: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): give backfill seeds their own lane per partition worker (#95484)
Matheus Batistac59af77dfbb1
diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rsindex cf80ae1d1ef9..1e81b224bb27 100644--- a/rust/cohort-stream-processor/src/config.rs+++ b/rust/cohort-stream-processor/src/config.rs@@ -75,13 +75,27 @@ pub struct Config {#[envconfig(default = "128")]pub partition_channel_buffer: usize,- /// Per-partition ceiling on un-drained events in a worker's channel — the binding intake bound- /// (the 128-slot buffer counts sub-batches, not the events inside them). Worst case in channels- /// ≈ `cap × owned_partitions × avg_event_bytes`. Tune down if soak RSS runs hot; too low churns- /// pause/resume.+ /// Per-partition ceiling on un-drained events in a worker's **live** lane — the binding intake+ /// bound (the 128-slot buffer counts sub-batches, not the events inside them). Seeds have their+ /// own lane and their own cap, [`PARTITION_INTAKE_MAX_SEEDS`](Self::partition_intake_max_seeds).+ /// Worst case in channels ≈ `cap × owned_partitions × avg_event_bytes`. Tune down if soak RSS+ /// runs hot; too low churns pause/resume.#[envconfig(from = "PARTITION_INTAKE_MAX_EVENTS", default = "1024")]pub partition_intake_max_events: usize,+ /// The seed lane's capacity, in seeds, for one partition worker. The lane holds one seed per+ /// slot, so this value *is* the seed intake cap — there is no separate counter.+ ///+ /// The resident bound per partition is `cap + COHORT_SEED_APPLY_BATCH_MAX`: `recv_many` frees+ /// the slots it takes at the start of a seed turn and the dispatcher refills them while the+ /// turn runs, which is wanted — the next turn is already full when this one ends.+ ///+ /// Additive with the event cap, so a revoke or shutdown drain now covers up to this many seeds+ /// **plus** `PARTITION_INTAKE_MAX_EVENTS` events per partition. At the default that is about+ /// four quanta of seeds, seconds of drain at the rates the apply path sustains.+ #[envconfig(from = "PARTITION_INTAKE_MAX_SEEDS", default = "1024")]+ pub partition_intake_max_seeds: usize,+#[envconfig(default = "localhost:9092")]pub kafka_hosts: String,@@ -696,6 +710,12 @@ impl Config {}}+ /// The seed lane's capacity for one partition worker. Validated at startup, so a zero here is+ /// a bug rather than a config error.+ pub fn seed_lane_cap(&self) -> NonZeroUsize {+ NonZeroUsize::new(self.partition_intake_max_seeds).unwrap_or(NonZeroUsize::MIN)+ }+pub fn reconcile_tick_interval(&self) -> Duration {Duration::from_millis(self.cohort_seed_reconcile_tick_interval_ms)}@@ -813,6 +833,17 @@ impl Config {self.cohort_seed_apply_batch_max_rows > 0,"COHORT_SEED_APPLY_BATCH_MAX_ROWS must be greater than zero.",);+ // A zero-capacity mpsc channel panics on construction, and so does one above tokio's+ // permit bound, so either would take the pod down at the first worker spawn.+ ensure!(+ self.partition_intake_max_seeds > 0,+ "PARTITION_INTAKE_MAX_SEEDS must be greater than zero (it is the seed lane's capacity in seeds).",+ );+ ensure!(+ self.partition_intake_max_seeds <= tokio::sync::Semaphore::MAX_PERMITS,+ "PARTITION_INTAKE_MAX_SEEDS must not exceed {} (tokio's channel capacity bound).",+ tokio::sync::Semaphore::MAX_PERMITS,+ );let pacing = self.seed_pacing_config()?;// Idle partitions' watermarks advance only once per probe, so a pause threshold inside@@ -1117,6 +1148,7 @@ mod tests {cohort_event_name_gating_enabled: true,partition_channel_buffer: 128,partition_intake_max_events: 1024,+ partition_intake_max_seeds: 1024,kafka_hosts: "localhost:9092".to_string(),kafka_tls: false,kafka_client_id: String::new(),@@ -1316,8 +1348,20 @@ mod tests {.to_string().contains("COHORT_SEED_APPLY_BATCH_MAX_ROWS"),);- // `1` is the documented hatch back to the per-seed apply, so it must start.+ // A zero-capacity seed lane would panic the first worker spawn, and so would one above+ // tokio's channel bound, so both must be refused too.config.cohort_seed_apply_batch_max_rows = 1;+ for cap in [0, usize::MAX] {+ config.partition_intake_max_seeds = cap;+ assert!(config+ .validate_startup()+ .unwrap_err()+ .to_string()+ .contains("PARTITION_INTAKE_MAX_SEEDS"),);+ }++ // `1` is the documented hatch back to the per-seed apply, so it must start.+ config.partition_intake_max_seeds = 1;assert!(config.validate_startup().is_ok());assert_eq!(config.seed_run_budget().seeds.get(), 1);}@@ -1485,6 +1529,8 @@ mod tests {fn intake_and_boot_ordering_knobs_default_and_override_from_env() {let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();assert_eq!(defaults.partition_intake_max_events, 1024);+ assert_eq!(defaults.partition_intake_max_seeds, 1024);+ assert_eq!(defaults.seed_lane_cap().get(), 1024);assert_eq!(defaults.kafka_queued_max_messages_kbytes, 131_072);assert_eq!(defaults.kafka_queued_min_messages, 2000);assert_eq!(@@ -1494,6 +1540,7 @@ mod tests {let env: std::collections::HashMap<String, String> = [("PARTITION_INTAKE_MAX_EVENTS", "512"),+ ("PARTITION_INTAKE_MAX_SEEDS", "64"),("COHORT_KAFKA_QUEUED_MAX_MESSAGES_KBYTES", "65536"),("COHORT_KAFKA_QUEUED_MIN_MESSAGES", "1000"),("COHORT_FIRST_EVICTION_SWEEP_DELAY_MS", "30000"),@@ -1503,6 +1550,7 @@ mod tests {.collect();let config = Config::init_from_hashmap(&env).unwrap();assert_eq!(config.partition_intake_max_events, 512);+ assert_eq!(config.seed_lane_cap().get(), 64);assert_eq!(config.fetch_queue_config().queued_max_messages_kbytes,65536diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rsindex 58b292759cfb..a90911d28e38 100644--- a/rust/cohort-stream-processor/src/consumers/events.rs+++ b/rust/cohort-stream-processor/src/consumers/events.rs@@ -48,7 +48,7 @@ use crate::partitions::backpressure::Backpressure;use crate::partitions::offset_tracker::OffsetTracker;use crate::partitions::pause::{ConsumerPauser, PartitionPauser};use crate::partitions::rebalance::{CohortConsumerContext, ConsumerCommandReceiver};-use crate::partitions::router::{PartitionRouter, SendOutcome};+use crate::partitions::router::{PartitionRouter, SeedRefusal, SeedSendOutcome, SendOutcome};use crate::partitions::shuffle_message::ShuffleMessage;use crate::producer::MembershipSink;use crate::store::durability::OffsetManifest;@@ -384,9 +384,10 @@ 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.+ /// Non-blocking seed dispatch onto the workers' seed lanes, raising the **seed** tracker's+ /// ceiling only for what lands. A sub-batch may land as a prefix, so the ceiling comes from the+ /// router's report of the highest offset that reached the lane, never from the batch maximum.+ /// 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() {@@ -399,49 +400,39 @@ impl EventDispatcher {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 owned_seeds: Vec<ConsumedSeed> = Vec::with_capacity(batch.len());let mut not_owned = 0u64;for consumed in batch {- let partition = consumed.partition;- if !self.owned.contains(&partition) {+ if !self.owned.contains(&consumed.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()));+ self.ensure_worker(consumed.partition);+ owned_seeds.push(consumed);}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);+ for (partition, outcome) in self.router.try_route_seeds(owned_seeds) {+ let landed_max = match outcome {+ SeedSendOutcome::Sent { max_offset } => Some(max_offset),+ SeedSendOutcome::Refused {+ landed_max,+ reason,+ rest,+ } => {+ if reason != SeedRefusal::Full {+ route_errors += 1;}+ full.entry(partition).or_default().extend(rest);+ landed_max}- SendOutcome::Full(returned) => {- full.entry(partition).or_default().extend(- returned- .into_iter()- .filter_map(|message| ConsumedSeed::from_message(partition, message)),- );- }- SendOutcome::NoWorker(returned) | SendOutcome::ChannelClosed(returned) => {- full.entry(partition).or_default().extend(- returned- .into_iter()- .filter_map(|message| ConsumedSeed::from_message(partition, message)),- );- route_errors += 1;- }+ };+ if let Some(max_offset) = landed_max {+ self.merge+ .seed_tracker+ .mark_dispatched(partition, max_offset + 1);}}if route_errors > 0 {@@ -513,10 +504,10 @@ impl EventDispatcher {self.reclaim_stale_slice(partition);}match self.router.add_partition(partition) {- Some(receiver) => {+ Some(inbox) => {let worker = Stage1Worker::spawn_with_gating(partition as u16,- receiver,+ inbox,self.handle.clone(),self.catalog.clone(),self.sink.clone(),@@ -1482,9 +1473,12 @@ pub(crate) async fn run_pauser_loop(// facade.#[allow(clippy::disallowed_methods)]mod tests {+ use std::num::NonZeroUsize;+use super::*;use chrono_tz::UTC;use common_kafka::kafka_producer::KafkaProduceError;+ use futures::FutureExt;use serde_json::json;use tempfile::TempDir;use uuid::Uuid;@@ -2261,17 +2255,22 @@ mod tests {)}- /// Like [`dispatcher_with_buffer`] but with a per-partition event-intake `cap`, so a test can trip- /// the event budget while the mpsc slots stay free.+ /// Like [`dispatcher_with_buffer`] but with a per-partition event-intake `cap` and a seed-lane+ /// capacity, so a test can trip either lane's budget while the mpsc slots stay free.fn dispatcher_with_intake_cap(store: &CohortStore,catalog: Arc<CatalogHandle>,buffer: usize,cap: usize,+ seed_cap: usize,) -> EventDispatcher {let sink: Arc<dyn MembershipSink> = Arc::new(CaptureSink::new());EventDispatcher::new(- PartitionRouter::with_intake_cap(buffer, cap),+ PartitionRouter::with_intake_cap(+ buffer,+ cap,+ NonZeroUsize::new(seed_cap).expect("a test seed cap is non-zero"),+ ),Arc::new(OffsetTracker::new()),test_handle(store),catalog,@@ -2315,8 +2314,8 @@ mod tests {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();+ // Hold the inbox so no worker drains; the ceilings are the observable.+ let mut inbox = dispatcher.router.add_partition(0).unwrap();let full = dispatcher.dispatch_seeds(vec![consumed_seed(person(1), 0, 3),@@ -2326,7 +2325,7 @@ mod tests {]);assert!(full.is_empty(), "both owned seeds landed");- // Seeds carry no event offset, so the dispatcher must have raised the seed ceiling+ // Seeds never ride the live lane, so the dispatcher must have raised the seed ceiling// itself.let seed_tracker = &dispatcher.merge_deps().seed_tracker;assert_eq!(@@ -2346,27 +2345,72 @@ mod tests {);assert!(dispatcher.tracker().committable_offsets().is_empty());- let batch = rx.try_recv().unwrap();+ let mut landed = Vec::new();assert_eq!(- batch.iter().filter_map(ShuffleMessage::seed_offset).count(),- 2,- "the two owned seeds ride the worker channel",+ inbox.seeds.recv_many(&mut landed, 8).now_or_never(),+ Some(2)+ );+ assert_eq!(held_seed_offsets(&landed), vec![3, 5]);+ assert!(+ inbox.live.try_recv().is_err(),+ "nothing reached the live lane",);}#[tokio::test]- async fn dispatch_seeds_returns_the_over_budget_remainder_without_raising_its_ceiling() {+ async fn dispatch_seeds_lands_while_the_live_intake_is_full() {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);+ // One-event live budget, a roomy seed lane: the two must not share a budget.+ let dispatcher = dispatcher_with_intake_cap(&store, behavioral_catalog(), 16, 1, 16);dispatcher.assign_partition(0);- let _rx = dispatcher.router.add_partition(0).unwrap();+ let mut inbox = dispatcher.router.add_partition(0).unwrap();+ let no_held = HashSet::new();assert!(dispatcher- .dispatch_seeds(vec![consumed_seed(person(1), 0, 10)])+ .dispatch_events_nonblocking(vec![consumed(person(1), 0, 104)], &no_held).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!(+ dispatcher+ .dispatch_events_nonblocking(vec![consumed(person(2), 0, 105)], &no_held)+ .contains_key(&0),+ "the live lane is at its event ceiling",+ );++ assert!(+ dispatcher+ .dispatch_seeds(vec![consumed_seed(person(3), 0, 10)])+ .is_empty(),+ "the seed lane is unaffected by a full live intake",+ );+ let seed_tracker = &dispatcher.merge_deps().seed_tracker;+ assert_eq!(+ seed_tracker.mark_processed(0, 11),+ MarkOutcome::WithinDispatch,+ );+ assert_eq!(seed_tracker.committable_offsets().get(&0), Some(&11));++ let mut landed = Vec::new();+ assert_eq!(+ inbox.seeds.recv_many(&mut landed, 8).now_or_never(),+ Some(1)+ );+ assert_eq!(held_seed_offsets(&landed), vec![10]);+ }++ #[tokio::test]+ async fn dispatch_seeds_holds_the_suffix_on_the_seed_cap_and_raises_the_ceiling_only_for_what_landed(+ ) {+ let (_dir, store) = temp_store();+ // A one-seed lane, so the second seed of the sub-batch is refused.+ let dispatcher = dispatcher_with_intake_cap(&store, behavioral_catalog(), 16, 16, 1);+ dispatcher.assign_partition(0);+ let _inbox = dispatcher.router.add_partition(0).unwrap();++ let mut full = dispatcher.dispatch_seeds(vec![+ consumed_seed(person(1), 0, 10),+ consumed_seed(person(2), 0, 11),+ ]);+ let held = full.remove(&0).expect("partition 0 held on the seed cap");assert_eq!(held_seed_offsets(&held), vec![11]);let seed_tracker = &dispatcher.merge_deps().seed_tracker;@@ -2414,7 +2458,7 @@ mod tests {);// Drain A; the retry-flush now sends B and the ceiling advances past it.- let _a = rx.recv().await.unwrap();+ let _a = rx.live.recv().await.unwrap();assert!(dispatcher.redispatch_held(vec![(0, held)]).is_empty(),"the holdover flushed once the channel had room",@@ -2433,7 +2477,7 @@ mod tests {async fn nonblocking_dispatch_holds_on_the_event_cap_while_slots_stay_free() {let (_dir, store) = temp_store();// 16 mpsc slots but a one-event budget: the event cap, not the slots, is what holds batch B.- let dispatcher = dispatcher_with_intake_cap(&store, behavioral_catalog(), 16, 1);+ let dispatcher = dispatcher_with_intake_cap(&store, behavioral_catalog(), 16, 1, 16);dispatcher.assign_partition(0);let mut rx = dispatcher.router.add_partition(0).unwrap();let no_held = HashSet::new();@@ -2454,9 +2498,9 @@ mod tests {);// Drain A and step past it so the budget frees (release lands on the next recv), then B flushes.- let _a = rx.recv().await.unwrap();+ let _a = rx.live.recv().await.unwrap();assert!(- rx.try_recv().is_err(),+ rx.live.try_recv().is_err(),"channel drained; the recv released A's budget",);assert!(@@ -2483,7 +2527,10 @@ mod tests {dispatcher.dispatch_events_nonblocking(vec![consumed(person(1), 0, 200)], &held);assert_eq!(held_offsets(&full.remove(&0).unwrap()), vec![200]);- assert!(rx.try_recv().is_err(), "nothing was sent to the channel");+ assert!(+ rx.live.try_recv().is_err(),+ "nothing was sent to the channel"+ );assert!(!dispatcher.tracker().committable_offsets().contains_key(&0),"a deferred event never raised the ceiling",@@ -2882,7 +2929,7 @@ mod tests {dispatcher.route_sweep(cutoff).await;for rx in [&mut rx0, &mut rx1] {- let batch = rx.recv().await.expect("a sweep was routed");+ let batch = rx.live.recv().await.expect("a sweep was routed");assert_eq!(batch.len(), 1);match &batch[0] {ShuffleMessage::Sweep { due_before_ms } => assert_eq!(*due_before_ms, cutoff),@@ -2904,7 +2951,11 @@ mod tests {dispatcher.route_reconcile_drain().await;for receiver in [&mut rx0, &mut rx1] {- let batch = receiver.recv().await.expect("a reconcile tick was routed");+ let batch = receiver+ .live+ .recv()+ .await+ .expect("a reconcile tick was routed");assert!(matches!(batch.as_slice(), [ShuffleMessage::ReconcileDrain]));}}@@ -2954,6 +3005,7 @@ mod tests {dispatcher.route_sweep(777).await;for rx in [&mut rx0, &mut rx2] {let batch = rx+ .live.recv().await.expect("a worker-bearing partition got the sweep");diff --git a/rust/cohort-stream-processor/src/consumers/seeds.rs b/rust/cohort-stream-processor/src/consumers/seeds.rsindex c56f2deb5e32..8cffc70a9a83 100644--- a/rust/cohort-stream-processor/src/consumers/seeds.rs+++ b/rust/cohort-stream-processor/src/consumers/seeds.rs@@ -2,11 +2,13 @@//!//! Assignment arrives via the events group's rebalance mirror. Four admission gates share one//! holdover + pause mechanism: the apply fence (a tile dispatches only once its partition's live-//! watermark clears `s_chunk + margin`), a full worker channel, live-priority (the partition's-//! live watermark age crossed the pause threshold — live traffic always wins), and pod-wide disk+//! watermark clears `s_chunk + margin`), a full seed lane, live-priority (the partition's live+//! watermark age crossed the pause threshold — live traffic always wins), and pod-wide disk//! pressure. 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, but a live-lag/disk gate holds them too (nothing leapfrogs a gated partition).+//! The live-lag gate remains an admission backstop because an admitted seed run still uses the+//! worker and its CPU and I/O even though separate lanes keep queued seeds behind live traffic.+//! Consume-side skips ride the seed lane so their offsets mark in order; they never close the+//! fence, but a live-lag/disk gate holds them too (nothing leapfrogs a gated partition).//! The [`PauseLedger`] records why each partition is held and since when; the pause target and//! the age/count gauges all derive from it.@@ -39,7 +41,6 @@ use crate::partitions::pacing::{};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.@@ -91,31 +92,6 @@ pub struct ConsumedSeed {}impl ConsumedSeed {- pub(crate) fn into_message(self) -> ShuffleMessage {- ShuffleMessage::Seed {- work: Box::new(self.work),- offset: self.offset,- broker_ts_ms: self.broker_ts_ms,- }- }-- /// 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,- broker_ts_ms,- } => Some(Self {- work: *work,- partition,- offset,- broker_ts_ms,- }),- _ => None,- }- }-/// The fence input. Control messages, person seeds, and skips are fence-open: none of them/// bounds the arrival of events over the live stream.fn s_chunk_ms(&self) -> Option<SChunkMs> {@@ -1312,43 +1288,6 @@ mod tests {));}- /// A channel-full bounce round-trips through the shuffle message; losing `broker_ts_ms` there- /// would zero the oldest-held age gauge exactly when the partition is stuck.- #[test]- fn consumed_seed_round_trips_through_its_shuffle_message() {- let consumed = ConsumedSeed {- broker_ts_ms: Some(1_700_000_000_000),- ..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_eq!(back.broker_ts_ms, Some(1_700_000_000_000));- assert!(matches!(back.work, SeedWork::Tile(tile) if tile.s_chunk_ms() == SChunkMs(123)));-- let reconcile = ReconcileTile::new(- TeamId(2),- CohortId(42),- ReconcileScope::Behavioral(BehavioralShapeHash::parse("0123456789abcdef").unwrap()),- RunId(Uuid::nil()),- );- let consumed = ConsumedSeed {- work: SeedWork::Reconcile(reconcile.clone()),- partition: 9,- offset: 43,- broker_ts_ms: None,- };- let back = ConsumedSeed::from_message(9, consumed.into_message()).unwrap();- assert_eq!(back.offset, 43);- assert_eq!(back.broker_ts_ms, None);- assert!(matches!(back.work, SeedWork::Reconcile(tile) if tile == reconcile));-- let not_seed = ShuffleMessage::RedrivePendingTransfers;- assert!(ConsumedSeed::from_message(9, not_seed).is_none());- }-#[test]fn reconcile_is_fence_open_but_never_leapfrogs_a_closed_tile() {let reconcile = ReconcileTile::new(diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rsindex b3df865ecd8f..fecebabaff4e 100644--- a/rust/cohort-stream-processor/src/main.rs+++ b/rust/cohort-stream-processor/src/main.rs@@ -168,6 +168,7 @@ async fn async_main(config: Config) -> Result<()> {let router = PartitionRouter::with_intake_cap(config.partition_channel_buffer,config.partition_intake_max_events,+ config.seed_lane_cap(),);let offset_tracker = Arc::new(OffsetTracker::new());diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rsindex a8b7cd2c06e5..27fd45263b1c 100644--- a/rust/cohort-stream-processor/src/observability/metrics.rs+++ b/rust/cohort-stream-processor/src/observability/metrics.rs@@ -229,17 +229,28 @@ pub const TOKIO_BLOCKING_QUEUE_DEPTH: &str = "tokio_blocking_queue_depth";pub const PARTITIONS_ACTIVE: &str = "partitions_active";/// Messages dropped while routing (no live worker), labelled by `reason` (counter).pub const PARTITION_ROUTE_DROPPED_TOTAL: &str = "partition_route_dropped_total";-/// Sub-batches queued in a partition worker's channel, labelled by `partition` (gauge).+/// Sub-batches queued in a partition worker's live lane, labelled by `partition` (gauge).pub const PARTITION_CHANNEL_DEPTH: &str = "partition_channel_depth";-/// Events held back because a partition worker's channel was full, labelled by `partition` (counter).-/// Backpressure, not loss: the partition is paused and its events redispatch once the channel drains.-/// Re-counted on every retry of a still-full holdover, so it is a pressure rate, not a distinct-event-/// count.+/// Events held back because a partition worker's live lane was full, labelled by `partition`+/// (counter). Backpressure, not loss: the partition is paused and its events redispatch once the+/// lane drains. Re-counted on every retry of a still-full holdover, so it is a pressure rate, not a+/// distinct-event count.pub const PARTITION_CHANNEL_FULL_TOTAL: &str = "partition_channel_full_total";-/// Un-drained events in a partition worker's channel (plus the batch it is processing), labelled by-/// `partition` (gauge). A value pinned near `PARTITION_INTAKE_MAX_EVENTS` that never drains flags a-/// stuck worker.+/// Un-drained events in a partition worker's live lane (plus the batch it is processing), labelled+/// by `partition` (gauge). A value pinned near `PARTITION_INTAKE_MAX_EVENTS` that never drains flags+/// a stuck worker.pub const PARTITION_INTAKE_EVENTS: &str = "partition_intake_events";+/// Seeds resident in a partition worker's seed lane, queued plus the quantum being applied,+/// labelled by `partition` (gauge). The router adds what it lands, the worker releases a quantum+/// once its last run has applied, and a revoke zeroes the series. A value pinned near+/// `PARTITION_INTAKE_MAX_SEEDS` means the worker is serving live traffic and the seed lane is+/// backing up behind it: a partition whose live lane never empties makes no seed progress by+/// design, and shows under [`SEED_PAUSED_PARTITIONS`] with cause `channel_full`.+pub const PARTITION_SEED_CHANNEL_DEPTH: &str = "partition_seed_channel_depth";+/// Seeds held back because a partition worker's seed lane was full, labelled by `partition`+/// (counter). Backpressure, not loss, and re-counted on every retry of a still-full holdover, like+/// its live twin [`PARTITION_CHANNEL_FULL_TOTAL`].+pub const PARTITION_SEED_CHANNEL_FULL_TOTAL: &str = "partition_seed_channel_full_total";/// Partitions currently paused on the events consumer to shed downstream backpressure (gauge).pub const PARTITIONS_PAUSED: &str = "partitions_paused";/// Events currently held across all paused partitions, awaiting redispatch (gauge). Bounded — a@@ -798,6 +809,11 @@ mod tests {fn partition_backpressure_metric_names_are_stable() {assert_eq!(PARTITION_CHANNEL_FULL_TOTAL, "partition_channel_full_total");assert_eq!(PARTITION_INTAKE_EVENTS, "partition_intake_events");+ assert_eq!(PARTITION_SEED_CHANNEL_DEPTH, "partition_seed_channel_depth");+ assert_eq!(+ PARTITION_SEED_CHANNEL_FULL_TOTAL,+ "partition_seed_channel_full_total"+ );assert_eq!(PARTITIONS_PAUSED, "partitions_paused");assert_eq!(PENDING_HELD_EVENTS, "pending_held_events");}diff --git a/rust/cohort-stream-processor/src/partitions/intake.rs b/rust/cohort-stream-processor/src/partitions/intake.rsindex 733762169a76..7e46cd9d11d8 100644--- a/rust/cohort-stream-processor/src/partitions/intake.rs+++ b/rust/cohort-stream-processor/src/partitions/intake.rs@@ -1,5 +1,6 @@-//! 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.+//! App-side intake backpressure: a per-partition ceiling on events resident in a worker's live+//! lane. Over the cap, new messages are refused (→ held → paused), never buffered. Seeds are not+//! metered here — their lane holds one seed per slot, so its capacity is their cap.//!//! 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@@ -14,7 +15,7 @@ use tokio::sync::mpsc;use super::shuffle_message::ShuffleMessage;use crate::observability::metrics::PARTITION_INTAKE_EVENTS;-/// Intake-counted messages in a batch; maintenance ticks count 0.+/// Intake-counted events in a batch; maintenance ticks count 0.pub fn count_intake(batch: &[ShuffleMessage]) -> usize {batch.iter()@@ -30,7 +31,7 @@ pub enum Admission {Rejected,}-/// Per-partition ceiling on un-drained events.+/// Per-partition ceiling on un-drained events in the live lane.////// Releases (from the worker's [`MeteredReceiver`] and, on a failed send, the router) only ever lower/// the count, so [`try_admit`](Self::try_admit)'s plain load-then-add never overshoots `cap`: a@@ -129,6 +130,10 @@ impl MeteredReceiver {}/// Release the previous batch, then await the next.+ ///+ /// Cancel-safe, so the worker can poll it as a `select!` branch: the release runs on the first+ /// poll, strictly after the previous batch was processed, and is idempotent when the future is+ /// dropped and re-created on the next round.pub async fn recv(&mut self) -> Option<Vec<ShuffleMessage>> {self.release_outstanding();let batch = self.receiver.recv().await?;@@ -191,7 +196,7 @@ mod tests {}#[test]- fn count_intake_counts_events_and_seeds_but_ignores_maintenance() {+ fn count_intake_counts_events_but_ignores_maintenance() {let batch = vec![event(),ShuffleMessage::Sweep { due_before_ms: 1 },diff --git a/rust/cohort-stream-processor/src/partitions/mod.rs b/rust/cohort-stream-processor/src/partitions/mod.rsindex 8848497f9e81..ee139267d476 100644--- a/rust/cohort-stream-processor/src/partitions/mod.rs+++ b/rust/cohort-stream-processor/src/partitions/mod.rs@@ -33,6 +33,9 @@ pub use rebalance::{run_rebalance_worker, CohortConsumerContext, ConsumerCommand, ConsumerCommandReceiver,ConsumerCommandSender, RebalanceEvent, RebalanceEventReceiver,};-pub use router::{PartitionRouter, RouteError, SendOutcome};+pub use router::{+ PartitionRouter, RouteError, SeedReceiver, SeedRefusal, SeedSendOutcome, SendOutcome,+ WorkerInbox,+};pub use shuffle_message::ShuffleMessage;pub use watermarks::{LiveWatermarks, WatermarkMs};diff --git a/rust/cohort-stream-processor/src/partitions/router.rs b/rust/cohort-stream-processor/src/partitions/router.rsindex a52317c6a949..8104c050c00c 100644--- a/rust/cohort-stream-processor/src/partitions/router.rs+++ b/rust/cohort-stream-processor/src/partitions/router.rs@@ -1,12 +1,16 @@-//! Partition-affined routing. Maps a `cohort_stream_events` partition to its owning worker's-//! bounded channel and dispatches per-partition sub-batches, so every state mutation for a given+//! Partition-affined routing. Maps a `cohort_stream_events` partition to its owning worker's two+//! bounded lanes and dispatches per-partition sub-batches, so every state mutation for a given//! `(team_id, person_id)` serializes through exactly one worker.//!+//! Live messages and backfill seeds ride separate lanes with separate budgets, so an admitted seed+//! backlog can never queue in front of a live sub-batch. One worker task drains both, live first.+//!//! A slow partition cannot stall the rest: the `DashMap` guard is cloned (dropped) before any//! `.await`, and per-partition sends fan out concurrently via `join_all`.use std::collections::HashMap;-use std::sync::atomic::{AtomicBool, Ordering};+use std::num::NonZeroUsize;+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::Arc;use dashmap::mapref::entry::Entry;@@ -20,11 +24,16 @@ use tracing::warn;use super::intake::{count_intake, Admission, MeteredReceiver, PartitionIntake};use super::shuffle_message::ShuffleMessage;+use crate::consumers::seeds::ConsumedSeed;use crate::observability::metrics::{PARTITIONS_ACTIVE, PARTITION_CHANNEL_DEPTH, PARTITION_CHANNEL_FULL_TOTAL,- PARTITION_ROUTE_DROPPED_TOTAL,+ PARTITION_ROUTE_DROPPED_TOTAL, PARTITION_SEED_CHANNEL_DEPTH, PARTITION_SEED_CHANNEL_FULL_TOTAL,};+/// Seed-lane capacity for [`PartitionRouter::new`], the test constructor. Production sizes it from+/// `PARTITION_INTAKE_MAX_SEEDS` via [`PartitionRouter::with_intake_cap`].+const DEFAULT_SEED_CAP: NonZeroUsize = NonZeroUsize::new(1024).unwrap();+const REASON_NO_WORKER: &str = "no_worker";const REASON_CHANNEL_CLOSED: &str = "channel_closed";@@ -61,48 +70,241 @@ pub enum SendOutcome {ChannelClosed(Vec<ShuffleMessage>),}-/// A registered worker channel: the sender and the per-partition event-intake budget its-/// [`MeteredReceiver`] releases against. Cloning shares both (both are `Arc`), so a lookup can drop-/// the shard guard before use.+/// Per-partition result of [`try_route_seeds`](PartitionRouter::try_route_seeds). Seeds land as a+/// prefix in offset order: the first refused seed ends the attempt, and nothing after it is tried.+///+/// Stopping at the first refusal is what keeps the ceiling exact. The worker drains the lane+/// concurrently, so a `try_send` that returns `Full` can be followed by one that succeeds; carrying+/// on would raise the ceiling past the refused seed, let the worker mark the later one processed,+/// and commit the refused offset away while it still sits in the holdover.+#[derive(Debug)]+pub enum SeedSendOutcome {+ /// Every seed landed; the dispatch ceiling is `max_offset + 1`.+ Sent { max_offset: i64 },+ /// `landed_max` is the highest offset that reached the lane (`None`: nothing did); `rest` is+ /// the non-empty FIFO suffix for the caller to hold. Non-empty by construction, so a fully+ /// landed partition can never be paused for nothing.+ Refused {+ landed_max: Option<i64>,+ reason: SeedRefusal,+ rest: Vec<ConsumedSeed>,+ },+}++/// Why a seed sub-batch stopped short. `Full` is backpressure; the other two mean the worker is+/// gone and Kafka replays whatever the caller does not hold.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum SeedRefusal {+ Full,+ NoWorker,+ ChannelClosed,+}++/// The seed lane's sender and the resident-seed meter it shares with the worker's+/// [`SeedReceiver`].+#[derive(Clone)]+struct SeedLane {+ /// One item per seed: the channel's capacity is the seed intake cap. The meter admits and+ /// refuses nothing.+ sender: mpsc::Sender<ConsumedSeed>,+ meter: Arc<SeedLaneMeter>,+}++/// Seeds resident in one partition's seed lane, for [`PARTITION_SEED_CHANNEL_DEPTH`] only: the+/// channel's capacity is the cap, so this count gates nothing. The router adds what it lands, the+/// worker releases a quantum once its last run has applied, and dropping the [`SeedReceiver`]+/// zeroes the series. A gauge read off the sender's free capacity instead would miss the quantum+/// in hand (`recv_many` frees the slots it takes) and pin its last value after a drain or a+/// revoke.+pub(crate) struct SeedLaneMeter {+ resident: AtomicUsize,+ label: Arc<str>,+}++impl SeedLaneMeter {+ fn new(partition: i32) -> Self {+ Self {+ resident: AtomicUsize::new(0),+ label: Arc::from(partition.to_string()),+ }+ }++ fn add(&self, count: usize) {+ self.resident.fetch_add(count, Ordering::AcqRel);+ // Sample fresh: a concurrent release may have lowered the count below the sum.+ self.set_gauge(self.resident.load(Ordering::Acquire));+ }++ /// Saturating, so an accounting slip can never wrap the gauge.+ fn release(&self, count: usize) {+ let mut current = self.resident.load(Ordering::Acquire);+ loop {+ let next = current.saturating_sub(count);+ match self.resident.compare_exchange_weak(+ current,+ next,+ Ordering::AcqRel,+ Ordering::Acquire,+ ) {+ Ok(_) => {+ self.set_gauge(next);+ return;+ }+ Err(observed) => current = observed,+ }+ }+ }++ fn zero(&self) {+ self.resident.store(0, Ordering::Release);+ self.set_gauge(0);+ }++ #[cfg(test)]+ fn resident(&self) -> usize {+ self.resident.load(Ordering::Acquire)+ }++ fn set_gauge(&self, value: usize) {+ gauge!(PARTITION_SEED_CHANNEL_DEPTH, "partition" => self.label.clone()).set(value as f64);+ }+}++/// A registered worker's two lanes: the live sender with the event-intake budget its+/// [`MeteredReceiver`] releases against, and the seed sender. One struct, so a revoke drops both+/// senders together. Cloning shares everything, so a lookup can drop the shard guard before use.#[derive(Clone)]struct PartitionChannel {- sender: mpsc::Sender<Vec<ShuffleMessage>>,+ live: mpsc::Sender<Vec<ShuffleMessage>>,intake: Arc<PartitionIntake>,+ seeds: SeedLane,+}++/// What [`add_partition`](PartitionRouter::add_partition) hands a worker: the live lane behind its+/// intake meter, and the seed lane behind its depth meter.+pub struct WorkerInbox {+ pub live: MeteredReceiver,+ pub seeds: SeedReceiver,+}++impl WorkerInbox {+ /// Uncapped live lane and an already-closed seed lane, for tests that route no seeds.+ pub fn live_only(live: mpsc::Receiver<Vec<ShuffleMessage>>) -> Self {+ let (_, seeds) = mpsc::channel(1);+ Self::unmetered(live, seeds)+ }++ /// Uncapped live lane paired with a caller-owned seed lane, for tests that drive both.+ pub fn unmetered(+ live: mpsc::Receiver<Vec<ShuffleMessage>>,+ seeds: mpsc::Receiver<ConsumedSeed>,+ ) -> Self {+ Self {+ live: MeteredReceiver::unmetered(live),+ seeds: SeedReceiver::unmetered(seeds),+ }+ }+}++/// Worker-side end of the seed lane. Seeds taken by [`recv_many`](Self::recv_many) stay counted on+/// the meter until [`finish_turn`](Self::finish_turn), so the depth gauge covers the quantum being+/// applied; dropping it zeroes the gauge, so a revoked partition's series does not pin.+pub struct SeedReceiver {+ receiver: mpsc::Receiver<ConsumedSeed>,+ meter: Arc<SeedLaneMeter>,+ /// Seeds taken since the last `finish_turn`.+ in_hand: usize,+}++impl SeedReceiver {+ fn new(receiver: mpsc::Receiver<ConsumedSeed>, meter: Arc<SeedLaneMeter>) -> Self {+ Self {+ receiver,+ meter,+ in_hand: 0,+ }+ }++ /// A lane whose sends bypass the meter, for tests that own the sender.+ pub fn unmetered(receiver: mpsc::Receiver<ConsumedSeed>) -> Self {+ Self::new(receiver, Arc::new(SeedLaneMeter::new(0)))+ }++ /// Take up to `limit` seeds, waiting for the first; `0` means the lane closed. Cancel-safe, so+ /// the worker can poll it as a `select!` branch: the count moves only on completion.+ pub async fn recv_many(&mut self, buffer: &mut Vec<ConsumedSeed>, limit: usize) -> usize {+ let taken = self.receiver.recv_many(buffer, limit).await;+ self.in_hand += taken;+ taken+ }++ /// Release everything taken since the last call. The worker calls it once every run of the+ /// quantum has applied.+ pub fn finish_turn(&mut self) {+ let taken = std::mem::take(&mut self.in_hand);+ if taken > 0 {+ self.meter.release(taken);+ }+ }++ /// Non-awaiting single take for tests; counts on the meter like [`recv_many`](Self::recv_many).+ #[cfg(test)]+ pub fn try_recv(&mut self) -> Result<ConsumedSeed, mpsc::error::TryRecvError> {+ let seed = self.receiver.try_recv()?;+ self.in_hand += 1;+ Ok(seed)+ }}-/// Routes per-partition sub-batches to long-lived per-partition worker channels.+impl Drop for SeedReceiver {+ fn drop(&mut self) {+ self.meter.zero();+ }+}++/// Routes per-partition sub-batches to long-lived per-partition worker lanes.pub struct PartitionRouter {channels: DashMap<i32, PartitionChannel>,channel_buffer: usize,/// Per-partition ceiling on un-drained events; `usize::MAX` disables it (only the mpsc slots bound).intake_cap: usize,+ /// The seed lane's capacity, in seeds. `NonZeroUsize` because tokio panics on a zero-capacity+ /// channel, so the type carries what a worker spawn depends on.+ seed_cap: NonZeroUsize,/// Terminal: set by [`clear`](Self::clear), never unset. Read under the shard guard so no/// channel can be registered after the clear's removal pass.closed: AtomicBool,}impl PartitionRouter {- /// Router with the event-intake budget disabled — only the mpsc slots bound. Tests only:- /// production must use [`with_intake_cap`](Self::with_intake_cap) so intake is always bounded.+ /// Router with the event-intake budget disabled — only the mpsc slots bound — and a default+ /// seed cap. Tests only: production must use [`with_intake_cap`](Self::with_intake_cap) so both+ /// lanes are always bounded.pub fn new(channel_buffer: usize) -> Self {- Self::with_intake_cap(channel_buffer, usize::MAX)+ Self::with_intake_cap(channel_buffer, usize::MAX, DEFAULT_SEED_CAP)}- pub fn with_intake_cap(channel_buffer: usize, intake_cap: usize) -> Self {+ pub fn with_intake_cap(+ channel_buffer: usize,+ intake_cap: usize,+ seed_cap: NonZeroUsize,+ ) -> Self {Self {channels: DashMap::new(),channel_buffer,intake_cap,+ seed_cap,closed: AtomicBool::new(false),}}- /// Register a worker channel for `partition` and return its [`MeteredReceiver`].+ /// Register both lanes for `partition` and return the worker's [`WorkerInbox`].////// Returns `None` if: already registered with a live channel (reuses existing), or the router- /// is closed. If the existing channel is dead (receiver dropped), replaces it (self-heal) with a- /// fresh intake, discarding any stale counter from the prior incarnation.- pub fn add_partition(&self, partition: i32) -> Option<MeteredReceiver> {+ /// is closed. A half-dead channel — either lane's receiver dropped — is replaced (self-heal)+ /// with a fresh pair and a fresh intake, discarding any stale counter from the prior+ /// incarnation.+ pub fn add_partition(&self, partition: i32) -> Option<WorkerInbox> {let entry = self.channels.entry(partition);if self.closed.load(Ordering::SeqCst) {drop(entry);@@ -112,16 +314,17 @@ impl PartitionRouter {);return None;}- let receiver = match entry {+ let inbox = match entry {Entry::Occupied(mut slot) => {- if slot.get().sender.is_closed() {- let (channel, receiver) = self.make_channel(partition);+ let dead = slot.get().live.is_closed() || slot.get().seeds.sender.is_closed();+ if dead {+ let (channel, inbox) = self.make_channel(partition);slot.insert(channel);warn!(partition,"replacing closed worker channel on reassign (previous worker exited without revoke)");- Some(receiver)+ Some(inbox)} else {warn!(partition,@@ -131,22 +334,38 @@ impl PartitionRouter {}}Entry::Vacant(slot) => {- let (channel, receiver) = self.make_channel(partition);+ let (channel, inbox) = self.make_channel(partition);slot.insert(channel);- Some(receiver)+ Some(inbox)}};- if receiver.is_some() {+ if inbox.is_some() {self.emit_active_gauge();}- receiver+ inbox}- fn make_channel(&self, partition: i32) -> (PartitionChannel, MeteredReceiver) {- let (sender, receiver) = mpsc::channel(self.channel_buffer);+ fn make_channel(&self, partition: i32) -> (PartitionChannel, WorkerInbox) {+ let (live_tx, live_rx) = mpsc::channel(self.channel_buffer);+ let (seed_tx, seed_rx) = mpsc::channel(self.seed_cap.get());let intake = Arc::new(PartitionIntake::new(partition, self.intake_cap));- let metered = MeteredReceiver::new(receiver, intake.clone());- (PartitionChannel { sender, intake }, metered)+ let meter = Arc::new(SeedLaneMeter::new(partition));+ let live = MeteredReceiver::new(live_rx, intake.clone());+ let channel = PartitionChannel {+ live: live_tx,+ intake,+ seeds: SeedLane {+ sender: seed_tx,+ meter: meter.clone(),+ },+ };+ (+ channel,+ WorkerInbox {+ live,+ seeds: SeedReceiver::new(seed_rx, meter),+ },+ )}/// Drop the sender for `partition`, signalling the worker to shut down. Idempotent.@@ -203,9 +422,9 @@ impl PartitionRouter {};// Uncapped: control messages carry no events, so they must always flow.- match channel.sender.send(batch).await {+ match channel.live.send(batch).await {Ok(()) => {- self.emit_channel_depth(partition, &channel.sender);+ self.emit_channel_depth(partition, &channel.live);None}Err(mpsc::error::SendError(returned)) => {@@ -254,9 +473,9 @@ impl PartitionRouter {.increment(batch.len() as u64);return SendOutcome::Full(batch);}- match channel.sender.try_send(batch) {+ match channel.live.try_send(batch) {Ok(()) => {- self.emit_channel_depth(partition, &channel.sender);+ self.emit_channel_depth(partition, &channel.live);SendOutcome::Sent { max_offset, count }}Err(TrySendError::Full(returned)) => {@@ -273,6 +492,77 @@ impl PartitionRouter {}}+ /// Group `seeds` by partition, preserving offset order, and `try_send` each sub-batch onto its+ /// worker's seed lane. Never touches the live lane or its intake budget.+ pub fn try_route_seeds(&self, seeds: Vec<ConsumedSeed>) -> HashMap<i32, SeedSendOutcome> {+ if seeds.is_empty() {+ return HashMap::new();+ }+ let mut by_partition: HashMap<i32, Vec<ConsumedSeed>> = HashMap::new();+ for seed in seeds {+ by_partition.entry(seed.partition).or_default().push(seed);+ }+ by_partition+ .into_iter()+ .map(|(partition, batch)| (partition, self.try_send_seeds(partition, batch)))+ .collect()+ }++ /// Send one partition's seeds, in order, until one is refused. `seeds` is non-empty: it comes+ /// from the grouping in [`try_route_seeds`](Self::try_route_seeds).+ fn try_send_seeds(&self, partition: i32, seeds: Vec<ConsumedSeed>) -> SeedSendOutcome {+ let Some(channel) = self.channel_for(partition) else {+ return SeedSendOutcome::Refused {+ landed_max: None,+ reason: SeedRefusal::NoWorker,+ rest: seeds,+ };+ };+ let lane = &channel.seeds;++ let mut landed_max: Option<i64> = None;+ let mut landed = 0usize;+ let mut remaining = seeds.into_iter();+ let mut refused = None;+ for seed in remaining.by_ref() {+ let offset = seed.offset;+ match lane.sender.try_send(seed) {+ Ok(()) => {+ landed += 1;+ landed_max = Some(landed_max.map_or(offset, |max| max.max(offset)));+ }+ Err(TrySendError::Full(seed)) => {+ refused = Some((SeedRefusal::Full, seed));+ break;+ }+ Err(TrySendError::Closed(seed)) => {+ refused = Some((SeedRefusal::ChannelClosed, seed));+ break;+ }+ }+ }+ // Once per sub-batch, never per seed: one gauge write covers everything that landed.+ lane.meter.add(landed);++ let Some((reason, seed)) = refused else {+ return SeedSendOutcome::Sent {+ max_offset: landed_max.expect("a grouped sub-batch is never empty"),+ };+ };+ // The refused seed and everything behind it go back untried, so the ceiling never rises+ // past a hole and per-partition FIFO holds.+ let rest: Vec<ConsumedSeed> = std::iter::once(seed).chain(remaining).collect();+ if reason == SeedRefusal::Full {+ counter!(PARTITION_SEED_CHANNEL_FULL_TOTAL, "partition" => lane.meter.label.clone())+ .increment(rest.len() as u64);+ }+ SeedSendOutcome::Refused {+ landed_max,+ reason,+ rest,+ }+ }+pub fn partition_count(&self) -> usize {self.channels.len()}@@ -301,6 +591,8 @@ impl PartitionRouter {counter!(PARTITION_ROUTE_DROPPED_TOTAL, "reason" => reason).increment(dropped as u64);}+ /// The live lane's depth. The seed lane's is kept by its [`SeedLaneMeter`], which both ends+ /// update.fn emit_channel_depth(&self, partition: i32, sender: &mpsc::Sender<Vec<ShuffleMessage>>) {let depth = sender.max_capacity().saturating_sub(sender.capacity());gauge!(PARTITION_CHANNEL_DEPTH, "partition" => partition.to_string()).set(depth as f64);@@ -350,8 +642,7 @@ mod tests {| ShuffleMessage::Cascade { .. }| ShuffleMessage::RedrivePendingTransfers| ShuffleMessage::MergeCfGc { .. }- | ShuffleMessage::ReconcileDrain- | ShuffleMessage::Seed { .. } => {+ | ShuffleMessage::ReconcileDrain => {unreachable!("router tests route only events")}})@@ -373,11 +664,11 @@ mod tests {.await;assert!(errors.is_empty(), "no worker should be missing");- assert_eq!(tags(&rx5.recv().await.unwrap()), vec![1, 3]);- assert_eq!(tags(&rx6.recv().await.unwrap()), vec![2]);+ assert_eq!(tags(&rx5.live.recv().await.unwrap()), vec![1, 3]);+ assert_eq!(tags(&rx6.live.recv().await.unwrap()), vec![2]);assert!(router.route_batch(vec![(5, event(4))]).await.is_empty());- assert_eq!(tags(&rx5.recv().await.unwrap()), vec![4]);+ assert_eq!(tags(&rx5.live.recv().await.unwrap()), vec![4]);}#[tokio::test]@@ -408,7 +699,7 @@ mod tests {.add_partition(5).expect("re-add after removal yields a fresh receiver");assert!(router.route_batch(vec![(5, event(9))]).await.is_empty());- assert_eq!(tags(&rx_new.recv().await.unwrap()), vec![9]);+ assert_eq!(tags(&rx_new.live.recv().await.unwrap()), vec![9]);}#[tokio::test]@@ -420,7 +711,7 @@ mod tests {assert_eq!(router.partition_count(), 1);assert!(router.route_batch(vec![(5, event(1))]).await.is_empty());- assert_eq!(tags(&rx.recv().await.unwrap()), vec![1]);+ assert_eq!(tags(&rx.live.recv().await.unwrap()), vec![1]);}#[tokio::test]@@ -455,7 +746,7 @@ mod tests {dropped: 1}]);- assert_eq!(tags(&rx5.recv().await.unwrap()), vec![1, 3]);+ assert_eq!(tags(&rx5.live.recv().await.unwrap()), vec![1, 3]);}#[tokio::test]@@ -480,10 +771,10 @@ mod tests {"route_batch must stay pending while partition 1 is backpressured");- assert_eq!(tags(&rx2.try_recv().unwrap()), vec![2]);+ assert_eq!(tags(&rx2.live.try_recv().unwrap()), vec![2]);- assert_eq!(tags(&rx1.try_recv().unwrap()), vec![100]);- assert!(rx1.try_recv().is_err());+ assert_eq!(tags(&rx1.live.try_recv().unwrap()), vec![100]);+ assert!(rx1.live.try_recv().is_err());}#[tokio::test]@@ -493,7 +784,10 @@ mod tests {router.clear();assert!(router.is_closed());- assert!(rx.recv().await.is_none(), "clear dropped the live sender");+ assert!(+ rx.live.recv().await.is_none(),+ "clear dropped the live sender"+ );assert!(router.add_partition(5).is_none(),@@ -527,7 +821,7 @@ mod tests {assert_eq!(router.partition_count(), 1);assert!(router.route_batch(vec![(5, event(7))]).await.is_empty());- assert_eq!(tags(&rx_new.recv().await.unwrap()), vec![7]);+ assert_eq!(tags(&rx_new.live.recv().await.unwrap()), vec![7]);}/// An event whose `cse_offset` matches its `source_offset` tag, so [`tags`] and `max_offset`@@ -567,8 +861,8 @@ mod tests {}other => panic!("expected Sent for 6, got {other:?}"),}- assert_eq!(tags(&rx5.try_recv().unwrap()), vec![1, 3]);- assert_eq!(tags(&rx6.try_recv().unwrap()), vec![2]);+ assert_eq!(tags(&rx5.live.try_recv().unwrap()), vec![1, 3]);+ assert_eq!(tags(&rx6.live.try_recv().unwrap()), vec![2]);}#[tokio::test]@@ -586,8 +880,8 @@ mod tests {Some(SendOutcome::Full(returned)) => assert_eq!(tags(&returned), vec![7]),other => panic!("expected Full, got {other:?}"),}- assert_eq!(tags(&rx.try_recv().unwrap()), vec![100]);- assert!(rx.try_recv().is_err());+ assert_eq!(tags(&rx.live.try_recv().unwrap()), vec![100]);+ assert!(rx.live.try_recv().is_err());}#[tokio::test]@@ -619,7 +913,7 @@ mod tests {outcomes.remove(&2),Some(SendOutcome::Sent { .. })));- assert_eq!(tags(&rx2.try_recv().unwrap()), vec![2]);+ assert_eq!(tags(&rx2.live.try_recv().unwrap()), vec![2]);}#[tokio::test]@@ -655,7 +949,7 @@ mod tests {#[tokio::test]async fn the_event_cap_trips_full_before_the_mpsc_slots_fill() {// Two-event ceiling, 16 free slots: the intake refuses the third event with room to spare.- let router = PartitionRouter::with_intake_cap(16, 2);+ let router = PartitionRouter::with_intake_cap(16, 2, DEFAULT_SEED_CAP);let mut rx = router.add_partition(5).unwrap();match router@@ -671,9 +965,9 @@ mod tests {}// The budget frees on the *next* recv (it covers the in-hand batch), so step past the drain.- assert_eq!(tags(&rx.recv().await.unwrap()), vec![1, 2]);+ assert_eq!(tags(&rx.live.recv().await.unwrap()), vec![1, 2]);assert!(- rx.try_recv().is_err(),+ rx.live.try_recv().is_err(),"channel now empty; this recv released the drained batch",);assert!(matches!(@@ -684,7 +978,7 @@ mod tests {#[tokio::test]async fn maintenance_sends_bypass_the_event_cap() {- let router = PartitionRouter::with_intake_cap(16, 1);+ let router = PartitionRouter::with_intake_cap(16, 1, DEFAULT_SEED_CAP);let mut rx = router.add_partition(5).unwrap();assert!(matches!(@@ -705,16 +999,284 @@ mod tests {"the maintenance tick flows past a full event budget",);- assert_eq!(tags(&rx.recv().await.unwrap()), vec![1]);+ assert_eq!(tags(&rx.live.recv().await.unwrap()), vec![1]);assert!(- matches!(rx.recv().await, Some(batch) if matches!(batch.as_slice(), [ShuffleMessage::Sweep { .. }])),+ matches!(rx.live.recv().await, Some(batch) if matches!(batch.as_slice(), [ShuffleMessage::Sweep { .. }])),"the sweep was delivered despite the full event budget",);}+ fn consumed_seed(partition: i32, offset: i64) -> ConsumedSeed {+ use cohort_core::seed::{ClaimEpoch, ConditionHash, RunId, SChunkMs, SeedTile};++ crate::consumers::seeds::ConsumedSeed {+ work: crate::consumers::seeds::SeedWork::Tile(SeedTile::new(+ crate::filters::TeamId(1),+ uuid::Uuid::from_u128(offset as u128 + 1),+ ConditionHash::parse("0123456789abcdef").unwrap(),+ std::num::NonZeroU32::new(1).unwrap(),+ 20_614,+ SChunkMs(1_700_000_000_000),+ RunId(uuid::Uuid::nil()),+ ClaimEpoch(1),+ )),+ partition,+ offset,+ broker_ts_ms: None,+ }+ }++ fn seed_offsets(seeds: &[ConsumedSeed]) -> Vec<i64> {+ seeds.iter().map(|seed| seed.offset).collect()+ }++ fn drain_seeds(receiver: &mut SeedReceiver) -> Vec<i64> {+ let mut taken = Vec::new();+ while let Ok(seed) = receiver.try_recv() {+ taken.push(seed.offset);+ }+ taken+ }++ fn cap(value: usize) -> NonZeroUsize {+ NonZeroUsize::new(value).expect("a test capacity is non-zero")+ }++ #[tokio::test]+ async fn seed_lane_capacity_is_independent_of_the_live_intake() {+ // One event of live budget and one slot of seed lane: saturating either must leave the+ // other free, or the two lanes are sharing a budget again.+ let router = PartitionRouter::with_intake_cap(16, 1, cap(1));+ let mut inbox = router.add_partition(5).unwrap();++ assert!(matches!(+ router.try_route_batch(vec![(5, event_off(1))]).remove(&5),+ Some(SendOutcome::Sent { .. }),+ ));+ assert!(+ matches!(+ router+ .try_route_seeds(vec![consumed_seed(5, 10)])+ .remove(&5),+ Some(SeedSendOutcome::Sent { max_offset: 10 }),+ ),+ "a saturated live intake must not refuse a seed",+ );++ // Both lanes are now full. Free only the seed lane, and the live lane stays refused.+ assert_eq!(drain_seeds(&mut inbox.seeds), vec![10]);+ assert!(+ matches!(+ router.try_route_batch(vec![(5, event_off(2))]).remove(&5),+ Some(SendOutcome::Full(_)),+ ),+ "draining the seed lane must not free live intake",+ );++ // Free only the live lane; the seed lane still has its slot.+ assert_eq!(tags(&inbox.live.recv().await.unwrap()), vec![1]);+ assert!(inbox.live.try_recv().is_err(), "that recv released event 1");+ assert!(matches!(+ router+ .try_route_seeds(vec![consumed_seed(5, 11)])+ .remove(&5),+ Some(SeedSendOutcome::Sent { max_offset: 11 }),+ ));+ }++ #[tokio::test]+ async fn seed_routing_preserves_order_and_ceiling_per_partition() {+ let router = PartitionRouter::with_intake_cap(16, usize::MAX, cap(8));+ let mut five = router.add_partition(5).unwrap();+ let mut six = router.add_partition(6).unwrap();++ let mut outcomes = router.try_route_seeds(vec![+ consumed_seed(5, 1),+ consumed_seed(6, 2),+ consumed_seed(5, 3),+ ]);++ assert!(matches!(+ outcomes.remove(&5),+ Some(SeedSendOutcome::Sent { max_offset: 3 })+ ));+ assert!(matches!(+ outcomes.remove(&6),+ Some(SeedSendOutcome::Sent { max_offset: 2 })+ ));+ assert!(outcomes.is_empty());+ assert_eq!(drain_seeds(&mut five.seeds), vec![1, 3]);+ assert_eq!(drain_seeds(&mut six.seeds), vec![2]);+ }++ /// A refusal is only reachable here with the lane already full, so the stop-at-first-refusal+ /// loop itself cannot be staged — that needs a concurrent drain between two `try_send`s. What+ /// is observable is its consequence, and the one that matters: the reported ceiling follows+ /// what landed, never the batch maximum, and the suffix comes back whole and in order.+ #[tokio::test]+ async fn a_seed_sub_batch_lands_as_a_prefix_and_the_ceiling_follows_only_what_landed() {+ let router = PartitionRouter::with_intake_cap(16, usize::MAX, cap(2));+ let mut inbox = router.add_partition(5).unwrap();++ let five = vec![+ consumed_seed(5, 1),+ consumed_seed(5, 2),+ consumed_seed(5, 3),+ consumed_seed(5, 4),+ consumed_seed(5, 5),+ ];+ let suffix = match router.try_route_seeds(five).remove(&5) {+ Some(SeedSendOutcome::Refused {+ landed_max,+ reason,+ rest,+ }) => {+ assert_eq!(landed_max, Some(2), "only the first two fit the lane");+ assert_eq!(reason, SeedRefusal::Full);+ assert_eq!(+ seed_offsets(&rest),+ vec![3, 4, 5],+ "the suffix from the first refusal on, in order and untried",+ );+ rest+ }+ other => panic!("expected a prefix landing, got {other:?}"),+ };++ // Free exactly one slot: only the head of the suffix may land, and 4 and 5 stay behind it.+ let head = inbox.seeds.try_recv().expect("the lane holds two").offset;+ assert_eq!(head, 1);+ match router.try_route_seeds(suffix).remove(&5) {+ Some(SeedSendOutcome::Refused {+ landed_max,+ reason,+ rest,+ }) => {+ assert_eq!(landed_max, Some(3));+ assert_eq!(reason, SeedRefusal::Full);+ assert_eq!(seed_offsets(&rest), vec![4, 5]);+ }+ other => panic!("expected the third to land alone, got {other:?}"),+ }+ assert_eq!(drain_seeds(&mut inbox.seeds), vec![2, 3]);+ }++ #[tokio::test]+ async fn remove_partition_closes_both_lanes() {+ let router = PartitionRouter::new(16);+ let mut inbox = router.add_partition(5).unwrap();++ router.remove_partition(5);++ // `try_recv` rather than `recv`: a lane that outlived the revoke must fail this test, not+ // hang it (and it would hang the worker loop the same way).+ assert!(+ matches!(+ inbox.live.try_recv(),+ Err(mpsc::error::TryRecvError::Disconnected)+ ),+ "the live lane closed",+ );+ assert!(+ matches!(+ inbox.seeds.try_recv(),+ Err(mpsc::error::TryRecvError::Disconnected)+ ),+ "the seed lane closed with the same revoke",+ );+ }++ #[tokio::test]+ async fn try_route_seeds_reports_no_worker_and_channel_closed() {+ let router = PartitionRouter::new(16);+ match router.try_route_seeds(vec![consumed_seed(9, 1)]).remove(&9) {+ Some(SeedSendOutcome::Refused {+ landed_max,+ reason,+ rest,+ }) => {+ assert_eq!((landed_max, reason), (None, SeedRefusal::NoWorker));+ assert_eq!(seed_offsets(&rest), vec![1]);+ }+ other => panic!("expected NoWorker, got {other:?}"),+ }++ let inbox = router.add_partition(3).unwrap();+ drop(inbox);+ match router.try_route_seeds(vec![consumed_seed(3, 1)]).remove(&3) {+ Some(SeedSendOutcome::Refused {+ landed_max,+ reason,+ rest,+ }) => {+ assert_eq!((landed_max, reason), (None, SeedRefusal::ChannelClosed));+ assert_eq!(seed_offsets(&rest), vec![1]);+ }+ other => panic!("expected ChannelClosed, got {other:?}"),+ }+ }++ #[tokio::test]+ async fn try_route_seeds_is_empty_for_an_empty_batch() {+ let router = PartitionRouter::new(16);+ assert!(router.try_route_seeds(vec![]).is_empty());+ }++ /// The depth gauge must cover the queued seeds and the quantum in hand, and must not pin after+ /// the lane drains or the partition is revoked.+ #[tokio::test]+ async fn the_seed_lane_meter_counts_the_quantum_in_hand_and_zeroes_on_drop() {+ let router = PartitionRouter::with_intake_cap(16, usize::MAX, cap(2));+ let mut inbox = router.add_partition(5).unwrap();+ let meter = router+ .channels+ .get(&5)+ .expect("partition 5 is registered")+ .seeds+ .meter+ .clone();++ // Three seeds onto a two-slot lane: only what landed counts, never the refused suffix.+ assert!(matches!(+ router+ .try_route_seeds(vec![+ consumed_seed(5, 1),+ consumed_seed(5, 2),+ consumed_seed(5, 3)+ ])+ .remove(&5),+ Some(SeedSendOutcome::Refused {+ landed_max: Some(2),+ ..+ }),+ ));+ assert_eq!(meter.resident(), 2);++ // Taking the quantum frees the lane's slots but not the meter: the seeds are in hand.+ let mut quantum = Vec::new();+ assert_eq!(+ futures::FutureExt::now_or_never(inbox.seeds.recv_many(&mut quantum, 8)),+ Some(2)+ );+ assert_eq!(meter.resident(), 2, "the quantum in hand still counts");+ assert!(matches!(+ router.try_route_seeds(vec![consumed_seed(5, 3)]).remove(&5),+ Some(SeedSendOutcome::Sent { max_offset: 3 }),+ ));+ assert_eq!(meter.resident(), 3, "queued plus in hand");++ inbox.seeds.finish_turn();+ assert_eq!(meter.resident(), 1, "only the queued seed stays counted");++ // A revoke drops the worker's end with whatever it still held, and the series clears.+ router.remove_partition(5);+ drop(inbox);+ assert_eq!(meter.resident(), 0);+ }+#[tokio::test]async fn an_idle_partition_admits_an_over_cap_batch() {- let router = PartitionRouter::with_intake_cap(16, 2);+ let router = PartitionRouter::with_intake_cap(16, 2, DEFAULT_SEED_CAP);let mut rx = router.add_partition(5).unwrap();match router@@ -728,6 +1290,6 @@ mod tests {Some(SendOutcome::Sent { count, .. }) => assert_eq!(count, 3),other => panic!("an idle partition must admit an over-cap batch, got {other:?}"),}- assert_eq!(tags(&rx.recv().await.unwrap()), vec![1, 2, 3]);+ assert_eq!(tags(&rx.live.recv().await.unwrap()), vec![1, 2, 3]);}}diff --git a/rust/cohort-stream-processor/src/partitions/shuffle_message.rs b/rust/cohort-stream-processor/src/partitions/shuffle_message.rsindex a3417e212f32..17162e1095cd 100644--- a/rust/cohort-stream-processor/src/partitions/shuffle_message.rs+++ b/rust/cohort-stream-processor/src/partitions/shuffle_message.rs@@ -2,7 +2,6 @@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.@@ -53,21 +52,10 @@ pub enum ShuffleMessage {},/// Periodic bounded-progress tick for the partition's reconcile queue.ReconcileDrain,- /// 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,- /// Broker timestamp of the consumed seed message — the oldest-held age gauge's input.- /// Rides the round trip so a channel-full bounce keeps it; `None` reads as age 0.- broker_ts_ms: Option<i64>,- },}impl ShuffleMessage {- /// The offset an [`Event`](Self::Event) carries; `None` for every other variant, including- /// [`Seed`](Self::Seed) (its offset belongs to the seed tracker).+ /// The offset an [`Event`](Self::Event) carries; `None` for every other variant.pub fn event_offset(&self) -> Option<i64> {match self {ShuffleMessage::Event { cse_offset, .. } => Some(*cse_offset),@@ -77,31 +65,16 @@ impl ShuffleMessage {| ShuffleMessage::Cascade { .. }| ShuffleMessage::RedrivePendingTransfers| ShuffleMessage::MergeCfGc { .. }- | ShuffleMessage::ReconcileDrain- | 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 { .. }| ShuffleMessage::ReconcileDrain => None,}}- /// Whether this message reserves an intake-budget slot; maintenance/control messages must- /// always flow.+ /// Whether this message reserves a live-intake budget slot; maintenance/control messages must+ /// always flow. Only an [`Event`](Self::Event) counts — seeds ride their own lane, whose+ /// capacity is their cap.pub fn counts_toward_intake(&self) -> bool {match self {- ShuffleMessage::Event { .. } | ShuffleMessage::Seed { .. } => true,+ ShuffleMessage::Event { .. } => true,ShuffleMessage::Sweep { .. }| ShuffleMessage::Merge { .. }| ShuffleMessage::Transfer { .. }@@ -189,6 +162,11 @@ mod tests {cse_offset: 7,broker_ts_ms: Some(1_700_000_000_000),};+ assert_eq!(message.event_offset(), Some(7));+ assert!(message.counts_toward_intake());+ assert!(!ShuffleMessage::RedrivePendingTransfers.counts_toward_intake());+ assert!(!ShuffleMessage::ReconcileDrain.counts_toward_intake());+ assert_eq!(ShuffleMessage::ReconcileDrain.event_offset(), None);// No wildcard, so a new variant forces this test to be revisited.match message {@@ -208,57 +186,10 @@ mod tests {| ShuffleMessage::RedrivePendingTransfers| ShuffleMessage::MergeCfGc { .. }| ShuffleMessage::ReconcileDrain- | 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,- broker_ts_ms: Some(1_700_000_000_000),- };-- 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());- assert!(!ShuffleMessage::ReconcileDrain.counts_toward_intake());- assert_eq!(ShuffleMessage::ReconcileDrain.event_offset(), None);- assert_eq!(ShuffleMessage::ReconcileDrain.seed_offset(), None);- }-#[test]fn sweep_variant_carries_the_due_before_cutoff() {let message = ShuffleMessage::Sweep {@@ -272,7 +203,6 @@ mod tests {| ShuffleMessage::RedrivePendingTransfers| ShuffleMessage::MergeCfGc { .. }| ShuffleMessage::ReconcileDrain- | ShuffleMessage::Seed { .. }| ShuffleMessage::Cascade { .. } => unreachable!("constructed a Sweep"),}}@@ -297,7 +227,6 @@ mod tests {| ShuffleMessage::Transfer { .. }| ShuffleMessage::RedrivePendingTransfers| ShuffleMessage::ReconcileDrain- | ShuffleMessage::Seed { .. }| ShuffleMessage::Cascade { .. } => unreachable!("constructed a MergeCfGc"),}}@@ -319,7 +248,6 @@ mod tests {| ShuffleMessage::RedrivePendingTransfers| ShuffleMessage::MergeCfGc { .. }| ShuffleMessage::ReconcileDrain- | ShuffleMessage::Seed { .. }| ShuffleMessage::Cascade { .. } => unreachable!("constructed a Merge"),}@@ -338,7 +266,6 @@ mod tests {| ShuffleMessage::RedrivePendingTransfers| ShuffleMessage::MergeCfGc { .. }| ShuffleMessage::ReconcileDrain- | ShuffleMessage::Seed { .. }| ShuffleMessage::Cascade { .. } => unreachable!("constructed a Transfer"),}}@@ -362,8 +289,7 @@ mod tests {| ShuffleMessage::Transfer { .. }| ShuffleMessage::RedrivePendingTransfers| ShuffleMessage::MergeCfGc { .. }- | ShuffleMessage::ReconcileDrain- | ShuffleMessage::Seed { .. } => unreachable!("constructed a Cascade"),+ | ShuffleMessage::ReconcileDrain => unreachable!("constructed a Cascade"),}}}diff --git a/rust/cohort-stream-processor/src/workers/seed_apply.rs b/rust/cohort-stream-processor/src/workers/seed_apply.rsindex 9e6efeda775d..b2fe899bff73 100644--- a/rust/cohort-stream-processor/src/workers/seed_apply.rs+++ b/rust/cohort-stream-processor/src/workers/seed_apply.rs@@ -162,7 +162,7 @@ impl SeedHold {}/// What every stage borrows. `Copy`, so a stage can hand it on without ceremony. `catalog` is one-/// snapshot per channel batch, where the per-seed apply loaded its own per seed.+/// snapshot per run, where the per-seed apply loaded its own per seed.#[derive(Clone, Copy)]pub(crate) struct ApplyDeps<'a> {pub partition_id: u16,@@ -1129,7 +1129,9 @@ fn settle(}}-/// Apply one channel batch's seed groups in order on the owning partition worker.+/// Apply one collection's seed groups in order, as one shot. The partition worker applies them one+/// per round instead, through [`apply_seed_group`], so live batches can interleave; this is the+/// test rig's form of the same sequence.////// A group that holds pins the commit floor at its own first offset; later groups still run, and/// the floor keeps the published mark from leapfrogging the hold — the same envelope as the@@ -1137,6 +1139,7 @@ fn settle(////// The mark itself is published once, after the last group, because groups' spans interleave (see/// [`BatchMarks`]).+#[cfg(test)]pub(crate) async fn handle_seed_groups(deps: ApplyDeps<'_>,queue: &mut EvictionQueue<BehavioralKey>,@@ -1146,32 +1149,43 @@ pub(crate) async fn handle_seed_groups() {let mut marks = BatchMarks::default();for group in groups {- match group {- SeedGroup::Tiles(run) => {- apply::<crate::workers::seed_path::TileHead>(deps, queue, clock, &mut marks, run)- .await;- }- SeedGroup::Persons(run) => {- apply::<crate::workers::person_seed_path::PersonHead>(- deps, queue, clock, &mut marks, run,- )+ apply_seed_group(deps, queue, reconcile_queue, clock, &mut marks, group).await;+ }+ marks.publish(&deps.merge.seed_tracker, deps.partition_id);+}++/// Apply one group of a collection: its mark lands in `marks`, a hold publishes at once. The+/// caller publishes `marks` only after the collection's last group (see [`BatchMarks`]), which is+/// what lets the partition worker apply the groups one per round with live batches in between.+pub(crate) async fn apply_seed_group(+ deps: ApplyDeps<'_>,+ queue: &mut EvictionQueue<BehavioralKey>,+ reconcile_queue: &mut ReconcileQueue,+ clock: &mut LastUpdatedClock,+ marks: &mut BatchMarks,+ group: SeedGroup,+) {+ match group {+ SeedGroup::Tiles(run) => {+ apply::<crate::workers::seed_path::TileHead>(deps, queue, clock, marks, run).await;+ }+ SeedGroup::Persons(run) => {+ apply::<crate::workers::person_seed_path::PersonHead>(deps, queue, clock, marks, run).await;- }- SeedGroup::Reconcile(Admitted { work, offset }) => admit_reconcile(- deps.partition_id,- deps.merge,- reconcile_queue,- &mut marks,- &work,- offset,- ),- SeedGroup::Skip(Admitted { work, offset }) => {- counter!(SEED_TILES_SKIPPED_TOTAL, "reason" => work.as_str()).increment(1);- marks.mark(offset);- }+ }+ SeedGroup::Reconcile(Admitted { work, offset }) => admit_reconcile(+ deps.partition_id,+ deps.merge,+ reconcile_queue,+ marks,+ &work,+ offset,+ ),+ SeedGroup::Skip(Admitted { work, offset }) => {+ counter!(SEED_TILES_SKIPPED_TOTAL, "reason" => work.as_str()).increment(1);+ marks.mark(offset);}}- marks.publish(&deps.merge.seed_tracker, deps.partition_id);}#[cfg(test)]diff --git a/rust/cohort-stream-processor/src/workers/seed_run.rs b/rust/cohort-stream-processor/src/workers/seed_run.rsindex b04e1ced2bd2..a062199d7bf8 100644--- a/rust/cohort-stream-processor/src/workers/seed_run.rs+++ b/rust/cohort-stream-processor/src/workers/seed_run.rs@@ -15,7 +15,7 @@ use std::num::NonZeroUsize;use cohort_core::seed::{ConditionHash, PersonSeed, ReconcileTile, SeedTile};use uuid::Uuid;-use crate::consumers::seeds::{SeedSkipReason, SeedWork};+use crate::consumers::seeds::{ConsumedSeed, SeedSkipReason, SeedWork};use crate::filters::reverse_index::TeamFilters;use crate::filters::{FilterCatalog, TeamId};use crate::stage1::key::LeafStateKey;@@ -43,6 +43,17 @@ pub(crate) struct Admitted<T> {pub offset: SeedOffset,}+impl From<ConsumedSeed> for Admitted<SeedWork> {+ /// Drops `partition` and `broker_ts_ms`: only the consumer's holdover reads those, and a seed+ /// that reached the worker has left the holdover behind.+ fn from(seed: ConsumedSeed) -> Self {+ Self {+ work: seed.work,+ offset: SeedOffset(seed.offset),+ }+ }+}+/// A non-empty run of one seed kind, applied as one unit. Construction is the only place emptiness/// is checked, so [`span`](Self::span) can never be asked about a run with no offsets.#[derive(Debug, Clone, PartialEq, Eq)]diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rsindex 3394dad2e862..fcefd0da1bed 100644--- a/rust/cohort-stream-processor/src/workers/worker.rs+++ b/rust/cohort-stream-processor/src/workers/worker.rs@@ -1,11 +1,15 @@//! Per-partition Stage 1 worker.//!-//! [`Stage1Worker::spawn`] drains one partition's channel on a dedicated tokio task. Per sub-batch-//! it produces membership changes and straggler re-keys, awaits all acks, then marks the offset-//! processed. A produce failure holds the offset; a store error is logged and the event is skipped.+//! [`Stage1Worker::spawn`] drains one partition's two lanes on a dedicated tokio task. Per live+//! sub-batch it produces membership changes and straggler re-keys, awaits all acks, then marks the+//! offset processed. A produce failure holds the offset; a store error is logged and the event is+//! skipped. Between live sub-batches it applies at most one seed run: a quantum of seeds leaves+//! the lane only once the previous quantum has fully applied, and its runs go one per round, so+//! live latency is at most one run and an admitted seed backlog never queues in front of live+//! traffic.use std::borrow::Cow;-use std::collections::BTreeMap;+use std::collections::{BTreeMap, VecDeque};use std::sync::Arc;use std::time::{Duration, Instant};@@ -16,7 +20,7 @@ use uuid::Uuid;use crate::cascade::{first_cascade, CascadeMessage};use crate::consumers::events::CohortStreamEvent;-use crate::consumers::seeds::SeedWork;+use crate::consumers::seeds::{ConsumedSeed, SeedWork};use crate::filters::manager::CatalogHandle;use crate::filters::reverse_index::TeamFilters;use crate::filters::TeamId;@@ -29,8 +33,8 @@ use crate::observability::metrics::{STAGE1_STATE_DECODE_ERROR, STAGE1_TRANSITIONS, SWEEP_KEYS_DROPPED_TOTAL,SWEEP_KEYS_EVICTED_TOTAL,};-use crate::partitions::intake::MeteredReceiver;use crate::partitions::offset_tracker::{MarkOutcome, OffsetTracker};+use crate::partitions::router::WorkerInbox;use crate::partitions::shuffle_message::ShuffleMessage;use crate::producer::{map_transition, CohortMembershipChange, LastUpdatedClock, MembershipSink, MembershipStatus,@@ -49,8 +53,8 @@ use crate::workers::event_path::{use crate::workers::merge_gc::{handle_merge_gc, MergeGcCursor};use crate::workers::merge_path::{handle_apply, handle_merge, handle_redrive, MergeWorkerDeps};use crate::workers::reconcile::{handle_reconcile_drain, ReconcileQueue};-use crate::workers::seed_apply::{handle_seed_groups, ApplyDeps};-use crate::workers::seed_run::{group_seeds, row_weight, Admitted, SeedOffset};+use crate::workers::seed_apply::{apply_seed_group, ApplyDeps, BatchMarks};+use crate::workers::seed_run::{group_seeds, row_weight, Admitted, SeedGroup};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};@@ -82,7 +86,7 @@ impl Stage1Worker {#[allow(clippy::too_many_arguments)]pub fn spawn(partition_id: u16,- receiver: MeteredReceiver,+ inbox: WorkerInbox,store: StoreHandle,catalog: Arc<CatalogHandle>,sink: Arc<dyn MembershipSink>,@@ -92,7 +96,7 @@ impl Stage1Worker {) -> Self {Self::spawn_with_gating(partition_id,- receiver,+ inbox,store,catalog,sink,@@ -108,7 +112,7 @@ impl Stage1Worker {#[allow(clippy::too_many_arguments)]pub fn spawn_with_gating(partition_id: u16,- receiver: MeteredReceiver,+ inbox: WorkerInbox,store: StoreHandle,catalog: Arc<CatalogHandle>,sink: Arc<dyn MembershipSink>,@@ -119,7 +123,7 @@ impl Stage1Worker {) -> Self {let handle = tokio::spawn(run_worker(partition_id,- receiver,+ inbox,store,catalog,sink,@@ -143,10 +147,28 @@ impl Stage1Worker {}}+/// What one [`run_worker`] select round yielded, so the loop body is a plain `match`.+enum Turn {+ /// A live sub-batch, or `None` for a closed live lane.+ Live(Option<Vec<ShuffleMessage>>),+ /// The pending quantum has a run to apply.+ Run,+ /// Seeds taken from the lane this round; `0` means the lane closed.+ Seeds(usize),+}++/// One quantum's runs, applied one per round so live batches interleave with them. The marks are+/// published only after the last run (see [`BatchMarks`]); a hold publishes as it happens.+#[derive(Default)]+struct PendingRuns {+ groups: VecDeque<SeedGroup>,+ marks: BatchMarks,+}+#[allow(clippy::too_many_arguments)]async fn run_worker(partition_id: u16,- mut receiver: MeteredReceiver,+ inbox: WorkerInbox,handle: StoreHandle,catalog: Arc<CatalogHandle>,sink: Arc<dyn MembershipSink>,@@ -174,7 +196,89 @@ async fn run_worker(// Persists across batches so a stream of buffered batches still yields on the wall-clock interval.let mut last_yield = Instant::now();let mut last_updated_clock = LastUpdatedClock::default();- while let Some(batch) = receiver.recv().await {+ // Two locals, not `inbox.live`/`inbox.seeds`: both branch futures live at once inside the+ // macro, so they must borrow disjoint places.+ let WorkerInbox {+ mut live,+ mut seeds,+ } = inbox;+ // The seed quantum, from the run ceiling: one turn takes at most one run's worth of seeds.+ // The row budget, a kind change or a control seed can still cut a quantum into several runs,+ // which then apply one per round. `NonZeroUsize` on purpose: `recv_many` with a limit of 0+ // returns 0 at once, which reads here as a closed lane.+ let quantum = merge.seed_budget.seeds.get();+ // Grown by `recv_many` as seeds arrive, not sized up front: the run ceiling is a config knob,+ // and an oversized one must not reserve that many seeds per worker at spawn.+ let mut seed_buf: Vec<ConsumedSeed> = Vec::new();+ let mut pending = PendingRuns::default();+ let (mut live_open, mut seed_open) = (true, true);+ loop {+ // Live first: a seed run is bounded work, a live backlog is not. A seed branch is reached+ // only while the live lane is empty, so live latency is at most one seed run.+ //+ // A partition whose live lane is never empty makes no seed progress, by design: live+ // arrivals there already outpace the worker, a seed run would only deepen that backlog,+ // and the seed consumer's live-lag gate stops admitting to it. Its lane then fills and+ // `try_route_seeds` refuses, which is the alarm: `cohort_seed_paused_partitions` under+ // cause `channel_full` and `cohort_seed_oldest_held_age_ms` rise while+ // `cohort_seed_apply_run_size` goes flat.+ let turn = tokio::select! {+ biased;+ batch = live.recv(), if live_open => Turn::Live(batch),+ // Ready at once: the quantum's remaining runs go one per round, behind any live batch.+ () = std::future::ready(()), if !pending.groups.is_empty() => Turn::Run,+ // The lane is polled again only once the previous quantum has fully applied.+ taken = seeds.recv_many(&mut seed_buf, quantum),+ if seed_open && pending.groups.is_empty() => Turn::Seeds(taken),+ // Both lanes are closed and drained and no run is pending, so nothing more can arrive.+ else => break,+ };+ let batch = match turn {+ Turn::Live(Some(batch)) => batch,+ Turn::Live(None) => {+ live_open = false;+ continue;+ }+ Turn::Seeds(0) => {+ seed_open = false;+ continue;+ }+ // `recv_many` appends, so drain it: otherwise turn n re-groups turns 1..n-1.+ Turn::Seeds(_) => {+ debug_assert!(+ pending.groups.is_empty(),+ "a quantum is taken only once the last one applied"+ );+ pending = group_seed_turn(+ partition_id,+ &catalog,+ &merge,+ seed_buf.drain(..).map(Admitted::from).collect(),+ );+ continue;+ }+ Turn::Run => {+ apply_next_run(+ partition_id,+ &handle,+ &catalog,+ &sink,+ &merge,+ &mut queue,+ &mut reconcile_queue,+ &mut last_updated_clock,+ &mut pending,+ )+ .await;+ if pending.groups.is_empty() {+ // The whole quantum applied: its marks can publish, and the lane's meter stops+ // counting the seeds it took.+ std::mem::take(&mut pending.marks).publish(&merge.seed_tracker, partition_id);+ seeds.finish_turn();+ }+ continue;+ }+ };let mut buffer = OutputBuffer::new();let mut re_keys: Vec<CohortStreamEvent> = Vec::new();let mut max_offset: Option<i64> = None;@@ -184,37 +288,7 @@ async fn run_worker(// Set when a pre-arm flush fails: holds the whole batch's offset so Kafka replays it.let mut held = false;- // Seeds accumulate so one run amortizes a produce round trip across many of them. Every- // other arm closes the collection first, which keeps a seed's order against the messages- // around it — a reconcile control seed still lands behind the data seeds that precede it.- let mut seeds: Vec<Admitted<SeedWork>> = Vec::new();-for message in batch {- if let ShuffleMessage::Seed { work, offset, .. } = message {- seeds.push(Admitted {- work: *work,- offset: SeedOffset(offset),- });- continue;- }- if apply_seed_runs(- partition_id,- &handle,- &catalog,- &sink,- &merge,- &mut queue,- &mut reconcile_queue,- &mut last_updated_clock,- &mut buffer,- &mut held,- &mut seeds,- )- .await- {- break;- }-let last_updated = last_updated_clock.next();match message {ShuffleMessage::Event {@@ -379,8 +453,6 @@ async fn run_worker(.unwrap_or_default();}}- // Collected above, before this match ever sees one.- ShuffleMessage::Seed { .. } => unreachable!("seeds are collected into runs"),ShuffleMessage::ReconcileDrain => {if flush_event_changes_before_inline(&sink,@@ -411,23 +483,6 @@ async fn run_worker(}}- if !held {- apply_seed_runs(- partition_id,- &handle,- &catalog,- &sink,- &merge,- &mut queue,- &mut reconcile_queue,- &mut last_updated_clock,- &mut buffer,- &mut held,- &mut seeds,- )- .await;- }-if held {continue;}@@ -462,10 +517,10 @@ async fn run_worker(if errors > 0 {counter!(MERGE_REKEY_PRODUCE_FAILURE_TOTAL).increment(errors as u64);warn!(- partition_id,- errors,- "straggler re-key produce to cohort_stream_events failed; holding offset for replay",- );+ partition_id,+ errors,+ "straggler re-key produce to cohort_stream_events failed; holding offset for replay",+ );continue;}tombstone_redirect::record_re_keyed(produced);@@ -477,10 +532,10 @@ async fn run_worker({counter!(COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH).increment(1);warn!(- partition_id,- next_offset = max_offset + 1,- "offset mark exceeded the dispatch ceiling and was capped (F1 invariant violation)",- );+ partition_id,+ next_offset = max_offset + 1,+ "offset mark exceeded the dispatch ceiling and was capped (F1 invariant violation)",+ );}}// Strictly post-mark: a consume-time watermark would reopen the double-count branch the@@ -508,9 +563,10 @@ async fn flush_membership_buffer(produce_membership(sink, buffer.take()).await}-/// Flush buffered event-path changes ahead of an inline arm. Returns `true` when the flush failed:-/// sets `held` so the caller `break`s and `mark_processed` is skipped, causing Kafka to replay.-/// Returns `false` (empty or all acked) to run the arm normally.+/// Flush buffered event-path changes ahead of an inline arm (sweep, merge, transfer, cascade, or+/// reconcile drain). Returns `true` when the flush failed: sets `held` so the caller `break`s and+/// `mark_processed` is skipped, causing Kafka to replay. Returns `false` (empty or all acked) to+/// run the arm normally.async fn flush_event_changes_before_inline(sink: &Arc<dyn MembershipSink>,buffer: &mut OutputBuffer,@@ -529,29 +585,16 @@ async fn flush_event_changes_before_inline(false}-/// Apply the seeds collected so far as runs, ahead of whatever message closed the collection.+/// Split one quantum into the runs it will apply, one per worker round.///-/// Returns `true` when the pre-run flush of buffered live changes failed: the caller must stop the-/// batch without marking, so Kafka replays it. The collected seeds are then neither marked nor-/// held, which is what their own redelivery is for.-#[allow(clippy::too_many_arguments)]-async fn apply_seed_runs(+/// No live-buffer flush is needed first: the live `OutputBuffer` is produced (or its batch held) at+/// the end of every live sub-batch, so it is always empty when a seed run starts.+fn group_seed_turn(partition_id: u16,- handle: &StoreHandle,catalog: &CatalogHandle,- sink: &Arc<dyn MembershipSink>,merge: &MergeWorkerDeps,- queue: &mut EvictionQueue<BehavioralKey>,- reconcile_queue: &mut ReconcileQueue,- clock: &mut LastUpdatedClock,- buffer: &mut OutputBuffer,- held: &mut bool,- seeds: &mut Vec<Admitted<SeedWork>>,-) -> bool {- if seeds.is_empty() {- return false;- }- let seeds = std::mem::take(seeds);+ seeds: Vec<Admitted<SeedWork>>,+) -> PendingRuns {// Worker receipt is the first point that both proves these exact seeds landed and orders their// ceiling before even a zero-work run can mark them processed. The dispatcher also records the// delivered batch maximum, but that post-send accounting can race a fast worker on a@@ -561,12 +604,31 @@ async fn apply_seed_runs(.seed_tracker.mark_dispatched(partition_id as i32, max + 1);}- // Produce order equals state-commit order for the live buffer, so a run must not produce while- // unflushed live changes sit in it.- if flush_event_changes_before_inline(sink, buffer, partition_id, held).await {- return true;+ let snapshot = catalog.load();+ let groups = group_seeds(seeds, merge.seed_budget, |work| row_weight(&snapshot, work));+ PendingRuns {+ groups: groups.into(),+ marks: BatchMarks::default(),}+}+/// Apply the pending quantum's next run. Each run folds under its own catalog snapshot, so a+/// catalog refresh between two runs of one quantum is the same edit race a live batch runs under.+#[allow(clippy::too_many_arguments)]+async fn apply_next_run(+ partition_id: u16,+ handle: &StoreHandle,+ catalog: &CatalogHandle,+ sink: &Arc<dyn MembershipSink>,+ merge: &MergeWorkerDeps,+ queue: &mut EvictionQueue<BehavioralKey>,+ reconcile_queue: &mut ReconcileQueue,+ clock: &mut LastUpdatedClock,+ pending: &mut PendingRuns,+) {+ let Some(group) = pending.groups.pop_front() else {+ return;+ };let snapshot = catalog.load();let deps = ApplyDeps {partition_id,@@ -575,9 +637,15 @@ async fn apply_seed_runs(sink,merge,};- let groups = group_seeds(seeds, merge.seed_budget, |work| row_weight(&snapshot, work));- handle_seed_groups(deps, queue, reconcile_queue, clock, groups).await;- false+ apply_seed_group(+ deps,+ queue,+ reconcile_queue,+ clock,+ &mut pending.marks,+ group,+ )+ .await;}pub(crate) fn count_by_status(changes: &[CohortMembershipChange]) -> (u64, u64) {@@ -1289,6 +1357,15 @@ mod tombstone_redirect_tests {})}+ fn consumed_reconcile(tile: ReconcileTile, offset: i64) -> ConsumedSeed {+ ConsumedSeed {+ work: SeedWork::Reconcile(tile),+ partition: 0,+ offset,+ broker_ts_ms: None,+ }+ }+fn reconcile_deps() -> (Arc<MergeWorkerDeps>, CaptureReconcileMarkerSink) {let mut deps = Arc::try_unwrap(merge_deps_with(CaptureStreamEventSink::new())).unwrap_or_else(|_| panic!("test owns the only dependency Arc"));@@ -1373,6 +1450,7 @@ mod tombstone_redirect_tests {cse_offset: 0,broker_ts_ms: None,}],+ vec![],).await;(partition_id, tracker)@@ -1402,11 +1480,8 @@ mod tombstone_redirect_tests {&events_tracker,merge,0,- vec![ShuffleMessage::Seed {- work: Box::new(SeedWork::Reconcile(tile)),- offset: 5,- broker_ts_ms: None,- }],+ vec![],+ vec![consumed_reconcile(tile, 5)],).await;@@ -1430,24 +1505,39 @@ mod tombstone_redirect_tests {RunId(Uuid::from_u128(7)),);- run_batch(+ // The drain tick must arrive after the tile is admitted, so the two lanes are driven by+ // hand: a tick that beats the tile finds an empty queue and drains nothing. In production+ // that is only latency — the next 2 s tick drains it.+ let (live_tx, live_rx) = mpsc::channel(4);+ let (seed_tx, seed_rx) = mpsc::channel(4);+ let worker = Stage1Worker::spawn(0,- &store,+ WorkerInbox::unmetered(live_rx, seed_rx),+ test_handle(&store),reconcile_catalog(FILTERS_HASH),- &membership,- &events_tracker,+ Arc::new(membership.clone()),+ events_tracker.clone(),merge,- 0,- vec![- ShuffleMessage::Seed {- work: Box::new(SeedWork::Reconcile(tile)),- offset: 5,- broker_ts_ms: None,- },- ShuffleMessage::ReconcileDrain,- ],- )- .await;+ false,+ );+ seed_tx.send(consumed_reconcile(tile, 5)).await.unwrap();+ drop(seed_tx);+ // Bounded by the clock, not by a poll count: the admission's store section runs on the+ // blocking pool, so a busy CI box needs wall time, not yields.+ let deadline = Instant::now() + Duration::from_secs(10);+ while backlog.is_empty() {+ assert!(+ Instant::now() < deadline,+ "the reconcile tile was never admitted"+ );+ tokio::time::sleep(Duration::from_millis(5)).await;+ }+ live_tx+ .send(vec![ShuffleMessage::ReconcileDrain])+ .await+ .unwrap();+ drop(live_tx);+ worker.join().await.unwrap();assert!(membership.changes().is_empty());let markers = marker_sink.markers();@@ -1488,6 +1578,7 @@ mod tombstone_redirect_tests {broker_ts_ms: None,},],+ vec![],).await;@@ -1579,6 +1670,8 @@ mod tombstone_redirect_tests {);}+ /// Drive one worker over both lanes: `live` is sent as a single sub-batch, `seeds` one per+ /// lane slot, then both senders drop so the worker drains and exits.#[allow(clippy::too_many_arguments)]async fn run_batch(partition_id: u16,@@ -1588,13 +1681,14 @@ mod tombstone_redirect_tests {tracker: &Arc<OffsetTracker>,merge: Arc<MergeWorkerDeps>,dispatched: i64,- batch: Vec<ShuffleMessage>,+ live: Vec<ShuffleMessage>,+ seeds: Vec<ConsumedSeed>,) {- let (tx, rx) = mpsc::channel(4);- let rx = MeteredReceiver::unmetered(rx);+ let (live_tx, live_rx) = mpsc::channel(4);+ let (seed_tx, seed_rx) = mpsc::channel(16);let worker = Stage1Worker::spawn(partition_id,- rx,+ WorkerInbox::unmetered(live_rx, seed_rx),test_handle(store),catalog,Arc::new(membership.clone()),@@ -1603,8 +1697,14 @@ mod tombstone_redirect_tests {false,);tracker.mark_dispatched(partition_id as i32, dispatched);- tx.send(batch).await.unwrap();- drop(tx);+ for seed in seeds {+ seed_tx.send(seed).await.unwrap();+ }+ drop(seed_tx);+ if !live.is_empty() {+ live_tx.send(live).await.unwrap();+ }+ drop(live_tx);worker.join().await.unwrap();}@@ -1630,6 +1730,7 @@ mod tombstone_redirect_tests {cse_offset: 0,broker_ts_ms: None,}],+ vec![],).await;}@@ -1881,6 +1982,7 @@ mod tombstone_redirect_tests {merge_deps_with(stream_sink.clone()),2,batch(),+ vec![],).await;assert!(@@ -1906,6 +2008,7 @@ mod tombstone_redirect_tests {merge_deps_with(stream_sink.clone()),2,batch(),+ vec![],).await;assert!(@@ -2102,6 +2205,7 @@ mod tombstone_redirect_tests {marker_cutoff_ms: 0,tombstone_cutoff_ms: 0,}],+ vec![],).await;diff --git a/rust/cohort-stream-processor/tests/events_consumer.rs b/rust/cohort-stream-processor/tests/events_consumer.rsindex 52561fbbf0a6..e0ca292507e4 100644--- a/rust/cohort-stream-processor/tests/events_consumer.rs+++ b/rust/cohort-stream-processor/tests/events_consumer.rs@@ -40,8 +40,8 @@ use cohort_stream_processor::filters::{CatalogHandle, CohortId, FilterCatalog, TeamFiltersBuilder, TeamId,};use cohort_stream_processor::partitions::{- run_rebalance_worker, CohortConsumerContext, MeteredReceiver, OffsetTracker, PartitionMirror,- PartitionRouter, ShuffleMessage,+ run_rebalance_worker, CohortConsumerContext, OffsetTracker, PartitionMirror, PartitionRouter,+ ShuffleMessage, WorkerInbox,};use cohort_stream_processor::producer::{CaptureSink, CohortMembershipChange, KafkaMembershipSink, MembershipSink, MembershipStatus,@@ -1105,7 +1105,7 @@ async fn durable_restart_reopens_live_state_and_fires_a_dormant_left() {let far_future = 4_000_000_000_000i64; // ~year 2096, well past every BASE_TS + 7d deadlinefor partition in 0..NUM_PARTITIONS {let (tx, rx) = mpsc::channel(4);- let rx = MeteredReceiver::unmetered(rx);+ let rx = WorkerInbox::live_only(rx);let worker = Stage1Worker::spawn(partition as u16,rx,@@ -1487,7 +1487,7 @@ async fn s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormantlet far_future = 4_000_000_000_000i64; // ~year 2096, past every BASE_TS + 7d deadlinefor partition in 0..NUM_PARTITIONS {let (tx, rx) = mpsc::channel(4);- let rx = MeteredReceiver::unmetered(rx);+ let rx = WorkerInbox::live_only(rx);let worker = Stage1Worker::spawn(partition as u16,rx,diff --git a/rust/cohort-stream-processor/tests/stage1_worker.rs b/rust/cohort-stream-processor/tests/stage1_worker.rsindex 81ddca8975f2..f58a6ddca47d 100644--- a/rust/cohort-stream-processor/tests/stage1_worker.rs+++ b/rust/cohort-stream-processor/tests/stage1_worker.rs@@ -11,16 +11,20 @@#![allow(clippy::disallowed_methods)]use std::collections::BTreeMap;+use std::num::NonZeroUsize;use std::sync::Arc;+use std::time::{Duration, Instant};use chrono_tz::Asia::Kolkata;use chrono_tz::{Tz, UTC};-use cohort_stream_processor::consumers::{CohortStreamEvent, SeedWork};+use cohort_stream_processor::consumers::{CohortStreamEvent, ConsumedSeed, SeedWork};use cohort_stream_processor::filters::{CatalogHandle, CohortId, FilterCatalog, TeamFilters, TeamFiltersBuilder, TeamId,};-use cohort_stream_processor::partitions::{MeteredReceiver, OffsetTracker, ShuffleMessage};-use cohort_stream_processor::producer::{CaptureSink, MembershipStatus};+use cohort_stream_processor::partitions::{OffsetTracker, ShuffleMessage, WorkerInbox};+use cohort_stream_processor::producer::{+ CaptureSink, CohortMembershipChange, MembershipSink, MembershipStatus,+};use cohort_stream_processor::stage1::bucket_tz::{day_idx_in_tz, start_of_day_ms_in_tz};use cohort_stream_processor::stage1::person_record::{MatchedSet, PersonRecord};use cohort_stream_processor::stage1::{@@ -32,7 +36,9 @@ use cohort_stream_processor::store::{Behavioral, BehavioralKey, CohortStore, LeafStateKey, OffloadConfig, OffloadMode, PersonPrefix,PersonRecordKey, PersonRecords, Stage2Key, StoreConfig, StoreHandle,};+use cohort_stream_processor::workers::seed_run::RunBudget;use cohort_stream_processor::workers::{process_event, MergeWorkerDeps, SkipReason, Stage1Worker};+use common_kafka::kafka_producer::KafkaProduceError;use serde_json::{json, Value};use tempfile::TempDir;use tokio::sync::mpsc;@@ -1120,7 +1126,7 @@ async fn spawned_worker_drains_a_batch_and_commits_state() {let tracker = Arc::new(OffsetTracker::new());let (tx, rx) = mpsc::channel(16);- let rx = MeteredReceiver::unmetered(rx);+ let rx = WorkerInbox::live_only(rx);let worker = Stage1Worker::spawn(PARTITION_ID,rx,@@ -1176,7 +1182,7 @@ async fn sub_batch_read_your_writes_survives_offload() {let tracker = Arc::new(OffsetTracker::new());let (tx, rx) = mpsc::channel(16);- let rx = MeteredReceiver::unmetered(rx);+ let rx = WorkerInbox::live_only(rx);let worker = Stage1Worker::spawn(PARTITION_ID,rx,@@ -1237,7 +1243,7 @@ async fn spawned_worker_composes_two_leaf_cohort_and_emits_single_leaf_independelet tracker = Arc::new(OffsetTracker::new());let (tx, rx) = mpsc::channel(16);- let rx = MeteredReceiver::unmetered(rx);+ let rx = WorkerInbox::live_only(rx);let worker = Stage1Worker::spawn(PARTITION_ID,rx,@@ -1305,7 +1311,7 @@ async fn spawned_worker_skips_events_for_unknown_teams() {let tracker = Arc::new(OffsetTracker::new());let (tx, rx) = mpsc::channel(16);- let rx = MeteredReceiver::unmetered(rx);+ let rx = WorkerInbox::live_only(rx);let worker = Stage1Worker::spawn(PARTITION_ID,rx,@@ -1352,7 +1358,7 @@ async fn worker_produces_changes_and_advances_offset() {let tracker = Arc::new(OffsetTracker::new());let (tx, rx) = mpsc::channel(16);- let rx = MeteredReceiver::unmetered(rx);+ let rx = WorkerInbox::live_only(rx);let worker = Stage1Worker::spawn(PARTITION_ID,rx,@@ -1395,7 +1401,7 @@ async fn worker_advances_offset_on_empty_transition_subbatch() {let tracker = Arc::new(OffsetTracker::new());let (tx, rx) = mpsc::channel(16);- let rx = MeteredReceiver::unmetered(rx);+ let rx = WorkerInbox::live_only(rx);let worker = Stage1Worker::spawn(PARTITION_ID,rx,@@ -1430,7 +1436,7 @@ async fn worker_holds_offset_when_the_only_flush_fails() {let tracker = Arc::new(OffsetTracker::new());let (tx, rx) = mpsc::channel(16);- let rx = MeteredReceiver::unmetered(rx);+ let rx = WorkerInbox::live_only(rx);let worker = Stage1Worker::spawn(PARTITION_ID,rx,@@ -1461,7 +1467,7 @@ async fn worker_keeps_processing_after_a_produce_failure() {let tracker = Arc::new(OffsetTracker::new());let (tx, rx) = mpsc::channel(16);- let rx = MeteredReceiver::unmetered(rx);+ let rx = WorkerInbox::live_only(rx);let worker = Stage1Worker::spawn(PARTITION_ID,rx,@@ -1900,7 +1906,7 @@ async fn daily_multiple_single_leaf_cohort_emits_entered_then_left_to_the_sink()let tracker = Arc::new(OffsetTracker::new());let (tx, rx) = mpsc::channel(16);- let rx = MeteredReceiver::unmetered(rx);+ let rx = WorkerInbox::live_only(rx);let worker = Stage1Worker::spawn(PARTITION_ID,rx,@@ -2241,7 +2247,7 @@ async fn compressed_sweep_deletes_then_a_late_event_recreates_the_state() {let tracker = Arc::new(OffsetTracker::new());let (tx, rx) = mpsc::channel(16);- let rx = MeteredReceiver::unmetered(rx);+ let rx = WorkerInbox::live_only(rx);let worker = Stage1Worker::spawn(PARTITION_ID,rx,@@ -2418,9 +2424,10 @@ fn seed_tile(person: Uuid, day: i32, count: u32) -> cohort_core::seed::SeedTile)}-fn seed_message(person: Uuid, day: i32, count: u32, offset: i64) -> ShuffleMessage {- ShuffleMessage::Seed {- work: Box::new(SeedWork::Tile(seed_tile(person, day, count))),+fn consumed_seed(person: Uuid, day: i32, count: u32, offset: i64) -> ConsumedSeed {+ ConsumedSeed {+ work: SeedWork::Tile(seed_tile(person, day, count)),+ partition: PARTITION_ID as i32,offset,broker_ts_ms: None,}@@ -2430,26 +2437,105 @@ 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.+/// Bounded by the clock, not by a poll count: the worker's store sections run on the blocking+/// pool, so a busy CI box needs wall time, not yields.+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(5)).await;+ }+}++/// A sink that sends one live batch on its first produce, then delegates to a [`CaptureSink`].+/// Injecting from inside a produce is deterministic on any runtime flavor: the worker is mid-run,+/// so the batch is queued before its next select round. The sender goes with the batch, because+/// holding it past that would keep the live lane open and the worker would never exit.+struct InjectLiveOnFirstProduce {+ inner: CaptureSink,+ inject: std::sync::Mutex<Option<(mpsc::Sender<Vec<ShuffleMessage>>, ShuffleMessage)>>,+}++impl InjectLiveOnFirstProduce {+ fn new(+ inner: CaptureSink,+ live: mpsc::Sender<Vec<ShuffleMessage>>,+ message: ShuffleMessage,+ ) -> Self {+ Self {+ inner,+ inject: std::sync::Mutex::new(Some((live, message))),+ }+ }+}++#[async_trait::async_trait]+impl MembershipSink for InjectLiveOnFirstProduce {+ async fn produce(+ &self,+ changes: Vec<CohortMembershipChange>,+ ) -> Vec<Result<(), KafkaProduceError>> {+ if let Some((live, message)) = self.inject.lock().unwrap().take() {+ live.try_send(vec![message])+ .expect("the live lane has room");+ }+ self.inner.produce(changes).await+ }+}++/// Live wins every round while its lane holds a batch, however many are queued: a `biased;`+/// regression would let the waiting seeds go first, and the recorded produce order would flip.+/// This is the live-first contract, not a fairness one: a partition whose live lane never empties+/// makes no seed progress by design, and its lane filling is what pauses it at the seed consumer.#[tokio::test]-async fn seed_arm_flushes_buffered_event_changes_first_and_marks_both_trackers() {+async fn every_queued_live_batch_is_served_before_a_waiting_seed_turn() {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 carol = person(3);+ let live_people: Vec<_> = (1..=8).map(person).collect();+ let bob = person(9);+ let carol = person(10);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 (live_tx, live_rx) = mpsc::channel(16);+ let (seed_tx, seed_rx) = mpsc::channel(16);+ let broker_ts = 1_750_000_000_000_i64;+ tracker.mark_dispatched(PARTITION_ID as i32, 8);+ deps.seed_tracker.mark_dispatched(PARTITION_ID as i32, 8);++ // Both lanes are filled before the worker starts, so both select branches are ready at its+ // very first poll and the order is the priority, not a race. Eight live batches make an+ // unbiased select unlikely to serve every live round before the waiting seed turn.+ for (n, who) in live_people.iter().copied().enumerate() {+ live_tx+ .send(vec![ShuffleMessage::Event {+ event: Box::new(event(who, 5, 0)),+ cse_offset: n as i64,+ broker_ts_ms: Some(broker_ts + n as i64),+ }])+ .await+ .unwrap();+ }+ seed_tx+ .send(consumed_seed(bob, utc_today(), 1, 6))+ .await+ .unwrap();+ seed_tx+ .send(consumed_seed(carol, utc_today(), 1, 7))+ .await+ .unwrap();+ drop(live_tx);+ drop(seed_tx);+let worker = Stage1Worker::spawn(PARTITION_ID,- rx,+ WorkerInbox::unmetered(live_rx, seed_rx),test_handle(&store),catalog,Arc::new(sink.clone()),@@ -2457,76 +2543,68 @@ async fn seed_arm_flushes_buffered_event_changes_first_and_marks_both_trackers()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, 6),- seed_message(carol, utc_today(), 1, 7),- ])- .await- .unwrap();- drop(tx);worker.join().await.unwrap();let changes = sink.changes();- assert_eq!(changes.len(), 3, "one live flip, two seeded flips");+ assert_eq!(changes.len(), 10, "eight live flips, two seeded flips");assert_eq!(- (changes[0].person_id.clone(), changes[0].origin),- (alice.to_string(), None),- "the buffered live change flushed before the seed run ran",+ changes[..8]+ .iter()+ .map(|change| (change.person_id.clone(), change.origin))+ .collect::<Vec<_>>(),+ live_people+ .iter()+ .map(|who| (who.to_string(), None))+ .collect::<Vec<_>>(),+ "every queued live batch was served before the waiting seed turn",);assert_eq!(- changes[1..]+ changes[8..].iter().map(|change| change.person_id.clone()).collect::<std::collections::BTreeSet<_>>(),std::collections::BTreeSet::from([bob.to_string(), carol.to_string()]),- "both seeds of the collection applied",+ "both seeds of the turn applied",);assert!(- changes[1..].iter().all(|change| change.origin.is_some()),+ changes[8..].iter().all(|change| change.origin.is_some()),"the seeded changes are tagged",);assert_eq!(sink.produce_calls(),- 2,- "one call for the live flush and one for the whole seed run",+ 9,+ "one call per live batch and one for the whole seed run",);assert_eq!(tracker.committable_offsets().get(&(PARTITION_ID as i32)),- Some(&1),- "the events tracker advanced past the event",+ Some(&8),+ "the events tracker advanced past all eight events",);assert_eq!(deps.seed_tracker.committable_offsets().get(&(PARTITION_ID as i32)),Some(&8),- "the seed tracker advanced past the tile",+ "the seed tracker advanced past both tiles",);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",+ Some(cohort_stream_processor::partitions::WatermarkMs(+ broker_ts + 7+ )),+ "the folded batches advanced the live watermark",);}-/// The whole point of the batched apply: a channel batch's seeds pay one produce round trip per-/// run, not one per seed. A regression here shows up as latency, not as a wrong result, so nothing-/// else would catch it.+/// The whole point of the lane: a seed backlog is served in run-sized quanta, so it pays one+/// produce round trip per run rather than one per seed, and one turn never swallows the backlog.+/// A regression here shows up as latency, not as a wrong result, so nothing else would catch it.#[tokio::test]-async fn a_channel_batch_of_seeds_pays_one_produce_round_trip_per_run() {- const SEEDS: usize = 300;- // `COHORT_SEED_APPLY_BATCH_MAX` defaults to 256, so 300 seeds form two runs.- const RUNS: usize = 2;+async fn a_seed_backlog_is_served_in_run_sized_quanta() {+ const SEEDS: usize = 600;+ // `COHORT_SEED_APPLY_BATCH_MAX` defaults to 256, so 600 seeds form three quanta.+ const RUNS: usize = 3;let (_dir, store) = temp_store();let filters = build_team_filters(vec![(CohortId(1), cohort(vec![behavioral_leaf(7)]))]);@@ -2535,11 +2613,28 @@ async fn a_channel_batch_of_seeds_pays_one_produce_round_trip_per_run() {let tracker = Arc::new(OffsetTracker::new());let deps = MergeWorkerDeps::capture();- let (tx, rx) = mpsc::channel(16);- let rx = MeteredReceiver::unmetered(rx);+ let (live_tx, live_rx) = mpsc::channel(16);+ let (seed_tx, seed_rx) = mpsc::channel(SEEDS);+ deps.seed_tracker+ .mark_dispatched(PARTITION_ID as i32, SEEDS as i64);+ // Sent one at a time, as the dispatcher sends them: the quantum has to batch across sends.+ for n in 0..SEEDS {+ seed_tx+ .send(consumed_seed(+ person(n as u128 + 1),+ utc_today(),+ 1,+ n as i64,+ ))+ .await+ .unwrap();+ }+ drop(seed_tx);+ drop(live_tx);+let worker = Stage1Worker::spawn(PARTITION_ID,- rx,+ WorkerInbox::unmetered(live_rx, seed_rx),test_handle(&store),catalog,Arc::new(sink.clone()),@@ -2547,14 +2642,6 @@ async fn a_channel_batch_of_seeds_pays_one_produce_round_trip_per_run() {deps.clone(),false,);-- deps.seed_tracker- .mark_dispatched(PARTITION_ID as i32, SEEDS as i64);- let batch: Vec<ShuffleMessage> = (0..SEEDS)- .map(|n| seed_message(person(n as u128 + 1), utc_today(), 1, n as i64))- .collect();- tx.send(batch).await.unwrap();- drop(tx);worker.join().await.unwrap();assert_eq!(@@ -2565,14 +2652,289 @@ async fn a_channel_batch_of_seeds_pays_one_produce_round_trip_per_run() {assert_eq!(sink.produce_calls(),RUNS,- "one produce per run, not one per seed",+ "one produce per run-sized quantum, not one per seed and not one for the backlog",+ );+ assert_eq!(+ deps.seed_tracker+ .committable_offsets()+ .get(&(PARTITION_ID as i32)),+ Some(&(SEEDS as i64)),+ "every run marked its whole span",+ );+}++/// A live batch that arrives mid-backlog is served before the next seed turn, so live latency is+/// at most one turn. The sink wrapper injects it while run 1 is producing, which is deterministic+/// on any runtime flavor.+#[tokio::test]+async fn a_live_batch_arriving_during_a_seed_backlog_is_served_before_the_next_seed_turn() {+ const SEEDS: usize = 512;++ let (_dir, store) = temp_store();+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![behavioral_leaf(7)]))]);+ let catalog = catalog_of(filters);+ let recorder = CaptureSink::new();+ let tracker = Arc::new(OffsetTracker::new());+ let deps = MergeWorkerDeps::capture();+ let alice = person(0xA11CE);++ let (live_tx, live_rx) = mpsc::channel(16);+ let (seed_tx, seed_rx) = mpsc::channel(SEEDS);+ tracker.mark_dispatched(PARTITION_ID as i32, 1);+ deps.seed_tracker+ .mark_dispatched(PARTITION_ID as i32, SEEDS as i64);+ for n in 0..SEEDS {+ seed_tx+ .send(consumed_seed(+ person(n as u128 + 1),+ utc_today(),+ 1,+ n as i64,+ ))+ .await+ .unwrap();+ }+ drop(seed_tx);++ let sink = InjectLiveOnFirstProduce::new(+ recorder.clone(),+ live_tx,+ ShuffleMessage::Event {+ event: Box::new(event(alice, 5, 0)),+ cse_offset: 0,+ broker_ts_ms: None,+ },+ );++ let worker = Stage1Worker::spawn(+ PARTITION_ID,+ WorkerInbox::unmetered(live_rx, seed_rx),+ test_handle(&store),+ catalog,+ Arc::new(sink),+ tracker.clone(),+ deps.clone(),+ false,+ );+ worker.join().await.unwrap();++ // Run 1 emits 256 seeded changes, then the injected live change, then run 2's 256.+ let changes = recorder.changes();+ assert_eq!(changes.len(), SEEDS + 1);+ let live_at = changes+ .iter()+ .position(|change| change.person_id == alice.to_string())+ .expect("the injected live change landed");+ assert_eq!(+ live_at, 256,+ "the live batch was served between the two seed turns, not after the backlog",+ );+ assert!(+ changes[..live_at]+ .iter()+ .all(|change| change.origin.is_some()),+ "run 1 is all seeded changes",+ );+ assert!(+ changes[live_at + 1..]+ .iter()+ .all(|change| change.origin.is_some()),+ "run 2 is all seeded changes",+ );+}++/// A quantum can split into several runs (the row budget here; a kind change or a control seed+/// elsewhere), and a live batch that arrives during one of them is served before the next run,+/// not after the whole quantum. Eight seeds of two rows each under a four-row budget make four+/// runs out of one quantum.+#[tokio::test]+async fn a_live_batch_arriving_mid_quantum_is_served_before_the_next_run() {+ const SEEDS: usize = 8;+ const RUNS: usize = 4;++ let (_dir, store) = temp_store();+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![behavioral_leaf(7)]))]);+ let catalog = catalog_of(filters);+ let recorder = CaptureSink::new();+ let tracker = Arc::new(OffsetTracker::new());+ let mut deps = Arc::try_unwrap(MergeWorkerDeps::capture())+ .ok()+ .expect("the test owns the only dependency Arc");+ deps.seed_budget = RunBudget {+ seeds: NonZeroUsize::new(256).unwrap(),+ // One leaf backing one single-leaf cohort weighs two rows, so two seeds fill the budget.+ rows: NonZeroUsize::new(4).unwrap(),+ };+ let deps = Arc::new(deps);+ let alice = person(0xA11CE);++ let (live_tx, live_rx) = mpsc::channel(16);+ let (seed_tx, seed_rx) = mpsc::channel(SEEDS);+ tracker.mark_dispatched(PARTITION_ID as i32, 1);+ deps.seed_tracker+ .mark_dispatched(PARTITION_ID as i32, SEEDS as i64);+ for n in 0..SEEDS {+ seed_tx+ .send(consumed_seed(+ person(n as u128 + 1),+ utc_today(),+ 1,+ n as i64,+ ))+ .await+ .unwrap();+ }+ drop(seed_tx);++ let sink = InjectLiveOnFirstProduce::new(+ recorder.clone(),+ live_tx,+ ShuffleMessage::Event {+ event: Box::new(event(alice, 5, 0)),+ cse_offset: 0,+ broker_ts_ms: None,+ },+ );++ let worker = Stage1Worker::spawn(+ PARTITION_ID,+ WorkerInbox::unmetered(live_rx, seed_rx),+ test_handle(&store),+ catalog,+ Arc::new(sink),+ tracker.clone(),+ deps.clone(),+ false,+ );+ worker.join().await.unwrap();++ let changes = recorder.changes();+ assert_eq!(changes.len(), SEEDS + 1);+ let live_at = changes+ .iter()+ .position(|change| change.person_id == alice.to_string())+ .expect("the injected live change landed");+ assert_eq!(+ live_at,+ SEEDS / RUNS,+ "the live batch was served after the quantum's first run, not after the whole quantum",+ );+ assert_eq!(+ recorder.produce_calls(),+ RUNS + 1,+ "the row budget split the quantum into runs, plus one produce for the live batch",);assert_eq!(deps.seed_tracker.committable_offsets().get(&(PARTITION_ID as i32)),Some(&(SEEDS as i64)),- "both runs marked their whole spans",+ "the quantum's marks published once its last run applied",+ );+}++/// A closed seed lane must not stall the live lane, and the worker must still exit when the live+/// lane closes.+#[tokio::test]+async fn a_closed_seed_lane_does_not_stall_the_live_lane() {+ let (_dir, store) = temp_store();+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![behavioral_leaf(7)]))]);+ let alice = person(1);++ let sink = CaptureSink::new();+ let tracker = Arc::new(OffsetTracker::new());+ let deps = MergeWorkerDeps::capture();++ let (tx, rx) = mpsc::channel(16);+ let worker = Stage1Worker::spawn(+ PARTITION_ID,+ WorkerInbox::live_only(rx),+ test_handle(&store),+ catalog_of(filters),+ Arc::new(sink.clone()),+ tracker.clone(),+ deps.clone(),+ false,+ );++ // Let the worker observe the closed seed lane while the live lane is still open.+ tokio::task::yield_now().await;++ tracker.mark_dispatched(PARTITION_ID as i32, 1);+ tx.send(vec![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!(sink.changes().len(), 1, "the live event still folded");+ assert_eq!(+ tracker.committable_offsets().get(&(PARTITION_ID as i32)),+ Some(&1),+ "the live offset still marked",+ );+}++/// Both lanes drain before the worker exits: an exit on the first `None` would silently drop+/// whatever the other lane still held.+#[tokio::test]+async fn both_lanes_drain_before_the_worker_exits() {+ 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 sink = CaptureSink::new();+ let tracker = Arc::new(OffsetTracker::new());+ let deps = MergeWorkerDeps::capture();++ let (live_tx, live_rx) = mpsc::channel(16);+ let (seed_tx, seed_rx) = mpsc::channel(16);+ tracker.mark_dispatched(PARTITION_ID as i32, 1);+ deps.seed_tracker.mark_dispatched(PARTITION_ID as i32, 8);+ live_tx+ .send(vec![ShuffleMessage::Event {+ event: Box::new(event(alice, 5, 0)),+ cse_offset: 0,+ broker_ts_ms: None,+ }])+ .await+ .unwrap();+ seed_tx+ .send(consumed_seed(bob, utc_today(), 1, 7))+ .await+ .unwrap();+ drop(live_tx);+ drop(seed_tx);++ let worker = Stage1Worker::spawn(+ PARTITION_ID,+ WorkerInbox::unmetered(live_rx, seed_rx),+ test_handle(&store),+ catalog_of(filters),+ Arc::new(sink.clone()),+ tracker.clone(),+ deps.clone(),+ false,+ );+ worker.join().await.unwrap();++ assert_eq!(sink.changes().len(), 2, "both lanes' work landed");+ assert_eq!(+ tracker.committable_offsets().get(&(PARTITION_ID as i32)),+ Some(&1),+ "the events tracker advanced",+ );+ assert_eq!(+ deps.seed_tracker+ .committable_offsets()+ .get(&(PARTITION_ID as i32)),+ Some(&8),+ "the seed tracker advanced",);}@@ -2586,16 +2948,16 @@ async fn seed_produce_failure_holds_only_the_seed_tracker_and_the_redelivery_re_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.+ // The seed run's produce is the first: the seed lane is drained before the live batch is sent.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 (live_tx, live_rx) = mpsc::channel(16);+ let (seed_tx, seed_rx) = mpsc::channel(16);let worker = Stage1Worker::spawn(PARTITION_ID,- rx,+ WorkerInbox::unmetered(live_rx, seed_rx),test_handle(&store),catalog,Arc::new(sink.clone()),@@ -2606,17 +2968,26 @@ async fn seed_produce_failure_holds_only_the_seed_tracker_and_the_redelivery_re_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 {+ // The seed turn runs first, and its failure must not touch the live batch that follows. The+ // two lanes have no defined order between them, so the seed is drained to completion first.+ seed_tx+ .send(consumed_seed(bob, utc_today(), 1, 7))+ .await+ .unwrap();+ drop(seed_tx);+ wait_for("the seed run's produce", Duration::from_secs(10), || {+ sink.produce_calls() > 0+ })+ .await;+ live_tx+ .send(vec![ShuffleMessage::Event {event: Box::new(event(alice, 5, 0)),cse_offset: 0,broker_ts_ms: None,- },- ])- .await- .unwrap();- drop(tx);+ }])+ .await+ .unwrap();+ drop(live_tx);worker.join().await.unwrap();assert_eq!(@@ -2641,11 +3012,11 @@ async fn seed_produce_failure_holds_only_the_seed_tracker_and_the_redelivery_re_let replay_sink = CaptureSink::new();let replay_deps = MergeWorkerDeps::capture();let replay_tracker = Arc::new(OffsetTracker::new());- let (tx, rx) = mpsc::channel(16);- let rx = MeteredReceiver::unmetered(rx);+ let (live_tx, live_rx) = mpsc::channel(16);+ let (seed_tx, seed_rx) = mpsc::channel(16);let worker = Stage1Worker::spawn(PARTITION_ID,- rx,+ WorkerInbox::unmetered(live_rx, seed_rx),test_handle(&store),catalog_of(build_team_filters(vec![(CohortId(1),@@ -2659,10 +3030,12 @@ async fn seed_produce_failure_holds_only_the_seed_tracker_and_the_redelivery_re_replay_deps.seed_tracker.mark_dispatched(PARTITION_ID as i32, 8);- tx.send(vec![seed_message(bob, utc_today(), 1, 7)])+ seed_tx+ .send(consumed_seed(bob, utc_today(), 1, 7)).await.unwrap();- drop(tx);+ drop(seed_tx);+ drop(live_tx);worker.join().await.unwrap();let changes = replay_sink.changes();@@ -2709,7 +3082,7 @@ async fn watermark_advances_only_after_a_successful_mark() {let store = store.clone();async move {let (tx, rx) = mpsc::channel(16);- let rx = MeteredReceiver::unmetered(rx);+ let rx = WorkerInbox::live_only(rx);let worker = Stage1Worker::spawn(PARTITION_ID,rx,diff --git a/rust/cohort-stream-processor/tests/sweep_worker.rs b/rust/cohort-stream-processor/tests/sweep_worker.rsindex 97541d8751dc..b76ce677d019 100644--- a/rust/cohort-stream-processor/tests/sweep_worker.rs+++ b/rust/cohort-stream-processor/tests/sweep_worker.rs@@ -24,7 +24,7 @@ use cohort_stream_processor::filters::{CatalogHandle, CohortId, FilterCatalog, TeamFilters, TeamFiltersBuilder, TeamId,};use cohort_stream_processor::partitions::{- MeteredReceiver, OffsetTracker, PartitionRouter, ShuffleMessage,+ OffsetTracker, PartitionRouter, ShuffleMessage, WorkerInbox,};use cohort_stream_processor::producer::{CaptureSink, CohortMembershipChange, MembershipSink, MembershipStatus,@@ -304,7 +304,7 @@ fn spawn_worker_with_mode(mode: OffloadMode,) -> (mpsc::Sender<Vec<ShuffleMessage>>, Stage1Worker) {let (tx, rx) = mpsc::channel(16);- let rx = MeteredReceiver::unmetered(rx);+ let rx = WorkerInbox::live_only(rx);let worker = Stage1Worker::spawn(PARTITION_ID,rx,@@ -326,7 +326,7 @@ fn spawn_worker_with_restore(durable_restore: bool,) -> (mpsc::Sender<Vec<ShuffleMessage>>, Stage1Worker) {let (tx, rx) = mpsc::channel(16);- let rx = MeteredReceiver::unmetered(rx);+ let rx = WorkerInbox::live_only(rx);let worker = Stage1Worker::spawn(PARTITION_ID,rx,