:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(cohorts): batch seed apply (#95016)
Matheus Batista9f096c60af30
diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rsindex b0e759404db3..cf80ae1d1ef9 100644--- a/rust/cohort-stream-processor/src/config.rs+++ b/rust/cohort-stream-processor/src/config.rs@@ -1,5 +1,6 @@//! Service configuration, loaded from environment variables via `envconfig`.+use std::num::NonZeroUsize;use std::path::PathBuf;use std::time::Duration;@@ -14,6 +15,7 @@ use tracing::warn;use crate::partitions::pacing::{AgeMs, Hysteresis, SeedPacingConfig, UsedPct};use crate::store::durability::DurabilityConfig;use crate::store::{OffloadConfig, OffloadMode, StoreConfig};+use crate::workers::seed_run::RunBudget;use crate::workers::{CascadeConfig, EventNameGating, TransferRetryPolicy};const POOL_NAME: &str = "posthog_cohort";@@ -276,6 +278,20 @@ pub struct Config {#[envconfig(from = "COHORT_SEED_PERSON_LIVE_MARGIN_MS", default = "900000")]pub cohort_seed_person_live_margin_ms: i64,+ /// Seeds one partition worker applies as a single run. `1` limits each run to one seed through+ /// the same apply pipeline; it does not restore a different implementation.+ #[envconfig(from = "COHORT_SEED_APPLY_BATCH_MAX", default = "256")]+ pub cohort_seed_apply_batch_max: usize,++ /// Store rows one run may touch: the stage-1 rows its seeds fold plus one stage-2 register per+ /// cohort those leaves back. This bounds entry counts in the overlay, register read, recompute+ /// set, and outputs. It is not a byte limit: behavioral row sizes grow with their windows.+ /// Reads inside each composed evaluation scale with that cohort's tree and use the maintenance+ /// lane's permits. A run closes before the seed that would exceed the budget; a seed heavier+ /// than the whole budget still runs alone.+ #[envconfig(from = "COHORT_SEED_APPLY_BATCH_MAX_ROWS", default = "4096")]+ pub cohort_seed_apply_batch_max_rows: usize,+/// Live-priority gate: pause a seed partition once its live watermark age reaches this (ms)./// `0` disables the trigger.#[envconfig(from = "COHORT_SEED_LIVE_LAG_PAUSE_MS", default = "120000")]@@ -670,6 +686,16 @@ impl Config {.max(Duration::from_secs(1))}+ /// The run ceilings the partition workers group seeds under. Validated at startup, so a+ /// zero here is a bug rather than a config error.+ pub fn seed_run_budget(&self) -> RunBudget {+ RunBudget {+ seeds: NonZeroUsize::new(self.cohort_seed_apply_batch_max).unwrap_or(NonZeroUsize::MIN),+ rows: NonZeroUsize::new(self.cohort_seed_apply_batch_max_rows)+ .unwrap_or(NonZeroUsize::MIN),+ }+ }+pub fn reconcile_tick_interval(&self) -> Duration {Duration::from_millis(self.cohort_seed_reconcile_tick_interval_ms)}@@ -777,6 +803,16 @@ impl Config {self.cohort_seed_reconcile_tick_interval_ms > 0,"COHORT_SEED_RECONCILE_TICK_INTERVAL_MS must be greater than zero.",);+ // A zero run ceiling would form no run at all, so every seed would be neither marked nor+ // held and the partition would wedge behind the first one.+ ensure!(+ self.cohort_seed_apply_batch_max > 0,+ "COHORT_SEED_APPLY_BATCH_MAX must be greater than zero (1 = one seed per run).",+ );+ ensure!(+ self.cohort_seed_apply_batch_max_rows > 0,+ "COHORT_SEED_APPLY_BATCH_MAX_ROWS must be greater than zero.",+ );let pacing = self.seed_pacing_config()?;// Idle partitions' watermarks advance only once per probe, so a pause threshold inside@@ -1174,6 +1210,8 @@ mod tests {cohort_seed_reconcile_tick_interval_ms: 2_000,cohort_seed_person_apply_enabled: false,cohort_seed_person_live_margin_ms: 900_000,+ cohort_seed_apply_batch_max: 256,+ cohort_seed_apply_batch_max_rows: 4096,cohort_seed_live_lag_pause_ms: 120_000,cohort_seed_live_lag_resume_ms: 60_000,cohort_seed_disk_pause_pct: 60.0,@@ -1254,6 +1292,36 @@ mod tests {.contains("COHORT_SEED_RECONCILE_TICK_INTERVAL_MS"),);}+ /// A zero ceiling would form no run at all, so every seed would be neither marked nor held+ /// and the partition would wedge behind the first one.+ #[test]+ fn seed_run_budget_rejects_zero_ceilings_and_maps_the_defaults() {+ let defaults = test_config();+ assert_eq!(defaults.seed_run_budget().seeds.get(), 256);+ assert_eq!(defaults.seed_run_budget().rows.get(), 4096);++ let mut config = test_config();+ config.cohort_seed_apply_batch_max = 0;+ assert!(config+ .validate_startup()+ .unwrap_err()+ .to_string()+ .contains("COHORT_SEED_APPLY_BATCH_MAX"),);++ config.cohort_seed_apply_batch_max = 1;+ config.cohort_seed_apply_batch_max_rows = 0;+ assert!(config+ .validate_startup()+ .unwrap_err()+ .to_string()+ .contains("COHORT_SEED_APPLY_BATCH_MAX_ROWS"),);++ // `1` is the documented hatch back to the per-seed apply, so it must start.+ config.cohort_seed_apply_batch_max_rows = 1;+ assert!(config.validate_startup().is_ok());+ assert_eq!(config.seed_run_budget().seeds.get(), 1);+ }+#[test]fn reconcile_without_the_seed_consumer_warns_but_starts() {let mut config = test_config();diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rsindex 9a41f071280c..58b292759cfb 100644--- a/rust/cohort-stream-processor/src/consumers/events.rs+++ b/rust/cohort-stream-processor/src/consumers/events.rs@@ -1903,6 +1903,7 @@ mod tests {register_transfer_enabled: true,reconcile,person_seed: crate::workers::PersonSeedDeps::default(),+ seed_budget: crate::workers::seed_run::RunBudget::default(),});let dispatcher = EventDispatcher::new(PartitionRouter::new(64),@@ -2613,6 +2614,7 @@ mod tests {register_transfer_enabled: false,reconcile,person_seed: crate::workers::PersonSeedDeps::default(),+ seed_budget: crate::workers::seed_run::RunBudget::default(),});let dispatcher = Arc::new(EventDispatcher::new(PartitionRouter::new(64),diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rsindex 0e4028f29522..b3df865ecd8f 100644--- a/rust/cohort-stream-processor/src/main.rs+++ b/rust/cohort-stream-processor/src/main.rs@@ -263,6 +263,7 @@ async fn async_main(config: Config) -> Result<()> {enabled: config.cohort_seed_person_apply_enabled,live_margin_ms: config.cohort_seed_person_live_margin_ms,},+ seed_budget: config.seed_run_budget(),});// Cheap `Arc` clones taken before the originals move into the dispatcher: the checkpoint sweeperdiff --git a/rust/cohort-stream-processor/src/merge/tombstone_redirect.rs b/rust/cohort-stream-processor/src/merge/tombstone_redirect.rsindex aa79c1cf35b7..de9ab3995669 100644--- a/rust/cohort-stream-processor/src/merge/tombstone_redirect.rs+++ b/rust/cohort-stream-processor/src/merge/tombstone_redirect.rs@@ -8,6 +8,8 @@//! lands on a different partition (re-keyed and re-produced). The chain `origin` is always the//! straggler's own person id, since it keys into `redirect_dedup`.+use std::collections::HashMap;+use metrics::counter;use tracing::{debug, warn};use uuid::Uuid;@@ -108,13 +110,7 @@ fn read_tombstone(let Some(bytes) = store.get_tombstone(&key)? else {return Ok(None);};- match Tombstone::decode(&bytes) {- Ok(tombstone) => Ok(Some(tombstone)),- Err(error) => {- debug!(partition_id, %person, error = %error, "corrupt tombstone; treating as not merged");- Ok(None)- }- }+ Ok(decode_tombstone(partition_id, person, &bytes))}/// Async twin of [`resolve`] over the [`StoreHandle`] facade; each hop reads on the caller's@@ -133,8 +129,83 @@ pub async fn resolve_offloaded(else {return Ok(Resolution::NotMerged);};+ walk_from(+ handle,+ partition_id,+ team_id,+ person,+ first,+ partition_count,+ lane,+ )+ .await+}- let origin = person;+/// Resolve many distinct `(team, person)` keys, reading every chain's first hop in one batched+/// `multi_get` and walking the rest from there.+///+/// Only a chain whose first hop lands back on this partition needs its later hops walked one at a+/// time, and that requires a merge, so a backfill run normally pays exactly one read for the whole+/// run. A repeated key costs a redundant read and resolves to the same verdict.+///+/// A short `multi_get` yields a map missing those keys. The caller must treat a missing key as a+/// failure, never as `NotMerged`: applying a seed to a person that may have merged away is durable+/// state nothing downstream can retract.+pub async fn resolve_batch_offloaded(+ handle: &StoreHandle,+ partition_id: u16,+ persons: &[(TeamId, Uuid)],+ partition_count: u32,+ lane: ReadLane,+) -> Result<HashMap<(TeamId, Uuid), Resolution>, StoreError> {+ let keys: Vec<TombstoneKey> = persons+ .iter()+ .map(|&(team_id, person)| TombstoneKey {+ partition_id,+ team_id: team_id.0 as u64,+ person,+ })+ .collect();+ let values = handle.multi_get_tombstones(keys, lane).await?;++ let mut resolved = HashMap::with_capacity(persons.len());+ for (&(team_id, person), bytes) in persons.iter().zip(values) {+ let first = bytes+ .as_deref()+ .and_then(|bytes| decode_tombstone(partition_id, person, bytes));+ let resolution = match first {+ None => Resolution::NotMerged,+ Some(first) => {+ walk_from(+ handle,+ partition_id,+ team_id,+ person,+ first,+ partition_count,+ lane,+ )+ .await?+ }+ };+ resolved.insert((team_id, person), resolution);+ }+ Ok(resolved)+}++/// Follow a chain from its already-read first hop. Shared by the single and batched resolvers, so+/// a batched read's decoded hop is never re-read: the walk starts from its target and checks that+/// target's partition before touching the store again.+async fn walk_from(+ handle: &StoreHandle,+ partition_id: u16,+ team_id: TeamId,+ origin: Uuid,+ first: Tombstone,+ partition_count: u32,+ lane: ReadLane,+) -> Result<Resolution, StoreError> {+ let team = team_id.0 as u64;let mut current = first.new_person;for _hop in 0..MAX_TOMBSTONE_HOPS {@@ -185,11 +256,17 @@ async fn read_tombstone_offloaded(let Some(bytes) = handle.get_tombstone(&key, lane).await? else {return Ok(None);};- match Tombstone::decode(&bytes) {- Ok(tombstone) => Ok(Some(tombstone)),+ Ok(decode_tombstone(partition_id, person, &bytes))+}++/// Decode one stored tombstone, or `None` when the bytes are corrupt. A corrupt marker reads as+/// "not merged", the same degrade a missing marker gets.+fn decode_tombstone(partition_id: u16, person: Uuid, bytes: &[u8]) -> Option<Tombstone> {+ match Tombstone::decode(bytes) {+ Ok(tombstone) => Some(tombstone),Err(error) => {debug!(partition_id, %person, error = %error, "corrupt tombstone; treating as not merged");- Ok(None)+ None}}}@@ -221,7 +298,7 @@ mod tests {use crate::merge::transfer::Tombstone;use crate::partitions::partitioner::COHORT_PARTITION_COUNT;- use crate::store::StoreConfig;+ use crate::store::{OffloadConfig, OffloadMode, StoreConfig};const TEAM: TeamId = TeamId(7);@@ -379,6 +456,67 @@ mod tests {));}+ /// One batched first-hop read must answer every key with its own verdict. A shifted answer+ /// would route one person's seed through another person's merge chain, which is durable state+ /// nothing downstream can retract.+ #[tokio::test]+ async fn resolve_batch_reads_one_first_hop_per_key_and_walks_only_local_chains() {+ let (_dir, store) = temp_store();+ let handle = StoreHandle::new(+ store.clone(),+ OffloadConfig {+ mode: OffloadMode::All,+ event_read_permits: 4,+ maintenance_permits: 4,+ },+ );+ let p_old = Uuid::from_u128(0xA11CE);+ let part = partition(p_old);+ let locals = (1u128..)+ .map(Uuid::from_u128)+ .filter(|p| partition(*p) == part && *p != p_old)+ .take(3)+ .collect::<Vec<_>>();+ let (p_mid, p_final, p_unmerged) = (locals[0], locals[1], locals[2]);+ let p_leaving = (1u128..)+ .map(Uuid::from_u128)+ .find(|p| partition(*p) == part && ![p_old, p_mid, p_final, p_unmerged].contains(p))+ .unwrap();+ let p_far = person_not_on(part);+ write_tombstone(&store, part, p_old, p_mid);+ write_tombstone(&store, part, p_mid, p_final);+ write_tombstone(&store, part, p_leaving, p_far);++ let resolved = resolve_batch_offloaded(+ &handle,+ part,+ &[(TEAM, p_old), (TEAM, p_unmerged), (TEAM, p_leaving)],+ COHORT_PARTITION_COUNT,+ ReadLane::Maintenance,+ )+ .await+ .unwrap();++ assert_eq!(resolved.len(), 3, "one verdict per key asked");+ assert_eq!(+ resolved[&(TEAM, p_old)],+ Resolution::Inline {+ final_person: p_final,+ origin: p_old,+ },+ "the chain converges past the batched hop and the origin stays the first person",+ );+ assert_eq!(resolved[&(TEAM, p_unmerged)], Resolution::NotMerged);+ assert_eq!(+ resolved[&(TEAM, p_leaving)],+ Resolution::CrossPartition {+ target_person: p_far,+ origin: p_leaving,+ },+ "a first hop that leaves the partition is a hand-off, not a walk",+ );+ }+#[test]fn corrupt_tombstone_reads_as_not_merged() {let (_dir, store) = temp_store();diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rsindex 9b329336a032..a8b7cd2c06e5 100644--- a/rust/cohort-stream-processor/src/observability/metrics.rs+++ b/rust/cohort-stream-processor/src/observability/metrics.rs@@ -281,7 +281,9 @@ pub const STAGE1_PERSON_RECORD_TOTAL: &str = "stage1_person_record_total";pub const STAGE1_PERSON_RECORD_SIZE_BYTES: &str = "stage1_person_record_size_bytes";/// Behavioral applies staged per event — the write fan-out of the behavioral side (histogram).pub const STAGE1_BEHAVIORAL_APPLIES: &str = "stage1_behavioral_applies";-/// Leaf membership flips emitted, labelled by `kind` (counter).+/// Leaf membership flips emitted, labelled by `kind` (counter). The seed paths count a run's+/// *net* flip per leaf, not one per seed: a run that enters then leaves the same leaf counts+/// nothing, because that is what it tells downstream.pub const STAGE1_TRANSITIONS: &str = "stage1_transitions_total";/// `cf_behavioral` records written, labelled by `variant` (counter).pub const STAGE1_STATE_WRITES: &str = "stage1_state_writes_total";@@ -292,6 +294,8 @@ pub const STAGE1_REPLAY_SKIPPED: &str = "stage1_replay_skipped_total";/// (counter). A defensive guard against a stale catalog.pub const STAGE1_UNSUPPORTED_VARIANT_SKIPPED: &str = "stage1_unsupported_variant_skipped_total";/// Stored `cf_behavioral` values that failed to decode; the key is skipped, not panicked (counter).+/// The seed path counts once per corrupt row its run reads, not once per tile that touches it;+/// `cohort_seed_tiles_dropped_total{reason="corrupt_state"}` is still per tile-leaf.pub const STAGE1_STATE_DECODE_ERROR: &str = "stage1_state_decode_error_total";/// End-to-end per-event processing latency in the worker (histogram, seconds).pub const STAGE1_EVENT_PROCESS_DURATION: &str = "stage1_event_process_duration_seconds";@@ -503,6 +507,8 @@ pub const PERSON_SEEDS_DROPPED_TOTAL: &str = "cohort_person_seeds_dropped_total"/// from an absent baseline, dropping whatever the unreadable row held outside the seed's evaluated/// set. **Any non-zero value is a real record-codec failure, not a dormant person** — the event/// path's `stage1_person_record_total{result="corrupt"}` is the same signal for live traffic.+/// Counted once per corrupt row the run's batched read decodes, not once per seed that touches+/// it, so a rate comparison across the batched-apply roll is not apples to apples.pub const PERSON_SEED_PRIOR_CORRUPT_TOTAL: &str = "cohort_person_seed_prior_corrupt_total";/// Hashes dropped from a person seed's effective set, labelled by `reason`/// (`unknown_hash`|`variant_mismatch`) (counter). **Sustained non-zero means the run's pinned@@ -526,6 +532,17 @@ pub const PERSON_SEED_REKEY_PRODUCE_FAILURE_TOTAL: &str =/// edited cohort whose leaf key moved, a transferred fallback row — so read it against the seed/// produce-failure counters before concluding produces are failing.**pub const SEED_REGISTER_REPAIRS_TOTAL: &str = "cohort_seed_register_repairs_total";++/// Seeds applied as one run, labelled by `kind` (histogram). The p50 is the batching win: `1` means+/// every seed still pays its own produce round trip.+pub const SEED_APPLY_RUN_SIZE: &str = "cohort_seed_apply_run_size";+/// Wall time one run spent in each pipeline step, labelled by `kind` and `stage` (histogram). A+/// held run records no sample for the step that failed, so the histogram stays a picture of+/// completed work; [`SEED_APPLY_RUNS_HELD_TOTAL`] carries the failures.+pub const SEED_APPLY_RUN_DURATION_SECONDS: &str = "cohort_seed_apply_run_duration_seconds";+/// Runs that held their first offset instead of marking, labelled by `kind` and `stage` (counter).+/// **Alert on a sustained non-zero rate: the partition is replaying the same run.**+pub const SEED_APPLY_RUNS_HELD_TOTAL: &str = "cohort_seed_apply_runs_held_total";/// The seed commit floor pinned by a sticky offset hold, labelled by `partition` (gauge)./// **Alert on a sustained non-zero level.**pub const SEED_HELD_OFFSET_GAUGE: &str = "seed_held_offset";@@ -893,6 +910,15 @@ mod tests {SEED_REGISTER_REPAIRS_TOTAL,"cohort_seed_register_repairs_total");+ assert_eq!(SEED_APPLY_RUN_SIZE, "cohort_seed_apply_run_size");+ assert_eq!(+ SEED_APPLY_RUN_DURATION_SECONDS,+ "cohort_seed_apply_run_duration_seconds",+ );+ assert_eq!(+ SEED_APPLY_RUNS_HELD_TOTAL,+ "cohort_seed_apply_runs_held_total"+ );// The held-offset gauge deliberately mirrors merge_held_offset/cascade_held_offset.assert_eq!(SEED_HELD_OFFSET_GAUGE, "seed_held_offset");assert_eq!(SEED_FENCED_PARTITIONS, "cohort_seed_fenced_partitions");diff --git a/rust/cohort-stream-processor/src/producer/merge.rs b/rust/cohort-stream-processor/src/producer/merge.rsindex d47c958d8dfd..eafbaa7f6778 100644--- a/rust/cohort-stream-processor/src/producer/merge.rs+++ b/rust/cohort-stream-processor/src/producer/merge.rs@@ -113,6 +113,9 @@ const FAIL_ALWAYS: usize = usize::MAX;pub(crate) struct Capture<T> {items: Arc<Mutex<Vec<T>>>,fail_remaining: Arc<AtomicUsize>,+ /// Produce calls made, failed ones included. A test that asserts how much a batch amortizes+ /// counts calls, not records: the round trip is what a run is paying to avoid.+ calls: Arc<AtomicUsize>,}impl<T> Clone for Capture<T> {@@ -120,6 +123,7 @@ impl<T> Clone for Capture<T> {Self {items: self.items.clone(),fail_remaining: self.fail_remaining.clone(),+ calls: self.calls.clone(),}}}@@ -129,6 +133,7 @@ impl<T> Default for Capture<T> {Self {items: Arc::default(),fail_remaining: Arc::default(),+ calls: Arc::default(),}}}@@ -136,8 +141,8 @@ impl<T> Default for Capture<T> {impl<T> Capture<T> {pub(crate) fn failing_first(n: usize) -> Self {Self {- items: Arc::default(),fail_remaining: Arc::new(AtomicUsize::new(n)),+ ..Self::default()}}@@ -145,7 +150,12 @@ impl<T> Capture<T> {Self::failing_first(FAIL_ALWAYS)}+ pub(crate) fn produce_calls(&self) -> usize {+ self.calls.load(Ordering::SeqCst)+ }+pub(crate) fn produce(&self, items: Vec<T>) -> Vec<Result<(), KafkaProduceError>> {+ self.calls.fetch_add(1, Ordering::SeqCst);let should_fail = self.fail_remaining.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| match n {diff --git a/rust/cohort-stream-processor/src/producer/mod.rs b/rust/cohort-stream-processor/src/producer/mod.rsindex 9c8c613be9bf..12bd1b1f8b16 100644--- a/rust/cohort-stream-processor/src/producer/mod.rs+++ b/rust/cohort-stream-processor/src/producer/mod.rs@@ -183,6 +183,11 @@ impl CaptureSink {pub fn changes(&self) -> Vec<CohortMembershipChange> {self.0.recorded()}++ /// Produce calls made, failed ones included — the round trips a batched apply is amortizing.+ pub fn produce_calls(&self) -> usize {+ self.0.produce_calls()+ }}#[async_trait]diff --git a/rust/cohort-stream-processor/src/store/handle.rs b/rust/cohort-stream-processor/src/store/handle.rsindex fb18812cb51e..d8bd1f93f768 100644--- a/rust/cohort-stream-processor/src/store/handle.rs+++ b/rust/cohort-stream-processor/src/store/handle.rs@@ -292,6 +292,19 @@ impl StoreHandle {.await}+ /// Batch-read `cf_person_records` values, preserving input order. The person-seed run's read+ /// pass, on the maintenance lane.+ pub async fn multi_get_person_records(+ &self,+ keys: Vec<PersonRecordKey>,+ lane: ReadLane,+ ) -> Result<Vec<Option<Vec<u8>>>, StoreError> {+ self.read("multi_get_person_records", lane, move |store| {+ store.multi_get_person_records(&keys)+ })+ .await+ }+/// Point-read one person's `cf_person_records` value as raw bytes; decoding lives with the/// caller.pub async fn get_person_record(@@ -375,6 +388,19 @@ impl StoreHandle {self.store.track_stage2_dirty(prefix)}+ /// Batch-read redirect tombstones, preserving input order. One seed run resolves every+ /// distinct person's first hop here, then walks only the chains that stay on this partition.+ pub async fn multi_get_tombstones(+ &self,+ keys: Vec<TombstoneKey>,+ lane: ReadLane,+ ) -> Result<Vec<Option<Vec<u8>>>, StoreError> {+ self.read("multi_get_tombstones", lane, move |store| {+ store.multi_get_tombstones(&keys)+ })+ .await+ }+/// Point-read one redirect tombstone.pub async fn get_tombstone(&self,diff --git a/rust/cohort-stream-processor/src/store/rocks.rs b/rust/cohort-stream-processor/src/store/rocks.rsindex b12acf9ba0b8..caf9123c96e2 100644--- a/rust/cohort-stream-processor/src/store/rocks.rs+++ b/rust/cohort-stream-processor/src/store/rocks.rs@@ -446,22 +446,33 @@ impl CohortStore {self.get(Cf::Behavioral, &key.encode())}- /// Batch-read several `cf_behavioral` values in one call, preserving input order.- pub fn multi_get_behavioral(+ /// One batched read of `cf`, preserving input order. Every typed `multi_get_*` routes through+ /// it, so none can skip the empty-batch or answer-length checks or label its errors differently.+ fn multi_get_ordered<K, B: AsRef<[u8]>>(&self,- keys: &[BehavioralKey],+ cf: Cf,+ keys: &[K],+ encode: impl Fn(&K) -> B,) -> Result<Vec<Option<Vec<u8>>>, StoreError> {// An empty batch is not a read: skip it so it records no phantom read-latency sample.if keys.is_empty() {return Ok(Vec::new());}- let handle = self.cf(Cf::Behavioral)?;- let encoded: Vec<_> = keys.iter().map(BehavioralKey::encode).collect();+ let handle = self.cf(cf)?;+ let encoded: Vec<B> = keys.iter().map(encode).collect();let started = Instant::now();let results = self.db- .multi_get_cf(encoded.iter().map(|key| (handle, key.as_slice())));+ .multi_get_cf(encoded.iter().map(|key| (handle, key.as_ref())));record_multi_get(started, keys.len());+ if results.len() != keys.len() {+ counter!(STORE_ERRORS_TOTAL, "op" => OP_MULTI_GET).increment(1);+ return Err(StoreError::ShortRead {+ op: OP_MULTI_GET,+ asked: keys.len(),+ answered: results.len(),+ });+ }results.into_iter().map(|result| {@@ -476,6 +487,30 @@ impl CohortStore {.collect()}+ /// Batch-read several `cf_behavioral` values in one call, preserving input order.+ pub fn multi_get_behavioral(+ &self,+ keys: &[BehavioralKey],+ ) -> Result<Vec<Option<Vec<u8>>>, StoreError> {+ self.multi_get_ordered(Cf::Behavioral, keys, BehavioralKey::encode)+ }++ /// Batch-read several `cf_person_records` values in one call, preserving input order.+ pub fn multi_get_person_records(+ &self,+ keys: &[PersonRecordKey],+ ) -> Result<Vec<Option<Vec<u8>>>, StoreError> {+ self.multi_get_ordered(Cf::PersonRecords, keys, PersonRecordKey::encode)+ }++ /// Batch-read several `cf_merge_tombstones` values in one call, preserving input order.+ pub fn multi_get_tombstones(+ &self,+ keys: &[TombstoneKey],+ ) -> Result<Vec<Option<Vec<u8>>>, StoreError> {+ self.multi_get_ordered(Cf::MergeTombstones, keys, TombstoneKey::encode)+ }+/// Point-read one person's `cf_person_records` value as raw bytes. Decoding into a/// [`PersonRecord`](crate::stage1::PersonRecord) lives with the caller.pub fn get_person_record(&self, key: &PersonRecordKey) -> Result<Option<Vec<u8>>, StoreError> {@@ -607,29 +642,7 @@ impl CohortStore {/// Batch-read several `cf_stage2` values in one call, preserving input order.pub fn multi_get_stage2(&self, keys: &[Stage2Key]) -> Result<Vec<Option<Vec<u8>>>, StoreError> {- // An empty batch is not a read: skip it so it records no phantom read-latency sample.- if keys.is_empty() {- return Ok(Vec::new());- }- let handle = self.cf(Cf::Stage2)?;- let encoded: Vec<_> = keys.iter().map(Stage2Key::encode).collect();- let started = Instant::now();- let results = self- .db- .multi_get_cf(encoded.iter().map(|key| (handle, key.as_slice())));- record_multi_get(started, keys.len());- results- .into_iter()- .map(|result| {- result.map_err(|source| {- counter!(STORE_ERRORS_TOTAL, "op" => OP_MULTI_GET).increment(1);- StoreError::Backend {- op: OP_MULTI_GET,- source,- }- })- })- .collect()+ self.multi_get_ordered(Cf::Stage2, keys, Stage2Key::encode)}/// Scan up to `limit` keys in one partition/team/cohort slice of `cf_stage2`, in person order,@@ -1460,6 +1473,14 @@ mod tests {PersonRecordKey::new(partition, 7, Uuid::from_u128(person))}+ fn tombstone_key(person: u128) -> TombstoneKey {+ TombstoneKey {+ partition_id: 3,+ team_id: 7,+ person: Uuid::from_u128(person),+ }+ }+#[test]fn wipe_on_start_clears_existing_state_and_is_a_noop_when_off() {let dir = TempDir::new().unwrap();@@ -1646,6 +1667,65 @@ mod tests {);}+ /// A hole that shifted the answers would pair one person's record with another person's key,+ /// folding a seed onto the wrong state.+ #[test]+ fn multi_get_person_records_preserves_order_and_reports_absent_keys() {+ let dir = TempDir::new().unwrap();+ let store = CohortStore::open(&StoreConfig {+ path: dir.path().join("db"),+ ..StoreConfig::default()+ })+ .unwrap();++ let a = record_key(3, 1);+ let b = record_key(3, 2);+ let absent = record_key(3, 9);+ store+ .write_batch(|batch| {+ batch.put::<PersonRecords>(&a, b"alpha");+ batch.put::<PersonRecords>(&b, b"bravo");+ })+ .unwrap();++ let results = store.multi_get_person_records(&[a, absent, b]).unwrap();+ assert_eq!(results.len(), 3);+ assert_eq!(results[0].as_deref(), Some(b"alpha".as_slice()));+ assert_eq!(results[1], None);+ assert_eq!(results[2].as_deref(), Some(b"bravo".as_slice()));++ assert!(store.multi_get_person_records(&[]).unwrap().is_empty());+ }++ /// A shifted answer here would route a seed through another person's merge chain.+ #[test]+ fn multi_get_tombstones_preserves_order_and_reports_absent_keys() {+ let dir = TempDir::new().unwrap();+ let store = CohortStore::open(&StoreConfig {+ path: dir.path().join("db"),+ ..StoreConfig::default()+ })+ .unwrap();++ let a = tombstone_key(1);+ let b = tombstone_key(2);+ let absent = tombstone_key(9);+ store+ .write_batch(|batch| {+ batch.put_tombstone(&a, b"alpha");+ batch.put_tombstone(&b, b"bravo");+ })+ .unwrap();++ let results = store.multi_get_tombstones(&[a, absent, b]).unwrap();+ assert_eq!(results.len(), 3);+ assert_eq!(results[0].as_deref(), Some(b"alpha".as_slice()));+ assert_eq!(results[1], None);+ assert_eq!(results[2].as_deref(), Some(b"bravo".as_slice()));++ assert!(store.multi_get_tombstones(&[]).unwrap().is_empty());+ }+#[test]fn person_record_get_round_trips_through_its_cf() {let dir = TempDir::new().unwrap();diff --git a/rust/cohort-stream-processor/src/workers/cascade_path.rs b/rust/cohort-stream-processor/src/workers/cascade_path.rsindex 7754efd2d582..d925b71191f2 100644--- a/rust/cohort-stream-processor/src/workers/cascade_path.rs+++ b/rust/cohort-stream-processor/src/workers/cascade_path.rs@@ -449,6 +449,7 @@ mod tests {register_transfer_enabled: false,reconcile: crate::workers::ReconcileDeps::default(),person_seed: crate::workers::PersonSeedDeps::default(),+ seed_budget: crate::workers::seed_run::RunBudget::default(),};// The cascade was dispatched this tenure, so its ceiling is raised — mirrors the dispatcher.deps.cascade_trackerdiff --git a/rust/cohort-stream-processor/src/workers/merge_path.rs b/rust/cohort-stream-processor/src/workers/merge_path.rsindex 07c92b4db0b7..4a065497bcf1 100644--- a/rust/cohort-stream-processor/src/workers/merge_path.rs+++ b/rust/cohort-stream-processor/src/workers/merge_path.rs@@ -38,6 +38,7 @@ use crate::stage1::transition::LeafTransition;use crate::store::{BehavioralKey, PendingTransferKey, ReadLane, StoreHandle};use crate::sweep::EvictionQueue;use crate::workers::person_seed_path::PersonSeedDeps;+use crate::workers::seed_run::RunBudget;use crate::workers::stage2_path::compose_stage2;use crate::workers::worker::{affected_leaves, first_cascades, produce_cascades, produce_membership, transition_metric_label,@@ -139,6 +140,8 @@ pub struct MergeWorkerDeps {pub reconcile: ReconcileDeps,/// Person-property seed admission and its live-priority margin.pub person_seed: PersonSeedDeps,+ /// Ceilings the partition workers group a channel batch's seeds into runs under.+ pub seed_budget: RunBudget,}impl MergeWorkerDeps {@@ -161,6 +164,7 @@ impl MergeWorkerDeps {register_transfer_enabled: false,reconcile: ReconcileDeps::default(),person_seed: PersonSeedDeps::default(),+ seed_budget: RunBudget::default(),})}}@@ -914,6 +918,7 @@ mod tests {register_transfer_enabled: false,reconcile: ReconcileDeps::default(),person_seed: PersonSeedDeps::default(),+ seed_budget: RunBudget::default(),}}diff --git a/rust/cohort-stream-processor/src/workers/mod.rs b/rust/cohort-stream-processor/src/workers/mod.rsindex 78c85bab08f8..f141d6d5168d 100644--- a/rust/cohort-stream-processor/src/workers/mod.rs+++ b/rust/cohort-stream-processor/src/workers/mod.rs@@ -6,7 +6,9 @@ pub mod merge_gc;pub mod merge_path;pub mod person_seed_path;pub mod reconcile;+pub mod seed_apply;pub mod seed_path;+pub mod seed_run;pub mod stage2_gc;pub mod stage2_path;pub mod sweep_callback;diff --git a/rust/cohort-stream-processor/src/workers/person_seed_path.rs b/rust/cohort-stream-processor/src/workers/person_seed_path.rsindex efd7732c8e35..a1da25c29878 100644--- a/rust/cohort-stream-processor/src/workers/person_seed_path.rs+++ b/rust/cohort-stream-processor/src/workers/person_seed_path.rs@@ -1,52 +1,43 @@//! Applies person-property seeds to `cf_person_records`, giving dormant persons leaf state that//! otherwise only arrives on a live event carrying `person_properties`.//!-//! [`Apply::run`] is the algorithm; the other [`Apply`] methods are its I/O steps and the free-//! functions below are pure. Every step that must not commit returns [`SeedHold`], so the-//! `Ok ⇒ mark, Err ⇒ hold` decision lives in [`handle_person_seed`] alone.+//! [`PersonHead`] is this path's half of a seed run: route, read, fold. The free functions below+//! are pure. [`seed_apply`](crate::workers::seed_apply) owns everything after the fold, so the+//! `Ok ⇒ mark, Err ⇒ hold` decision lives at one site for both seed kinds.//!//! Ordering against live traffic is [`person_seed_verdict`]'s job, not the apply fence's: a person//! seed carries no arrival bound over the event stream, so it admits fence-open. The partition-wide//! live-lag, disk, and channel-full holds still apply.-use std::sync::Arc;+use std::collections::{BTreeMap, BTreeSet};-use chrono::Utc;-use cohort_core::seed::PersonSeed;+use cohort_core::seed::{PersonSeed, RunId};use metrics::counter;use tracing::{debug, warn};use uuid::Uuid;-use crate::filters::manager::CatalogHandle;use crate::filters::reverse_index::TeamFilters;-use crate::merge::tombstone_redirect::{self, MAX_CROSS_PARTITION_REDIRECT_HOPS};+use crate::filters::TeamId;+use crate::merge::tombstone_redirect::MAX_CROSS_PARTITION_REDIRECT_HOPS;use crate::observability::metrics::{- PERSON_SEEDS_APPLIED_TOTAL, PERSON_SEEDS_DROPPED_TOTAL, PERSON_SEEDS_SKIPPED_TOTAL,- PERSON_SEEDS_UNCHANGED_TOTAL, PERSON_SEED_HASHES_DROPPED_TOTAL,- PERSON_SEED_PRIOR_CORRUPT_TOTAL, PERSON_SEED_REKEYED_TOTAL, PERSON_SEED_REKEY_HOP_CAPPED_TOTAL,- PERSON_SEED_REKEY_PRODUCE_FAILURE_TOTAL,+ PERSON_SEED_HASHES_DROPPED_TOTAL, PERSON_SEED_PRIOR_CORRUPT_TOTAL,+ PERSON_SEED_REKEY_HOP_CAPPED_TOTAL,};-use crate::producer::{CohortMembershipChange, MembershipSink};use crate::stage1::key::LeafStateKey;use crate::stage1::person_record::{apply_person_seed, person_seed_verdict, MatchedSet, PersonRecord, PersonSeedOutcome,PersonSeedVerdict, PriorRecord,};use crate::stage1::state::StateVariant;-use crate::stage1::transition::LeafTransition;-use crate::stage2::Stage2State;-use crate::store::{- PersonPrefix, PersonRecordKey, PersonRecords, ReadLane, Stage2Key, StagedBatch, StoreError,- StoreHandle,+use crate::stage1::transition::{LeafTransition, TransitionKind};+use crate::store::{PersonPrefix, PersonRecordKey, PersonRecords, ReadLane, StagedBatch};+use crate::workers::seed_apply::{+ record_stage1_transition, resolve_run_persons, ApplyDeps, ApplyStage, Decoded, Folded, Outcome,+ Overlay, ReKeys, RunStamp, SeedHead, SeedHold, StageClock, Tally, TouchedPersons,};-use crate::workers::merge_path::MergeWorkerDeps;-use crate::workers::seed_path::{- count_stage1_transitions, hold, mark_processed, route_seed, tag_seed, SeedRoute,-};-use crate::workers::stage2_path::{- commit_stage2_writes, diff_single_leaf_registers, recompute_stage2, FoldedLeaf, Stage2Recompute,-};-use crate::workers::worker::{first_cascades, produce_cascades, produce_membership};+use crate::workers::seed_path::{route_seed, SeedRoute};+use crate::workers::seed_run::{Admitted, OffsetSpan, SeedKind, SeedRun};+use crate::workers::stage2_path::FoldedLeaf;/// Person-property seed admission for the partition workers.#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -69,376 +60,356 @@ impl Default for PersonSeedDeps {}}-/// Handle one person seed on its owning partition worker; touches the seed tracker only.-///-/// `Ok` means every durable effect landed, or the seed was skipped on purpose, and the offset may-/// commit. [`SeedHold`] means Kafka must redeliver.-#[allow(clippy::too_many_arguments)]-pub(crate) async fn handle_person_seed(- partition_id: u16,- handle: &StoreHandle,- catalog: &CatalogHandle,- sink: &Arc<dyn MembershipSink>,- merge: &MergeWorkerDeps,- last_updated: &str,- seed: &PersonSeed,- offset: i64,-) {- let apply = Apply {- partition_id,- handle,- catalog,- sink,- merge,- last_updated,- seed,- offset,- };- match apply.run().await {- Ok(()) => mark_processed(&merge.seed_tracker, partition_id, offset),- Err(held) => {- warn!(- partition_id,- team_id = seed.team_id().0,- run_id = %seed.run_id().0,- error = %held,- "person seed apply failed; holding the seed offset for redelivery",+/// The person head: route each seed, read every record the run can touch in one batch, and fold+/// them into an overlay. Everything after this is [`seed_apply`](crate::workers::seed_apply)'s.+pub(crate) struct PersonHead;++impl SeedHead for PersonHead {+ type Seed = PersonSeed;+ const KIND: SeedKind = SeedKind::Person;++ async fn fold(+ deps: ApplyDeps<'_>,+ run: SeedRun<PersonSeed>,+ _stamp: &RunStamp,+ clock: &mut StageClock,+ ) -> Result<Folded, SeedHold> {+ let span = run.span();+ let mut tally = Tally::default();++ if !deps.merge.person_seed.enabled {+ // A gate-off run is one message per scanned person, so this stays off `warn!` and+ // leans on `cohort_person_seeds_skipped_total{reason="apply_disabled"}` for the signal.+ for _ in 0..run.len() {+ tally.add(Outcome::PersonSkipped("apply_disabled"));+ }+ debug!(+ partition_id = deps.partition_id,+ seeds = run.len(),+ "person seed run skipped while person apply is disabled; re-produce the run after enabling",);- hold(&merge.seed_tracker, partition_id, offset);+ clock.mark(ApplyStage::Fold);+ return Ok(Folded::nothing(span, ReKeys::Persons(Vec::new()), tally));}- }-}-/// A failure that must not commit. `stage` is what tells an operator which half of the apply broke.-#[derive(Debug, thiserror::Error)]-enum SeedHold {- #[error("{stage}: {source}")]- Store {- stage: &'static str,- source: StoreError,- },- #[error("{stage}: {errors} message(s) failed to produce")]- Produce { stage: &'static str, errors: usize },-}+ let Routed { local, re_keys } = route_person_seeds(deps, run, &mut tally).await?;+ clock.mark(ApplyStage::Resolve);-impl SeedHold {- /// `map_err` adapter that labels a store failure with the step that hit it.- fn store(stage: &'static str) -> impl FnOnce(StoreError) -> Self {- move |source| Self::Store { stage, source }+ let overlay = read_person_records(deps, &local).await?;+ clock.mark(ApplyStage::Read);++ let folded = fold_person_seeds(deps, span, local, re_keys, overlay, tally);+ clock.mark(ApplyStage::Fold);+ Ok(folded)}}-struct Apply<'a> {- partition_id: u16,- handle: &'a StoreHandle,- catalog: &'a CatalogHandle,- sink: &'a Arc<dyn MembershipSink>,- merge: &'a MergeWorkerDeps,- last_updated: &'a str,- seed: &'a PersonSeed,- offset: i64,+/// One person seed that applies on this partition, with everything its fold needs resolved.+struct LocalPersonSeed<'a> {+ seed: PersonSeed,+ person: Uuid,+ filters: &'a TeamFilters,+ effective: EffectiveHashes,+ record_key: PersonRecordKey,}-impl Apply<'_> {- /// Each `return Ok(())` is a terminal skip whose offset commits; each `?` holds it.- async fn run(&self) -> Result<(), SeedHold> {- if !self.merge.person_seed.enabled {- self.skip_gate_off();- return Ok(());- }+struct Routed<'a> {+ local: Vec<LocalPersonSeed<'a>>,+ re_keys: Vec<PersonSeed>,+}- let snapshot = self.catalog.load();- let Some(filters) = snapshot.team(self.seed.team_id()) else {- counter!(PERSON_SEEDS_DROPPED_TOTAL, "reason" => "team_absent").increment(1);- return Ok(());+/// Resolve every distinct person's tombstone chain in one batched read, then split the run into+/// what applies here and what hands off.+///+/// The catalog checks run first: the catalog is team-wide, so a seed nothing backs is dropped+/// identically on the survivor's partition, and resolving first would spend a store read and+/// possibly a cross-partition re-produce on a message already doomed.+///+/// A read failure is fail-stop: a seed applied to a merged-away person is durable state that+/// nothing downstream can retract, so a missing verdict holds the run rather than reading as+/// not-merged.+async fn route_person_seeds<'a>(+ deps: ApplyDeps<'a>,+ run: SeedRun<PersonSeed>,+ tally: &mut Tally,+) -> Result<Routed<'a>, SeedHold> {+ let mut placed: Vec<(PersonSeed, &TeamFilters, EffectiveHashes)> =+ Vec::with_capacity(run.len());+ for Admitted { work: seed, .. } in run.into_items() {+ let Some(filters) = deps.team(seed.team_id()) else {+ tally.add(Outcome::PersonDropped("team_absent"));+ continue;};-- // Ahead of the tombstone resolution: the catalog is team-wide, so a seed nothing backs is- // dropped identically on the survivor's partition, and resolving first would spend a store- // read and possibly a cross-partition re-produce on a message already doomed.- let Some(effective) = effective_hashes(filters, self.seed) else {- counter!(PERSON_SEEDS_DROPPED_TOTAL, "reason" => "no_effective_hashes").increment(1);- return Ok(());+ let Some(effective) = effective_hashes(filters, &seed) else {+ tally.add(Outcome::PersonDropped("no_effective_hashes"));+ continue;};+ placed.push((seed, filters, effective));+ }- let Target::Local(person) = self.resolve_target().await? else {- return Ok(());+ let persons: Vec<(TeamId, Uuid)> = placed+ .iter()+ .map(|(seed, _, _)| (seed.team_id(), seed.person_id()))+ .collect();+ let resolved = resolve_run_persons(deps, persons).await?;++ let mut local = Vec::with_capacity(placed.len());+ let mut re_keys = Vec::new();+ for (seed, filters, effective) in placed {+ let resolution = resolved[&(seed.team_id(), seed.person_id())];+ let person = match route_seed(&seed, resolution, MAX_CROSS_PARTITION_REDIRECT_HOPS) {+ SeedRoute::ApplyLocal { person } => person,+ SeedRoute::ReProduce { seed: rekeyed } => {+ tally.add(Outcome::ReKeyed(SeedKind::Person));+ re_keys.push(rekeyed);+ continue;+ }+ // Apply at the best-known target once the hop budget is spent, matching the tile and+ // event paths: an orphaned row beats a silent seed loss, and holding the run instead+ // would stall every later seed on the partition behind a tombstone cycle that will+ // never resolve. The row lands under this worker's partition prefix, which the+ // survivor's own worker never reads. No sweep owns it — only the `cf_person_records`+ // TTL reclaims it, and `apply_person_seed` floors `last_seen_ms` at the scan instant+ // so it does age out wherever `COHORT_PERSON_RECORD_TTL_DAYS` is set.+ SeedRoute::CapExhausted { person } => {+ // On the attempt, with the warning: a run that a later hold keeps from settling+ // must not hide the anomaly.+ counter!(PERSON_SEED_REKEY_HOP_CAPPED_TOTAL).increment(1);+ warn!(+ partition_id = deps.partition_id,+ team_id = seed.team_id().0,+ %person,+ hops = seed.redirect_hops(),+ "person seed redirect hop cap hit (corrupt tombstone cycle?); applying inline at the best-known target",+ );+ person+ }};-let record_key =- PersonPrefix::new(self.partition_id, self.seed.team_id().0 as u64, person).record_key();- let prior = self.read_record(&record_key).await?;+ PersonPrefix::new(deps.partition_id, seed.team_id().0 as u64, person).record_key();+ local.push(LocalPersonSeed {+ seed,+ person,+ filters,+ effective,+ record_key,+ });+ }+ Ok(Routed { local, re_keys })+}++/// One `multi_get` over every record the run can touch, on the maintenance lane so backfill never+/// contends with live event reads.+///+/// A row that exists but does not decode is counted here, at the read, the way the event path+/// counts it: the fold rebuilds from an absent baseline, so without the counter a real codec+/// failure is indistinguishable from a dormant person that never had a record — and a run that a+/// later hold keeps from settling must not hide it.+async fn read_person_records(+ deps: ApplyDeps<'_>,+ local: &[LocalPersonSeed<'_>],+) -> Result<Overlay<PersonRecordKey, PersonRecord>, SeedHold> {+ let mut keys: Vec<PersonRecordKey> = local.iter().map(|seed| seed.record_key).collect();+ keys.sort_unstable();+ keys.dedup();++ let values = deps+ .handle+ .multi_get_person_records(keys.clone(), ReadLane::Maintenance)+ .await+ .map_err(SeedHold::store(ApplyStage::Read))?;+ let overlay =+ Overlay::from_read(+ ApplyStage::Read,+ keys,+ values,+ |bytes| match PersonRecord::decode(bytes) {+ Ok(record) => Decoded::Value(record),+ Err(_) => Decoded::Corrupt,+ },+ )?;+ let corrupt = overlay.prior_corrupt_rows();+ if corrupt > 0 {+ counter!(PERSON_SEED_PRIOR_CORRUPT_TOTAL).increment(corrupt as u64);+ }+ Ok(overlay)+}++/// What the run left on one person, carried from the fold to the emit.+struct SeededPerson<'a> {+ team_id: TeamId,+ filters: &'a TeamFilters,+ person: Uuid,+ /// Every effective evaluated hash of every seed that touched this person, `SkipLiveFresh` ones+ /// included: a register left `true` by a produce that never acked is only found by diffing the+ /// hashes the record does not match. Each maps to the run of the last seed that evaluated *it*,+ /// which is the leaf-level provenance a [`FoldedLeaf`] carries — two seeds of different runs+ /// can evaluate different hashes of one person.+ hashes: BTreeMap<[u8; 16], RunId>,+ /// The run of the last seed that touched this person, which their recomposed changes carry.+ run_id: RunId,+ /// The leaves some seed asked to recompose. Registered after the fold, so they carry the+ /// person's final run rather than the run of whichever seed happened to ask.+ recompose: BTreeSet<LeafStateKey>,+}++/// Fold every local seed into the overlay in offset order, then read the run's durable intent off+/// the touched slots.+fn fold_person_seeds(+ deps: ApplyDeps<'_>,+ span: OffsetSpan,+ local: Vec<LocalPersonSeed<'_>>,+ re_keys: Vec<PersonSeed>,+ mut overlay: Overlay<PersonRecordKey, PersonRecord>,+ mut tally: Tally,+) -> Folded {+ let margin_ms = deps.merge.person_seed.live_margin_ms;+ let mut touches: BTreeMap<PersonRecordKey, SeededPerson<'_>> = BTreeMap::new();+ let mut recompose = TouchedPersons::default();++ for seeded in &local {+ let team_id = seeded.seed.team_id();+ let run_id = seeded.seed.run_id();+ let slot = overlay+ .slot_mut(&seeded.record_key)+ .expect("the read pass keyed a slot for every person this run can touch");+ // Read-your-writes covers the verdict, not just the record: a second seed for the same+ // person in a run sees the first seed's stamp and zeroed fingerprints and gets+ // `SkipLiveFresh`, exactly as it would in a later run.+ let prior = match slot.current() {+ Some(record) => PriorRecord::Present(record.clone()),+ None if slot.prior_corrupt() => PriorRecord::Corrupt,+ None => PriorRecord::Absent,+ };let verdict = person_seed_verdict(&prior,- self.seed.scanned_at_ms(),- self.merge.person_seed.live_margin_ms,- filters.catalog_fingerprint,+ seeded.seed.scanned_at_ms(),+ margin_ms,+ seeded.filters.catalog_fingerprint,);// A live-fresh skip is not merged at all: the stored state already subsumes the seed.let update = match verdict {PersonSeedVerdict::SkipLiveFresh => RecordUpdate::Unchanged,- _ => record_update(- &prior,- self.seed,- person,- &effective,- self.merge.person_seed.live_margin_ms,- ),+ _ => record_update(&prior, &seeded.seed, &seeded.effective, margin_ms),};-- let now_ms = Utc::now().timestamp_millis();- // Read the registers before the pre-writes land, so a row this apply is about to place- // cannot be mistaken for one an earlier apply already told downstream about.- let folded = folded_leaves(&effective, person, &update, &prior);- let diff = diff_single_leaf_registers(- self.partition_id,- self.handle,- filters,- &folded,- now_ms,- self.last_updated,- ReadLane::Maintenance,- )- .await- .map_err(SeedHold::store("register read"))?;-- self.commit_stage1(&record_key, &update, &diff.stage1_writes)- .await?;- count_stage1_transitions(filters, update.transitions());- // A lagging register is its own reason to emit: the redelivery of a failed produce merges- // to `Unchanged` and mints nothing, so `recomposes` alone would stay silent.- if recomposes(&update, verdict, &prior) || !diff.recompute.is_empty() {- self.emit(filters, &effective.leaves(person), diff.recompute, now_ms)- .await?;+ tally.add(update.outcome(verdict));+ let recomposes_this = recomposes(&update, verdict, &prior);+ match update {+ RecordUpdate::Changed(record) => slot.advance(record),+ RecordUpdate::Unchanged => {}}- // Counted last: an emit failure holds the offset, and the redelivery re-derives the verdict- // against the record this attempt already wrote, so counting any earlier counts one seed- // twice under two different arms.- update.record_metric(verdict);- Ok(())- }- /// A gate-off run is one message per scanned person, so this stays off `warn!` and leans on- /// `cohort_person_seeds_skipped_total{reason="apply_disabled"}` for the signal.- fn skip_gate_off(&self) {- counter!(PERSON_SEEDS_SKIPPED_TOTAL, "reason" => "apply_disabled").increment(1);- debug!(- partition_id = self.partition_id,- team_id = self.seed.team_id().0,- run_id = %self.seed.run_id().0,- "person seed skipped while person apply is disabled; re-produce the run after enabling",- );- }-- /// A read failure is fail-stop: a seed applied to a merged-away person is durable state that- /// nothing downstream can retract.- async fn resolve_target(&self) -> Result<Target, SeedHold> {- let resolution = tombstone_redirect::resolve_offloaded(- self.handle,- self.partition_id,- self.seed.team_id(),- self.seed.person_id(),- self.merge.partition_count,- ReadLane::Maintenance,- )- .await- .map_err(SeedHold::store("tombstone preflight"))?;-- match route_seed(self.seed, resolution, MAX_CROSS_PARTITION_REDIRECT_HOPS) {- SeedRoute::ApplyLocal { person } => Ok(Target::Local(person)),- SeedRoute::ReProduce { seed: rekeyed } => self.hand_off(rekeyed).await,- SeedRoute::CapExhausted { person } => Ok(self.degrade_to(person)),- }- }-- /// Re-produce onto the survivor's partition. This is the seed's only remaining copy, so the- /// caller may not commit until exactly one `Ok` acks; an empty ack vector is a failure, not a- /// vacuous success.- async fn hand_off(&self, rekeyed: PersonSeed) -> Result<Target, SeedHold> {- let acks = self- .merge- .seed_tile_sink- .produce_person(vec![rekeyed])- .await;- if !matches!(acks.as_slice(), [Ok(())]) {- counter!(PERSON_SEED_REKEY_PRODUCE_FAILURE_TOTAL).increment(1);- return Err(SeedHold::Produce {- stage: "re-key produce",- errors: 1,+ let touch = touches+ .entry(seeded.record_key)+ .or_insert_with(|| SeededPerson {+ team_id,+ filters: seeded.filters,+ person: seeded.person,+ hashes: BTreeMap::new(),+ run_id,+ recompose: BTreeSet::new(),});+ // Offset order, so last write wins on both: the person carries the last seed that touched+ // them, each hash the last seed that evaluated that hash.+ touch.run_id = run_id;+ for &hash in &seeded.effective.evaluated {+ touch.hashes.insert(hash, run_id);}- counter!(PERSON_SEED_REKEYED_TOTAL).increment(1);- Ok(Target::HandedOff)- }-- /// Apply at the best-known target once the hop budget is spent, matching the tile and event- /// paths: an orphaned row beats a silent seed loss, and holding the offset instead would stall- /// every later seed on the partition behind a tombstone cycle that will never resolve.- ///- /// The row lands under this worker's partition prefix, which the survivor's own worker never- /// reads. Unlike the tile path's orphan, no sweep owns it — only the `cf_person_records` TTL- /// reclaims it, and `apply_person_seed` floors `last_seen_ms` at the scan instant so it does age- /// out wherever `COHORT_PERSON_RECORD_TTL_DAYS` is set.- fn degrade_to(&self, person: Uuid) -> Target {- counter!(PERSON_SEED_REKEY_HOP_CAPPED_TOTAL).increment(1);- warn!(- partition_id = self.partition_id,- team_id = self.seed.team_id().0,- %person,- hops = self.seed.redirect_hops(),- "person seed redirect hop cap hit (corrupt tombstone cycle?); applying inline at the best-known target",- );- Target::Local(person)- }-- /// Maintenance lane: backfill must not contend with live event reads.- ///- /// A row that exists but does not decode is counted here, the way the event path counts it: the- /// apply rebuilds from an absent baseline, so without the counter a real codec failure is- /// indistinguishable from a dormant person that never had a record.- async fn read_record(&self, key: &PersonRecordKey) -> Result<PriorRecord, SeedHold> {- let stored = self- .handle- .get_person_record(key, ReadLane::Maintenance)- .await- .map_err(SeedHold::store("person record read"))?;- let prior = PriorRecord::decode(stored.as_deref());- if matches!(prior, PriorRecord::Corrupt) {- counter!(PERSON_SEED_PRIOR_CORRUPT_TOTAL).increment(1);+ if recomposes_this {+ touch.recompose.extend(seeded.effective.leaf_keys());}- Ok(prior)}- /// One batch, so a register the diff pre-writes is never stranded without the record that- /// justifies it. Those are the only registers written here: a real bit waits for its produce- /// to ack, while the pre-write records what downstream held before it and needs no ack.- async fn commit_stage1(- &self,- key: &PersonRecordKey,- update: &RecordUpdate,- stage1_writes: &[(Stage2Key, Stage2State)],- ) -> Result<(), SeedHold> {- let mut staged = StagedBatch::default();- if let RecordUpdate::Changed { record, .. } = update {- staged.put::<PersonRecords>(key, &record.encode());+ let mut records = StagedBatch::default();+ let mut leaves: BTreeMap<TeamId, Vec<FoldedLeaf>> = BTreeMap::new();+ for (key, touch) in &touches {+ let slot = overlay+ .slot(key)+ .expect("every touch came from a slot the read pass keyed");+ if let Some(record) = slot.advanced() {+ records.put::<PersonRecords>(key, &record.encode());}- for (key, state) in stage1_writes {- staged.put_stage2(key, &state.encode());+ // A person with no stored record and no write has no leaves: nothing was durably+ // evaluated, so there is no register to diff. That is the dominant scan shape, a+ // non-matching dormant person, which stays at one batched read slot and no write.+ let evaluated = slot.advanced().is_some() || slot.before().is_some();+ if !evaluated && !slot.prior_corrupt() {+ continue;}- if staged.is_empty() {- return Ok(());+ // Every recomposing seed's leaves under the person's final run, so the composed change+ // names the last seed that touched them. A person with leaves here always has state to+ // evaluate, so the guard above never drops one.+ for &leaf in &touch.recompose {+ recompose.touch(touch.team_id, touch.person, touch.run_id, leaf);+ }+ for (hash, &run_id) in &touch.hashes {+ // An unreadable row survives only under seeds that matched nothing, so the seeds are+ // the one readable evaluation and they say no matches, which is also how the+ // composition reads the row.+ let in_cohort = evaluated+ && slot+ .current()+ .is_some_and(|record| record.matched.contains(hash));+ let before = slot+ .before()+ .is_some_and(|record| record.matched.contains(hash));+ let minted_transition = before != in_cohort;+ leaves.entry(touch.team_id).or_default().push(FoldedLeaf {+ leaf_state_key: LeafStateKey::for_person_property(hash),+ person_id: touch.person,+ in_cohort,+ minted_transition,+ run_id,+ });+ if minted_transition {+ let kind = if in_cohort {+ TransitionKind::Entered+ } else {+ TransitionKind::Left+ };+ let transition = LeafTransition {+ team_id: touch.team_id,+ leaf_state_key: LeafStateKey::for_person_property(hash),+ person_id: touch.person,+ condition_hash: *hash,+ kind,+ };+ // Stage-1 flips, not emissions: the register diff owns what downstream is told.+ record_stage1_transition(&mut tally, touch.filters, &transition);+ }}- self.handle- .commit(staged)- .await- .map_err(SeedHold::store("person record commit"))}- /// Recomposes every evaluated leaf, not just the ones this seed flipped, so a crash between the- /// two commits heals on replay ([`recomposes`] is what admits the healing pass).- ///- /// `registers` carries the single-leaf half the caller already diffed. Both halves commit only- /// after the produces ack, so every emitted change stays re-derivable: a composed flip from the- /// stored bit it did not advance, a single-leaf one from the register it did not advance.- async fn emit(- &self,- filters: &TeamFilters,- leaves: &[(LeafStateKey, Uuid)],- registers: Stage2Recompute,- now_ms: i64,- ) -> Result<(), SeedHold> {- let mut recompute = registers;- recompute.extend(- recompute_stage2(- self.partition_id,- self.handle,- filters,- leaves,- now_ms,- self.last_updated,- ReadLane::Maintenance,- )- .await- .map_err(SeedHold::store("stage 2 recompute"))?,- );-- let mut changes = std::mem::take(&mut recompute.changes);- tag_seed(&mut changes, self.seed.run_id());- self.produce(changes).await?;-- commit_stage2_writes(self.handle, &recompute.writes)- .await- .map_err(SeedHold::store("stage 2 commit"))?;- recompute.record_metrics();+ Folded {+ span,+ records,+ leaves,+ recompose,// Nothing to schedule: person-property membership has no window, so the sweep never owns// these leaves.- Ok(())- }-- async fn produce(&self, changes: Vec<CohortMembershipChange>) -> Result<(), SeedHold> {- // Built first: the cascade payload embeds the change, and `produce_membership` consumes it.- let cascades = first_cascades(self.merge, &changes, self.offset);-- let errors = if changes.is_empty() {- 0- } else {- produce_membership(self.sink, changes).await- };- if errors > 0 {- return Err(SeedHold::Produce {- stage: "membership produce",- errors,- });- }-- let errors = produce_cascades(self.merge, cascades).await;- if errors > 0 {- return Err(SeedHold::Produce {- stage: "cascade produce",- errors,- });- }- Ok(())+ schedules: Vec::new(),+ re_keys: ReKeys::Persons(re_keys),+ tally,}}-/// Where a seed's work belongs once its tombstone chain is resolved.-enum Target {- Local(Uuid),- /// Re-produced to the survivor's partition; this worker is done with it.- HandedOff,-}-#[derive(Debug, PartialEq, Eq)]enum RecordUpdate {- Changed {- record: PersonRecord,- transitions: Vec<LeafTransition>,- },+ Changed(PersonRecord),/// Nothing to write, so an absent record with no matches is never created and store growth/// stays proportional to matchers.Unchanged,}impl RecordUpdate {- fn transitions(&self) -> &[LeafTransition] {- match self {- Self::Changed { transitions, .. } => transitions,- Self::Unchanged => &[],- }- }-/// `verdict` labels the writing arm only: an unchanged merge says nothing about which verdict- /// admitted it.- fn record_metric(&self, verdict: PersonSeedVerdict) {+ /// admitted it. Counted only once the run settles, so a hold cannot count one seed twice under+ /// two different arms.+ fn outcome(&self, verdict: PersonSeedVerdict) -> Outcome {match (self, verdict) {- (_, PersonSeedVerdict::SkipLiveFresh) => {- counter!(PERSON_SEEDS_SKIPPED_TOTAL, "reason" => "stale_vs_live").increment(1);- }- (Self::Changed { .. }, _) => {- counter!(PERSON_SEEDS_APPLIED_TOTAL, "verdict" => verdict.as_str()).increment(1);- }- (Self::Unchanged, _) => counter!(PERSON_SEEDS_UNCHANGED_TOTAL).increment(1),+ (_, PersonSeedVerdict::SkipLiveFresh) => Outcome::PersonSkipped("stale_vs_live"),+ (Self::Changed(_), _) => Outcome::PersonApplied(verdict.as_str()),+ (Self::Unchanged, _) => Outcome::PersonUnchanged,}}}@@ -462,7 +433,7 @@ impl RecordUpdate {/// is the reconcile snapshot's to repair. The single-leaf half of the same replay is safe either/// way, because a lagging register admits the emit on its own.fn recomposes(update: &RecordUpdate, verdict: PersonSeedVerdict, prior: &PriorRecord) -> bool {- matches!(update, RecordUpdate::Changed { .. })+ matches!(update, RecordUpdate::Changed(_))|| verdict == PersonSeedVerdict::SkipLiveFresh|| matches!(prior, PriorRecord::Corrupt)}@@ -473,7 +444,6 @@ fn recomposes(update: &RecordUpdate, verdict: PersonSeedVerdict, prior: &PriorRefn record_update(prior: &PriorRecord,seed: &PersonSeed,- person: Uuid,effective: &EffectiveHashes,live_margin_ms: i64,) -> RecordUpdate {@@ -490,62 +460,12 @@ fn record_update(live_margin_ms,) {PersonSeedOutcome::Unchanged => RecordUpdate::Unchanged,- PersonSeedOutcome::Changed {- record,- transitions,- } => RecordUpdate::Changed {- record,- transitions: transitions- .into_iter()- .map(|(condition_hash, kind)| LeafTransition {- team_id: seed.team_id(),- leaf_state_key: LeafStateKey::for_person_property(&condition_hash),- person_id: person,- condition_hash,- kind,- })- .collect(),- },+ // The per-seed transitions are dropped: a run counts the *net* flip per hash, which the+ // fold derives from the overlay once every seed has folded.+ PersonSeedOutcome::Changed { record, .. } => RecordUpdate::Changed(record),}}-/// The person leaves this apply leaves behind, with the membership the stored record implies.-///-/// A person with no stored record has none: nothing was durably evaluated, so there is no register-/// to diff. That is the dominant scan shape, a non-matching dormant person, which stays at one-/// point read and no write. A person with a record folds every evaluated hash, matched or not,-/// because a register left at `true` by a produce that never acked is only found by diffing the-/// hashes the record does not match.-fn folded_leaves(- effective: &EffectiveHashes,- person: Uuid,- update: &RecordUpdate,- prior: &PriorRecord,-) -> Vec<FoldedLeaf> {- let matched = match (update, prior) {- (RecordUpdate::Changed { record, .. }, _) => Some(&record.matched),- (RecordUpdate::Unchanged, PriorRecord::Present(record)) => Some(&record.matched),- // An unreadable row survives only under a seed that matched nothing, so the seed is the one- // readable evaluation and it says no matches, which is also how the composition reads the- // row.- (RecordUpdate::Unchanged, PriorRecord::Corrupt) => None,- (RecordUpdate::Unchanged, PriorRecord::Absent) => return Vec::new(),- };- let transitions = update.transitions();- effective- .evaluated- .iter()- .map(|hash| FoldedLeaf {- leaf_state_key: LeafStateKey::for_person_property(hash),- person_id: person,- in_cohort: matched.is_some_and(|matched| matched.contains(hash)),- minted_transition: transitions- .iter()- .any(|transition| transition.condition_hash == *hash),- })- .collect()-}-/// The seed's hashes projected onto the team's live person-property catalog.struct EffectiveHashes {/// Sorted and distinct, so [`effective_hashes`] can binary-search it.@@ -554,11 +474,8 @@ struct EffectiveHashes {}impl EffectiveHashes {- fn leaves(&self, person: Uuid) -> Vec<(LeafStateKey, Uuid)> {- self.evaluated- .iter()- .map(|hash| (LeafStateKey::for_person_property(hash), person))- .collect()+ fn leaf_keys(&self) -> impl Iterator<Item = LeafStateKey> + '_ {+ self.evaluated.iter().map(LeafStateKey::for_person_property)}}@@ -605,17 +522,21 @@ fn effective_hashes(filters: &TeamFilters, seed: &PersonSeed) -> Option<Effectiv// Tests seed and assert against `CohortStore` directly, the sanctioned direct-store surface.#[allow(clippy::disallowed_methods)]mod tests {+ use std::sync::Arc;+use chrono_tz::UTC;- use cohort_core::seed::{ClaimEpoch, ConditionHash, RunId, ScannedAtMs};+ use cohort_core::seed::{ClaimEpoch, ConditionHash, ScannedAtMs};use serde_json::{json, Value};use tempfile::TempDir;use crate::consumers::events::CohortStreamEvent;+ use crate::filters::manager::CatalogHandle;use crate::filters::{CohortId, FilterCatalog, TeamFiltersBuilder, TeamId};use crate::merge::transfer::Tombstone;use crate::partitions::offset_tracker::OffsetTracker;use crate::partitions::partitioner::{partition_of, COHORT_PARTITION_COUNT};use crate::partitions::watermarks::LiveWatermarks;+ use crate::producer::MembershipSink;use crate::producer::{CaptureCascadeSink, CaptureSeedTileSink, CaptureSink, CaptureStreamEventSink,CaptureTransferSink, ChangeOrigin, MembershipStatus,@@ -623,10 +544,15 @@ mod tests {use crate::stage1::person_record::{PropsFingerprint, Stamp};use crate::stage1::state::AppliedOffsets;use crate::stage2::state::Stage2State;+ use crate::store::{BehavioralKey, StoreHandle};use crate::store::{CohortStore, OffloadConfig, OffloadMode, Stage2Key, StoreConfig, TombstoneKey,};+ use crate::sweep::EvictionQueue;use crate::workers::event_path::{process_event_gated, EventNameGating};+ use crate::workers::merge_path::MergeWorkerDeps;+ use crate::workers::seed_apply::{apply, BatchMarks};+ use crate::workers::seed_run::{SeedOffset, SeedRun};use crate::workers::stage2_path::compose_stage2;use crate::workers::{CascadeConfig, ReconcileDeps, TransferRetryPolicy};@@ -634,6 +560,7 @@ mod tests {const TEAM: TeamId = TeamId(7);const PERSON_HASH: &str = "fedcba9876543210";+ const OTHER_HASH: &str = "abcdef0123456789";const UNKNOWN_HASH: &str = "0000000000000000";const LAST_UPDATED: &str = "2026-06-15 12:00:00.000000";const MARGIN_MS: i64 = 900_000;@@ -671,6 +598,14 @@ mod tests {]}+ /// One single-leaf cohort per hash, so each hash's own change carries its own provenance.+ fn one_cohort_per_hash() -> Vec<(i32, Value)> {+ vec![+ (1, wrap(vec![person_leaf(PERSON_HASH)])),+ (3, wrap(vec![person_leaf(OTHER_HASH)])),+ ]+ }+fn build_filters(cohorts: &[(i32, Value)]) -> TeamFilters {let mut builder = TeamFiltersBuilder::default();for (id, filters) in cohorts {@@ -688,6 +623,22 @@ mod tests {evaluated: &[&str],matched: &[&str],scanned_at_ms: i64,+ ) -> PersonSeed {+ seed_of_run(+ person,+ RunId(Uuid::from_u128(0xBF)),+ evaluated,+ matched,+ scanned_at_ms,+ )+ }++ fn seed_of_run(+ person: Uuid,+ run: RunId,+ evaluated: &[&str],+ matched: &[&str],+ scanned_at_ms: i64,) -> PersonSeed {PersonSeed::new(TEAM,@@ -695,7 +646,7 @@ mod tests {evaluated.iter().copied().map(hash).collect(),matched.iter().copied().map(hash).collect(),ScannedAtMs(scanned_at_ms),- RunId(Uuid::from_u128(0xBF)),+ run,ClaimEpoch(1),).unwrap()@@ -764,6 +715,7 @@ mod tests {enabled: true,live_margin_ms: MARGIN_MS,},+ seed_budget: crate::workers::seed_run::RunBudget::default(),};Self {_dir: dir,@@ -778,23 +730,41 @@ mod tests {}}+ /// Apply one seed as a run of one, which is what a batch of one seed becomes.async fn run(&mut self, partition_id: u16, seed: &PersonSeed, offset: i64) {+ self.run_batch(partition_id, vec![(seed.clone(), offset)])+ .await;+ }++ /// Apply several seeds as one run, the way a channel batch of them applies.+ async fn run_batch(&mut self, partition_id: u16, seeds: Vec<(PersonSeed, i64)>) {+ let max = seeds.iter().map(|(_, offset)| *offset).max().unwrap();self.deps.seed_tracker- .mark_dispatched(partition_id as i32, offset + 1);+ .mark_dispatched(partition_id as i32, max + 1);let sink: Arc<dyn MembershipSink> = Arc::new(self.sink.clone());- let last_updated = self.clock.next();- handle_person_seed(+ let snapshot = self.catalog.load();+ let deps = ApplyDeps {partition_id,- &self.handle,- &self.catalog,- &sink,- &self.deps,- &last_updated,- seed,- offset,+ handle: &self.handle,+ catalog: &snapshot,+ sink: &sink,+ merge: &self.deps,+ };+ let run = SeedRun::new(+ seeds+ .into_iter()+ .map(|(work, offset)| Admitted {+ work,+ offset: SeedOffset(offset),+ })+ .collect(),)- .await;+ .expect("a run of at least one seed");+ let mut queue = EvictionQueue::<BehavioralKey>::new();+ let mut marks = BatchMarks::default();+ apply::<PersonHead>(deps, &mut queue, &mut self.clock, &mut marks, run).await;+ marks.publish(&self.deps.seed_tracker, partition_id);}/// Without `person_properties`, this leaves behavioral state written and no person record.@@ -1248,6 +1218,312 @@ mod tests {assert_eq!(shell.committable(partition_id), Some(1));}+ // ---- runs of more than one seed ----++ /// Read-your-writes has to cover the verdict, not just the record: the second seed for one+ /// person must see the first seed's stamp and zeroed fingerprints and skip, exactly as it+ /// would in a later run. Folding it against the run-start bytes would let the older scan+ /// retract what the newer one matched.+ #[tokio::test]+ async fn a_second_seed_for_one_person_in_a_run_sees_the_first_seeds_write() {+ let (person, partition_id) = dormant_person();+ let mut shell = Shell::new(mixed_cohorts());+ let scanned_at = now_ms();++ shell+ .run_batch(+ partition_id,+ vec![+ (+ seed_for(person, &[PERSON_HASH], &[PERSON_HASH], scanned_at),+ 0,+ ),+ // A second scan of the same person, within the live margin of the first, so its+ // retraction must lose to the stamp the first seed installed.+ (seed_for(person, &[PERSON_HASH], &[], scanned_at), 1),+ ],+ )+ .await;++ let stored = shell+ .record(partition_id, person)+ .expect("the first seed created the record");+ assert!(+ stored.matched.contains(&hash(PERSON_HASH).as_bytes()),+ "the second seed was live-fresh against the first seed's stamp, so it changed nothing",+ );+ assert!(shell.stage2(partition_id, person, 1).unwrap().in_cohort);+ assert_eq!(shell.committable(partition_id), Some(2));+ }++ /// Splitting a person's leaves across two recompute calls would evaluate the composed cohort+ /// twice against the same uncommitted bit and emit its flip twice.+ #[tokio::test]+ async fn a_person_touched_by_two_seeds_in_a_run_recomposes_once() {+ let (person, partition_id) = dormant_person();+ let mut shell = Shell::new(mixed_cohorts());+ // The behavioral half of cohort 2, so the person composes in once the person half lands.+ shell.live_pageview(partition_id, person, None);+ let scanned_at = now_ms();++ shell+ .run_batch(+ partition_id,+ vec![+ (+ seed_for(person, &[PERSON_HASH], &[PERSON_HASH], scanned_at),+ 0,+ ),+ (+ seed_for(person, &[PERSON_HASH], &[PERSON_HASH], scanned_at),+ 1,+ ),+ ],+ )+ .await;++ let composed: Vec<_> = shell+ .sink+ .changes()+ .into_iter()+ .filter(|change| change.cohort_id == 2)+ .collect();+ assert_eq!(+ composed.len(),+ 1,+ "the composed cohort flipped once for the run, not once per seed",+ );+ assert_eq!(composed[0].status, MembershipStatus::Entered);+ }++ /// Provenance is per leaf, not per person: two backfill runs can seed one person on different+ /// hashes in one batch, and a change for a hash the later run never evaluated must not claim+ /// that run.+ #[tokio::test]+ async fn each_leafs_change_carries_the_run_that_last_evaluated_that_leaf() {+ let (person, partition_id) = dormant_person();+ let mut shell = Shell::new(one_cohort_per_hash());+ let first = RunId(Uuid::from_u128(0xA));+ let second = RunId(Uuid::from_u128(0xB));++ shell+ .run_batch(+ partition_id,+ vec![+ (+ seed_of_run(+ person,+ first,+ &[PERSON_HASH],+ &[PERSON_HASH],+ now_ms() - 2 * MARGIN_MS,+ ),+ 0,+ ),+ // A later scan of the same person on a different hash, past the first seed's+ // stamp floor so it applies rather than skipping live-fresh.+ (+ seed_of_run(person, second, &[OTHER_HASH], &[OTHER_HASH], now_ms()),+ 1,+ ),+ ],+ )+ .await;++ let runs: BTreeMap<u64, Option<RunId>> = shell+ .sink+ .changes()+ .into_iter()+ .map(|change| (change.cohort_id as u64, change.run_id))+ .collect();+ assert_eq!(+ runs,+ BTreeMap::from([(1, Some(first)), (3, Some(second))]),+ "each cohort names the run of the seed that evaluated its hash",+ );+ }++ /// A person's composed change carries the last seed that touched them, whether or not that+ /// seed was the one that asked for the recompose.+ #[tokio::test]+ async fn a_composed_change_carries_the_last_seed_that_touched_the_person() {+ let (person, partition_id) = dormant_person();+ let mut shell = Shell::new(mixed_cohorts());+ // The behavioral half of cohort 2, so the person composes in once the person half lands.+ shell.live_pageview(partition_id, person, None);+ let first = RunId(Uuid::from_u128(0xA));+ let second = RunId(Uuid::from_u128(0xB));++ shell+ .run_batch(+ partition_id,+ vec![+ (+ seed_of_run(+ person,+ first,+ &[PERSON_HASH],+ &[PERSON_HASH],+ now_ms() - 2 * MARGIN_MS,+ ),+ 0,+ ),+ // Asserts what the first seed already wrote, so it recomposes nothing itself.+ (+ seed_of_run(person, second, &[PERSON_HASH], &[PERSON_HASH], now_ms()),+ 1,+ ),+ ],+ )+ .await;++ let composed: Vec<_> = shell+ .sink+ .changes()+ .into_iter()+ .filter(|change| change.cohort_id == 2)+ .collect();+ assert_eq!(composed.len(), 1, "one composed flip for the run");+ assert_eq!(+ composed[0].run_id,+ Some(second),+ "the last seed to touch the person, not the one that asked to recompose",+ );+ }++ /// A run mixes local and redirected seeds, so a hand-off that fails must not strand the local+ /// registers. The membership leg already acked, and the cascade for that flip is consumed+ /// against the *stored* bit right after this run: an unwritten bit reads every referring+ /// cohort as unchanged until the next tenure replays the run.+ #[tokio::test]+ async fn a_failed_rekey_commits_the_local_registers_before_it_holds() {+ let (redirected, partition_id, survivor) = cross_partition_pair();+ let local = (100u128..)+ .map(Uuid::from_u128)+ .find(|person| {+ partition_of(TEAM, person, COHORT_PARTITION_COUNT) as u16 == partition_id+ })+ .expect("some uuid hashes onto the delivering partition");+ let mut shell = Shell::with_sinks(+ mixed_cohorts(),+ CaptureSink::new(),+ CaptureSeedTileSink::failing_always(),+ );+ write_tombstone(&shell.store, partition_id, redirected, survivor);+ let scanned_at = now_ms();++ shell+ .run_batch(+ partition_id,+ vec![+ (+ seed_for(local, &[PERSON_HASH], &[PERSON_HASH], scanned_at),+ 4,+ ),+ (+ seed_for(redirected, &[PERSON_HASH], &[PERSON_HASH], scanned_at),+ 5,+ ),+ ],+ )+ .await;++ assert_eq!(+ shell.sink.changes().len(),+ 1,+ "the local seed's membership acked",+ );+ assert!(+ shell+ .stage2(partition_id, local, 1)+ .expect("the register row exists")+ .in_cohort,+ "and the register says what downstream was told",+ );+ assert_eq!(+ shell.committable(partition_id),+ None,+ "the run still holds its first offset for the hand-off",+ );+ }++ /// A seed that asserts what the record already holds recomposes nothing on its own, so a+ /// register the last run failed to emit would strand the person outside every composed cohort.+ /// The lagging row has to be its own reason to recompose.+ #[tokio::test]+ async fn a_person_whose_only_signal_is_a_lagging_register_still_recomposes() {+ let (person, partition_id) = dormant_person();+ let mut shell = Shell::new(mixed_cohorts());+ // The behavioral half of cohort 2, so the person composes in once stage 2 runs.+ shell.live_pageview(partition_id, person, None);+ let live = PersonRecord {+ last_seen_ms: now_ms(),+ stamp: Stamp::new(now_ms() - 2 * MARGIN_MS, 0),+ props_fingerprint: PropsFingerprint::of(r#"{"email":"[email protected]"}"#),+ catalog_fingerprint: shell.filters.catalog_fingerprint,+ matched: MatchedSet::from_iter([hash(PERSON_HASH).as_bytes()]),+ applied_offsets: AppliedOffsets::default(),+ redirect_dedup: Default::default(),+ };+ shell.put_record(partition_id, person, &live);+ // What a run that acked nothing leaves behind: the single-leaf register says the person is+ // out while the record says they are in.+ shell.put_register(partition_id, person, 1, false);++ // Asserts exactly what the record already holds, so the merge is Unchanged and mints no+ // transition — nothing in the fold would admit a recompose.+ let seed = seed_for(person, &[PERSON_HASH], &[PERSON_HASH], now_ms());+ shell.run(partition_id, &seed, 0).await;++ assert_eq!(+ shell.record(partition_id, person).unwrap().matched,+ live.matched,+ "the seed changed nothing about the record",+ );+ let changes = shell.sink.changes();+ assert_eq!(+ changes+ .iter()+ .map(|change| change.cohort_id)+ .collect::<BTreeSet<_>>(),+ BTreeSet::from([1, 2]),+ "the lagging register admits both the repair and the composition behind it",+ );+ assert!(shell.stage2(partition_id, person, 1).unwrap().in_cohort);+ assert!(shell.stage2(partition_id, person, 2).unwrap().in_cohort);+ assert_eq!(shell.committable(partition_id), Some(1));+ }++ /// A gate-off run is dark: it marks every offset it carries and touches nothing. Marking only+ /// the last seed would be right; marking none would wedge the partition.+ #[tokio::test]+ async fn a_gate_off_run_marks_its_whole_span_without_touching_the_store() {+ let (person, partition_id) = dormant_person();+ let mut shell = Shell::new(mixed_cohorts());+ shell.deps.person_seed.enabled = false;+ let scanned_at = now_ms();++ shell+ .run_batch(+ partition_id,+ vec![+ (+ seed_for(person, &[PERSON_HASH], &[PERSON_HASH], scanned_at),+ 4,+ ),+ (+ seed_for(person, &[PERSON_HASH], &[PERSON_HASH], scanned_at),+ 5,+ ),+ ],+ )+ .await;++ assert!(shell.record(partition_id, person).is_none());+ assert!(shell.sink.changes().is_empty());+ assert_eq!(shell.committable(partition_id), Some(6));+ }+#[tokio::test]async fn person_apply_disabled_skips_and_commits_without_touching_the_store() {let (person, partition_id) = dormant_person();diff --git a/rust/cohort-stream-processor/src/workers/seed_apply.rs b/rust/cohort-stream-processor/src/workers/seed_apply.rsnew file mode 100644index 000000000000..9e6efeda775d--- /dev/null+++ b/rust/cohort-stream-processor/src/workers/seed_apply.rs@@ -0,0 +1,1365 @@+//! The apply pipeline a seed run runs through, shared by both seed kinds.+//!+//! Applying seeds one at a time costs one awaited produce per seed that flips anything, so a+//! worker spends its time waiting on Kafka instead of folding. A run amortizes that: one read+//! pass, one register diff, one stage-1 commit, one recompute, one joined produce round trip, one+//! stage-2 commit, one mark.+//!+//! Each stage is a struct whose one method consumes `self` and returns the next stage or+//! [`SeedHold`], so the compiler enforces the order: register diff → stage-1 commit → schedule →+//! recompute → produce → stage-2 commit → settle. Kind-specific work lives in the *head* — route,+//! read, fold — which produces a [`Folded`]; everything after that is shared. The heads are+//! [`seed_path`](super::seed_path) for tiles and [`person_seed_path`](super::person_seed_path) for+//! person seeds.+//!+//! Every produce acks before the state it reports commits, so a failed leg holds the run's *first*+//! offset with its durable effects either absent or idempotently re-appliable, and the redelivery+//! replays the whole run.++use std::collections::{BTreeMap, BTreeSet, HashMap};+use std::sync::Arc;+use std::time::Instant;++use cohort_core::seed::{PersonSeed, ReconcileTile, RunId, SeedTile};+use metrics::{counter, histogram};+use tracing::warn;+use uuid::Uuid;++use crate::filters::reverse_index::TeamFilters;+use crate::filters::{FilterCatalog, TeamId};+use crate::merge::tombstone_redirect::{self, Resolution};+use crate::observability::metrics::{+ COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH, OUTPUT_TRANSITIONS_UNMAPPED,+ PERSON_SEEDS_APPLIED_TOTAL, PERSON_SEEDS_DROPPED_TOTAL, PERSON_SEEDS_SKIPPED_TOTAL,+ PERSON_SEEDS_UNCHANGED_TOTAL, PERSON_SEED_REKEYED_TOTAL,+ PERSON_SEED_REKEY_PRODUCE_FAILURE_TOTAL, RECONCILE_JOBS_ENQUEUED_TOTAL,+ RECONCILE_JOBS_SUPERSEDED_TOTAL, SEED_APPLY_RUNS_HELD_TOTAL, SEED_APPLY_RUN_DURATION_SECONDS,+ SEED_APPLY_RUN_SIZE, SEED_HELD_OFFSET_GAUGE, SEED_REKEYED_TOTAL,+ SEED_REKEY_PRODUCE_FAILURE_TOTAL, SEED_TILES_APPLIED_TOTAL, SEED_TILES_DROPPED_TOTAL,+ SEED_TILES_SKIPPED_TOTAL, SEED_TILES_UNCHANGED_TOTAL, STAGE1_TRANSITIONS,+};+use crate::partitions::offset_tracker::MarkOutcome;+use crate::partitions::offset_tracker::OffsetTracker;+use crate::producer::{ChangeOrigin, CohortMembershipChange, LastUpdatedClock, MembershipSink};+use crate::stage1::key::LeafStateKey;+use crate::stage1::transition::LeafTransition;+use crate::store::{BehavioralKey, ReadLane, StagedBatch, StoreError, StoreHandle};+use crate::sweep::EvictionQueue;+use crate::workers::merge_path::MergeWorkerDeps;+use crate::workers::reconcile::{ReconcileQueue, SupersedeOutcome};+use crate::workers::seed_run::{Admitted, OffsetSpan, SeedGroup, SeedKind, SeedOffset, SeedRun};+use crate::workers::stage2_path::{+ commit_stage2_writes, diff_single_leaf_registers, recompute_stage2, FoldedLeaf, RegisterDiff,+ Stage2Recompute,+};+use crate::workers::worker::{+ first_cascades, produce_cascades, produce_membership, transition_metric_label,+};++/// The ordered steps every run takes. Doubles as the `stage` metric label, so the duration+/// histogram and the held counter can never name a step the pipeline does not have.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum ApplyStage {+ /// Tombstone resolution and cross-partition routing.+ Resolve,+ /// The batched state read that seeds the overlay.+ Read,+ /// The pure fold of every seed into the overlay. No I/O, so it never holds.+ Fold,+ RegisterDiff,+ Stage1Commit,+ Recompute,+ Produce,+ Stage2Commit,+}++impl ApplyStage {+ pub(crate) fn as_str(self) -> &'static str {+ match self {+ Self::Resolve => "resolve",+ Self::Read => "read",+ Self::Fold => "fold",+ Self::RegisterDiff => "register_diff",+ Self::Stage1Commit => "stage1_commit",+ Self::Recompute => "recompute",+ Self::Produce => "produce",+ Self::Stage2Commit => "stage2_commit",+ }+ }+}++impl std::fmt::Display for ApplyStage {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(self.as_str())+ }+}++/// Which output a run's produce failed on. All three legs are issued together, so the leg names+/// the topic for the operator where the stage alone could not.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum ProduceLeg {+ Membership,+ Cascade,+ /// The cross-partition hand-off back onto the seed topic.+ ReKey,+}++impl std::fmt::Display for ProduceLeg {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(match self {+ Self::Membership => "membership",+ Self::Cascade => "cascade",+ Self::ReKey => "re-key",+ })+ }+}++/// A failure that must not commit. Every step that can leave durable state half-written returns+/// this, so the `Ok ⇒ mark, Err ⇒ hold` decision lives at one site.+#[derive(Debug, thiserror::Error)]+pub(crate) enum SeedHold {+ #[error("{stage}: {source}")]+ Store {+ stage: ApplyStage,+ source: StoreError,+ },+ #[error("{leg} produce: {errors} message(s) failed")]+ Produce { leg: ProduceLeg, errors: usize },+ /// A batched read answered fewer slots than keys. Pairing a slot with the wrong key would fold+ /// one person's seed onto another's state, so the run holds instead.+ #[error("{stage}: batched read answered {answered} of {asked} keys")]+ ShortRead {+ stage: ApplyStage,+ asked: usize,+ answered: usize,+ },+}++impl SeedHold {+ /// `map_err` adapter that labels a store failure with the step that hit it.+ pub(crate) fn store(stage: ApplyStage) -> impl FnOnce(StoreError) -> Self {+ move |source| Self::Store { stage, source }+ }++ /// `Ok` when a batched read answered every key; the run's hold otherwise.+ pub(crate) fn check_read(stage: ApplyStage, asked: usize, answered: usize) -> Result<(), Self> {+ if asked == answered {+ return Ok(());+ }+ Err(Self::ShortRead {+ stage,+ asked,+ answered,+ })+ }++ pub(crate) fn stage(&self) -> ApplyStage {+ match self {+ Self::Store { stage, .. } | Self::ShortRead { stage, .. } => *stage,+ Self::Produce { .. } => ApplyStage::Produce,+ }+ }+}++/// What every stage borrows. `Copy`, so a stage can hand it on without ceremony. `catalog` is one+/// snapshot per channel batch, where the per-seed apply loaded its own per seed.+#[derive(Clone, Copy)]+pub(crate) struct ApplyDeps<'a> {+ pub partition_id: u16,+ pub handle: &'a StoreHandle,+ pub catalog: &'a FilterCatalog,+ pub sink: &'a Arc<dyn MembershipSink>,+ pub merge: &'a MergeWorkerDeps,+}++impl<'a> ApplyDeps<'a> {+ pub(crate) fn team(&self, team_id: TeamId) -> Option<&'a TeamFilters> {+ self.catalog.team(team_id).map(|filters| &**filters)+ }+}++pub(crate) async fn resolve_run_persons(+ deps: ApplyDeps<'_>,+ mut persons: Vec<(TeamId, Uuid)>,+) -> Result<HashMap<(TeamId, Uuid), Resolution>, SeedHold> {+ persons.sort_unstable();+ persons.dedup();+ let resolved = tombstone_redirect::resolve_batch_offloaded(+ deps.handle,+ deps.partition_id,+ &persons,+ deps.merge.partition_count,+ ReadLane::Maintenance,+ )+ .await+ .map_err(SeedHold::store(ApplyStage::Resolve))?;+ SeedHold::check_read(ApplyStage::Resolve, persons.len(), resolved.len())?;+ Ok(resolved)+}++pub(crate) fn record_stage1_transition(+ tally: &mut Tally,+ filters: &TeamFilters,+ transition: &LeafTransition,+) {+ if let Some(kind) = transition_metric_label(filters, transition) {+ tally.add(Outcome::Stage1Transition(kind));+ }+ if filters+ .by_lsk_to_single_leaf_cohorts+ .get(&transition.leaf_state_key)+ .is_none_or(Vec::is_empty)+ && !filters+ .by_lsk_to_composable_cohorts+ .contains_key(&transition.leaf_state_key)+ {+ tally.add(Outcome::UnmappedTransition);+ }+}++pub(crate) fn admit_reconcile(+ partition_id: u16,+ merge: &MergeWorkerDeps,+ queue: &mut ReconcileQueue,+ marks: &mut BatchMarks,+ tile: &ReconcileTile,+ offset: SeedOffset,+) {+ if !merge.reconcile.enabled {+ counter!(SEED_TILES_SKIPPED_TOTAL, "reason" => "reconcile_disabled").increment(1);+ warn!(+ partition_id,+ team_id = tile.team_id().0,+ cohort_id = tile.cohort_id().0,+ run_id = %tile.run_id().0,+ "reconcile seed skipped while reconcile is disabled; re-dispatch after enabling",+ );+ marks.mark(offset);+ return;+ }++ let kind = tile.scope().kind();+ let deferred = match queue.supersede_if_newer(tile.team_id(), tile.cohort_id(), kind, offset.0)+ {+ SupersedeOutcome::NoQueuedJob => merge.seed_tracker.defer(partition_id as i32, offset.0),+ SupersedeOutcome::Replaced(superseded) => {+ let (replacement, outcome) = merge+ .seed_tracker+ .replace_deferred(superseded, offset.0)+ .expect("a queued reconcile must retain its deferred offset in the current tenure");+ if let MarkOutcome::CappedAheadOfDispatch = outcome {+ counter!(COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH).increment(1);+ warn!(+ partition_id,+ "superseded reconcile completion exceeded the seed dispatch ceiling",+ );+ }+ counter!(RECONCILE_JOBS_SUPERSEDED_TOTAL, "kind" => kind.as_str()).increment(1);+ replacement+ }+ SupersedeOutcome::RetainedNewerOrEqual => {+ counter!(SEED_TILES_SKIPPED_TOTAL, "reason" => "reconcile_stale_replay").increment(1);+ tracing::debug!(+ partition_id,+ team_id = tile.team_id().0,+ cohort_id = tile.cohort_id().0,+ run_id = %tile.run_id().0,+ offset = offset.0,+ "replayed reconcile seed retained the newer or equal queued job",+ );+ marks.mark(offset);+ return;+ }+ };++ queue.enqueue(tile.clone(), deferred);+ counter!(RECONCILE_JOBS_ENQUEUED_TOTAL, "kind" => kind.as_str()).increment(1);+}++pub(crate) fn tag_seed(changes: &mut [CohortMembershipChange], run_id: RunId) {+ for change in changes {+ change.origin = Some(ChangeOrigin::Seed);+ change.run_id = Some(run_id);+ }+}++/// Advance the seed tracker past `offset`. A mark beyond the dispatch ceiling is capped and counted.+pub(crate) fn mark_processed(tracker: &OffsetTracker, partition_id: u16, offset: SeedOffset) {+ if let MarkOutcome::CappedAheadOfDispatch =+ tracker.mark_processed(partition_id as i32, offset.0 + 1)+ {+ counter!(COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH).increment(1);+ warn!(+ partition_id,+ next_offset = offset.0 + 1,+ "seed offset mark exceeded the dispatch ceiling and was capped (F1 invariant violation)",+ );+ }+}++/// Pin the seed commit floor at the failed offset so Kafka redelivers it; emit+/// [`SEED_HELD_OFFSET_GAUGE`] so the stall is visible.+pub(crate) fn hold(tracker: &OffsetTracker, partition_id: u16, offset: SeedOffset) {+ let floor = tracker.hold(partition_id as i32, offset.0);+ let partition: Arc<str> = Arc::from(partition_id.to_string());+ metrics::gauge!(SEED_HELD_OFFSET_GAUGE, "partition" => partition).set(floor as f64);+}++/// The one clock reading and the one output version a whole run shares.+///+/// `now_ms` is taken once, after every member was fenced individually at admission, so the newest+/// seed applies up to one run duration after its fence check — which only widens its eviction+/// window. Each `(cohort, person)` appears at most once in a run's output, so one `last_updated`+/// needs no intra-run ordering and the next run's stamp is strictly newer.+pub(crate) struct RunStamp {+ pub now_ms: i64,+ pub last_updated: String,+}++// ---- The overlay: read-your-writes within a run ----++/// One key's state through a run: what the read pass saw, and what the fold made of it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct Slot<V> {+ /// What the read pass saw — the run-start truth the net-transition rule diffs against.+ before: Option<V>,+ /// The fold's fixed point, once some seed changed the bytes.+ advanced: Option<V>,+ /// The row existed but did not decode. The tile fold refuses such a slot; the person fold+ /// rebuilds from the absent baseline, as its per-seed apply does.+ prior_corrupt: bool,+}++impl<V> Slot<V> {+ /// What the next seed folds against: the run's own writes first, then the read pass.+ pub(crate) fn current(&self) -> Option<&V> {+ self.advanced.as_ref().or(self.before.as_ref())+ }++ pub(crate) fn before(&self) -> Option<&V> {+ self.before.as_ref()+ }++ pub(crate) fn advanced(&self) -> Option<&V> {+ self.advanced.as_ref()+ }++ pub(crate) fn prior_corrupt(&self) -> bool {+ self.prior_corrupt+ }++ /// Record a fold that changed the bytes.+ pub(crate) fn advance(&mut self, value: V) {+ self.advanced = Some(value);+ }+}++/// One stored row of a batched read, decoded. Absence is not a variant: the read reports it, and+/// no keyspace here stores a value that means "absent".+pub(crate) enum Decoded<V> {+ Value(V),+ /// The row exists but does not decode. Counted once per row, not once per seed that touches it.+ Corrupt,+}++/// Read-your-writes within a run (RocksDB's `WriteBatchWithIndex` idea, in memory): a later seed+/// for the same key folds onto the earlier seed's result, not onto the bytes the read pass saw.+#[derive(Debug, Default)]+pub(crate) struct Overlay<K: Ord, V> {+ slots: BTreeMap<K, Slot<V>>,+}++impl<K: Ord + Copy, V> Overlay<K, V> {+ /// Pair each key with its answer. A short answer is a hold, never a silent absent: pairing a+ /// slot with the wrong key would fold one person's seed onto another's state.+ pub(crate) fn from_read(+ stage: ApplyStage,+ keys: Vec<K>,+ values: Vec<Option<Vec<u8>>>,+ decode: impl Fn(&[u8]) -> Decoded<V>,+ ) -> Result<Self, SeedHold> {+ SeedHold::check_read(stage, keys.len(), values.len())?;+ let mut slots = BTreeMap::new();+ for (key, bytes) in keys.into_iter().zip(values) {+ let (before, prior_corrupt) = match bytes.as_deref().map(&decode) {+ None => (None, false),+ Some(Decoded::Value(value)) => (Some(value), false),+ Some(Decoded::Corrupt) => (None, true),+ };+ slots.insert(+ key,+ Slot {+ before,+ advanced: None,+ prior_corrupt,+ },+ );+ }+ Ok(Self { slots })+ }++ pub(crate) fn slot(&self, key: &K) -> Option<&Slot<V>> {+ self.slots.get(key)+ }++ pub(crate) fn slot_mut(&mut self, key: &K) -> Option<&mut Slot<V>> {+ self.slots.get_mut(key)+ }++ /// Rows that exist but did not decode, for the head to count once per row at the read.+ pub(crate) fn prior_corrupt_rows(&self) -> usize {+ self.slots+ .values()+ .filter(|slot| slot.prior_corrupt)+ .count()+ }+}++// ---- What a head hands the shared pipeline ----++/// A run's cross-partition hand-offs. One kind per run, because a run is one kind.+#[derive(Debug)]+pub(crate) enum ReKeys {+ Tiles(Vec<SeedTile>),+ Persons(Vec<PersonSeed>),+}++impl ReKeys {+ fn is_empty(&self) -> bool {+ match self {+ Self::Tiles(tiles) => tiles.is_empty(),+ Self::Persons(seeds) => seeds.is_empty(),+ }+ }+}++/// The persons a run touched: which leaves each needs recomposed, and the run of the last seed+/// that touched them in offset order, which is the provenance their recomposed changes carry.+///+/// Keeping a person whole matters: splitting their leaves across two recompute calls would+/// evaluate the same cohort twice against the same uncommitted bit and emit the flip twice.+#[derive(Debug, Default)]+pub(crate) struct TouchedPersons {+ per_person: BTreeMap<(TeamId, Uuid), PersonTouch>,+}++#[derive(Debug)]+struct PersonTouch {+ run: RunId,+ leaves: BTreeSet<LeafStateKey>,+}++impl TouchedPersons {+ fn entry(&mut self, team_id: TeamId, person: Uuid, run: RunId) -> &mut PersonTouch {+ self.per_person+ .entry((team_id, person))+ .or_insert_with(|| PersonTouch {+ run,+ leaves: BTreeSet::new(),+ })+ }++ pub(crate) fn touch(&mut self, team_id: TeamId, person: Uuid, run: RunId, leaf: LeafStateKey) {+ let touch = self.entry(team_id, person, run);+ // Last call wins, and the heads call in offset order: the person stays in one recompose+ // group under the run of the last seed that touched them.+ touch.run = run;+ touch.leaves.insert(leaf);+ }++ /// Admit a leaf the register diff found lagging. The person's provenance stays with the fold's+ /// last seed; the leaf's run counts only for a person the fold never admitted.+ pub(crate) fn touch_lagging(+ &mut self,+ team_id: TeamId,+ person: Uuid,+ run: RunId,+ leaf: LeafStateKey,+ ) {+ self.entry(team_id, person, run).leaves.insert(leaf);+ }++ fn is_empty(&self) -> bool {+ self.per_person.is_empty()+ }++ /// One recompute call per `(team, run)`: the team owns the catalog that composes the leaves,+ /// the run owns their provenance tag.+ fn groups(self) -> BTreeMap<(TeamId, RunId), Vec<(LeafStateKey, Uuid)>> {+ let mut groups: BTreeMap<(TeamId, RunId), Vec<(LeafStateKey, Uuid)>> = BTreeMap::new();+ for ((team_id, person), touch) in self.per_person {+ let group = groups.entry((team_id, touch.run)).or_default();+ group.extend(touch.leaves.into_iter().map(|leaf| (leaf, person)));+ }+ groups+ }+}++// ---- Deferred outcome counters ----++/// One thing a run did, held as data until the boundary that makes it exactly-once. Exhaustive, so+/// a new outcome cannot be counted mid-flight by accident.+///+/// Only work the run did is deferred. What a run *found* stays attempt-based, because a run that a+/// later hold keeps from settling must not hide it: corrupt rows, hop-capped redirects, dropped+/// hashes, produce failures, held runs, and `OUTPUT_MEMBERSHIP_CHANGES_EMITTED`, which fires inside+/// `produce_membership` before the stage-2 commit.+///+/// The payloads are the metric labels rather than the domain enums, because that is what a counter+/// takes and it keeps this key orderable without an `Ord` on types that have no order.+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+pub(crate) enum Outcome {+ /// `variant` label.+ TileApplied(&'static str),+ /// `variant` label.+ TileUnchanged(&'static str),+ /// `reason` label.+ TileDropped(&'static str),+ /// `verdict` label.+ PersonApplied(&'static str),+ PersonUnchanged,+ /// `reason` label.+ PersonSkipped(&'static str),+ /// `reason` label.+ PersonDropped(&'static str),+ /// `kind` label, as [`crate::workers::worker::transition_metric_label`] names it.+ Stage1Transition(&'static str),+ UnmappedTransition,+ ReKeyed(SeedKind),+}++impl Outcome {+ /// Whether the stage-1 commit is this outcome's exactly-once boundary.+ ///+ /// These three say the run *advanced* durable state. Once that commit lands, a replay folds+ /// the same seeds to `Unchanged` over their own rows and mints nothing, so deferring them any+ /// further loses a held run's work for good. Every other outcome is re-derived identically by+ /// a replay — a drop drops again, an idempotent merge is unchanged again — so counting it+ /// before the run settles would count it once per attempt.+ fn durable_at_stage1(self) -> bool {+ matches!(+ self,+ Self::TileApplied(_)+ | Self::PersonApplied(_)+ | Self::Stage1Transition(_)+ | Self::UnmappedTransition+ )+ }+}++/// A run's non-failure counts, each held until the boundary that makes it exactly-once: the+/// stage-1 commit for work that moved durable state, the settled run for everything else.+#[derive(Debug, Default)]+pub(crate) struct Tally {+ durable: BTreeMap<Outcome, u64>,+ settled: BTreeMap<Outcome, u64>,+}++impl Tally {+ pub(crate) fn add(&mut self, outcome: Outcome) {+ let half = if outcome.durable_at_stage1() {+ &mut self.durable+ } else {+ &mut self.settled+ };+ *half.entry(outcome).or_default() += 1;+ }++ /// Publish the half the stage-1 commit just made durable. Call only once that commit returned+ /// `Ok`, so a hold before it re-mints these on replay instead of double-counting them.+ fn record_durable(&mut self) {+ record_outcomes(std::mem::take(&mut self.durable));+ }++ fn record(self) {+ debug_assert!(+ self.durable.is_empty(),+ "the stage-1 commit publishes the durable half",+ );+ record_outcomes(self.settled);+ }+}++fn record_outcomes(outcomes: BTreeMap<Outcome, u64>) {+ for (outcome, count) in outcomes {+ match outcome {+ Outcome::TileApplied(variant) => {+ counter!(SEED_TILES_APPLIED_TOTAL, "variant" => variant).increment(count);+ }+ Outcome::TileUnchanged(variant) => {+ counter!(SEED_TILES_UNCHANGED_TOTAL, "variant" => variant).increment(count);+ }+ Outcome::TileDropped(reason) => {+ counter!(SEED_TILES_DROPPED_TOTAL, "reason" => reason).increment(count);+ }+ Outcome::PersonApplied(verdict) => {+ counter!(PERSON_SEEDS_APPLIED_TOTAL, "verdict" => verdict).increment(count);+ }+ Outcome::PersonUnchanged => {+ counter!(PERSON_SEEDS_UNCHANGED_TOTAL).increment(count);+ }+ Outcome::PersonSkipped(reason) => {+ counter!(PERSON_SEEDS_SKIPPED_TOTAL, "reason" => reason).increment(count);+ }+ Outcome::PersonDropped(reason) => {+ counter!(PERSON_SEEDS_DROPPED_TOTAL, "reason" => reason).increment(count);+ }+ Outcome::Stage1Transition(kind) => {+ counter!(STAGE1_TRANSITIONS, "kind" => kind).increment(count);+ }+ Outcome::UnmappedTransition => {+ counter!(OUTPUT_TRANSITIONS_UNMAPPED, "reason" => "no_emitting_cohort")+ .increment(count);+ }+ Outcome::ReKeyed(SeedKind::Tile) => {+ counter!(SEED_REKEYED_TOTAL).increment(count);+ }+ Outcome::ReKeyed(SeedKind::Person) => {+ counter!(PERSON_SEED_REKEYED_TOTAL).increment(count);+ }+ }+ }+}++/// Splits one run's wall clock into per-stage samples: each [`mark`](Self::mark) records the time+/// since the previous one. A held run records no sample for the step that failed, so the histogram+/// stays a picture of completed work; [`SEED_APPLY_RUNS_HELD_TOTAL`] carries the failures.+pub(crate) struct StageClock {+ kind: SeedKind,+ last: Instant,+}++impl StageClock {+ fn start(kind: SeedKind, size: usize) -> Self {+ histogram!(SEED_APPLY_RUN_SIZE, "kind" => kind.as_str()).record(size as f64);+ Self {+ kind,+ last: Instant::now(),+ }+ }++ pub(crate) fn mark(&mut self, stage: ApplyStage) {+ let now = Instant::now();+ histogram!(+ SEED_APPLY_RUN_DURATION_SECONDS,+ "kind" => self.kind.as_str(),+ "stage" => stage.as_str(),+ )+ .record(now.duration_since(self.last).as_secs_f64());+ self.last = now;+ }+}++/// One collection's marks, published only once every group in it has run.+///+/// Groups do not partition the collection's offsets: one open run per kind means a tile run and a+/// person run interleave, so a tile run's `span.last` can sit above a person seed the pipeline has+/// not reached yet. The seed consumer commits from its own task off the shared tracker, so marking+/// mid-collection could commit past that person seed and lose it on the next tenure. Holds stay+/// immediate: a hold only ever lowers the floor, so publishing one early is always safe.+#[derive(Default)]+pub(crate) struct BatchMarks(Option<SeedOffset>);++impl BatchMarks {+ pub(crate) fn mark(&mut self, offset: SeedOffset) {+ self.0 = Some(self.0.map_or(offset, |seen| seen.max(offset)));+ }++ pub(crate) fn publish(self, tracker: &OffsetTracker, partition_id: u16) {+ if let Some(offset) = self.0 {+ mark_processed(tracker, partition_id, offset);+ }+ }+}++// ---- The pipeline ----++/// The head's output: the run's whole durable intent, nothing written yet.+#[must_use]+pub(crate) struct Folded {+ pub span: OffsetSpan,+ /// Stage-1 rows (`cf_behavioral` or `cf_person_records`), final state per key.+ pub records: StagedBatch,+ /// One entry per distinct `(team, leaf, person)` the run touched, with the run-final truth and+ /// the net transition. Grouped by team because the register diff is per catalog.+ pub leaves: BTreeMap<TeamId, Vec<FoldedLeaf>>,+ /// Persons whose composable cohorts must recompose, with the run that last touched them.+ pub recompose: TouchedPersons,+ /// Final eviction deadline per touched behavioral key. Empty for person seeds.+ pub schedules: Vec<(BehavioralKey, i64)>,+ pub re_keys: ReKeys,+ pub tally: Tally,+}++impl Folded {+ /// A run with no durable intent: the gate-off person run, which marks its span and does+ /// nothing else. Every later stage is a no-op on it.+ pub(crate) fn nothing(span: OffsetSpan, re_keys: ReKeys, tally: Tally) -> Self {+ Self {+ span,+ records: StagedBatch::default(),+ leaves: BTreeMap::new(),+ recompose: TouchedPersons::default(),+ schedules: Vec::new(),+ re_keys,+ tally,+ }+ }++ /// One [`diff_single_leaf_registers`] per team. Every person the diff emits a change or a write+ /// for joins `recompose`: a lagging register is its own reason to recompose, and nothing the+ /// fold saw would admit it — the redelivery of a failed produce mints no transition.+ async fn diff_registers(+ mut self,+ deps: ApplyDeps<'_>,+ stamp: &RunStamp,+ ) -> Result<Diffed, SeedHold> {+ let mut diff = RegisterDiff::default();+ for (&team_id, leaves) in &self.leaves {+ // Only teams the same snapshot already resolved reach here, so the miss arm is dead; it+ // degrades to skipping one team's diff rather than killing the partition worker.+ let Some(filters) = deps.team(team_id) else {+ continue;+ };+ let team_diff = diff_single_leaf_registers(+ deps.partition_id,+ deps.handle,+ filters,+ leaves,+ stamp.now_ms,+ &stamp.last_updated,+ ReadLane::Maintenance,+ )+ .await+ .map_err(SeedHold::store(ApplyStage::RegisterDiff))?;++ let lagging: BTreeSet<Uuid> = team_diff+ .recompute+ .writes+ .iter()+ .chain(team_diff.stage1_writes.iter())+ .map(|(key, _)| key.person_id)+ .collect();+ for leaf in leaves {+ if lagging.contains(&leaf.person_id) {+ self.recompose.touch_lagging(+ team_id,+ leaf.person_id,+ leaf.run_id,+ leaf.leaf_state_key,+ );+ }+ }+ diff.extend(team_diff);+ }++ // One batch, so a register the diff pre-writes is never stranded without the stage-1 row+ // that justifies it.+ let mut records = self.records;+ for (key, state) in &diff.stage1_writes {+ records.put_stage2(key, &state.encode());+ }+ Ok(Diffed {+ span: self.span,+ records,+ recompute: diff.recompute,+ recompose: self.recompose,+ schedules: self.schedules,+ re_keys: self.re_keys,+ tally: self.tally,+ })+ }+}++#[must_use]+struct Diffed {+ span: OffsetSpan,+ records: StagedBatch,+ recompute: Stage2Recompute,+ recompose: TouchedPersons,+ schedules: Vec<(BehavioralKey, i64)>,+ re_keys: ReKeys,+ tally: Tally,+}++impl Diffed {+ async fn commit_stage1(self, deps: ApplyDeps<'_>) -> Result<Committed, SeedHold> {+ if !self.records.is_empty() {+ deps.handle+ .commit(self.records)+ .await+ .map_err(SeedHold::store(ApplyStage::Stage1Commit))?;+ }+ let mut tally = self.tally;+ // The run's advances are durable here, and a replay would fold them to `Unchanged` over+ // their own rows and mint nothing, so a later hold would drop these counts for good.+ tally.record_durable();+ Ok(Committed {+ span: self.span,+ recompute: self.recompute,+ recompose: self.recompose,+ schedules: self.schedules,+ re_keys: self.re_keys,+ tally,+ })+ }+}++#[must_use]+struct Committed {+ span: OffsetSpan,+ recompute: Stage2Recompute,+ recompose: TouchedPersons,+ schedules: Vec<(BehavioralKey, i64)>,+ re_keys: ReKeys,+ tally: Tally,+}++impl Committed {+ /// Infallible, and taken here rather than after the produce: the rows are already durable, so+ /// their deadlines are owed whatever follows. A deadline lost to a later hold is re-derived+ /// from `cf_behavioral` by `rebuild_eviction_queue` at the next tenure start.+ fn schedule(self, queue: &mut EvictionQueue<BehavioralKey>) -> Scheduled {+ for (key, deadline) in self.schedules {+ queue.schedule(key, deadline);+ }+ Scheduled {+ span: self.span,+ recompute: self.recompute,+ recompose: self.recompose,+ re_keys: self.re_keys,+ tally: self.tally,+ }+ }+}++#[must_use]+struct Scheduled {+ span: OffsetSpan,+ recompute: Stage2Recompute,+ recompose: TouchedPersons,+ re_keys: ReKeys,+ tally: Tally,+}++impl Scheduled {+ /// One recompute per `(team, run)`, folded into the register diff's half so one produce and+ /// one commit cover both.+ async fn recompute(+ mut self,+ deps: ApplyDeps<'_>,+ stamp: &RunStamp,+ ) -> Result<Recomputed, SeedHold> {+ if !self.recompose.is_empty() {+ for ((team_id, run), leaves) in self.recompose.groups() {+ let Some(filters) = deps.team(team_id) else {+ continue;+ };+ let mut composed = recompute_stage2(+ deps.partition_id,+ deps.handle,+ filters,+ &leaves,+ stamp.now_ms,+ &stamp.last_updated,+ ReadLane::Maintenance,+ )+ .await+ .map_err(SeedHold::store(ApplyStage::Recompute))?;+ // The register diff stamps its own changes from the leaf, so only the composed+ // half still needs the run tag.+ tag_seed(&mut composed.changes, run);+ self.recompute.extend(composed);+ }+ }+ let changes = std::mem::take(&mut self.recompute.changes);+ Ok(Recomputed {+ span: self.span,+ changes,+ stage2: self.recompute,+ re_keys: self.re_keys,+ tally: self.tally,+ })+ }+}++#[must_use]+struct Recomputed {+ span: OffsetSpan,+ /// Taken out of `stage2` so the produce moves them instead of cloning.+ changes: Vec<CohortMembershipChange>,+ stage2: Stage2Recompute,+ re_keys: ReKeys,+ tally: Tally,+}++impl Recomputed {+ /// One round trip for all three legs.+ ///+ /// After stage 1 committed, every membership change is re-derivable — single-leaf ones from the+ /// register the run has not advanced, composed ones from the stage-2 bits it has not written —+ /// so a failed leg holds the run and the replay re-emits the whole output. Duplicates are safe+ /// on every leg: membership is LWW downstream, a duplicate cascade re-evaluates a referrer from+ /// the store, and a duplicate re-keyed seed re-applies idempotently on its target.+ ///+ /// The two output legs decide the run here. The hand-off leg does not: it is carried past the+ /// stage-2 commit, because a run mixes local and redirected seeds and a hand-off that failed+ /// says nothing about what downstream was told.+ async fn produce(self, deps: ApplyDeps<'_>) -> Result<Produced, SeedHold> {+ let Self {+ span,+ changes,+ stage2,+ re_keys,+ tally,+ } = self;+ // Built from a borrow before `changes` moves: the cascade payload embeds the change.+ let cascades = first_cascades(deps.merge, &changes, span.last.0);+ let (membership, cascade, re_key) = tokio::join!(+ produce_membership_if_any(deps.sink, changes),+ produce_cascades(deps.merge, cascades),+ produce_re_keys(deps.merge, re_keys),+ );+ require_acked(ProduceLeg::Membership, membership)?;+ require_acked(ProduceLeg::Cascade, cascade)?;+ Ok(Produced {+ span,+ stage2,+ tally,+ re_key_errors: re_key,+ })+ }+}++#[must_use]+struct Produced {+ span: OffsetSpan,+ stage2: Stage2Recompute,+ tally: Tally,+ /// Hand-offs that did not ack. Held until after the stage-2 commit; see+ /// [`Produced::commit_stage2`].+ re_key_errors: usize,+}++impl Produced {+ /// The composed bits and the single-leaf register bits commit only after the produce acks, so+ /// a failed produce is re-derived on replay instead of lost against a flipped bit.+ ///+ /// A failed hand-off still holds the run, but only once these bits are committed. The+ /// membership leg acked, so downstream holds the new truth and the register has to say so: the+ /// cascade for that flip is co-partitioned and is consumed right after this run, and it reads+ /// the referenced cohort's *stored* bit. Leaving that bit unwritten makes the cascade read the+ /// referrer as unchanged and mark itself, and every referring cohort stays stale until the next+ /// tenure replays the run. The replay is clean either way: the local seeds fold to `Unchanged`+ /// over their own rows, the register agrees, and only the hand-off is produced again.+ async fn commit_stage2(self, deps: ApplyDeps<'_>) -> Result<Settled, SeedHold> {+ commit_stage2_writes(deps.handle, &self.stage2.writes)+ .await+ .map_err(SeedHold::store(ApplyStage::Stage2Commit))?;+ // Committed, so a redelivery cannot double-count these and a hold cannot lose them.+ self.stage2.record_metrics();+ Ok(Settled {+ span: self.span,+ tally: self.tally,+ re_key_errors: self.re_key_errors,+ })+ }+}++#[must_use]+struct Settled {+ span: OffsetSpan,+ tally: Tally,+ re_key_errors: usize,+}++impl Settled {+ /// Everything the run counted, emitted once its offsets are safe to mark.+ ///+ /// A failed hand-off holds the run here, after its stage-2 commit; see+ /// [`Produced::commit_stage2`] for why the commit must not wait on that leg.+ fn record(self) -> Result<OffsetSpan, SeedHold> {+ require_acked(ProduceLeg::ReKey, self.re_key_errors)?;+ self.tally.record();+ Ok(self.span)+ }+}++// ---- Produce legs ----++async fn produce_membership_if_any(+ sink: &Arc<dyn MembershipSink>,+ changes: Vec<CohortMembershipChange>,+) -> usize {+ if changes.is_empty() {+ return 0;+ }+ produce_membership(sink, changes).await+}++/// Re-produce a run's hand-offs, awaiting exactly one `Ok` per seed. A re-keyed seed has no other+/// copy, so a short ack vector is a failure, never a vacuous success.+async fn produce_re_keys(merge: &MergeWorkerDeps, re_keys: ReKeys) -> usize {+ if re_keys.is_empty() {+ return 0;+ }+ let (errors, failure_metric) = match re_keys {+ ReKeys::Tiles(tiles) => {+ let expected = tiles.len();+ let acks = merge.seed_tile_sink.produce(tiles).await;+ (+ ack_errors(&acks, expected),+ SEED_REKEY_PRODUCE_FAILURE_TOTAL,+ )+ }+ ReKeys::Persons(seeds) => {+ let expected = seeds.len();+ let acks = merge.seed_tile_sink.produce_person(seeds).await;+ (+ ack_errors(&acks, expected),+ PERSON_SEED_REKEY_PRODUCE_FAILURE_TOTAL,+ )+ }+ };+ if errors > 0 {+ counter!(failure_metric).increment(errors as u64);+ }+ errors+}++fn ack_errors<E>(acks: &[Result<(), E>], expected: usize) -> usize {+ acks.iter().filter(|result| result.is_err()).count() + acks.len().abs_diff(expected)+}++fn require_acked(leg: ProduceLeg, errors: usize) -> Result<(), SeedHold> {+ if errors == 0 {+ return Ok(());+ }+ Err(SeedHold::Produce { leg, errors })+}++// ---- Driving a run ----++/// The kind-specific half of a run: route, read, fold. Exists only so [`apply`] is written once;+/// the two heads are ordinary modules.+pub(crate) trait SeedHead {+ type Seed;+ const KIND: SeedKind;++ async fn fold(+ deps: ApplyDeps<'_>,+ run: SeedRun<Self::Seed>,+ stamp: &RunStamp,+ clock: &mut StageClock,+ ) -> Result<Folded, SeedHold>;+}++/// Apply one run: fold it, then drive the shared pipeline, then mark or hold its whole span.+pub(crate) async fn apply<H: SeedHead>(+ deps: ApplyDeps<'_>,+ queue: &mut EvictionQueue<BehavioralKey>,+ clock: &mut LastUpdatedClock,+ marks: &mut BatchMarks,+ run: SeedRun<H::Seed>,+) {+ let span = run.span();+ let mut stages = StageClock::start(H::KIND, run.len());+ let stamp = RunStamp {+ now_ms: chrono::Utc::now().timestamp_millis(),+ last_updated: clock.next(),+ };+ let outcome = drive::<H>(deps, queue, run, &stamp, &mut stages).await;+ settle(deps, H::KIND, span, marks, outcome);+}++async fn drive<H: SeedHead>(+ deps: ApplyDeps<'_>,+ queue: &mut EvictionQueue<BehavioralKey>,+ run: SeedRun<H::Seed>,+ stamp: &RunStamp,+ stages: &mut StageClock,+) -> Result<OffsetSpan, SeedHold> {+ let folded = H::fold(deps, run, stamp, stages).await?;++ let diffed = folded.diff_registers(deps, stamp).await?;+ stages.mark(ApplyStage::RegisterDiff);++ let committed = diffed.commit_stage1(deps).await?;+ stages.mark(ApplyStage::Stage1Commit);++ let recomputed = committed.schedule(queue).recompute(deps, stamp).await?;+ stages.mark(ApplyStage::Recompute);++ let produced = recomputed.produce(deps).await?;+ stages.mark(ApplyStage::Produce);++ let settled = produced.commit_stage2(deps).await?;+ stages.mark(ApplyStage::Stage2Commit);++ settled.record()+}++/// Mark the run's whole span, or hold its first offset and count the failed stage.+fn settle(+ deps: ApplyDeps<'_>,+ kind: SeedKind,+ span: OffsetSpan,+ marks: &mut BatchMarks,+ outcome: Result<OffsetSpan, SeedHold>,+) {+ match outcome {+ Ok(marked) => marks.mark(marked.last),+ Err(held) => {+ counter!(+ SEED_APPLY_RUNS_HELD_TOTAL,+ "kind" => kind.as_str(),+ "stage" => held.stage().as_str(),+ )+ .increment(1);+ warn!(+ partition_id = deps.partition_id,+ kind = kind.as_str(),+ first_offset = span.first.0,+ last_offset = span.last.0,+ error = %held,+ "seed run apply failed; holding the run's first seed offset for redelivery",+ );+ hold(&deps.merge.seed_tracker, deps.partition_id, span.first);+ }+ }+}++/// Apply one channel batch's seed groups in order on the owning partition worker.+///+/// A group that holds pins the commit floor at its own first offset; later groups still run, and+/// the floor keeps the published mark from leapfrogging the hold — the same envelope as the+/// per-seed path, now at run granularity.+///+/// The mark itself is published once, after the last group, because groups' spans interleave (see+/// [`BatchMarks`]).+pub(crate) async fn handle_seed_groups(+ deps: ApplyDeps<'_>,+ queue: &mut EvictionQueue<BehavioralKey>,+ reconcile_queue: &mut ReconcileQueue,+ clock: &mut LastUpdatedClock,+ groups: Vec<SeedGroup>,+) {+ let mut marks = BatchMarks::default();+ for group in groups {+ match group {+ SeedGroup::Tiles(run) => {+ apply::<crate::workers::seed_path::TileHead>(deps, queue, clock, &mut marks, run)+ .await;+ }+ SeedGroup::Persons(run) => {+ apply::<crate::workers::person_seed_path::PersonHead>(+ deps, queue, clock, &mut marks, run,+ )+ .await;+ }+ SeedGroup::Reconcile(Admitted { work, offset }) => admit_reconcile(+ deps.partition_id,+ deps.merge,+ reconcile_queue,+ &mut marks,+ &work,+ offset,+ ),+ SeedGroup::Skip(Admitted { work, offset }) => {+ counter!(SEED_TILES_SKIPPED_TOTAL, "reason" => work.as_str()).increment(1);+ marks.mark(offset);+ }+ }+ }+ marks.publish(&deps.merge.seed_tracker, deps.partition_id);+}++#[cfg(test)]+mod tests {+ use chrono_tz::UTC;+ use metrics_exporter_prometheus::PrometheusBuilder;++ use crate::filters::TeamFiltersBuilder;++ use super::*;++ fn overlay_of(values: Vec<Option<&str>>) -> Overlay<u8, String> {+ let keys: Vec<u8> = (0..values.len() as u8).collect();+ let values: Vec<Option<Vec<u8>>> = values+ .into_iter()+ .map(|value| value.map(|value| value.as_bytes().to_vec()))+ .collect();+ Overlay::from_read(+ ApplyStage::Read,+ keys,+ values,+ |bytes| match std::str::from_utf8(bytes) {+ Ok("corrupt") | Err(_) => Decoded::Corrupt,+ Ok(value) => Decoded::Value(value.to_string()),+ },+ )+ .unwrap()+ }++ /// The whole point of the overlay: a second seed for one key must fold onto the first seed's+ /// result, or a run of two would apply both against the same run-start bytes.+ #[test]+ fn a_later_fold_sees_the_earlier_folds_result_but_before_stays_the_read() {+ let mut overlay = overlay_of(vec![Some("first")]);++ let slot = overlay.slot_mut(&0).unwrap();+ assert_eq!(slot.current().map(String::as_str), Some("first"));+ slot.advance("second".to_string());+ assert_eq!(slot.current().map(String::as_str), Some("second"));+ assert_eq!(+ slot.before().map(String::as_str),+ Some("first"),+ "the net-transition rule diffs against the read pass, not the last write",+ );+ assert!(slot.advanced().is_some());+ }++ /// A corrupt row reads as absent with the flag set, so the tile fold can refuse it while the+ /// person fold rebuilds from the absent baseline.+ #[test]+ fn a_corrupt_row_reads_absent_and_flags_itself() {+ let mut overlay = overlay_of(vec![Some("corrupt")]);+ let slot = overlay.slot_mut(&0).unwrap();++ assert!(slot.prior_corrupt());+ assert!(slot.current().is_none());+ assert!(slot.before().is_none());+ }++ /// A short answer would pair one key's slot with another key's bytes.+ #[test]+ fn a_short_read_holds_the_run_rather_than_pairing_slots_wrongly() {+ let result = Overlay::<u8, String>::from_read(+ ApplyStage::Read,+ vec![0, 1, 2],+ vec![None, None],+ |_| Decoded::Corrupt,+ );++ assert!(matches!(+ result,+ Err(SeedHold::ShortRead {+ stage: ApplyStage::Read,+ asked: 3,+ answered: 2,+ }),+ ));+ }++ /// Counting mid-run would report a held run's work once per redelivery.+ #[test]+ fn a_tally_sums_repeats_of_one_outcome() {+ let mut tally = Tally::default();+ tally.add(Outcome::TileApplied("behavioral_single"));+ tally.add(Outcome::TileApplied("behavioral_single"));+ tally.add(Outcome::PersonUnchanged);++ assert_eq!(tally.durable[&Outcome::TileApplied("behavioral_single")], 2);+ assert_eq!(tally.settled[&Outcome::PersonUnchanged], 1);+ }++ /// The split is what makes each half exactly-once. An advance the replay cannot re-mint has to+ /// publish at the stage-1 commit; anything a replay repeats has to wait for the run to settle,+ /// or a hold counts it once per attempt.+ #[test]+ fn a_tally_splits_advances_from_what_a_replay_repeats() {+ for outcome in [+ Outcome::TileApplied("behavioral_single"),+ Outcome::PersonApplied("fresh"),+ Outcome::Stage1Transition("entered"),+ Outcome::UnmappedTransition,+ ] {+ assert!(+ outcome.durable_at_stage1(),+ "{outcome:?} advanced durable state, so the replay mints nothing",+ );+ }+ for outcome in [+ Outcome::TileUnchanged("behavioral_single"),+ Outcome::TileDropped("corrupt_state"),+ Outcome::PersonUnchanged,+ Outcome::PersonSkipped("stale_vs_live"),+ Outcome::PersonDropped("team_absent"),+ Outcome::ReKeyed(SeedKind::Tile),+ ] {+ assert!(+ !outcome.durable_at_stage1(),+ "a replay derives {outcome:?} again",+ );+ }+ }++ /// A run held after its stage-1 commit must not publish the advances that commit already+ /// counted a second time when it settles.+ #[test]+ fn the_durable_half_publishes_once() {+ let mut tally = Tally::default();+ tally.add(Outcome::TileApplied("behavioral_single"));+ tally.add(Outcome::PersonUnchanged);+ tally.record_durable();++ assert!(tally.durable.is_empty(), "drained by the stage-1 commit");+ assert_eq!(+ tally.settled[&Outcome::PersonUnchanged],+ 1,+ "what a replay repeats still waits for the run to settle",+ );+ }++ #[test]+ fn an_unmapped_transition_publishes_once_at_the_stage1_boundary() {+ let recorder = PrometheusBuilder::new().build_recorder();+ let handle = recorder.handle();+ let filters = TeamFiltersBuilder::default().freeze(UTC);+ let transition = LeafTransition {+ team_id: TeamId(7),+ leaf_state_key: LeafStateKey([0xEE; 16]),+ person_id: Uuid::from_u128(1),+ condition_hash: [0xDD; 16],+ kind: crate::stage1::transition::TransitionKind::Entered,+ };+ let mut tally = Tally::default();+ record_stage1_transition(&mut tally, &filters, &transition);++ metrics::with_local_recorder(&recorder, || {+ tally.record_durable();+ tally.record_durable();+ tally.record();+ });++ assert!(handle+ .render()+ .contains("output_transitions_unmapped_total{reason=\"no_emitting_cohort\"} 1"));+ }++ /// Splitting a person across two recompute calls would evaluate the same cohort twice against+ /// the same uncommitted bit and emit the flip twice.+ #[test]+ fn a_person_touched_twice_stays_in_one_group_under_the_last_run() {+ let team = TeamId(7);+ let alice = Uuid::from_u128(1);+ let first = RunId(Uuid::from_u128(0xA));+ let last = RunId(Uuid::from_u128(0xB));+ let mut touched = TouchedPersons::default();+ touched.touch(team, alice, first, LeafStateKey([1; 16]));+ touched.touch(team, alice, last, LeafStateKey([2; 16]));+ touched.touch_lagging(team, alice, first, LeafStateKey([3; 16]));++ let groups = touched.groups();+ assert_eq!(groups.len(), 1, "one call, not one per seed");+ assert_eq!(+ groups[&(team, last)],+ vec![+ (LeafStateKey([1; 16]), alice),+ (LeafStateKey([2; 16]), alice),+ (LeafStateKey([3; 16]), alice),+ ],+ "every leaf rides the last seed's run; a lagging leaf joins without moving it",+ );+ }+}diff --git a/rust/cohort-stream-processor/src/workers/seed_path.rs b/rust/cohort-stream-processor/src/workers/seed_path.rsindex 337cc1c3c9ef..3a5b51cf6505 100644--- a/rust/cohort-stream-processor/src/workers/seed_path.rs+++ b/rust/cohort-stream-processor/src/workers/seed_path.rs@@ -1,43 +1,34 @@//! The seed-tile apply path: a pure, clock-free core ([`merge_tile_into_leaf`]) that mirrors the//! live fold minus dedup (slide-before-evaluate, max-merge of the tile's absolute count,-//! structural-equality `Unchanged` — the whole of tile idempotency), and an imperative shell-//! ([`handle_seed`]) ordered register diff → stage-1 commit → stage-2 recompute → produce →-//! stage-2 commit → mark.+//! structural-equality `Unchanged` — the whole of tile idempotency), and [`TileHead`], which routes+//! a run of tiles, reads every leaf they can touch in one batch, and folds them into an overlay.//!+//! [`seed_apply`](crate::workers::seed_apply) owns everything after the fold: register diff →+//! stage-1 commit → schedule → recompute → produce → stage-2 commit → mark.//! Before an emission, this path records the retired membership with stage 1 and advances it only//! after the produce acks. A failed produce is therefore re-derived while replay still folds the-//! leaf. If the leaf expires before replay and is dropped by the fold, sweep or reconcile retires-//! its stored state. Composed bits come from [`recompute_stage2`]; single-leaf ones from+//! leaf. If the leaf expires before replay and the fold drops it, this repair no longer applies;+//! eviction and reconcile remain its recovery paths. Composed bits come from+//! [`recompute_stage2`](crate::workers::stage2_path::recompute_stage2); single-leaf ones from//! [`diff_single_leaf_registers`](crate::workers::stage2_path::diff_single_leaf_registers), which//! is why `Unchanged` leaves still take part. The replay mints no transition, so the persisted//! register is the only record of what downstream was told. Store and produce failures hold the-//! seed offset.+//! run's first seed offset.+use std::collections::{BTreeMap, HashMap};use std::num::NonZeroU32;-use std::sync::Arc;-use chrono::Utc;use chrono_tz::Tz;-use metrics::{counter, gauge};-use tracing::{debug, warn};+use metrics::counter;+use tracing::warn;use uuid::Uuid;-use cohort_core::seed::{PersonSeed, ReconcileTile, RunId, SeedTile};+use cohort_core::seed::{PersonSeed, RunId, SeedTile};-use crate::consumers::seeds::SeedWork;-use crate::filters::manager::CatalogHandle;use crate::filters::reverse_index::{LeafStateMeta, TeamFilters};use crate::filters::TeamId;-use crate::merge::tombstone_redirect::{self, Resolution, MAX_CROSS_PARTITION_REDIRECT_HOPS};-use crate::observability::metrics::{- COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH, OUTPUT_TRANSITIONS_UNMAPPED,- RECONCILE_JOBS_ENQUEUED_TOTAL, RECONCILE_JOBS_SUPERSEDED_TOTAL, SEED_HELD_OFFSET_GAUGE,- SEED_REKEYED_TOTAL, SEED_REKEY_HOP_CAPPED_TOTAL, SEED_REKEY_PRODUCE_FAILURE_TOTAL,- SEED_TILES_APPLIED_TOTAL, SEED_TILES_DROPPED_TOTAL, SEED_TILES_SKIPPED_TOTAL,- SEED_TILES_UNCHANGED_TOTAL, STAGE1_STATE_DECODE_ERROR, STAGE1_TRANSITIONS,-};-use crate::partitions::offset_tracker::{MarkOutcome, OffsetTracker};-use crate::producer::{ChangeOrigin, CohortMembershipChange, MembershipSink};+use crate::merge::tombstone_redirect::{Resolution, MAX_CROSS_PARTITION_REDIRECT_HOPS};+use crate::observability::metrics::{SEED_REKEY_HOP_CAPPED_TOTAL, STAGE1_STATE_DECODE_ERROR};use crate::stage1::bucket_tz::{daily_bucket_len, day_idx_in_tz, start_of_day_ms_in_tz, window_start_for_now, DayIdx,};@@ -49,17 +40,13 @@ use crate::stage1::predicate::{compressed_predicate, daily_predicate, predicate}use crate::stage1::state::{Stage1State, StateVariant, StatefulRecord};use crate::stage1::transition::{LeafTransition, TransitionKind};use crate::stage2::leaf_membership;-use crate::store::{Behavioral, BehavioralKey, PersonPrefix, ReadLane, StagedBatch, StoreHandle};-use crate::sweep::EvictionQueue;-use crate::workers::merge_path::MergeWorkerDeps;-use crate::workers::person_seed_path::handle_person_seed;-use crate::workers::reconcile::{ReconcileQueue, SupersedeOutcome};-use crate::workers::stage2_path::{- commit_stage2_writes, diff_single_leaf_registers, recompute_stage2, FoldedLeaf,-};-use crate::workers::worker::{- first_cascades, produce_cascades, produce_membership, transition_metric_label,+use crate::store::{Behavioral, BehavioralKey, PersonPrefix, ReadLane, StagedBatch};+use crate::workers::seed_apply::{+ record_stage1_transition, resolve_run_persons, ApplyDeps, ApplyStage, Decoded, Folded, Outcome,+ Overlay, ReKeys, RunStamp, SeedHead, SeedHold, StageClock, Tally, TouchedPersons,};+use crate::workers::seed_run::{Admitted, OffsetSpan, SeedKind, SeedRun};+use crate::workers::stage2_path::FoldedLeaf;/// A seed kind that can be re-keyed onto a merge survivor.pub(crate) trait RekeyableSeed: Sized {@@ -198,7 +185,7 @@ pub(crate) fn merge_tile_into_leaf(identity: LeafIdentity,tile_day: DayIdx,count: NonZeroU32,- prev: Option<StatefulRecord>,+ prev: Option<&StatefulRecord>,now_day: DayIdx,now_ms: i64,) -> LeafMergeOutcome {@@ -241,7 +228,7 @@ fn merge_single(tz: Tz,identity: LeafIdentity,tile_day: DayIdx,- prev: Option<StatefulRecord>,+ prev: Option<&StatefulRecord>,now_ms: i64,) -> LeafMergeOutcome {let Some(window) = window else {@@ -262,19 +249,18 @@ fn merge_single(EvictionWindow::RelativeDays { .. } => {}}- let prev_state = prev.as_ref().map(|record| record.state.clone());let (prev_last, predicate_before, applied, redirect) = match prev {None => (i64::MIN, false, Default::default(), Default::default()),Some(record) => {let before = predicate(&record.state);- match record.state {+ match &record.state {Stage1State::BehavioralSingle {last_event_at_ms, ..} => (- last_event_at_ms,+ *last_event_at_ms,before,- record.applied_offsets,- record.redirect_dedup,+ record.applied_offsets.clone(),+ record.redirect_dedup.clone(),),_ => return LeafMergeOutcome::Dropped(SeedDropReason::VariantMismatch),}@@ -298,7 +284,7 @@ fn merge_single(};finish(identity,- prev_state,+ prev.map(|record| &record.state),record,predicate_before,true,@@ -314,7 +300,7 @@ fn merge_daily(identity: LeafIdentity,tile_day: DayIdx,count: NonZeroU32,- prev: Option<StatefulRecord>,+ prev: Option<&StatefulRecord>,now_day: DayIdx,) -> LeafMergeOutcome {let (Some(window_days), Some(op)) = (window_days, op) else {@@ -322,22 +308,23 @@ fn merge_daily(};let len = daily_bucket_len(window_days);- let prev_state = prev.as_ref().map(|record| record.state.clone());let (prior, predicate_before, applied, redirect) = match prev {None => (None, false, Default::default(), Default::default()),- Some(record) => match record.state {+ Some(record) => match &record.state {Stage1State::BehavioralDailyBuckets {buckets,window_start_day,last_event_at_ms,..} => {- let before = daily_predicate(&buckets, op);+ let before = daily_predicate(buckets, op);(- Some((buckets, window_start_day, last_event_at_ms)),+ // Cloned because the merge mutates it; the prior state itself stays borrowed+ // for the `Unchanged` compare.+ Some((buckets.clone(), *window_start_day, *last_event_at_ms)),before,- record.applied_offsets,- record.redirect_dedup,+ record.applied_offsets.clone(),+ record.redirect_dedup.clone(),)}_ => return LeafMergeOutcome::Dropped(SeedDropReason::VariantMismatch),@@ -390,7 +377,7 @@ fn merge_daily(};finish(identity,- prev_state,+ prev.map(|record| &record.state),record,predicate_before,predicate_after,@@ -406,29 +393,30 @@ fn merge_compressed(identity: LeafIdentity,tile_day: DayIdx,count: NonZeroU32,- prev: Option<StatefulRecord>,+ prev: Option<&StatefulRecord>,now_day: DayIdx,) -> LeafMergeOutcome {let (Some(window_days), Some(op)) = (window_days, op) else {return LeafMergeOutcome::Dropped(SeedDropReason::MetaIncomplete);};- let prev_state = prev.as_ref().map(|record| record.state.clone());let (prior, predicate_before, applied, redirect) = match prev {None => (None, false, Default::default(), Default::default()),- Some(record) => match record.state {+ Some(record) => match &record.state {Stage1State::BehavioralCompressedHistory {entries,window_start_day,last_event_at_ms,..} => {- let before = compressed_predicate(&entries, op);+ let before = compressed_predicate(entries, op);(- Some((entries, window_start_day, last_event_at_ms)),+ // Cloned because the merge mutates it; the prior state itself stays borrowed+ // for the `Unchanged` compare.+ Some((entries.clone(), *window_start_day, *last_event_at_ms)),before,- record.applied_offsets,- record.redirect_dedup,+ record.applied_offsets.clone(),+ record.redirect_dedup.clone(),)}_ => return LeafMergeOutcome::Dropped(SeedDropReason::VariantMismatch),@@ -473,7 +461,7 @@ fn merge_compressed(};finish(identity,- prev_state,+ prev.map(|record| &record.state),record,predicate_before,predicate_after,@@ -484,13 +472,13 @@ fn merge_compressed(/// `Unchanged` detection + transition minting shared by all three variants.fn finish(identity: LeafIdentity,- prev_state: Option<Stage1State>,+ prev_state: Option<&Stage1State>,record: StatefulRecord,predicate_before: bool,predicate_after: bool,deadline_ms: i64,) -> LeafMergeOutcome {- if prev_state.as_ref() == Some(&record.state) {+ if prev_state == Some(&record.state) {return LeafMergeOutcome::Unchanged { record };}let kind = match (predicate_before, predicate_after) {@@ -505,495 +493,327 @@ fn finish(}}-/// Handle one seed message on its owning partition worker; marks or holds the seed tracker only.-#[allow(clippy::too_many_arguments)]-pub(crate) async fn handle_seed(- partition_id: u16,- handle: &StoreHandle,- catalog: &CatalogHandle,- sink: &Arc<dyn MembershipSink>,- merge: &MergeWorkerDeps,- queue: &mut EvictionQueue<BehavioralKey>,- reconcile_queue: &mut ReconcileQueue,- last_updated: &str,- work: &SeedWork,- offset: i64,-) {- let tile = match work {- SeedWork::Skip(reason) => {- counter!(SEED_TILES_SKIPPED_TOTAL, "reason" => reason.as_str()).increment(1);- mark_processed(&merge.seed_tracker, partition_id, offset);- return;- }- SeedWork::Reconcile(tile) => {- admit_reconcile(partition_id, merge, reconcile_queue, tile, offset);- return;- }- SeedWork::Person(seed) => {- handle_person_seed(- partition_id,- handle,- catalog,- sink,- merge,- last_updated,- seed,- offset,- )- .await;- return;- }- SeedWork::Tile(tile) => tile,- };-- let snapshot = catalog.load();- let Some(team_filters) = snapshot.team(tile.team_id()) else {- counter!(SEED_TILES_DROPPED_TOTAL, "reason" => "team_absent").increment(1);- mark_processed(&merge.seed_tracker, partition_id, offset);- return;- };- let filters: &TeamFilters = team_filters;-- // A read failure is fail-stop: a tile mis-applied to a merged-away person is durable state- // reconcile cannot retract.- let resolution = match tombstone_redirect::resolve_offloaded(- handle,- partition_id,- tile.team_id(),- tile.person_id(),- merge.partition_count,- ReadLane::Maintenance,- )- .await- {- Ok(resolution) => resolution,- Err(error) => {- warn!(- partition_id,- team_id = tile.team_id().0,- error = %error,- "seed tombstone preflight read failed; holding the seed offset for redelivery",- );- hold(&merge.seed_tracker, partition_id, offset);- return;- }- };- let person = match route_seed(tile, resolution, MAX_CROSS_PARTITION_REDIRECT_HOPS) {- SeedRoute::ApplyLocal { person } => person,- SeedRoute::ReProduce { seed: rekeyed } => {- // Ack before mark; the tile has no other copy. Exactly one Ok ack — an empty vector- // would make an `all(is_ok)` guard vacuously true and commit past a lost tile.- let acks = merge.seed_tile_sink.produce(vec![rekeyed]).await;- if matches!(acks.as_slice(), [Ok(())]) {- counter!(SEED_REKEYED_TOTAL).increment(1);- mark_processed(&merge.seed_tracker, partition_id, offset);- } else {- counter!(SEED_REKEY_PRODUCE_FAILURE_TOTAL).increment(1);- warn!(- partition_id,- team_id = tile.team_id().0,- "seed tile re-key produce failed; holding the seed offset for redelivery",- );- hold(&merge.seed_tracker, partition_id, offset);- }- return;- }- SeedRoute::CapExhausted { person } => {- counter!(SEED_REKEY_HOP_CAPPED_TOTAL).increment(1);- // Same degrade as the event path: orphaned-but-bounded state (the survivor's live- // path never reads this slice) that ages out via eviction, preferred over a silent- // tile loss.- warn!(- partition_id,- team_id = tile.team_id().0,- %person,- hops = tile.redirect_hops(),- "seed redirect hop cap hit (corrupt tombstone cycle?); applying inline at the best-known target",- );- person- }- };+/// The tile head: route each seed, read every leaf it can touch in one batch, and fold the run+/// into an overlay. Everything after this is [`seed_apply`](crate::workers::seed_apply)'s.+pub(crate) struct TileHead;- let lsks: &[LeafStateKey] = filters- .by_condition_to_lsk- .get(&tile.condition_hash().as_bytes())- .map_or(&[], Vec::as_slice);- if lsks.is_empty() {- // Expected for a stale/edited cohort: the hash no longer resolves.- counter!(SEED_TILES_DROPPED_TOTAL, "reason" => "no_referencing_leaves").increment(1);- mark_processed(&merge.seed_tracker, partition_id, offset);- return;- }-- let prefix = PersonPrefix::new(partition_id, tile.team_id().0 as u64, person);- let keys: Vec<BehavioralKey> = lsks.iter().map(|&lsk| prefix.behavioral_key(lsk)).collect();- // Maintenance lane: backfill must not contend with live event reads.- let values = match handle- .multi_get_behavioral(keys, ReadLane::Maintenance)- .await- {- Ok(values) => values,- Err(error) => {- warn!(- partition_id,- team_id = tile.team_id().0,- error = %error,- "seed state read failed; holding the seed offset for redelivery",- );- hold(&merge.seed_tracker, partition_id, offset);- return;- }- };+impl SeedHead for TileHead {+ type Seed = SeedTile;+ const KIND: SeedKind = SeedKind::Tile;- let now_ms = Utc::now().timestamp_millis();- let now_day = day_idx_in_tz(now_ms, filters.timezone);- let TileApplication {- mut staged,- transitions,- leaves,- schedules,- } = apply_tile_to_leaves(- filters, &prefix, lsks, values, tile, person, now_day, now_ms,- );+ async fn fold(+ deps: ApplyDeps<'_>,+ run: SeedRun<SeedTile>,+ stamp: &RunStamp,+ clock: &mut StageClock,+ ) -> Result<Folded, SeedHold> {+ let span = run.span();+ let mut tally = Tally::default();- // Order: register diff → stage-1 commit → stage-2 recompute → produce → stage-2 commit →- // schedule → mark. The diff reads first, so a row this apply is about to place cannot be- // mistaken for one an earlier apply already told downstream about.- let diff = match diff_single_leaf_registers(- partition_id,- handle,- filters,- &leaves,- now_ms,- last_updated,- ReadLane::Maintenance,- )- .await- {- Ok(diff) => diff,- Err(error) => {- warn!(- partition_id,- team_id = tile.team_id().0,- error = %error,- "seed register read failed; holding the seed offset for redelivery",- );- hold(&merge.seed_tracker, partition_id, offset);- return;- }- };- for (key, state) in &diff.stage1_writes {- staged.put_stage2(key, &state.encode());- }+ let Routed { local, re_keys } = route_tiles(deps, run, &mut tally).await?;+ clock.mark(ApplyStage::Resolve);- if !staged.is_empty() {- if let Err(error) = handle.commit(staged).await {- warn!(- partition_id,- team_id = tile.team_id().0,- error = %error,- "seed state commit failed; holding the seed offset for redelivery",- );- hold(&merge.seed_tracker, partition_id, offset);- return;- }- }+ let overlay = read_leaf_state(deps, &local).await?;+ clock.mark(ApplyStage::Read);- count_stage1_transitions(filters, &transitions);- let stage2_leaves: Vec<(LeafStateKey, Uuid)> = leaves.iter().map(|leaf| leaf.pair()).collect();- // `event_ms := now_ms`: `last_evaluated_at_ms` is a freshness stamp, and the worker-batch- // `last_updated` makes backfill flips win LWW downstream.- let mut recompute = diff.recompute;- match recompute_stage2(- partition_id,- handle,- filters,- &stage2_leaves,- now_ms,- last_updated,- ReadLane::Maintenance,- )- .await- {- Ok(composed) => recompute.extend(composed),- Err(error) => {- warn!(- partition_id,- team_id = tile.team_id().0,- error = %error,- "seed stage 2 recompute failed; holding the seed offset for redelivery",- );- hold(&merge.seed_tracker, partition_id, offset);- return;- }- }- let mut changes = std::mem::take(&mut recompute.changes);-- tag_seed(&mut changes, tile.run_id());- // Only the cascade topic can re-evaluate cohort-of-cohort referrers; gate-off builds nothing.- let cascades = first_cascades(merge, &changes, offset);- if !changes.is_empty() {- let errors = produce_membership(sink, changes).await;- if errors > 0 {- // Every bit this apply would advance is still unwritten, so the replay re-derives both- // halves and re-emits; the duplicates are LWW-safe downstream.- warn!(- partition_id,- team_id = tile.team_id().0,- errors,- "seed membership produce failed; holding the seed offset for redelivery",- );- hold(&merge.seed_tracker, partition_id, offset);- return;- }- }- let cascade_errors = produce_cascades(merge, cascades).await;- if cascade_errors > 0 {- warn!(- partition_id,- team_id = tile.team_id().0,- errors = cascade_errors,- "seed cascade produce failed; holding the seed offset for redelivery",- );- hold(&merge.seed_tracker, partition_id, offset);- return;+ let folded = fold_tiles(span, local, re_keys, overlay, stamp, tally);+ clock.mark(ApplyStage::Fold);+ Ok(folded)}+}- // The composed bits and the single-leaf register bits commit only after both produces ack, so- // a failed produce is re-derived on replay instead of lost against a flipped bit.- if let Err(error) = commit_stage2_writes(handle, &recompute.writes).await {- warn!(- partition_id,- team_id = tile.team_id().0,- error = %error,- "seed stage 2 commit failed; holding the seed offset for redelivery",- );- hold(&merge.seed_tracker, partition_id, offset);- return;- }- recompute.record_metrics();+/// One tile that applies on this partition, with everything its fold needs already resolved.+struct LocalTile<'a> {+ tile: SeedTile,+ person: Uuid,+ filters: &'a TeamFilters,+ /// The leaves this tile's condition reaches. Never empty: an empty set is a counted drop.+ lsks: &'a [LeafStateKey],+ prefix: PersonPrefix,+}- for (key, deadline) in schedules {- queue.schedule(key, deadline);- }- mark_processed(&merge.seed_tracker, partition_id, offset);+struct Routed<'a> {+ local: Vec<LocalTile<'a>>,+ re_keys: Vec<SeedTile>,}-fn admit_reconcile(- partition_id: u16,- merge: &MergeWorkerDeps,- queue: &mut ReconcileQueue,- tile: &ReconcileTile,- offset: i64,-) {- if !merge.reconcile.enabled {- counter!(SEED_TILES_SKIPPED_TOTAL, "reason" => "reconcile_disabled").increment(1);- warn!(- partition_id,- team_id = tile.team_id().0,- cohort_id = tile.cohort_id().0,- run_id = %tile.run_id().0,- "reconcile seed skipped while reconcile is disabled; re-dispatch after enabling",- );- mark_processed(&merge.seed_tracker, partition_id, offset);- return;+/// Resolve every distinct person's tombstone chain in one batched read, then split the run into+/// what applies here and what hands off.+///+/// A read failure is fail-stop: a tile mis-applied to a merged-away person is durable state+/// reconcile cannot retract, so a missing verdict holds the run rather than reading as not-merged.+async fn route_tiles<'a>(+ deps: ApplyDeps<'a>,+ run: SeedRun<SeedTile>,+ tally: &mut Tally,+) -> Result<Routed<'a>, SeedHold> {+ let mut placed: Vec<(SeedTile, &TeamFilters)> = Vec::with_capacity(run.len());+ for Admitted { work: tile, .. } in run.into_items() {+ let Some(filters) = deps.team(tile.team_id()) else {+ tally.add(Outcome::TileDropped("team_absent"));+ continue;+ };+ placed.push((tile, filters));}- let kind = tile.scope().kind();- let deferred = match queue.supersede_if_newer(tile.team_id(), tile.cohort_id(), kind, offset) {- SupersedeOutcome::NoQueuedJob => merge.seed_tracker.defer(partition_id as i32, offset),- SupersedeOutcome::Replaced(superseded) => {- let (replacement, outcome) = merge- .seed_tracker- .replace_deferred(superseded, offset)- .expect("a queued reconcile must retain its deferred offset in the current tenure");- match outcome {- MarkOutcome::WithinDispatch => {}- MarkOutcome::CappedAheadOfDispatch => {- counter!(COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH).increment(1);- warn!(- partition_id,- "superseded reconcile completion exceeded the seed dispatch ceiling",- );- }+ let persons: Vec<(TeamId, Uuid)> = placed+ .iter()+ .map(|(tile, _)| (tile.team_id(), tile.person_id()))+ .collect();+ let resolved = resolve_run_persons(deps, persons).await?;++ let mut local = Vec::with_capacity(placed.len());+ let mut re_keys = Vec::new();+ for (tile, filters) in placed {+ let resolution = resolved[&(tile.team_id(), tile.person_id())];+ let person = match route_seed(&tile, resolution, MAX_CROSS_PARTITION_REDIRECT_HOPS) {+ SeedRoute::ApplyLocal { person } => person,+ SeedRoute::ReProduce { seed: rekeyed } => {+ tally.add(Outcome::ReKeyed(SeedKind::Tile));+ re_keys.push(rekeyed);+ continue;}- counter!(RECONCILE_JOBS_SUPERSEDED_TOTAL, "kind" => kind.as_str()).increment(1);- replacement- }- SupersedeOutcome::RetainedNewerOrEqual => {- counter!(SEED_TILES_SKIPPED_TOTAL, "reason" => "reconcile_stale_replay").increment(1);- debug!(- partition_id,- team_id = tile.team_id().0,- cohort_id = tile.cohort_id().0,- run_id = %tile.run_id().0,- offset,- "replayed reconcile seed retained the newer or equal queued job",- );- mark_processed(&merge.seed_tracker, partition_id, offset);- return;+ SeedRoute::CapExhausted { person } => {+ // On the attempt, with the warning: a run that a later hold keeps from settling+ // must not hide the anomaly.+ counter!(SEED_REKEY_HOP_CAPPED_TOTAL).increment(1);+ // Same degrade as the event path: orphaned-but-bounded state (the survivor's live+ // path never reads this slice) that ages out via eviction, preferred over a silent+ // tile loss.+ warn!(+ partition_id = deps.partition_id,+ team_id = tile.team_id().0,+ %person,+ hops = tile.redirect_hops(),+ "seed redirect hop cap hit (corrupt tombstone cycle?); applying inline at the best-known target",+ );+ person+ }+ };+ let lsks: &[LeafStateKey] = filters+ .by_condition_to_lsk+ .get(&tile.condition_hash().as_bytes())+ .map_or(&[], Vec::as_slice);+ if lsks.is_empty() {+ // Expected for a stale/edited cohort: the hash no longer resolves.+ tally.add(Outcome::TileDropped("no_referencing_leaves"));+ continue;}- };+ let prefix = PersonPrefix::new(deps.partition_id, tile.team_id().0 as u64, person);+ local.push(LocalTile {+ tile,+ person,+ filters,+ lsks,+ prefix,+ });+ }+ Ok(Routed { local, re_keys })+}- queue.enqueue(tile.clone(), deferred);- counter!(RECONCILE_JOBS_ENQUEUED_TOTAL, "kind" => kind.as_str()).increment(1);+/// One `multi_get` over every leaf the run can touch, on the maintenance lane so backfill never+/// contends with live event reads. A row that does not decode is counted here, at the read: a run+/// that a later hold keeps from settling must not hide it.+async fn read_leaf_state(+ deps: ApplyDeps<'_>,+ local: &[LocalTile<'_>],+) -> Result<Overlay<BehavioralKey, StatefulRecord>, SeedHold> {+ let mut keys: Vec<BehavioralKey> = local+ .iter()+ .flat_map(|tile| tile.lsks.iter().map(|&lsk| tile.prefix.behavioral_key(lsk)))+ .collect();+ keys.sort_unstable();+ keys.dedup();++ let values = deps+ .handle+ .multi_get_behavioral(keys.clone(), ReadLane::Maintenance)+ .await+ .map_err(SeedHold::store(ApplyStage::Read))?;+ let overlay =+ Overlay::from_read(+ ApplyStage::Read,+ keys,+ values,+ |bytes| match StatefulRecord::decode(bytes) {+ Ok(record) => Decoded::Value(record),+ Err(_) => Decoded::Corrupt,+ },+ )?;+ let corrupt = overlay.prior_corrupt_rows();+ if corrupt > 0 {+ counter!(STAGE1_STATE_DECODE_ERROR).increment(corrupt as u64);+ }+ Ok(overlay)}-/// What one tile staged across its referencing leaves.-#[derive(Default)]-struct TileApplication {- staged: StagedBatch,- transitions: Vec<LeafTransition>,- /// Merged *and* Unchanged leaves both feed the register diff and the Stage 2 recompute, so a- /// crash between the two commits self-heals on replay: the replayed tile mints no transition,- /// but the leaf's folded truth still diffs against what downstream was told.- leaves: Vec<FoldedLeaf>,- schedules: Vec<(BehavioralKey, i64)>,+/// What the run left on one leaf, carried from the fold to the emit.+struct LeafTouch<'a> {+ team_id: TeamId,+ filters: &'a TeamFilters,+ meta: &'a LeafStateMeta,+ /// The run of the last seed that touched this leaf; stamped on the changes it emits.+ run_id: RunId,+ /// The last merge's deadline. [`i64::MAX`] = permanent, never scheduled.+ deadline_ms: i64,}-/// Fold the tile into every referencing leaf.-#[allow(clippy::too_many_arguments)]-fn apply_tile_to_leaves(- filters: &TeamFilters,- prefix: &PersonPrefix,- lsks: &[LeafStateKey],- values: Vec<Option<Vec<u8>>>,- tile: &SeedTile,- person: Uuid,- now_day: DayIdx,- now_ms: i64,-) -> TileApplication {- let count = tile.count_nonzero();- let mut application = TileApplication::default();- for (&lsk, bytes) in lsks.iter().zip(values) {- let Some(meta) = filters.by_lsk.get(&lsk) else {- counter!(SEED_TILES_DROPPED_TOTAL, "reason" => SeedDropReason::MetaIncomplete.as_str())- .increment(1);- continue;- };- let prev = match bytes {- None => None,- Some(bytes) => match StatefulRecord::decode(&bytes) {- Ok(record) => Some(record),- Err(_) => {- counter!(STAGE1_STATE_DECODE_ERROR).increment(1);- counter!(SEED_TILES_DROPPED_TOTAL, "reason" => "corrupt_state").increment(1);- continue;+/// Fold every local tile into the overlay in offset order, then read the run's durable intent off+/// the touched slots.+fn fold_tiles(+ span: OffsetSpan,+ local: Vec<LocalTile<'_>>,+ re_keys: Vec<SeedTile>,+ mut overlay: Overlay<BehavioralKey, StatefulRecord>,+ stamp: &RunStamp,+ mut tally: Tally,+) -> Folded {+ // Once per team: a run can span teams in different time zones.+ let mut now_days: HashMap<TeamId, DayIdx> = HashMap::new();+ let mut touches: BTreeMap<BehavioralKey, LeafTouch<'_>> = BTreeMap::new();+ let mut recompose = TouchedPersons::default();++ for tile in &local {+ let team_id = tile.tile.team_id();+ let now_day = *now_days+ .entry(team_id)+ .or_insert_with(|| day_idx_in_tz(stamp.now_ms, tile.filters.timezone));+ let count = tile.tile.count_nonzero();+ for &lsk in tile.lsks {+ let Some(meta) = tile.filters.by_lsk.get(&lsk) else {+ tally.add(Outcome::TileDropped(+ SeedDropReason::MetaIncomplete.as_str(),+ ));+ continue;+ };+ let key = tile.prefix.behavioral_key(lsk);+ let slot = overlay+ .slot_mut(&key)+ .expect("the read pass keyed a slot for every leaf this run can touch");+ if slot.prior_corrupt() {+ tally.add(Outcome::TileDropped("corrupt_state"));+ continue;+ }+ let identity = LeafIdentity {+ team_id,+ lsk,+ person_id: tile.person,+ condition_hash: tile.tile.condition_hash().as_bytes(),+ };+ let outcome = merge_tile_into_leaf(+ meta,+ tile.filters.timezone,+ identity,+ tile.tile.day_idx(),+ count,+ slot.current(),+ now_day,+ stamp.now_ms,+ );+ let deadline_ms = match outcome {+ LeafMergeOutcome::Merged {+ record,+ deadline_ms,+ ..+ } => {+ tally.add(Outcome::TileApplied(record.state.variant().as_str()));+ slot.advance(record);+ deadline_ms}- },- };- let identity = LeafIdentity {- team_id: tile.team_id(),- lsk,- person_id: person,- condition_hash: tile.condition_hash().as_bytes(),- };- match merge_tile_into_leaf(- meta,- filters.timezone,- identity,- tile.day_idx(),- count,- prev,- now_day,- now_ms,- ) {- LeafMergeOutcome::Merged {- record,- transition,- deadline_ms,- } => {- counter!(SEED_TILES_APPLIED_TOTAL, "variant" => record.state.variant().as_str())- .increment(1);- let key = prefix.behavioral_key(lsk);- application.leaves.push(FoldedLeaf {- leaf_state_key: lsk,- person_id: person,- in_cohort: leaf_membership(Some(&record.state), meta),- minted_transition: transition.is_some(),- });- application.staged.put::<Behavioral>(&key, &record.encode());- if let Some(transition) = transition {- application.transitions.push(transition);+ LeafMergeOutcome::Unchanged { .. } => {+ tally.add(Outcome::TileUnchanged(meta.variant.as_str()));+ i64::MAX}- if deadline_ms != i64::MAX {- application.schedules.push((key, deadline_ms));+ LeafMergeOutcome::Dropped(reason) => {+ tally.add(Outcome::TileDropped(reason.as_str()));+ continue;}+ };+ let touch = touches.entry(key).or_insert(LeafTouch {+ team_id,+ filters: tile.filters,+ meta,+ run_id: tile.tile.run_id(),+ deadline_ms,+ });+ touch.run_id = tile.tile.run_id();+ if deadline_ms != i64::MAX {+ touch.deadline_ms = deadline_ms;}- LeafMergeOutcome::Unchanged { record } => {- counter!(SEED_TILES_UNCHANGED_TOTAL, "variant" => meta.variant.as_str())- .increment(1);- application.leaves.push(FoldedLeaf {- leaf_state_key: lsk,- person_id: person,- in_cohort: leaf_membership(Some(&record.state), meta),- minted_transition: false,- });- }- LeafMergeOutcome::Dropped(reason) => {- counter!(SEED_TILES_DROPPED_TOTAL, "reason" => reason.as_str()).increment(1);- }+ // Merged and Unchanged alike, so a crash between the two commits self-heals on replay:+ // the replayed run mints no transition, but the leaf's folded truth still diffs against+ // what downstream was told. Here, in offset order, so the person's provenance is the+ // last seed that touched them rather than the last leaf in key order.+ recompose.touch(team_id, tile.person, tile.tile.run_id(), lsk);}}- application-}-pub(crate) fn tag_seed(changes: &mut [CohortMembershipChange], run_id: RunId) {- for change in changes {- change.origin = Some(ChangeOrigin::Seed);- change.run_id = Some(run_id);- }-}--/// Count stage-1 flips without deriving emissions, which the seed register diff owns.-pub(crate) fn count_stage1_transitions(filters: &TeamFilters, transitions: &[LeafTransition]) {- for transition in transitions {- if let Some(kind) = transition_metric_label(filters, transition) {- counter!(STAGE1_TRANSITIONS, "kind" => kind).increment(1);+ let mut records = StagedBatch::default();+ let mut leaves: BTreeMap<TeamId, Vec<FoldedLeaf>> = BTreeMap::new();+ let mut schedules = Vec::new();+ for (key, touch) in &touches {+ let slot = overlay+ .slot(key)+ .expect("every touch came from a slot the read pass keyed");+ let person_id = key.prefix.person_id;+ let in_cohort = leaf_membership(slot.current().map(|record| &record.state), touch.meta);+ // Net against the run-start read, not against the last seed: a run that enters and then+ // leaves the same leaf told downstream nothing.+ let minted_transition =+ leaf_membership(slot.before().map(|record| &record.state), touch.meta) != in_cohort;+ leaves.entry(touch.team_id).or_default().push(FoldedLeaf {+ leaf_state_key: key.lsk,+ person_id,+ in_cohort,+ minted_transition,+ run_id: touch.run_id,+ });+ if let Some(record) = slot.advanced() {+ records.put::<Behavioral>(key, &record.encode());+ if touch.deadline_ms != i64::MAX {+ schedules.push((*key, touch.deadline_ms));+ }}- if filters- .by_lsk_to_single_leaf_cohorts- .get(&transition.leaf_state_key)- .is_none_or(Vec::is_empty)- && !filters- .by_lsk_to_composable_cohorts- .contains_key(&transition.leaf_state_key)- {- counter!(OUTPUT_TRANSITIONS_UNMAPPED, "reason" => "no_emitting_cohort").increment(1);+ if minted_transition {+ let kind = if in_cohort {+ TransitionKind::Entered+ } else {+ TransitionKind::Left+ };+ let transition = LeafTransition {+ team_id: touch.team_id,+ leaf_state_key: key.lsk,+ person_id,+ condition_hash: touch.meta.condition_hash,+ kind,+ };+ // Stage-1 flips, not emissions: the register diff owns what downstream is told.+ record_stage1_transition(&mut tally, touch.filters, &transition);}}-}-/// Advance the seed tracker past `offset`. A mark beyond the dispatch ceiling is capped and counted.-pub(crate) fn mark_processed(tracker: &OffsetTracker, partition_id: u16, offset: i64) {- if let MarkOutcome::CappedAheadOfDispatch =- tracker.mark_processed(partition_id as i32, offset + 1)- {- counter!(COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH).increment(1);- warn!(- partition_id,- next_offset = offset + 1,- "seed offset mark exceeded the dispatch ceiling and was capped (F1 invariant violation)",- );+ Folded {+ span,+ records,+ leaves,+ recompose,+ schedules,+ re_keys: ReKeys::Tiles(re_keys),+ tally,}}-/// Pin the seed commit floor at the failed offset so Kafka redelivers it; emit-/// [`SEED_HELD_OFFSET_GAUGE`] so the stall is visible.-pub(crate) fn hold(tracker: &OffsetTracker, partition_id: u16, offset: i64) {- let floor = tracker.hold(partition_id as i32, offset);- gauge!(SEED_HELD_OFFSET_GAUGE, "partition" => partition_id.to_string()).set(floor as f64);-}-#[cfg(test)]// Tests seed and assert against `CohortStore` directly, the sanctioned direct-store surface.#[allow(clippy::disallowed_methods)]mod tests {- use std::collections::BTreeMap;+ use std::collections::BTreeSet;+ use std::sync::Arc;use chrono_tz::America::New_York;+ use chrono_tz::Etc::GMTPlus12;+ use chrono_tz::Pacific::Kiritimati;use chrono_tz::UTC;- use metrics_exporter_prometheus::PrometheusBuilder;use proptest::prelude::*;use serde_json::{json, Value};use tempfile::TempDir;@@ -1003,45 +823,33 @@ mod tests {SeedTile,};- use crate::consumers::seeds::SeedSkipReason;+ use crate::consumers::seeds::{SeedSkipReason, SeedWork};+ use crate::filters::manager::CatalogHandle;use crate::filters::{CohortId, FilterCatalog, TeamFiltersBuilder};use crate::merge::transfer::Tombstone;use crate::partitions::partitioner::{partition_of, COHORT_PARTITION_COUNT};+ use crate::partitions::OffsetTracker;use crate::producer::{- CaptureReconcileMarkerSink, CaptureSeedTileSink, CaptureSink, MembershipStatus,+ CaptureReconcileMarkerSink, CaptureSeedTileSink, CaptureSink, ChangeOrigin,+ CohortMembershipChange, MembershipSink, MembershipStatus,};use crate::stage1::state::AppliedOffsets;use crate::stage2::state::Stage2State;use crate::store::{- CohortStore, OffloadConfig, OffloadMode, Stage2Key, StoreConfig, TombstoneKey,+ CohortStore, OffloadConfig, OffloadMode, Stage2Key, StoreConfig, StoreHandle, TombstoneKey,};+ use crate::sweep::EvictionQueue;use crate::workers::event_path::{process_event_gated, EventNameGating};+ use crate::workers::merge_path::MergeWorkerDeps;+ use crate::workers::reconcile::ReconcileQueue;+ use crate::workers::seed_apply::handle_seed_groups;+ use crate::workers::seed_run::{group_seeds, row_weight, RunBudget, SeedOffset};use super::*;const TEAM: TeamId = TeamId(7);- #[test]- fn an_unmapped_seed_transition_keeps_its_diagnostic() {- let recorder = PrometheusBuilder::new().build_recorder();- let handle = recorder.handle();- let filters = build_filters(Vec::new(), UTC);- let transition = LeafIdentity {- team_id: TEAM,- lsk: LeafStateKey([0xEE; 16]),- person_id: Uuid::from_u128(1),- condition_hash: [0xDD; 16],- }- .transition(TransitionKind::Entered);-- metrics::with_local_recorder(&recorder, || {- count_stage1_transitions(&filters, &[transition]);- });-- assert!(handle- .render()- .contains("output_transitions_unmapped_total{reason=\"no_emitting_cohort\"} 1"));- }+ const OTHER_TEAM: TeamId = TeamId(8);const HASH: [u8; 16] = *b"0123456789abcdef";/// A fixed "now": 2026-06-15 12:00:00 UTC.const NOW_MS: i64 = 1_781_524_800_000;@@ -1105,7 +913,7 @@ mod tests {identity(),tile_day,count(n),- prev,+ prev.as_ref(),now_day(),NOW_MS,)@@ -1509,7 +1317,7 @@ mod tests {identity(),now_day - offset,count(n),- prev.clone(),+ prev.as_ref(),now_day,now_ms,);@@ -1549,7 +1357,7 @@ mod tests {identity(),today - offset,count(n),- prev.clone(),+ prev.as_ref(),today,now_ms,) {@@ -1609,7 +1417,7 @@ mod tests {identity(),now_day() - offset,count(n),- settled.clone(),+ settled.as_ref(),now_day(),NOW_MS,);@@ -1645,7 +1453,7 @@ mod tests {identity(),now_day() - offset,count(n),- settled.clone(),+ settled.as_ref(),now_day(),NOW_MS,);@@ -1682,11 +1490,25 @@ mod tests {json!(["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11])}+ const PERSON_HASH: &str = "fedcba9876543210";++ fn person_leaf_json() -> 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 single_leaf_json(window_days: i64) -> Value {+ single_leaf_json_with("0123456789abcdef", window_days)+ }++ fn single_leaf_json_with(condition_hash: &str, window_days: i64) -> Value {json!({"type": "behavioral", "value": "performed_event", "key": "$pageview","time_value": window_days, "time_interval": "day",- "conditionHash": "0123456789abcdef",+ "conditionHash": condition_hash,"bytecode": behavioral_bytecode(),})}@@ -1706,9 +1528,17 @@ mod tests {}fn build_filters(cohorts: Vec<(i32, Value)>, tz: chrono_tz::Tz) -> TeamFilters {+ build_filters_for(TEAM, cohorts, tz)+ }++ fn build_filters_for(+ team: TeamId,+ cohorts: Vec<(i32, Value)>,+ tz: chrono_tz::Tz,+ ) -> TeamFilters {let mut builder = TeamFiltersBuilder::default();for (id, filters) in cohorts {- builder.add_cohort(CohortId(id), TEAM, &filters).unwrap();+ builder.add_cohort(CohortId(id), team, &filters).unwrap();}builder.freeze(tz)}@@ -1868,8 +1698,12 @@ mod tests {// ---- shell tests: handle_seed against a temp store ----fn tile_for(person: Uuid, day: DayIdx, n: u32) -> SeedTile {+ tile_for_team(TEAM, person, day, n)+ }++ fn tile_for_team(team: TeamId, person: Uuid, day: DayIdx, n: u32) -> SeedTile {SeedTile::new(- TEAM,+ team,person,ConditionHash::parse("0123456789abcdef").unwrap(),count(n),@@ -1880,6 +1714,32 @@ mod tests {)}+ fn tile_from_run(person: Uuid, condition_hash: &str, run: u128, day: DayIdx) -> SeedTile {+ SeedTile::new(+ TEAM,+ person,+ ConditionHash::parse(condition_hash).unwrap(),+ count(1),+ day,+ SChunkMs(1_700_000_000_000),+ RunId(Uuid::from_u128(run)),+ ClaimEpoch(1),+ )+ }++ fn person_seed_for(person: Uuid) -> PersonSeed {+ PersonSeed::new(+ TEAM,+ person,+ vec![ConditionHash::parse(PERSON_HASH).unwrap()],+ vec![ConditionHash::parse(PERSON_HASH).unwrap()],+ cohort_core::seed::ScannedAtMs(chrono::Utc::now().timestamp_millis()),+ RunId(Uuid::from_u128(0xBF)),+ ClaimEpoch(1),+ )+ .unwrap()+ }+fn reconcile_for(cohort_id: i32, run_id: u128) -> ReconcileTile {ReconcileTile::new(TEAM,@@ -1914,6 +1774,16 @@ mod tests {Self::with_sink(cohorts, CaptureSink::new(), CaptureSeedTileSink::new())}+ /// The same cohort shape under two teams, so a run can span them.+ fn with_two_teams(cohorts: Vec<(i32, Value)>) -> Self {+ let mut shell = Self::new(cohorts.clone());+ shell.catalog = Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([+ (TEAM, build_filters_for(TEAM, cohorts.clone(), UTC)),+ (OTHER_TEAM, build_filters_for(OTHER_TEAM, cohorts, New_York)),+ ])));+ shell+ }+fn with_sink(cohorts: Vec<(i32, Value)>,sink: CaptureSink,@@ -1980,6 +1850,7 @@ mod tests {..crate::workers::ReconcileDeps::default()},person_seed: crate::workers::PersonSeedDeps::default(),+ seed_budget: crate::workers::seed_run::RunBudget::default(),};let reconcile_queue =ReconcileQueue::new(0, deps.reconcile.backlog.clone(), handle.clone());@@ -2000,23 +1871,43 @@ mod tests {}}+ /// Apply one seed as a run of one, which is what a channel batch of one seed becomes.async fn run(&mut self, partition_id: u16, work: SeedWork, offset: i64) {+ self.run_batch(partition_id, vec![(work, offset)]).await;+ }++ /// Apply a channel batch's worth of seeds the way the worker does: group them into runs,+ /// then apply each group in order.+ async fn run_batch(&mut self, partition_id: u16, seeds: Vec<(SeedWork, i64)>) {+ let max = seeds.iter().map(|(_, offset)| *offset).max().unwrap();self.deps.seed_tracker- .mark_dispatched(partition_id as i32, offset + 1);+ .mark_dispatched(partition_id as i32, max + 1);let sink = self.membership.clone();- let last_updated = self.clock.next();- handle_seed(+ let snapshot = self.catalog.load();+ let deps = ApplyDeps {partition_id,- &self.handle,- &self.catalog,- &sink,- &self.deps,+ handle: &self.handle,+ catalog: &snapshot,+ sink: &sink,+ merge: &self.deps,+ };+ let admitted: Vec<Admitted<SeedWork>> = seeds+ .into_iter()+ .map(|(work, offset)| Admitted {+ work,+ offset: SeedOffset(offset),+ })+ .collect();+ let groups = group_seeds(admitted, RunBudget::default(), |work| {+ row_weight(&snapshot, work)+ });+ handle_seed_groups(+ deps,&mut self.queue,&mut self.reconcile_queue,- &last_updated,- &work,- offset,+ &mut self.clock,+ groups,).await;}@@ -2251,6 +2142,555 @@ mod tests {);}+ // ---- runs of more than one seed ----++ /// A run of two tiles must reach the same state and the same output as the same two tiles in+ /// two runs. Without read-your-writes the second tile would fold against the run-start bytes+ /// and lose the first tile's day.+ #[tokio::test]+ async fn a_run_of_two_tiles_matches_the_same_tiles_applied_one_at_a_time() {+ let person = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16;+ let cohorts = vec![(1, wrap(vec![multiple_leaf_json(7, "gte", 2)]))];+ let day = today();++ let mut batched = Shell::new(cohorts.clone());+ batched+ .run_batch(+ partition_id,+ vec![+ (SeedWork::Tile(tile_for(person, day - 1, 1)), 0),+ (SeedWork::Tile(tile_for(person, day, 1)), 1),+ ],+ )+ .await;++ let mut serial = Shell::new(cohorts);+ serial+ .run(+ partition_id,+ SeedWork::Tile(tile_for(person, day - 1, 1)),+ 0,+ )+ .await;+ serial+ .run(partition_id, SeedWork::Tile(tile_for(person, day, 1)), 1)+ .await;++ let lsk = *batched+ .catalog+ .load()+ .team(TEAM)+ .unwrap()+ .by_lsk+ .keys()+ .next()+ .unwrap();+ let key = PersonPrefix::new(partition_id, TEAM.0 as u64, person).behavioral_key(lsk);+ assert_eq!(+ batched.store.get_behavioral(&key).unwrap(),+ serial.store.get_behavioral(&key).unwrap(),+ "the run folds to the same bytes as the seeds one at a time",+ );+ assert_eq!(+ downstream(&batched.sink.changes()),+ downstream(&serial.sink.changes()),+ "and downstream converges on the same membership",+ );+ assert_eq!(+ batched.sink.changes().len(),+ 1,+ "the run emits the net entry once, not once per tile",+ );+ assert_eq!(batched.committable(partition_id), Some(2));+ }++ #[tokio::test]+ async fn an_unchanged_later_tile_keeps_the_runs_eviction_deadline() {+ let person = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16;+ let mut shell = Shell::new(vec![(1, wrap(vec![multiple_leaf_json(7, "gte", 1)]))]);+ let day = today();++ shell+ .run_batch(+ partition_id,+ vec![+ (SeedWork::Tile(tile_for(person, day, 2)), 0),+ (SeedWork::Tile(tile_for(person, day, 1)), 1),+ ],+ )+ .await;++ assert_eq!(+ shell.queue.len(),+ 1,+ "the unchanged max-merge must not replace the earlier finite deadline",+ );+ }++ /// A run that enters and then leaves the same leaf told downstream nothing, so it must emit+ /// nothing and leave no register behind. Emitting the intermediate flip would make a run of+ /// two differ from a run of one over the same net state.+ #[tokio::test]+ async fn enter_then_leave_in_one_run_emits_nothing_and_writes_no_register() {+ let person = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16;+ let mut shell = Shell::new(vec![(1, wrap(vec![multiple_leaf_json(7, "gte", 2)]))]);+ let day = today();++ shell+ .run_batch(+ partition_id,+ vec![+ // Enters: two events on `day` meet `gte 2`.+ (SeedWork::Tile(tile_for(person, day, 2)), 0),+ // Leaves: a future-dated tile slides `day` out of the window and carries one.+ (SeedWork::Tile(tile_for(person, day + 8, 1)), 1),+ ],+ )+ .await;++ assert!(+ shell.sink.changes().is_empty(),+ "the net transition is none, so downstream hears nothing",+ );+ assert_eq!(+ shell.register(partition_id, person, 1),+ None,+ "and no register is written for a person downstream was never told about",+ );+ assert_eq!(shell.committable(partition_id), Some(2));+ }++ /// The same run against a register that says the person is in: the stored bit disagrees with+ /// the run's truth, so exactly one retraction goes out.+ #[tokio::test]+ async fn enter_then_leave_in_one_run_emits_once_over_a_lagging_register() {+ let person = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16;+ let mut shell = Shell::new(vec![(1, wrap(vec![multiple_leaf_json(7, "gte", 2)]))]);+ let day = today();+ shell+ .store+ .write_batch(|batch| {+ batch.put_stage2(+ &shell.register_key(partition_id, person, 1),+ &Stage2State {+ in_cohort: true,+ last_evaluated_at_ms: 1,+ }+ .encode(),+ )+ })+ .unwrap();++ shell+ .run_batch(+ partition_id,+ vec![+ (SeedWork::Tile(tile_for(person, day, 2)), 0),+ (SeedWork::Tile(tile_for(person, day + 8, 1)), 1),+ ],+ )+ .await;++ let changes = shell.sink.changes();+ assert_eq!(changes.len(), 1, "one retraction, not an entry and a leave");+ assert_eq!(changes[0].status, MembershipStatus::Left);+ assert!(!shell.register(partition_id, person, 1).unwrap().in_cohort);+ }++ /// A run either lands whole or replays whole: the hold pins the run's *lowest* offset, and the+ /// redelivery emits each change exactly once. A hold at `last` would commit past a tile that+ /// was never applied. The trailing skip is what makes the floor observable: later groups in the+ /// same channel batch still run and mark, and the hold is what keeps their marks from+ /// leapfrogging it.+ #[tokio::test]+ async fn a_held_run_holds_its_first_offset_and_the_replay_emits_each_change_once() {+ let alice = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &alice, COHORT_PARTITION_COUNT) as u16;+ let bob = (0x5EEEu128..)+ .map(Uuid::from_u128)+ .find(|p| partition_of(TEAM, p, COHORT_PARTITION_COUNT) as u16 == partition_id)+ .unwrap();+ let mut shell = Shell::with_sink(+ vec![(1, wrap(vec![single_leaf_json(7)]))],+ CaptureSink::failing_first(1),+ CaptureSeedTileSink::new(),+ );+ let batch = || {+ vec![+ (SeedWork::Tile(tile_for(alice, today(), 1)), 4),+ (SeedWork::Tile(tile_for(bob, today(), 1)), 5),+ (SeedWork::Skip(SeedSkipReason::UnknownKind), 6),+ ]+ };++ shell.run_batch(partition_id, batch()).await;++ assert!(shell.sink.changes().is_empty());+ assert_eq!(+ shell.committable(partition_id),+ Some(4),+ "the skip marked past the run, but the hold pins the floor at the run's first offset",+ );+ assert!(+ !shell.queue.is_empty(),+ "the schedules stay: the stage-1 rows they belong to are already durable",+ );++ shell.restart();+ shell.run_batch(partition_id, batch()).await;++ let changes = shell.sink.changes();+ assert_eq!(changes.len(), 2, "one entry per person, once");+ assert_eq!(+ downstream(&changes)+ .values()+ .filter(|status| **status == MembershipStatus::Entered)+ .count(),+ 2,+ );+ assert_eq!(shell.committable(partition_id), Some(7));+ }++ /// Records the seed tracker's committable offset at every produce, which is what a crash or a+ /// rebalance at that instant would have left committed.+ #[derive(Clone)]+ struct FloorProbeSink {+ inner: CaptureSink,+ tracker: Arc<OffsetTracker>,+ partition_id: u16,+ floors: Arc<std::sync::Mutex<Vec<Option<i64>>>>,+ }++ #[async_trait::async_trait]+ impl MembershipSink for FloorProbeSink {+ async fn produce(+ &self,+ changes: Vec<CohortMembershipChange>,+ ) -> Vec<Result<(), common_kafka::kafka_producer::KafkaProduceError>> {+ let floor = self+ .tracker+ .committable_offsets()+ .get(&(self.partition_id as i32))+ .copied();+ self.floors.lock().unwrap().push(floor);+ self.inner.produce(changes).await+ }+ }++ /// Groups' spans interleave: one open run per kind means a tile run can span offsets a person+ /// run in the same collection still owes. Marking per group would let the consumer commit past+ /// that person seed while it is still unapplied, and a crash in that window loses it for good.+ #[tokio::test]+ async fn no_offset_becomes_committable_while_the_collection_still_owes_a_seed() {+ let alice = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &alice, COHORT_PARTITION_COUNT) as u16;+ let bob = (0x5EEEu128..)+ .map(Uuid::from_u128)+ .find(|p| partition_of(TEAM, p, COHORT_PARTITION_COUNT) as u16 == partition_id)+ .unwrap();+ let mut shell = Shell::new(vec![+ (1, wrap(vec![single_leaf_json(7)])),+ (2, wrap(vec![person_leaf_json()])),+ ]);+ shell.deps.person_seed.enabled = true;+ let probe = FloorProbeSink {+ inner: shell.sink.clone(),+ tracker: shell.deps.seed_tracker.clone(),+ partition_id,+ floors: Arc::default(),+ };+ shell.membership = Arc::new(probe.clone());++ // Tiles at 0 and 2 straddle the person seed at 1, so the tile run's span covers an offset+ // the person run has not reached.+ shell+ .run_batch(+ partition_id,+ vec![+ (SeedWork::Tile(tile_for(alice, today(), 1)), 0),+ (SeedWork::Person(person_seed_for(bob)), 1),+ (SeedWork::Tile(tile_for(alice, today() - 1, 1)), 2),+ ],+ )+ .await;++ assert_eq!(+ shell.sink.changes().len(),+ 2,+ "one behavioral entry and one person entry",+ );+ let floors = probe.floors.lock().unwrap().clone();+ assert_eq!(floors.len(), 2, "one produce per group");+ assert!(+ floors.iter().all(Option::is_none),+ "an offset became committable mid-collection: {floors:?}",+ );+ assert_eq!(+ shell.committable(partition_id),+ Some(3),+ "and the whole collection commits once every group has run",+ );+ }++ /// A re-keyed seed has no other copy, so an ack vector shorter than the run's hand-offs must+ /// hold the run rather than read as a vacuous success.+ #[tokio::test]+ async fn a_short_rekey_ack_holds_the_whole_run() {+ let (p_old, partition_id, p_new) = cross_partition_pair();+ let other_old = (0xA11CEu128..)+ .map(Uuid::from_u128)+ .find(|p| {+ partition_of(TEAM, p, COHORT_PARTITION_COUNT) as u16 == partition_id && *p != p_old+ })+ .unwrap();+ let mut shell = Shell::new(vec![(1, wrap(vec![single_leaf_json(7)]))]);+ write_tombstone(&shell.store, partition_id, p_old, p_new);+ write_tombstone(&shell.store, partition_id, other_old, p_new);+ shell.deps.seed_tile_sink = Arc::new(EmptyAckSink);++ shell+ .run_batch(+ partition_id,+ vec![+ (SeedWork::Tile(tile_for(p_old, today(), 1)), 7),+ (SeedWork::Tile(tile_for(other_old, today(), 1)), 8),+ ],+ )+ .await;++ assert_eq!(+ shell.committable(partition_id),+ None,+ "a short ack vector must hold the run, never commit it",+ );+ }++ /// Every seed folds against its own team's catalog, and the register diff runs once per team.+ /// One catalog for the whole run would drop the other team's leaves.+ #[tokio::test]+ async fn a_multi_team_run_diffs_each_teams_registers_against_its_own_catalog() {+ let alice = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &alice, COHORT_PARTITION_COUNT) as u16;+ let bob = (0x5EEEu128..)+ .map(Uuid::from_u128)+ .find(|p| partition_of(OTHER_TEAM, p, COHORT_PARTITION_COUNT) as u16 == partition_id)+ .unwrap();+ let mut shell = Shell::with_two_teams(vec![(1, wrap(vec![single_leaf_json(7)]))]);++ shell+ .run_batch(+ partition_id,+ vec![+ (SeedWork::Tile(tile_for(alice, today(), 1)), 0),+ (+ SeedWork::Tile(tile_for_team(OTHER_TEAM, bob, today(), 1)),+ 1,+ ),+ ],+ )+ .await;++ let changes = shell.sink.changes();+ assert_eq!(changes.len(), 2, "both teams' single-leaf cohorts entered");+ assert_eq!(+ changes+ .iter()+ .map(|change| change.team_id)+ .collect::<BTreeSet<_>>(),+ BTreeSet::from([TEAM.0, OTHER_TEAM.0]),+ );+ assert!(shell.register(partition_id, alice, 1).unwrap().in_cohort);+ assert!(+ Stage2State::decode(+ &shell+ .store+ .get_stage2(&Stage2Key {+ partition_id,+ team_id: OTHER_TEAM.0 as u64,+ cohort_id: 1,+ person_id: bob,+ })+ .unwrap()+ .unwrap()+ )+ .unwrap()+ .in_cohort,+ "the other team's register lands under its own team id",+ );+ assert_eq!(shell.committable(partition_id), Some(2));+ }++ #[test]+ fn a_multi_team_fold_uses_each_teams_day_index() {+ let cohorts = vec![(1, wrap(vec![multiple_leaf_json(1, "gte", 1)]))];+ let late_filters = build_filters_for(TEAM, cohorts.clone(), Kiritimati);+ let early_filters = build_filters_for(OTHER_TEAM, cohorts, GMTPlus12);+ let hash = ConditionHash::parse("0123456789abcdef").unwrap();+ let late_lsk = late_filters.by_condition_to_lsk[&hash.as_bytes()][0];+ let early_lsk = early_filters.by_condition_to_lsk[&hash.as_bytes()][0];+ let late_person = Uuid::from_u128(1);+ let early_person = Uuid::from_u128(2);+ let partition_id = 0;+ let stamp = RunStamp {+ now_ms: NOW_MS,+ last_updated: "fixed".to_string(),+ };+ let early_day = day_idx_in_tz(stamp.now_ms, GMTPlus12);+ assert!(day_idx_in_tz(stamp.now_ms, Kiritimati) > early_day);+ let tile_day = early_day - 1;+ let late_prefix = PersonPrefix::new(partition_id, TEAM.0 as u64, late_person);+ let early_prefix = PersonPrefix::new(partition_id, OTHER_TEAM.0 as u64, early_person);+ let late_lsks = [late_lsk];+ let early_lsks = [early_lsk];+ let local = vec![+ LocalTile {+ tile: tile_for_team(TEAM, late_person, tile_day, 1),+ person: late_person,+ filters: &late_filters,+ lsks: &late_lsks,+ prefix: late_prefix,+ },+ LocalTile {+ tile: tile_for_team(OTHER_TEAM, early_person, tile_day, 1),+ person: early_person,+ filters: &early_filters,+ lsks: &early_lsks,+ prefix: early_prefix,+ },+ ];+ let keys = vec![+ late_prefix.behavioral_key(late_lsk),+ early_prefix.behavioral_key(early_lsk),+ ];+ let overlay = Overlay::from_read(ApplyStage::Read, keys, vec![None, None], |_| {+ Decoded::Corrupt+ })+ .unwrap();++ let folded = fold_tiles(+ OffsetSpan {+ first: SeedOffset(0),+ last: SeedOffset(1),+ },+ local,+ Vec::new(),+ overlay,+ &stamp,+ Tally::default(),+ );++ assert!(+ !folded.leaves.contains_key(&TEAM),+ "the late timezone has already elapsed the tile",+ );+ assert_eq!(+ folded.leaves[&OTHER_TEAM][0].person_id, early_person,+ "the early timezone still includes the tile",+ );+ assert!(folded.leaves[&OTHER_TEAM][0].in_cohort);+ }++ /// A composed change carries the run of the last seed that touched the person, in offset+ /// order. Picking it in leaf-key order would stamp whichever leaf happens to sort last, so the+ /// test runs both orders: one of them is the key order, and both must answer alike. The+ /// register diff's lagging pass walks the same leaves in key order after the fold, so it must+ /// not move the provenance either.+ #[tokio::test]+ async fn a_composed_change_carries_the_run_of_the_last_seed_by_offset() {+ const FIRST_HASH: &str = "0123456789abcdef";+ const SECOND_HASH: &str = "fedcba0123456789";+ let person = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16;+ // Each hash also backs a single-leaf cohort, so the register diff finds the person's rows+ // lagging (absent) and revisits their leaves after the fold has spoken.+ let cohorts = vec![+ (+ 1,+ wrap(vec![+ single_leaf_json_with(FIRST_HASH, 7),+ single_leaf_json_with(SECOND_HASH, 7),+ ]),+ ),+ (2, wrap(vec![single_leaf_json_with(FIRST_HASH, 7)])),+ (3, wrap(vec![single_leaf_json_with(SECOND_HASH, 7)])),+ ];++ for [earlier, later] in [[FIRST_HASH, SECOND_HASH], [SECOND_HASH, FIRST_HASH]] {+ let mut shell = Shell::new(cohorts.clone());+ shell+ .run_batch(+ partition_id,+ vec![+ (+ SeedWork::Tile(tile_from_run(person, earlier, 0xA, today())),+ 0,+ ),+ (+ SeedWork::Tile(tile_from_run(person, later, 0xB, today())),+ 1,+ ),+ ],+ )+ .await;++ let changes = shell.sink.changes();+ let composed: Vec<_> = changes+ .iter()+ .filter(|change| change.cohort_id == 1)+ .collect();+ assert_eq!(+ (changes.len(), composed.len()),+ (3, 1),+ "both single-leaf cohorts entered and the composed cohort flipped once",+ );+ assert_eq!(+ composed[0].run_id,+ Some(RunId(Uuid::from_u128(0xB))),+ "the later seed by offset owns the composed flip, whichever leaf sorts last",+ );+ }+ }++ /// `OffsetTracker::defer` panics on a second defer of one offset in a tenure. A held run+ /// followed by a reconcile must not turn its redelivery into that panic.+ #[tokio::test]+ async fn a_held_run_replayed_across_a_reconcile_seed_does_not_double_defer() {+ let person = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16;+ let mut shell = Shell::with_sink(+ vec![(1, wrap(vec![single_leaf_json(7)]))],+ CaptureSink::failing_first(1),+ CaptureSeedTileSink::new(),+ );+ shell.deps.reconcile.enabled = true;+ let batch = || {+ vec![+ (SeedWork::Tile(tile_for(person, today(), 1)), 4),+ (SeedWork::Reconcile(reconcile_for(1, 1)), 5),+ ]+ };++ shell.run_batch(partition_id, batch()).await;+ assert_eq!(shell.committable(partition_id), None);+ assert_eq!(shell.reconcile_queue.len(), 1);++ // A new tenure clears the deferral, then the whole batch is redelivered.+ shell.restart();+ shell.run_batch(partition_id, batch()).await;++ assert_eq!(shell.sink.changes().len(), 1);+ assert_eq!(shell.reconcile_queue.len(), 1);+ assert_eq!(+ shell.committable(partition_id),+ Some(5),+ "the reconcile still pins the floor at its own deferred offset",+ );+ }+/// A non-member downstream was never told about gets no register row: nothing downstream/// needs one, and a reconcile page has nothing to repair for it. The Unchanged replay is just/// as silent.diff --git a/rust/cohort-stream-processor/src/workers/seed_run.rs b/rust/cohort-stream-processor/src/workers/seed_run.rsnew file mode 100644index 000000000000..b04e1ced2bd2--- /dev/null+++ b/rust/cohort-stream-processor/src/workers/seed_run.rs@@ -0,0 +1,804 @@+//! Run boundaries for the batched seed apply: a channel batch's seeds become runs of one kind,+//! and each run reaches exactly one mark or one hold.+//!+//! Applying seeds one at a time costs one awaited produce per seed that flips anything, so a+//! worker spends its time waiting on Kafka instead of folding. A run amortizes that: one read+//! pass, one register diff, one stage-1 commit, one recompute, one produce round trip, one+//! stage-2 commit, one mark. This module owns only the boundaries; the pipeline lives in+//! [`seed_apply`](super::seed_apply) and the two folds with their seed kinds.+//!+//! Pure: no I/O, no clock.++use std::collections::HashMap;+use std::num::NonZeroUsize;++use cohort_core::seed::{ConditionHash, PersonSeed, ReconcileTile, SeedTile};+use uuid::Uuid;++use crate::consumers::seeds::{SeedSkipReason, SeedWork};+use crate::filters::reverse_index::TeamFilters;+use crate::filters::{FilterCatalog, TeamId};+use crate::stage1::key::LeafStateKey;++/// One message's offset on `cohort_stream_seed_events`. A newtype so the seed tracker can never be+/// handed another topic's offset.+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+pub(crate) struct SeedOffset(pub i64);++/// The offsets a run acts on: `first` is what a failure holds, `last` is what a success marks.+///+/// `first` is the run's *lowest* offset, not its leading one. The consumer delivers in offset+/// order, but a hold above the true minimum would pin the commit floor past a seed that was never+/// applied, so the span is derived from the items rather than assumed from delivery order.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) struct OffsetSpan {+ pub first: SeedOffset,+ pub last: SeedOffset,+}++/// One seed with the offset that must be marked or held for it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct Admitted<T> {+ pub work: T,+ pub offset: SeedOffset,+}++/// A non-empty run of one seed kind, applied as one unit. Construction is the only place emptiness+/// is checked, so [`span`](Self::span) can never be asked about a run with no offsets.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct SeedRun<T> {+ items: Vec<Admitted<T>>,+ span: OffsetSpan,+}++impl<T> SeedRun<T> {+ /// `None` for an empty run: a group with no offsets could neither mark nor hold.+ pub(crate) fn new(items: Vec<Admitted<T>>) -> Option<Self> {+ let first = items.iter().map(|item| item.offset).min()?;+ let last = items+ .iter()+ .map(|item| item.offset)+ .max()+ .expect("a run with a lowest offset has a highest one too");+ Some(Self {+ items,+ span: OffsetSpan { first, last },+ })+ }++ pub(crate) fn span(&self) -> OffsetSpan {+ self.span+ }++ pub(crate) fn len(&self) -> usize {+ self.items.len()+ }++ pub(crate) fn into_items(self) -> Vec<Admitted<T>> {+ self.items+ }+}++/// A channel batch's seeds, split so each group is applied by exactly one handler.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) enum SeedGroup {+ Tiles(SeedRun<SeedTile>),+ Persons(SeedRun<PersonSeed>),+ /// Control tiles stay single: admission defers one offset and orders one queue entry, which a+ /// run of them could not express.+ Reconcile(Admitted<ReconcileTile>),+ /// Consume-side skips stay single: each one commits its own offset and does no work.+ Skip(Admitted<SeedSkipReason>),+}++impl SeedGroup {+ /// The lowest offset this group acts on — the order groups are applied in.+ fn first_offset(&self) -> SeedOffset {+ match self {+ Self::Tiles(run) => run.span().first,+ Self::Persons(run) => run.span().first,+ Self::Reconcile(admitted) => admitted.offset,+ Self::Skip(admitted) => admitted.offset,+ }+ }+}++/// Which apply pipeline a run belongs to; also the `kind` metric label.+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+pub(crate) enum SeedKind {+ Tile,+ Person,+}++impl SeedKind {+ pub(crate) fn as_str(self) -> &'static str {+ match self {+ Self::Tile => "tile",+ Self::Person => "person",+ }+ }+}++/// Both ceilings on one run. `seeds` bounds messages; `rows` bounds the run's footprint, so a hash+/// resolving to many leaves, a leaf backing many cohorts, or a 1,024-hash person seed cannot make+/// a run arbitrarily heavy.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct RunBudget {+ /// Seeds per run. `1` restores the per-seed apply, which is the hatch if batching misbehaves.+ pub seeds: NonZeroUsize,+ /// Store rows per run, as [`row_weight`] weighs them. A run closes before the seed that would+ /// exceed it; a seed heavier than the whole budget still runs alone.+ pub rows: NonZeroUsize,+}++impl Default for RunBudget {+ /// Mirrors the `COHORT_SEED_APPLY_BATCH_MAX*` defaults, for deps built without explicit config.+ fn default() -> Self {+ Self {+ seeds: NonZeroUsize::new(256).expect("256 > 0"),+ rows: NonZeroUsize::new(4096).expect("4096 > 0"),+ }+ }+}++/// How much of a run one seed can occupy, against the catalog snapshot the run will fold with: one+/// unit per leaf it reaches, plus one per stage-2 register each of those leaves backs, plus the+/// person seed's own record row. Every per-run structure — the overlay, the folded leaves, the+/// recompose set, the register read, the membership output and its cascades — holds at most one+/// entry per unit, so the budget this feeds is a ceiling on all of them, not on the overlay alone.+///+/// Both kinds charge for a leaf that backs no register, because the fold still retains one entry+/// for it. A person seed carries up to 1,024 hashes, so charging only its registers would let a+/// full run of leaves that can emit nothing slip under the ceiling.+///+/// It is a ceiling on what a run retains and emits, not on the reads inside each composed+/// evaluation: those scale with that cohort's tree exactly as under the per-seed apply, and the+/// maintenance lane's permits are what meter them.+///+/// A seed the catalog cannot place weighs one, so a run of them is still bounded by the seed cap+/// rather than by nothing. Control and skip seeds weigh nothing: they are always their own group.+pub(crate) fn row_weight(catalog: &FilterCatalog, work: &SeedWork) -> usize {+ let rows = match work {+ SeedWork::Tile(tile) => catalog.team(tile.team_id()).map_or(0, |filters| {+ leaves_of(filters, tile.condition_hash())+ .map(|lsk| 1 + registers_backed_by(filters, lsk))+ .sum::<usize>()+ }),+ SeedWork::Person(seed) => catalog.team(seed.team_id()).map_or(0, |filters| {+ 1 + seed+ .evaluated()+ .iter()+ .flat_map(|&hash| leaves_of(filters, hash))+ .map(|lsk| 1 + registers_backed_by(filters, lsk))+ .sum::<usize>()+ }),+ SeedWork::Reconcile(_) | SeedWork::Skip(_) => return 0,+ };+ rows.max(1)+}++/// The leaves a condition hash resolves to: one per window the catalog keeps over it.+fn leaves_of(filters: &TeamFilters, hash: ConditionHash) -> impl Iterator<Item = &LeafStateKey> {+ filters+ .by_condition_to_lsk+ .get(&hash.as_bytes())+ .into_iter()+ .flatten()+}++/// The `cf_stage2` rows one leaf reaches for one person: one per single-leaf cohort the register+/// diff keys on it, one per composable cohort the recompute re-walks for it.+fn registers_backed_by(filters: &TeamFilters, lsk: &LeafStateKey) -> usize {+ let single = filters+ .by_lsk_to_single_leaf_cohorts+ .get(lsk)+ .map_or(0, Vec::len);+ let composable = filters+ .by_lsk_to_composable_cohorts+ .get(lsk)+ .map_or(0, Vec::len);+ single + composable+}++/// Split `seeds` into runs of one kind, in offset order, each within `budget` under `weigh`.+///+/// One open run per kind: a tile does not close the open person run and vice versa, so an+/// interleaved stream still forms full runs. A reconcile seed closes both open runs first because+/// it orders a queue entry; a skip has no durable effect and does not split them. A budget closes+/// only the run it bounds.+///+/// Runs apply in first-offset order, so two open runs could apply one person's seeds out of offset+/// order when both kinds touch them, and a composed cohort would then emit flips the per-seed+/// apply never emits. A seed joins its kind's open run only if that run starts above the other+/// kind's latest run for its person; otherwise it starts a new run. Different persons keep+/// batching, which is the ordinary shape.+///+/// Residue: a tombstone redirects a seed to the merge survivor, and routing runs after grouping, so+/// two seeds that meet only on the survivor are not seen to share a person here. That window is a+/// straggler seed for a person merged mid-backfill, and it degrades to the reorder above, not to a+/// wrong final membership.+///+/// Pure and total: every input seed lands in exactly one group, groups are emitted in the order of+/// their first offset, and offset order is preserved within each kind.+pub(crate) fn group_seeds(+ seeds: Vec<Admitted<SeedWork>>,+ budget: RunBudget,+ weigh: impl Fn(&SeedWork) -> usize,+) -> Vec<SeedGroup> {+ let mut groups = Vec::new();+ let mut tiles = OpenRun::new(SeedGroup::Tiles);+ let mut persons = OpenRun::new(SeedGroup::Persons);++ for Admitted { work, offset } in seeds {+ let weight = weigh(&work);+ match work {+ SeedWork::Tile(tile) => {+ let person = (tile.team_id(), tile.person_id());+ let other_kind_run_start = persons.run_start_for(person);+ tiles.admit(+ Admitted { work: tile, offset },+ person,+ other_kind_run_start,+ weight,+ budget,+ &mut groups,+ );+ }+ SeedWork::Person(seed) => {+ let person = (seed.team_id(), seed.person_id());+ let other_kind_run_start = tiles.run_start_for(person);+ persons.admit(+ Admitted { work: seed, offset },+ person,+ other_kind_run_start,+ weight,+ budget,+ &mut groups,+ );+ }+ SeedWork::Reconcile(tile) => {+ tiles.close(&mut groups);+ persons.close(&mut groups);+ groups.push(SeedGroup::Reconcile(Admitted { work: tile, offset }));+ }+ SeedWork::Skip(reason) => {+ groups.push(SeedGroup::Skip(Admitted {+ work: reason,+ offset,+ }));+ }+ }+ }++ tiles.close(&mut groups);+ persons.close(&mut groups);+ // Two open runs close at the end in kind order, which is not offset order. Sorting restores the+ // contract callers read the groups under; it does not make a group's span disjoint from its+ // neighbours', which is why the mark is buffered rather than published per group.+ groups.sort_by_key(SeedGroup::first_offset);+ groups+}++/// One person of one team, the unit both seed kinds order against: stage-1 rows, stage-2 registers+/// and cascades are all keyed on it, so runs that share no person cannot observe each other.+type TeamPerson = (TeamId, Uuid);++/// A run of one kind still accepting seeds, with the row weight it has admitted.+struct OpenRun<T> {+ into: fn(SeedRun<T>) -> SeedGroup,+ items: Vec<Admitted<T>>,+ rows: usize,+ /// Per person, the first offset of the latest run of this kind that took them. Kept across+ /// closes: a closed run still applies at its own first offset.+ run_start_by_person: HashMap<TeamPerson, SeedOffset>,+}++impl<T> OpenRun<T> {+ fn new(into: fn(SeedRun<T>) -> SeedGroup) -> Self {+ Self {+ into,+ items: Vec::new(),+ rows: 0,+ run_start_by_person: HashMap::new(),+ }+ }++ /// The start of the latest run of this kind for this person.+ fn run_start_for(&self, person: TeamPerson) -> Option<SeedOffset> {+ self.run_start_by_person.get(&person).copied()+ }++ /// Admit one seed. The run closes first when the other kind's run for this person starts above+ /// it or the weight would overflow the row budget, and after when the seed count fills. An+ /// empty run always admits, so a seed heavier than the whole budget still runs alone.+ fn admit(+ &mut self,+ item: Admitted<T>,+ person: TeamPerson,+ other_kind_run_start: Option<SeedOffset>,+ weight: usize,+ budget: RunBudget,+ groups: &mut Vec<SeedGroup>,+ ) {+ let start = self.items.first().map(|first| first.offset);+ let reorders = start+ .zip(other_kind_run_start)+ .is_some_and(|(start, since)| start < since);+ let overflows = self.rows.saturating_add(weight) > budget.rows.get();+ if reorders || (overflows && !self.items.is_empty()) {+ self.close(groups);+ }+ self.items.push(item);+ self.rows = self.rows.saturating_add(weight);+ let start = self.items[0].offset;+ self.run_start_by_person.insert(person, start);+ if self.items.len() >= budget.seeds.get() {+ self.close(groups);+ }+ }++ /// Close the run, if non-empty, as one group.+ fn close(&mut self, groups: &mut Vec<SeedGroup>) {+ let Some(run) = SeedRun::new(std::mem::take(&mut self.items)) else {+ return;+ };+ self.rows = 0;+ groups.push((self.into)(run));+ }+}++#[cfg(test)]+mod tests {+ use std::num::NonZeroU32;++ use cohort_core::seed::{+ BehavioralShapeHash, ClaimEpoch, ConditionHash, ReconcileScope, RunId, SChunkMs,+ ScannedAtMs,+ };+ use serde_json::{json, Value};+ use uuid::Uuid;++ use crate::filters::{CohortId, TeamFiltersBuilder, TeamId};++ use super::*;++ const TEAM: TeamId = TeamId(7);+ const BEHAVIORAL: &str = "0123456789abcdef";+ const PERSON: &str = "person0000000001";++ fn hash(value: &str) -> ConditionHash {+ ConditionHash::parse(value).unwrap()+ }++ fn tile() -> SeedTile {+ tile_with(TEAM, BEHAVIORAL)+ }++ fn tile_for(person: Uuid) -> SeedTile {+ SeedTile::new(+ TEAM,+ person,+ hash(BEHAVIORAL),+ NonZeroU32::new(1).unwrap(),+ 20_614,+ SChunkMs(1),+ RunId(Uuid::nil()),+ ClaimEpoch(1),+ )+ }++ fn tile_with(team: TeamId, condition_hash: &str) -> SeedTile {+ SeedTile::new(+ team,+ Uuid::from_u128(1),+ hash(condition_hash),+ NonZeroU32::new(1).unwrap(),+ 20_614,+ SChunkMs(1),+ RunId(Uuid::nil()),+ ClaimEpoch(1),+ )+ }++ fn person_seed(evaluated: &[&str]) -> PersonSeed {+ person_seed_for(Uuid::from_u128(2), evaluated)+ }++ fn person_seed_for(person: Uuid, evaluated: &[&str]) -> PersonSeed {+ PersonSeed::new(+ TEAM,+ person,+ evaluated.iter().copied().map(hash).collect(),+ vec![],+ ScannedAtMs(1),+ RunId(Uuid::nil()),+ ClaimEpoch(1),+ )+ .unwrap()+ }++ fn reconcile() -> ReconcileTile {+ ReconcileTile::new(+ TEAM,+ CohortId(1),+ ReconcileScope::Behavioral(BehavioralShapeHash::parse(BEHAVIORAL).unwrap()),+ RunId(Uuid::nil()),+ )+ }++ fn admitted(work: SeedWork, offset: i64) -> Admitted<SeedWork> {+ Admitted {+ work,+ offset: SeedOffset(offset),+ }+ }++ /// The offsets each group would act on: `(first, last)` per group, in group order.+ fn spans(groups: &[SeedGroup]) -> Vec<(i64, i64)> {+ groups+ .iter()+ .map(|group| match group {+ SeedGroup::Tiles(run) => (run.span().first.0, run.span().last.0),+ SeedGroup::Persons(run) => (run.span().first.0, run.span().last.0),+ SeedGroup::Reconcile(admitted) => (admitted.offset.0, admitted.offset.0),+ SeedGroup::Skip(admitted) => (admitted.offset.0, admitted.offset.0),+ })+ .collect()+ }++ fn budget(seeds: usize, rows: usize) -> RunBudget {+ RunBudget {+ seeds: NonZeroUsize::new(seeds).unwrap(),+ rows: NonZeroUsize::new(rows).unwrap(),+ }+ }++ /// Group under the seed cap alone: every seed weighs one and the row budget is unbounded.+ fn group_by_count(seeds: Vec<Admitted<SeedWork>>, max_seeds: usize) -> Vec<SeedGroup> {+ group_seeds(seeds, budget(max_seeds, usize::MAX), |_| 1)+ }++ fn tiles(offsets: std::ops::Range<i64>) -> Vec<Admitted<SeedWork>> {+ offsets+ .map(|offset| admitted(SeedWork::Tile(tile()), offset))+ .collect()+ }++ /// Reconcile must stay behind preceding data, while a no-op skip must not fragment a data run.+ #[test]+ fn reconcile_closes_both_runs_while_skip_stays_nonbarrier() {+ let groups = group_by_count(+ vec![+ admitted(SeedWork::Tile(tile()), 0),+ admitted(SeedWork::Person(person_seed(&[PERSON])), 1),+ admitted(SeedWork::Reconcile(reconcile()), 2),+ admitted(SeedWork::Tile(tile()), 3),+ admitted(SeedWork::Skip(SeedSkipReason::UnknownKind), 4),+ admitted(SeedWork::Tile(tile()), 5),+ ],+ 256,+ );++ assert_eq!(+ spans(&groups),+ vec![(0, 0), (1, 1), (2, 2), (3, 5), (4, 4)],+ "reconcile closes both runs, while skip leaves the tile run open",+ );+ assert!(matches!(groups[0], SeedGroup::Tiles(_)));+ assert!(matches!(groups[1], SeedGroup::Persons(_)));+ assert!(matches!(groups[2], SeedGroup::Reconcile(_)));+ assert!(matches!(groups[3], SeedGroup::Tiles(ref run) if run.len() == 2));+ assert!(matches!(groups[4], SeedGroup::Skip(_)));+ }++ /// An interleaved tile/person stream degraded to runs of one under #93822's kind-change close,+ /// which is the whole win lost. `tile()` and `person_seed()` name different persons, so the+ /// two runs cannot observe each other and both stay open.+ #[test]+ fn an_interleaved_stream_of_distinct_persons_still_forms_one_run_per_kind() {+ let groups = group_by_count(+ vec![+ admitted(SeedWork::Tile(tile()), 0),+ admitted(SeedWork::Person(person_seed(&[PERSON])), 1),+ admitted(SeedWork::Tile(tile()), 2),+ admitted(SeedWork::Person(person_seed(&[PERSON])), 3),+ ],+ 256,+ );++ assert_eq!(groups.len(), 2, "one run per kind, not four runs of one");+ assert!(matches!(groups[0], SeedGroup::Tiles(ref run) if run.len() == 2));+ assert!(matches!(groups[1], SeedGroup::Persons(ref run) if run.len() == 2));+ assert_eq!(+ spans(&groups),+ vec![(0, 2), (1, 3)],+ "each kind keeps its own offset order",+ );+ }++ /// Two open runs apply in first-offset order, so a person both kinds touch would have the+ /// person seed at offset 2 applied before the tile at offset 1. Both leaves feed one composed+ /// cohort, so that reorder emits an entry and a retraction the per-seed apply never emits.+ #[test]+ fn a_person_both_kinds_touch_keeps_every_seed_in_offset_order() {+ let alice = Uuid::from_u128(11);+ let groups = group_by_count(+ vec![+ admitted(SeedWork::Person(person_seed_for(alice, &[PERSON])), 0),+ admitted(SeedWork::Tile(tile_for(alice)), 1),+ admitted(SeedWork::Person(person_seed_for(alice, &[PERSON])), 2),+ ],+ 256,+ );++ assert_eq!(+ spans(&groups),+ vec![(0, 0), (1, 1), (2, 2)],+ "no group's span crosses another's",+ );+ }++ /// A run that starts above the other kind's run for its persons applies after it, so it+ /// batches.+ #[test]+ fn a_run_starting_above_the_other_kinds_run_batches_its_shared_persons() {+ let alice = Uuid::from_u128(11);+ let bob = Uuid::from_u128(12);+ let groups = group_by_count(+ vec![+ admitted(SeedWork::Person(person_seed_for(alice, &[PERSON])), 0),+ admitted(SeedWork::Person(person_seed_for(bob, &[PERSON])), 1),+ admitted(SeedWork::Tile(tile_for(bob)), 2),+ admitted(SeedWork::Tile(tile_for(alice)), 3),+ ],+ 256,+ );++ assert_eq!(+ spans(&groups),+ vec![(0, 1), (2, 3)],+ "the tile run starts above the person run, so nothing closes",+ );+ }++ /// A closed run still applies at its own first offset, so forgetting its persons on close would+ /// let the tile at 3 join the run at 0 and apply before the person seeds at 1 and 2.+ #[test]+ fn a_person_admitted_by_a_closed_run_of_the_other_kind_still_orders_the_seed() {+ let alice = Uuid::from_u128(11);+ let bob = Uuid::from_u128(12);+ let groups = group_by_count(+ vec![+ admitted(SeedWork::Tile(tile_for(bob)), 0),+ admitted(SeedWork::Person(person_seed_for(alice, &[PERSON])), 1),+ admitted(SeedWork::Person(person_seed_for(alice, &[PERSON])), 2),+ admitted(SeedWork::Tile(tile_for(alice)), 3),+ ],+ 2,+ );++ assert_eq!(+ spans(&groups),+ vec![(0, 0), (1, 2), (3, 3)],+ "the tile starts above the closed person run",+ );+ }++ #[test]+ fn a_run_longer_than_the_cap_splits_into_capped_groups() {+ assert_eq!(+ spans(&group_by_count(tiles(0..7), 3)),+ vec![(0, 2), (3, 5), (6, 6)]+ );+ }++ /// The zero-cost hatch: `COHORT_SEED_APPLY_BATCH_MAX=1` must reproduce the per-seed apply.+ #[test]+ fn a_cap_of_one_yields_one_group_per_seed() {+ assert_eq!(+ spans(&group_by_count(tiles(0..3), 1)),+ vec![(0, 0), (1, 1), (2, 2)]+ );+ }++ #[test]+ fn an_empty_batch_yields_no_groups() {+ assert!(group_by_count(Vec::new(), 256).is_empty());+ }++ /// The budget bounds what a run expands to, so it has to be checked before a seed is admitted:+ /// applied after, every run would overshoot by one seed's whole leaf set.+ #[test]+ fn a_run_closes_before_the_seed_that_would_exceed_the_row_budget() {+ let groups = group_seeds(tiles(0..5), budget(256, 10), |_| 4);++ assert_eq!(spans(&groups), vec![(0, 1), (2, 3), (4, 4)]);+ }++ /// A seed heavier than the whole budget can never fit, so an empty run must still admit it:+ /// refusing would leave the seed neither marked nor held, and the partition wedged behind it.+ #[test]+ fn a_seed_heavier_than_the_whole_budget_still_forms_a_run_of_one() {+ let groups = group_seeds(tiles(0..3), budget(256, 10), |_| 1000);++ assert_eq!(spans(&groups), vec![(0, 0), (1, 1), (2, 2)]);+ }++ /// A budget on one kind must not close the other kind's open run: it would undo the+ /// interleaving win without bounding anything the other run reads.+ #[test]+ fn a_budget_closes_only_the_run_it_bounds() {+ let groups = group_seeds(+ vec![+ admitted(SeedWork::Person(person_seed(&[PERSON])), 0),+ admitted(SeedWork::Tile(tile()), 1),+ admitted(SeedWork::Tile(tile()), 2),+ admitted(SeedWork::Person(person_seed(&[PERSON])), 3),+ ],+ budget(2, usize::MAX),+ |_| 1,+ );++ assert!(matches!(groups[0], SeedGroup::Persons(ref run) if run.len() == 2));+ assert!(matches!(groups[1], SeedGroup::Tiles(ref run) if run.len() == 2));+ assert_eq!(+ spans(&groups),+ vec![(0, 3), (1, 2)],+ "groups are emitted in first-offset order even when the budget closes one kind first",+ );+ }++ /// Callers apply groups in the order they come out, so the order has to be the offset order the+ /// consumer delivered in — not the order the two open runs happened to close in.+ #[test]+ fn groups_are_emitted_in_first_offset_order() {+ let groups = group_seeds(+ vec![+ admitted(SeedWork::Person(person_seed(&[PERSON])), 0),+ admitted(SeedWork::Tile(tile()), 1),+ admitted(SeedWork::Person(person_seed(&[PERSON])), 2),+ admitted(SeedWork::Reconcile(reconcile()), 3),+ admitted(SeedWork::Tile(tile()), 4),+ ],+ budget(256, usize::MAX),+ |_| 1,+ );++ let firsts: Vec<i64> = spans(&groups).into_iter().map(|(first, _)| first).collect();+ let mut sorted = firsts.clone();+ sorted.sort_unstable();+ assert_eq!(+ firsts, sorted,+ "groups came out out of offset order: {firsts:?}"+ );+ }++ /// The weight is the run's footprint, not its leaf count: a leaf backing many cohorts costs a+ /// register read, a recompute, and an emission per cohort, and that is what the budget has to+ /// bound for a run's memory and output to stay finite.+ #[test]+ fn row_weight_counts_stage1_rows_plus_backed_registers_and_floors_at_one() {+ let behavioral = |condition_hash: &str, window_days: i64| {+ json!({+ "type": "behavioral", "value": "performed_event", "key": "$pageview",+ "time_value": window_days, "time_interval": "day",+ "conditionHash": condition_hash,+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],+ })+ };+ let person_property = json!({+ "type": "person", "key": "email", "value": "[email protected]", "operator": "exact",+ "conditionHash": PERSON,+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],+ });+ let cohort =+ |leaves: Vec<Value>| json!({ "properties": { "type": "AND", "values": leaves } });+ let mut builder = TeamFiltersBuilder::default();+ // Two windows over one condition hash: two leaves. Three single-leaf cohorts share the+ // 7-day one, a fourth keys on the 30-day one, and a composed cohort walks the 7-day one+ // together with the person leaf.+ for id in 1..=3 {+ builder+ .add_cohort(CohortId(id), TEAM, &cohort(vec![behavioral(BEHAVIORAL, 7)]))+ .unwrap();+ }+ builder+ .add_cohort(CohortId(4), TEAM, &cohort(vec![behavioral(BEHAVIORAL, 30)]))+ .unwrap();+ builder+ .add_cohort(CohortId(5), TEAM, &cohort(vec![person_property.clone()]))+ .unwrap();+ builder+ .add_cohort(+ CohortId(6),+ TEAM,+ &cohort(vec![behavioral(BEHAVIORAL, 7), person_property]),+ )+ .unwrap();+ let catalog = FilterCatalog::from_teams([(TEAM, builder.freeze(chrono_tz::UTC))]);++ assert_eq!(+ row_weight(&catalog, &SeedWork::Tile(tile_with(TEAM, BEHAVIORAL))),+ (1 + 3 + 1) + (1 + 1),+ "the 7-day leaf is its row, three single-leaf registers and one composed; the 30-day leaf its row and one register",+ );+ assert_eq!(+ row_weight(+ &catalog,+ &SeedWork::Tile(tile_with(TEAM, "no_such_cond0000"))+ ),+ 1,+ "a hash the catalog no longer resolves still weighs one",+ );+ assert_eq!(+ row_weight(&catalog, &SeedWork::Tile(tile_with(TeamId(99), BEHAVIORAL))),+ 1,+ "an unknown team still weighs one",+ );+ assert_eq!(+ row_weight(&catalog, &SeedWork::Person(person_seed(&[PERSON]))),+ 1 + (1 + 1 + 1),+ "a person seed is one record, then its leaf and the two registers that leaf backs",+ );+ assert_eq!(+ row_weight(+ &catalog,+ &SeedWork::Person(person_seed(&[BEHAVIORAL, PERSON])),+ ),+ 1 + (1 + 3 + 1) + (1 + 1) + (1 + 1 + 1),+ "every hash the seed evaluated counts, whatever the fold later drops",+ );+ assert_eq!(row_weight(&catalog, &SeedWork::Reconcile(reconcile())), 0);+ assert_eq!(+ row_weight(&catalog, &SeedWork::Skip(SeedSkipReason::UnknownKind)),+ 0,+ );+ }++ /// The fold keeps one entry per evaluated hash, not per register, and a person seed carries up+ /// to 1,024 hashes. Charging only registers would let a run of seeds whose leaves can emit+ /// nothing measure its seed count while retaining hash-count entries.+ #[test]+ fn a_leaf_that_backs_no_register_still_bounds_the_run() {+ // A ref-bearing cohort is excluded from composition while cascade is off, so its person+ // leaf is indexed but keys neither register map.+ let mut builder = TeamFiltersBuilder::default();+ builder+ .add_cohort(+ CohortId(1),+ TEAM,+ &json!({ "properties": { "type": "AND", "values": [+ {+ "type": "person", "key": "email", "value": "[email protected]", "operator": "exact",+ "conditionHash": PERSON,+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],+ },+ { "type": "cohort", "value": 99, "negation": false },+ ] } }),+ )+ .unwrap();+ let catalog = FilterCatalog::from_teams([(TEAM, builder.freeze(chrono_tz::UTC))]);++ assert_eq!(+ row_weight(&catalog, &SeedWork::Person(person_seed(&[PERSON]))),+ 1 + 1,+ "the record and the leaf the fold retains, with no register behind it",+ );++ let seeds: Vec<Admitted<SeedWork>> = (0..4)+ .map(|offset| admitted(SeedWork::Person(person_seed(&[PERSON])), offset))+ .collect();+ let groups = group_seeds(seeds, budget(256, 4), |work| row_weight(&catalog, work));++ assert_eq!(+ spans(&groups),+ vec![(0, 1), (2, 3)],+ "the row ceiling still splits a run that backs no register at all",+ );+ }++ #[test]+ fn an_empty_run_has_no_span_so_it_cannot_become_a_group() {+ assert!(SeedRun::<SeedTile>::new(Vec::new()).is_none());+ }+}diff --git a/rust/cohort-stream-processor/src/workers/stage2_path.rs b/rust/cohort-stream-processor/src/workers/stage2_path.rsindex 1a58ff0d2fab..6e3bed5beb78 100644--- a/rust/cohort-stream-processor/src/workers/stage2_path.rs+++ b/rust/cohort-stream-processor/src/workers/stage2_path.rs@@ -7,6 +7,7 @@use std::collections::{BTreeMap, BTreeSet, HashMap};+use cohort_core::seed::RunId;use metrics::counter;use uuid::Uuid;@@ -17,7 +18,7 @@ use crate::observability::metrics::{SEED_REGISTER_REPAIRS_TOTAL, STAGE2_COHORTS_EVALUATED, STAGE2_STATE_DECODE_ERROR,STAGE2_TRANSITIONS,};-use crate::producer::{CohortMembershipChange, MembershipStatus};+use crate::producer::{ChangeOrigin, CohortMembershipChange, MembershipStatus};use crate::stage1::key::LeafStateKey;use crate::stage1::person_record::PersonRecord;use crate::stage1::state::{Stage1State, StateVariant, StatefulRecord};@@ -85,11 +86,6 @@ impl Stage2Recompute {self.composed.add(other.composed);self.repairs.add(other.repairs);}-- /// Nothing to emit and nothing to commit.- pub(crate) fn is_empty(&self) -> bool {- self.changes.is_empty() && self.writes.is_empty()- }}/// Per-status flip counts, kept so [`Stage2Recompute::record_metrics`] can attribute each half of a@@ -230,22 +226,19 @@ pub(crate) async fn recompute_stage2(})}-/// One leaf a seed apply folded, with the membership its resulting state implies. The caller holds+/// One leaf a seed run folded, with the membership its resulting state implies. The caller holds/// that truth already, so the register diff never re-reads `cf_behavioral`.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub(crate) struct FoldedLeaf {pub leaf_state_key: LeafStateKey,pub person_id: Uuid,pub in_cohort: bool,- /// Whether stage 1 minted a transition for this leaf in this apply. Only the fold knows it, and- /// it is what separates an ordinary flip from a register repair in the metrics.+ /// Whether the run *net* flipped this leaf's membership against the state its read pass saw.+ /// Only the fold knows it, and it is what separates an ordinary flip from a register repair in+ /// the metrics. A run that enters then leaves the same leaf mints nothing.pub minted_transition: bool,-}--impl FoldedLeaf {- pub(crate) fn pair(self) -> (LeafStateKey, Uuid) {- (self.leaf_state_key, self.person_id)- }+ /// The run that last touched this leaf, stamped onto every change the diff emits for it.+ pub run_id: RunId,}/// What the single-leaf register diff decided for one apply.@@ -260,6 +253,14 @@ pub(crate) struct RegisterDiff {pub stage1_writes: Vec<(Stage2Key, Stage2State)>,}+impl RegisterDiff {+ /// Fold another team's diff in, so a multi-team run still commits and produces once.+ pub(crate) fn extend(&mut self, other: Self) {+ self.recompute.extend(other.recompute);+ self.stage1_writes.extend(other.stage1_writes);+ }+}+/// Derive each single-leaf cohort's membership change from the folded leaf's truth and the/// persisted register row, which on the seed paths records what downstream was last told.///@@ -307,19 +308,20 @@ pub(crate) async fn diff_single_leaf_registers(cohort_id: cohort_id.0 as u64,person_id: leaf.person_id,};- let previous = wanted.insert(- key,- WantedRegister {- team_id: tree.team_id.0,- cohort_id: *cohort_id,- in_cohort: leaf.in_cohort,- minted_transition: leaf.minted_transition,- },- );- // A single-leaf cohort resolves to one leaf, so one apply reaches each row once.+ let want = WantedRegister {+ team_id: tree.team_id.0,+ cohort_id: *cohort_id,+ in_cohort: leaf.in_cohort,+ minted_transition: leaf.minted_transition,+ run_id: leaf.run_id,+ };+ let previous = wanted.insert(key, want);+ // A single-leaf cohort resolves to one leaf, so one run reaches each row exactly once.+ // A duplicate is the overlay-dedup bug that would silently drop a net transition, and+ // this is its only guard — hence the whole-value compare rather than the bit alone.debug_assert!(- previous.is_none_or(|prior| prior.in_cohort == leaf.in_cohort),- "one apply folded {key:?} to two different memberships",+ previous.is_none_or(|prior| prior == want),+ "one run folded {key:?} to two different register verdicts",);}}@@ -329,15 +331,6 @@ pub(crate) async fn diff_single_leaf_registers(let keys: Vec<Stage2Key> = wanted.keys().copied().collect();let stored = handle.multi_get_stage2(keys, lane).await?;- // A short answer would zip one register's bytes onto another register's key and silently drop- // the tail's emissions.- if stored.len() != wanted.len() {- return Err(StoreError::ShortRead {- op: "multi_get_stage2",- asked: wanted.len(),- answered: stored.len(),- });- }let mut changes = Vec::new();let mut writes: Vec<(Stage2Key, Stage2State)> = Vec::new();@@ -400,8 +393,9 @@ pub(crate) async fn diff_single_leaf_registers(person_id: key.person_id.to_string(),last_updated: last_updated.to_string(),status,- origin: None,- run_id: None,+ // Stamped from the leaf, so only the composed half still needs `tag_seed`.+ origin: Some(ChangeOrigin::Seed),+ run_id: Some(want.run_id),});}@@ -420,11 +414,13 @@ pub(crate) async fn diff_single_leaf_registers(}/// One `(single-leaf cohort, person)` the fold decided, before its stored row is read.+#[derive(Clone, Copy, PartialEq, Eq)]struct WantedRegister {team_id: i32,cohort_id: CohortId,in_cohort: bool,minted_transition: bool,+ run_id: RunId,}fn membership_status(in_cohort: bool) -> MembershipStatus {@@ -873,6 +869,7 @@ mod tests {const PERSON_HASH: [u8; 16] = *b"fedcba9876543210";const TS: &str = "2026-05-26 12:34:56.789123";const EVENT_MS: i64 = 1_700_000_000_000;+ const RUN: RunId = RunId(Uuid::from_u128(0xBF));fn temp_store() -> (TempDir, CohortStore) {let dir = TempDir::new().unwrap();@@ -1433,6 +1430,7 @@ mod tests {person_id,in_cohort,minted_transition: false,+ run_id: RUN,}}@@ -1715,6 +1713,7 @@ mod tests {person_id: alice,in_cohort,minted_transition: minted,+ run_id: RUN,}],EVENT_MS,TS,@@ -1786,6 +1785,7 @@ mod tests {person_id: alice,in_cohort: stored,minted_transition: true,+ run_id: RUN,}],EVENT_MS,TS,@@ -1939,6 +1939,7 @@ mod tests {person_id: alice,in_cohort,minted_transition: minted,+ run_id: RUN,}],EVENT_MS,TS,diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rsindex 0e21c89e9c45..3394dad2e862 100644--- a/rust/cohort-stream-processor/src/workers/worker.rs+++ b/rust/cohort-stream-processor/src/workers/worker.rs@@ -16,6 +16,7 @@ use uuid::Uuid;use crate::cascade::{first_cascade, CascadeMessage};use crate::consumers::events::CohortStreamEvent;+use crate::consumers::seeds::SeedWork;use crate::filters::manager::CatalogHandle;use crate::filters::reverse_index::TeamFilters;use crate::filters::TeamId;@@ -48,7 +49,8 @@ use crate::workers::event_path::{use crate::workers::merge_gc::{handle_merge_gc, MergeGcCursor};use crate::workers::merge_path::{handle_apply, handle_merge, handle_redrive, MergeWorkerDeps};use crate::workers::reconcile::{handle_reconcile_drain, ReconcileQueue};-use crate::workers::seed_path::handle_seed;+use crate::workers::seed_apply::{handle_seed_groups, ApplyDeps};+use crate::workers::seed_run::{group_seeds, row_weight, Admitted, SeedOffset};use crate::workers::stage2_gc::{handle_stage2_orphan_gc, Stage2GcCursor};use crate::workers::stage2_path::compose_stage2;use crate::workers::sweep_callback::{sweep_evict, EvictionAction, SweepDropReason};@@ -182,7 +184,37 @@ async fn run_worker(// Set when a pre-arm flush fails: holds the whole batch's offset so Kafka replays it.let mut held = false;+ // Seeds accumulate so one run amortizes a produce round trip across many of them. Every+ // other arm closes the collection first, which keeps a seed's order against the messages+ // around it — a reconcile control seed still lands behind the data seeds that precede it.+ let mut seeds: Vec<Admitted<SeedWork>> = Vec::new();+for message in batch {+ if let ShuffleMessage::Seed { work, offset, .. } = message {+ seeds.push(Admitted {+ work: *work,+ offset: SeedOffset(offset),+ });+ continue;+ }+ if apply_seed_runs(+ partition_id,+ &handle,+ &catalog,+ &sink,+ &merge,+ &mut queue,+ &mut reconcile_queue,+ &mut last_updated_clock,+ &mut buffer,+ &mut held,+ &mut seeds,+ )+ .await+ {+ break;+ }+let last_updated = last_updated_clock.next();match message {ShuffleMessage::Event {@@ -303,42 +335,6 @@ async fn run_worker().await;}- ShuffleMessage::Seed {- work,- offset,- broker_ts_ms: _,- } => {- // Worker receipt is the first point that both proves this exact seed landed and- // orders its ceiling before even a zero-work handler can mark it processed.- // The dispatcher also records the delivered batch maximum, but that post-send- // accounting can race a fast worker on a multithreaded runtime.- merge- .seed_tracker- .mark_dispatched(partition_id as i32, offset + 1);- if flush_event_changes_before_inline(- &sink,- &mut buffer,- partition_id,- &mut held,- )- .await- {- break;- }- handle_seed(- partition_id,- &handle,- &catalog,- &sink,- &merge,- &mut queue,- &mut reconcile_queue,- &last_updated,- &work,- offset,- )- .await;- }ShuffleMessage::RedrivePendingTransfers => {handle_redrive(partition_id, &handle, &merge).await;}@@ -383,6 +379,8 @@ async fn run_worker(.unwrap_or_default();}}+ // Collected above, before this match ever sees one.+ ShuffleMessage::Seed { .. } => unreachable!("seeds are collected into runs"),ShuffleMessage::ReconcileDrain => {if flush_event_changes_before_inline(&sink,@@ -413,6 +411,23 @@ async fn run_worker(}}+ if !held {+ apply_seed_runs(+ partition_id,+ &handle,+ &catalog,+ &sink,+ &merge,+ &mut queue,+ &mut reconcile_queue,+ &mut last_updated_clock,+ &mut buffer,+ &mut held,+ &mut seeds,+ )+ .await;+ }+if held {continue;}@@ -514,6 +529,57 @@ async fn flush_event_changes_before_inline(false}+/// Apply the seeds collected so far as runs, ahead of whatever message closed the collection.+///+/// Returns `true` when the pre-run flush of buffered live changes failed: the caller must stop the+/// batch without marking, so Kafka replays it. The collected seeds are then neither marked nor+/// held, which is what their own redelivery is for.+#[allow(clippy::too_many_arguments)]+async fn apply_seed_runs(+ partition_id: u16,+ handle: &StoreHandle,+ catalog: &CatalogHandle,+ sink: &Arc<dyn MembershipSink>,+ merge: &MergeWorkerDeps,+ queue: &mut EvictionQueue<BehavioralKey>,+ reconcile_queue: &mut ReconcileQueue,+ clock: &mut LastUpdatedClock,+ buffer: &mut OutputBuffer,+ held: &mut bool,+ seeds: &mut Vec<Admitted<SeedWork>>,+) -> bool {+ if seeds.is_empty() {+ return false;+ }+ let seeds = std::mem::take(seeds);+ // Worker receipt is the first point that both proves these exact seeds landed and orders their+ // ceiling before even a zero-work run can mark them processed. The dispatcher also records the+ // delivered batch maximum, but that post-send accounting can race a fast worker on a+ // multithreaded runtime.+ if let Some(max) = seeds.iter().map(|seed| seed.offset.0).max() {+ merge+ .seed_tracker+ .mark_dispatched(partition_id as i32, max + 1);+ }+ // Produce order equals state-commit order for the live buffer, so a run must not produce while+ // unflushed live changes sit in it.+ if flush_event_changes_before_inline(sink, buffer, partition_id, held).await {+ return true;+ }++ let snapshot = catalog.load();+ let deps = ApplyDeps {+ partition_id,+ handle,+ catalog: &snapshot,+ sink,+ merge,+ };+ let groups = group_seeds(seeds, merge.seed_budget, |work| row_weight(&snapshot, work));+ handle_seed_groups(deps, queue, reconcile_queue, clock, groups).await;+ false+}+pub(crate) fn count_by_status(changes: &[CohortMembershipChange]) -> (u64, u64) {changes.iter()@@ -1219,6 +1285,7 @@ mod tombstone_redirect_tests {register_transfer_enabled: false,reconcile: crate::workers::ReconcileDeps::default(),person_seed: crate::workers::PersonSeedDeps::default(),+ seed_budget: crate::workers::seed_run::RunBudget::default(),})}@@ -1252,6 +1319,7 @@ mod tombstone_redirect_tests {register_transfer_enabled: false,reconcile: crate::workers::ReconcileDeps::default(),person_seed: crate::workers::PersonSeedDeps::default(),+ seed_budget: crate::workers::seed_run::RunBudget::default(),})}@@ -1279,6 +1347,7 @@ mod tombstone_redirect_tests {register_transfer_enabled: false,reconcile: crate::workers::ReconcileDeps::default(),person_seed: crate::workers::PersonSeedDeps::default(),+ seed_budget: crate::workers::seed_run::RunBudget::default(),})}diff --git a/rust/cohort-stream-processor/tests/cascade_consumer.rs b/rust/cohort-stream-processor/tests/cascade_consumer.rsindex 66d73c03207b..7071ca7aa353 100644--- a/rust/cohort-stream-processor/tests/cascade_consumer.rs+++ b/rust/cohort-stream-processor/tests/cascade_consumer.rs@@ -468,6 +468,7 @@ async fn spawn_instance(register_transfer_enabled: false,reconcile: cohort_stream_processor::workers::ReconcileDeps::default(),person_seed: cohort_stream_processor::workers::PersonSeedDeps::default(),+ seed_budget: cohort_stream_processor::workers::seed_run::RunBudget::default(),});let dispatcher = Arc::new(EventDispatcher::new(diff --git a/rust/cohort-stream-processor/tests/merge_consumer.rs b/rust/cohort-stream-processor/tests/merge_consumer.rsindex 58fbdc8545b8..a37704b0ebd0 100644--- a/rust/cohort-stream-processor/tests/merge_consumer.rs+++ b/rust/cohort-stream-processor/tests/merge_consumer.rs@@ -624,6 +624,7 @@ async fn spawn_instance(register_transfer_enabled: false,reconcile: cohort_stream_processor::workers::ReconcileDeps::default(),person_seed: cohort_stream_processor::workers::PersonSeedDeps::default(),+ seed_budget: cohort_stream_processor::workers::seed_run::RunBudget::default(),});let dispatcher = Arc::new(EventDispatcher::new(diff --git a/rust/cohort-stream-processor/tests/merge_durability.rs b/rust/cohort-stream-processor/tests/merge_durability.rsindex 5971c165af62..46ee59d06b9d 100644--- a/rust/cohort-stream-processor/tests/merge_durability.rs+++ b/rust/cohort-stream-processor/tests/merge_durability.rs@@ -722,6 +722,7 @@ async fn spawn_instance(register_transfer_enabled: false,reconcile: cohort_stream_processor::workers::ReconcileDeps::default(),person_seed: cohort_stream_processor::workers::PersonSeedDeps::default(),+ seed_budget: cohort_stream_processor::workers::seed_run::RunBudget::default(),});let dispatcher = Arc::new(EventDispatcher::new(diff --git a/rust/cohort-stream-processor/tests/seed_consumer.rs b/rust/cohort-stream-processor/tests/seed_consumer.rsindex 47d62bb32a6b..ce23a4e0f79b 100644--- a/rust/cohort-stream-processor/tests/seed_consumer.rs+++ b/rust/cohort-stream-processor/tests/seed_consumer.rs@@ -683,6 +683,7 @@ async fn spawn_instance(marker_sink,},person_seed: cohort_stream_processor::workers::PersonSeedDeps::default(),+ seed_budget: cohort_stream_processor::workers::seed_run::RunBudget::default(),});let dispatcher = Arc::new(EventDispatcher::new(diff --git a/rust/cohort-stream-processor/tests/stage1_worker.rs b/rust/cohort-stream-processor/tests/stage1_worker.rsindex cffeb686bb81..81ddca8975f2 100644--- a/rust/cohort-stream-processor/tests/stage1_worker.rs+++ b/rust/cohort-stream-processor/tests/stage1_worker.rs@@ -2438,6 +2438,7 @@ async fn seed_arm_flushes_buffered_event_changes_first_and_marks_both_trackers()let filters = build_team_filters(vec![(CohortId(1), cohort(vec![behavioral_leaf(7)]))]);let alice = person(1);let bob = person(2);+ let carol = person(3);let catalog = catalog_of(filters);let sink = CaptureSink::new();@@ -2466,7 +2467,8 @@ async fn seed_arm_flushes_buffered_event_changes_first_and_marks_both_trackers()cse_offset: 0,broker_ts_ms: Some(broker_ts),},- seed_message(bob, utc_today(), 1, 7),+ seed_message(bob, utc_today(), 1, 6),+ seed_message(carol, utc_today(), 1, 7),]).await.unwrap();@@ -2474,14 +2476,29 @@ async fn seed_arm_flushes_buffered_event_changes_first_and_marks_both_trackers()worker.join().await.unwrap();let changes = sink.changes();- assert_eq!(changes.len(), 2, "one live flip, one seeded flip");+ assert_eq!(changes.len(), 3, "one live flip, two seeded flips");assert_eq!((changes[0].person_id.clone(), changes[0].origin),(alice.to_string(), None),- "the buffered live change flushed before the seed arm ran",+ "the buffered live change flushed before the seed run ran",+ );+ assert_eq!(+ changes[1..]+ .iter()+ .map(|change| change.person_id.clone())+ .collect::<std::collections::BTreeSet<_>>(),+ std::collections::BTreeSet::from([bob.to_string(), carol.to_string()]),+ "both seeds of the collection applied",+ );+ assert!(+ changes[1..].iter().all(|change| change.origin.is_some()),+ "the seeded changes are tagged",+ );+ assert_eq!(+ sink.produce_calls(),+ 2,+ "one call for the live flush and one for the whole seed run",);- assert_eq!(changes[1].person_id, bob.to_string());- assert!(changes[1].origin.is_some(), "the seeded change is tagged");assert_eq!(tracker.committable_offsets().get(&(PARTITION_ID as i32)),@@ -2502,6 +2519,63 @@ async fn seed_arm_flushes_buffered_event_changes_first_and_marks_both_trackers());}+/// The whole point of the batched apply: a channel batch's seeds pay one produce round trip per+/// run, not one per seed. A regression here shows up as latency, not as a wrong result, so nothing+/// else would catch it.+#[tokio::test]+async fn a_channel_batch_of_seeds_pays_one_produce_round_trip_per_run() {+ const SEEDS: usize = 300;+ // `COHORT_SEED_APPLY_BATCH_MAX` defaults to 256, so 300 seeds form two runs.+ const RUNS: usize = 2;++ let (_dir, store) = temp_store();+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![behavioral_leaf(7)]))]);+ let catalog = catalog_of(filters);+ let sink = CaptureSink::new();+ let tracker = Arc::new(OffsetTracker::new());+ let deps = MergeWorkerDeps::capture();++ let (tx, rx) = mpsc::channel(16);+ let rx = MeteredReceiver::unmetered(rx);+ let worker = Stage1Worker::spawn(+ PARTITION_ID,+ rx,+ test_handle(&store),+ catalog,+ Arc::new(sink.clone()),+ tracker.clone(),+ deps.clone(),+ false,+ );++ deps.seed_tracker+ .mark_dispatched(PARTITION_ID as i32, SEEDS as i64);+ let batch: Vec<ShuffleMessage> = (0..SEEDS)+ .map(|n| seed_message(person(n as u128 + 1), utc_today(), 1, n as i64))+ .collect();+ tx.send(batch).await.unwrap();+ drop(tx);+ worker.join().await.unwrap();++ assert_eq!(+ sink.changes().len(),+ SEEDS,+ "every seed still lands its own entry",+ );+ assert_eq!(+ sink.produce_calls(),+ RUNS,+ "one produce per run, not one per seed",+ );+ assert_eq!(+ deps.seed_tracker+ .committable_offsets()+ .get(&(PARTITION_ID as i32)),+ Some(&(SEEDS as i64)),+ "both runs marked their whole spans",+ );+}+/// A failed seed emission holds only the seed tracker; the events tracker is unaffected, and the/// next tenure's redelivery re-emits the lost change.#[tokio::test]