: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
chore(cohorts): bound intake and fix order (#67984)
Matheus Batistabe50d5c7a17e
diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rsindex 761f2b6356a3..d6330303edc0 100644--- a/rust/cohort-stream-processor/src/config.rs+++ b/rust/cohort-stream-processor/src/config.rs@@ -76,6 +76,13 @@ 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.+ #[envconfig(from = "PARTITION_INTAKE_MAX_EVENTS", default = "1024")]+ pub partition_intake_max_events: usize,+#[envconfig(default = "localhost:9092")]pub kafka_hosts: String,@@ -104,6 +111,16 @@ pub struct Config {#[envconfig(default = "60000")]pub kafka_session_timeout_ms: u64,+ /// `queued.max.messages.kbytes` (KB). For a `subscribe()` consumer this is an *aggregate* cap+ /// across all partitions — the ceiling on librdkafka's fetch buffer. 128 MB.+ #[envconfig(from = "COHORT_KAFKA_QUEUED_MAX_MESSAGES_KBYTES", default = "131072")]+ pub kafka_queued_max_messages_kbytes: u32,++ /// `queued.min.messages` — per-partition prefetch floor. Low so a paused partition hoards fewer+ /// stragglers; too low risks `fetch.queue.backoff.ms` inter-fetch gaps.+ #[envconfig(from = "COHORT_KAFKA_QUEUED_MIN_MESSAGES", default = "2000")]+ pub kafka_queued_min_messages: u32,+/// The person-merge trigger topic, keyed by `hash(team_id, old_person_uuid)` so a merge lands on/// P_old's worker.#[envconfig(default = "person_merge_events")]@@ -254,6 +271,12 @@ pub struct Config {#[envconfig(default = "30000")]pub sweep_interval_ms: u64,+ /// Startup delay before the *first* eviction sweep, so its overdue-eviction read burst doesn't+ /// compete with backlog catch-up on a cold, idle store at boot. Counts from sweep-task spawn+ /// (≈ process boot), not "backlog drained", so raise it if the burst still lands on catch-up.+ #[envconfig(from = "COHORT_FIRST_EVICTION_SWEEP_DELAY_MS", default = "120000")]+ pub first_eviction_sweep_delay_ms: u64,+/// Grace period added to every eviction deadline before the sweep acts. The sweep evicts a key/// only once `deadline + safety_margin < now`, absorbing consumer-lag spikes.#[envconfig(default = "300000")]@@ -413,6 +436,14 @@ pub struct Config {pub checkpoint_import_timeout_secs: u64,}+/// librdkafka consumer fetch-queue bounds: an aggregate byte cap across all partitions and a+/// per-partition prefetch floor.+#[derive(Clone, Copy, Debug)]+pub struct FetchQueueConfig {+ pub queued_max_messages_kbytes: u32,+ pub queued_min_messages: u32,+}+impl Config {pub fn bind_address(&self) -> String {format!("{}:{}", self.bind_host, self.bind_port)@@ -454,6 +485,17 @@ impl Config {Duration::from_millis(self.sweep_interval_ms)}+ pub fn first_eviction_sweep_delay(&self) -> Duration {+ Duration::from_millis(self.first_eviction_sweep_delay_ms)+ }++ pub fn fetch_queue_config(&self) -> FetchQueueConfig {+ FetchQueueConfig {+ queued_max_messages_kbytes: self.kafka_queued_max_messages_kbytes,+ queued_min_messages: self.kafka_queued_min_messages,+ }+ }+pub fn sweep_safety_margin(&self) -> Duration {Duration::from_millis(self.sweep_safety_margin_ms)}@@ -625,6 +667,15 @@ impl Config {.set("heartbeat.interval.ms", "5000").set("max.poll.interval.ms", "300000");+ // Bound librdkafka's fetch buffer: an aggregate byte ceiling plus a per-partition prefetch floor.+ let fetch = self.fetch_queue_config();+ config+ .set(+ "queued.max.messages.kbytes",+ fetch.queued_max_messages_kbytes.to_string(),+ )+ .set("queued.min.messages", fetch.queued_min_messages.to_string());+// Static membership; an explicit `kafka_client_id` overrides `client.id` below.if let Some(id) = self.pod_identity() {config.set("group.instance.id", id).set("client.id", id);@@ -734,6 +785,7 @@ mod tests {cohort_person_memo_capacity: 20000,cohort_event_name_gating_enabled: true,partition_channel_buffer: 128,+ partition_intake_max_events: 1024,kafka_hosts: "localhost:9092".to_string(),kafka_tls: false,kafka_client_id: String::new(),@@ -741,6 +793,8 @@ mod tests {cohort_stream_events_topic: "cohort_stream_events".to_string(),kafka_consumer_group: "cohort-stream-processor".to_string(),kafka_consumer_offset_reset: "latest".to_string(),+ kafka_queued_max_messages_kbytes: 131_072,+ kafka_queued_min_messages: 2000,person_merge_events_topic: "person_merge_events".to_string(),cohort_merge_state_transfer_topic: "cohort_merge_state_transfer".to_string(),kafka_merge_consumer_group: "cohort-stream-merges".to_string(),@@ -772,6 +826,7 @@ mod tests {offset_commit_interval_ms: 5000,tokio_worker_threads: 0,sweep_interval_ms: 30000,+ first_eviction_sweep_delay_ms: 120_000,sweep_safety_margin_ms: 300000,stats_publish_interval_secs: 15,store_path: "cohort-store".to_string(),@@ -865,6 +920,47 @@ mod tests {assert_eq!(client.get("session.timeout.ms"), Some("45000"));}+ #[test]+ fn consumer_config_sets_the_fetch_queue_bounds() {+ let config = test_config();+ let client = config.consumer_client_config();+ assert_eq!(client.get("queued.max.messages.kbytes"), Some("131072"));+ assert_eq!(client.get("queued.min.messages"), Some("2000"));+ }++ #[test]+ 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.kafka_queued_max_messages_kbytes, 131_072);+ assert_eq!(defaults.kafka_queued_min_messages, 2000);+ assert_eq!(+ defaults.first_eviction_sweep_delay(),+ Duration::from_millis(120_000),+ );++ let env: std::collections::HashMap<String, String> = [+ ("PARTITION_INTAKE_MAX_EVENTS", "512"),+ ("COHORT_KAFKA_QUEUED_MAX_MESSAGES_KBYTES", "65536"),+ ("COHORT_KAFKA_QUEUED_MIN_MESSAGES", "1000"),+ ("COHORT_FIRST_EVICTION_SWEEP_DELAY_MS", "30000"),+ ]+ .into_iter()+ .map(|(key, value)| (key.to_string(), value.to_string()))+ .collect();+ let config = Config::init_from_hashmap(&env).unwrap();+ assert_eq!(config.partition_intake_max_events, 512);+ assert_eq!(+ config.fetch_queue_config().queued_max_messages_kbytes,+ 65536+ );+ assert_eq!(config.fetch_queue_config().queued_min_messages, 1000);+ assert_eq!(+ config.first_eviction_sweep_delay(),+ Duration::from_millis(30_000),+ );+ }+#[test]fn consumer_config_sets_static_membership_only_when_pod_identity_is_present() {let mut config = test_config();diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rsindex b14ae5f3f0d7..e24599f5ea53 100644--- a/rust/cohort-stream-processor/src/consumers/events.rs+++ b/rust/cohort-stream-processor/src/consumers/events.rs@@ -2068,6 +2068,25 @@ 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.+ fn dispatcher_with_intake_cap(+ store: &CohortStore,+ catalog: Arc<CatalogHandle>,+ buffer: usize,+ cap: usize,+ ) -> EventDispatcher {+ let sink: Arc<dyn MembershipSink> = Arc::new(CaptureSink::new());+ EventDispatcher::new(+ PartitionRouter::with_intake_cap(buffer, cap),+ Arc::new(OffsetTracker::new()),+ store.clone(),+ catalog,+ sink,+ MergeWorkerDeps::capture(),+ )+ }+fn held_offsets(messages: &[ShuffleMessage]) -> Vec<i64> {messages.iter()@@ -2126,6 +2145,46 @@ mod tests {);}+ #[tokio::test]+ 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);+ dispatcher.assign_partition(0);+ let mut rx = dispatcher.router.add_partition(0).unwrap();+ let no_held = HashSet::new();++ // Batch A fills the one-event budget and raises the ceiling to 105.+ assert!(dispatcher+ .dispatch_events_nonblocking(vec![consumed(person(1), 0, 104)], &no_held)+ .is_empty());+ // Batch B is refused by the event cap even though 15 slots remain free.+ let mut full =+ dispatcher.dispatch_events_nonblocking(vec![consumed(person(2), 0, 105)], &no_held);+ let held = full.remove(&0).expect("partition 0 held on the event cap");+ assert_eq!(held_offsets(&held), vec![105]);+ assert_eq!(+ dispatcher.tracker().mark_processed(0, 106),+ MarkOutcome::CappedAheadOfDispatch,+ "the held event stays above the dispatch ceiling",+ );++ // 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();+ assert!(+ rx.try_recv().is_err(),+ "channel drained; the recv released A's budget",+ );+ assert!(+ dispatcher.redispatch_held(vec![(0, held)]).is_empty(),+ "the held batch flushes once the event budget frees",+ );+ assert_eq!(+ dispatcher.tracker().mark_processed(0, 106),+ MarkOutcome::WithinDispatch,+ );+ }+#[tokio::test]async fn nonblocking_dispatch_defers_events_for_a_held_partition_even_with_room() {let (_dir, store) = temp_store();diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rsindex 74e38f59686f..6ff5d12e9d00 100644--- a/rust/cohort-stream-processor/src/main.rs+++ b/rust/cohort-stream-processor/src/main.rs@@ -39,7 +39,7 @@ use cohort_stream_processor::store::durability::{S3Uploader, TrackedTopic, CHECKPOINT_LOOP_NAME,};use cohort_stream_processor::store::CohortStore;-use cohort_stream_processor::sweep::{run_sweep_loop, DispatchSweeper};+use cohort_stream_processor::sweep::{run_sweep_loop, run_sweep_loop_delayed, DispatchSweeper};use cohort_stream_processor::workers::MergeWorkerDeps;common_alloc::used!();@@ -152,7 +152,10 @@ async fn async_main(config: Config) -> Result<()> {"opening RocksDB state store",);let store = CohortStore::open(&store_config).context("opening RocksDB state store")?;- let router = PartitionRouter::new(config.partition_channel_buffer);+ let router = PartitionRouter::with_intake_cap(+ config.partition_channel_buffer,+ config.partition_intake_max_events,+ );let offset_tracker = Arc::new(OffsetTracker::new());let kafka_config = config.build_kafka_config();@@ -381,7 +384,10 @@ async fn async_main(config: Config) -> Result<()> {consumer_handle.shutdown_token(),));- tokio::spawn(run_sweep_loop(+ // Hold the first eviction pass past the boot window so its read burst doesn't stack on backlog+ // catch-up; only the eviction sweep is delayed.+ tokio::spawn(run_sweep_loop_delayed(+ config.first_eviction_sweep_delay(),DispatchSweeper::new(dispatcher.clone(), config.sweep_safety_margin_ms as i64),config.sweep_interval(),"eviction",diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rsindex 7c0b65363fed..11de97542ea8 100644--- a/rust/cohort-stream-processor/src/observability/metrics.rs+++ b/rust/cohort-stream-processor/src/observability/metrics.rs@@ -207,6 +207,10 @@ pub const PARTITION_CHANNEL_DEPTH: &str = "partition_channel_depth";/// 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.+pub const PARTITION_INTAKE_EVENTS: &str = "partition_intake_events";/// 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@@ -571,6 +575,7 @@ mod tests {#[test]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!(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.rsnew file mode 100644index 000000000000..1cb3892a825e--- /dev/null+++ b/rust/cohort-stream-processor/src/partitions/intake.rs@@ -0,0 +1,271 @@+//! App-side intake backpressure: a per-partition ceiling on **events** resident in a worker's+//! channel. The mpsc slots bound sub-batches; this bounds the events inside them. Over the cap, new+//! events are refused (→ held → paused), never buffered.+//!+//! The counter cannot drift: [`PartitionIntake::try_admit`] reserves a batch's events (only the+//! consume loop admits), [`MeteredReceiver`] releases them on the next `recv` and on `Drop`, and the+//! router releases eagerly when an admitted batch fails to enter the channel. Both sides count events+//! only, so maintenance ticks reserve and release 0.++use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;++use metrics::gauge;+use tokio::sync::mpsc;++use super::shuffle_message::ShuffleMessage;+use crate::observability::metrics::PARTITION_INTAKE_EVENTS;++/// Event-carrying messages in a batch. Maintenance ticks carry no offset and count 0.+pub fn count_events(batch: &[ShuffleMessage]) -> usize {+ batch+ .iter()+ .filter(|message| message.event_offset().is_some())+ .count()+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Admission {+ /// Reserved under the cap; the caller must send the batch or release the reservation.+ Admitted,+ /// At the event ceiling; the caller holds the batch and pauses the partition.+ Rejected,+}++/// Per-partition ceiling on un-drained events.+///+/// 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+/// concurrent release between its load and its add can only have freed room.+pub struct PartitionIntake {+ cap: usize,+ in_flight_events: AtomicUsize,+ partition_label: Arc<str>,+}++impl PartitionIntake {+ pub fn new(partition: i32, cap: usize) -> Self {+ Self {+ cap,+ in_flight_events: AtomicUsize::new(0),+ partition_label: Arc::from(partition.to_string()),+ }+ }++ /// Reserve `count` events if they fit under `cap`. An idle partition always admits — even an+ /// over-cap batch — so `cap` is a soft ceiling on the steady state, not a hard per-batch limit.+ ///+ /// Not a CAS: correct only because a single task (the consume loop) admits for a given partition.+ /// Two concurrent admitters could both pass the check and overshoot `cap`.+ pub fn try_admit(&self, count: usize) -> Admission {+ let current = self.in_flight_events.load(Ordering::Acquire);+ if current == 0 || current + count <= self.cap {+ self.in_flight_events.fetch_add(count, Ordering::AcqRel);+ // Sample fresh: a concurrent release may have lowered the counter below the reserved total.+ self.set_gauge(self.in_flight_events.load(Ordering::Acquire));+ Admission::Admitted+ } else {+ Admission::Rejected+ }+ }++ /// Release a reservation once its events drain (or fail to land). Saturating, so an accounting+ /// slip can't underflow into a permanent stall.+ pub fn release(&self, count: usize) {+ if count == 0 {+ return;+ }+ let mut current = self.in_flight_events.load(Ordering::Acquire);+ loop {+ let next = current.saturating_sub(count);+ match self.in_flight_events.compare_exchange_weak(+ current,+ next,+ Ordering::AcqRel,+ Ordering::Acquire,+ ) {+ Ok(_) => {+ self.set_gauge(next);+ return;+ }+ Err(observed) => current = observed,+ }+ }+ }++ pub fn in_flight(&self) -> usize {+ self.in_flight_events.load(Ordering::Acquire)+ }++ fn set_gauge(&self, value: usize) {+ gauge!(PARTITION_INTAKE_EVENTS, "partition" => self.partition_label.clone())+ .set(value as f64);+ }+}++/// Worker-side receiver that releases each batch's event reservation back to the partition's+/// [`PartitionIntake`]. Releases on the *next* `recv` and on `Drop`, so the budget also covers the+/// batch the worker currently holds.+pub struct MeteredReceiver {+ receiver: mpsc::Receiver<Vec<ShuffleMessage>>,+ intake: Arc<PartitionIntake>,+ /// Events reserved for the last batch handed out, released on the next `recv`/`Drop`.+ outstanding: usize,+}++impl MeteredReceiver {+ pub fn new(+ receiver: mpsc::Receiver<Vec<ShuffleMessage>>,+ intake: Arc<PartitionIntake>,+ ) -> Self {+ Self {+ receiver,+ intake,+ outstanding: 0,+ }+ }++ /// Uncapped intake wrapper for tests: only the mpsc slots bound.+ pub fn unmetered(receiver: mpsc::Receiver<Vec<ShuffleMessage>>) -> Self {+ Self::new(receiver, Arc::new(PartitionIntake::new(0, usize::MAX)))+ }++ /// Release the previous batch, then await the next.+ pub async fn recv(&mut self) -> Option<Vec<ShuffleMessage>> {+ self.release_outstanding();+ let batch = self.receiver.recv().await?;+ self.outstanding = count_events(&batch);+ Some(batch)+ }++ fn release_outstanding(&mut self) {+ if self.outstanding > 0 {+ self.intake.release(self.outstanding);+ self.outstanding = 0;+ }+ }++ /// Non-awaiting drain for tests; releases like [`recv`](Self::recv).+ #[cfg(test)]+ pub fn try_recv(&mut self) -> Result<Vec<ShuffleMessage>, mpsc::error::TryRecvError> {+ self.release_outstanding();+ let batch = self.receiver.try_recv()?;+ self.outstanding = count_events(&batch);+ Ok(batch)+ }+}++impl Drop for MeteredReceiver {+ fn drop(&mut self) {+ self.release_outstanding();+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::consumers::events::CohortStreamEvent;++ fn event() -> ShuffleMessage {+ ShuffleMessage::Event {+ event: Box::new(CohortStreamEvent {+ team_id: 1,+ person_id: "p".to_string(),+ distinct_id: "d".to_string(),+ uuid: "u".to_string(),+ event: "$pageview".to_string(),+ timestamp: "2026-05-26 12:34:56.789000".to_string(),+ properties: None,+ person_properties: None,+ elements_chain: None,+ source_offset: 0,+ source_partition: 0,+ redirected_from: None,+ redirect_hops: 0,+ }),+ cse_offset: 0,+ }+ }++ fn events(n: usize) -> Vec<ShuffleMessage> {+ (0..n).map(|_| event()).collect()+ }++ #[test]+ fn count_events_ignores_maintenance_messages() {+ let batch = vec![+ event(),+ ShuffleMessage::Sweep { due_before_ms: 1 },+ event(),+ ShuffleMessage::RedrivePendingTransfers,+ ];+ assert_eq!(count_events(&batch), 2);+ }++ #[test]+ fn admits_under_cap_and_rejects_over_cap() {+ let intake = PartitionIntake::new(0, 10);+ assert_eq!(intake.try_admit(6), Admission::Admitted);+ assert_eq!(intake.in_flight(), 6);+ assert_eq!(intake.try_admit(5), Admission::Rejected);+ assert_eq!(intake.in_flight(), 6);+ assert_eq!(intake.try_admit(4), Admission::Admitted);+ assert_eq!(intake.in_flight(), 10);+ }++ #[test]+ fn an_idle_partition_admits_an_over_cap_batch_for_progress() {+ let intake = PartitionIntake::new(0, 10);+ assert_eq!(intake.try_admit(25), Admission::Admitted);+ assert_eq!(intake.in_flight(), 25);+ assert_eq!(intake.try_admit(1), Admission::Rejected);+ }++ #[test]+ fn release_is_saturating() {+ let intake = PartitionIntake::new(0, 10);+ intake.try_admit(3);+ intake.release(10);+ assert_eq!(intake.in_flight(), 0);+ }++ #[tokio::test]+ async fn metered_receiver_releases_the_previous_batch_on_the_next_recv() {+ let intake = Arc::new(PartitionIntake::new(0, 100));+ let (tx, rx) = mpsc::channel(8);+ let mut rx = MeteredReceiver::new(rx, intake.clone());++ assert_eq!(intake.try_admit(3), Admission::Admitted);+ tx.send(events(3)).await.unwrap();+ assert_eq!(intake.try_admit(2), Admission::Admitted);+ tx.send(events(2)).await.unwrap();+ assert_eq!(intake.in_flight(), 5);++ assert_eq!(count_events(&rx.recv().await.unwrap()), 3);+ assert_eq!(intake.in_flight(), 5, "the in-hand batch stays counted");++ assert_eq!(count_events(&rx.recv().await.unwrap()), 2);+ assert_eq!(intake.in_flight(), 2, "recv released the previous batch");++ drop(rx);+ assert_eq!(+ intake.in_flight(),+ 0,+ "drop releases the last in-hand batch"+ );+ }++ #[tokio::test]+ async fn a_maintenance_batch_does_not_move_the_counter() {+ let intake = Arc::new(PartitionIntake::new(0, 100));+ let (tx, rx) = mpsc::channel(8);+ let mut rx = MeteredReceiver::new(rx, intake.clone());++ tx.send(vec![ShuffleMessage::Sweep { due_before_ms: 1 }])+ .await+ .unwrap();+ rx.recv().await.unwrap();+ drop(rx);+ assert_eq!(intake.in_flight(), 0);+ }+}diff --git a/rust/cohort-stream-processor/src/partitions/mod.rs b/rust/cohort-stream-processor/src/partitions/mod.rsindex 1c9d2e9b7498..28b320f16df9 100644--- a/rust/cohort-stream-processor/src/partitions/mod.rs+++ b/rust/cohort-stream-processor/src/partitions/mod.rs@@ -7,6 +7,7 @@pub mod backpressure;pub mod follower;+pub mod intake;pub mod offset_tracker;pub mod partitioner;pub mod pause;@@ -16,6 +17,7 @@ pub mod shuffle_message;pub use backpressure::Backpressure;pub use follower::{Follower, FollowerSet, PartitionMirror};+pub use intake::{Admission, MeteredReceiver, PartitionIntake};pub use offset_tracker::{MarkOutcome, OffsetTracker};pub use partitioner::{merge_partition_key, murmur2, partition_for, partition_of, COHORT_PARTITION_COUNT,diff --git a/rust/cohort-stream-processor/src/partitions/router.rs b/rust/cohort-stream-processor/src/partitions/router.rsindex f7ecbc67da86..5b6cffbce6f8 100644--- a/rust/cohort-stream-processor/src/partitions/router.rs+++ b/rust/cohort-stream-processor/src/partitions/router.rs@@ -7,6 +7,7 @@use std::collections::HashMap;use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;use dashmap::mapref::entry::Entry;use dashmap::DashMap;@@ -17,6 +18,7 @@ use tokio::sync::mpsc;use tokio::sync::mpsc::error::TrySendError;use tracing::warn;+use super::intake::{count_events, Admission, MeteredReceiver, PartitionIntake};use super::shuffle_message::ShuffleMessage;use crate::observability::metrics::{PARTITIONS_ACTIVE, PARTITION_CHANNEL_DEPTH, PARTITION_CHANNEL_FULL_TOTAL,@@ -57,30 +59,49 @@ pub enum SendOutcome {ChannelClosed,}+/// 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.+#[derive(Clone)]+struct PartitionChannel {+ sender: mpsc::Sender<Vec<ShuffleMessage>>,+ intake: Arc<PartitionIntake>,+}+/// Routes per-partition sub-batches to long-lived per-partition worker channels.pub struct PartitionRouter {- senders: DashMap<i32, mpsc::Sender<Vec<ShuffleMessage>>>,+ 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,/// Terminal: set by [`clear`](Self::clear), never unset. Read under the shard guard so no- /// sender can be registered after the clear's removal pass.+ /// 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.pub fn new(channel_buffer: usize) -> Self {+ Self::with_intake_cap(channel_buffer, usize::MAX)+ }++ pub fn with_intake_cap(channel_buffer: usize, intake_cap: usize) -> Self {Self {- senders: DashMap::new(),+ channels: DashMap::new(),channel_buffer,+ intake_cap,closed: AtomicBool::new(false),}}- /// Register a worker channel for `partition` and return its `Receiver`.+ /// Register a worker channel for `partition` and return its [`MeteredReceiver`].////// 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).- pub fn add_partition(&self, partition: i32) -> Option<mpsc::Receiver<Vec<ShuffleMessage>>> {- let entry = self.senders.entry(partition);+ /// 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> {+ let entry = self.channels.entry(partition);if self.closed.load(Ordering::SeqCst) {drop(entry);warn!(@@ -91,9 +112,9 @@ impl PartitionRouter {}let receiver = match entry {Entry::Occupied(mut slot) => {- if slot.get().is_closed() {- let (sender, receiver) = mpsc::channel(self.channel_buffer);- slot.insert(sender);+ if slot.get().sender.is_closed() {+ let (channel, receiver) = self.make_channel(partition);+ slot.insert(channel);warn!(partition,"replacing closed worker channel on reassign (previous worker exited without revoke)"@@ -108,8 +129,8 @@ impl PartitionRouter {}}Entry::Vacant(slot) => {- let (sender, receiver) = mpsc::channel(self.channel_buffer);- slot.insert(sender);+ let (channel, receiver) = self.make_channel(partition);+ slot.insert(channel);Some(receiver)}};@@ -119,9 +140,16 @@ impl PartitionRouter {receiver}+ fn make_channel(&self, partition: i32) -> (PartitionChannel, MeteredReceiver) {+ let (sender, receiver) = mpsc::channel(self.channel_buffer);+ let intake = Arc::new(PartitionIntake::new(partition, self.intake_cap));+ let metered = MeteredReceiver::new(receiver, intake.clone());+ (PartitionChannel { sender, intake }, metered)+ }+/// Drop the sender for `partition`, signalling the worker to shut down. Idempotent.pub fn remove_partition(&self, partition: i32) {- if self.senders.remove(&partition).is_some() {+ if self.channels.remove(&partition).is_some() {self.emit_active_gauge();}}@@ -129,7 +157,7 @@ impl PartitionRouter {/// Drop every sender and terminally close the router. All later `add_partition` calls refuse.pub fn clear(&self) {self.closed.store(true, Ordering::SeqCst);- self.senders.clear();+ self.channels.clear();self.emit_active_gauge();}@@ -140,6 +168,10 @@ impl PartitionRouter {/// Group a batch by partition and dispatch each sub-batch to its worker, preserving/// per-partition order. Per-partition failures are collected rather than aborting the batch.+ ///+ /// This async path does **not** apply the event-intake cap, so it must carry only maintenance/+ /// control messages (which carry no events). Events go through the bounded+ /// [`try_route_batch`](Self::try_route_batch).pub async fn route_batch(&self, messages: Vec<(i32, ShuffleMessage)>) -> Vec<RouteError> {if messages.is_empty() {return Vec::new();@@ -163,14 +195,15 @@ impl PartitionRouter {) -> Option<RouteError> {let dropped = batch.len();- let Some(sender) = self.sender_for(partition) else {+ let Some(channel) = self.channel_for(partition) else {self.record_drop(partition, dropped, REASON_NO_WORKER);return Some(RouteError::NoWorker { partition, dropped });};- match sender.send(batch).await {+ // Uncapped: control messages carry no events, so they must always flow.+ match channel.sender.send(batch).await {Ok(()) => {- self.emit_channel_depth(partition, &sender);+ self.emit_channel_depth(partition, &channel.sender);None}Err(mpsc::error::SendError(returned)) => {@@ -203,25 +236,37 @@ impl PartitionRouter {}fn try_send_to_partition(&self, partition: i32, batch: Vec<ShuffleMessage>) -> SendOutcome {- let Some(sender) = self.sender_for(partition) else {+ let Some(channel) = self.channel_for(partition) else {self.record_drop(partition, batch.len(), REASON_NO_WORKER);return SendOutcome::NoWorker;};let count = batch.len();- // `None` for an event-less batch — carried through, not defaulted to 0, so a future non-Event- // caller can't fabricate a ceiling (`route_and_fold` only marks when `Some`).+ // `None` for an event-less batch — carried through, not defaulted to 0, so a non-Event caller+ // can't fabricate a ceiling (the dispatcher only marks when `Some`).let max_offset = batch.iter().filter_map(ShuffleMessage::event_offset).max();- match sender.try_send(batch) {+ // Refuse (→ hold → pause) once the partition holds its event ceiling, before the batch reaches+ // the mpsc slot. Count events only, so an event-less batch reserves 0 and stays balanced with+ // the receiver's release.+ let events = count_events(&batch);+ if channel.intake.try_admit(events) == Admission::Rejected {+ counter!(PARTITION_CHANNEL_FULL_TOTAL, "partition" => partition.to_string())+ .increment(batch.len() as u64);+ return SendOutcome::Full(batch);+ }+ match channel.sender.try_send(batch) {Ok(()) => {- self.emit_channel_depth(partition, &sender);+ self.emit_channel_depth(partition, &channel.sender);SendOutcome::Sent { max_offset, count }}Err(TrySendError::Full(returned)) => {+ // Reserved above but the slot is full: release so the counter tracks only what landed.+ channel.intake.release(events);counter!(PARTITION_CHANNEL_FULL_TOTAL, "partition" => partition.to_string()).increment(returned.len() as u64);SendOutcome::Full(returned)}Err(TrySendError::Closed(returned)) => {+ channel.intake.release(events);self.record_drop(partition, returned.len(), REASON_CHANNEL_CLOSED);SendOutcome::ChannelClosed}@@ -229,7 +274,7 @@ impl PartitionRouter {}pub fn partition_count(&self) -> usize {- self.senders.len()+ self.channels.len()}/// Whether a worker channel is registered for `partition`.@@ -240,12 +285,12 @@ impl PartitionRouter {/// channel at all — the idle steady state — is reported absent, letting a tick skip the guaranteed/// `no_worker` no-op.pub fn has_partition(&self, partition: i32) -> bool {- self.senders.contains_key(&partition)+ self.channels.contains_key(&partition)}- fn sender_for(&self, partition: i32) -> Option<mpsc::Sender<Vec<ShuffleMessage>>> {- let sender = self.senders.get(&partition)?;- Some(sender.clone())+ /// Clone the channel out from under the shard guard so callers can send after dropping it.+ fn channel_for(&self, partition: i32) -> Option<PartitionChannel> {+ Some(self.channels.get(&partition)?.clone())}fn record_drop(&self, partition: i32, dropped: usize, reason: &'static str) {@@ -262,7 +307,7 @@ impl PartitionRouter {}fn emit_active_gauge(&self) {- gauge!(PARTITIONS_ACTIVE).set(self.senders.len() as f64);+ gauge!(PARTITIONS_ACTIVE).set(self.channels.len() as f64);}}@@ -599,4 +644,83 @@ mod tests {router.remove_partition(5);assert!(!router.has_partition(5), "absent after removal");}++ #[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 mut rx = router.add_partition(5).unwrap();++ match router+ .try_route_batch(vec![(5, event_off(1)), (5, event_off(2))])+ .remove(&5)+ {+ Some(SendOutcome::Sent { count, .. }) => assert_eq!(count, 2),+ other => panic!("expected the first two events to land, got {other:?}"),+ }+ match router.try_route_batch(vec![(5, event_off(3))]).remove(&5) {+ Some(SendOutcome::Full(returned)) => assert_eq!(tags(&returned), vec![3]),+ other => panic!("expected the over-cap event to be held, got {other:?}"),+ }++ // 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!(+ rx.try_recv().is_err(),+ "channel now empty; this recv released the drained batch",+ );+ assert!(matches!(+ router.try_route_batch(vec![(5, event_off(3))]).remove(&5),+ Some(SendOutcome::Sent { .. }),+ ));+ }++ #[tokio::test]+ async fn maintenance_sends_bypass_the_event_cap() {+ let router = PartitionRouter::with_intake_cap(16, 1);+ let mut rx = 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_batch(vec![(5, event_off(2))]).remove(&5),+ Some(SendOutcome::Full(_)),+ ),+ "the partition is at its event ceiling",+ );++ let sweep = || ShuffleMessage::Sweep { due_before_ms: 1 };+ assert!(+ router.route_batch(vec![(5, sweep())]).await.is_empty(),+ "the maintenance tick flows past a full event budget",+ );++ assert_eq!(tags(&rx.recv().await.unwrap()), vec![1]);+ assert!(+ matches!(rx.recv().await, Some(batch) if matches!(batch.as_slice(), [ShuffleMessage::Sweep { .. }])),+ "the sweep was delivered despite the full event budget",+ );+ }++ #[tokio::test]+ async fn an_idle_partition_admits_an_over_cap_batch() {+ let router = PartitionRouter::with_intake_cap(16, 2);+ let mut rx = router.add_partition(5).unwrap();++ match router+ .try_route_batch(vec![+ (5, event_off(1)),+ (5, event_off(2)),+ (5, event_off(3)),+ ])+ .remove(&5)+ {+ 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]);+ }}diff --git a/rust/cohort-stream-processor/src/sweep/mod.rs b/rust/cohort-stream-processor/src/sweep/mod.rsindex 44e9b22964db..5bdf8b4bfab6 100644--- a/rust/cohort-stream-processor/src/sweep/mod.rs+++ b/rust/cohort-stream-processor/src/sweep/mod.rs@@ -15,4 +15,4 @@ pub mod scheduler;pub use dispatch::DispatchSweeper;pub use eviction_queue::EvictionQueue;-pub use scheduler::{due_before_ms, run_sweep_loop, Sweeper};+pub use scheduler::{due_before_ms, run_sweep_loop, run_sweep_loop_delayed, Sweeper};diff --git a/rust/cohort-stream-processor/src/sweep/scheduler.rs b/rust/cohort-stream-processor/src/sweep/scheduler.rsindex 10226bd5732c..27592919457c 100644--- a/rust/cohort-stream-processor/src/sweep/scheduler.rs+++ b/rust/cohort-stream-processor/src/sweep/scheduler.rs@@ -77,6 +77,31 @@ pub async fn run_sweep_loop<S: Sweeper>(}}+/// [`run_sweep_loop`] with its first pass held for `first_delay`; the rest of the cadence is+/// unchanged. `cancel` is honored during the delay. Keeps the eviction sweep's overdue-eviction read+/// burst from firing into a cold, idle store during backlog catch-up.+pub async fn run_sweep_loop_delayed<S: Sweeper>(+ first_delay: Duration,+ sweeper: S,+ interval: Duration,+ loop_name: &'static str,+ cancel: CancellationToken,+) {+ info!(+ first_delay_ms = first_delay.as_millis(),+ loop_name, "sweep loop deferring its first pass"+ );+ tokio::select! {+ biased;+ _ = cancel.cancelled() => {+ info!(loop_name, "sweep loop stopping during startup delay");+ return;+ }+ _ = tokio::time::sleep(first_delay) => {}+ }+ run_sweep_loop(sweeper, interval, loop_name, cancel).await;+}+#[cfg(test)]mod tests {use std::sync::atomic::{AtomicUsize, Ordering};@@ -156,4 +181,72 @@ mod tests {tokio::task::yield_now().await;assert_eq!(count.load(Ordering::SeqCst), after_cancel);}++ #[tokio::test(flavor = "current_thread", start_paused = true)]+ async fn delayed_loop_holds_the_first_pass_then_resumes_the_cadence() {+ let sweeper = CountingSweeper::default();+ let count = sweeper.count.clone();+ let cancel = CancellationToken::new();+ let first_delay = Duration::from_secs(120);+ let interval = Duration::from_secs(30);++ let handle = tokio::spawn(run_sweep_loop_delayed(+ first_delay,+ sweeper,+ interval,+ "eviction",+ cancel.clone(),+ ));++ // Let the task register its startup sleep at t=0 before advancing the clock.+ tokio::task::yield_now().await;++ tokio::time::advance(first_delay - Duration::from_secs(1)).await;+ tokio::task::yield_now().await;+ assert_eq!(count.load(Ordering::SeqCst), 0, "no sweep before the delay");++ tokio::time::advance(Duration::from_secs(1)).await;+ tokio::task::yield_now().await;+ assert_eq!(+ count.load(Ordering::SeqCst),+ 1,+ "first pass after the delay"+ );+ for expected in 2..=4 {+ tokio::time::advance(interval).await;+ tokio::task::yield_now().await;+ assert_eq!(count.load(Ordering::SeqCst), expected);+ }++ cancel.cancel();+ handle.await.expect("delayed sweep loop exits cleanly");+ }++ #[tokio::test(flavor = "current_thread", start_paused = true)]+ async fn delayed_loop_cancelled_mid_delay_runs_no_pass() {+ let sweeper = CountingSweeper::default();+ let count = sweeper.count.clone();+ let cancel = CancellationToken::new();+ let first_delay = Duration::from_secs(120);++ let handle = tokio::spawn(run_sweep_loop_delayed(+ first_delay,+ sweeper,+ Duration::from_secs(30),+ "eviction",+ cancel.clone(),+ ));++ tokio::time::advance(first_delay / 2).await;+ cancel.cancel();+ handle.await.expect("cancel mid-delay exits cleanly");++ tokio::time::advance(first_delay * 2).await;+ tokio::task::yield_now().await;+ assert_eq!(+ count.load(Ordering::SeqCst),+ 0,+ "cancel before the delay elapsed → no pass"+ );+ }}diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rsindex a65443ee144a..91c86289faca 100644--- a/rust/cohort-stream-processor/src/workers/worker.rs+++ b/rust/cohort-stream-processor/src/workers/worker.rs@@ -10,7 +10,6 @@ use std::sync::Arc;use std::time::{Duration, Instant};use metrics::{counter, histogram};-use tokio::sync::mpsc;use tokio::task::JoinHandle;use tracing::{info, warn};use uuid::Uuid;@@ -29,6 +28,7 @@ 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::shuffle_message::ShuffleMessage;use crate::producer::{@@ -74,7 +74,7 @@ impl Stage1Worker {#[allow(clippy::too_many_arguments)]pub fn spawn(partition_id: u16,- receiver: mpsc::Receiver<Vec<ShuffleMessage>>,+ receiver: MeteredReceiver,store: CohortStore,catalog: Arc<CatalogHandle>,sink: Arc<dyn MembershipSink>,@@ -101,7 +101,7 @@ impl Stage1Worker {#[allow(clippy::too_many_arguments)]pub fn spawn_with_memo(partition_id: u16,- receiver: mpsc::Receiver<Vec<ShuffleMessage>>,+ receiver: MeteredReceiver,store: CohortStore,catalog: Arc<CatalogHandle>,sink: Arc<dyn MembershipSink>,@@ -141,7 +141,7 @@ impl Stage1Worker {#[allow(clippy::too_many_arguments)]async fn run_worker(partition_id: u16,- mut receiver: mpsc::Receiver<Vec<ShuffleMessage>>,+ mut receiver: MeteredReceiver,store: CohortStore,catalog: Arc<CatalogHandle>,sink: Arc<dyn MembershipSink>,@@ -934,6 +934,7 @@ mod tombstone_redirect_tests {use chrono_tz::UTC;use serde_json::json;use tempfile::TempDir;+ use tokio::sync::mpsc;use crate::filters::{CohortId, FilterCatalog, TeamFiltersBuilder};use crate::merge::transfer::Tombstone;@@ -1192,6 +1193,7 @@ mod tombstone_redirect_tests {batch: Vec<ShuffleMessage>,) {let (tx, rx) = mpsc::channel(4);+ let rx = MeteredReceiver::unmetered(rx);let worker = Stage1Worker::spawn(partition_id,rx,diff --git a/rust/cohort-stream-processor/tests/events_consumer.rs b/rust/cohort-stream-processor/tests/events_consumer.rsindex d646c5b7f28f..17e94ca17ec1 100644--- a/rust/cohort-stream-processor/tests/events_consumer.rs+++ b/rust/cohort-stream-processor/tests/events_consumer.rs@@ -37,8 +37,8 @@ use cohort_stream_processor::filters::{CatalogHandle, CohortId, FilterCatalog, TeamFiltersBuilder, TeamId,};use cohort_stream_processor::partitions::{- run_rebalance_worker, CohortConsumerContext, OffsetTracker, PartitionMirror, PartitionRouter,- ShuffleMessage,+ run_rebalance_worker, CohortConsumerContext, MeteredReceiver, OffsetTracker, PartitionMirror,+ PartitionRouter, ShuffleMessage,};use cohort_stream_processor::producer::{CaptureSink, CohortMembershipChange, KafkaMembershipSink, MembershipSink, MembershipStatus,@@ -1102,6 +1102,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 worker = Stage1Worker::spawn(partition as u16,rx,@@ -1483,6 +1484,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 worker = Stage1Worker::spawn(partition as u16,rx,diff --git a/rust/cohort-stream-processor/tests/person_memo_parity.rs b/rust/cohort-stream-processor/tests/person_memo_parity.rsindex c4e02ed1c2f7..093e596380d1 100644--- a/rust/cohort-stream-processor/tests/person_memo_parity.rs+++ b/rust/cohort-stream-processor/tests/person_memo_parity.rs@@ -10,7 +10,7 @@ use cohort_stream_processor::consumers::CohortStreamEvent;use cohort_stream_processor::filters::{CatalogHandle, CohortId, FilterCatalog, Generation, TeamFilters, TeamFiltersBuilder, TeamId,};-use cohort_stream_processor::partitions::{OffsetTracker, ShuffleMessage};+use cohort_stream_processor::partitions::{MeteredReceiver, OffsetTracker, ShuffleMessage};use cohort_stream_processor::producer::{CaptureSink, MembershipStatus};use cohort_stream_processor::stage1::{LeafTransition, TransitionKind};use cohort_stream_processor::store::{CohortStore, StoreConfig};@@ -336,6 +336,7 @@ async fn run_worker_sequence(let sink = CaptureSink::new();let tracker = std::sync::Arc::new(OffsetTracker::new());let (tx, rx) = mpsc::channel(16);+ let rx = MeteredReceiver::unmetered(rx);let worker = Stage1Worker::spawn_with_memo(PARTITION,rx,diff --git a/rust/cohort-stream-processor/tests/stage1_worker.rs b/rust/cohort-stream-processor/tests/stage1_worker.rsindex 0c3a9f4678f5..db0c8baa6f29 100644--- a/rust/cohort-stream-processor/tests/stage1_worker.rs+++ b/rust/cohort-stream-processor/tests/stage1_worker.rs@@ -16,7 +16,7 @@ use cohort_stream_processor::consumers::CohortStreamEvent;use cohort_stream_processor::filters::{CatalogHandle, CohortId, FilterCatalog, TeamFilters, TeamFiltersBuilder, TeamId,};-use cohort_stream_processor::partitions::{OffsetTracker, ShuffleMessage};+use cohort_stream_processor::partitions::{MeteredReceiver, OffsetTracker, ShuffleMessage};use cohort_stream_processor::producer::{CaptureSink, MembershipStatus};use cohort_stream_processor::stage1::bucket_tz::{day_idx_in_tz, start_of_day_ms_in_tz};use cohort_stream_processor::stage1::{@@ -1045,6 +1045,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 worker = Stage1Worker::spawn(PARTITION_ID,rx,@@ -1101,6 +1102,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 worker = Stage1Worker::spawn(PARTITION_ID,rx,@@ -1168,6 +1170,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 worker = Stage1Worker::spawn(PARTITION_ID,rx,@@ -1219,6 +1222,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 worker = Stage1Worker::spawn(PARTITION_ID,rx,@@ -1253,6 +1257,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 worker = Stage1Worker::spawn(PARTITION_ID,rx,@@ -1287,6 +1292,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 worker = Stage1Worker::spawn(PARTITION_ID,rx,@@ -1317,6 +1323,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 worker = Stage1Worker::spawn(PARTITION_ID,rx,@@ -1755,6 +1762,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 worker = Stage1Worker::spawn(PARTITION_ID,rx,@@ -2086,6 +2094,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 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 ffec20d892d9..3f8a2356f9ec 100644--- a/rust/cohort-stream-processor/tests/sweep_worker.rs+++ b/rust/cohort-stream-processor/tests/sweep_worker.rs@@ -20,7 +20,9 @@ use cohort_stream_processor::consumers::{CohortStreamEvent, EventDispatcher};use cohort_stream_processor::filters::{CatalogHandle, CohortId, FilterCatalog, TeamFilters, TeamFiltersBuilder, TeamId,};-use cohort_stream_processor::partitions::{OffsetTracker, PartitionRouter, ShuffleMessage};+use cohort_stream_processor::partitions::{+ MeteredReceiver, OffsetTracker, PartitionRouter, ShuffleMessage,+};use cohort_stream_processor::producer::{CaptureSink, CohortMembershipChange, MembershipSink, MembershipStatus,};@@ -288,6 +290,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 worker = Stage1Worker::spawn(PARTITION_ID,rx,