Skip to content

: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.

feat(cohorts): live-priority pause and pacing (#74371)

Matheus Batista6fc8eea4a302
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 2fef29672122..d2a0d26fca12 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2679,6 +2679,7 @@ dependencies = [
"lifecycle",
"metrics",
"metrics-exporter-prometheus",
+ "nix 0.31.3",
"object_store",
"proptest",
"rand 0.8.5",
diff --git a/rust/cohort-stream-processor/Cargo.toml b/rust/cohort-stream-processor/Cargo.toml
index fdd01791a75d..651929a8df61 100644
--- a/rust/cohort-stream-processor/Cargo.toml
+++ b/rust/cohort-stream-processor/Cargo.toml
@@ -62,6 +62,10 @@ tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter", "json"] }
uuid = { workspace = true }
+[target.'cfg(unix)'.dependencies]
+# `statvfs` for the store-filesystem utilization sample (`observability::disk`).
+nix = { version = "0.31", features = ["fs"] }
+
[dev-dependencies]
# Integration tests in `tests/` build `TeamFilters` via `freeze(UTC)`, so they name `chrono_tz::UTC`
# directly (a normal dependency is not in scope for the separate integration-test crates).
diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rs
index f1cae583dfb8..ff112b1687bb 100644
--- a/rust/cohort-stream-processor/src/config.rs
+++ b/rust/cohort-stream-processor/src/config.rs
@@ -3,7 +3,7 @@
use std::path::PathBuf;
use std::time::Duration;
-use anyhow::ensure;
+use anyhow::{ensure, Context};
use common_database::PoolConfig;
use common_kafka::config::KafkaConfig;
use common_types::cohort::TeamAllowlist;
@@ -11,6 +11,7 @@ use envconfig::Envconfig;
use rdkafka::ClientConfig;
use tracing::warn;
+use crate::partitions::pacing::{AgeMs, Hysteresis, SeedPacingConfig, UsedPct};
use crate::store::durability::DurabilityConfig;
use crate::store::{OffloadConfig, OffloadMode, StoreConfig};
use crate::workers::{CascadeConfig, EventNameGating, TransferRetryPolicy};
@@ -264,6 +265,28 @@ pub struct Config {
#[envconfig(from = "COHORT_SEED_RECONCILE_TICK_INTERVAL_MS", default = "2000")]
pub cohort_seed_reconcile_tick_interval_ms: u64,
+ /// Live-priority gate: pause a seed partition once its live watermark age reaches this (ms).
+ /// `0` disables the trigger.
+ #[envconfig(from = "COHORT_SEED_LIVE_LAG_PAUSE_MS", default = "120000")]
+ pub cohort_seed_live_lag_pause_ms: i64,
+
+ /// Resume a live-lag-paused seed partition once its watermark age drops below this (ms).
+ /// Must be positive and below the pause threshold when the trigger is enabled.
+ #[envconfig(from = "COHORT_SEED_LIVE_LAG_RESUME_MS", default = "60000")]
+ pub cohort_seed_live_lag_resume_ms: i64,
+
+ /// Disk gate: pause all seed partitions once the store filesystem's used share reaches
+ /// this (%). `0` (the default) disables the trigger: pausing seeds cannot shrink a store
+ /// grown by the live path, so a threshold below the steady-state footprint would engage and
+ /// never release. Opt in per deployment once the utilization gauge has baseline history.
+ #[envconfig(from = "COHORT_SEED_DISK_PAUSE_PCT", default = "0")]
+ pub cohort_seed_disk_pause_pct: f64,
+
+ /// Resume disk-paused seed partitions once the used share drops below this (%). Must be
+ /// positive and below the pause threshold when the trigger is enabled.
+ #[envconfig(from = "COHORT_SEED_DISK_RESUME_PCT", default = "55")]
+ pub cohort_seed_disk_resume_pct: f64,
+
/// Stable per-pod identity for `group.instance.id` + `client.id`, enabling static membership.
/// Read from `POD_NAME`, else `HOSTNAME`. Absent means no static membership.
#[envconfig(from = "POD_NAME")]
@@ -623,6 +646,55 @@ impl Config {
Duration::from_millis(self.cohort_seed_reconcile_tick_interval_ms)
}
+ /// The seed consumer's pacing gates. `0` on a pause threshold disables that trigger; an
+ /// enabled trigger requires `0 < resume < pause` (and `pause <= 100` for the disk share) so a
+ /// flapping or never-releasing pair is refused at startup.
+ pub fn seed_pacing_config(&self) -> anyhow::Result<SeedPacingConfig> {
+ let live_lag = if self.cohort_seed_live_lag_pause_ms == 0 {
+ None
+ } else {
+ ensure!(
+ self.cohort_seed_live_lag_pause_ms > 0,
+ "COHORT_SEED_LIVE_LAG_PAUSE_MS must be positive (0 disables the trigger).",
+ );
+ ensure!(
+ self.cohort_seed_live_lag_resume_ms > 0,
+ "COHORT_SEED_LIVE_LAG_RESUME_MS must be positive: a non-positive resume \
+ threshold could never release the pause.",
+ );
+ Some(
+ Hysteresis::new(
+ AgeMs(self.cohort_seed_live_lag_pause_ms),
+ AgeMs(self.cohort_seed_live_lag_resume_ms),
+ )
+ .context(
+ "COHORT_SEED_LIVE_LAG_RESUME_MS must be below COHORT_SEED_LIVE_LAG_PAUSE_MS",
+ )?,
+ )
+ };
+ let disk = if self.cohort_seed_disk_pause_pct == 0.0 {
+ None
+ } else {
+ ensure!(
+ self.cohort_seed_disk_pause_pct > 0.0 && self.cohort_seed_disk_pause_pct <= 100.0,
+ "COHORT_SEED_DISK_PAUSE_PCT must be within (0, 100] (0 disables the trigger).",
+ );
+ ensure!(
+ self.cohort_seed_disk_resume_pct > 0.0,
+ "COHORT_SEED_DISK_RESUME_PCT must be positive: a non-positive resume threshold \
+ could never release the pause.",
+ );
+ Some(
+ Hysteresis::new(
+ UsedPct(self.cohort_seed_disk_pause_pct),
+ UsedPct(self.cohort_seed_disk_resume_pct),
+ )
+ .context("COHORT_SEED_DISK_RESUME_PCT must be below COHORT_SEED_DISK_PAUSE_PCT")?,
+ )
+ };
+ Ok(SeedPacingConfig { live_lag, disk })
+ }
+
pub fn checkpoint_interval(&self) -> Duration {
Duration::from_millis(self.checkpoint_interval_ms)
}
@@ -658,7 +730,8 @@ impl Config {
}
}
- /// Refuse unsafe durability startup combinations. Pure (no I/O), so unit-testable without a broker.
+ /// Refuse unsafe startup combinations (durability, reconcile, and pacing knobs). Pure
+ /// (no I/O), so unit-testable without a broker.
///
/// Guards:
/// - Reconcile scan and tick limits must be non-zero; a zero page would falsely certify an
@@ -667,7 +740,7 @@ impl Config {
/// on open, silently discarding the restore.
/// - `durable_restore_enabled` + `cohort_cascade_enabled` requires `durable_restore_single_pod`
/// and a pod identity: `pod_identity()` alone is not a single-pod signal (set on every k8s pod).
- pub fn validate_durability_startup(&self) -> anyhow::Result<()> {
+ pub fn validate_startup(&self) -> anyhow::Result<()> {
ensure!(
self.cohort_seed_reconcile_scan_page > 0,
"COHORT_SEED_RECONCILE_SCAN_PAGE must be greater than zero.",
@@ -677,6 +750,23 @@ impl Config {
"COHORT_SEED_RECONCILE_TICK_INTERVAL_MS must be greater than zero.",
);
+ let pacing = self.seed_pacing_config()?;
+ // Idle partitions' watermarks advance only once per probe, so a pause threshold inside
+ // two probe intervals would flap on quiet partitions.
+ let idle_probe_ms =
+ i64::try_from(self.cohort_seed_watermark_idle_probe_interval_ms).unwrap_or(i64::MAX);
+ if pacing.live_lag.is_some()
+ && self.cohort_seed_live_lag_pause_ms <= idle_probe_ms.saturating_mul(2)
+ {
+ warn!(
+ cohort_seed_live_lag_pause_ms = self.cohort_seed_live_lag_pause_ms,
+ idle_probe_interval_ms = self.cohort_seed_watermark_idle_probe_interval_ms,
+ "COHORT_SEED_LIVE_LAG_PAUSE_MS within 2× the idle-probe interval: idle \
+ partitions advance only per probe, so the live-lag gate may flap on quiet \
+ partitions.",
+ );
+ }
+
if self.cohort_seed_reconcile_enabled && !self.cohort_seed_consumer_enabled {
warn!(
"COHORT_SEED_RECONCILE_ENABLED without COHORT_SEED_CONSUMER_ENABLED: no reconcile \
@@ -1014,6 +1104,10 @@ mod tests {
cohort_seed_reconcile_enabled: false,
cohort_seed_reconcile_scan_page: 256,
cohort_seed_reconcile_tick_interval_ms: 2_000,
+ cohort_seed_live_lag_pause_ms: 120_000,
+ cohort_seed_live_lag_resume_ms: 60_000,
+ cohort_seed_disk_pause_pct: 60.0,
+ cohort_seed_disk_resume_pct: 55.0,
}
}
@@ -1059,7 +1153,7 @@ mod tests {
let mut config = test_config();
config.cohort_seed_reconcile_scan_page = 0;
assert!(config
- .validate_durability_startup()
+ .validate_startup()
.unwrap_err()
.to_string()
.contains("COHORT_SEED_RECONCILE_SCAN_PAGE"),);
@@ -1067,7 +1161,7 @@ mod tests {
config.cohort_seed_reconcile_scan_page = 1;
config.cohort_seed_reconcile_tick_interval_ms = 0;
assert!(config
- .validate_durability_startup()
+ .validate_startup()
.unwrap_err()
.to_string()
.contains("COHORT_SEED_RECONCILE_TICK_INTERVAL_MS"),);
@@ -1079,7 +1173,74 @@ mod tests {
config.cohort_seed_reconcile_enabled = true;
config.cohort_seed_consumer_enabled = false;
- assert!(config.validate_durability_startup().is_ok());
+ assert!(config.validate_startup().is_ok());
+ }
+
+ /// A flapping (inverted/equal) threshold pair or a never-releasing resume must be refused at
+ /// startup, not discovered as a wedged or flapping gate in production.
+ #[test]
+ fn seed_pacing_validation_rejects_inverted_equal_and_non_positive_thresholds() {
+ let defaults = test_config();
+ let pacing = defaults.seed_pacing_config().unwrap();
+ assert!(pacing.live_lag.is_some());
+ assert!(pacing.disk.is_some());
+
+ type Mutation = fn(&mut Config);
+ let cases: [(&str, Mutation); 6] = [
+ ("COHORT_SEED_LIVE_LAG_RESUME_MS must be below", |config| {
+ config.cohort_seed_live_lag_resume_ms = 120_000; // equal
+ }),
+ ("COHORT_SEED_LIVE_LAG_RESUME_MS must be below", |config| {
+ config.cohort_seed_live_lag_resume_ms = 240_000; // inverted
+ }),
+ (
+ "COHORT_SEED_LIVE_LAG_RESUME_MS must be positive",
+ |config| {
+ config.cohort_seed_live_lag_resume_ms = -1;
+ },
+ ),
+ ("COHORT_SEED_LIVE_LAG_PAUSE_MS must be positive", |config| {
+ config.cohort_seed_live_lag_pause_ms = -1;
+ }),
+ ("COHORT_SEED_DISK_RESUME_PCT must be below", |config| {
+ config.cohort_seed_disk_resume_pct = 60.0; // equal
+ }),
+ ("COHORT_SEED_DISK_PAUSE_PCT must be within", |config| {
+ config.cohort_seed_disk_pause_pct = 101.0;
+ }),
+ ];
+ for (expected, mutate) in cases {
+ let mut config = test_config();
+ mutate(&mut config);
+ let err = config.validate_startup().unwrap_err().to_string();
+ assert!(err.contains(expected), "expected {expected:?} in {err:?}");
+ }
+ }
+
+ /// The env defaults must ship the disk gate dark: it can engage on deployments that already
+ /// run the seed consumer, and a threshold below the store's steady-state footprint would
+ /// never release.
+ #[test]
+ fn seed_pacing_env_defaults_enable_live_lag_and_disable_disk() {
+ let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();
+ let pacing = defaults.seed_pacing_config().unwrap();
+ assert!(pacing.live_lag.is_some());
+ assert!(pacing.disk.is_none());
+ }
+
+ #[test]
+ fn seed_pacing_zero_pause_thresholds_disable_their_triggers() {
+ let mut config = test_config();
+ config.cohort_seed_live_lag_pause_ms = 0;
+ config.cohort_seed_disk_pause_pct = 0.0;
+ // Resume thresholds are irrelevant while disabled — even nonsense must not refuse boot.
+ config.cohort_seed_live_lag_resume_ms = -5;
+ config.cohort_seed_disk_resume_pct = -5.0;
+
+ let pacing = config.seed_pacing_config().unwrap();
+ assert!(pacing.live_lag.is_none());
+ assert!(pacing.disk.is_none());
+ assert!(config.validate_startup().is_ok());
}
#[test]
@@ -1433,14 +1594,14 @@ mod tests {
#[test]
fn durability_startup_guard_passes_for_the_default_config() {
- assert!(test_config().validate_durability_startup().is_ok());
+ assert!(test_config().validate_startup().is_ok());
}
#[test]
fn durability_startup_guard_passes_for_a_plain_durable_restore() {
let mut config = test_config();
config.durable_restore_enabled = true;
- assert!(config.validate_durability_startup().is_ok());
+ assert!(config.validate_startup().is_ok());
}
#[test]
@@ -1450,7 +1611,7 @@ mod tests {
config.cohort_cascade_enabled = true;
config.pod_name = Some("pod-0".to_string());
let err = config
- .validate_durability_startup()
+ .validate_startup()
.expect_err("durable + cascade without the opt-in must be refused");
assert!(
err.to_string().contains("DURABLE_RESTORE_SINGLE_POD"),
@@ -1467,7 +1628,7 @@ mod tests {
config.pod_name = None;
config.pod_hostname = None;
assert!(
- config.validate_durability_startup().is_err(),
+ config.validate_startup().is_err(),
"single-pod opt-in without a pod identity must still refuse the combo",
);
}
@@ -1480,7 +1641,7 @@ mod tests {
config.durable_restore_single_pod = true;
config.pod_name = Some("cohort-stream-processor-0".to_string());
assert!(
- config.validate_durability_startup().is_ok(),
+ config.validate_startup().is_ok(),
"durable + cascade is allowed on a single-pod static-membership deploy",
);
}
@@ -1491,7 +1652,7 @@ mod tests {
config.checkpoint_enabled = true;
config.durable_restore_enabled = false;
let err = config
- .validate_durability_startup()
+ .validate_startup()
.expect_err("checkpoint without durable restore must be refused");
assert!(
err.to_string().contains("DURABLE_RESTORE_ENABLED"),
@@ -1504,7 +1665,7 @@ mod tests {
let mut config = test_config();
config.checkpoint_enabled = true;
config.durable_restore_enabled = true;
- assert!(config.validate_durability_startup().is_ok());
+ assert!(config.validate_startup().is_ok());
}
#[test]
diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rs
index e771e5964e37..9ca77c1e74c9 100644
--- a/rust/cohort-stream-processor/src/consumers/events.rs
+++ b/rust/cohort-stream-processor/src/consumers/events.rs
@@ -42,7 +42,7 @@ use crate::observability::metrics::{
MERGE_HELD_OFFSET_GAUGE, MERGE_PENDING_TRANSFERS_GAUGE, PARTITIONS_ASSIGNED_TOTAL,
PARTITIONS_PAUSED, PARTITIONS_REVOKED_TOTAL, PARTITION_STATE_DELETED_TOTAL,
PENDING_HELD_EVENTS, REBALANCE_CLEANUP_SKIPPED_TOTAL, REVOKE_DRAIN_DURATION_SECONDS,
- SEED_HELD_OFFSET_GAUGE,
+ SEED_HELD_OFFSET_GAUGE, SEED_OLDEST_HELD_AGE_MS, SEED_PAUSE_AGE_MS,
};
use crate::partitions::backpressure::Backpressure;
use crate::partitions::offset_tracker::OffsetTracker;
@@ -701,6 +701,8 @@ impl EventDispatcher {
gauge!(CASCADE_HELD_OFFSET_GAUGE, "partition" => partition.to_string()).set(0.0);
gauge!(SEED_HELD_OFFSET_GAUGE, "partition" => partition.to_string()).set(0.0);
gauge!(LIVE_WATERMARK_AGE_MS, "partition" => partition.to_string()).set(0.0);
+ gauge!(SEED_PAUSE_AGE_MS, "partition" => partition.to_string()).set(0.0);
+ gauge!(SEED_OLDEST_HELD_AGE_MS, "partition" => partition.to_string()).set(0.0);
let Some(partition_id) = partition_to_store_id(partition) else {
warn!(
@@ -1454,9 +1456,24 @@ pub(crate) async fn run_pauser_loop(
while let Some(target) = rx.recv().await {
let to_pause: Vec<i32> = target.iter().copied().collect();
let to_resume: Vec<i32> = applied.difference(&target).copied().collect();
- pauser.pause(&to_pause);
- pauser.resume(&to_resume);
- applied = target;
+ // Run the blocking FFI off the worker threads, awaited serially so updates keep their
+ // order.
+ let ffi_pauser = pauser.clone();
+ let applied_ffi = tokio::task::spawn_blocking(move || {
+ ffi_pauser.pause(&to_pause);
+ ffi_pauser.resume(&to_resume);
+ })
+ .await;
+ match applied_ffi {
+ Ok(()) => applied = target,
+ Err(err) => {
+ // The task may have died anywhere between pause and resume, so fold the target
+ // in rather than replace: every possibly-paused partition stays eligible for a
+ // future resume, and resuming a never-paused partition is a librdkafka no-op.
+ applied.extend(target);
+ warn!(error = %err, "pauser task's blocking pause/resume panicked; retrying the delta on the next target update");
+ }
+ }
}
}
@@ -2290,6 +2307,7 @@ mod tests {
)),
partition,
offset,
+ broker_ts_ms: None,
}
}
@@ -2621,6 +2639,7 @@ mod tests {
work: SeedWork::Reconcile(tile.clone()),
partition: 0,
offset: 5,
+ broker_ts_ms: None,
}]);
assert!(held.is_empty());
for _ in 0..10_000 {
@@ -2672,6 +2691,7 @@ mod tests {
work: SeedWork::Reconcile(tile.clone()),
partition: 0,
offset: 5,
+ broker_ts_ms: None,
}]);
assert_eq!(
held_seed_offsets(held.get(&0).expect("the draining route is held")),
diff --git a/rust/cohort-stream-processor/src/consumers/seeds.rs b/rust/cohort-stream-processor/src/consumers/seeds.rs
index 22a89cca4121..e3cb07f10765 100644
--- a/rust/cohort-stream-processor/src/consumers/seeds.rs
+++ b/rust/cohort-stream-processor/src/consumers/seeds.rs
@@ -1,15 +1,18 @@
//! The `cohort_stream_seed_events` follower consumer — the backfill day-tile input.
//!
-//! Assignment arrives via the events group's rebalance mirror. The apply fence is enforced at
-//! admission: a tile dispatches only once its partition's live watermark clears
-//! `s_chunk + margin`; fence-closed and channel-full tiles share one holdover + pause mechanism,
-//! and an un-dispatched tile was never `mark_dispatched`ed, so its offset cannot commit.
+//! Assignment arrives via the events group's rebalance mirror. Four admission gates share one
+//! holdover + pause mechanism: the apply fence (a tile dispatches only once its partition's live
+//! watermark clears `s_chunk + margin`), a full worker channel, live-priority (the partition's
+//! live watermark age crossed the pause threshold — live traffic always wins), and pod-wide disk
+//! pressure. An un-dispatched tile was never `mark_dispatched`ed, so its offset cannot commit.
//! Consume-side skips ride the worker channel so their offsets mark in order; they never close
-//! the fence.
+//! the fence, but a live-lag/disk gate holds them too (nothing leapfrogs a gated partition).
+//! The [`PauseLedger`] records why each partition is held and since when; the pause target and
+//! the age/count gauges all derive from it.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
-use std::time::Duration;
+use std::time::{Duration, Instant};
use cohort_core::seed::{decode_seed, DecodedSeed, ReconcileTile, SChunkMs, SeedTile};
use lifecycle::Handle;
@@ -21,12 +24,19 @@ use tracing::{debug, info, warn};
use crate::consumers::events::{fsync_then_commit, run_pauser_loop, EventDispatcher};
use crate::consumers::merges::owned_committable_offsets;
+use crate::observability::disk::{DiskUtilization, SharedDiskUtilization};
use crate::observability::metrics::{
COHORT_STREAM_KAFKA_RECV_ERRORS, COHORT_STREAM_SEEDS_CONSUMED,
COHORT_STREAM_SEEDS_CONSUME_BATCH_SIZE, COHORT_STREAM_SEED_DESERIALIZE_ERRORS,
LIVE_WATERMARK_AGE_MS, SEED_FENCED_PARTITIONS, SEED_FENCE_DEFICIT_MS,
+ SEED_IDLE_PROBE_DURATION_SECONDS, SEED_IDLE_PROBE_LAST_PASS_TIMESTAMP_SECONDS,
+ SEED_NO_WATERMARK_PARTITIONS, SEED_OLDEST_HELD_AGE_MS, SEED_PAUSED_PARTITIONS,
+ SEED_PAUSE_AGE_MS,
};
use crate::partitions::backpressure::PartitionHoldover;
+use crate::partitions::pacing::{
+ AgeMs, CauseSet, Hysteresis, PauseCause, PauseLedger, SeedPacing, SeedPacingConfig, UsedPct,
+};
use crate::partitions::pause::PartitionPauser;
use crate::partitions::rebalance::CohortConsumerContext;
use crate::partitions::shuffle_message::ShuffleMessage;
@@ -74,6 +84,9 @@ pub struct ConsumedSeed {
pub work: SeedWork,
pub partition: i32,
pub offset: i64,
+ /// Broker timestamp of the consumed message — the oldest-held age gauge's input. `None`
+ /// (`Timestamp::NotAvailable`) reads as age 0.
+ pub broker_ts_ms: Option<i64>,
}
impl ConsumedSeed {
@@ -81,16 +94,22 @@ impl ConsumedSeed {
ShuffleMessage::Seed {
work: Box::new(self.work),
offset: self.offset,
+ broker_ts_ms: self.broker_ts_ms,
}
}
/// Inverse of [`into_message`](Self::into_message); `None` for a non-seed message.
pub(crate) fn from_message(partition: i32, message: ShuffleMessage) -> Option<Self> {
match message {
- ShuffleMessage::Seed { work, offset } => Some(Self {
+ ShuffleMessage::Seed {
+ work,
+ offset,
+ broker_ts_ms,
+ } => Some(Self {
work: *work,
partition,
offset,
+ broker_ts_ms,
}),
_ => None,
}
@@ -134,40 +153,95 @@ pub(crate) fn fence_decision(
}
}
-/// A consumed batch split at the fence, preserving per-partition FIFO.
+/// The gates evaluated at admission, beyond the per-tile fence.
+pub(crate) struct AdmissionPolicy<'a, F: Fn(i32) -> Option<WatermarkMs>> {
+ pub fence_margin_ms: i64,
+ pub watermark_of: F,
+ /// Partitions gated by live-priority: hold everything, including leading skips.
+ pub live_lagging: &'a HashSet<i32>,
+ /// Pod-wide disk gate: hold everything for every partition.
+ pub disk_pressure: bool,
+}
+
+/// A consumed batch split at the admission gates, preserving per-partition FIFO.
#[derive(Debug, Default)]
-pub(crate) struct FenceSplit {
+pub(crate) struct AdmissionSplit {
pub admitted: Vec<ConsumedSeed>,
pub held: HashMap<i32, Vec<ConsumedSeed>>,
+ /// Why each partition that closed in this split is held.
+ pub causes: HashMap<i32, CauseSet>,
/// Deficit per partition whose fence closed in this split.
pub deficits: HashMap<i32, Option<i64>>,
}
/// Admit each partition's open prefix; from the first fence-closed tile hold everything for that
-/// partition (skips included) so nothing leapfrogs a held offset. `already_held` partitions queue
-/// entirely behind their holdover.
-pub(crate) fn split_at_fence(
+/// partition (skips included) so nothing leapfrogs a held offset. A gated partition
+/// (live-lag/disk) holds everything from its first message, leading skips included.
+/// `already_held` partitions queue entirely behind their holdover (their causes were attributed
+/// when the holdover re-split this cycle).
+pub(crate) fn split_for_admission<F: Fn(i32) -> Option<WatermarkMs>>(
seeds: Vec<ConsumedSeed>,
already_held: &HashSet<i32>,
- margin_ms: i64,
- watermark_of: impl Fn(i32) -> Option<WatermarkMs>,
-) -> FenceSplit {
- let mut split = FenceSplit::default();
+ policy: &AdmissionPolicy<'_, F>,
+) -> AdmissionSplit {
+ let mut split = AdmissionSplit::default();
let mut closed: HashSet<i32> = HashSet::new();
+ // Gated partitions whose first tile has not been fence-probed yet: even when gated, the first
+ // tile still evaluates the fence so the fence cause and deficit stay continuous through a
+ // live-lag/disk episode.
+ let mut fence_probe_pending: HashSet<i32> = HashSet::new();
for seed in seeds {
let partition = seed.partition;
- if already_held.contains(&partition) || closed.contains(&partition) {
+ if already_held.contains(&partition) {
+ split.held.entry(partition).or_default().push(seed);
+ continue;
+ }
+ if !closed.contains(&partition) {
+ let gate = gate_causes(policy, partition);
+ if !gate.is_empty() {
+ closed.insert(partition);
+ fence_probe_pending.insert(partition);
+ split.causes.insert(partition, gate);
+ }
+ }
+ if closed.contains(&partition) {
+ if fence_probe_pending.contains(&partition) {
+ if let Some(s_chunk) = seed.s_chunk_ms() {
+ fence_probe_pending.remove(&partition);
+ if let FenceDecision::Closed { deficit_ms } = fence_decision(
+ (policy.watermark_of)(partition),
+ s_chunk,
+ policy.fence_margin_ms,
+ ) {
+ split
+ .causes
+ .entry(partition)
+ .or_default()
+ .insert(PauseCause::Fence);
+ split.deficits.insert(partition, deficit_ms);
+ }
+ }
+ }
split.held.entry(partition).or_default().push(seed);
continue;
}
let decision = match seed.s_chunk_ms() {
None => FenceDecision::Open,
- Some(s_chunk) => fence_decision(watermark_of(partition), s_chunk, margin_ms),
+ Some(s_chunk) => fence_decision(
+ (policy.watermark_of)(partition),
+ s_chunk,
+ policy.fence_margin_ms,
+ ),
};
match decision {
FenceDecision::Open => split.admitted.push(seed),
FenceDecision::Closed { deficit_ms } => {
closed.insert(partition);
+ split
+ .causes
+ .entry(partition)
+ .or_default()
+ .insert(PauseCause::Fence);
split.deficits.insert(partition, deficit_ms);
split.held.entry(partition).or_default().push(seed);
}
@@ -176,7 +250,22 @@ pub(crate) fn split_at_fence(
split
}
-/// Holdover of fence-closed or backpressured seeds.
+/// The partition-level gate verdict under `policy`, independent of any tile.
+fn gate_causes<F: Fn(i32) -> Option<WatermarkMs>>(
+ policy: &AdmissionPolicy<'_, F>,
+ partition: i32,
+) -> CauseSet {
+ let mut causes = CauseSet::default();
+ if policy.live_lagging.contains(&partition) {
+ causes.insert(PauseCause::LiveLag);
+ }
+ if policy.disk_pressure {
+ causes.insert(PauseCause::DiskPressure);
+ }
+ causes
+}
+
+/// Holdover of fence-closed, backpressured, or pacing-gated seeds.
type SeedHoldover = PartitionHoldover<ConsumedSeed>;
/// The holdover flattened in per-partition FIFO order.
@@ -188,6 +277,200 @@ fn drain_held(holdover: &mut SeedHoldover) -> Vec<ConsumedSeed> {
.collect()
}
+/// One pass over the owned partitions: watermark ages (for the age gauge), the live-lag verdicts,
+/// and the no-watermark count.
+#[derive(Debug, Default)]
+struct LiveLagAssessment {
+ /// Partitions whose seed applies must yield to live consumption this cycle.
+ lagging: HashSet<i32>,
+ /// Watermark age per partition that has one.
+ ages_ms: HashMap<i32, i64>,
+ /// Owned partitions with no watermark at all: fence-fail-closed with an unknown deficit, so
+ /// otherwise invisible on the deficit gauge.
+ no_watermark: usize,
+}
+
+/// An absent watermark is never a live-lag hold — tiles are already fence-fail-closed there, and
+/// a redundant hold would poison the hysteresis memory on a new tenure — it is only counted.
+fn assess_live_lag(
+ owned: &HashSet<i32>,
+ watermark_of: impl Fn(i32) -> Option<WatermarkMs>,
+ ledger: &PauseLedger,
+ hysteresis: Option<Hysteresis<AgeMs>>,
+ now_ms: i64,
+) -> LiveLagAssessment {
+ let mut assessment = LiveLagAssessment::default();
+ for &partition in owned {
+ let Some(WatermarkMs(watermark_ms)) = watermark_of(partition) else {
+ assessment.no_watermark += 1;
+ continue;
+ };
+ let age_ms = now_ms.saturating_sub(watermark_ms);
+ assessment.ages_ms.insert(partition, age_ms);
+ let Some(hysteresis) = hysteresis else {
+ continue;
+ };
+ let engaged = ledger.has_cause(partition, PauseCause::LiveLag);
+ if hysteresis.decide(engaged, AgeMs(age_ms)) {
+ assessment.lagging.insert(partition);
+ }
+ }
+ assessment
+}
+
+/// This cycle's per-partition causes: the two splits' verdicts unioned, plus `ChannelFull` for
+/// every partition whose dispatch bounced. Feeds [`PauseLedger::reconcile`], so a partition absent
+/// here has drained and its episode ends.
+fn merge_cycle_causes(
+ refence: HashMap<i32, CauseSet>,
+ fresh: HashMap<i32, CauseSet>,
+ bounced: impl IntoIterator<Item = i32>,
+) -> HashMap<i32, CauseSet> {
+ let mut merged = refence;
+ for (partition, causes) in fresh {
+ let entry = merged.entry(partition).or_default();
+ *entry = entry.union(causes);
+ }
+ for partition in bounced {
+ merged
+ .entry(partition)
+ .or_default()
+ .insert(PauseCause::ChannelFull);
+ }
+ merged
+}
+
+/// The admission core of one consume cycle: prune revoked state, assess the gates, split and
+/// dispatch held seeds before fresh ones, reconcile the ledger, and emit the pacing gauges.
+/// Both clock readings are inputs, so tests can drive it without a consumer.
+#[allow(clippy::too_many_arguments)]
+fn run_admission_cycle(
+ dispatcher: &EventDispatcher,
+ pacing_config: &SeedPacingConfig,
+ disk_sample: Option<DiskUtilization>,
+ fence_margin_ms: i64,
+ seeds: Vec<ConsumedSeed>,
+ holdover: &mut SeedHoldover,
+ pacing: &mut SeedPacing,
+ prev_paused_target: &mut HashSet<i32>,
+ pause_tx: &tokio::sync::mpsc::UnboundedSender<HashSet<i32>>,
+ now_ms: i64,
+ now: Instant,
+) {
+ let owned = dispatcher.owned_set();
+ holdover.prune_revoked(&owned);
+ pacing.ledger.drop_unowned(&owned);
+
+ let watermarks = dispatcher.merge_deps().live_watermarks.clone();
+ let watermark_of = |partition: i32| watermarks.get(partition);
+
+ let live_lag = assess_live_lag(
+ &owned,
+ watermark_of,
+ &pacing.ledger,
+ pacing_config.live_lag,
+ now_ms,
+ );
+ for (&partition, &age_ms) in &live_lag.ages_ms {
+ gauge!(LIVE_WATERMARK_AGE_MS, "partition" => partition.to_string()).set(age_ms as f64);
+ }
+ gauge!(SEED_NO_WATERMARK_PARTITIONS).set(live_lag.no_watermark as f64);
+
+ // Pod-wide disk verdict; an absent sample can never pause (fail-open).
+ pacing.disk_engaged = match (pacing_config.disk, disk_sample) {
+ (Some(hysteresis), Some(sample)) => {
+ hysteresis.decide(pacing.disk_engaged, UsedPct(sample.used_pct()))
+ }
+ _ => false,
+ };
+
+ let policy = AdmissionPolicy {
+ fence_margin_ms,
+ watermark_of,
+ live_lagging: &live_lag.lagging,
+ disk_pressure: pacing.disk_engaged,
+ };
+
+ // Held before fresh; the channel-full remainder re-absorbs before the still-fenced
+ // suffix so per-partition FIFO holds.
+ let refence = split_for_admission(drain_held(holdover), &HashSet::new(), &policy);
+ let still_full = dispatcher.dispatch_seeds(refence.admitted);
+ let mut bounced: Vec<i32> = still_full.keys().copied().collect();
+ holdover.absorb(still_full);
+ holdover.absorb(refence.held);
+
+ // Fresh seeds queue behind held partitions rather than leapfrogging older offsets.
+ let fresh = split_for_admission(seeds, &holdover.held_partitions(), &policy);
+ let fresh_full = dispatcher.dispatch_seeds(fresh.admitted);
+ bounced.extend(fresh_full.keys().copied());
+ holdover.absorb(fresh_full);
+ holdover.absorb(fresh.held);
+
+ for (partition, deficit) in refence.deficits.into_iter().chain(fresh.deficits) {
+ if let Some(deficit_ms) = deficit {
+ gauge!(SEED_FENCE_DEFICIT_MS, "partition" => partition.to_string())
+ .set(deficit_ms as f64);
+ }
+ }
+
+ let causes = merge_cycle_causes(refence.causes, fresh.causes, bounced);
+ // Reconcile owned ∪ caused: owned partitions with no causes drain (episode ends), and a
+ // just-revoked partition whose polled seeds were held this cycle still enters the ledger so
+ // the target matches the holdover until both prune next cycle.
+ let mut to_reconcile = owned;
+ to_reconcile.extend(causes.keys().copied());
+ for partition in to_reconcile {
+ pacing.ledger.reconcile(
+ partition,
+ causes.get(&partition).copied().unwrap_or_default(),
+ now,
+ );
+ }
+
+ // A partition is paused iff its holdover is non-empty; the ledger is the causes-and-age view
+ // of that same set.
+ debug_assert_eq!(pacing.ledger.pause_target(), holdover.held_partitions());
+
+ let target = pacing.ledger.pause_target();
+ for partition in prev_paused_target.difference(&target) {
+ // Zero the per-partition gauges for drained partitions so they clear.
+ let label: Arc<str> = Arc::from(partition.to_string());
+ gauge!(SEED_FENCE_DEFICIT_MS, "partition" => label.clone()).set(0.0);
+ gauge!(SEED_PAUSE_AGE_MS, "partition" => label.clone()).set(0.0);
+ gauge!(SEED_OLDEST_HELD_AGE_MS, "partition" => label).set(0.0);
+ }
+ // A partition can stay held (live-lag/disk/channel-full) after its fence opens; nothing
+ // rewrites the deficit then, so clear it rather than pin the last fence-closed reading.
+ for &partition in &target {
+ if !pacing.ledger.has_cause(partition, PauseCause::Fence) {
+ gauge!(SEED_FENCE_DEFICIT_MS, "partition" => partition.to_string()).set(0.0);
+ }
+ }
+ if (!target.is_empty() || !prev_paused_target.is_empty())
+ && pause_tx.send(target.clone()).is_err()
+ {
+ debug!("seed pauser task has exited; skipping a pause/resume update");
+ }
+
+ for &partition in &target {
+ if let Some(age) = pacing.ledger.age(partition, now) {
+ gauge!(SEED_PAUSE_AGE_MS, "partition" => partition.to_string())
+ .set(age.as_millis() as f64);
+ }
+ }
+ for (partition, head) in holdover.held_heads() {
+ let age_ms = head.broker_ts_ms.map_or(0, |ts| (now_ms - ts).max(0));
+ gauge!(SEED_OLDEST_HELD_AGE_MS, "partition" => partition.to_string()).set(age_ms as f64);
+ }
+ for cause in PauseCause::ALL {
+ gauge!(SEED_PAUSED_PARTITIONS, "cause" => cause.as_str())
+ .set(pacing.ledger.count_with(cause) as f64);
+ }
+ gauge!(SEED_FENCED_PARTITIONS).set(holdover.held_partition_count() as f64);
+
+ *prev_paused_target = target;
+}
+
/// The seed-topic follower consume loop. Commits go through the seed tracker +
/// `fsync_then_commit`, so a committed offset is a durably-applied tile.
pub struct SeedFollowerConsumer {
@@ -204,6 +487,8 @@ pub struct SeedFollowerConsumer {
offset_commit_interval: Duration,
fence_margin_ms: i64,
idle_probe_interval: Duration,
+ pacing_config: SeedPacingConfig,
+ disk_state: Arc<SharedDiskUtilization>,
}
impl SeedFollowerConsumer {
@@ -221,6 +506,8 @@ impl SeedFollowerConsumer {
offset_commit_interval: Duration,
fence_margin_ms: i64,
idle_probe_interval: Duration,
+ pacing_config: SeedPacingConfig,
+ disk_state: Arc<SharedDiskUtilization>,
) -> Self {
Self {
consumer,
@@ -235,6 +522,8 @@ impl SeedFollowerConsumer {
offset_commit_interval,
fence_margin_ms,
idle_probe_interval,
+ pacing_config,
+ disk_state,
}
}
@@ -256,6 +545,7 @@ impl SeedFollowerConsumer {
));
let mut holdover = SeedHoldover::default();
+ let mut pacing = SeedPacing::default();
let mut prev_paused_target: HashSet<i32> = HashSet::new();
let mut commit_deadline = tokio::time::Instant::now() + self.offset_commit_interval;
@@ -267,7 +557,7 @@ impl SeedFollowerConsumer {
break;
}
outcome = self.consume_batch() => {
- self.cycle(outcome, &mut holdover, &mut prev_paused_target, &pause_tx).await;
+ self.cycle(outcome, &mut holdover, &mut pacing, &mut prev_paused_target, &pause_tx).await;
let now = tokio::time::Instant::now();
if now >= commit_deadline {
fsync_then_commit(
@@ -305,12 +595,14 @@ impl SeedFollowerConsumer {
info!(topic = %self.topic, "seed follower consume loop stopped");
}
- /// One non-blocking cycle: prune revoked holdover, re-fence and redispatch held seeds before
- /// fresh ones, dispatch the polled batch, reconcile the paused target and gauges.
+ /// One non-blocking cycle: prune revoked holdover, assess the pacing gates, re-admit and
+ /// redispatch held seeds before fresh ones, dispatch the polled batch, reconcile the paused
+ /// target and gauges.
async fn cycle(
&self,
outcome: SeedConsumeOutcome,
holdover: &mut SeedHoldover,
+ pacing: &mut SeedPacing,
prev_paused_target: &mut HashSet<i32>,
pause_tx: &tokio::sync::mpsc::UnboundedSender<HashSet<i32>>,
) {
@@ -322,60 +614,19 @@ impl SeedFollowerConsumer {
counter!(COHORT_STREAM_SEED_DESERIALIZE_ERRORS).increment(outcome.deserialize_errors);
}
- let owned = self.dispatcher.owned_set();
- holdover.prune_revoked(&owned);
- let watermarks = self.dispatcher.merge_deps().live_watermarks.clone();
- let watermark_of = |partition: i32| watermarks.get(partition);
-
- // Held before fresh; the channel-full remainder re-absorbs before the still-fenced
- // suffix so per-partition FIFO holds.
- let refence = split_at_fence(
- drain_held(holdover),
- &HashSet::new(),
+ run_admission_cycle(
+ &self.dispatcher,
+ &self.pacing_config,
+ self.disk_state.latest(),
self.fence_margin_ms,
- watermark_of,
- );
- let still_full = self.dispatcher.dispatch_seeds(refence.admitted);
- holdover.absorb(still_full);
- holdover.absorb(refence.held);
-
- // Fresh seeds queue behind held partitions rather than leapfrogging older offsets.
- let fresh = split_at_fence(
outcome.seeds,
- &holdover.held_partitions(),
- self.fence_margin_ms,
- watermark_of,
+ holdover,
+ pacing,
+ prev_paused_target,
+ pause_tx,
+ chrono::Utc::now().timestamp_millis(),
+ Instant::now(),
);
- let fresh_full = self.dispatcher.dispatch_seeds(fresh.admitted);
- holdover.absorb(fresh_full);
- holdover.absorb(fresh.held);
-
- for (partition, deficit) in refence.deficits.into_iter().chain(fresh.deficits) {
- if let Some(deficit_ms) = deficit {
- gauge!(SEED_FENCE_DEFICIT_MS, "partition" => partition.to_string())
- .set(deficit_ms as f64);
- }
- }
- let now_ms = chrono::Utc::now().timestamp_millis();
- for &partition in &owned {
- if let Some(WatermarkMs(watermark_ms)) = watermarks.get(partition) {
- gauge!(LIVE_WATERMARK_AGE_MS, "partition" => partition.to_string())
- .set(now_ms.saturating_sub(watermark_ms) as f64);
- }
- }
-
- let target = holdover.held_partitions();
- if !target.is_empty() || !prev_paused_target.is_empty() {
- for partition in prev_paused_target.difference(&target) {
- // Zero the deficit for drained partitions so the gauge clears.
- gauge!(SEED_FENCE_DEFICIT_MS, "partition" => partition.to_string()).set(0.0);
- }
- if pause_tx.send(target.clone()).is_err() {
- debug!("seed pauser task has exited; skipping a pause/resume update");
- }
- *prev_paused_target = target;
- }
- gauge!(SEED_FENCED_PARTITIONS).set(holdover.held_partition_count() as f64);
if outcome.transport_error {
tokio::time::sleep(RECV_ERROR_BACKOFF).await;
@@ -403,7 +654,12 @@ impl SeedFollowerConsumer {
if matches!(work, SeedWork::Skip(SeedSkipReason::DecodeError)) {
outcome.deserialize_errors += 1;
}
- outcome.seeds.push(ConsumedSeed { work, partition, offset });
+ outcome.seeds.push(ConsumedSeed {
+ work,
+ partition,
+ offset,
+ broker_ts_ms: message.timestamp().to_millis(),
+ });
}
Err(err) => {
outcome.transport_error = true;
@@ -489,6 +745,7 @@ async fn run_idle_probe_loop(
let folded = dispatcher.events_tracker().committable_offsets();
let consumer = events_consumer.clone();
let topic = events_topic.clone();
+ let pass_started = Instant::now();
let probe = tokio::task::spawn_blocking(move || {
probe_idle_partitions(consumer.as_ref(), &topic, &owned, &folded)
});
@@ -501,7 +758,11 @@ async fn run_idle_probe_loop(
};
match probed {
Ok(idle_partitions) => {
+ histogram!(SEED_IDLE_PROBE_DURATION_SECONDS)
+ .record(pass_started.elapsed().as_secs_f64());
let now_ms = chrono::Utc::now().timestamp_millis();
+ gauge!(SEED_IDLE_PROBE_LAST_PASS_TIMESTAMP_SECONDS)
+ .set(now_ms as f64 / 1_000.0);
advance_probed_idle(
&dispatcher.merge_deps().live_watermarks,
&dispatcher.owned_set(),
@@ -634,6 +895,7 @@ mod tests {
work: SeedWork::Tile(tile_at(s_chunk_ms)),
partition,
offset,
+ broker_ts_ms: None,
}
}
@@ -642,6 +904,7 @@ mod tests {
work: SeedWork::Skip(SeedSkipReason::UnknownKind),
partition,
offset,
+ broker_ts_ms: None,
}
}
@@ -649,6 +912,27 @@ mod tests {
seeds.iter().map(|seed| seed.offset).collect()
}
+ /// A policy with only the fence gate active: no live-lag set, no disk pressure.
+ fn fence_only<F: Fn(i32) -> Option<WatermarkMs>>(
+ live_lagging: &HashSet<i32>,
+ watermark_of: F,
+ ) -> AdmissionPolicy<'_, F> {
+ AdmissionPolicy {
+ fence_margin_ms: MARGIN_MS,
+ watermark_of,
+ live_lagging,
+ disk_pressure: false,
+ }
+ }
+
+ fn causes_of(list: &[PauseCause]) -> CauseSet {
+ let mut set = CauseSet::default();
+ for &cause in list {
+ set.insert(cause);
+ }
+ set
+ }
+
#[test]
fn fence_decision_table_pins_the_boundary_arithmetic() {
let s_chunk = SChunkMs(1_000_000);
@@ -700,7 +984,12 @@ mod tests {
seed(1, 14, 100), // would be open, but queues behind the held offset
];
- let split = split_at_fence(batch, &HashSet::new(), MARGIN_MS, |p| watermarks.get(p));
+ let none = HashSet::new();
+ let split = split_for_admission(
+ batch,
+ &HashSet::new(),
+ &fence_only(&none, |p| watermarks.get(p)),
+ );
assert_eq!(offsets(&split.admitted), vec![10, 11]);
assert_eq!(offsets(&split.held[&1]), vec![12, 13, 14]);
@@ -708,13 +997,15 @@ mod tests {
split.deficits[&1],
Some(10_000_000 + MARGIN_MS - (100 + MARGIN_MS + 1))
);
+ assert_eq!(split.causes[&1], causes_of(&[PauseCause::Fence]));
}
#[test]
fn split_holds_everything_for_an_absent_watermark_except_leading_skips() {
let batch = vec![skip(3, 1), seed(3, 2, 0), skip(3, 3)];
- let split = split_at_fence(batch, &HashSet::new(), MARGIN_MS, |_| None);
+ let none = HashSet::new();
+ let split = split_for_admission(batch, &HashSet::new(), &fence_only(&none, |_| None));
assert_eq!(
offsets(&split.admitted),
@@ -731,7 +1022,12 @@ mod tests {
watermarks.observe(5, i64::MAX); // fence wide open
let batch = vec![seed(5, 20, 0), skip(5, 21)];
- let split = split_at_fence(batch, &HashSet::from([5]), MARGIN_MS, |p| watermarks.get(p));
+ let none = HashSet::new();
+ let split = split_for_admission(
+ batch,
+ &HashSet::from([5]),
+ &fence_only(&none, |p| watermarks.get(p)),
+ );
assert!(split.admitted.is_empty(), "nothing leapfrogs a held offset");
assert_eq!(offsets(&split.held[&5]), vec![20, 21]);
@@ -744,13 +1040,175 @@ mod tests {
// Partition 2 has no watermark: closed.
let batch = vec![seed(1, 1, 0), seed(2, 1, 0), seed(1, 2, 0)];
- let split = split_at_fence(batch, &HashSet::new(), MARGIN_MS, |p| watermarks.get(p));
+ let none = HashSet::new();
+ let split = split_for_admission(
+ batch,
+ &HashSet::new(),
+ &fence_only(&none, |p| watermarks.get(p)),
+ );
assert_eq!(offsets(&split.admitted), vec![1, 2]);
assert!(split.admitted.iter().all(|seed| seed.partition == 1));
assert_eq!(offsets(&split.held[&2]), vec![1]);
}
+ /// Live-priority violated by leaking fence-open tiles: a lagging partition must hold its
+ /// whole batch — leading skips included — while other partitions stay unaffected.
+ #[test]
+ fn live_lag_gate_holds_everything_including_leading_skips() {
+ let watermarks = LiveWatermarks::new();
+ watermarks.observe(3, i64::MAX); // fence wide open — the gate must hold regardless
+ watermarks.observe(4, i64::MAX);
+ let batch = vec![skip(3, 1), seed(3, 2, 0), skip(3, 3), seed(4, 7, 0)];
+
+ let lagging = HashSet::from([3]);
+ let split = split_for_admission(
+ batch,
+ &HashSet::new(),
+ &fence_only(&lagging, |p| watermarks.get(p)),
+ );
+
+ assert_eq!(
+ offsets(&split.admitted),
+ vec![7],
+ "only the un-gated partition flows"
+ );
+ assert_eq!(offsets(&split.held[&3]), vec![1, 2, 3]);
+ assert_eq!(split.causes[&3], causes_of(&[PauseCause::LiveLag]));
+ assert!(
+ !split.deficits.contains_key(&3),
+ "an open fence adds neither a fence cause nor a deficit while gated",
+ );
+ }
+
+ /// The pod-wide disk gate must hold every partition, fence state notwithstanding.
+ #[test]
+ fn disk_gate_holds_all_partitions() {
+ let watermarks = LiveWatermarks::new();
+ watermarks.observe(1, i64::MAX);
+ watermarks.observe(2, i64::MAX);
+ let batch = vec![seed(1, 10, 0), skip(1, 11), seed(2, 20, 0)];
+
+ let none = HashSet::new();
+ let policy = AdmissionPolicy {
+ disk_pressure: true,
+ ..fence_only(&none, |p| watermarks.get(p))
+ };
+ let split = split_for_admission(batch, &HashSet::new(), &policy);
+
+ assert!(split.admitted.is_empty());
+ assert_eq!(offsets(&split.held[&1]), vec![10, 11]);
+ assert_eq!(offsets(&split.held[&2]), vec![20]);
+ assert_eq!(split.causes[&1], causes_of(&[PauseCause::DiskPressure]));
+ assert_eq!(split.causes[&2], causes_of(&[PauseCause::DiskPressure]));
+ }
+
+ /// The fence gauges must stay continuous through a live-lag/disk episode: a gated partition
+ /// still probes its first tile's fence and attributes the cause + deficit.
+ #[test]
+ fn gated_partition_still_attributes_fence_and_deficit() {
+ let watermarks = LiveWatermarks::new();
+ watermarks.observe(1, 100 + MARGIN_MS + 1); // clears s_chunk 100, not 10_000_000
+ let batch = vec![skip(1, 9), seed(1, 10, 10_000_000), seed(1, 11, 100)];
+
+ let lagging = HashSet::from([1]);
+ let split = split_for_admission(
+ batch,
+ &HashSet::new(),
+ &fence_only(&lagging, |p| watermarks.get(p)),
+ );
+
+ assert!(split.admitted.is_empty());
+ assert_eq!(offsets(&split.held[&1]), vec![9, 10, 11]);
+ assert_eq!(
+ split.causes[&1],
+ causes_of(&[PauseCause::LiveLag, PauseCause::Fence]),
+ );
+ assert_eq!(
+ split.deficits[&1],
+ Some(10_000_000 + MARGIN_MS - (100 + MARGIN_MS + 1)),
+ "the first tile's deficit is attributed even while gated",
+ );
+ }
+
+ /// An absent watermark is fence-fail-closed already; a redundant live-lag hold would poison
+ /// the hysteresis memory on a new tenure. It must be counted, never gated.
+ #[test]
+ fn absent_watermark_counts_no_watermark_but_never_live_lags() {
+ let watermarks = LiveWatermarks::new();
+ let now_ms = 1_000_000;
+ watermarks.observe(1, now_ms - 500_000); // deep lag: gated
+ // Partition 2 has no watermark at all.
+ let owned = HashSet::from([1, 2]);
+ let hysteresis = Hysteresis::new(AgeMs(120_000), AgeMs(60_000)).unwrap();
+
+ let assessment = assess_live_lag(
+ &owned,
+ |p| watermarks.get(p),
+ &PauseLedger::default(),
+ Some(hysteresis),
+ now_ms,
+ );
+
+ assert_eq!(assessment.lagging, HashSet::from([1]));
+ assert_eq!(assessment.no_watermark, 1);
+ assert_eq!(assessment.ages_ms, HashMap::from([(1, 500_000)]));
+ }
+
+ /// The release threshold must apply only to partitions the ledger remembers as live-lagging;
+ /// an age between the thresholds engages nothing new.
+ #[test]
+ fn live_lag_hysteresis_uses_ledger_memory() {
+ let watermarks = LiveWatermarks::new();
+ let now_ms = 1_000_000;
+ // Both partitions sit between release (60s) and engage (120s).
+ watermarks.observe(1, now_ms - 90_000);
+ watermarks.observe(2, now_ms - 90_000);
+ let owned = HashSet::from([1, 2]);
+ let hysteresis = Hysteresis::new(AgeMs(120_000), AgeMs(60_000)).unwrap();
+
+ let mut ledger = PauseLedger::default();
+ ledger.reconcile(1, causes_of(&[PauseCause::LiveLag]), Instant::now());
+
+ let assessment = assess_live_lag(
+ &owned,
+ |p| watermarks.get(p),
+ &ledger,
+ Some(hysteresis),
+ now_ms,
+ );
+
+ assert_eq!(
+ assessment.lagging,
+ HashSet::from([1]),
+ "only the remembered partition stays engaged between the thresholds",
+ );
+ }
+
+ /// A partition whose ledger causes cleared but whose dispatch bounced must re-enter the
+ /// causes map as channel-full, or the ledger would resume a partition that still holds work.
+ #[test]
+ fn merge_cycle_causes_adds_channel_full_for_bounced_partitions() {
+ let refence = HashMap::from([(1, causes_of(&[PauseCause::Fence]))]);
+ let fresh = HashMap::from([
+ (1, causes_of(&[PauseCause::LiveLag])),
+ (2, causes_of(&[PauseCause::DiskPressure])),
+ ]);
+
+ let merged = merge_cycle_causes(refence, fresh, [1, 3]);
+
+ assert_eq!(
+ merged[&1],
+ causes_of(&[
+ PauseCause::Fence,
+ PauseCause::LiveLag,
+ PauseCause::ChannelFull
+ ]),
+ );
+ assert_eq!(merged[&2], causes_of(&[PauseCause::DiskPressure]));
+ assert_eq!(merged[&3], causes_of(&[PauseCause::ChannelFull]));
+ }
+
#[test]
fn holdover_absorb_take_preserves_per_partition_fifo_and_prunes_revoked() {
let mut holdover = SeedHoldover::default();
@@ -817,14 +1275,20 @@ mod tests {
));
}
+ /// A channel-full bounce round-trips through the shuffle message; losing `broker_ts_ms` there
+ /// would zero the oldest-held age gauge exactly when the partition is stuck.
#[test]
fn consumed_seed_round_trips_through_its_shuffle_message() {
- let consumed = seed(9, 42, 123);
+ let consumed = ConsumedSeed {
+ broker_ts_ms: Some(1_700_000_000_000),
+ ..seed(9, 42, 123)
+ };
let message = consumed.into_message();
assert_eq!(message.seed_offset(), Some(42));
let back = ConsumedSeed::from_message(9, message).unwrap();
assert_eq!(back.partition, 9);
assert_eq!(back.offset, 42);
+ assert_eq!(back.broker_ts_ms, Some(1_700_000_000_000));
assert!(matches!(back.work, SeedWork::Tile(tile) if tile.s_chunk_ms() == SChunkMs(123)));
let reconcile = ReconcileTile::new(
@@ -837,9 +1301,11 @@ mod tests {
work: SeedWork::Reconcile(reconcile.clone()),
partition: 9,
offset: 43,
+ broker_ts_ms: None,
};
let back = ConsumedSeed::from_message(9, consumed.into_message()).unwrap();
assert_eq!(back.offset, 43);
+ assert_eq!(back.broker_ts_ms, None);
assert!(matches!(back.work, SeedWork::Reconcile(tile) if tile == reconcile));
let not_seed = ShuffleMessage::RedrivePendingTransfers;
@@ -858,22 +1324,22 @@ mod tests {
work: SeedWork::Reconcile(reconcile.clone()),
partition: 3,
offset,
+ broker_ts_ms: None,
};
- let open_prefix = split_at_fence(
+ let none = HashSet::new();
+ let open_prefix = split_for_admission(
vec![reconcile_seed(1), seed(3, 2, 0)],
&HashSet::new(),
- MARGIN_MS,
- |_| None,
+ &fence_only(&none, |_| None),
);
assert_eq!(offsets(&open_prefix.admitted), vec![1]);
assert_eq!(offsets(&open_prefix.held[&3]), vec![2]);
- let closed_prefix = split_at_fence(
+ let closed_prefix = split_for_admission(
vec![seed(3, 3, 0), reconcile_seed(4)],
&HashSet::new(),
- MARGIN_MS,
- |_| None,
+ &fence_only(&none, |_| None),
);
assert!(closed_prefix.admitted.is_empty());
assert_eq!(offsets(&closed_prefix.held[&3]), vec![3, 4]);
@@ -949,4 +1415,220 @@ mod tests {
"the still-owned partition advances",
);
}
+
+ mod admission_cycle {
+ //! Behavioral checks of [`run_admission_cycle`] against a real dispatcher and store;
+ //! the pause channel and the seed tracker's ceiling are the observables.
+
+ use tempfile::TempDir;
+
+ use crate::observability::disk::DiskUtilization;
+ use crate::partitions::{OffsetTracker, PartitionRouter};
+ use crate::producer::CaptureSink;
+ use crate::store::{CohortStore, OffloadConfig, OffloadMode, StoreConfig, StoreHandle};
+ use crate::workers::MergeWorkerDeps;
+
+ use super::*;
+
+ fn pacing_dispatcher(dir: &TempDir) -> Arc<EventDispatcher> {
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .expect("open store");
+ let handle = StoreHandle::new(
+ store,
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ );
+ Arc::new(EventDispatcher::new(
+ PartitionRouter::new(64),
+ Arc::new(OffsetTracker::new()),
+ handle,
+ Arc::new(crate::filters::CatalogHandle::new()),
+ Arc::new(CaptureSink::new()),
+ MergeWorkerDeps::capture(),
+ ))
+ }
+
+ /// The spawned worker marks a dispatched skip processed; a held skip never advances.
+ async fn wait_for_committable(dispatcher: &EventDispatcher, partition: i32, expected: i64) {
+ let deadline = Instant::now() + Duration::from_secs(10);
+ loop {
+ let committable = dispatcher
+ .merge_deps()
+ .seed_tracker
+ .committable_offsets()
+ .get(&partition)
+ .copied();
+ if committable == Some(expected) {
+ return;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "timed out waiting for partition {partition} committable {expected}, at {committable:?}",
+ );
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ }
+
+ /// A lagging live watermark holds the polled seeds and pauses the partition within one
+ /// cycle; recovery past the release threshold redispatches the held offset before the
+ /// fresh one.
+ #[tokio::test]
+ async fn live_lag_pauses_within_a_cycle_and_resumes_held_before_fresh() {
+ let dir = TempDir::new().unwrap();
+ let dispatcher = pacing_dispatcher(&dir);
+ dispatcher.assign_partition(0);
+ let watermarks = dispatcher.merge_deps().live_watermarks.clone();
+
+ let pacing_config = SeedPacingConfig {
+ live_lag: Some(Hysteresis::new(AgeMs(120_000), AgeMs(60_000)).unwrap()),
+ disk: None,
+ };
+ let mut holdover = SeedHoldover::default();
+ let mut pacing = SeedPacing::default();
+ let mut prev = HashSet::new();
+ let (pause_tx, mut pause_rx) = tokio::sync::mpsc::unbounded_channel();
+
+ let now_ms = chrono::Utc::now().timestamp_millis();
+ watermarks.observe(0, now_ms - 300_000);
+ run_admission_cycle(
+ &dispatcher,
+ &pacing_config,
+ None,
+ MARGIN_MS,
+ vec![skip(0, 5)],
+ &mut holdover,
+ &mut pacing,
+ &mut prev,
+ &pause_tx,
+ now_ms,
+ Instant::now(),
+ );
+ assert_eq!(holdover.held_partitions(), HashSet::from([0]));
+ assert_eq!(pause_rx.try_recv().unwrap(), HashSet::from([0]));
+ assert!(
+ dispatcher
+ .merge_deps()
+ .seed_tracker
+ .committable_offsets()
+ .is_empty(),
+ "a gated skip never dispatches, so its offset cannot commit",
+ );
+
+ let now_ms = chrono::Utc::now().timestamp_millis();
+ watermarks.observe(0, now_ms);
+ run_admission_cycle(
+ &dispatcher,
+ &pacing_config,
+ None,
+ MARGIN_MS,
+ vec![skip(0, 6)],
+ &mut holdover,
+ &mut pacing,
+ &mut prev,
+ &pause_tx,
+ now_ms,
+ Instant::now(),
+ );
+ assert!(holdover.held_partitions().is_empty());
+ assert_eq!(pause_rx.try_recv().unwrap(), HashSet::new());
+ // Committable 7 requires both offsets marked: held 5 redispatched before fresh 6.
+ wait_for_committable(&dispatcher, 0, 7).await;
+ }
+
+ /// A sample at or above the pause threshold holds every partition, a between-thresholds
+ /// sample stays engaged (hysteresis), and an absent sample releases — a broken probe
+ /// must never wedge seeding.
+ #[tokio::test]
+ async fn disk_pressure_pauses_all_partitions_and_an_absent_sample_never_pauses() {
+ let dir = TempDir::new().unwrap();
+ let dispatcher = pacing_dispatcher(&dir);
+ dispatcher.assign_partition(1);
+ dispatcher.assign_partition(2);
+ let watermarks = dispatcher.merge_deps().live_watermarks.clone();
+ let now_ms = chrono::Utc::now().timestamp_millis();
+ watermarks.observe(1, now_ms);
+ watermarks.observe(2, now_ms);
+
+ let pacing_config = SeedPacingConfig {
+ live_lag: None,
+ disk: Some(Hysteresis::new(UsedPct(60.0), UsedPct(55.0)).unwrap()),
+ };
+ let mut holdover = SeedHoldover::default();
+ let mut pacing = SeedPacing::default();
+ let mut prev = HashSet::new();
+ let (pause_tx, mut pause_rx) = tokio::sync::mpsc::unbounded_channel();
+
+ let over = DiskUtilization {
+ total_bytes: 100,
+ available_bytes: 30, // 70% used
+ };
+ run_admission_cycle(
+ &dispatcher,
+ &pacing_config,
+ Some(over),
+ MARGIN_MS,
+ vec![skip(1, 0), skip(2, 0)],
+ &mut holdover,
+ &mut pacing,
+ &mut prev,
+ &pause_tx,
+ now_ms,
+ Instant::now(),
+ );
+ assert!(pacing.disk_engaged);
+ assert_eq!(holdover.held_partitions(), HashSet::from([1, 2]));
+ assert_eq!(pause_rx.try_recv().unwrap(), HashSet::from([1, 2]));
+
+ // Between the thresholds: sticky, still held.
+ let between = DiskUtilization {
+ total_bytes: 100,
+ available_bytes: 43, // 57% used
+ };
+ run_admission_cycle(
+ &dispatcher,
+ &pacing_config,
+ Some(between),
+ MARGIN_MS,
+ vec![],
+ &mut holdover,
+ &mut pacing,
+ &mut prev,
+ &pause_tx,
+ now_ms,
+ Instant::now(),
+ );
+ assert!(
+ pacing.disk_engaged,
+ "57% is above the 55% release threshold"
+ );
+ assert_eq!(holdover.held_partitions(), HashSet::from([1, 2]));
+ assert_eq!(pause_rx.try_recv().unwrap(), HashSet::from([1, 2]));
+
+ // The probe breaks: fail-open, everything drains.
+ run_admission_cycle(
+ &dispatcher,
+ &pacing_config,
+ None,
+ MARGIN_MS,
+ vec![],
+ &mut holdover,
+ &mut pacing,
+ &mut prev,
+ &pause_tx,
+ now_ms,
+ Instant::now(),
+ );
+ assert!(!pacing.disk_engaged);
+ assert!(holdover.held_partitions().is_empty());
+ assert_eq!(pause_rx.try_recv().unwrap(), HashSet::new());
+ wait_for_committable(&dispatcher, 1, 1).await;
+ wait_for_committable(&dispatcher, 2, 1).await;
+ }
+ }
}
diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rs
index 66467531192d..aec0e515655f 100644
--- a/rust/cohort-stream-processor/src/main.rs
+++ b/rust/cohort-stream-processor/src/main.rs
@@ -24,7 +24,8 @@ use cohort_stream_processor::filters::{run_refresh_loop, CatalogHandle};
use cohort_stream_processor::merge::gc::MergeGcSweeper;
use cohort_stream_processor::merge::redrive::RedriveSweeper;
use cohort_stream_processor::observability;
-use cohort_stream_processor::observability::store_stats::StoreStatsSweeper;
+use cohort_stream_processor::observability::disk::SharedDiskUtilization;
+use cohort_stream_processor::observability::store_stats::{DiskProbe, StoreStatsSweeper};
use cohort_stream_processor::observability::tokio_monitor::TokioRuntimeMonitor;
use cohort_stream_processor::partitions::{
run_rebalance_worker, CohortConsumerContext, ConsumerPauser, Follower, FollowerSet,
@@ -69,7 +70,7 @@ async fn async_main(config: Config) -> Result<()> {
init_tracing();
log_startup(&config);
- config.validate_durability_startup()?;
+ config.validate_startup()?;
let mut manager = Manager::builder(SERVICE_NAME)
.with_global_shutdown_timeout(Duration::from_secs(90))
@@ -498,10 +499,18 @@ async fn async_main(config: Config) -> Result<()> {
));
}
- // Publish store cache/size metrics via the sweep machinery, and Tokio runtime metrics via a
- // separate monitor.
+ // Publish store cache/size metrics and the store filesystem's utilization via the sweep
+ // machinery, and Tokio runtime metrics via a separate monitor. The disk snapshot feeds the
+ // seed consumer's disk-backpressure gate; a sample surviving four sweep ticks unrefreshed
+ // means the sweep is wedged, so it expires rather than latching the gate.
+ let disk_state = Arc::new(SharedDiskUtilization::new(
+ config.stats_publish_interval() * 4,
+ ));
tokio::spawn(run_sweep_loop(
- StoreStatsSweeper::new(handle_for_stats),
+ StoreStatsSweeper::new(
+ handle_for_stats,
+ DiskProbe::new(PathBuf::from(&config.store_path), disk_state.clone()),
+ ),
config.stats_publish_interval(),
"store_stats",
consumer_handle.shutdown_token(),
@@ -625,6 +634,8 @@ async fn async_main(config: Config) -> Result<()> {
config.offset_commit_interval(),
config.cohort_seed_fence_margin_ms,
config.seed_idle_probe_interval(),
+ config.seed_pacing_config()?,
+ disk_state.clone(),
);
let seed_catalog = catalog.clone();
tokio::spawn(async move {
@@ -790,6 +801,10 @@ fn log_startup(config: &Config) {
seed_topic = %config.cohort_stream_seed_events_topic,
seed_consumer_group = %config.kafka_seed_consumer_group,
seed_fence_margin_ms = config.cohort_seed_fence_margin_ms,
+ cohort_seed_live_lag_pause_ms = config.cohort_seed_live_lag_pause_ms,
+ cohort_seed_live_lag_resume_ms = config.cohort_seed_live_lag_resume_ms,
+ cohort_seed_disk_pause_pct = config.cohort_seed_disk_pause_pct,
+ cohort_seed_disk_resume_pct = config.cohort_seed_disk_resume_pct,
cohort_seed_reconcile_enabled = config.cohort_seed_reconcile_enabled,
cohort_seed_reconcile_scan_page = config.cohort_seed_reconcile_scan_page,
cohort_seed_reconcile_tick_interval_ms = config.cohort_seed_reconcile_tick_interval_ms,
diff --git a/rust/cohort-stream-processor/src/observability/disk.rs b/rust/cohort-stream-processor/src/observability/disk.rs
new file mode 100644
index 000000000000..2bc333ec3bb4
--- /dev/null
+++ b/rust/cohort-stream-processor/src/observability/disk.rs
@@ -0,0 +1,177 @@
+//! Store-filesystem utilization sampling — the seed consumer's disk-backpressure input.
+//!
+//! The [`StoreStatsSweeper`](crate::observability::store_stats::StoreStatsSweeper) samples and
+//! publishes into a [`SharedDiskUtilization`]; the seed consumer reads the latest snapshot each
+//! cycle. `None` (no successful sample yet, the last sample failed, or the last sample is older
+//! than the staleness bound) is **fail-open**: absence can never pause — a broken or wedged probe
+//! must never wedge seeding.
+
+use std::io;
+use std::path::Path;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use arc_swap::ArcSwapOption;
+
+/// One filesystem sample. `available_bytes` is `f_bavail`-based (bytes available to unprivileged
+/// writes), matching df. Kubelet's `used_bytes` is `f_bfree`-based, so on a filesystem with a
+/// root reserve this reads a few points higher than kubelet's used/capacity ratio.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct DiskUtilization {
+ pub total_bytes: u64,
+ pub available_bytes: u64,
+}
+
+impl DiskUtilization {
+ /// Used share in percent, 0–100. Root-reserved blocks count as used (the `f_bavail` view), so
+ /// this reads slightly higher than raw free space — conservative in the pause direction.
+ pub fn used_pct(&self) -> f64 {
+ if self.total_bytes == 0 {
+ return 0.0;
+ }
+ let used = self.total_bytes.saturating_sub(self.available_bytes);
+ (used as f64 / self.total_bytes as f64) * 100.0
+ }
+}
+
+/// Sample the filesystem holding `path` via `statvfs`. Byte sizes use `f_frsize` (the fragment
+/// size), which is the unit `f_blocks`/`f_bavail` are counted in — `f_bsize` is only the
+/// preferred I/O size and differs on some filesystems.
+#[cfg(unix)]
+// The statvfs field widths are platform-dependent (u32 vs u64), so these widening conversions
+// are identity on some targets.
+#[allow(clippy::useless_conversion)]
+pub fn sample_store_filesystem(path: &Path) -> io::Result<DiskUtilization> {
+ let stat = nix::sys::statvfs::statvfs(path)
+ .map_err(|errno| io::Error::from_raw_os_error(errno as i32))?;
+ let fragment_size = u64::from(stat.fragment_size());
+ Ok(DiskUtilization {
+ total_bytes: u64::from(stat.blocks()).saturating_mul(fragment_size),
+ available_bytes: u64::from(stat.blocks_available()).saturating_mul(fragment_size),
+ })
+}
+
+#[cfg(not(unix))]
+pub fn sample_store_filesystem(_path: &Path) -> io::Result<DiskUtilization> {
+ Err(io::Error::new(
+ io::ErrorKind::Unsupported,
+ "statvfs is unavailable on this platform",
+ ))
+}
+
+/// The latest disk sample: sweeper-written, seed-consumer-read. A sample older than
+/// `max_sample_age` reads as `None`, so a wedged sweep loop cannot latch the gate on a stale
+/// reading — staleness fails open like any other probe failure.
+#[derive(Debug)]
+pub struct SharedDiskUtilization {
+ sample: ArcSwapOption<StampedSample>,
+ max_sample_age: Duration,
+}
+
+#[derive(Debug)]
+struct StampedSample {
+ utilization: DiskUtilization,
+ sampled_at: Instant,
+}
+
+impl SharedDiskUtilization {
+ pub fn new(max_sample_age: Duration) -> Self {
+ Self {
+ sample: ArcSwapOption::empty(),
+ max_sample_age,
+ }
+ }
+
+ /// Publish the newest sample; `None` records a failed sample (fail-open for the gate).
+ pub fn publish(&self, sample: Option<DiskUtilization>) {
+ self.sample.store(sample.map(|utilization| {
+ Arc::new(StampedSample {
+ utilization,
+ sampled_at: Instant::now(),
+ })
+ }));
+ }
+
+ pub fn latest(&self) -> Option<DiskUtilization> {
+ let sample = self.sample.load();
+ let sample = sample.as_deref()?;
+ (sample.sampled_at.elapsed() < self.max_sample_age).then_some(sample.utilization)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Pins the percentage arithmetic (an available/total swap or a fragment-size mixup would show
+ /// up as a nonsense share) and the zero-total guard.
+ #[test]
+ fn used_pct_is_the_unavailable_share_and_zero_total_is_zero() {
+ let sample = DiskUtilization {
+ total_bytes: 100,
+ available_bytes: 25,
+ };
+ assert_eq!(sample.used_pct(), 75.0);
+
+ let empty = DiskUtilization {
+ total_bytes: 0,
+ available_bytes: 0,
+ };
+ assert_eq!(empty.used_pct(), 0.0);
+
+ // Available beyond total (never expected from statvfs) saturates to 0% used, not a panic.
+ let odd = DiskUtilization {
+ total_bytes: 10,
+ available_bytes: 20,
+ };
+ assert_eq!(odd.used_pct(), 0.0);
+ }
+
+ /// Catches unit/field mixups (`f_bsize` vs `f_frsize`, blocks vs bytes): a real filesystem
+ /// must report a sane, internally-consistent sample.
+ #[cfg(unix)]
+ #[test]
+ fn sample_store_filesystem_on_tempdir() {
+ let dir = tempfile::tempdir().unwrap();
+ let sample = sample_store_filesystem(dir.path()).unwrap();
+ assert!(sample.total_bytes > 0, "a real filesystem has capacity");
+ assert!(
+ sample.available_bytes <= sample.total_bytes,
+ "available cannot exceed total",
+ );
+ let pct = sample.used_pct();
+ assert!((0.0..=100.0).contains(&pct), "share out of range: {pct}");
+ }
+
+ #[test]
+ fn shared_snapshot_publishes_and_clears() {
+ let shared = SharedDiskUtilization::new(Duration::MAX);
+ assert_eq!(shared.latest(), None, "fail-open before any sample");
+
+ let sample = DiskUtilization {
+ total_bytes: 50,
+ available_bytes: 10,
+ };
+ shared.publish(Some(sample));
+ assert_eq!(shared.latest(), Some(sample));
+
+ shared.publish(None);
+ assert_eq!(
+ shared.latest(),
+ None,
+ "a failed sample returns to fail-open"
+ );
+ }
+
+ /// A wedged sweep loop stops republishing; the last sample must expire into `None` rather
+ /// than latch the gate on a stale reading.
+ #[test]
+ fn a_sample_older_than_the_bound_reads_as_none() {
+ let shared = SharedDiskUtilization::new(Duration::ZERO);
+ shared.publish(Some(DiskUtilization {
+ total_bytes: 50,
+ available_bytes: 10,
+ }));
+ assert_eq!(shared.latest(), None, "at or past the bound is stale");
+ }
+}
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
index 073592cc078c..8e72f5f7451d 100644
--- a/rust/cohort-stream-processor/src/observability/metrics.rs
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -169,6 +169,19 @@ pub const STORE_LIVE_DATA_BYTES: &str = "store_live_data_bytes";
/// Estimated key count, labelled by `cf` (gauge).
pub const STORE_ESTIMATE_NUM_KEYS: &str = "store_estimate_num_keys";
+/// Size of the filesystem holding the store (gauge, bytes).
+pub const STORE_DISK_TOTAL_BYTES: &str = "store_disk_total_bytes";
+/// Bytes on the store filesystem available to unprivileged writes (`f_bavail`) (gauge).
+pub const STORE_DISK_AVAILABLE_BYTES: &str = "store_disk_available_bytes";
+/// Used share of the store filesystem, 0–100 (gauge). `f_bavail`-based like df, so it reads a
+/// few points above kubelet's used/capacity ratio on filesystems with a root reserve.
+/// **Alert on a sustained high level** — RocksDB compaction needs headroom well before disk-full.
+pub const STORE_DISK_UTILIZATION_PCT: &str = "store_disk_utilization_pct";
+/// Failed store-filesystem samples, including ticks skipped because the previous sample is still
+/// running (counter). While failing, the seed disk gate reads no fresh sample and never pauses
+/// (fail-open), so a persistently non-zero rate means the gate is dark.
+pub const STORE_DISK_SAMPLE_ERRORS_TOTAL: &str = "store_disk_sample_errors_total";
+
/// Fraction of wall-clock worker-time spent executing tasks (gauge, 0.0–1.0).
pub const TOKIO_RUNTIME_BUSY_RATIO: &str = "tokio_runtime_busy_ratio";
/// Tasks spawned but not yet completed on the runtime (gauge).
@@ -461,12 +474,36 @@ pub const SEED_REKEY_HOP_CAPPED_TOTAL: &str = "cohort_seed_rekey_hop_capped_tota
/// The seed commit floor pinned by a sticky offset hold, labelled by `partition` (gauge).
/// **Alert on a sustained non-zero level.**
pub const SEED_HELD_OFFSET_GAUGE: &str = "seed_held_offset";
-/// Seed partitions currently held, fence-closed or backpressured (gauge).
+/// Seed partitions currently held for any cause (gauge) — sustained non-zero means tiles are not
+/// landing. [`SEED_PAUSED_PARTITIONS`] carries the per-cause breakdown.
pub const SEED_FENCED_PARTITIONS: &str = "cohort_seed_fenced_partitions";
/// How far the watermark trails `s_chunk + margin` per fenced partition (gauge, ms).
pub const SEED_FENCE_DEFICIT_MS: &str = "cohort_seed_fence_deficit_ms";
/// Age of each owned partition's live watermark, labelled by `partition` (gauge, ms).
pub const LIVE_WATERMARK_AGE_MS: &str = "cohort_live_watermark_age_ms";
+/// Seed partitions currently paused, labelled by `cause`
+/// (`fence`|`channel_full`|`live_lag`|`disk_pressure`) (gauge). A partition holding several
+/// causes counts under each.
+pub const SEED_PAUSED_PARTITIONS: &str = "cohort_seed_paused_partitions";
+/// Continuous pause age per paused seed partition, labelled by `partition` (gauge, ms). Cause
+/// churn does not reset it. **Alert well below the seed topic's retention** — sustained live load
+/// can defer seeding indefinitely without any lag alarm firing.
+pub const SEED_PAUSE_AGE_MS: &str = "cohort_seed_pause_age_ms";
+/// Owned partitions with no live watermark at all (gauge). Fence-fail-closed with an unknown
+/// deficit, so otherwise indistinguishable from a merely trailing watermark on the deficit gauge.
+pub const SEED_NO_WATERMARK_PARTITIONS: &str = "cohort_seed_no_watermark_partitions";
+/// Broker-timestamp age of the oldest held seed per held partition, labelled by `partition`
+/// (gauge, ms). During a long pause this — not the pause age — is the distance to the seed
+/// topic's retention cliff. A missing broker timestamp reads 0.
+pub const SEED_OLDEST_HELD_AGE_MS: &str = "cohort_seed_oldest_held_age_ms";
+/// Wall-clock duration of one idle-probe pass across all owned partitions (histogram, seconds).
+/// Quiet partitions' watermarks advance only per pass, so a slow pass delays fence opens and
+/// live-lag releases alike.
+pub const SEED_IDLE_PROBE_DURATION_SECONDS: &str = "cohort_seed_idle_probe_duration_seconds";
+/// Unix timestamp of the last completed idle-probe pass (gauge, seconds). **Alert on
+/// staleness** — quiet partitions' fences and the live-lag gate both stall when the probe stops.
+pub const SEED_IDLE_PROBE_LAST_PASS_TIMESTAMP_SECONDS: &str =
+ "cohort_seed_idle_probe_last_pass_timestamp_seconds";
/// Reconcile jobs admitted to partition-local queues (counter).
pub const RECONCILE_JOBS_ENQUEUED_TOTAL: &str = "cohort_reconcile_jobs_enqueued_total";
/// Reconcile jobs that emitted their completion marker and released their seed floor (counter).
@@ -626,6 +663,13 @@ mod tests {
assert_eq!(STORE_SST_BYTES, "store_sst_bytes");
assert_eq!(STORE_LIVE_DATA_BYTES, "store_live_data_bytes");
assert_eq!(STORE_ESTIMATE_NUM_KEYS, "store_estimate_num_keys");
+ assert_eq!(STORE_DISK_TOTAL_BYTES, "store_disk_total_bytes");
+ assert_eq!(STORE_DISK_AVAILABLE_BYTES, "store_disk_available_bytes");
+ assert_eq!(STORE_DISK_UTILIZATION_PCT, "store_disk_utilization_pct");
+ assert_eq!(
+ STORE_DISK_SAMPLE_ERRORS_TOTAL,
+ "store_disk_sample_errors_total"
+ );
assert_eq!(TOKIO_RUNTIME_BUSY_RATIO, "tokio_runtime_busy_ratio");
assert_eq!(TOKIO_RUNTIME_ALIVE_TASKS, "tokio_runtime_alive_tasks");
assert_eq!(
@@ -734,6 +778,21 @@ mod tests {
assert_eq!(SEED_HELD_OFFSET_GAUGE, "seed_held_offset");
assert_eq!(SEED_FENCED_PARTITIONS, "cohort_seed_fenced_partitions");
assert_eq!(SEED_FENCE_DEFICIT_MS, "cohort_seed_fence_deficit_ms");
+ assert_eq!(SEED_PAUSED_PARTITIONS, "cohort_seed_paused_partitions");
+ assert_eq!(SEED_PAUSE_AGE_MS, "cohort_seed_pause_age_ms");
+ assert_eq!(
+ SEED_NO_WATERMARK_PARTITIONS,
+ "cohort_seed_no_watermark_partitions"
+ );
+ assert_eq!(SEED_OLDEST_HELD_AGE_MS, "cohort_seed_oldest_held_age_ms");
+ assert_eq!(
+ SEED_IDLE_PROBE_DURATION_SECONDS,
+ "cohort_seed_idle_probe_duration_seconds"
+ );
+ assert_eq!(
+ SEED_IDLE_PROBE_LAST_PASS_TIMESTAMP_SECONDS,
+ "cohort_seed_idle_probe_last_pass_timestamp_seconds"
+ );
assert_eq!(
RECONCILE_JOBS_ENQUEUED_TOTAL,
"cohort_reconcile_jobs_enqueued_total"
diff --git a/rust/cohort-stream-processor/src/observability/mod.rs b/rust/cohort-stream-processor/src/observability/mod.rs
index c6b55f334e9b..4007a0a9bdd8 100644
--- a/rust/cohort-stream-processor/src/observability/mod.rs
+++ b/rust/cohort-stream-processor/src/observability/mod.rs
@@ -1,6 +1,7 @@
//! Observability surface: health/readiness probes, Prometheus metrics, and the canonical log.
pub mod canonical_log;
+pub mod disk;
pub mod health;
pub mod metrics;
pub mod store_stats;
diff --git a/rust/cohort-stream-processor/src/observability/store_stats.rs b/rust/cohort-stream-processor/src/observability/store_stats.rs
index 9b9104b05fbc..5628dc30591b 100644
--- a/rust/cohort-stream-processor/src/observability/store_stats.rs
+++ b/rust/cohort-stream-processor/src/observability/store_stats.rs
@@ -1,37 +1,101 @@
//! Periodic publisher of RocksDB store statistics (block-cache tickers, cache usage, per-CF sizes)
-//! via the shared sweep machinery. Read latency is timed inline in [`crate::store::rocks`].
+//! and the store filesystem's utilization, via the shared sweep machinery. Read latency is timed
+//! inline in [`crate::store::rocks`].
+
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
use async_trait::async_trait;
use metrics::{counter, gauge};
-use tracing::debug;
+use tracing::{debug, warn};
+use crate::observability::disk::{sample_store_filesystem, SharedDiskUtilization};
use crate::observability::metrics::{
STORE_BLOCK_CACHE_DATA_HITS_TOTAL, STORE_BLOCK_CACHE_DATA_MISSES_TOTAL,
STORE_BLOCK_CACHE_FILTER_HITS_TOTAL, STORE_BLOCK_CACHE_FILTER_MISSES_TOTAL,
STORE_BLOCK_CACHE_HITS_TOTAL, STORE_BLOCK_CACHE_INDEX_HITS_TOTAL,
STORE_BLOCK_CACHE_INDEX_MISSES_TOTAL, STORE_BLOCK_CACHE_MISSES_TOTAL,
- STORE_BLOCK_CACHE_USAGE_BYTES, STORE_BLOOM_FILTER_USEFUL_TOTAL, STORE_ESTIMATE_NUM_KEYS,
- STORE_LIVE_DATA_BYTES, STORE_SST_BYTES,
+ STORE_BLOCK_CACHE_USAGE_BYTES, STORE_BLOOM_FILTER_USEFUL_TOTAL, STORE_DISK_AVAILABLE_BYTES,
+ STORE_DISK_SAMPLE_ERRORS_TOTAL, STORE_DISK_TOTAL_BYTES, STORE_DISK_UTILIZATION_PCT,
+ STORE_ESTIMATE_NUM_KEYS, STORE_LIVE_DATA_BYTES, STORE_SST_BYTES,
};
use crate::store::StoreHandle;
use crate::sweep::Sweeper;
+/// Samples the store filesystem each stats tick, publishing the `store_disk_*` gauges plus the
+/// shared snapshot the seed consumer's disk gate reads.
+pub struct DiskProbe {
+ store_path: PathBuf,
+ shared: Arc<SharedDiskUtilization>,
+ /// At most one statvfs call outstanding: a hung mount must not leak one blocking thread per
+ /// tick until the pool is exhausted.
+ in_flight: Arc<AtomicBool>,
+}
+
+impl DiskProbe {
+ pub fn new(store_path: PathBuf, shared: Arc<SharedDiskUtilization>) -> Self {
+ Self {
+ store_path,
+ shared,
+ in_flight: Arc::new(AtomicBool::new(false)),
+ }
+ }
+
+ /// Detached: the sample publishes from inside the blocking task, so a hung statvfs can never
+ /// wedge the sweep loop or delay the store snapshot — the shared snapshot's staleness bound
+ /// turns the missing refresh into fail-open, and the skipped ticks keep the error counter
+ /// climbing so the wedge is visible.
+ fn run_once(&self) {
+ if self.in_flight.swap(true, Ordering::AcqRel) {
+ counter!(STORE_DISK_SAMPLE_ERRORS_TOTAL).increment(1);
+ warn!(path = %self.store_path.display(), "previous store filesystem sample still running; skipping this tick");
+ return;
+ }
+ let path = self.store_path.clone();
+ let shared = self.shared.clone();
+ let in_flight = self.in_flight.clone();
+ tokio::task::spawn_blocking(move || {
+ let sample = match sample_store_filesystem(&path) {
+ Ok(sample) => {
+ gauge!(STORE_DISK_TOTAL_BYTES).set(sample.total_bytes as f64);
+ gauge!(STORE_DISK_AVAILABLE_BYTES).set(sample.available_bytes as f64);
+ gauge!(STORE_DISK_UTILIZATION_PCT).set(sample.used_pct());
+ Some(sample)
+ }
+ Err(err) => {
+ counter!(STORE_DISK_SAMPLE_ERRORS_TOTAL).increment(1);
+ warn!(error = %err, path = %path.display(), "store filesystem sample failed; the seed disk gate stays fail-open");
+ None
+ }
+ };
+ shared.publish(sample);
+ in_flight.store(false, Ordering::Release);
+ });
+ }
+}
+
/// Publishes [`CohortStore::stats_snapshot`](crate::store::CohortStore::stats_snapshot) onto metrics
/// once per sweep tick, driven by [`run_sweep_loop`](crate::sweep::run_sweep_loop). Goes through the
/// [`StoreHandle`] so its many RocksDB property reads run off the runtime threads.
pub struct StoreStatsSweeper {
handle: StoreHandle,
+ disk: DiskProbe,
}
impl StoreStatsSweeper {
- pub fn new(handle: StoreHandle) -> Self {
- Self { handle }
+ pub fn new(handle: StoreHandle, disk: DiskProbe) -> Self {
+ Self { handle, disk }
}
}
#[async_trait]
impl Sweeper for StoreStatsSweeper {
async fn run_once(&self) {
+ // Fire-and-forget, so neither the disk sample nor the store snapshot can delay or
+ // suppress the other.
+ self.disk.run_once();
+
let stats = match self.handle.stats_snapshot().await {
Ok(stats) => stats,
// Only teardown cancellation errors here; the next tick (if any) re-reads.
diff --git a/rust/cohort-stream-processor/src/partitions/backpressure.rs b/rust/cohort-stream-processor/src/partitions/backpressure.rs
index 7e36c104d393..230cf5c5173a 100644
--- a/rust/cohort-stream-processor/src/partitions/backpressure.rs
+++ b/rust/cohort-stream-processor/src/partitions/backpressure.rs
@@ -69,6 +69,14 @@ impl<T> PartitionHoldover<T> {
self.pending.len()
}
+ /// The FIFO head of each held partition's holdover, read-only. Feeds the oldest-held age
+ /// gauge.
+ pub fn held_heads(&self) -> impl Iterator<Item = (i32, &T)> {
+ self.pending
+ .iter()
+ .filter_map(|(&partition, messages)| messages.first().map(|head| (partition, head)))
+ }
+
/// Total messages held across all held partitions. Feeds the `pending_held_events` gauge.
pub fn held_message_count(&self) -> usize {
self.pending.values().map(Vec::len).sum()
@@ -166,6 +174,26 @@ mod tests {
assert_eq!(offsets(&held[&5]), vec![10, 11, 12]);
}
+ /// The oldest-held age gauge reads the FIFO head; returning any later message would
+ /// understate the retention risk.
+ #[test]
+ fn held_heads_returns_fifo_heads() {
+ let mut bp = Backpressure::new();
+ bp.absorb(HashMap::from([
+ (5, vec![event(10), event(11)]),
+ (6, vec![event(20)]),
+ ]));
+ bp.absorb(HashMap::from([(5, vec![event(12)])]));
+
+ let heads: HashMap<i32, i64> = bp
+ .held_heads()
+ .filter_map(|(partition, message)| {
+ message.event_offset().map(|offset| (partition, offset))
+ })
+ .collect();
+ assert_eq!(heads, HashMap::from([(5, 10), (6, 20)]));
+ }
+
#[test]
fn held_message_count_sums_across_partitions() {
let mut bp = Backpressure::new();
diff --git a/rust/cohort-stream-processor/src/partitions/mod.rs b/rust/cohort-stream-processor/src/partitions/mod.rs
index ca57b5eb908d..8848497f9e81 100644
--- a/rust/cohort-stream-processor/src/partitions/mod.rs
+++ b/rust/cohort-stream-processor/src/partitions/mod.rs
@@ -9,6 +9,7 @@ pub mod backpressure;
pub mod follower;
pub mod intake;
pub mod offset_tracker;
+pub mod pacing;
pub mod pause;
pub mod rebalance;
pub mod router;
@@ -21,6 +22,9 @@ pub use backpressure::{Backpressure, PartitionHoldover};
pub use follower::{Follower, FollowerSet, PartitionMirror};
pub use intake::{Admission, MeteredReceiver, PartitionIntake};
pub use offset_tracker::{DeferredOffset, MarkOutcome, OffsetTracker};
+pub use pacing::{
+ AgeMs, CauseSet, Hysteresis, PauseCause, PauseLedger, SeedPacing, SeedPacingConfig, UsedPct,
+};
pub use partitioner::{
merge_partition_key, murmur2, partition_for, partition_of, COHORT_PARTITION_COUNT,
};
diff --git a/rust/cohort-stream-processor/src/partitions/pacing.rs b/rust/cohort-stream-processor/src/partitions/pacing.rs
new file mode 100644
index 000000000000..ba1d09ec0fe2
--- /dev/null
+++ b/rust/cohort-stream-processor/src/partitions/pacing.rs
@@ -0,0 +1,323 @@
+//! Pure pacing types for the seed consumer's admission gates: *why* a partition's work is held,
+//! for how long, and the hysteresis that keeps the gates from flapping.
+//!
+//! A seed partition is paused **iff** its holdover is non-empty. The [`PauseLedger`] records
+//! per-partition cause sets plus the episode start, and both the pause target and the age/count
+//! metrics derive from it, so "resumed while a cause is active" is unrepresentable: the target is
+//! computed, never mutated.
+
+use std::collections::{HashMap, HashSet};
+use std::time::{Duration, Instant};
+
+/// Why a seed partition's work is held in the holdover.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PauseCause {
+ /// The apply fence: the live watermark has not cleared `s_chunk + margin`.
+ Fence,
+ /// The partition worker's channel (or intake budget) refused the dispatch.
+ ChannelFull,
+ /// Live consumption is lagging; seeding yields (live-priority).
+ LiveLag,
+ /// The store filesystem is above the pause threshold.
+ DiskPressure,
+}
+
+impl PauseCause {
+ pub const ALL: [PauseCause; 4] = [
+ PauseCause::Fence,
+ PauseCause::ChannelFull,
+ PauseCause::LiveLag,
+ PauseCause::DiskPressure,
+ ];
+
+ pub fn as_str(self) -> &'static str {
+ match self {
+ PauseCause::Fence => "fence",
+ PauseCause::ChannelFull => "channel_full",
+ PauseCause::LiveLag => "live_lag",
+ PauseCause::DiskPressure => "disk_pressure",
+ }
+ }
+}
+
+/// A payload-free set of [`PauseCause`]s.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub struct CauseSet {
+ fence: bool,
+ channel_full: bool,
+ live_lag: bool,
+ disk_pressure: bool,
+}
+
+impl CauseSet {
+ pub fn insert(&mut self, cause: PauseCause) {
+ match cause {
+ PauseCause::Fence => self.fence = true,
+ PauseCause::ChannelFull => self.channel_full = true,
+ PauseCause::LiveLag => self.live_lag = true,
+ PauseCause::DiskPressure => self.disk_pressure = true,
+ }
+ }
+
+ pub fn contains(self, cause: PauseCause) -> bool {
+ match cause {
+ PauseCause::Fence => self.fence,
+ PauseCause::ChannelFull => self.channel_full,
+ PauseCause::LiveLag => self.live_lag,
+ PauseCause::DiskPressure => self.disk_pressure,
+ }
+ }
+
+ pub fn union(self, other: Self) -> Self {
+ Self {
+ fence: self.fence || other.fence,
+ channel_full: self.channel_full || other.channel_full,
+ live_lag: self.live_lag || other.live_lag,
+ disk_pressure: self.disk_pressure || other.disk_pressure,
+ }
+ }
+
+ pub fn is_empty(self) -> bool {
+ self == Self::default()
+ }
+}
+
+/// One continuous pause of one partition. `started` survives cause churn, so the age is the
+/// continuous-pause age, not the current cause's age.
+#[derive(Debug)]
+struct PauseEpisode {
+ started: Instant,
+ causes: CauseSet,
+}
+
+/// Per-partition pause bookkeeping: cause sets plus episode start, reconciled once per cycle.
+#[derive(Debug, Default)]
+pub struct PauseLedger {
+ episodes: HashMap<i32, PauseEpisode>,
+}
+
+impl PauseLedger {
+ /// Record this cycle's causes for `partition`. An empty set ends the episode; a non-empty set
+ /// starts one or updates the causes while keeping the original `started`.
+ pub fn reconcile(&mut self, partition: i32, causes: CauseSet, now: Instant) {
+ if causes.is_empty() {
+ self.episodes.remove(&partition);
+ return;
+ }
+ self.episodes
+ .entry(partition)
+ .and_modify(|episode| episode.causes = causes)
+ .or_insert(PauseEpisode {
+ started: now,
+ causes,
+ });
+ }
+
+ /// The partitions to pause — exactly those inside an episode.
+ pub fn pause_target(&self) -> HashSet<i32> {
+ self.episodes.keys().copied().collect()
+ }
+
+ /// Whether `partition` is currently held for `cause` — the hysteresis memory.
+ pub fn has_cause(&self, partition: i32, cause: PauseCause) -> bool {
+ self.episodes
+ .get(&partition)
+ .is_some_and(|episode| episode.causes.contains(cause))
+ }
+
+ /// How long `partition` has been continuously paused; `None` when not paused.
+ pub fn age(&self, partition: i32, now: Instant) -> Option<Duration> {
+ self.episodes
+ .get(&partition)
+ .map(|episode| now.duration_since(episode.started))
+ }
+
+ /// Paused partitions holding `cause`. A partition with several causes counts under each.
+ pub fn count_with(&self, cause: PauseCause) -> usize {
+ self.episodes
+ .values()
+ .filter(|episode| episode.causes.contains(cause))
+ .count()
+ }
+
+ /// Drop episodes for partitions no longer owned, mirroring the holdover's revoke prune, so a
+ /// stale episode can neither pause an unowned toppar nor keep aging its gauge.
+ pub fn drop_unowned(&mut self, owned: &HashSet<i32>) {
+ self.episodes
+ .retain(|partition, _| owned.contains(partition));
+ }
+}
+
+/// A flap-free threshold pair: engage at `engage` or above, release strictly below `release`,
+/// sticky in between. Constructible only with `engage > release`, so a flapping pair is
+/// unrepresentable.
+#[derive(Debug, Clone, Copy)]
+pub struct Hysteresis<T: PartialOrd + Copy> {
+ engage: T,
+ release: T,
+}
+
+/// Rejected [`Hysteresis`] thresholds: `engage <= release` would flap or never release.
+#[derive(Debug, PartialEq, Eq, thiserror::Error)]
+#[error("hysteresis requires engage > release")]
+pub struct InvalidHysteresis;
+
+impl<T: PartialOrd + Copy> Hysteresis<T> {
+ pub fn new(engage: T, release: T) -> Result<Self, InvalidHysteresis> {
+ if engage > release {
+ Ok(Self { engage, release })
+ } else {
+ Err(InvalidHysteresis)
+ }
+ }
+
+ /// The next engaged state given the previous one.
+ pub fn decide(&self, engaged: bool, value: T) -> bool {
+ if engaged {
+ value >= self.release
+ } else {
+ value >= self.engage
+ }
+ }
+}
+
+/// A live-watermark age in ms — a unit newtype so ms and percent cannot cross at the
+/// [`Hysteresis`] seam.
+#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
+pub struct AgeMs(pub i64);
+
+/// A filesystem used share, 0–100.
+#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
+pub struct UsedPct(pub f64);
+
+/// The seed consumer's pacing gates; `None` disables a trigger.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct SeedPacingConfig {
+ pub live_lag: Option<Hysteresis<AgeMs>>,
+ pub disk: Option<Hysteresis<UsedPct>>,
+}
+
+/// The consume loop's pacing state: the ledger plus the disk gate's hysteresis memory. The disk
+/// verdict is pod-wide, so its memory cannot live on any one partition's episode.
+#[derive(Debug, Default)]
+pub struct SeedPacing {
+ pub ledger: PauseLedger,
+ pub disk_engaged: bool,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn causes(list: &[PauseCause]) -> CauseSet {
+ let mut set = CauseSet::default();
+ for &cause in list {
+ set.insert(cause);
+ }
+ set
+ }
+
+ #[test]
+ fn cause_set_insert_contains_union_and_empty() {
+ let mut set = CauseSet::default();
+ assert!(set.is_empty());
+ for cause in PauseCause::ALL {
+ assert!(!set.contains(cause));
+ }
+
+ set.insert(PauseCause::LiveLag);
+ assert!(!set.is_empty());
+ assert!(set.contains(PauseCause::LiveLag));
+ assert!(!set.contains(PauseCause::Fence));
+
+ let merged = set.union(causes(&[PauseCause::Fence, PauseCause::DiskPressure]));
+ assert!(merged.contains(PauseCause::LiveLag));
+ assert!(merged.contains(PauseCause::Fence));
+ assert!(merged.contains(PauseCause::DiskPressure));
+ assert!(!merged.contains(PauseCause::ChannelFull));
+ }
+
+ /// A flapping pair (engage <= release) must be unconstructible; the decide table pins the
+ /// engage-at/release-below boundary semantics.
+ #[test]
+ fn hysteresis_table() {
+ assert!(Hysteresis::new(AgeMs(100), AgeMs(100)).is_err());
+ assert!(Hysteresis::new(AgeMs(100), AgeMs(200)).is_err());
+
+ let hysteresis = Hysteresis::new(AgeMs(100), AgeMs(50)).unwrap();
+ let cases = [
+ (false, 99, false, "below engage stays released"),
+ (false, 100, true, "engages at the threshold"),
+ (false, 101, true, "engages above the threshold"),
+ (
+ true,
+ 50,
+ true,
+ "at release stays engaged (releases strictly below)",
+ ),
+ (true, 75, true, "sticky between the thresholds"),
+ (true, 49, false, "releases below the release threshold"),
+ (
+ false,
+ 75,
+ false,
+ "between the thresholds stays released when not engaged",
+ ),
+ ];
+ for (engaged, value, expected, why) in cases {
+ assert_eq!(hysteresis.decide(engaged, AgeMs(value)), expected, "{why}");
+ }
+
+ let pct = Hysteresis::new(UsedPct(60.0), UsedPct(55.0)).unwrap();
+ assert!(pct.decide(false, UsedPct(60.0)));
+ assert!(pct.decide(true, UsedPct(55.0)));
+ assert!(!pct.decide(true, UsedPct(54.9)));
+ }
+
+ /// A cause change mid-episode must not reset the pause age; only a genuine resume (empty
+ /// causes) starts a fresh episode.
+ #[test]
+ fn episode_age_survives_cause_churn_and_resets_after_resume() {
+ let mut ledger = PauseLedger::default();
+ let start = Instant::now();
+ let later = start + Duration::from_secs(60);
+ let latest = start + Duration::from_secs(120);
+
+ ledger.reconcile(5, causes(&[PauseCause::Fence]), start);
+ assert_eq!(ledger.age(5, later), Some(Duration::from_secs(60)));
+
+ // The cause churns fence → live-lag; the episode keeps its original start.
+ ledger.reconcile(5, causes(&[PauseCause::LiveLag]), later);
+ assert_eq!(ledger.age(5, latest), Some(Duration::from_secs(120)));
+ assert!(ledger.has_cause(5, PauseCause::LiveLag));
+ assert!(!ledger.has_cause(5, PauseCause::Fence));
+
+ // Resume, then a new pause starts a fresh episode.
+ ledger.reconcile(5, CauseSet::default(), later);
+ assert_eq!(ledger.age(5, latest), None);
+ assert!(ledger.pause_target().is_empty());
+ ledger.reconcile(5, causes(&[PauseCause::DiskPressure]), later);
+ assert_eq!(ledger.age(5, latest), Some(Duration::from_secs(60)));
+ }
+
+ /// A revoked partition's episode must not keep aging its gauge or pause an unowned toppar.
+ #[test]
+ fn drop_unowned_prunes_episodes() {
+ let mut ledger = PauseLedger::default();
+ let now = Instant::now();
+ ledger.reconcile(1, causes(&[PauseCause::Fence]), now);
+ ledger.reconcile(2, causes(&[PauseCause::LiveLag, PauseCause::Fence]), now);
+
+ assert_eq!(ledger.pause_target(), HashSet::from([1, 2]));
+ assert_eq!(ledger.count_with(PauseCause::Fence), 2);
+ assert_eq!(ledger.count_with(PauseCause::LiveLag), 1);
+ assert_eq!(ledger.count_with(PauseCause::DiskPressure), 0);
+
+ ledger.drop_unowned(&HashSet::from([2]));
+
+ assert_eq!(ledger.pause_target(), HashSet::from([2]));
+ assert_eq!(ledger.age(1, now), None);
+ assert!(!ledger.has_cause(1, PauseCause::Fence));
+ assert_eq!(ledger.count_with(PauseCause::Fence), 1);
+ }
+}
diff --git a/rust/cohort-stream-processor/src/partitions/shuffle_message.rs b/rust/cohort-stream-processor/src/partitions/shuffle_message.rs
index 0dfd9a8d82ef..a3417e212f32 100644
--- a/rust/cohort-stream-processor/src/partitions/shuffle_message.rs
+++ b/rust/cohort-stream-processor/src/partitions/shuffle_message.rs
@@ -56,7 +56,13 @@ pub enum ShuffleMessage {
/// A backfill day-tile (or its consume-side skip), paired with its topic offset. Marked on
/// the seed tracker, never the events tracker. Boxed so the tile doesn't inflate every
/// `ShuffleMessage`.
- Seed { work: Box<SeedWork>, offset: i64 },
+ Seed {
+ work: Box<SeedWork>,
+ offset: i64,
+ /// Broker timestamp of the consumed seed message — the oldest-held age gauge's input.
+ /// Rides the round trip so a channel-full bounce keeps it; `None` reads as age 0.
+ broker_ts_ms: Option<i64>,
+ },
}
impl ShuffleMessage {
@@ -229,6 +235,7 @@ mod tests {
let message = ShuffleMessage::Seed {
work: Box::new(sample_seed_work()),
offset: 17,
+ broker_ts_ms: Some(1_700_000_000_000),
};
assert_eq!(
diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rs
index bc89214a710d..5fe32d31dd17 100644
--- a/rust/cohort-stream-processor/src/workers/worker.rs
+++ b/rust/cohort-stream-processor/src/workers/worker.rs
@@ -303,7 +303,11 @@ async fn run_worker(
)
.await;
}
- ShuffleMessage::Seed { work, offset } => {
+ ShuffleMessage::Seed {
+ work,
+ offset,
+ broker_ts_ms: _,
+ } => {
// Worker receipt is the first point that both proves this exact seed landed and
// orders its ceiling before even a zero-work handler can mark it processed.
// The dispatcher also records the delivered batch maximum, but that post-send
@@ -1322,6 +1326,7 @@ mod tombstone_redirect_tests {
vec![ShuffleMessage::Seed {
work: Box::new(SeedWork::Reconcile(tile)),
offset: 5,
+ broker_ts_ms: None,
}],
)
.await;
@@ -1358,6 +1363,7 @@ mod tombstone_redirect_tests {
ShuffleMessage::Seed {
work: Box::new(SeedWork::Reconcile(tile)),
offset: 5,
+ broker_ts_ms: None,
},
ShuffleMessage::ReconcileDrain,
],
diff --git a/rust/cohort-stream-processor/tests/merge_durability.rs b/rust/cohort-stream-processor/tests/merge_durability.rs
index 9f71841f5703..5bd7daa6024c 100644
--- a/rust/cohort-stream-processor/tests/merge_durability.rs
+++ b/rust/cohort-stream-processor/tests/merge_durability.rs
@@ -864,7 +864,7 @@ fn commit_follower_offsets_from_manifest(
}
/// `durable_restore_enabled && cohort_cascade_enabled` requires `durable_restore_single_pod &&
-/// pod_identity().is_some()` to pass `validate_durability_startup`, so those knobs are set too.
+/// pod_identity().is_some()` to pass `validate_startup`, so those knobs are set too.
#[allow(clippy::too_many_arguments)]
fn merge_durability_config(
store_path: &Path,
@@ -927,7 +927,7 @@ fn merge_durability_config(
}
let config = Config::init_from_hashmap(&env).expect("build merge-durability config");
config
- .validate_durability_startup()
+ .validate_startup()
.expect("merge-durability config must satisfy the durability startup guard");
config
}
diff --git a/rust/cohort-stream-processor/tests/seed_consumer.rs b/rust/cohort-stream-processor/tests/seed_consumer.rs
index 34da27059d78..8ba80d23cd64 100644
--- a/rust/cohort-stream-processor/tests/seed_consumer.rs
+++ b/rust/cohort-stream-processor/tests/seed_consumer.rs
@@ -30,10 +30,11 @@ use cohort_stream_processor::consumers::{
use cohort_stream_processor::filters::{
CatalogHandle, CohortId, FilterCatalog, TeamFiltersBuilder, TeamId,
};
+use cohort_stream_processor::observability::disk::SharedDiskUtilization;
use cohort_stream_processor::partitions::{
merge_partition_key, partition_for, partition_of, run_rebalance_worker, CohortConsumerContext,
ConsumerPauser, Follower, FollowerSet, LiveWatermarks, OffsetTracker, PartitionPauser,
- PartitionRouter, COHORT_PARTITION_COUNT,
+ PartitionRouter, SeedPacingConfig, COHORT_PARTITION_COUNT,
};
use cohort_stream_processor::producer::{
CascadeSink, ChangeOrigin, CohortMembershipChange, KafkaCascadeSink, KafkaMembershipSink,
@@ -724,6 +725,9 @@ async fn spawn_instance(
COMMIT_INTERVAL,
fence_margin_ms,
PROBE_NEVER,
+ // Both pacing triggers disabled: these tests pin fence and holdover behavior.
+ SeedPacingConfig::default(),
+ Arc::new(SharedDiskUtilization::new(Duration::MAX)),
);
tasks.push(tokio::spawn(seed_follower.process()));
diff --git a/rust/cohort-stream-processor/tests/stage1_worker.rs b/rust/cohort-stream-processor/tests/stage1_worker.rs
index 72aef2e34f75..f468f9662711 100644
--- a/rust/cohort-stream-processor/tests/stage1_worker.rs
+++ b/rust/cohort-stream-processor/tests/stage1_worker.rs
@@ -2422,6 +2422,7 @@ fn seed_message(person: Uuid, day: i32, count: u32, offset: i64) -> ShuffleMessa
ShuffleMessage::Seed {
work: Box::new(SeedWork::Tile(seed_tile(person, day, count))),
offset,
+ broker_ts_ms: None,
}
}