:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(cohorts): bound the eviction sweep and interleave it with live work (#98624)
Matheus Batista5846d2adb600
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rsindex d9fb49b51704..9e5fb5189b88 100644--- a/rust/cohort-stream-processor/src/observability/metrics.rs+++ b/rust/cohort-stream-processor/src/observability/metrics.rs@@ -407,6 +407,29 @@ pub const SWEEP_CYCLES_TOTAL: &str = "sweep_cycles_total";pub const SWEEP_CYCLE_DURATION_SECONDS: &str = "sweep_cycle_duration_seconds";/// Keys the sweep evicted, labelled by `variant` (counter).pub const SWEEP_KEYS_EVICTED_TOTAL: &str = "sweep_keys_evicted_total";+/// Wall-clock duration of one sweep **batch** inside the partition worker: read, produce, commit and+/// Stage 2 composition (histogram, seconds). This is the number that says how long live traffic waits+/// behind eviction. [`SWEEP_CYCLE_DURATION_SECONDS`] does not: it times the dispatch that hands each+/// worker a request, and returns before any worker starts.+pub const SWEEP_BATCH_DURATION_SECONDS: &str = "sweep_batch_duration_seconds";+/// Time one sweep batch spent awaiting the acks of its single-leaf membership produce (histogram,+/// seconds). Splits [`SWEEP_BATCH_DURATION_SECONDS`] between the store and the delivery report:+/// every batch pays the producer's linger and a broker round trip whatever its size, which is the+/// cost a larger batch target would amortize.+pub const SWEEP_BATCH_PRODUCE_SECONDS: &str = "sweep_batch_produce_seconds";+/// Keys one sweep batch claimed out of the queue (histogram). Bounded by the batch target, except+/// where one person's group does not fit and the batch takes it whole, so the upper quantiles are+/// the wide-person signal.+pub const SWEEP_BATCH_KEYS_CLAIMED: &str = "sweep_batch_keys_claimed";+/// Raw value bytes one batched `cf_behavioral` read returned inside a sweep batch (histogram, bytes).+/// **A key limit does not bound bytes**, because behavioral values grow with window length, so read+/// this before assuming the batch target is a memory ceiling.+pub const SWEEP_READ_CHUNK_BYTES: &str = "sweep_read_chunk_bytes";+/// How far a partition's soonest queued deadline sits behind the newest cutoff the sweep was asked+/// for, labelled by `partition` (gauge, seconds). Zero when nothing is overdue. A level that grows+/// across ticks means eviction is not keeping up with the wave, which the evicted counter alone+/// cannot show.+pub const SWEEP_QUEUE_LAG_SECONDS: &str = "sweep_queue_lag_seconds";/// Person merges handled, labelled by `path` (`same_partition`|`cross_partition`) (counter).pub const MERGE_HANDLED_TOTAL: &str = "merge_handled_total";/// Drain messages short-circuited by a `cf_merge_drains_applied` hit (counter).@@ -484,9 +507,17 @@ pub const STAGE2_ORPHAN_GC_UNDECODABLE_KEYS_TOTAL: &str = "stage2_orphan_gc_unde/// `cf_stage2` keys a cohort-prefix scan could not decode and skipped (counter).pub const STAGE2_SCAN_UNDECODABLE_KEYS_TOTAL: &str = "stage2_scan_undecodable_keys_total";-/// Keys the sweep popped but did not evict, labelled by `reason` (counter). Conservation:-/// `popped == evicted + dropped`.+/// Keys the sweep claimed but did not evict, labelled by `reason` (counter). Every reason here is a+/// lost eviction. Conservation over a pass whose batches all settle: `claimed == evicted + dropped`;+/// a batch that fails its produce or commit is counted under neither until the request that retries+/// it. Keys selected but never claimed are counted under [`SWEEP_KEYS_NOT_CLAIMED_TOTAL`] instead,+/// so this counter stays summable across `reason`.pub const SWEEP_KEYS_DROPPED_TOTAL: &str = "sweep_keys_dropped_total";+/// Keys a sweep pass selected but could not claim (counter): an event rescheduled the key past the+/// cutoff, so it stays queued on its new deadline, or a merge cancelled it, so it was retired on+/// purpose. Not a lost eviction, and expected to be non-zero on an active partition. Read+/// [`SWEEP_QUEUE_LAG_SECONDS`] to size an eviction backlog.+pub const SWEEP_KEYS_NOT_CLAIMED_TOTAL: &str = "sweep_keys_not_claimed_total";/// Seed payloads consumed and decoded — tiles and ordered skips both (counter).pub const COHORT_STREAM_SEEDS_CONSUMED: &str = "cohort_stream_seeds_consumed_total";diff --git a/rust/cohort-stream-processor/src/stage2/state.rs b/rust/cohort-stream-processor/src/stage2/state.rsindex 41c90b1f6db0..6c0946c91c71 100644--- a/rust/cohort-stream-processor/src/stage2/state.rs+++ b/rust/cohort-stream-processor/src/stage2/state.rs@@ -24,8 +24,9 @@ use serde::{Deserialize, Serialize};/// Every other writer (the live event path, the sweep, the merge apply, the cascade apply,/// reconcile) writes the bit as **recomputed stage-1 truth**. A seed apply trusts such a row even/// when its writer committed before a failed produce. This also applies to legacy seed writers-/// that stored truth before producing; reconcile repairs those deliveries. See `handle_sweep` for-/// why the sweep must derive retractions from transitions even over an agreeing register.+/// that stored truth before producing; reconcile repairs those deliveries. See+/// `workers::sweep_path::PreparedSweep::absorb` for why the sweep must derive retractions from+/// transitions even over an agreeing register.////// When a row commits is a separate axis from what it records. The live event path and the merge/// apply commit with stage 1 and produce after. The single-leaf sweep commits after its producediff --git a/rust/cohort-stream-processor/src/store/staged.rs b/rust/cohort-stream-processor/src/store/staged.rsindex 6a7b0beae4dd..6031328916ed 100644--- a/rust/cohort-stream-processor/src/store/staged.rs+++ b/rust/cohort-stream-processor/src/store/staged.rs@@ -65,6 +65,17 @@ impl StagedBatch {});}+ /// [`put`](Self::put) taking the value by value, so an already-encoded buffer moves into the+ /// batch instead of being copied. For callers that encode straight into an owned `Vec`, such as+ /// the sweep's advanced eviction states.+ pub(crate) fn put_owned<K: Keyspace>(&mut self, key: &K::Key, value: Vec<u8>) {+ self.ops.push(StagedOp::Put {+ cf: K::CF,+ key: K::encode(key),+ value,+ });+ }+/// Delete a typed key from its keyspace's CF.pub fn delete<K: Keyspace>(&mut self, key: &K::Key) {self.ops.push(StagedOp::Delete {diff --git a/rust/cohort-stream-processor/src/sweep/eviction_queue.rs b/rust/cohort-stream-processor/src/sweep/eviction_queue.rsindex 3aafafcfada9..7f73fa810fb3 100644--- a/rust/cohort-stream-processor/src/sweep/eviction_queue.rs+++ b/rust/cohort-stream-processor/src/sweep/eviction_queue.rs@@ -19,16 +19,17 @@//! the superseded entry **precisely** in `O(log n)`, in either direction. `len()` therefore always//! equals the live-key count, and the staleness problem class disappears. `K` needs no `Ord` (it is//! the map *value*); `seq` is a global monotonic tiebreaker that only disambiguates two live keys-//! sharing a deadline, giving a deterministic pop order.+//! sharing a deadline, giving a deterministic selection order.use std::collections::{BTreeMap, HashMap};use std::hash::Hash;/// The ordered coordinate of a live entry: its deadline (epoch ms) plus a monotonic tiebreaker.-/// `Copy`, so it is cheaply read out of `by_deadline` before a mutating call.+/// `Copy`, so it is cheaply read out of the reverse index before a mutating call.type Coord = (i64, u64);-/// A deadline-ordered queue of keys, drained soonest-first by [`pop_due`](Self::pop_due).+/// A deadline-ordered queue of keys, drained soonest-first by [`due_keys`](Self::due_keys) ++/// [`take_due`](Self::take_due).////// Single-threaded by design: each partition worker owns one `EvictionQueue<BehavioralKey>` and is/// the only mutator, so no internal synchronization is needed. Generic over `K` purely so the@@ -38,7 +39,7 @@ type Coord = (i64, u64);/// so `by_deadline.len() == index.len() == ` the live-key count, and each key maps to exactly one/// coordinate in both directions.pub struct EvictionQueue<K> {- /// Keys ordered by `(deadline_ms, seq)`, so `first_key_value` is always the soonest due. `seq`+ /// Keys ordered by `(deadline_ms, seq)`, so the front of the map is always the soonest due. `seq`/// only breaks ties between equal deadlines.by_deadline: BTreeMap<Coord, K>,/// Reverse index `K → its live coordinate`, so a reschedule (or [`cancel`](Self::cancel)) removes@@ -76,26 +77,39 @@ whereself.index.insert(key, coord);}- /// Pop the soonest-due key whose deadline is **strictly before** `due_before_ms`, returning- /// `(key, deadline_ms)`; or [`None`] when the soonest live deadline is `>= due_before_ms` (i.e.- /// nothing is due yet). Drain a tick by calling this in a loop until it returns [`None`].+ /// The soonest-due keys whose deadline is **strictly before** `due_before_ms`, in pop order, at+ /// most `limit` of them — **without removing any of them**. Selection and removal are split so+ /// the queue stays the single source of truth for a key's deadline while a sweep pass is in+ /// flight: a selected key an event reschedules or a merge cancels is simply no longer claimable+ /// by [`take_due`](Self::take_due), instead of sitting in a copy that has to be reconciled.////// The cutoff is `due_before_ms = now_ms − safety_margin_ms`, computed by the caller (see/// [`due_before_ms`](super::scheduler::due_before_ms)) so the queue stays clock- and/// arithmetic-free.- pub fn pop_due(&mut self, due_before_ms: i64) -> Option<(K, i64)> {- // Copy the soonest coordinate out, dropping the immutable borrow before the mutating remove.- let (&coord, _) = self.by_deadline.first_key_value()?;+ pub fn due_keys(&self, due_before_ms: i64, limit: usize) -> impl Iterator<Item = &K> + '_ {+ // `seq` is unsigned, so `(due_before_ms, 0)` is the least coordinate at the cutoff: the range+ // is exactly the strictly-earlier deadlines.+ self.by_deadline+ .range(..(due_before_ms, 0))+ .map(|(_, key)| key)+ .take(limit)+ }++ /// Remove `key` only if its **current** deadline is still strictly before `due_before_ms`,+ /// returning that deadline so a failed batch can put the key back where it was. [`None`] when the+ /// key was cancelled or rescheduled to or past the cutoff since it was selected, in which case it+ /// stays queued on its live deadline.+ pub fn take_due(&mut self, key: &K, due_before_ms: i64) -> Option<i64> {+ let &coord = self.index.get(key)?;let (deadline_ms, _) = coord;if deadline_ms >= due_before_ms {return None;}- let key = self- .by_deadline+ self.by_deadline.remove(&coord)- .expect("the peeked coordinate is present");- self.index.remove(&key);- Some((key, deadline_ms))+ .expect("the indexed coordinate is present");+ self.index.remove(key);+ Some(deadline_ms)}/// Remove `key` from the queue, if present, so its pending eviction never fires.@@ -136,20 +150,34 @@ wheremod tests {use super::*;+ /// Select the soonest due key and claim it, the two-step the sweep runs. `None` when nothing is+ /// due — the shape the scheduling tests below assert against.+ fn claim_soonest_due<K: Hash + Eq + Clone>(+ queue: &mut EvictionQueue<K>,+ due_before_ms: i64,+ ) -> Option<(K, i64)> {+ let key = queue.due_keys(due_before_ms, 1).next()?.clone();+ let deadline = queue+ .take_due(&key, due_before_ms)+ .expect("a key selected as due is claimable when nothing intervened");+ Some((key, deadline))+ }+fn drain<K: Hash + Eq + Clone>(queue: &mut EvictionQueue<K>,due_before_ms: i64,) -> Vec<(K, i64)> {let mut out = Vec::new();- while let Some(entry) = queue.pop_due(due_before_ms) {+ while let Some(entry) = claim_soonest_due(queue, due_before_ms) {out.push(entry);}out}#[test]- fn pop_due_boundary_triple() {- // Strict `<`: at the exact cutoff and beyond, the key is held; one ms before, it is due.+ fn due_boundary_triple() {+ // Strict `<`, on both halves of the pair: at the exact cutoff and beyond, the key is neither+ // selected nor claimable; one ms before, it is both.let due_before = 1_000;for (deadline, should_evict) in [(due_before - 1, true),@@ -158,16 +186,67 @@ mod tests {] {let mut queue = EvictionQueue::new();queue.schedule("k", deadline);- let popped = queue.pop_due(due_before);assert_eq!(- popped.is_some(),+ queue.due_keys(due_before, 16).count(),+ usize::from(should_evict),+ "selection: deadline {deadline} vs due_before {due_before}",+ );+ assert_eq!(+ queue.take_due(&"k", due_before).is_some(),should_evict,- "deadline {deadline} vs due_before {due_before}",+ "claim: deadline {deadline} vs due_before {due_before}",);assert_eq!(queue.len(), if should_evict { 0 } else { 1 });}}+ #[test]+ fn take_due_refuses_a_key_rescheduled_past_the_cutoff_since_selection() {+ // The freshness guarantee the split buys: a key selected as due, then pushed past the cutoff+ // by an intervening event, is not claimable and stays queued on its live deadline.+ let mut queue = EvictionQueue::new();+ queue.schedule("k", 100);+ let selected: Vec<&str> = queue.due_keys(200, 16).copied().collect();+ assert_eq!(selected, vec!["k"]);++ queue.schedule("k", 900); // a late event slid the window forward+ assert_eq!(queue.take_due(&"k", 200), None);+ assert_eq!(queue.len(), 1, "the refused key stays queued");+ assert_eq!(queue.peek_next_deadline(), Some(900));+ }++ #[test]+ fn take_due_refuses_a_key_cancelled_since_selection() {+ // The other half: a merge cancels the key between selection and claim, so the claim finds+ // nothing and the eviction never fires.+ let mut queue = EvictionQueue::new();+ queue.schedule("k", 100);+ assert_eq!(queue.due_keys(200, 16).count(), 1);++ queue.cancel(&"k");+ assert_eq!(queue.take_due(&"k", 200), None);+ assert_eq!(queue.len(), 0);+ }++ #[test]+ fn due_keys_stops_at_the_limit_without_removing_anything() {+ let mut queue = EvictionQueue::new();+ for (key, deadline) in [("a", 100), ("b", 200), ("c", 300)] {+ queue.schedule(key, deadline);+ }+ let selected: Vec<&str> = queue.due_keys(1_000, 2).copied().collect();+ assert_eq!(+ selected,+ vec!["a", "b"],+ "soonest first, capped at the limit"+ );+ assert_eq!(queue.len(), 3, "selection removes nothing");++ // Selecting again returns the same keys, so a pass that abandons its candidates loses none.+ let again: Vec<&str> = queue.due_keys(1_000, 2).copied().collect();+ assert_eq!(again, selected);+ }+#[test]fn reschedule_to_later_pops_once_at_the_later_deadline() {let mut queue = EvictionQueue::new();@@ -176,12 +255,12 @@ mod tests {assert_eq!(queue.len(), 1, "reschedule must not duplicate the key");// Nothing due at the original deadline anymore.- assert_eq!(queue.pop_due(101), None);+ assert_eq!(claim_soonest_due(&mut queue, 101), None);assert_eq!(queue.len(), 1);- assert_eq!(queue.pop_due(501), Some(("k", 500)));+ assert_eq!(claim_soonest_due(&mut queue, 501), Some(("k", 500)));assert_eq!(queue.len(), 0);- assert_eq!(queue.pop_due(501), None);+ assert_eq!(claim_soonest_due(&mut queue, 501), None);}#[test]@@ -193,14 +272,14 @@ mod tests {queue.schedule("k", 200); // late event in an older bucket pulls it earlierassert_eq!(queue.len(), 1);- assert_eq!(queue.pop_due(201), Some(("k", 200)));+ assert_eq!(claim_soonest_due(&mut queue, 201), Some(("k", 200)));assert_eq!(queue.len(),0,"the superseded far-future entry must not linger",);// Draining far past the old far-future deadline yields nothing — proof it is gone.- assert_eq!(queue.pop_due(1_000_000), None);+ assert_eq!(claim_soonest_due(&mut queue, 1_000_000), None);assert_eq!(queue.peek_next_deadline(), None);}@@ -211,7 +290,7 @@ mod tests {queue.cancel(&"k");assert_eq!(queue.len(), 0);assert!(queue.is_empty());- assert_eq!(queue.pop_due(1_000_000), None);+ assert_eq!(claim_soonest_due(&mut queue, 1_000_000), None);// Cancelling an absent key is a no-op.queue.cancel(&"missing");@@ -225,20 +304,24 @@ mod tests {queue.schedule("b", 200);queue.cancel(&"a");assert_eq!(queue.len(), 1);- assert_eq!(queue.pop_due(1_000), Some(("b", 200)));+ assert_eq!(claim_soonest_due(&mut queue, 1_000), Some(("b", 200)));}#[test]fn resurrection_after_pop_pops_again_at_the_new_deadline() {let mut queue = EvictionQueue::new();queue.schedule("k", 100);- assert_eq!(queue.pop_due(101), Some(("k", 100)));+ assert_eq!(claim_soonest_due(&mut queue, 101), Some(("k", 100)));assert_eq!(queue.len(), 0);queue.schedule("k", 900);assert_eq!(queue.len(), 1);- assert_eq!(queue.pop_due(200), None, "not due at the old deadline");- assert_eq!(queue.pop_due(901), Some(("k", 900)));+ assert_eq!(+ claim_soonest_due(&mut queue, 200),+ None,+ "not due at the old deadline"+ );+ assert_eq!(claim_soonest_due(&mut queue, 901), Some(("k", 900)));assert_eq!(queue.len(), 0);}@@ -258,7 +341,7 @@ mod tests {}#[test]- fn pop_due_drains_in_deadline_then_seq_order() {+ fn selection_is_in_deadline_then_seq_order() {let mut queue = EvictionQueue::new();// Insert out of deadline order, with a tie at 200.queue.schedule("late", 300);@@ -266,6 +349,13 @@ mod tests {queue.schedule("early", 100);queue.schedule("tie_second", 200);+ let selected: Vec<&str> = queue.due_keys(1_000, usize::MAX).copied().collect();+ assert_eq!(+ selected,+ vec!["early", "tie_first", "tie_second", "late"],+ "one selection pass already yields the drain order",+ );+let drained = drain(&mut queue, 1_000);assert_eq!(drained,@@ -295,21 +385,23 @@ mod tests {queue.cancel(&"a");assert_eq!(queue.peek_next_deadline(), Some(900));- assert_eq!(queue.pop_due(1_000), Some(("b", 900)));+ assert_eq!(claim_soonest_due(&mut queue, 1_000), Some(("b", 900)));assert_eq!(queue.peek_next_deadline(), None);}#[test]fn very_negative_due_before_holds_everything_without_panic() {// The caller's saturating `now − margin` (now small, margin huge) yields a far-negative- // cutoff. `pop_due` is pure arithmetic-free comparison, so it holds every real (positive)- // deadline — the safe "nothing due" direction — and never panics. See+ // cutoff. Both halves of the pair are arithmetic-free comparisons, so they hold every real+ // (positive) deadline — the safe "nothing due" direction — and never panic. See// `scheduler::tests::due_before_saturates_when_margin_exceeds_now`.let mut queue = EvictionQueue::new();queue.schedule("k", 1);let cutoff = 0_i64.saturating_sub(i64::MAX);- assert_eq!(queue.pop_due(cutoff), None);- assert_eq!(queue.pop_due(i64::MIN), None);+ assert_eq!(queue.due_keys(cutoff, usize::MAX).count(), 0);+ assert_eq!(queue.due_keys(i64::MIN, usize::MAX).count(), 0);+ assert_eq!(queue.take_due(&"k", cutoff), None);+ assert_eq!(queue.take_due(&"k", i64::MIN), None);assert_eq!(queue.len(), 1);}diff --git a/rust/cohort-stream-processor/src/sweep/mod.rs b/rust/cohort-stream-processor/src/sweep/mod.rsindex 524e42509199..c7422cc1ad6f 100644--- a/rust/cohort-stream-processor/src/sweep/mod.rs+++ b/rust/cohort-stream-processor/src/sweep/mod.rs@@ -7,7 +7,7 @@//! - [`EvictionQueue`] — the per-worker, deadline-ordered structure, drained soonest-first.//! - [`run_sweep_loop`] — the periodic timer that, each tick, asks a [`Sweeper`] to drain due keys.//! - [`due_before_ms`] — the `now − safety_margin` cutoff the worker feeds to-//! [`EvictionQueue::pop_due`].+//! [`EvictionQueue::due_keys`] and [`EvictionQueue::take_due`].pub mod dispatch;pub mod eviction_queue;diff --git a/rust/cohort-stream-processor/src/sweep/scheduler.rs b/rust/cohort-stream-processor/src/sweep/scheduler.rsindex 677c4adf2953..2a9d0c9ee963 100644--- a/rust/cohort-stream-processor/src/sweep/scheduler.rs+++ b/rust/cohort-stream-processor/src/sweep/scheduler.rs@@ -23,8 +23,8 @@ pub trait Sweeper: Send + Sync {async fn run_once(&self);}-/// The cutoff a worker passes to [`EvictionQueue::pop_due`](super::EvictionQueue::pop_due): a key is-/// due once its deadline is strictly before `now_ms − safety_margin_ms`.+/// The cutoff a worker passes to [`EvictionQueue::due_keys`](super::EvictionQueue::due_keys): a key+/// is due once its deadline is strictly before `now_ms − safety_margin_ms`.////// Centralizes the only arithmetic in the sweep so the queue stays pure. `saturating_sub` keeps it/// total: a test clock with `now_ms < safety_margin_ms` yields a far-negative cutoff — below everydiff --git a/rust/cohort-stream-processor/src/workers/mod.rs b/rust/cohort-stream-processor/src/workers/mod.rsindex 41052bc5eefa..452d0c489e21 100644--- a/rust/cohort-stream-processor/src/workers/mod.rs+++ b/rust/cohort-stream-processor/src/workers/mod.rs@@ -13,6 +13,7 @@ pub mod stage2_gc;pub mod stage2_path;pub mod stage2_person_inputs;pub mod sweep_callback;+pub mod sweep_path;pub mod worker;pub use event_path::{diff --git a/rust/cohort-stream-processor/src/workers/sweep_callback.rs b/rust/cohort-stream-processor/src/workers/sweep_callback.rsindex d89db4c5c615..0f18ca5c957c 100644--- a/rust/cohort-stream-processor/src/workers/sweep_callback.rs+++ b/rust/cohort-stream-processor/src/workers/sweep_callback.rs@@ -41,7 +41,7 @@ pub(crate) struct EvictionResult {pub reschedule: Option<i64>,}-/// Why the sweep dropped a popped key instead of evicting it.+/// Why the sweep dropped a claimed key instead of evicting it.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub(crate) enum SweepDropReason {TeamDrift,diff --git a/rust/cohort-stream-processor/src/workers/sweep_path.rs b/rust/cohort-stream-processor/src/workers/sweep_path.rsnew file mode 100644index 000000000000..745aee1ce390--- /dev/null+++ b/rust/cohort-stream-processor/src/workers/sweep_path.rs@@ -0,0 +1,835 @@+//! Bounded, resumable eviction sweeps: turning one `Sweep` request into small batches the worker+//! interleaves with live traffic.+//!+//! A `Sweep` message records a request on [`SweepSchedule`], which the worker's turn loop drains one+//! [`SweepBatch`] at a time, alternating with live batches so a wave of tz-midnight deadlines cannot+//! hold the partition. Each batch reads, produces, commits and recomposes on its own, so peak memory+//! tracks the batch rather than the whole wave.+//!+//! Selection and claim are split across [`EvictionQueue::due_keys`] and+//! [`EvictionQueue::take_due`]: a pass plans over candidates but the queue stays authoritative, so+//! an event that reschedules a candidate or a merge that cancels one wins over the plan. The+//! per-key eviction arithmetic itself is unchanged, in [`super::sweep_callback`].++use std::collections::{BTreeMap, VecDeque};+use std::sync::Arc;+use std::time::Instant;++use metrics::{counter, gauge, histogram};+use tracing::warn;++use crate::filters::manager::CatalogHandle;+use crate::filters::reverse_index::TeamFilters;+use crate::filters::TeamId;+use crate::observability::metrics::{+ STAGE1_TRANSITIONS, SWEEP_BATCH_DURATION_SECONDS, SWEEP_BATCH_KEYS_CLAIMED,+ SWEEP_BATCH_PRODUCE_SECONDS, SWEEP_KEYS_DROPPED_TOTAL, SWEEP_KEYS_EVICTED_TOTAL,+ SWEEP_KEYS_NOT_CLAIMED_TOTAL, SWEEP_QUEUE_LAG_SECONDS, SWEEP_READ_CHUNK_BYTES,+};+use crate::producer::{map_transition, CohortMembershipChange, LastUpdatedClock, MembershipSink};+use crate::stage1::key::LeafStateKey;+use crate::stage1::state::StateVariant;+use crate::stage1::transition::LeafTransition;+use crate::stage2::{single_leaf_transition_register_writes, stage_register_writes};+use crate::store::{+ Behavioral, BehavioralKey, PersonPrefix, ReadLane, StagedBatch, StoreError, StoreHandle,+};+use crate::sweep::EvictionQueue;+use crate::workers::merge_path::MergeWorkerDeps;+use crate::workers::stage2_path::compose_stage2;+use crate::workers::sweep_callback::{+ sweep_evict, EvictionAction, EvictionResult, SweepDropReason, SweepEvictions,+};+use crate::workers::worker::{+ affected_leaves, first_cascades, produce_cascades, produce_membership, transition_metric_label,+};++/// Max eviction keys one request plans over. Daily-bucket deadlines cluster on tz-midnight, so a+/// large team's whole wave can come due on one tick; capping selection bounds how far ahead of the+/// queue a pass can plan. Leftover due keys stay scheduled and drain on the next request.+///+/// The budget is spent on selection, not on eviction: a candidate an event reschedules or a merge+/// cancels between selection and claim still counts against it, so a pass on a churning partition+/// can evict well under this many keys. Do not read it as a per-tick drain rate.+const MAX_SWEEP_KEYS_PER_PASS: usize = 10_000;++/// Keys one batch aims to claim, and the widest `cf_behavioral` read it issues. Person groups pack+/// whole, so a batch can overshoot this by one group: a batch under half full takes the next group+/// whatever its size, and a person with more leaves than this otherwise starts a batch and runs+/// alone. This bounds the ordinary batch; it is not a byte limit, because one behavioral value grows+/// with window length.+///+/// Whole-group packing holds **within** a pass. [`MAX_SWEEP_KEYS_PER_PASS`] cuts the flat,+/// deadline-ordered candidate list before grouping, so a person whose leaves carry different+/// deadlines can still straddle two passes and compose against half their eviction in between. The+/// next pass picks up the rest and the composition converges.+const SWEEP_BATCH_KEYS: usize = 256;++/// The worker's eviction-sweep state: at most one pass in flight and one coalesced follow-up cutoff.+///+/// Owned by the partition worker, mutated only from its turn loop.+pub(crate) struct SweepSchedule {+ partition_label: Arc<str>,+ active: Option<SweepPass>,+ /// The greatest cutoff requested that no pass has started on yet. One slot is enough: a later+ /// cutoff subsumes an earlier one over the same queue, so requests coalesce.+ pending_cutoff: Option<i64>,+ /// A live batch has run since the last sweep batch, so the sweep is owed the next turn.+ turn_owed: bool,+}++impl SweepSchedule {+ pub(crate) fn new(partition_id: u16) -> Self {+ Self {+ partition_label: Arc::from(partition_id.to_string()),+ active: None,+ pending_cutoff: None,+ turn_owed: false,+ }+ }++ /// Record an eviction request for `due_before_ms`. Never runs anything: the turn loop decides+ /// when the work happens.+ pub(crate) fn request(&mut self, due_before_ms: i64, queue: &EvictionQueue<BehavioralKey>) {+ self.pending_cutoff = Some(+ self.pending_cutoff+ .map_or(due_before_ms, |pending| pending.max(due_before_ms)),+ );+ self.record_queue_lag(queue);+ }++ /// Whether a batch is still available to run.+ pub(crate) fn has_work(&self) -> bool {+ self.pending_cutoff.is_some()+ || self+ .active+ .as_ref()+ .is_some_and(|pass| !pass.is_exhausted())+ }++ /// Whether the sweep must take this turn ahead of a ready live batch. True only after a live+ /// batch has run, which is what makes the two lanes alternate instead of live starving eviction.+ pub(crate) fn owes_turn(&self) -> bool {+ self.turn_owed && self.has_work()+ }++ /// A live batch finished its output and progress handling, so the sweep is owed the next turn.+ pub(crate) fn live_batch_done(&mut self) {+ self.turn_owed = true;+ }++ /// Claim the next batch, starting a pass from the pending cutoff and retiring an exhausted one+ /// as needed. [`None`] once nothing is due.+ fn next_batch(&mut self, queue: &mut EvictionQueue<BehavioralKey>) -> Option<SweepBatch> {+ // The turn is spent whether or not it yields work, so a retired pass cannot re-enter the+ // loop on the same alternation slot.+ self.turn_owed = false;+ loop {+ if self.active.is_none() {+ let cutoff = self.pending_cutoff.take()?;+ self.active = Some(SweepPass::select(queue, cutoff));+ }+ let pass = self.active.as_mut().expect("a pass was just started");+ if let Some(batch) = pass.next_batch(queue) {+ return Some(batch);+ }+ self.active = None;+ }+ }++ /// The newest cutoff the sweep knows about: the pending request, or the pass in flight.+ fn newest_cutoff(&self) -> Option<i64> {+ let active = self.active.as_ref().map(|pass| pass.due_before_ms);+ match (active, self.pending_cutoff) {+ (Some(active), Some(pending)) => Some(active.max(pending)),+ (active, pending) => active.or(pending),+ }+ }++ fn record_queue_lag(&self, queue: &EvictionQueue<BehavioralKey>) {+ let lag_ms = match (queue.peek_next_deadline(), self.newest_cutoff()) {+ (Some(oldest), Some(cutoff)) => cutoff.saturating_sub(oldest).max(0),+ _ => 0,+ };+ gauge!(SWEEP_QUEUE_LAG_SECONDS, "partition" => self.partition_label.clone())+ .set(lag_ms as f64 / 1_000.0);+ }+}++impl Drop for SweepSchedule {+ /// Zero the partition's lag gauge when the worker exits, so a revoked partition's last value+ /// does not pin. A frozen series reads exactly like the backlog the gauge exists to warn about.+ fn drop(&mut self) {+ gauge!(SWEEP_QUEUE_LAG_SECONDS, "partition" => self.partition_label.clone()).set(0.0);+ }+}++/// One request's candidates: a fixed cutoff and the persons selected from the queue when the pass+/// started, at most [`MAX_SWEEP_KEYS_PER_PASS`] keys across them.+///+/// Holds no state values and no deadlines. `PersonPrefix` orders by `(partition, team, person)`, so+/// popping from the front walks one team at a time.+struct SweepPass {+ due_before_ms: i64,+ groups: VecDeque<(PersonPrefix, Vec<LeafStateKey>)>,+}++impl SweepPass {+ fn select(queue: &EvictionQueue<BehavioralKey>, due_before_ms: i64) -> Self {+ let mut by_person: BTreeMap<PersonPrefix, Vec<LeafStateKey>> = BTreeMap::new();+ for key in queue.due_keys(due_before_ms, MAX_SWEEP_KEYS_PER_PASS) {+ by_person.entry(key.prefix).or_default().push(key.lsk);+ }+ Self {+ due_before_ms,+ groups: by_person.into_iter().collect(),+ }+ }++ fn is_exhausted(&self) -> bool {+ self.groups.is_empty()+ }++ /// Pack whole person groups from one team up to [`SWEEP_BATCH_KEYS`] and claim each of their+ /// keys out of the queue. Skips over persons whose keys all stopped being due.+ fn next_batch(&mut self, queue: &mut EvictionQueue<BehavioralKey>) -> Option<SweepBatch> {+ loop {+ let team_id = self.groups.front().map(|(prefix, _)| prefix.team_id)?;+ let mut claimed: Vec<(BehavioralKey, i64)> = Vec::with_capacity(SWEEP_BATCH_KEYS);+ loop {+ let Some((prefix, leaves)) = self.groups.front() else {+ break;+ };+ // One team per batch: the filter snapshot and the Stage 2 composition are per team.+ if prefix.team_id != team_id {+ break;+ }+ // Whole groups only, so composition sees a person's combined eviction. The cap+ // applies once the batch is at least half full: `leaves` counts selections, not+ // claims, so a run of persons whose keys mostly went stale would otherwise shrink+ // a batch to a key or two. A person wider than the target therefore starts a batch+ // and runs alone, unless an under-half batch takes it.+ if claimed.len() >= SWEEP_BATCH_KEYS / 2+ && claimed.len() + leaves.len() > SWEEP_BATCH_KEYS+ {+ break;+ }+ let (prefix, leaves) = self.groups.pop_front().expect("the front was just read");+ let mut not_claimed = 0u64;+ for lsk in leaves {+ let key = prefix.behavioral_key(lsk);+ match queue.take_due(&key, self.due_before_ms) {+ Some(deadline) => claimed.push((key, deadline)),+ // Rescheduled past the cutoff, or cancelled by a merge, since selection.+ // A rescheduled key stays queued on its live deadline and a cancelled one+ // was retired deliberately, so either way this is a skipped plan rather+ // than a lost eviction.+ None => not_claimed += 1,+ }+ }+ // Once per person, not per key: this loop can walk a whole stale pass in one call.+ if not_claimed > 0 {+ counter!(SWEEP_KEYS_NOT_CLAIMED_TOTAL).increment(not_claimed);+ }+ }+ if !claimed.is_empty() {+ return Some(SweepBatch {+ team_id,+ due_before_ms: self.due_before_ms,+ claimed,+ });+ }+ // Every person in that run had gone stale. Keep packing rather than spending the turn+ // on an empty batch.+ }+ }+}++/// The keys one turn claimed: whole person groups from a single team, each with the deadline it was+/// claimed at so a failed batch can put them back exactly where they were.+///+/// Constructed only by [`SweepPass::next_batch`], so the single-team, whole-person boundary the+/// composition depends on cannot be bypassed.+pub(crate) struct SweepBatch {+ team_id: u64,+ due_before_ms: i64,+ claimed: Vec<(BehavioralKey, i64)>,+}++/// What one batch's reads produced, before any of it is applied: the writes to commit, the changes+/// to produce, the transitions Stage 2 recomposes from, the deadlines to re-arm, and the outcome+/// records for the counters. Values read from the store are decoded into this and dropped, so a+/// batch retains prepared writes rather than raw rows.+#[derive(Default)]+struct PreparedSweep {+ staged: StagedBatch,+ changes: Vec<CohortMembershipChange>,+ transitions: Vec<LeafTransition>,+ reschedules: Vec<(BehavioralKey, i64)>,+ evicted: Vec<StateVariant>,+ drops: Vec<SweepDropReason>,+}++impl PreparedSweep {+ fn absorb(+ &mut self,+ partition_id: u16,+ filters: &TeamFilters,+ evictions: SweepEvictions,+ due_before_ms: i64,+ last_updated: &str,+ ) {+ for result in evictions.results {+ let EvictionResult {+ key,+ variant,+ transition,+ action,+ reschedule,+ } = result;+ match action {+ EvictionAction::Write(bytes) => self.staged.put_owned::<Behavioral>(&key, bytes),+ EvictionAction::Delete => self.staged.delete::<Behavioral>(&key),+ }+ if let Some(transition) = transition {+ if let Some(kind) = transition_metric_label(filters, &transition) {+ counter!(STAGE1_TRANSITIONS, "kind" => kind).increment(1);+ }+ self.changes+ .extend(map_transition(filters, &transition, last_updated));+ // Keep this leg transition-based. The seed paths derive their single-leaf changes by+ // diffing this register, and between a seed's acked produce and its post-ack commit+ // the register reads `false` while downstream holds `Entered`. A register-diffed+ // sweep would compute `false == false` there and emit no `Left`, so the entry would+ // outlive the state that justified it. At most one of the path that emits an entry+ // and the path that retracts it may read the register.+ stage_register_writes(+ &mut self.staged,+ single_leaf_transition_register_writes(+ filters,+ partition_id,+ &transition,+ due_before_ms,+ ),+ );+ self.transitions.push(transition);+ }+ if let Some(deadline) = reschedule {+ self.reschedules.push((key, deadline));+ }+ self.evicted.push(variant);+ }+ self.drops.extend(evictions.drops);+ }+}++/// Run at most one sweep batch, then return so the worker can select again. No-op when nothing is+/// due.+#[allow(clippy::too_many_arguments)]+pub(crate) async fn run_sweep_turn(+ partition_id: u16,+ handle: &StoreHandle,+ catalog: &CatalogHandle,+ sink: &Arc<dyn MembershipSink>,+ merge: &MergeWorkerDeps,+ queue: &mut EvictionQueue<BehavioralKey>,+ clock: &mut LastUpdatedClock,+ schedule: &mut SweepSchedule,+) {+ let Some(batch) = schedule.next_batch(queue) else {+ return;+ };+ let started = Instant::now();+ run_batch(+ partition_id,+ handle,+ catalog,+ sink,+ merge,+ queue,+ clock,+ &batch,+ )+ .await;+ histogram!(SWEEP_BATCH_DURATION_SECONDS).record(started.elapsed().as_secs_f64());+ schedule.record_queue_lag(queue);+}++#[allow(clippy::too_many_arguments)]+async fn run_batch(+ partition_id: u16,+ handle: &StoreHandle,+ catalog: &CatalogHandle,+ sink: &Arc<dyn MembershipSink>,+ merge: &MergeWorkerDeps,+ queue: &mut EvictionQueue<BehavioralKey>,+ clock: &mut LastUpdatedClock,+ batch: &SweepBatch,+) {+ histogram!(SWEEP_BATCH_KEYS_CLAIMED).record(batch.claimed.len() as f64);+ // One snapshot held to the end: a catalog refresh mid-batch must not split one person's eviction+ // across two views of the team.+ let snapshot = catalog.load();+ let Some(filters) = snapshot.team(TeamId(batch.team_id as i32)) else {+ // Terminal, unlike the three legs below: with the team gone from the snapshot there is+ // nothing to evict against, and a rescheduled key would be re-selected and re-dropped on+ // every pass.+ counter!(SWEEP_KEYS_DROPPED_TOTAL, "reason" => SweepDropReason::TeamDrift.as_str())+ .increment(batch.claimed.len() as u64);+ return;+ };+ let filters: &TeamFilters = filters;+ // Taken per batch, after whatever live output ran in between, so a resumed sweep never stamps a+ // change older than one a later live batch already emitted.+ let last_updated = clock.next();++ let prepared = match prepare(partition_id, handle, filters, batch, &last_updated).await {+ Ok(prepared) => prepared,+ Err(error) => {+ warn!(+ partition_id,+ team_id = batch.team_id,+ error = %error,+ "sweep state read failed; rescheduling the batch's keys for retry",+ );+ reschedule(queue, batch);+ return;+ }+ };+ let PreparedSweep {+ staged,+ changes,+ transitions,+ reschedules,+ evicted,+ drops,+ } = prepared;++ if !changes.is_empty() {+ let produce_started = Instant::now();+ let errors = produce_membership(sink, changes).await;+ histogram!(SWEEP_BATCH_PRODUCE_SECONDS).record(produce_started.elapsed().as_secs_f64());+ if errors > 0 {+ warn!(+ partition_id,+ errors, "sweep produce to the membership topic failed; rescheduling for replay",+ );+ reschedule(queue, batch);+ return;+ }+ }++ if !staged.is_empty() {+ if let Err(error) = handle.commit(staged).await {+ warn!(+ partition_id,+ error = %error,+ "sweep state write failed; rescheduling claimed keys to retry the eviction",+ );+ reschedule(queue, batch);+ return;+ }+ }++ for (key, deadline) in reschedules {+ queue.schedule(key, deadline);+ }+ for variant in evicted {+ counter!(SWEEP_KEYS_EVICTED_TOTAL, "variant" => variant.as_str()).increment(1);+ }+ for reason in drops {+ counter!(SWEEP_KEYS_DROPPED_TOTAL, "reason" => reason.as_str()).increment(1);+ }++ if transitions.is_empty() {+ return;+ }+ let stage2_changes = match compose_stage2(+ partition_id,+ handle,+ filters,+ &affected_leaves(&transitions),+ batch.due_before_ms,+ &last_updated,+ ReadLane::Event,+ )+ .await+ {+ Ok(changes) => changes,+ Err(error) => {+ warn!(+ partition_id,+ team_id = batch.team_id,+ error = %error,+ "sweep stage 2 composition failed; skipping (self-heals on the person's next event)",+ );+ return;+ }+ };+ if stage2_changes.is_empty() {+ return;+ }++ // Only Stage 2 membership changes cascade; single-leaf evictions self-heal on the referrer's next event.+ let cascades = first_cascades(merge, &stage2_changes, 0);+ let errors = produce_membership(sink, stage2_changes).await;+ if errors > 0 {+ warn!(+ partition_id,+ errors,+ "sweep stage 2 produce to the membership topic failed; dropping (cf_stage2 already committed, at-most-once)",+ );+ return;+ }+ let cascade_errors = produce_cascades(merge, cascades).await;+ if cascade_errors > 0 {+ warn!(+ partition_id,+ errors = cascade_errors,+ "sweep cascade produce failed; dropping (at-most-once). Recovery depends on each referrer being re-evaluated on its next event; the sweep does not re-evaluate cohort-ref shapes with no behavioral leaf",+ );+ }+}++/// Read the batch's states and fold them into the writes, changes and schedules they imply. An+/// ordinary batch is one read, because it was packed to [`SWEEP_BATCH_KEYS`], which is also the read+/// width. Only a batch that overshot the target reads in several chunks, each decoded and dropped+/// before the next is fetched.+async fn prepare(+ partition_id: u16,+ handle: &StoreHandle,+ filters: &TeamFilters,+ batch: &SweepBatch,+ last_updated: &str,+) -> Result<PreparedSweep, StoreError> {+ let mut prepared = PreparedSweep::default();+ for chunk in batch.claimed.chunks(SWEEP_BATCH_KEYS) {+ let keys: Vec<BehavioralKey> = chunk.iter().map(|&(key, _)| key).collect();+ // Cloned, not moved: the read takes its keys by value so its closure is `'static`, and the+ // eviction pass below still needs them to align each value with its key.+ let values = handle+ .multi_get_behavioral(keys.clone(), ReadLane::Maintenance)+ .await?;+ let raw_bytes: usize = values.iter().flatten().map(Vec::len).sum();+ histogram!(SWEEP_READ_CHUNK_BYTES).record(raw_bytes as f64);+ let evictions = sweep_evict(filters, &keys, values, batch.due_before_ms);+ prepared.absorb(+ partition_id,+ filters,+ evictions,+ batch.due_before_ms,+ last_updated,+ );+ }+ Ok(prepared)+}++/// Put a failed batch's keys back on the deadlines they were claimed at, so a later request retries+/// them. Batches that already settled stay settled. The deadline is restored exactly; the position+/// within its tier is not, because [`EvictionQueue::schedule`] mints a fresh tiebreaker.+fn reschedule(queue: &mut EvictionQueue<BehavioralKey>, batch: &SweepBatch) {+ for &(key, deadline) in &batch.claimed {+ queue.schedule(key, deadline);+ }+}++#[cfg(test)]+mod tests {+ use uuid::Uuid;++ use super::*;++ const TEAM: u64 = 7;+ const OTHER_TEAM: u64 = 8;+ const CUTOFF: i64 = 1_000;++ fn key(team_id: u64, person: u128, leaf: u128) -> BehavioralKey {+ BehavioralKey::new(+ 0,+ team_id,+ Uuid::from_u128(person),+ LeafStateKey(leaf.to_le_bytes()),+ )+ }++ fn queue_of(entries: &[(BehavioralKey, i64)]) -> EvictionQueue<BehavioralKey> {+ let mut queue = EvictionQueue::new();+ for &(key, deadline) in entries {+ queue.schedule(key, deadline);+ }+ queue+ }++ fn drain_batches(+ pass: &mut SweepPass,+ queue: &mut EvictionQueue<BehavioralKey>,+ ) -> Vec<SweepBatch> {+ let mut out = Vec::new();+ while let Some(batch) = pass.next_batch(queue) {+ out.push(batch);+ }+ out+ }++ #[test]+ fn a_batch_never_spans_two_teams() {+ let entries: Vec<(BehavioralKey, i64)> = [TEAM, OTHER_TEAM]+ .into_iter()+ .flat_map(|team| (0..4).map(move |person| (key(team, person, 0), 100)))+ .collect();+ let mut queue = queue_of(&entries);+ let mut pass = SweepPass::select(&queue, CUTOFF);++ let batches = drain_batches(&mut pass, &mut queue);+ assert_eq!(+ batches.len(),+ 2,+ "one batch per team, both well under the target"+ );+ assert_eq!(batches[0].team_id, TEAM);+ assert_eq!(batches[1].team_id, OTHER_TEAM);+ assert!(queue.is_empty(), "every due key was claimed");+ }++ #[test]+ fn a_persons_leaves_are_never_split_across_batches() {+ // Two persons of 200 leaves each: packing whole groups puts them in separate batches rather+ // than filling the first to exactly 256.+ let entries: Vec<(BehavioralKey, i64)> = (0..2)+ .flat_map(|person| (0..200).map(move |leaf| (key(TEAM, person, leaf), 100)))+ .collect();+ let mut queue = queue_of(&entries);+ let mut pass = SweepPass::select(&queue, CUTOFF);++ let batches = drain_batches(&mut pass, &mut queue);+ let sizes: Vec<usize> = batches.iter().map(|batch| batch.claimed.len()).collect();+ assert_eq!(sizes, vec![200, 200]);+ for batch in &batches {+ let persons: Vec<Uuid> = batch+ .claimed+ .iter()+ .map(|&(key, _)| key.person_id())+ .collect();+ assert!(+ persons.windows(2).all(|pair| pair[0] == pair[1]),+ "a batch carries one person's whole group",+ );+ }+ }++ #[test]+ fn a_person_wider_than_the_target_runs_alone() {+ let wide: Vec<(BehavioralKey, i64)> = (0..SWEEP_BATCH_KEYS + 50)+ .map(|leaf| (key(TEAM, 1, leaf as u128), 100))+ .collect();+ let mut entries = wide.clone();+ entries.push((key(TEAM, 2, 0), 100));+ let mut queue = queue_of(&entries);+ let mut pass = SweepPass::select(&queue, CUTOFF);++ let batches = drain_batches(&mut pass, &mut queue);+ assert_eq!(batches.len(), 2);+ assert_eq!(+ batches[0].claimed.len(),+ wide.len(),+ "the wide person is not split"+ );+ assert_eq!(batches[1].claimed.len(), 1);+ }++ #[test]+ fn stale_selections_do_not_count_against_the_batch_cap() {+ // Four persons selected at the target width each, all but one leaf rescheduled since. A cap+ // measured against selections would refuse the second person next to a single claim and+ // ship four one-key batches.+ let live: Vec<(BehavioralKey, i64)> =+ (0..4).map(|person| (key(TEAM, person, 0), 100)).collect();+ let stale: Vec<(BehavioralKey, i64)> = (0..4)+ .flat_map(|person| {+ (1..SWEEP_BATCH_KEYS).map(move |leaf| (key(TEAM, person, leaf as u128), 100))+ })+ .collect();+ let mut queue = queue_of(&[live.clone(), stale.clone()].concat());+ let mut pass = SweepPass::select(&queue, CUTOFF);+ for &(key, _) in &stale {+ queue.schedule(key, CUTOFF + 500);+ }++ let batches = drain_batches(&mut pass, &mut queue);+ let sizes: Vec<usize> = batches.iter().map(|batch| batch.claimed.len()).collect();+ assert_eq!(+ sizes,+ vec![live.len()],+ "the four claims pack into one batch"+ );+ }++ #[test]+ fn selection_caps_at_the_pass_limit_and_leaves_the_rest_queued() {+ let total = MAX_SWEEP_KEYS_PER_PASS + 10;+ // One shared deadline, the tz-midnight shape: selection order is then insertion order.+ let entries: Vec<(BehavioralKey, i64)> = (0..total)+ .map(|person| (key(TEAM, person as u128, 0), 100))+ .collect();+ let mut queue = queue_of(&entries);+ let mut pass = SweepPass::select(&queue, CUTOFF);++ let claimed: usize = drain_batches(&mut pass, &mut queue)+ .iter()+ .map(|batch| batch.claimed.len())+ .sum();+ assert_eq!(claimed, MAX_SWEEP_KEYS_PER_PASS);+ assert_eq!(queue.len(), 10, "the over-cap keys stay scheduled");+ }++ #[test]+ fn a_candidate_rescheduled_past_the_cutoff_is_not_claimed() {+ let stale = key(TEAM, 1, 0);+ let live = key(TEAM, 2, 0);+ let mut queue = queue_of(&[(stale, 100), (live, 100)]);+ let mut pass = SweepPass::select(&queue, CUTOFF);++ // An event lands for person 1 between selection and the batch, sliding its window forward.+ queue.schedule(stale, CUTOFF + 500);++ let batches = drain_batches(&mut pass, &mut queue);+ assert_eq!(batches.len(), 1);+ assert_eq!(+ batches[0]+ .claimed+ .iter()+ .map(|&(key, _)| key)+ .collect::<Vec<_>>(),+ vec![live],+ );+ assert_eq!(queue.len(), 1, "the rescheduled key stays queued");+ assert_eq!(queue.peek_next_deadline(), Some(CUTOFF + 500));+ }++ #[test]+ fn a_candidate_cancelled_before_its_batch_is_not_claimed() {+ let cancelled = key(TEAM, 1, 0);+ let live = key(TEAM, 2, 0);+ let mut queue = queue_of(&[(cancelled, 100), (live, 100)]);+ let mut pass = SweepPass::select(&queue, CUTOFF);++ // A merge drained person 1 and cancelled its keys.+ queue.cancel(&cancelled);++ let batches = drain_batches(&mut pass, &mut queue);+ assert_eq!(batches.len(), 1);+ assert_eq!(batches[0].claimed.len(), 1);+ assert!(queue.is_empty());+ }++ #[test]+ fn a_team_whose_every_candidate_went_stale_is_skipped_for_the_next_team() {+ // The inner loop yields an empty claim for the whole first team, so the pass must keep+ // packing into the next team rather than returning an empty batch and spending a turn.+ let stale = key(TEAM, 1, 0);+ let live = key(OTHER_TEAM, 1, 0);+ let mut queue = queue_of(&[(stale, 100), (live, 100)]);+ let mut pass = SweepPass::select(&queue, CUTOFF);++ queue.cancel(&stale);++ let batches = drain_batches(&mut pass, &mut queue);+ assert_eq!(batches.len(), 1, "no empty batch for the drained team");+ assert_eq!(batches[0].team_id, OTHER_TEAM);+ assert_eq!(batches[0].claimed.len(), 1);+ }++ #[test]+ fn a_failed_batch_returns_its_keys_on_the_deadlines_it_claimed() {+ // Two deliberately different deadlines: restoring both at the batch's soonest, or at one+ // shared value, is the easy way to get this wrong, so check each key's own deadline back.+ let (early, late) = (key(TEAM, 1, 0), key(TEAM, 1, 1));+ let mut queue = queue_of(&[(early, 100), (late, 250)]);+ let mut pass = SweepPass::select(&queue, CUTOFF);+ let batch = pass.next_batch(&mut queue).expect("one batch");+ assert!(queue.is_empty(), "claiming removes the keys");++ reschedule(&mut queue, &batch);+ assert_eq!(queue.len(), 2);+ assert_eq!(+ queue.take_due(&early, 101),+ Some(100),+ "the early key is due again one ms past its own deadline",+ );+ assert_eq!(+ queue.take_due(&late, 101),+ None,+ "the late key is not due there, so it did not inherit the early deadline",+ );+ assert_eq!(queue.take_due(&late, 251), Some(250));+ }++ #[test]+ fn requests_coalesce_onto_the_greatest_cutoff() {+ let mut queue = queue_of(&[(key(TEAM, 1, 0), 100)]);+ let mut schedule = SweepSchedule::new(0);+ assert!(!schedule.has_work());++ schedule.request(500, &queue);+ schedule.request(900, &queue);+ schedule.request(700, &queue);+ assert_eq!(schedule.newest_cutoff(), Some(900));++ let batch = schedule.next_batch(&mut queue).expect("one batch");+ assert_eq!(+ batch.due_before_ms, 900,+ "the pass runs at the greatest cutoff"+ );+ assert!(!schedule.has_work(), "one request yields one pass");+ }++ #[test]+ fn a_request_arriving_mid_pass_starts_a_second_pass_after_the_first_drains() {+ // Two teams, so the first pass takes two batches and a request can land between them.+ let entries: Vec<(BehavioralKey, i64)> = [TEAM, OTHER_TEAM]+ .into_iter()+ .map(|team| (key(team, 1, 0), 100))+ .collect();+ let mut queue = queue_of(&entries);+ let mut schedule = SweepSchedule::new(0);+ schedule.request(500, &queue);++ let first = schedule.next_batch(&mut queue).expect("first batch");+ assert_eq!(first.team_id, TEAM);++ // A later tick arrives while the pass is still draining, and a new key comes due with it.+ queue.schedule(key(TEAM, 2, 0), 600);+ schedule.request(700, &queue);++ let second = schedule+ .next_batch(&mut queue)+ .expect("second batch of the first pass");+ assert_eq!(second.team_id, OTHER_TEAM);+ assert_eq!(second.due_before_ms, 500, "the pass keeps its own cutoff");++ let third = schedule+ .next_batch(&mut queue)+ .expect("the coalesced request starts a second pass");+ assert_eq!(third.due_before_ms, 700);+ assert_eq!(third.claimed.len(), 1, "the key that came due at 600");+ assert!(!schedule.has_work());+ }++ #[test]+ fn the_sweep_is_owed_a_turn_only_after_a_live_batch_and_only_while_work_remains() {+ let mut queue = queue_of(&[(key(TEAM, 1, 0), 100)]);+ let mut schedule = SweepSchedule::new(0);++ schedule.live_batch_done();+ assert!(!schedule.owes_turn(), "no request, so nothing is owed");++ schedule.request(500, &queue);+ assert!(schedule.owes_turn());++ schedule.next_batch(&mut queue).expect("one batch");+ assert!(+ !schedule.owes_turn(),+ "the sweep spent its turn; live goes next",+ );+ }+}diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rsindex fcefd0da1bed..d0d63034be84 100644--- a/rust/cohort-stream-processor/src/workers/worker.rs+++ b/rust/cohort-stream-processor/src/workers/worker.rs@@ -7,9 +7,14 @@//! 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.+//!+//! A `Sweep` message records an eviction request rather than running one. The pass then advances one+//! bounded batch per round, alternating with live batches and running ahead of seeds+//! ([`crate::workers::sweep_path`]), so a wave of deadlines coming due together costs live traffic+//! one batch at a time instead of the whole wave at once.use std::borrow::Cow;-use std::collections::{BTreeMap, VecDeque};+use std::collections::VecDeque;use std::sync::Arc;use std::time::{Duration, Instant};@@ -30,8 +35,7 @@ use crate::observability::metrics::{EVICTION_QUEUE_REBUILT_KEYS_TOTAL, MERGE_REDIRECT_HOP_CAPPED_TOTAL,MERGE_REKEY_PRODUCE_FAILURE_TOTAL, OUTPUT_MEMBERSHIP_CHANGES_EMITTED, OUTPUT_PRODUCE_ERRORS,STAGE1_EVENTS_PROCESSED, STAGE1_EVENTS_SKIPPED, STAGE1_EVENT_PROCESS_DURATION,- STAGE1_STATE_DECODE_ERROR, STAGE1_TRANSITIONS, SWEEP_KEYS_DROPPED_TOTAL,- SWEEP_KEYS_EVICTED_TOTAL,+ STAGE1_STATE_DECODE_ERROR, STAGE1_TRANSITIONS,};use crate::partitions::offset_tracker::{MarkOutcome, OffsetTracker};use crate::partitions::router::WorkerInbox;@@ -43,8 +47,7 @@ use crate::producer::{use crate::stage1::key::LeafStateKey;use crate::stage1::state::{StateVariant, StatefulRecord};use crate::stage1::transition::{LeafTransition, TransitionKind};-use crate::stage2::{single_leaf_transition_register_writes, stage_register_writes};-use crate::store::{Behavioral, BehavioralKey, ReadLane, StagedBatch, StoreHandle};+use crate::store::{BehavioralKey, ReadLane, StoreHandle};use crate::sweep::EvictionQueue;use crate::workers::cascade_path::handle_cascade;use crate::workers::event_path::{@@ -57,20 +60,10 @@ 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};--/// Max eviction keys a single sweep pass drains. Daily-bucket deadlines cluster on tz-midnight, so a-/// large team's whole wave can come due on one tick; capping the pop loop bounds the per-pass RocksDB-/// read + produce + write batch + Stage 2 pass so events do not queue behind one giant sweep. Leftover-/// due keys stay scheduled and drain on the next sweep tick.-const MAX_SWEEP_KEYS_PER_PASS: usize = 10_000;+use crate::workers::sweep_path::{run_sweep_turn, SweepSchedule};const REBUILD_SCAN_PAGE: usize = 10_000;-/// Chunk size for a team's sweep-state prefetch, so each `multi_get_behavioral` spans a bounded number of-/// keys and no single read op holds long before the sweep makes progress.-const SWEEP_MULTI_GET_CHUNK: usize = 1024;-/// Cooperative-yield cadence inside the worker fold. `handle_event` is synchronous, so a backlog of/// CPU-bound events would hold the runtime thread, starving the commit task and consume loop. A/// wall-clock interval adapts to per-event cost across catalogs of different sizes.@@ -151,6 +144,8 @@ impl Stage1Worker {enum Turn {/// A live sub-batch, or `None` for a closed live lane.Live(Option<Vec<ShuffleMessage>>),+ /// One bounded eviction batch of the pending sweep work.+ Sweep,/// The pending quantum has a run to apply.Run,/// Seeds taken from the lane this round; `0` means the lane closed.@@ -180,6 +175,7 @@ async fn run_worker(info!(partition_id, "stage 1 worker started");let mut queue = EvictionQueue::<BehavioralKey>::new();+ let mut sweep = SweepSchedule::new(partition_id);let mut reconcile_queue = ReconcileQueue::new(partition_id,merge.reconcile.backlog.clone(),@@ -213,8 +209,11 @@ async fn run_worker(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.+ // Live before seeds: 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. The+ // eviction sweep sits between the two: it is maintenance the queue already owes, not+ // admitted backlog, so it runs ahead of seeds, and it alternates with live rather than+ // queueing behind it.//// 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,@@ -222,9 +221,18 @@ async fn run_worker(// `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.+ //+ // A draining sweep pass reads the same way for as long as it lasts, since it too sits ahead+ // of both seed branches. Check `sweep_queue_lag_seconds` before concluding the live lane is+ // the cause: a pass is bounded and clears, a live backlog does not.let turn = tokio::select! {biased;+ // Ahead of live, but only for the one turn a live batch just earned it: eviction and live+ // then alternate, so a lane that is never empty cannot hold a due wave indefinitely.+ () = std::future::ready(()), if sweep.owes_turn() => Turn::Sweep,batch = live.recv(), if live_open => Turn::Live(batch),+ // Live is idle, so the pass keeps going rather than waiting for the next tick.+ () = std::future::ready(()), if sweep.has_work() => Turn::Sweep,// 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.@@ -257,6 +265,20 @@ async fn run_worker();continue;}+ Turn::Sweep => {+ run_sweep_turn(+ partition_id,+ &handle,+ &catalog,+ &sink,+ &merge,+ &mut queue,+ &mut last_updated_clock,+ &mut sweep,+ )+ .await;+ continue;+ }Turn::Run => {apply_next_run(partition_id,@@ -279,6 +301,10 @@ async fn run_worker(continue;}};+ // Claimed before the batch runs, not after: every exit path below (held offset, produce+ // failure, clean mark) must still yield the next turn, or a partition that keeps failing to+ // produce would starve eviction.+ sweep.live_batch_done();let mut buffer = OutputBuffer::new();let mut re_keys: Vec<CohortStreamEvent> = Vec::new();let mut max_offset: Option<i64> = None;@@ -316,6 +342,13 @@ async fn run_worker(re_keys.extend(effects.re_keys);}ShuffleMessage::Sweep { due_before_ms } => {+ // The eviction runs on a later turn, but the buffer still flushes here, so this+ // batch's own `Entered` output precedes the request that may retract it. A+ // later live batch whose end-of-batch produce fails is not covered: its output+ // is dropped for replay while the sweep keeps its turn, so a `Left` can reach+ // the wire first. That converges, because the replayed `Entered` stamps newer+ // than the sweep's `Left`, and holding the sweep behind a failing lane instead+ // would starve eviction (see `live_batch_done`).if flush_event_changes_before_inline(&sink,&mut buffer,@@ -326,17 +359,7 @@ async fn run_worker({break;}- handle_sweep(- partition_id,- &handle,- &catalog,- &sink,- &merge,- &mut queue,- &last_updated,- due_before_ms,- )- .await;+ sweep.request(due_before_ms, &queue);}ShuffleMessage::Merge { event, offset } => {if flush_event_changes_before_inline(@@ -550,7 +573,7 @@ async fn run_worker(info!(partition_id, "stage 1 worker stopped");}-/// Flush buffered event-path changes so they land before an inline (sweep/merge/transfer) produce,+/// Flush buffered event-path changes so they land before an inline (merge/transfer) produce,/// preserving produce order == state-commit order. No-op when the buffer is empty./// Returns the failed-ack count (`0` = fully acked / empty).async fn flush_membership_buffer(@@ -563,10 +586,13 @@ async fn flush_membership_buffer(produce_membership(sink, buffer.take()).await}-/// 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+/// Flush buffered event-path changes ahead of an inline arm (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.+///+/// The `Sweep` arm produces nothing inline, but flushes here so the batch's own `Entered` output+/// precedes the request that may retract it. Its call site says what that does not cover.async fn flush_event_changes_before_inline(sink: &Arc<dyn MembershipSink>,buffer: &mut OutputBuffer,@@ -891,206 +917,6 @@ fn rewrite_to(event: &CohortStreamEvent, final_person: Uuid, origin: Uuid) -> Co}}-#[allow(clippy::too_many_arguments)]-async fn handle_sweep(- partition_id: u16,- handle: &StoreHandle,- catalog: &CatalogHandle,- sink: &Arc<dyn MembershipSink>,- merge: &MergeWorkerDeps,- queue: &mut EvictionQueue<BehavioralKey>,- last_updated: &str,- due_before_ms: i64,-) {- let mut popped: Vec<(BehavioralKey, i64)> = Vec::new();- while popped.len() < MAX_SWEEP_KEYS_PER_PASS {- let Some(entry) = queue.pop_due(due_before_ms) else {- break;- };- popped.push(entry);- }- if popped.is_empty() {- return;- }-- let mut by_team: BTreeMap<u64, Vec<BehavioralKey>> = BTreeMap::new();- for &(key, _) in &popped {- by_team.entry(key.team_id()).or_default().push(key);- }-- let snapshot = catalog.load();- let mut changes = Vec::new();- let mut results = Vec::new();- let mut drops: Vec<SweepDropReason> = Vec::new();- for (team_id, keys) in &by_team {- let Some(filters) = snapshot.team(TeamId(*team_id as i32)) else {- drops.extend(std::iter::repeat_n(SweepDropReason::TeamDrift, keys.len()));- continue;- };- let filters: &TeamFilters = filters;- // Per-team retry: a read failure anywhere in the team reschedules all its keys and applies- // none of it, so gather every chunk before evicting.- let mut values: Vec<Option<Vec<u8>>> = Vec::with_capacity(keys.len());- let mut read_failed = false;- for chunk in keys.chunks(SWEEP_MULTI_GET_CHUNK) {- // The maintenance permit rotates between chunks, keeping each op fair against event reads.- match handle- .multi_get_behavioral(chunk.to_vec(), ReadLane::Maintenance)- .await- {- Ok(chunk_values) => values.extend(chunk_values),- Err(error) => {- warn!(- partition_id,- team_id,- error = %error,- "sweep state read failed; rescheduling the team's keys for retry",- );- reschedule_team(queue, &popped, *team_id);- read_failed = true;- break;- }- }- }- if read_failed {- continue;- }-- let evictions = sweep_evict(filters, keys, values, due_before_ms);- for result in &evictions.results {- if let Some(transition) = &result.transition {- if let Some(kind) = transition_metric_label(filters, transition) {- counter!(STAGE1_TRANSITIONS, "kind" => kind).increment(1);- }- changes.extend(map_transition(filters, transition, last_updated));- }- }- results.extend(evictions.results);- drops.extend(evictions.drops);- }-- if !changes.is_empty() {- let errors = produce_membership(sink, changes).await;- if errors > 0 {- warn!(- partition_id,- errors, "sweep produce to the membership topic failed; rescheduling for replay",- );- reschedule_all(queue, &popped);- return;- }- }-- if !results.is_empty() {- let mut staged = StagedBatch::default();- for result in &results {- match &result.action {- EvictionAction::Write(bytes) => staged.put::<Behavioral>(&result.key, bytes),- EvictionAction::Delete => staged.delete::<Behavioral>(&result.key),- }- // Keep this leg transition-based. The seed paths derive their single-leaf changes by- // diffing this register, and between a seed's acked produce and its post-ack commit- // the register reads `false` while downstream holds `Entered`. A register-diffed- // sweep would compute `false == false` there and emit no `Left`, so the entry would- // outlive the state that justified it. At most one of the path that emits an entry- // and the path that retracts it may read the register.- if let Some(transition) = &result.transition {- if let Some(filters) = snapshot.team(transition.team_id) {- stage_register_writes(- &mut staged,- single_leaf_transition_register_writes(- filters,- partition_id,- transition,- due_before_ms,- ),- );- }- }- }- let written = handle.commit(staged).await;- if let Err(error) = written {- warn!(- partition_id,- error = %error,- "sweep state write failed; rescheduling popped keys to retry the eviction",- );- reschedule_all(queue, &popped);- return;- }-- for result in &results {- if let Some(deadline) = result.reschedule {- queue.schedule(result.key, deadline);- }- counter!(SWEEP_KEYS_EVICTED_TOTAL, "variant" => result.variant.as_str()).increment(1);- }- }-- for reason in &drops {- counter!(SWEEP_KEYS_DROPPED_TOTAL, "reason" => reason.as_str()).increment(1);- }-- let mut by_team_transitions: BTreeMap<u64, Vec<LeafTransition>> = BTreeMap::new();- for result in &results {- if let Some(transition) = &result.transition {- by_team_transitions- .entry(result.key.team_id())- .or_default()- .push(transition.clone());- }- }- let mut stage2_changes = Vec::new();- for (team_id, transitions) in &by_team_transitions {- let Some(filters) = snapshot.team(TeamId(*team_id as i32)) else {- continue;- };- let filters: &TeamFilters = filters;- match compose_stage2(- partition_id,- handle,- filters,- &affected_leaves(transitions),- due_before_ms,- last_updated,- ReadLane::Event,- )- .await- {- Ok(changes) => stage2_changes.extend(changes),- Err(error) => warn!(- partition_id,- team_id,- error = %error,- "sweep stage 2 composition failed; skipping (self-heals on the person's next event)",- ),- }- }- if stage2_changes.is_empty() {- return;- }-- // Only Stage 2 membership changes cascade; single-leaf evictions self-heal on the referrer's next event.- let cascades = first_cascades(merge, &stage2_changes, 0);- let errors = produce_membership(sink, stage2_changes).await;- if errors > 0 {- warn!(- partition_id,- errors,- "sweep stage 2 produce to the membership topic failed; dropping (cf_stage2 already committed, at-most-once)",- );- return;- }- let cascade_errors = produce_cascades(merge, cascades).await;- if cascade_errors > 0 {- warn!(- partition_id,- errors = cascade_errors,- "sweep cascade produce failed; dropping (at-most-once). Recovery depends on each referrer being re-evaluated on its next event; the sweep does not re-evaluate cohort-ref shapes with no behavioral leaf",- );- }-}-/// Re-seed the per-worker [`EvictionQueue`] from `cf_behavioral`, scheduling every behavioral key on/// its stored deadline. Skips `PersonProperty` variants (no time-based eviction) and `i64::MAX`/// deadlines (permanent). Corrupt records are counted and skipped — the event path re-derives them. A@@ -1149,24 +975,6 @@ async fn rebuild_eviction_queue(}}-fn reschedule_all(queue: &mut EvictionQueue<BehavioralKey>, popped: &[(BehavioralKey, i64)]) {- for &(key, deadline) in popped {- queue.schedule(key, deadline);- }-}--fn reschedule_team(- queue: &mut EvictionQueue<BehavioralKey>,- popped: &[(BehavioralKey, i64)],- team_id: u64,-) {- for &(key, deadline) in popped {- if key.team_id() == team_id {- queue.schedule(key, deadline);- }- }-}-/// The `(leaf, person)` pairs [`compose_stage2`] recomputes for.pub fn affected_leaves(transitions: &[LeafTransition]) -> Vec<(LeafStateKey, Uuid)> {transitionsdiff --git a/rust/cohort-stream-processor/tests/sweep_eviction_queue.rs b/rust/cohort-stream-processor/tests/sweep_eviction_queue.rsindex 700281eabf7f..c58c7a07f0eb 100644--- a/rust/cohort-stream-processor/tests/sweep_eviction_queue.rs+++ b/rust/cohort-stream-processor/tests/sweep_eviction_queue.rs@@ -3,9 +3,9 @@//!//! The deterministic oracle is the whole point: an independent `HashMap<BehavioralKey, deadline>` of each//! key's *live* (post-reschedule) deadline. Stepping a fake `now` in 30 s increments and draining-//! `pop_due(now − margin)` each step, we assert every key evicts **exactly once**, at the **first**-//! step where `live_deadline + safety_margin < now`, never earlier, with the queue length equal to-//! the not-yet-evicted count throughout.+//! `due_keys` + `take_due` at `now − margin` each step, we assert every key evicts **exactly once**,+//! at the **first** step where `live_deadline + safety_margin < now`, never earlier, with the queue+//! length equal to the not-yet-evicted count throughout.use std::collections::HashMap;@@ -30,6 +30,16 @@ fn key(i: usize) -> BehavioralKey {)}+/// One sweep pass over the queue: select every due key, then claim each one. Selection and claim are+/// separate calls in production too, so the oracle drives the pair the worker drives.+fn drain(queue: &mut EvictionQueue<BehavioralKey>, cutoff: i64) -> Vec<(BehavioralKey, i64)> {+ let selected: Vec<BehavioralKey> = queue.due_keys(cutoff, usize::MAX).copied().collect();+ selected+ .into_iter()+ .filter_map(|key| queue.take_due(&key, cutoff).map(|deadline| (key, deadline)))+ .collect()+}+#[test]fn one_day_of_events_evicts_each_key_once_at_its_deadline() {const N: usize = 300;@@ -82,7 +92,7 @@ fn one_day_of_events_evicts_each_key_once_at_its_deadline() {assert!(steps < 100_000, "simulation failed to converge");let cutoff = due_before_ms(now, MARGIN_MS);- while let Some((evicted_key, deadline)) = queue.pop_due(cutoff) {+ for (evicted_key, deadline) in drain(&mut queue, cutoff) {let live = oracle[&evicted_key];assert_eq!(deadline, live, "a key evicts carrying its live deadline");assert!(@@ -112,7 +122,7 @@ fn one_day_of_events_evicts_each_key_once_at_its_deadline() {assert_eq!(queue.peek_next_deadline(), None);// Every eviction lands within one sweep step after the ideal `deadline + margin` instant. The- // window is half-open `(ideal, ideal + STEP]`: strict `<` in `pop_due` means a deadline+margin+ // window is half-open `(ideal, ideal + STEP]`: strict `<` in `take_due` means a deadline+margin// exactly on a step boundary is held one more step, firing at `ideal + STEP`.for (k, &fired_at) in &evicted {let ideal = oracle[k] + MARGIN_MS;@@ -140,10 +150,10 @@ fn cancelled_keys_never_evict() {// Step well past the deadline + margin and drain.let cutoff = due_before_ms(deadline + MARGIN_MS + STEP_MS, MARGIN_MS);- let mut evicted = Vec::new();- while let Some((k, _)) = queue.pop_due(cutoff) {- evicted.push(k);- }+ let evicted: Vec<BehavioralKey> = drain(&mut queue, cutoff)+ .into_iter()+ .map(|(k, _)| k)+ .collect();assert_eq!(evicted.len(), 5, "only the non-cancelled keys evict");for i in (0..10).step_by(2) {diff --git a/rust/cohort-stream-processor/tests/sweep_worker.rs b/rust/cohort-stream-processor/tests/sweep_worker.rsindex 9d8e6ed927cb..e27246b75135 100644--- a/rust/cohort-stream-processor/tests/sweep_worker.rs+++ b/rust/cohort-stream-processor/tests/sweep_worker.rs@@ -12,6 +12,7 @@// Tests seed and assert through `CohortStore` directly — the sanctioned direct-store test surface.#![allow(clippy::disallowed_methods)]+use std::collections::HashSet;use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::{Arc, Mutex};@@ -51,6 +52,12 @@ const BEHAVIORAL_HASH: [u8; 16] = *b"0123456789abcdef";const DAY_MS: i64 = 86_400_000;/// A window over 180 days routes `performed_event_multiple` to the compressed history variant.const COMPRESSED_WINDOW_DAYS: i64 = 365;+/// Mirrors `workers::sweep_path::SWEEP_BATCH_KEYS`, the keys one sweep batch claims.+const SWEEP_BATCH_KEYS: usize = 256;+/// The wave in [`wave_against_a_full_live_lane`]: 600 keys is three batches at the target, so the+/// scheduler has to hand the live lane a turn twice while draining it.+const INTERLEAVED_WAVE: usize = 600;+const INTERLEAVED_LIVE_AFTER: usize = 8;fn temp_store() -> (TempDir, CohortStore) {let dir = TempDir::new().unwrap();@@ -266,7 +273,7 @@ async fn drain_until(what: &str, mut predicate: impl FnMut() -> bool) {panic!("timed out waiting for {what}");}-/// [`drain_until`] on the sink's change count. `handle_sweep` produces before its state write, so a+/// [`drain_until`] on the sink's change count. A sweep batch produces before its state write, so a/// test inspecting post-sweep state must follow this with a [`drain_until`] on the store itself.async fn drain_until_changes(sink: &CaptureSink, count: usize) {drain_until("the worker to record changes", || {@@ -340,6 +347,99 @@ fn spawn_worker_with_restore((tx, worker)}+/// Queue every batch up front, then start the worker, so the live lane is provably non-empty from+/// the first turn. The interleaving the tests below assert is then a property of the scheduler+/// rather than of how fast the test task sends.+fn spawn_worker_prefilled(+ store: &CohortStore,+ catalog: Arc<CatalogHandle>,+ sink: Arc<dyn MembershipSink>,+ tracker: Arc<OffsetTracker>,+ batches: Vec<Vec<ShuffleMessage>>,+) -> Stage1Worker {+ let (tx, rx) = mpsc::channel(batches.len().max(1));+ for batch in batches {+ tx.try_send(batch)+ .expect("the lane is sized for every batch");+ }+ drop(tx);+ Stage1Worker::spawn(+ PARTITION_ID,+ WorkerInbox::live_only(rx),+ test_handle(store),+ catalog,+ sink,+ tracker,+ MergeWorkerDeps::capture(),+ false,+ )+}++/// One live batch: `count` matching events, one person each at `ts`, then a sweep whose cutoff is+/// past their shared deadline, so the whole wave comes due at once.+fn wave_then_sweep(count: usize, ts: &str, cutoff: i64) -> Vec<ShuffleMessage> {+ let mut batch: Vec<ShuffleMessage> = (0..count)+ .map(|i| ShuffleMessage::Event {+ event: Box::new(event_at(person(i as u128 + 1), ts, i as i64)),+ cse_offset: i as i64,+ broker_ts_ms: None,+ })+ .collect();+ batch.push(ShuffleMessage::Sweep {+ due_before_ms: cutoff,+ });+ batch+}++/// The length of each contiguous run of `status` in the change stream, in order. Two runs mean+/// something of another status came between them.+fn status_runs(changes: &[CohortMembershipChange], status: MembershipStatus) -> Vec<usize> {+ let mut runs = Vec::new();+ let mut run = 0usize;+ for change in changes {+ if change.status == status {+ run += 1;+ } else if run > 0 {+ runs.push(std::mem::take(&mut run));+ }+ }+ if run > 0 {+ runs.push(run);+ }+ runs+}++/// Drive a due wave larger than one sweep batch against a live lane that is already full, producing+/// into `sink`, and return once the worker has drained both.+async fn wave_against_a_full_live_lane(+ wave: usize,+ live_after: usize,+ sink: Arc<dyn MembershipSink>,+) {+ let (_dir, store) = temp_store();+ let filters = build_team_filters(vec![behavioral_leaf(7)]);+ let tracker = Arc::new(OffsetTracker::new());++ let ts = "2026-05-20 10:00:00.000000";+ let event_ms = clickhouse_timestamp_to_millis(ts).unwrap();+ let cutoff = event_ms + 8 * DAY_MS;+ tracker.mark_dispatched(PARTITION_ID as i32, (wave + live_after) as i64);++ let mut batches = vec![wave_then_sweep(wave, ts, cutoff)];+ // Distinct persons, so these enter on their own rather than reviving a key the pass selected.+ batches.extend((0..live_after).map(|i| {+ let offset = (wave + i) as i64;+ vec![ShuffleMessage::Event {+ event: Box::new(event_at(person(offset as u128 + 1), ts, offset)),+ cse_offset: offset,+ broker_ts_ms: None,+ }]+ }));++ let worker = spawn_worker_prefilled(&store, catalog_of(filters), sink, tracker, batches);+ worker.join().await.unwrap();+}+#[tokio::test]async fn sweep_evicts_a_single_leaf_member_emits_left_and_deletes() {let (_dir, store) = temp_store();@@ -481,11 +581,11 @@ async fn without_durable_restart_a_dormant_member_is_not_re_evicted() {#[tokio::test]async fn event_then_sweep_in_one_batch_emits_entered_before_left() {// Regression: event-path changes accumulate in the buffer and were produced *after* the message- // loop, while the Sweep arm produces inline mid-loop. So a single `[Event, Sweep]` batch where the- // event enters then the sweep immediately ages it out used to emit `Left` (inline) before `Entered`- // (post-loop) — out of state-commit order. A last-write-wins consumer of the shadow topic would then- // read "member" while RocksDB says "left", a false parity mismatch. The buffer is now flushed before- // the Sweep arm, so produce order matches commit order: Entered then Left.+ // loop, while the sweep produced mid-loop. So a single `[Event, Sweep]` batch where the event+ // enters then the sweep immediately ages it out used to emit `Left` before `Entered` — out of+ // state-commit order. A last-write-wins consumer of the shadow topic would then read "member"+ // while RocksDB says "left", a false parity mismatch. The buffer is flushed at the Sweep arm and+ // the eviction runs on a later turn, so produce order still matches commit order.let (_dir, store) = temp_store();let filters = build_team_filters(vec![behavioral_leaf(7)]);let lsk = behavioral_lsk(&filters);@@ -526,11 +626,11 @@ async fn event_then_sweep_in_one_batch_emits_entered_before_left() {assert_eq!(statuses,vec![MembershipStatus::Entered, MembershipStatus::Left],- "within one batch the event's Entered must be produced before the sweep's inline Left",+ "the event's Entered must be produced before the sweep's Left",);assert!(state_at(&store, lsk, alice).is_none(),- "the fully-expired single is deleted by the in-batch sweep",+ "the fully-expired single is deleted by the sweep the batch requested",);assert_eq!(tracker.committable_offsets().get(&(PARTITION_ID as i32)),@@ -638,11 +738,10 @@ async fn sweep_on_an_empty_queue_is_a_noop() {#[tokio::test]async fn sweep_caps_evictions_per_pass_and_drains_the_remainder_next_tick() {- // A large wave of single-leaf members all come due at one cutoff. `handle_sweep` caps the pop loop- // at `MAX_SWEEP_KEYS_PER_PASS` (10_000, private to the worker), so the first pass evicts exactly the- // cap and the leftover keys stay scheduled, draining on a second sweep. This bounds the per-pass- // RocksDB read + produce + write batch so events do not starve behind one giant sweep.- const CAP: usize = 10_000; // mirrors worker::MAX_SWEEP_KEYS_PER_PASS+ // A large wave of single-leaf members all come due at one cutoff. One request plans over at most+ // `MAX_SWEEP_KEYS_PER_PASS` (10_000, private to `workers::sweep_path`) of them, so the first pass+ // evicts exactly the cap and the leftover keys stay scheduled, draining on a second sweep.+ const CAP: usize = 10_000; // mirrors sweep_path::MAX_SWEEP_KEYS_PER_PASSlet total = CAP + 1;let (_dir, store) = temp_store();@@ -714,6 +813,241 @@ async fn sweep_caps_evictions_per_pass_and_drains_the_remainder_next_tick() {);}+#[tokio::test]+async fn a_due_wave_drains_in_batches_that_alternate_with_live_traffic() {+ // A wave used to drain in one pass, holding the partition for its whole duration and allocating+ // every state value at once. Each batch now claims at most the target, and a live batch takes the+ // turn in between, so a tz-midnight wave costs live traffic one batch at a time.+ let sink = CaptureSink::new();+ wave_against_a_full_live_lane(+ INTERLEAVED_WAVE,+ INTERLEAVED_LIVE_AFTER,+ Arc::new(sink.clone()),+ )+ .await;+ let changes = sink.changes();++ assert_eq!(+ status_runs(&changes, MembershipStatus::Left),+ vec![+ SWEEP_BATCH_KEYS,+ SWEEP_BATCH_KEYS,+ INTERLEAVED_WAVE - 2 * SWEEP_BATCH_KEYS,+ ],+ "three bounded batches, each separated by the live output of the batch that ran between",+ );+ assert_eq!(+ changes+ .iter()+ .filter(|change| change.status == MembershipStatus::Left)+ .count(),+ INTERLEAVED_WAVE,+ "interleaving does not cost the sweep any of its wave",+ );+ assert_eq!(+ changes+ .iter()+ .filter(|change| change.status == MembershipStatus::Entered)+ .count(),+ INTERLEAVED_WAVE + INTERLEAVED_LIVE_AFTER,+ "every queued live event entered while the sweep was draining",+ );+}++#[tokio::test]+async fn a_resumed_sweep_stamps_newer_than_the_live_output_it_yielded_to() {+ // A batch takes its `last_updated` when it runs, not when its request arrived. Stamping at request+ // time would give a resumed batch a timestamp older than the live change that ran in between, and+ // a last-write-wins consumer would then resurrect the membership that batch just retracted.+ let sink = CaptureSink::new();+ wave_against_a_full_live_lane(+ INTERLEAVED_WAVE,+ INTERLEAVED_LIVE_AFTER,+ Arc::new(sink.clone()),+ )+ .await;+ let changes = sink.changes();++ for pair in changes.windows(2) {+ assert!(+ pair[0].last_updated <= pair[1].last_updated,+ "produce order must not go backwards in time: {} then {}",+ pair[0].last_updated,+ pair[1].last_updated,+ );+ // Every live change in this fixture is an `Entered` and every sweep change a `Left`, so a+ // status change here is exactly a batch boundary.+ if pair[0].status != pair[1].status {+ assert!(+ pair[0].last_updated < pair[1].last_updated,+ "a sweep/live boundary must move strictly forward: {} then {}",+ pair[0].last_updated,+ pair[1].last_updated,+ );+ }+ }+}++#[tokio::test]+async fn an_event_between_batches_saves_a_key_the_pass_had_already_selected() {+ // A pass plans over candidates up front but claims each key only as its batch runs, and the claim+ // re-reads the deadline. A person whose window slides forward while an earlier batch is running+ // therefore keeps their membership, rather than being evicted against a stale plan.+ const WAVE: usize = 300;+ // Persons sort by uuid, so the wave's persons 1..=300 split 1..=256 then 257..=300. This one is in+ // the second batch, which runs after the live batch below.+ let saved = person(WAVE as u128);++ let (_dir, store) = temp_store();+ let filters = build_team_filters(vec![behavioral_leaf(7)]);+ let lsk = behavioral_lsk(&filters);+ let sink = CaptureSink::new();+ let tracker = Arc::new(OffsetTracker::new());++ let ts = "2026-05-20 10:00:00.000000";+ let event_ms = clickhouse_timestamp_to_millis(ts).unwrap();+ let cutoff = event_ms + 8 * DAY_MS;+ tracker.mark_dispatched(PARTITION_ID as i32, WAVE as i64 + 1);++ let worker = spawn_worker_prefilled(+ &store,+ catalog_of(filters),+ Arc::new(sink.clone()),+ tracker,+ vec![+ wave_then_sweep(WAVE, ts, cutoff),+ // Two days later, so this person's new deadline lands past the pass's cutoff.+ vec![ShuffleMessage::Event {+ event: Box::new(event_at(saved, "2026-05-22 10:00:00.000000", WAVE as i64)),+ cse_offset: WAVE as i64,+ broker_ts_ms: None,+ }],+ ],+ );+ worker.join().await.unwrap();++ let changes = sink.changes();+ assert_eq!(+ changes+ .iter()+ .filter(|change| change.status == MembershipStatus::Left)+ .count(),+ WAVE - 1,+ "every selected key evicted except the one an event pulled back",+ );+ assert!(+ !changes.iter().any(|change| {+ change.status == MembershipStatus::Left && change.person_id == saved.to_string()+ }),+ "the saved person must never be retracted",+ );+ assert!(+ state_at(&store, lsk, saved).is_some(),+ "the saved person's state survives the pass that had selected it",+ );+}++#[tokio::test]+async fn a_later_batchs_produce_failure_leaves_the_earlier_batches_settled() {+ // Failure is now per batch, not per pass. The first batch's evictions stay committed and are never+ // re-emitted; only the keys the failed batch claimed go back on the queue, and the next request+ // retries exactly those.+ const WAVE: usize = 300;+ // Produce calls: 1 the wave's Entered, 2 the first sweep batch, 3 the second (fails), 4 the retry.+ let sink = FailNthSink::new(3);++ let (_dir, store) = temp_store();+ let filters = build_team_filters(vec![behavioral_leaf(7)]);+ let lsk = behavioral_lsk(&filters);+ let tracker = Arc::new(OffsetTracker::new());++ let ts = "2026-05-20 10:00:00.000000";+ let event_ms = clickhouse_timestamp_to_millis(ts).unwrap();+ let cutoff = event_ms + 8 * DAY_MS;+ tracker.mark_dispatched(PARTITION_ID as i32, WAVE as i64);++ let worker = spawn_worker_prefilled(+ &store,+ catalog_of(filters),+ Arc::new(sink.clone()),+ tracker,+ vec![+ wave_then_sweep(WAVE, ts, cutoff),+ vec![ShuffleMessage::Sweep {+ due_before_ms: cutoff,+ }],+ ],+ );+ worker.join().await.unwrap();++ assert_eq!(+ sink.calls(),+ 4,+ "the failed batch produced once and retried once",+ );+ let changes = sink.changes();+ let evicted: HashSet<&String> = changes+ .iter()+ .filter(|change| change.status == MembershipStatus::Left)+ .map(|change| &change.person_id)+ .collect();+ assert_eq!(+ changes+ .iter()+ .filter(|change| change.status == MembershipStatus::Left)+ .count(),+ WAVE,+ "the whole wave evicted across the retry",+ );+ assert_eq!(+ evicted.len(),+ WAVE,+ "the settled batch was not replayed into the retry",+ );+ for i in 0..WAVE {+ assert!(+ state_at(&store, lsk, person(i as u128 + 1)).is_none(),+ "person {} still has state after the retry",+ i + 1,+ );+ }+}++#[tokio::test]+async fn a_live_lane_that_keeps_failing_its_produce_still_yields_the_sweep_its_turns() {+ // The sweep's turn is claimed before a live batch runs, so a batch that fails its produce and+ // skips the rest of the loop body still owes it. Claiming after the batch instead passes every+ // test whose live lane succeeds, while a lane that keeps failing holds a due wave until it closes.+ // Call 1 is the wave's own Entered; every live produce after it fails.+ let sink = FailingLiveSink::new(2);+ wave_against_a_full_live_lane(+ INTERLEAVED_WAVE,+ INTERLEAVED_LIVE_AFTER,+ Arc::new(sink.clone()),+ )+ .await;++ // `None` is a failed live produce. Each sweep batch after the first runs on the turn the failed+ // live batch before it owed, rather than all of them once the lane has closed.+ assert_eq!(+ sink.outcomes(),+ [+ vec![+ Some(MembershipStatus::Entered),+ Some(MembershipStatus::Left)+ ],+ vec![+ None,+ Some(MembershipStatus::Left),+ None,+ Some(MembershipStatus::Left)+ ],+ vec![None; INTERLEAVED_LIVE_AFTER - 2],+ ]+ .concat(),+ );+}+#[tokio::test]async fn single_does_not_evict_before_its_calendar_midnight_and_does_after() {let lsk = behavioral_lsk(&build_team_filters_tz(vec![behavioral_leaf(7)], Kolkata));@@ -1242,6 +1576,51 @@ impl MembershipSink for FailNthSink {}}+/// A sink that fails every live produce from `fail_from` (1-based) on while letting sweep batches+/// through, telling them apart by their changes being all `Left`. Records each call as the status of+/// its first change, or `None` when it failed.+#[derive(Clone)]+struct FailingLiveSink {+ outcomes: Arc<Mutex<Vec<Option<MembershipStatus>>>>,+ fail_from: usize,+}++impl FailingLiveSink {+ fn new(fail_from: usize) -> Self {+ Self {+ outcomes: Arc::default(),+ fail_from,+ }+ }++ fn outcomes(&self) -> Vec<Option<MembershipStatus>> {+ self.outcomes.lock().unwrap().clone()+ }+}++#[async_trait]+impl MembershipSink for FailingLiveSink {+ async fn produce(+ &self,+ changes: Vec<CohortMembershipChange>,+ ) -> Vec<Result<(), KafkaProduceError>> {+ let mut outcomes = self.outcomes.lock().unwrap();+ let call = outcomes.len() + 1;+ let is_sweep = changes+ .iter()+ .all(|change| change.status == MembershipStatus::Left);+ if call >= self.fail_from && !is_sweep {+ outcomes.push(None);+ return changes+ .iter()+ .map(|_| Err(KafkaProduceError::KafkaProduceCanceled))+ .collect();+ }+ outcomes.push(changes.first().map(|change| change.status));+ changes.iter().map(|_| Ok(())).collect()+ }+}+#[tokio::test]async fn sweep_produce_failure_reschedules_and_a_later_sweep_retries() {let (_dir, store) = temp_store();