Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(cohorts): wire type + processor apply path (#74979)

Matheus Batista6d1beb18b3f9
diff --git a/rust/cohort-core/src/seed/decode.rs b/rust/cohort-core/src/seed/decode.rs
index 0dfeb1bb11a8..f46f676075a0 100644
--- a/rust/cohort-core/src/seed/decode.rs
+++ b/rust/cohort-core/src/seed/decode.rs
@@ -6,6 +6,7 @@
use serde::Deserialize;
+use super::person::{PersonSeed, PERSON_KIND, PERSON_SCHEMA_VERSION};
use super::reconcile::{ReconcileTile, RECONCILE_KIND, RECONCILE_SCHEMA_VERSION};
use super::tile::{SeedTile, SCHEMA_VERSION, TILE_KIND};
@@ -15,6 +16,7 @@ use super::tile::{SeedTile, SCHEMA_VERSION, TILE_KIND};
pub enum DecodedSeed {
Tile(SeedTile),
Reconcile(ReconcileTile),
+ Person(PersonSeed),
UnknownKind { kind: String, schema_version: u32 },
UnsupportedSchema { kind: String, schema_version: u32 },
}
@@ -34,7 +36,10 @@ pub fn decode_seed(payload: &[u8]) -> Result<DecodedSeed, serde_json::Error> {
RECONCILE_KIND if probe.schema_version == RECONCILE_SCHEMA_VERSION => {
Ok(DecodedSeed::Reconcile(serde_json::from_slice(payload)?))
}
- TILE_KIND | RECONCILE_KIND => Ok(DecodedSeed::UnsupportedSchema {
+ PERSON_KIND if probe.schema_version == PERSON_SCHEMA_VERSION => {
+ Ok(DecodedSeed::Person(serde_json::from_slice(payload)?))
+ }
+ TILE_KIND | RECONCILE_KIND | PERSON_KIND => Ok(DecodedSeed::UnsupportedSchema {
kind: probe.kind,
schema_version: probe.schema_version,
}),
@@ -53,7 +58,8 @@ mod tests {
use crate::filters::TeamId;
use crate::seed::{
- BehavioralShapeHash, ClaimEpoch, ConditionHash, ReconcileTile, RunId, SChunkMs,
+ BehavioralShapeHash, ClaimEpoch, ConditionHash, PersonSeed, ReconcileTile, RunId, SChunkMs,
+ ScannedAtMs,
};
use super::*;
@@ -85,6 +91,22 @@ mod tests {
.unwrap()
}
+ fn person_json() -> serde_json::Value {
+ serde_json::to_value(
+ PersonSeed::new(
+ TeamId(2),
+ Uuid::from_u128(7),
+ vec![ConditionHash::parse("0123456789abcdef").unwrap()],
+ vec![ConditionHash::parse("0123456789abcdef").unwrap()],
+ ScannedAtMs(1_783_470_000_000),
+ RunId(Uuid::nil()),
+ ClaimEpoch(1),
+ )
+ .unwrap(),
+ )
+ .unwrap()
+ }
+
#[test]
fn decode_probes_kind_and_schema_before_the_full_parse() {
let tile = tile_json();
@@ -98,6 +120,27 @@ mod tests {
DecodedSeed::Reconcile(serde_json::from_value(reconcile.clone()).unwrap()),
);
+ let person = person_json();
+ assert_eq!(
+ decode(&person).unwrap(),
+ DecodedSeed::Person(serde_json::from_value(person.clone()).unwrap()),
+ );
+
+ let mut newer_person = person.clone();
+ newer_person["schema_version"] = serde_json::json!(2);
+ assert_eq!(
+ decode(&newer_person).unwrap(),
+ DecodedSeed::UnsupportedSchema {
+ kind: "person_property".to_string(),
+ schema_version: 2,
+ },
+ );
+
+ // Supported kind and schema, illegal body: a decode error, never a silent skip.
+ let mut broken_person = person;
+ broken_person["matched"] = serde_json::json!(["fedcba9876543210"]);
+ assert!(decode(&broken_person).is_err());
+
let mut unknown = tile.clone();
unknown["kind"] = serde_json::json!("future_control");
assert_eq!(
diff --git a/rust/cohort-core/src/seed/ids.rs b/rust/cohort-core/src/seed/ids.rs
index 98b0c566a515..58076d651238 100644
--- a/rust/cohort-core/src/seed/ids.rs
+++ b/rust/cohort-core/src/seed/ids.rs
@@ -1,6 +1,7 @@
-//! The seed contract's newtyped ids: `RunId`, `ClaimEpoch`, `SChunkMs`, and `ConditionHash`. They
-//! ride the [`super::tile::SeedTile`] wire and the seeder's PostgreSQL ledger (hence the `sqlx`
-//! derives), so both ends resolve them to the same types.
+//! The seed contract's newtyped ids: `RunId`, `ClaimEpoch`, `SChunkMs`, `ScannedAtMs`, and
+//! `ConditionHash`. They ride the [`super::tile::SeedTile`] / [`super::person::PersonSeed`] wires
+//! and the seeder's PostgreSQL ledger (hence the `sqlx` derives), so both ends resolve them to the
+//! same types.
use std::borrow::Borrow;
use std::fmt;
@@ -33,6 +34,16 @@ pub struct ClaimEpoch(pub i32);
#[sqlx(transparent)]
pub struct SChunkMs(pub i64);
+/// The persons-scan instant (epoch ms, UTC): the last-write-wins input the apply path weighs
+/// against the stored record's stamp. A separate type from [`SChunkMs`] so it cannot reach the
+/// apply fence, which it would answer wrongly.
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Type,
+)]
+#[serde(transparent)]
+#[sqlx(transparent)]
+pub struct ScannedAtMs(pub i64);
+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ConditionHash([u8; 16]);
diff --git a/rust/cohort-core/src/seed/mod.rs b/rust/cohort-core/src/seed/mod.rs
index 51ca40b7a450..999cc9518fe7 100644
--- a/rust/cohort-core/src/seed/mod.rs
+++ b/rust/cohort-core/src/seed/mod.rs
@@ -1,6 +1,7 @@
//! The seed wire contract shared by the backfill seeder (producer) and the stream processor
-//! (consumer): the [`SeedTile`] day-tile, [`ReconcileTile`] control tile, their newtypes, and the
-//! tolerant [`decode_seed`] entry point. Lives here — not in the seeder crate — for the same reason
+//! (consumer): the [`SeedTile`] day-tile, [`PersonSeed`] person-property verdict, [`ReconcileTile`]
+//! control tile, their newtypes, and the tolerant [`decode_seed`] entry point. Lives here — not in
+//! the seeder crate — for the same reason
//! as [`crate::events`]: both processes must agree on these bytes, and the processor cannot depend
//! on the seeder.
//!
@@ -11,11 +12,13 @@
pub mod decode;
pub mod ids;
+pub mod person;
pub mod reconcile;
pub mod tile;
pub use decode::{decode_seed, DecodedSeed};
-pub use ids::{ClaimEpoch, ConditionHash, ConditionHashError, RunId, SChunkMs};
+pub use ids::{ClaimEpoch, ConditionHash, ConditionHashError, RunId, SChunkMs, ScannedAtMs};
+pub use person::{PersonSeed, PersonSeedError, MAX_PERSON_SEED_HASHES};
pub use reconcile::{
BehavioralShapeHash, BehavioralShapeHashError, ReconcileCompleteMarker, ReconcileTile,
};
diff --git a/rust/cohort-core/src/seed/person.rs b/rust/cohort-core/src/seed/person.rs
new file mode 100644
index 000000000000..176a21b723ee
--- /dev/null
+++ b/rust/cohort-core/src/seed/person.rs
@@ -0,0 +1,507 @@
+//! [`PersonSeed`]: one person's person-property scan verdict, produced by the backfill seeder and
+//! applied by the stream processor to `cf_person_records`.
+//!
+//! Field order is the wire order. New fields must be appended and skipped at their
+//! absent-equivalent value (see `redirect_hops`), or bytes an older seeder produced stop parsing.
+//!
+//! Every change here is consumer-first. An older consumer ignores an unknown field, so a producer
+//! that starts populating one is silently half-understood; bumping the schema version instead
+//! routes the payload to `UnsupportedSchema`, which commits the offset without applying. Either way
+//! the consumer has to reach every pod before the producer emits.
+
+use serde::de::{Deserializer, Error as DeError, Unexpected};
+use serde::ser::{SerializeSeq, Serializer};
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use crate::filters::TeamId;
+
+use super::ids::{ClaimEpoch, ConditionHash, ConditionHashError, RunId, ScannedAtMs};
+
+pub(super) const PERSON_SCHEMA_VERSION: u32 = 1;
+pub(super) const PERSON_KIND: &str = "person_property";
+
+/// Decode guard bounding `evaluated`, and through the subset invariant `matched` too.
+pub const MAX_PERSON_SEED_HASHES: usize = 1024;
+
+/// `evaluated` is what the scan ran (sorted, distinct, non-empty); `matched ⊆ evaluated` is what
+/// came back TRUE. A hash in `evaluated` but not in `matched` asserts FALSE, which is what lets a
+/// seed retract a stale TRUE.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(try_from = "PersonSeedWire")]
+pub struct PersonSeed {
+ schema_version: u32,
+ kind: PersonKind,
+ #[serde(serialize_with = "serialize_team_id")]
+ team_id: TeamId,
+ person_id: Uuid,
+ #[serde(serialize_with = "serialize_hashes")]
+ evaluated: Vec<ConditionHash>,
+ #[serde(serialize_with = "serialize_hashes")]
+ matched: Vec<ConditionHash>,
+ scanned_at_ms: ScannedAtMs,
+ run_id: RunId,
+ claim_epoch: ClaimEpoch,
+ /// Times re-produced to a merge survivor's partition. Absent on the wire at 0.
+ #[serde(skip_serializing_if = "hops_are_zero")]
+ redirect_hops: u8,
+}
+
+impl PersonSeed {
+ /// The only constructor. [`Deserialize`] funnels through it too, so an illegal payload fails
+ /// to decode instead of half-applying.
+ pub fn new(
+ team_id: TeamId,
+ person_id: Uuid,
+ evaluated: Vec<ConditionHash>,
+ matched: Vec<ConditionHash>,
+ scanned_at_ms: ScannedAtMs,
+ run_id: RunId,
+ claim_epoch: ClaimEpoch,
+ ) -> Result<Self, PersonSeedError> {
+ if evaluated.is_empty() {
+ return Err(PersonSeedError::EvaluatedEmpty);
+ }
+ if evaluated.len() > MAX_PERSON_SEED_HASHES {
+ return Err(PersonSeedError::EvaluatedTooLarge(evaluated.len()));
+ }
+ if !is_strictly_sorted(&evaluated) {
+ return Err(PersonSeedError::EvaluatedNotSortedDistinct);
+ }
+ if !is_strictly_sorted(&matched) {
+ return Err(PersonSeedError::MatchedNotSortedDistinct);
+ }
+ if !is_subset(&matched, &evaluated) {
+ return Err(PersonSeedError::MatchedNotSubset);
+ }
+ if scanned_at_ms.0 <= 0 {
+ return Err(PersonSeedError::ScannedAtNotPositive(scanned_at_ms.0));
+ }
+ Ok(Self {
+ schema_version: PERSON_SCHEMA_VERSION,
+ kind: PersonKind,
+ team_id,
+ person_id,
+ evaluated,
+ matched,
+ scanned_at_ms,
+ run_id,
+ claim_epoch,
+ redirect_hops: 0,
+ })
+ }
+
+ /// The seed re-keyed to a merge survivor, or `None` once `cap` hops are exhausted, forcing the
+ /// caller to handle exhaustion explicitly.
+ #[must_use]
+ pub fn rekeyed_to(&self, survivor: Uuid, cap: u8) -> Option<Self> {
+ let redirect_hops = self
+ .redirect_hops
+ .checked_add(1)
+ .filter(|hops| *hops <= cap)?;
+ Some(Self {
+ person_id: survivor,
+ redirect_hops,
+ ..self.clone()
+ })
+ }
+
+ /// Must stay identical to [`super::tile::SeedTile::partition_key`]: both kinds have to land on
+ /// the worker that owns the person's state.
+ pub fn partition_key(&self) -> String {
+ format!("{}:{}", self.team_id.0, self.person_id)
+ }
+
+ pub const fn team_id(&self) -> TeamId {
+ self.team_id
+ }
+
+ pub const fn person_id(&self) -> Uuid {
+ self.person_id
+ }
+
+ pub fn evaluated(&self) -> &[ConditionHash] {
+ &self.evaluated
+ }
+
+ pub fn matched(&self) -> &[ConditionHash] {
+ &self.matched
+ }
+
+ pub const fn scanned_at_ms(&self) -> ScannedAtMs {
+ self.scanned_at_ms
+ }
+
+ pub const fn run_id(&self) -> RunId {
+ self.run_id
+ }
+
+ pub const fn claim_epoch(&self) -> ClaimEpoch {
+ self.claim_epoch
+ }
+
+ pub const fn redirect_hops(&self) -> u8 {
+ self.redirect_hops
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+pub enum PersonSeedError {
+ #[error("evaluated must not be empty: a seed that ran no condition asserts nothing")]
+ EvaluatedEmpty,
+ #[error("evaluated must hold at most {MAX_PERSON_SEED_HASHES} hashes, got {0}")]
+ EvaluatedTooLarge(usize),
+ #[error("evaluated must be sorted and distinct")]
+ EvaluatedNotSortedDistinct,
+ #[error("matched must be sorted and distinct")]
+ MatchedNotSortedDistinct,
+ #[error("matched must be a subset of evaluated")]
+ MatchedNotSubset,
+ /// An unset or negative scan instant would floor `last_seen_ms` below every TTL cutoff and
+ /// never win the apply path's last-write-wins comparison.
+ #[error("scanned_at_ms must be a positive epoch-ms instant, got {0}")]
+ ScannedAtNotPositive(i64),
+ #[error("malformed condition hash: {0}")]
+ Hash(#[from] ConditionHashError),
+}
+
+/// Raw strings for the hash lists, then one [`TryFrom`] into [`PersonSeed::new`]'s validation.
+#[derive(Deserialize)]
+struct PersonSeedWire {
+ #[serde(deserialize_with = "deserialize_schema_version")]
+ #[allow(dead_code)] // Validated by its deserializer, never read.
+ schema_version: u32,
+ #[allow(dead_code)] // Validated by its deserializer, never read.
+ kind: PersonKind,
+ #[serde(deserialize_with = "deserialize_team_id")]
+ team_id: TeamId,
+ person_id: Uuid,
+ evaluated: Vec<String>,
+ matched: Vec<String>,
+ scanned_at_ms: ScannedAtMs,
+ run_id: RunId,
+ claim_epoch: ClaimEpoch,
+ #[serde(default)]
+ redirect_hops: u8,
+}
+
+impl TryFrom<PersonSeedWire> for PersonSeed {
+ type Error = PersonSeedError;
+
+ fn try_from(wire: PersonSeedWire) -> Result<Self, Self::Error> {
+ let evaluated = parse_hashes(&wire.evaluated)?;
+ let matched = parse_hashes(&wire.matched)?;
+ let seed = Self::new(
+ wire.team_id,
+ wire.person_id,
+ evaluated,
+ matched,
+ wire.scanned_at_ms,
+ wire.run_id,
+ wire.claim_epoch,
+ )?;
+ // Reinstated outside the constructor, which only ever mints hop 0. The cap belongs to the
+ // re-keying caller (`rekeyed_to`), so validating it here would fork a second copy of a
+ // constant this crate does not own; an over-cap value is already unrepresentable as a
+ // further re-produce and degrades to an inline apply.
+ Ok(Self {
+ redirect_hops: wire.redirect_hops,
+ ..seed
+ })
+ }
+}
+
+fn parse_hashes(raw: &[String]) -> Result<Vec<ConditionHash>, ConditionHashError> {
+ raw.iter()
+ .map(|value| ConditionHash::parse(value))
+ .collect()
+}
+
+fn is_strictly_sorted(hashes: &[ConditionHash]) -> bool {
+ hashes.windows(2).all(|pair| pair[0] < pair[1])
+}
+
+/// Subset test over two sorted-distinct lists, in one merge walk.
+fn is_subset(subset: &[ConditionHash], superset: &[ConditionHash]) -> bool {
+ let mut candidates = superset.iter();
+ subset
+ .iter()
+ .all(|hash| candidates.any(|candidate| candidate == hash))
+}
+
+/// A zero-sized discriminant proven to be [`PERSON_KIND`] during deserialization.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+struct PersonKind;
+
+impl Serialize for PersonKind {
+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ serializer.serialize_str(PERSON_KIND)
+ }
+}
+
+impl<'de> Deserialize<'de> for PersonKind {
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let value = String::deserialize(deserializer)?;
+ if value != PERSON_KIND {
+ return Err(DeError::invalid_value(
+ Unexpected::Str(&value),
+ &"seed kind \"person_property\"",
+ ));
+ }
+ Ok(Self)
+ }
+}
+
+fn hops_are_zero(hops: &u8) -> bool {
+ *hops == 0
+}
+
+fn serialize_team_id<S: Serializer>(value: &TeamId, serializer: S) -> Result<S::Ok, S::Error> {
+ serializer.serialize_i32(value.0)
+}
+
+fn deserialize_team_id<'de, D: Deserializer<'de>>(deserializer: D) -> Result<TeamId, D::Error> {
+ i32::deserialize(deserializer).map(TeamId)
+}
+
+fn serialize_hashes<S: Serializer>(
+ hashes: &[ConditionHash],
+ serializer: S,
+) -> Result<S::Ok, S::Error> {
+ let mut sequence = serializer.serialize_seq(Some(hashes.len()))?;
+ for hash in hashes {
+ sequence.serialize_element(hash.as_str())?;
+ }
+ sequence.end()
+}
+
+fn deserialize_schema_version<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u32, D::Error> {
+ let value = u32::deserialize(deserializer)?;
+ if value != PERSON_SCHEMA_VERSION {
+ return Err(DeError::invalid_value(
+ Unexpected::Unsigned(u64::from(value)),
+ &"person seed schema version 1",
+ ));
+ }
+ Ok(value)
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::partitioner::{partition_for, COHORT_PARTITION_COUNT};
+
+ use super::*;
+
+ fn hash(value: &str) -> ConditionHash {
+ ConditionHash::parse(value).unwrap()
+ }
+
+ fn seed() -> PersonSeed {
+ PersonSeed::new(
+ TeamId(2),
+ Uuid::from_u128(0x0192_8aaa_bbbb_cccc_dddd_eeee_eeee_eeee),
+ vec![hash("0123456789abcdef"), hash("fedcba9876543210")],
+ vec![hash("0123456789abcdef")],
+ ScannedAtMs(1_783_470_000_000),
+ RunId(Uuid::nil()),
+ ClaimEpoch(4),
+ )
+ .unwrap()
+ }
+
+ #[test]
+ fn person_seed_wire_contract_and_partition_key_are_fixed_by_construction() {
+ let seed = seed();
+ assert_eq!(
+ seed.partition_key(),
+ "2:01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee",
+ );
+ assert_eq!(
+ partition_for(&seed.partition_key(), COHORT_PARTITION_COUNT),
+ 58,
+ "a person seed must route exactly like the same person's day tiles",
+ );
+ assert_eq!(
+ serde_json::to_string(&seed).unwrap(),
+ r#"{"schema_version":1,"kind":"person_property","team_id":2,"person_id":"01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee","evaluated":["0123456789abcdef","fedcba9876543210"],"matched":["0123456789abcdef"],"scanned_at_ms":1783470000000,"run_id":"00000000-0000-0000-0000-000000000000","claim_epoch":4}"#,
+ );
+ assert_eq!(
+ serde_json::from_str::<PersonSeed>(&serde_json::to_string(&seed).unwrap()).unwrap(),
+ seed,
+ );
+ }
+
+ #[test]
+ fn an_empty_matched_set_is_legal_and_is_the_stale_true_healing_case() {
+ let healing = PersonSeed::new(
+ TeamId(2),
+ Uuid::from_u128(7),
+ vec![hash("0123456789abcdef")],
+ Vec::new(),
+ ScannedAtMs(1),
+ RunId(Uuid::nil()),
+ ClaimEpoch(1),
+ )
+ .unwrap();
+ assert!(healing.matched().is_empty());
+ assert_eq!(
+ serde_json::from_value::<PersonSeed>(serde_json::to_value(&healing).unwrap()).unwrap(),
+ healing,
+ );
+ }
+
+ #[test]
+ fn the_constructor_rejects_every_illegal_hash_list() {
+ let build = |evaluated: Vec<ConditionHash>, matched: Vec<ConditionHash>| {
+ PersonSeed::new(
+ TeamId(2),
+ Uuid::from_u128(7),
+ evaluated,
+ matched,
+ ScannedAtMs(1),
+ RunId(Uuid::nil()),
+ ClaimEpoch(1),
+ )
+ };
+ let scanned_at = |ms: i64| {
+ PersonSeed::new(
+ TeamId(2),
+ Uuid::from_u128(7),
+ vec![hash("0123456789abcdef")],
+ Vec::new(),
+ ScannedAtMs(ms),
+ RunId(Uuid::nil()),
+ ClaimEpoch(1),
+ )
+ };
+ let a = hash("0123456789abcdef");
+ let b = hash("fedcba9876543210");
+
+ assert_eq!(
+ build(Vec::new(), Vec::new()),
+ Err(PersonSeedError::EvaluatedEmpty)
+ );
+ assert_eq!(
+ build(vec![a; MAX_PERSON_SEED_HASHES + 1], Vec::new()),
+ Err(PersonSeedError::EvaluatedTooLarge(
+ MAX_PERSON_SEED_HASHES + 1
+ )),
+ );
+ assert_eq!(
+ build(vec![b, a], Vec::new()),
+ Err(PersonSeedError::EvaluatedNotSortedDistinct),
+ );
+ assert_eq!(
+ build(vec![a, a], Vec::new()),
+ Err(PersonSeedError::EvaluatedNotSortedDistinct),
+ "a duplicate is as unrepresentable as a bad order",
+ );
+ assert_eq!(
+ build(vec![a, b], vec![b, a]),
+ Err(PersonSeedError::MatchedNotSortedDistinct),
+ );
+ assert_eq!(
+ build(vec![a], vec![b]),
+ Err(PersonSeedError::MatchedNotSubset),
+ "a matched hash the scan never evaluated cannot be applied",
+ );
+ assert_eq!(
+ scanned_at(0),
+ Err(PersonSeedError::ScannedAtNotPositive(0)),
+ "an unset scan instant floors last_seen below every TTL cutoff",
+ );
+ assert_eq!(
+ scanned_at(-1),
+ Err(PersonSeedError::ScannedAtNotPositive(-1))
+ );
+ assert!(scanned_at(1).is_ok());
+ }
+
+ #[test]
+ fn deserialize_funnels_through_the_same_validation_as_the_constructor() {
+ let golden = serde_json::to_value(seed()).unwrap();
+ for (field, value, why) in [
+ ("kind", serde_json::json!("behavioral_tile"), "foreign kind"),
+ ("schema_version", serde_json::json!(2), "newer schema"),
+ ("evaluated", serde_json::json!([]), "empty evaluated"),
+ (
+ "evaluated",
+ serde_json::json!(["fedcba9876543210", "0123456789abcdef"]),
+ "unsorted evaluated",
+ ),
+ (
+ "evaluated",
+ serde_json::json!(["0123456789abcdef", "0123456789abcdef"]),
+ "duplicate evaluated",
+ ),
+ (
+ "evaluated",
+ serde_json::json!(vec!["0123456789abcdef"; MAX_PERSON_SEED_HASHES + 1]),
+ "oversize evaluated",
+ ),
+ ("evaluated", serde_json::json!(["short"]), "malformed hash"),
+ (
+ "matched",
+ serde_json::json!(["00000000000000ff"]),
+ "matched outside evaluated",
+ ),
+ ("scanned_at_ms", serde_json::json!(0), "unset scan instant"),
+ ] {
+ let mut broken = golden.clone();
+ broken[field] = value;
+ assert!(
+ serde_json::from_value::<PersonSeed>(broken).is_err(),
+ "accepted a person seed with {why}",
+ );
+ }
+
+ // An unknown future field is ignored, so an older consumer keeps parsing a newer producer.
+ let mut extended = golden;
+ extended["future_metadata"] = serde_json::json!({ "source": "seeder" });
+ assert_eq!(
+ serde_json::from_value::<PersonSeed>(extended).unwrap(),
+ seed(),
+ );
+ }
+
+ #[test]
+ fn redirect_hops_are_absent_at_zero_and_roundtrip_when_set() {
+ let seed = seed();
+ assert!(!serde_json::to_string(&seed)
+ .unwrap()
+ .contains("redirect_hops"));
+
+ let hopped = seed
+ .rekeyed_to(Uuid::from_u128(1), 3)
+ .and_then(|seed| seed.rekeyed_to(Uuid::from_u128(2), 3))
+ .and_then(|seed| seed.rekeyed_to(Uuid::from_u128(3), 3))
+ .unwrap();
+ assert_eq!(hopped.redirect_hops(), 3);
+ let encoded = serde_json::to_string(&hopped).unwrap();
+ assert!(encoded.contains(r#""redirect_hops":3"#));
+ assert_eq!(
+ serde_json::from_str::<PersonSeed>(&encoded).unwrap(),
+ hopped
+ );
+ }
+
+ #[test]
+ fn rekeyed_to_swaps_the_person_rides_the_scan_instant_and_exhausts_at_the_cap() {
+ let seed = seed();
+ let survivor = Uuid::from_u128(0xdead_beef);
+ let rekeyed = seed.rekeyed_to(survivor, 2).unwrap();
+ assert_eq!(rekeyed.person_id(), survivor);
+ assert_eq!(rekeyed.redirect_hops(), 1);
+ assert_eq!(rekeyed.scanned_at_ms(), seed.scanned_at_ms());
+ assert_eq!(rekeyed.team_id(), seed.team_id());
+ assert_eq!(rekeyed.evaluated(), seed.evaluated());
+ assert_eq!(rekeyed.matched(), seed.matched());
+ assert_eq!(rekeyed.run_id(), seed.run_id());
+ assert_eq!(rekeyed.claim_epoch(), seed.claim_epoch());
+
+ let at_cap = rekeyed.rekeyed_to(survivor, 2).unwrap();
+ assert_eq!(at_cap.redirect_hops(), 2);
+ assert!(at_cap.rekeyed_to(survivor, 2).is_none());
+ assert!(seed.rekeyed_to(survivor, 0).is_none());
+ }
+}
diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rs
index ff112b1687bb..bcadddceb0ad 100644
--- a/rust/cohort-stream-processor/src/config.rs
+++ b/rust/cohort-stream-processor/src/config.rs
@@ -265,6 +265,17 @@ pub struct Config {
#[envconfig(from = "COHORT_SEED_RECONCILE_TICK_INTERVAL_MS", default = "2000")]
pub cohort_seed_reconcile_tick_interval_ms: u64,
+ /// Apply `person_property` seeds. Default off; while off they skip and commit, so a run
+ /// produced against a gate-off fleet has to be re-produced after enabling.
+ #[envconfig(from = "COHORT_SEED_PERSON_APPLY_ENABLED", default = "false")]
+ pub cohort_seed_person_apply_enabled: bool,
+
+ /// How far a person seed's scan instant must beat the stored record's stamp before it may
+ /// overwrite live-evaluated state (ms). Covers ClickHouse replication lag plus modest client
+ /// clock skew; ties go to live.
+ #[envconfig(from = "COHORT_SEED_PERSON_LIVE_MARGIN_MS", default = "900000")]
+ pub cohort_seed_person_live_margin_ms: i64,
+
/// Live-priority gate: pause a seed partition once its live watermark age reaches this (ms).
/// `0` disables the trigger.
#[envconfig(from = "COHORT_SEED_LIVE_LAG_PAUSE_MS", default = "120000")]
@@ -774,6 +785,31 @@ impl Config {
);
}
+ // A negative margin biases the person-seed verdict toward the seed, letting a stale scan
+ // overwrite fresher live state.
+ ensure!(
+ self.cohort_seed_person_live_margin_ms >= 0,
+ "COHORT_SEED_PERSON_LIVE_MARGIN_MS must not be negative.",
+ );
+
+ if self.cohort_seed_person_apply_enabled && !self.cohort_seed_consumer_enabled {
+ warn!(
+ "COHORT_SEED_PERSON_APPLY_ENABLED without COHORT_SEED_CONSUMER_ENABLED: no person \
+ seeds can be consumed; enable the seed consumer or turn person apply off.",
+ );
+ }
+
+ // 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.
+ 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.",
+ );
+ }
+
ensure!(
!self.checkpoint_enabled || self.durable_restore_enabled,
"CHECKPOINT_ENABLED requires DURABLE_RESTORE_ENABLED: restoring a checkpoint without \
@@ -1104,6 +1140,8 @@ mod tests {
cohort_seed_reconcile_enabled: false,
cohort_seed_reconcile_scan_page: 256,
cohort_seed_reconcile_tick_interval_ms: 2_000,
+ cohort_seed_person_apply_enabled: false,
+ cohort_seed_person_live_margin_ms: 900_000,
cohort_seed_live_lag_pause_ms: 120_000,
cohort_seed_live_lag_resume_ms: 60_000,
cohort_seed_disk_pause_pct: 60.0,
@@ -1176,6 +1214,38 @@ mod tests {
assert!(config.validate_startup().is_ok());
}
+ #[test]
+ fn person_seed_knobs_default_dark_and_refuse_a_negative_live_margin() {
+ let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();
+ assert!(!defaults.cohort_seed_person_apply_enabled);
+ assert_eq!(defaults.cohort_seed_person_live_margin_ms, 900_000);
+
+ let env: std::collections::HashMap<String, String> = [
+ ("COHORT_SEED_PERSON_APPLY_ENABLED", "true"),
+ ("COHORT_SEED_PERSON_LIVE_MARGIN_MS", "1234"),
+ ]
+ .into_iter()
+ .map(|(key, value)| (key.to_string(), value.to_string()))
+ .collect();
+ let config = Config::init_from_hashmap(&env).unwrap();
+ assert!(config.cohort_seed_person_apply_enabled);
+ assert_eq!(config.cohort_seed_person_live_margin_ms, 1234);
+
+ let mut negative = test_config();
+ negative.cohort_seed_person_live_margin_ms = -1;
+ assert!(negative
+ .validate_startup()
+ .unwrap_err()
+ .to_string()
+ .contains("COHORT_SEED_PERSON_LIVE_MARGIN_MS"));
+
+ // Apply-on without the consumer is a warning, not a refusal — same as reconcile.
+ let mut orphaned = test_config();
+ orphaned.cohort_seed_person_apply_enabled = true;
+ orphaned.cohort_seed_consumer_enabled = false;
+ assert!(orphaned.validate_startup().is_ok());
+ }
+
/// A flapping (inverted/equal) threshold pair or a never-releasing resume must be refused at
/// startup, not discovered as a wedged or flapping gate in production.
#[test]
diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rs
index 9ca77c1e74c9..1b3eca2c550b 100644
--- a/rust/cohort-stream-processor/src/consumers/events.rs
+++ b/rust/cohort-stream-processor/src/consumers/events.rs
@@ -1909,6 +1909,7 @@ mod tests {
// The dispatch tests exercise cross-partition register transfer end to end.
register_transfer_enabled: true,
reconcile,
+ person_seed: crate::workers::PersonSeedDeps::default(),
});
let dispatcher = EventDispatcher::new(
PartitionRouter::new(64),
@@ -2618,6 +2619,7 @@ mod tests {
live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),
register_transfer_enabled: false,
reconcile,
+ person_seed: crate::workers::PersonSeedDeps::default(),
});
let dispatcher = Arc::new(EventDispatcher::new(
PartitionRouter::new(64),
diff --git a/rust/cohort-stream-processor/src/consumers/seeds.rs b/rust/cohort-stream-processor/src/consumers/seeds.rs
index e3cb07f10765..42ae19f7287d 100644
--- a/rust/cohort-stream-processor/src/consumers/seeds.rs
+++ b/rust/cohort-stream-processor/src/consumers/seeds.rs
@@ -14,7 +14,7 @@ use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};
-use cohort_core::seed::{decode_seed, DecodedSeed, ReconcileTile, SChunkMs, SeedTile};
+use cohort_core::seed::{decode_seed, DecodedSeed, PersonSeed, ReconcileTile, SChunkMs, SeedTile};
use lifecycle::Handle;
use metrics::{counter, gauge, histogram};
use rdkafka::consumer::{CommitMode, Consumer, StreamConsumer};
@@ -74,6 +74,7 @@ impl SeedSkipReason {
#[derive(Debug)]
pub enum SeedWork {
Tile(SeedTile),
+ Person(PersonSeed),
Reconcile(ReconcileTile),
Skip(SeedSkipReason),
}
@@ -115,11 +116,12 @@ impl ConsumedSeed {
}
}
- /// The fence input; control messages and skips are fence-open.
+ /// The fence input. Control messages, person seeds, and skips are fence-open: none of them
+ /// bounds the arrival of events over the live stream.
fn s_chunk_ms(&self) -> Option<SChunkMs> {
match &self.work {
SeedWork::Tile(tile) => Some(tile.s_chunk_ms()),
- SeedWork::Reconcile(_) | SeedWork::Skip(_) => None,
+ SeedWork::Person(_) | SeedWork::Reconcile(_) | SeedWork::Skip(_) => None,
}
}
}
@@ -691,6 +693,7 @@ fn decode_payload(payload: Option<&[u8]>, partition: i32, offset: i64) -> SeedWo
};
match decode_seed(payload) {
Ok(DecodedSeed::Tile(tile)) => SeedWork::Tile(tile),
+ Ok(DecodedSeed::Person(seed)) => SeedWork::Person(seed),
Ok(DecodedSeed::Reconcile(tile)) => SeedWork::Reconcile(tile),
Ok(DecodedSeed::UnknownKind { kind, .. }) => {
debug!(partition, offset, kind, "skipping seed of unknown kind");
@@ -866,7 +869,8 @@ mod tests {
use std::num::NonZeroU32;
use cohort_core::seed::{
- BehavioralShapeHash, ClaimEpoch, ConditionHash, ReconcileTile, RunId, SChunkMs,
+ BehavioralShapeHash, ClaimEpoch, ConditionHash, PersonSeed, ReconcileTile, RunId, SChunkMs,
+ ScannedAtMs,
};
use uuid::Uuid;
@@ -908,6 +912,28 @@ mod tests {
}
}
+ fn person_seed() -> PersonSeed {
+ PersonSeed::new(
+ TeamId(2),
+ Uuid::from_u128(7),
+ vec![ConditionHash::parse("0123456789abcdef").unwrap()],
+ vec![ConditionHash::parse("0123456789abcdef").unwrap()],
+ ScannedAtMs(1_700_000_000_000),
+ RunId(Uuid::nil()),
+ ClaimEpoch(1),
+ )
+ .unwrap()
+ }
+
+ fn person(partition: i32, offset: i64) -> ConsumedSeed {
+ ConsumedSeed {
+ work: SeedWork::Person(person_seed()),
+ partition,
+ offset,
+ broker_ts_ms: None,
+ }
+ }
+
fn offsets(seeds: &[ConsumedSeed]) -> Vec<i64> {
seeds.iter().map(|seed| seed.offset).collect()
}
@@ -1257,6 +1283,15 @@ mod tests {
SeedWork::Reconcile(decoded) if decoded == reconcile,
));
+ // An undecodable person seed would skip-and-commit and never replay, so the decode arm has
+ // to land before any seeder emits the kind.
+ let person = person_seed();
+ let bytes = serde_json::to_vec(&person).unwrap();
+ assert!(matches!(
+ decode_payload(Some(&bytes), 0, 0),
+ SeedWork::Person(decoded) if decoded == person,
+ ));
+
let mut newer = serde_json::to_value(&tile).unwrap();
newer["schema_version"] = serde_json::json!(2);
let bytes = serde_json::to_vec(&newer).unwrap();
@@ -1345,6 +1380,38 @@ mod tests {
assert_eq!(offsets(&closed_prefix.held[&3]), vec![3, 4]);
}
+ #[test]
+ fn person_seeds_are_fence_open_but_never_leapfrog_a_held_partition() {
+ let none = HashSet::new();
+ let open_prefix = split_for_admission(
+ vec![person(3, 1), seed(3, 2, 0)],
+ &HashSet::new(),
+ &fence_only(&none, |_| None),
+ );
+ assert_eq!(offsets(&open_prefix.admitted), vec![1]);
+ assert_eq!(offsets(&open_prefix.held[&3]), vec![2]);
+
+ let closed_prefix = split_for_admission(
+ vec![seed(3, 3, 0), person(3, 4)],
+ &HashSet::new(),
+ &fence_only(&none, |_| None),
+ );
+ assert!(closed_prefix.admitted.is_empty());
+ assert_eq!(offsets(&closed_prefix.held[&3]), vec![3, 4]);
+
+ let watermarks = LiveWatermarks::new();
+ watermarks.observe(3, i64::MAX); // fence wide open — live-priority must hold regardless
+ let lagging = HashSet::from([3]);
+ let gated = split_for_admission(
+ vec![person(3, 5), person(3, 6)],
+ &HashSet::new(),
+ &fence_only(&lagging, |p| watermarks.get(p)),
+ );
+ assert!(gated.admitted.is_empty());
+ assert_eq!(offsets(&gated.held[&3]), vec![5, 6]);
+ assert_eq!(gated.causes[&3], causes_of(&[PauseCause::LiveLag]));
+ }
+
/// A wrong `true` declares a partition with unfolded live events idle — the fence's
/// fail-open direction.
#[test]
diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rs
index aec0e515655f..182c1f8fc0dc 100644
--- a/rust/cohort-stream-processor/src/main.rs
+++ b/rust/cohort-stream-processor/src/main.rs
@@ -44,7 +44,9 @@ use cohort_stream_processor::store::{CohortStore, StoreHandle};
use cohort_stream_processor::sweep::{
run_sweep_loop, run_sweep_loop_delayed, DispatchSweeper, ReconcileDrainSweeper,
};
-use cohort_stream_processor::workers::{MergeWorkerDeps, ReconcileBacklog, ReconcileDeps};
+use cohort_stream_processor::workers::{
+ MergeWorkerDeps, PersonSeedDeps, ReconcileBacklog, ReconcileDeps,
+};
common_alloc::used!();
@@ -242,6 +244,10 @@ async fn async_main(config: Config) -> Result<()> {
scan_page: config.cohort_seed_reconcile_scan_page,
backlog: reconcile_backlog.clone(),
},
+ person_seed: PersonSeedDeps {
+ enabled: config.cohort_seed_person_apply_enabled,
+ live_margin_ms: config.cohort_seed_person_live_margin_ms,
+ },
});
// Cheap `Arc` clones taken before the originals move into the dispatcher: the checkpoint sweeper
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
index 8e72f5f7451d..23acb5b463e3 100644
--- a/rust/cohort-stream-processor/src/observability/metrics.rs
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -471,6 +471,36 @@ pub const SEED_REKEYED_TOTAL: &str = "cohort_seed_rekeyed_total";
pub const SEED_REKEY_PRODUCE_FAILURE_TOTAL: &str = "cohort_seed_rekey_produce_failure_total";
/// Hop-capped tile redirects applied inline (counter). Non-zero means a corrupt tombstone cycle.
pub const SEED_REKEY_HOP_CAPPED_TOTAL: &str = "cohort_seed_rekey_hop_capped_total";
+
+/// Person seeds that wrote a record, labelled by `verdict`
+/// (`fresh`|`seed_newer`|`catalog_uncovered`) (counter).
+pub const PERSON_SEEDS_APPLIED_TOTAL: &str = "cohort_person_seeds_applied_total";
+/// Person seeds whose merge left the record unchanged (counter). The steady state of a re-run
+/// chunk.
+pub const PERSON_SEEDS_UNCHANGED_TOTAL: &str = "cohort_person_seeds_unchanged_total";
+/// Person seeds skipped and committed, labelled by `reason`
+/// (`apply_disabled`|`stale_vs_live`) (counter).
+pub const PERSON_SEEDS_SKIPPED_TOTAL: &str = "cohort_person_seeds_skipped_total";
+/// Person seeds dropped without a write, labelled by `reason`
+/// (`team_absent`|`no_effective_hashes`) (counter).
+pub const PERSON_SEEDS_DROPPED_TOTAL: &str = "cohort_person_seeds_dropped_total";
+/// Person seeds whose stored record existed but did not decode (counter). The apply then rebuilds
+/// from an absent baseline, dropping whatever the unreadable row held outside the seed's evaluated
+/// set. **Any non-zero value is a real record-codec failure, not a dormant person** — the event
+/// path's `stage1_person_record_total{result="corrupt"}` is the same signal for live traffic.
+pub const PERSON_SEED_PRIOR_CORRUPT_TOTAL: &str = "cohort_person_seed_prior_corrupt_total";
+/// Hashes dropped from a person seed's effective set, labelled by `reason`
+/// (`unknown_hash`|`variant_mismatch`) (counter). **Sustained non-zero means the run's pinned
+/// conditions have drifted from the live catalog.**
+pub const PERSON_SEED_HASHES_DROPPED_TOTAL: &str = "cohort_person_seed_hashes_dropped_total";
+/// Person seeds re-produced to a merge survivor's partition, counted post-ack (counter).
+pub const PERSON_SEED_REKEYED_TOTAL: &str = "cohort_person_seeds_rekeyed_total";
+/// Hop-capped person-seed redirects applied inline (counter). Non-zero means a corrupt tombstone
+/// cycle.
+pub const PERSON_SEED_REKEY_HOP_CAPPED_TOTAL: &str = "cohort_person_seeds_rekey_hop_capped_total";
+/// 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";
/// 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";
@@ -774,6 +804,42 @@ mod tests {
SEED_REKEY_HOP_CAPPED_TOTAL,
"cohort_seed_rekey_hop_capped_total"
);
+ assert_eq!(
+ PERSON_SEEDS_APPLIED_TOTAL,
+ "cohort_person_seeds_applied_total"
+ );
+ assert_eq!(
+ PERSON_SEEDS_UNCHANGED_TOTAL,
+ "cohort_person_seeds_unchanged_total"
+ );
+ assert_eq!(
+ PERSON_SEEDS_SKIPPED_TOTAL,
+ "cohort_person_seeds_skipped_total"
+ );
+ assert_eq!(
+ PERSON_SEEDS_DROPPED_TOTAL,
+ "cohort_person_seeds_dropped_total"
+ );
+ assert_eq!(
+ PERSON_SEED_PRIOR_CORRUPT_TOTAL,
+ "cohort_person_seed_prior_corrupt_total",
+ );
+ assert_eq!(
+ PERSON_SEED_HASHES_DROPPED_TOTAL,
+ "cohort_person_seed_hashes_dropped_total",
+ );
+ assert_eq!(
+ PERSON_SEED_REKEYED_TOTAL,
+ "cohort_person_seeds_rekeyed_total"
+ );
+ assert_eq!(
+ PERSON_SEED_REKEY_HOP_CAPPED_TOTAL,
+ "cohort_person_seeds_rekey_hop_capped_total",
+ );
+ assert_eq!(
+ PERSON_SEED_REKEY_PRODUCE_FAILURE_TOTAL,
+ "cohort_person_seeds_rekey_produce_failure_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/producer/seed.rs b/rust/cohort-stream-processor/src/producer/seed.rs
index 5498e1c498ab..44c33992f6cd 100644
--- a/rust/cohort-stream-processor/src/producer/seed.rs
+++ b/rust/cohort-stream-processor/src/producer/seed.rs
@@ -1,9 +1,9 @@
-//! Re-key producer for `cohort_stream_seed_events`: cross-partition-merged tiles are re-produced
-//! to the survivor's partition, keyed exactly as the seeder keys them.
+//! Re-key producer for `cohort_stream_seed_events`: cross-partition-merged seeds of either kind are
+//! re-produced to the survivor's partition, keyed exactly as the seeder keys them.
use anyhow::{Context, Result};
use async_trait::async_trait;
-use cohort_core::seed::SeedTile;
+use cohort_core::seed::{PersonSeed, SeedTile};
use common_kafka::config::KafkaConfig;
use common_kafka::kafka_producer::{
create_kafka_producer, send_keyed_iter_to_kafka_with_headers, KafkaContext, KafkaProduceError,
@@ -16,6 +16,8 @@ use crate::producer::merge::Capture;
#[async_trait]
pub trait SeedTileSink: Send + Sync {
async fn produce(&self, tiles: Vec<SeedTile>) -> Vec<Result<(), KafkaProduceError>>;
+
+ async fn produce_person(&self, seeds: Vec<PersonSeed>) -> Vec<Result<(), KafkaProduceError>>;
}
pub struct KafkaSeedTileSink {
@@ -44,6 +46,17 @@ impl SeedTileSink for KafkaSeedTileSink {
)
.await
}
+
+ async fn produce_person(&self, seeds: Vec<PersonSeed>) -> Vec<Result<(), KafkaProduceError>> {
+ send_keyed_iter_to_kafka_with_headers(
+ &self.producer,
+ &self.topic,
+ |seed| Some(seed.partition_key()),
+ |_| None,
+ seeds,
+ )
+ .await
+ }
}
/// Inert sink for gate-off deploys: a produce is a coding error made loud, not a silent drop.
@@ -57,43 +70,57 @@ impl SeedTileSink for NoopSeedTileSink {
.map(|_| Err(KafkaProduceError::KafkaProduceCanceled))
.collect()
}
+
+ async fn produce_person(&self, seeds: Vec<PersonSeed>) -> Vec<Result<(), KafkaProduceError>> {
+ seeds
+ .into_iter()
+ .map(|_| Err(KafkaProduceError::KafkaProduceCanceled))
+ .collect()
+ }
}
-pub struct CaptureSeedTileSink(Capture<SeedTile>);
+/// Independent failure budgets per kind, so a test can fail one leg without arming the other.
+#[derive(Clone, Default)]
+pub struct CaptureSeedTileSink {
+ tiles: Capture<SeedTile>,
+ persons: Capture<PersonSeed>,
+}
impl CaptureSeedTileSink {
pub fn new() -> Self {
- Self(Capture::default())
+ Self::default()
}
pub fn failing_first(n: usize) -> Self {
- Self(Capture::failing_first(n))
+ Self {
+ tiles: Capture::failing_first(n),
+ persons: Capture::failing_first(n),
+ }
}
pub fn failing_always() -> Self {
- Self(Capture::failing_always())
+ Self {
+ tiles: Capture::failing_always(),
+ persons: Capture::failing_always(),
+ }
}
pub fn tiles(&self) -> Vec<SeedTile> {
- self.0.recorded()
- }
-}
-
-impl Default for CaptureSeedTileSink {
- fn default() -> Self {
- Self::new()
+ self.tiles.recorded()
}
-}
-impl Clone for CaptureSeedTileSink {
- fn clone(&self) -> Self {
- Self(self.0.clone())
+ pub fn person_seeds(&self) -> Vec<PersonSeed> {
+ self.persons.recorded()
}
}
#[async_trait]
impl SeedTileSink for CaptureSeedTileSink {
async fn produce(&self, tiles: Vec<SeedTile>) -> Vec<Result<(), KafkaProduceError>> {
- self.0.produce(tiles)
+ self.tiles.produce(tiles)
+ }
+
+ async fn produce_person(&self, seeds: Vec<PersonSeed>) -> Vec<Result<(), KafkaProduceError>> {
+ self.persons.produce(seeds)
}
}
diff --git a/rust/cohort-stream-processor/src/stage1/person_record.rs b/rust/cohort-stream-processor/src/stage1/person_record.rs
index a633778b9ed3..038ff30e7d96 100644
--- a/rust/cohort-stream-processor/src/stage1/person_record.rs
+++ b/rust/cohort-stream-processor/src/stage1/person_record.rs
@@ -17,7 +17,8 @@
//!
//! The [`decide`] / `apply_*` split is a pure, table-testable core with no store, HogVM, or clock:
//! [`decide`] classifies an event against the prior record into a [`Decision`], and the `apply_*`
-//! constructors build the next record for each arm.
+//! constructors build the next record for each arm. [`person_seed_verdict`] / [`apply_person_seed`]
+//! are the same split for the backfill's person seeds.
use std::collections::BTreeMap;
@@ -26,6 +27,7 @@ use sha2::{Digest, Sha256};
use uuid::Uuid;
pub use cohort_core::fingerprint::CatalogFingerprint;
+use cohort_core::seed::ScannedAtMs;
use crate::stage1::state::{dedup_is_replay, dedup_record, AppliedOffsets};
use crate::stage1::transition::TransitionKind;
@@ -213,6 +215,12 @@ impl PersonRecord {
}
}
+ /// Whether the stored fingerprints came from a live evaluation. [`apply_person_seed`] zeroes
+ /// both, so a seed-written record carries no evidence of what any catalog covered.
+ fn is_live_evaluated(&self) -> bool {
+ self.props_fingerprint != PropsFingerprint(0)
+ }
+
/// Origin-aware replay check, sharing the row-level implementation so the two cannot drift.
pub fn is_replay_for(&self, origin: Option<&Uuid>, sp: i32, so: i64) -> bool {
dedup_is_replay(&self.applied_offsets, &self.redirect_dedup, origin, sp, so)
@@ -466,6 +474,149 @@ pub fn apply_eval(
(next, transitions)
}
+// --- Person-property seed (backfill) ---
+
+/// Whether a person seed may overwrite the stored record's person-property state.
+///
+/// Whole-record, not per-hash: the record keeps one [`Stamp`] and one [`CatalogFingerprint`] for
+/// the whole person, so which hashes its last evaluation covered is unrecoverable.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum PersonSeedVerdict {
+ /// Absent or corrupt record.
+ ApplyFresh,
+ /// The scan ran, margin-adjusted, after the record's last live evaluation.
+ ApplySeedNewer,
+ /// Live-fresh, but evaluated against a different catalog, so it cannot have covered the seed's
+ /// hashes.
+ ApplyCatalogUncovered,
+ /// The stored state already subsumes the seed: a catalog-covered live evaluation, or another
+ /// seed's write this scan does not beat.
+ SkipLiveFresh,
+}
+
+impl PersonSeedVerdict {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::ApplyFresh => "fresh",
+ Self::ApplySeedNewer => "seed_newer",
+ Self::ApplyCatalogUncovered => "catalog_uncovered",
+ Self::SkipLiveFresh => "live_fresh",
+ }
+ }
+}
+
+/// Classify one person seed against the prior record. Pure: no store, HogVM, or clock.
+///
+/// `scanned_at` is the seeder's wall clock; `record.stamp.ms` is client event time. Two different
+/// clocks, so the seed must beat the record by `live_margin_ms` rather than merely tie it. A tie
+/// resolved for the seed lets a stale scan overwrite fresher live state.
+///
+/// Both apply arms need the scan to be at least as recent as the record. The catalog fingerprint
+/// covers every person condition in the team, so one unrelated cohort edit rotates it for every
+/// record at once; without the recency test an arbitrarily old scan would overwrite live state on
+/// the strength of an edit it had nothing to do with. What survives the test is the window between
+/// the two clocks, where a record can carry a newer stamp than the scan and still have been
+/// evaluated against a catalog that predates the seed's conditions.
+///
+/// Seed-over-seed ordering is [`ApplySeedNewer`](PersonSeedVerdict::ApplySeedNewer)'s alone: a seed
+/// installs [`seed_stamp_floor`], so the margin cancels and the test reduces to "this scan ran after
+/// the one that wrote this record".
+pub fn person_seed_verdict(
+ prior: &PriorRecord,
+ scanned_at: ScannedAtMs,
+ live_margin_ms: i64,
+ catalog_fp: CatalogFingerprint,
+) -> PersonSeedVerdict {
+ let PriorRecord::Present(record) = prior else {
+ return PersonSeedVerdict::ApplyFresh;
+ };
+ if scanned_at.0.saturating_sub(live_margin_ms) > record.stamp.ms {
+ return PersonSeedVerdict::ApplySeedNewer;
+ }
+ // Only a live evaluation's fingerprint mismatch proves the record missed the seed's hashes. A
+ // seed zeroed its own, so admitting on that would re-admit every seed scanned within a margin of
+ // an earlier one's floor, letting the older scan retract what the newer one matched.
+ if record.is_live_evaluated()
+ && record.catalog_fingerprint != catalog_fp
+ && scanned_at.0 >= record.stamp.ms
+ {
+ return PersonSeedVerdict::ApplyCatalogUncovered;
+ }
+ PersonSeedVerdict::SkipLiveFresh
+}
+
+#[must_use]
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum PersonSeedOutcome {
+ Changed {
+ record: PersonRecord,
+ transitions: Vec<([u8; 16], TransitionKind)>,
+ },
+ /// The seed asserted what the record already held. Nothing is written, so an absent record with
+ /// no matches is never created and store growth stays proportional to matchers.
+ Unchanged,
+}
+
+/// Merge one person seed into `prior`, restricted to the hashes the scan evaluated.
+///
+/// A seed speaks only for `evaluated` (`E`, sorted and distinct) and `matched` (`T ⊆ E`), so
+/// passing `E` where [`apply_eval`] passes the catalog yields the subset semantics: the stored set
+/// becomes `T ∪ (S \ E)`, `Entered = T \ S`, and `Left = (S ∩ E) \ T`.
+///
+/// Both fingerprints are zeroed on a change so the record never claims a full-catalog evaluation;
+/// that is what forces a full `Eval` on the person's next event. `last_seen_ms` takes the scan
+/// instant as a floor, without which a record built from [`PersonRecord::absent`] starts at
+/// `i64::MIN` and is immediately TTL-eligible.
+///
+/// The stamp is raised to [`seed_stamp_floor`] but never lowered, and both dedup maps are left
+/// alone — seed-topic offsets share no numbering with the live topic's.
+pub fn apply_person_seed(
+ prior: &PersonRecord,
+ evaluated: &[[u8; 16]],
+ matched: &MatchedSet,
+ scanned_at: ScannedAtMs,
+ live_margin_ms: i64,
+) -> PersonSeedOutcome {
+ debug_assert_sorted(evaluated);
+ let transitions: Vec<_> = prior.matched.diff(matched, evaluated).collect();
+ // No transition ⇒ `T ∪ (S \ E)` equals `S`: every hash in `T` was already in `S` (else
+ // `Entered`) and every hash of `S ∩ E` is still in `T` (else `Left`).
+ if transitions.is_empty() {
+ return PersonSeedOutcome::Unchanged;
+ }
+
+ let untouched = prior
+ .matched
+ .iter()
+ .copied()
+ .filter(|hash| evaluated.binary_search(hash).is_err());
+ let stored: MatchedSet = matched.iter().copied().chain(untouched).collect();
+
+ let mut record = prior.clone();
+ record.matched = stored;
+ record.props_fingerprint = PropsFingerprint(0);
+ record.catalog_fingerprint = CatalogFingerprint(0);
+ record.last_seen_ms = record.last_seen_ms.max(scanned_at.0);
+ record.stamp = record
+ .stamp
+ .max(seed_stamp_floor(scanned_at, live_margin_ms));
+ PersonSeedOutcome::Changed {
+ record,
+ transitions,
+ }
+}
+
+/// The argMax floor a seed installs. An event older than this lost to the scan, so it must not
+/// re-evaluate the person and revert the seed — for a dormant person nothing newer would ever
+/// arrive to correct it. Margin-adjusted for the same two-clock reason [`person_seed_verdict`]
+/// applies it, and offset-minimal so an event exactly at the floor still counts as fresher.
+///
+/// Anything above the floor still takes `Eval` against the zeroed fingerprints, which is what keeps
+/// the seed from suppressing a genuinely newer evaluation.
+fn seed_stamp_floor(scanned_at: ScannedAtMs, live_margin_ms: i64) -> Stamp {
+ Stamp::new(scanned_at.0.saturating_sub(live_margin_ms), i64::MIN)
+}
+
// --- Binary codec v1 ---
/// The on-disk format version. A decode of any other value is a typed error, so an incompatible
@@ -735,6 +886,8 @@ fn array<const N: usize>(slice: &[u8]) -> [u8; N] {
#[cfg(test)]
mod tests {
+ use proptest::prelude::*;
+
use super::*;
fn hash(byte: u8) -> [u8; 16] {
@@ -1136,6 +1289,324 @@ mod tests {
assert_eq!(next.catalog_fingerprint, new_catalog);
}
+ // --- person-property seed (backfill) ---
+
+ /// Matches `COHORT_SEED_PERSON_LIVE_MARGIN_MS`'s default.
+ const MARGIN: i64 = 900_000;
+
+ fn at(ms: i64) -> ScannedAtMs {
+ ScannedAtMs(ms)
+ }
+
+ /// A live-written record: stamped at `stamp_ms`, evaluated against `catalog`.
+ fn live_record(stamp_ms: i64, catalog: CatalogFingerprint) -> PriorRecord {
+ let mut record = sample_record();
+ record.stamp = Stamp::new(stamp_ms, 0);
+ record.catalog_fingerprint = catalog;
+ PriorRecord::Present(record)
+ }
+
+ #[test]
+ fn person_seed_verdict_truth_table() {
+ let catalog = CatalogFingerprint::of_sorted(&[hash(1), hash(2)]);
+ let other = CatalogFingerprint::of_sorted(&[hash(1)]);
+ // What a seed scanned at 1_000_000 leaves behind: both fingerprints zeroed, stamp at the
+ // floor. Built through the merge so the fixture cannot drift from what a seed really writes.
+ let seed_written = |scanned_at: ScannedAtMs| {
+ let PersonSeedOutcome::Changed { record, .. } = apply_person_seed(
+ &PersonRecord::absent(),
+ &[hash(1)],
+ &MatchedSet::from_iter([hash(1)]),
+ scanned_at,
+ MARGIN,
+ ) else {
+ panic!("a seed matching a hash on an absent record writes");
+ };
+ PriorRecord::Present(record)
+ };
+
+ let cases = [
+ (
+ PriorRecord::Absent,
+ at(1_000),
+ PersonSeedVerdict::ApplyFresh,
+ "no record at all is the dormant-person case",
+ ),
+ (
+ PriorRecord::Corrupt,
+ at(1_000),
+ PersonSeedVerdict::ApplyFresh,
+ "a corrupt row re-evaluates rather than freezing membership",
+ ),
+ (
+ live_record(1_000_000, catalog),
+ at(1_000_000 + MARGIN + 1),
+ PersonSeedVerdict::ApplySeedNewer,
+ "the scan beat the record's stamp by more than the margin",
+ ),
+ (
+ live_record(1_000_000, catalog),
+ at(1_000_000 + MARGIN),
+ PersonSeedVerdict::SkipLiveFresh,
+ "exactly at the margin is not newer: ties go to live",
+ ),
+ (
+ live_record(1_000_000, catalog),
+ at(0),
+ PersonSeedVerdict::SkipLiveFresh,
+ "a stale scan never overwrites covered live state",
+ ),
+ (
+ live_record(1_000_000, other),
+ at(0),
+ PersonSeedVerdict::SkipLiveFresh,
+ "a rotated catalog does not license an older scan to overwrite a newer record",
+ ),
+ (
+ live_record(1_000_000, other),
+ at(1_000_000),
+ PersonSeedVerdict::ApplyCatalogUncovered,
+ "same instant, rotated catalog: the record cannot have covered the seed's hashes",
+ ),
+ (
+ live_record(1_000_000, other),
+ at(1_000_000 + MARGIN),
+ PersonSeedVerdict::ApplyCatalogUncovered,
+ "inside the margin the record is not provably older, but the catalog rotated",
+ ),
+ (
+ live_record(i64::MAX, catalog),
+ at(i64::MIN),
+ PersonSeedVerdict::SkipLiveFresh,
+ "the margin subtraction must saturate, not overflow",
+ ),
+ (
+ seed_written(at(1_000_000)),
+ at(1_000_000),
+ PersonSeedVerdict::SkipLiveFresh,
+ "a seed's own replay adds nothing: the zeroed fingerprints are its write, not an \
+ uncovered live evaluation",
+ ),
+ (
+ seed_written(at(1_000_000)),
+ at(1_000_000 - MARGIN + 1),
+ PersonSeedVerdict::SkipLiveFresh,
+ "an older overlapping scan sits above the floor a newer seed installed, and must \
+ not retract what that scan matched",
+ ),
+ (
+ seed_written(at(1_000_000)),
+ at(1_000_001),
+ PersonSeedVerdict::ApplySeedNewer,
+ "the floor cancels the margin between two seeds, so a later scan still wins",
+ ),
+ ];
+
+ for (prior, scanned_at, expected, why) in cases {
+ assert_eq!(
+ person_seed_verdict(&prior, scanned_at, MARGIN, catalog),
+ expected,
+ "{why}",
+ );
+ }
+ assert_eq!(PersonSeedVerdict::ApplyFresh.as_str(), "fresh");
+ assert_eq!(PersonSeedVerdict::ApplySeedNewer.as_str(), "seed_newer");
+ assert_eq!(
+ PersonSeedVerdict::ApplyCatalogUncovered.as_str(),
+ "catalog_uncovered",
+ );
+ assert_eq!(PersonSeedVerdict::SkipLiveFresh.as_str(), "live_fresh");
+ }
+
+ #[test]
+ fn apply_person_seed_mints_transitions_only_inside_the_evaluated_set() {
+ let mut prior = PersonRecord::absent();
+ prior.matched = MatchedSet::from_iter([hash(1), hash(2), hash(9)]);
+ let evaluated = [hash(1), hash(2), hash(3)];
+
+ let PersonSeedOutcome::Changed {
+ record,
+ mut transitions,
+ } = apply_person_seed(
+ &prior,
+ &evaluated,
+ &MatchedSet::from_iter([hash(2), hash(3)]),
+ at(5_000),
+ MARGIN,
+ )
+ else {
+ panic!("expected Changed");
+ };
+
+ transitions.sort_by_key(|(hash, _)| *hash);
+ assert_eq!(
+ transitions,
+ vec![
+ (hash(1), TransitionKind::Left),
+ (hash(3), TransitionKind::Entered),
+ ],
+ );
+ assert!(record.matched.contains(&hash(2)));
+ assert!(record.matched.contains(&hash(3)));
+ assert!(!record.matched.contains(&hash(1)), "the retraction lands");
+ assert!(
+ record.matched.contains(&hash(9)),
+ "a hash the scan never evaluated is untouched, and mints no Left",
+ );
+ }
+
+ #[test]
+ fn apply_person_seed_zeroes_fingerprints_floors_last_seen_and_freezes_dedup() {
+ let mut prior = sample_record();
+ prior.matched = MatchedSet::empty();
+ prior.last_seen_ms = 1_000;
+
+ let PersonSeedOutcome::Changed { record, .. } = apply_person_seed(
+ &prior,
+ &[hash(1)],
+ &MatchedSet::from_iter([hash(1)]),
+ at(9_000),
+ MARGIN,
+ ) else {
+ panic!("expected Changed");
+ };
+
+ assert_eq!(
+ record.props_fingerprint,
+ PropsFingerprint(0),
+ "a subset evaluation must never claim to cover the person's props",
+ );
+ assert_eq!(record.catalog_fingerprint, CatalogFingerprint(0));
+ assert_eq!(
+ record.last_seen_ms, 9_000,
+ "the scan instant floors last_seen, or the record is instantly TTL-eligible",
+ );
+ assert_eq!(
+ record.stamp, prior.stamp,
+ "a floor below the record's own stamp never lowers it",
+ );
+ assert_eq!(record.applied_offsets, prior.applied_offsets);
+ assert_eq!(record.redirect_dedup, prior.redirect_dedup);
+
+ // An older scan never regresses last_seen.
+ let PersonSeedOutcome::Changed { record, .. } = apply_person_seed(
+ &prior,
+ &[hash(1)],
+ &MatchedSet::from_iter([hash(1)]),
+ at(-9_000),
+ MARGIN,
+ ) else {
+ panic!("expected Changed");
+ };
+ assert_eq!(record.last_seen_ms, 1_000);
+ }
+
+ /// Without the floor a seeded record keeps [`Stamp::MIN`] and loses argMax to every event, so
+ /// any straggler older than the scan re-evaluates the person from staler properties and
+ /// silently reverts the backfill. A dormant person never gets a newer event to correct it.
+ #[test]
+ fn a_seed_installs_an_argmax_floor_that_older_stragglers_lose_to() {
+ let scanned_at = at(9_000_000);
+ let PersonSeedOutcome::Changed { record, .. } = apply_person_seed(
+ &PersonRecord::absent(),
+ &[hash(1)],
+ &MatchedSet::from_iter([hash(1)]),
+ scanned_at,
+ MARGIN,
+ ) else {
+ panic!("expected Changed");
+ };
+
+ let floor = seed_stamp_floor(scanned_at, MARGIN);
+ assert_eq!(record.stamp, floor);
+ assert_eq!(
+ decide(
+ &PriorRecord::Present(record.clone()),
+ Stamp::new(floor.ms - 1, i64::MAX),
+ coords(),
+ PropsFingerprint::of("{}"),
+ CatalogFingerprint::of_sorted(&[hash(1)]),
+ ),
+ Decision::Stale,
+ "an event from before the scan must not re-evaluate the person",
+ );
+ assert_eq!(
+ decide(
+ &PriorRecord::Present(record),
+ Stamp::new(floor.ms, i64::MIN + 1),
+ coords(),
+ PropsFingerprint::of("{}"),
+ CatalogFingerprint::of_sorted(&[hash(1)]),
+ ),
+ Decision::Eval {
+ freshness: Freshness::StaleBoth,
+ },
+ "anything above the floor still re-evaluates against the zeroed fingerprints",
+ );
+ }
+
+ #[test]
+ fn apply_person_seed_writes_nothing_when_the_seed_adds_nothing() {
+ let mut settled = sample_record();
+ settled.matched = MatchedSet::from_iter([hash(1), hash(9)]);
+
+ let cases = [
+ (
+ settled,
+ MatchedSet::from_iter([hash(1)]),
+ "1 already TRUE, 2 already absent, 9 outside the evaluated set",
+ ),
+ (
+ PersonRecord::absent(),
+ MatchedSet::empty(),
+ "no record and no match: the store-growth guarantee — a team-wide scan of dormant \
+ non-matchers writes no rows",
+ ),
+ ];
+
+ for (prior, matched, why) in cases {
+ assert_eq!(
+ apply_person_seed(&prior, &[hash(1), hash(2)], &matched, at(9_000), MARGIN),
+ PersonSeedOutcome::Unchanged,
+ "{why}",
+ );
+ }
+ }
+
+ proptest! {
+ #![proptest_config(ProptestConfig::with_cases(64))]
+
+ #[test]
+ fn re_applying_a_landed_person_seed_is_never_a_second_change(
+ prior_bits in prop::collection::vec(any::<bool>(), 8),
+ evaluated_bits in prop::collection::vec(any::<bool>(), 8),
+ matched_bits in prop::collection::vec(any::<bool>(), 8),
+ ) {
+ let evaluated: Vec<[u8; 16]> = (0u8..8)
+ .filter(|i| evaluated_bits[*i as usize])
+ .map(hash)
+ .collect();
+ prop_assume!(!evaluated.is_empty());
+ let matched: MatchedSet = (0u8..8)
+ .filter(|i| evaluated_bits[*i as usize] && matched_bits[*i as usize])
+ .map(hash)
+ .collect();
+
+ let mut prior = PersonRecord::absent();
+ prior.matched = (0u8..8).filter(|i| prior_bits[*i as usize]).map(hash).collect();
+
+ let settled = match apply_person_seed(&prior, &evaluated, &matched, at(1_000), MARGIN)
+ {
+ PersonSeedOutcome::Changed { record, .. } => record,
+ PersonSeedOutcome::Unchanged => prior,
+ };
+ prop_assert_eq!(
+ apply_person_seed(&settled, &evaluated, &matched, at(1_000), MARGIN),
+ PersonSeedOutcome::Unchanged,
+ );
+ }
+ }
+
// --- dedup carrier / absorb ---
#[test]
diff --git a/rust/cohort-stream-processor/src/workers/cascade_path.rs b/rust/cohort-stream-processor/src/workers/cascade_path.rs
index 288c206aeebc..7754efd2d582 100644
--- a/rust/cohort-stream-processor/src/workers/cascade_path.rs
+++ b/rust/cohort-stream-processor/src/workers/cascade_path.rs
@@ -448,6 +448,7 @@ mod tests {
live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),
register_transfer_enabled: false,
reconcile: crate::workers::ReconcileDeps::default(),
+ person_seed: crate::workers::PersonSeedDeps::default(),
};
// The cascade was dispatched this tenure, so its ceiling is raised — mirrors the dispatcher.
deps.cascade_tracker
diff --git a/rust/cohort-stream-processor/src/workers/merge_path.rs b/rust/cohort-stream-processor/src/workers/merge_path.rs
index 0d3476f89e30..07c92b4db0b7 100644
--- a/rust/cohort-stream-processor/src/workers/merge_path.rs
+++ b/rust/cohort-stream-processor/src/workers/merge_path.rs
@@ -37,6 +37,7 @@ use crate::producer::{
use crate::stage1::transition::LeafTransition;
use crate::store::{BehavioralKey, PendingTransferKey, ReadLane, StoreHandle};
use crate::sweep::EvictionQueue;
+use crate::workers::person_seed_path::PersonSeedDeps;
use crate::workers::stage2_path::compose_stage2;
use crate::workers::worker::{
affected_leaves, first_cascades, produce_cascades, produce_membership, transition_metric_label,
@@ -136,6 +137,8 @@ pub struct MergeWorkerDeps {
pub register_transfer_enabled: bool,
/// Reconcile admission and the pod-wide scheduler wake-up count.
pub reconcile: ReconcileDeps,
+ /// Person-property seed admission and its live-priority margin.
+ pub person_seed: PersonSeedDeps,
}
impl MergeWorkerDeps {
@@ -157,6 +160,7 @@ impl MergeWorkerDeps {
live_watermarks: Arc::new(LiveWatermarks::new()),
register_transfer_enabled: false,
reconcile: ReconcileDeps::default(),
+ person_seed: PersonSeedDeps::default(),
})
}
}
@@ -909,6 +913,7 @@ mod tests {
live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),
register_transfer_enabled: false,
reconcile: ReconcileDeps::default(),
+ person_seed: PersonSeedDeps::default(),
}
}
diff --git a/rust/cohort-stream-processor/src/workers/mod.rs b/rust/cohort-stream-processor/src/workers/mod.rs
index c6ed2522655c..78c85bab08f8 100644
--- a/rust/cohort-stream-processor/src/workers/mod.rs
+++ b/rust/cohort-stream-processor/src/workers/mod.rs
@@ -4,6 +4,7 @@ pub mod cascade_path;
pub mod event_path;
pub mod merge_gc;
pub mod merge_path;
+pub mod person_seed_path;
pub mod reconcile;
pub mod seed_path;
pub mod stage2_gc;
@@ -18,6 +19,7 @@ pub use merge_gc::{handle_merge_gc, MergeGcCursor};
pub use merge_path::{
CascadeConfig, MergeWorkerDeps, TransferRetryPolicy, DEFAULT_MERGE_GC_SCAN_LIMIT,
};
+pub use person_seed_path::PersonSeedDeps;
pub use reconcile::{ReconcileBacklog, ReconcileDeps, DEFAULT_RECONCILE_SCAN_PAGE};
pub use stage2_gc::{handle_stage2_orphan_gc, Stage2GcCursor};
pub use stage2_path::compose_stage2;
diff --git a/rust/cohort-stream-processor/src/workers/person_seed_path.rs b/rust/cohort-stream-processor/src/workers/person_seed_path.rs
new file mode 100644
index 000000000000..efbdae444783
--- /dev/null
+++ b/rust/cohort-stream-processor/src/workers/person_seed_path.rs
@@ -0,0 +1,1363 @@
+//! Applies person-property seeds to `cf_person_records`, giving dormant persons leaf state that
+//! otherwise only arrives on a live event carrying `person_properties`.
+//!
+//! [`Apply::run`] is the algorithm; the other [`Apply`] methods are its I/O steps and the free
+//! functions below are pure. Every step that must not commit returns [`SeedHold`], so the
+//! `Ok ⇒ mark, Err ⇒ hold` decision lives in [`handle_person_seed`] alone.
+//!
+//! Ordering against live traffic is [`person_seed_verdict`]'s job, not the apply fence's: a person
+//! seed carries no arrival bound over the event stream, so it admits fence-open. The partition-wide
+//! live-lag, disk, and channel-full holds still apply.
+
+use std::sync::Arc;
+
+use chrono::Utc;
+use cohort_core::seed::PersonSeed;
+use metrics::counter;
+use tracing::{debug, warn};
+use uuid::Uuid;
+
+use crate::filters::manager::CatalogHandle;
+use crate::filters::reverse_index::TeamFilters;
+use crate::merge::tombstone_redirect::{self, MAX_CROSS_PARTITION_REDIRECT_HOPS};
+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,
+};
+use crate::producer::{map_transition, CohortMembershipChange, MembershipSink};
+use crate::stage1::key::LeafStateKey;
+use crate::stage1::person_record::{
+ apply_person_seed, person_seed_verdict, MatchedSet, PersonRecord, PersonSeedOutcome,
+ PersonSeedVerdict, PriorRecord,
+};
+use crate::stage1::state::StateVariant;
+use crate::stage1::transition::LeafTransition;
+use crate::stage2::{single_leaf_transition_register_writes, stage_register_writes};
+use crate::store::{
+ PersonPrefix, PersonRecordKey, PersonRecords, ReadLane, 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,
+};
+
+/// Person-property seed admission for the partition workers.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct PersonSeedDeps {
+ /// While off, person seeds skip and commit, so a run produced against a gate-off fleet has to
+ /// be re-produced.
+ pub enabled: bool,
+ /// How far a scan instant must beat the stored record's stamp before the seed may overwrite it.
+ /// Covers ClickHouse replication lag plus client-clock skew; see
+ /// [`crate::stage1::person_record::person_seed_verdict`].
+ pub live_margin_ms: i64,
+}
+
+impl Default for PersonSeedDeps {
+ fn default() -> Self {
+ Self {
+ enabled: false,
+ live_margin_ms: 900_000,
+ }
+ }
+}
+
+/// Handle one person seed on its owning partition worker; touches the seed tracker only.
+///
+/// `Ok` means every durable effect landed, or the seed was skipped on purpose, and the offset may
+/// commit. [`SeedHold`] means Kafka must redeliver.
+#[allow(clippy::too_many_arguments)]
+pub(crate) async fn handle_person_seed(
+ partition_id: u16,
+ handle: &StoreHandle,
+ catalog: &CatalogHandle,
+ sink: &Arc<dyn MembershipSink>,
+ merge: &MergeWorkerDeps,
+ last_updated: &str,
+ seed: &PersonSeed,
+ offset: i64,
+) {
+ let apply = Apply {
+ partition_id,
+ handle,
+ catalog,
+ sink,
+ merge,
+ last_updated,
+ seed,
+ offset,
+ };
+ match apply.run().await {
+ Ok(()) => mark_processed(&merge.seed_tracker, partition_id, offset),
+ Err(held) => {
+ warn!(
+ partition_id,
+ team_id = seed.team_id().0,
+ run_id = %seed.run_id().0,
+ error = %held,
+ "person seed apply failed; holding the seed offset for redelivery",
+ );
+ hold(&merge.seed_tracker, partition_id, offset);
+ }
+ }
+}
+
+/// A failure that must not commit. `stage` is what tells an operator which half of the apply broke.
+#[derive(Debug, thiserror::Error)]
+enum SeedHold {
+ #[error("{stage}: {source}")]
+ Store {
+ stage: &'static str,
+ source: StoreError,
+ },
+ #[error("{stage}: {errors} message(s) failed to produce")]
+ Produce { stage: &'static str, errors: usize },
+}
+
+impl SeedHold {
+ /// `map_err` adapter that labels a store failure with the step that hit it.
+ fn store(stage: &'static str) -> impl FnOnce(StoreError) -> Self {
+ move |source| Self::Store { stage, source }
+ }
+}
+
+struct Apply<'a> {
+ partition_id: u16,
+ handle: &'a StoreHandle,
+ catalog: &'a CatalogHandle,
+ sink: &'a Arc<dyn MembershipSink>,
+ merge: &'a MergeWorkerDeps,
+ last_updated: &'a str,
+ seed: &'a PersonSeed,
+ offset: i64,
+}
+
+impl Apply<'_> {
+ /// Each `return Ok(())` is a terminal skip whose offset commits; each `?` holds it.
+ async fn run(&self) -> Result<(), SeedHold> {
+ if !self.merge.person_seed.enabled {
+ self.skip_gate_off();
+ return Ok(());
+ }
+
+ let snapshot = self.catalog.load();
+ let Some(filters) = snapshot.team(self.seed.team_id()) else {
+ counter!(PERSON_SEEDS_DROPPED_TOTAL, "reason" => "team_absent").increment(1);
+ return Ok(());
+ };
+
+ // Ahead of the tombstone resolution: the catalog is team-wide, so a seed nothing backs is
+ // dropped identically on the survivor's partition, and resolving first would spend a store
+ // read and possibly a cross-partition re-produce on a message already doomed.
+ let Some(effective) = effective_hashes(filters, self.seed) else {
+ counter!(PERSON_SEEDS_DROPPED_TOTAL, "reason" => "no_effective_hashes").increment(1);
+ return Ok(());
+ };
+
+ let Target::Local(person) = self.resolve_target().await? else {
+ return Ok(());
+ };
+
+ let record_key =
+ PersonPrefix::new(self.partition_id, self.seed.team_id().0 as u64, person).record_key();
+ let prior = self.read_record(&record_key).await?;
+ let verdict = person_seed_verdict(
+ &prior,
+ self.seed.scanned_at_ms(),
+ self.merge.person_seed.live_margin_ms,
+ filters.catalog_fingerprint,
+ );
+ // A live-fresh skip is not merged at all: the stored state already subsumes the seed.
+ let update = match verdict {
+ PersonSeedVerdict::SkipLiveFresh => RecordUpdate::Unchanged,
+ _ => record_update(
+ &prior,
+ self.seed,
+ person,
+ &effective,
+ self.merge.person_seed.live_margin_ms,
+ ),
+ };
+
+ let now_ms = Utc::now().timestamp_millis();
+ self.commit_stage1(filters, &record_key, &update, now_ms)
+ .await?;
+ if recomposes(&update, verdict, &prior) {
+ self.emit(filters, &effective.leaves(person), &update, now_ms)
+ .await?;
+ }
+ // Counted last: an emit failure holds the offset, and the redelivery re-derives the verdict
+ // against the record this attempt already wrote, so counting any earlier counts one seed
+ // twice under two different arms.
+ update.record_metric(verdict);
+ Ok(())
+ }
+
+ /// A gate-off run is one message per scanned person, so this stays off `warn!` and leans on
+ /// `cohort_person_seeds_skipped_total{reason="apply_disabled"}` for the signal.
+ fn skip_gate_off(&self) {
+ counter!(PERSON_SEEDS_SKIPPED_TOTAL, "reason" => "apply_disabled").increment(1);
+ debug!(
+ partition_id = self.partition_id,
+ team_id = self.seed.team_id().0,
+ run_id = %self.seed.run_id().0,
+ "person seed skipped while person apply is disabled; re-produce the run after enabling",
+ );
+ }
+
+ /// A read failure is fail-stop: a seed applied to a merged-away person is durable state that
+ /// nothing downstream can retract.
+ async fn resolve_target(&self) -> Result<Target, SeedHold> {
+ let resolution = tombstone_redirect::resolve_offloaded(
+ self.handle,
+ self.partition_id,
+ self.seed.team_id(),
+ self.seed.person_id(),
+ self.merge.partition_count,
+ ReadLane::Maintenance,
+ )
+ .await
+ .map_err(SeedHold::store("tombstone preflight"))?;
+
+ match route_seed(self.seed, resolution, MAX_CROSS_PARTITION_REDIRECT_HOPS) {
+ SeedRoute::ApplyLocal { person } => Ok(Target::Local(person)),
+ SeedRoute::ReProduce { seed: rekeyed } => self.hand_off(rekeyed).await,
+ SeedRoute::CapExhausted { person } => Ok(self.degrade_to(person)),
+ }
+ }
+
+ /// Re-produce onto the survivor's partition. This is the seed's only remaining copy, so the
+ /// caller may not commit until exactly one `Ok` acks; an empty ack vector is a failure, not a
+ /// vacuous success.
+ async fn hand_off(&self, rekeyed: PersonSeed) -> Result<Target, SeedHold> {
+ let acks = self
+ .merge
+ .seed_tile_sink
+ .produce_person(vec![rekeyed])
+ .await;
+ if !matches!(acks.as_slice(), [Ok(())]) {
+ counter!(PERSON_SEED_REKEY_PRODUCE_FAILURE_TOTAL).increment(1);
+ return Err(SeedHold::Produce {
+ stage: "re-key produce",
+ errors: 1,
+ });
+ }
+ counter!(PERSON_SEED_REKEYED_TOTAL).increment(1);
+ Ok(Target::HandedOff)
+ }
+
+ /// Apply at the best-known target once the hop budget is spent, matching the tile and event
+ /// paths: an orphaned row beats a silent seed loss, and holding the offset instead would stall
+ /// every later seed on the partition behind a tombstone cycle that will never resolve.
+ ///
+ /// The row lands under this worker's partition prefix, which the survivor's own worker never
+ /// reads. Unlike the tile path's orphan, no sweep owns it — only the `cf_person_records` TTL
+ /// reclaims it, and `apply_person_seed` floors `last_seen_ms` at the scan instant so it does age
+ /// out wherever `COHORT_PERSON_RECORD_TTL_DAYS` is set.
+ fn degrade_to(&self, person: Uuid) -> Target {
+ counter!(PERSON_SEED_REKEY_HOP_CAPPED_TOTAL).increment(1);
+ warn!(
+ partition_id = self.partition_id,
+ team_id = self.seed.team_id().0,
+ %person,
+ hops = self.seed.redirect_hops(),
+ "person seed redirect hop cap hit (corrupt tombstone cycle?); applying inline at the best-known target",
+ );
+ Target::Local(person)
+ }
+
+ /// Maintenance lane: backfill must not contend with live event reads.
+ ///
+ /// A row that exists but does not decode is counted here, the way the event path counts it: the
+ /// apply rebuilds from an absent baseline, so without the counter a real codec failure is
+ /// indistinguishable from a dormant person that never had a record.
+ async fn read_record(&self, key: &PersonRecordKey) -> Result<PriorRecord, SeedHold> {
+ let stored = self
+ .handle
+ .get_person_record(key, ReadLane::Maintenance)
+ .await
+ .map_err(SeedHold::store("person record read"))?;
+ let prior = PriorRecord::decode(stored.as_deref());
+ if matches!(prior, PriorRecord::Corrupt) {
+ counter!(PERSON_SEED_PRIOR_CORRUPT_TOTAL).increment(1);
+ }
+ Ok(prior)
+ }
+
+ /// One batch, so a register is never stranded without the matched set that justifies it.
+ async fn commit_stage1(
+ &self,
+ filters: &TeamFilters,
+ key: &PersonRecordKey,
+ update: &RecordUpdate,
+ now_ms: i64,
+ ) -> 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,
+ ),
+ );
+ }
+ self.handle
+ .commit(staged)
+ .await
+ .map_err(SeedHold::store("person record commit"))
+ }
+
+ /// 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.
+ ///
+ /// 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.
+ async fn emit(
+ &self,
+ filters: &TeamFilters,
+ leaves: &[(LeafStateKey, Uuid)],
+ update: &RecordUpdate,
+ 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());
+
+ tag_seed(&mut changes, self.seed.run_id());
+ self.produce(changes).await?;
+
+ commit_stage2_writes(self.handle, &recompute.writes)
+ .await
+ .map_err(SeedHold::store("stage 2 commit"))?;
+ recompute.record_metrics();
+ // Nothing to schedule: person-property membership has no window, so the sweep never owns
+ // these leaves.
+ Ok(())
+ }
+
+ async fn produce(&self, changes: Vec<CohortMembershipChange>) -> Result<(), SeedHold> {
+ // Built first: the cascade payload embeds the change, and `produce_membership` consumes it.
+ let cascades = first_cascades(self.merge, &changes, self.offset);
+
+ let errors = if changes.is_empty() {
+ 0
+ } else {
+ produce_membership(self.sink, changes).await
+ };
+ if errors > 0 {
+ return Err(SeedHold::Produce {
+ stage: "membership produce",
+ errors,
+ });
+ }
+
+ let errors = produce_cascades(self.merge, cascades).await;
+ if errors > 0 {
+ return Err(SeedHold::Produce {
+ stage: "cascade produce",
+ errors,
+ });
+ }
+ Ok(())
+ }
+}
+
+/// Where a seed's work belongs once its tombstone chain is resolved.
+enum Target {
+ Local(Uuid),
+ /// Re-produced to the survivor's partition; this worker is done with it.
+ HandedOff,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+enum RecordUpdate {
+ Changed {
+ record: PersonRecord,
+ transitions: Vec<LeafTransition>,
+ },
+ /// Nothing to write, so an absent record with no matches is never created and store growth
+ /// stays proportional to matchers.
+ Unchanged,
+}
+
+impl RecordUpdate {
+ fn transitions(&self) -> &[LeafTransition] {
+ match self {
+ Self::Changed { transitions, .. } => transitions,
+ Self::Unchanged => &[],
+ }
+ }
+
+ /// `verdict` labels the writing arm only: an unchanged merge says nothing about which verdict
+ /// admitted it.
+ fn record_metric(&self, verdict: PersonSeedVerdict) {
+ match (self, verdict) {
+ (_, PersonSeedVerdict::SkipLiveFresh) => {
+ counter!(PERSON_SEEDS_SKIPPED_TOTAL, "reason" => "stale_vs_live").increment(1);
+ }
+ (Self::Changed { .. }, _) => {
+ counter!(PERSON_SEEDS_APPLIED_TOTAL, "verdict" => verdict.as_str()).increment(1);
+ }
+ (Self::Unchanged, _) => counter!(PERSON_SEEDS_UNCHANGED_TOTAL).increment(1),
+ }
+ }
+}
+
+/// Whether stage 2 has to be recomposed for this seed.
+///
+/// A merge that changed nothing leaves stage 2 already consistent with stage 1, and skipping the
+/// recompose keeps a non-matching dormant person to a single point read instead of a composition
+/// over every cohort its hashes touch — the dominant message shape of a scan that emits
+/// non-matchers. Two outcomes still have to recompose:
+///
+/// - `SkipLiveFresh` may be the redelivery of an attempt that committed stage 1 and then failed its
+/// produce. The replay merges to `Unchanged` and mints no transition, and a live event that
+/// re-derives the same matched set mints none either, so nothing else would ever write those
+/// stage-2 bits and the person would sit outside every composed cohort.
+/// - A corrupt prior's stage-1 truth is unreadable, so the stored bits cannot be assumed to match
+/// it.
+///
+/// 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.
+fn recomposes(update: &RecordUpdate, verdict: PersonSeedVerdict, prior: &PriorRecord) -> bool {
+ matches!(update, RecordUpdate::Changed { .. })
+ || verdict == PersonSeedVerdict::SkipLiveFresh
+ || matches!(prior, PriorRecord::Corrupt)
+}
+
+/// An absent or corrupt prior folds from the absent baseline rather than skipping: freezing
+/// membership on an unreadable row would be a silent correctness hole. What the unreadable row held
+/// outside `evaluated` is lost with it, and mints no `Left` — hence the corrupt counter at the read.
+fn record_update(
+ prior: &PriorRecord,
+ seed: &PersonSeed,
+ person: Uuid,
+ effective: &EffectiveHashes,
+ live_margin_ms: i64,
+) -> RecordUpdate {
+ let baseline = PersonRecord::absent();
+ let from = match prior {
+ PriorRecord::Present(record) => record,
+ PriorRecord::Absent | PriorRecord::Corrupt => &baseline,
+ };
+ match apply_person_seed(
+ from,
+ &effective.evaluated,
+ &effective.matched,
+ seed.scanned_at_ms(),
+ live_margin_ms,
+ ) {
+ PersonSeedOutcome::Unchanged => RecordUpdate::Unchanged,
+ PersonSeedOutcome::Changed {
+ record,
+ transitions,
+ } => RecordUpdate::Changed {
+ record,
+ transitions: transitions
+ .into_iter()
+ .map(|(condition_hash, kind)| LeafTransition {
+ team_id: seed.team_id(),
+ leaf_state_key: LeafStateKey::for_person_property(&condition_hash),
+ person_id: person,
+ condition_hash,
+ kind,
+ })
+ .collect(),
+ },
+ }
+}
+
+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 seed's hashes projected onto the team's live person-property catalog.
+struct EffectiveHashes {
+ /// Sorted and distinct, so [`effective_hashes`] can binary-search it.
+ evaluated: Vec<[u8; 16]>,
+ matched: MatchedSet,
+}
+
+impl EffectiveHashes {
+ fn leaves(&self, person: Uuid) -> Vec<(LeafStateKey, Uuid)> {
+ self.evaluated
+ .iter()
+ .map(|hash| (LeafStateKey::for_person_property(hash), person))
+ .collect()
+ }
+}
+
+/// Restrict the seed to hashes this team's catalog still resolves to a person-property leaf, or
+/// `None` when nothing survives.
+///
+/// Both lists must be filtered together: keeping a hash in `evaluated` that was dropped from
+/// `matched` would retract a TRUE the catalog no longer knows how to re-derive.
+fn effective_hashes(filters: &TeamFilters, seed: &PersonSeed) -> Option<EffectiveHashes> {
+ let mut evaluated: Vec<[u8; 16]> = Vec::with_capacity(seed.evaluated().len());
+ for hash in seed.evaluated() {
+ let condition_hash = hash.as_bytes();
+ if !filters.person_property_conditions.contains(&condition_hash) {
+ counter!(PERSON_SEED_HASHES_DROPPED_TOTAL, "reason" => "unknown_hash").increment(1);
+ continue;
+ }
+ let lsk = LeafStateKey::for_person_property(&condition_hash);
+ match filters.by_lsk.get(&lsk).map(|meta| meta.variant) {
+ Some(StateVariant::PersonProperty) => evaluated.push(condition_hash),
+ Some(_) => {
+ counter!(PERSON_SEED_HASHES_DROPPED_TOTAL, "reason" => "variant_mismatch")
+ .increment(1);
+ }
+ None => {
+ counter!(PERSON_SEED_HASHES_DROPPED_TOTAL, "reason" => "unknown_hash").increment(1);
+ }
+ }
+ }
+ if evaluated.is_empty() {
+ return None;
+ }
+
+ // `evaluated` was built in the seed's sorted order, so it stays sorted for the binary search.
+ let matched: MatchedSet = seed
+ .matched()
+ .iter()
+ .map(|hash| hash.as_bytes())
+ .filter(|hash| evaluated.binary_search(hash).is_ok())
+ .collect();
+ Some(EffectiveHashes { evaluated, matched })
+}
+
+#[cfg(test)]
+// Tests seed and assert against `CohortStore` directly, the sanctioned direct-store surface.
+#[allow(clippy::disallowed_methods)]
+mod tests {
+ use chrono_tz::UTC;
+ use cohort_core::seed::{ClaimEpoch, ConditionHash, RunId, ScannedAtMs};
+ use serde_json::{json, Value};
+ use tempfile::TempDir;
+
+ use crate::consumers::events::CohortStreamEvent;
+ use crate::filters::{CohortId, FilterCatalog, TeamFiltersBuilder, TeamId};
+ use crate::merge::transfer::Tombstone;
+ use crate::partitions::offset_tracker::OffsetTracker;
+ use crate::partitions::partitioner::{partition_of, COHORT_PARTITION_COUNT};
+ use crate::partitions::watermarks::LiveWatermarks;
+ use crate::producer::{
+ CaptureCascadeSink, CaptureSeedTileSink, CaptureSink, CaptureStreamEventSink,
+ CaptureTransferSink, ChangeOrigin, MembershipStatus,
+ };
+ use crate::stage1::person_record::{PropsFingerprint, Stamp};
+ use crate::stage1::state::AppliedOffsets;
+ use crate::stage2::state::Stage2State;
+ use crate::store::{
+ CohortStore, OffloadConfig, OffloadMode, Stage2Key, StoreConfig, TombstoneKey,
+ };
+ use crate::workers::event_path::{process_event_gated, EventNameGating};
+ use crate::workers::stage2_path::compose_stage2;
+ use crate::workers::{CascadeConfig, ReconcileDeps, TransferRetryPolicy};
+
+ use super::*;
+
+ const TEAM: TeamId = TeamId(7);
+ const PERSON_HASH: &str = "fedcba9876543210";
+ const UNKNOWN_HASH: &str = "0000000000000000";
+ const LAST_UPDATED: &str = "2026-06-15 12:00:00.000000";
+ const MARGIN_MS: i64 = 900_000;
+
+ fn person_leaf(hash: &str) -> Value {
+ json!({
+ "type": "person",
+ "key": "email",
+ "value": "[email protected]",
+ "operator": "exact",
+ "conditionHash": hash,
+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],
+ })
+ }
+
+ fn behavioral_leaf() -> Value {
+ json!({
+ "type": "behavioral", "value": "performed_event", "key": "$pageview",
+ "time_value": 7, "time_interval": "day",
+ "conditionHash": "0123456789abcdef",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ })
+ }
+
+ fn wrap(values: Vec<Value>) -> Value {
+ json!({ "properties": { "type": "AND", "values": values } })
+ }
+
+ /// Cohort 1 is the person leaf alone (single-leaf register + direct emission); cohort 2 ANDs it
+ /// with a behavioral leaf (Stage 2 composition).
+ fn mixed_cohorts() -> Vec<(i32, Value)> {
+ vec![
+ (1, wrap(vec![person_leaf(PERSON_HASH)])),
+ (2, wrap(vec![person_leaf(PERSON_HASH), behavioral_leaf()])),
+ ]
+ }
+
+ fn build_filters(cohorts: &[(i32, Value)]) -> TeamFilters {
+ let mut builder = TeamFiltersBuilder::default();
+ for (id, filters) in cohorts {
+ builder.add_cohort(CohortId(*id), TEAM, filters).unwrap();
+ }
+ builder.freeze(UTC)
+ }
+
+ fn hash(value: &str) -> ConditionHash {
+ ConditionHash::parse(value).unwrap()
+ }
+
+ fn seed_for(
+ person: Uuid,
+ evaluated: &[&str],
+ matched: &[&str],
+ scanned_at_ms: i64,
+ ) -> PersonSeed {
+ PersonSeed::new(
+ TEAM,
+ person,
+ evaluated.iter().copied().map(hash).collect(),
+ matched.iter().copied().map(hash).collect(),
+ ScannedAtMs(scanned_at_ms),
+ RunId(Uuid::from_u128(0xBF)),
+ ClaimEpoch(1),
+ )
+ .unwrap()
+ }
+
+ struct Shell {
+ _dir: TempDir,
+ store: CohortStore,
+ handle: StoreHandle,
+ filters: TeamFilters,
+ catalog: Arc<CatalogHandle>,
+ sink: CaptureSink,
+ seed_sink: CaptureSeedTileSink,
+ deps: MergeWorkerDeps,
+ }
+
+ impl Shell {
+ fn new(cohorts: Vec<(i32, Value)>) -> Self {
+ Self::with_sinks(cohorts, CaptureSink::new(), CaptureSeedTileSink::new())
+ }
+
+ fn with_sinks(
+ cohorts: Vec<(i32, Value)>,
+ sink: CaptureSink,
+ seed_sink: CaptureSeedTileSink,
+ ) -> Self {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ let handle = StoreHandle::new(
+ store.clone(),
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ );
+ let catalog = Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([(
+ TEAM,
+ build_filters(&cohorts),
+ )])));
+ let deps = MergeWorkerDeps {
+ transfer_sink: Arc::new(CaptureTransferSink::new()),
+ stream_event_sink: Arc::new(CaptureStreamEventSink::new()),
+ merge_tracker: Arc::new(OffsetTracker::new()),
+ transfer_tracker: Arc::new(OffsetTracker::new()),
+ retry: TransferRetryPolicy::default(),
+ gc_scan_limit: crate::workers::DEFAULT_MERGE_GC_SCAN_LIMIT,
+ stage2_orphan_gc_enabled: true,
+ cascade_sink: Arc::new(CaptureCascadeSink::new()),
+ cascade_tracker: Arc::new(OffsetTracker::new()),
+ cascade: CascadeConfig::default(),
+ partition_count: COHORT_PARTITION_COUNT,
+ seed_tile_sink: Arc::new(seed_sink.clone()),
+ seed_tracker: Arc::new(OffsetTracker::new()),
+ live_watermarks: Arc::new(LiveWatermarks::new()),
+ register_transfer_enabled: false,
+ reconcile: ReconcileDeps::default(),
+ person_seed: PersonSeedDeps {
+ enabled: true,
+ live_margin_ms: MARGIN_MS,
+ },
+ };
+ Self {
+ _dir: dir,
+ store,
+ handle,
+ filters: build_filters(&cohorts),
+ catalog,
+ sink,
+ seed_sink,
+ deps,
+ }
+ }
+
+ async fn run(&mut self, partition_id: u16, seed: &PersonSeed, offset: i64) {
+ self.deps
+ .seed_tracker
+ .mark_dispatched(partition_id as i32, offset + 1);
+ let sink: Arc<dyn MembershipSink> = Arc::new(self.sink.clone());
+ handle_person_seed(
+ partition_id,
+ &self.handle,
+ &self.catalog,
+ &sink,
+ &self.deps,
+ LAST_UPDATED,
+ seed,
+ offset,
+ )
+ .await;
+ }
+
+ /// Without `person_properties`, this leaves behavioral state written and no person record.
+ fn live_pageview(&self, partition_id: u16, person: Uuid, person_properties: Option<&str>) {
+ process_event_gated(
+ partition_id,
+ &self.store,
+ &self.filters,
+ &CohortStreamEvent {
+ team_id: TEAM.0,
+ person_id: person.to_string(),
+ distinct_id: "d".to_string(),
+ uuid: "u".to_string(),
+ event: "$pageview".to_string(),
+ timestamp: chrono::Utc::now()
+ .format("%Y-%m-%d %H:%M:%S%.6f")
+ .to_string(),
+ properties: Some("{}".to_string()),
+ person_properties: person_properties.map(str::to_string),
+ elements_chain: None,
+ source_offset: 1,
+ source_partition: 0,
+ redirected_from: None,
+ redirect_hops: 0,
+ },
+ EventNameGating::Disabled,
+ )
+ .unwrap();
+ }
+
+ fn record(&self, partition_id: u16, person: Uuid) -> Option<PersonRecord> {
+ let key = PersonPrefix::new(partition_id, TEAM.0 as u64, person).record_key();
+ self.store
+ .get_person_record(&key)
+ .unwrap()
+ .map(|bytes| PersonRecord::decode(&bytes).unwrap())
+ }
+
+ fn put_record(&self, partition_id: u16, person: Uuid, record: &PersonRecord) {
+ let key = PersonPrefix::new(partition_id, TEAM.0 as u64, person).record_key();
+ self.store
+ .write_batch(|batch| batch.put::<PersonRecords>(&key, &record.encode()))
+ .unwrap();
+ }
+
+ fn stage2(&self, partition_id: u16, person: Uuid, cohort_id: u64) -> Option<Stage2State> {
+ self.store
+ .get_stage2(&Stage2Key {
+ partition_id,
+ team_id: TEAM.0 as u64,
+ cohort_id,
+ person_id: person,
+ })
+ .unwrap()
+ .map(|bytes| Stage2State::decode(&bytes).unwrap())
+ }
+
+ fn committable(&self, partition_id: u16) -> Option<i64> {
+ self.deps
+ .seed_tracker
+ .committable_offsets()
+ .get(&(partition_id as i32))
+ .copied()
+ }
+ }
+
+ fn dormant_person() -> (Uuid, u16) {
+ let person = Uuid::from_u128(0x5EED);
+ let partition_id = partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16;
+ (person, partition_id)
+ }
+
+ fn now_ms() -> i64 {
+ chrono::Utc::now().timestamp_millis()
+ }
+
+ #[tokio::test]
+ async fn a_dormant_person_seed_creates_the_record_and_lands_both_cohorts() {
+ let (person, partition_id) = dormant_person();
+ let mut shell = Shell::new(mixed_cohorts());
+ shell.live_pageview(partition_id, person, None);
+ assert!(
+ shell.record(partition_id, person).is_none(),
+ "an event without person_properties leaves the person record absent",
+ );
+
+ let seed = seed_for(person, &[PERSON_HASH], &[PERSON_HASH], now_ms());
+ shell.run(partition_id, &seed, 9).await;
+
+ let stored = shell
+ .record(partition_id, person)
+ .expect("the seed creates the record");
+ assert!(stored.matched.contains(&hash(PERSON_HASH).as_bytes()));
+ assert_eq!(
+ stored.catalog_fingerprint,
+ crate::stage1::person_record::CatalogFingerprint(0),
+ "a subset evaluation must not claim full-catalog coverage",
+ );
+
+ let changes = shell.sink.changes();
+ assert_eq!(
+ changes.len(),
+ 2,
+ "single-leaf cohort 1 and composed cohort 2"
+ );
+ assert!(changes.iter().all(|change| {
+ change.status == MembershipStatus::Entered
+ && change.origin == Some(ChangeOrigin::Seed)
+ && change.run_id == Some(seed.run_id())
+ && change.person_id == person.to_string()
+ }));
+ 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(10));
+
+ // Replay: the merge is Unchanged, so nothing is re-emitted.
+ shell.run(partition_id, &seed, 10).await;
+ assert_eq!(shell.sink.changes().len(), 2);
+ assert_eq!(shell.committable(partition_id), Some(11));
+ }
+
+ #[tokio::test]
+ async fn a_live_fresh_covered_record_skips_the_seed_without_writing() {
+ let (person, partition_id) = dormant_person();
+ let mut shell = Shell::new(mixed_cohorts());
+ let live = PersonRecord {
+ last_seen_ms: now_ms(),
+ stamp: Stamp::new(now_ms(), 0),
+ props_fingerprint: PropsFingerprint::of(r#"{"email":"[email protected]"}"#),
+ 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, &live);
+
+ // An older scan that would retract the hash.
+ let seed = seed_for(person, &[PERSON_HASH], &[], now_ms() - 1_000);
+ shell.run(partition_id, &seed, 0).await;
+
+ assert_eq!(
+ shell.record(partition_id, person).unwrap(),
+ live,
+ "the record is byte-identical: no write at all",
+ );
+ assert!(shell.sink.changes().is_empty());
+ assert_eq!(shell.committable(partition_id), Some(1));
+ }
+
+ #[tokio::test]
+ async fn a_newer_seed_retracts_a_stale_true_hash() {
+ let (person, partition_id) = dormant_person();
+ let mut shell = Shell::new(mixed_cohorts());
+ 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!(shell
+ .record(partition_id, person)
+ .unwrap()
+ .matched
+ .is_empty());
+ let changes = shell.sink.changes();
+ assert_eq!(changes.len(), 1, "cohort 1 only: cohort 2 was never in");
+ assert_eq!(changes[0].cohort_id, 1);
+ assert_eq!(changes[0].status, MembershipStatus::Left);
+ assert!(!shell.stage2(partition_id, person, 1).unwrap().in_cohort);
+ }
+
+ #[tokio::test]
+ async fn a_record_evaluated_under_another_catalog_still_applies() {
+ let (person, partition_id) = dormant_person();
+ let mut shell = Shell::new(mixed_cohorts());
+ let stamped_at = now_ms();
+ let uncovered = PersonRecord {
+ last_seen_ms: stamped_at,
+ stamp: Stamp::new(stamped_at, 0),
+ props_fingerprint: PropsFingerprint::of("{}"),
+ // Evaluated against a catalog that did not hold this team's person conditions.
+ catalog_fingerprint: crate::stage1::person_record::CatalogFingerprint(0xDEAD),
+ matched: MatchedSet::empty(),
+ applied_offsets: AppliedOffsets::default(),
+ redirect_dedup: Default::default(),
+ };
+ shell.put_record(partition_id, person, &uncovered);
+
+ // Inside the margin, so the record is not provably older; only the catalog rotation admits.
+ let seed = seed_for(person, &[PERSON_HASH], &[PERSON_HASH], stamped_at + 1_000);
+ shell.run(partition_id, &seed, 0).await;
+
+ assert!(shell
+ .record(partition_id, person)
+ .unwrap()
+ .matched
+ .contains(&hash(PERSON_HASH).as_bytes()));
+ assert_eq!(shell.sink.changes().len(), 1);
+ }
+
+ /// A rotated catalog is a team-wide event, so without a recency test any backlogged scan would
+ /// overwrite live state on the strength of an unrelated cohort edit.
+ #[tokio::test]
+ async fn a_scan_older_than_the_record_never_applies_on_a_catalog_rotation_alone() {
+ let (person, partition_id) = dormant_person();
+ let mut shell = Shell::new(mixed_cohorts());
+ let live = PersonRecord {
+ last_seen_ms: now_ms(),
+ stamp: Stamp::new(now_ms(), 0),
+ props_fingerprint: PropsFingerprint::of(r#"{"email":"[email protected]"}"#),
+ catalog_fingerprint: crate::stage1::person_record::CatalogFingerprint(0xDEAD),
+ matched: MatchedSet::empty(),
+ applied_offsets: AppliedOffsets::default(),
+ redirect_dedup: Default::default(),
+ };
+ shell.put_record(partition_id, person, &live);
+
+ shell
+ .run(
+ partition_id,
+ &seed_for(
+ person,
+ &[PERSON_HASH],
+ &[PERSON_HASH],
+ now_ms() - 86_400_000,
+ ),
+ 0,
+ )
+ .await;
+
+ assert_eq!(
+ shell.record(partition_id, person).unwrap(),
+ live,
+ "a day-old scan must not re-enter a person live already evaluated out",
+ );
+ assert!(shell.sink.changes().is_empty());
+ assert_eq!(shell.committable(partition_id), Some(1));
+ }
+
+ #[tokio::test]
+ async fn hashes_the_catalog_no_longer_backs_drop_out_of_the_effective_set() {
+ let (person, partition_id) = dormant_person();
+ let mut shell = Shell::new(mixed_cohorts());
+
+ let partial = seed_for(
+ person,
+ &[UNKNOWN_HASH, PERSON_HASH],
+ &[UNKNOWN_HASH, PERSON_HASH],
+ now_ms(),
+ );
+ shell.run(partition_id, &partial, 0).await;
+
+ let stored = shell.record(partition_id, person).unwrap();
+ assert_eq!(stored.matched.len(), 1, "only the known hash is stored");
+ assert!(stored.matched.contains(&hash(PERSON_HASH).as_bytes()));
+
+ // Nothing survives the projection: a whole-seed drop that still commits its offset.
+ let orphaned = seed_for(person, &[UNKNOWN_HASH], &[UNKNOWN_HASH], now_ms());
+ shell.run(partition_id, &orphaned, 1).await;
+ assert_eq!(shell.record(partition_id, person).unwrap(), stored);
+ assert_eq!(shell.committable(partition_id), Some(2));
+ }
+
+ #[tokio::test]
+ async fn a_non_matching_dormant_person_creates_no_record() {
+ let (person, partition_id) = dormant_person();
+ let mut shell = Shell::new(mixed_cohorts());
+
+ shell
+ .run(
+ partition_id,
+ &seed_for(person, &[PERSON_HASH], &[], now_ms()),
+ 0,
+ )
+ .await;
+
+ assert!(shell.record(partition_id, person).is_none());
+ assert!(shell.sink.changes().is_empty());
+ assert_eq!(shell.committable(partition_id), Some(1));
+ }
+
+ #[tokio::test]
+ async fn person_apply_disabled_skips_and_commits_without_touching_the_store() {
+ let (person, partition_id) = dormant_person();
+ let mut shell = Shell::new(mixed_cohorts());
+ shell.deps.person_seed.enabled = false;
+
+ shell
+ .run(
+ partition_id,
+ &seed_for(person, &[PERSON_HASH], &[PERSON_HASH], now_ms()),
+ 4,
+ )
+ .await;
+
+ assert!(shell.record(partition_id, person).is_none());
+ assert!(shell.sink.changes().is_empty());
+ assert_eq!(shell.committable(partition_id), Some(5));
+ }
+
+ /// A merged-away person and a survivor on the same partition, so the tombstone resolves inline.
+ fn same_partition_pair() -> (Uuid, u16, Uuid) {
+ let p_old = Uuid::from_u128(0xA11CE);
+ let partition_id = partition_of(TEAM, &p_old, COHORT_PARTITION_COUNT) as u16;
+ let p_new = (10u128..)
+ .map(Uuid::from_u128)
+ .find(|p| partition_of(TEAM, p, COHORT_PARTITION_COUNT) as u16 == partition_id)
+ .expect("some uuid hashes onto p_old's partition");
+ (p_old, partition_id, p_new)
+ }
+
+ fn cross_partition_pair() -> (Uuid, u16, Uuid) {
+ let p_old = Uuid::from_u128(1);
+ let partition_id = partition_of(TEAM, &p_old, COHORT_PARTITION_COUNT) as u16;
+ let p_new = (10u128..)
+ .map(Uuid::from_u128)
+ .find(|p| partition_of(TEAM, p, COHORT_PARTITION_COUNT) as u16 != partition_id)
+ .expect("some uuid hashes off p_old's partition");
+ (p_old, partition_id, p_new)
+ }
+
+ fn write_tombstone(store: &CohortStore, partition_id: u16, old: Uuid, new: Uuid) {
+ store
+ .write_batch(|batch| {
+ batch.put_tombstone(
+ &TombstoneKey {
+ partition_id,
+ team_id: TEAM.0 as u64,
+ person: old,
+ },
+ &Tombstone {
+ new_person: new,
+ merged_at_ms: 1,
+ }
+ .encode(),
+ )
+ })
+ .unwrap();
+ }
+
+ /// The resolved survivor feeds the record key, the transition's person, and the recomposed
+ /// leaves. Should any of the three regress to the seed's own merged-away person, the record would
+ /// land on one person and its membership on another.
+ #[tokio::test]
+ async fn an_inline_redirect_applies_the_seed_at_the_survivor() {
+ let (p_old, partition_id, p_new) = same_partition_pair();
+ let mut shell = Shell::new(mixed_cohorts());
+ write_tombstone(&shell.store, partition_id, p_old, p_new);
+ shell.live_pageview(partition_id, p_new, None);
+
+ let seed = seed_for(p_old, &[PERSON_HASH], &[PERSON_HASH], now_ms());
+ shell.run(partition_id, &seed, 0).await;
+
+ assert!(
+ shell.record(partition_id, p_old).is_none(),
+ "nothing is written for the merged-away person",
+ );
+ assert!(shell
+ .record(partition_id, p_new)
+ .expect("the survivor gets the record")
+ .matched
+ .contains(&hash(PERSON_HASH).as_bytes()));
+ let changes = shell.sink.changes();
+ assert_eq!(
+ changes.len(),
+ 2,
+ "single-leaf cohort 1 and composed cohort 2"
+ );
+ assert!(changes
+ .iter()
+ .all(|change| change.person_id == p_new.to_string()));
+ assert!(
+ shell.stage2(partition_id, p_new, 2).unwrap().in_cohort,
+ "the composed bit follows the survivor too",
+ );
+ assert_eq!(shell.committable(partition_id), Some(1));
+ }
+
+ /// A capped redirect applies inline rather than dropping the seed or holding forever: the chain
+ /// is corrupt, so a hold would stall every later seed on the partition behind it. The write lands
+ /// under this worker's prefix, which is the accepted orphan — see `Apply::degrade_to`.
+ #[tokio::test]
+ async fn a_hop_capped_seed_applies_inline_and_orphans_the_row_on_this_partition() {
+ let (p_old, partition_id, p_new) = cross_partition_pair();
+ let mut shell = Shell::new(mixed_cohorts());
+ write_tombstone(&shell.store, partition_id, p_old, p_new);
+
+ // Exhaust the hop budget on the wire, then deliver: rekeyed_to returns None at the cap.
+ let mut seed = seed_for(p_old, &[PERSON_HASH], &[PERSON_HASH], now_ms());
+ for _ in 0..MAX_CROSS_PARTITION_REDIRECT_HOPS {
+ seed = seed
+ .rekeyed_to(p_old, MAX_CROSS_PARTITION_REDIRECT_HOPS)
+ .unwrap();
+ }
+ shell.run(partition_id, &seed, 0).await;
+
+ assert!(
+ shell.seed_sink.person_seeds().is_empty(),
+ "the hop budget is spent: no further re-produce",
+ );
+ let changes = shell.sink.changes();
+ assert_eq!(changes.len(), 1, "cohort 1 applied inline instead");
+ assert_eq!(changes[0].person_id, p_new.to_string());
+ assert!(
+ shell.record(partition_id, p_new).is_some(),
+ "the record lands under the delivering partition's prefix",
+ );
+ let survivor_partition = partition_of(TEAM, &p_new, COHORT_PARTITION_COUNT) as u16;
+ assert!(
+ shell.record(survivor_partition, p_new).is_none(),
+ "and not under the survivor's own, which is what makes it an orphan",
+ );
+ assert_eq!(shell.committable(partition_id), Some(1));
+ }
+
+ #[tokio::test]
+ async fn a_cross_partition_redirect_re_produces_the_rekeyed_seed_before_marking() {
+ let (p_old, partition_id, p_new) = cross_partition_pair();
+ let mut shell = Shell::new(mixed_cohorts());
+ write_tombstone(&shell.store, partition_id, p_old, p_new);
+ let seed = seed_for(p_old, &[PERSON_HASH], &[PERSON_HASH], now_ms());
+
+ shell.run(partition_id, &seed, 7).await;
+
+ let produced = shell.seed_sink.person_seeds();
+ assert_eq!(produced.len(), 1);
+ assert_eq!(produced[0].person_id(), p_new);
+ assert_eq!(produced[0].redirect_hops(), 1);
+ assert_eq!(
+ produced[0].scanned_at_ms(),
+ seed.scanned_at_ms(),
+ "the LWW input rides verbatim to the survivor's worker",
+ );
+ assert!(
+ shell.record(partition_id, p_old).is_none(),
+ "no local apply"
+ );
+ assert_eq!(shell.committable(partition_id), Some(8));
+ }
+
+ #[tokio::test]
+ async fn a_failed_rekey_produce_holds_the_seed_offset() {
+ let (p_old, partition_id, p_new) = cross_partition_pair();
+ let mut shell = Shell::with_sinks(
+ mixed_cohorts(),
+ CaptureSink::new(),
+ CaptureSeedTileSink::failing_first(1),
+ );
+ write_tombstone(&shell.store, partition_id, p_old, p_new);
+ let seed = seed_for(p_old, &[PERSON_HASH], &[PERSON_HASH], now_ms());
+
+ shell.run(partition_id, &seed, 7).await;
+ assert_eq!(shell.committable(partition_id), None);
+
+ shell.run(partition_id, &seed, 7).await;
+ assert_eq!(shell.seed_sink.person_seeds().len(), 1);
+ assert_eq!(shell.committable(partition_id), Some(7));
+ }
+
+ #[tokio::test]
+ async fn a_failed_membership_produce_holds_and_the_replay_re_derives_the_composed_flip() {
+ let (person, partition_id) = dormant_person();
+ let mut shell = Shell::with_sinks(
+ mixed_cohorts(),
+ CaptureSink::failing_first(1),
+ CaptureSeedTileSink::new(),
+ );
+ shell.live_pageview(partition_id, person, None);
+ let seed = seed_for(person, &[PERSON_HASH], &[PERSON_HASH], now_ms());
+
+ shell.run(partition_id, &seed, 3).await;
+ assert_eq!(shell.committable(partition_id), None, "held for redelivery");
+ assert!(
+ shell.record(partition_id, person).is_some(),
+ "stage 1 committed before the produce",
+ );
+ assert!(
+ shell.stage2(partition_id, person, 2).is_none(),
+ "the composed bit must stay unwritten under a failed produce",
+ );
+
+ 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",
+ );
+ assert_eq!(changes[0].cohort_id, 2);
+ assert_eq!(changes[0].origin, Some(ChangeOrigin::Seed));
+ assert!(shell.stage2(partition_id, person, 2).unwrap().in_cohort);
+ assert_eq!(shell.committable(partition_id), Some(3));
+ }
+
+ /// The held replay can arrive after a live event has already re-derived the same matched set.
+ /// That event mints no transition, so it composes nothing, and the seed then reads as live
+ /// fresh. If the skip committed without recomposing, the person would sit outside every
+ /// composed cohort forever: no later event flips a leaf, and reconcile scans `cf_stage2` rows,
+ /// which is precisely what is missing.
+ #[tokio::test]
+ async fn a_live_fresh_skip_still_recomposes_a_stage_2_bit_a_held_attempt_never_wrote() {
+ let (person, partition_id) = dormant_person();
+ let mut shell = Shell::with_sinks(
+ mixed_cohorts(),
+ CaptureSink::failing_first(1),
+ CaptureSeedTileSink::new(),
+ );
+ shell.live_pageview(partition_id, person, None);
+ let seed = seed_for(person, &[PERSON_HASH], &[PERSON_HASH], now_ms());
+
+ shell.run(partition_id, &seed, 3).await;
+ assert_eq!(shell.committable(partition_id), None, "held for redelivery");
+ assert!(shell.stage2(partition_id, person, 2).is_none());
+
+ // A live event carrying the same properties re-evaluates to the set the seed already
+ // stored, so it mints no transition and composes nothing.
+ shell.live_pageview(partition_id, person, Some(r#"{"email":"[email protected]"}"#));
+ assert!(
+ shell.stage2(partition_id, person, 2).is_none(),
+ "the no-op re-eval leaves the composed bit unwritten",
+ );
+
+ shell.run(partition_id, &seed, 3).await;
+
+ assert!(
+ shell.stage2(partition_id, person, 2).unwrap().in_cohort,
+ "the live-fresh skip must still recompose the bit nothing else would ever write",
+ );
+ assert_eq!(shell.committable(partition_id), Some(3));
+ }
+
+ #[tokio::test]
+ async fn a_seeded_dormant_person_reaches_the_same_membership_as_a_live_evaluated_one() {
+ let live_person = Uuid::from_u128(0xA11CE);
+ let seeded_person = Uuid::from_u128(0x5EED);
+ // One partition for both, so the two folds are directly comparable.
+ let partition_id = 0;
+ let mut shell = Shell::new(mixed_cohorts());
+
+ shell.live_pageview(partition_id, live_person, Some(r#"{"email":"[email protected]"}"#));
+ // Same behavioral history, but no event carried person properties.
+ shell.live_pageview(partition_id, seeded_person, None);
+ shell
+ .run(
+ partition_id,
+ &seed_for(seeded_person, &[PERSON_HASH], &[PERSON_HASH], now_ms()),
+ 0,
+ )
+ .await;
+
+ let live = shell.record(partition_id, live_person).unwrap();
+ let seeded = shell.record(partition_id, seeded_person).unwrap();
+ assert_eq!(
+ seeded.matched, live.matched,
+ "the matched set is the whole of person-property membership",
+ );
+
+ // Compose the live person's stage 2 the way its next flip would; the seed already did so.
+ let leaves = [(
+ LeafStateKey::for_person_property(&hash(PERSON_HASH).as_bytes()),
+ live_person,
+ )];
+ compose_stage2(
+ partition_id,
+ &shell.handle,
+ &shell.filters,
+ &leaves,
+ now_ms(),
+ LAST_UPDATED,
+ ReadLane::Event,
+ )
+ .await
+ .unwrap();
+
+ for (person, who) in [(live_person, "live"), (seeded_person, "seeded")] {
+ assert!(
+ shell.stage2(partition_id, person, 1).unwrap().in_cohort,
+ "{who}: single-leaf cohort",
+ );
+ assert!(
+ shell.stage2(partition_id, person, 2).unwrap().in_cohort,
+ "{who}: composed cohort",
+ );
+ }
+
+ assert_ne!(
+ seeded.catalog_fingerprint, live.catalog_fingerprint,
+ "the seed's zeroed fingerprints must force a full re-eval on the next event",
+ );
+ assert_ne!(seeded.props_fingerprint, live.props_fingerprint);
+ assert!(
+ seeded.stamp < live.stamp,
+ "the seed installs a floor a margin below its scan, never the live event's own stamp",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/workers/seed_path.rs b/rust/cohort-stream-processor/src/workers/seed_path.rs
index d00b6dd70a0a..b8a9a1af8543 100644
--- a/rust/cohort-stream-processor/src/workers/seed_path.rs
+++ b/rust/cohort-stream-processor/src/workers/seed_path.rs
@@ -14,7 +14,7 @@ use metrics::{counter, gauge};
use tracing::{debug, warn};
use uuid::Uuid;
-use cohort_core::seed::{ReconcileTile, RunId, SeedTile};
+use cohort_core::seed::{PersonSeed, ReconcileTile, RunId, SeedTile};
use crate::consumers::seeds::SeedWork;
use crate::filters::manager::CatalogHandle;
@@ -46,34 +46,65 @@ use crate::stage2::{
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::worker::{
first_cascades, produce_cascades, produce_membership, transition_metric_label,
};
-/// Where a tile applies after tombstone resolution; an exhausted hop budget is unrepresentable
+/// A seed kind that can be re-keyed onto a merge survivor.
+pub(crate) trait RekeyableSeed: Sized {
+ fn person_id(&self) -> Uuid;
+ fn rekeyed_to(&self, survivor: Uuid, cap: u8) -> Option<Self>;
+}
+
+impl RekeyableSeed for SeedTile {
+ fn person_id(&self) -> Uuid {
+ SeedTile::person_id(self)
+ }
+
+ fn rekeyed_to(&self, survivor: Uuid, cap: u8) -> Option<Self> {
+ SeedTile::rekeyed_to(self, survivor, cap)
+ }
+}
+
+impl RekeyableSeed for PersonSeed {
+ fn person_id(&self) -> Uuid {
+ PersonSeed::person_id(self)
+ }
+
+ fn rekeyed_to(&self, survivor: Uuid, cap: u8) -> Option<Self> {
+ PersonSeed::rekeyed_to(self, survivor, cap)
+ }
+}
+
+/// Where a seed applies after tombstone resolution; an exhausted hop budget is unrepresentable
/// as a re-produce, forcing the degraded inline arm.
#[derive(Debug, Clone, PartialEq, Eq)]
-pub(crate) enum TileRoute {
+pub(crate) enum SeedRoute<T> {
ApplyLocal { person: Uuid },
- ReProduce { tile: SeedTile },
+ ReProduce { seed: T },
CapExhausted { person: Uuid },
}
-/// Total routing of a tile through its tombstone [`Resolution`].
-pub(crate) fn route_tile(tile: &SeedTile, resolution: Resolution, cap: u8) -> TileRoute {
+/// Total routing of a seed through its tombstone [`Resolution`].
+pub(crate) fn route_seed<T: RekeyableSeed>(
+ seed: &T,
+ resolution: Resolution,
+ cap: u8,
+) -> SeedRoute<T> {
match resolution {
- Resolution::NotMerged => TileRoute::ApplyLocal {
- person: tile.person_id(),
+ Resolution::NotMerged => SeedRoute::ApplyLocal {
+ person: seed.person_id(),
},
- Resolution::Inline { final_person, .. } => TileRoute::ApplyLocal {
+ Resolution::Inline { final_person, .. } => SeedRoute::ApplyLocal {
person: final_person,
},
Resolution::CrossPartition { target_person, .. } => {
- match tile.rekeyed_to(target_person, cap) {
- Some(rekeyed) => TileRoute::ReProduce { tile: rekeyed },
- None => TileRoute::CapExhausted {
+ match seed.rekeyed_to(target_person, cap) {
+ Some(rekeyed) => SeedRoute::ReProduce { seed: rekeyed },
+ None => SeedRoute::CapExhausted {
person: target_person,
},
}
@@ -490,6 +521,20 @@ pub(crate) async fn handle_seed(
admit_reconcile(partition_id, merge, reconcile_queue, tile, offset);
return;
}
+ SeedWork::Person(seed) => {
+ handle_person_seed(
+ partition_id,
+ handle,
+ catalog,
+ sink,
+ merge,
+ last_updated,
+ seed,
+ offset,
+ )
+ .await;
+ return;
+ }
SeedWork::Tile(tile) => tile,
};
@@ -525,9 +570,9 @@ pub(crate) async fn handle_seed(
return;
}
};
- let person = match route_tile(tile, resolution, MAX_CROSS_PARTITION_REDIRECT_HOPS) {
- TileRoute::ApplyLocal { person } => person,
- TileRoute::ReProduce { tile: rekeyed } => {
+ let person = match route_seed(tile, resolution, MAX_CROSS_PARTITION_REDIRECT_HOPS) {
+ SeedRoute::ApplyLocal { person } => person,
+ SeedRoute::ReProduce { seed: rekeyed } => {
// Ack before mark; the tile has no other copy. Exactly one Ok ack — an empty vector
// would make an `all(is_ok)` guard vacuously true and commit past a lost tile.
let acks = merge.seed_tile_sink.produce(vec![rekeyed]).await;
@@ -545,7 +590,7 @@ pub(crate) async fn handle_seed(
}
return;
}
- TileRoute::CapExhausted { person } => {
+ SeedRoute::CapExhausted { person } => {
counter!(SEED_REKEY_HOP_CAPPED_TOTAL).increment(1);
// Same degrade as the event path: orphaned-but-bounded state (the survivor's live
// path never reads this slice) that ages out via eviction, preferred over a silent
@@ -889,7 +934,7 @@ fn stage_seed_membership_registers(
);
}
-fn tag_seed(changes: &mut [CohortMembershipChange], run_id: RunId) {
+pub(crate) fn tag_seed(changes: &mut [CohortMembershipChange], run_id: RunId) {
for change in changes {
change.origin = Some(ChangeOrigin::Seed);
change.run_id = Some(run_id);
@@ -897,7 +942,7 @@ fn tag_seed(changes: &mut [CohortMembershipChange], run_id: RunId) {
}
/// Advance the seed tracker past `offset`. A mark beyond the dispatch ceiling is capped and counted.
-fn mark_processed(tracker: &OffsetTracker, partition_id: u16, offset: i64) {
+pub(crate) fn mark_processed(tracker: &OffsetTracker, partition_id: u16, offset: i64) {
if let MarkOutcome::CappedAheadOfDispatch =
tracker.mark_processed(partition_id as i32, offset + 1)
{
@@ -912,7 +957,7 @@ fn mark_processed(tracker: &OffsetTracker, partition_id: u16, offset: i64) {
/// Pin the seed commit floor at the failed offset so Kafka redelivers it; emit
/// [`SEED_HELD_OFFSET_GAUGE`] so the stall is visible.
-fn hold(tracker: &OffsetTracker, partition_id: u16, offset: i64) {
+pub(crate) fn hold(tracker: &OffsetTracker, partition_id: u16, offset: i64) {
let floor = tracker.hold(partition_id as i32, offset);
gauge!(SEED_HELD_OFFSET_GAUGE, "partition" => partition_id.to_string()).set(floor as f64);
}
@@ -1346,18 +1391,18 @@ mod tests {
}
#[test]
- fn route_tile_maps_each_resolution_and_caps_the_hop_budget() {
+ fn route_seed_maps_each_resolution_and_caps_the_hop_budget() {
let tile = tile_for(Uuid::from_u128(0xA11CE), now_day(), 1);
let survivor = Uuid::from_u128(0xB0B);
assert_eq!(
- route_tile(&tile, Resolution::NotMerged, 8),
- TileRoute::ApplyLocal {
+ route_seed(&tile, Resolution::NotMerged, 8),
+ SeedRoute::ApplyLocal {
person: tile.person_id()
},
);
assert_eq!(
- route_tile(
+ route_seed(
&tile,
Resolution::Inline {
final_person: survivor,
@@ -1365,9 +1410,9 @@ mod tests {
},
8,
),
- TileRoute::ApplyLocal { person: survivor },
+ SeedRoute::ApplyLocal { person: survivor },
);
- match route_tile(
+ match route_seed(
&tile,
Resolution::CrossPartition {
target_person: survivor,
@@ -1375,7 +1420,7 @@ mod tests {
},
8,
) {
- TileRoute::ReProduce { tile: rekeyed } => {
+ SeedRoute::ReProduce { seed: rekeyed } => {
assert_eq!(rekeyed.person_id(), survivor);
assert_eq!(rekeyed.redirect_hops(), 1);
assert_eq!(
@@ -1388,7 +1433,7 @@ mod tests {
}
// Cap 0: an over-cap re-produce is unrepresentable — the cap arm is forced.
assert_eq!(
- route_tile(
+ route_seed(
&tile,
Resolution::CrossPartition {
target_person: survivor,
@@ -1396,7 +1441,7 @@ mod tests {
},
0,
),
- TileRoute::CapExhausted { person: survivor },
+ SeedRoute::CapExhausted { person: survivor },
);
}
@@ -1820,6 +1865,7 @@ mod tests {
live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),
register_transfer_enabled: false,
reconcile: crate::workers::ReconcileDeps::default(),
+ person_seed: crate::workers::PersonSeedDeps::default(),
};
let reconcile_queue =
ReconcileQueue::new(0, deps.reconcile.backlog.clone(), handle.clone());
@@ -2214,6 +2260,13 @@ mod tests {
) -> Vec<Result<(), common_kafka::kafka_producer::KafkaProduceError>> {
Vec::new()
}
+
+ async fn produce_person(
+ &self,
+ _seeds: Vec<PersonSeed>,
+ ) -> Vec<Result<(), common_kafka::kafka_producer::KafkaProduceError>> {
+ Vec::new()
+ }
}
#[tokio::test]
diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rs
index 5fe32d31dd17..65ea8a8c1152 100644
--- a/rust/cohort-stream-processor/src/workers/worker.rs
+++ b/rust/cohort-stream-processor/src/workers/worker.rs
@@ -1213,6 +1213,7 @@ mod tombstone_redirect_tests {
live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),
register_transfer_enabled: false,
reconcile: crate::workers::ReconcileDeps::default(),
+ person_seed: crate::workers::PersonSeedDeps::default(),
})
}
@@ -1243,6 +1244,7 @@ mod tombstone_redirect_tests {
live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),
register_transfer_enabled: false,
reconcile: crate::workers::ReconcileDeps::default(),
+ person_seed: crate::workers::PersonSeedDeps::default(),
})
}
@@ -1269,6 +1271,7 @@ mod tombstone_redirect_tests {
live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),
register_transfer_enabled: false,
reconcile: crate::workers::ReconcileDeps::default(),
+ person_seed: crate::workers::PersonSeedDeps::default(),
})
}
diff --git a/rust/cohort-stream-processor/tests/cascade_consumer.rs b/rust/cohort-stream-processor/tests/cascade_consumer.rs
index dbc18d281b13..66d73c03207b 100644
--- a/rust/cohort-stream-processor/tests/cascade_consumer.rs
+++ b/rust/cohort-stream-processor/tests/cascade_consumer.rs
@@ -467,6 +467,7 @@ async fn spawn_instance(
),
register_transfer_enabled: false,
reconcile: cohort_stream_processor::workers::ReconcileDeps::default(),
+ person_seed: cohort_stream_processor::workers::PersonSeedDeps::default(),
});
let dispatcher = Arc::new(EventDispatcher::new(
diff --git a/rust/cohort-stream-processor/tests/merge_consumer.rs b/rust/cohort-stream-processor/tests/merge_consumer.rs
index e3843ed84f5e..58fbdc8545b8 100644
--- a/rust/cohort-stream-processor/tests/merge_consumer.rs
+++ b/rust/cohort-stream-processor/tests/merge_consumer.rs
@@ -623,6 +623,7 @@ async fn spawn_instance(
),
register_transfer_enabled: false,
reconcile: cohort_stream_processor::workers::ReconcileDeps::default(),
+ person_seed: cohort_stream_processor::workers::PersonSeedDeps::default(),
});
let dispatcher = Arc::new(EventDispatcher::new(
diff --git a/rust/cohort-stream-processor/tests/merge_durability.rs b/rust/cohort-stream-processor/tests/merge_durability.rs
index 5bd7daa6024c..5971c165af62 100644
--- a/rust/cohort-stream-processor/tests/merge_durability.rs
+++ b/rust/cohort-stream-processor/tests/merge_durability.rs
@@ -721,6 +721,7 @@ async fn spawn_instance(
),
register_transfer_enabled: false,
reconcile: cohort_stream_processor::workers::ReconcileDeps::default(),
+ person_seed: cohort_stream_processor::workers::PersonSeedDeps::default(),
});
let dispatcher = Arc::new(EventDispatcher::new(
diff --git a/rust/cohort-stream-processor/tests/seed_consumer.rs b/rust/cohort-stream-processor/tests/seed_consumer.rs
index 8ba80d23cd64..a2a4f1b94c4c 100644
--- a/rust/cohort-stream-processor/tests/seed_consumer.rs
+++ b/rust/cohort-stream-processor/tests/seed_consumer.rs
@@ -619,6 +619,7 @@ async fn spawn_instance(
scan_page: 1,
backlog: reconcile_backlog.clone(),
},
+ person_seed: cohort_stream_processor::workers::PersonSeedDeps::default(),
});
let dispatcher = Arc::new(EventDispatcher::new(