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): person memoization (#66903)

Matheus Batistabce7af4a9434
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 4e22740ac004..db42f3493f2a 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2176,6 +2176,7 @@ dependencies = [
"futures",
"hogvm",
"lifecycle",
+ "lru",
"metrics",
"metrics-exporter-prometheus",
"object_store",
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index dec2bda0c5b8..de0e9ef84afd 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -126,6 +126,7 @@ mockito = "1"
hyper = { version = "1.9.0", features = ["server", "http1", "http2"] }
hyper-util = { version = "0.1.20", features = ["server", "server-graceful", "tokio", "http1", "http2"] }
itoa = "1.0.15"
+lru = "0.12"
metrics = "0.22.0"
metrics-exporter-prometheus = "0.14.0"
metrics-util = "0.16.0"
diff --git a/rust/cohort-stream-processor/Cargo.toml b/rust/cohort-stream-processor/Cargo.toml
index 12cce1095305..11a9ae7447f0 100644
--- a/rust/cohort-stream-processor/Cargo.toml
+++ b/rust/cohort-stream-processor/Cargo.toml
@@ -35,6 +35,7 @@ envconfig = { workspace = true }
futures = { workspace = true }
hogvm = { path = "../common/hogvm" }
lifecycle = { path = "../common/lifecycle" }
+lru = { workspace = true }
metrics = { workspace = true }
metrics-exporter-prometheus = { workspace = true }
# Streaming `BufWriter` and prefix-list (`list_with_delimiter`) S3 for multi-MB checkpoint files.
diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rs
index 856c08ed0da2..9ac2c727bba7 100644
--- a/rust/cohort-stream-processor/src/config.rs
+++ b/rust/cohort-stream-processor/src/config.rs
@@ -13,7 +13,7 @@ use tracing::warn;
use crate::store::durability::DurabilityConfig;
use crate::store::StoreConfig;
-use crate::workers::{CascadeConfig, TransferRetryPolicy};
+use crate::workers::{CascadeConfig, PersonMemoConfig, TransferRetryPolicy};
const POOL_NAME: &str = "posthog_cohort";
@@ -58,6 +58,15 @@ pub struct Config {
#[envconfig(from = "REALTIME_COHORT_TEAM_ALLOWLIST", default = "2")]
pub team_allowlist: TeamAllowlist,
+ /// Memoize person-property results per `(team, person)`, skipping re-evaluation when a person's
+ /// properties are unchanged. Default on.
+ #[envconfig(from = "COHORT_PERSON_MEMO_ENABLED", default = "true")]
+ pub cohort_person_memo_enabled: bool,
+
+ /// Per-worker LRU capacity (entries) for the person-property result memo.
+ #[envconfig(from = "COHORT_PERSON_MEMO_CAPACITY", default = "20000")]
+ pub cohort_person_memo_capacity: usize,
+
/// Bounded buffer (in sub-batches) per per-partition worker channel.
/// Routing to a partition this far behind blocks rather than growing memory unbounded.
#[envconfig(default = "1024")]
@@ -429,6 +438,13 @@ impl Config {
}
}
+ pub fn person_memo_config(&self) -> PersonMemoConfig {
+ PersonMemoConfig {
+ enabled: self.cohort_person_memo_enabled,
+ capacity: self.cohort_person_memo_capacity,
+ }
+ }
+
pub fn merge_gc_interval(&self) -> Duration {
Duration::from_millis(self.merge_gc_interval_ms)
}
@@ -658,6 +674,8 @@ mod tests {
filter_catalog_refresh_secs: 300,
filter_catalog_refresh_jitter_secs: 60,
team_allowlist: TeamAllowlist::All,
+ cohort_person_memo_enabled: true,
+ cohort_person_memo_capacity: 20000,
partition_channel_buffer: 1024,
kafka_hosts: "localhost:9092".to_string(),
kafka_tls: false,
@@ -1216,6 +1234,35 @@ mod tests {
);
}
+ #[test]
+ fn person_memo_defaults_on_and_overrides_from_env() {
+ let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();
+ assert!(
+ defaults.cohort_person_memo_enabled,
+ "the person memo defaults on",
+ );
+ assert_eq!(defaults.cohort_person_memo_capacity, 20000);
+ assert!(
+ defaults.person_memo_config().enabled,
+ "person_memo_config threads the enabled flag",
+ );
+ assert_eq!(defaults.person_memo_config().capacity, 20000);
+
+ let env: std::collections::HashMap<String, String> = [
+ ("COHORT_PERSON_MEMO_ENABLED", "false"),
+ ("COHORT_PERSON_MEMO_CAPACITY", "5000"),
+ ]
+ .into_iter()
+ .map(|(key, value)| (key.to_string(), value.to_string()))
+ .collect();
+ let config = Config::init_from_hashmap(&env).unwrap();
+ assert!(
+ !config.cohort_person_memo_enabled,
+ "the kill-switch disables the memo",
+ );
+ assert_eq!(config.cohort_person_memo_capacity, 5000);
+ }
+
#[test]
fn cascade_caps_default_and_override_from_env() {
let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();
diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rs
index d106acf2850e..c63cc0fc2ac5 100644
--- a/rust/cohort-stream-processor/src/consumers/events.rs
+++ b/rust/cohort-stream-processor/src/consumers/events.rs
@@ -45,7 +45,7 @@ use crate::partitions::shuffle_message::ShuffleMessage;
use crate::producer::MembershipSink;
use crate::store::durability::OffsetManifest;
use crate::store::CohortStore;
-use crate::workers::{MergeWorkerDeps, Stage1Worker};
+use crate::workers::{MergeWorkerDeps, PersonMemoConfig, Stage1Worker};
/// Back-off after a Kafka transport error so a fast-failing `recv()` can't spin a consume loop.
pub(crate) const RECV_ERROR_BACKOFF: Duration = Duration::from_millis(500);
@@ -125,6 +125,8 @@ pub struct EventDispatcher {
/// after boot. `OnceLock` is `Sync`; the only race (get sees `None` before set) resolves to
/// "skip", so a boot partition is never wiped.
boot_assignment: OnceLock<HashSet<i32>>,
+ /// Person-memo config for spawned workers, set once at startup. Unset → disabled.
+ person_memo: OnceLock<PersonMemoConfig>,
}
impl EventDispatcher {
@@ -148,6 +150,7 @@ impl EventDispatcher {
draining: AtomicBool::new(false),
durable_restore: AtomicBool::new(false),
boot_assignment: OnceLock::new(),
+ person_memo: OnceLock::new(),
}
}
@@ -160,6 +163,18 @@ impl EventDispatcher {
self.durable_restore.load(Ordering::SeqCst)
}
+ /// Must be called before any worker spawns; later calls are ignored.
+ pub fn set_person_memo_config(&self, config: PersonMemoConfig) {
+ let _ = self.person_memo.set(config);
+ }
+
+ fn person_memo_config(&self) -> PersonMemoConfig {
+ self.person_memo
+ .get()
+ .copied()
+ .unwrap_or(PersonMemoConfig::DISABLED)
+ }
+
pub(crate) fn store(&self) -> &CohortStore {
&self.store
}
@@ -323,7 +338,7 @@ impl EventDispatcher {
}
match self.router.add_partition(partition) {
Some(receiver) => {
- let worker = Stage1Worker::spawn(
+ let worker = Stage1Worker::spawn_with_memo(
partition as u16,
receiver,
self.store.clone(),
@@ -332,6 +347,7 @@ impl EventDispatcher {
self.tracker.clone(),
self.merge.clone(),
self.durable_restore_enabled(),
+ self.person_memo_config(),
);
slot.insert(worker);
counter!(COHORT_STREAM_WORKERS_SPAWNED).increment(1);
diff --git a/rust/cohort-stream-processor/src/filters/manager.rs b/rust/cohort-stream-processor/src/filters/manager.rs
index 07eb061d064c..981c610b45e3 100644
--- a/rust/cohort-stream-processor/src/filters/manager.rs
+++ b/rust/cohort-stream-processor/src/filters/manager.rs
@@ -1,7 +1,9 @@
//! `FilterCatalog` + atomic swap + jittered periodic refresh loop.
+use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
-use std::sync::atomic::{AtomicBool, Ordering};
+use std::hash::{Hash, Hasher};
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;
@@ -19,15 +21,31 @@ use crate::filters::reverse_index::TeamFilters;
use crate::filters::{FilterError, TeamId};
use crate::observability::metrics::{FILTER_CATALOG_TEAMS, FILTER_CATALOG_UNIQUE_CONDITIONS};
+/// The catalog's content epoch. Compared for memo invalidation; advanced on a content change.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
+pub struct Generation(pub u64);
+
+impl Generation {
+ /// The empty pre-load catalog; no team is evaluated against it.
+ pub const INITIAL: Self = Self(0);
+
+ fn next(self) -> Self {
+ Self(self.0 + 1)
+ }
+}
+
#[derive(Debug, Default)]
pub struct FilterCatalog {
teams: HashMap<TeamId, Arc<TeamFilters>>,
+ /// Content epoch, stamped by [`CatalogHandle::store`].
+ generation: Generation,
}
impl FilterCatalog {
pub fn new() -> Self {
Self {
teams: HashMap::new(),
+ generation: Generation::INITIAL,
}
}
@@ -36,6 +54,10 @@ impl FilterCatalog {
self.teams.get(&team_id)
}
+ pub fn generation(&self) -> Generation {
+ self.generation
+ }
+
pub fn team_count(&self) -> usize {
self.teams.len()
}
@@ -54,6 +76,7 @@ impl FilterCatalog {
.into_iter()
.map(|(team, filters)| (team, Arc::new(filters)))
.collect(),
+ generation: Generation::INITIAL,
}
}
}
@@ -74,6 +97,11 @@ pub struct CatalogHandle {
/// Cohorts for teams outside this allowlist never enter the catalog.
allowlist: TeamAllowlist,
cascade_enabled: bool,
+ /// Last stamped generation, advanced by [`Self::store`]. Single-writer (the refresh loop),
+ /// so `Relaxed` suffices.
+ current_generation: AtomicU64,
+ /// Signature of the last stored catalog, to detect a no-op refresh.
+ current_signature: AtomicU64,
}
impl CatalogHandle {
@@ -88,6 +116,8 @@ impl CatalogHandle {
loaded_notify: Notify::new(),
allowlist,
cascade_enabled,
+ current_generation: AtomicU64::new(0),
+ current_signature: AtomicU64::new(0),
}
}
@@ -122,7 +152,22 @@ impl CatalogHandle {
handle
}
- fn store(&self, catalog: FilterCatalog) {
+ fn store(&self, mut catalog: FilterCatalog) {
+ // Advance the generation only on a content change (`INITIAL` is the first store); a no-op
+ // refresh reuses it so memo entries stay valid.
+ let signature = catalog_signature(&catalog);
+ let prev = Generation(self.current_generation.load(Ordering::Relaxed));
+ let prev_sig = self.current_signature.load(Ordering::Relaxed);
+ let generation = if prev == Generation::INITIAL || signature != prev_sig {
+ prev.next()
+ } else {
+ prev
+ };
+ self.current_signature.store(signature, Ordering::Relaxed);
+ self.current_generation
+ .store(generation.0, Ordering::Relaxed);
+ catalog.generation = generation;
+
gauge!(FILTER_CATALOG_TEAMS).set(catalog.team_count() as f64);
gauge!(FILTER_CATALOG_UNIQUE_CONDITIONS).set(catalog.total_unique_conditions() as f64);
self.catalog.store(Arc::new(catalog));
@@ -158,6 +203,22 @@ impl Default for CatalogHandle {
}
}
+/// Hashes equal iff each team carries the same condition set — the sorts make it independent of
+/// `HashMap`/`HashSet` order. `DefaultHasher` is unseeded; only intra-process consistency is needed
+/// (the memo it gates resets on restart).
+fn catalog_signature(catalog: &FilterCatalog) -> u64 {
+ let mut teams: Vec<(&TeamId, &Arc<TeamFilters>)> = catalog.teams.iter().collect();
+ teams.sort_unstable_by_key(|(team, _)| team.0);
+ let mut hasher = DefaultHasher::new();
+ for (team, filters) in teams {
+ team.0.hash(&mut hasher);
+ let mut hashes: Vec<[u8; 16]> = filters.unique_condition_hashes.iter().copied().collect();
+ hashes.sort_unstable();
+ hashes.hash(&mut hasher);
+ }
+ hasher.finish()
+}
+
/// Periodic catalog refresh task. On failure, keeps the previous snapshot and retries next tick.
pub async fn run_refresh_loop(
catalog: Arc<CatalogHandle>,
@@ -229,6 +290,27 @@ mod tests {
builder.freeze(UTC)
}
+ fn team_with_one_person() -> TeamFilters {
+ let mut builder = TeamFiltersBuilder::default();
+ let filters = json!({
+ "properties": {
+ "type": "AND",
+ "values": [{
+ "type": "person",
+ "key": "email",
+ "value": "[email protected]",
+ "operator": "exact",
+ "conditionHash": "fedcba9876543210",
+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],
+ }],
+ }
+ });
+ builder
+ .add_cohort(CohortId(1), TeamId(7), &filters)
+ .unwrap();
+ builder.freeze(UTC)
+ }
+
#[test]
fn new_handle_is_unloaded_and_empty() {
let handle = CatalogHandle::new();
@@ -271,6 +353,62 @@ mod tests {
handle.wait_until_loaded().await;
}
+ #[test]
+ fn first_store_advances_past_the_initial_generation() {
+ let handle = CatalogHandle::new();
+ assert_eq!(handle.load().generation(), Generation::INITIAL);
+ handle.store(FilterCatalog::from_teams([(
+ TeamId(7),
+ team_with_one_behavioral(),
+ )]));
+ assert_eq!(handle.load().generation(), Generation(1));
+ }
+
+ #[test]
+ fn no_op_refresh_keeps_the_generation_and_a_content_change_bumps_it() {
+ let handle = CatalogHandle::new();
+ handle.store(FilterCatalog::from_teams([(
+ TeamId(7),
+ team_with_one_behavioral(),
+ )]));
+ let gen1 = handle.load().generation();
+
+ // Same condition set → same signature → generation unchanged (the memo survives the refresh).
+ handle.store(FilterCatalog::from_teams([(
+ TeamId(7),
+ team_with_one_behavioral(),
+ )]));
+ assert_eq!(
+ handle.load().generation(),
+ gen1,
+ "a no-op refresh reuses the generation",
+ );
+
+ // A different condition hash → signature changes → generation advances (memo invalidates).
+ handle.store(FilterCatalog::from_teams([(
+ TeamId(7),
+ team_with_one_person(),
+ )]));
+ assert_ne!(
+ handle.load().generation(),
+ gen1,
+ "a content change bumps the generation",
+ );
+ }
+
+ #[test]
+ fn catalog_signature_ignores_team_iteration_order() {
+ let a = FilterCatalog::from_teams([
+ (TeamId(7), team_with_one_behavioral()),
+ (TeamId(8), team_with_one_person()),
+ ]);
+ let b = FilterCatalog::from_teams([
+ (TeamId(8), team_with_one_person()),
+ (TeamId(7), team_with_one_behavioral()),
+ ]);
+ assert_eq!(catalog_signature(&a), catalog_signature(&b));
+ }
+
#[test]
fn next_interval_without_jitter_is_exact() {
let interval = Duration::from_secs(300);
diff --git a/rust/cohort-stream-processor/src/filters/mod.rs b/rust/cohort-stream-processor/src/filters/mod.rs
index 8aa3db496081..5c2164b573e3 100644
--- a/rust/cohort-stream-processor/src/filters/mod.rs
+++ b/rust/cohort-stream-processor/src/filters/mod.rs
@@ -11,7 +11,7 @@ use thiserror::Error;
pub use leaf_classifier::{classify_leaf, LeafClass, LeafDropReason};
pub use loader::{build_catalog_from_rows, load_realtime_cohorts, CohortRow, REALTIME_COHORTS_SQL};
-pub use manager::{run_refresh_loop, CatalogHandle, CatalogStats, FilterCatalog};
+pub use manager::{run_refresh_loop, CatalogHandle, CatalogStats, FilterCatalog, Generation};
pub use reverse_index::{TeamFilters, TeamFiltersBuilder};
pub use tree::{
parse_cohort_tree, BehavioralLeafConfig, BehavioralValue, BoolOp, CohortLeaf,
diff --git a/rust/cohort-stream-processor/src/filters/reverse_index.rs b/rust/cohort-stream-processor/src/filters/reverse_index.rs
index 68dc43e6dd02..33d05bfcb223 100644
--- a/rust/cohort-stream-processor/src/filters/reverse_index.rs
+++ b/rust/cohort-stream-processor/src/filters/reverse_index.rs
@@ -48,6 +48,9 @@ pub struct TeamFilters {
/// conditionHashes whose leaves are behavioral. Disjoint from person-property conditions.
pub behavioral_conditions: HashSet<[u8; 16]>,
pub person_property_conditions: HashSet<[u8; 16]>,
+ /// `person_property_conditions` sorted — the stable bit positions the person memo indexes by, so
+ /// an entry's bits stay aligned across no-op refreshes.
+ pub person_conditions_ordered: Vec<[u8; 16]>,
/// `LeafStateKey → [CohortId]` for single-leaf cohorts.
pub by_lsk_to_single_leaf_cohorts: HashMap<LeafStateKey, Vec<CohortId>>,
/// `LeafStateKey → [CohortId]` for `Stage2Composable` cohorts.
@@ -74,6 +77,7 @@ impl Default for TeamFilters {
by_lsk: HashMap::new(),
behavioral_conditions: HashSet::new(),
person_property_conditions: HashSet::new(),
+ person_conditions_ordered: Vec::new(),
by_lsk_to_single_leaf_cohorts: HashMap::new(),
by_lsk_to_composable_cohorts: HashMap::new(),
by_referenced_cohort: HashMap::new(),
@@ -247,6 +251,10 @@ impl TeamFiltersBuilder {
cohorts.sort_unstable();
}
+ let mut person_conditions_ordered: Vec<[u8; 16]> =
+ person_property_conditions.iter().copied().collect();
+ person_conditions_ordered.sort_unstable();
+
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),
@@ -255,6 +263,7 @@ impl TeamFiltersBuilder {
by_lsk,
behavioral_conditions,
person_property_conditions,
+ person_conditions_ordered,
by_lsk_to_single_leaf_cohorts,
by_lsk_to_composable_cohorts,
by_referenced_cohort,
@@ -757,6 +766,40 @@ mod tests {
.is_disjoint(&frozen.person_property_conditions));
}
+ #[test]
+ fn person_conditions_ordered_is_the_sorted_person_condition_set() {
+ let mut other_person = person_leaf();
+ other_person
+ .as_object_mut()
+ .unwrap()
+ .insert("conditionHash".to_string(), json!("0011223344556677"));
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![
+ person_leaf(),
+ other_person,
+ behavioral_performed_event(7),
+ ]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ let mut expected: Vec<[u8; 16]> =
+ frozen.person_property_conditions.iter().copied().collect();
+ expected.sort_unstable();
+ assert_eq!(frozen.person_conditions_ordered, expected);
+ assert!(
+ frozen
+ .person_conditions_ordered
+ .windows(2)
+ .all(|w| w[0] < w[1]),
+ "the order is strictly ascending and carries no behavioral hash",
+ );
+ }
+
#[test]
fn freeze_recurses_into_nested_groups() {
let mut builder = TeamFiltersBuilder::default();
diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rs
index 8e2ccae7e86c..1623ac39ec41 100644
--- a/rust/cohort-stream-processor/src/main.rs
+++ b/rust/cohort-stream-processor/src/main.rs
@@ -223,6 +223,8 @@ async fn async_main(config: Config) -> Result<()> {
if config.durable_restore_enabled {
dispatcher.enable_durable_restore();
}
+ // Person-memo config, likewise set before any worker spawns.
+ dispatcher.set_person_memo_config(config.person_memo_config());
let (context, rebalance_rx) = CohortConsumerContext::new(dispatcher.clone());
let stream_consumer: StreamConsumer<CohortConsumerContext> = config
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
index db08338a77e0..10f8c41207c4 100644
--- a/rust/cohort-stream-processor/src/observability/metrics.rs
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -157,6 +157,11 @@ 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";
+/// Condition evaluations skipped because the result was already known, labelled by `reason`
+/// (`person_memo_hit`) (counter).
+pub const STAGE1_CONDITIONS_SKIPPED: &str = "stage1_conditions_skipped_total";
+/// Person-property memo lookups, labelled by `result` (`hit`|`miss`) (counter).
+pub const STAGE1_PERSON_MEMO: &str = "stage1_person_memo_total";
/// Leaf membership flips emitted, labelled by `kind` (counter).
pub const STAGE1_TRANSITIONS: &str = "stage1_transitions_total";
/// `cf_stage1` records written, labelled by `variant` (counter).
diff --git a/rust/cohort-stream-processor/src/workers/event_path.rs b/rust/cohort-stream-processor/src/workers/event_path.rs
index 1ba867641f33..db087f9e4878 100644
--- a/rust/cohort-stream-processor/src/workers/event_path.rs
+++ b/rust/cohort-stream-processor/src/workers/event_path.rs
@@ -12,12 +12,12 @@ use uuid::Uuid;
use crate::consumers::events::CohortStreamEvent;
use crate::filters::reverse_index::TeamFilters;
-use crate::filters::TeamId;
+use crate::filters::{Generation, TeamId};
use crate::hogvm::{build_behavioral_globals, build_person_property_globals, CohortEvaluator};
use crate::observability::metrics::{
- STAGE1_ARGMAX_STALE, STAGE1_CONDITIONS_EVALUATED, STAGE1_PERSON_INDEX_APPENDS,
- STAGE1_REPLAY_SKIPPED, STAGE1_STATE_DECODE_ERROR, STAGE1_STATE_WRITES,
- STAGE1_UNSUPPORTED_VARIANT_SKIPPED,
+ STAGE1_ARGMAX_STALE, STAGE1_CONDITIONS_EVALUATED, STAGE1_CONDITIONS_SKIPPED,
+ STAGE1_PERSON_INDEX_APPENDS, STAGE1_REPLAY_SKIPPED, STAGE1_STATE_DECODE_ERROR,
+ STAGE1_STATE_WRITES, STAGE1_UNSUPPORTED_VARIANT_SKIPPED,
};
use crate::stage1::bucket_tz::{
daily_bucket_len, day_idx_in_tz, now_day_for_window, window_start_for_now,
@@ -33,6 +33,7 @@ use crate::stage1::state::{
use crate::stage1::time::clickhouse_timestamp_to_millis;
use crate::stage1::transition::{LeafTransition, TransitionKind};
use crate::store::{CohortStore, IndexOp, PersonIndexKey, StoreError};
+use crate::workers::person_memo::{ConditionBitset, Lookup, PersonKey, PersonMemo, Receipt};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SkipReason {
@@ -120,11 +121,34 @@ struct PendingWrite {
variant: StateVariant,
}
+/// Fold one event with the person memo disabled (full person sweep). The memoizing entry is
+/// [`process_event_with_memo`].
pub fn process_event(
partition_id: u16,
store: &CohortStore,
filters: &TeamFilters,
event: &CohortStreamEvent,
+) -> Result<EventOutcome, StoreError> {
+ process_event_with_memo(
+ partition_id,
+ store,
+ filters,
+ Generation::INITIAL,
+ event,
+ &mut PersonMemo::disabled(),
+ )
+}
+
+/// Fold one event, consulting the per-worker person memo. A hit answers the person conditions from
+/// cache — no JSON parse, no HogVM eval — keyed on `generation` plus a fingerprint of the raw
+/// `person_properties`.
+pub fn process_event_with_memo(
+ partition_id: u16,
+ store: &CohortStore,
+ filters: &TeamFilters,
+ generation: Generation,
+ event: &CohortStreamEvent,
+ memo: &mut PersonMemo,
) -> Result<EventOutcome, StoreError> {
if event.person_id.is_empty() {
return Ok(EventOutcome::skipped(SkipReason::NullPersonId));
@@ -145,6 +169,8 @@ pub fn process_event(
return Ok(EventOutcome::skipped(SkipReason::NoConditions));
}
+ // Build globals and resolve the person plan before any evaluation, so a malformed payload skips
+ // the event before any condition runs. A memo hit resolves without parsing person globals.
let behavioral_globals = if has_behavioral {
match build_behavioral_globals(event) {
Ok(globals) => Some(globals),
@@ -153,23 +179,20 @@ pub fn process_event(
} else {
None
};
- let person_active = has_person
- && event
- .person_properties
- .as_deref()
- .is_some_and(|raw| !raw.is_empty());
- let person_globals = if person_active {
- match build_person_property_globals(event) {
- Ok(globals) => Some(globals),
- Err(_) => return Ok(EventOutcome::skipped(SkipReason::GlobalsParseError)),
- }
- } else {
- None
+ let person = match resolve_person(filters, event, person_id, generation, memo) {
+ Ok(person) => person,
+ Err(skip) => return Ok(EventOutcome::skipped(skip)),
};
// One evaluator reused across the event's conditions: globals set once per kind, program per condition.
let mut evaluator = CohortEvaluator::new();
- let applies = collect_applies(filters, &mut evaluator, behavioral_globals, person_globals);
+ let mut applies: Vec<Apply> = Vec::new();
+ if let Some(globals) = behavioral_globals {
+ evaluator.set_globals(globals);
+ collect_behavioral_applies(filters, &mut evaluator, &mut applies);
+ }
+ collect_person_applies(filters, &mut evaluator, person, memo, &mut applies);
+
if applies.is_empty() {
return Ok(EventOutcome::processed(Vec::new(), Vec::new(), 0));
}
@@ -309,64 +332,84 @@ pub(crate) fn schedule_deadline(state: &Stage1State) -> Option<i64> {
state.eviction_deadline().filter(|&d| d != i64::MAX)
}
-fn collect_applies(
- filters: &TeamFilters,
- evaluator: &mut CohortEvaluator,
- behavioral_globals: Option<serde_json::Value>,
- person_globals: Option<serde_json::Value>,
-) -> Vec<Apply> {
- let mut applies = Vec::new();
+/// How the event's person conditions will be answered, resolved before any evaluation.
+enum PersonResolution {
+ /// No person conditions, or empty `person_properties`.
+ Inactive,
+ /// Memo hit: reuse the cached results (globals never parsed).
+ Cached(ConditionBitset),
+ /// Evaluate `globals`, then cache the results under `receipt`.
+ Evaluate {
+ globals: serde_json::Value,
+ receipt: Receipt,
+ },
+}
- if let Some(globals) = behavioral_globals {
- evaluator.set_globals(globals);
- for &hash in &filters.behavioral_conditions {
- let Some(bytecode) = filters.by_condition_to_bytecode.get(&hash) else {
- continue;
- };
- counter!(STAGE1_CONDITIONS_EVALUATED, "kind" => "behavioral").increment(1);
- if !evaluator.evaluate(Arc::clone(bytecode)) {
- continue;
- }
- let Some(lsks) = filters.by_condition_to_lsk.get(&hash) else {
- continue;
- };
- for &lsk in lsks {
- match filters.by_lsk.get(&lsk).map(|meta| meta.variant) {
- Some(
- StateVariant::BehavioralSingle
- | StateVariant::BehavioralDailyBuckets
- | StateVariant::BehavioralCompressedHistory,
- ) => {
- applies.push(Apply::Behavioral {
- lsk,
- condition_hash: hash,
- });
- }
- Some(other) => {
- counter!(STAGE1_UNSUPPORTED_VARIANT_SKIPPED, "variant" => other.as_str())
- .increment(1);
- }
- None => {}
- }
- }
+/// The raw `person_properties` iff there is a person condition and the payload is non-empty.
+fn active_person_props<'a>(filters: &TeamFilters, event: &'a CohortStreamEvent) -> Option<&'a str> {
+ if filters.person_property_conditions.is_empty() {
+ return None;
+ }
+ event
+ .person_properties
+ .as_deref()
+ .filter(|raw| !raw.is_empty())
+}
+
+/// Decide how to answer the person conditions. The only error is a malformed-props parse failure on
+/// the eval path, which the caller turns into a `GlobalsParseError` skip.
+fn resolve_person(
+ filters: &TeamFilters,
+ event: &CohortStreamEvent,
+ person_id: Uuid,
+ generation: Generation,
+ memo: &mut PersonMemo,
+) -> Result<PersonResolution, SkipReason> {
+ let Some(raw) = active_person_props(filters, event) else {
+ return Ok(PersonResolution::Inactive);
+ };
+ let key = PersonKey {
+ team: TeamId(event.team_id),
+ person: person_id,
+ };
+ match memo.probe(key, generation, raw) {
+ Lookup::Hit(results) => Ok(PersonResolution::Cached(results)),
+ Lookup::Miss(receipt) => {
+ let globals =
+ build_person_property_globals(event).map_err(|_| SkipReason::GlobalsParseError)?;
+ Ok(PersonResolution::Evaluate { globals, receipt })
}
}
+}
- if let Some(globals) = person_globals {
- evaluator.set_globals(globals);
- for &hash in &filters.person_property_conditions {
- let Some(bytecode) = filters.by_condition_to_bytecode.get(&hash) else {
- continue;
- };
- counter!(STAGE1_CONDITIONS_EVALUATED, "kind" => "person_property").increment(1);
- let matches = evaluator.evaluate(Arc::clone(bytecode));
- let lsk = LeafStateKey::for_person_property(&hash);
+/// Evaluate every behavioral condition against the set globals, pushing an `Apply::Behavioral` per
+/// matching leaf.
+fn collect_behavioral_applies(
+ filters: &TeamFilters,
+ evaluator: &mut CohortEvaluator,
+ applies: &mut Vec<Apply>,
+) {
+ for &hash in &filters.behavioral_conditions {
+ let Some(bytecode) = filters.by_condition_to_bytecode.get(&hash) else {
+ continue;
+ };
+ counter!(STAGE1_CONDITIONS_EVALUATED, "kind" => "behavioral").increment(1);
+ if !evaluator.evaluate(Arc::clone(bytecode)) {
+ continue;
+ }
+ let Some(lsks) = filters.by_condition_to_lsk.get(&hash) else {
+ continue;
+ };
+ for &lsk in lsks {
match filters.by_lsk.get(&lsk).map(|meta| meta.variant) {
- Some(StateVariant::PersonProperty) => {
- applies.push(Apply::Person {
+ Some(
+ StateVariant::BehavioralSingle
+ | StateVariant::BehavioralDailyBuckets
+ | StateVariant::BehavioralCompressedHistory,
+ ) => {
+ applies.push(Apply::Behavioral {
lsk,
condition_hash: hash,
- matches,
});
}
Some(other) => {
@@ -377,8 +420,90 @@ fn collect_applies(
}
}
}
+}
- applies
+/// Push person applies for a resolved plan. The cached-read and fresh-eval paths produce the
+/// identical `Apply` multiset.
+fn collect_person_applies(
+ filters: &TeamFilters,
+ evaluator: &mut CohortEvaluator,
+ person: PersonResolution,
+ memo: &mut PersonMemo,
+ applies: &mut Vec<Apply>,
+) {
+ match person {
+ PersonResolution::Inactive => {}
+ PersonResolution::Cached(cached) => {
+ read_person_conditions_cached(filters, &cached, applies);
+ }
+ PersonResolution::Evaluate { globals, receipt } => {
+ evaluator.set_globals(globals);
+ let results = eval_person_conditions(filters, evaluator, applies);
+ memo.store(receipt, results);
+ }
+ }
+}
+
+/// Memo miss: evaluate the person conditions in stable order, recording results into a bitset for
+/// the caller to cache.
+fn eval_person_conditions(
+ filters: &TeamFilters,
+ evaluator: &mut CohortEvaluator,
+ applies: &mut Vec<Apply>,
+) -> ConditionBitset {
+ let mut results = ConditionBitset::zeros(filters.person_conditions_ordered.len());
+ for (idx, &hash) in filters.person_conditions_ordered.iter().enumerate() {
+ let Some(bytecode) = filters.by_condition_to_bytecode.get(&hash) else {
+ continue;
+ };
+ counter!(STAGE1_CONDITIONS_EVALUATED, "kind" => "person_property").increment(1);
+ let matches = evaluator.evaluate(Arc::clone(bytecode));
+ if matches {
+ results.set(idx);
+ }
+ push_person_apply(filters, hash, matches, applies);
+ }
+ results
+}
+
+/// Memo hit: push applies from the cached bits. The bytecode-presence skip mirrors the eval path so
+/// the `Apply` multiset matches a miss.
+fn read_person_conditions_cached(
+ filters: &TeamFilters,
+ cached: &ConditionBitset,
+ applies: &mut Vec<Apply>,
+) {
+ for (idx, &hash) in filters.person_conditions_ordered.iter().enumerate() {
+ if !filters.by_condition_to_bytecode.contains_key(&hash) {
+ continue;
+ }
+ counter!(STAGE1_CONDITIONS_SKIPPED, "reason" => "person_memo_hit").increment(1);
+ push_person_apply(filters, hash, cached.get(idx), applies);
+ }
+}
+
+/// Push one person condition's `Apply` behind the catalog variant guard. Shared by all three person
+/// paths so the guard is identical across them.
+fn push_person_apply(
+ filters: &TeamFilters,
+ hash: [u8; 16],
+ matches: bool,
+ applies: &mut Vec<Apply>,
+) {
+ let lsk = LeafStateKey::for_person_property(&hash);
+ match filters.by_lsk.get(&lsk).map(|meta| meta.variant) {
+ Some(StateVariant::PersonProperty) => {
+ applies.push(Apply::Person {
+ lsk,
+ condition_hash: hash,
+ matches,
+ });
+ }
+ Some(other) => {
+ counter!(STAGE1_UNSUPPORTED_VARIANT_SKIPPED, "variant" => other.as_str()).increment(1);
+ }
+ None => {}
+ }
}
/// Fold a behavioral match into a single-bit leaf. Never emits `Left` (match is never cleared).
diff --git a/rust/cohort-stream-processor/src/workers/mod.rs b/rust/cohort-stream-processor/src/workers/mod.rs
index 59bf64ad3b0d..3cfa68a77fb7 100644
--- a/rust/cohort-stream-processor/src/workers/mod.rs
+++ b/rust/cohort-stream-processor/src/workers/mod.rs
@@ -4,16 +4,18 @@ pub mod cascade_path;
pub mod event_path;
pub mod merge_gc;
pub mod merge_path;
+pub mod person_memo;
pub mod stage2_gc;
pub mod stage2_path;
pub mod sweep_callback;
pub mod worker;
-pub use event_path::{process_event, EventOutcome, SkipReason};
+pub use event_path::{process_event, process_event_with_memo, EventOutcome, SkipReason};
pub use merge_gc::{handle_merge_gc, MergeGcCursor};
pub use merge_path::{
CascadeConfig, MergeWorkerDeps, TransferRetryPolicy, DEFAULT_MERGE_GC_SCAN_LIMIT,
};
+pub use person_memo::{PersonMemo, PersonMemoConfig};
pub use stage2_gc::{handle_stage2_orphan_gc, Stage2GcCursor};
pub use stage2_path::compose_stage2;
pub use worker::Stage1Worker;
diff --git a/rust/cohort-stream-processor/src/workers/person_memo.rs b/rust/cohort-stream-processor/src/workers/person_memo.rs
new file mode 100644
index 000000000000..59ea15af7f6c
--- /dev/null
+++ b/rust/cohort-stream-processor/src/workers/person_memo.rs
@@ -0,0 +1,294 @@
+//! Per-worker memoization of person-property condition results.
+//!
+//! A person-property leaf's result is a pure function of `(catalog generation, person_properties)`:
+//! the person globals carry no clock and the STL has no `now()`. So a person's per-condition
+//! `matches` bits can be cached and reused while its raw `person_properties` are unchanged, skipping
+//! the JSON parse and the HogVM evaluations. A catalog change bumps the generation, invalidating
+//! every entry.
+
+use std::num::NonZeroUsize;
+
+use lru::LruCache;
+use metrics::counter;
+use sha2::{Digest, Sha256};
+use uuid::Uuid;
+
+use crate::filters::{Generation, TeamId};
+use crate::observability::metrics::STAGE1_PERSON_MEMO;
+
+#[derive(Clone, Copy, Debug)]
+pub struct PersonMemoConfig {
+ pub enabled: bool,
+ pub capacity: usize,
+}
+
+impl PersonMemoConfig {
+ pub const DISABLED: Self = Self {
+ enabled: false,
+ capacity: 0,
+ };
+}
+
+/// `team` keeps persons from different teams distinct on a shared worker.
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+pub(crate) struct PersonKey {
+ pub team: TeamId,
+ pub person: Uuid,
+}
+
+/// A cached result's validity: an entry is current iff its stamp equals the lookup's, so `==` is the
+/// invalidation rule. The generation also guarantees the bits align with the current
+/// `person_conditions_ordered`.
+#[derive(Clone, Copy, PartialEq, Eq)]
+struct Stamp {
+ generation: Generation,
+ fingerprint: PropsFingerprint,
+}
+
+/// 128 bits of SHA-256 over the raw props — collision-negligible, and computable without a JSON parse.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+struct PropsFingerprint(u128);
+
+impl PropsFingerprint {
+ fn of(raw: &str) -> Self {
+ let digest = Sha256::digest(raw.as_bytes());
+ Self(u128::from_le_bytes(
+ digest[..16].try_into().expect("SHA-256 yields 32 bytes"),
+ ))
+ }
+}
+
+struct MemoEntry {
+ stamp: Stamp,
+ results: ConditionBitset,
+}
+
+/// Person-condition results, one bit per position in `person_conditions_ordered`.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct ConditionBitset {
+ bits: Box<[u8]>,
+ len: usize,
+}
+
+impl ConditionBitset {
+ pub(crate) fn zeros(len: usize) -> Self {
+ Self {
+ bits: vec![0u8; len.div_ceil(8)].into_boxed_slice(),
+ len,
+ }
+ }
+
+ pub(crate) fn set(&mut self, idx: usize) {
+ debug_assert!(idx < self.len);
+ self.bits[idx / 8] |= 1 << (idx % 8);
+ }
+
+ pub(crate) fn get(&self, idx: usize) -> bool {
+ debug_assert!(idx < self.len);
+ self.bits[idx / 8] & (1 << (idx % 8)) != 0
+ }
+}
+
+/// The outcome of [`PersonMemo::probe`].
+pub(crate) enum Lookup {
+ /// The cached results are current; reuse them.
+ Hit(ConditionBitset),
+ /// Evaluate, then redeem the [`Receipt`] with the fresh results.
+ Miss(Receipt),
+}
+
+/// Proof of a miss carrying the `(key, stamp)` to cache under, so [`PersonMemo::store`] can only
+/// write what was probed. `None` when the memo is disabled, making the write a no-op.
+pub(crate) struct Receipt(Option<(PersonKey, Stamp)>);
+
+/// `None` cache means disabled (no allocation).
+pub struct PersonMemo {
+ cache: Option<LruCache<PersonKey, MemoEntry>>,
+}
+
+impl PersonMemo {
+ pub fn new(config: PersonMemoConfig) -> Self {
+ let cache = config.enabled.then(|| {
+ // Clamp so a misconfigured `0` still caches one entry rather than panicking.
+ LruCache::new(NonZeroUsize::new(config.capacity.max(1)).expect("capacity is >= 1"))
+ });
+ Self { cache }
+ }
+
+ pub fn disabled() -> Self {
+ Self { cache: None }
+ }
+
+ /// Consult the memo for `key` at the current `generation` and props. A stale, absent, or disabled
+ /// entry is a [`Lookup::Miss`]; the fingerprint is computed only when enabled, so the kill-switch
+ /// costs no hash.
+ pub(crate) fn probe(&mut self, key: PersonKey, generation: Generation, raw: &str) -> Lookup {
+ let Some(cache) = self.cache.as_mut() else {
+ return Lookup::Miss(Receipt(None));
+ };
+ let stamp = Stamp {
+ generation,
+ fingerprint: PropsFingerprint::of(raw),
+ };
+ if let Some(entry) = cache.get(&key) {
+ if entry.stamp == stamp {
+ counter!(STAGE1_PERSON_MEMO, "result" => "hit").increment(1);
+ return Lookup::Hit(entry.results.clone());
+ }
+ }
+ counter!(STAGE1_PERSON_MEMO, "result" => "miss").increment(1);
+ Lookup::Miss(Receipt(Some((key, stamp))))
+ }
+
+ /// Cache `results` under a miss receipt; a no-op when the receipt came from a disabled memo.
+ pub(crate) fn store(&mut self, receipt: Receipt, results: ConditionBitset) {
+ if let (Some(cache), Receipt(Some((key, stamp)))) = (self.cache.as_mut(), receipt) {
+ cache.put(key, MemoEntry { stamp, results });
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn config(capacity: usize) -> PersonMemoConfig {
+ PersonMemoConfig {
+ enabled: true,
+ capacity,
+ }
+ }
+
+ fn key(team: i32, person: u128) -> PersonKey {
+ PersonKey {
+ team: TeamId(team),
+ person: Uuid::from_u128(person),
+ }
+ }
+
+ /// Probe (asserting a miss) and cache `results` under the returned receipt.
+ fn seed(
+ memo: &mut PersonMemo,
+ key: PersonKey,
+ gen: Generation,
+ raw: &str,
+ results: ConditionBitset,
+ ) {
+ let Lookup::Miss(receipt) = memo.probe(key, gen, raw) else {
+ panic!("expected a miss for a fresh entry");
+ };
+ memo.store(receipt, results);
+ }
+
+ fn hit_bits(
+ memo: &mut PersonMemo,
+ key: PersonKey,
+ gen: Generation,
+ raw: &str,
+ ) -> ConditionBitset {
+ match memo.probe(key, gen, raw) {
+ Lookup::Hit(bits) => bits,
+ Lookup::Miss(_) => panic!("expected a hit"),
+ }
+ }
+
+ #[test]
+ fn bitset_roundtrips_each_bit_and_packs_to_ceil_div_8() {
+ let mut bits = ConditionBitset::zeros(10);
+ assert_eq!(bits.bits.len(), 2, "10 bits pack into 2 bytes");
+ for idx in [0, 3, 7, 8, 9] {
+ bits.set(idx);
+ }
+ for idx in 0..10 {
+ assert_eq!(bits.get(idx), [0, 3, 7, 8, 9].contains(&idx), "bit {idx}");
+ }
+ }
+
+ #[test]
+ fn zero_length_bitset_allocates_nothing() {
+ assert!(ConditionBitset::zeros(0).bits.is_empty());
+ }
+
+ #[test]
+ fn disabled_memo_never_caches() {
+ let mut memo = PersonMemo::disabled();
+ seed(
+ &mut memo,
+ key(7, 1),
+ Generation(1),
+ "p",
+ ConditionBitset::zeros(3),
+ );
+ assert!(matches!(
+ memo.probe(key(7, 1), Generation(1), "p"),
+ Lookup::Miss(_)
+ ));
+ }
+
+ #[test]
+ fn hit_requires_matching_generation_props_and_team() {
+ let mut memo = PersonMemo::new(config(8));
+ let mut results = ConditionBitset::zeros(2);
+ results.set(1);
+ seed(
+ &mut memo,
+ key(7, 1),
+ Generation(5),
+ "props-A",
+ results.clone(),
+ );
+
+ assert_eq!(
+ hit_bits(&mut memo, key(7, 1), Generation(5), "props-A"),
+ results
+ );
+ assert!(matches!(
+ memo.probe(key(7, 1), Generation(6), "props-A"),
+ Lookup::Miss(_)
+ ));
+ assert!(matches!(
+ memo.probe(key(7, 1), Generation(5), "props-B"),
+ Lookup::Miss(_)
+ ));
+ assert!(matches!(
+ memo.probe(key(8, 1), Generation(5), "props-A"),
+ Lookup::Miss(_)
+ ));
+ }
+
+ #[test]
+ fn a_new_generation_overwrites_the_stale_entry() {
+ let mut memo = PersonMemo::new(config(8));
+ seed(
+ &mut memo,
+ key(7, 1),
+ Generation(5),
+ "p",
+ ConditionBitset::zeros(2),
+ );
+ let mut fresh = ConditionBitset::zeros(2);
+ fresh.set(0);
+ seed(&mut memo, key(7, 1), Generation(6), "p", fresh.clone());
+ assert_eq!(hit_bits(&mut memo, key(7, 1), Generation(6), "p"), fresh);
+ }
+
+ #[test]
+ fn lru_evicts_the_least_recently_used_entry() {
+ let mut memo = PersonMemo::new(config(2));
+ let g = Generation(1);
+ seed(&mut memo, key(7, 1), g, "a", ConditionBitset::zeros(1));
+ seed(&mut memo, key(7, 2), g, "b", ConditionBitset::zeros(1));
+ // Touch entry 1 so entry 2 becomes the eviction victim.
+ assert!(matches!(memo.probe(key(7, 1), g, "a"), Lookup::Hit(_)));
+ seed(&mut memo, key(7, 3), g, "c", ConditionBitset::zeros(1));
+ assert!(matches!(memo.probe(key(7, 2), g, "b"), Lookup::Miss(_)));
+ assert!(matches!(memo.probe(key(7, 1), g, "a"), Lookup::Hit(_)));
+ assert!(matches!(memo.probe(key(7, 3), g, "c"), Lookup::Hit(_)));
+ }
+
+ #[test]
+ fn fingerprint_is_stable_and_sensitive() {
+ assert_eq!(PropsFingerprint::of("x"), PropsFingerprint::of("x"));
+ assert_ne!(PropsFingerprint::of("x"), PropsFingerprint::of("y"));
+ }
+}
diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rs
index 343f1b5c3b56..73ead3961786 100644
--- a/rust/cohort-stream-processor/src/workers/worker.rs
+++ b/rust/cohort-stream-processor/src/workers/worker.rs
@@ -41,9 +41,10 @@ use crate::stage1::transition::{LeafTransition, TransitionKind};
use crate::store::{CohortStore, IndexOp, PersonIndexKey};
use crate::sweep::EvictionQueue;
use crate::workers::cascade_path::handle_cascade;
-use crate::workers::event_path::{process_event, schedule_deadline, SkipReason};
+use crate::workers::event_path::{process_event_with_memo, schedule_deadline, SkipReason};
use crate::workers::merge_gc::{handle_merge_gc, MergeGcCursor};
use crate::workers::merge_path::{handle_apply, handle_merge, handle_redrive, MergeWorkerDeps};
+use crate::workers::person_memo::{PersonMemo, PersonMemoConfig};
use crate::workers::stage2_gc::{handle_stage2_orphan_gc, Stage2GcCursor};
use crate::workers::stage2_path::compose_stage2;
use crate::workers::sweep_callback::{sweep_evict, EvictionAction, SweepDropReason};
@@ -67,10 +68,35 @@ pub struct Stage1Worker {
}
impl Stage1Worker {
+ /// Spawn with the person memo disabled. The memoizing variant is [`Self::spawn_with_memo`].
+ #[allow(clippy::too_many_arguments)]
+ pub fn spawn(
+ partition_id: u16,
+ receiver: mpsc::Receiver<Vec<ShuffleMessage>>,
+ store: CohortStore,
+ catalog: Arc<CatalogHandle>,
+ sink: Arc<dyn MembershipSink>,
+ tracker: Arc<OffsetTracker>,
+ merge: Arc<MergeWorkerDeps>,
+ durable_restore: bool,
+ ) -> Self {
+ Self::spawn_with_memo(
+ partition_id,
+ receiver,
+ store,
+ catalog,
+ sink,
+ tracker,
+ merge,
+ durable_restore,
+ PersonMemoConfig::DISABLED,
+ )
+ }
+
/// When `durable_restore` is on, re-seeds the `EvictionQueue` from `cf_stage1` on spawn so a
/// dormant person's `Left` still fires after a crash-restart.
#[allow(clippy::too_many_arguments)]
- pub fn spawn(
+ pub fn spawn_with_memo(
partition_id: u16,
receiver: mpsc::Receiver<Vec<ShuffleMessage>>,
store: CohortStore,
@@ -79,6 +105,7 @@ impl Stage1Worker {
tracker: Arc<OffsetTracker>,
merge: Arc<MergeWorkerDeps>,
durable_restore: bool,
+ person_memo: PersonMemoConfig,
) -> Self {
let handle = tokio::spawn(run_worker(
partition_id,
@@ -89,6 +116,7 @@ impl Stage1Worker {
tracker,
merge,
durable_restore,
+ person_memo,
));
Self {
partition_id,
@@ -115,10 +143,13 @@ async fn run_worker(
tracker: Arc<OffsetTracker>,
merge: Arc<MergeWorkerDeps>,
durable_restore: bool,
+ person_memo: PersonMemoConfig,
) {
info!(partition_id, "stage 1 worker started");
let mut queue = EvictionQueue::<Stage1Key>::new();
+ // Reused across batches so cached results survive between events.
+ let mut person_memo = PersonMemo::new(person_memo);
// No-op for a cold partition (bloom-filtered scan finds nothing to schedule).
if durable_restore {
rebuild_eviction_queue(partition_id, &store, &mut queue).await;
@@ -149,6 +180,7 @@ async fn run_worker(
&event,
&last_updated,
merge.partition_count,
+ &mut person_memo,
);
buffer.extend(effects.changes);
for (key, deadline) in effects.schedules {
@@ -453,6 +485,7 @@ struct EventEffects {
re_keys: Vec<CohortStreamEvent>,
}
+#[allow(clippy::too_many_arguments)]
fn handle_event(
partition_id: u16,
store: &CohortStore,
@@ -460,8 +493,10 @@ fn handle_event(
event: &CohortStreamEvent,
last_updated: &str,
partition_count: u32,
+ person_memo: &mut PersonMemo,
) -> EventEffects {
let snapshot = catalog.load();
+ let generation = snapshot.generation();
let Some(team_filters) = snapshot.team(TeamId(event.team_id)) else {
counter!(STAGE1_EVENTS_SKIPPED, "reason" => SkipReason::NoTeamFilters.as_str())
.increment(1);
@@ -481,7 +516,14 @@ fn handle_event(
};
let started = Instant::now();
- let result = process_event(partition_id, store, filters, &resolved);
+ let result = process_event_with_memo(
+ partition_id,
+ store,
+ filters,
+ generation,
+ &resolved,
+ person_memo,
+ );
histogram!(STAGE1_EVENT_PROCESS_DURATION).record(started.elapsed().as_secs_f64());
match result {
@@ -1243,6 +1285,7 @@ mod tombstone_redirect_tests {
&straggler,
"ts",
COHORT_PARTITION_COUNT,
+ &mut PersonMemo::disabled(),
);
assert_eq!(effects.changes.len(), 1, "the straggler entered P_new");
@@ -1494,6 +1537,7 @@ mod tombstone_redirect_tests {
&straggler,
"ts",
COHORT_PARTITION_COUNT,
+ &mut PersonMemo::disabled(),
);
assert!(effects.changes.is_empty());
assert!(effects.schedules.is_empty());
@@ -1507,6 +1551,7 @@ mod tombstone_redirect_tests {
&re_keyed,
"ts",
COHORT_PARTITION_COUNT,
+ &mut PersonMemo::disabled(),
);
assert_eq!(effects.changes.len(), 1, "folds into P_new exactly once");
assert_eq!(effects.changes[0].person_id, p_new.to_string());
@@ -1536,6 +1581,7 @@ mod tombstone_redirect_tests {
&re_keyed,
"ts",
COHORT_PARTITION_COUNT,
+ &mut PersonMemo::disabled(),
);
assert!(dup.changes.is_empty(), "the duplicate folds zero times");
assert!(dup.re_keys.is_empty());
@@ -1560,6 +1606,7 @@ mod tombstone_redirect_tests {
&straggler,
"ts",
COHORT_PARTITION_COUNT,
+ &mut PersonMemo::disabled(),
);
assert!(effects.re_keys.is_empty(), "no re-produce at the cap");
@@ -1602,6 +1649,7 @@ mod tombstone_redirect_tests {
&event,
"ts",
COHORT_PARTITION_COUNT,
+ &mut PersonMemo::disabled(),
);
assert_eq!(effects.changes.len(), 1);
assert_eq!(effects.changes[0].person_id, alice.to_string());
diff --git a/rust/cohort-stream-processor/tests/person_memo_parity.rs b/rust/cohort-stream-processor/tests/person_memo_parity.rs
new file mode 100644
index 000000000000..35cd6d93454d
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/person_memo_parity.rs
@@ -0,0 +1,398 @@
+//! Differential parity for the person-property memo: the same event sequence with the memo ON and
+//! OFF must yield byte-identical `cf_stage1` and the same leaf transitions (a multiset — apply order
+//! is non-deterministic). Covers a hit, a property change (fingerprint miss), a generation bump
+//! (re-eval, no stale serve), an out-of-order stale event, and a second person.
+
+use std::collections::BTreeMap;
+
+use chrono_tz::UTC;
+use cohort_stream_processor::consumers::CohortStreamEvent;
+use cohort_stream_processor::filters::{
+ CatalogHandle, CohortId, FilterCatalog, Generation, TeamFilters, TeamFiltersBuilder, TeamId,
+};
+use cohort_stream_processor::partitions::{OffsetTracker, ShuffleMessage};
+use cohort_stream_processor::producer::{CaptureSink, MembershipStatus};
+use cohort_stream_processor::stage1::{LeafTransition, TransitionKind};
+use cohort_stream_processor::store::{CohortStore, StoreConfig};
+use cohort_stream_processor::workers::{
+ process_event_with_memo, EventOutcome, MergeWorkerDeps, PersonMemo, PersonMemoConfig,
+ Stage1Worker,
+};
+use serde_json::{json, Value};
+use tempfile::TempDir;
+use tokio::sync::mpsc;
+use uuid::Uuid;
+
+const TEAM: i32 = 7;
+const PARTITION: u16 = 0;
+
+// Distinct 16-byte condition hashes. `email` sorts before `plan`, so the email predicate is bit 0 in
+// both catalogs — the position a stale cross-generation serve would misread.
+const EMAIL_ALICE: &str = "emailAlice000001";
+const EMAIL_BOB: &str = "emailBob00000002";
+const PLAN_PRO: &str = "planPro000000003";
+const BEH_PAGEVIEW: &str = "pageviewbeh00004";
+
+const PROPS_PRO: &str = r#"{"email":"[email protected]","plan":"pro"}"#;
+const PROPS_FREE: &str = r#"{"email":"[email protected]","plan":"free"}"#;
+const PROPS_ENTERPRISE: &str = r#"{"email":"[email protected]","plan":"enterprise"}"#;
+const PROPS_BOB: &str = r#"{"email":"[email protected]","plan":"pro"}"#;
+
+fn person_leaf(key: &str, value: &str, hash: &str) -> Value {
+ json!({
+ "type": "person",
+ "key": key,
+ "value": value,
+ "operator": "exact",
+ "conditionHash": hash,
+ "bytecode": ["_H", 1, 32, value, 32, key, 32, "properties", 32, "person", 1, 3, 11],
+ })
+}
+
+fn behavioral_leaf(hash: &str) -> Value {
+ json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "time_value": 7,
+ "time_interval": "day",
+ "conditionHash": hash,
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ })
+}
+
+fn team_filters(values: Vec<Value>) -> TeamFilters {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(TEAM),
+ &json!({ "properties": { "type": "AND", "values": values } }),
+ )
+ .unwrap();
+ builder.freeze(UTC)
+}
+
+/// C1: alice's email, a plan, and a behavioral leaf.
+fn catalog_v1() -> TeamFilters {
+ team_filters(vec![
+ person_leaf("email", "[email protected]", EMAIL_ALICE),
+ person_leaf("plan", "pro", PLAN_PRO),
+ behavioral_leaf(BEH_PAGEVIEW),
+ ])
+}
+
+/// C2: the email predicate is flipped to bob (a *new* condition hash); plan + behavioral unchanged.
+fn catalog_v2() -> TeamFilters {
+ team_filters(vec![
+ person_leaf("email", "[email protected]", EMAIL_BOB),
+ person_leaf("plan", "pro", PLAN_PRO),
+ behavioral_leaf(BEH_PAGEVIEW),
+ ])
+}
+
+fn event(person: Uuid, props: &str, offset: i64, timestamp: &str) -> CohortStreamEvent {
+ CohortStreamEvent {
+ team_id: TEAM,
+ person_id: person.to_string(),
+ distinct_id: "d".to_string(),
+ uuid: format!("uuid-{offset}"),
+ event: "$pageview".to_string(),
+ timestamp: timestamp.to_string(),
+ properties: Some("{}".to_string()),
+ person_properties: Some(props.to_string()),
+ elements_chain: None,
+ source_offset: offset,
+ source_partition: 0,
+ redirected_from: None,
+ redirect_hops: 0,
+ }
+}
+
+fn temp_store() -> (TempDir, CohortStore) {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ (dir, store)
+}
+
+/// The partition's full `cf_stage1`, keyed by encoded key bytes (`Stage1Key` is not `Ord`). Two runs
+/// with byte-identical state produce equal maps regardless of write order.
+fn dump_stage1(store: &CohortStore) -> BTreeMap<Vec<u8>, Vec<u8>> {
+ let mut out = BTreeMap::new();
+ let mut cursor: Option<Vec<u8>> = None;
+ loop {
+ let page = store
+ .scan_stage1(PARTITION, cursor.as_deref(), 4096)
+ .unwrap();
+ if page.is_empty() {
+ break;
+ }
+ let page_len = page.len();
+ cursor = page.last().map(|(key, _)| key.encode().to_vec());
+ for (key, value) in page {
+ out.insert(key.encode().to_vec(), value);
+ }
+ if page_len < 4096 {
+ break;
+ }
+ }
+ out
+}
+
+/// Sort transitions by their debug form so two runs compare as multisets — apply order differs
+/// between the ordered (memo) and unordered (sweep) person loops, but the set is identical.
+fn sorted_transitions(transitions: &[LeafTransition]) -> Vec<LeafTransition> {
+ let mut sorted = transitions.to_vec();
+ sorted.sort_by_cached_key(|t| format!("{t:?}"));
+ sorted
+}
+
+/// Runs each event through two independent stores — memo on and memo off — and asserts parity after
+/// every step. The memo persists across the whole sequence.
+struct Parity {
+ _on_dir: TempDir,
+ _off_dir: TempDir,
+ on_store: CohortStore,
+ off_store: CohortStore,
+ on_memo: PersonMemo,
+ off_memo: PersonMemo,
+}
+
+impl Parity {
+ fn new() -> Self {
+ let (on_dir, on_store) = temp_store();
+ let (off_dir, off_store) = temp_store();
+ Self {
+ _on_dir: on_dir,
+ _off_dir: off_dir,
+ on_store,
+ off_store,
+ on_memo: PersonMemo::new(PersonMemoConfig {
+ enabled: true,
+ capacity: 16,
+ }),
+ off_memo: PersonMemo::disabled(),
+ }
+ }
+
+ /// Feed one event to both stores, assert outcome + state parity, and return the memo-on outcome.
+ fn feed(
+ &mut self,
+ filters: &TeamFilters,
+ generation: Generation,
+ event: &CohortStreamEvent,
+ label: &str,
+ ) -> EventOutcome {
+ let on = process_event_with_memo(
+ PARTITION,
+ &self.on_store,
+ filters,
+ generation,
+ event,
+ &mut self.on_memo,
+ )
+ .unwrap();
+ let off = process_event_with_memo(
+ PARTITION,
+ &self.off_store,
+ filters,
+ generation,
+ event,
+ &mut self.off_memo,
+ )
+ .unwrap();
+
+ assert_eq!(on.skipped, off.skipped, "{label}: skip reason");
+ assert_eq!(on.event_ms, off.event_ms, "{label}: event_ms");
+ assert_eq!(
+ sorted_transitions(&on.transitions),
+ sorted_transitions(&off.transitions),
+ "{label}: transitions",
+ );
+ let (mut on_sched, mut off_sched) = (on.schedules.clone(), off.schedules.clone());
+ on_sched.sort_by_key(|(key, deadline)| (key.encode(), *deadline));
+ off_sched.sort_by_key(|(key, deadline)| (key.encode(), *deadline));
+ assert_eq!(on_sched, off_sched, "{label}: schedules");
+ assert_eq!(
+ dump_stage1(&self.on_store),
+ dump_stage1(&self.off_store),
+ "{label}: cf_stage1 bytes",
+ );
+ on
+ }
+}
+
+fn transition_kinds(outcome: &EventOutcome) -> Vec<TransitionKind> {
+ let mut kinds: Vec<TransitionKind> = outcome.transitions.iter().map(|t| t.kind).collect();
+ kinds.sort_by_key(|k| matches!(k, TransitionKind::Left));
+ kinds
+}
+
+#[test]
+fn memo_matches_full_sweep_across_hit_miss_gen_bump_and_stale_events() {
+ let mut p = Parity::new();
+ let alice = Uuid::from_u128(1);
+ let bob = Uuid::from_u128(2);
+ let c1 = catalog_v1();
+ let c2 = catalog_v2();
+
+ // 1. First sighting (miss): email + plan + behavioral all match → three Entered.
+ let s1 = p.feed(
+ &c1,
+ Generation(1),
+ &event(alice, PROPS_PRO, 0, "2026-05-26 10:00:00.000000"),
+ "s1 miss",
+ );
+ assert_eq!(s1.transitions.len(), 3, "s1: three leaves entered");
+ assert!(s1
+ .transitions
+ .iter()
+ .all(|t| t.kind == TransitionKind::Entered));
+
+ // 2. Identical props (memo hit): no membership change, state advances identically.
+ let s2 = p.feed(
+ &c1,
+ Generation(1),
+ &event(alice, PROPS_PRO, 1, "2026-05-26 11:00:00.000000"),
+ "s2 hit",
+ );
+ assert!(
+ s2.transitions.is_empty(),
+ "s2: a repeat event flips nothing"
+ );
+
+ // 3. Plan changes free (fingerprint miss → re-eval): the plan leaf leaves.
+ let s3 = p.feed(
+ &c1,
+ Generation(1),
+ &event(alice, PROPS_FREE, 2, "2026-05-26 12:00:00.000000"),
+ "s3 fp miss",
+ );
+ assert_eq!(
+ transition_kinds(&s3),
+ vec![TransitionKind::Left],
+ "s3: plan left"
+ );
+
+ // 4. Catalog generation bumps and the email predicate flips to bob. The stale gen-1 entry must NOT
+ // be served: alice no longer matches the email leaf, and the plan leaf re-enters (pro again).
+ let s4 = p.feed(
+ &c2,
+ Generation(2),
+ &event(alice, PROPS_PRO, 3, "2026-05-26 13:00:00.000000"),
+ "s4 gen bump",
+ );
+ assert_eq!(
+ transition_kinds(&s4),
+ vec![TransitionKind::Entered],
+ "s4: only the plan re-enters; the flipped email leaf does not match alice",
+ );
+
+ // 5. An out-of-order, older event (enterprise plan): argMax rejects every leaf in both runs.
+ let s5 = p.feed(
+ &c2,
+ Generation(2),
+ &event(alice, PROPS_ENTERPRISE, 5, "2026-05-26 09:00:00.000000"),
+ "s5 stale",
+ );
+ assert!(s5.transitions.is_empty(), "s5: a stale event flips nothing");
+
+ // 6. A second person under the same generation: a distinct memo key, evaluated fresh (merge analog).
+ let s6 = p.feed(
+ &c2,
+ Generation(2),
+ &event(bob, PROPS_BOB, 4, "2026-05-26 14:00:00.000000"),
+ "s6 new person",
+ );
+ assert_eq!(
+ s6.transitions.len(),
+ 3,
+ "s6: bob enters email + plan + behavioral"
+ );
+ assert!(s6
+ .transitions
+ .iter()
+ .all(|t| t.kind == TransitionKind::Entered));
+}
+
+/// Drive an enter → hit → leave sequence for one person through a spawned worker, returning the
+/// membership statuses and final `cf_stage1`. The `TempDir` is returned so its store outlives the scan.
+async fn run_worker_sequence(
+ filters: TeamFilters,
+ person: Uuid,
+ memo: PersonMemoConfig,
+) -> (Vec<MembershipStatus>, BTreeMap<Vec<u8>, Vec<u8>>, TempDir) {
+ let (dir, store) = temp_store();
+ let catalog = std::sync::Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([(
+ TeamId(TEAM),
+ filters,
+ )])));
+ let sink = CaptureSink::new();
+ let tracker = std::sync::Arc::new(OffsetTracker::new());
+ let (tx, rx) = mpsc::channel(16);
+ let worker = Stage1Worker::spawn_with_memo(
+ PARTITION,
+ rx,
+ store.clone(),
+ catalog,
+ std::sync::Arc::new(sink.clone()),
+ tracker.clone(),
+ MergeWorkerDeps::capture(),
+ false,
+ memo,
+ );
+
+ let sequence = [
+ (PROPS_PRO, 0, "2026-05-26 10:00:00.000000"), // enter
+ (PROPS_PRO, 1, "2026-05-26 11:00:00.000000"), // hit, no change
+ (r#"{"email":"[email protected]"}"#, 2, "2026-05-26 12:00:00.000000"), // miss, leave
+ ];
+ for (props, offset, ts) in sequence {
+ tracker.mark_dispatched(PARTITION as i32, offset + 1);
+ tx.send(vec![ShuffleMessage::Event {
+ event: event(person, props, offset, ts),
+ cse_offset: offset,
+ }])
+ .await
+ .unwrap();
+ }
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let statuses = sink.changes().iter().map(|c| c.status).collect();
+ (statuses, dump_stage1(&store), dir)
+}
+
+/// End-to-end through a spawned worker with the memo enabled vs disabled: the membership output and
+/// `cf_stage1` must be identical across an enter → hit → leave sequence, covering `run_worker`'s memo
+/// construction and the `snapshot.generation()` threading in `handle_event`.
+#[tokio::test]
+async fn memo_enabled_worker_matches_a_disabled_worker_end_to_end() {
+ // `TeamFilters` is not `Clone`, so build it fresh for each run.
+ let single_email = || team_filters(vec![person_leaf("email", "[email protected]", EMAIL_ALICE)]);
+ let alice = Uuid::from_u128(1);
+
+ let (on_statuses, on_state, _on_dir) = run_worker_sequence(
+ single_email(),
+ alice,
+ PersonMemoConfig {
+ enabled: true,
+ capacity: 16,
+ },
+ )
+ .await;
+ let (off_statuses, off_state, _off_dir) =
+ run_worker_sequence(single_email(), alice, PersonMemoConfig::DISABLED).await;
+
+ assert_eq!(
+ on_statuses,
+ vec![MembershipStatus::Entered, MembershipStatus::Left],
+ "enabled worker: enter then leave",
+ );
+ assert_eq!(on_statuses, off_statuses, "membership output parity");
+ assert_eq!(on_state, off_state, "cf_stage1 parity");
+}