: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
feat(cohorts): materialize single-leaf membership register in cf_stage2 (#72726)
Matheus Batistac9366298dfa0
diff --git a/rust/cohort-core/src/eligibility.rs b/rust/cohort-core/src/eligibility.rsindex 5f00a1cdee50..ff9143dbee69 100644--- a/rust/cohort-core/src/eligibility.rs+++ b/rust/cohort-core/src/eligibility.rs@@ -83,6 +83,19 @@ impl CohortEligibility {pub fn writes_cf_stage2(self) -> bool {matches!(self, Self::Stage2Composable | Self::Stage2ComposableRef)}++ /// Whether this class persists membership in `cf_stage2`. Broader than [`Self::writes_cf_stage2`],+ /// which covers the composable classes only: single-leaf cohorts also register a row here, holding+ /// their own leaf's membership bit rather than a composition result.+ ///+ /// Enumerated positively so a new eligibility variant must opt in here rather than silently start+ /// registering membership; the orphan-GC keep-predicate reads it.+ pub fn registers_membership(self) -> bool {+ matches!(+ self,+ Self::SingleLeaf(_) | Self::Stage2Composable | Self::Stage2ComposableRef+ )+ }}/// Whether a tree's root condition is negated: AND requires all children negated, OR requires any.@@ -904,6 +917,12 @@ mod tests {"a still-excluded ref cohort persists no cf_stage2 row",);assert!(!CohortEligibility::Excluded(ExcludedReason::CycleDetected).writes_cf_stage2());++ assert!(CohortEligibility::Stage2Composable.registers_membership());+ assert!(CohortEligibility::Stage2ComposableRef.registers_membership());+ assert!(CohortEligibility::SingleLeaf(LeafStateKey(HASH_A)).registers_membership());+ assert!(!CohortEligibility::Excluded(ExcludedReason::HasCohortRef).registers_membership(),);+ assert!(!CohortEligibility::Excluded(ExcludedReason::CycleDetected).registers_membership(),);}#[test]diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rsindex debbe1aedb72..f84362182087 100644--- a/rust/cohort-stream-processor/src/config.rs+++ b/rust/cohort-stream-processor/src/config.rs@@ -243,6 +243,13 @@ pub struct Config {)]pub cohort_seed_watermark_idle_probe_interval_ms: u64,+ /// Permit cross-partition membership-register transfer. Local register writers and transfer+ /// receivers are always active; only drain-side emission is gated. Enable only after every+ /// processor pod can apply the additive transfer payload. While off, a cross-partition merge ships+ /// leaves only and never holds, so it cannot wedge live merge consumption.+ #[envconfig(from = "COHORT_REGISTER_TRANSFER_ENABLED", default = "false")]+ pub cohort_register_transfer_enabled: bool,+/// Stable per-pod identity for `group.instance.id` + `client.id`, enabling static membership./// Read from `POD_NAME`, else `HOSTNAME`. Absent means no static membership.#[envconfig(from = "POD_NAME")]@@ -967,6 +974,7 @@ mod tests {kafka_seed_consumer_group: "cohort-stream-seeds".to_string(),cohort_seed_fence_margin_ms: 600_000,cohort_seed_watermark_idle_probe_interval_ms: 30_000,+ cohort_register_transfer_enabled: false,}}@@ -1118,6 +1126,22 @@ mod tests {assert!(!config.store_config().wipe_on_start);}+ #[test]+ fn register_transfer_gate_defaults_dark_and_overrides_from_env() {+ let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();+ assert!(+ !defaults.cohort_register_transfer_enabled,+ "register transfer must stay off until the whole fleet can apply the payload",+ );++ let enabled = Config::init_from_hashmap(&std::collections::HashMap::from([(+ "COHORT_REGISTER_TRANSFER_ENABLED".to_owned(),+ "true".to_owned(),+ )]))+ .unwrap();+ assert!(enabled.cohort_register_transfer_enabled);+ }+#[test]fn wipe_on_schema_mismatch_defaults_off_and_threads_into_store_config() {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 8beac31b9cc3..70b78295692b 100644--- a/rust/cohort-stream-processor/src/consumers/events.rs+++ b/rust/cohort-stream-processor/src/consumers/events.rs@@ -1785,6 +1785,8 @@ mod tests {seed_tile_sink: Arc::new(crate::producer::CaptureSeedTileSink::new()),seed_tracker: Arc::new(crate::partitions::offset_tracker::OffsetTracker::new()),live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),+ // The dispatch tests exercise cross-partition register transfer end to end.+ register_transfer_enabled: true,});let dispatcher = EventDispatcher::new(PartitionRouter::new(64),@@ -2950,6 +2952,7 @@ mod tests {source_partition: source.0,source_offset: source.1,leaves,+ membership_registers: vec![],forward_hops: 0,person_dedup: None,diff --git a/rust/cohort-stream-processor/src/consumers/merges.rs b/rust/cohort-stream-processor/src/consumers/merges.rsindex 0167216909a6..70e2cdace5ca 100644--- a/rust/cohort-stream-processor/src/consumers/merges.rs+++ b/rust/cohort-stream-processor/src/consumers/merges.rs@@ -396,6 +396,7 @@ mod tests {AppliedOffsets::default(),),)],+ membership_registers: vec![],forward_hops: 0,person_dedup: None,diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rsindex 154f8fc6ae9e..09342868e6b0 100644--- a/rust/cohort-stream-processor/src/main.rs+++ b/rust/cohort-stream-processor/src/main.rs@@ -232,6 +232,7 @@ async fn async_main(config: Config) -> Result<()> {seed_tracker: Arc::new(OffsetTracker::new()),// Unconditional (cheap): the event path observes regardless of the seed gate.live_watermarks: Arc::new(LiveWatermarks::new()),+ register_transfer_enabled: config.cohort_register_transfer_enabled,});// Cheap `Arc` clones taken before the originals move into the dispatcher: the checkpoint sweeperdiff --git a/rust/cohort-stream-processor/src/merge/apply_handler.rs b/rust/cohort-stream-processor/src/merge/apply_handler.rsindex 3c4ebf9c0219..ff6d628cfd9e 100644--- a/rust/cohort-stream-processor/src/merge/apply_handler.rs+++ b/rust/cohort-stream-processor/src/merge/apply_handler.rs@@ -11,14 +11,19 @@//! state to the live survivor instead — inline when the survivor co-resides on this partition,//! forwarded on `cohort_merge_state_transfer` when it lives on another.+use std::collections::BTreeMap;+use metrics::counter;use uuid::Uuid;use crate::filters::reverse_index::TeamFilters;-use crate::filters::TeamId;+use crate::filters::{CohortId, TeamId};use crate::merge::rules::merge_records;use crate::merge::tombstone_redirect::{resolve, Resolution};-use crate::merge::transfer::{ApplyStamp, MergeStateTransfer};+use crate::merge::transfer::{+ ApplyStamp, MergeStateTransfer, TransferMembershipRegister, TransferMembershipRegisterKind,+ TransferredRegisterProvenance,+};use crate::observability::metrics::{MERGE_APPLIES_SKIPPED_REPLAY_TOTAL, MERGE_FORWARD_HOP_CAPPED_TOTAL, MERGE_LEAVES_DROPPED_TOTAL,MERGE_TRANSFER_FORWARDS_TOTAL,@@ -27,9 +32,12 @@ use crate::stage1::key::LeafStateKey;use crate::stage1::person_record::{PersonDedup, PersonRecord};use crate::stage1::state::StatefulRecord;use crate::stage1::transition::LeafTransition;+use crate::stage2::{+ leaf_membership, single_leaf_register_writes, MembershipRegisterSource, Stage2State,+};use crate::store::{Behavioral, BehavioralKey, CohortStore, MergeAppliedKey, PersonPrefix, PersonRecords,- StoreError,+ Stage2Key, Stage2TransferredRegisterKey, StoreError,};use crate::sweep::EvictionQueue;use crate::workers::event_path::schedule_deadline;@@ -228,9 +236,42 @@ fn apply_into(let stamp = ApplyStamp {applied_at_ms: transfer.merged_at_ms,};+ let fallback_register_writes = missing_transferred_register_writes(+ partition_id,+ store,+ filters,+ transfer.team_id,+ target,+ &transfer.membership_registers,+ transfer.merged_at_ms,+ )?;store.write_batch(|batch| {- for (key, bytes) in &apply.puts {- batch.put::<Behavioral>(key, bytes);+ for write in &fallback_register_writes {+ if let Some(state) = &write.state {+ batch.put_stage2(&write.key, &state.encode_transferred_fallback());+ }+ if let Some(provenance) = &write.provenance {+ batch.put_stage2_transferred_register(+ &Stage2TransferredRegisterKey::new(write.key),+ &provenance.encode(),+ );+ }+ }+ for leaf in &apply.puts {+ batch.put::<Behavioral>(&leaf.key, &leaf.bytes);+ for write in single_leaf_register_writes(+ filters,+ MembershipRegisterSource {+ partition_id,+ team_id: TeamId(transfer.team_id),+ person_id: target,+ leaf_state_key: leaf.key.lsk(),+ },+ leaf.in_cohort,+ transfer.merged_at_ms,+ ) {+ batch.put_stage2(&write.key, &write.state.encode());+ }}if let Some(bytes) = &record_put {batch.put::<PersonRecords>(&target_prefix.record_key(), bytes);@@ -292,15 +333,123 @@ pub(crate) fn merge_person_records(}}+/// One merge-carried register settlement. The logical state and person-first provenance are+/// fill-only. A decoded existing state may be rewritten only to mark its ownership as transferred,+/// preserving its bit and timestamp so a later receiver evaluation can settle the provenance.+pub(crate) struct TransferredRegisterWrite {+ pub key: Stage2Key,+ pub state: Option<Stage2State>,+ pub provenance: Option<TransferredRegisterProvenance>,+}++/// Fill only missing survivor rows from transferred membership registers. A recognized receiver+/// shape chooses the conservative local bit (so a real single-leaf-to-composable edit starts false);+/// otherwise the self-describing wire kind does. Source kind + bit remain in person-first provenance+/// for another catalogless hop. Applied leaf evaluation remains authoritative and is staged later.+#[allow(clippy::too_many_arguments, clippy::disallowed_methods)]+pub(crate) fn missing_transferred_register_writes(+ partition_id: u16,+ store: &CohortStore,+ filters: &TeamFilters,+ team_id: i32,+ person_id: Uuid,+ registers: &[TransferMembershipRegister],+ last_evaluated_at_ms: i64,+) -> Result<Vec<TransferredRegisterWrite>, StoreError> {+ let registers_by_cohort: BTreeMap<CohortId, TransferMembershipRegister> = registers+ .iter()+ .map(|register| (CohortId(register.cohort_id), *register))+ .collect();+ let keys: Vec<Stage2Key> = registers_by_cohort+ .keys()+ .map(|cohort_id| Stage2Key {+ partition_id,+ team_id: team_id as u64,+ cohort_id: cohort_id.0 as u64,+ person_id,+ })+ .collect();+ let existing = store.multi_get_stage2(&keys)?;+ let inventory_keys: Vec<Stage2TransferredRegisterKey> = keys+ .iter()+ .copied()+ .map(Stage2TransferredRegisterKey::new)+ .collect();+ let existing_provenance = store.multi_get_stage2_transferred_registers(&inventory_keys)?;++ Ok(keys+ .into_iter()+ .zip(registers_by_cohort.into_values())+ .zip(existing)+ .zip(existing_provenance)+ .map(|(((key, register), existing), existing_provenance)| {+ let receiver_kind =+ TransferMembershipRegisterKind::from_filters(filters, CohortId(register.cohort_id));+ let primary_missing = existing.is_none();+ let existing_state = existing+ .as_deref()+ .and_then(|bytes| Stage2State::decode(bytes).ok());+ let existing_bit = existing_state.as_ref().map(|state| state.in_cohort);+ let materialized_kind = receiver_kind.unwrap_or(register.kind);+ let install_existing_provenance =+ !primary_missing && existing_provenance.is_none() && receiver_kind.is_none();+ let state = if primary_missing {+ Some(Stage2State {+ in_cohort: materialized_kind.materialized_bit(register.in_cohort),+ last_evaluated_at_ms,+ })+ } else if install_existing_provenance {+ // A corrupt primary has no fill-only bit to preserve. Repair it with the same+ // conservative source fallback used for a missing catalogless primary.+ Some(existing_state.unwrap_or(Stage2State {+ in_cohort: register.kind.materialized_bit(register.in_cohort),+ last_evaluated_at_ms,+ }))+ } else {+ None+ };+ let provenance = (primary_missing || install_existing_provenance).then(|| {+ let source = TransferMembershipRegister {+ // The survivor's existing primary is fill-only and therefore owns the bit. The+ // incoming register supplies only the otherwise-unavailable kind clue.+ in_cohort: existing_bit.unwrap_or(register.in_cohort),+ ..register+ };+ let encoded_state = state.as_ref().map(Stage2State::encode_transferred_fallback);+ let expected_primary = encoded_state.as_deref().expect(+ "installing provenance always materializes explicit fallback ownership",+ );+ TransferredRegisterProvenance::new(source, expected_primary)+ });+ TransferredRegisterWrite {+ key,+ state,+ // Fill-only applies to provenance too: an existing survivor inventory wins. If+ // neither inventory nor catalog can enumerate an existing row, the incoming+ // source is the only safe person-first provenance to install.+ provenance,+ }+ })+ .collect())+}+/// 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<(BehavioralKey, Vec<u8>)>,+ pub puts: Vec<AppliedLeafWrite>,pub transitions: Vec<LeafTransition>,pub schedules: Vec<(BehavioralKey, i64)>,}+/// One survivor leaf write coupled to the membership derived from those exact post-merge bytes.+#[derive(Debug)]+pub(crate) struct AppliedLeafWrite {+ pub key: BehavioralKey,+ pub bytes: Vec<u8>,+ pub in_cohort: bool,+}+/// Merge each of P_old's `leaves` into P_new's state on `partition_new`. Pure reads only — the/// caller composes the final write batch. A leaf whose LSK left the catalog is skipped; a corrupt/// P_new record is treated as absent.@@ -349,7 +498,11 @@ pub(crate) fn apply_leaves(if let Some(deadline) = schedule_deadline(&record.state) {out.schedules.push((p_new_key, deadline));}- out.puts.push((p_new_key, record.encode()));+ out.puts.push(AppliedLeafWrite {+ key: p_new_key,+ bytes: record.encode(),+ in_cohort: leaf_membership(Some(&record.state), meta),+ });}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 59d833d5557c..64649afc517f 100644--- a/rust/cohort-stream-processor/src/merge/drain_handler.rs+++ b/rust/cohort-stream-processor/src/merge/drain_handler.rs@@ -10,31 +10,40 @@//! the transfer for the caller to produce.//!//! 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).+//! range delete over its person prefix. P_old's `cf_stage2` keys are built from the catalog; when+//! register transfer is enabled ([`MembershipRegisterTransferMode`]) the existing membership rows+//! ride the cross-partition transfer so a no-op merge or catalog refresh cannot strand the survivor's+//! membership row. While it is disabled the drain ships leaves only.++use std::collections::BTreeMap;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, merge_person_records, QueueEffects};+use crate::merge::apply_handler::{+ apply_leaves, merge_person_records, missing_transferred_register_writes, QueueEffects,+};use crate::merge::tombstone_redirect::{resolve, Resolution};use crate::merge::transfer::{DrainStamp, MergeStateTransfer, PendingTransfer, PersonMergeEvent, Tombstone, TransferLeaf,+ TransferMembershipRegister, TransferMembershipRegisterKind, TransferredRegisterProvenance,};use crate::observability::metrics::{MERGE_DRAINS_SKIPPED_REPLAY_TOTAL, MERGE_DRAIN_LEAVES_SCANNED, MERGE_HANDLED_TOTAL,- MERGE_LEAVES_DROPPED_TOTAL,+ MERGE_LEAVES_DROPPED_TOTAL, STAGE2_STATE_DECODE_ERROR,};use crate::partitions::partitioner::partition_of;use crate::stage1::key::LeafStateKey;use crate::stage1::person_record::{PersonDedup, PersonRecord};use crate::stage1::state::StatefulRecord;use crate::stage1::transition::LeafTransition;+use crate::stage2::{single_leaf_register_writes, MembershipRegisterSource, Stage2State};use crate::store::{Behavioral, BehavioralKey, CohortStore, MergeDrainKey, PendingTransferKey, PersonPrefix,- PersonRecords, Stage2Key, StoreError, TombstoneKey,+ PersonRecords, Stage2Key, Stage2TransferredRegisterKey, Stage2TransferredRegisterPersonPrefix,+ StoreError, TombstoneKey,};#[derive(Debug, Clone, PartialEq)]@@ -46,9 +55,8 @@ pub enum DrainOutcome {effects: QueueEffects,},/// Cross-partition slow path: state drained into `transfer`, staged in `cf_pending_transfers`.- /// 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).+ /// A transfer with no payload 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,@@ -64,6 +72,37 @@ pub enum DrainSkip {SamePerson,}+/// Whether a cross-partition drain emits the additive membership-register payload.+///+/// Local register writes and receiver application are unconditional; only the sender is gated. While+/// the gate is off the drain carries no register bits: it transfers leaves only and never holds, so a+/// receiver that cannot apply the payload never sees one and merge consumption never stalls. P_new+/// re-derives its single-leaf registers locally from the transferred leaves; composable membership+/// falls back to lazy recompose on the survivor.+///+/// Once the gate is on the sender emits, and a receiver that does not understand `membership_registers`+/// (no `deny_unknown_fields`) silently drops it, deleting the survivor's only register row. So enable+/// the sender only once every pod can apply the transfer, and disable it before rolling the image back.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum MembershipRegisterTransferMode {+ Disabled,+ Enabled,+}++impl MembershipRegisterTransferMode {+ pub(crate) const fn from_enabled(enabled: bool) -> Self {+ if enabled {+ Self::Enabled+ } else {+ Self::Disabled+ }+ }++ const fn is_enabled(self) -> bool {+ matches!(self, Self::Enabled)+ }+}+/// Drain the merge `event` on P_old's worker (`partition_id` owns P_old).////// `partition_count` is the live co-partitioned topic count (production 64; test lanes lower it):@@ -79,6 +118,28 @@ pub fn handle_merge_event(event: &PersonMergeEvent,msg_coords: (i32, i64),partition_count: u32,+) -> Result<DrainOutcome, StoreError> {+ handle_merge_event_with_transfer_mode(+ partition_id,+ store,+ filters,+ event,+ msg_coords,+ partition_count,+ MembershipRegisterTransferMode::Enabled,+ )+}++/// Production entry with rollout-safe cross-partition register transfer.+#[allow(clippy::disallowed_methods)]+pub(crate) fn handle_merge_event_with_transfer_mode(+ partition_id: u16,+ store: &CohortStore,+ filters: &TeamFilters,+ event: &PersonMergeEvent,+ msg_coords: (i32, i64),+ partition_count: u32,+ register_transfer_mode: MembershipRegisterTransferMode,) -> Result<DrainOutcome, StoreError> {let team_id = event.team_id;let team_u64 = team_id as u64;@@ -146,14 +207,30 @@ pub fn handle_merge_event(team_id: team_u64,person: old_person,};- let old_stage2_keys: Vec<Stage2Key> = composable_cohort_ids(filters)- .map(|cohort_id| Stage2Key {+ let transferred_inventory = store.scan_stage2_transferred_registers(+ Stage2TransferredRegisterPersonPrefix::new(partition_id, team_u64, old_person),+ )?;+ let old_transferred_register_keys: Vec<Stage2TransferredRegisterKey> = transferred_inventory+ .iter()+ .map(|(key, _value)| *key)+ .collect();+ let registering_cohorts = collect_registering_cohorts(filters, &transferred_inventory);+ let old_stage2_keys: Vec<Stage2Key> = registering_cohorts+ .iter()+ .map(|(cohort_id, _source)| Stage2Key {partition_id,team_id: team_u64,cohort_id: cohort_id.0 as u64,person_id: old_person,}).collect();+ // Gate off ⇒ carry no register bits (see [`MembershipRegisterTransferMode`]): the drain still+ // reclaims P_old's own register rows below but ships leaves only, so the read is skipped.+ let old_membership_registers = if register_transfer_mode.is_enabled() {+ read_membership_registers(store, ®istering_cohorts, &old_stage2_keys)?+ } else {+ Vec::new()+ };// Same-slice assist: if P_new is itself tombstoned in *this* slice, drain straight to the live// survivor, skipping a hop the apply-side resolution would otherwise take. Only the routing/apply@@ -188,6 +265,8 @@ pub fn handle_merge_event(&old_keys,&old_prefix,&old_stage2_keys,+ &old_transferred_register_keys,+ &old_membership_registers,&present_leaves,person_dedup.as_ref(),);@@ -206,6 +285,8 @@ pub fn handle_merge_event(&old_keys,&old_prefix,&old_stage2_keys,+ &old_transferred_register_keys,+ old_membership_registers,&present_leaves,person_dedup,)@@ -226,6 +307,8 @@ fn fast_path(old_keys: &[BehavioralKey],old_prefix: &PersonPrefix,old_stage2_keys: &[Stage2Key],+ old_transferred_register_keys: &[Stage2TransferredRegisterKey],+ old_membership_registers: &[TransferMembershipRegister],present_leaves: &[(LeafStateKey, StatefulRecord)],person_dedup: Option<&PersonDedup>,) -> Result<DrainOutcome, StoreError> {@@ -249,17 +332,52 @@ fn fast_path(Some(dedup) => merge_person_records(store, &new_prefix, event.old_person_uuid, dedup)?,None => None,};-+ let fallback_register_writes = missing_transferred_register_writes(+ partition_id,+ store,+ filters,+ event.team_id,+ effective_new_person,+ old_membership_registers,+ event.merged_at_ms,+ )?;store.write_batch(|batch| {batch.delete_behavioral_prefix(old_prefix);batch.delete::<PersonRecords>(&old_prefix.record_key());for key in old_stage2_keys {batch.delete_stage2(key);}+ for key in old_transferred_register_keys {+ batch.delete_stage2_transferred_register(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::<Behavioral>(key, bytes);+ for write in &fallback_register_writes {+ if let Some(state) = &write.state {+ batch.put_stage2(&write.key, &state.encode_transferred_fallback());+ }+ if let Some(provenance) = &write.provenance {+ batch.put_stage2_transferred_register(+ &Stage2TransferredRegisterKey::new(write.key),+ &provenance.encode(),+ );+ }+ }+ for leaf in &apply.puts {+ batch.put::<Behavioral>(&leaf.key, &leaf.bytes);+ for write in single_leaf_register_writes(+ filters,+ MembershipRegisterSource {+ partition_id,+ team_id: TeamId(event.team_id),+ person_id: effective_new_person,+ leaf_state_key: leaf.key.lsk(),+ },+ leaf.in_cohort,+ event.merged_at_ms,+ ) {+ batch.put_stage2(&write.key, &write.state.encode());+ }}if let Some(bytes) = &record_put {batch.put::<PersonRecords>(&new_prefix.record_key(), bytes);@@ -290,6 +408,8 @@ fn slow_path(old_keys: &[BehavioralKey],old_prefix: &PersonPrefix,old_stage2_keys: &[Stage2Key],+ old_transferred_register_keys: &[Stage2TransferredRegisterKey],+ old_membership_registers: Vec<TransferMembershipRegister>,present_leaves: &[(LeafStateKey, StatefulRecord)],person_dedup: Option<PersonDedup>,) -> Result<DrainOutcome, StoreError> {@@ -307,14 +427,13 @@ fn slow_path(.iter().map(|(lsk, record)| TransferLeaf::new(*lsk, record.clone())).collect(),+ membership_registers: old_membership_registers,forward_hops: 0,person_dedup,};- // 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+ // Stage iff the transfer carries state. 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 {+ let pending = transfer.has_payload().then(|| PendingTransfer {transfer: transfer.clone(),merge_msg_partition: msg_coords.0,merge_msg_offset: msg_coords.1,@@ -335,6 +454,9 @@ fn slow_path(for key in old_stage2_keys {batch.delete_stage2(key);}+ for key in old_transferred_register_keys {+ batch.delete_stage2_transferred_register(key);+ }batch.put_tombstone(tombstone_key, &tombstone.encode());})?;@@ -347,23 +469,127 @@ fn slow_path(})}-/// The team's cohort ids that write `cf_stage2` rows (both composable classes). See-/// [`writes_cf_stage2`](crate::stage2::CohortEligibility::writes_cf_stage2).-fn composable_cohort_ids(filters: &TeamFilters) -> impl Iterator<Item = CohortId> + '_ {- filters- .eligibility+/// The team's cohorts that persist membership in `cf_stage2`, coupled to the source semantics a+/// receiver needs when its own catalog is missing or stale.+fn membership_registering_cohorts(+ filters: &TeamFilters,+) -> impl Iterator<Item = (CohortId, TransferMembershipRegisterKind)> + '_ {+ filters.eligibility.keys().filter_map(|&cohort_id| {+ TransferMembershipRegisterKind::from_filters(filters, cohort_id)+ .map(|kind| (cohort_id, kind))+ })+}++#[derive(Debug, Clone)]+struct DrainRegisterSource {+ catalog_kind: Option<TransferMembershipRegisterKind>,+ provenance: Option<TransferredRegisterProvenance>,+}++/// Assemble the cohorts whose `cf_stage2` register P_old may carry across the merge: the team's+/// catalog-declared registering cohorts, unioned with any transferred-register inventory keyed on+/// P_old (which survives a stale or missing catalog). Decoded provenance refines each source; an+/// undecodable inventory row still proves a register exists, defaulting to the conservative+/// composable kind when neither the value nor the catalog can name it.+fn collect_registering_cohorts(+ filters: &TeamFilters,+ transferred_inventory: &[(Stage2TransferredRegisterKey, Vec<u8>)],+) -> Vec<(CohortId, DrainRegisterSource)> {+ let mut registering_cohorts: BTreeMap<CohortId, DrainRegisterSource> =+ membership_registering_cohorts(filters)+ .map(|(cohort_id, kind)| {+ (+ cohort_id,+ DrainRegisterSource {+ catalog_kind: Some(kind),+ provenance: None,+ },+ )+ })+ .collect();+ for (key, value) in transferred_inventory {+ let Ok(cohort_id) = i32::try_from(key.stage2_key().cohort_id) else {+ counter!(MERGE_LEAVES_DROPPED_TOTAL, "reason" => "register_inventory_cohort")+ .increment(1);+ continue;+ };+ let source =+ registering_cohorts+ .entry(CohortId(cohort_id))+ .or_insert(DrainRegisterSource {+ catalog_kind: None,+ provenance: None,+ });+ match TransferredRegisterProvenance::decode(value) {+ Some(provenance) => source.provenance = Some(provenance),+ None => {+ counter!(MERGE_LEAVES_DROPPED_TOTAL, "reason" => "register_inventory_decode")+ .increment(1);+ source+ .catalog_kind+ .get_or_insert(TransferMembershipRegisterKind::Composable);+ }+ }+ }+ registering_cohorts.into_iter().collect()+}++#[allow(clippy::disallowed_methods)]+fn read_membership_registers(+ store: &CohortStore,+ cohorts: &[(CohortId, DrainRegisterSource)],+ keys: &[Stage2Key],+) -> Result<Vec<TransferMembershipRegister>, StoreError> {+ debug_assert_eq!(cohorts.len(), keys.len());+ Ok(cohorts.iter()- .filter_map(|(&cohort_id, eligibility)| eligibility.writes_cf_stage2().then_some(cohort_id))+ .zip(store.multi_get_stage2(keys)?)+ .filter_map(|((cohort_id, source), bytes)| {+ let bytes = bytes?;+ let active_provenance = source+ .provenance+ .as_ref()+ .filter(|provenance| provenance.matches_primary(&bytes));+ let kind = active_provenance+ .map(|provenance| provenance.kind)+ .or(source.catalog_kind)+ .or_else(|| source.provenance.as_ref().map(|provenance| provenance.kind))+ .unwrap_or(TransferMembershipRegisterKind::Composable);+ let materialized_bit = match Stage2State::decode(&bytes) {+ Ok(state) => Some(state.in_cohort),+ Err(_) => {+ counter!(STAGE2_STATE_DECODE_ERROR).increment(1);+ None+ }+ };+ Some(TransferMembershipRegister {+ cohort_id: cohort_id.0,+ // An exact fingerprint means the receiver has not evaluated this register since+ // transfer, so retain the source bit. Otherwise the current primary row wins.+ in_cohort: active_provenance+ .map(|provenance| provenance.in_cohort)+ .or(materialized_bit)+ .unwrap_or(false),+ kind,+ })+ })+ .collect())}#[cfg(test)]+#[allow(clippy::disallowed_methods)]mod tests {use super::*;use chrono_tz::UTC;use serde_json::{json, Value};+ use tempfile::TempDir;use crate::filters::TeamFiltersBuilder;+ use crate::merge::apply_handler::{handle_transfer, ApplyOutcome};+ use crate::partitions::partitioner::COHORT_PARTITION_COUNT;+ use crate::stage2::state::Stage2Ownership;use crate::stage2::CohortEligibility;+ use crate::store::StoreConfig;fn behavioral(time_value: i64) -> Value {json!({@@ -391,9 +617,9 @@ mod tests {}#[test]- fn composable_cohort_ids_enumerates_both_composable_classes_for_row_deletion() {+ fn membership_registering_cohorts_enumerates_single_leaf_and_composable_classes() {let mut builder = TeamFiltersBuilder::default();- // 2: single-leaf referent — does NOT write cf_stage2.+ // 2: single-leaf referent — writes its direct membership register.builder.add_cohort(CohortId(2), TeamId(7), &cohort(vec![behavioral(7)])).unwrap();@@ -419,17 +645,19 @@ mod tests {filters.eligibility[&CohortId(1)],CohortEligibility::Stage2ComposableRef,);- let mut ids: Vec<i32> = composable_cohort_ids(&filters).map(|c| c.0).collect();+ let mut ids: Vec<i32> = membership_registering_cohorts(&filters)+ .map(|(cohort_id, _kind)| cohort_id.0)+ .collect();ids.sort_unstable();assert_eq!(ids,- vec![1, 3],- "a Stage2ComposableRef writer is enumerated alongside Stage2Composable; the SingleLeaf referent is not",+ vec![1, 2, 3],+ "all membership-registering classes are reclaimed for the merged-away person",);}#[test]- fn composable_cohort_ids_gate_off_drops_the_still_excluded_ref_cohort() {+ fn membership_registering_cohorts_excludes_a_ref_cohort_when_the_gate_is_off() {let mut builder = TeamFiltersBuilder::default();builder.add_cohort(CohortId(2), TeamId(7), &cohort(vec![behavioral(7)]))@@ -443,10 +671,524 @@ mod tests {.unwrap();let filters = builder.freeze_with(UTC, false);- let ids: Vec<i32> = composable_cohort_ids(&filters).map(|c| c.0).collect();+ let ids: Vec<i32> = membership_registering_cohorts(&filters)+ .map(|(cohort_id, _kind)| cohort_id.0)+ .collect();+ assert_eq!(+ ids,+ vec![2],+ "gate off excludes the ref cohort but retains its single-leaf referent's register",+ );+ }++ #[test]+ fn disabled_register_transfer_drains_leaves_only_and_carries_no_register_bits() {+ let mut builder = TeamFiltersBuilder::default();+ builder+ .add_cohort(CohortId(1), TeamId(7), &cohort(vec![behavioral(7)]))+ .unwrap();+ let filters = builder.freeze(UTC);+ let old_person = Uuid::from_u128(1);+ let old_partition = partition_of(TeamId(7), &old_person, COHORT_PARTITION_COUNT) as u16;+ let new_person = (2u128..)+ .map(Uuid::from_u128)+ .find(|person| {+ partition_of(TeamId(7), person, COHORT_PARTITION_COUNT) as u16 != old_partition+ })+ .unwrap();+ let register_key = Stage2Key {+ partition_id: old_partition,+ team_id: 7,+ cohort_id: 1,+ person_id: old_person,+ };+ let dir = TempDir::new().unwrap();+ let store = CohortStore::open(&StoreConfig {+ path: dir.path().join("db"),+ ..StoreConfig::default()+ })+ .unwrap();+ store+ .write_batch(|batch| {+ batch.put_stage2(+ ®ister_key,+ &Stage2State {+ in_cohort: true,+ last_evaluated_at_ms: 1,+ }+ .encode(),+ )+ })+ .unwrap();++ let outcome = handle_merge_event_with_transfer_mode(+ old_partition,+ &store,+ &filters,+ &PersonMergeEvent {+ team_id: 7,+ old_person_uuid: old_person,+ new_person_uuid: new_person,+ merged_at_ms: 2,+ schema_version: crate::merge::transfer::MERGE_EVENT_SCHEMA_VERSION,+ },+ (3, 4),+ COHORT_PARTITION_COUNT,+ MembershipRegisterTransferMode::Disabled,+ )+ .unwrap();++ let DrainOutcome::Drained { transfer, .. } = outcome else {+ panic!("a disabled cross-partition merge drains like the pre-register pipeline");+ };+ assert!(+ transfer.membership_registers.is_empty(),+ "gate off ships no register bits, so an old receiver never sees a payload it can't apply",+ );+ assert!(+ store.get_stage2(®ister_key).unwrap().is_none(),+ "P_old's register row is reclaimed by the drain, like the pre-register pipeline",+ );+ }++ #[test]+ fn catalogless_existing_row_seeds_provenance_from_the_survivor_bit() {+ let person = Uuid::from_u128(1);+ let partition = partition_of(TeamId(7), &person, COHORT_PARTITION_COUNT) as u16;+ let key = Stage2Key {+ partition_id: partition,+ team_id: 7,+ cohort_id: 1,+ person_id: person,+ };+ let inventory = Stage2TransferredRegisterKey::new(key);+ let dir = TempDir::new().unwrap();+ let store = CohortStore::open(&StoreConfig {+ path: dir.path().join("db"),+ ..StoreConfig::default()+ })+ .unwrap();+ store+ .write_batch(|batch| {+ batch.put_stage2(+ &key,+ &Stage2State {+ in_cohort: true,+ last_evaluated_at_ms: 1,+ }+ .encode(),+ );+ })+ .unwrap();++ handle_transfer(+ partition,+ &store,+ &TeamFilters::default(),+ &MergeStateTransfer {+ team_id: 7,+ old_person_uuid: Uuid::from_u128(99),+ new_person_uuid: person,+ merged_at_ms: 2,+ source_partition: 3,+ source_offset: 4,+ leaves: Vec::new(),+ membership_registers: vec![TransferMembershipRegister {+ cohort_id: 1,+ in_cohort: false,+ kind: TransferMembershipRegisterKind::SingleLeafBehavioral,+ }],+ forward_hops: 0,+ person_dedup: None,+ },+ (partition.into(), 5),+ COHORT_PARTITION_COUNT,+ )+ .unwrap();++ assert!(+ Stage2State::decode(&store.get_stage2(&key).unwrap().unwrap())+ .unwrap()+ .in_cohort+ );+ assert_eq!(+ TransferredRegisterProvenance::decode(+ &store+ .get_stage2_transferred_register(&inventory)+ .unwrap()+ .unwrap(),+ ),+ Some(TransferredRegisterProvenance::new(+ TransferMembershipRegister {+ cohort_id: 1,+ in_cohort: true,+ kind: TransferMembershipRegisterKind::SingleLeafBehavioral,+ },+ &Stage2State {+ in_cohort: true,+ last_evaluated_at_ms: 1,+ }+ .encode_transferred_fallback(),+ )),+ );+ }++ #[test]+ fn catalogless_corrupt_existing_row_is_repaired_as_an_owned_fallback() {+ let person = Uuid::from_u128(1);+ let partition = partition_of(TeamId(7), &person, COHORT_PARTITION_COUNT) as u16;+ let key = Stage2Key {+ partition_id: partition,+ team_id: 7,+ cohort_id: 1,+ person_id: person,+ };+ let inventory = Stage2TransferredRegisterKey::new(key);+ let dir = TempDir::new().unwrap();+ let store = CohortStore::open(&StoreConfig {+ path: dir.path().join("db"),+ ..StoreConfig::default()+ })+ .unwrap();+ store+ .write_batch(|batch| batch.put_stage2(&key, b"corrupt"))+ .unwrap();++ let source_register = TransferMembershipRegister {+ cohort_id: 1,+ in_cohort: true,+ kind: TransferMembershipRegisterKind::Composable,+ };+ handle_transfer(+ partition,+ &store,+ &TeamFilters::default(),+ &MergeStateTransfer {+ team_id: 7,+ old_person_uuid: Uuid::from_u128(99),+ new_person_uuid: person,+ merged_at_ms: 2,+ source_partition: 3,+ source_offset: 4,+ leaves: Vec::new(),+ membership_registers: vec![source_register],+ forward_hops: 0,+ person_dedup: None,+ },+ (partition.into(), 5),+ COHORT_PARTITION_COUNT,+ )+ .unwrap();++ let primary = store.get_stage2(&key).unwrap().unwrap();+ assert_eq!(+ Stage2State::decode_with_ownership(&primary).unwrap(),+ (+ Stage2State {+ in_cohort: false,+ last_evaluated_at_ms: 2,+ },+ Stage2Ownership::TransferredFallback,+ ),+ );+ let provenance = TransferredRegisterProvenance::decode(+ &store+ .get_stage2_transferred_register(&inventory)+ .unwrap()+ .unwrap(),+ )+ .unwrap();+ assert_eq!(provenance.kind, source_register.kind);+ assert_eq!(provenance.in_cohort, source_register.in_cohort);+ assert!(provenance.matches_primary(&primary));+ }++ #[test]+ fn local_noop_stage2_update_supersedes_transfer_provenance_before_gc() {+ let old_person = Uuid::from_u128(1);+ let old_partition = partition_of(TeamId(7), &old_person, COHORT_PARTITION_COUNT) as u16;+ let new_person = (2u128..)+ .map(Uuid::from_u128)+ .find(|person| {+ partition_of(TeamId(7), person, COHORT_PARTITION_COUNT) as u16 != old_partition+ })+ .unwrap();+ let register_key = Stage2Key {+ partition_id: old_partition,+ team_id: 7,+ cohort_id: 1,+ person_id: old_person,+ };+ let dir = TempDir::new().unwrap();+ let store = CohortStore::open(&StoreConfig {+ path: dir.path().join("db"),+ ..StoreConfig::default()+ })+ .unwrap();+ let mut current_filters = TeamFilters::default();+ current_filters+ .eligibility+ .insert(CohortId(1), CohortEligibility::Stage2Composable);++ handle_transfer(+ old_partition,+ &store,+ ¤t_filters,+ &MergeStateTransfer {+ team_id: 7,+ old_person_uuid: Uuid::from_u128(99),+ new_person_uuid: old_person,+ merged_at_ms: 1,+ source_partition: 3,+ source_offset: 4,+ leaves: Vec::new(),+ membership_registers: vec![TransferMembershipRegister {+ cohort_id: 1,+ in_cohort: true,+ kind: TransferMembershipRegisterKind::SingleLeafBehavioral,+ }],+ forward_hops: 0,+ person_dedup: None,+ },+ (old_partition.into(), 5),+ COHORT_PARTITION_COUNT,+ )+ .unwrap();++ store+ .write_batch(|batch| {+ batch.put_stage2(+ ®ister_key,+ &Stage2State {+ in_cohort: false,+ last_evaluated_at_ms: 1,+ }+ .encode(),+ );+ })+ .unwrap();++ let outcome = handle_merge_event_with_transfer_mode(+ old_partition,+ &store,+ ¤t_filters,+ &PersonMergeEvent {+ team_id: 7,+ old_person_uuid: old_person,+ new_person_uuid: new_person,+ merged_at_ms: 3,+ schema_version: crate::merge::transfer::MERGE_EVENT_SCHEMA_VERSION,+ },+ (old_partition.into(), 6),+ COHORT_PARTITION_COUNT,+ MembershipRegisterTransferMode::Enabled,+ )+ .unwrap();++ let DrainOutcome::Drained { transfer, .. } = outcome else {+ panic!("the ownership-settled register should drain");+ };+ assert_eq!(+ transfer.membership_registers,+ vec![TransferMembershipRegister {+ cohort_id: 1,+ in_cohort: false,+ kind: TransferMembershipRegisterKind::Composable,+ }],+ "removing only fallback ownership makes the current primary and catalog authoritative",+ );+ }++ #[test]+ fn catalogless_register_survives_a_stale_catalog_and_transfers_on_the_next_hop() {+ let middle_person = Uuid::from_u128(1);+ let middle_partition =+ partition_of(TeamId(7), &middle_person, COHORT_PARTITION_COUNT) as u16;+ let final_person = (2u128..)+ .map(Uuid::from_u128)+ .find(|person| {+ partition_of(TeamId(7), person, COHORT_PARTITION_COUNT) as u16 != middle_partition+ })+ .unwrap();+ let register_key = Stage2Key {+ partition_id: middle_partition,+ team_id: 7,+ cohort_id: 1,+ person_id: middle_person,+ };+ let dir = TempDir::new().unwrap();+ let store = CohortStore::open(&StoreConfig {+ path: dir.path().join("db"),+ ..StoreConfig::default()+ })+ .unwrap();++ let mut stale_receiver_filters = TeamFilters::default();+ stale_receiver_filters.eligibility.insert(+ CohortId(1),+ crate::stage2::CohortEligibility::Excluded(crate::stage2::ExcludedReason::NotMultiLeaf),+ );+ let applied = handle_transfer(+ middle_partition,+ &store,+ &stale_receiver_filters,+ &MergeStateTransfer {+ team_id: 7,+ old_person_uuid: Uuid::from_u128(99),+ new_person_uuid: middle_person,+ merged_at_ms: 1,+ source_partition: 3,+ source_offset: 4,+ leaves: Vec::new(),+ membership_registers: vec![TransferMembershipRegister {+ cohort_id: 1,+ in_cohort: true,+ kind: TransferMembershipRegisterKind::SingleLeafBehavioral,+ }],+ forward_hops: 0,+ person_dedup: None,+ },+ (middle_partition.into(), 5),+ COHORT_PARTITION_COUNT,+ )+ .unwrap();+ assert!(matches!(applied, ApplyOutcome::Applied { .. }));+ assert!(+ Stage2State::decode(&store.get_stage2(®ister_key).unwrap().unwrap())+ .unwrap()+ .in_cohort,+ "the wire register survives a stale receiver catalog that excludes the cohort",+ );+ let register_inventory = Stage2TransferredRegisterKey::new(register_key);+ assert_eq!(+ TransferredRegisterProvenance::decode(+ &store+ .get_stage2_transferred_register(®ister_inventory)+ .unwrap()+ .unwrap(),+ ),+ Some(TransferredRegisterProvenance::new(+ TransferMembershipRegister {+ cohort_id: 1,+ in_cohort: true,+ kind: TransferMembershipRegisterKind::SingleLeafBehavioral,+ },+ &Stage2State {+ in_cohort: true,+ last_evaluated_at_ms: 1,+ }+ .encode_transferred_fallback(),+ )),+ );++ // A second catalogless source collides with the survivor. Both the primary bit and the+ // existing survivor provenance are fill-only; the incoming composable sentinel cannot+ // rewrite either one.+ handle_transfer(+ middle_partition,+ &store,+ &TeamFilters::default(),+ &MergeStateTransfer {+ team_id: 7,+ old_person_uuid: Uuid::from_u128(98),+ new_person_uuid: middle_person,+ merged_at_ms: 1,+ source_partition: 30,+ source_offset: 40,+ leaves: Vec::new(),+ membership_registers: vec![TransferMembershipRegister {+ cohort_id: 1,+ in_cohort: true,+ kind: TransferMembershipRegisterKind::Composable,+ }],+ forward_hops: 0,+ person_dedup: None,+ },+ (middle_partition.into(), 41),+ COHORT_PARTITION_COUNT,+ )+ .unwrap();+ assert!(+ Stage2State::decode(&store.get_stage2(®ister_key).unwrap().unwrap())+ .unwrap()+ .in_cohort,+ );+ assert_eq!(+ TransferredRegisterProvenance::decode(+ &store+ .get_stage2_transferred_register(®ister_inventory)+ .unwrap()+ .unwrap(),+ ),+ Some(TransferredRegisterProvenance::new(+ TransferMembershipRegister {+ cohort_id: 1,+ in_cohort: true,+ kind: TransferMembershipRegisterKind::SingleLeafBehavioral,+ },+ &Stage2State {+ in_cohort: true,+ last_evaluated_at_ms: 1,+ }+ .encode_transferred_fallback(),+ )),+ );++ let empty_filters = TeamFilters::default();+ let second_event = PersonMergeEvent {+ team_id: 7,+ old_person_uuid: middle_person,+ new_person_uuid: final_person,+ merged_at_ms: 2,+ schema_version: crate::merge::transfer::MERGE_EVENT_SCHEMA_VERSION,+ };+ let drained = handle_merge_event_with_transfer_mode(+ middle_partition,+ &store,+ &empty_filters,+ &second_event,+ (middle_partition.into(), 6),+ COHORT_PARTITION_COUNT,+ MembershipRegisterTransferMode::Enabled,+ )+ .unwrap();+ let DrainOutcome::Drained { transfer, .. } = drained else {+ panic!("the enabled second hop should drain the catalogless register");+ };+ assert_eq!(+ transfer.membership_registers,+ vec![TransferMembershipRegister {+ cohort_id: 1,+ in_cohort: true,+ kind: TransferMembershipRegisterKind::SingleLeafBehavioral,+ }],+ );+ assert!(store.get_stage2(®ister_key).unwrap().is_none());++ let final_partition = partition_of(TeamId(7), &final_person, COHORT_PARTITION_COUNT) as u16;+ let applied = handle_transfer(+ final_partition,+ &store,+ &empty_filters,+ &transfer,+ (final_partition.into(), 7),+ COHORT_PARTITION_COUNT,+ )+ .unwrap();+ assert!(matches!(applied, ApplyOutcome::Applied { .. }));+ let final_key = Stage2Key {+ partition_id: final_partition,+ person_id: final_person,+ ..register_key+ };assert!(- ids.is_empty(),- "gate off keeps the ref cohort Excluded(HasCohortRef), which writes no cf_stage2 row",+ Stage2State::decode(&store.get_stage2(&final_key).unwrap().unwrap())+ .unwrap()+ .in_cohort,);+ assert!(store+ .get_stage2_transferred_register(&Stage2TransferredRegisterKey::new(final_key))+ .unwrap()+ .is_some());}}diff --git a/rust/cohort-stream-processor/src/merge/transfer.rs b/rust/cohort-stream-processor/src/merge/transfer.rsindex b9f828a0a0ee..f71fb8aec75d 100644--- a/rust/cohort-stream-processor/src/merge/transfer.rs+++ b/rust/cohort-stream-processor/src/merge/transfer.rs@@ -9,9 +9,11 @@use serde::{Deserialize, Serialize};use uuid::Uuid;+use crate::filters::reverse_index::TeamFilters;+use crate::filters::CohortId;use crate::stage1::key::LeafStateKey;use crate::stage1::person_record::PersonDedup;-use crate::stage1::state::StatefulRecord;+use crate::stage1::state::{StateVariant, StatefulRecord};pub const MERGE_EVENT_SCHEMA_VERSION: u32 = 1;@@ -33,6 +35,124 @@ pub struct TransferLeaf {pub record: StatefulRecord,}+/// One persisted membership register carried alongside P_old's leaf state.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+pub struct TransferMembershipRegister {+ pub cohort_id: i32,+ pub in_cohort: bool,+ /// Enough source semantics for a receiver to materialize the scan register without consulting+ /// a potentially older or not-yet-loaded filter catalog.+ #[serde(default)]+ pub kind: TransferMembershipRegisterKind,+}++/// Source semantics for a transferred membership register.+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum TransferMembershipRegisterKind {+ SingleLeafBehavioral,+ SingleLeafPersonProperty,+ #[default]+ Composable,+}++/// Persisted source provenance for a merge-carried register. The local Stage 2 row may use a+/// conservative bit from the receiver's current catalog shape; this value keeps the original wire+/// bit and kind available for another catalogless hop.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct TransferredRegisterProvenance {+ pub kind: TransferMembershipRegisterKind,+ pub in_cohort: bool,+ expected_primary: Vec<u8>,+}++impl TransferredRegisterProvenance {+ pub fn new(register: TransferMembershipRegister, expected_primary: &[u8]) -> Self {+ Self {+ kind: register.kind,+ in_cohort: register.in_cohort,+ expected_primary: expected_primary.to_vec(),+ }+ }++ pub fn encode(&self) -> Vec<u8> {+ let mut encoded = Vec::with_capacity(2 + self.expected_primary.len());+ encoded.push(self.kind.encode()[0]);+ encoded.push(self.in_cohort as u8);+ encoded.extend_from_slice(&self.expected_primary);+ encoded+ }++ pub fn decode(bytes: &[u8]) -> Option<Self> {+ let [kind, in_cohort, expected_primary @ ..] = bytes else {+ return None;+ };+ Some(Self {+ kind: TransferMembershipRegisterKind::decode(&[*kind])?,+ in_cohort: match *in_cohort {+ 0 => false,+ 1 => true,+ _ => return None,+ },+ expected_primary: expected_primary.to_vec(),+ })+ }++ pub fn matches_primary(&self, primary: &[u8]) -> bool {+ self.expected_primary == primary+ }+}++impl TransferMembershipRegisterKind {+ /// The safe initial value for a missing survivor register. Behavioral single-leaf state carries+ /// its exact bit; person-property and composable state must be recomputed for the survivor.+ pub const fn materialized_bit(self, transferred_bit: bool) -> bool {+ match self {+ Self::SingleLeafBehavioral => transferred_bit,+ Self::SingleLeafPersonProperty | Self::Composable => false,+ }+ }++ /// Compact persisted form used by the catalog-independent Stage 2 transfer inventory.+ pub const fn encode(self) -> [u8; 1] {+ [match self {+ Self::SingleLeafBehavioral => 1,+ Self::SingleLeafPersonProperty => 2,+ Self::Composable => 3,+ }]+ }++ pub fn decode(bytes: &[u8]) -> Option<Self> {+ match bytes {+ [1] => Some(Self::SingleLeafBehavioral),+ [2] => Some(Self::SingleLeafPersonProperty),+ [3] => Some(Self::Composable),+ _ => None,+ }+ }++ /// Derive the register semantics from one catalog snapshot. `None` means the cohort does not+ /// currently register membership.+ pub(crate) fn from_filters(filters: &TeamFilters, cohort_id: CohortId) -> Option<Self> {+ match filters.eligibility.get(&cohort_id)? {+ crate::stage2::CohortEligibility::SingleLeaf(lsk) => {+ Some(match filters.by_lsk.get(lsk).map(|meta| meta.variant) {+ Some(StateVariant::PersonProperty) => Self::SingleLeafPersonProperty,+ Some(+ StateVariant::BehavioralSingle+ | StateVariant::BehavioralDailyBuckets+ | StateVariant::BehavioralCompressedHistory,+ ) => Self::SingleLeafBehavioral,+ None => Self::Composable,+ })+ }+ crate::stage2::CohortEligibility::Stage2Composable+ | crate::stage2::CohortEligibility::Stage2ComposableRef => Some(Self::Composable),+ crate::stage2::CohortEligibility::Excluded(_) => None,+ }+ }+}+impl TransferLeaf {pub fn new(leaf_state_key: LeafStateKey, record: StatefulRecord) -> Self {Self {@@ -59,6 +179,12 @@ pub struct MergeStateTransfer {pub source_partition: i32,pub source_offset: i64,pub leaves: Vec<TransferLeaf>,+ /// P_old's materialized behavioral membership rows. Carrying these preserves the reconcile scan+ /// domain when no leaf transition recreates a composable row, and across catalog refreshes+ /// between drain and apply. An apply uses them only to fill a missing survivor register;+ /// post-merge evaluation remains authoritative.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub membership_registers: Vec<TransferMembershipRegister>,/// Cross-partition forward hops taken so far when `new_person_uuid` was itself tombstoned at/// apply time (chained merge `A → B → C` where `B → C` drained before `A → B` applied). Bounded/// by [`crate::merge::apply_handler::MAX_TRANSFER_FORWARD_HOPS`]. `#[serde(default)]`: a message@@ -74,6 +200,15 @@ pub struct MergeStateTransfer {pub person_dedup: Option<PersonDedup>,}+impl MergeStateTransfer {+ /// Whether applying this transfer can change survivor state.+ pub fn has_payload(&self) -> bool {+ !self.leaves.is_empty()+ || !self.membership_registers.is_empty()+ || self.person_dedup.is_some()+ }+}+/// Staged transfer in `cf_pending_transfers`. Survives a crash between the drain batch and the/// produce; the redrive re-produces it.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]@@ -203,6 +338,61 @@ mod tests {assert_eq!(bad_char.decode_leaf_state_key(), None, "non-hex char");}+ #[test]+ fn membership_register_kind_inventory_codec_is_closed() {+ for kind in [+ TransferMembershipRegisterKind::SingleLeafBehavioral,+ TransferMembershipRegisterKind::SingleLeafPersonProperty,+ TransferMembershipRegisterKind::Composable,+ ] {+ assert_eq!(+ TransferMembershipRegisterKind::decode(&kind.encode()),+ Some(kind)+ );+ }+ assert_eq!(TransferMembershipRegisterKind::decode(&[]), None);+ assert_eq!(TransferMembershipRegisterKind::decode(&[0]), None);+ assert_eq!(TransferMembershipRegisterKind::decode(&[1, 2]), None);+ }++ #[test]+ fn transferred_register_provenance_codec_preserves_kind_and_bit() {+ for provenance in [+ TransferredRegisterProvenance::new(+ TransferMembershipRegister {+ cohort_id: 1,+ in_cohort: true,+ kind: TransferMembershipRegisterKind::SingleLeafBehavioral,+ },+ b"primary-a",+ ),+ TransferredRegisterProvenance::new(+ TransferMembershipRegister {+ cohort_id: 1,+ in_cohort: false,+ kind: TransferMembershipRegisterKind::SingleLeafPersonProperty,+ },+ b"primary-b",+ ),+ TransferredRegisterProvenance::new(+ TransferMembershipRegister {+ cohort_id: 1,+ in_cohort: true,+ kind: TransferMembershipRegisterKind::Composable,+ },+ b"primary-c",+ ),+ ] {+ assert_eq!(+ TransferredRegisterProvenance::decode(&provenance.encode()),+ Some(provenance.clone()),+ );+ assert!(provenance.matches_primary(&provenance.expected_primary));+ }+ assert_eq!(TransferredRegisterProvenance::decode(&[1]), None);+ assert_eq!(TransferredRegisterProvenance::decode(&[1, 2]), None);+ }+#[test]fn person_merge_event_shape_is_pinned() {let event = PersonMergeEvent {@@ -244,17 +434,52 @@ mod tests {source_partition: 17,source_offset: 12_345,leaves: vec![TransferLeaf::new(LeafStateKey([0xAB; 16]), single_record())],+ membership_registers: vec![TransferMembershipRegister {+ cohort_id: 9,+ in_cohort: false,+ kind: TransferMembershipRegisterKind::Composable,+ }],forward_hops: 0,person_dedup: None,};let decoded = MergeStateTransfer::decode(&transfer.encode()).unwrap();assert_eq!(decoded, transfer);+ let wire: serde_json::Value = serde_json::from_slice(&transfer.encode()).unwrap();+ assert_eq!(+ wire["membership_registers"][0]["kind"],+ serde_json::json!("composable"),+ "the self-describing register kind is pinned on the wire",+ );assert_eq!(decoded.leaves[0].record,single_record(),"the leaf's StatefulRecord transfers whole, so redirect_dedup chains for free",);+ assert_eq!(decoded.membership_registers, transfer.membership_registers);+ assert!(decoded.has_payload());+ }++ #[test]+ fn register_only_transfer_is_not_empty() {+ let transfer = MergeStateTransfer {+ team_id: 7,+ old_person_uuid: uuid(0xAAAA),+ new_person_uuid: uuid(0xBBBB),+ merged_at_ms: 1,+ source_partition: 3,+ source_offset: 4,+ leaves: vec![],+ membership_registers: vec![TransferMembershipRegister {+ cohort_id: 9,+ in_cohort: false,+ kind: TransferMembershipRegisterKind::SingleLeafBehavioral,+ }],+ forward_hops: 0,+ person_dedup: None,+ };++ assert!(transfer.has_payload());}#[test]@@ -276,6 +501,7 @@ mod tests {source_partition: 17,source_offset: 12_345,leaves: vec![],+ membership_registers: vec![],forward_hops: 0,person_dedup: Some(PersonDedup {applied_offsets: AppliedOffsets::from_sorted_entries(vec![(1, 100), (2, 200)]),@@ -306,6 +532,51 @@ mod tests {decoded.forward_hops, 0,"missing forward_hops defaults to 0");+ assert!(+ decoded.membership_registers.is_empty(),+ "older transfers default to no carried register rows",+ );+ }++ #[test]+ fn transfer_tolerates_unknown_fields_so_a_new_sender_cannot_poison_an_old_receiver() {+ // A sender may add fields to the transfer wire; a receiver that does not know them must+ // ignore them, not reject the whole message. This pins the absence of+ // `#[serde(deny_unknown_fields)]` on MergeStateTransfer — adding it would silently drop every+ // cross-partition merge whose transfer carries an unknown field.+ let json = serde_json::json!({+ "team_id": 7,+ "old_person_uuid": uuid(0xAAAA).to_string(),+ "new_person_uuid": uuid(0xBBBB).to_string(),+ "merged_at_ms": 1_716_800_000_000_i64,+ "source_partition": 17,+ "source_offset": 12_345,+ "leaves": [],+ "membership_registers": [{ "cohort_id": 9, "in_cohort": false, "kind": "composable" }],+ "some_future_field": { "added": "by a newer sender" },+ });+ let decoded = MergeStateTransfer::decode(&serde_json::to_vec(&json).unwrap())+ .expect("an unknown extra field must not fail the decode");+ assert_eq!(+ decoded.membership_registers,+ vec![TransferMembershipRegister {+ cohort_id: 9,+ in_cohort: false,+ kind: TransferMembershipRegisterKind::Composable,+ }],+ "the known additive field still round-trips alongside the ignored unknown one",+ );+ }++ #[test]+ fn register_without_kind_defaults_to_safe_composable_semantics() {+ let register: TransferMembershipRegister = serde_json::from_value(serde_json::json!({+ "cohort_id": 9,+ "in_cohort": true,+ }))+ .unwrap();+ assert_eq!(register.kind, TransferMembershipRegisterKind::Composable);+ assert!(!register.kind.materialized_bit(register.in_cohort));}#[test]@@ -318,6 +589,7 @@ mod tests {source_partition: 3,source_offset: 4,leaves: vec![],+ membership_registers: vec![],forward_hops: 0,person_dedup: None,diff --git a/rust/cohort-stream-processor/src/partitions/shuffle_message.rs b/rust/cohort-stream-processor/src/partitions/shuffle_message.rsindex 66799031c645..983393017acc 100644--- a/rust/cohort-stream-processor/src/partitions/shuffle_message.rs+++ b/rust/cohort-stream-processor/src/partitions/shuffle_message.rs@@ -164,6 +164,7 @@ mod tests {source_partition: 3,source_offset: 9,leaves: vec![],+ membership_registers: vec![],forward_hops: 0,person_dedup: None,diff --git a/rust/cohort-stream-processor/src/producer/merge.rs b/rust/cohort-stream-processor/src/producer/merge.rsindex 283b78cc3406..d47c958d8dfd 100644--- a/rust/cohort-stream-processor/src/producer/merge.rs+++ b/rust/cohort-stream-processor/src/producer/merge.rs@@ -260,6 +260,7 @@ mod tests {AppliedOffsets::default(),),)],+ membership_registers: vec![],forward_hops: 0,person_dedup: None,diff --git a/rust/cohort-stream-processor/src/stage2/mod.rs b/rust/cohort-stream-processor/src/stage2/mod.rsindex 28400d96efce..5f3c1202ecff 100644--- a/rust/cohort-stream-processor/src/stage2/mod.rs+++ b/rust/cohort-stream-processor/src/stage2/mod.rs@@ -1,9 +1,14 @@//! Stage 2: per-person Boolean composition of a cohort's leaves into membership flips.pub mod evaluator;+mod register;pub mod state;pub use cohort_core::eligibility;pub use eligibility::{classify, CohortEligibility, CohortParseFlags, ExcludedReason};pub use evaluator::{evaluate_tree, leaf_membership};+pub(crate) use register::{+ single_leaf_register_writes, single_leaf_transition_register_writes, stage_register_writes,+ MembershipRegisterSource,+};pub use state::Stage2State;diff --git a/rust/cohort-stream-processor/src/stage2/register.rs b/rust/cohort-stream-processor/src/stage2/register.rsnew file mode 100644index 000000000000..05cdfbbad945--- /dev/null+++ b/rust/cohort-stream-processor/src/stage2/register.rs@@ -0,0 +1,182 @@+//! Typed writes for the persisted single-leaf membership register.++use uuid::Uuid;++use crate::filters::reverse_index::TeamFilters;+use crate::filters::TeamId;+use crate::stage1::key::LeafStateKey;+use crate::stage1::transition::{LeafTransition, TransitionKind};+use crate::store::{Stage2Key, StagedBatch};++use super::Stage2State;++/// One complete `cf_stage2` register write for a single-leaf cohort.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct MembershipRegisterWrite {+ pub key: Stage2Key,+ pub state: Stage2State,+}++/// Person/leaf coordinates shared by every register write in one fan-out.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) struct MembershipRegisterSource {+ pub partition_id: u16,+ pub team_id: TeamId,+ pub person_id: Uuid,+ pub leaf_state_key: LeafStateKey,+}++/// Fan out one leaf's current membership to every single-leaf cohort backed by that leaf. The+/// returned iterator borrows `filters`, so it stays allocation-free on the hot per-transition path.+pub(crate) fn single_leaf_register_writes(+ filters: &TeamFilters,+ source: MembershipRegisterSource,+ in_cohort: bool,+ last_evaluated_at_ms: i64,+) -> impl Iterator<Item = MembershipRegisterWrite> + '_ {+ filters+ .by_lsk_to_single_leaf_cohorts+ .get(&source.leaf_state_key)+ .into_iter()+ .flatten()+ .map(move |cohort_id| MembershipRegisterWrite {+ key: Stage2Key {+ partition_id: source.partition_id,+ team_id: source.team_id.0 as u64,+ cohort_id: cohort_id.0 as u64,+ person_id: source.person_id,+ },+ state: Stage2State {+ in_cohort,+ last_evaluated_at_ms,+ },+ })+}++/// Fan out a membership transition as a complete register overwrite, including explicit `false`.+pub(crate) fn single_leaf_transition_register_writes<'a>(+ filters: &'a TeamFilters,+ partition_id: u16,+ transition: &LeafTransition,+ last_evaluated_at_ms: i64,+) -> impl Iterator<Item = MembershipRegisterWrite> + 'a {+ single_leaf_register_writes(+ filters,+ MembershipRegisterSource {+ partition_id,+ team_id: transition.team_id,+ person_id: transition.person_id,+ leaf_state_key: transition.leaf_state_key,+ },+ matches!(transition.kind, TransitionKind::Entered),+ last_evaluated_at_ms,+ )+}++/// Stage a register fan-out into `staged`, encoding each write into its `cf_stage2` row.+pub(crate) fn stage_register_writes(+ staged: &mut StagedBatch,+ writes: impl IntoIterator<Item = MembershipRegisterWrite>,+) {+ for write in writes {+ staged.put_stage2(&write.key, &write.state.encode());+ }+}++#[cfg(test)]+mod tests {+ use chrono_tz::UTC;+ use serde_json::json;++ use super::*;+ use crate::filters::{CohortId, TeamFiltersBuilder};++ #[test]+ fn fans_out_a_leaf_to_each_single_leaf_cohort_with_an_explicit_bit() {+ let mut builder = TeamFiltersBuilder::default();+ let cohort = json!({+ "properties": {+ "type": "AND",+ "values": [{+ "type": "behavioral",+ "key": "purchase",+ "value": "performed_event",+ "time_value": 7,+ "time_interval": "day",+ "conditionHash": "0123456789abcdef",+ "bytecode": ["_H", 1, 32, "purchase", 32, "event", 1, 3, 11]+ }]+ }+ });+ builder.add_cohort(CohortId(1), TeamId(7), &cohort).unwrap();+ builder.add_cohort(CohortId(2), TeamId(7), &cohort).unwrap();+ let filters = builder.freeze(UTC);+ let leaf_state_key = *filters.by_lsk_to_single_leaf_cohorts.keys().next().unwrap();+ let person_id = Uuid::from_u128(42);++ let mut writes: Vec<_> = single_leaf_register_writes(+ &filters,+ MembershipRegisterSource {+ partition_id: 3,+ team_id: TeamId(7),+ person_id,+ leaf_state_key,+ },+ false,+ 1_700_000_000_123,+ )+ .collect();+ writes.sort_unstable_by_key(|write| write.key.cohort_id);++ assert_eq!(writes.len(), 2);+ assert_eq!(writes[0].key.cohort_id, 1);+ assert_eq!(writes[1].key.cohort_id, 2);+ assert!(writes.iter().all(|write| {+ write.key.partition_id == 3+ && write.key.team_id == 7+ && write.key.person_id == person_id+ && write.state+ == Stage2State {+ in_cohort: false,+ last_evaluated_at_ms: 1_700_000_000_123,+ }+ }));+ }++ #[test]+ fn a_leaf_with_no_single_leaf_cohort_keyed_on_it_registers_nothing() {+ // A single-leaf cohort exists, but the queried leaf is not the one it is keyed on.+ let mut builder = TeamFiltersBuilder::default();+ let cohort = json!({+ "properties": {+ "type": "AND",+ "values": [{+ "type": "behavioral",+ "key": "purchase",+ "value": "performed_event",+ "time_value": 7,+ "time_interval": "day",+ "conditionHash": "0123456789abcdef",+ "bytecode": ["_H", 1, 32, "purchase", 32, "event", 1, 3, 11]+ }]+ }+ });+ builder.add_cohort(CohortId(1), TeamId(7), &cohort).unwrap();+ let filters = builder.freeze(UTC);++ let writes: Vec<_> = single_leaf_register_writes(+ &filters,+ MembershipRegisterSource {+ partition_id: 3,+ team_id: TeamId(7),+ person_id: Uuid::from_u128(42),+ leaf_state_key: LeafStateKey([0xEE; 16]),+ },+ true,+ 1_700_000_000_123,+ )+ .collect();++ assert!(writes.is_empty());+ }+}diff --git a/rust/cohort-stream-processor/src/stage2/state.rs b/rust/cohort-stream-processor/src/stage2/state.rsindex bc55e4b3c1bb..ab3e76fdb281 100644--- a/rust/cohort-stream-processor/src/stage2/state.rs+++ b/rust/cohort-stream-processor/src/stage2/state.rs@@ -2,17 +2,43 @@use serde::{Deserialize, Serialize};-/// The composed membership of one `(cohort, person)`: whether the person is in the cohort, and when-/// that was last evaluated.+/// The registered membership of one `(cohort, person)`: whether the person is in the cohort, and+/// when that was last evaluated. Single-leaf cohorts write this directly from their leaf state;+/// composable cohorts write it after Boolean composition.///-/// `last_evaluated_at_ms` is write-only for now (nothing reads it). It is the source event's-/// timestamp, not a wall clock, so the value is replay-stable.+/// `last_evaluated_at_ms` is write-only for now (nothing reads it). Writers use the timestamp of the+/// operation that evaluated membership: event time for live/merge work, the sweep cutoff for+/// evictions, and application time for seed work.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Stage2State {pub in_cohort: bool,pub last_evaluated_at_ms: i64,}+/// Who last established the persisted bit. Transfer fallbacks are deliberately explicit so the+/// first receiver-side evaluation can claim the row even when it computes identical membership.+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub(crate) enum Stage2Ownership {+ #[default]+ Local,+ TransferredFallback,+}++impl Stage2Ownership {+ const fn is_local(&self) -> bool {+ matches!(self, Self::Local)+ }+}++#[derive(Debug, Serialize, Deserialize)]+struct PersistedStage2State {+ in_cohort: bool,+ last_evaluated_at_ms: i64,+ #[serde(default, skip_serializing_if = "Stage2Ownership::is_local")]+ ownership: Stage2Ownership,+}+/// A failure decoding a stored [`Stage2State`]; surfaced (never panicked) so a single corrupt row is/// skipped rather than taking down the worker.#[derive(Debug, thiserror::Error)]@@ -26,9 +52,33 @@ impl Stage2State {serde_json::to_vec(self).expect("Stage2State is plain data and always serializes")}+ /// Encode a conservative merge-carried fallback. The additive ownership field is omitted from+ /// ordinary rows, preserving their existing on-disk bytes.+ pub(crate) fn encode_transferred_fallback(&self) -> Vec<u8> {+ serde_json::to_vec(&PersistedStage2State {+ in_cohort: self.in_cohort,+ last_evaluated_at_ms: self.last_evaluated_at_ms,+ ownership: Stage2Ownership::TransferredFallback,+ })+ .expect("PersistedStage2State is plain data and always serializes")+ }+/// Garbage bytes and missing fields both yield an [`Err`], never a panic.pub fn decode(bytes: &[u8]) -> Result<Self, Stage2CodecError> {- Ok(serde_json::from_slice(bytes)?)+ Ok(Self::decode_with_ownership(bytes)?.0)+ }++ pub(crate) fn decode_with_ownership(+ bytes: &[u8],+ ) -> Result<(Self, Stage2Ownership), Stage2CodecError> {+ let persisted: PersistedStage2State = serde_json::from_slice(bytes)?;+ Ok((+ Self {+ in_cohort: persisted.in_cohort,+ last_evaluated_at_ms: persisted.last_evaluated_at_ms,+ },+ persisted.ownership,+ ))}}@@ -65,6 +115,29 @@ mod tests {);}+ #[test]+ fn transferred_fallback_is_additive_and_decodes_through_the_normal_codec() {+ let state = Stage2State {+ in_cohort: false,+ last_evaluated_at_ms: 1_700_000_000_123,+ };+ let bytes = state.encode_transferred_fallback();++ assert_eq!(Stage2State::decode(&bytes).unwrap(), state);+ assert_eq!(+ Stage2State::decode_with_ownership(&bytes).unwrap(),+ (state, Stage2Ownership::TransferredFallback),+ );+ assert_eq!(+ serde_json::from_slice::<serde_json::Value>(&bytes).unwrap(),+ serde_json::json!({+ "in_cohort": false,+ "last_evaluated_at_ms": 1_700_000_000_123_i64,+ "ownership": "transferred_fallback",+ }),+ );+ }+#[test]fn garbage_bytes_decode_to_err_not_panic() {assert!(Stage2State::decode(b"not json at all").is_err());diff --git a/rust/cohort-stream-processor/src/store/keys.rs b/rust/cohort-stream-processor/src/store/keys.rsindex a96559ff1ff6..5f01f2be85e9 100644--- a/rust/cohort-stream-processor/src/store/keys.rs+++ b/rust/cohort-stream-processor/src/store/keys.rs@@ -11,6 +11,12 @@ use super::rocks::StoreError;/// `[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][0xFF; 32][transferred-register discriminant][team_id u64][person_id 16]`.+pub const STAGE2_TRANSFERRED_REGISTER_PERSON_PREFIX_LEN: usize = STAGE2_KEY_LEN + 1 + 8 + 16;+/// `[transferred-register person prefix][cohort_id u64]`.+pub const STAGE2_TRANSFERRED_REGISTER_KEY_LEN: usize =+ STAGE2_TRANSFERRED_REGISTER_PERSON_PREFIX_LEN + 8;+const STAGE2_TRANSFERRED_REGISTER_DISCRIMINANT: u8 = 2;/// `[partition_id u16][team_id u64][old_person 16][merge_msg_partition u32][merge_msg_offset u64]`.pub const MERGE_DRAIN_KEY_LEN: usize = 2 + 8 + 16 + 4 + 8;/// `[partition_id u16][team_id u64][old_person 16]`.@@ -29,6 +35,23 @@ pub struct Stage2Key {pub person_id: Uuid,}+/// Catalog-independent inventory for a register received through the merge protocol.+///+/// The primary Stage 2 layout is cohort-first, so a merge drain cannot enumerate one person's rows+/// when its local catalog has not learned the cohort yet. This person-first metadata key closes that+/// gap. Its value carries the source transfer kind and bit plus the exact primary bytes they+/// describe; the primary row remains the receiver's current materialized membership state.+#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]+pub struct Stage2TransferredRegisterKey(Stage2Key);++/// Prefix selecting one person's transferred-register inventory entries.+#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]+pub struct Stage2TransferredRegisterPersonPrefix {+ pub partition_id: u16,+ pub team_id: u64,+ pub person_id: Uuid,+}+/// `cf_merge_drains_applied` key: Phase 1 idempotence marker for one merge message.#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]pub struct MergeDrainKey {@@ -91,6 +114,105 @@ impl Stage2Key {}}+impl Stage2TransferredRegisterKey {+ pub const fn new(key: Stage2Key) -> Self {+ Self(key)+ }++ pub const fn stage2_key(self) -> Stage2Key {+ self.0+ }++ pub fn encode(self) -> [u8; STAGE2_TRANSFERRED_REGISTER_KEY_LEN] {+ let mut out = [0u8; STAGE2_TRANSFERRED_REGISTER_KEY_LEN];+ out[0..2].copy_from_slice(&self.0.partition_id.to_be_bytes());+ out[2..STAGE2_KEY_LEN].fill(0xFF);+ out[STAGE2_KEY_LEN] = STAGE2_TRANSFERRED_REGISTER_DISCRIMINANT;+ out[(STAGE2_KEY_LEN + 1)..(STAGE2_KEY_LEN + 9)]+ .copy_from_slice(&self.0.team_id.to_be_bytes());+ out[(STAGE2_KEY_LEN + 9)..STAGE2_TRANSFERRED_REGISTER_PERSON_PREFIX_LEN]+ .copy_from_slice(self.0.person_id.as_bytes());+ out[STAGE2_TRANSFERRED_REGISTER_PERSON_PREFIX_LEN..]+ .copy_from_slice(&self.0.cohort_id.to_be_bytes());+ out+ }++ pub fn decode(bytes: &[u8]) -> Result<Self, StoreError> {+ check_len(+ bytes,+ STAGE2_TRANSFERRED_REGISTER_KEY_LEN,+ "stage2 transferred register",+ )?;+ if bytes[2..STAGE2_KEY_LEN].iter().any(|byte| *byte != 0xFF)+ || bytes[STAGE2_KEY_LEN] != STAGE2_TRANSFERRED_REGISTER_DISCRIMINANT+ {+ return Err(StoreError::UnknownKey {+ kind: "stage2 transferred register",+ });+ }+ Ok(Self(Stage2Key {+ partition_id: u16::from_be_bytes(array2(&bytes[0..2])),+ team_id: u64::from_be_bytes(array8(&bytes[(STAGE2_KEY_LEN + 1)..(STAGE2_KEY_LEN + 9)])),+ cohort_id: u64::from_be_bytes(array8(+ &bytes[STAGE2_TRANSFERRED_REGISTER_PERSON_PREFIX_LEN..],+ )),+ person_id: Uuid::from_bytes(array16(+ &bytes[(STAGE2_KEY_LEN + 9)..STAGE2_TRANSFERRED_REGISTER_PERSON_PREFIX_LEN],+ )),+ }))+ }++ pub const fn person_prefix(self) -> Stage2TransferredRegisterPersonPrefix {+ Stage2TransferredRegisterPersonPrefix {+ partition_id: self.0.partition_id,+ team_id: self.0.team_id,+ person_id: self.0.person_id,+ }+ }+}++impl Stage2TransferredRegisterPersonPrefix {+ pub const fn new(partition_id: u16, team_id: u64, person_id: Uuid) -> Self {+ Self {+ partition_id,+ team_id,+ person_id,+ }+ }++ pub fn encode(self) -> [u8; STAGE2_TRANSFERRED_REGISTER_PERSON_PREFIX_LEN] {+ let key = Stage2Key {+ partition_id: self.partition_id,+ team_id: self.team_id,+ cohort_id: 0,+ person_id: self.person_id,+ };+ let encoded = Stage2TransferredRegisterKey::new(key).encode();+ let mut out = [0u8; STAGE2_TRANSFERRED_REGISTER_PERSON_PREFIX_LEN];+ out.copy_from_slice(&encoded[..STAGE2_TRANSFERRED_REGISTER_PERSON_PREFIX_LEN]);+ out+ }++ pub fn range(self) -> (Vec<u8>, Vec<u8>) {+ let start = self.encode().to_vec();+ let mut end = start.clone();+ for byte in end.iter_mut().rev() {+ if let Some(next) = byte.checked_add(1) {+ *byte = next;+ return (start, end);+ }+ *byte = 0;+ }+ unreachable!("the transferred-register discriminant has a lexicographic successor")+ }+}++impl From<Stage2Key> for Stage2TransferredRegisterKey {+ fn from(value: Stage2Key) -> Self {+ Self::new(value)+ }+}+impl MergeDrainKey {pub fn encode(&self) -> [u8; MERGE_DRAIN_KEY_LEN] {let mut out = [0u8; MERGE_DRAIN_KEY_LEN];@@ -250,6 +372,19 @@ mod tests {34,);assert_eq!(STAGE2_KEY_LEN, 34);+ assert_eq!(STAGE2_TRANSFERRED_REGISTER_PERSON_PREFIX_LEN, 59);+ assert_eq!(+ Stage2TransferredRegisterKey::new(Stage2Key {+ partition_id: 1,+ team_id: 2,+ cohort_id: 3,+ person_id: person(4),+ })+ .encode()+ .len(),+ STAGE2_TRANSFERRED_REGISTER_KEY_LEN,+ );+ assert_eq!(STAGE2_TRANSFERRED_REGISTER_KEY_LEN, 67);}#[test]@@ -279,6 +414,84 @@ mod tests {);}+ #[test]+ fn transferred_register_key_round_trips_and_groups_by_person() {+ let row = Stage2Key {+ partition_id: 7,+ team_id: 42,+ cohort_id: 99,+ person_id: person(123),+ };+ let inventory = Stage2TransferredRegisterKey::new(row);+ assert_eq!(+ Stage2TransferredRegisterKey::decode(&inventory.encode()).unwrap(),+ inventory,+ );+ assert_eq!(inventory.stage2_key(), row);+ assert_eq!(+ inventory.person_prefix(),+ Stage2TransferredRegisterPersonPrefix::new(7, 42, person(123)),+ );+ assert!(Stage2Key::decode(&inventory.encode()).is_err());+ }++ #[test]+ fn transferred_register_namespace_sorts_after_rows_and_inside_partition() {+ for partition_id in [0, 7, u16::MAX] {+ let row = Stage2Key {+ partition_id,+ team_id: u64::MAX,+ cohort_id: u64::MAX,+ person_id: person(u128::MAX),+ };+ let inventory = Stage2TransferredRegisterKey::new(row).encode();+ assert!(row.encode().as_slice() < inventory.as_slice());+ let (partition_start, partition_end) = partition_range(partition_id);+ assert!(partition_start.as_slice() <= inventory.as_slice());+ assert!(inventory.as_slice() < partition_end.as_slice());+ }+ }++ #[test]+ fn transferred_register_person_prefix_selects_all_and_only_that_person() {+ let prefix = Stage2TransferredRegisterPersonPrefix::new(7, 42, person(9));+ let (start, end) = prefix.range();+ for cohort_id in [0, 1, u64::MAX] {+ let encoded = Stage2TransferredRegisterKey::new(Stage2Key {+ partition_id: 7,+ team_id: 42,+ cohort_id,+ person_id: person(9),+ })+ .encode();+ assert!(start.as_slice() <= encoded.as_slice());+ assert!(encoded.as_slice() < end.as_slice());+ }+ for foreign in [+ Stage2Key {+ partition_id: 8,+ team_id: 42,+ cohort_id: 1,+ person_id: person(9),+ },+ Stage2Key {+ partition_id: 7,+ team_id: 43,+ cohort_id: 1,+ person_id: person(9),+ },+ Stage2Key {+ partition_id: 7,+ team_id: 42,+ cohort_id: 1,+ person_id: person(10),+ },+ ] {+ let encoded = Stage2TransferredRegisterKey::new(foreign).encode();+ assert!(encoded.as_slice() < start.as_slice() || encoded.as_slice() >= end.as_slice());+ }+ }+#[test]fn partition_range_is_the_two_byte_successor() {let (start, end) = partition_range(0);diff --git a/rust/cohort-stream-processor/src/store/mod.rs b/rust/cohort-stream-processor/src/store/mod.rsindex c5e1803eb70c..5db880af00e9 100644--- a/rust/cohort-stream-processor/src/store/mod.rs+++ b/rust/cohort-stream-processor/src/store/mod.rs@@ -14,7 +14,10 @@ pub use column_families::{CF_META, CF_PENDING_TRANSFERS, CF_PERSON_RECORDS, CF_STAGE2,};pub use handle::{OffloadConfig, OffloadMode, ReadLane, StoreHandle};-pub use keys::{MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage2Key, TombstoneKey};+pub use keys::{+ MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage2Key, Stage2TransferredRegisterKey,+ Stage2TransferredRegisterPersonPrefix, TombstoneKey,+};pub use keyspace::{Behavioral, BehavioralKey, Keyspace, Meta, MetaKey, PersonPrefix, PersonRecordKey,PersonRecords,diff --git a/rust/cohort-stream-processor/src/store/rocks.rs b/rust/cohort-stream-processor/src/store/rocks.rsindex 72d39b1c038e..cfcf30722e91 100644--- a/rust/cohort-stream-processor/src/store/rocks.rs+++ b/rust/cohort-stream-processor/src/store/rocks.rs@@ -22,7 +22,8 @@ use tracing::warn;use super::column_families::{self, Cf, OpaqueCf};use super::keys::{- self, MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage2Key, TombstoneKey,+ self, MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage2Key,+ Stage2TransferredRegisterKey, Stage2TransferredRegisterPersonPrefix, TombstoneKey,};use super::keyspace::{BehavioralKey, Keyspace, Meta, PersonPrefix, PersonRecordKey, META_SCHEMA_VERSION,@@ -433,6 +434,42 @@ impl CohortStore {self.get(Cf::Stage2, &key.encode())}+ pub fn get_stage2_transferred_register(+ &self,+ key: &Stage2TransferredRegisterKey,+ ) -> Result<Option<Vec<u8>>, StoreError> {+ self.get(Cf::Stage2, &key.encode())+ }++ /// Batch-read transferred-register inventory values, preserving input order.+ pub fn multi_get_stage2_transferred_registers(+ &self,+ keys: &[Stage2TransferredRegisterKey],+ ) -> Result<Vec<Option<Vec<u8>>>, StoreError> {+ if keys.is_empty() {+ return Ok(Vec::new());+ }+ let handle = self.cf(Cf::Stage2)?;+ let encoded: Vec<_> = keys.iter().map(|key| key.encode()).collect();+ let started = Instant::now();+ let results = self+ .db+ .multi_get_cf(encoded.iter().map(|key| (handle, key.as_slice())));+ record_multi_get(started, keys.len());+ results+ .into_iter()+ .map(|result| {+ result.map_err(|source| {+ counter!(STORE_ERRORS_TOTAL, "op" => OP_MULTI_GET).increment(1);+ StoreError::Backend {+ op: OP_MULTI_GET,+ source,+ }+ })+ })+ .collect()+ }+/// Batch-read several `cf_stage2` values in one call, preserving input order.pub fn multi_get_stage2(&self, keys: &[Stage2Key]) -> Result<Vec<Option<Vec<u8>>>, StoreError> {// An empty batch is not a read: skip it so it records no phantom read-latency sample.@@ -460,6 +497,38 @@ impl CohortStore {.collect()}+ /// Scan the catalog-independent transferred-register inventory for one person.+ pub fn scan_stage2_transferred_registers(+ &self,+ prefix: Stage2TransferredRegisterPersonPrefix,+ ) -> Result<Vec<(Stage2TransferredRegisterKey, Vec<u8>)>, StoreError> {+ let (prefix_start, prefix_end) = prefix.range();+ let handle = self.cf(Cf::Stage2)?;+ let mut read_opts = ReadOptions::default();+ read_opts.set_iterate_upper_bound(prefix_end);+ let iter = self.db.iterator_cf_opt(+ handle,+ read_opts,+ IteratorMode::From(&prefix_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((+ Stage2TransferredRegisterKey::decode(&key_bytes)?,+ value.to_vec(),+ ));+ }+ Ok(out)+ }+/// Apply writes across CFs in one atomic `WriteBatch`.pub fn write_batch<F>(&self, build: F) -> Result<(), StoreError>where@@ -953,6 +1022,19 @@ impl<'db> BatchBuilder<'db> {self.batch.delete_cf(self.stage2, key.encode());}+ /// Preserve a merge-carried register independently of the receiver's current catalog.+ pub fn put_stage2_transferred_register(+ &mut self,+ key: &Stage2TransferredRegisterKey,+ value: &[u8],+ ) {+ self.batch.put_cf(self.stage2, key.encode(), value);+ }++ pub fn delete_stage2_transferred_register(&mut self, key: &Stage2TransferredRegisterKey) {+ self.batch.delete_cf(self.stage2, key.encode());+ }+/// Stage the Phase 1 idempotence marker for a drained merge message.pub fn put_merge_drain_applied(&mut self, key: &MergeDrainKey, value: &[u8]) {self.batch@@ -1429,6 +1511,50 @@ mod tests {);}+ #[test]+ fn transferred_register_inventory_scans_one_person_in_cohort_order() {+ let dir = TempDir::new().unwrap();+ let store = CohortStore::open(&StoreConfig {+ path: dir.path().join("transferred-register-scan"),+ ..StoreConfig::default()+ })+ .unwrap();+ let person_id = Uuid::from_u128(7);+ let prefix = Stage2TransferredRegisterPersonPrefix::new(3, 7, person_id);+ store+ .write_batch(|batch| {+ for cohort_id in [9, 2, 5] {+ batch.put_stage2_transferred_register(+ &Stage2TransferredRegisterKey::new(Stage2Key {+ partition_id: 3,+ team_id: 7,+ cohort_id,+ person_id,+ }),+ &[cohort_id as u8],+ );+ }+ batch.put_stage2_transferred_register(+ &Stage2TransferredRegisterKey::new(Stage2Key {+ partition_id: 3,+ team_id: 7,+ cohort_id: 1,+ person_id: Uuid::from_u128(8),+ }),+ b"foreign",+ );+ })+ .unwrap();++ let rows = store.scan_stage2_transferred_registers(prefix).unwrap();+ assert_eq!(+ rows.iter()+ .map(|(key, value)| (key.stage2_key().cohort_id, value.clone()))+ .collect::<Vec<_>>(),+ vec![(2, vec![2]), (5, vec![5]), (9, vec![9])],+ );+ }+#[test]fn scan_merge_cf_resumes_after_the_cursor_and_honors_the_limit_and_partition_bounds() {let dir = TempDir::new().unwrap();diff --git a/rust/cohort-stream-processor/src/store/staged.rs b/rust/cohort-stream-processor/src/store/staged.rsindex e66612d09f86..e6ef21a39bc3 100644--- a/rust/cohort-stream-processor/src/store/staged.rs+++ b/rust/cohort-stream-processor/src/store/staged.rs@@ -11,7 +11,10 @@//! that sequence built through `BatchBuilder` and committed through `write_batch`.use super::column_families::{Cf, OpaqueCf};-use super::keys::{MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage2Key, TombstoneKey};+use super::keys::{+ MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage2Key, Stage2TransferredRegisterKey,+ TombstoneKey,+};use super::keyspace::Keyspace;/// One staged RocksDB operation with owned bytes, so the batch is `Send + 'static`.@@ -85,6 +88,25 @@ impl StagedBatch {});}+ pub fn put_stage2_transferred_register(+ &mut self,+ key: &Stage2TransferredRegisterKey,+ value: &[u8],+ ) {+ self.ops.push(StagedOp::Put {+ cf: Cf::Stage2,+ key: key.encode().to_vec(),+ value: value.to_vec(),+ });+ }++ pub fn delete_stage2_transferred_register(&mut self, key: &Stage2TransferredRegisterKey) {+ self.ops.push(StagedOp::Delete {+ cf: Cf::Stage2,+ key: key.encode().to_vec(),+ });+ }+/// Stage the Phase 1 idempotence marker for a drained merge message.pub fn put_merge_drain_applied(&mut self, key: &MergeDrainKey, value: &[u8]) {self.ops.push(StagedOp::Put {@@ -253,6 +275,13 @@ mod tests {b.put_stage2(&stage2_key(1, 100), b"s2-put");b.put_stage2(&stage2_key(2, 200), b"s2-doomed");b.delete_stage2(&stage2_key(2, 200));+ b.put_stage2_transferred_register(+ &Stage2TransferredRegisterKey::new(stage2_key(1, 100)),+ b"kind",+ );+ b.delete_stage2_transferred_register(&Stage2TransferredRegisterKey::new(stage2_key(+ 2, 200,+ )));b.put_merge_drain_applied(&merge_drain_key(1), b"drain-put");b.delete_merge_drain_applied(&merge_drain_key(2));@@ -283,6 +312,13 @@ mod tests {s.put_stage2(&stage2_key(1, 100), b"s2-put");s.put_stage2(&stage2_key(2, 200), b"s2-doomed");s.delete_stage2(&stage2_key(2, 200));+ s.put_stage2_transferred_register(+ &Stage2TransferredRegisterKey::new(stage2_key(1, 100)),+ b"kind",+ );+ s.delete_stage2_transferred_register(&Stage2TransferredRegisterKey::new(stage2_key(+ 2, 200,+ )));s.put_merge_drain_applied(&merge_drain_key(1), b"drain-put");s.delete_merge_drain_applied(&merge_drain_key(2));@@ -315,7 +351,7 @@ mod tests {let mut staged = StagedBatch::default();drive_staged_batch(&mut staged);assert!(!staged.is_empty());- assert_eq!(staged.len(), 16);+ assert_eq!(staged.len(), 18);via_staged.apply(&staged).unwrap();// `scan_merge_cf` is CF-generic and all keys carry the partition prefix, so it enumerates anydiff --git a/rust/cohort-stream-processor/src/workers/cascade_path.rs b/rust/cohort-stream-processor/src/workers/cascade_path.rsindex b60871b468db..0277b7418df3 100644--- a/rust/cohort-stream-processor/src/workers/cascade_path.rs+++ b/rust/cohort-stream-processor/src/workers/cascade_path.rs@@ -129,6 +129,15 @@ pub(crate) async fn handle_cascade(return;}};+ if diff.requires_write() {+ writes.push((+ diff.stage2_key,+ Stage2State {+ in_cohort: diff.new_bit,+ last_evaluated_at_ms: evaluated_at_ms,+ },+ ));+ }if !diff.flipped() {continue;}@@ -142,13 +151,6 @@ pub(crate) async fn handle_cascade(origin: None,run_id: None,});- writes.push((- diff.stage2_key,- Stage2State {- in_cohort: diff.new_bit,- last_evaluated_at_ms: evaluated_at_ms,- },- ));// The external flip above is unconditional; only the onward hop is depth/cycle bounded.match should_emit(message,@@ -180,31 +182,33 @@ pub(crate) async fn handle_cascade(}}- if changes.is_empty() {+ if changes.is_empty() && writes.is_empty() {mark_processed(&merge.cascade_tracker, partition_id, offset);return;}- // Produce-before-state: both legs must ack before the bits commit (see the module doc).- let membership_errors = produce_membership(sink, changes).await;- if membership_errors > 0 {- warn!(- partition_id,- errors = membership_errors,- "cascade membership produce failed; holding the cascade offset for redelivery",- );- hold(&merge.cascade_tracker, partition_id, offset);- return;- }- let cascade_errors = produce_cascades(merge, outgoing).await;- if cascade_errors > 0 {- warn!(- partition_id,- errors = cascade_errors,- "cascade onward produce failed; holding the cascade offset for redelivery",- );- hold(&merge.cascade_tracker, partition_id, offset);- return;+ if !changes.is_empty() {+ // Produce-before-state: both legs must ack before flipped bits commit (see the module doc).+ let membership_errors = produce_membership(sink, changes).await;+ if membership_errors > 0 {+ warn!(+ partition_id,+ errors = membership_errors,+ "cascade membership produce failed; holding the cascade offset for redelivery",+ );+ hold(&merge.cascade_tracker, partition_id, offset);+ return;+ }+ let cascade_errors = produce_cascades(merge, outgoing).await;+ if cascade_errors > 0 {+ warn!(+ partition_id,+ errors = cascade_errors,+ "cascade onward produce failed; holding the cascade offset for redelivery",+ );+ hold(&merge.cascade_tracker, partition_id, offset);+ return;+ }}let mut staged = StagedBatch::default();@@ -272,6 +276,7 @@ mod tests {use crate::stage1::key::LeafStateKey;use crate::stage1::person_record::{MatchedSet, PersonRecord};use crate::stage1::state::{AppliedOffsets, Stage1State, StatefulRecord};+ use crate::stage2::state::Stage2Ownership;use crate::store::{Behavioral, BehavioralKey, CohortStore, OffloadConfig, OffloadMode, PersonRecordKey,PersonRecords, StoreConfig,@@ -441,6 +446,7 @@ mod tests {seed_tile_sink: Arc::new(crate::producer::CaptureSeedTileSink::new()),seed_tracker: Arc::new(crate::partitions::offset_tracker::OffsetTracker::new()),live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),+ register_transfer_enabled: false,};// The cascade was dispatched this tenure, so its ceiling is raised — mirrors the dispatcher.deps.cascade_tracker@@ -564,6 +570,70 @@ mod tests {assert_eq!(committed(&deps), Some(OFFSET + 1), "still advances");}+ #[tokio::test]+ async fn cascade_noop_claims_a_transferred_fallback_without_emitting() {+ let (_dir, store) = temp_store();+ let catalog = catalog(+ vec![+ (2, vec![behavioral_leaf()]),+ (1, vec![person_leaf(), cohort_ref(2)]),+ ],+ true,+ );+ let alice = person(1);+ write_behavioral(&store, behavioral_lsk(&catalog), alice, behavioral_match());+ write_person_record(&store, alice, &[PERSON_HASH]);+ let key = Stage2Key {+ partition_id: PARTITION,+ team_id: TEAM as u64,+ cohort_id: 1,+ person_id: alice,+ };+ store+ .write_batch(|batch| {+ batch.put_stage2(+ &key,+ &Stage2State {+ in_cohort: true,+ last_evaluated_at_ms: 0,+ }+ .encode_transferred_fallback(),+ );+ })+ .unwrap();++ let membership = CaptureSink::new();+ let cascade = CaptureCascadeSink::new();+ let (sink, deps) = deps(&membership, &cascade, true, 1000);+ let msg = first_cascade(incoming(2, alice, 1, vec![2]).change, 99);++ handle_cascade(+ PARTITION,+ &handle(&store),+ &catalog,+ &sink,+ &deps,+ TS,+ &msg,+ OFFSET,+ )+ .await;++ let bytes = store.get_stage2(&key).unwrap().unwrap();+ let (state, ownership) = Stage2State::decode_with_ownership(&bytes).unwrap();+ assert!(state.in_cohort);+ assert_eq!(ownership, Stage2Ownership::Local);+ assert!(+ membership.changes().is_empty(),+ "ownership settlement is not a flip"+ );+ assert!(+ cascade.messages().is_empty(),+ "ownership settlement does not cascade"+ );+ assert_eq!(committed(&deps), Some(OFFSET + 1));+ }+#[tokio::test]async fn no_referrers_drains_without_emitting() {let (_dir, store) = temp_store();diff --git a/rust/cohort-stream-processor/src/workers/event_path.rs b/rust/cohort-stream-processor/src/workers/event_path.rsindex 38543b57d6b6..efbcb5b26fa8 100644--- a/rust/cohort-stream-processor/src/workers/event_path.rs+++ b/rust/cohort-stream-processor/src/workers/event_path.rs@@ -45,6 +45,7 @@ use crate::stage1::state::{};use crate::stage1::time::clickhouse_timestamp_to_millis;use crate::stage1::transition::{LeafTransition, TransitionKind};+use crate::stage2::{single_leaf_transition_register_writes, stage_register_writes};use crate::store::{Behavioral, BehavioralKey, CohortStore, EventSnapshotRaw, PersonPrefix, PersonRecords,StagedBatch, StoreError, StoreHandle,@@ -538,6 +539,17 @@ pub(crate) fn fold_event(write_stats.record_size = Some(bytes.len());staged.put::<PersonRecords>(&prefix.record_key(), &bytes);}+ for transition in &transitions {+ stage_register_writes(+ &mut staged,+ single_leaf_transition_register_writes(+ filters,+ prefix.partition_id,+ transition,+ event_ms,+ ),+ );+ }FoldResult::Folded(FoldOutput {staged,diff --git a/rust/cohort-stream-processor/src/workers/merge_path.rs b/rust/cohort-stream-processor/src/workers/merge_path.rsindex 2ac59ec90daa..caddbaf4e9b8 100644--- a/rust/cohort-stream-processor/src/workers/merge_path.rs+++ b/rust/cohort-stream-processor/src/workers/merge_path.rs@@ -16,7 +16,9 @@ use crate::filters::manager::CatalogHandle;use crate::filters::reverse_index::TeamFilters;use crate::filters::{TeamFiltersBuilder, TeamId};use crate::merge::apply_handler::{handle_transfer, ApplyOutcome};-use crate::merge::drain_handler::{handle_merge_event, DrainOutcome};+use crate::merge::drain_handler::{+ handle_merge_event_with_transfer_mode, DrainOutcome, MembershipRegisterTransferMode,+};use crate::merge::transfer::{MergeStateTransfer, PendingTransfer, PersonMergeEvent};use crate::observability::metrics::{COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH, MERGE_APPLY_DURATION_SECONDS,@@ -127,6 +129,10 @@ pub struct MergeWorkerDeps {pub seed_tracker: Arc<OffsetTracker>,/// Fold-frontier watermarks the seed fence reads; the worker advances them post-mark.pub live_watermarks: Arc<LiveWatermarks>,+ /// Whether cross-partition merge drains ship the additive membership-register payload. Keep+ /// `false` until every pod in the fleet can apply the transfer; while off the drain ships leaves+ /// only and never holds. Wired from `COHORT_REGISTER_TRANSFER_ENABLED`.+ pub register_transfer_enabled: bool,}impl MergeWorkerDeps {@@ -146,6 +152,7 @@ impl MergeWorkerDeps {seed_tile_sink: Arc::new(CaptureSeedTileSink::new()),seed_tracker: Arc::new(OffsetTracker::new()),live_watermarks: Arc::new(LiveWatermarks::new()),+ register_transfer_enabled: false,})}}@@ -173,6 +180,8 @@ pub(crate) async fn handle_merge(let snapshot = snapshot.clone();let event_owned = event.clone();let partition_count = merge.partition_count;+ let register_transfer_mode =+ MembershipRegisterTransferMode::from_enabled(merge.register_transfer_enabled);handle.run_section("merge_drain", move |store| {let fallback: TeamFilters;@@ -186,13 +195,14 @@ pub(crate) async fn handle_merge(// Timed inside the section so the histogram keeps measuring drain execution only;// permit and pool-queue waits are on `store_offload_*{op="merge_drain"}`.let started = Instant::now();- let outcome = handle_merge_event(+ let outcome = handle_merge_event_with_transfer_mode(partition_id,store,filters,&event_owned,msg_coords,partition_count,+ register_transfer_mode,);histogram!(MERGE_DRAIN_DURATION_SECONDS).record(started.elapsed().as_secs_f64());outcome@@ -252,9 +262,9 @@ pub(crate) async fn handle_merge(}Ok(DrainOutcome::Drained { transfer, effects }) => {effects.apply_to(queue);- // 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() {+ // Nothing to apply — skip the produce. The transfer type owns this predicate so drain+ // staging and worker settlement cannot disagree about new payload classes.+ if !transfer.has_payload() {counter!(MERGE_TRANSFERS_SKIPPED_EMPTY_TOTAL).increment(1);mark_processed(&merge.merge_tracker, partition_id, offset);return;@@ -723,13 +733,18 @@ fn empty_team_filters() -> TeamFilters {mod tests {use super::*;use envconfig::Envconfig;+ use serde_json::json;use tempfile::TempDir;use uuid::Uuid;- use crate::merge::transfer::TransferLeaf;+ use crate::filters::{CohortId, FilterCatalog};+ use crate::merge::transfer::{TransferLeaf, MERGE_EVENT_SCHEMA_VERSION};+ use crate::partitions::partitioner::partition_of;+ use crate::producer::CaptureSink;use crate::stage1::key::LeafStateKey;use crate::stage1::state::{AppliedOffsets, Stage1State, StatefulRecord};- use crate::store::{CohortStore, OffloadConfig, OffloadMode, StoreConfig};+ use crate::stage2::Stage2State;+ use crate::store::{CohortStore, OffloadConfig, OffloadMode, Stage2Key, StoreConfig};/// Wrap a test store in the `All` operating point so `handle_redrive` runs on the blocking pool.fn handle(store: &CohortStore) -> StoreHandle {@@ -818,6 +833,7 @@ mod tests {source_partition: 0,source_offset: 0,leaves: vec![],+ membership_registers: vec![],forward_hops: 0,person_dedup: None,@@ -846,6 +862,7 @@ mod tests {source_partition: 0,source_offset: 0,leaves: vec![],+ membership_registers: vec![],forward_hops: 0,person_dedup: None,@@ -886,6 +903,7 @@ mod tests {seed_tile_sink: Arc::new(crate::producer::CaptureSeedTileSink::new()),seed_tracker: Arc::new(crate::partitions::offset_tracker::OffsetTracker::new()),live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),+ register_transfer_enabled: false,}}@@ -908,6 +926,7 @@ mod tests {AppliedOffsets::default(),),)],+ membership_registers: vec![],forward_hops: 0,person_dedup: None,@@ -1095,6 +1114,7 @@ mod tests {source_partition: 9,source_offset: 100,leaves: vec![],+ membership_registers: vec![],forward_hops: 1,person_dedup: None,@@ -1168,4 +1188,96 @@ mod tests {"the later success must NOT advance committable past the held offset 41",);}++ /// With `register_transfer_enabled` false, a cross-partition merge of a person that owns a+ /// single-leaf register row must drain and advance its offset (never hold and wedge the partition)+ /// and reclaim P_old's register row. Guards against reintroducing a gate-off hold.+ #[tokio::test]+ async fn disabled_register_transfer_drains_the_cross_partition_merge_without_holding() {+ const K: i64 = 50;++ let cohort = json!({+ "properties": {+ "type": "AND",+ "values": [{+ "type": "behavioral", "key": "$pageview", "value": "performed_event",+ "time_value": 7, "time_interval": "day",+ "conditionHash": "0123456789abcdef",+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],+ }]+ }+ });+ let mut builder = TeamFiltersBuilder::default();+ builder.add_cohort(CohortId(1), TeamId(7), &cohort).unwrap();+ let filters = builder.freeze(UTC);+ let catalog =+ CatalogHandle::from_catalog(FilterCatalog::from_teams([(TeamId(7), filters)]));++ let old_person = Uuid::from_u128(1);+ let old_partition = partition_of(TeamId(7), &old_person, COHORT_PARTITION_COUNT) as u16;+ let new_person = (2u128..)+ .map(Uuid::from_u128)+ .find(|person| {+ partition_of(TeamId(7), person, COHORT_PARTITION_COUNT) as u16 != old_partition+ })+ .unwrap();+ let register_key = Stage2Key {+ partition_id: old_partition,+ team_id: 7,+ cohort_id: 1,+ person_id: old_person,+ };++ let (_dir, store) = temp_store();+ store+ .write_batch(|batch| {+ batch.put_stage2(+ ®ister_key,+ &Stage2State {+ in_cohort: true,+ last_evaluated_at_ms: 1,+ }+ .encode(),+ );+ })+ .unwrap();++ // `capture_deps` builds with `register_transfer_enabled: false`.+ let deps = capture_deps(CaptureTransferSink::new());+ deps.merge_tracker+ .mark_dispatched(old_partition as i32, K + 1);++ let sink: Arc<dyn MembershipSink> = Arc::new(CaptureSink::new());+ let mut queue: EvictionQueue<BehavioralKey> = EvictionQueue::new();+ handle_merge(+ old_partition,+ &handle(&store),+ &catalog,+ &sink,+ &deps,+ &mut queue,+ "1",+ &PersonMergeEvent {+ team_id: 7,+ old_person_uuid: old_person,+ new_person_uuid: new_person,+ merged_at_ms: 2,+ schema_version: MERGE_EVENT_SCHEMA_VERSION,+ },+ K,+ )+ .await;++ assert_eq!(+ deps.merge_tracker+ .committable_offsets()+ .get(&(old_partition as i32)),+ Some(&(K + 1)),+ "the disabled-transfer merge drains and advances past its offset rather than holding",+ );+ assert!(+ store.get_stage2(®ister_key).unwrap().is_none(),+ "P_old's register row is reclaimed by the drain, like the pre-register pipeline",+ );+ }}diff --git a/rust/cohort-stream-processor/src/workers/seed_path.rs b/rust/cohort-stream-processor/src/workers/seed_path.rsindex c21920c5e21f..f6ab5dad8927 100644--- a/rust/cohort-stream-processor/src/workers/seed_path.rs+++ b/rust/cohort-stream-processor/src/workers/seed_path.rs@@ -39,6 +39,9 @@ use crate::stage1::pick_state::{EvictionWindow, PredicateOp};use crate::stage1::predicate::{compressed_predicate, daily_predicate, predicate};use crate::stage1::state::{Stage1State, StateVariant, StatefulRecord};use crate::stage1::transition::{LeafTransition, TransitionKind};+use crate::stage2::{+ leaf_membership, single_leaf_register_writes, stage_register_writes, MembershipRegisterSource,+};use crate::store::{Behavioral, BehavioralKey, PersonPrefix, ReadLane, StagedBatch, StoreHandle};use crate::sweep::EvictionQueue;use crate::workers::merge_path::MergeWorkerDeps;@@ -107,8 +110,8 @@ impl SeedDropReason {}}-/// One leaf's merge outcome; `Unchanged` (byte-identical post-merge record) is the tile-/// idempotency.+/// One leaf's merge outcome; `Unchanged` carries the post-merge record so idempotent seed delivery+/// can still repair the single-leaf membership register.#[must_use]#[derive(Debug, Clone, PartialEq)]pub(crate) enum LeafMergeOutcome {@@ -118,7 +121,9 @@ pub(crate) enum LeafMergeOutcome {/// The recomputed eviction deadline ([`i64::MAX`] = permanent, never scheduled).deadline_ms: i64,},- Unchanged,+ Unchanged {+ record: StatefulRecord,+ },Dropped(SeedDropReason),}@@ -445,7 +450,7 @@ fn finish(deadline_ms: i64,) -> LeafMergeOutcome {if prev_state.as_ref() == Some(&record.state) {- return LeafMergeOutcome::Unchanged;+ return LeafMergeOutcome::Unchanged { record };}let kind = match (predicate_before, predicate_after) {(false, true) => Some(TransitionKind::Entered),@@ -755,6 +760,19 @@ fn apply_tile_to_leaves(counter!(SEED_TILES_APPLIED_TOTAL, "variant" => record.state.variant().as_str()).increment(1);let key = prefix.behavioral_key(lsk);+ stage_seed_membership_registers(+ &mut application.staged,+ filters,+ MembershipRegisterSource {+ partition_id: prefix.partition_id,+ team_id: identity.team_id,+ person_id: identity.person_id,+ leaf_state_key: identity.lsk,+ },+ meta,+ &record.state,+ now_ms,+ );application.staged.put::<Behavioral>(&key, &record.encode());application.stage2_leaves.push((lsk, person));if let Some(transition) = transition {@@ -764,9 +782,22 @@ fn apply_tile_to_leaves(application.schedules.push((key, deadline_ms));}}- LeafMergeOutcome::Unchanged => {+ LeafMergeOutcome::Unchanged { record } => {counter!(SEED_TILES_UNCHANGED_TOTAL, "variant" => meta.variant.as_str()).increment(1);+ stage_seed_membership_registers(+ &mut application.staged,+ filters,+ MembershipRegisterSource {+ partition_id: prefix.partition_id,+ team_id: identity.team_id,+ person_id: identity.person_id,+ leaf_state_key: identity.lsk,+ },+ meta,+ &record.state,+ now_ms,+ );application.stage2_leaves.push((lsk, person));}LeafMergeOutcome::Dropped(reason) => {@@ -777,6 +808,21 @@ fn apply_tile_to_leaves(application}+fn stage_seed_membership_registers(+ staged: &mut StagedBatch,+ filters: &TeamFilters,+ source: MembershipRegisterSource,+ meta: &LeafStateMeta,+ state: &Stage1State,+ now_ms: i64,+) {+ let in_cohort = leaf_membership(Some(state), meta);+ stage_register_writes(+ staged,+ single_leaf_register_writes(filters, source, in_cohort, now_ms),+ );+}+fn tag_seed(changes: &mut [CohortMembershipChange], run_id: RunId) {for change in changes {change.origin = Some(ChangeOrigin::Seed);@@ -931,9 +977,11 @@ mod tests {EvictionWindow::RelativeDays { days: 7 }.earliest_eviction_at_ms(NOW_MS, UTC),);- assert_eq!(- merge(&meta, now_day(), 1, Some(record)),- LeafMergeOutcome::Unchanged,+ assert!(+ matches!(+ merge(&meta, now_day(), 1, Some(record)),+ LeafMergeOutcome::Unchanged { .. }+ ),"re-delivery is a structural no-op",);}@@ -1115,10 +1163,10 @@ mod tests {let (live, _, _) = merged(merge(&meta, now_day(), 3, None));// A tile counting a subset (late-arrival overlap) is absorbed: max(3, 2) = 3 → Unchanged.- assert_eq!(+ assert!(matches!(merge(&meta, now_day(), 2, Some(live.clone())),- LeafMergeOutcome::Unchanged,- );+ LeafMergeOutcome::Unchanged { .. }+ ));// A tile counting a superset raises the bucket to the absolute count, never the sum.let (after, _, _) = merged(merge(&meta, now_day(), 5, Some(live)));let Stage1State::BehavioralDailyBuckets { ref buckets, .. } = after.state else {@@ -1148,10 +1196,10 @@ mod tests {start_of_day_ms_in_tz(now_day() - 30 + 365 + 1, UTC));- assert_eq!(+ assert!(matches!(merge(&meta, now_day() - 30, 2, Some(record)),- LeafMergeOutcome::Unchanged,- );+ LeafMergeOutcome::Unchanged { .. }+ ));}#[test]@@ -1692,6 +1740,7 @@ mod tests {seed_tile_sink: Arc::new(seed_sink.clone()),seed_tracker: Arc::new(OffsetTracker::new()),live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),+ register_transfer_enabled: false,};Self {_dir,@@ -1768,10 +1817,80 @@ mod tests {assert_eq!(shell.committable(partition_id), Some(10));assert_eq!(shell.queue.len(), 1, "the leaf's eviction was scheduled");- // Re-delivery: max-merge no-op, no duplicate emission, offset still advances.+ let register_key = Stage2Key {+ partition_id,+ team_id: TEAM.0 as u64,+ cohort_id: 1,+ person_id: person,+ };+ assert!(+ Stage2State::decode(&shell.store.get_stage2(®ister_key).unwrap().unwrap())+ .unwrap()+ .in_cohort,+ "the seed apply materializes the single-leaf register",+ );++ shell+ .store+ .write_batch(|batch| batch.delete_stage2(®ister_key))+ .unwrap();++ // Re-delivery: max-merge no-op, no duplicate emission, and the missing register self-heals.shell.run(partition_id, SeedWork::Tile(tile), 10).await;assert_eq!(shell.sink.changes().len(), 1);assert_eq!(shell.committable(partition_id), Some(11));+ assert!(+ Stage2State::decode(&shell.store.get_stage2(®ister_key).unwrap().unwrap())+ .unwrap()+ .in_cohort,+ "an Unchanged seed replay restores the register from its post-merge record",+ );+ }++ #[tokio::test]+ async fn unchanged_non_member_seed_restores_an_explicit_false_register_without_emission() {+ let person = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16;+ let mut shell = Shell::new(vec![(1, wrap(vec![multiple_leaf_json(7, "gte", 3)]))]);+ let tile = tile_for(person, today(), 1);+ let register_key = Stage2Key {+ partition_id,+ team_id: TEAM.0 as u64,+ cohort_id: 1,+ person_id: person,+ };++ shell+ .run(partition_id, SeedWork::Tile(tile.clone()), 0)+ .await;+ let registered = Stage2State::decode(+ &shell+ .store+ .get_stage2(®ister_key)+ .unwrap()+ .expect("seeded non-member has a register row"),+ )+ .unwrap();+ assert!(!registered.in_cohort);+ assert!(shell.sink.changes().is_empty());++ shell+ .store+ .write_batch(|batch| batch.delete_stage2(®ister_key))+ .unwrap();+ shell.run(partition_id, SeedWork::Tile(tile), 1).await;++ let restored = Stage2State::decode(+ &shell+ .store+ .get_stage2(®ister_key)+ .unwrap()+ .expect("Unchanged replay restores the false register"),+ )+ .unwrap();+ assert!(!restored.in_cohort);+ assert!(shell.sink.changes().is_empty());+ assert_eq!(shell.committable(partition_id), Some(2));}#[tokio::test]diff --git a/rust/cohort-stream-processor/src/workers/stage2_gc.rs b/rust/cohort-stream-processor/src/workers/stage2_gc.rsindex dae3488c0e1a..f62d0ce25da2 100644--- a/rust/cohort-stream-processor/src/workers/stage2_gc.rs+++ b/rust/cohort-stream-processor/src/workers/stage2_gc.rs@@ -1,15 +1,15 @@//! Worker-side `cf_stage2` orphan garbage collection.//!-//! [`handle_stage2_orphan_gc`] reclaims `cf_stage2` rows whose cohort is no longer composable, on the-//! same [`ShuffleMessage::MergeCfGc`](crate::partitions::shuffle_message::ShuffleMessage::MergeCfGc)+//! [`handle_stage2_orphan_gc`] reclaims `cf_stage2` rows whose cohort no longer registers membership,+//! on the same+//! [`ShuffleMessage::MergeCfGc`](crate::partitions::shuffle_message::ShuffleMessage::MergeCfGc)//! tick as [`handle_merge_gc`](crate::workers::merge_gc::handle_merge_gc). Two paths strand such rows:-//! an absent-team merge drain (the drain deletes via the catalog's composable cohorts, empty when the-//! team is absent) and a cohort reclassified out of the composable set (`Stage2Composable` →-//! `SingleLeaf`, deleted, or made non-realtime).+//! an absent-team merge drain (the catalog provides no ids to delete) and a cohort deleted or made+//! non-realtime.//!//! The victim decision is **catalog absence, not a timestamp**: a `cf_stage2` value's-//! `last_evaluated_at_ms` is the replay-stable source event time, so a time cutoff would evict a-//! still-live dormant member.+//! `last_evaluated_at_ms` records its latest evaluation, not its retention lifetime, so a time cutoff+//! would evict a still-live dormant member.//!//! Two gates keep the pass from deleting live state on an untrustworthy snapshot — a successful//! *empty* refresh is indistinguishable from "every cohort vanished":@@ -23,11 +23,12 @@ use tracing::warn;use crate::filters::manager::CatalogHandle;use crate::filters::{CohortId, FilterCatalog, TeamId};+use crate::merge::transfer::{TransferMembershipRegisterKind, TransferredRegisterProvenance};use crate::observability::metrics::{STAGE2_ORPHAN_GC_KEYS_DELETED_TOTAL, STAGE2_ORPHAN_GC_KEYS_SCANNED_TOTAL,STAGE2_ORPHAN_GC_SKIPPED_TOTAL, STAGE2_ORPHAN_GC_UNDECODABLE_KEYS_TOTAL,};-use crate::store::{Cf, CohortStore, Stage2Key};+use crate::store::{Cf, CohortStore, Stage2Key, Stage2TransferredRegisterKey};/// Per-worker resume cursor: the raw last-key scanned in this partition's `cf_stage2` slice; `None`/// restarts at the prefix start. Loss on a rebalance is benign — a fresh tenure rescans and@@ -35,9 +36,12 @@ use crate::store::{Cf, CohortStore, Stage2Key};#[derive(Default)]pub struct Stage2GcCursor(Option<Vec<u8>>);-/// GC one partition's `cf_stage2` orphans for one tick: scan up to `scan_limit` rows, delete every-/// row whose cohort is no longer composable in `catalog`, and advance the cursor (wrapping on-/// exhaustion). A no-op before the first catalog load or against an empty catalog (the two safety gates).+/// GC one partition's `cf_stage2` orphans for one tick: inspect at most `scan_limit` raw keys,+/// delete every Stage 2 row whose cohort no longer registers membership in `catalog`, and advance+/// the raw cursor (wrapping on exhaustion). Transferred-register metadata counts against the hard+/// per-tick budget but is not a membership row; it protects a catalog-skewed row until the catalog+/// recognizes it. A no-op before the first catalog load or against an empty catalog (the two+/// safety gates).// Sync GC core; runs on the blocking pool inside `StoreHandle::run_section`, so its direct// `CohortStore` I/O is already off the runtime threads.#[allow(clippy::disallowed_methods)]@@ -61,9 +65,9 @@ pub fn handle_stage2_orphan_gc(return;}- let page = match store.scan_merge_cf(Cf::Stage2, partition_id, cursor.0.as_deref(), scan_limit)+ let rows = match store.scan_merge_cf(Cf::Stage2, partition_id, cursor.0.as_deref(), scan_limit){- Ok(page) => page,+ Ok(rows) => rows,Err(error) => {warn!(partition_id,@@ -74,21 +78,74 @@ pub fn handle_stage2_orphan_gc(}};- if page.is_empty() {- // Slice exhausted — wrap the cursor to the prefix start.+ if rows.is_empty() {cursor.0 = None;return;}- counter!(STAGE2_ORPHAN_GC_KEYS_SCANNED_TOTAL).increment(page.len() as u64);+ counter!(STAGE2_ORPHAN_GC_KEYS_SCANNED_TOTAL).increment(rows.len() as u64);+ let next_cursor = (rows.len() == scan_limit).then(|| {+ rows.last()+ .expect("a full raw page has a final key")+ .0+ .clone()+ });// Decode and classify before opening the batch, since the batch closure is infallible.let mut undecodable = 0u64;let mut victims: Vec<Stage2Key> = Vec::new();- for (key_bytes, _value) in &page {+ let mut settled_transferred: Vec<Stage2TransferredRegisterKey> = Vec::new();+ for (key_bytes, value) in &rows {+ if let Ok(transferred) = Stage2TransferredRegisterKey::decode(key_bytes) {+ let stage2_key = transferred.stage2_key();+ let primary = match store.get_stage2(&stage2_key) {+ Ok(row) => row,+ Err(error) => {+ warn!(+ partition_id,+ error = %error,+ "cf_stage2 orphan GC inventory read failed; retrying this page next tick",+ );+ return;+ }+ };+ // Exact primary bytes tie provenance to the receiver fallback it describes. A later+ // local evaluation supersedes that fallback without requiring an extra tombstone on+ // every Stage 2 write. Matching catalog semantics also make person-first enumeration+ // redundant. Missing primaries always leave stale inventory.+ let settled = match (+ primary.as_deref(),+ TransferredRegisterProvenance::decode(value),+ ) {+ (None, _) => true,+ (Some(primary), Some(provenance)) => {+ !provenance.matches_primary(primary)+ || Some(provenance.kind) == catalog_register_kind(&snapshot, &stage2_key)+ }+ (Some(_), None) => false,+ };+ if settled {+ settled_transferred.push(transferred);+ }+ continue;+ }match Stage2Key::decode(key_bytes) {Ok(key) => match is_orphan(&snapshot, &key) {- Some(true) => victims.push(key),+ Some(true) => {+ let inventory = Stage2TransferredRegisterKey::new(key);+ match store.get_stage2_transferred_register(&inventory) {+ Ok(Some(_)) => {}+ Ok(None) => victims.push(key),+ Err(error) => {+ warn!(+ partition_id,+ error = %error,+ "cf_stage2 orphan GC protection read failed; retrying this page next tick",+ );+ return;+ }+ }+ }Some(false) => {}// An id outside `i32` can't be classified — leave it in place (not corruption).None => undecodable += 1,@@ -104,11 +161,14 @@ pub fn handle_stage2_orphan_gc(}}- if !victims.is_empty() {+ if !victims.is_empty() || !settled_transferred.is_empty() {let result = store.write_batch(|batch| {for key in &victims {batch.delete_stage2(key);}+ for key in &settled_transferred {+ batch.delete_stage2_transferred_register(key);+ }});match result {Ok(()) => {@@ -130,16 +190,12 @@ pub fn handle_stage2_orphan_gc(counter!(STAGE2_ORPHAN_GC_UNDECODABLE_KEYS_TOTAL).increment(undecodable);}- // Full page → resume after the last key; short page → wrap. The cursor is the last *scanned* key- // (survivors included), so a mostly-live slice still advances over successive ticks.- cursor.0 = (page.len() == scan_limit)- .then(|| page.last().expect("non-empty by the guard above").0.clone());+ cursor.0 = next_cursor;}-/// Whether a `cf_stage2` row is an orphan: its cohort is not a composable cohort in `snapshot`-/// (`writes_cf_stage2()` is `true` only for the two composable classes, so team-absent, cohort-absent,-/// and reclassified-out all resolve to orphan). `None` when the id can't be classified (outside `i32`),-/// which the caller leaves in place.+/// Whether a `cf_stage2` row is an orphan: its cohort does not register membership in `snapshot`.+/// Team-absent, cohort-absent, and excluded cohorts resolve to orphan. `None` when the id can't be+/// classified (outside `i32`), which the caller leaves in place.fn is_orphan(snapshot: &FilterCatalog, key: &Stage2Key) -> Option<bool> {// Keys store `u64`; `TeamId`/`CohortId` are `i32`, so an overflowing id can't be matched.let team_id = i32::try_from(key.team_id).ok()?;@@ -147,10 +203,20 @@ fn is_orphan(snapshot: &FilterCatalog, key: &Stage2Key) -> Option<bool> {let live = snapshot.team(TeamId(team_id)).and_then(|team_filters| team_filters.eligibility.get(&CohortId(cohort_id)))- .is_some_and(|eligibility| eligibility.writes_cf_stage2());+ .is_some_and(|eligibility| eligibility.registers_membership());Some(!live)}+/// Catalog semantics for a register, when both ids are representable and the cohort is live.+fn catalog_register_kind(+ snapshot: &FilterCatalog,+ key: &Stage2Key,+) -> Option<TransferMembershipRegisterKind> {+ let team_id = TeamId(i32::try_from(key.team_id).ok()?);+ let cohort_id = CohortId(i32::try_from(key.cohort_id).ok()?);+ TransferMembershipRegisterKind::from_filters(snapshot.team(team_id)?, cohort_id)+}+// Tests seed and read stage-2 rows directly against the store.#[cfg(test)]#[allow(clippy::disallowed_methods)]@@ -160,6 +226,7 @@ mod tests {use uuid::Uuid;use crate::filters::reverse_index::TeamFilters;+ use crate::merge::transfer::TransferMembershipRegister;use crate::stage1::key::LeafStateKey;use crate::stage2::state::Stage2State;use crate::stage2::{CohortEligibility, ExcludedReason};@@ -251,9 +318,9 @@ mod tests {}#[test]- fn orphan_row_for_a_cohort_reclassified_out_of_composable_is_deleted() {+ fn single_leaf_register_is_kept_while_an_absent_cohort_is_deleted() {let (_dir, store) = temp_store();- // Team present, but cohort 1 is now SingleLeaf and cohort 2 absent — both left the composable set.+ // Team present: cohort 1 still registers membership, while cohort 2 is absent.let reclassified = stage2_key(LIVE_TEAM, 1, 100);let deleted_cohort = stage2_key(LIVE_TEAM, 2, 100);put_row(&store, &reclassified);@@ -264,8 +331,8 @@ mod tests {handle_stage2_orphan_gc(PARTITION, &store, &catalog, &mut cursor, NO_CAP);assert!(- !exists(&store, &reclassified),- "a SingleLeaf reclassification leaves the cf_stage2 row an orphan",+ exists(&store, &reclassified),+ "a SingleLeaf row is a live membership register",);assert!(!exists(&store, &deleted_cohort),@@ -417,6 +484,117 @@ mod tests {}}+ #[test]+ fn transferred_register_survives_gc_until_catalog_refresh() {+ let (_dir, store) = temp_store();+ let transferred = stage2_key(ABSENT_TEAM, 17, 100);+ let inventory = Stage2TransferredRegisterKey::new(transferred);+ let state = Stage2State {+ in_cohort: true,+ last_evaluated_at_ms: 1,+ };+ let provenance = TransferredRegisterProvenance::new(+ TransferMembershipRegister {+ cohort_id: 17,+ in_cohort: true,+ kind: TransferMembershipRegisterKind::Composable,+ },+ &state.encode_transferred_fallback(),+ );+ store+ .write_batch(|batch| {+ batch.put_stage2(&transferred, &state.encode_transferred_fallback());+ batch.put_stage2_transferred_register(&inventory, &provenance.encode());+ })+ .unwrap();++ let mut cursor = Stage2GcCursor::default();+ handle_stage2_orphan_gc(PARTITION, &store, &live_team_only(), &mut cursor, NO_CAP);+ assert!(exists(&store, &transferred));+ assert!(store+ .get_stage2_transferred_register(&inventory)+ .unwrap()+ .is_some());++ // A later catalog snapshot recognizes the cohort. The ordinary keep predicate now protects+ // the row and GC retires only the temporary person-first inventory.+ let refreshed = loaded(&[(+ ABSENT_TEAM as i32,+ &[(17, CohortEligibility::Stage2Composable)],+ )]);+ cursor.0 = None;+ handle_stage2_orphan_gc(PARTITION, &store, &refreshed, &mut cursor, NO_CAP);+ assert!(exists(&store, &transferred));+ assert!(store+ .get_stage2_transferred_register(&inventory)+ .unwrap()+ .is_none());+ }++ #[test]+ fn stale_catalog_shape_cannot_retire_wire_inventory() {+ let (_dir, store) = temp_store();+ let transferred = stage2_key(LIVE_TEAM, 17, 100);+ let inventory = Stage2TransferredRegisterKey::new(transferred);+ let transferred_state = Stage2State {+ in_cohort: true,+ last_evaluated_at_ms: 1,+ };+ let provenance = TransferredRegisterProvenance::new(+ TransferMembershipRegister {+ cohort_id: 17,+ in_cohort: true,+ kind: TransferMembershipRegisterKind::SingleLeafBehavioral,+ },+ &transferred_state.encode_transferred_fallback(),+ );+ store+ .write_batch(|batch| {+ batch.put_stage2(+ &transferred,+ &transferred_state.encode_transferred_fallback(),+ );+ batch.put_stage2_transferred_register(&inventory, &provenance.encode());+ })+ .unwrap();+ let stale_shape = loaded(&[(+ LIVE_TEAM as i32,+ &[(17, CohortEligibility::Stage2Composable)],+ )]);+ let mut cursor = Stage2GcCursor::default();++ handle_stage2_orphan_gc(PARTITION, &store, &stale_shape, &mut cursor, NO_CAP);+ assert!(store+ .get_stage2_transferred_register(&inventory)+ .unwrap()+ .is_some());++ // A later normal evaluation write supersedes the exact fallback fingerprint. GC can retire+ // the provenance without adding a second write to the evaluation hot path.+ store+ .write_batch(|batch| {+ batch.put_stage2(+ &transferred,+ &Stage2State {+ in_cohort: false,+ last_evaluated_at_ms: 2,+ }+ .encode(),+ );+ })+ .unwrap();+ assert!(store+ .get_stage2_transferred_register(&inventory)+ .unwrap()+ .is_some());+ cursor.0 = None;+ handle_stage2_orphan_gc(PARTITION, &store, &stale_shape, &mut cursor, NO_CAP);+ assert!(store+ .get_stage2_transferred_register(&inventory)+ .unwrap()+ .is_none());+ }+#[test]fn undecodable_or_impossible_key_is_left_in_place() {let (_dir, store) = temp_store();@@ -476,10 +654,10 @@ mod tests {is_orphan(&catalog, &stage2_key(LIVE_TEAM, 2, 0)),Some(false));- // SingleLeaf / Excluded no longer write cf_stage2 → orphan.+ // SingleLeaf registers membership; Excluded persists no row.assert_eq!(is_orphan(&catalog, &stage2_key(LIVE_TEAM, 3, 0)),- Some(true)+ Some(false));assert_eq!(is_orphan(&catalog, &stage2_key(LIVE_TEAM, 4, 0)),diff --git a/rust/cohort-stream-processor/src/workers/stage2_path.rs b/rust/cohort-stream-processor/src/workers/stage2_path.rsindex 04fc9d8a5607..5bb87c5d2e70 100644--- a/rust/cohort-stream-processor/src/workers/stage2_path.rs+++ b/rust/cohort-stream-processor/src/workers/stage2_path.rs@@ -21,7 +21,7 @@ use crate::stage1::key::LeafStateKey;use crate::stage1::person_record::PersonRecord;use crate::stage1::state::{Stage1State, StateVariant, StatefulRecord};use crate::stage2::evaluator::{evaluate_tree, leaf_membership};-use crate::stage2::state::Stage2State;+use crate::stage2::state::{Stage2Ownership, Stage2State};use crate::stage2::CohortEligibility;use crate::store::{BehavioralKey, PersonRecordKey, ReadLane, Stage2Key, StagedBatch, StoreError, StoreHandle,@@ -102,27 +102,28 @@ pub(crate) async fn recompute_stage2(let diff = recompute_and_diff(partition_id, person_id, tree, filters, handle, lane).await?;evaluated += 1;- if !diff.flipped() {- continue;+ if diff.flipped() {+ changes.push(CohortMembershipChange {+ team_id: tree.team_id.0,+ cohort_id: cohort_id.0,+ person_id: person_id.to_string(),+ last_updated: last_updated.to_string(),+ status: diff.status(),+ origin: None,+ run_id: None,+ });+ }+ if diff.requires_write() {+ // Write `false` rather than deleting so absence means "never evaluated". A no-flip+ // transferred fallback is rewritten once so receiver evaluation claims ownership.+ writes.push((+ diff.stage2_key,+ Stage2State {+ in_cohort: diff.new_bit,+ last_evaluated_at_ms: event_ms,+ },+ ));}-- changes.push(CohortMembershipChange {- team_id: tree.team_id.0,- cohort_id: cohort_id.0,- person_id: person_id.to_string(),- last_updated: last_updated.to_string(),- status: diff.status(),- origin: None,- run_id: None,- });- // Write `false` rather than deleting so absence means "never evaluated".- writes.push((- diff.stage2_key,- Stage2State {- in_cohort: diff.new_bit,- last_evaluated_at_ms: event_ms,- },- ));}Ok(Stage2Recompute {@@ -153,6 +154,7 @@ pub(crate) struct RecomputeDiff {pub new_bit: bool,pub prior_bit: bool,pub stage2_key: Stage2Key,+ settles_transfer_fallback: bool,}impl RecomputeDiff {@@ -167,6 +169,12 @@ impl RecomputeDiff {MembershipStatus::Left}}++ /// A receiver evaluation must rewrite a transferred fallback even when the logical bit is+ /// unchanged, making source provenance observably stale without touching ordinary no-flip rows.+ pub fn requires_write(&self) -> bool {+ self.flipped() || self.settles_transfer_fallback+ }}/// Recompute one cohort's membership and diff against the stored `cf_stage2` bit. Reads only — the@@ -196,11 +204,12 @@ pub(crate) async fn recompute_and_diff(cohort_id: tree.cohort_id.0 as u64,person_id,};- let prior_bit = read_stage2_bit(handle, &stage2_key, lane).await?;+ let prior = read_prior_stage2_state(handle, &stage2_key, lane).await?;Ok(RecomputeDiff {new_bit,- prior_bit,+ prior_bit: prior.in_cohort,stage2_key,+ settles_transfer_fallback: prior.ownership == Stage2Ownership::TransferredFallback,})}@@ -433,13 +442,37 @@ fn decode_stage1_state(bytes: Option<Vec<u8>>) -> Option<Stage1State> {}}-/// The stored `cf_stage2` membership bit for `key`, `false` when absent or undecodable.-async fn read_stage2_bit(+struct PriorStage2State {+ in_cohort: bool,+ ownership: Stage2Ownership,+}++/// Decode both the logical prior bit and its ownership. Missing or corrupt rows keep the existing+/// fail-closed `false` behavior and are never mistaken for a transferred fallback.+async fn read_prior_stage2_state(handle: &StoreHandle,key: &Stage2Key,lane: ReadLane,-) -> Result<bool, StoreError> {- Ok(decode_stage2_bit(handle.get_stage2(key, lane).await?))+) -> Result<PriorStage2State, StoreError> {+ let Some(bytes) = handle.get_stage2(key, lane).await? else {+ return Ok(PriorStage2State {+ in_cohort: false,+ ownership: Stage2Ownership::Local,+ });+ };+ match Stage2State::decode_with_ownership(&bytes) {+ Ok((state, ownership)) => Ok(PriorStage2State {+ in_cohort: state.in_cohort,+ ownership,+ }),+ Err(_) => {+ counter!(STAGE2_STATE_DECODE_ERROR).increment(1);+ Ok(PriorStage2State {+ in_cohort: false,+ ownership: Stage2Ownership::Local,+ })+ }+ }}/// Decode a `cf_stage2` value into its membership bit, `false` when absent or undecodable.@@ -814,6 +847,18 @@ mod tests {.await.unwrap();assert_eq!(first.len(), 1, "the first evaluation enters");+ let key = Stage2Key {+ partition_id: PARTITION,+ team_id: TEAM,+ cohort_id: 1,+ person_id: alice,+ };+ let current = Stage2State::decode(&store.get_stage2(&key).unwrap().unwrap()).unwrap();+ store+ .write_batch(|batch| {+ batch.put_stage2(&key, ¤t.encode_transferred_fallback());+ })+ .unwrap();let second = compose_stage2(PARTITION,@@ -830,6 +875,12 @@ mod tests {second.is_empty(),"a re-evaluation with no change emits nothing");+ let bytes = store.get_stage2(&key).unwrap().unwrap();+ assert_eq!(+ Stage2State::decode_with_ownership(&bytes).unwrap().1,+ Stage2Ownership::Local,+ "the no-op evaluation still claims a transferred fallback",+ );}#[tokio::test]diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rsindex 9581ff9e3448..bc4fbcef7baa 100644--- a/rust/cohort-stream-processor/src/workers/worker.rs+++ b/rust/cohort-stream-processor/src/workers/worker.rs@@ -38,6 +38,7 @@ use crate::producer::{use crate::stage1::key::LeafStateKey;use crate::stage1::state::{StateVariant, StatefulRecord};use crate::stage1::transition::{LeafTransition, TransitionKind};+use crate::stage2::{single_leaf_transition_register_writes, stage_register_writes};use crate::store::{Behavioral, BehavioralKey, ReadLane, StagedBatch, StoreHandle};use crate::sweep::EvictionQueue;use crate::workers::cascade_path::handle_cascade;@@ -808,6 +809,19 @@ async fn handle_sweep(EvictionAction::Write(bytes) => staged.put::<Behavioral>(&result.key, bytes),EvictionAction::Delete => staged.delete::<Behavioral>(&result.key),}+ if let Some(transition) = &result.transition {+ if let Some(filters) = snapshot.team(transition.team_id) {+ stage_register_writes(+ &mut staged,+ single_leaf_transition_register_writes(+ filters,+ partition_id,+ transition,+ due_before_ms,+ ),+ );+ }+ }}let written = handle.commit(staged).await;if let Err(error) = written {@@ -1126,6 +1140,7 @@ mod tombstone_redirect_tests {seed_tile_sink: Arc::new(crate::producer::CaptureSeedTileSink::new()),seed_tracker: Arc::new(crate::partitions::offset_tracker::OffsetTracker::new()),live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),+ register_transfer_enabled: false,})}@@ -1146,6 +1161,7 @@ mod tombstone_redirect_tests {seed_tile_sink: Arc::new(crate::producer::CaptureSeedTileSink::new()),seed_tracker: Arc::new(crate::partitions::offset_tracker::OffsetTracker::new()),live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),+ register_transfer_enabled: false,})}@@ -1170,6 +1186,7 @@ mod tombstone_redirect_tests {seed_tile_sink: Arc::new(crate::producer::CaptureSeedTileSink::new()),seed_tracker: Arc::new(crate::partitions::offset_tracker::OffsetTracker::new()),live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),+ register_transfer_enabled: false,})}@@ -1764,7 +1781,7 @@ mod tombstone_redirect_tests {}/// The `MergeCfGc` arm runs the `cf_stage2` orphan GC only when `stage2_orphan_gc_enabled`: a- /// SingleLeaf cohort's row (an orphan) survives with the kill-switch off and is reclaimed with it on.+ /// catalog-absent cohort's row survives with the kill-switch off and is reclaimed with it on.#[tokio::test]async fn merge_cf_gc_arm_runs_stage2_orphan_gc_only_when_enabled() {for (enabled, expect_present) in [(false, true), (true, false)] {@@ -1774,7 +1791,7 @@ mod tombstone_redirect_tests {let orphan = Stage2Key {partition_id,team_id: TEAM as u64,- cohort_id: 1, // SingleLeaf in person_catalog → an orphan+ cohort_id: 99,person_id: person,};storediff --git a/rust/cohort-stream-processor/tests/cascade_consumer.rs b/rust/cohort-stream-processor/tests/cascade_consumer.rsindex 8c202d0f2c16..5cfa10a3160d 100644--- a/rust/cohort-stream-processor/tests/cascade_consumer.rs+++ b/rust/cohort-stream-processor/tests/cascade_consumer.rs@@ -465,6 +465,7 @@ async fn spawn_instance(live_watermarks: Arc::new(cohort_stream_processor::partitions::watermarks::LiveWatermarks::new(),),+ register_transfer_enabled: false,});let dispatcher = Arc::new(EventDispatcher::new(diff --git a/rust/cohort-stream-processor/tests/merge_consumer.rs b/rust/cohort-stream-processor/tests/merge_consumer.rsindex d6ba7f22e974..afeaffa53224 100644--- a/rust/cohort-stream-processor/tests/merge_consumer.rs+++ b/rust/cohort-stream-processor/tests/merge_consumer.rs@@ -621,6 +621,7 @@ async fn spawn_instance(live_watermarks: Arc::new(cohort_stream_processor::partitions::watermarks::LiveWatermarks::new(),),+ register_transfer_enabled: false,});let dispatcher = Arc::new(EventDispatcher::new(@@ -768,6 +769,7 @@ async fn keyed_produces_agree_with_partition_of_live() {source_partition: 0,source_offset: n as i64,leaves: vec![],+ membership_registers: vec![],forward_hops: 0,person_dedup: None,})diff --git a/rust/cohort-stream-processor/tests/merge_durability.rs b/rust/cohort-stream-processor/tests/merge_durability.rsindex ee9d39703828..203a2cf1322a 100644--- a/rust/cohort-stream-processor/tests/merge_durability.rs+++ b/rust/cohort-stream-processor/tests/merge_durability.rs@@ -719,6 +719,7 @@ async fn spawn_instance(live_watermarks: Arc::new(cohort_stream_processor::partitions::watermarks::LiveWatermarks::new(),),+ register_transfer_enabled: false,});let dispatcher = Arc::new(EventDispatcher::new(diff --git a/rust/cohort-stream-processor/tests/merge_protocol.rs b/rust/cohort-stream-processor/tests/merge_protocol.rsindex 90973970333a..04c57ebbfe9a 100644--- a/rust/cohort-stream-processor/tests/merge_protocol.rs+++ b/rust/cohort-stream-processor/tests/merge_protocol.rs@@ -18,7 +18,8 @@ use cohort_stream_processor::merge::apply_handler::{use cohort_stream_processor::merge::drain_handler::{handle_merge_event, DrainOutcome};use cohort_stream_processor::merge::tombstone_redirect::{resolve, Resolution};use cohort_stream_processor::merge::transfer::{- MergeStateTransfer, PendingTransfer, PersonMergeEvent, Tombstone, MERGE_EVENT_SCHEMA_VERSION,+ MergeStateTransfer, PendingTransfer, PersonMergeEvent, Tombstone, TransferMembershipRegister,+ TransferMembershipRegisterKind, MERGE_EVENT_SCHEMA_VERSION,};use cohort_stream_processor::partitions::{partition_of, COHORT_PARTITION_COUNT};use cohort_stream_processor::producer::{now_last_updated, MembershipStatus};@@ -132,6 +133,14 @@ fn build_filters() -> TeamFilters {builder.freeze(UTC)}+fn false_single_leaf_filters() -> TeamFilters {+ let mut builder = TeamFiltersBuilder::default();+ builder+ .add_cohort(CohortId(1), TeamId(TEAM), &cohort(vec![daily_leaf()]))+ .unwrap();+ builder.freeze(UTC)+}+fn pageview_event(person: Uuid, source_partition: i32, source_offset: i64) -> CohortStreamEvent {CohortStreamEvent {team_id: TEAM,@@ -262,6 +271,357 @@ fn behavioral_states()}+fn membership_register_key(partition_id: u16, cohort_id: u64, person: Uuid) -> Stage2Key {+ Stage2Key {+ partition_id,+ team_id: TEAM as u64,+ cohort_id,+ person_id: person,+ }+}++fn membership_register_bit(+ store: &CohortStore,+ partition_id: u16,+ cohort_id: u64,+ person: Uuid,+) -> Option<bool> {+ store+ .get_stage2(&membership_register_key(partition_id, cohort_id, person))+ .unwrap()+ .map(|bytes| Stage2State::decode(&bytes).unwrap().in_cohort)+}++fn put_membership_register(+ store: &CohortStore,+ partition_id: u16,+ cohort_id: u64,+ person: Uuid,+ in_cohort: bool,+) {+ store+ .write_batch(|batch| {+ batch.put_stage2(+ &membership_register_key(partition_id, cohort_id, person),+ &Stage2State {+ in_cohort,+ last_evaluated_at_ms: 1,+ }+ .encode(),+ )+ })+ .unwrap();+}++#[test]+fn merge_preserves_a_false_single_leaf_register_with_or_without_leaf_state() {+ for same_partition in [false, true] {+ for leaf_state_present in [false, true] {+ let dir = TempDir::new().unwrap();+ let store = temp_store_in(&dir);+ let filters = false_single_leaf_filters();+ let p_old = Uuid::from_u128(0xA11CE);+ let p_old_part = part(p_old);+ let p_new = if same_partition {+ person_on(p_old_part)+ } else {+ person_not_on(p_old_part)+ };+ let p_new_part = part(p_new);++ if leaf_state_present {+ fold_pageview(&store, &filters, p_old_part, p_old, 10, 0);+ }+ put_membership_register(&store, p_old_part, 1, p_old, false);++ let drained = handle_merge_event(+ p_old_part,+ &store,+ &filters,+ &merge_event(p_old, p_new),+ (5, 100),+ COHORT_PARTITION_COUNT,+ )+ .unwrap();+ match drained {+ DrainOutcome::FastPath { .. } if same_partition => {}+ DrainOutcome::Drained { transfer, .. } if !same_partition => {+ assert_eq!(+ transfer.membership_registers,+ vec![TransferMembershipRegister {+ cohort_id: 1,+ in_cohort: false,+ kind: TransferMembershipRegisterKind::SingleLeafBehavioral,+ }],+ );+ assert!(matches!(+ handle_transfer(+ p_new_part,+ &store,+ &filters,+ &transfer,+ (5, 7),+ COHORT_PARTITION_COUNT,+ )+ .unwrap(),+ ApplyOutcome::Applied { .. }+ ));+ }+ other => {+ panic!("unexpected merge path (same_partition={same_partition}): {other:?}")+ }+ }++ assert_eq!(+ membership_register_bit(&store, p_old_part, 1, p_old),+ None,+ "the merged-away identity is reclaimed",+ );+ assert_eq!(+ membership_register_bit(&store, p_new_part, 1, p_new),+ Some(false),+ "the survivor stays in the reconcile scan domain (same_partition={same_partition}, leaf_state_present={leaf_state_present})",+ );+ assert_eq!(+ leaf_state(+ &store,+ p_new_part,+ lsk_of(&filters, StateVariant::BehavioralDailyBuckets),+ p_new,+ )+ .is_some(),+ leaf_state_present,+ );+ }+ }+}++#[test]+fn cross_partition_catalog_edit_preserves_the_register_scan_domain() {+ let dir = TempDir::new().unwrap();+ let store = temp_store_in(&dir);+ let source_filters = false_single_leaf_filters();+ let mut target_builder = TeamFiltersBuilder::default();+ target_builder+ .add_cohort(CohortId(1), TeamId(TEAM), &cohort(vec![single_leaf()]))+ .unwrap();+ let target_filters = target_builder.freeze(UTC);+ 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_pageview(&store, &source_filters, p_old_part, p_old, 10, 0);+ put_membership_register(&store, p_old_part, 1, p_old, false);++ let transfer = match handle_merge_event(+ p_old_part,+ &store,+ &source_filters,+ &merge_event(p_old, p_new),+ (5, 100),+ COHORT_PARTITION_COUNT,+ )+ .unwrap()+ {+ DrainOutcome::Drained { transfer, .. } => transfer,+ other => panic!("expected a cross-partition transfer, got {other:?}"),+ };+ assert_eq!(+ transfer.membership_registers,+ vec![TransferMembershipRegister {+ cohort_id: 1,+ in_cohort: false,+ kind: TransferMembershipRegisterKind::SingleLeafBehavioral,+ }],+ );++ assert!(matches!(+ handle_transfer(+ p_new_part,+ &store,+ &target_filters,+ &transfer,+ (5, 7),+ COHORT_PARTITION_COUNT,+ )+ .unwrap(),+ ApplyOutcome::Applied { .. }+ ));+ assert_eq!(+ membership_register_bit(&store, p_new_part, 1, p_new),+ Some(false),+ "the transfer fallback keeps the survivor scannable across a single-leaf LSK edit",+ );+}++#[test]+fn cross_partition_single_leaf_to_composable_edit_materializes_a_false_sentinel() {+ let dir = TempDir::new().unwrap();+ let store = temp_store_in(&dir);+ let source_filters = false_single_leaf_filters();+ let mut target_builder = TeamFiltersBuilder::default();+ target_builder+ .add_cohort(+ CohortId(1),+ TeamId(TEAM),+ &cohort(vec![single_leaf(), compressed_leaf()]),+ )+ .unwrap();+ let target_filters = target_builder.freeze(UTC);+ 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);++ put_membership_register(&store, p_old_part, 1, p_old, true);+ let transfer = match handle_merge_event(+ p_old_part,+ &store,+ &source_filters,+ &merge_event(p_old, p_new),+ (5, 100),+ COHORT_PARTITION_COUNT,+ )+ .unwrap()+ {+ DrainOutcome::Drained { transfer, .. } => transfer,+ other => panic!("expected a cross-partition transfer, got {other:?}"),+ };+ assert_eq!(+ transfer.membership_registers,+ vec![TransferMembershipRegister {+ cohort_id: 1,+ in_cohort: true,+ kind: TransferMembershipRegisterKind::SingleLeafBehavioral,+ }],+ );++ assert!(matches!(+ handle_transfer(+ p_new_part,+ &store,+ &target_filters,+ &transfer,+ (5, 7),+ COHORT_PARTITION_COUNT,+ )+ .unwrap(),+ ApplyOutcome::Applied { .. }+ ));+ assert_eq!(+ membership_register_bit(&store, p_new_part, 1, p_new),+ Some(false),+ "a newly composable row gains scan presence without changing its absent-is-false semantics",+ );+}++#[test]+fn cross_partition_merge_preserves_a_composable_false_row_without_leaf_state() {+ let dir = TempDir::new().unwrap();+ let store = temp_store_in(&dir);+ let mut builder = TeamFiltersBuilder::default();+ builder+ .add_cohort(+ CohortId(1),+ TeamId(TEAM),+ &cohort(vec![single_leaf(), compressed_leaf()]),+ )+ .unwrap();+ let filters = builder.freeze(UTC);+ 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);++ put_membership_register(&store, p_old_part, 1, p_old, false);+ let transfer = match handle_merge_event(+ p_old_part,+ &store,+ &filters,+ &merge_event(p_old, p_new),+ (5, 100),+ COHORT_PARTITION_COUNT,+ )+ .unwrap()+ {+ DrainOutcome::Drained { transfer, .. } => transfer,+ other => panic!("expected a cross-partition transfer, got {other:?}"),+ };++ assert!(matches!(+ handle_transfer(+ p_new_part,+ &store,+ &filters,+ &transfer,+ (5, 7),+ COHORT_PARTITION_COUNT,+ )+ .unwrap(),+ ApplyOutcome::Applied { .. }+ ));+ assert_eq!(+ membership_register_bit(&store, p_new_part, 1, p_new),+ Some(false),+ "the existing composable scan domain follows the survivor even without leaf transitions",+ );+}++#[test]+fn cross_partition_merge_preserves_the_domain_of_a_corrupt_register_row() {+ let dir = TempDir::new().unwrap();+ let store = temp_store_in(&dir);+ let filters = false_single_leaf_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);+ store+ .write_batch(|batch| {+ batch.put_stage2(&membership_register_key(p_old_part, 1, p_old), b"corrupt")+ })+ .unwrap();++ let transfer = match handle_merge_event(+ p_old_part,+ &store,+ &filters,+ &merge_event(p_old, p_new),+ (5, 100),+ COHORT_PARTITION_COUNT,+ )+ .unwrap()+ {+ DrainOutcome::Drained { transfer, .. } => transfer,+ other => panic!("expected a cross-partition transfer, got {other:?}"),+ };+ assert_eq!(+ transfer.membership_registers,+ vec![TransferMembershipRegister {+ cohort_id: 1,+ in_cohort: false,+ kind: TransferMembershipRegisterKind::SingleLeafBehavioral,+ }],+ );+ assert!(matches!(+ handle_transfer(+ p_new_part,+ &store,+ &filters,+ &transfer,+ (5, 7),+ COHORT_PARTITION_COUNT,+ )+ .unwrap(),+ ApplyOutcome::Applied { .. }+ ));+ assert_eq!(+ membership_register_bit(&store, p_new_part, 1, p_new),+ Some(false),+ );+}+#[test]fn cross_partition_drain_transfer_apply_merges_all_variants_and_matches_the_oracle() {let dir = TempDir::new().unwrap();@@ -279,6 +639,10 @@ fn cross_partition_drain_transfer_apply_merges_all_variants_and_matches_the_oracfold_pageview(&store, &filters, p_old_part, p_old, 10, 0);fold_pageview(&store, &filters, p_new_part, p_new, 20, 0);+ // Model the complete seed-created register domain: these leaves have state but are not members+ // until old and survivor state are combined by the merge.+ put_membership_register(&store, p_old_part, 2, p_old, false);+ put_membership_register(&store, p_old_part, 3, p_old, false);let drained = handle_merge_event(p_old_part,@@ -299,6 +663,13 @@ fn cross_partition_drain_transfer_apply_merges_all_variants_and_matches_the_oracs.is_none() && d.is_none() && c.is_none(),"P_old's state was drained");+ for cohort_id in 1..=3 {+ assert_eq!(+ membership_register_bit(&store, p_old_part, cohort_id, p_old),+ None,+ "drain removes P_old's single-leaf register for cohort {cohort_id}",+ );+ }assert!(store.get_tombstone(&TombstoneKey {partition_id: p_old_part,@@ -337,6 +708,13 @@ fn cross_partition_drain_transfer_apply_merges_all_variants_and_matches_the_orac"daily summed across both persons");assert_eq!(compressed_sum(&compressed.clone().unwrap()), 2);+ for cohort_id in 1..=3 {+ assert_eq!(+ membership_register_bit(&store, p_new_part, cohort_id, p_new),+ Some(true),+ "apply aligns the survivor's single-leaf register for cohort {cohort_id}",+ );+ }// Oracle: a person that received both events from the start, keyed to P_new's partition.let oracle = Uuid::from_u128(0xABCDE);@@ -541,6 +919,8 @@ fn fast_path_equals_the_cross_partition_result() {fold_pageview(&store, &filters, p_old_part, p_old, 10, 0);fold_pageview(&store, &filters, p_old_part, p_new, 20, 0);+ put_membership_register(&store, p_old_part, 2, p_old, false);+ put_membership_register(&store, p_old_part, 3, p_old, false);let outcome = handle_merge_event(p_old_part,@@ -573,6 +953,13 @@ fn fast_path_equals_the_cross_partition_result() {let (s, d, c) = behavioral_states(&store, &filters, p_old_part, p_old);assert!(s.is_none() && d.is_none() && c.is_none());+ for cohort_id in 1..=3 {+ assert_eq!(+ membership_register_bit(&store, p_old_part, cohort_id, p_old),+ None,+ "fast-path drain removes P_old's register for cohort {cohort_id}",+ );+ }let (single, daily, compressed) = behavioral_states(&store, &filters, p_old_part, p_new);assert!(matches!(single,@@ -583,6 +970,13 @@ fn fast_path_equals_the_cross_partition_result() {));assert_eq!(daily_sum(&daily.unwrap()), 2);assert_eq!(compressed_sum(&compressed.unwrap()), 2);+ for cohort_id in 1..=3 {+ assert_eq!(+ membership_register_bit(&store, p_old_part, cohort_id, p_new),+ Some(true),+ "fast-path apply aligns P_new's register for cohort {cohort_id}",+ );+ }}#[test]diff --git a/rust/cohort-stream-processor/tests/seed_consumer.rs b/rust/cohort-stream-processor/tests/seed_consumer.rsindex eca4403b1f85..39451beaf654 100644--- a/rust/cohort-stream-processor/tests/seed_consumer.rs+++ b/rust/cohort-stream-processor/tests/seed_consumer.rs@@ -495,6 +495,7 @@ async fn spawn_instance(seed_tile_sink,seed_tracker: Arc::new(OffsetTracker::new()),live_watermarks: Arc::new(LiveWatermarks::new()),+ register_transfer_enabled: false,});let dispatcher = Arc::new(EventDispatcher::new(diff --git a/rust/cohort-stream-processor/tests/stage1_worker.rs b/rust/cohort-stream-processor/tests/stage1_worker.rsindex 46e7ce404b30..72aef2e34f75 100644--- a/rust/cohort-stream-processor/tests/stage1_worker.rs+++ b/rust/cohort-stream-processor/tests/stage1_worker.rs@@ -27,9 +27,10 @@ use cohort_stream_processor::stage1::{clickhouse_timestamp_to_millis, AppliedOffsets, LeafTransition, Stage1State, StateVariant,StatefulRecord, TransitionKind,};+use cohort_stream_processor::stage2::Stage2State;use cohort_stream_processor::store::{Behavioral, BehavioralKey, CohortStore, LeafStateKey, OffloadConfig, OffloadMode, PersonPrefix,- PersonRecordKey, PersonRecords, StoreConfig, StoreHandle,+ PersonRecordKey, PersonRecords, Stage2Key, StoreConfig, StoreHandle,};use cohort_stream_processor::workers::{process_event, MergeWorkerDeps, SkipReason, Stage1Worker};use serde_json::{json, Value};@@ -250,6 +251,22 @@ fn state_at(store: &CohortStore, lsk: LeafStateKey, person: Uuid) -> Option<Stagrecord_at(store, lsk, person).map(|record| record.state)}+fn membership_register_at(+ store: &CohortStore,+ cohort_id: u64,+ person: Uuid,+) -> Option<Stage2State> {+ store+ .get_stage2(&Stage2Key {+ partition_id: PARTITION_ID,+ team_id: TEAM as u64,+ cohort_id,+ person_id: person,+ })+ .unwrap()+ .map(|bytes| Stage2State::decode(&bytes).unwrap())+}+/// The full persisted record (state + per-source-partition applied offsets), for the cross-partition/// replay-dedup assertions.fn record_at(store: &CohortStore, lsk: LeafStateKey, person: Uuid) -> Option<StatefulRecord> {@@ -1360,6 +1377,14 @@ async fn worker_produces_changes_and_advances_offset() {assert_eq!(changes[0].cohort_id, 1);assert_eq!(changes[0].status, MembershipStatus::Entered);assert_eq!(changes[0].person_id, person(1).to_string());+ assert_eq!(+ membership_register_at(&store, 1, person(1)),+ Some(Stage2State {+ in_cohort: true,+ last_evaluated_at_ms: clickhouse_timestamp_to_millis(BASE_TS).unwrap(),+ }),+ "the event commit atomically materializes the single-leaf membership register",+ );}#[tokio::test]@@ -1913,6 +1938,15 @@ async fn daily_multiple_single_leaf_cohort_emits_entered_then_left_to_the_sink()assert_eq!(changes[0].status, MembershipStatus::Entered);assert_eq!(changes[0].person_id, alice.to_string());assert_eq!(changes[1].status, MembershipStatus::Left);+ assert_eq!(+ membership_register_at(&store, 1, alice),+ Some(Stage2State {+ in_cohort: false,+ last_evaluated_at_ms: clickhouse_timestamp_to_millis("2026-05-28 10:00:00.000000")+ .unwrap(),+ }),+ "a live-event Left persists an explicit false register row",+ );assert_eq!(tracker.committable_offsets().get(&(PARTITION_ID as i32)),Some(&4),diff --git a/rust/cohort-stream-processor/tests/sweep_worker.rs b/rust/cohort-stream-processor/tests/sweep_worker.rsindex b4bd26a190cd..97541d8751dc 100644--- a/rust/cohort-stream-processor/tests/sweep_worker.rs+++ b/rust/cohort-stream-processor/tests/sweep_worker.rs@@ -376,6 +376,11 @@ async fn sweep_evicts_a_single_leaf_member_emits_left_and_deletes() {state_at(&store, lsk, alice).is_none(),"a fully-expired single is deleted",);+ assert_eq!(+ stage2_bit(&store, 1, alice),+ Some(false),+ "the sweep commit retains an explicit false membership register after deleting leaf state",+ );}#[tokio::test]