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.

perf(cohorts): decode bytecode once (#95610)

Matheus Batista002d55724c05
diff --git a/products/cohorts/backend/parity/eligibility.py b/products/cohorts/backend/parity/eligibility.py
index dd0e0991a757..59e83e217c51 100644
--- a/products/cohorts/backend/parity/eligibility.py
+++ b/products/cohorts/backend/parity/eligibility.py
@@ -33,6 +33,8 @@ EXCLUDED_HAS_COHORT_REF = "excluded_has_cohort_ref"
EXCLUDED_CYCLE_DETECTED = "excluded_cycle_detected"
EXCLUDED_UNRESOLVED_REF = "excluded_unresolved_ref"
EXCLUDED_HAS_DROPPED_LEAF = "excluded_has_dropped_leaf"
+# HogVM RETURN, which the catalog loader appends to every stored program before loading it.
+_OP_RETURN = 38
# Not a processor metric class: the Rust loader skips these cohorts entirely.
PARSE_ERROR = "parse_error"
@@ -249,6 +251,22 @@ def _valid_condition_hash(value: Any) -> bool:
return isinstance(value, str) and len(value.encode("utf-8")) == 16
+def _loads_as_hog_program(bytecode: list[Any]) -> bool:
+ """Mirror of hogvm `Program::from_shared` header acceptance, checked per leaf by the catalog.
+
+ The loader appends a trailing RETURN before loading, so an empty stored program presents that
+ opcode as its marker and is rejected; a bare `["_H"]` takes the appended opcode as its version.
+
+ Not `common/hogvm/python/execute.py`: that loader accepts `_h` too and never reads the version,
+ so it would keep programs the Rust catalog drops.
+ """
+ marker = bytecode[0] if bytecode else _OP_RETURN
+ if marker != "_H":
+ return False
+ version = bytecode[1] if len(bytecode) > 1 else _OP_RETURN
+ return isinstance(version, int) and not isinstance(version, bool) and 0 <= version <= 2**64 - 1
+
+
def _classify_leaf(node: Mapping[str, Any]) -> Union[_Leaf, str]:
"""Mirror of leaf_classifier.rs classify_leaf: a kept/ref _Leaf, or a drop-reason string."""
leaf_type = node.get("type")
@@ -274,8 +292,11 @@ def _classify_behavioral(node: Mapping[str, Any]) -> Union[_Leaf, str]:
return "behavioral_action_key"
if not _valid_condition_hash(node.get("conditionHash")):
return "missing_condition_hash"
- if not isinstance(node.get("bytecode"), list):
+ bytecode = node.get("bytecode")
+ if not isinstance(bytecode, list):
return "missing_bytecode"
+ if not _loads_as_hog_program(bytecode):
+ return "malformed_bytecode"
if not isinstance(key, str) or not key:
return "malformed_leaf"
window = _behavioral_window_days(node, value)
@@ -287,8 +308,11 @@ def _classify_behavioral(node: Mapping[str, Any]) -> Union[_Leaf, str]:
def _classify_person(node: Mapping[str, Any]) -> Union[_Leaf, str]:
if not _valid_condition_hash(node.get("conditionHash")):
return "missing_condition_hash"
- if not isinstance(node.get("bytecode"), list):
+ bytecode = node.get("bytecode")
+ if not isinstance(bytecode, list):
return "missing_bytecode"
+ if not _loads_as_hog_program(bytecode):
+ return "malformed_bytecode"
return _Leaf(kind="person", negated=_explicit_negation(node))
diff --git a/products/cohorts/backend/parity/test/fixtures/eligibility_golden.json b/products/cohorts/backend/parity/test/fixtures/eligibility_golden.json
index 5b9f94c2d262..373a575cd693 100644
--- a/products/cohorts/backend/parity/test/fixtures/eligibility_golden.json
+++ b/products/cohorts/backend/parity/test/fixtures/eligibility_golden.json
@@ -86,6 +86,47 @@
"filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event", "key": "$pageview", "time_value": 7, "time_interval": "day", "conditionHash": "0123456789abcdef", "bytecode": "not-an-array"}]}},
"expected": "excluded_has_dropped_leaf"
},
+ {
+ "name": "empty_bytecode_is_dropped_as_malformed",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event", "key": "$pageview", "time_value": 7, "time_interval": "day", "conditionHash": "0123456789abcdef", "bytecode": []}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "wrong_bytecode_marker_is_dropped_as_malformed",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event", "key": "$pageview", "time_value": 7, "time_interval": "day", "conditionHash": "0123456789abcdef", "bytecode": ["_X", 1, 29]}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "non_integer_bytecode_version_is_dropped_as_malformed",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event", "key": "$pageview", "time_value": 7, "time_interval": "day", "conditionHash": "0123456789abcdef", "bytecode": ["_H", "one", 29]}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "max_u64_bytecode_version_is_kept",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event", "key": "$pageview", "time_value": 7, "time_interval": "day", "conditionHash": "0123456789abcdef", "bytecode": ["_H", 18446744073709551615, 29]}]}},
+ "expected": "single_leaf",
+ "expected_window_days": 7
+ },
+ {
+ "name": "bytecode_version_above_u64_is_dropped_as_malformed",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event", "key": "$pageview", "time_value": 7, "time_interval": "day", "conditionHash": "0123456789abcdef", "bytecode": ["_H", 18446744073709551616, 29]}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "person_max_u64_bytecode_version_is_kept",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "person", "key": "email", "value": "[email protected]", "conditionHash": "0123456789abcdef", "bytecode": ["_H", 18446744073709551615, 29]}]}},
+ "expected": "single_leaf"
+ },
+ {
+ "name": "person_bytecode_version_above_u64_is_dropped_as_malformed",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "person", "key": "email", "value": "[email protected]", "conditionHash": "0123456789abcdef", "bytecode": ["_H", 18446744073709551616, 29]}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "person_wrong_bytecode_marker_is_dropped_as_malformed",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "person", "key": "email", "value": "[email protected]", "conditionHash": "0123456789abcdef", "bytecode": ["_X", 1, 29]}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
{
"name": "person_leaf_is_single_leaf_without_window",
"filters": {"properties": {"type": "AND", "values": [{"type": "person", "key": "email", "value": "[email protected]", "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 1, 2, 11]}]}},
diff --git a/rust/cohort-core/src/eligibility.rs b/rust/cohort-core/src/eligibility.rs
index ff9143dbee69..9c11f0d55a51 100644
--- a/rust/cohort-core/src/eligibility.rs
+++ b/rust/cohort-core/src/eligibility.rs
@@ -12,6 +12,9 @@ use crate::leaf_state::key::LeafStateKey;
pub struct CohortParseFlags {
/// Number of kept, state-keyed leaves in the parsed tree.
pub state_keyed_leaf_count: u32,
+ /// Number of leaves dropped because the HogVM could not load their bytecode. Reported at
+ /// freeze; [`classify`] reads `has_dropped_leaf` instead, which any drop reason sets.
+ pub malformed_leaf_count: u32,
/// The cohort has ≥1 cohort-reference leaf.
pub has_cohort_ref: bool,
/// The cohort lost ≥1 leaf during parse.
@@ -227,9 +230,6 @@ fn single_supported_leaf(root: &FilterNode) -> Option<LeafStateKey> {
#[cfg(test)]
mod tests {
- use std::sync::Arc;
-
- use serde_json::Value;
use super::*;
use crate::filters::tree::{CohortLeaf, CohortRefLeafConfig, PersonLeafConfig};
@@ -247,8 +247,6 @@ mod tests {
FilterNode::Leaf(CohortLeaf::PersonProperty(PersonLeafConfig {
condition_hash: hash,
leaf_state_key: LeafStateKey::for_person_property(&hash),
- bytecode: Arc::new(Vec::new()),
- raw: Value::Null,
negated,
}))
}
diff --git a/rust/cohort-core/src/filters/leaf_classifier.rs b/rust/cohort-core/src/filters/leaf_classifier.rs
index c10476b5119c..ec5b97208969 100644
--- a/rust/cohort-core/src/filters/leaf_classifier.rs
+++ b/rust/cohort-core/src/filters/leaf_classifier.rs
@@ -1,21 +1,15 @@
//! Raw leaf JSON classification into kept, dropped, or cohort-reference leaves.
-use std::sync::Arc;
-
use serde_json::Value;
use crate::filters::tree::{
BehavioralLeafConfig, BehavioralValue, CohortLeaf, CohortRefLeafConfig, PersonLeafConfig,
};
use crate::filters::CohortId;
+use crate::hogvm::ConditionProgram;
use crate::leaf_state::key::LeafStateKey;
use crate::leaf_state::select::pick_state_variant;
-/// HogVM `RETURN` opcode, appended to each program at load. Python-compiled cohort bytecode ends at
-/// its root comparison with no `RETURN`, which the Rust VM would hit as `EndOfProgram`. A program
-/// already ending in `RETURN` stops at the first, so the appended one is inert.
-const OP_RETURN: i64 = 38;
-
/// Why a leaf was dropped during parse. Used as the `reason` label on the skip counter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LeafDropReason {
@@ -23,6 +17,8 @@ pub enum LeafDropReason {
MissingConditionHash,
/// No inline array `bytecode`.
MissingBytecode,
+ /// Inline `bytecode` the HogVM refuses to load: no `_H` marker, or a non-integer version.
+ MalformedBytecode,
/// A behavioral `value` outside the two bytecode-producing types.
UnsupportedBehavioralValue,
/// A behavioral leaf keyed by an action id (integer `key`).
@@ -40,6 +36,7 @@ impl LeafDropReason {
match self {
Self::MissingConditionHash => "missing_condition_hash",
Self::MissingBytecode => "missing_bytecode",
+ Self::MalformedBytecode => "malformed_bytecode",
Self::UnsupportedBehavioralValue => "unsupported_behavioral_value",
Self::BehavioralActionKey => "behavioral_action_key",
Self::UnsupportedStateVariant => "unsupported_state_variant",
@@ -49,13 +46,16 @@ impl LeafDropReason {
}
}
-pub enum LeafClass {
- Keep(CohortLeaf),
+pub enum LeafClass<'a> {
+ /// A kept leaf, carrying the stored bytecode array this classifier accepted for it (`None` for
+ /// a kept kind that has none). The pairing is what lets a sink load the program without a
+ /// validity check of its own.
+ Keep(CohortLeaf, Option<&'a [Value]>),
Drop(LeafDropReason),
CohortRef(CohortRefLeafConfig),
}
-pub fn classify_leaf(node: &Value) -> LeafClass {
+pub fn classify_leaf(node: &Value) -> LeafClass<'_> {
match node.get("type").and_then(Value::as_str) {
Some("behavioral") => classify_behavioral(node),
Some("cohort") => classify_cohort_ref(node),
@@ -64,7 +64,7 @@ pub fn classify_leaf(node: &Value) -> LeafClass {
}
}
-fn classify_behavioral(node: &Value) -> LeafClass {
+fn classify_behavioral(node: &Value) -> LeafClass<'_> {
let value = match node
.get("value")
.and_then(Value::as_str)
@@ -83,8 +83,9 @@ fn classify_behavioral(node: &Value) -> LeafClass {
return LeafClass::Drop(LeafDropReason::MissingConditionHash);
};
- let Some(bytecode) = bytecode_array(node.get("bytecode")) else {
- return LeafClass::Drop(LeafDropReason::MissingBytecode);
+ let bytecode = match validate_bytecode(node.get("bytecode")) {
+ Ok(bytecode) => bytecode,
+ Err(reason) => return LeafClass::Drop(reason),
};
let Some(event_key) = node
@@ -107,20 +108,20 @@ fn classify_behavioral(node: &Value) -> LeafClass {
explicit_datetime_to: opt_string(node.get("explicit_datetime_to")),
leaf_state_key: LeafStateKey([0u8; 16]),
state_variant: None,
- bytecode,
negated: explicit_negation(node),
}
.with_state_key();
match pick_state_variant(&leaf) {
- Ok((variant, _window)) => {
- LeafClass::Keep(CohortLeaf::Behavioral(leaf.with_state_variant(variant)))
- }
+ Ok((variant, _window)) => LeafClass::Keep(
+ CohortLeaf::Behavioral(leaf.with_state_variant(variant)),
+ Some(bytecode),
+ ),
Err(_) => LeafClass::Drop(LeafDropReason::UnsupportedStateVariant),
}
}
-fn classify_cohort_ref(node: &Value) -> LeafClass {
+fn classify_cohort_ref(node: &Value) -> LeafClass<'_> {
match cohort_id_from_value(node.get("value")) {
Some(id) => LeafClass::CohortRef(CohortRefLeafConfig {
referenced_cohort_id: CohortId(id),
@@ -144,20 +145,22 @@ fn cohort_ref_negation(node: &Value) -> bool {
explicit_negation(node) || node.get("operator").and_then(Value::as_str) == Some("not_in")
}
-fn classify_person(node: &Value) -> LeafClass {
+fn classify_person(node: &Value) -> LeafClass<'_> {
let Some(condition_hash) = condition_hash_bytes(node.get("conditionHash")) else {
return LeafClass::Drop(LeafDropReason::MissingConditionHash);
};
- let Some(bytecode) = bytecode_array(node.get("bytecode")) else {
- return LeafClass::Drop(LeafDropReason::MissingBytecode);
+ let bytecode = match validate_bytecode(node.get("bytecode")) {
+ Ok(bytecode) => bytecode,
+ Err(reason) => return LeafClass::Drop(reason),
};
- LeafClass::Keep(CohortLeaf::PersonProperty(PersonLeafConfig {
- condition_hash,
- leaf_state_key: LeafStateKey::for_person_property(&condition_hash),
- bytecode,
- raw: node.clone(),
- negated: explicit_negation(node),
- }))
+ LeafClass::Keep(
+ CohortLeaf::PersonProperty(PersonLeafConfig {
+ condition_hash,
+ leaf_state_key: LeafStateKey::for_person_property(&condition_hash),
+ negated: explicit_negation(node),
+ }),
+ Some(bytecode),
+ )
}
/// The 16 ASCII bytes of the hex `conditionHash` string, or `None` if not exactly 16 bytes.
@@ -173,11 +176,17 @@ fn condition_hash_bytes(value: Option<&Value>) -> Option<[u8; 16]> {
}
}
-fn bytecode_array(value: Option<&Value>) -> Option<Arc<Vec<Value>>> {
- let array = value?.as_array()?;
- let mut bytecode = array.clone();
- bytecode.push(Value::from(OP_RETURN));
- Some(Arc::new(bytecode))
+/// Validate every leaf before hash deduplication so a healthy duplicate cannot hide a corrupt one.
+/// Returns the accepted array, so a kept leaf carries the bytecode that was checked for it.
+fn validate_bytecode(value: Option<&Value>) -> Result<&[Value], LeafDropReason> {
+ let array = value
+ .and_then(Value::as_array)
+ .ok_or(LeafDropReason::MissingBytecode)?;
+ if ConditionProgram::has_valid_stored_header(array) {
+ Ok(array)
+ } else {
+ Err(LeafDropReason::MalformedBytecode)
+ }
}
/// A referenced cohort id as a JSON number or string-encoded int.
@@ -211,13 +220,6 @@ mod tests {
json!(["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11])
}
- /// The stored form of [`bytecode`]: the loader appends a trailing `RETURN` (opcode 38).
- fn bytecode_loaded() -> Vec<Value> {
- let mut bc = bytecode().as_array().unwrap().clone();
- bc.push(json!(OP_RETURN));
- bc
- }
-
fn hash_bytes() -> [u8; 16] {
*b"0123456789abcdef"
}
@@ -233,7 +235,7 @@ mod tests {
"conditionHash": HASH,
"bytecode": bytecode(),
});
- let LeafClass::Keep(CohortLeaf::Behavioral(leaf)) = classify_leaf(&node) else {
+ let LeafClass::Keep(CohortLeaf::Behavioral(leaf), _) = classify_leaf(&node) else {
panic!("expected a kept behavioral leaf");
};
assert_eq!(leaf.condition_hash, hash_bytes());
@@ -241,7 +243,6 @@ mod tests {
assert_eq!(leaf.event_key, "$pageview");
assert_eq!(leaf.time_value, Some(7));
assert_eq!(leaf.leaf_state_key, LeafStateKey::for_behavioral(&leaf));
- assert_eq!(leaf.bytecode.as_ref(), &bytecode_loaded());
assert_eq!(
leaf.state_variant,
Some(crate::leaf_state::variant::StateVariant::BehavioralSingle),
@@ -261,7 +262,7 @@ mod tests {
"conditionHash": HASH,
"bytecode": bytecode(),
});
- let LeafClass::Keep(CohortLeaf::Behavioral(leaf)) = classify_leaf(&node) else {
+ let LeafClass::Keep(CohortLeaf::Behavioral(leaf), _) = classify_leaf(&node) else {
panic!("a daily-window multiple is now kept");
};
assert_eq!(leaf.value, BehavioralValue::PerformedEventMultiple);
@@ -318,7 +319,7 @@ mod tests {
"conditionHash": HASH,
"bytecode": bytecode(),
});
- let LeafClass::Keep(CohortLeaf::Behavioral(leaf)) = classify_leaf(&node) else {
+ let LeafClass::Keep(CohortLeaf::Behavioral(leaf), _) = classify_leaf(&node) else {
panic!("a >180-day multiple is kept as compressed: {why}");
};
assert_eq!(
@@ -356,7 +357,7 @@ mod tests {
"conditionHash": HASH,
"bytecode": bytecode(),
});
- let LeafClass::Keep(CohortLeaf::Behavioral(leaf)) = classify_leaf(&node) else {
+ let LeafClass::Keep(CohortLeaf::Behavioral(leaf), _) = classify_leaf(&node) else {
panic!("an explicit relative-lower multiple is kept: {why}");
};
assert_eq!(leaf.value, BehavioralValue::PerformedEventMultiple);
@@ -477,13 +478,11 @@ mod tests {
"conditionHash": HASH,
"bytecode": bytecode(),
});
- let LeafClass::Keep(CohortLeaf::PersonProperty(leaf)) = classify_leaf(&node) else {
+ let LeafClass::Keep(CohortLeaf::PersonProperty(leaf), _) = classify_leaf(&node) else {
panic!("expected a kept person leaf");
};
assert_eq!(leaf.condition_hash, hash_bytes());
assert_eq!(leaf.leaf_state_key, LeafStateKey(hash_bytes()));
- assert_eq!(leaf.bytecode.as_ref(), &bytecode_loaded());
- assert_eq!(leaf.raw, node);
}
#[test]
@@ -509,6 +508,56 @@ mod tests {
));
}
+ #[test]
+ fn bytecode_the_vm_cannot_load_is_dropped_as_malformed() {
+ // The three ways `Program` rejects a header, on both leaf types. Such a leaf used to be
+ // kept and evaluate to `false` on every event; it is now dropped, which excludes its cohort.
+ for (stored, why) in [
+ (
+ json!([]),
+ "empty stored array becomes `[RETURN]`, whose marker is a number",
+ ),
+ (json!(["_X", 1, 29]), "marker is not `_H`"),
+ (json!(["_H", "one", 29]), "version is not an integer"),
+ ] {
+ let behavioral = json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "time_value": 7,
+ "time_interval": "day",
+ "conditionHash": HASH,
+ "bytecode": stored.clone(),
+ });
+ assert!(
+ matches!(
+ classify_leaf(&behavioral),
+ LeafClass::Drop(LeafDropReason::MalformedBytecode)
+ ),
+ "behavioral leaf, {why}",
+ );
+
+ let person = json!({
+ "type": "person",
+ "key": "email",
+ "value": "[email protected]",
+ "conditionHash": HASH,
+ "bytecode": stored,
+ });
+ assert!(
+ matches!(
+ classify_leaf(&person),
+ LeafClass::Drop(LeafDropReason::MalformedBytecode)
+ ),
+ "person leaf, {why}",
+ );
+ }
+ assert_eq!(
+ LeafDropReason::MalformedBytecode.as_str(),
+ "malformed_bytecode"
+ );
+ }
+
#[test]
fn person_without_bytecode_is_dropped() {
let node = json!({
@@ -621,7 +670,7 @@ mod tests {
"bytecode": bytecode(),
"negation": true,
});
- let LeafClass::Keep(CohortLeaf::Behavioral(leaf)) = classify_leaf(&node) else {
+ let LeafClass::Keep(CohortLeaf::Behavioral(leaf), _) = classify_leaf(&node) else {
panic!("expected a kept behavioral leaf");
};
assert!(leaf.negated);
@@ -638,7 +687,7 @@ mod tests {
"conditionHash": HASH,
"bytecode": bytecode(),
});
- let LeafClass::Keep(CohortLeaf::Behavioral(leaf)) = classify_leaf(&node) else {
+ let LeafClass::Keep(CohortLeaf::Behavioral(leaf), _) = classify_leaf(&node) else {
panic!("expected a kept behavioral leaf");
};
assert!(!leaf.negated);
@@ -654,7 +703,7 @@ mod tests {
"bytecode": bytecode(),
"negation": true,
});
- let LeafClass::Keep(CohortLeaf::PersonProperty(leaf)) = classify_leaf(&node) else {
+ let LeafClass::Keep(CohortLeaf::PersonProperty(leaf), _) = classify_leaf(&node) else {
panic!("expected a kept person leaf");
};
assert!(leaf.negated);
@@ -669,7 +718,7 @@ mod tests {
"conditionHash": HASH,
"bytecode": bytecode(),
});
- let LeafClass::Keep(CohortLeaf::PersonProperty(leaf)) = classify_leaf(&node) else {
+ let LeafClass::Keep(CohortLeaf::PersonProperty(leaf), _) = classify_leaf(&node) else {
panic!("expected a kept person leaf");
};
assert!(!leaf.negated);
@@ -687,7 +736,7 @@ mod tests {
"bytecode": bytecode(),
"negation": false,
});
- let LeafClass::Keep(CohortLeaf::Behavioral(leaf)) = classify_leaf(&node) else {
+ let LeafClass::Keep(CohortLeaf::Behavioral(leaf), _) = classify_leaf(&node) else {
panic!("expected a kept behavioral leaf");
};
assert!(!leaf.negated);
diff --git a/rust/cohort-core/src/filters/reverse_index.rs b/rust/cohort-core/src/filters/reverse_index.rs
index 4f10ef1d5eeb..ef4ee179fbb0 100644
--- a/rust/cohort-core/src/filters/reverse_index.rs
+++ b/rust/cohort-core/src/filters/reverse_index.rs
@@ -1,7 +1,6 @@
//! Per-team reverse indices, dedup set, and eligibility classification.
use std::collections::{HashMap, HashSet};
-use std::sync::Arc;
use chrono_tz::{Tz, UTC};
use metrics::counter;
@@ -15,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::ConditionProgram;
use crate::leaf_state::key::LeafStateKey;
use crate::leaf_state::select::{
effective_window_days, pick_state_variant, EvictionWindow, PredicateOp,
@@ -43,8 +43,8 @@ pub struct TeamFilters {
pub by_condition_to_lsk: HashMap<[u8; 16], Vec<LeafStateKey>>,
/// `conditionHash → [CohortId]` for the Stage 2 walk back to owning cohorts.
pub by_condition_to_cohorts: HashMap<[u8; 16], Vec<CohortId>>,
- /// `conditionHash → bytecode`. One entry per conditionHash.
- pub by_condition_to_bytecode: HashMap<[u8; 16], Arc<Vec<Value>>>,
+ /// `conditionHash → loaded program`. One entry per conditionHash.
+ 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.
@@ -85,7 +85,7 @@ impl Default for TeamFilters {
Self {
by_condition_to_lsk: HashMap::new(),
by_condition_to_cohorts: HashMap::new(),
- by_condition_to_bytecode: HashMap::new(),
+ by_condition_to_program: HashMap::new(),
unique_condition_hashes: HashSet::new(),
by_lsk: HashMap::new(),
behavioral_conditions: HashSet::new(),
@@ -120,7 +120,7 @@ impl TeamFilters {
pub struct TeamFiltersBuilder {
by_condition_to_lsk: HashMap<[u8; 16], HashSet<LeafStateKey>>,
by_condition_to_cohorts: HashMap<[u8; 16], HashSet<CohortId>>,
- by_condition_to_bytecode: HashMap<[u8; 16], Arc<Vec<Value>>>,
+ by_condition_to_program: HashMap<[u8; 16], ConditionProgram>,
unique_condition_hashes: HashSet<[u8; 16]>,
cohorts: HashMap<CohortId, CohortTree>,
/// Per-cohort eligibility signals captured during parse.
@@ -135,7 +135,7 @@ impl LeafSink for TeamFiltersBuilder {
cohort_id: CohortId,
condition_hash: [u8; 16],
leaf_state_key: LeafStateKey,
- bytecode: &Arc<Vec<Value>>,
+ bytecode: &[Value],
) {
self.by_condition_to_lsk
.entry(condition_hash)
@@ -145,9 +145,12 @@ impl LeafSink for TeamFiltersBuilder {
.entry(condition_hash)
.or_default()
.insert(cohort_id);
- self.by_condition_to_bytecode
+ self.by_condition_to_program
.entry(condition_hash)
- .or_insert_with(|| Arc::clone(bytecode));
+ .or_insert_with(|| {
+ ConditionProgram::from_stored(bytecode)
+ .expect("the leaf classifier validated the program header")
+ });
self.unique_condition_hashes.insert(condition_hash);
let flags = self.flags.entry(cohort_id).or_default();
@@ -160,7 +163,11 @@ impl LeafSink for TeamFiltersBuilder {
fn record_dropped(&mut self, cohort_id: CohortId, reason: LeafDropReason) {
counter!(FILTER_CATALOG_SKIPPED_LEAVES, "reason" => reason.as_str()).increment(1);
- self.flags.entry(cohort_id).or_default().has_dropped_leaf = true;
+ let flags = self.flags.entry(cohort_id).or_default();
+ flags.has_dropped_leaf = true;
+ if reason == LeafDropReason::MalformedBytecode {
+ flags.malformed_leaf_count += 1;
+ }
}
}
@@ -196,6 +203,16 @@ impl TeamFiltersBuilder {
/// ref-bearing cohorts become [`CohortEligibility::Stage2ComposableRef`] and join the composable
/// emit-map by their own leaves; otherwise they stay `Excluded(HasCohortRef)`.
pub fn freeze_with(self, timezone: Tz, cascade_enabled: bool) -> 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 {
+ warn!(
+ cohort_id = cohort_id.0,
+ malformed_leaves = flags.malformed_leaf_count,
+ "cohort has bytecode the HogVM cannot load; excluding the cohort",
+ );
+ }
+ }
let mut by_lsk = HashMap::new();
let mut behavioral_conditions = HashSet::new();
let mut behavioral_by_event_name: HashMap<String, HashSet<[u8; 16]>> = HashMap::new();
@@ -305,7 +322,7 @@ impl TeamFiltersBuilder {
TeamFilters {
by_condition_to_lsk: sorted_vec_map(self.by_condition_to_lsk),
by_condition_to_cohorts: sorted_vec_map(self.by_condition_to_cohorts),
- by_condition_to_bytecode: self.by_condition_to_bytecode,
+ by_condition_to_program: self.by_condition_to_program,
unique_condition_hashes: self.unique_condition_hashes,
by_lsk,
behavioral_conditions,
@@ -568,19 +585,67 @@ mod tests {
#[test]
fn identical_leaves_dedupe_to_single_entries() {
- let mut builder = TeamFiltersBuilder::default();
- let filters = wrap(vec![
- behavioral_performed_event(7),
- behavioral_performed_event(7),
- ]);
- builder
- .add_cohort(CohortId(1), TeamId(7), &filters)
- .unwrap();
- let frozen = builder.freeze(UTC);
+ for (leaf, hash) in [
+ (behavioral_performed_event(7), HASH),
+ (person_leaf(), PERSON_HASH),
+ ] {
+ let filters = wrap(vec![leaf.clone(), leaf]);
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(1), TeamId(7), &filters)
+ .unwrap();
+ builder
+ .add_cohort(CohortId(2), TeamId(7), &filters)
+ .unwrap();
+ let frozen = builder.freeze(UTC);
- assert_eq!(frozen.by_condition_to_lsk[&HASH].len(), 1);
- assert_eq!(frozen.by_condition_to_cohorts[&HASH], vec![CohortId(1)]);
- assert_eq!(frozen.unique_condition_hashes.len(), 1);
+ assert_eq!(frozen.by_condition_to_lsk[&hash].len(), 1);
+ assert_eq!(
+ frozen.by_condition_to_cohorts[&hash],
+ vec![CohortId(1), CohortId(2)]
+ );
+ assert_eq!(frozen.unique_condition_hashes.len(), 1);
+ assert_eq!(frozen.by_condition_to_program.len(), 1);
+ for tree in frozen.cohorts.values() {
+ let FilterNode::Group { children, .. } = &tree.root else {
+ panic!("expected a group");
+ };
+ assert_eq!(children.len(), 2);
+ }
+ }
+ }
+
+ /// Decoding is the cost this catalog pays once, so a repeat occurrence must reuse the decoded
+ /// tokens rather than produce an equal copy of them. With `Program`'s fields private, slice
+ /// identity is the only public probe.
+ #[test]
+ fn a_repeated_condition_hash_reuses_the_first_decoded_program() {
+ for (leaf, hash) in [
+ (behavioral_performed_event(7), HASH),
+ (person_leaf(), PERSON_HASH),
+ ] {
+ let filters = wrap(vec![leaf.clone(), leaf]);
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(1), TeamId(7), &filters)
+ .unwrap();
+ let first_program = builder.by_condition_to_program[&hash].clone();
+ builder
+ .add_cohort(CohortId(2), TeamId(7), &filters)
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ let retained = frozen.by_condition_to_program[&hash]
+ .program()
+ .body_tokens();
+ // Two empty slices can compare pointer-equal, so prove the comparison has something to
+ // bite on.
+ assert!(!retained.is_empty());
+ assert!(std::ptr::eq(
+ first_program.program().body_tokens(),
+ retained,
+ ));
+ }
}
#[test]
@@ -608,11 +673,11 @@ mod tests {
vec![CohortId(1), CohortId(2)]
);
assert_eq!(frozen.unique_condition_hashes.len(), 1);
- assert_eq!(frozen.by_condition_to_bytecode.len(), 1);
+ assert_eq!(frozen.by_condition_to_program.len(), 1);
}
#[test]
- fn bytecode_is_captured_under_its_condition_hash() {
+ fn the_loaded_program_is_captured_under_its_condition_hash() {
let mut builder = TeamFiltersBuilder::default();
builder
.add_cohort(
@@ -623,11 +688,62 @@ mod tests {
.unwrap();
let frozen = builder.freeze(UTC);
- let bytecode = frozen
- .by_condition_to_bytecode
+ let program = frozen
+ .by_condition_to_program
.get(&HASH)
- .expect("bytecode captured under the conditionHash");
- assert_eq!(bytecode.as_ref(), &behavioral_bytecode_loaded());
+ .expect("the program is captured under the conditionHash");
+ assert_eq!(program.tokens(), &behavioral_bytecode_loaded());
+ }
+
+ #[test]
+ fn a_leaf_with_unloadable_bytecode_excludes_its_cohort_and_indexes_nothing() {
+ // The cohort keeps a healthy person leaf, so the exclusion is the malformed leaf's doing,
+ // not an empty tree. Nothing about the dropped leaf reaches any index: a hash left behind in
+ // one of them would be evaluated, swept, or fingerprinted for a cohort that never emits.
+ let mut malformed = person_leaf();
+ malformed["bytecode"] = json!(["not-a-header", 1, 29]);
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7), malformed]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::HasDroppedLeaf),
+ );
+ assert!(!frozen.by_condition_to_program.contains_key(&PERSON_HASH));
+ assert!(!frozen.by_condition_to_lsk.contains_key(&PERSON_HASH));
+ assert!(!frozen
+ .by_lsk
+ .contains_key(&LeafStateKey::for_person_property(&PERSON_HASH)));
+ assert!(!frozen.person_property_conditions.contains(&PERSON_HASH));
+ // The healthy sibling still indexed, so the drop is scoped to the malformed leaf.
+ assert!(frozen.by_condition_to_program.contains_key(&HASH));
+
+ for malformed_first in [true, false] {
+ let mut malformed = person_leaf();
+ malformed["bytecode"] = json!(["not-a-header", 1, 29]);
+ let mut leaves = vec![malformed, person_leaf()];
+ if !malformed_first {
+ leaves.reverse();
+ }
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(1), TeamId(7), &wrap(leaves))
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::HasDroppedLeaf),
+ "a valid duplicate must not mask a malformed leaf",
+ );
+ assert_eq!(frozen.by_condition_to_program.len(), 1);
+ }
}
#[test]
diff --git a/rust/cohort-core/src/filters/tree.rs b/rust/cohort-core/src/filters/tree.rs
index 0da8e83e0991..d7145f9275a7 100644
--- a/rust/cohort-core/src/filters/tree.rs
+++ b/rust/cohort-core/src/filters/tree.rs
@@ -1,7 +1,5 @@
//! Filter-tree types and parser.
-use std::sync::Arc;
-
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -69,7 +67,6 @@ pub struct BehavioralLeafConfig {
pub explicit_datetime_to: Option<String>,
pub leaf_state_key: LeafStateKey,
pub state_variant: Option<StateVariant>,
- pub bytecode: Arc<Vec<Value>>,
/// Excluded from [`LeafStateKey`] -- state is shared between positive and negated instances.
pub negated: bool,
}
@@ -92,8 +89,6 @@ impl BehavioralLeafConfig {
pub struct PersonLeafConfig {
pub condition_hash: [u8; 16],
pub leaf_state_key: LeafStateKey,
- pub bytecode: Arc<Vec<Value>>,
- pub raw: Value,
pub negated: bool,
}
@@ -136,15 +131,6 @@ impl CohortLeaf {
Self::CohortRef(_) => None,
}
}
-
- /// The leaf's inline bytecode, or `None` for a cohort reference.
- pub fn bytecode(&self) -> Option<&Arc<Vec<Value>>> {
- match self {
- Self::PersonProperty(leaf) => Some(&leaf.bytecode),
- Self::Behavioral(leaf) => Some(&leaf.bytecode),
- Self::CohortRef(_) => None,
- }
- }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -172,12 +158,14 @@ pub struct CohortTree {
/// Receives the indexable side effects of a parse.
pub trait LeafSink {
+ /// Record one kept, state-keyed leaf. `bytecode` is the leaf's stored array, already accepted
+ /// by `ConditionProgram::has_valid_stored_header`, so loading it cannot fail.
fn record_state_keyed(
&mut self,
cohort_id: CohortId,
condition_hash: [u8; 16],
leaf_state_key: LeafStateKey,
- bytecode: &Arc<Vec<Value>>,
+ bytecode: &[Value],
);
fn record_cohort_ref(&mut self, cohort_id: CohortId);
@@ -223,12 +211,10 @@ fn parse_node(cohort_id: CohortId, node: &Value, sink: &mut dyn LeafSink) -> Opt
}
match classify_leaf(node) {
- LeafClass::Keep(leaf) => {
- if let (Some(hash), Some(lsk), Some(bytecode)) = (
- leaf.condition_hash(),
- leaf.leaf_state_key(),
- leaf.bytecode(),
- ) {
+ LeafClass::Keep(leaf, bytecode) => {
+ if let (Some(hash), Some(lsk), Some(bytecode)) =
+ (leaf.condition_hash(), leaf.leaf_state_key(), bytecode)
+ {
sink.record_state_keyed(cohort_id, hash, lsk, bytecode);
}
Some(FilterNode::Leaf(leaf))
@@ -273,7 +259,7 @@ mod tests {
cohort_id: CohortId,
hash: [u8; 16],
lsk: LeafStateKey,
- _bytecode: &Arc<Vec<Value>>,
+ _bytecode: &[Value],
) {
self.state_keyed.push((cohort_id, hash, lsk));
}
diff --git a/rust/cohort-core/src/hogvm/executor.rs b/rust/cohort-core/src/hogvm/executor.rs
index 2bf2ccfd12c3..5a4f5288d389 100644
--- a/rust/cohort-core/src/hogvm/executor.rs
+++ b/rust/cohort-core/src/hogvm/executor.rs
@@ -5,7 +5,7 @@
//! The hot path reuses one [`CohortEvaluator`] per event: the STL context and globals are set once
//! and only the program is swapped per condition, amortizing the context build across all conditions.
-use std::sync::{Arc, LazyLock};
+use std::sync::LazyLock;
use dashmap::DashSet;
use hogvm::{sync_execute, ExecutionContext, Program, VmError};
@@ -13,6 +13,7 @@ use metrics::counter;
use serde_json::Value;
use tracing::info;
+use crate::hogvm::ConditionProgram;
use crate::metrics::{STAGE1_HOGVM_ERROR, STAGE1_HOGVM_UNKNOWN_FUNCTION};
/// Unknown-native function names already logged once. Bounded by the HogQL native surface
@@ -126,24 +127,20 @@ impl CohortEvaluator {
self.context.set_globals(globals);
}
- /// Evaluate one condition's bytecode against the current globals, coercing failures and non-bool
- /// results to `false`. Self-counting (the processor's hot path): a VM error or unknown-function
- /// call increments a per-class `STAGE1_HOGVM_*` metric (keeping a genuinely failing cohort
- /// observable); a non-bool result is coerced to `false` with no metric. `bytecode` must be
- /// `RETURN`-terminated (the loader appends it).
- pub fn evaluate(&mut self, bytecode: Arc<Vec<Value>>) -> bool {
- outcome_to_bool(self.evaluate_detailed(bytecode))
+ /// Evaluate one condition against the current globals, coercing failures and non-bool results
+ /// to `false`. Self-counting (the processor's hot path): a VM error or unknown-function call
+ /// increments a per-class `STAGE1_HOGVM_*` metric (keeping a genuinely failing cohort
+ /// observable); a non-bool result is coerced to `false` with no metric.
+ pub fn evaluate(&mut self, condition: &ConditionProgram) -> bool {
+ outcome_to_bool(self.evaluate_detailed(condition))
}
/// As [`Self::evaluate`] but returns the detailed [`EvalOutcome`] and emits no metric — the
/// caller owns classification (the seeder's bring-your-own-metrics path).
- pub fn evaluate_detailed(&mut self, bytecode: Arc<Vec<Value>>) -> EvalOutcome {
- // `from_shared` clones the `Arc`, not the opcode vector, so swapping programs is just a refcount bump.
- let program = match Program::from_shared(bytecode) {
- Ok(program) => program,
- Err(error) => return classify_failure(error),
- };
- self.context.set_program(program);
+ pub fn evaluate_detailed(&mut self, condition: &ConditionProgram) -> EvalOutcome {
+ // Cloning a loaded program is two refcount bumps: the header is already validated and the
+ // tokens already decoded, so swapping conditions never re-decodes.
+ self.context.set_program(condition.program().clone());
run(&self.context)
}
}
@@ -408,6 +405,47 @@ mod tests {
assert!(!evaluate(&bc, json!({ "person": { "properties": {} } })));
}
+ /// Real compiled bytecode from the `isnull_numeric_gte_match` parity fixture, whose Python
+ /// oracle recorded `true`. Stored as compiled, without the loader's trailing `RETURN`, and
+ /// branch-lowered — the compiler rewrites `>=` into an `if`, so it exercises jumps the
+ /// hand-built fixtures above do not.
+ fn corpus_isnull_numeric_gte() -> Vec<Value> {
+ vec![
+ json!("_H"),
+ json!(1),
+ json!(32),
+ json!("$screen_height"),
+ json!(32),
+ json!("properties"),
+ json!(1),
+ json!(2),
+ json!(2),
+ json!("isNull"),
+ json!(1),
+ json!(33),
+ json!(500),
+ json!(2),
+ json!("isNull"),
+ json!(1),
+ json!(4),
+ json!(2),
+ json!(40),
+ json!(3),
+ json!(30),
+ json!(39),
+ json!(9),
+ json!(33),
+ json!(500),
+ json!(32),
+ json!("$screen_height"),
+ json!(32),
+ json!("properties"),
+ json!(1),
+ json!(2),
+ json!(14),
+ ]
+ }
+
#[test]
fn reused_evaluator_matches_a_fresh_context_per_eval() {
// Interleave programs and globals so a stale-globals or un-swapped-program leak would diverge
@@ -426,27 +464,63 @@ mod tests {
bc.extend_from_slice(&[json!(OP_GT), json!(OP_RETURN)]);
bc
};
+ let corpus = corpus_isnull_numeric_gte();
let g_match = json!({ "person": { "properties": { "email": "[email protected]", "bc_num": 20 } } });
let g_miss = json!({ "person": { "properties": { "email": "[email protected]", "bc_num": 5 } } });
+ let g_screen = json!({ "properties": { "$screen_height": 800 } });
- let cases: [(&Vec<Value>, &Value); 5] = [
+ let cases: [(&Vec<Value>, &Value); 6] = [
(&email_eq, &g_match),
(&num_gt, &g_match),
(&email_eq, &g_miss),
(&num_gt, &g_miss),
(&email_eq, &g_match),
+ (&corpus, &g_screen),
];
let mut evaluator = CohortEvaluator::new();
- for (bytecode, globals) in cases {
+ for (stored, globals) in cases {
+ let condition = ConditionProgram::from_stored(stored).expect("a valid header loads");
evaluator.set_globals(globals.clone());
- let reused = evaluator.evaluate(Arc::new(bytecode.clone()));
- let fresh = evaluate(bytecode, globals.clone());
+ let reused = evaluator.evaluate(&condition);
+ let fresh = evaluate(condition.tokens(), globals.clone());
assert_eq!(
reused, fresh,
"reused evaluator diverged from a fresh per-eval context",
);
}
+
+ // The corpus case also carries an oracle verdict, so the reused path is pinned to an answer
+ // rather than only to the free function agreeing with it.
+ evaluator.set_globals(g_screen.clone());
+ assert!(
+ evaluator
+ .evaluate(&ConditionProgram::from_stored(&corpus).expect("a valid header loads")),
+ "the `isnull_numeric_gte_match` fixture's oracle verdict is true",
+ );
+ }
+
+ #[test]
+ fn evaluate_runs_the_conditions_own_decoded_tokens() {
+ // The context must borrow the condition's already-decoded token vector, not a fresh decode
+ // of its JSON. With `Program`'s fields private, slice identity is the only public probe.
+ let stored = [header(), vec![json!(OP_TRUE), json!(OP_RETURN)]].concat();
+ let condition = ConditionProgram::from_stored(&stored).expect("a valid header loads");
+
+ let mut evaluator = CohortEvaluator::new();
+ evaluator.set_globals(json!({}));
+ assert!(evaluator.evaluate(&condition));
+
+ let running = evaluator
+ .context
+ .chunk_tokens(&None)
+ .expect("the root chunk is always resolvable");
+ // Two empty slices can compare pointer-equal, so prove the comparison has something to bite on.
+ assert!(!running.is_empty());
+ assert!(
+ std::ptr::eq(running, condition.program().body_tokens()),
+ "the evaluator re-decoded the condition instead of reusing its tokens",
+ );
}
#[test]
@@ -502,8 +576,9 @@ mod tests {
// Fix, reused-evaluator site (production hot path): likewise no overflow.
let mut evaluator = CohortEvaluator::new();
evaluator.set_globals(json!({}));
+ let condition = ConditionProgram::from_stored(&prog).expect("a valid header loads");
assert!(matches!(
- evaluator.evaluate_detailed(Arc::new(prog)),
+ evaluator.evaluate_detailed(&condition),
EvalOutcome::Matched(_)
));
}
diff --git a/rust/cohort-core/src/hogvm/mod.rs b/rust/cohort-core/src/hogvm/mod.rs
index b85ebdefffee..8fd8d5a704aa 100644
--- a/rust/cohort-core/src/hogvm/mod.rs
+++ b/rust/cohort-core/src/hogvm/mod.rs
@@ -13,6 +13,7 @@
pub mod analysis;
mod executor;
mod globals;
+mod program;
pub use executor::{
classify_vm_error, evaluate_detailed, CohortEvaluator, EvalOutcome, VmErrorClass,
@@ -21,3 +22,4 @@ pub use globals::{
build_behavioral_globals, build_person_property_globals, build_person_scan_globals,
GlobalsError,
};
+pub use program::ConditionProgram;
diff --git a/rust/cohort-core/src/hogvm/program.rs b/rust/cohort-core/src/hogvm/program.rs
new file mode 100644
index 000000000000..1dec6490c248
--- /dev/null
+++ b/rust/cohort-core/src/hogvm/program.rs
@@ -0,0 +1,163 @@
+//! The loaded form of a cohort condition's bytecode: header-validated and token-decoded once.
+
+use std::fmt;
+
+use hogvm::{Operation, Program, VmError};
+use serde_json::Value;
+
+/// A cohort condition's bytecode in the form the evaluator runs: the stored program with the
+/// loader's trailing `RETURN`, header-validated and token-decoded once at catalog build. Wraps
+/// [`Program`] (two `Arc`s), so cloning one into an `ExecutionContext` is two refcount bumps and
+/// never re-decodes.
+#[derive(Clone)]
+pub struct ConditionProgram(Program);
+
+impl ConditionProgram {
+ /// Mirrors the VM's load acceptance without decoding duplicate condition bodies. A differential
+ /// test guards this mirror against changes to the VM loader.
+ pub(crate) fn has_valid_stored_header(stored: &[Value]) -> bool {
+ // A missing version becomes the appended RETURN, which is a valid u64 version.
+ stored.first().and_then(Value::as_str) == Some("_H")
+ && stored
+ .get(1)
+ .is_none_or(|version| version.as_u64().is_some())
+ }
+
+ /// Load a stored cohort program: append `RETURN`, then validate the header and decode the
+ /// tokens. The only failure is a rejected header.
+ ///
+ /// # Errors
+ /// [`VmError::InvalidBytecode`] when the array does not start with the `_H` marker followed by
+ /// an integer version.
+ pub fn from_stored(stored: &[Value]) -> Result<Self, VmError> {
+ let mut bytecode = Vec::with_capacity(stored.len() + 1);
+ bytecode.extend_from_slice(stored);
+ // Python-compiled cohort bytecode ends at its root comparison with no `RETURN`, which the
+ // Rust VM would hit as `EndOfProgram`. A program already ending in `RETURN` stops at the
+ // first, so the appended one is inert.
+ bytecode.push(Value::from(Operation::Return));
+ Program::new(bytecode).map(Self)
+ }
+
+ /// The full token array, header and appended `RETURN` included: the input of the static
+ /// analysis and the view a census or a test needs.
+ pub fn tokens(&self) -> &[Value] {
+ self.0.tokens()
+ }
+
+ pub(crate) fn program(&self) -> &Program {
+ &self.0
+ }
+}
+
+/// Required, not stylistic: [`Program`] has no `Debug`, so [`crate::TeamFilters`] and the seeder's
+/// pinned runs could not derive theirs without it. Prints the token count and
+/// version rather than the tokens, which would otherwise dump every condition's whole program.
+impl fmt::Debug for ConditionProgram {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("ConditionProgram")
+ .field("tokens", &self.0.tokens().len())
+ .field("version", &self.0.version())
+ .finish()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::hogvm::{evaluate_detailed, EvalOutcome};
+ use serde_json::json;
+
+ const OP_TRUE: i64 = 29;
+ const OP_RETURN: i64 = Operation::Return as i64;
+
+ #[test]
+ fn from_stored_appends_the_terminating_return() {
+ let stored = [json!("_H"), json!(1), json!(OP_TRUE)];
+ let program = ConditionProgram::from_stored(&stored).expect("a valid header loads");
+ assert_eq!(
+ program.tokens(),
+ &[json!("_H"), json!(1), json!(OP_TRUE), json!(OP_RETURN)],
+ );
+ }
+
+ #[test]
+ fn an_already_terminated_program_evaluates_the_same_after_the_append() {
+ // The first `RETURN` finishes the run with an empty frame stack, so the appended one is
+ // unreachable — a stored program that already ends in `RETURN` must not change meaning.
+ let terminated = [json!("_H"), json!(1), json!(OP_TRUE), json!(OP_RETURN)];
+ let program = ConditionProgram::from_stored(&terminated).expect("a valid header loads");
+ assert_eq!(program.tokens().len(), terminated.len() + 1);
+ assert!(matches!(
+ evaluate_detailed(&terminated, json!({})),
+ EvalOutcome::Matched(true),
+ ));
+ assert!(matches!(
+ evaluate_detailed(program.tokens(), json!({})),
+ EvalOutcome::Matched(true),
+ ));
+ }
+
+ #[test]
+ fn stored_header_validation_matches_the_vm_load() {
+ for (stored, expected) in [
+ (json!([]), false),
+ (json!(["_X", 1]), false),
+ (json!(["_H", "one"]), false),
+ (json!(["_H", -1]), false),
+ (json!(["_H", true]), false),
+ (json!(["_H", 1.0]), false),
+ (json!(["_H", null]), false),
+ (json!(["_H", []]), false),
+ (json!(["_H"]), true),
+ (json!(["_H", 0]), true),
+ (json!(["_H", 1, OP_TRUE]), true),
+ (json!(["_H", u64::MAX]), true),
+ (
+ serde_json::from_str("[\"_H\",18446744073709551616]").unwrap(),
+ false,
+ ),
+ ] {
+ let stored = stored.as_array().unwrap();
+ assert_eq!(
+ ConditionProgram::has_valid_stored_header(stored),
+ expected,
+ "{stored:?}"
+ );
+ assert_eq!(
+ ConditionProgram::from_stored(stored).is_ok(),
+ expected,
+ "{stored:?}"
+ );
+ }
+
+ let header_values = [
+ Value::Null,
+ json!(false),
+ json!(true),
+ json!(-1),
+ json!(0),
+ json!(u64::MAX),
+ json!(1.0),
+ serde_json::from_str("18446744073709551616").unwrap(),
+ json!(""),
+ json!("_H"),
+ json!("_X"),
+ json!([]),
+ json!({}),
+ ];
+ for marker in &header_values {
+ for version in &header_values {
+ for body in [json!([]), json!([OP_TRUE, OP_RETURN]), json!(header_values)] {
+ let mut stored = vec![marker.clone(), version.clone()];
+ stored.extend(body.as_array().unwrap().iter().cloned());
+ assert_eq!(
+ ConditionProgram::has_valid_stored_header(&stored),
+ ConditionProgram::from_stored(&stored).is_ok(),
+ "{stored:?}",
+ );
+ }
+ }
+ }
+ }
+}
diff --git a/rust/cohort-core/src/leaf_state/key.rs b/rust/cohort-core/src/leaf_state/key.rs
index 384c8c324f82..9dd8c42389cc 100644
--- a/rust/cohort-core/src/leaf_state/key.rs
+++ b/rust/cohort-core/src/leaf_state/key.rs
@@ -19,7 +19,7 @@ impl LeafStateKey {
}
/// Hash the full predicate config. Field order must match the Python port
- /// (`_extract_leaf_state_keys` in `posthog/models/cohort/dependencies.py`).
+ /// (`behavioral_leaf_key` in `products/cohorts/backend/models/leaf_shape.py`).
pub fn for_behavioral(leaf: &BehavioralLeafConfig) -> Self {
let mut h = Sha256::new();
h.update(leaf.condition_hash);
@@ -45,10 +45,8 @@ impl LeafStateKey {
#[cfg(test)]
mod tests {
- use std::sync::Arc;
-
use super::*;
- use crate::filters::tree::{BehavioralLeafConfig, BehavioralValue};
+ use crate::filters::tree::BehavioralValue;
const HASH: [u8; 16] = *b"0123456789abcdef";
@@ -65,7 +63,6 @@ mod tests {
explicit_datetime_to: None,
leaf_state_key: LeafStateKey([0u8; 16]),
state_variant: None,
- bytecode: Arc::new(vec![]),
negated: false,
}
.with_state_key()
@@ -108,7 +105,6 @@ mod tests {
explicit_datetime_to: Some("2026-02-01T00:00:00Z".to_string()),
leaf_state_key: LeafStateKey([0u8; 16]),
state_variant: None,
- bytecode: Arc::new(vec![]),
negated: false,
}
.with_state_key()
@@ -139,7 +135,7 @@ mod tests {
#[test]
fn with_state_key_caches_the_derived_key() {
- let leaf = baseline();
+ let leaf = golden_leaf();
assert_eq!(leaf.leaf_state_key, LeafStateKey::for_behavioral(&leaf));
}
@@ -169,8 +165,8 @@ mod tests {
#[test]
fn negation_is_excluded_from_the_key() {
- let positive = baseline();
- let mut negated = baseline();
+ let positive = golden_leaf();
+ let mut negated = golden_leaf();
negated.negated = true;
assert_eq!(
LeafStateKey::for_behavioral(&positive),
diff --git a/rust/cohort-core/src/leaf_state/select.rs b/rust/cohort-core/src/leaf_state/select.rs
index 0113e0a147dd..c4803f81e1bd 100644
--- a/rust/cohort-core/src/leaf_state/select.rs
+++ b/rust/cohort-core/src/leaf_state/select.rs
@@ -396,7 +396,6 @@ fn explicit_window_days(from: Option<&str>, to: Option<&str>) -> u32 {
#[cfg(test)]
mod tests {
- use std::sync::Arc;
use chrono::{NaiveDate, TimeZone, Utc};
use chrono_tz::America::New_York;
@@ -437,7 +436,6 @@ mod tests {
explicit_datetime_to: None,
leaf_state_key: LeafStateKey([0u8; 16]),
state_variant: None,
- bytecode: Arc::new(vec![]),
negated: false,
}
.with_state_key()
diff --git a/rust/cohort-core/src/lib.rs b/rust/cohort-core/src/lib.rs
index bc335cf9ac73..7f24b3509ab7 100644
--- a/rust/cohort-core/src/lib.rs
+++ b/rust/cohort-core/src/lib.rs
@@ -44,8 +44,8 @@ pub use filters::{
};
pub use fingerprint::CatalogFingerprint;
pub use hogvm::{
- build_behavioral_globals, classify_vm_error, evaluate_detailed, CohortEvaluator, EvalOutcome,
- VmErrorClass,
+ build_behavioral_globals, classify_vm_error, evaluate_detailed, CohortEvaluator,
+ ConditionProgram, EvalOutcome, VmErrorClass,
};
pub use leaf_state::{EvictionWindow, LeafStateKey, StateVariant};
pub use partitioner::{partition_for, COHORT_PARTITION_COUNT};
diff --git a/rust/cohort-seeder/src/domain/aggregate.rs b/rust/cohort-seeder/src/domain/aggregate.rs
index d738a6b544c8..720e9efdde30 100644
--- a/rust/cohort-seeder/src/domain/aggregate.rs
+++ b/rust/cohort-seeder/src/domain/aggregate.rs
@@ -5,12 +5,12 @@
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::num::NonZeroU32;
-use std::sync::Arc;
use cohort_core::events::CohortStreamEvent;
use cohort_core::filters::{TeamFilters, TeamId};
use cohort_core::hogvm::{
- build_behavioral_globals, classify_vm_error, CohortEvaluator, EvalOutcome, VmErrorClass,
+ build_behavioral_globals, classify_vm_error, CohortEvaluator, ConditionProgram, EvalOutcome,
+ VmErrorClass,
};
use uuid::Uuid;
@@ -69,7 +69,7 @@ impl VmFailureCounts {
struct ActiveCandidate {
hash: ConditionHash,
- bytecode: Arc<Vec<serde_json::Value>>,
+ program: ConditionProgram,
}
pub struct ChunkAccumulator {
@@ -93,12 +93,12 @@ impl ChunkAccumulator {
.iter()
.filter_map(|candidate| active.get(candidate).map(|hash| (candidate, hash)))
.map(|(candidate, hash)| {
- let bytecode = filters
- .by_condition_to_bytecode
+ let program = filters
+ .by_condition_to_program
.get(candidate)
- .map(Arc::clone)
+ .cloned()
.ok_or(AggregateError::MissingBytecode(hash))?;
- Ok(ActiveCandidate { hash, bytecode })
+ Ok(ActiveCandidate { hash, program })
})
.collect::<Result<Vec<_>, AggregateError>>()?;
Ok((event_name.clone(), candidates))
@@ -145,10 +145,7 @@ impl ChunkAccumulator {
.map_or(&[][..], Vec::as_slice);
let mut stats = RecordStats::default();
for candidate in candidates {
- match self
- .evaluator
- .evaluate_detailed(Arc::clone(&candidate.bytecode))
- {
+ match self.evaluator.evaluate_detailed(&candidate.program) {
EvalOutcome::Matched(true) => {
increment_outcome(&mut stats.matched, OutcomeKind::Matched)?;
}
@@ -324,7 +321,8 @@ mod tests {
"properties": { "type": "AND", "values": [
{ "type": "behavioral", "value": "performed_event", "key": "false", "conditionHash": HASH_FALSE, "time_value": 7, "time_interval": "day", "bytecode": ["_H", 1, 30] },
{ "type": "behavioral", "value": "performed_event", "key": "unknown", "conditionHash": HASH_UNKNOWN, "time_value": 7, "time_interval": "day", "bytecode": ["_H", 1, 2, "definitelyNotANative", 0] },
- { "type": "behavioral", "value": "performed_event", "key": "broken", "conditionHash": HASH_BROKEN, "time_value": 7, "time_interval": "day", "bytecode": [] },
+ // Loads (the header is valid) but 9999 is no opcode, so it fails at run time.
+ { "type": "behavioral", "value": "performed_event", "key": "broken", "conditionHash": HASH_BROKEN, "time_value": 7, "time_interval": "day", "bytecode": ["_H", 1, 9999] },
]}
}),
)
diff --git a/rust/cohort-seeder/src/domain/condition_analysis.rs b/rust/cohort-seeder/src/domain/condition_analysis.rs
index 1890d5e41261..3ebeb1376061 100644
--- a/rust/cohort-seeder/src/domain/condition_analysis.rs
+++ b/rust/cohort-seeder/src/domain/condition_analysis.rs
@@ -133,15 +133,15 @@ impl ConditionAnalyses {
if by_hash.contains_key(&condition.hash) {
continue;
}
- let Some(bytecode) = filters
- .by_condition_to_bytecode
+ let Some(program) = filters
+ .by_condition_to_program
.get(&condition.hash.as_bytes())
else {
continue;
};
by_hash.insert(
condition.hash,
- analyze_condition_within(bytecode.as_slice(), &mut budget),
+ analyze_condition_within(program.tokens(), &mut budget),
);
}
Self { by_hash }
diff --git a/rust/cohort-seeder/src/domain/person.rs b/rust/cohort-seeder/src/domain/person.rs
index 72010f601f08..cd6ea7f0a7f7 100644
--- a/rust/cohort-seeder/src/domain/person.rs
+++ b/rust/cohort-seeder/src/domain/person.rs
@@ -9,12 +9,11 @@
//! decode would strand claimed chunks `scanning`.
use std::collections::{BTreeMap, HashSet};
-use std::sync::Arc;
use chrono::NaiveDate;
use cohort_core::filters::{CohortId, TeamFilters, TeamId};
use cohort_core::hogvm::{
- build_person_scan_globals, classify_vm_error, CohortEvaluator, EvalOutcome,
+ build_person_scan_globals, classify_vm_error, CohortEvaluator, ConditionProgram, EvalOutcome,
};
use cohort_core::seed::PersonSeed;
use cohort_core::{LeafStateKey, StateVariant};
@@ -195,7 +194,7 @@ impl PinnedPersonRun {
let tz = resolve_timezone(&snapshot.timezone, &mut warnings);
let participation = ParticipationSet::build(snapshot.team_id, snapshot.participations, tz)?;
- let mut surviving: BTreeMap<ConditionHash, Arc<Vec<Value>>> = BTreeMap::new();
+ let mut surviving: BTreeMap<ConditionHash, ConditionProgram> = BTreeMap::new();
let mut covered: HashSet<CohortId> = HashSet::new();
for raw in payload.conditions {
let cohort_id = CohortId(raw.cohort_id);
@@ -213,8 +212,8 @@ impl PinnedPersonRun {
continue;
}
match classify_person_condition(hash, participation.filters()) {
- PersonSurvival::Survives(bytecode) => {
- surviving.entry(hash).or_insert(bytecode);
+ PersonSurvival::Survives(program) => {
+ surviving.entry(hash).or_insert(program);
covered.insert(cohort_id);
}
PersonSurvival::Dropped(reason) => {
@@ -275,7 +274,7 @@ impl PinnedPersonRun {
/// Whether one pinned hash survives against the frozen catalog — the structural mirror of the
/// processor's `effective_hashes` projection.
enum PersonSurvival {
- Survives(Arc<Vec<Value>>),
+ Survives(ConditionProgram),
Dropped(PinnedDropReason),
}
@@ -293,21 +292,21 @@ fn classify_person_condition(hash: ConditionHash, filters: &TeamFilters) -> Pers
Some(_) => return PersonSurvival::Dropped(PinnedDropReason::VariantMismatch),
None => return PersonSurvival::Dropped(PinnedDropReason::AbsentFromFrozenCatalog),
}
- match filters.by_condition_to_bytecode.get(&bytes) {
- Some(bytecode) => PersonSurvival::Survives(Arc::clone(bytecode)),
+ match filters.by_condition_to_program.get(&bytes) {
+ Some(program) => PersonSurvival::Survives(program.clone()),
None => PersonSurvival::Dropped(PinnedDropReason::AbsentFromFrozenCatalog),
}
}
/// The surviving person conditions: non-empty, sorted-distinct by hash, each with its frozen
-/// bytecode — so an empty `evaluated` or a hash/bytecode mismatch is unrepresentable at eval time.
+/// program — so an empty `evaluated` or a hash/program mismatch is unrepresentable at eval time.
#[derive(Debug, Clone)]
-pub struct EvaluatedConditions(Vec<(ConditionHash, Arc<Vec<Value>>)>);
+pub struct EvaluatedConditions(Vec<(ConditionHash, ConditionProgram)>);
// Non-empty by construction, so an `is_empty` would be a method whose contract is "never call me".
#[allow(clippy::len_without_is_empty)]
impl EvaluatedConditions {
- fn new(surviving: BTreeMap<ConditionHash, Arc<Vec<Value>>>) -> Result<Self, PinnedError> {
+ fn new(surviving: BTreeMap<ConditionHash, ConditionProgram>) -> Result<Self, PinnedError> {
if surviving.is_empty() {
return Err(PinnedError::NoSurvivingPersonConditions);
}
@@ -321,7 +320,7 @@ impl EvaluatedConditions {
self.0.len()
}
- pub fn iter(&self) -> impl Iterator<Item = &(ConditionHash, Arc<Vec<Value>>)> {
+ pub fn iter(&self) -> impl Iterator<Item = &(ConditionHash, ConditionProgram)> {
self.0.iter()
}
}
@@ -404,8 +403,8 @@ impl PersonEvaluator {
let mut evaluated = Vec::with_capacity(self.conditions.len());
let mut matched = Vec::new();
- for (hash, bytecode) in self.conditions.iter() {
- match self.evaluator.evaluate_detailed(Arc::clone(bytecode)) {
+ for (hash, program) in self.conditions.iter() {
+ match self.evaluator.evaluate_detailed(program) {
EvalOutcome::Matched(true) => {
evaluated.push(*hash);
matched.push(*hash);
@@ -897,9 +896,9 @@ mod tests {
let PersonRowOutcome::Seed(seed) = outcome else {
panic!("expected a seed, got {outcome:?}");
};
- for (hash, bytecode) in build_evaluator(true).conditions.iter() {
+ for (hash, program) in build_evaluator(true).conditions.iter() {
let live = matches!(
- cohort_core::hogvm::evaluate_detailed(bytecode, globals.clone()),
+ cohort_core::hogvm::evaluate_detailed(program.tokens(), globals.clone()),
EvalOutcome::Matched(true)
);
assert_eq!(seed.matched().contains(hash), live, "hash {hash} diverged");
@@ -911,7 +910,9 @@ mod tests {
/// assert FALSE for a hash the VM never answered — and an all-failure row emits nothing.
#[test]
fn vm_failures_drop_hashes_from_evaluated_rather_than_asserting_false() {
- let broken = json!([]);
+ // Loads (the header is valid) but 9999 is no opcode, so it fails at run time. Bytecode the
+ // loader rejects outright never reaches the evaluator: that leaf is dropped at catalog build.
+ let broken = json!(["_H", 1, 9999]);
let mut leaves = person_filter_leaves(&[(HASH_A, "email", "[email protected]")]);
leaves["properties"]["values"]
.as_array_mut()
diff --git a/rust/cohort-seeder/src/domain/pinned.rs b/rust/cohort-seeder/src/domain/pinned.rs
index 0428cab47190..5d39aa3bef8f 100644
--- a/rust/cohort-seeder/src/domain/pinned.rs
+++ b/rust/cohort-seeder/src/domain/pinned.rs
@@ -3,7 +3,6 @@
use std::collections::{HashMap, HashSet};
use std::str::FromStr;
-use std::sync::Arc;
use chrono_tz::Tz;
use cohort_core::filters::tree::{BehavioralLeafConfig, BehavioralValue};
@@ -459,6 +458,8 @@ fn derive_lookback(
PinnedDropReason::AbsentFromFrozenCatalog,
));
};
+ // The event name is not hashed into the key, but a condition without one never matched a
+ // catalog leaf, so it stays a drop.
let Some(event_name) = raw.event_name.as_ref() else {
return Ok(LookbackResolution::Dropped(
PinnedDropReason::AbsentFromFrozenCatalog,
@@ -476,7 +477,6 @@ fn derive_lookback(
explicit_datetime_to: raw.explicit_datetime_to.clone(),
leaf_state_key: LeafStateKey([0; 16]),
state_variant: None,
- bytecode: Arc::new(Vec::new()),
negated: false,
}
.with_state_key();
diff --git a/rust/cohort-stream-processor/src/filters/manager.rs b/rust/cohort-stream-processor/src/filters/manager.rs
index 141cfc4361af..56041dc20d61 100644
--- a/rust/cohort-stream-processor/src/filters/manager.rs
+++ b/rust/cohort-stream-processor/src/filters/manager.rs
@@ -4,23 +4,25 @@ use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
-use std::time::{Duration, SystemTime, UNIX_EPOCH};
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use arc_swap::{ArcSwap, Guard};
use common_types::cohort::TeamAllowlist;
use lifecycle::Handle;
-use metrics::{counter, gauge};
+use metrics::{counter, gauge, histogram};
use rand::Rng;
use sqlx::PgPool;
+use thiserror::Error;
use tokio::sync::Notify;
+use tokio::task::JoinError;
use tracing::{debug, info, warn};
use crate::filters::loader::{build_catalog_from_rows, load_realtime_cohorts, CohortRow};
use crate::filters::FilterError;
use crate::filters::{FilterCatalog, Generation};
use crate::observability::metrics::{
- FILTER_CATALOG_LAST_SUCCESS_TIMESTAMP_SECONDS, FILTER_CATALOG_REFRESH_TOTAL,
- FILTER_CATALOG_TEAMS, FILTER_CATALOG_UNIQUE_CONDITIONS,
+ FILTER_CATALOG_BUILD_DURATION_SECONDS, FILTER_CATALOG_LAST_SUCCESS_TIMESTAMP_SECONDS,
+ FILTER_CATALOG_REFRESH_TOTAL, FILTER_CATALOG_TEAMS, FILTER_CATALOG_UNIQUE_CONDITIONS,
};
/// Snapshot counts returned by [`CatalogHandle::refresh`] for logging.
@@ -30,6 +32,14 @@ pub struct CatalogStats {
pub unique_conditions: usize,
}
+#[derive(Debug, Error)]
+pub enum CatalogRefreshError {
+ #[error(transparent)]
+ Load(#[from] FilterError),
+ #[error("filter catalog build worker failed: {0}")]
+ Build(#[from] JoinError),
+}
+
/// Lock-free, atomically-swapped catalog handle. Starts empty and unloaded; the pipeline fails
/// closed until the first successful refresh.
pub struct CatalogHandle {
@@ -129,7 +139,7 @@ impl CatalogHandle {
/// The staleness metrics are stamped here rather than in [`run_refresh_loop`] so the boot load
/// in `main` counts too — otherwise a pod that booted fine and then lost its refresh loop would
/// look identical to one that never loaded.
- pub async fn refresh(&self, pool: &PgPool) -> Result<CatalogStats, FilterError> {
+ pub async fn refresh(&self, pool: &PgPool) -> Result<CatalogStats, CatalogRefreshError> {
match self.refresh_inner(pool).await {
Ok(stats) => {
gauge!(FILTER_CATALOG_LAST_SUCCESS_TIMESTAMP_SECONDS).set(now_unix_seconds());
@@ -143,7 +153,7 @@ impl CatalogHandle {
}
}
- async fn refresh_inner(&self, pool: &PgPool) -> Result<CatalogStats, FilterError> {
+ async fn refresh_inner(&self, pool: &PgPool) -> Result<CatalogStats, CatalogRefreshError> {
let mut rows = load_realtime_cohorts(pool).await?;
let fetched_rows = rows.len();
retain_allowlisted(&mut rows, &self.allowlist);
@@ -154,7 +164,23 @@ impl CatalogHandle {
"filter catalog dropped cohort rows outside REALTIME_COHORT_TEAM_ALLOWLIST",
);
}
- let catalog = build_catalog_from_rows(rows, self.cascade_enabled);
+ let cascade_enabled = self.cascade_enabled;
+ self.build_and_store(move || build_catalog_from_rows(rows, cascade_enabled))
+ .await
+ }
+
+ async fn build_and_store(
+ &self,
+ build: impl FnOnce() -> FilterCatalog + Send + 'static,
+ ) -> Result<CatalogStats, CatalogRefreshError> {
+ let catalog = tokio::task::spawn_blocking(move || {
+ let build_started = Instant::now();
+ let catalog = build();
+ histogram!(FILTER_CATALOG_BUILD_DURATION_SECONDS)
+ .record(build_started.elapsed().as_secs_f64());
+ catalog
+ })
+ .await?;
let stats = CatalogStats {
teams: catalog.team_count(),
unique_conditions: catalog.total_unique_conditions(),
@@ -317,6 +343,31 @@ mod tests {
assert_eq!(snapshot.total_unique_conditions(), 1);
}
+ #[tokio::test]
+ async fn catalog_build_runs_off_the_runtime_and_failure_keeps_the_snapshot() {
+ let handle = CatalogHandle::new();
+ let runtime_thread = std::thread::current().id();
+ let stats = handle
+ .build_and_store(move || {
+ assert_ne!(std::thread::current().id(), runtime_thread);
+ FilterCatalog::from_teams([(TeamId(7), team_with_one_behavioral())])
+ })
+ .await
+ .unwrap();
+ assert_eq!(stats.teams, 1);
+ assert_eq!(stats.unique_conditions, 1);
+ assert!(handle.is_loaded());
+ let snapshot = handle.load_full();
+
+ let error = handle
+ .build_and_store(|| panic!("catalog build failed"))
+ .await
+ .unwrap_err();
+ assert!(matches!(error, CatalogRefreshError::Build(error) if error.is_panic()));
+ assert!(Arc::ptr_eq(&snapshot, &handle.load_full()));
+ assert!(handle.is_loaded());
+ }
+
#[tokio::test]
async fn wait_until_loaded_resolves_on_the_first_store_and_immediately_after() {
let handle = Arc::new(CatalogHandle::new());
diff --git a/rust/cohort-stream-processor/src/filters/mod.rs b/rust/cohort-stream-processor/src/filters/mod.rs
index a90825b95f9a..250ccb971d9f 100644
--- a/rust/cohort-stream-processor/src/filters/mod.rs
+++ b/rust/cohort-stream-processor/src/filters/mod.rs
@@ -13,4 +13,4 @@ pub use cohort_core::filters::{
pub use cohort_core::filters::{FilterCatalog, Generation};
pub use cohort_core::filters::{TeamFilters, TeamFiltersBuilder};
-pub use manager::{run_refresh_loop, CatalogHandle, CatalogStats};
+pub use manager::{run_refresh_loop, CatalogHandle, CatalogRefreshError, CatalogStats};
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
index 27fd45263b1c..b39e665ebb99 100644
--- a/rust/cohort-stream-processor/src/observability/metrics.rs
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -26,6 +26,11 @@ pub const FILTER_CATALOG_LAST_SUCCESS_TIMESTAMP_SECONDS: &str =
/// Catalog refresh attempts, labelled by `result` (`success`|`error`) (counter). The `error` series
/// gives the failure rate; the `success` series proves the loop is still ticking at all.
pub const FILTER_CATALOG_REFRESH_TOTAL: &str = "filter_catalog_refresh_total";
+/// Wall time of one catalog build — parsing every cohort's filters JSON and loading every leaf's
+/// bytecode (histogram, seconds). The build runs on the blocking pool, so it cannot stall a
+/// partition worker; a build that grew into the seconds instead shows up as catalog staleness.
+/// Measured inside the offloaded closure, so it excludes blocking-pool queue delay.
+pub const FILTER_CATALOG_BUILD_DURATION_SECONDS: &str = "filter_catalog_build_duration_seconds";
/// Cascade depths reached, from the `depth` field on cascade messages (histogram). Cohort ids are
/// logged, not labelled, to keep cardinality bounded.
pub const CASCADE_DEPTH_OBSERVED: &str = "cascade_depth_observed";
@@ -644,6 +649,10 @@ mod tests {
"filter_catalog_last_success_timestamp_seconds",
);
assert_eq!(FILTER_CATALOG_REFRESH_TOTAL, "filter_catalog_refresh_total");
+ assert_eq!(
+ FILTER_CATALOG_BUILD_DURATION_SECONDS,
+ "filter_catalog_build_duration_seconds",
+ );
}
#[test]
diff --git a/rust/cohort-stream-processor/src/stage2/evaluator.rs b/rust/cohort-stream-processor/src/stage2/evaluator.rs
index 1647506dc596..1b01ced82f97 100644
--- a/rust/cohort-stream-processor/src/stage2/evaluator.rs
+++ b/rust/cohort-stream-processor/src/stage2/evaluator.rs
@@ -86,10 +86,6 @@ pub fn evaluate_tree(
#[cfg(test)]
mod tests {
- use std::sync::Arc;
-
- use serde_json::Value;
-
use super::*;
use crate::filters::tree::{CohortLeaf, CohortRefLeafConfig, CohortTree, PersonLeafConfig};
use crate::filters::{CohortId, TeamId};
@@ -108,8 +104,6 @@ mod tests {
FilterNode::Leaf(CohortLeaf::PersonProperty(PersonLeafConfig {
condition_hash: key.0,
leaf_state_key: key,
- bytecode: Arc::new(Vec::new()),
- raw: Value::Null,
negated,
}))
}
@@ -150,8 +144,7 @@ mod tests {
};
let flags = CohortParseFlags {
state_keyed_leaf_count: state_keyed_leaf_count(root),
- has_cohort_ref: false,
- has_dropped_leaf: false,
+ ..CohortParseFlags::default()
};
matches!(
classify(&tree, &flags),
diff --git a/rust/cohort-stream-processor/src/workers/event_path.rs b/rust/cohort-stream-processor/src/workers/event_path.rs
index efbcb5b26fa8..b08ff444c730 100644
--- a/rust/cohort-stream-processor/src/workers/event_path.rs
+++ b/rust/cohort-stream-processor/src/workers/event_path.rs
@@ -13,7 +13,6 @@
//! `cf_person_records`, updated per the freshness decision table in [`crate::stage1::person_record`].
use std::collections::BTreeMap;
-use std::sync::Arc;
use metrics::{counter, histogram};
use uuid::Uuid;
@@ -837,11 +836,11 @@ fn eval_behavioral_condition(
evaluator: &mut CohortEvaluator,
applies: &mut Vec<BehavioralApply>,
) {
- let Some(bytecode) = filters.by_condition_to_bytecode.get(&hash) else {
+ let Some(program) = filters.by_condition_to_program.get(&hash) else {
return;
};
counter!(STAGE1_CONDITIONS_EVALUATED, "kind" => "behavioral").increment(1);
- if !evaluator.evaluate(Arc::clone(bytecode)) {
+ if !evaluator.evaluate(program) {
return;
}
let Some(lsks) = filters.by_condition_to_lsk.get(&hash) else {
@@ -880,7 +879,7 @@ fn eval_person_conditions(
let mut true_hashes: Vec<[u8; 16]> = Vec::new();
let mut effective_catalog: Vec<[u8; 16]> = Vec::new();
for &hash in &filters.person_conditions_ordered {
- let Some(bytecode) = filters.by_condition_to_bytecode.get(&hash) else {
+ let Some(program) = filters.by_condition_to_program.get(&hash) else {
continue;
};
// A hash whose LSK meta is missing or not a `PersonProperty` variant is skipped, so it is not
@@ -899,7 +898,7 @@ fn eval_person_conditions(
// `person_conditions_ordered` is sorted, so pushing in iteration order keeps the effective
// catalog sorted for the binary searches in `diff`/`apply_eval`.
effective_catalog.push(hash);
- if evaluator.evaluate(Arc::clone(bytecode)) {
+ if evaluator.evaluate(program) {
true_hashes.push(hash);
}
}
diff --git a/rust/cohort-stream-processor/tests/filter_catalog.rs b/rust/cohort-stream-processor/tests/filter_catalog.rs
index 93e8b45322a7..5dc4a6f09fe9 100644
--- a/rust/cohort-stream-processor/tests/filter_catalog.rs
+++ b/rust/cohort-stream-processor/tests/filter_catalog.rs
@@ -1,6 +1,9 @@
//! Public-API integration tests for the filter catalog. The exhaustive per-field discrimination
//! matrix and classifier edge cases live in the in-crate `#[cfg(test)]` modules.
+use std::io::{self, Write};
+use std::sync::{Arc, Mutex};
+
use cohort_stream_processor::filters::{
build_catalog_from_rows, CohortId, CohortLeaf, CohortRow, FilterCatalog, FilterNode, TeamId,
};
@@ -151,7 +154,68 @@ fn dropped_leaves_are_skipped_while_survivors_stay_indexed() {
}
#[test]
-fn bytecode_is_captured_and_deduped_by_condition_hash() {
+fn malformed_leaves_warn_once_per_cohort_per_build() {
+ struct LogWriter(Arc<Mutex<Vec<u8>>>);
+
+ impl Write for LogWriter {
+ fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
+ self.0.lock().unwrap().write(bytes)
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ Ok(())
+ }
+ }
+
+ let output = Arc::new(Mutex::new(Vec::new()));
+ let writer = output.clone();
+ let subscriber = tracing_subscriber::fmt()
+ .json()
+ .without_time()
+ .with_writer(move || LogWriter(writer.clone()))
+ .finish();
+ let _guard = tracing::subscriber::set_default(subscriber);
+ let mut malformed = person_leaf();
+ malformed["bytecode"] = json!(["_X", 1]);
+
+ for _ in 0..2 {
+ let catalog = build_catalog(vec![
+ row(1, 7, cohort(vec![malformed.clone(); 10])),
+ row(2, 7, cohort(vec![malformed.clone(); 3])),
+ row(3, 7, cohort(vec![behavioral_performed_event(7)])),
+ ]);
+ let team = catalog.team(TeamId(7)).unwrap();
+ for id in [1, 2] {
+ assert_eq!(
+ team.eligibility[&CohortId(id)],
+ CohortEligibility::Excluded(ExcludedReason::HasDroppedLeaf),
+ );
+ }
+ assert_eq!(team.by_condition_to_program.len(), 1);
+ }
+
+ let output = output.lock().unwrap();
+ // Narrowed to the warning under test: the same builds emit a cohort-parse warning carrying a
+ // `cohort_id` but no count, and a timezone warning carrying neither, so a fixture that grew one
+ // would panic inside the closure instead of failing an assertion.
+ let mut warnings: Vec<(i64, u64)> = String::from_utf8_lossy(&output)
+ .lines()
+ .map(|line| serde_json::from_str::<Value>(line).unwrap())
+ .filter(|event| event["fields"]["malformed_leaves"].is_u64())
+ .map(|event| {
+ assert_eq!(event["level"], "WARN");
+ (
+ event["fields"]["cohort_id"].as_i64().unwrap(),
+ event["fields"]["malformed_leaves"].as_u64().unwrap(),
+ )
+ })
+ .collect();
+ warnings.sort_unstable();
+ assert_eq!(warnings, vec![(1, 10), (1, 10), (2, 3), (2, 3)]);
+}
+
+#[test]
+fn the_loaded_program_is_captured_and_deduped_by_condition_hash() {
let catalog = build_catalog(vec![
row(
1,
@@ -162,12 +226,12 @@ fn bytecode_is_captured_and_deduped_by_condition_hash() {
]);
let team = catalog.team(TeamId(7)).expect("team 7 present");
- assert_eq!(team.by_condition_to_bytecode.len(), 2);
+ assert_eq!(team.by_condition_to_program.len(), 2);
assert_eq!(
- team.by_condition_to_bytecode[&BEHAVIORAL_HASH].as_ref(),
+ team.by_condition_to_program[&BEHAVIORAL_HASH].tokens(),
&behavioral_bytecode_loaded(),
);
- assert!(team.by_condition_to_bytecode.contains_key(&PERSON_HASH));
+ assert!(team.by_condition_to_program.contains_key(&PERSON_HASH));
}
#[test]
@@ -187,7 +251,7 @@ fn leaf_without_bytecode_is_dropped() {
let team = catalog.team(TeamId(7)).expect("team 7 present");
assert!(team.unique_condition_hashes.is_empty());
- assert!(team.by_condition_to_bytecode.is_empty());
+ assert!(team.by_condition_to_program.is_empty());
assert!(team.by_condition_to_lsk.is_empty());
}