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.

chore(cohorts): extract shared logic into cohort-core crate (#71142)

Matheus Batistad26998b2f23a
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.yml
index 7c60dcd389a0..ad7aca9059fd 100644
--- a/.github/workflows/ci-rust.yml
+++ b/.github/workflows/ci-rust.yml
@@ -134,6 +134,7 @@ jobs:
"common-metrics": 6,
"common-profiler": 51,
"common-s3": 31,
+ "cohort-core": 45,
"cyclotron-core": 17,
"cyclotron-janitor": 139,
"cyclotron-node": 31,
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 75b58454d87c..f1e34632ccb6 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2178,6 +2178,25 @@ version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7ee2cfacbd29706479902b06d75ad8f1362900836aa32799eabc7e004bfd854"
+[[package]]
+name = "cohort-core"
+version = "0.1.0"
+dependencies = [
+ "chrono",
+ "chrono-tz",
+ "dashmap 6.1.0",
+ "hogvm",
+ "metrics",
+ "petgraph 0.8.3",
+ "serde",
+ "serde_json",
+ "sha2",
+ "sqlx",
+ "thiserror 2.0.18",
+ "tracing",
+ "uuid",
+]
+
[[package]]
name = "cohort-event-shuffler"
version = "0.1.0"
@@ -2219,6 +2238,7 @@ dependencies = [
"axum 0.7.9",
"chrono",
"chrono-tz",
+ "cohort-core",
"common-alloc",
"common-database",
"common-kafka",
@@ -2227,12 +2247,10 @@ dependencies = [
"dashmap 6.1.0",
"envconfig",
"futures",
- "hogvm",
"lifecycle",
"metrics",
"metrics-exporter-prometheus",
"object_store",
- "petgraph 0.8.3",
"rand 0.8.5",
"rdkafka",
"rocksdb",
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 07e8cfbb214b..dbfb2e11bb9f 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -7,6 +7,7 @@ members = [
"capture",
"capture-load-gen",
"capture-logs",
+ "cohort-core",
"cohort-event-shuffler",
"cohort-stream-processor",
"common/alloc",
diff --git a/rust/cohort-core/Cargo.toml b/rust/cohort-core/Cargo.toml
new file mode 100644
index 000000000000..7fe25c3cb9c8
--- /dev/null
+++ b/rust/cohort-core/Cargo.toml
@@ -0,0 +1,22 @@
+[package]
+name = "cohort-core"
+version = "0.1.0"
+edition = "2021"
+
+[lints]
+workspace = true
+
+[dependencies]
+chrono = { workspace = true }
+chrono-tz = { workspace = true }
+dashmap = { workspace = true }
+hogvm = { path = "../common/hogvm" }
+metrics = { workspace = true }
+petgraph = "0.8"
+serde = { workspace = true }
+serde_json = { workspace = true }
+sha2 = { workspace = true }
+sqlx = { workspace = true }
+thiserror = { workspace = true }
+tracing = { workspace = true }
+uuid = { workspace = true }
diff --git a/rust/cohort-stream-processor/src/stage1/bucket_tz.rs b/rust/cohort-core/src/bucket_tz.rs
similarity index 86%
rename from rust/cohort-stream-processor/src/stage1/bucket_tz.rs
rename to rust/cohort-core/src/bucket_tz.rs
index 0004d2356631..dd69c90bcbfd 100644
--- a/rust/cohort-stream-processor/src/stage1/bucket_tz.rs
+++ b/rust/cohort-core/src/bucket_tz.rs
@@ -1,8 +1,8 @@
//! Calendar-day-in-team-timezone bucket math.
//!
//! Pure, zone-agnostic, and total: every function takes time as an `i64` (epoch ms) plus a
-//! [`Tz`] and returns without a `Result` and without reading a wall-clock "now". The bucket
-//! variants and the sweep consume it.
+//! [`Tz`] and returns without a `Result` and without reading a wall-clock "now". Consumers — the
+//! stream processor and the seeder — build calendar-day buckets and eviction windows from it.
//!
//! ## Window boundary (the highest-risk decision)
//!
@@ -18,7 +18,7 @@
//! instant ([`start_of_day_ms_in_tz`], [`start_of_hour_ms_in_tz`]) can be ambiguous (fall-back) or
//! nonexistent (spring-forward gap); it picks the **earliest** instant on `Ambiguous` (= Python
//! `ZoneInfo` fold=0) and the **post-gap** instant on `None`. Only this eviction-timing path is
-//! DST-tie-broken, and it rides the sweep's ±5 min `safety_margin` tolerance.
+//! DST-tie-broken, and a consumer's small eviction-timing tolerance (a few minutes) absorbs the tie.
use chrono::{DateTime, Duration, LocalResult, NaiveDate, NaiveDateTime, TimeZone, Timelike, Utc};
use chrono_tz::{Tz, UTC};
@@ -26,10 +26,8 @@ use chrono_tz::{Tz, UTC};
/// A calendar-day index: days since the Unix epoch (1970-01-01) in a given timezone.
pub type DayIdx = i32;
-/// Upper bound (minutes) on the forward probe used to find the post-gap instant for a local time
-/// that falls inside a spring-forward gap. Comfortably exceeds the largest real DST shift; the probe
-/// only runs when a transition lands exactly on the requested boundary (rare).
-const MAX_DST_GAP_MINUTES: i64 = 180;
+/// Covers the largest IANA local-time discontinuity: a fully skipped civil day.
+const MAX_LOCAL_GAP_MINUTES: i64 = 24 * 60;
/// The calendar-day index of `epoch_ms` in `tz`. Instant → day is never DST-ambiguous.
pub fn day_idx_in_tz(epoch_ms: i64, tz: Tz) -> DayIdx {
@@ -37,8 +35,8 @@ pub fn day_idx_in_tz(epoch_ms: i64, tz: Tz) -> DayIdx {
}
/// Local-midnight epoch-ms for day index `day` in `tz` — the base for an eviction deadline. On a
-/// fall-back midnight picks the earliest instant; on a spring-forward gap at midnight picks the
-/// post-gap instant.
+/// fall-back midnight picks the earliest instant; on a local-time gap picks the post-gap instant.
+/// A fully skipped civil day therefore has the same start as its following day.
pub fn start_of_day_ms_in_tz(day: DayIdx, tz: Tz) -> i64 {
let midnight = date_for_day(day)
.and_hms_opt(0, 0, 0)
@@ -77,7 +75,7 @@ pub fn window_start_for_now(now_day: DayIdx, window_days: u32) -> DayIdx {
/// The epoch-ms (team tz, local midnight) at which a day-`oldest_day` bucket/entry leaves an
/// `N`-day window — the start of day `oldest_day + N + 1`. Computed in `i64` and, mirroring
-/// [`super::pick_state::EvictionWindow::earliest_eviction_at_ms`], returns [`i64::MAX`] (never
+/// [`crate::leaf_state::select::EvictionWindow::earliest_eviction_at_ms`], returns [`i64::MAX`] (never
/// evict) when the leave-day overflows [`DayIdx`] for an astronomical window rather than wrapping
/// to a near-epoch instant (which would flap entered/left).
pub fn window_leave_day_ms(oldest_day: DayIdx, window_days: u32, tz: Tz) -> i64 {
@@ -97,12 +95,18 @@ pub fn day_idx_of_naive_date(date: NaiveDate) -> DayIdx {
}
/// The local hour-of-day `[0, 23]` of `epoch_ms` in `tz` — the bucket index for the 24-hour variant.
+///
+/// Future sub-day window seam (`Lookback::SubDay`): the seeder's day-granular scan does not call this,
+/// but it is the hook a sub-day (hourly) window would bucket through.
pub fn hour_of_day_in_tz(epoch_ms: i64, tz: Tz) -> u32 {
utc_instant(epoch_ms).with_timezone(&tz).hour()
}
/// Epoch-ms of the start of the local hour containing `epoch_ms` in `tz` — the hourly variant's
/// eviction base. DST-tie-broken like [`start_of_day_ms_in_tz`].
+///
+/// Future sub-day window seam (`Lookback::SubDay`): the seeder's day-granular scan does not call this,
+/// but it is the hook a sub-day (hourly) window would compute its eviction base through.
pub fn start_of_hour_ms_in_tz(epoch_ms: i64, tz: Tz) -> i64 {
let local = utc_instant(epoch_ms).with_timezone(&tz);
let on_the_hour = local
@@ -152,24 +156,30 @@ fn local_naive_to_instant(naive: NaiveDateTime, tz: Tz) -> DateTime<Tz> {
LocalResult::Single(dt) => dt,
// Overlap: the wall-clock time occurs twice. Earliest = Python `ZoneInfo` fold=0.
LocalResult::Ambiguous(earliest, _latest) => earliest,
- // Gap: the wall-clock time does not exist. Walk forward to the first representable local
- // minute and take its earliest instant — the post-gap instant. Bounded by the max DST shift;
- // only reachable when a transition lands exactly on this boundary.
- LocalResult::None => (1..=MAX_DST_GAP_MINUTES)
- .find_map(|m| {
- naive
- .checked_add_signed(Duration::minutes(m))
- .and_then(|t| tz.from_local_datetime(&t).earliest())
- })
+ LocalResult::None => first_valid_after_gap(naive, tz)
.unwrap_or_else(|| Utc.from_utc_datetime(&naive).with_timezone(&tz)),
}
}
+fn first_valid_after_gap(naive: NaiveDateTime, tz: Tz) -> Option<DateTime<Tz>> {
+ let upper = (1..=MAX_LOCAL_GAP_MINUTES).find_map(|minutes| {
+ let candidate = naive.checked_add_signed(Duration::minutes(minutes))?;
+ tz.from_local_datetime(&candidate)
+ .earliest()
+ .map(|_| candidate)
+ })?;
+ (0..60).rev().find_map(|seconds_before| {
+ let candidate = upper.checked_sub_signed(Duration::seconds(seconds_before))?;
+ tz.from_local_datetime(&candidate).earliest()
+ })
+}
+
#[cfg(test)]
mod tests {
use super::*;
use chrono_tz::America::{New_York, Sao_Paulo};
use chrono_tz::Asia::Kolkata;
+ use chrono_tz::Pacific::Apia;
const MS_PER_DAY: i64 = 86_400_000;
const MS_PER_HOUR: i64 = 3_600_000;
@@ -294,6 +304,30 @@ mod tests {
);
}
+ #[test]
+ fn fully_skipped_civil_day_projects_to_the_following_midnight() {
+ let preceding = day_idx_of_naive_date(NaiveDate::from_ymd_opt(2011, 12, 29).unwrap());
+ let skipped = day_idx_of_naive_date(NaiveDate::from_ymd_opt(2011, 12, 30).unwrap());
+ let following = day_idx_of_naive_date(NaiveDate::from_ymd_opt(2011, 12, 31).unwrap());
+
+ assert_eq!(
+ start_of_day_ms_in_tz(preceding, Apia),
+ utc_ms(2011, 12, 29, 10, 0)
+ );
+ assert_eq!(
+ start_of_day_ms_in_tz(skipped, Apia),
+ utc_ms(2011, 12, 30, 10, 0)
+ );
+ assert_eq!(
+ start_of_day_ms_in_tz(following, Apia),
+ utc_ms(2011, 12, 30, 10, 0)
+ );
+ assert_eq!(
+ start_of_day_ms_in_tz(following + 1, Apia),
+ utc_ms(2011, 12, 31, 10, 0)
+ );
+ }
+
#[test]
fn window_is_inclusive_of_now_minus_n() {
// relative_date_parse("-7d") = now − 7 days; the predicate `event_day >= now_day − 7` makes
diff --git a/rust/cohort-stream-processor/src/stage2/eligibility.rs b/rust/cohort-core/src/eligibility.rs
similarity index 98%
rename from rust/cohort-stream-processor/src/stage2/eligibility.rs
rename to rust/cohort-core/src/eligibility.rs
index 7477a2d2d6d5..5f00a1cdee50 100644
--- a/rust/cohort-stream-processor/src/stage2/eligibility.rs
+++ b/rust/cohort-core/src/eligibility.rs
@@ -5,7 +5,7 @@ use std::collections::HashMap;
use crate::filters::cohort_graph::RefGraphAnalysis;
use crate::filters::tree::{BoolOp, CohortTree, FilterNode};
use crate::filters::CohortId;
-use crate::stage1::key::LeafStateKey;
+use crate::leaf_state::key::LeafStateKey;
/// Per-cohort signals accumulated while parsing the cohort's filter tree.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
@@ -60,7 +60,7 @@ pub enum CohortEligibility {
/// ≥2 positive, state-keyed, cohort-ref-free leaves.
Stage2Composable,
/// A resolvable, cycle-free ref-bearing cohort promoted to composition when `cohort_cascade_enabled`;
- /// composes from each referent's stored membership and persists a `cf_stage2` bit.
+ /// a consumer composes it from each referent's stored membership and persists the composed result.
Stage2ComposableRef,
/// Not emitted; see [`ExcludedReason`].
Excluded(ExcludedReason),
@@ -77,8 +77,9 @@ impl CohortEligibility {
}
}
- /// Whether this class persists a `cf_stage2` row — both composable classes do; single-leaf
- /// membership lives in `cf_behavioral` and excluded cohorts persist nothing.
+ /// Whether a consumer stores this class's membership as a separately-composed row — both
+ /// composable classes do; single-leaf membership is the leaf's own state and excluded cohorts
+ /// persist nothing.
pub fn writes_cf_stage2(self) -> bool {
matches!(self, Self::Stage2Composable | Self::Stage2ComposableRef)
}
diff --git a/rust/cohort-core/src/events.rs b/rust/cohort-core/src/events.rs
new file mode 100644
index 000000000000..10247f66b433
--- /dev/null
+++ b/rust/cohort-core/src/events.rs
@@ -0,0 +1,33 @@
+use serde::{Deserialize, Serialize};
+
+/// One re-keyed event as published to `cohort_stream_events`. Field names mirror the shuffler
+/// envelope exactly.
+///
+/// `properties` / `person_properties` are raw JSON strings parsed lazily in globals construction.
+/// `source_partition` / `source_offset` are the upstream coordinates for replay-safe counter
+/// increments.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CohortStreamEvent {
+ pub team_id: i32,
+ pub person_id: String,
+ pub distinct_id: String,
+ pub uuid: String,
+ pub event: String,
+ /// ClickHouse wire format `"YYYY-MM-DD HH:MM:SS.ffffff"`; normalized to ISO 8601 in globals.
+ pub timestamp: String,
+ pub properties: Option<String>,
+ pub person_properties: Option<String>,
+ pub elements_chain: Option<String>,
+ pub source_offset: i64,
+ pub source_partition: i32,
+ /// The merge origin person, set when a post-merge straggler is redirected to the merged-into
+ /// person. `None` for a normal event. Stage 1 routes replay-dedup through
+ /// `redirect_dedup[origin]` when set, preventing double-fold.
+ #[serde(default)]
+ pub redirected_from: Option<String>,
+ /// Cross-partition re-produce hops this straggler has taken through the tombstone redirect.
+ /// `0` for a normal event; incremented on each re-key produce. At the cap
+ /// (`MAX_CROSS_PARTITION_REDIRECT_HOPS`) the worker degrades to an inline fold to break cycles.
+ #[serde(default)]
+ pub redirect_hops: u8,
+}
diff --git a/rust/cohort-core/src/filters/catalog.rs b/rust/cohort-core/src/filters/catalog.rs
new file mode 100644
index 000000000000..52b534368ff4
--- /dev/null
+++ b/rust/cohort-core/src/filters/catalog.rs
@@ -0,0 +1,90 @@
+use std::collections::HashMap;
+use std::hash::{Hash, Hasher};
+use std::sync::Arc;
+
+use crate::filters::reverse_index::TeamFilters;
+use crate::filters::TeamId;
+
+/// 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);
+
+ pub fn next(self) -> Self {
+ Self(self.0 + 1)
+ }
+}
+
+#[derive(Debug, Default)]
+pub struct FilterCatalog {
+ teams: HashMap<TeamId, Arc<TeamFilters>>,
+ generation: Generation,
+}
+
+impl FilterCatalog {
+ pub fn new() -> Self {
+ Self {
+ teams: HashMap::new(),
+ generation: Generation::INITIAL,
+ }
+ }
+
+ /// The frozen filters for a team, or `None` if it has no realtime cohorts.
+ pub fn team(&self, team_id: TeamId) -> Option<&Arc<TeamFilters>> {
+ self.teams.get(&team_id)
+ }
+
+ pub fn generation(&self) -> Generation {
+ self.generation
+ }
+
+ /// Stamp the content generation. Stamped once, pre-publication (by the refresh loop, before the
+ /// atomic swap), so it consumes `self` rather than mutating a published catalog.
+ pub fn with_generation(mut self, generation: Generation) -> Self {
+ self.generation = generation;
+ self
+ }
+
+ pub fn team_count(&self) -> usize {
+ self.teams.len()
+ }
+
+ /// Total distinct conditionHashes across all teams (sum of the per-team dedup sets).
+ pub fn total_unique_conditions(&self) -> usize {
+ self.teams
+ .values()
+ .map(|team| team.unique_condition_hashes.len())
+ .sum()
+ }
+
+ pub fn from_teams(teams: impl IntoIterator<Item = (TeamId, TeamFilters)>) -> Self {
+ Self {
+ teams: teams
+ .into_iter()
+ .map(|(team, filters)| (team, Arc::new(filters)))
+ .collect(),
+ generation: Generation::INITIAL,
+ }
+ }
+}
+
+/// Hashes only the per-team condition sets (order-independent via the sorts), deliberately excluding
+/// `generation`. This backs the processor's `catalog_signature` memo invalidation: two catalogs with
+/// the same conditions must hash equal so a no-op refresh reuses the generation and keeps memo entries
+/// valid. `manager.rs`'s equivalence test guards the contract.
+impl Hash for FilterCatalog {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ let mut teams: Vec<(&TeamId, &Arc<TeamFilters>)> = self.teams.iter().collect();
+ teams.sort_unstable_by_key(|(team, _)| team.0);
+ for (team, filters) in teams {
+ team.0.hash(state);
+ let mut hashes: Vec<[u8; 16]> =
+ filters.unique_condition_hashes.iter().copied().collect();
+ hashes.sort_unstable();
+ hashes.hash(state);
+ }
+ }
+}
diff --git a/rust/cohort-stream-processor/src/filters/cohort_graph.rs b/rust/cohort-core/src/filters/cohort_graph.rs
similarity index 100%
rename from rust/cohort-stream-processor/src/filters/cohort_graph.rs
rename to rust/cohort-core/src/filters/cohort_graph.rs
diff --git a/rust/cohort-stream-processor/src/filters/leaf_classifier.rs b/rust/cohort-core/src/filters/leaf_classifier.rs
similarity index 98%
rename from rust/cohort-stream-processor/src/filters/leaf_classifier.rs
rename to rust/cohort-core/src/filters/leaf_classifier.rs
index b430ac4980a7..c10476b5119c 100644
--- a/rust/cohort-stream-processor/src/filters/leaf_classifier.rs
+++ b/rust/cohort-core/src/filters/leaf_classifier.rs
@@ -8,8 +8,8 @@ use crate::filters::tree::{
BehavioralLeafConfig, BehavioralValue, CohortLeaf, CohortRefLeafConfig, PersonLeafConfig,
};
use crate::filters::CohortId;
-use crate::stage1::key::LeafStateKey;
-use crate::stage1::pick_state::pick_state_variant;
+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
@@ -244,7 +244,7 @@ mod tests {
assert_eq!(leaf.bytecode.as_ref(), &bytecode_loaded());
assert_eq!(
leaf.state_variant,
- Some(crate::stage1::state::StateVariant::BehavioralSingle),
+ Some(crate::leaf_state::variant::StateVariant::BehavioralSingle),
);
}
@@ -269,7 +269,7 @@ mod tests {
assert_eq!(leaf.operator_value, Some(3));
assert_eq!(
leaf.state_variant,
- Some(crate::stage1::state::StateVariant::BehavioralDailyBuckets),
+ Some(crate::leaf_state::variant::StateVariant::BehavioralDailyBuckets),
);
}
@@ -323,7 +323,7 @@ mod tests {
};
assert_eq!(
leaf.state_variant,
- Some(crate::stage1::state::StateVariant::BehavioralCompressedHistory),
+ Some(crate::leaf_state::variant::StateVariant::BehavioralCompressedHistory),
"{why}",
);
}
@@ -331,7 +331,7 @@ mod tests {
#[test]
fn performed_event_multiple_explicit_relative_lower_window_is_kept() {
- use crate::stage1::state::StateVariant;
+ use crate::leaf_state::variant::StateVariant;
// The cohort UI stores "in the last N days" as `explicit_datetime: "-Nd"` with no
// time_interval/time_value; the multiple path must resolve it like the single path does.
for (explicit_datetime, expected_variant, why) in [
diff --git a/rust/cohort-stream-processor/src/filters/loader.rs b/rust/cohort-core/src/filters/loader.rs
similarity index 79%
rename from rust/cohort-stream-processor/src/filters/loader.rs
rename to rust/cohort-core/src/filters/loader.rs
index 8b234fb6b0fe..5c52114246a0 100644
--- a/rust/cohort-stream-processor/src/filters/loader.rs
+++ b/rust/cohort-core/src/filters/loader.rs
@@ -4,18 +4,15 @@
use std::collections::HashMap;
use chrono_tz::{Tz, UTC};
-use common_types::cohort::TeamAllowlist;
use metrics::counter;
use serde_json::Value;
use sqlx::PgPool;
use tracing::warn;
-use crate::filters::manager::FilterCatalog;
+use crate::filters::catalog::FilterCatalog;
use crate::filters::reverse_index::TeamFiltersBuilder;
use crate::filters::{CohortId, FilterError, TeamId};
-use crate::observability::metrics::{
- FILTER_CATALOG_COHORT_PARSE_ERRORS, FILTER_CATALOG_TZ_FALLBACK,
-};
+use crate::metrics::{FILTER_CATALOG_COHORT_PARSE_ERRORS, FILTER_CATALOG_TZ_FALLBACK};
/// Realtime cohorts to load, mirroring the Node filter manager's predicate, joined to
/// `posthog_team` for the team timezone the bucket variants use for calendar-day computation.
@@ -41,13 +38,6 @@ pub async fn load_realtime_cohorts(pool: &PgPool) -> Result<Vec<CohortRow>, Filt
Ok(rows)
}
-/// Drop rows for teams outside `allowlist`, in place, before catalog building. Kept separate from
-/// [`build_catalog_from_rows`] (which stays allowlist-agnostic) and DB-free for unit testability.
-/// Keeps the catalog lean and scopes shadow output for events injected directly into the stream.
-pub(crate) fn retain_allowlisted(rows: &mut Vec<CohortRow>, allowlist: &TeamAllowlist) {
- rows.retain(|row| allowlist.includes(row.team_id));
-}
-
/// Group rows by team into a catalog. A cohort that fails to parse is counted, warned, and skipped
/// rather than poisoning the rest of the catalog.
pub fn build_catalog_from_rows(rows: Vec<CohortRow>, cascade_enabled: bool) -> FilterCatalog {
@@ -99,8 +89,6 @@ fn resolve_team_tz(raw: &str, team_id: TeamId) -> Tz {
#[cfg(test)]
mod tests {
- use std::collections::HashSet;
-
use super::*;
use serde_json::json;
@@ -172,7 +160,7 @@ mod tests {
#[test]
fn build_catalog_threads_the_cascade_gate_into_freeze() {
- use crate::stage2::{CohortEligibility, ExcludedReason};
+ use crate::eligibility::{CohortEligibility, ExcludedReason};
let referrer = json!({
"properties": {
@@ -196,32 +184,4 @@ mod tests {
"gate on promotes the resolvable ref cohort",
);
}
-
- #[test]
- fn retain_allowlisted_keeps_only_in_scope_rows() {
- let mut rows = vec![
- row(1, 2, behavioral_cohort()),
- row(2, 7, behavioral_cohort()),
- ];
- retain_allowlisted(&mut rows, &TeamAllowlist::Only(HashSet::from([2])));
- assert_eq!(rows.len(), 1);
- assert_eq!(rows[0].team_id, 2);
- }
-
- #[test]
- fn retain_allowlisted_all_keeps_everything() {
- let mut rows = vec![
- row(1, 2, behavioral_cohort()),
- row(2, 7, behavioral_cohort()),
- ];
- retain_allowlisted(&mut rows, &TeamAllowlist::All);
- assert_eq!(rows.len(), 2);
- }
-
- #[test]
- fn retain_allowlisted_empty_scope_drops_everything() {
- let mut rows = vec![row(1, 2, behavioral_cohort())];
- retain_allowlisted(&mut rows, &TeamAllowlist::Only(HashSet::new()));
- assert!(rows.is_empty());
- }
}
diff --git a/rust/cohort-core/src/filters/mod.rs b/rust/cohort-core/src/filters/mod.rs
new file mode 100644
index 000000000000..f299cfb735c2
--- /dev/null
+++ b/rust/cohort-core/src/filters/mod.rs
@@ -0,0 +1,35 @@
+pub mod catalog;
+pub(crate) mod cohort_graph;
+pub mod leaf_classifier;
+pub mod loader;
+pub mod reverse_index;
+pub mod tree;
+
+use thiserror::Error;
+
+pub use catalog::{FilterCatalog, Generation};
+pub use leaf_classifier::{classify_leaf, LeafClass, LeafDropReason};
+pub use loader::{build_catalog_from_rows, load_realtime_cohorts, CohortRow, REALTIME_COHORTS_SQL};
+pub use reverse_index::{TeamFilters, TeamFiltersBuilder};
+pub use tree::{
+ parse_cohort_tree, BehavioralLeafConfig, BehavioralValue, BoolOp, CohortLeaf,
+ CohortRefLeafConfig, CohortTree, FilterNode, LeafSink, PersonLeafConfig,
+};
+
+/// Team identifier (`posthog_cohort.team_id`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct TeamId(pub i32);
+
+/// Cohort identifier (`posthog_cohort.id`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct CohortId(pub i32);
+
+/// Errors from loading or parsing the filter catalog.
+#[derive(Debug, Error)]
+pub enum FilterError {
+ #[error("querying posthog_cohort: {0}")]
+ Query(#[from] sqlx::Error),
+
+ #[error("cohort {cohort_id} filters has no `properties`")]
+ MissingProperties { cohort_id: i32 },
+}
diff --git a/rust/cohort-stream-processor/src/filters/reverse_index.rs b/rust/cohort-core/src/filters/reverse_index.rs
similarity index 97%
rename from rust/cohort-stream-processor/src/filters/reverse_index.rs
rename to rust/cohort-core/src/filters/reverse_index.rs
index b5ccb05b695b..5f2a0f1c8327 100644
--- a/rust/cohort-stream-processor/src/filters/reverse_index.rs
+++ b/rust/cohort-core/src/filters/reverse_index.rs
@@ -8,21 +8,21 @@ use metrics::counter;
use serde_json::Value;
use tracing::warn;
+use crate::eligibility::refine_ref_bearing;
+use crate::eligibility::{classify, CohortEligibility, CohortParseFlags};
use crate::filters::cohort_graph;
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::observability::metrics::{
- COHORT_ELIGIBILITY_TOTAL, COHORT_IN_CYCLE_TOTAL, FILTER_CATALOG_SKIPPED_LEAVES,
-};
-use crate::stage1::key::LeafStateKey;
-use crate::stage1::person_record::CatalogFingerprint;
-use crate::stage1::pick_state::{
+use crate::fingerprint::CatalogFingerprint;
+use crate::leaf_state::key::LeafStateKey;
+use crate::leaf_state::select::{
effective_window_days, pick_state_variant, EvictionWindow, PredicateOp,
};
-use crate::stage1::state::StateVariant;
-use crate::stage2::eligibility::refine_ref_bearing;
-use crate::stage2::{classify, CohortEligibility, CohortParseFlags};
+use crate::leaf_state::variant::StateVariant;
+use crate::metrics::{
+ COHORT_ELIGIBILITY_TOTAL, COHORT_IN_CYCLE_TOTAL, FILTER_CATALOG_SKIPPED_LEAVES,
+};
#[derive(Debug, Clone, Copy)]
pub struct LeafStateMeta {
@@ -56,9 +56,8 @@ pub struct TeamFilters {
/// is computed over.
pub person_conditions_ordered: Vec<[u8; 16]>,
/// SHA-256 over `person_conditions_ordered`, computed once at freeze. A content fingerprint of the
- /// team's person conditions: a stored [`PersonRecord`](crate::stage1::PersonRecord) whose catalog
- /// fingerprint matches this needs no re-evaluation, and a no-op catalog refresh (same conditions)
- /// leaves it unchanged, so records are not needlessly invalidated.
+ /// team's person conditions: a stored person record whose catalog fingerprint matches this needs
+ /// no re-evaluation, and a no-op catalog refresh leaves it unchanged.
pub catalog_fingerprint: CatalogFingerprint,
/// `LeafStateKey → [CohortId]` for single-leaf cohorts.
pub by_lsk_to_single_leaf_cohorts: HashMap<LeafStateKey, Vec<CohortId>>,
@@ -398,7 +397,7 @@ mod tests {
use super::*;
use serde_json::json;
- use crate::stage2::ExcludedReason;
+ use crate::eligibility::ExcludedReason;
const HASH: [u8; 16] = *b"0123456789abcdef";
@@ -1662,12 +1661,9 @@ mod tests {
}
#[test]
- fn cascade_on_negated_missing_ref_with_own_leaf_is_composable_ref_and_reads_true() {
- use crate::stage2::evaluator::evaluate_tree;
-
+ fn cascade_on_negated_missing_ref_with_own_leaf_is_composable_ref_and_indexed() {
let mut builder = TeamFiltersBuilder::default();
- // 1 = AND(own person leaf, NOT in 99). 99 is never added: an absent negated ref reads
- // `true`, so the missing target must not exclude 1 (oracle: `false ^ true = true`).
+ // 99 is never added; a negated missing target must not exclude the referrer.
builder
.add_cohort(
CohortId(1),
@@ -1688,21 +1684,6 @@ mod tests {
vec![CohortId(1)],
"the cohort's own person leaf indexes it for re-evaluation on the event path",
);
-
- // The composer fills a missing referent as `false`; the negated leaf flips it to `true`,
- // so the cohort's membership tracks its own leaf alone.
- let root = &frozen.cohorts[&CohortId(1)].root;
- let ref_membership = HashMap::from([(CohortId(99), false)]);
- let off = evaluate_tree(root, &HashMap::from([(per_lsk, false)]), &ref_membership);
- let on = evaluate_tree(root, &HashMap::from([(per_lsk, true)]), &ref_membership);
- assert!(
- !off,
- "own leaf off ⇒ non-member even though the negated ref reads true"
- );
- assert!(
- on,
- "own leaf flipping on ⇒ member, the Entered the cascade slice must emit"
- );
}
#[test]
diff --git a/rust/cohort-stream-processor/src/filters/tree.rs b/rust/cohort-core/src/filters/tree.rs
similarity index 99%
rename from rust/cohort-stream-processor/src/filters/tree.rs
rename to rust/cohort-core/src/filters/tree.rs
index da0d2c833b34..0da8e83e0991 100644
--- a/rust/cohort-stream-processor/src/filters/tree.rs
+++ b/rust/cohort-core/src/filters/tree.rs
@@ -7,8 +7,8 @@ use serde_json::Value;
use crate::filters::leaf_classifier::{classify_leaf, LeafClass, LeafDropReason};
use crate::filters::{CohortId, FilterError, TeamId};
-use crate::stage1::key::LeafStateKey;
-use crate::stage1::state::StateVariant;
+use crate::leaf_state::key::LeafStateKey;
+use crate::leaf_state::variant::StateVariant;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
diff --git a/rust/cohort-core/src/fingerprint.rs b/rust/cohort-core/src/fingerprint.rs
new file mode 100644
index 000000000000..9eb33072a0cc
--- /dev/null
+++ b/rust/cohort-core/src/fingerprint.rs
@@ -0,0 +1,20 @@
+use sha2::{Digest, Sha256};
+
+/// 128 bits of SHA-256 over the concatenation of a team's sorted person condition hashes.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct CatalogFingerprint(pub u128);
+
+impl CatalogFingerprint {
+ /// Fingerprint the already-sorted person condition hashes. The input must be sorted so a
+ /// permutation of the same conditions yields one value.
+ pub fn of_sorted(conditions: &[[u8; 16]]) -> Self {
+ let mut hasher = Sha256::new();
+ for condition in conditions {
+ hasher.update(condition);
+ }
+ let digest = hasher.finalize();
+ Self(u128::from_le_bytes(
+ digest[..16].try_into().expect("SHA-256 yields 32 bytes"),
+ ))
+ }
+}
diff --git a/rust/cohort-stream-processor/src/hogvm/executor.rs b/rust/cohort-core/src/hogvm/executor.rs
similarity index 80%
rename from rust/cohort-stream-processor/src/hogvm/executor.rs
rename to rust/cohort-core/src/hogvm/executor.rs
index 3e4396de0427..c04f932edc74 100644
--- a/rust/cohort-stream-processor/src/hogvm/executor.rs
+++ b/rust/cohort-core/src/hogvm/executor.rs
@@ -12,7 +12,7 @@ use metrics::counter;
use serde_json::Value;
use tracing::info;
-use crate::observability::metrics::{STAGE1_HOGVM_ERROR, STAGE1_HOGVM_UNKNOWN_FUNCTION};
+use crate::metrics::{STAGE1_HOGVM_ERROR, STAGE1_HOGVM_UNKNOWN_FUNCTION};
/// Unknown-native function names already logged once. Bounded by the HogQL native surface
/// (~hundreds max), so it never grows without bound; keeps the per-event unknown-function path
@@ -49,6 +49,53 @@ pub enum EvalOutcome {
VmError(VmError),
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+#[repr(u8)]
+pub enum VmErrorClass {
+ TypeCoercion,
+ Stack,
+ NotImplemented,
+ UnknownReference,
+ Program,
+ Exception,
+ Runtime,
+ UnknownFunction,
+ Other,
+}
+
+impl VmErrorClass {
+ pub const ALL: [Self; 9] = [
+ Self::TypeCoercion,
+ Self::Stack,
+ Self::NotImplemented,
+ Self::UnknownReference,
+ Self::Program,
+ Self::Exception,
+ Self::Runtime,
+ Self::UnknownFunction,
+ Self::Other,
+ ];
+ pub const COUNT: usize = Self::ALL.len();
+
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::TypeCoercion => "type_coercion",
+ Self::Stack => "stack",
+ Self::NotImplemented => "not_implemented",
+ Self::UnknownReference => "unknown_ref",
+ Self::Program => "program",
+ Self::Exception => "exception",
+ Self::Runtime => "runtime",
+ Self::UnknownFunction => "unknown_function",
+ Self::Other => "other",
+ }
+ }
+
+ pub const fn index(self) -> usize {
+ self as usize
+ }
+}
+
/// A reusable evaluator owning one [`ExecutionContext`]: set globals once per event, swap the program
/// per condition, both in place.
///
@@ -79,13 +126,16 @@ impl CohortEvaluator {
}
/// Evaluate one condition's bytecode against the current globals, coercing failures and non-bool
- /// results to `false` and emitting a per-class metric so a silently-failing cohort stays
- /// observable. `bytecode` must be `RETURN`-terminated (the loader appends it).
+ /// 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))
}
- /// As [`Self::evaluate`] but returns the detailed [`EvalOutcome`].
+ /// 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) {
@@ -106,7 +156,8 @@ fn run(context: &ExecutionContext) -> EvalOutcome {
}
}
-/// One-shot evaluation building a fresh context (used by the parity test). `bytecode` must be
+/// One-shot evaluation building a fresh context (the seeder's path; also the parity test's). Emits
+/// no metric — the caller classifies the returned [`EvalOutcome`]. `bytecode` must be
/// `RETURN`-terminated, as the catalog loader leaves it.
pub fn evaluate_detailed(bytecode: &[Value], globals: Value) -> EvalOutcome {
let program = match Program::new(bytecode.to_vec()) {
@@ -117,10 +168,6 @@ pub fn evaluate_detailed(bytecode: &[Value], globals: Value) -> EvalOutcome {
run(&context)
}
-pub fn evaluate(bytecode: &[Value], globals: Value) -> bool {
- outcome_to_bool(evaluate_detailed(bytecode, globals))
-}
-
/// Collapse an [`EvalOutcome`] to `bool`, emitting a per-class metric on failure.
fn outcome_to_bool(outcome: EvalOutcome) -> bool {
match outcome {
@@ -140,31 +187,29 @@ fn outcome_to_bool(outcome: EvalOutcome) -> bool {
false
}
EvalOutcome::VmError(error) => {
- counter!(STAGE1_HOGVM_ERROR, "reason" => vm_error_reason(&error)).increment(1);
+ counter!(STAGE1_HOGVM_ERROR, "reason" => classify_vm_error(&error).as_str())
+ .increment(1);
false
}
}
}
-/// Collapse a [`VmError`] into a bounded `reason` label for [`STAGE1_HOGVM_ERROR`]. The bucket set is
-/// fixed and small so the Prometheus series count stays constant; the `_` arm keeps the match total
-/// over the `#[non_exhaustive]` enum and folds in `VmError::Other`. `UnknownFunction`/`UnknownSymbol`
-/// are normally routed to [`EvalOutcome::UnknownFunction`] (separate counter) — mapped here only for
-/// totality in case [`classify_failure`] ever changes.
-fn vm_error_reason(error: &VmError) -> &'static str {
+/// Collapse a [`VmError`] into a bounded class. `UnknownFunction`/`UnknownSymbol` normally become
+/// [`EvalOutcome::UnknownFunction`], but remain classified here for totality.
+pub fn classify_vm_error(error: &VmError) -> VmErrorClass {
match error {
VmError::InvalidValue(..)
| VmError::CannotCoerce(..)
| VmError::InvalidNumber(_)
- | VmError::IntegerOverflow => "type_coercion",
+ | VmError::IntegerOverflow => VmErrorClass::TypeCoercion,
VmError::StackOverflow | VmError::StackUnderflow | VmError::StackIndexOutOfBounds => {
- "stack"
+ VmErrorClass::Stack
}
- VmError::NotImplemented(_) => "not_implemented",
+ VmError::NotImplemented(_) => VmErrorClass::NotImplemented,
- VmError::UnknownGlobal(_) | VmError::UnknownProperty(_) => "unknown_ref",
+ VmError::UnknownGlobal(_) | VmError::UnknownProperty(_) => VmErrorClass::UnknownReference,
VmError::NotAnOperation(_)
| VmError::InvalidOperation(_)
@@ -173,9 +218,9 @@ fn vm_error_reason(error: &VmError) -> &'static str {
| VmError::InvalidCall(_)
| VmError::NotEnoughArguments(..)
| VmError::CaptureOutOfBounds(_)
- | VmError::NoFrame => "program",
+ | VmError::NoFrame => VmErrorClass::Program,
- VmError::UncaughtException(..) | VmError::InvalidException => "exception",
+ VmError::UncaughtException(..) | VmError::InvalidException => VmErrorClass::Exception,
VmError::DivisionByZero
| VmError::HeapIndexOutOfBounds
@@ -187,11 +232,11 @@ fn vm_error_reason(error: &VmError) -> &'static str {
| VmError::IndexOutOfBounds(..)
| VmError::OutOfResource(_)
| VmError::NativeCallFailed(_)
- | VmError::InvalidRegex(..) => "runtime",
+ | VmError::InvalidRegex(..) => VmErrorClass::Runtime,
- VmError::UnknownFunction(_) | VmError::UnknownSymbol(_) => "unknown_function",
+ VmError::UnknownFunction(_) | VmError::UnknownSymbol(_) => VmErrorClass::UnknownFunction,
- _ => "other", // VmError::Other + any future #[non_exhaustive] variant
+ _ => VmErrorClass::Other,
}
}
@@ -229,6 +274,12 @@ mod tests {
vec![json!("_H"), json!(1)]
}
+ /// One-shot `bool` collapse for the fixtures below, matching [`CohortEvaluator::evaluate`] on a
+ /// fresh context. Kept local now that the public free helper is gone.
+ fn evaluate(bytecode: &[Value], globals: Value) -> bool {
+ outcome_to_bool(evaluate_detailed(bytecode, globals))
+ }
+
#[test]
fn true_literal_coerces_to_true() {
let bc = [header(), vec![json!(OP_TRUE), json!(OP_RETURN)]].concat();
@@ -474,36 +525,63 @@ mod tests {
}
#[test]
- fn vm_error_reason_buckets_one_representative_per_class() {
+ fn vm_errors_map_to_one_bounded_class() {
// One representative `VmError` per bucket. Catches a forgotten or mis-bucketed variant: a
// new `#[non_exhaustive]` variant left unhandled silently falls into `other`, and moving an
// existing variant (e.g. `DivisionByZero` out of `runtime`) breaks the label breakdown.
- let cases: [(VmError, &str); 11] = [
+ let cases: [(VmError, VmErrorClass, &str); 11] = [
(
VmError::InvalidValue("a".into(), "b".into()),
+ VmErrorClass::TypeCoercion,
+ "type_coercion",
+ ),
+ (
+ VmError::IntegerOverflow,
+ VmErrorClass::TypeCoercion,
"type_coercion",
),
- (VmError::IntegerOverflow, "type_coercion"),
- (VmError::StackOverflow, "stack"),
- (VmError::NotImplemented("x".into()), "not_implemented"),
- (VmError::UnknownGlobal("g".into()), "unknown_ref"),
- (VmError::InvalidBytecode("b".into()), "program"),
+ (VmError::StackOverflow, VmErrorClass::Stack, "stack"),
+ (
+ VmError::NotImplemented("x".into()),
+ VmErrorClass::NotImplemented,
+ "not_implemented",
+ ),
+ (
+ VmError::UnknownGlobal("g".into()),
+ VmErrorClass::UnknownReference,
+ "unknown_ref",
+ ),
+ (
+ VmError::InvalidBytecode("b".into()),
+ VmErrorClass::Program,
+ "program",
+ ),
(
VmError::UncaughtException("t".into(), "m".into()),
+ VmErrorClass::Exception,
"exception",
),
- (VmError::DivisionByZero, "runtime"),
+ (VmError::DivisionByZero, VmErrorClass::Runtime, "runtime"),
// The `max_steps` blowup (`vm.rs` synthesizes `OutOfResource`) must stay visible.
- (VmError::OutOfResource("steps".into()), "runtime"),
- (VmError::UnknownFunction("f".into()), "unknown_function"),
- (VmError::Other("o".into()), "other"),
+ (
+ VmError::OutOfResource("steps".into()),
+ VmErrorClass::Runtime,
+ "runtime",
+ ),
+ (
+ VmError::UnknownFunction("f".into()),
+ VmErrorClass::UnknownFunction,
+ "unknown_function",
+ ),
+ (VmError::Other("o".into()), VmErrorClass::Other, "other"),
];
- for (error, expected) in &cases {
- assert_eq!(
- vm_error_reason(error),
- *expected,
- "wrong bucket for {error:?}"
- );
+ for (error, expected_class, expected_label) in &cases {
+ let class = classify_vm_error(error);
+ assert_eq!(class, *expected_class, "wrong bucket for {error:?}");
+ assert_eq!(class.as_str(), *expected_label);
+ }
+ for (index, class) in VmErrorClass::ALL.into_iter().enumerate() {
+ assert_eq!(class.index(), index);
}
}
diff --git a/rust/cohort-stream-processor/src/hogvm/globals.rs b/rust/cohort-core/src/hogvm/globals.rs
similarity index 98%
rename from rust/cohort-stream-processor/src/hogvm/globals.rs
rename to rust/cohort-core/src/hogvm/globals.rs
index d4fa2af118df..e59172e9d891 100644
--- a/rust/cohort-stream-processor/src/hogvm/globals.rs
+++ b/rust/cohort-core/src/hogvm/globals.rs
@@ -4,8 +4,8 @@ use chrono::{DateTime, NaiveDateTime};
use metrics::counter;
use serde_json::{json, Value};
-use crate::consumers::events::CohortStreamEvent;
-use crate::observability::metrics::STAGE1_GLOBALS_PARSE_ERROR;
+use crate::events::CohortStreamEvent;
+use crate::metrics::STAGE1_GLOBALS_PARSE_ERROR;
/// A malformed `properties`/`person_properties` JSON payload.
#[derive(Debug, thiserror::Error)]
diff --git a/rust/cohort-core/src/hogvm/mod.rs b/rust/cohort-core/src/hogvm/mod.rs
new file mode 100644
index 000000000000..7e9acb16f19d
--- /dev/null
+++ b/rust/cohort-core/src/hogvm/mod.rs
@@ -0,0 +1,19 @@
+//! Evaluate compiled cohort-filter bytecode against an event, coercing non-bool results to
+//! `false` to match the Node consumer.
+//!
+//! ## Metric-emission contract
+//!
+//! The `bool`-collapsing path ([`CohortEvaluator::evaluate`]) is self-counting: a failed result (VM
+//! error or unknown function) increments a `STAGE1_HOGVM_*` counter, while a non-bool result is
+//! coerced to `false` silently. That is the processor's path. The
+//! [`EvalOutcome`]-returning path ([`CohortEvaluator::evaluate_detailed`] and [`evaluate_detailed`])
+//! is bring-your-own-metrics: it emits nothing and hands the caller the classified outcome. The
+//! seeder uses it so failures land on its own `seeder_hogvm_*` counters, not these.
+
+mod executor;
+mod globals;
+
+pub use executor::{
+ classify_vm_error, evaluate_detailed, CohortEvaluator, EvalOutcome, VmErrorClass,
+};
+pub use globals::{build_behavioral_globals, build_person_property_globals, GlobalsError};
diff --git a/rust/cohort-stream-processor/src/stage1/key.rs b/rust/cohort-core/src/leaf_state/key.rs
similarity index 100%
rename from rust/cohort-stream-processor/src/stage1/key.rs
rename to rust/cohort-core/src/leaf_state/key.rs
diff --git a/rust/cohort-core/src/leaf_state/mod.rs b/rust/cohort-core/src/leaf_state/mod.rs
new file mode 100644
index 000000000000..1240bd62a155
--- /dev/null
+++ b/rust/cohort-core/src/leaf_state/mod.rs
@@ -0,0 +1,10 @@
+//! Leaf-state addressing: a leaf's persisted-state [`key`], the [`variant`] (which state
+//! representation it uses), and [`select`]ing both — plus an eviction window — from a leaf's config.
+
+pub mod key;
+pub mod select;
+pub mod variant;
+
+pub use key::LeafStateKey;
+pub use select::EvictionWindow;
+pub use variant::StateVariant;
diff --git a/rust/cohort-stream-processor/src/stage1/pick_state.rs b/rust/cohort-core/src/leaf_state/select.rs
similarity index 97%
rename from rust/cohort-stream-processor/src/stage1/pick_state.rs
rename to rust/cohort-core/src/leaf_state/select.rs
index 0a0aaf880fa5..0113e0a147dd 100644
--- a/rust/cohort-stream-processor/src/stage1/pick_state.rs
+++ b/rust/cohort-core/src/leaf_state/select.rs
@@ -2,11 +2,9 @@
use chrono_tz::Tz;
+use crate::bucket_tz::{day_idx_in_tz, day_idx_of_naive_date, start_of_day_ms_in_tz, DayIdx};
use crate::filters::tree::{BehavioralLeafConfig, BehavioralValue};
-use crate::stage1::bucket_tz::{
- day_idx_in_tz, day_idx_of_naive_date, start_of_day_ms_in_tz, DayIdx,
-};
-use crate::stage1::state::StateVariant;
+use crate::leaf_state::variant::StateVariant;
/// A cohort time interval with its fixed second-count (the `INTERVAL_TO_SECONDS` contract).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -138,11 +136,11 @@ pub enum UnsupportedVariant {
MissingWindow,
#[error("behavioral value does not contribute realtime bytecode")]
NonRealtimeValue,
- /// An `explicit_datetime` range the sweep cannot model: a relative *upper* bound, or a relative
- /// lower bound paired with any upper bound. These need delayed entry and double-ended eviction
- /// (a person enters only once the relative `from` slides past and leaves once the relative `to`
- /// does), which the single-deadline sweep does not represent. Skipping the leaf is the safe
- /// choice — no realtime state, hence no wrong members — until that machinery exists.
+ /// An `explicit_datetime` range the single-deadline eviction model cannot represent: a relative
+ /// *upper* bound, or a relative lower bound paired with any upper bound. These need delayed entry
+ /// and double-ended eviction (a person enters only once the relative `from` slides past and leaves
+ /// once the relative `to` does), which one eviction deadline does not capture. Skipping the leaf
+ /// is the safe choice — no realtime state, hence no wrong members — until that machinery exists.
#[error("explicit_datetime relative range is unsupported")]
RelativeRangeUnsupported,
/// A *present* `explicit_datetime`(_to) bound that parses as neither an absolute date nor a known
@@ -184,7 +182,7 @@ pub fn pick_state_variant(
/// is byte-identical to the `time_value:N, time_interval:<unit>` path the oracle also funnels
/// through `relative_date_parse` — so a sliding window recovers the common case correctly;
/// - **relative with any upper bound, or a relative upper bound** → [`UnsupportedVariant`], because
-/// the sweep cannot model delayed entry / double-ended eviction.
+/// a single eviction deadline cannot model delayed entry / double-ended eviction.
fn eviction_window(leaf: &BehavioralLeafConfig) -> Result<EvictionWindow, UnsupportedVariant> {
if leaf.explicit_datetime.is_some() || leaf.explicit_datetime_to.is_some() {
return explicit_eviction_window(
@@ -218,7 +216,7 @@ fn explicit_eviction_window(
Err(UnsupportedVariant::UnparseableExplicitBound)
}
// A relative *upper* bound (with or without a lower bound) needs delayed double-ended
- // eviction the sweep does not model.
+ // eviction a single deadline does not model.
(_, Some(Bound::Relative(_))) => Err(UnsupportedVariant::RelativeRangeUnsupported),
// A relative *lower* bound combined with any upper bound is the same problem: the person
// would enter only once the relative `from` slides past, then leave at the upper bound.
@@ -406,7 +404,7 @@ mod tests {
use super::*;
- use crate::stage1::key::LeafStateKey;
+ use crate::leaf_state::key::LeafStateKey;
const HASH: [u8; 16] = *b"0123456789abcdef";
@@ -819,7 +817,7 @@ mod tests {
#[test]
fn relative_explicit_ranges_and_relative_upper_bounds_are_unsupported() {
// Two-sided relative, relative upper bound, and relative-lower + absolute-upper all need
- // delayed-entry / double-ended eviction the sweep cannot model.
+ // delayed-entry / double-ended eviction a single eviction deadline cannot model.
let cases = [
(Some("-30d"), Some("-7d")), // two-sided relative
(Some("2026-01-01 00:00:00.000000"), Some("-7d")), // absolute lower, relative upper
@@ -915,7 +913,7 @@ mod tests {
#[test]
fn explicit_window_never_evicts_for_permanent_membership() {
- // An in-range absolute match is permanent: never evict at the upper bound, or the sweep would
+ // An in-range absolute match is permanent: never evict at the upper bound, or a consumer would
// emit a spurious `Left` even though the oracle's fixed-date predicate still matches.
for window in [
EvictionWindow::Explicit {
diff --git a/rust/cohort-core/src/leaf_state/variant.rs b/rust/cohort-core/src/leaf_state/variant.rs
new file mode 100644
index 000000000000..0b19c3965710
--- /dev/null
+++ b/rust/cohort-core/src/leaf_state/variant.rs
@@ -0,0 +1,25 @@
+/// Which state representation a leaf uses.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum StateVariant {
+ /// `performed_event`: a single "has any matching event in window" bit.
+ BehavioralSingle,
+ /// `performed_event_multiple` with a `1..=180`-day window: dense per-calendar-day counts.
+ BehavioralDailyBuckets,
+ /// `performed_event_multiple` with a window over 180 days: sparse run-length per-calendar-day
+ /// counts.
+ BehavioralCompressedHistory,
+ /// A person-property filter: a last-write-wins boolean.
+ PersonProperty,
+}
+
+impl StateVariant {
+ /// The metric-label / log form.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::BehavioralSingle => "behavioral_single",
+ Self::BehavioralDailyBuckets => "behavioral_daily_buckets",
+ Self::BehavioralCompressedHistory => "behavioral_compressed_history",
+ Self::PersonProperty => "person_property",
+ }
+ }
+}
diff --git a/rust/cohort-core/src/lib.rs b/rust/cohort-core/src/lib.rs
new file mode 100644
index 000000000000..5ef93d881116
--- /dev/null
+++ b/rust/cohort-core/src/lib.rs
@@ -0,0 +1,51 @@
+//! `cohort-core`: the evaluation kernel shared by the Behavioral Cohorts stream processor and the
+//! backfill seeder. It owns the pieces whose result must be byte-for-byte identical across every
+//! process that computes cohort membership: HogVM configuration, timezone calendar-day bucketing,
+//! `condition_hash` / leaf-state-key derivation, the filter catalog, and the metric surface.
+//!
+//! ## Load-bearing contracts
+//!
+//! 1. **Parity is frozen against the Node reference.** The HogVM execution config (stack/step
+//! ceilings, coercing comparisons), the tz calendar-day bucketing, and `condition_hash` handling
+//! reproduce the TS/Python/ClickHouse oracle exactly. Changing any of them silently diverges
+//! membership from production and must be treated as a wire break.
+//! 2. **Every linking process evaluates identically by construction.** The processor and the seeder
+//! share these types rather than reimplementing them, so a leaf that matches in one matches in the
+//! other. New consumers route through this crate, never a private copy.
+//! 3. **Metrics are emitted by this crate itself** (see [`metrics`]): any process that links
+//! `cohort-core` emits the same counters, so dashboards must scope by a job/service label rather
+//! than assume a single emitter.
+//!
+//! ## Facade
+//!
+//! The [`pub use`](self) block below is the API of record for new code: prefer `cohort_core::Foo`
+//! over the deeper module path. The modules stay `pub` because the processor shims re-export whole
+//! modules under their historical paths.
+
+pub mod bucket_tz;
+pub mod eligibility;
+pub mod events;
+pub mod filters;
+pub mod fingerprint;
+pub mod hogvm;
+pub mod leaf_state;
+pub mod metrics;
+pub mod partitioner;
+pub mod timestamp;
+
+pub use bucket_tz::{
+ day_idx_in_tz, day_idx_of_naive_date, resolve_tz_or_utc, start_of_day_ms_in_tz, DayIdx,
+};
+pub use eligibility::{classify, CohortEligibility, CohortParseFlags, ExcludedReason};
+pub use events::CohortStreamEvent;
+pub use filters::{
+ CohortId, FilterCatalog, FilterError, Generation, TeamFilters, TeamFiltersBuilder, TeamId,
+};
+pub use fingerprint::CatalogFingerprint;
+pub use hogvm::{
+ build_behavioral_globals, classify_vm_error, evaluate_detailed, CohortEvaluator, EvalOutcome,
+ VmErrorClass,
+};
+pub use leaf_state::{EvictionWindow, LeafStateKey, StateVariant};
+pub use partitioner::{partition_for, COHORT_PARTITION_COUNT};
+pub use timestamp::clickhouse_timestamp_to_millis;
diff --git a/rust/cohort-core/src/metrics.rs b/rust/cohort-core/src/metrics.rs
new file mode 100644
index 000000000000..04fc538cc15d
--- /dev/null
+++ b/rust/cohort-core/src/metrics.rs
@@ -0,0 +1,22 @@
+//! Metric-name constants for the cohort evaluation surface.
+//!
+//! These counters are emitted by `cohort-core` itself, from any process that links it (both the
+//! stream processor and the backfill seeder do). A dashboard cannot assume a single emitter: scope
+//! every query by the job/service label to attribute a series to the process that produced it.
+
+/// Leaves dropped during parse, labelled by `reason` (counter).
+pub const FILTER_CATALOG_SKIPPED_LEAVES: &str = "filter_catalog_skipped_leaves_total";
+/// Cohorts skipped because their filter tree failed to parse (counter).
+pub const FILTER_CATALOG_COHORT_PARSE_ERRORS: &str = "filter_catalog_cohort_parse_errors_total";
+/// Teams whose timezone did not parse as an IANA zone and fell back to UTC (counter).
+pub const FILTER_CATALOG_TZ_FALLBACK: &str = "filter_catalog_tz_fallback_total";
+/// Cohorts classified by composition eligibility at freeze, labelled by `class` (counter).
+pub const COHORT_ELIGIBILITY_TOTAL: &str = "cohort_eligibility_total";
+/// Cohorts excluded because they sit in a cohort-reference cycle (counter).
+pub const COHORT_IN_CYCLE_TOTAL: &str = "cohort_in_cycle_total";
+/// Cohort bytecode invoked a symbol with no registered native (counter).
+pub const STAGE1_HOGVM_UNKNOWN_FUNCTION: &str = "stage1_hogvm_unknown_function_total";
+/// Other VM/program failures during cohort evaluation, labelled by bounded `reason` values.
+pub const STAGE1_HOGVM_ERROR: &str = "stage1_hogvm_error_total";
+/// `properties`/`person_properties` JSON parse failures, labelled by `field` (counter).
+pub const STAGE1_GLOBALS_PARSE_ERROR: &str = "stage1_globals_parse_error_total";
diff --git a/rust/cohort-stream-processor/src/partitions/partitioner.rs b/rust/cohort-core/src/partitioner.rs
similarity index 100%
rename from rust/cohort-stream-processor/src/partitions/partitioner.rs
rename to rust/cohort-core/src/partitioner.rs
diff --git a/rust/cohort-stream-processor/src/stage1/time.rs b/rust/cohort-core/src/timestamp.rs
similarity index 100%
rename from rust/cohort-stream-processor/src/stage1/time.rs
rename to rust/cohort-core/src/timestamp.rs
diff --git a/rust/cohort-stream-processor/Cargo.toml b/rust/cohort-stream-processor/Cargo.toml
index 12cce1095305..65b54cf4904c 100644
--- a/rust/cohort-stream-processor/Cargo.toml
+++ b/rust/cohort-stream-processor/Cargo.toml
@@ -17,6 +17,7 @@ chrono = { workspace = true }
# Team-timezone-aware calendar-day bucket math (`stage1::bucket_tz`): `Tz` resolves
# `posthog_team.timezone` and is `Copy`, so it rides on the hot path inside the frozen `TeamFilters`.
chrono-tz = { workspace = true }
+cohort-core = { path = "../cohort-core" }
common-alloc = { path = "../common/alloc" }
common-database = { path = "../common/database" }
common-types = { path = "../common/types" }
@@ -33,16 +34,11 @@ envconfig = { workspace = true }
# `join_all` for routing each poll's per-partition sub-batches concurrently, so a full channel on
# one partition can't head-of-line-block the sends to the others. Same version dedup uses.
futures = { workspace = true }
-hogvm = { path = "../common/hogvm" }
lifecycle = { path = "../common/lifecycle" }
metrics = { workspace = true }
metrics-exporter-prometheus = { workspace = true }
# Streaming `BufWriter` and prefix-list (`list_with_delimiter`) S3 for multi-MB checkpoint files.
object_store = { version = "0.13.0", features = ["aws"] }
-# Tarjan SCC (`tarjan_scc`) for the per-team cohort-reference cycle defense at filter freeze
-# (`filters::cohort_graph`). Pinned to the same 0.8 line as `rust/feature-flags/Cargo.toml` so the
-# workspace resolves a single copy.
-petgraph = "0.8"
rand = { workspace = true }
# Raw `StreamConsumer` for `cohort_stream_events`. The consume loop and manual offset commit are
# driven directly (mirroring `rust/kafka-deduplicator`) rather than through `common-kafka`'s
diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rs
index c2cafee734a3..7a0be0866c76 100644
--- a/rust/cohort-stream-processor/src/consumers/events.rs
+++ b/rust/cohort-stream-processor/src/consumers/events.rs
@@ -1,8 +1,9 @@
//! The `cohort_stream_events` wire envelope and the group consumer that drives it.
//!
-//! [`CohortStreamEvent`] is the processor's own deserialize struct, deliberately decoupled from
-//! `cohort-event-shuffler`'s producer type: the two services share only the JSON field names, so a
-//! private copy means neither can break the other by adding a one-sided field.
+//! [`CohortStreamEvent`] is defined in `cohort-core` and intentionally shared with the backfill
+//! seeder, which produces the same envelope. It stays decoupled from `cohort-event-shuffler`'s
+//! producer type — they share only the JSON field names, so neither can break the other by adding a
+//! one-sided field.
//!
//! The Kafka-free routing core lives in [`EventDispatcher`] so it can be unit-tested with an
//! in-process router/store/catalog and no broker.
@@ -19,9 +20,10 @@ use metrics::{counter, gauge, histogram};
use rdkafka::consumer::{CommitMode, Consumer, ConsumerContext, StreamConsumer};
use rdkafka::message::Message;
use rdkafka::{Offset, TopicPartitionList};
-use serde::{Deserialize, Serialize};
use tracing::{debug, info, warn};
+pub use cohort_core::events::CohortStreamEvent;
+
use crate::consumers::merges::{ConsumedCascade, ConsumedMerge, ConsumedTransfer};
use crate::filters::manager::CatalogHandle;
use crate::merge::transfer::PendingTransfer;
@@ -63,38 +65,6 @@ const RESTORE_SEEK_TIMEOUT: Duration = Duration::from_secs(10);
/// peak memory per page.
const EAGER_BOOT_REDRIVE_PAGE_SIZE: usize = 100_000;
-/// One re-keyed event as published to `cohort_stream_events`. Field names mirror the shuffler
-/// envelope exactly.
-///
-/// `properties` / `person_properties` are raw JSON strings parsed lazily in globals construction.
-/// `source_partition` / `source_offset` are the upstream coordinates for replay-safe counter
-/// increments.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct CohortStreamEvent {
- pub team_id: i32,
- pub person_id: String,
- pub distinct_id: String,
- pub uuid: String,
- pub event: String,
- /// ClickHouse wire format `"YYYY-MM-DD HH:MM:SS.ffffff"`; normalized to ISO 8601 in globals.
- pub timestamp: String,
- pub properties: Option<String>,
- pub person_properties: Option<String>,
- pub elements_chain: Option<String>,
- pub source_offset: i64,
- pub source_partition: i32,
- /// The merge origin person, set when a post-merge straggler is redirected to the merged-into
- /// person. `None` for a normal event. Stage 1 routes replay-dedup through
- /// `redirect_dedup[origin]` when set, preventing double-fold.
- #[serde(default)]
- pub redirected_from: Option<String>,
- /// Cross-partition re-produce hops this straggler has taken through the tombstone redirect.
- /// `0` for a normal event; incremented on each re-key produce. At the cap
- /// (`MAX_CROSS_PARTITION_REDIRECT_HOPS`) the worker degrades to an inline fold to break cycles.
- #[serde(default)]
- pub redirect_hops: u8,
-}
-
/// One event consumed from `cohort_stream_events`, paired with its commit coordinates on that topic.
///
/// `partition`/`offset` here are commit coordinates, distinct from the event's upstream
diff --git a/rust/cohort-stream-processor/src/filters/manager.rs b/rust/cohort-stream-processor/src/filters/manager.rs
index 10e0296e1a13..5216ba17457b 100644
--- a/rust/cohort-stream-processor/src/filters/manager.rs
+++ b/rust/cohort-stream-processor/src/filters/manager.rs
@@ -1,7 +1,6 @@
//! `FilterCatalog` + atomic swap + jittered periodic refresh loop.
use std::collections::hash_map::DefaultHasher;
-use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
@@ -16,71 +15,11 @@ use sqlx::PgPool;
use tokio::sync::Notify;
use tracing::{debug, info, warn};
-use crate::filters::loader::{build_catalog_from_rows, load_realtime_cohorts, retain_allowlisted};
-use crate::filters::reverse_index::TeamFilters;
-use crate::filters::{FilterError, TeamId};
+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_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,
- }
- }
-
- /// The frozen filters for a team, or `None` if it has no realtime cohorts.
- pub fn team(&self, team_id: TeamId) -> Option<&Arc<TeamFilters>> {
- self.teams.get(&team_id)
- }
-
- pub fn generation(&self) -> Generation {
- self.generation
- }
-
- pub fn team_count(&self) -> usize {
- self.teams.len()
- }
-
- /// Total distinct conditionHashes across all teams (sum of the per-team dedup sets).
- pub fn total_unique_conditions(&self) -> usize {
- self.teams
- .values()
- .map(|team| team.unique_condition_hashes.len())
- .sum()
- }
-
- pub fn from_teams(teams: impl IntoIterator<Item = (TeamId, TeamFilters)>) -> Self {
- Self {
- teams: teams
- .into_iter()
- .map(|(team, filters)| (team, Arc::new(filters)))
- .collect(),
- generation: Generation::INITIAL,
- }
- }
-}
-
/// Snapshot counts returned by [`CatalogHandle::refresh`] for logging.
#[derive(Debug, Clone, Copy)]
pub struct CatalogStats {
@@ -159,7 +98,7 @@ impl CatalogHandle {
handle
}
- fn store(&self, mut catalog: FilterCatalog) {
+ fn store(&self, 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);
@@ -173,7 +112,7 @@ impl CatalogHandle {
self.current_signature.store(signature, Ordering::Relaxed);
self.current_generation
.store(generation.0, Ordering::Relaxed);
- catalog.generation = generation;
+ let catalog = catalog.with_generation(generation);
gauge!(FILTER_CATALOG_TEAMS).set(catalog.team_count() as f64);
gauge!(FILTER_CATALOG_UNIQUE_CONDITIONS).set(catalog.total_unique_conditions() as f64);
@@ -204,6 +143,11 @@ impl CatalogHandle {
}
}
+/// Drop rows outside the configured team scope before catalog construction.
+fn retain_allowlisted(rows: &mut Vec<CohortRow>, allowlist: &TeamAllowlist) {
+ rows.retain(|row| allowlist.includes(row.team_id));
+}
+
impl Default for CatalogHandle {
fn default() -> Self {
Self::new()
@@ -214,15 +158,8 @@ impl Default for CatalogHandle {
/// `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);
- }
+ catalog.hash(&mut hasher);
hasher.finish()
}
@@ -268,12 +205,23 @@ fn next_interval(interval: Duration, jitter: Duration) -> Duration {
#[cfg(test)]
mod tests {
+ use std::collections::HashSet;
+
use super::*;
use chrono_tz::UTC;
use serde_json::json;
use crate::filters::reverse_index::TeamFiltersBuilder;
- use crate::filters::CohortId;
+ use crate::filters::{CohortId, TeamFilters, TeamId};
+
+ fn cohort_row(id: i32, team_id: i32) -> CohortRow {
+ CohortRow {
+ id,
+ team_id,
+ filters: serde_json::Value::Null,
+ timezone: "UTC".to_string(),
+ }
+ }
fn team_with_one_behavioral() -> TeamFilters {
let mut builder = TeamFiltersBuilder::default();
@@ -416,6 +364,28 @@ mod tests {
assert_eq!(catalog_signature(&a), catalog_signature(&b));
}
+ #[test]
+ fn retain_allowlisted_keeps_only_in_scope_rows() {
+ let mut rows = vec![cohort_row(1, 2), cohort_row(2, 7)];
+ retain_allowlisted(&mut rows, &TeamAllowlist::Only(HashSet::from([2])));
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0].team_id, 2);
+ }
+
+ #[test]
+ fn retain_allowlisted_all_keeps_everything() {
+ let mut rows = vec![cohort_row(1, 2), cohort_row(2, 7)];
+ retain_allowlisted(&mut rows, &TeamAllowlist::All);
+ assert_eq!(rows.len(), 2);
+ }
+
+ #[test]
+ fn retain_allowlisted_empty_scope_drops_everything() {
+ let mut rows = vec![cohort_row(1, 2)];
+ retain_allowlisted(&mut rows, &TeamAllowlist::Only(HashSet::new()));
+ assert!(rows.is_empty());
+ }
+
#[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 5c2164b573e3..a90825b95f9a 100644
--- a/rust/cohort-stream-processor/src/filters/mod.rs
+++ b/rust/cohort-stream-processor/src/filters/mod.rs
@@ -1,40 +1,16 @@
//! Filter catalog: the in-memory view of realtime cohorts.
-pub(crate) mod cohort_graph;
-pub mod leaf_classifier;
-pub mod loader;
pub mod manager;
-pub mod reverse_index;
-pub mod tree;
-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, Generation};
-pub use reverse_index::{TeamFilters, TeamFiltersBuilder};
-pub use tree::{
- parse_cohort_tree, BehavioralLeafConfig, BehavioralValue, BoolOp, CohortLeaf,
- CohortRefLeafConfig, CohortTree, FilterNode, LeafSink, PersonLeafConfig,
+pub use cohort_core::filters::{
+ build_catalog_from_rows, load_realtime_cohorts, CohortRow, REALTIME_COHORTS_SQL,
};
+pub use cohort_core::filters::{leaf_classifier, loader, reverse_index, tree};
+pub use cohort_core::filters::{
+ BehavioralLeafConfig, BehavioralValue, BoolOp, CohortId, CohortLeaf, CohortRefLeafConfig,
+ CohortTree, FilterError, FilterNode, PersonLeafConfig, TeamId,
+};
+pub use cohort_core::filters::{FilterCatalog, Generation};
+pub use cohort_core::filters::{TeamFilters, TeamFiltersBuilder};
-/// Team identifier (`posthog_cohort.team_id`).
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
-pub struct TeamId(pub i32);
-
-/// Cohort identifier (`posthog_cohort.id`).
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
-pub struct CohortId(pub i32);
-
-/// Errors from loading or parsing the filter catalog.
-#[derive(Debug, Error)]
-pub enum FilterError {
- #[error("querying posthog_cohort: {0}")]
- Query(#[from] sqlx::Error),
-
- #[error("cohort {cohort_id} filters has no `properties`")]
- MissingProperties { cohort_id: i32 },
-
- #[error("cohort {cohort_id} is malformed: {detail}")]
- Malformed { cohort_id: i32, detail: String },
-}
+pub use manager::{run_refresh_loop, CatalogHandle, CatalogStats};
diff --git a/rust/cohort-stream-processor/src/hogvm/mod.rs b/rust/cohort-stream-processor/src/hogvm/mod.rs
deleted file mode 100644
index eb6446b57bec..000000000000
--- a/rust/cohort-stream-processor/src/hogvm/mod.rs
+++ /dev/null
@@ -1,8 +0,0 @@
-//! Evaluate compiled cohort-filter bytecode against an event, coercing non-bool results to
-//! `false` to match the Node consumer.
-
-mod executor;
-mod globals;
-
-pub use executor::{evaluate, evaluate_detailed, CohortEvaluator, EvalOutcome};
-pub use globals::{build_behavioral_globals, build_person_property_globals, GlobalsError};
diff --git a/rust/cohort-stream-processor/src/lib.rs b/rust/cohort-stream-processor/src/lib.rs
index e036a24293ad..f0efbdfc1119 100644
--- a/rust/cohort-stream-processor/src/lib.rs
+++ b/rust/cohort-stream-processor/src/lib.rs
@@ -8,7 +8,7 @@ pub mod cascade;
pub mod config;
pub mod consumers;
pub mod filters;
-pub mod hogvm;
+pub use cohort_core::hogvm;
pub mod kill_switch;
pub mod merge;
pub mod observability;
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
index c1273da9c11d..886f1ceb08bb 100644
--- a/rust/cohort-stream-processor/src/observability/metrics.rs
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -2,22 +2,17 @@
use metrics_exporter_prometheus::{PrometheusBuilder, PrometheusHandle};
+// The `cohort-core`-owned metric names this binary emits: its metric-surface manifest.
+pub use cohort_core::metrics::{
+ COHORT_ELIGIBILITY_TOTAL, COHORT_IN_CYCLE_TOTAL, FILTER_CATALOG_COHORT_PARSE_ERRORS,
+ FILTER_CATALOG_SKIPPED_LEAVES, FILTER_CATALOG_TZ_FALLBACK, STAGE1_GLOBALS_PARSE_ERROR,
+ STAGE1_HOGVM_ERROR, STAGE1_HOGVM_UNKNOWN_FUNCTION,
+};
+
/// Teams with ≥1 realtime cohort in the current catalog snapshot (gauge).
pub const FILTER_CATALOG_TEAMS: &str = "filter_catalog_teams";
/// Distinct `conditionHash`es across all teams in the current snapshot (gauge).
pub const FILTER_CATALOG_UNIQUE_CONDITIONS: &str = "filter_catalog_unique_conditions";
-/// Leaves dropped during parse, labelled by `reason` (counter).
-pub const FILTER_CATALOG_SKIPPED_LEAVES: &str = "filter_catalog_skipped_leaves_total";
-/// Cohorts skipped because their filter tree failed to parse (counter).
-pub const FILTER_CATALOG_COHORT_PARSE_ERRORS: &str = "filter_catalog_cohort_parse_errors_total";
-/// Teams whose timezone did not parse as an IANA zone and fell back to UTC (counter).
-pub const FILTER_CATALOG_TZ_FALLBACK: &str = "filter_catalog_tz_fallback_total";
-
-/// Cohorts classified by composition eligibility at freeze, labelled by `class` (counter).
-pub const COHORT_ELIGIBILITY_TOTAL: &str = "cohort_eligibility_total";
-/// Cohorts excluded because they sit in a cohort-reference cycle (counter).
-pub const COHORT_IN_CYCLE_TOTAL: &str = "cohort_in_cycle_total";
-
/// 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";
@@ -204,16 +199,6 @@ pub const TOKIO_IDLE_BLOCKING_THREADS: &str = "tokio_idle_blocking_threads";
/// Tasks waiting for a blocking thread (gauge).
pub const TOKIO_BLOCKING_QUEUE_DEPTH: &str = "tokio_blocking_queue_depth";
-/// Cohort bytecode invoked a symbol with no registered native (counter). The function name is
-/// logged, not labelled, to keep cardinality bounded.
-pub const STAGE1_HOGVM_UNKNOWN_FUNCTION: &str = "stage1_hogvm_unknown_function_total";
-/// Any other VM/program failure during cohort evaluation, coerced to `false`, labelled by `reason`
-/// (a bounded semantic bucket: `type_coercion`|`stack`|`program`|`runtime`|… — see
-/// `vm_error_reason`) (counter).
-pub const STAGE1_HOGVM_ERROR: &str = "stage1_hogvm_error_total";
-/// `properties`/`person_properties` JSON parse failure, labelled by `field` (counter).
-pub const STAGE1_GLOBALS_PARSE_ERROR: &str = "stage1_globals_parse_error_total";
-
/// Partitions with a live worker channel registered on the router (gauge).
pub const PARTITIONS_ACTIVE: &str = "partitions_active";
/// Messages dropped while routing (no live worker), labelled by `reason` (counter).
diff --git a/rust/cohort-stream-processor/src/partitions/mod.rs b/rust/cohort-stream-processor/src/partitions/mod.rs
index 28b320f16df9..e1cc10eabef5 100644
--- a/rust/cohort-stream-processor/src/partitions/mod.rs
+++ b/rust/cohort-stream-processor/src/partitions/mod.rs
@@ -9,12 +9,13 @@ pub mod backpressure;
pub mod follower;
pub mod intake;
pub mod offset_tracker;
-pub mod partitioner;
pub mod pause;
pub mod rebalance;
pub mod router;
pub mod shuffle_message;
+pub use cohort_core::partitioner;
+
pub use backpressure::Backpressure;
pub use follower::{Follower, FollowerSet, PartitionMirror};
pub use intake::{Admission, MeteredReceiver, PartitionIntake};
diff --git a/rust/cohort-stream-processor/src/stage1/mod.rs b/rust/cohort-stream-processor/src/stage1/mod.rs
index 90029c8dde3a..180b985c1b3f 100644
--- a/rust/cohort-stream-processor/src/stage1/mod.rs
+++ b/rust/cohort-stream-processor/src/stage1/mod.rs
@@ -2,17 +2,18 @@
//! when a leaf predicate flips. State is keyed by a derived `leaf_state_key`, not `condition_hash`
//! alone, because the bytecode omits the window and threshold.
-pub mod bucket_tz;
pub mod compressed_history;
pub mod daily;
-pub mod key;
pub mod person_record;
-pub mod pick_state;
pub mod predicate;
pub mod state;
-pub mod time;
pub mod transition;
+pub use cohort_core::bucket_tz;
+pub use cohort_core::leaf_state::key;
+pub use cohort_core::leaf_state::select as pick_state;
+pub use cohort_core::timestamp as time;
+
pub use person_record::{
apply_eval, apply_skip_eval, apply_stale, decide, CatalogFingerprint, Decision, DedupCoords,
Freshness, MatchedSet, PersonDedup, PersonRecord, PersonRecordCodecError, PriorRecord,
diff --git a/rust/cohort-stream-processor/src/stage1/person_record.rs b/rust/cohort-stream-processor/src/stage1/person_record.rs
index 1251cde5db7a..a633778b9ed3 100644
--- a/rust/cohort-stream-processor/src/stage1/person_record.rs
+++ b/rust/cohort-stream-processor/src/stage1/person_record.rs
@@ -25,6 +25,8 @@ use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use uuid::Uuid;
+pub use cohort_core::fingerprint::CatalogFingerprint;
+
use crate::stage1::state::{dedup_is_replay, dedup_record, AppliedOffsets};
use crate::stage1::transition::TransitionKind;
@@ -88,39 +90,6 @@ impl PropsFingerprint {
}
}
-/// 128 bits of SHA-256 over the concatenation of a team's `person_conditions_ordered` (its sorted
-/// person condition hashes). Two catalog snapshots with the same person conditions produce the same
-/// fingerprint; adding, removing, or changing a person condition changes it. Empty conditions hash
-/// the empty input, a stable constant.
-///
-/// A content fingerprint, so a no-op catalog refresh (same conditions) does not invalidate stored
-/// records.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub struct CatalogFingerprint(pub u128);
-
-impl CatalogFingerprint {
- /// Fingerprint the already-sorted person condition hashes. The input must be sorted (as
- /// `person_conditions_ordered` is) so a permutation of the same conditions yields one value.
- pub fn of_sorted(conditions: &[[u8; 16]]) -> Self {
- let mut hasher = Sha256::new();
- for condition in conditions {
- hasher.update(condition);
- }
- let digest = hasher.finalize();
- Self(u128::from_le_bytes(
- digest[..16].try_into().expect("SHA-256 yields 32 bytes"),
- ))
- }
-
- fn to_bytes(self) -> [u8; 16] {
- self.0.to_le_bytes()
- }
-
- fn from_bytes(bytes: [u8; 16]) -> Self {
- Self(u128::from_le_bytes(bytes))
- }
-}
-
/// A sorted, deduplicated set of condition hashes that currently evaluate TRUE for a person. The
/// sortedness is upheld by the constructors, so a stored record's bytes are canonical and
/// [`Self::contains`] is a binary search.
@@ -558,7 +527,7 @@ fn encode(record: &PersonRecord) -> Vec<u8> {
out.extend_from_slice(&record.stamp.ms.to_be_bytes());
out.extend_from_slice(&record.stamp.offset.to_be_bytes());
out.extend_from_slice(&record.props_fingerprint.to_bytes());
- out.extend_from_slice(&record.catalog_fingerprint.to_bytes());
+ out.extend_from_slice(&record.catalog_fingerprint.0.to_le_bytes());
write_u32(&mut out, record.matched.len());
for hash in record.matched.iter() {
@@ -599,7 +568,8 @@ fn decode(bytes: &[u8]) -> Result<PersonRecord, PersonRecordCodecError> {
offset: cur.take_i64("stamp.offset")?,
};
let props_fingerprint = PropsFingerprint::from_bytes(cur.take_16("props_fingerprint")?);
- let catalog_fingerprint = CatalogFingerprint::from_bytes(cur.take_16("catalog_fingerprint")?);
+ let catalog_fingerprint =
+ CatalogFingerprint(u128::from_le_bytes(cur.take_16("catalog_fingerprint")?));
let matched_count = cur.take_u32("matched.count")? as usize;
let mut matched = Vec::with_capacity(matched_count.min(1024));
diff --git a/rust/cohort-stream-processor/src/stage1/state.rs b/rust/cohort-stream-processor/src/stage1/state.rs
index b1161de5af6c..bda553109f16 100644
--- a/rust/cohort-stream-processor/src/stage1/state.rs
+++ b/rust/cohort-stream-processor/src/stage1/state.rs
@@ -5,31 +5,7 @@ use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
-/// Which state representation a leaf uses.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-pub enum StateVariant {
- /// `performed_event`: a single "has any matching event in window" bit.
- BehavioralSingle,
- /// `performed_event_multiple` with a `1..=180`-day window: dense per-calendar-day counts.
- BehavioralDailyBuckets,
- /// `performed_event_multiple` with a window over 180 days: sparse run-length per-calendar-day
- /// counts.
- BehavioralCompressedHistory,
- /// A person-property filter: a last-write-wins boolean.
- PersonProperty,
-}
-
-impl StateVariant {
- /// The metric-label / log form.
- pub fn as_str(self) -> &'static str {
- match self {
- Self::BehavioralSingle => "behavioral_single",
- Self::BehavioralDailyBuckets => "behavioral_daily_buckets",
- Self::BehavioralCompressedHistory => "behavioral_compressed_history",
- Self::PersonProperty => "person_property",
- }
- }
-}
+pub use cohort_core::leaf_state::StateVariant;
/// The incremental per-`(team_id, leaf_state_key, person_id)` state a leaf maintains.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
diff --git a/rust/cohort-stream-processor/src/stage2/evaluator.rs b/rust/cohort-stream-processor/src/stage2/evaluator.rs
index a3aaebe17e1c..1647506dc596 100644
--- a/rust/cohort-stream-processor/src/stage2/evaluator.rs
+++ b/rust/cohort-stream-processor/src/stage2/evaluator.rs
@@ -91,10 +91,10 @@ mod tests {
use serde_json::Value;
use super::*;
- use crate::filters::tree::{CohortLeaf, CohortRefLeafConfig, PersonLeafConfig};
- use crate::filters::CohortId;
+ use crate::filters::tree::{CohortLeaf, CohortRefLeafConfig, CohortTree, PersonLeafConfig};
+ use crate::filters::{CohortId, TeamId};
use crate::stage1::pick_state::PredicateOp;
- use crate::stage2::eligibility::condition_negation;
+ use crate::stage2::{classify, CohortEligibility, CohortParseFlags, ExcludedReason};
fn lsk(byte: u8) -> LeafStateKey {
LeafStateKey([byte; 16])
@@ -133,6 +133,32 @@ mod tests {
FilterNode::Group { op, children }
}
+ fn classifier_excludes_top_level_negation(root: &FilterNode) -> bool {
+ fn state_keyed_leaf_count(node: &FilterNode) -> u32 {
+ match node {
+ FilterNode::Group { children, .. } => {
+ children.iter().map(state_keyed_leaf_count).sum()
+ }
+ FilterNode::Leaf(leaf) => u32::from(leaf.leaf_state_key().is_some()),
+ }
+ }
+
+ let tree = CohortTree {
+ cohort_id: CohortId(1),
+ team_id: TeamId(1),
+ root: root.clone(),
+ };
+ let flags = CohortParseFlags {
+ state_keyed_leaf_count: state_keyed_leaf_count(root),
+ has_cohort_ref: false,
+ has_dropped_leaf: false,
+ };
+ matches!(
+ classify(&tree, &flags),
+ CohortEligibility::Excluded(ExcludedReason::TopLevelNegation)
+ )
+ }
+
fn person_meta() -> LeafStateMeta {
LeafStateMeta {
variant: StateVariant::PersonProperty,
@@ -516,7 +542,7 @@ mod tests {
let leaf = person_leaf_neg(lsk(1), neg);
for &op in &ops {
let tree = group(op, vec![leaf.clone()]);
- if !condition_negation(&tree) {
+ if !classifier_excludes_top_level_negation(&tree) {
assert!(
!evaluate_tree(&tree, &empty, &no_refs()),
"depth=1, op={op:?}, neg={neg}",
@@ -532,7 +558,7 @@ mod tests {
let b = person_leaf_neg(lsk(2), neg_b);
for &op in &ops {
let tree = group(op, vec![a.clone(), b.clone()]);
- if !condition_negation(&tree) {
+ if !classifier_excludes_top_level_negation(&tree) {
assert!(
!evaluate_tree(&tree, &empty, &no_refs()),
"depth=1, op={op:?}, neg_a={neg_a}, neg_b={neg_b}",
@@ -555,7 +581,7 @@ mod tests {
outer_op,
vec![group(inner_op, vec![a.clone(), b.clone()]), c.clone()],
);
- if !condition_negation(&tree) {
+ if !classifier_excludes_top_level_negation(&tree) {
assert!(
!evaluate_tree(&tree, &empty, &no_refs()),
"depth=2, outer={outer_op:?}, inner={inner_op:?}, \
diff --git a/rust/cohort-stream-processor/src/stage2/mod.rs b/rust/cohort-stream-processor/src/stage2/mod.rs
index 638fb670476a..28400d96efce 100644
--- a/rust/cohort-stream-processor/src/stage2/mod.rs
+++ b/rust/cohort-stream-processor/src/stage2/mod.rs
@@ -1,9 +1,9 @@
//! Stage 2: per-person Boolean composition of a cohort's leaves into membership flips.
-pub mod eligibility;
pub mod evaluator;
pub mod state;
+pub use cohort_core::eligibility;
pub use eligibility::{classify, CohortEligibility, CohortParseFlags, ExcludedReason};
pub use evaluator::{evaluate_tree, leaf_membership};
pub use state::Stage2State;
diff --git a/rust/cohort-stream-processor/src/workers/stage2_gc.rs b/rust/cohort-stream-processor/src/workers/stage2_gc.rs
index 140f3dc6f8df..dae3488c0e1a 100644
--- a/rust/cohort-stream-processor/src/workers/stage2_gc.rs
+++ b/rust/cohort-stream-processor/src/workers/stage2_gc.rs
@@ -21,8 +21,8 @@
use metrics::counter;
use tracing::warn;
-use crate::filters::manager::{CatalogHandle, FilterCatalog};
-use crate::filters::{CohortId, TeamId};
+use crate::filters::manager::CatalogHandle;
+use crate::filters::{CohortId, FilterCatalog, TeamId};
use crate::observability::metrics::{
STAGE2_ORPHAN_GC_KEYS_DELETED_TOTAL, STAGE2_ORPHAN_GC_KEYS_SCANNED_TOTAL,
STAGE2_ORPHAN_GC_SKIPPED_TOTAL, STAGE2_ORPHAN_GC_UNDECODABLE_KEYS_TOTAL,