: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
feat(cohorts): processor seed consumer (#72021)
Matheus Batistaf40aae766c2b
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 41c084b6440a..5f7bd9dc6c2c 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2286,6 +2286,7 @@ dependencies = ["metrics","metrics-exporter-prometheus","object_store",+ "proptest","rand 0.8.5","rdkafka","rocksdb",diff --git a/rust/cohort-core/src/seed/tile.rs b/rust/cohort-core/src/seed/tile.rsindex 6c0b8fd766ba..24554972e47c 100644--- a/rust/cohort-core/src/seed/tile.rs+++ b/rust/cohort-core/src/seed/tile.rs@@ -115,6 +115,11 @@ impl SeedTile {self.count.get()}+ /// The count with its non-zero proof intact, for consumers whose merge math relies on it.+ pub const fn count_nonzero(&self) -> NonZeroU32 {+ self.count+ }+pub const fn run_id(&self) -> RunId {self.run_id}diff --git a/rust/cohort-stream-processor/Cargo.toml b/rust/cohort-stream-processor/Cargo.tomlindex 65b54cf4904c..fdd01791a75d 100644--- a/rust/cohort-stream-processor/Cargo.toml+++ b/rust/cohort-stream-processor/Cargo.toml@@ -66,6 +66,8 @@ uuid = { workspace = true }# Integration tests in `tests/` build `TeamFilters` via `freeze(UTC)`, so they name `chrono_tz::UTC`# directly (a normal dependency is not in scope for the separate integration-test crates).chrono-tz = { workspace = true }+# Convergence/idempotency property tests for the seed-tile apply core (`workers::seed_path`).+proptest = "1"serde_json = { workspace = true }tempfile = "3"# `test-util` enables the paused clock (`start_paused` / `tokio::time::advance`) the sweep timerdiff --git a/rust/cohort-stream-processor/src/cascade/decision.rs b/rust/cohort-stream-processor/src/cascade/decision.rsindex a8e832653b82..efff26153a18 100644--- a/rust/cohort-stream-processor/src/cascade/decision.rs+++ b/rust/cohort-stream-processor/src/cascade/decision.rs@@ -37,6 +37,8 @@ pub fn should_emit(person_id: incoming.change.person_id.clone(),last_updated: new_last_updated.to_string(),status: new_status,+ origin: None,+ run_id: None,},// Carried forward so the chain keeps one stable replay identity across hops.source_offset: incoming.source_offset,@@ -75,6 +77,8 @@ mod tests {person_id: "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string(),last_updated: TS_IN.to_string(),status,+ origin: None,+ run_id: None,}}diff --git a/rust/cohort-stream-processor/src/cascade/message.rs b/rust/cohort-stream-processor/src/cascade/message.rsindex f56f135386d0..867eb8c21b7a 100644--- a/rust/cohort-stream-processor/src/cascade/message.rs+++ b/rust/cohort-stream-processor/src/cascade/message.rs@@ -62,6 +62,8 @@ mod tests {person_id: "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string(),last_updated: TS.to_string(),status: MembershipStatus::Entered,+ origin: None,+ run_id: None,},source_offset: 12345,depth: 2,diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rsindex 996ac8efe5de..debbe1aedb72 100644--- a/rust/cohort-stream-processor/src/config.rs+++ b/rust/cohort-stream-processor/src/config.rs@@ -218,6 +218,31 @@ pub struct Config {#[envconfig(default = "cohort-stream-cascade")]pub kafka_cascade_consumer_group: String,+ /// Consume `cohort_stream_seed_events` and apply backfill day-tiles. Default off.+ #[envconfig(from = "COHORT_SEED_CONSUMER_ENABLED", default = "false")]+ pub cohort_seed_consumer_enabled: bool,++ /// The backfill seed-tile topic; must be co-partitioned with `cohort_stream_events`.+ #[envconfig(default = "cohort_stream_seed_events")]+ pub cohort_stream_seed_events_topic: String,++ /// Group for the seed follower — separate so backfill lag age is observable on its own.+ #[envconfig(default = "cohort-stream-seeds")]+ pub kafka_seed_consumer_group: String,++ /// Apply-fence margin (ms) over `s_chunk`: covers shuffler clock skew, lag spread, and+ /// producer linger.+ #[envconfig(from = "COHORT_SEED_FENCE_MARGIN_MS", default = "600000")]+ pub cohort_seed_fence_margin_ms: i64,++ /// How often the seed consumer probes idle live partitions so a quiet partition's fence can+ /// still open.+ #[envconfig(+ from = "COHORT_SEED_WATERMARK_IDLE_PROBE_INTERVAL_MS",+ default = "30000"+ )]+ pub cohort_seed_watermark_idle_probe_interval_ms: u64,+/// Stable per-pod identity for `group.instance.id` + `client.id`, enabling static membership./// Read from `POD_NAME`, else `HOSTNAME`. Absent means no static membership.#[envconfig(from = "POD_NAME")]@@ -567,6 +592,12 @@ impl Config {Duration::from_millis(self.merge_gc_interval_ms)}+ pub fn seed_idle_probe_interval(&self) -> Duration {+ // Floor at 1s: `tokio::time::interval` panics on a zero period.+ Duration::from_millis(self.cohort_seed_watermark_idle_probe_interval_ms)+ .max(Duration::from_secs(1))+ }+pub fn checkpoint_interval(&self) -> Duration {Duration::from_millis(self.checkpoint_interval_ms)}@@ -637,6 +668,16 @@ impl Config {);}+ // Not a refusal (dev runs with durability off), but a crash then loses applied tiles+ // that never replay.+ if self.cohort_seed_consumer_enabled && !self.durable_restore_enabled {+ warn!(+ "COHORT_SEED_CONSUMER_ENABLED without DURABLE_RESTORE_ENABLED: a committed seed \+ offset does not imply a durably applied tile across restarts; do not stamp \+ backfill readiness against this deployment.",+ );+ }+Ok(())}@@ -921,6 +962,11 @@ mod tests {checkpoint_import_window_hours: 24,checkpoint_import_attempt_depth: 10,checkpoint_import_timeout_secs: 240,+ cohort_seed_consumer_enabled: false,+ cohort_stream_seed_events_topic: "cohort_stream_seed_events".to_string(),+ kafka_seed_consumer_group: "cohort-stream-seeds".to_string(),+ cohort_seed_fence_margin_ms: 600_000,+ cohort_seed_watermark_idle_probe_interval_ms: 30_000,}}diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rsindex 7a0be0866c76..8beac31b9cc3 100644--- a/rust/cohort-stream-processor/src/consumers/events.rs+++ b/rust/cohort-stream-processor/src/consumers/events.rs@@ -25,6 +25,7 @@ use tracing::{debug, info, warn};pub use cohort_core::events::CohortStreamEvent;use crate::consumers::merges::{ConsumedCascade, ConsumedMerge, ConsumedTransfer};+use crate::consumers::seeds::ConsumedSeed;use crate::filters::manager::CatalogHandle;use crate::merge::transfer::PendingTransfer;use crate::observability::metrics::{@@ -34,12 +35,14 @@ use crate::observability::metrics::{COHORT_STREAM_EVENTS_SKIPPED_NOT_OWNED, COHORT_STREAM_KAFKA_RECV_ERRORS,COHORT_STREAM_MERGES_SKIPPED_NOT_OWNED, COHORT_STREAM_OFFSET_COMMITS,COHORT_STREAM_OFFSET_COMMIT_ERRORS, COHORT_STREAM_ROUTE_ERRORS,- COHORT_STREAM_TRANSFERS_SKIPPED_NOT_OWNED, COHORT_STREAM_WORKERS_SPAWNED,- DURABLE_RESTORE_PARTITIONS_KEPT_TOTAL, DURABLE_RESTORE_PARTITIONS_WIPED_STALE_TOTAL,- DURABLE_RESTORE_PENDING_TRANSFERS_RECOVERED_PARTITIONS_TOTAL, MERGE_HELD_OFFSET_GAUGE,- MERGE_PENDING_TRANSFERS_GAUGE, PARTITIONS_ASSIGNED_TOTAL, PARTITIONS_PAUSED,- PARTITIONS_REVOKED_TOTAL, PARTITION_STATE_DELETED_TOTAL, PENDING_HELD_EVENTS,- REBALANCE_CLEANUP_SKIPPED_TOTAL, REVOKE_DRAIN_DURATION_SECONDS,+ COHORT_STREAM_SEEDS_SKIPPED_NOT_OWNED, COHORT_STREAM_TRANSFERS_SKIPPED_NOT_OWNED,+ COHORT_STREAM_WORKERS_SPAWNED, DURABLE_RESTORE_PARTITIONS_KEPT_TOTAL,+ DURABLE_RESTORE_PARTITIONS_WIPED_STALE_TOTAL,+ DURABLE_RESTORE_PENDING_TRANSFERS_RECOVERED_PARTITIONS_TOTAL, LIVE_WATERMARK_AGE_MS,+ MERGE_HELD_OFFSET_GAUGE, MERGE_PENDING_TRANSFERS_GAUGE, PARTITIONS_ASSIGNED_TOTAL,+ PARTITIONS_PAUSED, PARTITIONS_REVOKED_TOTAL, PARTITION_STATE_DELETED_TOTAL,+ PENDING_HELD_EVENTS, REBALANCE_CLEANUP_SKIPPED_TOTAL, REVOKE_DRAIN_DURATION_SECONDS,+ SEED_HELD_OFFSET_GAUGE,};use crate::partitions::backpressure::Backpressure;use crate::partitions::offset_tracker::OffsetTracker;@@ -74,6 +77,9 @@ pub struct ConsumedEvent {pub event: CohortStreamEvent,pub partition: i32,pub offset: i64,+ /// Broker timestamp (CreateTime ≈ shuffler produce instant) — the seed fence's live-watermark+ /// input. `None` (`Timestamp::NotAvailable`) never advances the watermark.+ pub broker_ts_ms: Option<i64>,}/// The Kafka-free routing core: dispatches consumed batches to per-partition workers, tracks@@ -171,6 +177,7 @@ impl EventDispatcher {ShuffleMessage::Event {event: Box::new(consumed.event),cse_offset: consumed.offset,+ broker_ts_ms: consumed.broker_ts_ms,},)})@@ -213,6 +220,7 @@ impl EventDispatcher {let message = ShuffleMessage::Event {event: Box::new(consumed.event),cse_offset: consumed.offset,+ broker_ts_ms: consumed.broker_ts_ms,};// A paused partition can still deliver a few already-fetched stragglers; queue them behind// the holdover rather than racing them ahead of older offsets.@@ -365,6 +373,65 @@ impl EventDispatcher {counter!(COHORT_STREAM_CASCADES_SKIPPED_NOT_OWNED).increment(stats.not_owned_skipped);}+ /// Non-blocking seed dispatch, raising the **seed** tracker's ceiling only for what lands+ /// (seeds carry no `event_offset`, so the router can't). Returns the un-dispatched seeds for+ /// the caller to hold and pause.+ pub fn dispatch_seeds(&self, batch: Vec<ConsumedSeed>) -> HashMap<i32, Vec<ConsumedSeed>> {+ if self.draining.load(Ordering::SeqCst) {+ if !batch.is_empty() {+ counter!(COHORT_STREAM_SEEDS_SKIPPED_NOT_OWNED).increment(batch.len() as u64);+ debug!(+ dropped = batch.len(),+ "seed dispatch after shutdown began; dropping batch for replay"+ );+ }+ return HashMap::new();+ }++ let mut messages: Vec<(i32, ShuffleMessage)> = Vec::with_capacity(batch.len());+ let mut max_offsets: HashMap<i32, i64> = HashMap::new();+ let mut not_owned = 0u64;+ for consumed in batch {+ let partition = consumed.partition;+ if !self.owned.contains(&partition) {+ not_owned += 1;+ continue;+ }+ self.ensure_worker(partition);+ let entry = max_offsets.entry(partition).or_insert(consumed.offset);+ *entry = (*entry).max(consumed.offset);+ messages.push((partition, consumed.into_message()));+ }+ counter!(COHORT_STREAM_SEEDS_SKIPPED_NOT_OWNED).increment(not_owned);++ let mut full: HashMap<i32, Vec<ConsumedSeed>> = HashMap::new();+ let mut route_errors = 0u64;+ for (partition, outcome) in self.router.try_route_batch(messages) {+ match outcome {+ // A sub-batch lands whole or not at all, so the pre-computed max is the ceiling.+ SendOutcome::Sent { .. } => {+ if let Some(&max_offset) = max_offsets.get(&partition) {+ self.merge+ .seed_tracker+ .mark_dispatched(partition, max_offset + 1);+ }+ }+ SendOutcome::Full(returned) => {+ full.entry(partition).or_default().extend(+ returned+ .into_iter()+ .filter_map(|message| ConsumedSeed::from_message(partition, message)),+ );+ }+ SendOutcome::NoWorker | SendOutcome::ChannelClosed => route_errors += 1,+ }+ }+ if route_errors > 0 {+ counter!(COHORT_STREAM_ROUTE_ERRORS).increment(route_errors);+ }+ full+ }+async fn dispatch_to_workers(&self,items: Vec<(i32, i64, ShuffleMessage)>,@@ -523,6 +590,9 @@ impl EventDispatcher {}pub fn assign_partition(&self, partition: i32) {+ // Forget before ownership flips: every tenure starts fail-closed for the seed fence, and+ // a concurrent idle-probe advance can't slip in between.+ self.merge.live_watermarks.forget_partition(partition);self.owned.insert(partition);counter!(PARTITIONS_ASSIGNED_TOTAL).increment(1);}@@ -569,12 +639,17 @@ impl EventDispatcher {self.merge.merge_tracker.forget_partition(partition);self.merge.transfer_tracker.forget_partition(partition);self.merge.cascade_tracker.forget_partition(partition);+ self.merge.seed_tracker.forget_partition(partition);+ // Fail-closed on re-acquire: the next tenure re-derives its own watermark.+ self.merge.live_watermarks.forget_partition(partition);// Reset per-partition gauges. Held-offset gauges in particular are alerted on a sustained// non-zero level — without this, a hold that cleared on revoke would keep the alert firing.gauge!(MERGE_PENDING_TRANSFERS_GAUGE, "partition" => partition.to_string()).set(0.0);gauge!(MERGE_HELD_OFFSET_GAUGE, "partition" => partition.to_string()).set(0.0);gauge!(CASCADE_HELD_OFFSET_GAUGE, "partition" => partition.to_string()).set(0.0);+ gauge!(SEED_HELD_OFFSET_GAUGE, "partition" => partition.to_string()).set(0.0);+ gauge!(LIVE_WATERMARK_AGE_MS, "partition" => partition.to_string()).set(0.0);let Some(partition_id) = partition_to_store_id(partition) else {warn!(@@ -792,6 +867,11 @@ impl EventDispatcher {self.tracker.as_ref()}+ /// The events-topic tracker, for the seed consumer's idle probe.+ pub(crate) fn events_tracker(&self) -> &Arc<OffsetTracker> {+ &self.tracker+ }+fn owned_committable_offsets(&self) -> HashMap<i32, i64> {self.tracker.committable_offsets()@@ -867,7 +947,7 @@ pub struct CohortStreamEventsConsumer {impl CohortStreamEventsConsumer {#[allow(clippy::too_many_arguments)]pub fn new(- consumer: StreamConsumer<CohortConsumerContext>,+ consumer: Arc<StreamConsumer<CohortConsumerContext>>,topic: String,dispatcher: Arc<EventDispatcher>,handle: Handle,@@ -878,7 +958,6 @@ impl CohortStreamEventsConsumer {consumer_command_rx: ConsumerCommandReceiver,restore_manifest: Option<OffsetManifest>,) -> Self {- let consumer = Arc::new(consumer);let pauser: Arc<dyn PartitionPauser> =Arc::new(ConsumerPauser::new(consumer.clone(), topic.clone()));Self {@@ -1122,7 +1201,7 @@ impl CohortStreamEventsConsumer {*prev_paused_target = target;}gauge!(PARTITIONS_PAUSED).set(backpressure.held_partition_count() as f64);- gauge!(PENDING_HELD_EVENTS).set(backpressure.held_event_count() as f64);+ gauge!(PENDING_HELD_EVENTS).set(backpressure.held_message_count() as f64);if outcome.transport_error {tokio::time::sleep(RECV_ERROR_BACKOFF).await;@@ -1156,7 +1235,12 @@ impl CohortStreamEventsConsumer {);}Some(payload) => match serde_json::from_slice::<CohortStreamEvent>(payload) {- Ok(event) => outcome.events.push(ConsumedEvent { event, partition, offset }),+ Ok(event) => outcome.events.push(ConsumedEvent {+ event,+ partition,+ offset,+ broker_ts_ms: message.timestamp().to_millis(),+ }),Err(err) => {outcome.deserialize_errors += 1;debug!(@@ -1304,7 +1388,7 @@ async fn run_commit_loop(/// never delays the heartbeat. Re-asserts the full target every update — idempotent in librdkafka — so/// a swallowed pause error or a rebalance-reset toppar self-heals. `applied` tracks only which/// partitions to resume (those that left the target). Exits when the sender is dropped.-async fn run_pauser_loop(+pub(crate) async fn run_pauser_loop(pauser: Arc<dyn PartitionPauser>,mut rx: tokio::sync::mpsc::UnboundedReceiver<HashSet<i32>>,) {@@ -1698,6 +1782,9 @@ mod tests {cascade_tracker: Arc::new(OffsetTracker::new()),cascade: crate::workers::CascadeConfig::default(),partition_count: COHORT_PARTITION_COUNT,+ seed_tile_sink: Arc::new(crate::producer::CaptureSeedTileSink::new()),+ seed_tracker: Arc::new(crate::partitions::offset_tracker::OffsetTracker::new()),+ live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),});let dispatcher = EventDispatcher::new(PartitionRouter::new(64),@@ -1747,6 +1834,7 @@ mod tests {event: matching_event(person, topic_partition, topic_offset),partition: topic_partition,offset: topic_offset,+ broker_ts_ms: None,}}@@ -2011,6 +2099,19 @@ mod tests {assert_eq!(tracker.partition_count(), 1);}+ /// Re-acquiring a partition clears any stale watermark, so every tenure starts fail-closed.+ #[tokio::test]+ async fn assign_partition_resets_the_live_watermark_so_a_new_tenure_is_fail_closed() {+ let (_dir, store) = temp_store();+ let dispatcher = dispatcher_with(&store, behavioral_catalog());++ dispatcher.merge_deps().live_watermarks.observe(5, 1_000);+ dispatcher.assign_partition(5);++ assert_eq!(dispatcher.merge_deps().live_watermarks.get(5), None);+ let _tracker = dispatcher.shutdown().await;+ }+#[tokio::test]async fn dispatch_empty_batch_is_a_noop() {let (_dir, store) = temp_store();@@ -2067,6 +2168,96 @@ mod tests {.collect()}+ fn consumed_seed(seed_person: Uuid, partition: i32, offset: i64) -> ConsumedSeed {+ use cohort_core::seed::{ClaimEpoch, ConditionHash, RunId, SChunkMs, SeedTile};+ ConsumedSeed {+ work: crate::consumers::seeds::SeedWork::Tile(SeedTile::new(+ TeamId(TEAM),+ seed_person,+ ConditionHash::parse("0123456789abcdef").unwrap(),+ std::num::NonZeroU32::new(1).unwrap(),+ 20_614,+ SChunkMs(1_700_000_000_000),+ RunId(Uuid::nil()),+ ClaimEpoch(1),+ )),+ partition,+ offset,+ }+ }++ fn held_seed_offsets(seeds: &[ConsumedSeed]) -> Vec<i64> {+ seeds.iter().map(|seed| seed.offset).collect()+ }++ #[tokio::test]+ async fn dispatch_seeds_raises_only_the_seed_ceiling_from_its_own_offsets() {+ let (_dir, store) = temp_store();+ let dispatcher = dispatcher_with_buffer(&store, behavioral_catalog(), 16);+ dispatcher.assign_partition(0);+ // Hold the receiver so no worker drains; the ceilings are the observable.+ let mut rx = dispatcher.router.add_partition(0).unwrap();++ let full = dispatcher.dispatch_seeds(vec![+ consumed_seed(person(1), 0, 3),+ consumed_seed(person(2), 0, 5),+ // Unowned partition: dropped for replay, never held.+ consumed_seed(person(3), 9, 1),+ ]);+ assert!(full.is_empty(), "both owned seeds landed");++ // Seeds carry no event offset, so the dispatcher must have raised the seed ceiling+ // itself.+ let seed_tracker = &dispatcher.merge_deps().seed_tracker;+ assert_eq!(+ seed_tracker.mark_processed(0, 6),+ MarkOutcome::WithinDispatch+ );+ assert_eq!(seed_tracker.committable_offsets().get(&0), Some(&6));+ assert_eq!(+ seed_tracker.mark_processed(0, 7),+ MarkOutcome::CappedAheadOfDispatch,+ "the ceiling is exactly the dispatched max + 1",+ );++ assert_eq!(+ dispatcher.tracker().mark_processed(0, 1),+ MarkOutcome::CappedAheadOfDispatch,+ );+ assert!(dispatcher.tracker().committable_offsets().is_empty());++ let batch = rx.try_recv().unwrap();+ assert_eq!(+ batch.iter().filter_map(ShuffleMessage::seed_offset).count(),+ 2,+ "the two owned seeds ride the worker channel",+ );+ }++ #[tokio::test]+ async fn dispatch_seeds_returns_the_over_budget_remainder_without_raising_its_ceiling() {+ let (_dir, store) = temp_store();+ // Seeds share the event intake budget: a one-message cap refuses the second sub-batch.+ let dispatcher = dispatcher_with_intake_cap(&store, behavioral_catalog(), 16, 1);+ dispatcher.assign_partition(0);+ let _rx = dispatcher.router.add_partition(0).unwrap();++ assert!(dispatcher+ .dispatch_seeds(vec![consumed_seed(person(1), 0, 10)])+ .is_empty());+ let mut full = dispatcher.dispatch_seeds(vec![consumed_seed(person(2), 0, 11)]);+ let held = full.remove(&0).expect("partition 0 held on the intake cap");+ assert_eq!(held_seed_offsets(&held), vec![11]);++ let seed_tracker = &dispatcher.merge_deps().seed_tracker;+ assert_eq!(+ seed_tracker.mark_processed(0, 12),+ MarkOutcome::CappedAheadOfDispatch,+ "a held seed's offset stays above the ceiling, so it can never commit",+ );+ assert_eq!(seed_tracker.committable_offsets().get(&0), Some(&11));+ }+#[tokio::test]async fn nonblocking_dispatch_holds_a_full_channel_and_advances_the_offset_only_after_flush() {let (_dir, store) = temp_store();diff --git a/rust/cohort-stream-processor/src/consumers/merges.rs b/rust/cohort-stream-processor/src/consumers/merges.rsindex 0771a07a7e18..0167216909a6 100644--- a/rust/cohort-stream-processor/src/consumers/merges.rs+++ b/rust/cohort-stream-processor/src/consumers/merges.rs@@ -329,10 +329,7 @@ impl<R: FollowerRoute> FollowerConsumer<R> {}fn owned_committable_offsets(&self) -> HashMap<i32, i64> {- restrict_to_owned(- self.tracker().committable_offsets(),- &self.dispatcher.owned_partitions(),- )+ owned_committable_offsets(self.tracker(), &self.dispatcher)}}@@ -342,6 +339,17 @@ struct FollowerOutcome<T> {transport_error: bool,}+/// A tracker's committable offsets restricted to the partitions this pod currently owns.+pub(crate) fn owned_committable_offsets(+ tracker: &OffsetTracker,+ dispatcher: &EventDispatcher,+) -> HashMap<i32, i64> {+ restrict_to_owned(+ tracker.committable_offsets(),+ &dispatcher.owned_partitions(),+ )+}+fn restrict_to_owned(offsets: HashMap<i32, i64>, owned: &[i32]) -> HashMap<i32, i64> {let owned: HashSet<i32> = owned.iter().copied().collect();offsets@@ -424,6 +432,8 @@ mod tests {person_id: Uuid::from_u128(0xCAFE).to_string(),last_updated: "2026-05-26 12:34:56.789000".to_string(),status: crate::producer::MembershipStatus::Entered,+ origin: None,+ run_id: None,},123,)diff --git a/rust/cohort-stream-processor/src/consumers/mod.rs b/rust/cohort-stream-processor/src/consumers/mod.rsindex 11fe941f34e7..32f725e500e9 100644--- a/rust/cohort-stream-processor/src/consumers/mod.rs+++ b/rust/cohort-stream-processor/src/consumers/mod.rs@@ -1,11 +1,14 @@//! Kafka consumers — one rdkafka `StreamConsumer` per input topic. The `events` submodule covers-//! `cohort_stream_events`, the hot path; `merges` carries the merge-protocol follower consumers.+//! `cohort_stream_events`, the hot path; `merges` carries the merge-protocol follower consumers;+//! `seeds` carries the backfill seed follower.pub mod events;pub mod merges;+pub mod seeds;pub use events::{CohortStreamEvent, CohortStreamEventsConsumer, ConsumedEvent, EventDispatcher};pub use merges::{CascadeRoute, ConsumedCascade, ConsumedMerge, ConsumedTransfer, FollowerConsumer,FollowerRoute, MergeRoute, TransferRoute,};+pub use seeds::{ConsumedSeed, SeedFollowerConsumer, SeedSkipReason, SeedWork};diff --git a/rust/cohort-stream-processor/src/consumers/seeds.rs b/rust/cohort-stream-processor/src/consumers/seeds.rsnew file mode 100644index 000000000000..36e79d15d25f--- /dev/null+++ b/rust/cohort-stream-processor/src/consumers/seeds.rs@@ -0,0 +1,894 @@+//! The `cohort_stream_seed_events` follower consumer — the backfill day-tile input.+//!+//! Assignment arrives via the events group's rebalance mirror. The apply fence is enforced at+//! admission: a tile dispatches only once its partition's live watermark clears+//! `s_chunk + margin`; fence-closed and channel-full tiles share one holdover + pause mechanism,+//! and an un-dispatched tile was never `mark_dispatched`ed, so its offset cannot commit.+//! Consume-side skips ride the worker channel so their offsets mark in order; they never close+//! the fence.++use std::collections::{HashMap, HashSet};+use std::sync::Arc;+use std::time::Duration;++use cohort_core::seed::{decode_seed, DecodedSeed, SChunkMs, SeedTile};+use lifecycle::Handle;+use metrics::{counter, gauge, histogram};+use rdkafka::consumer::{CommitMode, Consumer, StreamConsumer};+use rdkafka::message::Message;+use rdkafka::{Offset, TopicPartitionList};+use tracing::{debug, info, warn};++use crate::consumers::events::{fsync_then_commit, run_pauser_loop, EventDispatcher};+use crate::consumers::merges::owned_committable_offsets;+use crate::observability::metrics::{+ COHORT_STREAM_KAFKA_RECV_ERRORS, COHORT_STREAM_SEEDS_CONSUMED,+ COHORT_STREAM_SEEDS_CONSUME_BATCH_SIZE, COHORT_STREAM_SEED_DESERIALIZE_ERRORS,+ LIVE_WATERMARK_AGE_MS, SEED_FENCED_PARTITIONS, SEED_FENCE_DEFICIT_MS,+};+use crate::partitions::backpressure::PartitionHoldover;+use crate::partitions::pause::PartitionPauser;+use crate::partitions::rebalance::CohortConsumerContext;+use crate::partitions::shuffle_message::ShuffleMessage;+use crate::partitions::watermarks::WatermarkMs;++/// Back-off after a Kafka transport error, mirroring the sibling consume loops.+const RECV_ERROR_BACKOFF: Duration = Duration::from_millis(500);++/// Timeout for the idle probe's blocking watermark/committed fetches.+const PROBE_FETCH_TIMEOUT: Duration = Duration::from_secs(5);++/// Why a consumed seed payload is skipped rather than applied.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum SeedSkipReason {+ /// A kind this consumer does not handle (e.g. a `reconcile` control tile).+ UnknownKind,+ /// A newer schema version. The skip commits and never replays, so this consumer must be+ /// upgraded before any seeder emits a new schema.+ UnsupportedSchema,+ /// Empty or undecodable payload: deterministic bytes, so halting would wedge the partition.+ DecodeError,+}++impl SeedSkipReason {+ pub fn as_str(self) -> &'static str {+ match self {+ Self::UnknownKind => "unknown_kind",+ Self::UnsupportedSchema => "unsupported_schema",+ Self::DecodeError => "decode_error",+ }+ }+}++/// A decoded unit of seed work, routed to the owning partition worker.+#[derive(Debug)]+pub enum SeedWork {+ Tile(SeedTile),+ Skip(SeedSkipReason),+}++/// One message consumed from `cohort_stream_seed_events`, paired with its commit coordinates.+#[derive(Debug)]+pub struct ConsumedSeed {+ pub work: SeedWork,+ pub partition: i32,+ pub offset: i64,+}++impl ConsumedSeed {+ pub(crate) fn into_message(self) -> ShuffleMessage {+ ShuffleMessage::Seed {+ work: Box::new(self.work),+ offset: self.offset,+ }+ }++ /// Inverse of [`into_message`](Self::into_message); `None` for a non-seed message.+ pub(crate) fn from_message(partition: i32, message: ShuffleMessage) -> Option<Self> {+ match message {+ ShuffleMessage::Seed { work, offset } => Some(Self {+ work: *work,+ partition,+ offset,+ }),+ _ => None,+ }+ }++ /// The fence input; `None` for skips.+ fn s_chunk_ms(&self) -> Option<SChunkMs> {+ match &self.work {+ SeedWork::Tile(tile) => Some(tile.s_chunk_ms()),+ SeedWork::Skip(_) => None,+ }+ }+}++/// The apply-fence verdict for one tile.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum FenceDecision {+ Open,+ /// How far the watermark trails `s_chunk + margin`; `None` = no watermark at all.+ Closed {+ deficit_ms: Option<i64>,+ },+}++/// Open only when the watermark exceeds `s_chunk + margin`; an absent watermark is fail-closed.+pub(crate) fn fence_decision(+ watermark: Option<WatermarkMs>,+ s_chunk: SChunkMs,+ margin_ms: i64,+) -> FenceDecision {+ let Some(WatermarkMs(watermark_ms)) = watermark else {+ return FenceDecision::Closed { deficit_ms: None };+ };+ let bound = s_chunk.0.saturating_add(margin_ms);+ if watermark_ms > bound {+ FenceDecision::Open+ } else {+ FenceDecision::Closed {+ deficit_ms: Some(bound - watermark_ms),+ }+ }+}++/// A consumed batch split at the fence, preserving per-partition FIFO.+#[derive(Debug, Default)]+pub(crate) struct FenceSplit {+ pub admitted: Vec<ConsumedSeed>,+ pub held: HashMap<i32, Vec<ConsumedSeed>>,+ /// Deficit per partition whose fence closed in this split.+ pub deficits: HashMap<i32, Option<i64>>,+}++/// Admit each partition's open prefix; from the first fence-closed tile hold everything for that+/// partition (skips included) so nothing leapfrogs a held offset. `already_held` partitions queue+/// entirely behind their holdover.+pub(crate) fn split_at_fence(+ seeds: Vec<ConsumedSeed>,+ already_held: &HashSet<i32>,+ margin_ms: i64,+ watermark_of: impl Fn(i32) -> Option<WatermarkMs>,+) -> FenceSplit {+ let mut split = FenceSplit::default();+ let mut closed: HashSet<i32> = HashSet::new();+ for seed in seeds {+ let partition = seed.partition;+ if already_held.contains(&partition) || closed.contains(&partition) {+ split.held.entry(partition).or_default().push(seed);+ continue;+ }+ let decision = match seed.s_chunk_ms() {+ None => FenceDecision::Open,+ Some(s_chunk) => fence_decision(watermark_of(partition), s_chunk, margin_ms),+ };+ match decision {+ FenceDecision::Open => split.admitted.push(seed),+ FenceDecision::Closed { deficit_ms } => {+ closed.insert(partition);+ split.deficits.insert(partition, deficit_ms);+ split.held.entry(partition).or_default().push(seed);+ }+ }+ }+ split+}++/// Holdover of fence-closed or backpressured seeds.+type SeedHoldover = PartitionHoldover<ConsumedSeed>;++/// The holdover flattened in per-partition FIFO order.+fn drain_held(holdover: &mut SeedHoldover) -> Vec<ConsumedSeed> {+ holdover+ .take_held()+ .into_iter()+ .flat_map(|(_, seeds)| seeds)+ .collect()+}++/// The seed-topic follower consume loop. Commits go through the seed tracker ++/// `fsync_then_commit`, so a committed offset is a durably-applied tile.+pub struct SeedFollowerConsumer {+ consumer: Arc<StreamConsumer>,+ topic: String,+ /// The events group's consumer, shared for the idle probe's watermark + boot-committed reads.+ events_consumer: Arc<StreamConsumer<CohortConsumerContext>>,+ events_topic: String,+ dispatcher: Arc<EventDispatcher>,+ handle: Handle,+ pauser: Arc<dyn PartitionPauser>,+ recv_batch_size: usize,+ recv_batch_timeout: Duration,+ offset_commit_interval: Duration,+ fence_margin_ms: i64,+ idle_probe_interval: Duration,+}++impl SeedFollowerConsumer {+ #[allow(clippy::too_many_arguments)]+ pub fn new(+ consumer: Arc<StreamConsumer>,+ topic: String,+ events_consumer: Arc<StreamConsumer<CohortConsumerContext>>,+ events_topic: String,+ dispatcher: Arc<EventDispatcher>,+ handle: Handle,+ pauser: Arc<dyn PartitionPauser>,+ recv_batch_size: usize,+ recv_batch_timeout: Duration,+ offset_commit_interval: Duration,+ fence_margin_ms: i64,+ idle_probe_interval: Duration,+ ) -> Self {+ Self {+ consumer,+ topic,+ events_consumer,+ events_topic,+ dispatcher,+ handle,+ pauser,+ recv_batch_size,+ recv_batch_timeout,+ offset_commit_interval,+ fence_margin_ms,+ idle_probe_interval,+ }+ }++ pub async fn process(self) {+ let _guard = self.handle.process_scope();+ info!(topic = %self.topic, "seed follower consume loop starting");++ // Pause/resume off-loop: librdkafka's calls are synchronous FFI and must never delay+ // the heartbeat.+ let (pause_tx, pause_rx) = tokio::sync::mpsc::unbounded_channel::<HashSet<i32>>();+ let pauser_task = tokio::spawn(run_pauser_loop(self.pauser.clone(), pause_rx));++ let probe_task = tokio::spawn(run_idle_probe_loop(+ self.events_consumer.clone(),+ self.events_topic.clone(),+ self.dispatcher.clone(),+ self.idle_probe_interval,+ self.handle.clone(),+ ));++ let mut holdover = SeedHoldover::default();+ let mut prev_paused_target: HashSet<i32> = HashSet::new();+ let mut commit_deadline = tokio::time::Instant::now() + self.offset_commit_interval;++ loop {+ tokio::select! {+ biased;+ _ = self.handle.shutdown_recv() => {+ info!(topic = %self.topic, "shutdown signal received, stopping seed consume loop");+ break;+ }+ outcome = self.consume_batch() => {+ self.cycle(outcome, &mut holdover, &mut prev_paused_target, &pause_tx).await;+ let now = tokio::time::Instant::now();+ if now >= commit_deadline {+ fsync_then_commit(+ self.dispatcher.handle(),+ &self.consumer,+ &self.dispatcher.merge_deps().seed_tracker,+ self.owned_committable_offsets(),+ &self.topic,+ CommitMode::Async,+ )+ .await;+ commit_deadline = now + self.offset_commit_interval;+ }+ }+ }+ }++ drop(pause_tx);+ if let Err(err) = pauser_task.await {+ warn!(error = %err, "seed pauser task did not exit cleanly");+ }+ if let Err(err) = probe_task.await {+ warn!(error = %err, "seed idle-probe task did not exit cleanly");+ }++ fsync_then_commit(+ self.dispatcher.handle(),+ &self.consumer,+ &self.dispatcher.merge_deps().seed_tracker,+ self.owned_committable_offsets(),+ &self.topic,+ CommitMode::Sync,+ )+ .await;+ info!(topic = %self.topic, "seed follower consume loop stopped");+ }++ /// One non-blocking cycle: prune revoked holdover, re-fence and redispatch held seeds before+ /// fresh ones, dispatch the polled batch, reconcile the paused target and gauges.+ async fn cycle(+ &self,+ outcome: SeedConsumeOutcome,+ holdover: &mut SeedHoldover,+ prev_paused_target: &mut HashSet<i32>,+ pause_tx: &tokio::sync::mpsc::UnboundedSender<HashSet<i32>>,+ ) {+ histogram!(COHORT_STREAM_SEEDS_CONSUME_BATCH_SIZE).record(outcome.seeds.len() as f64);+ if !outcome.seeds.is_empty() {+ counter!(COHORT_STREAM_SEEDS_CONSUMED).increment(outcome.seeds.len() as u64);+ }+ if outcome.deserialize_errors > 0 {+ counter!(COHORT_STREAM_SEED_DESERIALIZE_ERRORS).increment(outcome.deserialize_errors);+ }++ let owned = self.dispatcher.owned_set();+ holdover.prune_revoked(&owned);+ let watermarks = self.dispatcher.merge_deps().live_watermarks.clone();+ let watermark_of = |partition: i32| watermarks.get(partition);++ // Held before fresh; the channel-full remainder re-absorbs before the still-fenced+ // suffix so per-partition FIFO holds.+ let refence = split_at_fence(+ drain_held(holdover),+ &HashSet::new(),+ self.fence_margin_ms,+ watermark_of,+ );+ let still_full = self.dispatcher.dispatch_seeds(refence.admitted);+ holdover.absorb(still_full);+ holdover.absorb(refence.held);++ // Fresh seeds queue behind held partitions rather than leapfrogging older offsets.+ let fresh = split_at_fence(+ outcome.seeds,+ &holdover.held_partitions(),+ self.fence_margin_ms,+ watermark_of,+ );+ let fresh_full = self.dispatcher.dispatch_seeds(fresh.admitted);+ holdover.absorb(fresh_full);+ holdover.absorb(fresh.held);++ for (partition, deficit) in refence.deficits.into_iter().chain(fresh.deficits) {+ if let Some(deficit_ms) = deficit {+ gauge!(SEED_FENCE_DEFICIT_MS, "partition" => partition.to_string())+ .set(deficit_ms as f64);+ }+ }+ let now_ms = chrono::Utc::now().timestamp_millis();+ for &partition in &owned {+ if let Some(WatermarkMs(watermark_ms)) = watermarks.get(partition) {+ gauge!(LIVE_WATERMARK_AGE_MS, "partition" => partition.to_string())+ .set(now_ms.saturating_sub(watermark_ms) as f64);+ }+ }++ let target = holdover.held_partitions();+ if !target.is_empty() || !prev_paused_target.is_empty() {+ for partition in prev_paused_target.difference(&target) {+ // Zero the deficit for drained partitions so the gauge clears.+ gauge!(SEED_FENCE_DEFICIT_MS, "partition" => partition.to_string()).set(0.0);+ }+ if pause_tx.send(target.clone()).is_err() {+ debug!("seed pauser task has exited; skipping a pause/resume update");+ }+ *prev_paused_target = target;+ }+ gauge!(SEED_FENCED_PARTITIONS).set(holdover.held_partition_count() as f64);++ if outcome.transport_error {+ tokio::time::sleep(RECV_ERROR_BACKOFF).await;+ } else {+ self.handle.report_healthy();+ }+ }++ async fn consume_batch(&self) -> SeedConsumeOutcome {+ let mut outcome = SeedConsumeOutcome {+ seeds: Vec::with_capacity(self.recv_batch_size),+ deserialize_errors: 0,+ transport_error: false,+ };++ tokio::select! {+ _ = tokio::time::sleep(self.recv_batch_timeout) => {}+ _ = async {+ while outcome.seeds.len() < self.recv_batch_size {+ match self.consumer.recv().await {+ Ok(message) => {+ let partition = message.partition();+ let offset = message.offset();+ let work = decode_payload(message.payload(), partition, offset);+ if matches!(work, SeedWork::Skip(SeedSkipReason::DecodeError)) {+ outcome.deserialize_errors += 1;+ }+ outcome.seeds.push(ConsumedSeed { work, partition, offset });+ }+ Err(err) => {+ outcome.transport_error = true;+ counter!(COHORT_STREAM_KAFKA_RECV_ERRORS).increment(1);+ warn!(topic = %self.topic, error = %err, "kafka recv error while consuming seed topic");+ break;+ }+ }+ }+ } => {}+ }++ outcome+ }++ fn owned_committable_offsets(&self) -> HashMap<i32, i64> {+ owned_committable_offsets(&self.dispatcher.merge_deps().seed_tracker, &self.dispatcher)+ }+}++/// Decode one payload; every non-tile outcome is a channel-riding skip so its offset marks in+/// order.+fn decode_payload(payload: Option<&[u8]>, partition: i32, offset: i64) -> SeedWork {+ let Some(payload) = payload else {+ debug!(+ partition,+ offset, "skipping seed message with empty payload"+ );+ return SeedWork::Skip(SeedSkipReason::DecodeError);+ };+ match decode_seed(payload) {+ Ok(DecodedSeed::Tile(tile)) => SeedWork::Tile(tile),+ Ok(DecodedSeed::UnknownKind { kind, .. }) => {+ debug!(partition, offset, kind, "skipping seed of unknown kind");+ SeedWork::Skip(SeedSkipReason::UnknownKind)+ }+ Ok(DecodedSeed::UnsupportedSchema {+ kind,+ schema_version,+ }) => {+ debug!(+ partition,+ offset, kind, schema_version, "skipping seed at unsupported schema version",+ );+ SeedWork::Skip(SeedSkipReason::UnsupportedSchema)+ }+ Err(err) => {+ debug!(partition, offset, error = %err, "skipping undeserializable seed message");+ SeedWork::Skip(SeedSkipReason::DecodeError)+ }+ }+}++struct SeedConsumeOutcome {+ seeds: Vec<ConsumedSeed>,+ deserialize_errors: u64,+ transport_error: bool,+}++/// Advance idle partitions' watermarks: once everything retained is folded, "now" is a valid+/// arrival bound. Accepted residual: a silent shuffler stall longer than the margin opens the+/// fence early, surfaced via the watermark-age gauge + shuffler-lag alerting.+async fn run_idle_probe_loop(+ events_consumer: Arc<StreamConsumer<CohortConsumerContext>>,+ events_topic: String,+ dispatcher: Arc<EventDispatcher>,+ interval: Duration,+ handle: Handle,+) {+ let mut ticker = tokio::time::interval(interval);+ ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);+ // Skip the immediate first tick so the probe never races boot recovery.+ ticker.tick().await;+ loop {+ tokio::select! {+ biased;+ _ = handle.shutdown_recv() => break,+ _ = ticker.tick() => {+ let owned = dispatcher.owned_partitions();+ if owned.is_empty() {+ continue;+ }+ let folded = dispatcher.events_tracker().committable_offsets();+ let consumer = events_consumer.clone();+ let topic = events_topic.clone();+ let probe = tokio::task::spawn_blocking(move || {+ probe_idle_partitions(consumer.as_ref(), &topic, &owned, &folded)+ });+ // Race against shutdown: the blocking fetch can spend ~5 s per partition against+ // an unresponsive broker.+ let probed = tokio::select! {+ biased;+ _ = handle.shutdown_recv() => break,+ probed = probe => probed,+ };+ match probed {+ Ok(idle_partitions) => {+ let now_ms = chrono::Utc::now().timestamp_millis();+ advance_probed_idle(+ &dispatcher.merge_deps().live_watermarks,+ &dispatcher.owned_set(),+ idle_partitions,+ now_ms,+ );+ }+ Err(err) => warn!(error = %err, "seed idle probe task failed"),+ }+ }+ }+ }+}++/// Advance probed-idle watermarks, re-checking ownership at advance time: the probe's snapshot is+/// stale by up to the blocking fetch, and re-creating an entry a mid-probe revoke forgot would+/// open the fence for a later tenure before its replayed events fold. The assign path forgets+/// independently, covering the residual race.+fn advance_probed_idle(+ watermarks: &crate::partitions::watermarks::LiveWatermarks,+ owned_now: &HashSet<i32>,+ idle_partitions: Vec<i32>,+ now_ms: i64,+) {+ for partition in idle_partitions {+ if owned_now.contains(&partition) {+ watermarks.advance_idle(partition, now_ms);+ }+ }+}++/// Blocking half of the idle probe: compare each owned partition's high watermark to the folded+/// frontier, falling back to the events group's committed offset before any fold this tenure.+/// Errors skip the partition (fence stays closed).+fn probe_idle_partitions<C: rdkafka::consumer::ConsumerContext + 'static>(+ consumer: &StreamConsumer<C>,+ topic: &str,+ owned: &[i32],+ folded: &HashMap<i32, i64>,+) -> Vec<i32> {+ let unfolded: Vec<i32> = owned+ .iter()+ .copied()+ .filter(|partition| !folded.contains_key(partition))+ .collect();+ let committed: HashMap<i32, i64> = if unfolded.is_empty() {+ HashMap::new()+ } else {+ let mut tpl = TopicPartitionList::new();+ for &partition in &unfolded {+ tpl.add_partition(topic, partition);+ }+ match consumer.committed_offsets(tpl, PROBE_FETCH_TIMEOUT) {+ Ok(tpl) => tpl+ .elements_for_topic(topic)+ .iter()+ .filter_map(|elem| match elem.offset() {+ Offset::Offset(next) => Some((elem.partition(), next)),+ _ => None,+ })+ .collect(),+ Err(err) => {+ warn!(topic, error = %err, "idle probe: committed-offset fetch failed; boot-edge partitions stay fenced");+ HashMap::new()+ }+ }+ };++ let mut idle = Vec::new();+ for &partition in owned {+ let (low, high) = match consumer.fetch_watermarks(topic, partition, PROBE_FETCH_TIMEOUT) {+ Ok(bounds) => bounds,+ Err(err) => {+ debug!(topic, partition, error = %err, "idle probe: watermark fetch failed; partition stays fenced");+ continue;+ }+ };+ let frontier = folded+ .get(&partition)+ .copied()+ .or_else(|| committed.get(&partition).copied());+ if frontier_is_caught_up(frontier, low, high) {+ idle.push(partition);+ }+ }+ idle+}++/// Whether every retained live message is behind the folded frontier (a next-to-consume offset).+/// No frontier is idle only with nothing retained. A wrong `true` opens the fence over unfolded+/// live events.+fn frontier_is_caught_up(frontier: Option<i64>, low: i64, high: i64) -> bool {+ match frontier {+ Some(next) => next >= high,+ None => high == low,+ }+}++#[cfg(test)]+mod tests {+ use std::num::NonZeroU32;++ use cohort_core::seed::{ClaimEpoch, ConditionHash, RunId, SChunkMs};+ use uuid::Uuid;++ use crate::filters::TeamId;+ use crate::partitions::watermarks::LiveWatermarks;++ use super::*;++ const MARGIN_MS: i64 = 600_000;++ fn tile_at(s_chunk_ms: i64) -> SeedTile {+ SeedTile::new(+ TeamId(2),+ Uuid::from_u128(7),+ ConditionHash::parse("0123456789abcdef").unwrap(),+ NonZeroU32::new(1).unwrap(),+ 20_614,+ SChunkMs(s_chunk_ms),+ RunId(Uuid::nil()),+ ClaimEpoch(1),+ )+ }++ fn seed(partition: i32, offset: i64, s_chunk_ms: i64) -> ConsumedSeed {+ ConsumedSeed {+ work: SeedWork::Tile(tile_at(s_chunk_ms)),+ partition,+ offset,+ }+ }++ fn skip(partition: i32, offset: i64) -> ConsumedSeed {+ ConsumedSeed {+ work: SeedWork::Skip(SeedSkipReason::UnknownKind),+ partition,+ offset,+ }+ }++ fn offsets(seeds: &[ConsumedSeed]) -> Vec<i64> {+ seeds.iter().map(|seed| seed.offset).collect()+ }++ #[test]+ fn fence_decision_table_pins_the_boundary_arithmetic() {+ let s_chunk = SChunkMs(1_000_000);+ // No watermark at all: fail-closed with an unknown deficit.+ assert_eq!(+ fence_decision(None, s_chunk, MARGIN_MS),+ FenceDecision::Closed { deficit_ms: None },+ );+ // Exactly at the bound is still closed — the watermark must *exceed* s_chunk + margin.+ assert_eq!(+ fence_decision(Some(WatermarkMs(1_000_000 + MARGIN_MS)), s_chunk, MARGIN_MS),+ FenceDecision::Closed {+ deficit_ms: Some(0)+ },+ );+ assert_eq!(+ fence_decision(+ Some(WatermarkMs(1_000_000 + MARGIN_MS + 1)),+ s_chunk,+ MARGIN_MS+ ),+ FenceDecision::Open,+ );+ assert_eq!(+ fence_decision(Some(WatermarkMs(900_000)), s_chunk, MARGIN_MS),+ FenceDecision::Closed {+ deficit_ms: Some(100_000 + MARGIN_MS)+ },+ );+ // A far-future s_chunk must not overflow the bound arithmetic.+ assert_eq!(+ fence_decision(Some(WatermarkMs(i64::MAX)), SChunkMs(i64::MAX), MARGIN_MS),+ FenceDecision::Closed {+ deficit_ms: Some(0)+ },+ );+ }++ #[test]+ fn split_admits_the_open_prefix_and_holds_everything_from_the_first_closed_tile() {+ let watermarks = LiveWatermarks::new();+ // Partition 1's watermark clears s_chunk 100 but not 10_000_000.+ watermarks.observe(1, 100 + MARGIN_MS + 1);+ let batch = vec![+ seed(1, 10, 100), // open+ skip(1, 11), // skip in the open prefix: admitted+ seed(1, 12, 10_000_000), // closed → holds from here+ skip(1, 13), // skip AFTER the closed tile: held, FIFO preserved+ seed(1, 14, 100), // would be open, but queues behind the held offset+ ];++ let split = split_at_fence(batch, &HashSet::new(), MARGIN_MS, |p| watermarks.get(p));++ assert_eq!(offsets(&split.admitted), vec![10, 11]);+ assert_eq!(offsets(&split.held[&1]), vec![12, 13, 14]);+ assert_eq!(+ split.deficits[&1],+ Some(10_000_000 + MARGIN_MS - (100 + MARGIN_MS + 1))+ );+ }++ #[test]+ fn split_holds_everything_for_an_absent_watermark_except_leading_skips() {+ let batch = vec![skip(3, 1), seed(3, 2, 0), skip(3, 3)];++ let split = split_at_fence(batch, &HashSet::new(), MARGIN_MS, |_| None);++ assert_eq!(+ offsets(&split.admitted),+ vec![1],+ "a leading skip is always admitted; it cannot double-count anything",+ );+ assert_eq!(offsets(&split.held[&3]), vec![2, 3]);+ assert_eq!(split.deficits[&3], None, "no watermark → unknown deficit");+ }++ #[test]+ fn split_queues_an_already_held_partition_entirely_behind_its_holdover() {+ let watermarks = LiveWatermarks::new();+ watermarks.observe(5, i64::MAX); // fence wide open+ let batch = vec![seed(5, 20, 0), skip(5, 21)];++ let split = split_at_fence(batch, &HashSet::from([5]), MARGIN_MS, |p| watermarks.get(p));++ assert!(split.admitted.is_empty(), "nothing leapfrogs a held offset");+ assert_eq!(offsets(&split.held[&5]), vec![20, 21]);+ }++ #[test]+ fn split_isolates_partitions_from_each_other() {+ let watermarks = LiveWatermarks::new();+ watermarks.observe(1, i64::MAX);+ // Partition 2 has no watermark: closed.+ let batch = vec![seed(1, 1, 0), seed(2, 1, 0), seed(1, 2, 0)];++ let split = split_at_fence(batch, &HashSet::new(), MARGIN_MS, |p| watermarks.get(p));++ assert_eq!(offsets(&split.admitted), vec![1, 2]);+ assert!(split.admitted.iter().all(|seed| seed.partition == 1));+ assert_eq!(offsets(&split.held[&2]), vec![1]);+ }++ #[test]+ fn holdover_absorb_take_preserves_per_partition_fifo_and_prunes_revoked() {+ let mut holdover = SeedHoldover::default();+ holdover.absorb(HashMap::from([(1, vec![seed(1, 10, 0), seed(1, 11, 0)])]));+ holdover.absorb(HashMap::from([+ (1, vec![seed(1, 12, 0)]),+ (2, vec![seed(2, 5, 0)]),+ ]));++ assert_eq!(holdover.held_partitions(), HashSet::from([1, 2]));+ assert_eq!(holdover.held_partition_count(), 2);++ holdover.prune_revoked(&HashSet::from([1]));+ assert_eq!(holdover.held_partitions(), HashSet::from([1]));++ let taken = drain_held(&mut holdover);+ assert_eq!(+ offsets(&taken),+ vec![10, 11, 12],+ "FIFO within the partition"+ );+ assert!(holdover.held_partitions().is_empty());+ }++ #[test]+ fn decode_payload_classifies_tiles_skips_and_garbage() {+ let tile = tile_at(1_700_000_000_000);+ let bytes = serde_json::to_vec(&tile).unwrap();+ assert!(matches!(+ decode_payload(Some(&bytes), 0, 0),+ SeedWork::Tile(decoded) if decoded == tile,+ ));++ let mut reconcile = serde_json::to_value(&tile).unwrap();+ reconcile["kind"] = serde_json::json!("reconcile");+ let bytes = serde_json::to_vec(&reconcile).unwrap();+ assert!(matches!(+ decode_payload(Some(&bytes), 0, 0),+ SeedWork::Skip(SeedSkipReason::UnknownKind),+ ));++ let mut newer = serde_json::to_value(&tile).unwrap();+ newer["schema_version"] = serde_json::json!(2);+ let bytes = serde_json::to_vec(&newer).unwrap();+ assert!(matches!(+ decode_payload(Some(&bytes), 0, 0),+ SeedWork::Skip(SeedSkipReason::UnsupportedSchema),+ ));++ assert!(matches!(+ decode_payload(Some(b"not json"), 0, 0),+ SeedWork::Skip(SeedSkipReason::DecodeError),+ ));+ assert!(matches!(+ decode_payload(None, 0, 0),+ SeedWork::Skip(SeedSkipReason::DecodeError),+ ));+ }++ #[test]+ fn consumed_seed_round_trips_through_its_shuffle_message() {+ let consumed = seed(9, 42, 123);+ let message = consumed.into_message();+ assert_eq!(message.seed_offset(), Some(42));+ let back = ConsumedSeed::from_message(9, message).unwrap();+ assert_eq!(back.partition, 9);+ assert_eq!(back.offset, 42);+ assert!(matches!(back.work, SeedWork::Tile(tile) if tile.s_chunk_ms() == SChunkMs(123)));++ let not_seed = ShuffleMessage::RedrivePendingTransfers;+ assert!(ConsumedSeed::from_message(9, not_seed).is_none());+ }++ /// A wrong `true` declares a partition with unfolded live events idle — the fence's+ /// fail-open direction.+ #[test]+ fn frontier_is_caught_up_table() {+ let cases = [+ (+ Some(10),+ 0,+ 10,+ true,+ "folded frontier at the high watermark",+ ),+ (Some(9), 0, 10, false, "one retained message unfolded"),+ (+ Some(11),+ 0,+ 10,+ true,+ "frontier past the watermark (post-truncation)",+ ),+ (Some(0), 0, 0, true, "empty partition with a zero frontier"),+ (+ None,+ 5,+ 5,+ true,+ "boot edge: nothing retained, nothing committed",+ ),+ (None, 0, 0, true, "boot edge: never-produced partition"),+ (+ None,+ 4,+ 10,+ false,+ "no frontier with retained messages stays fenced",+ ),+ ];+ for (frontier, low, high, expected, why) in cases {+ assert_eq!(+ frontier_is_caught_up(frontier, low, high),+ expected,+ "{why}"+ );+ }+ }++ /// A revoke mid-probe forgot the watermark; the advance-time re-check must not re-create it.+ #[test]+ fn probe_advance_never_recreates_a_watermark_revoked_mid_probe() {+ let watermarks = LiveWatermarks::new();+ watermarks.observe(5, 1_000);+ watermarks.observe(6, 1_000);++ // Mid-probe: partition 5 is revoked and forgotten; the probe's stale snapshot still+ // reports both partitions idle.+ watermarks.forget_partition(5);+ let owned_now = HashSet::from([6]);+ advance_probed_idle(&watermarks, &owned_now, vec![5, 6], 2_000);++ assert_eq!(+ watermarks.get(5),+ None,+ "the revoked partition stays fail-closed",+ );+ assert_eq!(+ watermarks.get(6),+ Some(WatermarkMs(2_000)),+ "the still-owned partition advances",+ );+ }+}diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rsindex 454303c3c866..154f8fc6ae9e 100644--- a/rust/cohort-stream-processor/src/main.rs+++ b/rust/cohort-stream-processor/src/main.rs@@ -18,7 +18,7 @@ use tracing_subscriber::{fmt, EnvFilter, Layer};use cohort_stream_processor::config::Config;use cohort_stream_processor::consumers::{CascadeRoute, CohortStreamEventsConsumer, EventDispatcher, FollowerConsumer, FollowerRoute,- MergeRoute, TransferRoute,+ MergeRoute, SeedFollowerConsumer, TransferRoute,};use cohort_stream_processor::filters::{run_refresh_loop, CatalogHandle};use cohort_stream_processor::merge::gc::MergeGcSweeper;@@ -27,12 +27,13 @@ use cohort_stream_processor::observability;use cohort_stream_processor::observability::store_stats::StoreStatsSweeper;use cohort_stream_processor::observability::tokio_monitor::TokioRuntimeMonitor;use cohort_stream_processor::partitions::{- run_rebalance_worker, CohortConsumerContext, Follower, FollowerSet, OffsetTracker,- PartitionRouter,+ run_rebalance_worker, CohortConsumerContext, ConsumerPauser, Follower, FollowerSet,+ LiveWatermarks, OffsetTracker, PartitionPauser, PartitionRouter,};use cohort_stream_processor::producer::{- CascadeSink, KafkaCascadeSink, KafkaMembershipSink, KafkaStreamEventSink, KafkaTransferSink,- MembershipSink, NoopCascadeSink, StreamEventSink, TransferSink,+ CascadeSink, KafkaCascadeSink, KafkaMembershipSink, KafkaSeedTileSink, KafkaStreamEventSink,+ KafkaTransferSink, MembershipSink, NoopCascadeSink, NoopSeedTileSink, SeedTileSink,+ StreamEventSink, TransferSink,};use cohort_stream_processor::store::durability::{run_boot_restore, upload_cadence, CheckpointExporter, CheckpointSweeper, OffsetManifest,@@ -101,6 +102,12 @@ async fn async_main(config: Config) -> Result<()> {ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(30)),)});+ let seed_follower_handle = config.cohort_seed_consumer_enabled.then(|| {+ manager.register(+ "seed-follower",+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(30)),+ )+ });// Short graceful window: it holds no state and its next tick is disposable.let tokio_monitor_handle = manager.register("tokio-runtime-monitor",@@ -197,6 +204,18 @@ async fn async_main(config: Config) -> Result<()> {} else {Arc::new(NoopCascadeSink)};+ let seed_tile_sink: Arc<dyn SeedTileSink> = if config.cohort_seed_consumer_enabled {+ Arc::new(+ KafkaSeedTileSink::new(+ &kafka_config,+ config.cohort_stream_seed_events_topic.clone(),+ )+ .await+ .context("creating cohort_stream_seed_events re-key producer")?,+ )+ } else {+ Arc::new(NoopSeedTileSink)+ };let merge_deps = Arc::new(MergeWorkerDeps {transfer_sink,stream_event_sink,@@ -209,6 +228,10 @@ async fn async_main(config: Config) -> Result<()> {cascade_tracker: Arc::new(OffsetTracker::new()),cascade: config.cascade_config(),partition_count: config.cohort_partition_count,+ seed_tile_sink,+ seed_tracker: Arc::new(OffsetTracker::new()),+ // Unconditional (cheap): the event path observes regardless of the seed gate.+ live_watermarks: Arc::new(LiveWatermarks::new()),});// Cheap `Arc` clones taken before the originals move into the dispatcher: the checkpoint sweeper@@ -221,6 +244,7 @@ async fn async_main(config: Config) -> Result<()> {let merge_tracker_for_checkpoint = merge_deps.merge_tracker.clone();let transfer_tracker_for_checkpoint = merge_deps.transfer_tracker.clone();let cascade_tracker_for_checkpoint = merge_deps.cascade_tracker.clone();+ let seed_tracker_for_checkpoint = merge_deps.seed_tracker.clone();let handle = StoreHandle::new(store, config.offload_config());let handle_for_stats = handle.clone();@@ -249,6 +273,8 @@ async fn async_main(config: Config) -> Result<()> {stream_consumer.subscribe(&[config.cohort_stream_events_topic.as_str()]).context("subscribing to cohort_stream_events")?;+ // Shared with the seed consumer's idle probe.+ let stream_consumer = Arc::new(stream_consumer);let merges_follower_consumer: Arc<StreamConsumer> = Arc::new(config@@ -273,6 +299,18 @@ async fn async_main(config: Config) -> Result<()> {} else {None};+ // Gated: a gate-off deploy is safe without the seed topic existing at all.+ let seed_follower_consumer: Option<Arc<StreamConsumer>> = if config.cohort_seed_consumer_enabled+ {+ Some(Arc::new(+ config+ .follower_client_config(&config.kafka_seed_consumer_group)+ .create()+ .context("creating cohort_stream_seed_events follower consumer")?,+ ))+ } else {+ None+ };let events_partitions =fetch_partition_count(&stream_consumer, &config.cohort_stream_events_topic)?;@@ -320,6 +358,19 @@ async fn async_main(config: Config) -> Result<()> {cascade_partitions,);}+ // A tile must land on the partition owning its person's state slice.+ if let Some(seed_consumer) = &seed_follower_consumer {+ let seed_partitions =+ fetch_partition_count(seed_consumer, &config.cohort_stream_seed_events_topic)?;+ anyhow::ensure!(+ seed_partitions as u32 == config.cohort_partition_count,+ "cohort_stream_seed_events must be co-partitioned with {} at COHORT_PARTITION_COUNT={}: {} has {}",+ config.cohort_stream_events_topic,+ config.cohort_partition_count,+ config.cohort_stream_seed_events_topic,+ seed_partitions,+ );+ }if let Some(manifest) = restore.manifest.as_ref() {commit_follower_offsets_from_manifest(@@ -339,6 +390,15 @@ async fn async_main(config: Config) -> Result<()> {manifest,);}+ // State rolls back to the snapshot, so the seed offsets must roll back with it or the+ // in-between tiles never replay.+ if let Some(seed_consumer) = &seed_follower_consumer {+ commit_follower_offsets_from_manifest(+ seed_consumer,+ &config.cohort_stream_seed_events_topic,+ manifest,+ );+ }}let mut follower_mirrors = vec![@@ -357,6 +417,12 @@ async fn async_main(config: Config) -> Result<()> {config.cohort_cascade_events_topic.clone(),));}+ if let Some(seed_consumer) = &seed_follower_consumer {+ follower_mirrors.push(Follower::new(+ seed_consumer.clone(),+ config.cohort_stream_seed_events_topic.clone(),+ ));+ }let followers = Arc::new(FollowerSet::new(follower_mirrors));let (consumer_command_tx, consumer_command_rx) = mpsc::unbounded_channel();@@ -462,6 +528,12 @@ async fn async_main(config: Config) -> Result<()> {cascade_tracker_for_checkpoint,));}+ if config.cohort_seed_consumer_enabled {+ trackers.push((+ config.cohort_stream_seed_events_topic.clone(),+ seed_tracker_for_checkpoint,+ ));+ }tokio::spawn(run_sweep_loop(CheckpointSweeper::new(store_for_checkpoint,@@ -515,6 +587,37 @@ async fn async_main(config: Config) -> Result<()> {spawn_follower_after_catalog_load(catalog.clone(), cascade_follower, cascade_handle);}+ if let (Some(seed_consumer), Some(seed_handle)) = (seed_follower_consumer, seed_follower_handle)+ {+ let seed_topic = config.cohort_stream_seed_events_topic.clone();+ let pauser: Arc<dyn PartitionPauser> = Arc::new(ConsumerPauser::new(+ seed_consumer.clone(),+ seed_topic.clone(),+ ));+ let seed_follower = SeedFollowerConsumer::new(+ seed_consumer,+ seed_topic,+ stream_consumer.clone(),+ config.cohort_stream_events_topic.clone(),+ dispatcher.clone(),+ seed_handle.clone(),+ pauser,+ config.recv_batch_size,+ config.recv_batch_timeout(),+ config.offset_commit_interval(),+ config.cohort_seed_fence_margin_ms,+ config.seed_idle_probe_interval(),+ );+ let seed_catalog = catalog.clone();+ tokio::spawn(async move {+ tokio::select! {+ biased;+ _ = seed_handle.shutdown_recv() => {}+ _ = seed_catalog.wait_until_loaded() => seed_follower.process().await,+ }+ });+ }+let events_consumer = CohortStreamEventsConsumer::new(stream_consumer,config.cohort_stream_events_topic.clone(),@@ -665,6 +768,10 @@ fn log_startup(config: &Config) {cohort_cascade_enabled = config.cohort_cascade_enabled,cascade_topic = %config.cohort_cascade_events_topic,cascade_consumer_group = %config.kafka_cascade_consumer_group,+ cohort_seed_consumer_enabled = config.cohort_seed_consumer_enabled,+ seed_topic = %config.cohort_stream_seed_events_topic,+ seed_consumer_group = %config.kafka_seed_consumer_group,+ seed_fence_margin_ms = config.cohort_seed_fence_margin_ms,"starting cohort-stream-processor",);}diff --git a/rust/cohort-stream-processor/src/merge/tombstone_redirect.rs b/rust/cohort-stream-processor/src/merge/tombstone_redirect.rsindex 240145055427..aa79c1cf35b7 100644--- a/rust/cohort-stream-processor/src/merge/tombstone_redirect.rs+++ b/rust/cohort-stream-processor/src/merge/tombstone_redirect.rs@@ -16,7 +16,7 @@ use crate::filters::TeamId;use crate::merge::transfer::Tombstone;use crate::observability::metrics::MERGE_TOMBSTONE_REDIRECTS_TOTAL;use crate::partitions::partitioner::partition_of;-use crate::store::{CohortStore, StoreError, StoreHandle, TombstoneKey};+use crate::store::{CohortStore, ReadLane, StoreError, StoreHandle, TombstoneKey};/// Defensive bound on same-partition tombstone hops in one [`resolve`] call.const MAX_TOMBSTONE_HOPS: usize = 16;@@ -117,20 +117,20 @@ fn read_tombstone(}}-/// Async twin of [`resolve`] over the [`StoreHandle`] facade: identical tombstone walk,-/// [`Resolution`] semantics, and [`MAX_TOMBSTONE_HOPS`] cap, but each hop reads through the Event-/// lane so the store I/O runs on the blocking pool. Used by the event-path worker; drain/apply call-/// the sync [`resolve`] inside their `run_section` closures.+/// Async twin of [`resolve`] over the [`StoreHandle`] facade; each hop reads on the caller's+/// `lane`. Drain/apply call the sync [`resolve`] inside their `run_section` closures.pub async fn resolve_offloaded(handle: &StoreHandle,partition_id: u16,team_id: TeamId,person: Uuid,partition_count: u32,+ lane: ReadLane,) -> Result<Resolution, StoreError> {let team = team_id.0 as u64;- let Some(first) = read_tombstone_offloaded(handle, partition_id, team, person).await? else {+ let Some(first) = read_tombstone_offloaded(handle, partition_id, team, person, lane).await?+ else {return Ok(Resolution::NotMerged);};@@ -145,7 +145,7 @@ pub async fn resolve_offloaded(origin,});}- match read_tombstone_offloaded(handle, partition_id, team, current).await? {+ match read_tombstone_offloaded(handle, partition_id, team, current, lane).await? {Some(next) => current = next.new_person,None => {return Ok(Resolution::Inline {@@ -169,19 +169,20 @@ pub async fn resolve_offloaded(})}-/// Read and decode one tombstone through the Event lane, or `None` when absent or corrupt.+/// Read and decode one tombstone, or `None` when absent or corrupt.async fn read_tombstone_offloaded(handle: &StoreHandle,partition_id: u16,team: u64,person: Uuid,+ lane: ReadLane,) -> Result<Option<Tombstone>, StoreError> {let key = TombstoneKey {partition_id,team_id: team,person,};- let Some(bytes) = handle.get_tombstone(&key).await? else {+ let Some(bytes) = handle.get_tombstone(&key, lane).await? else {return Ok(None);};match Tombstone::decode(&bytes) {diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rsindex 886f1ceb08bb..6d70a74e664f 100644--- a/rust/cohort-stream-processor/src/observability/metrics.rs+++ b/rust/cohort-stream-processor/src/observability/metrics.rs@@ -431,6 +431,41 @@ pub const STAGE2_ORPHAN_GC_UNDECODABLE_KEYS_TOTAL: &str = "stage2_orphan_gc_unde/// `popped == evicted + dropped`.pub const SWEEP_KEYS_DROPPED_TOTAL: &str = "sweep_keys_dropped_total";+/// Seed payloads consumed and decoded — tiles and ordered skips both (counter).+pub const COHORT_STREAM_SEEDS_CONSUMED: &str = "cohort_stream_seeds_consumed_total";+/// Seed payloads that were empty or failed to decode (counter).+pub const COHORT_STREAM_SEED_DESERIALIZE_ERRORS: &str =+ "cohort_stream_seed_deserialize_errors_total";+/// Decoded seed payloads accumulated per consume → dispatch cycle (histogram).+pub const COHORT_STREAM_SEEDS_CONSUME_BATCH_SIZE: &str = "cohort_stream_seeds_consume_batch_size";+/// Seed messages dropped because the partition is no longer owned or shutdown is draining (counter).+pub const COHORT_STREAM_SEEDS_SKIPPED_NOT_OWNED: &str =+ "cohort_stream_seeds_skipped_not_owned_total";+/// Tile applies that advanced a leaf's state, labelled by `variant` (counter).+pub const SEED_TILES_APPLIED_TOTAL: &str = "cohort_seed_tiles_applied_total";+/// Tile applies that left the leaf byte-identical (the idempotency path), labelled by `variant`+/// (counter).+pub const SEED_TILES_UNCHANGED_TOTAL: &str = "cohort_seed_tiles_unchanged_total";+/// Tile leaf-applies dropped without a write, labelled by `reason` (counter).+pub const SEED_TILES_DROPPED_TOTAL: &str = "cohort_seed_tiles_dropped_total";+/// Consume-side skips marked in order, labelled by `reason` (counter).+pub const SEED_TILES_SKIPPED_TOTAL: &str = "cohort_seed_tiles_skipped_total";+/// Tiles re-produced to a merge survivor's partition, counted post-ack (counter).+pub const SEED_REKEYED_TOTAL: &str = "cohort_seed_rekeyed_total";+/// Failed tile re-key produces; the seed offset is held (counter).+pub const SEED_REKEY_PRODUCE_FAILURE_TOTAL: &str = "cohort_seed_rekey_produce_failure_total";+/// Hop-capped tile redirects applied inline (counter). Non-zero means a corrupt tombstone cycle.+pub const SEED_REKEY_HOP_CAPPED_TOTAL: &str = "cohort_seed_rekey_hop_capped_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";+/// Seed partitions currently held, fence-closed or backpressured (gauge).+pub const SEED_FENCED_PARTITIONS: &str = "cohort_seed_fenced_partitions";+/// How far the watermark trails `s_chunk + margin` per fenced partition (gauge, ms).+pub const SEED_FENCE_DEFICIT_MS: &str = "cohort_seed_fence_deficit_ms";+/// Age of each owned partition's live watermark, labelled by `partition` (gauge, ms).+pub const LIVE_WATERMARK_AGE_MS: &str = "cohort_live_watermark_age_ms";+/// Install the global Prometheus recorder. Call once at startup.////// # Panics@@ -635,6 +670,47 @@ mod tests {);}+ #[test]+ fn seed_metric_names_are_stable() {+ assert_eq!(+ COHORT_STREAM_SEEDS_CONSUMED,+ "cohort_stream_seeds_consumed_total"+ );+ assert_eq!(+ COHORT_STREAM_SEED_DESERIALIZE_ERRORS,+ "cohort_stream_seed_deserialize_errors_total",+ );+ assert_eq!(+ COHORT_STREAM_SEEDS_CONSUME_BATCH_SIZE,+ "cohort_stream_seeds_consume_batch_size",+ );+ assert_eq!(+ COHORT_STREAM_SEEDS_SKIPPED_NOT_OWNED,+ "cohort_stream_seeds_skipped_not_owned_total",+ );+ assert_eq!(SEED_TILES_APPLIED_TOTAL, "cohort_seed_tiles_applied_total");+ assert_eq!(+ SEED_TILES_UNCHANGED_TOTAL,+ "cohort_seed_tiles_unchanged_total"+ );+ assert_eq!(SEED_TILES_DROPPED_TOTAL, "cohort_seed_tiles_dropped_total");+ assert_eq!(SEED_TILES_SKIPPED_TOTAL, "cohort_seed_tiles_skipped_total");+ assert_eq!(SEED_REKEYED_TOTAL, "cohort_seed_rekeyed_total");+ assert_eq!(+ SEED_REKEY_PRODUCE_FAILURE_TOTAL,+ "cohort_seed_rekey_produce_failure_total",+ );+ assert_eq!(+ SEED_REKEY_HOP_CAPPED_TOTAL,+ "cohort_seed_rekey_hop_capped_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");+ assert_eq!(SEED_FENCE_DEFICIT_MS, "cohort_seed_fence_deficit_ms");+ assert_eq!(LIVE_WATERMARK_AGE_MS, "cohort_live_watermark_age_ms");+ }+#[test]fn schema_guard_and_drain_scan_metric_names_are_stable() {assert_eq!(diff --git a/rust/cohort-stream-processor/src/partitions/backpressure.rs b/rust/cohort-stream-processor/src/partitions/backpressure.rsindex 0aafeee606e4..7e36c104d393 100644--- a/rust/cohort-stream-processor/src/partitions/backpressure.rs+++ b/rust/cohort-stream-processor/src/partitions/backpressure.rs@@ -1,24 +1,32 @@-//! The events consume loop's per-partition holdover of un-dispatched events, kept broker-free so its-//! transitions are unit-testable in isolation.-//!-//! A partition holds a non-empty entry in [`pending`](Backpressure::pending) **iff** its events could-//! not be dispatched, so [`held_partitions`](Backpressure::held_partitions) (`pending.keys()`) is-//! exactly the paused target. Applying and re-asserting that target on the consumer is owned by the-//! pauser task (`run_pauser_loop`), not this struct.+//! Per-partition holdover of un-dispatched messages, kept broker-free so its transitions are+//! unit-testable. A partition has an entry **iff** its messages could not be dispatched, so+//! `pending.keys()` is exactly the paused target; the pauser task owns applying it. Instantiated+//! by the events consumer ([`Backpressure`]) and the seed consumer.use std::collections::{HashMap, HashSet};use crate::partitions::shuffle_message::ShuffleMessage;-/// Held events per held partition for the events consume loop. Never keeps an empty holdover, so-/// `pending.keys()` is exactly the paused target.-#[derive(Debug, Default)]-pub struct Backpressure {- /// Un-dispatched events per held partition, coalesced in offset order.- pending: HashMap<i32, Vec<ShuffleMessage>>,+/// The events consume loop's holdover.+pub type Backpressure = PartitionHoldover<ShuffleMessage>;++/// Held messages per held partition. Never keeps an empty holdover, so `pending.keys()` is exactly+/// the paused target.+#[derive(Debug)]+pub struct PartitionHoldover<T> {+ /// Un-dispatched messages per held partition, coalesced in offset order.+ pending: HashMap<i32, Vec<T>>,+}++impl<T> Default for PartitionHoldover<T> {+ fn default() -> Self {+ Self {+ pending: HashMap::new(),+ }+ }}-impl Backpressure {+impl<T> PartitionHoldover<T> {pub fn new() -> Self {Self::default()}@@ -30,21 +38,21 @@ impl Backpressure {.retain(|partition, _| owned.contains(partition));}- /// Take the whole holdover for a retry-flush, emptying `pending`; the caller re-[`absorb`](Self::absorb)s- /// whatever stays full.- pub fn take_held(&mut self) -> Vec<(i32, Vec<ShuffleMessage>)> {+ /// Take the whole holdover for a retry-flush, emptying `pending`; the caller+ /// re-[`absorb`](Self::absorb)s whatever stays full.+ pub fn take_held(&mut self) -> Vec<(i32, Vec<T>)> {std::mem::take(&mut self.pending).into_iter().collect()}- /// Partitions with an outstanding holdover: the paused target, and the set fresh events must queue- /// behind rather than leapfrog.+ /// Partitions with an outstanding holdover: the paused target, and the set fresh messages must+ /// queue behind rather than leapfrog.pub fn held_partitions(&self) -> HashSet<i32> {self.pending.keys().copied().collect()}- /// Append un-dispatched events to their partition's holdover in offset order. Empty batches are- /// skipped, so a present entry always means a non-empty holdover.- pub fn absorb(&mut self, full: HashMap<i32, Vec<ShuffleMessage>>) {+ /// Append un-dispatched messages to their partition's holdover in offset order. Empty batches+ /// are skipped, so a present entry always means a non-empty holdover.+ pub fn absorb(&mut self, full: HashMap<i32, Vec<T>>) {for (partition, mut messages) in full {if messages.is_empty() {continue;@@ -61,8 +69,8 @@ impl Backpressure {self.pending.len()}- /// Total events held across all held partitions. Feeds the `pending_held_events` gauge.- pub fn held_event_count(&self) -> usize {+ /// Total messages held across all held partitions. Feeds the `pending_held_events` gauge.+ pub fn held_message_count(&self) -> usize {self.pending.values().map(Vec::len).sum()}}@@ -90,6 +98,7 @@ mod tests {redirect_hops: 0,}),cse_offset,+ broker_ts_ms: None,}}@@ -158,12 +167,12 @@ mod tests {}#[test]- fn held_event_count_sums_across_partitions() {+ fn held_message_count_sums_across_partitions() {let mut bp = Backpressure::new();bp.absorb(HashMap::from([(5, vec![event(10), event(11)]),(6, vec![event(20)]),]));- assert_eq!(bp.held_event_count(), 3);+ assert_eq!(bp.held_message_count(), 3);}}diff --git a/rust/cohort-stream-processor/src/partitions/intake.rs b/rust/cohort-stream-processor/src/partitions/intake.rsindex 1cb3892a825e..733762169a76 100644--- a/rust/cohort-stream-processor/src/partitions/intake.rs+++ b/rust/cohort-stream-processor/src/partitions/intake.rs@@ -1,11 +1,9 @@-//! App-side intake backpressure: a per-partition ceiling on **events** resident in a worker's-//! channel. The mpsc slots bound sub-batches; this bounds the events inside them. Over the cap, new-//! events are refused (→ held → paused), never buffered.+//! App-side intake backpressure: a per-partition ceiling on events and seed tiles resident in a+//! worker's channel. Over the cap, new messages are refused (→ held → paused), never buffered.//!-//! The counter cannot drift: [`PartitionIntake::try_admit`] reserves a batch's events (only the-//! consume loop admits), [`MeteredReceiver`] releases them on the next `recv` and on `Drop`, and the-//! router releases eagerly when an admitted batch fails to enter the channel. Both sides count events-//! only, so maintenance ticks reserve and release 0.+//! The counter cannot drift: [`PartitionIntake::try_admit`] reserves, [`MeteredReceiver`] releases+//! on the next `recv` and on `Drop`, and the router releases eagerly on a failed send. Both sides+//! share [`ShuffleMessage::counts_toward_intake`], so they can never disagree on what counts.use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::Arc;@@ -16,11 +14,11 @@ use tokio::sync::mpsc;use super::shuffle_message::ShuffleMessage;use crate::observability::metrics::PARTITION_INTAKE_EVENTS;-/// Event-carrying messages in a batch. Maintenance ticks carry no offset and count 0.-pub fn count_events(batch: &[ShuffleMessage]) -> usize {+/// Intake-counted messages in a batch; maintenance ticks count 0.+pub fn count_intake(batch: &[ShuffleMessage]) -> usize {batch.iter()- .filter(|message| message.event_offset().is_some())+ .filter(|message| message.counts_toward_intake()).count()}@@ -134,7 +132,7 @@ impl MeteredReceiver {pub async fn recv(&mut self) -> Option<Vec<ShuffleMessage>> {self.release_outstanding();let batch = self.receiver.recv().await?;- self.outstanding = count_events(&batch);+ self.outstanding = count_intake(&batch);Some(batch)}@@ -150,7 +148,7 @@ impl MeteredReceiver {pub fn try_recv(&mut self) -> Result<Vec<ShuffleMessage>, mpsc::error::TryRecvError> {self.release_outstanding();let batch = self.receiver.try_recv()?;- self.outstanding = count_events(&batch);+ self.outstanding = count_intake(&batch);Ok(batch)}}@@ -184,6 +182,7 @@ mod tests {redirect_hops: 0,}),cse_offset: 0,+ broker_ts_ms: None,}}@@ -192,14 +191,14 @@ mod tests {}#[test]- fn count_events_ignores_maintenance_messages() {+ fn count_intake_counts_events_and_seeds_but_ignores_maintenance() {let batch = vec![event(),ShuffleMessage::Sweep { due_before_ms: 1 },event(),ShuffleMessage::RedrivePendingTransfers,];- assert_eq!(count_events(&batch), 2);+ assert_eq!(count_intake(&batch), 2);}#[test]@@ -241,10 +240,10 @@ mod tests {tx.send(events(2)).await.unwrap();assert_eq!(intake.in_flight(), 5);- assert_eq!(count_events(&rx.recv().await.unwrap()), 3);+ assert_eq!(count_intake(&rx.recv().await.unwrap()), 3);assert_eq!(intake.in_flight(), 5, "the in-hand batch stays counted");- assert_eq!(count_events(&rx.recv().await.unwrap()), 2);+ assert_eq!(count_intake(&rx.recv().await.unwrap()), 2);assert_eq!(intake.in_flight(), 2, "recv released the previous batch");drop(rx);diff --git a/rust/cohort-stream-processor/src/partitions/mod.rs b/rust/cohort-stream-processor/src/partitions/mod.rsindex e1cc10eabef5..02c723d2a216 100644--- a/rust/cohort-stream-processor/src/partitions/mod.rs+++ b/rust/cohort-stream-processor/src/partitions/mod.rs@@ -13,10 +13,11 @@ pub mod pause;pub mod rebalance;pub mod router;pub mod shuffle_message;+pub mod watermarks;pub use cohort_core::partitioner;-pub use backpressure::Backpressure;+pub use backpressure::{Backpressure, PartitionHoldover};pub use follower::{Follower, FollowerSet, PartitionMirror};pub use intake::{Admission, MeteredReceiver, PartitionIntake};pub use offset_tracker::{MarkOutcome, OffsetTracker};@@ -30,3 +31,4 @@ pub use rebalance::{};pub use router::{PartitionRouter, RouteError, SendOutcome};pub use shuffle_message::ShuffleMessage;+pub use watermarks::{LiveWatermarks, WatermarkMs};diff --git a/rust/cohort-stream-processor/src/partitions/pause.rs b/rust/cohort-stream-processor/src/partitions/pause.rsindex 1c60f0834412..0dc777e62790 100644--- a/rust/cohort-stream-processor/src/partitions/pause.rs+++ b/rust/cohort-stream-processor/src/partitions/pause.rs@@ -4,26 +4,27 @@use std::sync::Arc;-use rdkafka::consumer::{Consumer, StreamConsumer};+use rdkafka::consumer::{Consumer, ConsumerContext, StreamConsumer};use rdkafka::TopicPartitionList;use tracing::warn;use crate::partitions::rebalance::CohortConsumerContext;-/// Pause/resume Kafka fetching for specific partitions of the events topic.+/// Pause/resume Kafka fetching for specific partitions of one input topic.pub trait PartitionPauser: Send + Sync {fn pause(&self, partitions: &[i32]);fn resume(&self, partitions: &[i32]);}-/// Production [`PartitionPauser`]: drives `pause`/`resume` on the events `StreamConsumer`.-pub struct ConsumerPauser {- consumer: Arc<StreamConsumer<CohortConsumerContext>>,+/// Production [`PartitionPauser`]: drives `pause`/`resume` on a `StreamConsumer`. Generic over+/// the consumer context so the events consumer and the seed follower share it.+pub struct ConsumerPauser<C: ConsumerContext + 'static = CohortConsumerContext> {+ consumer: Arc<StreamConsumer<C>>,topic: String,}-impl ConsumerPauser {- pub fn new(consumer: Arc<StreamConsumer<CohortConsumerContext>>, topic: String) -> Self {+impl<C: ConsumerContext + 'static> ConsumerPauser<C> {+ pub fn new(consumer: Arc<StreamConsumer<C>>, topic: String) -> Self {Self { consumer, topic }}@@ -36,7 +37,7 @@ impl ConsumerPauser {}}-impl PartitionPauser for ConsumerPauser {+impl<C: ConsumerContext + 'static> PartitionPauser for ConsumerPauser<C> {fn pause(&self, partitions: &[i32]) {if partitions.is_empty() {return;diff --git a/rust/cohort-stream-processor/src/partitions/router.rs b/rust/cohort-stream-processor/src/partitions/router.rsindex 5b6cffbce6f8..e05f6fa87574 100644--- a/rust/cohort-stream-processor/src/partitions/router.rs+++ b/rust/cohort-stream-processor/src/partitions/router.rs@@ -18,7 +18,7 @@ use tokio::sync::mpsc;use tokio::sync::mpsc::error::TrySendError;use tracing::warn;-use super::intake::{count_events, Admission, MeteredReceiver, PartitionIntake};+use super::intake::{count_intake, Admission, MeteredReceiver, PartitionIntake};use super::shuffle_message::ShuffleMessage;use crate::observability::metrics::{PARTITIONS_ACTIVE, PARTITION_CHANNEL_DEPTH, PARTITION_CHANNEL_FULL_TOTAL,@@ -247,8 +247,8 @@ impl PartitionRouter {// Refuse (→ hold → pause) once the partition holds its event ceiling, before the batch reaches// the mpsc slot. Count events only, so an event-less batch reserves 0 and stays balanced with// the receiver's release.- let events = count_events(&batch);- if channel.intake.try_admit(events) == Admission::Rejected {+ let counted = count_intake(&batch);+ if channel.intake.try_admit(counted) == Admission::Rejected {counter!(PARTITION_CHANNEL_FULL_TOTAL, "partition" => partition.to_string()).increment(batch.len() as u64);return SendOutcome::Full(batch);@@ -260,13 +260,13 @@ impl PartitionRouter {}Err(TrySendError::Full(returned)) => {// Reserved above but the slot is full: release so the counter tracks only what landed.- channel.intake.release(events);+ channel.intake.release(counted);counter!(PARTITION_CHANNEL_FULL_TOTAL, "partition" => partition.to_string()).increment(returned.len() as u64);SendOutcome::Full(returned)}Err(TrySendError::Closed(returned)) => {- channel.intake.release(events);+ channel.intake.release(counted);self.record_drop(partition, returned.len(), REASON_CHANNEL_CLOSED);SendOutcome::ChannelClosed}@@ -335,6 +335,7 @@ mod tests {redirect_hops: 0,}),cse_offset: 0,+ broker_ts_ms: None,}}@@ -348,7 +349,8 @@ mod tests {| ShuffleMessage::Transfer { .. }| ShuffleMessage::Cascade { .. }| ShuffleMessage::RedrivePendingTransfers- | ShuffleMessage::MergeCfGc { .. } => {+ | ShuffleMessage::MergeCfGc { .. }+ | ShuffleMessage::Seed { .. } => {unreachable!("router tests route only events")}})@@ -531,7 +533,11 @@ mod tests {/// assertions line up.fn event_off(cse_offset: i64) -> ShuffleMessage {match event(cse_offset) {- ShuffleMessage::Event { event, .. } => ShuffleMessage::Event { event, cse_offset },+ ShuffleMessage::Event { event, .. } => ShuffleMessage::Event {+ event,+ cse_offset,+ broker_ts_ms: None,+ },other => other,}}diff --git a/rust/cohort-stream-processor/src/partitions/shuffle_message.rs b/rust/cohort-stream-processor/src/partitions/shuffle_message.rsindex a65ab79aabb6..66799031c645 100644--- a/rust/cohort-stream-processor/src/partitions/shuffle_message.rs+++ b/rust/cohort-stream-processor/src/partitions/shuffle_message.rs@@ -2,6 +2,7 @@use crate::cascade::CascadeMessage;use crate::consumers::events::CohortStreamEvent;+use crate::consumers::seeds::SeedWork;use crate::merge::transfer::{MergeStateTransfer, PersonMergeEvent};/// A unit of work routed to the partition worker that owns its `(team_id, person_id)` key.@@ -13,6 +14,9 @@ pub enum ShuffleMessage {Event {event: Box<CohortStreamEvent>,cse_offset: i64,+ /// Broker timestamp of the consumed message — the seed fence's watermark input. `None`+ /// never advances the watermark.+ broker_ts_ms: Option<i64>,},/// A time-driven eviction tick with the cutoff `due_before_ms`. Serialized on the same channel/// as events so the worker processes it in order with no locks.@@ -47,10 +51,15 @@ pub enum ShuffleMessage {marker_cutoff_ms: i64,tombstone_cutoff_ms: i64,},+ /// A backfill day-tile (or its consume-side skip), paired with its topic offset. Marked on+ /// the seed tracker, never the events tracker. Boxed so the tile doesn't inflate every+ /// `ShuffleMessage`.+ Seed { work: Box<SeedWork>, offset: i64 },}impl ShuffleMessage {- /// The offset an [`Event`](Self::Event) carries; `None` for the maintenance variants.+ /// The offset an [`Event`](Self::Event) carries; `None` for every other variant, including+ /// [`Seed`](Self::Seed) (its offset belongs to the seed tracker).pub fn event_offset(&self) -> Option<i64> {match self {ShuffleMessage::Event { cse_offset, .. } => Some(*cse_offset),@@ -59,9 +68,38 @@ impl ShuffleMessage {| ShuffleMessage::Transfer { .. }| ShuffleMessage::Cascade { .. }| ShuffleMessage::RedrivePendingTransfers+ | ShuffleMessage::MergeCfGc { .. }+ | ShuffleMessage::Seed { .. } => None,+ }+ }++ /// The seed-topic offset a [`Seed`](Self::Seed) carries; `None` for every other variant.+ pub fn seed_offset(&self) -> Option<i64> {+ match self {+ ShuffleMessage::Seed { offset, .. } => Some(*offset),+ ShuffleMessage::Event { .. }+ | ShuffleMessage::Sweep { .. }+ | ShuffleMessage::Merge { .. }+ | ShuffleMessage::Transfer { .. }+ | ShuffleMessage::Cascade { .. }+ | ShuffleMessage::RedrivePendingTransfers| ShuffleMessage::MergeCfGc { .. } => None,}}++ /// Whether this message reserves an intake-budget slot; maintenance/control messages must+ /// always flow.+ pub fn counts_toward_intake(&self) -> bool {+ match self {+ ShuffleMessage::Event { .. } | ShuffleMessage::Seed { .. } => true,+ ShuffleMessage::Sweep { .. }+ | ShuffleMessage::Merge { .. }+ | ShuffleMessage::Transfer { .. }+ | ShuffleMessage::Cascade { .. }+ | ShuffleMessage::RedrivePendingTransfers+ | ShuffleMessage::MergeCfGc { .. } => false,+ }+ }}#[cfg(test)]@@ -79,6 +117,8 @@ mod tests {person_id: "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string(),last_updated: "2026-05-26 12:34:56.789000".to_string(),status: MembershipStatus::Entered,+ origin: None,+ run_id: None,},source_offset: 9,depth: 1,@@ -131,28 +171,77 @@ mod tests {}#[test]- fn event_variant_carries_event_and_cse_offset() {+ fn event_variant_carries_event_offset_and_broker_ts() {let message = ShuffleMessage::Event {event: Box::new(sample_event(42)),cse_offset: 7,+ broker_ts_ms: Some(1_700_000_000_000),};// No wildcard, so a new variant forces this test to be revisited.match message {- ShuffleMessage::Event { event, cse_offset } => {+ ShuffleMessage::Event {+ event,+ cse_offset,+ broker_ts_ms,+ } => {assert_eq!(event.source_offset, 42);assert_eq!(event.source_partition, 3);assert_eq!(cse_offset, 7);+ assert_eq!(broker_ts_ms, Some(1_700_000_000_000));}ShuffleMessage::Sweep { .. }| ShuffleMessage::Merge { .. }| ShuffleMessage::Transfer { .. }| ShuffleMessage::RedrivePendingTransfers| ShuffleMessage::MergeCfGc { .. }+ | ShuffleMessage::Seed { .. }| ShuffleMessage::Cascade { .. } => unreachable!("constructed an Event"),}}+ fn sample_seed_work() -> SeedWork {+ use std::num::NonZeroU32;++ use cohort_core::seed::{ClaimEpoch, ConditionHash, RunId, SChunkMs, SeedTile};++ SeedWork::Tile(SeedTile::new(+ crate::filters::TeamId(1),+ Uuid::from_u128(9),+ ConditionHash::parse("0123456789abcdef").unwrap(),+ NonZeroU32::new(3).unwrap(),+ 20_614,+ SChunkMs(1_700_000_000_000),+ RunId(Uuid::nil()),+ ClaimEpoch(1),+ ))+ }++ #[test]+ fn seed_variant_carries_its_own_offset_and_never_an_event_offset() {+ let message = ShuffleMessage::Seed {+ work: Box::new(sample_seed_work()),+ offset: 17,+ };++ assert_eq!(+ message.event_offset(),+ None,+ "a seed offset must never reach the events tracker",+ );+ assert_eq!(message.seed_offset(), Some(17));+ assert!(message.counts_toward_intake());++ let event = ShuffleMessage::Event {+ event: Box::new(sample_event(1)),+ cse_offset: 3,+ broker_ts_ms: None,+ };+ assert_eq!(event.seed_offset(), None);+ assert!(event.counts_toward_intake());+ assert!(!ShuffleMessage::RedrivePendingTransfers.counts_toward_intake());+ }+#[test]fn sweep_variant_carries_the_due_before_cutoff() {let message = ShuffleMessage::Sweep {@@ -165,6 +254,7 @@ mod tests {| ShuffleMessage::Transfer { .. }| ShuffleMessage::RedrivePendingTransfers| ShuffleMessage::MergeCfGc { .. }+ | ShuffleMessage::Seed { .. }| ShuffleMessage::Cascade { .. } => unreachable!("constructed a Sweep"),}}@@ -188,6 +278,7 @@ mod tests {| ShuffleMessage::Merge { .. }| ShuffleMessage::Transfer { .. }| ShuffleMessage::RedrivePendingTransfers+ | ShuffleMessage::Seed { .. }| ShuffleMessage::Cascade { .. } => unreachable!("constructed a MergeCfGc"),}}@@ -208,6 +299,7 @@ mod tests {| ShuffleMessage::Transfer { .. }| ShuffleMessage::RedrivePendingTransfers| ShuffleMessage::MergeCfGc { .. }+ | ShuffleMessage::Seed { .. }| ShuffleMessage::Cascade { .. } => unreachable!("constructed a Merge"),}@@ -225,6 +317,7 @@ mod tests {| ShuffleMessage::Merge { .. }| ShuffleMessage::RedrivePendingTransfers| ShuffleMessage::MergeCfGc { .. }+ | ShuffleMessage::Seed { .. }| ShuffleMessage::Cascade { .. } => unreachable!("constructed a Transfer"),}}@@ -247,7 +340,8 @@ mod tests {| ShuffleMessage::Merge { .. }| ShuffleMessage::Transfer { .. }| ShuffleMessage::RedrivePendingTransfers- | ShuffleMessage::MergeCfGc { .. } => unreachable!("constructed a Cascade"),+ | ShuffleMessage::MergeCfGc { .. }+ | ShuffleMessage::Seed { .. } => unreachable!("constructed a Cascade"),}}}diff --git a/rust/cohort-stream-processor/src/partitions/watermarks.rs b/rust/cohort-stream-processor/src/partitions/watermarks.rsnew file mode 100644index 000000000000..9cb8088dacab--- /dev/null+++ b/rust/cohort-stream-processor/src/partitions/watermarks.rs@@ -0,0 +1,89 @@+//! Per-partition live-consumption watermarks — the seed apply-fence's input.+//!+//! The running max of broker timestamps the partition worker has **folded**, advanced only+//! post-mark so unfolded events can never open the fence early; idle partitions advance via the+//! seed consumer's probe. Absent entries are fail-closed.++use dashmap::DashMap;++/// A live watermark instant (epoch ms, broker CreateTime ≈ arrival).+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+pub struct WatermarkMs(pub i64);++/// Monotonic per-partition watermark map.+#[derive(Debug, Default)]+pub struct LiveWatermarks {+ partitions: DashMap<i32, i64>,+}++impl LiveWatermarks {+ pub fn new() -> Self {+ Self::default()+ }++ /// Fold-frontier advance; running max because broker CreateTime is not per-partition+ /// monotonic across shuffler replicas.+ pub fn observe(&self, partition: i32, broker_ts_ms: i64) {+ self.advance(partition, broker_ts_ms);+ }++ /// Idle advance: everything retained is folded, so "now" is a valid arrival bound.+ pub fn advance_idle(&self, partition: i32, now_ms: i64) {+ self.advance(partition, now_ms);+ }++ /// `None` = never observed (fail-closed for the fence).+ pub fn get(&self, partition: i32) -> Option<WatermarkMs> {+ self.partitions+ .get(&partition)+ .map(|entry| WatermarkMs(*entry))+ }++ pub fn forget_partition(&self, partition: i32) {+ self.partitions.remove(&partition);+ }++ fn advance(&self, partition: i32, candidate_ms: i64) {+ let mut entry = self.partitions.entry(partition).or_insert(candidate_ms);+ *entry = (*entry).max(candidate_ms);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn watermark_is_a_running_max_across_observe_and_idle_advances() {+ let watermarks = LiveWatermarks::new();+ assert_eq!(+ watermarks.get(5),+ None,+ "fail-closed before any observation"+ );++ watermarks.observe(5, 1_000);+ assert_eq!(watermarks.get(5), Some(WatermarkMs(1_000)));++ // Out-of-order broker timestamps (multiple shuffler replicas) never regress it.+ watermarks.observe(5, 900);+ assert_eq!(watermarks.get(5), Some(WatermarkMs(1_000)));++ watermarks.advance_idle(5, 2_000);+ assert_eq!(watermarks.get(5), Some(WatermarkMs(2_000)));+ watermarks.observe(5, 1_500);+ assert_eq!(watermarks.get(5), Some(WatermarkMs(2_000)));+ }++ #[test]+ fn forget_partition_returns_it_to_fail_closed() {+ let watermarks = LiveWatermarks::new();+ watermarks.observe(3, 1_000);+ watermarks.observe(4, 2_000);++ watermarks.forget_partition(3);++ assert_eq!(watermarks.get(3), None, "the next tenure re-derives");+ assert_eq!(watermarks.get(4), Some(WatermarkMs(2_000)), "others keep");+ }+}diff --git a/rust/cohort-stream-processor/src/producer/batcher.rs b/rust/cohort-stream-processor/src/producer/batcher.rsindex 0b659e30ad60..368c7cfcb271 100644--- a/rust/cohort-stream-processor/src/producer/batcher.rs+++ b/rust/cohort-stream-processor/src/producer/batcher.rs@@ -41,6 +41,8 @@ mod tests {person_id: "p".to_string(),last_updated: "2026-05-26 12:34:56.789123".to_string(),status: MembershipStatus::Entered,+ origin: None,+ run_id: None,}}diff --git a/rust/cohort-stream-processor/src/producer/cascade.rs b/rust/cohort-stream-processor/src/producer/cascade.rsindex 2a0ac375c40b..dd8ca9daf1df 100644--- a/rust/cohort-stream-processor/src/producer/cascade.rs+++ b/rust/cohort-stream-processor/src/producer/cascade.rs@@ -119,6 +119,8 @@ mod tests {person_id: person.to_string(),last_updated: TS.to_string(),status: MembershipStatus::Entered,+ origin: None,+ run_id: None,},777,)diff --git a/rust/cohort-stream-processor/src/producer/kafka.rs b/rust/cohort-stream-processor/src/producer/kafka.rsindex 0792d86f27b9..7adb40778154 100644--- a/rust/cohort-stream-processor/src/producer/kafka.rs+++ b/rust/cohort-stream-processor/src/producer/kafka.rs@@ -68,6 +68,8 @@ mod tests {person_id: "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string(),last_updated: "2026-05-26 12:34:56.789123".to_string(),status: MembershipStatus::Entered,+ origin: None,+ run_id: None,};assert_eq!(membership_key(&change), Some(change.person_id.clone()));}diff --git a/rust/cohort-stream-processor/src/producer/mod.rs b/rust/cohort-stream-processor/src/producer/mod.rsindex 75debb75e078..b5ee792eb7ba 100644--- a/rust/cohort-stream-processor/src/producer/mod.rs+++ b/rust/cohort-stream-processor/src/producer/mod.rs@@ -7,6 +7,7 @@ pub mod batcher;pub mod cascade;pub mod kafka;pub mod merge;+pub mod seed;use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::{Arc, Mutex};@@ -17,6 +18,8 @@ use common_kafka::kafka_producer::KafkaProduceError;use metrics::counter;use serde::{Deserialize, Serialize};+use cohort_core::seed::RunId;+use crate::filters::reverse_index::TeamFilters;use crate::filters::CohortId;use crate::observability::metrics::OUTPUT_TRANSITIONS_UNMAPPED;@@ -29,8 +32,12 @@ pub use merge::{CaptureStreamEventSink, CaptureTransferSink, KafkaStreamEventSink, KafkaTransferSink,StreamEventSink, TransferSink,};+pub use seed::{CaptureSeedTileSink, KafkaSeedTileSink, NoopSeedTileSink, SeedTileSink};/// One per-cohort membership change on `cohort_membership_changed_shadow`.+///+/// `origin`/`run_id` are additive and absent on the live path, so live emissions stay+/// byte-identical to the pre-field contract.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct CohortMembershipChange {pub team_id: i32,@@ -39,6 +46,20 @@ pub struct CohortMembershipChange {/// ClickHouse `DateTime64(6)` wire format.pub last_updated: String,pub status: MembershipStatus,+ /// Backfill provenance; `None` on the live path.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub origin: Option<ChangeOrigin>,+ /// The backfill run that emitted this change; set iff `origin` is.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub run_id: Option<RunId>,+}++/// Non-live provenance of a membership change; new origins (e.g. a reconcile snapshot) land+/// additively with their producers.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ChangeOrigin {+ Seed,}#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]@@ -94,6 +115,8 @@ pub fn map_transition<'a>(person_id: person_id.clone(),last_updated: last_updated.to_string(),status,+ origin: None,+ run_id: None,})}@@ -301,6 +324,8 @@ mod tests {person_id: "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string(),last_updated: TS.to_string(),status: MembershipStatus::Entered,+ origin: None,+ run_id: None,};let value = serde_json::to_value(&change).unwrap();let object = value.as_object().unwrap();@@ -328,6 +353,42 @@ mod tests {assert_eq!(value, json!("left"));}+ #[test]+ fn live_path_change_stays_byte_identical_and_a_seed_tag_adds_only_the_two_keys() {+ let live = CohortMembershipChange {+ team_id: 42,+ cohort_id: 91204,+ person_id: "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string(),+ last_updated: TS.to_string(),+ status: MembershipStatus::Entered,+ origin: None,+ run_id: None,+ };+ // The exact pre-field wire string: downstream JSONEachRow must see no new keys on the+ // live path.+ assert_eq!(+ serde_json::to_string(&live).unwrap(),+ r#"{"team_id":42,"cohort_id":91204,"person_id":"01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee","last_updated":"2026-05-26 12:34:56.789123","status":"entered"}"#,+ );+ // And the pre-field payload still deserializes (defaulting both to None).+ let decoded: CohortMembershipChange =+ serde_json::from_str(&serde_json::to_string(&live).unwrap()).unwrap();+ assert_eq!(decoded, live);++ let tagged = CohortMembershipChange {+ origin: Some(ChangeOrigin::Seed),+ run_id: Some(RunId(uuid::Uuid::nil())),+ ..live+ };+ let value = serde_json::to_value(&tagged).unwrap();+ assert_eq!(value["origin"], json!("seed"));+ assert_eq!(+ value["run_id"],+ json!("00000000-0000-0000-0000-000000000000")+ );+ assert_eq!(value.as_object().unwrap().len(), 7);+ }+#[test]fn now_last_updated_is_microsecond_clickhouse_format() {let now = now_last_updated();@@ -350,6 +411,8 @@ mod tests {person_id: "p".to_string(),last_updated: TS.to_string(),status: MembershipStatus::Entered,+ origin: None,+ run_id: None,};let acks = sink.produce(vec![change.clone(), change.clone()]).await;assert_eq!(acks.len(), 2);@@ -366,6 +429,8 @@ mod tests {person_id: "p".to_string(),last_updated: TS.to_string(),status: MembershipStatus::Left,+ origin: None,+ run_id: None,};let first = sink.produce(vec![change.clone()]).await;diff --git a/rust/cohort-stream-processor/src/producer/seed.rs b/rust/cohort-stream-processor/src/producer/seed.rsnew file mode 100644index 000000000000..5498e1c498ab--- /dev/null+++ b/rust/cohort-stream-processor/src/producer/seed.rs@@ -0,0 +1,99 @@+//! Re-key producer for `cohort_stream_seed_events`: cross-partition-merged tiles are re-produced+//! to the survivor's partition, keyed exactly as the seeder keys them.++use anyhow::{Context, Result};+use async_trait::async_trait;+use cohort_core::seed::SeedTile;+use common_kafka::config::KafkaConfig;+use common_kafka::kafka_producer::{+ create_kafka_producer, send_keyed_iter_to_kafka_with_headers, KafkaContext, KafkaProduceError,+};+use rdkafka::producer::FutureProducer;++use crate::producer::kafka::AlwaysHealthy;+use crate::producer::merge::Capture;++#[async_trait]+pub trait SeedTileSink: Send + Sync {+ async fn produce(&self, tiles: Vec<SeedTile>) -> Vec<Result<(), KafkaProduceError>>;+}++pub struct KafkaSeedTileSink {+ producer: FutureProducer<KafkaContext>,+ topic: String,+}++impl KafkaSeedTileSink {+ pub async fn new(kafka_config: &KafkaConfig, topic: String) -> Result<Self> {+ let producer = create_kafka_producer(kafka_config, AlwaysHealthy)+ .await+ .context("creating cohort_stream_seed_events re-key producer")?;+ Ok(Self { producer, topic })+ }+}++#[async_trait]+impl SeedTileSink for KafkaSeedTileSink {+ async fn produce(&self, tiles: Vec<SeedTile>) -> Vec<Result<(), KafkaProduceError>> {+ send_keyed_iter_to_kafka_with_headers(+ &self.producer,+ &self.topic,+ |tile| Some(tile.partition_key()),+ |_| None,+ tiles,+ )+ .await+ }+}++/// Inert sink for gate-off deploys: a produce is a coding error made loud, not a silent drop.+pub struct NoopSeedTileSink;++#[async_trait]+impl SeedTileSink for NoopSeedTileSink {+ async fn produce(&self, tiles: Vec<SeedTile>) -> Vec<Result<(), KafkaProduceError>> {+ tiles+ .into_iter()+ .map(|_| Err(KafkaProduceError::KafkaProduceCanceled))+ .collect()+ }+}++pub struct CaptureSeedTileSink(Capture<SeedTile>);++impl CaptureSeedTileSink {+ pub fn new() -> Self {+ Self(Capture::default())+ }++ pub fn failing_first(n: usize) -> Self {+ Self(Capture::failing_first(n))+ }++ pub fn failing_always() -> Self {+ Self(Capture::failing_always())+ }++ pub fn tiles(&self) -> Vec<SeedTile> {+ self.0.recorded()+ }+}++impl Default for CaptureSeedTileSink {+ fn default() -> Self {+ Self::new()+ }+}++impl Clone for CaptureSeedTileSink {+ fn clone(&self) -> Self {+ Self(self.0.clone())+ }+}++#[async_trait]+impl SeedTileSink for CaptureSeedTileSink {+ async fn produce(&self, tiles: Vec<SeedTile>) -> Vec<Result<(), KafkaProduceError>> {+ self.0.produce(tiles)+ }+}diff --git a/rust/cohort-stream-processor/src/stage1/compressed_history.rs b/rust/cohort-stream-processor/src/stage1/compressed_history.rsindex 2d0bc71cbf27..ed3d079e2035 100644--- a/rust/cohort-stream-processor/src/stage1/compressed_history.rs+++ b/rust/cohort-stream-processor/src/stage1/compressed_history.rs@@ -17,6 +17,17 @@ pub(crate) fn insert_event(entries: &mut Vec<(i32, u32)>, day: i32) {}}+/// Max-merge `day`'s absolute `count` — the seed-tile analog of [`insert_event`]: the tile carries+/// the whole day's count, so merging takes the max instead of incrementing. Keeps entries sorted+/// with no zero-count entries (`count ≥ 1` by the tile's `NonZeroU32`). The caller must slide the+/// window before calling; `day` must be within the current window.+pub(crate) fn merge_day_count(entries: &mut Vec<(i32, u32)>, day: i32, count: u32) {+ match entries.binary_search_by_key(&day, |&(entry_day, _)| entry_day) {+ Ok(idx) => entries[idx].1 = entries[idx].1.max(count),+ Err(idx) => entries.insert(idx, (day, count)),+ }+}+/// Slide the sparse window forward to `target_now_day`, dropping entries below the new lower bound./// No-op when the window already covers `target_now_day`; the window only moves forward, never back.pub(crate) fn slide_window_forward(@@ -109,6 +120,25 @@ mod tests {assert_eq!(entries, vec![(100, u32::MAX)], "saturating, never wraps");}+ #[test]+ fn merge_day_count_keeps_the_max_keeps_sorting_and_never_stores_zero() {+ // Fresh day: inserted at its sorted position with the absolute count.+ let mut entries = vec![(100, 3), (110, 1)];+ merge_day_count(&mut entries, 105, 4);+ assert_eq!(entries, vec![(100, 3), (105, 4), (110, 1)]);++ // Existing day: max, not sum — re-delivery and live overlap must not inflate the count.+ merge_day_count(&mut entries, 100, 2);+ assert_eq!(entries[0], (100, 3), "smaller tile count is absorbed");+ merge_day_count(&mut entries, 100, 9);+ assert_eq!(entries[0], (100, 9), "larger tile count wins");++ // Idempotent: the same merge twice is a no-op.+ let before = entries.clone();+ merge_day_count(&mut entries, 105, 4);+ assert_eq!(entries, before);+ }+#[test]fn slide_to_the_current_now_day_is_a_noop() {// window_days 365, window [100 ..= 465]; target == cur_now_day (465) → unchanged.diff --git a/rust/cohort-stream-processor/src/store/handle.rs b/rust/cohort-stream-processor/src/store/handle.rsindex 2524144d2fbf..25dbcd4d4ac5 100644--- a/rust/cohort-stream-processor/src/store/handle.rs+++ b/rust/cohort-stream-processor/src/store/handle.rs@@ -288,14 +288,15 @@ impl StoreHandle {.await}- /// Point-read one person's `cf_person_records` value as raw bytes. The event fold reads this on- /// the hot path (Event lane); decoding lives with the caller.+ /// Point-read one person's `cf_person_records` value as raw bytes; decoding lives with the+ /// caller.pub async fn get_person_record(&self,key: &PersonRecordKey,+ lane: ReadLane,) -> Result<Option<Vec<u8>>, StoreError> {let key = *key;- self.read("get_person_record", ReadLane::Event, move |store| {+ self.read("get_person_record", lane, move |store| {store.get_person_record(&key)}).await@@ -315,30 +316,37 @@ impl StoreHandle {.await}- /// Point-read one `cf_stage2` value (stage-2 compose is an event-path read).- pub async fn get_stage2(&self, key: &Stage2Key) -> Result<Option<Vec<u8>>, StoreError> {+ /// Point-read one `cf_stage2` value.+ pub async fn get_stage2(+ &self,+ key: &Stage2Key,+ lane: ReadLane,+ ) -> Result<Option<Vec<u8>>, StoreError> {let key = *key;- self.read("get_stage2", ReadLane::Event, move |store| {- store.get_stage2(&key)- })- .await+ self.read("get_stage2", lane, move |store| store.get_stage2(&key))+ .await}- /// Batch-read `cf_stage2` values, preserving input order (stage-2 compose, event path).+ /// Batch-read `cf_stage2` values, preserving input order.pub async fn multi_get_stage2(&self,keys: Vec<Stage2Key>,+ lane: ReadLane,) -> Result<Vec<Option<Vec<u8>>>, StoreError> {- self.read("multi_get_stage2", ReadLane::Event, move |store| {+ self.read("multi_get_stage2", lane, move |store| {store.multi_get_stage2(&keys)}).await}- /// Point-read one redirect tombstone (the tombstone-redirect hop is an event-path read).- pub async fn get_tombstone(&self, key: &TombstoneKey) -> Result<Option<Vec<u8>>, StoreError> {+ /// Point-read one redirect tombstone.+ pub async fn get_tombstone(+ &self,+ key: &TombstoneKey,+ lane: ReadLane,+ ) -> Result<Option<Vec<u8>>, StoreError> {let key = *key;- self.read("get_tombstone", ReadLane::Event, move |store| {+ self.read("get_tombstone", lane, move |store| {store.get_tombstone(&key)}).awaitdiff --git a/rust/cohort-stream-processor/src/workers/cascade_path.rs b/rust/cohort-stream-processor/src/workers/cascade_path.rsindex d00e7cf2d735..b60871b468db 100644--- a/rust/cohort-stream-processor/src/workers/cascade_path.rs+++ b/rust/cohort-stream-processor/src/workers/cascade_path.rs@@ -30,7 +30,7 @@ use crate::observability::metrics::{use crate::partitions::offset_tracker::{MarkOutcome, OffsetTracker};use crate::producer::{CohortMembershipChange, MembershipSink};use crate::stage2::state::Stage2State;-use crate::store::{Stage2Key, StagedBatch, StoreHandle};+use crate::store::{ReadLane, Stage2Key, StagedBatch, StoreHandle};use crate::workers::merge_path::MergeWorkerDeps;use crate::workers::stage2_path::recompute_and_diff;use crate::workers::worker::{produce_cascades, produce_membership};@@ -106,7 +106,16 @@ pub(crate) async fn handle_cascade(let Some(tree) = filters.cohorts.get(&referrer) else {continue;};- let diff = match recompute_and_diff(partition_id, person_id, tree, filters, handle).await {+ let diff = match recompute_and_diff(+ partition_id,+ person_id,+ tree,+ filters,+ handle,+ ReadLane::Event,+ )+ .await+ {Ok(diff) => diff,Err(error) => {warn!(@@ -130,6 +139,8 @@ pub(crate) async fn handle_cascade(person_id: message.change.person_id.clone(),last_updated: last_updated.to_string(),status,+ origin: None,+ run_id: None,});writes.push((diff.stage2_key,@@ -427,6 +438,9 @@ mod tests {fanout_cap,},partition_count: crate::partitions::partitioner::COHORT_PARTITION_COUNT,+ seed_tile_sink: Arc::new(crate::producer::CaptureSeedTileSink::new()),+ seed_tracker: Arc::new(crate::partitions::offset_tracker::OffsetTracker::new()),+ live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),};// The cascade was dispatched this tenure, so its ceiling is raised — mirrors the dispatcher.deps.cascade_tracker@@ -442,6 +456,8 @@ mod tests {person_id: who.to_string(),last_updated: TS.to_string(),status: MembershipStatus::Entered,+ origin: None,+ run_id: None,},source_offset: 99,depth,diff --git a/rust/cohort-stream-processor/src/workers/merge_path.rs b/rust/cohort-stream-processor/src/workers/merge_path.rsindex 58b82f921a8c..2ac59ec90daa 100644--- a/rust/cohort-stream-processor/src/workers/merge_path.rs+++ b/rust/cohort-stream-processor/src/workers/merge_path.rs@@ -26,16 +26,18 @@ use crate::observability::metrics::{};use crate::partitions::offset_tracker::{MarkOutcome, OffsetTracker};use crate::partitions::partitioner::COHORT_PARTITION_COUNT;+use crate::partitions::watermarks::LiveWatermarks;use crate::producer::{- map_transition, CaptureCascadeSink, CaptureStreamEventSink, CaptureTransferSink, CascadeSink,- CohortMembershipChange, MembershipSink, StreamEventSink, TransferSink,+ map_transition, CaptureCascadeSink, CaptureSeedTileSink, CaptureStreamEventSink,+ CaptureTransferSink, CascadeSink, CohortMembershipChange, MembershipSink, SeedTileSink,+ StreamEventSink, TransferSink,};use crate::stage1::transition::LeafTransition;-use crate::store::{BehavioralKey, PendingTransferKey, StoreHandle};+use crate::store::{BehavioralKey, PendingTransferKey, ReadLane, StoreHandle};use crate::sweep::EvictionQueue;use crate::workers::stage2_path::compose_stage2;use crate::workers::worker::{- first_cascades, produce_cascades, produce_membership, transition_metric_label,+ affected_leaves, first_cascades, produce_cascades, produce_membership, transition_metric_label,};/// Inline bounded backoff for the transfer produce.@@ -118,6 +120,13 @@ pub struct MergeWorkerDeps {/// from [`crate::config::Config::cohort_partition_count`] so a re-partitioned lane cannot/// misroute against a hardcoded literal.pub partition_count: u32,+ /// Sink for cross-partition tile re-keys back into `cohort_stream_seed_events` (a no-op when+ /// the seed gate is off).+ pub seed_tile_sink: Arc<dyn SeedTileSink>,+ /// Isolated from every other tracker so seed offsets can never contaminate the events ceiling.+ pub seed_tracker: Arc<OffsetTracker>,+ /// Fold-frontier watermarks the seed fence reads; the worker advances them post-mark.+ pub live_watermarks: Arc<LiveWatermarks>,}impl MergeWorkerDeps {@@ -134,6 +143,9 @@ impl MergeWorkerDeps {cascade_tracker: Arc::new(OffsetTracker::new()),cascade: CascadeConfig::default(),partition_count: COHORT_PARTITION_COUNT,+ seed_tile_sink: Arc::new(CaptureSeedTileSink::new()),+ seed_tracker: Arc::new(OffsetTracker::new()),+ live_watermarks: Arc::new(LiveWatermarks::new()),})}}@@ -637,9 +649,10 @@ async fn produce_merge_transitions(partition_id,handle,filters,- transitions,+ &affected_leaves(transitions),merged_at_ms,last_updated,+ ReadLane::Event,).await{@@ -870,6 +883,9 @@ mod tests {cascade_tracker: Arc::new(OffsetTracker::new()),cascade: CascadeConfig::default(),partition_count: COHORT_PARTITION_COUNT,+ seed_tile_sink: Arc::new(crate::producer::CaptureSeedTileSink::new()),+ seed_tracker: Arc::new(crate::partitions::offset_tracker::OffsetTracker::new()),+ live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),}}diff --git a/rust/cohort-stream-processor/src/workers/mod.rs b/rust/cohort-stream-processor/src/workers/mod.rsindex b148e89cc1de..c44e92013b05 100644--- a/rust/cohort-stream-processor/src/workers/mod.rs+++ b/rust/cohort-stream-processor/src/workers/mod.rs@@ -4,6 +4,7 @@ pub mod cascade_path;pub mod event_path;pub mod merge_gc;pub mod merge_path;+pub mod seed_path;pub mod stage2_gc;pub mod stage2_path;pub mod sweep_callback;diff --git a/rust/cohort-stream-processor/src/workers/seed_path.rs b/rust/cohort-stream-processor/src/workers/seed_path.rsnew file mode 100644index 000000000000..c21920c5e21f--- /dev/null+++ b/rust/cohort-stream-processor/src/workers/seed_path.rs@@ -0,0 +1,2155 @@+//! 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 stage-1 commit → stage-2 recompute → produce → stage-2 commit → mark.+//! Committing the stage-2 bits after the produces ack makes a failed produce re-derivable on+//! replay; store/produce failures hold the seed offset.++use std::num::NonZeroU32;+use std::sync::Arc;++use chrono::Utc;+use chrono_tz::Tz;+use metrics::{counter, gauge};+use tracing::warn;+use uuid::Uuid;++use cohort_core::seed::{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, 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::{map_transition, ChangeOrigin, CohortMembershipChange, MembershipSink};+use crate::stage1::bucket_tz::{+ daily_bucket_len, day_idx_in_tz, start_of_day_ms_in_tz, window_start_for_now, DayIdx,+};+use crate::stage1::compressed_history;+use crate::stage1::daily::{daily_eviction_deadline, slide_window_forward};+use crate::stage1::key::LeafStateKey;+use crate::stage1::pick_state::{EvictionWindow, PredicateOp};+use crate::stage1::predicate::{compressed_predicate, daily_predicate, predicate};+use crate::stage1::state::{Stage1State, StateVariant, StatefulRecord};+use crate::stage1::transition::{LeafTransition, TransitionKind};+use crate::store::{Behavioral, BehavioralKey, PersonPrefix, ReadLane, StagedBatch, StoreHandle};+use crate::sweep::EvictionQueue;+use crate::workers::merge_path::MergeWorkerDeps;+use crate::workers::stage2_path::{commit_stage2_writes, recompute_stage2};+use crate::workers::worker::{+ first_cascades, produce_cascades, produce_membership, transition_metric_label,+};++/// Where a tile applies after tombstone resolution; an exhausted hop budget is unrepresentable+/// as a re-produce, forcing the degraded inline arm.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) enum TileRoute {+ ApplyLocal { person: Uuid },+ ReProduce { tile: SeedTile },+ CapExhausted { person: Uuid },+}++/// Total routing of a tile through its tombstone [`Resolution`].+pub(crate) fn route_tile(tile: &SeedTile, resolution: Resolution, cap: u8) -> TileRoute {+ match resolution {+ Resolution::NotMerged => TileRoute::ApplyLocal {+ person: tile.person_id(),+ },+ Resolution::Inline { final_person, .. } => TileRoute::ApplyLocal {+ person: final_person,+ },+ Resolution::CrossPartition { target_person, .. } => {+ match tile.rekeyed_to(target_person, cap) {+ Some(rekeyed) => TileRoute::ReProduce { tile: rekeyed },+ None => TileRoute::CapExhausted {+ person: target_person,+ },+ }+ }+ }+}++/// Why a tile's apply to one leaf was dropped without a write. Each arm is a metric label.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum SeedDropReason {+ /// The leaf's `explicit_datetime` range excludes the tile's day (the bounds are not in the+ /// bytecode, so the reverse index over-delivers).+ ExplicitRangeExcludesDay,+ /// Below the window after the slide to "now"; applying would resurrect an expired record.+ DayBelowWindow,+ /// The Single analog of the slide-drop: the recomputed deadline is already due.+ WindowElapsed,+ /// The stored record or leaf variant does not match what the tile can merge into.+ VariantMismatch,+ /// The catalog meta lacks the window/op the variant requires.+ MetaIncomplete,+ /// A sub-day window: a whole-day tile cannot represent it, so hourly leaves are not seeded.+ SubDayWindow,+}++impl SeedDropReason {+ pub(crate) fn as_str(self) -> &'static str {+ match self {+ Self::ExplicitRangeExcludesDay => "explicit_range_excludes_day",+ Self::DayBelowWindow => "day_below_window",+ Self::WindowElapsed => "window_elapsed",+ Self::VariantMismatch => "variant_mismatch",+ Self::MetaIncomplete => "meta_incomplete",+ Self::SubDayWindow => "sub_day_window",+ }+ }+}++/// One leaf's merge outcome; `Unchanged` (byte-identical post-merge record) is the tile+/// idempotency.+#[must_use]+#[derive(Debug, Clone, PartialEq)]+pub(crate) enum LeafMergeOutcome {+ Merged {+ record: StatefulRecord,+ transition: Option<LeafTransition>,+ /// The recomputed eviction deadline ([`i64::MAX`] = permanent, never scheduled).+ deadline_ms: i64,+ },+ Unchanged,+ Dropped(SeedDropReason),+}++/// Identity of the leaf being merged into, so the pure core can mint transitions.+#[derive(Debug, Clone, Copy)]+pub(crate) struct LeafIdentity {+ pub team_id: TeamId,+ pub lsk: LeafStateKey,+ pub person_id: Uuid,+ pub condition_hash: [u8; 16],+}++impl LeafIdentity {+ fn transition(&self, kind: TransitionKind) -> LeafTransition {+ LeafTransition {+ team_id: self.team_id,+ leaf_state_key: self.lsk,+ person_id: self.person_id,+ condition_hash: self.condition_hash,+ kind,+ }+ }+}++/// Merge one day-tile into one leaf's state. Total: every mismatch is a counted drop, never a+/// panic.+#[allow(clippy::too_many_arguments)]+pub(crate) fn merge_tile_into_leaf(+ meta: &LeafStateMeta,+ tz: Tz,+ identity: LeafIdentity,+ tile_day: DayIdx,+ count: NonZeroU32,+ prev: Option<StatefulRecord>,+ now_day: DayIdx,+ now_ms: i64,+) -> LeafMergeOutcome {+ match meta.variant {+ StateVariant::BehavioralSingle => {+ merge_single(meta.window, tz, identity, tile_day, prev, now_ms)+ }+ StateVariant::BehavioralDailyBuckets => merge_daily(+ meta.window_days,+ meta.predicate_op,+ tz,+ identity,+ tile_day,+ count,+ prev,+ now_day,+ ),+ StateVariant::BehavioralCompressedHistory => merge_compressed(+ meta.window_days,+ meta.predicate_op,+ tz,+ identity,+ tile_day,+ count,+ prev,+ now_day,+ ),+ StateVariant::PersonProperty => LeafMergeOutcome::Dropped(SeedDropReason::VariantMismatch),+ }+}++/// Last millisecond of `tile_day` in the team tz — for calendar-floored (`RelativeDays`) windows+/// exactly equivalent to any same-day live instant.+fn end_of_day_ms(tile_day: DayIdx, tz: Tz) -> i64 {+ start_of_day_ms_in_tz(tile_day.saturating_add(1), tz).saturating_sub(1)+}++fn merge_single(+ window: Option<EvictionWindow>,+ tz: Tz,+ identity: LeafIdentity,+ tile_day: DayIdx,+ prev: Option<StatefulRecord>,+ now_ms: i64,+) -> LeafMergeOutcome {+ let Some(window) = window else {+ return LeafMergeOutcome::Dropped(SeedDropReason::MetaIncomplete);+ };+ match window {+ EvictionWindow::RelativeSeconds { .. } => {+ return LeafMergeOutcome::Dropped(SeedDropReason::SubDayWindow)+ }+ EvictionWindow::Explicit { from_day, to_day } => {+ // Day-granularity, inclusive — mirrors the event path's explicit-range check.+ let before_from = from_day.is_some_and(|from| tile_day < from);+ let after_to = to_day.is_some_and(|to| tile_day > to);+ if before_from || after_to {+ return LeafMergeOutcome::Dropped(SeedDropReason::ExplicitRangeExcludesDay);+ }+ }+ 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 {+ Stage1State::BehavioralSingle {+ last_event_at_ms, ..+ } => (+ last_event_at_ms,+ before,+ record.applied_offsets,+ record.redirect_dedup,+ ),+ _ => return LeafMergeOutcome::Dropped(SeedDropReason::VariantMismatch),+ }+ }+ };++ let last_event_at_ms = prev_last.max(end_of_day_ms(tile_day, tz));+ let earliest_eviction_at_ms = window.earliest_eviction_at_ms(last_event_at_ms, tz);+ if earliest_eviction_at_ms <= now_ms {+ return LeafMergeOutcome::Dropped(SeedDropReason::WindowElapsed);+ }++ let record = StatefulRecord {+ state: Stage1State::BehavioralSingle {+ has_match: true,+ last_event_at_ms,+ earliest_eviction_at_ms,+ },+ applied_offsets: applied,+ redirect_dedup: redirect,+ };+ finish(+ identity,+ prev_state,+ record,+ predicate_before,+ true,+ earliest_eviction_at_ms,+ )+}++#[allow(clippy::too_many_arguments)]+fn merge_daily(+ window_days: Option<u32>,+ op: Option<PredicateOp>,+ tz: Tz,+ identity: LeafIdentity,+ tile_day: DayIdx,+ count: NonZeroU32,+ prev: Option<StatefulRecord>,+ now_day: DayIdx,+) -> LeafMergeOutcome {+ let (Some(window_days), Some(op)) = (window_days, op) else {+ return LeafMergeOutcome::Dropped(SeedDropReason::MetaIncomplete);+ };+ 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 {+ Stage1State::BehavioralDailyBuckets {+ buckets,+ window_start_day,+ last_event_at_ms,+ ..+ } => {+ let before = daily_predicate(&buckets, op);+ (+ Some((buckets, window_start_day, last_event_at_ms)),+ before,+ record.applied_offsets,+ record.redirect_dedup,+ )+ }+ _ => return LeafMergeOutcome::Dropped(SeedDropReason::VariantMismatch),+ },+ };++ // A future-dated tile extends the target like a client-skewed live event would, keeping+ // apply order commutative.+ let target_now_day = now_day.max(tile_day);+ let (mut buckets, mut window_start_day, prev_last) = match prior {+ Some((buckets, start, last)) if buckets.len() == len => (buckets, start, last),+ Some(_) => return LeafMergeOutcome::Dropped(SeedDropReason::VariantMismatch),+ None => (+ vec![0; len],+ window_start_for_now(target_now_day, window_days),+ i64::MIN,+ ),+ };+ slide_window_forward(+ &mut buckets,+ &mut window_start_day,+ window_days,+ target_now_day,+ );++ if tile_day < window_start_day {+ return LeafMergeOutcome::Dropped(SeedDropReason::DayBelowWindow);+ }+ let idx = (tile_day - window_start_day) as usize;+ let Some(bucket) = buckets.get_mut(idx) else {+ // Unreachable: tile_day ≤ target_now_day = window_start + window_days ⇒ idx < len.+ return LeafMergeOutcome::Dropped(SeedDropReason::DayBelowWindow);+ };+ *bucket = (*bucket).max(count.get());++ let last_event_at_ms = prev_last.max(end_of_day_ms(tile_day, tz));+ let earliest_eviction_at_ms =+ daily_eviction_deadline(&buckets, window_start_day, window_days, tz);+ let predicate_after = daily_predicate(&buckets, op);++ let record = StatefulRecord {+ state: Stage1State::BehavioralDailyBuckets {+ buckets,+ window_start_day,+ last_event_at_ms,+ earliest_eviction_at_ms,+ },+ applied_offsets: applied,+ redirect_dedup: redirect,+ };+ finish(+ identity,+ prev_state,+ record,+ predicate_before,+ predicate_after,+ earliest_eviction_at_ms,+ )+}++#[allow(clippy::too_many_arguments)]+fn merge_compressed(+ window_days: Option<u32>,+ op: Option<PredicateOp>,+ tz: Tz,+ identity: LeafIdentity,+ tile_day: DayIdx,+ count: NonZeroU32,+ 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 {+ Stage1State::BehavioralCompressedHistory {+ entries,+ window_start_day,+ last_event_at_ms,+ ..+ } => {+ let before = compressed_predicate(&entries, op);+ (+ Some((entries, window_start_day, last_event_at_ms)),+ before,+ record.applied_offsets,+ record.redirect_dedup,+ )+ }+ _ => return LeafMergeOutcome::Dropped(SeedDropReason::VariantMismatch),+ },+ };++ let target_now_day = now_day.max(tile_day);+ let (mut entries, mut window_start_day, prev_last) = match prior {+ Some((entries, start, last)) => (entries, start, last),+ None => (+ Vec::new(),+ window_start_for_now(target_now_day, window_days),+ i64::MIN,+ ),+ };+ compressed_history::slide_window_forward(+ &mut entries,+ &mut window_start_day,+ window_days,+ target_now_day,+ );++ if tile_day < window_start_day {+ return LeafMergeOutcome::Dropped(SeedDropReason::DayBelowWindow);+ }+ compressed_history::merge_day_count(&mut entries, tile_day, count.get());++ let last_event_at_ms = prev_last.max(end_of_day_ms(tile_day, tz));+ let earliest_eviction_at_ms =+ compressed_history::compressed_eviction_deadline(&entries, window_days, tz);+ let predicate_after = compressed_predicate(&entries, op);++ let record = StatefulRecord {+ state: Stage1State::BehavioralCompressedHistory {+ entries,+ window_start_day,+ last_event_at_ms,+ earliest_eviction_at_ms,+ },+ applied_offsets: applied,+ redirect_dedup: redirect,+ };+ finish(+ identity,+ prev_state,+ record,+ predicate_before,+ predicate_after,+ earliest_eviction_at_ms,+ )+}++/// `Unchanged` detection + transition minting shared by all three variants.+fn finish(+ identity: LeafIdentity,+ prev_state: Option<Stage1State>,+ record: StatefulRecord,+ predicate_before: bool,+ predicate_after: bool,+ deadline_ms: i64,+) -> LeafMergeOutcome {+ if prev_state.as_ref() == Some(&record.state) {+ return LeafMergeOutcome::Unchanged;+ }+ let kind = match (predicate_before, predicate_after) {+ (false, true) => Some(TransitionKind::Entered),+ (true, false) => Some(TransitionKind::Left),+ _ => None,+ };+ LeafMergeOutcome::Merged {+ record,+ transition: kind.map(|kind| identity.transition(kind)),+ deadline_ms,+ }+}++/// 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>,+ 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::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_tile(tile, resolution, MAX_CROSS_PARTITION_REDIRECT_HOPS) {+ TileRoute::ApplyLocal { person } => person,+ TileRoute::ReProduce { tile: 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;+ }+ TileRoute::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+ }+ };++ 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;+ }+ };++ let now_ms = Utc::now().timestamp_millis();+ let now_day = day_idx_in_tz(now_ms, filters.timezone);+ let TileApplication {+ staged,+ transitions,+ stage2_leaves,+ schedules,+ } = apply_tile_to_leaves(+ filters, &prefix, lsks, values, tile, person, now_day, now_ms,+ );++ // Order: stage-1 commit → stage-2 recompute → produce → stage-2 commit → schedule → mark.+ 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 mut changes: Vec<CohortMembershipChange> = Vec::new();+ for transition in &transitions {+ if let Some(kind) = transition_metric_label(filters, transition) {+ counter!(STAGE1_TRANSITIONS, "kind" => kind).increment(1);+ }+ changes.extend(map_transition(filters, transition, last_updated));+ }+ // `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 recompute = match recompute_stage2(+ partition_id,+ handle,+ filters,+ &stage2_leaves,+ now_ms,+ last_updated,+ ReadLane::Maintenance,+ )+ .await+ {+ Ok(recompute) => recompute,+ 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;+ }+ };+ changes.extend(recompute.changes.iter().cloned());++ 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 {+ // Replay re-derives the stage-2 flips (bits unwritten); a lost single-leaf change is+ // not re-emitted — the reconcile snapshot heals that class.+ 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;+ }++ // The bits commit only after both produces ack, so a failed produce is re-derived on replay+ // instead of lost against a flipped bit; replay duplicates are LWW-safe downstream.+ 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();++ for (key, deadline) in schedules {+ queue.schedule(key, deadline);+ }+ mark_processed(&merge.seed_tracker, partition_id, offset);+}++/// What one tile staged across its referencing leaves.+#[derive(Default)]+struct TileApplication {+ staged: StagedBatch,+ transitions: Vec<LeafTransition>,+ /// Merged *and* Unchanged leaves both recompose Stage 2, so a crash between the two commits+ /// self-heals on replay.+ stage2_leaves: Vec<(LeafStateKey, Uuid)>,+ schedules: Vec<(BehavioralKey, 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;+ }+ },+ };+ 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.staged.put::<Behavioral>(&key, &record.encode());+ application.stage2_leaves.push((lsk, person));+ if let Some(transition) = transition {+ application.transitions.push(transition);+ }+ if deadline_ms != i64::MAX {+ application.schedules.push((key, deadline_ms));+ }+ }+ LeafMergeOutcome::Unchanged => {+ counter!(SEED_TILES_UNCHANGED_TOTAL, "variant" => meta.variant.as_str())+ .increment(1);+ application.stage2_leaves.push((lsk, person));+ }+ LeafMergeOutcome::Dropped(reason) => {+ counter!(SEED_TILES_DROPPED_TOTAL, "reason" => reason.as_str()).increment(1);+ }+ }+ }+ application+}++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.+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)",+ );+ }+}++/// Pin the seed commit floor at the failed offset so Kafka redelivers it; emit+/// [`SEED_HELD_OFFSET_GAUGE`] so the stall is visible.+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 chrono_tz::America::New_York;+ use chrono_tz::UTC;+ use proptest::prelude::*;+ use serde_json::{json, Value};+ use tempfile::TempDir;++ use cohort_core::seed::{ClaimEpoch, ConditionHash, SChunkMs, SeedTile};++ use crate::consumers::seeds::SeedSkipReason;+ use crate::filters::{CohortId, FilterCatalog, TeamFiltersBuilder};+ use crate::merge::transfer::Tombstone;+ use crate::partitions::partitioner::{partition_of, COHORT_PARTITION_COUNT};+ use crate::producer::{CaptureSeedTileSink, CaptureSink, MembershipStatus};+ use crate::stage1::state::AppliedOffsets;+ use crate::stage2::state::Stage2State;+ use crate::store::{+ CohortStore, OffloadConfig, OffloadMode, Stage2Key, StoreConfig, TombstoneKey,+ };+ use crate::workers::event_path::{process_event_gated, EventNameGating};++ use super::*;++ const TEAM: TeamId = TeamId(7);+ 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;++ fn now_day() -> DayIdx {+ day_idx_in_tz(NOW_MS, UTC)+ }++ fn identity() -> LeafIdentity {+ LeafIdentity {+ team_id: TEAM,+ lsk: LeafStateKey([0xAB; 16]),+ person_id: Uuid::from_u128(0xA11CE),+ condition_hash: HASH,+ }+ }++ fn single_meta(window: EvictionWindow) -> LeafStateMeta {+ LeafStateMeta {+ variant: StateVariant::BehavioralSingle,+ condition_hash: HASH,+ window: Some(window),+ window_days: None,+ predicate_op: None,+ }+ }++ fn daily_meta(window_days: u32, op: PredicateOp) -> LeafStateMeta {+ LeafStateMeta {+ variant: StateVariant::BehavioralDailyBuckets,+ condition_hash: HASH,+ window: None,+ window_days: Some(window_days),+ predicate_op: Some(op),+ }+ }++ fn compressed_meta(window_days: u32, op: PredicateOp) -> LeafStateMeta {+ LeafStateMeta {+ variant: StateVariant::BehavioralCompressedHistory,+ condition_hash: HASH,+ window: None,+ window_days: Some(window_days),+ predicate_op: Some(op),+ }+ }++ fn count(n: u32) -> NonZeroU32 {+ NonZeroU32::new(n).unwrap()+ }++ fn merge(+ meta: &LeafStateMeta,+ tile_day: DayIdx,+ n: u32,+ prev: Option<StatefulRecord>,+ ) -> LeafMergeOutcome {+ merge_tile_into_leaf(+ meta,+ UTC,+ identity(),+ tile_day,+ count(n),+ prev,+ now_day(),+ NOW_MS,+ )+ }++ fn merged(outcome: LeafMergeOutcome) -> (StatefulRecord, Option<LeafTransition>, i64) {+ match outcome {+ LeafMergeOutcome::Merged {+ record,+ transition,+ deadline_ms,+ } => (record, transition, deadline_ms),+ other => panic!("expected Merged, got {other:?}"),+ }+ }++ #[test]+ fn single_tile_enters_with_the_live_paths_exact_deadline_and_replays_unchanged() {+ let meta = single_meta(EvictionWindow::RelativeDays { days: 7 });+ let (record, transition, deadline) = merged(merge(&meta, now_day(), 1, None));++ assert_eq!(+ transition.map(|t| t.kind),+ Some(TransitionKind::Entered),+ "a fresh in-window tile enters",+ );+ // The end-of-day synthetic instant yields exactly the deadline any same-day live+ // instant would (RelativeDays calendar-floors its anchor).+ assert_eq!(+ deadline,+ EvictionWindow::RelativeDays { days: 7 }.earliest_eviction_at_ms(NOW_MS, UTC),+ );++ assert_eq!(+ merge(&meta, now_day(), 1, Some(record)),+ LeafMergeOutcome::Unchanged,+ "re-delivery is a structural no-op",+ );+ }++ #[test]+ fn single_sub_day_window_is_never_seeded() {+ let meta = single_meta(EvictionWindow::RelativeSeconds { seconds: 3_600 });+ assert_eq!(+ merge(&meta, now_day(), 1, None),+ LeafMergeOutcome::Dropped(SeedDropReason::SubDayWindow),+ );+ }++ #[test]+ fn single_elapsed_window_drops_instead_of_flapping() {+ // A 7-day window tile 9 days old: the recomputed deadline is already due, so applying+ // would enter → sweep → left. Prev state stays untouched (total no-op).+ let meta = single_meta(EvictionWindow::RelativeDays { days: 7 });+ assert_eq!(+ merge(&meta, now_day() - 9, 1, None),+ LeafMergeOutcome::Dropped(SeedDropReason::WindowElapsed),+ );+ }++ #[test]+ fn single_explicit_bounds_gate_the_tile_day_and_hold_forever_in_range() {+ let day = now_day();+ let cases = [+ (+ Some(day - 5),+ Some(day + 5),+ day,+ true,+ "inside both bounds",+ ),+ (Some(day - 5), Some(day + 5), day - 6, false, "before from"),+ (Some(day - 5), Some(day + 5), day + 6, false, "after to"),+ (+ Some(day - 5),+ Some(day + 5),+ day - 5,+ true,+ "inclusive from",+ ),+ (Some(day - 5), Some(day + 5), day + 5, true, "inclusive to"),+ (Some(day - 5), None, day + 400, true, "open above"),+ (None, Some(day + 5), day - 400, true, "open below"),+ (None, None, day - 1_000, true, "unbounded"),+ ];+ for (from_day, to_day, tile_day, in_range, why) in cases {+ let meta = single_meta(EvictionWindow::Explicit { from_day, to_day });+ let outcome = merge(&meta, tile_day, 1, None);+ if in_range {+ let (_, transition, deadline) = merged(outcome);+ assert_eq!(+ deadline,+ i64::MAX,+ "{why}: explicit membership is permanent"+ );+ assert_eq!(+ transition.map(|t| t.kind),+ Some(TransitionKind::Entered),+ "{why}"+ );+ } else {+ assert_eq!(+ outcome,+ LeafMergeOutcome::Dropped(SeedDropReason::ExplicitRangeExcludesDay),+ "{why}",+ );+ }+ }+ }++ #[test]+ fn daily_fresh_tile_anchors_at_wall_clock_now_and_merges_at_the_right_index() {+ let meta = daily_meta(7, PredicateOp::Gte(3));+ let (record, transition, deadline) = merged(merge(&meta, now_day() - 2, 3, None));++ let Stage1State::BehavioralDailyBuckets {+ ref buckets,+ window_start_day,+ earliest_eviction_at_ms,+ ..+ } = record.state+ else {+ panic!("daily variant expected");+ };+ assert_eq!(+ window_start_day,+ now_day() - 7,+ "anchored at now, not the tile day"+ );+ let mut expected = vec![0u32; 8];+ expected[5] = 3; // (now − 2) − (now − 7)+ assert_eq!(*buckets, expected);+ assert_eq!(transition.map(|t| t.kind), Some(TransitionKind::Entered));+ assert_eq!(+ deadline,+ start_of_day_ms_in_tz(now_day() - 2 + 7 + 1, UTC),+ "deadline from the oldest (only) non-zero bucket",+ );+ assert_eq!(deadline, earliest_eviction_at_ms);+ }++ #[test]+ fn daily_below_window_tile_drops_without_resurrecting_after_a_sweep_delete() {+ let meta = daily_meta(7, PredicateOp::Gte(1));++ // First delivery, in-window: enters.+ let (_, transition, _) = merged(merge(&meta, now_day(), 1, None));+ assert_eq!(transition.map(|t| t.kind), Some(TransitionKind::Entered));++ // The sweep later deletes the record; the tile is re-delivered once its day has left the+ // window. The fresh-path anchor at wall-clock "now" must classify it below-window and drop+ // before any write — no record, no `Entered`, no re-flap.+ let later_now_ms = NOW_MS + 10 * 86_400_000;+ let later_now_day = day_idx_in_tz(later_now_ms, UTC);+ assert_eq!(+ merge_tile_into_leaf(+ &meta,+ UTC,+ identity(),+ now_day(),+ count(1),+ None,+ later_now_day,+ later_now_ms,+ ),+ LeafMergeOutcome::Dropped(SeedDropReason::DayBelowWindow),+ );+ }++ #[test]+ fn daily_slide_before_evaluate_emits_the_slide_induced_left() {+ // Prev record: 3 matches on a day about to leave the window (predicate true under gte 3).+ // The tile lands on "now" with count 1; the slide zeroes the old day first, so the count+ // falls below the threshold and the merge emits `Left` — the pre-slide predicate is the+ // "before" side.+ let meta = daily_meta(7, PredicateOp::Gte(3));+ let old_anchor = now_day() - 12;+ let mut buckets = vec![0u32; 8];+ buckets[0] = 3; // day old_anchor − 7... window [old_anchor-7? no: [start ..= start+7]+ let prev = StatefulRecord::new(+ Stage1State::BehavioralDailyBuckets {+ buckets,+ window_start_day: old_anchor,+ last_event_at_ms: NOW_MS - 12 * 86_400_000,+ earliest_eviction_at_ms: start_of_day_ms_in_tz(old_anchor + 8, UTC),+ },+ AppliedOffsets::default(),+ );++ let (record, transition, _) = merged(merge(&meta, now_day(), 1, Some(prev)));+ assert_eq!(+ transition.map(|t| t.kind),+ Some(TransitionKind::Left),+ "slide-induced true→false must emit Left",+ );+ let Stage1State::BehavioralDailyBuckets {+ ref buckets,+ window_start_day,+ ..+ } = record.state+ else {+ panic!("daily variant expected");+ };+ assert_eq!(window_start_day, now_day() - 7, "the slide is persisted");+ assert_eq!(+ buckets.iter().sum::<u32>(),+ 1,+ "only the tile's day remains"+ );+ }++ #[test]+ fn daily_max_merge_absorbs_live_overlap_exactly() {+ let meta = daily_meta(7, PredicateOp::Gte(10));+ let (live, _, _) = merged(merge(&meta, now_day(), 3, None));++ // A tile counting a subset (late-arrival overlap) is absorbed: max(3, 2) = 3 → Unchanged.+ assert_eq!(+ merge(&meta, now_day(), 2, Some(live.clone())),+ LeafMergeOutcome::Unchanged,+ );+ // A tile counting a superset raises the bucket to the absolute count, never the sum.+ let (after, _, _) = merged(merge(&meta, now_day(), 5, Some(live)));+ let Stage1State::BehavioralDailyBuckets { ref buckets, .. } = after.state else {+ panic!("daily variant expected");+ };+ assert_eq!(buckets.iter().sum::<u32>(), 5);+ }++ #[test]+ fn compressed_merges_and_replays_unchanged() {+ let meta = compressed_meta(365, PredicateOp::Gte(2));+ let (record, transition, deadline) = merged(merge(&meta, now_day() - 30, 2, None));++ let Stage1State::BehavioralCompressedHistory {+ ref entries,+ window_start_day,+ ..+ } = record.state+ else {+ panic!("compressed variant expected");+ };+ assert_eq!(*entries, vec![(now_day() - 30, 2)]);+ assert_eq!(window_start_day, now_day() - 365);+ assert_eq!(transition.map(|t| t.kind), Some(TransitionKind::Entered));+ assert_eq!(+ deadline,+ start_of_day_ms_in_tz(now_day() - 30 + 365 + 1, UTC)+ );++ assert_eq!(+ merge(&meta, now_day() - 30, 2, Some(record)),+ LeafMergeOutcome::Unchanged,+ );+ }++ #[test]+ fn mismatched_meta_and_state_drop_totally() {+ // A person-property LSK sharing the hash must never absorb a behavioral tile.+ let person_meta = LeafStateMeta {+ variant: StateVariant::PersonProperty,+ condition_hash: HASH,+ window: None,+ window_days: None,+ predicate_op: None,+ };+ assert_eq!(+ merge(&person_meta, now_day(), 1, None),+ LeafMergeOutcome::Dropped(SeedDropReason::VariantMismatch),+ );++ // Meta lacking its window/op is incomplete, not a panic.+ let broken = LeafStateMeta {+ variant: StateVariant::BehavioralDailyBuckets,+ condition_hash: HASH,+ window: None,+ window_days: None,+ predicate_op: None,+ };+ assert_eq!(+ merge(&broken, now_day(), 1, None),+ LeafMergeOutcome::Dropped(SeedDropReason::MetaIncomplete),+ );++ // A stored record of a different variant than the meta's is a mismatch drop.+ let single_record = StatefulRecord::new(+ Stage1State::BehavioralSingle {+ has_match: true,+ last_event_at_ms: NOW_MS,+ earliest_eviction_at_ms: i64::MAX,+ },+ AppliedOffsets::default(),+ );+ assert_eq!(+ merge(+ &daily_meta(7, PredicateOp::Gte(1)),+ now_day(),+ 1,+ Some(single_record)+ ),+ LeafMergeOutcome::Dropped(SeedDropReason::VariantMismatch),+ );+ }++ #[test]+ fn dedup_maps_ride_through_bit_identical() {+ // The tile never touches `applied_offsets`/`redirect_dedup`.+ let meta = daily_meta(7, PredicateOp::Gte(1));+ let mut applied = AppliedOffsets::default();+ applied.record(17, 42);+ applied.record(3, 9);+ let mut redirect: BTreeMap<Uuid, AppliedOffsets> = BTreeMap::new();+ let mut ancestor = AppliedOffsets::default();+ ancestor.record(5, 100);+ redirect.insert(Uuid::from_u128(1), ancestor);+ let prev = StatefulRecord {+ state: Stage1State::BehavioralDailyBuckets {+ buckets: vec![0; 8],+ window_start_day: now_day() - 7,+ last_event_at_ms: NOW_MS - 1,+ earliest_eviction_at_ms: i64::MAX,+ },+ applied_offsets: applied.clone(),+ redirect_dedup: redirect.clone(),+ };++ let (record, _, _) = merged(merge(&meta, now_day(), 4, Some(prev)));+ assert_eq!(record.applied_offsets, applied);+ assert_eq!(record.redirect_dedup, redirect);+ }++ #[test]+ fn route_tile_maps_each_resolution_and_caps_the_hop_budget() {+ let tile = tile_for(Uuid::from_u128(0xA11CE), now_day(), 1);+ let survivor = Uuid::from_u128(0xB0B);++ assert_eq!(+ route_tile(&tile, Resolution::NotMerged, 8),+ TileRoute::ApplyLocal {+ person: tile.person_id()+ },+ );+ assert_eq!(+ route_tile(+ &tile,+ Resolution::Inline {+ final_person: survivor,+ origin: tile.person_id()+ },+ 8,+ ),+ TileRoute::ApplyLocal { person: survivor },+ );+ match route_tile(+ &tile,+ Resolution::CrossPartition {+ target_person: survivor,+ origin: tile.person_id(),+ },+ 8,+ ) {+ TileRoute::ReProduce { tile: rekeyed } => {+ assert_eq!(rekeyed.person_id(), survivor);+ assert_eq!(rekeyed.redirect_hops(), 1);+ assert_eq!(+ rekeyed.s_chunk_ms(),+ tile.s_chunk_ms(),+ "fence input rides verbatim"+ );+ }+ other => panic!("expected ReProduce, got {other:?}"),+ }+ // Cap 0: an over-cap re-produce is unrepresentable — the cap arm is forced.+ assert_eq!(+ route_tile(+ &tile,+ Resolution::CrossPartition {+ target_person: survivor,+ origin: tile.person_id(),+ },+ 0,+ ),+ TileRoute::CapExhausted { person: survivor },+ );+ }++ /// Apply a tile multiset in order, threading the record through.+ fn apply_all(+ meta: &LeafStateMeta,+ tiles: &[(i32, u32)],+ now_day: DayIdx,+ now_ms: i64,+ ) -> Option<StatefulRecord> {+ let mut prev: Option<StatefulRecord> = None;+ for &(offset, n) in tiles {+ let outcome = merge_tile_into_leaf(+ meta,+ UTC,+ identity(),+ now_day - offset,+ count(n),+ prev.clone(),+ now_day,+ now_ms,+ );+ if let LeafMergeOutcome::Merged { record, .. } = outcome {+ prev = Some(record);+ }+ }+ prev+ }++ proptest! {+ #![proptest_config(ProptestConfig::with_cases(64))]++ /// An arbitrary tile multiset applied in an arbitrary order (some tiles below the+ /// window) reaches one unique final state.+ #[test]+ fn daily_apply_order_commutes(+ (tiles, shuffled) in prop::collection::vec((0i32..=12, 1u32..=5), 1..10)+ .prop_flat_map(|tiles| {+ let shuffled = Just(tiles.clone()).prop_shuffle();+ (Just(tiles), shuffled)+ })+ ) {+ let meta = daily_meta(7, PredicateOp::Gte(3));+ prop_assert_eq!(+ apply_all(&meta, &tiles, now_day(), NOW_MS),+ apply_all(&meta, &shuffled, now_day(), NOW_MS),+ );+ }++ /// apply ∘ apply = apply: after a multiset lands, re-applying any of its tiles is never a+ /// `Merged` (only `Unchanged` or a below-window `Dropped`).+ #[test]+ fn daily_replay_is_never_a_second_merge(+ tiles in prop::collection::vec((0i32..=12, 1u32..=5), 1..10)+ ) {+ let meta = daily_meta(7, PredicateOp::Gte(3));+ let settled = apply_all(&meta, &tiles, now_day(), NOW_MS);+ for &(offset, n) in &tiles {+ let outcome = merge_tile_into_leaf(+ &meta,+ UTC,+ identity(),+ now_day() - offset,+ count(n),+ settled.clone(),+ now_day(),+ NOW_MS,+ );+ prop_assert!(+ !matches!(outcome, LeafMergeOutcome::Merged { .. }),+ "replay of ({}, {}) merged again: {:?}",+ offset,+ n,+ outcome,+ );+ }+ }++ /// Same two properties for the sparse variant, whose merge op (`merge_day_count`) is new.+ #[test]+ fn compressed_apply_order_commutes_and_replays_unchanged(+ (tiles, shuffled) in prop::collection::vec((0i32..=400, 1u32..=5), 1..10)+ .prop_flat_map(|tiles| {+ let shuffled = Just(tiles.clone()).prop_shuffle();+ (Just(tiles), shuffled)+ })+ ) {+ let meta = compressed_meta(365, PredicateOp::Gte(3));+ let settled = apply_all(&meta, &tiles, now_day(), NOW_MS);+ prop_assert_eq!(+ settled.clone(),+ apply_all(&meta, &shuffled, now_day(), NOW_MS),+ );+ for &(offset, n) in &tiles {+ let outcome = merge_tile_into_leaf(+ &meta,+ UTC,+ identity(),+ now_day() - offset,+ count(n),+ settled.clone(),+ now_day(),+ NOW_MS,+ );+ let replay_merged = matches!(outcome, LeafMergeOutcome::Merged { .. });+ prop_assert!(!replay_merged, "replay merged again");+ }+ }+ }++ // ---- live-equivalence: tile (d, N) on empty ≡ N same-day live events ----++ fn temp_store() -> (TempDir, CohortStore) {+ let dir = TempDir::new().unwrap();+ let store = CohortStore::open(&StoreConfig {+ path: dir.path().join("db"),+ ..StoreConfig::default()+ })+ .unwrap();+ (dir, store)+ }++ fn test_handle(store: &CohortStore) -> StoreHandle {+ StoreHandle::new(+ store.clone(),+ OffloadConfig {+ mode: OffloadMode::All,+ event_read_permits: 16,+ maintenance_permits: 6,+ },+ )+ }++ fn behavioral_bytecode() -> Value {+ json!(["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11])+ }++ fn single_leaf_json(window_days: i64) -> Value {+ json!({+ "type": "behavioral", "value": "performed_event", "key": "$pageview",+ "time_value": window_days, "time_interval": "day",+ "conditionHash": "0123456789abcdef",+ "bytecode": behavioral_bytecode(),+ })+ }++ fn multiple_leaf_json(window_days: i64, op: &str, value: i64) -> Value {+ json!({+ "type": "behavioral", "value": "performed_event_multiple", "key": "$pageview",+ "time_value": window_days, "time_interval": "day",+ "operator": op, "operator_value": value,+ "conditionHash": "0123456789abcdef",+ "bytecode": behavioral_bytecode(),+ })+ }++ fn wrap(values: Vec<Value>) -> Value {+ json!({ "properties": { "type": "AND", "values": values } })+ }++ fn build_filters(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.freeze(tz)+ }++ /// The ClickHouse-format timestamp of noon (team tz) on `day`.+ fn noon_ts(day: DayIdx, tz: chrono_tz::Tz) -> String {+ let ms = start_of_day_ms_in_tz(day, tz) + 12 * 3_600_000;+ chrono::DateTime::from_timestamp_millis(ms)+ .unwrap()+ .format("%Y-%m-%d %H:%M:%S%.6f")+ .to_string()+ }++ fn live_event(+ person: Uuid,+ timestamp: &str,+ source_offset: i64,+ ) -> crate::consumers::events::CohortStreamEvent {+ crate::consumers::events::CohortStreamEvent {+ team_id: TEAM.0,+ person_id: person.to_string(),+ distinct_id: "d".to_string(),+ uuid: "u".to_string(),+ event: "$pageview".to_string(),+ timestamp: timestamp.to_string(),+ properties: Some("{}".to_string()),+ person_properties: None,+ elements_chain: None,+ source_offset,+ source_partition: 0,+ redirected_from: None,+ redirect_hops: 0,+ }+ }++ /// One tile `(d, N)` merged onto empty state must equal `N` same-day events through the live+ /// fold — same buckets, window anchor, and deadline (`last_event_at_ms` and the dedup maps are+ /// the two designed differences). DST coverage via a non-UTC team tz.+ #[test]+ fn tile_on_empty_equals_n_live_same_day_events_for_every_variant() {+ for tz in [UTC, New_York] {+ let (_dir, store) = temp_store();+ let filters = build_filters(+ vec![+ (1, wrap(vec![single_leaf_json(7)])),+ (2, wrap(vec![multiple_leaf_json(7, "gte", 3)])),+ (3, wrap(vec![multiple_leaf_json(365, "gte", 3)])),+ ],+ tz,+ );+ let person = Uuid::from_u128(0xE0);+ let n = 3u32;+ let now_ms = chrono::Utc::now().timestamp_millis();+ let today = day_idx_in_tz(now_ms, tz);+ let ts = noon_ts(today, tz);+ let event_ms = crate::stage1::clickhouse_timestamp_to_millis(&ts).unwrap();++ for offset in 0..n {+ process_event_gated(+ 0,+ &store,+ &filters,+ &live_event(person, &ts, offset as i64),+ EventNameGating::Disabled,+ )+ .unwrap();+ }++ for &lsk in &filters.by_condition_to_lsk[&HASH] {+ let meta = &filters.by_lsk[&lsk];+ let key = PersonPrefix::new(0, TEAM.0 as u64, person).behavioral_key(lsk);+ let live =+ StatefulRecord::decode(&store.get_behavioral(&key).unwrap().unwrap()).unwrap();++ let seeded_identity = LeafIdentity {+ team_id: TEAM,+ lsk,+ person_id: person,+ condition_hash: HASH,+ };+ let (seeded, _, _) = merged(merge_tile_into_leaf(+ meta,+ tz,+ seeded_identity,+ today,+ count(n),+ None,+ today,+ now_ms,+ ));++ match (&live.state, &seeded.state) {+ (+ Stage1State::BehavioralSingle {+ earliest_eviction_at_ms: live_deadline,+ ..+ },+ Stage1State::BehavioralSingle {+ has_match,+ earliest_eviction_at_ms: seeded_deadline,+ ..+ },+ ) => {+ assert!(has_match);+ // Exact deadline equality against a live instant.+ assert_eq!(seeded_deadline, live_deadline, "single deadline, tz {tz}");+ assert_eq!(+ *seeded_deadline,+ EvictionWindow::RelativeDays { days: 7 }+ .earliest_eviction_at_ms(event_ms, tz),+ );+ }+ (+ Stage1State::BehavioralDailyBuckets {+ buckets: live_buckets,+ window_start_day: live_start,+ earliest_eviction_at_ms: live_deadline,+ ..+ },+ Stage1State::BehavioralDailyBuckets {+ buckets: seeded_buckets,+ window_start_day: seeded_start,+ earliest_eviction_at_ms: seeded_deadline,+ ..+ },+ ) => {+ assert_eq!(seeded_buckets, live_buckets, "daily buckets, tz {tz}");+ assert_eq!(seeded_start, live_start);+ assert_eq!(seeded_deadline, live_deadline);+ }+ (+ Stage1State::BehavioralCompressedHistory {+ entries: live_entries,+ window_start_day: live_start,+ earliest_eviction_at_ms: live_deadline,+ ..+ },+ Stage1State::BehavioralCompressedHistory {+ entries: seeded_entries,+ window_start_day: seeded_start,+ earliest_eviction_at_ms: seeded_deadline,+ ..+ },+ ) => {+ assert_eq!(seeded_entries, live_entries, "compressed entries, tz {tz}");+ assert_eq!(seeded_start, live_start);+ assert_eq!(seeded_deadline, live_deadline);+ }+ (live_state, seeded_state) => {+ panic!("variant mismatch: live {live_state:?} vs seeded {seeded_state:?}")+ }+ }+ }+ }+ }++ // ---- shell tests: handle_seed against a temp store ----++ fn tile_for(person: Uuid, day: DayIdx, n: u32) -> SeedTile {+ SeedTile::new(+ TEAM,+ person,+ ConditionHash::parse("0123456789abcdef").unwrap(),+ count(n),+ day,+ SChunkMs(1_700_000_000_000),+ RunId(Uuid::from_u128(0xBF)),+ ClaimEpoch(1),+ )+ }++ struct Shell {+ _dir: TempDir,+ store: CohortStore,+ handle: StoreHandle,+ catalog: Arc<CatalogHandle>,+ sink: CaptureSink,+ seed_sink: CaptureSeedTileSink,+ cascade_sink: crate::producer::CaptureCascadeSink,+ deps: MergeWorkerDeps,+ queue: EvictionQueue<BehavioralKey>,+ }++ impl Shell {+ fn new(cohorts: Vec<(i32, Value)>) -> Self {+ Self::with_sink(cohorts, CaptureSink::new(), CaptureSeedTileSink::new())+ }++ fn with_sink(+ cohorts: Vec<(i32, Value)>,+ sink: CaptureSink,+ seed_sink: CaptureSeedTileSink,+ ) -> Self {+ Self::build(+ cohorts,+ sink,+ seed_sink,+ crate::producer::CaptureCascadeSink::new(),+ crate::workers::CascadeConfig::default(),+ )+ }++ fn with_cascade(+ cohorts: Vec<(i32, Value)>,+ cascade_sink: crate::producer::CaptureCascadeSink,+ ) -> Self {+ Self::build(+ cohorts,+ CaptureSink::new(),+ CaptureSeedTileSink::new(),+ cascade_sink,+ crate::workers::CascadeConfig {+ enabled: true,+ depth_cap: 8,+ fanout_cap: 1000,+ },+ )+ }++ fn build(+ cohorts: Vec<(i32, Value)>,+ sink: CaptureSink,+ seed_sink: CaptureSeedTileSink,+ cascade_sink: crate::producer::CaptureCascadeSink,+ cascade: crate::workers::CascadeConfig,+ ) -> Self {+ let (_dir, store) = temp_store();+ let handle = test_handle(&store);+ let catalog = Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([(+ TEAM,+ build_filters(cohorts, UTC),+ )])));+ let deps = MergeWorkerDeps {+ transfer_sink: Arc::new(crate::producer::CaptureTransferSink::new()),+ stream_event_sink: Arc::new(crate::producer::CaptureStreamEventSink::new()),+ merge_tracker: Arc::new(OffsetTracker::new()),+ transfer_tracker: Arc::new(OffsetTracker::new()),+ retry: crate::workers::TransferRetryPolicy::default(),+ gc_scan_limit: crate::workers::DEFAULT_MERGE_GC_SCAN_LIMIT,+ stage2_orphan_gc_enabled: true,+ cascade_sink: Arc::new(cascade_sink.clone()),+ cascade_tracker: Arc::new(OffsetTracker::new()),+ cascade,+ partition_count: COHORT_PARTITION_COUNT,+ seed_tile_sink: Arc::new(seed_sink.clone()),+ seed_tracker: Arc::new(OffsetTracker::new()),+ live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),+ };+ Self {+ _dir,+ store,+ handle,+ catalog,+ sink,+ seed_sink,+ cascade_sink,+ deps,+ queue: EvictionQueue::new(),+ }+ }++ async fn run(&mut self, partition_id: u16, work: SeedWork, offset: i64) {+ self.deps+ .seed_tracker+ .mark_dispatched(partition_id as i32, offset + 1);+ let sink: Arc<dyn MembershipSink> = Arc::new(self.sink.clone());+ handle_seed(+ partition_id,+ &self.handle,+ &self.catalog,+ &sink,+ &self.deps,+ &mut self.queue,+ "2026-06-15 12:00:00.000000",+ &work,+ offset,+ )+ .await;+ }++ fn committable(&self, partition_id: u16) -> Option<i64> {+ self.deps+ .seed_tracker+ .committable_offsets()+ .get(&(partition_id as i32))+ .copied()+ }+ }++ fn today() -> DayIdx {+ day_idx_in_tz(chrono::Utc::now().timestamp_millis(), UTC)+ }++ #[tokio::test]+ async fn skip_work_marks_the_seed_offset_in_order() {+ let mut shell = Shell::new(vec![(1, wrap(vec![single_leaf_json(7)]))]);+ shell+ .run(0, SeedWork::Skip(SeedSkipReason::UnknownKind), 5)+ .await;+ assert_eq!(shell.committable(0), Some(6), "the skip's offset commits");+ assert!(shell.sink.changes().is_empty());+ }++ #[tokio::test]+ async fn tile_flip_emits_an_origin_tagged_change_and_schedules_eviction() {+ 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![single_leaf_json(7)]))]);+ let tile = tile_for(person, today(), 1);++ shell+ .run(partition_id, SeedWork::Tile(tile.clone()), 9)+ .await;++ let changes = shell.sink.changes();+ assert_eq!(changes.len(), 1, "the single-leaf cohort entered");+ assert_eq!(changes[0].status, MembershipStatus::Entered);+ assert_eq!(changes[0].origin, Some(ChangeOrigin::Seed));+ assert_eq!(changes[0].run_id, Some(tile.run_id()));+ assert_eq!(changes[0].person_id, person.to_string());+ assert_eq!(shell.committable(partition_id), Some(10));+ assert_eq!(shell.queue.len(), 1, "the leaf's eviction was scheduled");++ // Re-delivery: max-merge no-op, no duplicate emission, offset still advances.+ shell.run(partition_id, SeedWork::Tile(tile), 10).await;+ assert_eq!(shell.sink.changes().len(), 1);+ assert_eq!(shell.committable(partition_id), Some(11));+ }++ #[tokio::test]+ async fn unknown_team_and_unreferenced_hash_are_counted_drops_that_still_commit() {+ let person = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16;++ // No cohorts at all: the team resolves but the hash references nothing.+ let mut shell = Shell::new(vec![]);+ shell+ .run(+ partition_id,+ SeedWork::Tile(tile_for(person, today(), 1)),+ 3,+ )+ .await;+ assert!(shell.sink.changes().is_empty());+ assert_eq!(+ shell.committable(partition_id),+ Some(4),+ "a design-expected drop must not wedge the partition",+ );+ }++ fn write_tombstone(store: &CohortStore, partition_id: u16, old: Uuid, new: Uuid) {+ store+ .write_batch(|b| {+ b.put_tombstone(+ &TombstoneKey {+ partition_id,+ team_id: TEAM.0 as u64,+ person: old,+ },+ &Tombstone {+ new_person: new,+ merged_at_ms: 1,+ }+ .encode(),+ )+ })+ .unwrap();+ }++ fn cross_partition_pair() -> (Uuid, u16, Uuid) {+ let p_old = Uuid::from_u128(1);+ let partition_id = partition_of(TEAM, &p_old, COHORT_PARTITION_COUNT) as u16;+ let p_new = (10u128..)+ .map(Uuid::from_u128)+ .find(|p| partition_of(TEAM, p, COHORT_PARTITION_COUNT) as u16 != partition_id)+ .expect("some uuid hashes off p_old's partition");+ (p_old, partition_id, p_new)+ }++ #[tokio::test]+ async fn inline_redirect_applies_the_tile_at_the_survivor() {+ let p_old = Uuid::from_u128(0xA11CE);+ let partition_id = partition_of(TEAM, &p_old, COHORT_PARTITION_COUNT) as u16;+ let p_new = (10u128..)+ .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)]))]);+ write_tombstone(&shell.store, partition_id, p_old, p_new);++ shell+ .run(partition_id, SeedWork::Tile(tile_for(p_old, today(), 1)), 0)+ .await;++ let changes = shell.sink.changes();+ assert_eq!(changes.len(), 1);+ assert_eq!(+ changes[0].person_id,+ p_new.to_string(),+ "membership lands on the survivor, not the dead person",+ );+ assert_eq!(shell.committable(partition_id), Some(1));+ }++ #[tokio::test]+ async fn cross_partition_redirect_re_produces_the_rekeyed_tile_before_marking() {+ let (p_old, partition_id, p_new) = cross_partition_pair();+ let mut shell = Shell::new(vec![(1, wrap(vec![single_leaf_json(7)]))]);+ write_tombstone(&shell.store, partition_id, p_old, p_new);+ let tile = tile_for(p_old, today(), 2);++ shell+ .run(partition_id, SeedWork::Tile(tile.clone()), 7)+ .await;++ let produced = shell.seed_sink.tiles();+ assert_eq!(produced.len(), 1, "one re-keyed tile produced");+ assert_eq!(produced[0].person_id(), p_new);+ assert_eq!(produced[0].redirect_hops(), 1);+ assert_eq!(produced[0].s_chunk_ms(), tile.s_chunk_ms());+ assert!(shell.sink.changes().is_empty(), "no local apply");+ assert_eq!(+ shell.committable(partition_id),+ Some(8),+ "the acked re-produce releases the seed offset",+ );+ }++ #[tokio::test]+ async fn rekey_produce_failure_holds_the_seed_offset_until_a_later_success() {+ let (p_old, partition_id, p_new) = cross_partition_pair();+ let mut shell = Shell::with_sink(+ vec![(1, wrap(vec![single_leaf_json(7)]))],+ CaptureSink::new(),+ CaptureSeedTileSink::failing_first(1),+ );+ write_tombstone(&shell.store, partition_id, p_old, p_new);+ let tile = tile_for(p_old, today(), 2);++ shell+ .run(partition_id, SeedWork::Tile(tile.clone()), 7)+ .await;+ assert_eq!(+ shell.committable(partition_id),+ None,+ "the failed re-produce holds the seed offset",+ );++ // Redelivery with the sink healthy: the re-key lands and the hold is honored by the floor.+ shell.run(partition_id, SeedWork::Tile(tile), 7).await;+ assert_eq!(shell.seed_sink.tiles().len(), 1);+ // The tenure-sticky hold pins the committable at the held offset (redelivery replays it).+ assert_eq!(shell.committable(partition_id), Some(7));+ }++ #[tokio::test]+ async fn hop_capped_tile_applies_inline_at_the_best_known_target() {+ let (p_old, partition_id, p_new) = cross_partition_pair();+ let mut shell = Shell::new(vec![(1, wrap(vec![single_leaf_json(7)]))]);+ write_tombstone(&shell.store, partition_id, p_old, p_new);++ // Exhaust the hop budget on the wire, then deliver: rekeyed_to returns None at the cap.+ let mut tile = tile_for(p_old, today(), 1);+ for _ in 0..MAX_CROSS_PARTITION_REDIRECT_HOPS {+ tile = tile+ .rekeyed_to(p_old, MAX_CROSS_PARTITION_REDIRECT_HOPS)+ .unwrap();+ }+ shell.run(partition_id, SeedWork::Tile(tile), 0).await;++ assert!(shell.seed_sink.tiles().is_empty(), "no further re-produce");+ let changes = shell.sink.changes();+ assert_eq!(changes.len(), 1, "applied inline instead");+ assert_eq!(changes[0].person_id, p_new.to_string());+ assert_eq!(shell.committable(partition_id), Some(1));+ }++ /// Zero acks treated as success (the vacuous `all(is_ok)` on `[]`) would commit past a tile+ /// that was never re-produced.+ struct EmptyAckSink;++ #[async_trait::async_trait]+ impl crate::producer::SeedTileSink for EmptyAckSink {+ async fn produce(+ &self,+ _tiles: Vec<SeedTile>,+ ) -> Vec<Result<(), common_kafka::kafka_producer::KafkaProduceError>> {+ Vec::new()+ }+ }++ #[tokio::test]+ async fn an_empty_rekey_ack_vector_is_a_failure_not_a_vacuous_success() {+ let (p_old, partition_id, p_new) = cross_partition_pair();+ let mut shell = Shell::new(vec![(1, wrap(vec![single_leaf_json(7)]))]);+ write_tombstone(&shell.store, partition_id, p_old, p_new);+ shell.deps.seed_tile_sink = Arc::new(EmptyAckSink);++ shell+ .run(partition_id, SeedWork::Tile(tile_for(p_old, today(), 1)), 7)+ .await;++ assert_eq!(+ shell.committable(partition_id),+ None,+ "zero acks must hold the offset, never commit it",+ );+ assert!(shell.sink.changes().is_empty(), "no local apply either");+ }++ #[tokio::test]+ async fn membership_produce_failure_holds_the_seed_offset() {+ 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+ .run(+ partition_id,+ SeedWork::Tile(tile_for(person, today(), 1)),+ 4,+ )+ .await;+ assert_eq!(shell.committable(partition_id), None, "held for redelivery");+ }++ /// A seeded flip that never cascades leaves cohort-of-cohort referrers permanently stale.+ #[tokio::test]+ async fn seed_flip_with_cascade_on_produces_a_first_hop_cascade() {+ let person = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16;+ let cascade_sink = crate::producer::CaptureCascadeSink::new();+ let mut shell = Shell::with_cascade(+ vec![(1, wrap(vec![single_leaf_json(7)]))],+ cascade_sink.clone(),+ );+ let tile = tile_for(person, today(), 1);++ shell+ .run(partition_id, SeedWork::Tile(tile.clone()), 3)+ .await;++ assert_eq!(shell.sink.changes().len(), 1, "the cohort entered");+ let cascades = shell.cascade_sink.messages();+ assert_eq!(cascades.len(), 1, "one first-hop cascade for the flip");+ assert_eq!(cascades[0].change.cohort_id, 1);+ assert_eq!(cascades[0].depth, 1);+ assert_eq!(cascades[0].originating_cohort_id, 1);+ assert_eq!(+ cascades[0].change.origin,+ Some(ChangeOrigin::Seed),+ "the embedded change keeps its backfill provenance",+ );+ assert_eq!(+ shell.committable(partition_id),+ Some(4),+ "both acked produces release the seed offset",+ );++ // Re-delivery is Unchanged: no duplicate flip, no duplicate cascade.+ shell.run(partition_id, SeedWork::Tile(tile), 4).await;+ assert_eq!(shell.cascade_sink.messages().len(), 1);+ assert_eq!(shell.committable(partition_id), Some(5));+ }++ /// A failed cascade produce leaves the stage-2 bit unwritten, so the redelivery re-derives+ /// the composed flip and re-emits its cascade.+ #[tokio::test]+ async fn failed_composed_cascade_is_re_derived_and_emitted_on_redelivery() {+ let person = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16;+ // Both leaves satisfied by one tile, so the flip is stage-2-derived.+ let mut shell = Shell::with_cascade(+ vec![(+ 1,+ wrap(vec![single_leaf_json(7), multiple_leaf_json(7, "gte", 1)]),+ )],+ crate::producer::CaptureCascadeSink::failing_first(1),+ );+ let tile = tile_for(person, today(), 1);+ let stage2_key = Stage2Key {+ partition_id,+ team_id: TEAM.0 as u64,+ cohort_id: 1,+ person_id: person,+ };++ shell+ .run(partition_id, SeedWork::Tile(tile.clone()), 3)+ .await;+ assert_eq!(shell.committable(partition_id), None, "held for redelivery");+ assert!(shell.cascade_sink.messages().is_empty());+ assert!(+ shell.store.get_stage2(&stage2_key).unwrap().is_none(),+ "the stage-2 bit must stay unwritten under the failed produce",+ );++ shell.run(partition_id, SeedWork::Tile(tile), 3).await;+ let cascades = shell.cascade_sink.messages();+ assert_eq!(+ cascades.len(),+ 1,+ "the redelivery re-derived the flip and produced its cascade",+ );+ assert_eq!(cascades[0].change.cohort_id, 1);+ assert_eq!(+ shell.sink.changes().len(),+ 2,+ "the re-derived membership change re-emits too (a LWW-safe duplicate)",+ );+ assert!(+ Stage2State::decode(&shell.store.get_stage2(&stage2_key).unwrap().unwrap())+ .unwrap()+ .in_cohort,+ "the bit commits once both produces ack",+ );+ // The tenure-sticky hold pins the committable at the held offset (redelivery replays it).+ assert_eq!(shell.committable(partition_id), Some(3));+ }++ #[tokio::test]+ async fn seed_cascade_produce_failure_holds_the_seed_offset() {+ let person = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16;+ let mut shell = Shell::with_cascade(+ vec![(1, wrap(vec![single_leaf_json(7)]))],+ crate::producer::CaptureCascadeSink::failing_always(),+ );++ shell+ .run(+ partition_id,+ SeedWork::Tile(tile_for(person, today(), 1)),+ 3,+ )+ .await;++ assert_eq!(+ shell.sink.changes().len(),+ 1,+ "membership is the first leg and acked before the cascade leg",+ );+ assert!(shell.cascade_sink.messages().is_empty());+ assert_eq!(+ shell.committable(partition_id),+ None,+ "a failed cascade produce holds the seed offset for redelivery",+ );+ }++ /// Stage-1 committed but stage-2 lost: the replayed tile lands `Unchanged`, yet composition+ /// re-runs for every touched leaf and heals the stale bit.+ #[tokio::test]+ async fn unchanged_replay_recomposes_stage2_and_heals_a_stale_bit() {+ let person = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16;+ // Both leaves share the tile's hash, so one tile flips the composition.+ let mut shell = Shell::new(vec![(+ 1,+ wrap(vec![single_leaf_json(7), multiple_leaf_json(7, "gte", 1)]),+ )]);+ let tile = tile_for(person, today(), 1);++ shell+ .run(partition_id, SeedWork::Tile(tile.clone()), 0)+ .await;+ let changes = shell.sink.changes();+ assert_eq!(changes.len(), 1, "the composed cohort entered");+ assert_eq!(changes[0].cohort_id, 1);+ assert_eq!(changes[0].origin, Some(ChangeOrigin::Seed));++ // Simulate the crash window: the stage-2 bit rolls back while cf_behavioral stands.+ let stage2_key = Stage2Key {+ partition_id,+ team_id: TEAM.0 as u64,+ cohort_id: 1,+ person_id: person,+ };+ shell+ .store+ .write_batch(|b| {+ b.put_stage2(+ &stage2_key,+ &Stage2State {+ in_cohort: false,+ last_evaluated_at_ms: 1,+ }+ .encode(),+ )+ })+ .unwrap();++ shell.run(partition_id, SeedWork::Tile(tile), 1).await;+ let changes = shell.sink.changes();+ assert_eq!(+ changes.len(),+ 2,+ "the Unchanged replay still re-composed and re-emitted the flip",+ );+ assert_eq!(changes[1].status, MembershipStatus::Entered);+ assert_eq!(changes[1].origin, Some(ChangeOrigin::Seed));+ }+}diff --git a/rust/cohort-stream-processor/src/workers/stage2_path.rs b/rust/cohort-stream-processor/src/workers/stage2_path.rsindex 8183a37d496c..04fc9d8a5607 100644--- a/rust/cohort-stream-processor/src/workers/stage2_path.rs+++ b/rust/cohort-stream-processor/src/workers/stage2_path.rs@@ -20,7 +20,6 @@ use crate::producer::{CohortMembershipChange, MembershipStatus};use crate::stage1::key::LeafStateKey;use crate::stage1::person_record::PersonRecord;use crate::stage1::state::{Stage1State, StateVariant, StatefulRecord};-use crate::stage1::transition::LeafTransition;use crate::stage2::evaluator::{evaluate_tree, leaf_membership};use crate::stage2::state::Stage2State;use crate::stage2::CohortEligibility;@@ -28,31 +27,72 @@ use crate::store::{BehavioralKey, PersonRecordKey, ReadLane, Stage2Key, StagedBatch, StoreError, StoreHandle,};+/// `affected_leaves` is the touched `(leaf, person)` set; `lane` is the read lane every recompute+/// read runs on (`Maintenance` on the seed path, so backfill never contends with live reads).pub async fn compose_stage2(partition_id: u16,handle: &StoreHandle,filters: &TeamFilters,- transitions: &[LeafTransition],+ affected_leaves: &[(LeafStateKey, Uuid)],event_ms: i64,last_updated: &str,+ lane: ReadLane,) -> Result<Vec<CohortMembershipChange>, StoreError> {+ let recompute = recompute_stage2(+ partition_id,+ handle,+ filters,+ affected_leaves,+ event_ms,+ last_updated,+ lane,+ )+ .await?;+ commit_stage2_writes(handle, &recompute.writes).await?;+ recompute.record_metrics();+ Ok(recompute.changes)+}++/// Uncommitted recompute result: the flips and their pending `cf_stage2` writes. Lets+/// produce-before-state callers commit only after their produces ack, so a failed produce is+/// re-derived on replay.+pub(crate) struct Stage2Recompute {+ pub changes: Vec<CohortMembershipChange>,+ pub writes: Vec<(Stage2Key, Stage2State)>,+ evaluated: u64,+}++impl Stage2Recompute {+ /// Call only once the writes committed, so a failed commit's redelivery cannot double-count.+ pub(crate) fn record_metrics(&self) {+ counter!(STAGE2_COHORTS_EVALUATED).increment(self.evaluated);+ for change in &self.changes {+ counter!(STAGE2_TRANSITIONS, "kind" => change.status.as_str()).increment(1);+ }+ }+}++/// The read-only half of [`compose_stage2`].+pub(crate) async fn recompute_stage2(+ partition_id: u16,+ handle: &StoreHandle,+ filters: &TeamFilters,+ affected_leaves: &[(LeafStateKey, Uuid)],+ event_ms: i64,+ last_updated: &str,+ lane: ReadLane,+) -> Result<Stage2Recompute, StoreError> {let mut affected: BTreeSet<(CohortId, Uuid)> = BTreeSet::new();- for transition in transitions {- if let Some(cohorts) = filters- .by_lsk_to_composable_cohorts- .get(&transition.leaf_state_key)- {+ for &(leaf_state_key, person_id) in affected_leaves {+ if let Some(cohorts) = filters.by_lsk_to_composable_cohorts.get(&leaf_state_key) {for &cohort_id in cohorts {- affected.insert((cohort_id, transition.person_id));+ affected.insert((cohort_id, person_id));}}}- if affected.is_empty() {- return Ok(Vec::new());- }let mut changes = Vec::new();- let mut pending: Vec<(Stage2Key, Stage2State)> = Vec::new();+ let mut writes: Vec<(Stage2Key, Stage2State)> = Vec::new();let mut evaluated: u64 = 0;for (cohort_id, person_id) in affected {@@ -60,7 +100,7 @@ pub async fn compose_stage2(continue;};- let diff = recompute_and_diff(partition_id, person_id, tree, filters, handle).await?;+ let diff = recompute_and_diff(partition_id, person_id, tree, filters, handle, lane).await?;evaluated += 1;if !diff.flipped() {continue;@@ -72,9 +112,11 @@ pub async fn compose_stage2(person_id: person_id.to_string(),last_updated: last_updated.to_string(),status: diff.status(),+ origin: None,+ run_id: None,});// Write `false` rather than deleting so absence means "never evaluated".- pending.push((+ writes.push((diff.stage2_key,Stage2State {in_cohort: diff.new_bit,@@ -83,20 +125,26 @@ pub async fn compose_stage2());}- if !pending.is_empty() {- let mut staged = StagedBatch::default();- for (key, state) in &pending {- staged.put_stage2(key, &state.encode());- }- handle.commit(staged).await?;- }+ Ok(Stage2Recompute {+ changes,+ writes,+ evaluated,+ })+}- counter!(STAGE2_COHORTS_EVALUATED).increment(evaluated);- for change in &changes {- counter!(STAGE2_TRANSITIONS, "kind" => change.status.as_str()).increment(1);+/// Commit recomputed `cf_stage2` bits.+pub(crate) async fn commit_stage2_writes(+ handle: &StoreHandle,+ writes: &[(Stage2Key, Stage2State)],+) -> Result<(), StoreError> {+ if writes.is_empty() {+ return Ok(());}-- Ok(changes)+ let mut staged = StagedBatch::default();+ for (key, state) in writes {+ staged.put_stage2(key, &state.encode());+ }+ handle.commit(staged).await}/// One cohort's recomputed membership for one person, diffed against the stored `cf_stage2` bit.@@ -129,16 +177,26 @@ pub(crate) async fn recompute_and_diff(tree: &CohortTree,filters: &TeamFilters,handle: &StoreHandle,+ lane: ReadLane,) -> Result<RecomputeDiff, StoreError> {let team_id = tree.team_id.0 as u64;- let new_bit = evaluate_cohort(partition_id, team_id, person_id, tree, filters, handle).await?;+ let new_bit = evaluate_cohort(+ partition_id,+ team_id,+ person_id,+ tree,+ filters,+ handle,+ lane,+ )+ .await?;let stage2_key = Stage2Key {partition_id,team_id,cohort_id: tree.cohort_id.0 as u64,person_id,};- let prior_bit = read_stage2_bit(handle, &stage2_key).await?;+ let prior_bit = read_stage2_bit(handle, &stage2_key, lane).await?;Ok(RecomputeDiff {new_bit,prior_bit,@@ -148,6 +206,7 @@ pub(crate) async fn recompute_and_diff(/// Compose one cohort for one person. A leaf with absent or undecodable state reads as non-member;/// a cohort-reference leaf reads the referenced cohort's stored membership (see [`resolve_ref_membership`]).+#[allow(clippy::too_many_arguments)]async fn evaluate_cohort(partition_id: u16,team_id: u64,@@ -155,15 +214,25 @@ async fn evaluate_cohort(tree: &CohortTree,filters: &TeamFilters,handle: &StoreHandle,+ lane: ReadLane,) -> Result<bool, StoreError> {let mut lsks = Vec::new();collect_leaf_state_keys(&tree.root, &mut lsks);- let resolver = LeafMembershipResolver::new(partition_id, team_id, person_id, filters, handle);+ let resolver =+ LeafMembershipResolver::new(partition_id, team_id, person_id, filters, handle, lane);let membership = resolver.resolve(&lsks).await?;- let ref_membership =- resolve_ref_membership(partition_id, team_id, person_id, tree, filters, handle).await?;+ let ref_membership = resolve_ref_membership(+ partition_id,+ team_id,+ person_id,+ tree,+ filters,+ handle,+ lane,+ )+ .await?;Ok(evaluate_tree(&tree.root, &membership, &ref_membership))}@@ -180,6 +249,7 @@ struct LeafMembershipResolver<'a> {person_id: Uuid,filters: &'a TeamFilters,handle: &'a StoreHandle,+ lane: ReadLane,}impl<'a> LeafMembershipResolver<'a> {@@ -189,6 +259,7 @@ impl<'a> LeafMembershipResolver<'a> {person_id: Uuid,filters: &'a TeamFilters,handle: &'a StoreHandle,+ lane: ReadLane,) -> Self {Self {partition_id,@@ -196,6 +267,7 @@ impl<'a> LeafMembershipResolver<'a> {person_id,filters,handle,+ lane,}}@@ -238,10 +310,7 @@ impl<'a> LeafMembershipResolver<'a> {.iter().map(|&lsk| BehavioralKey::new(self.partition_id, self.team_id, self.person_id, lsk)).collect();- let raw = self- .handle- .multi_get_behavioral(keys, ReadLane::Event)- .await?;+ let raw = self.handle.multi_get_behavioral(keys, self.lane).await?;for (&lsk, bytes) in lsks.iter().zip(raw) {let Some(meta) = self.filters.by_lsk.get(&lsk) else {continue;@@ -265,7 +334,7 @@ impl<'a> LeafMembershipResolver<'a> {return Ok(());}let key = PersonRecordKey::new(self.partition_id, self.team_id, self.person_id);- let matched = match self.handle.get_person_record(&key).await? {+ let matched = match self.handle.get_person_record(&key, self.lane).await? {None => None,Some(bytes) => match PersonRecord::decode(&bytes) {Ok(record) => Some(record.matched),@@ -289,6 +358,7 @@ impl<'a> LeafMembershipResolver<'a> {/// A `SingleLeaf` referent is read from `cf_behavioral` via [`leaf_membership`] (so its comparator/// applies); a composable referent from its stored `cf_stage2` bit; anything else as non-member./// One batched read per store.+#[allow(clippy::too_many_arguments)]async fn resolve_ref_membership(partition_id: u16,team_id: u64,@@ -296,6 +366,7 @@ async fn resolve_ref_membership(tree: &CohortTree,filters: &TeamFilters,handle: &StoreHandle,+ lane: ReadLane,) -> Result<HashMap<CohortId, bool>, StoreError> {let mut ref_ids = Vec::new();collect_cohort_refs(&tree.root, &mut ref_ids);@@ -323,7 +394,7 @@ async fn resolve_ref_membership(// Resolve single-leaf referents through the same seam as the cohort's own leaves, so both// apply the leaf's comparator identically.let resolver =- LeafMembershipResolver::new(partition_id, team_id, person_id, filters, handle);+ LeafMembershipResolver::new(partition_id, team_id, person_id, filters, handle, lane);let lsks: Vec<LeafStateKey> = single_leaf_refs.iter().map(|(_, lsk)| *lsk).collect();let membership = resolver.resolve(&lsks).await?;for (ref_id, lsk) in &single_leaf_refs {@@ -341,7 +412,7 @@ async fn resolve_ref_membership(person_id,}).collect();- let raw = handle.multi_get_stage2(keys).await?;+ let raw = handle.multi_get_stage2(keys, lane).await?;for (ref_id, bytes) in composable_refs.iter().zip(raw) {ref_membership.insert(*ref_id, decode_stage2_bit(bytes));}@@ -363,8 +434,12 @@ fn decode_stage1_state(bytes: Option<Vec<u8>>) -> Option<Stage1State> {}/// The stored `cf_stage2` membership bit for `key`, `false` when absent or undecodable.-async fn read_stage2_bit(handle: &StoreHandle, key: &Stage2Key) -> Result<bool, StoreError> {- Ok(decode_stage2_bit(handle.get_stage2(key).await?))+async fn read_stage2_bit(+ handle: &StoreHandle,+ key: &Stage2Key,+ lane: ReadLane,+) -> Result<bool, StoreError> {+ Ok(decode_stage2_bit(handle.get_stage2(key, lane).await?))}/// Decode a `cf_stage2` value into its membership bit, `false` when absent or undecodable.@@ -424,7 +499,6 @@ mod tests {use crate::filters::{CohortId, TeamFiltersBuilder, TeamId};use crate::stage1::person_record::{MatchedSet, PersonRecord};use crate::stage1::state::AppliedOffsets;- use crate::stage1::transition::TransitionKind;use crate::store::{Behavioral, CohortStore, OffloadConfig, OffloadMode, PersonRecordKey, PersonRecords,StoreConfig,@@ -544,21 +618,6 @@ mod tests {.unwrap();}- fn transition(- lsk: LeafStateKey,- who: Uuid,- hash: [u8; 16],- kind: TransitionKind,- ) -> LeafTransition {- LeafTransition {- team_id: TeamId(TEAM as i32),- leaf_state_key: lsk,- person_id: who,- condition_hash: hash,- kind,- }- }-fn stage2_bit(store: &CohortStore, cohort: u64, who: Uuid) -> Option<bool> {let key = Stage2Key {partition_id: PARTITION,@@ -593,9 +652,10 @@ mod tests {PARTITION,&handle(&store),&filters,- &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],+ &[(beh_lsk, alice)],EVENT_MS,TS,+ ReadLane::Event,).await.unwrap();@@ -627,9 +687,10 @@ mod tests {PARTITION,&handle(&store),&filters,- &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],+ &[(beh_lsk, alice)],EVENT_MS,TS,+ ReadLane::Event,).await.unwrap();@@ -657,9 +718,10 @@ mod tests {PARTITION,&handle(&store),&filters,- &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],+ &[(beh_lsk, alice)],EVENT_MS,TS,+ ReadLane::Event,).await.unwrap();@@ -675,14 +737,10 @@ mod tests {PARTITION,&handle(&store),&filters,- &[transition(- per_lsk,- alice,- PERSON_HASH,- TransitionKind::Entered,- )],+ &[(per_lsk, alice)],EVENT_MS,TS,+ ReadLane::Event,).await.unwrap();@@ -704,9 +762,10 @@ mod tests {PARTITION,&handle(&store),&filters,- &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],+ &[(beh_lsk, alice)],EVENT_MS,TS,+ ReadLane::Event,).await.unwrap();@@ -718,14 +777,10 @@ mod tests {PARTITION,&handle(&store),&filters,- &[transition(- per_lsk,- alice,- PERSON_HASH,- TransitionKind::Left,- )],+ &[(per_lsk, alice)],EVENT_MS,TS,+ ReadLane::Event,).await.unwrap();@@ -751,9 +806,10 @@ mod tests {PARTITION,&handle(&store),&filters,- &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],+ &[(beh_lsk, alice)],EVENT_MS,TS,+ ReadLane::Event,).await.unwrap();@@ -763,9 +819,10 @@ mod tests {PARTITION,&handle(&store),&filters,- &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],+ &[(beh_lsk, alice)],EVENT_MS,TS,+ ReadLane::Event,).await.unwrap();@@ -789,12 +846,10 @@ mod tests {PARTITION,&handle(&store),&filters,- &[- transition(lsks[0], alice, HASH, TransitionKind::Entered),- transition(lsks[1], alice, HASH, TransitionKind::Entered),- ],+ &[(lsks[0], alice), (lsks[1], alice)],EVENT_MS,TS,+ ReadLane::Event,).await.unwrap();@@ -820,9 +875,10 @@ mod tests {PARTITION,&handle(&store),&filters,- &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],+ &[(beh_lsk, alice)],EVENT_MS,TS,+ ReadLane::Event,).await.unwrap();@@ -841,9 +897,10 @@ mod tests {PARTITION,&handle(&store2),&filters,- &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],+ &[(beh_lsk, alice)],EVENT_MS,TS,+ ReadLane::Event,).await.unwrap();@@ -865,9 +922,10 @@ mod tests {PARTITION,&handle(&store),&filters,- &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],+ &[(beh_lsk, alice)],EVENT_MS,TS,+ ReadLane::Event,).await.unwrap();@@ -899,9 +957,10 @@ mod tests {PARTITION,&handle(&store),&filters,- &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],+ &[(beh_lsk, alice)],EVENT_MS,TS,+ ReadLane::Event,).await.unwrap();@@ -921,9 +980,10 @@ mod tests {PARTITION,&handle(&store),&filters,- &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],+ &[(beh_lsk, alice)],EVENT_MS,TS,+ ReadLane::Event,).await.unwrap();@@ -935,14 +995,10 @@ mod tests {PARTITION,&handle(&store),&filters,- &[transition(- per_lsk,- alice,- PERSON_HASH,- TransitionKind::Entered,- )],+ &[(per_lsk, alice)],EVENT_MS,TS,+ ReadLane::Event,).await.unwrap();@@ -1006,14 +1062,10 @@ mod tests {PARTITION,handle,filters,- &[transition(- per_lsk,- who,- PERSON_HASH,- TransitionKind::Entered,- )],+ &[(per_lsk, who)],EVENT_MS,TS,+ ReadLane::Event,).await.unwrap()diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rsindex 2439866000e7..9581ff9e3448 100644--- a/rust/cohort-stream-processor/src/workers/worker.rs+++ b/rust/cohort-stream-processor/src/workers/worker.rs@@ -35,6 +35,7 @@ use crate::producer::{map_transition, now_last_updated, CohortMembershipChange, MembershipSink, MembershipStatus,OutputBuffer,};+use crate::stage1::key::LeafStateKey;use crate::stage1::state::{StateVariant, StatefulRecord};use crate::stage1::transition::{LeafTransition, TransitionKind};use crate::store::{Behavioral, BehavioralKey, ReadLane, StagedBatch, StoreHandle};@@ -45,6 +46,7 @@ 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::seed_path::handle_seed;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};@@ -167,14 +169,22 @@ async fn run_worker(let mut buffer = OutputBuffer::new();let mut re_keys: Vec<CohortStreamEvent> = Vec::new();let mut max_offset: Option<i64> = None;+ // Observed into the live watermarks only post-mark, so a held batch never advances the+ // seed fence.+ let mut max_broker_ts: Option<i64> = None;// Set when a pre-arm flush fails: holds the whole batch's offset so Kafka replays it.let mut held = false;for message in batch {match message {- ShuffleMessage::Event { event, cse_offset } => {+ ShuffleMessage::Event {+ event,+ cse_offset,+ broker_ts_ms,+ } => {max_offset =Some(max_offset.map_or(cse_offset, |current| current.max(cse_offset)));+ max_broker_ts = max_broker_ts.max(broker_ts_ms);let effects = handle_event(partition_id,&handle,@@ -285,6 +295,30 @@ async fn run_worker().await;}+ ShuffleMessage::Seed { work, offset } => {+ 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,+ &last_updated,+ &work,+ offset,+ )+ .await;+ }ShuffleMessage::RedrivePendingTransfers => {handle_redrive(partition_id, &handle, &merge).await;}@@ -393,6 +427,13 @@ async fn run_worker();}}+ // Strictly post-mark: a consume-time watermark would reopen the double-count branch the+ // fence deletes.+ if let Some(broker_ts_ms) = max_broker_ts {+ merge+ .live_watermarks+ .observe(partition_id as i32, broker_ts_ms);+ }}info!(partition_id, "stage 1 worker stopped");@@ -559,9 +600,10 @@ async fn handle_event(partition_id,handle,filters,- &outcome.transitions,+ &affected_leaves(&outcome.transitions),outcome.event_ms,last_updated,+ ReadLane::Event,).await{@@ -612,6 +654,7 @@ async fn redirect_for_tombstone<'a>(TeamId(event.team_id),person_id,partition_count,+ ReadLane::Event,).await{@@ -808,9 +851,10 @@ async fn handle_sweep(partition_id,handle,filters,- transitions,+ &affected_leaves(transitions),due_before_ms,last_updated,+ ReadLane::Event,).await{@@ -924,6 +968,14 @@ fn reschedule_team(}}+/// The `(leaf, person)` pairs [`compose_stage2`] recomputes for.+pub fn affected_leaves(transitions: &[LeafTransition]) -> Vec<(LeafStateKey, Uuid)> {+ transitions+ .iter()+ .map(|transition| (transition.leaf_state_key, transition.person_id))+ .collect()+}+pub(crate) fn transition_metric_label(filters: &TeamFilters,transition: &LeafTransition,@@ -1071,6 +1123,9 @@ mod tombstone_redirect_tests {cascade_tracker: Arc::new(OffsetTracker::new()),cascade: crate::workers::CascadeConfig::default(),partition_count: COHORT_PARTITION_COUNT,+ seed_tile_sink: Arc::new(crate::producer::CaptureSeedTileSink::new()),+ seed_tracker: Arc::new(crate::partitions::offset_tracker::OffsetTracker::new()),+ live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),})}@@ -1088,6 +1143,9 @@ mod tombstone_redirect_tests {cascade_tracker: Arc::new(OffsetTracker::new()),cascade: crate::workers::CascadeConfig::default(),partition_count: COHORT_PARTITION_COUNT,+ seed_tile_sink: Arc::new(crate::producer::CaptureSeedTileSink::new()),+ seed_tracker: Arc::new(crate::partitions::offset_tracker::OffsetTracker::new()),+ live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),})}@@ -1109,6 +1167,9 @@ mod tombstone_redirect_tests {fanout_cap: 1000,},partition_count: COHORT_PARTITION_COUNT,+ seed_tile_sink: Arc::new(crate::producer::CaptureSeedTileSink::new()),+ seed_tracker: Arc::new(crate::partitions::offset_tracker::OffsetTracker::new()),+ live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),})}@@ -1132,6 +1193,7 @@ mod tombstone_redirect_tests {vec![ShuffleMessage::Event {event: Box::new(person_event(person, "[email protected]", 5, 0)),cse_offset: 0,+ broker_ts_ms: None,}],).await;@@ -1268,6 +1330,7 @@ mod tombstone_redirect_tests {vec![ShuffleMessage::Event {event: Box::new(event),cse_offset: 0,+ broker_ts_ms: None,}],).await;@@ -1497,10 +1560,12 @@ mod tombstone_redirect_tests {ShuffleMessage::Event {event: Box::new(person_event(alice, "[email protected]", 5, 0)),cse_offset: 0,+ broker_ts_ms: None,},ShuffleMessage::Event {event: Box::new(person_event(p_old, "[email protected]", 5, 9)),cse_offset: 1,+ broker_ts_ms: None,},]};diff --git a/rust/cohort-stream-processor/tests/cascade_consumer.rs b/rust/cohort-stream-processor/tests/cascade_consumer.rsindex de11facbf117..8c202d0f2c16 100644--- a/rust/cohort-stream-processor/tests/cascade_consumer.rs+++ b/rust/cohort-stream-processor/tests/cascade_consumer.rs@@ -458,6 +458,13 @@ async fn spawn_instance(fanout_cap: 1000,},partition_count: COHORT_PARTITION_COUNT,+ seed_tile_sink: Arc::new(cohort_stream_processor::producer::CaptureSeedTileSink::new()),+ seed_tracker: Arc::new(+ cohort_stream_processor::partitions::offset_tracker::OffsetTracker::new(),+ ),+ live_watermarks: Arc::new(+ cohort_stream_processor::partitions::watermarks::LiveWatermarks::new(),+ ),});let dispatcher = Arc::new(EventDispatcher::new(@@ -548,7 +555,7 @@ async fn spawn_instance(tasks.push(tokio::spawn(cascade_follower.process()));let events_consumer = CohortStreamEventsConsumer::new(- events_client,+ Arc::new(events_client),topics.events.clone(),dispatcher.clone(),events_handle,@@ -591,6 +598,8 @@ async fn cascade_producer_co_partitions_with_events() {person_id: person.to_string(),last_updated: TS.to_string(),status: MembershipStatus::Entered,+ origin: None,+ run_id: None,},n as i64,)diff --git a/rust/cohort-stream-processor/tests/events_consumer.rs b/rust/cohort-stream-processor/tests/events_consumer.rsindex 747fa9355712..52561fbbf0a6 100644--- a/rust/cohort-stream-processor/tests/events_consumer.rs+++ b/rust/cohort-stream-processor/tests/events_consumer.rs@@ -282,7 +282,7 @@ fn build_consumer_with_restore());CohortStreamEventsConsumer::new(- consumer,+ Arc::new(consumer),topic.to_string(),dispatcher,handle,@@ -1224,7 +1224,7 @@ fn build_consumer_with_manifest());CohortStreamEventsConsumer::new(- consumer,+ Arc::new(consumer),topic.to_string(),dispatcher,handle,diff --git a/rust/cohort-stream-processor/tests/merge_consumer.rs b/rust/cohort-stream-processor/tests/merge_consumer.rsindex 9848a990690d..d6ba7f22e974 100644--- a/rust/cohort-stream-processor/tests/merge_consumer.rs+++ b/rust/cohort-stream-processor/tests/merge_consumer.rs@@ -614,6 +614,13 @@ async fn spawn_instance(cascade_tracker: Arc::new(OffsetTracker::new()),cascade: CascadeConfig::default(),partition_count: COHORT_PARTITION_COUNT,+ seed_tile_sink: Arc::new(cohort_stream_processor::producer::CaptureSeedTileSink::new()),+ seed_tracker: Arc::new(+ cohort_stream_processor::partitions::offset_tracker::OffsetTracker::new(),+ ),+ live_watermarks: Arc::new(+ cohort_stream_processor::partitions::watermarks::LiveWatermarks::new(),+ ),});let dispatcher = Arc::new(EventDispatcher::new(@@ -680,7 +687,7 @@ async fn spawn_instance(tasks.push(tokio::spawn(transfer_follower.process()));let events_consumer = CohortStreamEventsConsumer::new(- events_client,+ Arc::new(events_client),topics.events.clone(),dispatcher.clone(),events_handle,diff --git a/rust/cohort-stream-processor/tests/merge_durability.rs b/rust/cohort-stream-processor/tests/merge_durability.rsindex 66f9aa004a7c..ee9d39703828 100644--- a/rust/cohort-stream-processor/tests/merge_durability.rs+++ b/rust/cohort-stream-processor/tests/merge_durability.rs@@ -712,6 +712,13 @@ async fn spawn_instance(fanout_cap: 1000,},partition_count: COHORT_PARTITION_COUNT,+ seed_tile_sink: Arc::new(cohort_stream_processor::producer::CaptureSeedTileSink::new()),+ seed_tracker: Arc::new(+ cohort_stream_processor::partitions::offset_tracker::OffsetTracker::new(),+ ),+ live_watermarks: Arc::new(+ cohort_stream_processor::partitions::watermarks::LiveWatermarks::new(),+ ),});let dispatcher = Arc::new(EventDispatcher::new(@@ -805,7 +812,7 @@ async fn spawn_instance(tasks.push(tokio::spawn(cascade_follower.process()));let events_consumer = CohortStreamEventsConsumer::new(- events_client,+ Arc::new(events_client),topics.events.clone(),dispatcher.clone(),events_handle,diff --git a/rust/cohort-stream-processor/tests/merge_protocol.rs b/rust/cohort-stream-processor/tests/merge_protocol.rsindex 7dfd67c3bd75..90973970333a 100644--- a/rust/cohort-stream-processor/tests/merge_protocol.rs+++ b/rust/cohort-stream-processor/tests/merge_protocol.rs@@ -27,8 +27,8 @@ use cohort_stream_processor::stage1::{Stage1State, StateVariant, StatefulRecord}use cohort_stream_processor::stage2::Stage2State;use cohort_stream_processor::store::{BehavioralKey, CohortStore, LeafStateKey, MergeAppliedKey, MergeDrainKey, OffloadConfig,- OffloadMode, PendingTransferKey, PersonRecordKey, PersonRecords, Stage2Key, StoreConfig,- StoreHandle, TombstoneKey,+ OffloadMode, PendingTransferKey, PersonRecordKey, PersonRecords, ReadLane, Stage2Key,+ StoreConfig, StoreHandle, TombstoneKey,};use cohort_stream_processor::workers::{compose_stage2, handle_merge_gc, handle_stage2_orphan_gc, process_event, MergeGcCursor,@@ -712,9 +712,10 @@ async fn apply_transitions_compose_into_stage2() {p_new_part,&handle(&store),&filters,- &transitions,+ &cohort_stream_processor::workers::worker::affected_leaves(&transitions),MERGED_AT,&now_last_updated(),+ ReadLane::Event,).await.unwrap();@@ -2305,9 +2306,10 @@ async fn each_offload_mode_yields_the_same_merge_result() {p_new_part,&handle,&filters,- &transitions,+ &cohort_stream_processor::workers::worker::affected_leaves(&transitions),MERGED_AT,&last_updated,+ ReadLane::Event,).await.unwrap();diff --git a/rust/cohort-stream-processor/tests/seed_consumer.rs b/rust/cohort-stream-processor/tests/seed_consumer.rsnew file mode 100644index 000000000000..eca4403b1f85--- /dev/null+++ b/rust/cohort-stream-processor/tests/seed_consumer.rs@@ -0,0 +1,804 @@+//! End-to-end tests for the backfill seed path against a **real** Kafka broker: the keyed+//! `cohort_stream_seed_events` produce, the assignment-mirrored seed follower (5-topic+//! co-assignment), the apply fence, and the worker-affined tile apply with `origin` tagging —+//! wired like `main.rs` with the seed gate on.+//!+//! `#[ignore]`d by default (group joins and `incremental_assign` semantics the in-process+//! `MockCluster` does not exercise faithfully). All topics are created with the production+//! partition count (64) because the routing invariant is the thing under test. Run against a local+//! stack serially:+//!+//! ```sh+//! cargo test -p cohort-stream-processor --test seed_consumer -- --ignored --test-threads=1+//! ```++use std::collections::HashSet;+use std::future::Future;+use std::num::NonZeroU32;+use std::panic::AssertUnwindSafe;+use std::sync::Arc;+use std::time::{Duration, Instant};++use chrono_tz::UTC;+use cohort_core::seed::{ClaimEpoch, ConditionHash, RunId, SChunkMs, SeedTile};+use cohort_stream_processor::consumers::{+ CascadeRoute, CohortStreamEventsConsumer, EventDispatcher, FollowerConsumer, MergeRoute,+ SeedFollowerConsumer, TransferRoute,+};+use cohort_stream_processor::filters::{+ CatalogHandle, CohortId, FilterCatalog, TeamFiltersBuilder, TeamId,+};+use cohort_stream_processor::partitions::{+ merge_partition_key, partition_for, partition_of, run_rebalance_worker, CohortConsumerContext,+ ConsumerPauser, Follower, FollowerSet, LiveWatermarks, OffsetTracker, PartitionPauser,+ PartitionRouter, COHORT_PARTITION_COUNT,+};+use cohort_stream_processor::producer::{+ CascadeSink, ChangeOrigin, CohortMembershipChange, KafkaCascadeSink, KafkaMembershipSink,+ KafkaSeedTileSink, KafkaStreamEventSink, KafkaTransferSink, MembershipSink, MembershipStatus,+ SeedTileSink, StreamEventSink, TransferSink,+};+use cohort_stream_processor::stage1::bucket_tz::day_idx_in_tz;+use cohort_stream_processor::store::{+ CohortStore, OffloadConfig, OffloadMode, StoreConfig, StoreHandle,+};+use cohort_stream_processor::workers::{+ CascadeConfig, MergeWorkerDeps, TransferRetryPolicy, DEFAULT_MERGE_GC_SCAN_LIMIT,+};+use common_kafka::config::KafkaConfig;+use futures::FutureExt;+use lifecycle::{ComponentOptions, Handle, Manager};+use rdkafka::admin::{AdminClient, AdminOptions, NewTopic, TopicReplication};+use rdkafka::client::DefaultClientContext;+use rdkafka::consumer::{Consumer, StreamConsumer};+use rdkafka::message::Message;+use rdkafka::producer::{FutureProducer, FutureRecord};+use rdkafka::util::Timeout;+use rdkafka::{ClientConfig, Offset, TopicPartitionList};+use serde_json::json;+use tempfile::TempDir;+use tokio::sync::mpsc;+use tokio::task::JoinHandle;+use uuid::Uuid;++const TEAM: i32 = 7;+const NUM_PARTITIONS: i32 = COHORT_PARTITION_COUNT as i32;+const COMMIT_INTERVAL: Duration = Duration::from_millis(250);+const RECV_TIMEOUT: Duration = Duration::from_millis(200);+/// Effectively never: the idle probe must not open a fence behind an assertion's back.+const PROBE_NEVER: Duration = Duration::from_secs(3_600);++fn bootstrap_servers() -> String {+ std::env::var("KAFKA_HOSTS").unwrap_or_else(|_| "localhost:9092".to_string())+}++/// One single-leaf behavioral cohort sharing the tile's condition hash.+fn seed_catalog() -> CatalogHandle {+ let leaf = json!({+ "type": "behavioral", "value": "performed_event", "key": "$pageview",+ "time_value": 7, "time_interval": "day",+ "conditionHash": "0123456789abcdef",+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],+ });+ let mut builder = TeamFiltersBuilder::default();+ builder+ .add_cohort(+ CohortId(1),+ TeamId(TEAM),+ &json!({ "properties": { "type": "AND", "values": [leaf] } }),+ )+ .expect("add cohort");+ CatalogHandle::from_catalog(FilterCatalog::from_teams([(+ TeamId(TEAM),+ builder.freeze(UTC),+ )]))+}++async fn create_topic(topic: &str, partitions: i32) {+ let admin: AdminClient<DefaultClientContext> = ClientConfig::new()+ .set("bootstrap.servers", bootstrap_servers())+ .create()+ .expect("create admin client");+ let new_topic = NewTopic::new(topic, partitions, TopicReplication::Fixed(1));+ let opts = AdminOptions::new().operation_timeout(Some(Duration::from_secs(10)));+ let results = admin+ .create_topics(&[new_topic], &opts)+ .await+ .expect("create_topics");+ for result in results {+ match result {+ Ok(_) | Err((_, rdkafka::types::RDKafkaErrorCode::TopicAlreadyExists)) => {}+ Err((name, err)) => panic!("failed to create topic {name}: {err:?}"),+ }+ }+ let verifier: StreamConsumer = ClientConfig::new()+ .set("bootstrap.servers", bootstrap_servers())+ .set("group.id", format!("metadata-verifier-{}", Uuid::new_v4()))+ .create()+ .expect("create metadata verifier");+ let start = Instant::now();+ loop {+ let ready = verifier+ .fetch_metadata(Some(topic), Duration::from_secs(5))+ .ok()+ .is_some_and(|metadata| {+ metadata.topics().iter().any(|meta| {+ meta.name() == topic+ && meta.error().is_none()+ && meta.partitions().len() == partitions as usize+ })+ });+ if ready {+ break;+ }+ assert!(+ start.elapsed() < Duration::from_secs(30),+ "timed out waiting for topic {topic} metadata to propagate",+ );+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+}++async fn delete_topics(topics: &[&str]) {+ let admin: AdminClient<DefaultClientContext> = ClientConfig::new()+ .set("bootstrap.servers", bootstrap_servers())+ .create()+ .expect("create admin client");+ let opts = AdminOptions::new().operation_timeout(Some(Duration::from_secs(10)));+ if let Err(err) = admin.delete_topics(topics, &opts).await {+ eprintln!("topic cleanup failed; leaked {topics:?}: {err}");+ }+}++async fn with_topics_cleanup<F: Future<Output = ()>>(topics: &[&str], body: F) {+ let result = AssertUnwindSafe(body).catch_unwind().await;+ delete_topics(topics).await;+ if let Err(panic) = result {+ std::panic::resume_unwind(panic);+ }+}++fn producer_kafka_config() -> KafkaConfig {+ KafkaConfig {+ kafka_hosts: bootstrap_servers(),+ kafka_tls: false,+ kafka_client_rack: String::new(),+ kafka_client_id: String::new(),+ kafka_compression_codec: "none".to_string(),+ kafka_producer_partitioner: Some("murmur2_random".to_string()),+ kafka_producer_linger_ms: 20,+ kafka_producer_queue_mib: 400,+ kafka_producer_queue_messages: 10_000_000,+ kafka_message_timeout_ms: 20_000,+ kafka_producer_batch_size: None,+ kafka_producer_batch_num_messages: None,+ kafka_producer_enable_idempotence: None,+ kafka_producer_max_in_flight_requests_per_connection: None,+ kafka_producer_topic_metadata_refresh_interval_ms: None,+ kafka_producer_message_max_bytes: None,+ kafka_producer_sticky_partitioning_linger_ms: None,+ kafka_producer_acks: None,+ kafka_producer_retries: None,+ }+}++fn murmur2_producer() -> FutureProducer {+ ClientConfig::new()+ .set("bootstrap.servers", bootstrap_servers())+ .set("message.timeout.ms", "10000")+ .set("partitioner", "murmur2_random")+ .create()+ .expect("create murmur2 producer")+}++fn events_client_config(group: &str) -> ClientConfig {+ let mut config = ClientConfig::new();+ config+ .set("bootstrap.servers", bootstrap_servers())+ .set("group.id", group)+ .set("enable.auto.commit", "false")+ .set("enable.auto.offset.store", "false")+ .set("auto.offset.reset", "earliest")+ .set("partition.assignment.strategy", "cooperative-sticky")+ .set("session.timeout.ms", "6000");+ config+}++fn follower_client_config(group: &str) -> ClientConfig {+ let mut config = ClientConfig::new();+ config+ .set("bootstrap.servers", bootstrap_servers())+ .set("group.id", group)+ .set("enable.auto.commit", "false")+ .set("enable.auto.offset.store", "false")+ .set("auto.offset.reset", "earliest")+ .set("socket.timeout.ms", "10000");+ config+}++fn topic_message_count(topic: &str) -> i64 {+ let consumer: StreamConsumer = ClientConfig::new()+ .set("bootstrap.servers", bootstrap_servers())+ .set("group.id", format!("watermark-verifier-{}", Uuid::new_v4()))+ .create()+ .expect("create watermark verifier");+ (0..NUM_PARTITIONS)+ .map(|partition| {+ let (low, high) = consumer+ .fetch_watermarks(topic, partition, Duration::from_secs(10))+ .expect("fetch watermarks");+ high - low+ })+ .sum()+}++/// Read up to `expected` messages (all partitions from the beginning). Assigned explicitly — no+/// group join, no commit.+async fn consume_all(topic: &str, expected: usize, deadline: Duration) -> Vec<(i32, Vec<u8>)> {+ let consumer: StreamConsumer = ClientConfig::new()+ .set("bootstrap.servers", bootstrap_servers())+ .set("group.id", format!("scan-verifier-{}", Uuid::new_v4()))+ .set("enable.auto.commit", "false")+ .create()+ .expect("create scan verifier");+ let mut tpl = TopicPartitionList::new();+ for partition in 0..NUM_PARTITIONS {+ tpl.add_partition_offset(topic, partition, Offset::Beginning)+ .expect("add partition to scan TPL");+ }+ consumer.assign(&tpl).expect("assign scan verifier");++ let mut messages = Vec::new();+ let start = Instant::now();+ while messages.len() < expected && start.elapsed() < deadline {+ match tokio::time::timeout(Duration::from_secs(2), consumer.recv()).await {+ Ok(Ok(message)) => {+ if let Some(payload) = message.payload() {+ messages.push((message.partition(), payload.to_vec()));+ }+ }+ Ok(Err(err)) => panic!("scan verifier recv error: {err}"),+ Err(_) => {}+ }+ }+ messages+}++async fn wait_for(what: &str, deadline: Duration, mut condition: impl FnMut() -> bool) {+ let start = Instant::now();+ while !condition() {+ assert!(+ start.elapsed() < deadline,+ "timed out after {deadline:?} waiting for {what}",+ );+ tokio::time::sleep(Duration::from_millis(200)).await;+ }+}++fn part(person: Uuid) -> u16 {+ partition_of(TeamId(TEAM), &person, COHORT_PARTITION_COUNT) as u16+}++/// The seed group's committed next-offset for `partition`, read without joining the group.+fn seed_group_committed(group: &str, topic: &str, partition: i32) -> Option<i64> {+ let consumer: StreamConsumer = follower_client_config(group)+ .create()+ .expect("create committed-offset verifier");+ let mut tpl = TopicPartitionList::new();+ tpl.add_partition(topic, partition);+ let committed = consumer+ .committed_offsets(tpl, Duration::from_secs(10))+ .ok()?;+ committed+ .elements_for_topic(topic)+ .iter()+ .find(|elem| elem.partition() == partition)+ .and_then(|elem| match elem.offset() {+ Offset::Offset(next) => Some(next),+ _ => None,+ })+}++/// A name-mismatched warm-up event: folds (advancing the watermark) without flipping anything.+fn warm_envelope(person: Uuid, source_offset: i64) -> Vec<u8> {+ serde_json::to_vec(&json!({+ "team_id": TEAM,+ "person_id": person.to_string(),+ "distinct_id": "d",+ "uuid": Uuid::from_u128(0xE0_0000 + source_offset as u128).to_string(),+ "event": "$warm",+ "timestamp": "2026-06-10 12:34:56.789000",+ "properties": "{}",+ "person_properties": null,+ "elements_chain": null,+ "source_offset": source_offset,+ "source_partition": 0,+ }))+ .expect("serialize envelope")+}++async fn produce_warm_event(producer: &FutureProducer, topic: &str, person: Uuid, offset: i64) {+ let key = merge_partition_key(TeamId(TEAM), &person);+ let payload = warm_envelope(person, offset);+ let (partition, _) = producer+ .send(+ FutureRecord::to(topic).key(&key).payload(&payload),+ Timeout::After(Duration::from_secs(10)),+ )+ .await+ .expect("produce warm event");+ assert_eq!(partition as u16, part(person), "event must co-partition");+}++fn tile(person: Uuid, s_chunk_ms: i64) -> SeedTile {+ SeedTile::new(+ TeamId(TEAM),+ person,+ ConditionHash::parse("0123456789abcdef").unwrap(),+ NonZeroU32::new(2).unwrap(),+ day_idx_in_tz(chrono::Utc::now().timestamp_millis(), UTC),+ SChunkMs(s_chunk_ms),+ RunId(Uuid::from_u128(0xBF)),+ ClaimEpoch(1),+ )+}++/// Produce a tile through the production sink (the same keying the seeder and the re-key path use).+async fn produce_tile(seed_sink: &KafkaSeedTileSink, produced: SeedTile) {+ let acks = seed_sink.produce(vec![produced]).await;+ assert!(acks.iter().all(Result::is_ok), "tile produce must ack");+}++fn open_store(dir: &TempDir) -> CohortStore {+ CohortStore::open(&StoreConfig {+ path: dir.path().join("db"),+ ..StoreConfig::default()+ })+ .expect("open store")+}++struct Topics {+ events: String,+ merges: String,+ transfers: String,+ cascade: String,+ seeds: String,+ shadow: String,+}++impl Topics {+ fn unique(suffix: &Uuid) -> Self {+ Self {+ events: format!("cohort_stream_events_seed_{suffix}"),+ merges: format!("person_merge_events_{suffix}"),+ transfers: format!("cohort_merge_state_transfer_{suffix}"),+ cascade: format!("cohort_cascade_events_{suffix}"),+ seeds: format!("cohort_stream_seed_events_{suffix}"),+ shadow: format!("cohort_membership_changed_{suffix}"),+ }+ }++ async fn create(&self) {+ for topic in self.names() {+ create_topic(topic, NUM_PARTITIONS).await;+ }+ }++ fn names(&self) -> [&str; 6] {+ [+ &self.events,+ &self.merges,+ &self.transfers,+ &self.cascade,+ &self.seeds,+ &self.shadow,+ ]+ }+}++struct Groups {+ events: String,+ merges: String,+ transfers: String,+ cascade: String,+ seeds: String,+}++impl Groups {+ fn unique(suffix: &Uuid) -> Self {+ Self {+ events: format!("cohort-stream-processor-{suffix}"),+ merges: format!("cohort-stream-merges-{suffix}"),+ transfers: format!("cohort-stream-merge-apply-{suffix}"),+ cascade: format!("cohort-stream-cascade-{suffix}"),+ seeds: format!("cohort-stream-seeds-{suffix}"),+ }+ }+}++fn register_instance(manager: &mut Manager) -> [Handle; 5] {+ let options = || ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(15));+ [+ manager.register("consumer", options()),+ manager.register("merge-follower", options()),+ manager.register("transfer-follower", options()),+ manager.register("cascade-follower", options()),+ manager.register("seed-follower", options()),+ ]+}++struct Instance {+ dispatcher: Arc<EventDispatcher>,+ tasks: Vec<JoinHandle<()>>,+}++impl Instance {+ fn owned(&self) -> HashSet<i32> {+ self.dispatcher.owned_partitions().into_iter().collect()+ }++ async fn join(self) {+ for task in self.tasks {+ task.await.expect("instance task panicked");+ }+ }+}++async fn spawn_instance(+ topics: &Topics,+ groups: &Groups,+ store: CohortStore,+ catalog: CatalogHandle,+ handles: [Handle; 5],+ fence_margin_ms: i64,+) -> Instance {+ let [events_handle, merge_handle, transfer_handle, cascade_handle, seed_handle] = handles;+ let kafka_config = producer_kafka_config();++ let transfer_sink: Arc<dyn TransferSink> = Arc::new(+ KafkaTransferSink::new(&kafka_config, topics.transfers.clone())+ .await+ .expect("create transfer sink"),+ );+ let stream_event_sink: Arc<dyn StreamEventSink> = Arc::new(+ KafkaStreamEventSink::new(&kafka_config, topics.events.clone())+ .await+ .expect("create re-key sink"),+ );+ let cascade_sink: Arc<dyn CascadeSink> = Arc::new(+ KafkaCascadeSink::new(&kafka_config, topics.cascade.clone())+ .await+ .expect("create cascade sink"),+ );+ let seed_tile_sink: Arc<dyn SeedTileSink> = Arc::new(+ KafkaSeedTileSink::new(&kafka_config, topics.seeds.clone())+ .await+ .expect("create seed re-key sink"),+ );+ let membership_sink: Arc<dyn MembershipSink> = Arc::new(+ KafkaMembershipSink::new(&kafka_config, topics.shadow.clone())+ .await+ .expect("create membership sink"),+ );+ let merge_deps = Arc::new(MergeWorkerDeps {+ transfer_sink,+ stream_event_sink,+ merge_tracker: Arc::new(OffsetTracker::new()),+ transfer_tracker: Arc::new(OffsetTracker::new()),+ retry: TransferRetryPolicy::default(),+ gc_scan_limit: DEFAULT_MERGE_GC_SCAN_LIMIT,+ stage2_orphan_gc_enabled: true,+ cascade_sink,+ cascade_tracker: Arc::new(OffsetTracker::new()),+ cascade: CascadeConfig::default(),+ partition_count: COHORT_PARTITION_COUNT,+ seed_tile_sink,+ seed_tracker: Arc::new(OffsetTracker::new()),+ live_watermarks: Arc::new(LiveWatermarks::new()),+ });++ let dispatcher = Arc::new(EventDispatcher::new(+ PartitionRouter::new(64),+ Arc::new(OffsetTracker::new()),+ StoreHandle::new(+ store,+ OffloadConfig {+ mode: OffloadMode::All,+ event_read_permits: 16,+ maintenance_permits: 6,+ },+ ),+ Arc::new(catalog),+ membership_sink,+ merge_deps,+ ));++ let merges_consumer: Arc<StreamConsumer> = Arc::new(+ follower_client_config(&groups.merges)+ .create()+ .expect("create merges follower consumer"),+ );+ let transfers_consumer: Arc<StreamConsumer> = Arc::new(+ follower_client_config(&groups.transfers)+ .create()+ .expect("create transfers follower consumer"),+ );+ let cascade_consumer: Arc<StreamConsumer> = Arc::new(+ follower_client_config(&groups.cascade)+ .create()+ .expect("create cascade follower consumer"),+ );+ let seeds_consumer: Arc<StreamConsumer> = Arc::new(+ follower_client_config(&groups.seeds)+ .create()+ .expect("create seed follower consumer"),+ );+ let followers = Arc::new(FollowerSet::new([+ Follower::new(merges_consumer.clone(), topics.merges.clone()),+ Follower::new(transfers_consumer.clone(), topics.transfers.clone()),+ Follower::new(cascade_consumer.clone(), topics.cascade.clone()),+ Follower::new(seeds_consumer.clone(), topics.seeds.clone()),+ ]));++ let (context, rebalance_rx) = CohortConsumerContext::new(dispatcher.clone());+ let events_client: StreamConsumer<CohortConsumerContext> = events_client_config(&groups.events)+ .create_with_context(context)+ .expect("create events consumer");+ events_client+ .subscribe(&[topics.events.as_str()])+ .expect("subscribe events");+ let events_client = Arc::new(events_client);++ let (command_tx, command_rx) = mpsc::unbounded_channel();+ let mut tasks = vec![tokio::spawn(run_rebalance_worker(+ rebalance_rx,+ dispatcher.clone(),+ followers,+ command_tx,+ events_handle.shutdown_token(),+ ))];++ let merge_follower = FollowerConsumer::<MergeRoute>::new(+ merges_consumer,+ topics.merges.clone(),+ dispatcher.clone(),+ merge_handle,+ 100,+ RECV_TIMEOUT,+ COMMIT_INTERVAL,+ );+ tasks.push(tokio::spawn(merge_follower.process()));++ let transfer_follower = FollowerConsumer::<TransferRoute>::new(+ transfers_consumer,+ topics.transfers.clone(),+ dispatcher.clone(),+ transfer_handle,+ 100,+ RECV_TIMEOUT,+ COMMIT_INTERVAL,+ );+ tasks.push(tokio::spawn(transfer_follower.process()));++ let cascade_follower = FollowerConsumer::<CascadeRoute>::new(+ cascade_consumer,+ topics.cascade.clone(),+ dispatcher.clone(),+ cascade_handle,+ 100,+ RECV_TIMEOUT,+ COMMIT_INTERVAL,+ );+ tasks.push(tokio::spawn(cascade_follower.process()));++ let seed_pauser: Arc<dyn PartitionPauser> = Arc::new(ConsumerPauser::new(+ seeds_consumer.clone(),+ topics.seeds.clone(),+ ));+ let seed_follower = SeedFollowerConsumer::new(+ seeds_consumer,+ topics.seeds.clone(),+ events_client.clone(),+ topics.events.clone(),+ dispatcher.clone(),+ seed_handle,+ seed_pauser,+ 100,+ RECV_TIMEOUT,+ COMMIT_INTERVAL,+ fence_margin_ms,+ PROBE_NEVER,+ );+ tasks.push(tokio::spawn(seed_follower.process()));++ let events_consumer = CohortStreamEventsConsumer::new(+ events_client,+ topics.events.clone(),+ dispatcher.clone(),+ events_handle,+ 100,+ RECV_TIMEOUT,+ COMMIT_INTERVAL,+ NUM_PARTITIONS as usize,+ command_rx,+ None,+ );+ tasks.push(tokio::spawn(events_consumer.process()));++ Instance { dispatcher, tasks }+}++/// A tile lands on its owning worker via the 5-topic co-assignment, applies behind an open+/// fence, emits a tagged change, and the seed group's commits reach the produced high-water mark.+#[tokio::test]+#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]+async fn seed_tile_applies_on_the_owning_worker_and_commits_to_the_hwm() {+ let suffix = Uuid::new_v4();+ let topics = Topics::unique(&suffix);+ let groups = Groups::unique(&suffix);+ with_topics_cleanup(&topics.names(), async {+ topics.create().await;++ let mut manager = Manager::builder("seed-e2e-itest")+ .with_trap_signals(false)+ .build();+ let handles = register_instance(&mut manager);+ let shutdown = handles[0].clone();+ let _monitor = manager.monitor_background();++ let dir = TempDir::new().unwrap();+ let instance = spawn_instance(+ &topics,+ &groups,+ open_store(&dir),+ seed_catalog(),+ handles,+ 2_000,+ )+ .await;+ wait_for(+ "the consumer to own every partition",+ Duration::from_secs(30),+ || instance.owned().len() == NUM_PARTITIONS as usize,+ )+ .await;++ let alice = Uuid::from_u128(0xA11CE);+ // One folded live event opens the fence for the hour-old scan point.+ let producer = murmur2_producer();+ produce_warm_event(&producer, &topics.events, alice, 0).await;++ let seed_sink = KafkaSeedTileSink::new(&producer_kafka_config(), topics.seeds.clone())+ .await+ .expect("create test seed sink");+ let s_chunk = chrono::Utc::now().timestamp_millis() - 3_600_000;+ produce_tile(&seed_sink, tile(alice, s_chunk)).await;++ wait_for(+ "the seeded flip on the shadow topic",+ Duration::from_secs(60),+ || topic_message_count(&topics.shadow) == 1,+ )+ .await;+ let (partition, payload) = consume_all(&topics.shadow, 1, Duration::from_secs(30))+ .await+ .into_iter()+ .next()+ .expect("one membership change");+ let change: CohortMembershipChange = serde_json::from_slice(&payload).unwrap();+ assert_eq!(change.person_id, alice.to_string());+ assert_eq!(change.cohort_id, 1);+ assert_eq!(change.status, MembershipStatus::Entered);+ assert_eq!(change.origin, Some(ChangeOrigin::Seed));+ assert_eq!(change.run_id, Some(RunId(Uuid::from_u128(0xBF))));+ // The shadow topic is person-id keyed, so it does not co-partition with the owning+ // worker; only the keying is assertable.+ assert_eq!(+ partition as u32,+ partition_for(&alice.to_string(), COHORT_PARTITION_COUNT),+ "the change is person-id keyed on the shadow topic",+ );++ // Run-completion precondition: committed ⇒ durably applied, reaching the produced HWM.+ let seed_partition = part(alice) as i32;+ wait_for(+ "the seed group's committed offset to reach the produced HWM",+ Duration::from_secs(30),+ || seed_group_committed(&groups.seeds, &topics.seeds, seed_partition) == Some(1),+ )+ .await;++ shutdown.request_shutdown();+ instance.join().await;+ })+ .await;+}++/// A tile scanned "now" stays fenced until live consumption flows past `s_chunk + margin`.+#[tokio::test]+#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]+async fn fence_holds_a_fresh_tile_until_live_consumption_passes_its_scan_point() {+ let suffix = Uuid::new_v4();+ let topics = Topics::unique(&suffix);+ let groups = Groups::unique(&suffix);+ with_topics_cleanup(&topics.names(), async {+ topics.create().await;++ let mut manager = Manager::builder("seed-fence-itest")+ .with_trap_signals(false)+ .build();+ let handles = register_instance(&mut manager);+ let shutdown = handles[0].clone();+ let _monitor = manager.monitor_background();++ let fence_margin_ms = 5_000;+ let dir = TempDir::new().unwrap();+ let instance = spawn_instance(+ &topics,+ &groups,+ open_store(&dir),+ seed_catalog(),+ handles,+ fence_margin_ms,+ )+ .await;+ wait_for(+ "the consumer to own every partition",+ Duration::from_secs(30),+ || instance.owned().len() == NUM_PARTITIONS as usize,+ )+ .await;++ let alice = Uuid::from_u128(0xA11CE);+ let seed_sink = KafkaSeedTileSink::new(&producer_kafka_config(), topics.seeds.clone())+ .await+ .expect("create test seed sink");+ let s_chunk = chrono::Utc::now().timestamp_millis();+ produce_tile(&seed_sink, tile(alice, s_chunk)).await;++ // No watermark at all: fail-closed, nothing applies, nothing commits.+ tokio::time::sleep(Duration::from_secs(3)).await;+ assert_eq!(+ topic_message_count(&topics.shadow),+ 0,+ "the fenced tile must not apply",+ );+ assert_eq!(+ seed_group_committed(&groups.seeds, &topics.seeds, part(alice) as i32),+ None,+ "a held tile's offset must never commit",+ );++ // A live event folded before `s_chunk + margin` has elapsed still leaves the fence closed.+ let producer = murmur2_producer();+ produce_warm_event(&producer, &topics.events, alice, 0).await;+ tokio::time::sleep(Duration::from_secs(2)).await;+ assert_eq!(+ topic_message_count(&topics.shadow),+ 0,+ "a watermark below s_chunk + margin keeps the fence closed",+ );++ // Past s_chunk + margin, a newer live fold opens the fence for the held tile.+ tokio::time::sleep(Duration::from_millis(fence_margin_ms as u64 + 1_500)).await;+ produce_warm_event(&producer, &topics.events, alice, 1).await;+ wait_for(+ "the fence to open and the held tile to apply",+ Duration::from_secs(60),+ || topic_message_count(&topics.shadow) == 1,+ )+ .await;+ let (_, payload) = consume_all(&topics.shadow, 1, Duration::from_secs(30))+ .await+ .into_iter()+ .next()+ .expect("one membership change");+ let change: CohortMembershipChange = serde_json::from_slice(&payload).unwrap();+ assert_eq!(change.origin, Some(ChangeOrigin::Seed));+ assert_eq!(change.person_id, alice.to_string());++ shutdown.request_shutdown();+ instance.join().await;+ })+ .await;+}diff --git a/rust/cohort-stream-processor/tests/stage1_worker.rs b/rust/cohort-stream-processor/tests/stage1_worker.rsindex b142dfee1b55..46e7ce404b30 100644--- a/rust/cohort-stream-processor/tests/stage1_worker.rs+++ b/rust/cohort-stream-processor/tests/stage1_worker.rs@@ -15,7 +15,7 @@ use std::sync::Arc;use chrono_tz::Asia::Kolkata;use chrono_tz::{Tz, UTC};-use cohort_stream_processor::consumers::CohortStreamEvent;+use cohort_stream_processor::consumers::{CohortStreamEvent, SeedWork};use cohort_stream_processor::filters::{CatalogHandle, CohortId, FilterCatalog, TeamFilters, TeamFiltersBuilder, TeamId,};@@ -78,6 +78,7 @@ async fn dispatch_to_worker(tx.send(vec![ShuffleMessage::Event {event: Box::new(event),cse_offset,+ broker_ts_ms: None,}]).await.unwrap();@@ -1177,10 +1178,12 @@ async fn sub_batch_read_your_writes_survives_offload() {ShuffleMessage::Event {event: Box::new(event(alice, 5, 0)),cse_offset: 0,+ broker_ts_ms: None,},ShuffleMessage::Event {event: Box::new(event(alice, 5, 0)),cse_offset: 0,+ broker_ts_ms: None,},]).await@@ -2364,3 +2367,225 @@ fn redirected_event_at_or_below_ancestor_max_is_skipped_then_above_folds() {"the redirected fold did not touch the main map",);}++// ---- seed arm: ordering barrier, tracker isolation, watermark advance ----++fn seed_tile(person: Uuid, day: i32, count: u32) -> cohort_core::seed::SeedTile {+ use cohort_core::seed::{ClaimEpoch, ConditionHash, RunId, SChunkMs, SeedTile};+ SeedTile::new(+ TeamId(TEAM),+ person,+ ConditionHash::parse("0123456789abcdef").unwrap(),+ std::num::NonZeroU32::new(count).unwrap(),+ day,+ SChunkMs(1_700_000_000_000),+ RunId(Uuid::from_u128(0xBF)),+ ClaimEpoch(1),+ )+}++fn seed_message(person: Uuid, day: i32, count: u32, offset: i64) -> ShuffleMessage {+ ShuffleMessage::Seed {+ work: Box::new(SeedWork::Tile(seed_tile(person, day, count))),+ offset,+ }+}++fn utc_today() -> i32 {+ day_idx_in_tz(chrono::Utc::now().timestamp_millis(), UTC)+}++/// Buffered event-path changes flush before the tile's own emission, each input marks its own+/// tracker, and the watermark advances only after the batch's final mark.+#[tokio::test]+async fn seed_arm_flushes_buffered_event_changes_first_and_marks_both_trackers() {+ let (_dir, store) = temp_store();+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![behavioral_leaf(7)]))]);+ let alice = person(1);+ let bob = person(2);++ 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,+ );++ let broker_ts = 1_750_000_000_000_i64;+ tracker.mark_dispatched(PARTITION_ID as i32, 1);+ deps.seed_tracker.mark_dispatched(PARTITION_ID as i32, 8);+ tx.send(vec![+ ShuffleMessage::Event {+ event: Box::new(event(alice, 5, 0)),+ cse_offset: 0,+ broker_ts_ms: Some(broker_ts),+ },+ seed_message(bob, utc_today(), 1, 7),+ ])+ .await+ .unwrap();+ drop(tx);+ worker.join().await.unwrap();++ let changes = sink.changes();+ assert_eq!(changes.len(), 2, "one live flip, one seeded flip");+ assert_eq!(+ (changes[0].person_id.clone(), changes[0].origin),+ (alice.to_string(), None),+ "the buffered live change flushed before the seed arm ran",+ );+ 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)),+ Some(&1),+ "the events tracker advanced past the event",+ );+ assert_eq!(+ deps.seed_tracker+ .committable_offsets()+ .get(&(PARTITION_ID as i32)),+ Some(&8),+ "the seed tracker advanced past the tile",+ );+ assert_eq!(+ deps.live_watermarks.get(PARTITION_ID as i32),+ Some(cohort_stream_processor::partitions::WatermarkMs(broker_ts)),+ "the folded batch advanced the live watermark",+ );+}++/// A failed seed emission holds only the seed tracker; the events tracker is unaffected.+#[tokio::test]+async fn seed_produce_failure_holds_the_seed_tracker_but_not_the_events_tracker() {+ let (_dir, store) = temp_store();+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![behavioral_leaf(7)]))]);+ let alice = person(1);+ let bob = person(2);++ let catalog = catalog_of(filters);+ // The seed's produce is the first flush (the tile leads the batch); the event's is the second.+ let sink = CaptureSink::failing_first(1);+ 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,+ );++ tracker.mark_dispatched(PARTITION_ID as i32, 1);+ deps.seed_tracker.mark_dispatched(PARTITION_ID as i32, 8);+ tx.send(vec![+ seed_message(bob, utc_today(), 1, 7),+ ShuffleMessage::Event {+ event: Box::new(event(alice, 5, 0)),+ cse_offset: 0,+ broker_ts_ms: None,+ },+ ])+ .await+ .unwrap();+ drop(tx);+ worker.join().await.unwrap();++ assert_eq!(+ deps.seed_tracker+ .committable_offsets()+ .get(&(PARTITION_ID as i32)),+ None,+ "the failed seed produce holds the seed offset",+ );+ assert_eq!(+ tracker.committable_offsets().get(&(PARTITION_ID as i32)),+ Some(&1),+ "the events offset is unaffected by the seed hold",+ );+ let changes = sink.changes();+ assert_eq!(changes.len(), 1, "only the live flip landed");+ assert_eq!(changes[0].person_id, alice.to_string());+}++/// A held batch must not advance the watermark; the successful redelivery does.+#[tokio::test]+async fn watermark_advances_only_after_a_successful_mark() {+ let (_dir, store) = temp_store();+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![behavioral_leaf(7)]))]);+ let alice = person(1);++ let catalog = catalog_of(filters);+ let sink = CaptureSink::failing_first(1);+ let tracker = Arc::new(OffsetTracker::new());+ let deps = MergeWorkerDeps::capture();++ let broker_ts = 1_750_000_000_000_i64;+ let run = |batch: Vec<ShuffleMessage>| {+ let catalog = catalog.clone();+ let sink = sink.clone();+ let tracker = tracker.clone();+ let deps = deps.clone();+ let store = store.clone();+ async move {+ 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),+ tracker.clone(),+ deps,+ false,+ );+ tracker.mark_dispatched(PARTITION_ID as i32, 1);+ tx.send(batch).await.unwrap();+ drop(tx);+ worker.join().await.unwrap();+ }+ };++ run(vec![ShuffleMessage::Event {+ event: Box::new(event(alice, 5, 0)),+ cse_offset: 0,+ broker_ts_ms: Some(broker_ts),+ }])+ .await;+ assert_eq!(+ deps.live_watermarks.get(PARTITION_ID as i32),+ None,+ "a held (unmarked) batch never advances the watermark",+ );++ run(vec![ShuffleMessage::Event {+ event: Box::new(event(alice, 5, 0)),+ cse_offset: 0,+ broker_ts_ms: Some(broker_ts),+ }])+ .await;+ assert_eq!(+ deps.live_watermarks.get(PARTITION_ID as i32),+ Some(cohort_stream_processor::partitions::WatermarkMs(broker_ts)),+ "the successful redelivery advances it",+ );+}diff --git a/rust/cohort-stream-processor/tests/sweep_worker.rs b/rust/cohort-stream-processor/tests/sweep_worker.rsindex 7ca07331e820..b4bd26a190cd 100644--- a/rust/cohort-stream-processor/tests/sweep_worker.rs+++ b/rust/cohort-stream-processor/tests/sweep_worker.rs@@ -240,6 +240,7 @@ async fn send_event(tx.send(vec![ShuffleMessage::Event {event: Box::new(event),cse_offset,+ broker_ts_ms: None,}]).await.unwrap();@@ -504,6 +505,7 @@ async fn event_then_sweep_in_one_batch_emits_entered_before_left() {ShuffleMessage::Event {event: Box::new(event_at(alice, ts, 0)),cse_offset: 0,+ broker_ts_ms: None,},ShuffleMessage::Sweep {due_before_ms: deadline + DAY_MS,@@ -661,6 +663,7 @@ async fn sweep_caps_evictions_per_pass_and_drains_the_remainder_next_tick() {.map(|i| ShuffleMessage::Event {event: Box::new(event_at(person(i as u128 + 1), ts, i as i64)),cse_offset: i as i64,+ broker_ts_ms: None,}).collect();tx.send(events).await.unwrap();@@ -1858,6 +1861,7 @@ async fn dispatch_sweeper_routes_an_end_to_end_eviction() {event: event_at(alice, ts, 0),partition: 0,offset: 0,+ broker_ts_ms: None,}]).await;