: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
fix(cohorts): re-emit a seed's lost membership change on redelivery (#94548)
Matheus Batista585174b707af
diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rsindex cec4eda0c17e..b0e759404db3 100644--- a/rust/cohort-stream-processor/src/config.rs+++ b/rust/cohort-stream-processor/src/config.rs@@ -816,14 +816,16 @@ impl Config {);}- // A membership produce that fails after stage 1 commits drops the single-leaf change: the- // replayed seed merges to Unchanged and re-emits only composed flips. The reconcile- // snapshot is what repairs that, and it can, because the register row committed with- // stage 1 — but only if it is switched on.+ // Seed redelivery repairs failed produces only when the register preserves the retired+ // value. Legacy seed writers stored truth before producing, so a held seed replayed across+ // that writer change can read an agreeing row and emit nothing. Reconcile must cover those+ // deliveries, cohort edits, and live/merge produces whose state already committed.if self.cohort_seed_person_apply_enabled && !self.cohort_seed_reconcile_enabled {warn!(- "COHORT_SEED_PERSON_APPLY_ENABLED without COHORT_SEED_RECONCILE_ENABLED: a failed \- membership produce drops its single-leaf change permanently, with no repair path.",+ "COHORT_SEED_PERSON_APPLY_ENABLED without COHORT_SEED_RECONCILE_ENABLED: a live \+ event that fails its produce, a cohort edited mid-run, and a merge apply that \+ fails its produce have no repair path. Failed deliveries from seed writers \+ that stored truth before producing also require reconcile.",);}diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rsindex ede4684f62dd..9b329336a032 100644--- a/rust/cohort-stream-processor/src/observability/metrics.rs+++ b/rust/cohort-stream-processor/src/observability/metrics.rs@@ -516,6 +516,16 @@ pub const PERSON_SEED_REKEY_HOP_CAPPED_TOTAL: &str = "cohort_person_seeds_rekey_/// Failed person-seed re-key produces; the seed offset is held (counter).pub const PERSON_SEED_REKEY_PRODUCE_FAILURE_TOTAL: &str ="cohort_person_seeds_rekey_produce_failure_total";+/// Single-leaf membership changes a seed apply derived from the persisted register with no stage-1+/// transition behind them, labelled by `kind` (`entered`|`left`) and `found`, which names what the+/// row held rather than why (counter). `absent`: no row, a register that predates the apply, such+/// as a cohort added over existing leaf state; expect these in bulk through the first full run+/// after a roll. `corrupt`: a row that did not decode, also counted on+/// [`STAGE2_STATE_DECODE_ERROR`]. `mismatch`: a row that disagreed with the truth.+/// **A `mismatch` rate has more than one cause — a redelivery repairing a failed produce, an+/// edited cohort whose leaf key moved, a transferred fallback row — so read it against the seed+/// produce-failure counters before concluding produces are failing.**+pub const SEED_REGISTER_REPAIRS_TOTAL: &str = "cohort_seed_register_repairs_total";/// The seed commit floor pinned by a sticky offset hold, labelled by `partition` (gauge)./// **Alert on a sustained non-zero level.**pub const SEED_HELD_OFFSET_GAUGE: &str = "seed_held_offset";@@ -879,6 +889,10 @@ mod tests {PERSON_SEED_REKEY_PRODUCE_FAILURE_TOTAL,"cohort_person_seeds_rekey_produce_failure_total",);+ assert_eq!(+ SEED_REGISTER_REPAIRS_TOTAL,+ "cohort_seed_register_repairs_total"+ );// The held-offset gauge deliberately mirrors merge_held_offset/cascade_held_offset.assert_eq!(SEED_HELD_OFFSET_GAUGE, "seed_held_offset");assert_eq!(SEED_FENCED_PARTITIONS, "cohort_seed_fenced_partitions");diff --git a/rust/cohort-stream-processor/src/stage2/state.rs b/rust/cohort-stream-processor/src/stage2/state.rsindex ab3e76fdb281..41c90b1f6db0 100644--- a/rust/cohort-stream-processor/src/stage2/state.rs+++ b/rust/cohort-stream-processor/src/stage2/state.rs@@ -6,6 +6,33 @@ use serde::{Deserialize, Serialize};/// when that was last evaluated. Single-leaf cohorts write this directly from their leaf state;/// composable cohorts write it after Boolean composition.///+/// # What the bit means, per writer+///+/// Absence means **no registered membership**, and composes as `false`; it does not mean the pair+/// was never evaluated. Flip-based writers can leave an initial non-member absent, while merge+/// writers register every leaf they put, including non-members. Retractions write an explicit+/// `false` rather than deleting the row.+///+/// The two seed paths ([`handle_seed`](crate::workers::seed_path) and the person-seed apply) hold a+/// stricter meaning: the bit is **what downstream was last told**. Before every emission they+/// record, with stage 1, the value that emission retires, so a produce that fails after stage 1+/// commits leaves the row disagreeing with the truth and the redelivery re-emits. A row that agrees+/// with the truth never vetoes a transition minted in the same apply: it can be that pre-write, or+/// the row an apply left behind when it acked and then held before its post-ack commit. A silent+/// apply leaves an absent row absent, but replaces a corrupt row with a readable `false`.+///+/// Every other writer (the live event path, the sweep, the merge apply, the cascade apply,+/// reconcile) writes the bit as **recomputed stage-1 truth**. A seed apply trusts such a row even+/// when its writer committed before a failed produce. This also applies to legacy seed writers+/// that stored truth before producing; reconcile repairs those deliveries. See `handle_sweep` for+/// why the sweep must derive retractions from transitions even over an agreeing register.+///+/// When a row commits is a separate axis from what it records. The live event path and the merge+/// apply commit with stage 1 and produce after. The single-leaf sweep commits after its produce+/// acks and reschedules failed keys; its composed leg commits before producing. Cascade apply,+/// reconcile, and the seed paths' post-ack write commit after acknowledgments, retrying their+/// respective message, page, or seed apply.+////// `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.diff --git a/rust/cohort-stream-processor/src/store/keys.rs b/rust/cohort-stream-processor/src/store/keys.rsindex 7ee61defe88c..4e136f839b78 100644--- a/rust/cohort-stream-processor/src/store/keys.rs+++ b/rust/cohort-stream-processor/src/store/keys.rs@@ -34,7 +34,9 @@ pub const MERGE_APPLIED_KEY_LEN: usize = 2 + 8 + 16 + 4 + 8;pub const TOMBSTONE_KEY_LEN: usize = 2 + 8 + 16;/// `cf_stage2` key: per-`(cohort, person)` membership state.-#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]+///+/// Derives `Ord` so the register diff can collect keys in a deterministic order.+#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]pub struct Stage2Key {pub partition_id: u16,pub team_id: u64,diff --git a/rust/cohort-stream-processor/src/store/rocks.rs b/rust/cohort-stream-processor/src/store/rocks.rsindex b8452167e33d..b12acf9ba0b8 100644--- a/rust/cohort-stream-processor/src/store/rocks.rs+++ b/rust/cohort-stream-processor/src/store/rocks.rs@@ -181,6 +181,16 @@ pub enum StoreError {)]SchemaMismatch { found: Option<u32>, expected: u32 },+ /// A batched read answered fewer slots than it was asked keys. RocksDB answers one slot per+ /// key, so this is a backend contract break rather than a data problem, and pairing a slot+ /// with the wrong key would attribute one person's stored state to another.+ #[error("{op}: batched read answered {answered} of {asked} keys")]+ ShortRead {+ op: &'static str,+ asked: usize,+ answered: usize,+ },+#[error("store offload cancelled by runtime shutdown")]OffloadCancelled,}diff --git a/rust/cohort-stream-processor/src/workers/person_seed_path.rs b/rust/cohort-stream-processor/src/workers/person_seed_path.rsindex efbdae444783..efd7732c8e35 100644--- a/rust/cohort-stream-processor/src/workers/person_seed_path.rs+++ b/rust/cohort-stream-processor/src/workers/person_seed_path.rs@@ -24,9 +24,9 @@ use crate::observability::metrics::{PERSON_SEEDS_APPLIED_TOTAL, PERSON_SEEDS_DROPPED_TOTAL, PERSON_SEEDS_SKIPPED_TOTAL,PERSON_SEEDS_UNCHANGED_TOTAL, PERSON_SEED_HASHES_DROPPED_TOTAL,PERSON_SEED_PRIOR_CORRUPT_TOTAL, PERSON_SEED_REKEYED_TOTAL, PERSON_SEED_REKEY_HOP_CAPPED_TOTAL,- PERSON_SEED_REKEY_PRODUCE_FAILURE_TOTAL, STAGE1_TRANSITIONS,+ PERSON_SEED_REKEY_PRODUCE_FAILURE_TOTAL,};-use crate::producer::{map_transition, CohortMembershipChange, MembershipSink};+use crate::producer::{CohortMembershipChange, MembershipSink};use crate::stage1::key::LeafStateKey;use crate::stage1::person_record::{apply_person_seed, person_seed_verdict, MatchedSet, PersonRecord, PersonSeedOutcome,@@ -34,16 +34,19 @@ use crate::stage1::person_record::{};use crate::stage1::state::StateVariant;use crate::stage1::transition::LeafTransition;-use crate::stage2::{single_leaf_transition_register_writes, stage_register_writes};+use crate::stage2::Stage2State;use crate::store::{- PersonPrefix, PersonRecordKey, PersonRecords, ReadLane, StagedBatch, StoreError, StoreHandle,+ PersonPrefix, PersonRecordKey, PersonRecords, ReadLane, Stage2Key, StagedBatch, StoreError,+ StoreHandle,};use crate::workers::merge_path::MergeWorkerDeps;-use crate::workers::seed_path::{hold, mark_processed, route_seed, tag_seed, SeedRoute};-use crate::workers::stage2_path::{commit_stage2_writes, recompute_stage2};-use crate::workers::worker::{- first_cascades, produce_cascades, produce_membership, transition_metric_label,+use crate::workers::seed_path::{+ count_stage1_transitions, hold, mark_processed, route_seed, tag_seed, SeedRoute,};+use crate::workers::stage2_path::{+ commit_stage2_writes, diff_single_leaf_registers, recompute_stage2, FoldedLeaf, Stage2Recompute,+};+use crate::workers::worker::{first_cascades, produce_cascades, produce_membership};/// Person-property seed admission for the partition workers.#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -184,10 +187,28 @@ impl Apply<'_> {};let now_ms = Utc::now().timestamp_millis();- self.commit_stage1(filters, &record_key, &update, now_ms)+ // Read the registers before the pre-writes land, so a row this apply is about to place+ // cannot be mistaken for one an earlier apply already told downstream about.+ let folded = folded_leaves(&effective, person, &update, &prior);+ let diff = diff_single_leaf_registers(+ self.partition_id,+ self.handle,+ filters,+ &folded,+ now_ms,+ self.last_updated,+ ReadLane::Maintenance,+ )+ .await+ .map_err(SeedHold::store("register read"))?;++ self.commit_stage1(&record_key, &update, &diff.stage1_writes).await?;- if recomposes(&update, verdict, &prior) {- self.emit(filters, &effective.leaves(person), &update, now_ms)+ count_stage1_transitions(filters, update.transitions());+ // A lagging register is its own reason to emit: the redelivery of a failed produce merges+ // to `Unchanged` and mints nothing, so `recomposes` alone would stay silent.+ if recomposes(&update, verdict, &prior) || !diff.recompute.is_empty() {+ self.emit(filters, &effective.leaves(person), diff.recompute, now_ms).await?;}// Counted last: an emit failure holds the offset, and the redelivery re-derives the verdict@@ -288,34 +309,24 @@ impl Apply<'_> {Ok(prior)}- /// One batch, so a register is never stranded without the matched set that justifies it.+ /// One batch, so a register the diff pre-writes is never stranded without the record that+ /// justifies it. Those are the only registers written here: a real bit waits for its produce+ /// to ack, while the pre-write records what downstream held before it and needs no ack.async fn commit_stage1(&self,- filters: &TeamFilters,key: &PersonRecordKey,update: &RecordUpdate,- now_ms: i64,+ stage1_writes: &[(Stage2Key, Stage2State)],) -> Result<(), SeedHold> {- let RecordUpdate::Changed {- record,- transitions,- } = update- else {- return Ok(());- };-let mut staged = StagedBatch::default();- staged.put::<PersonRecords>(key, &record.encode());- for transition in transitions {- stage_register_writes(- &mut staged,- single_leaf_transition_register_writes(- filters,- self.partition_id,- transition,- now_ms,- ),- );+ if let RecordUpdate::Changed { record, .. } = update {+ staged.put::<PersonRecords>(key, &record.encode());+ }+ for (key, state) in stage1_writes {+ staged.put_stage2(key, &state.encode());+ }+ if staged.is_empty() {+ return Ok(());}self.handle.commit(staged)@@ -324,34 +335,34 @@ impl Apply<'_> {}/// Recomposes every evaluated leaf, not just the ones this seed flipped, so a crash between the- /// two commits heals on replay ([`recomposes`] is what admits the healing pass). The stage-2 bits- /// land only after both produces ack, which keeps a composed flip re-derivable instead of lost- /// against a flipped bit.+ /// two commits heals on replay ([`recomposes`] is what admits the healing pass).///- /// Single-leaf changes are not re-derivable that way: the replay merges to `Unchanged` and- /// mints no transition, so a failed membership produce drops them. Their register row did- /// commit with stage 1, which is what lets the reconcile snapshot repair them.+ /// `registers` carries the single-leaf half the caller already diffed. Both halves commit only+ /// after the produces ack, so every emitted change stays re-derivable: a composed flip from the+ /// stored bit it did not advance, a single-leaf one from the register it did not advance.async fn emit(&self,filters: &TeamFilters,leaves: &[(LeafStateKey, Uuid)],- update: &RecordUpdate,+ registers: Stage2Recompute,now_ms: i64,) -> Result<(), SeedHold> {- let mut changes = single_leaf_changes(filters, update.transitions(), self.last_updated);- let recompute = recompute_stage2(- self.partition_id,- self.handle,- filters,- leaves,- now_ms,- self.last_updated,- ReadLane::Maintenance,- )- .await- .map_err(SeedHold::store("stage 2 recompute"))?;- changes.extend(recompute.changes.iter().cloned());+ let mut recompute = registers;+ recompute.extend(+ recompute_stage2(+ self.partition_id,+ self.handle,+ filters,+ leaves,+ now_ms,+ self.last_updated,+ ReadLane::Maintenance,+ )+ .await+ .map_err(SeedHold::store("stage 2 recompute"))?,+ );+ let mut changes = std::mem::take(&mut recompute.changes);tag_seed(&mut changes, self.seed.run_id());self.produce(changes).await?;@@ -448,8 +459,8 @@ impl RecordUpdate {////// Residue: once a live event has overwritten a held attempt's zeroed fingerprints *and* the catalog/// has since rotated, the replay reads as an ordinary catalog-uncovered no-op and the composed bit-/// is the reconcile snapshot's to repair — the same surface that already owns single-leaf changes-/// lost to a failed produce.+/// is the reconcile snapshot's to repair. The single-leaf half of the same replay is safe either+/// way, because a lagging register admits the emit on its own.fn recomposes(update: &RecordUpdate, verdict: PersonSeedVerdict, prior: &PriorRecord) -> bool {matches!(update, RecordUpdate::Changed { .. })|| verdict == PersonSeedVerdict::SkipLiveFresh@@ -498,19 +509,41 @@ fn record_update(}}-fn single_leaf_changes(- filters: &TeamFilters,- transitions: &[LeafTransition],- last_updated: &str,-) -> Vec<CohortMembershipChange> {- let mut changes = Vec::new();- for transition in transitions {- if let Some(kind) = transition_metric_label(filters, transition) {- counter!(STAGE1_TRANSITIONS, "kind" => kind).increment(1);- }- changes.extend(map_transition(filters, transition, last_updated));- }- changes+/// The person leaves this apply leaves behind, with the membership the stored record implies.+///+/// A person with no stored record has none: nothing was durably evaluated, so there is no register+/// to diff. That is the dominant scan shape, a non-matching dormant person, which stays at one+/// point read and no write. A person with a record folds every evaluated hash, matched or not,+/// because a register left at `true` by a produce that never acked is only found by diffing the+/// hashes the record does not match.+fn folded_leaves(+ effective: &EffectiveHashes,+ person: Uuid,+ update: &RecordUpdate,+ prior: &PriorRecord,+) -> Vec<FoldedLeaf> {+ let matched = match (update, prior) {+ (RecordUpdate::Changed { record, .. }, _) => Some(&record.matched),+ (RecordUpdate::Unchanged, PriorRecord::Present(record)) => Some(&record.matched),+ // An unreadable row survives only under a seed that matched nothing, so the seed is the one+ // readable evaluation and it says no matches, which is also how the composition reads the+ // row.+ (RecordUpdate::Unchanged, PriorRecord::Corrupt) => None,+ (RecordUpdate::Unchanged, PriorRecord::Absent) => return Vec::new(),+ };+ let transitions = update.transitions();+ effective+ .evaluated+ .iter()+ .map(|hash| FoldedLeaf {+ leaf_state_key: LeafStateKey::for_person_property(hash),+ person_id: person,+ in_cohort: matched.is_some_and(|matched| matched.contains(hash)),+ minted_transition: transitions+ .iter()+ .any(|transition| transition.condition_hash == *hash),+ })+ .collect()}/// The seed's hashes projected onto the team's live person-property catalog.@@ -677,6 +710,9 @@ mod tests {sink: CaptureSink,seed_sink: CaptureSeedTileSink,deps: MergeWorkerDeps,+ /// Mints a strictly increasing stamp per run, the way a partition worker does, so a+ /// re-emission wins LWW against the change it replaces.+ clock: crate::producer::LastUpdatedClock,}impl Shell {@@ -738,6 +774,7 @@ mod tests {sink,seed_sink,deps,+ clock: crate::producer::LastUpdatedClock::default(),}}@@ -746,13 +783,14 @@ mod tests {.seed_tracker.mark_dispatched(partition_id as i32, offset + 1);let sink: Arc<dyn MembershipSink> = Arc::new(self.sink.clone());+ let last_updated = self.clock.next();handle_person_seed(partition_id,&self.handle,&self.catalog,&sink,&self.deps,- LAST_UPDATED,+ &last_updated,seed,offset,)@@ -802,6 +840,40 @@ mod tests {.unwrap();}+ fn put_corrupt_record(&self, partition_id: u16, person: Uuid) {+ let key = PersonPrefix::new(partition_id, TEAM.0 as u64, person).record_key();+ self.store+ .write_batch(|batch| batch.put::<PersonRecords>(&key, b"not a person record"))+ .unwrap();+ }++ /// A new tenure over the same store, catalog, and sinks: fresh offset trackers, the way a+ /// restart or rebalance re-assigns the partition at `Offset::Stored` and replays whatever a+ /// hold pinned.+ fn restart(&mut self) {+ self.deps.seed_tracker = Arc::new(OffsetTracker::new());+ self.deps.merge_tracker = Arc::new(OffsetTracker::new());+ self.deps.transfer_tracker = Arc::new(OffsetTracker::new());+ self.deps.cascade_tracker = Arc::new(OffsetTracker::new());+ }++ /// The register row a live evaluation would have left beside `put_record`'s record.+ fn put_register(&self, partition_id: u16, person: Uuid, cohort_id: u64, in_cohort: bool) {+ let key = Stage2Key {+ partition_id,+ team_id: TEAM.0 as u64,+ cohort_id,+ person_id: person,+ };+ let state = Stage2State {+ in_cohort,+ last_evaluated_at_ms: now_ms(),+ };+ self.store+ .write_batch(|b| b.put_stage2(&key, &state.encode()))+ .unwrap();+ }+fn stage2(&self, partition_id: u16, person: Uuid, cohort_id: u64) -> Option<Stage2State> {self.store.get_stage2(&Stage2Key {@@ -892,6 +964,7 @@ mod tests {redirect_dedup: Default::default(),};shell.put_record(partition_id, person, &live);+ shell.put_register(partition_id, person, 1, true);// An older scan that would retract the hash.let seed = seed_for(person, &[PERSON_HASH], &[], now_ms() - 1_000);@@ -902,12 +975,17 @@ mod tests {live,"the record is byte-identical: no write at all",);+ assert!(shell.stage2(partition_id, person, 1).unwrap().in_cohort);assert!(shell.sink.changes().is_empty());assert_eq!(shell.committable(partition_id), Some(1));}+ /// The record carries the hash but no register row, the state left behind when the row is GC'd+ /// or when the cohort post-dates the live evaluation that matched. A retraction must still be+ /// emitted: an absent row cannot prove downstream was never told, and the minted `Left` is the+ /// only thing that can retire a stale entry.#[tokio::test]- async fn a_newer_seed_retracts_a_stale_true_hash() {+ async fn a_newer_seed_retracts_a_stale_true_hash_with_no_register_row() {let (person, partition_id) = dormant_person();let mut shell = Shell::new(mixed_cohorts());let stale = PersonRecord {@@ -920,6 +998,7 @@ mod tests {redirect_dedup: Default::default(),};shell.put_record(partition_id, person, &stale);+ assert!(shell.stage2(partition_id, person, 1).is_none());let seed = seed_for(person, &[PERSON_HASH], &[], 1_000 + MARGIN_MS + 1);shell.run(partition_id, &seed, 0).await;@@ -936,6 +1015,124 @@ mod tests {assert!(!shell.stage2(partition_id, person, 1).unwrap().in_cohort);}+ #[tokio::test]+ async fn a_nonmatching_seed_retracts_a_true_register_over_a_corrupt_record() {+ let (person, partition_id) = dormant_person();+ let mut shell = Shell::new(mixed_cohorts());+ shell.put_corrupt_record(partition_id, person);+ shell.put_register(partition_id, person, 1, true);++ let seed = seed_for(person, &[PERSON_HASH], &[], now_ms());+ shell.run(partition_id, &seed, 0).await;++ let changes = shell.sink.changes();+ assert_eq!(changes.len(), 1);+ assert_eq!(changes[0].cohort_id, 1);+ assert_eq!(changes[0].status, MembershipStatus::Left);+ assert!(!shell.stage2(partition_id, person, 1).unwrap().in_cohort);+ }++ /// The same retraction with its produce failing: the stage-1 pre-write has to record that+ /// downstream still holds the entry, or the redelivery merges to `Unchanged`, mints nothing,+ /// and the `Left` is lost for good.+ #[tokio::test]+ async fn a_failed_retraction_over_an_absent_register_is_re_emitted_on_redelivery() {+ let (person, partition_id) = dormant_person();+ let mut shell = Shell::with_sinks(+ mixed_cohorts(),+ CaptureSink::failing_first(1),+ CaptureSeedTileSink::new(),+ );+ let stale = PersonRecord {+ last_seen_ms: 1_000,+ stamp: Stamp::new(1_000, 0),+ props_fingerprint: PropsFingerprint::of("{}"),+ catalog_fingerprint: shell.filters.catalog_fingerprint,+ matched: MatchedSet::from_iter([hash(PERSON_HASH).as_bytes()]),+ applied_offsets: AppliedOffsets::default(),+ redirect_dedup: Default::default(),+ };+ shell.put_record(partition_id, person, &stale);+ let seed = seed_for(person, &[PERSON_HASH], &[], 1_000 + MARGIN_MS + 1);++ shell.run(partition_id, &seed, 0).await;+ assert_eq!(shell.committable(partition_id), None, "held for redelivery");+ assert!(shell.sink.changes().is_empty());+ assert!(+ shell.stage2(partition_id, person, 1).unwrap().in_cohort,+ "the pre-write records the entry downstream still holds",+ );++ shell.restart();+ shell.run(partition_id, &seed, 0).await;++ let changes = shell.sink.changes();+ assert_eq!(changes.len(), 1, "the redelivery re-derived the retraction");+ assert_eq!(changes[0].cohort_id, 1);+ assert_eq!(changes[0].status, MembershipStatus::Left);+ assert!(!shell.stage2(partition_id, person, 1).unwrap().in_cohort);+ }++ /// A retraction over an absent register pre-writes `true` and then fails its produce, so+ /// downstream was told nothing while the register claims it holds the entry. A newer seed that+ /// re-matches before the redelivery mints `Entered` over a register already reading `true`;+ /// the minted transition wins, or downstream would never hear of a membership the store holds.+ #[tokio::test]+ async fn a_re_entry_over_a_stranded_true_pre_write_is_emitted() {+ let (person, partition_id) = dormant_person();+ let mut shell = Shell::with_sinks(+ mixed_cohorts(),+ CaptureSink::failing_first(1),+ CaptureSeedTileSink::new(),+ );+ let stale = PersonRecord {+ last_seen_ms: 1_000,+ stamp: Stamp::new(1_000, 0),+ props_fingerprint: PropsFingerprint::of("{}"),+ catalog_fingerprint: shell.filters.catalog_fingerprint,+ matched: MatchedSet::from_iter([hash(PERSON_HASH).as_bytes()]),+ applied_offsets: AppliedOffsets::default(),+ redirect_dedup: Default::default(),+ };+ shell.put_record(partition_id, person, &stale);+ assert!(shell.stage2(partition_id, person, 1).is_none());++ let retract = seed_for(person, &[PERSON_HASH], &[], 1_000 + MARGIN_MS + 1);+ shell.run(partition_id, &retract, 0).await;+ assert!(+ shell.sink.changes().is_empty(),+ "nothing reached downstream"+ );+ assert!(+ shell.stage2(partition_id, person, 1).unwrap().in_cohort,+ "the pre-write claims downstream still holds the entry",+ );++ let rematch = seed_for(+ person,+ &[PERSON_HASH],+ &[PERSON_HASH],+ 1_000 + 2 * MARGIN_MS + 2,+ );+ shell.run(partition_id, &rematch, 1).await;++ let changes = shell.sink.changes();+ assert_eq!(+ changes+ .iter()+ .map(|change| (change.cohort_id, change.status))+ .collect::<Vec<_>>(),+ vec![(1, MembershipStatus::Entered)],+ "downstream is told about the membership the store holds",+ );+ assert!(shell.stage2(partition_id, person, 1).unwrap().in_cohort);+ assert_eq!(+ shell.committable(partition_id),+ None,+ "the held retraction still pins the floor"+ );+ }+#[tokio::test]async fn a_record_evaluated_under_another_catalog_still_applies() {let (person, partition_id) = dormant_person();@@ -1043,6 +1240,11 @@ mod tests {assert!(shell.record(partition_id, person).is_none());assert!(shell.sink.changes().is_empty());+ assert!(+ shell.stage2(partition_id, person, 1).is_none(),+ "no record means nothing was durably evaluated, so no register row is invented \+ either, and store growth stays proportional to matchers",+ );assert_eq!(shell.committable(partition_id), Some(1));}@@ -1225,7 +1427,7 @@ mod tests {}#[tokio::test]- async fn a_failed_membership_produce_holds_and_the_replay_re_derives_the_composed_flip() {+ async fn a_failed_membership_produce_holds_and_the_replay_re_derives_both_halves() {let (person, partition_id) = dormant_person();let mut shell = Shell::with_sinks(mixed_cohorts(),@@ -1245,18 +1447,40 @@ mod tests {shell.stage2(partition_id, person, 2).is_none(),"the composed bit must stay unwritten under a failed produce",);+ assert_eq!(+ shell+ .stage2(partition_id, person, 1)+ .map(|state| state.in_cohort),+ Some(false),+ "the single-leaf register holds its pre-write: downstream was never told",+ );+ shell.restart();shell.run(partition_id, &seed, 3).await;let changes = shell.sink.changes();assert_eq!(changes.len(),- 1,- "the Unchanged replay re-derives the composed flip only",+ 2,+ "the Unchanged replay re-derives the single-leaf change and the composed flip",);- assert_eq!(changes[0].cohort_id, 2);- assert_eq!(changes[0].origin, Some(ChangeOrigin::Seed));+ assert_eq!(+ changes+ .iter()+ .map(|change| change.cohort_id)+ .collect::<Vec<_>>(),+ vec![1, 2],+ );+ assert!(changes+ .iter()+ .all(|change| change.origin == Some(ChangeOrigin::Seed)+ && change.status == MembershipStatus::Entered));+ assert!(shell.stage2(partition_id, person, 1).unwrap().in_cohort);assert!(shell.stage2(partition_id, person, 2).unwrap().in_cohort);- assert_eq!(shell.committable(partition_id), Some(3));+ assert_eq!(+ shell.committable(partition_id),+ Some(4),+ "a fresh tenure commits past the redelivered offset"+ );}/// The held replay can arrive after a live event has already re-derived the same matched set.@@ -1293,9 +1517,56 @@ mod tests {shell.stage2(partition_id, person, 2).unwrap().in_cohort,"the live-fresh skip must still recompose the bit nothing else would ever write",);+ let changes = shell.sink.changes();+ assert_eq!(+ changes+ .iter()+ .map(|change| change.cohort_id)+ .collect::<Vec<_>>(),+ vec![1, 2],+ "the single-leaf change the failed produce lost is re-derived alongside it",+ );+ assert!(shell.stage2(partition_id, person, 1).unwrap().in_cohort);assert_eq!(shell.committable(partition_id), Some(3));}+ /// A cohort added over a record that predates it has no register row, so the next seed tells+ /// downstream even though the merge is a no-op and mints no transition.+ #[tokio::test]+ async fn a_cohort_added_over_an_existing_record_enters_on_the_next_unchanged_seed() {+ let (person, partition_id) = dormant_person();+ let mut shell = Shell::new(mixed_cohorts());+ let seed = seed_for(person, &[PERSON_HASH], &[PERSON_HASH], now_ms());++ shell.run(partition_id, &seed, 0).await;+ assert_eq!(+ shell.sink.changes().len(),+ 1,+ "cohort 1 only: no behavioral state"+ );++ // Cohort 3 arrives on the same person leaf, over a record it never saw evaluated.+ let mut cohorts = mixed_cohorts();+ cohorts.push((3, wrap(vec![person_leaf(PERSON_HASH)])));+ shell.catalog = Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([(+ TEAM,+ build_filters(&cohorts),+ )])));++ shell.run(partition_id, &seed, 1).await;++ let changes = shell.sink.changes();+ assert_eq!(+ changes.len(),+ 2,+ "the replay is Unchanged but cohort 3 is new"+ );+ assert_eq!(changes[1].cohort_id, 3);+ assert_eq!(changes[1].status, MembershipStatus::Entered);+ assert!(shell.stage2(partition_id, person, 3).unwrap().in_cohort);+ assert_eq!(shell.committable(partition_id), Some(2));+ }+#[tokio::test]async fn a_seeded_dormant_person_reaches_the_same_membership_as_a_live_evaluated_one() {let live_person = Uuid::from_u128(0xA11CE);diff --git a/rust/cohort-stream-processor/src/workers/seed_path.rs b/rust/cohort-stream-processor/src/workers/seed_path.rsindex 87057217acf6..337cc1c3c9ef 100644--- a/rust/cohort-stream-processor/src/workers/seed_path.rs+++ b/rust/cohort-stream-processor/src/workers/seed_path.rs@@ -1,9 +1,17 @@//! The seed-tile apply path: a pure, clock-free core ([`merge_tile_into_leaf`]) that mirrors the//! live fold minus dedup (slide-before-evaluate, max-merge of the tile's absolute count,//! structural-equality `Unchanged` — the whole of tile idempotency), and an imperative shell-//! ([`handle_seed`]) ordered stage-1 commit → stage-2 recompute → produce → stage-2 commit → mark.-//! Committing the stage-2 bits after the produces ack makes a failed produce re-derivable on-//! replay; store/produce failures hold the seed offset.+//! ([`handle_seed`]) ordered register diff → stage-1 commit → stage-2 recompute → produce →+//! stage-2 commit → mark.+//!+//! Before an emission, this path records the retired membership with stage 1 and advances it only+//! after the produce acks. A failed produce is therefore re-derived while replay still folds the+//! leaf. If the leaf expires before replay and is dropped by the fold, sweep or reconcile retires+//! its stored state. Composed bits come from [`recompute_stage2`]; single-leaf ones from+//! [`diff_single_leaf_registers`](crate::workers::stage2_path::diff_single_leaf_registers), which+//! is why `Unchanged` leaves still take part. The replay mints no transition, so the persisted+//! register is the only record of what downstream was told. Store and produce failures hold the+//! seed offset.use std::num::NonZeroU32;use std::sync::Arc;@@ -22,14 +30,14 @@ use crate::filters::reverse_index::{LeafStateMeta, TeamFilters};use crate::filters::TeamId;use crate::merge::tombstone_redirect::{self, Resolution, MAX_CROSS_PARTITION_REDIRECT_HOPS};use crate::observability::metrics::{- COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH, RECONCILE_JOBS_ENQUEUED_TOTAL,- RECONCILE_JOBS_SUPERSEDED_TOTAL, SEED_HELD_OFFSET_GAUGE, SEED_REKEYED_TOTAL,- SEED_REKEY_HOP_CAPPED_TOTAL, SEED_REKEY_PRODUCE_FAILURE_TOTAL, SEED_TILES_APPLIED_TOTAL,- SEED_TILES_DROPPED_TOTAL, SEED_TILES_SKIPPED_TOTAL, SEED_TILES_UNCHANGED_TOTAL,- STAGE1_STATE_DECODE_ERROR, STAGE1_TRANSITIONS,+ COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH, OUTPUT_TRANSITIONS_UNMAPPED,+ RECONCILE_JOBS_ENQUEUED_TOTAL, RECONCILE_JOBS_SUPERSEDED_TOTAL, SEED_HELD_OFFSET_GAUGE,+ SEED_REKEYED_TOTAL, SEED_REKEY_HOP_CAPPED_TOTAL, SEED_REKEY_PRODUCE_FAILURE_TOTAL,+ SEED_TILES_APPLIED_TOTAL, SEED_TILES_DROPPED_TOTAL, SEED_TILES_SKIPPED_TOTAL,+ SEED_TILES_UNCHANGED_TOTAL, STAGE1_STATE_DECODE_ERROR, STAGE1_TRANSITIONS,};use crate::partitions::offset_tracker::{MarkOutcome, OffsetTracker};-use crate::producer::{map_transition, ChangeOrigin, CohortMembershipChange, MembershipSink};+use crate::producer::{ChangeOrigin, CohortMembershipChange, MembershipSink};use crate::stage1::bucket_tz::{daily_bucket_len, day_idx_in_tz, start_of_day_ms_in_tz, window_start_for_now, DayIdx,};@@ -40,15 +48,15 @@ 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::stage2::leaf_membership;use crate::store::{Behavioral, BehavioralKey, PersonPrefix, ReadLane, StagedBatch, StoreHandle};use crate::sweep::EvictionQueue;use crate::workers::merge_path::MergeWorkerDeps;use crate::workers::person_seed_path::handle_person_seed;use crate::workers::reconcile::{ReconcileQueue, SupersedeOutcome};-use crate::workers::stage2_path::{commit_stage2_writes, recompute_stage2};+use crate::workers::stage2_path::{+ commit_stage2_writes, diff_single_leaf_registers, recompute_stage2, FoldedLeaf,+};use crate::workers::worker::{first_cascades, produce_cascades, produce_membership, transition_metric_label,};@@ -640,15 +648,44 @@ pub(crate) async fn handle_seed(let now_ms = Utc::now().timestamp_millis();let now_day = day_idx_in_tz(now_ms, filters.timezone);let TileApplication {- staged,+ mut staged,transitions,- stage2_leaves,+ leaves,schedules,} = apply_tile_to_leaves(filters, &prefix, lsks, values, tile, person, now_day, now_ms,);- // Order: stage-1 commit → stage-2 recompute → produce → stage-2 commit → schedule → mark.+ // Order: register diff → stage-1 commit → stage-2 recompute → produce → stage-2 commit →+ // schedule → mark. The diff reads first, so a row this apply is about to place cannot be+ // mistaken for one an earlier apply already told downstream about.+ let diff = match diff_single_leaf_registers(+ partition_id,+ handle,+ filters,+ &leaves,+ now_ms,+ last_updated,+ ReadLane::Maintenance,+ )+ .await+ {+ Ok(diff) => diff,+ Err(error) => {+ warn!(+ partition_id,+ team_id = tile.team_id().0,+ error = %error,+ "seed register read failed; holding the seed offset for redelivery",+ );+ hold(&merge.seed_tracker, partition_id, offset);+ return;+ }+ };+ for (key, state) in &diff.stage1_writes {+ staged.put_stage2(key, &state.encode());+ }+if !staged.is_empty() {if let Err(error) = handle.commit(staged).await {warn!(@@ -662,16 +699,12 @@ pub(crate) async fn handle_seed(}}- let mut changes: Vec<CohortMembershipChange> = Vec::new();- for transition in &transitions {- if let Some(kind) = transition_metric_label(filters, transition) {- counter!(STAGE1_TRANSITIONS, "kind" => kind).increment(1);- }- changes.extend(map_transition(filters, transition, last_updated));- }+ count_stage1_transitions(filters, &transitions);+ let stage2_leaves: Vec<(LeafStateKey, Uuid)> = leaves.iter().map(|leaf| leaf.pair()).collect();// `event_ms := now_ms`: `last_evaluated_at_ms` is a freshness stamp, and the worker-batch// `last_updated` makes backfill flips win LWW downstream.- let recompute = match recompute_stage2(+ let mut recompute = diff.recompute;+ match recompute_stage2(partition_id,handle,filters,@@ -682,7 +715,7 @@ pub(crate) async fn handle_seed().await{- Ok(recompute) => recompute,+ Ok(composed) => recompute.extend(composed),Err(error) => {warn!(partition_id,@@ -693,8 +726,8 @@ pub(crate) async fn handle_seed(hold(&merge.seed_tracker, partition_id, offset);return;}- };- changes.extend(recompute.changes.iter().cloned());+ }+ let mut changes = std::mem::take(&mut recompute.changes);tag_seed(&mut changes, tile.run_id());// Only the cascade topic can re-evaluate cohort-of-cohort referrers; gate-off builds nothing.@@ -702,8 +735,8 @@ pub(crate) async fn handle_seed(if !changes.is_empty() {let errors = produce_membership(sink, changes).await;if errors > 0 {- // Replay re-derives the stage-2 flips (bits unwritten); a lost single-leaf change is- // not re-emitted — the reconcile snapshot heals that class.+ // Every bit this apply would advance is still unwritten, so the replay re-derives both+ // halves and re-emits; the duplicates are LWW-safe downstream.warn!(partition_id,team_id = tile.team_id().0,@@ -726,8 +759,8 @@ pub(crate) async fn handle_seed(return;}- // The bits commit only after both produces ack, so a failed produce is re-derived on replay- // instead of lost against a flipped bit; replay duplicates are LWW-safe downstream.+ // The composed bits and the single-leaf register bits commit only after both produces ack, so+ // a failed produce is re-derived on replay instead of lost against a flipped bit.if let Err(error) = commit_stage2_writes(handle, &recompute.writes).await {warn!(partition_id,@@ -811,9 +844,10 @@ fn admit_reconcile(struct TileApplication {staged: StagedBatch,transitions: Vec<LeafTransition>,- /// Merged *and* Unchanged leaves both recompose Stage 2, so a crash between the two commits- /// self-heals on replay.- stage2_leaves: Vec<(LeafStateKey, Uuid)>,+ /// Merged *and* Unchanged leaves both feed the register diff and the Stage 2 recompute, so a+ /// crash between the two commits self-heals on replay: the replayed tile mints no transition,+ /// but the leaf's folded truth still diffs against what downstream was told.+ leaves: Vec<FoldedLeaf>,schedules: Vec<(BehavioralKey, i64)>,}@@ -872,21 +906,13 @@ 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.leaves.push(FoldedLeaf {+ leaf_state_key: lsk,+ person_id: person,+ in_cohort: leaf_membership(Some(&record.state), meta),+ minted_transition: transition.is_some(),+ });application.staged.put::<Behavioral>(&key, &record.encode());- application.stage2_leaves.push((lsk, person));if let Some(transition) = transition {application.transitions.push(transition);}@@ -897,20 +923,12 @@ fn apply_tile_to_leaves(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));+ application.leaves.push(FoldedLeaf {+ leaf_state_key: lsk,+ person_id: person,+ in_cohort: leaf_membership(Some(&record.state), meta),+ minted_transition: false,+ });}LeafMergeOutcome::Dropped(reason) => {counter!(SEED_TILES_DROPPED_TOTAL, "reason" => reason.as_str()).increment(1);@@ -920,21 +938,6 @@ 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),- );-}-pub(crate) fn tag_seed(changes: &mut [CohortMembershipChange], run_id: RunId) {for change in changes {change.origin = Some(ChangeOrigin::Seed);@@ -942,6 +945,25 @@ pub(crate) fn tag_seed(changes: &mut [CohortMembershipChange], run_id: RunId) {}}+/// Count stage-1 flips without deriving emissions, which the seed register diff owns.+pub(crate) fn count_stage1_transitions(filters: &TeamFilters, transitions: &[LeafTransition]) {+ for transition in transitions {+ if let Some(kind) = transition_metric_label(filters, transition) {+ counter!(STAGE1_TRANSITIONS, "kind" => kind).increment(1);+ }+ if filters+ .by_lsk_to_single_leaf_cohorts+ .get(&transition.leaf_state_key)+ .is_none_or(Vec::is_empty)+ && !filters+ .by_lsk_to_composable_cohorts+ .contains_key(&transition.leaf_state_key)+ {+ counter!(OUTPUT_TRANSITIONS_UNMAPPED, "reason" => "no_emitting_cohort").increment(1);+ }+ }+}+/// Advance the seed tracker past `offset`. A mark beyond the dispatch ceiling is capped and counted.pub(crate) fn mark_processed(tracker: &OffsetTracker, partition_id: u16, offset: i64) {if let MarkOutcome::CappedAheadOfDispatch =@@ -971,6 +993,7 @@ mod tests {use chrono_tz::America::New_York;use chrono_tz::UTC;+ use metrics_exporter_prometheus::PrometheusBuilder;use proptest::prelude::*;use serde_json::{json, Value};use tempfile::TempDir;@@ -997,6 +1020,28 @@ mod tests {use super::*;const TEAM: TeamId = TeamId(7);++ #[test]+ fn an_unmapped_seed_transition_keeps_its_diagnostic() {+ let recorder = PrometheusBuilder::new().build_recorder();+ let handle = recorder.handle();+ let filters = build_filters(Vec::new(), UTC);+ let transition = LeafIdentity {+ team_id: TEAM,+ lsk: LeafStateKey([0xEE; 16]),+ person_id: Uuid::from_u128(1),+ condition_hash: [0xDD; 16],+ }+ .transition(TransitionKind::Entered);++ metrics::with_local_recorder(&recorder, || {+ count_stage1_transitions(&filters, &[transition]);+ });++ assert!(handle+ .render()+ .contains("output_transitions_unmapped_total{reason=\"no_emitting_cohort\"} 1"));+ }const HASH: [u8; 16] = *b"0123456789abcdef";/// A fixed "now": 2026-06-15 12:00:00 UTC.const NOW_MS: i64 = 1_781_524_800_000;@@ -1478,6 +1523,60 @@ mod tests {proptest! {#![proptest_config(ProptestConfig::with_cases(64))]+ /// The register diff and the stage-1 transition must agree over any tile sequence and+ /// comparator direction. Otherwise, a first apply can emit a change stage 1 never flipped+ /// or swallow one it did.+ #[test]+ fn leaf_membership_agrees_with_the_transition_the_merge_mints(+ tiles in prop::collection::vec((0i32..=12, 1u32..=5, 0i32..=3), 1..10),+ gte in any::<bool>(),+ threshold in 1u32..=4,+ ) {+ let op = if gte { PredicateOp::Gte(threshold) } else { PredicateOp::Lte(threshold) };+ let meta = daily_meta(7, op);+ let mut prev: Option<StatefulRecord> = None;+ // Wall time advances between applies, so the window slides and the slide-induced+ // transitions are in scope too.+ let mut today = now_day();+ let mut now_ms = NOW_MS;+ for &(offset, n, advance) in &tiles {+ today += advance;+ now_ms += advance as i64 * 86_400_000;+ let before = leaf_membership(prev.as_ref().map(|record| &record.state), &meta);+ match merge_tile_into_leaf(+ &meta,+ UTC,+ identity(),+ today - offset,+ count(n),+ prev.clone(),+ today,+ now_ms,+ ) {+ LeafMergeOutcome::Merged { record, transition, .. } => {+ let after = leaf_membership(Some(&record.state), &meta);+ prop_assert_eq!(+ transition.map(|transition| transition.kind),+ match (before, after) {+ (false, true) => Some(TransitionKind::Entered),+ (true, false) => Some(TransitionKind::Left),+ _ => None,+ },+ );+ prev = Some(record);+ }+ LeafMergeOutcome::Unchanged { record } => {+ prop_assert_eq!(+ leaf_membership(Some(&record.state), &meta),+ before,+ "an Unchanged merge cannot move membership",+ );+ }+ LeafMergeOutcome::Dropped(_) => {}+ }+ }+ }+/// An arbitrary tile multiset applied in an arbitrary order (some tiles below the/// window) reaches one unique final state.#[test]@@ -1802,6 +1901,12 @@ mod tests {deps: MergeWorkerDeps,queue: EvictionQueue<BehavioralKey>,reconcile_queue: ReconcileQueue,+ /// Mints a strictly increasing stamp per run, the way a partition worker does, so a+ /// re-emission wins LWW against the change it replaces.+ clock: crate::producer::LastUpdatedClock,+ /// What `handle_seed` produces through. Defaults to `sink`; a test swaps it to reach an+ /// ack shape `CaptureSink` cannot produce.+ membership: Arc<dyn MembershipSink>,}impl Shell {@@ -1883,13 +1988,15 @@ mod tests {store,handle,catalog,- sink,+ sink: sink.clone(),seed_sink,cascade_sink,marker_sink,deps,queue: EvictionQueue::new(),reconcile_queue,+ clock: crate::producer::LastUpdatedClock::default(),+ membership: Arc::new(sink),}}@@ -1897,7 +2004,8 @@ mod tests {self.deps.seed_tracker.mark_dispatched(partition_id as i32, offset + 1);- let sink: Arc<dyn MembershipSink> = Arc::new(self.sink.clone());+ let sink = self.membership.clone();+ let last_updated = self.clock.next();handle_seed(partition_id,&self.handle,@@ -1906,13 +2014,66 @@ mod tests {&self.deps,&mut self.queue,&mut self.reconcile_queue,- "2026-06-15 12:00:00.000000",+ &last_updated,&work,offset,).await;}+ /// A new tenure over the same store, catalog, and sinks: fresh offset trackers and+ /// in-memory queues, the way a restart or rebalance re-assigns the partition at+ /// `Offset::Stored` and replays whatever a hold pinned. The clock is kept: a real tenure+ /// mints a fresh one whose first stamp is wall time, later than anything the last tenure+ /// minted, which the shared clock also guarantees.+ fn restart(&mut self) {+ self.deps.seed_tracker = Arc::new(OffsetTracker::new());+ self.deps.merge_tracker = Arc::new(OffsetTracker::new());+ self.deps.transfer_tracker = Arc::new(OffsetTracker::new());+ self.deps.cascade_tracker = Arc::new(OffsetTracker::new());+ self.queue = EvictionQueue::new();+ self.reconcile_queue =+ ReconcileQueue::new(0, self.deps.reconcile.backlog.clone(), self.handle.clone());+ }++ /// Drain the queued reconcile to completion, one page per tick, the way the worker does.+ async fn drain_reconcile(&mut self, partition_id: u16) {+ let sink = self.membership.clone();+ for _ in 0..64 {+ if self.reconcile_queue.len() == 0 {+ return;+ }+ let last_updated = self.clock.next();+ crate::workers::reconcile::handle_reconcile_drain(+ partition_id,+ &self.handle,+ &self.catalog,+ &sink,+ &self.deps,+ &mut self.reconcile_queue,+ &last_updated,+ )+ .await;+ }+ panic!("the reconcile never completed");+ }++ fn register_key(&self, partition_id: u16, person: Uuid, cohort_id: u64) -> Stage2Key {+ Stage2Key {+ partition_id,+ team_id: TEAM.0 as u64,+ cohort_id,+ person_id: person,+ }+ }++ fn register(&self, partition_id: u16, person: Uuid, cohort_id: u64) -> Option<Stage2State> {+ self.store+ .get_stage2(&self.register_key(partition_id, person, cohort_id))+ .unwrap()+ .map(|bytes| Stage2State::decode(&bytes).unwrap())+ }+fn committable(&self, partition_id: u16) -> Option<i64> {self.deps.seed_tracker@@ -1922,6 +2083,25 @@ mod tests {}}+ /// What the CDP consumer would hold after applying `changes` in produce order: the newest+ /// `last_updated` per `(cohort, person)` wins, ties to the later record.+ fn downstream(changes: &[CohortMembershipChange]) -> BTreeMap<(i32, String), MembershipStatus> {+ let mut model: BTreeMap<(i32, String), (String, MembershipStatus)> = BTreeMap::new();+ for change in changes {+ let entry = (change.cohort_id, change.person_id.clone());+ let beats = model+ .get(&entry)+ .is_none_or(|(seen, _)| change.last_updated >= *seen);+ if beats {+ model.insert(entry, (change.last_updated.clone(), change.status));+ }+ }+ model+ .into_iter()+ .map(|(entry, (_, status))| (entry, status))+ .collect()+ }+fn today() -> DayIdx {day_idx_in_tz(chrono::Utc::now().timestamp_millis(), UTC)}@@ -2051,9 +2231,17 @@ mod tests {.write_batch(|batch| batch.delete_stage2(®ister_key)).unwrap();- // Re-delivery: max-merge no-op, no duplicate emission, and the missing register self-heals.+ // Re-delivery: the max-merge is a no-op, but a missing register reads as "downstream was+ // never told", so the entry is re-emitted and the row restored. The duplicate is what the+ // LWW sink is for.shell.run(partition_id, SeedWork::Tile(tile), 10).await;- assert_eq!(shell.sink.changes().len(), 1);+ let changes = shell.sink.changes();+ assert_eq!(changes.len(), 2);+ assert_eq!(changes[1].status, MembershipStatus::Entered);+ assert!(+ changes[1].last_updated > changes[0].last_updated,+ "the re-emission carries the newer stamp, so it wins downstream",+ );assert_eq!(shell.committable(partition_id), Some(11));assert!(Stage2State::decode(&shell.store.get_stage2(®ister_key).unwrap().unwrap())@@ -2063,48 +2251,24 @@ mod tests {);}+ /// A non-member downstream was never told about gets no register row: nothing downstream+ /// needs one, and a reconcile page has nothing to repair for it. The Unchanged replay is just+ /// as silent.#[tokio::test]- async fn unchanged_non_member_seed_restores_an_explicit_false_register_without_emission() {+ async fn a_never_told_non_member_seed_writes_no_register_and_emits_nothing() {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.register(partition_id, person, 1).is_none());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.register(partition_id, person, 1).is_none());assert!(shell.sink.changes().is_empty());assert_eq!(shell.committable(partition_id), Some(2));}@@ -2298,8 +2462,180 @@ mod tests {assert!(shell.sink.changes().is_empty(), "no local apply either");}+ /// Stage 1 committed, then the membership produce failed. The redelivery merges to+ /// `Unchanged` and mints no transition, so only the register diff can tell that downstream was+ /// never told and re-emit.+ #[tokio::test]+ async fn membership_produce_failure_holds_and_the_redelivery_re_emits_the_single_leaf_change() {+ let person = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16;+ let mut shell = Shell::with_sink(+ vec![(1, wrap(vec![single_leaf_json(7)]))],+ CaptureSink::failing_first(1),+ CaptureSeedTileSink::new(),+ );+ let tile = tile_for(person, today(), 1);++ shell+ .run(partition_id, SeedWork::Tile(tile.clone()), 4)+ .await;++ assert_eq!(shell.committable(partition_id), None, "held for redelivery");+ assert!(shell.sink.changes().is_empty());+ assert_eq!(+ shell+ .register(partition_id, person, 1)+ .map(|state| state.in_cohort),+ Some(false),+ "the row exists for the reconcile scan, but reads `false`: downstream was never told",+ );++ shell.restart();+ shell.run(partition_id, SeedWork::Tile(tile), 4).await;++ let changes = shell.sink.changes();+ assert_eq!(+ changes.len(),+ 1,+ "the redelivery re-derived the lost change"+ );+ assert_eq!(changes[0].cohort_id, 1);+ assert_eq!(changes[0].status, MembershipStatus::Entered);+ assert_eq!(changes[0].origin, Some(ChangeOrigin::Seed));+ assert!(+ shell.register(partition_id, person, 1).unwrap().in_cohort,+ "the bit advances once the produce acks",+ );+ assert_eq!(+ downstream(&changes),+ BTreeMap::from([((1, person.to_string()), MembershipStatus::Entered)]),+ );+ assert_eq!(shell.committable(partition_id), Some(5));+ }++ /// Acks the first record of one batch and fails the rest, which is what a broker does when+ /// its queue fills mid-batch. The acked record lands in the wrapped capture, so the model+ /// sees exactly what downstream got.+ #[derive(Clone)]+ struct PartialAckSink {+ inner: CaptureSink,+ split_next: Arc<std::sync::atomic::AtomicBool>,+ }++ #[async_trait::async_trait]+ impl MembershipSink for PartialAckSink {+ async fn produce(+ &self,+ changes: Vec<CohortMembershipChange>,+ ) -> Vec<Result<(), common_kafka::kafka_producer::KafkaProduceError>> {+ if !self+ .split_next+ .swap(false, std::sync::atomic::Ordering::SeqCst)+ {+ return self.inner.produce(changes).await;+ }+ let mut acks = Vec::with_capacity(changes.len());+ for (index, change) in changes.into_iter().enumerate() {+ if index == 0 {+ acks.extend(self.inner.produce(vec![change]).await);+ } else {+ acks.push(Err(+ common_kafka::kafka_producer::KafkaProduceError::KafkaProduceCanceled,+ ));+ }+ }+ acks+ }+ }++ /// One record of the batch acked, the rest failed. No bit advances, so the redelivery re-emits+ /// the whole batch and downstream converges on the store's truth.#[tokio::test]- async fn membership_produce_failure_holds_the_seed_offset() {+ async fn a_partially_acked_produce_holds_and_the_redelivery_re_emits_the_whole_batch() {+ let person = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16;+ // Two single-leaf cohorts on one leaf, so one tile produces a two-record batch.+ let mut shell = Shell::new(vec![+ (1, wrap(vec![single_leaf_json(7)])),+ (2, wrap(vec![single_leaf_json(7)])),+ ]);+ shell.membership = Arc::new(PartialAckSink {+ inner: shell.sink.clone(),+ split_next: Arc::new(std::sync::atomic::AtomicBool::new(true)),+ });+ let tile = tile_for(person, today(), 1);++ shell+ .run(partition_id, SeedWork::Tile(tile.clone()), 4)+ .await;++ assert_eq!(shell.sink.changes().len(), 1, "only cohort 1 acked");+ assert_eq!(shell.committable(partition_id), None, "held for redelivery");+ for cohort_id in [1, 2] {+ assert_eq!(+ shell+ .register(partition_id, person, cohort_id)+ .map(|state| state.in_cohort),+ Some(false),+ "cohort {cohort_id}: a partial ack advances no bit at all",+ );+ }++ shell.restart();+ shell.run(partition_id, SeedWork::Tile(tile), 4).await;++ let changes = shell.sink.changes();+ assert_eq!(+ changes.len(),+ 3,+ "the acked record duplicates, the failed one lands"+ );+ assert_eq!(+ downstream(&changes),+ BTreeMap::from([+ ((1, person.to_string()), MembershipStatus::Entered),+ ((2, person.to_string()), MembershipStatus::Entered),+ ]),+ "the model matches the store's truth for both cohorts",+ );+ assert!(shell.register(partition_id, person, 1).unwrap().in_cohort);+ assert!(shell.register(partition_id, person, 2).unwrap().in_cohort);+ }++ /// Membership acked, then the cascade leg failed. The single-leaf change is re-emitted with+ /// its cascade, so a cohort-of-cohort referrer is not left stale.+ #[tokio::test]+ async fn a_failed_cascade_re_emits_the_single_leaf_change_and_its_cascade_on_redelivery() {+ let person = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16;+ let mut shell = Shell::with_cascade(+ vec![(1, wrap(vec![single_leaf_json(7)]))],+ crate::producer::CaptureCascadeSink::failing_first(1),+ );+ let tile = tile_for(person, today(), 1);++ shell+ .run(partition_id, SeedWork::Tile(tile.clone()), 3)+ .await;++ assert_eq!(shell.sink.changes().len(), 1, "membership is the first leg");+ assert!(shell.cascade_sink.messages().is_empty());+ assert_eq!(shell.committable(partition_id), None, "held for redelivery");++ shell.restart();+ shell.run(partition_id, SeedWork::Tile(tile), 3).await;++ assert_eq!(shell.sink.changes().len(), 2, "the change re-emits with it");+ let cascades = shell.cascade_sink.messages();+ assert_eq!(cascades.len(), 1, "the lost single-leaf cascade lands");+ assert_eq!(cascades[0].change.cohort_id, 1);+ assert_eq!(cascades[0].change.origin, Some(ChangeOrigin::Seed));+ }++ /// A later tile on the same leaf advances the register before the held one is redelivered, so+ /// the redelivery has nothing to repair. Over-emission is the fix's own failure mode.+ #[tokio::test]+ async fn a_later_tiles_ack_silences_the_held_tiles_redelivery() {let person = Uuid::from_u128(0x5EED);let partition_id = partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16;let mut shell = Shell::with_sink(@@ -2307,15 +2643,202 @@ mod tests {CaptureSink::failing_first(1),CaptureSeedTileSink::new(),);+ let held = tile_for(person, today(), 1);++ shell+ .run(partition_id, SeedWork::Tile(held.clone()), 4)+ .await;+ assert!(shell.sink.changes().is_empty(), "held before any emission");++ // A hold pauses nothing, so the next tile on the partition still applies and acks.+ shell+ .run(+ partition_id,+ SeedWork::Tile(tile_for(person, today() - 1, 1)),+ 5,+ )+ .await;+ assert_eq!(shell.sink.changes().len(), 1);++ shell.restart();+ shell.run(partition_id, SeedWork::Tile(held), 4).await;++ let changes = shell.sink.changes();+ assert_eq!(changes.len(), 1, "the register already matched the truth");+ assert_eq!(+ downstream(&changes),+ BTreeMap::from([((1, person.to_string()), MembershipStatus::Entered)]),+ );+ }++ /// A cohort added over leaf state that predates it has no register row, so the next tile on+ /// that leaf tells downstream even though the merge is a no-op. Nothing minted a transition+ /// for this person, which is why only a register diff can reach the case.+ #[tokio::test]+ async fn a_cohort_added_over_existing_leaf_state_enters_on_the_next_unchanged_tile() {+ 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![single_leaf_json(7)]))]);+ let tile = tile_for(person, today(), 1);++ shell+ .run(partition_id, SeedWork::Tile(tile.clone()), 0)+ .await;+ assert_eq!(shell.sink.changes().len(), 1, "cohort 1 entered");++ // Cohort 2 arrives keyed on the same leaf, over state it never saw evaluated.+ shell.catalog = Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([(+ TEAM,+ build_filters(+ vec![+ (1, wrap(vec![single_leaf_json(7)])),+ (2, wrap(vec![single_leaf_json(7)])),+ ],+ UTC,+ ),+ )])));++ shell.run(partition_id, SeedWork::Tile(tile), 1).await;++ let changes = shell.sink.changes();+ assert_eq!(+ changes.len(),+ 2,+ "the replay is Unchanged but cohort 2 is new"+ );+ assert_eq!(changes[1].cohort_id, 2);+ assert_eq!(changes[1].status, MembershipStatus::Entered);+ assert!(shell.register(partition_id, person, 2).unwrap().in_cohort);+ assert_eq!(shell.committable(partition_id), Some(2));+ }++ /// Membership acked, then the cascade leg failed, then a later tile in the same tenure retracts+ /// the leaf. The register still reads the `false` the held apply pre-wrote and never advanced,+ /// so a register-only diff would read `false == false` and stay silent; the minted `Left` is+ /// what retires the entry downstream holds, and the redelivery then has nothing to repair.+ #[tokio::test]+ async fn a_minted_retraction_is_emitted_after_an_acked_entry_held_on_its_cascade() {+ let person = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16;+ // `lte 3`: one event is a member, nine are not.+ let mut shell = Shell::with_cascade(+ vec![(1, wrap(vec![multiple_leaf_json(7, "lte", 3)]))],+ crate::producer::CaptureCascadeSink::failing_first(1),+ );shell.run(partition_id,SeedWork::Tile(tile_for(person, today(), 1)),- 4,+ 0,).await;- assert_eq!(shell.committable(partition_id), None, "held for redelivery");+ assert_eq!(+ shell.sink.changes().len(),+ 1,+ "the Entered acked downstream"+ );+ assert_eq!(shell.committable(partition_id), None, "held on the cascade");+ assert_eq!(+ shell+ .register(partition_id, person, 1)+ .map(|state| state.in_cohort),+ Some(false),+ "the bit never advanced past the failed cascade",+ );++ // A hold pauses nothing: the next tile on the partition still applies, and stage 1 mints+ // `Left` because the count now exceeds the comparator.+ shell+ .run(+ partition_id,+ SeedWork::Tile(tile_for(person, today(), 9)),+ 1,+ )+ .await;+ let changes = shell.sink.changes();+ assert_eq!(changes.len(), 2, "the retraction is emitted");+ assert_eq!(changes[1].status, MembershipStatus::Left);++ // The redelivery merges to `Unchanged`, mints nothing, and finds the register in agreement.+ shell.restart();+ shell+ .run(+ partition_id,+ SeedWork::Tile(tile_for(person, today(), 1)),+ 0,+ )+ .await;++ let changes = shell.sink.changes();+ assert_eq!(changes.len(), 2, "nothing left to repair");+ assert_eq!(+ downstream(&changes),+ BTreeMap::from([((1, person.to_string()), MembershipStatus::Left)]),+ );+ assert_eq!(shell.committable(partition_id), Some(1));+ }++ /// A reconcile page drained over a held tile finds the row stage 1 recorded and repairs it,+ /// which is why an emitting apply records its row before the produce. The redelivery then+ /// finds the register in agreement and stays silent.+ #[tokio::test]+ async fn a_reconcile_page_repairs_a_held_tile_and_its_redelivery_is_silent() {+ let person = Uuid::from_u128(0x5EED);+ let partition_id = partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16;+ let mut shell = Shell::with_sink(+ vec![(1, wrap(vec![single_leaf_json(7)]))],+ CaptureSink::failing_first(1),+ CaptureSeedTileSink::new(),+ );+ shell.deps.reconcile.enabled = true;+ // The reconcile guard pins the run to the cohort's behavioral shape.+ let mut builder = TeamFiltersBuilder::default();+ builder+ .add_cohort(CohortId(1), TEAM, &wrap(vec![single_leaf_json(7)]))+ .unwrap();+ builder.set_behavioral_shape_hash(+ CohortId(1),+ BehavioralShapeHash::parse("0123456789abcdef").unwrap(),+ );+ shell.catalog = Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([(+ TEAM,+ builder.freeze(UTC),+ )])));+ let tile = tile_for(person, today(), 1);++ shell+ .run(partition_id, SeedWork::Tile(tile.clone()), 4)+ .await;+ assert!(shell.sink.changes().is_empty(), "held before any emission");+ assert_eq!(+ shell+ .register(partition_id, person, 1)+ .map(|state| state.in_cohort),+ Some(false),+ "the row the page has to find",+ );++ shell+ .run(partition_id, SeedWork::Reconcile(reconcile_for(1, 1)), 5)+ .await;+ shell.drain_reconcile(partition_id).await;++ let changes = shell.sink.changes();+ assert_eq!(changes.len(), 1, "the page found the row and repaired it");+ assert_eq!(changes[0].origin, Some(ChangeOrigin::Reconcile));+ assert_eq!(changes[0].status, MembershipStatus::Entered);+ assert!(shell.register(partition_id, person, 1).unwrap().in_cohort);++ shell.restart();+ shell.run(partition_id, SeedWork::Tile(tile), 4).await;++ assert_eq!(+ shell.sink.changes().len(),+ 1,+ "nothing left for the redelivery to repair"+ );+ assert_eq!(shell.committable(partition_id), Some(5));}/// A seeded flip that never cascades leaves cohort-of-cohort referrers permanently stale.diff --git a/rust/cohort-stream-processor/src/workers/stage2_path.rs b/rust/cohort-stream-processor/src/workers/stage2_path.rsindex 5bb87c5d2e70..1a58ff0d2fab 100644--- a/rust/cohort-stream-processor/src/workers/stage2_path.rs+++ b/rust/cohort-stream-processor/src/workers/stage2_path.rs@@ -5,7 +5,7 @@//! the Stage 1 and Stage 2 commits drops a flip, but `evaluate_tree` recomputes the whole cohort//! each event, so a mismatch self-heals on the person's next event.-use std::collections::{BTreeSet, HashMap};+use std::collections::{BTreeMap, BTreeSet, HashMap};use metrics::counter;use uuid::Uuid;@@ -14,7 +14,8 @@ use crate::filters::reverse_index::TeamFilters;use crate::filters::tree::{CohortLeaf, CohortTree, FilterNode};use crate::filters::CohortId;use crate::observability::metrics::{- STAGE2_COHORTS_EVALUATED, STAGE2_STATE_DECODE_ERROR, STAGE2_TRANSITIONS,+ SEED_REGISTER_REPAIRS_TOTAL, STAGE2_COHORTS_EVALUATED, STAGE2_STATE_DECODE_ERROR,+ STAGE2_TRANSITIONS,};use crate::producer::{CohortMembershipChange, MembershipStatus};use crate::stage1::key::LeafStateKey;@@ -56,20 +57,111 @@ pub async fn compose_stage2(/// Uncommitted recompute result: the flips and their pending `cf_stage2` writes. Lets/// produce-before-state callers commit only after their produces ack, so a failed produce is/// re-derived on replay.+#[derive(Default)]pub(crate) struct Stage2Recompute {pub changes: Vec<CohortMembershipChange>,pub writes: Vec<(Stage2Key, Stage2State)>,evaluated: u64,+ /// Composed flips only. `changes` also carries the single-leaf changes a register diff folds+ /// in, so counting over it would report those as Stage 2 transitions.+ composed: StatusCounts,+ /// Single-leaf changes a register diff derived with no stage-1 transition behind them.+ repairs: RepairCounts,}impl Stage2Recompute {/// Call only once the writes committed, so a failed commit's redelivery cannot double-count.pub(crate) fn record_metrics(&self) {counter!(STAGE2_COHORTS_EVALUATED).increment(self.evaluated);- for change in &self.changes {- counter!(STAGE2_TRANSITIONS, "kind" => change.status.as_str()).increment(1);+ self.composed.record(STAGE2_TRANSITIONS);+ self.repairs.record(SEED_REGISTER_REPAIRS_TOTAL);+ }++ /// Fold a sibling recompute in, so one produce and one commit cover both halves.+ pub(crate) fn extend(&mut self, other: Self) {+ self.changes.extend(other.changes);+ self.writes.extend(other.writes);+ self.evaluated += other.evaluated;+ self.composed.add(other.composed);+ self.repairs.add(other.repairs);+ }++ /// Nothing to emit and nothing to commit.+ pub(crate) fn is_empty(&self) -> bool {+ self.changes.is_empty() && self.writes.is_empty()+ }+}++/// Per-status flip counts, kept so [`Stage2Recompute::record_metrics`] can attribute each half of a+/// folded recompute to its own metric without re-walking `changes`.+#[derive(Debug, Default, Clone, Copy)]+struct StatusCounts {+ entered: u64,+ left: u64,+}++impl StatusCounts {+ fn count(&mut self, status: MembershipStatus) {+ match status {+ MembershipStatus::Entered => self.entered += 1,+ MembershipStatus::Left => self.left += 1,+ }+ }++ fn add(&mut self, other: Self) {+ self.entered += other.entered;+ self.left += other.left;+ }++ /// A zero count emits nothing, so a path that cannot move the metric never creates its series.+ fn record(self, metric: &'static str) {+ for (count, status) in self.non_zero() {+ counter!(metric, "kind" => status.as_str()).increment(count);}}++ fn record_found(self, metric: &'static str, found: &'static str) {+ for (count, status) in self.non_zero() {+ counter!(metric, "kind" => status.as_str(), "found" => found).increment(count);+ }+ }++ fn non_zero(self) -> impl Iterator<Item = (u64, MembershipStatus)> {+ [+ (self.entered, MembershipStatus::Entered),+ (self.left, MembershipStatus::Left),+ ]+ .into_iter()+ .filter(|(count, _)| *count > 0)+ }+}++/// Register repairs split by what the diff found in the row. The split is what the read observed,+/// not why the row got that way: a row can disagree with the truth because a produce failed and+/// was redelivered, because the cohort was edited and its leaf key moved, or because a transfer+/// left a fallback behind, and nothing persisted tells those apart.+#[derive(Debug, Default, Clone, Copy)]+struct RepairCounts {+ /// No row at all — the register predates this apply.+ absent: StatusCounts,+ /// A row that did not decode; also counted on `STAGE2_STATE_DECODE_ERROR` at the read.+ corrupt: StatusCounts,+ /// A row that decoded and disagreed with the truth.+ mismatch: StatusCounts,+}++impl RepairCounts {+ fn add(&mut self, other: Self) {+ self.absent.add(other.absent);+ self.corrupt.add(other.corrupt);+ self.mismatch.add(other.mismatch);+ }++ fn record(self, metric: &'static str) {+ self.absent.record_found(metric, "absent");+ self.corrupt.record_found(metric, "corrupt");+ self.mismatch.record_found(metric, "mismatch");+ }}/// The read-only half of [`compose_stage2`].@@ -94,6 +186,7 @@ pub(crate) async fn recompute_stage2(let mut changes = Vec::new();let mut writes: Vec<(Stage2Key, Stage2State)> = Vec::new();let mut evaluated: u64 = 0;+ let mut composed = StatusCounts::default();for (cohort_id, person_id) in affected {let Some(tree) = filters.cohorts.get(&cohort_id) else {@@ -103,6 +196,7 @@ 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() {+ composed.count(diff.status());changes.push(CohortMembershipChange {team_id: tree.team_id.0,cohort_id: cohort_id.0,@@ -114,8 +208,9 @@ pub(crate) async fn recompute_stage2(});}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.+ // Write `false` rather than deleting so the retracted pair stays enumerable by the+ // reconcile scan. A no-flip transferred fallback is rewritten once so receiver+ // evaluation claims ownership.writes.push((diff.stage2_key,Stage2State {@@ -130,9 +225,243 @@ pub(crate) async fn recompute_stage2(changes,writes,evaluated,+ composed,+ ..Default::default()})}+/// One leaf a seed apply folded, with the membership its resulting state implies. The caller holds+/// that truth already, so the register diff never re-reads `cf_behavioral`.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) struct FoldedLeaf {+ pub leaf_state_key: LeafStateKey,+ pub person_id: Uuid,+ pub in_cohort: bool,+ /// Whether stage 1 minted a transition for this leaf in this apply. Only the fold knows it, and+ /// it is what separates an ordinary flip from a register repair in the metrics.+ pub minted_transition: bool,+}++impl FoldedLeaf {+ pub(crate) fn pair(self) -> (LeafStateKey, Uuid) {+ (self.leaf_state_key, self.person_id)+ }+}++/// What the single-leaf register diff decided for one apply.+#[must_use]+#[derive(Default)]+pub(crate) struct RegisterDiff {+ /// Changes to emit and the rows to commit after the ack; folds into the composed recompute.+ pub recompute: Stage2Recompute,+ /// Rows recording what downstream holds before this apply's emission. The caller stages them+ /// in stage 1, so a produce that then fails leaves the row disagreeing with the truth and the+ /// redelivery re-emits.+ pub stage1_writes: Vec<(Stage2Key, Stage2State)>,+}++/// Derive each single-leaf cohort's membership change from the folded leaf's truth and the+/// persisted register row, which on the seed paths records what downstream was last told.+///+/// An apply emits when stage 1 minted a transition, as the transition-derived paths do, or when+/// the stored bit disagrees with the truth, which is what a produce that never acked leaves+/// behind. An absent row says nothing, so it reads as "never told": an entry is emitted, a+/// non-member is not. A row that agrees with the truth never vetoes a minted transition: it can be+/// a stage-1 guess (the pre-write below) or the leftover of an apply that acked and then held+/// before its post-ack commit, and emitting on a transition is at worst a duplicate the LWW sink+/// absorbs.+///+/// Before an emission the row must read the opposite of the truth, so a failed produce is+/// re-derivable on redelivery; when it does not, stage 1 writes it. A silent apply leaves an+/// agreeing row alone, so an active reconcile scan is not dirtied, and does not write an absent+/// one, because nothing downstream needs a row for a person it was never told about. A corrupt row+/// is replaced with a readable bit even on a silent apply so it does not fail every later decode.+///+/// One batched `cf_stage2` read on `lane`. Leaves with no single-leaf cohort keyed on them cost+/// nothing.+pub(crate) async fn diff_single_leaf_registers(+ partition_id: u16,+ handle: &StoreHandle,+ filters: &TeamFilters,+ folded: &[FoldedLeaf],+ evaluated_at_ms: i64,+ last_updated: &str,+ lane: ReadLane,+) -> Result<RegisterDiff, StoreError> {+ // Ordered and deduplicated, so the read is one batch and the writes are deterministic.+ let mut wanted: BTreeMap<Stage2Key, WantedRegister> = BTreeMap::new();+ for leaf in folded {+ let Some(cohort_ids) = filters+ .by_lsk_to_single_leaf_cohorts+ .get(&leaf.leaf_state_key)+ else {+ continue;+ };+ for cohort_id in cohort_ids {+ let Some(tree) = filters.cohorts.get(cohort_id) else {+ continue;+ };+ let key = Stage2Key {+ partition_id,+ team_id: tree.team_id.0 as u64,+ cohort_id: cohort_id.0 as u64,+ person_id: leaf.person_id,+ };+ let previous = wanted.insert(+ key,+ WantedRegister {+ team_id: tree.team_id.0,+ cohort_id: *cohort_id,+ in_cohort: leaf.in_cohort,+ minted_transition: leaf.minted_transition,+ },+ );+ // A single-leaf cohort resolves to one leaf, so one apply reaches each row once.+ debug_assert!(+ previous.is_none_or(|prior| prior.in_cohort == leaf.in_cohort),+ "one apply folded {key:?} to two different memberships",+ );+ }+ }+ if wanted.is_empty() {+ return Ok(RegisterDiff::default());+ }++ let keys: Vec<Stage2Key> = wanted.keys().copied().collect();+ let stored = handle.multi_get_stage2(keys, lane).await?;+ // A short answer would zip one register's bytes onto another register's key and silently drop+ // the tail's emissions.+ if stored.len() != wanted.len() {+ return Err(StoreError::ShortRead {+ op: "multi_get_stage2",+ asked: wanted.len(),+ answered: stored.len(),+ });+ }++ let mut changes = Vec::new();+ let mut writes: Vec<(Stage2Key, Stage2State)> = Vec::new();+ let mut stage1_writes: Vec<(Stage2Key, Stage2State)> = Vec::new();+ let mut repairs = RepairCounts::default();+ for ((key, want), bytes) in wanted.into_iter().zip(stored) {+ let truth = want.in_cohort;+ let stored = read_register(bytes);+ let stored_bit = match stored {+ StoredRegister::Present(prior) => Some(prior.in_cohort),+ StoredRegister::Absent | StoredRegister::Corrupt => None,+ };+ let emits = want.minted_transition || stored_bit.map_or(truth, |bit| bit != truth);+ // What downstream is taken to hold before this apply: the value an emission retires, or+ // the truth when nothing is emitted.+ let before = if emits { !truth } else { truth };+ let records_before = match stored {+ StoredRegister::Present(prior) => prior.in_cohort != before,+ StoredRegister::Corrupt => true,+ StoredRegister::Absent => emits,+ };+ if records_before {+ stage1_writes.push((+ key,+ Stage2State {+ in_cohort: before,+ last_evaluated_at_ms: evaluated_at_ms,+ },+ ));+ }+ // A no-flip transferred fallback is still rewritten once, so receiver evaluation claims+ // the row the way the composed path claims its own.+ let claims_fallback = matches!(+ stored,+ StoredRegister::Present(prior) if prior.ownership == Stage2Ownership::TransferredFallback+ );+ if emits || claims_fallback {+ writes.push((+ key,+ Stage2State {+ in_cohort: truth,+ last_evaluated_at_ms: evaluated_at_ms,+ },+ ));+ }+ if !emits {+ continue;+ }+ let status = membership_status(truth);+ if !want.minted_transition {+ match stored {+ StoredRegister::Absent => repairs.absent.count(status),+ StoredRegister::Corrupt => repairs.corrupt.count(status),+ StoredRegister::Present(_) => repairs.mismatch.count(status),+ }+ }+ changes.push(CohortMembershipChange {+ team_id: want.team_id,+ cohort_id: want.cohort_id.0,+ person_id: key.person_id.to_string(),+ last_updated: last_updated.to_string(),+ status,+ origin: None,+ run_id: None,+ });+ }++ Ok(RegisterDiff {+ recompute: Stage2Recompute {+ changes,+ writes,+ // The register diff evaluates nothing, so `STAGE2_COHORTS_EVALUATED` keeps meaning+ // composed evaluations.+ evaluated: 0,+ repairs,+ ..Default::default()+ },+ stage1_writes,+ })+}++/// One `(single-leaf cohort, person)` the fold decided, before its stored row is read.+struct WantedRegister {+ team_id: i32,+ cohort_id: CohortId,+ in_cohort: bool,+ minted_transition: bool,+}++fn membership_status(in_cohort: bool) -> MembershipStatus {+ if in_cohort {+ MembershipStatus::Entered+ } else {+ MembershipStatus::Left+ }+}++/// What the store holds for one register row. Absence stays distinct from a stored `false`,+/// because the diff has to tell "never told" from "told `false`".+#[derive(Clone, Copy)]+enum StoredRegister {+ Absent,+ /// A row that exists but does not decode. It cannot say what downstream was told, so it reads+ /// as absent and is replaced with a decodable bit; counted on `STAGE2_STATE_DECODE_ERROR`.+ Corrupt,+ Present(PriorStage2State),+}++fn read_register(bytes: Option<Vec<u8>>) -> StoredRegister {+ let Some(bytes) = bytes else {+ return StoredRegister::Absent;+ };+ match Stage2State::decode_with_ownership(&bytes) {+ Ok((state, ownership)) => StoredRegister::Present(PriorStage2State {+ in_cohort: state.in_cohort,+ ownership,+ }),+ Err(_) => {+ counter!(STAGE2_STATE_DECODE_ERROR).increment(1);+ StoredRegister::Corrupt+ }+ }+}+/// Commit recomputed `cf_stage2` bits.pub(crate) async fn commit_stage2_writes(handle: &StoreHandle,@@ -442,6 +771,7 @@ fn decode_stage1_state(bytes: Option<Vec<u8>>) -> Option<Stage1State> {}}+#[derive(Clone, Copy)]struct PriorStage2State {in_cohort: bool,ownership: Stage2Ownership,@@ -1095,6 +1425,17 @@ mod tests {.unwrap();}+ /// A leaf whose stage 1 minted nothing this apply, which is what a redelivery or a+ /// catalog-added cohort looks like.+ fn folded(leaf_state_key: LeafStateKey, person_id: Uuid, in_cohort: bool) -> FoldedLeaf {+ FoldedLeaf {+ leaf_state_key,+ person_id,+ in_cohort,+ minted_transition: false,+ }+ }+fn single_leaf_lsk(filters: &TeamFilters, cohort: i32) -> LeafStateKey {match filters.eligibility[&CohortId(cohort)] {CohortEligibility::SingleLeaf(lsk) => lsk,@@ -1258,4 +1599,422 @@ mod tests {"no cf_stage2 bit written when the gate is off",);}+ // --- Single-leaf register diff ---++ /// The diff's whole rule set, one row per `(stored register, folded truth, minted transition)`+ /// cell. Each row states what downstream is told, what stage 1 records first, and what the+ /// post-ack commit writes.+ #[tokio::test]+ async fn register_diff_emits_on_a_minted_transition_or_a_lagging_register() {+ use MembershipStatus::{Entered, Left};+ // (stored, truth, minted) -> (change, stage-1 write, post-ack write, repairs)+ let cases = [+ (+ None,+ true,+ false,+ Some(Entered),+ Some(false),+ Some(true),+ (1, 0, 0),+ ),+ (+ None,+ true,+ true,+ Some(Entered),+ Some(false),+ Some(true),+ (0, 0, 0),+ ),+ (None, false, false, None, None, None, (0, 0, 0)),+ (+ None,+ false,+ true,+ Some(Left),+ Some(true),+ Some(false),+ (0, 0, 0),+ ),+ (+ Some(false),+ true,+ false,+ Some(Entered),+ None,+ Some(true),+ (0, 0, 1),+ ),+ (+ Some(false),+ true,+ true,+ Some(Entered),+ None,+ Some(true),+ (0, 0, 0),+ ),+ (+ Some(true),+ false,+ false,+ Some(Left),+ None,+ Some(false),+ (0, 0, 1),+ ),+ (+ Some(true),+ false,+ true,+ Some(Left),+ None,+ Some(false),+ (0, 0, 0),+ ),+ (Some(true), true, false, None, None, None, (0, 0, 0)),+ (+ Some(true),+ true,+ true,+ Some(Entered),+ Some(false),+ Some(true),+ (0, 0, 0),+ ),+ (Some(false), false, false, None, None, None, (0, 0, 0)),+ (+ Some(false),+ false,+ true,+ Some(Left),+ Some(true),+ Some(false),+ (0, 0, 0),+ ),+ ];+ for (stored, in_cohort, minted, want_change, want_stage1, want_post_ack, want_repairs) in+ cases+ {+ let why = format!("stored {stored:?}, truth {in_cohort}, minted {minted}");+ let (_dir, store) = temp_store();+ let filters = freeze(vec![behavioral_leaf(7)]);+ let lsk = single_leaf_lsk(&filters, 1);+ let alice = person(1);+ if let Some(bit) = stored {+ write_stage2(&store, 1, alice, bit);+ }++ let diff = diff_single_leaf_registers(+ PARTITION,+ &handle(&store),+ &filters,+ &[FoldedLeaf {+ leaf_state_key: lsk,+ person_id: alice,+ in_cohort,+ minted_transition: minted,+ }],+ EVENT_MS,+ TS,+ ReadLane::Maintenance,+ )+ .await+ .unwrap();++ assert_eq!(+ diff.recompute+ .changes+ .iter()+ .map(|change| change.status)+ .collect::<Vec<_>>(),+ want_change.into_iter().collect::<Vec<_>>(),+ "{why}",+ );+ assert_eq!(+ diff.stage1_writes+ .iter()+ .map(|(_, state)| state.in_cohort)+ .collect::<Vec<_>>(),+ want_stage1.into_iter().collect::<Vec<_>>(),+ "{why}: stage 1 records what downstream held before the emission",+ );+ assert_eq!(+ diff.recompute+ .writes+ .iter()+ .map(|(_, state)| state.in_cohort)+ .collect::<Vec<_>>(),+ want_post_ack.into_iter().collect::<Vec<_>>(),+ "{why}",+ );+ assert_eq!(repair_totals(diff.recompute.repairs), want_repairs, "{why}");+ assert_eq!(+ (+ diff.recompute.composed.entered,+ diff.recompute.composed.left+ ),+ (0, 0),+ "{why}: register changes are not composed transitions",+ );+ }+ }++ /// A register that already agrees with the post-transition truth cannot prove downstream was+ /// told: it is the pre-write of a retraction whose produce failed, or the row an apply left+ /// behind when it acked its membership and then held on its cascade. The minted transition+ /// wins, and the pre-write keeps its emission re-derivable if this produce fails too.+ #[tokio::test]+ async fn a_minted_transition_is_emitted_over_an_agreeing_register() {+ for (stored, status) in [+ (false, MembershipStatus::Left),+ (true, MembershipStatus::Entered),+ ] {+ let (_dir, store) = temp_store();+ let filters = freeze(vec![behavioral_leaf(7)]);+ let lsk = single_leaf_lsk(&filters, 1);+ let alice = person(1);+ write_stage2(&store, 1, alice, stored);++ let diff = diff_single_leaf_registers(+ PARTITION,+ &handle(&store),+ &filters,+ &[FoldedLeaf {+ leaf_state_key: lsk,+ person_id: alice,+ in_cohort: stored,+ minted_transition: true,+ }],+ EVENT_MS,+ TS,+ ReadLane::Maintenance,+ )+ .await+ .unwrap();++ assert_eq!(diff.recompute.changes.len(), 1, "register {stored}");+ assert_eq!(diff.recompute.changes[0].status, status);+ assert_eq!(+ diff.stage1_writes[0].1.in_cohort, !stored,+ "register {stored}: stage 1 first records the value this emission retires",+ );+ assert_eq!(+ diff.recompute.writes[0].1.in_cohort, stored,+ "the post-ack bit"+ );+ }+ }++ /// The change carries the cohort's own coordinates, not the leaf's, so it lands on the same+ /// row a transition-derived change would.+ #[tokio::test]+ async fn a_register_derived_change_addresses_the_single_leaf_cohort() {+ let (_dir, store) = temp_store();+ let filters = freeze(vec![behavioral_leaf(7)]);+ let lsk = single_leaf_lsk(&filters, 1);+ let alice = person(1);++ let diff = diff_single_leaf_registers(+ PARTITION,+ &handle(&store),+ &filters,+ &[folded(lsk, alice, true)],+ EVENT_MS,+ TS,+ ReadLane::Maintenance,+ )+ .await+ .unwrap();++ let change = &diff.recompute.changes[0];+ assert_eq!(change.cohort_id, 1);+ assert_eq!(change.team_id, TEAM as i32);+ assert_eq!(change.person_id, alice.to_string());+ assert_eq!(change.last_updated, TS);+ assert_eq!(diff.stage1_writes[0].0.cohort_id, 1);+ assert_eq!(diff.recompute.writes[0].0.person_id, alice);+ }++ /// A composable cohort's bit is `recompute_stage2`'s to own. Diffing it here too would emit+ /// every composed flip twice.+ #[tokio::test]+ async fn a_composable_cohorts_leaf_is_not_register_diffed() {+ let (_dir, store) = temp_store();+ let filters = freeze(vec![behavioral_leaf(7), person_leaf()]);+ let (beh_lsk, _) = and_leaf_keys(&filters);+ let alice = person(1);++ let diff = diff_single_leaf_registers(+ PARTITION,+ &handle(&store),+ &filters,+ &[folded(beh_lsk, alice, true)],+ EVENT_MS,+ TS,+ ReadLane::Maintenance,+ )+ .await+ .unwrap();++ assert!(diff.recompute.changes.is_empty());+ assert!(diff.recompute.writes.is_empty());+ assert!(diff.stage1_writes.is_empty());+ }++ /// Mirrors the composed path: a merge-carried fallback is claimed by the first local+ /// evaluation even when the bit it holds is already right.+ #[tokio::test]+ async fn a_transferred_fallback_is_rewritten_without_an_emission() {+ let (_dir, store) = temp_store();+ let filters = freeze(vec![behavioral_leaf(7)]);+ let lsk = single_leaf_lsk(&filters, 1);+ let alice = person(1);+ let key = Stage2Key {+ partition_id: PARTITION,+ team_id: TEAM,+ cohort_id: 1,+ person_id: alice,+ };+ let state = Stage2State {+ in_cohort: true,+ last_evaluated_at_ms: EVENT_MS,+ };+ store+ .write_batch(|b| b.put_stage2(&key, &state.encode_transferred_fallback()))+ .unwrap();++ let diff = diff_single_leaf_registers(+ PARTITION,+ &handle(&store),+ &filters,+ &[folded(lsk, alice, true)],+ EVENT_MS,+ TS,+ ReadLane::Maintenance,+ )+ .await+ .unwrap();++ assert!(diff.recompute.changes.is_empty(), "the bit did not flip");+ assert!(diff.stage1_writes.is_empty(), "the row agrees");+ assert_eq!(+ diff.recompute.writes,+ vec![(key, state)],+ "the fallback is claimed locally",+ );+ }++ /// An undecodable row cannot say what downstream was told, so it reads as absent: an entry is+ /// emitted, a non-member is not, and either way stage 1 replaces the row with a readable bit.+ #[tokio::test]+ async fn a_corrupt_register_row_reads_as_never_told_and_is_replaced() {+ for (in_cohort, minted, want_changes, want_stage1, want_repairs) in [+ (true, false, 1, false, (0, 1, 0)),+ (false, false, 0, false, (0, 0, 0)),+ (true, true, 1, false, (0, 0, 0)),+ (false, true, 1, true, (0, 0, 0)),+ ] {+ let (_dir, store) = temp_store();+ let filters = freeze(vec![behavioral_leaf(7)]);+ let lsk = single_leaf_lsk(&filters, 1);+ let alice = person(1);+ let key = Stage2Key {+ partition_id: PARTITION,+ team_id: TEAM,+ cohort_id: 1,+ person_id: alice,+ };+ store+ .write_batch(|b| b.put_stage2(&key, b"not a stage 2 state"))+ .unwrap();++ let diff = diff_single_leaf_registers(+ PARTITION,+ &handle(&store),+ &filters,+ &[FoldedLeaf {+ leaf_state_key: lsk,+ person_id: alice,+ in_cohort,+ minted_transition: minted,+ }],+ EVENT_MS,+ TS,+ ReadLane::Maintenance,+ )+ .await+ .unwrap();++ assert_eq!(+ diff.recompute.changes.len(),+ want_changes,+ "truth {in_cohort}, minted {minted}"+ );+ assert_eq!(+ diff.stage1_writes.len(),+ 1,+ "truth {in_cohort}, minted {minted}: the row is replaced"+ );+ assert_eq!(diff.stage1_writes[0].1.in_cohort, want_stage1);+ assert_eq!(repair_totals(diff.recompute.repairs), want_repairs);+ assert_eq!(+ (+ diff.recompute.composed.entered,+ diff.recompute.composed.left+ ),+ (0, 0),+ );+ }+ }++ fn repair_totals(repairs: RepairCounts) -> (u64, u64, u64) {+ let total = |counts: StatusCounts| counts.entered + counts.left;+ (+ total(repairs.absent),+ total(repairs.corrupt),+ total(repairs.mismatch),+ )+ }++ /// Two single-leaf cohorts on one leaf both diff, and a leaf the catalog does not back costs+ /// nothing. Those are the two halves of the fan-out the seed paths depend on.+ #[tokio::test]+ async fn the_diff_fans_out_to_every_single_leaf_cohort_on_the_leaf() {+ let (_dir, store) = temp_store();+ let filters = freeze_cascade(+ vec![(1, vec![behavioral_leaf(7)]), (2, vec![behavioral_leaf(7)])],+ false,+ );+ let lsk = single_leaf_lsk(&filters, 1);+ let alice = person(1);+ write_stage2(&store, 1, alice, true);++ let diff = diff_single_leaf_registers(+ PARTITION,+ &handle(&store),+ &filters,+ &[+ folded(lsk, alice, true),+ folded(LeafStateKey([0xEE; 16]), alice, true),+ ],+ EVENT_MS,+ TS,+ ReadLane::Maintenance,+ )+ .await+ .unwrap();++ assert_eq!(+ diff.recompute+ .changes+ .iter()+ .map(|change| change.cohort_id)+ .collect::<Vec<_>>(),+ vec![2],+ "cohort 1's register was already true; the unbacked leaf contributes nothing",+ );+ assert_eq!(diff.stage1_writes.len(), 1, "only cohort 2 had no row");+ }}diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rsindex 0fd3446d5b90..0e21c89e9c45 100644--- a/rust/cohort-stream-processor/src/workers/worker.rs+++ b/rust/cohort-stream-processor/src/workers/worker.rs@@ -854,6 +854,12 @@ async fn handle_sweep(EvictionAction::Write(bytes) => staged.put::<Behavioral>(&result.key, bytes),EvictionAction::Delete => staged.delete::<Behavioral>(&result.key),}+ // Keep this leg transition-based. The seed paths derive their single-leaf changes by+ // diffing this register, and between a seed's acked produce and its post-ack commit+ // the register reads `false` while downstream holds `Entered`. A register-diffed+ // sweep would compute `false == false` there and emit no `Left`, so the entry would+ // outlive the state that justified it. At most one of the path that emits an entry+ // and the path that retracts it may read the register.if let Some(transition) = &result.transition {if let Some(filters) = snapshot.team(transition.team_id) {stage_register_writes(diff --git a/rust/cohort-stream-processor/tests/seed_consumer.rs b/rust/cohort-stream-processor/tests/seed_consumer.rsindex a14a8abe12af..47d62bb32a6b 100644--- a/rust/cohort-stream-processor/tests/seed_consumer.rs+++ b/rust/cohort-stream-processor/tests/seed_consumer.rs@@ -16,9 +16,11 @@ use std::collections::{HashMap, HashSet};use std::future::Future;use std::num::NonZeroU32;use std::panic::AssertUnwindSafe;+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;use std::time::{Duration, Instant};+use async_trait::async_trait;use chrono_tz::UTC;use cohort_core::seed::{BehavioralShapeHash, ClaimEpoch, ConditionHash, ReconcileScope, ReconcileTile, RunId, SChunkMs,@@ -599,6 +601,9 @@ impl Instance {}}+/// `membership` replaces the Kafka membership sink, so a test can reach an ack shape a healthy+/// broker never produces; `None` keeps the production wiring.+#[allow(clippy::too_many_arguments)]async fn spawn_instance(topics: &Topics,groups: &Groups,@@ -606,6 +611,7 @@ async fn spawn_instance(catalog: CatalogHandle,handles: [Handle; 5],fence_margin_ms: i64,+ membership: Option<Arc<dyn MembershipSink>>,) -> Instance {let [events_handle, merge_handle, transfer_handle, cascade_handle, seed_handle] = handles;let kafka_config = producer_kafka_config();@@ -641,11 +647,14 @@ async fn spawn_instance(.await.expect("create seed re-key sink"),);- let membership_sink: Arc<dyn MembershipSink> = Arc::new(- KafkaMembershipSink::new(&kafka_config, topics.shadow.clone())- .await- .expect("create membership sink"),- );+ let membership_sink: Arc<dyn MembershipSink> = match membership {+ Some(sink) => sink,+ None => Arc::new(+ KafkaMembershipSink::new(&kafka_config, topics.shadow.clone())+ .await+ .expect("create membership sink"),+ ),+ };let marker_sink: Arc<dyn ReconcileMarkerSink> = Arc::new(KafkaReconcileMarkerSink::new(&kafka_config, topics.markers.clone()).await@@ -837,6 +846,7 @@ async fn seed_tile_applies_on_the_owning_worker_and_commits_to_the_hwm() {seed_catalog(),handles,2_000,+ None,).await;wait_for(@@ -904,6 +914,231 @@ async fn seed_tile_applies_on_the_owning_worker_and_commits_to_the_hwm() {.await;}+/// Wraps the real sink and fails its first produce, so the seed offset holds with nothing on the+/// topic, which is the crash point the redelivery has to repair.+struct FailFirstMembershipSink {+ inner: Arc<dyn MembershipSink>,+ fail_next: AtomicBool,+ failed: AtomicBool,+}++#[async_trait]+impl MembershipSink for FailFirstMembershipSink {+ async fn produce(+ &self,+ changes: Vec<CohortMembershipChange>,+ ) -> Vec<Result<(), common_kafka::kafka_producer::KafkaProduceError>> {+ if self.fail_next.swap(false, Ordering::SeqCst) {+ self.failed.store(true, Ordering::SeqCst);+ return changes+ .iter()+ .map(|_| Err(common_kafka::kafka_producer::KafkaProduceError::KafkaProduceCanceled))+ .collect();+ }+ self.inner.produce(changes).await+ }+}++/// Block until the apply has committed its stage-1 batch, which is what places the register row.+async fn await_register(instance: &Instance, key: &Stage2Key) -> Stage2State {+ let start = Instant::now();+ loop {+ if let Some(bytes) = instance+ .store+ .get_stage2(key, ReadLane::Maintenance)+ .await+ .expect("read register")+ {+ return Stage2State::decode(&bytes).expect("decode register");+ }+ assert!(+ start.elapsed() < Duration::from_secs(60),+ "the held tile never committed its placeholder register",+ );+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+}++/// Reopen the same on-disk store once the previous instance has released its RocksDB lock.+async fn reopen_store_live(dir: &TempDir) -> CohortStore {+ let config = StoreConfig {+ path: dir.path().join("db"),+ wipe_on_start: false,+ ..StoreConfig::default()+ };+ let start = Instant::now();+ loop {+ match CohortStore::open(&config) {+ Ok(store) => return store,+ Err(_) if start.elapsed() < Duration::from_secs(10) => {+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ Err(error) => panic!("failed to reopen store live: {error}"),+ }+ }+}++/// End to end through a real broker: the first instance commits stage 1 and then fails its+/// membership produce, so nothing reaches the topic and the seed offset holds. A second instance+/// over the same store re-derives the change from the register the first one never advanced.+#[tokio::test]+#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]+async fn a_failed_seed_produce_is_re_emitted_after_a_restart() {+ let suffix = Uuid::new_v4();+ let topics = Topics::unique(&suffix);+ let groups = Groups::unique(&suffix);+ with_topics_cleanup(&topics.names(), async {+ topics.create().await;+ let alice = Uuid::from_u128(0xA11CE);+ let register = Stage2Key {+ partition_id: part(alice),+ team_id: TEAM as u64,+ cohort_id: 1,+ person_id: alice,+ };+ let dir = TempDir::new().unwrap();+ let producer = murmur2_producer();+ let seed_sink = KafkaSeedTileSink::new(&producer_kafka_config(), topics.seeds.clone())+ .await+ .expect("create test seed sink");++ // First tenure: stage 1 commits, the membership produce fails.+ let mut manager = Manager::builder("seed-e2e-itest")+ .with_trap_signals(false)+ .build();+ let handles = register_instance(&mut manager);+ let shutdown = handles[0].clone();+ let monitor = manager.monitor_background();+ let failing = Arc::new(FailFirstMembershipSink {+ inner: Arc::new(+ KafkaMembershipSink::new(&producer_kafka_config(), topics.shadow.clone())+ .await+ .expect("create membership sink"),+ ),+ fail_next: AtomicBool::new(true),+ failed: AtomicBool::new(false),+ });+ let instance = spawn_instance(+ &topics,+ &groups,+ open_store(&dir),+ seed_catalog(),+ handles,+ 2_000,+ Some(failing.clone()),+ )+ .await;+ wait_for(+ "the consumer to own every partition",+ Duration::from_secs(30),+ || instance.owned().len() == NUM_PARTITIONS as usize,+ )+ .await;++ produce_warm_event(+ &producer,+ &topics.events,+ alice,+ 0,+ chrono::Utc::now().timestamp_millis(),+ )+ .await;+ produce_tile(+ &seed_sink,+ tile(alice, chrono::Utc::now().timestamp_millis() - 3_600_000),+ )+ .await;++ let seed_partition = part(alice);+ wait_for(+ "the first membership produce to fail",+ Duration::from_secs(60),+ || failing.failed.load(Ordering::SeqCst),+ )+ .await;+ assert!(+ !await_register(&instance, ®ister).await.in_cohort,+ "the bit must not advance past a failed produce",+ );+ assert_eq!(+ topic_message_count(&topics.shadow),+ 0,+ "nothing was emitted"+ );+ assert_eq!(+ instance.seed_committable(seed_partition),+ None,+ "the failed produce holds the seed offset",+ );++ shutdown.request_shutdown();+ instance.join().await;+ drop(monitor);++ // Second tenure over the same store: the redelivered tile merges to `Unchanged`, so only+ // the lagging register can say downstream was never told.+ let mut manager = Manager::builder("seed-e2e-itest")+ .with_trap_signals(false)+ .build();+ let handles = register_instance(&mut manager);+ let shutdown = handles[0].clone();+ let _monitor = manager.monitor_background();+ let instance = spawn_instance(+ &topics,+ &groups,+ reopen_store_live(&dir).await,+ seed_catalog(),+ handles,+ 2_000,+ None,+ )+ .await;+ wait_for(+ "the consumer to own every partition",+ Duration::from_secs(30),+ || instance.owned().len() == NUM_PARTITIONS as usize,+ )+ .await;+ // The new tenure resumes live consumption at its committed offset, so the apply fence+ // needs a fresh live event before it will re-admit the redelivered tile.+ produce_warm_event(+ &producer,+ &topics.events,+ alice,+ 1,+ chrono::Utc::now().timestamp_millis(),+ )+ .await;++ wait_for(+ "the re-derived flip on the shadow topic",+ Duration::from_secs(60),+ || topic_message_count(&topics.shadow) == 1,+ )+ .await;+ let changes = drain_membership_only(&topics.shadow, 1).await;+ assert_eq!(changes.len(), 1, "exactly one change, not a duplicate");+ assert_eq!(changes[0].person_id, alice.to_string());+ assert_eq!(changes[0].cohort_id, 1);+ assert_eq!(changes[0].status, MembershipStatus::Entered);+ assert_eq!(changes[0].origin, Some(ChangeOrigin::Seed));+ assert!(+ instance.stage2(®ister).await.in_cohort,+ "the bit advances once the re-emission acks",+ );+ wait_for(+ "the seed group's committed offset to reach the produced HWM",+ Duration::from_secs(30),+ || seed_group_committed(&groups.seeds, &topics.seeds, seed_partition as i32) == Some(1),+ )+ .await;++ shutdown.request_shutdown();+ instance.join().await;+ })+ .await;+}+/// Partition-targeted controls drain a full 64-partition snapshot, repair a stale membership bit,/// and release each seed offset only after that partition's completion marker is acknowledged.#[tokio::test]@@ -930,6 +1165,7 @@ async fn reconcile_snapshot_repairs_stale_state_and_commits_after_markers() {seed_catalog(),handles,2_000,+ None,).await;wait_for(@@ -1207,6 +1443,7 @@ async fn fence_holds_a_fresh_tile_until_live_consumption_passes_its_scan_point()seed_catalog(),handles,fence_margin_ms,+ None,).await;wait_for(diff --git a/rust/cohort-stream-processor/tests/stage1_worker.rs b/rust/cohort-stream-processor/tests/stage1_worker.rsindex f468f9662711..cffeb686bb81 100644--- a/rust/cohort-stream-processor/tests/stage1_worker.rs+++ b/rust/cohort-stream-processor/tests/stage1_worker.rs@@ -2502,9 +2502,10 @@ async fn seed_arm_flushes_buffered_event_changes_first_and_marks_both_trackers());}-/// A failed seed emission holds only the seed tracker; the events tracker is unaffected.+/// A failed seed emission holds only the seed tracker; the events tracker is unaffected, and the+/// next tenure's redelivery re-emits the lost change.#[tokio::test]-async fn seed_produce_failure_holds_the_seed_tracker_but_not_the_events_tracker() {+async fn seed_produce_failure_holds_only_the_seed_tracker_and_the_redelivery_re_emits() {let (_dir, store) = temp_store();let filters = build_team_filters(vec![(CohortId(1), cohort(vec![behavioral_leaf(7)]))]);let alice = person(1);@@ -2559,6 +2560,58 @@ async fn seed_produce_failure_holds_the_seed_tracker_but_not_the_events_tracker(let changes = sink.changes();assert_eq!(changes.len(), 1, "only the live flip landed");assert_eq!(changes[0].person_id, alice.to_string());++ // The next tenure re-assigns at the stored offset and redelivers the held tile. Its merge is+ // `Unchanged` and mints no transition, so only the persisted register can say downstream was+ // never told.+ let replay_sink = CaptureSink::new();+ let replay_deps = MergeWorkerDeps::capture();+ let replay_tracker = Arc::new(OffsetTracker::new());+ let (tx, rx) = mpsc::channel(16);+ let rx = MeteredReceiver::unmetered(rx);+ let worker = Stage1Worker::spawn(+ PARTITION_ID,+ rx,+ test_handle(&store),+ catalog_of(build_team_filters(vec![(+ CohortId(1),+ cohort(vec![behavioral_leaf(7)]),+ )])),+ Arc::new(replay_sink.clone()),+ replay_tracker.clone(),+ replay_deps.clone(),+ false,+ );+ replay_deps+ .seed_tracker+ .mark_dispatched(PARTITION_ID as i32, 8);+ tx.send(vec![seed_message(bob, utc_today(), 1, 7)])+ .await+ .unwrap();+ drop(tx);+ worker.join().await.unwrap();++ let changes = replay_sink.changes();+ assert_eq!(+ changes.len(),+ 1,+ "the redelivery re-derived the lost change"+ );+ assert_eq!(changes[0].person_id, bob.to_string());+ assert_eq!(changes[0].status, MembershipStatus::Entered);+ assert_eq!(+ replay_deps+ .seed_tracker+ .committable_offsets()+ .get(&(PARTITION_ID as i32)),+ Some(&8),+ "the seed offset commits once the re-emission acks",+ );+ assert_eq!(+ replay_deps.live_watermarks.get(PARTITION_ID as i32),+ None,+ "a seed-only batch never advances the live watermark",+ );}/// A held batch must not advance the watermark; the successful redelivery does.