Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

perf(cohorts): amortize reconcile page reads across bounded sections (#99450)

Matheus Batistae6b25adb65ca
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
index 9e5fb5189b88..7dfbed8aafee 100644
--- a/rust/cohort-stream-processor/src/observability/metrics.rs
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -661,6 +661,35 @@ pub const RECONCILE_JOBS_DISCARDED_TOTAL: &str = "cohort_reconcile_jobs_discarde
/// Stage 2 rows read by reconcile and durably settled, counted once per committed page (counter). A
/// page that fails its produce or commit and retries is not double-counted.
pub const RECONCILE_ROWS_SCANNED_TOTAL: &str = "cohort_reconcile_rows_scanned_total";
+/// Rows whose composition read a reconcile section started (counter). Attempt-based, unlike
+/// [`RECONCILE_ROWS_SCANNED_TOTAL`]: a page that fails its produce or commit counts its rows again
+/// on the retry, so the gap between the two series is the retried work.
+pub const RECONCILE_ROWS_ATTEMPTED_TOTAL: &str = "cohort_reconcile_rows_attempted_total";
+/// Store keys those sections fetched, labelled by `source` (`behavioral`|`person_record`|`stage2`)
+/// (counter). Over [`RECONCILE_ROWS_ATTEMPTED_TOTAL`] this is keys per row, which is what the
+/// cohort's shape costs. The handoff saving is instead
+/// `store_offload_exec_duration_seconds{op="reconcile_page"}_count` over
+/// [`RECONCILE_ROWS_ATTEMPTED_TOTAL`], because one section now carries many rows.
+pub const RECONCILE_KEYS_FETCHED_TOTAL: &str = "cohort_reconcile_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 this
+/// is the only read of how much a section actually held.
+///
+/// One sample is one row's batch of one source, not a budget-sized chunk, so ordinary samples sit
+/// far below the section's 4 MiB budget; a sample above it is the documented overshoot, where the
+/// read that crossed the budget had already returned. A batch that matched nothing records a real
+/// `0`, and a miss inside a batch is invisible in the sum, so prefer the upper quantiles while a
+/// scan sweeps persons it finds nothing for.
+pub const RECONCILE_READ_BYTES: &str = "cohort_reconcile_read_bytes";
+/// Wall time one settlement page spent in each step, labelled by `stage`
+/// (`recompute`|`membership_produce`|`cascade_produce`|`commit`) (histogram). A page that fails
+/// records no sample for the step that failed, so the histogram stays a picture of settled work.
+/// `recompute` covers every section of the page's read and evaluation, permit waits included.
+///
+/// A step with nothing to do still records its real near-zero duration: `cascade_produce` on a page
+/// with no flips, and both produce and commit on a dirty page whose every row was deleted. Read the
+/// upper quantiles, not the median, which on a quiet cohort is mostly those pages.
+pub const RECONCILE_PAGE_DURATION_SECONDS: &str = "cohort_reconcile_page_duration_seconds";
/// Snapshot membership rows acknowledged by Kafka and durably settled, labelled by `status`, counted
/// once per committed page (counter).
pub const RECONCILE_ROWS_EMITTED_TOTAL: &str = "cohort_reconcile_rows_emitted_total";
@@ -1062,6 +1091,19 @@ mod tests {
RECONCILE_ROWS_SCANNED_TOTAL,
"cohort_reconcile_rows_scanned_total",
);
+ assert_eq!(
+ RECONCILE_ROWS_ATTEMPTED_TOTAL,
+ "cohort_reconcile_rows_attempted_total",
+ );
+ assert_eq!(
+ RECONCILE_KEYS_FETCHED_TOTAL,
+ "cohort_reconcile_keys_fetched_total",
+ );
+ assert_eq!(RECONCILE_READ_BYTES, "cohort_reconcile_read_bytes");
+ assert_eq!(
+ RECONCILE_PAGE_DURATION_SECONDS,
+ "cohort_reconcile_page_duration_seconds",
+ );
assert_eq!(
RECONCILE_ROWS_EMITTED_TOTAL,
"cohort_reconcile_rows_emitted_total",
diff --git a/rust/cohort-stream-processor/src/workers/composition_inputs.rs b/rust/cohort-stream-processor/src/workers/composition_inputs.rs
new file mode 100644
index 000000000000..52d19f880a9a
--- /dev/null
+++ b/rust/cohort-stream-processor/src/workers/composition_inputs.rs
@@ -0,0 +1,500 @@
+//! What Stage 2 composition reads from the store for one person, and how those reads decode.
+//!
+//! A [`CompositionReadPlan`] is settled from a frozen catalog and names no person, so one plan
+//! serves every person it is bound to: the seed path builds one per person's affected cohorts,
+//! reconcile builds one per page. [`PersonScope`] turns it into keys;
+//! [`ResolvedPersonInputs`] is what the raw values decode to, compact enough to outlive the
+//! sections that read them.
+//!
+//! Both recompute orders classify references through [`ReferenceSource`], so a referent cannot
+//! resolve from one store on one path and another on the other.
+
+use std::collections::{BTreeMap, HashMap};
+
+use metrics::counter;
+use uuid::Uuid;
+
+use crate::filters::reverse_index::{LeafStateMeta, TeamFilters};
+use crate::filters::CohortId;
+use crate::observability::metrics::STAGE2_STATE_DECODE_ERROR;
+use crate::stage1::key::LeafStateKey;
+use crate::stage1::person_record::PersonRecord;
+use crate::stage1::state::StateVariant;
+use crate::stage2::evaluator::leaf_membership;
+use crate::stage2::CohortEligibility;
+use crate::store::{BehavioralKey, PersonRecordKey, Stage2Key};
+use crate::workers::stage2_path::{
+ collect_cohort_refs, collect_leaf_state_keys, decode_stage1_state, read_prior_stage2,
+ PriorStage2State,
+};
+
+/// How a referenced cohort's membership resolves for one person.
+#[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 composing a set of cohorts reads from the store, minus the person. Owned, so a reader
+/// can carry it into blocking sections.
+#[derive(Debug)]
+pub(super) struct CompositionReadPlan {
+ /// Ascending and deduplicated. Every id here has a tree in the frozen catalog.
+ cohorts: Vec<CohortId>,
+ behavioral: Vec<(LeafStateKey, LeafStateMeta)>,
+ person_leaves: Vec<LeafStateKey>,
+ /// Each composed cohort's own prior row, plus every composed referent. One row serves both when
+ /// a referent is also composed here.
+ stage2_cohorts: Vec<CohortId>,
+ references: BTreeMap<CohortId, ReferenceSource>,
+}
+
+impl CompositionReadPlan {
+ /// Reads the frozen catalog only, so the plan is settled before anything holds a store permit.
+ pub(super) fn for_cohorts(
+ cohorts: impl IntoIterator<Item = CohortId>,
+ filters: &TeamFilters,
+ ) -> Self {
+ let mut plan = Self {
+ cohorts: Vec::new(),
+ behavioral: Vec::new(),
+ person_leaves: Vec::new(),
+ stage2_cohorts: Vec::new(),
+ 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.cohorts.sort_unstable();
+ self.cohorts.dedup();
+ 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();
+ }
+
+ pub(super) fn is_empty(&self) -> bool {
+ self.cohorts.is_empty()
+ }
+
+ pub(super) fn cohorts(&self) -> &[CohortId] {
+ &self.cohorts
+ }
+
+ pub(super) fn behavioral(&self) -> &[(LeafStateKey, LeafStateMeta)] {
+ &self.behavioral
+ }
+
+ pub(super) fn person_leaves(&self) -> &[LeafStateKey] {
+ &self.person_leaves
+ }
+
+ pub(super) fn stage2_cohorts(&self) -> &[CohortId] {
+ &self.stage2_cohorts
+ }
+
+ /// One bit per referenced cohort, shared by every cohort here that names it. Entries a given
+ /// tree does not reference are inert, because `evaluate_tree` reads only its own ids.
+ pub(super) 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()
+ }
+}
+
+/// One person's corner of the keyspace: what binds a [`CompositionReadPlan`] to store keys.
+#[derive(Debug, Clone, Copy)]
+pub(super) struct PersonScope {
+ partition_id: u16,
+ team_id: u64,
+ person_id: Uuid,
+}
+
+impl PersonScope {
+ pub(super) fn new(partition_id: u16, team_id: u64, person_id: Uuid) -> Self {
+ Self {
+ partition_id,
+ team_id,
+ person_id,
+ }
+ }
+
+ pub(super) fn behavioral_key(&self, lsk: LeafStateKey) -> BehavioralKey {
+ BehavioralKey::new(self.partition_id, self.team_id, self.person_id, lsk)
+ }
+
+ pub(super) fn person_record_key(&self) -> PersonRecordKey {
+ PersonRecordKey::new(self.partition_id, self.team_id, self.person_id)
+ }
+
+ pub(super) 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 person's decoded inputs. Compact enough to outlive the sections that read them, because each
+/// batch's raw values are dropped as they decode.
+#[derive(Debug, Default)]
+pub(super) struct ResolvedPersonInputs {
+ membership: HashMap<LeafStateKey, bool>,
+ stage2: HashMap<CohortId, PriorStage2State>,
+}
+
+impl ResolvedPersonInputs {
+ pub(super) fn with_capacity_for(plan: &CompositionReadPlan) -> Self {
+ Self {
+ membership: HashMap::with_capacity(plan.behavioral.len() + plan.person_leaves.len()),
+ stage2: HashMap::with_capacity(plan.stage2_cohorts.len()),
+ }
+ }
+
+ pub(super) fn membership(&self) -> &HashMap<LeafStateKey, bool> {
+ &self.membership
+ }
+
+ /// 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.
+ pub(super) 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.
+ pub(super) 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);
+ }
+ }
+
+ pub(super) fn absorb_behavioral(
+ &mut self,
+ batch: &[(LeafStateKey, LeafStateMeta)],
+ raw: Vec<Option<Vec<u8>>>,
+ ) {
+ for (&(lsk, ref meta), bytes) in batch.iter().zip(raw) {
+ let state = decode_stage1_state(bytes);
+ self.membership
+ .insert(lsk, leaf_membership(state.as_ref(), meta));
+ }
+ }
+
+ pub(super) fn absorb_stage2(&mut self, batch: &[CohortId], raw: Vec<Option<Vec<u8>>>) {
+ for (&cohort_id, bytes) in batch.iter().zip(raw) {
+ self.stage2.insert(cohort_id, read_prior_stage2(bytes));
+ }
+ }
+}
+
+/// What one batched read returned, for the byte histograms. A miss contributes a real `0`.
+pub(super) 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 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 {
+ negated_cohort_ref(target, false)
+ }
+
+ fn negated_cohort_ref(target: i32, negation: bool) -> Value {
+ json!({ "type": "cohort", "value": target, "negation": negation })
+ }
+
+ 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]) -> CompositionReadPlan {
+ CompositionReadPlan::for_cohorts(cohorts.iter().map(|&id| CohortId(id)), filters)
+ }
+
+ fn behavioral_lsks(plan: &CompositionReadPlan) -> 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)]);
+ }
+
+ /// Negation belongs to the leaf, not to the row, so a referent named twice under opposite
+ /// negations is one key and one bit. Reading it twice would let the two leaves disagree.
+ #[test]
+ fn a_referent_named_twice_under_opposite_negations_is_one_row() {
+ let filters = freeze(vec![
+ (
+ 1,
+ vec![person_leaf(), cohort_ref(2), negated_cohort_ref(2, true)],
+ ),
+ (2, vec![behavioral_leaf("shared0000000001"), person_leaf()]),
+ ]);
+ let plan = plan_for(&filters, &[1]);
+
+ assert_eq!(
+ plan.references,
+ BTreeMap::from([(CohortId(2), ReferenceSource::Stored)]),
+ );
+ assert_eq!(plan.stage2_cohorts(), [CohortId(1), CohortId(2)]);
+ }
+
+ /// A caller naming the same cohort twice plans it once, so a repeated id costs no extra key.
+ #[test]
+ fn a_repeated_cohort_is_planned_once() {
+ let filters = freeze(vec![(
+ 1,
+ vec![behavioral_leaf("shared0000000001"), person_leaf()],
+ )]);
+ let plan = plan_for(&filters, &[1, 1]);
+
+ assert_eq!(plan.cohorts(), [CohortId(1)]);
+ assert_eq!(plan.stage2_cohorts(), [CohortId(1)]);
+ assert_eq!(behavioral_lsks(&plan).len(), 1);
+ }
+}
diff --git a/rust/cohort-stream-processor/src/workers/mod.rs b/rust/cohort-stream-processor/src/workers/mod.rs
index 452d0c489e21..41e76d1c79c6 100644
--- a/rust/cohort-stream-processor/src/workers/mod.rs
+++ b/rust/cohort-stream-processor/src/workers/mod.rs
@@ -1,11 +1,13 @@
//! Stage 1 per-partition workers: the I/O and channel layer over [`crate::stage1`].
pub mod cascade_path;
+mod composition_inputs;
pub mod event_path;
pub mod merge_gc;
pub mod merge_path;
pub mod person_seed_path;
pub mod reconcile;
+mod reconcile_page;
pub mod seed_apply;
pub mod seed_path;
pub mod seed_run;
diff --git a/rust/cohort-stream-processor/src/workers/reconcile.rs b/rust/cohort-stream-processor/src/workers/reconcile.rs
index 7950692b60b2..9ca530922ae5 100644
--- a/rust/cohort-stream-processor/src/workers/reconcile.rs
+++ b/rust/cohort-stream-processor/src/workers/reconcile.rs
@@ -7,8 +7,9 @@
use std::collections::VecDeque;
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::Arc;
+use std::time::Instant;
-use metrics::{counter, gauge};
+use metrics::{counter, gauge, histogram};
use tracing::{debug, info, warn};
use cohort_core::clickhouse_timestamp_to_millis;
@@ -22,8 +23,9 @@ use crate::filters::reverse_index::TeamFilters;
use crate::observability::metrics::{
COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH, RECONCILE_BITS_FIXED_TOTAL,
RECONCILE_JOBS_COMPLETED_TOTAL, RECONCILE_JOBS_DISCARDED_TOTAL,
- RECONCILE_MARKERS_EMITTED_TOTAL, RECONCILE_MARKER_PRODUCE_ERRORS, RECONCILE_QUEUE_DEPTH,
- RECONCILE_ROWS_EMITTED_TOTAL, RECONCILE_ROWS_SCANNED_TOTAL,
+ RECONCILE_MARKERS_EMITTED_TOTAL, RECONCILE_MARKER_PRODUCE_ERRORS,
+ RECONCILE_PAGE_DURATION_SECONDS, RECONCILE_QUEUE_DEPTH, RECONCILE_ROWS_EMITTED_TOTAL,
+ RECONCILE_ROWS_SCANNED_TOTAL,
};
use crate::partitions::offset_tracker::{DeferredOffset, MarkOutcome, OffsetTracker};
use crate::producer::{
@@ -35,7 +37,9 @@ use crate::store::{
ReadLane, Stage2CohortPrefix, Stage2DirtyKey, Stage2Key, StagedBatch, StoreHandle,
};
use crate::workers::merge_path::MergeWorkerDeps;
-use crate::workers::stage2_path::recompute_and_diff;
+use crate::workers::reconcile_page::read_page;
+#[cfg(test)]
+use crate::workers::reconcile_page::MAX_ROWS;
use crate::workers::worker::{
count_by_status, first_cascades, produce_cascades, produce_membership,
};
@@ -355,8 +359,8 @@ pub(crate) async fn handle_reconcile_drain(
// ordering prevents observing `loaded = true` alongside the pre-refresh empty snapshot.
let catalog_loaded = catalog.is_loaded();
let catalog_snapshot = catalog.load_full();
- let filters = catalog_snapshot.team(tile.team_id()).map(Arc::as_ref);
- match evaluate_guard(catalog_loaded, filters, &tile) {
+ let filters = catalog_snapshot.team(tile.team_id());
+ match evaluate_guard(catalog_loaded, filters.map(Arc::as_ref), &tile) {
ReconcileGuard::Retry(ReconcileRetryReason::CatalogNotLoaded) => {
debug!(
partition_id,
@@ -396,10 +400,6 @@ pub(crate) async fn handle_reconcile_drain(
}
let filters = filters.expect("the proceed guard proved the team exists");
- let tree = filters
- .cohorts
- .get(&tile.cohort_id())
- .expect("the proceed guard proved the cohort exists");
// Only flipped bits of a full-tree cohort cascade to referrers; single-leaf fixes never do.
let cascades_flips = filters
.eligibility
@@ -425,7 +425,6 @@ pub(crate) async fn handle_reconcile_drain(
queue,
&tile,
filters,
- tree,
cascades_flips,
prefix,
source_offset,
@@ -443,7 +442,6 @@ pub(crate) async fn handle_reconcile_drain(
queue,
&tile,
filters,
- tree,
cascades_flips,
prefix,
source_offset,
@@ -489,8 +487,7 @@ async fn drain_scanning(
merge: &MergeWorkerDeps,
queue: &mut ReconcileQueue,
tile: &ReconcileTile,
- filters: &TeamFilters,
- tree: &crate::filters::tree::CohortTree,
+ filters: &Arc<TeamFilters>,
cascades_flips: bool,
prefix: Stage2CohortPrefix,
source_offset: i64,
@@ -529,7 +526,6 @@ async fn drain_scanning(
merge,
tile,
filters,
- tree,
cascades_flips,
&page,
&dirty_to_clear,
@@ -575,8 +571,7 @@ async fn drain_dirty(
merge: &MergeWorkerDeps,
queue: &mut ReconcileQueue,
tile: &ReconcileTile,
- filters: &TeamFilters,
- tree: &crate::filters::tree::CohortTree,
+ filters: &Arc<TeamFilters>,
cascades_flips: bool,
prefix: Stage2CohortPrefix,
source_offset: i64,
@@ -640,7 +635,6 @@ async fn drain_dirty(
merge,
tile,
filters,
- tree,
cascades_flips,
&existing_keys,
&page,
@@ -797,6 +791,50 @@ struct PageProgress {
bits_fixed: u64,
}
+/// The ordered steps one settlement page takes. Doubles as the `stage` metric label, so the
+/// duration histogram can never name a step the page does not have.
+#[derive(Debug, Clone, Copy)]
+enum PageStage {
+ /// Every section of the page's read and evaluation, permit waits included.
+ Recompute,
+ MembershipProduce,
+ CascadeProduce,
+ Commit,
+}
+
+impl PageStage {
+ fn as_str(self) -> &'static str {
+ match self {
+ Self::Recompute => "recompute",
+ Self::MembershipProduce => "membership_produce",
+ Self::CascadeProduce => "cascade_produce",
+ Self::Commit => "commit",
+ }
+ }
+}
+
+/// Splits one page's wall clock into per-stage samples: each [`mark`](Self::mark) records the time
+/// since the previous one. A page that fails records no sample for the step that failed, so the
+/// histogram stays a picture of settled work.
+struct PageClock {
+ last: Instant,
+}
+
+impl PageClock {
+ fn start() -> Self {
+ Self {
+ last: Instant::now(),
+ }
+ }
+
+ fn mark(&mut self, stage: PageStage) {
+ let now = Instant::now();
+ histogram!(RECONCILE_PAGE_DURATION_SECONDS, "stage" => stage.as_str())
+ .record(now.duration_since(self.last).as_secs_f64());
+ self.last = now;
+ }
+}
+
/// Emit one current reconcile page, then atomically commit any corrected bits and clear the exact
/// dirty markers covered by that evaluation. Returning `None` leaves the queue phase unchanged so
/// the same page is retried on the next tick.
@@ -807,8 +845,7 @@ async fn settle_reconcile_page(
sink: &Arc<dyn MembershipSink>,
merge: &MergeWorkerDeps,
tile: &ReconcileTile,
- filters: &TeamFilters,
- tree: &crate::filters::tree::CohortTree,
+ filters: &Arc<TeamFilters>,
cascades_flips: bool,
page: &[Stage2Key],
dirty_to_clear: &[Stage2DirtyKey],
@@ -817,38 +854,37 @@ async fn settle_reconcile_page(
) -> Option<PageProgress> {
let evaluated_at_ms = clickhouse_timestamp_to_millis(last_updated)
.expect("worker-generated last_updated timestamps always parse");
- let mut changes = Vec::with_capacity(page.len());
+ let mut clock = PageClock::start();
+ let diffs = match read_page(handle, filters, tile.cohort_id(), page).await {
+ Ok(diffs) => diffs,
+ Err(error) => {
+ warn_job!(
+ tile,
+ partition_id,
+ rows = page.len(),
+ error = %error,
+ "reconcile page read failed; retrying this page on the next tick",
+ );
+ return None;
+ }
+ };
+ clock.mark(PageStage::Recompute);
+ debug_assert_eq!(
+ diffs.len(),
+ page.len(),
+ "the page reader returns one diff per requested row",
+ );
+
+ let mut changes = Vec::with_capacity(diffs.len());
let mut cascade_changes = Vec::new();
let mut writes: Vec<(Stage2Key, Stage2State)> = Vec::new();
let mut fixed_entered = 0u64;
let mut fixed_left = 0u64;
- for key in page {
- let diff = match recompute_and_diff(
- partition_id,
- key.person_id,
- tree,
- filters,
- handle,
- ReadLane::Maintenance,
- )
- .await
- {
- Ok(diff) => diff,
- Err(error) => {
- warn_job!(
- tile,
- partition_id,
- person_id = %key.person_id,
- error = %error,
- "reconcile recompute failed; retrying this page on the next tick",
- );
- return None;
- }
- };
+ for diff in &diffs {
let change = CohortMembershipChange {
team_id: tile.team_id().0,
cohort_id: tile.cohort_id().0,
- person_id: key.person_id.to_string(),
+ person_id: diff.stage2_key.person_id.to_string(),
last_updated: last_updated.to_string(),
status: diff.status(),
origin: Some(ChangeOrigin::Reconcile),
@@ -892,6 +928,7 @@ async fn settle_reconcile_page(
);
return None;
}
+ clock.mark(PageStage::MembershipProduce);
let cascade_errors = produce_cascades(merge, cascades).await;
if cascade_errors > 0 {
@@ -903,6 +940,7 @@ async fn settle_reconcile_page(
);
return None;
}
+ clock.mark(PageStage::CascadeProduce);
let mut staged = StagedBatch::default();
for (key, state) in &writes {
@@ -924,10 +962,11 @@ async fn settle_reconcile_page(
return None;
}
}
+ clock.mark(PageStage::Commit);
// Count only durably-settled pages: membership produce, cascade produce, and commit have all
// succeeded here. Any earlier failure returns `None` above and retries the whole page, so
// incrementing here keeps a retry from double-counting.
- counter!(RECONCILE_ROWS_SCANNED_TOTAL).increment(page.len() as u64);
+ counter!(RECONCILE_ROWS_SCANNED_TOTAL).increment(diffs.len() as u64);
if entered > 0 {
counter!(RECONCILE_ROWS_EMITTED_TOTAL, "status" => "entered").increment(entered);
}
@@ -942,7 +981,7 @@ async fn settle_reconcile_page(
}
Some(PageProgress {
- rows_scanned: page.len() as u64,
+ rows_scanned: diffs.len() as u64,
bits_fixed: fixed_entered + fixed_left,
})
}
@@ -2006,6 +2045,48 @@ mod tests {
assert_eq!(shell.committable(), Some(6));
}
+ /// A page wider than one read section still settles as one unit: the produce sees the whole
+ /// page, and a failure re-reads every row rather than resuming from the sections already read.
+ #[tokio::test]
+ async fn a_page_spanning_read_sections_retries_as_one_unit_after_a_membership_failure() {
+ let sink = CaptureSink::failing_first(1);
+ let rows = MAX_ROWS + 1;
+ let mut shell =
+ DrainShell::new(true, Arc::new(sink.clone()), CaptureCascadeSink::new(), 64);
+ let people: Vec<Uuid> = (1..=rows as u128).map(Uuid::from_u128).collect();
+ for &who in &people {
+ shell.write_current(who, true, false, false);
+ }
+ shell.enqueue(tile(TEAM, COHORT, 16), 5);
+
+ shell.tick().await;
+
+ assert_eq!(sink.produce_calls(), 1, "one produce for the whole page");
+ assert!(sink.changes().is_empty());
+ assert!(shell.markers.markers().is_empty());
+ assert!(
+ people.iter().all(|&who| !shell.stage2_bit(who)),
+ "no row of a failed page commits",
+ );
+ assert!(matches!(
+ shell.queue.front().map(|job| &job.phase),
+ Some(ScanPhase::Scanning { cursor: None }),
+ ));
+ assert_eq!(shell.committable(), Some(5));
+
+ shell.tick().await;
+
+ assert_eq!(
+ sink.changes().len(),
+ rows,
+ "the whole page was emitted again"
+ );
+ assert!(people.iter().all(|&who| shell.stage2_bit(who)));
+ shell.tick().await;
+ assert_eq!(shell.markers.markers().len(), 1);
+ assert_eq!(shell.committable(), Some(6));
+ }
+
#[tokio::test]
async fn cascade_failure_retries_before_committing_or_advancing() {
let sink = CaptureSink::new();
diff --git a/rust/cohort-stream-processor/src/workers/reconcile_page.rs b/rust/cohort-stream-processor/src/workers/reconcile_page.rs
new file mode 100644
index 000000000000..9eaf9361dc4a
--- /dev/null
+++ b/rust/cohort-stream-processor/src/workers/reconcile_page.rs
@@ -0,0 +1,1081 @@
+//! Reading and evaluating one reconcile settlement page in bounded blocking sections.
+//!
+//! Reconcile scans a whole cohort, so every row of a page composes the same tree: one
+//! [`CompositionReadPlan`] serves the page, and each row only binds it to a person. That lets a
+//! section carry many rows through one handoff instead of one row per handoff, which is the whole
+//! point of this module.
+//!
+//! What a section must not become is unbounded. A started blocking task cannot be cancelled and
+//! shutdown joins it, so each section stops at [`MAX_ROWS`] rows, [`MAX_KEYS`] keys, or
+//! [`MAX_BYTES`] of returned values, releases the maintenance permit, and resumes from the row it
+//! stopped in. Rows and keys are hard stops. Bytes are not: the budget is consulted between reads,
+//! so the peak a section can hold is [`MAX_BYTES`] plus whatever one more read of up to
+//! [`MAX_KEYS`] values returns. Sizing memory from [`MAX_BYTES`] alone understates it.
+//!
+//! The page stays the settlement boundary: [`read_page`] returns one diff per row or an error, so no
+//! caller can produce half a page. Only decoded inputs cross a section boundary, never a raw value.
+
+use std::sync::Arc;
+
+use metrics::{counter, histogram};
+
+use crate::filters::reverse_index::TeamFilters;
+use crate::filters::tree::CohortTree;
+use crate::filters::CohortId;
+use crate::observability::metrics::{
+ RECONCILE_KEYS_FETCHED_TOTAL, RECONCILE_READ_BYTES, RECONCILE_ROWS_ATTEMPTED_TOTAL,
+};
+use crate::stage2::evaluator::evaluate_tree;
+use crate::store::{BehavioralKey, CohortStore, Stage2Key, StoreError, StoreHandle};
+use crate::workers::composition_inputs::{
+ raw_bytes, CompositionReadPlan, PersonScope, ResolvedPersonInputs,
+};
+use crate::workers::stage2_path::RecomputeDiff;
+
+/// Rows one section may settle before handing the page back. Caps how much of a page one
+/// uncancellable blocking task owns, and with it the store permit it holds. Visible to
+/// [`reconcile`](super::reconcile) so its retry test can size a page that spans sections.
+pub(super) const MAX_ROWS: usize = 32;
+/// Keys one section may fetch, counting every state source. A fresh section always has its whole
+/// allowance, so every section issues at least one read and the page cannot stall.
+const MAX_KEYS: usize = 1_024;
+/// Returned value bytes after which a section stops issuing **further** reads. Not a ceiling: the
+/// read that crosses it has already returned, and the next read is handed the whole remaining key
+/// allowance, so a section's peak is this plus one read of up to [`MAX_KEYS`] values. Behavioral
+/// values grow with their window, which is why no key count bounds bytes, and why a single value
+/// larger than the whole budget still has to make progress rather than deadlock its row.
+/// [`RECONCILE_READ_BYTES`] measures what a read actually cost.
+const MAX_BYTES: usize = 4 * 1024 * 1024;
+
+const SECTION_OP: &str = "reconcile_page";
+
+/// Compose and diff every row of `page` against the bit the store holds, in sections that release
+/// the maintenance permit between them.
+///
+/// Reconcile's reads belong on [`ReadLane::Maintenance`](crate::store::ReadLane), which is the
+/// permit [`StoreHandle::run_section`] draws, so a cohort scan cannot contend with live event reads.
+///
+/// Diffs come back in scan order, one per row including the rows that did not change: the caller
+/// emits a full snapshot, not only flips.
+///
+/// # Panics
+/// `filters` must be the same frozen snapshot the drain guard passed, in which `cohort_id` has a
+/// tree. Reconcile's guard proves that before it scans; a caller that passes another snapshot
+/// panics in [`PageReader::evaluate`].
+pub(super) async fn read_page(
+ handle: &StoreHandle,
+ filters: &Arc<TeamFilters>,
+ cohort_id: CohortId,
+ page: &[Stage2Key],
+) -> Result<Vec<RecomputeDiff>, StoreError> {
+ // Dirty verification reaches here with every row of its page deleted. Those pages still have
+ // markers to clear, so the caller runs on; there is just nothing to take a store permit for.
+ if page.is_empty() {
+ return Ok(Vec::new());
+ }
+ let plan = Arc::new(CompositionReadPlan::for_cohorts([cohort_id], filters));
+ let mut reader = PageReader::new(Arc::clone(filters), plan, cohort_id, page.to_vec());
+ loop {
+ match handle
+ .run_section(SECTION_OP, move |store| reader.run_section(store))
+ .await??
+ {
+ PageRead::Complete(diffs) => return Ok(diffs),
+ PageRead::Reading(resumed) => reader = resumed,
+ }
+ }
+}
+
+/// One section's outcome. `Complete` is the only way to reach the diffs, so a page whose reads are
+/// unfinished cannot be settled.
+enum PageRead {
+ /// Keys are still outstanding. The reader carries every diff settled so far, and at most one
+ /// row's decoded inputs.
+ Reading(PageReader),
+ /// One diff per requested row, in scan order.
+ Complete(Vec<RecomputeDiff>),
+}
+
+struct PageReader {
+ filters: Arc<TeamFilters>,
+ plan: Arc<CompositionReadPlan>,
+ cohort_id: CohortId,
+ /// The rows to settle, in scan order.
+ page: Vec<Stage2Key>,
+ /// One diff per row already evaluated, so `page[diffs.len()]` is the row being read.
+ diffs: Vec<RecomputeDiff>,
+ /// Set only while that row's keys span a section boundary.
+ pending: Option<RowRead>,
+}
+
+impl PageReader {
+ fn new(
+ filters: Arc<TeamFilters>,
+ plan: Arc<CompositionReadPlan>,
+ cohort_id: CohortId,
+ page: Vec<Stage2Key>,
+ ) -> Self {
+ // The prior bit is read under `cohort_id` while the key written back comes from the row, so
+ // a row from another cohort's prefix would read one key and write another.
+ debug_assert!(
+ page.iter().all(|row| row.cohort_id == cohort_id.0 as u64),
+ "a reconcile page is one cohort's prefix scan",
+ );
+ Self {
+ filters,
+ plan,
+ cohort_id,
+ diffs: Vec::with_capacity(page.len()),
+ page,
+ pending: None,
+ }
+ }
+
+ /// Read, decode and evaluate rows until a budget stops the section or the page is finished.
+ /// Raw values are dropped inside this call, so only the diffs and one row's decoded inputs
+ /// survive it.
+ fn run_section(mut self, store: &CohortStore) -> Result<PageRead, StoreError> {
+ let plan = Arc::clone(&self.plan);
+ let filters = Arc::clone(&self.filters);
+ // Hoisted out of the row loop, so the section states the catalog precondition once.
+ let tree = filters
+ .cohorts
+ .get(&self.cohort_id)
+ .expect("the drain guard proved this cohort has a tree in the frozen catalog");
+ let mut budget = SectionBudget::default();
+ while self.diffs.len() < self.page.len() {
+ if !budget.accepts_row() {
+ return Ok(PageRead::Reading(self));
+ }
+ let row = self.page[self.diffs.len()];
+ let mut read = self.pending.take().unwrap_or_else(|| {
+ // Counted on the blocking thread with the keys, so a section whose caller future
+ // was dropped still records the rows it read.
+ counter!(RECONCILE_ROWS_ATTEMPTED_TOTAL).increment(1);
+ RowRead::new(&plan)
+ });
+ let scope = PersonScope::new(row.partition_id, row.team_id, row.person_id);
+ while let Some(next) = read.next {
+ let Some(key_limit) = budget.key_allowance() else {
+ self.pending = Some(read);
+ return Ok(PageRead::Reading(self));
+ };
+ read.next = RowSection {
+ store,
+ plan: &plan,
+ scope,
+ inputs: &mut read.inputs,
+ budget: &mut budget,
+ }
+ .read(next, key_limit)?;
+ }
+ let diff = self.evaluate(tree, row, &read.inputs);
+ self.diffs.push(diff);
+ budget.row_settled();
+ }
+ Ok(PageRead::Complete(self.diffs))
+ }
+
+ /// Compose the row and diff it against the bit the store holds. Runs in the section that
+ /// finished the row's reads, so the decoded inputs are spent here rather than retained for the
+ /// page.
+ fn evaluate(
+ &self,
+ tree: &CohortTree,
+ row: Stage2Key,
+ inputs: &ResolvedPersonInputs,
+ ) -> RecomputeDiff {
+ let references = self.plan.reference_membership(inputs);
+ let new_bit = evaluate_tree(&tree.root, inputs.membership(), &references);
+ RecomputeDiff::new(new_bit, inputs.prior_stage2(self.cohort_id), row)
+ }
+}
+
+/// What one section has spent.
+#[derive(Debug, Default)]
+struct SectionBudget {
+ rows: usize,
+ keys: usize,
+ bytes: usize,
+}
+
+impl SectionBudget {
+ fn accepts_row(&self) -> bool {
+ self.rows < MAX_ROWS
+ }
+
+ /// How many keys the next read may fetch, or `None` once the section is out of work.
+ fn key_allowance(&self) -> Option<usize> {
+ (self.keys < MAX_KEYS && self.bytes < MAX_BYTES).then(|| MAX_KEYS - self.keys)
+ }
+
+ fn spend(&mut self, keys: usize, bytes: usize) {
+ self.keys += keys;
+ self.bytes += bytes;
+ }
+
+ fn row_settled(&mut self) {
+ self.rows += 1;
+ }
+}
+
+/// One row's read in progress.
+struct RowRead {
+ inputs: ResolvedPersonInputs,
+ /// `None` once every key the plan names is decoded.
+ next: Option<NextRead>,
+}
+
+impl RowRead {
+ fn new(plan: &CompositionReadPlan) -> Self {
+ Self {
+ inputs: ResolvedPersonInputs::with_capacity_for(plan),
+ next: Some(NextRead::RecordAndBehavioral),
+ }
+ }
+}
+
+/// The next keys one row needs, in source order.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum NextRead {
+ /// Nothing read yet: the person record rides along the first batch of behavioral keys, in the
+ /// one mixed-CF lookup the event fold already issues.
+ RecordAndBehavioral,
+ /// Behavioral keys from this offset on; the record is decoded.
+ Behavioral(usize),
+ /// Stage 2 rows from this offset on.
+ Stage2(usize),
+}
+
+impl NextRead {
+ /// Where a row stands with `offset` behavioral keys decoded: the rest of them, else the next
+ /// source. [`RowRead::new`] names the first source; these two name every step after it.
+ fn behavioral_at(offset: usize, plan: &CompositionReadPlan) -> Option<Self> {
+ if offset < plan.behavioral().len() {
+ Some(Self::Behavioral(offset))
+ } else {
+ Self::stage2_at(0, plan)
+ }
+ }
+
+ fn stage2_at(offset: usize, plan: &CompositionReadPlan) -> Option<Self> {
+ (offset < plan.stage2_cohorts().len()).then_some(Self::Stage2(offset))
+ }
+}
+
+/// One section's reads for one row: holds what the whole section shares, so each read takes only
+/// what varies.
+struct RowSection<'a> {
+ store: &'a CohortStore,
+ plan: &'a CompositionReadPlan,
+ scope: PersonScope,
+ inputs: &'a mut ResolvedPersonInputs,
+ budget: &'a mut SectionBudget,
+}
+
+// The sanctioned sync context: these reads already run on the blocking pool, inside the section
+// `StoreHandle::run_section` offloaded.
+#[allow(clippy::disallowed_methods)]
+impl RowSection<'_> {
+ /// Fetch at most `key_limit` of the row's outstanding keys, decode them, and drop the raw
+ /// values. `None` once every key the plan names is decoded.
+ fn read(&mut self, next: NextRead, key_limit: usize) -> Result<Option<NextRead>, StoreError> {
+ match next {
+ NextRead::RecordAndBehavioral => self.record_and_behavioral(key_limit),
+ NextRead::Behavioral(from) => self.behavioral(from, key_limit),
+ NextRead::Stage2(from) => self.stage2(from, key_limit),
+ }
+ }
+
+ /// The person record rides along the first behavioral batch in one mixed-CF `multi_get`, so a
+ /// row costs one RocksDB lookup fewer. A row whose cohort reads no person condition asks for no
+ /// record.
+ fn record_and_behavioral(&mut self, key_limit: usize) -> Result<Option<NextRead>, StoreError> {
+ let record_key =
+ (!self.plan.person_leaves().is_empty()).then(|| self.scope.person_record_key());
+ let batch = batch_from(
+ self.plan.behavioral(),
+ 0,
+ key_limit.saturating_sub(usize::from(record_key.is_some())),
+ );
+ let keys: Vec<BehavioralKey> = batch
+ .iter()
+ .map(|&(lsk, _)| self.scope.behavioral_key(lsk))
+ .collect();
+ let snapshot = self.store.read_event_snapshot(&keys, record_key.as_ref())?;
+ if let Some(record) = snapshot.record {
+ self.spend(
+ ReadSource::PersonRecord,
+ 1,
+ record.as_ref().map_or(0, Vec::len),
+ );
+ self.inputs
+ .absorb_person_record(self.plan.person_leaves(), record);
+ }
+ if !batch.is_empty() {
+ self.spend(
+ ReadSource::Behavioral,
+ batch.len(),
+ raw_bytes(&snapshot.behavioral),
+ );
+ self.inputs.absorb_behavioral(batch, snapshot.behavioral);
+ }
+ Ok(NextRead::behavioral_at(batch.len(), self.plan))
+ }
+
+ fn behavioral(
+ &mut self,
+ from: usize,
+ key_limit: usize,
+ ) -> Result<Option<NextRead>, StoreError> {
+ let batch = batch_from(self.plan.behavioral(), from, key_limit);
+ let keys: Vec<BehavioralKey> = batch
+ .iter()
+ .map(|&(lsk, _)| self.scope.behavioral_key(lsk))
+ .collect();
+ let raw = self.store.multi_get_behavioral(&keys)?;
+ self.spend(ReadSource::Behavioral, batch.len(), raw_bytes(&raw));
+ self.inputs.absorb_behavioral(batch, raw);
+ Ok(NextRead::behavioral_at(from + batch.len(), self.plan))
+ }
+
+ /// The row's own prior bit and every composed referent's bit come from one key set, so a
+ /// referent is read as stored rather than substituted with a bit this page is about to write.
+ fn stage2(&mut self, from: usize, key_limit: usize) -> Result<Option<NextRead>, StoreError> {
+ let batch = batch_from(self.plan.stage2_cohorts(), from, key_limit);
+ let keys: Vec<Stage2Key> = batch
+ .iter()
+ .map(|&cohort_id| self.scope.stage2_key(cohort_id))
+ .collect();
+ let raw = self.store.multi_get_stage2(&keys)?;
+ self.spend(ReadSource::Stage2, batch.len(), raw_bytes(&raw));
+ self.inputs.absorb_stage2(batch, raw);
+ Ok(NextRead::stage2_at(from + batch.len(), self.plan))
+ }
+
+ fn spend(&mut self, source: ReadSource, keys: usize, bytes: usize) {
+ source.record(keys, bytes);
+ self.budget.spend(keys, bytes);
+ }
+}
+
+/// At most `limit` entries of `source` from `from`.
+fn batch_from<T>(source: &[T], from: usize, limit: usize) -> &[T] {
+ &source[from..source.len().min(from + limit)]
+}
+
+/// The closed set of `source` label values on the page 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!(RECONCILE_KEYS_FETCHED_TOTAL, "source" => self.label()).increment(keys as u64);
+ histogram!(RECONCILE_READ_BYTES, "source" => self.label()).record(bytes as f64);
+ }
+}
+
+#[cfg(test)]
+// Tests seed the store directly through `CohortStore`, the sanctioned direct-store surface for tests.
+#[allow(clippy::disallowed_methods)]
+mod tests {
+ use super::*;
+ use chrono_tz::UTC;
+ use serde_json::{json, Value};
+ use tempfile::TempDir;
+ use uuid::Uuid;
+
+ use crate::filters::{TeamFiltersBuilder, TeamId};
+ use crate::stage1::key::LeafStateKey;
+ use crate::stage1::person_record::{MatchedSet, PersonRecord};
+ use crate::stage1::state::{AppliedOffsets, Stage1State, StatefulRecord};
+ use crate::stage2::state::Stage2State;
+ use crate::store::{
+ Behavioral, OffloadConfig, OffloadMode, PersonRecordKey, PersonRecords, ReadLane,
+ StoreConfig,
+ };
+ use crate::workers::stage2_path::recompute_and_diff;
+
+ const TEAM: u64 = 7;
+ const PARTITION: u16 = 0;
+ const COHORT: CohortId = CohortId(1);
+ /// Composable, so cohort 1 reads it as a stored row.
+ const COMPOSED_REF: CohortId = CohortId(2);
+ /// One leaf, so cohort 1 reads it through that leaf's comparator.
+ const SINGLE_LEAF_REF: CohortId = CohortId(3);
+ const PERSON_HASH: [u8; 16] = *b"fedcba9876543210";
+ const EVENT_MS: i64 = 1_700_000_000_000;
+
+ fn temp_store() -> (TempDir, CohortStore) {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ (dir, store)
+ }
+
+ /// Wraps the store so `read_page` exercises the same blocking-pool transport as production.
+ fn handle(store: &CohortStore) -> StoreHandle {
+ StoreHandle::new(
+ store.clone(),
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ )
+ }
+
+ 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": "fedcba9876543210",
+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],
+ })
+ }
+
+ fn cohort_ref(target: CohortId, negation: bool) -> Value {
+ json!({ "type": "cohort", "value": target.0, "negation": negation })
+ }
+
+ fn hash(text: &str) -> [u8; 16] {
+ text.as_bytes().try_into().expect("a 16-byte hash")
+ }
+
+ fn freeze(cohorts: Vec<(CohortId, Vec<Value>)>) -> Arc<TeamFilters> {
+ let mut builder = TeamFiltersBuilder::default();
+ for (id, values) in cohorts {
+ let cohort = json!({ "properties": { "type": "AND", "values": values } });
+ builder
+ .add_cohort(id, TeamId(TEAM as i32), &cohort)
+ .unwrap();
+ }
+ Arc::new(builder.freeze_with(UTC, true))
+ }
+
+ /// Cohort 1 over every reference kind and both leaf stores, so one page exercises each state
+ /// source a reconcile read has.
+ fn mixed_cohort() -> Arc<TeamFilters> {
+ freeze(vec![
+ (
+ COHORT,
+ vec![
+ behavioral_leaf("own0000000000001"),
+ person_leaf(),
+ cohort_ref(COMPOSED_REF, false),
+ cohort_ref(SINGLE_LEAF_REF, false),
+ // Absent from the catalog, so it reads as a non-member and the negation lets
+ // the AND through.
+ cohort_ref(CohortId(404), true),
+ ],
+ ),
+ (
+ COMPOSED_REF,
+ vec![behavioral_leaf("ref0000000000002"), person_leaf()],
+ ),
+ (SINGLE_LEAF_REF, vec![behavioral_leaf("ref0000000000003")]),
+ ])
+ }
+
+ fn person(n: u128) -> Uuid {
+ Uuid::from_u128(n)
+ }
+
+ fn stage2_key(cohort: CohortId, who: Uuid) -> Stage2Key {
+ Stage2Key {
+ partition_id: PARTITION,
+ team_id: TEAM,
+ cohort_id: cohort.0 as u64,
+ person_id: who,
+ }
+ }
+
+ fn behavioral_match() -> Stage1State {
+ Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: EVENT_MS,
+ earliest_eviction_at_ms: i64::MAX,
+ }
+ }
+
+ fn behavioral_miss() -> Stage1State {
+ Stage1State::BehavioralSingle {
+ has_match: false,
+ last_event_at_ms: EVENT_MS,
+ earliest_eviction_at_ms: i64::MAX,
+ }
+ }
+
+ fn write_behavioral(store: &CohortStore, lsk: LeafStateKey, who: Uuid, state: Stage1State) {
+ let record = StatefulRecord::new(state, AppliedOffsets::default());
+ write_behavioral_bytes(store, lsk, who, &record.encode());
+ }
+
+ fn write_behavioral_bytes(store: &CohortStore, lsk: LeafStateKey, who: Uuid, bytes: &[u8]) {
+ let key = BehavioralKey::new(PARTITION, TEAM, who, lsk);
+ store
+ .write_batch(|b| b.put::<Behavioral>(&key, bytes))
+ .unwrap();
+ }
+
+ fn write_person_record(store: &CohortStore, who: Uuid, matched: &[[u8; 16]]) {
+ let key = PersonRecordKey::new(PARTITION, TEAM, who);
+ let mut record = PersonRecord::absent();
+ record.matched = MatchedSet::from_iter(matched.iter().copied());
+ store
+ .write_batch(|b| b.put::<PersonRecords>(&key, &record.encode()))
+ .unwrap();
+ }
+
+ fn write_corrupt_person_record(store: &CohortStore, who: Uuid) {
+ let key = PersonRecordKey::new(PARTITION, TEAM, who);
+ store
+ .write_batch(|b| b.put::<PersonRecords>(&key, b"not a person record"))
+ .unwrap();
+ }
+
+ fn write_stage2(store: &CohortStore, cohort: CohortId, who: Uuid, in_cohort: bool) {
+ let state = Stage2State {
+ in_cohort,
+ last_evaluated_at_ms: EVENT_MS,
+ };
+ write_stage2_bytes(store, cohort, who, &state.encode());
+ }
+
+ /// A bit a merge transfer carried over, which a receiver-side evaluation must claim even when
+ /// the logical membership is unchanged.
+ fn write_transferred_fallback(store: &CohortStore, cohort: CohortId, who: Uuid, bit: bool) {
+ let state = Stage2State {
+ in_cohort: bit,
+ last_evaluated_at_ms: EVENT_MS,
+ };
+ write_stage2_bytes(store, cohort, who, &state.encode_transferred_fallback());
+ }
+
+ fn write_stage2_bytes(store: &CohortStore, cohort: CohortId, who: Uuid, bytes: &[u8]) {
+ let key = stage2_key(cohort, who);
+ store.write_batch(|b| b.put_stage2(&key, bytes)).unwrap();
+ }
+
+ /// Everything the settlement path reads off one diff.
+ fn settled(diff: &RecomputeDiff) -> (Stage2Key, bool, bool, bool, bool) {
+ (
+ diff.stage2_key,
+ diff.new_bit,
+ diff.prior_bit,
+ diff.flipped(),
+ diff.requires_write(),
+ )
+ }
+
+ /// Drive the reader the way [`read_page`] does, but synchronously, so a test can see exactly
+ /// where the section boundaries fell: one entry per section, holding the rows it settled and
+ /// where the next section resumes. `None` means it stopped between rows, not inside one.
+ fn read_in_sections(
+ store: &CohortStore,
+ filters: &Arc<TeamFilters>,
+ page: &[Stage2Key],
+ ) -> (Vec<RecomputeDiff>, Vec<(usize, Option<NextRead>)>) {
+ let plan = Arc::new(CompositionReadPlan::for_cohorts([COHORT], filters));
+ let mut reader = PageReader::new(Arc::clone(filters), plan, COHORT, page.to_vec());
+ let mut sections = Vec::new();
+ let mut settled = 0;
+ loop {
+ match reader.run_section(store).unwrap() {
+ PageRead::Complete(diffs) => {
+ sections.push((diffs.len() - settled, None));
+ return (diffs, sections);
+ }
+ PageRead::Reading(resumed) => {
+ let resume = resumed.pending.as_ref().and_then(|read| read.next);
+ sections.push((resumed.diffs.len() - settled, resume));
+ settled = resumed.diffs.len();
+ reader = resumed;
+ }
+ }
+ }
+ }
+
+ async fn per_row(
+ store: &CohortStore,
+ filters: &Arc<TeamFilters>,
+ page: &[Stage2Key],
+ ) -> Vec<RecomputeDiff> {
+ let handle = handle(store);
+ let tree = filters.cohorts.get(&COHORT).expect("the cohort is frozen");
+ let mut diffs = Vec::with_capacity(page.len());
+ for key in page {
+ diffs.push(
+ recompute_and_diff(
+ PARTITION,
+ key.person_id,
+ tree,
+ filters,
+ &handle,
+ ReadLane::Maintenance,
+ )
+ .await
+ .unwrap(),
+ );
+ }
+ diffs
+ }
+
+ /// One person per state shape a reconcile scan meets. Returns the page in scan order.
+ fn seed_every_state_shape(store: &CohortStore, filters: &TeamFilters) -> Vec<Stage2Key> {
+ let own = filters.by_condition_to_lsk[&hash("own0000000000001")][0];
+ let referent = filters.by_condition_to_lsk[&hash("ref0000000000003")][0];
+
+ // Everything matches over a non-member row: enters.
+ let entering = person(1);
+ write_behavioral(store, own, entering, behavioral_match());
+ write_person_record(store, entering, &[PERSON_HASH]);
+ write_behavioral(store, referent, entering, behavioral_match());
+ write_stage2(store, COMPOSED_REF, entering, true);
+ write_stage2(store, COHORT, entering, false);
+
+ // No state at all, and no row of its own: stays a non-member and writes nothing.
+ let absent = person(2);
+ write_stage2(store, COHORT, absent, false);
+
+ // Everything matches over a member row: unchanged.
+ let unchanged = person(3);
+ write_behavioral(store, own, unchanged, behavioral_match());
+ write_person_record(store, unchanged, &[PERSON_HASH]);
+ write_behavioral(store, referent, unchanged, behavioral_match());
+ write_stage2(store, COMPOSED_REF, unchanged, true);
+ write_stage2(store, COHORT, unchanged, true);
+
+ // A corrupt behavioral value reads as a non-member, so a stale member bit is fixed.
+ let corrupt_leaf = person(4);
+ write_behavioral_bytes(store, own, corrupt_leaf, b"not a stage 1 record");
+ write_person_record(store, corrupt_leaf, &[PERSON_HASH]);
+ write_behavioral(store, referent, corrupt_leaf, behavioral_match());
+ write_stage2(store, COMPOSED_REF, corrupt_leaf, true);
+ write_stage2(store, COHORT, corrupt_leaf, true);
+
+ // A corrupt person record reads every person leaf as a non-member, over a transferred
+ // fallback the evaluation must claim even though the bit does not move.
+ let corrupt_record = person(5);
+ write_behavioral(store, own, corrupt_record, behavioral_match());
+ write_corrupt_person_record(store, corrupt_record);
+ write_behavioral(store, referent, corrupt_record, behavioral_match());
+ write_stage2(store, COMPOSED_REF, corrupt_record, true);
+ write_transferred_fallback(store, COHORT, corrupt_record, false);
+
+ // A corrupt own row reads as a non-member prior, so a real member enters again.
+ let corrupt_prior = person(6);
+ write_behavioral(store, own, corrupt_prior, behavioral_match());
+ write_person_record(store, corrupt_prior, &[PERSON_HASH]);
+ write_behavioral(store, referent, corrupt_prior, behavioral_match());
+ write_stage2(store, COMPOSED_REF, corrupt_prior, true);
+ write_stage2_bytes(store, COHORT, corrupt_prior, b"not a stage 2 row");
+
+ // The composed referent is a non-member, so the AND fails on the reference alone.
+ let referent_missing = person(7);
+ write_behavioral(store, own, referent_missing, behavioral_match());
+ write_person_record(store, referent_missing, &[PERSON_HASH]);
+ write_behavioral(store, referent, referent_missing, behavioral_match());
+ write_stage2(store, COHORT, referent_missing, true);
+
+ // The single-leaf referent misses, which only its own comparator can tell.
+ let leaf_referent_miss = person(8);
+ write_behavioral(store, own, leaf_referent_miss, behavioral_match());
+ write_person_record(store, leaf_referent_miss, &[PERSON_HASH]);
+ write_behavioral(store, referent, leaf_referent_miss, behavioral_miss());
+ write_stage2(store, COMPOSED_REF, leaf_referent_miss, true);
+ write_stage2(store, COHORT, leaf_referent_miss, true);
+
+ (1..=8).map(|n| stage2_key(COHORT, person(n))).collect()
+ }
+
+ /// The page reader is the only reconcile read path, so what keeps it honest is agreement with
+ /// `recompute_and_diff` — the per-row path it replaced, still live on the cascade.
+ #[tokio::test]
+ async fn a_page_agrees_with_the_per_row_path_on_every_state_shape() {
+ let (_dir, store) = temp_store();
+ let filters = mixed_cohort();
+ let page = seed_every_state_shape(&store, &filters);
+
+ let by_page = read_page(&handle(&store), &filters, COHORT, &page)
+ .await
+ .unwrap();
+ let by_row = per_row(&store, &filters, &page).await;
+
+ assert_eq!(
+ by_page.iter().map(settled).collect::<Vec<_>>(),
+ by_row.iter().map(settled).collect::<Vec<_>>(),
+ );
+ assert_eq!(
+ by_page.iter().map(|diff| diff.new_bit).collect::<Vec<_>>(),
+ [true, false, true, false, false, true, false, false],
+ "the fixture has to exercise both bits, or agreement proves nothing",
+ );
+ assert_eq!(
+ by_page
+ .iter()
+ .map(|diff| diff.requires_write())
+ .collect::<Vec<_>>(),
+ [true, false, false, true, true, true, true, true],
+ "an unchanged transferred fallback still settles its ownership",
+ );
+ }
+
+ /// Page widths derived from the row budget, so the test sits on the boundary wherever it moves:
+ /// exactly the budget is one section, one more splits it.
+ const ROW_BOUNDARY_PAGES: [usize; 2] = [MAX_ROWS, MAX_ROWS + 1];
+
+ #[tokio::test]
+ async fn a_page_wider_than_the_row_budget_settles_every_row_across_sections() {
+ for (rows, expected) in ROW_BOUNDARY_PAGES
+ .into_iter()
+ .zip([vec![(MAX_ROWS, None)], vec![(MAX_ROWS, None), (1, None)]])
+ {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![(COHORT, vec![behavioral_leaf("own0000000000001")])]);
+ let own = filters.by_condition_to_lsk[&hash("own0000000000001")][0];
+ let page: Vec<Stage2Key> = (0..rows)
+ .map(|index| {
+ let who = person(index as u128 + 1);
+ write_behavioral(&store, own, who, behavioral_match());
+ write_stage2(&store, COHORT, who, false);
+ stage2_key(COHORT, who)
+ })
+ .collect();
+
+ let (diffs, sections) = read_in_sections(&store, &filters, &page);
+
+ assert_eq!(
+ sections, expected,
+ "{rows} rows: the row budget stops a section between rows, never inside one",
+ );
+ assert_eq!(
+ diffs.iter().map(settled).collect::<Vec<_>>(),
+ per_row(&store, &filters, &page)
+ .await
+ .iter()
+ .map(settled)
+ .collect::<Vec<_>>(),
+ "{rows} rows",
+ );
+ }
+ }
+
+ /// Leaf counts derived from the key budget. A row reads its person record, its behavioral
+ /// leaves and its one Stage 2 row, so `MAX_KEYS - 2` leaves is exactly one section's allowance
+ /// and one more splits the row.
+ const KEY_BOUNDARY_WIDTHS: [usize; 2] = [MAX_KEYS - 2, MAX_KEYS - 1];
+
+ fn wide_leaf(index: usize) -> Value {
+ behavioral_leaf(&format!("beh{index:013}"))
+ }
+
+ /// A leaf the read skipped would leave the AND short, so the entry proves every key landed.
+ #[tokio::test]
+ async fn a_row_wider_than_the_key_budget_reads_every_key_across_sections() {
+ let expectations = [
+ vec![(1, None)],
+ // One key short: the row's own Stage 2 read is what spills into a second section.
+ vec![(0, Some(NextRead::Stage2(0))), (1, None)],
+ ];
+ for (leaves, expected) in KEY_BOUNDARY_WIDTHS.into_iter().zip(expectations) {
+ let (_dir, store) = temp_store();
+ let mut values: Vec<Value> = (0..leaves).map(wide_leaf).collect();
+ values.push(person_leaf());
+ let filters = freeze(vec![(COHORT, values)]);
+ let lsks: Vec<LeafStateKey> = (0..leaves)
+ .map(|index| filters.by_condition_to_lsk[&hash(&format!("beh{index:013}"))][0])
+ .collect();
+
+ let alice = person(1);
+ for &lsk in &lsks {
+ write_behavioral(&store, lsk, alice, behavioral_match());
+ }
+ write_person_record(&store, alice, &[PERSON_HASH]);
+ let page = vec![stage2_key(COHORT, alice)];
+
+ let (entered, sections) = read_in_sections(&store, &filters, &page);
+ assert_eq!(sections, expected, "{leaves} leaves");
+ assert!(entered[0].new_bit, "{leaves} leaves");
+
+ // The entry above proves every batch landed. This half pins that the last leaf's value
+ // is read, not just its key.
+ write_behavioral(&store, lsks[leaves - 1], alice, behavioral_miss());
+ let (left, _) = read_in_sections(&store, &filters, &page);
+ assert!(!left[0].new_bit, "{leaves} leaves");
+ }
+ }
+
+ /// A value bigger than the whole byte budget: the read that crosses it is already issued, so
+ /// the section has to stop after it rather than refuse to make progress.
+ #[tokio::test]
+ async fn a_value_larger_than_the_byte_budget_stops_the_section_after_it() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![(COHORT, vec![behavioral_leaf("own0000000000001")])]);
+ let own = filters.by_condition_to_lsk[&hash("own0000000000001")][0];
+ let oversized = vec![b'x'; MAX_BYTES + 1];
+ let page: Vec<Stage2Key> = (1..=2)
+ .map(|index| {
+ let who = person(index);
+ write_behavioral_bytes(&store, own, who, &oversized);
+ write_stage2(&store, COHORT, who, true);
+ stage2_key(COHORT, who)
+ })
+ .collect();
+
+ let (diffs, sections) = read_in_sections(&store, &filters, &page);
+
+ // Per row: the oversized behavioral read crosses the budget and ends the section with the
+ // row unsettled, then the next section reads its Stage 2 row.
+ assert_eq!(
+ sections,
+ [
+ (0, Some(NextRead::Stage2(0))),
+ (1, Some(NextRead::Stage2(0))),
+ (1, None),
+ ],
+ );
+ assert_eq!(
+ diffs.iter().map(settled).collect::<Vec<_>>(),
+ per_row(&store, &filters, &page)
+ .await
+ .iter()
+ .map(settled)
+ .collect::<Vec<_>>(),
+ "an undecodable oversized value still reads as a non-member",
+ );
+ }
+
+ /// A cohort whose tree names only references reads no behavioral key and no person record, so
+ /// its first source is empty. Skipping an empty source has to advance the read; a reader that
+ /// re-entered it would spin on a section that spends nothing.
+ #[tokio::test]
+ async fn a_cohort_with_no_leaves_reads_only_its_stage_2_rows() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![
+ (
+ COHORT,
+ vec![
+ cohort_ref(COMPOSED_REF, false),
+ cohort_ref(CohortId(404), true),
+ ],
+ ),
+ (
+ COMPOSED_REF,
+ vec![behavioral_leaf("ref0000000000002"), person_leaf()],
+ ),
+ ]);
+ let alice = person(1);
+ write_stage2(&store, COMPOSED_REF, alice, true);
+ write_stage2(&store, COHORT, alice, false);
+ let page = vec![stage2_key(COHORT, alice)];
+
+ let (diffs, sections) = read_in_sections(&store, &filters, &page);
+
+ assert_eq!(sections, [(1, None)]);
+ assert!(
+ diffs[0].new_bit,
+ "the referent's stored bit is the only input this cohort has",
+ );
+ assert_eq!(
+ diffs.iter().map(settled).collect::<Vec<_>>(),
+ per_row(&store, &filters, &page)
+ .await
+ .iter()
+ .map(settled)
+ .collect::<Vec<_>>(),
+ );
+ }
+
+ /// The row that starts with one key left in the section reads its person record alone. Charging
+ /// the record to the row's own allowance is what keeps that read non-empty — a section that
+ /// handed out a zero allowance would spin instead of yielding.
+ #[tokio::test]
+ async fn a_row_that_starts_with_one_key_left_reads_its_record_alone() {
+ // A row costs its record, its behavioral leaves and its one Stage 2 row. Size the cohort so
+ // that every row but the last spends the key allowance down to exactly one.
+ let full_rows = MAX_ROWS - 1;
+ let keys_per_row = (MAX_KEYS - 1) / full_rows;
+ assert_eq!(
+ full_rows * keys_per_row,
+ MAX_KEYS - 1,
+ "the budgets no longer divide into the corner this test exists for",
+ );
+ let leaves = keys_per_row - 2;
+
+ let (_dir, store) = temp_store();
+ let mut values: Vec<Value> = (0..leaves).map(wide_leaf).collect();
+ values.push(person_leaf());
+ let filters = freeze(vec![(COHORT, values)]);
+ let lsks: Vec<LeafStateKey> = (0..leaves)
+ .map(|index| filters.by_condition_to_lsk[&hash(&format!("beh{index:013}"))][0])
+ .collect();
+ let page: Vec<Stage2Key> = (0..MAX_ROWS)
+ .map(|index| {
+ let who = person(index as u128 + 1);
+ for &lsk in &lsks {
+ write_behavioral(&store, lsk, who, behavioral_match());
+ }
+ write_person_record(&store, who, &[PERSON_HASH]);
+ write_stage2(&store, COHORT, who, false);
+ stage2_key(COHORT, who)
+ })
+ .collect();
+
+ let (diffs, sections) = read_in_sections(&store, &filters, &page);
+
+ assert_eq!(
+ sections,
+ [(full_rows, Some(NextRead::Behavioral(0))), (1, None)],
+ "the one key left buys the record alone, so the behavioral read resumes at 0",
+ );
+ assert!(
+ diffs.iter().all(|diff| diff.new_bit),
+ "a row split across sections still reads every leaf",
+ );
+ }
+
+ /// Bytes accumulate across rows, not only within one read. A page of many moderate values is
+ /// what the byte budget exists for; the oversized-value case above crosses it inside one read.
+ #[tokio::test]
+ async fn bytes_accumulate_across_rows_until_the_budget_stops_the_section() {
+ // Sized so a whole number of rows fits under the budget, with rows to spare after it.
+ let value_bytes = MAX_BYTES / 8 + 1;
+ let rows_within_budget = MAX_BYTES / value_bytes;
+ let rows = rows_within_budget + 3;
+
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![(COHORT, vec![behavioral_leaf("own0000000000001")])]);
+ let own = filters.by_condition_to_lsk[&hash("own0000000000001")][0];
+ let value = vec![b'x'; value_bytes];
+ let page: Vec<Stage2Key> = (0..rows)
+ .map(|index| {
+ let who = person(index as u128 + 1);
+ write_behavioral_bytes(&store, own, who, &value);
+ write_stage2(&store, COHORT, who, true);
+ stage2_key(COHORT, who)
+ })
+ .collect();
+
+ let (diffs, sections) = read_in_sections(&store, &filters, &page);
+
+ // The budget is consulted between reads, so the row that crosses it has already issued one
+ // read and finishes in the next section — it is not held back whole.
+ assert_eq!(
+ sections,
+ [
+ (rows_within_budget, Some(NextRead::Stage2(0))),
+ (rows - rows_within_budget, None),
+ ],
+ "the crossing row settles in the next section, not the one that read it",
+ );
+ assert_eq!(
+ diffs.iter().map(settled).collect::<Vec<_>>(),
+ per_row(&store, &filters, &page)
+ .await
+ .iter()
+ .map(settled)
+ .collect::<Vec<_>>(),
+ );
+ }
+
+ /// Benchmark, not a test. Run it in release:
+ ///
+ /// ```text
+ /// cargo test -p cohort-stream-processor --release --lib \
+ /// reconcile_page_benchmark -- --ignored --nocapture
+ /// ```
+ ///
+ /// It asserts agreement only, because a wall-time threshold would flake on a slower box. It
+ /// times the read and evaluation alone: acknowledgments are the settlement half, measured in
+ /// production off `cohort_reconcile_page_duration_seconds`. Handoffs per row come from
+ /// `store_offload_exec_duration_seconds{op="reconcile_page"}_count` over
+ /// `cohort_reconcile_rows_attempted_total`.
+ #[tokio::test]
+ #[ignore = "benchmark; run in release with --ignored --nocapture"]
+ async fn reconcile_page_benchmark() {
+ use std::time::Instant;
+
+ println!(
+ "{:>5} {:>12} {:>12} {:>7}",
+ "page", "per-row", "by-page", "ratio"
+ );
+ for rows in [256, 512] {
+ let (_dir, store) = temp_store();
+ let filters = mixed_cohort();
+ let own = filters.by_condition_to_lsk[&hash("own0000000000001")][0];
+ let referent = filters.by_condition_to_lsk[&hash("ref0000000000003")][0];
+ let page: Vec<Stage2Key> = (0..rows)
+ .map(|index| {
+ let who = person(index as u128 + 1);
+ write_behavioral(&store, own, who, year_long_history());
+ write_behavioral(&store, referent, who, year_long_history());
+ write_person_record(&store, who, &[PERSON_HASH]);
+ write_stage2(&store, COMPOSED_REF, who, true);
+ // Half the rows disagree with the truth, so half the page really flips.
+ write_stage2(&store, COHORT, who, index % 2 == 0);
+ stage2_key(COHORT, who)
+ })
+ .collect();
+ let handle = handle(&store);
+
+ // Warm the block cache, so the timed passes measure the read shape and not the first
+ // touch of every SST.
+ let warm_by_page = read_page(&handle, &filters, COHORT, &page).await.unwrap();
+ let warm_per_row = per_row(&store, &filters, &page).await;
+ assert_eq!(
+ warm_by_page.iter().map(settled).collect::<Vec<_>>(),
+ warm_per_row.iter().map(settled).collect::<Vec<_>>(),
+ );
+
+ let started = Instant::now();
+ per_row(&store, &filters, &page).await;
+ let per_row_elapsed = started.elapsed();
+
+ let started = Instant::now();
+ read_page(&handle, &filters, COHORT, &page).await.unwrap();
+ let by_page_elapsed = started.elapsed();
+
+ println!(
+ "{:>5} {:>10.1?} {:>10.1?} {:>6.2}x",
+ rows,
+ per_row_elapsed,
+ by_page_elapsed,
+ per_row_elapsed.as_secs_f64() / by_page_elapsed.as_secs_f64(),
+ );
+ }
+ }
+
+ /// One entry per day of a year-long window, so each value is kilobytes rather than bytes.
+ fn year_long_history() -> 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,
+ }
+ }
+}
diff --git a/rust/cohort-stream-processor/src/workers/stage2_path.rs b/rust/cohort-stream-processor/src/workers/stage2_path.rs
index f463e6da71f0..1d0f89f8b2cb 100644
--- a/rust/cohort-stream-processor/src/workers/stage2_path.rs
+++ b/rust/cohort-stream-processor/src/workers/stage2_path.rs
@@ -27,7 +27,7 @@ use crate::stage2::state::{Stage2Ownership, Stage2State};
use crate::store::{
BehavioralKey, PersonRecordKey, ReadLane, Stage2Key, StagedBatch, StoreError, StoreHandle,
};
-use crate::workers::stage2_person_inputs::ReferenceSource;
+use crate::workers::composition_inputs::ReferenceSource;
/// `affected_leaves` is the touched `(leaf, person)` set; `lane` is the read lane every recompute
/// read runs on. Every caller passes `Event`: the seed paths, which read on `Maintenance`, go
@@ -504,7 +504,8 @@ pub(crate) async fn commit_stage2_writes(
}
/// One cohort's recomputed membership for one person, diffed against the stored `cf_stage2` bit.
-/// Shared by Stage 2 composition and the cascade handler so the two recompute paths cannot diverge.
+/// Shared by Stage 2 composition, the cascade handler and reconcile's page reader, so those
+/// recompute paths cannot diverge on what a diff means.
pub(crate) struct RecomputeDiff {
pub new_bit: bool,
pub prior_bit: bool,
diff --git a/rust/cohort-stream-processor/src/workers/stage2_person_inputs.rs b/rust/cohort-stream-processor/src/workers/stage2_person_inputs.rs
index 3bc89dca86cf..1b0b5bf84f52 100644
--- a/rust/cohort-stream-processor/src/workers/stage2_person_inputs.rs
+++ b/rust/cohort-stream-processor/src/workers/stage2_person_inputs.rs
@@ -1,7 +1,8 @@
//! 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.
+//! each person once rather than once per affected cohort. The plan and the decoded inputs are
+//! [`composition_inputs`](super::composition_inputs); this module is the seed-side reader over them.
//!
//! Two boundaries the sharing must not cross:
//!
@@ -11,29 +12,23 @@
//! 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 std::collections::{BTreeMap, BTreeSet};
use metrics::{counter, histogram};
use uuid::Uuid;
-use crate::filters::reverse_index::{LeafStateMeta, TeamFilters};
+use crate::filters::reverse_index::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,
+use crate::stage2::evaluator::evaluate_tree;
+use crate::store::{BehavioralKey, CohortStore, Stage2Key, StoreError, StoreHandle};
+use crate::workers::composition_inputs::{
+ raw_bytes, CompositionReadPlan, PersonScope, ResolvedPersonInputs,
};
+use crate::workers::stage2_path::{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
@@ -46,9 +41,10 @@ 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
+/// maintenance permit. The live, sweep and cascade paths compose on
/// [`ReadLane::Event`](crate::store::ReadLane) and cannot move here without putting hot-path reads
-/// behind the backfill lane.
+/// behind the backfill lane; reconcile already reads on the maintenance lane and has its own
+/// page-wide reader in [`reconcile_page`](super::reconcile_page).
///
/// `team_id` is the key `filters` sit under in the frozen catalog, so every cohort here composes
/// from that team's keyspace.
@@ -84,12 +80,13 @@ pub(crate) async fn recompute_stage2_by_person(
// 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);
+ let plan = CompositionReadPlan::for_cohorts(cohorts.iter().copied(), filters);
if plan.is_empty() {
continue;
}
+ let scope = PersonScope::new(partition_id, team_id.0 as u64, person_id);
- let mut reader = PersonInputReader::new(plan);
+ let mut reader = PersonInputReader::new(plan, scope);
loop {
reader = handle
.run_section(SECTION_OP, move |store| {
@@ -104,7 +101,7 @@ pub(crate) async fn recompute_stage2_by_person(
let (plan, inputs) = reader.finish();
let references = plan.reference_membership(&inputs);
- for &cohort_id in &plan.cohorts {
+ for &cohort_id in plan.cohorts() {
let tree = filters
.cohorts
.get(&cohort_id)
@@ -116,13 +113,13 @@ pub(crate) async fn recompute_stage2_by_person(
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);
+ 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),
+ scope.stage2_key(cohort_id),
),
);
}
@@ -144,236 +141,16 @@ pub(crate) async fn recompute_stage2_by_person(
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.
+/// Executes one person's [`CompositionReadPlan`] 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,
+ plan: CompositionReadPlan,
+ scope: PersonScope,
inputs: ResolvedPersonInputs,
started: bool,
behavioral_read: usize,
@@ -382,13 +159,11 @@ struct PersonInputReader {
#[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()),
- };
+ fn new(plan: CompositionReadPlan, scope: PersonScope) -> Self {
+ let inputs = ResolvedPersonInputs::with_capacity_for(&plan);
Self {
plan,
+ scope,
inputs,
started: false,
behavioral_read: 0,
@@ -412,11 +187,11 @@ impl PersonInputReader {
fn is_done(&self) -> bool {
self.started
- && self.behavioral_read == self.plan.behavioral.len()
- && self.stage2_read == self.plan.stage2_cohorts.len()
+ && self.behavioral_read == self.plan.behavioral().len()
+ && self.stage2_read == self.plan.stage2_cohorts().len()
}
- fn finish(self) -> (PersonReadPlan, ResolvedPersonInputs) {
+ fn finish(self) -> (CompositionReadPlan, ResolvedPersonInputs) {
(self.plan, self.inputs)
}
@@ -428,21 +203,21 @@ impl PersonInputReader {
) -> Result<(), StoreError> {
let chunk = self
.plan
- .behavioral
+ .behavioral()
.chunks(READ_CHUNK_KEYS)
.next()
.unwrap_or(&[]);
let keys: Vec<BehavioralKey> = chunk
.iter()
- .map(|&(lsk, _)| self.plan.behavioral_key(lsk))
+ .map(|&(lsk, _)| self.scope.behavioral_key(lsk))
.collect();
let record_key =
- (!self.plan.person_leaves.is_empty()).then(|| self.plan.person_record_key());
+ (!self.plan.person_leaves().is_empty()).then(|| self.scope.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);
+ .absorb_person_record(self.plan.person_leaves(), record);
}
if !keys.is_empty() {
ReadSource::Behavioral.record(keys.len(), raw_bytes(&snapshot.behavioral));
@@ -453,13 +228,13 @@ impl PersonInputReader {
}
fn read_behavioral_chunk(&mut self, store: &CohortStore) -> Result<(), StoreError> {
- let rest = &self.plan.behavioral[self.behavioral_read..];
+ 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))
+ .map(|&(lsk, _)| self.scope.behavioral_key(lsk))
.collect();
let raw = store.multi_get_behavioral(&keys)?;
ReadSource::Behavioral.record(keys.len(), raw_bytes(&raw));
@@ -471,21 +246,17 @@ impl PersonInputReader {
/// 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 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))
+ .map(|&cohort_id| self.scope.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.inputs.absorb_stage2(chunk, raw);
self.stage2_read += chunk.len();
Ok(())
}
@@ -514,171 +285,3 @@ impl ReadSource {
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)]);
- }
-}