: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(cohorts): share stage-2 person inputs across their cohorts (#97425)
Matheus Batista302bf6a67185
diff --git a/rust/cohort-stream-processor/clippy.toml b/rust/cohort-stream-processor/clippy.tomlindex 98bc00df68a2..14849f84636b 100644--- a/rust/cohort-stream-processor/clippy.toml+++ b/rust/cohort-stream-processor/clippy.toml@@ -8,6 +8,9 @@ disallowed-methods = [{ path = "cohort_stream_processor::store::rocks::CohortStore::get", reason = "async code must read through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },{ path = "cohort_stream_processor::store::rocks::CohortStore::get_behavioral", reason = "async code must read through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },{ path = "cohort_stream_processor::store::rocks::CohortStore::multi_get_behavioral", reason = "async code must read through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },+ { path = "cohort_stream_processor::store::rocks::CohortStore::get_person_record", reason = "async code must read through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },+ { path = "cohort_stream_processor::store::rocks::CohortStore::multi_get_person_records", reason = "async code must read through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },+ { path = "cohort_stream_processor::store::rocks::CohortStore::read_event_snapshot", reason = "async code must read through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },{ path = "cohort_stream_processor::store::rocks::CohortStore::get_stage2", reason = "async code must read through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },{ path = "cohort_stream_processor::store::rocks::CohortStore::multi_get_stage2", reason = "async code must read through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },{ path = "cohort_stream_processor::store::rocks::CohortStore::write_batch", reason = "async code must write through StoreHandle::commit; sync contexts need a module-level allow — see store/handle.rs" },diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rsindex d96946fe26e9..d9fb49b51704 100644--- a/rust/cohort-stream-processor/src/observability/metrics.rs+++ b/rust/cohort-stream-processor/src/observability/metrics.rs@@ -148,9 +148,11 @@ pub const STORE_OFFLOAD_QUEUE_WAIT_DURATION_SECONDS: &str =/// Execution time of the offloaded op inside the blocking closure, labelled by `op` (histogram,/// seconds) — excludes permit and queue waits, so it is the pure on-thread store cost.pub const STORE_OFFLOAD_EXEC_DURATION_SECONDS: &str = "store_offload_exec_duration_seconds";-/// Store ops currently executing inside a blocking closure, labelled by `lane`-/// (`event`|`maintenance`|`write`|`section`) (gauge). Maintained inside the closure so it stays-/// correct even if the caller future is dropped mid-flight.+/// Store ops currently executing inside a blocking closure, labelled by `lane` (gauge). The label is+/// the permit lane the op holds (`event`|`maintenance`), or `write` and `section` for the permit-free+/// write and stats-snapshot offloads, so `lane="maintenance"` is the maintenance permits in use,+/// sections included. Maintained inside the closure so it stays correct even if the caller future+/// is dropped mid-flight.pub const STORE_OFFLOAD_INFLIGHT: &str = "store_offload_inflight";/// Latency of a RocksDB read, labelled by `op` (histogram, seconds). `op=get` is sampled 1-in-N@@ -554,6 +556,22 @@ pub const PERSON_SEED_REKEY_PRODUCE_FAILURE_TOTAL: &str =/// produce-failure counters before concluding produces are failing.**pub const SEED_REGISTER_REPAIRS_TOTAL: &str = "cohort_seed_register_repairs_total";+/// Persons whose Stage 2 inputs a seed apply read through shared store sections (counter).+/// Attempt-based: a held run counts its persons, and so does the redelivery that replays it.+/// **Do not divide [`STAGE2_COHORTS_EVALUATED`] by this**, because that counter is settled-based and+/// the ratio then under-reports the sharing on exactly the runs that hold. Read keys per person off+/// [`SEED_RECOMPUTE_KEYS_FETCHED_TOTAL`], which is attempt-based on both sides.+pub const SEED_RECOMPUTE_PERSONS_TOTAL: &str = "cohort_seed_recompute_persons_total";+/// Store keys those sections fetched, labelled by `source` (`behavioral`|`person_record`|`stage2`)+/// (counter). Over [`SEED_RECOMPUTE_PERSONS_TOTAL`] this is the sharing win: `person_record` holds+/// at one per person however many cohorts that person reaches.+pub const SEED_RECOMPUTE_KEYS_FETCHED_TOTAL: &str = "cohort_seed_recompute_keys_fetched_total";+/// Raw value bytes one batched read returned, labelled by the same `source` (histogram, bytes).+/// **A key limit does not bound bytes**, because behavioral values grow with window length, so read+/// this before assuming the read plan has a memory ceiling. A miss records a real `0`, so prefer the+/// upper quantiles while a backfill sweeps persons it finds nothing for.+pub const SEED_RECOMPUTE_CHUNK_BYTES: &str = "cohort_seed_recompute_chunk_bytes";+/// Seeds applied as one run, labelled by `kind` (histogram). The p50 is the batching win: `1` means/// every seed still pays its own produce round trip.pub const SEED_APPLY_RUN_SIZE: &str = "cohort_seed_apply_run_size";@@ -940,6 +958,18 @@ mod tests {SEED_REGISTER_REPAIRS_TOTAL,"cohort_seed_register_repairs_total");+ assert_eq!(+ SEED_RECOMPUTE_PERSONS_TOTAL,+ "cohort_seed_recompute_persons_total"+ );+ assert_eq!(+ SEED_RECOMPUTE_KEYS_FETCHED_TOTAL,+ "cohort_seed_recompute_keys_fetched_total",+ );+ assert_eq!(+ SEED_RECOMPUTE_CHUNK_BYTES,+ "cohort_seed_recompute_chunk_bytes"+ );assert_eq!(SEED_APPLY_RUN_SIZE, "cohort_seed_apply_run_size");assert_eq!(SEED_APPLY_RUN_DURATION_SECONDS,diff --git a/rust/cohort-stream-processor/src/store/handle.rs b/rust/cohort-stream-processor/src/store/handle.rsindex d8bd1f93f768..cdc8140170ac 100644--- a/rust/cohort-stream-processor/src/store/handle.rs+++ b/rust/cohort-stream-processor/src/store/handle.rs@@ -181,14 +181,17 @@ impl StoreHandle {self.offload(op, LANE_WRITE, None, f).await}- /// Run a whole infallible sync section (reads + writes mixed) under the [`LANE_SECTION`] label:- /// offloads under Maintenance and All, inline under Off. `permits` is the lane the section draws- /// from — the maintenance lane for [`Self::run_section`], `None` for the permit-free- /// observability snapshot ([`Self::stats_snapshot`]). Keeping stats on this executor is what lets- /// `mode` stay matched in exactly the three executors (`read`, `write`, `section`).+ /// Run a whole infallible sync section (reads + writes mixed): offloads under Maintenance and+ /// All, inline under Off. `permits` is the lane the section draws from, and `lane_label` is how+ /// the in-flight gauge names it: the maintenance lane for [`Self::run_section`], `None` under+ /// [`LANE_SECTION`] for the permit-free observability snapshot ([`Self::stats_snapshot`]). The+ /// label follows the permit so that `store_offload_inflight{lane="maintenance"}` counts every+ /// holder of a maintenance permit, sections included. Keeping stats on this executor is what+ /// lets `mode` stay matched in exactly the three executors (`read`, `write`, `section`).async fn section<T, F>(&self,op: &'static str,+ lane_label: &'static str,permits: Option<Arc<Semaphore>>,f: F,) -> Result<T, StoreError>@@ -201,7 +204,7 @@ impl StoreHandle {}// A section's closure is infallible (it returns `T`, not `Result`); wrap it so it shares the// one offload path. Only teardown cancellation can then make the outer result an `Err`.- self.offload(op, LANE_SECTION, permits, move |store| Ok(f(store)))+ self.offload(op, lane_label, permits, move |store| Ok(f(store))).await}@@ -503,8 +506,8 @@ impl StoreHandle {/// Run a self-contained sync store state machine (mixed reads and writes) on the blocking pool:/// the sanctioned context for merge drain/apply and GC, whose deep sync cores are not worth- /// async-ifying. Draws a maintenance permit. The result is `Err` only on runtime-teardown- /// cancellation ([`StoreError::OffloadCancelled`]).+ /// async-ifying. Draws a maintenance permit, and counts on the in-flight gauge under that lane.+ /// The result is `Err` only on runtime-teardown cancellation ([`StoreError::OffloadCancelled`]).////// Keep each section individually short: a started blocking task cannot be cancelled, and/// shutdown joins started tasks — a long section extends the effective drain time.@@ -513,7 +516,8 @@ impl StoreHandle {T: Send + 'static,F: FnOnce(&CohortStore) -> T + Send + 'static,{- self.section(op, self.maintenance_permits.clone(), f).await+ self.section(op, LANE_MAINTENANCE, self.maintenance_permits.clone(), f)+ .await}/// Snapshot the store's cache tickers and per-CF sizes. No permit — observability must not queue@@ -523,8 +527,10 @@ impl StoreHandle {pub async fn stats_snapshot(&self) -> Result<StoreStats, StoreError> {// Routed through `section` with the `None` lane (no permit) so the mode match stays in the// three executors rather than being open-coded here.- self.section("stats_snapshot", None, |store| store.stats_snapshot())- .await+ self.section("stats_snapshot", LANE_SECTION, None, |store| {+ store.stats_snapshot()+ })+ .await}/// SYNCHRONOUS escape hatch: delete one partition's state on the caller's thread, bypassing thediff --git a/rust/cohort-stream-processor/src/workers/mod.rs b/rust/cohort-stream-processor/src/workers/mod.rsindex f141d6d5168d..41052bc5eefa 100644--- a/rust/cohort-stream-processor/src/workers/mod.rs+++ b/rust/cohort-stream-processor/src/workers/mod.rs@@ -11,6 +11,7 @@ pub mod seed_path;pub mod seed_run;pub mod stage2_gc;pub mod stage2_path;+pub mod stage2_person_inputs;pub mod sweep_callback;pub mod worker;diff --git a/rust/cohort-stream-processor/src/workers/seed_apply.rs b/rust/cohort-stream-processor/src/workers/seed_apply.rsindex b2fe899bff73..e5caa939b557 100644--- a/rust/cohort-stream-processor/src/workers/seed_apply.rs+++ b/rust/cohort-stream-processor/src/workers/seed_apply.rs@@ -49,9 +49,9 @@ use crate::workers::merge_path::MergeWorkerDeps;use crate::workers::reconcile::{ReconcileQueue, SupersedeOutcome};use crate::workers::seed_run::{Admitted, OffsetSpan, SeedGroup, SeedKind, SeedOffset, SeedRun};use crate::workers::stage2_path::{- commit_stage2_writes, diff_single_leaf_registers, recompute_stage2, FoldedLeaf, RegisterDiff,- Stage2Recompute,+ commit_stage2_writes, diff_single_leaf_registers, FoldedLeaf, RegisterDiff, Stage2Recompute,};+use crate::workers::stage2_person_inputs::recompute_stage2_by_person;use crate::workers::worker::{first_cascades, produce_cascades, produce_membership, transition_metric_label,};@@ -855,14 +855,14 @@ impl Scheduled {let Some(filters) = deps.team(team_id) else {continue;};- let mut composed = recompute_stage2(+ let mut composed = recompute_stage2_by_person(deps.partition_id,deps.handle,+ team_id,filters,&leaves,stamp.now_ms,&stamp.last_updated,- ReadLane::Maintenance,).await.map_err(SeedHold::store(ApplyStage::Recompute))?;diff --git a/rust/cohort-stream-processor/src/workers/seed_path.rs b/rust/cohort-stream-processor/src/workers/seed_path.rsindex 3a5b51cf6505..cccd1fad95b6 100644--- a/rust/cohort-stream-processor/src/workers/seed_path.rs+++ b/rust/cohort-stream-processor/src/workers/seed_path.rs@@ -9,7 +9,8 @@//! after the produce acks. A failed produce is therefore re-derived while replay still folds the//! leaf. If the leaf expires before replay and the fold drops it, this repair no longer applies;//! eviction and reconcile remain its recovery paths. Composed bits come from-//! [`recompute_stage2`](crate::workers::stage2_path::recompute_stage2); single-leaf ones from+//! [`recompute_stage2_by_person`](crate::workers::stage2_person_inputs::recompute_stage2_by_person),+//! which reads each person once for all their cohorts; single-leaf ones from//! [`diff_single_leaf_registers`](crate::workers::stage2_path::diff_single_leaf_registers), which//! is why `Unchanged` leaves still take part. The replay mints no transition, so the persisted//! register is the only record of what downstream was told. Store and produce failures hold thediff --git a/rust/cohort-stream-processor/src/workers/seed_run.rs b/rust/cohort-stream-processor/src/workers/seed_run.rsindex a062199d7bf8..4f35274a8745 100644--- a/rust/cohort-stream-processor/src/workers/seed_run.rs+++ b/rust/cohort-stream-processor/src/workers/seed_run.rs@@ -163,8 +163,9 @@ impl Default for RunBudget {/// full run of leaves that can emit nothing slip under the ceiling.////// It is a ceiling on what a run retains and emits, not on the reads inside each composed-/// evaluation: those scale with that cohort's tree exactly as under the per-seed apply, and the-/// maintenance lane's permits are what meter them.+/// evaluation: those scale with the trees of every cohort a person is in. The maintenance lane+/// still meters them, one permit per bounded section of a person's reads rather than one per+/// evaluation (see [`stage2_person_inputs`](crate::workers::stage2_person_inputs)).////// A seed the catalog cannot place weighs one, so a run of them is still bounded by the seed cap/// rather than by nothing. Control and skip seeds weigh nothing: they are always their own group.diff --git a/rust/cohort-stream-processor/src/workers/stage2_path.rs b/rust/cohort-stream-processor/src/workers/stage2_path.rsindex 6e3bed5beb78..f463e6da71f0 100644--- a/rust/cohort-stream-processor/src/workers/stage2_path.rs+++ b/rust/cohort-stream-processor/src/workers/stage2_path.rs@@ -24,13 +24,15 @@ use crate::stage1::person_record::PersonRecord;use crate::stage1::state::{Stage1State, StateVariant, StatefulRecord};use crate::stage2::evaluator::{evaluate_tree, leaf_membership};use crate::stage2::state::{Stage2Ownership, Stage2State};-use crate::stage2::CohortEligibility;use crate::store::{BehavioralKey, PersonRecordKey, ReadLane, Stage2Key, StagedBatch, StoreError, StoreHandle,};+use crate::workers::stage2_person_inputs::ReferenceSource;/// `affected_leaves` is the touched `(leaf, person)` set; `lane` is the read lane every recompute-/// read runs on (`Maintenance` on the seed path, so backfill never contends with live reads).+/// read runs on. Every caller passes `Event`: the seed paths, which read on `Maintenance`, go+/// through [`recompute_stage2_by_person`](super::stage2_person_inputs::recompute_stage2_by_person)+/// instead, whose store sections draw the maintenance permit.pub async fn compose_stage2(partition_id: u16,handle: &StoreHandle,@@ -86,6 +88,57 @@ impl Stage2Recompute {self.composed.add(other.composed);self.repairs.add(other.repairs);}++ /// Both recompute orders call this, so what a composed evaluation emits cannot depend on+ /// whether the caller walked cohorts or persons.+ pub(super) fn record_pair(+ &mut self,+ pair: RecomputedPair,+ diff: &RecomputeDiff,+ event_ms: i64,+ last_updated: &str,+ ) {+ self.evaluated += 1;+ if diff.flipped() {+ self.composed.count(diff.status());+ self.changes.push(CohortMembershipChange {+ team_id: pair.team_id,+ cohort_id: pair.cohort_id.0,+ person_id: pair.person_id.to_string(),+ last_updated: last_updated.to_string(),+ status: diff.status(),+ origin: None,+ run_id: None,+ });+ }+ if diff.requires_write() {+ // Write `false` rather than deleting so the retracted pair stays enumerable by the+ // reconcile scan. A no-flip transferred fallback is rewritten once so receiver+ // evaluation claims ownership.+ self.writes.push((+ diff.stage2_key,+ Stage2State {+ in_cohort: diff.new_bit,+ last_evaluated_at_ms: event_ms,+ },+ ));+ }+ }+}++#[cfg(test)]+impl Stage2Recompute {+ /// Pairs composed, which is what `STAGE2_COHORTS_EVALUATED` reports. A pair that flips nothing+ /// leaves no other trace for a test to compare.+ pub(super) fn evaluated(&self) -> u64 {+ self.evaluated+ }+}++pub(super) struct RecomputedPair {+ pub team_id: i32,+ pub cohort_id: CohortId,+ pub person_id: Uuid,}/// Per-status flip counts, kept so [`Stage2Recompute::record_metrics`] can attribute each half of a@@ -160,8 +213,10 @@ impl RepairCounts {}}-/// The read-only half of [`compose_stage2`].-pub(crate) async fn recompute_stage2(+/// The read-only half of [`compose_stage2`]: one cohort at a time, in `(cohort, person)` order.+/// The seed paths use+/// [`recompute_stage2_by_person`](super::stage2_person_inputs::recompute_stage2_by_person) instead.+pub(super) async fn recompute_stage2(partition_id: u16,handle: &StoreHandle,filters: &TeamFilters,@@ -179,51 +234,26 @@ pub(crate) async fn recompute_stage2(}}- let mut changes = Vec::new();- let mut writes: Vec<(Stage2Key, Stage2State)> = Vec::new();- let mut evaluated: u64 = 0;- let mut composed = StatusCounts::default();-+ let mut recompute = Stage2Recompute::default();for (cohort_id, person_id) in affected {let Some(tree) = filters.cohorts.get(&cohort_id) else {continue;};let diff = recompute_and_diff(partition_id, person_id, tree, filters, handle, lane).await?;- evaluated += 1;- if diff.flipped() {- composed.count(diff.status());- changes.push(CohortMembershipChange {+ recompute.record_pair(+ RecomputedPair {team_id: tree.team_id.0,- cohort_id: cohort_id.0,- person_id: person_id.to_string(),- last_updated: last_updated.to_string(),- status: diff.status(),- origin: None,- run_id: None,- });- }- if diff.requires_write() {- // Write `false` rather than deleting so the retracted pair stays enumerable by the- // reconcile scan. A no-flip transferred fallback is rewritten once so receiver- // evaluation claims ownership.- writes.push((- diff.stage2_key,- Stage2State {- in_cohort: diff.new_bit,- last_evaluated_at_ms: event_ms,- },- ));- }+ cohort_id,+ person_id,+ },+ &diff,+ event_ms,+ last_updated,+ );}- Ok(Stage2Recompute {- changes,- writes,- evaluated,- composed,- ..Default::default()- })+ Ok(recompute)}/// One leaf a seed run folded, with the membership its resulting state implies. The caller holds@@ -483,6 +513,15 @@ pub(crate) struct RecomputeDiff {}impl RecomputeDiff {+ pub(super) fn new(new_bit: bool, prior: PriorStage2State, stage2_key: Stage2Key) -> Self {+ Self {+ new_bit,+ prior_bit: prior.in_cohort,+ stage2_key,+ settles_transfer_fallback: prior.ownership == Stage2Ownership::TransferredFallback,+ }+ }+pub fn flipped(&self) -> bool {self.new_bit != self.prior_bit}@@ -529,13 +568,8 @@ pub(crate) async fn recompute_and_diff(cohort_id: tree.cohort_id.0 as u64,person_id,};- let prior = read_prior_stage2_state(handle, &stage2_key, lane).await?;- Ok(RecomputeDiff {- new_bit,- prior_bit: prior.in_cohort,- stage2_key,- settles_transfer_fallback: prior.ownership == Stage2Ownership::TransferredFallback,- })+ let prior = read_prior_stage2(handle.get_stage2(&stage2_key, lane).await?);+ Ok(RecomputeDiff::new(new_bit, prior, stage2_key))}/// Compose one cohort for one person. A leaf with absent or undecodable state reads as non-member;@@ -714,11 +748,10 @@ async fn resolve_ref_membership(let mut single_leaf_refs: Vec<(CohortId, LeafStateKey)> = Vec::new();let mut composable_refs: Vec<CohortId> = Vec::new();for ref_id in ref_ids {- match filters.eligibility.get(&ref_id) {- Some(CohortEligibility::SingleLeaf(lsk)) => single_leaf_refs.push((ref_id, *lsk)),- Some(elig) if elig.writes_cf_stage2() => composable_refs.push(ref_id),- // Excluded, cyclic, or absent from the catalog: non-member.- _ => {+ match ReferenceSource::classify(filters, ref_id) {+ ReferenceSource::Leaf(lsk) => single_leaf_refs.push((ref_id, lsk)),+ ReferenceSource::Stored => composable_refs.push(ref_id),+ ReferenceSource::NonMember => {ref_membership.insert(ref_id, false);}}@@ -756,7 +789,7 @@ async fn resolve_ref_membership(}/// Decode a `cf_behavioral` value, or [`None`] for absent/undecodable rows.-fn decode_stage1_state(bytes: Option<Vec<u8>>) -> Option<Stage1State> {+pub(super) fn decode_stage1_state(bytes: Option<Vec<u8>>) -> Option<Stage1State> {let bytes = bytes?;match StatefulRecord::decode(&bytes) {Ok(record) => Some(record.state),@@ -767,36 +800,28 @@ fn decode_stage1_state(bytes: Option<Vec<u8>>) -> Option<Stage1State> {}}-#[derive(Clone, Copy)]-struct PriorStage2State {- in_cohort: bool,+/// One stored `cf_stage2` row as composition reads it. [`Default`] is the fail-closed reading for+/// an absent or corrupt row.+#[derive(Debug, Clone, Copy, Default)]+pub(super) struct PriorStage2State {+ pub in_cohort: bool,ownership: Stage2Ownership,}/// Decode both the logical prior bit and its ownership. Missing or corrupt rows keep the existing/// fail-closed `false` behavior and are never mistaken for a transferred fallback.-async fn read_prior_stage2_state(- handle: &StoreHandle,- key: &Stage2Key,- lane: ReadLane,-) -> Result<PriorStage2State, StoreError> {- let Some(bytes) = handle.get_stage2(key, lane).await? else {- return Ok(PriorStage2State {- in_cohort: false,- ownership: Stage2Ownership::Local,- });+pub(super) fn read_prior_stage2(bytes: Option<Vec<u8>>) -> PriorStage2State {+ let Some(bytes) = bytes else {+ return PriorStage2State::default();};match Stage2State::decode_with_ownership(&bytes) {- Ok((state, ownership)) => Ok(PriorStage2State {+ Ok((state, ownership)) => PriorStage2State {in_cohort: state.in_cohort,ownership,- }),+ },Err(_) => {counter!(STAGE2_STATE_DECODE_ERROR).increment(1);- Ok(PriorStage2State {- in_cohort: false,- ownership: Stage2Ownership::Local,- })+ PriorStage2State::default()}}}@@ -816,7 +841,7 @@ fn decode_stage2_bit(bytes: Option<Vec<u8>>) -> bool {}/// Collect every state-keyed leaf's [`LeafStateKey`] in pre-order.-fn collect_leaf_state_keys(node: &FilterNode, out: &mut Vec<LeafStateKey>) {+pub(super) fn collect_leaf_state_keys(node: &FilterNode, out: &mut Vec<LeafStateKey>) {match node {FilterNode::Group { children, .. } => {for child in children {@@ -833,7 +858,7 @@ fn collect_leaf_state_keys(node: &FilterNode, out: &mut Vec<LeafStateKey>) {/// Collect referenced cohort ids (with duplicates; the caller dedups). Negation is left to/// `evaluate_tree`, so a referent referenced twice with opposite negation reads one bit.-fn collect_cohort_refs(node: &FilterNode, out: &mut Vec<CohortId>) {+pub(super) fn collect_cohort_refs(node: &FilterNode, out: &mut Vec<CohortId>) {match node {FilterNode::Group { children, .. } => {for child in children {@@ -932,10 +957,15 @@ mod tests {}fn freeze(values: Vec<Value>) -> TeamFilters {+ freeze_for_team(TEAM as i32, values)+ }++ /// Freeze one cohort under an explicit team, so a test can prove state is keyed by team.+ fn freeze_for_team(team_id: i32, values: Vec<Value>) -> TeamFilters {let cohort = json!({ "properties": { "type": "AND", "values": values } });let mut builder = TeamFiltersBuilder::default();builder- .add_cohort(CohortId(1), TeamId(TEAM as i32), &cohort)+ .add_cohort(CohortId(1), TeamId(team_id), &cohort).unwrap();builder.freeze(UTC)}@@ -2018,4 +2048,652 @@ mod tests {);assert_eq!(diff.stage1_writes.len(), 1, "only cohort 2 had no row");}++ // ---- Sharing one person's inputs across their cohorts ----+ //+ // Every test below holds `recompute_stage2_by_person` to the cohort-ordered path as an oracle+ // over the same store, then asserts what the shared read had to get right for the two to agree.++ use crate::workers::stage2_person_inputs::{recompute_stage2_by_person, READ_CHUNK_KEYS};++ /// Run both recompute orders over the same store and return the agreed result. Neither commits,+ /// so running them back to back reads the same durable state twice.+ async fn recompute_both_ways(+ store: &CohortStore,+ filters: &TeamFilters,+ team_id: i32,+ affected: &[(LeafStateKey, Uuid)],+ ) -> Stage2Recompute {+ let handle = handle(store);+ let cohort_ordered = recompute_stage2(+ PARTITION,+ &handle,+ filters,+ affected,+ EVENT_MS,+ TS,+ ReadLane::Maintenance,+ )+ .await+ .unwrap();+ let by_person = recompute_stage2_by_person(+ PARTITION,+ &handle,+ TeamId(team_id),+ filters,+ affected,+ EVENT_MS,+ TS,+ )+ .await+ .unwrap();++ assert_eq!(+ by_person.changes, cohort_ordered.changes,+ "sharing a person's inputs changed which flips the run emits",+ );+ assert_eq!(+ by_person.writes, cohort_ordered.writes,+ "sharing a person's inputs changed which cf_stage2 rows the run owes",+ );+ assert_eq!(+ by_person.evaluated(),+ cohort_ordered.evaluated(),+ "sharing a person's inputs changed how many pairs the run composed",+ );+ by_person+ }++ fn compressed_leaf(op: &str, value: i64) -> Value {+ json!({+ "type": "behavioral", "value": "performed_event_multiple", "key": "$pageview",+ "time_value": 1, "time_interval": "year",+ "operator": op, "operator_value": value,+ "conditionHash": "0123456789abcdef",+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],+ })+ }++ fn compressed_state(count: u32) -> Stage1State {+ Stage1State::BehavioralCompressedHistory {+ entries: vec![(20_607, count)],+ window_start_day: 20_600,+ last_event_at_ms: EVENT_MS,+ earliest_eviction_at_ms: i64::MAX,+ }+ }++ fn statuses(recompute: &Stage2Recompute) -> Vec<(i32, MembershipStatus)> {+ recompute+ .changes+ .iter()+ .map(|change| (change.cohort_id, change.status))+ .collect()+ }++ fn other_person_leaf() -> Value {+ json!({+ "type": "person", "key": "email", "value": "[email protected]", "operator": "exact",+ "conditionHash": "0f0f0f0f0f0f0f0f",+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],+ })+ }++ /// Cohort 4 names a second person condition the record does not match, so a read that answered+ /// the record as one bit rather than per condition would enter it.+ #[tokio::test]+ async fn shared_inputs_compose_every_leaf_variant_from_one_read() {+ let (_dir, store) = temp_store();+ let filters = freeze_cascade(+ vec![+ (1, vec![behavioral_leaf(7), person_leaf()]),+ (2, vec![daily_leaf(7, "gte", 2), person_leaf()]),+ (3, vec![compressed_leaf("gte", 2), person_leaf()]),+ (4, vec![behavioral_leaf(7), other_person_leaf()]),+ ],+ false,+ );+ let single_lsk = filters.by_condition_to_lsk[&HASH]+ .iter()+ .copied()+ .find(|lsk| filters.by_lsk[lsk].variant == StateVariant::BehavioralSingle)+ .unwrap();+ let daily_lsk = filters.by_condition_to_lsk[&HASH]+ .iter()+ .copied()+ .find(|lsk| filters.by_lsk[lsk].variant == StateVariant::BehavioralDailyBuckets)+ .unwrap();+ let compressed_lsk = filters.by_condition_to_lsk[&HASH]+ .iter()+ .copied()+ .find(|lsk| filters.by_lsk[lsk].variant == StateVariant::BehavioralCompressedHistory)+ .unwrap();+ let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);+ let alice = person(1);++ write_behavioral(&store, single_lsk, alice, behavioral_match());+ write_behavioral(&store, daily_lsk, alice, daily_state(2));+ write_behavioral(&store, compressed_lsk, alice, compressed_state(2));+ write_person_record(&store, alice, &[PERSON_HASH]);++ // Cohort 4 hangs off the shared behavioral leaf, not the person condition.+ let affected = [(single_lsk, alice), (per_lsk, alice)];+ let entered = recompute_both_ways(&store, &filters, TEAM as i32, &affected).await;+ assert_eq!(+ statuses(&entered),+ vec![+ (1, MembershipStatus::Entered),+ (2, MembershipStatus::Entered),+ (3, MembershipStatus::Entered),+ ],+ "each variant's comparator still decides its own leaf, and the unmatched person \+ condition keeps cohort 4 out of the same record's answers",+ );+ // Both orders build the change through one shared `record_pair`, so only a literal pins+ // which team the shared read stamped on it.+ assert!(entered+ .changes+ .iter()+ .all(|change| change.team_id == TEAM as i32));++ // The daily leaf now misses its threshold, and only that cohort may leave.+ write_behavioral(&store, daily_lsk, alice, daily_state(1));+ for cohort in [1, 2, 3] {+ write_stage2(&store, cohort, alice, true);+ }+ let left = recompute_both_ways(&store, &filters, TEAM as i32, &affected).await;+ assert_eq!(statuses(&left), vec![(2, MembershipStatus::Left)]);+ }++ /// The referrer must read the referent's *stored* bit, not the one this run is about to write,+ /// or it emits a cascade nothing has acknowledged.+ #[tokio::test]+ async fn a_referent_recomputed_in_the_same_call_is_still_read_from_the_store() {+ let (_dir, store) = temp_store();+ let filters = freeze_cascade(+ vec![+ (1, vec![person_leaf(), cohort_ref(2)]),+ (2, vec![behavioral_leaf(7), person_leaf()]),+ ],+ true,+ );+ let beh_lsk = filters.by_condition_to_lsk[&HASH][0];+ let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);+ let alice = person(1);++ write_behavioral(&store, beh_lsk, alice, behavioral_match());+ write_person_record(&store, alice, &[PERSON_HASH]);+ // Cohort 2 will recompute to `true` in this same call; the store still says `false`.+ write_stage2(&store, 2, alice, false);++ let recompute =+ recompute_both_ways(&store, &filters, TEAM as i32, &[(per_lsk, alice)]).await;++ assert_eq!(+ statuses(&recompute),+ vec![(2, MembershipStatus::Entered)],+ "cohort 1 read the stored `false` for its referent and did not enter",+ );+ }++ /// The one reference kind whose bit comes back through the behavioral batch. Resolving it from+ /// a stored membership row instead would read every referrer of a single-leaf cohort as a+ /// non-member.+ #[tokio::test]+ async fn a_single_leaf_referent_resolves_through_its_own_leaf_and_comparator() {+ let (_dir, store) = temp_store();+ let filters = freeze_cascade(+ vec![+ (1, vec![person_leaf(), cohort_ref(3)]),+ (3, vec![daily_leaf(7, "gte", 2)]),+ ],+ true,+ );+ assert!(+ matches!(+ filters.eligibility[&CohortId(3)],+ CohortEligibility::SingleLeaf(_)+ ),+ "cohort 3 has to be the single-leaf kind for this to be the case under test",+ );+ let referent_lsk = single_leaf_lsk(&filters, 3);+ let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);+ let alice = person(1);+ write_person_record(&store, alice, &[PERSON_HASH]);++ // Below the referent's threshold: the referrer must not enter, even though the referent has+ // behavioral state and no cf_stage2 row of its own to read.+ write_behavioral(&store, referent_lsk, alice, daily_state(1));+ let below = recompute_both_ways(&store, &filters, TEAM as i32, &[(per_lsk, alice)]).await;+ assert!(+ below.changes.is_empty(),+ "the referent's own comparator says it is not a member",+ );++ write_behavioral(&store, referent_lsk, alice, daily_state(2));+ let above = recompute_both_ways(&store, &filters, TEAM as i32, &[(per_lsk, alice)]).await;+ assert_eq!(statuses(&above), vec![(1, MembershipStatus::Entered)]);+ }++ /// One referent named twice with opposite negation is one row and two consistent answers.+ #[tokio::test]+ async fn a_referent_named_twice_with_opposite_negation_reads_one_row() {+ let (_dir, store) = temp_store();+ let filters = freeze_cascade(+ vec![+ (1, vec![person_leaf(), cohort_ref(2), negated_cohort_ref(2)]),+ (2, vec![behavioral_leaf(7), person_leaf()]),+ ],+ true,+ );+ let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);+ let alice = person(1);++ write_person_record(&store, alice, &[PERSON_HASH]);+ write_stage2(&store, 2, alice, true);++ let recompute =+ recompute_both_ways(&store, &filters, TEAM as i32, &[(per_lsk, alice)]).await;+ assert!(+ !recompute.changes.iter().any(|change| change.cohort_id == 1),+ "`ref AND NOT ref` over one bit cannot be satisfied",+ );+ assert_eq!(+ recompute.evaluated(),+ 2,+ "both cohorts composed; cohort 1 just could not satisfy `ref AND NOT ref`",+ );+ }++ /// A transferred fallback is still settled on a pair that does not flip.+ #[tokio::test]+ async fn corrupt_rows_stay_non_member_and_a_transferred_fallback_still_settles() {+ let (_dir, store) = temp_store();+ let filters = freeze_cascade(+ vec![+ (1, vec![behavioral_leaf(7), person_leaf()]),+ (2, vec![daily_leaf(7, "gte", 2), person_leaf()]),+ ],+ false,+ );+ let beh_lsk = filters.by_condition_to_lsk[&HASH]+ .iter()+ .copied()+ .find(|lsk| filters.by_lsk[lsk].variant == StateVariant::BehavioralSingle)+ .unwrap();+ let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);+ let alice = person(1);++ write_behavioral(&store, beh_lsk, alice, behavioral_match());+ write_corrupt_person_record(&store, alice);+ // Cohort 1's row is already `false` and carries a transfer fallback, so the receiver has to+ // claim it even though the bit does not move.+ let key = Stage2Key {+ partition_id: PARTITION,+ team_id: TEAM,+ cohort_id: 1,+ person_id: alice,+ };+ let fallback = Stage2State {+ in_cohort: false,+ last_evaluated_at_ms: EVENT_MS,+ };+ store+ .write_batch(|b| b.put_stage2(&key, &fallback.encode_transferred_fallback()))+ .unwrap();++ let recompute =+ recompute_both_ways(&store, &filters, TEAM as i32, &[(per_lsk, alice)]).await;++ assert!(+ recompute.changes.is_empty(),+ "a corrupt person record reads every person leaf as a non-member",+ );+ assert_eq!(+ recompute.writes,+ vec![(+ key,+ Stage2State {+ in_cohort: false,+ last_evaluated_at_ms: EVENT_MS,+ }+ )],+ "the fallback row is rewritten once, and the ordinary no-flip row is left alone",+ );+ }++ /// Sharing is per person, so neither may see the other's record or leaves.+ #[tokio::test]+ async fn two_persons_in_one_call_keep_their_own_inputs() {+ let (_dir, store) = temp_store();+ let filters = freeze_cascade(+ vec![+ (1, vec![behavioral_leaf(7), person_leaf()]),+ (2, vec![behavioral_leaf(7), person_leaf()]),+ ],+ false,+ );+ let beh_lsk = filters.by_condition_to_lsk[&HASH][0];+ let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);+ let (alice, bob) = (person(1), person(2));++ write_behavioral(&store, beh_lsk, alice, behavioral_match());+ write_person_record(&store, alice, &[PERSON_HASH]);+ // Bob matches the person condition but has no behavioral state.+ write_person_record(&store, bob, &[PERSON_HASH]);++ let recompute = recompute_both_ways(+ &store,+ &filters,+ TEAM as i32,+ &[(per_lsk, alice), (per_lsk, bob)],+ )+ .await;++ assert_eq!(+ recompute+ .changes+ .iter()+ .map(|change| (change.cohort_id, change.person_id.clone()))+ .collect::<Vec<_>>(),+ vec![(1, alice.to_string()), (2, alice.to_string()),],+ "changes stay in (cohort, person) order and Bob's missing leaf keeps him out",+ );+ assert_eq!(+ recompute.evaluated(),+ 4,+ "both persons composed both cohorts"+ );+ }++ /// The same person and the same leaf under a different team must not see the first team's rows.+ #[tokio::test]+ async fn state_written_for_one_team_is_invisible_to_another() {+ let (_dir, store) = temp_store();+ let leaves = vec![behavioral_leaf(7), person_leaf()];+ let ours = freeze_for_team(TEAM as i32, leaves.clone());+ let theirs = freeze_for_team(TEAM as i32 + 1, leaves);+ let beh_lsk = ours.by_condition_to_lsk[&HASH][0];+ let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);+ let alice = person(1);++ write_behavioral(&store, beh_lsk, alice, behavioral_match());+ write_person_record(&store, alice, &[PERSON_HASH]);++ let ours_recompute =+ recompute_both_ways(&store, &ours, TEAM as i32, &[(per_lsk, alice)]).await;+ assert_eq!(+ statuses(&ours_recompute),+ vec![(1, MembershipStatus::Entered)]+ );++ let theirs_recompute =+ recompute_both_ways(&store, &theirs, TEAM as i32 + 1, &[(per_lsk, alice)]).await;+ assert!(+ theirs_recompute.changes.is_empty(),+ "the neighbouring team's keyspace holds none of this state",+ );+ }++ fn wide_behavioral_leaf(index: usize) -> Value {+ json!({+ "type": "behavioral", "value": "performed_event", "key": "$pageview",+ "time_value": 7, "time_interval": "day",+ "conditionHash": format!("beh{index:013}"),+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],+ })+ }++ fn wide_behavioral_hash(index: usize) -> [u8; 16] {+ format!("beh{index:013}").as_bytes().try_into().unwrap()+ }++ /// Widths derived from the chunk size, so the tests sit on the boundary wherever it moves:+ /// exactly one chunk catches a `<` for `<=` slip, and one past it makes the second section run.+ const CHUNK_BOUNDARY_WIDTHS: [usize; 2] = [READ_CHUNK_KEYS, READ_CHUNK_KEYS + 1];++ /// A chunk the read skipped would leave its leaves non-member and break the AND, so the entry+ /// proves every chunk landed.+ #[tokio::test]+ async fn a_cohort_wider_than_one_chunk_reads_every_leaf() {+ for leaves in CHUNK_BOUNDARY_WIDTHS {+ let (_dir, store) = temp_store();+ let filters = freeze((0..leaves).map(wide_behavioral_leaf).collect());+ let lsks: Vec<LeafStateKey> = (0..leaves)+ .map(|index| filters.by_condition_to_lsk[&wide_behavioral_hash(index)][0])+ .collect();+ let alice = person(1);+ for &lsk in &lsks {+ write_behavioral(&store, lsk, alice, behavioral_match());+ }++ let entered =+ recompute_both_ways(&store, &filters, TEAM as i32, &[(lsks[0], alice)]).await;+ assert_eq!(+ statuses(&entered),+ vec![(1, MembershipStatus::Entered)],+ "{leaves} leaves",+ );++ // The `Entered` above proves every chunk landed. This half pins that the last leaf's+ // value is read, not just its key.+ write_behavioral(+ &store,+ lsks[leaves - 1],+ alice,+ Stage1State::BehavioralSingle {+ has_match: false,+ last_event_at_ms: EVENT_MS,+ earliest_eviction_at_ms: i64::MAX,+ },+ );+ write_stage2(&store, 1, alice, true);+ let left =+ recompute_both_ways(&store, &filters, TEAM as i32, &[(lsks[0], alice)]).await;+ assert_eq!(+ statuses(&left),+ vec![(1, MembershipStatus::Left)],+ "{leaves} leaves",+ );+ }+ }++ /// The pair whose prior row already agrees is the last one, so only a read that reached the end+ /// of the key set stays silent.+ #[tokio::test]+ async fn a_person_in_more_cohorts_than_one_chunk_reads_every_prior_row() {+ for cohorts in CHUNK_BOUNDARY_WIDTHS {+ let last = cohorts as i32;+ let (_dir, store) = temp_store();+ let filters = freeze_cascade(+ (1..=last)+ .map(|id| (id, vec![behavioral_leaf(7), person_leaf()]))+ .collect(),+ false,+ );+ let beh_lsk = filters.by_condition_to_lsk[&HASH][0];+ let alice = person(1);+ write_behavioral(&store, beh_lsk, alice, behavioral_match());+ write_person_record(&store, alice, &[PERSON_HASH]);+ write_stage2(&store, last as u64, alice, true);++ let recompute =+ recompute_both_ways(&store, &filters, TEAM as i32, &[(beh_lsk, alice)]).await;++ assert_eq!(+ recompute.evaluated(),+ cohorts as u64,+ "every cohort on the leaf composed ({cohorts} cohorts)",+ );+ assert_eq!(+ recompute.changes.len(),+ cohorts - 1,+ "the one cohort whose stored bit already said `true` did not flip ({cohorts} cohorts)",+ );+ assert!(+ !recompute+ .changes+ .iter()+ .any(|change| change.cohort_id == last),+ "and it is the last cohort, whose row sits at the end of the key set",+ );+ }+ }++ /// Wide fanout over mostly shared state, with per-cohort leaves big enough that re-reading them+ /// is not free. With `referencing`, every cohort also names two referents off the seeded leaf:+ /// a single-leaf cohort, resolved through the behavioral batch, and a composable one, resolved+ /// from its stored row. Those are the reads the cohort-ordered path pays extra offloads for.+ fn wide_fixture(+ store: &CohortStore,+ cohorts: usize,+ persons: usize,+ referencing: bool,+ ) -> (TeamFilters, Vec<(LeafStateKey, Uuid)>) {+ let shared = 0;+ let single_leaf_referent = cohorts as i32 + 1;+ let composable_referent = cohorts as i32 + 2;+ let mut definitions: Vec<(i32, Vec<Value>)> = (0..cohorts)+ .map(|index| {+ let mut leaves = vec![+ wide_behavioral_leaf(shared),+ wide_compressed_leaf(index + 1),+ person_leaf(),+ ];+ if referencing {+ leaves.push(cohort_ref(single_leaf_referent));+ leaves.push(cohort_ref(composable_referent));+ }+ (index as i32 + 1, leaves)+ })+ .collect();+ if referencing {+ definitions.push((single_leaf_referent, vec![wide_compressed_leaf(0)]));+ definitions.push((+ composable_referent,+ vec![wide_compressed_leaf(0), person_leaf()],+ ));+ }+ let filters = freeze_cascade(definitions, referencing);+ let shared_lsk = filters.by_condition_to_lsk[&wide_behavioral_hash(shared)][0];++ let mut affected = Vec::with_capacity(persons);+ for index in 0..persons {+ let who = person(index as u128 + 1);+ write_behavioral(store, shared_lsk, who, behavioral_match());+ for cohort in 0..cohorts {+ let own = filters.by_condition_to_lsk[&wide_compressed_hash(cohort + 1)][0];+ write_behavioral(store, own, who, year_long_compressed_state());+ }+ if referencing {+ let referent = filters.by_condition_to_lsk[&wide_compressed_hash(0)][0];+ write_behavioral(store, referent, who, year_long_compressed_state());+ write_stage2(store, composable_referent as u64, who, true);+ }+ write_person_record(store, who, &[PERSON_HASH]);+ affected.push((shared_lsk, who));+ }+ (filters, affected)+ }++ fn wide_compressed_leaf(index: usize) -> Value {+ json!({+ "type": "behavioral", "value": "performed_event_multiple", "key": "$pageview",+ "time_value": 1, "time_interval": "year",+ "operator": "gte", "operator_value": 1,+ "conditionHash": format!("cmp{index:013}"),+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],+ })+ }++ fn wide_compressed_hash(index: usize) -> [u8; 16] {+ format!("cmp{index:013}").as_bytes().try_into().unwrap()+ }++ /// One entry per day of the window, so each value is kilobytes rather than bytes.+ fn year_long_compressed_state() -> Stage1State {+ Stage1State::BehavioralCompressedHistory {+ entries: (0..365).map(|day| (20_600 + day, 1)).collect(),+ window_start_day: 20_600,+ last_event_at_ms: EVENT_MS,+ earliest_eviction_at_ms: i64::MAX,+ }+ }++ /// Benchmark, not a test. Run it in release:+ ///+ /// ```text+ /// cargo test -p cohort-stream-processor --release --lib \+ /// recompute_orders_benchmark -- --ignored --nocapture+ /// ```+ ///+ /// It asserts agreement only, because a wall-time threshold would flake on a slower box. Reads+ /// per source and memory come from `cohort_seed_recompute_*` under real load.+ #[tokio::test]+ #[ignore = "benchmark; run in release with --ignored --nocapture"]+ async fn recompute_orders_benchmark() {+ use std::time::Instant;++ const PERSONS: usize = 500;++ println!(+ "{:>8} {:>5} {:>8} {:>12} {:>12} {:>7}",+ "cohorts", "refs", "pairs", "by-cohort", "by-person", "ratio"+ );+ let shapes = [1, 4, 14]+ .into_iter()+ .flat_map(|cohorts| [(cohorts, false), (cohorts, true)]);+ for (cohorts, referencing) in shapes {+ let (_dir, store) = temp_store();+ let (filters, affected) = wide_fixture(&store, cohorts, PERSONS, referencing);+ let handle = handle(&store);+ let run_by_cohort = || {+ recompute_stage2(+ PARTITION,+ &handle,+ &filters,+ &affected,+ EVENT_MS,+ TS,+ ReadLane::Maintenance,+ )+ };+ let run_by_person = || {+ recompute_stage2_by_person(+ PARTITION,+ &handle,+ TeamId(TEAM as i32),+ &filters,+ &affected,+ EVENT_MS,+ TS,+ )+ };++ // Warm the block cache, so the timed pass measures the read shape and not the first+ // touch of every SST.+ let warm_by_cohort = run_by_cohort().await.unwrap();+ let warm_by_person = run_by_person().await.unwrap();+ assert_eq!(warm_by_person.changes, warm_by_cohort.changes);+ assert_eq!(warm_by_person.writes, warm_by_cohort.writes);++ let started = Instant::now();+ run_by_cohort().await.unwrap();+ let by_cohort = started.elapsed();++ let started = Instant::now();+ run_by_person().await.unwrap();+ let by_person = started.elapsed();++ println!(+ "{:>8} {:>5} {:>8} {:>10.1?} {:>10.1?} {:>6.2}x",+ cohorts,+ if referencing { "yes" } else { "no" },+ cohorts * PERSONS,+ by_cohort,+ by_person,+ by_cohort.as_secs_f64() / by_person.as_secs_f64(),+ );+ }+ }}diff --git a/rust/cohort-stream-processor/src/workers/stage2_person_inputs.rs b/rust/cohort-stream-processor/src/workers/stage2_person_inputs.rsnew file mode 100644index 000000000000..3bc89dca86cf--- /dev/null+++ b/rust/cohort-stream-processor/src/workers/stage2_person_inputs.rs@@ -0,0 +1,684 @@+//! Stage 2 recomputation for a seed run, sharing each person's store inputs across their cohorts.+//!+//! Same output as [`recompute_stage2`](super::stage2_path::recompute_stage2), reached by reading+//! each person once rather than once per affected cohort.+//!+//! Two boundaries the sharing must not cross:+//!+//! - A composed referent resolves from the bit the store holds, even when that referent recomputes+//! in this same group. A freshly computed bit would emit a cascade nothing has acknowledged.+//! - Behavioral values carry whole event histories, so a section reads at most one chunk per source+//! and drops its raw buffers before the next. A wide person releases the maintenance permit+//! between chunks instead of holding it across all of them.++use std::collections::{BTreeMap, BTreeSet, HashMap};++use metrics::{counter, histogram};+use uuid::Uuid;++use crate::filters::reverse_index::{LeafStateMeta, TeamFilters};+use crate::filters::{CohortId, TeamId};+use crate::observability::metrics::{+ SEED_RECOMPUTE_CHUNK_BYTES, SEED_RECOMPUTE_KEYS_FETCHED_TOTAL, SEED_RECOMPUTE_PERSONS_TOTAL,+ STAGE2_STATE_DECODE_ERROR,+};+use crate::stage1::key::LeafStateKey;+use crate::stage1::person_record::PersonRecord;+use crate::stage1::state::StateVariant;+use crate::stage2::evaluator::{evaluate_tree, leaf_membership};+use crate::stage2::CohortEligibility;+use crate::store::{+ BehavioralKey, CohortStore, PersonRecordKey, Stage2Key, StoreError, StoreHandle,+};+use crate::workers::stage2_path::{+ collect_cohort_refs, collect_leaf_state_keys, decode_stage1_state, read_prior_stage2,+ PriorStage2State, RecomputeDiff, RecomputedPair, Stage2Recompute,+};++/// Keys per batched read, the same chunk the sweep prefetch uses. A chunk is decoded and dropped+/// before the next is read, so this bounds the raw buffers one section holds and with them the+/// drain time a started section can add. It is not a byte bound, because behavioral values vary+/// in size with their window; [`SEED_RECOMPUTE_CHUNK_BYTES`] measures what a chunk actually cost.+pub(super) const READ_CHUNK_KEYS: usize = 1024;++const SECTION_OP: &str = "stage2_person_inputs";++/// Recompute one seed group's composable cohorts, sharing each person's reads across their cohorts.+///+/// Seed-only by construction: the reads run through [`StoreHandle::run_section`], which draws the+/// maintenance permit. The live, sweep, cascade and reconcile paths compose on+/// [`ReadLane::Event`](crate::store::ReadLane) and cannot move here without putting hot-path reads+/// behind the backfill lane.+///+/// `team_id` is the key `filters` sit under in the frozen catalog, so every cohort here composes+/// from that team's keyspace.+///+/// Changes and writes come back in `(cohort, person)` order, matching the cohort-ordered path.+///+/// A read failure returns before any output exists, so the held run publishes nothing partial.+pub(crate) async fn recompute_stage2_by_person(+ partition_id: u16,+ handle: &StoreHandle,+ team_id: TeamId,+ filters: &TeamFilters,+ affected_leaves: &[(LeafStateKey, Uuid)],+ event_ms: i64,+ last_updated: &str,+) -> Result<Stage2Recompute, StoreError> {+ let mut affected: BTreeMap<Uuid, BTreeSet<CohortId>> = BTreeMap::new();+ for &(leaf_state_key, person_id) in affected_leaves {+ if let Some(cohorts) = filters.by_lsk_to_composable_cohorts.get(&leaf_state_key) {+ affected+ .entry(person_id)+ .or_default()+ .extend(cohorts.iter().copied());+ }+ }++ // A map rather than pushes. No consumer needs cohort order (changes are keyed by person and+ // writes by row), but the differential tests compare this path with the cohort-ordered one+ // verbatim, and the map also collapses a duplicate pair into one `record_pair`.+ let mut pairs: BTreeMap<(CohortId, Uuid), RecomputeDiff> = BTreeMap::new();+ // Persons run one at a time on purpose. Every partition worker applies its own runs against+ // this one maintenance lane, whose permits are already contended across partitions and shared+ // with the sweep, merge and GC sections. Overlapping persons inside one run would add+ // contenders to that lane without adding permits.+ for (person_id, cohorts) in affected {+ let plan = PersonReadPlan::build(partition_id, team_id, person_id, &cohorts, filters);+ if plan.is_empty() {+ continue;+ }++ let mut reader = PersonInputReader::new(plan);+ loop {+ reader = handle+ .run_section(SECTION_OP, move |store| {+ reader.read_section(store)?;+ Ok(reader)+ })+ .await??;+ if reader.is_done() {+ break;+ }+ }+ let (plan, inputs) = reader.finish();++ let references = plan.reference_membership(&inputs);+ for &cohort_id in &plan.cohorts {+ let tree = filters+ .cohorts+ .get(&cohort_id)+ .expect("the plan keeps only cohorts this frozen catalog has a tree for");+ // The cohort-ordered path stamps changes from the tree; this one from the group. The+ // catalog keys one `TeamFilters` per team and stamps its trees with that same id, so+ // the two stamps agree.+ debug_assert_eq!(+ tree.team_id, team_id,+ "a team's catalog holds only that team's cohorts",+ );+ let new_bit = evaluate_tree(&tree.root, &inputs.membership, &references);+ pairs.insert(+ (cohort_id, person_id),+ RecomputeDiff::new(+ new_bit,+ inputs.prior_stage2(cohort_id),+ plan.stage2_key(cohort_id),+ ),+ );+ }+ }++ let mut recompute = Stage2Recompute::default();+ for ((cohort_id, person_id), diff) in pairs {+ recompute.record_pair(+ RecomputedPair {+ team_id: team_id.0,+ cohort_id,+ person_id,+ },+ &diff,+ event_ms,+ last_updated,+ );+ }+ Ok(recompute)+}++// ---- What one person's cohorts read ----++/// How a referenced cohort's membership resolves for one person. Both recompute orders classify+/// through [`Self::classify`], so a referent cannot resolve from one store on the seed path and+/// another on the live path.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(super) enum ReferenceSource {+ /// Membership is the leaf's own bit, read through that leaf's comparator.+ Leaf(LeafStateKey),+ /// Membership is the composed row the store holds.+ Stored,+ /// Excluded, cyclic, or absent from the frozen catalog.+ NonMember,+}++impl ReferenceSource {+ pub(super) fn classify(filters: &TeamFilters, ref_id: CohortId) -> Self {+ match filters.eligibility.get(&ref_id) {+ Some(CohortEligibility::SingleLeaf(lsk)) => Self::Leaf(*lsk),+ Some(eligibility) if eligibility.writes_cf_stage2() => Self::Stored,+ _ => Self::NonMember,+ }+ }+}++/// Everything one person's affected cohorts read from the store. Owned, so the read can run in+/// blocking sections.+#[derive(Debug)]+struct PersonReadPlan {+ partition_id: u16,+ team_id: u64,+ person_id: Uuid,+ /// Ascending. Every id here has a tree in the frozen catalog.+ cohorts: Vec<CohortId>,+ behavioral: Vec<(LeafStateKey, LeafStateMeta)>,+ person_leaves: Vec<LeafStateKey>,+ /// Each recomputed pair's own prior row, plus every composed referent. One row serves both when+ /// a referent also recomputes here.+ stage2_cohorts: Vec<CohortId>,+ references: BTreeMap<CohortId, ReferenceSource>,+}++impl PersonReadPlan {+ /// Reads the frozen catalog only, so the plan is settled before the run holds a store permit.+ fn build(+ partition_id: u16,+ team_id: TeamId,+ person_id: Uuid,+ cohorts: &BTreeSet<CohortId>,+ filters: &TeamFilters,+ ) -> Self {+ let mut plan = Self {+ partition_id,+ team_id: team_id.0 as u64,+ person_id,+ cohorts: Vec::with_capacity(cohorts.len()),+ behavioral: Vec::new(),+ person_leaves: Vec::new(),+ stage2_cohorts: Vec::with_capacity(cohorts.len()),+ references: BTreeMap::new(),+ };++ let mut lsks = Vec::new();+ let mut refs = Vec::new();+ for &cohort_id in cohorts {+ let Some(tree) = filters.cohorts.get(&cohort_id) else {+ continue;+ };+ plan.cohorts.push(cohort_id);+ // The diff needs the prior row whether or not the cohort flips.+ plan.stage2_cohorts.push(cohort_id);++ lsks.clear();+ collect_leaf_state_keys(&tree.root, &mut lsks);+ for &lsk in &lsks {+ plan.route_leaf(lsk, filters);+ }++ refs.clear();+ collect_cohort_refs(&tree.root, &mut refs);+ for &ref_id in &refs {+ plan.route_reference(ref_id, filters);+ }+ }++ plan.dedup_read_sets();+ plan+ }++ /// A key the frozen catalog does not carry is routed nowhere, so composition reads it as a+ /// non-member.+ fn route_leaf(&mut self, lsk: LeafStateKey, filters: &TeamFilters) {+ let Some(meta) = filters.by_lsk.get(&lsk) else {+ return;+ };+ match meta.variant {+ StateVariant::PersonProperty => self.person_leaves.push(lsk),+ // No wildcard, so a future membership source reading from another store fails to+ // compile here instead of being misrouted into `cf_behavioral`.+ StateVariant::BehavioralSingle+ | StateVariant::BehavioralDailyBuckets+ | StateVariant::BehavioralCompressedHistory => self.behavioral.push((lsk, *meta)),+ }+ }++ fn route_reference(&mut self, ref_id: CohortId, filters: &TeamFilters) {+ if self.references.contains_key(&ref_id) {+ return;+ }+ let source = ReferenceSource::classify(filters, ref_id);+ match source {+ ReferenceSource::Leaf(lsk) => self.route_leaf(lsk, filters),+ ReferenceSource::Stored => self.stage2_cohorts.push(ref_id),+ ReferenceSource::NonMember => {}+ }+ self.references.insert(ref_id, source);+ }++ fn dedup_read_sets(&mut self) {+ self.behavioral.sort_unstable_by_key(|(lsk, _)| *lsk);+ self.behavioral.dedup_by_key(|(lsk, _)| *lsk);+ self.person_leaves.sort_unstable();+ self.person_leaves.dedup();+ self.stage2_cohorts.sort_unstable();+ self.stage2_cohorts.dedup();+ }++ fn is_empty(&self) -> bool {+ self.cohorts.is_empty()+ }++ fn person_record_key(&self) -> PersonRecordKey {+ PersonRecordKey::new(self.partition_id, self.team_id, self.person_id)+ }++ fn behavioral_key(&self, lsk: LeafStateKey) -> BehavioralKey {+ BehavioralKey::new(self.partition_id, self.team_id, self.person_id, lsk)+ }++ fn stage2_key(&self, cohort_id: CohortId) -> Stage2Key {+ Stage2Key {+ partition_id: self.partition_id,+ team_id: self.team_id,+ cohort_id: cohort_id.0 as u64,+ person_id: self.person_id,+ }+ }++ /// One bit per referenced cohort, shared by every cohort of this person that names it. Entries+ /// a given tree does not reference are inert, because `evaluate_tree` reads only its own ids.+ fn reference_membership(&self, inputs: &ResolvedPersonInputs) -> HashMap<CohortId, bool> {+ self.references+ .iter()+ .map(|(&ref_id, source)| {+ let member = match source {+ ReferenceSource::Leaf(lsk) => inputs.leaf_membership(*lsk),+ ReferenceSource::Stored => inputs.prior_stage2(ref_id).in_cohort,+ ReferenceSource::NonMember => false,+ };+ (ref_id, member)+ })+ .collect()+ }+}++// ---- Reading them ----++/// One person's decoded inputs. Compact enough to outlive the sections that read them, because each+/// chunk's raw values are dropped as they decode.+#[derive(Debug, Default)]+struct ResolvedPersonInputs {+ membership: HashMap<LeafStateKey, bool>,+ stage2: HashMap<CohortId, PriorStage2State>,+}++impl ResolvedPersonInputs {+ /// A leaf the frozen catalog did not back was never read, and reads as a non-member.+ fn leaf_membership(&self, lsk: LeafStateKey) -> bool {+ self.membership.get(&lsk).copied().unwrap_or(false)+ }++ /// A row the plan did not ask for takes the same fail-closed reading as an absent one.+ fn prior_stage2(&self, cohort_id: CohortId) -> PriorStage2State {+ self.stage2.get(&cohort_id).copied().unwrap_or_default()+ }++ /// A person leaf's state key *is* its condition hash, so its bit is+ /// `record.matched.contains(hash)`. An absent or corrupt record reads every person leaf as a+ /// non-member, and a corrupt one counts once per person rather than once per cohort.+ fn absorb_person_record(&mut self, person_leaves: &[LeafStateKey], bytes: Option<Vec<u8>>) {+ let matched = match bytes {+ None => None,+ Some(bytes) => match PersonRecord::decode(&bytes) {+ Ok(record) => Some(record.matched),+ Err(_) => {+ counter!(STAGE2_STATE_DECODE_ERROR).increment(1);+ None+ }+ },+ };+ for &lsk in person_leaves {+ let member = matched+ .as_ref()+ .is_some_and(|matched| matched.contains(&lsk.0));+ self.membership.insert(lsk, member);+ }+ }++ fn absorb_behavioral(+ &mut self,+ chunk: &[(LeafStateKey, LeafStateMeta)],+ raw: Vec<Option<Vec<u8>>>,+ ) {+ for (&(lsk, ref meta), bytes) in chunk.iter().zip(raw) {+ let state = decode_stage1_state(bytes);+ self.membership+ .insert(lsk, leaf_membership(state.as_ref(), meta));+ }+ }+}++/// Executes one [`PersonReadPlan`] across as many [`StoreHandle::run_section`] calls as its width+/// needs.+///+/// Each section draws the maintenance permit, so backfill cannot contend with live event reads.+///+/// A started section cannot be cancelled and shutdown joins it, so [`Self::read_section`] bounds one+/// section to the person record plus one [`READ_CHUNK_KEYS`] chunk of each batched source.+struct PersonInputReader {+ plan: PersonReadPlan,+ inputs: ResolvedPersonInputs,+ started: bool,+ behavioral_read: usize,+ stage2_read: usize,+}++#[allow(clippy::disallowed_methods)]+impl PersonInputReader {+ fn new(plan: PersonReadPlan) -> Self {+ let inputs = ResolvedPersonInputs {+ membership: HashMap::with_capacity(plan.behavioral.len() + plan.person_leaves.len()),+ stage2: HashMap::with_capacity(plan.stage2_cohorts.len()),+ };+ Self {+ plan,+ inputs,+ started: false,+ behavioral_read: 0,+ stage2_read: 0,+ }+ }++ fn read_section(&mut self, store: &CohortStore) -> Result<(), StoreError> {+ if self.started {+ self.read_behavioral_chunk(store)?;+ } else {+ self.started = true;+ // Counted on the blocking thread with the keys. A started section completes even when+ // the caller future is dropped, so counting outside would record keys for a person the+ // cancelled offload never counted.+ counter!(SEED_RECOMPUTE_PERSONS_TOTAL).increment(1);+ self.read_record_with_first_behavioral_chunk(store)?;+ }+ self.read_stage2_chunk(store)+ }++ fn is_done(&self) -> bool {+ self.started+ && self.behavioral_read == self.plan.behavioral.len()+ && self.stage2_read == self.plan.stage2_cohorts.len()+ }++ fn finish(self) -> (PersonReadPlan, ResolvedPersonInputs) {+ (self.plan, self.inputs)+ }++ /// The person record rides along the first behavioral chunk in one mixed-CF `multi_get`, the+ /// read the event fold already issues, so a person costs one RocksDB lookup fewer.+ fn read_record_with_first_behavioral_chunk(+ &mut self,+ store: &CohortStore,+ ) -> Result<(), StoreError> {+ let chunk = self+ .plan+ .behavioral+ .chunks(READ_CHUNK_KEYS)+ .next()+ .unwrap_or(&[]);+ let keys: Vec<BehavioralKey> = chunk+ .iter()+ .map(|&(lsk, _)| self.plan.behavioral_key(lsk))+ .collect();+ let record_key =+ (!self.plan.person_leaves.is_empty()).then(|| self.plan.person_record_key());+ let snapshot = store.read_event_snapshot(&keys, record_key.as_ref())?;+ if let Some(record) = snapshot.record {+ ReadSource::PersonRecord.record(1, record.as_ref().map_or(0, Vec::len));+ self.inputs+ .absorb_person_record(&self.plan.person_leaves, record);+ }+ if !keys.is_empty() {+ ReadSource::Behavioral.record(keys.len(), raw_bytes(&snapshot.behavioral));+ self.inputs.absorb_behavioral(chunk, snapshot.behavioral);+ self.behavioral_read += chunk.len();+ }+ Ok(())+ }++ fn read_behavioral_chunk(&mut self, store: &CohortStore) -> Result<(), StoreError> {+ let rest = &self.plan.behavioral[self.behavioral_read..];+ let Some(chunk) = rest.chunks(READ_CHUNK_KEYS).next() else {+ return Ok(());+ };+ let keys: Vec<BehavioralKey> = chunk+ .iter()+ .map(|&(lsk, _)| self.plan.behavioral_key(lsk))+ .collect();+ let raw = store.multi_get_behavioral(&keys)?;+ ReadSource::Behavioral.record(keys.len(), raw_bytes(&raw));+ self.inputs.absorb_behavioral(chunk, raw);+ self.behavioral_read += chunk.len();+ Ok(())+ }++ /// Prior rows and composed referents share one key set, so a referent that also recomputes here+ /// is read once, and read as stored.+ fn read_stage2_chunk(&mut self, store: &CohortStore) -> Result<(), StoreError> {+ let rest = &self.plan.stage2_cohorts[self.stage2_read..];+ let Some(chunk) = rest.chunks(READ_CHUNK_KEYS).next() else {+ return Ok(());+ };+ let keys: Vec<Stage2Key> = chunk+ .iter()+ .map(|&cohort_id| self.plan.stage2_key(cohort_id))+ .collect();+ let raw = store.multi_get_stage2(&keys)?;+ ReadSource::Stage2.record(keys.len(), raw_bytes(&raw));+ for (&cohort_id, bytes) in chunk.iter().zip(raw) {+ self.inputs+ .stage2+ .insert(cohort_id, read_prior_stage2(bytes));+ }+ self.stage2_read += chunk.len();+ Ok(())+ }+}++/// The closed set of `source` label values on the section counters.+#[derive(Debug, Clone, Copy)]+enum ReadSource {+ Behavioral,+ PersonRecord,+ Stage2,+}++impl ReadSource {+ fn label(self) -> &'static str {+ match self {+ Self::Behavioral => "behavioral",+ Self::PersonRecord => "person_record",+ Self::Stage2 => "stage2",+ }+ }++ fn record(self, keys: usize, bytes: usize) {+ counter!(SEED_RECOMPUTE_KEYS_FETCHED_TOTAL, "source" => self.label())+ .increment(keys as u64);+ histogram!(SEED_RECOMPUTE_CHUNK_BYTES, "source" => self.label()).record(bytes as f64);+ }+}++fn raw_bytes(values: &[Option<Vec<u8>>]) -> usize {+ values.iter().flatten().map(Vec::len).sum()+}++#[cfg(test)]+mod tests {+ use super::*;+ use chrono_tz::UTC;+ use serde_json::{json, Value};++ use crate::filters::{TeamFiltersBuilder, TeamId};++ const PARTITION: u16 = 0;+ const TEAM: TeamId = TeamId(7);+ const PERSON_HASH: &str = "person0000000001";++ fn hash(text: &str) -> [u8; 16] {+ text.as_bytes()+ .try_into()+ .expect("a 16-byte condition hash")+ }++ fn behavioral_leaf(condition_hash: &str) -> Value {+ json!({+ "type": "behavioral", "value": "performed_event", "key": "$pageview",+ "time_value": 7, "time_interval": "day",+ "conditionHash": condition_hash,+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],+ })+ }++ fn person_leaf() -> Value {+ json!({+ "type": "person", "key": "email", "value": "[email protected]", "operator": "exact",+ "conditionHash": PERSON_HASH,+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],+ })+ }++ fn cohort_ref(target: i32) -> Value {+ json!({ "type": "cohort", "value": target, "negation": false })+ }++ fn freeze(cohorts: Vec<(i32, Vec<Value>)>) -> TeamFilters {+ let mut builder = TeamFiltersBuilder::default();+ for (id, values) in cohorts {+ let cohort = json!({ "properties": { "type": "AND", "values": values } });+ builder.add_cohort(CohortId(id), TEAM, &cohort).unwrap();+ }+ builder.freeze_with(UTC, true)+ }++ fn plan_for(filters: &TeamFilters, cohorts: &[i32]) -> PersonReadPlan {+ let cohorts: BTreeSet<CohortId> = cohorts.iter().map(|&id| CohortId(id)).collect();+ PersonReadPlan::build(PARTITION, TEAM, Uuid::from_u128(1), &cohorts, filters)+ }++ fn behavioral_lsks(plan: &PersonReadPlan) -> Vec<LeafStateKey> {+ plan.behavioral.iter().map(|&(lsk, _)| lsk).collect()+ }++ /// Whatever the fan-out, one person is one record read and one key per distinct row.+ #[test]+ fn a_person_reads_one_record_and_one_key_per_distinct_row() {+ let filters = freeze(vec![+ (1, vec![behavioral_leaf("shared0000000001"), person_leaf()]),+ (2, vec![behavioral_leaf("shared0000000001"), person_leaf()]),+ (3, vec![behavioral_leaf("own0000000000003"), person_leaf()]),+ ]);+ let plan = plan_for(&filters, &[1, 2, 3]);++ assert_eq!(plan.cohorts, [CohortId(1), CohortId(2), CohortId(3)]);+ assert_eq!(+ plan.person_leaves,+ [LeafStateKey::for_person_property(&hash(PERSON_HASH))],+ "three cohorts naming one person condition still read one record",+ );+ assert_eq!(+ behavioral_lsks(&plan),+ {+ let mut want = vec![+ filters.by_condition_to_lsk[&hash("shared0000000001")][0],+ filters.by_condition_to_lsk[&hash("own0000000000003")][0],+ ];+ want.sort_unstable();+ want+ },+ "the leaf two cohorts share is one key, not two",+ );+ assert_eq!(+ plan.stage2_cohorts,+ [CohortId(1), CohortId(2), CohortId(3)],+ "each pair's own prior row, and nothing else",+ );+ assert!(plan.references.is_empty());+ }++ /// A referent recomputing in the same group is still one stored row, read alongside the pairs'+ /// own priors rather than substituted with the bit this run is about to write.+ #[test]+ fn a_referent_recomputed_in_the_same_group_is_planned_as_one_stored_row() {+ let filters = freeze(vec![+ (1, vec![person_leaf(), cohort_ref(2)]),+ (2, vec![behavioral_leaf("shared0000000001"), person_leaf()]),+ ]);+ let plan = plan_for(&filters, &[1, 2]);++ assert_eq!(+ plan.references,+ BTreeMap::from([(CohortId(2), ReferenceSource::Stored)]),+ );+ assert_eq!(+ plan.stage2_cohorts,+ [CohortId(1), CohortId(2)],+ "cohort 2's row serves both its own diff and cohort 1's reference",+ );+ }++ /// Each reference kind reaches the state source that answers it, and only the composed kind+ /// adds a row.+ #[test]+ fn each_reference_kind_routes_to_its_own_state_source() {+ let single_leaf_hash = "singleleaf000003";+ let filters = freeze(vec![+ (+ 1,+ vec![person_leaf(), cohort_ref(2), cohort_ref(3), cohort_ref(404)],+ ),+ (2, vec![behavioral_leaf("shared0000000001"), person_leaf()]),+ (3, vec![behavioral_leaf(single_leaf_hash)]),+ ]);+ let referent_lsk = filters.by_condition_to_lsk[&hash(single_leaf_hash)][0];+ let plan = plan_for(&filters, &[1]);++ assert_eq!(+ plan.references,+ BTreeMap::from([+ (CohortId(2), ReferenceSource::Stored),+ (CohortId(3), ReferenceSource::Leaf(referent_lsk)),+ (CohortId(404), ReferenceSource::NonMember),+ ]),+ );+ assert_eq!(+ plan.stage2_cohorts,+ [CohortId(1), CohortId(2)],+ "only the composed referent adds a row; the single-leaf one is read as a leaf",+ );+ assert!(+ behavioral_lsks(&plan).contains(&referent_lsk),+ "the single-leaf referent joins the behavioral batch, comparator and all",+ );+ }++ /// A cohort the frozen catalog no longer carries is dropped before any read, so it costs no key+ /// and composes no pair.+ #[test]+ fn a_cohort_the_catalog_dropped_is_not_planned() {+ let filters = freeze(vec![(+ 1,+ vec![behavioral_leaf("shared0000000001"), person_leaf()],+ )]);+ let plan = plan_for(&filters, &[1, 2]);++ assert_eq!(plan.cohorts, [CohortId(1)]);+ assert_eq!(plan.stage2_cohorts, [CohortId(1)]);+ }+}diff --git a/rust/cohort-stream-processor/tests/stage1_worker.rs b/rust/cohort-stream-processor/tests/stage1_worker.rsindex 1a36a254b16b..1926b50df108 100644--- a/rust/cohort-stream-processor/tests/stage1_worker.rs+++ b/rust/cohort-stream-processor/tests/stage1_worker.rs@@ -2981,6 +2981,122 @@ async fn both_lanes_drain_before_the_worker_exits() {);}+/// The composed half of the same guarantee: a run that flips two cohorts commits stage 1, fails its+/// produce, and holds. Nothing downstream was told and no `cf_stage2` row says otherwise, so the+/// redelivery re-derives both flips and only then commits the offset.+#[tokio::test]+async fn a_failed_composed_seed_produce_replays_from_the_row_it_never_wrote() {+ let (_dir, store) = temp_store();+ // Two composable cohorts on the same leaf, so one person recomputes for both from one shared+ // read.+ let composed = || {+ build_team_filters(vec![+ (CohortId(1), cohort(vec![behavioral_leaf(7), person_leaf()])),+ (CohortId(2), cohort(vec![behavioral_leaf(7), person_leaf()])),+ ])+ };+ let bob = person(2);+ // The person leaf already holds, so the seed tile's behavioral leaf is what completes the AND.+ write_person_record(&store, bob, &[PERSON_HASH], AppliedOffsets::default(), &[]);++ let sink = CaptureSink::failing_first(1);+ let deps = MergeWorkerDeps::capture();+ let (live_tx, live_rx) = mpsc::channel(16);+ let (seed_tx, seed_rx) = mpsc::channel(16);+ let worker = Stage1Worker::spawn(+ PARTITION_ID,+ WorkerInbox::unmetered(live_rx, seed_rx),+ test_handle(&store),+ catalog_of(composed()),+ Arc::new(sink.clone()),+ Arc::new(OffsetTracker::new()),+ deps.clone(),+ false,+ );+ deps.seed_tracker.mark_dispatched(PARTITION_ID as i32, 8);+ seed_tx+ .send(consumed_seed(bob, utc_today(), 1, 7))+ .await+ .unwrap();+ drop(seed_tx);+ drop(live_tx);+ worker.join().await.unwrap();++ assert!(+ sink.changes().is_empty(),+ "the produce failed, so downstream was told nothing",+ );+ for cohort_id in [1, 2] {+ assert_eq!(+ membership_register_at(&store, cohort_id, bob),+ None,+ "the composed bits commit only after their produce acks",+ );+ }+ assert_eq!(+ deps.seed_tracker+ .committable_offsets()+ .get(&(PARTITION_ID as i32)),+ None,+ "the failed produce holds the seed offset",+ );++ // The redelivered tile merges to `Unchanged` and mints no transition, so only the absent+ // stage-2 row can say the flips were never emitted.+ let replay_sink = CaptureSink::new();+ let replay_deps = MergeWorkerDeps::capture();+ let (live_tx, live_rx) = mpsc::channel(16);+ let (seed_tx, seed_rx) = mpsc::channel(16);+ let worker = Stage1Worker::spawn(+ PARTITION_ID,+ WorkerInbox::unmetered(live_rx, seed_rx),+ test_handle(&store),+ catalog_of(composed()),+ Arc::new(replay_sink.clone()),+ Arc::new(OffsetTracker::new()),+ replay_deps.clone(),+ false,+ );+ replay_deps+ .seed_tracker+ .mark_dispatched(PARTITION_ID as i32, 8);+ seed_tx+ .send(consumed_seed(bob, utc_today(), 1, 7))+ .await+ .unwrap();+ drop(seed_tx);+ drop(live_tx);+ worker.join().await.unwrap();++ let changes = replay_sink.changes();+ assert_eq!(+ changes+ .iter()+ .map(|change| (change.cohort_id, change.person_id.clone(), change.status))+ .collect::<Vec<_>>(),+ vec![+ (1, bob.to_string(), MembershipStatus::Entered),+ (2, bob.to_string(), MembershipStatus::Entered),+ ],+ "the redelivery re-derived both lost changes from one shared read",+ );+ for cohort_id in [1, 2] {+ assert_eq!(+ membership_register_at(&store, cohort_id, bob).map(|state| state.in_cohort),+ Some(true),+ "and the rows it emitted are now durable",+ );+ }+ assert_eq!(+ replay_deps+ .seed_tracker+ .committable_offsets()+ .get(&(PARTITION_ID as i32)),+ Some(&8),+ "the seed offset commits once the re-emission acks",+ );+}+/// A failed seed emission holds only the seed tracker; the events tracker is unaffected, and the/// next tenure's redelivery re-emits the lost change.#[tokio::test]