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): use multi_get_stage1 to batch reads (#67978)

Matheus Batista263a91ebc4b6
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
index 9798861e3ab9..7c0b65363fed 100644
--- a/rust/cohort-stream-processor/src/observability/metrics.rs
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -257,6 +257,9 @@ pub const STAGE1_UNSUPPORTED_VARIANT_SKIPPED: &str = "stage1_unsupported_variant
pub const STAGE1_STATE_DECODE_ERROR: &str = "stage1_state_decode_error_total";
/// End-to-end per-event processing latency in the worker (histogram, seconds).
pub const STAGE1_EVENT_PROCESS_DURATION: &str = "stage1_event_process_duration_seconds";
+/// Keys in the event's single batched Stage-1 pre-read — the reads-per-event distribution
+/// (histogram).
+pub const STAGE1_SNAPSHOT_KEYS: &str = "stage1_snapshot_keys";
/// Envelopes consumed and successfully deserialized from `cohort_stream_events` (counter).
pub const COHORT_STREAM_EVENTS_CONSUMED: &str = "cohort_stream_events_consumed_total";
diff --git a/rust/cohort-stream-processor/src/workers/event_path.rs b/rust/cohort-stream-processor/src/workers/event_path.rs
index a86a78be38aa..d826380b46d0 100644
--- a/rust/cohort-stream-processor/src/workers/event_path.rs
+++ b/rust/cohort-stream-processor/src/workers/event_path.rs
@@ -7,7 +7,7 @@
use std::collections::BTreeMap;
use std::sync::Arc;
-use metrics::counter;
+use metrics::{counter, histogram};
use uuid::Uuid;
use crate::consumers::events::CohortStreamEvent;
@@ -16,8 +16,8 @@ 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_CONDITIONS_SKIPPED,
- STAGE1_PERSON_INDEX_APPENDS, STAGE1_REPLAY_SKIPPED, STAGE1_STATE_DECODE_ERROR,
- STAGE1_STATE_WRITES, STAGE1_UNSUPPORTED_VARIANT_SKIPPED,
+ STAGE1_PERSON_INDEX_APPENDS, STAGE1_REPLAY_SKIPPED, STAGE1_SNAPSHOT_KEYS,
+ 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,
@@ -142,6 +142,33 @@ struct PendingWrite {
variant: StateVariant,
}
+/// One apply's stored state as read by the event's single batched pre-event read.
+enum PriorState {
+ /// No row: this apply is the leaf's first write.
+ Absent,
+ /// The decoded pre-event record.
+ Present(StatefulRecord),
+ /// A row exists but does not decode; the apply is skipped.
+ Corrupt,
+}
+
+impl PriorState {
+ /// Decode one `multi_get_stage1` slot. The decode error is counted here — the only place a
+ /// `Corrupt` can be born.
+ fn decode(bytes: Option<Vec<u8>>) -> Self {
+ match bytes {
+ None => Self::Absent,
+ Some(bytes) => match StatefulRecord::decode(&bytes) {
+ Ok(record) => Self::Present(record),
+ Err(_) => {
+ counter!(STAGE1_STATE_DECODE_ERROR).increment(1);
+ Self::Corrupt
+ }
+ },
+ }
+ }
+}
+
/// Fold one event with the person memo disabled (full person sweep). The memoizing entry is
/// [`process_event_with_memo`].
pub fn process_event(
@@ -231,75 +258,77 @@ pub fn process_event_with_memo(
};
let team_id = event.team_id as u64;
- let mut transitions = Vec::new();
- let mut schedules: Vec<(Stage1Key, i64)> = Vec::new();
- let mut pending = Vec::new();
-
- for apply in &applies {
- let key = Stage1Key {
+ // One batched pre-event read; all writes defer to the post-loop `write_batch`, so every apply
+ // sees the pre-event image. The batch spans exactly one event: the next event in the sub-batch
+ // must see this event's committed writes (argMax tiebreaker, replay dedup).
+ let keys: Vec<Stage1Key> = applies
+ .iter()
+ .map(|apply| Stage1Key {
partition_id,
team_id,
leaf_state_key: apply.lsk(),
person_id,
- };
+ })
+ .collect();
+ histogram!(STAGE1_SNAPSHOT_KEYS).record(keys.len() as f64);
+ let values = store.multi_get_stage1(&keys)?;
- let prev = match store.get_stage1(&key)? {
- None => None,
- Some(bytes) => match StatefulRecord::decode(&bytes) {
- Ok(record) => Some(record),
- Err(_) => {
- counter!(STAGE1_STATE_DECODE_ERROR).increment(1);
- continue;
- }
- },
+ let mut transitions = Vec::new();
+ let mut schedules: Vec<(Stage1Key, i64)> = Vec::new();
+ let mut pending = Vec::new();
+
+ // Alignment-safe zip: `multi_get_stage1` preserves input order, `None` for absent keys.
+ for ((apply, key), bytes) in applies.into_iter().zip(keys).zip(values) {
+ let (prev, first_write) = match PriorState::decode(bytes) {
+ PriorState::Absent => (None, true),
+ PriorState::Present(record) => (Some(record), false),
+ PriorState::Corrupt => continue,
};
- let first_write = prev.is_none();
let mutation = match apply {
- Apply::Behavioral { condition_hash, .. } => {
- match filters.by_lsk.get(&apply.lsk()).map(|meta| meta.variant) {
- Some(StateVariant::BehavioralDailyBuckets) => mutate_behavioral_daily(
- filters,
- apply.lsk(),
- *condition_hash,
- person_id,
- origin,
- event,
- event_ms,
- prev,
- ),
- Some(StateVariant::BehavioralCompressedHistory) => {
- mutate_behavioral_compressed(
- filters,
- apply.lsk(),
- *condition_hash,
- person_id,
- origin,
- event,
- event_ms,
- prev,
- )
- }
- _ => mutate_behavioral(
- filters,
- apply.lsk(),
- *condition_hash,
- person_id,
- origin,
- event,
- event_ms,
- prev,
- ),
- }
- }
+ Apply::Behavioral {
+ lsk,
+ condition_hash,
+ } => match filters.by_lsk.get(&lsk).map(|meta| meta.variant) {
+ Some(StateVariant::BehavioralDailyBuckets) => mutate_behavioral_daily(
+ filters,
+ lsk,
+ condition_hash,
+ person_id,
+ origin,
+ event,
+ event_ms,
+ prev,
+ ),
+ Some(StateVariant::BehavioralCompressedHistory) => mutate_behavioral_compressed(
+ filters,
+ lsk,
+ condition_hash,
+ person_id,
+ origin,
+ event,
+ event_ms,
+ prev,
+ ),
+ _ => mutate_behavioral(
+ filters,
+ lsk,
+ condition_hash,
+ person_id,
+ origin,
+ event,
+ event_ms,
+ prev,
+ ),
+ },
Apply::Person {
+ lsk,
condition_hash,
matches,
- ..
} => mutate_person(
- apply.lsk(),
- *condition_hash,
- *matches,
+ lsk,
+ condition_hash,
+ matches,
person_id,
origin,
event,
diff --git a/rust/cohort-stream-processor/tests/stage1_worker.rs b/rust/cohort-stream-processor/tests/stage1_worker.rs
index ea201fb87d45..0c3a9f4678f5 100644
--- a/rust/cohort-stream-processor/tests/stage1_worker.rs
+++ b/rust/cohort-stream-processor/tests/stage1_worker.rs
@@ -405,6 +405,100 @@ fn c1_same_hash_two_windows_get_independent_state_and_deadlines() {
assert_eq!(after_replay, advanced, "replay must not regress state");
}
+/// The batched pre-event read under a mixed read set — stored rows `[present, corrupt, absent]`
+/// across one event's applies. Pins the alignment of `multi_get` slots to applies: a hole or a
+/// decode failure in one slot must not shift a neighbour's prior state or first-write bookkeeping.
+#[test]
+fn mixed_present_corrupt_absent_read_set_stays_aligned() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![
+ (CohortId(1), cohort(vec![behavioral_leaf(7)])),
+ (
+ CohortId(2),
+ cohort(vec![behavioral_leaf_multiple(7, "gte", 1)]),
+ ),
+ (CohortId(3), cohort(vec![person_leaf()])),
+ ]);
+ let lsks = &filters.by_condition_to_lsk[&BEHAVIORAL_HASH];
+ let single_lsk = *lsks
+ .iter()
+ .find(|lsk| filters.by_lsk[*lsk].variant == StateVariant::BehavioralSingle)
+ .unwrap();
+ let daily_lsk = *lsks
+ .iter()
+ .find(|lsk| filters.by_lsk[*lsk].variant == StateVariant::BehavioralDailyBuckets)
+ .unwrap();
+ let person_lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ let alice = person(1);
+
+ // Present: a member record whose last-event ts is NEWER than the incoming event — the folded
+ // result (max) can only come from the decoded prior, never from a first write.
+ let newer_ts = "2026-05-27 12:34:56.789000";
+ let newer_ms = clickhouse_timestamp_to_millis(newer_ts).unwrap();
+ let seeded = StatefulRecord::new(
+ Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: newer_ms,
+ earliest_eviction_at_ms: start_of_day_ms_in_tz(
+ day_idx_in_tz(newer_ms, UTC) + 7 + 1,
+ UTC,
+ ),
+ },
+ AppliedOffsets::default(),
+ );
+ store
+ .write_batch(|batch| {
+ batch.put_stage1(&stage1_key(single_lsk, alice), &seeded.encode());
+ // Corrupt: undecodable bytes under the daily leaf's key. The person leaf stays absent.
+ batch.put_stage1(&stage1_key(daily_lsk, alice), b"not a record");
+ })
+ .unwrap();
+
+ let out = process_event(PARTITION_ID, &store, &filters, &event(alice, 1, 10)).unwrap();
+ assert_eq!(out.skipped, None);
+
+ // Only the absent slot first-writes: one Entered, one index append, both for exactly that leaf.
+ assert_eq!(out.transitions.len(), 1);
+ assert_eq!(out.transitions[0].leaf_state_key, person_lsk);
+ assert_eq!(out.transitions[0].kind, TransitionKind::Entered);
+ assert_eq!(
+ store.get_person_index(&person_index_key(alice)).unwrap(),
+ vec![person_lsk],
+ );
+ match state_at(&store, person_lsk, alice).unwrap() {
+ Stage1State::PersonProperty { matches, .. } => assert!(matches),
+ other => panic!("expected PersonProperty, got {other:?}"),
+ }
+
+ // The present slot folded the event into its decoded prior: the newer seeded ts survives the
+ // max, and the event's offset advanced the dedup high-water mark.
+ let record = record_at(&store, single_lsk, alice).unwrap();
+ match record.state {
+ Stage1State::BehavioralSingle {
+ has_match,
+ last_event_at_ms,
+ ..
+ } => {
+ assert!(has_match);
+ assert_eq!(
+ last_event_at_ms, newer_ms,
+ "prior state lost or misattributed",
+ );
+ }
+ other => panic!("expected BehavioralSingle, got {other:?}"),
+ }
+ assert_high_water(&record.applied_offsets, 1, 10);
+
+ // The corrupt slot is skipped, not written: the garbage stays in place.
+ assert_eq!(
+ store
+ .get_stage1(&stage1_key(daily_lsk, alice))
+ .unwrap()
+ .unwrap(),
+ b"not a record",
+ );
+}
+
#[test]
fn behavioral_deadline_tracks_newest_event_not_the_late_one() {
let (_dir, store) = temp_store();