:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(cohorts): person clustered store schema (#68465)
Matheus Batista659e670e917e
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 42ed25860d7b..6bfd20669012 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2206,7 +2206,6 @@ dependencies = ["futures","hogvm","lifecycle",- "lru","metrics","metrics-exporter-prometheus","object_store",diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex 7c888cf13979..0abe1fc72c0b 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -134,7 +134,6 @@ hyper = { version = "1.9.0", features = ["server", "http1", "http2"] }hyper-util = { version = "0.1.20", features = ["server", "server-graceful", "tokio", "http1", "http2"] }itoa = "1.0.15"libdeflater = "1"-lru = "0.12"metrics = "0.22.0"metrics-exporter-prometheus = "0.14.0"metrics-util = "0.16.0"diff --git a/rust/cohort-stream-processor/Cargo.toml b/rust/cohort-stream-processor/Cargo.tomlindex 11a9ae7447f0..12cce1095305 100644--- a/rust/cohort-stream-processor/Cargo.toml+++ b/rust/cohort-stream-processor/Cargo.toml@@ -35,7 +35,6 @@ envconfig = { workspace = true }futures = { workspace = true }hogvm = { path = "../common/hogvm" }lifecycle = { path = "../common/lifecycle" }-lru = { workspace = true }metrics = { workspace = true }metrics-exporter-prometheus = { workspace = true }# Streaming `BufWriter` and prefix-list (`list_with_delimiter`) S3 for multi-MB checkpoint files.diff --git a/rust/cohort-stream-processor/clippy.toml b/rust/cohort-stream-processor/clippy.tomlindex 0cd24da64ce6..98bc00df68a2 100644--- a/rust/cohort-stream-processor/clippy.toml+++ b/rust/cohort-stream-processor/clippy.toml@@ -6,11 +6,10 @@# 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_behavioral", 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_behavioral", 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" },@@ -20,7 +19,8 @@ disallowed-methods = [{ 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::scan_behavioral", 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_behavioral_prefix", 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" },diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rsindex 43eb410d00a2..64c86a2ccd23 100644--- a/rust/cohort-stream-processor/src/config.rs+++ b/rust/cohort-stream-processor/src/config.rs@@ -13,10 +13,15 @@ use tracing::warn;use crate::store::durability::DurabilityConfig;use crate::store::{OffloadConfig, OffloadMode, StoreConfig};-use crate::workers::{CascadeConfig, EventNameGating, PersonMemoConfig, TransferRetryPolicy};+use crate::workers::{CascadeConfig, EventNameGating, TransferRetryPolicy};const POOL_NAME: &str = "posthog_cohort";+/// The smallest person-record TTL that stays safely beyond the replay horizon of the merge and+/// `clickhouse_events_json` topics (~7 days): a record reclaimed while its events can still replay+/// loses its replay dedup, so a non-zero TTL below this floor warns at startup.+const MIN_SAFE_PERSON_RECORD_TTL_DAYS: u32 = 30;+#[derive(Envconfig, Clone, Debug)]pub struct Config {/// Host for the observability HTTP server (`/_health`, `/_ready`, `/metrics`).@@ -58,15 +63,6 @@ pub struct Config {#[envconfig(from = "REALTIME_COHORT_TEAM_ALLOWLIST", default = "2")]pub team_allowlist: TeamAllowlist,- /// Memoize person-property results per `(team, person)`, skipping re-evaluation when a person's- /// properties are unchanged. Default on.- #[envconfig(from = "COHORT_PERSON_MEMO_ENABLED", default = "true")]- pub cohort_person_memo_enabled: bool,-- /// Per-worker LRU capacity (entries) for the person-property result memo.- #[envconfig(from = "COHORT_PERSON_MEMO_CAPACITY", default = "20000")]- pub cohort_person_memo_capacity: usize,-/// Evaluate only the behavioral conditions whose event name matches the incoming event. Default on.#[envconfig(from = "COHORT_EVENT_NAME_GATING_ENABLED", default = "true")]pub cohort_event_name_gating_enabled: bool,@@ -296,6 +292,12 @@ pub struct Config {#[envconfig(default = "true")]pub wipe_store_on_start: bool,+ /// On a store-schema version mismatch, destroy and recreate the store instead of failing fast.+ /// Off by default: a mismatch is an operator decision (wipe or roll back), not something to eat+ /// silently.+ #[envconfig(from = "COHORT_WIPE_ON_SCHEMA_MISMATCH", default = "false")]+ pub cohort_wipe_on_schema_mismatch: bool,+/// Enable RocksDB statistics so the store-stats publisher can report cache tickers and per-CF/// sizes. See [`StoreConfig::statistics_enabled`].#[envconfig(from = "COHORT_STORE_STATISTICS_ENABLED", default = "true")]@@ -327,6 +329,20 @@ pub struct Config {#[envconfig(from = "COHORT_MAX_BACKGROUND_JOBS", default = "0")]pub cohort_max_background_jobs: i32,+ /// TTL in days for `cf_person_records`: a compaction filter drops a person record whose+ /// `last_seen_ms` is older than this. `0` (the default) disables it — no filter is installed, so a+ /// persisted record never ages out. Attached to `cf_person_records` only; `cf_behavioral` eviction+ /// stays the sweep's contract.+ ///+ /// In production this MUST be well beyond the replay horizon of the merge / `clickhouse_events_json`+ /// topics, so a live-again person's replayed events cannot arrive after their record was reclaimed.+ /// A non-zero value below [`MIN_SAFE_PERSON_RECORD_TTL_DAYS`] days warns at startup.+ /// A TTL-dropped dormant person re-derives on their next event and re-emits `Entered` for+ /// single-leaf person cohorts (at-least-once across dormancy); composable cohorts are suppressed by+ /// the surviving `cf_stage2` bit.+ #[envconfig(from = "COHORT_PERSON_RECORD_TTL_DAYS", default = "0")]+ pub cohort_person_record_ttl_days: u32,+/// 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).@@ -543,13 +559,6 @@ impl Config {}}- pub fn person_memo_config(&self) -> PersonMemoConfig {- PersonMemoConfig {- enabled: self.cohort_person_memo_enabled,- capacity: self.cohort_person_memo_capacity,- }- }-pub fn event_name_gating(&self) -> EventNameGating {EventNameGating::from_enabled(self.cohort_event_name_gating_enabled)}@@ -640,9 +649,19 @@ impl Config {}pub fn store_config(&self) -> StoreConfig {+ if self.person_record_ttl_below_safe_floor() {+ warn!(+ cohort_person_record_ttl_days = self.cohort_person_record_ttl_days,+ safe_floor_days = MIN_SAFE_PERSON_RECORD_TTL_DAYS,+ "COHORT_PERSON_RECORD_TTL_DAYS is inside the replay horizon: a reclaimed record \+ loses its replay dedup, so replayed events for a live-again person re-fold and \+ single-leaf person cohorts re-emit Entered; raise it to the safe floor or above",+ );+ }StoreConfig {path: PathBuf::from(&self.store_path),wipe_on_start: self.effective_wipe_on_start(),+ wipe_on_schema_mismatch: self.cohort_wipe_on_schema_mismatch,statistics_enabled: self.store_statistics_enabled,read_sample_ratio: self.store_read_sample_ratio,block_cache_bytes: self.cohort_block_cache_bytes,@@ -650,10 +669,18 @@ impl Config {compact_on_deletion: self.cohort_compact_on_deletion_enabled,periodic_compaction_seconds: self.cohort_periodic_compaction_seconds,max_background_jobs: self.cohort_max_background_jobs,+ person_record_ttl_days: self.cohort_person_record_ttl_days,..StoreConfig::default()}}+ /// Whether a configured (non-zero) person-record TTL sits inside+ /// [`MIN_SAFE_PERSON_RECORD_TTL_DAYS`] — a misconfiguration worth a startup warning, not a+ /// refusal: the knob is operator-owned and `0` (off) is always safe.+ fn person_record_ttl_below_safe_floor(&self) -> bool {+ (1..MIN_SAFE_PERSON_RECORD_TTL_DAYS).contains(&self.cohort_person_record_ttl_days)+ }+/// Resolve the store-offload strategy and per-lane concurrency bounds handed to the/// [`StoreHandle`](crate::store::StoreHandle).pub fn offload_config(&self) -> OffloadConfig {@@ -809,8 +836,6 @@ mod tests {filter_catalog_refresh_secs: 300,filter_catalog_refresh_jitter_secs: 60,team_allowlist: TeamAllowlist::All,- cohort_person_memo_enabled: true,- cohort_person_memo_capacity: 20000,cohort_event_name_gating_enabled: true,partition_channel_buffer: 128,partition_intake_max_events: 1024,@@ -859,6 +884,7 @@ mod tests {stats_publish_interval_secs: 15,store_path: "cohort-store".to_string(),wipe_store_on_start: true,+ cohort_wipe_on_schema_mismatch: false,store_statistics_enabled: true,store_read_sample_ratio: 64,cohort_block_cache_bytes: 134_217_728,@@ -866,6 +892,7 @@ mod tests {cohort_compact_on_deletion_enabled: true,cohort_periodic_compaction_seconds: 0,cohort_max_background_jobs: 0,+ cohort_person_record_ttl_days: 0,cohort_store_offload_mode: OffloadMode::All,cohort_store_event_read_permits: 16,cohort_store_maintenance_permits: 6,@@ -1043,6 +1070,66 @@ mod tests {assert!(!config.store_config().wipe_on_start);}+ #[test]+ fn wipe_on_schema_mismatch_defaults_off_and_threads_into_store_config() {+ let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();+ assert!(+ !defaults.cohort_wipe_on_schema_mismatch,+ "a schema mismatch must fail fast unless the operator opts in",+ );+ assert!(!defaults.store_config().wipe_on_schema_mismatch);++ let enabled = Config::init_from_hashmap(&std::collections::HashMap::from([(+ "COHORT_WIPE_ON_SCHEMA_MISMATCH".to_owned(),+ "true".to_owned(),+ )]))+ .unwrap();+ assert!(enabled.store_config().wipe_on_schema_mismatch);+ }++ #[test]+ fn person_record_ttl_defaults_off_and_threads_into_store_config() {+ let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();+ assert_eq!(+ defaults.cohort_person_record_ttl_days, 0,+ "the person-record TTL defaults off (no compaction filter)",+ );+ assert_eq!(defaults.store_config().person_record_ttl_days, 0);++ let enabled = Config::init_from_hashmap(&std::collections::HashMap::from([(+ "COHORT_PERSON_RECORD_TTL_DAYS".to_owned(),+ "30".to_owned(),+ )]))+ .unwrap();+ assert_eq!(enabled.cohort_person_record_ttl_days, 30);+ assert_eq!(+ enabled.store_config().person_record_ttl_days,+ 30,+ "the TTL reaches StoreConfig",+ );+ }++ #[test]+ fn person_record_ttl_safe_floor_flags_only_non_zero_values_below_it() {+ let cases = [+ (0u32, false, "off is always safe"),+ (1, true, "inside the replay horizon"),+ (7, true, "the replay horizon itself is unsafe"),+ (29, true, "one below the floor"),+ (30, false, "the floor is safe"),+ (365, false, "well above the floor"),+ ];+ for (days, risky, why) in cases {+ let mut config = test_config();+ config.cohort_person_record_ttl_days = days;+ assert_eq!(+ config.person_record_ttl_below_safe_floor(),+ risky,+ "{days} days: {why}",+ );+ }+ }+#[test]fn stats_knobs_default_on_and_thread_into_store_config() {let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();@@ -1516,35 +1603,6 @@ mod tests {);}- #[test]- fn person_memo_defaults_on_and_overrides_from_env() {- let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();- assert!(- defaults.cohort_person_memo_enabled,- "the person memo defaults on",- );- assert_eq!(defaults.cohort_person_memo_capacity, 20000);- assert!(- defaults.person_memo_config().enabled,- "person_memo_config threads the enabled flag",- );- assert_eq!(defaults.person_memo_config().capacity, 20000);-- let env: std::collections::HashMap<String, String> = [- ("COHORT_PERSON_MEMO_ENABLED", "false"),- ("COHORT_PERSON_MEMO_CAPACITY", "5000"),- ]- .into_iter()- .map(|(key, value)| (key.to_string(), value.to_string()))- .collect();- let config = Config::init_from_hashmap(&env).unwrap();- assert!(- !config.cohort_person_memo_enabled,- "the kill-switch disables the memo",- );- assert_eq!(config.cohort_person_memo_capacity, 5000);- }-#[test]fn event_name_gating_defaults_on_and_overrides_from_env() {let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rsindex bfd8c749dcda..c2cafee734a3 100644--- a/rust/cohort-stream-processor/src/consumers/events.rs+++ b/rust/cohort-stream-processor/src/consumers/events.rs@@ -48,7 +48,7 @@ use crate::partitions::shuffle_message::ShuffleMessage;use crate::producer::MembershipSink;use crate::store::durability::OffsetManifest;use crate::store::StoreHandle;-use crate::workers::{EventNameGating, MergeWorkerDeps, PersonMemoConfig, Stage1Worker};+use crate::workers::{EventNameGating, MergeWorkerDeps, Stage1Worker};/// Back-off after a Kafka transport error so a fast-failing `recv()` can't spin a consume loop.pub(crate) const RECV_ERROR_BACKOFF: Duration = Duration::from_millis(500);@@ -128,8 +128,6 @@ pub struct EventDispatcher {/// after boot. `OnceLock` is `Sync`; the only race (get sees `None` before set) resolves to/// "skip", so a boot partition is never wiped.boot_assignment: OnceLock<HashSet<i32>>,- /// Person-memo config for spawned workers, set once at startup. Unset → disabled.- person_memo: OnceLock<PersonMemoConfig>,/// Event-name fan-out gating for spawned workers, set once at startup. Unset → disabled.event_name_gating: OnceLock<EventNameGating>,}@@ -155,7 +153,6 @@ impl EventDispatcher {draining: AtomicBool::new(false),durable_restore: AtomicBool::new(false),boot_assignment: OnceLock::new(),- person_memo: OnceLock::new(),event_name_gating: OnceLock::new(),}}@@ -169,18 +166,6 @@ impl EventDispatcher {self.durable_restore.load(Ordering::SeqCst)}- /// Must be called before any worker spawns; later calls are ignored.- pub fn set_person_memo_config(&self, config: PersonMemoConfig) {- let _ = self.person_memo.set(config);- }-- fn person_memo_config(&self) -> PersonMemoConfig {- self.person_memo- .get()- .copied()- .unwrap_or(PersonMemoConfig::DISABLED)- }-/// Must be called before any worker spawns; later calls are ignored.pub fn set_event_name_gating(&self, gating: EventNameGating) {let _ = self.event_name_gating.set(gating);@@ -467,7 +452,7 @@ impl EventDispatcher {}match self.router.add_partition(partition) {Some(receiver) => {- let worker = Stage1Worker::spawn_with_memo(+ let worker = Stage1Worker::spawn_with_gating(partition as u16,receiver,self.handle.clone(),@@ -476,7 +461,6 @@ impl EventDispatcher {self.tracker.clone(),self.merge.clone(),self.durable_restore_enabled(),- self.person_memo_config(),self.event_name_gating(),);slot.insert(worker);@@ -1388,8 +1372,8 @@ mod tests {use crate::stage1::state::AppliedOffsets;use crate::stage1::{Stage1State, StatefulRecord};use crate::store::{- CohortStore, LeafStateKey, MergeAppliedKey, MergeDrainKey, OffloadConfig, OffloadMode,- PendingTransferKey, Stage1Key, StoreConfig, TombstoneKey,+ Behavioral, BehavioralKey, CohortStore, LeafStateKey, MergeAppliedKey, MergeDrainKey,+ OffloadConfig, OffloadMode, PendingTransferKey, StoreConfig, TombstoneKey,};use crate::workers::TransferRetryPolicy;@@ -1802,14 +1786,9 @@ mod tests {person: Uuid,lsk: LeafStateKey,) -> Option<Stage1State> {- let key = Stage1Key {- partition_id,- team_id: TEAM as u64,- leaf_state_key: lsk,- person_id: person,- };+ let key = BehavioralKey::new(partition_id, TEAM as u64, person, lsk);store- .get_stage1(&key)+ .get_behavioral(&key).unwrap().map(|bytes| StatefulRecord::decode(&bytes).unwrap().state)}@@ -1817,13 +1796,8 @@ mod tests {fn seed_slice(store: &CohortStore, partition: u16, lsk: LeafStateKey) {store.write_batch(|b| {- b.put_stage1(- &Stage1Key {- partition_id: partition,- team_id: TEAM as u64,- leaf_state_key: lsk,- person_id: person(1),- },+ b.put::<Behavioral>(+ &BehavioralKey::new(partition, TEAM as u64, person(1), lsk),b"state",)})@@ -1832,12 +1806,7 @@ mod tests {fn slice_present(store: &CohortStore, partition: u16, lsk: LeafStateKey) -> bool {store- .get_stage1(&Stage1Key {- partition_id: partition,- team_id: TEAM as u64,- leaf_state_key: lsk,- person_id: person(1),- })+ .get_behavioral(&BehavioralKey::new(partition, TEAM as u64, person(1), lsk)).unwrap().is_some()}@@ -2821,6 +2790,8 @@ mod tests {source_offset: source.1,leaves,forward_hops: 0,++ person_dedup: None,}}@@ -3488,23 +3459,10 @@ mod tests {let partition = partition_of(TeamId(TEAM), &p_new, COHORT_PARTITION_COUNT) as i32;let p_old = person(1);let lsk = LeafStateKey([0xAB; 16]);- let p_old_key = Stage1Key {- partition_id: partition as u16,- team_id: TEAM as u64,- leaf_state_key: lsk,- person_id: p_old,- };+ let p_old_key = BehavioralKey::new(partition as u16, TEAM as u64, p_old, lsk);store.write_batch(|batch| {- batch.put_stage1(&p_old_key, &behavioral_match_record().encode());- batch.merge_person_index(- &crate::store::PersonIndexKey {- partition_id: partition as u16,- team_id: TEAM as u64,- person_id: p_old,- },- crate::store::IndexOp::Append(lsk),- );+ batch.put::<Behavioral>(&p_old_key, &behavioral_match_record().encode());}).unwrap();@@ -3536,7 +3494,7 @@ mod tests {.unwrap().is_some(),);assert!(- store.get_stage1(&p_old_key).unwrap().is_none(),+ store.get_behavioral(&p_old_key).unwrap().is_none(),"P_old's state was deleted",);assert!(sink.changes().is_empty(), "drifted leaves emit nothing");@@ -3591,12 +3549,7 @@ mod tests {);assert!(store- .get_stage1(&Stage1Key {- partition_id: 0,- team_id: TEAM as u64,- leaf_state_key: lsk,- person_id: p_new,- })+ .get_behavioral(&BehavioralKey::new(0, TEAM as u64, p_new, lsk)).unwrap().is_none(),"the drifted leaf wrote no state",diff --git a/rust/cohort-stream-processor/src/consumers/merges.rs b/rust/cohort-stream-processor/src/consumers/merges.rsindex e8abd80ed60e..0771a07a7e18 100644--- a/rust/cohort-stream-processor/src/consumers/merges.rs+++ b/rust/cohort-stream-processor/src/consumers/merges.rs@@ -389,6 +389,8 @@ mod tests {),)],forward_hops: 0,++ person_dedup: None,}}diff --git a/rust/cohort-stream-processor/src/filters/reverse_index.rs b/rust/cohort-stream-processor/src/filters/reverse_index.rsindex ac6f30393b9d..b5ccb05b695b 100644--- a/rust/cohort-stream-processor/src/filters/reverse_index.rs+++ b/rust/cohort-stream-processor/src/filters/reverse_index.rs@@ -16,6 +16,7 @@ use crate::observability::metrics::{COHORT_ELIGIBILITY_TOTAL, COHORT_IN_CYCLE_TOTAL, FILTER_CATALOG_SKIPPED_LEAVES,};use crate::stage1::key::LeafStateKey;+use crate::stage1::person_record::CatalogFingerprint;use crate::stage1::pick_state::{effective_window_days, pick_state_variant, EvictionWindow, PredicateOp,};@@ -51,9 +52,14 @@ pub struct TeamFilters {/// fan-out gate evaluates only the incoming event's bucket.pub behavioral_by_event_name: HashMap<String, Vec<[u8; 16]>>,pub person_property_conditions: HashSet<[u8; 16]>,- /// `person_property_conditions` sorted — the stable bit positions the person memo indexes by, so- /// an entry's bits stay aligned across no-op refreshes.+ /// `person_property_conditions` sorted — the stable order the person record's catalog fingerprint+ /// is computed over.pub person_conditions_ordered: Vec<[u8; 16]>,+ /// SHA-256 over `person_conditions_ordered`, computed once at freeze. A content fingerprint of the+ /// team's person conditions: a stored [`PersonRecord`](crate::stage1::PersonRecord) whose catalog+ /// fingerprint matches this needs no re-evaluation, and a no-op catalog refresh (same conditions)+ /// leaves it unchanged, so records are not needlessly invalidated.+ pub catalog_fingerprint: CatalogFingerprint,/// `LeafStateKey → [CohortId]` for single-leaf cohorts.pub by_lsk_to_single_leaf_cohorts: HashMap<LeafStateKey, Vec<CohortId>>,/// `LeafStateKey → [CohortId]` for `Stage2Composable` cohorts.@@ -82,6 +88,8 @@ impl Default for TeamFilters {behavioral_by_event_name: HashMap::new(),person_property_conditions: HashSet::new(),person_conditions_ordered: Vec::new(),+ // Fingerprint of the empty condition set, matching a `freeze` of no person conditions.+ catalog_fingerprint: CatalogFingerprint::of_sorted(&[]),by_lsk_to_single_leaf_cohorts: HashMap::new(),by_lsk_to_composable_cohorts: HashMap::new(),by_referenced_cohort: HashMap::new(),@@ -260,6 +268,7 @@ impl TeamFiltersBuilder {let mut person_conditions_ordered: Vec<[u8; 16]> =person_property_conditions.iter().copied().collect();person_conditions_ordered.sort_unstable();+ let catalog_fingerprint = CatalogFingerprint::of_sorted(&person_conditions_ordered);let behavioral_by_event_name = behavioral_by_event_name.into_iter()@@ -280,6 +289,7 @@ impl TeamFiltersBuilder {behavioral_by_event_name,person_property_conditions,person_conditions_ordered,+ catalog_fingerprint,by_lsk_to_single_leaf_cohorts,by_lsk_to_composable_cohorts,by_referenced_cohort,@@ -822,6 +832,85 @@ mod tests {);}+ /// Build a person leaf carrying a specific conditionHash literal.+ fn person_leaf_with_hash(hash: &str) -> Value {+ let mut leaf = person_leaf();+ leaf.as_object_mut()+ .unwrap()+ .insert("conditionHash".to_string(), json!(hash));+ leaf+ }++ fn freeze_person_conditions(leaves: Vec<Value>) -> TeamFilters {+ let mut builder = TeamFiltersBuilder::default();+ builder+ .add_cohort(CohortId(1), TeamId(7), &wrap(leaves))+ .unwrap();+ builder.freeze(UTC)+ }++ #[test]+ fn catalog_fingerprint_matches_the_sorted_conditions_and_is_freeze_stable() {+ let a = freeze_person_conditions(vec![+ person_leaf_with_hash("aaaaaaaaaaaaaaaa"),+ person_leaf_with_hash("bbbbbbbbbbbbbbbb"),+ ]);+ assert_eq!(+ a.catalog_fingerprint,+ CatalogFingerprint::of_sorted(&a.person_conditions_ordered),+ );+ let b = freeze_person_conditions(vec![+ person_leaf_with_hash("aaaaaaaaaaaaaaaa"),+ person_leaf_with_hash("bbbbbbbbbbbbbbbb"),+ ]);+ assert_eq!(a.catalog_fingerprint, b.catalog_fingerprint);+ }++ #[test]+ fn catalog_fingerprint_is_invariant_to_insertion_order() {+ let ordered = freeze_person_conditions(vec![+ person_leaf_with_hash("aaaaaaaaaaaaaaaa"),+ person_leaf_with_hash("bbbbbbbbbbbbbbbb"),+ ]);+ let reversed = freeze_person_conditions(vec![+ person_leaf_with_hash("bbbbbbbbbbbbbbbb"),+ person_leaf_with_hash("aaaaaaaaaaaaaaaa"),+ ]);+ assert_eq!(ordered.catalog_fingerprint, reversed.catalog_fingerprint);+ }++ #[test]+ fn catalog_fingerprint_changes_when_a_condition_is_added_or_removed() {+ let two = freeze_person_conditions(vec![+ person_leaf_with_hash("aaaaaaaaaaaaaaaa"),+ person_leaf_with_hash("bbbbbbbbbbbbbbbb"),+ ]);+ let one = freeze_person_conditions(vec![person_leaf_with_hash("aaaaaaaaaaaaaaaa")]);+ let three = freeze_person_conditions(vec![+ person_leaf_with_hash("aaaaaaaaaaaaaaaa"),+ person_leaf_with_hash("bbbbbbbbbbbbbbbb"),+ person_leaf_with_hash("cccccccccccccccc"),+ ]);+ assert_ne!(two.catalog_fingerprint, one.catalog_fingerprint);+ assert_ne!(two.catalog_fingerprint, three.catalog_fingerprint);+ }++ #[test]+ fn catalog_fingerprint_of_no_person_conditions_is_the_empty_constant() {+ // A team with only a behavioral leaf has no person conditions.+ let behavioral_only = freeze_person_conditions(vec![behavioral_performed_event(7)]);+ assert!(behavioral_only.person_conditions_ordered.is_empty());+ assert_eq!(+ behavioral_only.catalog_fingerprint,+ CatalogFingerprint::of_sorted(&[]),+ "no person conditions ⇒ the stable empty-input fingerprint",+ );+ assert_eq!(+ behavioral_only.catalog_fingerprint,+ TeamFilters::default().catalog_fingerprint,+ );+ }+#[test]fn behavioral_by_event_name_buckets_each_name_and_unions_to_behavioral_conditions() {const PURCHASE_HASH: [u8; 16] = *b"purchasehash0002";diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rsindex 11459d32b189..454303c3c866 100644--- a/rust/cohort-stream-processor/src/main.rs+++ b/rust/cohort-stream-processor/src/main.rs@@ -238,8 +238,6 @@ async fn async_main(config: Config) -> Result<()> {if config.durable_restore_enabled {dispatcher.enable_durable_restore();}- // Person-memo config, likewise set before any worker spawns.- dispatcher.set_person_memo_config(config.person_memo_config());// Event-name fan-out gating, likewise set before any worker spawns.dispatcher.set_event_name_gating(config.event_name_gating());diff --git a/rust/cohort-stream-processor/src/merge/apply_handler.rs b/rust/cohort-stream-processor/src/merge/apply_handler.rsindex 09eb7c518008..3c4ebf9c0219 100644--- a/rust/cohort-stream-processor/src/merge/apply_handler.rs+++ b/rust/cohort-stream-processor/src/merge/apply_handler.rs@@ -1,9 +1,9 @@//! Apply a `MergeStateTransfer` on P_new's worker (phase 2 of cross-partition merge).//!//! Given a transfer (P_old's drained per-leaf records), merges each leaf into P_new's state, commits-//! one atomic `WriteBatch` (merged puts, `cf_person_index` appends, and the `cf_merge_applied`-//! idempotence marker), schedules P_new's eviction deadlines, and returns the membership transitions-//! for the caller to compose Stage 2 and produce.+//! one atomic `WriteBatch` (merged puts and the `cf_merge_applied` idempotence marker), schedules+//! P_new's eviction deadlines, and returns the membership transitions for the caller to compose Stage+//! 2 and produce.//!//! Before applying, the target `new_person_uuid` is resolved through the local slice's tombstones://! in a chained merge `A → B → C` where `B → C` drained before `A → B` applies, P_new (= B) is@@ -23,10 +23,14 @@ use crate::observability::metrics::{MERGE_APPLIES_SKIPPED_REPLAY_TOTAL, MERGE_FORWARD_HOP_CAPPED_TOTAL, MERGE_LEAVES_DROPPED_TOTAL,MERGE_TRANSFER_FORWARDS_TOTAL,};-use crate::stage1::key::{LeafStateKey, Stage1Key};+use crate::stage1::key::LeafStateKey;+use crate::stage1::person_record::{PersonDedup, PersonRecord};use crate::stage1::state::StatefulRecord;use crate::stage1::transition::LeafTransition;-use crate::store::{CohortStore, IndexOp, MergeAppliedKey, PersonIndexKey, StoreError};+use crate::store::{+ Behavioral, BehavioralKey, CohortStore, MergeAppliedKey, PersonPrefix, PersonRecords,+ StoreError,+};use crate::sweep::EvictionQueue;use crate::workers::event_path::schedule_deadline;use tracing::warn;@@ -39,14 +43,14 @@ use tracing::warn;#[must_use]#[derive(Debug, Default, Clone, PartialEq, Eq)]pub struct QueueEffects {- pub cancels: Vec<Stage1Key>,- pub schedules: Vec<(Stage1Key, i64)>,+ pub cancels: Vec<BehavioralKey>,+ pub schedules: Vec<(BehavioralKey, 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>) {+ pub fn apply_to(&self, queue: &mut EvictionQueue<BehavioralKey>) {for key in &self.cancels {queue.cancel(key);}@@ -91,7 +95,8 @@ pub enum ApplyOutcome {/// 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.+// `CohortStore` I/O (and that of `apply_into`/`apply_leaves`/`merge_person_records`) is already off+// the runtime threads.#[allow(clippy::disallowed_methods)]pub fn handle_transfer(partition_id: u16,@@ -169,9 +174,8 @@ fn applied_key(}/// Apply `transfer`'s leaves into `target` (the resolved survivor, co-resident on `partition_id`),-/// 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`.+/// commit the merged puts + 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,@@ -213,20 +217,23 @@ fn apply_into(&leaves,)?;- let target_index = PersonIndexKey {- partition_id,- team_id: team_u64,- person_id: target,+ // Fold P_old's person-record dedup into the target's record: a present record absorbs P_old as an+ // ancestor; an absent or corrupt one writes nothing.+ let target_prefix = PersonPrefix::new(partition_id, team_u64, target);+ let record_put = match &transfer.person_dedup {+ Some(dedup) => merge_person_records(store, &target_prefix, old_person, dedup)?,+ None => None,};+let stamp = ApplyStamp {applied_at_ms: transfer.merged_at_ms,};store.write_batch(|batch| {for (key, bytes) in &apply.puts {- batch.put_stage1(key, bytes);+ batch.put::<Behavioral>(key, bytes);}- for lsk in &apply.appends {- batch.merge_person_index(&target_index, IndexOp::Append(*lsk));+ if let Some(bytes) = &record_put {+ batch.put::<PersonRecords>(&target_prefix.record_key(), bytes);}batch.put_merge_applied(&target_applied_key, &stamp.encode());// Fixed-origin dedup: also stamp under the original `new_person_uuid` when the chain@@ -257,14 +264,41 @@ fn apply_into(})}+/// Merge P_old's person-record dedup into the target's record, returning the encoded record to put or+/// `None` to write nothing. A present target record absorbs P_old as an ancestor (idempotent under+/// redelivery). A target with no record — or a corrupt one — writes nothing: the person re-evaluates+/// lazily on their next event.+#[allow(clippy::disallowed_methods)]+pub(crate) fn merge_person_records(+ store: &CohortStore,+ target_prefix: &PersonPrefix,+ old_person: Uuid,+ dedup: &PersonDedup,+) -> Result<Option<Vec<u8>>, StoreError> {+ let bytes = store.get_person_record(&target_prefix.record_key())?;+ let Some(bytes) = bytes else {+ return Ok(None);+ };+ match PersonRecord::decode(&bytes) {+ Ok(mut record) => {+ record.absorb_ancestor(old_person, dedup);+ Ok(Some(record.encode()))+ }+ Err(_) => {+ // Corrupt target record: count and write nothing rather than clobbering it.+ counter!(MERGE_LEAVES_DROPPED_TOTAL, "reason" => "target_record_decode").increment(1);+ Ok(None)+ }+ }+}+/// Computed writes from applying P_old's leaves into P_new, uncommitted so the caller can compose/// the final batch.#[derive(Debug, Default)]pub(crate) struct LeafApply {- pub puts: Vec<(Stage1Key, Vec<u8>)>,- pub appends: Vec<LeafStateKey>,+ pub puts: Vec<(BehavioralKey, Vec<u8>)>,pub transitions: Vec<LeafTransition>,- pub schedules: Vec<(Stage1Key, i64)>,+ pub schedules: Vec<(BehavioralKey, i64)>,}/// Merge each of P_old's `leaves` into P_new's state on `partition_new`. Pure reads only — the@@ -285,16 +319,11 @@ pub(crate) fn apply_leaves(// One batched read of every leaf's `p_new` state. Keys are built in `leaves` order so the zip// below stays aligned; a leaf later skipped by the drift check simply ignores its result.- let p_new_keys: Vec<Stage1Key> = leaves+ let p_new_keys: Vec<BehavioralKey> = leaves.iter()- .map(|(lsk, _)| Stage1Key {- partition_id: partition_new,- team_id: team_u64,- leaf_state_key: *lsk,- person_id: new_person,- })+ .map(|(lsk, _)| BehavioralKey::new(partition_new, team_u64, new_person, *lsk)).collect();- let p_new_raw = store.multi_get_stage1(&p_new_keys)?;+ let p_new_raw = store.multi_get_behavioral(&p_new_keys)?;for ((lsk, old_record), (p_new_key, p_new_bytes)) inleaves.iter().zip(p_new_keys.into_iter().zip(p_new_raw))@@ -321,7 +350,6 @@ pub(crate) fn apply_leaves(out.schedules.push((p_new_key, deadline));}out.puts.push((p_new_key, record.encode()));- out.appends.push(*lsk);}if let Some(kind) = merged.flip {out.transitions.push(LeafTransition {diff --git a/rust/cohort-stream-processor/src/merge/drain_handler.rs b/rust/cohort-stream-processor/src/merge/drain_handler.rsindex b7a10e894677..59d833d5557c 100644--- a/rust/cohort-stream-processor/src/merge/drain_handler.rs+++ b/rust/cohort-stream-processor/src/merge/drain_handler.rs@@ -1,6 +1,7 @@//! Drain P_old on its own worker (phase 1 of cross-partition merge).//!-//! Given a `PersonMergeEvent` (keyed by P_old), reads P_old's per-leaf state, then either:+//! Given a `PersonMergeEvent` (keyed by P_old), enumerates P_old's per-leaf state with one scan of+//! its person prefix, then either://!//! - **fast path** (P_new co-resides on this partition): merges inline via the apply core in one//! atomic `WriteBatch`, returning P_new's transitions; or@@ -8,29 +9,32 @@//! `cf_pending_transfers`, deletes P_old's state, writes the tombstone + drain marker, and returns//! the transfer for the caller to produce.//!-//! The drain emits no `Left` for P_old — it silently deletes P_old's rows. P_old's `cf_stage2` keys-//! are built from the catalog (no reads needed; deleting an absent key is a no-op).+//! The drain emits no `Left` for P_old — it silently reclaims P_old's `cf_behavioral` slice with one+//! range delete over its person prefix. P_old's `cf_stage2` keys are built from the catalog (no+//! reads needed; deleting an absent key is a no-op).-use metrics::counter;+use metrics::{counter, histogram};use uuid::Uuid;use crate::filters::reverse_index::TeamFilters;use crate::filters::{CohortId, TeamId};-use crate::merge::apply_handler::{apply_leaves, QueueEffects};+use crate::merge::apply_handler::{apply_leaves, merge_person_records, QueueEffects};use crate::merge::tombstone_redirect::{resolve, Resolution};use crate::merge::transfer::{DrainStamp, MergeStateTransfer, PendingTransfer, PersonMergeEvent, Tombstone, TransferLeaf,};use crate::observability::metrics::{- MERGE_DRAINS_SKIPPED_REPLAY_TOTAL, MERGE_HANDLED_TOTAL, MERGE_LEAVES_DROPPED_TOTAL,+ MERGE_DRAINS_SKIPPED_REPLAY_TOTAL, MERGE_DRAIN_LEAVES_SCANNED, MERGE_HANDLED_TOTAL,+ MERGE_LEAVES_DROPPED_TOTAL,};use crate::partitions::partitioner::partition_of;-use crate::stage1::key::{LeafStateKey, Stage1Key};+use crate::stage1::key::LeafStateKey;+use crate::stage1::person_record::{PersonDedup, PersonRecord};use crate::stage1::state::StatefulRecord;use crate::stage1::transition::LeafTransition;use crate::store::{- CohortStore, IndexOp, MergeDrainKey, PendingTransferKey, PersonIndexKey, Stage2Key, StoreError,- TombstoneKey,+ Behavioral, BehavioralKey, CohortStore, MergeDrainKey, PendingTransferKey, PersonPrefix,+ PersonRecords, Stage2Key, StoreError, TombstoneKey,};#[derive(Debug, Clone, PartialEq)]@@ -42,8 +46,9 @@ pub enum DrainOutcome {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.- /// `effects` cancels P_old's now-deleted keys (no schedules — the state left this partition).+ /// A transfer with no leaves and no person-record dedup is not staged; the caller skips the produce+ /// and commits directly. `effects` cancels P_old's now-deleted keys (no schedules — the state left+ /// this partition).Drained {transfer: MergeStateTransfer,effects: QueueEffects,@@ -97,37 +102,37 @@ pub fn handle_merge_event(return Ok(DrainOutcome::AlreadyDrained);}- let old_index = PersonIndexKey {- partition_id,- team_id: team_u64,- person_id: old_person,- };- let lsks = store.get_person_index(&old_index)?;- let old_keys: Vec<Stage1Key> = lsks- .iter()- .map(|&lsk| Stage1Key {- partition_id,- team_id: team_u64,- leaf_state_key: lsk,- person_id: old_person,- })- .collect();- let raw = store.multi_get_stage1(&old_keys)?;+ // Enumerate P_old's leaves by prefix-scanning its `cf_behavioral` slice. Scan order is lsk-byte+ // order, so transfer leaf ordering is stable. `old_keys` is kept for the eviction queue's per-key+ // cancels; the range delete below reclaims the rows in one tombstone.+ let old_prefix = PersonPrefix::new(partition_id, team_u64, old_person);+ let old_rows = store.scan_behavioral_prefix(old_prefix)?;+ histogram!(MERGE_DRAIN_LEAVES_SCANNED).record(old_rows.len() as f64);+ let old_keys: Vec<BehavioralKey> = old_rows.iter().map(|(key, _)| *key).collect();let mut present_leaves: Vec<(LeafStateKey, StatefulRecord)> = Vec::new();- for (&lsk, bytes) in lsks.iter().zip(raw) {- match bytes {- None => {- counter!(MERGE_LEAVES_DROPPED_TOTAL, "reason" => "stale_index").increment(1);+ for (key, bytes) in &old_rows {+ match StatefulRecord::decode(bytes) {+ Ok(record) => present_leaves.push((key.lsk(), record)),+ Err(_) => {+ counter!(MERGE_LEAVES_DROPPED_TOTAL, "reason" => "decode").increment(1);}- Some(bytes) => match StatefulRecord::decode(&bytes) {- Ok(record) => present_leaves.push((lsk, record)),+ }+ }++ // P_old's person record carries only its replay-dedup offsets to P_new (never its matched set,+ // fingerprints, or stamp — P_new re-evaluates lazily). Absent or corrupt carries nothing.+ let person_dedup: Option<PersonDedup> =+ match store.get_person_record(&old_prefix.record_key())? {+ None => None,+ Some(bytes) => match PersonRecord::decode(&bytes) {+ Ok(record) => Some(record.dedup_carrier()),Err(_) => {- counter!(MERGE_LEAVES_DROPPED_TOTAL, "reason" => "decode").increment(1);+ counter!(MERGE_LEAVES_DROPPED_TOTAL, "reason" => "record_decode").increment(1);+ None}},- }- }+ };let tombstone = Tombstone {new_person,@@ -181,9 +186,10 @@ pub fn handle_merge_event(&tombstone_key,&tombstone,&old_keys,- &old_index,+ &old_prefix,&old_stage2_keys,&present_leaves,+ person_dedup.as_ref(),);}@@ -198,9 +204,10 @@ pub fn handle_merge_event(&tombstone_key,&tombstone,&old_keys,- &old_index,+ &old_prefix,&old_stage2_keys,&present_leaves,+ person_dedup,)}@@ -216,14 +223,14 @@ fn fast_path(drain_stamp: &DrainStamp,tombstone_key: &TombstoneKey,tombstone: &Tombstone,- old_keys: &[Stage1Key],- old_index: &PersonIndexKey,+ old_keys: &[BehavioralKey],+ old_prefix: &PersonPrefix,old_stage2_keys: &[Stage2Key],present_leaves: &[(LeafStateKey, StatefulRecord)],+ person_dedup: Option<&PersonDedup>,) -> Result<DrainOutcome, StoreError> {counter!(MERGE_HANDLED_TOTAL, "path" => "same_partition").increment(1);- let team_u64 = event.team_id as u64;let apply = apply_leaves(partition_id,store,@@ -234,26 +241,28 @@ fn fast_path(present_leaves,)?;- let new_index = PersonIndexKey {- partition_id,- team_id: team_u64,- person_id: effective_new_person,+ // Fold P_old's record dedup into P_new's record in the same batch; an absent/corrupt P_new record+ // writes nothing.+ let team_u64 = event.team_id as u64;+ let new_prefix = PersonPrefix::new(partition_id, team_u64, effective_new_person);+ let record_put = match person_dedup {+ Some(dedup) => merge_person_records(store, &new_prefix, event.old_person_uuid, dedup)?,+ None => None,};+store.write_batch(|batch| {- for key in old_keys {- batch.delete_stage1(key);- }- batch.delete_person_index(old_index);+ batch.delete_behavioral_prefix(old_prefix);+ batch.delete::<PersonRecords>(&old_prefix.record_key());for key in old_stage2_keys {batch.delete_stage2(key);}batch.put_tombstone(tombstone_key, &tombstone.encode());batch.put_merge_drain_applied(drain_key, &drain_stamp.encode());for (key, bytes) in &apply.puts {- batch.put_stage1(key, bytes);+ batch.put::<Behavioral>(key, bytes);}- for lsk in &apply.appends {- batch.merge_person_index(&new_index, IndexOp::Append(*lsk));+ if let Some(bytes) = &record_put {+ batch.put::<PersonRecords>(&new_prefix.record_key(), bytes);}})?;@@ -278,10 +287,11 @@ fn slow_path(drain_stamp: &DrainStamp,tombstone_key: &TombstoneKey,tombstone: &Tombstone,- old_keys: &[Stage1Key],- old_index: &PersonIndexKey,+ old_keys: &[BehavioralKey],+ old_prefix: &PersonPrefix,old_stage2_keys: &[Stage2Key],present_leaves: &[(LeafStateKey, StatefulRecord)],+ person_dedup: Option<PersonDedup>,) -> Result<DrainOutcome, StoreError> {counter!(MERGE_HANDLED_TOTAL, "path" => "cross_partition").increment(1);@@ -298,10 +308,13 @@ fn slow_path(.map(|(lsk, record)| TransferLeaf::new(*lsk, record.clone())).collect(),forward_hops: 0,+ person_dedup,};- // An empty transfer is never staged: a duplicate merge event at fresh coordinates could- // overwrite a still-pending, never-produced transfer with an empty payload.- let pending = (!transfer.leaves.is_empty()).then(|| PendingTransfer {+ // Stage iff the transfer carries leaves or a person-record dedup; a record-only person would+ // otherwise lose its straggler-dedup ancestry. A truly empty transfer is never staged — a duplicate+ // merge event at fresh coordinates could overwrite a still-pending, never-produced transfer.+ let has_payload = !transfer.leaves.is_empty() || transfer.person_dedup.is_some();+ let pending = has_payload.then(|| PendingTransfer {transfer: transfer.clone(),merge_msg_partition: msg_coords.0,merge_msg_offset: msg_coords.1,@@ -317,10 +330,8 @@ fn slow_path(batch.put_pending_transfer(&pending_key, &pending.encode());}batch.put_merge_drain_applied(drain_key, &drain_stamp.encode());- for key in old_keys {- batch.delete_stage1(key);- }- batch.delete_person_index(old_index);+ batch.delete_behavioral_prefix(old_prefix);+ batch.delete::<PersonRecords>(&old_prefix.record_key());for key in old_stage2_keys {batch.delete_stage2(key);}diff --git a/rust/cohort-stream-processor/src/merge/rules.rs b/rust/cohort-stream-processor/src/merge/rules.rsindex 58ed9f3d9ce7..5b14c880bec1 100644--- a/rust/cohort-stream-processor/src/merge/rules.rs+++ b/rust/cohort-stream-processor/src/merge/rules.rs@@ -16,7 +16,9 @@ use crate::observability::metrics::MERGE_LEAVES_DROPPED_TOTAL;use crate::stage1::bucket_tz::{daily_bucket_len, now_day_for_window};use crate::stage1::compressed_history::{compressed_eviction_deadline, slide_window_forward};use crate::stage1::daily::daily_eviction_deadline;-use crate::stage1::state::{AppliedOffsets, Stage1State, StateVariant, StatefulRecord};+#[cfg(test)]+use crate::stage1::state::StateVariant;+use crate::stage1::state::{AppliedOffsets, Stage1State, StatefulRecord};use crate::stage1::transition::TransitionKind;use crate::stage2::evaluator::leaf_membership;@@ -48,11 +50,6 @@ pub fn merge_records(return keep_new(old_person, old, new);}- // Person properties: drop P_old's bit; P_new re-evaluates lazily on its next event.- if matches!(meta.variant, StateVariant::PersonProperty) {- return keep_new(old_person, old, new);- }-let merged_state = match new {None => old.state.clone(),Some(new_record) => match merge_behavioral_pair(meta, &old.state, &new_record.state, tz) {@@ -289,16 +286,6 @@ mod tests {}}- fn person_meta() -> LeafStateMeta {- LeafStateMeta {- variant: StateVariant::PersonProperty,- condition_hash: [0; 16],- window: None,- window_days: None,- predicate_op: None,- }- }-fn single(last: i64, deadline: i64) -> StatefulRecord {StatefulRecord::new(Stage1State::BehavioralSingle {@@ -334,17 +321,6 @@ mod tests {)}- fn person(matches: bool, last: i64) -> StatefulRecord {- StatefulRecord::new(- Stage1State::PersonProperty {- matches,- last_updated_at_ms: last,- last_updated_offset: 0,- },- AppliedOffsets::default(),- )- }-fn applied(entries: &[(i32, i64)]) -> AppliedOffsets {let mut applied = AppliedOffsets::default();for &(partition, offset) in entries {@@ -547,29 +523,6 @@ mod tests {}}- #[test]- fn person_property_keeps_new_and_drops_old() {- let merged = merge_records(- uuid(1),- &person(true, 100),- Some(&person(false, 200)),- &person_meta(),- TZ,- );- assert_eq!(merged.flip, None);- assert!(matches!(- merged.record.unwrap().state,- Stage1State::PersonProperty { matches: false, .. }- ));- }-- #[test]- fn person_property_with_absent_new_writes_nothing() {- let merged = merge_records(uuid(1), &person(true, 100), None, &person_meta(), TZ);- assert_eq!(merged.record, None, "no state migrated for P_new");- assert_eq!(merged.flip, None);- }-#[test]fn merged_record_keeps_p_news_main_map_and_adds_an_ancestor_entry() {let mut old = single(100, 500);@@ -613,7 +566,7 @@ mod tests {fn variant_mismatch_keeps_new_defensively() {let merged = merge_records(uuid(1),- &person(true, 100),+ &daily(vec![0u32; 8], 100),Some(&single(200, 400)),&single_meta(),TZ,diff --git a/rust/cohort-stream-processor/src/merge/transfer.rs b/rust/cohort-stream-processor/src/merge/transfer.rsindex f7b8654391f2..b9f828a0a0ee 100644--- a/rust/cohort-stream-processor/src/merge/transfer.rs+++ b/rust/cohort-stream-processor/src/merge/transfer.rs@@ -10,6 +10,7 @@ use serde::{Deserialize, Serialize};use uuid::Uuid;use crate::stage1::key::LeafStateKey;+use crate::stage1::person_record::PersonDedup;use crate::stage1::state::StatefulRecord;pub const MERGE_EVENT_SCHEMA_VERSION: u32 = 1;@@ -64,6 +65,13 @@ pub struct MergeStateTransfer {/// without the field decodes to `0`, so the field is JSON-compatible both ways.#[serde(default)]pub forward_hops: u8,+ /// P_old's person-record replay-dedup, carried so a straggler routed to P_new after the merge+ /// deduplicates against P_old's high-water marks. Only the offsets travel — never P_old's matched+ /// set, fingerprints, or stamp; P_new re-evaluates the person lazily. `#[serde(default,+ /// skip_serializing_if)]`: wire-compatible both ways, and a person with no record contributes no+ /// field.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub person_dedup: Option<PersonDedup>,}/// Staged transfer in `cf_pending_transfers`. Survives a crash between the drain batch and the@@ -146,6 +154,8 @@ fn hex_decode(s: &str) -> Option<[u8; 16]> {#[cfg(test)]mod tests {+ use std::collections::BTreeMap;+use super::*;use crate::stage1::state::{AppliedOffsets, Stage1State};@@ -235,6 +245,8 @@ mod tests {source_offset: 12_345,leaves: vec![TransferLeaf::new(LeafStateKey([0xAB; 16]), single_record())],forward_hops: 0,++ person_dedup: None,};let decoded = MergeStateTransfer::decode(&transfer.encode()).unwrap();assert_eq!(decoded, transfer);@@ -245,6 +257,38 @@ mod tests {);}+ #[test]+ fn transfer_round_trips_a_non_empty_person_dedup() {+ // Every other round-trip sets `person_dedup: None`. `PersonDedup.redirect_dedup` carries+ // `#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]`; a non-empty round-trip is+ // what guards that derive. If it silently dropped the field, the None-only tests would all+ // still pass, so assert the offsets survive the wire whole.+ let mut redirect_dedup = BTreeMap::new();+ redirect_dedup.insert(+ uuid(0xCCCC),+ AppliedOffsets::from_sorted_entries(vec![(3, 300)]),+ );+ let transfer = MergeStateTransfer {+ team_id: 7,+ old_person_uuid: uuid(0xAAAA),+ new_person_uuid: uuid(0xBBBB),+ merged_at_ms: 1_716_800_000_000,+ source_partition: 17,+ source_offset: 12_345,+ leaves: vec![],+ forward_hops: 0,+ person_dedup: Some(PersonDedup {+ applied_offsets: AppliedOffsets::from_sorted_entries(vec![(1, 100), (2, 200)]),+ redirect_dedup,+ }),+ };+ let decoded = MergeStateTransfer::decode(&transfer.encode()).unwrap();+ assert_eq!(+ decoded, transfer,+ "a non-empty person_dedup (direct + redirect offsets) survives the wire round-trip",+ );+ }+#[test]fn transfer_without_forward_hops_decodes_to_zero_for_wire_compat() {// A transfer JSON that omits `forward_hops` must decode to `0` (`#[serde(default)]`).@@ -275,6 +319,8 @@ mod tests {source_offset: 4,leaves: vec![],forward_hops: 0,++ person_dedup: None,};let pending = PendingTransfer {transfer,diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rsindex 3cf28a044145..c1273da9c11d 100644--- a/rust/cohort-stream-processor/src/observability/metrics.rs+++ b/rust/cohort-stream-processor/src/observability/metrics.rs@@ -62,7 +62,7 @@ pub const DURABLE_RESTORE_PARTITIONS_KEPT_TOTAL: &str = "durable_restore_partiti/// from the committed offset (counter).pub const DURABLE_RESTORE_PARTITIONS_WIPED_STALE_TOTAL: &str ="durable_restore_partitions_wiped_stale_total";-/// `cf_stage1` keys re-seeded into a worker's `EvictionQueue` on spawn during a durable restart,+/// `cf_behavioral` keys re-seeded into a worker's `EvictionQueue` on spawn during a durable restart,/// labelled by `partition` (counter). Re-fires a dormant person's `Left`.pub const EVICTION_QUEUE_REBUILT_KEYS_TOTAL: &str = "eviction_queue_rebuilt_keys_total";/// Owned partitions that had at least one `cf_pending_transfers` entry re-produced by the eager boot@@ -118,8 +118,10 @@ pub const STORE_WRITE_BATCH_TOTAL: &str = "store_write_batch_total";pub const STORE_WRITE_DURATION_SECONDS: &str = "store_write_duration_seconds";/// RocksDB operations that returned an error, labelled by `op` (counter).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";+/// Stores destroyed and recreated at open because the on-disk schema version did not match, under the+/// `COHORT_WIPE_ON_SCHEMA_MISMATCH` opt-in (counter). Non-zero means a store layout revision wiped+/// durable state; expected only on a deliberate schema migration.+pub const STORE_SCHEMA_MISMATCH_WIPES_TOTAL: &str = "store_schema_mismatch_wipes_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.@@ -255,25 +257,30 @@ pub const STAGE1_EVENTS_SKIPPED: &str = "stage1_events_skipped_total";/// HogVM evaluations, labelled by `kind` — one per unique conditionHash per event (counter).pub const STAGE1_CONDITIONS_EVALUATED: &str = "stage1_conditions_evaluated_total";/// Condition evaluations skipped because the result was already known, labelled by `reason`-/// (`person_memo_hit`|`event_name_gate`) (counter).+/// (`event_name_gate`) (counter).pub const STAGE1_CONDITIONS_SKIPPED: &str = "stage1_conditions_skipped_total";-/// Person-property memo lookups, labelled by `result` (`hit`|`miss`) (counter).-pub const STAGE1_PERSON_MEMO: &str = "stage1_person_memo_total";+/// Person side of an event resolved against the durable [`crate::stage1::PersonRecord`], labelled by+/// `result` (`fresh`|`stale_props`|`stale_catalog`|`stale_both`|`absent`|`corrupt`|`argmax_stale`|+/// `replay`) (counter). One increment per event that touches the person side. `absent`/`corrupt` come+/// from the prior-record classification (an evaluation from nothing), not the freshness axis, so they+/// are not folded into `stale_both`.+pub const STAGE1_PERSON_RECORD_TOTAL: &str = "stage1_person_record_total";+/// Encoded byte size of a [`crate::stage1::PersonRecord`] at each write (histogram). Watches record+/// growth on hot persons; the TTL backstop bounds it.+pub const STAGE1_PERSON_RECORD_SIZE_BYTES: &str = "stage1_person_record_size_bytes";+/// Behavioral applies staged per event — the write fan-out of the behavioral side (histogram).+pub const STAGE1_BEHAVIORAL_APPLIES: &str = "stage1_behavioral_applies";/// Leaf membership flips emitted, labelled by `kind` (counter).pub const STAGE1_TRANSITIONS: &str = "stage1_transitions_total";-/// `cf_stage1` records written, labelled by `variant` (counter).+/// `cf_behavioral` records written, labelled by `variant` (counter).pub const STAGE1_STATE_WRITES: &str = "stage1_state_writes_total";-/// First-time `cf_person_index` appends, one per newly-seen `(person, leaf_state_key)` (counter).-pub const STAGE1_PERSON_INDEX_APPENDS: &str = "stage1_person_index_appends_total";/// Applies skipped because the source `(partition, offset)` was already folded in, labelled by/// `variant` (counter).pub const STAGE1_REPLAY_SKIPPED: &str = "stage1_replay_skipped_total";-/// Person-property applies dropped by the event-time argMax tiebreaker (counter).-pub const STAGE1_ARGMAX_STALE: &str = "stage1_argmax_stale_total";/// Applies skipped because the leaf's resolved variant is unsupported, labelled by `variant`/// (counter). A defensive guard against a stale catalog.pub const STAGE1_UNSUPPORTED_VARIANT_SKIPPED: &str = "stage1_unsupported_variant_skipped_total";-/// Stored `cf_stage1` values that failed to decode; the key is skipped, not panicked (counter).+/// Stored `cf_behavioral` values that failed to decode; the key is skipped, not panicked (counter).pub const STAGE1_STATE_DECODE_ERROR: &str = "stage1_state_decode_error_total";/// End-to-end per-event processing latency in the worker (histogram, seconds).pub const STAGE1_EVENT_PROCESS_DURATION: &str = "stage1_event_process_duration_seconds";@@ -411,6 +418,10 @@ pub const MERGE_HELD_OFFSET_GAUGE: &str = "merge_held_offset";pub const MERGE_DRAIN_DURATION_SECONDS: &str = "merge_drain_duration_seconds";/// Latency of one transfer apply (histogram, seconds).pub const MERGE_APPLY_DURATION_SECONDS: &str = "merge_apply_duration_seconds";+/// Behavioral rows enumerated for P_old on one merge drain — the drain-scan cost distribution+/// (histogram). Recorded once per non-replay drain. The drain enumerates P_old's leaves with a prefix+/// scan, so this is the visibility into how many rows that scan touches.+pub const MERGE_DRAIN_LEAVES_SCANNED: &str = "merge_drain_leaves_scanned";/// Merge-CF keys scanned by the GC sweep, labelled by `cf` (counter).pub const MERGE_GC_KEYS_SCANNED_TOTAL: &str = "merge_gc_keys_scanned_total";@@ -609,6 +620,16 @@ mod tests {assert_eq!(PENDING_HELD_EVENTS, "pending_held_events");}+ #[test]+ fn person_record_metric_names_are_stable() {+ assert_eq!(STAGE1_PERSON_RECORD_TOTAL, "stage1_person_record_total");+ assert_eq!(+ STAGE1_PERSON_RECORD_SIZE_BYTES,+ "stage1_person_record_size_bytes",+ );+ assert_eq!(STAGE1_BEHAVIORAL_APPLIES, "stage1_behavioral_applies");+ }+#[test]fn stage2_orphan_gc_metric_names_are_stable() {assert_eq!(@@ -628,4 +649,13 @@ mod tests {"stage2_orphan_gc_undecodable_keys_total",);}++ #[test]+ fn schema_guard_and_drain_scan_metric_names_are_stable() {+ assert_eq!(+ STORE_SCHEMA_MISMATCH_WIPES_TOTAL,+ "store_schema_mismatch_wipes_total",+ );+ assert_eq!(MERGE_DRAIN_LEAVES_SCANNED, "merge_drain_leaves_scanned");+ }}diff --git a/rust/cohort-stream-processor/src/partitions/offset_tracker.rs b/rust/cohort-stream-processor/src/partitions/offset_tracker.rsindex 390ecf9c7921..9da3f6b76d55 100644--- a/rust/cohort-stream-processor/src/partitions/offset_tracker.rs+++ b/rust/cohort-stream-processor/src/partitions/offset_tracker.rs@@ -4,7 +4,7 @@//! channel plus serial worker already guarantee in-partition order.//!//! Per-key replay dedup is a separate concern, owned by-//! [`AppliedOffsets`](crate::stage1::state::AppliedOffsets) on each `cf_stage1` record.+//! [`AppliedOffsets`](crate::stage1::state::AppliedOffsets) on each `cf_behavioral` record.use std::collections::HashMap;diff --git a/rust/cohort-stream-processor/src/partitions/rebalance.rs b/rust/cohort-stream-processor/src/partitions/rebalance.rsindex f3a06a9ec2be..f7f3c771bbf8 100644--- a/rust/cohort-stream-processor/src/partitions/rebalance.rs+++ b/rust/cohort-stream-processor/src/partitions/rebalance.rs@@ -198,7 +198,8 @@ mod tests {use crate::partitions::{MarkOutcome, OffsetTracker, PartitionRouter};use crate::producer::{CaptureSink, MembershipSink};use crate::store::{- CohortStore, LeafStateKey, OffloadConfig, OffloadMode, Stage1Key, StoreConfig, StoreHandle,+ Behavioral, BehavioralKey, CohortStore, LeafStateKey, OffloadConfig, OffloadMode,+ StoreConfig, StoreHandle,};use crate::workers::MergeWorkerDeps;use uuid::Uuid;@@ -420,25 +421,25 @@ mod tests {assert!(!dispatcher.owns(3));}- fn slice_key(partition: u16) -> Stage1Key {- Stage1Key {- partition_id: partition,- team_id: 7,- leaf_state_key: LeafStateKey([0xAB; 16]),- person_id: Uuid::from_u128(1),- }+ fn slice_key(partition: u16) -> BehavioralKey {+ BehavioralKey::new(partition, 7, Uuid::from_u128(1), LeafStateKey([0xAB; 16]))}fn seed_slice(store: &CohortStore, partition: u16) {store- .write_batch(|b| b.put_stage1(&slice_key(partition), b"state"))+ .write_batch(|b| b.put::<Behavioral>(&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(store: &CohortStore, partition: u16) -> impl Fn() -> bool + '_ {- move || store.get_stage1(&slice_key(partition)).unwrap().is_some()+ move || {+ store+ .get_behavioral(&slice_key(partition))+ .unwrap()+ .is_some()+ }}fn seed_and_present(store: &CohortStore, partition: u16) -> impl Fn() -> bool + '_ {diff --git a/rust/cohort-stream-processor/src/partitions/shuffle_message.rs b/rust/cohort-stream-processor/src/partitions/shuffle_message.rsindex de9f8778d685..a65ab79aabb6 100644--- a/rust/cohort-stream-processor/src/partitions/shuffle_message.rs+++ b/rust/cohort-stream-processor/src/partitions/shuffle_message.rs@@ -125,6 +125,8 @@ mod tests {source_offset: 9,leaves: vec![],forward_hops: 0,++ person_dedup: None,}}diff --git a/rust/cohort-stream-processor/src/producer/cascade.rs b/rust/cohort-stream-processor/src/producer/cascade.rsindex 1a7dbfe56a39..2a0ac375c40b 100644--- a/rust/cohort-stream-processor/src/producer/cascade.rs+++ b/rust/cohort-stream-processor/src/producer/cascade.rs@@ -2,7 +2,7 @@//!//! [`cascade_key`] keys on `(team, person)` over the same `murmur2_random` partitioner as the//! shuffler, so a flip co-partitions with `cohort_stream_events` and lands on the worker that owns-//! that person's `cf_stage1`/`cf_stage2`.+//! that person's `cf_behavioral`/`cf_stage2`.use anyhow::{Context, Result};use async_trait::async_trait;diff --git a/rust/cohort-stream-processor/src/producer/merge.rs b/rust/cohort-stream-processor/src/producer/merge.rsindex 8f5010a69371..283b78cc3406 100644--- a/rust/cohort-stream-processor/src/producer/merge.rs+++ b/rust/cohort-stream-processor/src/producer/merge.rs@@ -261,6 +261,8 @@ mod tests {),)],forward_hops: 0,++ person_dedup: None,}}diff --git a/rust/cohort-stream-processor/src/stage1/key.rs b/rust/cohort-stream-processor/src/stage1/key.rsindex 313d587c9caf..384c8c324f82 100644--- a/rust/cohort-stream-processor/src/stage1/key.rs+++ b/rust/cohort-stream-processor/src/stage1/key.rs@@ -1,11 +1,10 @@-//! `LeafStateKey` derivation and `Stage1Key`.+//! `LeafStateKey` derivation.//!//! `conditionHash` encodes only the event matcher, so two leaves with different windows can share//! the same hash. State is keyed by a [`LeafStateKey`] that hashes the full predicate configuration.use serde::{Deserialize, Serialize};use sha2::{Digest, Sha256};-use uuid::Uuid;use crate::filters::tree::BehavioralLeafConfig;@@ -44,15 +43,6 @@ impl LeafStateKey {}}-/// Stage 1 state-storage key. Partition prefix enables per-partition `delete_range` on rebalance.-#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]-pub struct Stage1Key {- pub partition_id: u16,- pub team_id: u64,- pub leaf_state_key: LeafStateKey,- pub person_id: Uuid,-}-#[cfg(test)]mod tests {use std::sync::Arc;diff --git a/rust/cohort-stream-processor/src/stage1/mod.rs b/rust/cohort-stream-processor/src/stage1/mod.rsindex 052bb7711405..90029c8dde3a 100644--- a/rust/cohort-stream-processor/src/stage1/mod.rs+++ b/rust/cohort-stream-processor/src/stage1/mod.rs@@ -6,12 +6,18 @@ pub mod bucket_tz;pub mod compressed_history;pub mod daily;pub mod key;+pub mod person_record;pub mod pick_state;pub mod predicate;pub mod state;pub mod time;pub mod transition;+pub use person_record::{+ apply_eval, apply_skip_eval, apply_stale, decide, CatalogFingerprint, Decision, DedupCoords,+ Freshness, MatchedSet, PersonDedup, PersonRecord, PersonRecordCodecError, PriorRecord,+ PropsFingerprint, Stamp,+};pub use pick_state::{pick_state_variant, EvictionWindow, PredicateOp, TimeInterval, UnsupportedVariant,};diff --git a/rust/cohort-stream-processor/src/stage1/person_record.rs b/rust/cohort-stream-processor/src/stage1/person_record.rsnew file mode 100644index 000000000000..1251cde5db7a--- /dev/null+++ b/rust/cohort-stream-processor/src/stage1/person_record.rs@@ -0,0 +1,1480 @@+//! The durable per-person record: one row that collapses all of a person's person-property leaf+//! state into a single value, plus the pure decision core that drives its update.+//!+//! A [`PersonRecord`] carries, once for the whole person:+//!+//! - A record-level argMax [`Stamp`] (`(ms, offset)`) that decides staleness for the person as a+//! unit (an equal-or-older stamp is stale).+//! - A [`PropsFingerprint`] (SHA-256 of the raw `person_properties`) and a [`CatalogFingerprint`]+//! (SHA-256 over the sorted person condition hashes) that together decide whether the person's+//! evaluated membership can possibly have changed: if both match the stored record, no HogVM+//! evaluation is needed.+//! - A [`MatchedSet`] of the condition hashes that currently evaluate TRUE; membership transitions+//! are the set difference between the stored and freshly-evaluated sets.+//! - The replay-dedup offsets (`applied_offsets` + `redirect_dedup`), shared with the per-row codec+//! via the same free functions in [`crate::stage1::state`] so record- and row-level dedup cannot+//! drift.+//!+//! The [`decide`] / `apply_*` split is a pure, table-testable core with no store, HogVM, or clock:+//! [`decide`] classifies an event against the prior record into a [`Decision`], and the `apply_*`+//! constructors build the next record for each arm.++use std::collections::BTreeMap;++use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};+use uuid::Uuid;++use crate::stage1::state::{dedup_is_replay, dedup_record, AppliedOffsets};+use crate::stage1::transition::TransitionKind;++/// The record-level argMax key: last-write-wins ordered by event time then source offset. "Fresh"+/// is strictly greater — an equal-or-older stamp is stale.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Stamp {+ pub ms: i64,+ pub offset: i64,+}++impl Stamp {+ /// The baseline for an absent (or corrupt) prior record: older than every real event, so the+ /// first event is always fresh against it.+ pub const MIN: Self = Self {+ ms: i64::MIN,+ offset: i64::MIN,+ };++ pub fn new(ms: i64, offset: i64) -> Self {+ Self { ms, offset }+ }+}++impl PartialOrd for Stamp {+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {+ Some(self.cmp(other))+ }+}++impl Ord for Stamp {+ fn cmp(&self, other: &Self) -> std::cmp::Ordering {+ // Lexicographic: ms first, offset as the tiebreaker.+ (self.ms, self.offset).cmp(&(other.ms, other.offset))+ }+}++/// 128 bits of SHA-256 over the raw `person_properties` bytes — collision-negligible and computable+/// without a JSON parse, so an unchanged props payload short-circuits before any evaluation.+///+/// The `u128` is the little-endian interpretation of the digest's first 16 bytes, so its 16-byte+/// encoding is exactly those digest bytes (round-trip byte-stable).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct PropsFingerprint(pub u128);++impl PropsFingerprint {+ pub fn of(raw: &str) -> Self {+ let digest = Sha256::digest(raw.as_bytes());+ Self(u128::from_le_bytes(+ digest[..16].try_into().expect("SHA-256 yields 32 bytes"),+ ))+ }++ /// The raw digest-prefix bytes (little-endian of the `u128`).+ fn to_bytes(self) -> [u8; 16] {+ self.0.to_le_bytes()+ }++ fn from_bytes(bytes: [u8; 16]) -> Self {+ Self(u128::from_le_bytes(bytes))+ }+}++/// 128 bits of SHA-256 over the concatenation of a team's `person_conditions_ordered` (its sorted+/// person condition hashes). Two catalog snapshots with the same person conditions produce the same+/// fingerprint; adding, removing, or changing a person condition changes it. Empty conditions hash+/// the empty input, a stable constant.+///+/// A content fingerprint, so a no-op catalog refresh (same conditions) does not invalidate stored+/// records.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct CatalogFingerprint(pub u128);++impl CatalogFingerprint {+ /// Fingerprint the already-sorted person condition hashes. The input must be sorted (as+ /// `person_conditions_ordered` is) so a permutation of the same conditions yields one value.+ pub fn of_sorted(conditions: &[[u8; 16]]) -> Self {+ let mut hasher = Sha256::new();+ for condition in conditions {+ hasher.update(condition);+ }+ let digest = hasher.finalize();+ Self(u128::from_le_bytes(+ digest[..16].try_into().expect("SHA-256 yields 32 bytes"),+ ))+ }++ fn to_bytes(self) -> [u8; 16] {+ self.0.to_le_bytes()+ }++ fn from_bytes(bytes: [u8; 16]) -> Self {+ Self(u128::from_le_bytes(bytes))+ }+}++/// A sorted, deduplicated set of condition hashes that currently evaluate TRUE for a person. The+/// sortedness is upheld by the constructors, so a stored record's bytes are canonical and+/// [`Self::contains`] is a binary search.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct MatchedSet(Vec<[u8; 16]>);++impl MatchedSet {+ pub fn empty() -> Self {+ Self(Vec::new())+ }++ /// Reconstruct from bytes already known to be sorted and distinct (the codec verifies this+ /// before calling), skipping the re-sort.+ fn from_sorted_distinct(hashes: Vec<[u8; 16]>) -> Self {+ Self(hashes)+ }++ pub fn contains(&self, hash: &[u8; 16]) -> bool {+ self.0.binary_search(hash).is_ok()+ }++ pub fn len(&self) -> usize {+ self.0.len()+ }++ pub fn is_empty(&self) -> bool {+ self.0.is_empty()+ }++ pub fn iter(&self) -> impl Iterator<Item = &[u8; 16]> {+ self.0.iter()+ }++ /// The person transitions from this set (`S`, the stored/prior TRUE set) to `next` (`T`, the+ /// freshly evaluated TRUE set), given the current `catalog` (`person_conditions_ordered`,+ /// sorted). The ONLY producer of person membership transitions:+ ///+ /// - `Entered` = `T \ S`: a hash that is TRUE now and was not before.+ /// - `Left` = `(S ∩ catalog) \ T`: a hash that was TRUE, is still in the catalog, and is no+ /// longer TRUE. Restricting to `S ∩ catalog` means a hash whose condition was removed from the+ /// catalog does NOT emit `Left` — it is retained silently. That retention prevents a duplicate+ /// `Entered` if the condition is later re-added: the hash stays in `S`, so re-adding it is not+ /// a new entry.+ ///+ /// Hashes in `S \ catalog` are neither entered nor left — they are the retained orphans.+ pub fn diff<'a>(+ &'a self,+ next: &'a MatchedSet,+ catalog: &'a [[u8; 16]],+ ) -> impl Iterator<Item = ([u8; 16], TransitionKind)> + 'a {+ debug_assert_sorted(catalog);+ let entered = next+ .0+ .iter()+ .filter(move |hash| !self.contains(hash))+ .map(|hash| (*hash, TransitionKind::Entered));+ let left = self+ .0+ .iter()+ .filter(move |hash| catalog.binary_search(hash).is_ok() && !next.contains(hash))+ .map(|hash| (*hash, TransitionKind::Left));+ entered.chain(left)+ }+}++/// `MatchedSet::from_iter(...)` (and `.collect()`) sorts and deduplicates so the sortedness invariant+/// holds regardless of input order.+impl FromIterator<[u8; 16]> for MatchedSet {+ fn from_iter<I: IntoIterator<Item = [u8; 16]>>(hashes: I) -> Self {+ let mut hashes: Vec<[u8; 16]> = hashes.into_iter().collect();+ hashes.sort_unstable();+ hashes.dedup();+ Self(hashes)+ }+}++/// The replay-dedup carrier a merge moves from P_old to P_new: only the offsets, never the matched+/// set, fingerprints, or stamp, so P_new re-evaluates lazily. Serde-serialized onto the merge+/// transfer.+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct PersonDedup {+ pub applied_offsets: AppliedOffsets,+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub redirect_dedup: BTreeMap<Uuid, AppliedOffsets>,+}++/// The durable per-person value. See the module docs for the field roles.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct PersonRecord {+ /// Most recent event time (epoch ms) seen for this person — the ONLY field the TTL filter reads,+ /// at a fixed byte offset. Advanced on every non-replay event (fresh or stale).+ pub last_seen_ms: i64,+ /// The record-level argMax key: adopts a fresh event's `(ms, offset)`; unchanged by a stale one.+ pub stamp: Stamp,+ /// SHA-256 of the raw props behind the current matched set.+ pub props_fingerprint: PropsFingerprint,+ /// SHA-256 of the catalog the current matched set was evaluated against.+ pub catalog_fingerprint: CatalogFingerprint,+ /// Condition hashes currently TRUE (sorted, distinct).+ pub matched: MatchedSet,+ /// Per-source-partition replay-dedup high-water marks for direct events.+ pub applied_offsets: AppliedOffsets,+ /// Per-ancestor replay-dedup for post-merge straggler events, keyed by the ancestor person.+ pub redirect_dedup: BTreeMap<Uuid, AppliedOffsets>,+}++impl PersonRecord {+ /// The evaluation baseline for a person with no stored record (or a corrupt one): nothing+ /// matched, a stamp every real event beats, fingerprints that are never consulted (the decision+ /// table routes Absent/Corrupt straight to a full evaluation, which overwrites them), and no+ /// dedup history.+ pub fn absent() -> Self {+ Self {+ last_seen_ms: i64::MIN,+ stamp: Stamp::MIN,+ props_fingerprint: PropsFingerprint(0),+ catalog_fingerprint: CatalogFingerprint(0),+ matched: MatchedSet::empty(),+ applied_offsets: AppliedOffsets::default(),+ redirect_dedup: BTreeMap::new(),+ }+ }++ /// Origin-aware replay check, sharing the row-level implementation so the two cannot drift.+ pub fn is_replay_for(&self, origin: Option<&Uuid>, sp: i32, so: i64) -> bool {+ dedup_is_replay(&self.applied_offsets, &self.redirect_dedup, origin, sp, so)+ }++ /// Origin-aware offset advance, sharing the row-level implementation.+ pub fn record_for(&mut self, origin: Option<&Uuid>, sp: i32, so: i64) {+ dedup_record(+ &mut self.applied_offsets,+ &mut self.redirect_dedup,+ origin,+ sp,+ so,+ );+ }++ /// Extract this record's replay-dedup for a merge transfer. Carries only the offsets — never the+ /// matched set, fingerprints, or stamp — so P_new re-evaluates the person lazily on its next+ /// event.+ pub fn dedup_carrier(&self) -> PersonDedup {+ PersonDedup {+ applied_offsets: self.applied_offsets.clone(),+ redirect_dedup: self.redirect_dedup.clone(),+ }+ }++ /// Fold a merged-away ancestor's replay-dedup into this record: `old_person` becomes an ancestor+ /// under its own uuid (its direct offsets merged there), and each of its own ancestors carries+ /// forward under its original origin. Ancestors are keyed, never unioned into the main map, so a+ /// straggler routed by tombstone to a specific ancestor deduplicates against exactly that+ /// ancestor's high-water marks.+ pub fn absorb_ancestor(&mut self, old_person: Uuid, dedup: &PersonDedup) {+ self.redirect_dedup+ .entry(old_person)+ .or_default()+ .merge_max(&dedup.applied_offsets);+ for (ancestor, offsets) in &dedup.redirect_dedup {+ self.redirect_dedup+ .entry(*ancestor)+ .or_default()+ .merge_max(offsets);+ }+ }++ pub fn encode(&self) -> Vec<u8> {+ encode(self)+ }++ pub fn decode(bytes: &[u8]) -> Result<Self, PersonRecordCodecError> {+ decode(bytes)+ }+}++/// Whether a person's evaluated membership can have changed since the stored record: a total+/// function of the two fingerprint comparisons, with a stable metric label.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Freshness {+ /// Both fingerprints match: the stored matched set is still correct, no evaluation needed.+ Fresh,+ /// Only the props changed.+ StaleProps,+ /// Only the catalog changed.+ StaleCatalog,+ /// Both changed.+ StaleBoth,+}++impl Freshness {+ /// The total truth table over `(props_match, catalog_match)`.+ pub fn of(props_match: bool, catalog_match: bool) -> Self {+ match (props_match, catalog_match) {+ (true, true) => Self::Fresh,+ (false, true) => Self::StaleProps,+ (true, false) => Self::StaleCatalog,+ (false, false) => Self::StaleBoth,+ }+ }++ pub fn as_str(self) -> &'static str {+ match self {+ Self::Fresh => "fresh",+ Self::StaleProps => "stale_props",+ Self::StaleCatalog => "stale_catalog",+ Self::StaleBoth => "stale_both",+ }+ }+}++/// One stored `cf_person_records` slot as read by the event's single batched pre-event read.+/// `Corrupt` never panics; the decode metric is counted at the call site so this stays a pure+/// classifier.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum PriorRecord {+ /// No row: the person has no stored record.+ Absent,+ /// The decoded prior record.+ Present(PersonRecord),+ /// A row exists but does not decode; the caller re-evaluates from an absent-equivalent baseline+ /// rather than skipping (a skip on a corrupt row would silently freeze membership).+ Corrupt,+}++impl PriorRecord {+ pub fn decode(bytes: Option<&[u8]>) -> Self {+ match bytes {+ None => Self::Absent,+ Some(bytes) => match PersonRecord::decode(bytes) {+ Ok(record) => Self::Present(record),+ Err(_) => Self::Corrupt,+ },+ }+ }+}++/// The dedup routing coordinates for one event: the origin ancestor (from a tombstone redirect, else+/// `None`) plus the source partition/offset.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct DedupCoords {+ pub origin: Option<Uuid>,+ pub sp: i32,+ pub so: i64,+}++impl DedupCoords {+ pub fn new(origin: Option<Uuid>, sp: i32, so: i64) -> Self {+ Self { origin, sp, so }+ }+}++/// The classification of one active event against the prior record.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Decision {+ /// This `(origin, sp, so)` was already applied. Skip the person side entirely — no write.+ Replay,+ /// argMax-stale (`event <= stamp`). Advance dedup + `last_seen`, keep the matched set, stamp,+ /// and fingerprints. One write, no transitions, no evaluation.+ Stale,+ /// Fresh and both fingerprints match. Adopt the event stamp, advance dedup + `last_seen`. One+ /// write, no transitions, no evaluation.+ SkipEval,+ /// Fresh with a fingerprint mismatch (or an absent/corrupt prior). Needs a props parse and a+ /// HogVM evaluation of every person condition; the caller then calls [`apply_eval`].+ Eval { freshness: Freshness },+}++/// Classify one active event against the prior record. Pure: no store, HogVM, or clock — dedup+/// advance is applied by the `apply_*` constructors, not here.+///+/// Check order, top to bottom:+/// 1. `Replay` — an already-applied offset skips everything (no write).+/// 2. `Stale` — an equal-or-older stamp.+/// 3. fingerprints — matching ⇒ `SkipEval`, mismatched ⇒ `Eval`.+///+/// A corrupt or absent prior classifies as `Eval` against an absent-equivalent baseline+/// (`matched = ∅`, `stamp = MIN`), never a skip: freezing membership on a corrupt row would be a+/// silent correctness hole.+pub fn decide(+ prior: &PriorRecord,+ event: Stamp,+ dedup: DedupCoords,+ props_fp: PropsFingerprint,+ catalog_fp: CatalogFingerprint,+) -> Decision {+ match prior {+ PriorRecord::Present(record) => {+ if record.is_replay_for(dedup.origin.as_ref(), dedup.sp, dedup.so) {+ return Decision::Replay;+ }+ if event <= record.stamp {+ return Decision::Stale;+ }+ let props_match = props_fp == record.props_fingerprint;+ let catalog_match = catalog_fp == record.catalog_fingerprint;+ if props_match && catalog_match {+ Decision::SkipEval+ } else {+ Decision::Eval {+ freshness: Freshness::of(props_match, catalog_match),+ }+ }+ }+ // Absent or corrupt: full re-eval from the baseline. `StaleBoth` labels a from-nothing+ // evaluation, keeping the metric honest about the work done.+ PriorRecord::Absent | PriorRecord::Corrupt => Decision::Eval {+ freshness: Freshness::StaleBoth,+ },+ }+}++/// The next record for an argMax-stale event. Keeps the matched set, stamp, and both fingerprints;+/// advances the dedup offset and `last_seen_ms`. Always a write — the `last_seen` advance is+/// load-bearing for TTL, and recording the offset closes the replay window even though the event+/// lost argMax.+pub fn apply_stale(prior: &PersonRecord, event: Stamp, dedup: DedupCoords) -> PersonRecord {+ let mut next = prior.clone();+ next.record_for(dedup.origin.as_ref(), dedup.sp, dedup.so);+ next.last_seen_ms = next.last_seen_ms.max(event.ms);+ next+}++/// The next record when both fingerprints match. Adopts the event stamp (so a later out-of-order+/// event between the old and new stamps cannot wrongly win argMax), advances the dedup offset and+/// `last_seen_ms`, and keeps the matched set and fingerprints. No transitions.+pub fn apply_skip_eval(prior: &PersonRecord, event: Stamp, dedup: DedupCoords) -> PersonRecord {+ let mut next = prior.clone();+ next.stamp = event;+ next.record_for(dedup.origin.as_ref(), dedup.sp, dedup.so);+ next.last_seen_ms = next.last_seen_ms.max(event.ms);+ next+}++/// The next record and the person transitions after a HogVM evaluation produced `true_set` (`T`)+/// against `catalog` (`person_conditions_ordered`, sorted).+///+/// The prior matched set `S` is read from `prior` (`prior.matched`) so the transition source and the+/// stored record cannot drift. The stored matched set becomes `T ∪ (S \ catalog)`: the freshly-TRUE+/// hashes plus the retained orphans (hashes that were TRUE but whose condition is no longer in the+/// catalog). Keeping the orphans in the stored set is what makes a catalog re-add not re-`Enter` —+/// the hash never left `S`.+///+/// Transitions come ONLY from [`MatchedSet::diff`] between `S` and `T`. The record adopts the event+/// stamp, both fingerprints, and the advanced dedup + `last_seen`.+pub fn apply_eval(+ true_set: MatchedSet,+ catalog: &[[u8; 16]],+ prior: &PersonRecord,+ event: Stamp,+ dedup: DedupCoords,+ props_fp: PropsFingerprint,+ catalog_fp: CatalogFingerprint,+) -> (PersonRecord, Vec<([u8; 16], TransitionKind)>) {+ debug_assert_sorted(catalog);+ let transitions: Vec<_> = prior.matched.diff(&true_set, catalog).collect();++ // The stored set keeps orphans (in S but not in the catalog) so a later catalog re-add does not+ // re-Enter. `T` already holds the currently-TRUE hashes; add the orphans and re-canonicalize.+ let orphans = prior+ .matched+ .iter()+ .copied()+ .filter(|hash| catalog.binary_search(hash).is_err());+ let stored: MatchedSet = true_set.iter().copied().chain(orphans).collect();++ let mut next = prior.clone();+ next.stamp = event;+ next.props_fingerprint = props_fp;+ next.catalog_fingerprint = catalog_fp;+ next.matched = stored;+ next.record_for(dedup.origin.as_ref(), dedup.sp, dedup.so);+ next.last_seen_ms = next.last_seen_ms.max(event.ms);+ (next, transitions)+}++// --- Binary codec v1 ---++/// The on-disk format version. A decode of any other value is a typed error, so an incompatible+/// value layout can never be misread as this one. Visible to the TTL compaction filter+/// ([`crate::store::ttl_filter`]) so its version guard shares this codec's constant.+pub(crate) const FORMAT_VERSION: u8 = 1;++/// Reserved flag byte; nonzero is a typed error so a future flag can be added without silently+/// misinterpreting an old reader.+const FLAGS: u8 = 0;++/// Byte offset of `last_seen_ms`. The TTL compaction filter ([`crate::store::ttl_filter`]) reads only+/// this field, at this fixed offset, without a full decode, so it must never move. Visible to that+/// filter so the offset has a single source of truth.+pub(crate) const LAST_SEEN_MS_OFFSET: usize = 2;++/// A failure decoding a [`PersonRecord`]. Total: every malformed input maps to one of these, never a+/// panic.+#[derive(Debug, thiserror::Error, PartialEq, Eq)]+pub enum PersonRecordCodecError {+ #[error("person record buffer too short: needed {needed} more bytes at {section}")]+ ShortBuffer {+ section: &'static str,+ needed: usize,+ },+ #[error("person record format version {found} is not {expected}")]+ BadVersion { found: u8, expected: u8 },+ #[error("person record flags {found:#04x} are not zero (reserved)")]+ NonZeroFlags { found: u8 },+ #[error("person record {section} is not sorted-distinct")]+ NotSorted { section: &'static str },+ #[error("person record has {trailing} trailing bytes")]+ TrailingBytes { trailing: usize },+}++/// Serialize a record into the canonical v1 layout. Infallible: `BTreeMap` iteration is sorted and+/// [`MatchedSet`] is sorted by construction, so equal logical records encode byte-identically.+///+/// Layout (all integers big-endian, all length-prefixed sections `u32` count then fixed entries):+/// ```text+/// off 0 u8 format_version = 1+/// 1 u8 flags = 0+/// 2 i64 last_seen_ms+/// 10 i64 stamp.ms+/// 18 i64 stamp.offset+/// 26 16B props_fingerprint (raw digest-prefix bytes)+/// 42 16B catalog_fingerprint+/// 58 u32 N, N × 16B matched (sorted, distinct)+/// .. u32 M, M × (i32 partition, i64 offset) applied_offsets (sorted by partition)+/// .. u32 K, K × (uuid 16B, u32 C, C × (i32, i64)) redirect_dedup (sorted by uuid)+/// ```+fn encode(record: &PersonRecord) -> Vec<u8> {+ let mut out = Vec::with_capacity(58 + 4 + record.matched.len() * 16);+ out.push(FORMAT_VERSION);+ out.push(FLAGS);+ // `last_seen_ms` must land at the fixed offset the TTL filter reads without a full decode.+ debug_assert_eq!(out.len(), LAST_SEEN_MS_OFFSET);+ out.extend_from_slice(&record.last_seen_ms.to_be_bytes());+ out.extend_from_slice(&record.stamp.ms.to_be_bytes());+ out.extend_from_slice(&record.stamp.offset.to_be_bytes());+ out.extend_from_slice(&record.props_fingerprint.to_bytes());+ out.extend_from_slice(&record.catalog_fingerprint.to_bytes());++ write_u32(&mut out, record.matched.len());+ for hash in record.matched.iter() {+ out.extend_from_slice(hash);+ }++ encode_applied_offsets(&mut out, &record.applied_offsets);++ write_u32(&mut out, record.redirect_dedup.len());+ for (ancestor, offsets) in &record.redirect_dedup {+ out.extend_from_slice(ancestor.as_bytes());+ encode_applied_offsets(&mut out, offsets);+ }++ out+}++/// Deserialize a record. Total: any short buffer at any boundary, a bad version, nonzero flags, an+/// unsorted/duplicate section, or trailing bytes yields a typed error. Never panics.+fn decode(bytes: &[u8]) -> Result<PersonRecord, PersonRecordCodecError> {+ let mut cur = Cursor::new(bytes);++ let version = cur.take_u8("version")?;+ if version != FORMAT_VERSION {+ return Err(PersonRecordCodecError::BadVersion {+ found: version,+ expected: FORMAT_VERSION,+ });+ }+ let flags = cur.take_u8("flags")?;+ if flags != FLAGS {+ return Err(PersonRecordCodecError::NonZeroFlags { found: flags });+ }++ let last_seen_ms = cur.take_i64("last_seen_ms")?;+ let stamp = Stamp {+ ms: cur.take_i64("stamp.ms")?,+ offset: cur.take_i64("stamp.offset")?,+ };+ let props_fingerprint = PropsFingerprint::from_bytes(cur.take_16("props_fingerprint")?);+ let catalog_fingerprint = CatalogFingerprint::from_bytes(cur.take_16("catalog_fingerprint")?);++ let matched_count = cur.take_u32("matched.count")? as usize;+ let mut matched = Vec::with_capacity(matched_count.min(1024));+ for _ in 0..matched_count {+ matched.push(cur.take_16("matched.entry")?);+ }+ if !is_strictly_sorted(&matched) {+ return Err(PersonRecordCodecError::NotSorted { section: "matched" });+ }++ let applied_offsets = decode_applied_offsets(&mut cur, "applied_offsets")?;++ let redirect_count = cur.take_u32("redirect_dedup.count")? as usize;+ let mut redirect_dedup: BTreeMap<Uuid, AppliedOffsets> = BTreeMap::new();+ let mut prev_ancestor: Option<Uuid> = None;+ for _ in 0..redirect_count {+ let ancestor = Uuid::from_bytes(cur.take_16("redirect_dedup.uuid")?);+ // Strictly ascending by uuid ⇒ canonical, and distinct keys (a `BTreeMap` would otherwise+ // silently collapse a duplicate, hiding a corrupt buffer).+ if prev_ancestor.is_some_and(|prev| ancestor <= prev) {+ return Err(PersonRecordCodecError::NotSorted {+ section: "redirect_dedup",+ });+ }+ prev_ancestor = Some(ancestor);+ let offsets = decode_applied_offsets(&mut cur, "redirect_dedup.offsets")?;+ redirect_dedup.insert(ancestor, offsets);+ }++ if !cur.is_exhausted() {+ return Err(PersonRecordCodecError::TrailingBytes {+ trailing: cur.remaining(),+ });+ }++ Ok(PersonRecord {+ last_seen_ms,+ stamp,+ props_fingerprint,+ catalog_fingerprint,+ matched: MatchedSet::from_sorted_distinct(matched),+ applied_offsets,+ redirect_dedup,+ })+}++/// Encode an [`AppliedOffsets`] as `u32` count then `(i32 partition, i64 offset)` entries, in the+/// map's already-sorted partition order.+fn encode_applied_offsets(out: &mut Vec<u8>, offsets: &AppliedOffsets) {+ let entries = offsets.entries();+ write_u32(out, entries.len());+ for (partition, offset) in entries {+ out.extend_from_slice(&partition.to_be_bytes());+ out.extend_from_slice(&offset.to_be_bytes());+ }+}++/// Decode an [`AppliedOffsets`], verifying the partitions are strictly ascending (canonical).+fn decode_applied_offsets(+ cur: &mut Cursor<'_>,+ section: &'static str,+) -> Result<AppliedOffsets, PersonRecordCodecError> {+ let count = cur.take_u32(section)? as usize;+ let mut entries: Vec<(i32, i64)> = Vec::with_capacity(count.min(1024));+ let mut prev: Option<i32> = None;+ for _ in 0..count {+ let partition = cur.take_i32(section)?;+ let offset = cur.take_i64(section)?;+ if prev.is_some_and(|p| partition <= p) {+ return Err(PersonRecordCodecError::NotSorted { section });+ }+ prev = Some(partition);+ entries.push((partition, offset));+ }+ Ok(AppliedOffsets::from_sorted_entries(entries))+}++fn write_u32(out: &mut Vec<u8>, value: usize) {+ // A person's matched-set / offset counts are far below u32::MAX; the cast is safe in practice+ // and any overflow would surface as a too-large count the decoder rejects on a short buffer.+ debug_assert!(value <= u32::MAX as usize, "section count exceeds u32");+ out.extend_from_slice(&(value as u32).to_be_bytes());+}++fn is_strictly_sorted(hashes: &[[u8; 16]]) -> bool {+ hashes.windows(2).all(|w| w[0] < w[1])+}++/// Debug-time guard for the `catalog` slices [`MatchedSet::diff`] and [`apply_eval`] binary-search+/// over: an unsorted catalog would silently suppress `Left` transitions.+fn debug_assert_sorted(catalog: &[[u8; 16]]) {+ debug_assert!(+ catalog.windows(2).all(|w| w[0] <= w[1]),+ "catalog slice must be sorted for binary search",+ );+}++/// A forward-only reader over the record buffer that turns every out-of-bounds read into a typed+/// [`PersonRecordCodecError::ShortBuffer`] rather than a panic.+struct Cursor<'a> {+ bytes: &'a [u8],+ pos: usize,+}++impl<'a> Cursor<'a> {+ fn new(bytes: &'a [u8]) -> Self {+ Self { bytes, pos: 0 }+ }++ fn take(+ &mut self,+ n: usize,+ section: &'static str,+ ) -> Result<&'a [u8], PersonRecordCodecError> {+ let end = self.pos.checked_add(n);+ match end {+ Some(end) if end <= self.bytes.len() => {+ let slice = &self.bytes[self.pos..end];+ self.pos = end;+ Ok(slice)+ }+ _ => Err(PersonRecordCodecError::ShortBuffer {+ section,+ needed: n.saturating_sub(self.bytes.len().saturating_sub(self.pos)),+ }),+ }+ }++ fn take_u8(&mut self, section: &'static str) -> Result<u8, PersonRecordCodecError> {+ Ok(self.take(1, section)?[0])+ }++ fn take_u32(&mut self, section: &'static str) -> Result<u32, PersonRecordCodecError> {+ Ok(u32::from_be_bytes(array(self.take(4, section)?)))+ }++ fn take_i32(&mut self, section: &'static str) -> Result<i32, PersonRecordCodecError> {+ Ok(i32::from_be_bytes(array(self.take(4, section)?)))+ }++ fn take_i64(&mut self, section: &'static str) -> Result<i64, PersonRecordCodecError> {+ Ok(i64::from_be_bytes(array(self.take(8, section)?)))+ }++ fn take_16(&mut self, section: &'static str) -> Result<[u8; 16], PersonRecordCodecError> {+ Ok(array(self.take(16, section)?))+ }++ fn remaining(&self) -> usize {+ self.bytes.len() - self.pos+ }++ fn is_exhausted(&self) -> bool {+ self.pos == self.bytes.len()+ }+}++/// Copy a slice of the exact length into a fixed array. The caller only passes slices produced by+/// [`Cursor::take`], which already guarantees the length, so the `try_into` cannot fail.+fn array<const N: usize>(slice: &[u8]) -> [u8; N] {+ slice.try_into().expect("cursor slice is exactly N bytes")+}++#[cfg(test)]+mod tests {+ use super::*;++ fn hash(byte: u8) -> [u8; 16] {+ [byte; 16]+ }++ fn uuid(n: u128) -> Uuid {+ Uuid::from_u128(n)+ }++ fn applied(entries: &[(i32, i64)]) -> AppliedOffsets {+ let mut applied = AppliedOffsets::default();+ for &(partition, offset) in entries {+ applied.record(partition, offset);+ }+ applied+ }++ fn sample_record() -> PersonRecord {+ let mut redirect = BTreeMap::new();+ redirect.insert(uuid(0xA11CE), applied(&[(9, 42)]));+ PersonRecord {+ last_seen_ms: 1_700_000_000_000,+ stamp: Stamp::new(1_700_000_000_123, 99),+ props_fingerprint: PropsFingerprint(0x1122_3344_5566_7788_99AA_BBCC_DDEE_FF00),+ catalog_fingerprint: CatalogFingerprint(0x0FED_CBA9_8765_4321_1234_5678_9ABC_DEF0),+ matched: MatchedSet::from_iter([hash(0x11), hash(0x22)]),+ applied_offsets: applied(&[(3, 100), (7, 5)]),+ redirect_dedup: redirect,+ }+ }++ #[test]+ fn stamp_orders_by_ms_then_offset_and_min_is_the_floor() {+ assert!(Stamp::new(1, 0) < Stamp::new(1, 1));+ assert!(Stamp::new(1, 999) < Stamp::new(2, 0));+ assert!(Stamp::MIN < Stamp::new(i64::MIN + 1, i64::MIN));+ assert!(Stamp::MIN < Stamp::new(i64::MIN, i64::MIN + 1));+ // Equality is not "fresh": an equal stamp is stale under the `<=` rule decide() applies.+ assert_eq!(Stamp::new(5, 5), Stamp::new(5, 5));+ }++ #[test]+ fn props_fingerprint_matches_the_person_memo_derivation_and_round_trips() {+ // The digest-prefix bytes are the little-endian of the u128, so encode is exactly those bytes.+ let fp = PropsFingerprint::of(r#"{"plan":"pro"}"#);+ assert_eq!(PropsFingerprint::from_bytes(fp.to_bytes()), fp);+ assert_eq!(PropsFingerprint::of("x"), PropsFingerprint::of("x"));+ assert_ne!(PropsFingerprint::of("x"), PropsFingerprint::of("y"));++ let expected = {+ let digest = Sha256::digest(b"x");+ u128::from_le_bytes(digest[..16].try_into().unwrap())+ };+ assert_eq!(PropsFingerprint::of("x").0, expected);+ }++ #[test]+ fn catalog_fingerprint_is_order_stable_and_sensitive() {+ let a = CatalogFingerprint::of_sorted(&[hash(1), hash(2), hash(3)]);+ let b = CatalogFingerprint::of_sorted(&[hash(1), hash(2), hash(3)]);+ assert_eq!(a, b, "same sorted conditions ⇒ same fingerprint");++ let removed = CatalogFingerprint::of_sorted(&[hash(1), hash(2)]);+ assert_ne!(a, removed, "removing a condition changes the fingerprint");++ let added = CatalogFingerprint::of_sorted(&[hash(1), hash(2), hash(3), hash(4)]);+ assert_ne!(a, added, "adding a condition changes the fingerprint");++ // Empty input is a stable constant (the SHA-256 of nothing), distinct from any non-empty set.+ let empty_a = CatalogFingerprint::of_sorted(&[]);+ let empty_b = CatalogFingerprint::of_sorted(&[]);+ assert_eq!(empty_a, empty_b);+ assert_ne!(empty_a, a);+ }++ #[test]+ fn matched_set_sorts_dedups_and_binary_searches() {+ let set = MatchedSet::from_iter([hash(3), hash(1), hash(3), hash(2), hash(1)]);+ assert_eq!(set.len(), 3, "duplicates collapse");+ assert!(set.contains(&hash(1)) && set.contains(&hash(2)) && set.contains(&hash(3)));+ assert!(!set.contains(&hash(4)));+ // Sorted ascending.+ let collected: Vec<_> = set.iter().copied().collect();+ assert_eq!(collected, vec![hash(1), hash(2), hash(3)]);+ }++ #[test]+ fn matched_set_diff_enters_leaves_and_reports_both() {+ let catalog = [hash(1), hash(2), hash(3)];+ let s = MatchedSet::from_iter([hash(1), hash(2)]);+ let t = MatchedSet::from_iter([hash(2), hash(3)]);+ let mut transitions: Vec<_> = s.diff(&t, &catalog).collect();+ transitions.sort_by_key(|(h, _)| *h);+ assert_eq!(+ transitions,+ vec![+ (hash(1), TransitionKind::Left),+ (hash(3), TransitionKind::Entered),+ ],+ );+ }++ #[test]+ fn matched_set_diff_none_when_unchanged() {+ let catalog = [hash(1), hash(2)];+ let s = MatchedSet::from_iter([hash(1), hash(2)]);+ let t = MatchedSet::from_iter([hash(1), hash(2)]);+ assert_eq!(s.diff(&t, &catalog).count(), 0);+ }++ #[test]+ fn matched_set_diff_retains_orphans_across_catalog_remove_readd_and_genuine_leave() {+ // S has a hash whose condition was removed from the catalog.+ let s = MatchedSet::from_iter([hash(0xAA)]);++ // Catalog lacks 0xAA and T lacks it ⇒ NO Left (retained orphan, not a departure).+ let catalog_removed: [[u8; 16]; 0] = [];+ let t_absent = MatchedSet::empty();+ assert_eq!(+ s.diff(&t_absent, &catalog_removed).count(),+ 0,+ "an orphaned hash (condition removed) must not emit Left",+ );++ // Catalog regains 0xAA and T regains it ⇒ no duplicate Entered, because the stored set kept+ // the hash the whole time (this is the S-side view: 0xAA is still in S).+ let catalog_readded = [hash(0xAA)];+ let t_present = MatchedSet::from_iter([hash(0xAA)]);+ assert_eq!(+ s.diff(&t_present, &catalog_readded).count(),+ 0,+ "re-adding a retained hash must not re-Enter",+ );++ // Catalog regains 0xAA but T does NOT ⇒ Left fires now (the hash genuinely departed).+ let left: Vec<_> = s.diff(&t_absent, &catalog_readded).collect();+ assert_eq!(left, vec![(hash(0xAA), TransitionKind::Left)]);+ }++ // --- decision core ---++ fn present(record: PersonRecord) -> PriorRecord {+ PriorRecord::Present(record)+ }++ fn coords() -> DedupCoords {+ DedupCoords::new(None, 5, 100)+ }++ #[test]+ fn decide_replay_skips_everything() {+ let mut record = sample_record();+ record.applied_offsets = applied(&[(5, 100)]);+ let decision = decide(+ &present(record.clone()),+ Stamp::new(record.stamp.ms + 1_000, 0),+ DedupCoords::new(None, 5, 100),+ record.props_fingerprint,+ record.catalog_fingerprint,+ );+ assert_eq!(decision, Decision::Replay, "offset 100 <= applied 100");+ }++ #[test]+ fn decide_stale_on_equal_or_older_stamp() {+ let record = sample_record();+ // Equal stamp: stale (the `<=` rule).+ assert_eq!(+ decide(+ &present(record.clone()),+ record.stamp,+ DedupCoords::new(None, 5, 1_000),+ record.props_fingerprint,+ record.catalog_fingerprint,+ ),+ Decision::Stale,+ );+ // Strictly older ms: stale.+ assert_eq!(+ decide(+ &present(record.clone()),+ Stamp::new(record.stamp.ms - 1, i64::MAX),+ DedupCoords::new(None, 5, 1_000),+ record.props_fingerprint,+ record.catalog_fingerprint,+ ),+ Decision::Stale,+ );+ }++ #[test]+ fn decide_skip_eval_when_fresh_and_both_fingerprints_match() {+ let record = sample_record();+ let decision = decide(+ &present(record.clone()),+ Stamp::new(record.stamp.ms + 1, 0),+ DedupCoords::new(None, 5, 1_000),+ record.props_fingerprint,+ record.catalog_fingerprint,+ );+ assert_eq!(decision, Decision::SkipEval);+ }++ #[test]+ fn decide_eval_labels_the_mismatch_axis() {+ let record = sample_record();+ let fresh = Stamp::new(record.stamp.ms + 1, 0);+ let other_props = PropsFingerprint(record.props_fingerprint.0 ^ 1);+ let other_catalog = CatalogFingerprint(record.catalog_fingerprint.0 ^ 1);++ assert_eq!(+ decide(+ &present(record.clone()),+ fresh,+ DedupCoords::new(None, 5, 1_000),+ other_props,+ record.catalog_fingerprint,+ ),+ Decision::Eval {+ freshness: Freshness::StaleProps+ },+ );+ assert_eq!(+ decide(+ &present(record.clone()),+ fresh,+ DedupCoords::new(None, 5, 1_000),+ record.props_fingerprint,+ other_catalog,+ ),+ Decision::Eval {+ freshness: Freshness::StaleCatalog+ },+ );+ assert_eq!(+ decide(+ &present(record.clone()),+ fresh,+ DedupCoords::new(None, 5, 1_000),+ other_props,+ other_catalog,+ ),+ Decision::Eval {+ freshness: Freshness::StaleBoth+ },+ );+ }++ #[test]+ fn decide_absent_and_corrupt_always_evaluate_never_skip() {+ let props = PropsFingerprint::of("p");+ let catalog = CatalogFingerprint::of_sorted(&[hash(1)]);+ for prior in [PriorRecord::Absent, PriorRecord::Corrupt] {+ assert_eq!(+ decide(&prior, Stamp::new(10, 0), coords(), props, catalog),+ Decision::Eval {+ freshness: Freshness::StaleBoth+ },+ "an absent/corrupt prior must evaluate, never skip",+ );+ }+ }++ #[test]+ fn decide_check_order_replay_precedes_staleness() {+ // A replay of an old offset that is ALSO argMax-stale must classify Replay, not Stale — the+ // replay check is first, so a duplicate delivery writes nothing at all.+ let mut record = sample_record();+ record.applied_offsets = applied(&[(5, 100)]);+ let decision = decide(+ &present(record.clone()),+ Stamp::new(record.stamp.ms - 5, 0), // also stale+ DedupCoords::new(None, 5, 100), // and a replay+ record.props_fingerprint,+ record.catalog_fingerprint,+ );+ assert_eq!(decision, Decision::Replay);+ }++ #[test]+ fn apply_stale_advances_dedup_and_last_seen_but_keeps_everything_else() {+ let mut prior = sample_record();+ prior.last_seen_ms = 1_000;+ prior.applied_offsets = applied(&[(5, 10)]);+ let event = Stamp::new(500, 7); // older than the stamp, newer last_seen+ let next = apply_stale(&prior, Stamp::new(2_000, 7), DedupCoords::new(None, 5, 20));+ let _ = event;+ assert_eq!(next.stamp, prior.stamp, "stamp unchanged by a stale event");+ assert_eq!(next.matched, prior.matched, "matched set unchanged");+ assert_eq!(+ next.props_fingerprint, prior.props_fingerprint,+ "fingerprints unchanged",+ );+ assert_eq!(+ next.last_seen_ms, 2_000,+ "last_seen advances to the event ms"+ );+ assert!(+ next.applied_offsets.is_replay(5, 20),+ "the stale event still records its offset",+ );+ }++ #[test]+ fn apply_stale_never_regresses_last_seen() {+ let mut prior = sample_record();+ prior.last_seen_ms = 5_000;+ let next = apply_stale(&prior, Stamp::new(1_000, 0), coords());+ assert_eq!(+ next.last_seen_ms, 5_000,+ "an older event never lowers last_seen"+ );+ }++ #[test]+ fn apply_skip_eval_adopts_the_stamp_and_advances_dedup_and_last_seen() {+ let mut prior = sample_record();+ prior.last_seen_ms = 1_000;+ let event = Stamp::new(9_000, 3);+ let next = apply_skip_eval(&prior, event, DedupCoords::new(None, 5, 20));+ assert_eq!(+ next.stamp, event,+ "the fresh stamp is adopted (load-bearing for argMax)"+ );+ assert_eq!(+ next.matched, prior.matched,+ "no eval ⇒ matched set unchanged"+ );+ assert_eq!(next.last_seen_ms, 9_000);+ assert!(next.applied_offsets.is_replay(5, 20));+ }++ #[test]+ fn apply_eval_diffs_transitions_retains_orphans_and_adopts_stamp_and_fps() {+ let catalog = [hash(1), hash(2)]; // hash(0xAA) is an orphan (in prior, not in catalog)+ let mut prior = sample_record();+ prior.matched = MatchedSet::from_iter([hash(1), hash(0xAA)]);+ prior.last_seen_ms = 1_000;+ let event = Stamp::new(9_000, 3);+ let new_props = PropsFingerprint(0xDEAD);+ let new_catalog = CatalogFingerprint(0xBEEF);++ let true_set = MatchedSet::from_iter([hash(2)]); // 1 leaves, 2 enters+ let (next, transitions) = apply_eval(+ true_set,+ &catalog,+ &prior,+ event,+ DedupCoords::new(None, 5, 20),+ new_props,+ new_catalog,+ );++ let mut sorted = transitions.clone();+ sorted.sort_by_key(|(h, _)| *h);+ assert_eq!(+ sorted,+ vec![+ (hash(1), TransitionKind::Left),+ (hash(2), TransitionKind::Entered),+ ],+ "0xAA is an orphan: no Left for it",+ );+ // Stored set is T ∪ (S \ catalog) = {2} ∪ {0xAA}.+ assert!(next.matched.contains(&hash(2)));+ assert!(+ next.matched.contains(&hash(0xAA)),+ "the orphan is retained in the stored set so a catalog re-add does not re-Enter",+ );+ assert!(!next.matched.contains(&hash(1)), "the left hash is dropped");+ assert_eq!(next.stamp, event);+ assert_eq!(next.props_fingerprint, new_props);+ assert_eq!(next.catalog_fingerprint, new_catalog);+ assert_eq!(next.last_seen_ms, 9_000);+ assert!(next.applied_offsets.is_replay(5, 20));+ }++ #[test]+ fn apply_eval_identical_true_set_yields_no_transitions_but_still_adopts_stamp_and_fps() {+ let catalog = [hash(1), hash(2)];+ let mut prior = sample_record();+ prior.matched = MatchedSet::from_iter([hash(1), hash(2)]);+ let event = Stamp::new(9_000, 3);+ let new_props = PropsFingerprint(0xF00D);+ let new_catalog = CatalogFingerprint(0xC0DE);+ let (next, transitions) = apply_eval(+ MatchedSet::from_iter([hash(1), hash(2)]),+ &catalog,+ &prior,+ event,+ coords(),+ new_props,+ new_catalog,+ );+ assert!(transitions.is_empty(), "T == S ⇒ zero transitions");+ assert_eq!(next.stamp, event, "but the stamp is still adopted");+ assert_eq!(next.props_fingerprint, new_props);+ assert_eq!(next.catalog_fingerprint, new_catalog);+ }++ // --- dedup carrier / absorb ---++ #[test]+ fn dedup_carrier_extracts_only_offsets() {+ let record = sample_record();+ let carrier = record.dedup_carrier();+ assert_eq!(carrier.applied_offsets, record.applied_offsets);+ assert_eq!(carrier.redirect_dedup, record.redirect_dedup);+ }++ #[test]+ fn absorb_ancestor_keys_old_person_and_carries_grandparents() {+ let grandparent = uuid(0x6172);+ let p_old = uuid(0xA11CE);+ let mut carrier = PersonDedup {+ applied_offsets: applied(&[(5, 100)]),+ redirect_dedup: BTreeMap::from([(grandparent, applied(&[(9, 42)]))]),+ };+ // A pre-existing ancestor on P_new's side must survive.+ carrier.redirect_dedup.entry(grandparent).or_default();++ let mut record = sample_record();+ record.redirect_dedup.clear();+ record.absorb_ancestor(p_old, &carrier);++ assert!(+ record.redirect_dedup[&p_old].is_replay(5, 100),+ "P_old becomes an ancestor under its own uuid",+ );+ assert!(+ record.redirect_dedup[&grandparent].is_replay(9, 42),+ "the grandparent carries forward under its own origin, keyed not unioned",+ );+ assert!(+ !record.applied_offsets.is_replay(5, 100),+ "the ancestor's offsets never fold into the main map",+ );+ }++ #[test]+ fn is_replay_and_record_for_share_the_row_level_routing() {+ let mut record = sample_record();+ record.applied_offsets = AppliedOffsets::default();+ record.redirect_dedup.clear();+ let ancestor = uuid(0xA11CE);++ record.record_for(None, 5, 100);+ assert!(record.is_replay_for(None, 5, 100));+ assert!(+ record.redirect_dedup.is_empty(),+ "a direct event touches only the main map"+ );++ record.record_for(Some(&ancestor), 5, 200);+ assert!(record.is_replay_for(Some(&ancestor), 5, 200));+ assert!(+ !record.is_replay_for(None, 5, 150),+ "recording into the ancestor map must not advance the main map",+ );+ }++ // --- freshness labels ---++ #[test]+ fn freshness_truth_table_and_labels() {+ assert_eq!(Freshness::of(true, true), Freshness::Fresh);+ assert_eq!(Freshness::of(false, true), Freshness::StaleProps);+ assert_eq!(Freshness::of(true, false), Freshness::StaleCatalog);+ assert_eq!(Freshness::of(false, false), Freshness::StaleBoth);+ assert_eq!(Freshness::Fresh.as_str(), "fresh");+ assert_eq!(Freshness::StaleProps.as_str(), "stale_props");+ assert_eq!(Freshness::StaleCatalog.as_str(), "stale_catalog");+ assert_eq!(Freshness::StaleBoth.as_str(), "stale_both");+ }++ // --- codec ---++ #[test]+ fn record_round_trips_through_the_codec() {+ let record = sample_record();+ assert_eq!(PersonRecord::decode(&record.encode()).unwrap(), record);+ }++ #[test]+ fn empty_record_round_trips() {+ let record = PersonRecord {+ last_seen_ms: 0,+ stamp: Stamp::MIN,+ props_fingerprint: PropsFingerprint(0),+ catalog_fingerprint: CatalogFingerprint(0),+ matched: MatchedSet::empty(),+ applied_offsets: AppliedOffsets::default(),+ redirect_dedup: BTreeMap::new(),+ };+ assert_eq!(PersonRecord::decode(&record.encode()).unwrap(), record);+ }++ #[test]+ fn encoding_is_canonical_across_insertion_orders() {+ // Build the "same" record two ways: different matched-hash insertion order, different+ // ancestor insertion order. The canonical codec must produce identical bytes.+ let build = |matched_order: [u8; 3], ancestors: &[(u128, i32, i64)]| {+ let mut redirect = BTreeMap::new();+ for &(u, p, o) in ancestors {+ redirect.insert(uuid(u), applied(&[(p, o)]));+ }+ PersonRecord {+ last_seen_ms: 42,+ stamp: Stamp::new(7, 3),+ props_fingerprint: PropsFingerprint(1),+ catalog_fingerprint: CatalogFingerprint(2),+ matched: MatchedSet::from_iter(matched_order.map(hash)),+ applied_offsets: applied(&[(2, 9), (0, 1)]),+ redirect_dedup: redirect,+ }+ };+ let a = build([3, 1, 2], &[(20, 1, 1), (10, 2, 2)]);+ let b = build([2, 3, 1], &[(10, 2, 2), (20, 1, 1)]);+ assert_eq!(a, b, "logically equal");+ assert_eq!(a.encode(), b.encode(), "and byte-identical");+ }++ #[test]+ fn last_seen_ms_lives_at_the_fixed_ttl_offset() {+ // The TTL compaction filter reads only `last_seen_ms`, at this fixed byte offset, without a+ // full decode. Pin it: byte 0 is the version, byte 1 the flags, then the i64 at 2.+ let mut record = sample_record();+ record.last_seen_ms = 0x0102_0304_0506_0708;+ let bytes = record.encode();+ assert_eq!(&bytes[0..2], &[FORMAT_VERSION, FLAGS]);+ assert_eq!(+ i64::from_be_bytes(+ bytes[LAST_SEEN_MS_OFFSET..LAST_SEEN_MS_OFFSET + 8]+ .try_into()+ .unwrap()+ ),+ 0x0102_0304_0506_0708,+ "the TTL filter's fixed offset must decode last_seen_ms",+ );+ }++ #[test]+ fn golden_bytes_pin_the_wire_format() {+ // A small record: last_seen=1, stamp=(2,3), props_fp=0x04 (LE u128 ⇒ byte 0 = 0x04),+ // catalog_fp=0x05, one matched hash (all 0xAA), two applied offsets, one ancestor with one+ // offset. Hand-written so any accidental reordering of the layout is caught.+ let mut redirect = BTreeMap::new();+ redirect.insert(uuid(0), applied(&[(0x0000_0007, 0x0000_0000_0000_0008)]));+ let record = PersonRecord {+ last_seen_ms: 1,+ stamp: Stamp::new(2, 3),+ props_fingerprint: PropsFingerprint(4),+ catalog_fingerprint: CatalogFingerprint(5),+ matched: MatchedSet::from_iter([[0xAA; 16]]),+ applied_offsets: applied(&[+ (0x0000_0001, 0x0000_0000_0000_0064),+ (0x0000_0002, 0x03E8),+ ]),+ redirect_dedup: redirect,+ };++ let mut expected = Vec::new();+ expected.push(1u8); // format_version+ expected.push(0u8); // flags+ expected.extend_from_slice(&1i64.to_be_bytes()); // last_seen_ms+ expected.extend_from_slice(&2i64.to_be_bytes()); // stamp.ms+ expected.extend_from_slice(&3i64.to_be_bytes()); // stamp.offset+ expected.extend_from_slice(&4u128.to_le_bytes()); // props_fingerprint (LE ⇒ digest bytes)+ expected.extend_from_slice(&5u128.to_le_bytes()); // catalog_fingerprint+ expected.extend_from_slice(&1u32.to_be_bytes()); // matched count+ expected.extend_from_slice(&[0xAA; 16]); // matched[0]+ expected.extend_from_slice(&2u32.to_be_bytes()); // applied count+ expected.extend_from_slice(&1i32.to_be_bytes()); // applied[0].partition+ expected.extend_from_slice(&100i64.to_be_bytes()); // applied[0].offset+ expected.extend_from_slice(&2i32.to_be_bytes()); // applied[1].partition+ expected.extend_from_slice(&1000i64.to_be_bytes()); // applied[1].offset+ expected.extend_from_slice(&1u32.to_be_bytes()); // redirect count+ expected.extend_from_slice(uuid(0).as_bytes()); // ancestor uuid+ expected.extend_from_slice(&1u32.to_be_bytes()); // ancestor offset count+ expected.extend_from_slice(&7i32.to_be_bytes()); // ancestor[0].partition+ expected.extend_from_slice(&8i64.to_be_bytes()); // ancestor[0].offset++ assert_eq!(record.encode(), expected);+ // And it survives a decode.+ assert_eq!(PersonRecord::decode(&expected).unwrap(), record);+ }++ #[test]+ fn decode_truncation_at_every_boundary_errs_never_panics() {+ let bytes = sample_record().encode();+ for k in 0..bytes.len() {+ let result = PersonRecord::decode(&bytes[..k]);+ assert!(+ result.is_err(),+ "a buffer truncated to {k} of {} bytes must fail to decode",+ bytes.len(),+ );+ }+ // The full buffer decodes.+ assert!(PersonRecord::decode(&bytes).is_ok());+ }++ #[test]+ fn decode_rejects_a_bad_version() {+ let mut bytes = sample_record().encode();+ bytes[0] = 2;+ assert_eq!(+ PersonRecord::decode(&bytes),+ Err(PersonRecordCodecError::BadVersion {+ found: 2,+ expected: 1,+ }),+ );+ }++ #[test]+ fn decode_rejects_nonzero_flags() {+ let mut bytes = sample_record().encode();+ bytes[1] = 0x80;+ assert_eq!(+ PersonRecord::decode(&bytes),+ Err(PersonRecordCodecError::NonZeroFlags { found: 0x80 }),+ );+ }++ #[test]+ fn decode_rejects_trailing_bytes() {+ let mut bytes = sample_record().encode();+ bytes.push(0);+ assert_eq!(+ PersonRecord::decode(&bytes),+ Err(PersonRecordCodecError::TrailingBytes { trailing: 1 }),+ );+ }++ #[test]+ fn decode_rejects_an_unsorted_matched_section() {+ // Hand-build a record with two matched hashes in descending order.+ let mut bytes = Vec::new();+ bytes.push(1u8);+ bytes.push(0u8);+ bytes.extend_from_slice(&0i64.to_be_bytes()); // last_seen+ bytes.extend_from_slice(&0i64.to_be_bytes()); // stamp.ms+ bytes.extend_from_slice(&0i64.to_be_bytes()); // stamp.offset+ bytes.extend_from_slice(&[0u8; 16]); // props_fp+ bytes.extend_from_slice(&[0u8; 16]); // catalog_fp+ bytes.extend_from_slice(&2u32.to_be_bytes()); // matched count = 2+ bytes.extend_from_slice(&[0xBB; 16]); // matched[0] (larger)+ bytes.extend_from_slice(&[0xAA; 16]); // matched[1] (smaller ⇒ unsorted)+ bytes.extend_from_slice(&0u32.to_be_bytes()); // applied count+ bytes.extend_from_slice(&0u32.to_be_bytes()); // redirect count+ assert_eq!(+ PersonRecord::decode(&bytes),+ Err(PersonRecordCodecError::NotSorted { section: "matched" }),+ );+ }++ #[test]+ fn decode_rejects_unsorted_applied_offsets() {+ let mut bytes = Vec::new();+ bytes.push(1u8);+ bytes.push(0u8);+ bytes.extend_from_slice(&0i64.to_be_bytes());+ bytes.extend_from_slice(&0i64.to_be_bytes());+ bytes.extend_from_slice(&0i64.to_be_bytes());+ bytes.extend_from_slice(&[0u8; 16]);+ bytes.extend_from_slice(&[0u8; 16]);+ bytes.extend_from_slice(&0u32.to_be_bytes()); // matched count = 0+ bytes.extend_from_slice(&2u32.to_be_bytes()); // applied count = 2+ bytes.extend_from_slice(&5i32.to_be_bytes()); // partition 5+ bytes.extend_from_slice(&0i64.to_be_bytes());+ bytes.extend_from_slice(&3i32.to_be_bytes()); // partition 3 (< 5 ⇒ unsorted)+ bytes.extend_from_slice(&0i64.to_be_bytes());+ bytes.extend_from_slice(&0u32.to_be_bytes()); // redirect count+ assert_eq!(+ PersonRecord::decode(&bytes),+ Err(PersonRecordCodecError::NotSorted {+ section: "applied_offsets"+ }),+ );+ }++ #[test]+ fn decode_rejects_unsorted_redirect_ancestors() {+ let build_offsets = |out: &mut Vec<u8>| {+ out.extend_from_slice(&1u32.to_be_bytes());+ out.extend_from_slice(&0i32.to_be_bytes());+ out.extend_from_slice(&0i64.to_be_bytes());+ };+ let mut bytes = Vec::new();+ bytes.push(1u8);+ bytes.push(0u8);+ bytes.extend_from_slice(&0i64.to_be_bytes());+ bytes.extend_from_slice(&0i64.to_be_bytes());+ bytes.extend_from_slice(&0i64.to_be_bytes());+ bytes.extend_from_slice(&[0u8; 16]);+ bytes.extend_from_slice(&[0u8; 16]);+ bytes.extend_from_slice(&0u32.to_be_bytes()); // matched+ bytes.extend_from_slice(&0u32.to_be_bytes()); // applied+ bytes.extend_from_slice(&2u32.to_be_bytes()); // redirect count = 2+ bytes.extend_from_slice(uuid(5).as_bytes()); // ancestor 5+ build_offsets(&mut bytes);+ bytes.extend_from_slice(uuid(3).as_bytes()); // ancestor 3 (< 5 ⇒ unsorted)+ build_offsets(&mut bytes);+ assert_eq!(+ PersonRecord::decode(&bytes),+ Err(PersonRecordCodecError::NotSorted {+ section: "redirect_dedup"+ }),+ );+ }+}diff --git a/rust/cohort-stream-processor/src/stage1/predicate.rs b/rust/cohort-stream-processor/src/stage1/predicate.rsindex 57ad82710d57..4cebebc35474 100644--- a/rust/cohort-stream-processor/src/stage1/predicate.rs+++ b/rust/cohort-stream-processor/src/stage1/predicate.rs@@ -8,17 +8,16 @@ use crate::stage1::compressed_history::compressed_sum;use crate::stage1::pick_state::PredicateOp;use crate::stage1::state::Stage1State;-/// Whether `state` currently satisfies its leaf predicate, for the **op-less** variants-/// (`BehavioralSingle`, `PersonProperty`). The bucket variants carry a count comparator and must be-/// evaluated via [`daily_predicate`] / [`compressed_predicate`] with their leaf's [`PredicateOp`] —-/// every real caller already does (the worker's `mutate_behavioral_daily` and the sweep call those-/// directly). Reaching a bucket variant here is a dispatch desync: the `LeafStateKey` pins the-/// variant, so this can only happen on a coding error, and it is counted via-/// `STAGE1_STATE_DECODE_ERROR` and read as a non-member — loud, never a silently-dropped member.+/// Whether `state` currently satisfies its leaf predicate, for the **op-less** `BehavioralSingle`+/// variant. The bucket variants carry a count comparator and must be evaluated via [`daily_predicate`]+/// / [`compressed_predicate`] with their leaf's [`PredicateOp`] — every real caller already does (the+/// worker's `mutate_behavioral_daily` and the sweep call those directly). Reaching a bucket variant+/// here is a dispatch desync: the `LeafStateKey` pins the variant, so this can only happen on a coding+/// error, and it is counted via `STAGE1_STATE_DECODE_ERROR` and read as a non-member — loud, never a+/// silently-dropped member.pub fn predicate(state: &Stage1State) -> bool {match state {Stage1State::BehavioralSingle { has_match, .. } => *has_match,- Stage1State::PersonProperty { matches, .. } => *matches,Stage1State::BehavioralDailyBuckets { .. }| Stage1State::BehavioralCompressedHistory { .. } => {counter!(STAGE1_STATE_DECODE_ERROR).increment(1);@@ -71,22 +70,6 @@ mod tests {assert!(!predicate(&unmatched));}- #[test]- fn person_property_predicate_is_matches() {- let matched = Stage1State::PersonProperty {- matches: true,- last_updated_at_ms: 1,- last_updated_offset: 2,- };- let unmatched = Stage1State::PersonProperty {- matches: false,- last_updated_at_ms: 1,- last_updated_offset: 2,- };- assert!(predicate(&matched));- assert!(!predicate(&unmatched));- }-#[test]fn daily_predicate_applies_the_comparator_to_the_bucket_sum() {let buckets = [0, 1, 0, 2, 1]; // sum 4diff --git a/rust/cohort-stream-processor/src/stage1/state.rs b/rust/cohort-stream-processor/src/stage1/state.rsindex 16285241c01a..b1161de5af6c 100644--- a/rust/cohort-stream-processor/src/stage1/state.rs+++ b/rust/cohort-stream-processor/src/stage1/state.rs@@ -79,15 +79,6 @@ pub enum Stage1State {/// ([`i64::MAX`] when empty).earliest_eviction_at_ms: i64,},- /// A person-property filter: last-write-wins, tie-broken by event-time argMax- /// (`argMax(matches, (_timestamp, _offset))`).- PersonProperty {- matches: bool,- /// The argMax key's first component.- last_updated_at_ms: i64,- /// The argMax key's tiebreaker second component.- last_updated_offset: i64,- },}impl Stage1State {@@ -96,13 +87,13 @@ impl Stage1State {Self::BehavioralSingle { .. } => StateVariant::BehavioralSingle,Self::BehavioralDailyBuckets { .. } => StateVariant::BehavioralDailyBuckets,Self::BehavioralCompressedHistory { .. } => StateVariant::BehavioralCompressedHistory,- Self::PersonProperty { .. } => StateVariant::PersonProperty,}}- /// The eviction deadline (epoch ms) for this state, or [`None`] for `PersonProperty`, which is- /// last-write-wins and never time-evicts. A behavioral deadline may be [`i64::MAX`] (permanent- /// membership).+ /// The eviction deadline (epoch ms) for this state. Every `cf_behavioral` variant is behavioral+ /// and time-bounded (person-property membership lives in `cf_person_records`, which is+ /// sweep-invariant), so this is always `Some`; the deadline may be [`i64::MAX`] (permanent+ /// membership). Kept `Option`-returning so the sweep-scheduling call sites read uniformly.pub fn eviction_deadline(&self) -> Option<i64> {match self {Self::BehavioralSingle {@@ -117,7 +108,6 @@ impl Stage1State {earliest_eviction_at_ms,..} => Some(*earliest_eviction_at_ms),- Self::PersonProperty { .. } => None,}}}@@ -150,9 +140,22 @@ impl AppliedOffsets {self.record(partition, offset);}}++ /// The `(source_partition, high_water_offset)` pairs in ascending partition order — the canonical+ /// order a binary codec serializes them in.+ pub fn entries(&self) -> Vec<(i32, i64)> {+ self.0.iter().map(|(&p, &o)| (p, o)).collect()+ }++ /// Rebuild from entries already known to be sorted-distinct by partition (a codec verifies this+ /// before calling). The `BTreeMap` re-imposes the ordering regardless, so a caller that violates+ /// the precondition loses only canonicality, not correctness.+ pub fn from_sorted_entries(entries: Vec<(i32, i64)>) -> Self {+ Self(entries.into_iter().collect())+ }}-/// The persisted `cf_stage1` value: a [`Stage1State`] plus replay-dedup offsets.+/// The persisted `cf_behavioral` value: a [`Stage1State`] plus replay-dedup offsets.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct StatefulRecord {pub state: Stage1State,@@ -269,12 +272,14 @@ mod tests {)}- fn person() -> StatefulRecord {+ /// A second behavioral record with distinct offsets, used by the dedup-routing tests (whose+ /// invariants are variant-agnostic — they exercise `applied_offsets` / `redirect_dedup` only).+ fn dedup_record() -> StatefulRecord {StatefulRecord::new(- Stage1State::PersonProperty {- matches: false,- last_updated_at_ms: 1_700_000_000_123,- last_updated_offset: 99,+ Stage1State::BehavioralSingle {+ has_match: true,+ last_event_at_ms: 1_700_000_000_123,+ earliest_eviction_at_ms: i64::MAX,},applied(&[(3, 100)]),)@@ -306,7 +311,7 @@ mod tests {#[test]fn round_trips_every_variant() {- for record in [behavioral(), person(), daily(), compressed()] {+ for record in [behavioral(), dedup_record(), daily(), compressed()] {let bytes = record.encode();assert_eq!(StatefulRecord::decode(&bytes).unwrap(), record);}@@ -573,10 +578,10 @@ mod tests {#[test]fn is_replay_for_routes_by_origin() {let mut record = StatefulRecord::new(- Stage1State::PersonProperty {- matches: true,- last_updated_at_ms: 1,- last_updated_offset: 2,+ Stage1State::BehavioralSingle {+ has_match: true,+ last_event_at_ms: 1,+ earliest_eviction_at_ms: i64::MAX,},applied(&[(5, 100)]),);@@ -599,10 +604,10 @@ mod tests {#[test]fn record_for_routes_by_origin_and_creates_entries_on_demand() {let mut record = StatefulRecord::new(- Stage1State::PersonProperty {- matches: true,- last_updated_at_ms: 1,- last_updated_offset: 2,+ Stage1State::BehavioralSingle {+ has_match: true,+ last_event_at_ms: 1,+ earliest_eviction_at_ms: i64::MAX,},AppliedOffsets::default(),);@@ -626,7 +631,6 @@ mod tests {#[test]fn variant_reports_the_state_kind() {assert_eq!(behavioral().state.variant(), StateVariant::BehavioralSingle);- assert_eq!(person().state.variant(), StateVariant::PersonProperty);assert_eq!(daily().state.variant(),StateVariant::BehavioralDailyBuckets@@ -638,7 +642,7 @@ mod tests {}#[test]- fn eviction_deadline_is_some_for_behavioral_and_none_for_person_property() {+ fn eviction_deadline_is_some_for_every_behavioral_variant() {assert_eq!(behavioral().state.eviction_deadline(),Some(1_700_000_000_000 + 7 * 86_400 * 1000),@@ -651,7 +655,6 @@ mod tests {compressed().state.eviction_deadline(),Some(1_700_000_000_000 + 365 * 86_400 * 1000),);- assert_eq!(person().state.eviction_deadline(), None);// A permanent membership reports the i64::MAX sentinel.let permanent = Stage1State::BehavioralSingle {diff --git a/rust/cohort-stream-processor/src/stage2/eligibility.rs b/rust/cohort-stream-processor/src/stage2/eligibility.rsindex 4546e24d0d17..7477a2d2d6d5 100644--- a/rust/cohort-stream-processor/src/stage2/eligibility.rs+++ b/rust/cohort-stream-processor/src/stage2/eligibility.rs@@ -78,7 +78,7 @@ impl CohortEligibility {}/// Whether this class persists a `cf_stage2` row — both composable classes do; single-leaf- /// membership lives in `cf_stage1` and excluded cohorts persist nothing.+ /// membership lives in `cf_behavioral` and excluded cohorts persist nothing.pub fn writes_cf_stage2(self) -> bool {matches!(self, Self::Stage2Composable | Self::Stage2ComposableRef)}diff --git a/rust/cohort-stream-processor/src/stage2/evaluator.rs b/rust/cohort-stream-processor/src/stage2/evaluator.rsindex 60226f76ad61..a3aaebe17e1c 100644--- a/rust/cohort-stream-processor/src/stage2/evaluator.rs+++ b/rust/cohort-stream-processor/src/stage2/evaluator.rs@@ -12,13 +12,22 @@ use crate::stage1::key::LeafStateKey;use crate::stage1::predicate::{compressed_predicate, daily_predicate, predicate};use crate::stage1::state::{Stage1State, StateVariant};-/// Whether one leaf is currently a member. Absent state is `false`.+/// Whether one leaf is currently a member, from its `cf_behavioral` state. Absent state is `false`.+///+/// Person-property leaves are NOT resolved here — their membership lives in the durable+/// [`PersonRecord`](crate::stage1::PersonRecord), read directly by the Stage 2 resolver. A+/// `PersonProperty` meta reaching this function is a desync (no person-property state is ever stored in+/// `cf_behavioral`), counted and read as a non-member — loud, never a silent member.pub fn leaf_membership(state: Option<&Stage1State>, meta: &LeafStateMeta) -> bool {let Some(state) = state else {return false;};match meta.variant {- StateVariant::BehavioralSingle | StateVariant::PersonProperty => predicate(state),+ StateVariant::BehavioralSingle => predicate(state),+ StateVariant::PersonProperty => {+ counter!(STAGE2_STATE_DECODE_ERROR).increment(1);+ false+ }StateVariant::BehavioralDailyBuckets => match (state, meta.predicate_op) {(Stage1State::BehavioralDailyBuckets { buckets, .. }, Some(op)) => {daily_predicate(buckets, op)@@ -150,20 +159,7 @@ mod tests {}#[test]- fn leaf_membership_reads_the_op_less_bit() {- let yes = Stage1State::PersonProperty {- matches: true,- last_updated_at_ms: 1,- last_updated_offset: 2,- };- let no = Stage1State::PersonProperty {- matches: false,- last_updated_at_ms: 1,- last_updated_offset: 2,- };- assert!(leaf_membership(Some(&yes), &person_meta()));- assert!(!leaf_membership(Some(&no), &person_meta()));-+ fn leaf_membership_reads_the_behavioral_single_bit() {let single = LeafStateMeta {variant: StateVariant::BehavioralSingle,..person_meta()@@ -173,7 +169,23 @@ mod tests {last_event_at_ms: 1,earliest_eviction_at_ms: 2,};+ let unmatched = Stage1State::BehavioralSingle {+ has_match: false,+ last_event_at_ms: 1,+ earliest_eviction_at_ms: 2,+ };assert!(leaf_membership(Some(&matched), &single));+ assert!(!leaf_membership(Some(&unmatched), &single));+ }++ #[test]+ fn leaf_membership_person_property_meta_reads_non_member() {+ let matched = Stage1State::BehavioralSingle {+ has_match: true,+ last_event_at_ms: 1,+ earliest_eviction_at_ms: 2,+ };+ assert!(!leaf_membership(Some(&matched), &person_meta()));}#[test]diff --git a/rust/cohort-stream-processor/src/store/column_families.rs b/rust/cohort-stream-processor/src/store/column_families.rsindex 0db45356f60e..fab1e1ed5e85 100644--- a/rust/cohort-stream-processor/src/store/column_families.rs+++ b/rust/cohort-stream-processor/src/store/column_families.rs@@ -2,16 +2,18 @@use rocksdb::{BlockBasedIndexType, BlockBasedOptions, Cache, ColumnFamilyDescriptor, DBCompressionType,- Options,+ Options, SliceTransform,};+use super::keyspace::PERSON_PREFIX_LEN;use super::rocks::StoreConfig;-use super::secondary_index::{full_merge, partial_merge, PERSON_INDEX_MERGE_OPERATOR_NAME};+use super::ttl_filter::PersonRecordTtlFactory;-/// Stage 1 per-leaf state.-pub const CF_STAGE1: &str = "cf_stage1";-/// Per-person secondary index.-pub const CF_PERSON_INDEX: &str = "cf_person_index";+/// Person-clustered per-leaf state: `(partition, team, person, lsk)`.+pub const CF_BEHAVIORAL: &str = "cf_behavioral";+/// One durable record per person, keyed `(partition, team, person)` — collapses a person's+/// person-property leaf state into a single value.+pub const CF_PERSON_RECORDS: &str = "cf_person_records";/// Stage 2 membership.pub const CF_STAGE2: &str = "cf_stage2";/// Merge Phase 1 idempotence: short-circuits re-drained merge messages.@@ -22,9 +24,16 @@ pub const CF_PENDING_TRANSFERS: &str = "cf_pending_transfers";pub const CF_MERGE_APPLIED: &str = "cf_merge_applied";/// Post-merge straggler redirect: records merged-away persons for late-event redirection.pub const CF_MERGE_TOMBSTONES: &str = "cf_merge_tombstones";+/// Store-wide metadata (schema version guard). Not partition-prefixed.+pub const CF_META: &str = "cf_meta";const BLOOM_FILTER_BITS_PER_KEY: f64 = 10.0;+/// Fraction of each `cf_behavioral` memtable reserved for a prefix bloom, so a person-prefix scan can+/// skip memtables that hold none of the person's rows. Small: the on-disk prefix bloom does the heavy+/// lifting; this only trims the write-buffer edge.+const BEHAVIORAL_MEMTABLE_PREFIX_BLOOM_RATIO: f64 = 0.05;+/// Per-CF memtable count, pinned so the memtable-memory multiplier (CF × write_buffer_bytes × this)/// can't silently double if the write-buffer size is raised.const MAX_WRITE_BUFFER_NUMBER: i32 = 2;@@ -32,50 +41,70 @@ const MAX_WRITE_BUFFER_NUMBER: i32 = 2;/// Column family enum.#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]pub enum Cf {- Stage1,- PersonIndex,+ Behavioral,+ PersonRecords,Stage2,MergeDrainsApplied,PendingTransfers,MergeApplied,MergeTombstones,+ Meta,}impl Cf {- pub const ALL: [Cf; 7] = [- Cf::Stage1,- Cf::PersonIndex,+ pub const ALL: [Cf; 8] = [+ Cf::Behavioral,+ Cf::PersonRecords,Cf::Stage2,Cf::MergeDrainsApplied,Cf::PendingTransfers,Cf::MergeApplied,Cf::MergeTombstones,+ Cf::Meta,];pub const fn as_str(self) -> &'static str {match self {- Cf::Stage1 => CF_STAGE1,- Cf::PersonIndex => CF_PERSON_INDEX,+ Cf::Behavioral => CF_BEHAVIORAL,+ Cf::PersonRecords => CF_PERSON_RECORDS,Cf::Stage2 => CF_STAGE2,Cf::MergeDrainsApplied => CF_MERGE_DRAINS_APPLIED,Cf::PendingTransfers => CF_PENDING_TRANSFERS,Cf::MergeApplied => CF_MERGE_APPLIED,Cf::MergeTombstones => CF_MERGE_TOMBSTONES,+ Cf::Meta => CF_META,+ }+ }++ /// Whether this CF's keys carry the partition prefix, so a partition wipe's range delete reclaims+ /// them. Exhaustive (no wildcard arm) so every new CF is forced to declare it — a range delete over+ /// a non-partitioned CF (whose short literal keys collide with an arbitrary partition's slice)+ /// would corrupt store-wide state such as the schema guard.+ pub const fn partitioned(self) -> bool {+ match self {+ Cf::Behavioral+ | Cf::PersonRecords+ | Cf::Stage2+ | Cf::MergeDrainsApplied+ | Cf::PendingTransfers+ | Cf::MergeApplied+ | Cf::MergeTombstones => true,+ Cf::Meta => false,}}}-/// A column family safe for raw `put` (excludes `cf_person_index`).+/// A column family safe for raw `put` by pre-encoded key bytes.#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]pub enum OpaqueCf {- Stage1,+ Behavioral,Stage2,}impl OpaqueCf {pub const fn cf(self) -> Cf {match self {- OpaqueCf::Stage1 => Cf::Stage1,+ OpaqueCf::Behavioral => Cf::Behavioral,OpaqueCf::Stage2 => Cf::Stage2,}}@@ -102,7 +131,8 @@ fn cf_options(cf: Cf, config: &StoreConfig, cache: &Cache) -> Options {if config.tuned_block_options {// Cache index/filter blocks and partition them behind a two-level index (required by// partitioned filters) so point lookups short-circuit on the bloom. Whole-key filtering- // matches the point-lookup pattern; there is no prefix extractor.+ // matches the point-lookup pattern and is kept even under the prefix extractor so single-key+ // gets still short-circuit.block_opts.set_cache_index_and_filter_blocks(true);block_opts.set_pin_l0_filter_and_index_blocks_in_cache(true);block_opts.set_pin_top_level_index_and_filter(true);@@ -129,17 +159,34 @@ fn cf_options(cf: Cf, config: &StoreConfig, cache: &Cache) -> Options {opts.set_periodic_compaction_seconds(config.periodic_compaction_seconds);}+ // The exhaustive match is the structural guarantee that the TTL compaction filter can only land on+ // `Cf::PersonRecords`, never on `cf_behavioral` (whose eviction deadlines are the sweep's contract).match cf {- Cf::PersonIndex => {- opts.set_merge_operator(PERSON_INDEX_MERGE_OPERATOR_NAME, full_merge, partial_merge);+ // A fixed-length prefix extractor over the person prefix turns a person's contiguous leaf slice+ // into a bloom-backed prefix seek. Only `cf_behavioral` needs it: it holds many leaves per+ // person, so a person's rows are a range.+ Cf::Behavioral => {+ opts.set_prefix_extractor(SliceTransform::create_fixed_prefix(PERSON_PREFIX_LEN));+ opts.set_memtable_prefix_bloom_ratio(BEHAVIORAL_MEMTABLE_PREFIX_BLOOM_RATIO);+ }+ // One row per person keyed by the 26-byte prefix itself, so it keeps plain point-lookup options.+ // Install the TTL compaction filter when configured; `0` leaves the CF untouched.+ Cf::PersonRecords => {+ if config.person_record_ttl_days != 0 {+ opts.set_compaction_filter_factory(PersonRecordTtlFactory::new(+ config.person_record_ttl_days,+ ));+ }}- Cf::Stage1- | Cf::Stage2+ // `cf_meta` and the merge CFs keep plain point-lookup options.+ Cf::Stage2| Cf::MergeDrainsApplied| Cf::PendingTransfers| Cf::MergeApplied- | Cf::MergeTombstones => {}+ | Cf::MergeTombstones+ | Cf::Meta => {}}+opts}@@ -149,23 +196,35 @@ mod tests {#[test]fn cf_names_are_stable() {- assert_eq!(Cf::Stage1.as_str(), "cf_stage1");- assert_eq!(Cf::PersonIndex.as_str(), "cf_person_index");+ assert_eq!(Cf::Behavioral.as_str(), "cf_behavioral");+ assert_eq!(Cf::PersonRecords.as_str(), "cf_person_records");assert_eq!(Cf::Stage2.as_str(), "cf_stage2");assert_eq!(Cf::MergeDrainsApplied.as_str(), "cf_merge_drains_applied");assert_eq!(Cf::PendingTransfers.as_str(), "cf_pending_transfers");assert_eq!(Cf::MergeApplied.as_str(), "cf_merge_applied");assert_eq!(Cf::MergeTombstones.as_str(), "cf_merge_tombstones");+ assert_eq!(Cf::Meta.as_str(), "cf_meta");}#[test]fn all_is_exhaustive_and_unique() {- assert_eq!(Cf::ALL.len(), 7);+ assert_eq!(Cf::ALL.len(), 8);for cf in Cf::ALL {assert!(Cf::ALL.iter().filter(|&&c| c == cf).count() == 1);}}+ #[test]+ fn only_meta_is_non_partitioned() {+ for cf in Cf::ALL {+ assert_eq!(+ cf.partitioned(),+ cf != Cf::Meta,+ "every CF but cf_meta must be partition-prefixed: {cf:?}",+ );+ }+ }+#[test]fn descriptors_cover_every_cf() {let config = StoreConfig::default();diff --git a/rust/cohort-stream-processor/src/store/durability/import.rs b/rust/cohort-stream-processor/src/store/durability/import.rsindex 87ee45a444f3..e22b877c8ee3 100644--- a/rust/cohort-stream-processor/src/store/durability/import.rs+++ b/rust/cohort-stream-processor/src/store/durability/import.rs@@ -6,6 +6,7 @@ use super::{CheckpointDownloader, CheckpointMetadata, DirCleanupGuard, STORE_TOPuse crate::observability::metrics::{CHECKPOINT_IMPORT_ATTEMPT_DURATION_SECONDS, CHECKPOINT_IMPORT_DURATION_SECONDS,};+use crate::store::STORE_SCHEMA_VERSION;use anyhow::{Context, Result};use tokio_util::sync::CancellationToken;@@ -139,6 +140,20 @@ impl CheckpointImporter {}};+ // Skip a schema-mismatched checkpoint before the bulk data-file download or any local dir+ // mutation. Skipping (not failing) falls through to the next candidate, and a fully-skipped+ // list downgrades to a cold start in `restore_from_s3`.+ if attempt.store_schema != STORE_SCHEMA_VERSION {+ warn!(+ store = STORE_TOPIC,+ checkpoint = %remote_key,+ found = attempt.store_schema,+ expected = STORE_SCHEMA_VERSION,+ "Skipping checkpoint written under a different store schema version",+ );+ continue;+ }+let attempt_tag = attempt.get_attempt_path();if target_path.exists() {@@ -541,6 +556,59 @@ mod tests {);}+ #[tokio::test]+ async fn import_skips_a_schema_mismatched_checkpoint_and_uses_the_next() {+ let tmp_dir = TempDir::new().unwrap();+ let target_path = tmp_dir.path().join("store");++ let mut newest = create_test_metadata(13);+ newest.store_schema = STORE_SCHEMA_VERSION + 1; // incompatible+ let current = create_test_metadata(12); // stamped with STORE_SCHEMA_VERSION by `new`+ assert_eq!(current.store_schema, STORE_SCHEMA_VERSION);++ // Newest first, matching the S3 listing order.+ let downloader = CancellationTestDownloader::new(vec![newest.clone(), current.clone()]);+ let importer = CheckpointImporter::new(Box::new(downloader), 3, Duration::from_secs(60));++ let import_path = importer+ .import_checkpoint(&target_path)+ .await+ .expect("import should skip the mismatched candidate and use the current one");++ let loaded = CheckpointMetadata::load_from_dir(&import_path)+ .await+ .expect("metadata.json written for the accepted candidate");+ assert_eq!(+ loaded.store_schema, STORE_SCHEMA_VERSION,+ "the imported checkpoint is the current-era one, not the mismatched newest",+ );+ assert_eq!(+ loaded.id, current.id,+ "the accepted attempt is the older, schema-matching candidate",+ );+ }++ #[tokio::test]+ async fn import_fails_when_every_candidate_has_a_mismatched_schema() {+ let tmp_dir = TempDir::new().unwrap();+ let target_path = tmp_dir.path().join("store");++ let mut old_era = create_test_metadata(12);+ old_era.store_schema = 0; // pre-versioning metadata.json decodes to this+ let downloader = CancellationTestDownloader::new(vec![old_era]);+ let importer = CheckpointImporter::new(Box::new(downloader), 3, Duration::from_secs(60));++ let result = importer.import_checkpoint(&target_path).await;+ assert!(+ result.is_err(),+ "an all-mismatched candidate list yields no usable checkpoint",+ );+ assert!(+ !target_path.exists(),+ "a skipped candidate must not create or leave any local store directory",+ );+ }+#[derive(Debug)]struct FailingDownloader {metadata: CheckpointMetadata,diff --git a/rust/cohort-stream-processor/src/store/durability/metadata.rs b/rust/cohort-stream-processor/src/store/durability/metadata.rsindex 2f05921cd136..b67074361eb9 100644--- a/rust/cohort-stream-processor/src/store/durability/metadata.rs+++ b/rust/cohort-stream-processor/src/store/durability/metadata.rs@@ -13,6 +13,7 @@ use sha2::{Digest, Sha256};use tracing::debug;use super::{STORE_PARTITION, STORE_TOPIC};+use crate::store::STORE_SCHEMA_VERSION;/// Deterministic 8-hex-char prefix for spreading S3 object keys across internal partitions./// Applied ONLY to checkpoint object file paths, NEVER to metadata.json paths.@@ -70,6 +71,12 @@ pub struct CheckpointMetadata {/// deserializing metadata.json that lacks this field (backward compat).#[serde(default = "Utc::now")]pub updated_at: DateTime<Utc>,+ /// The [`STORE_SCHEMA_VERSION`] the checkpointed DB was written under, stamped at construction. A+ /// restore skips a checkpoint whose `store_schema` does not match this binary before downloading+ /// it. `#[serde(default)]` makes pre-versioning metadata.json decode to `0`, which never matches a+ /// real version and is therefore skipped.+ #[serde(default)]+ pub store_schema: u32,/// Registry of file metadata for all remotely-stored files required to reconstitute a local/// RocksDB store across all relevant checkpoint attempts.pub files: Vec<CheckpointFile>,@@ -93,6 +100,7 @@ impl CheckpointMetadata {consumer_offset,producer_offset,updated_at: attempt_timestamp,+ store_schema: STORE_SCHEMA_VERSION,files: Vec::new(),}}@@ -380,6 +388,35 @@ mod tests {assert_eq!(metadata.topic, "cohort_stream_state");assert_eq!(metadata.partition, 0);assert!(metadata.updated_at.timestamp() > 0);+ assert_eq!(+ metadata.store_schema, 0,+ "metadata without store_schema defaults to 0 (old-era, skipped on restore)",+ );+ }++ #[test]+ fn store_schema_is_stamped_on_new_and_round_trips() {+ let mut metadata = CheckpointMetadata::new(+ STORE_TOPIC.to_string(),+ STORE_PARTITION,+ Utc::now(),+ 1,+ 0,+ 0,+ );+ assert_eq!(+ metadata.store_schema, STORE_SCHEMA_VERSION,+ "a newly-constructed checkpoint is stamped with the current store schema",+ );+ let decoded = CheckpointMetadata::from_json_bytes(metadata.to_json().unwrap().as_bytes())+ .expect("round-trip");+ assert_eq!(decoded.store_schema, STORE_SCHEMA_VERSION);++ // A hand-forged older-era value survives decode unchanged (so the restore skip can read it).+ metadata.store_schema = STORE_SCHEMA_VERSION - 1;+ let older = CheckpointMetadata::from_json_bytes(metadata.to_json().unwrap().as_bytes())+ .expect("round-trip");+ assert_eq!(older.store_schema, STORE_SCHEMA_VERSION - 1);}#[test]diff --git a/rust/cohort-stream-processor/src/store/handle.rs b/rust/cohort-stream-processor/src/store/handle.rsindex 5361e9b80f6f..2524144d2fbf 100644--- a/rust/cohort-stream-processor/src/store/handle.rs+++ b/rust/cohort-stream-processor/src/store/handle.rs@@ -26,14 +26,14 @@ 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::keys::{PendingTransferKey, Stage2Key, TombstoneKey};+use super::keyspace::{BehavioralKey, PersonPrefix, PersonRecordKey};+use super::rocks::{CohortStore, EventSnapshotRaw, 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";@@ -260,28 +260,57 @@ impl StoreHandle {// --- Public async surface. Each method wraps exactly one sync `CohortStore` method. ---- /// Point-read one `cf_stage1` value. Lane-parameterized: the event fold reads on+ /// Point-read one `cf_behavioral` value. Lane-parameterized: the event fold reads on/// [`ReadLane::Event`], background scans/prefetch on [`ReadLane::Maintenance`].- pub async fn get_stage1(+ pub async fn get_behavioral(&self,- key: &Stage1Key,+ key: &BehavioralKey,lane: ReadLane,) -> Result<Option<Vec<u8>>, StoreError> {let key = *key;- self.read("get_stage1", lane, move |store| store.get_stage1(&key))- .await+ self.read("get_behavioral", lane, move |store| {+ store.get_behavioral(&key)+ })+ .await}- /// Batch-read `cf_stage1` values, preserving input order. Lane-parameterized (event fold =+ /// Batch-read `cf_behavioral` 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(+ pub async fn multi_get_behavioral(&self,- keys: Vec<Stage1Key>,+ keys: Vec<BehavioralKey>,lane: ReadLane,) -> Result<Vec<Option<Vec<u8>>>, StoreError> {- self.read("multi_get_stage1", lane, move |store| {- store.multi_get_stage1(&keys)+ self.read("multi_get_behavioral", lane, move |store| {+ store.multi_get_behavioral(&keys)+ })+ .await+ }++ /// Point-read one person's `cf_person_records` value as raw bytes. The event fold reads this on+ /// the hot path (Event lane); decoding lives with the caller.+ pub async fn get_person_record(+ &self,+ key: &PersonRecordKey,+ ) -> Result<Option<Vec<u8>>, StoreError> {+ let key = *key;+ self.read("get_person_record", ReadLane::Event, move |store| {+ store.get_person_record(&key)+ })+ .await+ }++ /// Read one event's full state snapshot in a single mixed-CF `multi_get` (behavioral keys plus+ /// the optional person-record key). The event fold's hot-path read, on the Event lane. Keys are+ /// taken by value so the closure is trivially `'static`.+ pub async fn read_event_snapshot(+ &self,+ behavioral: Vec<BehavioralKey>,+ record: Option<PersonRecordKey>,+ ) -> Result<EventSnapshotRaw, StoreError> {+ self.read("read_event_snapshot", ReadLane::Event, move |store| {+ store.read_event_snapshot(&behavioral, record.as_ref())}).await}@@ -315,18 +344,6 @@ impl StoreHandle {.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,@@ -341,19 +358,32 @@ impl StoreHandle {.await}- /// Scan a page of one partition's `cf_stage1` slice (boot rebuild, maintenance lane).- pub async fn scan_stage1(+ /// Scan a page of one partition's `cf_behavioral` slice (boot rebuild, maintenance lane).+ pub async fn scan_behavioral(&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)+ ) -> Result<Vec<(BehavioralKey, Vec<u8>)>, StoreError> {+ self.read("scan_behavioral", ReadLane::Maintenance, move |store| {+ store.scan_behavioral(partition_id, start_after.as_deref(), limit)}).await}+ /// Scan one person's whole `cf_behavioral` slice in lsk order (merge drain, maintenance lane).+ pub async fn scan_behavioral_prefix(+ &self,+ prefix: PersonPrefix,+ ) -> Result<Vec<(BehavioralKey, Vec<u8>)>, StoreError> {+ self.read(+ "scan_behavioral_prefix",+ ReadLane::Maintenance,+ move |store| store.scan_behavioral_prefix(prefix),+ )+ .await+ }+/// Scan a page of one partition's `cf_pending_transfers` slice (redrive, maintenance lane).pub async fn scan_pending_transfers(&self,diff --git a/rust/cohort-stream-processor/src/store/keys.rs b/rust/cohort-stream-processor/src/store/keys.rsindex 8bf5e405c5ae..a96559ff1ff6 100644--- a/rust/cohort-stream-processor/src/store/keys.rs+++ b/rust/cohort-stream-processor/src/store/keys.rs@@ -1,16 +1,14 @@-//! Typed, partition-prefixed key encoders for the state column families.+//! Typed, partition-prefixed key encoders for the non-state column families.//!-//! Keys are fixed-size big-endian so a partition's state is one contiguous `delete_range`.+//! Keys are fixed-size big-endian so a partition's state is one contiguous `delete_range`. The+//! person-clustered state keys live in [`super::keyspace`]; these are the merge-protocol and Stage 2+//! keys.use uuid::Uuid;+use super::keyspace::BEHAVIORAL_KEY_LEN;use super::rocks::StoreError;-use crate::stage1::key::{LeafStateKey, Stage1Key};-/// `[partition_id u16][team_id u64][leaf_state_key 16][person_id 16]`.-pub const STAGE1_KEY_LEN: usize = 2 + 8 + 16 + 16;-/// `[partition_id u16][team_id u64][person_id 16]`.-pub const PERSON_INDEX_KEY_LEN: usize = 2 + 8 + 16;/// `[partition_id u16][team_id u64][cohort_id u64][person_id 16]`.pub const STAGE2_KEY_LEN: usize = 2 + 8 + 8 + 16;/// `[partition_id u16][team_id u64][old_person 16][merge_msg_partition u32][merge_msg_offset u64]`.@@ -22,14 +20,6 @@ pub const MERGE_APPLIED_KEY_LEN: usize = 2 + 8 + 16 + 4 + 8;/// `[partition_id u16][team_id u64][person 16]`.pub const TOMBSTONE_KEY_LEN: usize = 2 + 8 + 16;-/// `cf_person_index` key: a person's Stage 1 leaf states live under this prefix.-#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]-pub struct PersonIndexKey {- pub partition_id: u16,- pub team_id: u64,- pub person_id: Uuid,-}-/// `cf_stage2` key: per-`(cohort, person)` membership state.#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]pub struct Stage2Key {@@ -80,46 +70,6 @@ pub struct TombstoneKey {pub person: Uuid,}-impl Stage1Key {- pub fn encode(&self) -> [u8; STAGE1_KEY_LEN] {- let mut out = [0u8; STAGE1_KEY_LEN];- out[0..2].copy_from_slice(&self.partition_id.to_be_bytes());- out[2..10].copy_from_slice(&self.team_id.to_be_bytes());- out[10..26].copy_from_slice(&self.leaf_state_key.0);- out[26..42].copy_from_slice(self.person_id.as_bytes());- out- }-- pub fn decode(bytes: &[u8]) -> Result<Self, StoreError> {- check_len(bytes, STAGE1_KEY_LEN, "stage1")?;- Ok(Self {- partition_id: u16::from_be_bytes(array2(&bytes[0..2])),- team_id: u64::from_be_bytes(array8(&bytes[2..10])),- leaf_state_key: LeafStateKey(array16(&bytes[10..26])),- person_id: Uuid::from_bytes(array16(&bytes[26..42])),- })- }-}--impl PersonIndexKey {- pub fn encode(&self) -> [u8; PERSON_INDEX_KEY_LEN] {- let mut out = [0u8; PERSON_INDEX_KEY_LEN];- out[0..2].copy_from_slice(&self.partition_id.to_be_bytes());- out[2..10].copy_from_slice(&self.team_id.to_be_bytes());- out[10..26].copy_from_slice(self.person_id.as_bytes());- out- }-- pub fn decode(bytes: &[u8]) -> Result<Self, StoreError> {- check_len(bytes, PERSON_INDEX_KEY_LEN, "person_index")?;- Ok(Self {- partition_id: u16::from_be_bytes(array2(&bytes[0..2])),- team_id: u64::from_be_bytes(array8(&bytes[2..10])),- person_id: Uuid::from_bytes(array16(&bytes[10..26])),- })- }-}-impl Stage2Key {pub fn encode(&self) -> [u8; STAGE2_KEY_LEN] {let mut out = [0u8; STAGE2_KEY_LEN];@@ -234,7 +184,7 @@ pub fn partition_range(partition_id: u16) -> (Vec<u8>, Vec<u8>) {let start = partition_id.to_be_bytes().to_vec();let end = match partition_id.checked_add(1) {Some(next) => next.to_be_bytes().to_vec(),- None => vec![0xFFu8; STAGE1_KEY_LEN + 1],+ None => vec![0xFFu8; BEHAVIORAL_KEY_LEN + 1],};(start, end)}@@ -275,39 +225,19 @@ fn array16(s: &[u8]) -> [u8; 16] {#[cfg(test)]mod tests {use super::*;-- fn lsk(b: u8) -> LeafStateKey {- LeafStateKey([b; 16])- }+ use crate::stage1::key::LeafStateKey;+ use crate::store::keyspace::BehavioralKey;fn person(n: u128) -> Uuid {Uuid::from_u128(n)}- fn stage1(partition_id: u16, team_id: u64) -> Stage1Key {- Stage1Key {- partition_id,- team_id,- leaf_state_key: lsk(0xAB),- person_id: person(1),- }+ fn behavioral(partition_id: u16, team_id: u64) -> BehavioralKey {+ BehavioralKey::new(partition_id, team_id, person(1), LeafStateKey([0xAB; 16]))}#[test]fn encoded_lengths_are_exact() {- assert_eq!(stage1(1, 2).encode().len(), 42);- assert_eq!(STAGE1_KEY_LEN, 42);- assert_eq!(- PersonIndexKey {- partition_id: 1,- team_id: 2,- person_id: person(3),- }- .encode()- .len(),- 26,- );- assert_eq!(PERSON_INDEX_KEY_LEN, 26);assert_eq!(Stage2Key {partition_id: 1,@@ -322,27 +252,6 @@ mod tests {assert_eq!(STAGE2_KEY_LEN, 34);}- #[test]- fn stage1_round_trips() {- let key = Stage1Key {- partition_id: 0xBEEF,- team_id: 0x0123_4567_89AB_CDEF,- leaf_state_key: lsk(0x5A),- person_id: person(0xDEAD_BEEF),- };- assert_eq!(Stage1Key::decode(&key.encode()).unwrap(), key);- }-- #[test]- fn person_index_round_trips() {- let key = PersonIndexKey {- partition_id: 7,- team_id: 42,- person_id: person(0xFEED),- };- assert_eq!(PersonIndexKey::decode(&key.encode()).unwrap(), key);- }-#[test]fn stage2_round_trips() {let key = Stage2Key {@@ -355,29 +264,21 @@ mod tests {}#[test]- fn decode_rejects_wrong_length() {- let err = Stage1Key::decode(&[0u8; 41]).unwrap_err();+ fn stage2_decode_rejects_wrong_length() {+ let err = Stage2Key::decode(&[0u8; 33]).unwrap_err();assert!(matches!(err,StoreError::KeyDecode {- kind: "stage1",- expected: 42,- actual: 41+ kind: "stage2",+ expected: 34,+ actual: 33}),"unexpected error: {err:?}",);}- #[test]- fn big_endian_prefix_orders_by_partition_then_team() {- assert!(stage1(1, u64::MAX).encode() < stage1(2, 0).encode());- assert!(stage1(1, 0).encode() < stage1(256, 0).encode());- assert!(stage1(5, 1).encode() < stage1(5, 2).encode());- assert!(stage1(5, 1).encode() < stage1(5, u64::from(u32::MAX)).encode());- }-#[test]fn partition_range_is_the_two_byte_successor() {let (start, end) = partition_range(0);@@ -391,26 +292,18 @@ mod tests {#[test]fn partition_range_brackets_every_key_in_the_partition() {+ // The behavioral key is the longest partition-prefixed state key, so bracketing it (and the+ // stage2 key) proves a partition wipe reclaims the partition's whole state slice.for p in [0u16, 5, 256, u16::MAX - 1, u16::MAX] {let (start, end) = partition_range(p);- let max_key = Stage1Key {- partition_id: p,- team_id: u64::MAX,- leaf_state_key: lsk(0xFF),- person_id: person(u128::MAX),- }- .encode();- let min_key = Stage1Key {- partition_id: p,- team_id: 0,- leaf_state_key: lsk(0x00),- person_id: person(0),- }- .encode();+ let max_key =+ BehavioralKey::new(p, u64::MAX, person(u128::MAX), LeafStateKey([0xFF; 16]))+ .encode();+ let min_key = BehavioralKey::new(p, 0, person(0), LeafStateKey([0x00; 16])).encode();assert!(start.as_slice() <= min_key.as_slice(), "start>min at p={p}");assert!(max_key.as_slice() < end.as_slice(), "max>=end at p={p}");if let Some(next) = p.checked_add(1) {- let next_min = stage1(next, 0).encode();+ let next_min = behavioral(next, 0).encode();assert!(end.as_slice() <= next_min.as_slice(),"end>next_min at p={p}"@@ -422,11 +315,11 @@ mod tests {#[test]fn max_partition_sentinel_exceeds_the_all_ones_key() {let (_start, end) = partition_range(u16::MAX);- assert!([0xFFu8; STAGE1_KEY_LEN].as_slice() < end.as_slice());+ assert!([0xFFu8; BEHAVIORAL_KEY_LEN].as_slice() < end.as_slice());}#[test]- fn merge_key_lengths_are_exact_and_within_the_stage1_bound() {+ fn merge_key_lengths_are_exact_and_within_the_state_key_bound() {assert_eq!(MERGE_DRAIN_KEY_LEN, 38);assert_eq!(PENDING_TRANSFER_KEY_LEN, 26);assert_eq!(MERGE_APPLIED_KEY_LEN, 38);@@ -437,7 +330,10 @@ mod tests {MERGE_APPLIED_KEY_LEN,TOMBSTONE_KEY_LEN,] {- assert!(len <= STAGE1_KEY_LEN, "{len} exceeds STAGE1_KEY_LEN");+ assert!(+ len <= BEHAVIORAL_KEY_LEN,+ "{len} exceeds BEHAVIORAL_KEY_LEN"+ );}let drain = MergeDrainKey {diff --git a/rust/cohort-stream-processor/src/store/keyspace.rs b/rust/cohort-stream-processor/src/store/keyspace.rsnew file mode 100644index 000000000000..1da9318d3e11--- /dev/null+++ b/rust/cohort-stream-processor/src/store/keyspace.rs@@ -0,0 +1,530 @@+//! Typed keyspaces: the sole constructors of the state column families' keys.+//!+//! A [`Keyspace`] binds a key type to exactly one [`Cf`] and to whether that CF is partition-prefixed,+//! so a key cannot be encoded for the wrong column family and every new CF is forced to declare+//! whether a partition wipe reclaims it (the [`Cf::partitioned`] exhaustive match). The state CFs are+//! person-clustered: [`PersonPrefix`] is the 26-byte `(partition, team, person)` prefix under which a+//! person's rows sort contiguously, and [`BehavioralKey`] appends a 16-byte leaf-state key so one+//! person's leaf rows form one contiguous, prefix-scannable slice.++use uuid::Uuid;++use super::column_families::Cf;+use super::rocks::StoreError;+use crate::stage1::key::LeafStateKey;++/// `[partition_id u16][team_id u64][person_id 16]`. The person-clustered prefix.+pub const PERSON_PREFIX_LEN: usize = 2 + 8 + 16;+/// `[partition_id u16][team_id u64][person_id 16][leaf_state_key 16]`.+pub const BEHAVIORAL_KEY_LEN: usize = PERSON_PREFIX_LEN + 16;++/// The 26-byte person prefix: every state key for one person sorts under it, so a person's rows are+/// one contiguous slice reachable by a prefix scan or reclaimed by a single range delete.+#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]+pub struct PersonPrefix {+ pub partition_id: u16,+ pub team_id: u64,+ pub person_id: Uuid,+}++impl PersonPrefix {+ pub fn new(partition_id: u16, team_id: u64, person_id: Uuid) -> Self {+ Self {+ partition_id,+ team_id,+ person_id,+ }+ }++ pub fn encode(&self) -> [u8; PERSON_PREFIX_LEN] {+ let mut out = [0u8; PERSON_PREFIX_LEN];+ out[0..2].copy_from_slice(&self.partition_id.to_be_bytes());+ out[2..10].copy_from_slice(&self.team_id.to_be_bytes());+ out[10..26].copy_from_slice(self.person_id.as_bytes());+ out+ }++ pub fn decode(bytes: &[u8]) -> Result<Self, StoreError> {+ check_len(bytes, PERSON_PREFIX_LEN, "person_prefix")?;+ Ok(Self {+ partition_id: u16::from_be_bytes(array2(&bytes[0..2])),+ team_id: u64::from_be_bytes(array8(&bytes[2..10])),+ person_id: Uuid::from_bytes(array16(&bytes[10..26])),+ })+ }++ /// The behavioral state key for one of this person's leaves.+ pub fn behavioral_key(&self, lsk: LeafStateKey) -> BehavioralKey {+ BehavioralKey { prefix: *self, lsk }+ }++ /// This person's `cf_person_records` key — the 26-byte prefix itself, since there is exactly one+ /// record per person.+ pub fn record_key(&self) -> PersonRecordKey {+ PersonRecordKey(*self)+ }++ /// The half-open byte range `[prefix, prefix-successor)` covering exactly this person's slice of a+ /// person-clustered CF — the unit of prefix iteration and of a single `delete_range_cf`. For an+ /// all-`0xFF` prefix (which has no shorter successor) the end is an all-`0xFF` sentinel one byte+ /// longer than the longest key under the prefix, which exceeds every such key.+ pub fn scan_range(&self) -> (Vec<u8>, Vec<u8>) {+ let start = self.encode().to_vec();+ let end = prefix_successor(&start).unwrap_or_else(|| vec![0xFFu8; BEHAVIORAL_KEY_LEN + 1]);+ (start, end)+ }+}++/// `cf_behavioral` key: one person's per-leaf state, keyed person-first so all of a person's leaves+/// sort contiguously under their [`PersonPrefix`].+#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]+pub struct BehavioralKey {+ pub prefix: PersonPrefix,+ pub lsk: LeafStateKey,+}++impl BehavioralKey {+ pub fn new(partition_id: u16, team_id: u64, person_id: Uuid, lsk: LeafStateKey) -> Self {+ Self {+ prefix: PersonPrefix::new(partition_id, team_id, person_id),+ lsk,+ }+ }++ pub fn partition_id(&self) -> u16 {+ self.prefix.partition_id+ }++ pub fn team_id(&self) -> u64 {+ self.prefix.team_id+ }++ pub fn person_id(&self) -> Uuid {+ self.prefix.person_id+ }++ pub fn lsk(&self) -> LeafStateKey {+ self.lsk+ }++ pub fn encode(&self) -> [u8; BEHAVIORAL_KEY_LEN] {+ let mut out = [0u8; BEHAVIORAL_KEY_LEN];+ out[0..PERSON_PREFIX_LEN].copy_from_slice(&self.prefix.encode());+ out[PERSON_PREFIX_LEN..].copy_from_slice(&self.lsk.0);+ out+ }++ pub fn decode(bytes: &[u8]) -> Result<Self, StoreError> {+ check_len(bytes, BEHAVIORAL_KEY_LEN, "behavioral")?;+ Ok(Self {+ prefix: PersonPrefix::decode(&bytes[0..PERSON_PREFIX_LEN])?,+ lsk: LeafStateKey(array16(&bytes[PERSON_PREFIX_LEN..])),+ })+ }+}++/// `cf_person_records` key: exactly one record per person, so the key IS the 26-byte+/// [`PersonPrefix`] — no leaf suffix. Byte-identical to the prefix encoding, so it nests inside the+/// same partition range as the behavioral keys and a partition wipe reclaims it.+#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]+pub struct PersonRecordKey(pub PersonPrefix);++impl PersonRecordKey {+ pub fn new(partition_id: u16, team_id: u64, person_id: Uuid) -> Self {+ Self(PersonPrefix::new(partition_id, team_id, person_id))+ }++ pub fn encode(&self) -> [u8; PERSON_PREFIX_LEN] {+ self.0.encode()+ }++ pub fn decode(bytes: &[u8]) -> Result<Self, StoreError> {+ Ok(Self(PersonPrefix::decode(bytes)?))+ }+}++/// `cf_meta` key: a small set of ASCII-literal keys carrying store-wide guards (schema version). Not+/// partition-prefixed, so it is exempt from partition wipes.+#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]+pub struct MetaKey(pub &'static [u8]);++/// `cf_meta[b"schema_version"]` → the store schema version as a big-endian `u32`.+pub const META_SCHEMA_VERSION: MetaKey = MetaKey(b"schema_version");++mod sealed {+ /// Sealed so only this module's keyspaces implement [`super::Keyspace`]; downstream code cannot+ /// bind a new key type to a CF without declaring its partitioning here.+ pub trait Sealed {}+}++/// A typed keyspace: one key type bound to one column family and to whether that CF is partitioned.+///+/// The binding is what stops a key from being written to the wrong CF (the generic+/// `BatchBuilder::put::<K>` / `StagedBatch::put::<K>` route by `K::CF`) and what forces every CF to+/// declare, via [`Cf::partitioned`]'s exhaustive match, whether a partition wipe reclaims it.+pub trait Keyspace: sealed::Sealed {+ /// The column family this keyspace's keys live in.+ const CF: Cf;+ /// Whether keys carry the partition prefix, so a partition wipe's range delete reclaims them.+ const PARTITIONED: bool;+ /// The typed key. `Copy + Send + 'static` so it can be encoded into an owned staged op.+ type Key: Copy + Send + 'static;++ fn encode(key: &Self::Key) -> Vec<u8>;+ fn decode(bytes: &[u8]) -> Result<Self::Key, StoreError>;+}++/// The person-clustered behavioral-state keyspace.+pub struct Behavioral;++impl sealed::Sealed for Behavioral {}++impl Keyspace for Behavioral {+ const CF: Cf = Cf::Behavioral;+ const PARTITIONED: bool = true;+ type Key = BehavioralKey;++ fn encode(key: &BehavioralKey) -> Vec<u8> {+ key.encode().to_vec()+ }++ fn decode(bytes: &[u8]) -> Result<BehavioralKey, StoreError> {+ BehavioralKey::decode(bytes)+ }+}++/// The per-person-record keyspace: one row per person under the 26-byte prefix. Partitioned, so a+/// partition wipe reclaims it via the shared partition range.+pub struct PersonRecords;++impl sealed::Sealed for PersonRecords {}++impl Keyspace for PersonRecords {+ const CF: Cf = Cf::PersonRecords;+ const PARTITIONED: bool = true;+ type Key = PersonRecordKey;++ fn encode(key: &PersonRecordKey) -> Vec<u8> {+ key.encode().to_vec()+ }++ fn decode(bytes: &[u8]) -> Result<PersonRecordKey, StoreError> {+ PersonRecordKey::decode(bytes)+ }+}++/// The store-metadata keyspace. Not partitioned: its ASCII-literal keys are shorter than a partition+/// range's upper bound and would collide with an arbitrary partition's slice, so a partition wipe must+/// never range over it (e.g. `b"sc"` = `0x7363` sits inside partition `29539`'s range).+pub struct Meta;++impl sealed::Sealed for Meta {}++impl Keyspace for Meta {+ const CF: Cf = Cf::Meta;+ const PARTITIONED: bool = false;+ type Key = MetaKey;++ fn encode(key: &MetaKey) -> Vec<u8> {+ key.0.to_vec()+ }++ fn decode(bytes: &[u8]) -> Result<MetaKey, StoreError> {+ // `cf_meta` keys are a closed set of literals; match them rather than fabricate a `&'static`+ // from runtime bytes. A wrong length is a length error; a right-length key that matches no+ // literal is an unknown key — conflating the two would report "expected N bytes, got N".+ if bytes == META_SCHEMA_VERSION.0 {+ Ok(META_SCHEMA_VERSION)+ } else if bytes.len() != META_SCHEMA_VERSION.0.len() {+ Err(StoreError::KeyDecode {+ kind: "meta",+ expected: META_SCHEMA_VERSION.0.len(),+ actual: bytes.len(),+ })+ } else {+ Err(StoreError::UnknownKey { kind: "meta" })+ }+ }+}++/// The smallest byte string strictly greater than every extension of `prefix`: increment the last+/// byte below `0xFF`, dropping the trailing `0xFF` run. Returns `None` for an all-`0xFF` prefix, which+/// has no such bound — the caller supplies a length-based sentinel that exceeds every key.+fn prefix_successor(prefix: &[u8]) -> Option<Vec<u8>> {+ let mut end = prefix.to_vec();+ while let Some(last) = end.last_mut() {+ if *last == 0xFF {+ end.pop();+ } else {+ *last += 1;+ return Some(end);+ }+ }+ None+}++fn check_len(bytes: &[u8], expected: usize, kind: &'static str) -> Result<(), StoreError> {+ if bytes.len() == expected {+ Ok(())+ } else {+ Err(StoreError::KeyDecode {+ kind,+ expected,+ actual: bytes.len(),+ })+ }+}++fn array2(s: &[u8]) -> [u8; 2] {+ let mut a = [0u8; 2];+ a.copy_from_slice(s);+ a+}+fn array8(s: &[u8]) -> [u8; 8] {+ let mut a = [0u8; 8];+ a.copy_from_slice(s);+ a+}+fn array16(s: &[u8]) -> [u8; 16] {+ let mut a = [0u8; 16];+ a.copy_from_slice(s);+ a+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::store::keys::partition_range;++ fn lsk(b: u8) -> LeafStateKey {+ LeafStateKey([b; 16])+ }++ fn person(n: u128) -> Uuid {+ Uuid::from_u128(n)+ }++ fn behavioral(partition_id: u16, team_id: u64, p: u128, l: u8) -> BehavioralKey {+ BehavioralKey::new(partition_id, team_id, person(p), lsk(l))+ }++ #[test]+ fn encoded_lengths_are_exact() {+ assert_eq!(PERSON_PREFIX_LEN, 26);+ assert_eq!(BEHAVIORAL_KEY_LEN, 42);+ assert_eq!(+ PersonPrefix::new(1, 2, person(3)).encode().len(),+ PERSON_PREFIX_LEN,+ );+ assert_eq!(behavioral(1, 2, 3, 4).encode().len(), BEHAVIORAL_KEY_LEN);+ }++ #[test]+ fn person_prefix_round_trips() {+ let key = PersonPrefix::new(0xBEEF, 0x0123_4567_89AB_CDEF, person(0xDEAD_BEEF));+ assert_eq!(PersonPrefix::decode(&key.encode()).unwrap(), key);+ }++ #[test]+ fn behavioral_key_round_trips() {+ let key = behavioral(0xBEEF, 0x0123_4567_89AB_CDEF, 0xDEAD_BEEF, 0x5A);+ assert_eq!(BehavioralKey::decode(&key.encode()).unwrap(), key);+ }++ #[test]+ fn behavioral_key_accessors_match_the_prefix() {+ let key = behavioral(7, 42, 99, 0xAB);+ assert_eq!(key.partition_id(), 7);+ assert_eq!(key.team_id(), 42);+ assert_eq!(key.person_id(), person(99));+ assert_eq!(key.lsk(), lsk(0xAB));+ }++ #[test]+ fn decode_rejects_wrong_length() {+ let err = BehavioralKey::decode(&[0u8; 41]).unwrap_err();+ assert!(+ matches!(+ err,+ StoreError::KeyDecode {+ kind: "behavioral",+ expected: 42,+ actual: 41,+ }+ ),+ "unexpected error: {err:?}",+ );+ }++ #[test]+ fn behavioral_keys_sort_person_first_then_leaf() {+ // Person clustering: a person's leaves are contiguous; a different person sorts as a block.+ assert!(behavioral(5, 7, 1, 0xFF).encode() < behavioral(5, 7, 2, 0x00).encode());+ // Within one person, leaves sort by lsk.+ assert!(behavioral(5, 7, 1, 0x01).encode() < behavioral(5, 7, 1, 0x02).encode());+ // Partition then team still dominate.+ assert!(+ behavioral(1, u64::MAX, u128::MAX, 0xFF).encode() < behavioral(2, 0, 0, 0x00).encode()+ );+ assert!(behavioral(5, 1, 0, 0x00).encode() < behavioral(5, 2, 0, 0x00).encode());+ }++ #[test]+ fn scan_range_brackets_exactly_one_persons_leaves() {+ let prefix = PersonPrefix::new(5, 7, person(42));+ let (start, end) = prefix.scan_range();++ let min_leaf = prefix.behavioral_key(lsk(0x00)).encode();+ let max_leaf = prefix.behavioral_key(lsk(0xFF)).encode();+ assert!(start.as_slice() <= min_leaf.as_slice());+ assert!(max_leaf.as_slice() < end.as_slice());++ // A neighbouring person's minimum leaf is at or past the end (never inside this person's range).+ let next_person = PersonPrefix::new(5, 7, person(43))+ .behavioral_key(lsk(0x00))+ .encode();+ assert!(end.as_slice() <= next_person.as_slice());+ // The previous person's maximum leaf is strictly below the start.+ let prev_person = PersonPrefix::new(5, 7, person(41))+ .behavioral_key(lsk(0xFF))+ .encode();+ assert!(prev_person.as_slice() < start.as_slice());+ }++ #[test]+ fn scan_range_handles_a_trailing_0xff_in_the_person_id() {+ // The middle `prefix_successor` case, hit by neither existing test: a trailing `0xFF` run is+ // popped and then a non-`0xFF` byte is incremented, yielding a *shortened* successor.+ // person(0xFF)'s 26-byte prefix ends `..0x00 0xFF` while the partition/team are not maxed, so+ // it takes neither the no-pop path (person(42)) nor the all-ones sentinel path. A bug in the+ // popping loop would mis-bracket exactly the persons whose UUID ends in `0xFF`.+ let prefix = PersonPrefix::new(5, 7, person(0xFF));+ let (start, end) = prefix.scan_range();++ let min_leaf = prefix.behavioral_key(lsk(0x00)).encode();+ let max_leaf = prefix.behavioral_key(lsk(0xFF)).encode();+ assert!(start.as_slice() <= min_leaf.as_slice());+ assert!(max_leaf.as_slice() < end.as_slice());++ // The next person (UUID rolls `..0x00 0xFF` -> `..0x01 0x00`) starts at or past the end.+ let next_person = PersonPrefix::new(5, 7, person(0x100))+ .behavioral_key(lsk(0x00))+ .encode();+ assert!(end.as_slice() <= next_person.as_slice());+ // The previous person's maximum leaf is strictly below the start.+ let prev_person = PersonPrefix::new(5, 7, person(0xFE))+ .behavioral_key(lsk(0xFF))+ .encode();+ assert!(prev_person.as_slice() < start.as_slice());+ }++ #[test]+ fn scan_range_handles_the_all_ones_prefix() {+ let prefix = PersonPrefix::new(u16::MAX, u64::MAX, person(u128::MAX));+ let (start, end) = prefix.scan_range();+ let max_leaf = prefix.behavioral_key(lsk(0xFF)).encode();+ assert!(start.as_slice() <= max_leaf.as_slice());+ assert!(+ max_leaf.as_slice() < end.as_slice(),+ "sentinel exceeds the all-ones key"+ );+ }++ #[test]+ fn behavioral_keys_share_the_partition_prefix_so_delete_range_reclaims_them() {+ // The person-prefix range nests inside the partition range, so a partition wipe still reclaims+ // every behavioral key in the partition.+ for p in [0u16, 5, 256, u16::MAX] {+ let (start, end) = partition_range(p);+ let max = behavioral(p, u64::MAX, u128::MAX, 0xFF).encode();+ let min = behavioral(p, 0, 0, 0x00).encode();+ assert!(start.as_slice() <= min.as_slice(), "start>min at p={p}");+ assert!(max.as_slice() < end.as_slice(), "max>=end at p={p}");+ }+ }++ #[test]+ fn keyspace_consts_bind_key_types_to_the_right_cf() {+ assert_eq!(Behavioral::CF, Cf::Behavioral);+ assert_eq!(PersonRecords::CF, Cf::PersonRecords);+ assert_eq!(Meta::CF, Cf::Meta);+ // Each keyspace's PARTITIONED const must agree with its CF's `partitioned()` — the exhaustive+ // match `delete_partition` relies on. A drift here would range-delete (or spare) the wrong CF.+ assert_eq!(Behavioral::PARTITIONED, Cf::Behavioral.partitioned());+ assert_eq!(PersonRecords::PARTITIONED, Cf::PersonRecords.partitioned());+ assert_eq!(Meta::PARTITIONED, Cf::Meta.partitioned());+ }++ #[test]+ fn person_record_key_is_byte_identical_to_the_person_prefix() {+ let prefix = PersonPrefix::new(0xBEEF, 0x0123_4567_89AB_CDEF, person(0xDEAD_BEEF));+ let key = prefix.record_key();+ assert_eq!(key.0, prefix);+ assert_eq!(+ key.encode(),+ prefix.encode(),+ "record key encodes as the bare prefix"+ );+ assert_eq!(PersonRecordKey::decode(&key.encode()).unwrap(), key);+ assert_eq!(+ PersonRecordKey::new(0xBEEF, 0x0123_4567_89AB_CDEF, person(0xDEAD_BEEF)),+ key,+ );+ }++ #[test]+ fn person_record_keyspace_encode_matches_the_key_encoder() {+ let key = PersonRecordKey::new(3, 7, person(9));+ assert_eq!(PersonRecords::encode(&key), key.encode().to_vec());+ assert_eq!(+ PersonRecords::decode(&PersonRecords::encode(&key)).unwrap(),+ key+ );+ }++ #[test]+ fn person_record_keys_share_the_partition_prefix_so_delete_range_reclaims_them() {+ // Same nesting property as the behavioral keys: a person-record key sits inside the partition+ // range, so a partition wipe reclaims it too.+ for p in [0u16, 5, 256, u16::MAX] {+ let (start, end) = partition_range(p);+ let max = PersonRecordKey::new(p, u64::MAX, person(u128::MAX)).encode();+ let min = PersonRecordKey::new(p, 0, person(0)).encode();+ assert!(start.as_slice() <= min.as_slice(), "start>min at p={p}");+ assert!(max.as_slice() < end.as_slice(), "max>=end at p={p}");+ }+ }++ #[test]+ fn behavioral_keyspace_encode_matches_the_key_encoder() {+ let key = behavioral(3, 7, 9, 0xAB);+ assert_eq!(Behavioral::encode(&key), key.encode().to_vec());+ assert_eq!(Behavioral::decode(&Behavioral::encode(&key)).unwrap(), key);+ }++ #[test]+ fn meta_keyspace_round_trips_the_known_literal_and_rejects_others() {+ assert_eq!(+ Meta::encode(&META_SCHEMA_VERSION),+ b"schema_version".to_vec()+ );+ assert_eq!(+ Meta::decode(b"schema_version").unwrap(),+ META_SCHEMA_VERSION,+ );+ // Wrong length reports the length; a right-length unknown key reports the content — a+ // conflation would claim "expected 14 bytes, got 14" for the latter.+ assert!(matches!(+ Meta::decode(b"unknown").unwrap_err(),+ StoreError::KeyDecode {+ kind: "meta",+ expected: 14,+ actual: 7,+ },+ ));+ assert!(matches!(+ Meta::decode(b"schema_versioX").unwrap_err(),+ StoreError::UnknownKey { kind: "meta" },+ ));+ }+}diff --git a/rust/cohort-stream-processor/src/store/mod.rs b/rust/cohort-stream-processor/src/store/mod.rsindex 0a26580534fa..c5e1803eb70c 100644--- a/rust/cohort-stream-processor/src/store/mod.rs+++ b/rust/cohort-stream-processor/src/store/mod.rs@@ -4,20 +4,25 @@ pub mod column_families;pub mod durability;pub mod handle;pub mod keys;+pub mod keyspace;pub mod rocks;-pub mod secondary_index;pub mod staged;+pub mod ttl_filter;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,+ Cf, OpaqueCf, CF_BEHAVIORAL, CF_MERGE_APPLIED, CF_MERGE_DRAINS_APPLIED, CF_MERGE_TOMBSTONES,+ CF_META, CF_PENDING_TRANSFERS, CF_PERSON_RECORDS, CF_STAGE2,};pub use handle::{OffloadConfig, OffloadMode, ReadLane, StoreHandle};-pub use keys::{- MergeAppliedKey, MergeDrainKey, PendingTransferKey, PersonIndexKey, Stage2Key, TombstoneKey,+pub use keys::{MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage2Key, TombstoneKey};+pub use keyspace::{+ Behavioral, BehavioralKey, Keyspace, Meta, MetaKey, PersonPrefix, PersonRecordKey,+ PersonRecords,+};+pub use rocks::{+ BatchBuilder, CfStats, CohortStore, EventSnapshotRaw, StoreConfig, StoreError, StoreStats,+ STORE_SCHEMA_VERSION,};-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};+pub use crate::stage1::key::LeafStateKey;diff --git a/rust/cohort-stream-processor/src/store/rocks.rs b/rust/cohort-stream-processor/src/store/rocks.rsindex 8fcaa8aabfcf..72d39b1c038e 100644--- a/rust/cohort-stream-processor/src/store/rocks.rs+++ b/rust/cohort-stream-processor/src/store/rocks.rs@@ -18,20 +18,32 @@ use rocksdb::{ReadOptions, SingleThreaded, WriteBatch, WriteOptions,};use thiserror::Error;+use tracing::warn;use super::column_families::{self, Cf, OpaqueCf};use super::keys::{- self, MergeAppliedKey, MergeDrainKey, PendingTransferKey, PersonIndexKey, Stage2Key,- TombstoneKey,+ self, MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage2Key, TombstoneKey,+};+use super::keyspace::{+ BehavioralKey, Keyspace, Meta, PersonPrefix, PersonRecordKey, META_SCHEMA_VERSION,};-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,- WAL_FSYNC_DURATION_SECONDS, WAL_FSYNC_ERRORS_TOTAL,+ STORE_READ_DURATION_SECONDS, STORE_SCHEMA_MISMATCH_WIPES_TOTAL, STORE_WRITE_BATCH_TOTAL,+ STORE_WRITE_DURATION_SECONDS, WAL_FSYNC_DURATION_SECONDS, WAL_FSYNC_ERRORS_TOTAL,};-use crate::stage1::key::{LeafStateKey, Stage1Key};++/// On-disk store schema version, stamped into `cf_meta` at first open and checked on every reopen.+/// A layout revision (key codec, value shape) that keeps the same CF set MUST bump this so an older+/// store fails fast instead of being misread; an on-disk CF *outside* `Cf::ALL` is caught independently+/// by `open_cf_descriptors` (see [`CohortStore::open_inner`]).+///+/// The same version is also stamped into checkpoint `metadata.json` and checked on restore+/// (`store/durability/import.rs`), which has *different* failure semantics: a mismatched checkpoint is+/// silently skipped (falling through to the next candidate, then to a cold start), never a hard fail.+/// A future bump must keep both guards in mind.+pub const STORE_SCHEMA_VERSION: u32 = 3;const OP_OPEN: &str = "open";const OP_DESTROY: &str = "destroy";@@ -65,6 +77,9 @@ pub struct StoreConfig {pub create_if_missing: bool,/// Destroy any existing database at `path` before opening.pub wipe_on_start: bool,+ /// On a schema-version mismatch at open, destroy and recreate the store instead of failing fast.+ /// Off by default: a mismatch is a hard error so a stale store or checkpoint is never misread.+ pub wipe_on_schema_mismatch: bool,/// Enable RocksDB statistics so [`CohortStore::stats_snapshot`] reports live cache tickers; they/// read 0 when off.pub statistics_enabled: bool,@@ -85,6 +100,11 @@ pub struct StoreConfig {pub periodic_compaction_seconds: u64,/// Non-positive leaves RocksDB's default untouched.pub max_background_jobs: i32,+ /// TTL in days for `cf_person_records`: a compaction filter drops a person record whose+ /// `last_seen_ms` is older than this. `0` (the default) installs no filter. Attached to+ /// `cf_person_records` **only** — never `cf_behavioral`, whose eviction deadlines are the sweep's+ /// contract. See [`super::ttl_filter`].+ pub person_record_ttl_days: u32,}impl Default for StoreConfig {@@ -96,6 +116,7 @@ impl Default for StoreConfig {max_open_files: DEFAULT_MAX_OPEN_FILES,create_if_missing: true,wipe_on_start: false,+ wipe_on_schema_mismatch: false,statistics_enabled: true,read_sample_ratio: DEFAULT_READ_SAMPLE_RATIO,tuned_block_options: true,@@ -105,6 +126,7 @@ impl Default for StoreConfig {compact_on_deletion_ratio: DEFAULT_COMPACT_ON_DELETION_RATIO,periodic_compaction_seconds: 0,max_background_jobs: 0,+ person_record_ttl_days: 0,}}}@@ -134,6 +156,17 @@ pub enum StoreError {actual: usize,},+ /// A key of the right length that matches none of the keyspace's known literals (closed-set+ /// keyspaces like `cf_meta`). Distinct from [`Self::KeyDecode`], which reports a length mismatch.+ #[error("unknown {kind} key: matches no known literal")]+ UnknownKey { kind: &'static str },++ #[error(+ "store schema mismatch: on-disk version {found:?} != expected {expected}; refusing to open \+ (set COHORT_WIPE_ON_SCHEMA_MISMATCH=true to wipe and recreate)"+ )]+ SchemaMismatch { found: Option<u32>, expected: u32 },+#[error("store offload cancelled by runtime shutdown")]OffloadCancelled,}@@ -161,26 +194,60 @@ pub struct CohortStore {impl CohortStore {/// Open the column families at `config.path`, creating them if missing.+ ///+ /// After open, the schema guard runs: a store that did not exist before this open is stamped with+ /// [`STORE_SCHEMA_VERSION`]; an existing store's stamp is checked. A mismatch (or an absent stamp on+ /// an existing store) is a hard [`StoreError::SchemaMismatch`] — unless `wipe_on_schema_mismatch`,+ /// which destroys and recreates the store, then stamps the fresh one. A store carrying a CF outside+ /// `Cf::ALL` never reaches this guard: it fails earlier in [`Self::open_inner`] (see there for the+ /// extra-vs-subset asymmetry the version key exists to close).pub fn open(config: &StoreConfig) -> Result<Self, StoreError> {- let cache = Cache::new_lru_cache(config.block_cache_bytes);let db_opts = db_options(config);if config.wipe_on_start && config.path.exists() {- DBWithThreadMode::<SingleThreaded>::destroy(&db_opts, &config.path).map_err(- |source| {- counter!(STORE_ERRORS_TOTAL, "op" => OP_DESTROY).increment(1);- StoreError::Open {- path: config.path.clone(),- source,- }- },- )?;+ destroy_db(&db_opts, &config.path)?;}- let descriptors = column_families::descriptors(config, &cache);+ let mut path_existed = config.path.exists();+ loop {+ let store = Self::open_inner(config, &db_opts)?;+ match store.check_schema(path_existed, config.wipe_on_schema_mismatch)? {+ SchemaCheck::Ok => return Ok(store),+ SchemaCheck::WipeAndRetry => {+ // Drop the handle before destroy: RocksDB cannot destroy an open DB.+ drop(store);+ counter!(STORE_SCHEMA_MISMATCH_WIPES_TOTAL).increment(1);+ warn!(+ path = ?config.path,+ expected = STORE_SCHEMA_VERSION,+ "store schema mismatch with wipe-on-mismatch set: destroying and recreating",+ );+ destroy_db(&db_opts, &config.path)?;+ // The recreated store is fresh, so the retry stamps it rather than re-checking.+ path_existed = false;+ }+ }+ }+ }+ /// Open the DB handle without the schema guard. Shared by the first open and the post-wipe reopen.+ ///+ /// The descriptor list is the fixed `Cf::ALL` set, and this is where cross-era CF-set differences+ /// are caught — but only in one direction, so the `cf_meta` version key is not redundant with it:+ /// - A store with a CF *absent from* `Cf::ALL` (e.g. a pre-`cf_behavioral` store's `cf_stage1` /+ /// `cf_person_index`) hard-fails here with a generic [`StoreError::Open`], before `check_schema`+ /// and its `wipe_on_schema_mismatch` branch run. That is intentional: fail-fast and incapable of+ /// misreading bytes. Such a store cannot exist once this schema is live (PoC posture wipes and+ /// replays rather than migrates), so there is deliberately no legacy-CF upgrade path here.+ /// - A store *missing* a CF that `Cf::ALL` adds (a subset) does NOT fail: `create_missing_column_+ /// families(true)` creates it and the open succeeds. Same for an identical CF set with a changed+ /// value layout. Those are exactly the cases the [`STORE_SCHEMA_VERSION`] stamp in `cf_meta`+ /// guards against being silently misread.+ fn open_inner(config: &StoreConfig, db_opts: &Options) -> Result<Self, StoreError> {+ let cache = Cache::new_lru_cache(config.block_cache_bytes);+ let descriptors = column_families::descriptors(config, &cache);let db = DBWithThreadMode::<SingleThreaded>::open_cf_descriptors(- &db_opts,+ db_opts,&config.path,descriptors,)@@ -194,12 +261,50 @@ impl CohortStore {Ok(Self {db: Arc::new(db),- db_opts: Arc::new(db_opts),+ db_opts: Arc::new(db_opts.clone()),// Floor at 1: `next % ratio` must not divide by zero.read_sample_ratio: config.read_sample_ratio.max(1),})}+ /// Compare the `cf_meta` schema stamp against [`STORE_SCHEMA_VERSION`]. A fresh store (one that+ /// did not exist before this open) is stamped and passes; an existing store must match. On+ /// mismatch, either fail typed or signal a wipe-and-retry per `wipe_on_schema_mismatch`.+ fn check_schema(+ &self,+ path_existed: bool,+ wipe_on_schema_mismatch: bool,+ ) -> Result<SchemaCheck, StoreError> {+ if !path_existed {+ self.stamp_schema_version()?;+ return Ok(SchemaCheck::Ok);+ }+ let found = self+ .get(Cf::Meta, META_SCHEMA_VERSION.0)?+ .and_then(|bytes| {+ bytes+ .get(0..4)+ .map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]))+ });+ if found == Some(STORE_SCHEMA_VERSION) {+ Ok(SchemaCheck::Ok)+ } else if wipe_on_schema_mismatch {+ Ok(SchemaCheck::WipeAndRetry)+ } else {+ Err(StoreError::SchemaMismatch {+ found,+ expected: STORE_SCHEMA_VERSION,+ })+ }+ }++ /// Stamp `cf_meta[b"schema_version"]` with the current schema version (big-endian `u32`).+ fn stamp_schema_version(&self) -> Result<(), StoreError> {+ self.write_batch(|batch| {+ batch.put::<Meta>(&META_SCHEMA_VERSION, &STORE_SCHEMA_VERSION.to_be_bytes());+ })+ }+/// Read a raw value from any CF.pub fn get(&self, cf: Cf, key: &[u8]) -> Result<Option<Vec<u8>>, StoreError> {let handle = self.cf(cf)?;@@ -217,18 +322,21 @@ impl CohortStore {})}- pub fn get_stage1(&self, key: &Stage1Key) -> Result<Option<Vec<u8>>, StoreError> {- self.get(Cf::Stage1, &key.encode())+ pub fn get_behavioral(&self, key: &BehavioralKey) -> Result<Option<Vec<u8>>, StoreError> {+ self.get(Cf::Behavioral, &key.encode())}- /// Batch-read several `cf_stage1` values in one call, preserving input order.- pub fn multi_get_stage1(&self, keys: &[Stage1Key]) -> Result<Vec<Option<Vec<u8>>>, StoreError> {+ /// Batch-read several `cf_behavioral` values in one call, preserving input order.+ pub fn multi_get_behavioral(+ &self,+ keys: &[BehavioralKey],+ ) -> Result<Vec<Option<Vec<u8>>>, StoreError> {// An empty batch is not a read: skip it so it records no phantom read-latency sample.if keys.is_empty() {return Ok(Vec::new());}- let handle = self.cf(Cf::Stage1)?;- let encoded: Vec<_> = keys.iter().map(Stage1Key::encode).collect();+ let handle = self.cf(Cf::Behavioral)?;+ let encoded: Vec<_> = keys.iter().map(BehavioralKey::encode).collect();let started = Instant::now();let results = self.db@@ -248,6 +356,79 @@ impl CohortStore {.collect()}+ /// Point-read one person's `cf_person_records` value as raw bytes. Decoding into a+ /// [`PersonRecord`](crate::stage1::PersonRecord) lives with the caller.+ pub fn get_person_record(&self, key: &PersonRecordKey) -> Result<Option<Vec<u8>>, StoreError> {+ self.get(Cf::PersonRecords, &key.encode())+ }++ /// Read one event's full state snapshot in a single mixed-CF `multi_get`: the `behavioral` keys+ /// (in order) plus, when `record` is given, the person's `cf_person_records` key as the final+ /// lookup.+ ///+ /// The result preserves order: `behavioral[i]` corresponds to the i-th requested behavioral key,+ /// and `record` is `Some(_)` iff a record key was requested (`Some(None)` = requested but absent).+ /// An empty behavioral set with no record key reads nothing.+ pub fn read_event_snapshot(+ &self,+ behavioral: &[BehavioralKey],+ record: Option<&PersonRecordKey>,+ ) -> Result<EventSnapshotRaw, StoreError> {+ // Nothing to read: skip so no phantom read-latency sample is recorded.+ if behavioral.is_empty() && record.is_none() {+ return Ok(EventSnapshotRaw {+ behavioral: Vec::new(),+ record: None,+ });+ }++ let behavioral_handle = self.cf(Cf::Behavioral)?;+ let behavioral_encoded: Vec<_> = behavioral.iter().map(BehavioralKey::encode).collect();++ // Behavioral handles first, the record handle last; `multi_get_cf` preserves this order, so the+ // record's result is the trailing slot.+ let mut pairs: Vec<(&ColumnFamily, &[u8])> = behavioral_encoded+ .iter()+ .map(|key| (behavioral_handle, key.as_slice()))+ .collect();++ let record_encoded = record.map(PersonRecordKey::encode);+ if let Some(encoded) = record_encoded.as_ref() {+ let record_handle = self.cf(Cf::PersonRecords)?;+ pairs.push((record_handle, encoded.as_slice()));+ }++ let started = Instant::now();+ let results = self.db.multi_get_cf(pairs);+ record_multi_get(started, results.len());++ let mut decoded: Vec<Option<Vec<u8>>> = Vec::with_capacity(results.len());+ for result in results {+ decoded.push(result.map_err(|source| {+ counter!(STORE_ERRORS_TOTAL, "op" => OP_MULTI_GET).increment(1);+ StoreError::Backend {+ op: OP_MULTI_GET,+ source,+ }+ })?);+ }++ let record_slot = if record.is_some() {+ Some(+ decoded+ .pop()+ .expect("a requested record key yields a result slot"),+ )+ } else {+ None+ };++ Ok(EventSnapshotRaw {+ behavioral: decoded,+ record: record_slot,+ })+ }+pub fn get_stage2(&self, key: &Stage2Key) -> Result<Option<Vec<u8>>, StoreError> {self.get(Cf::Stage2, &key.encode())}@@ -279,14 +460,6 @@ impl CohortStore {.collect()}- /// A missing key decodes to an empty vec.- pub fn get_person_index(&self, key: &PersonIndexKey) -> Result<Vec<LeafStateKey>, StoreError> {- Ok(self- .get(Cf::PersonIndex, &key.encode())?- .map(|bytes| decode_person_index(&bytes))- .unwrap_or_default())- }-/// Apply writes across CFs in one atomic `WriteBatch`.pub fn write_batch<F>(&self, build: F) -> Result<(), StoreError>where@@ -294,13 +467,14 @@ impl CohortStore {{let mut builder = BatchBuilder {batch: WriteBatch::default(),- stage1: self.cf(Cf::Stage1)?,- person_index: self.cf(Cf::PersonIndex)?,+ behavioral: self.cf(Cf::Behavioral)?,+ person_records: self.cf(Cf::PersonRecords)?,stage2: self.cf(Cf::Stage2)?,merge_drains_applied: self.cf(Cf::MergeDrainsApplied)?,pending_transfers: self.cf(Cf::PendingTransfers)?,merge_applied: self.cf(Cf::MergeApplied)?,merge_tombstones: self.cf(Cf::MergeTombstones)?,+ meta: self.cf(Cf::Meta)?,};build(&mut builder);self.commit(builder.batch, OP_WRITE_BATCH)@@ -321,9 +495,6 @@ impl CohortStore {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)@@ -359,7 +530,7 @@ impl CohortStore {/// Scan up to `limit` of one partition's `cf_pending_transfers` slice, returning `(key, value)`/// in key order, resuming strictly *after* `start_after` (exclusive) when given. The per-tick/// redrive passes a bounded `limit` and no cursor; the eager boot redrive paginates with a cursor- /// to drain the whole outbox (mirrors [`Self::scan_stage1`] / [`Self::scan_merge_cf`]).+ /// to drain the whole outbox (mirrors [`Self::scan_behavioral`] / [`Self::scan_merge_cf`]).pub fn scan_pending_transfers(&self,partition_id: u16,@@ -456,11 +627,16 @@ impl CohortStore {Ok(out)}- /// Reclaim all state for one partition on rebalance.+ /// Reclaim all state for one partition on rebalance. Non-partitioned CFs (`cf_meta`) are skipped:+ /// their short literal keys collide with an arbitrary partition's byte range, so a range delete+ /// would wipe store-wide guards like the schema stamp.pub fn delete_partition(&self, partition_id: u16) -> Result<(), StoreError> {let (start, end) = keys::partition_range(partition_id);let mut batch = WriteBatch::default();for cf in Cf::ALL {+ if !cf.partitioned() {+ continue;+ }let handle = self.cf(cf)?;batch.delete_range_cf(handle, start.as_slice(), end.as_slice());}@@ -469,15 +645,10 @@ impl CohortStore {/// Flush all CF memtables to SST. Checkpoint path and tests only.pub fn flush(&self) -> Result<(), StoreError> {- let handles = [- self.cf(Cf::Stage1)?,- self.cf(Cf::PersonIndex)?,- self.cf(Cf::Stage2)?,- self.cf(Cf::MergeDrainsApplied)?,- self.cf(Cf::PendingTransfers)?,- self.cf(Cf::MergeApplied)?,- self.cf(Cf::MergeTombstones)?,- ];+ let handles: Vec<&ColumnFamily> = Cf::ALL+ .iter()+ .map(|&cf| self.cf(cf))+ .collect::<Result<_, _>>()?;let mut flush_opts = FlushOptions::default();flush_opts.set_wait(true);self.db@@ -525,18 +696,23 @@ impl CohortStore {})}- /// Scan up to `limit` of one partition's `cf_stage1` slice as `(Stage1Key, raw_value)` in key- /// order, resuming strictly after `start_after` when given. The value stays raw so the caller+ /// Scan up to `limit` of one partition's `cf_behavioral` slice as `(BehavioralKey, raw_value)` in+ /// key order, resuming strictly after `start_after` when given. The value stays raw so the caller/// decodes the [`StatefulRecord`](crate::stage1::StatefulRecord) (and owns the decode-error metric)/// and the resume cursor is the last scanned key.- pub fn scan_stage1(+ ///+ /// This is a partition-wide scan that crosses many 26-byte person prefixes. `cf_behavioral` has a+ /// fixed-prefix extractor, so the iterator defaults to prefix-seek mode and would silently stop at+ /// the first person boundary; `set_total_order_seek(true)` forces a full-order iteration across all+ /// prefixes.+ pub fn scan_behavioral(&self,partition_id: u16,start_after: Option<&[u8]>,limit: usize,- ) -> Result<Vec<(Stage1Key, Vec<u8>)>, StoreError> {+ ) -> Result<Vec<(BehavioralKey, Vec<u8>)>, StoreError> {let (prefix_start, prefix_end) = keys::partition_range(partition_id);- let handle = self.cf(Cf::Stage1)?;+ let handle = self.cf(Cf::Behavioral)?;// Resume after the cursor when it falls inside this partition, else at the prefix start.let begin: Vec<u8> = match start_after {@@ -548,6 +724,7 @@ impl CohortStore {let mut read_opts = ReadOptions::default();read_opts.set_iterate_upper_bound(prefix_end);+ read_opts.set_total_order_seek(true);let iter = self.db.iterator_cf_opt(handle,read_opts,@@ -566,7 +743,42 @@ impl CohortStore {source,}})?;- out.push((Stage1Key::decode(&key_bytes)?, value.to_vec()));+ out.push((BehavioralKey::decode(&key_bytes)?, value.to_vec()));+ }+ Ok(out)+ }++ /// Scan one person's whole `cf_behavioral` slice as `(BehavioralKey, raw_value)` in lsk order.+ ///+ /// Bounded to the person's 26-byte prefix by both the iterate-upper-bound (the prefix successor)+ /// and `set_prefix_same_as_start(true)`, which pins the iterator to the seek key's prefix so it can+ /// never leak into an adjacent person's rows. Used by the merge drain to enumerate P_old's leaves.+ pub fn scan_behavioral_prefix(+ &self,+ prefix: PersonPrefix,+ ) -> Result<Vec<(BehavioralKey, Vec<u8>)>, StoreError> {+ let (start, end) = prefix.scan_range();+ let handle = self.cf(Cf::Behavioral)?;++ let mut read_opts = ReadOptions::default();+ read_opts.set_iterate_upper_bound(end);+ read_opts.set_prefix_same_as_start(true);+ let iter = self.db.iterator_cf_opt(+ handle,+ read_opts,+ IteratorMode::From(&start, Direction::Forward),+ );++ let mut out = Vec::new();+ for item in iter {+ let (key_bytes, value) = item.map_err(|source| {+ counter!(STORE_ERRORS_TOTAL, "op" => OP_SCAN).increment(1);+ StoreError::Backend {+ op: OP_SCAN,+ source,+ }+ })?;+ out.push((BehavioralKey::decode(&key_bytes)?, value.to_vec()));}Ok(out)}@@ -588,7 +800,7 @@ impl CohortStore {bloom_filter_useful: ticker(Ticker::BloomFilterUseful),// The block cache is shared across every CF, so any CF handle reports the same usage.block_cache_usage_bytes: self- .cf_property_u64(Cf::Stage1, properties::BLOCK_CACHE_USAGE),+ .cf_property_u64(Cf::Behavioral, properties::BLOCK_CACHE_USAGE),per_cf: Cf::ALL.iter().map(|&cf| CfStats {@@ -672,36 +884,65 @@ pub struct CfStats {pub num_keys: u64,}+/// The raw bytes of one event's state snapshot from a single mixed-CF `multi_get`, produced by+/// [`CohortStore::read_event_snapshot`]. Decoding lives with the caller.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct EventSnapshotRaw {+ /// One slot per requested behavioral key, in request order; `None` = absent row.+ pub behavioral: Vec<Option<Vec<u8>>>,+ /// The person-record slot: outer `None` = no record key was requested; `Some(None)` = requested+ /// but absent; `Some(Some(bytes))` = present.+ pub record: Option<Option<Vec<u8>>>,+}+/// Typed builder for a multi-CF [`WriteBatch`].pub struct BatchBuilder<'db> {batch: WriteBatch,- stage1: &'db ColumnFamily,- person_index: &'db ColumnFamily,+ behavioral: &'db ColumnFamily,+ person_records: &'db ColumnFamily,stage2: &'db ColumnFamily,merge_drains_applied: &'db ColumnFamily,pending_transfers: &'db ColumnFamily,merge_applied: &'db ColumnFamily,merge_tombstones: &'db ColumnFamily,+ meta: &'db ColumnFamily,}-impl BatchBuilder<'_> {- pub fn put_stage1(&mut self, key: &Stage1Key, value: &[u8]) {- self.batch.put_cf(self.stage1, key.encode(), value);+impl<'db> BatchBuilder<'db> {+ /// The held handle for one CF, returned at the store's `'db` lifetime rather than `&self` so it+ /// does not alias the `&mut self.batch` callers immediately take.+ fn handle(&self, cf: Cf) -> &'db ColumnFamily {+ match cf {+ Cf::Behavioral => self.behavioral,+ Cf::PersonRecords => self.person_records,+ Cf::Stage2 => self.stage2,+ Cf::MergeDrainsApplied => self.merge_drains_applied,+ Cf::PendingTransfers => self.pending_transfers,+ Cf::MergeApplied => self.merge_applied,+ Cf::MergeTombstones => self.merge_tombstones,+ Cf::Meta => self.meta,+ }}- pub fn delete_stage1(&mut self, key: &Stage1Key) {- self.batch.delete_cf(self.stage1, key.encode());+ /// Put a typed key/value into its keyspace's CF. The [`Keyspace`] binding routes to the right CF,+ /// so a key cannot be written to the wrong column family.+ pub fn put<K: Keyspace>(&mut self, key: &K::Key, value: &[u8]) {+ let handle = self.handle(K::CF);+ self.batch.put_cf(handle, K::encode(key), value);}- /// Read-free append/remove on the person's index.- pub fn merge_person_index(&mut self, key: &PersonIndexKey, op: IndexOp) {- self.batch- .merge_cf(self.person_index, key.encode(), op.encode());+ /// Delete a typed key from its keyspace's CF.+ pub fn delete<K: Keyspace>(&mut self, key: &K::Key) {+ let handle = self.handle(K::CF);+ self.batch.delete_cf(handle, K::encode(key));}- /// Whole-key delete of a person's index entry.- pub fn delete_person_index(&mut self, key: &PersonIndexKey) {- self.batch.delete_cf(self.person_index, key.encode());+ /// Range-delete one person's whole `cf_behavioral` slice in a single tombstone, reclaiming every+ /// leaf under the person prefix at once (used when a merge drains P_old's state).+ pub fn delete_behavioral_prefix(&mut self, prefix: &PersonPrefix) {+ let (start, end) = prefix.scan_range();+ self.batch+ .delete_range_cf(self.behavioral, start.as_slice(), end.as_slice());}pub fn put_stage2(&mut self, key: &Stage2Key, value: &[u8]) {@@ -758,11 +999,7 @@ impl BatchBuilder<'_> {/// Raw put by pre-encoded key bytes. Restricted to [`OpaqueCf`].pub fn put_raw(&mut self, cf: OpaqueCf, key: &[u8], value: &[u8]) {- let handle = match cf {- OpaqueCf::Stage1 => self.stage1,- OpaqueCf::Stage2 => self.stage2,- };- self.batch.put_cf(handle, key, value);+ self.batch.put_cf(self.handle(cf.cf()), key, value);}}@@ -797,6 +1034,25 @@ fn successor(key: &[u8]) -> Vec<u8> {next}+/// Outcome of the open-time schema-version check.+enum SchemaCheck {+ /// The stamp matched (or a fresh store was just stamped).+ Ok,+ /// A mismatch under `wipe_on_schema_mismatch`: the caller destroys and reopens fresh.+ WipeAndRetry,+}++/// Destroy the store at `path`, counting a metric on failure. Requires no open handle.+fn destroy_db(db_opts: &Options, path: &Path) -> Result<(), StoreError> {+ DBWithThreadMode::<SingleThreaded>::destroy(db_opts, path).map_err(|source| {+ counter!(STORE_ERRORS_TOTAL, "op" => OP_DESTROY).increment(1);+ StoreError::Open {+ path: path.to_path_buf(),+ source,+ }+ })+}+fn db_options(config: &StoreConfig) -> Options {let mut opts = Options::default();opts.create_if_missing(config.create_if_missing);@@ -823,20 +1079,22 @@ mod tests {use tempfile::TempDir;use uuid::Uuid;- fn stage1_key() -> Stage1Key {- Stage1Key {- partition_id: 3,- team_id: 7,- leaf_state_key: LeafStateKey([0xAB; 16]),- person_id: Uuid::from_u128(1),- }+ use super::super::keyspace::{Behavioral, PersonRecords};+ use crate::stage1::key::LeafStateKey;++ fn behavioral_key() -> BehavioralKey {+ BehavioralKey::new(3, 7, Uuid::from_u128(1), LeafStateKey([0xAB; 16]))+ }++ fn record_key(partition: u16, person: u128) -> PersonRecordKey {+ PersonRecordKey::new(partition, 7, Uuid::from_u128(person))}#[test]fn wipe_on_start_clears_existing_state_and_is_a_noop_when_off() {let dir = TempDir::new().unwrap();let path = dir.path().join("db");- let key = stage1_key();+ let key = behavioral_key();// Seed a value, then close the database (drop the only handle).{@@ -845,9 +1103,11 @@ mod tests {..StoreConfig::default()}).unwrap();- store.write_batch(|b| b.put_stage1(&key, b"state")).unwrap();+ store+ .write_batch(|b| b.put::<Behavioral>(&key, b"state"))+ .unwrap();assert_eq!(- store.get_stage1(&key).unwrap().as_deref(),+ store.get_behavioral(&key).unwrap().as_deref(),Some(b"state".as_slice()),);}@@ -861,7 +1121,7 @@ mod tests {}).unwrap();assert_eq!(- store.get_stage1(&key).unwrap().as_deref(),+ store.get_behavioral(&key).unwrap().as_deref(),Some(b"state".as_slice()),);}@@ -874,7 +1134,7 @@ mod tests {..StoreConfig::default()}).unwrap();- assert_eq!(store.get_stage1(&key).unwrap(), None);+ assert_eq!(store.get_behavioral(&key).unwrap(), None);}}@@ -887,11 +1147,101 @@ mod tests {..StoreConfig::default()}).unwrap();- assert_eq!(store.get_stage1(&stage1_key()).unwrap(), None);+ assert_eq!(store.get_behavioral(&behavioral_key()).unwrap(), None);+ }++ #[test]+ fn fresh_store_stamps_the_schema_version_and_a_reopen_matches() {+ let dir = TempDir::new().unwrap();+ let path = dir.path().join("db");+ {+ let store = CohortStore::open(&StoreConfig {+ path: path.clone(),+ ..StoreConfig::default()+ })+ .unwrap();+ assert_eq!(+ store+ .get(Cf::Meta, META_SCHEMA_VERSION.0)+ .unwrap()+ .as_deref(),+ Some(STORE_SCHEMA_VERSION.to_be_bytes().as_slice()),+ "a fresh store stamps the current schema version",+ );+ }+ // A reopen matches the stamp and opens cleanly.+ CohortStore::open(&StoreConfig {+ path,+ wipe_on_start: false,+ ..StoreConfig::default()+ })+ .unwrap();+ }++ #[test]+ fn a_version_mismatch_fails_typed_and_the_wipe_flag_recreates_empty() {+ let dir = TempDir::new().unwrap();+ let path = dir.path().join("db");+ let key = behavioral_key();++ // Seed a store and corrupt its stamp to a bogus version.+ {+ let store = CohortStore::open(&StoreConfig {+ path: path.clone(),+ ..StoreConfig::default()+ })+ .unwrap();+ store+ .write_batch(|b| b.put::<Behavioral>(&key, b"state"))+ .unwrap();+ store+ .write_batch(|b| b.put::<Meta>(&META_SCHEMA_VERSION, &999u32.to_be_bytes()))+ .unwrap();+ }++ // Without the wipe flag, a mismatch is a typed hard error and the store is untouched.+ // (`CohortStore` is not `Debug`, so match the `Result` rather than `unwrap_err`.)+ let result = CohortStore::open(&StoreConfig {+ path: path.clone(),+ wipe_on_start: false,+ ..StoreConfig::default()+ });+ assert!(+ matches!(+ result,+ Err(StoreError::SchemaMismatch {+ found: Some(999),+ expected,+ }) if expected == STORE_SCHEMA_VERSION+ ),+ "expected a typed schema mismatch",+ );++ // With the wipe flag, the store is destroyed, recreated, and re-stamped — the old row is gone.+ let store = CohortStore::open(&StoreConfig {+ path,+ wipe_on_start: false,+ wipe_on_schema_mismatch: true,+ ..StoreConfig::default()+ })+ .unwrap();+ assert_eq!(+ store.get_behavioral(&key).unwrap(),+ None,+ "wipe-on-mismatch recreates an empty store",+ );+ assert_eq!(+ store+ .get(Cf::Meta, META_SCHEMA_VERSION.0)+ .unwrap()+ .as_deref(),+ Some(STORE_SCHEMA_VERSION.to_be_bytes().as_slice()),+ "the recreated store is re-stamped with the current version",+ );}#[test]- fn multi_get_stage1_preserves_order_and_reports_absent_keys() {+ fn multi_get_behavioral_preserves_order_and_reports_absent_keys() {let dir = TempDir::new().unwrap();let store = CohortStore::open(&StoreConfig {path: dir.path().join("db"),@@ -899,36 +1249,147 @@ mod tests {}).unwrap();- let present = |person: u128, lsk: u8| Stage1Key {- partition_id: 3,- team_id: 7,- leaf_state_key: LeafStateKey([lsk; 16]),- person_id: Uuid::from_u128(person),+ let present = |person: u128, lsk: u8| {+ BehavioralKey::new(3, 7, Uuid::from_u128(person), LeafStateKey([lsk; 16]))};let a = present(1, 0xA0);let b = present(2, 0xB0);let absent = present(9, 0xFF);store.write_batch(|batch| {- batch.put_stage1(&a, b"alpha");- batch.put_stage1(&b, b"bravo");+ batch.put::<Behavioral>(&a, b"alpha");+ batch.put::<Behavioral>(&b, b"bravo");}).unwrap();// Order: present, absent, present — the absent key must surface as a `None` hole, not shift// the others.- let results = store.multi_get_stage1(&[a, absent, b]).unwrap();+ let results = store.multi_get_behavioral(&[a, absent, b]).unwrap();assert_eq!(results.len(), 3);assert_eq!(results[0].as_deref(), Some(b"alpha".as_slice()));assert_eq!(results[1], None);assert_eq!(results[2].as_deref(), Some(b"bravo".as_slice()));assert!(- store.multi_get_stage1(&[]).unwrap().is_empty(),+ store.multi_get_behavioral(&[]).unwrap().is_empty(),"an empty key set reads no values",);}+ #[test]+ fn person_record_get_round_trips_through_its_cf() {+ let dir = TempDir::new().unwrap();+ let store = CohortStore::open(&StoreConfig {+ path: dir.path().join("db"),+ ..StoreConfig::default()+ })+ .unwrap();+ let key = record_key(3, 1);+ assert_eq!(+ store.get_person_record(&key).unwrap(),+ None,+ "absent before write"+ );+ store+ .write_batch(|b| b.put::<PersonRecords>(&key, b"record-bytes"))+ .unwrap();+ assert_eq!(+ store.get_person_record(&key).unwrap().as_deref(),+ Some(b"record-bytes".as_slice()),+ );+ }++ #[test]+ fn read_event_snapshot_aligns_behavioral_hits_misses_and_the_record_slot() {+ let dir = TempDir::new().unwrap();+ let store = CohortStore::open(&StoreConfig {+ path: dir.path().join("db"),+ ..StoreConfig::default()+ })+ .unwrap();++ let b = |person: u128, lsk: u8| {+ BehavioralKey::new(3, 7, Uuid::from_u128(person), LeafStateKey([lsk; 16]))+ };+ let present_a = b(1, 0xA0);+ let present_b = b(1, 0xB0);+ let absent = b(9, 0xFF);+ let record = record_key(3, 1);+ store+ .write_batch(|batch| {+ batch.put::<Behavioral>(&present_a, b"alpha");+ batch.put::<Behavioral>(&present_b, b"bravo");+ batch.put::<PersonRecords>(&record, b"rec");+ })+ .unwrap();++ // Behavioral order present/absent/present, plus the record present.+ let snap = store+ .read_event_snapshot(&[present_a, absent, present_b], Some(&record))+ .unwrap();+ assert_eq!(snap.behavioral.len(), 3);+ assert_eq!(snap.behavioral[0].as_deref(), Some(b"alpha".as_slice()));+ assert_eq!(+ snap.behavioral[1], None,+ "the absent behavioral key is a hole"+ );+ assert_eq!(snap.behavioral[2].as_deref(), Some(b"bravo".as_slice()));+ assert_eq!(snap.record, Some(Some(b"rec".to_vec())), "record present");++ // Record requested but absent ⇒ Some(None); behavioral all present.+ let absent_record = record_key(3, 999);+ let snap = store+ .read_event_snapshot(&[present_a], Some(&absent_record))+ .unwrap();+ assert_eq!(snap.behavioral.len(), 1);+ assert_eq!(snap.record, Some(None), "requested but absent record");++ // Record not requested ⇒ outer None; behavioral only.+ let snap = store.read_event_snapshot(&[present_a], None).unwrap();+ assert_eq!(snap.behavioral.len(), 1);+ assert_eq!(snap.record, None, "no record key requested");++ // Record-only (empty behavioral).+ let snap = store.read_event_snapshot(&[], Some(&record)).unwrap();+ assert!(snap.behavioral.is_empty());+ assert_eq!(snap.record, Some(Some(b"rec".to_vec())));++ // Empty both ⇒ no read, empty result.+ let snap = store.read_event_snapshot(&[], None).unwrap();+ assert!(snap.behavioral.is_empty());+ assert_eq!(snap.record, None);+ }++ #[test]+ fn delete_partition_wipes_person_records_for_that_partition_only() {+ let dir = TempDir::new().unwrap();+ let store = CohortStore::open(&StoreConfig {+ path: dir.path().join("db"),+ ..StoreConfig::default()+ })+ .unwrap();+ let victim = record_key(5, 1);+ let survivor = record_key(6, 1);+ store+ .write_batch(|batch| {+ batch.put::<PersonRecords>(&victim, b"v");+ batch.put::<PersonRecords>(&survivor, b"s");+ })+ .unwrap();++ store.delete_partition(5).unwrap();+ assert_eq!(+ store.get_person_record(&victim).unwrap(),+ None,+ "partition 5's record is reclaimed",+ );+ assert_eq!(+ store.get_person_record(&survivor).unwrap().as_deref(),+ Some(b"s".as_slice()),+ "partition 6's record is untouched",+ );+ }+#[test]fn multi_get_stage2_preserves_order_and_reports_absent_keys() {let dir = TempDir::new().unwrap();@@ -1044,7 +1505,7 @@ mod tests {fn flush_wal_sync_succeeds_and_persists_writes_across_a_reopen() {let dir = TempDir::new().unwrap();let path = dir.path().join("db");- let key = stage1_key();+ let key = behavioral_key();{let store = CohortStore::open(&StoreConfig {path: path.clone(),@@ -1052,7 +1513,7 @@ mod tests {}).unwrap();store- .write_batch(|b| b.put_stage1(&key, b"durable"))+ .write_batch(|b| b.put::<Behavioral>(&key, b"durable")).unwrap();store.flush_wal_sync().unwrap();// A second fsync with nothing new pending is a no-op, not an error.@@ -1065,7 +1526,7 @@ mod tests {}).unwrap();assert_eq!(- reopened.get_stage1(&key).unwrap().as_deref(),+ reopened.get_behavioral(&key).unwrap().as_deref(),Some(b"durable".as_slice()),);}@@ -1076,7 +1537,7 @@ mod tests {let path = dir.path().join("db");// The checkpoint must be a sibling of the store path, never a child (RocksDB hard-links SSTs).let checkpoint = dir.path().join("checkpoint");- let key = stage1_key();+ let key = behavioral_key();let store = CohortStore::open(&StoreConfig {path,@@ -1084,7 +1545,7 @@ mod tests {}).unwrap();store- .write_batch(|b| b.put_stage1(&key, b"snapshot"))+ .write_batch(|b| b.put::<Behavioral>(&key, b"snapshot")).unwrap();store.create_checkpoint(&checkpoint).unwrap();@@ -1095,7 +1556,7 @@ mod tests {}).unwrap();assert_eq!(- restored.get_stage1(&key).unwrap().as_deref(),+ restored.get_behavioral(&key).unwrap().as_deref(),Some(b"snapshot".as_slice()),);}@@ -1110,9 +1571,9 @@ mod tests {..StoreConfig::default()}).unwrap();- let key = stage1_key();+ let key = behavioral_key();store- .write_batch(|b| b.put_stage1(&key, b"snapshot"))+ .write_batch(|b| b.put::<Behavioral>(&key, b"snapshot")).unwrap();// Parent exists, leaf does not — the correct usage.@@ -1128,7 +1589,7 @@ mod tests {}).unwrap();assert_eq!(- restored.get_stage1(&key).unwrap().as_deref(),+ restored.get_behavioral(&key).unwrap().as_deref(),Some(b"snapshot".as_slice()),);}@@ -1153,7 +1614,7 @@ mod tests {}#[test]- fn scan_stage1_resumes_after_the_cursor_and_honors_the_limit_and_partition_bounds() {+ fn scan_behavioral_resumes_after_the_cursor_and_honors_the_limit_and_partition_bounds() {let dir = TempDir::new().unwrap();let store = CohortStore::open(&StoreConfig {path: dir.path().join("db"),@@ -1161,66 +1622,74 @@ mod tests {}).unwrap();- let key = |partition_id: u16, person: u128| Stage1Key {- partition_id,- team_id: 7,- leaf_state_key: LeafStateKey([0xAB; 16]),- person_id: Uuid::from_u128(person),+ let key = |partition_id: u16, person: u128| {+ BehavioralKey::new(+ partition_id,+ 7,+ Uuid::from_u128(person),+ LeafStateKey([0xAB; 16]),+ )};// Three keys in partition 5, one in partition 6 (must never surface for a p=5 scan).store.write_batch(|batch| {for person in 1..=3u128 {- batch.put_stage1(&key(5, person), format!("v{person}").as_bytes());+ batch.put::<Behavioral>(&key(5, person), format!("v{person}").as_bytes());}- batch.put_stage1(&key(6, 9), b"other-partition");+ batch.put::<Behavioral>(&key(6, 9), b"other-partition");}).unwrap();- let page1 = store.scan_stage1(5, None, 2).unwrap();+ let page1 = store.scan_behavioral(5, None, 2).unwrap();assert_eq!(page1.len(), 2);assert_eq!(page1[0].0, key(5, 1));assert_eq!(page1[0].1, b"v1");assert_eq!(page1[1].0, key(5, 2));let cursor = page1.last().unwrap().0.encode();- let page2 = store.scan_stage1(5, Some(&cursor), 10).unwrap();+ let page2 = store.scan_behavioral(5, Some(&cursor), 10).unwrap();assert_eq!(page2.len(), 1, "only the remaining partition-5 key");assert_eq!(page2[0].0, key(5, 3));// A cursor at the partition's last key is exhausted.let last = page2.last().unwrap().0.encode();- assert!(store.scan_stage1(5, Some(&last), 10).unwrap().is_empty());+ assert!(store+ .scan_behavioral(5, Some(&last), 10)+ .unwrap()+ .is_empty());assert!(- store.scan_stage1(9, None, 10).unwrap().is_empty(),+ store.scan_behavioral(9, None, 10).unwrap().is_empty(),"empty partition");}- fn stage1_key_for(partition_id: u16, person: u128) -> Stage1Key {- Stage1Key {+ fn behavioral_key_for(partition_id: u16, person: u128) -> BehavioralKey {+ BehavioralKey::new(partition_id,- team_id: 7,- leaf_state_key: LeafStateKey([0xAB; 16]),- person_id: Uuid::from_u128(person),- }+ 7,+ Uuid::from_u128(person),+ LeafStateKey([0xAB; 16]),+ )}/// Five partition-5 keys plus one partition-6 key a partition-5 scan must never surface.fn seed_p5_and_one_p6(batch: &mut BatchBuilder<'_>) {for person in 1..=5u128 {- batch.put_stage1(&stage1_key_for(5, person), format!("v{person}").as_bytes());+ batch.put::<Behavioral>(+ &behavioral_key_for(5, person),+ format!("v{person}").as_bytes(),+ );}- batch.put_stage1(&stage1_key_for(6, 9), b"other-partition");+ batch.put::<Behavioral>(&behavioral_key_for(6, 9), b"other-partition");}/// Flushes to SST so the scan hits on-disk index/filter blocks, not the memtable.fn flushed_p5_scan(config: &StoreConfig,seed: impl FnOnce(&mut BatchBuilder<'_>),- ) -> Vec<(Stage1Key, Vec<u8>)> {+ ) -> Vec<(BehavioralKey, Vec<u8>)> {let store = CohortStore::open(config).unwrap();store.write_batch(seed).unwrap();store.flush().unwrap();@@ -1228,7 +1697,7 @@ mod tests {let mut out = Vec::new();let mut cursor: Option<Vec<u8>> = None;loop {- let page = store.scan_stage1(5, cursor.as_deref(), 2).unwrap();+ let page = store.scan_behavioral(5, cursor.as_deref(), 2).unwrap();let Some((last_key, _)) = page.last() else {break;};@@ -1238,6 +1707,124 @@ mod tests {out}+ /// Seeds several persons × several leaves in one partition plus neighbours in adjacent partitions,+ /// flushes to SST (so iteration hits on-disk prefix blocks, not the memtable where truncation is+ /// masked), and returns the store.+ fn seed_multi_person_flushed() -> (TempDir, CohortStore) {+ let dir = TempDir::new().unwrap();+ let store = CohortStore::open(&StoreConfig {+ path: dir.path().join("db"),+ tuned_block_options: true,+ ..StoreConfig::default()+ })+ .unwrap();+ store+ .write_batch(|batch| {+ for person in 1..=4u128 {+ for leaf in 0..3u8 {+ let key = BehavioralKey::new(+ 5,+ 7,+ Uuid::from_u128(person),+ LeafStateKey([leaf; 16]),+ );+ batch.put::<Behavioral>(&key, b"v");+ }+ }+ // Neighbours in adjacent partitions the partition-5 scan must never surface.+ batch.put::<Behavioral>(&behavioral_key_for(4, 99), b"prev-partition");+ batch.put::<Behavioral>(&behavioral_key_for(6, 99), b"next-partition");+ })+ .unwrap();+ store.flush().unwrap();+ (dir, store)+ }++ #[test]+ fn scan_behavioral_crosses_every_person_prefix_in_the_partition() {+ // The regression this pins: with the fixed-prefix extractor in place, a partition-wide scan+ // must set total-order seek or it truncates at the first person's prefix boundary.+ let (_dir, store) = seed_multi_person_flushed();++ let mut all = Vec::new();+ let mut cursor: Option<Vec<u8>> = None;+ loop {+ let page = store.scan_behavioral(5, cursor.as_deref(), 2).unwrap();+ let Some((last, _)) = page.last() else {+ break;+ };+ cursor = Some(last.encode().to_vec());+ all.extend(page);+ }++ assert_eq!(+ all.len(),+ 12,+ "4 persons × 3 leaves, crossing every person prefix"+ );+ let persons: std::collections::BTreeSet<u128> =+ all.iter().map(|(k, _)| k.person_id().as_u128()).collect();+ assert_eq!(+ persons,+ [1, 2, 3, 4].into_iter().collect(),+ "the scan reaches all four persons, not just the first prefix",+ );+ assert!(+ all.iter().all(|(k, _)| k.partition_id() == 5),+ "the adjacent-partition neighbours are excluded by the upper bound",+ );+ }++ #[test]+ fn scan_behavioral_prefix_returns_exactly_one_persons_leaves_in_lsk_order() {+ let (_dir, store) = seed_multi_person_flushed();+ let prefix = PersonPrefix::new(5, 7, Uuid::from_u128(2));++ let rows = store.scan_behavioral_prefix(prefix).unwrap();+ assert_eq!(rows.len(), 3, "only person 2's three leaves");+ assert!(+ rows.iter()+ .all(|(k, _)| k.person_id() == Uuid::from_u128(2)),+ "the scan never leaks past the 26-byte person prefix",+ );+ let lsks: Vec<[u8; 16]> = rows.iter().map(|(k, _)| k.lsk().0).collect();+ let mut sorted = lsks.clone();+ sorted.sort();+ assert_eq!(lsks, sorted, "leaves come back in lsk-byte order");+ }++ #[test]+ fn delete_partition_wipes_partitioned_cfs_but_preserves_the_schema_stamp() {+ let dir = TempDir::new().unwrap();+ let store = CohortStore::open(&StoreConfig {+ path: dir.path().join("db"),+ ..StoreConfig::default()+ })+ .unwrap();++ let key = behavioral_key_for(5, 1);+ store+ .write_batch(|b| b.put::<Behavioral>(&key, b"state"))+ .unwrap();+ assert!(store.get_behavioral(&key).unwrap().is_some());++ store.delete_partition(5).unwrap();++ assert_eq!(+ store.get_behavioral(&key).unwrap(),+ None,+ "the partition's behavioral rows are reclaimed",+ );+ assert_eq!(+ store+ .get(Cf::Meta, META_SCHEMA_VERSION.0)+ .unwrap()+ .as_deref(),+ Some(STORE_SCHEMA_VERSION.to_be_bytes().as_slice()),+ "cf_meta is exempt from the partition wipe, so the schema guard survives a rebalance",+ );+ }+#[test]fn tuned_block_options_preserve_scan_semantics_across_flushed_ssts() {// Partitioned filters + two-level index change SST metadata layout only, not scan order.@@ -1289,7 +1876,7 @@ mod tests {store.write_batch(|batch| {for person in 1..=10u128 {- batch.put_stage1(&stage1_key_for(5, person), b"v");+ batch.put::<Behavioral>(&behavioral_key_for(5, person), b"v");}}).unwrap();@@ -1299,7 +1886,7 @@ mod tests {store.write_batch(|batch| {for person in (2..=10u128).step_by(2) {- batch.delete_stage1(&stage1_key_for(5, person));+ batch.delete::<Behavioral>(&behavioral_key_for(5, person));}}).unwrap();@@ -1307,19 +1894,21 @@ mod tests {// Force a physical compaction so the tombstones actually rewrite the SSTs, exercising the// compaction path instead of only the read-time merge iterator.- store- .db- .compact_range_cf(store.cf(Cf::Stage1).unwrap(), None::<&[u8]>, None::<&[u8]>);+ store.db.compact_range_cf(+ store.cf(Cf::Behavioral).unwrap(),+ None::<&[u8]>,+ None::<&[u8]>,+ );let mut survivors = Vec::new();let mut cursor: Option<Vec<u8>> = None;loop {- let page = store.scan_stage1(5, cursor.as_deref(), 3).unwrap();+ let page = store.scan_behavioral(5, cursor.as_deref(), 3).unwrap();let Some((last_key, _)) = page.last() else {break;};cursor = Some(last_key.encode().to_vec());- survivors.extend(page.iter().map(|(key, _)| key.person_id.as_u128()));+ survivors.extend(page.iter().map(|(key, _)| key.person_id().as_u128()));}assert_eq!(survivors,@@ -1328,6 +1917,122 @@ mod tests {);}+ #[test]+ fn person_record_ttl_drops_ancient_keeps_fresh_and_malformed_and_never_touches_behavioral() {+ use crate::stage1::person_record::{PersonRecord, Stamp};+ use chrono::Utc;++ // A 30-day TTL against a fixed enough gap: `last_seen_ms = 0` is ~epoch, far older than any+ // real `now - 30d`, so it is ancient; a `last_seen_ms` at `now` is fresh.+ let now_ms = Utc::now().timestamp_millis();+ let fresh_ms = now_ms;+ let ancient_ms = 0;++ let dir = TempDir::new().unwrap();+ let store = CohortStore::open(&StoreConfig {+ path: dir.path().join("db"),+ person_record_ttl_days: 30,+ compact_on_deletion: false,+ ..StoreConfig::default()+ })+ .unwrap();++ let record_bytes = |last_seen_ms: i64| {+ let mut record = PersonRecord::absent();+ record.last_seen_ms = last_seen_ms;+ record.stamp = Stamp::new(last_seen_ms, 0);+ record.encode()+ };++ let ancient_key = record_key(5, 1);+ let fresh_key = record_key(5, 2);+ // A malformed person-record value: the keyspace treats the value as opaque, so a raw put of+ // garbage bytes seeds a row the codec cannot decode.+ let malformed_key = record_key(5, 3);+ let malformed_value = b"not a person record";+ // An ancient behavioral row: the sweep owns its eviction, so the TTL filter must never touch it.+ let behavioral_key = BehavioralKey::new(5, 7, Uuid::from_u128(4), LeafStateKey([0xCD; 16]));++ store+ .write_batch(|b| {+ b.put::<PersonRecords>(&ancient_key, &record_bytes(ancient_ms));+ b.put::<PersonRecords>(&fresh_key, &record_bytes(fresh_ms));+ b.put::<PersonRecords>(&malformed_key, malformed_value);+ b.put::<Behavioral>(&behavioral_key, &record_bytes(ancient_ms));+ })+ .unwrap();+ store.flush().unwrap();++ // Force a physical compaction of both CFs so the filter actually runs over the SSTs.+ store.db.compact_range_cf(+ store.cf(Cf::PersonRecords).unwrap(),+ None::<&[u8]>,+ None::<&[u8]>,+ );+ store.db.compact_range_cf(+ store.cf(Cf::Behavioral).unwrap(),+ None::<&[u8]>,+ None::<&[u8]>,+ );++ assert_eq!(+ store.get_person_record(&ancient_key).unwrap(),+ None,+ "a record older than the TTL is dropped by compaction",+ );+ assert_eq!(+ store.get_person_record(&fresh_key).unwrap().as_deref(),+ Some(record_bytes(fresh_ms).as_slice()),+ "a record newer than the TTL survives",+ );+ assert_eq!(+ store.get_person_record(&malformed_key).unwrap().as_deref(),+ Some(malformed_value.as_slice()),+ "a malformed value is never TTL-dropped — it surfaces as a read-time decode error instead",+ );+ assert_eq!(+ store.get_behavioral(&behavioral_key).unwrap().as_deref(),+ Some(record_bytes(ancient_ms).as_slice()),+ "an ancient behavioral row is untouched: the TTL filter attaches to cf_person_records only",+ );+ }++ #[test]+ fn person_record_ttl_zero_installs_no_filter_so_ancient_records_survive() {+ use crate::stage1::person_record::{PersonRecord, Stamp};++ let dir = TempDir::new().unwrap();+ let store = CohortStore::open(&StoreConfig {+ path: dir.path().join("db"),+ person_record_ttl_days: 0, // default: no compaction filter+ compact_on_deletion: false,+ ..StoreConfig::default()+ })+ .unwrap();++ let key = record_key(5, 1);+ let mut record = PersonRecord::absent();+ record.last_seen_ms = 0; // epoch-ancient+ record.stamp = Stamp::new(0, 0);+ let encoded = record.encode();++ store+ .write_batch(|b| b.put::<PersonRecords>(&key, &encoded))+ .unwrap();+ store.flush().unwrap();+ store.db.compact_range_cf(+ store.cf(Cf::PersonRecords).unwrap(),+ None::<&[u8]>,+ None::<&[u8]>,+ );++ assert_eq!(+ store.get_person_record(&key).unwrap().as_deref(),+ Some(encoded.as_slice()),+ "with TTL=0 no filter is installed, so even an ancient record survives compaction",+ );+ }+#[test]fn stats_snapshot_reports_keys_and_cache_activity_after_reads() {let dir = TempDir::new().unwrap();@@ -1338,16 +2043,13 @@ mod tests {}).unwrap();- let key = |person: u128| Stage1Key {- partition_id: 3,- team_id: 7,- leaf_state_key: LeafStateKey([0xAB; 16]),- person_id: Uuid::from_u128(person),+ let key = |person: u128| {+ BehavioralKey::new(3, 7, Uuid::from_u128(person), LeafStateKey([0xAB; 16]))};store.write_batch(|batch| {for person in 1..=8u128 {- batch.put_stage1(&key(person), b"state");+ batch.put::<Behavioral>(&key(person), b"state");}}).unwrap();@@ -1355,7 +2057,7 @@ mod tests {store.flush().unwrap();for person in 1..=8u128 {- assert!(store.get_stage1(&key(person)).unwrap().is_some());+ assert!(store.get_behavioral(&key(person)).unwrap().is_some());}let stats = store.stats_snapshot();@@ -1364,16 +2066,19 @@ mod tests {Cf::ALL.len(),"one CfStats entry per column family",);- let stage1 = stats+ let behavioral = stats.per_cf.iter()- .find(|cf| cf.cf == Cf::Stage1)- .expect("Stage1 CF present in the snapshot");+ .find(|cf| cf.cf == Cf::Behavioral)+ .expect("Behavioral CF present in the snapshot");assert!(- stage1.num_keys > 0,+ behavioral.num_keys > 0,"estimate-num-keys counts the written keys");- assert!(stage1.sst_bytes > 0, "flushed Stage1 keys occupy SST bytes");+ assert!(+ behavioral.sst_bytes > 0,+ "flushed behavioral keys occupy SST bytes"+ );assert!(stats.block_cache_hits + stats.block_cache_misses > 0,"reads against the flushed SSTs drove block-cache lookups: hits={}, misses={}",@@ -1391,18 +2096,24 @@ mod tests {..StoreConfig::default()}).unwrap();- let key = stage1_key();- store.write_batch(|b| b.put_stage1(&key, b"state")).unwrap();+ let key = behavioral_key();+ store+ .write_batch(|b| b.put::<Behavioral>(&key, b"state"))+ .unwrap();store.flush().unwrap();- assert!(store.get_stage1(&key).unwrap().is_some());+ assert!(store.get_behavioral(&key).unwrap().is_some());let stats = store.stats_snapshot();// Tickers read 0 with statistics off; size properties are not gated on statistics.assert_eq!(stats.block_cache_hits, 0);assert_eq!(stats.block_cache_misses, 0);- let stage1 = stats.per_cf.iter().find(|cf| cf.cf == Cf::Stage1).unwrap();+ let behavioral = stats+ .per_cf+ .iter()+ .find(|cf| cf.cf == Cf::Behavioral)+ .unwrap();assert!(- stage1.num_keys > 0,+ behavioral.num_keys > 0,"size properties work without statistics");}@@ -1448,7 +2159,7 @@ mod tests {}).unwrap();// `0` would panic `next % ratio` in `should_sample_read`; `open()` clamps it to 1.- assert!(store.get(Cf::Stage1, b"missing").unwrap().is_none());+ assert!(store.get(Cf::Behavioral, b"missing").unwrap().is_none());}#[test]diff --git a/rust/cohort-stream-processor/src/store/secondary_index.rs b/rust/cohort-stream-processor/src/store/secondary_index.rsdeleted file mode 100644index 1715c02ab013..000000000000--- a/rust/cohort-stream-processor/src/store/secondary_index.rs+++ /dev/null@@ -1,257 +0,0 @@-//! `cf_person_index` maintenance via a non-associative RocksDB merge operator.-//!-//! The hot path appends a [`LeafStateKey`] to a person's set without a read, in the same-//! `WriteBatch` as the `cf_stage1` put. Append *and* remove are both needed, so the operator is-//! non-associative (operand format ≠ value format):-//!-//! - **Value** — the set, a sorted, de-duplicated, packed `[u8; 16] × N` (untagged).-//! - **Operand** — a 17-byte `[tag u8][lsk 16]` ([`IndexOp`]); a concatenation of several is itself-//! a valid operand.-//!-//! Maintained on the hot path even though its only readers are the merge drain (enumerating P_old's-//! leaves on a person merge, [`crate::merge::drain_handler`]) and Stage 2 composition: writing it-//! eagerly gives the non-associative merge operator production bake time on real compaction/flush-//! threads before readers depend on it, and lets readers inherit a fully-built person→leaf-state-//! index with no historical backfill pass.-//!-//! Two correctness rules:-//!-//! 1. **Never panic.** The merge fns run on RocksDB compaction/flush threads; a panic across that-//! FFI boundary is UB. Every decode is length-checked and skips (with a metric).-//! 2. **Never return `None`.** `None` from `full_merge` signals a *merge failure* (a-//! `"Merge operator failed"` error on the next read), not a key drop. The empty set therefore-//! encodes to an empty value, which reads back as "no states" — same as a missing key.-//!-//! Append-present and remove-absent are `BTreeSet` no-ops, so replay is idempotent.--use std::collections::BTreeSet;--use metrics::counter;-use rocksdb::MergeOperands;--use crate::observability::metrics::STORE_MERGE_MALFORMED_TOTAL;-use crate::stage1::key::LeafStateKey;--/// RocksDB treats the operator name as a forward-compat contract: bump `_vN` on any format change.-pub const PERSON_INDEX_MERGE_OPERATOR_NAME: &str = "cf_person_index_merge_v1";--const LSK_LEN: usize = 16;-const OPERAND_LEN: usize = 1 + LSK_LEN;-const TAG_APPEND: u8 = 0;-const TAG_REMOVE: u8 = 1;--/// A mutation of a person's leaf-state set, applied to `cf_person_index` via `merge_cf`.-#[derive(Copy, Clone, Debug, Eq, PartialEq)]-pub enum IndexOp {- Append(LeafStateKey),- Remove(LeafStateKey),-}--impl IndexOp {- pub fn encode(&self) -> [u8; OPERAND_LEN] {- let (tag, lsk) = match self {- IndexOp::Append(lsk) => (TAG_APPEND, lsk),- IndexOp::Remove(lsk) => (TAG_REMOVE, lsk),- };- let mut out = [0u8; OPERAND_LEN];- out[0] = tag;- out[1..].copy_from_slice(&lsk.0);- out- }-}--/// Decode a stored `cf_person_index` value into sorted, unique leaf-state keys. Infallible: a-/// trailing partial entry is dropped (with a metric) rather than erroring; empty yields "no states".-pub fn decode_person_index(value: &[u8]) -> Vec<LeafStateKey> {- decode_packed(value).into_iter().map(LeafStateKey).collect()-}--pub(crate) fn full_merge(- _key: &[u8],- existing: Option<&[u8]>,- operands: &MergeOperands,-) -> Option<Vec<u8>> {- Some(collapse(existing, operands))-}--/// Concatenate operand logs without a base value. RocksDB only re-feeds the result as another-/// operand (`existing` is always `None`), so a concatenation of valid logs is itself valid.-pub(crate) fn partial_merge(- _key: &[u8],- _existing: Option<&[u8]>,- operands: &MergeOperands,-) -> Option<Vec<u8>> {- Some(concat_logs(operands))-}--/// Fold `existing` + ordered `operands` into the encoded set. Takes an iterator (not-/// `MergeOperands`) so the tests, which can't construct one, can share it.-fn collapse<'a>(existing: Option<&[u8]>, operands: impl IntoIterator<Item = &'a [u8]>) -> Vec<u8> {- let mut set: BTreeSet<[u8; LSK_LEN]> = existing- .map(|bytes| decode_packed(bytes).into_iter().collect())- .unwrap_or_default();- for operand in operands {- apply_operand_log(&mut set, operand);- }- encode_set(&set)-}--/// Concatenate operand logs, skipping any not a whole number of entries so one malformed operand-/// can't misalign the rest.-fn concat_logs<'a>(operands: impl IntoIterator<Item = &'a [u8]>) -> Vec<u8> {- let mut combined = Vec::new();- for operand in operands {- if operand.len() % OPERAND_LEN == 0 {- combined.extend_from_slice(operand);- } else {- counter!(STORE_MERGE_MALFORMED_TOTAL, "kind" => "operand_len").increment(1);- }- }- combined-}--fn apply_operand_log(set: &mut BTreeSet<[u8; LSK_LEN]>, log: &[u8]) {- let mut entries = log.chunks_exact(OPERAND_LEN);- for entry in &mut entries {- let [tag, lsk_bytes @ ..] = entry else {- continue;- };- let mut lsk = [0u8; LSK_LEN];- lsk.copy_from_slice(lsk_bytes);- match *tag {- TAG_APPEND => {- set.insert(lsk);- }- TAG_REMOVE => {- set.remove(&lsk);- }- _ => {- counter!(STORE_MERGE_MALFORMED_TOTAL, "kind" => "operand_tag").increment(1);- }- }- }- if !entries.remainder().is_empty() {- counter!(STORE_MERGE_MALFORMED_TOTAL, "kind" => "operand_len").increment(1);- }-}--fn encode_set(set: &BTreeSet<[u8; LSK_LEN]>) -> Vec<u8> {- let mut out = Vec::with_capacity(set.len() * LSK_LEN);- for lsk in set {- out.extend_from_slice(lsk);- }- out-}--/// Decode the packed value into raw 16-byte keys, dropping a trailing partial entry (with a metric).-fn decode_packed(bytes: &[u8]) -> Vec<[u8; LSK_LEN]> {- let mut out = Vec::with_capacity(bytes.len() / LSK_LEN);- let mut chunks = bytes.chunks_exact(LSK_LEN);- for chunk in &mut chunks {- let mut lsk = [0u8; LSK_LEN];- lsk.copy_from_slice(chunk);- out.push(lsk);- }- if !chunks.remainder().is_empty() {- counter!(STORE_MERGE_MALFORMED_TOTAL, "kind" => "base_len").increment(1);- }- out-}--#[cfg(test)]-mod tests {- use super::*;-- fn lsk(b: u8) -> LeafStateKey {- LeafStateKey([b; 16])- }-- fn append(b: u8) -> [u8; OPERAND_LEN] {- IndexOp::Append(lsk(b)).encode()- }-- fn remove(b: u8) -> [u8; OPERAND_LEN] {- IndexOp::Remove(lsk(b)).encode()- }-- #[test]- fn operand_encoding_is_tag_then_key() {- let a = append(0xAB);- assert_eq!(a[0], TAG_APPEND);- assert_eq!(&a[1..], &[0xAB; 16]);-- let r = remove(0xCD);- assert_eq!(r[0], TAG_REMOVE);- assert_eq!(&r[1..], &[0xCD; 16]);- }-- #[test]- fn append_then_collapse_round_trips_through_decode() {- let value = collapse(None, [&append(1)[..], &append(2)[..]]);- assert_eq!(decode_person_index(&value), vec![lsk(1), lsk(2)]);- }-- #[test]- fn append_then_remove_leaves_the_set_empty() {- let value = collapse(None, [&append(1)[..], &remove(1)[..]]);- assert!(value.is_empty());- assert_eq!(decode_person_index(&value), vec![]);- }-- /// Removing before the matching append is a no-op, so the key survives.- #[test]- fn remove_then_append_keeps_the_key() {- let value = collapse(None, [&remove(1)[..], &append(1)[..]]);- assert_eq!(decode_person_index(&value), vec![lsk(1)]);- }-- #[test]- fn duplicate_appends_are_deduplicated_and_sorted() {- let value = collapse(None, [&append(2)[..], &append(1)[..], &append(2)[..]]);- assert_eq!(decode_person_index(&value), vec![lsk(1), lsk(2)]);- }-- #[test]- fn merge_folds_into_an_existing_base() {- let base = collapse(None, [&append(1)[..]]);- let value = collapse(Some(&base), [&append(2)[..], &remove(1)[..]]);- assert_eq!(decode_person_index(&value), vec![lsk(2)]);- }-- /// `partial_merge` grouping must not change the final set, whatever the grouping.- #[test]- fn partial_merge_grouping_is_invariant() {- let ops: [&[u8]; 3] = [&append(1), &append(2), &remove(1)];- let direct = collapse(None, ops);-- let fully_grouped = concat_logs(ops);- assert_eq!(collapse(None, [&fully_grouped[..]]), direct);-- let prefix = concat_logs([ops[0], ops[1]]);- assert_eq!(collapse(None, [&prefix[..], ops[2]]), direct);- }-- #[test]- fn malformed_operand_length_does_not_panic_or_corrupt() {- let value = collapse(None, [&append(1)[..], &[0u8; 5][..], &append(2)[..]]);- assert_eq!(decode_person_index(&value), vec![lsk(1), lsk(2)]);-- let mut corrupt_base = collapse(None, [&append(9)[..]]);- corrupt_base.push(0xFF);- let value = collapse(Some(&corrupt_base), [&append(8)[..]]);- assert_eq!(decode_person_index(&value), vec![lsk(8), lsk(9)]);- }-- #[test]- fn unknown_operand_tag_is_skipped() {- let mut bad = [0u8; OPERAND_LEN];- bad[0] = 99;- let value = collapse(None, [&append(1)[..], &bad[..]]);- assert_eq!(decode_person_index(&value), vec![lsk(1)]);- }-- #[test]- fn decode_person_index_of_empty_is_empty() {- assert_eq!(decode_person_index(&[]), vec![]);- }-}diff --git a/rust/cohort-stream-processor/src/store/staged.rs b/rust/cohort-stream-processor/src/store/staged.rsindex 4f92f2a7ebe3..e66612d09f86 100644--- a/rust/cohort-stream-processor/src/store/staged.rs+++ b/rust/cohort-stream-processor/src/store/staged.rs@@ -2,27 +2,19 @@//!//! [`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).+//! [`StagedBatch`] is the owned counterpart: each staging call encodes its key 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;+use super::keys::{MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage2Key, TombstoneKey};+use super::keyspace::Keyspace;/// 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,@@ -33,11 +25,6 @@ pub(crate) enum StagedOp {cf: Cf,key: Vec<u8>,},- Merge {- cf: Cf,- key: Vec<u8>,- operand: Vec<u8>,- },}/// Owned, `Send`-able staging for a multi-CF `WriteBatch`, mirroring@@ -65,35 +52,21 @@ impl StagedBatch {&self.ops}- pub fn put_stage1(&mut self, key: &Stage1Key, value: &[u8]) {+ /// Put a typed key/value into its keyspace's CF. The [`Keyspace`] binding routes to the right CF,+ /// so a key cannot be staged for the wrong column family.+ pub fn put<K: Keyspace>(&mut self, key: &K::Key, value: &[u8]) {self.ops.push(StagedOp::Put {- cf: Cf::Stage1,- key: key.encode().to_vec(),+ cf: K::CF,+ key: K::encode(key),value: value.to_vec(),});}- pub fn delete_stage1(&mut self, key: &Stage1Key) {+ /// Delete a typed key from its keyspace's CF.+ pub fn delete<K: Keyspace>(&mut self, key: &K::Key) {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(),+ cf: K::CF,+ key: K::encode(key),});}@@ -201,27 +174,20 @@ mod tests {use super::*;use crate::stage1::key::LeafStateKey;+ use crate::store::keyspace::{Behavioral, BehavioralKey};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 behavioral_key(person: u128, lsk: u8) -> BehavioralKey {+ BehavioralKey::new(+ PARTITION,+ TEAM,+ Uuid::from_u128(person),+ LeafStateKey([lsk; 16]),+ )}fn stage2_key(person: u128, cohort: u64) -> Stage2Key {@@ -277,31 +243,12 @@ mod tests {.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.+ /// Drives every staging method through `BatchBuilder`, including a behavioral put that survives and+ /// one cancelled by a delete, and both `OpaqueCf` arms of `put_raw`.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::<Behavioral>(&behavioral_key(1, 0xA0), b"s1-put");+ b.put::<Behavioral>(&behavioral_key(2, 0xA1), b"s1-doomed");+ b.delete::<Behavioral>(&behavioral_key(2, 0xA1));b.put_stage2(&stage2_key(1, 100), b"s2-put");b.put_stage2(&stage2_key(2, 200), b"s2-doomed");@@ -319,33 +266,19 @@ mod tests {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::Behavioral,+ &behavioral_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::<Behavioral>(&behavioral_key(1, 0xA0), b"s1-put");+ s.put::<Behavioral>(&behavioral_key(2, 0xA1), b"s1-doomed");+ s.delete::<Behavioral>(&behavioral_key(2, 0xA1));s.put_stage2(&stage2_key(1, 100), b"s2-put");s.put_stage2(&stage2_key(2, 200), b"s2-doomed");@@ -363,7 +296,11 @@ mod tests {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::Behavioral,+ &behavioral_key(9, 0xF0).encode(),+ b"raw-s1",+ );s.put_raw(OpaqueCf::Stage2, &stage2_key(9, 900).encode(), b"raw-s2");}@@ -378,12 +315,15 @@ mod tests {let mut staged = StagedBatch::default();drive_staged_batch(&mut staged);assert!(!staged.is_empty());- assert_eq!(staged.len(), 21);+ assert_eq!(staged.len(), 16);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.+ // partitioned CF's slice.for cf in Cf::ALL {+ if !cf.partitioned() {+ continue;+ }let builder_kvs = via_builder.scan_merge_cf(cf, PARTITION, None, LARGE_LIMIT).unwrap();@@ -396,25 +336,18 @@ mod tests {);}- // 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.+ // The surviving behavioral put leaves exactly one row; the put-then-deleted one is gone.+ assert_eq!(+ via_staged+ .get_behavioral(&behavioral_key(1, 0xA0))+ .unwrap()+ .as_deref(),+ Some(b"s1-put".as_slice()),+ );assert_eq!(- via_staged.get_person_index(&person_index_key(1)).unwrap(),- vec![LeafStateKey([0x11; 16])],+ via_staged.get_behavioral(&behavioral_key(2, 0xA1)).unwrap(),+ None,);- assert!(via_staged- .get_person_index(&person_index_key(2))- .unwrap()- .is_empty());}#[test]diff --git a/rust/cohort-stream-processor/src/store/ttl_filter.rs b/rust/cohort-stream-processor/src/store/ttl_filter.rsnew file mode 100644index 000000000000..5e70ed28fc91--- /dev/null+++ b/rust/cohort-stream-processor/src/store/ttl_filter.rs@@ -0,0 +1,233 @@+//! Env-gated TTL compaction filter for `cf_person_records`.+//!+//! When `COHORT_PERSON_RECORD_TTL_DAYS` is set (default OFF), a compaction-filter factory is installed+//! on `cf_person_records` only — never on `cf_behavioral`, whose live eviction deadlines are the+//! sweep's contract. Each compaction run gets a fresh filter whose cutoff is frozen at filter creation+//! (`now_ms - ttl`), so every value in that run is judged against one instant.+//!+//! A record whose `last_seen_ms` is strictly older than the cutoff is removed; any value that cannot+//! be positively read as expired (too short, wrong version byte, garbage) is kept.+//!+//! [`PersonRecordTtlFilter::filter`] runs on RocksDB compaction threads across the C FFI boundary,+//! where a panic is undefined behavior, so it must never panic: no unchecked indexing, no unwrap/expect+//! on fallible input. It is also kept free of metrics and logging (no re-entrancy guarantees on the+//! compaction thread); the only observability is a factory-creation `debug!`.++use std::ffi::{CStr, CString};++use rocksdb::compaction_filter::{CompactionFilter, Decision};+use rocksdb::compaction_filter_factory::{CompactionFilterContext, CompactionFilterFactory};+use tracing::debug;++use crate::stage1::person_record::{FORMAT_VERSION, LAST_SEEN_MS_OFFSET};++/// Bump the `_vN` suffix on any change to the filter's semantics so it is visible in the RocksDB LOG.+const FACTORY_NAME: &[u8] = b"cf_person_records_ttl_v1\0";+const FILTER_NAME: &[u8] = b"cf_person_records_ttl_filter_v1\0";++/// Milliseconds per day, the unit `COHORT_PERSON_RECORD_TTL_DAYS` is expressed in.+const MS_PER_DAY: i64 = 86_400_000;++/// The smallest value long enough to carry `last_seen_ms`. Shorter values are always kept.+const MIN_TTL_READABLE_LEN: usize = LAST_SEEN_MS_OFFSET + 8;++/// Factory installed on `cf_person_records` when the TTL is enabled. RocksDB calls [`Self::create`]+/// once per compaction run; the returned filter carries a cutoff frozen at that instant.+pub struct PersonRecordTtlFactory {+ ttl_ms: i64,+ /// The clock, read once per compaction run. Boxed so tests can inject a fixed instant.+ now_ms: Box<dyn Fn() -> i64 + Send>,+}++impl PersonRecordTtlFactory {+ /// A factory that reads the wall clock at each compaction run.+ pub fn new(ttl_days: u32) -> Self {+ Self::with_clock(ttl_days, wall_clock_ms)+ }++ fn with_clock(ttl_days: u32, now_ms: impl Fn() -> i64 + Send + 'static) -> Self {+ Self {+ ttl_ms: ttl_ms_for(ttl_days),+ now_ms: Box::new(now_ms),+ }+ }++ /// The cutoff for a run starting now: records with `last_seen_ms < cutoff` are dropped. Saturating+ /// so an enormous TTL cannot underflow the cutoff.+ fn cutoff(&self) -> i64 {+ (self.now_ms)().saturating_sub(self.ttl_ms)+ }+}++impl CompactionFilterFactory for PersonRecordTtlFactory {+ type Filter = PersonRecordTtlFilter;++ fn create(&mut self, context: CompactionFilterContext) -> Self::Filter {+ let cutoff = self.cutoff();+ // Log here, not in `filter`: this runs once per compaction run, outside the per-key FFI loop.+ debug!(+ cutoff_ms = cutoff,+ is_full_compaction = context.is_full_compaction,+ is_manual_compaction = context.is_manual_compaction,+ "cf_person_records TTL compaction filter created",+ );+ PersonRecordTtlFilter {+ cutoff,+ name: filter_name(),+ }+ }++ fn name(&self) -> &CStr {+ factory_name()+ }+}++/// One compaction run's filter. Holds the frozen cutoff; classifies each value with no allocation,+/// no clock read, and no panic, metric, or log.+pub struct PersonRecordTtlFilter {+ cutoff: i64,+ name: CString,+}++impl CompactionFilter for PersonRecordTtlFilter {+ fn filter(&mut self, _level: u32, _key: &[u8], value: &[u8]) -> Decision {+ match last_seen_ms(value) {+ Some(last_seen_ms) if last_seen_ms < self.cutoff => Decision::Remove,+ // Fresh enough, or unreadable (short / wrong version / garbage): keep it.+ _ => Decision::Keep,+ }+ }++ fn name(&self) -> &CStr {+ self.name.as_c_str()+ }+}++/// Read `last_seen_ms` from a value that is a well-formed v1 person record, else `None`. Panic-free:+/// the length guard makes the fixed-offset slice in-bounds.+fn last_seen_ms(value: &[u8]) -> Option<i64> {+ if value.len() < MIN_TTL_READABLE_LEN || value[0] != FORMAT_VERSION {+ return None;+ }+ let bytes: [u8; 8] = value[LAST_SEEN_MS_OFFSET..LAST_SEEN_MS_OFFSET + 8]+ .try_into()+ .ok()?;+ Some(i64::from_be_bytes(bytes))+}++/// `ttl_days` as milliseconds, saturating so a pathological day count cannot overflow `i64`.+fn ttl_ms_for(ttl_days: u32) -> i64 {+ (ttl_days as i64).saturating_mul(MS_PER_DAY)+}++fn wall_clock_ms() -> i64 {+ chrono::Utc::now().timestamp_millis()+}++fn factory_name() -> &'static CStr {+ CStr::from_bytes_with_nul(FACTORY_NAME).expect("factory name is a valid C string literal")+}++fn filter_name() -> CString {+ CStr::from_bytes_with_nul(FILTER_NAME)+ .expect("filter name is a valid C string literal")+ .to_owned()+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::stage1::person_record::{PersonRecord, Stamp};++ fn record_with_last_seen(last_seen_ms: i64) -> Vec<u8> {+ let mut record = PersonRecord::absent();+ record.last_seen_ms = last_seen_ms;+ record.stamp = Stamp::new(last_seen_ms, 0);+ record.encode()+ }++ /// A factory whose "now" is fixed, so a run's cutoff is deterministic.+ fn factory_at(now_ms: i64, ttl_days: u32) -> PersonRecordTtlFactory {+ PersonRecordTtlFactory::with_clock(ttl_days, move || now_ms)+ }++ #[test]+ fn expired_record_is_removed_and_fresh_is_kept() {+ // now = day 40, TTL = 30d → cutoff = day 10.+ let mut filter = factory_at(40 * MS_PER_DAY, 30).create(context());++ let ancient = record_with_last_seen(5 * MS_PER_DAY); // < cutoff+ let fresh = record_with_last_seen(35 * MS_PER_DAY); // > cutoff+ assert!(matches!(filter.filter(0, b"k", &ancient), Decision::Remove));+ assert!(matches!(filter.filter(0, b"k", &fresh), Decision::Keep));+ }++ #[test]+ fn a_record_exactly_at_the_cutoff_is_kept() {+ // Strictly-older is the drop rule: `last_seen_ms == cutoff` must survive.+ let mut filter = factory_at(40 * MS_PER_DAY, 30).create(context()); // cutoff = day 10+ let at_cutoff = record_with_last_seen(10 * MS_PER_DAY);+ assert!(matches!(filter.filter(0, b"k", &at_cutoff), Decision::Keep));+ }++ #[test]+ fn malformed_values_are_always_kept() {+ let mut filter = factory_at(40 * MS_PER_DAY, 30).create(context()); // cutoff = day 10+ for value in [+ [].as_slice(),+ &[FORMAT_VERSION], // version only+ // One byte short of the 10-byte minimum (`last_seen_ms` spans bytes 2..10) — the+ // tightest truncation the length guard must reject.+ &[FORMAT_VERSION, 0, 0, 0, 0, 0, 0, 0, 0],+ &[0xFF; 32], // wrong version byte, plenty long+ ] {+ assert!(+ matches!(filter.filter(0, b"k", value), Decision::Keep),+ "malformed value {value:?} must be kept",+ );+ }+ }++ #[test]+ fn last_seen_ms_reads_only_well_formed_v1_records() {+ let encoded = record_with_last_seen(1_234_567_890);+ assert_eq!(last_seen_ms(&encoded), Some(1_234_567_890));+ assert_eq!(last_seen_ms(&[]), None);+ assert_eq!(last_seen_ms(&[FORMAT_VERSION, 0, 0]), None, "too short");+ let mut wrong_version = encoded.clone();+ wrong_version[0] = FORMAT_VERSION + 1;+ assert_eq!(last_seen_ms(&wrong_version), None, "version guard");+ }++ #[test]+ fn cutoff_does_not_underflow_for_a_small_now_and_a_large_ttl() {+ // A wrap would flip the cutoff positive and classify nothing as expired.+ let mut factory = factory_at(0, 30);+ factory.ttl_ms = i64::MAX;+ assert_eq!(factory.cutoff(), 0i64.saturating_sub(i64::MAX));+ assert!(factory.cutoff() < 0);+ }++ #[test]+ fn ttl_ms_for_maps_days_to_millis_without_overflow_for_any_u32() {+ assert_eq!(ttl_ms_for(30), 30 * MS_PER_DAY);+ // Every `u32` day count fits in `i64` millis, so the saturating multiply never saturates here.+ assert_eq!(ttl_ms_for(u32::MAX), u32::MAX as i64 * MS_PER_DAY);+ }++ #[test]+ fn names_are_valid_nul_terminated_c_strings() {+ assert_eq!(factory_name().to_bytes(), b"cf_person_records_ttl_v1");+ assert_eq!(+ filter_name().as_c_str().to_bytes(),+ b"cf_person_records_ttl_filter_v1",+ );+ }++ fn context() -> CompactionFilterContext {+ CompactionFilterContext {+ is_full_compaction: true,+ is_manual_compaction: true,+ }+ }+}diff --git a/rust/cohort-stream-processor/src/sweep/eviction_queue.rs b/rust/cohort-stream-processor/src/sweep/eviction_queue.rsindex 1cf8af663e9a..3aafafcfada9 100644--- a/rust/cohort-stream-processor/src/sweep/eviction_queue.rs+++ b/rust/cohort-stream-processor/src/sweep/eviction_queue.rs@@ -30,9 +30,9 @@ type Coord = (i64, u64);/// A deadline-ordered queue of keys, drained soonest-first by [`pop_due`](Self::pop_due).///-/// Single-threaded by design: each partition worker owns one `EvictionQueue<Stage1Key>` and is the-/// only mutator, so no internal synchronization is needed. Generic over `K` purely so the structure-/// can be unit-tested in isolation from `Stage1Key`.+/// Single-threaded by design: each partition worker owns one `EvictionQueue<BehavioralKey>` and is+/// the only mutator, so no internal synchronization is needed. Generic over `K` purely so the+/// structure can be unit-tested in isolation from `BehavioralKey`.////// Invariant, upheld by every method: `by_deadline` and `index` hold exactly the same set of keys,/// so `by_deadline.len() == index.len() == ` the live-key count, and each key maps to exactly onediff --git a/rust/cohort-stream-processor/src/workers/cascade_path.rs b/rust/cohort-stream-processor/src/workers/cascade_path.rsindex fa0457c51e14..d00e7cf2d735 100644--- a/rust/cohort-stream-processor/src/workers/cascade_path.rs+++ b/rust/cohort-stream-processor/src/workers/cascade_path.rs@@ -9,7 +9,7 @@//! **Produce-before-state.** A referrer's new `cf_stage2` bit is committed only after both produces//! ack; a failure holds without writing, so replay re-detects the still-old bit and re-emits (the//! downstream UPSERT is idempotent). The cascade input is a fixed message that recomputes the same-//! flip on replay — unlike Stage 2 composition, which dedupes by `cf_stage1`'s applied-offset and+//! flip on replay — unlike Stage 2 composition, which dedupes by `cf_behavioral`'s applied-offset and//! writes state-before-produce (at-most-once).use std::sync::Arc;@@ -259,8 +259,12 @@ mod tests {MembershipStatus,};use crate::stage1::key::LeafStateKey;+ use crate::stage1::person_record::{MatchedSet, PersonRecord};use crate::stage1::state::{AppliedOffsets, Stage1State, StatefulRecord};- use crate::store::{CohortStore, OffloadConfig, OffloadMode, Stage1Key, StoreConfig};+ use crate::store::{+ Behavioral, BehavioralKey, CohortStore, OffloadConfig, OffloadMode, PersonRecordKey,+ PersonRecords, StoreConfig,+ };use crate::workers::{CascadeConfig, TransferRetryPolicy, DEFAULT_MERGE_GC_SCAN_LIMIT};const TEAM: i32 = 7;@@ -336,24 +340,24 @@ mod tests {.by_condition_to_lsk[&HASH][0]}- fn person_lsk() -> LeafStateKey {- LeafStateKey::for_person_property(&PERSON_HASH)- }-fn person(n: u128) -> Uuid {Uuid::from_u128(n)}- fn write_stage1(store: &CohortStore, lsk: LeafStateKey, who: Uuid, state: Stage1State) {- let key = Stage1Key {- partition_id: PARTITION,- team_id: TEAM as u64,- leaf_state_key: lsk,- person_id: who,- };+ fn write_behavioral(store: &CohortStore, lsk: LeafStateKey, who: Uuid, state: Stage1State) {+ let key = BehavioralKey::new(PARTITION, TEAM as u64, who, lsk);let record = StatefulRecord::new(state, AppliedOffsets::default());store- .write_batch(|b| b.put_stage1(&key, &record.encode()))+ .write_batch(|b| b.put::<Behavioral>(&key, &record.encode()))+ .unwrap();+ }++ fn write_person_record(store: &CohortStore, who: Uuid, matched: &[[u8; 16]]) {+ let key = PersonRecordKey::new(PARTITION, TEAM as u64, who);+ let mut record = PersonRecord::absent();+ record.matched = MatchedSet::from_iter(matched.iter().copied());+ store+ .write_batch(|b| b.put::<PersonRecords>(&key, &record.encode())).unwrap();}@@ -399,14 +403,6 @@ mod tests {}}- fn person_match() -> Stage1State {- Stage1State::PersonProperty {- matches: true,- last_updated_at_ms: 1,- last_updated_offset: 0,- }- }-/// Worker deps with the cascade gate on, capturing both the membership and cascade sinks.fn deps(membership: &CaptureSink,@@ -474,8 +470,8 @@ mod tests {true,);let alice = person(1);- write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());- write_stage1(&store, person_lsk(), alice, person_match());+ write_behavioral(&store, behavioral_lsk(&catalog), alice, behavioral_match());+ write_person_record(&store, alice, &[PERSON_HASH]);let membership = CaptureSink::new();let cascade = CaptureCascadeSink::new();@@ -526,8 +522,8 @@ mod tests {true,);let alice = person(1);- write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());- write_stage1(&store, person_lsk(), alice, person_match());+ write_behavioral(&store, behavioral_lsk(&catalog), alice, behavioral_match());+ write_person_record(&store, alice, &[PERSON_HASH]);write_stage2(&store, 1, alice, true); // B already a memberlet membership = CaptureSink::new();@@ -558,7 +554,7 @@ mod tests {// Cohort 2 is single-leaf and referenced by nothing.let catalog = catalog(vec![(2, vec![behavioral_leaf()])], true);let alice = person(1);- write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());+ write_behavioral(&store, behavioral_lsk(&catalog), alice, behavioral_match());let membership = CaptureSink::new();let cascade = CaptureCascadeSink::new();@@ -593,8 +589,8 @@ mod tests {true,);let alice = person(1);- write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());- write_stage1(&store, person_lsk(), alice, person_match());+ write_behavioral(&store, behavioral_lsk(&catalog), alice, behavioral_match());+ write_person_record(&store, alice, &[PERSON_HASH]);let membership = CaptureSink::new();let cascade = CaptureCascadeSink::new();@@ -630,8 +626,8 @@ mod tests {true,);let alice = person(1);- write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());- write_stage1(&store, person_lsk(), alice, person_match());+ write_behavioral(&store, behavioral_lsk(&catalog), alice, behavioral_match());+ write_person_record(&store, alice, &[PERSON_HASH]);let membership = CaptureSink::new();let cascade = CaptureCascadeSink::new();@@ -679,8 +675,8 @@ mod tests {true,);let alice = person(1);- write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());- write_stage1(&store, person_lsk(), alice, person_match());+ write_behavioral(&store, behavioral_lsk(&catalog), alice, behavioral_match());+ write_person_record(&store, alice, &[PERSON_HASH]);let membership = CaptureSink::new();let cascade = CaptureCascadeSink::new();@@ -727,8 +723,8 @@ mod tests {true,);let alice = person(1);- write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());- write_stage1(&store, person_lsk(), alice, person_match());+ write_behavioral(&store, behavioral_lsk(&catalog), alice, behavioral_match());+ write_person_record(&store, alice, &[PERSON_HASH]);let membership = CaptureSink::new();let cascade = CaptureCascadeSink::new();@@ -771,8 +767,8 @@ mod tests {true,);let alice = person(1);- write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());- write_stage1(&store, person_lsk(), alice, person_match());+ write_behavioral(&store, behavioral_lsk(&catalog), alice, behavioral_match());+ write_person_record(&store, alice, &[PERSON_HASH]);let membership = CaptureSink::new();let cascade = CaptureCascadeSink::new();@@ -821,8 +817,8 @@ mod tests {true,);let alice = person(1);- write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());- write_stage1(&store, person_lsk(), alice, person_match());+ write_behavioral(&store, behavioral_lsk(&catalog), alice, behavioral_match());+ write_person_record(&store, alice, &[PERSON_HASH]);let membership = CaptureSink::failing_first(1);let cascade = CaptureCascadeSink::new();@@ -866,8 +862,8 @@ mod tests {true,);let alice = person(1);- write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());- write_stage1(&store, person_lsk(), alice, person_match());+ write_behavioral(&store, behavioral_lsk(&catalog), alice, behavioral_match());+ write_person_record(&store, alice, &[PERSON_HASH]);let membership = CaptureSink::new();let cascade = CaptureCascadeSink::failing_always();diff --git a/rust/cohort-stream-processor/src/workers/event_path.rs b/rust/cohort-stream-processor/src/workers/event_path.rsindex fe7346dccbc6..38543b57d6b6 100644--- a/rust/cohort-stream-processor/src/workers/event_path.rs+++ b/rust/cohort-stream-processor/src/workers/event_path.rs@@ -7,6 +7,10 @@//! [`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.+//!+//! The behavioral side stages a per-leaf `cf_behavioral` row per matching condition; the person side+//! collapses all of a person's person-property leaf state into one durable [`PersonRecord`] in+//! `cf_person_records`, updated per the freshness decision table in [`crate::stage1::person_record`].use std::collections::BTreeMap;use std::sync::Arc;@@ -16,19 +20,24 @@ use uuid::Uuid;use crate::consumers::events::CohortStreamEvent;use crate::filters::reverse_index::TeamFilters;-use crate::filters::{Generation, TeamId};+use crate::filters::TeamId;use crate::hogvm::{build_behavioral_globals, build_person_property_globals, CohortEvaluator};use crate::observability::metrics::{- STAGE1_ARGMAX_STALE, STAGE1_CONDITIONS_EVALUATED, STAGE1_CONDITIONS_SKIPPED,- STAGE1_PERSON_INDEX_APPENDS, STAGE1_REPLAY_SKIPPED, STAGE1_SNAPSHOT_KEYS,- STAGE1_STATE_DECODE_ERROR, STAGE1_STATE_WRITES, STAGE1_UNSUPPORTED_VARIANT_SKIPPED,+ STAGE1_BEHAVIORAL_APPLIES, STAGE1_CONDITIONS_EVALUATED, STAGE1_CONDITIONS_SKIPPED,+ STAGE1_PERSON_RECORD_SIZE_BYTES, STAGE1_PERSON_RECORD_TOTAL, STAGE1_REPLAY_SKIPPED,+ STAGE1_SNAPSHOT_KEYS, STAGE1_STATE_DECODE_ERROR, STAGE1_STATE_WRITES,+ STAGE1_UNSUPPORTED_VARIANT_SKIPPED,};use crate::stage1::bucket_tz::{daily_bucket_len, day_idx_in_tz, now_day_for_window, window_start_for_now,};use crate::stage1::compressed_history;use crate::stage1::daily::{daily_eviction_deadline, slide_window_forward};-use crate::stage1::key::{LeafStateKey, Stage1Key};+use crate::stage1::key::LeafStateKey;+use crate::stage1::person_record::{+ apply_eval, apply_skip_eval, apply_stale, decide, CatalogFingerprint, Decision, DedupCoords,+ MatchedSet, PersonRecord, PriorRecord, PropsFingerprint, Stamp,+};use crate::stage1::pick_state::EvictionWindow;use crate::stage1::predicate::{compressed_predicate, daily_predicate, predicate};use crate::stage1::state::{@@ -37,13 +46,13 @@ use crate::stage1::state::{use crate::stage1::time::clickhouse_timestamp_to_millis;use crate::stage1::transition::{LeafTransition, TransitionKind};use crate::store::{- CohortStore, IndexOp, PersonIndexKey, ReadLane, StagedBatch, StoreError, StoreHandle,+ Behavioral, BehavioralKey, CohortStore, EventSnapshotRaw, PersonPrefix, PersonRecords,+ 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/// leaf's bytecode roots at `event == event_key`, so a name mismatch can never match: gating it out-/// drops no `Apply`.+/// drops no `BehavioralApply`.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum EventNameGating {/// Evaluate only the event's name bucket.@@ -89,7 +98,7 @@ impl SkipReason {#[derive(Debug, Default, PartialEq, Eq)]pub struct EventOutcome {pub transitions: Vec<LeafTransition>,- pub schedules: Vec<(Stage1Key, i64)>,+ pub schedules: Vec<(BehavioralKey, i64)>,/// This event's parsed timestamp (epoch ms). `0` on skip/no-applies paths.pub event_ms: i64,pub skipped: Option<SkipReason>,@@ -98,7 +107,7 @@ pub struct EventOutcome {impl EventOutcome {fn processed(transitions: Vec<LeafTransition>,- schedules: Vec<(Stage1Key, i64)>,+ schedules: Vec<(BehavioralKey, i64)>,event_ms: i64,) -> Self {Self {@@ -119,92 +128,118 @@ impl EventOutcome {}}-enum Apply {- /// Behavioral leaf matched (recorded only on match).- Behavioral {- lsk: LeafStateKey,- condition_hash: [u8; 16],- },- /// Person-property leaf evaluated (recorded on match *and* non-match).- Person {- lsk: LeafStateKey,- condition_hash: [u8; 16],- matches: bool,+/// One behavioral leaf that matched this event: recorded only on a match, so a behavioral row is+/// staged for it.+struct BehavioralApply {+ lsk: LeafStateKey,+ condition_hash: [u8; 16],+}++/// How the person side of an event is handled, resolved once before the read.+enum PersonPlan {+ /// No person conditions, or empty `person_properties`: the record is neither read nor written.+ Inactive,+ /// A person condition exists and the payload is non-empty. The record is read and the freshness+ /// decision table runs; `props_fp`/`catalog_fp` are the fingerprints the table compares against+ /// the stored record.+ Active {+ props_fp: PropsFingerprint,+ catalog_fp: CatalogFingerprint,},}-impl Apply {- fn lsk(&self) -> LeafStateKey {- match self {- Self::Behavioral { lsk, .. } | Self::Person { lsk, .. } => *lsk,- }+impl PersonPlan {+ fn is_active(&self) -> bool {+ matches!(self, Self::Active { .. })}}struct PendingWrite {- key: Stage1Key,+ key: BehavioralKey,bytes: Vec<u8>,- first_write: bool,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.+ /// Nothing to read or write: no behavioral leaf matched and the person side is inactive.NoApplies,- /// Leaves applied; read `keys` (in order) and hand the result to [`fold_event`].+ /// Work to do; read the snapshot 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.+/// The data [`fold_event`] needs from [`plan_event`], carried by [`EventPlan::Read`]. The behavioral+/// keys are derived from `prefix` in `behavioral` order so the fold's zip over the read result stays+/// aligned; the record key is the person prefix (read iff the person side is active).pub(crate) struct ReadPlan {- partition_id: u16,- team_id: u64,- applies: Vec<Apply>,- keys: Vec<Stage1Key>,+ prefix: PersonPrefix,+ behavioral: Vec<BehavioralApply>,+ person: PersonPlan,event_ms: i64,- person_id: Uuid,origin: Option<Uuid>,}+impl ReadPlan {+ /// The behavioral keys to read, in `behavioral` order.+ fn behavioral_keys(&self) -> Vec<BehavioralKey> {+ self.behavioral+ .iter()+ .map(|apply| self.prefix.behavioral_key(apply.lsk))+ .collect()+ }+}+/// 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,+ /// Encoded person-record size to record on [`STAGE1_PERSON_RECORD_SIZE_BYTES`], when a record was+ /// staged.+ record_size: Option<usize>,+ /// The person side's decision outcome for [`STAGE1_PERSON_RECORD_TOTAL`], `None` when the person+ /// side was inactive. Deferred with the write metrics so a failed commit's redelivery cannot+ /// double-count; a write-free outcome (replay) still counts, since emission is gated on the commit+ /// step passing, not on there being writes.+ person_record_result: Option<&'static str>,}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.+ /// Emit the deferred write metrics. Called by the compositions only after the commit step+ /// succeeded (an event that staged nothing has no commit to fail), so a failed write records no+ /// phantom 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);+ if let Some(size) = self.record_size {+ histogram!(STAGE1_PERSON_RECORD_SIZE_BYTES).record(size as f64);+ }+ if let Some(result) = self.person_record_result {+ counter!(STAGE1_PERSON_RECORD_TOTAL, "result" => result).increment(1);}}}-/// The pure result of [`fold_event`]: the staged writes plus what the caller surfaces after commit.-/// Infallible — the fold touches no store.+/// The pure result of [`fold_event`]: either a whole-event skip (a person-props parse failure on the+/// evaluation arm) or the staged writes plus what the caller surfaces after commit. Infallible+/// w.r.t. the store — the fold touches no store.+pub(crate) enum FoldResult {+ Skip(SkipReason),+ Folded(FoldOutput),+}++/// The staged writes plus what the caller surfaces after commit.pub(crate) struct FoldOutput {pub staged: StagedBatch,pub transitions: Vec<LeafTransition>,- pub schedules: Vec<(Stage1Key, i64)>,+ pub schedules: Vec<(BehavioralKey, i64)>,pub write_stats: WriteStats,}-/// One apply's stored state as read by the event's single batched pre-event read.+/// One behavioral 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.Absent,@@ -215,7 +250,7 @@ enum PriorState {}impl PriorState {- /// Decode one `multi_get_stage1` slot. The decode error is counted here — the only place a+ /// Decode one behavioral snapshot slot. The decode error is counted here — the only place a/// `Corrupt` can be born.fn decode(bytes: Option<Vec<u8>>) -> Self {match bytes {@@ -231,81 +266,72 @@ impl PriorState {}}-/// Fold one event with the person memo disabled (full person sweep). The memoizing entry is-/// [`process_event_with_memo`].+/// Fold one event with event-name gating disabled (full behavioral sweep). The gating-aware entry is+/// [`process_event_gated`].pub fn process_event(partition_id: u16,store: &CohortStore,filters: &TeamFilters,event: &CohortStreamEvent,) -> Result<EventOutcome, StoreError> {- process_event_with_memo(+ process_event_gated(partition_id,store,filters,- Generation::INITIAL,event,- &mut PersonMemo::disabled(),EventNameGating::Disabled,)}-/// 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.+/// Fold one event through the synchronous store, with explicit event-name gating. The public test+/// surface; the production async composition is [`process_event_offloaded`].+// The sync composition runs in blocking contexts, so its direct `read_event_snapshot` + `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(+pub fn process_event_gated(partition_id: u16,store: &CohortStore,filters: &TeamFilters,- generation: Generation,event: &CohortStreamEvent,- 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,- ) {+ let read = match plan_event(partition_id, filters, event, 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);+ let behavioral_keys = read.behavioral_keys();+ let record_key = read.person.is_active().then(|| read.prefix.record_key());+ let snapshot = store.read_event_snapshot(&behavioral_keys, record_key.as_ref())?;+ record_snapshot_keys(&snapshot);++ let (staged, transitions, schedules, write_stats) =+ match fold_event(filters, read, snapshot, event) {+ FoldResult::Skip(reason) => return Ok(EventOutcome::skipped(reason)),+ FoldResult::Folded(FoldOutput {+ staged,+ transitions,+ schedules,+ write_stats,+ }) => (staged, transitions, schedules, write_stats),+ };// 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.+ // committed writes (argMax tiebreaker, replay dedup, the person record's stamp/matched set).+ // Metrics emit only once the commit step passed.if !staged.is_empty() {store.apply(&staged)?;- write_stats.emit();}+ 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.+/// async [`StoreHandle`] facade so the store I/O runs on the blocking pool.////// Sequential awaits only: the batched read must observe the prior event's committed writes, so the/// read and commit are never joined or reordered.@@ -313,56 +339,56 @@ 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,- ) {+ let read = match plan_event(partition_id, filters, event, 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)+ let behavioral_keys = read.behavioral_keys();+ let record_key = read.person.is_active().then(|| read.prefix.record_key());+ let snapshot = handle+ .read_event_snapshot(behavioral_keys, record_key).await?;+ record_snapshot_keys(&snapshot);++ let (staged, transitions, schedules, write_stats) =+ match fold_event(filters, read, snapshot, event) {+ FoldResult::Skip(reason) => return Ok(EventOutcome::skipped(reason)),+ FoldResult::Folded(FoldOutput {+ staged,+ transitions,+ schedules,+ write_stats,+ }) => (staged, transitions, schedules, write_stats),+ };- 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.+ // Commit before the caller processes the next event; metrics emit only once the commit step passed.if !staged.is_empty() {handle.commit(staged).await?;- write_stats.emit();}+ 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.+/// Record the snapshot's total key count (behavioral rows + the 0-or-1 record slot) on+/// [`STAGE1_SNAPSHOT_KEYS`].+fn record_snapshot_keys(snapshot: &EventSnapshotRaw) {+ let keys = snapshot.behavioral.len() + usize::from(snapshot.record.is_some());+ histogram!(STAGE1_SNAPSHOT_KEYS).record(keys as f64);+}++/// Resolve everything up to the pre-event read: gating, behavioral evaluation and applies, and the+/// person plan (fingerprints only — the person record read and evaluation happen in the fold).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() {@@ -383,8 +409,8 @@ pub(crate) fn plan_event(return EventPlan::Skip(SkipReason::NoConditions);}- // Build globals and resolve the person plan before any evaluation, so a malformed payload skips- // the event before any condition runs. A memo hit resolves without parsing person globals.+ // Build behavioral globals before any evaluation, so a malformed payload skips the event before+ // any condition runs. The person side parses its own globals only on the evaluation arm, in the fold.let behavioral_globals = if has_behavioral {match build_behavioral_globals(event) {Ok(globals) => Some(globals),@@ -393,14 +419,9 @@ pub(crate) fn plan_event(} else {None};- let person = match resolve_person(filters, event, person_id, generation, memo) {- Ok(person) => person,- Err(skip) => return EventPlan::Skip(skip),- };- // One evaluator reused across the event's conditions: globals set once per kind, program per condition.let mut evaluator = CohortEvaluator::new();- let mut applies: Vec<Apply> = Vec::new();+ let mut behavioral: Vec<BehavioralApply> = Vec::new();if let Some(globals) = behavioral_globals {evaluator.set_globals(globals);collect_behavioral_applies(@@ -408,12 +429,20 @@ pub(crate) fn plan_event(&event.event,event_name_gating,&mut evaluator,- &mut applies,+ &mut behavioral,);}- collect_person_applies(filters, &mut evaluator, person, memo, &mut applies);- if applies.is_empty() {+ // Fingerprints are computed here; the record read and evaluation happen in the fold.+ let person = match active_person_props(filters, event) {+ Some(raw) => PersonPlan::Active {+ props_fp: PropsFingerprint::of(raw),+ catalog_fp: filters.catalog_fingerprint,+ },+ None => PersonPlan::Inactive,+ };++ if behavioral.is_empty() && !person.is_active() {return EventPlan::NoApplies;}@@ -421,104 +450,156 @@ pub(crate) fn plan_event(return EventPlan::Skip(SkipReason::BadTimestamp);};- let team_id = event.team_id as u64;- // 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 {- partition_id,- team_id,- leaf_state_key: apply.lsk(),- person_id,- })- .collect();-+ let prefix = PersonPrefix::new(partition_id, event.team_id as u64, person_id);EventPlan::Read(ReadPlan {- partition_id,- team_id,- applies,- keys,+ prefix,+ behavioral,+ person,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.+/// Fold the pre-event `snapshot` into the behavioral rows and the person record, staging the writes+/// into a [`StagedBatch`] for the caller to commit. Pure w.r.t. the store. Returns+/// [`FoldResult::Skip`] on a person-props parse failure.pub(crate) fn fold_event(filters: &TeamFilters,read: ReadPlan,- values: Vec<Option<Vec<u8>>>,+ snapshot: EventSnapshotRaw,event: &CohortStreamEvent,-) -> FoldOutput {+) -> FoldResult {let ReadPlan {- partition_id,- team_id,- applies,- keys,+ prefix,+ behavioral,+ person,event_ms,- person_id,origin,} = read;- let origin = origin.as_ref();+ let person_id = prefix.person_id;+ let origin_ref = origin.as_ref();+ let EventSnapshotRaw {+ behavioral: behavioral_values,+ record: record_slot,+ } = snapshot;++ // Person side first: an evaluation-arm parse failure skips the whole event, so nothing (behavioral+ // included) may be staged before the person decision succeeds.+ let (record_put, mut transitions, record_result) = match fold_person(+ filters,+ &prefix,+ &person,+ record_slot,+ event,+ event_ms,+ origin_ref,+ ) {+ PersonFoldResult::Skip(reason) => return FoldResult::Skip(reason),+ PersonFoldResult::Folded {+ record_put,+ transitions,+ record_result,+ } => (record_put, transitions, record_result),+ };- let mut transitions = Vec::new();- let mut schedules: Vec<(Stage1Key, i64)> = Vec::new();+ let behavioral_keys: Vec<BehavioralKey> = behavioral+ .iter()+ .map(|apply| prefix.behavioral_key(apply.lsk))+ .collect();+ histogram!(STAGE1_BEHAVIORAL_APPLIES).record(behavioral.len() as f64);++ let mut schedules: Vec<(BehavioralKey, i64)> = Vec::new();let mut pending: Vec<PendingWrite> = Vec::new();+ fold_behavioral(+ filters,+ &behavioral,+ &behavioral_keys,+ behavioral_values,+ person_id,+ origin_ref,+ event,+ event_ms,+ &mut transitions,+ &mut schedules,+ &mut pending,+ );- // 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) {- let (prev, first_write) = match PriorState::decode(bytes) {- PriorState::Absent => (None, true),- PriorState::Present(record) => (Some(record), false),+ let mut staged = StagedBatch::default();+ let mut write_stats = WriteStats {+ variant_writes: Vec::new(),+ record_size: None,+ person_record_result: record_result,+ };+ for write in &pending {+ staged.put::<Behavioral>(&write.key, &write.bytes);+ record_variant_write(&mut write_stats.variant_writes, write.variant);+ }+ if let Some(bytes) = record_put {+ write_stats.record_size = Some(bytes.len());+ staged.put::<PersonRecords>(&prefix.record_key(), &bytes);+ }++ FoldResult::Folded(FoldOutput {+ staged,+ transitions,+ schedules,+ write_stats,+ })+}++/// Fold each behavioral apply via the `mutate_behavioral*` variants: a match stages an advanced+/// `cf_behavioral` row, may schedule a sweep deadline, and may emit a transition.+#[allow(clippy::too_many_arguments)]+fn fold_behavioral(+ filters: &TeamFilters,+ behavioral: &[BehavioralApply],+ behavioral_keys: &[BehavioralKey],+ behavioral_values: Vec<Option<Vec<u8>>>,+ person_id: Uuid,+ origin: Option<&Uuid>,+ event: &CohortStreamEvent,+ event_ms: i64,+ transitions: &mut Vec<LeafTransition>,+ schedules: &mut Vec<(BehavioralKey, i64)>,+ pending: &mut Vec<PendingWrite>,+) {+ // Alignment-safe zip: the snapshot preserves the request order, `None` for absent keys.+ for ((apply, &key), bytes) in behavioral+ .iter()+ .zip(behavioral_keys)+ .zip(behavioral_values)+ {+ let prev = match PriorState::decode(bytes) {+ PriorState::Absent => None,+ PriorState::Present(record) => Some(record),PriorState::Corrupt => continue,};- let mutation = match apply {- Apply::Behavioral {- lsk,- condition_hash,- } => match filters.by_lsk.get(&lsk).map(|meta| meta.variant) {- Some(StateVariant::BehavioralDailyBuckets) => mutate_behavioral_daily(- filters,- lsk,- condition_hash,- person_id,- origin,- event,- event_ms,- prev,- ),- Some(StateVariant::BehavioralCompressedHistory) => mutate_behavioral_compressed(- filters,- lsk,- condition_hash,- person_id,- origin,- event,- event_ms,- prev,- ),- _ => mutate_behavioral(- filters,- lsk,- condition_hash,- person_id,- origin,- event,- event_ms,- prev,- ),- },- Apply::Person {- lsk,- condition_hash,- matches,- } => mutate_person(- lsk,- condition_hash,- matches,+ let mutation = match filters.by_lsk.get(&apply.lsk).map(|meta| meta.variant) {+ Some(StateVariant::BehavioralDailyBuckets) => mutate_behavioral_daily(+ filters,+ apply.lsk,+ apply.condition_hash,+ person_id,+ origin,+ event,+ event_ms,+ prev,+ ),+ Some(StateVariant::BehavioralCompressedHistory) => mutate_behavioral_compressed(+ filters,+ apply.lsk,+ apply.condition_hash,+ person_id,+ origin,+ event,+ event_ms,+ prev,+ ),+ _ => mutate_behavioral(+ filters,+ apply.lsk,+ apply.condition_hash,person_id,origin,event,@@ -541,36 +622,136 @@ pub(crate) fn fold_event(variant: record.state.variant(),bytes: record.encode(),key,- first_write,});}+}- 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,+/// The result of the person side of a fold: either a whole-event skip (an evaluation-arm parse+/// failure) or the record put to stage (if any) plus the person transitions.+enum PersonFoldResult {+ Skip(SkipReason),+ Folded {+ record_put: Option<Vec<u8>>,+ transitions: Vec<LeafTransition>,+ /// The decision outcome for [`STAGE1_PERSON_RECORD_TOTAL`]; `None` when the person side was+ /// inactive. Deferred to post-commit via [`WriteStats`] so a failed commit's redelivery+ /// cannot double-count.+ record_result: Option<&'static str>,+ },+}++/// Run the freshness decision table for the person side against the stored record.+///+/// `Inactive` touches nothing. Otherwise the prior record is decoded (its classification — present,+/// absent, corrupt — feeds the metric), [`decide`] classifies the event, and:+///+/// - `Replay`: nothing staged, no transitions.+/// - `Stale`: the record advances its dedup + `last_seen` only; no HogVM, no transitions.+/// - `SkipEval`: the record adopts the event stamp; no HogVM, no transitions.+/// - `Eval`: parse the person globals (a failure skips the whole event), evaluate the effective+/// person conditions, and diff the resulting TRUE set against the record's matched set.+#[allow(clippy::too_many_arguments)]+fn fold_person(+ filters: &TeamFilters,+ prefix: &PersonPrefix,+ person: &PersonPlan,+ record_slot: Option<Option<Vec<u8>>>,+ event: &CohortStreamEvent,+ event_ms: i64,+ origin: Option<&Uuid>,+) -> PersonFoldResult {+ let PersonPlan::Active {+ props_fp,+ catalog_fp,+ } = person+ else {+ return PersonFoldResult::Folded {+ record_put: None,+ transitions: Vec::new(),+ record_result: None,};- for write in &pending {- staged.put_stage1(&write.key, &write.bytes);- if write.first_write {- staged.merge_person_index(&person_index, IndexOp::Append(write.key.leaf_state_key));- write_stats.person_index_appends += 1;+ };++ // The record slot is always requested for an active person, so the outer `Option` is `Some`.+ let record_bytes = record_slot.flatten();+ let prior = PriorRecord::decode(record_bytes.as_deref());+ let baseline = PersonRecord::absent();+ let event_stamp = Stamp::new(event_ms, event.source_offset);+ let dedup = DedupCoords::new(origin.copied(), event.source_partition, event.source_offset);++ // Absent/corrupt priors fold from an absent baseline; a present prior folds from itself.+ let from = match &prior {+ PriorRecord::Present(record) => record,+ PriorRecord::Absent | PriorRecord::Corrupt => &baseline,+ };++ match decide(&prior, event_stamp, dedup, *props_fp, *catalog_fp) {+ Decision::Replay => PersonFoldResult::Folded {+ record_put: None,+ transitions: Vec::new(),+ record_result: Some("replay"),+ },+ Decision::Stale => {+ let record = apply_stale(from, event_stamp, dedup);+ PersonFoldResult::Folded {+ record_put: Some(record.encode()),+ transitions: Vec::new(),+ record_result: Some("argmax_stale"),+ }+ }+ Decision::SkipEval => {+ let record = apply_skip_eval(from, event_stamp, dedup);+ PersonFoldResult::Folded {+ record_put: Some(record.encode()),+ transitions: Vec::new(),+ record_result: Some("fresh"),+ }+ }+ Decision::Eval { freshness } => {+ // A globals parse failure skips the whole event. The effective condition subset and the+ // catalog slice passed to `diff`/`apply_eval` are the same filtered set, so a+ // defensively-skipped hash in the stored set never emits a spurious `Left`.+ let globals = match build_person_property_globals(event) {+ Ok(globals) => globals,+ Err(_) => return PersonFoldResult::Skip(SkipReason::GlobalsParseError),+ };+ let mut evaluator = CohortEvaluator::new();+ evaluator.set_globals(globals);+ let (true_set, effective_catalog) = eval_person_conditions(filters, &mut evaluator);++ let (record, raw_transitions) = apply_eval(+ true_set,+ &effective_catalog,+ from,+ event_stamp,+ dedup,+ *props_fp,+ *catalog_fp,+ );+ // absent/corrupt are labelled from the prior classification (an eval from nothing), not+ // from the freshness axis (which reports StaleBoth for both).+ let record_result = match &prior {+ PriorRecord::Absent => "absent",+ PriorRecord::Corrupt => "corrupt",+ PriorRecord::Present(_) => freshness.as_str(),+ };++ let transitions = raw_transitions+ .into_iter()+ .map(|(hash, kind)| LeafTransition {+ team_id: TeamId(event.team_id),+ leaf_state_key: LeafStateKey::for_person_property(&hash),+ person_id: prefix.person_id,+ condition_hash: hash,+ kind,+ })+ .collect();+ PersonFoldResult::Folded {+ record_put: Some(record.encode()),+ transitions,+ record_result: Some(record_result),}- record_variant_write(&mut write_stats.variant_writes, write.variant);}- }-- FoldOutput {- staged,- transitions,- schedules,- write_stats,}}@@ -590,19 +771,6 @@ pub(crate) fn schedule_deadline(state: &Stage1State) -> Option<i64> {state.eviction_deadline().filter(|&d| d != i64::MAX)}-/// How the event's person conditions will be answered, resolved before any evaluation.-enum PersonResolution {- /// No person conditions, or empty `person_properties`.- Inactive,- /// Memo hit: reuse the cached results (globals never parsed).- Cached(ConditionBitset),- /// Evaluate `globals`, then cache the results under `receipt`.- Evaluate {- globals: serde_json::Value,- receipt: Receipt,- },-}-/// The raw `person_properties` iff there is a person condition and the payload is non-empty.fn active_person_props<'a>(filters: &TeamFilters, event: &'a CohortStreamEvent) -> Option<&'a str> {if filters.person_property_conditions.is_empty() {@@ -614,40 +782,14 @@ fn active_person_props<'a>(filters: &TeamFilters, event: &'a CohortStreamEvent).filter(|raw| !raw.is_empty())}-/// Decide how to answer the person conditions. The only error is a malformed-props parse failure on-/// the eval path, which the caller turns into a `GlobalsParseError` skip.-fn resolve_person(- filters: &TeamFilters,- event: &CohortStreamEvent,- person_id: Uuid,- generation: Generation,- memo: &mut PersonMemo,-) -> Result<PersonResolution, SkipReason> {- let Some(raw) = active_person_props(filters, event) else {- return Ok(PersonResolution::Inactive);- };- let key = PersonKey {- team: TeamId(event.team_id),- person: person_id,- };- match memo.probe(key, generation, raw) {- Lookup::Hit(results) => Ok(PersonResolution::Cached(results)),- Lookup::Miss(receipt) => {- let globals =- build_person_property_globals(event).map_err(|_| SkipReason::GlobalsParseError)?;- Ok(PersonResolution::Evaluate { globals, receipt })- }- }-}--/// Evaluate this event's behavioral conditions against the set globals, pushing an `Apply::Behavioral`+/// Evaluate this event's behavioral conditions against the set globals, pushing a [`BehavioralApply`]/// per matching leaf. Under [`EventNameGating::Enabled`] only the event's name bucket is evaluated.fn collect_behavioral_applies(filters: &TeamFilters,event_name: &str,gating: EventNameGating,evaluator: &mut CohortEvaluator,- applies: &mut Vec<Apply>,+ applies: &mut Vec<BehavioralApply>,) {match gating {EventNameGating::Disabled => {@@ -675,13 +817,13 @@ fn collect_behavioral_applies(}}-/// Evaluate one behavioral condition, pushing an `Apply::Behavioral` for each supported state-keyed+/// Evaluate one behavioral condition, pushing a [`BehavioralApply`] for each supported state-keyed/// leaf on a match.fn eval_behavioral_condition(filters: &TeamFilters,hash: [u8; 16],evaluator: &mut CohortEvaluator,- applies: &mut Vec<Apply>,+ applies: &mut Vec<BehavioralApply>,) {let Some(bytecode) = filters.by_condition_to_bytecode.get(&hash) else {return;@@ -700,7 +842,7 @@ fn eval_behavioral_condition(| StateVariant::BehavioralDailyBuckets| StateVariant::BehavioralCompressedHistory,) => {- applies.push(Apply::Behavioral {+ applies.push(BehavioralApply {lsk,condition_hash: hash,});@@ -714,88 +856,42 @@ fn eval_behavioral_condition(}}-/// Push person applies for a resolved plan. The cached-read and fresh-eval paths produce the-/// identical `Apply` multiset.-fn collect_person_applies(- filters: &TeamFilters,- evaluator: &mut CohortEvaluator,- person: PersonResolution,- memo: &mut PersonMemo,- applies: &mut Vec<Apply>,-) {- match person {- PersonResolution::Inactive => {}- PersonResolution::Cached(cached) => {- read_person_conditions_cached(filters, &cached, applies);- }- PersonResolution::Evaluate { globals, receipt } => {- evaluator.set_globals(globals);- let results = eval_person_conditions(filters, evaluator, applies);- memo.store(receipt, results);- }- }-}--/// Memo miss: evaluate the person conditions in stable order, recording results into a bitset for-/// the caller to cache.+/// Evaluate the person conditions in stable order, returning the TRUE set and the effective catalog+/// slice — the subset of `person_conditions_ordered` that has bytecode and a `PersonProperty`-variant+/// LSK meta. Both are the same filtered subset, so passing the effective catalog to+/// [`apply_eval`]/[`MatchedSet::diff`] means a defensively-skipped hash in the stored set is never+/// diffed and never emits a spurious `Left`.fn eval_person_conditions(filters: &TeamFilters,evaluator: &mut CohortEvaluator,- applies: &mut Vec<Apply>,-) -> ConditionBitset {- let mut results = ConditionBitset::zeros(filters.person_conditions_ordered.len());- for (idx, &hash) in filters.person_conditions_ordered.iter().enumerate() {+) -> (MatchedSet, Vec<[u8; 16]>) {+ let mut true_hashes: Vec<[u8; 16]> = Vec::new();+ let mut effective_catalog: Vec<[u8; 16]> = Vec::new();+ for &hash in &filters.person_conditions_ordered {let Some(bytecode) = filters.by_condition_to_bytecode.get(&hash) else {continue;};- counter!(STAGE1_CONDITIONS_EVALUATED, "kind" => "person_property").increment(1);- let matches = evaluator.evaluate(Arc::clone(bytecode));- if matches {- results.set(idx);- }- push_person_apply(filters, hash, matches, applies);- }- results-}--/// Memo hit: push applies from the cached bits. The bytecode-presence skip mirrors the eval path so-/// the `Apply` multiset matches a miss.-fn read_person_conditions_cached(- filters: &TeamFilters,- cached: &ConditionBitset,- applies: &mut Vec<Apply>,-) {- for (idx, &hash) in filters.person_conditions_ordered.iter().enumerate() {- if !filters.by_condition_to_bytecode.contains_key(&hash) {- continue;- }- counter!(STAGE1_CONDITIONS_SKIPPED, "reason" => "person_memo_hit").increment(1);- push_person_apply(filters, hash, cached.get(idx), applies);- }-}--/// Push one person condition's `Apply` behind the catalog variant guard. Shared by all three person-/// paths so the guard is identical across them.-fn push_person_apply(- filters: &TeamFilters,- hash: [u8; 16],- matches: bool,- applies: &mut Vec<Apply>,-) {- let lsk = LeafStateKey::for_person_property(&hash);- match filters.by_lsk.get(&lsk).map(|meta| meta.variant) {- Some(StateVariant::PersonProperty) => {- applies.push(Apply::Person {- lsk,- condition_hash: hash,- matches,- });+ // A hash whose LSK meta is missing or not a `PersonProperty` variant is skipped, so it is not+ // part of the effective catalog.+ let lsk = LeafStateKey::for_person_property(&hash);+ match filters.by_lsk.get(&lsk).map(|meta| meta.variant) {+ Some(StateVariant::PersonProperty) => {}+ Some(other) => {+ counter!(STAGE1_UNSUPPORTED_VARIANT_SKIPPED, "variant" => other.as_str())+ .increment(1);+ continue;+ }+ None => continue,}- Some(other) => {- counter!(STAGE1_UNSUPPORTED_VARIANT_SKIPPED, "variant" => other.as_str()).increment(1);+ counter!(STAGE1_CONDITIONS_EVALUATED, "kind" => "person_property").increment(1);+ // `person_conditions_ordered` is sorted, so pushing in iteration order keeps the effective+ // catalog sorted for the binary searches in `diff`/`apply_eval`.+ effective_catalog.push(hash);+ if evaluator.evaluate(Arc::clone(bytecode)) {+ true_hashes.push(hash);}- None => {}}+ (MatchedSet::from_iter(true_hashes), effective_catalog)}/// Fold a behavioral match into a single-bit leaf. Never emits `Left` (match is never cleared).@@ -1152,103 +1248,3 @@ fn mutate_behavioral_compressed(});Some((record, transition))}--/// Fold a person-property evaluation into a leaf's state with replay-dedup and argMax tiebreaker.-#[allow(clippy::too_many_arguments)]-fn mutate_person(- lsk: LeafStateKey,- condition_hash: [u8; 16],- matches: bool,- person_id: Uuid,- origin: Option<&Uuid>,- event: &CohortStreamEvent,- event_ms: i64,- prev: Option<StatefulRecord>,-) -> Option<(StatefulRecord, Option<LeafTransition>)> {- let (prev_matches, prev_updated_at, prev_updated_offset, mut applied, mut redirect_dedup) =- match prev {- None => (- false,- i64::MIN,- i64::MIN,- AppliedOffsets::default(),- BTreeMap::new(),- ),- Some(record) => match record.state {- Stage1State::PersonProperty {- matches,- last_updated_at_ms,- last_updated_offset,- } => (- matches,- last_updated_at_ms,- last_updated_offset,- record.applied_offsets,- record.redirect_dedup,- ),- _ => {- counter!(STAGE1_STATE_DECODE_ERROR).increment(1);- return None;- }- },- };-- if dedup_is_replay(- &applied,- &redirect_dedup,- origin,- event.source_partition,- event.source_offset,- ) {- counter!(STAGE1_REPLAY_SKIPPED, "variant" => StateVariant::PersonProperty.as_str())- .increment(1);- return None;- }- dedup_record(- &mut applied,- &mut redirect_dedup,- origin,- event.source_partition,- event.source_offset,- );-- if (event_ms, event.source_offset) <= (prev_updated_at, prev_updated_offset) {- counter!(STAGE1_ARGMAX_STALE).increment(1);- let record = StatefulRecord {- state: Stage1State::PersonProperty {- matches: prev_matches,- last_updated_at_ms: prev_updated_at,- last_updated_offset: prev_updated_offset,- },- applied_offsets: applied,- redirect_dedup,- };- return Some((record, None));- }-- let record = StatefulRecord {- state: Stage1State::PersonProperty {- matches,- last_updated_at_ms: event_ms,- last_updated_offset: event.source_offset,- },- applied_offsets: applied,- redirect_dedup,- };- let transition = if matches == prev_matches {- None- } else {- Some(LeafTransition {- team_id: TeamId(event.team_id),- leaf_state_key: lsk,- person_id,- condition_hash,- kind: if matches {- TransitionKind::Entered- } else {- TransitionKind::Left- },- })- };- Some((record, transition))-}diff --git a/rust/cohort-stream-processor/src/workers/merge_path.rs b/rust/cohort-stream-processor/src/workers/merge_path.rsindex 249fc3c9cc9e..58b82f921a8c 100644--- a/rust/cohort-stream-processor/src/workers/merge_path.rs+++ b/rust/cohort-stream-processor/src/workers/merge_path.rs@@ -30,9 +30,8 @@ use crate::producer::{map_transition, CaptureCascadeSink, CaptureStreamEventSink, CaptureTransferSink, CascadeSink,CohortMembershipChange, MembershipSink, StreamEventSink, TransferSink,};-use crate::stage1::key::Stage1Key;use crate::stage1::transition::LeafTransition;-use crate::store::{PendingTransferKey, StoreHandle};+use crate::store::{BehavioralKey, PendingTransferKey, StoreHandle};use crate::sweep::EvictionQueue;use crate::workers::stage2_path::compose_stage2;use crate::workers::worker::{@@ -146,7 +145,7 @@ pub(crate) async fn handle_merge(catalog: &CatalogHandle,sink: &Arc<dyn MembershipSink>,merge: &MergeWorkerDeps,- queue: &mut EvictionQueue<Stage1Key>,+ queue: &mut EvictionQueue<BehavioralKey>,last_updated: &str,event: &PersonMergeEvent,offset: i64,@@ -241,7 +240,9 @@ pub(crate) async fn handle_merge(}Ok(DrainOutcome::Drained { transfer, effects }) => {effects.apply_to(queue);- if transfer.leaves.is_empty() {+ // Nothing to apply without leaves or a person-record dedup — skip the produce. A record-only+ // transfer still produces so P_new absorbs the ancestry (matches the drain's staging).+ if transfer.leaves.is_empty() && transfer.person_dedup.is_none() {counter!(MERGE_TRANSFERS_SKIPPED_EMPTY_TOTAL).increment(1);mark_processed(&merge.merge_tracker, partition_id, offset);return;@@ -315,7 +316,7 @@ pub(crate) async fn handle_apply(catalog: &CatalogHandle,sink: &Arc<dyn MembershipSink>,merge: &MergeWorkerDeps,- queue: &mut EvictionQueue<Stage1Key>,+ queue: &mut EvictionQueue<BehavioralKey>,last_updated: &str,transfer: &MergeStateTransfer,offset: i64,@@ -805,6 +806,8 @@ mod tests {source_offset: 0,leaves: vec![],forward_hops: 0,++ person_dedup: None,};let acked =@@ -831,6 +834,8 @@ mod tests {source_offset: 0,leaves: vec![],forward_hops: 0,++ person_dedup: None,};let acked =@@ -888,6 +893,8 @@ mod tests {),)],forward_hops: 0,++ person_dedup: None,};let key = PendingTransferKey {partition_id: REDRIVE_PARTITION,@@ -1073,6 +1080,8 @@ mod tests {source_offset: 100,leaves: vec![],forward_hops: 1,++ person_dedup: None,}}diff --git a/rust/cohort-stream-processor/src/workers/mod.rs b/rust/cohort-stream-processor/src/workers/mod.rsindex 3740ea2ec63d..b148e89cc1de 100644--- a/rust/cohort-stream-processor/src/workers/mod.rs+++ b/rust/cohort-stream-processor/src/workers/mod.rs@@ -4,20 +4,18 @@ pub mod cascade_path;pub mod event_path;pub mod merge_gc;pub mod merge_path;-pub mod person_memo;pub mod stage2_gc;pub mod stage2_path;pub mod sweep_callback;pub mod worker;pub use event_path::{- process_event, process_event_with_memo, EventNameGating, EventOutcome, SkipReason,+ process_event, process_event_gated, EventNameGating, EventOutcome, SkipReason,};pub use merge_gc::{handle_merge_gc, MergeGcCursor};pub use merge_path::{CascadeConfig, MergeWorkerDeps, TransferRetryPolicy, DEFAULT_MERGE_GC_SCAN_LIMIT,};-pub use person_memo::{PersonMemo, PersonMemoConfig};pub use stage2_gc::{handle_stage2_orphan_gc, Stage2GcCursor};pub use stage2_path::compose_stage2;pub use worker::Stage1Worker;diff --git a/rust/cohort-stream-processor/src/workers/person_memo.rs b/rust/cohort-stream-processor/src/workers/person_memo.rsdeleted file mode 100644index 59ea15af7f6c..000000000000--- a/rust/cohort-stream-processor/src/workers/person_memo.rs+++ /dev/null@@ -1,294 +0,0 @@-//! Per-worker memoization of person-property condition results.-//!-//! A person-property leaf's result is a pure function of `(catalog generation, person_properties)`:-//! the person globals carry no clock and the STL has no `now()`. So a person's per-condition-//! `matches` bits can be cached and reused while its raw `person_properties` are unchanged, skipping-//! the JSON parse and the HogVM evaluations. A catalog change bumps the generation, invalidating-//! every entry.--use std::num::NonZeroUsize;--use lru::LruCache;-use metrics::counter;-use sha2::{Digest, Sha256};-use uuid::Uuid;--use crate::filters::{Generation, TeamId};-use crate::observability::metrics::STAGE1_PERSON_MEMO;--#[derive(Clone, Copy, Debug)]-pub struct PersonMemoConfig {- pub enabled: bool,- pub capacity: usize,-}--impl PersonMemoConfig {- pub const DISABLED: Self = Self {- enabled: false,- capacity: 0,- };-}--/// `team` keeps persons from different teams distinct on a shared worker.-#[derive(Clone, Copy, PartialEq, Eq, Hash)]-pub(crate) struct PersonKey {- pub team: TeamId,- pub person: Uuid,-}--/// A cached result's validity: an entry is current iff its stamp equals the lookup's, so `==` is the-/// invalidation rule. The generation also guarantees the bits align with the current-/// `person_conditions_ordered`.-#[derive(Clone, Copy, PartialEq, Eq)]-struct Stamp {- generation: Generation,- fingerprint: PropsFingerprint,-}--/// 128 bits of SHA-256 over the raw props — collision-negligible, and computable without a JSON parse.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-struct PropsFingerprint(u128);--impl PropsFingerprint {- fn of(raw: &str) -> Self {- let digest = Sha256::digest(raw.as_bytes());- Self(u128::from_le_bytes(- digest[..16].try_into().expect("SHA-256 yields 32 bytes"),- ))- }-}--struct MemoEntry {- stamp: Stamp,- results: ConditionBitset,-}--/// Person-condition results, one bit per position in `person_conditions_ordered`.-#[derive(Clone, Debug, PartialEq, Eq)]-pub(crate) struct ConditionBitset {- bits: Box<[u8]>,- len: usize,-}--impl ConditionBitset {- pub(crate) fn zeros(len: usize) -> Self {- Self {- bits: vec![0u8; len.div_ceil(8)].into_boxed_slice(),- len,- }- }-- pub(crate) fn set(&mut self, idx: usize) {- debug_assert!(idx < self.len);- self.bits[idx / 8] |= 1 << (idx % 8);- }-- pub(crate) fn get(&self, idx: usize) -> bool {- debug_assert!(idx < self.len);- self.bits[idx / 8] & (1 << (idx % 8)) != 0- }-}--/// The outcome of [`PersonMemo::probe`].-pub(crate) enum Lookup {- /// The cached results are current; reuse them.- Hit(ConditionBitset),- /// Evaluate, then redeem the [`Receipt`] with the fresh results.- Miss(Receipt),-}--/// Proof of a miss carrying the `(key, stamp)` to cache under, so [`PersonMemo::store`] can only-/// write what was probed. `None` when the memo is disabled, making the write a no-op.-pub(crate) struct Receipt(Option<(PersonKey, Stamp)>);--/// `None` cache means disabled (no allocation).-pub struct PersonMemo {- cache: Option<LruCache<PersonKey, MemoEntry>>,-}--impl PersonMemo {- pub fn new(config: PersonMemoConfig) -> Self {- let cache = config.enabled.then(|| {- // Clamp so a misconfigured `0` still caches one entry rather than panicking.- LruCache::new(NonZeroUsize::new(config.capacity.max(1)).expect("capacity is >= 1"))- });- Self { cache }- }-- pub fn disabled() -> Self {- Self { cache: None }- }-- /// Consult the memo for `key` at the current `generation` and props. A stale, absent, or disabled- /// entry is a [`Lookup::Miss`]; the fingerprint is computed only when enabled, so the kill-switch- /// costs no hash.- pub(crate) fn probe(&mut self, key: PersonKey, generation: Generation, raw: &str) -> Lookup {- let Some(cache) = self.cache.as_mut() else {- return Lookup::Miss(Receipt(None));- };- let stamp = Stamp {- generation,- fingerprint: PropsFingerprint::of(raw),- };- if let Some(entry) = cache.get(&key) {- if entry.stamp == stamp {- counter!(STAGE1_PERSON_MEMO, "result" => "hit").increment(1);- return Lookup::Hit(entry.results.clone());- }- }- counter!(STAGE1_PERSON_MEMO, "result" => "miss").increment(1);- Lookup::Miss(Receipt(Some((key, stamp))))- }-- /// Cache `results` under a miss receipt; a no-op when the receipt came from a disabled memo.- pub(crate) fn store(&mut self, receipt: Receipt, results: ConditionBitset) {- if let (Some(cache), Receipt(Some((key, stamp)))) = (self.cache.as_mut(), receipt) {- cache.put(key, MemoEntry { stamp, results });- }- }-}--#[cfg(test)]-mod tests {- use super::*;-- fn config(capacity: usize) -> PersonMemoConfig {- PersonMemoConfig {- enabled: true,- capacity,- }- }-- fn key(team: i32, person: u128) -> PersonKey {- PersonKey {- team: TeamId(team),- person: Uuid::from_u128(person),- }- }-- /// Probe (asserting a miss) and cache `results` under the returned receipt.- fn seed(- memo: &mut PersonMemo,- key: PersonKey,- gen: Generation,- raw: &str,- results: ConditionBitset,- ) {- let Lookup::Miss(receipt) = memo.probe(key, gen, raw) else {- panic!("expected a miss for a fresh entry");- };- memo.store(receipt, results);- }-- fn hit_bits(- memo: &mut PersonMemo,- key: PersonKey,- gen: Generation,- raw: &str,- ) -> ConditionBitset {- match memo.probe(key, gen, raw) {- Lookup::Hit(bits) => bits,- Lookup::Miss(_) => panic!("expected a hit"),- }- }-- #[test]- fn bitset_roundtrips_each_bit_and_packs_to_ceil_div_8() {- let mut bits = ConditionBitset::zeros(10);- assert_eq!(bits.bits.len(), 2, "10 bits pack into 2 bytes");- for idx in [0, 3, 7, 8, 9] {- bits.set(idx);- }- for idx in 0..10 {- assert_eq!(bits.get(idx), [0, 3, 7, 8, 9].contains(&idx), "bit {idx}");- }- }-- #[test]- fn zero_length_bitset_allocates_nothing() {- assert!(ConditionBitset::zeros(0).bits.is_empty());- }-- #[test]- fn disabled_memo_never_caches() {- let mut memo = PersonMemo::disabled();- seed(- &mut memo,- key(7, 1),- Generation(1),- "p",- ConditionBitset::zeros(3),- );- assert!(matches!(- memo.probe(key(7, 1), Generation(1), "p"),- Lookup::Miss(_)- ));- }-- #[test]- fn hit_requires_matching_generation_props_and_team() {- let mut memo = PersonMemo::new(config(8));- let mut results = ConditionBitset::zeros(2);- results.set(1);- seed(- &mut memo,- key(7, 1),- Generation(5),- "props-A",- results.clone(),- );-- assert_eq!(- hit_bits(&mut memo, key(7, 1), Generation(5), "props-A"),- results- );- assert!(matches!(- memo.probe(key(7, 1), Generation(6), "props-A"),- Lookup::Miss(_)- ));- assert!(matches!(- memo.probe(key(7, 1), Generation(5), "props-B"),- Lookup::Miss(_)- ));- assert!(matches!(- memo.probe(key(8, 1), Generation(5), "props-A"),- Lookup::Miss(_)- ));- }-- #[test]- fn a_new_generation_overwrites_the_stale_entry() {- let mut memo = PersonMemo::new(config(8));- seed(- &mut memo,- key(7, 1),- Generation(5),- "p",- ConditionBitset::zeros(2),- );- let mut fresh = ConditionBitset::zeros(2);- fresh.set(0);- seed(&mut memo, key(7, 1), Generation(6), "p", fresh.clone());- assert_eq!(hit_bits(&mut memo, key(7, 1), Generation(6), "p"), fresh);- }-- #[test]- fn lru_evicts_the_least_recently_used_entry() {- let mut memo = PersonMemo::new(config(2));- let g = Generation(1);- seed(&mut memo, key(7, 1), g, "a", ConditionBitset::zeros(1));- seed(&mut memo, key(7, 2), g, "b", ConditionBitset::zeros(1));- // Touch entry 1 so entry 2 becomes the eviction victim.- assert!(matches!(memo.probe(key(7, 1), g, "a"), Lookup::Hit(_)));- seed(&mut memo, key(7, 3), g, "c", ConditionBitset::zeros(1));- assert!(matches!(memo.probe(key(7, 2), g, "b"), Lookup::Miss(_)));- assert!(matches!(memo.probe(key(7, 1), g, "a"), Lookup::Hit(_)));- assert!(matches!(memo.probe(key(7, 3), g, "c"), Lookup::Hit(_)));- }-- #[test]- fn fingerprint_is_stable_and_sensitive() {- assert_eq!(PropsFingerprint::of("x"), PropsFingerprint::of("x"));- assert_ne!(PropsFingerprint::of("x"), PropsFingerprint::of("y"));- }-}diff --git a/rust/cohort-stream-processor/src/workers/stage2_path.rs b/rust/cohort-stream-processor/src/workers/stage2_path.rsindex 38697ece8d06..8183a37d496c 100644--- a/rust/cohort-stream-processor/src/workers/stage2_path.rs+++ b/rust/cohort-stream-processor/src/workers/stage2_path.rs@@ -17,13 +17,16 @@ use crate::observability::metrics::{STAGE2_COHORTS_EVALUATED, STAGE2_STATE_DECODE_ERROR, STAGE2_TRANSITIONS,};use crate::producer::{CohortMembershipChange, MembershipStatus};-use crate::stage1::key::{LeafStateKey, Stage1Key};-use crate::stage1::state::{Stage1State, StatefulRecord};+use crate::stage1::key::LeafStateKey;+use crate::stage1::person_record::PersonRecord;+use crate::stage1::state::{Stage1State, StateVariant, StatefulRecord};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::{ReadLane, Stage2Key, StagedBatch, StoreError, StoreHandle};+use crate::store::{+ BehavioralKey, PersonRecordKey, ReadLane, Stage2Key, StagedBatch, StoreError, StoreHandle,+};pub async fn compose_stage2(partition_id: u16,@@ -156,34 +159,134 @@ async fn evaluate_cohort(let mut lsks = Vec::new();collect_leaf_state_keys(&tree.root, &mut lsks);- let keys: Vec<Stage1Key> = lsks- .iter()- .map(|&lsk| Stage1Key {+ let resolver = LeafMembershipResolver::new(partition_id, team_id, person_id, filters, handle);+ let membership = resolver.resolve(&lsks).await?;++ let ref_membership =+ resolve_ref_membership(partition_id, team_id, person_id, tree, filters, handle).await?;++ Ok(evaluate_tree(&tree.root, &membership, &ref_membership))+}++/// Turns a person's leaf-state keys into per-leaf membership bits, partitioned by the leaf's+/// [`StateVariant`]: behavioral leaves resolve from `cf_behavioral` rows via [`leaf_membership`] (so+/// each leaf's comparator applies), person-property leaves from the durable+/// [`PersonRecord`](crate::stage1::PersonRecord) — a person LSK *is* its condition hash, so membership+/// is `record.matched.contains(hash)`. Keys whose leaf is absent from the frozen catalog are+/// non-member.+struct LeafMembershipResolver<'a> {+ partition_id: u16,+ team_id: u64,+ person_id: Uuid,+ filters: &'a TeamFilters,+ handle: &'a StoreHandle,+}++impl<'a> LeafMembershipResolver<'a> {+ fn new(+ partition_id: u16,+ team_id: u64,+ person_id: Uuid,+ filters: &'a TeamFilters,+ handle: &'a StoreHandle,+ ) -> Self {+ Self {partition_id,team_id,- leaf_state_key: lsk,person_id,- })- .collect();- let raw = handle.multi_get_stage1(keys, ReadLane::Event).await?;+ filters,+ handle,+ }+ }- let mut membership: HashMap<LeafStateKey, bool> = HashMap::with_capacity(lsks.len());- for (lsk, bytes) in lsks.iter().zip(raw) {- let Some(meta) = filters.by_lsk.get(lsk) else {- continue;- };- let state = decode_stage1_state(bytes);- membership.insert(*lsk, leaf_membership(state.as_ref(), meta));+ async fn resolve(+ &self,+ lsks: &[LeafStateKey],+ ) -> Result<HashMap<LeafStateKey, bool>, StoreError> {+ let mut behavioral_lsks = Vec::new();+ let mut person_lsks = Vec::new();+ for &lsk in lsks {+ match self.filters.by_lsk.get(&lsk).map(|meta| meta.variant) {+ None => continue,+ Some(StateVariant::PersonProperty) => person_lsks.push(lsk),+ // Exhaustive (no wildcard) so a future membership source resolving from another store+ // fails to compile here instead of being silently misrouted into `cf_behavioral`.+ Some(+ StateVariant::BehavioralSingle+ | StateVariant::BehavioralDailyBuckets+ | StateVariant::BehavioralCompressedHistory,+ ) => behavioral_lsks.push(lsk),+ }+ }++ let mut membership = HashMap::with_capacity(behavioral_lsks.len() + person_lsks.len());+ self.read_behavioral_into(&behavioral_lsks, &mut membership)+ .await?;+ self.read_person_into(&person_lsks, &mut membership).await?;+ Ok(membership)}- let ref_membership =- resolve_ref_membership(partition_id, team_id, person_id, tree, filters, handle).await?;+ async fn read_behavioral_into(+ &self,+ lsks: &[LeafStateKey],+ out: &mut HashMap<LeafStateKey, bool>,+ ) -> Result<(), StoreError> {+ if lsks.is_empty() {+ return Ok(());+ }+ let keys: Vec<BehavioralKey> = lsks+ .iter()+ .map(|&lsk| BehavioralKey::new(self.partition_id, self.team_id, self.person_id, lsk))+ .collect();+ let raw = self+ .handle+ .multi_get_behavioral(keys, ReadLane::Event)+ .await?;+ for (&lsk, bytes) in lsks.iter().zip(raw) {+ let Some(meta) = self.filters.by_lsk.get(&lsk) else {+ continue;+ };+ let state = decode_stage1_state(bytes);+ out.insert(lsk, leaf_membership(state.as_ref(), meta));+ }+ Ok(())+ }- Ok(evaluate_tree(&tree.root, &membership, &ref_membership))+ /// Resolve person-property `lsks` from the person's one durable record via a single point read: a+ /// person LSK is its condition hash, so its bit is `record.matched.contains(hash)`. An absent or+ /// corrupt record reads every person leaf as non-member (a corrupt record counts+ /// `STAGE2_STATE_DECODE_ERROR`).+ async fn read_person_into(+ &self,+ lsks: &[LeafStateKey],+ out: &mut HashMap<LeafStateKey, bool>,+ ) -> Result<(), StoreError> {+ if lsks.is_empty() {+ return Ok(());+ }+ let key = PersonRecordKey::new(self.partition_id, self.team_id, self.person_id);+ let matched = match self.handle.get_person_record(&key).await? {+ None => None,+ Some(bytes) => match PersonRecord::decode(&bytes) {+ Ok(record) => Some(record.matched),+ Err(_) => {+ counter!(STAGE2_STATE_DECODE_ERROR).increment(1);+ None+ }+ },+ };+ for &lsk in lsks {+ let member = matched+ .as_ref()+ .is_some_and(|matched| matched.contains(&lsk.0));+ out.insert(lsk, member);+ }+ Ok(())+ }}/// Resolve each referenced cohort's membership for one person, keyed by referenced cohort id.-/// A `SingleLeaf` referent is read from `cf_stage1` via [`leaf_membership`] (so its comparator+/// A `SingleLeaf` referent is read from `cf_behavioral` 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.async fn resolve_ref_membership(@@ -217,23 +320,14 @@ async fn resolve_ref_membership(}if !single_leaf_refs.is_empty() {- let keys: Vec<Stage1Key> = single_leaf_refs- .iter()- .map(|(_, lsk)| Stage1Key {- partition_id,- team_id,- leaf_state_key: *lsk,- person_id,- })- .collect();- 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- .get(lsk)- .map(|meta| leaf_membership(decode_stage1_state(bytes).as_ref(), meta))- .unwrap_or(false);- ref_membership.insert(*ref_id, bit);+ // Resolve single-leaf referents through the same seam as the cohort's own leaves, so both+ // apply the leaf's comparator identically.+ let resolver =+ LeafMembershipResolver::new(partition_id, team_id, person_id, filters, handle);+ let lsks: Vec<LeafStateKey> = single_leaf_refs.iter().map(|(_, lsk)| *lsk).collect();+ let membership = resolver.resolve(&lsks).await?;+ for (ref_id, lsk) in &single_leaf_refs {+ ref_membership.insert(*ref_id, membership.get(lsk).copied().unwrap_or(false));}}@@ -256,7 +350,7 @@ async fn resolve_ref_membership(Ok(ref_membership)}-/// Decode a `cf_stage1` value, or [`None`] for absent/undecodable rows.+/// Decode a `cf_behavioral` value, or [`None`] for absent/undecodable rows.fn decode_stage1_state(bytes: Option<Vec<u8>>) -> Option<Stage1State> {let bytes = bytes?;match StatefulRecord::decode(&bytes) {@@ -328,9 +422,13 @@ mod tests {use uuid::Uuid;use crate::filters::{CohortId, TeamFiltersBuilder, TeamId};+ use crate::stage1::person_record::{MatchedSet, PersonRecord};use crate::stage1::state::AppliedOffsets;use crate::stage1::transition::TransitionKind;- use crate::store::{CohortStore, OffloadConfig, OffloadMode, StoreConfig};+ use crate::store::{+ Behavioral, CohortStore, OffloadConfig, OffloadMode, PersonRecordKey, PersonRecords,+ StoreConfig,+ };const TEAM: u64 = 7;const PARTITION: u16 = 0;@@ -420,24 +518,29 @@ mod tests {}}- fn person_state(matches: bool) -> Stage1State {- Stage1State::PersonProperty {- matches,- last_updated_at_ms: EVENT_MS,- last_updated_offset: 0,- }+ fn write_behavioral(store: &CohortStore, lsk: LeafStateKey, who: Uuid, state: Stage1State) {+ let key = BehavioralKey::new(PARTITION, TEAM, who, lsk);+ let record = StatefulRecord::new(state, AppliedOffsets::default());+ store+ .write_batch(|b| b.put::<Behavioral>(&key, &record.encode()))+ .unwrap();}- fn write_stage1(store: &CohortStore, lsk: LeafStateKey, who: Uuid, state: Stage1State) {- let key = Stage1Key {- partition_id: PARTITION,- team_id: TEAM,- leaf_state_key: lsk,- person_id: who,- };- let record = StatefulRecord::new(state, AppliedOffsets::default());+ fn write_person_record(store: &CohortStore, who: Uuid, matched: &[[u8; 16]]) {+ let key = PersonRecordKey::new(PARTITION, TEAM, who);+ let mut record = PersonRecord::absent();+ record.matched = MatchedSet::from_iter(matched.iter().copied());store- .write_batch(|b| b.put_stage1(&key, &record.encode()))+ .write_batch(|b| b.put::<PersonRecords>(&key, &record.encode()))+ .unwrap();+ }++ /// Write bytes that fail `PersonRecord::decode` (byte 0 is not the format version) to the person's+ /// record key, so the compose read path takes its corrupt-record arm.+ fn write_corrupt_person_record(store: &CohortStore, who: Uuid) {+ let key = PersonRecordKey::new(PARTITION, TEAM, who);+ store+ .write_batch(|b| b.put::<PersonRecords>(&key, b"not a valid person record")).unwrap();}@@ -480,11 +583,11 @@ mod tests {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);+ let (beh_lsk, _per_lsk) = and_leaf_keys(&filters);let alice = person(1);- write_stage1(&store, beh_lsk, alice, behavioral_match());- write_stage1(&store, per_lsk, alice, person_state(true));+ write_behavioral(&store, beh_lsk, alice, behavioral_match());+ write_person_record(&store, alice, &[PERSON_HASH]);let changes = compose_stage2(PARTITION,@@ -506,6 +609,42 @@ mod tests {assert_eq!(stage2_bit(&store, 1, alice), Some(true), "bit committed");}+ #[tokio::test]+ async fn corrupt_person_record_composes_as_non_member() {+ // A record whose bytes fail to decode must read as non-member on the compose path (never a+ // stale/garbage bit), so the AND cannot enter. Sibling to `entered_when_the_and_is_satisfied`+ // with the person record corrupted; a regression here would silently drop a still-matching+ // member from every person-property cohort.+ let (_dir, store) = temp_store();+ let filters = freeze(vec![behavioral_leaf(7), person_leaf()]);+ let (beh_lsk, _per_lsk) = and_leaf_keys(&filters);+ let alice = person(1);++ write_behavioral(&store, beh_lsk, alice, behavioral_match());+ write_corrupt_person_record(&store, alice);++ let changes = compose_stage2(+ PARTITION,+ &handle(&store),+ &filters,+ &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],+ EVENT_MS,+ TS,+ )+ .await+ .unwrap();++ assert!(+ changes.is_empty(),+ "a corrupt person record reads as non-member, so the AND does not enter",+ );+ assert_eq!(+ stage2_bit(&store, 1, alice),+ None,+ "no membership bit is written",+ );+ }+#[tokio::test]async fn no_emit_until_the_second_leaf_flips() {let (_dir, store) = temp_store();@@ -513,7 +652,7 @@ mod tests {let (beh_lsk, per_lsk) = and_leaf_keys(&filters);let alice = person(1);- write_stage1(&store, beh_lsk, alice, behavioral_match());+ write_behavioral(&store, beh_lsk, alice, behavioral_match());let phase_a = compose_stage2(PARTITION,&handle(&store),@@ -531,7 +670,7 @@ mod tests {"no bit written on a non-flip");- write_stage1(&store, per_lsk, alice, person_state(true));+ write_person_record(&store, alice, &[PERSON_HASH]);let phase_b = compose_stage2(PARTITION,&handle(&store),@@ -559,8 +698,8 @@ mod tests {let (beh_lsk, per_lsk) = and_leaf_keys(&filters);let alice = person(1);- write_stage1(&store, beh_lsk, alice, behavioral_match());- write_stage1(&store, per_lsk, alice, person_state(true));+ write_behavioral(&store, beh_lsk, alice, behavioral_match());+ write_person_record(&store, alice, &[PERSON_HASH]);let entered = compose_stage2(PARTITION,&handle(&store),@@ -574,7 +713,7 @@ mod tests {assert_eq!(entered.len(), 1);assert_eq!(entered[0].status, MembershipStatus::Entered);- write_stage1(&store, per_lsk, alice, person_state(false));+ write_person_record(&store, alice, &[]);let left = compose_stage2(PARTITION,&handle(&store),@@ -603,10 +742,10 @@ mod tests {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);+ let (beh_lsk, _per_lsk) = and_leaf_keys(&filters);let alice = person(1);- write_stage1(&store, beh_lsk, alice, behavioral_match());- write_stage1(&store, per_lsk, alice, person_state(true));+ write_behavioral(&store, beh_lsk, alice, behavioral_match());+ write_person_record(&store, alice, &[PERSON_HASH]);let first = compose_stage2(PARTITION,@@ -643,8 +782,8 @@ mod tests {let lsks = &filters.by_condition_to_lsk[&HASH];assert_eq!(lsks.len(), 2, "two windows fan out to two LSKs");let alice = person(1);- write_stage1(&store, lsks[0], alice, behavioral_match());- write_stage1(&store, lsks[1], alice, behavioral_match());+ write_behavioral(&store, lsks[0], alice, behavioral_match());+ write_behavioral(&store, lsks[1], alice, behavioral_match());let changes = compose_stage2(PARTITION,@@ -673,10 +812,9 @@ mod tests {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];- let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);let alice = person(1);- write_stage1(&store, beh_lsk, alice, daily_state(2));- write_stage1(&store, per_lsk, alice, person_state(true));+ write_behavioral(&store, beh_lsk, alice, daily_state(2));+ write_person_record(&store, alice, &[PERSON_HASH]);let changes = compose_stage2(PARTITION,@@ -697,8 +835,8 @@ mod tests {assert_eq!(changes[0].cohort_id, 1);let (_dir2, store2) = temp_store();- write_stage1(&store2, beh_lsk, alice, daily_state(1)); // 1 < gte 2- write_stage1(&store2, per_lsk, alice, person_state(true));+ write_behavioral(&store2, beh_lsk, alice, daily_state(1)); // 1 < gte 2+ write_person_record(&store2, alice, &[PERSON_HASH]);let below = compose_stage2(PARTITION,&handle(&store2),@@ -721,7 +859,7 @@ mod tests {let filters = freeze(vec![behavioral_leaf(7)]);let beh_lsk = filters.by_condition_to_lsk[&HASH][0];let alice = person(1);- write_stage1(&store, beh_lsk, alice, behavioral_match());+ write_behavioral(&store, beh_lsk, alice, behavioral_match());let changes = compose_stage2(PARTITION,@@ -755,7 +893,7 @@ mod tests {let (beh_lsk, _per_lsk) = and_leaf_keys(&filters);let alice = person(1);- write_stage1(&store, beh_lsk, alice, behavioral_match());+ write_behavioral(&store, beh_lsk, alice, behavioral_match());let changes = compose_stage2(PARTITION,@@ -778,7 +916,7 @@ mod tests {let (beh_lsk, per_lsk) = and_leaf_keys(&filters);let alice = person(1);- write_stage1(&store, beh_lsk, alice, behavioral_match());+ write_behavioral(&store, beh_lsk, alice, behavioral_match());let entered = compose_stage2(PARTITION,&handle(&store),@@ -792,7 +930,7 @@ mod tests {assert_eq!(entered.len(), 1);assert_eq!(entered[0].status, MembershipStatus::Entered);- write_stage1(&store, per_lsk, alice, person_state(true));+ write_person_record(&store, alice, &[PERSON_HASH]);let left = compose_stage2(PARTITION,&handle(&store),@@ -882,7 +1020,7 @@ mod tests {}#[tokio::test]- async fn composable_ref_reads_a_single_leaf_referent_from_cf_stage1_via_its_op() {+ async fn composable_ref_reads_a_single_leaf_referent_from_cf_behavioral_via_its_op() {let filters = freeze_cascade(vec![(2, vec![daily_leaf(7, "gte", 2)]),@@ -895,13 +1033,12 @@ mod tests {CohortEligibility::Stage2ComposableRef,);let ref2_lsk = single_leaf_lsk(&filters, 2);- let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);let alice = person(1);// Count 2 ≥ gte 2: referent 2 is a member.let (_dir, store) = temp_store();- write_stage1(&store, ref2_lsk, alice, daily_state(2));- write_stage1(&store, per_lsk, alice, person_state(true));+ write_behavioral(&store, ref2_lsk, alice, daily_state(2));+ write_person_record(&store, alice, &[PERSON_HASH]);let entered = compose_referrer_on_own_leaf(&handle(&store), &filters, alice).await;assert_eq!(entered.len(), 1);assert_eq!(entered[0].cohort_id, 1);@@ -909,8 +1046,8 @@ mod tests {// Count 1 < gte 2: the referent's comparator applies, so it is a non-member.let (_dir2, store2) = temp_store();- write_stage1(&store2, ref2_lsk, alice, daily_state(1));- write_stage1(&store2, per_lsk, alice, person_state(true));+ write_behavioral(&store2, ref2_lsk, alice, daily_state(1));+ write_person_record(&store2, alice, &[PERSON_HASH]);let below = compose_referrer_on_own_leaf(&handle(&store2), &filters, alice).await;assert!(below.is_empty(),@@ -932,14 +1069,13 @@ mod tests {filters.eligibility[&CohortId(2)],CohortEligibility::Stage2Composable,);- let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);let alice = person(1);let (_dir, store) = temp_store();- // cohort 2's cf_stage1 is left absent: a recompute would read non-member, so Entered proves+ // cohort 2's cf_behavioral is left absent: a recompute would read non-member, so Entered proves// the stored cf_stage2 bit is read.write_stage2(&store, 2, alice, true);- write_stage1(&store, per_lsk, alice, person_state(true));+ write_person_record(&store, alice, &[PERSON_HASH]);let entered = compose_referrer_on_own_leaf(&handle(&store), &filters, alice).await;assert_eq!(entered.len(), 1);@@ -956,11 +1092,10 @@ mod tests {],true,);- let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);let alice = person(1);let (_dir, store) = temp_store();- write_stage1(&store, per_lsk, alice, person_state(true));+ write_person_record(&store, alice, &[PERSON_HASH]);let changes = compose_referrer_on_own_leaf(&handle(&store), &filters, alice).await;assert!(changes.is_empty(),@@ -981,12 +1116,11 @@ mod tests {filters.eligibility[&CohortId(1)],CohortEligibility::Stage2ComposableRef,);- let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);let alice = person(1);// Referent 2 absent → negated ref reads true → Entered.let (_dir, store) = temp_store();- write_stage1(&store, per_lsk, alice, person_state(true));+ write_person_record(&store, alice, &[PERSON_HASH]);let entered = compose_referrer_on_own_leaf(&handle(&store), &filters, alice).await;assert_eq!(entered.len(), 1);assert_eq!(entered[0].cohort_id, 1);@@ -1005,12 +1139,11 @@ mod tests {false,);let ref2_lsk = single_leaf_lsk(&filters, 2);- let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);let alice = person(1);let (_dir, store) = temp_store();- write_stage1(&store, ref2_lsk, alice, daily_state(2));- write_stage1(&store, per_lsk, alice, person_state(true));+ write_behavioral(&store, ref2_lsk, alice, daily_state(2));+ write_person_record(&store, alice, &[PERSON_HASH]);let changes = compose_referrer_on_own_leaf(&handle(&store), &filters, alice).await;assert!(changes.is_empty(),diff --git a/rust/cohort-stream-processor/src/workers/sweep_callback.rs b/rust/cohort-stream-processor/src/workers/sweep_callback.rsindex e27e3272f14c..d89db4c5c615 100644--- a/rust/cohort-stream-processor/src/workers/sweep_callback.rs+++ b/rust/cohort-stream-processor/src/workers/sweep_callback.rs@@ -17,10 +17,10 @@ use crate::observability::metrics::{use crate::stage1::bucket_tz::{daily_bucket_len, day_idx_in_tz};use crate::stage1::compressed_history;use crate::stage1::daily::{daily_eviction_deadline, slide_window_forward};-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::BehavioralKey;/// The state mutation an eviction implies.#[derive(Debug, Clone, PartialEq, Eq)]@@ -34,7 +34,7 @@ pub(crate) enum EvictionAction {/// The outcome of evicting one key: optional transition, state mutation, and next deadline.#[derive(Debug, Clone, PartialEq, Eq)]pub(crate) struct EvictionResult {- pub key: Stage1Key,+ pub key: BehavioralKey,pub variant: StateVariant,pub transition: Option<LeafTransition>,pub action: EvictionAction,@@ -77,7 +77,7 @@ pub(crate) struct SweepEvictions {/// `filters`' team. Pure: no reads, no writes.pub(crate) fn sweep_evict(filters: &TeamFilters,- due_keys: &[Stage1Key],+ due_keys: &[BehavioralKey],values: Vec<Option<Vec<u8>>>,due_before_ms: i64,) -> SweepEvictions {@@ -85,7 +85,7 @@ pub(crate) fn sweep_evict(results: Vec::with_capacity(due_keys.len()),drops: Vec::new(),};- // Alignment-safe zip: `multi_get_stage1` preserves input order, `None` for absent keys.+ // Alignment-safe zip: `multi_get_behavioral` preserves input order, `None` for absent keys.for (&key, bytes) in due_keys.iter().zip(values) {let record = match bytes {None => {@@ -101,7 +101,7 @@ pub(crate) fn sweep_evict(}},};- let Some(meta) = filters.by_lsk.get(&key.leaf_state_key) else {+ let Some(meta) = filters.by_lsk.get(&key.lsk()) else {out.drops.push(SweepDropReason::LeafDrift);continue;};@@ -125,7 +125,7 @@ pub(crate) fn sweep_evict(/// Evict a `performed_event` single: always deletes.fn evict_single(- key: Stage1Key,+ key: BehavioralKey,meta: &LeafStateMeta,record: StatefulRecord,) -> Result<EvictionResult, SweepDropReason> {@@ -147,7 +147,7 @@ fn evict_single(/// Slide the daily window forward, recompute the predicate, and return the net membership flip./// Rewrites while any bucket survives; deletes when every bucket drains.fn evict_daily(- key: Stage1Key,+ key: BehavioralKey,meta: &LeafStateMeta,record: StatefulRecord,tz: Tz,@@ -226,7 +226,7 @@ fn evict_daily(/// Slide the compressed window forward and return the net membership flip (sparse run-length/// analog of [`evict_daily`]).fn evict_compressed(- key: Stage1Key,+ key: BehavioralKey,meta: &LeafStateMeta,record: StatefulRecord,tz: Tz,@@ -298,11 +298,15 @@ fn evict_compressed(})}-fn transition_for(key: Stage1Key, meta: &LeafStateMeta, kind: TransitionKind) -> LeafTransition {+fn transition_for(+ key: BehavioralKey,+ meta: &LeafStateMeta,+ kind: TransitionKind,+) -> LeafTransition {LeafTransition {- team_id: TeamId(key.team_id as i32),- leaf_state_key: key.leaf_state_key,- person_id: key.person_id,+ team_id: TeamId(key.team_id() as i32),+ leaf_state_key: key.lsk(),+ person_id: key.person_id(),condition_hash: meta.condition_hash,kind,}@@ -375,13 +379,13 @@ mod tests {})}- fn key_for(filters: &TeamFilters, person: u128) -> Stage1Key {- Stage1Key {- partition_id: PARTITION,- team_id: TEAM,- leaf_state_key: filters.by_condition_to_lsk[&HASH][0],- person_id: Uuid::from_u128(person),- }+ fn key_for(filters: &TeamFilters, person: u128) -> BehavioralKey {+ BehavioralKey::new(+ PARTITION,+ TEAM,+ Uuid::from_u128(person),+ filters.by_condition_to_lsk[&HASH][0],+ )}/// `state` encoded as the worker's prefetch would hand it to `sweep_evict`.@@ -415,7 +419,7 @@ mod tests {transition.condition_hash, HASH,"condition_hash from the meta");- assert_eq!(transition.person_id, key.person_id);+ assert_eq!(transition.person_id, key.person_id());assert_eq!(transition.team_id, TeamId(TEAM as i32));assert_eq!(result.action, EvictionAction::Delete);assert_eq!(result.reschedule, None);@@ -754,17 +758,20 @@ mod tests {#[test]fn person_property_key_is_skipped() {+ // A scheduled person-property key should never occur, but if one does the sweep drops it on the+ // `StateVariant::PersonProperty` arm. The stored value decodes before the variant dispatch, so a+ // behavioral shape under the person LSK still reaches and exercises that arm.let filters = freeze(vec![person_leaf()]);- let key = Stage1Key {- partition_id: PARTITION,- team_id: TEAM,- leaf_state_key: LeafStateKey::for_person_property(&PERSON_HASH),- person_id: Uuid::from_u128(1),- };- let values = vec![encoded(Stage1State::PersonProperty {- matches: true,- last_updated_at_ms: 1,- last_updated_offset: 2,+ let key = BehavioralKey::new(+ PARTITION,+ TEAM,+ Uuid::from_u128(1),+ LeafStateKey::for_person_property(&PERSON_HASH),+ );+ let values = vec![encoded(Stage1State::BehavioralSingle {+ has_match: true,+ last_event_at_ms: 1,+ earliest_eviction_at_ms: 2,})];let out = sweep_evict(&filters, &[key], values, i64::MAX);assert!(@@ -782,12 +789,12 @@ mod tests {fn unknown_leaf_and_missing_state_are_skipped() {let filters = freeze(vec![single_leaf(7)]);- let drifted = Stage1Key {- partition_id: PARTITION,- team_id: TEAM,- leaf_state_key: LeafStateKey([0xFF; 16]),- person_id: Uuid::from_u128(1),- };+ let drifted = BehavioralKey::new(+ PARTITION,+ TEAM,+ Uuid::from_u128(1),+ LeafStateKey([0xFF; 16]),+ );let missing = key_for(&filters, 999);// The drifted key has state; the missing key reads back as `None`.let values = vec![@@ -814,7 +821,7 @@ mod tests {#[test]fn evicts_multiple_keys_in_one_pass() {let filters = freeze(vec![single_leaf(7)]);- let keys: Vec<Stage1Key> = (1..=3).map(|p| key_for(&filters, p)).collect();+ let keys: Vec<BehavioralKey> = (1..=3).map(|p| key_for(&filters, p)).collect();let values: Vec<Option<Vec<u8>>> = keys.iter().map(|_| {diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rsindex a16451b85ef3..2439866000e7 100644--- a/rust/cohort-stream-processor/src/workers/worker.rs+++ b/rust/cohort-stream-processor/src/workers/worker.rs@@ -35,10 +35,9 @@ use crate::producer::{map_transition, now_last_updated, CohortMembershipChange, MembershipSink, MembershipStatus,OutputBuffer,};-use crate::stage1::key::Stage1Key;use crate::stage1::state::{StateVariant, StatefulRecord};use crate::stage1::transition::{LeafTransition, TransitionKind};-use crate::store::{IndexOp, PersonIndexKey, ReadLane, StagedBatch, StoreHandle};+use crate::store::{Behavioral, BehavioralKey, ReadLane, StagedBatch, StoreHandle};use crate::sweep::EvictionQueue;use crate::workers::cascade_path::handle_cascade;use crate::workers::event_path::{@@ -46,7 +45,6 @@ use crate::workers::event_path::{};use crate::workers::merge_gc::{handle_merge_gc, MergeGcCursor};use crate::workers::merge_path::{handle_apply, handle_merge, handle_redrive, MergeWorkerDeps};-use crate::workers::person_memo::{PersonMemo, PersonMemoConfig};use crate::workers::stage2_gc::{handle_stage2_orphan_gc, Stage2GcCursor};use crate::workers::stage2_path::compose_stage2;use crate::workers::sweep_callback::{sweep_evict, EvictionAction, SweepDropReason};@@ -59,7 +57,7 @@ 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+/// Chunk size for a team's sweep-state prefetch, so each `multi_get_behavioral` spans a bounded number of/// keys and no single read op holds long before the sweep makes progress.const SWEEP_MULTI_GET_CHUNK: usize = 1024;@@ -74,7 +72,7 @@ pub struct Stage1Worker {}impl Stage1Worker {- /// Spawn with the person memo disabled. The memoizing variant is [`Self::spawn_with_memo`].+ /// Spawn with event-name gating disabled. The gating-aware variant is [`Self::spawn_with_gating`].#[allow(clippy::too_many_arguments)]pub fn spawn(partition_id: u16,@@ -86,7 +84,7 @@ impl Stage1Worker {merge: Arc<MergeWorkerDeps>,durable_restore: bool,) -> Self {- Self::spawn_with_memo(+ Self::spawn_with_gating(partition_id,receiver,store,@@ -95,15 +93,14 @@ impl Stage1Worker {tracker,merge,durable_restore,- PersonMemoConfig::DISABLED,EventNameGating::Disabled,)}- /// When `durable_restore` is on, re-seeds the `EvictionQueue` from `cf_stage1` on spawn so a+ /// When `durable_restore` is on, re-seeds the `EvictionQueue` from `cf_behavioral` on spawn so a/// dormant person's `Left` still fires after a crash-restart.#[allow(clippy::too_many_arguments)]- pub fn spawn_with_memo(+ pub fn spawn_with_gating(partition_id: u16,receiver: MeteredReceiver,store: StoreHandle,@@ -112,7 +109,6 @@ impl Stage1Worker {tracker: Arc<OffsetTracker>,merge: Arc<MergeWorkerDeps>,durable_restore: bool,- person_memo: PersonMemoConfig,event_name_gating: EventNameGating,) -> Self {let handle = tokio::spawn(run_worker(@@ -124,7 +120,6 @@ impl Stage1Worker {tracker,merge,durable_restore,- person_memo,event_name_gating,));Self {@@ -152,14 +147,11 @@ async fn run_worker(tracker: Arc<OffsetTracker>,merge: Arc<MergeWorkerDeps>,durable_restore: bool,- person_memo: PersonMemoConfig,event_name_gating: EventNameGating,) {info!(partition_id, "stage 1 worker started");- let mut queue = EvictionQueue::<Stage1Key>::new();- // Reused across batches so cached results survive between events.- let mut person_memo = PersonMemo::new(person_memo);+ let mut queue = EvictionQueue::<BehavioralKey>::new();// No-op for a cold partition (bloom-filtered scan finds nothing to schedule).if durable_restore {rebuild_eviction_queue(partition_id, &handle, &mut queue).await;@@ -190,7 +182,6 @@ async fn run_worker(&event,&last_updated,merge.partition_count,- &mut person_memo,event_name_gating,).await;@@ -512,7 +503,7 @@ pub(crate) async fn produce_cascades(#[derive(Default)]struct EventEffects {changes: Vec<CohortMembershipChange>,- schedules: Vec<(Stage1Key, i64)>,+ schedules: Vec<(BehavioralKey, i64)>,re_keys: Vec<CohortStreamEvent>,}@@ -524,11 +515,9 @@ async fn handle_event(event: &CohortStreamEvent,last_updated: &str,partition_count: u32,- person_memo: &mut PersonMemo,event_name_gating: EventNameGating,) -> EventEffects {let snapshot = catalog.load();- let generation = snapshot.generation();let Some(team_filters) = snapshot.team(TeamId(event.team_id)) else {counter!(STAGE1_EVENTS_SKIPPED, "reason" => SkipReason::NoTeamFilters.as_str()).increment(1);@@ -548,16 +537,8 @@ async fn handle_event(};let started = Instant::now();- let result = process_event_offloaded(- partition_id,- handle,- filters,- generation,- &resolved,- person_memo,- event_name_gating,- )- .await;+ let result =+ process_event_offloaded(partition_id, handle, filters, &resolved, event_name_gating).await;histogram!(STAGE1_EVENT_PROCESS_DURATION).record(started.elapsed().as_secs_f64());match result {@@ -693,11 +674,11 @@ async fn handle_sweep(catalog: &CatalogHandle,sink: &Arc<dyn MembershipSink>,merge: &MergeWorkerDeps,- queue: &mut EvictionQueue<Stage1Key>,+ queue: &mut EvictionQueue<BehavioralKey>,last_updated: &str,due_before_ms: i64,) {- let mut popped: Vec<(Stage1Key, i64)> = Vec::new();+ let mut popped: Vec<(BehavioralKey, i64)> = Vec::new();while popped.len() < MAX_SWEEP_KEYS_PER_PASS {let Some(entry) = queue.pop_due(due_before_ms) else {break;@@ -708,9 +689,9 @@ async fn handle_sweep(return;}- let mut by_team: BTreeMap<u64, Vec<Stage1Key>> = BTreeMap::new();+ let mut by_team: BTreeMap<u64, Vec<BehavioralKey>> = BTreeMap::new();for &(key, _) in &popped {- by_team.entry(key.team_id).or_default().push(key);+ by_team.entry(key.team_id()).or_default().push(key);}let snapshot = catalog.load();@@ -730,7 +711,7 @@ async fn handle_sweep(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)+ .multi_get_behavioral(chunk.to_vec(), ReadLane::Maintenance).await{Ok(chunk_values) => values.extend(chunk_values),@@ -781,18 +762,8 @@ async fn handle_sweep(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),- );- }+ EvictionAction::Write(bytes) => staged.put::<Behavioral>(&result.key, bytes),+ EvictionAction::Delete => staged.delete::<Behavioral>(&result.key),}}let written = handle.commit(staged).await;@@ -822,7 +793,7 @@ async fn handle_sweep(for result in &results {if let Some(transition) = &result.transition {by_team_transitions- .entry(result.key.team_id)+ .entry(result.key.team_id()).or_default().push(transition.clone());}@@ -877,20 +848,20 @@ async fn handle_sweep(}}-/// Re-seed the per-worker [`EvictionQueue`] from `cf_stage1`, scheduling every behavioral key on its-/// stored deadline. Skips `PersonProperty` variants (no time-based eviction) and `i64::MAX` deadlines-/// (permanent). Corrupt records are counted and skipped — the event path re-derives them. A scan error-/// stops early; new events reschedule any missing keys.+/// Re-seed the per-worker [`EvictionQueue`] from `cf_behavioral`, scheduling every behavioral key on+/// its stored deadline. Skips `PersonProperty` variants (no time-based eviction) and `i64::MAX`+/// deadlines (permanent). Corrupt records are counted and skipped — the event path re-derives them. A+/// scan error stops early; new events reschedule any missing keys.async fn rebuild_eviction_queue(partition_id: u16,handle: &StoreHandle,- queue: &mut EvictionQueue<Stage1Key>,+ queue: &mut EvictionQueue<BehavioralKey>,) {let mut cursor: Option<Vec<u8>> = None;let mut rebuilt: u64 = 0;loop {let page = match handle- .scan_stage1(partition_id, cursor.clone(), REBUILD_SCAN_PAGE)+ .scan_behavioral(partition_id, cursor.clone(), REBUILD_SCAN_PAGE).await{Ok(page) => page,@@ -898,7 +869,7 @@ async fn rebuild_eviction_queue(warn!(partition_id,error = %err,- "durable restore: cf_stage1 scan failed; eviction queue may be incomplete",+ "durable restore: cf_behavioral scan failed; eviction queue may be incomplete",);break;}@@ -930,24 +901,24 @@ async fn rebuild_eviction_queue(.increment(rebuilt);info!(partition_id,- rebuilt, "durable restore: re-seeded eviction queue from cf_stage1",+ rebuilt, "durable restore: re-seeded eviction queue from cf_behavioral",);}}-fn reschedule_all(queue: &mut EvictionQueue<Stage1Key>, popped: &[(Stage1Key, i64)]) {+fn reschedule_all(queue: &mut EvictionQueue<BehavioralKey>, popped: &[(BehavioralKey, i64)]) {for &(key, deadline) in popped {queue.schedule(key, deadline);}}fn reschedule_team(- queue: &mut EvictionQueue<Stage1Key>,- popped: &[(Stage1Key, i64)],+ queue: &mut EvictionQueue<BehavioralKey>,+ popped: &[(BehavioralKey, i64)],team_id: u64,) {for &(key, deadline) in popped {- if key.team_id == team_id {+ if key.team_id() == team_id {queue.schedule(key, deadline);}}@@ -994,11 +965,12 @@ mod tombstone_redirect_tests {use crate::producer::{CaptureCascadeSink, CaptureSink, CaptureStreamEventSink, CaptureTransferSink,};- use crate::stage1::key::LeafStateKey;- use crate::stage1::state::{AppliedOffsets, Stage1State, StatefulRecord};+ use crate::stage1::person_record::PersonRecord;+ use crate::stage1::state::AppliedOffsets;use crate::stage2::state::Stage2State;use crate::store::{- CohortStore, OffloadConfig, OffloadMode, Stage2Key, StoreConfig, TombstoneKey,+ CohortStore, OffloadConfig, OffloadMode, PersonRecordKey, PersonRecords, Stage2Key,+ StoreConfig, TombstoneKey,};use crate::workers::merge_path::TransferRetryPolicy;use crate::workers::CascadeConfig;@@ -1301,13 +1273,19 @@ mod tombstone_redirect_tests {.await;}- fn stage1_key(partition_id: u16, lsk: LeafStateKey, person: Uuid) -> Stage1Key {- Stage1Key {- partition_id,- team_id: TEAM as u64,- leaf_state_key: lsk,- person_id: person,- }+ fn record_key(partition_id: u16, person: Uuid) -> PersonRecordKey {+ PersonRecordKey::new(partition_id, TEAM as u64, person)+ }++ fn read_person_record(+ store: &CohortStore,+ partition_id: u16,+ person: Uuid,+ ) -> Option<PersonRecord> {+ store+ .get_person_record(&record_key(partition_id, person))+ .unwrap()+ .map(|bytes| PersonRecord::decode(&bytes).unwrap())}fn write_tombstone(store: &CohortStore, partition_id: u16, old: Uuid, new: Uuid) {@@ -1333,25 +1311,22 @@ mod tombstone_redirect_tests {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);let p_new = Uuid::from_u128(2);let partition_id = partition_of(TeamId(TEAM), &p_new, COHORT_PARTITION_COUNT) as u16;let p_old = Uuid::from_u128(1);write_tombstone(&store, partition_id, p_old, p_new);- let mut seed = StatefulRecord::new(- Stage1State::PersonProperty {- matches: false,- last_updated_at_ms: 1_000,- last_updated_offset: 0,- },- applied(&[(5, 50)]),- );+ // Seed P_new's record: not yet a member, main-map offset {5:50}, and an ancestor entry for+ // p_old at {5:100}. The absent-baseline fingerprints (0,0) never match the event, so the+ // straggler re-evaluates and the email leaf enters.+ let mut seed = PersonRecord::absent();+ seed.applied_offsets = applied(&[(5, 50)]);seed.redirect_dedup.insert(p_old, applied(&[(5, 100)]));- let p_new_key = stage1_key(partition_id, lsk, p_new);store- .write_batch(|b| b.put_stage1(&p_new_key, &seed.encode()))+ .write_batch(|b| {+ b.put::<PersonRecords>(&record_key(partition_id, p_new), &seed.encode())+ }).unwrap();let straggler = person_event(p_old, "[email protected]", 5, 101);@@ -1362,7 +1337,6 @@ mod tombstone_redirect_tests {&straggler,"ts",COHORT_PARTITION_COUNT,- &mut PersonMemo::disabled(),EventNameGating::Disabled,).await;@@ -1371,12 +1345,11 @@ mod tombstone_redirect_tests {assert_eq!(effects.changes[0].person_id, p_new.to_string());assert_eq!(effects.changes[0].status, MembershipStatus::Entered);- let after =- StatefulRecord::decode(&store.get_stage1(&p_new_key).unwrap().unwrap()).unwrap();- assert!(matches!(- after.state,- Stage1State::PersonProperty { matches: true, .. }- ));+ let after = read_person_record(&store, partition_id, p_new).unwrap();+ assert!(+ after.matched.contains(&PERSON_HASH),+ "the email leaf entered the record's matched set",+ );assert!(after.redirect_dedup[&p_old].is_replay(5, 101),"the fold advanced redirect_dedup[origin]",@@ -1386,17 +1359,16 @@ mod tombstone_redirect_tests {"the main map is untouched by a redirected straggler",);- assert!(store- .get_stage1(&stage1_key(partition_id, lsk, p_old))- .unwrap()- .is_none());+ assert!(+ read_person_record(&store, partition_id, p_old).is_none(),+ "no record written for P_old",+ );}#[tokio::test]async fn cross_partition_redirect_re_keys_the_straggler_to_the_target() {let (_dir, store) = temp_store();let catalog = person_catalog();- let lsk = LeafStateKey::for_person_property(&PERSON_HASH);let (p_old, partition_id, p_new) = cross_partition_pair();write_tombstone(&store, partition_id, p_old, p_new);@@ -1436,18 +1408,12 @@ mod tombstone_redirect_tests {assert!(membership.changes().is_empty(), "no local processing");assert!(- store- .get_stage1(&stage1_key(partition_id, lsk, p_old))- .unwrap()- .is_none(),- "no state written for P_old in the source slice",+ read_person_record(&store, partition_id, p_old).is_none(),+ "no record written for P_old in the source slice",);assert!(- store- .get_stage1(&stage1_key(partition_id, lsk, p_new))- .unwrap()- .is_none(),- "no state written for P_new in the source slice",+ read_person_record(&store, partition_id, p_new).is_none(),+ "no record written for P_new in the source slice",);assert_eq!(tracker.committable_offsets().get(&(partition_id as i32)),@@ -1602,7 +1568,6 @@ mod tombstone_redirect_tests {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);let (p_old, source_partition, p_new) = cross_partition_pair();let target_partition = partition_of(TeamId(TEAM), &p_new, COHORT_PARTITION_COUNT) as u16;assert_ne!(source_partition, target_partition);@@ -1617,7 +1582,6 @@ mod tombstone_redirect_tests {&straggler,"ts",COHORT_PARTITION_COUNT,- &mut PersonMemo::disabled(),EventNameGating::Disabled,).await;@@ -1633,7 +1597,6 @@ mod tombstone_redirect_tests {&re_keyed,"ts",COHORT_PARTITION_COUNT,- &mut PersonMemo::disabled(),EventNameGating::Disabled,).await;@@ -1642,13 +1605,12 @@ mod tombstone_redirect_tests {assert_eq!(effects.changes[0].status, MembershipStatus::Entered);assert!(effects.re_keys.is_empty(), "no further hop: P_new is live");- let folded = StatefulRecord::decode(- &store- .get_stage1(&stage1_key(target_partition, lsk, p_new))- .unwrap()- .expect("P_new state written in the target slice"),- )- .unwrap();+ let folded = read_person_record(&store, target_partition, p_new)+ .expect("P_new record written in the target slice");+ assert!(+ folded.matched.contains(&PERSON_HASH),+ "the email leaf entered P_new's record",+ );assert!(folded.redirect_dedup[&p_old].is_replay(5, 9),"the fold recorded the original source coords under redirect_dedup[origin]",@@ -1665,7 +1627,6 @@ mod tombstone_redirect_tests {&re_keyed,"ts",COHORT_PARTITION_COUNT,- &mut PersonMemo::disabled(),EventNameGating::Disabled,).await;@@ -1677,7 +1638,6 @@ mod tombstone_redirect_tests {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);let (p_old, partition_id, p_new) = cross_partition_pair();write_tombstone(&store, partition_id, p_old, p_new);@@ -1692,7 +1652,6 @@ mod tombstone_redirect_tests {&straggler,"ts",COHORT_PARTITION_COUNT,- &mut PersonMemo::disabled(),EventNameGating::Disabled,).await;@@ -1701,23 +1660,15 @@ mod tombstone_redirect_tests {assert_eq!(effects.changes.len(), 1, "processed inline instead");assert_eq!(effects.changes[0].person_id, p_new.to_string());- let folded = StatefulRecord::decode(- &store- .get_stage1(&stage1_key(partition_id, lsk, p_new))- .unwrap()- .expect("the degraded fold writes P_new state in the local slice"),- )- .unwrap();+ let folded = read_person_record(&store, partition_id, p_new)+ .expect("the degraded fold writes P_new's record in the local slice");assert!(folded.redirect_dedup[&p_old].is_replay(5, 9),"the inline degrade still dedups by the chain origin",);assert!(- store- .get_stage1(&stage1_key(partition_id, lsk, p_old))- .unwrap()- .is_none(),- "no P_old state rebuilt",+ read_person_record(&store, partition_id, p_old).is_none(),+ "no P_old record rebuilt",);}@@ -1725,7 +1676,6 @@ mod tombstone_redirect_tests {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);let alice = Uuid::from_u128(3);let partition_id = partition_of(TeamId(TEAM), &alice, COHORT_PARTITION_COUNT) as u16;@@ -1737,18 +1687,14 @@ mod tombstone_redirect_tests {&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!(- store- .get_stage1(&stage1_key(partition_id, lsk, alice))- .unwrap()- .is_some(),- "alice's own state was written",+ read_person_record(&store, partition_id, alice).is_some(),+ "alice's own record was written",);}diff --git a/rust/cohort-stream-processor/tests/event_name_gating_parity.rs b/rust/cohort-stream-processor/tests/event_name_gating_parity.rsindex 0eff40855873..d43d4d52b7e1 100644--- a/rust/cohort-stream-processor/tests/event_name_gating_parity.rs+++ b/rust/cohort-stream-processor/tests/event_name_gating_parity.rs@@ -1,6 +1,6 @@//! Differential parity for the event-name fan-out gate: the same event sequence with gating ON//! (evaluate only the event's name bucket) and OFF (full behavioral sweep) must yield byte-identical-//! `cf_stage1` and the same leaf transitions. Covers a matching name, a non-matching name, and+//! `cf_behavioral` 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.@@ -10,14 +10,10 @@ use std::collections::BTreeMap;use chrono_tz::UTC;use cohort_stream_processor::consumers::CohortStreamEvent;-use cohort_stream_processor::filters::{- CohortId, Generation, TeamFilters, TeamFiltersBuilder, TeamId,-};+use cohort_stream_processor::filters::{CohortId, TeamFilters, TeamFiltersBuilder, TeamId};use cohort_stream_processor::stage1::LeafTransition;use cohort_stream_processor::store::{CohortStore, StoreConfig};-use cohort_stream_processor::workers::{- process_event_with_memo, EventNameGating, EventOutcome, PersonMemo,-};+use cohort_stream_processor::workers::{process_event_gated, EventNameGating, EventOutcome};use serde_json::{json, Value};use tempfile::TempDir;use uuid::Uuid;@@ -149,14 +145,14 @@ fn temp_store() -> (TempDir, CohortStore) {(dir, store)}-/// The partition's full `cf_stage1`, keyed by encoded key bytes. Two byte-identical runs compare+/// The partition's full `cf_behavioral`, keyed by encoded key bytes. Two byte-identical runs compare/// equal regardless of write order.fn dump_stage1(store: &CohortStore) -> BTreeMap<Vec<u8>, Vec<u8>> {let mut out = BTreeMap::new();let mut cursor: Option<Vec<u8>> = None;loop {let page = store- .scan_stage1(PARTITION, cursor.as_deref(), 4096)+ .scan_behavioral(PARTITION, cursor.as_deref(), 4096).unwrap();if page.is_empty() {break;@@ -182,7 +178,8 @@ fn sorted_transitions(transitions: &[LeafTransition]) -> Vec<LeafTransition> {}/// Feeds each event to two independent stores — gating ON and OFF — and asserts parity after every-/// step. The memo is disabled on both so the gate is the only varying axis.+/// step. Gating is the only varying axis; the person leaf never matches, so the person record is+/// identical on both sides and the gate's effect is confined to `cf_behavioral`.struct GatingParity {_on_dir: TempDir,_off_dir: TempDir,@@ -208,23 +205,19 @@ impl GatingParity {event: &CohortStreamEvent,label: &str,) -> EventOutcome {- let on = process_event_with_memo(+ let on = process_event_gated(PARTITION,&self.on_store,filters,- Generation(1),event,- &mut PersonMemo::disabled(),EventNameGating::Enabled,).unwrap();- let off = process_event_with_memo(+ let off = process_event_gated(PARTITION,&self.off_store,filters,- Generation(1),event,- &mut PersonMemo::disabled(),EventNameGating::Disabled,).unwrap();@@ -243,7 +236,7 @@ impl GatingParity {assert_eq!(dump_stage1(&self.on_store),dump_stage1(&self.off_store),- "{label}: cf_stage1 bytes",+ "{label}: cf_behavioral bytes",);on}@@ -313,7 +306,7 @@ fn gating_matches_full_sweep_on_a_multi_condition_event_name_bucket() {// conditionHashes. The single-leaf-per-name catalog above never exercises a 2+ condition bucket,// so a gate that dropped or double-counted a hash within one bucket would diverge from the full// sweep silently. Feed a `$pageview` into a bucket holding both a `BehavioralSingle` and a- // `BehavioralDailyBuckets` leaf: `feed` asserts byte-identical `cf_stage1` (covering the+ // `BehavioralDailyBuckets` leaf: `feed` asserts byte-identical `cf_behavioral` (covering the// daily-bucket write path), and both leaves must flip.let filters = multi_condition_catalog();assert_eq!(diff --git a/rust/cohort-stream-processor/tests/events_consumer.rs b/rust/cohort-stream-processor/tests/events_consumer.rsindex 5138c102c29d..8c9b90ab7de8 100644--- a/rust/cohort-stream-processor/tests/events_consumer.rs+++ b/rust/cohort-stream-processor/tests/events_consumer.rs@@ -52,7 +52,7 @@ use cohort_stream_processor::store::durability::{RestoreSource, S3Uploader,};use cohort_stream_processor::store::{- CohortStore, LeafStateKey, OffloadConfig, OffloadMode, Stage1Key, StoreConfig, StoreHandle,+ BehavioralKey, CohortStore, LeafStateKey, OffloadConfig, OffloadMode, StoreConfig, StoreHandle,};use cohort_stream_processor::sweep::Sweeper;@@ -373,15 +373,10 @@ fn entered_persons(store: &CohortStore, lsk: LeafStateKey) -> usize {.filter(|&n| {let p = person(n);(0..NUM_PARTITIONS).any(|partition| {- let key = Stage1Key {- partition_id: partition as u16,- team_id: TEAM as u64,- leaf_state_key: lsk,- person_id: p,- };+ let key = BehavioralKey::new(partition as u16, TEAM as u64, p, lsk);matches!(store- .get_stage1(&key)+ .get_behavioral(&key).unwrap().map(|bytes| StatefulRecord::decode(&bytes).unwrap().state),Some(Stage1State::BehavioralSingle {@@ -591,15 +586,10 @@ fn entered_persons_range(store: &CohortStore, lsk: LeafStateKey, n: usize) -> us.filter(|&i| {let p = person(i);(0..NUM_PARTITIONS).any(|partition| {- let key = Stage1Key {- partition_id: partition as u16,- team_id: TEAM as u64,- leaf_state_key: lsk,- person_id: p,- };+ let key = BehavioralKey::new(partition as u16, TEAM as u64, p, lsk);matches!(store- .get_stage1(&key)+ .get_behavioral(&key).unwrap().map(|bytes| StatefulRecord::decode(&bytes).unwrap().state),Some(Stage1State::BehavioralSingle {@@ -847,13 +837,8 @@ async fn does_not_commit_past_a_blocked_produce() {/// Whether any produced person has behavioral state under `partition` in `store`.fn partition_has_state(store: &CohortStore, partition: i32, lsk: LeafStateKey) -> bool {(1..=PERSONS).any(|n| {- let key = Stage1Key {- partition_id: partition as u16,- team_id: TEAM as u64,- leaf_state_key: lsk,- person_id: person(n),- };- store.get_stage1(&key).unwrap().is_some()+ let key = BehavioralKey::new(partition as u16, TEAM as u64, person(n), lsk);+ store.get_behavioral(&key).unwrap().is_some()})}@@ -1111,7 +1096,7 @@ async fn durable_restart_reopens_live_state_and_fires_a_dormant_left() {"no Kafka loss: committed offsets are unchanged across the restart",);- // --- Dormant Left: durable workers re-seed queues from cf_stage1; a sweep past the window+ // --- Dormant Left: durable workers re-seed queues from cf_behavioral; a sweep past the window// evicts each member with no new events. ---let catalog = Arc::new(behavioral_catalog());let sink = Arc::new(CaptureSink::new());@@ -1319,7 +1304,7 @@ async fn delete_s3_prefix(config: &Config) {/// Full disaster-recovery path through a real broker + S3: fold + checkpoint to S3 (tenure 1), delete/// the store + checkpoint dirs (PVC loss), then restore from S3 and seek the manifest offsets (tenure/// 2). Asserts state is restored (not cold-replayed), the resume neither skips nor re-folds, and a-/// dormant `Left` fires from the eviction queue rebuilt over the restored `cf_stage1`.+/// dormant `Left` fires from the eviction queue rebuilt over the restored `cf_behavioral`.////// Asserting count-exact (not mere presence) sidesteps the documented fast-broker flake.#[tokio::test]@@ -1493,7 +1478,7 @@ async fn s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormant"state count is still exact after the restore-seek resume",);- // (c) Dormant Left: workers re-seed the eviction queue from the restored cf_stage1, then a sweep+ // (c) Dormant Left: workers re-seed the eviction queue from the restored cf_behavioral, then a sweep// past the window evicts every now-dormant member.let catalog = Arc::new(behavioral_catalog());let left_sink = Arc::new(CaptureSink::new());@@ -1526,7 +1511,7 @@ async fn s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormant.count();assert_eq!(lefts, PERSONS as usize,- "every restored-then-dormant member emits a Left from the eviction queue rebuilt over the S3-restored cf_stage1",+ "every restored-then-dormant member emits a Left from the eviction queue rebuilt over the S3-restored cf_behavioral",);// --- Cleanup: delete the topic and the S3 prefix. ---diff --git a/rust/cohort-stream-processor/tests/merge_consumer.rs b/rust/cohort-stream-processor/tests/merge_consumer.rsindex e2372ee4088e..512786350ca4 100644--- a/rust/cohort-stream-processor/tests/merge_consumer.rs+++ b/rust/cohort-stream-processor/tests/merge_consumer.rs@@ -51,7 +51,7 @@ use cohort_stream_processor::producer::{};use cohort_stream_processor::stage1::{Stage1State, StateVariant, StatefulRecord};use cohort_stream_processor::store::{- CohortStore, LeafStateKey, OffloadConfig, OffloadMode, Stage1Key, StoreConfig, StoreHandle,+ BehavioralKey, CohortStore, LeafStateKey, OffloadConfig, OffloadMode, StoreConfig, StoreHandle,TombstoneKey,};use cohort_stream_processor::workers::{@@ -464,14 +464,9 @@ fn stage1_state(lsk: LeafStateKey,person: Uuid,) -> Option<Stage1State> {- let key = Stage1Key {- partition_id,- team_id: TEAM as u64,- leaf_state_key: lsk,- person_id: person,- };+ let key = BehavioralKey::new(partition_id, TEAM as u64, person, lsk);store- .get_stage1(&key)+ .get_behavioral(&key).unwrap().map(|bytes| StatefulRecord::decode(&bytes).unwrap().state)}@@ -765,6 +760,7 @@ async fn keyed_produces_agree_with_partition_of_live() {source_offset: n as i64,leaves: vec![],forward_hops: 0,+ person_dedup: None,}).collect();let acks = transfer_sink.produce(transfers).await;diff --git a/rust/cohort-stream-processor/tests/merge_durability.rs b/rust/cohort-stream-processor/tests/merge_durability.rsindex 50aa124bc55a..4ea627c1a0c9 100644--- a/rust/cohort-stream-processor/tests/merge_durability.rs+++ b/rust/cohort-stream-processor/tests/merge_durability.rs@@ -50,7 +50,7 @@ use cohort_stream_processor::store::durability::{OffsetManifest, RestoreSource, S3Uploader,};use cohort_stream_processor::store::{- CohortStore, LeafStateKey, OffloadConfig, OffloadMode, Stage1Key, StoreConfig, StoreHandle,+ BehavioralKey, CohortStore, LeafStateKey, OffloadConfig, OffloadMode, StoreConfig, StoreHandle,TombstoneKey,};use cohort_stream_processor::sweep::Sweeper;@@ -515,14 +515,9 @@ fn stage1_state(lsk: LeafStateKey,person: Uuid,) -> Option<Stage1State> {- let key = Stage1Key {- partition_id,- team_id: TEAM as u64,- leaf_state_key: lsk,- person_id: person,- };+ let key = BehavioralKey::new(partition_id, TEAM as u64, person, lsk);store- .get_stage1(&key)+ .get_behavioral(&key).unwrap().map(|bytes| StatefulRecord::decode(&bytes).unwrap().state)}diff --git a/rust/cohort-stream-processor/tests/merge_protocol.rs b/rust/cohort-stream-processor/tests/merge_protocol.rsindex 2532cd464dcb..7dfd67c3bd75 100644--- a/rust/cohort-stream-processor/tests/merge_protocol.rs+++ b/rust/cohort-stream-processor/tests/merge_protocol.rs@@ -22,11 +22,13 @@ use cohort_stream_processor::merge::transfer::{};use cohort_stream_processor::partitions::{partition_of, COHORT_PARTITION_COUNT};use cohort_stream_processor::producer::{now_last_updated, MembershipStatus};+use cohort_stream_processor::stage1::person_record::{MatchedSet, PersonRecord};use cohort_stream_processor::stage1::{Stage1State, StateVariant, StatefulRecord};use cohort_stream_processor::stage2::Stage2State;use cohort_stream_processor::store::{- CohortStore, LeafStateKey, MergeAppliedKey, MergeDrainKey, OffloadConfig, OffloadMode,- PendingTransferKey, Stage1Key, Stage2Key, StoreConfig, StoreHandle, TombstoneKey,+ BehavioralKey, CohortStore, LeafStateKey, MergeAppliedKey, MergeDrainKey, OffloadConfig,+ OffloadMode, PendingTransferKey, PersonRecordKey, PersonRecords, Stage2Key, StoreConfig,+ StoreHandle, TombstoneKey,};use cohort_stream_processor::workers::{compose_stage2, handle_merge_gc, handle_stage2_orphan_gc, process_event, MergeGcCursor,@@ -204,14 +206,9 @@ fn leaf_state(lsk: LeafStateKey,person: Uuid,) -> Option<Stage1State> {- let key = Stage1Key {- partition_id,- team_id: TEAM as u64,- leaf_state_key: lsk,- person_id: person,- };+ let key = BehavioralKey::new(partition_id, TEAM as u64, person, lsk);store- .get_stage1(&key)+ .get_behavioral(&key).unwrap().map(|bytes| StatefulRecord::decode(&bytes).unwrap().state)}@@ -566,11 +563,11 @@ fn fast_path_equals_the_cross_partition_result() {effects.schedules.iter()- .all(|(key, _)| key.person_id == p_new),+ .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),+ effects.cancels.iter().all(|key| key.person_id() == p_old),"the cancelled keys are P_old's drained keys",);@@ -1946,6 +1943,286 @@ fn checkpoint_restore_preserves_the_drain_marker_so_a_replayed_merge_does_not_re);}+// --- PersonRecord merge dedup carry (Slice B2) ---+//+// The person side no longer transfers per-leaf rows: a merge carries only P_old's replay-dedup+// (`transfer.person_dedup`), which P_new's record absorbs as an ancestor. These pins cover the+// record-only transfer (the empty-transfer predicate fix), the absent/corrupt-target arms (write+// nothing, byte-parity with the old per-leaf `keep_new` absent arm), redelivery idempotence, and the+// straggler that dedups against the carried ancestor.++const PERSON_HASH: [u8; 16] = *b"fedcba9876543210";++/// A team with one person-only cohort, so a drain packages no behavioral leaves — only the record.+fn person_only_filters() -> TeamFilters {+ let mut builder = TeamFiltersBuilder::default();+ builder+ .add_cohort(CohortId(1), TeamId(TEAM), &cohort(vec![person_leaf()]))+ .unwrap();+ builder.freeze(UTC)+}++fn record_at(store: &CohortStore, partition_id: u16, person: Uuid) -> Option<PersonRecord> {+ store+ .get_person_record(&PersonRecordKey::new(partition_id, TEAM as u64, person))+ .unwrap()+ .map(|bytes| PersonRecord::decode(&bytes).unwrap())+}++/// A record that matches the person leaf, with `applied` on the main map.+fn seed_member_record(store: &CohortStore, partition_id: u16, person: Uuid) {+ let mut record = PersonRecord::absent();+ record.matched = MatchedSet::from_iter([PERSON_HASH]);+ store+ .write_batch(|b| {+ b.put::<PersonRecords>(+ &PersonRecordKey::new(partition_id, TEAM as u64, person),+ &record.encode(),+ )+ })+ .unwrap();+}++/// Fold one matching person event for `person` on its partition under person-only filters, writing a+/// member record.+fn fold_person(store: &CohortStore, filters: &TeamFilters, person: Uuid, source_offset: i64) {+ let partition_id = part(person);+ process_event(+ partition_id,+ store,+ filters,+ &pageview_event(person, 5, source_offset),+ )+ .unwrap();+}++#[test]+fn record_only_person_transfers_its_dedup_and_a_straggler_dedups_against_the_ancestor() {+ let dir = TempDir::new().unwrap();+ let store = temp_store_in(&dir);+ let filters = person_only_filters();++ let p_old = Uuid::from_u128(0xA11CE);+ let p_old_part = part(p_old);+ let p_new = person_not_on(p_old_part);+ let p_new_part = part(p_new);++ // P_old has ONLY a person record (no behavioral rows) folded from a source event at (5, 40).+ fold_person(&store, &filters, p_old, 40);+ assert!(+ record_at(&store, p_old_part, p_old)+ .unwrap()+ .applied_offsets+ .is_replay(5, 40),+ "P_old's record recorded its source offset",+ );+ // P_new already exists as a member so it can absorb the ancestor.+ seed_member_record(&store, p_new_part, p_new);++ // Drain P_old cross-partition: no leaves, but a person_dedup — so the transfer is still produced.+ let drained = handle_merge_event(+ p_old_part,+ &store,+ &filters,+ &merge_event(p_old, p_new),+ (5, 100),+ COHORT_PARTITION_COUNT,+ )+ .unwrap();+ let transfer = match drained {+ DrainOutcome::Drained { transfer, .. } => transfer,+ other => panic!("expected a cross-partition Drained, got {other:?}"),+ };+ assert!(+ transfer.leaves.is_empty(),+ "a person-only drain carries no leaves"+ );+ assert!(+ transfer.person_dedup.is_some(),+ "the person-only drain still carries P_old's record dedup (the empty-transfer fix)",+ );+ assert!(+ record_at(&store, p_old_part, p_old).is_none(),+ "P_old's record was reclaimed by the drain",+ );++ // Apply into P_new: its present record absorbs P_old as an ancestor at the carried high-water 40.+ let applied = handle_transfer(+ p_new_part,+ &store,+ &filters,+ &transfer,+ (7, 200),+ COHORT_PARTITION_COUNT,+ )+ .unwrap();+ let ApplyOutcome::Applied { transitions, .. } = applied else {+ panic!("expected Applied, got {applied:?}");+ };+ assert!(+ transitions.is_empty(),+ "a record merge produces no person transition (P_new was already a member; keep_new yields no flip)",+ );+ let p_new_record = record_at(&store, p_new_part, p_new).unwrap();+ assert!(+ p_new_record.redirect_dedup[&p_old].is_replay(5, 40),+ "P_new absorbed P_old's offsets under redirect_dedup[P_old]",+ );+ assert!(+ !p_new_record.applied_offsets.is_replay(5, 40),+ "the ancestor's offsets never fold into P_new's main map",+ );++ // A straggler for P_old (redirected to P_new) at offset 40 ≤ the carried ancestor max is a replay.+ let mut straggler = pageview_event(p_new, 5, 40);+ straggler.redirected_from = Some(p_old.to_string());+ let out = process_event(p_new_part, &store, &filters, &straggler).unwrap();+ assert!(+ out.transitions.is_empty(),+ "the straggler dedups against the carried ancestor high-water and flips nothing",+ );+}++#[test]+fn record_merge_into_absent_or_corrupt_target_writes_nothing() {+ let dir = TempDir::new().unwrap();+ let store = temp_store_in(&dir);+ let filters = person_only_filters();++ let p_old = Uuid::from_u128(0xA11CE);+ let p_old_part = part(p_old);+ let p_new = person_not_on(p_old_part);+ let p_new_part = part(p_new);++ fold_person(&store, &filters, p_old, 40);+ // P_new has NO record.+ let drained = handle_merge_event(+ p_old_part,+ &store,+ &filters,+ &merge_event(p_old, p_new),+ (5, 100),+ COHORT_PARTITION_COUNT,+ )+ .unwrap();+ let transfer = match drained {+ DrainOutcome::Drained { transfer, .. } => transfer,+ other => panic!("expected Drained, got {other:?}"),+ };++ // Absent target: nothing written (byte-parity with the per-leaf absent-new arm).+ handle_transfer(+ p_new_part,+ &store,+ &filters,+ &transfer,+ (7, 200),+ COHORT_PARTITION_COUNT,+ )+ .unwrap();+ assert!(+ record_at(&store, p_new_part, p_new).is_none(),+ "an absent target record is not created by the merge",+ );++ // Corrupt target: a new drain (fresh coords so it is not a replay) applying into a corrupt record+ // writes nothing rather than clobbering it.+ let p_new2 = (p_new.as_u128() + 1..)+ .map(Uuid::from_u128)+ .find(|p| part(*p) == p_new_part && *p != p_new)+ .unwrap();+ store+ .write_batch(|b| {+ b.put::<PersonRecords>(+ &PersonRecordKey::new(p_new_part, TEAM as u64, p_new2),+ b"not a record",+ )+ })+ .unwrap();+ let mut corrupt_transfer = transfer.clone();+ corrupt_transfer.new_person_uuid = p_new2;+ corrupt_transfer.source_offset = 101;+ handle_transfer(+ p_new_part,+ &store,+ &filters,+ &corrupt_transfer,+ (7, 201),+ COHORT_PARTITION_COUNT,+ )+ .unwrap();+ assert_eq!(+ store+ .get_person_record(&PersonRecordKey::new(p_new_part, TEAM as u64, p_new2))+ .unwrap()+ .as_deref(),+ Some(b"not a record".as_slice()),+ "a corrupt target record is left untouched, not overwritten",+ );+}++#[test]+fn redelivered_record_merge_is_idempotent_via_merge_max() {+ let dir = TempDir::new().unwrap();+ let store = temp_store_in(&dir);+ let filters = person_only_filters();++ let p_old = Uuid::from_u128(0xA11CE);+ let p_old_part = part(p_old);+ let p_new = person_not_on(p_old_part);+ let p_new_part = part(p_new);++ fold_person(&store, &filters, p_old, 40);+ seed_member_record(&store, p_new_part, p_new);+ let drained = handle_merge_event(+ p_old_part,+ &store,+ &filters,+ &merge_event(p_old, p_new),+ (5, 100),+ COHORT_PARTITION_COUNT,+ )+ .unwrap();+ let transfer = match drained {+ DrainOutcome::Drained { transfer, .. } => transfer,+ other => panic!("expected Drained, got {other:?}"),+ };++ handle_transfer(+ p_new_part,+ &store,+ &filters,+ &transfer,+ (7, 200),+ COHORT_PARTITION_COUNT,+ )+ .unwrap();+ let after_first = record_at(&store, p_new_part, p_new).unwrap();++ // A duplicate transfer copy (fresh transfer coords, same source coords) is short-circuited by the+ // apply marker, so the record is byte-identical — merge_max would also be idempotent, but the+ // marker means the second apply does not even touch the record.+ let second = handle_transfer(+ p_new_part,+ &store,+ &filters,+ &transfer,+ (7, 999),+ COHORT_PARTITION_COUNT,+ )+ .unwrap();+ assert_eq!(+ second,+ ApplyOutcome::AlreadyApplied,+ "the redelivery is deduped by the marker"+ );+ assert_eq!(+ record_at(&store, p_new_part, p_new).unwrap(),+ after_first,+ "the redelivered merge left P_new's record byte-identical",+ );+}+/// 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.@@ -1956,7 +2233,10 @@ 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>)>,+ behavioral: Vec<(Vec<u8>, Vec<u8>)>,+ /// `[P_old, P_new]` raw person records: the drain deletes P_old's, and P_new's absorbed+ /// dedup must be byte-identical across modes (the codec is canonical).+ records: Vec<Option<Vec<u8>>>,}let p_old = Uuid::from_u128(0xBEE5);@@ -2038,14 +2318,27 @@ async fn each_offload_mode_yields_the_same_merge_result() {.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]+ let mut behavioral: Vec<(Vec<u8>, Vec<u8>)> = [p_old_part, p_new_part].into_iter()- .flat_map(|pid| store.scan_stage1(pid, None, 10_000).unwrap())+ .flat_map(|pid| store.scan_behavioral(pid, None, 10_000).unwrap()).map(|(key, value)| (key.encode().to_vec(), value)).collect();- stage1.sort();+ behavioral.sort();- per_mode.push(ModeOutcome { composed, stage1 });+ let records: Vec<Option<Vec<u8>>> = [(p_old_part, p_old), (p_new_part, p_new)]+ .into_iter()+ .map(|(pid, person)| {+ store+ .get_person_record(&PersonRecordKey::new(pid, TEAM as u64, person))+ .unwrap()+ })+ .collect();++ per_mode.push(ModeOutcome {+ composed,+ behavioral,+ records,+ });}// The scenario must actually compose an enter for P_new, so parity compares real work rather than@@ -2056,6 +2349,10 @@ async fn each_offload_mode_yields_the_same_merge_result() {}),"the seed must produce a composable enter for P_new",);+ assert!(+ per_mode[0].records[0].is_none() && per_mode[0].records[1].is_some(),+ "the drain must delete P_old's record and leave P_new's in place",+ );let (off, rest) = per_mode.split_first().unwrap();for (arm, mode) in rest@@ -2064,7 +2361,7 @@ async fn each_offload_mode_yields_the_same_merge_result() {{assert_eq!(arm, off,- "mode {mode:?} diverged from Off: merge emissions and cf_stage1 bytes must be identical across operating points",+ "mode {mode:?} diverged from Off: merge emissions, cf_behavioral bytes, and person records 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.rsdeleted file mode 100644index 6f569a5dd815..000000000000--- a/rust/cohort-stream-processor/tests/person_memo_parity.rs+++ /dev/null@@ -1,530 +0,0 @@-//! Differential parity for the person-property memo: the same event sequence with the memo ON and-//! OFF must yield byte-identical `cf_stage1` and the same leaf transitions (a multiset — apply order-//! 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;-use cohort_stream_processor::consumers::CohortStreamEvent;-use cohort_stream_processor::filters::{- CatalogHandle, CohortId, FilterCatalog, Generation, TeamFilters, TeamFiltersBuilder, TeamId,-};-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, OffloadConfig, OffloadMode, StoreConfig, StoreHandle,-};-use cohort_stream_processor::workers::{- process_event, process_event_with_memo, EventNameGating, EventOutcome, MergeWorkerDeps,- PersonMemo, PersonMemoConfig, Stage1Worker,-};-use serde_json::{json, Value};-use tempfile::TempDir;-use tokio::sync::mpsc;-use uuid::Uuid;--const TEAM: i32 = 7;-const PARTITION: u16 = 0;--// Distinct 16-byte condition hashes. `email` sorts before `plan`, so the email predicate is bit 0 in-// both catalogs — the position a stale cross-generation serve would misread.-const EMAIL_ALICE: &str = "emailAlice000001";-const EMAIL_BOB: &str = "emailBob00000002";-const PLAN_PRO: &str = "planPro000000003";-const BEH_PAGEVIEW: &str = "pageviewbeh00004";--const PROPS_PRO: &str = r#"{"email":"[email protected]","plan":"pro"}"#;-const PROPS_FREE: &str = r#"{"email":"[email protected]","plan":"free"}"#;-const PROPS_ENTERPRISE: &str = r#"{"email":"[email protected]","plan":"enterprise"}"#;-const PROPS_BOB: &str = r#"{"email":"[email protected]","plan":"pro"}"#;--fn person_leaf(key: &str, value: &str, hash: &str) -> Value {- json!({- "type": "person",- "key": key,- "value": value,- "operator": "exact",- "conditionHash": hash,- "bytecode": ["_H", 1, 32, value, 32, key, 32, "properties", 32, "person", 1, 3, 11],- })-}--fn behavioral_leaf(hash: &str) -> Value {- json!({- "type": "behavioral",- "value": "performed_event",- "key": "$pageview",- "time_value": 7,- "time_interval": "day",- "conditionHash": hash,- "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],- })-}--fn team_filters(values: Vec<Value>) -> TeamFilters {- let mut builder = TeamFiltersBuilder::default();- builder- .add_cohort(- CohortId(1),- TeamId(TEAM),- &json!({ "properties": { "type": "AND", "values": values } }),- )- .unwrap();- builder.freeze(UTC)-}--/// C1: alice's email, a plan, and a behavioral leaf.-fn catalog_v1() -> TeamFilters {- team_filters(vec![- person_leaf("email", "[email protected]", EMAIL_ALICE),- person_leaf("plan", "pro", PLAN_PRO),- behavioral_leaf(BEH_PAGEVIEW),- ])-}--/// C2: the email predicate is flipped to bob (a *new* condition hash); plan + behavioral unchanged.-fn catalog_v2() -> TeamFilters {- team_filters(vec![- person_leaf("email", "[email protected]", EMAIL_BOB),- person_leaf("plan", "pro", PLAN_PRO),- behavioral_leaf(BEH_PAGEVIEW),- ])-}--fn event(person: Uuid, props: &str, offset: i64, timestamp: &str) -> CohortStreamEvent {- CohortStreamEvent {- team_id: TEAM,- person_id: person.to_string(),- distinct_id: "d".to_string(),- uuid: format!("uuid-{offset}"),- event: "$pageview".to_string(),- timestamp: timestamp.to_string(),- properties: Some("{}".to_string()),- person_properties: Some(props.to_string()),- elements_chain: None,- source_offset: offset,- source_partition: 0,- redirected_from: None,- redirect_hops: 0,- }-}--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 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>> {- let mut out = BTreeMap::new();- let mut cursor: Option<Vec<u8>> = None;- loop {- let page = store- .scan_stage1(PARTITION, cursor.as_deref(), 4096)- .unwrap();- if page.is_empty() {- break;- }- let page_len = page.len();- cursor = page.last().map(|(key, _)| key.encode().to_vec());- for (key, value) in page {- out.insert(key.encode().to_vec(), value);- }- if page_len < 4096 {- break;- }- }- out-}--/// Sort transitions by their debug form so two runs compare as multisets — apply order differs-/// between the ordered (memo) and unordered (sweep) person loops, but the set is identical.-fn sorted_transitions(transitions: &[LeafTransition]) -> Vec<LeafTransition> {- let mut sorted = transitions.to_vec();- sorted.sort_by_cached_key(|t| format!("{t:?}"));- sorted-}--/// Runs each event through two independent stores — memo on and memo off — and asserts parity after-/// every step. The memo persists across the whole sequence.-struct Parity {- _on_dir: TempDir,- _off_dir: TempDir,- on_store: CohortStore,- off_store: CohortStore,- on_memo: PersonMemo,- off_memo: PersonMemo,-}--impl Parity {- fn new() -> Self {- let (on_dir, on_store) = temp_store();- let (off_dir, off_store) = temp_store();- Self {- _on_dir: on_dir,- _off_dir: off_dir,- on_store,- off_store,- on_memo: PersonMemo::new(PersonMemoConfig {- enabled: true,- capacity: 16,- }),- off_memo: PersonMemo::disabled(),- }- }-- /// Feed one event to both stores, assert outcome + state parity, and return the memo-on outcome.- fn feed(- &mut self,- filters: &TeamFilters,- generation: Generation,- event: &CohortStreamEvent,- label: &str,- ) -> EventOutcome {- let on = process_event_with_memo(- PARTITION,- &self.on_store,- filters,- generation,- event,- &mut self.on_memo,- EventNameGating::Disabled,- )- .unwrap();- let off = process_event_with_memo(- PARTITION,- &self.off_store,- filters,- generation,- event,- &mut self.off_memo,- EventNameGating::Disabled,- )- .unwrap();-- assert_eq!(on.skipped, off.skipped, "{label}: skip reason");- assert_eq!(on.event_ms, off.event_ms, "{label}: event_ms");- assert_eq!(- sorted_transitions(&on.transitions),- sorted_transitions(&off.transitions),- "{label}: transitions",- );- let (mut on_sched, mut off_sched) = (on.schedules.clone(), off.schedules.clone());- on_sched.sort_by_key(|(key, deadline)| (key.encode(), *deadline));- off_sched.sort_by_key(|(key, deadline)| (key.encode(), *deadline));- assert_eq!(on_sched, off_sched, "{label}: schedules");- assert_eq!(- dump_stage1(&self.on_store),- dump_stage1(&self.off_store),- "{label}: cf_stage1 bytes",- );- on- }-}--fn transition_kinds(outcome: &EventOutcome) -> Vec<TransitionKind> {- let mut kinds: Vec<TransitionKind> = outcome.transitions.iter().map(|t| t.kind).collect();- kinds.sort_by_key(|k| matches!(k, TransitionKind::Left));- kinds-}--#[test]-fn memo_matches_full_sweep_across_hit_miss_gen_bump_and_stale_events() {- let mut p = Parity::new();- let alice = Uuid::from_u128(1);- let bob = Uuid::from_u128(2);- let c1 = catalog_v1();- let c2 = catalog_v2();-- // 1. First sighting (miss): email + plan + behavioral all match → three Entered.- let s1 = p.feed(- &c1,- Generation(1),- &event(alice, PROPS_PRO, 0, "2026-05-26 10:00:00.000000"),- "s1 miss",- );- assert_eq!(s1.transitions.len(), 3, "s1: three leaves entered");- assert!(s1- .transitions- .iter()- .all(|t| t.kind == TransitionKind::Entered));-- // 2. Identical props (memo hit): no membership change, state advances identically.- let s2 = p.feed(- &c1,- Generation(1),- &event(alice, PROPS_PRO, 1, "2026-05-26 11:00:00.000000"),- "s2 hit",- );- assert!(- s2.transitions.is_empty(),- "s2: a repeat event flips nothing"- );-- // 3. Plan changes free (fingerprint miss → re-eval): the plan leaf leaves.- let s3 = p.feed(- &c1,- Generation(1),- &event(alice, PROPS_FREE, 2, "2026-05-26 12:00:00.000000"),- "s3 fp miss",- );- assert_eq!(- transition_kinds(&s3),- vec![TransitionKind::Left],- "s3: plan left"- );-- // 4. Catalog generation bumps and the email predicate flips to bob. The stale gen-1 entry must NOT- // be served: alice no longer matches the email leaf, and the plan leaf re-enters (pro again).- let s4 = p.feed(- &c2,- Generation(2),- &event(alice, PROPS_PRO, 3, "2026-05-26 13:00:00.000000"),- "s4 gen bump",- );- assert_eq!(- transition_kinds(&s4),- vec![TransitionKind::Entered],- "s4: only the plan re-enters; the flipped email leaf does not match alice",- );-- // 5. An out-of-order, older event (enterprise plan): argMax rejects every leaf in both runs.- let s5 = p.feed(- &c2,- Generation(2),- &event(alice, PROPS_ENTERPRISE, 5, "2026-05-26 09:00:00.000000"),- "s5 stale",- );- assert!(s5.transitions.is_empty(), "s5: a stale event flips nothing");-- // 6. A second person under the same generation: a distinct memo key, evaluated fresh (merge analog).- let s6 = p.feed(- &c2,- Generation(2),- &event(bob, PROPS_BOB, 4, "2026-05-26 14:00:00.000000"),- "s6 new person",- );- assert_eq!(- s6.transitions.len(),- 3,- "s6: bob enters email + plan + behavioral"- );- assert!(s6- .transitions- .iter()- .all(|t| t.kind == TransitionKind::Entered));-}--/// Drive an enter → hit → leave sequence for one person through a spawned worker, returning the-/// membership statuses and final `cf_stage1`. The `TempDir` is returned so its store outlives the scan.-async fn run_worker_sequence(- filters: TeamFilters,- person: Uuid,- memo: PersonMemoConfig,-) -> (Vec<MembershipStatus>, BTreeMap<Vec<u8>, Vec<u8>>, TempDir) {- let (dir, store) = temp_store();- let catalog = std::sync::Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([(- TeamId(TEAM),- 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(&store),- catalog,- std::sync::Arc::new(sink.clone()),- tracker.clone(),- MergeWorkerDeps::capture(),- false,- memo,- EventNameGating::Disabled,- );-- let sequence = [- (PROPS_PRO, 0, "2026-05-26 10:00:00.000000"), // enter- (PROPS_PRO, 1, "2026-05-26 11:00:00.000000"), // hit, no change- (r#"{"email":"[email protected]"}"#, 2, "2026-05-26 12:00:00.000000"), // miss, leave- ];- for (props, offset, ts) in sequence {- tracker.mark_dispatched(PARTITION as i32, offset + 1);- tx.send(vec![ShuffleMessage::Event {- event: Box::new(event(person, props, offset, ts)),- cse_offset: offset,- }])- .await- .unwrap();- }- drop(tx);- worker.join().await.unwrap();-- let statuses = sink.changes().iter().map(|c| c.status).collect();- (statuses, dump_stage1(&store), dir)-}--/// End-to-end through a spawned worker with the memo enabled vs disabled: the membership output and-/// `cf_stage1` must be identical across an enter → hit → leave sequence, covering `run_worker`'s memo-/// construction and the `snapshot.generation()` threading in `handle_event`.-#[tokio::test]-async fn memo_enabled_worker_matches_a_disabled_worker_end_to_end() {- // `TeamFilters` is not `Clone`, so build it fresh for each run.- let single_email = || team_filters(vec![person_leaf("email", "[email protected]", EMAIL_ALICE)]);- let alice = Uuid::from_u128(1);-- let (on_statuses, on_state, _on_dir) = run_worker_sequence(- single_email(),- alice,- PersonMemoConfig {- enabled: true,- capacity: 16,- },- )- .await;- let (off_statuses, off_state, _off_dir) =- run_worker_sequence(single_email(), alice, PersonMemoConfig::DISABLED).await;-- assert_eq!(- on_statuses,- vec![MembershipStatus::Entered, MembershipStatus::Left],- "enabled worker: enter then leave",- );- 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/person_record_fold.rs b/rust/cohort-stream-processor/tests/person_record_fold.rsnew file mode 100644index 000000000000..7b20db0e3925--- /dev/null+++ b/rust/cohort-stream-processor/tests/person_record_fold.rs@@ -0,0 +1,595 @@+//! The freshness decision table driven through the real event fold against a live RocksDB store.+//!+//! `stage1/person_record.rs` unit-tests the pure `decide` / `apply_*` core; these tests exercise the+//! wiring in `event_path::fold_person` — that each decision-table row stages (or does not stage) the+//! right record, advances the stamp where it is load-bearing, and emits the right transitions — plus+//! the two cross-cutting equivalences the PersonRecord collapse must uphold:+//!+//! - the record-level argMax must agree with the old per-leaf last-write-wins rule, and+//! - the fingerprint-match fast path (`SkipEval`) must be indistinguishable from a full re-evaluation.++// 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::{CohortId, TeamFilters, TeamFiltersBuilder, TeamId};+use cohort_stream_processor::stage1::person_record::{+ CatalogFingerprint, PersonRecord, PropsFingerprint,+};+use cohort_stream_processor::stage1::time::clickhouse_timestamp_to_millis;+use cohort_stream_processor::stage1::{AppliedOffsets, LeafTransition, TransitionKind};+use cohort_stream_processor::store::{CohortStore, PersonRecordKey, PersonRecords, StoreConfig};+use cohort_stream_processor::workers::{process_event, EventOutcome};+use serde_json::{json, Value};+use tempfile::TempDir;+use uuid::Uuid;++const TEAM: i32 = 7;+const PARTITION: u16 = 0;++// Two distinct person-condition hashes. `email` sorts before `plan`.+const EMAIL_HASH: [u8; 16] = *b"emailhash0000001";+const PLAN_HASH: [u8; 16] = *b"planhash00000002";++/// `email == "[email protected]"`.+fn email_leaf() -> Value {+ json!({+ "type": "person", "key": "email", "value": "[email protected]", "operator": "exact",+ "conditionHash": "emailhash0000001",+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],+ })+}++/// `plan == "pro"`.+fn plan_leaf() -> Value {+ json!({+ "type": "person", "key": "plan", "value": "pro", "operator": "exact",+ "conditionHash": "planhash00000002",+ "bytecode": ["_H", 1, 32, "pro", 32, "plan", 32, "properties", 32, "person", 1, 3, 11],+ })+}++fn filters(leaves: Vec<Value>) -> TeamFilters {+ let mut builder = TeamFiltersBuilder::default();+ builder+ .add_cohort(+ CohortId(1),+ TeamId(TEAM),+ &json!({ "properties": { "type": "AND", "values": leaves } }),+ )+ .unwrap();+ builder.freeze(UTC)+}++fn event(person: Uuid, props: &str, offset: i64, ts: &str) -> CohortStreamEvent {+ CohortStreamEvent {+ team_id: TEAM,+ person_id: person.to_string(),+ distinct_id: "d".to_string(),+ uuid: format!("uuid-{offset}"),+ event: "$pageview".to_string(),+ timestamp: ts.to_string(),+ properties: Some("{}".to_string()),+ person_properties: Some(props.to_string()),+ elements_chain: None,+ source_offset: offset,+ source_partition: 0,+ redirected_from: None,+ redirect_hops: 0,+ }+}++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 person(n: u128) -> Uuid {+ Uuid::from_u128(n)+}++fn applied(entries: &[(i32, i64)]) -> AppliedOffsets {+ let mut a = AppliedOffsets::default();+ for &(partition, offset) in entries {+ a.record(partition, offset);+ }+ a+}++fn feed(store: &CohortStore, filters: &TeamFilters, event: &CohortStreamEvent) -> EventOutcome {+ process_event(PARTITION, store, filters, event).unwrap()+}++fn record(store: &CohortStore, who: Uuid) -> Option<PersonRecord> {+ store+ .get_person_record(&PersonRecordKey::new(PARTITION, TEAM as u64, who))+ .unwrap()+ .map(|bytes| PersonRecord::decode(&bytes).unwrap())+}++fn is_member(store: &CohortStore, who: Uuid, hash: [u8; 16]) -> bool {+ record(store, who).is_some_and(|r| r.matched.contains(&hash))+}++/// Sort a transition list by its condition hash + kind so two folds compare as multisets.+fn sorted(transitions: &[LeafTransition]) -> Vec<([u8; 16], TransitionKind)> {+ let mut out: Vec<_> = transitions+ .iter()+ .map(|t| (t.condition_hash, t.kind))+ .collect();+ out.sort_by_key(|(h, k)| (*h, matches!(k, TransitionKind::Left)));+ out+}++const PRO: &str = r#"{"email":"[email protected]","plan":"pro"}"#;+const FREE: &str = r#"{"email":"[email protected]","plan":"free"}"#;+const NO_EMAIL: &str = r#"{"email":"[email protected]","plan":"pro"}"#;++// --- Decision-table rows through the fold ---++#[test]+fn row0_inactive_person_side_neither_reads_nor_writes_the_record() {+ // No person conditions at all in the catalog: any event's person side is inactive.+ let (_dir, store) = temp_store();+ let f = filters(vec![email_leaf()]);+ let alice = person(1);++ // An event whose person_properties are empty is inactive even with person conditions present.+ let inactive = CohortStreamEvent {+ person_properties: Some(String::new()),+ ..event(alice, PRO, 0, "2026-05-26 10:00:00.000000")+ };+ let out = feed(&store, &f, &inactive);+ assert_eq!(+ out.skipped, None,+ "an empty-props event is a processed no-op"+ );+ assert!(out.transitions.is_empty());+ assert!(record(&store, alice).is_none(), "row 0 writes no record");+}++#[test]+fn row4b_first_eval_enters_true_conditions_and_writes_the_record() {+ let (_dir, store) = temp_store();+ let f = filters(vec![email_leaf(), plan_leaf()]);+ let alice = person(1);++ // First sighting: absent prior ⇒ Eval. Both conditions true ⇒ two Entered.+ let out = feed(+ &store,+ &f,+ &event(alice, PRO, 0, "2026-05-26 10:00:00.000000"),+ );+ assert_eq!(+ sorted(&out.transitions),+ vec![+ (EMAIL_HASH, TransitionKind::Entered),+ (PLAN_HASH, TransitionKind::Entered),+ ],+ );+ let r = record(&store, alice).unwrap();+ assert!(r.matched.contains(&EMAIL_HASH) && r.matched.contains(&PLAN_HASH));+ assert!(+ r.applied_offsets.is_replay(0, 0),+ "the event offset advanced dedup"+ );+}++#[test]+fn row1_replay_of_an_applied_offset_stages_nothing() {+ let (_dir, store) = temp_store();+ let f = filters(vec![email_leaf(), plan_leaf()]);+ let alice = person(1);++ feed(+ &store,+ &f,+ &event(alice, PRO, 0, "2026-05-26 10:00:00.000000"),+ );+ let before = record(&store, alice).unwrap();++ // Replay the same offset: is_replay(0, 0) ⇒ skip, nothing changes.+ let out = feed(+ &store,+ &f,+ &event(alice, FREE, 0, "2026-05-26 11:00:00.000000"),+ );+ assert!(out.transitions.is_empty(), "a replay flips nothing");+ assert_eq!(+ record(&store, alice).unwrap(),+ before,+ "a replay leaves the record byte-identical"+ );+}++#[test]+fn row4a_fingerprint_match_skips_eval_but_advances_the_stamp() {+ let (_dir, store) = temp_store();+ let f = filters(vec![email_leaf(), plan_leaf()]);+ let alice = person(1);++ feed(+ &store,+ &f,+ &event(alice, PRO, 0, "2026-05-26 10:00:00.000000"),+ );+ let stamp_before = record(&store, alice).unwrap().stamp;++ // Identical props + catalog, newer event: fingerprints match ⇒ SkipEval. No transition, but the+ // stamp advances (load-bearing so a later out-of-order event cannot wrongly win argMax).+ let out = feed(+ &store,+ &f,+ &event(alice, PRO, 1, "2026-05-26 12:00:00.000000"),+ );+ assert!(+ out.transitions.is_empty(),+ "a fingerprint-match event flips nothing"+ );+ let after = record(&store, alice).unwrap();+ assert!(+ after.stamp > stamp_before,+ "SkipEval adopts the fresh stamp"+ );+ assert!(after.applied_offsets.is_replay(0, 1), "and advances dedup");+ assert!(after.matched.contains(&EMAIL_HASH) && after.matched.contains(&PLAN_HASH));+}++#[test]+fn row4b_props_change_re_evaluates_and_leaves_the_false_condition() {+ let (_dir, store) = temp_store();+ let f = filters(vec![email_leaf(), plan_leaf()]);+ let alice = person(1);++ feed(+ &store,+ &f,+ &event(alice, PRO, 0, "2026-05-26 10:00:00.000000"),+ );+ // plan → free: props fingerprint mismatch ⇒ Eval. plan leaves; email stays.+ let out = feed(+ &store,+ &f,+ &event(alice, FREE, 1, "2026-05-26 11:00:00.000000"),+ );+ assert_eq!(+ sorted(&out.transitions),+ vec![(PLAN_HASH, TransitionKind::Left)],+ );+ assert!(is_member(&store, alice, EMAIL_HASH));+ assert!(!is_member(&store, alice, PLAN_HASH));+}++#[test]+fn row3_argmax_stale_event_advances_dedup_and_last_seen_but_not_membership() {+ let (_dir, store) = temp_store();+ let f = filters(vec![email_leaf(), plan_leaf()]);+ let alice = person(1);++ // Newest first (offset 0, ts 13:00): both enter.+ feed(+ &store,+ &f,+ &event(alice, PRO, 0, "2026-05-26 13:00:00.000000"),+ );+ let before = record(&store, alice).unwrap();++ // An older event (ts 12:00) on a new source partition. It is argMax-stale, so membership and the+ // stamp are unchanged — but it still records its offset (a genuine first sighting of partition 9).+ let older = CohortStreamEvent {+ source_partition: 9,+ ..event(alice, NO_EMAIL, 5, "2026-05-26 12:00:00.000000")+ };+ let out = feed(&store, &f, &older);+ assert!(out.transitions.is_empty(), "a stale event flips nothing");+ let after = record(&store, alice).unwrap();+ assert_eq!(after.stamp, before.stamp, "argMax kept the newer stamp");+ assert_eq!(+ after.matched, before.matched,+ "membership unchanged by a stale event"+ );+ assert!(+ after.applied_offsets.is_replay(9, 5),+ "the stale event still recorded its offset (row 2 precedes row 3)",+ );+ assert_eq!(+ after.last_seen_ms, before.last_seen_ms,+ "an older event never lowers last_seen"+ );+}++/// The stamp-advance counterexample: without row 4a advancing the stamp, an out-of-order event landing+/// between the old and new stamps would wrongly win argMax. Because 4a advances it, that middle event+/// is stale.+#[test]+fn row4a_stamp_advance_makes_an_intervening_out_of_order_event_stale() {+ let (_dir, store) = temp_store();+ let f = filters(vec![email_leaf(), plan_leaf()]);+ let alice = person(1);++ // t0 at 10:00 (enter).+ feed(+ &store,+ &f,+ &event(alice, PRO, 0, "2026-05-26 10:00:00.000000"),+ );+ // t2 at 14:00, identical props ⇒ SkipEval, stamp advances to 14:00.+ feed(+ &store,+ &f,+ &event(alice, PRO, 1, "2026-05-26 14:00:00.000000"),+ );++ // t1 at 12:00 (between t0 and t2), plan → free. Its ms (12:00) < the advanced stamp (14:00) ⇒+ // stale ⇒ plan must NOT leave. Had 4a not advanced the stamp, t1 would beat t0's 10:00 and wrongly+ // flip plan.+ let out = feed(+ &store,+ &f,+ &event(alice, FREE, 2, "2026-05-26 12:00:00.000000"),+ );+ assert!(+ out.transitions.is_empty(),+ "the intervening older event is stale"+ );+ assert!(+ is_member(&store, alice, PLAN_HASH),+ "plan stayed TRUE because 4a advanced the stamp past the intervening event",+ );+}++/// The replay-advance counterexample: an argMax-stale event still advances dedup, so a later replay of+/// it is skipped.+#[test]+fn a_stale_event_advances_dedup_so_its_replay_is_then_skipped() {+ let (_dir, store) = temp_store();+ let f = filters(vec![email_leaf(), plan_leaf()]);+ let alice = person(1);++ feed(+ &store,+ &f,+ &event(alice, PRO, 0, "2026-05-26 13:00:00.000000"),+ );+ let stale = CohortStreamEvent {+ source_partition: 9,+ ..event(alice, FREE, 5, "2026-05-26 12:00:00.000000")+ };+ feed(&store, &f, &stale); // argMax-stale, but records (9, 5)+ let after_stale = record(&store, alice).unwrap();++ // Replay the stale event: now a replay via the advanced dedup ⇒ skip, no change.+ let out = feed(&store, &f, &stale);+ assert!(out.transitions.is_empty());+ assert_eq!(+ record(&store, alice).unwrap(),+ after_stale,+ "the replay changed nothing"+ );+}++// --- Record-vs-per-leaf argMax equivalence ---++/// The old per-leaf rule: each condition's `matches` is the value of the argMax-latest event by+/// `(event_ms, source_offset)`. This oracle computes the final membership set that rule would produce+/// for a sequence of (props, event_ms, offset) events, and asserts the record's matched set equals it.+#[test]+fn record_argmax_matches_the_old_per_leaf_last_write_wins_rule() {+ let (_dir, store) = temp_store();+ let f = filters(vec![email_leaf(), plan_leaf()]);+ let alice = person(1);++ // Out-of-order events (offset == arrival order; ms drives argMax). Each row: (props, ms_suffix,+ // offset). All same partition 0. `email` is TRUE iff props has email [email protected]; `plan` iff plan pro.+ let seq: &[(&str, &str, i64)] = &[+ (PRO, "12:00:00", 0), // enter both+ (FREE, "14:00:00", 1), // newest so far: plan false+ (PRO, "13:00:00", 2), // older than offset-1: stale, ignored+ (NO_EMAIL, "15:00:00", 3), // newest: email false, plan true+ (FREE, "13:30:00", 4), // older than offset-3: stale+ ];++ // Oracle: the winning event per the argMax key is the one with the max (ms, offset).+ let base = "2026-05-26 ";+ let ms =+ |suffix: &str| clickhouse_timestamp_to_millis(&format!("{base}{suffix}.000000")).unwrap();+ let winner = seq+ .iter()+ .max_by_key(|(_, suffix, offset)| (ms(suffix), *offset))+ .unwrap();+ let email_expected = winner.0.contains("[email protected]");+ let plan_expected = winner.0.contains("\"plan\":\"pro\"");++ for (props, suffix, offset) in seq {+ feed(+ &store,+ &f,+ &event(alice, props, *offset, &format!("{base}{suffix}.000000")),+ );+ }++ assert_eq!(+ is_member(&store, alice, EMAIL_HASH),+ email_expected,+ "email membership matches the argMax-winning event",+ );+ assert_eq!(+ is_member(&store, alice, PLAN_HASH),+ plan_expected,+ "plan membership matches the argMax-winning event",+ );+}++// --- Record-skip parity (successor of person_memo_parity) ---++/// Feed the same event stream two ways: once normally (the fingerprint fast path `SkipEval` fires on+/// repeats), once with the stored record's fingerprints zeroed between events so every event takes the+/// full-evaluation arm. The emitted transitions (multiset), the final matched set + stamp, and the+/// event outcomes must be identical — proving `SkipEval` is indistinguishable from a re-evaluation.+#[test]+fn skip_eval_is_indistinguishable_from_a_full_re_evaluation() {+ let seq: &[(&str, i64, &str)] = &[+ (PRO, 0, "2026-05-26 10:00:00.000000"), // enter both+ (PRO, 1, "2026-05-26 11:00:00.000000"), // repeat (SkipEval on the normal run)+ (FREE, 2, "2026-05-26 12:00:00.000000"), // plan leaves+ (FREE, 3, "2026-05-26 13:00:00.000000"), // repeat+ (PRO, 4, "2026-05-26 14:00:00.000000"), // plan re-enters+ ];+ let alice = person(1);++ // Normal run.+ let (_dir_a, store_a) = temp_store();+ let f_a = filters(vec![email_leaf(), plan_leaf()]);+ let mut normal_transitions: Vec<([u8; 16], TransitionKind)> = Vec::new();+ for (props, offset, ts) in seq {+ let out = feed(&store_a, &f_a, &event(alice, props, *offset, ts));+ normal_transitions.extend(sorted(&out.transitions));+ }++ // Forced-re-eval run: zero the record's fingerprints before each event so the decision table can+ // never take the SkipEval fast path — it must re-evaluate every time.+ let (_dir_b, store_b) = temp_store();+ let f_b = filters(vec![email_leaf(), plan_leaf()]);+ let mut forced_transitions: Vec<([u8; 16], TransitionKind)> = Vec::new();+ for (props, offset, ts) in seq {+ if let Some(mut r) = record(&store_b, alice) {+ r.props_fingerprint = PropsFingerprint(0);+ r.catalog_fingerprint = CatalogFingerprint(0);+ store_b+ .write_batch(|b| {+ b.put::<PersonRecords>(+ &PersonRecordKey::new(PARTITION, TEAM as u64, alice),+ &r.encode(),+ )+ })+ .unwrap();+ }+ let out = feed(&store_b, &f_b, &event(alice, props, *offset, ts));+ forced_transitions.extend(sorted(&out.transitions));+ }++ assert_eq!(+ normal_transitions, forced_transitions,+ "SkipEval must emit the same transitions as a forced re-evaluation",+ );+ // Final membership must agree.+ assert_eq!(+ record(&store_a, alice).unwrap().matched,+ record(&store_b, alice).unwrap().matched,+ "final matched set identical",+ );+ assert_eq!(+ record(&store_a, alice).unwrap().stamp,+ record(&store_b, alice).unwrap().stamp,+ "final stamp identical",+ );+}++// --- Catalog add / remove / re-add retention through the fold ---++/// A condition removed from the catalog leaves no `Left` (the hash is retained as an orphan); re-added+/// while still true emits no duplicate `Entered`; re-added then false emits `Left`.+#[test]+fn catalog_remove_readd_retention_through_the_fold() {+ let alice = person(1);++ // Start with both conditions; alice matches both.+ let (_dir, store) = temp_store();+ let with_both = filters(vec![email_leaf(), plan_leaf()]);+ let out = feed(+ &store,+ &with_both,+ &event(alice, PRO, 0, "2026-05-26 10:00:00.000000"),+ );+ assert_eq!(out.transitions.len(), 2, "both enter");++ // Remove the plan condition from the catalog. A fresh event under the reduced catalog re-evaluates+ // (catalog fingerprint changed) but must NOT emit Left for plan — its hash is a retained orphan.+ let email_only = filters(vec![email_leaf()]);+ let out = feed(+ &store,+ &email_only,+ &event(alice, PRO, 1, "2026-05-26 11:00:00.000000"),+ );+ assert!(+ out.transitions.is_empty(),+ "removing a condition emits no Left (retained orphan)",+ );+ // The orphan hash is still in the stored matched set.+ assert!(+ record(&store, alice).unwrap().matched.contains(&PLAN_HASH),+ "the removed condition's hash is retained, not dropped",+ );++ // Re-add plan while alice still matches it: no duplicate Entered (the hash never left the set).+ let out = feed(+ &store,+ &with_both,+ &event(alice, PRO, 2, "2026-05-26 12:00:00.000000"),+ );+ assert!(+ out.transitions.is_empty(),+ "re-adding a still-true retained condition does not re-Enter",+ );++ // Re-add plan but now alice is false for it: Left fires (a genuine departure).+ let out = feed(+ &store,+ &with_both,+ &event(alice, FREE, 3, "2026-05-26 13:00:00.000000"),+ );+ assert_eq!(+ sorted(&out.transitions),+ vec![(PLAN_HASH, TransitionKind::Left)],+ "the re-added condition going false emits Left",+ );+}++/// A person with a redirect-dedup ancestor whose main-map offsets are distinct: the fold never+/// confuses the two maps. (Guards the `DedupCoords` wiring in `fold_person`.)+#[test]+fn direct_and_redirected_events_use_distinct_dedup_maps() {+ let (_dir, store) = temp_store();+ let f = filters(vec![email_leaf()]);+ let p_new = person(2);+ let ancestor = person(1);++ // Seed a member record with main {5:50} and an ancestor entry {5:100}.+ let mut seed = PersonRecord::absent();+ seed.matched = [EMAIL_HASH].into_iter().collect();+ seed.applied_offsets = applied(&[(5, 50)]);+ seed.redirect_dedup.insert(ancestor, applied(&[(5, 100)]));+ store+ .write_batch(|b| {+ b.put::<PersonRecords>(+ &PersonRecordKey::new(PARTITION, TEAM as u64, p_new),+ &seed.encode(),+ )+ })+ .unwrap();++ // A direct event on source partition 5 at offset 60 (> main's 50) folds even though 60 < the+ // ancestor's 100 — the main map gates direct events, not the ancestor entry.+ let direct = CohortStreamEvent {+ source_partition: 5,+ ..event(p_new, PRO, 60, "2026-05-26 10:00:00.000000")+ };+ let out = feed(&store, &f, &direct);+ assert!(out.transitions.is_empty(), "already a member; no re-enter");+ let after = record(&store, p_new).unwrap();+ assert!(+ after.applied_offsets.is_replay(5, 60),+ "the main map advanced"+ );+ assert!(+ after.redirect_dedup[&ancestor].is_replay(5, 100)+ && !after.redirect_dedup[&ancestor].is_replay(5, 101),+ "the ancestor entry is untouched by a direct event",+ );+}diff --git a/rust/cohort-stream-processor/tests/stage1_worker.rs b/rust/cohort-stream-processor/tests/stage1_worker.rsindex 0ab8ad1c2b42..b142dfee1b55 100644--- a/rust/cohort-stream-processor/tests/stage1_worker.rs+++ b/rust/cohort-stream-processor/tests/stage1_worker.rs@@ -22,13 +22,14 @@ 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::bucket_tz::{day_idx_in_tz, start_of_day_ms_in_tz};+use cohort_stream_processor::stage1::person_record::{MatchedSet, PersonRecord};use cohort_stream_processor::stage1::{clickhouse_timestamp_to_millis, AppliedOffsets, LeafTransition, Stage1State, StateVariant,StatefulRecord, TransitionKind,};use cohort_stream_processor::store::{- CohortStore, LeafStateKey, OffloadConfig, OffloadMode, PersonIndexKey, Stage1Key, StoreConfig,- StoreHandle,+ Behavioral, BehavioralKey, CohortStore, LeafStateKey, OffloadConfig, OffloadMode, PersonPrefix,+ PersonRecordKey, PersonRecords, StoreConfig, StoreHandle,};use cohort_stream_processor::workers::{process_event, MergeWorkerDeps, SkipReason, Stage1Worker};use serde_json::{json, Value};@@ -229,21 +230,19 @@ fn event_at(}}-fn stage1_key(lsk: LeafStateKey, person: Uuid) -> Stage1Key {- Stage1Key {- partition_id: PARTITION_ID,- team_id: TEAM as u64,- leaf_state_key: lsk,- person_id: person,- }+fn behavioral_key(lsk: LeafStateKey, person: Uuid) -> BehavioralKey {+ BehavioralKey::new(PARTITION_ID, TEAM as u64, person, lsk)}-fn person_index_key(person: Uuid) -> PersonIndexKey {- PersonIndexKey {- partition_id: PARTITION_ID,- team_id: TEAM as u64,- person_id: person,- }+/// One person's stored leaf-state keys, read by prefix-scanning their `cf_behavioral` slice (the+/// person-clustered replacement for the old per-person index). Returned in lsk-byte order.+fn person_leaves(store: &CohortStore, person: Uuid) -> Vec<LeafStateKey> {+ store+ .scan_behavioral_prefix(PersonPrefix::new(PARTITION_ID, TEAM as u64, person))+ .unwrap()+ .into_iter()+ .map(|(key, _)| key.lsk())+ .collect()}fn state_at(store: &CohortStore, lsk: LeafStateKey, person: Uuid) -> Option<Stage1State> {@@ -254,11 +253,48 @@ fn state_at(store: &CohortStore, lsk: LeafStateKey, person: Uuid) -> Option<Stag/// replay-dedup assertions.fn record_at(store: &CohortStore, lsk: LeafStateKey, person: Uuid) -> Option<StatefulRecord> {store- .get_stage1(&stage1_key(lsk, person))+ .get_behavioral(&behavioral_key(lsk, person)).unwrap().map(|bytes| StatefulRecord::decode(&bytes).unwrap())}+/// The person's decoded durable record, or `None` when absent.+fn person_record_at(store: &CohortStore, who: Uuid) -> Option<PersonRecord> {+ store+ .get_person_record(&PersonRecordKey::new(PARTITION_ID, TEAM as u64, who))+ .unwrap()+ .map(|bytes| PersonRecord::decode(&bytes).unwrap())+}++/// Whether `who`'s person leaf (PERSON_HASH) is currently a member, per the durable record.+fn person_is_member(store: &CohortStore, who: Uuid) -> bool {+ person_record_at(store, who).is_some_and(|r| r.matched.contains(&PERSON_HASH))+}++/// Write a person record for `who` with the given matched hashes + optional main-map/ancestor dedup.+fn write_person_record(+ store: &CohortStore,+ who: Uuid,+ matched: &[[u8; 16]],+ applied: AppliedOffsets,+ redirect: &[(Uuid, AppliedOffsets)],+) {+ let mut record = PersonRecord::absent();+ record.matched = MatchedSet::from_iter(matched.iter().copied());+ record.applied_offsets = applied;+ for (anc, offs) in redirect {+ record.redirect_dedup.insert(*anc, offs.clone());+ }+ store+ .write_batch(|b| {+ b.put::<PersonRecords>(+ &PersonRecordKey::new(PARTITION_ID, TEAM as u64, who),+ &record.encode(),+ )+ })+ .unwrap();+}+/// Assert `offset` is the recorded high-water mark for `partition` — probed via the public/// `is_replay` (the inner map is intentionally private): `offset` is a replay, `offset + 1` is new.fn assert_high_water(applied: &AppliedOffsets, partition: i32, offset: i64) {@@ -463,27 +499,28 @@ fn mixed_present_corrupt_absent_read_set_stays_aligned() {);store.write_batch(|batch| {- batch.put_stage1(&stage1_key(single_lsk, alice), &seeded.encode());+ batch.put::<Behavioral>(&behavioral_key(single_lsk, alice), &seeded.encode());// Corrupt: undecodable bytes under the daily leaf's key. The person leaf stays absent.- batch.put_stage1(&stage1_key(daily_lsk, alice), b"not a record");+ batch.put::<Behavioral>(&behavioral_key(daily_lsk, alice), b"not a record");}).unwrap();let out = process_event(PARTITION_ID, &store, &filters, &event(alice, 1, 10)).unwrap();assert_eq!(out.skipped, None);- // Only the absent slot first-writes: one Entered, one index append, both for exactly that leaf.+ // Only the absent slot first-writes: one Entered for exactly that leaf, and the person record now+ // exists (the person leaf was absent before the event).assert_eq!(out.transitions.len(), 1);assert_eq!(out.transitions[0].leaf_state_key, person_lsk);assert_eq!(out.transitions[0].kind, TransitionKind::Entered);- assert_eq!(- store.get_person_index(&person_index_key(alice)).unwrap(),- vec![person_lsk],+ assert!(+ person_record_at(&store, alice).is_some(),+ "the first-written person record is now stored",+ );+ assert!(+ person_is_member(&store, alice),+ "the person leaf evaluated true",);- match state_at(&store, person_lsk, alice).unwrap() {- Stage1State::PersonProperty { matches, .. } => assert!(matches),- other => panic!("expected PersonProperty, got {other:?}"),- }// The present slot folded the event into its decoded prior: the newer seeded ts survives the// max, and the event's offset advanced the dedup high-water mark.@@ -507,7 +544,7 @@ fn mixed_present_corrupt_absent_read_set_stays_aligned() {// The corrupt slot is skipped, not written: the garbage stays in place.assert_eq!(store- .get_stage1(&stage1_key(daily_lsk, alice))+ .get_behavioral(&behavioral_key(daily_lsk, alice)).unwrap().unwrap(),b"not a record",@@ -653,15 +690,27 @@ fn ten_thousand_events_then_replay_is_idempotent() {assert_eq!(unexpected, 0);for &p in &persons {- for lsk in filters.by_lsk.keys() {+ // The behavioral leaf lives in `cf_behavioral`; the person leaf lives in the durable record.+ for (lsk, leaf) in &filters.by_lsk {+ if leaf.variant == StateVariant::PersonProperty {+ continue;+ }assert!(- store.get_stage1(&stage1_key(*lsk, p)).unwrap().is_some(),- "missing state row",+ store+ .get_behavioral(&behavioral_key(*lsk, p))+ .unwrap()+ .is_some(),+ "missing behavioral state row",);}assert_eq!(- store.get_person_index(&person_index_key(p)).unwrap().len(),- 2+ person_leaves(&store, p).len(),+ 1,+ "the person's one behavioral leaf is stored in cf_behavioral",+ );+ assert!(+ person_is_member(&store, p),+ "the person leaf is a member per the durable record",);}@@ -687,10 +736,18 @@ fn snapshot_state(store: &CohortStore, filters: &TeamFilters, persons: &[Uuid])let mut map = BTreeMap::new();for &p in persons {for lsk in filters.by_lsk.keys() {- if let Some(bytes) = store.get_stage1(&stage1_key(*lsk, p)).unwrap() {+ if let Some(bytes) = store.get_behavioral(&behavioral_key(*lsk, p)).unwrap() {map.insert((p.as_u128(), lsk.0), bytes);}}+ // The person leaf's state now lives in the durable record, not `cf_behavioral`; capture its+ // bytes under the person LSK's (otherwise-empty) slot so replay-idempotency still covers it.+ if let Some(bytes) = store+ .get_person_record(&PersonRecordKey::new(PARTITION_ID, TEAM as u64, p))+ .unwrap()+ {+ map.insert((p.as_u128(), PERSON_HASH), bytes);+ }}map}@@ -699,7 +756,6 @@ fn snapshot_state(store: &CohortStore, filters: &TeamFilters, persons: &[Uuid])fn cross_partition_low_offset_is_not_masked_by_a_high_offset_elsewhere() {let (_dir, store) = temp_store();let filters = build_team_filters(vec![(CohortId(1), cohort(vec![person_leaf()]))]);- let lsk = LeafStateKey::for_person_property(&PERSON_HASH);let p = person(1);// Enter from source partition 10 at a high offset.@@ -717,7 +773,7 @@ fn cross_partition_low_offset_is_not_masked_by_a_high_offset_elsewhere() {);assert_eq!(out.transitions[0].kind, TransitionKind::Left);- let applied = record_at(&store, lsk, p).unwrap().applied_offsets;+ let applied = person_record_at(&store, p).unwrap().applied_offsets;assert_high_water(&applied, 10, 100);assert_high_water(&applied, 20, 3);}@@ -757,7 +813,6 @@ fn cross_partition_replay_does_not_double_apply_or_disturb_other_partitions() {fn cross_partition_person_replay_leaves_state_and_other_partitions_intact() {let (_dir, store) = temp_store();let filters = build_team_filters(vec![(CohortId(1), cohort(vec![person_leaf()]))]);- let lsk = LeafStateKey::for_person_property(&PERSON_HASH);let p = person(1);let from_a = person_event(p, "[email protected]", "2026-05-26 12:00:00.000000", 10, 5);@@ -765,7 +820,7 @@ fn cross_partition_person_replay_leaves_state_and_other_partitions_intact() {let later_b = person_event(p, "[email protected]", "2026-05-26 13:00:00.000000", 20, 10);process_event(PARTITION_ID, &store, &filters, &later_b).unwrap();- let before = record_at(&store, lsk, p).unwrap();+ let before = person_record_at(&store, p).unwrap();assert_high_water(&before.applied_offsets, 10, 5);assert_high_water(&before.applied_offsets, 20, 10);@@ -776,7 +831,7 @@ fn cross_partition_person_replay_leaves_state_and_other_partitions_intact() {);assert_eq!(- record_at(&store, lsk, p).unwrap(),+ person_record_at(&store, p).unwrap(),before,"the person replay left state and partition 20 untouched",);@@ -786,7 +841,6 @@ fn cross_partition_person_replay_leaves_state_and_other_partitions_intact() {fn argmax_stale_event_still_advances_applied_offsets_across_partitions() {let (_dir, store) = temp_store();let filters = build_team_filters(vec![(CohortId(1), cohort(vec![person_leaf()]))]);- let lsk = LeafStateKey::for_person_property(&PERSON_HASH);let p = person(1);// Newest write from partition 10 (offset 5).@@ -799,18 +853,14 @@ fn argmax_stale_event_still_advances_applied_offsets_across_partitions() {let out = process_event(PARTITION_ID, &store, &filters, &older_b).unwrap();assert!(out.transitions.is_empty(), "a stale event flips nothing");- let record = record_at(&store, lsk, p).unwrap();- match record.state {- Stage1State::PersonProperty {- matches,- last_updated_offset,- ..- } => {- assert!(matches, "the stale event kept the newer match");- assert_eq!(last_updated_offset, 5, "argMax kept partition 10's offset");- }- other => panic!("expected PersonProperty, got {other:?}"),- }+ // Under B2, a stale event advances the record's dedup + last_seen but does NOT rewrite the matched+ // set or stamp from its own snapshot: the newer match and its stamp survive unchanged.+ let record = person_record_at(&store, p).unwrap();+ assert!(+ record.matched.contains(&PERSON_HASH),+ "the stale event kept the newer match",+ );+ assert_eq!(record.stamp.offset, 5, "argMax kept partition 10's offset");assert_high_water(&record.applied_offsets, 10, 5);assert_high_water(&record.applied_offsets, 20, 0);}@@ -820,7 +870,6 @@ fn out_of_order_person_events_keep_the_latest_by_event_time() {let (_dir, store) = temp_store();let filters = build_team_filters(vec![(CohortId(1), cohort(vec![person_leaf()]))]);let bob = person(1);- let lsk = LeafStateKey::for_person_property(&PERSON_HASH);let newest_ts = "2026-05-26 12:00:00.000000";let newest = person_event(bob, "[email protected]", newest_ts, 1, 100);@@ -833,18 +882,13 @@ fn out_of_order_person_events_keep_the_latest_by_event_time() {assert!(out.transitions.is_empty(), "stale event emits nothing");let newest_ms = clickhouse_timestamp_to_millis(newest_ts).unwrap();- match state_at(&store, lsk, bob).unwrap() {- Stage1State::PersonProperty {- matches,- last_updated_at_ms,- last_updated_offset,- } => {- assert!(matches, "the newest-by-event-time value (a match) is kept");- assert_eq!(last_updated_at_ms, newest_ms);- assert_eq!(last_updated_offset, 100);- }- other => panic!("expected PersonProperty, got {other:?}"),- }+ let record = person_record_at(&store, bob).unwrap();+ assert!(+ record.matched.contains(&PERSON_HASH),+ "the newest-by-event-time value (a match) is kept",+ );+ assert_eq!(record.stamp.ms, newest_ms);+ assert_eq!(record.stamp.offset, 100);}#[test]@@ -926,15 +970,18 @@ fn person_records_every_event_with_no_false_to_false_transition() {let (_dir, store) = temp_store();let filters = build_team_filters(vec![(CohortId(1), cohort(vec![person_leaf()]))]);let carol = person(1);- let lsk = LeafStateKey::for_person_property(&PERSON_HASH);let miss = person_event(carol, "[email protected]", "2026-05-26 12:00:00.000000", 1, 10);let out = process_event(PARTITION_ID, &store, &filters, &miss).unwrap();assert!(out.transitions.is_empty(), "no false→false transition");- match state_at(&store, lsk, carol).expect("row written even on non-match") {- Stage1State::PersonProperty { matches, .. } => assert!(!matches),- other => panic!("expected PersonProperty, got {other:?}"),- }+ assert!(+ person_record_at(&store, carol).is_some(),+ "record written even on non-match",+ );+ assert!(+ !person_is_member(&store, carol),+ "the non-matching person leaf is not a member",+ );let hit = person_event(carol, "[email protected]", "2026-05-26 13:00:00.000000", 1, 11);let out = process_event(PARTITION_ID, &store, &filters, &hit).unwrap();@@ -967,9 +1014,8 @@ fn person_path_is_inactive_for_null_or_empty_person_properties() {let (_dir, store) = temp_store();let filters = build_team_filters(vec![(CohortId(1), cohort(vec![person_leaf()]))]);let erin = person(1);- let lsk = LeafStateKey::for_person_property(&PERSON_HASH);- // Null and empty-string are both JS-falsy → person path never runs → processed no-op, no row.+ // Null and empty-string are both JS-falsy → person path never runs → processed no-op, no record.for (offset, payload) in [(10, None), (11, Some(String::new()))] {let ev = CohortStreamEvent {person_properties: payload,@@ -979,8 +1025,8 @@ fn person_path_is_inactive_for_null_or_empty_person_properties() {assert_eq!(out.skipped, None, "processed as a no-op, not skipped whole");assert!(out.transitions.is_empty());assert!(- state_at(&store, lsk, erin).is_none(),- "no person row written"+ person_record_at(&store, erin).is_none(),+ "no person record written");}}@@ -993,7 +1039,6 @@ fn empty_person_properties_does_not_skip_a_behavioral_match() {cohort(vec![behavioral_leaf(7), person_leaf()]),)]);let behavioral_lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];- let person_lsk = LeafStateKey::for_person_property(&PERSON_HASH);let alice = person(1);// Empty-string person_properties is JS-falsy: Node skips the person path but still runs the@@ -1019,8 +1064,8 @@ fn empty_person_properties_does_not_skip_a_behavioral_match() {"behavioral row written");assert!(- state_at(&store, person_lsk, alice).is_none(),- "empty person_properties → person path inactive, no row",+ person_record_at(&store, alice).is_none(),+ "empty person_properties → person path inactive, no record",);}@@ -1030,16 +1075,14 @@ fn non_boolean_person_result_coerces_to_false() {let nonbool = person_leaf_with_bytecode(json!(["_H", 1, 33, 42]));let filters = build_team_filters(vec![(CohortId(1), cohort(vec![nonbool]))]);let frank = person(1);- let lsk = LeafStateKey::for_person_property(&PERSON_HASH);let out = process_event(PARTITION_ID, &store, &filters, &event(frank, 1, 0)).unwrap();assert!(out.transitions.is_empty(), "false → no enter");- match state_at(&store, lsk, frank).expect("row written") {- Stage1State::PersonProperty { matches, .. } => {- assert!(!matches, "non-bool result coerced to false")- }- other => panic!("expected PersonProperty, got {other:?}"),- }+ assert!(person_record_at(&store, frank).is_some(), "record written",);+ assert!(+ !person_is_member(&store, frank),+ "non-bool result coerced to false",+ );}#[tokio::test]@@ -1052,7 +1095,6 @@ async fn spawned_worker_drains_a_batch_and_commits_state() {cohort(vec![behavioral_leaf(7), person_leaf()]),)]);let behavioral_lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];- let person_lsk = LeafStateKey::for_person_property(&PERSON_HASH);let alice = person(1);let catalog = catalog_of(filters);@@ -1078,13 +1120,14 @@ async fn spawned_worker_drains_a_batch_and_commits_state() {worker.join().await.unwrap();assert!(state_at(&store, behavioral_lsk, alice).is_some());- assert!(state_at(&store, person_lsk, alice).is_some());+ assert!(+ person_is_member(&store, alice),+ "the person leaf entered via the durable record",+ );assert_eq!(- store- .get_person_index(&person_index_key(alice))- .unwrap()- .len(),- 2+ person_leaves(&store, alice).len(),+ 1,+ "alice's one behavioral leaf is stored in cf_behavioral",);let changes = sink.changes();assert_eq!(@@ -1263,14 +1306,9 @@ async fn spawned_worker_skips_events_for_unknown_teams() {drop(tx);worker.join().await.unwrap();- let key = Stage1Key {- partition_id: PARTITION_ID,- team_id: 999,- leaf_state_key: behavioral_lsk,- person_id: alice,- };+ let key = BehavioralKey::new(PARTITION_ID, 999, alice, behavioral_lsk);assert!(- store.get_stage1(&key).unwrap().is_none(),+ store.get_behavioral(&key).unwrap().is_none(),"no write for unknown team");assert!(sink.changes().is_empty());@@ -2226,34 +2264,25 @@ fn applied(entries: &[(i32, i64)]) -> AppliedOffsets {applied}-/// Seed a person-property record (with a chosen dedup state) directly into `cf_stage1`.-fn seed_person_record(store: &CohortStore, lsk: LeafStateKey, who: Uuid, record: &StatefulRecord) {- store- .write_batch(|b| b.put_stage1(&stage1_key(lsk, who), &record.encode()))- .unwrap();-}-#[test]fn fresh_event_on_a_redirect_dedup_partition_still_folds_main_map_authoritative() {// A fresh (non-redirected) P_new event must dedup against the MAIN map, not an ancestor's// `redirect_dedup` entry.let (_dir, store) = temp_store();let filters = build_team_filters(vec![(CohortId(1), cohort(vec![person_leaf()]))]);- let lsk = LeafStateKey::for_person_property(&PERSON_HASH);let p_new = person(2);let ancestor = person(1);// P_new: not a member, main offsets at partition 5 = 50, an ancestor entry at partition 5 = 100.- let mut seed = StatefulRecord::new(- Stage1State::PersonProperty {- matches: false,- last_updated_at_ms: 1_000,- last_updated_offset: 0,- },+ // The seed's stamp/fingerprints stay at the absent() baseline, so the fresh event below takes the+ // Eval arm (its real props fingerprint never equals 0) and re-evaluates the email leaf.+ write_person_record(+ &store,+ p_new,+ &[],applied(&[(5, 50)]),+ &[(ancestor, applied(&[(5, 100)]))],);- seed.redirect_dedup.insert(ancestor, applied(&[(5, 100)]));- seed_person_record(&store, lsk, p_new, &seed);// A fresh event on partition 5 at offset 60: 60 > main's 50 ⇒ fold, even though 60 ≤ the ancestor// entry's 100. The matching email flips the person leaf false→true.@@ -2266,11 +2295,11 @@ fn fresh_event_on_a_redirect_dedup_partition_still_folds_main_map_authoritative("the fresh event folded and flipped");assert_eq!(out.transitions[0].kind, TransitionKind::Entered);- let after = record_at(&store, lsk, p_new).unwrap();- assert!(matches!(- after.state,- Stage1State::PersonProperty { matches: true, .. }- ));+ let after = person_record_at(&store, p_new).unwrap();+ assert!(+ after.matched.contains(&PERSON_HASH),+ "the person leaf is now a member"+ );assert!(after.applied_offsets.is_replay(5, 60),"the main map advanced to the fresh event's offset",@@ -2287,21 +2316,19 @@ fn redirected_event_at_or_below_ancestor_max_is_skipped_then_above_folds() {// A redirected straggler (origin = P_old) must dedup against `redirect_dedup[P_old]`.let (_dir, store) = temp_store();let filters = build_team_filters(vec![(CohortId(1), cohort(vec![person_leaf()]))]);- let lsk = LeafStateKey::for_person_property(&PERSON_HASH);let p_new = person(2);let p_old = person(1);- // P_new is a member; P_old (an ancestor) folded up to offset 100 on partition 5.- let mut seed = StatefulRecord::new(- Stage1State::PersonProperty {- matches: true,- last_updated_at_ms: 1_000,- last_updated_offset: 0,- },+ // P_new is a member; P_old (an ancestor) folded up to offset 100 on partition 5. The seed's+ // stamp/fingerprints stay at the absent() baseline: the above-max event below is fresh and takes+ // the Eval arm, re-evaluating the (now non-matching) email leaf into a Left.+ write_person_record(+ &store,+ p_new,+ &[PERSON_HASH],applied(&[(5, 50)]),+ &[(p_old, applied(&[(5, 100)]))],);- seed.redirect_dedup.insert(p_old, applied(&[(5, 100)]));- seed_person_record(&store, lsk, p_new, &seed);// A redirected event at offset 80 ≤ the ancestor's 100 → replay via redirect_dedup[P_old] → skip.let mut redirected_replay = person_event(p_new, "[email protected]", BASE_TS, 5, 80);@@ -2312,11 +2339,8 @@ fn redirected_event_at_or_below_ancestor_max_is_skipped_then_above_folds() {"a redirected replay at/below the ancestor max is skipped",);assert!(- matches!(- record_at(&store, lsk, p_new).unwrap().state,- Stage1State::PersonProperty { matches: true, .. }- ),- "the skipped replay leaves P_new's state unchanged",+ person_is_member(&store, p_new),+ "the skipped replay leaves P_new's membership unchanged",);// A redirected event at offset 101 > the ancestor's 100 → not a replay → folds (email no longer@@ -2330,7 +2354,7 @@ fn redirected_event_at_or_below_ancestor_max_is_skipped_then_above_folds() {"the above-max redirected event folds");assert_eq!(folded.transitions[0].kind, TransitionKind::Left);- let after = record_at(&store, lsk, p_new).unwrap();+ let after = person_record_at(&store, p_new).unwrap();assert!(after.redirect_dedup[&p_old].is_replay(5, 101),"the ancestor entry advanced to the folded offset",diff --git a/rust/cohort-stream-processor/tests/store.rs b/rust/cohort-stream-processor/tests/store.rsindex cad13aa0d222..ddd0cbd0f85c 100644--- a/rust/cohort-stream-processor/tests/store.rs+++ b/rust/cohort-stream-processor/tests/store.rs@@ -4,8 +4,8 @@#![allow(clippy::disallowed_methods)]use cohort_stream_processor::store::{- Cf, CohortStore, IndexOp, LeafStateKey, MergeAppliedKey, MergeDrainKey, OpaqueCf,- PendingTransferKey, PersonIndexKey, Stage1Key, Stage2Key, StoreConfig, TombstoneKey,+ Behavioral, BehavioralKey, Cf, CohortStore, LeafStateKey, MergeAppliedKey, MergeDrainKey,+ OpaqueCf, PendingTransferKey, PersonPrefix, Stage2Key, StoreConfig, TombstoneKey,};use tempfile::TempDir;use uuid::Uuid;@@ -29,21 +29,8 @@ fn person(n: u128) -> Uuid {Uuid::from_u128(n)}-fn stage1_key(partition: u16, team: u64, leaf: u8, p: u128) -> Stage1Key {- Stage1Key {- partition_id: partition,- team_id: team,- leaf_state_key: lsk(leaf),- person_id: person(p),- }-}--fn person_index_key(partition: u16, team: u64, p: u128) -> PersonIndexKey {- PersonIndexKey {- partition_id: partition,- team_id: team,- person_id: person(p),- }+fn behavioral_key(partition: u16, team: u64, leaf: u8, p: u128) -> BehavioralKey {+ BehavioralKey::new(partition, team, person(p), lsk(leaf))}fn stage2_key(partition: u16, team: u64, cohort: u64, p: u128) -> Stage2Key {@@ -96,41 +83,34 @@ fn point_writes_and_reads_per_cf() {let dir = TempDir::new().unwrap();let store = open_store(&dir);- let s1 = stage1_key(0, 100, 1, 7);+ let s1 = behavioral_key(0, 100, 1, 7);let s2 = stage2_key(0, 100, 55, 7);- let pix = person_index_key(0, 100, 7);store.write_batch(|b| {- b.put_stage1(&s1, b"stage1-value");+ b.put::<Behavioral>(&s1, b"behavioral-value");b.put_stage2(&s2, b"stage2-value");- b.merge_person_index(&pix, IndexOp::Append(lsk(1)));}).unwrap();assert_eq!(- store.get_stage1(&s1).unwrap().as_deref(),- Some(&b"stage1-value"[..])+ store.get_behavioral(&s1).unwrap().as_deref(),+ Some(&b"behavioral-value"[..]));assert_eq!(store.get_stage2(&s2).unwrap().as_deref(),Some(&b"stage2-value"[..]));- assert_eq!(store.get_person_index(&pix).unwrap(), vec![lsk(1)]);assert_eq!(- store.get(Cf::Stage1, &s1.encode()).unwrap().as_deref(),- Some(&b"stage1-value"[..])+ store.get(Cf::Behavioral, &s1.encode()).unwrap().as_deref(),+ Some(&b"behavioral-value"[..]));assert!(store- .get_stage1(&stage1_key(0, 100, 1, 999))+ .get_behavioral(&behavioral_key(0, 100, 1, 999)).unwrap().is_none());- assert!(store- .get_person_index(&person_index_key(0, 100, 999))- .unwrap()- .is_empty());}#[test]@@ -138,22 +118,22 @@ fn put_raw_writes_to_the_addressed_opaque_cf() {let dir = TempDir::new().unwrap();let store = open_store(&dir);- let s1 = stage1_key(4, 100, 7, 11);+ let s1 = behavioral_key(4, 100, 7, 11);let s2 = stage2_key(4, 100, 88, 11);store.write_batch(|b| {- b.put_raw(OpaqueCf::Stage1, &s1.encode(), b"raw-s1");+ b.put_raw(OpaqueCf::Behavioral, &s1.encode(), b"raw-s1");b.put_raw(OpaqueCf::Stage2, &s2.encode(), b"raw-s2");}).unwrap();assert_eq!(- store.get_stage1(&s1).unwrap().as_deref(),+ store.get_behavioral(&s1).unwrap().as_deref(),Some(&b"raw-s1"[..]));assert_eq!(- store.get(Cf::Stage1, &s1.encode()).unwrap().as_deref(),+ store.get(Cf::Behavioral, &s1.encode()).unwrap().as_deref(),Some(&b"raw-s1"[..]));assert_eq!(@@ -167,56 +147,91 @@ fn cross_cf_write_batch_is_atomic() {let dir = TempDir::new().unwrap();let store = open_store(&dir);- let s1 = stage1_key(3, 200, 9, 42);- let pix = person_index_key(3, 200, 42);+ let s1 = behavioral_key(3, 200, 9, 42);+ let s2 = stage2_key(3, 200, 88, 42);store.write_batch(|b| {- b.put_stage1(&s1, b"v");- b.merge_person_index(&pix, IndexOp::Append(s1.leaf_state_key));+ b.put::<Behavioral>(&s1, b"v");+ b.put_stage2(&s2, b"w");}).unwrap();- assert_eq!(store.get_stage1(&s1).unwrap().as_deref(), Some(&b"v"[..]));- assert_eq!(store.get_person_index(&pix).unwrap(), vec![lsk(9)]);+ assert_eq!(+ store.get_behavioral(&s1).unwrap().as_deref(),+ Some(&b"v"[..])+ );+ assert_eq!(store.get_stage2(&s2).unwrap().as_deref(), Some(&b"w"[..]));}-/// Removing every entry must read back as empty, not a "Merge operator failed" error (which is what-/// returning `None` from `full_merge` would produce).+/// A person's leaves are one contiguous prefix slice: a prefix scan returns exactly them in lsk order,+/// crossing neither into an adjacent person nor an adjacent partition.#[test]-fn secondary_index_merge_append_and_remove() {+fn behavioral_prefix_scan_returns_one_persons_leaves_in_lsk_order() {let dir = TempDir::new().unwrap();let store = open_store(&dir);- let pix = person_index_key(1, 300, 5);- for leaf in [10u8, 20, 30] {- store- .write_batch(|b| b.merge_person_index(&pix, IndexOp::Append(lsk(leaf))))- .unwrap();- }+ store+ .write_batch(|b| {+ for leaf in [30u8, 10, 20] {+ b.put::<Behavioral>(&behavioral_key(1, 300, leaf, 5), b"v");+ }+ // A neighbouring person in the same partition, and the same person in another partition.+ b.put::<Behavioral>(&behavioral_key(1, 300, 99, 6), b"other-person");+ b.put::<Behavioral>(&behavioral_key(2, 300, 10, 5), b"other-partition");+ })+ .unwrap();+ store.flush().unwrap();++ let rows = store+ .scan_behavioral_prefix(PersonPrefix::new(1, 300, person(5)))+ .unwrap();+ let leaves: Vec<[u8; 16]> = rows.iter().map(|(k, _)| k.lsk().0).collect();assert_eq!(- store.get_person_index(&pix).unwrap(),- vec![lsk(10), lsk(20), lsk(30)]+ leaves,+ vec![lsk(10).0, lsk(20).0, lsk(30).0],+ "exactly person 5's leaves, in lsk-byte order, never leaking to a neighbour",);+}++#[test]+fn behavioral_prefix_scan_spans_multiple_flushed_ssts() {+ // The single-batch test above flushes once, so the scan only ever reads one SST. Force one+ // person's leaves across two flushed SSTs so the prefix seek (prefix bloom + upper-bound iterator)+ // is exercised across an SST boundary: a scan that stops one key early, or lets the prefix bloom+ // skip a live SST, would pass the single-SST test but fail here.+ let dir = TempDir::new().unwrap();+ let store = open_store(&dir);- // Flush forces the operator to collapse into an SST before the read-back.+ // SST 1: person 5's leaf 10, plus a neighbouring person that must not leak into the scan.store- .write_batch(|b| b.merge_person_index(&pix, IndexOp::Remove(lsk(20))))+ .write_batch(|b| {+ b.put::<Behavioral>(&behavioral_key(1, 300, 10, 5), b"a");+ b.put::<Behavioral>(&behavioral_key(1, 300, 99, 6), b"other-person");+ }).unwrap();store.flush().unwrap();- assert_eq!(- store.get_person_index(&pix).unwrap(),- vec![lsk(10), lsk(30)]- );+ // SST 2: person 5's leaves 30 and 20 (written out of order), plus the same person in another+ // partition, which shares neither the partition nor the person prefix.store.write_batch(|b| {- b.merge_person_index(&pix, IndexOp::Remove(lsk(10)));- b.merge_person_index(&pix, IndexOp::Remove(lsk(30)));+ b.put::<Behavioral>(&behavioral_key(1, 300, 30, 5), b"c");+ b.put::<Behavioral>(&behavioral_key(1, 300, 20, 5), b"b");+ b.put::<Behavioral>(&behavioral_key(2, 300, 10, 5), b"other-partition");}).unwrap();store.flush().unwrap();- assert_eq!(store.get_person_index(&pix).unwrap(), vec![]);++ let rows = store+ .scan_behavioral_prefix(PersonPrefix::new(1, 300, person(5)))+ .unwrap();+ let leaves: Vec<[u8; 16]> = rows.iter().map(|(k, _)| k.lsk().0).collect();+ assert_eq!(+ leaves,+ vec![lsk(10).0, lsk(20).0, lsk(30).0],+ "person 5's leaves stay contiguous and in lsk order across two SSTs, no neighbour leak",+ );}#[test]@@ -227,9 +242,8 @@ fn delete_partition_isolates_other_partitions() {let write_partition = |p: u16| {store.write_batch(|b| {- b.put_stage1(&stage1_key(p, 100, 1, 7), b"s1");+ b.put::<Behavioral>(&behavioral_key(p, 100, 1, 7), b"s1");b.put_stage2(&stage2_key(p, 100, 55, 7), b"s2");- b.merge_person_index(&person_index_key(p, 100, 7), IndexOp::Append(lsk(1)));}).unwrap();};@@ -239,21 +253,17 @@ fn delete_partition_isolates_other_partitions() {store.delete_partition(0).unwrap();assert!(store- .get_stage1(&stage1_key(0, 100, 1, 7))+ .get_behavioral(&behavioral_key(0, 100, 1, 7)).unwrap().is_none());assert!(store.get_stage2(&stage2_key(0, 100, 55, 7)).unwrap().is_none());- assert!(store- .get_person_index(&person_index_key(0, 100, 7))- .unwrap()- .is_empty());assert_eq!(store- .get_stage1(&stage1_key(1, 100, 1, 7))+ .get_behavioral(&behavioral_key(1, 100, 1, 7)).unwrap().as_deref(),Some(&b"s1"[..])@@ -265,12 +275,6 @@ fn delete_partition_isolates_other_partitions() {.as_deref(),Some(&b"s2"[..]));- assert_eq!(- store- .get_person_index(&person_index_key(1, 100, 7))- .unwrap(),- vec![lsk(1)]- );}#[test]@@ -278,15 +282,13 @@ fn data_survives_reopen() {let dir = TempDir::new().unwrap();let config = config_in(&dir);- let s1 = stage1_key(2, 100, 4, 8);- let pix = person_index_key(2, 100, 8);+ let s1 = behavioral_key(2, 100, 4, 8);{let store = CohortStore::open(&config).unwrap();store.write_batch(|b| {- b.put_stage1(&s1, b"persisted");- b.merge_person_index(&pix, IndexOp::Append(lsk(4)));+ b.put::<Behavioral>(&s1, b"persisted");}).unwrap();store.flush().unwrap();@@ -294,10 +296,9 @@ fn data_survives_reopen() {let reopened = CohortStore::open(&config).unwrap();assert_eq!(- reopened.get_stage1(&s1).unwrap().as_deref(),+ reopened.get_behavioral(&s1).unwrap().as_deref(),Some(&b"persisted"[..]));- assert_eq!(reopened.get_person_index(&pix).unwrap(), vec![lsk(4)]);}#[test]@@ -305,30 +306,25 @@ fn one_write_batch_spans_state_and_merge_cfs_atomically() {let dir = TempDir::new().unwrap();let store = open_store(&dir);- let s1 = stage1_key(2, 100, 1, 7);+ let s1 = behavioral_key(2, 100, 1, 7);let s2 = stage2_key(2, 100, 55, 7);let drain = merge_drain_key(2, 100, 7);let pending = pending_transfer_key(2, 100, 7);let applied = merge_applied_key(2, 100, 8);let tombstone = tombstone_key(2, 100, 7);- // A drain-shaped batch: delete P_old's state, stage the outbox + idempotence markers + tombstone,- // all in one WriteBatch spanning the old and new CFs.+ // A drain-shaped batch: delete P_old's whole prefix slice, stage the outbox + idempotence markers+ // + tombstone, all in one WriteBatch spanning the old and new CFs.store.write_batch(|b| {- b.put_stage1(&s1, b"old-state");+ b.put::<Behavioral>(&s1, b"old-state");b.put_stage2(&s2, b"old-stage2");}).unwrap();store.write_batch(|b| {- b.delete_stage1(&s1);+ b.delete_behavioral_prefix(&PersonPrefix::new(2, 100, person(7)));b.delete_stage2(&s2);- b.delete_person_index(&PersonIndexKey {- partition_id: 2,- team_id: 100,- person_id: person(7),- });b.put_merge_drain_applied(&drain, b"drained_at");b.put_pending_transfer(&pending, b"transfer-payload");b.put_merge_applied(&applied, b"applied_at");@@ -337,7 +333,7 @@ fn one_write_batch_spans_state_and_merge_cfs_atomically() {.unwrap();assert!(- store.get_stage1(&s1).unwrap().is_none(),+ store.get_behavioral(&s1).unwrap().is_none(),"P_old state deleted");assert!(store.get_stage2(&s2).unwrap().is_none());@@ -368,37 +364,6 @@ fn one_write_batch_spans_state_and_merge_cfs_atomically() {);}-#[test]-fn delete_person_index_then_reappend_rebuilds_from_empty() {- let dir = TempDir::new().unwrap();- let store = open_store(&dir);- let pix = person_index_key(0, 100, 7);-- store- .write_batch(|b| {- b.merge_person_index(&pix, IndexOp::Append(lsk(1)));- b.merge_person_index(&pix, IndexOp::Append(lsk(2)));- })- .unwrap();- store.flush().unwrap();- assert_eq!(store.get_person_index(&pix).unwrap(), vec![lsk(1), lsk(2)]);-- store.write_batch(|b| b.delete_person_index(&pix)).unwrap();- store.flush().unwrap();- assert!(store.get_person_index(&pix).unwrap().is_empty());-- // A fresh append after the delete starts from empty — only the new leaf is present.- store- .write_batch(|b| b.merge_person_index(&pix, IndexOp::Append(lsk(9))))- .unwrap();- store.flush().unwrap();- assert_eq!(- store.get_person_index(&pix).unwrap(),- vec![lsk(9)],- "the whole-key delete is a base tombstone; the re-append never resurrects lsk 1/2",- );-}-#[test]fn delete_partition_reclaims_the_merge_cfs() {let dir = TempDir::new().unwrap();diff --git a/rust/cohort-stream-processor/tests/sweep_eviction_queue.rs b/rust/cohort-stream-processor/tests/sweep_eviction_queue.rsindex 05f039f50b98..700281eabf7f 100644--- a/rust/cohort-stream-processor/tests/sweep_eviction_queue.rs+++ b/rust/cohort-stream-processor/tests/sweep_eviction_queue.rs@@ -1,7 +1,7 @@-//! `EvictionQueue` driven against the real `Stage1Key` over a simulated day of events, through the+//! `EvictionQueue` driven against the real `BehavioralKey` over a simulated day of events, through the//! crate's public sweep API (no Kafka, no clock — synthetic `now` stepped by hand).//!-//! The deterministic oracle is the whole point: an independent `HashMap<Stage1Key, deadline>` of each+//! The deterministic oracle is the whole point: an independent `HashMap<BehavioralKey, deadline>` of each//! key's *live* (post-reschedule) deadline. Stepping a fake `now` in 30 s increments and draining//! `pop_due(now − margin)` each step, we assert every key evicts **exactly once**, at the **first**//! step where `live_deadline + safety_margin < now`, never earlier, with the queue length equal to@@ -9,7 +9,8 @@use std::collections::HashMap;-use cohort_stream_processor::stage1::key::{LeafStateKey, Stage1Key};+use cohort_stream_processor::stage1::key::LeafStateKey;+use cohort_stream_processor::store::BehavioralKey;use cohort_stream_processor::sweep::{due_before_ms, EvictionQueue};use uuid::Uuid;@@ -18,24 +19,24 @@ const DAY_MS: i64 = 86_400_000;const STEP_MS: i64 = 30_000; // the 30 s sweep cadenceconst MARGIN_MS: i64 = 300_000; // the 5 min safety margin-/// A distinct `Stage1Key` per index. `person_id` alone guarantees distinctness; `team`, `partition`,+/// A distinct `BehavioralKey` per index. `person_id` alone guarantees distinctness; `team`, `partition`,/// and `leaf_state_key` are varied too so the simulation looks like real `(team, leaf, person)` keys.-fn key(i: usize) -> Stage1Key {- Stage1Key {- partition_id: (i % 64) as u16,- team_id: (i % 5) as u64 + 1,- leaf_state_key: LeafStateKey((i as u128).to_le_bytes()),- person_id: Uuid::from_u128(0x00C0_FFEE_0000_0000_u128 + i as u128),- }+fn key(i: usize) -> BehavioralKey {+ BehavioralKey::new(+ (i % 64) as u16,+ (i % 5) as u64 + 1,+ Uuid::from_u128(0x00C0_FFEE_0000_0000_u128 + i as u128),+ LeafStateKey((i as u128).to_le_bytes()),+ )}#[test]fn one_day_of_events_evicts_each_key_once_at_its_deadline() {const N: usize = 300;- let mut queue: EvictionQueue<Stage1Key> = EvictionQueue::new();+ let mut queue: EvictionQueue<BehavioralKey> = EvictionQueue::new();// The independent oracle: each key's *final* deadline after all reschedules.- let mut oracle: HashMap<Stage1Key, i64> = HashMap::new();+ let mut oracle: HashMap<BehavioralKey, i64> = HashMap::new();// Pass 1 — initial deadlines spread evenly across the 24 h window, all at least `MARGIN_MS` past// `BASE_MS` so nothing is due at the first step.@@ -70,7 +71,7 @@ fn one_day_of_events_evicts_each_key_once_at_its_deadline() {);// Step `now` forward in 30 s increments, draining everything due at each step.- let mut evicted: HashMap<Stage1Key, i64> = HashMap::new();+ let mut evicted: HashMap<BehavioralKey, i64> = HashMap::new();let mut now = BASE_MS;let mut prev_due_before = i64::MIN; // the previous step's cutoff; -inf before the first steplet mut steps = 0;@@ -125,7 +126,7 @@ fn one_day_of_events_evicts_each_key_once_at_its_deadline() {#[test]fn cancelled_keys_never_evict() {- let mut queue: EvictionQueue<Stage1Key> = EvictionQueue::new();+ let mut queue: EvictionQueue<BehavioralKey> = EvictionQueue::new();let deadline = BASE_MS + MARGIN_MS;for i in 0..10 {queue.schedule(key(i), deadline);diff --git a/rust/cohort-stream-processor/tests/sweep_worker.rs b/rust/cohort-stream-processor/tests/sweep_worker.rsindex 65ebed06e8b0..7ca07331e820 100644--- a/rust/cohort-stream-processor/tests/sweep_worker.rs+++ b/rust/cohort-stream-processor/tests/sweep_worker.rs@@ -35,8 +35,8 @@ use cohort_stream_processor::stage1::{};use cohort_stream_processor::stage2::Stage2State;use cohort_stream_processor::store::{- CohortStore, LeafStateKey, OffloadConfig, OffloadMode, PersonIndexKey, Stage1Key, Stage2Key,- StoreConfig, StoreHandle,+ BehavioralKey, CohortStore, LeafStateKey, OffloadConfig, OffloadMode, PersonRecordKey,+ Stage2Key, StoreConfig, StoreHandle,};use cohort_stream_processor::workers::{process_event, MergeWorkerDeps, Stage1Worker};use common_kafka::kafka_producer::KafkaProduceError;@@ -217,14 +217,9 @@ fn stage2_bit(store: &CohortStore, cohort_id: u64, person: Uuid) -> Option<bool>}fn state_at(store: &CohortStore, lsk: LeafStateKey, person: Uuid) -> Option<Stage1State> {- let key = Stage1Key {- partition_id: PARTITION_ID,- team_id: TEAM as u64,- leaf_state_key: lsk,- person_id: person,- };+ let key = BehavioralKey::new(PARTITION_ID, TEAM as u64, person, lsk);store- .get_stage1(&key)+ .get_behavioral(&key).unwrap().map(|bytes| StatefulRecord::decode(&bytes).unwrap().state)}@@ -233,17 +228,6 @@ fn day_of(ts: &str) -> i32 {day_idx_in_tz(clickhouse_timestamp_to_millis(ts).unwrap(), UTC)}-/// The person's `cf_person_index` leaf-state set — the leaves the merge drain would enumerate.-fn person_index_of(store: &CohortStore, person: Uuid) -> Vec<LeafStateKey> {- store- .get_person_index(&PersonIndexKey {- partition_id: PARTITION_ID,- team_id: TEAM as u64,- person_id: person,- })- .unwrap()-}-/// Raise the dispatch ceiling, then deliver one event to the worker (matching the dispatcher's/// produce-before-commit ordering).async fn send_event(@@ -300,7 +284,7 @@ fn spawn_worker(}/// Like [`spawn_worker`] but with the durable-restart `EvictionQueue` rebuild on: the worker re-seeds-/// its queue from the partition's existing `cf_stage1` on spawn.+/// its queue from the partition's existing `cf_behavioral` on spawn.fn spawn_worker_durable(store: &CohortStore,catalog: Arc<CatalogHandle>,@@ -397,8 +381,8 @@ async fn sweep_evicts_a_single_leaf_member_emits_left_and_deletes() {async fn durable_restart_rebuilds_the_eviction_queue_so_a_dormant_left_still_fires() {// A member whose window expires during downtime — with no new event to reschedule her — must still// emit `Left`. The first worker enters alice and schedules her eviction in its in-memory queue,- // then "crashes" (drop loses the queue, but cf_stage1 persists); a durable-restart worker re-seeds- // its queue from cf_stage1, so a later sweep still evicts her.+ // then "crashes" (drop loses the queue, but cf_behavioral persists); a durable-restart worker re-seeds+ // its queue from cf_behavioral, so a later sweep still evicts her.let (_dir, store) = temp_store();let filters = build_team_filters(vec![behavioral_leaf(7)]);let lsk = behavioral_lsk(&filters);@@ -406,7 +390,7 @@ async fn durable_restart_rebuilds_the_eviction_queue_so_a_dormant_left_still_firlet alice = person(1);let ts = "2026-05-20 10:00:00.000000";- // First tenure: alice enters; her state + deadline persist to cf_stage1.+ // First tenure: alice enters; her state + deadline persist to cf_behavioral.let sink1 = CaptureSink::new();let tracker = Arc::new(OffsetTracker::new());let (tx1, worker1) = spawn_worker(@@ -568,27 +552,17 @@ async fn sweep_full_expiry_delete_retracts_the_person_index_entry() {let deadline = event_ms + 7 * DAY_MS;send_event(&tracker, &tx, event_at(alice, ts, 0), 0).await;- // Wait for the Entered to land, so the event's WriteBatch (cf_stage1 + the cf_person_index- // append) is durable before reading the index.+ // Wait for the Entered to land, so the event's cf_behavioral WriteBatch is durable.drain_until_changes(&sink, 1).await;- assert_eq!(- person_index_of(&store, alice),- vec![lsk],- "the entering event appends the leaf to cf_person_index",- );- // Sweep past the deadline: the single fully expires (Delete), retracting the index entry too.+ // Sweep past the deadline: the single fully expires (Delete), removing the behavioral row.send_sweep(&tx, deadline + DAY_MS).await;drop(tx);worker.join().await.unwrap();assert!(state_at(&store, lsk, alice).is_none(),- "the expired single's cf_stage1 row is gone",- );- assert!(- person_index_of(&store, alice).is_empty(),- "the full-expiry delete leaves no stale leaf in cf_person_index",+ "the expired single's cf_behavioral row is gone",);}@@ -1644,12 +1618,7 @@ fn relative_window_schedules_an_eviction_but_an_explicit_window_does_not() {assert_eq!(out.schedules,vec![(- Stage1Key {- partition_id: PARTITION_ID,- team_id: TEAM as u64,- leaf_state_key: lsk,- person_id: alice,- },+ BehavioralKey::new(PARTITION_ID, TEAM as u64, alice, lsk),start_of_day_ms_in_tz(day_of(ts) + 7 + 1, UTC),)],"a whole-day single schedules at the calendar midnight after day + window",@@ -1979,6 +1948,7 @@ async fn each_offload_mode_yields_the_same_emissions_and_state() {statuses: Vec<MembershipStatus>,stage2_bit: Option<bool>,stage1: Vec<(Vec<u8>, Vec<u8>)>,+ person_record: Option<Vec<u8>>,}let ts = "2026-05-20 10:00:00.000000";@@ -2013,20 +1983,26 @@ async fn each_offload_mode_yields_the_same_emissions_and_state() {vec![MembershipStatus::Entered, MembershipStatus::Left],"mode {mode:?}: the cohort enters on the event and leaves on the sweep",);+ // After the sweep evicts the behavioral leaf, `cf_behavioral` is empty — the never-evicted+ // person leaf lives in the sweep-invariant `cf_person_records` record, not here.let stage1: Vec<(Vec<u8>, Vec<u8>)> = store- .scan_stage1(PARTITION_ID, None, 10_000)+ .scan_behavioral(PARTITION_ID, None, 10_000).unwrap().into_iter().map(|(key, value)| (key.encode().to_vec(), value)).collect();+ let person_record = store+ .get_person_record(&PersonRecordKey::new(PARTITION_ID, TEAM as u64, alice))+ .unwrap();assert!(- !stage1.is_empty(),- "mode {mode:?}: the never-evicted person leaf still holds state",+ person_record.is_some(),+ "mode {mode:?}: the never-evicted person leaf still holds its durable record",);per_mode.push(ModeOutcome {statuses,stage2_bit: stage2_bit(&store, 1, alice),stage1,+ person_record,});}@@ -2037,7 +2013,7 @@ async fn each_offload_mode_yields_the_same_emissions_and_state() {{assert_eq!(arm, off,- "mode {mode:?} diverged from Off: emissions, stage-2 bit, and cf_stage1 bytes must be identical across operating points",+ "mode {mode:?} diverged from Off: emissions, stage-2 bit, cf_behavioral bytes, and the person record must be identical across operating points",);}}