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): reconcile snapshot drain path (#72728)

Matheus Batista2eab04729764
diff --git a/rust/cohort-core/src/filters/loader.rs b/rust/cohort-core/src/filters/loader.rs
index 5c52114246a0..e1a340835d53 100644
--- a/rust/cohort-core/src/filters/loader.rs
+++ b/rust/cohort-core/src/filters/loader.rs
@@ -12,11 +12,16 @@ use tracing::warn;
use crate::filters::catalog::FilterCatalog;
use crate::filters::reverse_index::TeamFiltersBuilder;
use crate::filters::{CohortId, FilterError, TeamId};
-use crate::metrics::{FILTER_CATALOG_COHORT_PARSE_ERRORS, FILTER_CATALOG_TZ_FALLBACK};
+use crate::metrics::{
+ FILTER_CATALOG_COHORT_PARSE_ERRORS, FILTER_CATALOG_INVALID_SHAPE_HASH,
+ FILTER_CATALOG_TZ_FALLBACK,
+};
+use crate::seed::BehavioralShapeHash;
/// Realtime cohorts to load, mirroring the Node filter manager's predicate, joined to
/// `posthog_team` for the team timezone the bucket variants use for calendar-day computation.
-pub const REALTIME_COHORTS_SQL: &str = "SELECT c.id, c.team_id, c.filters, t.timezone \
+pub const REALTIME_COHORTS_SQL: &str = "SELECT c.id, c.team_id, c.filters, \
+ c.behavioral_filters_shape_hash, t.timezone \
FROM posthog_cohort c \
JOIN posthog_team t ON t.id = c.team_id \
WHERE c.cohort_type = 'realtime' AND c.deleted = false AND c.filters IS NOT NULL";
@@ -27,6 +32,7 @@ pub struct CohortRow {
pub id: i32,
pub team_id: i32,
pub filters: Value,
+ pub behavioral_filters_shape_hash: Option<String>,
/// `posthog_team.timezone` — a non-null IANA zone name (default `"UTC"`).
pub timezone: String,
}
@@ -54,14 +60,36 @@ pub fn build_catalog_from_rows(rows: Vec<CohortRow>, cascade_enabled: bool) -> F
)
});
- if let Err(err) = builder.add_cohort(cohort_id, team_id, &row.filters) {
- counter!(FILTER_CATALOG_COHORT_PARSE_ERRORS).increment(1);
- warn!(
- cohort_id = cohort_id.0,
- team_id = team_id.0,
- error = %err,
- "skipping cohort that failed to parse",
- );
+ match builder.add_cohort(cohort_id, team_id, &row.filters) {
+ Ok(()) => {
+ match row.behavioral_filters_shape_hash {
+ // Python's canonical extractor returns an empty string when a cohort has no
+ // behavioral leaves. It is an expected unknown guard, not malformed data.
+ None => {}
+ Some(raw_hash) if raw_hash.is_empty() => {}
+ Some(raw_hash) => match BehavioralShapeHash::parse(&raw_hash) {
+ Ok(hash) => builder.set_behavioral_shape_hash(cohort_id, hash),
+ Err(error) => {
+ counter!(FILTER_CATALOG_INVALID_SHAPE_HASH).increment(1);
+ warn!(
+ cohort_id = cohort_id.0,
+ team_id = team_id.0,
+ error = %error,
+ "ignoring invalid persisted behavioral shape hash",
+ );
+ }
+ },
+ }
+ }
+ Err(err) => {
+ counter!(FILTER_CATALOG_COHORT_PARSE_ERRORS).increment(1);
+ warn!(
+ cohort_id = cohort_id.0,
+ team_id = team_id.0,
+ error = %err,
+ "skipping cohort that failed to parse",
+ );
+ }
}
}
@@ -92,6 +120,8 @@ mod tests {
use super::*;
use serde_json::json;
+ const SHAPE_HASH: &str = "persisted-authoritative-hash";
+
fn row(id: i32, team_id: i32, filters: Value) -> CohortRow {
row_with_tz(id, team_id, filters, "UTC")
}
@@ -101,10 +131,17 @@ mod tests {
id,
team_id,
filters,
+ behavioral_filters_shape_hash: None,
timezone: timezone.to_string(),
}
}
+ fn row_with_shape_hash(id: i32, team_id: i32, shape_hash: Option<&str>) -> CohortRow {
+ let mut row = row(id, team_id, behavioral_cohort());
+ row.behavioral_filters_shape_hash = shape_hash.map(str::to_string);
+ row
+ }
+
fn behavioral_cohort() -> Value {
json!({
"properties": {
@@ -128,6 +165,42 @@ mod tests {
assert_eq!(catalog.team_count(), 0);
}
+ #[test]
+ fn build_catalog_carries_only_valid_persisted_behavioral_shape_hashes() {
+ assert!(REALTIME_COHORTS_SQL.contains("c.behavioral_filters_shape_hash"));
+ let mut malformed = row(5, 7, json!({ "bogus": true }));
+ malformed.behavioral_filters_shape_hash = Some(SHAPE_HASH.to_string());
+ let catalog = build_catalog_from_rows(
+ vec![
+ row_with_shape_hash(1, 7, Some(SHAPE_HASH)),
+ row_with_shape_hash(2, 7, None),
+ row_with_shape_hash(3, 7, Some("")),
+ row_with_shape_hash(4, 7, Some("non-ascii-é")),
+ malformed,
+ ],
+ false,
+ );
+
+ let team = catalog.team(TeamId(7)).expect("team present");
+ assert_eq!(
+ team.behavioral_shape_hashes[&CohortId(1)].as_str(),
+ SHAPE_HASH,
+ );
+ assert!(!team.behavioral_shape_hashes.contains_key(&CohortId(2)));
+ assert!(!team.behavioral_shape_hashes.contains_key(&CohortId(3)));
+ assert!(!team.behavioral_shape_hashes.contains_key(&CohortId(4)));
+ assert!(!team.behavioral_shape_hashes.contains_key(&CohortId(5)));
+ assert!(team.cohorts.contains_key(&CohortId(3)));
+ assert!(
+ team.cohorts.contains_key(&CohortId(4)),
+ "only the bad hash is ignored"
+ );
+ assert!(
+ !team.cohorts.contains_key(&CohortId(5)),
+ "the malformed cohort is skipped"
+ );
+ }
+
#[test]
fn build_catalog_resolves_team_timezone_and_falls_back_to_utc() {
use chrono_tz::America::New_York;
diff --git a/rust/cohort-core/src/filters/reverse_index.rs b/rust/cohort-core/src/filters/reverse_index.rs
index 5f2a0f1c8327..4ddf2376cf0d 100644
--- a/rust/cohort-core/src/filters/reverse_index.rs
+++ b/rust/cohort-core/src/filters/reverse_index.rs
@@ -23,6 +23,7 @@ use crate::leaf_state::variant::StateVariant;
use crate::metrics::{
COHORT_ELIGIBILITY_TOTAL, COHORT_IN_CYCLE_TOTAL, FILTER_CATALOG_SKIPPED_LEAVES,
};
+use crate::seed::BehavioralShapeHash;
#[derive(Debug, Clone, Copy)]
pub struct LeafStateMeta {
@@ -70,6 +71,8 @@ pub struct TeamFilters {
pub eligibility: HashMap<CohortId, CohortEligibility>,
/// Parsed trees by cohort, retained for the Stage 2 re-walk.
pub cohorts: HashMap<CohortId, CohortTree>,
+ /// Persisted behavioral leaf-shape hashes used to fence reconcile work from cohort edits.
+ pub behavioral_shape_hashes: HashMap<CohortId, BehavioralShapeHash>,
/// The team's resolved IANA timezone, used by bucket variants for calendar-day computation.
pub timezone: Tz,
}
@@ -94,6 +97,7 @@ impl Default for TeamFilters {
by_referenced_cohort: HashMap::new(),
eligibility: HashMap::new(),
cohorts: HashMap::new(),
+ behavioral_shape_hashes: HashMap::new(),
timezone: UTC,
}
}
@@ -118,6 +122,7 @@ pub struct TeamFiltersBuilder {
cohorts: HashMap<CohortId, CohortTree>,
/// Per-cohort eligibility signals captured during parse.
flags: HashMap<CohortId, CohortParseFlags>,
+ behavioral_shape_hashes: HashMap<CohortId, BehavioralShapeHash>,
}
impl LeafSink for TeamFiltersBuilder {
@@ -156,6 +161,12 @@ impl LeafSink for TeamFiltersBuilder {
}
impl TeamFiltersBuilder {
+ /// Attach the persisted behavioral shape guard for `cohort_id`. Freeze discards the value when
+ /// no cohort with that id parsed successfully.
+ pub fn set_behavioral_shape_hash(&mut self, cohort_id: CohortId, hash: BehavioralShapeHash) {
+ self.behavioral_shape_hashes.insert(cohort_id, hash);
+ }
+
pub fn add_cohort(
&mut self,
cohort_id: CohortId,
@@ -277,6 +288,8 @@ impl TeamFiltersBuilder {
(name, hashes)
})
.collect();
+ let mut behavioral_shape_hashes = self.behavioral_shape_hashes;
+ behavioral_shape_hashes.retain(|cohort_id, _| self.cohorts.contains_key(cohort_id));
TeamFilters {
by_condition_to_lsk: sorted_vec_map(self.by_condition_to_lsk),
@@ -294,6 +307,7 @@ impl TeamFiltersBuilder {
by_referenced_cohort,
eligibility,
cohorts: self.cohorts,
+ behavioral_shape_hashes,
timezone,
}
}
@@ -505,6 +519,31 @@ mod tests {
);
}
+ #[test]
+ fn freeze_retains_behavioral_shape_hashes_only_for_parsed_cohorts() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder.set_behavioral_shape_hash(
+ CohortId(1),
+ BehavioralShapeHash::parse("persisted").unwrap(),
+ );
+ builder
+ .set_behavioral_shape_hash(CohortId(99), BehavioralShapeHash::parse("orphan").unwrap());
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7)]),
+ )
+ .unwrap();
+
+ let frozen = builder.freeze(UTC);
+ assert_eq!(
+ frozen.behavioral_shape_hashes[&CohortId(1)].as_str(),
+ "persisted",
+ );
+ assert!(!frozen.behavioral_shape_hashes.contains_key(&CohortId(99)));
+ }
+
#[test]
fn identical_leaves_dedupe_to_single_entries() {
let mut builder = TeamFiltersBuilder::default();
diff --git a/rust/cohort-core/src/metrics.rs b/rust/cohort-core/src/metrics.rs
index 04fc538cc15d..a45e1ef9a08e 100644
--- a/rust/cohort-core/src/metrics.rs
+++ b/rust/cohort-core/src/metrics.rs
@@ -10,6 +10,10 @@ pub const FILTER_CATALOG_SKIPPED_LEAVES: &str = "filter_catalog_skipped_leaves_t
pub const FILTER_CATALOG_COHORT_PARSE_ERRORS: &str = "filter_catalog_cohort_parse_errors_total";
/// Teams whose timezone did not parse as an IANA zone and fell back to UTC (counter).
pub const FILTER_CATALOG_TZ_FALLBACK: &str = "filter_catalog_tz_fallback_total";
+/// Cohorts whose persisted `behavioral_filters_shape_hash` failed to parse (counter). The cohort
+/// loads but reads as `HashUnknown`, so every reconcile for it discards — **alert on a sustained
+/// non-zero level**, it signals drift between the Python hash extractor and the Rust bounds.
+pub const FILTER_CATALOG_INVALID_SHAPE_HASH: &str = "filter_catalog_invalid_shape_hash_total";
/// Cohorts classified by composition eligibility at freeze, labelled by `class` (counter).
pub const COHORT_ELIGIBILITY_TOTAL: &str = "cohort_eligibility_total";
/// Cohorts excluded because they sit in a cohort-reference cycle (counter).
diff --git a/rust/cohort-core/src/seed/decode.rs b/rust/cohort-core/src/seed/decode.rs
index 3f3c5c873310..0dfeb1bb11a8 100644
--- a/rust/cohort-core/src/seed/decode.rs
+++ b/rust/cohort-core/src/seed/decode.rs
@@ -1,19 +1,20 @@
//! Tolerant two-stage decode of a seed-topic payload: a cheap kind/schema probe, then the full
-//! [`SeedTile`] parse only for a supported combination. The consumer's policy is skip-and-count
-//! (never wedge a partition): unknown kinds and newer schemas are data for later slices'
+//! the full wire type parse only for a supported combination. The consumer's policy is
+//! skip-and-count (never wedge a partition): unknown kinds and newer schemas are data for later
//! consumers, and a malformed payload is deterministic bytes that would fail identically on every
//! redelivery.
use serde::Deserialize;
+use super::reconcile::{ReconcileTile, RECONCILE_KIND, RECONCILE_SCHEMA_VERSION};
use super::tile::{SeedTile, SCHEMA_VERSION, TILE_KIND};
-/// The probe outcome for a supported-or-not payload. `UnknownKind` covers kinds this consumer
-/// does not handle (e.g. a reconcile control tile before its slice ships); `UnsupportedSchema`
-/// covers a known kind at a newer schema version.
+/// The probe outcome for a supported-or-not payload. `UnknownKind` covers kinds this consumer does
+/// not handle; `UnsupportedSchema` covers a known kind at a newer schema version.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DecodedSeed {
Tile(SeedTile),
+ Reconcile(ReconcileTile),
UnknownKind { kind: String, schema_version: u32 },
UnsupportedSchema { kind: String, schema_version: u32 },
}
@@ -26,19 +27,22 @@ struct SeedProbe {
pub fn decode_seed(payload: &[u8]) -> Result<DecodedSeed, serde_json::Error> {
let probe: SeedProbe = serde_json::from_slice(payload)?;
- if probe.kind != TILE_KIND {
- return Ok(DecodedSeed::UnknownKind {
+ match probe.kind.as_str() {
+ TILE_KIND if probe.schema_version == SCHEMA_VERSION => {
+ Ok(DecodedSeed::Tile(serde_json::from_slice(payload)?))
+ }
+ RECONCILE_KIND if probe.schema_version == RECONCILE_SCHEMA_VERSION => {
+ Ok(DecodedSeed::Reconcile(serde_json::from_slice(payload)?))
+ }
+ TILE_KIND | RECONCILE_KIND => Ok(DecodedSeed::UnsupportedSchema {
kind: probe.kind,
schema_version: probe.schema_version,
- });
- }
- if probe.schema_version != SCHEMA_VERSION {
- return Ok(DecodedSeed::UnsupportedSchema {
+ }),
+ _ => Ok(DecodedSeed::UnknownKind {
kind: probe.kind,
schema_version: probe.schema_version,
- });
+ }),
}
- Ok(DecodedSeed::Tile(serde_json::from_slice(payload)?))
}
#[cfg(test)]
@@ -48,7 +52,9 @@ mod tests {
use uuid::Uuid;
use crate::filters::TeamId;
- use crate::seed::{ClaimEpoch, ConditionHash, RunId, SChunkMs};
+ use crate::seed::{
+ BehavioralShapeHash, ClaimEpoch, ConditionHash, ReconcileTile, RunId, SChunkMs,
+ };
use super::*;
@@ -66,6 +72,19 @@ mod tests {
.unwrap()
}
+ fn reconcile_json() -> serde_json::Value {
+ serde_json::to_value(ReconcileTile::new(
+ TeamId(2),
+ crate::filters::CohortId(42),
+ BehavioralShapeHash::parse(
+ "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
+ )
+ .unwrap(),
+ RunId(Uuid::nil()),
+ ))
+ .unwrap()
+ }
+
#[test]
fn decode_probes_kind_and_schema_before_the_full_parse() {
let tile = tile_json();
@@ -73,14 +92,20 @@ mod tests {
assert!(matches!(decode(&tile).unwrap(), DecodedSeed::Tile(_)));
- let mut reconcile = tile.clone();
- reconcile["kind"] = serde_json::json!("reconcile");
+ let reconcile = reconcile_json();
assert_eq!(
decode(&reconcile).unwrap(),
+ DecodedSeed::Reconcile(serde_json::from_value(reconcile.clone()).unwrap()),
+ );
+
+ let mut unknown = tile.clone();
+ unknown["kind"] = serde_json::json!("future_control");
+ assert_eq!(
+ decode(&unknown).unwrap(),
DecodedSeed::UnknownKind {
- kind: "reconcile".to_string(),
+ kind: "future_control".to_string(),
schema_version: 1,
- }
+ },
);
let mut newer = tile.clone();
@@ -93,12 +118,27 @@ mod tests {
}
);
+ let mut newer_reconcile = reconcile.clone();
+ newer_reconcile["schema_version"] = serde_json::json!(2);
+ newer_reconcile["filters_hash"] = serde_json::json!("");
+ assert_eq!(
+ decode(&newer_reconcile).unwrap(),
+ DecodedSeed::UnsupportedSchema {
+ kind: "reconcile".to_string(),
+ schema_version: 2,
+ },
+ );
+
// A supported kind/schema with a malformed body is a decode error, not a skip: the probe
// admits it, the full parse rejects it (zero count here).
let mut zero_count = tile.clone();
zero_count["count"] = serde_json::json!(0);
assert!(decode(&zero_count).is_err());
+ let mut empty_hash = reconcile;
+ empty_hash["filters_hash"] = serde_json::json!("");
+ assert!(decode(&empty_hash).is_err());
+
let mut kindless = tile;
kindless.as_object_mut().unwrap().remove("kind");
assert!(decode(&kindless).is_err());
diff --git a/rust/cohort-core/src/seed/mod.rs b/rust/cohort-core/src/seed/mod.rs
index 92b05acbef00..aeab50b6e0e6 100644
--- a/rust/cohort-core/src/seed/mod.rs
+++ b/rust/cohort-core/src/seed/mod.rs
@@ -1,16 +1,20 @@
//! The seed wire contract shared by the backfill seeder (producer) and the stream processor
-//! (consumer): the [`SeedTile`] day-tile, its id 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.
+//! (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
+//! as [`crate::events`]: both processes must agree on these bytes, and the processor cannot depend
+//! on the seeder.
//!
-//! The JSON layout is frozen; the golden test in [`tile`] is the byte-level regression gate. New
-//! fields must be additive and skipped when absent-equivalent (see `redirect_hops`) so tiles
-//! produced by older seeders keep parsing and older consumers keep ignoring newer producers.
+//! The JSON layouts are frozen; the golden tests in [`tile`] and [`reconcile`] are the byte-level
+//! regression gates. New fields must be additive and skipped when absent-equivalent (see
+//! `redirect_hops`) so tiles produced by older seeders keep parsing and older consumers keep
+//! ignoring newer producers.
pub mod decode;
pub mod ids;
+pub mod reconcile;
pub mod tile;
pub use decode::{decode_seed, DecodedSeed};
pub use ids::{ClaimEpoch, ConditionHash, ConditionHashError, RunId, SChunkMs};
+pub use reconcile::{BehavioralShapeHash, BehavioralShapeHashError, ReconcileTile};
pub use tile::SeedTile;
diff --git a/rust/cohort-core/src/seed/reconcile.rs b/rust/cohort-core/src/seed/reconcile.rs
new file mode 100644
index 000000000000..67e6666cd2b5
--- /dev/null
+++ b/rust/cohort-core/src/seed/reconcile.rs
@@ -0,0 +1,275 @@
+//! Wire contract for one partition-targeted reconcile control tile.
+
+use std::fmt;
+use std::str::FromStr;
+
+use serde::de::{Deserializer, Error as DeError, Unexpected};
+use serde::ser::Serializer;
+use serde::{Deserialize, Serialize};
+
+use crate::filters::{CohortId, TeamId};
+
+use super::ids::RunId;
+
+pub(super) const RECONCILE_SCHEMA_VERSION: u32 = 1;
+pub(super) const RECONCILE_KIND: &str = "reconcile";
+
+/// The persisted behavioral filter-shape fingerprint that fences a reconcile job from cohort edits.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct BehavioralShapeHash(Box<str>);
+
+impl BehavioralShapeHash {
+ pub fn parse(value: &str) -> Result<Self, BehavioralShapeHashError> {
+ if value.is_empty() {
+ return Err(BehavioralShapeHashError::Empty);
+ }
+ if value.len() > 64 {
+ return Err(BehavioralShapeHashError::TooLong(value.len()));
+ }
+ if !value.is_ascii() {
+ return Err(BehavioralShapeHashError::NonAscii);
+ }
+ Ok(Self(value.into()))
+ }
+
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+impl fmt::Display for BehavioralShapeHash {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter.write_str(self.as_str())
+ }
+}
+
+impl FromStr for BehavioralShapeHash {
+ type Err = BehavioralShapeHashError;
+
+ fn from_str(value: &str) -> Result<Self, Self::Err> {
+ Self::parse(value)
+ }
+}
+
+impl Serialize for BehavioralShapeHash {
+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ serializer.serialize_str(self.as_str())
+ }
+}
+
+impl<'de> Deserialize<'de> for BehavioralShapeHash {
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let value = String::deserialize(deserializer)?;
+ Self::parse(&value).map_err(|_| {
+ DeError::invalid_value(
+ Unexpected::Str(&value),
+ &"a non-empty ASCII behavioral shape hash of at most 64 bytes",
+ )
+ })
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+pub enum BehavioralShapeHashError {
+ #[error("behavioral shape hash must not be empty")]
+ Empty,
+ #[error("behavioral shape hash must be at most 64 bytes, got {0}")]
+ TooLong(usize),
+ #[error("behavioral shape hash must contain only ASCII characters")]
+ NonAscii,
+}
+
+/// A control tile that requests one partition's full current snapshot for one behavioral cohort.
+/// Field order is the wire order.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ReconcileTile {
+ #[serde(deserialize_with = "deserialize_schema_version")]
+ schema_version: u32,
+ kind: ReconcileKind,
+ #[serde(
+ serialize_with = "serialize_team_id",
+ deserialize_with = "deserialize_team_id"
+ )]
+ team_id: TeamId,
+ #[serde(
+ serialize_with = "serialize_cohort_id",
+ deserialize_with = "deserialize_cohort_id"
+ )]
+ cohort_id: CohortId,
+ filters_hash: BehavioralShapeHash,
+ run_id: RunId,
+}
+
+impl ReconcileTile {
+ pub fn new(
+ team_id: TeamId,
+ cohort_id: CohortId,
+ filters_hash: BehavioralShapeHash,
+ run_id: RunId,
+ ) -> Self {
+ Self {
+ schema_version: RECONCILE_SCHEMA_VERSION,
+ kind: ReconcileKind,
+ team_id,
+ cohort_id,
+ filters_hash,
+ run_id,
+ }
+ }
+
+ pub const fn team_id(&self) -> TeamId {
+ self.team_id
+ }
+
+ pub const fn cohort_id(&self) -> CohortId {
+ self.cohort_id
+ }
+
+ pub fn filters_hash(&self) -> &BehavioralShapeHash {
+ &self.filters_hash
+ }
+
+ pub const fn run_id(&self) -> RunId {
+ self.run_id
+ }
+}
+
+/// A zero-sized discriminant proven to be [`RECONCILE_KIND`] during deserialization.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+struct ReconcileKind;
+
+impl Serialize for ReconcileKind {
+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ serializer.serialize_str(RECONCILE_KIND)
+ }
+}
+
+impl<'de> Deserialize<'de> for ReconcileKind {
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let value = String::deserialize(deserializer)?;
+ if value != RECONCILE_KIND {
+ return Err(DeError::invalid_value(
+ Unexpected::Str(&value),
+ &"seed kind \"reconcile\"",
+ ));
+ }
+ Ok(Self)
+ }
+}
+
+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_cohort_id<S: Serializer>(value: &CohortId, serializer: S) -> Result<S::Ok, S::Error> {
+ serializer.serialize_i32(value.0)
+}
+
+fn deserialize_cohort_id<'de, D: Deserializer<'de>>(deserializer: D) -> Result<CohortId, D::Error> {
+ i32::deserialize(deserializer).map(CohortId)
+}
+
+fn deserialize_schema_version<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u32, D::Error> {
+ let value = u32::deserialize(deserializer)?;
+ if value != RECONCILE_SCHEMA_VERSION {
+ return Err(DeError::invalid_value(
+ Unexpected::Unsigned(u64::from(value)),
+ &"reconcile schema version 1",
+ ));
+ }
+ Ok(value)
+}
+
+#[cfg(test)]
+mod tests {
+ use uuid::Uuid;
+
+ use super::*;
+
+ // `extract_behavioral_leaf_shape_hash` for the canonical Python behavioral-leaf fixture.
+ const SHA256: &str = "9efcd8a99c5334a19b52f6a7b990e3b862ad116031a0b47481f8bbb09e54a7de";
+
+ fn tile() -> ReconcileTile {
+ ReconcileTile::new(
+ TeamId(2),
+ CohortId(42),
+ BehavioralShapeHash::parse(SHA256).unwrap(),
+ RunId(Uuid::nil()),
+ )
+ }
+
+ #[test]
+ fn reconcile_wire_contract_is_fixed() {
+ let tile = tile();
+ assert_eq!(
+ serde_json::to_value(&tile).unwrap(),
+ serde_json::json!({
+ "schema_version": 1,
+ "kind": "reconcile",
+ "team_id": 2,
+ "cohort_id": 42,
+ "filters_hash": SHA256,
+ "run_id": "00000000-0000-0000-0000-000000000000",
+ })
+ );
+ assert_eq!(
+ serde_json::to_string(&tile).unwrap(),
+ r#"{"schema_version":1,"kind":"reconcile","team_id":2,"cohort_id":42,"filters_hash":"9efcd8a99c5334a19b52f6a7b990e3b862ad116031a0b47481f8bbb09e54a7de","run_id":"00000000-0000-0000-0000-000000000000"}"#
+ );
+ }
+
+ #[test]
+ fn reconcile_roundtrips_and_rejects_foreign_kind_schema_and_hash() {
+ let tile = tile();
+ let bytes = serde_json::to_vec(&tile).unwrap();
+ assert_eq!(
+ serde_json::from_slice::<ReconcileTile>(&bytes).unwrap(),
+ tile
+ );
+
+ let golden = serde_json::to_value(&tile).unwrap();
+ let mut extended = golden.clone();
+ extended["future_metadata"] = serde_json::json!({ "source": "scheduler" });
+ assert_eq!(
+ serde_json::from_value::<ReconcileTile>(extended).unwrap(),
+ tile
+ );
+
+ for (field, value) in [
+ ("kind", serde_json::json!("behavioral_tile")),
+ ("schema_version", serde_json::json!(2)),
+ ("filters_hash", serde_json::json!("")),
+ ("filters_hash", serde_json::json!("x".repeat(65))),
+ ("filters_hash", serde_json::json!("non-ascii-é")),
+ ] {
+ let mut broken = golden.clone();
+ broken[field] = value;
+ assert!(
+ serde_json::from_value::<ReconcileTile>(broken).is_err(),
+ "accepted a reconcile tile with mutated {field}",
+ );
+ }
+ }
+
+ #[test]
+ fn behavioral_shape_hash_matches_the_persisted_output_bounds() {
+ assert_eq!(BehavioralShapeHash::parse(SHA256).unwrap().as_str(), SHA256,);
+ assert_eq!(BehavioralShapeHash::parse("a").unwrap().as_str(), "a",);
+ assert_eq!(
+ BehavioralShapeHash::parse(""),
+ Err(BehavioralShapeHashError::Empty),
+ );
+ assert_eq!(
+ BehavioralShapeHash::parse(&"x".repeat(65)),
+ Err(BehavioralShapeHashError::TooLong(65)),
+ );
+ assert_eq!(
+ BehavioralShapeHash::parse("é"),
+ Err(BehavioralShapeHashError::NonAscii),
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rs
index f84362182087..f1cae583dfb8 100644
--- a/rust/cohort-stream-processor/src/config.rs
+++ b/rust/cohort-stream-processor/src/config.rs
@@ -250,6 +250,20 @@ pub struct Config {
#[envconfig(from = "COHORT_REGISTER_TRANSFER_ENABLED", default = "false")]
pub cohort_register_transfer_enabled: bool,
+ /// Admit and drain reconcile controls. Default off; enable only once every downstream consumer
+ /// tolerates completion markers. Register transfer is gated separately by
+ /// `COHORT_REGISTER_TRANSFER_ENABLED`.
+ #[envconfig(from = "COHORT_SEED_RECONCILE_ENABLED", default = "false")]
+ pub cohort_seed_reconcile_enabled: bool,
+
+ /// Maximum Stage 2 rows one partition worker evaluates per reconcile tick.
+ #[envconfig(from = "COHORT_SEED_RECONCILE_SCAN_PAGE", default = "256")]
+ pub cohort_seed_reconcile_scan_page: usize,
+
+ /// Cadence for routing one bounded reconcile-drain tick to each active partition worker.
+ #[envconfig(from = "COHORT_SEED_RECONCILE_TICK_INTERVAL_MS", default = "2000")]
+ pub cohort_seed_reconcile_tick_interval_ms: u64,
+
/// Stable per-pod identity for `group.instance.id` + `client.id`, enabling static membership.
/// Read from `POD_NAME`, else `HOSTNAME`. Absent means no static membership.
#[envconfig(from = "POD_NAME")]
@@ -605,6 +619,10 @@ impl Config {
.max(Duration::from_secs(1))
}
+ pub fn reconcile_tick_interval(&self) -> Duration {
+ Duration::from_millis(self.cohort_seed_reconcile_tick_interval_ms)
+ }
+
pub fn checkpoint_interval(&self) -> Duration {
Duration::from_millis(self.checkpoint_interval_ms)
}
@@ -643,11 +661,29 @@ impl Config {
/// Refuse unsafe durability startup combinations. Pure (no I/O), so unit-testable without a broker.
///
/// Guards:
+ /// - Reconcile scan and tick limits must be non-zero; a zero page would falsely certify an
+ /// unscanned snapshot, while Tokio rejects a zero timer interval.
/// - `checkpoint_enabled` requires `durable_restore_enabled`: without it the restored DB is wiped
/// on open, silently discarding the restore.
/// - `durable_restore_enabled` + `cohort_cascade_enabled` requires `durable_restore_single_pod`
/// and a pod identity: `pod_identity()` alone is not a single-pod signal (set on every k8s pod).
pub fn validate_durability_startup(&self) -> anyhow::Result<()> {
+ ensure!(
+ self.cohort_seed_reconcile_scan_page > 0,
+ "COHORT_SEED_RECONCILE_SCAN_PAGE must be greater than zero.",
+ );
+ ensure!(
+ self.cohort_seed_reconcile_tick_interval_ms > 0,
+ "COHORT_SEED_RECONCILE_TICK_INTERVAL_MS must be greater than zero.",
+ );
+
+ if self.cohort_seed_reconcile_enabled && !self.cohort_seed_consumer_enabled {
+ warn!(
+ "COHORT_SEED_RECONCILE_ENABLED without COHORT_SEED_CONSUMER_ENABLED: no reconcile \
+ controls can be consumed; enable the seed consumer or turn reconcile off.",
+ );
+ }
+
ensure!(
!self.checkpoint_enabled || self.durable_restore_enabled,
"CHECKPOINT_ENABLED requires DURABLE_RESTORE_ENABLED: restoring a checkpoint without \
@@ -975,6 +1011,9 @@ mod tests {
cohort_seed_fence_margin_ms: 600_000,
cohort_seed_watermark_idle_probe_interval_ms: 30_000,
cohort_register_transfer_enabled: false,
+ cohort_seed_reconcile_enabled: false,
+ cohort_seed_reconcile_scan_page: 256,
+ cohort_seed_reconcile_tick_interval_ms: 2_000,
}
}
@@ -991,6 +1030,58 @@ mod tests {
);
}
+ #[test]
+ fn reconcile_knobs_default_dark_and_override_from_env() {
+ let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();
+ assert!(!defaults.cohort_seed_reconcile_enabled);
+ assert_eq!(defaults.cohort_seed_reconcile_scan_page, 256);
+ assert_eq!(
+ defaults.reconcile_tick_interval(),
+ Duration::from_millis(2_000)
+ );
+
+ let env: std::collections::HashMap<String, String> = [
+ ("COHORT_SEED_RECONCILE_ENABLED", "true"),
+ ("COHORT_SEED_RECONCILE_SCAN_PAGE", "17"),
+ ("COHORT_SEED_RECONCILE_TICK_INTERVAL_MS", "345"),
+ ]
+ .into_iter()
+ .map(|(key, value)| (key.to_string(), value.to_string()))
+ .collect();
+ let config = Config::init_from_hashmap(&env).unwrap();
+ assert!(config.cohort_seed_reconcile_enabled);
+ assert_eq!(config.cohort_seed_reconcile_scan_page, 17);
+ assert_eq!(config.reconcile_tick_interval(), Duration::from_millis(345));
+ }
+
+ #[test]
+ fn reconcile_startup_validation_rejects_zero_work_limits() {
+ let mut config = test_config();
+ config.cohort_seed_reconcile_scan_page = 0;
+ assert!(config
+ .validate_durability_startup()
+ .unwrap_err()
+ .to_string()
+ .contains("COHORT_SEED_RECONCILE_SCAN_PAGE"),);
+
+ config.cohort_seed_reconcile_scan_page = 1;
+ config.cohort_seed_reconcile_tick_interval_ms = 0;
+ assert!(config
+ .validate_durability_startup()
+ .unwrap_err()
+ .to_string()
+ .contains("COHORT_SEED_RECONCILE_TICK_INTERVAL_MS"),);
+ }
+
+ #[test]
+ fn reconcile_without_the_seed_consumer_warns_but_starts() {
+ let mut config = test_config();
+ config.cohort_seed_reconcile_enabled = true;
+ config.cohort_seed_consumer_enabled = false;
+
+ assert!(config.validate_durability_startup().is_ok());
+ }
+
#[test]
fn sweep_interval_and_safety_margin_map_from_millis() {
let config = test_config();
diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rs
index 70b78295692b..e771e5964e37 100644
--- a/rust/cohort-stream-processor/src/consumers/events.rs
+++ b/rust/cohort-stream-processor/src/consumers/events.rs
@@ -82,12 +82,19 @@ pub struct ConsumedEvent {
pub broker_ts_ms: Option<i64>,
}
+/// A partition entry remains present while its old worker drains. That sentinel serializes worker
+/// replacement with tracker-tenure reset during a rapid revoke/reassign.
+enum WorkerSlot {
+ Running(Stage1Worker),
+ Draining,
+}
+
/// The Kafka-free routing core: dispatches consumed batches to per-partition workers, tracks
/// processed offsets, and owns the partition lifecycle the rebalance handler drives.
pub struct EventDispatcher {
router: Arc<PartitionRouter>,
tracker: Arc<OffsetTracker>,
- workers: Arc<DashMap<i32, Stage1Worker>>,
+ workers: Arc<DashMap<i32, WorkerSlot>>,
/// Partitions currently assigned to this consumer.
owned: Arc<DashSet<i32>>,
handle: StoreHandle,
@@ -237,8 +244,8 @@ impl EventDispatcher {
}
/// Retry-send held sub-batches, raising the ceiling for any that flush. Returns the partitions
- /// still full (retained holdover) to keep paused; a flushed or worker-gone one is absent, so the
- /// caller resumes it.
+ /// still unavailable (full, missing, or closed) to keep paused; only a flushed partition is
+ /// absent, so the caller resumes it.
pub fn redispatch_held(
&self,
held: Vec<(i32, Vec<ShuffleMessage>)>,
@@ -246,6 +253,7 @@ impl EventDispatcher {
// Each partition's Vec stays contiguous, so the regrouped route keeps offset order.
let mut messages: Vec<(i32, ShuffleMessage)> = Vec::new();
for (partition, batch) in held {
+ self.ensure_worker(partition);
for message in batch {
messages.push((partition, message));
}
@@ -282,7 +290,10 @@ impl EventDispatcher {
SendOutcome::Full(returned) => {
full.entry(partition).or_default().extend(returned);
}
- SendOutcome::NoWorker | SendOutcome::ChannelClosed => route_errors += 1,
+ SendOutcome::NoWorker(returned) | SendOutcome::ChannelClosed(returned) => {
+ full.entry(partition).or_default().extend(returned);
+ route_errors += 1;
+ }
}
}
if dispatched > 0 {
@@ -423,7 +434,14 @@ impl EventDispatcher {
.filter_map(|message| ConsumedSeed::from_message(partition, message)),
);
}
- SendOutcome::NoWorker | SendOutcome::ChannelClosed => route_errors += 1,
+ SendOutcome::NoWorker(returned) | SendOutcome::ChannelClosed(returned) => {
+ full.entry(partition).or_default().extend(
+ returned
+ .into_iter()
+ .filter_map(|message| ConsumedSeed::from_message(partition, message)),
+ );
+ route_errors += 1;
+ }
}
}
if route_errors > 0 {
@@ -470,7 +488,14 @@ impl EventDispatcher {
/// partition is unowned. The ownership check and insert are atomic under the DashMap shard guard.
fn ensure_worker(&self, partition: i32) {
match self.workers.entry(partition) {
- Entry::Occupied(_) => {}
+ Entry::Occupied(slot) => {
+ if matches!(slot.get(), WorkerSlot::Draining) {
+ debug!(
+ partition,
+ "worker replacement waits for the revoked worker to finish draining"
+ );
+ }
+ }
Entry::Vacant(slot) => {
// No `.await` in this arm — the DashMap shard guard is held.
if !self.owned.contains(&partition) {
@@ -500,7 +525,7 @@ impl EventDispatcher {
self.durable_restore_enabled(),
self.event_name_gating(),
);
- slot.insert(worker);
+ slot.insert(WorkerSlot::Running(worker));
counter!(COHORT_STREAM_WORKERS_SPAWNED).increment(1);
info!(
partition,
@@ -560,6 +585,11 @@ impl EventDispatcher {
.await;
}
+ /// Route one bounded reconcile-drain tick to each owned partition with a live worker.
+ pub async fn route_reconcile_drain(&self) {
+ self.route_to_owned(|| ShuffleMessage::ReconcileDrain).await;
+ }
+
/// Owned partitions that currently have a live worker channel — the only partitions a maintenance
/// tick can reach. An owned partition that never received an event has no worker, so a tick to it
/// is a guaranteed `no_worker` no-op (no in-memory state to evict, redrive, or GC); skipping it
@@ -616,8 +646,24 @@ impl EventDispatcher {
return;
}
+ let worker = match self.workers.entry(partition) {
+ Entry::Occupied(mut slot) => {
+ if matches!(slot.get(), WorkerSlot::Draining) {
+ debug!(partition, "revoke cleanup is already draining this worker");
+ return;
+ }
+ match slot.insert(WorkerSlot::Draining) {
+ WorkerSlot::Running(worker) => Some(worker),
+ WorkerSlot::Draining => unreachable!("the occupied slot was checked above"),
+ }
+ }
+ Entry::Vacant(slot) => {
+ slot.insert(WorkerSlot::Draining);
+ None
+ }
+ };
self.router.remove_partition(partition);
- if let Some((_, worker)) = self.workers.remove(&partition) {
+ if let Some(worker) = worker {
let started = Instant::now();
if let Err(err) = worker.join().await {
warn!(partition, error = %err, "stage 1 worker panicked during revoke drain");
@@ -626,7 +672,12 @@ impl EventDispatcher {
}
if self.owned.contains(&partition) {
- // re-acquired during the join — skip cleanup
+ // The draining sentinel prevents an in-flight follower batch from spawning a replacement
+ // worker before the old in-memory reconcile queue is gone and its tracker tenure resets.
+ // The rebalance worker then rewinds the follower, so anything dropped against the
+ // sentinel is replayed into the fresh tenure.
+ self.merge.seed_tracker.forget_partition(partition);
+ self.finish_worker_drain(partition);
counter!(REBALANCE_CLEANUP_SKIPPED_TOTAL, "phase" => "post_join").increment(1);
debug!(
partition,
@@ -656,6 +707,7 @@ impl EventDispatcher {
partition,
"revoked partition out of u16 range; skipping state delete"
);
+ self.finish_worker_drain(partition);
return;
};
match self.handle.delete_partition(partition_id).await {
@@ -664,6 +716,12 @@ impl EventDispatcher {
warn!(partition, error = %err, "failed to delete revoked partition state")
}
}
+ self.finish_worker_drain(partition);
+ }
+
+ fn finish_worker_drain(&self, partition: i32) {
+ self.workers
+ .remove_if(&partition, |_, slot| matches!(slot, WorkerSlot::Draining));
}
/// Delete a moving-in partition's stale on-disk slice so the worker cold-rebuilds from the
@@ -886,7 +944,7 @@ impl EventDispatcher {
self.router.clear();
let partitions: Vec<i32> = self.workers.iter().map(|entry| *entry.key()).collect();
for partition in partitions {
- if let Some((_, worker)) = self.workers.remove(&partition) {
+ if let Some((_, WorkerSlot::Running(worker))) = self.workers.remove(&partition) {
if let Err(err) = worker.join().await {
warn!(partition, error = %err, "stage 1 worker panicked during shutdown drain");
}
@@ -1409,10 +1467,14 @@ pub(crate) async fn run_pauser_loop(
mod tests {
use super::*;
use chrono_tz::UTC;
+ use common_kafka::kafka_producer::KafkaProduceError;
use serde_json::json;
use tempfile::TempDir;
use uuid::Uuid;
+ use cohort_core::seed::{BehavioralShapeHash, ReconcileTile, RunId};
+
+ use crate::consumers::seeds::SeedWork;
use crate::filters::{CohortId, FilterCatalog, TeamFiltersBuilder, TeamId};
use crate::merge::transfer::{
MergeStateTransfer, PendingTransfer, PersonMergeEvent, Tombstone, TransferLeaf,
@@ -1421,7 +1483,8 @@ mod tests {
use crate::partitions::offset_tracker::MarkOutcome;
use crate::partitions::partitioner::{partition_of, COHORT_PARTITION_COUNT};
use crate::producer::{
- CaptureSink, CaptureStreamEventSink, CaptureTransferSink, MembershipStatus,
+ CaptureSink, CaptureStreamEventSink, CaptureTransferSink, CohortMembershipChange,
+ MembershipStatus, ReconcileCompleteMarker,
};
use crate::stage1::state::AppliedOffsets;
use crate::stage1::{Stage1State, StatefulRecord};
@@ -1435,6 +1498,43 @@ mod tests {
const BEHAVIORAL_HASH: [u8; 16] = *b"0123456789abcdef";
const BASE_TS: &str = "2026-05-26 12:34:56.789000";
+ struct BlockingMembershipSink {
+ entered: tokio::sync::Notify,
+ release: tokio::sync::Notify,
+ block_first: AtomicBool,
+ }
+
+ impl BlockingMembershipSink {
+ fn new() -> Arc<Self> {
+ Arc::new(Self {
+ entered: tokio::sync::Notify::new(),
+ release: tokio::sync::Notify::new(),
+ block_first: AtomicBool::new(true),
+ })
+ }
+ }
+
+ #[async_trait::async_trait]
+ impl MembershipSink for BlockingMembershipSink {
+ async fn produce(
+ &self,
+ changes: Vec<CohortMembershipChange>,
+ ) -> Vec<Result<(), KafkaProduceError>> {
+ if self.block_first.swap(false, Ordering::SeqCst) {
+ self.entered.notify_one();
+ self.release.notified().await;
+ }
+ changes.into_iter().map(|_| Ok(())).collect()
+ }
+
+ async fn produce_markers(
+ &self,
+ markers: Vec<ReconcileCompleteMarker>,
+ ) -> Vec<Result<(), KafkaProduceError>> {
+ markers.into_iter().map(|_| Ok(())).collect()
+ }
+ }
+
/// Wrap a test store in the `All` operating point so the dispatcher runs on the blocking pool.
fn test_handle(store: &CohortStore) -> StoreHandle {
StoreHandle::new(
@@ -1770,6 +1870,10 @@ mod tests {
let sink = Arc::new(sink);
let transfer_sink = Arc::new(transfer_sink);
let transfer_sink_dyn: Arc<dyn crate::producer::TransferSink> = transfer_sink.clone();
+ let reconcile = crate::workers::ReconcileDeps {
+ enabled: true,
+ ..crate::workers::ReconcileDeps::default()
+ };
let merge = Arc::new(MergeWorkerDeps {
transfer_sink: transfer_sink_dyn,
stream_event_sink: Arc::new(CaptureStreamEventSink::new()),
@@ -1787,6 +1891,7 @@ mod tests {
live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),
// The dispatch tests exercise cross-partition register transfer end to end.
register_transfer_enabled: true,
+ reconcile,
});
let dispatcher = EventDispatcher::new(
PartitionRouter::new(64),
@@ -2470,6 +2575,165 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn post_join_reacquire_starts_a_fresh_seed_tenure_for_reconcile_replay() {
+ let (_dir, store) = temp_store();
+ let sink = BlockingMembershipSink::new();
+ let reconcile = crate::workers::ReconcileDeps {
+ enabled: true,
+ ..crate::workers::ReconcileDeps::default()
+ };
+ let merge = Arc::new(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(crate::producer::CaptureCascadeSink::new()),
+ cascade_tracker: Arc::new(OffsetTracker::new()),
+ cascade: crate::workers::CascadeConfig::default(),
+ partition_count: COHORT_PARTITION_COUNT,
+ seed_tile_sink: Arc::new(crate::producer::CaptureSeedTileSink::new()),
+ seed_tracker: Arc::new(OffsetTracker::new()),
+ live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),
+ register_transfer_enabled: false,
+ reconcile,
+ });
+ let dispatcher = Arc::new(EventDispatcher::new(
+ PartitionRouter::new(64),
+ Arc::new(OffsetTracker::new()),
+ test_handle(&store),
+ behavioral_catalog(),
+ sink.clone(),
+ merge.clone(),
+ ));
+ dispatcher.assign_partition(0);
+
+ let tile = ReconcileTile::new(
+ TeamId(TEAM),
+ CohortId(1),
+ BehavioralShapeHash::parse("0123456789abcdef").unwrap(),
+ RunId(Uuid::from_u128(1)),
+ );
+ let held = dispatcher.dispatch_seeds(vec![ConsumedSeed {
+ work: SeedWork::Reconcile(tile.clone()),
+ partition: 0,
+ offset: 5,
+ }]);
+ assert!(held.is_empty());
+ for _ in 0..10_000 {
+ if merge.reconcile.backlog.len() == 1 {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ assert_eq!(merge.reconcile.backlog.len(), 1, "reconcile was admitted");
+
+ dispatcher.dispatch(vec![consumed(person(1), 0, 6)]).await;
+ sink.entered.notified().await;
+
+ dispatcher.revoke_partition_sync(0);
+ let drain = {
+ let dispatcher = dispatcher.clone();
+ tokio::spawn(async move { dispatcher.revoke_partition_drain(0).await })
+ };
+ for _ in 0..10_000 {
+ if dispatcher
+ .workers
+ .get(&0)
+ .is_some_and(|slot| matches!(slot.value(), WorkerSlot::Draining))
+ {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ assert!(
+ dispatcher
+ .workers
+ .get(&0)
+ .is_some_and(|slot| matches!(slot.value(), WorkerSlot::Draining)),
+ "the old worker was replaced by a draining sentinel before its blocked join",
+ );
+
+ dispatcher.assign_partition(0);
+ let held_events = dispatcher
+ .dispatch_events_nonblocking(vec![consumed(person(2), 0, 7)], &HashSet::new());
+ assert_eq!(
+ held_offsets(
+ held_events
+ .get(&0)
+ .expect("a primary event is held behind the draining worker"),
+ ),
+ vec![7],
+ );
+ let mut held = dispatcher.dispatch_seeds(vec![ConsumedSeed {
+ work: SeedWork::Reconcile(tile.clone()),
+ partition: 0,
+ offset: 5,
+ }]);
+ assert_eq!(
+ held_seed_offsets(held.get(&0).expect("the draining route is held")),
+ vec![5],
+ );
+ assert!(
+ dispatcher
+ .workers
+ .get(&0)
+ .is_some_and(|slot| matches!(slot.value(), WorkerSlot::Draining)),
+ "an in-flight follower batch cannot replace the draining worker",
+ );
+
+ sink.release.notify_one();
+ drain.await.unwrap();
+
+ assert!(dispatcher.owns(0));
+ assert!(merge.reconcile.backlog.is_empty());
+ assert!(dispatcher.workers.is_empty(), "the sentinel was released");
+
+ let still_held = dispatcher.redispatch_held(held_events.into_iter().collect());
+ assert!(
+ still_held.is_empty(),
+ "the primary event routes after the draining sentinel is released",
+ );
+ let held = dispatcher.dispatch_seeds(
+ held.remove(&0)
+ .expect("the held follower batch is retried after the drain"),
+ );
+ assert!(held.is_empty());
+ for _ in 0..10_000 {
+ if merge.reconcile.backlog.len() == 1 {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ assert_eq!(merge.reconcile.backlog.len(), 1, "replay was re-admitted");
+ assert_eq!(
+ merge.seed_tracker.mark_processed(0, 6),
+ MarkOutcome::WithinDispatch,
+ "worker receipt raises the fresh tenure's seed ceiling before admission",
+ );
+ assert_eq!(
+ merge.seed_tracker.committable_offsets().get(&0),
+ Some(&5),
+ "the replayed reconcile owns the fresh tenure's commit floor",
+ );
+ for _ in 0..10_000 {
+ if dispatcher.tracker().committable_offsets().get(&0) == Some(&8) {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ assert_eq!(
+ dispatcher.tracker().committable_offsets().get(&0),
+ Some(&8),
+ "the held primary event is processed after worker replacement",
+ );
+
+ dispatcher.shutdown().await;
+ }
+
#[tokio::test]
async fn revoke_then_shutdown_drain_each_worker_exactly_once() {
let (_dir, store) = temp_store();
@@ -2610,6 +2874,24 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn route_reconcile_drain_delivers_one_tick_to_each_active_worker() {
+ let (_dir, store) = temp_store();
+ let dispatcher = dispatcher_with(&store, behavioral_catalog());
+
+ dispatcher.assign_partition(0);
+ dispatcher.assign_partition(1);
+ let mut rx0 = dispatcher.router.add_partition(0).unwrap();
+ let mut rx1 = dispatcher.router.add_partition(1).unwrap();
+
+ dispatcher.route_reconcile_drain().await;
+
+ for receiver in [&mut rx0, &mut rx1] {
+ let batch = receiver.recv().await.expect("a reconcile tick was routed");
+ assert!(matches!(batch.as_slice(), [ShuffleMessage::ReconcileDrain]));
+ }
+ }
+
#[tokio::test]
async fn route_sweep_is_benign_for_workerless_or_no_owned_partitions() {
let (_dir, store) = temp_store();
diff --git a/rust/cohort-stream-processor/src/consumers/seeds.rs b/rust/cohort-stream-processor/src/consumers/seeds.rs
index 36e79d15d25f..22a89cca4121 100644
--- a/rust/cohort-stream-processor/src/consumers/seeds.rs
+++ b/rust/cohort-stream-processor/src/consumers/seeds.rs
@@ -11,7 +11,7 @@ use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::Duration;
-use cohort_core::seed::{decode_seed, DecodedSeed, SChunkMs, SeedTile};
+use cohort_core::seed::{decode_seed, DecodedSeed, ReconcileTile, SChunkMs, SeedTile};
use lifecycle::Handle;
use metrics::{counter, gauge, histogram};
use rdkafka::consumer::{CommitMode, Consumer, StreamConsumer};
@@ -41,7 +41,7 @@ const PROBE_FETCH_TIMEOUT: Duration = Duration::from_secs(5);
/// Why a consumed seed payload is skipped rather than applied.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SeedSkipReason {
- /// A kind this consumer does not handle (e.g. a `reconcile` control tile).
+ /// A kind the current worker path does not handle.
UnknownKind,
/// A newer schema version. The skip commits and never replays, so this consumer must be
/// upgraded before any seeder emits a new schema.
@@ -64,6 +64,7 @@ impl SeedSkipReason {
#[derive(Debug)]
pub enum SeedWork {
Tile(SeedTile),
+ Reconcile(ReconcileTile),
Skip(SeedSkipReason),
}
@@ -95,11 +96,11 @@ impl ConsumedSeed {
}
}
- /// The fence input; `None` for skips.
+ /// The fence input; control messages and skips are fence-open.
fn s_chunk_ms(&self) -> Option<SChunkMs> {
match &self.work {
SeedWork::Tile(tile) => Some(tile.s_chunk_ms()),
- SeedWork::Skip(_) => None,
+ SeedWork::Reconcile(_) | SeedWork::Skip(_) => None,
}
}
}
@@ -423,8 +424,7 @@ impl SeedFollowerConsumer {
}
}
-/// Decode one payload; every non-tile outcome is a channel-riding skip so its offset marks in
-/// order.
+/// Decode one payload into channel-riding work so every outcome retains its in-order offset.
fn decode_payload(payload: Option<&[u8]>, partition: i32, offset: i64) -> SeedWork {
let Some(payload) = payload else {
debug!(
@@ -435,6 +435,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::Reconcile(tile)) => SeedWork::Reconcile(tile),
Ok(DecodedSeed::UnknownKind { kind, .. }) => {
debug!(partition, offset, kind, "skipping seed of unknown kind");
SeedWork::Skip(SeedSkipReason::UnknownKind)
@@ -603,10 +604,12 @@ fn frontier_is_caught_up(frontier: Option<i64>, low: i64, high: i64) -> bool {
mod tests {
use std::num::NonZeroU32;
- use cohort_core::seed::{ClaimEpoch, ConditionHash, RunId, SChunkMs};
+ use cohort_core::seed::{
+ BehavioralShapeHash, ClaimEpoch, ConditionHash, ReconcileTile, RunId, SChunkMs,
+ };
use uuid::Uuid;
- use crate::filters::TeamId;
+ use crate::filters::{CohortId, TeamId};
use crate::partitions::watermarks::LiveWatermarks;
use super::*;
@@ -781,12 +784,19 @@ mod tests {
SeedWork::Tile(decoded) if decoded == tile,
));
- let mut reconcile = serde_json::to_value(&tile).unwrap();
- reconcile["kind"] = serde_json::json!("reconcile");
+ let reconcile = ReconcileTile::new(
+ TeamId(2),
+ CohortId(42),
+ BehavioralShapeHash::parse(
+ "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
+ )
+ .unwrap(),
+ RunId(Uuid::nil()),
+ );
let bytes = serde_json::to_vec(&reconcile).unwrap();
assert!(matches!(
decode_payload(Some(&bytes), 0, 0),
- SeedWork::Skip(SeedSkipReason::UnknownKind),
+ SeedWork::Reconcile(decoded) if decoded == reconcile,
));
let mut newer = serde_json::to_value(&tile).unwrap();
@@ -817,10 +827,58 @@ mod tests {
assert_eq!(back.offset, 42);
assert!(matches!(back.work, SeedWork::Tile(tile) if tile.s_chunk_ms() == SChunkMs(123)));
+ let reconcile = ReconcileTile::new(
+ TeamId(2),
+ CohortId(42),
+ BehavioralShapeHash::parse("0123456789abcdef").unwrap(),
+ RunId(Uuid::nil()),
+ );
+ let consumed = ConsumedSeed {
+ work: SeedWork::Reconcile(reconcile.clone()),
+ partition: 9,
+ offset: 43,
+ };
+ let back = ConsumedSeed::from_message(9, consumed.into_message()).unwrap();
+ assert_eq!(back.offset, 43);
+ assert!(matches!(back.work, SeedWork::Reconcile(tile) if tile == reconcile));
+
let not_seed = ShuffleMessage::RedrivePendingTransfers;
assert!(ConsumedSeed::from_message(9, not_seed).is_none());
}
+ #[test]
+ fn reconcile_is_fence_open_but_never_leapfrogs_a_closed_tile() {
+ let reconcile = ReconcileTile::new(
+ TeamId(2),
+ CohortId(42),
+ BehavioralShapeHash::parse("0123456789abcdef").unwrap(),
+ RunId(Uuid::nil()),
+ );
+ let reconcile_seed = |offset| ConsumedSeed {
+ work: SeedWork::Reconcile(reconcile.clone()),
+ partition: 3,
+ offset,
+ };
+
+ let open_prefix = split_at_fence(
+ vec![reconcile_seed(1), seed(3, 2, 0)],
+ &HashSet::new(),
+ MARGIN_MS,
+ |_| None,
+ );
+ assert_eq!(offsets(&open_prefix.admitted), vec![1]);
+ assert_eq!(offsets(&open_prefix.held[&3]), vec![2]);
+
+ let closed_prefix = split_at_fence(
+ vec![seed(3, 3, 0), reconcile_seed(4)],
+ &HashSet::new(),
+ MARGIN_MS,
+ |_| None,
+ );
+ assert!(closed_prefix.admitted.is_empty());
+ assert_eq!(offsets(&closed_prefix.held[&3]), vec![3, 4]);
+ }
+
/// 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/filters/manager.rs b/rust/cohort-stream-processor/src/filters/manager.rs
index 5216ba17457b..d8aa40ab1ef5 100644
--- a/rust/cohort-stream-processor/src/filters/manager.rs
+++ b/rust/cohort-stream-processor/src/filters/manager.rs
@@ -219,6 +219,7 @@ mod tests {
id,
team_id,
filters: serde_json::Value::Null,
+ behavioral_filters_shape_hash: None,
timezone: "UTC".to_string(),
}
}
diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rs
index 09342868e6b0..66467531192d 100644
--- a/rust/cohort-stream-processor/src/main.rs
+++ b/rust/cohort-stream-processor/src/main.rs
@@ -40,8 +40,10 @@ use cohort_stream_processor::store::durability::{
S3Uploader, TrackedTopic, CHECKPOINT_LOOP_NAME,
};
use cohort_stream_processor::store::{CohortStore, StoreHandle};
-use cohort_stream_processor::sweep::{run_sweep_loop, run_sweep_loop_delayed, DispatchSweeper};
-use cohort_stream_processor::workers::MergeWorkerDeps;
+use cohort_stream_processor::sweep::{
+ run_sweep_loop, run_sweep_loop_delayed, DispatchSweeper, ReconcileDrainSweeper,
+};
+use cohort_stream_processor::workers::{MergeWorkerDeps, ReconcileBacklog, ReconcileDeps};
common_alloc::used!();
@@ -216,6 +218,7 @@ async fn async_main(config: Config) -> Result<()> {
} else {
Arc::new(NoopSeedTileSink)
};
+ let reconcile_backlog = Arc::new(ReconcileBacklog::default());
let merge_deps = Arc::new(MergeWorkerDeps {
transfer_sink,
stream_event_sink,
@@ -233,6 +236,11 @@ async fn async_main(config: Config) -> Result<()> {
// Unconditional (cheap): the event path observes regardless of the seed gate.
live_watermarks: Arc::new(LiveWatermarks::new()),
register_transfer_enabled: config.cohort_register_transfer_enabled,
+ reconcile: ReconcileDeps {
+ enabled: config.cohort_seed_reconcile_enabled,
+ scan_page: config.cohort_seed_reconcile_scan_page,
+ backlog: reconcile_backlog.clone(),
+ },
});
// Cheap `Arc` clones taken before the originals move into the dispatcher: the checkpoint sweeper
@@ -481,6 +489,15 @@ async fn async_main(config: Config) -> Result<()> {
consumer_handle.shutdown_token(),
));
+ if config.cohort_seed_reconcile_enabled {
+ tokio::spawn(run_sweep_loop(
+ ReconcileDrainSweeper::new(dispatcher.clone(), reconcile_backlog),
+ config.reconcile_tick_interval(),
+ "reconcile",
+ consumer_handle.shutdown_token(),
+ ));
+ }
+
// Publish store cache/size metrics via the sweep machinery, and Tokio runtime metrics via a
// separate monitor.
tokio::spawn(run_sweep_loop(
@@ -773,6 +790,9 @@ fn log_startup(config: &Config) {
seed_topic = %config.cohort_stream_seed_events_topic,
seed_consumer_group = %config.kafka_seed_consumer_group,
seed_fence_margin_ms = config.cohort_seed_fence_margin_ms,
+ cohort_seed_reconcile_enabled = config.cohort_seed_reconcile_enabled,
+ cohort_seed_reconcile_scan_page = config.cohort_seed_reconcile_scan_page,
+ cohort_seed_reconcile_tick_interval_ms = config.cohort_seed_reconcile_tick_interval_ms,
"starting cohort-stream-processor",
);
}
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
index 6d70a74e664f..073592cc078c 100644
--- a/rust/cohort-stream-processor/src/observability/metrics.rs
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -5,8 +5,8 @@ use metrics_exporter_prometheus::{PrometheusBuilder, PrometheusHandle};
// The `cohort-core`-owned metric names this binary emits: its metric-surface manifest.
pub use cohort_core::metrics::{
COHORT_ELIGIBILITY_TOTAL, COHORT_IN_CYCLE_TOTAL, FILTER_CATALOG_COHORT_PARSE_ERRORS,
- FILTER_CATALOG_SKIPPED_LEAVES, FILTER_CATALOG_TZ_FALLBACK, STAGE1_GLOBALS_PARSE_ERROR,
- STAGE1_HOGVM_ERROR, STAGE1_HOGVM_UNKNOWN_FUNCTION,
+ FILTER_CATALOG_INVALID_SHAPE_HASH, FILTER_CATALOG_SKIPPED_LEAVES, FILTER_CATALOG_TZ_FALLBACK,
+ STAGE1_GLOBALS_PARSE_ERROR, STAGE1_HOGVM_ERROR, STAGE1_HOGVM_UNKNOWN_FUNCTION,
};
/// Teams with ≥1 realtime cohort in the current catalog snapshot (gauge).
@@ -426,6 +426,8 @@ pub const STAGE2_ORPHAN_GC_SKIPPED_TOTAL: &str = "stage2_orphan_gc_skipped_total
/// `cf_stage2` keys the orphan GC could not classify and left in place (counter): a key the decoder
/// rejected, or an id that overflows `i32`.
pub const STAGE2_ORPHAN_GC_UNDECODABLE_KEYS_TOTAL: &str = "stage2_orphan_gc_undecodable_keys_total";
+/// `cf_stage2` keys a cohort-prefix scan could not decode and skipped (counter).
+pub const STAGE2_SCAN_UNDECODABLE_KEYS_TOTAL: &str = "stage2_scan_undecodable_keys_total";
/// Keys the sweep popped but did not evict, labelled by `reason` (counter). Conservation:
/// `popped == evicted + dropped`.
@@ -465,6 +467,26 @@ pub const SEED_FENCED_PARTITIONS: &str = "cohort_seed_fenced_partitions";
pub const SEED_FENCE_DEFICIT_MS: &str = "cohort_seed_fence_deficit_ms";
/// Age of each owned partition's live watermark, labelled by `partition` (gauge, ms).
pub const LIVE_WATERMARK_AGE_MS: &str = "cohort_live_watermark_age_ms";
+/// Reconcile jobs admitted to partition-local queues (counter).
+pub const RECONCILE_JOBS_ENQUEUED_TOTAL: &str = "cohort_reconcile_jobs_enqueued_total";
+/// Reconcile jobs that emitted their completion marker and released their seed floor (counter).
+pub const RECONCILE_JOBS_COMPLETED_TOTAL: &str = "cohort_reconcile_jobs_completed_total";
+/// Queued jobs replaced by a higher Kafka offset for the same team and cohort (counter).
+pub const RECONCILE_JOBS_SUPERSEDED_TOTAL: &str = "cohort_reconcile_jobs_superseded_total";
+/// Reconcile jobs invalidated by a drain-time guard, labelled by bounded `reason` (counter).
+pub const RECONCILE_JOBS_DISCARDED_TOTAL: &str = "cohort_reconcile_jobs_discarded_total";
+/// Stage 2 rows read by reconcile and durably settled, counted once per committed page (counter). A
+/// page that fails its produce or commit and retries is not double-counted.
+pub const RECONCILE_ROWS_SCANNED_TOTAL: &str = "cohort_reconcile_rows_scanned_total";
+/// Snapshot membership rows acknowledged by Kafka and durably settled, labelled by `status`, counted
+/// once per committed page (counter).
+pub const RECONCILE_ROWS_EMITTED_TOTAL: &str = "cohort_reconcile_rows_emitted_total";
+/// Stale Stage 2 bits durably fixed, labelled by `direction` (counter).
+pub const RECONCILE_BITS_FIXED_TOTAL: &str = "cohort_reconcile_bits_fixed_total";
+/// Reconcile completion markers acknowledged by Kafka (counter).
+pub const RECONCILE_MARKERS_EMITTED_TOTAL: &str = "cohort_reconcile_markers_emitted_total";
+/// Partition-local reconcile queue depth, labelled by `partition` (gauge).
+pub const RECONCILE_QUEUE_DEPTH: &str = "cohort_reconcile_queue_depth";
/// Install the global Prometheus recorder. Call once at startup.
///
@@ -668,6 +690,10 @@ mod tests {
STAGE2_ORPHAN_GC_UNDECODABLE_KEYS_TOTAL,
"stage2_orphan_gc_undecodable_keys_total",
);
+ assert_eq!(
+ STAGE2_SCAN_UNDECODABLE_KEYS_TOTAL,
+ "stage2_scan_undecodable_keys_total",
+ );
}
#[test]
@@ -708,9 +734,54 @@ mod tests {
assert_eq!(SEED_HELD_OFFSET_GAUGE, "seed_held_offset");
assert_eq!(SEED_FENCED_PARTITIONS, "cohort_seed_fenced_partitions");
assert_eq!(SEED_FENCE_DEFICIT_MS, "cohort_seed_fence_deficit_ms");
+ assert_eq!(
+ RECONCILE_JOBS_ENQUEUED_TOTAL,
+ "cohort_reconcile_jobs_enqueued_total"
+ );
+ assert_eq!(
+ RECONCILE_JOBS_SUPERSEDED_TOTAL,
+ "cohort_reconcile_jobs_superseded_total"
+ );
assert_eq!(LIVE_WATERMARK_AGE_MS, "cohort_live_watermark_age_ms");
}
+ #[test]
+ fn reconcile_metric_names_are_stable() {
+ assert_eq!(
+ RECONCILE_JOBS_ENQUEUED_TOTAL,
+ "cohort_reconcile_jobs_enqueued_total",
+ );
+ assert_eq!(
+ RECONCILE_JOBS_COMPLETED_TOTAL,
+ "cohort_reconcile_jobs_completed_total",
+ );
+ assert_eq!(
+ RECONCILE_JOBS_SUPERSEDED_TOTAL,
+ "cohort_reconcile_jobs_superseded_total",
+ );
+ assert_eq!(
+ RECONCILE_JOBS_DISCARDED_TOTAL,
+ "cohort_reconcile_jobs_discarded_total",
+ );
+ assert_eq!(
+ RECONCILE_ROWS_SCANNED_TOTAL,
+ "cohort_reconcile_rows_scanned_total",
+ );
+ assert_eq!(
+ RECONCILE_ROWS_EMITTED_TOTAL,
+ "cohort_reconcile_rows_emitted_total",
+ );
+ assert_eq!(
+ RECONCILE_BITS_FIXED_TOTAL,
+ "cohort_reconcile_bits_fixed_total",
+ );
+ assert_eq!(
+ RECONCILE_MARKERS_EMITTED_TOTAL,
+ "cohort_reconcile_markers_emitted_total",
+ );
+ assert_eq!(RECONCILE_QUEUE_DEPTH, "cohort_reconcile_queue_depth");
+ }
+
#[test]
fn schema_guard_and_drain_scan_metric_names_are_stable() {
assert_eq!(
@@ -719,4 +790,12 @@ mod tests {
);
assert_eq!(MERGE_DRAIN_LEAVES_SCANNED, "merge_drain_leaves_scanned");
}
+
+ #[test]
+ fn catalog_metric_name_is_stable() {
+ assert_eq!(
+ FILTER_CATALOG_INVALID_SHAPE_HASH,
+ "filter_catalog_invalid_shape_hash_total",
+ );
+ }
}
diff --git a/rust/cohort-stream-processor/src/partitions/mod.rs b/rust/cohort-stream-processor/src/partitions/mod.rs
index 02c723d2a216..ca57b5eb908d 100644
--- a/rust/cohort-stream-processor/src/partitions/mod.rs
+++ b/rust/cohort-stream-processor/src/partitions/mod.rs
@@ -20,7 +20,7 @@ pub use cohort_core::partitioner;
pub use backpressure::{Backpressure, PartitionHoldover};
pub use follower::{Follower, FollowerSet, PartitionMirror};
pub use intake::{Admission, MeteredReceiver, PartitionIntake};
-pub use offset_tracker::{MarkOutcome, OffsetTracker};
+pub use offset_tracker::{DeferredOffset, MarkOutcome, OffsetTracker};
pub use partitioner::{
merge_partition_key, murmur2, partition_for, partition_of, COHORT_PARTITION_COUNT,
};
diff --git a/rust/cohort-stream-processor/src/partitions/offset_tracker.rs b/rust/cohort-stream-processor/src/partitions/offset_tracker.rs
index 9da3f6b76d55..2027daf56d3e 100644
--- a/rust/cohort-stream-processor/src/partitions/offset_tracker.rs
+++ b/rust/cohort-stream-processor/src/partitions/offset_tracker.rs
@@ -6,13 +6,17 @@
//! Per-key replay dedup is a separate concern, owned by
//! [`AppliedOffsets`](crate::stage1::state::AppliedOffsets) on each `cf_behavioral` record.
-use std::collections::HashMap;
+use std::collections::{BTreeSet, HashMap};
+use std::sync::Arc;
use dashmap::DashMap;
/// Per-partition consume/commit progress.
-#[derive(Debug, Default, Clone, Copy)]
+#[derive(Debug, Default)]
struct PartitionProgress {
+ /// Identity for one partition tenure. A deferred token from a forgotten tenure must not release
+ /// an equal offset deferred by a later owner.
+ tenure: Arc<()>,
/// Next offset to consume (highest processed `+ 1`), the value committed to Kafka. Monotonic.
/// `0` is the "never processed" sentinel; a real mark is always `≥ 1`, so
/// [`committable_offsets`](OffsetTracker::committable_offsets) treats `0` as nothing to commit.
@@ -35,11 +39,59 @@ struct PartitionProgress {
/// persistent store error a *visible* commit-stall (lag grows; emit the `held_offset` gauge and
/// alert) rather than a silent state loss — the intended fail-stop for a correctness-critical pipeline.
held_offset: Option<i64>,
+ /// Releasable commit floors owned by in-flight work that outlives its consumed message. Unlike
+ /// [`held_offset`](Self::held_offset), each floor is removed explicitly when that work finishes.
+ deferred: BTreeSet<i64>,
/// Last offset Kafka acked as committed. The gap to `processed_offset` is the window Kafka
/// replays after a crash.
committed_offset: i64,
}
+impl PartitionProgress {
+ fn mark_processed(&mut self, next_offset: i64) -> MarkOutcome {
+ let capped = next_offset.min(self.dispatched_offset);
+ self.processed_offset = self.processed_offset.max(capped);
+ if capped < next_offset {
+ MarkOutcome::CappedAheadOfDispatch
+ } else {
+ MarkOutcome::WithinDispatch
+ }
+ }
+
+ fn committable_offset(&self) -> Option<i64> {
+ let committable = [
+ Some(self.processed_offset),
+ self.held_offset,
+ self.deferred.first().copied(),
+ ]
+ .into_iter()
+ .flatten()
+ .min()
+ .expect("processed offset always supplies a commit candidate");
+
+ (self.processed_offset > 0 && committable > 0).then_some(committable)
+ }
+}
+
+/// Ownership token for a releasable commit floor created by [`OffsetTracker::defer`].
+///
+/// The token is deliberately non-`Clone`: one in-flight operation owns one completion. Dropping it
+/// leaves the floor pinned until the partition is forgotten, so a lost job fails closed and Kafka
+/// replays the message on the next tenure.
+#[derive(Debug)]
+#[must_use = "a deferred offset must be completed after its durable work finishes"]
+pub struct DeferredOffset {
+ partition: i32,
+ offset: i64,
+ tenure: Arc<()>,
+}
+
+impl DeferredOffset {
+ pub(crate) fn offset(&self) -> i64 {
+ self.offset
+ }
+}
+
/// What [`OffsetTracker::mark_processed`] did with a mark — returned so the worker can emit a metric
/// without the tracker importing `metrics`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -82,13 +134,72 @@ impl OffsetTracker {
#[must_use = "a CappedAheadOfDispatch outcome is an F1 invariant violation the worker must surface"]
pub fn mark_processed(&self, partition: i32, next_offset: i64) -> MarkOutcome {
let mut progress = self.partitions.entry(partition).or_default();
- let capped = next_offset.min(progress.dispatched_offset);
- progress.processed_offset = progress.processed_offset.max(capped);
- if capped < next_offset {
- MarkOutcome::CappedAheadOfDispatch
- } else {
- MarkOutcome::WithinDispatch
+ progress.mark_processed(next_offset)
+ }
+
+ /// Pin this partition's committable offset at the consumed message's own `offset` until the
+ /// returned token is passed to [`complete_deferred`](Self::complete_deferred).
+ ///
+ /// This is for durable work that continues after the message handler returns. Later processed
+ /// marks may advance normally, but Kafka cannot commit past the earliest deferred offset. The
+ /// serial partition worker must defer each consumed offset at most once per tenure.
+ pub fn defer(&self, partition: i32, offset: i64) -> DeferredOffset {
+ let mut progress = self.partitions.entry(partition).or_default();
+ assert!(
+ progress.deferred.insert(offset),
+ "partition {partition} offset {offset} was deferred twice in one tenure",
+ );
+ DeferredOffset {
+ partition,
+ offset,
+ tenure: Arc::clone(&progress.tenure),
+ }
+ }
+
+ /// Release a deferred floor and mark its consumed message processed (`offset + 1`).
+ ///
+ /// Returns `None` when the partition was forgotten or the token no longer belongs to its
+ /// current progress. This makes late completion after a rebalance harmless and avoids
+ /// recreating tracking state for a revoked partition.
+ pub fn complete_deferred(&self, deferred: DeferredOffset) -> Option<MarkOutcome> {
+ let mut progress = self.partitions.get_mut(&deferred.partition)?;
+ if !Arc::ptr_eq(&progress.tenure, &deferred.tenure)
+ || !progress.deferred.remove(&deferred.offset)
+ {
+ return None;
+ }
+ Some(progress.mark_processed(deferred.offset + 1))
+ }
+
+ /// Atomically replace one deferred floor with another and mark the superseded message processed.
+ ///
+ /// Keeping both mutations under the partition lock matters when the replacement reuses an
+ /// offset after a follower rewind: a concurrent commit snapshot must never observe the old floor
+ /// removed before the replacement is installed. Returns `None` when the token belongs to a
+ /// forgotten tenure or no longer owns its floor.
+ pub fn replace_deferred(
+ &self,
+ deferred: DeferredOffset,
+ replacement_offset: i64,
+ ) -> Option<(DeferredOffset, MarkOutcome)> {
+ let mut progress = self.partitions.get_mut(&deferred.partition)?;
+ if !Arc::ptr_eq(&progress.tenure, &deferred.tenure)
+ || !progress.deferred.remove(&deferred.offset)
+ {
+ return None;
}
+ assert!(
+ progress.deferred.insert(replacement_offset),
+ "partition {} offset {replacement_offset} was deferred twice in one tenure",
+ deferred.partition,
+ );
+ let outcome = progress.mark_processed(deferred.offset + 1);
+ let replacement = DeferredOffset {
+ partition: deferred.partition,
+ offset: replacement_offset,
+ tenure: Arc::clone(&progress.tenure),
+ };
+ Some((replacement, outcome))
}
/// Pin the partition's commit floor at `offset` (the failed message's *own* offset `K`, **not**
@@ -120,27 +231,24 @@ impl OffsetTracker {
}
/// Snapshot of `partition → next-offset-to-consume` for every partition with a *processed*
- /// offset, **capped at any [`hold`](Self::hold) floor**. Partitions tracked only because they were
- /// dispatched carry the `processed_offset == 0` sentinel and are excluded — nothing safe to
- /// commit, so Kafka replays them. A real mark is always `≥ 1`, so the filter never drops a
- /// committable offset.
+ /// offset, capped at the earliest sticky [`hold`](Self::hold) or releasable
+ /// [`defer`](Self::defer) floor. Partitions tracked only because they were dispatched or deferred
+ /// carry the `processed_offset == 0` sentinel and are excluded — nothing safe to commit, so
+ /// Kafka replays them. A real mark is always `≥ 1`, so the filter never drops a committable
+ /// offset.
///
- /// The hold cap is applied to the *value*, not the filter: a hold pinned at the message's own
- /// offset `K` makes the committable value `min(processed, K)` so a later success cannot leapfrog
- /// the failed message. A hold at `0` (or a hold while `processed == 0`) yields a value of `0`,
- /// which the `> 0` filter then excludes — Kafka replays the partition from the start of its
- /// uncommitted range, redelivering the held message rather than skipping it.
+ /// Floors cap the *value*, not the filter: a floor pinned at the message's own offset `K` makes
+ /// the committable value `min(processed, K)` so a later success cannot leapfrog the unfinished
+ /// message. A floor at `0` (or any floor while `processed == 0`) yields no committable value, so
+ /// Kafka replays from the start of the uncommitted range.
pub fn committable_offsets(&self) -> HashMap<i32, i64> {
self.partitions
.iter()
- .filter(|entry| entry.value().processed_offset > 0)
.filter_map(|entry| {
- let progress = entry.value();
- let committable = match progress.held_offset {
- Some(held) => progress.processed_offset.min(held),
- None => progress.processed_offset,
- };
- (committable > 0).then_some((*entry.key(), committable))
+ entry
+ .value()
+ .committable_offset()
+ .map(|offset| (*entry.key(), offset))
})
.collect()
}
@@ -150,8 +258,9 @@ impl OffsetTracker {
}
/// Drop all tracking for a revoked partition. Its offset should already be committed. Removing the
- /// whole entry also clears any [`hold`](Self::hold), so the next tenure starts unheld and replays
- /// from the committed offset — the only way a sticky hold is released.
+ /// whole entry also clears any [`hold`](Self::hold) and [`defer`](Self::defer) floors, so the next
+ /// tenure starts unheld and replays from the committed offset — the only way a sticky hold is
+ /// released.
pub fn forget_partition(&self, partition: i32) {
self.partitions.remove(&partition);
}
@@ -351,4 +460,184 @@ mod tests {
assert_eq!(tracker.committable_offsets().get(&4), None);
assert_eq!(tracker.partition_count(), 1);
}
+
+ #[test]
+ fn later_processed_marks_cannot_leapfrog_a_deferred_offset() {
+ let tracker = OffsetTracker::new();
+ tracker.mark_dispatched(4, 100);
+ let deferred = tracker.defer(4, 41);
+
+ assert_eq!(tracker.mark_processed(4, 80), MarkOutcome::WithinDispatch);
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&41));
+
+ assert_eq!(
+ tracker.complete_deferred(deferred),
+ Some(MarkOutcome::WithinDispatch),
+ );
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&80));
+ }
+
+ #[test]
+ fn completing_a_deferred_offset_zero_marks_next_offset_one() {
+ let tracker = OffsetTracker::new();
+ tracker.mark_dispatched(4, 1);
+ let deferred = tracker.defer(4, 0);
+
+ assert_eq!(tracker.committable_offsets().get(&4), None);
+ assert_eq!(
+ tracker.complete_deferred(deferred),
+ Some(MarkOutcome::WithinDispatch),
+ );
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&1));
+ }
+
+ #[test]
+ fn multiple_deferred_offsets_reveal_the_next_lowest_floor() {
+ let tracker = OffsetTracker::new();
+ tracker.mark_dispatched(4, 100);
+ let first = tracker.defer(4, 20);
+ let second = tracker.defer(4, 40);
+ let _ = tracker.mark_processed(4, 80);
+
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&20));
+ assert_eq!(
+ tracker.complete_deferred(first),
+ Some(MarkOutcome::WithinDispatch),
+ );
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&40));
+ assert_eq!(
+ tracker.complete_deferred(second),
+ Some(MarkOutcome::WithinDispatch),
+ );
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&80));
+
+ let tracker = OffsetTracker::new();
+ tracker.mark_dispatched(4, 100);
+ let first = tracker.defer(4, 20);
+ let second = tracker.defer(4, 40);
+ let _ = tracker.mark_processed(4, 80);
+
+ assert_eq!(
+ tracker.complete_deferred(second),
+ Some(MarkOutcome::WithinDispatch),
+ );
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&20));
+ assert_eq!(
+ tracker.complete_deferred(first),
+ Some(MarkOutcome::WithinDispatch),
+ );
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&80));
+ }
+
+ #[test]
+ fn replacing_a_deferred_offset_never_exposes_an_unpinned_commit() {
+ let tracker = OffsetTracker::new();
+ tracker.mark_dispatched(4, 100);
+ let original = tracker.defer(4, 20);
+ let _ = tracker.mark_processed(4, 80);
+
+ let (replacement, outcome) = tracker
+ .replace_deferred(original, 20)
+ .expect("the current tenure owns the original floor");
+
+ assert_eq!(outcome, MarkOutcome::WithinDispatch);
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&20));
+ assert_eq!(
+ tracker.complete_deferred(replacement),
+ Some(MarkOutcome::WithinDispatch),
+ );
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&80));
+ }
+
+ #[test]
+ fn replacing_a_deferred_offset_moves_the_floor_atomically() {
+ let tracker = OffsetTracker::new();
+ tracker.mark_dispatched(4, 100);
+ let original = tracker.defer(4, 40);
+ let _ = tracker.mark_processed(4, 80);
+
+ let (replacement, _) = tracker
+ .replace_deferred(original, 20)
+ .expect("the current tenure owns the original floor");
+
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&20));
+ assert_eq!(
+ tracker.complete_deferred(replacement),
+ Some(MarkOutcome::WithinDispatch),
+ );
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&80));
+ }
+
+ #[test]
+ fn deferred_and_sticky_floors_compose_by_minimum() {
+ for (partition, held, deferred_offset, expected_before, expected_after) in
+ [(1, 30, 40, 30, 30), (2, 50, 40, 40, 50)]
+ {
+ let tracker = OffsetTracker::new();
+ tracker.mark_dispatched(partition, 100);
+ tracker.hold(partition, held);
+ let deferred = tracker.defer(partition, deferred_offset);
+ let _ = tracker.mark_processed(partition, 80);
+
+ assert_eq!(
+ tracker.committable_offsets().get(&partition),
+ Some(&expected_before),
+ );
+ assert_eq!(
+ tracker.complete_deferred(deferred),
+ Some(MarkOutcome::WithinDispatch),
+ );
+ assert_eq!(
+ tracker.committable_offsets().get(&partition),
+ Some(&expected_after),
+ );
+ }
+ }
+
+ #[test]
+ fn forgetting_a_partition_invalidates_its_deferred_tokens() {
+ let tracker = OffsetTracker::new();
+ tracker.mark_dispatched(4, 100);
+ let stale = tracker.defer(4, 40);
+ let _ = tracker.mark_processed(4, 80);
+ tracker.forget_partition(4);
+
+ // Recreate the same offset in a new tenure to pin the ABA case: the stale token cannot
+ // release work now owned by the new partition worker.
+ tracker.mark_dispatched(4, 100);
+ let current = tracker.defer(4, 40);
+ let _ = tracker.mark_processed(4, 80);
+ assert_eq!(tracker.complete_deferred(stale), None);
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&40));
+
+ assert_eq!(
+ tracker.complete_deferred(current),
+ Some(MarkOutcome::WithinDispatch),
+ );
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&80));
+ }
+
+ #[test]
+ fn dropping_a_deferred_token_pins_until_the_partition_is_forgotten() {
+ let tracker = OffsetTracker::new();
+ tracker.mark_dispatched(4, 100);
+ let deferred = tracker.defer(4, 40);
+ let _ = tracker.mark_processed(4, 80);
+
+ drop(deferred);
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&40));
+
+ tracker.forget_partition(4);
+ tracker.mark_dispatched(4, 100);
+ let _ = tracker.mark_processed(4, 80);
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&80));
+ }
+
+ #[test]
+ #[should_panic(expected = "offset 40 was deferred twice in one tenure")]
+ fn deferring_the_same_offset_twice_fails_closed() {
+ let tracker = OffsetTracker::new();
+ let _first = tracker.defer(4, 40);
+ let _second = tracker.defer(4, 40);
+ }
}
diff --git a/rust/cohort-stream-processor/src/partitions/router.rs b/rust/cohort-stream-processor/src/partitions/router.rs
index e05f6fa87574..a52317c6a949 100644
--- a/rust/cohort-stream-processor/src/partitions/router.rs
+++ b/rust/cohort-stream-processor/src/partitions/router.rs
@@ -53,10 +53,12 @@ pub enum SendOutcome {
},
/// Channel full: carries the un-sent sub-batch to hold, pause, and redispatch. No drop recorded.
Full(Vec<ShuffleMessage>),
- /// No worker registered (never assigned, or revoked): dropped and recorded; Kafka replays.
- NoWorker,
- /// Worker channel closed (worker exited): dropped and recorded; Kafka replays.
- ChannelClosed,
+ /// No worker registered (never assigned, or revoked). The caller may hold the returned batch;
+ /// otherwise Kafka replays it.
+ NoWorker(Vec<ShuffleMessage>),
+ /// Worker channel closed (worker exited). The caller may hold the returned batch; otherwise Kafka
+ /// replays it.
+ ChannelClosed(Vec<ShuffleMessage>),
}
/// A registered worker channel: the sender and the per-partition event-intake budget its
@@ -237,8 +239,7 @@ impl PartitionRouter {
fn try_send_to_partition(&self, partition: i32, batch: Vec<ShuffleMessage>) -> SendOutcome {
let Some(channel) = self.channel_for(partition) else {
- self.record_drop(partition, batch.len(), REASON_NO_WORKER);
- return SendOutcome::NoWorker;
+ return SendOutcome::NoWorker(batch);
};
let count = batch.len();
// `None` for an event-less batch — carried through, not defaulted to 0, so a non-Event caller
@@ -267,8 +268,7 @@ impl PartitionRouter {
}
Err(TrySendError::Closed(returned)) => {
channel.intake.release(counted);
- self.record_drop(partition, returned.len(), REASON_CHANNEL_CLOSED);
- SendOutcome::ChannelClosed
+ SendOutcome::ChannelClosed(returned)
}
}
}
@@ -350,6 +350,7 @@ mod tests {
| ShuffleMessage::Cascade { .. }
| ShuffleMessage::RedrivePendingTransfers
| ShuffleMessage::MergeCfGc { .. }
+ | ShuffleMessage::ReconcileDrain
| ShuffleMessage::Seed { .. } => {
unreachable!("router tests route only events")
}
@@ -592,17 +593,17 @@ mod tests {
#[tokio::test]
async fn try_route_batch_reports_no_worker_and_channel_closed() {
let router = PartitionRouter::new(16);
- assert!(matches!(
- router.try_route_batch(vec![(9, event_off(1))]).remove(&9),
- Some(SendOutcome::NoWorker),
- ));
+ match router.try_route_batch(vec![(9, event_off(1))]).remove(&9) {
+ Some(SendOutcome::NoWorker(returned)) => assert_eq!(tags(&returned), vec![1]),
+ other => panic!("expected NoWorker, got {other:?}"),
+ }
let rx = router.add_partition(3).unwrap();
drop(rx);
- assert!(matches!(
- router.try_route_batch(vec![(3, event_off(1))]).remove(&3),
- Some(SendOutcome::ChannelClosed),
- ));
+ match router.try_route_batch(vec![(3, event_off(1))]).remove(&3) {
+ Some(SendOutcome::ChannelClosed(returned)) => assert_eq!(tags(&returned), vec![1]),
+ other => panic!("expected ChannelClosed, got {other:?}"),
+ }
}
#[tokio::test]
diff --git a/rust/cohort-stream-processor/src/partitions/shuffle_message.rs b/rust/cohort-stream-processor/src/partitions/shuffle_message.rs
index 983393017acc..0dfd9a8d82ef 100644
--- a/rust/cohort-stream-processor/src/partitions/shuffle_message.rs
+++ b/rust/cohort-stream-processor/src/partitions/shuffle_message.rs
@@ -51,6 +51,8 @@ pub enum ShuffleMessage {
marker_cutoff_ms: i64,
tombstone_cutoff_ms: i64,
},
+ /// Periodic bounded-progress tick for the partition's reconcile queue.
+ ReconcileDrain,
/// A backfill day-tile (or its consume-side skip), paired with its topic offset. Marked on
/// the seed tracker, never the events tracker. Boxed so the tile doesn't inflate every
/// `ShuffleMessage`.
@@ -69,6 +71,7 @@ impl ShuffleMessage {
| ShuffleMessage::Cascade { .. }
| ShuffleMessage::RedrivePendingTransfers
| ShuffleMessage::MergeCfGc { .. }
+ | ShuffleMessage::ReconcileDrain
| ShuffleMessage::Seed { .. } => None,
}
}
@@ -83,7 +86,8 @@ impl ShuffleMessage {
| ShuffleMessage::Transfer { .. }
| ShuffleMessage::Cascade { .. }
| ShuffleMessage::RedrivePendingTransfers
- | ShuffleMessage::MergeCfGc { .. } => None,
+ | ShuffleMessage::MergeCfGc { .. }
+ | ShuffleMessage::ReconcileDrain => None,
}
}
@@ -97,7 +101,8 @@ impl ShuffleMessage {
| ShuffleMessage::Transfer { .. }
| ShuffleMessage::Cascade { .. }
| ShuffleMessage::RedrivePendingTransfers
- | ShuffleMessage::MergeCfGc { .. } => false,
+ | ShuffleMessage::MergeCfGc { .. }
+ | ShuffleMessage::ReconcileDrain => false,
}
}
}
@@ -196,6 +201,7 @@ mod tests {
| ShuffleMessage::Transfer { .. }
| ShuffleMessage::RedrivePendingTransfers
| ShuffleMessage::MergeCfGc { .. }
+ | ShuffleMessage::ReconcileDrain
| ShuffleMessage::Seed { .. }
| ShuffleMessage::Cascade { .. } => unreachable!("constructed an Event"),
}
@@ -241,6 +247,9 @@ mod tests {
assert_eq!(event.seed_offset(), None);
assert!(event.counts_toward_intake());
assert!(!ShuffleMessage::RedrivePendingTransfers.counts_toward_intake());
+ assert!(!ShuffleMessage::ReconcileDrain.counts_toward_intake());
+ assert_eq!(ShuffleMessage::ReconcileDrain.event_offset(), None);
+ assert_eq!(ShuffleMessage::ReconcileDrain.seed_offset(), None);
}
#[test]
@@ -255,6 +264,7 @@ mod tests {
| ShuffleMessage::Transfer { .. }
| ShuffleMessage::RedrivePendingTransfers
| ShuffleMessage::MergeCfGc { .. }
+ | ShuffleMessage::ReconcileDrain
| ShuffleMessage::Seed { .. }
| ShuffleMessage::Cascade { .. } => unreachable!("constructed a Sweep"),
}
@@ -279,6 +289,7 @@ mod tests {
| ShuffleMessage::Merge { .. }
| ShuffleMessage::Transfer { .. }
| ShuffleMessage::RedrivePendingTransfers
+ | ShuffleMessage::ReconcileDrain
| ShuffleMessage::Seed { .. }
| ShuffleMessage::Cascade { .. } => unreachable!("constructed a MergeCfGc"),
}
@@ -300,6 +311,7 @@ mod tests {
| ShuffleMessage::Transfer { .. }
| ShuffleMessage::RedrivePendingTransfers
| ShuffleMessage::MergeCfGc { .. }
+ | ShuffleMessage::ReconcileDrain
| ShuffleMessage::Seed { .. }
| ShuffleMessage::Cascade { .. } => unreachable!("constructed a Merge"),
}
@@ -318,6 +330,7 @@ mod tests {
| ShuffleMessage::Merge { .. }
| ShuffleMessage::RedrivePendingTransfers
| ShuffleMessage::MergeCfGc { .. }
+ | ShuffleMessage::ReconcileDrain
| ShuffleMessage::Seed { .. }
| ShuffleMessage::Cascade { .. } => unreachable!("constructed a Transfer"),
}
@@ -342,6 +355,7 @@ mod tests {
| ShuffleMessage::Transfer { .. }
| ShuffleMessage::RedrivePendingTransfers
| ShuffleMessage::MergeCfGc { .. }
+ | ShuffleMessage::ReconcileDrain
| ShuffleMessage::Seed { .. } => unreachable!("constructed a Cascade"),
}
}
diff --git a/rust/cohort-stream-processor/src/producer/kafka.rs b/rust/cohort-stream-processor/src/producer/kafka.rs
index 7adb40778154..0ddf0c77344e 100644
--- a/rust/cohort-stream-processor/src/producer/kafka.rs
+++ b/rust/cohort-stream-processor/src/producer/kafka.rs
@@ -9,7 +9,7 @@ use common_kafka::kafka_producer::{
use common_liveness::SyncLivenessReporter;
use rdkafka::producer::FutureProducer;
-use crate::producer::{CohortMembershipChange, MembershipSink};
+use crate::producer::{CohortMembershipChange, MembershipSink, ReconcileCompleteMarker};
/// No-op liveness reporter — producer stalls are surfaced by the consumer's liveness deadline.
#[derive(Clone, Copy)]
@@ -49,16 +49,42 @@ impl MembershipSink for KafkaMembershipSink {
)
.await
}
+
+ async fn produce_markers(
+ &self,
+ markers: Vec<ReconcileCompleteMarker>,
+ ) -> Vec<Result<(), KafkaProduceError>> {
+ send_keyed_iter_to_kafka_with_headers(
+ &self.producer,
+ &self.topic,
+ reconcile_complete_key,
+ |_| None,
+ markers,
+ )
+ .await
+ }
}
fn membership_key(change: &CohortMembershipChange) -> Option<String> {
Some(change.person_id.clone())
}
+fn reconcile_complete_key(marker: &ReconcileCompleteMarker) -> Option<String> {
+ Some(format!(
+ "{}:{}:{}",
+ marker.team_id().0,
+ marker.cohort_id().0,
+ marker.run_id().0
+ ))
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ use crate::filters::{CohortId, TeamId};
use crate::producer::MembershipStatus;
+ use cohort_core::seed::RunId;
+ use uuid::Uuid;
#[test]
fn membership_key_is_the_person_id() {
@@ -73,4 +99,33 @@ mod tests {
};
assert_eq!(membership_key(&change), Some(change.person_id.clone()));
}
+
+ #[test]
+ fn reconcile_complete_key_identifies_the_run_without_the_partition() {
+ let run_id = RunId(Uuid::nil());
+ let marker = ReconcileCompleteMarker::new(
+ TeamId(42),
+ CohortId(91204),
+ 63,
+ run_id,
+ "2026-05-26 12:34:56.789123".to_string(),
+ );
+ let other_partition = ReconcileCompleteMarker::new(
+ TeamId(42),
+ CohortId(91204),
+ 0,
+ run_id,
+ "2026-05-26 12:34:56.789123".to_string(),
+ );
+
+ assert_eq!(
+ reconcile_complete_key(&marker),
+ Some("42:91204:00000000-0000-0000-0000-000000000000".to_string())
+ );
+ assert_eq!(
+ reconcile_complete_key(&marker),
+ reconcile_complete_key(&other_partition),
+ "all partition markers for one run share the same Kafka key",
+ );
+ }
}
diff --git a/rust/cohort-stream-processor/src/producer/mod.rs b/rust/cohort-stream-processor/src/producer/mod.rs
index b5ee792eb7ba..e2e7a97bb2b9 100644
--- a/rust/cohort-stream-processor/src/producer/mod.rs
+++ b/rust/cohort-stream-processor/src/producer/mod.rs
@@ -16,12 +16,14 @@ use async_trait::async_trait;
use chrono::Utc;
use common_kafka::kafka_producer::KafkaProduceError;
use metrics::counter;
+use serde::de::{Deserializer, Error as DeError, Unexpected};
+use serde::ser::Serializer;
use serde::{Deserialize, Serialize};
use cohort_core::seed::RunId;
use crate::filters::reverse_index::TeamFilters;
-use crate::filters::CohortId;
+use crate::filters::{CohortId, TeamId};
use crate::observability::metrics::OUTPUT_TRANSITIONS_UNMAPPED;
use crate::stage1::transition::{LeafTransition, TransitionKind};
@@ -60,6 +62,85 @@ pub struct CohortMembershipChange {
#[serde(rename_all = "snake_case")]
pub enum ChangeOrigin {
Seed,
+ Reconcile,
+}
+
+const RECONCILE_COMPLETE_KIND: &str = "reconcile_complete";
+
+/// A completion certificate emitted after one partition's reconcile snapshot is durable.
+/// Field order is the wire order.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ReconcileCompleteMarker {
+ #[serde(rename = "type")]
+ kind: ReconcileCompleteKind,
+ team_id: i32,
+ cohort_id: i32,
+ partition: u16,
+ run_id: RunId,
+ /// ClickHouse `DateTime64(6)` wire format.
+ last_updated: String,
+}
+
+impl ReconcileCompleteMarker {
+ pub fn new(
+ team_id: TeamId,
+ cohort_id: CohortId,
+ partition: u16,
+ run_id: RunId,
+ last_updated: String,
+ ) -> Self {
+ Self {
+ kind: ReconcileCompleteKind,
+ team_id: team_id.0,
+ cohort_id: cohort_id.0,
+ partition,
+ run_id,
+ last_updated,
+ }
+ }
+
+ pub const fn team_id(&self) -> TeamId {
+ TeamId(self.team_id)
+ }
+
+ pub const fn cohort_id(&self) -> CohortId {
+ CohortId(self.cohort_id)
+ }
+
+ pub const fn partition(&self) -> u16 {
+ self.partition
+ }
+
+ pub const fn run_id(&self) -> RunId {
+ self.run_id
+ }
+
+ pub fn last_updated(&self) -> &str {
+ &self.last_updated
+ }
+}
+
+/// A zero-sized discriminant proven to be [`RECONCILE_COMPLETE_KIND`] during deserialization.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+struct ReconcileCompleteKind;
+
+impl Serialize for ReconcileCompleteKind {
+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ serializer.serialize_str(RECONCILE_COMPLETE_KIND)
+ }
+}
+
+impl<'de> Deserialize<'de> for ReconcileCompleteKind {
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let value = String::deserialize(deserializer)?;
+ if value != RECONCILE_COMPLETE_KIND {
+ return Err(DeError::invalid_value(
+ Unexpected::Str(&value),
+ &"marker type \"reconcile_complete\"",
+ ));
+ }
+ Ok(Self)
+ }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -122,7 +203,35 @@ pub fn map_transition<'a>(
/// Current UTC time as a ClickHouse `DateTime64(6)` string (microseconds).
pub fn now_last_updated() -> String {
- Utc::now().format("%Y-%m-%d %H:%M:%S%.6f").to_string()
+ format_last_updated(Utc::now().timestamp_micros())
+}
+
+/// Per-partition output-version allocator. Wall time supplies the normal value; the local floor
+/// makes every later worker message strictly newer even if the clock stalls or moves backward.
+#[derive(Debug, Default)]
+pub(crate) struct LastUpdatedClock {
+ last_micros: Option<i64>,
+}
+
+impl LastUpdatedClock {
+ pub fn next(&mut self) -> String {
+ self.next_at(Utc::now().timestamp_micros())
+ }
+
+ fn next_at(&mut self, observed_micros: i64) -> String {
+ let next_micros = self.last_micros.map_or(observed_micros, |last_micros| {
+ observed_micros.max(last_micros.saturating_add(1))
+ });
+ self.last_micros = Some(next_micros);
+ format_last_updated(next_micros)
+ }
+}
+
+fn format_last_updated(timestamp_micros: i64) -> String {
+ chrono::DateTime::<Utc>::from_timestamp_micros(timestamp_micros)
+ .expect("current UTC timestamps fit Chrono's supported range")
+ .format("%Y-%m-%d %H:%M:%S%.6f")
+ .to_string()
}
#[async_trait]
@@ -131,11 +240,17 @@ pub trait MembershipSink: Send + Sync {
&self,
changes: Vec<CohortMembershipChange>,
) -> Vec<Result<(), KafkaProduceError>>;
+
+ async fn produce_markers(
+ &self,
+ markers: Vec<ReconcileCompleteMarker>,
+ ) -> Vec<Result<(), KafkaProduceError>>;
}
#[derive(Debug, Default, Clone)]
pub struct CaptureSink {
changes: Arc<Mutex<Vec<CohortMembershipChange>>>,
+ markers: Arc<Mutex<Vec<ReconcileCompleteMarker>>>,
fail_remaining: Arc<AtomicUsize>,
}
@@ -147,6 +262,7 @@ impl CaptureSink {
pub fn failing_first(n: usize) -> Self {
Self {
changes: Arc::default(),
+ markers: Arc::default(),
fail_remaining: Arc::new(AtomicUsize::new(n)),
}
}
@@ -157,6 +273,21 @@ impl CaptureSink {
.expect("CaptureSink mutex poisoned")
.clone()
}
+
+ pub fn markers(&self) -> Vec<ReconcileCompleteMarker> {
+ self.markers
+ .lock()
+ .expect("CaptureSink mutex poisoned")
+ .clone()
+ }
+
+ fn should_fail(&self) -> bool {
+ self.fail_remaining
+ .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| {
+ (n > 0).then(|| n - 1)
+ })
+ .is_ok()
+ }
}
#[async_trait]
@@ -165,13 +296,7 @@ impl MembershipSink for CaptureSink {
&self,
changes: Vec<CohortMembershipChange>,
) -> Vec<Result<(), KafkaProduceError>> {
- let should_fail = self
- .fail_remaining
- .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| {
- (n > 0).then(|| n - 1)
- })
- .is_ok();
- if should_fail {
+ if self.should_fail() {
return changes
.into_iter()
.map(|_| Err(KafkaProduceError::KafkaProduceCanceled))
@@ -184,6 +309,24 @@ impl MembershipSink for CaptureSink {
.extend(changes);
acks
}
+
+ async fn produce_markers(
+ &self,
+ markers: Vec<ReconcileCompleteMarker>,
+ ) -> Vec<Result<(), KafkaProduceError>> {
+ if self.should_fail() {
+ return markers
+ .into_iter()
+ .map(|_| Err(KafkaProduceError::KafkaProduceCanceled))
+ .collect();
+ }
+ let acks = (0..markers.len()).map(|_| Ok(())).collect();
+ self.markers
+ .lock()
+ .expect("CaptureSink mutex poisoned")
+ .extend(markers);
+ acks
+ }
}
#[cfg(test)]
@@ -236,6 +379,16 @@ mod tests {
}
}
+ fn reconcile_complete_marker(partition: u16) -> ReconcileCompleteMarker {
+ ReconcileCompleteMarker::new(
+ TeamId(42),
+ CohortId(91204),
+ partition,
+ RunId(Uuid::nil()),
+ TS.to_string(),
+ )
+ }
+
#[test]
fn map_transition_entered_maps_to_one_change() {
let mut builder = TeamFiltersBuilder::default();
@@ -353,6 +506,38 @@ mod tests {
assert_eq!(value, json!("left"));
}
+ #[test]
+ fn reconcile_origin_serializes_snake_case() {
+ let value = serde_json::to_value(ChangeOrigin::Reconcile).unwrap();
+ assert_eq!(value, json!("reconcile"));
+ }
+
+ #[test]
+ fn reconcile_complete_marker_has_the_exact_wire_contract() {
+ let marker = reconcile_complete_marker(7);
+
+ assert_eq!(
+ serde_json::to_string(&marker).unwrap(),
+ r#"{"type":"reconcile_complete","team_id":42,"cohort_id":91204,"partition":7,"run_id":"00000000-0000-0000-0000-000000000000","last_updated":"2026-05-26 12:34:56.789123"}"#,
+ );
+ assert_eq!(
+ serde_json::from_str::<ReconcileCompleteMarker>(
+ &serde_json::to_string(&marker).unwrap()
+ )
+ .unwrap(),
+ marker
+ );
+ }
+
+ #[test]
+ fn reconcile_complete_marker_rejects_another_message_type() {
+ let payload = serde_json::to_string(&reconcile_complete_marker(7))
+ .unwrap()
+ .replace("reconcile_complete", "seed");
+
+ assert!(serde_json::from_str::<ReconcileCompleteMarker>(&payload).is_err());
+ }
+
#[test]
fn live_path_change_stays_byte_identical_and_a_seed_tag_adds_only_the_two_keys() {
let live = CohortMembershipChange {
@@ -402,6 +587,21 @@ mod tests {
assert_eq!(time.matches(':').count(), 2);
}
+ #[test]
+ fn last_updated_clock_is_strictly_monotonic_when_wall_time_stalls_or_rewinds() {
+ let mut clock = LastUpdatedClock::default();
+
+ let first = clock.next_at(1_700_000_000_000_000);
+ let stalled = clock.next_at(1_700_000_000_000_000);
+ let rewound = clock.next_at(1_699_999_999_000_000);
+
+ assert!(first < stalled);
+ assert!(stalled < rewound);
+ assert_eq!(first, "2023-11-14 22:13:20.000000");
+ assert_eq!(stalled, "2023-11-14 22:13:20.000001");
+ assert_eq!(rewound, "2023-11-14 22:13:20.000002");
+ }
+
#[tokio::test]
async fn capture_sink_records_and_acks_in_order() {
let sink = CaptureSink::new();
@@ -441,4 +641,41 @@ mod tests {
assert!(second.iter().all(Result::is_ok), "second flush succeeds");
assert_eq!(sink.changes(), vec![change]);
}
+
+ #[tokio::test]
+ async fn capture_sink_records_markers_and_shares_failure_order_across_message_types() {
+ let sink = CaptureSink::failing_first(1);
+ let change = CohortMembershipChange {
+ team_id: 42,
+ cohort_id: 91204,
+ person_id: "p".to_string(),
+ last_updated: TS.to_string(),
+ status: MembershipStatus::Entered,
+ origin: Some(ChangeOrigin::Reconcile),
+ run_id: Some(RunId(Uuid::nil())),
+ };
+ let marker = reconcile_complete_marker(7);
+
+ let first = sink.produce(vec![change]).await;
+ assert!(first.iter().all(Result::is_err), "first flush fails");
+ assert!(sink.changes().is_empty(), "a failed flush records nothing");
+
+ let second = sink.produce_markers(vec![marker.clone()]).await;
+ assert!(second.iter().all(Result::is_ok), "second flush succeeds");
+ assert_eq!(sink.markers(), vec![marker]);
+ }
+
+ #[tokio::test]
+ async fn capture_sink_retries_a_failed_marker_without_recording_the_failed_attempt() {
+ let sink = CaptureSink::failing_first(1);
+ let marker = reconcile_complete_marker(7);
+
+ let first = sink.produce_markers(vec![marker.clone()]).await;
+ assert!(first.iter().all(Result::is_err), "first flush fails");
+ assert!(sink.markers().is_empty(), "a failed flush records nothing");
+
+ let second = sink.produce_markers(vec![marker.clone()]).await;
+ assert!(second.iter().all(Result::is_ok), "retry succeeds");
+ assert_eq!(sink.markers(), vec![marker]);
+ }
}
diff --git a/rust/cohort-stream-processor/src/store/handle.rs b/rust/cohort-stream-processor/src/store/handle.rs
index 25dbcd4d4ac5..fb18812cb51e 100644
--- a/rust/cohort-stream-processor/src/store/handle.rs
+++ b/rust/cohort-stream-processor/src/store/handle.rs
@@ -26,9 +26,13 @@ use metrics::{gauge, histogram};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use tokio::task::JoinError;
-use super::keys::{PendingTransferKey, Stage2Key, TombstoneKey};
+use super::keys::{
+ PendingTransferKey, Stage2CohortPrefix, Stage2DirtyKey, Stage2Key, TombstoneKey,
+};
use super::keyspace::{BehavioralKey, PersonPrefix, PersonRecordKey};
-use super::rocks::{CohortStore, EventSnapshotRaw, StoreError, StoreStats};
+use super::rocks::{
+ CohortStore, EventSnapshotRaw, Stage2DirtyTrackingGuard, StoreError, StoreStats,
+};
use super::staged::StagedBatch;
use crate::observability::metrics::{
STORE_OFFLOAD_EXEC_DURATION_SECONDS, STORE_OFFLOAD_INFLIGHT,
@@ -339,6 +343,38 @@ impl StoreHandle {
.await
}
+ /// Scan one bounded page of a partition/team/cohort `cf_stage2` slice on the maintenance lane.
+ pub async fn scan_stage2_cohort(
+ &self,
+ prefix: Stage2CohortPrefix,
+ start_after: Option<Vec<u8>>,
+ limit: usize,
+ ) -> Result<Vec<Stage2Key>, StoreError> {
+ self.read("scan_stage2_cohort", ReadLane::Maintenance, move |store| {
+ store.scan_stage2_cohort(prefix, start_after.as_deref(), limit)
+ })
+ .await
+ }
+
+ /// Scan one bounded page of a cohort's dirty-person markers on the maintenance lane.
+ pub async fn scan_stage2_dirty(
+ &self,
+ prefix: Stage2CohortPrefix,
+ start_after: Option<Vec<u8>>,
+ limit: usize,
+ ) -> Result<Vec<Stage2DirtyKey>, StoreError> {
+ self.read("scan_stage2_dirty", ReadLane::Maintenance, move |store| {
+ store.scan_stage2_dirty(prefix, start_after.as_deref(), limit)
+ })
+ .await
+ }
+
+ /// Start process-local dirty capture for one queued reconcile job. The returned lease owns the
+ /// registration and disables it on drop.
+ pub fn track_stage2_dirty(&self, prefix: Stage2CohortPrefix) -> Stage2DirtyTrackingGuard {
+ self.store.track_stage2_dirty(prefix)
+ }
+
/// Point-read one redirect tombstone.
pub async fn get_tombstone(
&self,
diff --git a/rust/cohort-stream-processor/src/store/keys.rs b/rust/cohort-stream-processor/src/store/keys.rs
index 5f01f2be85e9..7ee61defe88c 100644
--- a/rust/cohort-stream-processor/src/store/keys.rs
+++ b/rust/cohort-stream-processor/src/store/keys.rs
@@ -11,6 +11,13 @@ use super::rocks::StoreError;
/// `[partition_id u16][team_id u64][cohort_id u64][person_id 16]`.
pub const STAGE2_KEY_LEN: usize = 2 + 8 + 8 + 16;
+/// `[partition_id u16][team_id u64][cohort_id u64]`.
+pub const STAGE2_COHORT_PREFIX_LEN: usize = 2 + 8 + 8;
+/// `[partition_id u16][0xFF; 32][dirty discriminant][team_id u64][cohort_id u64]`.
+pub const STAGE2_DIRTY_COHORT_PREFIX_LEN: usize = STAGE2_KEY_LEN + 1 + 8 + 8;
+/// `[dirty cohort prefix][person_id 16]`.
+pub const STAGE2_DIRTY_KEY_LEN: usize = STAGE2_DIRTY_COHORT_PREFIX_LEN + 16;
+const STAGE2_DIRTY_DISCRIMINANT: u8 = 1;
/// `[partition_id u16][0xFF; 32][transferred-register discriminant][team_id u64][person_id 16]`.
pub const STAGE2_TRANSFERRED_REGISTER_PERSON_PREFIX_LEN: usize = STAGE2_KEY_LEN + 1 + 8 + 16;
/// `[transferred-register person prefix][cohort_id u64]`.
@@ -35,6 +42,26 @@ pub struct Stage2Key {
pub person_id: Uuid,
}
+/// Prefix selecting one cohort's membership rows in one partition.
+#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
+pub struct Stage2CohortPrefix {
+ pub partition_id: u16,
+ pub team_id: u64,
+ pub cohort_id: u64,
+}
+
+/// Coalescing mutation marker for one Stage 2 person row.
+///
+/// Dirty keys sort after every valid [`Stage2Key`] in their partition. Their namespace starts with
+/// the partition's maximum 34-byte Stage 2 row, followed by a discriminant below `0xFF`; this keeps
+/// them inside the partition range without colliding with a row, including in partition `u16::MAX`.
+#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
+pub struct Stage2DirtyKey(Stage2Key);
+
+/// Prefix selecting one cohort's dirty-person markers.
+#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
+pub struct Stage2DirtyPrefix(Stage2CohortPrefix);
+
/// Catalog-independent inventory for a register received through the merge protocol.
///
/// The primary Stage 2 layout is cohort-first, so a merge drain cannot enumerate one person's rows
@@ -112,6 +139,130 @@ impl Stage2Key {
person_id: Uuid::from_bytes(array16(&bytes[18..34])),
})
}
+
+ pub fn cohort_prefix(&self) -> Stage2CohortPrefix {
+ Stage2CohortPrefix {
+ partition_id: self.partition_id,
+ team_id: self.team_id,
+ cohort_id: self.cohort_id,
+ }
+ }
+}
+
+impl Stage2CohortPrefix {
+ pub fn encode(&self) -> [u8; STAGE2_COHORT_PREFIX_LEN] {
+ let mut out = [0u8; STAGE2_COHORT_PREFIX_LEN];
+ out[0..2].copy_from_slice(&self.partition_id.to_be_bytes());
+ out[2..10].copy_from_slice(&self.team_id.to_be_bytes());
+ out[10..18].copy_from_slice(&self.cohort_id.to_be_bytes());
+ out
+ }
+
+ pub fn decode(bytes: &[u8]) -> Result<Self, StoreError> {
+ check_len(bytes, STAGE2_COHORT_PREFIX_LEN, "stage2 cohort prefix")?;
+ Ok(Self {
+ partition_id: u16::from_be_bytes(array2(&bytes[0..2])),
+ team_id: u64::from_be_bytes(array8(&bytes[2..10])),
+ cohort_id: u64::from_be_bytes(array8(&bytes[10..18])),
+ })
+ }
+
+ /// Half-open byte range containing the matching [`Stage2Key`] values.
+ pub fn range(&self) -> (Vec<u8>, Vec<u8>) {
+ let start = self.encode().to_vec();
+ let mut end = start.clone();
+ for byte in end.iter_mut().rev() {
+ if let Some(next) = byte.checked_add(1) {
+ *byte = next;
+ return (start, end);
+ }
+ *byte = 0;
+ }
+
+ // The maximum valid Stage2 key is 34 bytes of 0xFF, so the same bytes plus one remain a
+ // strict exclusive upper bound when the 18-byte prefix itself has no successor.
+ (start, vec![0xFF; STAGE2_KEY_LEN + 1])
+ }
+
+ pub const fn dirty_prefix(self) -> Stage2DirtyPrefix {
+ Stage2DirtyPrefix(self)
+ }
+}
+
+impl Stage2DirtyKey {
+ pub const fn new(key: Stage2Key) -> Self {
+ Self(key)
+ }
+
+ pub const fn stage2_key(self) -> Stage2Key {
+ self.0
+ }
+
+ pub fn encode(self) -> [u8; STAGE2_DIRTY_KEY_LEN] {
+ let mut out = [0u8; STAGE2_DIRTY_KEY_LEN];
+ out[0..2].copy_from_slice(&self.0.partition_id.to_be_bytes());
+ out[2..STAGE2_KEY_LEN].fill(0xFF);
+ out[STAGE2_KEY_LEN] = STAGE2_DIRTY_DISCRIMINANT;
+ out[(STAGE2_KEY_LEN + 1)..(STAGE2_KEY_LEN + 9)]
+ .copy_from_slice(&self.0.team_id.to_be_bytes());
+ out[(STAGE2_KEY_LEN + 9)..STAGE2_DIRTY_COHORT_PREFIX_LEN]
+ .copy_from_slice(&self.0.cohort_id.to_be_bytes());
+ out[STAGE2_DIRTY_COHORT_PREFIX_LEN..].copy_from_slice(self.0.person_id.as_bytes());
+ out
+ }
+
+ pub fn decode(bytes: &[u8]) -> Result<Self, StoreError> {
+ check_len(bytes, STAGE2_DIRTY_KEY_LEN, "stage2 dirty")?;
+ if bytes[2..STAGE2_KEY_LEN].iter().any(|byte| *byte != 0xFF)
+ || bytes[STAGE2_KEY_LEN] != STAGE2_DIRTY_DISCRIMINANT
+ {
+ return Err(StoreError::UnknownKey {
+ kind: "stage2 dirty",
+ });
+ }
+ Ok(Self(Stage2Key {
+ partition_id: u16::from_be_bytes(array2(&bytes[0..2])),
+ team_id: u64::from_be_bytes(array8(&bytes[(STAGE2_KEY_LEN + 1)..(STAGE2_KEY_LEN + 9)])),
+ cohort_id: u64::from_be_bytes(array8(
+ &bytes[(STAGE2_KEY_LEN + 9)..STAGE2_DIRTY_COHORT_PREFIX_LEN],
+ )),
+ person_id: Uuid::from_bytes(array16(&bytes[STAGE2_DIRTY_COHORT_PREFIX_LEN..])),
+ }))
+ }
+}
+
+impl Stage2DirtyPrefix {
+ pub fn encode(self) -> [u8; STAGE2_DIRTY_COHORT_PREFIX_LEN] {
+ let key = Stage2Key {
+ partition_id: self.0.partition_id,
+ team_id: self.0.team_id,
+ cohort_id: self.0.cohort_id,
+ person_id: Uuid::nil(),
+ };
+ let encoded = Stage2DirtyKey::new(key).encode();
+ let mut out = [0u8; STAGE2_DIRTY_COHORT_PREFIX_LEN];
+ out.copy_from_slice(&encoded[..STAGE2_DIRTY_COHORT_PREFIX_LEN]);
+ out
+ }
+
+ pub fn range(self) -> (Vec<u8>, Vec<u8>) {
+ let start = self.encode().to_vec();
+ let mut end = start.clone();
+ for byte in end.iter_mut().rev() {
+ if let Some(next) = byte.checked_add(1) {
+ *byte = next;
+ return (start, end);
+ }
+ *byte = 0;
+ }
+ unreachable!("the dirty discriminant has a lexicographic successor")
+ }
+}
+
+impl From<Stage2Key> for Stage2DirtyKey {
+ fn from(value: Stage2Key) -> Self {
+ Self::new(value)
+ }
}
impl Stage2TransferredRegisterKey {
@@ -346,6 +497,8 @@ fn array16(s: &[u8]) -> [u8; 16] {
#[cfg(test)]
mod tests {
+ use proptest::prelude::*;
+
use super::*;
use crate::stage1::key::LeafStateKey;
use crate::store::keyspace::BehavioralKey;
@@ -372,6 +525,29 @@ mod tests {
34,
);
assert_eq!(STAGE2_KEY_LEN, 34);
+ assert_eq!(
+ Stage2CohortPrefix {
+ partition_id: 1,
+ team_id: 2,
+ cohort_id: 3,
+ }
+ .encode()
+ .len(),
+ 18,
+ );
+ assert_eq!(STAGE2_COHORT_PREFIX_LEN, 18);
+ assert_eq!(
+ Stage2DirtyKey::new(Stage2Key {
+ partition_id: 1,
+ team_id: 2,
+ cohort_id: 3,
+ person_id: person(4),
+ })
+ .encode()
+ .len(),
+ STAGE2_DIRTY_KEY_LEN,
+ );
+ assert_eq!(STAGE2_DIRTY_KEY_LEN, 67);
assert_eq!(STAGE2_TRANSFERRED_REGISTER_PERSON_PREFIX_LEN, 59);
assert_eq!(
Stage2TransferredRegisterKey::new(Stage2Key {
@@ -414,6 +590,41 @@ mod tests {
);
}
+ #[test]
+ fn stage2_dirty_key_round_trips_without_colliding_with_a_person_row() {
+ let row = Stage2Key {
+ partition_id: 7,
+ team_id: 42,
+ cohort_id: 99,
+ person_id: person(123),
+ };
+ let dirty = Stage2DirtyKey::new(row);
+ let encoded = dirty.encode();
+ assert_eq!(Stage2DirtyKey::decode(&encoded).unwrap(), dirty);
+ assert!(Stage2Key::decode(&encoded).is_err());
+
+ let mut wrong_discriminant = encoded;
+ wrong_discriminant[STAGE2_KEY_LEN] = 2;
+ assert!(Stage2DirtyKey::decode(&wrong_discriminant).is_err());
+ }
+
+ #[test]
+ fn stage2_dirty_namespace_sorts_after_rows_and_inside_its_partition() {
+ for partition_id in [0, 7, u16::MAX] {
+ let row = Stage2Key {
+ partition_id,
+ team_id: u64::MAX,
+ cohort_id: u64::MAX,
+ person_id: person(u128::MAX),
+ };
+ let dirty = Stage2DirtyKey::new(row).encode();
+ assert!(row.encode().as_slice() < dirty.as_slice());
+ let (partition_start, partition_end) = partition_range(partition_id);
+ assert!(partition_start.as_slice() <= dirty.as_slice());
+ assert!(dirty.as_slice() < partition_end.as_slice());
+ }
+ }
+
#[test]
fn transferred_register_key_round_trips_and_groups_by_person() {
let row = Stage2Key {
@@ -433,10 +644,11 @@ mod tests {
Stage2TransferredRegisterPersonPrefix::new(7, 42, person(123)),
);
assert!(Stage2Key::decode(&inventory.encode()).is_err());
+ assert!(Stage2DirtyKey::decode(&inventory.encode()).is_err());
}
#[test]
- fn transferred_register_namespace_sorts_after_rows_and_inside_partition() {
+ fn transferred_register_namespace_sorts_after_dirty_and_inside_partition() {
for partition_id in [0, 7, u16::MAX] {
let row = Stage2Key {
partition_id,
@@ -444,8 +656,10 @@ mod tests {
cohort_id: u64::MAX,
person_id: person(u128::MAX),
};
+ let dirty = Stage2DirtyKey::new(row).encode();
let inventory = Stage2TransferredRegisterKey::new(row).encode();
- assert!(row.encode().as_slice() < inventory.as_slice());
+ assert!(row.encode().as_slice() < dirty.as_slice());
+ assert!(dirty.as_slice() < inventory.as_slice());
let (partition_start, partition_end) = partition_range(partition_id);
assert!(partition_start.as_slice() <= inventory.as_slice());
assert!(inventory.as_slice() < partition_end.as_slice());
@@ -492,6 +706,164 @@ mod tests {
}
}
+ #[test]
+ fn stage2_dirty_prefix_selects_exactly_one_cohort() {
+ let prefix = Stage2CohortPrefix {
+ partition_id: 7,
+ team_id: 42,
+ cohort_id: 99,
+ }
+ .dirty_prefix();
+ let (start, end) = prefix.range();
+ for person_id in [0, 1, u128::MAX] {
+ let encoded = Stage2DirtyKey::new(Stage2Key {
+ partition_id: 7,
+ team_id: 42,
+ cohort_id: 99,
+ person_id: person(person_id),
+ })
+ .encode();
+ assert!(start.as_slice() <= encoded.as_slice());
+ assert!(encoded.as_slice() < end.as_slice());
+ }
+ for foreign in [
+ Stage2Key {
+ partition_id: 8,
+ team_id: 42,
+ cohort_id: 99,
+ person_id: person(1),
+ },
+ Stage2Key {
+ partition_id: 7,
+ team_id: 43,
+ cohort_id: 99,
+ person_id: person(1),
+ },
+ Stage2Key {
+ partition_id: 7,
+ team_id: 42,
+ cohort_id: 100,
+ person_id: person(1),
+ },
+ ] {
+ let encoded = Stage2DirtyKey::new(foreign).encode();
+ assert!(encoded.as_slice() < start.as_slice() || encoded.as_slice() >= end.as_slice());
+ }
+ }
+
+ proptest! {
+ #[test]
+ fn stage2_cohort_prefix_range_contains_exactly_matching_keys(
+ partition_id in any::<u16>(),
+ team_id in any::<u64>(),
+ cohort_id in any::<u64>(),
+ person_id in any::<u128>(),
+ foreign_axis in 0u8..3,
+ ) {
+ let prefix = Stage2CohortPrefix {
+ partition_id,
+ team_id,
+ cohort_id,
+ };
+ let (start, end) = prefix.range();
+ let matching = Stage2Key {
+ partition_id,
+ team_id,
+ cohort_id,
+ person_id: person(person_id),
+ }
+ .encode();
+ prop_assert!(start.as_slice() <= matching.as_slice());
+ prop_assert!(matching.as_slice() < end.as_slice());
+
+ let (foreign_partition, foreign_team, foreign_cohort) = match foreign_axis {
+ 0 => (partition_id.wrapping_add(1), team_id, cohort_id),
+ 1 => (partition_id, team_id.wrapping_add(1), cohort_id),
+ _ => (partition_id, team_id, cohort_id.wrapping_add(1)),
+ };
+ let foreign = Stage2Key {
+ partition_id: foreign_partition,
+ team_id: foreign_team,
+ cohort_id: foreign_cohort,
+ person_id: person(person_id),
+ }
+ .encode();
+ prop_assert!(
+ foreign.as_slice() < start.as_slice() || foreign.as_slice() >= end.as_slice()
+ );
+ }
+ }
+
+ #[test]
+ fn stage2_cohort_prefix_range_carries_and_bounds_the_all_ones_key() {
+ for (prefix, expected_end) in [
+ (
+ Stage2CohortPrefix {
+ partition_id: 1,
+ team_id: 2,
+ cohort_id: 3,
+ },
+ Stage2CohortPrefix {
+ partition_id: 1,
+ team_id: 2,
+ cohort_id: 4,
+ }
+ .encode()
+ .to_vec(),
+ ),
+ (
+ Stage2CohortPrefix {
+ partition_id: 1,
+ team_id: 2,
+ cohort_id: u64::MAX,
+ },
+ Stage2CohortPrefix {
+ partition_id: 1,
+ team_id: 3,
+ cohort_id: 0,
+ }
+ .encode()
+ .to_vec(),
+ ),
+ (
+ Stage2CohortPrefix {
+ partition_id: 1,
+ team_id: u64::MAX,
+ cohort_id: u64::MAX,
+ },
+ Stage2CohortPrefix {
+ partition_id: 2,
+ team_id: 0,
+ cohort_id: 0,
+ }
+ .encode()
+ .to_vec(),
+ ),
+ ] {
+ assert_eq!(prefix.range().1, expected_end);
+ }
+
+ let max_prefix = Stage2CohortPrefix {
+ partition_id: u16::MAX,
+ team_id: u64::MAX,
+ cohort_id: u64::MAX,
+ };
+ let (start, end) = max_prefix.range();
+ assert_eq!(start, vec![0xFF; STAGE2_COHORT_PREFIX_LEN]);
+ assert_eq!(end, vec![0xFF; STAGE2_KEY_LEN + 1]);
+ assert!(
+ Stage2Key {
+ partition_id: u16::MAX,
+ team_id: u64::MAX,
+ cohort_id: u64::MAX,
+ person_id: person(u128::MAX),
+ }
+ .encode()
+ .as_slice()
+ < end.as_slice(),
+ );
+ }
+
#[test]
fn partition_range_is_the_two_byte_successor() {
let (start, end) = partition_range(0);
diff --git a/rust/cohort-stream-processor/src/store/mod.rs b/rust/cohort-stream-processor/src/store/mod.rs
index 5db880af00e9..6a183a5dffce 100644
--- a/rust/cohort-stream-processor/src/store/mod.rs
+++ b/rust/cohort-stream-processor/src/store/mod.rs
@@ -15,7 +15,8 @@ pub use column_families::{
};
pub use handle::{OffloadConfig, OffloadMode, ReadLane, StoreHandle};
pub use keys::{
- MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage2Key, Stage2TransferredRegisterKey,
+ MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage2CohortPrefix, Stage2DirtyKey,
+ Stage2DirtyPrefix, Stage2Key, Stage2TransferredRegisterKey,
Stage2TransferredRegisterPersonPrefix, TombstoneKey,
};
pub use keyspace::{
@@ -23,8 +24,8 @@ pub use keyspace::{
PersonRecords,
};
pub use rocks::{
- BatchBuilder, CfStats, CohortStore, EventSnapshotRaw, StoreConfig, StoreError, StoreStats,
- STORE_SCHEMA_VERSION,
+ BatchBuilder, CfStats, CohortStore, EventSnapshotRaw, Stage2DirtyTrackingGuard, StoreConfig,
+ StoreError, StoreStats, STORE_SCHEMA_VERSION,
};
pub use staged::StagedBatch;
diff --git a/rust/cohort-stream-processor/src/store/rocks.rs b/rust/cohort-stream-processor/src/store/rocks.rs
index cfcf30722e91..a5ec274a7ac7 100644
--- a/rust/cohort-stream-processor/src/store/rocks.rs
+++ b/rust/cohort-stream-processor/src/store/rocks.rs
@@ -6,8 +6,10 @@
#![allow(clippy::disallowed_methods)]
use std::cell::Cell;
+use std::collections::HashSet;
use std::path::{Path, PathBuf};
-use std::sync::Arc;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, RwLock};
use std::time::Instant;
use metrics::{counter, histogram};
@@ -22,17 +24,19 @@ use tracing::warn;
use super::column_families::{self, Cf, OpaqueCf};
use super::keys::{
- self, MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage2Key,
- Stage2TransferredRegisterKey, Stage2TransferredRegisterPersonPrefix, TombstoneKey,
+ self, MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage2CohortPrefix, Stage2DirtyKey,
+ Stage2Key, Stage2TransferredRegisterKey, Stage2TransferredRegisterPersonPrefix, TombstoneKey,
+ STAGE2_DIRTY_KEY_LEN,
};
use super::keyspace::{
BehavioralKey, Keyspace, Meta, PersonPrefix, PersonRecordKey, META_SCHEMA_VERSION,
};
use super::staged::{StagedBatch, StagedOp};
use crate::observability::metrics::{
- CHECKPOINT_DURATION_SECONDS, STORE_ERRORS_TOTAL, STORE_READS_TOTAL,
- STORE_READ_DURATION_SECONDS, STORE_SCHEMA_MISMATCH_WIPES_TOTAL, STORE_WRITE_BATCH_TOTAL,
- STORE_WRITE_DURATION_SECONDS, WAL_FSYNC_DURATION_SECONDS, WAL_FSYNC_ERRORS_TOTAL,
+ CHECKPOINT_DURATION_SECONDS, STAGE2_SCAN_UNDECODABLE_KEYS_TOTAL, STORE_ERRORS_TOTAL,
+ STORE_READS_TOTAL, STORE_READ_DURATION_SECONDS, STORE_SCHEMA_MISMATCH_WIPES_TOTAL,
+ STORE_WRITE_BATCH_TOTAL, STORE_WRITE_DURATION_SECONDS, WAL_FSYNC_DURATION_SECONDS,
+ WAL_FSYNC_ERRORS_TOTAL,
};
/// On-disk store schema version, stamped into `cf_meta` at first open and checked on every reopen.
@@ -157,6 +161,13 @@ pub enum StoreError {
actual: usize,
},
+ #[error("decoding {kind} value: expected {expected} bytes, got {actual}")]
+ ValueDecode {
+ kind: &'static str,
+ expected: usize,
+ actual: usize,
+ },
+
/// A key of the right length that matches none of the keyspace's known literals (closed-set
/// keyspaces like `cf_meta`). Distinct from [`Self::KeyDecode`], which reports a length mismatch.
#[error("unknown {kind} key: matches no known literal")]
@@ -175,6 +186,88 @@ pub enum StoreError {
/// One scanned key/value pair as raw bytes — the merge-CF GC decodes each per CF.
pub type RawKv = (Vec<u8>, Vec<u8>);
+#[derive(Debug, Default)]
+struct Stage2DirtyTracking {
+ /// The set of cohort prefixes with a reconcile drain currently capturing dirty rows. At most one
+ /// job per prefix ever holds a lease (admission supersedes same `(partition, team, cohort)`, and
+ /// the partition worker is serial), so a set — not a refcount — models the real invariant.
+ active: RwLock<HashSet<Stage2CohortPrefix>>,
+ active_count: AtomicUsize,
+}
+
+impl Stage2DirtyTracking {
+ fn acquire(self: &Arc<Self>, prefix: Stage2CohortPrefix) -> Stage2DirtyTrackingGuard {
+ let mut active = self
+ .active
+ .write()
+ .expect("Stage 2 dirty-tracking lock is not held across fallible work");
+ let inserted = active.insert(prefix);
+ debug_assert!(
+ inserted,
+ "a cohort prefix cannot hold two dirty-tracking leases"
+ );
+ self.active_count.fetch_add(1, Ordering::Release);
+ Stage2DirtyTrackingGuard {
+ tracking: self.clone(),
+ prefix,
+ }
+ }
+
+ /// Cheap pre-check for the hot write path: whether any drain is capturing at all. A `false` lets
+ /// a reconcile-disabled pipeline skip decoding the Stage 2 key entirely.
+ fn any_active(&self) -> bool {
+ self.active_count.load(Ordering::Acquire) != 0
+ }
+
+ fn is_active(&self, prefix: Stage2CohortPrefix) -> bool {
+ if !self.any_active() {
+ return false;
+ }
+ self.active
+ .read()
+ .expect("Stage 2 dirty-tracking lock is not held across fallible work")
+ .contains(&prefix)
+ }
+
+ /// The dirty marker to stage for a `cf_stage2` write, or `None` when no drain tracks its cohort.
+ /// The single home of the "is this cohort captured / which marker do we write" decision, shared by
+ /// the live-event [`BatchBuilder`] path and the owned [`StagedBatch`] apply path so the rule for
+ /// emitting a marker cannot drift between them.
+ fn dirty_marker(&self, key: &Stage2Key) -> Option<[u8; STAGE2_DIRTY_KEY_LEN]> {
+ self.is_active(key.cohort_prefix())
+ .then(|| Stage2DirtyKey::new(*key).encode())
+ }
+
+ fn release(&self, prefix: Stage2CohortPrefix) {
+ let removed = self
+ .active
+ .write()
+ .expect("Stage 2 dirty-tracking lock is not held across fallible work")
+ .remove(&prefix);
+ debug_assert!(removed, "every dirty-tracking guard owns one active lease");
+ let previous = self.active_count.fetch_sub(1, Ordering::Release);
+ debug_assert!(previous > 0, "dirty-tracking reference count underflow");
+ }
+}
+
+/// In-memory lease enabling per-person dirty capture for one active reconcile cohort.
+///
+/// The lease is owned by the queued job. Dropping the job on completion, supersession, rebalance,
+/// or shutdown disables future capture. Already-written markers are safe for GC to reclaim because
+/// a replayed job starts from a full cohort scan.
+#[must_use]
+#[derive(Debug)]
+pub struct Stage2DirtyTrackingGuard {
+ tracking: Arc<Stage2DirtyTracking>,
+ prefix: Stage2CohortPrefix,
+}
+
+impl Drop for Stage2DirtyTrackingGuard {
+ fn drop(&mut self) {
+ self.tracking.release(self.prefix);
+ }
+}
+
/// Handle to the per-process state store.
///
/// Writes have two layers. The closure-based [`Self::write_batch`] is for synchronous callers that
@@ -191,6 +284,7 @@ pub struct CohortStore {
db_opts: Arc<Options>,
/// See [`StoreConfig::read_sample_ratio`]; `>= 1`.
read_sample_ratio: u32,
+ dirty_tracking: Arc<Stage2DirtyTracking>,
}
impl CohortStore {
@@ -265,6 +359,7 @@ impl CohortStore {
db_opts: Arc::new(db_opts.clone()),
// Floor at 1: `next % ratio` must not divide by zero.
read_sample_ratio: config.read_sample_ratio.max(1),
+ dirty_tracking: Arc::new(Stage2DirtyTracking::default()),
})
}
@@ -434,6 +529,22 @@ impl CohortStore {
self.get(Cf::Stage2, &key.encode())
}
+ /// Enable coalescing dirty-person capture for one active reconcile cohort until the returned
+ /// lease is dropped. This is process-local by design: a crash replays the held reconcile tile
+ /// and starts a fresh full scan, so correctness never depends on preserving an inactive marker.
+ pub fn track_stage2_dirty(&self, prefix: Stage2CohortPrefix) -> Stage2DirtyTrackingGuard {
+ self.dirty_tracking.acquire(prefix)
+ }
+
+ /// Whether this process currently owns a reconcile scan for `prefix`.
+ ///
+ /// Stage 2 GC uses this to distinguish live dirty work from metadata left by a completed,
+ /// discarded, or rebalanced job. Partition-worker serialization prevents a lease transition
+ /// from racing the corresponding GC tick.
+ pub(crate) fn is_stage2_dirty_tracking_active(&self, prefix: Stage2CohortPrefix) -> bool {
+ self.dirty_tracking.is_active(prefix)
+ }
+
pub fn get_stage2_transferred_register(
&self,
key: &Stage2TransferredRegisterKey,
@@ -497,6 +608,116 @@ impl CohortStore {
.collect()
}
+ /// Scan up to `limit` keys in one partition/team/cohort slice of `cf_stage2`, in person order,
+ /// resuming strictly after `start_after` when it decodes as a key in that slice.
+ ///
+ /// Corrupt keys are counted and skipped. The scan continues until it collects `limit` valid
+ /// keys or exhausts the prefix, so a short result proves there are no later decodable rows.
+ pub fn scan_stage2_cohort(
+ &self,
+ prefix: Stage2CohortPrefix,
+ start_after: Option<&[u8]>,
+ limit: usize,
+ ) -> Result<Vec<Stage2Key>, StoreError> {
+ if limit == 0 {
+ return Ok(Vec::new());
+ }
+
+ let (prefix_start, prefix_end) = prefix.range();
+ let begin = match start_after {
+ Some(cursor)
+ if cursor >= prefix_start.as_slice()
+ && cursor < prefix_end.as_slice()
+ && Stage2Key::decode(cursor).is_ok() =>
+ {
+ successor(cursor)
+ }
+ _ => prefix_start,
+ };
+ let handle = self.cf(Cf::Stage2)?;
+
+ let mut read_opts = ReadOptions::default();
+ read_opts.set_iterate_upper_bound(prefix_end);
+ let iter = self.db.iterator_cf_opt(
+ handle,
+ read_opts,
+ IteratorMode::From(&begin, Direction::Forward),
+ );
+ let mut out = Vec::with_capacity(limit.min(1024));
+ for item in iter {
+ if out.len() == limit {
+ break;
+ }
+ let (key_bytes, _value) = item.map_err(|source| {
+ counter!(STORE_ERRORS_TOTAL, "op" => OP_SCAN).increment(1);
+ StoreError::Backend {
+ op: OP_SCAN,
+ source,
+ }
+ })?;
+ if Stage2DirtyKey::decode(&key_bytes).is_ok()
+ || Stage2TransferredRegisterKey::decode(&key_bytes).is_ok()
+ {
+ // Metadata is the partition tail, so no Stage 2 row can follow it. This is reachable
+ // only for the all-ones row prefix; ordinary cohort ranges end earlier.
+ break;
+ }
+ match Stage2Key::decode(&key_bytes) {
+ Ok(key) => out.push(key),
+ Err(_) => counter!(STAGE2_SCAN_UNDECODABLE_KEYS_TOTAL).increment(1),
+ }
+ }
+ Ok(out)
+ }
+
+ /// Scan up to `limit` dirty-person markers for one Stage 2 cohort, resuming strictly after a
+ /// marker in that same prefix. A malformed key inside the reserved namespace is an error: the
+ /// reconciler must stop rather than mistake corruption for an empty dirty set.
+ pub fn scan_stage2_dirty(
+ &self,
+ prefix: Stage2CohortPrefix,
+ start_after: Option<&[u8]>,
+ limit: usize,
+ ) -> Result<Vec<Stage2DirtyKey>, StoreError> {
+ if limit == 0 {
+ return Ok(Vec::new());
+ }
+
+ let dirty_prefix = prefix.dirty_prefix();
+ let (prefix_start, prefix_end) = dirty_prefix.range();
+ let begin = match start_after {
+ Some(cursor)
+ if cursor >= prefix_start.as_slice()
+ && cursor < prefix_end.as_slice()
+ && Stage2DirtyKey::decode(cursor).is_ok() =>
+ {
+ successor(cursor)
+ }
+ _ => prefix_start,
+ };
+ let handle = self.cf(Cf::Stage2)?;
+ let mut read_opts = ReadOptions::default();
+ read_opts.set_iterate_upper_bound(prefix_end);
+ let iter = self.db.iterator_cf_opt(
+ handle,
+ read_opts,
+ IteratorMode::From(&begin, Direction::Forward),
+ );
+
+ let mut out = Vec::with_capacity(limit.min(1024));
+ for item in iter.take(limit) {
+ let (key_bytes, _value) = item.map_err(|source| {
+ counter!(STORE_ERRORS_TOTAL, "op" => OP_SCAN).increment(1);
+ StoreError::Backend {
+ op: OP_SCAN,
+ source,
+ }
+ })?;
+ out.push(Stage2DirtyKey::decode(&key_bytes)?);
+ }
+ Ok(out)
+ }
+
/// Scan the catalog-independent transferred-register inventory for one person.
pub fn scan_stage2_transferred_registers(
&self,
@@ -544,6 +765,7 @@ impl CohortStore {
merge_applied: self.cf(Cf::MergeApplied)?,
merge_tombstones: self.cf(Cf::MergeTombstones)?,
meta: self.cf(Cf::Meta)?,
+ dirty_tracking: &self.dirty_tracking,
};
build(&mut builder);
self.commit(builder.batch, OP_WRITE_BATCH)
@@ -560,15 +782,38 @@ impl CohortStore {
match op {
StagedOp::Put { cf, key, value } => {
batch.put_cf(self.cf(*cf)?, key, value);
+ self.mark_staged_stage2_dirty(&mut batch, *cf, key);
}
StagedOp::Delete { cf, key } => {
batch.delete_cf(self.cf(*cf)?, key);
+ self.mark_staged_stage2_dirty(&mut batch, *cf, key);
}
}
}
self.commit(batch, OP_WRITE_BATCH)
}
+ fn mark_staged_stage2_dirty(&self, batch: &mut WriteBatch, cf: Cf, encoded_key: &[u8]) {
+ if !matches!(cf, Cf::Stage2) {
+ return;
+ }
+ // Skip decoding the key on the hot write path when no reconcile drain is capturing dirties.
+ if !self.dirty_tracking.any_active() {
+ return;
+ }
+ let Ok(key) = Stage2Key::decode(encoded_key) else {
+ return;
+ };
+ if let Some(marker) = self.dirty_tracking.dirty_marker(&key) {
+ batch.put_cf(
+ self.cf(Cf::Stage2)
+ .expect("the Stage 2 CF was opened before applying a batch"),
+ marker,
+ [],
+ );
+ }
+ }
+
pub fn get_merge_drain_applied(
&self,
key: &MergeDrainKey,
@@ -975,6 +1220,7 @@ pub struct BatchBuilder<'db> {
merge_applied: &'db ColumnFamily,
merge_tombstones: &'db ColumnFamily,
meta: &'db ColumnFamily,
+ dirty_tracking: &'db Stage2DirtyTracking,
}
impl<'db> BatchBuilder<'db> {
@@ -1016,10 +1262,17 @@ impl<'db> BatchBuilder<'db> {
pub fn put_stage2(&mut self, key: &Stage2Key, value: &[u8]) {
self.batch.put_cf(self.stage2, key.encode(), value);
+ self.mark_stage2_dirty(key);
}
pub fn delete_stage2(&mut self, key: &Stage2Key) {
self.batch.delete_cf(self.stage2, key.encode());
+ self.mark_stage2_dirty(key);
+ }
+
+ /// Clear a reconcile dirty marker without creating another marker.
+ pub fn delete_stage2_dirty(&mut self, key: &Stage2DirtyKey) {
+ self.batch.delete_cf(self.stage2, key.encode());
}
/// Preserve a merge-carried register independently of the receiver's current catalog.
@@ -1082,6 +1335,17 @@ impl<'db> BatchBuilder<'db> {
/// Raw put by pre-encoded key bytes. Restricted to [`OpaqueCf`].
pub fn put_raw(&mut self, cf: OpaqueCf, key: &[u8], value: &[u8]) {
self.batch.put_cf(self.handle(cf.cf()), key, value);
+ if matches!(cf, OpaqueCf::Stage2) {
+ if let Ok(key) = Stage2Key::decode(key) {
+ self.mark_stage2_dirty(&key);
+ }
+ }
+ }
+
+ fn mark_stage2_dirty(&mut self, key: &Stage2Key) {
+ if let Some(marker) = self.dirty_tracking.dirty_marker(key) {
+ self.batch.put_cf(self.stage2, marker, []);
+ }
}
}
@@ -1511,6 +1775,163 @@ mod tests {
);
}
+ #[test]
+ fn stage2_mutations_atomically_coalesce_one_dirty_marker_per_person() {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ let key = |person_id: u128, cohort_id: u64| Stage2Key {
+ partition_id: 3,
+ team_id: 7,
+ cohort_id,
+ person_id: Uuid::from_u128(person_id),
+ };
+ let watched = key(1, 100);
+ let prefix = watched.cohort_prefix();
+ let _tracking = store.track_stage2_dirty(prefix);
+ assert!(store
+ .scan_stage2_dirty(prefix, None, 10)
+ .unwrap()
+ .is_empty());
+
+ store
+ .write_batch(|batch| {
+ batch.put_stage2(&watched, b"member");
+ batch.put_stage2(&watched, b"member-again");
+ batch.put_stage2(&key(2, 100), b"second person");
+ batch.put_stage2(&key(1, 101), b"other cohort");
+ })
+ .unwrap();
+ assert_eq!(
+ store
+ .scan_stage2_dirty(prefix, None, 10)
+ .unwrap()
+ .into_iter()
+ .map(Stage2DirtyKey::stage2_key)
+ .collect::<Vec<_>>(),
+ vec![watched, key(2, 100)],
+ "repeated writes coalesce and another cohort stays outside the prefix",
+ );
+
+ let mut staged = StagedBatch::default();
+ staged.delete_stage2(&watched);
+ store.apply(&staged).unwrap();
+ assert!(store.get_stage2(&watched).unwrap().is_none());
+ assert_eq!(
+ store.scan_stage2_dirty(prefix, None, 10).unwrap().len(),
+ 2,
+ "a delete retains the coalesced marker even though the row is gone",
+ );
+
+ store
+ .write_batch(|batch| {
+ batch.delete_stage2_dirty(&Stage2DirtyKey::new(watched));
+ batch.delete_stage2_dirty(&Stage2DirtyKey::new(key(2, 100)));
+ })
+ .unwrap();
+ assert!(store
+ .scan_stage2_dirty(prefix, None, 10)
+ .unwrap()
+ .is_empty());
+ }
+
+ #[test]
+ fn stage2_dirty_capture_is_scoped_to_the_tracking_lease() {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ let key = Stage2Key {
+ partition_id: 3,
+ team_id: 7,
+ cohort_id: 100,
+ person_id: Uuid::from_u128(1),
+ };
+ let prefix = key.cohort_prefix();
+
+ store
+ .write_batch(|batch| batch.put_stage2(&key, b"before"))
+ .unwrap();
+ assert!(store
+ .scan_stage2_dirty(prefix, None, 10)
+ .unwrap()
+ .is_empty());
+
+ let tracking = store.track_stage2_dirty(prefix);
+ let mut staged = StagedBatch::default();
+ staged.put_stage2(&key, b"during");
+ store.apply(&staged).unwrap();
+ assert_eq!(store.scan_stage2_dirty(prefix, None, 10).unwrap().len(), 1);
+ store
+ .write_batch(|batch| batch.delete_stage2_dirty(&Stage2DirtyKey::new(key)))
+ .unwrap();
+ drop(tracking);
+
+ store
+ .write_batch(|batch| batch.put_stage2(&key, b"after"))
+ .unwrap();
+ assert!(
+ store
+ .scan_stage2_dirty(prefix, None, 10)
+ .unwrap()
+ .is_empty(),
+ "idle Stage 2 writes do not accumulate permanent dirty metadata",
+ );
+ }
+
+ #[test]
+ fn scan_stage2_dirty_is_bounded_and_resumable() {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ let key = |person_id: u128| Stage2Key {
+ partition_id: 3,
+ team_id: 7,
+ cohort_id: 100,
+ person_id: Uuid::from_u128(person_id),
+ };
+ let prefix = key(1).cohort_prefix();
+ let _tracking = store.track_stage2_dirty(prefix);
+ store
+ .write_batch(|batch| {
+ for person_id in 1..=4 {
+ batch.put_stage2(&key(person_id), b"member");
+ }
+ })
+ .unwrap();
+
+ let first = store.scan_stage2_dirty(prefix, None, 2).unwrap();
+ assert_eq!(
+ first
+ .iter()
+ .map(|dirty| dirty.stage2_key().person_id)
+ .collect::<Vec<_>>(),
+ vec![Uuid::from_u128(1), Uuid::from_u128(2)],
+ );
+ let cursor = first.last().unwrap().encode();
+ let second = store.scan_stage2_dirty(prefix, Some(&cursor), 2).unwrap();
+ assert_eq!(
+ second
+ .iter()
+ .map(|dirty| dirty.stage2_key().person_id)
+ .collect::<Vec<_>>(),
+ vec![Uuid::from_u128(3), Uuid::from_u128(4)],
+ );
+ let cursor = second.last().unwrap().encode();
+ assert!(store
+ .scan_stage2_dirty(prefix, Some(&cursor), 2)
+ .unwrap()
+ .is_empty());
+ }
+
#[test]
fn transferred_register_inventory_scans_one_person_in_cohort_order() {
let dir = TempDir::new().unwrap();
@@ -1555,6 +1976,132 @@ mod tests {
);
}
+ #[test]
+ fn scan_stage2_cohort_is_bounded_resumable_and_skips_corrupt_keys() {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ let prefix = Stage2CohortPrefix {
+ partition_id: 3,
+ team_id: 7,
+ cohort_id: 100,
+ };
+ let key = |partition_id: u16, team_id: u64, cohort_id: u64, person: u128| Stage2Key {
+ partition_id,
+ team_id,
+ cohort_id,
+ person_id: Uuid::from_u128(person),
+ };
+
+ store
+ .write_batch(|batch| {
+ for person in 1..=4 {
+ batch.put_stage2(&key(3, 7, 100, person), b"member");
+ }
+ batch.put_stage2(&key(3, 7, 101, 1), b"other-cohort");
+ batch.put_stage2(&key(3, 8, 100, 1), b"other-team");
+ batch.put_stage2(&key(4, 7, 100, 1), b"other-partition");
+ })
+ .unwrap();
+
+ // This malformed key is inside the prefix range and sorts before person 1. It must not
+ // consume the valid-key page limit or make the scan fail.
+ let mut malformed = prefix.encode().to_vec();
+ malformed.extend_from_slice(&[0; 15]);
+ store
+ .db
+ .put_cf(store.cf(Cf::Stage2).unwrap(), malformed, b"corrupt-prefix")
+ .unwrap();
+ let mut malformed_tail = prefix.encode().to_vec();
+ malformed_tail.extend_from_slice(Uuid::from_u128(5).as_bytes());
+ malformed_tail.push(0);
+ store
+ .db
+ .put_cf(
+ store.cf(Cf::Stage2).unwrap(),
+ &malformed_tail,
+ b"corrupt-tail",
+ )
+ .unwrap();
+
+ let first = store.scan_stage2_cohort(prefix, None, 2).unwrap();
+ assert_eq!(
+ first.iter().map(|key| key.person_id).collect::<Vec<_>>(),
+ vec![Uuid::from_u128(1), Uuid::from_u128(2)],
+ );
+
+ let cursor = first.last().unwrap().encode().to_vec();
+ let second = store.scan_stage2_cohort(prefix, Some(&cursor), 2).unwrap();
+ assert_eq!(
+ second.iter().map(|key| key.person_id).collect::<Vec<_>>(),
+ vec![Uuid::from_u128(3), Uuid::from_u128(4)],
+ );
+
+ let last = second.last().unwrap().encode().to_vec();
+ assert!(
+ store
+ .scan_stage2_cohort(prefix, Some(&last), 10)
+ .unwrap()
+ .is_empty(),
+ "the cohort prefix is exhausted after person 4",
+ );
+
+ assert_eq!(
+ store
+ .scan_stage2_cohort(prefix, Some(&malformed_tail), 10)
+ .unwrap()
+ .len(),
+ 4,
+ "an in-prefix cursor must decode before it can skip rows",
+ );
+
+ let foreign_cursor = key(3, 7, 101, 1).encode();
+ assert_eq!(
+ store
+ .scan_stage2_cohort(prefix, Some(&foreign_cursor), 10)
+ .unwrap()
+ .len(),
+ 4,
+ "an out-of-prefix cursor starts a fresh scan",
+ );
+ assert!(store
+ .scan_stage2_cohort(prefix, None, 0)
+ .unwrap()
+ .is_empty());
+ }
+
+ #[test]
+ fn scan_stage2_cohort_includes_the_all_ones_key() {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ let prefix = Stage2CohortPrefix {
+ partition_id: u16::MAX,
+ team_id: u64::MAX,
+ cohort_id: u64::MAX,
+ };
+ let key = Stage2Key {
+ partition_id: u16::MAX,
+ team_id: u64::MAX,
+ cohort_id: u64::MAX,
+ person_id: Uuid::from_u128(u128::MAX),
+ };
+ store
+ .write_batch(|batch| batch.put_stage2(&key, b"max"))
+ .unwrap();
+
+ assert_eq!(
+ store.scan_stage2_cohort(prefix, None, 1).unwrap(),
+ vec![key]
+ );
+ }
+
#[test]
fn scan_merge_cf_resumes_after_the_cursor_and_honors_the_limit_and_partition_bounds() {
let dir = TempDir::new().unwrap();
diff --git a/rust/cohort-stream-processor/src/store/staged.rs b/rust/cohort-stream-processor/src/store/staged.rs
index e6ef21a39bc3..6a7b0beae4dd 100644
--- a/rust/cohort-stream-processor/src/store/staged.rs
+++ b/rust/cohort-stream-processor/src/store/staged.rs
@@ -12,8 +12,8 @@
use super::column_families::{Cf, OpaqueCf};
use super::keys::{
- MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage2Key, Stage2TransferredRegisterKey,
- TombstoneKey,
+ MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage2DirtyKey, Stage2Key,
+ Stage2TransferredRegisterKey, TombstoneKey,
};
use super::keyspace::Keyspace;
@@ -88,6 +88,14 @@ impl StagedBatch {
});
}
+ /// Clear a reconcile dirty marker without creating another marker.
+ pub fn delete_stage2_dirty(&mut self, key: &Stage2DirtyKey) {
+ self.ops.push(StagedOp::Delete {
+ cf: Cf::Stage2,
+ key: key.encode().to_vec(),
+ });
+ }
+
pub fn put_stage2_transferred_register(
&mut self,
key: &Stage2TransferredRegisterKey,
@@ -198,6 +206,7 @@ mod tests {
use crate::stage1::key::LeafStateKey;
use crate::store::keyspace::{Behavioral, BehavioralKey};
use crate::store::rocks::{BatchBuilder, CohortStore, StoreConfig};
+ use crate::store::Stage2DirtyKey;
const PARTITION: u16 = 3;
const TEAM: u64 = 7;
@@ -345,6 +354,8 @@ mod tests {
let dir = TempDir::new().unwrap();
let via_builder = open_store(&dir, "builder");
let via_staged = open_store(&dir, "staged");
+ let _builder_tracking = via_builder.track_stage2_dirty(stage2_key(1, 100).cohort_prefix());
+ let _staged_tracking = via_staged.track_stage2_dirty(stage2_key(1, 100).cohort_prefix());
via_builder.write_batch(drive_batch_builder).unwrap();
@@ -384,6 +395,13 @@ mod tests {
via_staged.get_behavioral(&behavioral_key(2, 0xA1)).unwrap(),
None,
);
+ assert!(via_staged
+ .get(
+ Cf::Stage2,
+ &Stage2DirtyKey::new(stage2_key(1, 100)).encode()
+ )
+ .unwrap()
+ .is_some());
}
#[test]
diff --git a/rust/cohort-stream-processor/src/sweep/mod.rs b/rust/cohort-stream-processor/src/sweep/mod.rs
index 5bdf8b4bfab6..524e42509199 100644
--- a/rust/cohort-stream-processor/src/sweep/mod.rs
+++ b/rust/cohort-stream-processor/src/sweep/mod.rs
@@ -11,8 +11,10 @@
pub mod dispatch;
pub mod eviction_queue;
+pub mod reconcile;
pub mod scheduler;
pub use dispatch::DispatchSweeper;
pub use eviction_queue::EvictionQueue;
+pub use reconcile::ReconcileDrainSweeper;
pub use scheduler::{due_before_ms, run_sweep_loop, run_sweep_loop_delayed, Sweeper};
diff --git a/rust/cohort-stream-processor/src/sweep/reconcile.rs b/rust/cohort-stream-processor/src/sweep/reconcile.rs
new file mode 100644
index 000000000000..7cd3e1f1c89b
--- /dev/null
+++ b/rust/cohort-stream-processor/src/sweep/reconcile.rs
@@ -0,0 +1,113 @@
+//! Periodic bounded-progress ticks for admitted reconcile snapshots.
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+
+use crate::consumers::events::EventDispatcher;
+use crate::sweep::Sweeper;
+use crate::workers::ReconcileBacklog;
+
+/// Routes one reconcile page to each active partition only while this pod owns queued work.
+pub struct ReconcileDrainSweeper {
+ dispatcher: Arc<EventDispatcher>,
+ backlog: Arc<ReconcileBacklog>,
+}
+
+impl ReconcileDrainSweeper {
+ pub fn new(dispatcher: Arc<EventDispatcher>, backlog: Arc<ReconcileBacklog>) -> Self {
+ Self {
+ dispatcher,
+ backlog,
+ }
+ }
+
+ fn has_work(&self) -> bool {
+ !self.backlog.is_empty()
+ }
+}
+
+#[async_trait]
+impl Sweeper for ReconcileDrainSweeper {
+ async fn run_once(&self) {
+ if !self.has_work() {
+ return;
+ }
+ // B6's live-lag pause belongs here, before fan-out, so admitted jobs keep their deferred
+ // offsets while maintenance reads are paused without waking every partition worker.
+ self.dispatcher.route_reconcile_drain().await;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use tempfile::TempDir;
+ use uuid::Uuid;
+
+ use cohort_core::filters::{CohortId, TeamId};
+ use cohort_core::seed::{BehavioralShapeHash, ReconcileTile, RunId};
+
+ use crate::filters::{CatalogHandle, FilterCatalog};
+ use crate::partitions::{OffsetTracker, PartitionRouter};
+ use crate::producer::{CaptureSink, MembershipSink};
+ use crate::store::{CohortStore, OffloadConfig, OffloadMode, StoreConfig, StoreHandle};
+ use crate::workers::reconcile::ReconcileQueue;
+ use crate::workers::MergeWorkerDeps;
+
+ use super::*;
+
+ fn dispatcher() -> (TempDir, Arc<EventDispatcher>, StoreHandle) {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ let handle = StoreHandle::new(
+ store,
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ );
+ let catalog = Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([])));
+ let sink: Arc<dyn MembershipSink> = Arc::new(CaptureSink::new());
+ let dispatcher = EventDispatcher::new(
+ PartitionRouter::new(64),
+ Arc::new(OffsetTracker::new()),
+ handle.clone(),
+ catalog,
+ sink,
+ MergeWorkerDeps::capture(),
+ );
+ (dir, Arc::new(dispatcher), handle)
+ }
+
+ #[tokio::test]
+ async fn idle_short_circuit_arms_only_while_a_job_is_owned() {
+ let (_dir, dispatcher, handle) = dispatcher();
+ let backlog = Arc::new(ReconcileBacklog::default());
+ let sweeper = ReconcileDrainSweeper::new(dispatcher, backlog.clone());
+ assert!(!sweeper.has_work());
+ sweeper.run_once().await;
+
+ let tracker = OffsetTracker::new();
+ tracker.mark_dispatched(0, 6);
+ let mut queue = ReconcileQueue::new(0, backlog, handle);
+ queue.enqueue(
+ ReconcileTile::new(
+ TeamId(7),
+ CohortId(1),
+ BehavioralShapeHash::parse("shape-v1").unwrap(),
+ RunId(Uuid::nil()),
+ ),
+ tracker.defer(0, 5),
+ );
+
+ assert!(sweeper.has_work());
+ sweeper.run_once().await;
+ drop(queue);
+ assert!(!sweeper.has_work());
+ }
+}
diff --git a/rust/cohort-stream-processor/src/sweep/scheduler.rs b/rust/cohort-stream-processor/src/sweep/scheduler.rs
index 27592919457c..677c4adf2953 100644
--- a/rust/cohort-stream-processor/src/sweep/scheduler.rs
+++ b/rust/cohort-stream-processor/src/sweep/scheduler.rs
@@ -36,8 +36,9 @@ pub fn due_before_ms(now_ms: i64, safety_margin_ms: i64) -> i64 {
/// Drive the periodic sweep until `cancel` fires, invoking `sweeper.run_once()` once per tick and
/// recording [`SWEEP_CYCLES_TOTAL`] + [`SWEEP_CYCLE_DURATION_SECONDS`], both labelled by `loop_name`.
///
-/// `loop_name` (`eviction`|`redrive`|`merge_gc`|`checkpoint`|`store_stats`) labels the cycle metrics
-/// so the concurrent loops — same timer machinery, different cadences — stay distinguishable.
+/// `loop_name` (`eviction`|`redrive`|`merge_gc`|`reconcile`|`checkpoint`|`store_stats`) labels the
+/// cycle metrics so the concurrent loops — same timer machinery, different cadences — stay
+/// distinguishable.
///
/// - **`MissedTickBehavior::Skip`**: if a sweep runs long or the task is starved, the timer drops the
/// ticks it slept through rather than firing a catch-up burst — one sweep then resumes on the
diff --git a/rust/cohort-stream-processor/src/workers/cascade_path.rs b/rust/cohort-stream-processor/src/workers/cascade_path.rs
index 0277b7418df3..288c206aeebc 100644
--- a/rust/cohort-stream-processor/src/workers/cascade_path.rs
+++ b/rust/cohort-stream-processor/src/workers/cascade_path.rs
@@ -447,6 +447,7 @@ mod tests {
seed_tracker: Arc::new(crate::partitions::offset_tracker::OffsetTracker::new()),
live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),
register_transfer_enabled: false,
+ reconcile: crate::workers::ReconcileDeps::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 caddbaf4e9b8..0d3476f89e30 100644
--- a/rust/cohort-stream-processor/src/workers/merge_path.rs
+++ b/rust/cohort-stream-processor/src/workers/merge_path.rs
@@ -41,6 +41,7 @@ use crate::workers::stage2_path::compose_stage2;
use crate::workers::worker::{
affected_leaves, first_cascades, produce_cascades, produce_membership, transition_metric_label,
};
+use crate::workers::ReconcileDeps;
/// Inline bounded backoff for the transfer produce.
///
@@ -133,6 +134,8 @@ pub struct MergeWorkerDeps {
/// `false` until every pod in the fleet can apply the transfer; while off the drain ships leaves
/// only and never holds. Wired from `COHORT_REGISTER_TRANSFER_ENABLED`.
pub register_transfer_enabled: bool,
+ /// Reconcile admission and the pod-wide scheduler wake-up count.
+ pub reconcile: ReconcileDeps,
}
impl MergeWorkerDeps {
@@ -153,6 +156,7 @@ impl MergeWorkerDeps {
seed_tracker: Arc::new(OffsetTracker::new()),
live_watermarks: Arc::new(LiveWatermarks::new()),
register_transfer_enabled: false,
+ reconcile: ReconcileDeps::default(),
})
}
}
@@ -904,6 +908,7 @@ mod tests {
seed_tracker: Arc::new(crate::partitions::offset_tracker::OffsetTracker::new()),
live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),
register_transfer_enabled: false,
+ reconcile: ReconcileDeps::default(),
}
}
diff --git a/rust/cohort-stream-processor/src/workers/mod.rs b/rust/cohort-stream-processor/src/workers/mod.rs
index c44e92013b05..c6ed2522655c 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 reconcile;
pub mod seed_path;
pub mod stage2_gc;
pub mod stage2_path;
@@ -17,6 +18,7 @@ pub use merge_gc::{handle_merge_gc, MergeGcCursor};
pub use merge_path::{
CascadeConfig, MergeWorkerDeps, TransferRetryPolicy, DEFAULT_MERGE_GC_SCAN_LIMIT,
};
+pub use reconcile::{ReconcileBacklog, ReconcileDeps, DEFAULT_RECONCILE_SCAN_PAGE};
pub use stage2_gc::{handle_stage2_orphan_gc, Stage2GcCursor};
pub use stage2_path::compose_stage2;
pub use worker::Stage1Worker;
diff --git a/rust/cohort-stream-processor/src/workers/reconcile.rs b/rust/cohort-stream-processor/src/workers/reconcile.rs
new file mode 100644
index 000000000000..e1d403115886
--- /dev/null
+++ b/rust/cohort-stream-processor/src/workers/reconcile.rs
@@ -0,0 +1,1894 @@
+//! In-memory reconcile work admitted by the seed consumer.
+//!
+//! The queue belongs to one partition worker. Its deferred offsets deliberately die with the
+//! worker without completing; partition teardown then forgets the tracker tenure so Kafka replays
+//! every unfinished reconcile from the beginning.
+
+use std::collections::VecDeque;
+use std::sync::atomic::{AtomicI64, Ordering};
+use std::sync::Arc;
+
+use metrics::{counter, gauge};
+use tracing::{debug, info, warn};
+
+use cohort_core::clickhouse_timestamp_to_millis;
+use cohort_core::filters::{CohortId, TeamId};
+use cohort_core::seed::ReconcileTile;
+#[cfg(test)]
+use cohort_core::seed::RunId;
+
+use crate::filters::manager::CatalogHandle;
+use crate::filters::reverse_index::TeamFilters;
+use crate::observability::metrics::{
+ COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH, RECONCILE_BITS_FIXED_TOTAL,
+ RECONCILE_JOBS_COMPLETED_TOTAL, RECONCILE_JOBS_DISCARDED_TOTAL,
+ RECONCILE_MARKERS_EMITTED_TOTAL, RECONCILE_QUEUE_DEPTH, RECONCILE_ROWS_EMITTED_TOTAL,
+ RECONCILE_ROWS_SCANNED_TOTAL,
+};
+use crate::partitions::offset_tracker::{DeferredOffset, MarkOutcome, OffsetTracker};
+use crate::producer::{
+ ChangeOrigin, CohortMembershipChange, MembershipSink, ReconcileCompleteMarker,
+};
+use crate::stage2::Stage2State;
+use crate::store::{
+ ReadLane, Stage2CohortPrefix, Stage2DirtyKey, Stage2Key, StagedBatch, StoreHandle,
+};
+use crate::workers::merge_path::MergeWorkerDeps;
+use crate::workers::stage2_path::recompute_and_diff;
+use crate::workers::worker::{
+ count_by_status, first_cascades, produce_cascades, produce_membership,
+};
+
+/// Emit a `warn!` carrying the reconcile job identity (`team_id`, `cohort_id`, `run_id`) read from
+/// `$tile`, so the drain warnings share one definition of those fields. Extra fields and the message
+/// follow exactly as in a bare `warn!`: `warn_job!(tile, partition_id, error = %error, "…")`.
+macro_rules! warn_job {
+ ($tile:expr, $($rest:tt)*) => {
+ warn!(
+ team_id = $tile.team_id().0,
+ cohort_id = $tile.cohort_id().0,
+ run_id = %$tile.run_id().0,
+ $($rest)*
+ )
+ };
+}
+
+/// Default number of Stage 2 rows one reconcile drain tick may scan.
+pub const DEFAULT_RECONCILE_SCAN_PAGE: usize = 256;
+
+/// Pod-wide count of admitted jobs still owned by partition queues.
+#[derive(Debug, Default)]
+pub struct ReconcileBacklog(AtomicI64);
+
+impl ReconcileBacklog {
+ pub fn len(&self) -> i64 {
+ self.0.load(Ordering::Relaxed)
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+
+ fn add(&self) {
+ self.0.fetch_add(1, Ordering::Relaxed);
+ }
+
+ fn done(&self, count: usize) {
+ let count = i64::try_from(count).expect("an in-memory queue cannot exceed i64::MAX jobs");
+ let updated = self
+ .0
+ .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
+ current.checked_sub(count).filter(|next| *next >= 0)
+ });
+ debug_assert!(updated.is_ok(), "reconcile backlog ownership underflow");
+ }
+}
+
+/// Runtime dependencies shared by every partition's reconcile queue.
+#[derive(Debug, Clone)]
+pub struct ReconcileDeps {
+ pub enabled: bool,
+ pub scan_page: usize,
+ pub backlog: Arc<ReconcileBacklog>,
+}
+
+impl Default for ReconcileDeps {
+ fn default() -> Self {
+ Self {
+ enabled: false,
+ scan_page: DEFAULT_RECONCILE_SCAN_PAGE,
+ backlog: Arc::new(ReconcileBacklog::default()),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum ScanPhase {
+ Scanning { cursor: Option<Vec<u8>> },
+ DrainingDirty { cursor: Option<Vec<u8>> },
+ MarkerReady,
+}
+
+#[derive(Debug)]
+struct ReconcileJob {
+ tile: ReconcileTile,
+ offset: DeferredOffset,
+ dirty_tracking: Option<crate::store::Stage2DirtyTrackingGuard>,
+ phase: ScanPhase,
+ rows_scanned: u64,
+ bits_fixed: u64,
+}
+
+pub(crate) enum SupersedeOutcome {
+ NoQueuedJob,
+ Replaced(DeferredOffset),
+ RetainedNewerOrEqual,
+}
+
+/// FIFO reconcile work for one partition worker.
+pub(crate) struct ReconcileQueue {
+ jobs: VecDeque<ReconcileJob>,
+ backlog: Arc<ReconcileBacklog>,
+ partition_label: Arc<str>,
+ handle: StoreHandle,
+}
+
+impl ReconcileQueue {
+ pub(crate) fn new(
+ partition_id: u16,
+ backlog: Arc<ReconcileBacklog>,
+ handle: StoreHandle,
+ ) -> Self {
+ let queue = Self {
+ jobs: VecDeque::new(),
+ backlog,
+ partition_label: Arc::from(partition_id.to_string()),
+ handle,
+ };
+ queue.record_depth();
+ queue
+ }
+
+ pub(crate) fn enqueue(&mut self, tile: ReconcileTile, offset: DeferredOffset) {
+ self.jobs.push_back(ReconcileJob {
+ tile,
+ offset,
+ dirty_tracking: None,
+ phase: ScanPhase::Scanning { cursor: None },
+ rows_scanned: 0,
+ bits_fixed: 0,
+ });
+ self.backlog.add();
+ self.record_depth();
+ }
+
+ /// Start dirty capture only for the queue head, immediately before its first scan. Mutations
+ /// while a job waits behind another snapshot are covered by its future full scan and need no
+ /// per-person metadata.
+ fn activate_front_tracking(&mut self, prefix: Stage2CohortPrefix) {
+ if self
+ .jobs
+ .front()
+ .is_some_and(|job| job.dirty_tracking.is_none())
+ {
+ let tracking = self.handle.track_stage2_dirty(prefix);
+ self.jobs
+ .front_mut()
+ .expect("the queue head was present before acquiring its tracking lease")
+ .dirty_tracking = Some(tracking);
+ }
+ }
+
+ /// Replace a queued job only when the incoming Kafka offset is newer. A follower rewind may
+ /// replay an older job while a newer run is still queued; that replay must never evict the newer
+ /// snapshot.
+ pub(crate) fn supersede_if_newer(
+ &mut self,
+ team_id: TeamId,
+ cohort_id: CohortId,
+ incoming_offset: i64,
+ ) -> SupersedeOutcome {
+ let Some(position) = self
+ .jobs
+ .iter()
+ .position(|job| job.tile.team_id() == team_id && job.tile.cohort_id() == cohort_id)
+ else {
+ return SupersedeOutcome::NoQueuedJob;
+ };
+ if incoming_offset <= self.jobs[position].offset.offset() {
+ return SupersedeOutcome::RetainedNewerOrEqual;
+ }
+ let job = self
+ .jobs
+ .remove(position)
+ .expect("position came from the same queue");
+ self.backlog.done(1);
+ self.record_depth();
+ SupersedeOutcome::Replaced(job.offset)
+ }
+
+ fn front(&self) -> Option<&ReconcileJob> {
+ self.jobs.front()
+ }
+
+ fn front_mut(&mut self) -> Option<&mut ReconcileJob> {
+ self.jobs.front_mut()
+ }
+
+ fn finish_front(&mut self) -> Option<ReconcileJob> {
+ let job = self.jobs.pop_front()?;
+ self.backlog.done(1);
+ self.record_depth();
+ Some(job)
+ }
+
+ fn record_depth(&self) {
+ gauge!(RECONCILE_QUEUE_DEPTH, "partition" => self.partition_label.clone())
+ .set(self.jobs.len() as f64);
+ }
+
+ #[cfg(test)]
+ pub(crate) fn len(&self) -> usize {
+ self.jobs.len()
+ }
+
+ #[cfg(test)]
+ pub(crate) fn front_run_id(&self) -> Option<RunId> {
+ self.jobs.front().map(|job| job.tile.run_id())
+ }
+}
+
+impl Drop for ReconcileQueue {
+ fn drop(&mut self) {
+ self.backlog.done(self.jobs.len());
+ gauge!(RECONCILE_QUEUE_DEPTH, "partition" => self.partition_label.clone()).set(0.0);
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum ReconcileRetryReason {
+ CatalogNotLoaded,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum ReconcileDiscardReason {
+ TeamAbsent,
+ CohortAbsent,
+ NotEmitting,
+ HashMismatch,
+ HashUnknown,
+}
+
+impl ReconcileDiscardReason {
+ const fn as_str(self) -> &'static str {
+ match self {
+ Self::TeamAbsent => "team_absent",
+ Self::CohortAbsent => "cohort_absent",
+ Self::NotEmitting => "not_emitting",
+ Self::HashMismatch => "hash_mismatch",
+ Self::HashUnknown => "hash_unknown",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum ReconcileGuard {
+ Proceed,
+ Retry(ReconcileRetryReason),
+ Discard(ReconcileDiscardReason),
+}
+
+fn evaluate_guard(
+ catalog_loaded: bool,
+ filters: Option<&TeamFilters>,
+ tile: &ReconcileTile,
+) -> ReconcileGuard {
+ if !catalog_loaded {
+ return ReconcileGuard::Retry(ReconcileRetryReason::CatalogNotLoaded);
+ }
+ let Some(filters) = filters else {
+ return ReconcileGuard::Discard(ReconcileDiscardReason::TeamAbsent);
+ };
+ if !filters.cohorts.contains_key(&tile.cohort_id()) {
+ return ReconcileGuard::Discard(ReconcileDiscardReason::CohortAbsent);
+ }
+ let Some(eligibility) = filters.eligibility.get(&tile.cohort_id()) else {
+ return ReconcileGuard::Discard(ReconcileDiscardReason::CohortAbsent);
+ };
+ if !eligibility.registers_membership() {
+ return ReconcileGuard::Discard(ReconcileDiscardReason::NotEmitting);
+ }
+ // An absent hash means the cohort has no behavioral leaves (the loader omits person-only
+ // cohorts, which the person-property backfill heals separately) or the run was superseded. Either
+ // way this is the intended fail-closed skip, observable via the `hash_unknown` discard counter.
+ let Some(actual_hash) = filters.behavioral_shape_hashes.get(&tile.cohort_id()) else {
+ return ReconcileGuard::Discard(ReconcileDiscardReason::HashUnknown);
+ };
+ if actual_hash != tile.filters_hash() {
+ return ReconcileGuard::Discard(ReconcileDiscardReason::HashMismatch);
+ }
+ ReconcileGuard::Proceed
+}
+
+/// Advance at most one scan page for the queue head. Guard-discarded jobs are drained in the same
+/// tick; a successfully completed job stops the tick so the next queued snapshot gets its own page
+/// budget.
+#[allow(clippy::too_many_arguments)]
+pub(crate) async fn handle_reconcile_drain(
+ partition_id: u16,
+ handle: &StoreHandle,
+ catalog: &CatalogHandle,
+ sink: &Arc<dyn MembershipSink>,
+ merge: &MergeWorkerDeps,
+ queue: &mut ReconcileQueue,
+ last_updated: &str,
+) {
+ loop {
+ let Some(job) = queue.front() else {
+ return;
+ };
+ let tile = job.tile.clone();
+ let phase = job.phase.clone();
+ let source_offset = job.offset.offset();
+
+ // Read the release-published loaded flag before the ArcSwap. On the first refresh, that
+ // ordering prevents observing `loaded = true` alongside the pre-refresh empty snapshot.
+ let catalog_loaded = catalog.is_loaded();
+ let catalog_snapshot = catalog.load_full();
+ let filters = catalog_snapshot.team(tile.team_id()).map(Arc::as_ref);
+ match evaluate_guard(catalog_loaded, filters, &tile) {
+ ReconcileGuard::Retry(ReconcileRetryReason::CatalogNotLoaded) => {
+ debug!(
+ partition_id,
+ team_id = tile.team_id().0,
+ cohort_id = tile.cohort_id().0,
+ run_id = %tile.run_id().0,
+ "reconcile drain waiting for the first filter catalog load",
+ );
+ return;
+ }
+ ReconcileGuard::Discard(reason) => {
+ let discarded = queue
+ .finish_front()
+ .expect("the guarded queue head is still present");
+ complete_offset(
+ &merge.seed_tracker,
+ partition_id,
+ discarded.offset,
+ "discarded reconcile",
+ );
+ counter!(RECONCILE_JOBS_DISCARDED_TOTAL, "reason" => reason.as_str()).increment(1);
+ warn_job!(
+ tile,
+ partition_id,
+ reason = reason.as_str(),
+ "discarding reconcile job without a completion marker",
+ );
+ continue;
+ }
+ ReconcileGuard::Proceed => {}
+ }
+
+ let filters = filters.expect("the proceed guard proved the team exists");
+ let tree = filters
+ .cohorts
+ .get(&tile.cohort_id())
+ .expect("the proceed guard proved the cohort exists");
+ // Only flipped bits of a full-tree cohort cascade to referrers; single-leaf fixes never do.
+ let cascades_flips = filters
+ .eligibility
+ .get(&tile.cohort_id())
+ .copied()
+ .expect("the proceed guard proved eligibility exists")
+ .writes_cf_stage2();
+
+ let prefix = Stage2CohortPrefix {
+ partition_id,
+ team_id: tile.team_id().0 as u64,
+ cohort_id: tile.cohort_id().0 as u64,
+ };
+ queue.activate_front_tracking(prefix);
+
+ let step = match phase {
+ ScanPhase::Scanning { cursor } => {
+ drain_scanning(
+ partition_id,
+ handle,
+ sink,
+ merge,
+ queue,
+ &tile,
+ filters,
+ tree,
+ cascades_flips,
+ prefix,
+ source_offset,
+ cursor,
+ last_updated,
+ )
+ .await
+ }
+ ScanPhase::DrainingDirty { cursor } => {
+ drain_dirty(
+ partition_id,
+ handle,
+ sink,
+ merge,
+ queue,
+ &tile,
+ filters,
+ tree,
+ cascades_flips,
+ prefix,
+ source_offset,
+ cursor,
+ last_updated,
+ )
+ .await
+ }
+ ScanPhase::MarkerReady => {
+ drain_marker(
+ partition_id,
+ handle,
+ sink,
+ merge,
+ queue,
+ &tile,
+ prefix,
+ last_updated,
+ )
+ .await
+ }
+ };
+ match step {
+ DrainStep::Reenter => continue,
+ DrainStep::Yield => return,
+ }
+ }
+}
+
+/// Whether the drain loop should re-enter against the head's newly transitioned phase
+/// ([`DrainStep::Reenter`]) or yield the tick because its work budget is spent ([`DrainStep::Yield`]).
+enum DrainStep {
+ Reenter,
+ Yield,
+}
+
+/// Scan one Stage 2 page for the cohort and emit its current membership. An empty page hands off to
+/// dirty verification; a settled non-empty page is the tick's whole budget.
+#[allow(clippy::too_many_arguments)]
+async fn drain_scanning(
+ partition_id: u16,
+ handle: &StoreHandle,
+ sink: &Arc<dyn MembershipSink>,
+ merge: &MergeWorkerDeps,
+ queue: &mut ReconcileQueue,
+ tile: &ReconcileTile,
+ filters: &TeamFilters,
+ tree: &crate::filters::tree::CohortTree,
+ cascades_flips: bool,
+ prefix: Stage2CohortPrefix,
+ source_offset: i64,
+ cursor: Option<Vec<u8>>,
+ last_updated: &str,
+) -> DrainStep {
+ let page = match handle
+ .scan_stage2_cohort(prefix, cursor, merge.reconcile.scan_page)
+ .await
+ {
+ Ok(page) => page,
+ Err(error) => {
+ warn_job!(
+ tile,
+ partition_id,
+ error = %error,
+ "reconcile Stage 2 scan failed; retrying this page on the next tick",
+ );
+ return DrainStep::Yield;
+ }
+ };
+ if page.is_empty() {
+ queue
+ .front_mut()
+ .expect("the scanned queue head is still present")
+ .phase = ScanPhase::DrainingDirty { cursor: None };
+ return DrainStep::Reenter;
+ }
+
+ let dirty_to_clear: Vec<Stage2DirtyKey> =
+ page.iter().copied().map(Stage2DirtyKey::new).collect();
+ let Some(progress) = settle_reconcile_page(
+ partition_id,
+ handle,
+ sink,
+ merge,
+ tile,
+ filters,
+ tree,
+ cascades_flips,
+ &page,
+ &dirty_to_clear,
+ source_offset,
+ last_updated,
+ )
+ .await
+ else {
+ return DrainStep::Yield;
+ };
+
+ let short_page = page.len() < merge.reconcile.scan_page;
+ let next_cursor = page
+ .last()
+ .expect("a non-empty page has a final key")
+ .encode()
+ .to_vec();
+ let job = queue
+ .front_mut()
+ .expect("the advanced queue head is still present");
+ job.rows_scanned = job.rows_scanned.saturating_add(progress.rows_scanned);
+ job.bits_fixed = job.bits_fixed.saturating_add(progress.bits_fixed);
+ job.phase = if short_page {
+ ScanPhase::DrainingDirty { cursor: None }
+ } else {
+ ScanPhase::Scanning {
+ cursor: Some(next_cursor),
+ }
+ };
+ // One non-empty settlement page is the tick's work budget. Even a short final main page leaves
+ // dirty verification for the next tick, so mutations behind the cursor cannot silently double the
+ // configured per-tick ceiling.
+ DrainStep::Yield
+}
+
+/// Re-settle rows mutated behind the main scan, verifying from the cohort prefix until the dirty set
+/// is empty before advancing to the marker.
+#[allow(clippy::too_many_arguments)]
+async fn drain_dirty(
+ partition_id: u16,
+ handle: &StoreHandle,
+ sink: &Arc<dyn MembershipSink>,
+ merge: &MergeWorkerDeps,
+ queue: &mut ReconcileQueue,
+ tile: &ReconcileTile,
+ filters: &TeamFilters,
+ tree: &crate::filters::tree::CohortTree,
+ cascades_flips: bool,
+ prefix: Stage2CohortPrefix,
+ source_offset: i64,
+ cursor: Option<Vec<u8>>,
+ last_updated: &str,
+) -> DrainStep {
+ let page = match handle
+ .scan_stage2_dirty(prefix, cursor.clone(), merge.reconcile.scan_page)
+ .await
+ {
+ Ok(page) => page,
+ Err(error) => {
+ warn_job!(
+ tile,
+ partition_id,
+ error = %error,
+ "reconcile dirty scan failed; retrying this page on the next tick",
+ );
+ return DrainStep::Yield;
+ }
+ };
+ if page.is_empty() {
+ let job = queue
+ .front_mut()
+ .expect("the dirty-scanning queue head is still present");
+ if cursor.is_some() {
+ // Verify once more from the prefix so a marker inserted behind the cursor
+ // between ticks cannot be missed.
+ job.phase = ScanPhase::DrainingDirty { cursor: None };
+ } else {
+ job.phase = ScanPhase::MarkerReady;
+ }
+ return DrainStep::Reenter;
+ }
+
+ let stage2_keys: Vec<Stage2Key> = page.iter().map(|dirty| dirty.stage2_key()).collect();
+ let current_rows = match handle
+ .multi_get_stage2(stage2_keys.clone(), ReadLane::Maintenance)
+ .await
+ {
+ Ok(rows) => rows,
+ Err(error) => {
+ warn_job!(
+ tile,
+ partition_id,
+ error = %error,
+ "reconcile dirty-row read failed; retrying this page on the next tick",
+ );
+ return DrainStep::Yield;
+ }
+ };
+ let existing_keys: Vec<Stage2Key> = stage2_keys
+ .into_iter()
+ .zip(current_rows)
+ .filter_map(|(key, value)| value.is_some().then_some(key))
+ .collect();
+ let Some(progress) = settle_reconcile_page(
+ partition_id,
+ handle,
+ sink,
+ merge,
+ tile,
+ filters,
+ tree,
+ cascades_flips,
+ &existing_keys,
+ &page,
+ source_offset,
+ last_updated,
+ )
+ .await
+ else {
+ return DrainStep::Yield;
+ };
+
+ let short_page = page.len() < merge.reconcile.scan_page;
+ let next_cursor = page
+ .last()
+ .expect("a non-empty dirty page has a final key")
+ .encode()
+ .to_vec();
+ let job = queue
+ .front_mut()
+ .expect("the advanced dirty queue head is still present");
+ job.rows_scanned = job.rows_scanned.saturating_add(progress.rows_scanned);
+ job.bits_fixed = job.bits_fixed.saturating_add(progress.bits_fixed);
+ job.phase = ScanPhase::DrainingDirty {
+ cursor: Some(next_cursor.clone()),
+ };
+
+ // A full page does not prove exhaustion, so first look strictly after it. This is
+ // verification only: if another page exists, the next tick settles it.
+ if !short_page {
+ match handle.scan_stage2_dirty(prefix, Some(next_cursor), 1).await {
+ Ok(remaining) if !remaining.is_empty() => return DrainStep::Yield,
+ Ok(_) => {}
+ Err(error) => {
+ warn_job!(
+ tile,
+ partition_id,
+ error = %error,
+ "reconcile dirty tail verification failed; retrying next tick",
+ );
+ return DrainStep::Yield;
+ }
+ }
+ }
+
+ // Verify once from the prefix to catch work inserted behind an earlier cursor. The
+ // worker owns this partition serially, so an empty result immediately after the
+ // settlement closes the hot-single-key case even when page size is one. Never
+ // settle a second nonempty page in this tick.
+ queue
+ .front_mut()
+ .expect("the verified dirty queue head is still present")
+ .phase = ScanPhase::DrainingDirty { cursor: None };
+ match handle.scan_stage2_dirty(prefix, None, 1).await {
+ Ok(remaining) if !remaining.is_empty() => DrainStep::Yield,
+ Ok(_) => {
+ queue
+ .front_mut()
+ .expect("the verified dirty queue head is still present")
+ .phase = ScanPhase::MarkerReady;
+ DrainStep::Reenter
+ }
+ Err(error) => {
+ warn_job!(
+ tile,
+ partition_id,
+ error = %error,
+ "reconcile dirty prefix verification failed; retrying next tick",
+ );
+ DrainStep::Yield
+ }
+ }
+}
+
+/// Emit the per-partition completion marker once the dirty set is drained. A failed marker produce
+/// retries the marker only; work dirtied while the marker was pending is settled before the retry.
+#[allow(clippy::too_many_arguments)]
+async fn drain_marker(
+ partition_id: u16,
+ handle: &StoreHandle,
+ sink: &Arc<dyn MembershipSink>,
+ merge: &MergeWorkerDeps,
+ queue: &mut ReconcileQueue,
+ tile: &ReconcileTile,
+ prefix: Stage2CohortPrefix,
+ last_updated: &str,
+) -> DrainStep {
+ // A marker produce may have failed on a prior tick. Recheck the dirty prefix before
+ // every retry so newly arrived work is settled first without rescanning the cohort.
+ let pending_dirty = match handle.scan_stage2_dirty(prefix, None, 1).await {
+ Ok(page) => page,
+ Err(error) => {
+ warn_job!(
+ tile,
+ partition_id,
+ error = %error,
+ "reconcile dirty verification failed before marker; retrying on the next tick",
+ );
+ return DrainStep::Yield;
+ }
+ };
+ if !pending_dirty.is_empty() {
+ queue
+ .front_mut()
+ .expect("the marker-ready queue head is still present")
+ .phase = ScanPhase::DrainingDirty { cursor: None };
+ return DrainStep::Reenter;
+ }
+ let marker = ReconcileCompleteMarker::new(
+ tile.team_id(),
+ tile.cohort_id(),
+ partition_id,
+ tile.run_id(),
+ last_updated.to_string(),
+ );
+ let acks = sink.produce_markers(vec![marker]).await;
+ // Exactly one marker went in, so anything but a single successful ack is a produce failure.
+ let failed_acks = acks.iter().filter(|ack| ack.is_err()).count();
+ if acks.len() != 1 || failed_acks > 0 {
+ warn_job!(
+ tile,
+ partition_id,
+ ack_count = acks.len(),
+ failed_acks,
+ "reconcile completion-marker produce failed; rechecking dirty work before retry",
+ );
+ return DrainStep::Yield;
+ }
+
+ counter!(RECONCILE_MARKERS_EMITTED_TOTAL).increment(1);
+ let completed = queue
+ .finish_front()
+ .expect("the marker-producing queue head is still present");
+ complete_offset(
+ &merge.seed_tracker,
+ partition_id,
+ completed.offset,
+ "completed reconcile",
+ );
+ counter!(RECONCILE_JOBS_COMPLETED_TOTAL).increment(1);
+ info!(
+ partition_id,
+ team_id = tile.team_id().0,
+ cohort_id = tile.cohort_id().0,
+ run_id = %tile.run_id().0,
+ rows_scanned = completed.rows_scanned,
+ bits_fixed = completed.bits_fixed,
+ "reconcile job completed",
+ );
+ DrainStep::Yield
+}
+
+struct PageProgress {
+ rows_scanned: u64,
+ bits_fixed: u64,
+}
+
+/// Emit one current reconcile page, then atomically commit any corrected bits and clear the exact
+/// dirty markers covered by that evaluation. Returning `None` leaves the queue phase unchanged so
+/// the same page is retried on the next tick.
+#[allow(clippy::too_many_arguments)]
+async fn settle_reconcile_page(
+ partition_id: u16,
+ handle: &StoreHandle,
+ sink: &Arc<dyn MembershipSink>,
+ merge: &MergeWorkerDeps,
+ tile: &ReconcileTile,
+ filters: &TeamFilters,
+ tree: &crate::filters::tree::CohortTree,
+ cascades_flips: bool,
+ page: &[Stage2Key],
+ dirty_to_clear: &[Stage2DirtyKey],
+ source_offset: i64,
+ last_updated: &str,
+) -> Option<PageProgress> {
+ let evaluated_at_ms = clickhouse_timestamp_to_millis(last_updated)
+ .expect("worker-generated last_updated timestamps always parse");
+ let mut changes = Vec::with_capacity(page.len());
+ let mut cascade_changes = Vec::new();
+ let mut writes: Vec<(Stage2Key, Stage2State)> = Vec::new();
+ let mut fixed_entered = 0u64;
+ let mut fixed_left = 0u64;
+ for key in page {
+ let diff = match recompute_and_diff(
+ partition_id,
+ key.person_id,
+ tree,
+ filters,
+ handle,
+ ReadLane::Maintenance,
+ )
+ .await
+ {
+ Ok(diff) => diff,
+ Err(error) => {
+ warn_job!(
+ tile,
+ partition_id,
+ person_id = %key.person_id,
+ error = %error,
+ "reconcile recompute failed; retrying this page on the next tick",
+ );
+ return None;
+ }
+ };
+ let change = CohortMembershipChange {
+ team_id: tile.team_id().0,
+ cohort_id: tile.cohort_id().0,
+ person_id: key.person_id.to_string(),
+ last_updated: last_updated.to_string(),
+ status: diff.status(),
+ origin: Some(ChangeOrigin::Reconcile),
+ run_id: Some(tile.run_id()),
+ };
+ if diff.requires_write() {
+ writes.push((
+ diff.stage2_key,
+ Stage2State {
+ in_cohort: diff.new_bit,
+ last_evaluated_at_ms: evaluated_at_ms,
+ },
+ ));
+ }
+ if diff.flipped() {
+ if diff.new_bit {
+ fixed_entered += 1;
+ } else {
+ fixed_left += 1;
+ }
+ if cascades_flips {
+ cascade_changes.push(change.clone());
+ }
+ }
+ changes.push(change);
+ }
+
+ let cascades = first_cascades(merge, &cascade_changes, source_offset);
+ let (entered, left) = count_by_status(&changes);
+ let membership_errors = if changes.is_empty() {
+ 0
+ } else {
+ produce_membership(sink, changes).await
+ };
+ if membership_errors > 0 {
+ warn_job!(
+ tile,
+ partition_id,
+ errors = membership_errors,
+ "reconcile membership produce failed; retrying this page on the next tick",
+ );
+ return None;
+ }
+
+ let cascade_errors = produce_cascades(merge, cascades).await;
+ if cascade_errors > 0 {
+ warn_job!(
+ tile,
+ partition_id,
+ errors = cascade_errors,
+ "reconcile cascade produce failed; retrying this page on the next tick",
+ );
+ return None;
+ }
+
+ let mut staged = StagedBatch::default();
+ for (key, state) in &writes {
+ staged.put_stage2(key, &state.encode());
+ }
+ // These deletes are deliberately staged after the puts. A fix marks its row dirty through the
+ // normal typed write path, then this page-clear consumes that marker in the same atomic batch.
+ for dirty in dirty_to_clear {
+ staged.delete_stage2_dirty(dirty);
+ }
+ if !staged.is_empty() {
+ if let Err(error) = handle.commit(staged).await {
+ warn_job!(
+ tile,
+ partition_id,
+ error = %error,
+ "reconcile Stage 2 settlement failed; retrying this page on the next tick",
+ );
+ return None;
+ }
+ }
+ // Count only durably-settled pages: membership produce, cascade produce, and commit have all
+ // succeeded here. Any earlier failure returns `None` above and retries the whole page, so
+ // incrementing here keeps a retry from double-counting.
+ counter!(RECONCILE_ROWS_SCANNED_TOTAL).increment(page.len() as u64);
+ if entered > 0 {
+ counter!(RECONCILE_ROWS_EMITTED_TOTAL, "status" => "entered").increment(entered);
+ }
+ if left > 0 {
+ counter!(RECONCILE_ROWS_EMITTED_TOTAL, "status" => "left").increment(left);
+ }
+ if fixed_entered > 0 {
+ counter!(RECONCILE_BITS_FIXED_TOTAL, "direction" => "entered").increment(fixed_entered);
+ }
+ if fixed_left > 0 {
+ counter!(RECONCILE_BITS_FIXED_TOTAL, "direction" => "left").increment(fixed_left);
+ }
+
+ Some(PageProgress {
+ rows_scanned: page.len() as u64,
+ bits_fixed: fixed_entered + fixed_left,
+ })
+}
+
+fn complete_offset(
+ tracker: &OffsetTracker,
+ partition_id: u16,
+ offset: DeferredOffset,
+ operation: &'static str,
+) {
+ match tracker.complete_deferred(offset) {
+ Some(MarkOutcome::WithinDispatch) => {}
+ Some(MarkOutcome::CappedAheadOfDispatch) => {
+ counter!(COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH).increment(1);
+ warn!(
+ partition_id,
+ operation, "reconcile completion exceeded the seed dispatch ceiling",
+ );
+ }
+ None => warn!(
+ partition_id,
+ operation, "reconcile completion belonged to an expired seed-tracker tenure",
+ ),
+ }
+}
+
+#[cfg(test)]
+#[allow(clippy::disallowed_methods)]
+mod tests {
+ use std::sync::atomic::AtomicBool;
+
+ use async_trait::async_trait;
+ use chrono_tz::UTC;
+ use common_kafka::kafka_producer::KafkaProduceError;
+ use serde_json::{json, Value};
+ use tempfile::TempDir;
+ use uuid::Uuid;
+
+ use cohort_core::seed::BehavioralShapeHash;
+ use cohort_core::{CohortEligibility, ExcludedReason, FilterCatalog, LeafStateKey};
+
+ use crate::filters::tree::{CohortTree, FilterNode};
+ use crate::filters::{BoolOp, TeamFiltersBuilder};
+ use crate::partitions::offset_tracker::OffsetTracker;
+ use crate::producer::{CaptureCascadeSink, CaptureSink, MembershipStatus};
+ use crate::stage1::person_record::{MatchedSet, PersonRecord};
+ use crate::stage1::state::{AppliedOffsets, Stage1State, StatefulRecord};
+ use crate::stage2::state::Stage2Ownership;
+ use crate::store::{
+ Behavioral, BehavioralKey, CohortStore, OffloadConfig, OffloadMode, PersonRecordKey,
+ PersonRecords, StoreConfig,
+ };
+
+ use super::*;
+
+ const TEAM: i32 = 7;
+ const COHORT: i32 = 1;
+ const PARTITION: u16 = 0;
+ const BEHAVIORAL_HASH: [u8; 16] = *b"0123456789abcdef";
+ const PERSON_HASH: [u8; 16] = *b"fedcba9876543210";
+ const SHAPE_HASH: &str = "shape-v1";
+ const TS: &str = "2026-05-26 12:34:56.789123";
+
+ fn temp_store() -> (TempDir, CohortStore) {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ (dir, store)
+ }
+
+ fn store_handle(store: &CohortStore) -> StoreHandle {
+ StoreHandle::new(
+ store.clone(),
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ )
+ }
+
+ fn behavioral_leaf() -> Value {
+ json!({
+ "type": "behavioral", "value": "performed_event", "key": "$pageview",
+ "time_value": 7, "time_interval": "day",
+ "conditionHash": "0123456789abcdef",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ })
+ }
+
+ fn person_leaf() -> Value {
+ json!({
+ "type": "person", "key": "email", "value": "[email protected]", "operator": "exact",
+ "conditionHash": "fedcba9876543210",
+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],
+ })
+ }
+
+ fn catalog(single_leaf: bool) -> (CatalogHandle, LeafStateKey) {
+ let values = if single_leaf {
+ vec![behavioral_leaf()]
+ } else {
+ vec![behavioral_leaf(), person_leaf()]
+ };
+ let cohort = json!({ "properties": { "type": "AND", "values": values } });
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(COHORT), TeamId(TEAM), &cohort)
+ .unwrap();
+ builder.set_behavioral_shape_hash(
+ CohortId(COHORT),
+ BehavioralShapeHash::parse(SHAPE_HASH).unwrap(),
+ );
+ let filters = builder.freeze(UTC);
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ (
+ CatalogHandle::from_catalog(FilterCatalog::from_teams([(TeamId(TEAM), filters)])),
+ lsk,
+ )
+ }
+
+ struct DrainShell {
+ _dir: TempDir,
+ store: CohortStore,
+ handle: StoreHandle,
+ catalog: CatalogHandle,
+ sink: Arc<dyn MembershipSink>,
+ deps: MergeWorkerDeps,
+ queue: ReconcileQueue,
+ lsk: LeafStateKey,
+ }
+
+ impl DrainShell {
+ fn new(
+ single_leaf: bool,
+ sink: Arc<dyn MembershipSink>,
+ cascade_sink: CaptureCascadeSink,
+ scan_page: usize,
+ ) -> Self {
+ let (_dir, store) = temp_store();
+ let handle = store_handle(&store);
+ let (catalog, lsk) = catalog(single_leaf);
+ let mut deps = Arc::try_unwrap(MergeWorkerDeps::capture())
+ .unwrap_or_else(|_| panic!("test owns the only dependency Arc"));
+ deps.reconcile.enabled = true;
+ deps.reconcile.scan_page = scan_page;
+ deps.cascade.enabled = true;
+ deps.cascade_sink = Arc::new(cascade_sink);
+ let queue =
+ ReconcileQueue::new(PARTITION, deps.reconcile.backlog.clone(), handle.clone());
+ Self {
+ _dir,
+ store,
+ handle,
+ catalog,
+ sink,
+ deps,
+ queue,
+ lsk,
+ }
+ }
+
+ fn write_current(&self, person: Uuid, behavioral: bool, person_match: bool, prior: bool) {
+ if behavioral {
+ let key = BehavioralKey::new(PARTITION, TEAM as u64, person, self.lsk);
+ let state = Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: i64::MAX,
+ };
+ let record = StatefulRecord::new(state, AppliedOffsets::default());
+ self.store
+ .write_batch(|batch| batch.put::<Behavioral>(&key, &record.encode()))
+ .unwrap();
+ }
+ if person_match {
+ let key = PersonRecordKey::new(PARTITION, TEAM as u64, person);
+ let mut record = PersonRecord::absent();
+ record.matched = MatchedSet::from_iter([PERSON_HASH]);
+ self.store
+ .write_batch(|batch| batch.put::<PersonRecords>(&key, &record.encode()))
+ .unwrap();
+ }
+ let key = Stage2Key {
+ partition_id: PARTITION,
+ team_id: TEAM as u64,
+ cohort_id: COHORT as u64,
+ person_id: person,
+ };
+ let state = Stage2State {
+ in_cohort: prior,
+ last_evaluated_at_ms: 1,
+ };
+ self.store
+ .write_batch(|batch| batch.put_stage2(&key, &state.encode()))
+ .unwrap();
+ }
+
+ fn stage2_bit(&self, person: Uuid) -> bool {
+ let key = Stage2Key {
+ partition_id: PARTITION,
+ team_id: TEAM as u64,
+ cohort_id: COHORT as u64,
+ person_id: person,
+ };
+ Stage2State::decode(&self.store.get_stage2(&key).unwrap().unwrap())
+ .unwrap()
+ .in_cohort
+ }
+
+ fn enqueue(&mut self, tile: ReconcileTile, offset: i64) {
+ self.deps
+ .seed_tracker
+ .mark_dispatched(PARTITION as i32, offset + 1);
+ if self.committable().is_none() {
+ assert_eq!(
+ self.deps
+ .seed_tracker
+ .mark_processed(PARTITION as i32, offset),
+ MarkOutcome::WithinDispatch,
+ );
+ }
+ let deferred = self.deps.seed_tracker.defer(PARTITION as i32, offset);
+ self.queue.enqueue(tile, deferred);
+ }
+
+ /// Admit a newer run over a queued job exactly as `admit_reconcile` does: supersede, hand the
+ /// superseded floor to `replace_deferred`, then enqueue the replacement at the new offset.
+ fn supersede(&mut self, tile: ReconcileTile, offset: i64) {
+ self.deps
+ .seed_tracker
+ .mark_dispatched(PARTITION as i32, offset + 1);
+ let SupersedeOutcome::Replaced(superseded) =
+ self.queue
+ .supersede_if_newer(tile.team_id(), tile.cohort_id(), offset)
+ else {
+ panic!("a newer run must supersede the queued job");
+ };
+ let (replacement, _) = self
+ .deps
+ .seed_tracker
+ .replace_deferred(superseded, offset)
+ .expect("the superseded reconcile retains its deferred offset");
+ self.queue.enqueue(tile, replacement);
+ }
+
+ async fn tick(&mut self) {
+ handle_reconcile_drain(
+ PARTITION,
+ &self.handle,
+ &self.catalog,
+ &self.sink,
+ &self.deps,
+ &mut self.queue,
+ TS,
+ )
+ .await;
+ }
+
+ fn committable(&self) -> Option<i64> {
+ self.deps
+ .seed_tracker
+ .committable_offsets()
+ .get(&(PARTITION as i32))
+ .copied()
+ }
+ }
+
+ fn tile(team_id: i32, cohort_id: i32, run_id: u128) -> ReconcileTile {
+ ReconcileTile::new(
+ TeamId(team_id),
+ CohortId(cohort_id),
+ BehavioralShapeHash::parse(SHAPE_HASH).unwrap(),
+ RunId(Uuid::from_u128(run_id)),
+ )
+ }
+
+ #[test]
+ fn queue_tracks_backlog_and_drop_releases_only_the_backlog_count() {
+ let (_dir, store) = temp_store();
+ let tracker = OffsetTracker::new();
+ let backlog = Arc::new(ReconcileBacklog::default());
+ tracker.mark_dispatched(3, 11);
+
+ {
+ let mut queue = ReconcileQueue::new(3, backlog.clone(), store_handle(&store));
+ queue.enqueue(tile(1, 7, 1), tracker.defer(3, 10));
+ assert_eq!(queue.len(), 1);
+ assert_eq!(backlog.len(), 1);
+ }
+
+ assert!(backlog.is_empty());
+ assert_eq!(
+ tracker.mark_processed(3, 11),
+ crate::partitions::offset_tracker::MarkOutcome::WithinDispatch,
+ );
+ assert_eq!(
+ tracker.committable_offsets().get(&3),
+ Some(&10),
+ "dropping a queued job does not complete its deferred offset",
+ );
+ }
+
+ #[test]
+ fn only_the_active_queue_head_tracks_dirty_people() {
+ let (_dir, store) = temp_store();
+ let tracker = OffsetTracker::new();
+ let backlog = Arc::new(ReconcileBacklog::default());
+ tracker.mark_dispatched(PARTITION as i32, 12);
+ let mut queue = ReconcileQueue::new(PARTITION, backlog, store_handle(&store));
+ queue.enqueue(tile(TEAM, COHORT, 1), tracker.defer(PARTITION as i32, 10));
+ queue.enqueue(
+ tile(TEAM, COHORT + 1, 2),
+ tracker.defer(PARTITION as i32, 11),
+ );
+ let head_prefix = Stage2CohortPrefix {
+ partition_id: PARTITION,
+ team_id: TEAM as u64,
+ cohort_id: COHORT as u64,
+ };
+ let waiting_prefix = Stage2CohortPrefix {
+ cohort_id: (COHORT + 1) as u64,
+ ..head_prefix
+ };
+
+ // Enqueue alone captures nothing: a future full scan covers these writes.
+ for (prefix, person) in [(head_prefix, 1), (waiting_prefix, 2)] {
+ let key = Stage2Key {
+ partition_id: prefix.partition_id,
+ team_id: prefix.team_id,
+ cohort_id: prefix.cohort_id,
+ person_id: Uuid::from_u128(person),
+ };
+ store
+ .write_batch(|batch| batch.put_stage2(&key, b"before"))
+ .unwrap();
+ assert!(store
+ .scan_stage2_dirty(prefix, None, 10)
+ .unwrap()
+ .is_empty());
+ }
+
+ queue.activate_front_tracking(head_prefix);
+ for (prefix, person) in [(head_prefix, 3), (waiting_prefix, 4)] {
+ let key = Stage2Key {
+ partition_id: prefix.partition_id,
+ team_id: prefix.team_id,
+ cohort_id: prefix.cohort_id,
+ person_id: Uuid::from_u128(person),
+ };
+ store
+ .write_batch(|batch| batch.put_stage2(&key, b"during"))
+ .unwrap();
+ }
+
+ assert_eq!(
+ store
+ .scan_stage2_dirty(head_prefix, None, 10)
+ .unwrap()
+ .len(),
+ 1
+ );
+ assert!(store
+ .scan_stage2_dirty(waiting_prefix, None, 10)
+ .unwrap()
+ .is_empty());
+ }
+
+ #[test]
+ fn supersede_matches_team_and_cohort_and_preserves_other_jobs() {
+ let (_dir, store) = temp_store();
+ let tracker = OffsetTracker::new();
+ let backlog = Arc::new(ReconcileBacklog::default());
+ tracker.mark_dispatched(3, 14);
+ let mut queue = ReconcileQueue::new(3, backlog.clone(), store_handle(&store));
+ queue.enqueue(tile(1, 7, 1), tracker.defer(3, 10));
+ queue.enqueue(tile(1, 8, 2), tracker.defer(3, 11));
+ queue.enqueue(tile(2, 7, 3), tracker.defer(3, 12));
+
+ let SupersedeOutcome::Replaced(superseded) =
+ queue.supersede_if_newer(TeamId(1), CohortId(7), 13)
+ else {
+ panic!("the newer run should supersede team 1 cohort 7");
+ };
+
+ assert_eq!(queue.len(), 2);
+ assert_eq!(queue.front_run_id(), Some(RunId(Uuid::from_u128(2))));
+ assert_eq!(backlog.len(), 2);
+ assert_eq!(
+ tracker.complete_deferred(superseded),
+ Some(crate::partitions::offset_tracker::MarkOutcome::WithinDispatch),
+ );
+ assert!(matches!(
+ queue.supersede_if_newer(TeamId(2), CohortId(7), 12),
+ SupersedeOutcome::RetainedNewerOrEqual,
+ ));
+ }
+
+ #[test]
+ fn older_or_duplicate_replay_never_evicts_the_queued_run() {
+ let (_dir, store) = temp_store();
+ let tracker = OffsetTracker::new();
+ let backlog = Arc::new(ReconcileBacklog::default());
+ tracker.mark_dispatched(3, 20);
+ let mut queue = ReconcileQueue::new(3, backlog.clone(), store_handle(&store));
+ queue.enqueue(tile(1, 7, 2), tracker.defer(3, 15));
+
+ for replayed_offset in [10, 15] {
+ assert!(matches!(
+ queue.supersede_if_newer(TeamId(1), CohortId(7), replayed_offset),
+ SupersedeOutcome::RetainedNewerOrEqual,
+ ));
+ assert_eq!(queue.front_run_id(), Some(RunId(Uuid::from_u128(2))));
+ assert_eq!(backlog.len(), 1);
+ assert_eq!(tracker.committable_offsets().get(&3), None);
+ }
+ }
+
+ #[tokio::test]
+ async fn superseding_a_mid_drain_run_reemits_under_the_new_run_and_releases_its_offset() {
+ let sink = CaptureSink::new();
+ // A one-row page over three people keeps run A mid-scan (active dirty lease, cursor set) when
+ // the newer run arrives.
+ let mut shell = DrainShell::new(true, Arc::new(sink.clone()), CaptureCascadeSink::new(), 1);
+ let people = [Uuid::from_u128(1), Uuid::from_u128(2), Uuid::from_u128(3)];
+ for person in people {
+ shell.write_current(person, true, false, true);
+ }
+ shell.enqueue(tile(TEAM, COHORT, 100), 5);
+
+ shell.tick().await;
+ assert_eq!(
+ sink.changes().len(),
+ 1,
+ "run A emitted one page before being superseded",
+ );
+ assert!(matches!(
+ shell.queue.front().map(|job| &job.phase),
+ Some(ScanPhase::Scanning { cursor: Some(_) }),
+ ));
+
+ shell.supersede(tile(TEAM, COHORT, 200), 7);
+ assert_eq!(shell.queue.len(), 1);
+ assert_eq!(
+ shell.queue.front_run_id(),
+ Some(RunId(Uuid::from_u128(200)))
+ );
+
+ for _ in 0..16 {
+ if shell.queue.front().is_none() {
+ break;
+ }
+ shell.tick().await;
+ }
+ assert!(shell.queue.front().is_none());
+ assert!(shell.deps.reconcile.backlog.is_empty());
+
+ let markers = sink.markers();
+ assert_eq!(
+ markers.len(),
+ 1,
+ "the superseded run never emits its own marker"
+ );
+ assert_eq!(markers[0].run_id(), RunId(Uuid::from_u128(200)));
+
+ let reemitted: std::collections::HashSet<String> = sink
+ .changes()
+ .iter()
+ .filter(|change| change.run_id == Some(RunId(Uuid::from_u128(200))))
+ .map(|change| change.person_id.clone())
+ .collect();
+ assert_eq!(
+ reemitted,
+ people
+ .iter()
+ .map(Uuid::to_string)
+ .collect::<std::collections::HashSet<_>>(),
+ "run B re-emits the full current membership",
+ );
+
+ assert_eq!(
+ shell.committable(),
+ Some(8),
+ "the deferred floor releases only after run B completes",
+ );
+ }
+
+ fn guard_filters(eligibility: Option<CohortEligibility>, hash: Option<&str>) -> TeamFilters {
+ let mut filters = TeamFilters::default();
+ filters.cohorts.insert(
+ CohortId(COHORT),
+ CohortTree {
+ cohort_id: CohortId(COHORT),
+ team_id: TeamId(TEAM),
+ root: FilterNode::Group {
+ op: BoolOp::And,
+ children: Vec::new(),
+ },
+ },
+ );
+ if let Some(eligibility) = eligibility {
+ filters.eligibility.insert(CohortId(COHORT), eligibility);
+ }
+ if let Some(hash) = hash {
+ filters
+ .behavioral_shape_hashes
+ .insert(CohortId(COHORT), BehavioralShapeHash::parse(hash).unwrap());
+ }
+ filters
+ }
+
+ #[test]
+ fn drain_guard_classifies_every_retry_discard_and_proceed_state() {
+ let reconcile = tile(TEAM, COHORT, 1);
+
+ assert_eq!(
+ evaluate_guard(false, None, &reconcile),
+ ReconcileGuard::Retry(ReconcileRetryReason::CatalogNotLoaded),
+ );
+ assert_eq!(
+ evaluate_guard(true, None, &reconcile),
+ ReconcileGuard::Discard(ReconcileDiscardReason::TeamAbsent),
+ );
+ assert_eq!(
+ evaluate_guard(true, Some(&TeamFilters::default()), &reconcile),
+ ReconcileGuard::Discard(ReconcileDiscardReason::CohortAbsent),
+ );
+
+ let missing_eligibility = guard_filters(None, Some(SHAPE_HASH));
+ assert_eq!(
+ evaluate_guard(true, Some(&missing_eligibility), &reconcile),
+ ReconcileGuard::Discard(ReconcileDiscardReason::CohortAbsent),
+ );
+ let excluded = guard_filters(
+ Some(CohortEligibility::Excluded(ExcludedReason::HasDroppedLeaf)),
+ Some(SHAPE_HASH),
+ );
+ assert_eq!(
+ evaluate_guard(true, Some(&excluded), &reconcile),
+ ReconcileGuard::Discard(ReconcileDiscardReason::NotEmitting),
+ );
+ let hash_unknown = guard_filters(Some(CohortEligibility::Stage2Composable), None);
+ assert_eq!(
+ evaluate_guard(true, Some(&hash_unknown), &reconcile),
+ ReconcileGuard::Discard(ReconcileDiscardReason::HashUnknown),
+ );
+ let hash_mismatch =
+ guard_filters(Some(CohortEligibility::Stage2Composable), Some("shape-v2"));
+ assert_eq!(
+ evaluate_guard(true, Some(&hash_mismatch), &reconcile),
+ ReconcileGuard::Discard(ReconcileDiscardReason::HashMismatch),
+ );
+
+ for eligibility in [
+ CohortEligibility::SingleLeaf(LeafStateKey(BEHAVIORAL_HASH)),
+ CohortEligibility::Stage2Composable,
+ CohortEligibility::Stage2ComposableRef,
+ ] {
+ let filters = guard_filters(Some(eligibility), Some(SHAPE_HASH));
+ assert_eq!(
+ evaluate_guard(true, Some(&filters), &reconcile),
+ ReconcileGuard::Proceed,
+ "{eligibility:?} registers membership",
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn drain_emits_the_full_snapshot_fixes_only_flips_and_paginates() {
+ let sink = CaptureSink::new();
+ let cascades = CaptureCascadeSink::new();
+ let mut shell = DrainShell::new(false, Arc::new(sink.clone()), cascades.clone(), 2);
+ let alice = Uuid::from_u128(1);
+ let bob = Uuid::from_u128(2);
+ let charlie = Uuid::from_u128(3);
+ shell.write_current(alice, true, true, false);
+ shell.write_current(bob, false, false, true);
+ shell.write_current(charlie, true, true, true);
+ shell.enqueue(tile(TEAM, COHORT, 11), 5);
+
+ shell.tick().await;
+
+ assert_eq!(sink.changes().len(), 2, "one bounded page was emitted");
+ assert!(sink.markers().is_empty());
+ assert_eq!(shell.committable(), Some(5));
+ assert!(matches!(
+ shell.queue.front().map(|job| &job.phase),
+ Some(ScanPhase::Scanning {
+ cursor: Some(_),
+ ..
+ }),
+ ));
+
+ shell.tick().await;
+
+ let changes = sink.changes();
+ assert_eq!(changes.len(), 3, "unchanged rows are emitted too");
+ assert_eq!(
+ changes
+ .iter()
+ .map(|change| change.status)
+ .collect::<Vec<_>>(),
+ vec![
+ MembershipStatus::Entered,
+ MembershipStatus::Left,
+ MembershipStatus::Entered,
+ ],
+ );
+ assert!(changes.iter().all(|change| {
+ change.origin == Some(ChangeOrigin::Reconcile)
+ && change.run_id == Some(RunId(Uuid::from_u128(11)))
+ }));
+ assert!(shell.stage2_bit(alice));
+ assert!(!shell.stage2_bit(bob));
+ assert!(shell.stage2_bit(charlie));
+
+ let cascade_messages = cascades.messages();
+ assert_eq!(cascade_messages.len(), 2, "only flipped bits cascade");
+ assert_eq!(cascade_messages[0].change.person_id, alice.to_string());
+ assert_eq!(cascade_messages[1].change.person_id, bob.to_string());
+ shell.tick().await;
+ assert_eq!(sink.markers().len(), 1);
+ assert!(shell.queue.front().is_none());
+ assert!(shell.deps.reconcile.backlog.is_empty());
+ assert_eq!(shell.committable(), Some(6));
+ }
+
+ #[tokio::test]
+ async fn noop_reconcile_claims_a_transferred_fallback() {
+ let sink = CaptureSink::new();
+ let cascades = CaptureCascadeSink::new();
+ let mut shell = DrainShell::new(false, Arc::new(sink.clone()), cascades.clone(), 2);
+ let person = Uuid::from_u128(1);
+ let key = Stage2Key {
+ partition_id: PARTITION,
+ team_id: TEAM as u64,
+ cohort_id: COHORT as u64,
+ person_id: person,
+ };
+ let fallback = Stage2State {
+ in_cohort: false,
+ last_evaluated_at_ms: 1,
+ };
+ shell
+ .store
+ .write_batch(|batch| {
+ batch.put_stage2(&key, &fallback.encode_transferred_fallback());
+ })
+ .unwrap();
+ shell.enqueue(tile(TEAM, COHORT, 12), 5);
+
+ shell.tick().await;
+
+ let bytes = shell.store.get_stage2(&key).unwrap().unwrap();
+ let (state, ownership) = Stage2State::decode_with_ownership(&bytes).unwrap();
+ assert!(!state.in_cohort);
+ assert_eq!(ownership, Stage2Ownership::Local);
+ assert_eq!(
+ sink.changes().len(),
+ 1,
+ "the full snapshot still emits the row"
+ );
+ assert_eq!(sink.changes()[0].status, MembershipStatus::Left);
+ assert!(
+ cascades.messages().is_empty(),
+ "ownership settlement is not a flip"
+ );
+ }
+
+ #[tokio::test]
+ async fn paged_scan_drains_a_row_inserted_behind_its_cursor_without_restarting() {
+ let sink = CaptureSink::new();
+ let mut shell = DrainShell::new(true, Arc::new(sink.clone()), CaptureCascadeSink::new(), 1);
+ let later_key = Uuid::from_u128(2);
+ let inserted_behind_cursor = Uuid::from_u128(1);
+ shell.write_current(later_key, true, false, true);
+ shell.enqueue(tile(TEAM, COHORT, 111), 5);
+
+ shell.tick().await;
+ assert_eq!(sink.changes().len(), 1);
+ assert_eq!(sink.changes()[0].person_id, later_key.to_string());
+ assert!(sink.markers().is_empty());
+
+ shell.write_current(inserted_behind_cursor, true, false, true);
+ shell.tick().await;
+
+ assert_eq!(
+ sink.changes()[1].person_id,
+ inserted_behind_cursor.to_string(),
+ "the dirty-person pass catches a row inserted behind the main cursor",
+ );
+ assert_eq!(
+ sink.changes()
+ .iter()
+ .map(|change| change.person_id.clone())
+ .collect::<Vec<_>>(),
+ vec![later_key.to_string(), inserted_behind_cursor.to_string(),],
+ "the main cohort page is not rescanned because another person changed",
+ );
+ assert_eq!(sink.markers().len(), 1);
+ assert_eq!(shell.committable(), Some(6));
+ }
+
+ #[tokio::test]
+ async fn repeatedly_mutated_hot_person_does_not_restart_main_scan() {
+ let sink = CaptureSink::new();
+ let mut shell = DrainShell::new(true, Arc::new(sink.clone()), CaptureCascadeSink::new(), 1);
+ let hot = Uuid::from_u128(10);
+ let second = Uuid::from_u128(20);
+ let third = Uuid::from_u128(30);
+ for person in [hot, second, third] {
+ shell.write_current(person, true, false, true);
+ }
+ shell.enqueue(tile(TEAM, COHORT, 112), 5);
+
+ for expected in [hot, second, third] {
+ shell.tick().await;
+ assert_eq!(
+ sink.changes().last().unwrap().person_id,
+ expected.to_string(),
+ "the main cursor advances despite a mutation behind it",
+ );
+ shell.write_current(hot, true, false, true);
+ }
+
+ shell.tick().await;
+ assert_eq!(sink.changes().last().unwrap().person_id, hot.to_string());
+ assert_eq!(
+ sink.markers().len(),
+ 1,
+ "the job completes in the same tick that settles the full hot-person page",
+ );
+ assert_eq!(shell.committable(), Some(6));
+ }
+
+ #[tokio::test]
+ async fn deleted_dirty_row_is_cleared_without_being_resurrected_or_emitted_again() {
+ let sink = CaptureSink::new();
+ let mut shell = DrainShell::new(true, Arc::new(sink.clone()), CaptureCascadeSink::new(), 1);
+ let alice = Uuid::from_u128(1);
+ let bob = Uuid::from_u128(2);
+ shell.write_current(alice, true, false, true);
+ shell.write_current(bob, true, false, true);
+ shell.enqueue(tile(TEAM, COHORT, 113), 5);
+
+ shell.tick().await;
+ let deleted_key = Stage2Key {
+ partition_id: PARTITION,
+ team_id: TEAM as u64,
+ cohort_id: COHORT as u64,
+ person_id: alice,
+ };
+ shell
+ .store
+ .write_batch(|batch| batch.delete_stage2(&deleted_key))
+ .unwrap();
+
+ shell.tick().await;
+ shell.tick().await;
+ shell.tick().await;
+
+ assert_eq!(
+ sink.changes()
+ .iter()
+ .map(|change| change.person_id.clone())
+ .collect::<Vec<_>>(),
+ vec![alice.to_string(), bob.to_string()],
+ "the tombstoned scan row is not evaluated or emitted from its dirty marker",
+ );
+ assert!(shell.store.get_stage2(&deleted_key).unwrap().is_none());
+ assert_eq!(sink.markers().len(), 1);
+ }
+
+ #[tokio::test]
+ async fn single_leaf_fix_never_cascades() {
+ let sink = CaptureSink::new();
+ let cascades = CaptureCascadeSink::new();
+ let mut shell = DrainShell::new(true, Arc::new(sink.clone()), cascades.clone(), 8);
+ let alice = Uuid::from_u128(1);
+ shell.write_current(alice, true, false, false);
+ shell.enqueue(tile(TEAM, COHORT, 12), 5);
+
+ shell.tick().await;
+
+ assert_eq!(sink.changes().len(), 1);
+ assert_eq!(sink.changes()[0].status, MembershipStatus::Entered);
+ assert!(shell.stage2_bit(alice));
+ assert!(cascades.messages().is_empty());
+ shell.tick().await;
+ assert_eq!(sink.markers().len(), 1);
+ assert_eq!(shell.committable(), Some(6));
+ }
+
+ #[tokio::test]
+ async fn discard_continues_to_a_zero_row_job_and_emits_only_its_marker() {
+ let sink = CaptureSink::new();
+ let mut shell =
+ DrainShell::new(false, Arc::new(sink.clone()), CaptureCascadeSink::new(), 8);
+ shell.enqueue(tile(999, COHORT, 1), 5);
+ shell.enqueue(tile(TEAM, COHORT, 2), 6);
+
+ shell.tick().await;
+
+ assert!(sink.changes().is_empty());
+ let markers = sink.markers();
+ assert_eq!(markers.len(), 1);
+ assert_eq!(markers[0].run_id(), RunId(Uuid::from_u128(2)));
+ assert!(shell.queue.front().is_none());
+ assert!(shell.deps.reconcile.backlog.is_empty());
+ assert_eq!(shell.committable(), Some(7));
+ }
+
+ #[tokio::test]
+ async fn membership_failure_retries_the_same_page_without_advancing() {
+ let sink = CaptureSink::failing_first(1);
+ let mut shell = DrainShell::new(true, Arc::new(sink.clone()), CaptureCascadeSink::new(), 8);
+ let alice = Uuid::from_u128(1);
+ shell.write_current(alice, true, false, false);
+ shell.enqueue(tile(TEAM, COHORT, 13), 5);
+
+ shell.tick().await;
+
+ assert!(sink.changes().is_empty());
+ assert!(sink.markers().is_empty());
+ assert!(!shell.stage2_bit(alice));
+ assert!(matches!(
+ shell.queue.front().map(|job| &job.phase),
+ Some(ScanPhase::Scanning { cursor: None }),
+ ));
+
+ shell.tick().await;
+
+ assert_eq!(sink.changes().len(), 1);
+ assert!(shell.stage2_bit(alice));
+ shell.tick().await;
+ assert_eq!(sink.markers().len(), 1);
+ assert_eq!(shell.committable(), Some(6));
+ }
+
+ #[tokio::test]
+ async fn cascade_failure_retries_before_committing_or_advancing() {
+ let sink = CaptureSink::new();
+ let cascades = CaptureCascadeSink::failing_first(1);
+ let mut shell = DrainShell::new(false, Arc::new(sink.clone()), cascades.clone(), 8);
+ let alice = Uuid::from_u128(1);
+ shell.write_current(alice, true, true, false);
+ shell.enqueue(tile(TEAM, COHORT, 14), 5);
+
+ shell.tick().await;
+
+ assert_eq!(sink.changes().len(), 1, "the membership leg acked");
+ assert!(sink.markers().is_empty());
+ assert!(!shell.stage2_bit(alice));
+ assert!(matches!(
+ shell.queue.front().map(|job| &job.phase),
+ Some(ScanPhase::Scanning { cursor: None }),
+ ));
+
+ shell.tick().await;
+
+ assert_eq!(sink.changes().len(), 2, "the page was emitted again");
+ assert_eq!(cascades.messages().len(), 1);
+ assert!(shell.stage2_bit(alice));
+ shell.tick().await;
+ assert_eq!(sink.markers().len(), 1);
+ assert_eq!(shell.committable(), Some(6));
+ }
+
+ struct FailFirstMarkerSink {
+ capture: CaptureSink,
+ fail_marker: AtomicBool,
+ }
+
+ impl FailFirstMarkerSink {
+ fn new() -> Self {
+ Self {
+ capture: CaptureSink::new(),
+ fail_marker: AtomicBool::new(true),
+ }
+ }
+ }
+
+ #[async_trait]
+ impl MembershipSink for FailFirstMarkerSink {
+ async fn produce(
+ &self,
+ changes: Vec<CohortMembershipChange>,
+ ) -> Vec<Result<(), KafkaProduceError>> {
+ self.capture.produce(changes).await
+ }
+
+ async fn produce_markers(
+ &self,
+ markers: Vec<ReconcileCompleteMarker>,
+ ) -> Vec<Result<(), KafkaProduceError>> {
+ if self.fail_marker.swap(false, Ordering::SeqCst) {
+ return markers
+ .into_iter()
+ .map(|_| Err(KafkaProduceError::KafkaProduceCanceled))
+ .collect();
+ }
+ self.capture.produce_markers(markers).await
+ }
+ }
+
+ #[tokio::test]
+ async fn marker_failure_retries_only_the_marker_phase() {
+ let sink = Arc::new(FailFirstMarkerSink::new());
+ let mut shell = DrainShell::new(true, sink.clone(), CaptureCascadeSink::new(), 8);
+ let alice = Uuid::from_u128(1);
+ shell.write_current(alice, true, false, false);
+ shell.enqueue(tile(TEAM, COHORT, 15), 5);
+
+ shell.tick().await;
+ shell.tick().await;
+
+ assert_eq!(sink.capture.changes().len(), 1);
+ assert!(sink.capture.markers().is_empty());
+ assert!(shell.stage2_bit(alice), "the page committed before marker");
+ assert!(matches!(
+ shell.queue.front().map(|job| &job.phase),
+ Some(ScanPhase::MarkerReady),
+ ));
+ assert_eq!(shell.committable(), Some(5));
+
+ shell.tick().await;
+
+ assert_eq!(
+ sink.capture.changes().len(),
+ 1,
+ "the page was not rescanned"
+ );
+ assert_eq!(sink.capture.markers().len(), 1);
+ assert!(shell.queue.front().is_none());
+ assert_eq!(shell.committable(), Some(6));
+ }
+
+ #[tokio::test]
+ async fn marker_retry_drains_new_dirty_work_without_rescanning_clean_rows() {
+ let sink = Arc::new(FailFirstMarkerSink::new());
+ let mut shell = DrainShell::new(true, sink.clone(), CaptureCascadeSink::new(), 8);
+ let alice = Uuid::from_u128(2);
+ let bob = Uuid::from_u128(1);
+ shell.write_current(alice, true, false, true);
+ shell.enqueue(tile(TEAM, COHORT, 16), 5);
+
+ shell.tick().await;
+ shell.tick().await;
+ assert_eq!(sink.capture.changes().len(), 1);
+ assert!(sink.capture.markers().is_empty());
+ assert!(matches!(
+ shell.queue.front().map(|job| &job.phase),
+ Some(ScanPhase::MarkerReady),
+ ));
+
+ shell.write_current(bob, true, false, true);
+ shell.tick().await;
+
+ assert_eq!(
+ sink.capture
+ .changes()
+ .iter()
+ .map(|change| change.person_id.clone())
+ .collect::<Vec<_>>(),
+ vec![alice.to_string(), bob.to_string()],
+ "a failed marker drains only the person that changed while the marker was pending",
+ );
+ assert_eq!(sink.capture.markers().len(), 1);
+ assert_eq!(shell.committable(), Some(6));
+ }
+}
diff --git a/rust/cohort-stream-processor/src/workers/seed_path.rs b/rust/cohort-stream-processor/src/workers/seed_path.rs
index f6ab5dad8927..d00b6dd70a0a 100644
--- a/rust/cohort-stream-processor/src/workers/seed_path.rs
+++ b/rust/cohort-stream-processor/src/workers/seed_path.rs
@@ -11,10 +11,10 @@ use std::sync::Arc;
use chrono::Utc;
use chrono_tz::Tz;
use metrics::{counter, gauge};
-use tracing::warn;
+use tracing::{debug, warn};
use uuid::Uuid;
-use cohort_core::seed::{RunId, SeedTile};
+use cohort_core::seed::{ReconcileTile, RunId, SeedTile};
use crate::consumers::seeds::SeedWork;
use crate::filters::manager::CatalogHandle;
@@ -22,7 +22,8 @@ use crate::filters::reverse_index::{LeafStateMeta, TeamFilters};
use crate::filters::TeamId;
use crate::merge::tombstone_redirect::{self, Resolution, MAX_CROSS_PARTITION_REDIRECT_HOPS};
use crate::observability::metrics::{
- COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH, SEED_HELD_OFFSET_GAUGE, SEED_REKEYED_TOTAL,
+ COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH, RECONCILE_JOBS_ENQUEUED_TOTAL,
+ RECONCILE_JOBS_SUPERSEDED_TOTAL, SEED_HELD_OFFSET_GAUGE, SEED_REKEYED_TOTAL,
SEED_REKEY_HOP_CAPPED_TOTAL, SEED_REKEY_PRODUCE_FAILURE_TOTAL, SEED_TILES_APPLIED_TOTAL,
SEED_TILES_DROPPED_TOTAL, SEED_TILES_SKIPPED_TOTAL, SEED_TILES_UNCHANGED_TOTAL,
STAGE1_STATE_DECODE_ERROR, STAGE1_TRANSITIONS,
@@ -45,6 +46,7 @@ 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::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,
@@ -473,6 +475,7 @@ pub(crate) async fn handle_seed(
sink: &Arc<dyn MembershipSink>,
merge: &MergeWorkerDeps,
queue: &mut EvictionQueue<BehavioralKey>,
+ reconcile_queue: &mut ReconcileQueue,
last_updated: &str,
work: &SeedWork,
offset: i64,
@@ -483,6 +486,10 @@ pub(crate) async fn handle_seed(
mark_processed(&merge.seed_tracker, partition_id, offset);
return;
}
+ SeedWork::Reconcile(tile) => {
+ admit_reconcile(partition_id, merge, reconcile_queue, tile, offset);
+ return;
+ }
SeedWork::Tile(tile) => tile,
};
@@ -694,6 +701,65 @@ pub(crate) async fn handle_seed(
mark_processed(&merge.seed_tracker, partition_id, offset);
}
+fn admit_reconcile(
+ partition_id: u16,
+ merge: &MergeWorkerDeps,
+ queue: &mut ReconcileQueue,
+ tile: &ReconcileTile,
+ offset: i64,
+) {
+ if !merge.reconcile.enabled {
+ counter!(SEED_TILES_SKIPPED_TOTAL, "reason" => "reconcile_disabled").increment(1);
+ warn!(
+ partition_id,
+ team_id = tile.team_id().0,
+ cohort_id = tile.cohort_id().0,
+ run_id = %tile.run_id().0,
+ "reconcile seed skipped while reconcile is disabled; re-dispatch after enabling",
+ );
+ mark_processed(&merge.seed_tracker, partition_id, offset);
+ return;
+ }
+
+ let deferred = match queue.supersede_if_newer(tile.team_id(), tile.cohort_id(), offset) {
+ SupersedeOutcome::NoQueuedJob => merge.seed_tracker.defer(partition_id as i32, offset),
+ SupersedeOutcome::Replaced(superseded) => {
+ let (replacement, outcome) = merge
+ .seed_tracker
+ .replace_deferred(superseded, offset)
+ .expect("a queued reconcile must retain its deferred offset in the current tenure");
+ match outcome {
+ MarkOutcome::WithinDispatch => {}
+ MarkOutcome::CappedAheadOfDispatch => {
+ counter!(COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH).increment(1);
+ warn!(
+ partition_id,
+ "superseded reconcile completion exceeded the seed dispatch ceiling",
+ );
+ }
+ }
+ counter!(RECONCILE_JOBS_SUPERSEDED_TOTAL).increment(1);
+ replacement
+ }
+ SupersedeOutcome::RetainedNewerOrEqual => {
+ counter!(SEED_TILES_SKIPPED_TOTAL, "reason" => "reconcile_stale_replay").increment(1);
+ debug!(
+ partition_id,
+ team_id = tile.team_id().0,
+ cohort_id = tile.cohort_id().0,
+ run_id = %tile.run_id().0,
+ offset,
+ "replayed reconcile seed retained the newer or equal queued job",
+ );
+ mark_processed(&merge.seed_tracker, partition_id, offset);
+ return;
+ }
+ };
+
+ queue.enqueue(tile.clone(), deferred);
+ counter!(RECONCILE_JOBS_ENQUEUED_TOTAL).increment(1);
+}
+
/// What one tile staged across its referencing leaves.
#[derive(Default)]
struct TileApplication {
@@ -863,7 +929,9 @@ mod tests {
use serde_json::{json, Value};
use tempfile::TempDir;
- use cohort_core::seed::{ClaimEpoch, ConditionHash, SChunkMs, SeedTile};
+ use cohort_core::seed::{
+ BehavioralShapeHash, ClaimEpoch, ConditionHash, ReconcileTile, SChunkMs, SeedTile,
+ };
use crate::consumers::seeds::SeedSkipReason;
use crate::filters::{CohortId, FilterCatalog, TeamFiltersBuilder};
@@ -1664,6 +1732,15 @@ mod tests {
)
}
+ fn reconcile_for(cohort_id: i32, run_id: u128) -> ReconcileTile {
+ ReconcileTile::new(
+ TEAM,
+ CohortId(cohort_id),
+ BehavioralShapeHash::parse("0123456789abcdef").unwrap(),
+ RunId(Uuid::from_u128(run_id)),
+ )
+ }
+
struct Shell {
_dir: TempDir,
store: CohortStore,
@@ -1674,6 +1751,7 @@ mod tests {
cascade_sink: crate::producer::CaptureCascadeSink,
deps: MergeWorkerDeps,
queue: EvictionQueue<BehavioralKey>,
+ reconcile_queue: ReconcileQueue,
}
impl Shell {
@@ -1741,7 +1819,10 @@ mod tests {
seed_tracker: Arc::new(OffsetTracker::new()),
live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),
register_transfer_enabled: false,
+ reconcile: crate::workers::ReconcileDeps::default(),
};
+ let reconcile_queue =
+ ReconcileQueue::new(0, deps.reconcile.backlog.clone(), handle.clone());
Self {
_dir,
store,
@@ -1752,6 +1833,7 @@ mod tests {
cascade_sink,
deps,
queue: EvictionQueue::new(),
+ reconcile_queue,
}
}
@@ -1767,6 +1849,7 @@ mod tests {
&sink,
&self.deps,
&mut self.queue,
+ &mut self.reconcile_queue,
"2026-06-15 12:00:00.000000",
&work,
offset,
@@ -1797,6 +1880,83 @@ mod tests {
assert!(shell.sink.changes().is_empty());
}
+ #[tokio::test]
+ async fn disabled_reconcile_skips_and_commits_without_enqueuing() {
+ let mut shell = Shell::new(vec![(1, wrap(vec![single_leaf_json(7)]))]);
+
+ shell
+ .run(0, SeedWork::Reconcile(reconcile_for(1, 1)), 5)
+ .await;
+
+ assert_eq!(shell.committable(0), Some(6));
+ assert_eq!(shell.reconcile_queue.len(), 0);
+ assert!(shell.deps.reconcile.backlog.is_empty());
+ assert!(shell.sink.changes().is_empty());
+ assert!(shell.sink.markers().is_empty());
+ }
+
+ #[tokio::test]
+ async fn enabled_reconcile_enqueues_and_pins_later_seed_progress() {
+ let mut shell = Shell::new(vec![(1, wrap(vec![single_leaf_json(7)]))]);
+ shell.deps.reconcile.enabled = true;
+
+ shell
+ .run(0, SeedWork::Reconcile(reconcile_for(1, 1)), 5)
+ .await;
+ shell
+ .run(0, SeedWork::Skip(SeedSkipReason::UnknownKind), 6)
+ .await;
+
+ assert_eq!(shell.committable(0), Some(5));
+ assert_eq!(shell.reconcile_queue.len(), 1);
+ assert_eq!(shell.deps.reconcile.backlog.len(), 1);
+ }
+
+ #[tokio::test]
+ async fn newer_reconcile_supersedes_the_same_cohort_and_completes_the_old_floor() {
+ let mut shell = Shell::new(vec![(1, wrap(vec![single_leaf_json(7)]))]);
+ shell.deps.reconcile.enabled = true;
+
+ shell
+ .run(0, SeedWork::Reconcile(reconcile_for(1, 1)), 5)
+ .await;
+ shell
+ .run(0, SeedWork::Reconcile(reconcile_for(1, 2)), 6)
+ .await;
+
+ assert_eq!(shell.committable(0), Some(6));
+ assert_eq!(shell.reconcile_queue.len(), 1);
+ assert_eq!(shell.deps.reconcile.backlog.len(), 1);
+ assert_eq!(
+ shell.reconcile_queue.front_run_id(),
+ Some(RunId(Uuid::from_u128(2))),
+ );
+ }
+
+ #[tokio::test]
+ async fn older_reconcile_replay_cannot_evict_a_newer_queued_run() {
+ let mut shell = Shell::new(vec![(1, wrap(vec![single_leaf_json(7)]))]);
+ shell.deps.reconcile.enabled = true;
+
+ shell
+ .run(0, SeedWork::Reconcile(reconcile_for(1, 2)), 6)
+ .await;
+ shell
+ .run(0, SeedWork::Reconcile(reconcile_for(1, 1)), 5)
+ .await;
+ shell
+ .run(0, SeedWork::Skip(SeedSkipReason::UnknownKind), 7)
+ .await;
+
+ assert_eq!(shell.committable(0), Some(6));
+ assert_eq!(shell.reconcile_queue.len(), 1);
+ assert_eq!(shell.deps.reconcile.backlog.len(), 1);
+ assert_eq!(
+ shell.reconcile_queue.front_run_id(),
+ Some(RunId(Uuid::from_u128(2))),
+ );
+ }
+
#[tokio::test]
async fn tile_flip_emits_an_origin_tagged_change_and_schedules_eviction() {
let person = Uuid::from_u128(0x5EED);
diff --git a/rust/cohort-stream-processor/src/workers/stage2_gc.rs b/rust/cohort-stream-processor/src/workers/stage2_gc.rs
index f62d0ce25da2..9498054f7ca6 100644
--- a/rust/cohort-stream-processor/src/workers/stage2_gc.rs
+++ b/rust/cohort-stream-processor/src/workers/stage2_gc.rs
@@ -28,7 +28,7 @@ use crate::observability::metrics::{
STAGE2_ORPHAN_GC_KEYS_DELETED_TOTAL, STAGE2_ORPHAN_GC_KEYS_SCANNED_TOTAL,
STAGE2_ORPHAN_GC_SKIPPED_TOTAL, STAGE2_ORPHAN_GC_UNDECODABLE_KEYS_TOTAL,
};
-use crate::store::{Cf, CohortStore, Stage2Key, Stage2TransferredRegisterKey};
+use crate::store::{Cf, CohortStore, Stage2DirtyKey, Stage2Key, Stage2TransferredRegisterKey};
/// Per-worker resume cursor: the raw last-key scanned in this partition's `cf_stage2` slice; `None`
/// restarts at the prefix start. Loss on a rebalance is benign — a fresh tenure rescans and
@@ -38,10 +38,10 @@ pub struct Stage2GcCursor(Option<Vec<u8>>);
/// GC one partition's `cf_stage2` orphans for one tick: inspect at most `scan_limit` raw keys,
/// delete every Stage 2 row whose cohort no longer registers membership in `catalog`, and advance
-/// the raw cursor (wrapping on exhaustion). Transferred-register metadata counts against the hard
-/// per-tick budget but is not a membership row; it protects a catalog-skewed row until the catalog
-/// recognizes it. A no-op before the first catalog load or against an empty catalog (the two
-/// safety gates).
+/// the raw cursor (wrapping on exhaustion). Dirty and transferred-register metadata count against
+/// the hard per-tick budget but are not membership rows. Inactive dirty metadata is reclaimed;
+/// transferred-register metadata protects a catalog-skewed row until the catalog recognizes it. A
+/// no-op before the first catalog load or against an empty catalog (the two safety gates).
// Sync GC core; runs on the blocking pool inside `StoreHandle::run_section`, so its direct
// `CohortStore` I/O is already off the runtime threads.
#[allow(clippy::disallowed_methods)]
@@ -94,8 +94,15 @@ pub fn handle_stage2_orphan_gc(
// Decode and classify before opening the batch, since the batch closure is infallible.
let mut undecodable = 0u64;
let mut victims: Vec<Stage2Key> = Vec::new();
+ let mut stale_dirty: Vec<Stage2DirtyKey> = Vec::new();
let mut settled_transferred: Vec<Stage2TransferredRegisterKey> = Vec::new();
for (key_bytes, value) in &rows {
+ if let Ok(dirty) = Stage2DirtyKey::decode(key_bytes) {
+ if !store.is_stage2_dirty_tracking_active(dirty.stage2_key().cohort_prefix()) {
+ stale_dirty.push(dirty);
+ }
+ continue;
+ }
if let Ok(transferred) = Stage2TransferredRegisterKey::decode(key_bytes) {
let stage2_key = transferred.stage2_key();
let primary = match store.get_stage2(&stage2_key) {
@@ -161,10 +168,16 @@ pub fn handle_stage2_orphan_gc(
}
}
- if !victims.is_empty() || !settled_transferred.is_empty() {
+ if !victims.is_empty() || !stale_dirty.is_empty() || !settled_transferred.is_empty() {
let result = store.write_batch(|batch| {
for key in &victims {
batch.delete_stage2(key);
+ // Orphan deletion does not need reconcile coverage. Clear both a pre-existing dirty
+ // marker and the one `delete_stage2` just staged, in the same atomic batch.
+ batch.delete_stage2_dirty(&Stage2DirtyKey::new(*key));
+ }
+ for key in &stale_dirty {
+ batch.delete_stage2_dirty(key);
}
for key in &settled_transferred {
batch.delete_stage2_transferred_register(key);
@@ -484,6 +497,55 @@ mod tests {
}
}
+ #[test]
+ fn dirty_metadata_consumes_the_raw_per_tick_budget() {
+ let (_dir, store) = temp_store();
+ let live = stage2_key(LIVE_TEAM, 1, 100);
+ let _tracking = store.track_stage2_dirty(live.cohort_prefix());
+ put_row(&store, &live);
+ let dirty = Stage2DirtyKey::new(live).encode().to_vec();
+ let catalog = loaded(&[(LIVE_TEAM as i32, &[(1, single_leaf())])]);
+ let mut cursor = Stage2GcCursor::default();
+
+ handle_stage2_orphan_gc(PARTITION, &store, &catalog, &mut cursor, 1);
+ assert_eq!(cursor.0, Some(live.encode().to_vec()));
+
+ handle_stage2_orphan_gc(PARTITION, &store, &catalog, &mut cursor, 1);
+ assert_eq!(
+ cursor.0,
+ Some(dirty),
+ "one dirty marker consumes the entire one-key tick budget",
+ );
+ assert!(exists(&store, &live));
+
+ handle_stage2_orphan_gc(PARTITION, &store, &catalog, &mut cursor, 1);
+ assert!(cursor.0.is_none(), "the following empty tick wraps");
+ }
+
+ #[test]
+ fn inactive_dirty_only_marker_is_reclaimed() {
+ let (_dir, store) = temp_store();
+ let deleted = stage2_key(ABSENT_TEAM, 1, 100);
+ {
+ let _tracking = store.track_stage2_dirty(deleted.cohort_prefix());
+ store
+ .write_batch(|batch| batch.delete_stage2(&deleted))
+ .unwrap();
+ assert!(store
+ .get(Cf::Stage2, &Stage2DirtyKey::new(deleted).encode())
+ .unwrap()
+ .is_some());
+ }
+
+ let mut cursor = Stage2GcCursor::default();
+ handle_stage2_orphan_gc(PARTITION, &store, &live_team_only(), &mut cursor, NO_CAP);
+
+ assert!(store
+ .get(Cf::Stage2, &Stage2DirtyKey::new(deleted).encode())
+ .unwrap()
+ .is_none());
+ }
+
#[test]
fn transferred_register_survives_gc_until_catalog_refresh() {
let (_dir, store) = temp_store();
diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rs
index bc4fbcef7baa..bc89214a710d 100644
--- a/rust/cohort-stream-processor/src/workers/worker.rs
+++ b/rust/cohort-stream-processor/src/workers/worker.rs
@@ -32,7 +32,7 @@ use crate::partitions::intake::MeteredReceiver;
use crate::partitions::offset_tracker::{MarkOutcome, OffsetTracker};
use crate::partitions::shuffle_message::ShuffleMessage;
use crate::producer::{
- map_transition, now_last_updated, CohortMembershipChange, MembershipSink, MembershipStatus,
+ map_transition, CohortMembershipChange, LastUpdatedClock, MembershipSink, MembershipStatus,
OutputBuffer,
};
use crate::stage1::key::LeafStateKey;
@@ -47,6 +47,7 @@ use crate::workers::event_path::{
};
use crate::workers::merge_gc::{handle_merge_gc, MergeGcCursor};
use crate::workers::merge_path::{handle_apply, handle_merge, handle_redrive, MergeWorkerDeps};
+use crate::workers::reconcile::{handle_reconcile_drain, ReconcileQueue};
use crate::workers::seed_path::handle_seed;
use crate::workers::stage2_gc::{handle_stage2_orphan_gc, Stage2GcCursor};
use crate::workers::stage2_path::compose_stage2;
@@ -155,6 +156,11 @@ async fn run_worker(
info!(partition_id, "stage 1 worker started");
let mut queue = EvictionQueue::<BehavioralKey>::new();
+ let mut reconcile_queue = ReconcileQueue::new(
+ partition_id,
+ merge.reconcile.backlog.clone(),
+ handle.clone(),
+ );
// No-op for a cold partition (bloom-filtered scan finds nothing to schedule).
if durable_restore {
rebuild_eviction_queue(partition_id, &handle, &mut queue).await;
@@ -165,8 +171,8 @@ async fn run_worker(
// Persists across batches so a stream of buffered batches still yields on the wall-clock interval.
let mut last_yield = Instant::now();
+ let mut last_updated_clock = LastUpdatedClock::default();
while let Some(batch) = receiver.recv().await {
- let last_updated = now_last_updated();
let mut buffer = OutputBuffer::new();
let mut re_keys: Vec<CohortStreamEvent> = Vec::new();
let mut max_offset: Option<i64> = None;
@@ -177,6 +183,7 @@ async fn run_worker(
let mut held = false;
for message in batch {
+ let last_updated = last_updated_clock.next();
match message {
ShuffleMessage::Event {
event,
@@ -297,6 +304,13 @@ async fn run_worker(
.await;
}
ShuffleMessage::Seed { work, offset } => {
+ // Worker receipt is the first point that both proves this exact seed landed and
+ // orders its ceiling before even a zero-work handler can mark it processed.
+ // The dispatcher also records the delivered batch maximum, but that post-send
+ // accounting can race a fast worker on a multithreaded runtime.
+ merge
+ .seed_tracker
+ .mark_dispatched(partition_id as i32, offset + 1);
if flush_event_changes_before_inline(
&sink,
&mut buffer,
@@ -314,6 +328,7 @@ async fn run_worker(
&sink,
&merge,
&mut queue,
+ &mut reconcile_queue,
&last_updated,
&work,
offset,
@@ -364,6 +379,28 @@ async fn run_worker(
.unwrap_or_default();
}
}
+ ShuffleMessage::ReconcileDrain => {
+ if flush_event_changes_before_inline(
+ &sink,
+ &mut buffer,
+ partition_id,
+ &mut held,
+ )
+ .await
+ {
+ break;
+ }
+ handle_reconcile_drain(
+ partition_id,
+ &handle,
+ &catalog,
+ &sink,
+ &merge,
+ &mut reconcile_queue,
+ &last_updated,
+ )
+ .await;
+ }
}
if last_yield.elapsed() >= WORKER_YIELD_INTERVAL {
@@ -483,15 +520,18 @@ pub(crate) fn count_by_status(changes: &[CohortMembershipChange]) -> (u64, u64)
})
}
-/// Produce membership `changes`, await acks, and record metrics. Returns the failed-ack count
-/// (`0` = fully acked). The caller owns the per-site warn and recovery action.
+/// Produce membership `changes`, await one ack per change, and record metrics. Returns the failed
+/// or missing/extra-ack count (`0` = fully acked). The caller owns the per-site warn and recovery
+/// action.
pub(crate) async fn produce_membership(
sink: &Arc<dyn MembershipSink>,
changes: Vec<CohortMembershipChange>,
) -> usize {
let (entered, left) = count_by_status(&changes);
+ let expected_acks = changes.len();
let acks = sink.produce(changes).await;
- let errors = acks.iter().filter(|result| result.is_err()).count();
+ let errors =
+ acks.iter().filter(|result| result.is_err()).count() + acks.len().abs_diff(expected_acks);
if errors > 0 {
counter!(OUTPUT_PRODUCE_ERRORS).increment(errors as u64);
return errors;
@@ -524,9 +564,10 @@ pub(crate) fn first_cascades(
.collect()
}
-/// Produce cascade messages and await acks. Returns the failed-ack count (`0` when empty or fully
-/// acked). The caller owns the recovery posture: the event path holds the offset; the sweep/merge
-/// paths drop (at-most-once). Shared by the first-hop leg and onward-hop consumer legs.
+/// Produce cascade messages and await one ack per message. Returns the failed or
+/// missing/extra-ack count (`0` when empty or fully acked). The caller owns the recovery posture:
+/// the event path holds the offset; the sweep/merge paths drop (at-most-once). Shared by the
+/// first-hop leg and onward-hop consumer legs.
pub(crate) async fn produce_cascades(
merge: &MergeWorkerDeps,
cascades: Vec<CascadeMessage>,
@@ -534,8 +575,10 @@ pub(crate) async fn produce_cascades(
if cascades.is_empty() {
return 0;
}
+ let expected_acks = cascades.len();
let acks = merge.cascade_sink.produce(cascades).await;
- let errors = acks.iter().filter(|result| result.is_err()).count();
+ let errors =
+ acks.iter().filter(|result| result.is_err()).count() + acks.len().abs_diff(expected_acks);
if errors > 0 {
counter!(CASCADE_PRODUCE_ERRORS_TOTAL).increment(errors as u64);
}
@@ -1025,6 +1068,9 @@ mod tombstone_redirect_tests {
use tempfile::TempDir;
use tokio::sync::mpsc;
+ use cohort_core::seed::{BehavioralShapeHash, ReconcileTile, RunId};
+
+ use crate::consumers::seeds::SeedWork;
use crate::filters::{CohortId, FilterCatalog, TeamFiltersBuilder};
use crate::merge::transfer::Tombstone;
use crate::partitions::partitioner::{partition_of, COHORT_PARTITION_COUNT};
@@ -1083,6 +1129,27 @@ mod tombstone_redirect_tests {
)])))
}
+ fn reconcile_catalog(filters_hash: &str) -> Arc<CatalogHandle> {
+ let leaf = json!({
+ "type": "person", "key": "email", "value": "[email protected]", "operator": "exact",
+ "conditionHash": "fedcba9876543210",
+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],
+ });
+ let cohort = json!({ "properties": { "type": "AND", "values": [leaf] } });
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(1), TeamId(TEAM), &cohort)
+ .unwrap();
+ builder.set_behavioral_shape_hash(
+ CohortId(1),
+ BehavioralShapeHash::parse(filters_hash).unwrap(),
+ );
+ Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([(
+ TeamId(TEAM),
+ builder.freeze(UTC),
+ )])))
+ }
+
fn applied(entries: &[(i32, i64)]) -> AppliedOffsets {
let mut applied = AppliedOffsets::default();
for &(partition, offset) in entries {
@@ -1141,9 +1208,18 @@ mod tombstone_redirect_tests {
seed_tracker: Arc::new(crate::partitions::offset_tracker::OffsetTracker::new()),
live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),
register_transfer_enabled: false,
+ reconcile: crate::workers::ReconcileDeps::default(),
})
}
+ fn reconcile_deps() -> Arc<MergeWorkerDeps> {
+ let mut deps = Arc::try_unwrap(merge_deps_with(CaptureStreamEventSink::new()))
+ .unwrap_or_else(|_| panic!("test owns the only dependency Arc"));
+ deps.reconcile.enabled = true;
+ deps.reconcile.scan_page = 2;
+ Arc::new(deps)
+ }
+
/// Deps with the `stage2_orphan_gc_enabled` kill-switch set to `stage2_orphan_gc_enabled`.
fn merge_deps_stage2_gc(stage2_orphan_gc_enabled: bool) -> Arc<MergeWorkerDeps> {
Arc::new(MergeWorkerDeps {
@@ -1162,6 +1238,7 @@ mod tombstone_redirect_tests {
seed_tracker: Arc::new(crate::partitions::offset_tracker::OffsetTracker::new()),
live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),
register_transfer_enabled: false,
+ reconcile: crate::workers::ReconcileDeps::default(),
})
}
@@ -1187,6 +1264,7 @@ mod tombstone_redirect_tests {
seed_tracker: Arc::new(crate::partitions::offset_tracker::OffsetTracker::new()),
live_watermarks: Arc::new(crate::partitions::watermarks::LiveWatermarks::new()),
register_transfer_enabled: false,
+ reconcile: crate::workers::ReconcileDeps::default(),
})
}
@@ -1217,6 +1295,124 @@ mod tombstone_redirect_tests {
(partition_id, tracker)
}
+ #[tokio::test]
+ async fn seed_receipt_raises_the_ceiling_before_a_disabled_reconcile_skip() {
+ let (_dir, store) = temp_store();
+ let membership = CaptureSink::new();
+ let merge = merge_deps_with(CaptureStreamEventSink::new());
+ let seed_tracker = merge.seed_tracker.clone();
+ let events_tracker = Arc::new(OffsetTracker::new());
+ let tile = ReconcileTile::new(
+ TeamId(TEAM),
+ CohortId(1),
+ BehavioralShapeHash::parse("0123456789abcdef").unwrap(),
+ RunId(Uuid::from_u128(1)),
+ );
+
+ // Bypass EventDispatcher's post-send seed ceiling accounting. The worker must establish the
+ // ceiling from receipt before the disabled fast path can mark the offset processed.
+ run_batch(
+ 0,
+ &store,
+ person_catalog(),
+ &membership,
+ &events_tracker,
+ merge,
+ 0,
+ vec![ShuffleMessage::Seed {
+ work: Box::new(SeedWork::Reconcile(tile)),
+ offset: 5,
+ }],
+ )
+ .await;
+
+ assert_eq!(seed_tracker.committable_offsets().get(&0), Some(&6));
+ }
+
+ #[tokio::test]
+ async fn worker_admits_and_drains_a_zero_row_reconcile_before_releasing_its_offset() {
+ const FILTERS_HASH: &str = "shape-v1";
+
+ let (_dir, store) = temp_store();
+ let membership = CaptureSink::new();
+ let merge = reconcile_deps();
+ let seed_tracker = merge.seed_tracker.clone();
+ let backlog = merge.reconcile.backlog.clone();
+ let events_tracker = Arc::new(OffsetTracker::new());
+ let tile = ReconcileTile::new(
+ TeamId(TEAM),
+ CohortId(1),
+ BehavioralShapeHash::parse(FILTERS_HASH).unwrap(),
+ RunId(Uuid::from_u128(7)),
+ );
+
+ run_batch(
+ 0,
+ &store,
+ reconcile_catalog(FILTERS_HASH),
+ &membership,
+ &events_tracker,
+ merge,
+ 0,
+ vec![
+ ShuffleMessage::Seed {
+ work: Box::new(SeedWork::Reconcile(tile)),
+ offset: 5,
+ },
+ ShuffleMessage::ReconcileDrain,
+ ],
+ )
+ .await;
+
+ assert!(membership.changes().is_empty());
+ let markers = membership.markers();
+ assert_eq!(markers.len(), 1);
+ assert_eq!(markers[0].partition(), 0);
+ assert_eq!(markers[0].run_id(), RunId(Uuid::from_u128(7)));
+ assert_eq!(seed_tracker.committable_offsets().get(&0), Some(&6));
+ assert!(backlog.is_empty());
+ }
+
+ #[tokio::test]
+ async fn maintenance_boundary_keeps_later_live_output_strictly_newer_in_one_batch() {
+ let (_dir, store) = temp_store();
+ let membership = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let person = Uuid::from_u128(0x71AE);
+ let mut leaves = person_event(person, "[email protected]", 5, 1);
+ leaves.timestamp = "2026-05-26 12:34:56.790000".to_string();
+
+ run_batch(
+ 0,
+ &store,
+ person_catalog(),
+ &membership,
+ &tracker,
+ merge_deps_with(CaptureStreamEventSink::new()),
+ 2,
+ vec![
+ ShuffleMessage::Event {
+ event: Box::new(person_event(person, "[email protected]", 5, 0)),
+ cse_offset: 0,
+ broker_ts_ms: None,
+ },
+ ShuffleMessage::ReconcileDrain,
+ ShuffleMessage::Event {
+ event: Box::new(leaves),
+ cse_offset: 1,
+ broker_ts_ms: None,
+ },
+ ],
+ )
+ .await;
+
+ let changes = membership.changes();
+ assert_eq!(changes.len(), 2);
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ assert_eq!(changes[1].status, MembershipStatus::Left);
+ assert!(changes[0].last_updated < changes[1].last_updated);
+ }
+
#[tokio::test]
async fn event_flip_with_cascade_on_produces_a_depth_one_first_cascade() {
let (_dir, store) = temp_store();
diff --git a/rust/cohort-stream-processor/tests/cascade_consumer.rs b/rust/cohort-stream-processor/tests/cascade_consumer.rs
index 5cfa10a3160d..dbc18d281b13 100644
--- a/rust/cohort-stream-processor/tests/cascade_consumer.rs
+++ b/rust/cohort-stream-processor/tests/cascade_consumer.rs
@@ -466,6 +466,7 @@ async fn spawn_instance(
cohort_stream_processor::partitions::watermarks::LiveWatermarks::new(),
),
register_transfer_enabled: false,
+ reconcile: cohort_stream_processor::workers::ReconcileDeps::default(),
});
let dispatcher = Arc::new(EventDispatcher::new(
diff --git a/rust/cohort-stream-processor/tests/events_consumer.rs b/rust/cohort-stream-processor/tests/events_consumer.rs
index 52561fbbf0a6..24642fd36153 100644
--- a/rust/cohort-stream-processor/tests/events_consumer.rs
+++ b/rust/cohort-stream-processor/tests/events_consumer.rs
@@ -45,6 +45,7 @@ use cohort_stream_processor::partitions::{
};
use cohort_stream_processor::producer::{
CaptureSink, CohortMembershipChange, KafkaMembershipSink, MembershipSink, MembershipStatus,
+ ReconcileCompleteMarker,
};
use cohort_stream_processor::stage1::{Stage1State, StatefulRecord};
use cohort_stream_processor::store::durability::{
@@ -730,6 +731,16 @@ impl MembershipSink for BarrierSink {
.extend(changes);
acks
}
+
+ async fn produce_markers(
+ &self,
+ markers: Vec<ReconcileCompleteMarker>,
+ ) -> Vec<Result<(), KafkaProduceError>> {
+ markers
+ .into_iter()
+ .map(|_| Err(KafkaProduceError::KafkaProduceCanceled))
+ .collect()
+ }
}
#[tokio::test]
diff --git a/rust/cohort-stream-processor/tests/filter_catalog.rs b/rust/cohort-stream-processor/tests/filter_catalog.rs
index a35c48af2791..135344d243e2 100644
--- a/rust/cohort-stream-processor/tests/filter_catalog.rs
+++ b/rust/cohort-stream-processor/tests/filter_catalog.rs
@@ -19,6 +19,7 @@ fn row(id: i32, team_id: i32, filters: Value) -> CohortRow {
id,
team_id,
filters,
+ behavioral_filters_shape_hash: None,
timezone: "UTC".to_string(),
}
}
diff --git a/rust/cohort-stream-processor/tests/merge_consumer.rs b/rust/cohort-stream-processor/tests/merge_consumer.rs
index afeaffa53224..e3843ed84f5e 100644
--- a/rust/cohort-stream-processor/tests/merge_consumer.rs
+++ b/rust/cohort-stream-processor/tests/merge_consumer.rs
@@ -622,6 +622,7 @@ async fn spawn_instance(
cohort_stream_processor::partitions::watermarks::LiveWatermarks::new(),
),
register_transfer_enabled: false,
+ reconcile: cohort_stream_processor::workers::ReconcileDeps::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 203a2cf1322a..9f71841f5703 100644
--- a/rust/cohort-stream-processor/tests/merge_durability.rs
+++ b/rust/cohort-stream-processor/tests/merge_durability.rs
@@ -720,6 +720,7 @@ async fn spawn_instance(
cohort_stream_processor::partitions::watermarks::LiveWatermarks::new(),
),
register_transfer_enabled: false,
+ reconcile: cohort_stream_processor::workers::ReconcileDeps::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 39451beaf654..34da27059d78 100644
--- a/rust/cohort-stream-processor/tests/seed_consumer.rs
+++ b/rust/cohort-stream-processor/tests/seed_consumer.rs
@@ -12,7 +12,7 @@
//! cargo test -p cohort-stream-processor --test seed_consumer -- --ignored --test-threads=1
//! ```
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::num::NonZeroU32;
use std::panic::AssertUnwindSafe;
@@ -20,7 +20,9 @@ use std::sync::Arc;
use std::time::{Duration, Instant};
use chrono_tz::UTC;
-use cohort_core::seed::{ClaimEpoch, ConditionHash, RunId, SChunkMs, SeedTile};
+use cohort_core::seed::{
+ BehavioralShapeHash, ClaimEpoch, ConditionHash, ReconcileTile, RunId, SChunkMs, SeedTile,
+};
use cohort_stream_processor::consumers::{
CascadeRoute, CohortStreamEventsConsumer, EventDispatcher, FollowerConsumer, MergeRoute,
SeedFollowerConsumer, TransferRoute,
@@ -36,14 +38,17 @@ use cohort_stream_processor::partitions::{
use cohort_stream_processor::producer::{
CascadeSink, ChangeOrigin, CohortMembershipChange, KafkaCascadeSink, KafkaMembershipSink,
KafkaSeedTileSink, KafkaStreamEventSink, KafkaTransferSink, MembershipSink, MembershipStatus,
- SeedTileSink, StreamEventSink, TransferSink,
+ ReconcileCompleteMarker, SeedTileSink, StreamEventSink, TransferSink,
};
use cohort_stream_processor::stage1::bucket_tz::day_idx_in_tz;
+use cohort_stream_processor::stage2::state::Stage2State;
use cohort_stream_processor::store::{
- CohortStore, OffloadConfig, OffloadMode, StoreConfig, StoreHandle,
+ CohortStore, OffloadConfig, OffloadMode, ReadLane, Stage2Key, StagedBatch, StoreConfig,
+ StoreHandle,
};
use cohort_stream_processor::workers::{
- CascadeConfig, MergeWorkerDeps, TransferRetryPolicy, DEFAULT_MERGE_GC_SCAN_LIMIT,
+ CascadeConfig, MergeWorkerDeps, ReconcileBacklog, ReconcileDeps, TransferRetryPolicy,
+ DEFAULT_MERGE_GC_SCAN_LIMIT,
};
use common_kafka::config::KafkaConfig;
use futures::FutureExt;
@@ -62,6 +67,8 @@ use tokio::task::JoinHandle;
use uuid::Uuid;
const TEAM: i32 = 7;
+const COHORT: i32 = 1;
+const FILTERS_HASH: &str = "0123456789abcdef";
const NUM_PARTITIONS: i32 = COHORT_PARTITION_COUNT as i32;
const COMMIT_INTERVAL: Duration = Duration::from_millis(250);
const RECV_TIMEOUT: Duration = Duration::from_millis(200);
@@ -77,17 +84,21 @@ fn seed_catalog() -> CatalogHandle {
let leaf = json!({
"type": "behavioral", "value": "performed_event", "key": "$pageview",
"time_value": 7, "time_interval": "day",
- "conditionHash": "0123456789abcdef",
+ "conditionHash": FILTERS_HASH,
"bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
});
let mut builder = TeamFiltersBuilder::default();
builder
.add_cohort(
- CohortId(1),
+ CohortId(COHORT),
TeamId(TEAM),
&json!({ "properties": { "type": "AND", "values": [leaf] } }),
)
.expect("add cohort");
+ builder.set_behavioral_shape_hash(
+ CohortId(COHORT),
+ BehavioralShapeHash::parse(FILTERS_HASH).expect("valid test behavioral hash"),
+ );
CatalogHandle::from_catalog(FilterCatalog::from_teams([(
TeamId(TEAM),
builder.freeze(UTC),
@@ -281,22 +292,31 @@ fn part(person: Uuid) -> u16 {
/// The seed group's committed next-offset for `partition`, read without joining the group.
fn seed_group_committed(group: &str, topic: &str, partition: i32) -> Option<i64> {
+ seed_group_committed_offsets(group, topic)
+ .get(&partition)
+ .copied()
+}
+
+/// Every concrete committed next-offset for the seed topic, read in one coordinator request.
+fn seed_group_committed_offsets(group: &str, topic: &str) -> HashMap<i32, i64> {
let consumer: StreamConsumer = follower_client_config(group)
.create()
.expect("create committed-offset verifier");
let mut tpl = TopicPartitionList::new();
- tpl.add_partition(topic, partition);
+ for partition in 0..NUM_PARTITIONS {
+ tpl.add_partition(topic, partition);
+ }
let committed = consumer
.committed_offsets(tpl, Duration::from_secs(10))
- .ok()?;
+ .expect("query seed-group committed offsets");
committed
.elements_for_topic(topic)
.iter()
- .find(|elem| elem.partition() == partition)
- .and_then(|elem| match elem.offset() {
- Offset::Offset(next) => Some(next),
+ .filter_map(|elem| match elem.offset() {
+ Offset::Offset(next) => Some((elem.partition(), next)),
_ => None,
})
+ .collect()
}
/// A name-mismatched warm-up event: folds (advancing the watermark) without flipping anything.
@@ -317,12 +337,21 @@ fn warm_envelope(person: Uuid, source_offset: i64) -> Vec<u8> {
.expect("serialize envelope")
}
-async fn produce_warm_event(producer: &FutureProducer, topic: &str, person: Uuid, offset: i64) {
+async fn produce_warm_event(
+ producer: &FutureProducer,
+ topic: &str,
+ person: Uuid,
+ offset: i64,
+ broker_timestamp_ms: i64,
+) {
let key = merge_partition_key(TeamId(TEAM), &person);
let payload = warm_envelope(person, offset);
let (partition, _) = producer
.send(
- FutureRecord::to(topic).key(&key).payload(&payload),
+ FutureRecord::to(topic)
+ .key(&key)
+ .payload(&payload)
+ .timestamp(broker_timestamp_ms),
Timeout::After(Duration::from_secs(10)),
)
.await
@@ -349,6 +378,31 @@ async fn produce_tile(seed_sink: &KafkaSeedTileSink, produced: SeedTile) {
assert!(acks.iter().all(Result::is_ok), "tile produce must ack");
}
+async fn produce_reconcile(
+ producer: &FutureProducer,
+ topic: &str,
+ partition: i32,
+ tile: &ReconcileTile,
+) -> i64 {
+ let key = format!("reconcile:{TEAM}:{COHORT}:{partition}");
+ let payload = serde_json::to_vec(tile).expect("serialize reconcile control");
+ let (ack_partition, offset) = producer
+ .send(
+ FutureRecord::to(topic)
+ .partition(partition)
+ .key(&key)
+ .payload(&payload),
+ Timeout::After(Duration::from_secs(10)),
+ )
+ .await
+ .expect("produce reconcile control");
+ assert_eq!(
+ ack_partition, partition,
+ "broker acked the targeted partition"
+ );
+ offset
+}
+
fn open_store(dir: &TempDir) -> CohortStore {
CohortStore::open(&StoreConfig {
path: dir.path().join("db"),
@@ -429,6 +483,11 @@ fn register_instance(manager: &mut Manager) -> [Handle; 5] {
struct Instance {
dispatcher: Arc<EventDispatcher>,
+ store: StoreHandle,
+ reconcile_backlog: Arc<ReconcileBacklog>,
+ seed_tracker: Arc<OffsetTracker>,
+ seed_consumer: Arc<StreamConsumer>,
+ live_watermarks: Arc<LiveWatermarks>,
tasks: Vec<JoinHandle<()>>,
}
@@ -437,6 +496,53 @@ impl Instance {
self.dispatcher.owned_partitions().into_iter().collect()
}
+ async fn put_stage2(&self, key: &Stage2Key, state: &Stage2State) {
+ let mut staged = StagedBatch::default();
+ staged.put_stage2(key, &state.encode());
+ self.store
+ .commit(staged)
+ .await
+ .expect("write test Stage 2 state");
+ }
+
+ async fn stage2(&self, key: &Stage2Key) -> Stage2State {
+ let bytes = self
+ .store
+ .get_stage2(key, ReadLane::Maintenance)
+ .await
+ .expect("read test Stage 2 state")
+ .expect("test Stage 2 row exists");
+ Stage2State::decode(&bytes).expect("decode test Stage 2 state")
+ }
+
+ fn seed_committable(&self, partition: u16) -> Option<i64> {
+ self.seed_tracker
+ .committable_offsets()
+ .get(&(partition as i32))
+ .copied()
+ }
+
+ fn seed_position(&self, topic: &str, partition: u16) -> Option<i64> {
+ let positions = self
+ .seed_consumer
+ .position()
+ .expect("query seed-consumer positions");
+ positions
+ .elements_for_topic(topic)
+ .iter()
+ .find(|elem| elem.partition() == partition as i32)
+ .and_then(|elem| match elem.offset() {
+ Offset::Offset(next) => Some(next),
+ _ => None,
+ })
+ }
+
+ fn live_watermark(&self, partition: u16) -> Option<i64> {
+ self.live_watermarks
+ .get(partition as i32)
+ .map(|watermark| watermark.0)
+ }
+
async fn join(self) {
for task in self.tasks {
task.await.expect("instance task panicked");
@@ -454,6 +560,17 @@ async fn spawn_instance(
) -> Instance {
let [events_handle, merge_handle, transfer_handle, cascade_handle, seed_handle] = handles;
let kafka_config = producer_kafka_config();
+ let store = StoreHandle::new(
+ store,
+ OffloadConfig {
+ mode: OffloadMode::All,
+ event_read_permits: 16,
+ maintenance_permits: 6,
+ },
+ );
+ let reconcile_backlog = Arc::new(ReconcileBacklog::default());
+ let seed_tracker = Arc::new(OffsetTracker::new());
+ let live_watermarks = Arc::new(LiveWatermarks::new());
let transfer_sink: Arc<dyn TransferSink> = Arc::new(
KafkaTransferSink::new(&kafka_config, topics.transfers.clone())
@@ -493,22 +610,20 @@ async fn spawn_instance(
cascade: CascadeConfig::default(),
partition_count: COHORT_PARTITION_COUNT,
seed_tile_sink,
- seed_tracker: Arc::new(OffsetTracker::new()),
- live_watermarks: Arc::new(LiveWatermarks::new()),
+ seed_tracker: seed_tracker.clone(),
+ live_watermarks: live_watermarks.clone(),
register_transfer_enabled: false,
+ reconcile: ReconcileDeps {
+ enabled: true,
+ scan_page: 1,
+ backlog: reconcile_backlog.clone(),
+ },
});
let dispatcher = Arc::new(EventDispatcher::new(
PartitionRouter::new(64),
Arc::new(OffsetTracker::new()),
- StoreHandle::new(
- store,
- OffloadConfig {
- mode: OffloadMode::All,
- event_read_permits: 16,
- maintenance_permits: 6,
- },
- ),
+ store.clone(),
Arc::new(catalog),
membership_sink,
merge_deps,
@@ -597,7 +712,7 @@ async fn spawn_instance(
topics.seeds.clone(),
));
let seed_follower = SeedFollowerConsumer::new(
- seeds_consumer,
+ seeds_consumer.clone(),
topics.seeds.clone(),
events_client.clone(),
topics.events.clone(),
@@ -626,7 +741,15 @@ async fn spawn_instance(
);
tasks.push(tokio::spawn(events_consumer.process()));
- Instance { dispatcher, tasks }
+ Instance {
+ dispatcher,
+ store,
+ reconcile_backlog,
+ seed_tracker,
+ seed_consumer: seeds_consumer,
+ live_watermarks,
+ tasks,
+ }
}
/// A tile lands on its owning worker via the 5-topic co-assignment, applies behind an open
@@ -667,7 +790,14 @@ async fn seed_tile_applies_on_the_owning_worker_and_commits_to_the_hwm() {
let alice = Uuid::from_u128(0xA11CE);
// One folded live event opens the fence for the hour-old scan point.
let producer = murmur2_producer();
- produce_warm_event(&producer, &topics.events, alice, 0).await;
+ produce_warm_event(
+ &producer,
+ &topics.events,
+ alice,
+ 0,
+ chrono::Utc::now().timestamp_millis(),
+ )
+ .await;
let seed_sink = KafkaSeedTileSink::new(&producer_kafka_config(), topics.seeds.clone())
.await
@@ -715,24 +845,24 @@ async fn seed_tile_applies_on_the_owning_worker_and_commits_to_the_hwm() {
.await;
}
-/// A tile scanned "now" stays fenced until live consumption flows past `s_chunk + margin`.
+/// Partition-targeted controls drain a full 64-partition snapshot, repair a stale membership bit,
+/// and release each seed offset only after that partition's completion marker is acknowledged.
#[tokio::test]
#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]
-async fn fence_holds_a_fresh_tile_until_live_consumption_passes_its_scan_point() {
+async fn reconcile_snapshot_repairs_stale_state_and_commits_after_markers() {
let suffix = Uuid::new_v4();
let topics = Topics::unique(&suffix);
let groups = Groups::unique(&suffix);
with_topics_cleanup(&topics.names(), async {
topics.create().await;
- let mut manager = Manager::builder("seed-fence-itest")
+ let mut manager = Manager::builder("reconcile-e2e-itest")
.with_trap_signals(false)
.build();
let handles = register_instance(&mut manager);
let shutdown = handles[0].clone();
let _monitor = manager.monitor_background();
- let fence_margin_ms = 5_000;
let dir = TempDir::new().unwrap();
let instance = spawn_instance(
&topics,
@@ -740,7 +870,7 @@ async fn fence_holds_a_fresh_tile_until_live_consumption_passes_its_scan_point()
open_store(&dir),
seed_catalog(),
handles,
- fence_margin_ms,
+ 2_000,
)
.await;
wait_for(
@@ -750,15 +880,322 @@ async fn fence_holds_a_fresh_tile_until_live_consumption_passes_its_scan_point()
)
.await;
+ // This person has no leaf state, so current membership is false. The injected true
+ // register bit models an at-most-once output loss or an edit-path stale row.
+ let person = Uuid::from_u128(0xDEC0DE);
+ let person_partition = part(person);
+ let stage2_key = Stage2Key {
+ partition_id: person_partition,
+ team_id: TEAM as u64,
+ cohort_id: COHORT as u64,
+ person_id: person,
+ };
+ instance
+ .put_stage2(
+ &stage2_key,
+ &Stage2State {
+ in_cohort: true,
+ last_evaluated_at_ms: 1,
+ },
+ )
+ .await;
+ assert!(instance.stage2(&stage2_key).await.in_cohort);
+
+ let run_id = RunId(Uuid::from_u128(0xB4));
+ let reconcile = ReconcileTile::new(
+ TeamId(TEAM),
+ CohortId(COHORT),
+ BehavioralShapeHash::parse(FILTERS_HASH).unwrap(),
+ run_id,
+ );
+ let producer = murmur2_producer();
+
+ for partition in 0..NUM_PARTITIONS {
+ assert_eq!(
+ produce_reconcile(&producer, &topics.seeds, partition, &reconcile).await,
+ 0,
+ "a unique topic starts every partition at offset zero",
+ );
+ }
+ wait_for(
+ "all partition-targeted reconcile controls to be admitted",
+ Duration::from_secs(30),
+ || instance.reconcile_backlog.len() == i64::from(NUM_PARTITIONS),
+ )
+ .await;
+ let before_first_tick = seed_group_committed_offsets(&groups.seeds, &topics.seeds);
+ assert!(
+ before_first_tick.is_empty(),
+ "no reconcile control commits before draining starts",
+ );
+ assert!((0..NUM_PARTITIONS)
+ .all(|partition| { instance.seed_committable(partition as u16).is_none() }));
+
+ // scan_page=1 makes the stale row consume a whole first page. Every empty partition can
+ // emit its marker immediately, while this partition remains pinned after emitting `left`.
+ instance.dispatcher.route_reconcile_drain().await;
+ wait_for(
+ "63 empty-partition markers and one stale-row repair",
+ Duration::from_secs(60),
+ || topic_message_count(&topics.shadow) == NUM_PARTITIONS as i64,
+ )
+ .await;
+ wait_for(
+ "only the stale-row partition to remain queued",
+ Duration::from_secs(30),
+ || instance.reconcile_backlog.len() == 1,
+ )
+ .await;
+ assert_ne!(
+ seed_group_committed(&groups.seeds, &topics.seeds, person_partition as i32),
+ Some(1),
+ "the reconcile seed offset stays pinned before its marker",
+ );
+ assert_eq!(
+ instance.seed_committable(person_partition),
+ None,
+ "the production tracker stays pinned immediately after the row and before its marker",
+ );
+ assert!(!instance.stage2(&stage2_key).await.in_cohort);
+
+ let first_page = consume_all(
+ &topics.shadow,
+ NUM_PARTITIONS as usize,
+ Duration::from_secs(30),
+ )
+ .await;
+ let mut first_changes = Vec::new();
+ let mut first_markers = Vec::new();
+ for (_, payload) in first_page {
+ let value: serde_json::Value = serde_json::from_slice(&payload).unwrap();
+ if value.get("type").and_then(serde_json::Value::as_str) == Some("reconcile_complete") {
+ first_markers
+ .push(serde_json::from_slice::<ReconcileCompleteMarker>(&payload).unwrap());
+ } else {
+ first_changes
+ .push(serde_json::from_slice::<CohortMembershipChange>(&payload).unwrap());
+ }
+ }
+ assert_eq!(first_changes.len(), 1);
+ assert_eq!(first_changes[0].person_id, person.to_string());
+ assert_eq!(first_changes[0].status, MembershipStatus::Left);
+ assert_eq!(first_changes[0].origin, Some(ChangeOrigin::Reconcile));
+ assert_eq!(first_changes[0].run_id, Some(run_id));
+ assert_eq!(first_markers.len(), NUM_PARTITIONS as usize - 1);
+ assert!(!first_markers
+ .iter()
+ .any(|marker| marker.partition() == person_partition));
+
+ instance.dispatcher.route_reconcile_drain().await;
+ wait_for(
+ "the final partition marker",
+ Duration::from_secs(30),
+ || topic_message_count(&topics.shadow) == i64::from(NUM_PARTITIONS) + 1,
+ )
+ .await;
+ wait_for(
+ "all reconcile jobs to complete",
+ Duration::from_secs(30),
+ || instance.reconcile_backlog.is_empty(),
+ )
+ .await;
+ wait_for(
+ "every seed partition commit to advance past its marker",
+ Duration::from_secs(30),
+ || {
+ let offsets = seed_group_committed_offsets(&groups.seeds, &topics.seeds);
+ (0..NUM_PARTITIONS).all(|partition| offsets.get(&partition) == Some(&1))
+ },
+ )
+ .await;
+ assert!((0..NUM_PARTITIONS)
+ .all(|partition| { instance.seed_committable(partition as u16) == Some(1) }));
+
+ let first_snapshot = consume_all(
+ &topics.shadow,
+ NUM_PARTITIONS as usize + 1,
+ Duration::from_secs(30),
+ )
+ .await;
+ let mut marker_partitions = HashSet::new();
+ let mut snapshot_changes = Vec::new();
+ for (_, payload) in first_snapshot {
+ let value: serde_json::Value = serde_json::from_slice(&payload).unwrap();
+ if value.get("type").and_then(serde_json::Value::as_str) == Some("reconcile_complete") {
+ let marker: ReconcileCompleteMarker = serde_json::from_slice(&payload).unwrap();
+ assert_eq!(marker.team_id(), TeamId(TEAM));
+ assert_eq!(marker.cohort_id(), CohortId(COHORT));
+ assert_eq!(marker.run_id(), run_id);
+ marker_partitions.insert(marker.partition());
+ } else {
+ snapshot_changes
+ .push(serde_json::from_slice::<CohortMembershipChange>(&payload).unwrap());
+ }
+ }
+ let expected_marker_partitions: HashSet<u16> = (0..COHORT_PARTITION_COUNT)
+ .map(|partition| partition as u16)
+ .collect();
+ assert_eq!(marker_partitions, expected_marker_partitions);
+ assert_eq!(snapshot_changes.len(), 1);
+ assert_eq!(snapshot_changes[0].status, MembershipStatus::Left);
+
+ // A duplicate manual dispatch emits the same full snapshot and certificate set, leaves the
+ // repaired bit unchanged, and advances every partition by exactly one more seed offset.
+ for partition in 0..NUM_PARTITIONS {
+ assert_eq!(
+ produce_reconcile(&producer, &topics.seeds, partition, &reconcile).await,
+ 1,
+ );
+ }
+ wait_for(
+ "the duplicate reconcile controls to be admitted",
+ Duration::from_secs(30),
+ || instance.reconcile_backlog.len() == i64::from(NUM_PARTITIONS),
+ )
+ .await;
+ instance.dispatcher.route_reconcile_drain().await;
+ wait_for(
+ "the duplicate snapshot first page",
+ Duration::from_secs(60),
+ || topic_message_count(&topics.shadow) == i64::from(NUM_PARTITIONS) * 2 + 1,
+ )
+ .await;
+ assert_eq!(
+ seed_group_committed(&groups.seeds, &topics.seeds, person_partition as i32),
+ Some(1),
+ "redispatch stays pinned at the prior next-offset until its new marker",
+ );
+ assert_eq!(
+ instance.seed_committable(person_partition),
+ Some(1),
+ "the production tracker stays at the prior next-offset before the new marker",
+ );
+ instance.dispatcher.route_reconcile_drain().await;
+ wait_for(
+ "the duplicate snapshot marker set",
+ Duration::from_secs(30),
+ || topic_message_count(&topics.shadow) == i64::from(NUM_PARTITIONS) * 2 + 2,
+ )
+ .await;
+ wait_for(
+ "every redispatched seed partition commit to advance",
+ Duration::from_secs(30),
+ || {
+ let offsets = seed_group_committed_offsets(&groups.seeds, &topics.seeds);
+ (0..NUM_PARTITIONS).all(|partition| offsets.get(&partition) == Some(&2))
+ },
+ )
+ .await;
+ assert!((0..NUM_PARTITIONS)
+ .all(|partition| { instance.seed_committable(partition as u16) == Some(2) }));
+ assert!(!instance.stage2(&stage2_key).await.in_cohort);
+
+ let converged = consume_all(
+ &topics.shadow,
+ (NUM_PARTITIONS as usize * 2) + 2,
+ Duration::from_secs(30),
+ )
+ .await;
+ let mut marker_counts = HashMap::<u16, usize>::new();
+ let mut reconcile_changes = Vec::new();
+ for (_, payload) in converged {
+ let value: serde_json::Value = serde_json::from_slice(&payload).unwrap();
+ if value.get("type").and_then(serde_json::Value::as_str) == Some("reconcile_complete") {
+ let marker: ReconcileCompleteMarker = serde_json::from_slice(&payload).unwrap();
+ assert_eq!(marker.team_id(), TeamId(TEAM));
+ assert_eq!(marker.cohort_id(), CohortId(COHORT));
+ assert_eq!(marker.run_id(), run_id);
+ *marker_counts.entry(marker.partition()).or_default() += 1;
+ } else {
+ reconcile_changes
+ .push(serde_json::from_slice::<CohortMembershipChange>(&payload).unwrap());
+ }
+ }
+ assert_eq!(
+ marker_counts.keys().copied().collect::<HashSet<_>>(),
+ expected_marker_partitions,
+ );
+ assert!(marker_counts.values().all(|count| *count == 2));
+ assert_eq!(reconcile_changes.len(), 2);
+ assert!(reconcile_changes.iter().all(|change| {
+ change.person_id == person.to_string()
+ && change.status == MembershipStatus::Left
+ && change.origin == Some(ChangeOrigin::Reconcile)
+ && change.run_id == Some(run_id)
+ }));
+
+ shutdown.request_shutdown();
+ instance.join().await;
+ })
+ .await;
+}
+
+/// A tile scanned "now" stays fenced until live consumption flows past `s_chunk + margin`.
+#[tokio::test]
+#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]
+async fn fence_holds_a_fresh_tile_until_live_consumption_passes_its_scan_point() {
+ let suffix = Uuid::new_v4();
+ let topics = Topics::unique(&suffix);
+ let groups = Groups::unique(&suffix);
+ with_topics_cleanup(&topics.names(), async {
+ topics.create().await;
+
+ // Put both same-partition records on the broker before the follower starts so its first
+ // receive batch can observe the closed tile and the FIFO suffix together.
let alice = Uuid::from_u128(0xA11CE);
+ let fence_margin_ms = 5_000;
+ let producer = murmur2_producer();
let seed_sink = KafkaSeedTileSink::new(&producer_kafka_config(), topics.seeds.clone())
.await
.expect("create test seed sink");
let s_chunk = chrono::Utc::now().timestamp_millis();
produce_tile(&seed_sink, tile(alice, s_chunk)).await;
+ let run_id = RunId(Uuid::from_u128(0x0F3E_CEC0));
+ let reconcile = ReconcileTile::new(
+ TeamId(TEAM),
+ CohortId(COHORT),
+ BehavioralShapeHash::parse(FILTERS_HASH).unwrap(),
+ run_id,
+ );
+ assert_eq!(
+ produce_reconcile(&producer, &topics.seeds, part(alice) as i32, &reconcile,).await,
+ 1,
+ "the reconcile control follows the closed data tile in the same partition",
+ );
+
+ let mut manager = Manager::builder("seed-fence-itest")
+ .with_trap_signals(false)
+ .build();
+ let handles = register_instance(&mut manager);
+ let shutdown = handles[0].clone();
+ let _monitor = manager.monitor_background();
- // No watermark at all: fail-closed, nothing applies, nothing commits.
- tokio::time::sleep(Duration::from_secs(3)).await;
+ let dir = TempDir::new().unwrap();
+ let instance = spawn_instance(
+ &topics,
+ &groups,
+ open_store(&dir),
+ seed_catalog(),
+ handles,
+ fence_margin_ms,
+ )
+ .await;
+ wait_for(
+ "the consumer to own every partition",
+ Duration::from_secs(30),
+ || instance.owned().len() == NUM_PARTITIONS as usize,
+ )
+ .await;
+
+ // No watermark at all: wait until Kafka has delivered both records, then give the follower
+ // a full receive/commit cycle to expose any accidental reconcile admission.
+ wait_for(
+ "the seed consumer to fetch the closed tile and its FIFO suffix",
+ Duration::from_secs(30),
+ || instance.seed_position(&topics.seeds, part(alice)) == Some(2),
+ )
+ .await;
+ tokio::time::sleep(COMMIT_INTERVAL + RECV_TIMEOUT + Duration::from_millis(250)).await;
assert_eq!(
topic_message_count(&topics.shadow),
0,
@@ -769,34 +1206,104 @@ async fn fence_holds_a_fresh_tile_until_live_consumption_passes_its_scan_point()
None,
"a held tile's offset must never commit",
);
+ assert!(
+ instance.reconcile_backlog.is_empty(),
+ "reconcile must not leapfrog a closed data tile",
+ );
+ assert_eq!(instance.seed_committable(part(alice)), None);
- // A live event folded before `s_chunk + margin` has elapsed still leaves the fence closed.
- let producer = murmur2_producer();
- produce_warm_event(&producer, &topics.events, alice, 0).await;
- tokio::time::sleep(Duration::from_secs(2)).await;
+ // A live event at the exact bound still leaves the fence closed. Its explicit broker
+ // timestamp makes the assertion independent of manager startup and machine speed.
+ let closed_watermark = s_chunk + fence_margin_ms;
+ produce_warm_event(&producer, &topics.events, alice, 0, closed_watermark).await;
+ wait_for(
+ "the below-threshold live watermark to fold",
+ Duration::from_secs(30),
+ || instance.live_watermark(part(alice)) == Some(closed_watermark),
+ )
+ .await;
assert_eq!(
topic_message_count(&topics.shadow),
0,
"a watermark below s_chunk + margin keeps the fence closed",
);
+ assert!(instance.reconcile_backlog.is_empty());
- // Past s_chunk + margin, a newer live fold opens the fence for the held tile.
- tokio::time::sleep(Duration::from_millis(fence_margin_ms as u64 + 1_500)).await;
- produce_warm_event(&producer, &topics.events, alice, 1).await;
+ // One millisecond past the bound, a newer live fold opens the fence for the tile and then
+ // admits the reconcile control behind it. The tile materializes the scan register first.
+ produce_warm_event(&producer, &topics.events, alice, 1, closed_watermark + 1).await;
wait_for(
"the fence to open and the held tile to apply",
Duration::from_secs(60),
|| topic_message_count(&topics.shadow) == 1,
)
.await;
- let (_, payload) = consume_all(&topics.shadow, 1, Duration::from_secs(30))
- .await
- .into_iter()
- .next()
- .expect("one membership change");
- let change: CohortMembershipChange = serde_json::from_slice(&payload).unwrap();
- assert_eq!(change.origin, Some(ChangeOrigin::Seed));
- assert_eq!(change.person_id, alice.to_string());
+ wait_for(
+ "the reconcile control behind the opened tile to be admitted",
+ Duration::from_secs(30),
+ || instance.reconcile_backlog.len() == 1,
+ )
+ .await;
+ assert_eq!(
+ instance.seed_committable(part(alice)),
+ Some(1),
+ "the applied data tile advances to the following deferred control",
+ );
+
+ instance.dispatcher.route_reconcile_drain().await;
+ wait_for(
+ "the reconcile membership row",
+ Duration::from_secs(30),
+ || topic_message_count(&topics.shadow) == 2,
+ )
+ .await;
+ assert_eq!(instance.reconcile_backlog.len(), 1);
+ assert_eq!(
+ instance.seed_committable(part(alice)),
+ Some(1),
+ "the control remains deferred after its row and before its marker",
+ );
+
+ instance.dispatcher.route_reconcile_drain().await;
+ wait_for(
+ "the reconcile completion marker",
+ Duration::from_secs(30),
+ || topic_message_count(&topics.shadow) == 3,
+ )
+ .await;
+ assert!(instance.reconcile_backlog.is_empty());
+ assert_eq!(instance.seed_committable(part(alice)), Some(2));
+ wait_for(
+ "the seed group to commit both FIFO messages",
+ Duration::from_secs(30),
+ || seed_group_committed(&groups.seeds, &topics.seeds, part(alice) as i32) == Some(2),
+ )
+ .await;
+
+ let outputs = consume_all(&topics.shadow, 3, Duration::from_secs(30)).await;
+ let mut changes = Vec::new();
+ let mut markers = Vec::new();
+ for (_, payload) in outputs {
+ let value: serde_json::Value = serde_json::from_slice(&payload).unwrap();
+ if value.get("type").and_then(serde_json::Value::as_str) == Some("reconcile_complete") {
+ markers.push(serde_json::from_slice::<ReconcileCompleteMarker>(&payload).unwrap());
+ } else {
+ changes.push(serde_json::from_slice::<CohortMembershipChange>(&payload).unwrap());
+ }
+ }
+ assert_eq!(changes.len(), 2);
+ assert!(changes.iter().any(|change| {
+ change.person_id == alice.to_string() && change.origin == Some(ChangeOrigin::Seed)
+ }));
+ assert!(changes.iter().any(|change| {
+ change.person_id == alice.to_string()
+ && change.status == MembershipStatus::Entered
+ && change.origin == Some(ChangeOrigin::Reconcile)
+ && change.run_id == Some(run_id)
+ }));
+ assert_eq!(markers.len(), 1);
+ assert_eq!(markers[0].partition(), part(alice));
+ assert_eq!(markers[0].run_id(), run_id);
shutdown.request_shutdown();
instance.join().await;
diff --git a/rust/cohort-stream-processor/tests/sweep_worker.rs b/rust/cohort-stream-processor/tests/sweep_worker.rs
index 97541d8751dc..45fde3e3c72f 100644
--- a/rust/cohort-stream-processor/tests/sweep_worker.rs
+++ b/rust/cohort-stream-processor/tests/sweep_worker.rs
@@ -27,7 +27,7 @@ use cohort_stream_processor::partitions::{
MeteredReceiver, OffsetTracker, PartitionRouter, ShuffleMessage,
};
use cohort_stream_processor::producer::{
- CaptureSink, CohortMembershipChange, MembershipSink, MembershipStatus,
+ CaptureSink, CohortMembershipChange, MembershipSink, MembershipStatus, ReconcileCompleteMarker,
};
use cohort_stream_processor::stage1::bucket_tz::{day_idx_in_tz, start_of_day_ms_in_tz};
use cohort_stream_processor::stage1::{
@@ -1240,6 +1240,16 @@ impl MembershipSink for FailNthSink {
self.changes.lock().unwrap().extend(changes);
acks
}
+
+ async fn produce_markers(
+ &self,
+ markers: Vec<ReconcileCompleteMarker>,
+ ) -> Vec<Result<(), KafkaProduceError>> {
+ markers
+ .into_iter()
+ .map(|_| Err(KafkaProduceError::KafkaProduceCanceled))
+ .collect()
+ }
}
#[tokio::test]