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.

perf(cohorts): offload store io to spawn_blocking (#68243)

Matheus Batista6f5cf6a18ddb
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 6aed93fb2fe5..7c888cf13979 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -74,6 +74,9 @@ unit_bindings = "deny"
[workspace.lints.clippy]
# See https://rust-lang.github.io/rust-clippy/, we might want to add more
enum_glob_use = "deny"
+# Inert for every crate that ships no `clippy.toml` `disallowed-methods` list (all of them but
+# `cohort-stream-processor`, whose list confines async code to the `StoreHandle` facade).
+disallowed_methods = "deny"
# this is needed until getsentry/symbolic update the js-source-scopes to >0.6.0
# I made a PR for the upstream fix here https://github.com/getsentry/symbolic/pull/945
diff --git a/rust/cohort-stream-processor/clippy.toml b/rust/cohort-stream-processor/clippy.toml
new file mode 100644
index 000000000000..0cd24da64ce6
--- /dev/null
+++ b/rust/cohort-stream-processor/clippy.toml
@@ -0,0 +1,29 @@
+# Async code must reach the store through `StoreHandle` (which offloads I/O to the blocking pool),
+# never a raw `CohortStore` I/O method on a runtime thread. Every direct `CohortStore` I/O method is
+# disallowed here; the workspace lint level (`rust/Cargo.toml`) raises `disallowed_methods` to deny.
+# Sync contexts that legitimately need the direct surface each carry one
+# `#[allow(clippy::disallowed_methods)]` with a justification. `CohortStore::open` is omitted:
+# constructing the store is not an I/O op and every context needs it.
+disallowed-methods = [
+ { path = "cohort_stream_processor::store::rocks::CohortStore::get", reason = "async code must read through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::get_stage1", reason = "async code must read through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::multi_get_stage1", reason = "async code must read through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::get_stage2", reason = "async code must read through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::multi_get_stage2", reason = "async code must read through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::get_person_index", reason = "async code must read through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::write_batch", reason = "async code must write through StoreHandle::commit; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::apply", reason = "async code must write through StoreHandle::commit; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::get_merge_drain_applied", reason = "async code must read through StoreHandle or run_section; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::get_merge_applied", reason = "async code must read through StoreHandle or run_section; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::get_tombstone", reason = "async code must read through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::get_pending_transfer", reason = "async code must read through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::clear_pending_transfer", reason = "async code must write through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::scan_pending_transfers", reason = "async code must scan through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::scan_merge_cf", reason = "async code must scan through StoreHandle or run_section; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::scan_stage1", reason = "async code must scan through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::delete_partition", reason = "async code must use StoreHandle::delete_partition (or delete_partition_blocking under a no-await guard) — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::flush", reason = "async code must go through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::flush_wal_sync", reason = "async code must use StoreHandle::flush_wal_sync; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::create_checkpoint", reason = "async code must go through the checkpoint sweeper's own offload; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::stats_snapshot", reason = "async code must use StoreHandle::stats_snapshot; sync contexts need a module-level allow — see store/handle.rs" },
+]
diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rs
index d6330303edc0..43eb410d00a2 100644
--- a/rust/cohort-stream-processor/src/config.rs
+++ b/rust/cohort-stream-processor/src/config.rs
@@ -12,7 +12,7 @@ use rdkafka::ClientConfig;
use tracing::warn;
use crate::store::durability::DurabilityConfig;
-use crate::store::StoreConfig;
+use crate::store::{OffloadConfig, OffloadMode, StoreConfig};
use crate::workers::{CascadeConfig, EventNameGating, PersonMemoConfig, TransferRetryPolicy};
const POOL_NAME: &str = "posthog_cohort";
@@ -327,6 +327,24 @@ pub struct Config {
#[envconfig(from = "COHORT_MAX_BACKGROUND_JOBS", default = "0")]
pub cohort_max_background_jobs: i32,
+ /// Where store I/O runs relative to the runtime worker threads: `off` (inline on the caller — the
+ /// operator kill switch), `maintenance` (only maintenance-lane reads, the WAL fsync, and sections
+ /// offload; the event path stays inline), or `all` (every op offloads to the blocking pool).
+ /// Default `all`.
+ #[envconfig(from = "COHORT_STORE_OFFLOAD_MODE", default = "all")]
+ pub cohort_store_offload_mode: OffloadMode,
+
+ /// Bound on event-path store reads executing concurrently on the blocking pool. Keeps a burst of
+ /// event reads from saturating the disk queue; `0` disables the bound (unbounded lane).
+ #[envconfig(from = "COHORT_STORE_EVENT_READ_PERMITS", default = "16")]
+ pub cohort_store_event_read_permits: usize,
+
+ /// Bound on maintenance-lane store reads and sections executing concurrently on the blocking
+ /// pool (sweep prefetch, boot rebuild scans, GC). Held lower than the event lane so a
+ /// maintenance storm leaves disk headroom for the event path; `0` disables the bound.
+ #[envconfig(from = "COHORT_STORE_MAINTENANCE_PERMITS", default = "6")]
+ pub cohort_store_maintenance_permits: usize,
+
/// When on, reopen the existing store on restart instead of wiping it: recent Stage 1 state is
/// restored and only the gap since the last committed offset is replayed (idempotent via per-key
/// `AppliedOffsets`). Refused alongside `cohort_cascade_enabled` — merge column families are not
@@ -636,6 +654,16 @@ impl Config {
}
}
+ /// Resolve the store-offload strategy and per-lane concurrency bounds handed to the
+ /// [`StoreHandle`](crate::store::StoreHandle).
+ pub fn offload_config(&self) -> OffloadConfig {
+ OffloadConfig {
+ mode: self.cohort_store_offload_mode,
+ event_read_permits: self.cohort_store_event_read_permits,
+ maintenance_permits: self.cohort_store_maintenance_permits,
+ }
+ }
+
/// Stable per-pod identity for static group membership, `POD_NAME` preferred over `HOSTNAME`.
/// `None` leaves static membership off.
pub fn pod_identity(&self) -> Option<&str> {
@@ -838,6 +866,9 @@ mod tests {
cohort_compact_on_deletion_enabled: true,
cohort_periodic_compaction_seconds: 0,
cohort_max_background_jobs: 0,
+ cohort_store_offload_mode: OffloadMode::All,
+ cohort_store_event_read_permits: 16,
+ cohort_store_maintenance_permits: 6,
durable_restore_enabled: false,
durable_restore_single_pod: false,
checkpoint_enabled: false,
@@ -1044,6 +1075,52 @@ mod tests {
);
}
+ #[test]
+ fn offload_knobs_default_and_override_from_env() {
+ let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();
+ let offload = defaults.offload_config();
+ assert_eq!(offload.mode, OffloadMode::All, "offload defaults to All");
+ assert_eq!(offload.event_read_permits, 16);
+ assert_eq!(offload.maintenance_permits, 6);
+
+ let env: std::collections::HashMap<String, String> = [
+ ("COHORT_STORE_OFFLOAD_MODE", "maintenance"),
+ ("COHORT_STORE_EVENT_READ_PERMITS", "8"),
+ ("COHORT_STORE_MAINTENANCE_PERMITS", "0"),
+ ]
+ .into_iter()
+ .map(|(key, value)| (key.to_string(), value.to_string()))
+ .collect();
+ let config = Config::init_from_hashmap(&env).unwrap();
+ let offload = config.offload_config();
+ assert_eq!(offload.mode, OffloadMode::Maintenance);
+ assert_eq!(offload.event_read_permits, 8);
+ assert_eq!(offload.maintenance_permits, 0, "0 = unbounded lane");
+
+ let off_env: std::collections::HashMap<String, String> =
+ [("COHORT_STORE_OFFLOAD_MODE", "off")]
+ .into_iter()
+ .map(|(key, value)| (key.to_string(), value.to_string()))
+ .collect();
+ assert_eq!(
+ Config::init_from_hashmap(&off_env)
+ .unwrap()
+ .offload_config()
+ .mode,
+ OffloadMode::Off,
+ );
+
+ let bad_env: std::collections::HashMap<String, String> =
+ [("COHORT_STORE_OFFLOAD_MODE", "occasionally")]
+ .into_iter()
+ .map(|(key, value)| (key.to_string(), value.to_string()))
+ .collect();
+ assert!(
+ Config::init_from_hashmap(&bad_env).is_err(),
+ "an invalid offload mode must fail config init",
+ );
+ }
+
#[test]
fn stats_publish_interval_floors_zero_at_one_second() {
// Zero would panic `tokio::time::interval`; the accessor clamps to 1s.
diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rs
index e24599f5ea53..bfd8c749dcda 100644
--- a/rust/cohort-stream-processor/src/consumers/events.rs
+++ b/rust/cohort-stream-processor/src/consumers/events.rs
@@ -47,7 +47,7 @@ use crate::partitions::router::{PartitionRouter, SendOutcome};
use crate::partitions::shuffle_message::ShuffleMessage;
use crate::producer::MembershipSink;
use crate::store::durability::OffsetManifest;
-use crate::store::CohortStore;
+use crate::store::StoreHandle;
use crate::workers::{EventNameGating, MergeWorkerDeps, PersonMemoConfig, Stage1Worker};
/// Back-off after a Kafka transport error so a fast-failing `recv()` can't spin a consume loop.
@@ -114,7 +114,7 @@ pub struct EventDispatcher {
workers: Arc<DashMap<i32, Stage1Worker>>,
/// Partitions currently assigned to this consumer.
owned: Arc<DashSet<i32>>,
- store: CohortStore,
+ handle: StoreHandle,
catalog: Arc<CatalogHandle>,
sink: Arc<dyn MembershipSink>,
merge: Arc<MergeWorkerDeps>,
@@ -138,7 +138,7 @@ impl EventDispatcher {
pub fn new(
router: PartitionRouter,
tracker: Arc<OffsetTracker>,
- store: CohortStore,
+ handle: StoreHandle,
catalog: Arc<CatalogHandle>,
sink: Arc<dyn MembershipSink>,
merge: Arc<MergeWorkerDeps>,
@@ -148,7 +148,7 @@ impl EventDispatcher {
tracker,
workers: Arc::new(DashMap::new()),
owned: Arc::new(DashSet::new()),
- store,
+ handle,
catalog,
sink,
merge,
@@ -193,8 +193,8 @@ impl EventDispatcher {
.unwrap_or(EventNameGating::Disabled)
}
- pub(crate) fn store(&self) -> &CohortStore {
- &self.store
+ pub(crate) fn handle(&self) -> &StoreHandle {
+ &self.handle
}
/// Blocking events dispatch, retained for tests; the consume loop uses
@@ -470,7 +470,7 @@ impl EventDispatcher {
let worker = Stage1Worker::spawn_with_memo(
partition as u16,
receiver,
- self.store.clone(),
+ self.handle.clone(),
self.catalog.clone(),
self.sink.clone(),
self.tracker.clone(),
@@ -629,7 +629,7 @@ impl EventDispatcher {
);
return;
};
- match self.store.delete_partition(partition_id) {
+ match self.handle.delete_partition(partition_id).await {
Ok(()) => counter!(PARTITION_STATE_DELETED_TOTAL).increment(1),
Err(err) => {
warn!(partition, error = %err, "failed to delete revoked partition state")
@@ -659,7 +659,9 @@ impl EventDispatcher {
);
return;
};
- match self.store.delete_partition(partition_id) {
+ // Sync escape hatch: runs under the partition's DashMap shard guard, so no `.await`. The
+ // delete is one range tombstone per CF and rare (a post-boot move-in).
+ match self.handle.delete_partition_blocking(partition_id) {
Ok(()) => counter!(DURABLE_RESTORE_PARTITIONS_WIPED_STALE_TOTAL).increment(1),
Err(err) => warn!(
partition,
@@ -671,7 +673,7 @@ impl EventDispatcher {
/// Delete on-disk slices for partitions in `0..partition_count` not in `assignment`: they
/// moved away while this pod was down. `assignment` must be the settled (non-empty) assignment
/// — an empty set would delete all slices.
- pub(crate) fn reclaim_unassigned_partitions_on_boot(
+ pub(crate) async fn reclaim_unassigned_partitions_on_boot(
&self,
assignment: &std::collections::HashSet<i32>,
partition_count: usize,
@@ -684,7 +686,7 @@ impl EventDispatcher {
continue;
}
if let Some(partition_id) = partition_to_store_id(partition) {
- match self.store.delete_partition(partition_id) {
+ match self.handle.delete_partition(partition_id).await {
Ok(()) => wiped += 1,
Err(err) => warn!(
partition,
@@ -703,7 +705,7 @@ impl EventDispatcher {
/// Record the boot assignment snapshot, then sweep stale on-disk slices. Recording first makes
/// the assign path defer to the boot decision and reclaim only post-boot move-ins.
- pub(crate) fn reconcile_boot_assignment(
+ pub(crate) async fn reconcile_boot_assignment(
&self,
assignment: &HashSet<i32>,
partition_count: usize,
@@ -711,7 +713,8 @@ impl EventDispatcher {
if self.boot_assignment.set(assignment.clone()).is_err() {
debug!("boot assignment snapshot already recorded; keeping the first");
}
- self.reclaim_unassigned_partitions_on_boot(assignment, partition_count);
+ self.reclaim_unassigned_partitions_on_boot(assignment, partition_count)
+ .await;
}
/// Re-produce every staged `cf_pending_transfers` entry for the owned partitions at boot,
@@ -757,11 +760,11 @@ impl EventDispatcher {
let mut cursor: Option<Vec<u8>> = None;
let mut recovered = 0usize;
loop {
- let page = match self.store.scan_pending_transfers(
- store_partition,
- cursor.as_deref(),
- page_size,
- ) {
+ let page = match self
+ .handle
+ .scan_pending_transfers(store_partition, cursor.clone(), page_size)
+ .await
+ {
Ok(page) => page,
Err(error) => {
warn!(
@@ -811,7 +814,7 @@ impl EventDispatcher {
);
continue;
}
- if let Err(error) = self.store.clear_pending_transfer(&key) {
+ if let Err(error) = self.handle.clear_pending_transfer(&key).await {
warn!(
partition,
team_id,
@@ -983,7 +986,8 @@ impl CohortStreamEventsConsumer {
outcome = self.consume_batch() => {
// Sweep before dispatching, so the reclaim never races a worker spawn.
if !boot_sweep_done {
- boot_sweep_done = self.run_boot_staleness_sweep(&mut prev_assignment);
+ boot_sweep_done =
+ self.run_boot_staleness_sweep(&mut prev_assignment).await;
}
// Redrive after the boot sweep settles. Skip dispatching this batch so boot
// recovery completes before any fold work.
@@ -1027,24 +1031,26 @@ impl CohortStreamEventsConsumer {
let tracker = self.dispatcher.shutdown().await;
let offsets = self.dispatcher.owned_committable_offsets();
fsync_then_commit(
- self.dispatcher.store(),
+ self.dispatcher.handle(),
&self.consumer,
&tracker,
offsets,
&self.topic,
CommitMode::Sync,
- );
+ )
+ .await;
info!(topic = %self.topic, "cohort_stream_events consume loop stopped");
}
/// Returns `true` once the boot snapshot is reconciled, `false` while the assignment is unsettled.
- fn run_boot_staleness_sweep(&self, prev: &mut Option<HashSet<i32>>) -> bool {
+ async fn run_boot_staleness_sweep(&self, prev: &mut Option<HashSet<i32>>) -> bool {
let assignment = self.assigned_partitions();
if !boot_assignment_settled(&assignment, prev) {
return false;
}
self.dispatcher
- .reconcile_boot_assignment(&assignment, self.events_partitions);
+ .reconcile_boot_assignment(&assignment, self.events_partitions)
+ .await;
true
}
@@ -1289,8 +1295,12 @@ pub(crate) fn commit_offsets<C: ConsumerContext>(
/// fsync the store's WAL before committing offsets, upholding `committed <= durable`. Unconditional
/// so reopen-live is safe whenever the durability gate is flipped. A fsync error skips the commit.
-pub(crate) fn fsync_then_commit<C: ConsumerContext>(
- store: &CohortStore,
+///
+/// The caller captures `offsets` before this runs, so the fsync makes durable exactly what they
+/// already reflect. It runs on the write lane with no permit so the commit cadence never queues
+/// behind reads.
+pub(crate) async fn fsync_then_commit<C: ConsumerContext>(
+ handle: &StoreHandle,
consumer: &StreamConsumer<C>,
tracker: &OffsetTracker,
offsets: HashMap<i32, i64>,
@@ -1300,7 +1310,7 @@ pub(crate) fn fsync_then_commit<C: ConsumerContext>(
if offsets.is_empty() {
return;
}
- if store.flush_wal_sync().is_err() {
+ if handle.flush_wal_sync().await.is_err() {
return; // store counted the error; skip commit so `committed` never outruns `durable`
}
commit_offsets(consumer, tracker, offsets, topic, mode);
@@ -1323,13 +1333,14 @@ async fn run_commit_loop(
_ = handle.shutdown_recv() => break,
_ = ticker.tick() => {
fsync_then_commit(
- dispatcher.store(),
+ dispatcher.handle(),
&consumer,
dispatcher.tracker(),
dispatcher.owned_committable_offsets(),
&topic,
CommitMode::Async,
- );
+ )
+ .await;
}
}
}
@@ -1354,6 +1365,9 @@ async fn run_pauser_loop(
}
#[cfg(test)]
+// Tests seed and assert against `CohortStore` directly while the dispatchers hold the `StoreHandle`
+// facade.
+#[allow(clippy::disallowed_methods)]
mod tests {
use super::*;
use chrono_tz::UTC;
@@ -1374,8 +1388,8 @@ mod tests {
use crate::stage1::state::AppliedOffsets;
use crate::stage1::{Stage1State, StatefulRecord};
use crate::store::{
- LeafStateKey, MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage1Key, StoreConfig,
- TombstoneKey,
+ CohortStore, LeafStateKey, MergeAppliedKey, MergeDrainKey, OffloadConfig, OffloadMode,
+ PendingTransferKey, Stage1Key, StoreConfig, TombstoneKey,
};
use crate::workers::TransferRetryPolicy;
@@ -1383,6 +1397,18 @@ mod tests {
const BEHAVIORAL_HASH: [u8; 16] = *b"0123456789abcdef";
const BASE_TS: &str = "2026-05-26 12:34:56.789000";
+ /// Wrap a test store in the `All` operating point so the dispatcher runs on the blocking pool.
+ fn test_handle(store: &CohortStore) -> StoreHandle {
+ StoreHandle::new(
+ store.clone(),
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ )
+ }
+
/// Broker-free [`PartitionPauser`] recording every pause/resume call, to exercise the pauser task
/// without a Kafka client.
#[derive(Default)]
@@ -1722,7 +1748,7 @@ mod tests {
let dispatcher = EventDispatcher::new(
PartitionRouter::new(64),
Arc::new(OffsetTracker::new()),
- store.clone(),
+ test_handle(store),
catalog,
sink.clone(),
merge.clone(),
@@ -1827,7 +1853,9 @@ mod tests {
// Boot snapshot includes 6 (reopen-live) but not 5 (post-boot move-in); partition_count 5
// keeps the boot sweep off both 5 and 6.
- dispatcher.reconcile_boot_assignment(&[6].into_iter().collect(), 5);
+ dispatcher
+ .reconcile_boot_assignment(&[6].into_iter().collect(), 5)
+ .await;
dispatcher.reclaim_stale_slice(5);
assert!(
@@ -1852,7 +1880,9 @@ mod tests {
seed_slice(&store, 5, lsk);
// Boot excludes 5 (a post-boot move-in); partition_count 5 keeps the boot sweep off 5.
- dispatcher.reconcile_boot_assignment(&[6].into_iter().collect(), 5);
+ dispatcher
+ .reconcile_boot_assignment(&[6].into_iter().collect(), 5)
+ .await;
dispatcher.assign_partition(5);
dispatcher.ensure_worker(5);
@@ -1886,7 +1916,9 @@ mod tests {
// Durable restore left off: ensure_worker must never reclaim — wipe-on-start handles staleness.
seed_slice(&store, 5, lsk);
- dispatcher.reconcile_boot_assignment(&[6].into_iter().collect(), 5);
+ dispatcher
+ .reconcile_boot_assignment(&[6].into_iter().collect(), 5)
+ .await;
dispatcher.assign_partition(5);
dispatcher.ensure_worker(5);
@@ -1928,7 +1960,9 @@ mod tests {
}
let assignment: HashSet<i32> = [0, 2].into_iter().collect();
- dispatcher.reclaim_unassigned_partitions_on_boot(&assignment, 3);
+ dispatcher
+ .reclaim_unassigned_partitions_on_boot(&assignment, 3)
+ .await;
assert!(
slice_present(&store, 0, lsk),
@@ -2061,7 +2095,7 @@ mod tests {
EventDispatcher::new(
PartitionRouter::new(buffer),
Arc::new(OffsetTracker::new()),
- store.clone(),
+ test_handle(store),
catalog,
sink,
MergeWorkerDeps::capture(),
@@ -2080,7 +2114,7 @@ mod tests {
EventDispatcher::new(
PartitionRouter::with_intake_cap(buffer, cap),
Arc::new(OffsetTracker::new()),
- store.clone(),
+ test_handle(store),
catalog,
sink,
MergeWorkerDeps::capture(),
@@ -2988,7 +3022,7 @@ mod tests {
let dispatcher_b = EventDispatcher::new(
PartitionRouter::new(64),
Arc::new(OffsetTracker::new()),
- store.clone(),
+ test_handle(&store),
catalog,
Arc::new(CaptureSink::new()),
merge.clone(),
@@ -3154,7 +3188,7 @@ mod tests {
let dispatcher_b = EventDispatcher::new(
PartitionRouter::new(64),
Arc::new(OffsetTracker::new()),
- store.clone(),
+ test_handle(&store),
catalog.clone(),
Arc::new(CaptureSink::new()),
merge.clone(),
@@ -3179,7 +3213,7 @@ mod tests {
let dispatcher_c = EventDispatcher::new(
PartitionRouter::new(64),
Arc::new(OffsetTracker::new()),
- store.clone(),
+ test_handle(&store),
catalog,
Arc::new(apply_sink.clone()),
merge.clone(),
diff --git a/rust/cohort-stream-processor/src/consumers/merges.rs b/rust/cohort-stream-processor/src/consumers/merges.rs
index e9cea42be5a8..e8abd80ed60e 100644
--- a/rust/cohort-stream-processor/src/consumers/merges.rs
+++ b/rust/cohort-stream-processor/src/consumers/merges.rs
@@ -230,13 +230,14 @@ impl<R: FollowerRoute> FollowerConsumer<R> {
let now = tokio::time::Instant::now();
if now >= commit_deadline {
fsync_then_commit(
- self.dispatcher.store(),
+ self.dispatcher.handle(),
&self.consumer,
self.tracker(),
self.owned_committable_offsets(),
&self.topic,
CommitMode::Async,
- );
+ )
+ .await;
commit_deadline = now + self.offset_commit_interval;
}
}
@@ -246,13 +247,14 @@ impl<R: FollowerRoute> FollowerConsumer<R> {
// Final sync commit runs before the events consumer's shutdown; workers may still be marking
// offsets at this point, but follower offsets are independent.
fsync_then_commit(
- self.dispatcher.store(),
+ self.dispatcher.handle(),
&self.consumer,
self.tracker(),
self.owned_committable_offsets(),
&self.topic,
CommitMode::Sync,
- );
+ )
+ .await;
info!(topic = %self.topic, "follower consume loop stopped");
}
diff --git a/rust/cohort-stream-processor/src/filters/manager.rs b/rust/cohort-stream-processor/src/filters/manager.rs
index 981c610b45e3..10e0296e1a13 100644
--- a/rust/cohort-stream-processor/src/filters/manager.rs
+++ b/rust/cohort-stream-processor/src/filters/manager.rs
@@ -126,6 +126,13 @@ impl CatalogHandle {
self.catalog.load()
}
+ /// Load the current snapshot as an owned `Arc` that borrows nothing from `self`, so it can move
+ /// into a `'static` blocking closure (e.g. a
+ /// [`StoreHandle::run_section`](crate::store::StoreHandle::run_section) body).
+ pub fn load_full(&self) -> Arc<FilterCatalog> {
+ self.catalog.load_full()
+ }
+
/// True once the first refresh has succeeded. Before that the catalog is empty and consumers
/// should treat every team as having no realtime cohorts.
pub fn is_loaded(&self) -> bool {
diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rs
index 6ff5d12e9d00..11459d32b189 100644
--- a/rust/cohort-stream-processor/src/main.rs
+++ b/rust/cohort-stream-processor/src/main.rs
@@ -38,7 +38,7 @@ use cohort_stream_processor::store::durability::{
run_boot_restore, upload_cadence, CheckpointExporter, CheckpointSweeper, OffsetManifest,
S3Uploader, TrackedTopic, CHECKPOINT_LOOP_NAME,
};
-use cohort_stream_processor::store::CohortStore;
+use cohort_stream_processor::store::{CohortStore, StoreHandle};
use cohort_stream_processor::sweep::{run_sweep_loop, run_sweep_loop_delayed, DispatchSweeper};
use cohort_stream_processor::workers::MergeWorkerDeps;
@@ -212,19 +212,23 @@ async fn async_main(config: Config) -> Result<()> {
});
// Cheap `Arc` clones taken before the originals move into the dispatcher: the checkpoint sweeper
- // needs its own handle on the store and each per-topic tracker to capture the offset manifest.
+ // needs its own raw-store handle and each per-topic tracker to capture the offset manifest.
// Captured unconditionally to satisfy the borrow checker; consumed only when `checkpoint_enabled`.
+ // The sweeper keeps the raw `CohortStore` rather than the facade because of its must-not-panic
+ // policy (see checkpoint.rs).
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();
let cascade_tracker_for_checkpoint = merge_deps.cascade_tracker.clone();
+ let handle = StoreHandle::new(store, config.offload_config());
+ let handle_for_stats = handle.clone();
+
let dispatcher = Arc::new(EventDispatcher::new(
router,
offset_tracker,
- store,
+ handle,
catalog.clone(),
sink,
merge_deps,
@@ -415,7 +419,7 @@ async fn async_main(config: Config) -> Result<()> {
// 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),
+ StoreStatsSweeper::new(handle_for_stats),
config.stats_publish_interval(),
"store_stats",
consumer_handle.shutdown_token(),
diff --git a/rust/cohort-stream-processor/src/merge/apply_handler.rs b/rust/cohort-stream-processor/src/merge/apply_handler.rs
index f98b90f6d906..09eb7c518008 100644
--- a/rust/cohort-stream-processor/src/merge/apply_handler.rs
+++ b/rust/cohort-stream-processor/src/merge/apply_handler.rs
@@ -31,6 +31,31 @@ use crate::sweep::EvictionQueue;
use crate::workers::event_path::schedule_deadline;
use tracing::warn;
+/// The eviction-queue mutations a drain/apply commit implies. The handlers take owned inputs and no
+/// queue borrow, so they hand these back for the caller (which owns the queue) to apply after the
+/// atomic write commits and before any produce — a produce failure must never leave the queue ahead
+/// of the store. `cancels` are the old person's now-deleted keys; `schedules` the survivor's new
+/// eviction deadlines.
+#[must_use]
+#[derive(Debug, Default, Clone, PartialEq, Eq)]
+pub struct QueueEffects {
+ pub cancels: Vec<Stage1Key>,
+ pub schedules: Vec<(Stage1Key, i64)>,
+}
+
+impl QueueEffects {
+ /// Cancel first, then schedule. The two key sets are disjoint by construction (old person ≠ new
+ /// person), so the order is defensive.
+ pub fn apply_to(&self, queue: &mut EvictionQueue<Stage1Key>) {
+ for key in &self.cancels {
+ queue.cancel(key);
+ }
+ for &(key, deadline) in &self.schedules {
+ queue.schedule(key, deadline);
+ }
+ }
+}
+
/// Bound on cross-partition transfer-forward hops (`forward_hops` on the wire). Mirrors the
/// event-path [`crate::merge::tombstone_redirect::MAX_CROSS_PARTITION_REDIRECT_HOPS`] — prevents
/// infinite re-production between partitions in case of a corrupt cross-partition tombstone cycle.
@@ -39,7 +64,11 @@ pub const MAX_TRANSFER_FORWARD_HOPS: u8 = 8;
#[derive(Debug, Clone, PartialEq)]
pub enum ApplyOutcome {
/// Transfer applied; `transitions` are the resolved survivor's per-leaf membership flips.
- Applied { transitions: Vec<LeafTransition> },
+ /// `effects` carries the survivor's eviction schedules for the caller to apply to its queue.
+ Applied {
+ transitions: Vec<LeafTransition>,
+ effects: QueueEffects,
+ },
/// Idempotence hit — this transfer was already applied (replay / crash-recovery).
AlreadyApplied,
/// `new_person_uuid` is tombstoned to a survivor on a different partition. The caller forwards
@@ -61,13 +90,15 @@ pub enum ApplyOutcome {
/// `partition_count` is the live co-partitioned topic count (production 64; test lanes lower it):
/// the forward-vs-inline target resolution turns on whether the survivor hashes onto `partition_id`
/// under this count, so it must match the deploy's topology.
+// Sync apply core; runs on the blocking pool inside `StoreHandle::run_section`, so its direct
+// `CohortStore` I/O (and that of `apply_into`/`apply_leaves`) is already off the runtime threads.
+#[allow(clippy::disallowed_methods)]
pub fn handle_transfer(
partition_id: u16,
store: &CohortStore,
filters: &TeamFilters,
transfer: &MergeStateTransfer,
_transfer_coords: (i32, i64),
- queue: &mut EvictionQueue<Stage1Key>,
partition_count: u32,
) -> Result<ApplyOutcome, StoreError> {
let team_id = transfer.team_id;
@@ -93,12 +124,10 @@ pub fn handle_transfer(
new_person,
partition_count,
)? {
- Resolution::NotMerged => {
- apply_into(partition_id, store, filters, transfer, new_person, queue)
- }
+ Resolution::NotMerged => apply_into(partition_id, store, filters, transfer, new_person),
Resolution::Inline { final_person, .. } => {
counter!(MERGE_TRANSFER_FORWARDS_TOTAL, "path" => "inline").increment(1);
- apply_into(partition_id, store, filters, transfer, final_person, queue)
+ apply_into(partition_id, store, filters, transfer, final_person)
}
Resolution::CrossPartition { target_person, .. } => {
if transfer.forward_hops >= MAX_TRANSFER_FORWARD_HOPS {
@@ -143,13 +172,13 @@ fn applied_key(
/// commit the merged puts + person-index appends + the `cf_merge_applied` marker keyed by `target`,
/// schedule deadlines, and return the survivor's transitions. For the `NotMerged` case `target` is
/// just `new_person_uuid`.
+#[allow(clippy::disallowed_methods)]
fn apply_into(
partition_id: u16,
store: &CohortStore,
filters: &TeamFilters,
transfer: &MergeStateTransfer,
target: Uuid,
- queue: &mut EvictionQueue<Stage1Key>,
) -> Result<ApplyOutcome, StoreError> {
let team_u64 = transfer.team_id as u64;
let old_person = transfer.old_person_uuid;
@@ -219,12 +248,12 @@ fn apply_into(
}
})?;
- for (key, deadline) in &apply.schedules {
- queue.schedule(*key, *deadline);
- }
-
Ok(ApplyOutcome::Applied {
transitions: apply.transitions,
+ effects: QueueEffects {
+ cancels: Vec::new(),
+ schedules: apply.schedules,
+ },
})
}
@@ -241,6 +270,7 @@ pub(crate) struct LeafApply {
/// Merge each of P_old's `leaves` into P_new's state on `partition_new`. Pure reads only — the
/// caller composes the final write batch. A leaf whose LSK left the catalog is skipped; a corrupt
/// P_new record is treated as absent.
+#[allow(clippy::disallowed_methods)]
pub(crate) fn apply_leaves(
partition_new: u16,
store: &CohortStore,
diff --git a/rust/cohort-stream-processor/src/merge/drain_handler.rs b/rust/cohort-stream-processor/src/merge/drain_handler.rs
index 6c690b2d337d..b7a10e894677 100644
--- a/rust/cohort-stream-processor/src/merge/drain_handler.rs
+++ b/rust/cohort-stream-processor/src/merge/drain_handler.rs
@@ -16,7 +16,7 @@ use uuid::Uuid;
use crate::filters::reverse_index::TeamFilters;
use crate::filters::{CohortId, TeamId};
-use crate::merge::apply_handler::apply_leaves;
+use crate::merge::apply_handler::{apply_leaves, QueueEffects};
use crate::merge::tombstone_redirect::{resolve, Resolution};
use crate::merge::transfer::{
DrainStamp, MergeStateTransfer, PendingTransfer, PersonMergeEvent, Tombstone, TransferLeaf,
@@ -32,15 +32,22 @@ use crate::store::{
CohortStore, IndexOp, MergeDrainKey, PendingTransferKey, PersonIndexKey, Stage2Key, StoreError,
TombstoneKey,
};
-use crate::sweep::EvictionQueue;
#[derive(Debug, Clone, PartialEq)]
pub enum DrainOutcome {
- /// Same-partition fast path: P_old merged into P_new inline.
- FastPath { transitions: Vec<LeafTransition> },
+ /// Same-partition fast path: P_old merged into P_new inline. `effects` cancels P_old's keys and
+ /// schedules P_new's new deadlines.
+ FastPath {
+ transitions: Vec<LeafTransition>,
+ effects: QueueEffects,
+ },
/// Cross-partition slow path: state drained into `transfer`, staged in `cf_pending_transfers`.
/// An empty transfer (no leaves) is not staged; the caller skips the produce and commits directly.
- Drained { transfer: MergeStateTransfer },
+ /// `effects` cancels P_old's now-deleted keys (no schedules — the state left this partition).
+ Drained {
+ transfer: MergeStateTransfer,
+ effects: QueueEffects,
+ },
/// Idempotence hit — already drained. The caller re-produces any still-staged pending transfer.
AlreadyDrained,
/// Skipped before any state change (validation failure).
@@ -57,13 +64,15 @@ pub enum DrainSkip {
/// `partition_count` is the live co-partitioned topic count (production 64; test lanes lower it):
/// the fast-path-vs-slow-path decision turns on whether P_new hashes onto `partition_id` under this
/// count, so it must match the deploy's topology.
+// Sync drain core; runs on the blocking pool inside `StoreHandle::run_section`, so its direct
+// `CohortStore` I/O (and that of `fast_path`/`slow_path`) is already off the runtime threads.
+#[allow(clippy::disallowed_methods)]
pub fn handle_merge_event(
partition_id: u16,
store: &CohortStore,
filters: &TeamFilters,
event: &PersonMergeEvent,
msg_coords: (i32, i64),
- queue: &mut EvictionQueue<Stage1Key>,
partition_count: u32,
) -> Result<DrainOutcome, StoreError> {
let team_id = event.team_id;
@@ -175,7 +184,6 @@ pub fn handle_merge_event(
&old_index,
&old_stage2_keys,
&present_leaves,
- queue,
);
}
@@ -193,12 +201,11 @@ pub fn handle_merge_event(
&old_index,
&old_stage2_keys,
&present_leaves,
- queue,
)
}
/// Same-partition fast path: drain P_old and apply into P_new in one atomic batch.
-#[allow(clippy::too_many_arguments)]
+#[allow(clippy::too_many_arguments, clippy::disallowed_methods)]
fn fast_path(
partition_id: u16,
store: &CohortStore,
@@ -213,7 +220,6 @@ fn fast_path(
old_index: &PersonIndexKey,
old_stage2_keys: &[Stage2Key],
present_leaves: &[(LeafStateKey, StatefulRecord)],
- queue: &mut EvictionQueue<Stage1Key>,
) -> Result<DrainOutcome, StoreError> {
counter!(MERGE_HANDLED_TOTAL, "path" => "same_partition").increment(1);
@@ -251,20 +257,17 @@ fn fast_path(
}
})?;
- for key in old_keys {
- queue.cancel(key);
- }
- for (key, deadline) in &apply.schedules {
- queue.schedule(*key, *deadline);
- }
-
Ok(DrainOutcome::FastPath {
transitions: apply.transitions,
+ effects: QueueEffects {
+ cancels: old_keys.to_vec(),
+ schedules: apply.schedules,
+ },
})
}
/// Cross-partition slow path: drain P_old, stage the transfer for the caller to produce.
-#[allow(clippy::too_many_arguments)]
+#[allow(clippy::too_many_arguments, clippy::disallowed_methods)]
fn slow_path(
partition_id: u16,
store: &CohortStore,
@@ -279,7 +282,6 @@ fn slow_path(
old_index: &PersonIndexKey,
old_stage2_keys: &[Stage2Key],
present_leaves: &[(LeafStateKey, StatefulRecord)],
- queue: &mut EvictionQueue<Stage1Key>,
) -> Result<DrainOutcome, StoreError> {
counter!(MERGE_HANDLED_TOTAL, "path" => "cross_partition").increment(1);
@@ -325,11 +327,13 @@ fn slow_path(
batch.put_tombstone(tombstone_key, &tombstone.encode());
})?;
- for key in old_keys {
- queue.cancel(key);
- }
-
- Ok(DrainOutcome::Drained { transfer })
+ Ok(DrainOutcome::Drained {
+ transfer,
+ effects: QueueEffects {
+ cancels: old_keys.to_vec(),
+ schedules: Vec::new(),
+ },
+ })
}
/// The team's cohort ids that write `cf_stage2` rows (both composable classes). See
diff --git a/rust/cohort-stream-processor/src/merge/gc.rs b/rust/cohort-stream-processor/src/merge/gc.rs
index 090a5e39418f..30fc4e00197f 100644
--- a/rust/cohort-stream-processor/src/merge/gc.rs
+++ b/rust/cohort-stream-processor/src/merge/gc.rs
@@ -84,7 +84,7 @@ mod tests {
use crate::filters::{CatalogHandle, FilterCatalog};
use crate::partitions::{OffsetTracker, PartitionRouter};
use crate::producer::{CaptureSink, MembershipSink};
- use crate::store::{CohortStore, StoreConfig};
+ use crate::store::{CohortStore, OffloadConfig, OffloadMode, StoreConfig, StoreHandle};
use crate::workers::MergeWorkerDeps;
fn dispatcher() -> (TempDir, Arc<EventDispatcher>) {
@@ -94,12 +94,20 @@ mod tests {
..StoreConfig::default()
})
.unwrap();
+ let handle = StoreHandle::new(
+ store,
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ );
let catalog = Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([])));
let sink: Arc<dyn MembershipSink> = Arc::new(CaptureSink::new());
let dispatcher = EventDispatcher::new(
PartitionRouter::new(64),
Arc::new(OffsetTracker::new()),
- store,
+ handle,
catalog,
sink,
MergeWorkerDeps::capture(),
diff --git a/rust/cohort-stream-processor/src/merge/redrive.rs b/rust/cohort-stream-processor/src/merge/redrive.rs
index 951d6e518622..29d59eff2b89 100644
--- a/rust/cohort-stream-processor/src/merge/redrive.rs
+++ b/rust/cohort-stream-processor/src/merge/redrive.rs
@@ -37,7 +37,7 @@ mod tests {
use crate::filters::{CatalogHandle, FilterCatalog};
use crate::partitions::{OffsetTracker, PartitionRouter};
use crate::producer::{CaptureSink, MembershipSink};
- use crate::store::{CohortStore, StoreConfig};
+ use crate::store::{CohortStore, OffloadConfig, OffloadMode, StoreConfig, StoreHandle};
use crate::workers::MergeWorkerDeps;
fn dispatcher() -> (TempDir, Arc<EventDispatcher>) {
@@ -47,12 +47,20 @@ mod tests {
..StoreConfig::default()
})
.unwrap();
+ let handle = StoreHandle::new(
+ store,
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ );
let catalog = Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([])));
let sink: Arc<dyn MembershipSink> = Arc::new(CaptureSink::new());
let dispatcher = EventDispatcher::new(
PartitionRouter::new(64),
Arc::new(OffsetTracker::new()),
- store,
+ handle,
catalog,
sink,
MergeWorkerDeps::capture(),
diff --git a/rust/cohort-stream-processor/src/merge/tombstone_redirect.rs b/rust/cohort-stream-processor/src/merge/tombstone_redirect.rs
index af9023bbfc92..240145055427 100644
--- a/rust/cohort-stream-processor/src/merge/tombstone_redirect.rs
+++ b/rust/cohort-stream-processor/src/merge/tombstone_redirect.rs
@@ -16,7 +16,7 @@ use crate::filters::TeamId;
use crate::merge::transfer::Tombstone;
use crate::observability::metrics::MERGE_TOMBSTONE_REDIRECTS_TOTAL;
use crate::partitions::partitioner::partition_of;
-use crate::store::{CohortStore, StoreError, TombstoneKey};
+use crate::store::{CohortStore, StoreError, StoreHandle, TombstoneKey};
/// Defensive bound on same-partition tombstone hops in one [`resolve`] call.
const MAX_TOMBSTONE_HOPS: usize = 16;
@@ -90,6 +90,10 @@ pub fn resolve(
}
/// Read and decode one tombstone, or `None` when absent or corrupt.
+// Section-core surface: `resolve` calls this inside drain/apply `run_section` closures, so its direct
+// `get_tombstone` is already off the runtime threads. The async `resolve_offloaded` twin reads through
+// the `StoreHandle` facade, and the crate-wide lint keeps it free of raw `CohortStore` calls.
+#[allow(clippy::disallowed_methods)]
fn read_tombstone(
store: &CohortStore,
partition_id: u16,
@@ -113,6 +117,82 @@ fn read_tombstone(
}
}
+/// Async twin of [`resolve`] over the [`StoreHandle`] facade: identical tombstone walk,
+/// [`Resolution`] semantics, and [`MAX_TOMBSTONE_HOPS`] cap, but each hop reads through the Event
+/// lane so the store I/O runs on the blocking pool. Used by the event-path worker; drain/apply call
+/// the sync [`resolve`] inside their `run_section` closures.
+pub async fn resolve_offloaded(
+ handle: &StoreHandle,
+ partition_id: u16,
+ team_id: TeamId,
+ person: Uuid,
+ partition_count: u32,
+) -> Result<Resolution, StoreError> {
+ let team = team_id.0 as u64;
+
+ let Some(first) = read_tombstone_offloaded(handle, partition_id, team, person).await? else {
+ return Ok(Resolution::NotMerged);
+ };
+
+ let origin = person;
+ let mut current = first.new_person;
+
+ for _hop in 0..MAX_TOMBSTONE_HOPS {
+ let current_partition = partition_of(team_id, &current, partition_count);
+ if current_partition as u16 != partition_id {
+ return Ok(Resolution::CrossPartition {
+ target_person: current,
+ origin,
+ });
+ }
+ match read_tombstone_offloaded(handle, partition_id, team, current).await? {
+ Some(next) => current = next.new_person,
+ None => {
+ return Ok(Resolution::Inline {
+ final_person: current,
+ origin,
+ })
+ }
+ }
+ }
+
+ warn!(
+ partition_id,
+ team_id = team_id.0,
+ %origin,
+ %current,
+ "tombstone chain exceeded the hop cap; resolving inline to the last hop",
+ );
+ Ok(Resolution::Inline {
+ final_person: current,
+ origin,
+ })
+}
+
+/// Read and decode one tombstone through the Event lane, or `None` when absent or corrupt.
+async fn read_tombstone_offloaded(
+ handle: &StoreHandle,
+ partition_id: u16,
+ team: u64,
+ person: Uuid,
+) -> Result<Option<Tombstone>, StoreError> {
+ let key = TombstoneKey {
+ partition_id,
+ team_id: team,
+ person,
+ };
+ let Some(bytes) = handle.get_tombstone(&key).await? else {
+ return Ok(None);
+ };
+ match Tombstone::decode(&bytes) {
+ Ok(tombstone) => Ok(Some(tombstone)),
+ Err(error) => {
+ debug!(partition_id, %person, error = %error, "corrupt tombstone; treating as not merged");
+ Ok(None)
+ }
+ }
+}
+
/// Record an inline redirect metric. Cross-partition redirects are counted separately via
/// [`record_re_keyed`] after the re-produce ack.
pub fn record_redirect(resolution: &Resolution) {
@@ -131,7 +211,9 @@ pub fn record_re_keyed(count: u64) {
}
}
+// Tests seed and read tombstones directly against the store.
#[cfg(test)]
+#[allow(clippy::disallowed_methods)]
mod tests {
use super::*;
use tempfile::TempDir;
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
index 11de97542ea8..3cf28a044145 100644
--- a/rust/cohort-stream-processor/src/observability/metrics.rs
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -121,6 +121,22 @@ 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";
+/// Time an offloaded store op waited to acquire its read-lane permit on the async side, before it
+/// was ever spawned, labelled by `op` (histogram, seconds). Recorded only when the lane is bounded.
+pub const STORE_OFFLOAD_PERMIT_WAIT_DURATION_SECONDS: &str =
+ "store_offload_permit_wait_duration_seconds";
+/// Time from `spawn_blocking` to the offloaded closure actually starting, labelled by `op`
+/// (histogram, seconds) — the blocking-pool queue wait plus spawn overhead.
+pub const STORE_OFFLOAD_QUEUE_WAIT_DURATION_SECONDS: &str =
+ "store_offload_queue_wait_duration_seconds";
+/// Execution time of the offloaded op inside the blocking closure, labelled by `op` (histogram,
+/// seconds) — excludes permit and queue waits, so it is the pure on-thread store cost.
+pub const STORE_OFFLOAD_EXEC_DURATION_SECONDS: &str = "store_offload_exec_duration_seconds";
+/// Store ops currently executing inside a blocking closure, labelled by `lane`
+/// (`event`|`maintenance`|`write`|`section`) (gauge). Maintained inside the closure so it stays
+/// correct even if the caller future is dropped mid-flight.
+pub const STORE_OFFLOAD_INFLIGHT: &str = "store_offload_inflight";
+
/// 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.
@@ -504,6 +520,19 @@ mod tests {
// 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_OFFLOAD_PERMIT_WAIT_DURATION_SECONDS,
+ "store_offload_permit_wait_duration_seconds",
+ );
+ assert_eq!(
+ STORE_OFFLOAD_QUEUE_WAIT_DURATION_SECONDS,
+ "store_offload_queue_wait_duration_seconds",
+ );
+ assert_eq!(
+ STORE_OFFLOAD_EXEC_DURATION_SECONDS,
+ "store_offload_exec_duration_seconds",
+ );
+ assert_eq!(STORE_OFFLOAD_INFLIGHT, "store_offload_inflight");
assert_eq!(STORE_BLOCK_CACHE_HITS_TOTAL, "store_block_cache_hits_total");
assert_eq!(
STORE_BLOCK_CACHE_MISSES_TOTAL,
diff --git a/rust/cohort-stream-processor/src/observability/store_stats.rs b/rust/cohort-stream-processor/src/observability/store_stats.rs
index 97cbf2b8a925..9b9104b05fbc 100644
--- a/rust/cohort-stream-processor/src/observability/store_stats.rs
+++ b/rust/cohort-stream-processor/src/observability/store_stats.rs
@@ -3,6 +3,7 @@
use async_trait::async_trait;
use metrics::{counter, gauge};
+use tracing::debug;
use crate::observability::metrics::{
STORE_BLOCK_CACHE_DATA_HITS_TOTAL, STORE_BLOCK_CACHE_DATA_MISSES_TOTAL,
@@ -12,25 +13,33 @@ use crate::observability::metrics::{
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::store::StoreHandle;
use crate::sweep::Sweeper;
-/// Publishes [`CohortStore::stats_snapshot`] onto metrics once per sweep tick, driven by
-/// [`run_sweep_loop`](crate::sweep::run_sweep_loop).
+/// 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 {
- store: CohortStore,
+ handle: StoreHandle,
}
impl StoreStatsSweeper {
- pub fn new(store: CohortStore) -> Self {
- Self { store }
+ pub fn new(handle: StoreHandle) -> Self {
+ Self { handle }
}
}
#[async_trait]
impl Sweeper for StoreStatsSweeper {
async fn run_once(&self) {
- let stats = self.store.stats_snapshot();
+ let stats = match self.handle.stats_snapshot().await {
+ Ok(stats) => stats,
+ // Only teardown cancellation errors here; the next tick (if any) re-reads.
+ Err(err) => {
+ debug!(error = %err, "store stats snapshot skipped (offload cancelled)");
+ return;
+ }
+ };
// Tickers are cumulative, so publish them verbatim with `absolute`.
for (name, value) in [
diff --git a/rust/cohort-stream-processor/src/partitions/rebalance.rs b/rust/cohort-stream-processor/src/partitions/rebalance.rs
index 864d4b98216a..f3a06a9ec2be 100644
--- a/rust/cohort-stream-processor/src/partitions/rebalance.rs
+++ b/rust/cohort-stream-processor/src/partitions/rebalance.rs
@@ -186,6 +186,9 @@ fn partition_numbers(partitions: &TopicPartitionList) -> Vec<i32> {
}
#[cfg(test)]
+// Tests seed and probe partition slices against `CohortStore` directly while the dispatcher holds
+// the `StoreHandle` facade.
+#[allow(clippy::disallowed_methods)]
mod tests {
use super::*;
use std::sync::Mutex;
@@ -194,7 +197,9 @@ mod tests {
use crate::filters::{CatalogHandle, FilterCatalog};
use crate::partitions::{MarkOutcome, OffsetTracker, PartitionRouter};
use crate::producer::{CaptureSink, MembershipSink};
- use crate::store::{CohortStore, LeafStateKey, Stage1Key, StoreConfig};
+ use crate::store::{
+ CohortStore, LeafStateKey, OffloadConfig, OffloadMode, Stage1Key, StoreConfig, StoreHandle,
+ };
use crate::workers::MergeWorkerDeps;
use uuid::Uuid;
@@ -208,25 +213,40 @@ mod tests {
list
}
- fn test_dispatcher() -> (TempDir, Arc<EventDispatcher>, Arc<OffsetTracker>) {
+ /// Returns the raw store alongside the dispatcher (which wraps a clone of it) so tests can
+ /// seed/probe slices directly; the dispatcher itself only exposes the async facade.
+ fn test_dispatcher() -> (
+ TempDir,
+ Arc<EventDispatcher>,
+ Arc<OffsetTracker>,
+ CohortStore,
+ ) {
let dir = TempDir::new().unwrap();
let store = CohortStore::open(&StoreConfig {
path: dir.path().join("db"),
..StoreConfig::default()
})
.unwrap();
+ let handle = StoreHandle::new(
+ store.clone(),
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ );
let catalog = Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([])));
let sink: Arc<dyn MembershipSink> = Arc::new(CaptureSink::new());
let tracker = Arc::new(OffsetTracker::new());
let dispatcher = EventDispatcher::new(
PartitionRouter::new(64),
tracker.clone(),
- store,
+ handle,
catalog,
sink,
MergeWorkerDeps::capture(),
);
- (dir, Arc::new(dispatcher), tracker)
+ (dir, Arc::new(dispatcher), tracker, store)
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -305,7 +325,7 @@ mod tests {
#[tokio::test]
async fn on_assign_records_ownership_and_queues_an_assign_event() {
- let (_dir, dispatcher, _tracker) = test_dispatcher();
+ let (_dir, dispatcher, _tracker, _store) = test_dispatcher();
let (ctx, mut rx) = CohortConsumerContext::new(dispatcher.clone());
ctx.on_assign(&tpl(&[0, 1, 4]));
@@ -323,7 +343,7 @@ mod tests {
#[tokio::test]
async fn on_revoke_clears_ownership_and_queues_a_revoke_event() {
- let (_dir, dispatcher, _tracker) = test_dispatcher();
+ let (_dir, dispatcher, _tracker, _store) = test_dispatcher();
let (ctx, mut rx) = CohortConsumerContext::new(dispatcher.clone());
ctx.on_assign(&tpl(&[0, 1]));
@@ -343,7 +363,7 @@ mod tests {
#[tokio::test]
async fn empty_callbacks_are_noops_and_queue_nothing() {
- let (_dir, dispatcher, _tracker) = test_dispatcher();
+ let (_dir, dispatcher, _tracker, _store) = test_dispatcher();
let (ctx, mut rx) = CohortConsumerContext::new(dispatcher.clone());
ctx.on_assign(&tpl(&[]));
@@ -358,7 +378,7 @@ mod tests {
#[tokio::test]
async fn assign_event_mirrors_the_followers() {
- let (_dir, dispatcher, tracker) = test_dispatcher();
+ let (_dir, dispatcher, tracker, _store) = test_dispatcher();
let (ctx, rx) = CohortConsumerContext::new(dispatcher.clone());
let mirror = RecordingMirror::new(tracker);
@@ -371,7 +391,7 @@ mod tests {
#[tokio::test]
async fn revoke_unassigns_the_followers_before_the_drain() {
- let (_dir, dispatcher, tracker) = test_dispatcher();
+ let (_dir, dispatcher, tracker, _store) = test_dispatcher();
let (ctx, rx) = CohortConsumerContext::new(dispatcher.clone());
let mirror = RecordingMirror::new(tracker.clone());
@@ -409,28 +429,21 @@ mod tests {
}
}
- fn seed_slice(dispatcher: &EventDispatcher, partition: u16) {
- dispatcher
- .store()
+ fn seed_slice(store: &CohortStore, partition: u16) {
+ store
.write_batch(|b| b.put_stage1(&slice_key(partition), b"state"))
.unwrap();
}
/// Probe whether `partition`'s slice is present without seeding it, so the caller controls seed
/// ordering relative to a boot reconcile.
- fn present_probe(dispatcher: &EventDispatcher, partition: u16) -> impl Fn() -> bool + '_ {
- move || {
- dispatcher
- .store()
- .get_stage1(&slice_key(partition))
- .unwrap()
- .is_some()
- }
+ fn present_probe(store: &CohortStore, partition: u16) -> impl Fn() -> bool + '_ {
+ move || store.get_stage1(&slice_key(partition)).unwrap().is_some()
}
- fn seed_and_present(dispatcher: &EventDispatcher, partition: u16) -> impl Fn() -> bool + '_ {
- seed_slice(dispatcher, partition);
- present_probe(dispatcher, partition)
+ fn seed_and_present(store: &CohortStore, partition: u16) -> impl Fn() -> bool + '_ {
+ seed_slice(store, partition);
+ present_probe(store, partition)
}
#[tokio::test]
@@ -440,14 +453,16 @@ mod tests {
// the eviction-queue rebuild), so the slice survives the assign path until the first event —
// regardless of the durable-restore gate.
for durable_on in [false, true] {
- let (_dir, dispatcher, tracker) = test_dispatcher();
+ let (_dir, dispatcher, tracker, store) = test_dispatcher();
if durable_on {
dispatcher.enable_durable_restore();
}
// Snapshot excludes 3; seeding *after* reconcile keeps the boot wipe from deleting it, so
// only the (now inert) assign path could have wiped it.
- dispatcher.reconcile_boot_assignment(&[0].into_iter().collect(), 64);
- let present = seed_and_present(&dispatcher, 3);
+ dispatcher
+ .reconcile_boot_assignment(&[0].into_iter().collect(), 64)
+ .await;
+ let present = seed_and_present(&store, 3);
let (ctx, rx) = CohortConsumerContext::new(dispatcher.clone());
let mirror = RecordingMirror::new(tracker);
ctx.on_assign(&tpl(&[3]));
@@ -465,13 +480,15 @@ mod tests {
// The pod's own initial assignment routes through the assign path; the restored slices for the
// assigned partitions must survive it (the assign arm never wipes; spawn-time reclaim keeps
// boot-snapshot partitions).
- let (_dir, dispatcher, tracker) = test_dispatcher();
+ let (_dir, dispatcher, tracker, store) = test_dispatcher();
dispatcher.enable_durable_restore();
- seed_slice(&dispatcher, 0);
- seed_slice(&dispatcher, 1);
- let present_0 = present_probe(&dispatcher, 0);
- let present_1 = present_probe(&dispatcher, 1);
- dispatcher.reconcile_boot_assignment(&[0, 1].into_iter().collect(), 64);
+ seed_slice(&store, 0);
+ seed_slice(&store, 1);
+ let present_0 = present_probe(&store, 0);
+ let present_1 = present_probe(&store, 1);
+ dispatcher
+ .reconcile_boot_assignment(&[0, 1].into_iter().collect(), 64)
+ .await;
let (ctx, rx) = CohortConsumerContext::new(dispatcher.clone());
let mirror = RecordingMirror::new(tracker);
@@ -487,12 +504,12 @@ mod tests {
// The rebalance worker can process the initial Assign before the consume loop records the
// snapshot; the assign path never wipes, so the slices survive until they are either reopened
// live or reclaimed at spawn time.
- let (_dir, dispatcher, tracker) = test_dispatcher();
+ let (_dir, dispatcher, tracker, store) = test_dispatcher();
dispatcher.enable_durable_restore();
- seed_slice(&dispatcher, 0);
- seed_slice(&dispatcher, 1);
- let present_0 = present_probe(&dispatcher, 0);
- let present_1 = present_probe(&dispatcher, 1);
+ seed_slice(&store, 0);
+ seed_slice(&store, 1);
+ let present_0 = present_probe(&store, 0);
+ let present_1 = present_probe(&store, 1);
let (ctx, rx) = CohortConsumerContext::new(dispatcher.clone());
let mirror = RecordingMirror::new(tracker);
@@ -508,7 +525,7 @@ mod tests {
#[tokio::test]
async fn rapid_revoke_assign_mirrors_both_calls_unconditionally() {
- let (_dir, dispatcher, tracker) = test_dispatcher();
+ let (_dir, dispatcher, tracker, _store) = test_dispatcher();
let (ctx, rx) = CohortConsumerContext::new(dispatcher.clone());
let mirror = RecordingMirror::new(tracker.clone());
diff --git a/rust/cohort-stream-processor/src/store/durability/checkpoint.rs b/rust/cohort-stream-processor/src/store/durability/checkpoint.rs
index 88a83c378345..5ff6887389cd 100644
--- a/rust/cohort-stream-processor/src/store/durability/checkpoint.rs
+++ b/rust/cohort-stream-processor/src/store/durability/checkpoint.rs
@@ -18,6 +18,11 @@
//! checkpoints). Every fallible step is handled, the failure is logged and counted, and the loop
//! continues.
+// The checkpoint sweeper offloads its own store I/O (its own `spawn_blocking` + log-and-skip on
+// every `JoinError`) to honor the must-not-panic policy above, so its direct `CohortStore` calls are
+// sanctioned. See `checkpoint_once`.
+#![allow(clippy::disallowed_methods)]
+
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
@@ -109,6 +114,10 @@ impl CheckpointSweeper {
async fn checkpoint_once(&self) {
let tick = self.tick.fetch_add(1, Ordering::SeqCst);
+ // The checkpoint sweeper runs its own `spawn_blocking` and catches every `JoinError` to
+ // log-and-skip: the `Sweeper` contract forbids panicking (a panic aborts the timer task and
+ // stops all future checkpoints), so store panics must not propagate out of this loop.
+ //
// 1. fsync the WAL before the snapshot so `committed <= durable` holds. A failure here would
// yield a checkpoint whose manifest claims more than is durable — skip the tick.
let flush_store = self.store.clone();
diff --git a/rust/cohort-stream-processor/src/store/handle.rs b/rust/cohort-stream-processor/src/store/handle.rs
new file mode 100644
index 000000000000..5361e9b80f6f
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/handle.rs
@@ -0,0 +1,697 @@
+//! Async facade over [`CohortStore`]: the only store surface async production code sees.
+//!
+//! Synchronous RocksDB I/O blocks the thread that issues it. On the runtime's worker threads that
+//! is fatal to throughput — a thread parked in a read is a core that computes nothing. This facade
+//! moves store I/O onto Tokio's blocking pool via `spawn_blocking`, so the runtime worker threads
+//! stay CPU-only (HogVM eval, serde, plumbing) while store I/O runs elsewhere with bounded,
+//! observable concurrency.
+//!
+//! Bounding is two independent permit lanes ([`ReadLane`]): a maintenance storm (tz-midnight sweep
+//! waves, boot rebuild scans, GC) draws only on the maintenance lane and cannot starve event-path
+//! reads through a single shared FIFO pool. Writes take no permit — the commit cadence must never
+//! queue behind reads.
+//!
+//! [`CohortStore`] (sync) stays the surface for blocking contexts that cannot `.await`: whole-section
+//! state machines run through [`StoreHandle::run_section`], and checkpoint/tests call it directly.
+
+// This module is the sanctioned wrapper: every async method funnels one direct `CohortStore` I/O
+// call onto the blocking pool, so the lint must not fire on the wrapper itself.
+#![allow(clippy::disallowed_methods)]
+
+use std::str::FromStr;
+use std::sync::Arc;
+use std::time::Instant;
+
+use metrics::{gauge, histogram};
+use tokio::sync::{OwnedSemaphorePermit, Semaphore};
+use tokio::task::JoinError;
+
+use super::keys::{PendingTransferKey, PersonIndexKey, Stage2Key, TombstoneKey};
+use super::rocks::{CohortStore, StoreError, StoreStats};
+use super::staged::StagedBatch;
+use crate::observability::metrics::{
+ STORE_OFFLOAD_EXEC_DURATION_SECONDS, STORE_OFFLOAD_INFLIGHT,
+ STORE_OFFLOAD_PERMIT_WAIT_DURATION_SECONDS, STORE_OFFLOAD_QUEUE_WAIT_DURATION_SECONDS,
+};
+use crate::stage1::key::{LeafStateKey, Stage1Key};
+
+const LANE_EVENT: &str = "event";
+const LANE_MAINTENANCE: &str = "maintenance";
+const LANE_WRITE: &str = "write";
+const LANE_SECTION: &str = "section";
+
+/// Where each store op runs — one env knob (`COHORT_STORE_OFFLOAD_MODE`) with three operating points.
+///
+/// The mode is matched only inside the facade's private executors, never at call sites, so switching
+/// it re-routes every op at once.
+#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
+pub enum OffloadMode {
+ /// Every op runs inline on the caller's thread. The operator kill switch.
+ Off,
+ /// Maintenance-lane reads, `flush_wal_sync`, `run_section`, and `stats_snapshot` offload;
+ /// Event-lane reads and every other write run inline. Keeps the event path off the blocking pool
+ /// while still isolating maintenance storms and the fsync syscall.
+ Maintenance,
+ /// Every op offloads. The default operating point.
+ #[default]
+ All,
+}
+
+impl FromStr for OffloadMode {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s.to_ascii_lowercase().as_str() {
+ "off" => Ok(Self::Off),
+ "maintenance" => Ok(Self::Maintenance),
+ "all" => Ok(Self::All),
+ other => Err(format!(
+ "invalid COHORT_STORE_OFFLOAD_MODE {other:?}: expected \"off\", \"maintenance\", or \"all\""
+ )),
+ }
+ }
+}
+
+/// The two independent permit lanes. Separating them keeps a maintenance storm from starving
+/// event-path reads through one FIFO pool.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum ReadLane {
+ /// Event-path reads on the hot path (event fold pre-read, stage-2 compose, tombstone redirect).
+ Event,
+ /// Bulk/background reads (sweep prefetch, boot rebuild scans, GC/redrive scans).
+ Maintenance,
+}
+
+impl ReadLane {
+ /// The `lane` label value for the in-flight gauge.
+ fn label(self) -> &'static str {
+ match self {
+ ReadLane::Event => LANE_EVENT,
+ ReadLane::Maintenance => LANE_MAINTENANCE,
+ }
+ }
+}
+
+/// Resolved offload settings. `0` permits disables the bound on that lane (no semaphore).
+#[derive(Clone, Copy, Debug)]
+pub struct OffloadConfig {
+ pub mode: OffloadMode,
+ pub event_read_permits: usize,
+ pub maintenance_permits: usize,
+}
+
+/// The async store surface handed to production code. Cheap to clone: the inner [`CohortStore`] is
+/// `Arc`-backed and the permit lanes are shared `Arc<Semaphore>`s.
+#[derive(Clone)]
+pub struct StoreHandle {
+ store: CohortStore,
+ mode: OffloadMode,
+ /// `None` = the lane is unbounded (no permit acquired).
+ event_permits: Option<Arc<Semaphore>>,
+ maintenance_permits: Option<Arc<Semaphore>>,
+}
+
+impl StoreHandle {
+ pub fn new(store: CohortStore, config: OffloadConfig) -> Self {
+ // `0` = unbounded: model it as the absence of a semaphore so the offload path skips permit
+ // acquisition entirely.
+ let lane = |permits: usize| (permits > 0).then(|| Arc::new(Semaphore::new(permits)));
+ Self {
+ store,
+ mode: config.mode,
+ event_permits: lane(config.event_read_permits),
+ maintenance_permits: lane(config.maintenance_permits),
+ }
+ }
+
+ fn lane_permits(&self, lane: ReadLane) -> Option<&Arc<Semaphore>> {
+ match lane {
+ ReadLane::Event => self.event_permits.as_ref(),
+ ReadLane::Maintenance => self.maintenance_permits.as_ref(),
+ }
+ }
+
+ /// Whether a read on `lane` runs inline under the current mode. Off is always inline; under
+ /// Maintenance only the Event lane is inline (maintenance offloads); under All nothing is inline.
+ fn read_runs_inline(&self, lane: ReadLane) -> bool {
+ match self.mode {
+ OffloadMode::Off => true,
+ OffloadMode::Maintenance => matches!(lane, ReadLane::Event),
+ OffloadMode::All => false,
+ }
+ }
+
+ // --- Internal executors: the only places `mode` is matched. ---
+
+ /// Run a read op, offloading per mode + lane. Inline runs record no offload metrics, so Off adds
+ /// no measurement overhead; the rocks-level metrics inside `CohortStore` fire on both paths.
+ async fn read<T, F>(&self, op: &'static str, lane: ReadLane, f: F) -> Result<T, StoreError>
+ where
+ T: Send + 'static,
+ F: FnOnce(&CohortStore) -> Result<T, StoreError> + Send + 'static,
+ {
+ if self.read_runs_inline(lane) {
+ return f(&self.store);
+ }
+ self.offload(op, lane.label(), self.lane_permits(lane).cloned(), f)
+ .await
+ }
+
+ /// Run a write op. Writes take no permit. Under Maintenance every write runs inline *except*
+ /// `flush_wal_sync` (`is_fsync`): the fsync is the expensive syscall, memtable writes are cheap,
+ /// so the fsync offloads while ordinary commits stay on the caller's thread. Under Off all
+ /// inline, under All all offloaded.
+ async fn write<T, F>(&self, op: &'static str, is_fsync: bool, f: F) -> Result<T, StoreError>
+ where
+ T: Send + 'static,
+ F: FnOnce(&CohortStore) -> Result<T, StoreError> + Send + 'static,
+ {
+ let inline = match self.mode {
+ OffloadMode::Off => true,
+ OffloadMode::Maintenance => !is_fsync,
+ OffloadMode::All => false,
+ };
+ if inline {
+ return f(&self.store);
+ }
+ self.offload(op, LANE_WRITE, None, f).await
+ }
+
+ /// Run a whole infallible sync section (reads + writes mixed) under the [`LANE_SECTION`] label:
+ /// offloads under Maintenance and All, inline under Off. `permits` is the lane the section draws
+ /// from — the maintenance lane for [`Self::run_section`], `None` for the permit-free
+ /// observability snapshot ([`Self::stats_snapshot`]). Keeping stats on this executor is what lets
+ /// `mode` stay matched in exactly the three executors (`read`, `write`, `section`).
+ async fn section<T, F>(
+ &self,
+ op: &'static str,
+ permits: Option<Arc<Semaphore>>,
+ f: F,
+ ) -> Result<T, StoreError>
+ where
+ T: Send + 'static,
+ F: FnOnce(&CohortStore) -> T + Send + 'static,
+ {
+ if matches!(self.mode, OffloadMode::Off) {
+ return Ok(f(&self.store));
+ }
+ // A section's closure is infallible (it returns `T`, not `Result`); wrap it so it shares the
+ // one offload path. Only teardown cancellation can then make the outer result an `Err`.
+ self.offload(op, LANE_SECTION, permits, move |store| Ok(f(store)))
+ .await
+ }
+
+ /// The single offload path. Acquires the lane permit on the async side (cancellable), then moves
+ /// it into the blocking closure so its hold time is exactly the op's execution — never spanning
+ /// the post-spawn wake, which would couple hold time to runtime saturation.
+ async fn offload<T, F>(
+ &self,
+ op: &'static str,
+ lane_label: &'static str,
+ permits: Option<Arc<Semaphore>>,
+ f: F,
+ ) -> Result<T, StoreError>
+ where
+ T: Send + 'static,
+ F: FnOnce(&CohortStore) -> Result<T, StoreError> + Send + 'static,
+ {
+ // Acquire the lane permit before spawning. We never close these semaphores, so the only
+ // error variant (`AcquireError` from a closed semaphore) is unreachable.
+ let permit: Option<OwnedSemaphorePermit> = match permits {
+ Some(semaphore) => {
+ let started = Instant::now();
+ let permit = semaphore
+ .acquire_owned()
+ .await
+ .expect("store offload semaphore is never closed");
+ histogram!(STORE_OFFLOAD_PERMIT_WAIT_DURATION_SECONDS, "op" => op)
+ .record(started.elapsed().as_secs_f64());
+ Some(permit)
+ }
+ None => None,
+ };
+
+ let store = self.store.clone();
+ let spawned_at = Instant::now();
+ let join = tokio::task::spawn_blocking(move || {
+ // First thing on the blocking thread: the spawn→start gap is the pool-queue wait.
+ histogram!(STORE_OFFLOAD_QUEUE_WAIT_DURATION_SECONDS, "op" => op)
+ .record(spawned_at.elapsed().as_secs_f64());
+
+ // The in-flight gauge is maintained here, inside the closure, so it stays balanced even
+ // if the caller future is dropped: the increment and its RAII decrement both live on the
+ // blocking thread, which always runs to completion.
+ let _inflight = InflightGuard::enter(lane_label);
+
+ let exec_started = Instant::now();
+ let result = f(&store);
+ histogram!(STORE_OFFLOAD_EXEC_DURATION_SECONDS, "op" => op)
+ .record(exec_started.elapsed().as_secs_f64());
+
+ // Drop the permit here at the end of execution — moved in, released on this thread, so it
+ // is held for exactly the op, never into the caller's post-await continuation.
+ drop(permit);
+ result
+ })
+ .await;
+
+ unwrap_offload(join)?
+ }
+
+ // --- Public async surface. Each method wraps exactly one sync `CohortStore` method. ---
+
+ /// Point-read one `cf_stage1` value. Lane-parameterized: the event fold reads on
+ /// [`ReadLane::Event`], background scans/prefetch on [`ReadLane::Maintenance`].
+ pub async fn get_stage1(
+ &self,
+ key: &Stage1Key,
+ lane: ReadLane,
+ ) -> Result<Option<Vec<u8>>, StoreError> {
+ let key = *key;
+ self.read("get_stage1", lane, move |store| store.get_stage1(&key))
+ .await
+ }
+
+ /// Batch-read `cf_stage1` values, preserving input order. Lane-parameterized (event fold =
+ /// Event, sweep prefetch = Maintenance). Keys are taken by value so the closure is trivially
+ /// `'static`.
+ pub async fn multi_get_stage1(
+ &self,
+ keys: Vec<Stage1Key>,
+ lane: ReadLane,
+ ) -> Result<Vec<Option<Vec<u8>>>, StoreError> {
+ self.read("multi_get_stage1", lane, move |store| {
+ store.multi_get_stage1(&keys)
+ })
+ .await
+ }
+
+ /// Point-read one `cf_stage2` value (stage-2 compose is an event-path read).
+ pub async fn get_stage2(&self, key: &Stage2Key) -> Result<Option<Vec<u8>>, StoreError> {
+ let key = *key;
+ self.read("get_stage2", ReadLane::Event, move |store| {
+ store.get_stage2(&key)
+ })
+ .await
+ }
+
+ /// Batch-read `cf_stage2` values, preserving input order (stage-2 compose, event path).
+ pub async fn multi_get_stage2(
+ &self,
+ keys: Vec<Stage2Key>,
+ ) -> Result<Vec<Option<Vec<u8>>>, StoreError> {
+ self.read("multi_get_stage2", ReadLane::Event, move |store| {
+ store.multi_get_stage2(&keys)
+ })
+ .await
+ }
+
+ /// Point-read one redirect tombstone (the tombstone-redirect hop is an event-path read).
+ pub async fn get_tombstone(&self, key: &TombstoneKey) -> Result<Option<Vec<u8>>, StoreError> {
+ let key = *key;
+ self.read("get_tombstone", ReadLane::Event, move |store| {
+ store.get_tombstone(&key)
+ })
+ .await
+ }
+
+ /// Point-read one person-index entry (maintenance/merge path).
+ pub async fn get_person_index(
+ &self,
+ key: &PersonIndexKey,
+ ) -> Result<Vec<LeafStateKey>, StoreError> {
+ let key = *key;
+ self.read("get_person_index", ReadLane::Maintenance, move |store| {
+ store.get_person_index(&key)
+ })
+ .await
+ }
+
+ /// Point-read one pending-transfer outbox slot (maintenance/merge path).
+ pub async fn get_pending_transfer(
+ &self,
+ key: &PendingTransferKey,
+ ) -> Result<Option<Vec<u8>>, StoreError> {
+ let key = *key;
+ self.read(
+ "get_pending_transfer",
+ ReadLane::Maintenance,
+ move |store| store.get_pending_transfer(&key),
+ )
+ .await
+ }
+
+ /// Scan a page of one partition's `cf_stage1` slice (boot rebuild, maintenance lane).
+ pub async fn scan_stage1(
+ &self,
+ partition_id: u16,
+ start_after: Option<Vec<u8>>,
+ limit: usize,
+ ) -> Result<Vec<(Stage1Key, Vec<u8>)>, StoreError> {
+ self.read("scan_stage1", ReadLane::Maintenance, move |store| {
+ store.scan_stage1(partition_id, start_after.as_deref(), limit)
+ })
+ .await
+ }
+
+ /// Scan a page of one partition's `cf_pending_transfers` slice (redrive, maintenance lane).
+ pub async fn scan_pending_transfers(
+ &self,
+ partition_id: u16,
+ start_after: Option<Vec<u8>>,
+ limit: usize,
+ ) -> Result<Vec<(PendingTransferKey, Vec<u8>)>, StoreError> {
+ self.read(
+ "scan_pending_transfers",
+ ReadLane::Maintenance,
+ move |store| store.scan_pending_transfers(partition_id, start_after.as_deref(), limit),
+ )
+ .await
+ }
+
+ /// Commit an owned [`StagedBatch`] atomically. Consumes the batch, moving it into the closure.
+ /// No permit — the commit cadence must never queue behind reads.
+ pub async fn commit(&self, staged: StagedBatch) -> Result<(), StoreError> {
+ self.write("commit", false, move |store| store.apply(&staged))
+ .await
+ }
+
+ /// Clear one pending-transfer outbox slot once its transfer is acked. No permit.
+ pub async fn clear_pending_transfer(&self, key: &PendingTransferKey) -> Result<(), StoreError> {
+ let key = *key;
+ self.write("clear_pending_transfer", false, move |store| {
+ store.clear_pending_transfer(&key)
+ })
+ .await
+ }
+
+ /// Reclaim all state for one partition on rebalance. No permit.
+ pub async fn delete_partition(&self, partition_id: u16) -> Result<(), StoreError> {
+ self.write("delete_partition", false, move |store| {
+ store.delete_partition(partition_id)
+ })
+ .await
+ }
+
+ /// Synchronously fsync the WAL, making every write so far durable. No permit — the commit cadence
+ /// must not queue behind reads. Under Maintenance this offloads (the fsync is the expensive
+ /// syscall) even though ordinary writes run inline.
+ pub async fn flush_wal_sync(&self) -> Result<(), StoreError> {
+ self.write("flush_wal_sync", true, |store| store.flush_wal_sync())
+ .await
+ }
+
+ /// Run a self-contained sync store state machine (mixed reads and writes) on the blocking pool:
+ /// the sanctioned context for merge drain/apply and GC, whose deep sync cores are not worth
+ /// async-ifying. Draws a maintenance permit. The result is `Err` only on runtime-teardown
+ /// cancellation ([`StoreError::OffloadCancelled`]).
+ ///
+ /// Keep each section individually short: a started blocking task cannot be cancelled, and
+ /// shutdown joins started tasks — a long section extends the effective drain time.
+ pub async fn run_section<T, F>(&self, op: &'static str, f: F) -> Result<T, StoreError>
+ where
+ T: Send + 'static,
+ F: FnOnce(&CohortStore) -> T + Send + 'static,
+ {
+ self.section(op, self.maintenance_permits.clone(), f).await
+ }
+
+ /// Snapshot the store's cache tickers and per-CF sizes. No permit — observability must not queue
+ /// behind a permit-starved maintenance lane, which is exactly when the stats matter most. Offloads
+ /// under Maintenance and All (it reads many RocksDB properties, so keep it off the runtime
+ /// threads); only teardown cancellation can `Err`.
+ pub async fn stats_snapshot(&self) -> Result<StoreStats, StoreError> {
+ // Routed through `section` with the `None` lane (no permit) so the mode match stays in the
+ // three executors rather than being open-coded here.
+ self.section("stats_snapshot", None, |store| store.stats_snapshot())
+ .await
+ }
+
+ /// SYNCHRONOUS escape hatch: delete one partition's state on the caller's thread, bypassing the
+ /// offload path entirely.
+ ///
+ /// The single sanctioned caller is `EventDispatcher::reclaim_stale_slice`, which runs under a
+ /// DashMap shard guard where no `.await` is possible. It is rare (a post-boot partition move-in)
+ /// and fast (one range tombstone per CF). Any new caller must justify the same no-await
+ /// constraint — prefer the async [`Self::delete_partition`] everywhere else.
+ pub fn delete_partition_blocking(&self, partition_id: u16) -> Result<(), StoreError> {
+ self.store.delete_partition(partition_id)
+ }
+}
+
+/// RAII in-flight gauge guard, incremented on construction and decremented on drop, both on the
+/// blocking thread. Kept inside the offload closure so the gauge is balanced regardless of the
+/// caller future's fate.
+struct InflightGuard {
+ lane: &'static str,
+}
+
+impl InflightGuard {
+ fn enter(lane: &'static str) -> Self {
+ gauge!(STORE_OFFLOAD_INFLIGHT, "lane" => lane).increment(1.0);
+ Self { lane }
+ }
+}
+
+impl Drop for InflightGuard {
+ fn drop(&mut self) {
+ gauge!(STORE_OFFLOAD_INFLIGHT, "lane" => self.lane).decrement(1.0);
+ }
+}
+
+/// Map a `spawn_blocking` join result into a store result. A pure seam so the panic/cancel policy is
+/// unit-testable.
+///
+/// - Panic → resume the unwind on the caller's thread: a store panic must still kill the calling
+/// worker task (partition stall → lag alert). Never swallowed.
+/// - Cancellation → [`StoreError::OffloadCancelled`]: reachable only at runtime teardown, when the
+/// runtime cancels queued blocking tasks. Mapping it to an error (not a panic) avoids fake panic
+/// telemetry during a clean shutdown.
+fn unwrap_offload<T>(result: Result<T, JoinError>) -> Result<T, StoreError> {
+ match result {
+ Ok(value) => Ok(value),
+ Err(err) if err.is_panic() => std::panic::resume_unwind(err.into_panic()),
+ Err(err) if err.is_cancelled() => Err(StoreError::OffloadCancelled),
+ Err(_) => unreachable!("a spawn_blocking JoinError is either a panic or a cancellation"),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::mpsc;
+ use std::thread::ThreadId;
+ use std::time::Duration;
+
+ use tempfile::TempDir;
+
+ use super::*;
+ use crate::store::rocks::StoreConfig;
+
+ fn open_store(dir: &TempDir) -> CohortStore {
+ CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap()
+ }
+
+ fn handle(store: CohortStore, mode: OffloadMode, permits: usize) -> StoreHandle {
+ StoreHandle::new(
+ store,
+ OffloadConfig {
+ mode,
+ event_read_permits: permits,
+ maintenance_permits: permits,
+ },
+ )
+ }
+
+ /// A single permit must serialize two concurrently-offloaded ops: the second closure must not
+ /// enter while the first holds the permit, and must proceed once the first releases it. Catches a
+ /// permit acquired *after* the spawn, or dropped before the op finishes — either would let the
+ /// second op run concurrently.
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn read_permits_bound_in_flight_ops() {
+ let dir = TempDir::new().unwrap();
+ let handle = handle(open_store(&dir), OffloadMode::All, 1);
+
+ // First op: signal entry, then block until released.
+ let (first_entered_tx, first_entered_rx) = mpsc::channel::<()>();
+ let (release_first_tx, release_first_rx) = mpsc::channel::<()>();
+ let h1 = handle.clone();
+ let first = tokio::spawn(async move {
+ h1.read("probe", ReadLane::Event, move |_store| {
+ first_entered_tx.send(()).unwrap();
+ // Hold the permit until the test releases us.
+ release_first_rx.recv().unwrap();
+ Ok::<_, StoreError>(())
+ })
+ .await
+ .unwrap();
+ });
+
+ // Wait until the first op is actually inside its closure (holding the permit).
+ first_entered_rx
+ .recv_timeout(Duration::from_secs(5))
+ .unwrap();
+
+ // Second op: signal entry. It should be blocked on the permit and never enter yet.
+ let (second_entered_tx, second_entered_rx) = mpsc::channel::<()>();
+ let h2 = handle.clone();
+ let second = tokio::spawn(async move {
+ h2.read("probe", ReadLane::Event, move |_store| {
+ second_entered_tx.send(()).unwrap();
+ Ok::<_, StoreError>(())
+ })
+ .await
+ .unwrap();
+ });
+
+ assert!(
+ second_entered_rx
+ .recv_timeout(Duration::from_millis(300))
+ .is_err(),
+ "second op entered while the first held the only permit",
+ );
+
+ // Release the first; now the second must acquire the permit and enter.
+ release_first_tx.send(()).unwrap();
+ second_entered_rx
+ .recv_timeout(Duration::from_secs(5))
+ .expect("second op did not enter after the first released the permit");
+
+ first.await.unwrap();
+ second.await.unwrap();
+ }
+
+ /// A panic inside an offloaded op must resume-unwind on the caller, so the calling task's
+ /// `JoinError` reports a panic. Catches panic-swallowing — a worker that keeps running on
+ /// corrupted store invariants instead of dying.
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn offload_panic_resumes_unwind_in_the_caller() {
+ let dir = TempDir::new().unwrap();
+ let handle = handle(open_store(&dir), OffloadMode::All, 1);
+
+ // `run_section` draws the maintenance permit; keep a clone of the semaphore so we can confirm
+ // the permit is returned after the panic — a leak would let one store panic permanently
+ // starve the lane.
+ let maintenance = handle.maintenance_permits.clone().unwrap();
+ assert_eq!(maintenance.available_permits(), 1);
+
+ let task = tokio::spawn(async move {
+ handle
+ .run_section::<(), _>("boom", |_store| panic!("store invariant violated"))
+ .await
+ });
+
+ let join_err = task
+ .await
+ .expect_err("the panic must cross the offload boundary");
+ assert!(
+ join_err.is_panic(),
+ "the calling task's JoinError must be a panic, not a swallowed error",
+ );
+ assert_eq!(
+ maintenance.available_permits(),
+ 1,
+ "the permit the panicking section held must drop back to the lane as the closure unwinds",
+ );
+ }
+
+ /// `unwrap_offload` maps a cancelled join to [`StoreError::OffloadCancelled`] and re-raises a
+ /// panic join. Catches a cancel misclassified as Ok or as a panic (either would corrupt shutdown
+ /// telemetry or hide a real store panic).
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn cancelled_offload_maps_to_offload_cancelled() {
+ // A cancelled JoinError: spawn a task that never finishes, abort it, await its handle.
+ let never = tokio::spawn(async {
+ std::future::pending::<()>().await;
+ });
+ never.abort();
+ let cancelled = never.await;
+ assert!(
+ matches!(unwrap_offload(cancelled), Err(StoreError::OffloadCancelled)),
+ "a cancelled join must map to OffloadCancelled",
+ );
+
+ // A panic JoinError: `unwrap_offload` must resume the unwind. Catch it so the test survives.
+ let panicked = tokio::spawn(async { panic!("boom") }).await;
+ let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ drop(unwrap_offload::<()>(panicked));
+ }));
+ assert!(
+ unwound.is_err(),
+ "a panic join must resume the unwind, not return an Err or Ok",
+ );
+ }
+
+ /// In Off mode an op runs on the caller's thread and acquires no permit, even when permits are
+ /// configured. Catches an Off mode that still offloads or takes a permit.
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn off_mode_runs_on_the_caller_thread_without_permits() {
+ let dir = TempDir::new().unwrap();
+ let handle = handle(open_store(&dir), OffloadMode::Off, 1);
+ let caller_thread = std::thread::current().id();
+
+ // Snapshot permits before: 1 configured on each lane.
+ let event_before = handle.event_permits.as_ref().unwrap().available_permits();
+ let maint_before = handle
+ .maintenance_permits
+ .as_ref()
+ .unwrap()
+ .available_permits();
+ assert_eq!(event_before, 1);
+ assert_eq!(maint_before, 1);
+
+ let ran_on: ThreadId = handle
+ .read("probe", ReadLane::Event, |_store| {
+ Ok::<_, StoreError>(std::thread::current().id())
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(
+ ran_on, caller_thread,
+ "Off mode must run the op inline on the caller's thread, not spawn_blocking",
+ );
+ // Neither lane's permit count moved: Off never acquires.
+ assert_eq!(
+ handle.event_permits.as_ref().unwrap().available_permits(),
+ 1,
+ "Off mode must not acquire an event-lane permit",
+ );
+ assert_eq!(
+ handle
+ .maintenance_permits
+ .as_ref()
+ .unwrap()
+ .available_permits(),
+ 1,
+ "Off mode must not acquire a maintenance-lane permit",
+ );
+ }
+
+ #[test]
+ fn offload_mode_parses_case_insensitively_and_rejects_junk() {
+ assert_eq!("off".parse::<OffloadMode>().unwrap(), OffloadMode::Off);
+ assert_eq!("ALL".parse::<OffloadMode>().unwrap(), OffloadMode::All);
+ assert_eq!(
+ "Maintenance".parse::<OffloadMode>().unwrap(),
+ OffloadMode::Maintenance,
+ );
+ assert!("sometimes".parse::<OffloadMode>().is_err());
+ }
+
+ #[test]
+ fn offload_mode_default_is_all() {
+ assert_eq!(OffloadMode::default(), OffloadMode::All);
+ }
+
+ // The handle is cloned into every worker task and shared across the consume/commit loops: a
+ // non-Send member must fail here, not at the distant spawn sites.
+ #[test]
+ fn store_handle_is_send_and_sync() {
+ fn assert_send_sync<T: Send + Sync>() {}
+ assert_send_sync::<StoreHandle>();
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/mod.rs b/rust/cohort-stream-processor/src/store/mod.rs
index f0709270a5a0..0a26580534fa 100644
--- a/rust/cohort-stream-processor/src/store/mod.rs
+++ b/rust/cohort-stream-processor/src/store/mod.rs
@@ -2,18 +2,22 @@
pub mod column_families;
pub mod durability;
+pub mod handle;
pub mod keys;
pub mod rocks;
pub mod secondary_index;
+pub mod staged;
pub use column_families::{
Cf, OpaqueCf, CF_MERGE_APPLIED, CF_MERGE_DRAINS_APPLIED, CF_MERGE_TOMBSTONES,
CF_PENDING_TRANSFERS, CF_PERSON_INDEX, CF_STAGE1, CF_STAGE2,
};
+pub use handle::{OffloadConfig, OffloadMode, ReadLane, StoreHandle};
pub use keys::{
MergeAppliedKey, MergeDrainKey, PendingTransferKey, PersonIndexKey, Stage2Key, TombstoneKey,
};
pub use rocks::{BatchBuilder, CfStats, CohortStore, StoreConfig, StoreError, StoreStats};
pub use secondary_index::{decode_person_index, IndexOp, PERSON_INDEX_MERGE_OPERATOR_NAME};
+pub use staged::StagedBatch;
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 bb47dbef3eac..8fcaa8aabfcf 100644
--- a/rust/cohort-stream-processor/src/store/rocks.rs
+++ b/rust/cohort-stream-processor/src/store/rocks.rs
@@ -1,5 +1,10 @@
//! RocksDB wrapper: multi-CF atomic `WriteBatch`, async WAL.
+// This module defines the disallowed `CohortStore` I/O methods, which call one another internally
+// (e.g. `apply` replays through the `write_batch` path). The lint targets async callers, not the
+// store's own implementation.
+#![allow(clippy::disallowed_methods)]
+
use std::cell::Cell;
use std::path::{Path, PathBuf};
use std::sync::Arc;
@@ -20,6 +25,7 @@ use super::keys::{
TombstoneKey,
};
use super::secondary_index::{decode_person_index, IndexOp};
+use super::staged::{StagedBatch, StagedOp};
use crate::observability::metrics::{
CHECKPOINT_DURATION_SECONDS, STORE_ERRORS_TOTAL, STORE_READS_TOTAL,
STORE_READ_DURATION_SECONDS, STORE_WRITE_BATCH_TOTAL, STORE_WRITE_DURATION_SECONDS,
@@ -127,12 +133,22 @@ pub enum StoreError {
expected: usize,
actual: usize,
},
+
+ #[error("store offload cancelled by runtime shutdown")]
+ OffloadCancelled,
}
/// One scanned key/value pair as raw bytes — the merge-CF GC decodes each per CF.
pub type RawKv = (Vec<u8>, Vec<u8>);
/// Handle to the per-process state store.
+///
+/// Writes have two layers. The closure-based [`Self::write_batch`] is for synchronous callers that
+/// can borrow the store's CF handles for the duration of the call — it stages through a
+/// [`BatchBuilder`] whose handles are tied to `&self`. [`StagedBatch`] plus [`Self::apply`] is the
+/// owned staging path: keys and operands are encoded into owned bytes up front, so the batch is
+/// `Send + 'static` and can be built on one thread and applied on another. Both funnel through the
+/// same commit, so the two produce identical RocksDB writes.
#[derive(Clone)]
pub struct CohortStore {
db: Arc<DBWithThreadMode<SingleThreaded>>,
@@ -290,6 +306,29 @@ impl CohortStore {
self.commit(builder.batch, OP_WRITE_BATCH)
}
+ /// Replay an owned [`StagedBatch`] into one atomic `WriteBatch`, in staging order, and commit it.
+ ///
+ /// This is the owned counterpart to [`Self::write_batch`]: the same operations staged either way
+ /// produce identical writes. It goes through the same commit funnel with the same op label, so
+ /// metrics do not distinguish the two paths.
+ pub fn apply(&self, staged: &StagedBatch) -> Result<(), StoreError> {
+ let mut batch = WriteBatch::default();
+ for op in staged.ops() {
+ match op {
+ StagedOp::Put { cf, key, value } => {
+ batch.put_cf(self.cf(*cf)?, key, value);
+ }
+ StagedOp::Delete { cf, key } => {
+ batch.delete_cf(self.cf(*cf)?, key);
+ }
+ StagedOp::Merge { cf, key, operand } => {
+ batch.merge_cf(self.cf(*cf)?, key, operand);
+ }
+ }
+ }
+ self.commit(batch, OP_WRITE_BATCH)
+ }
+
pub fn get_merge_drain_applied(
&self,
key: &MergeDrainKey,
diff --git a/rust/cohort-stream-processor/src/store/staged.rs b/rust/cohort-stream-processor/src/store/staged.rs
new file mode 100644
index 000000000000..4f92f2a7ebe3
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/staged.rs
@@ -0,0 +1,434 @@
+//! Owned, `Send`-able write staging that can cross a `spawn_blocking` boundary.
+//!
+//! [`BatchBuilder`](super::rocks::BatchBuilder) borrows the store's CF handles, so a batch built
+//! through it is tied to the store's lifetime and cannot be moved into a `'static` blocking closure.
+//! [`StagedBatch`] is the owned counterpart: each staging call encodes its key (and, for the person
+//! index, its merge operand) into owned bytes at call time and remembers only the target [`Cf`], so
+//! the value is `Send + 'static` and can be replayed on a background thread via
+//! [`CohortStore::apply`](super::rocks::CohortStore::apply).
+//!
+//! The staging surface mirrors `BatchBuilder` one-to-one and encodes identically, so a sequence
+//! staged here and applied through `apply` is byte-for-byte the same set of RocksDB operations as
+//! that sequence built through `BatchBuilder` and committed through `write_batch`.
+
+use super::column_families::{Cf, OpaqueCf};
+use super::keys::{
+ MergeAppliedKey, MergeDrainKey, PendingTransferKey, PersonIndexKey, Stage2Key, TombstoneKey,
+};
+use super::secondary_index::IndexOp;
+use crate::stage1::key::Stage1Key;
+
+/// One staged RocksDB operation with owned bytes, so the batch is `Send + 'static`.
+///
+/// `Merge` carries the encoded [`IndexOp`] operand verbatim: the person-index merge operator must see
+/// the same operand bytes
+/// [`BatchBuilder::merge_person_index`](super::rocks::BatchBuilder::merge_person_index) produces.
+pub(crate) enum StagedOp {
+ Put {
+ cf: Cf,
+ key: Vec<u8>,
+ value: Vec<u8>,
+ },
+ Delete {
+ cf: Cf,
+ key: Vec<u8>,
+ },
+ Merge {
+ cf: Cf,
+ key: Vec<u8>,
+ operand: Vec<u8>,
+ },
+}
+
+/// Owned, `Send`-able staging for a multi-CF `WriteBatch`, mirroring
+/// [`BatchBuilder`](super::rocks::BatchBuilder) one-to-one.
+///
+/// Stage operations with the typed methods, then replay them into one atomic batch with
+/// [`CohortStore::apply`](super::rocks::CohortStore::apply). Holds no borrowed CF handles, so it can
+/// move across thread boundaries.
+#[must_use]
+#[derive(Default)]
+pub struct StagedBatch {
+ ops: Vec<StagedOp>,
+}
+
+impl StagedBatch {
+ pub fn is_empty(&self) -> bool {
+ self.ops.is_empty()
+ }
+
+ pub fn len(&self) -> usize {
+ self.ops.len()
+ }
+
+ pub(crate) fn ops(&self) -> &[StagedOp] {
+ &self.ops
+ }
+
+ pub fn put_stage1(&mut self, key: &Stage1Key, value: &[u8]) {
+ self.ops.push(StagedOp::Put {
+ cf: Cf::Stage1,
+ key: key.encode().to_vec(),
+ value: value.to_vec(),
+ });
+ }
+
+ pub fn delete_stage1(&mut self, key: &Stage1Key) {
+ self.ops.push(StagedOp::Delete {
+ cf: Cf::Stage1,
+ key: key.encode().to_vec(),
+ });
+ }
+
+ /// Read-free append/remove on the person's index.
+ pub fn merge_person_index(&mut self, key: &PersonIndexKey, op: IndexOp) {
+ self.ops.push(StagedOp::Merge {
+ cf: Cf::PersonIndex,
+ key: key.encode().to_vec(),
+ operand: op.encode().to_vec(),
+ });
+ }
+
+ /// Whole-key delete of a person's index entry.
+ pub fn delete_person_index(&mut self, key: &PersonIndexKey) {
+ self.ops.push(StagedOp::Delete {
+ cf: Cf::PersonIndex,
+ key: key.encode().to_vec(),
+ });
+ }
+
+ pub fn put_stage2(&mut self, key: &Stage2Key, value: &[u8]) {
+ self.ops.push(StagedOp::Put {
+ cf: Cf::Stage2,
+ key: key.encode().to_vec(),
+ value: value.to_vec(),
+ });
+ }
+
+ pub fn delete_stage2(&mut self, key: &Stage2Key) {
+ self.ops.push(StagedOp::Delete {
+ cf: Cf::Stage2,
+ key: key.encode().to_vec(),
+ });
+ }
+
+ /// Stage the Phase 1 idempotence marker for a drained merge message.
+ pub fn put_merge_drain_applied(&mut self, key: &MergeDrainKey, value: &[u8]) {
+ self.ops.push(StagedOp::Put {
+ cf: Cf::MergeDrainsApplied,
+ key: key.encode().to_vec(),
+ value: value.to_vec(),
+ });
+ }
+
+ /// GC-delete one expired Phase 1 idempotence marker.
+ pub fn delete_merge_drain_applied(&mut self, key: &MergeDrainKey) {
+ self.ops.push(StagedOp::Delete {
+ cf: Cf::MergeDrainsApplied,
+ key: key.encode().to_vec(),
+ });
+ }
+
+ /// Stage a packaged merge into the outbox.
+ pub fn put_pending_transfer(&mut self, key: &PendingTransferKey, value: &[u8]) {
+ self.ops.push(StagedOp::Put {
+ cf: Cf::PendingTransfers,
+ key: key.encode().to_vec(),
+ value: value.to_vec(),
+ });
+ }
+
+ /// Clear an outbox slot once its transfer is acked.
+ pub fn delete_pending_transfer(&mut self, key: &PendingTransferKey) {
+ self.ops.push(StagedOp::Delete {
+ cf: Cf::PendingTransfers,
+ key: key.encode().to_vec(),
+ });
+ }
+
+ /// Stage the Phase 2 idempotence marker for an applied transfer message.
+ pub fn put_merge_applied(&mut self, key: &MergeAppliedKey, value: &[u8]) {
+ self.ops.push(StagedOp::Put {
+ cf: Cf::MergeApplied,
+ key: key.encode().to_vec(),
+ value: value.to_vec(),
+ });
+ }
+
+ /// GC-delete one expired Phase 2 idempotence marker.
+ pub fn delete_merge_applied(&mut self, key: &MergeAppliedKey) {
+ self.ops.push(StagedOp::Delete {
+ cf: Cf::MergeApplied,
+ key: key.encode().to_vec(),
+ });
+ }
+
+ /// Stage the redirect tombstone for a merged-away person.
+ pub fn put_tombstone(&mut self, key: &TombstoneKey, value: &[u8]) {
+ self.ops.push(StagedOp::Put {
+ cf: Cf::MergeTombstones,
+ key: key.encode().to_vec(),
+ value: value.to_vec(),
+ });
+ }
+
+ /// GC-delete one expired redirect tombstone.
+ pub fn delete_tombstone(&mut self, key: &TombstoneKey) {
+ self.ops.push(StagedOp::Delete {
+ cf: Cf::MergeTombstones,
+ key: key.encode().to_vec(),
+ });
+ }
+
+ /// Raw put by pre-encoded key bytes. Restricted to [`OpaqueCf`].
+ pub fn put_raw(&mut self, cf: OpaqueCf, key: &[u8], value: &[u8]) {
+ self.ops.push(StagedOp::Put {
+ cf: cf.cf(),
+ key: key.to_vec(),
+ value: value.to_vec(),
+ });
+ }
+}
+
+#[cfg(test)]
+// Tests drive the store directly through `CohortStore` (`write_batch`/`apply`/`get_*`) — the
+// sanctioned direct-store surface for tests — to pin that `apply` writes exactly what `write_batch`
+// does.
+#[allow(clippy::disallowed_methods)]
+mod tests {
+ use tempfile::TempDir;
+ use uuid::Uuid;
+
+ use super::*;
+ use crate::stage1::key::LeafStateKey;
+ use crate::store::rocks::{BatchBuilder, CohortStore, StoreConfig};
+
+ const PARTITION: u16 = 3;
+ const TEAM: u64 = 7;
+ const LARGE_LIMIT: usize = 1024;
+
+ fn stage1_key(person: u128, lsk: u8) -> Stage1Key {
+ Stage1Key {
+ partition_id: PARTITION,
+ team_id: TEAM,
+ leaf_state_key: LeafStateKey([lsk; 16]),
+ person_id: Uuid::from_u128(person),
+ }
+ }
+
+ fn person_index_key(person: u128) -> PersonIndexKey {
+ PersonIndexKey {
+ partition_id: PARTITION,
+ team_id: TEAM,
+ person_id: Uuid::from_u128(person),
+ }
+ }
+
+ fn stage2_key(person: u128, cohort: u64) -> Stage2Key {
+ Stage2Key {
+ partition_id: PARTITION,
+ team_id: TEAM,
+ cohort_id: cohort,
+ person_id: Uuid::from_u128(person),
+ }
+ }
+
+ fn merge_drain_key(person: u128) -> MergeDrainKey {
+ MergeDrainKey {
+ partition_id: PARTITION,
+ team_id: TEAM,
+ old_person: Uuid::from_u128(person),
+ merge_msg_partition: 1,
+ merge_msg_offset: 2,
+ }
+ }
+
+ fn pending_transfer_key(person: u128) -> PendingTransferKey {
+ PendingTransferKey {
+ partition_id: PARTITION,
+ team_id: TEAM,
+ old_person: Uuid::from_u128(person),
+ }
+ }
+
+ fn merge_applied_key(person: u128) -> MergeAppliedKey {
+ MergeAppliedKey {
+ partition_id: PARTITION,
+ team_id: TEAM,
+ new_person: Uuid::from_u128(person),
+ source_partition: 4,
+ source_offset: 5,
+ }
+ }
+
+ fn tombstone_key(person: u128) -> TombstoneKey {
+ TombstoneKey {
+ partition_id: PARTITION,
+ team_id: TEAM,
+ person: Uuid::from_u128(person),
+ }
+ }
+
+ fn open_store(dir: &TempDir, name: &str) -> CohortStore {
+ CohortStore::open(&StoreConfig {
+ path: dir.path().join(name),
+ ..StoreConfig::default()
+ })
+ .unwrap()
+ }
+
+ /// Drives every staging method through `BatchBuilder`. `merge_person_index` uses both `IndexOp`
+ /// variants (an append that survives and one cancelled by a remove) to exercise the merge operand
+ /// on replay, and `put_raw` covers both `OpaqueCf` arms.
+ fn drive_batch_builder(b: &mut BatchBuilder<'_>) {
+ b.put_stage1(&stage1_key(1, 0xA0), b"s1-put");
+ b.put_stage1(&stage1_key(2, 0xA1), b"s1-doomed");
+ b.delete_stage1(&stage1_key(2, 0xA1));
+
+ b.merge_person_index(
+ &person_index_key(1),
+ IndexOp::Append(LeafStateKey([0x11; 16])),
+ );
+ b.merge_person_index(
+ &person_index_key(1),
+ IndexOp::Append(LeafStateKey([0x22; 16])),
+ );
+ b.merge_person_index(
+ &person_index_key(1),
+ IndexOp::Remove(LeafStateKey([0x22; 16])),
+ );
+ b.merge_person_index(
+ &person_index_key(2),
+ IndexOp::Append(LeafStateKey([0x33; 16])),
+ );
+ b.delete_person_index(&person_index_key(2));
+
+ b.put_stage2(&stage2_key(1, 100), b"s2-put");
+ b.put_stage2(&stage2_key(2, 200), b"s2-doomed");
+ b.delete_stage2(&stage2_key(2, 200));
+
+ b.put_merge_drain_applied(&merge_drain_key(1), b"drain-put");
+ b.delete_merge_drain_applied(&merge_drain_key(2));
+
+ b.put_pending_transfer(&pending_transfer_key(1), b"transfer-put");
+ b.delete_pending_transfer(&pending_transfer_key(2));
+
+ b.put_merge_applied(&merge_applied_key(1), b"applied-put");
+ b.delete_merge_applied(&merge_applied_key(2));
+
+ b.put_tombstone(&tombstone_key(1), b"tombstone-put");
+ b.delete_tombstone(&tombstone_key(2));
+
+ b.put_raw(OpaqueCf::Stage1, &stage1_key(9, 0xF0).encode(), b"raw-s1");
+ b.put_raw(OpaqueCf::Stage2, &stage2_key(9, 900).encode(), b"raw-s2");
+ }
+
+ /// The same sequence as [`drive_batch_builder`], staged into a `StagedBatch`.
+ fn drive_staged_batch(s: &mut StagedBatch) {
+ s.put_stage1(&stage1_key(1, 0xA0), b"s1-put");
+ s.put_stage1(&stage1_key(2, 0xA1), b"s1-doomed");
+ s.delete_stage1(&stage1_key(2, 0xA1));
+
+ s.merge_person_index(
+ &person_index_key(1),
+ IndexOp::Append(LeafStateKey([0x11; 16])),
+ );
+ s.merge_person_index(
+ &person_index_key(1),
+ IndexOp::Append(LeafStateKey([0x22; 16])),
+ );
+ s.merge_person_index(
+ &person_index_key(1),
+ IndexOp::Remove(LeafStateKey([0x22; 16])),
+ );
+ s.merge_person_index(
+ &person_index_key(2),
+ IndexOp::Append(LeafStateKey([0x33; 16])),
+ );
+ s.delete_person_index(&person_index_key(2));
+
+ s.put_stage2(&stage2_key(1, 100), b"s2-put");
+ s.put_stage2(&stage2_key(2, 200), b"s2-doomed");
+ s.delete_stage2(&stage2_key(2, 200));
+
+ s.put_merge_drain_applied(&merge_drain_key(1), b"drain-put");
+ s.delete_merge_drain_applied(&merge_drain_key(2));
+
+ s.put_pending_transfer(&pending_transfer_key(1), b"transfer-put");
+ s.delete_pending_transfer(&pending_transfer_key(2));
+
+ s.put_merge_applied(&merge_applied_key(1), b"applied-put");
+ s.delete_merge_applied(&merge_applied_key(2));
+
+ s.put_tombstone(&tombstone_key(1), b"tombstone-put");
+ s.delete_tombstone(&tombstone_key(2));
+
+ s.put_raw(OpaqueCf::Stage1, &stage1_key(9, 0xF0).encode(), b"raw-s1");
+ s.put_raw(OpaqueCf::Stage2, &stage2_key(9, 900).encode(), b"raw-s2");
+ }
+
+ #[test]
+ fn staged_batch_apply_writes_exactly_what_batch_builder_writes() {
+ let dir = TempDir::new().unwrap();
+ let via_builder = open_store(&dir, "builder");
+ let via_staged = open_store(&dir, "staged");
+
+ via_builder.write_batch(drive_batch_builder).unwrap();
+
+ let mut staged = StagedBatch::default();
+ drive_staged_batch(&mut staged);
+ assert!(!staged.is_empty());
+ assert_eq!(staged.len(), 21);
+ via_staged.apply(&staged).unwrap();
+
+ // `scan_merge_cf` is CF-generic and all keys carry the partition prefix, so it enumerates any
+ // CF's slice.
+ for cf in Cf::ALL {
+ let builder_kvs = via_builder
+ .scan_merge_cf(cf, PARTITION, None, LARGE_LIMIT)
+ .unwrap();
+ let staged_kvs = via_staged
+ .scan_merge_cf(cf, PARTITION, None, LARGE_LIMIT)
+ .unwrap();
+ assert_eq!(
+ builder_kvs, staged_kvs,
+ "CF {cf:?} diverged between write_batch and StagedBatch::apply",
+ );
+ }
+
+ // Decoded person-index output must agree too: a merge operand replayed to the wrong operator
+ // or with diverging bytes would collapse to a different set even if the raw value scan matched.
+ for person in [1u128, 2] {
+ let key = person_index_key(person);
+ assert_eq!(
+ via_builder.get_person_index(&key).unwrap(),
+ via_staged.get_person_index(&key).unwrap(),
+ "person index for {person} diverged",
+ );
+ }
+ // The surviving append leaves exactly one leaf; the appended-then-removed one is gone.
+ assert_eq!(
+ via_staged.get_person_index(&person_index_key(1)).unwrap(),
+ vec![LeafStateKey([0x11; 16])],
+ );
+ assert!(via_staged
+ .get_person_index(&person_index_key(2))
+ .unwrap()
+ .is_empty());
+ }
+
+ #[test]
+ fn default_staged_batch_is_empty() {
+ let batch = StagedBatch::default();
+ assert!(batch.is_empty());
+ assert_eq!(batch.len(), 0);
+ }
+
+ // The type exists to cross a `spawn_blocking` boundary: a field that is not `Send + 'static` must
+ // fail here, not at the distant offload call site.
+ #[test]
+ fn staged_batch_is_send_and_static() {
+ fn assert_send_static<T: Send + 'static>() {}
+ assert_send_static::<StagedBatch>();
+ }
+}
diff --git a/rust/cohort-stream-processor/src/sweep/dispatch.rs b/rust/cohort-stream-processor/src/sweep/dispatch.rs
index 5b1af7b4f637..86c4915eec62 100644
--- a/rust/cohort-stream-processor/src/sweep/dispatch.rs
+++ b/rust/cohort-stream-processor/src/sweep/dispatch.rs
@@ -56,7 +56,7 @@ mod tests {
use crate::filters::{CatalogHandle, FilterCatalog};
use crate::partitions::{OffsetTracker, PartitionRouter};
use crate::producer::{CaptureSink, MembershipSink};
- use crate::store::{CohortStore, StoreConfig};
+ use crate::store::{CohortStore, OffloadConfig, OffloadMode, StoreConfig, StoreHandle};
use crate::workers::MergeWorkerDeps;
fn dispatcher() -> (TempDir, Arc<EventDispatcher>) {
@@ -66,12 +66,20 @@ mod tests {
..StoreConfig::default()
})
.unwrap();
+ let handle = StoreHandle::new(
+ store,
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ );
let catalog = Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([])));
let sink: Arc<dyn MembershipSink> = Arc::new(CaptureSink::new());
let dispatcher = EventDispatcher::new(
PartitionRouter::new(64),
Arc::new(OffsetTracker::new()),
- store,
+ handle,
catalog,
sink,
MergeWorkerDeps::capture(),
diff --git a/rust/cohort-stream-processor/src/workers/cascade_path.rs b/rust/cohort-stream-processor/src/workers/cascade_path.rs
index f07d8912d6de..fa0457c51e14 100644
--- a/rust/cohort-stream-processor/src/workers/cascade_path.rs
+++ b/rust/cohort-stream-processor/src/workers/cascade_path.rs
@@ -30,7 +30,7 @@ use crate::observability::metrics::{
use crate::partitions::offset_tracker::{MarkOutcome, OffsetTracker};
use crate::producer::{CohortMembershipChange, MembershipSink};
use crate::stage2::state::Stage2State;
-use crate::store::{CohortStore, Stage2Key};
+use crate::store::{Stage2Key, StagedBatch, StoreHandle};
use crate::workers::merge_path::MergeWorkerDeps;
use crate::workers::stage2_path::recompute_and_diff;
use crate::workers::worker::{produce_cascades, produce_membership};
@@ -40,7 +40,7 @@ use crate::workers::worker::{produce_cascades, produce_membership};
#[allow(clippy::too_many_arguments)]
pub(crate) async fn handle_cascade(
partition_id: u16,
- store: &CohortStore,
+ handle: &StoreHandle,
catalog: &CatalogHandle,
sink: &Arc<dyn MembershipSink>,
merge: &MergeWorkerDeps,
@@ -106,7 +106,7 @@ pub(crate) async fn handle_cascade(
let Some(tree) = filters.cohorts.get(&referrer) else {
continue;
};
- let diff = match recompute_and_diff(partition_id, person_id, tree, filters, store) {
+ let diff = match recompute_and_diff(partition_id, person_id, tree, filters, handle).await {
Ok(diff) => diff,
Err(error) => {
warn!(
@@ -196,11 +196,11 @@ pub(crate) async fn handle_cascade(
return;
}
- if let Err(error) = store.write_batch(|batch| {
- for (key, state) in &writes {
- batch.put_stage2(key, &state.encode());
- }
- }) {
+ let mut staged = StagedBatch::default();
+ for (key, state) in &writes {
+ staged.put_stage2(key, &state.encode());
+ }
+ if let Err(error) = handle.commit(staged).await {
warn!(
partition_id,
error = %error,
@@ -244,6 +244,8 @@ fn clickhouse_millis(ts: &str) -> i64 {
}
#[cfg(test)]
+// Tests seed and assert against `CohortStore` directly, the sanctioned direct-store surface for tests.
+#[allow(clippy::disallowed_methods)]
mod tests {
use super::*;
use chrono_tz::UTC;
@@ -258,7 +260,7 @@ mod tests {
};
use crate::stage1::key::LeafStateKey;
use crate::stage1::state::{AppliedOffsets, Stage1State, StatefulRecord};
- use crate::store::{Stage1Key, StoreConfig};
+ use crate::store::{CohortStore, OffloadConfig, OffloadMode, Stage1Key, StoreConfig};
use crate::workers::{CascadeConfig, TransferRetryPolicy, DEFAULT_MERGE_GC_SCAN_LIMIT};
const TEAM: i32 = 7;
@@ -278,6 +280,18 @@ mod tests {
(dir, store)
}
+ /// Wraps the store so `handle_cascade` exercises the same blocking-pool transport as production.
+ fn handle(store: &CohortStore) -> StoreHandle {
+ StoreHandle::new(
+ store.clone(),
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ )
+ }
+
fn behavioral_leaf() -> Value {
json!({
"type": "behavioral", "value": "performed_event", "key": "$pageview",
@@ -468,7 +482,17 @@ mod tests {
let (sink, deps) = deps(&membership, &cascade, true, 1000);
let msg = first_cascade(incoming(2, alice, 1, vec![2]).change, 99);
- handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+ handle_cascade(
+ PARTITION,
+ &handle(&store),
+ &catalog,
+ &sink,
+ &deps,
+ TS,
+ &msg,
+ OFFSET,
+ )
+ .await;
let changes = membership.changes();
assert_eq!(changes.len(), 1, "B's external flip");
@@ -511,7 +535,17 @@ mod tests {
let (sink, deps) = deps(&membership, &cascade, true, 1000);
let msg = first_cascade(incoming(2, alice, 1, vec![2]).change, 99);
- handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+ handle_cascade(
+ PARTITION,
+ &handle(&store),
+ &catalog,
+ &sink,
+ &deps,
+ TS,
+ &msg,
+ OFFSET,
+ )
+ .await;
assert!(membership.changes().is_empty(), "no flip, no membership");
assert!(cascade.messages().is_empty(), "no flip, no onward cascade");
@@ -531,7 +565,17 @@ mod tests {
let (sink, deps) = deps(&membership, &cascade, true, 1000);
let msg = first_cascade(incoming(2, alice, 1, vec![2]).change, 99);
- handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+ handle_cascade(
+ PARTITION,
+ &handle(&store),
+ &catalog,
+ &sink,
+ &deps,
+ TS,
+ &msg,
+ OFFSET,
+ )
+ .await;
assert!(membership.changes().is_empty());
assert!(cascade.messages().is_empty());
@@ -557,7 +601,17 @@ mod tests {
let (sink, deps) = deps(&membership, &cascade, false, 1000); // gate OFF
let msg = first_cascade(incoming(2, alice, 1, vec![2]).change, 99);
- handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+ handle_cascade(
+ PARTITION,
+ &handle(&store),
+ &catalog,
+ &sink,
+ &deps,
+ TS,
+ &msg,
+ OFFSET,
+ )
+ .await;
assert!(membership.changes().is_empty(), "gate off: no re-eval");
assert!(cascade.messages().is_empty());
@@ -585,7 +639,17 @@ mod tests {
// Incoming depth == cap (8): the external flip still emits, the onward cascade drops.
let msg = incoming(2, alice, 8, vec![2, 90, 91, 92, 93, 94, 95, 96]);
- handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+ handle_cascade(
+ PARTITION,
+ &handle(&store),
+ &catalog,
+ &sink,
+ &deps,
+ TS,
+ &msg,
+ OFFSET,
+ )
+ .await;
assert_eq!(
membership.changes().len(),
@@ -624,7 +688,17 @@ mod tests {
// B (cohort 1) is already in the chain: the onward hop is a runtime cycle.
let msg = incoming(2, alice, 2, vec![2, 1]);
- handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+ handle_cascade(
+ PARTITION,
+ &handle(&store),
+ &catalog,
+ &sink,
+ &deps,
+ TS,
+ &msg,
+ OFFSET,
+ )
+ .await;
assert_eq!(
membership.changes().len(),
@@ -661,7 +735,17 @@ mod tests {
let (sink, deps) = deps(&membership, &cascade, true, 2); // cap 2 of 4 referrers
let msg = first_cascade(incoming(100, alice, 1, vec![100]).change, 99);
- handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+ handle_cascade(
+ PARTITION,
+ &handle(&store),
+ &catalog,
+ &sink,
+ &deps,
+ TS,
+ &msg,
+ OFFSET,
+ )
+ .await;
let cohorts: Vec<i32> = membership.changes().iter().map(|c| c.cohort_id).collect();
assert_eq!(
@@ -695,10 +779,30 @@ mod tests {
let (sink, deps) = deps(&membership, &cascade, true, 1000);
let msg = first_cascade(incoming(2, alice, 1, vec![2]).change, 99);
- handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+ handle_cascade(
+ PARTITION,
+ &handle(&store),
+ &catalog,
+ &sink,
+ &deps,
+ TS,
+ &msg,
+ OFFSET,
+ )
+ .await;
assert_eq!(membership.changes().len(), 1, "first pass emits");
- handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+ handle_cascade(
+ PARTITION,
+ &handle(&store),
+ &catalog,
+ &sink,
+ &deps,
+ TS,
+ &msg,
+ OFFSET,
+ )
+ .await;
assert_eq!(
membership.changes().len(),
1,
@@ -725,7 +829,17 @@ mod tests {
let (sink, deps) = deps(&membership, &cascade, true, 1000);
let msg = first_cascade(incoming(2, alice, 1, vec![2]).change, 99);
- handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+ handle_cascade(
+ PARTITION,
+ &handle(&store),
+ &catalog,
+ &sink,
+ &deps,
+ TS,
+ &msg,
+ OFFSET,
+ )
+ .await;
assert!(
membership.changes().is_empty(),
@@ -760,7 +874,17 @@ mod tests {
let (sink, deps) = deps(&membership, &cascade, true, 1000);
let msg = first_cascade(incoming(2, alice, 1, vec![2]).change, 99);
- handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+ handle_cascade(
+ PARTITION,
+ &handle(&store),
+ &catalog,
+ &sink,
+ &deps,
+ TS,
+ &msg,
+ OFFSET,
+ )
+ .await;
assert_eq!(
membership.changes().len(),
diff --git a/rust/cohort-stream-processor/src/workers/event_path.rs b/rust/cohort-stream-processor/src/workers/event_path.rs
index d826380b46d0..fe7346dccbc6 100644
--- a/rust/cohort-stream-processor/src/workers/event_path.rs
+++ b/rust/cohort-stream-processor/src/workers/event_path.rs
@@ -1,8 +1,12 @@
//! The per-event read-modify-write — the Stage 1 "brain".
//!
-//! [`process_event`] folds one re-keyed event into each affected leaf's RocksDB state under one
-//! atomic [`WriteBatch`](crate::store::CohortStore::write_batch) and returns the transitions that
-//! flipped. Transitions are surfaced only after the commit succeeds.
+//! [`plan_event`] decides what to read; [`fold_event`] folds one re-keyed event into each affected
+//! leaf's RocksDB state, staging every write into a [`StagedBatch`](crate::store::StagedBatch) that
+//! commits atomically through [`CohortStore::apply`](crate::store::CohortStore::apply). The sync
+//! [`process_event`] composition (tests, blocking contexts) and the async
+//! [`process_event_offloaded`] composition (production, over the
+//! [`StoreHandle`](crate::store::StoreHandle) facade) share those two cores. Both return the
+//! transitions that flipped, surfaced only after the commit succeeds.
use std::collections::BTreeMap;
use std::sync::Arc;
@@ -32,7 +36,9 @@ use crate::stage1::state::{
};
use crate::stage1::time::clickhouse_timestamp_to_millis;
use crate::stage1::transition::{LeafTransition, TransitionKind};
-use crate::store::{CohortStore, IndexOp, PersonIndexKey, StoreError};
+use crate::store::{
+ CohortStore, IndexOp, PersonIndexKey, ReadLane, StagedBatch, StoreError, StoreHandle,
+};
use crate::workers::person_memo::{ConditionBitset, Lookup, PersonKey, PersonMemo, Receipt};
/// Whether to evaluate only the behavioral conditions matching the incoming event name. A behavioral
@@ -142,6 +148,62 @@ struct PendingWrite {
variant: StateVariant,
}
+/// What [`plan_event`] resolved for one event, up to (but not including) the pre-event read.
+///
+/// The `&mut PersonMemo` borrow ends inside `plan_event`, so the read that fills [`Self::Read`] runs
+/// with no `&mut` in scope.
+pub(crate) enum EventPlan {
+ /// The event was skipped before any leaf evaluated (`skipped` reason).
+ Skip(SkipReason),
+ /// No leaf matched: nothing to read, nothing to write, no transitions.
+ NoApplies,
+ /// Leaves applied; read `keys` (in order) and hand the result to [`fold_event`].
+ Read(ReadPlan),
+}
+
+/// The data [`fold_event`] needs from [`plan_event`], carried by [`EventPlan::Read`]. `keys` are in
+/// `applies` order so the fold's zip over the read result stays aligned.
+pub(crate) struct ReadPlan {
+ partition_id: u16,
+ team_id: u64,
+ applies: Vec<Apply>,
+ keys: Vec<Stage1Key>,
+ event_ms: i64,
+ person_id: Uuid,
+ origin: Option<Uuid>,
+}
+
+/// The metric emissions a successful fold implies, captured so the compositions can defer them until
+/// after the commit succeeds. A fold that stages nothing yields empty stats.
+pub(crate) struct WriteStats {
+ /// Per-`StateVariant` `STAGE1_STATE_WRITES` counts, in first-seen order.
+ variant_writes: Vec<(StateVariant, u64)>,
+ /// Total `STAGE1_PERSON_INDEX_APPENDS` (one per first-write leaf).
+ person_index_appends: u64,
+}
+
+impl WriteStats {
+ /// Emit the deferred write metrics. Called by the compositions only after a successful commit, so
+ /// a failed write records no phantom write counts.
+ pub(crate) fn emit(&self) {
+ for &(variant, count) in &self.variant_writes {
+ counter!(STAGE1_STATE_WRITES, "variant" => variant.as_str()).increment(count);
+ }
+ if self.person_index_appends > 0 {
+ counter!(STAGE1_PERSON_INDEX_APPENDS).increment(self.person_index_appends);
+ }
+ }
+}
+
+/// The pure result of [`fold_event`]: the staged writes plus what the caller surfaces after commit.
+/// Infallible — the fold touches no store.
+pub(crate) struct FoldOutput {
+ pub staged: StagedBatch,
+ pub transitions: Vec<LeafTransition>,
+ pub schedules: Vec<(Stage1Key, i64)>,
+ pub write_stats: WriteStats,
+}
+
/// One apply's stored state as read by the event's single batched pre-event read.
enum PriorState {
/// No row: this apply is the leaf's first write.
@@ -191,6 +253,10 @@ pub fn process_event(
/// Fold one event, consulting the per-worker person memo. A hit answers the person conditions from
/// cache — no JSON parse, no HogVM eval — keyed on `generation` plus a fingerprint of the raw
/// `person_properties`.
+// The sync composition is the public test surface and runs in blocking contexts, so its direct
+// `multi_get_stage1` + `apply` are sanctioned; production folds through `process_event_offloaded`,
+// which the crate-wide lint keeps free of raw `CohortStore` calls.
+#[allow(clippy::disallowed_methods)]
pub fn process_event_with_memo(
partition_id: u16,
store: &CohortStore,
@@ -200,23 +266,121 @@ pub fn process_event_with_memo(
memo: &mut PersonMemo,
event_name_gating: EventNameGating,
) -> Result<EventOutcome, StoreError> {
+ // The `&mut PersonMemo` borrow ends inside `plan_event`; the read + fold below hold no mutable
+ // borrow.
+ let read = match plan_event(
+ partition_id,
+ filters,
+ generation,
+ event,
+ memo,
+ event_name_gating,
+ ) {
+ EventPlan::Skip(reason) => return Ok(EventOutcome::skipped(reason)),
+ EventPlan::NoApplies => return Ok(EventOutcome::processed(Vec::new(), Vec::new(), 0)),
+ EventPlan::Read(read) => read,
+ };
+
+ let event_ms = read.event_ms;
+ histogram!(STAGE1_SNAPSHOT_KEYS).record(read.keys.len() as f64);
+ let values = store.multi_get_stage1(&read.keys)?;
+
+ let FoldOutput {
+ staged,
+ transitions,
+ schedules,
+ write_stats,
+ } = fold_event(filters, read, values, event);
+
+ // The batch spans exactly one event: the next event in the sub-batch must see this event's
+ // committed writes (argMax tiebreaker, replay dedup). An event that stages nothing performs no
+ // write, and the write metrics emit only after the commit lands.
+ if !staged.is_empty() {
+ store.apply(&staged)?;
+ write_stats.emit();
+ }
+
+ Ok(EventOutcome::processed(transitions, schedules, event_ms))
+}
+
+/// The production composition of [`plan_event`] + [`fold_event`], reading and writing through the
+/// async [`StoreHandle`] facade so the store I/O runs on the blocking pool. The `&mut PersonMemo`
+/// borrow ends inside `plan_event`, so no mutable borrow spans an await.
+///
+/// Sequential awaits only: the batched read must observe the prior event's committed writes, so the
+/// read and commit are never joined or reordered.
+pub(crate) async fn process_event_offloaded(
+ partition_id: u16,
+ handle: &StoreHandle,
+ filters: &TeamFilters,
+ generation: Generation,
+ event: &CohortStreamEvent,
+ memo: &mut PersonMemo,
+ event_name_gating: EventNameGating,
+) -> Result<EventOutcome, StoreError> {
+ let read = match plan_event(
+ partition_id,
+ filters,
+ generation,
+ event,
+ memo,
+ event_name_gating,
+ ) {
+ EventPlan::Skip(reason) => return Ok(EventOutcome::skipped(reason)),
+ EventPlan::NoApplies => return Ok(EventOutcome::processed(Vec::new(), Vec::new(), 0)),
+ EventPlan::Read(read) => read,
+ };
+
+ let event_ms = read.event_ms;
+ histogram!(STAGE1_SNAPSHOT_KEYS).record(read.keys.len() as f64);
+ // Clone the keys for the read so the plan keeps its copy for `fold_event`'s zip.
+ let values = handle
+ .multi_get_stage1(read.keys.clone(), ReadLane::Event)
+ .await?;
+
+ let FoldOutput {
+ staged,
+ transitions,
+ schedules,
+ write_stats,
+ } = fold_event(filters, read, values, event);
+
+ // Commit before the caller processes the next event; emit the write metrics only after it lands.
+ if !staged.is_empty() {
+ handle.commit(staged).await?;
+ write_stats.emit();
+ }
+
+ Ok(EventOutcome::processed(transitions, schedules, event_ms))
+}
+
+/// Resolve everything up to the pre-event read: gating, globals, person memo, evaluation, applies,
+/// and the read keys. The `&mut PersonMemo` borrow lives entirely here, so on return the batched read
+/// that fills the plan can run with no `&mut` in scope.
+pub(crate) fn plan_event(
+ partition_id: u16,
+ filters: &TeamFilters,
+ generation: Generation,
+ event: &CohortStreamEvent,
+ memo: &mut PersonMemo,
+ event_name_gating: EventNameGating,
+) -> EventPlan {
if event.person_id.is_empty() {
- return Ok(EventOutcome::skipped(SkipReason::NullPersonId));
+ return EventPlan::Skip(SkipReason::NullPersonId);
}
let Ok(person_id) = Uuid::parse_str(&event.person_id) else {
- return Ok(EventOutcome::skipped(SkipReason::UnparseablePersonId));
+ return EventPlan::Skip(SkipReason::UnparseablePersonId);
};
let origin: Option<Uuid> = event
.redirected_from
.as_deref()
.and_then(|raw| Uuid::parse_str(raw).ok());
- let origin = origin.as_ref();
let has_behavioral = !filters.behavioral_conditions.is_empty();
let has_person = !filters.person_property_conditions.is_empty();
if !has_behavioral && !has_person {
- return Ok(EventOutcome::skipped(SkipReason::NoConditions));
+ return EventPlan::Skip(SkipReason::NoConditions);
}
// Build globals and resolve the person plan before any evaluation, so a malformed payload skips
@@ -224,14 +388,14 @@ pub fn process_event_with_memo(
let behavioral_globals = if has_behavioral {
match build_behavioral_globals(event) {
Ok(globals) => Some(globals),
- Err(_) => return Ok(EventOutcome::skipped(SkipReason::GlobalsParseError)),
+ Err(_) => return EventPlan::Skip(SkipReason::GlobalsParseError),
}
} else {
None
};
let person = match resolve_person(filters, event, person_id, generation, memo) {
Ok(person) => person,
- Err(skip) => return Ok(EventOutcome::skipped(skip)),
+ Err(skip) => return EventPlan::Skip(skip),
};
// One evaluator reused across the event's conditions: globals set once per kind, program per condition.
@@ -250,17 +414,15 @@ pub fn process_event_with_memo(
collect_person_applies(filters, &mut evaluator, person, memo, &mut applies);
if applies.is_empty() {
- return Ok(EventOutcome::processed(Vec::new(), Vec::new(), 0));
+ return EventPlan::NoApplies;
}
let Some(event_ms) = clickhouse_timestamp_to_millis(&event.timestamp) else {
- return Ok(EventOutcome::skipped(SkipReason::BadTimestamp));
+ return EventPlan::Skip(SkipReason::BadTimestamp);
};
let team_id = event.team_id as u64;
- // One batched pre-event read; all writes defer to the post-loop `write_batch`, so every apply
- // sees the pre-event image. The batch spans exactly one event: the next event in the sub-batch
- // must see this event's committed writes (argMax tiebreaker, replay dedup).
+ // Keys are built in `applies` order so the fold's zip over the read result stays aligned.
let keys: Vec<Stage1Key> = applies
.iter()
.map(|apply| Stage1Key {
@@ -270,12 +432,40 @@ pub fn process_event_with_memo(
person_id,
})
.collect();
- histogram!(STAGE1_SNAPSHOT_KEYS).record(keys.len() as f64);
- let values = store.multi_get_stage1(&keys)?;
+
+ EventPlan::Read(ReadPlan {
+ partition_id,
+ team_id,
+ applies,
+ keys,
+ event_ms,
+ person_id,
+ origin,
+ })
+}
+
+/// Fold the pre-event read `values` into each apply's next state, staging the writes into a
+/// [`StagedBatch`] for the caller to commit. Pure and infallible — touches no store.
+pub(crate) fn fold_event(
+ filters: &TeamFilters,
+ read: ReadPlan,
+ values: Vec<Option<Vec<u8>>>,
+ event: &CohortStreamEvent,
+) -> FoldOutput {
+ let ReadPlan {
+ partition_id,
+ team_id,
+ applies,
+ keys,
+ event_ms,
+ person_id,
+ origin,
+ } = read;
+ let origin = origin.as_ref();
let mut transitions = Vec::new();
let mut schedules: Vec<(Stage1Key, i64)> = Vec::new();
- let mut pending = Vec::new();
+ let mut pending: Vec<PendingWrite> = Vec::new();
// Alignment-safe zip: `multi_get_stage1` preserves input order, `None` for absent keys.
for ((apply, key), bytes) in applies.into_iter().zip(keys).zip(values) {
@@ -355,33 +545,43 @@ pub fn process_event_with_memo(
});
}
+ let mut staged = StagedBatch::default();
+ let mut write_stats = WriteStats {
+ variant_writes: Vec::new(),
+ person_index_appends: 0,
+ };
if !pending.is_empty() {
let person_index = PersonIndexKey {
partition_id,
team_id,
person_id,
};
- store.write_batch(|batch| {
- for write in &pending {
- batch.put_stage1(&write.key, &write.bytes);
- if write.first_write {
- batch.merge_person_index(
- &person_index,
- IndexOp::Append(write.key.leaf_state_key),
- );
- }
- }
- })?;
-
for write in &pending {
- counter!(STAGE1_STATE_WRITES, "variant" => write.variant.as_str()).increment(1);
+ staged.put_stage1(&write.key, &write.bytes);
if write.first_write {
- counter!(STAGE1_PERSON_INDEX_APPENDS).increment(1);
+ staged.merge_person_index(&person_index, IndexOp::Append(write.key.leaf_state_key));
+ write_stats.person_index_appends += 1;
}
+ record_variant_write(&mut write_stats.variant_writes, write.variant);
}
}
- Ok(EventOutcome::processed(transitions, schedules, event_ms))
+ FoldOutput {
+ staged,
+ transitions,
+ schedules,
+ write_stats,
+ }
+}
+
+/// Accumulate one write into its variant's running count, preserving first-seen order for the
+/// deferred emission.
+fn record_variant_write(counts: &mut Vec<(StateVariant, u64)>, variant: StateVariant) {
+ if let Some((_, count)) = counts.iter_mut().find(|(v, _)| *v == variant) {
+ *count += 1;
+ } else {
+ counts.push((variant, 1));
+ }
}
/// Returns `None` for permanent-membership states (`i64::MAX` sentinel), so only time-bounded
diff --git a/rust/cohort-stream-processor/src/workers/merge_gc.rs b/rust/cohort-stream-processor/src/workers/merge_gc.rs
index cfb215938594..5908602e4cac 100644
--- a/rust/cohort-stream-processor/src/workers/merge_gc.rs
+++ b/rust/cohort-stream-processor/src/workers/merge_gc.rs
@@ -102,6 +102,9 @@ pub fn handle_merge_gc(
/// Scan one CF up to the cap, collect expired/undecodable keys, delete them in one batch, and
/// advance the cursor (wrapping on exhaustion).
+// Sync GC core; runs on the blocking pool inside `StoreHandle::run_section` (via `handle_merge_gc`),
+// so its direct `CohortStore` I/O is already off the runtime threads.
+#[allow(clippy::disallowed_methods)]
fn sweep_one_cf(
partition_id: u16,
store: &CohortStore,
@@ -242,7 +245,9 @@ fn stage_delete(
}
}
+// Tests seed and read merge-CF rows directly against the store.
#[cfg(test)]
+#[allow(clippy::disallowed_methods)]
mod tests {
use super::*;
use tempfile::TempDir;
diff --git a/rust/cohort-stream-processor/src/workers/merge_path.rs b/rust/cohort-stream-processor/src/workers/merge_path.rs
index bf322f13834f..249fc3c9cc9e 100644
--- a/rust/cohort-stream-processor/src/workers/merge_path.rs
+++ b/rust/cohort-stream-processor/src/workers/merge_path.rs
@@ -32,7 +32,7 @@ use crate::producer::{
};
use crate::stage1::key::Stage1Key;
use crate::stage1::transition::LeafTransition;
-use crate::store::{CohortStore, PendingTransferKey};
+use crate::store::{PendingTransferKey, StoreHandle};
use crate::sweep::EvictionQueue;
use crate::workers::stage2_path::compose_stage2;
use crate::workers::worker::{
@@ -142,7 +142,7 @@ impl MergeWorkerDeps {
#[allow(clippy::too_many_arguments)]
pub(crate) async fn handle_merge(
partition_id: u16,
- store: &CohortStore,
+ handle: &StoreHandle,
catalog: &CatalogHandle,
sink: &Arc<dyn MembershipSink>,
merge: &MergeWorkerDeps,
@@ -153,8 +153,42 @@ pub(crate) async fn handle_merge(
) {
let msg_coords = (partition_id as i32, offset);
- // Drain against empty filters when the team is absent to avoid wedging.
- let snapshot = catalog.load();
+ // One snapshot serves both resolutions below; `filters` falls back to empty when the team is
+ // absent, so the drain never wedges on an unknown team.
+ let snapshot = catalog.load_full();
+
+ // The whole drain state machine runs as one sync section on the blocking pool with owned inputs.
+ let section = {
+ let snapshot = snapshot.clone();
+ let event_owned = event.clone();
+ let partition_count = merge.partition_count;
+ handle
+ .run_section("merge_drain", move |store| {
+ let fallback: TeamFilters;
+ let filters: &TeamFilters = match snapshot.team(TeamId(event_owned.team_id)) {
+ Some(team) => team,
+ None => {
+ fallback = empty_team_filters();
+ &fallback
+ }
+ };
+ // Timed inside the section so the histogram keeps measuring drain execution only;
+ // permit and pool-queue waits are on `store_offload_*{op="merge_drain"}`.
+ let started = Instant::now();
+ let outcome = handle_merge_event(
+ partition_id,
+ store,
+ filters,
+ &event_owned,
+ msg_coords,
+ partition_count,
+ );
+ histogram!(MERGE_DRAIN_DURATION_SECONDS).record(started.elapsed().as_secs_f64());
+ outcome
+ })
+ .await
+ };
+
let fallback: TeamFilters;
let filters: &TeamFilters = match snapshot.team(TeamId(event.team_id)) {
Some(team) => team,
@@ -164,17 +198,20 @@ pub(crate) async fn handle_merge(
}
};
- let started = Instant::now();
- let outcome = handle_merge_event(
- partition_id,
- store,
- filters,
- event,
- msg_coords,
- queue,
- merge.partition_count,
- );
- histogram!(MERGE_DRAIN_DURATION_SECONDS).record(started.elapsed().as_secs_f64());
+ // The section is only `Err` on teardown cancellation; hold the offset so the next tenure's
+ // redelivery resolves the merge.
+ let outcome = match section {
+ Ok(outcome) => outcome,
+ Err(_cancelled) => {
+ warn!(
+ partition_id,
+ team_id = event.team_id,
+ "merge drain offloaded section cancelled by shutdown; holding the merge offset for redelivery",
+ );
+ hold(&merge.merge_tracker, partition_id, offset);
+ return;
+ }
+ };
let pending_key = PendingTransferKey {
partition_id,
@@ -182,10 +219,15 @@ pub(crate) async fn handle_merge(
old_person: event.old_person_uuid,
};
match outcome {
- Ok(DrainOutcome::FastPath { transitions }) => {
+ Ok(DrainOutcome::FastPath {
+ transitions,
+ effects,
+ }) => {
+ // The drain's atomic write has committed; sync the queue before any produce.
+ effects.apply_to(queue);
produce_merge_transitions(
partition_id,
- store,
+ handle,
sink,
merge,
filters,
@@ -197,52 +239,55 @@ pub(crate) async fn handle_merge(
.await;
mark_processed(&merge.merge_tracker, partition_id, offset);
}
- Ok(DrainOutcome::Drained { transfer }) => {
+ Ok(DrainOutcome::Drained { transfer, effects }) => {
+ effects.apply_to(queue);
if transfer.leaves.is_empty() {
counter!(MERGE_TRANSFERS_SKIPPED_EMPTY_TOTAL).increment(1);
mark_processed(&merge.merge_tracker, partition_id, offset);
return;
}
- produce_and_settle(partition_id, store, merge, &transfer, &pending_key, offset).await;
+ produce_and_settle(partition_id, handle, merge, &transfer, &pending_key, offset).await;
}
- Ok(DrainOutcome::AlreadyDrained) => match store.get_pending_transfer(&pending_key) {
- Ok(None) => mark_processed(&merge.merge_tracker, partition_id, offset),
- Ok(Some(bytes)) => match PendingTransfer::decode(&bytes) {
- Ok(pending) => {
- produce_and_settle(
- partition_id,
- store,
- merge,
- &pending.transfer,
- &pending_key,
- offset,
- )
- .await;
- }
+ Ok(DrainOutcome::AlreadyDrained) => {
+ match handle.get_pending_transfer(&pending_key).await {
+ Ok(None) => mark_processed(&merge.merge_tracker, partition_id, offset),
+ Ok(Some(bytes)) => match PendingTransfer::decode(&bytes) {
+ Ok(pending) => {
+ produce_and_settle(
+ partition_id,
+ handle,
+ merge,
+ &pending.transfer,
+ &pending_key,
+ offset,
+ )
+ .await;
+ }
+ Err(error) => {
+ warn!(
+ partition_id,
+ team_id = event.team_id,
+ old_person = %event.old_person_uuid,
+ error = %error,
+ "pending transfer failed to decode; committing past it (entry left for the redrive to surface)",
+ );
+ mark_processed(&merge.merge_tracker, partition_id, offset);
+ }
+ },
Err(error) => {
+ // Category A: the outbox read itself failed, so we cannot re-produce the staged
+ // transfer this pass and have no other handle on it — a sticky hold redelivers the
+ // merge so a later pass (or the next tenure) can resolve it.
warn!(
partition_id,
team_id = event.team_id,
- old_person = %event.old_person_uuid,
error = %error,
- "pending transfer failed to decode; committing past it (entry left for the redrive to surface)",
+ "pending transfer read failed; holding the merge offset for redelivery",
);
- mark_processed(&merge.merge_tracker, partition_id, offset);
+ hold(&merge.merge_tracker, partition_id, offset);
}
- },
- Err(error) => {
- // Category A: the outbox read itself failed, so we cannot re-produce the staged
- // transfer this pass and have no other handle on it — a sticky hold redelivers the
- // merge so a later pass (or the next tenure) can resolve it.
- warn!(
- partition_id,
- team_id = event.team_id,
- error = %error,
- "pending transfer read failed; holding the merge offset for redelivery",
- );
- hold(&merge.merge_tracker, partition_id, offset);
}
- },
+ }
Ok(DrainOutcome::Skipped(_)) => {
mark_processed(&merge.merge_tracker, partition_id, offset);
}
@@ -266,7 +311,7 @@ pub(crate) async fn handle_merge(
#[allow(clippy::too_many_arguments)]
pub(crate) async fn handle_apply(
partition_id: u16,
- store: &CohortStore,
+ handle: &StoreHandle,
catalog: &CatalogHandle,
sink: &Arc<dyn MembershipSink>,
merge: &MergeWorkerDeps,
@@ -277,7 +322,40 @@ pub(crate) async fn handle_apply(
) {
let transfer_coords = (partition_id as i32, offset);
- let snapshot = catalog.load();
+ let snapshot = catalog.load_full();
+
+ // The whole apply state machine runs as one sync section on the blocking pool with owned inputs.
+ let section = {
+ let snapshot = snapshot.clone();
+ let transfer_owned = transfer.clone();
+ let partition_count = merge.partition_count;
+ handle
+ .run_section("merge_apply", move |store| {
+ let fallback: TeamFilters;
+ let filters: &TeamFilters = match snapshot.team(TeamId(transfer_owned.team_id)) {
+ Some(team) => team,
+ None => {
+ fallback = empty_team_filters();
+ &fallback
+ }
+ };
+ // Timed inside the section so the histogram keeps measuring apply execution only;
+ // permit and pool-queue waits are on `store_offload_*{op="merge_apply"}`.
+ let started = Instant::now();
+ let outcome = handle_transfer(
+ partition_id,
+ store,
+ filters,
+ &transfer_owned,
+ transfer_coords,
+ partition_count,
+ );
+ histogram!(MERGE_APPLY_DURATION_SECONDS).record(started.elapsed().as_secs_f64());
+ outcome
+ })
+ .await
+ };
+
let fallback: TeamFilters;
let filters: &TeamFilters = match snapshot.team(TeamId(transfer.team_id)) {
Some(team) => team,
@@ -287,23 +365,29 @@ pub(crate) async fn handle_apply(
}
};
- let started = Instant::now();
- let outcome = handle_transfer(
- partition_id,
- store,
- filters,
- transfer,
- transfer_coords,
- queue,
- merge.partition_count,
- );
- histogram!(MERGE_APPLY_DURATION_SECONDS).record(started.elapsed().as_secs_f64());
+ let outcome = match section {
+ Ok(outcome) => outcome,
+ Err(_cancelled) => {
+ warn!(
+ partition_id,
+ team_id = transfer.team_id,
+ "transfer apply offloaded section cancelled by shutdown; holding the transfer offset for redelivery",
+ );
+ hold(&merge.transfer_tracker, partition_id, offset);
+ return;
+ }
+ };
match outcome {
- Ok(ApplyOutcome::Applied { transitions }) => {
+ Ok(ApplyOutcome::Applied {
+ transitions,
+ effects,
+ }) => {
+ // The apply's atomic write has committed; sync the queue before any produce.
+ effects.apply_to(queue);
produce_merge_transitions(
partition_id,
- store,
+ handle,
sink,
merge,
filters,
@@ -385,21 +469,25 @@ const SCAN_PENDING_TRANSFERS_LIMIT: usize = REDRIVE_MAX_ATTEMPTS_PER_TICK * 8;
pub(crate) async fn handle_redrive(
partition_id: u16,
- store: &CohortStore,
+ handle: &StoreHandle,
merge: &MergeWorkerDeps,
) {
- let entries =
- match store.scan_pending_transfers(partition_id, None, SCAN_PENDING_TRANSFERS_LIMIT) {
- Ok(entries) => entries,
- Err(error) => {
- warn!(
- partition_id,
- error = %error,
- "pending-transfer redrive scan failed; retrying next tick",
- );
- return;
- }
- };
+ // Per-op through the facade, not one section: each produce interleaves with a store clear, and a
+ // section would serialize the whole tick's Kafka round-trips on one blocking thread.
+ let entries = match handle
+ .scan_pending_transfers(partition_id, None, SCAN_PENDING_TRANSFERS_LIMIT)
+ .await
+ {
+ Ok(entries) => entries,
+ Err(error) => {
+ warn!(
+ partition_id,
+ error = %error,
+ "pending-transfer redrive scan failed; retrying next tick",
+ );
+ return;
+ }
+ };
// Saturates at the scan limit, so this reflects `min(backlog, SCAN_PENDING_TRANSFERS_LIMIT)` — it
// still distinguishes an empty outbox from a backed-up one, just not the exact backlog depth.
gauge!(MERGE_PENDING_TRANSFERS_GAUGE, "partition" => partition_id.to_string())
@@ -440,7 +528,7 @@ pub(crate) async fn handle_redrive(
);
continue;
}
- if let Err(error) = store.clear_pending_transfer(&key) {
+ if let Err(error) = handle.clear_pending_transfer(&key).await {
counter!(MERGE_OUTBOX_CLEAR_FAILURE_TOTAL).increment(1);
warn!(
partition_id,
@@ -458,7 +546,7 @@ pub(crate) async fn handle_redrive(
/// Produce `transfer` with inline retry; on ack clear its outbox slot and mark the merge offset.
async fn produce_and_settle(
partition_id: u16,
- store: &CohortStore,
+ handle: &StoreHandle,
merge: &MergeWorkerDeps,
transfer: &MergeStateTransfer,
pending_key: &PendingTransferKey,
@@ -481,7 +569,7 @@ async fn produce_and_settle(
);
return;
}
- if let Err(error) = store.clear_pending_transfer(pending_key) {
+ if let Err(error) = handle.clear_pending_transfer(pending_key).await {
counter!(MERGE_OUTBOX_CLEAR_FAILURE_TOTAL).increment(1);
warn!(
partition_id,
@@ -525,7 +613,7 @@ async fn produce_transfer_with_retry(
#[allow(clippy::too_many_arguments)]
async fn produce_merge_transitions(
partition_id: u16,
- store: &CohortStore,
+ handle: &StoreHandle,
sink: &Arc<dyn MembershipSink>,
merge: &MergeWorkerDeps,
filters: &TeamFilters,
@@ -546,12 +634,14 @@ async fn produce_merge_transitions(
}
match compose_stage2(
partition_id,
- store,
+ handle,
filters,
transitions,
merged_at_ms,
last_updated,
- ) {
+ )
+ .await
+ {
Ok(stage2_changes) => changes.extend(stage2_changes),
Err(error) => warn!(
partition_id,
@@ -613,6 +703,9 @@ fn empty_team_filters() -> TeamFilters {
}
#[cfg(test)]
+// Tests seed and assert against `CohortStore` directly while driving `handle_redrive` through the
+// `StoreHandle` facade.
+#[allow(clippy::disallowed_methods)]
mod tests {
use super::*;
use envconfig::Envconfig;
@@ -622,7 +715,19 @@ mod tests {
use crate::merge::transfer::TransferLeaf;
use crate::stage1::key::LeafStateKey;
use crate::stage1::state::{AppliedOffsets, Stage1State, StatefulRecord};
- use crate::store::StoreConfig;
+ use crate::store::{CohortStore, OffloadConfig, OffloadMode, StoreConfig};
+
+ /// Wrap a test store in the `All` operating point so `handle_redrive` runs on the blocking pool.
+ fn handle(store: &CohortStore) -> StoreHandle {
+ StoreHandle::new(
+ store.clone(),
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ )
+ }
#[test]
fn default_retry_policy_budget() {
@@ -815,7 +920,7 @@ mod tests {
deps.merge_tracker
.mark_dispatched(REDRIVE_PARTITION as i32, 42);
- handle_redrive(REDRIVE_PARTITION, &store, &deps).await;
+ handle_redrive(REDRIVE_PARTITION, &handle(&store), &deps).await;
assert_eq!(sink.transfers(), vec![pending.transfer]);
assert!(
@@ -842,7 +947,7 @@ mod tests {
deps.merge_tracker
.mark_dispatched(REDRIVE_PARTITION as i32, 42);
- handle_redrive(REDRIVE_PARTITION, &store, &deps).await;
+ handle_redrive(REDRIVE_PARTITION, &handle(&store), &deps).await;
assert!(sink.transfers().is_empty());
assert!(store.get_pending_transfer(&key).unwrap().is_some());
assert!(
@@ -850,7 +955,7 @@ mod tests {
"a failed redrive marks nothing",
);
- handle_redrive(REDRIVE_PARTITION, &store, &deps).await;
+ handle_redrive(REDRIVE_PARTITION, &handle(&store), &deps).await;
assert_eq!(sink.transfers(), vec![pending.transfer]);
assert!(store.get_pending_transfer(&key).unwrap().is_none());
assert_eq!(
@@ -871,7 +976,7 @@ mod tests {
.mark_dispatched(REDRIVE_PARTITION as i32, 42);
let before = tokio::time::Instant::now();
- handle_redrive(REDRIVE_PARTITION, &store, &deps).await;
+ handle_redrive(REDRIVE_PARTITION, &handle(&store), &deps).await;
assert_eq!(
tokio::time::Instant::now() - before,
@@ -898,7 +1003,7 @@ mod tests {
deps.merge_tracker
.mark_dispatched(REDRIVE_PARTITION as i32, 42);
- handle_redrive(REDRIVE_PARTITION, &store, &deps).await;
+ handle_redrive(REDRIVE_PARTITION, &handle(&store), &deps).await;
assert_eq!(
sink.transfers(),
@@ -929,7 +1034,7 @@ mod tests {
deps.merge_tracker
.mark_dispatched(REDRIVE_PARTITION as i32, 41 + backlog as i64);
- handle_redrive(REDRIVE_PARTITION, &store, &deps).await;
+ handle_redrive(REDRIVE_PARTITION, &handle(&store), &deps).await;
assert_eq!(
sink.transfers().len(),
REDRIVE_MAX_ATTEMPTS_PER_TICK,
@@ -945,7 +1050,7 @@ mod tests {
);
}
- handle_redrive(REDRIVE_PARTITION, &store, &deps).await;
+ handle_redrive(REDRIVE_PARTITION, &handle(&store), &deps).await;
assert_eq!(
sink.transfers().len(),
backlog,
diff --git a/rust/cohort-stream-processor/src/workers/stage2_gc.rs b/rust/cohort-stream-processor/src/workers/stage2_gc.rs
index 1a0d9a38d8c9..140f3dc6f8df 100644
--- a/rust/cohort-stream-processor/src/workers/stage2_gc.rs
+++ b/rust/cohort-stream-processor/src/workers/stage2_gc.rs
@@ -38,6 +38,9 @@ pub struct Stage2GcCursor(Option<Vec<u8>>);
/// GC one partition's `cf_stage2` orphans for one tick: scan up to `scan_limit` rows, delete every
/// row whose cohort is no longer composable in `catalog`, and advance the cursor (wrapping on
/// exhaustion). A no-op before the first catalog load or against an empty catalog (the two safety gates).
+// Sync GC core; runs on the blocking pool inside `StoreHandle::run_section`, so its direct
+// `CohortStore` I/O is already off the runtime threads.
+#[allow(clippy::disallowed_methods)]
pub fn handle_stage2_orphan_gc(
partition_id: u16,
store: &CohortStore,
@@ -148,7 +151,9 @@ fn is_orphan(snapshot: &FilterCatalog, key: &Stage2Key) -> Option<bool> {
Some(!live)
}
+// Tests seed and read stage-2 rows directly against the store.
#[cfg(test)]
+#[allow(clippy::disallowed_methods)]
mod tests {
use super::*;
use tempfile::TempDir;
diff --git a/rust/cohort-stream-processor/src/workers/stage2_path.rs b/rust/cohort-stream-processor/src/workers/stage2_path.rs
index 1df240c5e8fb..38697ece8d06 100644
--- a/rust/cohort-stream-processor/src/workers/stage2_path.rs
+++ b/rust/cohort-stream-processor/src/workers/stage2_path.rs
@@ -23,11 +23,11 @@ use crate::stage1::transition::LeafTransition;
use crate::stage2::evaluator::{evaluate_tree, leaf_membership};
use crate::stage2::state::Stage2State;
use crate::stage2::CohortEligibility;
-use crate::store::{CohortStore, Stage2Key, StoreError};
+use crate::store::{ReadLane, Stage2Key, StagedBatch, StoreError, StoreHandle};
-pub fn compose_stage2(
+pub async fn compose_stage2(
partition_id: u16,
- store: &CohortStore,
+ handle: &StoreHandle,
filters: &TeamFilters,
transitions: &[LeafTransition],
event_ms: i64,
@@ -57,7 +57,7 @@ pub fn compose_stage2(
continue;
};
- let diff = recompute_and_diff(partition_id, person_id, tree, filters, store)?;
+ let diff = recompute_and_diff(partition_id, person_id, tree, filters, handle).await?;
evaluated += 1;
if !diff.flipped() {
continue;
@@ -81,11 +81,11 @@ pub fn compose_stage2(
}
if !pending.is_empty() {
- store.write_batch(|batch| {
- for (key, state) in &pending {
- batch.put_stage2(key, &state.encode());
- }
- })?;
+ let mut staged = StagedBatch::default();
+ for (key, state) in &pending {
+ staged.put_stage2(key, &state.encode());
+ }
+ handle.commit(staged).await?;
}
counter!(STAGE2_COHORTS_EVALUATED).increment(evaluated);
@@ -120,22 +120,22 @@ impl RecomputeDiff {
/// Recompute one cohort's membership and diff against the stored `cf_stage2` bit. Reads only — the
/// caller stages the write, so it owns the produce/commit ordering.
-pub(crate) fn recompute_and_diff(
+pub(crate) async fn recompute_and_diff(
partition_id: u16,
person_id: Uuid,
tree: &CohortTree,
filters: &TeamFilters,
- store: &CohortStore,
+ handle: &StoreHandle,
) -> Result<RecomputeDiff, StoreError> {
let team_id = tree.team_id.0 as u64;
- let new_bit = evaluate_cohort(partition_id, team_id, person_id, tree, filters, store)?;
+ let new_bit = evaluate_cohort(partition_id, team_id, person_id, tree, filters, handle).await?;
let stage2_key = Stage2Key {
partition_id,
team_id,
cohort_id: tree.cohort_id.0 as u64,
person_id,
};
- let prior_bit = read_stage2_bit(store, &stage2_key)?;
+ let prior_bit = read_stage2_bit(handle, &stage2_key).await?;
Ok(RecomputeDiff {
new_bit,
prior_bit,
@@ -145,13 +145,13 @@ pub(crate) fn recompute_and_diff(
/// Compose one cohort for one person. A leaf with absent or undecodable state reads as non-member;
/// a cohort-reference leaf reads the referenced cohort's stored membership (see [`resolve_ref_membership`]).
-fn evaluate_cohort(
+async fn evaluate_cohort(
partition_id: u16,
team_id: u64,
person_id: Uuid,
tree: &CohortTree,
filters: &TeamFilters,
- store: &CohortStore,
+ handle: &StoreHandle,
) -> Result<bool, StoreError> {
let mut lsks = Vec::new();
collect_leaf_state_keys(&tree.root, &mut lsks);
@@ -165,7 +165,7 @@ fn evaluate_cohort(
person_id,
})
.collect();
- let raw = store.multi_get_stage1(&keys)?;
+ let raw = handle.multi_get_stage1(keys, ReadLane::Event).await?;
let mut membership: HashMap<LeafStateKey, bool> = HashMap::with_capacity(lsks.len());
for (lsk, bytes) in lsks.iter().zip(raw) {
@@ -177,7 +177,7 @@ fn evaluate_cohort(
}
let ref_membership =
- resolve_ref_membership(partition_id, team_id, person_id, tree, filters, store)?;
+ resolve_ref_membership(partition_id, team_id, person_id, tree, filters, handle).await?;
Ok(evaluate_tree(&tree.root, &membership, &ref_membership))
}
@@ -186,13 +186,13 @@ fn evaluate_cohort(
/// A `SingleLeaf` referent is read from `cf_stage1` via [`leaf_membership`] (so its comparator
/// applies); a composable referent from its stored `cf_stage2` bit; anything else as non-member.
/// One batched read per store.
-fn resolve_ref_membership(
+async fn resolve_ref_membership(
partition_id: u16,
team_id: u64,
person_id: Uuid,
tree: &CohortTree,
filters: &TeamFilters,
- store: &CohortStore,
+ handle: &StoreHandle,
) -> Result<HashMap<CohortId, bool>, StoreError> {
let mut ref_ids = Vec::new();
collect_cohort_refs(&tree.root, &mut ref_ids);
@@ -226,7 +226,7 @@ fn resolve_ref_membership(
person_id,
})
.collect();
- let raw = store.multi_get_stage1(&keys)?;
+ let raw = handle.multi_get_stage1(keys, ReadLane::Event).await?;
for ((ref_id, lsk), bytes) in single_leaf_refs.iter().zip(raw) {
let bit = filters
.by_lsk
@@ -247,7 +247,7 @@ fn resolve_ref_membership(
person_id,
})
.collect();
- let raw = store.multi_get_stage2(&keys)?;
+ let raw = handle.multi_get_stage2(keys).await?;
for (ref_id, bytes) in composable_refs.iter().zip(raw) {
ref_membership.insert(*ref_id, decode_stage2_bit(bytes));
}
@@ -269,8 +269,8 @@ fn decode_stage1_state(bytes: Option<Vec<u8>>) -> Option<Stage1State> {
}
/// The stored `cf_stage2` membership bit for `key`, `false` when absent or undecodable.
-fn read_stage2_bit(store: &CohortStore, key: &Stage2Key) -> Result<bool, StoreError> {
- Ok(decode_stage2_bit(store.get_stage2(key)?))
+async fn read_stage2_bit(handle: &StoreHandle, key: &Stage2Key) -> Result<bool, StoreError> {
+ Ok(decode_stage2_bit(handle.get_stage2(key).await?))
}
/// Decode a `cf_stage2` value into its membership bit, `false` when absent or undecodable.
@@ -318,6 +318,8 @@ fn collect_cohort_refs(node: &FilterNode, out: &mut Vec<CohortId>) {
}
#[cfg(test)]
+// Tests seed the store directly through `CohortStore`, the sanctioned direct-store surface for tests.
+#[allow(clippy::disallowed_methods)]
mod tests {
use super::*;
use chrono_tz::UTC;
@@ -328,7 +330,7 @@ mod tests {
use crate::filters::{CohortId, TeamFiltersBuilder, TeamId};
use crate::stage1::state::AppliedOffsets;
use crate::stage1::transition::TransitionKind;
- use crate::store::StoreConfig;
+ use crate::store::{CohortStore, OffloadConfig, OffloadMode, StoreConfig};
const TEAM: u64 = 7;
const PARTITION: u16 = 0;
@@ -347,6 +349,18 @@ mod tests {
(dir, store)
}
+ /// Wraps the store so the compose paths exercise the same blocking-pool transport as production.
+ fn handle(store: &CohortStore) -> StoreHandle {
+ StoreHandle::new(
+ store.clone(),
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ )
+ }
+
fn behavioral_leaf(window_days: i64) -> Value {
json!({
"type": "behavioral", "value": "performed_event", "key": "$pageview",
@@ -462,8 +476,8 @@ mod tests {
)
}
- #[test]
- fn entered_when_the_and_is_satisfied() {
+ #[tokio::test]
+ async fn entered_when_the_and_is_satisfied() {
let (_dir, store) = temp_store();
let filters = freeze(vec![behavioral_leaf(7), person_leaf()]);
let (beh_lsk, per_lsk) = and_leaf_keys(&filters);
@@ -474,12 +488,13 @@ mod tests {
let changes = compose_stage2(
PARTITION,
- &store,
+ &handle(&store),
&filters,
&[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
EVENT_MS,
TS,
)
+ .await
.unwrap();
assert_eq!(changes.len(), 1);
@@ -491,8 +506,8 @@ mod tests {
assert_eq!(stage2_bit(&store, 1, alice), Some(true), "bit committed");
}
- #[test]
- fn no_emit_until_the_second_leaf_flips() {
+ #[tokio::test]
+ async fn no_emit_until_the_second_leaf_flips() {
let (_dir, store) = temp_store();
let filters = freeze(vec![behavioral_leaf(7), person_leaf()]);
let (beh_lsk, per_lsk) = and_leaf_keys(&filters);
@@ -501,12 +516,13 @@ mod tests {
write_stage1(&store, beh_lsk, alice, behavioral_match());
let phase_a = compose_stage2(
PARTITION,
- &store,
+ &handle(&store),
&filters,
&[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
EVENT_MS,
TS,
)
+ .await
.unwrap();
assert!(phase_a.is_empty(), "one leaf does not satisfy the AND");
assert_eq!(
@@ -518,7 +534,7 @@ mod tests {
write_stage1(&store, per_lsk, alice, person_state(true));
let phase_b = compose_stage2(
PARTITION,
- &store,
+ &handle(&store),
&filters,
&[transition(
per_lsk,
@@ -529,14 +545,15 @@ mod tests {
EVENT_MS,
TS,
)
+ .await
.unwrap();
assert_eq!(phase_b.len(), 1);
assert_eq!(phase_b[0].status, MembershipStatus::Entered);
assert_eq!(stage2_bit(&store, 1, alice), Some(true));
}
- #[test]
- fn left_when_a_leaf_drops() {
+ #[tokio::test]
+ async fn left_when_a_leaf_drops() {
let (_dir, store) = temp_store();
let filters = freeze(vec![behavioral_leaf(7), person_leaf()]);
let (beh_lsk, per_lsk) = and_leaf_keys(&filters);
@@ -546,12 +563,13 @@ mod tests {
write_stage1(&store, per_lsk, alice, person_state(true));
let entered = compose_stage2(
PARTITION,
- &store,
+ &handle(&store),
&filters,
&[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
EVENT_MS,
TS,
)
+ .await
.unwrap();
assert_eq!(entered.len(), 1);
assert_eq!(entered[0].status, MembershipStatus::Entered);
@@ -559,7 +577,7 @@ mod tests {
write_stage1(&store, per_lsk, alice, person_state(false));
let left = compose_stage2(
PARTITION,
- &store,
+ &handle(&store),
&filters,
&[transition(
per_lsk,
@@ -570,6 +588,7 @@ mod tests {
EVENT_MS,
TS,
)
+ .await
.unwrap();
assert_eq!(left.len(), 1);
assert_eq!(left[0].status, MembershipStatus::Left);
@@ -580,8 +599,8 @@ mod tests {
);
}
- #[test]
- fn idempotent_re_evaluation_emits_once() {
+ #[tokio::test]
+ async fn idempotent_re_evaluation_emits_once() {
let (_dir, store) = temp_store();
let filters = freeze(vec![behavioral_leaf(7), person_leaf()]);
let (beh_lsk, per_lsk) = and_leaf_keys(&filters);
@@ -591,23 +610,25 @@ mod tests {
let first = compose_stage2(
PARTITION,
- &store,
+ &handle(&store),
&filters,
&[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
EVENT_MS,
TS,
)
+ .await
.unwrap();
assert_eq!(first.len(), 1, "the first evaluation enters");
let second = compose_stage2(
PARTITION,
- &store,
+ &handle(&store),
&filters,
&[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
EVENT_MS,
TS,
)
+ .await
.unwrap();
assert!(
second.is_empty(),
@@ -615,8 +636,8 @@ mod tests {
);
}
- #[test]
- fn dedups_when_one_event_flips_two_leaves_of_one_cohort() {
+ #[tokio::test]
+ async fn dedups_when_one_event_flips_two_leaves_of_one_cohort() {
let (_dir, store) = temp_store();
let filters = freeze(vec![behavioral_leaf(7), behavioral_leaf(30)]);
let lsks = &filters.by_condition_to_lsk[&HASH];
@@ -627,7 +648,7 @@ mod tests {
let changes = compose_stage2(
PARTITION,
- &store,
+ &handle(&store),
&filters,
&[
transition(lsks[0], alice, HASH, TransitionKind::Entered),
@@ -636,6 +657,7 @@ mod tests {
EVENT_MS,
TS,
)
+ .await
.unwrap();
assert_eq!(
@@ -646,8 +668,8 @@ mod tests {
assert_eq!(changes[0].status, MembershipStatus::Entered);
}
- #[test]
- fn composes_a_performed_event_multiple_leaf_via_variant_dispatch() {
+ #[tokio::test]
+ async fn composes_a_performed_event_multiple_leaf_via_variant_dispatch() {
let (_dir, store) = temp_store();
let filters = freeze(vec![daily_leaf(7, "gte", 2), person_leaf()]);
let beh_lsk = filters.by_condition_to_lsk[&HASH][0];
@@ -658,12 +680,13 @@ mod tests {
let changes = compose_stage2(
PARTITION,
- &store,
+ &handle(&store),
&filters,
&[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
EVENT_MS,
TS,
)
+ .await
.unwrap();
assert_eq!(
changes.len(),
@@ -678,12 +701,13 @@ mod tests {
write_stage1(&store2, per_lsk, alice, person_state(true));
let below = compose_stage2(
PARTITION,
- &store2,
+ &handle(&store2),
&filters,
&[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
EVENT_MS,
TS,
)
+ .await
.unwrap();
assert!(
below.is_empty(),
@@ -691,8 +715,8 @@ mod tests {
);
}
- #[test]
- fn transitions_touching_no_composable_cohort_emit_nothing() {
+ #[tokio::test]
+ async fn transitions_touching_no_composable_cohort_emit_nothing() {
let (_dir, store) = temp_store();
let filters = freeze(vec![behavioral_leaf(7)]);
let beh_lsk = filters.by_condition_to_lsk[&HASH][0];
@@ -701,12 +725,13 @@ mod tests {
let changes = compose_stage2(
PARTITION,
- &store,
+ &handle(&store),
&filters,
&[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
EVENT_MS,
TS,
)
+ .await
.unwrap();
assert!(
changes.is_empty(),
@@ -723,8 +748,8 @@ mod tests {
})
}
- #[test]
- fn negated_leaf_absent_means_entered() {
+ #[tokio::test]
+ async fn negated_leaf_absent_means_entered() {
let (_dir, store) = temp_store();
let filters = freeze(vec![behavioral_leaf(7), negated_person_leaf()]);
let (beh_lsk, _per_lsk) = and_leaf_keys(&filters);
@@ -734,19 +759,20 @@ mod tests {
let changes = compose_stage2(
PARTITION,
- &store,
+ &handle(&store),
&filters,
&[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
EVENT_MS,
TS,
)
+ .await
.unwrap();
assert_eq!(changes.len(), 1);
assert_eq!(changes[0].status, MembershipStatus::Entered);
}
- #[test]
- fn negated_leaf_present_means_left() {
+ #[tokio::test]
+ async fn negated_leaf_present_means_left() {
let (_dir, store) = temp_store();
let filters = freeze(vec![behavioral_leaf(7), negated_person_leaf()]);
let (beh_lsk, per_lsk) = and_leaf_keys(&filters);
@@ -755,12 +781,13 @@ mod tests {
write_stage1(&store, beh_lsk, alice, behavioral_match());
let entered = compose_stage2(
PARTITION,
- &store,
+ &handle(&store),
&filters,
&[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
EVENT_MS,
TS,
)
+ .await
.unwrap();
assert_eq!(entered.len(), 1);
assert_eq!(entered[0].status, MembershipStatus::Entered);
@@ -768,7 +795,7 @@ mod tests {
write_stage1(&store, per_lsk, alice, person_state(true));
let left = compose_stage2(
PARTITION,
- &store,
+ &handle(&store),
&filters,
&[transition(
per_lsk,
@@ -779,6 +806,7 @@ mod tests {
EVENT_MS,
TS,
)
+ .await
.unwrap();
assert_eq!(left.len(), 1);
assert_eq!(left[0].status, MembershipStatus::Left);
@@ -830,15 +858,15 @@ mod tests {
}
/// Compose after flipping cohort 1's own person leaf.
- fn compose_referrer_on_own_leaf(
- store: &CohortStore,
+ async fn compose_referrer_on_own_leaf(
+ handle: &StoreHandle,
filters: &TeamFilters,
who: Uuid,
) -> Vec<CohortMembershipChange> {
let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);
compose_stage2(
PARTITION,
- store,
+ handle,
filters,
&[transition(
per_lsk,
@@ -849,11 +877,12 @@ mod tests {
EVENT_MS,
TS,
)
+ .await
.unwrap()
}
- #[test]
- fn composable_ref_reads_a_single_leaf_referent_from_cf_stage1_via_its_op() {
+ #[tokio::test]
+ async fn composable_ref_reads_a_single_leaf_referent_from_cf_stage1_via_its_op() {
let filters = freeze_cascade(
vec![
(2, vec![daily_leaf(7, "gte", 2)]),
@@ -873,7 +902,7 @@ mod tests {
let (_dir, store) = temp_store();
write_stage1(&store, ref2_lsk, alice, daily_state(2));
write_stage1(&store, per_lsk, alice, person_state(true));
- let entered = compose_referrer_on_own_leaf(&store, &filters, alice);
+ let entered = compose_referrer_on_own_leaf(&handle(&store), &filters, alice).await;
assert_eq!(entered.len(), 1);
assert_eq!(entered[0].cohort_id, 1);
assert_eq!(entered[0].status, MembershipStatus::Entered);
@@ -882,15 +911,15 @@ mod tests {
let (_dir2, store2) = temp_store();
write_stage1(&store2, ref2_lsk, alice, daily_state(1));
write_stage1(&store2, per_lsk, alice, person_state(true));
- let below = compose_referrer_on_own_leaf(&store2, &filters, alice);
+ let below = compose_referrer_on_own_leaf(&handle(&store2), &filters, alice).await;
assert!(
below.is_empty(),
"count 1 fails the referent's gte 2, so the referrer's AND is unsatisfied",
);
}
- #[test]
- fn composable_ref_reads_a_composable_referent_from_cf_stage2_verbatim() {
+ #[tokio::test]
+ async fn composable_ref_reads_a_composable_referent_from_cf_stage2_verbatim() {
let filters = freeze_cascade(
vec![
// Two distinct leaves make cohort 2 composable, so its membership lives in cf_stage2.
@@ -912,14 +941,14 @@ mod tests {
write_stage2(&store, 2, alice, true);
write_stage1(&store, per_lsk, alice, person_state(true));
- let entered = compose_referrer_on_own_leaf(&store, &filters, alice);
+ let entered = compose_referrer_on_own_leaf(&handle(&store), &filters, alice).await;
assert_eq!(entered.len(), 1);
assert_eq!(entered[0].cohort_id, 1);
assert_eq!(entered[0].status, MembershipStatus::Entered);
}
- #[test]
- fn composable_ref_absent_referent_reads_non_member() {
+ #[tokio::test]
+ async fn composable_ref_absent_referent_reads_non_member() {
let filters = freeze_cascade(
vec![
(2, vec![daily_leaf(7, "gte", 2)]),
@@ -932,15 +961,15 @@ mod tests {
let (_dir, store) = temp_store();
write_stage1(&store, per_lsk, alice, person_state(true));
- let changes = compose_referrer_on_own_leaf(&store, &filters, alice);
+ let changes = compose_referrer_on_own_leaf(&handle(&store), &filters, alice).await;
assert!(
changes.is_empty(),
"an absent referent reads as a non-member, so the AND is unsatisfied",
);
}
- #[test]
- fn composable_ref_negated_absent_referent_enters() {
+ #[tokio::test]
+ async fn composable_ref_negated_absent_referent_enters() {
let filters = freeze_cascade(
vec![
(2, vec![daily_leaf(7, "gte", 2)]),
@@ -958,14 +987,14 @@ mod tests {
// Referent 2 absent → negated ref reads true → Entered.
let (_dir, store) = temp_store();
write_stage1(&store, per_lsk, alice, person_state(true));
- let entered = compose_referrer_on_own_leaf(&store, &filters, alice);
+ let entered = compose_referrer_on_own_leaf(&handle(&store), &filters, alice).await;
assert_eq!(entered.len(), 1);
assert_eq!(entered[0].cohort_id, 1);
assert_eq!(entered[0].status, MembershipStatus::Entered);
}
- #[test]
- fn composable_ref_is_dormant_when_the_gate_is_off() {
+ #[tokio::test]
+ async fn composable_ref_is_dormant_when_the_gate_is_off() {
// Gate off: cohort 1 stays Excluded(HasCohortRef), is absent from the composable map, and
// emits nothing even though both its own leaf and the referent are satisfied.
let filters = freeze_cascade(
@@ -982,7 +1011,7 @@ mod tests {
let (_dir, store) = temp_store();
write_stage1(&store, ref2_lsk, alice, daily_state(2));
write_stage1(&store, per_lsk, alice, person_state(true));
- let changes = compose_referrer_on_own_leaf(&store, &filters, alice);
+ let changes = compose_referrer_on_own_leaf(&handle(&store), &filters, alice).await;
assert!(
changes.is_empty(),
"gate off: the ref cohort is not in the composable map, so compose_stage2 skips it",
diff --git a/rust/cohort-stream-processor/src/workers/sweep_callback.rs b/rust/cohort-stream-processor/src/workers/sweep_callback.rs
index b507f537dbb3..e27e3272f14c 100644
--- a/rust/cohort-stream-processor/src/workers/sweep_callback.rs
+++ b/rust/cohort-stream-processor/src/workers/sweep_callback.rs
@@ -1,9 +1,10 @@
//! Per-key time-driven eviction.
//!
-//! [`sweep_evict`] is a pure read-and-compute pass: for each due key it reads the stored state,
-//! drops aged-out bucket(s), recomputes the predicate, and returns the membership transition, state
-//! mutation, and next eviction deadline --- but writes nothing. The worker orchestrates
-//! produce-before-write ordering so a produce failure can replay against still-un-evicted state.
+//! [`sweep_evict`] is a pure compute pass over states the caller has already read: for each due key
+//! it drops aged-out bucket(s), recomputes the predicate, and returns the membership transition,
+//! state mutation, and next eviction deadline --- reading and writing nothing. The worker prefetches
+//! the states, orders produce before write (so a produce failure can replay against still-un-evicted
+//! state), and applies the resulting writes.
use chrono_tz::Tz;
use metrics::counter;
@@ -20,7 +21,6 @@ use crate::stage1::key::Stage1Key;
use crate::stage1::predicate::{compressed_predicate, daily_predicate, predicate};
use crate::stage1::state::{Stage1State, StateVariant, StatefulRecord};
use crate::stage1::transition::{LeafTransition, TransitionKind};
-use crate::store::{CohortStore, StoreError};
/// The state mutation an eviction implies.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -72,20 +72,22 @@ pub(crate) struct SweepEvictions {
pub drops: Vec<SweepDropReason>,
}
-/// Compute the eviction for each due key against a team's frozen filters, **without writing**.
-/// All `due_keys` must belong to `filters`' team.
+/// Compute the eviction for each due key against a team's frozen filters. `values` is aligned with
+/// `due_keys` (same order and length, `None` for an absent key). All `due_keys` must belong to
+/// `filters`' team. Pure: no reads, no writes.
pub(crate) fn sweep_evict(
filters: &TeamFilters,
due_keys: &[Stage1Key],
- store: &CohortStore,
+ values: Vec<Option<Vec<u8>>>,
due_before_ms: i64,
-) -> Result<SweepEvictions, StoreError> {
+) -> SweepEvictions {
let mut out = SweepEvictions {
results: Vec::with_capacity(due_keys.len()),
drops: Vec::new(),
};
- for &key in due_keys {
- let record = match store.get_stage1(&key)? {
+ // Alignment-safe zip: `multi_get_stage1` preserves input order, `None` for absent keys.
+ for (&key, bytes) in due_keys.iter().zip(values) {
+ let record = match bytes {
None => {
out.drops.push(SweepDropReason::MissingState);
continue;
@@ -118,7 +120,7 @@ pub(crate) fn sweep_evict(
Err(reason) => out.drops.push(reason),
}
}
- Ok(out)
+ out
}
/// Evict a `performed_event` single: always deletes.
@@ -311,7 +313,6 @@ mod tests {
use super::*;
use chrono_tz::UTC;
use serde_json::{json, Value};
- use tempfile::TempDir;
use uuid::Uuid;
use crate::filters::{CohortId, TeamFiltersBuilder, TeamId};
@@ -319,7 +320,6 @@ mod tests {
use crate::stage1::key::LeafStateKey;
use crate::stage1::state::AppliedOffsets;
use crate::stage1::time::clickhouse_timestamp_to_millis;
- use crate::store::StoreConfig;
const TEAM: u64 = 7;
const HASH: [u8; 16] = *b"0123456789abcdef";
@@ -329,16 +329,6 @@ mod tests {
const LEN: usize = WINDOW_DAYS as usize + 1;
const COMPRESSED_WINDOW_DAYS: u32 = 365;
- fn temp_store() -> (TempDir, CohortStore) {
- let dir = TempDir::new().unwrap();
- let store = CohortStore::open(&StoreConfig {
- path: dir.path().join("db"),
- ..StoreConfig::default()
- })
- .unwrap();
- (dir, store)
- }
-
fn freeze(values: Vec<Value>) -> TeamFilters {
let cohort = json!({ "properties": { "type": "AND", "values": values } });
let mut builder = TeamFiltersBuilder::default();
@@ -394,11 +384,9 @@ mod tests {
}
}
- fn write(store: &CohortStore, key: &Stage1Key, state: Stage1State) {
- let record = StatefulRecord::new(state, AppliedOffsets::default());
- store
- .write_batch(|b| b.put_stage1(key, &record.encode()))
- .unwrap();
+ /// `state` encoded as the worker's prefetch would hand it to `sweep_evict`.
+ fn encoded(state: Stage1State) -> Option<Vec<u8>> {
+ Some(StatefulRecord::new(state, AppliedOffsets::default()).encode())
}
fn day_of(ts: &str) -> i32 {
@@ -407,24 +395,17 @@ mod tests {
#[test]
fn single_eviction_emits_left_and_deletes() {
- let (_dir, store) = temp_store();
let filters = freeze(vec![single_leaf(7)]);
let key = key_for(&filters, 1);
let event_ms = clickhouse_timestamp_to_millis("2026-05-20 10:00:00.000000").unwrap();
let deadline = event_ms + 7 * 86_400 * 1_000;
- write(
- &store,
- &key,
- Stage1State::BehavioralSingle {
- has_match: true,
- last_event_at_ms: event_ms,
- earliest_eviction_at_ms: deadline,
- },
- );
+ let values = vec![encoded(Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: event_ms,
+ earliest_eviction_at_ms: deadline,
+ })];
- let results = sweep_evict(&filters, &[key], &store, deadline + 86_400_000)
- .unwrap()
- .results;
+ let results = sweep_evict(&filters, &[key], values, deadline + 86_400_000).results;
assert_eq!(results.len(), 1);
let result = &results[0];
assert_eq!(result.variant, StateVariant::BehavioralSingle);
@@ -442,7 +423,6 @@ mod tests {
#[test]
fn daily_all_buckets_drain_emits_left_and_deletes() {
- let (_dir, store) = temp_store();
let filters = freeze(vec![daily_leaf(7, "gte", 3)]);
let key = key_for(&filters, 1);
@@ -451,21 +431,15 @@ mod tests {
buckets[LEN - 1] = 3;
let window_start = day - WINDOW_DAYS as i32;
let deadline = daily_eviction_deadline(&buckets, window_start, WINDOW_DAYS, UTC);
- write(
- &store,
- &key,
- Stage1State::BehavioralDailyBuckets {
- buckets,
- window_start_day: window_start,
- last_event_at_ms: 1_700_000_000_000,
- earliest_eviction_at_ms: deadline,
- },
- );
+ let values = vec![encoded(Stage1State::BehavioralDailyBuckets {
+ buckets,
+ window_start_day: window_start,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: deadline,
+ })];
let cutoff = start_of_day_ms_in_tz(day + WINDOW_DAYS as i32 + 1, UTC);
- let results = sweep_evict(&filters, &[key], &store, cutoff)
- .unwrap()
- .results;
+ let results = sweep_evict(&filters, &[key], values, cutoff).results;
assert_eq!(results.len(), 1);
let result = &results[0];
assert_eq!(
@@ -478,7 +452,6 @@ mod tests {
#[test]
fn daily_drops_oldest_bucket_keeps_member_and_reschedules_later() {
- let (_dir, store) = temp_store();
let filters = freeze(vec![daily_leaf(7, "gte", 1)]);
let key = key_for(&filters, 1);
@@ -488,21 +461,15 @@ mod tests {
buckets[0] = 1; // day window_start
buckets[4] = 1; // day window_start + 4
let deadline = daily_eviction_deadline(&buckets, window_start, WINDOW_DAYS, UTC);
- write(
- &store,
- &key,
- Stage1State::BehavioralDailyBuckets {
- buckets,
- window_start_day: window_start,
- last_event_at_ms: 1_700_000_000_000,
- earliest_eviction_at_ms: deadline,
- },
- );
+ let values = vec![encoded(Stage1State::BehavioralDailyBuckets {
+ buckets,
+ window_start_day: window_start,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: deadline,
+ })];
let cutoff = start_of_day_ms_in_tz(window_start + WINDOW_DAYS as i32 + 1, UTC);
- let results = sweep_evict(&filters, &[key], &store, cutoff)
- .unwrap()
- .results;
+ let results = sweep_evict(&filters, &[key], values, cutoff).results;
assert_eq!(results.len(), 1);
let result = &results[0];
assert!(result.transition.is_none(), "still ≥ 1 match → no Left");
@@ -529,7 +496,6 @@ mod tests {
#[test]
fn daily_eq_slide_into_range_emits_entered() {
- let (_dir, store) = temp_store();
let filters = freeze(vec![daily_leaf(7, "eq", 1)]);
let key = key_for(&filters, 1);
@@ -539,21 +505,15 @@ mod tests {
buckets[0] = 1;
buckets[4] = 1;
let deadline = daily_eviction_deadline(&buckets, window_start, WINDOW_DAYS, UTC);
- write(
- &store,
- &key,
- Stage1State::BehavioralDailyBuckets {
- buckets,
- window_start_day: window_start,
- last_event_at_ms: 1_700_000_000_000,
- earliest_eviction_at_ms: deadline,
- },
- );
+ let values = vec![encoded(Stage1State::BehavioralDailyBuckets {
+ buckets,
+ window_start_day: window_start,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: deadline,
+ })];
let cutoff = start_of_day_ms_in_tz(window_start + WINDOW_DAYS as i32 + 1, UTC);
- let results = sweep_evict(&filters, &[key], &store, cutoff)
- .unwrap()
- .results;
+ let results = sweep_evict(&filters, &[key], values, cutoff).results;
assert_eq!(results.len(), 1);
let result = &results[0];
assert_eq!(
@@ -577,7 +537,6 @@ mod tests {
#[test]
fn daily_lte_slide_into_range_emits_entered() {
- let (_dir, store) = temp_store();
let filters = freeze(vec![daily_leaf(7, "lte", 2)]);
let key = key_for(&filters, 1);
@@ -587,21 +546,15 @@ mod tests {
buckets[0] = 1;
buckets[4] = 2;
let deadline = daily_eviction_deadline(&buckets, window_start, WINDOW_DAYS, UTC);
- write(
- &store,
- &key,
- Stage1State::BehavioralDailyBuckets {
- buckets,
- window_start_day: window_start,
- last_event_at_ms: 1_700_000_000_000,
- earliest_eviction_at_ms: deadline,
- },
- );
+ let values = vec![encoded(Stage1State::BehavioralDailyBuckets {
+ buckets,
+ window_start_day: window_start,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: deadline,
+ })];
let cutoff = start_of_day_ms_in_tz(window_start + WINDOW_DAYS as i32 + 1, UTC);
- let results = sweep_evict(&filters, &[key], &store, cutoff)
- .unwrap()
- .results;
+ let results = sweep_evict(&filters, &[key], values, cutoff).results;
assert_eq!(results.len(), 1);
let result = &results[0];
assert_eq!(
@@ -619,7 +572,6 @@ mod tests {
#[test]
fn compressed_all_entries_drain_emits_left_and_deletes() {
- let (_dir, store) = temp_store();
let filters = freeze(vec![compressed_leaf(
COMPRESSED_WINDOW_DAYS as i64,
"gte",
@@ -632,21 +584,15 @@ mod tests {
let window_start = day - COMPRESSED_WINDOW_DAYS as i32;
let deadline =
compressed_history::compressed_eviction_deadline(&entries, COMPRESSED_WINDOW_DAYS, UTC);
- write(
- &store,
- &key,
- Stage1State::BehavioralCompressedHistory {
- entries,
- window_start_day: window_start,
- last_event_at_ms: 1_700_000_000_000,
- earliest_eviction_at_ms: deadline,
- },
- );
+ let values = vec![encoded(Stage1State::BehavioralCompressedHistory {
+ entries,
+ window_start_day: window_start,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: deadline,
+ })];
let cutoff = start_of_day_ms_in_tz(day + COMPRESSED_WINDOW_DAYS as i32 + 1, UTC);
- let results = sweep_evict(&filters, &[key], &store, cutoff)
- .unwrap()
- .results;
+ let results = sweep_evict(&filters, &[key], values, cutoff).results;
assert_eq!(results.len(), 1);
let result = &results[0];
assert_eq!(result.variant, StateVariant::BehavioralCompressedHistory);
@@ -660,7 +606,6 @@ mod tests {
#[test]
fn compressed_drops_oldest_entry_keeps_member_and_reschedules_later() {
- let (_dir, store) = temp_store();
let filters = freeze(vec![compressed_leaf(
COMPRESSED_WINDOW_DAYS as i64,
"gte",
@@ -673,21 +618,15 @@ mod tests {
let entries = vec![(window_start, 1u32), (window_start + 100, 1u32)];
let deadline =
compressed_history::compressed_eviction_deadline(&entries, COMPRESSED_WINDOW_DAYS, UTC);
- write(
- &store,
- &key,
- Stage1State::BehavioralCompressedHistory {
- entries,
- window_start_day: window_start,
- last_event_at_ms: 1_700_000_000_000,
- earliest_eviction_at_ms: deadline,
- },
- );
+ let values = vec![encoded(Stage1State::BehavioralCompressedHistory {
+ entries,
+ window_start_day: window_start,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: deadline,
+ })];
let cutoff = start_of_day_ms_in_tz(window_start + COMPRESSED_WINDOW_DAYS as i32 + 1, UTC);
- let results = sweep_evict(&filters, &[key], &store, cutoff)
- .unwrap()
- .results;
+ let results = sweep_evict(&filters, &[key], values, cutoff).results;
assert_eq!(results.len(), 1);
let result = &results[0];
assert!(result.transition.is_none(), "still ≥ 1 match → no Left");
@@ -714,7 +653,6 @@ mod tests {
#[test]
fn compressed_eq_slide_into_range_emits_entered() {
- let (_dir, store) = temp_store();
let filters = freeze(vec![compressed_leaf(
COMPRESSED_WINDOW_DAYS as i64,
"eq",
@@ -727,21 +665,15 @@ mod tests {
let entries = vec![(window_start, 1u32), (window_start + 100, 1u32)];
let deadline =
compressed_history::compressed_eviction_deadline(&entries, COMPRESSED_WINDOW_DAYS, UTC);
- write(
- &store,
- &key,
- Stage1State::BehavioralCompressedHistory {
- entries,
- window_start_day: window_start,
- last_event_at_ms: 1_700_000_000_000,
- earliest_eviction_at_ms: deadline,
- },
- );
+ let values = vec![encoded(Stage1State::BehavioralCompressedHistory {
+ entries,
+ window_start_day: window_start,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: deadline,
+ })];
let cutoff = start_of_day_ms_in_tz(window_start + COMPRESSED_WINDOW_DAYS as i32 + 1, UTC);
- let results = sweep_evict(&filters, &[key], &store, cutoff)
- .unwrap()
- .results;
+ let results = sweep_evict(&filters, &[key], values, cutoff).results;
assert_eq!(results.len(), 1);
let result = &results[0];
assert_eq!(
@@ -762,7 +694,6 @@ mod tests {
#[test]
fn compressed_lte_slide_into_range_emits_entered() {
- let (_dir, store) = temp_store();
let filters = freeze(vec![compressed_leaf(
COMPRESSED_WINDOW_DAYS as i64,
"lte",
@@ -775,21 +706,15 @@ mod tests {
let entries = vec![(window_start, 1u32), (window_start + 100, 2u32)];
let deadline =
compressed_history::compressed_eviction_deadline(&entries, COMPRESSED_WINDOW_DAYS, UTC);
- write(
- &store,
- &key,
- Stage1State::BehavioralCompressedHistory {
- entries,
- window_start_day: window_start,
- last_event_at_ms: 1_700_000_000_000,
- earliest_eviction_at_ms: deadline,
- },
- );
+ let values = vec![encoded(Stage1State::BehavioralCompressedHistory {
+ entries,
+ window_start_day: window_start,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: deadline,
+ })];
let cutoff = start_of_day_ms_in_tz(window_start + COMPRESSED_WINDOW_DAYS as i32 + 1, UTC);
- let results = sweep_evict(&filters, &[key], &store, cutoff)
- .unwrap()
- .results;
+ let results = sweep_evict(&filters, &[key], values, cutoff).results;
assert_eq!(results.len(), 1);
let result = &results[0];
assert_eq!(
@@ -807,20 +732,15 @@ mod tests {
#[test]
fn daily_length_mismatch_skips_without_panic() {
- let (_dir, store) = temp_store();
let filters = freeze(vec![daily_leaf(7, "gte", 1)]); // expects length 8
let key = key_for(&filters, 1);
- write(
- &store,
- &key,
- Stage1State::BehavioralDailyBuckets {
- buckets: vec![1, 2, 3], // wrong length
- window_start_day: 100,
- last_event_at_ms: 1,
- earliest_eviction_at_ms: 2,
- },
- );
- let out = sweep_evict(&filters, &[key], &store, i64::MAX).unwrap();
+ let values = vec![encoded(Stage1State::BehavioralDailyBuckets {
+ buckets: vec![1, 2, 3], // wrong length
+ window_start_day: 100,
+ last_event_at_ms: 1,
+ earliest_eviction_at_ms: 2,
+ })];
+ let out = sweep_evict(&filters, &[key], values, i64::MAX);
assert!(
out.results.is_empty(),
"a length mismatch is skipped, not panicked"
@@ -834,7 +754,6 @@ mod tests {
#[test]
fn person_property_key_is_skipped() {
- let (_dir, store) = temp_store();
let filters = freeze(vec![person_leaf()]);
let key = Stage1Key {
partition_id: PARTITION,
@@ -842,16 +761,12 @@ mod tests {
leaf_state_key: LeafStateKey::for_person_property(&PERSON_HASH),
person_id: Uuid::from_u128(1),
};
- write(
- &store,
- &key,
- Stage1State::PersonProperty {
- matches: true,
- last_updated_at_ms: 1,
- last_updated_offset: 2,
- },
- );
- let out = sweep_evict(&filters, &[key], &store, i64::MAX).unwrap();
+ let values = vec![encoded(Stage1State::PersonProperty {
+ matches: true,
+ last_updated_at_ms: 1,
+ last_updated_offset: 2,
+ })];
+ let out = sweep_evict(&filters, &[key], values, i64::MAX);
assert!(
out.results.is_empty(),
"person-property leaves are never time-evicted",
@@ -865,7 +780,6 @@ mod tests {
#[test]
fn unknown_leaf_and_missing_state_are_skipped() {
- let (_dir, store) = temp_store();
let filters = freeze(vec![single_leaf(7)]);
let drifted = Stage1Key {
@@ -874,19 +788,18 @@ mod tests {
leaf_state_key: LeafStateKey([0xFF; 16]),
person_id: Uuid::from_u128(1),
};
- write(
- &store,
- &drifted,
- Stage1State::BehavioralSingle {
+ let missing = key_for(&filters, 999);
+ // The drifted key has state; the missing key reads back as `None`.
+ let values = vec![
+ encoded(Stage1State::BehavioralSingle {
has_match: true,
last_event_at_ms: 1,
earliest_eviction_at_ms: 2,
- },
- );
-
- let missing = key_for(&filters, 999);
+ }),
+ None,
+ ];
- let out = sweep_evict(&filters, &[drifted, missing], &store, i64::MAX).unwrap();
+ let out = sweep_evict(&filters, &[drifted, missing], values, i64::MAX);
assert!(
out.results.is_empty(),
"drift and missing rows both skip cleanly"
@@ -900,23 +813,19 @@ mod tests {
#[test]
fn evicts_multiple_keys_in_one_pass() {
- let (_dir, store) = temp_store();
let filters = freeze(vec![single_leaf(7)]);
let keys: Vec<Stage1Key> = (1..=3).map(|p| key_for(&filters, p)).collect();
- for key in &keys {
- write(
- &store,
- key,
- Stage1State::BehavioralSingle {
+ let values: Vec<Option<Vec<u8>>> = keys
+ .iter()
+ .map(|_| {
+ encoded(Stage1State::BehavioralSingle {
has_match: true,
last_event_at_ms: 1_000,
earliest_eviction_at_ms: 2_000,
- },
- );
- }
- let results = sweep_evict(&filters, &keys, &store, 10_000)
- .unwrap()
- .results;
+ })
+ })
+ .collect();
+ let results = sweep_evict(&filters, &keys, values, 10_000).results;
assert_eq!(results.len(), 3, "every member key evicts to a Left+Delete");
assert!(results
.iter()
diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rs
index 91c86289faca..a16451b85ef3 100644
--- a/rust/cohort-stream-processor/src/workers/worker.rs
+++ b/rust/cohort-stream-processor/src/workers/worker.rs
@@ -38,11 +38,11 @@ use crate::producer::{
use crate::stage1::key::Stage1Key;
use crate::stage1::state::{StateVariant, StatefulRecord};
use crate::stage1::transition::{LeafTransition, TransitionKind};
-use crate::store::{CohortStore, IndexOp, PersonIndexKey};
+use crate::store::{IndexOp, PersonIndexKey, ReadLane, StagedBatch, StoreHandle};
use crate::sweep::EvictionQueue;
use crate::workers::cascade_path::handle_cascade;
use crate::workers::event_path::{
- process_event_with_memo, schedule_deadline, EventNameGating, SkipReason,
+ process_event_offloaded, schedule_deadline, EventNameGating, SkipReason,
};
use crate::workers::merge_gc::{handle_merge_gc, MergeGcCursor};
use crate::workers::merge_path::{handle_apply, handle_merge, handle_redrive, MergeWorkerDeps};
@@ -59,6 +59,10 @@ const MAX_SWEEP_KEYS_PER_PASS: usize = 10_000;
const REBUILD_SCAN_PAGE: usize = 10_000;
+/// Chunk size for a team's sweep-state prefetch, so each `multi_get_stage1` spans a bounded number of
+/// keys and no single read op holds long before the sweep makes progress.
+const SWEEP_MULTI_GET_CHUNK: usize = 1024;
+
/// Cooperative-yield cadence inside the worker fold. `handle_event` is synchronous, so a backlog of
/// CPU-bound events would hold the runtime thread, starving the commit task and consume loop. A
/// wall-clock interval adapts to per-event cost across catalogs of different sizes.
@@ -75,7 +79,7 @@ impl Stage1Worker {
pub fn spawn(
partition_id: u16,
receiver: MeteredReceiver,
- store: CohortStore,
+ store: StoreHandle,
catalog: Arc<CatalogHandle>,
sink: Arc<dyn MembershipSink>,
tracker: Arc<OffsetTracker>,
@@ -102,7 +106,7 @@ impl Stage1Worker {
pub fn spawn_with_memo(
partition_id: u16,
receiver: MeteredReceiver,
- store: CohortStore,
+ store: StoreHandle,
catalog: Arc<CatalogHandle>,
sink: Arc<dyn MembershipSink>,
tracker: Arc<OffsetTracker>,
@@ -142,7 +146,7 @@ impl Stage1Worker {
async fn run_worker(
partition_id: u16,
mut receiver: MeteredReceiver,
- store: CohortStore,
+ handle: StoreHandle,
catalog: Arc<CatalogHandle>,
sink: Arc<dyn MembershipSink>,
tracker: Arc<OffsetTracker>,
@@ -158,7 +162,7 @@ async fn run_worker(
let mut person_memo = PersonMemo::new(person_memo);
// No-op for a cold partition (bloom-filtered scan finds nothing to schedule).
if durable_restore {
- rebuild_eviction_queue(partition_id, &store, &mut queue).await;
+ rebuild_eviction_queue(partition_id, &handle, &mut queue).await;
}
// In-memory resume cursors; loss on rebalance is benign (GC re-scans from the start).
let mut gc_cursor = MergeGcCursor::default();
@@ -181,14 +185,15 @@ async fn run_worker(
Some(max_offset.map_or(cse_offset, |current| current.max(cse_offset)));
let effects = handle_event(
partition_id,
- &store,
+ &handle,
&catalog,
&event,
&last_updated,
merge.partition_count,
&mut person_memo,
event_name_gating,
- );
+ )
+ .await;
buffer.extend(effects.changes);
for (key, deadline) in effects.schedules {
queue.schedule(key, deadline);
@@ -208,7 +213,7 @@ async fn run_worker(
}
handle_sweep(
partition_id,
- &store,
+ &handle,
&catalog,
&sink,
&merge,
@@ -231,7 +236,7 @@ async fn run_worker(
}
handle_merge(
partition_id,
- &store,
+ &handle,
&catalog,
&sink,
&merge,
@@ -255,7 +260,7 @@ async fn run_worker(
}
handle_apply(
partition_id,
- &store,
+ &handle,
&catalog,
&sink,
&merge,
@@ -279,7 +284,7 @@ async fn run_worker(
}
handle_cascade(
partition_id,
- &store,
+ &handle,
&catalog,
&sink,
&merge,
@@ -290,28 +295,47 @@ async fn run_worker(
.await;
}
ShuffleMessage::RedrivePendingTransfers => {
- handle_redrive(partition_id, &store, &merge).await;
+ handle_redrive(partition_id, &handle, &merge).await;
}
ShuffleMessage::MergeCfGc {
marker_cutoff_ms,
tombstone_cutoff_ms,
} => {
- handle_merge_gc(
- partition_id,
- &store,
- &mut gc_cursor,
- marker_cutoff_ms,
- tombstone_cutoff_ms,
- merge.gc_scan_limit,
- );
+ // The cursor moves into the section and back out by value; a teardown
+ // cancellation resets it to `Default`, which is benign — the GC re-scans from the
+ // prefix start next tenure.
+ let scan_limit = merge.gc_scan_limit;
+ let mut cursor = std::mem::take(&mut gc_cursor);
+ gc_cursor = handle
+ .run_section("merge_gc", move |store| {
+ handle_merge_gc(
+ partition_id,
+ store,
+ &mut cursor,
+ marker_cutoff_ms,
+ tombstone_cutoff_ms,
+ scan_limit,
+ );
+ cursor
+ })
+ .await
+ .unwrap_or_default();
if merge.stage2_orphan_gc_enabled {
- handle_stage2_orphan_gc(
- partition_id,
- &store,
- &catalog,
- &mut stage2_gc_cursor,
- merge.gc_scan_limit,
- );
+ let catalog = catalog.clone();
+ let mut cursor = std::mem::take(&mut stage2_gc_cursor);
+ stage2_gc_cursor = handle
+ .run_section("stage2_orphan_gc", move |store| {
+ handle_stage2_orphan_gc(
+ partition_id,
+ store,
+ &catalog,
+ &mut cursor,
+ scan_limit,
+ );
+ cursor
+ })
+ .await
+ .unwrap_or_default();
}
}
}
@@ -493,9 +517,9 @@ struct EventEffects {
}
#[allow(clippy::too_many_arguments)]
-fn handle_event(
+async fn handle_event(
partition_id: u16,
- store: &CohortStore,
+ handle: &StoreHandle,
catalog: &CatalogHandle,
event: &CohortStreamEvent,
last_updated: &str,
@@ -513,7 +537,7 @@ fn handle_event(
let filters: &TeamFilters = team_filters;
let resolved: Cow<'_, CohortStreamEvent> =
- match redirect_for_tombstone(partition_id, store, event, partition_count) {
+ match redirect_for_tombstone(partition_id, handle, event, partition_count).await {
Redirected::Process(event) => event,
Redirected::ReKey(re_keyed) => {
return EventEffects {
@@ -524,15 +548,16 @@ fn handle_event(
};
let started = Instant::now();
- let result = process_event_with_memo(
+ let result = process_event_offloaded(
partition_id,
- store,
+ handle,
filters,
generation,
&resolved,
person_memo,
event_name_gating,
- );
+ )
+ .await;
histogram!(STAGE1_EVENT_PROCESS_DURATION).record(started.elapsed().as_secs_f64());
match result {
@@ -551,12 +576,14 @@ fn handle_event(
}
match compose_stage2(
partition_id,
- store,
+ handle,
filters,
&outcome.transitions,
outcome.event_ms,
last_updated,
- ) {
+ )
+ .await
+ {
Ok(stage2_changes) => changes.extend(stage2_changes),
Err(error) => warn!(
partition_id,
@@ -589,22 +616,24 @@ enum Redirected<'a> {
ReKey(CohortStreamEvent),
}
-fn redirect_for_tombstone<'a>(
+async fn redirect_for_tombstone<'a>(
partition_id: u16,
- store: &CohortStore,
+ handle: &StoreHandle,
event: &'a CohortStreamEvent,
partition_count: u32,
) -> Redirected<'a> {
let Ok(person_id) = Uuid::parse_str(&event.person_id) else {
return Redirected::Process(Cow::Borrowed(event));
};
- let resolution = match tombstone_redirect::resolve(
- store,
+ let resolution = match tombstone_redirect::resolve_offloaded(
+ handle,
partition_id,
TeamId(event.team_id),
person_id,
partition_count,
- ) {
+ )
+ .await
+ {
Ok(resolution) => resolution,
Err(error) => {
warn!(
@@ -660,7 +689,7 @@ fn rewrite_to(event: &CohortStreamEvent, final_person: Uuid, origin: Uuid) -> Co
#[allow(clippy::too_many_arguments)]
async fn handle_sweep(
partition_id: u16,
- store: &CohortStore,
+ handle: &StoreHandle,
catalog: &CatalogHandle,
sink: &Arc<dyn MembershipSink>,
merge: &MergeWorkerDeps,
@@ -694,29 +723,45 @@ async fn handle_sweep(
continue;
};
let filters: &TeamFilters = filters;
- match sweep_evict(filters, keys, store, due_before_ms) {
- Ok(evictions) => {
- for result in &evictions.results {
- if let Some(transition) = &result.transition {
- if let Some(kind) = transition_metric_label(filters, transition) {
- counter!(STAGE1_TRANSITIONS, "kind" => kind).increment(1);
- }
- changes.extend(map_transition(filters, transition, last_updated));
- }
+ // Per-team retry: a read failure anywhere in the team reschedules all its keys and applies
+ // none of it, so gather every chunk before evicting.
+ let mut values: Vec<Option<Vec<u8>>> = Vec::with_capacity(keys.len());
+ let mut read_failed = false;
+ for chunk in keys.chunks(SWEEP_MULTI_GET_CHUNK) {
+ // The maintenance permit rotates between chunks, keeping each op fair against event reads.
+ match handle
+ .multi_get_stage1(chunk.to_vec(), ReadLane::Maintenance)
+ .await
+ {
+ Ok(chunk_values) => values.extend(chunk_values),
+ Err(error) => {
+ warn!(
+ partition_id,
+ team_id,
+ error = %error,
+ "sweep state read failed; rescheduling the team's keys for retry",
+ );
+ reschedule_team(queue, &popped, *team_id);
+ read_failed = true;
+ break;
}
- results.extend(evictions.results);
- drops.extend(evictions.drops);
}
- Err(error) => {
- warn!(
- partition_id,
- team_id,
- error = %error,
- "sweep state read failed; rescheduling the team's keys for retry",
- );
- reschedule_team(queue, &popped, *team_id);
+ }
+ if read_failed {
+ continue;
+ }
+
+ let evictions = sweep_evict(filters, keys, values, due_before_ms);
+ for result in &evictions.results {
+ if let Some(transition) = &result.transition {
+ if let Some(kind) = transition_metric_label(filters, transition) {
+ counter!(STAGE1_TRANSITIONS, "kind" => kind).increment(1);
+ }
+ changes.extend(map_transition(filters, transition, last_updated));
}
}
+ results.extend(evictions.results);
+ drops.extend(evictions.drops);
}
if !changes.is_empty() {
@@ -733,24 +778,24 @@ async fn handle_sweep(
}
if !results.is_empty() {
- let written = store.write_batch(|batch| {
- for result in &results {
- match &result.action {
- EvictionAction::Write(bytes) => batch.put_stage1(&result.key, bytes),
- EvictionAction::Delete => {
- batch.delete_stage1(&result.key);
- batch.merge_person_index(
- &PersonIndexKey {
- partition_id: result.key.partition_id,
- team_id: result.key.team_id,
- person_id: result.key.person_id,
- },
- IndexOp::Remove(result.key.leaf_state_key),
- );
- }
+ let mut staged = StagedBatch::default();
+ for result in &results {
+ match &result.action {
+ EvictionAction::Write(bytes) => staged.put_stage1(&result.key, bytes),
+ EvictionAction::Delete => {
+ staged.delete_stage1(&result.key);
+ staged.merge_person_index(
+ &PersonIndexKey {
+ partition_id: result.key.partition_id,
+ team_id: result.key.team_id,
+ person_id: result.key.person_id,
+ },
+ IndexOp::Remove(result.key.leaf_state_key),
+ );
}
}
- });
+ }
+ let written = handle.commit(staged).await;
if let Err(error) = written {
warn!(
partition_id,
@@ -790,12 +835,14 @@ async fn handle_sweep(
let filters: &TeamFilters = filters;
match compose_stage2(
partition_id,
- store,
+ handle,
filters,
transitions,
due_before_ms,
last_updated,
- ) {
+ )
+ .await
+ {
Ok(changes) => stage2_changes.extend(changes),
Err(error) => warn!(
partition_id,
@@ -836,13 +883,16 @@ async fn handle_sweep(
/// stops early; new events reschedule any missing keys.
async fn rebuild_eviction_queue(
partition_id: u16,
- store: &CohortStore,
+ handle: &StoreHandle,
queue: &mut EvictionQueue<Stage1Key>,
) {
let mut cursor: Option<Vec<u8>> = None;
let mut rebuilt: u64 = 0;
loop {
- let page = match store.scan_stage1(partition_id, cursor.as_deref(), REBUILD_SCAN_PAGE) {
+ let page = match handle
+ .scan_stage1(partition_id, cursor.clone(), REBUILD_SCAN_PAGE)
+ .await
+ {
Ok(page) => page,
Err(err) => {
warn!(
@@ -929,6 +979,8 @@ pub(crate) fn transition_metric_label(
}
#[cfg(test)]
+// Tests seed and assert against `CohortStore` directly, the sanctioned direct-store surface for tests.
+#[allow(clippy::disallowed_methods)]
mod tombstone_redirect_tests {
use super::*;
use chrono_tz::UTC;
@@ -945,7 +997,9 @@ mod tombstone_redirect_tests {
use crate::stage1::key::LeafStateKey;
use crate::stage1::state::{AppliedOffsets, Stage1State, StatefulRecord};
use crate::stage2::state::Stage2State;
- use crate::store::{Stage2Key, StoreConfig, TombstoneKey};
+ use crate::store::{
+ CohortStore, OffloadConfig, OffloadMode, Stage2Key, StoreConfig, TombstoneKey,
+ };
use crate::workers::merge_path::TransferRetryPolicy;
use crate::workers::CascadeConfig;
@@ -962,6 +1016,18 @@ mod tombstone_redirect_tests {
(dir, store)
}
+ /// Wraps a test store so tests exercise the same blocking-pool transport as production.
+ fn test_handle(store: &CohortStore) -> StoreHandle {
+ StoreHandle::new(
+ store.clone(),
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ )
+ }
+
fn person_catalog() -> Arc<CatalogHandle> {
let leaf = json!({
"type": "person", "key": "email", "value": "[email protected]", "operator": "exact",
@@ -1197,7 +1263,7 @@ mod tombstone_redirect_tests {
let worker = Stage1Worker::spawn(
partition_id,
rx,
- store.clone(),
+ test_handle(store),
catalog,
Arc::new(membership.clone()),
tracker.clone(),
@@ -1263,8 +1329,8 @@ mod tombstone_redirect_tests {
.unwrap();
}
- #[test]
- fn inline_redirect_folds_into_redirect_dedup_origin_not_the_main_map() {
+ #[tokio::test]
+ async fn inline_redirect_folds_into_redirect_dedup_origin_not_the_main_map() {
let (_dir, store) = temp_store();
let catalog = person_catalog();
let lsk = LeafStateKey::for_person_property(&PERSON_HASH);
@@ -1291,14 +1357,15 @@ mod tombstone_redirect_tests {
let straggler = person_event(p_old, "[email protected]", 5, 101);
let effects = handle_event(
partition_id,
- &store,
+ &test_handle(&store),
&catalog,
&straggler,
"ts",
COHORT_PARTITION_COUNT,
&mut PersonMemo::disabled(),
EventNameGating::Disabled,
- );
+ )
+ .await;
assert_eq!(effects.changes.len(), 1, "the straggler entered P_new");
assert_eq!(effects.changes[0].person_id, p_new.to_string());
@@ -1531,8 +1598,8 @@ mod tombstone_redirect_tests {
);
}
- #[test]
- fn re_keyed_event_folds_into_p_new_exactly_once_via_redirect_dedup() {
+ #[tokio::test]
+ async fn re_keyed_event_folds_into_p_new_exactly_once_via_redirect_dedup() {
let (_dir, store) = temp_store();
let catalog = person_catalog();
let lsk = LeafStateKey::for_person_property(&PERSON_HASH);
@@ -1540,18 +1607,20 @@ mod tombstone_redirect_tests {
let target_partition = partition_of(TeamId(TEAM), &p_new, COHORT_PARTITION_COUNT) as u16;
assert_ne!(source_partition, target_partition);
write_tombstone(&store, source_partition, p_old, p_new);
+ let handle = test_handle(&store);
let straggler = person_event(p_old, "[email protected]", 5, 9);
let mut effects = handle_event(
source_partition,
- &store,
+ &handle,
&catalog,
&straggler,
"ts",
COHORT_PARTITION_COUNT,
&mut PersonMemo::disabled(),
EventNameGating::Disabled,
- );
+ )
+ .await;
assert!(effects.changes.is_empty());
assert!(effects.schedules.is_empty());
assert_eq!(effects.re_keys.len(), 1);
@@ -1559,14 +1628,15 @@ mod tombstone_redirect_tests {
let effects = handle_event(
target_partition,
- &store,
+ &handle,
&catalog,
&re_keyed,
"ts",
COHORT_PARTITION_COUNT,
&mut PersonMemo::disabled(),
EventNameGating::Disabled,
- );
+ )
+ .await;
assert_eq!(effects.changes.len(), 1, "folds into P_new exactly once");
assert_eq!(effects.changes[0].person_id, p_new.to_string());
assert_eq!(effects.changes[0].status, MembershipStatus::Entered);
@@ -1590,20 +1660,21 @@ mod tombstone_redirect_tests {
let dup = handle_event(
target_partition,
- &store,
+ &handle,
&catalog,
&re_keyed,
"ts",
COHORT_PARTITION_COUNT,
&mut PersonMemo::disabled(),
EventNameGating::Disabled,
- );
+ )
+ .await;
assert!(dup.changes.is_empty(), "the duplicate folds zero times");
assert!(dup.re_keys.is_empty());
}
- #[test]
- fn hop_capped_redirect_processes_inline_at_the_best_known_target() {
+ #[tokio::test]
+ async fn hop_capped_redirect_processes_inline_at_the_best_known_target() {
let (_dir, store) = temp_store();
let catalog = person_catalog();
let lsk = LeafStateKey::for_person_property(&PERSON_HASH);
@@ -1616,14 +1687,15 @@ mod tombstone_redirect_tests {
};
let effects = handle_event(
partition_id,
- &store,
+ &test_handle(&store),
&catalog,
&straggler,
"ts",
COHORT_PARTITION_COUNT,
&mut PersonMemo::disabled(),
EventNameGating::Disabled,
- );
+ )
+ .await;
assert!(effects.re_keys.is_empty(), "no re-produce at the cap");
assert_eq!(effects.changes.len(), 1, "processed inline instead");
@@ -1649,8 +1721,8 @@ mod tombstone_redirect_tests {
);
}
- #[test]
- fn no_tombstone_processes_the_event_normally() {
+ #[tokio::test]
+ async fn no_tombstone_processes_the_event_normally() {
let (_dir, store) = temp_store();
let catalog = person_catalog();
let lsk = LeafStateKey::for_person_property(&PERSON_HASH);
@@ -1660,14 +1732,15 @@ mod tombstone_redirect_tests {
let event = person_event(alice, "[email protected]", 5, 0);
let effects = handle_event(
partition_id,
- &store,
+ &test_handle(&store),
&catalog,
&event,
"ts",
COHORT_PARTITION_COUNT,
&mut PersonMemo::disabled(),
EventNameGating::Disabled,
- );
+ )
+ .await;
assert_eq!(effects.changes.len(), 1);
assert_eq!(effects.changes[0].person_id, alice.to_string());
assert!(
diff --git a/rust/cohort-stream-processor/tests/cascade_consumer.rs b/rust/cohort-stream-processor/tests/cascade_consumer.rs
index 70ec1b83ada2..b1ba0122abf4 100644
--- a/rust/cohort-stream-processor/tests/cascade_consumer.rs
+++ b/rust/cohort-stream-processor/tests/cascade_consumer.rs
@@ -37,7 +37,9 @@ use cohort_stream_processor::producer::{
KafkaStreamEventSink, KafkaTransferSink, MembershipSink, MembershipStatus, StreamEventSink,
TransferSink,
};
-use cohort_stream_processor::store::{CohortStore, StoreConfig};
+use cohort_stream_processor::store::{
+ CohortStore, OffloadConfig, OffloadMode, StoreConfig, StoreHandle,
+};
use cohort_stream_processor::workers::{
CascadeConfig, MergeWorkerDeps, TransferRetryPolicy, DEFAULT_MERGE_GC_SCAN_LIMIT,
};
@@ -459,7 +461,14 @@ async fn spawn_instance(
let dispatcher = Arc::new(EventDispatcher::new(
PartitionRouter::new(64),
Arc::new(OffsetTracker::new()),
- store,
+ StoreHandle::new(
+ store,
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ ),
Arc::new(catalog),
membership_sink,
merge_deps,
diff --git a/rust/cohort-stream-processor/tests/event_name_gating_parity.rs b/rust/cohort-stream-processor/tests/event_name_gating_parity.rs
index 2879724083d9..0eff40855873 100644
--- a/rust/cohort-stream-processor/tests/event_name_gating_parity.rs
+++ b/rust/cohort-stream-processor/tests/event_name_gating_parity.rs
@@ -3,6 +3,9 @@
//! `cf_stage1` and the same leaf transitions. Covers a matching name, a non-matching name, and
//! numeric-looking names (`"0"` vs `"0.0"`) that must not cross-match.
+// Tests seed and assert through `CohortStore` directly — the sanctioned direct-store test surface.
+#![allow(clippy::disallowed_methods)]
+
use std::collections::BTreeMap;
use chrono_tz::UTC;
diff --git a/rust/cohort-stream-processor/tests/events_consumer.rs b/rust/cohort-stream-processor/tests/events_consumer.rs
index 17e94ca17ec1..5138c102c29d 100644
--- a/rust/cohort-stream-processor/tests/events_consumer.rs
+++ b/rust/cohort-stream-processor/tests/events_consumer.rs
@@ -24,6 +24,9 @@
//! Every test creates 4-partition topics and deletes the Kafka topic on exit (a leaked high-partition
//! topic wedges later runs); the S3 e2e also sweeps its per-test S3 prefix on exit.
+// Tests seed and assert through `CohortStore` directly — the sanctioned direct-store test surface.
+#![allow(clippy::disallowed_methods)]
+
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
@@ -48,8 +51,21 @@ use cohort_stream_processor::store::durability::{
run_boot_restore, upload_cadence, CheckpointExporter, CheckpointSweeper, OffsetManifest,
RestoreSource, S3Uploader,
};
-use cohort_stream_processor::store::{CohortStore, LeafStateKey, Stage1Key, StoreConfig};
+use cohort_stream_processor::store::{
+ CohortStore, LeafStateKey, OffloadConfig, OffloadMode, Stage1Key, StoreConfig, StoreHandle,
+};
use cohort_stream_processor::sweep::Sweeper;
+
+fn test_handle(store: &CohortStore) -> StoreHandle {
+ StoreHandle::new(
+ store.clone(),
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ )
+}
use cohort_stream_processor::workers::{MergeWorkerDeps, Stage1Worker};
use common_kafka::config::KafkaConfig;
use common_kafka::kafka_producer::KafkaProduceError;
@@ -234,7 +250,7 @@ fn build_consumer_with_restore(
let dispatcher = Arc::new(EventDispatcher::new(
PartitionRouter::new(64),
Arc::new(OffsetTracker::new()),
- store,
+ test_handle(&store),
Arc::new(catalog),
sink,
MergeWorkerDeps::capture(),
@@ -1106,7 +1122,7 @@ async fn durable_restart_reopens_live_state_and_fires_a_dormant_left() {
let worker = Stage1Worker::spawn(
partition as u16,
rx,
- store2.clone(),
+ test_handle(&store2),
catalog.clone(),
sink.clone(),
Arc::new(OffsetTracker::new()),
@@ -1191,7 +1207,7 @@ fn build_consumer_with_manifest(
let dispatcher = Arc::new(EventDispatcher::new(
PartitionRouter::new(64),
Arc::new(OffsetTracker::new()),
- store,
+ test_handle(&store),
Arc::new(catalog),
sink,
MergeWorkerDeps::capture(),
@@ -1378,7 +1394,7 @@ async fn s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormant
let ckpt_dispatcher = Arc::new(EventDispatcher::new(
PartitionRouter::new(64),
Arc::new(OffsetTracker::new()),
- store.clone(),
+ test_handle(&store),
Arc::new(behavioral_catalog()),
Arc::new(CaptureSink::new()),
MergeWorkerDeps::capture(),
@@ -1488,7 +1504,7 @@ async fn s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormant
let worker = Stage1Worker::spawn(
partition as u16,
rx,
- store2.clone(),
+ test_handle(&store2),
catalog.clone(),
left_sink.clone(),
Arc::new(OffsetTracker::new()),
diff --git a/rust/cohort-stream-processor/tests/merge_consumer.rs b/rust/cohort-stream-processor/tests/merge_consumer.rs
index 99135d4ffc36..e2372ee4088e 100644
--- a/rust/cohort-stream-processor/tests/merge_consumer.rs
+++ b/rust/cohort-stream-processor/tests/merge_consumer.rs
@@ -20,6 +20,9 @@
//! | xargs -r rpk topic delete'
//! ```
+// Tests seed and assert through `CohortStore` directly — the sanctioned direct-store test surface.
+#![allow(clippy::disallowed_methods)]
+
use std::collections::HashSet;
use std::future::Future;
use std::panic::AssertUnwindSafe;
@@ -48,7 +51,8 @@ use cohort_stream_processor::producer::{
};
use cohort_stream_processor::stage1::{Stage1State, StateVariant, StatefulRecord};
use cohort_stream_processor::store::{
- CohortStore, LeafStateKey, Stage1Key, StoreConfig, TombstoneKey,
+ CohortStore, LeafStateKey, OffloadConfig, OffloadMode, Stage1Key, StoreConfig, StoreHandle,
+ TombstoneKey,
};
use cohort_stream_processor::workers::{
CascadeConfig, MergeWorkerDeps, TransferRetryPolicy, DEFAULT_MERGE_GC_SCAN_LIMIT,
@@ -551,6 +555,17 @@ fn register_instance(manager: &mut Manager, name: &str) -> [Handle; 3] {
]
}
+fn test_handle(store: &CohortStore) -> StoreHandle {
+ StoreHandle::new(
+ store.clone(),
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ )
+}
+
struct Instance {
store: CohortStore,
dispatcher: Arc<EventDispatcher>,
@@ -607,7 +622,7 @@ async fn spawn_instance(
let dispatcher = Arc::new(EventDispatcher::new(
PartitionRouter::new(64),
Arc::new(OffsetTracker::new()),
- store.clone(),
+ test_handle(&store),
Arc::new(catalog),
membership_sink,
merge_deps,
diff --git a/rust/cohort-stream-processor/tests/merge_durability.rs b/rust/cohort-stream-processor/tests/merge_durability.rs
index 37a695597c2e..50aa124bc55a 100644
--- a/rust/cohort-stream-processor/tests/merge_durability.rs
+++ b/rust/cohort-stream-processor/tests/merge_durability.rs
@@ -14,6 +14,9 @@
//! cargo test -p cohort-stream-processor --test merge_durability -- --ignored --test-threads=1
//! ```
+// Tests seed and assert through `CohortStore` directly — the sanctioned direct-store test surface.
+#![allow(clippy::disallowed_methods)]
+
use std::collections::HashSet;
use std::future::Future;
use std::panic::AssertUnwindSafe;
@@ -47,7 +50,8 @@ use cohort_stream_processor::store::durability::{
OffsetManifest, RestoreSource, S3Uploader,
};
use cohort_stream_processor::store::{
- CohortStore, LeafStateKey, Stage1Key, StoreConfig, TombstoneKey,
+ CohortStore, LeafStateKey, OffloadConfig, OffloadMode, Stage1Key, StoreConfig, StoreHandle,
+ TombstoneKey,
};
use cohort_stream_processor::sweep::Sweeper;
use cohort_stream_processor::workers::{
@@ -614,6 +618,17 @@ fn register_instance(manager: &mut Manager, name: &str) -> [Handle; 4] {
]
}
+fn test_handle(store: &CohortStore) -> StoreHandle {
+ StoreHandle::new(
+ store.clone(),
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ )
+}
+
struct Instance {
store: CohortStore,
dispatcher: Arc<EventDispatcher>,
@@ -705,7 +720,7 @@ async fn spawn_instance(
let dispatcher = Arc::new(EventDispatcher::new(
PartitionRouter::new(64),
events_tracker,
- store.clone(),
+ test_handle(&store),
Arc::new(catalog),
membership_sink,
merge_deps,
diff --git a/rust/cohort-stream-processor/tests/merge_protocol.rs b/rust/cohort-stream-processor/tests/merge_protocol.rs
index 2656648603a3..2532cd464dcb 100644
--- a/rust/cohort-stream-processor/tests/merge_protocol.rs
+++ b/rust/cohort-stream-processor/tests/merge_protocol.rs
@@ -4,6 +4,9 @@
//! keyed to P_new from the start" oracle. Replays every handler twice for idempotence and exercises
//! the reopen-without-wipe recovery via `scan_pending_transfers`.
+// Tests seed and assert through `CohortStore` directly — the sanctioned direct-store test surface.
+#![allow(clippy::disallowed_methods)]
+
use chrono_tz::UTC;
use cohort_stream_processor::consumers::CohortStreamEvent;
use cohort_stream_processor::filters::{
@@ -22,10 +25,9 @@ use cohort_stream_processor::producer::{now_last_updated, MembershipStatus};
use cohort_stream_processor::stage1::{Stage1State, StateVariant, StatefulRecord};
use cohort_stream_processor::stage2::Stage2State;
use cohort_stream_processor::store::{
- CohortStore, LeafStateKey, MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage1Key,
- Stage2Key, StoreConfig, TombstoneKey,
+ CohortStore, LeafStateKey, MergeAppliedKey, MergeDrainKey, OffloadConfig, OffloadMode,
+ PendingTransferKey, Stage1Key, Stage2Key, StoreConfig, StoreHandle, TombstoneKey,
};
-use cohort_stream_processor::sweep::EvictionQueue;
use cohort_stream_processor::workers::{
compose_stage2, handle_merge_gc, handle_stage2_orphan_gc, process_event, MergeGcCursor,
Stage2GcCursor,
@@ -47,6 +49,22 @@ fn temp_store_in(dir: &TempDir) -> CohortStore {
.expect("open store")
}
+/// `All` mode so `compose_stage2` exercises the blocking-pool transport; handlers still take the raw store.
+fn handle(store: &CohortStore) -> StoreHandle {
+ handle_with_mode(store, OffloadMode::All)
+}
+
+fn handle_with_mode(store: &CohortStore, mode: OffloadMode) -> StoreHandle {
+ StoreHandle::new(
+ store.clone(),
+ OffloadConfig {
+ mode,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ )
+}
+
fn behavioral_bytecode() -> Value {
json!(["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11])
}
@@ -265,19 +283,17 @@ fn cross_partition_drain_transfer_apply_merges_all_variants_and_matches_the_orac
fold_pageview(&store, &filters, p_old_part, p_old, 10, 0);
fold_pageview(&store, &filters, p_new_part, p_new, 20, 0);
- let mut old_queue = EvictionQueue::<Stage1Key>::new();
let drained = handle_merge_event(
p_old_part,
&store,
&filters,
&merge_event(p_old, p_new),
(5, 100),
- &mut old_queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
let transfer = match drained {
- DrainOutcome::Drained { transfer } => transfer,
+ DrainOutcome::Drained { transfer, .. } => transfer,
other => panic!("expected a cross-partition Drained, got {other:?}"),
};
@@ -295,14 +311,12 @@ fn cross_partition_drain_transfer_apply_merges_all_variants_and_matches_the_orac
.unwrap()
.is_some());
- let mut new_queue = EvictionQueue::<Stage1Key>::new();
let applied = handle_transfer(
p_new_part,
&store,
&filters,
&transfer,
(5, 7),
- &mut new_queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
@@ -348,7 +362,6 @@ fn cross_partition_drain_transfer_apply_merges_all_variants_and_matches_the_orac
&filters,
&merge_event(p_old, p_new),
(5, 100),
- &mut old_queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
@@ -359,7 +372,6 @@ fn cross_partition_drain_transfer_apply_merges_all_variants_and_matches_the_orac
&filters,
&transfer,
(5, 7),
- &mut new_queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
@@ -401,19 +413,17 @@ fn seed_and_drain(dir: &TempDir) -> (CohortStore, TeamFilters, u16, Uuid, MergeS
fold_pageview(&store, &filters, p_old_part, p_old, 10, 0);
fold_pageview(&store, &filters, p_new_part, p_new, 20, 0);
- let mut old_queue = EvictionQueue::<Stage1Key>::new();
let transfer = match handle_merge_event(
p_old_part,
&store,
&filters,
&merge_event(p_old, p_new),
(5, 100),
- &mut old_queue,
COHORT_PARTITION_COUNT,
)
.unwrap()
{
- DrainOutcome::Drained { transfer } => transfer,
+ DrainOutcome::Drained { transfer, .. } => transfer,
other => panic!("expected Drained, got {other:?}"),
};
(store, filters, p_new_part, p_new, transfer)
@@ -425,14 +435,12 @@ fn duplicate_transfer_copy_under_different_transfer_coords_is_already_applied()
let dir = TempDir::new().unwrap();
let (store, filters, p_new_part, p_new, transfer) = seed_and_drain(&dir);
- let mut queue = EvictionQueue::<Stage1Key>::new();
let first = handle_transfer(
p_new_part,
&store,
&filters,
&transfer,
(5, 7),
- &mut queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
@@ -444,7 +452,6 @@ fn duplicate_transfer_copy_under_different_transfer_coords_is_already_applied()
&filters,
&transfer,
(63, 9_999),
- &mut queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
@@ -481,14 +488,12 @@ fn redrained_transfer_with_rebuilt_state_is_dropped_by_source_coords_dedup() {
let dir = TempDir::new().unwrap();
let (store, filters, p_new_part, p_new, transfer) = seed_and_drain(&dir);
- let mut queue = EvictionQueue::<Stage1Key>::new();
let first = handle_transfer(
p_new_part,
&store,
&filters,
&transfer,
(5, 7),
- &mut queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
@@ -513,7 +518,6 @@ fn redrained_transfer_with_rebuilt_state_is_dropped_by_source_coords_dedup() {
&filters,
&redrained,
(12, 345),
- &mut queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
@@ -541,20 +545,33 @@ fn fast_path_equals_the_cross_partition_result() {
fold_pageview(&store, &filters, p_old_part, p_old, 10, 0);
fold_pageview(&store, &filters, p_old_part, p_new, 20, 0);
- let mut queue = EvictionQueue::<Stage1Key>::new();
let outcome = handle_merge_event(
p_old_part,
&store,
&filters,
&merge_event(p_old, p_new),
(5, 100),
- &mut queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
+ let DrainOutcome::FastPath { effects, .. } = &outcome else {
+ panic!("same partition → fast path, got {outcome:?}");
+ };
+ // The fast path returns queue effects for the caller to apply rather than applying them inline.
+ assert!(
+ !effects.schedules.is_empty(),
+ "the merged behavioral leaves schedule P_new's eviction deadlines",
+ );
assert!(
- matches!(outcome, DrainOutcome::FastPath { .. }),
- "same partition → fast path"
+ effects
+ .schedules
+ .iter()
+ .all(|(key, _)| key.person_id == p_new),
+ "every scheduled key belongs to the survivor P_new",
+ );
+ assert!(
+ effects.cancels.iter().all(|key| key.person_id == p_old),
+ "the cancelled keys are P_old's drained keys",
);
let (s, d, c) = behavioral_states(&store, &filters, p_old_part, p_old);
@@ -586,14 +603,12 @@ fn reopen_between_drain_and_apply_recovers_via_scan_pending_transfers() {
let store = temp_store_in(&dir);
fold_pageview(&store, &filters, p_old_part, p_old, 10, 0);
fold_pageview(&store, &filters, p_new_part, p_new, 20, 0);
- let mut queue = EvictionQueue::<Stage1Key>::new();
let drained = handle_merge_event(
p_old_part,
&store,
&filters,
&merge_event(p_old, p_new),
(5, 100),
- &mut queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
@@ -613,14 +628,12 @@ fn reopen_between_drain_and_apply_recovers_via_scan_pending_transfers() {
let pending = PendingTransfer::decode(&recovered[0].1).unwrap();
assert_eq!(pending.transfer.old_person_uuid, p_old);
- let mut new_queue = EvictionQueue::<Stage1Key>::new();
let applied = handle_transfer(
p_new_part,
&store,
&filters,
&pending.transfer,
(5, 7),
- &mut new_queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
@@ -656,8 +669,8 @@ fn reopen_between_drain_and_apply_recovers_via_scan_pending_transfers() {
assert_eq!(compressed_sum(&compressed.unwrap()), 2);
}
-#[test]
-fn apply_transitions_compose_into_stage2() {
+#[tokio::test]
+async fn apply_transitions_compose_into_stage2() {
let dir = TempDir::new().unwrap();
let store = temp_store_in(&dir);
let filters = build_filters();
@@ -671,45 +684,42 @@ fn apply_transitions_compose_into_stage2() {
fold_pageview(&store, &filters, p_old_part, p_old, 10, 0);
fold_pageview(&store, &filters, p_new_part, p_new, 20, 0);
- let mut old_queue = EvictionQueue::<Stage1Key>::new();
let transfer = match handle_merge_event(
p_old_part,
&store,
&filters,
&merge_event(p_old, p_new),
(5, 100),
- &mut old_queue,
COHORT_PARTITION_COUNT,
)
.unwrap()
{
- DrainOutcome::Drained { transfer } => transfer,
+ DrainOutcome::Drained { transfer, .. } => transfer,
other => panic!("expected Drained, got {other:?}"),
};
- let mut new_queue = EvictionQueue::<Stage1Key>::new();
let transitions = match handle_transfer(
p_new_part,
&store,
&filters,
&transfer,
(5, 7),
- &mut new_queue,
COHORT_PARTITION_COUNT,
)
.unwrap()
{
- ApplyOutcome::Applied { transitions } => transitions,
+ ApplyOutcome::Applied { transitions, .. } => transitions,
other => panic!("expected Applied, got {other:?}"),
};
let changes = compose_stage2(
p_new_part,
- &store,
+ &handle(&store),
&filters,
&transitions,
MERGED_AT,
&now_last_updated(),
)
+ .await
.unwrap();
let composable_enter = changes
.iter()
@@ -748,19 +758,18 @@ fn empty_redrain_does_not_overwrite_a_still_pending_transfer() {
);
// Different source coords → drain marker misses → re-drain (empty, P_old already gone).
- let mut queue = EvictionQueue::<Stage1Key>::new();
let redrain = handle_merge_event(
p_old_part,
&store,
&filters,
&merge_event(p_old, p_new),
(5, 101),
- &mut queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
let DrainOutcome::Drained {
transfer: redrained,
+ ..
} = redrain
else {
panic!("expected Drained, got {redrain:?}");
@@ -804,22 +813,19 @@ fn merge_cf_gc_keeps_in_retention_markers_then_reclaims_out_of_retention_storage
fold_pageview(&store, &filters, p_old_part, p_old, 10, 0);
fold_pageview(&store, &filters, p_new_part, p_new, 20, 0);
- let mut old_queue = EvictionQueue::<Stage1Key>::new();
let transfer = match handle_merge_event(
p_old_part,
&store,
&filters,
&merge_event(p_old, p_new),
(5, 100),
- &mut old_queue,
COHORT_PARTITION_COUNT,
)
.unwrap()
{
- DrainOutcome::Drained { transfer } => transfer,
+ DrainOutcome::Drained { transfer, .. } => transfer,
other => panic!("expected Drained, got {other:?}"),
};
- let mut new_queue = EvictionQueue::<Stage1Key>::new();
assert!(matches!(
handle_transfer(
p_new_part,
@@ -827,7 +833,6 @@ fn merge_cf_gc_keeps_in_retention_markers_then_reclaims_out_of_retention_storage
&filters,
&transfer,
(5, 7),
- &mut new_queue,
COHORT_PARTITION_COUNT,
)
.unwrap(),
@@ -900,7 +905,6 @@ fn merge_cf_gc_keeps_in_retention_markers_then_reclaims_out_of_retention_storage
&filters,
&merge_event(p_old, p_new),
(5, 100),
- &mut old_queue,
COHORT_PARTITION_COUNT,
)
.unwrap(),
@@ -914,7 +918,6 @@ fn merge_cf_gc_keeps_in_retention_markers_then_reclaims_out_of_retention_storage
&filters,
&transfer,
(63, 9_999),
- &mut new_queue,
COHORT_PARTITION_COUNT,
)
.unwrap(),
@@ -960,12 +963,11 @@ fn merge_cf_gc_keeps_in_retention_markers_then_reclaims_out_of_retention_storage
&filters,
&merge_event(p_old, p_new),
(5, 100),
- &mut old_queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
assert!(
- matches!(&reclaimed_redrain, DrainOutcome::Drained { transfer } if transfer.leaves.is_empty()),
+ matches!(&reclaimed_redrain, DrainOutcome::Drained { transfer, .. } if transfer.leaves.is_empty()),
"after GC the marker no longer dedupes; the replay re-drains (empty), got {reclaimed_redrain:?}",
);
}
@@ -1000,14 +1002,12 @@ fn stage2_orphans_from_an_absent_team_drain_are_reclaimed_by_a_later_gc_tick() {
// Empty filters = absent-team fallback; drain deletes no cf_stage2 rows, so the row orphans.
let absent_team_filters = TeamFiltersBuilder::default().freeze(UTC);
- let mut queue = EvictionQueue::<Stage1Key>::new();
handle_merge_event(
p_old_part,
&store,
&absent_team_filters,
&merge_event(p_old, p_new),
(5, 100),
- &mut queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
@@ -1058,19 +1058,17 @@ fn drain_cross(
new: Uuid,
coords: (i32, i64),
) -> MergeStateTransfer {
- let mut queue = EvictionQueue::<Stage1Key>::new();
match handle_merge_event(
part(old),
store,
filters,
&merge_event(old, new),
coords,
- &mut queue,
COHORT_PARTITION_COUNT,
)
.unwrap()
{
- DrainOutcome::Drained { transfer } => transfer,
+ DrainOutcome::Drained { transfer, .. } => transfer,
other => panic!("expected a cross-partition Drained for {old}->{new}, got {other:?}"),
}
}
@@ -1093,7 +1091,6 @@ fn raced_chain_forwards_the_grandparent_transfer_through_the_tombstoned_intermed
// 1) B → C drains and applies at C → C = B + C (daily 2); B tombstoned to C.
let b_to_c = drain_cross(&store, &filters, b, c, (5, 200));
- let mut c_queue = EvictionQueue::<Stage1Key>::new();
assert!(matches!(
handle_transfer(
c_part,
@@ -1101,7 +1098,6 @@ fn raced_chain_forwards_the_grandparent_transfer_through_the_tombstoned_intermed
&filters,
&b_to_c,
(5, 71),
- &mut c_queue,
COHORT_PARTITION_COUNT
)
.unwrap(),
@@ -1120,14 +1116,12 @@ fn raced_chain_forwards_the_grandparent_transfer_through_the_tombstoned_intermed
let a_to_b = drain_cross(&store, &filters, a, b, (5, 100));
// 3) Apply on B's partition: B tombstoned to C (cross-partition) → Forward(C, hops=1).
- let mut b_queue = EvictionQueue::<Stage1Key>::new();
let forwarded = match handle_transfer(
b_part,
&store,
&filters,
&a_to_b,
(5, 80),
- &mut b_queue,
COHORT_PARTITION_COUNT,
)
.unwrap()
@@ -1163,7 +1157,6 @@ fn raced_chain_forwards_the_grandparent_transfer_through_the_tombstoned_intermed
&filters,
&forwarded,
(5, 81),
- &mut c_queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
@@ -1213,7 +1206,6 @@ fn ordered_chain_redelivery_dedups_on_the_intermediate_marker_without_forwarding
// 1) A → B drains and applies at B (not yet tombstoned) → marker under B.
let a_to_b = drain_cross(&store, &filters, a, b, (5, 100));
- let mut b_queue = EvictionQueue::<Stage1Key>::new();
assert!(matches!(
handle_transfer(
b_part,
@@ -1221,7 +1213,6 @@ fn ordered_chain_redelivery_dedups_on_the_intermediate_marker_without_forwarding
&filters,
&a_to_b,
(5, 80),
- &mut b_queue,
COHORT_PARTITION_COUNT
)
.unwrap(),
@@ -1230,7 +1221,6 @@ fn ordered_chain_redelivery_dedups_on_the_intermediate_marker_without_forwarding
// 2) B → C drains (B carries A + B) and applies at C → C = A + B + C.
let b_to_c = drain_cross(&store, &filters, b, c, (5, 200));
- let mut c_queue = EvictionQueue::<Stage1Key>::new();
assert!(matches!(
handle_transfer(
c_part,
@@ -1238,7 +1228,6 @@ fn ordered_chain_redelivery_dedups_on_the_intermediate_marker_without_forwarding
&filters,
&b_to_c,
(5, 71),
- &mut c_queue,
COHORT_PARTITION_COUNT
)
.unwrap(),
@@ -1258,7 +1247,6 @@ fn ordered_chain_redelivery_dedups_on_the_intermediate_marker_without_forwarding
&filters,
&a_to_b,
(61, 999),
- &mut b_queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
@@ -1290,27 +1278,23 @@ fn forwarded_copy_redelivery_dedups_on_the_survivor_marker() {
fold_pageview(&store, &filters, c_part, c, 30, 0);
let b_to_c = drain_cross(&store, &filters, b, c, (5, 200));
- let mut c_queue = EvictionQueue::<Stage1Key>::new();
handle_transfer(
c_part,
&store,
&filters,
&b_to_c,
(5, 71),
- &mut c_queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
let a_to_b = drain_cross(&store, &filters, a, b, (5, 100));
- let mut b_queue = EvictionQueue::<Stage1Key>::new();
let forwarded = match handle_transfer(
b_part,
&store,
&filters,
&a_to_b,
(5, 80),
- &mut b_queue,
COHORT_PARTITION_COUNT,
)
.unwrap()
@@ -1324,7 +1308,6 @@ fn forwarded_copy_redelivery_dedups_on_the_survivor_marker() {
&filters,
&forwarded,
(5, 81),
- &mut c_queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
@@ -1338,7 +1321,6 @@ fn forwarded_copy_redelivery_dedups_on_the_survivor_marker() {
&filters,
&a_to_b,
(62, 1000),
- &mut b_queue,
COHORT_PARTITION_COUNT,
)
.unwrap()
@@ -1352,7 +1334,6 @@ fn forwarded_copy_redelivery_dedups_on_the_survivor_marker() {
&filters,
&reforwarded,
(62, 1001),
- &mut c_queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
@@ -1412,7 +1393,6 @@ fn raced_chain_then_extends_dedups_on_the_origin_marker() {
// 1) B → C: same-partition fast path → B tombstoned to C, C = B + C (daily 2).
// Fast path writes no apply marker.
- let mut bc_queue = EvictionQueue::<Stage1Key>::new();
assert!(matches!(
handle_merge_event(
bcd_part,
@@ -1420,7 +1400,6 @@ fn raced_chain_then_extends_dedups_on_the_origin_marker() {
&filters,
&merge_event(b, c),
(5, 200),
- &mut bc_queue,
COHORT_PARTITION_COUNT,
)
.unwrap(),
@@ -1437,7 +1416,6 @@ fn raced_chain_then_extends_dedups_on_the_origin_marker() {
// 3) Apply on chain's partition: B tombstoned to C (inline) → apply into C = A+B+C (daily 3).
// Dual-write: marker written under C (resolved target) and B (original target).
- let mut chain_queue = EvictionQueue::<Stage1Key>::new();
assert!(matches!(
handle_transfer(
bcd_part,
@@ -1445,7 +1423,6 @@ fn raced_chain_then_extends_dedups_on_the_origin_marker() {
&filters,
&a_to_b,
(5, 80),
- &mut chain_queue,
COHORT_PARTITION_COUNT,
)
.unwrap(),
@@ -1476,7 +1453,6 @@ fn raced_chain_then_extends_dedups_on_the_origin_marker() {
// 4) C → D: same-partition fast path → C tombstoned to D, D = A+B+C+D (daily 4).
// The fast path writes no apply marker, so C's marker is stranded (no redelivery resolves to C).
- let mut cd_queue = EvictionQueue::<Stage1Key>::new();
assert!(matches!(
handle_merge_event(
bcd_part,
@@ -1484,7 +1460,6 @@ fn raced_chain_then_extends_dedups_on_the_origin_marker() {
&filters,
&merge_event(c, d),
(5, 300),
- &mut cd_queue,
COHORT_PARTITION_COUNT,
)
.unwrap(),
@@ -1505,7 +1480,6 @@ fn raced_chain_then_extends_dedups_on_the_origin_marker() {
&filters,
&a_to_b,
(61, 999),
- &mut chain_queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
@@ -1558,7 +1532,6 @@ fn drain_assist_folds_into_a_same_partition_tombstoned_target_directly() {
fold_pageview(&store, &filters, b_part, c, 30, 0);
// B → C is a same-partition fast-path merge → B tombstoned to C, C has B + C.
- let mut bc_queue = EvictionQueue::<Stage1Key>::new();
assert!(matches!(
handle_merge_event(
b_part,
@@ -1566,7 +1539,6 @@ fn drain_assist_folds_into_a_same_partition_tombstoned_target_directly() {
&filters,
&merge_event(b, c),
(5, 200),
- &mut bc_queue,
COHORT_PARTITION_COUNT,
)
.unwrap(),
@@ -1580,7 +1552,6 @@ fn drain_assist_folds_into_a_same_partition_tombstoned_target_directly() {
a_to_b.new_person_uuid, b,
"A and B differ in partition, so the assist did not retarget at A's drain (B's tombstone lives on B's slice, not A's)",
);
- let mut c_queue = EvictionQueue::<Stage1Key>::new();
assert!(matches!(
handle_transfer(
b_part,
@@ -1588,7 +1559,6 @@ fn drain_assist_folds_into_a_same_partition_tombstoned_target_directly() {
&filters,
&a_to_b,
(5, 81),
- &mut c_queue,
COHORT_PARTITION_COUNT
)
.unwrap(),
@@ -1626,7 +1596,6 @@ fn transfer_forward_stops_at_the_hop_cap_on_a_corrupt_tombstone_cycle() {
let a_to_b = drain_cross(&store, &filters, a, b, (5, 100));
let mut transfer = a_to_b;
- let mut queue = EvictionQueue::<Stage1Key>::new();
let mut hops = 0u8;
loop {
let on_part = part(transfer.new_person_uuid);
@@ -1636,7 +1605,6 @@ fn transfer_forward_stops_at_the_hop_cap_on_a_corrupt_tombstone_cycle() {
&filters,
&transfer,
(5, 80 + hops as i64),
- &mut queue,
COHORT_PARTITION_COUNT,
)
.unwrap()
@@ -1754,14 +1722,12 @@ fn checkpoint_restore_then_redrive_and_already_drained_replay_apply_once() {
p_new
);
- let mut new_queue = EvictionQueue::<Stage1Key>::new();
let applied = handle_transfer(
p_new_part,
&restored,
&filters,
&pending.transfer,
(5, 7),
- &mut new_queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
@@ -1784,14 +1750,12 @@ fn checkpoint_restore_then_redrive_and_already_drained_replay_apply_once() {
);
assert_eq!(compressed_sum(&compressed.unwrap()), 2);
- let mut old_queue = EvictionQueue::<Stage1Key>::new();
let replay_drain = handle_merge_event(
p_old_part,
&restored,
&filters,
&merge_event(p_old, p_new),
merge_coords,
- &mut old_queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
@@ -1807,7 +1771,6 @@ fn checkpoint_restore_then_redrive_and_already_drained_replay_apply_once() {
&filters,
&pending.transfer,
(63, 9_999),
- &mut new_queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
@@ -1960,14 +1923,12 @@ fn checkpoint_restore_preserves_the_drain_marker_so_a_replayed_merge_does_not_re
"the restored outbox starts empty",
);
- let mut queue = EvictionQueue::<Stage1Key>::new();
let replay = handle_merge_event(
p_old_part,
&restored,
&filters,
&merge_event(p_old, p_new),
merge_coords,
- &mut queue,
COHORT_PARTITION_COUNT,
)
.unwrap();
@@ -1984,3 +1945,126 @@ fn checkpoint_restore_preserves_the_drain_marker_so_a_replayed_merge_does_not_re
"the replayed merge did not stage a duplicate pending transfer",
);
}
+
+/// The merge drain and apply run inside `run_section` (the section lane) and stage-2 compose reads
+/// through the event lane; the offload mode changes only *where* those run, never the result. A
+/// mode-plumbing bug that inverted a lane inside the merge path would surface as a divergence here.
+/// Mirrors `each_offload_mode_yields_the_same_emissions_and_state` in the sweep suite, for the merge
+/// drain → apply → compose path — which the rest of the merge suite only exercises under `All`.
+#[tokio::test]
+async fn each_offload_mode_yields_the_same_merge_result() {
+ #[derive(Debug, PartialEq)]
+ struct ModeOutcome {
+ composed: Vec<(i32, String, MembershipStatus)>,
+ stage1: Vec<(Vec<u8>, Vec<u8>)>,
+ }
+
+ let p_old = Uuid::from_u128(0xBEE5);
+ let p_old_part = part(p_old);
+ let p_new = person_not_on(p_old_part);
+ let p_new_part = part(p_new);
+ // Fixed once so `last_updated` cannot vary the compose output across arms.
+ let last_updated = now_last_updated();
+
+ let mut per_mode: Vec<ModeOutcome> = Vec::new();
+ for mode in [OffloadMode::Off, OffloadMode::Maintenance, OffloadMode::All] {
+ let dir = TempDir::new().unwrap();
+ let store = temp_store_in(&dir);
+ let handle = handle_with_mode(&store, mode);
+ let filters = build_filters();
+
+ // After the merge P_new's daily flip AND its person leaf compose an enter (as in
+ // `apply_transitions_compose_into_stage2`).
+ fold_pageview(&store, &filters, p_old_part, p_old, 10, 0);
+ fold_pageview(&store, &filters, p_new_part, p_new, 20, 0);
+
+ // Drain P_old through the section lane, exactly as the worker's `handle_merge` does. `filters`
+ // is rebuilt inside the `'static` closure (it is not `Clone`), deterministically.
+ let drain_event = merge_event(p_old, p_new);
+ let transfer = match handle
+ .run_section("merge_drain", move |store| {
+ handle_merge_event(
+ p_old_part,
+ store,
+ &build_filters(),
+ &drain_event,
+ (5, 100),
+ COHORT_PARTITION_COUNT,
+ )
+ })
+ .await
+ .unwrap()
+ .unwrap()
+ {
+ DrainOutcome::Drained { transfer, .. } => transfer,
+ other => panic!("mode {mode:?}: expected Drained, got {other:?}"),
+ };
+
+ // Apply on P_new's partition through the section lane.
+ let transitions = match handle
+ .run_section("merge_apply", move |store| {
+ handle_transfer(
+ p_new_part,
+ store,
+ &build_filters(),
+ &transfer,
+ (5, 7),
+ COHORT_PARTITION_COUNT,
+ )
+ })
+ .await
+ .unwrap()
+ .unwrap()
+ {
+ ApplyOutcome::Applied { transitions, .. } => transitions,
+ other => panic!("mode {mode:?}: expected Applied, got {other:?}"),
+ };
+
+ // Compose stage-2 through the event lane.
+ let changes = compose_stage2(
+ p_new_part,
+ &handle,
+ &filters,
+ &transitions,
+ MERGED_AT,
+ &last_updated,
+ )
+ .await
+ .unwrap();
+
+ let mut composed: Vec<(i32, String, MembershipStatus)> = changes
+ .iter()
+ .map(|change| (change.cohort_id, change.person_id.clone(), change.status))
+ .collect();
+ composed.sort_by(|a, b| (a.0, a.1.as_str()).cmp(&(b.0, b.1.as_str())));
+
+ let mut stage1: Vec<(Vec<u8>, Vec<u8>)> = [p_old_part, p_new_part]
+ .into_iter()
+ .flat_map(|pid| store.scan_stage1(pid, None, 10_000).unwrap())
+ .map(|(key, value)| (key.encode().to_vec(), value))
+ .collect();
+ stage1.sort();
+
+ per_mode.push(ModeOutcome { composed, stage1 });
+ }
+
+ // The scenario must actually compose an enter for P_new, so parity compares real work rather than
+ // three identically-empty outcomes.
+ assert!(
+ per_mode[0].composed.iter().any(|(_, person, status)| {
+ *person == p_new.to_string() && *status == MembershipStatus::Entered
+ }),
+ "the seed must produce a composable enter for P_new",
+ );
+
+ let (off, rest) = per_mode.split_first().unwrap();
+ for (arm, mode) in rest
+ .iter()
+ .zip([OffloadMode::Maintenance, OffloadMode::All])
+ {
+ assert_eq!(
+ arm, off,
+ "mode {mode:?} diverged from Off: merge emissions and cf_stage1 bytes must be identical across operating points",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/tests/person_memo_parity.rs b/rust/cohort-stream-processor/tests/person_memo_parity.rs
index 093e596380d1..6f569a5dd815 100644
--- a/rust/cohort-stream-processor/tests/person_memo_parity.rs
+++ b/rust/cohort-stream-processor/tests/person_memo_parity.rs
@@ -3,6 +3,9 @@
//! is non-deterministic). Covers a hit, a property change (fingerprint miss), a generation bump
//! (re-eval, no stale serve), an out-of-order stale event, and a second person.
+// Tests seed and assert through `CohortStore` directly — the sanctioned direct-store test surface.
+#![allow(clippy::disallowed_methods)]
+
use std::collections::BTreeMap;
use chrono_tz::UTC;
@@ -13,10 +16,12 @@ use cohort_stream_processor::filters::{
use cohort_stream_processor::partitions::{MeteredReceiver, OffsetTracker, ShuffleMessage};
use cohort_stream_processor::producer::{CaptureSink, MembershipStatus};
use cohort_stream_processor::stage1::{LeafTransition, TransitionKind};
-use cohort_stream_processor::store::{CohortStore, StoreConfig};
+use cohort_stream_processor::store::{
+ CohortStore, OffloadConfig, OffloadMode, StoreConfig, StoreHandle,
+};
use cohort_stream_processor::workers::{
- process_event_with_memo, EventNameGating, EventOutcome, MergeWorkerDeps, PersonMemo,
- PersonMemoConfig, Stage1Worker,
+ process_event, process_event_with_memo, EventNameGating, EventOutcome, MergeWorkerDeps,
+ PersonMemo, PersonMemoConfig, Stage1Worker,
};
use serde_json::{json, Value};
use tempfile::TempDir;
@@ -119,6 +124,17 @@ fn temp_store() -> (TempDir, CohortStore) {
(dir, store)
}
+fn test_handle(store: &CohortStore) -> StoreHandle {
+ StoreHandle::new(
+ store.clone(),
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ )
+}
+
/// The partition's full `cf_stage1`, keyed by encoded key bytes (`Stage1Key` is not `Ord`). Two runs
/// with byte-identical state produce equal maps regardless of write order.
fn dump_stage1(store: &CohortStore) -> BTreeMap<Vec<u8>, Vec<u8>> {
@@ -340,7 +356,7 @@ async fn run_worker_sequence(
let worker = Stage1Worker::spawn_with_memo(
PARTITION,
rx,
- store.clone(),
+ test_handle(&store),
catalog,
std::sync::Arc::new(sink.clone()),
tracker.clone(),
@@ -400,3 +416,115 @@ async fn memo_enabled_worker_matches_a_disabled_worker_end_to_end() {
assert_eq!(on_statuses, off_statuses, "membership output parity");
assert_eq!(on_state, off_state, "cf_stage1 parity");
}
+
+/// `person`'s person-index leaves, sorted so two runs compare regardless of merge order.
+fn person_index_of(store: &CohortStore, person: Uuid) -> Vec<Vec<u8>> {
+ let mut leaves: Vec<Vec<u8>> = store
+ .get_person_index(&cohort_stream_processor::store::PersonIndexKey {
+ partition_id: PARTITION,
+ team_id: TEAM as u64,
+ person_id: person,
+ })
+ .unwrap()
+ .iter()
+ .map(|lsk| lsk.0.to_vec())
+ .collect();
+ leaves.sort_unstable();
+ leaves
+}
+
+/// An enter → hit → leave `(props, offset, ts)` sequence: the middle row repeats the entering props
+/// (a no-change hit); the third swaps in a non-matching email to leave.
+fn enter_hit_leave() -> [(&'static str, i64, &'static str); 3] {
+ [
+ (PROPS_PRO, 0, "2026-05-26 10:00:00.000000"),
+ (PROPS_PRO, 1, "2026-05-26 11:00:00.000000"),
+ (r#"{"email":"[email protected]"}"#, 2, "2026-05-26 12:00:00.000000"),
+ ]
+}
+
+/// The sync `process_event` composition and the offloaded worker composition must agree
+/// byte-for-byte: the same single-leaf sequence on store A (sync) and store B (spawned `All`-mode
+/// worker) yields equal `cf_stage1`, person-index, and emissions. Catches the two paths drifting.
+#[tokio::test]
+async fn sync_and_offloaded_process_event_agree() {
+ let alice = Uuid::from_u128(1);
+ // A single person-property leaf keeps stage-2 out, so `cf_stage1` + person-index + emissions
+ // fully capture the event fold both paths share.
+ let leaf = || person_leaf("email", "[email protected]", EMAIL_ALICE);
+
+ let (_a_dir, a_store) = temp_store();
+ let a_filters = team_filters(vec![leaf()]);
+ let mut a_statuses: Vec<MembershipStatus> = Vec::new();
+ for (props, offset, ts) in enter_hit_leave() {
+ let outcome = process_event(
+ PARTITION,
+ &a_store,
+ &a_filters,
+ &event(alice, props, offset, ts),
+ )
+ .unwrap();
+ // Mirror the worker's per-transition membership production so the emission lists compare.
+ for transition in &outcome.transitions {
+ a_statuses.push(match transition.kind {
+ TransitionKind::Entered => MembershipStatus::Entered,
+ TransitionKind::Left => MembershipStatus::Left,
+ });
+ }
+ }
+
+ let (_b_dir, b_store) = temp_store();
+ let b_filters = team_filters(vec![leaf()]);
+ let catalog = std::sync::Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([(
+ TeamId(TEAM),
+ b_filters,
+ )])));
+ let sink = CaptureSink::new();
+ let tracker = std::sync::Arc::new(OffsetTracker::new());
+ let (tx, rx) = mpsc::channel(16);
+ let rx = MeteredReceiver::unmetered(rx);
+ let worker = Stage1Worker::spawn_with_memo(
+ PARTITION,
+ rx,
+ test_handle(&b_store),
+ catalog,
+ std::sync::Arc::new(sink.clone()),
+ tracker.clone(),
+ MergeWorkerDeps::capture(),
+ false,
+ PersonMemoConfig::DISABLED,
+ EventNameGating::Disabled,
+ );
+ for (props, offset, ts) in enter_hit_leave() {
+ tracker.mark_dispatched(PARTITION as i32, offset + 1);
+ tx.send(vec![ShuffleMessage::Event {
+ event: Box::new(event(alice, props, offset, ts)),
+ cse_offset: offset,
+ }])
+ .await
+ .unwrap();
+ }
+ drop(tx);
+ worker.join().await.unwrap();
+ let b_statuses: Vec<MembershipStatus> = sink.changes().iter().map(|c| c.status).collect();
+
+ assert_eq!(
+ b_statuses,
+ vec![MembershipStatus::Entered, MembershipStatus::Left],
+ "the offloaded worker enters then leaves",
+ );
+ assert_eq!(
+ a_statuses, b_statuses,
+ "emissions agree (sync vs offloaded)"
+ );
+ assert_eq!(
+ dump_stage1(&a_store),
+ dump_stage1(&b_store),
+ "cf_stage1 bytes agree (sync vs offloaded)",
+ );
+ assert_eq!(
+ person_index_of(&a_store, alice),
+ person_index_of(&b_store, alice),
+ "person-index agrees (sync vs offloaded)",
+ );
+}
diff --git a/rust/cohort-stream-processor/tests/stage1_worker.rs b/rust/cohort-stream-processor/tests/stage1_worker.rs
index db0c8baa6f29..0ab8ad1c2b42 100644
--- a/rust/cohort-stream-processor/tests/stage1_worker.rs
+++ b/rust/cohort-stream-processor/tests/stage1_worker.rs
@@ -7,6 +7,9 @@
//! Parse-layer behaviors (globals shape, dropped/cohort-ref leaves, key derivation) are covered by
//! the in-crate classifier / catalog tests, not duplicated here.
+// Tests seed and assert through `CohortStore` directly — the sanctioned direct-store test surface.
+#![allow(clippy::disallowed_methods)]
+
use std::collections::BTreeMap;
use std::sync::Arc;
@@ -24,7 +27,8 @@ use cohort_stream_processor::stage1::{
StatefulRecord, TransitionKind,
};
use cohort_stream_processor::store::{
- CohortStore, LeafStateKey, PersonIndexKey, Stage1Key, StoreConfig,
+ CohortStore, LeafStateKey, OffloadConfig, OffloadMode, PersonIndexKey, Stage1Key, StoreConfig,
+ StoreHandle,
};
use cohort_stream_processor::workers::{process_event, MergeWorkerDeps, SkipReason, Stage1Worker};
use serde_json::{json, Value};
@@ -50,6 +54,17 @@ fn temp_store() -> (TempDir, CohortStore) {
(dir, store)
}
+fn test_handle(store: &CohortStore) -> StoreHandle {
+ StoreHandle::new(
+ store.clone(),
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ )
+}
+
/// Raise the dispatch ceiling *before* sending: `mark_processed` clamps a processed offset to what
/// was dispatched, and the worker may mark as soon as it receives the message.
async fn dispatch_to_worker(
@@ -1049,7 +1064,7 @@ async fn spawned_worker_drains_a_batch_and_commits_state() {
let worker = Stage1Worker::spawn(
PARTITION_ID,
rx,
- store.clone(),
+ test_handle(&store),
catalog,
Arc::new(sink.clone()),
tracker.clone(),
@@ -1086,6 +1101,63 @@ async fn spawned_worker_drains_a_batch_and_commits_state() {
);
}
+/// The offloaded read for a second event must observe the first event's committed write: within one
+/// batch, a replay racing ahead of that commit would re-apply and emit a spurious second transition.
+#[tokio::test]
+async fn sub_batch_read_your_writes_survives_offload() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![behavioral_leaf(7)]))]);
+ let behavioral_lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let alice = person(1);
+
+ let catalog = catalog_of(filters);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+
+ let (tx, rx) = mpsc::channel(16);
+ let rx = MeteredReceiver::unmetered(rx);
+ let worker = Stage1Worker::spawn(
+ PARTITION_ID,
+ rx,
+ test_handle(&store),
+ catalog,
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ MergeWorkerDeps::capture(),
+ false,
+ );
+
+ // Same source coordinates (5, 0) make the second event an exact replay of the first; shipping
+ // both in one batch forces the worker to process them back-to-back.
+ tracker.mark_dispatched(PARTITION_ID as i32, 1);
+ tx.send(vec![
+ ShuffleMessage::Event {
+ event: Box::new(event(alice, 5, 0)),
+ cse_offset: 0,
+ },
+ ShuffleMessage::Event {
+ event: Box::new(event(alice, 5, 0)),
+ cse_offset: 0,
+ },
+ ])
+ .await
+ .unwrap();
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let changes = sink.changes();
+ assert_eq!(
+ changes.len(),
+ 1,
+ "the replay in the same sub-batch must fold once, not twice (read-your-writes held)",
+ );
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ assert!(
+ state_at(&store, behavioral_lsk, alice).is_some(),
+ "the single fold wrote the leaf state",
+ );
+}
+
#[tokio::test]
async fn spawned_worker_composes_two_leaf_cohort_and_emits_single_leaf_independently() {
let (_dir, store) = temp_store();
@@ -1106,7 +1178,7 @@ async fn spawned_worker_composes_two_leaf_cohort_and_emits_single_leaf_independe
let worker = Stage1Worker::spawn(
PARTITION_ID,
rx,
- store.clone(),
+ test_handle(&store),
catalog,
Arc::new(sink.clone()),
tracker.clone(),
@@ -1174,7 +1246,7 @@ async fn spawned_worker_skips_events_for_unknown_teams() {
let worker = Stage1Worker::spawn(
PARTITION_ID,
rx,
- store.clone(),
+ test_handle(&store),
catalog,
Arc::new(sink.clone()),
tracker.clone(),
@@ -1226,7 +1298,7 @@ async fn worker_produces_changes_and_advances_offset() {
let worker = Stage1Worker::spawn(
PARTITION_ID,
rx,
- store.clone(),
+ test_handle(&store),
single_leaf_catalog(),
Arc::new(sink.clone()),
tracker.clone(),
@@ -1261,7 +1333,7 @@ async fn worker_advances_offset_on_empty_transition_subbatch() {
let worker = Stage1Worker::spawn(
PARTITION_ID,
rx,
- store.clone(),
+ test_handle(&store),
single_leaf_catalog(),
Arc::new(sink.clone()),
tracker.clone(),
@@ -1296,7 +1368,7 @@ async fn worker_holds_offset_when_the_only_flush_fails() {
let worker = Stage1Worker::spawn(
PARTITION_ID,
rx,
- store.clone(),
+ test_handle(&store),
single_leaf_catalog(),
Arc::new(sink.clone()),
tracker.clone(),
@@ -1327,7 +1399,7 @@ async fn worker_keeps_processing_after_a_produce_failure() {
let worker = Stage1Worker::spawn(
PARTITION_ID,
rx,
- store.clone(),
+ test_handle(&store),
single_leaf_catalog(),
Arc::new(sink.clone()),
tracker.clone(),
@@ -1766,7 +1838,7 @@ async fn daily_multiple_single_leaf_cohort_emits_entered_then_left_to_the_sink()
let worker = Stage1Worker::spawn(
PARTITION_ID,
rx,
- store.clone(),
+ test_handle(&store),
catalog,
Arc::new(sink.clone()),
tracker.clone(),
@@ -2098,7 +2170,7 @@ async fn compressed_sweep_deletes_then_a_late_event_recreates_the_state() {
let worker = Stage1Worker::spawn(
PARTITION_ID,
rx,
- store.clone(),
+ test_handle(&store),
catalog,
Arc::new(sink.clone()),
tracker.clone(),
diff --git a/rust/cohort-stream-processor/tests/store.rs b/rust/cohort-stream-processor/tests/store.rs
index f610ccd0f282..cad13aa0d222 100644
--- a/rust/cohort-stream-processor/tests/store.rs
+++ b/rust/cohort-stream-processor/tests/store.rs
@@ -1,5 +1,8 @@
//! End-to-end tests against a real RocksDB in a temp dir, through the public API only.
+// `CohortStore` is the API under test here, so tests call it directly.
+#![allow(clippy::disallowed_methods)]
+
use cohort_stream_processor::store::{
Cf, CohortStore, IndexOp, LeafStateKey, MergeAppliedKey, MergeDrainKey, OpaqueCf,
PendingTransferKey, PersonIndexKey, Stage1Key, Stage2Key, StoreConfig, TombstoneKey,
diff --git a/rust/cohort-stream-processor/tests/sweep_worker.rs b/rust/cohort-stream-processor/tests/sweep_worker.rs
index 3f8a2356f9ec..65ebed06e8b0 100644
--- a/rust/cohort-stream-processor/tests/sweep_worker.rs
+++ b/rust/cohort-stream-processor/tests/sweep_worker.rs
@@ -9,6 +9,9 @@
//! The Stage 2 section covers a time-driven leaf flip recomposing its composable (multi-leaf)
//! cohorts through the sweep's second produce.
+// Tests seed and assert through `CohortStore` directly — the sanctioned direct-store test surface.
+#![allow(clippy::disallowed_methods)]
+
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
@@ -32,7 +35,8 @@ use cohort_stream_processor::stage1::{
};
use cohort_stream_processor::stage2::Stage2State;
use cohort_stream_processor::store::{
- CohortStore, LeafStateKey, PersonIndexKey, Stage1Key, Stage2Key, StoreConfig,
+ CohortStore, LeafStateKey, OffloadConfig, OffloadMode, PersonIndexKey, Stage1Key, Stage2Key,
+ StoreConfig, StoreHandle,
};
use cohort_stream_processor::workers::{process_event, MergeWorkerDeps, Stage1Worker};
use common_kafka::kafka_producer::KafkaProduceError;
@@ -58,6 +62,22 @@ fn temp_store() -> (TempDir, CohortStore) {
(dir, store)
}
+/// `All` mode so the worker and dispatcher exercise the blocking-pool transport; the raw store stays for seeding and assertions.
+fn test_handle(store: &CohortStore) -> StoreHandle {
+ test_handle_with_mode(store, OffloadMode::All)
+}
+
+fn test_handle_with_mode(store: &CohortStore, mode: OffloadMode) -> StoreHandle {
+ StoreHandle::new(
+ store.clone(),
+ OffloadConfig {
+ mode,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ )
+}
+
fn behavioral_bytecode() -> Value {
json!(["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11])
}
@@ -247,19 +267,27 @@ async fn send_sweep(tx: &mpsc::Sender<Vec<ShuffleMessage>>, due_before_ms: i64)
.unwrap();
}
-/// Drive the current-thread runtime until the worker has recorded `count` changes, so a test can read
-/// the intermediate post-sweep state mid-stream (the queue is per-worker, so it can't drop the worker
-/// to barrier). [`CaptureSink::produce`] is immediately-ready and `handle_sweep` does its state write
-/// and reschedule synchronously right after it, so once a sweep's change lands its state mutation is
-/// durable too — no wall-clock sleep needed.
-async fn drain_until_changes(sink: &CaptureSink, count: usize) {
- for _ in 0..10_000 {
- if sink.changes().len() >= count {
+/// Poll `predicate` until it holds, so a test can observe intermediate mid-stream state without a
+/// barrier. Store I/O runs on the blocking pool, so probes sleep (rather than yield-spin) to let that
+/// wall-clock work land.
+async fn drain_until(what: &str, mut predicate: impl FnMut() -> bool) {
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
+ while std::time::Instant::now() < deadline {
+ if predicate() {
return;
}
- tokio::task::yield_now().await;
+ tokio::time::sleep(std::time::Duration::from_millis(1)).await;
}
- panic!("worker did not record {count} changes");
+ panic!("timed out waiting for {what}");
+}
+
+/// [`drain_until`] on the sink's change count. `handle_sweep` produces before its state write, so a
+/// test inspecting post-sweep state must follow this with a [`drain_until`] on the store itself.
+async fn drain_until_changes(sink: &CaptureSink, count: usize) {
+ drain_until("the worker to record changes", || {
+ sink.changes().len() >= count
+ })
+ .await;
}
fn spawn_worker(
@@ -282,6 +310,29 @@ fn spawn_worker_durable(
spawn_worker_with_restore(store, catalog, sink, tracker, true)
}
+/// Like [`spawn_worker`] but pinned to a given offload mode instead of the default `All`.
+fn spawn_worker_with_mode(
+ store: &CohortStore,
+ catalog: Arc<CatalogHandle>,
+ sink: Arc<dyn MembershipSink>,
+ tracker: Arc<OffsetTracker>,
+ mode: OffloadMode,
+) -> (mpsc::Sender<Vec<ShuffleMessage>>, Stage1Worker) {
+ let (tx, rx) = mpsc::channel(16);
+ let rx = MeteredReceiver::unmetered(rx);
+ let worker = Stage1Worker::spawn(
+ PARTITION_ID,
+ rx,
+ test_handle_with_mode(store, mode),
+ catalog,
+ sink,
+ tracker,
+ MergeWorkerDeps::capture(),
+ false,
+ );
+ (tx, worker)
+}
+
fn spawn_worker_with_restore(
store: &CohortStore,
catalog: Arc<CatalogHandle>,
@@ -294,7 +345,7 @@ fn spawn_worker_with_restore(
let worker = Stage1Worker::spawn(
PARTITION_ID,
rx,
- store.clone(),
+ test_handle(store),
catalog,
sink,
tracker,
@@ -886,8 +937,17 @@ async fn sweep_emits_entered_when_a_daily_eq_count_falls_into_range() {
send_sweep(&tx, start_of_day_ms_in_tz(day + 9, UTC)).await;
// Barrier on the Enter+Leave (events) + Enter (sweep): the slide advanced the window and
- // rescheduled to the surviving D+3 bucket's leave boundary (start of D+11).
+ // rescheduled to the surviving D+3 bucket's leave boundary (start of D+11). The sweep produces
+ // before its state write, so also wait for the slid record itself.
drain_until_changes(&sink, 3).await;
+ drain_until("the slid daily record to land", || {
+ matches!(
+ state_at(&store, lsk, alice),
+ Some(Stage1State::BehavioralDailyBuckets { ref buckets, .. })
+ if buckets.iter().sum::<u32>() == 1
+ )
+ })
+ .await;
match state_at(&store, lsk, alice).expect("still a member after the slide into eq 1") {
Stage1State::BehavioralDailyBuckets {
buckets,
@@ -1088,7 +1148,16 @@ async fn sweep_emits_entered_when_a_compressed_eq_count_falls_into_range() {
)
.await;
+ // The sweep produces before its state write, so also wait for the slid record before inspecting it.
drain_until_changes(&sink, 3).await;
+ drain_until("the slid compressed record to land", || {
+ matches!(
+ state_at(&store, lsk, alice),
+ Some(Stage1State::BehavioralCompressedHistory { ref entries, .. })
+ if entries.len() == 1
+ )
+ })
+ .await;
match state_at(&store, lsk, alice).expect("still a member after the slide into eq 1") {
Stage1State::BehavioralCompressedHistory {
entries,
@@ -1803,7 +1872,7 @@ async fn dispatch_sweeper_routes_an_end_to_end_eviction() {
let dispatcher = Arc::new(EventDispatcher::new(
PartitionRouter::new(64),
Arc::new(OffsetTracker::new()),
- store.clone(),
+ test_handle(&store),
catalog_of(filters),
sink.clone(),
MergeWorkerDeps::capture(),
@@ -1898,3 +1967,77 @@ fn state_variants_are_exhaustive() {
assert!(!variant.as_str().is_empty());
}
}
+
+/// The three offload modes route the same store ops inline vs onto the blocking pool; the observable
+/// outcome must be identical. One composable cohort driven through enter-then-evict exercises every
+/// lane per mode (event fold, stage-2 composition, sweep prefetch + recompose), catching mode
+/// plumbing that inverts a lane — e.g. `Maintenance` offloading the event read it must run inline.
+#[tokio::test]
+async fn each_offload_mode_yields_the_same_emissions_and_state() {
+ #[derive(Debug, PartialEq)]
+ struct ModeOutcome {
+ statuses: Vec<MembershipStatus>,
+ stage2_bit: Option<bool>,
+ stage1: Vec<(Vec<u8>, Vec<u8>)>,
+ }
+
+ let ts = "2026-05-20 10:00:00.000000";
+ let event_ms = clickhouse_timestamp_to_millis(ts).unwrap();
+ let deadline = event_ms + 7 * DAY_MS;
+ let alice = person(1);
+
+ let mut per_mode: Vec<ModeOutcome> = Vec::new();
+ for mode in [OffloadMode::Off, OffloadMode::Maintenance, OffloadMode::All] {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![behavioral_leaf(7), person_leaf()]);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker_with_mode(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ mode,
+ );
+
+ send_event(&tracker, &tx, person_event_at(alice, ts, 0), 0).await;
+ send_sweep(&tx, deadline + DAY_MS).await;
+ drop(tx);
+ // Join is the barrier: the worker awaits every commit before exiting.
+ worker.join().await.unwrap();
+
+ let statuses: Vec<MembershipStatus> =
+ sink.changes().iter().map(|change| change.status).collect();
+ assert_eq!(
+ statuses,
+ vec![MembershipStatus::Entered, MembershipStatus::Left],
+ "mode {mode:?}: the cohort enters on the event and leaves on the sweep",
+ );
+ let stage1: Vec<(Vec<u8>, Vec<u8>)> = store
+ .scan_stage1(PARTITION_ID, None, 10_000)
+ .unwrap()
+ .into_iter()
+ .map(|(key, value)| (key.encode().to_vec(), value))
+ .collect();
+ assert!(
+ !stage1.is_empty(),
+ "mode {mode:?}: the never-evicted person leaf still holds state",
+ );
+ per_mode.push(ModeOutcome {
+ statuses,
+ stage2_bit: stage2_bit(&store, 1, alice),
+ stage1,
+ });
+ }
+
+ let (off, rest) = per_mode.split_first().unwrap();
+ for (arm, mode) in rest
+ .iter()
+ .zip([OffloadMode::Maintenance, OffloadMode::All])
+ {
+ assert_eq!(
+ arm, off,
+ "mode {mode:?} diverged from Off: emissions, stage-2 bit, and cf_stage1 bytes must be identical across operating points",
+ );
+ }
+}