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.

chore(cohorts): rocksdb o11y improvement (#67477)

Matheus Batista561fc8a3b4e3
diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rs
index 099b8dc3211a..761f2b6356a3 100644
--- a/rust/cohort-stream-processor/src/config.rs
+++ b/rust/cohort-stream-processor/src/config.rs
@@ -259,6 +259,11 @@ pub struct Config {
#[envconfig(default = "300000")]
pub sweep_safety_margin_ms: u64,
+ /// How often the store-stats publisher and Tokio runtime monitor sample and emit their gauges
+ /// (seconds).
+ #[envconfig(from = "COHORT_STATS_PUBLISH_INTERVAL_SECS", default = "15")]
+ pub stats_publish_interval_secs: u64,
+
/// On-disk path for the per-process RocksDB state store.
#[envconfig(default = "cohort-store")]
pub store_path: String,
@@ -268,6 +273,16 @@ pub struct Config {
#[envconfig(default = "true")]
pub wipe_store_on_start: bool,
+ /// Enable RocksDB statistics so the store-stats publisher can report cache tickers and per-CF
+ /// sizes. See [`StoreConfig::statistics_enabled`].
+ #[envconfig(from = "COHORT_STORE_STATISTICS_ENABLED", default = "true")]
+ pub store_statistics_enabled: bool,
+
+ /// Sample 1-in-N reads into the read-latency histogram; the read counter stays exact. See
+ /// [`StoreConfig::read_sample_ratio`]. `1` records every read; `0` floors to `1`.
+ #[envconfig(from = "COHORT_STORE_READ_SAMPLE_RATIO", default = "64")]
+ pub store_read_sample_ratio: u32,
+
/// RocksDB block-cache size in bytes, shared across all column families.
#[envconfig(from = "COHORT_BLOCK_CACHE_BYTES", default = "134217728")]
pub cohort_block_cache_bytes: usize,
@@ -443,6 +458,11 @@ impl Config {
Duration::from_millis(self.sweep_safety_margin_ms)
}
+ pub fn stats_publish_interval(&self) -> Duration {
+ // Floor at 1s: `tokio::time::interval` panics on a zero period.
+ Duration::from_secs(self.stats_publish_interval_secs).max(Duration::from_secs(1))
+ }
+
pub fn transfer_retry_policy(&self) -> TransferRetryPolicy {
TransferRetryPolicy {
max_retries: self.merge_transfer_max_retries,
@@ -563,6 +583,8 @@ impl Config {
StoreConfig {
path: PathBuf::from(&self.store_path),
wipe_on_start: self.effective_wipe_on_start(),
+ statistics_enabled: self.store_statistics_enabled,
+ read_sample_ratio: self.store_read_sample_ratio,
block_cache_bytes: self.cohort_block_cache_bytes,
tuned_block_options: self.cohort_tuned_block_options_enabled,
compact_on_deletion: self.cohort_compact_on_deletion_enabled,
@@ -751,8 +773,11 @@ mod tests {
tokio_worker_threads: 0,
sweep_interval_ms: 30000,
sweep_safety_margin_ms: 300000,
+ stats_publish_interval_secs: 15,
store_path: "cohort-store".to_string(),
wipe_store_on_start: true,
+ store_statistics_enabled: true,
+ store_read_sample_ratio: 64,
cohort_block_cache_bytes: 134_217_728,
cohort_tuned_block_options_enabled: true,
cohort_compact_on_deletion_enabled: true,
@@ -891,6 +916,50 @@ mod tests {
assert!(!config.store_config().wipe_on_start);
}
+ #[test]
+ fn stats_knobs_default_on_and_thread_into_store_config() {
+ let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();
+ assert!(defaults.store_statistics_enabled);
+ assert!(defaults.store_config().statistics_enabled);
+ assert_eq!(defaults.stats_publish_interval(), Duration::from_secs(15));
+ assert_eq!(defaults.store_read_sample_ratio, 64);
+ assert_eq!(defaults.store_config().read_sample_ratio, 64);
+
+ let env: std::collections::HashMap<String, String> = [
+ ("COHORT_STORE_STATISTICS_ENABLED", "false"),
+ ("COHORT_STATS_PUBLISH_INTERVAL_SECS", "30"),
+ ("COHORT_STORE_READ_SAMPLE_RATIO", "8"),
+ ]
+ .into_iter()
+ .map(|(key, value)| (key.to_string(), value.to_string()))
+ .collect();
+ let config = Config::init_from_hashmap(&env).unwrap();
+ assert!(!config.store_statistics_enabled);
+ assert!(
+ !config.store_config().statistics_enabled,
+ "the flag reaches StoreConfig",
+ );
+ assert_eq!(config.stats_publish_interval(), Duration::from_secs(30));
+ assert_eq!(config.store_read_sample_ratio, 8);
+ assert_eq!(
+ config.store_config().read_sample_ratio,
+ 8,
+ "the sample ratio reaches StoreConfig",
+ );
+ }
+
+ #[test]
+ fn stats_publish_interval_floors_zero_at_one_second() {
+ // Zero would panic `tokio::time::interval`; the accessor clamps to 1s.
+ let env: std::collections::HashMap<String, String> =
+ [("COHORT_STATS_PUBLISH_INTERVAL_SECS", "0")]
+ .into_iter()
+ .map(|(key, value)| (key.to_string(), value.to_string()))
+ .collect();
+ let config = Config::init_from_hashmap(&env).unwrap();
+ assert_eq!(config.stats_publish_interval(), Duration::from_secs(1));
+ }
+
#[test]
fn consumer_config_sets_tls_keys_only_when_enabled() {
let mut config = test_config();
diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rs
index 07fc6c053d8d..74e38f59686f 100644
--- a/rust/cohort-stream-processor/src/main.rs
+++ b/rust/cohort-stream-processor/src/main.rs
@@ -24,6 +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::tokio_monitor::TokioRuntimeMonitor;
use cohort_stream_processor::partitions::{
run_rebalance_worker, CohortConsumerContext, Follower, FollowerSet, OffsetTracker,
PartitionRouter,
@@ -99,6 +101,11 @@ async fn async_main(config: Config) -> Result<()> {
ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(30)),
)
});
+ // Short graceful window: it holds no state and its next tick is disposable.
+ let tokio_monitor_handle = manager.register(
+ "tokio-runtime-monitor",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(2)),
+ );
let readiness = manager.readiness_handler();
let liveness = manager.liveness_handler();
@@ -205,6 +212,7 @@ async fn async_main(config: Config) -> Result<()> {
// needs its own handle on the store and each per-topic tracker to capture the offset manifest.
// Captured unconditionally to satisfy the borrow checker; consumed only when `checkpoint_enabled`.
let store_for_checkpoint = store.clone();
+ let store_for_stats = store.clone();
let events_tracker_for_checkpoint = offset_tracker.clone();
let merge_tracker_for_checkpoint = merge_deps.merge_tracker.clone();
let transfer_tracker_for_checkpoint = merge_deps.transfer_tracker.clone();
@@ -398,6 +406,22 @@ async fn async_main(config: Config) -> Result<()> {
consumer_handle.shutdown_token(),
));
+ // Publish store cache/size metrics via the sweep machinery, and Tokio runtime metrics via a
+ // separate monitor.
+ tokio::spawn(run_sweep_loop(
+ StoreStatsSweeper::new(store_for_stats),
+ config.stats_publish_interval(),
+ "store_stats",
+ consumer_handle.shutdown_token(),
+ ));
+ tokio::spawn(
+ TokioRuntimeMonitor::new(
+ &tokio::runtime::Handle::current(),
+ config.stats_publish_interval(),
+ )
+ .start_monitoring(tokio_monitor_handle),
+ );
+
// Whole-DB checkpoint → PVC + incremental S3 sweep loop. Spawned only when the master gate is on,
// so a default deploy starts no checkpoint task. The cascade tracker is included only when cascade
// is on; otherwise it is idle and would contribute an empty manifest entry.
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
index b6f2c3161a64..6a648bf21c03 100644
--- a/rust/cohort-stream-processor/src/observability/metrics.rs
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -121,6 +121,71 @@ pub const STORE_ERRORS_TOTAL: &str = "store_errors_total";
/// Malformed inputs the `cf_person_index` merge operator skipped, labelled by `kind` (counter).
pub const STORE_MERGE_MALFORMED_TOTAL: &str = "store_merge_malformed_total";
+/// Latency of a RocksDB read, labelled by `op` (histogram, seconds). `op=get` is sampled 1-in-N
+/// (`StoreConfig::read_sample_ratio`) — use [`STORE_READS_TOTAL`] for exact volume. `op=multi_get`
+/// records once per batch.
+pub const STORE_READ_DURATION_SECONDS: &str = "store_read_duration_seconds";
+/// Logical RocksDB reads issued, labelled by `op` (counter). A `multi_get` counts once per key.
+pub const STORE_READS_TOTAL: &str = "store_reads_total";
+
+/// Block-cache hits across all block types (counter, cumulative since store open).
+pub const STORE_BLOCK_CACHE_HITS_TOTAL: &str = "store_block_cache_hits_total";
+/// Block-cache misses across all block types (counter, cumulative since store open).
+pub const STORE_BLOCK_CACHE_MISSES_TOTAL: &str = "store_block_cache_misses_total";
+/// Data-block cache hits (counter, cumulative since store open).
+pub const STORE_BLOCK_CACHE_DATA_HITS_TOTAL: &str = "store_block_cache_data_hits_total";
+/// Data-block cache misses (counter, cumulative since store open).
+pub const STORE_BLOCK_CACHE_DATA_MISSES_TOTAL: &str = "store_block_cache_data_misses_total";
+/// Index-block cache hits (counter, cumulative since store open).
+pub const STORE_BLOCK_CACHE_INDEX_HITS_TOTAL: &str = "store_block_cache_index_hits_total";
+/// Index-block cache misses (counter, cumulative since store open).
+pub const STORE_BLOCK_CACHE_INDEX_MISSES_TOTAL: &str = "store_block_cache_index_misses_total";
+/// Filter-block (bloom) cache hits (counter, cumulative since store open).
+pub const STORE_BLOCK_CACHE_FILTER_HITS_TOTAL: &str = "store_block_cache_filter_hits_total";
+/// Filter-block (bloom) cache misses (counter, cumulative since store open).
+pub const STORE_BLOCK_CACHE_FILTER_MISSES_TOTAL: &str = "store_block_cache_filter_misses_total";
+/// Point lookups the bloom filter let skip a data-block read (counter, cumulative since store open).
+pub const STORE_BLOOM_FILTER_USEFUL_TOTAL: &str = "store_bloom_filter_useful_total";
+
+/// Bytes the shared block cache currently holds (gauge).
+pub const STORE_BLOCK_CACHE_USAGE_BYTES: &str = "store_block_cache_usage_bytes";
+/// On-disk SST bytes, labelled by `cf` (gauge).
+pub const STORE_SST_BYTES: &str = "store_sst_bytes";
+/// Estimated live (non-tombstone) data bytes, labelled by `cf` (gauge).
+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";
+
+/// 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).
+pub const TOKIO_RUNTIME_ALIVE_TASKS: &str = "tokio_runtime_alive_tasks";
+/// Tasks pending in the runtime's global injection queue (gauge).
+pub const TOKIO_RUNTIME_GLOBAL_QUEUE_DEPTH: &str = "tokio_runtime_global_queue_depth";
+/// Configured Tokio worker threads (gauge).
+pub const TOKIO_RUNTIME_NUM_WORKERS: &str = "tokio_runtime_num_workers";
+/// Per-worker busy time over the sample interval, labelled by `worker` (gauge, seconds).
+pub const TOKIO_WORKER_BUSY_DURATION_DELTA: &str = "tokio_worker_busy_duration_delta_secs";
+/// Per-worker park-count delta over the sample interval, labelled by `worker` (gauge).
+pub const TOKIO_WORKER_PARK_DELTA: &str = "tokio_worker_park_delta";
+/// Per-worker poll-count delta over the sample interval, labelled by `worker` (gauge).
+pub const TOKIO_WORKER_POLL_DELTA: &str = "tokio_worker_poll_delta";
+/// Per-worker steal-count delta over the sample interval, labelled by `worker` (gauge).
+pub const TOKIO_WORKER_STEAL_DELTA: &str = "tokio_worker_steal_delta";
+/// Per-worker local-queue overflow-to-global delta over the sample interval, labelled by `worker`
+/// (gauge).
+pub const TOKIO_WORKER_OVERFLOW_DELTA: &str = "tokio_worker_overflow_delta";
+/// Per-worker local run-queue depth, labelled by `worker` (gauge).
+pub const TOKIO_WORKER_LOCAL_QUEUE_DEPTH: &str = "tokio_worker_local_queue_depth";
+/// Per-worker mean poll duration, labelled by `worker` (gauge, microseconds).
+pub const TOKIO_WORKER_MEAN_POLL_TIME_US: &str = "tokio_worker_mean_poll_time_us";
+/// Threads in the blocking pool (gauge).
+pub const TOKIO_BLOCKING_THREADS: &str = "tokio_blocking_threads";
+/// Idle threads in the blocking pool (gauge).
+pub const TOKIO_IDLE_BLOCKING_THREADS: &str = "tokio_idle_blocking_threads";
+/// Tasks waiting for a blocking thread (gauge).
+pub const TOKIO_BLOCKING_QUEUE_DEPTH: &str = "tokio_blocking_queue_depth";
+
/// Cohort bytecode invoked a symbol with no registered native (counter). The function name is
/// logged, not labelled, to keep cardinality bounded.
pub const STAGE1_HOGVM_UNKNOWN_FUNCTION: &str = "stage1_hogvm_unknown_function_total";
@@ -255,8 +320,8 @@ pub const OUTPUT_TRANSITIONS_UNMAPPED: &str = "output_transitions_unmapped_total
/// Produce failures to `cohort_membership_changed_shadow` (counter).
pub const OUTPUT_PRODUCE_ERRORS: &str = "output_produce_errors_total";
-/// Sweep cycles that fired, labelled by `loop` (`eviction`|`redrive`|`merge_gc`|`checkpoint`)
-/// (counter).
+/// Sweep cycles that fired, labelled by `loop`
+/// (`eviction`|`redrive`|`merge_gc`|`checkpoint`|`store_stats`) (counter).
pub const SWEEP_CYCLES_TOTAL: &str = "sweep_cycles_total";
/// Wall-clock duration of one sweep cycle, labelled by `loop` (histogram, seconds).
pub const SWEEP_CYCLE_DURATION_SECONDS: &str = "sweep_cycle_duration_seconds";
@@ -416,6 +481,80 @@ mod tests {
);
}
+ #[test]
+ fn store_and_tokio_observability_metric_names_are_stable() {
+ // These names are a dashboard contract; a rename must be deliberate, not accidental. Every
+ // new store/tokio constant is pinned so a rename cannot silently break a panel.
+ assert_eq!(STORE_READ_DURATION_SECONDS, "store_read_duration_seconds");
+ assert_eq!(STORE_READS_TOTAL, "store_reads_total");
+ assert_eq!(STORE_BLOCK_CACHE_HITS_TOTAL, "store_block_cache_hits_total");
+ assert_eq!(
+ STORE_BLOCK_CACHE_MISSES_TOTAL,
+ "store_block_cache_misses_total"
+ );
+ assert_eq!(
+ STORE_BLOCK_CACHE_DATA_HITS_TOTAL,
+ "store_block_cache_data_hits_total",
+ );
+ assert_eq!(
+ STORE_BLOCK_CACHE_DATA_MISSES_TOTAL,
+ "store_block_cache_data_misses_total",
+ );
+ assert_eq!(
+ STORE_BLOCK_CACHE_INDEX_HITS_TOTAL,
+ "store_block_cache_index_hits_total",
+ );
+ assert_eq!(
+ STORE_BLOCK_CACHE_INDEX_MISSES_TOTAL,
+ "store_block_cache_index_misses_total",
+ );
+ assert_eq!(
+ STORE_BLOCK_CACHE_FILTER_HITS_TOTAL,
+ "store_block_cache_filter_hits_total",
+ );
+ assert_eq!(
+ STORE_BLOCK_CACHE_FILTER_MISSES_TOTAL,
+ "store_block_cache_filter_misses_total",
+ );
+ assert_eq!(
+ STORE_BLOOM_FILTER_USEFUL_TOTAL,
+ "store_bloom_filter_useful_total",
+ );
+ assert_eq!(
+ STORE_BLOCK_CACHE_USAGE_BYTES,
+ "store_block_cache_usage_bytes"
+ );
+ 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!(TOKIO_RUNTIME_BUSY_RATIO, "tokio_runtime_busy_ratio");
+ assert_eq!(TOKIO_RUNTIME_ALIVE_TASKS, "tokio_runtime_alive_tasks");
+ assert_eq!(
+ TOKIO_RUNTIME_GLOBAL_QUEUE_DEPTH,
+ "tokio_runtime_global_queue_depth",
+ );
+ assert_eq!(TOKIO_RUNTIME_NUM_WORKERS, "tokio_runtime_num_workers");
+ assert_eq!(
+ TOKIO_WORKER_BUSY_DURATION_DELTA,
+ "tokio_worker_busy_duration_delta_secs",
+ );
+ assert_eq!(TOKIO_WORKER_PARK_DELTA, "tokio_worker_park_delta");
+ assert_eq!(TOKIO_WORKER_POLL_DELTA, "tokio_worker_poll_delta");
+ assert_eq!(TOKIO_WORKER_STEAL_DELTA, "tokio_worker_steal_delta");
+ assert_eq!(TOKIO_WORKER_OVERFLOW_DELTA, "tokio_worker_overflow_delta");
+ assert_eq!(
+ TOKIO_WORKER_LOCAL_QUEUE_DEPTH,
+ "tokio_worker_local_queue_depth",
+ );
+ assert_eq!(
+ TOKIO_WORKER_MEAN_POLL_TIME_US,
+ "tokio_worker_mean_poll_time_us",
+ );
+ assert_eq!(TOKIO_BLOCKING_THREADS, "tokio_blocking_threads");
+ assert_eq!(TOKIO_IDLE_BLOCKING_THREADS, "tokio_idle_blocking_threads");
+ assert_eq!(TOKIO_BLOCKING_QUEUE_DEPTH, "tokio_blocking_queue_depth");
+ }
+
#[test]
fn stage2_orphan_gc_metric_names_are_stable() {
assert_eq!(
diff --git a/rust/cohort-stream-processor/src/observability/mod.rs b/rust/cohort-stream-processor/src/observability/mod.rs
index 0f1adf1ed73b..c6b55f334e9b 100644
--- a/rust/cohort-stream-processor/src/observability/mod.rs
+++ b/rust/cohort-stream-processor/src/observability/mod.rs
@@ -3,3 +3,5 @@
pub mod canonical_log;
pub mod health;
pub mod metrics;
+pub mod store_stats;
+pub mod tokio_monitor;
diff --git a/rust/cohort-stream-processor/src/observability/store_stats.rs b/rust/cohort-stream-processor/src/observability/store_stats.rs
new file mode 100644
index 000000000000..97cbf2b8a925
--- /dev/null
+++ b/rust/cohort-stream-processor/src/observability/store_stats.rs
@@ -0,0 +1,78 @@
+//! 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`].
+
+use async_trait::async_trait;
+use metrics::{counter, gauge};
+
+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,
+};
+use crate::store::CohortStore;
+use crate::sweep::Sweeper;
+
+/// Publishes [`CohortStore::stats_snapshot`] onto metrics once per sweep tick, driven by
+/// [`run_sweep_loop`](crate::sweep::run_sweep_loop).
+pub struct StoreStatsSweeper {
+ store: CohortStore,
+}
+
+impl StoreStatsSweeper {
+ pub fn new(store: CohortStore) -> Self {
+ Self { store }
+ }
+}
+
+#[async_trait]
+impl Sweeper for StoreStatsSweeper {
+ async fn run_once(&self) {
+ let stats = self.store.stats_snapshot();
+
+ // Tickers are cumulative, so publish them verbatim with `absolute`.
+ for (name, value) in [
+ (STORE_BLOCK_CACHE_HITS_TOTAL, stats.block_cache_hits),
+ (STORE_BLOCK_CACHE_MISSES_TOTAL, stats.block_cache_misses),
+ (
+ STORE_BLOCK_CACHE_DATA_HITS_TOTAL,
+ stats.block_cache_data_hits,
+ ),
+ (
+ STORE_BLOCK_CACHE_DATA_MISSES_TOTAL,
+ stats.block_cache_data_misses,
+ ),
+ (
+ STORE_BLOCK_CACHE_INDEX_HITS_TOTAL,
+ stats.block_cache_index_hits,
+ ),
+ (
+ STORE_BLOCK_CACHE_INDEX_MISSES_TOTAL,
+ stats.block_cache_index_misses,
+ ),
+ (
+ STORE_BLOCK_CACHE_FILTER_HITS_TOTAL,
+ stats.block_cache_filter_hits,
+ ),
+ (
+ STORE_BLOCK_CACHE_FILTER_MISSES_TOTAL,
+ stats.block_cache_filter_misses,
+ ),
+ (STORE_BLOOM_FILTER_USEFUL_TOTAL, stats.bloom_filter_useful),
+ ] {
+ counter!(name).absolute(value);
+ }
+
+ gauge!(STORE_BLOCK_CACHE_USAGE_BYTES).set(stats.block_cache_usage_bytes as f64);
+
+ for cf in &stats.per_cf {
+ // `cf.as_str()` is `&'static str`, so the label is static — no `Arc<str>` needed.
+ let label = cf.cf.as_str();
+ gauge!(STORE_SST_BYTES, "cf" => label).set(cf.sst_bytes as f64);
+ gauge!(STORE_LIVE_DATA_BYTES, "cf" => label).set(cf.live_data_bytes as f64);
+ gauge!(STORE_ESTIMATE_NUM_KEYS, "cf" => label).set(cf.num_keys as f64);
+ }
+ }
+}
diff --git a/rust/cohort-stream-processor/src/observability/tokio_monitor.rs b/rust/cohort-stream-processor/src/observability/tokio_monitor.rs
new file mode 100644
index 000000000000..0630570158fd
--- /dev/null
+++ b/rust/cohort-stream-processor/src/observability/tokio_monitor.rs
@@ -0,0 +1,312 @@
+//! Periodic Tokio runtime monitor: per-worker busy-ratio, queue depths, and blocking-pool depth.
+//! Full per-worker and blocking-pool metrics require `tokio_unstable` (enabled workspace-wide).
+
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use lifecycle::Handle;
+use metrics::gauge;
+use tokio::runtime::RuntimeMetrics;
+use tokio::time::interval;
+
+use crate::observability::metrics::{
+ TOKIO_RUNTIME_ALIVE_TASKS, TOKIO_RUNTIME_BUSY_RATIO, TOKIO_RUNTIME_GLOBAL_QUEUE_DEPTH,
+ TOKIO_RUNTIME_NUM_WORKERS, TOKIO_WORKER_BUSY_DURATION_DELTA, TOKIO_WORKER_PARK_DELTA,
+};
+
+#[cfg(tokio_unstable)]
+use crate::observability::metrics::{
+ TOKIO_BLOCKING_QUEUE_DEPTH, TOKIO_BLOCKING_THREADS, TOKIO_IDLE_BLOCKING_THREADS,
+ TOKIO_WORKER_LOCAL_QUEUE_DEPTH, TOKIO_WORKER_MEAN_POLL_TIME_US, TOKIO_WORKER_OVERFLOW_DELTA,
+ TOKIO_WORKER_POLL_DELTA, TOKIO_WORKER_STEAL_DELTA,
+};
+
+/// Samples [`RuntimeMetrics`] on a fixed cadence and publishes worker-utilization gauges. Per-worker
+/// counters are published as deltas over the interval.
+pub struct TokioRuntimeMonitor {
+ metrics: RuntimeMetrics,
+ interval: Duration,
+}
+
+impl TokioRuntimeMonitor {
+ pub fn new(handle: &tokio::runtime::Handle, interval: Duration) -> Self {
+ Self {
+ metrics: handle.metrics(),
+ interval,
+ }
+ }
+
+ pub async fn start_monitoring(self, shutdown: Handle) {
+ let _scope = shutdown.process_scope();
+ let num_workers = self.metrics.num_workers();
+
+ tracing::info!(
+ workers = num_workers,
+ interval_secs = self.interval.as_secs(),
+ "starting Tokio runtime monitor",
+ );
+
+ gauge!(TOKIO_RUNTIME_NUM_WORKERS).set(num_workers as f64);
+
+ let mut stable_state = WorkerState::new(num_workers, &self.metrics);
+
+ #[cfg(tokio_unstable)]
+ let mut unstable_state = UnstableWorkerState::new(num_workers, &self.metrics);
+
+ self.run_loop(
+ &shutdown,
+ &mut stable_state,
+ #[cfg(tokio_unstable)]
+ &mut unstable_state,
+ )
+ .await;
+ }
+
+ async fn run_loop(
+ &self,
+ shutdown: &Handle,
+ stable_state: &mut WorkerState,
+ #[cfg(tokio_unstable)] unstable_state: &mut UnstableWorkerState,
+ ) {
+ #[cfg(not(tokio_unstable))]
+ tracing::warn!(
+ "tokio_unstable not enabled — blocking pool and some per-worker metrics \
+ (poll count, steal count, overflow count, local queue depth, mean poll time) \
+ are unavailable. Enable with rustflags = [\"--cfg\", \"tokio_unstable\"] for full metrics."
+ );
+
+ let mut ticker = interval(self.interval);
+ // Skip the immediate first tick so the first report reflects a full interval of deltas.
+ ticker.tick().await;
+
+ loop {
+ tokio::select! {
+ _ = shutdown.shutdown_recv() => {
+ tracing::info!("Tokio runtime monitor shutting down");
+ break;
+ }
+ _ = ticker.tick() => {
+ let now = Instant::now();
+ let elapsed = now.duration_since(stable_state.last_sample);
+ stable_state.last_sample = now;
+
+ self.report_stable_metrics(stable_state, elapsed);
+
+ #[cfg(tokio_unstable)]
+ self.report_unstable_metrics(unstable_state, &stable_state.worker_labels);
+ }
+ }
+ }
+ }
+
+ fn report_stable_metrics(&self, state: &mut WorkerState, elapsed: Duration) {
+ gauge!(TOKIO_RUNTIME_ALIVE_TASKS).set(self.metrics.num_alive_tasks() as f64);
+ gauge!(TOKIO_RUNTIME_GLOBAL_QUEUE_DEPTH).set(self.metrics.global_queue_depth() as f64);
+
+ let num_workers = self.metrics.num_workers();
+ let elapsed_secs = elapsed.as_secs_f64();
+ let mut total_busy_delta = Duration::ZERO;
+
+ // busy-duration and park-count are tokio's only stable per-worker metrics; the rest are
+ // gathered under `tokio_unstable` in `report_unstable_metrics`.
+ for i in 0..num_workers {
+ let label = state.worker_labels[i].clone();
+
+ let busy = self.metrics.worker_total_busy_duration(i);
+ let busy_delta = busy.saturating_sub(state.prev_busy[i]);
+ state.prev_busy[i] = busy;
+ total_busy_delta += busy_delta;
+ gauge!(TOKIO_WORKER_BUSY_DURATION_DELTA, "worker" => label.clone())
+ .set(busy_delta.as_secs_f64());
+
+ let parks = self.metrics.worker_park_count(i);
+ let park_delta = parks.saturating_sub(state.prev_parks[i]);
+ state.prev_parks[i] = parks;
+ gauge!(TOKIO_WORKER_PARK_DELTA, "worker" => label).set(park_delta as f64);
+ }
+
+ let busy_ratio = if elapsed_secs > 0.0 && num_workers > 0 {
+ total_busy_delta.as_secs_f64() / (elapsed_secs * num_workers as f64)
+ } else {
+ 0.0
+ };
+ gauge!(TOKIO_RUNTIME_BUSY_RATIO).set(busy_ratio);
+ }
+
+ #[cfg(tokio_unstable)]
+ fn report_unstable_metrics(&self, state: &mut UnstableWorkerState, worker_labels: &[Arc<str>]) {
+ let num_workers = self.metrics.num_workers();
+
+ gauge!(TOKIO_BLOCKING_THREADS).set(self.metrics.num_blocking_threads() as f64);
+ gauge!(TOKIO_IDLE_BLOCKING_THREADS).set(self.metrics.num_idle_blocking_threads() as f64);
+ gauge!(TOKIO_BLOCKING_QUEUE_DEPTH).set(self.metrics.blocking_queue_depth() as f64);
+
+ for (i, label) in worker_labels.iter().enumerate().take(num_workers) {
+ let polls = self.metrics.worker_poll_count(i);
+ let poll_delta = polls.saturating_sub(state.prev_polls[i]);
+ state.prev_polls[i] = polls;
+ gauge!(TOKIO_WORKER_POLL_DELTA, "worker" => label.clone()).set(poll_delta as f64);
+
+ let steals = self.metrics.worker_steal_count(i);
+ let steal_delta = steals.saturating_sub(state.prev_steals[i]);
+ state.prev_steals[i] = steals;
+ gauge!(TOKIO_WORKER_STEAL_DELTA, "worker" => label.clone()).set(steal_delta as f64);
+
+ let overflows = self.metrics.worker_overflow_count(i);
+ let overflow_delta = overflows.saturating_sub(state.prev_overflows[i]);
+ state.prev_overflows[i] = overflows;
+ gauge!(TOKIO_WORKER_OVERFLOW_DELTA, "worker" => label.clone())
+ .set(overflow_delta as f64);
+
+ // Instantaneous gauges, not deltas.
+ gauge!(TOKIO_WORKER_LOCAL_QUEUE_DEPTH, "worker" => label.clone())
+ .set(self.metrics.worker_local_queue_depth(i) as f64);
+ gauge!(TOKIO_WORKER_MEAN_POLL_TIME_US, "worker" => label.clone())
+ .set(self.metrics.worker_mean_poll_time(i).as_micros() as f64);
+ }
+ }
+}
+
+struct WorkerState {
+ last_sample: Instant,
+ /// Per-worker `worker` label, built once and cloned into each macro call.
+ worker_labels: Vec<Arc<str>>,
+ prev_busy: Vec<Duration>,
+ prev_parks: Vec<u64>,
+}
+
+impl WorkerState {
+ fn new(num_workers: usize, metrics: &RuntimeMetrics) -> Self {
+ let worker_labels: Vec<Arc<str>> =
+ (0..num_workers).map(|i| Arc::from(i.to_string())).collect();
+
+ let mut prev_busy = vec![Duration::ZERO; num_workers];
+ let mut prev_parks = vec![0u64; num_workers];
+
+ // Snapshot current values so the first delta is accurate.
+ for i in 0..num_workers {
+ prev_busy[i] = metrics.worker_total_busy_duration(i);
+ prev_parks[i] = metrics.worker_park_count(i);
+ }
+
+ Self {
+ last_sample: Instant::now(),
+ worker_labels,
+ prev_busy,
+ prev_parks,
+ }
+ }
+}
+
+#[cfg(tokio_unstable)]
+struct UnstableWorkerState {
+ prev_polls: Vec<u64>,
+ prev_steals: Vec<u64>,
+ prev_overflows: Vec<u64>,
+}
+
+#[cfg(tokio_unstable)]
+impl UnstableWorkerState {
+ fn new(num_workers: usize, metrics: &RuntimeMetrics) -> Self {
+ let mut prev_polls = vec![0u64; num_workers];
+ let mut prev_steals = vec![0u64; num_workers];
+ let mut prev_overflows = vec![0u64; num_workers];
+
+ // Snapshot current values so the first delta is accurate.
+ for i in 0..num_workers {
+ prev_polls[i] = metrics.worker_poll_count(i);
+ prev_steals[i] = metrics.worker_steal_count(i);
+ prev_overflows[i] = metrics.worker_overflow_count(i);
+ }
+
+ Self {
+ prev_polls,
+ prev_steals,
+ prev_overflows,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // Runs the emission path and checks the busy-ratio stays in [0, 1] over a real elapsed window.
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn busy_ratio_bounded_with_real_elapsed() {
+ let handle = tokio::runtime::Handle::current();
+ let metrics = handle.metrics();
+ let num_workers = metrics.num_workers();
+ let monitor = TokioRuntimeMonitor::new(&handle, Duration::from_secs(15));
+ let mut state = WorkerState::new(num_workers, &metrics);
+
+ let busy_before: Vec<Duration> = (0..num_workers)
+ .map(|i| metrics.worker_total_busy_duration(i))
+ .collect();
+
+ let start = Instant::now();
+ for _ in 0..1000 {
+ tokio::task::yield_now().await;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ let elapsed = start.elapsed();
+
+ monitor.report_stable_metrics(&mut state, elapsed);
+
+ let mut total_busy_delta = Duration::ZERO;
+ for (i, &before) in busy_before.iter().enumerate().take(num_workers) {
+ let busy_now = metrics.worker_total_busy_duration(i);
+ total_busy_delta += busy_now.saturating_sub(before);
+ }
+
+ let ratio = total_busy_delta.as_secs_f64() / (elapsed.as_secs_f64() * num_workers as f64);
+ assert!(
+ (0.0..=1.0).contains(&ratio),
+ "busy ratio should be in [0, 1], got {ratio}"
+ );
+ }
+
+ // Covers the unstable delta path (poll/steal/overflow), which runs in production because
+ // `tokio_unstable` is enabled workspace-wide: a wrong `saturating_sub` order or a missed
+ // `prev_*` update would emit silently wrong deltas that the stable-path test cannot catch.
+ #[cfg(tokio_unstable)]
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn poll_and_busy_deltas_advance_after_work() {
+ let handle = tokio::runtime::Handle::current();
+ let metrics = handle.metrics();
+ let num_workers = metrics.num_workers();
+ let monitor = TokioRuntimeMonitor::new(&handle, Duration::from_secs(15));
+
+ let mut stable_state = WorkerState::new(num_workers, &metrics);
+ let mut unstable_state = UnstableWorkerState::new(num_workers, &metrics);
+ let polls_before: Vec<u64> = unstable_state.prev_polls.clone();
+ let busy_before: Vec<Duration> = stable_state.prev_busy.clone();
+
+ let mut handles = Vec::new();
+ for _ in 0..50 {
+ handles.push(tokio::spawn(async {
+ tokio::task::yield_now().await;
+ }));
+ }
+ for h in handles {
+ h.await.ok();
+ }
+
+ monitor.report_stable_metrics(&mut stable_state, Duration::from_secs(15));
+ monitor.report_unstable_metrics(&mut unstable_state, &stable_state.worker_labels);
+
+ let polls_advanced = unstable_state
+ .prev_polls
+ .iter()
+ .zip(polls_before.iter())
+ .any(|(after, before)| after > before);
+ assert!(polls_advanced, "poll counts should advance after work");
+
+ let busy_advanced = stable_state
+ .prev_busy
+ .iter()
+ .zip(busy_before.iter())
+ .any(|(after, before)| after > before);
+ assert!(busy_advanced, "busy durations should advance after work");
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/mod.rs b/rust/cohort-stream-processor/src/store/mod.rs
index 1025734b44b2..f0709270a5a0 100644
--- a/rust/cohort-stream-processor/src/store/mod.rs
+++ b/rust/cohort-stream-processor/src/store/mod.rs
@@ -13,7 +13,7 @@ pub use column_families::{
pub use keys::{
MergeAppliedKey, MergeDrainKey, PendingTransferKey, PersonIndexKey, Stage2Key, TombstoneKey,
};
-pub use rocks::{BatchBuilder, CohortStore, StoreConfig, StoreError};
+pub use rocks::{BatchBuilder, CfStats, CohortStore, StoreConfig, StoreError, StoreStats};
pub use secondary_index::{decode_person_index, IndexOp, PERSON_INDEX_MERGE_OPERATOR_NAME};
pub use crate::stage1::key::{LeafStateKey, Stage1Key};
diff --git a/rust/cohort-stream-processor/src/store/rocks.rs b/rust/cohort-stream-processor/src/store/rocks.rs
index d59c34d5336c..bb47dbef3eac 100644
--- a/rust/cohort-stream-processor/src/store/rocks.rs
+++ b/rust/cohort-stream-processor/src/store/rocks.rs
@@ -1,10 +1,13 @@
//! RocksDB wrapper: multi-CF atomic `WriteBatch`, async WAL.
+use std::cell::Cell;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;
use metrics::{counter, histogram};
+use rocksdb::properties::{self, PropName};
+use rocksdb::statistics::{StatsLevel, Ticker};
use rocksdb::{
Cache, ColumnFamily, DBWithThreadMode, Direction, FlushOptions, IteratorMode, Options,
ReadOptions, SingleThreaded, WriteBatch, WriteOptions,
@@ -18,8 +21,9 @@ use super::keys::{
};
use super::secondary_index::{decode_person_index, IndexOp};
use crate::observability::metrics::{
- CHECKPOINT_DURATION_SECONDS, STORE_ERRORS_TOTAL, STORE_WRITE_BATCH_TOTAL,
- STORE_WRITE_DURATION_SECONDS, WAL_FSYNC_DURATION_SECONDS, WAL_FSYNC_ERRORS_TOTAL,
+ CHECKPOINT_DURATION_SECONDS, STORE_ERRORS_TOTAL, STORE_READS_TOTAL,
+ STORE_READ_DURATION_SECONDS, STORE_WRITE_BATCH_TOTAL, STORE_WRITE_DURATION_SECONDS,
+ WAL_FSYNC_DURATION_SECONDS, WAL_FSYNC_ERRORS_TOTAL,
};
use crate::stage1::key::{LeafStateKey, Stage1Key};
@@ -37,6 +41,8 @@ const OP_CHECKPOINT: &str = "checkpoint";
const DEFAULT_BLOCK_CACHE_BYTES: usize = 128 * 1024 * 1024;
const DEFAULT_WRITE_BUFFER_BYTES: usize = 64 * 1024 * 1024;
const DEFAULT_MAX_OPEN_FILES: i32 = 1024;
+/// `get` is on the hot path, so sample the latency histogram 1-in-64 by default; the counter is exact.
+const DEFAULT_READ_SAMPLE_RATIO: u32 = 64;
const DEFAULT_COMPACT_ON_DELETION_WINDOW: usize = 1000;
const DEFAULT_COMPACT_ON_DELETION_NUM_DELS_TRIGGER: usize = 500;
@@ -53,6 +59,12 @@ pub struct StoreConfig {
pub create_if_missing: bool,
/// Destroy any existing database at `path` before opening.
pub wipe_on_start: bool,
+ /// Enable RocksDB statistics so [`CohortStore::stats_snapshot`] reports live cache tickers; they
+ /// read 0 when off.
+ pub statistics_enabled: bool,
+ /// Sample 1-in-N reads into [`STORE_READ_DURATION_SECONDS`] (the read counter stays exact).
+ /// `1` records every read; clamped to `>= 1` at open.
+ pub read_sample_ratio: u32,
/// Cache and partition index/filter blocks so point lookups short-circuit on the bloom.
pub tuned_block_options: bool,
/// Mark tombstone-heavy SSTs for compaction.
@@ -78,6 +90,8 @@ impl Default for StoreConfig {
max_open_files: DEFAULT_MAX_OPEN_FILES,
create_if_missing: true,
wipe_on_start: false,
+ statistics_enabled: true,
+ read_sample_ratio: DEFAULT_READ_SAMPLE_RATIO,
tuned_block_options: true,
compact_on_deletion: true,
compact_on_deletion_window: DEFAULT_COMPACT_ON_DELETION_WINDOW,
@@ -122,6 +136,11 @@ pub type RawKv = (Vec<u8>, Vec<u8>);
#[derive(Clone)]
pub struct CohortStore {
db: Arc<DBWithThreadMode<SingleThreaded>>,
+ /// Retained so [`Self::stats_snapshot`] can read cache tickers: RocksDB shares one statistics
+ /// handle between these `Options` and the live DB, so reads here reflect ongoing activity.
+ db_opts: Arc<Options>,
+ /// See [`StoreConfig::read_sample_ratio`]; `>= 1`.
+ read_sample_ratio: u32,
}
impl CohortStore {
@@ -157,13 +176,26 @@ impl CohortStore {
}
})?;
- Ok(Self { db: Arc::new(db) })
+ Ok(Self {
+ db: Arc::new(db),
+ db_opts: Arc::new(db_opts),
+ // Floor at 1: `next % ratio` must not divide by zero.
+ read_sample_ratio: config.read_sample_ratio.max(1),
+ })
}
/// Read a raw value from any CF.
pub fn get(&self, cf: Cf, key: &[u8]) -> Result<Option<Vec<u8>>, StoreError> {
let handle = self.cf(cf)?;
- self.db.get_cf(handle, key).map_err(|source| {
+ // Sample 1-in-N; unsampled reads skip even `Instant::now()`. The counter below stays exact.
+ let started = should_sample_read(self.read_sample_ratio).then(Instant::now);
+ let result = self.db.get_cf(handle, key);
+ if let Some(started) = started {
+ histogram!(STORE_READ_DURATION_SECONDS, "op" => OP_GET)
+ .record(started.elapsed().as_secs_f64());
+ }
+ counter!(STORE_READS_TOTAL, "op" => OP_GET).increment(1);
+ result.map_err(|source| {
counter!(STORE_ERRORS_TOTAL, "op" => OP_GET).increment(1);
StoreError::Backend { op: OP_GET, source }
})
@@ -175,10 +207,18 @@ impl CohortStore {
/// Batch-read several `cf_stage1` values in one call, preserving input order.
pub fn multi_get_stage1(&self, keys: &[Stage1Key]) -> Result<Vec<Option<Vec<u8>>>, StoreError> {
+ // An empty batch is not a read: skip it so it records no phantom read-latency sample.
+ if keys.is_empty() {
+ return Ok(Vec::new());
+ }
let handle = self.cf(Cf::Stage1)?;
let encoded: Vec<_> = keys.iter().map(Stage1Key::encode).collect();
- self.db
- .multi_get_cf(encoded.iter().map(|key| (handle, key.as_slice())))
+ let started = Instant::now();
+ let results = self
+ .db
+ .multi_get_cf(encoded.iter().map(|key| (handle, key.as_slice())));
+ record_multi_get(started, keys.len());
+ results
.into_iter()
.map(|result| {
result.map_err(|source| {
@@ -198,10 +238,18 @@ impl CohortStore {
/// Batch-read several `cf_stage2` values in one call, preserving input order.
pub fn multi_get_stage2(&self, keys: &[Stage2Key]) -> Result<Vec<Option<Vec<u8>>>, StoreError> {
+ // An empty batch is not a read: skip it so it records no phantom read-latency sample.
+ if keys.is_empty() {
+ return Ok(Vec::new());
+ }
let handle = self.cf(Cf::Stage2)?;
let encoded: Vec<_> = keys.iter().map(Stage2Key::encode).collect();
- self.db
- .multi_get_cf(encoded.iter().map(|key| (handle, key.as_slice())))
+ let started = Instant::now();
+ let results = self
+ .db
+ .multi_get_cf(encoded.iter().map(|key| (handle, key.as_slice())));
+ record_multi_get(started, keys.len());
+ results
.into_iter()
.map(|result| {
result.map_err(|source| {
@@ -484,6 +532,49 @@ impl CohortStore {
Ok(out)
}
+ /// Snapshot the block-cache tickers and per-CF size properties. Tickers are cumulative since store
+ /// open and read 0 when `statistics_enabled` is off; per-CF properties read 0 when RocksDB has no
+ /// estimate yet (a fresh, never-written CF).
+ pub fn stats_snapshot(&self) -> StoreStats {
+ let ticker = |t: Ticker| self.db_opts.get_ticker_count(t);
+ StoreStats {
+ block_cache_hits: ticker(Ticker::BlockCacheHit),
+ block_cache_misses: ticker(Ticker::BlockCacheMiss),
+ block_cache_data_hits: ticker(Ticker::BlockCacheDataHit),
+ block_cache_data_misses: ticker(Ticker::BlockCacheDataMiss),
+ block_cache_index_hits: ticker(Ticker::BlockCacheIndexHit),
+ block_cache_index_misses: ticker(Ticker::BlockCacheIndexMiss),
+ block_cache_filter_hits: ticker(Ticker::BlockCacheFilterHit),
+ block_cache_filter_misses: ticker(Ticker::BlockCacheFilterMiss),
+ bloom_filter_useful: ticker(Ticker::BloomFilterUseful),
+ // The block cache is shared across every CF, so any CF handle reports the same usage.
+ block_cache_usage_bytes: self
+ .cf_property_u64(Cf::Stage1, properties::BLOCK_CACHE_USAGE),
+ per_cf: Cf::ALL
+ .iter()
+ .map(|&cf| CfStats {
+ cf,
+ sst_bytes: self.cf_property_u64(cf, properties::TOTAL_SST_FILES_SIZE),
+ live_data_bytes: self.cf_property_u64(cf, properties::ESTIMATE_LIVE_DATA_SIZE),
+ num_keys: self.cf_property_u64(cf, properties::ESTIMATE_NUM_KEYS),
+ })
+ .collect(),
+ }
+ }
+
+ /// Read an integer RocksDB property for one CF; an absent handle, error, or missing estimate all
+ /// fold to 0.
+ fn cf_property_u64(&self, cf: Cf, name: &PropName) -> u64 {
+ let Ok(handle) = self.cf(cf) else {
+ return 0;
+ };
+ self.db
+ .property_int_value_cf(handle, name)
+ .ok()
+ .flatten()
+ .unwrap_or(0)
+ }
+
fn cf(&self, cf: Cf) -> Result<&ColumnFamily, StoreError> {
self.db
.cf_handle(cf.as_str())
@@ -512,6 +603,36 @@ impl CohortStore {
}
}
+/// Snapshot of the store's cache tickers and per-CF sizes, produced by
+/// [`CohortStore::stats_snapshot`].
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct StoreStats {
+ pub block_cache_hits: u64,
+ pub block_cache_misses: u64,
+ pub block_cache_data_hits: u64,
+ pub block_cache_data_misses: u64,
+ pub block_cache_index_hits: u64,
+ pub block_cache_index_misses: u64,
+ pub block_cache_filter_hits: u64,
+ pub block_cache_filter_misses: u64,
+ /// Point lookups the bloom filter let skip a data-block read.
+ pub bloom_filter_useful: u64,
+ pub block_cache_usage_bytes: u64,
+ /// One entry per [`Cf::ALL`].
+ pub per_cf: Vec<CfStats>,
+}
+
+/// Per-column-family size properties. See [`StoreStats`].
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct CfStats {
+ pub cf: Cf,
+ pub sst_bytes: u64,
+ /// Estimated live (non-tombstone) data bytes.
+ pub live_data_bytes: u64,
+ /// Estimated key count (memtable-inclusive, so non-zero before a flush).
+ pub num_keys: u64,
+}
+
/// Typed builder for a multi-CF [`WriteBatch`].
pub struct BatchBuilder<'db> {
batch: WriteBatch,
@@ -606,6 +727,28 @@ impl BatchBuilder<'_> {
}
}
+thread_local! {
+ /// Thread-local to avoid cross-worker contention; each worker samples independently (~1-in-N).
+ static READ_SAMPLE_COUNTER: Cell<u32> = const { Cell::new(0) };
+}
+
+/// Fires once per `ratio` calls. Count-based, so sampled quantiles stay unbiased; `ratio >= 1`.
+fn should_sample_read(ratio: u32) -> bool {
+ READ_SAMPLE_COUNTER.with(|counter| {
+ let next = counter.get().wrapping_add(1);
+ counter.set(next);
+ next % ratio == 0
+ })
+}
+
+/// Records one duration sample and `key_count` logical reads for a `multi_get` (a batch touches
+/// `key_count` keys).
+fn record_multi_get(started: Instant, key_count: usize) {
+ histogram!(STORE_READ_DURATION_SECONDS, "op" => OP_MULTI_GET)
+ .record(started.elapsed().as_secs_f64());
+ counter!(STORE_READS_TOTAL, "op" => OP_MULTI_GET).increment(key_count as u64);
+}
+
/// The smallest byte string strictly greater than `key`: `key` with a trailing `0x00` appended.
/// Used to turn an inclusive `IteratorMode::From` seek into an exclusive resume past a cursor.
fn successor(key: &[u8]) -> Vec<u8> {
@@ -623,6 +766,12 @@ fn db_options(config: &StoreConfig) -> Options {
opts.set_max_open_files(config.max_open_files);
opts.set_allow_mmap_reads(false);
opts.set_allow_mmap_writes(false);
+ if config.statistics_enabled {
+ // `ExceptHistogramOrTimers` keeps the cheap cache tickers and drops the expensive per-op
+ // histograms and timers.
+ opts.enable_statistics();
+ opts.set_statistics_level(StatsLevel::ExceptHistogramOrTimers);
+ }
if config.max_background_jobs > 0 {
opts.set_max_background_jobs(config.max_background_jobs);
}
@@ -1140,6 +1289,85 @@ mod tests {
);
}
+ #[test]
+ fn stats_snapshot_reports_keys_and_cache_activity_after_reads() {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ statistics_enabled: true,
+ ..StoreConfig::default()
+ })
+ .unwrap();
+
+ let key = |person: u128| Stage1Key {
+ partition_id: 3,
+ team_id: 7,
+ leaf_state_key: LeafStateKey([0xAB; 16]),
+ person_id: Uuid::from_u128(person),
+ };
+ store
+ .write_batch(|batch| {
+ for person in 1..=8u128 {
+ batch.put_stage1(&key(person), b"state");
+ }
+ })
+ .unwrap();
+ // Only SST reads exercise the block cache (memtable hits short-circuit it), so flush first.
+ store.flush().unwrap();
+
+ for person in 1..=8u128 {
+ assert!(store.get_stage1(&key(person)).unwrap().is_some());
+ }
+
+ let stats = store.stats_snapshot();
+ assert_eq!(
+ stats.per_cf.len(),
+ Cf::ALL.len(),
+ "one CfStats entry per column family",
+ );
+ let stage1 = stats
+ .per_cf
+ .iter()
+ .find(|cf| cf.cf == Cf::Stage1)
+ .expect("Stage1 CF present in the snapshot");
+ assert!(
+ stage1.num_keys > 0,
+ "estimate-num-keys counts the written keys"
+ );
+ assert!(stage1.sst_bytes > 0, "flushed Stage1 keys occupy SST bytes");
+ assert!(
+ stats.block_cache_hits + stats.block_cache_misses > 0,
+ "reads against the flushed SSTs drove block-cache lookups: hits={}, misses={}",
+ stats.block_cache_hits,
+ stats.block_cache_misses,
+ );
+ }
+
+ #[test]
+ fn stats_snapshot_tickers_are_zero_when_statistics_disabled() {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ statistics_enabled: false,
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ let key = stage1_key();
+ store.write_batch(|b| b.put_stage1(&key, b"state")).unwrap();
+ store.flush().unwrap();
+ assert!(store.get_stage1(&key).unwrap().is_some());
+
+ let stats = store.stats_snapshot();
+ // Tickers read 0 with statistics off; size properties are not gated on statistics.
+ assert_eq!(stats.block_cache_hits, 0);
+ assert_eq!(stats.block_cache_misses, 0);
+ let stage1 = stats.per_cf.iter().find(|cf| cf.cf == Cf::Stage1).unwrap();
+ assert!(
+ stage1.num_keys > 0,
+ "size properties work without statistics"
+ );
+ }
+
#[test]
fn default_config_is_sane() {
let config = StoreConfig::default();
@@ -1147,6 +1375,11 @@ mod tests {
assert!(config.block_cache_bytes > 0);
assert!(config.write_buffer_bytes > 0);
assert!(config.max_open_files > 0);
+ assert!(config.statistics_enabled, "statistics default on");
+ assert_eq!(
+ config.read_sample_ratio, 64,
+ "read latency sampling defaults to 1-in-64",
+ );
assert!(config.tuned_block_options);
assert!(config.compact_on_deletion);
assert!(config.compact_on_deletion_window > 0);
@@ -1157,6 +1390,28 @@ mod tests {
assert_eq!(config.max_background_jobs, 0);
}
+ #[test]
+ fn read_sampler_fires_once_per_ratio() {
+ // `ratio == 1` samples every read.
+ assert!((0..4).all(|_| should_sample_read(1)));
+ // Any 64 consecutive calls hold exactly one multiple of 64, so carry-over doesn't matter.
+ let hits = (0..64).filter(|_| should_sample_read(64)).count();
+ assert_eq!(hits, 1, "1-in-64 fires exactly once across 64 calls");
+ }
+
+ #[test]
+ fn read_sample_ratio_floors_zero_at_one() {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ read_sample_ratio: 0,
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ // `0` would panic `next % ratio` in `should_sample_read`; `open()` clamps it to 1.
+ assert!(store.get(Cf::Stage1, b"missing").unwrap().is_none());
+ }
+
#[test]
fn cohort_store_is_send_and_sync() {
fn assert_send_sync<T: Send + Sync>() {}
diff --git a/rust/cohort-stream-processor/src/sweep/scheduler.rs b/rust/cohort-stream-processor/src/sweep/scheduler.rs
index 36ade9101f2d..10226bd5732c 100644
--- a/rust/cohort-stream-processor/src/sweep/scheduler.rs
+++ b/rust/cohort-stream-processor/src/sweep/scheduler.rs
@@ -36,8 +36,8 @@ pub fn due_before_ms(now_ms: i64, safety_margin_ms: i64) -> i64 {
/// Drive the periodic sweep until `cancel` fires, invoking `sweeper.run_once()` once per tick and
/// recording [`SWEEP_CYCLES_TOTAL`] + [`SWEEP_CYCLE_DURATION_SECONDS`], both labelled by `loop_name`.
///
-/// `loop_name` (`eviction`|`redrive`|`merge_gc`|`checkpoint`) labels the cycle metrics so the
-/// concurrent loops — same timer machinery, different cadences — stay distinguishable.
+/// `loop_name` (`eviction`|`redrive`|`merge_gc`|`checkpoint`|`store_stats`) labels the cycle metrics
+/// so the concurrent loops — same timer machinery, different cadences — stay distinguishable.
///
/// - **`MissedTickBehavior::Skip`**: if a sweep runs long or the task is starved, the timer drops the
/// ticks it slept through rather than firing a catch-up burst — one sweep then resumes on the