:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cohorts): add cohort-seeder backfill binary (#71145)
Matheus Batista26baa8f0dceb
diff --git a/.github/rust-images.yml b/.github/rust-images.ymlindex 75fc66dfae60..3c37b44ef3a0 100644--- a/.github/rust-images.yml+++ b/.github/rust-images.yml@@ -72,6 +72,10 @@dockerfile: ./rust/Dockerfileproject: vglf58qgzw+- image: cohort-seeder+ dockerfile: ./rust/Dockerfile+ project: vglf58qgzw+- image: cohort-stream-processordockerfile: ./rust/Dockerfileproject: vglf58qgzwdiff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.ymlindex af419e8629b2..2c36f80cf4bf 100644--- a/.github/workflows/ci-rust.yml+++ b/.github/workflows/ci-rust.yml@@ -135,6 +135,7 @@ jobs:"common-profiler": 51,"common-s3": 31,"cohort-core": 45,+ "cohort-seeder": 60,"cyclotron-core": 17,"cyclotron-janitor": 139,"cyclotron-node": 31,@@ -444,7 +445,11 @@ jobs:if [ "$pkg" = "property-defs-rs" ]; thenextra_args="--test-threads=4"fi- run_nextest "$pkg" -p "$pkg" $extra_args+ if [ "$pkg" = "cohort-seeder" ] && [ -f cohort-seeder/Cargo.toml ] && grep -q '^pg-test-support[[:space:]]*=' cohort-seeder/Cargo.toml; then+ DATABASE_URL='postgres://posthog:posthog@localhost:5432/test_posthog' run_nextest "$pkg" -p "$pkg" --features pg-test-support $extra_args+ else+ run_nextest "$pkg" -p "$pkg" $extra_args+ fi# nextest skips doctests; run them only for packages with a lib target# (`cargo test --doc` errors on bin-only packages).if cargo metadata --no-deps --format-version 1 | jq -e --arg p "$pkg" '[.packages[] | select(.name == $p) | .targets[] | select(.kind | index("lib"))] | length > 0' >/dev/null; thendiff --git a/rust/Cargo.lock b/rust/Cargo.lockindex f1e34632ccb6..681341a9a9a6 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2228,6 +2228,39 @@ dependencies = ["uuid",]+[[package]]+name = "cohort-seeder"+version = "0.1.0"+dependencies = [+ "anyhow",+ "axum 0.7.9",+ "chrono",+ "chrono-tz",+ "clickhouse",+ "cohort-core",+ "common-alloc",+ "common-database",+ "common-kafka",+ "common-liveness",+ "common-types",+ "envconfig",+ "governor",+ "lifecycle",+ "metrics",+ "metrics-exporter-prometheus",+ "proptest",+ "rdkafka",+ "serde",+ "serde_json",+ "sqlx",+ "thiserror 2.0.18",+ "tokio",+ "tokio-util",+ "tracing",+ "tracing-subscriber",+ "uuid",+]+[[package]]name = "cohort-stream-processor"version = "0.1.0"diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex dbfb2e11bb9f..8815f3da81a1 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -9,6 +9,7 @@ members = ["capture-logs","cohort-core","cohort-event-shuffler",+ "cohort-seeder","cohort-stream-processor","common/alloc","common/assignment-coordination",diff --git a/rust/cohort-core/src/lib.rs b/rust/cohort-core/src/lib.rsindex 5ef93d881116..bc335cf9ac73 100644--- a/rust/cohort-core/src/lib.rs+++ b/rust/cohort-core/src/lib.rs@@ -31,6 +31,7 @@ pub mod hogvm;pub mod leaf_state;pub mod metrics;pub mod partitioner;+pub mod seed;pub mod timestamp;pub use bucket_tz::{diff --git a/rust/cohort-core/src/seed/decode.rs b/rust/cohort-core/src/seed/decode.rsnew file mode 100644index 000000000000..3f3c5c873310--- /dev/null+++ b/rust/cohort-core/src/seed/decode.rs@@ -0,0 +1,107 @@+//! 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'+//! consumers, and a malformed payload is deterministic bytes that would fail identically on every+//! redelivery.++use serde::Deserialize;++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.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum DecodedSeed {+ Tile(SeedTile),+ UnknownKind { kind: String, schema_version: u32 },+ UnsupportedSchema { kind: String, schema_version: u32 },+}++#[derive(Deserialize)]+struct SeedProbe {+ kind: String,+ schema_version: u32,+}++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 {+ kind: probe.kind,+ schema_version: probe.schema_version,+ });+ }+ if probe.schema_version != SCHEMA_VERSION {+ return Ok(DecodedSeed::UnsupportedSchema {+ kind: probe.kind,+ schema_version: probe.schema_version,+ });+ }+ Ok(DecodedSeed::Tile(serde_json::from_slice(payload)?))+}++#[cfg(test)]+mod tests {+ use std::num::NonZeroU32;++ use uuid::Uuid;++ use crate::filters::TeamId;+ use crate::seed::{ClaimEpoch, ConditionHash, RunId, SChunkMs};++ use super::*;++ fn tile_json() -> serde_json::Value {+ serde_json::to_value(SeedTile::new(+ TeamId(2),+ Uuid::from_u128(7),+ ConditionHash::parse("0123456789abcdef").unwrap(),+ NonZeroU32::new(3).unwrap(),+ 19,+ SChunkMs(1_700_000_000_000),+ RunId(Uuid::nil()),+ ClaimEpoch(1),+ ))+ .unwrap()+ }++ #[test]+ fn decode_probes_kind_and_schema_before_the_full_parse() {+ let tile = tile_json();+ let decode = |value: &serde_json::Value| decode_seed(&serde_json::to_vec(value).unwrap());++ assert!(matches!(decode(&tile).unwrap(), DecodedSeed::Tile(_)));++ let mut reconcile = tile.clone();+ reconcile["kind"] = serde_json::json!("reconcile");+ assert_eq!(+ decode(&reconcile).unwrap(),+ DecodedSeed::UnknownKind {+ kind: "reconcile".to_string(),+ schema_version: 1,+ }+ );++ let mut newer = tile.clone();+ newer["schema_version"] = serde_json::json!(2);+ assert_eq!(+ decode(&newer).unwrap(),+ DecodedSeed::UnsupportedSchema {+ kind: "behavioral_tile".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 kindless = tile;+ kindless.as_object_mut().unwrap().remove("kind");+ assert!(decode(&kindless).is_err());+ assert!(decode_seed(b"not json").is_err());+ }+}diff --git a/rust/cohort-core/src/seed/ids.rs b/rust/cohort-core/src/seed/ids.rsnew file mode 100644index 000000000000..98b0c566a515--- /dev/null+++ b/rust/cohort-core/src/seed/ids.rs@@ -0,0 +1,107 @@+//! The seed contract's newtyped ids: `RunId`, `ClaimEpoch`, `SChunkMs`, and `ConditionHash`. They+//! ride the [`super::tile::SeedTile`] wire and the seeder's PostgreSQL ledger (hence the `sqlx`+//! derives), so both ends resolve them to the same types.++use std::borrow::Borrow;+use std::fmt;+use std::str::FromStr;++use serde::{Deserialize, Serialize};+use sqlx::Type;+use uuid::Uuid;++#[derive(+ Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Type,+)]+#[serde(transparent)]+#[sqlx(transparent)]+pub struct RunId(pub Uuid);++#[derive(+ Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Type,+)]+#[serde(transparent)]+#[sqlx(transparent)]+pub struct ClaimEpoch(pub i32);++/// The chunk's scan instant (epoch ms, UTC): the arrival upper bound of the tile's domain and the+/// consumer's fence input. Rides re-keyed tiles verbatim.+#[derive(+ Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Type,+)]+#[serde(transparent)]+#[sqlx(transparent)]+pub struct SChunkMs(pub i64);++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct ConditionHash([u8; 16]);++impl ConditionHash {+ pub fn parse(value: &str) -> Result<Self, ConditionHashError> {+ if value.len() != 16 {+ return Err(ConditionHashError::Length(value.len()));+ }+ if !value.is_ascii() {+ return Err(ConditionHashError::NonAscii);+ }+ let mut bytes = [0; 16];+ bytes.copy_from_slice(value.as_bytes());+ Ok(Self(bytes))+ }++ pub const fn as_bytes(self) -> [u8; 16] {+ self.0+ }++ pub fn as_str(&self) -> &str {+ std::str::from_utf8(&self.0)+ .expect("ASCII by construction: parse() is the only constructor")+ }+}++impl Borrow<[u8; 16]> for ConditionHash {+ fn borrow(&self) -> &[u8; 16] {+ &self.0+ }+}++impl fmt::Display for ConditionHash {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter.write_str(self.as_str())+ }+}++impl FromStr for ConditionHash {+ type Err = ConditionHashError;++ fn from_str(value: &str) -> Result<Self, Self::Err> {+ Self::parse(value)+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]+pub enum ConditionHashError {+ #[error("conditionHash must be exactly 16 bytes, got {0}")]+ Length(usize),+ #[error("conditionHash must contain only ASCII characters")]+ NonAscii,+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn condition_hash_accepts_only_the_catalogs_literal_ascii_shape() {+ let hash = ConditionHash::parse("0123456789abcdef").unwrap();+ assert_eq!(hash.as_str(), "0123456789abcdef");+ assert_eq!(hash.as_bytes(), *b"0123456789abcdef");++ for invalid in ["0123456789abcde", "0123456789abcdefg", "é23456789abcdef"] {+ assert!(+ ConditionHash::parse(invalid).is_err(),+ "accepted {invalid:?}"+ );+ }+ }+}diff --git a/rust/cohort-core/src/seed/mod.rs b/rust/cohort-core/src/seed/mod.rsnew file mode 100644index 000000000000..92b05acbef00--- /dev/null+++ b/rust/cohort-core/src/seed/mod.rs@@ -0,0 +1,16 @@+//! 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.+//!+//! 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.++pub mod decode;+pub mod ids;+pub mod tile;++pub use decode::{decode_seed, DecodedSeed};+pub use ids::{ClaimEpoch, ConditionHash, ConditionHashError, RunId, SChunkMs};+pub use tile::SeedTile;diff --git a/rust/cohort-core/src/seed/tile.rs b/rust/cohort-core/src/seed/tile.rsnew file mode 100644index 000000000000..6c0b8fd766ba--- /dev/null+++ b/rust/cohort-core/src/seed/tile.rs@@ -0,0 +1,308 @@+//! `SeedTile`, the wire-frozen unit produced to `cohort_stream_seed_events` and applied by the+//! stream processor — typed private fields, a total constructor, and serde that emits exactly the+//! frozen JSON primitives. The golden test in this module is the byte-level regression gate.++use std::num::NonZeroU32;++use serde::de::{Deserializer, Error as DeError, Unexpected};+use serde::ser::Serializer;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use crate::bucket_tz::DayIdx;+use crate::filters::TeamId;++use super::ids::{ClaimEpoch, ConditionHash, RunId, SChunkMs};++pub(super) const SCHEMA_VERSION: u32 = 1;+pub(super) const TILE_KIND: &str = "behavioral_tile";++/// One `(person, condition, day)` absolute count. Field order is the wire order; new fields must+/// be appended and skipped at their absent-equivalent value (`redirect_hops`) so older payloads+/// keep parsing and seeder-produced bytes stay frozen.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct SeedTile {+ #[serde(deserialize_with = "deserialize_schema_version")]+ schema_version: u32,+ kind: TileKind,+ #[serde(+ serialize_with = "serialize_team_id",+ deserialize_with = "deserialize_team_id"+ )]+ team_id: TeamId,+ person_id: Uuid,+ #[serde(+ serialize_with = "serialize_condition_hash",+ deserialize_with = "deserialize_condition_hash"+ )]+ condition_hash: ConditionHash,+ day_idx: DayIdx,+ count: NonZeroU32,+ run_id: RunId,+ s_chunk_ms: SChunkMs,+ claim_epoch: ClaimEpoch,+ /// Times this tile has been re-produced to a merge survivor's partition. Absent on the wire at+ /// 0, so tiles the seeder emits are byte-identical to the pre-field contract.+ #[serde(default, skip_serializing_if = "hops_are_zero")]+ redirect_hops: u8,+}++impl SeedTile {+ #[allow(clippy::too_many_arguments)]+ pub fn new(+ team_id: TeamId,+ person_id: Uuid,+ condition_hash: ConditionHash,+ count: NonZeroU32,+ day_idx: DayIdx,+ s_chunk_ms: SChunkMs,+ run_id: RunId,+ claim_epoch: ClaimEpoch,+ ) -> Self {+ Self {+ schema_version: SCHEMA_VERSION,+ kind: TileKind,+ team_id,+ person_id,+ condition_hash,+ day_idx,+ count,+ run_id,+ s_chunk_ms,+ claim_epoch,+ redirect_hops: 0,+ }+ }++ /// The tile re-keyed to a merge survivor, or `None` once `cap` hops are exhausted — an+ /// over-cap re-produce is unrepresentable, so the caller must handle the cap arm explicitly.+ /// `s_chunk_ms` rides verbatim: the fence re-checks at the target partition against the+ /// original scan instant.+ #[must_use]+ pub fn rekeyed_to(&self, survivor: Uuid, cap: u8) -> Option<Self> {+ let redirect_hops = self+ .redirect_hops+ .checked_add(1)+ .filter(|hops| *hops <= cap)?;+ Some(Self {+ person_id: survivor,+ redirect_hops,+ ..self.clone()+ })+ }++ pub fn partition_key(&self) -> String {+ format!("{}:{}", self.team_id.0, self.person_id)+ }++ pub const fn team_id(&self) -> TeamId {+ self.team_id+ }++ pub const fn person_id(&self) -> Uuid {+ self.person_id+ }++ pub const fn condition_hash(&self) -> ConditionHash {+ self.condition_hash+ }++ pub const fn day_idx(&self) -> DayIdx {+ self.day_idx+ }++ pub const fn count(&self) -> u32 {+ self.count.get()+ }++ pub const fn run_id(&self) -> RunId {+ self.run_id+ }++ pub const fn s_chunk_ms(&self) -> SChunkMs {+ self.s_chunk_ms+ }++ pub const fn claim_epoch(&self) -> ClaimEpoch {+ self.claim_epoch+ }++ pub const fn redirect_hops(&self) -> u8 {+ self.redirect_hops+ }+}++/// The `kind` discriminant, zero-sized and proven to be [`TILE_KIND`] by parse — a borrowed+/// `&'static str` field would force `Deserialize<'static>` on the whole tile.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+struct TileKind;++impl Serialize for TileKind {+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {+ serializer.serialize_str(TILE_KIND)+ }+}++impl<'de> Deserialize<'de> for TileKind {+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ let value = String::deserialize(deserializer)?;+ if value != TILE_KIND {+ return Err(DeError::invalid_value(+ Unexpected::Str(&value),+ &"seed kind \"behavioral_tile\"",+ ));+ }+ Ok(Self)+ }+}++fn hops_are_zero(hops: &u8) -> bool {+ *hops == 0+}++fn serialize_team_id<S: Serializer>(value: &TeamId, serializer: S) -> Result<S::Ok, S::Error> {+ serializer.serialize_i32(value.0)+}++fn deserialize_team_id<'de, D: Deserializer<'de>>(deserializer: D) -> Result<TeamId, D::Error> {+ i32::deserialize(deserializer).map(TeamId)+}++fn serialize_condition_hash<S: Serializer>(+ value: &ConditionHash,+ serializer: S,+) -> Result<S::Ok, S::Error> {+ serializer.serialize_str(value.as_str())+}++fn deserialize_condition_hash<'de, D: Deserializer<'de>>(+ deserializer: D,+) -> Result<ConditionHash, D::Error> {+ let value = String::deserialize(deserializer)?;+ ConditionHash::parse(&value)+ .map_err(|_| DeError::invalid_value(Unexpected::Str(&value), &"a 16-byte ASCII hash"))+}++fn deserialize_schema_version<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u32, D::Error> {+ let value = u32::deserialize(deserializer)?;+ if value != SCHEMA_VERSION {+ return Err(DeError::invalid_value(+ Unexpected::Unsigned(u64::from(value)),+ &"seed tile schema version 1",+ ));+ }+ Ok(value)+}++#[cfg(test)]+mod tests {+ use crate::partitioner::{partition_for, COHORT_PARTITION_COUNT};++ use super::*;++ fn tile() -> SeedTile {+ SeedTile::new(+ TeamId(2),+ Uuid::from_u128(0x0192_8aaa_bbbb_cccc_dddd_eeee_eeee_eeee),+ ConditionHash::parse("0123456789abcdef").unwrap(),+ NonZeroU32::new(3).unwrap(),+ 19,+ SChunkMs(1_700_000_000_000),+ RunId(Uuid::nil()),+ ClaimEpoch(7),+ )+ }++ #[test]+ fn tile_wire_contract_and_partition_key_are_fixed_by_construction() {+ let tile = tile();+ assert_eq!(+ tile.partition_key(),+ "2:01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee"+ );+ assert_eq!(+ partition_for(&tile.partition_key(), COHORT_PARTITION_COUNT),+ 58+ );+ assert_eq!(+ serde_json::to_value(&tile).unwrap(),+ serde_json::json!({+ "schema_version": 1,+ "kind": "behavioral_tile",+ "team_id": 2,+ "person_id": "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee",+ "condition_hash": "0123456789abcdef",+ "day_idx": 19,+ "count": 3,+ "run_id": "00000000-0000-0000-0000-000000000000",+ "s_chunk_ms": 1_700_000_000_000_i64,+ "claim_epoch": 7,+ })+ );+ assert_eq!(+ serde_json::to_string(&tile).unwrap(),+ r#"{"schema_version":1,"kind":"behavioral_tile","team_id":2,"person_id":"01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee","condition_hash":"0123456789abcdef","day_idx":19,"count":3,"run_id":"00000000-0000-0000-0000-000000000000","s_chunk_ms":1700000000000,"claim_epoch":7}"#+ );+ }++ #[test]+ fn tile_roundtrips_and_rejects_foreign_kind_schema_and_zero_count() {+ let tile = tile();+ let bytes = serde_json::to_vec(&tile).unwrap();+ assert_eq!(serde_json::from_slice::<SeedTile>(&bytes).unwrap(), tile);++ let golden = serde_json::to_value(&tile).unwrap();+ for (field, value) in [+ ("kind", serde_json::json!("reconcile")),+ ("schema_version", serde_json::json!(2)),+ ("count", serde_json::json!(0)),+ ("condition_hash", serde_json::json!("too-short")),+ ] {+ let mut broken = golden.clone();+ broken[field] = value;+ assert!(+ serde_json::from_value::<SeedTile>(broken).is_err(),+ "accepted a tile with mutated {field}"+ );+ }+ }++ #[test]+ fn redirect_hops_are_absent_at_zero_and_roundtrip_when_set() {+ let tile = tile();+ assert!(!serde_json::to_string(&tile)+ .unwrap()+ .contains("redirect_hops"));++ let hopped = tile+ .rekeyed_to(Uuid::from_u128(1), 3)+ .and_then(|tile| tile.rekeyed_to(Uuid::from_u128(2), 3))+ .and_then(|tile| tile.rekeyed_to(Uuid::from_u128(3), 3))+ .unwrap();+ assert_eq!(hopped.redirect_hops(), 3);+ let encoded = serde_json::to_string(&hopped).unwrap();+ assert!(encoded.contains(r#""redirect_hops":3"#));+ assert_eq!(serde_json::from_str::<SeedTile>(&encoded).unwrap(), hopped);+ }++ #[test]+ fn rekeyed_to_swaps_the_person_rides_s_chunk_verbatim_and_exhausts_at_the_cap() {+ let tile = tile();+ let survivor = Uuid::from_u128(0xdead_beef);+ let rekeyed = tile.rekeyed_to(survivor, 2).unwrap();+ assert_eq!(rekeyed.person_id(), survivor);+ assert_eq!(rekeyed.redirect_hops(), 1);+ assert_eq!(rekeyed.s_chunk_ms(), tile.s_chunk_ms());+ assert_eq!(rekeyed.team_id(), tile.team_id());+ assert_eq!(rekeyed.condition_hash(), tile.condition_hash());+ assert_eq!(rekeyed.day_idx(), tile.day_idx());+ assert_eq!(rekeyed.count(), tile.count());+ assert_eq!(rekeyed.run_id(), tile.run_id());+ assert_eq!(rekeyed.claim_epoch(), tile.claim_epoch());++ let at_cap = rekeyed.rekeyed_to(survivor, 2).unwrap();+ assert_eq!(at_cap.redirect_hops(), 2);+ assert!(at_cap.rekeyed_to(survivor, 2).is_none());+ assert!(tile.rekeyed_to(survivor, 0).is_none());+ }+}diff --git a/rust/cohort-seeder/Cargo.toml b/rust/cohort-seeder/Cargo.tomlnew file mode 100644index 000000000000..2b05f081f7e7--- /dev/null+++ b/rust/cohort-seeder/Cargo.toml@@ -0,0 +1,41 @@+[package]+name = "cohort-seeder"+version = "0.1.0"+edition = "2021"++[lints]+workspace = true++[features]+pg-test-support = []++[dependencies]+anyhow = { workspace = true }+axum = { workspace = true }+chrono = { workspace = true }+chrono-tz = { workspace = true }+clickhouse = { workspace = true }+cohort-core = { path = "../cohort-core" }+common-alloc = { path = "../common/alloc" }+common-database = { path = "../common/database" }+common-kafka = { path = "../common/kafka" }+common-liveness = { path = "../common/liveness" }+common-types = { path = "../common/types" }+envconfig = { workspace = true }+governor = { workspace = true }+lifecycle = { path = "../common/lifecycle" }+metrics = { workspace = true }+metrics-exporter-prometheus = { workspace = true }+rdkafka = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+sqlx = { workspace = true }+thiserror = { workspace = true }+tokio = { workspace = true }+tokio-util = { workspace = true }+tracing = { workspace = true }+tracing-subscriber = { workspace = true, features = ["env-filter", "json"] }+uuid = { workspace = true }++[dev-dependencies]+proptest = "1"diff --git a/rust/cohort-seeder/src/app/deliver.rs b/rust/cohort-seeder/src/app/deliver.rsnew file mode 100644index 000000000000..fd6dc6f534ed--- /dev/null+++ b/rust/cohort-seeder/src/app/deliver.rs@@ -0,0 +1,238 @@+//! App layer, Kafka produce sequencing: the two-phase enqueue/await split. Depends on `domain`,+//! `kafka`, `store`, and `app::settings`; never imported by a lower layer.+//!+//! The sequence `enqueue_tiles → store.mark_produced → await_deliveries` (composed by `execute`) is+//! byte-equivalent to the former monolithic produce: enqueue every tile honoring the in-flight bound+//! and draining overflow acks before the mark, then drain the remaining acks after it, folding all+//! delivery high-water marks into one accumulator carried across the mark by [`InFlight`].++use std::collections::VecDeque;+use std::time::{Duration, Instant};++use metrics::{counter, histogram};+use rdkafka::error::KafkaError;+use rdkafka::producer::DeliveryFuture;+use tokio_util::sync::CancellationToken;++use crate::domain::{CancelCause, EnqueuedChunk, Halted, ProduceHwms, ProducedChunk, ScannedChunk};+use crate::kafka::pacing::TilePacer;+use crate::kafka::producer::{EnqueueError, SeedTileProducer};+use crate::observability::metrics::{+ PRODUCE_ACK_SECONDS, TILES_PRODUCED, TILE_PRODUCE_ERRORS, TILE_PRODUCE_QUEUE_FULL,+};+use crate::store::chunks::ChunkStoreError;++use super::settings::ProducerSettings;++/// The ceiling the queue-full backoff doubles up to; also clamps [`ProducerSettings`] at construction.+pub(super) const QUEUE_FULL_BACKOFF_CAP: Duration = Duration::from_secs(5);++/// The pending deliveries and folded high-water marks handed from the pre-mark enqueue phase to the+/// post-mark await phase, so both phases fold into the same accumulator in the same order.+pub(super) struct InFlight {+ pending: VecDeque<PendingDelivery>,+ hwms: ProduceHwms,+}++/// Phase one (pre-mark): pace and enqueue every tile honoring the in-flight bound, draining overflow+/// acks into the HWMs. Returns the still-`scanning` chunk (for the store's mark) plus the in-flight+/// deliveries. Every error hands the [`ScannedChunk`] back so the caller can release or fail it.+pub(super) async fn enqueue_tiles(+ producer: &SeedTileProducer,+ chunk: ScannedChunk,+ pacer: &TilePacer,+ settings: ProducerSettings,+ lease_cancel: &CancellationToken,+ shutdown: &CancellationToken,+) -> Result<(ScannedChunk, InFlight), Halted<ScannedChunk, ProduceError>> {+ let mut pending = VecDeque::with_capacity(settings.max_inflight.get());+ let mut hwms = ProduceHwms::default();++ for tile in chunk.tiles() {+ if let Err(cause) = wait_for_pacer(pacer, shutdown, lease_cancel).await {+ return Err(Halted::cancelled(chunk, cause));+ }+ let mut backoff = settings.queue_full_backoff;+ loop {+ match producer.enqueue(tile) {+ Ok(delivery) => {+ pending.push_back(PendingDelivery {+ delivery,+ sent_at: Instant::now(),+ });+ break;+ }+ Err(EnqueueError::QueueFull) => {+ counter!(TILE_PRODUCE_QUEUE_FULL).increment(1);+ if let Err(cause) = wait_for_backoff(backoff, shutdown, lease_cancel).await {+ return Err(Halted::cancelled(chunk, cause));+ }+ backoff = next_queue_full_backoff(backoff);+ }+ Err(EnqueueError::Fatal(error)) => {+ counter!(TILE_PRODUCE_ERRORS).increment(1);+ return Err(Halted::failed(chunk, ProduceError::Enqueue(error)));+ }+ }+ }++ if pending.len() >= settings.max_inflight.get() {+ let delivery = pending+ .pop_front()+ .expect("the in-flight bound guarantees one delivery");+ if let Err(stop) =+ observe_delivery_before_mark(delivery, &mut hwms, shutdown, lease_cancel).await+ {+ counter!(TILE_PRODUCE_ERRORS).increment(1);+ return Err(stop.into_halted(chunk));+ }+ }+ }++ Ok((chunk, InFlight { pending, hwms }))+}++/// Phase two (post-mark): drain the remaining acks into the HWMs, fold them onto the marked chunk,+/// and emit `TILES_PRODUCED`. A delivery failure hands the [`EnqueuedChunk`] back for fail-on-retry.+pub(super) async fn await_deliveries(+ enqueued: EnqueuedChunk,+ inflight: InFlight,+ lease_cancel: &CancellationToken,+) -> Result<ProducedChunk, Halted<EnqueuedChunk, ProduceError>> {+ let InFlight {+ mut pending,+ mut hwms,+ } = inflight;++ while let Some(delivery) = pending.pop_front() {+ if let Err(stop) = observe_delivery_after_mark(delivery, &mut hwms, lease_cancel).await {+ counter!(TILE_PRODUCE_ERRORS).increment(1);+ return Err(stop.into_halted(enqueued));+ }+ }++ let produced = enqueued.into_produced(hwms);+ counter!(TILES_PRODUCED).increment(produced.tiles_produced());+ Ok(produced)+}++struct PendingDelivery {+ delivery: DeliveryFuture,+ sent_at: Instant,+}++/// A stop signal from awaiting one delivery: a cancellation cause or a terminal delivery error.+enum ProduceStop {+ Cancelled(CancelCause),+ Failed(ProduceError),+}++impl ProduceStop {+ fn into_halted<S>(self, state: S) -> Halted<S, ProduceError> {+ match self {+ Self::Cancelled(cause) => Halted::cancelled(state, cause),+ Self::Failed(error) => Halted::failed(state, error),+ }+ }+}++async fn observe_delivery_before_mark(+ mut pending: PendingDelivery,+ hwms: &mut ProduceHwms,+ shutdown: &CancellationToken,+ lease_cancel: &CancellationToken,+) -> Result<(), ProduceStop> {+ let result = tokio::select! {+ biased;+ _ = shutdown.cancelled() => Err(ProduceStop::Cancelled(CancelCause::Shutdown)),+ _ = lease_cancel.cancelled() => Err(ProduceStop::Cancelled(CancelCause::LeaseLost)),+ delivery = resolve_delivery(&mut pending, hwms) => delivery.map_err(ProduceStop::Failed),+ };+ histogram!(PRODUCE_ACK_SECONDS).record(pending.sent_at.elapsed().as_secs_f64());+ result+}++async fn observe_delivery_after_mark(+ mut pending: PendingDelivery,+ hwms: &mut ProduceHwms,+ lease_cancel: &CancellationToken,+) -> Result<(), ProduceStop> {+ let result = tokio::select! {+ biased;+ _ = lease_cancel.cancelled() => Err(ProduceStop::Cancelled(CancelCause::LeaseLost)),+ delivery = resolve_delivery(&mut pending, hwms) => delivery.map_err(ProduceStop::Failed),+ };+ histogram!(PRODUCE_ACK_SECONDS).record(pending.sent_at.elapsed().as_secs_f64());+ result+}++async fn resolve_delivery(+ pending: &mut PendingDelivery,+ hwms: &mut ProduceHwms,+) -> Result<(), ProduceError> {+ match (&mut pending.delivery).await {+ Ok(Ok((partition, offset))) => {+ hwms.observe(partition, offset);+ Ok(())+ }+ Ok(Err((error, _))) => Err(ProduceError::Delivery(error)),+ Err(_) => Err(ProduceError::Delivery(KafkaError::Canceled)),+ }+}++async fn wait_for_pacer(+ pacer: &TilePacer,+ shutdown: &CancellationToken,+ lease_cancel: &CancellationToken,+) -> Result<(), CancelCause> {+ tokio::select! {+ biased;+ _ = shutdown.cancelled() => Err(CancelCause::Shutdown),+ _ = lease_cancel.cancelled() => Err(CancelCause::LeaseLost),+ _ = pacer.until_ready() => Ok(()),+ }+}++async fn wait_for_backoff(+ backoff: Duration,+ shutdown: &CancellationToken,+ lease_cancel: &CancellationToken,+) -> Result<(), CancelCause> {+ tokio::select! {+ biased;+ _ = shutdown.cancelled() => Err(CancelCause::Shutdown),+ _ = lease_cancel.cancelled() => Err(CancelCause::LeaseLost),+ _ = tokio::time::sleep(backoff) => Ok(()),+ }+}++fn next_queue_full_backoff(current: Duration) -> Duration {+ current.saturating_mul(2).min(QUEUE_FULL_BACKOFF_CAP)+}++#[derive(Debug, thiserror::Error)]+pub(super) enum ProduceError {+ #[error("fatal tile enqueue error: {0}")]+ Enqueue(KafkaError),+ #[error("tile delivery failed: {0}")]+ Delivery(KafkaError),+ #[error("marking the chunk produced failed")]+ MarkProduced(#[source] ChunkStoreError),+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn queue_full_backoff_doubles_and_caps() {+ assert_eq!(+ next_queue_full_backoff(Duration::from_secs(4)),+ QUEUE_FULL_BACKOFF_CAP+ );+ assert_eq!(+ next_queue_full_backoff(QUEUE_FULL_BACKOFF_CAP),+ QUEUE_FULL_BACKOFF_CAP+ );+ }+}diff --git a/rust/cohort-seeder/src/app/execute.rs b/rust/cohort-seeder/src/app/execute.rsnew file mode 100644index 000000000000..3238f79830b0--- /dev/null+++ b/rust/cohort-seeder/src/app/execute.rs@@ -0,0 +1,286 @@+//! App layer: one chunk's `scan → enqueue → mark → await → confirm` pipeline and the single recovery+//! resolver. Depends on `clickhouse`, `kafka`, `store`, `domain`, and its `app` siblings.+//!+//! The store's `mark_produced` sits between the two deliver phases: deliver owns Kafka, execute owns+//! the store gating. Every halt funnels through [`resolve_halt`], which applies the exact recovery+//! matrix — a pre-mark halt during shutdown unclaims (no attempt spent); everything else fails for+//! retry — encoded once in [`FailureDisposition::resolve`] and pinned by its unit test.++use std::sync::Arc;++use metrics::counter;+use tokio_util::sync::CancellationToken;+use tracing::{info, warn};++use crate::clickhouse::scanner::ChunkScanner;+use crate::domain::{+ ChunkLease, ChunkSpec, ClaimedChunk, EnqueuedChunk, HaltReason, Halted, PinnedRun,+ ProducedChunk, ScannedChunk,+};+use crate::kafka::pacing::TilePacer;+use crate::kafka::producer::SeedTileProducer;+use crate::observability::metrics::{CHUNKS_CONFIRMED, CHUNKS_FAILED};+use crate::store::chunks::{ChunkStoreError, PgChunkStore};+use crate::store::lease::LeaseHandle;+use crate::store::RenderedError;++use super::deliver::{self, ProduceError};+use super::settings::ProducerSettings;++/// The owned inputs to one chunk's processing task, bundled so the spawn stays tidy.+pub(super) struct ChunkTaskContext {+ pub(super) chunk: ClaimedChunk,+ pub(super) lease: LeaseHandle,+ pub(super) run: Arc<PinnedRun>,+ pub(super) store: PgChunkStore,+ pub(super) scanner: ChunkScanner,+ pub(super) producer: SeedTileProducer,+ pub(super) pacer: TilePacer,+ pub(super) producer_settings: ProducerSettings,+}++pub(super) async fn execute_chunk(+ ctx: ChunkTaskContext,+ shutdown: CancellationToken,+) -> ChunkOutcome {+ let ChunkTaskContext {+ chunk,+ lease,+ run,+ store,+ scanner,+ producer,+ pacer,+ producer_settings,+ } = ctx;+ let lease_cancel = lease.cancellation_token();++ // PreMark: scan history into tiles.+ let scanned = match scanner.scan(chunk, &run, &lease_cancel, &shutdown).await {+ Ok(scanned) => scanned,+ Err(halt) => return resolve_halt(&store, halt, &shutdown).await,+ };+ // PreMark: pace and enqueue every tile, holding the in-flight deliveries.+ let (scanned, inflight) = match deliver::enqueue_tiles(+ &producer,+ scanned,+ &pacer,+ producer_settings,+ &lease_cancel,+ &shutdown,+ )+ .await+ {+ Ok(pair) => pair,+ Err(halt) => return resolve_halt(&store, halt, &shutdown).await,+ };+ // PreMark: CAS `scanning`→`produced` — the row is still `scanning` on failure.+ let enqueued = match store.mark_produced(scanned).await {+ Ok(enqueued) => enqueued,+ Err(halt) => return resolve_halt(&store, mark_produced_halt(halt), &shutdown).await,+ };+ // PostMark: drain the remaining delivery acks and fold the high-water marks.+ let produced = match deliver::await_deliveries(enqueued, inflight, &lease_cancel).await {+ Ok(produced) => produced,+ Err(halt) => return resolve_halt(&store, halt, &shutdown).await,+ };+ // PostMark: the terminal confirm — on failure the row is `produced`, so it is failed for retry.+ let lease = produced.spec().lease;+ let tiles_produced = produced.tiles_produced();+ match store.confirm(produced).await {+ Ok(_) => ChunkOutcome::Confirmed {+ lease,+ tiles_produced,+ },+ Err(halt) => resolve_halt(&store, halt, &shutdown).await,+ }+}++/// Whether a halt struck before or after the store marked the chunk `produced` — the discriminator+/// the recovery matrix turns on. Each chunk state names its stage as a `const` via [`ChunkState`].+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum FailureStage {+ PreMark,+ PostMark,+}++/// The pipeline states seen by recovery: their [`FailureStage`] and their lease-bearing spec.+trait ChunkState {+ const STAGE: FailureStage;+ fn spec(&self) -> ChunkSpec;+}++impl ChunkState for ClaimedChunk {+ const STAGE: FailureStage = FailureStage::PreMark;+ fn spec(&self) -> ChunkSpec {+ self.spec()+ }+}++impl ChunkState for ScannedChunk {+ const STAGE: FailureStage = FailureStage::PreMark;+ fn spec(&self) -> ChunkSpec {+ self.spec()+ }+}++impl ChunkState for EnqueuedChunk {+ const STAGE: FailureStage = FailureStage::PostMark;+ fn spec(&self) -> ChunkSpec {+ self.spec()+ }+}++impl ChunkState for ProducedChunk {+ const STAGE: FailureStage = FailureStage::PostMark;+ fn spec(&self) -> ChunkSpec {+ self.spec()+ }+}++/// The recovery decision: unclaim the chunk (refunding the attempt) or fail it for retry.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum FailureDisposition {+ Unclaim,+ Fail,+}++impl FailureDisposition {+ /// Today's exact matrix: a pre-mark halt during shutdown unclaims; every other case fails —+ /// post-mark never unclaims, since the row is already `produced`.+ const fn resolve(stage: FailureStage, shutting_down: bool) -> Self {+ match (stage, shutting_down) {+ (FailureStage::PreMark, true) => Self::Unclaim,+ (FailureStage::PreMark, false) => Self::Fail,+ (FailureStage::PostMark, _) => Self::Fail,+ }+ }+}++/// Apply the recovery matrix to a halted state: render the operator detail, decide the disposition+/// from the state's stage and the shutdown flag, and drive the fencing store write.+async fn resolve_halt<S: ChunkState, E: std::error::Error>(+ store: &PgChunkStore,+ halt: Halted<S, E>,+ shutdown: &CancellationToken,+) -> ChunkOutcome {+ let lease = halt.state.spec().lease;+ let detail = render_reason(&halt.reason);+ match FailureDisposition::resolve(S::STAGE, shutdown.is_cancelled()) {+ FailureDisposition::Unclaim => match store.unclaim(lease).await {+ Ok(()) => ChunkOutcome::Unclaimed { lease },+ Err(recovery) => ChunkOutcome::RecoveryFailed {+ lease,+ detail: detail.as_str().to_string(),+ recovery,+ },+ },+ FailureDisposition::Fail => match store.fail(lease, &detail).await {+ Ok(()) => ChunkOutcome::Failed {+ lease,+ detail: detail.as_str().to_string(),+ },+ Err(recovery) => ChunkOutcome::RecoveryFailed {+ lease,+ detail: detail.as_str().to_string(),+ recovery,+ },+ },+ }+}++/// Re-wrap the store's mark error as the produce error the recovery path renders, preserving the+/// persisted `marking the chunk produced failed: …` text while the store stays store-typed.+fn mark_produced_halt(+ halt: Halted<ScannedChunk, ChunkStoreError>,+) -> Halted<ScannedChunk, ProduceError> {+ let Halted { state, reason } = halt;+ let reason = match reason {+ HaltReason::Failed(error) => HaltReason::Failed(ProduceError::MarkProduced(error)),+ HaltReason::Cancelled(cause) => HaltReason::Cancelled(cause),+ };+ Halted { state, reason }+}++fn render_reason<E: std::error::Error>(reason: &HaltReason<E>) -> RenderedError {+ match reason {+ HaltReason::Failed(error) => RenderedError::render(error),+ HaltReason::Cancelled(cause) => RenderedError::from_message(cause.as_str()),+ }+}++#[derive(Debug)]+pub(super) enum ChunkOutcome {+ Confirmed {+ lease: ChunkLease,+ tiles_produced: u64,+ },+ Failed {+ lease: ChunkLease,+ detail: String,+ },+ Unclaimed {+ lease: ChunkLease,+ },+ RecoveryFailed {+ lease: ChunkLease,+ detail: String,+ recovery: ChunkStoreError,+ },+}++pub(super) fn record_task_result(result: Result<ChunkOutcome, tokio::task::JoinError>) {+ match result {+ Ok(ChunkOutcome::Confirmed {+ lease,+ tiles_produced,+ }) => {+ counter!(CHUNKS_CONFIRMED).increment(1);+ info!(?lease, tiles_produced, "chunk confirmed");+ }+ Ok(ChunkOutcome::Failed { lease, detail }) => {+ counter!(CHUNKS_FAILED).increment(1);+ warn!(?lease, error = %detail, "chunk failed and was released for retry");+ }+ Ok(ChunkOutcome::Unclaimed { lease }) => {+ info!(?lease, "chunk unclaimed during shutdown");+ }+ Ok(ChunkOutcome::RecoveryFailed {+ lease,+ detail,+ recovery,+ }) => {+ counter!(CHUNKS_FAILED).increment(1);+ warn!(?lease, error = %detail, recovery_error = %recovery, "chunk recovery update did not apply");+ }+ Err(error) => {+ counter!(CHUNKS_FAILED).increment(1);+ warn!(error = %error, "chunk task failed unexpectedly");+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn failure_disposition_encodes_the_recovery_matrix() {+ assert_eq!(+ FailureDisposition::resolve(FailureStage::PreMark, true),+ FailureDisposition::Unclaim+ );+ assert_eq!(+ FailureDisposition::resolve(FailureStage::PreMark, false),+ FailureDisposition::Fail+ );+ assert_eq!(+ FailureDisposition::resolve(FailureStage::PostMark, true),+ FailureDisposition::Fail+ );+ assert_eq!(+ FailureDisposition::resolve(FailureStage::PostMark, false),+ FailureDisposition::Fail+ );+ }+}diff --git a/rust/cohort-seeder/src/app/mod.rs b/rust/cohort-seeder/src/app/mod.rsnew file mode 100644index 000000000000..f9ada2484a27--- /dev/null+++ b/rust/cohort-seeder/src/app/mod.rs@@ -0,0 +1,11 @@+//! Application layer: wires `store`, `clickhouse`, `kafka`, and `config` into the seeder's poll loop.+//! Depends on every lower layer; nothing below depends on it, so this is where the arrows terminate.++mod deliver;+mod execute;+mod orchestrator;+mod prepare;+pub mod settings;++pub use orchestrator::{SeederOrchestrator, ORCHESTRATOR_LIVENESS_DEADLINE};+pub use settings::OrchestratorSettings;diff --git a/rust/cohort-seeder/src/app/orchestrator.rs b/rust/cohort-seeder/src/app/orchestrator.rsnew file mode 100644index 000000000000..8c248333961d--- /dev/null+++ b/rust/cohort-seeder/src/app/orchestrator.rs@@ -0,0 +1,213 @@+//! App layer: the seeder poll loop that discovers runs, fills claim slots, and drains on shutdown.+//! Depends on `store`, `clickhouse`, `kafka`, `domain`, and its `app` siblings (`prepare`, `execute`,+//! `settings`); it is the crate's top module, imported only by `main`.++use std::collections::{HashMap, HashSet};+use std::sync::Arc;+use std::time::Duration;++use common_types::cohort::TeamAllowlist;+use lifecycle::Handle;+use metrics::counter;+use sqlx::PgPool;+use tokio::task::JoinSet;+use tokio_util::sync::CancellationToken;+use tracing::{info, warn};++use crate::clickhouse::scanner::ChunkScanner;+use crate::domain::{ClaimKind, PinnedRun, RunId};+use crate::kafka::pacing::TilePacer;+use crate::kafka::producer::SeedTileProducer;+use crate::observability::metrics::{CHUNKS_CLAIMED, CHUNKS_POISONED, CHUNKS_RECLAIMED};+use crate::store::chunks::{Claim, PgChunkStore};+use crate::store::Claimant;++use super::execute::{execute_chunk, record_task_result, ChunkOutcome, ChunkTaskContext};+use super::prepare::refresh_runs;+use super::settings::OrchestratorSettings;++const PRODUCER_FLUSH_TIMEOUT: Duration = Duration::from_secs(5);+pub const ORCHESTRATOR_LIVENESS_DEADLINE: Duration = Duration::from_secs(60);++pub struct SeederOrchestrator {+ pool: PgPool,+ store: PgChunkStore,+ scanner: ChunkScanner,+ producer: SeedTileProducer,+ pacer: TilePacer,+ allowlist: TeamAllowlist,+ settings: OrchestratorSettings,+ handle: Handle,+ claimant: Claimant,+}++impl SeederOrchestrator {+ #[allow(clippy::too_many_arguments)]+ pub fn new(+ pool: PgPool,+ scanner: ChunkScanner,+ producer: SeedTileProducer,+ pacer: TilePacer,+ allowlist: TeamAllowlist,+ settings: OrchestratorSettings,+ handle: Handle,+ claimed_by: String,+ ) -> Self {+ let claimant =+ Claimant::new(claimed_by).expect("seeder claimant is 1..=255 bytes by construction");+ Self {+ store: PgChunkStore::new(pool.clone()),+ pool,+ scanner,+ producer,+ pacer,+ allowlist,+ settings,+ handle,+ claimant,+ }+ }++ pub async fn process(self) {+ let _scope = self.handle.process_scope();+ let shutdown = self.handle.shutdown_token();+ let mut poll = tokio::time::interval(self.settings.run_poll_interval);+ poll.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);+ let mut tasks = JoinSet::new();+ let mut eligible_runs = HashMap::new();+ let mut reported_runs = HashSet::new();+ self.handle.report_healthy();+ info!(claimant = %self.claimant.as_str(), "cohort seeder orchestrator starting");++ loop {+ tokio::select! {+ biased;+ _ = shutdown.cancelled() => break,+ Some(result) = tasks.join_next(), if !tasks.is_empty() => {+ record_task_result(result);+ self.fill_claim_slots(&eligible_runs, &mut tasks, &shutdown).await;+ self.handle.report_healthy();+ }+ _ = poll.tick() => {+ eligible_runs = refresh_runs(+ &self.pool,+ &self.store,+ &self.allowlist,+ self.settings.plan_caps,+ &mut reported_runs,+ )+ .await;+ self.reap_poisoned_chunks(&eligible_runs).await;+ self.fill_claim_slots(&eligible_runs, &mut tasks, &shutdown).await;+ self.handle.report_healthy();+ }+ }+ }++ info!(+ active_chunks = tasks.len(),+ "stopping claims and draining active chunks"+ );+ while let Some(result) = tasks.join_next().await {+ record_task_result(result);+ }++ let producer = self.producer.clone();+ match tokio::task::spawn_blocking(move || producer.flush(PRODUCER_FLUSH_TIMEOUT)).await {+ Ok(Ok(())) => {}+ Ok(Err(error)) => warn!(error = %error, "producer flush failed during shutdown"),+ Err(error) => warn!(error = %error, "producer flush task failed during shutdown"),+ }+ info!("cohort seeder orchestrator stopped");+ }++ /// Dead-letter `scanning` chunks whose lease expired at the attempt cap — the chunks a+ /// hard-crashed worker left behind, which the claim predicate no longer reclaims.+ async fn reap_poisoned_chunks(&self, eligible_runs: &HashMap<RunId, Arc<PinnedRun>>) {+ if eligible_runs.is_empty() {+ return;+ }+ let run_ids = eligible_runs.keys().copied().collect::<Vec<_>>();+ match self+ .store+ .reap_poisoned_chunks(&run_ids, self.settings.max_chunk_attempts)+ .await+ {+ Ok(0) => {}+ Ok(reaped) => {+ counter!(CHUNKS_POISONED).increment(reaped);+ warn!(+ reaped,+ "dead-lettered scanning chunks whose lease expired at the attempt cap"+ );+ }+ Err(error) => warn!(error = %error, "reaping poisoned chunks failed"),+ }+ }++ async fn fill_claim_slots(+ &self,+ eligible_runs: &HashMap<RunId, Arc<PinnedRun>>,+ tasks: &mut JoinSet<ChunkOutcome>,+ shutdown: &CancellationToken,+ ) {+ if eligible_runs.is_empty() || shutdown.is_cancelled() {+ return;+ }+ let run_ids = eligible_runs.keys().copied().collect::<Vec<_>>();+ while tasks.len() < self.settings.max_concurrent_chunks.get() && !shutdown.is_cancelled() {+ let claim = match self+ .store+ .claim_next(+ &run_ids,+ &self.claimant,+ self.settings.chunk_lease,+ self.settings.max_chunk_attempts,+ )+ .await+ {+ Ok(claim) => claim,+ Err(error) => {+ warn!(error = %error, "chunk claim failed");+ return;+ }+ };+ let Some(Claim { chunk, kind, lease }) = claim else {+ return;+ };+ if kind == ClaimKind::Reclaim {+ counter!(CHUNKS_RECLAIMED).increment(1);+ }+ let Some(run) = eligible_runs.get(&chunk.spec().lease.run_id()).cloned() else {+ let chunk_lease = chunk.spec().lease;+ if let Err(error) = self.store.unclaim(chunk_lease).await {+ warn!(?chunk_lease, error = %error, "claimed chunk had no validated run and could not be unclaimed");+ }+ continue;+ };+ counter!(CHUNKS_CLAIMED).increment(1);+ let store = self.store.clone();+ let scanner = self.scanner.clone();+ let producer = self.producer.clone();+ let pacer = self.pacer.clone();+ let producer_settings = self.settings.producer;+ let shutdown = shutdown.clone();+ tasks.spawn(async move {+ execute_chunk(+ ChunkTaskContext {+ chunk,+ lease,+ run,+ store,+ scanner,+ producer,+ pacer,+ producer_settings,+ },+ shutdown,+ )+ .await+ });+ }+ }+}diff --git a/rust/cohort-seeder/src/app/prepare.rs b/rust/cohort-seeder/src/app/prepare.rsnew file mode 100644index 000000000000..231a287e804f--- /dev/null+++ b/rust/cohort-seeder/src/app/prepare.rs@@ -0,0 +1,248 @@+//! App layer: run discovery → boundary → validate → plan, per run. Depends on `store`, `domain`, and+//! `config`'s allowlist type; never imported by a lower layer.+//!+//! [`refresh_runs`] is the thin fold over discovered runs; [`prepare_run`] is the per-run pipeline+//! that classifies each into a [`PrepareOutcome`]. Every counter and gauge stays at its former point.++use std::collections::{HashMap, HashSet};+use std::sync::Arc;++use cohort_core::bucket_tz::window_start_for_now;+use common_types::cohort::TeamAllowlist;+use metrics::{counter, gauge};+use sqlx::PgPool;+use tracing::warn;++use crate::domain::{plan_days, Lookback, PinnedRun, PinnedWarning, PlanCaps, RunId};+use crate::observability::metrics::{+ BOUNDARY_CAS_LOST, BOUNDARY_ESTABLISHED, CHUNKS_PLANNED, CONDITIONS_DROPPED,+ LOOKBACK_TRUNCATED, RUNS_DISCOVERED, RUNS_WAITING_BOUNDARY, RUNS_WITHOUT_CHUNKS,+ RUN_CHUNKS_REMAINING, RUN_VALIDATION_FAILURES, TZ_FALLBACK, WINDOW_DAYS_MISMATCH,+};+use crate::store::chunks::{PgChunkStore, PlanOutcome};+use crate::store::runs::{+ discover_runs, establish_boundary, fail_run, record_run_warning, BoundaryOutcome,+ DiscoveredRun, RunError, RunStatus, RunWarningNote,+};+use crate::store::RenderedError;++/// One discovered run's classification after its boundary/validate/plan pipeline.+enum PrepareOutcome {+ Eligible(Arc<PinnedRun>),+ WaitingBoundary,+ NoChunks,+ Skipped,+}++pub(super) async fn refresh_runs(+ pool: &PgPool,+ store: &PgChunkStore,+ allowlist: &TeamAllowlist,+ plan_caps: PlanCaps,+ reported_runs: &mut HashSet<RunId>,+) -> HashMap<RunId, Arc<PinnedRun>> {+ let discovered = match discover_runs(pool, allowlist).await {+ Ok(runs) => runs,+ Err(error) => {+ let run_id = error.run_id();+ handle_run_error(pool, run_id, error).await;+ return HashMap::new();+ }+ };+ let mut eligible = HashMap::with_capacity(discovered.len());+ let mut seen_runs = HashSet::with_capacity(discovered.len());+ let mut waiting_boundary = 0_u64;+ let mut without_chunks = 0_u64;++ for run in discovered {+ seen_runs.insert(run.run_id);+ match prepare_run(pool, store, plan_caps, reported_runs, run).await {+ PrepareOutcome::Eligible(pinned) => {+ eligible.insert(pinned.run_id, pinned);+ }+ PrepareOutcome::WaitingBoundary => waiting_boundary += 1,+ PrepareOutcome::NoChunks => without_chunks += 1,+ PrepareOutcome::Skipped => {}+ }+ }++ gauge!(RUNS_WAITING_BOUNDARY).set(waiting_boundary as f64);+ gauge!(RUNS_WITHOUT_CHUNKS).set(without_chunks as f64);+ let eligible_run_ids = eligible.keys().copied().collect::<Vec<_>>();+ match store.remaining_chunks(&eligible_run_ids).await {+ Ok(remaining) => gauge!(RUN_CHUNKS_REMAINING).set(remaining as f64),+ Err(error) => warn!(error = %error, "counting remaining chunks failed"),+ }+ reported_runs.retain(|run_id| seen_runs.contains(run_id));+ eligible+}++async fn prepare_run(+ pool: &PgPool,+ store: &PgChunkStore,+ plan_caps: PlanCaps,+ reported_runs: &mut HashSet<RunId>,+ run: DiscoveredRun,+) -> PrepareOutcome {+ counter!(RUNS_DISCOVERED, "status" => run.status.as_str()).increment(1);++ let was_awaiting_boundary = run.status == RunStatus::AwaitingBoundary;+ let discovered_run_id = run.run_id;+ let boundary = match establish_boundary(pool, run).await {+ Ok(BoundaryOutcome::Established(run)) => {+ counter!(BOUNDARY_ESTABLISHED, "trigger" => run.trigger.as_str()).increment(1);+ run+ }+ Ok(BoundaryOutcome::AlreadyEstablished(run)) => {+ if was_awaiting_boundary {+ counter!(BOUNDARY_CAS_LOST).increment(1);+ }+ run+ }+ Ok(BoundaryOutcome::NoLongerSeedable { .. }) => return PrepareOutcome::Skipped,+ Err(RunError::DisasterRecoveryBoundaryMissing(_)) => {+ return PrepareOutcome::WaitingBoundary;+ }+ Err(error) => {+ handle_run_error(pool, Some(discovered_run_id), error).await;+ return PrepareOutcome::Skipped;+ }+ };++ let run_id = boundary.run_id;+ let validated = match boundary.load_pinned(pool).await {+ Ok(validated) => validated,+ Err(error) => {+ handle_run_error(pool, Some(run_id), error).await;+ return PrepareOutcome::Skipped;+ }+ };+ let lookback_truncated = lookback_was_truncated(&validated.run, plan_caps);+ if reported_runs.insert(run_id) {+ record_pinned_warnings(&validated.warnings);+ if lookback_truncated {+ counter!(LOOKBACK_TRUNCATED).increment(1);+ }+ }+ if validated+ .warnings+ .iter()+ .any(|warning| matches!(warning, PinnedWarning::ConditionDropped { .. }))+ {+ persist_run_warning(pool, run_id, RunWarningNote::ConditionsDropped).await;+ }+ if lookback_truncated {+ persist_run_warning(pool, run_id, RunWarningNote::LookbackTruncated).await;+ }++ let days = plan_days(+ &validated.run.conditions,+ validated.run.boundary,+ &plan_caps,+ );+ if days.is_empty() {+ return PrepareOutcome::NoChunks;+ }+ match store+ .plan_chunks(validated.run.run_id, days, plan_caps.bands_per_day)+ .await+ {+ Ok(PlanOutcome::Planned { inserted }) => {+ counter!(CHUNKS_PLANNED).increment(inserted);+ }+ Ok(PlanOutcome::RunNotSeeding) => return PrepareOutcome::Skipped,+ Err(error) => {+ warn!(run_id = ?validated.run.run_id, error = %error, "chunk planning failed");+ return PrepareOutcome::Skipped;+ }+ }+ PrepareOutcome::Eligible(Arc::new(validated.run))+}++async fn handle_run_error(pool: &PgPool, run_id: Option<RunId>, error: RunError) {+ let disposition = run_error_disposition(run_id, &error);+ if let RunErrorDisposition::Fail { run_id, reason } = disposition {+ counter!(RUN_VALIDATION_FAILURES, "reason" => reason).increment(1);+ let detail = RenderedError::render(&error);+ if let Err(failure) = fail_run(pool, run_id, &detail).await {+ warn!(run_id = ?run_id, error = %failure, "failing invalid run did not apply");+ }+ return;+ }+ warn!(error = %error, "transient run preparation failed");+}++async fn persist_run_warning(pool: &PgPool, run_id: RunId, note: RunWarningNote) {+ if let Err(error) = record_run_warning(pool, run_id, note).await {+ warn!(run_id = ?run_id, error = %error, "persisting run warning failed");+ }+}++fn record_pinned_warnings(warnings: &[PinnedWarning]) {+ for warning in warnings {+ match warning {+ PinnedWarning::TimezoneFallback { .. } => counter!(TZ_FALLBACK).increment(1),+ PinnedWarning::ConditionDropped { reason, .. } => {+ counter!(CONDITIONS_DROPPED, "reason" => reason.as_str()).increment(1);+ }+ PinnedWarning::ConditionSuperseded { .. } => {+ counter!(CONDITIONS_DROPPED, "reason" => "superseded_participation").increment(1);+ }+ PinnedWarning::WindowDaysMismatch { .. } => {+ counter!(WINDOW_DAYS_MISMATCH).increment(1);+ }+ }+ }+}++fn lookback_was_truncated(run: &PinnedRun, caps: PlanCaps) -> bool {+ let capped_start = window_start_for_now(run.boundary.day(), caps.max_lookback_days);+ run.conditions+ .iter()+ .any(|condition| match condition.lookback {+ Lookback::SlidingDays(days) => days > caps.max_lookback_days,+ Lookback::FixedRange { from_day: None, .. } => true,+ Lookback::FixedRange {+ from_day: Some(from),+ ..+ } => from < capped_start,+ Lookback::SubDay => false,+ })+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum RunErrorDisposition {+ Retry,+ Fail { run_id: RunId, reason: &'static str },+}++fn run_error_disposition(run_id: Option<RunId>, error: &RunError) -> RunErrorDisposition {+ match error {+ RunError::Pg(_) => RunErrorDisposition::Retry,+ RunError::Pinned(_) => run_id.map_or(RunErrorDisposition::Retry, |run_id| {+ RunErrorDisposition::Fail {+ run_id,+ reason: "pinned_validation",+ }+ }),+ RunError::CrossTeamParticipation { run_id, .. } => RunErrorDisposition::Fail {+ run_id: *run_id,+ reason: "cross_team_participation",+ },+ RunError::SeedingBoundaryMissing(run_id) => RunErrorDisposition::Fail {+ run_id: *run_id,+ reason: "missing_boundary",+ },+ RunError::DisasterRecoveryBoundaryMissing(_) => RunErrorDisposition::Retry,+ RunError::InvalidTrigger { run_id, .. }+ | RunError::InvalidScope { run_id, .. }+ | RunError::InvalidStatus { run_id, .. } => RunErrorDisposition::Fail {+ run_id: *run_id,+ reason: "invalid_run_row",+ },+ RunError::UnknownStatus(_)+ | RunError::UnknownScope(_)+ | RunError::NotFound(_)+ | RunError::NotActive(_) => RunErrorDisposition::Retry,+ }+}diff --git a/rust/cohort-seeder/src/app/settings.rs b/rust/cohort-seeder/src/app/settings.rsnew file mode 100644index 000000000000..166553b57431--- /dev/null+++ b/rust/cohort-seeder/src/app/settings.rs@@ -0,0 +1,287 @@+//! App layer: validated orchestrator/producer tunables parsed once from [`Config`]. Depends on+//! `config`, `domain`, `store`, and its `app` siblings; this `TryFrom<&Config>` is what keeps the+//! dependency arrow pointing down (`config` no longer names an `app` type).++use std::num::{NonZeroU16, NonZeroUsize};+use std::time::Duration;++use crate::config::Config;+use crate::domain::PlanCaps;+use crate::store::{LeaseDuration, LeaseDurationError, MaxAttempts, MaxAttemptsError};++use super::deliver::QUEUE_FULL_BACKOFF_CAP;+use super::orchestrator::ORCHESTRATOR_LIVENESS_DEADLINE;++#[derive(Debug, Clone, Copy)]+pub struct OrchestratorSettings {+ pub(super) run_poll_interval: Duration,+ pub(super) max_concurrent_chunks: NonZeroUsize,+ pub(super) chunk_lease: LeaseDuration,+ pub(super) max_chunk_attempts: MaxAttempts,+ pub(super) plan_caps: PlanCaps,+ pub(super) producer: ProducerSettings,+}++impl OrchestratorSettings {+ pub fn new(+ run_poll_interval: Duration,+ max_concurrent_chunks: usize,+ chunk_lease: Duration,+ max_chunk_attempts: u32,+ max_lookback_days: u32,+ bands_per_day: u16,+ producer: ProducerSettings,+ ) -> Result<Self, OrchestratorSettingsError> {+ if run_poll_interval.is_zero() {+ return Err(OrchestratorSettingsError::ZeroPollInterval);+ }+ if run_poll_interval >= ORCHESTRATOR_LIVENESS_DEADLINE {+ return Err(OrchestratorSettingsError::PollIntervalExceedsLivenessDeadline);+ }+ let max_concurrent_chunks = NonZeroUsize::new(max_concurrent_chunks)+ .ok_or(OrchestratorSettingsError::ZeroConcurrency)?;+ let chunk_lease = LeaseDuration::new(chunk_lease).map_err(|error| match error {+ LeaseDurationError::TooShort => OrchestratorSettingsError::LeaseTooShort,+ LeaseDurationError::TooLong => OrchestratorSettingsError::LeaseTooLong,+ })?;+ let max_chunk_attempts =+ MaxAttempts::new(max_chunk_attempts).map_err(|error| match error {+ MaxAttemptsError::Zero => OrchestratorSettingsError::ZeroMaxAttempts,+ MaxAttemptsError::OutOfRange(_) => OrchestratorSettingsError::MaxAttemptsOutOfRange,+ })?;+ // The `band` column is a smallint, so the count must fit i16 for band indices to encode.+ let bands_per_day = NonZeroU16::new(bands_per_day)+ .filter(|bands| i16::try_from(bands.get()).is_ok())+ .ok_or(OrchestratorSettingsError::BandsPerDayOutOfRange)?;+ Ok(Self {+ run_poll_interval,+ max_concurrent_chunks,+ chunk_lease,+ max_chunk_attempts,+ plan_caps: PlanCaps {+ max_lookback_days,+ bands_per_day,+ },+ producer,+ })+ }+}++impl TryFrom<&Config> for OrchestratorSettings {+ type Error = SettingsError;++ fn try_from(config: &Config) -> Result<Self, Self::Error> {+ let producer = ProducerSettings::new(+ config.seeder_max_inflight_tiles,+ Duration::from_millis(config.seeder_queue_full_backoff_ms),+ )?;+ Ok(Self::new(+ Duration::from_secs(config.seeder_run_poll_secs),+ config.seeder_max_concurrent_chunks,+ Duration::from_secs(config.seeder_chunk_lease_secs),+ config.seeder_max_chunk_attempts,+ config.seeder_max_lookback_days,+ config.seeder_bands_per_day,+ producer,+ )?)+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]+pub enum OrchestratorSettingsError {+ #[error("run poll interval must be greater than zero")]+ ZeroPollInterval,+ #[error("run poll interval must be shorter than the liveness deadline")]+ PollIntervalExceedsLivenessDeadline,+ #[error("maximum concurrent chunks must be greater than zero")]+ ZeroConcurrency,+ #[error("chunk lease must be at least three seconds")]+ LeaseTooShort,+ #[error("chunk lease exceeds PostgreSQL interval range")]+ LeaseTooLong,+ #[error("maximum chunk attempts must be greater than zero")]+ ZeroMaxAttempts,+ #[error("maximum chunk attempts exceeds PostgreSQL integer range")]+ MaxAttemptsOutOfRange,+ #[error("bands per day must be between 1 and 32767")]+ BandsPerDayOutOfRange,+}++/// The produce sequencing's tunables: the in-flight delivery bound and the queue-full backoff (capped+/// at [`QUEUE_FULL_BACKOFF_CAP`]). Consumed by `app::deliver`.+#[derive(Debug, Clone, Copy)]+pub struct ProducerSettings {+ pub(super) max_inflight: NonZeroUsize,+ pub(super) queue_full_backoff: Duration,+}++impl ProducerSettings {+ pub fn new(+ max_inflight: usize,+ queue_full_backoff: Duration,+ ) -> Result<Self, ProducerSettingsError> {+ let max_inflight =+ NonZeroUsize::new(max_inflight).ok_or(ProducerSettingsError::ZeroMaxInflight)?;+ if queue_full_backoff.is_zero() {+ return Err(ProducerSettingsError::ZeroQueueFullBackoff);+ }+ Ok(Self {+ max_inflight,+ queue_full_backoff: queue_full_backoff.min(QUEUE_FULL_BACKOFF_CAP),+ })+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]+pub enum ProducerSettingsError {+ #[error("maximum in-flight tiles must be greater than zero")]+ ZeroMaxInflight,+ #[error("queue-full backoff must be greater than zero")]+ ZeroQueueFullBackoff,+}++/// Folds the producer- and orchestrator-settings validations behind one `TryFrom<&Config>` error, so+/// the seeder binary sees a single failure type when parsing its environment.+#[derive(Debug, thiserror::Error)]+pub enum SettingsError {+ #[error(transparent)]+ Producer(#[from] ProducerSettingsError),+ #[error(transparent)]+ Orchestrator(#[from] OrchestratorSettingsError),+}++#[cfg(test)]+mod tests {+ use std::collections::HashMap;++ use envconfig::Envconfig;++ use super::*;++ fn producer_settings() -> ProducerSettings {+ ProducerSettings::new(1, Duration::from_millis(1)).unwrap()+ }++ #[test]+ fn producer_settings_reject_unbounded_bounds() {+ assert_eq!(+ ProducerSettings::new(0, Duration::from_millis(1)).unwrap_err(),+ ProducerSettingsError::ZeroMaxInflight+ );+ assert_eq!(+ ProducerSettings::new(1, Duration::ZERO).unwrap_err(),+ ProducerSettingsError::ZeroQueueFullBackoff+ );+ assert_eq!(+ ProducerSettings::new(1, Duration::from_secs(60))+ .unwrap()+ .queue_full_backoff,+ QUEUE_FULL_BACKOFF_CAP+ );+ }++ #[test]+ fn settings_reject_values_that_disable_progress_or_lease_heartbeats() {+ let cases = [+ (+ OrchestratorSettings::new(+ ORCHESTRATOR_LIVENESS_DEADLINE,+ 1,+ Duration::from_secs(3),+ 1,+ 400,+ 1,+ producer_settings(),+ ),+ OrchestratorSettingsError::PollIntervalExceedsLivenessDeadline,+ ),+ (+ OrchestratorSettings::new(+ Duration::ZERO,+ 1,+ Duration::from_secs(3),+ 1,+ 400,+ 1,+ producer_settings(),+ ),+ OrchestratorSettingsError::ZeroPollInterval,+ ),+ (+ OrchestratorSettings::new(+ Duration::from_secs(1),+ 0,+ Duration::from_secs(3),+ 1,+ 400,+ 1,+ producer_settings(),+ ),+ OrchestratorSettingsError::ZeroConcurrency,+ ),+ (+ OrchestratorSettings::new(+ Duration::from_secs(1),+ 1,+ Duration::from_secs(2),+ 1,+ 400,+ 1,+ producer_settings(),+ ),+ OrchestratorSettingsError::LeaseTooShort,+ ),+ (+ OrchestratorSettings::new(+ Duration::from_secs(1),+ 1,+ Duration::from_secs(3),+ 0,+ 400,+ 1,+ producer_settings(),+ ),+ OrchestratorSettingsError::ZeroMaxAttempts,+ ),+ (+ OrchestratorSettings::new(+ Duration::from_secs(1),+ 1,+ Duration::from_secs(3),+ 1,+ 400,+ 0,+ producer_settings(),+ ),+ OrchestratorSettingsError::BandsPerDayOutOfRange,+ ),+ (+ OrchestratorSettings::new(+ Duration::from_secs(1),+ 1,+ Duration::from_secs(3),+ 1,+ 400,+ u16::MAX,+ producer_settings(),+ ),+ OrchestratorSettingsError::BandsPerDayOutOfRange,+ ),+ ];+ for (result, expected) in cases {+ assert_eq!(result.unwrap_err(), expected);+ }+ }++ #[test]+ fn try_from_config_rejects_disabled_concurrency() {+ let mut config = Config::init_from_hashmap(&HashMap::new()).unwrap();+ config.seeder_max_concurrent_chunks = 0;+ assert!(matches!(+ OrchestratorSettings::try_from(&config),+ Err(SettingsError::Orchestrator(+ OrchestratorSettingsError::ZeroConcurrency+ ))+ ));+ }+}diff --git a/rust/cohort-seeder/src/clickhouse/client.rs b/rust/cohort-seeder/src/clickhouse/client.rsnew file mode 100644index 000000000000..2be7506c180f--- /dev/null+++ b/rust/cohort-seeder/src/clickhouse/client.rs@@ -0,0 +1,230 @@+//! ClickHouse client construction: endpoint precedence and the typed `join_algorithm` setting.+//!+//! Depends on `config` for the raw env strings; every value that shapes a ClickHouse query option is+//! parsed here so a misconfiguration fails startup instead of silently degrading query behavior.++use std::str::FromStr;++use crate::config::Config;++/// The resolved ClickHouse HTTP endpoint. Precedence is explicit URL > offline cluster host > host;+/// the scheme comes from `secure`, and a bare host gets the canonical port (8443 secure, 8123 plain).+/// Resolved exactly once by [`ClickHouseEndpoint::resolve`].+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ClickHouseEndpoint(String);++impl ClickHouseEndpoint {+ pub fn resolve(config: &Config) -> Self {+ Self(resolve_endpoint(config))+ }++ pub fn as_str(&self) -> &str {+ &self.0+ }+}++fn resolve_endpoint(config: &Config) -> String {+ if !config.clickhouse_url.is_empty() {+ return config.clickhouse_url.clone();+ }+ let host = if config.clickhouse_offline_cluster_host.is_empty() {+ &config.clickhouse_host+ } else {+ &config.clickhouse_offline_cluster_host+ };+ if host.starts_with("http://") || host.starts_with("https://") {+ return host.clone();+ }+ let scheme = if config.clickhouse_secure {+ "https"+ } else {+ "http"+ };+ if has_explicit_port(host) {+ format!("{scheme}://{host}")+ } else {+ let port = if config.clickhouse_secure { 8443 } else { 8123 };+ format!("{scheme}://{host}:{port}")+ }+}++fn has_explicit_port(host: &str) -> bool {+ if let Some(bracket_end) = host.find(']') {+ return host+ .get(bracket_end + 1..)+ .is_some_and(|suffix| suffix.starts_with(':'));+ }+ let Some((_, port)) = host.rsplit_once(':') else {+ return false;+ };+ host.matches(':').count() == 1 && port.parse::<u16>().is_ok()+}++/// The ClickHouse `join_algorithm` query setting. Parsed from config so an unknown value is a startup+/// failure rather than a silent pass-through that would degrade join memory behavior. `as_str` emits+/// the exact ClickHouse token, so the option value is byte-identical to the raw string it parses.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ClickHouseJoinAlgorithm {+ Default,+ Auto,+ Hash,+ ParallelHash,+ GraceHash,+ PartialMerge,+ PreferPartialMerge,+ FullSortingMerge,+ Direct,+}++impl ClickHouseJoinAlgorithm {+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::Default => "default",+ Self::Auto => "auto",+ Self::Hash => "hash",+ Self::ParallelHash => "parallel_hash",+ Self::GraceHash => "grace_hash",+ Self::PartialMerge => "partial_merge",+ Self::PreferPartialMerge => "prefer_partial_merge",+ Self::FullSortingMerge => "full_sorting_merge",+ Self::Direct => "direct",+ }+ }+}++impl FromStr for ClickHouseJoinAlgorithm {+ type Err = UnknownJoinAlgorithm;++ fn from_str(value: &str) -> Result<Self, Self::Err> {+ match value {+ "default" => Ok(Self::Default),+ "auto" => Ok(Self::Auto),+ "hash" => Ok(Self::Hash),+ "parallel_hash" => Ok(Self::ParallelHash),+ "grace_hash" => Ok(Self::GraceHash),+ "partial_merge" => Ok(Self::PartialMerge),+ "prefer_partial_merge" => Ok(Self::PreferPartialMerge),+ "full_sorting_merge" => Ok(Self::FullSortingMerge),+ "direct" => Ok(Self::Direct),+ other => Err(UnknownJoinAlgorithm(other.to_string())),+ }+ }+}++#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]+#[error("unknown ClickHouse join algorithm {0:?}")]+pub struct UnknownJoinAlgorithm(pub String);++pub fn build_client(config: &Config) -> Result<clickhouse::Client, UnknownJoinAlgorithm> {+ let join_algorithm = config+ .seeder_ch_join_algorithm+ .parse::<ClickHouseJoinAlgorithm>()?;+ Ok(clickhouse::Client::default()+ .with_url(ClickHouseEndpoint::resolve(config).as_str())+ .with_user(&config.clickhouse_user)+ .with_password(&config.clickhouse_password)+ .with_database(&config.clickhouse_database)+ .with_option(+ "max_execution_time",+ config.seeder_ch_max_execution_time_secs.to_string(),+ )+ .with_option(+ "max_bytes_before_external_group_by",+ config+ .seeder_ch_max_bytes_before_external_group_by+ .to_string(),+ )+ .with_option(+ "max_bytes_before_external_sort",+ config.seeder_ch_max_bytes_before_external_sort.to_string(),+ )+ .with_option("join_algorithm", join_algorithm.as_str()))+}++#[cfg(test)]+mod tests {+ use std::collections::HashMap;++ use envconfig::Envconfig;++ use super::*;++ fn default_config() -> Config {+ Config::init_from_hashmap(&HashMap::new()).unwrap()+ }++ fn endpoint(config: &Config) -> String {+ ClickHouseEndpoint::resolve(config).as_str().to_string()+ }++ #[test]+ fn bare_clickhouse_hosts_get_the_canonical_port_for_the_scheme() {+ for (secure, expected) in [+ (false, "http://clickhouse.internal:8123"),+ (true, "https://clickhouse.internal:8443"),+ ] {+ let mut config = default_config();+ config.clickhouse_host = "clickhouse.internal".to_string();+ config.clickhouse_secure = secure;+ assert_eq!(endpoint(&config), expected);+ }++ let mut config = default_config();+ config.clickhouse_host = "fallback.internal".to_string();+ config.clickhouse_offline_cluster_host = "offline.internal".to_string();+ config.clickhouse_secure = true;+ assert_eq!(endpoint(&config), "https://offline.internal:8443");+ }++ #[test]+ fn explicit_clickhouse_urls_and_ports_are_preserved() {+ let mut config = default_config();+ config.clickhouse_url = "https://proxy.example:9440/clickhouse".to_string();+ assert_eq!(endpoint(&config), "https://proxy.example:9440/clickhouse");++ config.clickhouse_url.clear();+ config.clickhouse_host = "clickhouse.internal:9000".to_string();+ config.clickhouse_secure = true;+ assert_eq!(endpoint(&config), "https://clickhouse.internal:9000");+ }++ #[test]+ fn join_algorithm_default_config_parses_and_round_trips() {+ assert_eq!(+ default_config()+ .seeder_ch_join_algorithm+ .parse::<ClickHouseJoinAlgorithm>()+ .unwrap(),+ ClickHouseJoinAlgorithm::GraceHash+ );+ for algorithm in [+ ClickHouseJoinAlgorithm::Default,+ ClickHouseJoinAlgorithm::Auto,+ ClickHouseJoinAlgorithm::Hash,+ ClickHouseJoinAlgorithm::ParallelHash,+ ClickHouseJoinAlgorithm::GraceHash,+ ClickHouseJoinAlgorithm::PartialMerge,+ ClickHouseJoinAlgorithm::PreferPartialMerge,+ ClickHouseJoinAlgorithm::FullSortingMerge,+ ClickHouseJoinAlgorithm::Direct,+ ] {+ assert_eq!(+ algorithm+ .as_str()+ .parse::<ClickHouseJoinAlgorithm>()+ .unwrap(),+ algorithm+ );+ }+ }++ #[test]+ fn build_client_rejects_a_join_algorithm_typo_at_startup() {+ let mut config = default_config();+ config.seeder_ch_join_algorithm = "grace_hashh".to_string();+ assert_eq!(+ build_client(&config).err(),+ Some(UnknownJoinAlgorithm("grace_hashh".to_string()))+ );+ }+}diff --git a/rust/cohort-seeder/src/clickhouse/mod.rs b/rust/cohort-seeder/src/clickhouse/mod.rsnew file mode 100644index 000000000000..81fa5e40a399--- /dev/null+++ b/rust/cohort-seeder/src/clickhouse/mod.rs@@ -0,0 +1,10 @@+//! ClickHouse layer: scan planning, row decoding, the streaming scanner, and the client builder.+//! Depends only on `domain` and `config` (plus the `clickhouse` crate); never on `store` or `kafka`.++pub mod client;+pub mod row;+pub mod scanner;+pub mod sql;++pub use client::{build_client, ClickHouseEndpoint, ClickHouseJoinAlgorithm};+pub use scanner::{ChunkScanner, ScanError};diff --git a/rust/cohort-seeder/src/clickhouse/row.rs b/rust/cohort-seeder/src/clickhouse/row.rsnew file mode 100644index 000000000000..562c46e31355--- /dev/null+++ b/rust/cohort-seeder/src/clickhouse/row.rs@@ -0,0 +1,83 @@+//! ClickHouse row decoding: the scanned event columns and their lift into a `CohortStreamEvent`.+//! Depends on `cohort-core`; never on `store` or `domain`.++use clickhouse::Row;+use cohort_core::events::CohortStreamEvent;+use cohort_core::filters::TeamId;+use serde::Deserialize;++#[derive(Debug, Row, Deserialize, PartialEq, Eq)]+pub struct EventRow {+ pub uuid: String,+ pub event: String,+ pub properties: String,+ pub timestamp: String,+ pub distinct_id: String,+ pub person_id: String,+ pub person_properties: String,+ pub elements_chain: String,+}++pub fn row_to_event(team_id: TeamId, row: EventRow) -> CohortStreamEvent {+ CohortStreamEvent {+ team_id: team_id.0,+ person_id: row.person_id,+ distinct_id: row.distinct_id,+ uuid: row.uuid,+ event: row.event,+ timestamp: row.timestamp,+ properties: non_empty(row.properties),+ person_properties: non_empty(row.person_properties),+ elements_chain: non_empty(row.elements_chain),+ source_offset: 0,+ source_partition: -1,+ redirected_from: None,+ redirect_hops: 0,+ }+}++fn non_empty(value: String) -> Option<String> {+ (!value.is_empty()).then_some(value)+}++#[cfg(test)]+mod tests {+ use uuid::Uuid;++ use super::*;++ fn row(timestamp: &str) -> EventRow {+ EventRow {+ uuid: Uuid::from_u128(1).to_string(),+ event: "purchase".to_string(),+ properties: "{}".to_string(),+ timestamp: timestamp.to_string(),+ distinct_id: "distinct".to_string(),+ person_id: Uuid::from_u128(2).to_string(),+ person_properties: "{}".to_string(),+ elements_chain: String::new(),+ }+ }++ #[test]+ fn row_conversion_restores_optional_fields_and_seed_sentinels() {+ let event = row_to_event(+ TeamId(2),+ EventRow {+ properties: String::new(),+ person_properties: "{\"plan\":\"paid\"}".to_string(),+ elements_chain: String::new(),+ ..row("1970-01-02 12:00:00.000000")+ },+ );+ assert_eq!(event.team_id, 2);+ assert_eq!(event.properties, None);+ assert_eq!(+ event.person_properties.as_deref(),+ Some("{\"plan\":\"paid\"}")+ );+ assert_eq!(event.elements_chain, None);+ assert_eq!(event.source_partition, -1);+ assert_eq!(event.source_offset, 0);+ }+}diff --git a/rust/cohort-seeder/src/clickhouse/scanner.rs b/rust/cohort-seeder/src/clickhouse/scanner.rsnew file mode 100644index 000000000000..f658821435b8--- /dev/null+++ b/rust/cohort-seeder/src/clickhouse/scanner.rs@@ -0,0 +1,444 @@+//! The streaming ClickHouse scanner: drives one chunk's query, folds rows through the shared+//! evaluator into tiles, and emits the scan metrics. Depends on `domain`, `config`, and the sibling+//! `sql`/`row` modules; never on `store` or `kafka`.++use std::time::Instant;++use chrono::Utc;+use chrono_tz::Tz;+use cohort_core::clickhouse_timestamp_to_millis;+use cohort_core::day_idx_in_tz;+use cohort_core::events::CohortStreamEvent;+use cohort_core::hogvm::VmErrorClass;+use metrics::{counter, histogram};+use tokio_util::sync::CancellationToken;+use tracing::info;++use super::row::{row_to_event, EventRow};+use super::sql::{plan_scan, scan_sql, ScanPlan};+use crate::domain::{+ conditions_active_on, ActiveConditions, AggregateError, CancelCause, ChunkAccumulator,+ ChunkDomainError, ClaimedChunk, DayIdx, EventNameSet, Halted, PinnedCondition, PinnedRun,+ RecordOutcome, RecordStats, ScannedChunk, SeedDomain, SeedTile, UtcMillis,+};+use crate::observability::metrics::{+ AGGREGATE_ENTRIES, CHUNKS_VACUOUS, CHUNK_SCAN_DURATION_SECONDS, CONDITIONS_EVALUATED,+ EVENTS_SKIPPED, HOGVM_ERRORS, ROWS_SCANNED,+};++#[derive(Clone)]+pub struct ChunkScanner {+ client: clickhouse::Client,+}++impl ChunkScanner {+ pub fn new(client: clickhouse::Client) -> Self {+ Self { client }+ }++ pub async fn scan(+ &self,+ chunk: ClaimedChunk,+ run: &PinnedRun,+ lease_cancel: &CancellationToken,+ shutdown: &CancellationToken,+ ) -> Result<ScannedChunk, Halted<ClaimedChunk, ScanError>> {+ self.scan_at(+ chunk,+ run,+ Utc::now().timestamp_millis(),+ lease_cancel,+ shutdown,+ )+ .await+ }++ async fn scan_at(+ &self,+ chunk: ClaimedChunk,+ run: &PinnedRun,+ now_ms: i64,+ lease_cancel: &CancellationToken,+ shutdown: &CancellationToken,+ ) -> Result<ScannedChunk, Halted<ClaimedChunk, ScanError>> {+ match self+ .scan_tiles(&chunk, run, now_ms, lease_cancel, shutdown)+ .await+ {+ Ok(tiles) => Ok(chunk.into_scanned(tiles)),+ Err(ScanHalt::Cancelled(cause)) => Err(Halted::cancelled(chunk, cause)),+ Err(ScanHalt::Failed(source)) => Err(Halted::failed(chunk, source)),+ }+ }++ async fn scan_tiles(+ &self,+ chunk: &ClaimedChunk,+ run: &PinnedRun,+ now_ms: i64,+ lease_cancel: &CancellationToken,+ shutdown: &CancellationToken,+ ) -> Result<Vec<SeedTile>, ScanHalt> {+ let _timer = ScanTimer::start();+ let spec = chunk.spec();+ let domain = run.domain_for(&spec).map_err(ScanError::from)?;+ let active = active_conditions_at(spec.day, run.tz, now_ms, &run.conditions);+ if active.is_empty() {+ info!(+ day = spec.day,+ boundary_day = run.boundary.day(),+ "chunk skipped: every referencing window has slid past this day"+ );+ counter!(CHUNKS_VACUOUS, "reason" => "window_expired").increment(1);+ return Ok(Vec::new());+ }+ let event_names = active_event_names(run, &active);+ let scan_spec = match plan_scan(spec.team_id, &domain, &event_names, spec.band) {+ ScanPlan::Scan(scan_spec) => scan_spec,+ ScanPlan::Vacuous => {+ counter!(CHUNKS_VACUOUS, "reason" => "empty_scan").increment(1);+ return Ok(Vec::new());+ }+ };++ let mut cursor = self+ .client+ .query(&scan_sql(&scan_spec))+ .fetch::<EventRow>()+ .map_err(ScanError::Query)?;+ let mut accumulator =+ ChunkAccumulator::new(run.team_id, &run.filters, &active).map_err(ScanError::from)?;+ let mut saw_row = false;++ loop {+ let row = tokio::select! {+ biased;+ _ = shutdown.cancelled() => return Err(ScanHalt::Cancelled(CancelCause::Shutdown)),+ _ = lease_cancel.cancelled() => return Err(ScanHalt::Cancelled(CancelCause::LeaseLost)),+ row = cursor.next() => row.map_err(ScanError::Cursor)?,+ };+ let Some(row) = row else {+ break;+ };+ saw_row = true;+ counter!(ROWS_SCANNED).increment(1);+ match fold_event(&domain, &mut accumulator, row_to_event(run.team_id, row))+ .map_err(ScanError::from)?+ {+ ScanEventOutcome::Evaluated(stats) => record_evaluation(stats),+ ScanEventOutcome::Skipped(reason) => {+ counter!(EVENTS_SKIPPED, "reason" => reason.as_str()).increment(1);+ }+ }+ }+ if !saw_row {+ counter!(CHUNKS_VACUOUS, "reason" => "no_rows").increment(1);+ }++ histogram!(AGGREGATE_ENTRIES).record(accumulator.entry_count() as f64);+ let tiles = accumulator.into_tiles(&domain, run.run_id, spec.lease.epoch());+ Ok(tiles)+ }+}++/// The scanner's internal stop signal, lifted to a [`Halted`] by `scan_at`: a cancellation cause or+/// a terminal [`ScanError`].+enum ScanHalt {+ Cancelled(CancelCause),+ Failed(ScanError),+}++impl From<ScanError> for ScanHalt {+ fn from(error: ScanError) -> Self {+ Self::Failed(error)+ }+}++/// The conditions still referencing `day` at scan time, gated at wall-clock now — deliberately NOT+/// at the run's boundary day. Planning anchors at the boundary pessimistically; by the time a chunk+/// is scanned, a sliding window may have moved past its day, and the consumer's apply rule slides+/// each record's window to at least the wall-clock day before evaluating, dropping below-window+/// tiles unevaluated. Scanning such a day would only produce tiles the consumer must discard.+///+/// This holds for disaster-recovery runs, whose boundary is a past instant: the boundary is the+/// timestamp the wiped processor resumes live consumption from, so every post-boundary day is+/// covered by live replay, and any pre-boundary day still inside a window anchored at the scan day+/// or later stays admitted here (window anchors only move forward, so the gate at scan time admits+/// a superset of every later evaluation's reachable days). The only skipped days are those that can+/// no longer affect membership at any evaluation from scan time on.+fn active_conditions_at(+ day: DayIdx,+ tz: Tz,+ now_ms: i64,+ conditions: &[PinnedCondition],+) -> ActiveConditions {+ conditions_active_on(day, day_idx_in_tz(now_ms, tz), conditions)+}++fn active_event_names(run: &PinnedRun, active: &ActiveConditions) -> EventNameSet {+ EventNameSet::new(+ run.event_names+ .iter()+ .filter(|event_name| {+ run.filters+ .behavioral_by_event_name+ .get(*event_name)+ .is_some_and(|hashes| hashes.iter().any(|hash| active.get(hash).is_some()))+ })+ .cloned(),+ )+}++fn fold_event(+ domain: &SeedDomain,+ accumulator: &mut ChunkAccumulator,+ event: CohortStreamEvent,+) -> Result<ScanEventOutcome, AggregateError> {+ let Some(timestamp_ms) = clickhouse_timestamp_to_millis(&event.timestamp) else {+ return Ok(ScanEventOutcome::Skipped(ScanSkipReason::TimestampParse));+ };+ if !domain.contains(UtcMillis::new(timestamp_ms)) {+ return Ok(ScanEventOutcome::Skipped(ScanSkipReason::DayMismatch));+ }+ Ok(match accumulator.record_event(&event)? {+ RecordOutcome::Evaluated(stats) => ScanEventOutcome::Evaluated(stats),+ RecordOutcome::SkippedGlobals => {+ ScanEventOutcome::Skipped(ScanSkipReason::GlobalsParseError)+ }+ })+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum ScanEventOutcome {+ Evaluated(RecordStats),+ Skipped(ScanSkipReason),+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum ScanSkipReason {+ TimestampParse,+ DayMismatch,+ GlobalsParseError,+}++impl ScanSkipReason {+ const fn as_str(self) -> &'static str {+ match self {+ Self::TimestampParse => "timestamp_parse",+ Self::DayMismatch => "day_mismatch",+ Self::GlobalsParseError => "globals_parse_error",+ }+ }+}++fn record_evaluation(stats: RecordStats) {+ let evaluated = u64::from(stats.matched)+ + u64::from(stats.non_matched)+ + u64::from(stats.unknown_functions)+ + stats+ .vm_failures+ .iter()+ .map(|(_, count)| u64::from(count))+ .sum::<u64>();+ counter!(CONDITIONS_EVALUATED).increment(evaluated);+ if stats.unknown_functions > 0 {+ counter!(HOGVM_ERRORS, "class" => VmErrorClass::UnknownFunction.as_str())+ .increment(u64::from(stats.unknown_functions));+ }+ for (class, count) in stats.vm_failures.iter().filter(|(_, count)| *count > 0) {+ counter!(HOGVM_ERRORS, "class" => class.as_str()).increment(u64::from(count));+ }+}++struct ScanTimer(Instant);++impl ScanTimer {+ fn start() -> Self {+ Self(Instant::now())+ }+}++impl Drop for ScanTimer {+ fn drop(&mut self) {+ histogram!(CHUNK_SCAN_DURATION_SECONDS).record(self.0.elapsed().as_secs_f64());+ }+}++#[derive(Debug, thiserror::Error)]+pub enum ScanError {+ #[error("resolving the chunk seed domain")]+ Domain(#[from] ChunkDomainError),+ #[error("building ClickHouse scan cursor")]+ Query(#[source] clickhouse::error::Error),+ #[error("streaming ClickHouse scan cursor")]+ Cursor(#[source] clickhouse::error::Error),+ #[error("aggregating ClickHouse scan row")]+ Aggregate(#[from] AggregateError),+}++#[cfg(test)]+mod tests {+ use chrono_tz::UTC;+ use cohort_core::filters::{CohortId, TeamFilters, TeamFiltersBuilder, TeamId};+ use serde_json::json;+ use uuid::Uuid;++ use std::collections::BTreeSet;++ use super::*;+ use crate::domain::{+ plan_days, Boundary, ClaimEpoch, ConditionHash, Lookback, PlanCaps, RunId, SChunkMs,+ };++ const HASH: &str = "aaaaaaaaaaaaaaaa";++ fn domain() -> SeedDomain {+ SeedDomain::new(+ 1,+ Boundary::new(UtcMillis::new(2 * 86_400_000), UTC),+ UTC,+ SChunkMs(200_000_000),+ )+ .unwrap()+ }++ fn filters() -> TeamFilters {+ let mut builder = TeamFiltersBuilder::default();+ builder+ .add_cohort(+ CohortId(1),+ TeamId(2),+ &json!({+ "properties": { "type": "AND", "values": [{+ "type": "behavioral",+ "value": "performed_event",+ "key": "purchase",+ "conditionHash": HASH,+ "time_value": 7,+ "time_interval": "day",+ "bytecode": ["_H", 1, 32, "purchase", 32, "event", 1, 1, 11]+ }]}+ }),+ )+ .unwrap();+ builder.freeze(UTC)+ }++ fn row(timestamp: &str) -> EventRow {+ EventRow {+ uuid: Uuid::from_u128(1).to_string(),+ event: "purchase".to_string(),+ properties: "{}".to_string(),+ timestamp: timestamp.to_string(),+ distinct_id: "distinct".to_string(),+ person_id: Uuid::from_u128(2).to_string(),+ person_properties: "{}".to_string(),+ elements_chain: String::new(),+ }+ }++ #[test]+ fn scan_fold_skips_bad_timestamps_wrong_days_and_malformed_globals() {+ let domain = domain();+ let filters = filters();+ let active = ActiveConditions::new([ConditionHash::parse(HASH).unwrap()]);+ let cases = [+ (+ row("not-a-timestamp"),+ ScanEventOutcome::Skipped(ScanSkipReason::TimestampParse),+ ),+ (+ row("1970-01-03 12:00:00.000000"),+ ScanEventOutcome::Skipped(ScanSkipReason::DayMismatch),+ ),+ (+ EventRow {+ properties: "not-json".to_string(),+ ..row("1970-01-02 12:00:00.000000")+ },+ ScanEventOutcome::Skipped(ScanSkipReason::GlobalsParseError),+ ),+ ];+ for (row, expected) in cases {+ let mut accumulator = ChunkAccumulator::new(TeamId(2), &filters, &active).unwrap();+ assert_eq!(+ fold_event(&domain, &mut accumulator, row_to_event(TeamId(2), row)).unwrap(),+ expected+ );+ assert_eq!(accumulator.entry_count(), 0);+ }+ }++ #[test]+ fn scan_fold_uses_the_shared_evaluator_and_accumulator() {+ let domain = domain();+ let filters = filters();+ let active = ActiveConditions::new([ConditionHash::parse(HASH).unwrap()]);+ let mut accumulator = ChunkAccumulator::new(TeamId(2), &filters, &active).unwrap();+ assert_eq!(+ fold_event(+ &domain,+ &mut accumulator,+ row_to_event(TeamId(2), row("1970-01-02 12:00:00.000000")),+ )+ .unwrap(),+ ScanEventOutcome::Evaluated(RecordStats {+ matched: 1,+ ..RecordStats::default()+ })+ );+ let tiles = accumulator.into_tiles(&domain, RunId(Uuid::nil()), ClaimEpoch(1));+ assert_eq!(tiles.len(), 1);+ assert_eq!(tiles[0].count(), 1);+ }++ #[test]+ fn scan_time_rechecks_sliding_conditions_against_the_current_day() {+ let hash = ConditionHash::parse(HASH).unwrap();+ let conditions = [PinnedCondition {+ cohort_id: CohortId(1),+ hash,+ event_name: "purchase".to_string(),+ lookback: Lookback::SlidingDays(1),+ }];+ assert!(active_conditions_at(1, UTC, 2 * 86_400_000, &conditions).contains(&hash));+ assert!(!active_conditions_at(1, UTC, 3 * 86_400_000, &conditions).contains(&hash));+ }++ /// Disaster-recovery shape: the boundary is a past instant, so the scan runs days after the+ /// plan was anchored. Every pre-boundary day still inside the wall-clock window must stay+ /// admitted (those days feed membership the live replay cannot reconstruct); days that slid+ /// out of every window are skipped, matching the consumer's drop-below-window apply rule.+ #[test]+ fn dr_scan_admits_every_pre_boundary_day_still_inside_the_window() {+ let hash = ConditionHash::parse(HASH).unwrap();+ let conditions = [PinnedCondition {+ cohort_id: CohortId(1),+ hash,+ event_name: "purchase".to_string(),+ lookback: Lookback::SlidingDays(7),+ }];+ let boundary = Boundary::new(UtcMillis::new(100 * 86_400_000), UTC);+ let planned = plan_days(&conditions, boundary, &PlanCaps::default());+ assert_eq!(planned, BTreeSet::from_iter(93..=99));++ let admitted_at = |now_day: i64| {+ planned+ .iter()+ .copied()+ .filter(|day| {+ active_conditions_at(*day, UTC, now_day * 86_400_000, &conditions)+ .contains(&hash)+ })+ .collect::<Vec<_>>()+ };+ // Scanned the boundary day (enablement shape): every planned day is admitted.+ assert_eq!(admitted_at(100), (93..=99).collect::<Vec<_>>());+ // Scanned three days later (DR shape): the window is [96, 103]; days 93-95 can no longer+ // affect any evaluation and are skipped, days 96-99 are still scanned.+ assert_eq!(admitted_at(103), (96..=99).collect::<Vec<_>>());+ // Boundary older than the window: live replay from the boundary covers the whole window,+ // so the seed correctly has nothing left to contribute.+ assert_eq!(admitted_at(107), Vec::<DayIdx>::new());+ }+}diff --git a/rust/cohort-seeder/src/clickhouse/sql.rs b/rust/cohort-seeder/src/clickhouse/sql.rsnew file mode 100644index 000000000000..71f2401a1808--- /dev/null+++ b/rust/cohort-seeder/src/clickhouse/sql.rs@@ -0,0 +1,197 @@+//! ClickHouse scan planning: the `Vacuous`-vs-`Scan` parse and the byte-frozen SQL renderer. Depends+//! on `domain` (the proven range/band/event-name inputs) and `cohort-core`; never on `store`.++use std::num::NonZeroU32;++use cohort_core::filters::TeamId;++use crate::domain::{BandSpec, EventNameSet, SeedDomain};++/// The rendered scan's inputs, proven complete: constructed only by [`plan_scan`] from already-proven+/// types, so [`scan_sql`] never re-validates. Fields stay private — the SQL text is the only output.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ScanSpec {+ team_id: TeamId,+ day_start_ms: i64,+ day_end_ms: i64,+ s_chunk_ms: i64,+ event_names: Vec<String>,+ band: u32,+ num_bands: NonZeroU32,+}++/// Whether a chunk has anything to scan. `plan_scan` collapses the empty-domain and empty-event-name+/// cases into [`ScanPlan::Vacuous`], so the scanner treats "nothing to do" as a parse, not a check.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum ScanPlan {+ Vacuous,+ Scan(ScanSpec),+}++/// Parse a claimed chunk into a scan plan. Takes the resolved `EventNameSet` by reference (already+/// sorted and deduplicated), so no set is rebuilt. An empty domain or empty event set is vacuous.+pub fn plan_scan(+ team_id: TeamId,+ domain: &SeedDomain,+ event_names: &EventNameSet,+ band: BandSpec,+) -> ScanPlan {+ if domain.is_empty() || event_names.is_empty() {+ return ScanPlan::Vacuous;+ }+ let range = domain.utc_range();+ ScanPlan::Scan(ScanSpec {+ team_id,+ day_start_ms: range.start().as_i64(),+ day_end_ms: range.end().as_i64(),+ s_chunk_ms: domain.s_chunk().0,+ event_names: event_names.as_slice().to_vec(),+ band: band.band(),+ num_bands: band.num_bands(),+ })+}++pub fn scan_sql(spec: &ScanSpec) -> String {+ let event_names = spec+ .event_names+ .iter()+ .map(|name| clickhouse_string_literal(name))+ .collect::<Vec<_>>()+ .join(", ");+ let band_predicate = if spec.num_bands.get() > 1 {+ format!(+ "\n AND cityHash64(toString(if(notEmpty(ov.distinct_id), ov.person_id, e.person_id)))\n % {} = {}",+ spec.num_bands, spec.band+ )+ } else {+ String::new()+ };++ format!(+ "SELECT toString(e.uuid) AS uuid, e.event, e.properties, toString(e.timestamp) AS timestamp,\n e.distinct_id,\n toString(if(notEmpty(ov.distinct_id), ov.person_id, e.person_id)) AS person_id,\n e.person_properties, e.elements_chain\nFROM events AS e\nLEFT JOIN (\n SELECT distinct_id, argMax(person_id, version) AS person_id\n FROM person_distinct_id_overrides\n WHERE team_id = {}\n GROUP BY distinct_id\n HAVING argMax(is_deleted, version) = 0\n) AS ov ON e.distinct_id = ov.distinct_id\nWHERE e.team_id = {}\n AND e.timestamp >= fromUnixTimestamp64Milli({})\n AND e.timestamp < fromUnixTimestamp64Milli({})\n AND e.event IN ({})\n AND coalesce(e.inserted_at, e._timestamp) < fromUnixTimestamp64Milli({}){}",+ spec.team_id.0,+ spec.team_id.0,+ spec.day_start_ms,+ spec.day_end_ms,+ event_names,+ spec.s_chunk_ms,+ band_predicate,+ )+}++fn clickhouse_string_literal(value: &str) -> String {+ let mut escaped = String::with_capacity(value.len() + 2);+ escaped.push('\'');+ for character in value.chars() {+ match character {+ '\\' => escaped.push_str("\\\\"),+ '\'' => escaped.push_str("\\'"),+ '`' => escaped.push_str("\\`"),+ // Client-side, not server-side: the `clickhouse` crate's template parser treats every+ // bare `?` as a bind placeholder — even inside string literals — and fails the query+ // with "unbound query argument". `??` collapses back to a literal `?` before the SQL+ // reaches the server.+ '?' => escaped.push_str("??"),+ '\0' => escaped.push_str("\\0"),+ '\u{0007}' => escaped.push_str("\\a"),+ '\u{0008}' => escaped.push_str("\\b"),+ '\t' => escaped.push_str("\\t"),+ '\n' => escaped.push_str("\\n"),+ '\u{000B}' => escaped.push_str("\\v"),+ '\u{000C}' => escaped.push_str("\\f"),+ '\r' => escaped.push_str("\\r"),+ character if character.is_control() => {+ let mut bytes = [0; 4];+ for byte in character.encode_utf8(&mut bytes).as_bytes() {+ escaped.push_str(&format!("\\x{byte:02X}"));+ }+ }+ character => escaped.push(character),+ }+ }+ escaped.push('\'');+ escaped+}++#[cfg(test)]+mod tests {+ use chrono_tz::UTC;++ use super::*;+ use crate::domain::{Boundary, SChunkMs, SeedDomain, UtcMillis};++ fn domain() -> SeedDomain {+ SeedDomain::new(+ 1,+ Boundary::new(UtcMillis::new(2 * 86_400_000), UTC),+ UTC,+ SChunkMs(200_000_000),+ )+ .unwrap()+ }++ fn spec(event_names: Vec<String>, band: BandSpec) -> ScanSpec {+ match plan_scan(TeamId(2), &domain(), &EventNameSet::new(event_names), band) {+ ScanPlan::Scan(spec) => spec,+ ScanPlan::Vacuous => panic!("expected a scannable plan"),+ }+ }++ #[test]+ fn unbanded_scan_sql_pins_tenant_time_cutoff_and_override_semantics() {+ let spec = spec(+ vec!["purchase".to_string(), "$pageview".to_string()],+ BandSpec::new(0, 1).unwrap(),+ );+ assert_eq!(+ scan_sql(&spec),+ "SELECT toString(e.uuid) AS uuid, e.event, e.properties, toString(e.timestamp) AS timestamp,\n e.distinct_id,\n toString(if(notEmpty(ov.distinct_id), ov.person_id, e.person_id)) AS person_id,\n e.person_properties, e.elements_chain\nFROM events AS e\nLEFT JOIN (\n SELECT distinct_id, argMax(person_id, version) AS person_id\n FROM person_distinct_id_overrides\n WHERE team_id = 2\n GROUP BY distinct_id\n HAVING argMax(is_deleted, version) = 0\n) AS ov ON e.distinct_id = ov.distinct_id\nWHERE e.team_id = 2\n AND e.timestamp >= fromUnixTimestamp64Milli(86400000)\n AND e.timestamp < fromUnixTimestamp64Milli(172800000)\n AND e.event IN ('$pageview', 'purchase')\n AND coalesce(e.inserted_at, e._timestamp) < fromUnixTimestamp64Milli(200000000)"+ );+ }++ #[test]+ fn banded_scan_sql_hashes_the_resolved_person() {+ let spec = spec(vec!["purchase".to_string()], BandSpec::new(3, 8).unwrap());+ assert_eq!(+ scan_sql(&spec),+ "SELECT toString(e.uuid) AS uuid, e.event, e.properties, toString(e.timestamp) AS timestamp,\n e.distinct_id,\n toString(if(notEmpty(ov.distinct_id), ov.person_id, e.person_id)) AS person_id,\n e.person_properties, e.elements_chain\nFROM events AS e\nLEFT JOIN (\n SELECT distinct_id, argMax(person_id, version) AS person_id\n FROM person_distinct_id_overrides\n WHERE team_id = 2\n GROUP BY distinct_id\n HAVING argMax(is_deleted, version) = 0\n) AS ov ON e.distinct_id = ov.distinct_id\nWHERE e.team_id = 2\n AND e.timestamp >= fromUnixTimestamp64Milli(86400000)\n AND e.timestamp < fromUnixTimestamp64Milli(172800000)\n AND e.event IN ('purchase')\n AND coalesce(e.inserted_at, e._timestamp) < fromUnixTimestamp64Milli(200000000)\n AND cityHash64(toString(if(notEmpty(ov.distinct_id), ov.person_id, e.person_id)))\n % 8 = 3"+ );+ }++ #[test]+ fn scan_sql_escapes_hostile_event_names_as_literals() {+ let spec = spec(+ vec![+ "quote' OR 1 = 1 --".to_string(),+ "slash\\name\nnext".to_string(),+ ],+ BandSpec::new(0, 1).unwrap(),+ );+ assert_eq!(+ scan_sql(&spec),+ "SELECT toString(e.uuid) AS uuid, e.event, e.properties, toString(e.timestamp) AS timestamp,\n e.distinct_id,\n toString(if(notEmpty(ov.distinct_id), ov.person_id, e.person_id)) AS person_id,\n e.person_properties, e.elements_chain\nFROM events AS e\nLEFT JOIN (\n SELECT distinct_id, argMax(person_id, version) AS person_id\n FROM person_distinct_id_overrides\n WHERE team_id = 2\n GROUP BY distinct_id\n HAVING argMax(is_deleted, version) = 0\n) AS ov ON e.distinct_id = ov.distinct_id\nWHERE e.team_id = 2\n AND e.timestamp >= fromUnixTimestamp64Milli(86400000)\n AND e.timestamp < fromUnixTimestamp64Milli(172800000)\n AND e.event IN ('quote\\' OR 1 = 1 --', 'slash\\\\name\\nnext')\n AND coalesce(e.inserted_at, e._timestamp) < fromUnixTimestamp64Milli(200000000)"+ );+ }++ /// A `?` in an event name is a client-side hazard, not a server-side one: the `clickhouse`+ /// crate's template parser turns every bare `?` into a bind placeholder (and `?fields` into a+ /// struct-fields expansion) even inside string literals, failing the whole scan with+ /// "unbound query argument". Doubling each `?` renders the literal the server actually sees.+ #[test]+ fn scan_sql_doubles_question_marks_so_the_client_never_sees_a_placeholder() {+ let spec = spec(+ vec!["converted?".to_string(), "why?fields".to_string()],+ BandSpec::new(0, 1).unwrap(),+ );+ let sql = scan_sql(&spec);+ assert!(sql.contains("e.event IN ('converted??', 'why??fields')"));+ let unescaped_placeholders = sql+ .char_indices()+ .filter(|(_, character)| *character == '?')+ .filter(|(index, _)| {+ !sql[index + 1..].starts_with('?') && (*index == 0 || !sql[..*index].ends_with('?'))+ })+ .count();+ assert_eq!(unescaped_placeholders, 0, "a lone `?` survived escaping");+ }+}diff --git a/rust/cohort-seeder/src/config.rs b/rust/cohort-seeder/src/config.rsnew file mode 100644index 000000000000..a5088018731c--- /dev/null+++ b/rust/cohort-seeder/src/config.rs@@ -0,0 +1,298 @@+//! Service configuration and infrastructure client builders — the `envconfig` mirror plus the pool+//! and Kafka builders. A leaf: it names no other seeder module, so dependency arrows point at it,+//! never away.++use std::fmt;+use std::num::NonZeroU32;+use std::str::FromStr;+use std::time::Duration;++use common_database::PoolConfig;+use common_kafka::config::KafkaConfig;+use common_types::cohort::TeamAllowlist;+use envconfig::Envconfig;++const POOL_NAME: &str = "posthog_cohort_seeder";++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum KafkaProducerPartitioner {+ Murmur2Random,+}++impl KafkaProducerPartitioner {+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::Murmur2Random => "murmur2_random",+ }+ }+}++impl fmt::Display for KafkaProducerPartitioner {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter.write_str(self.as_str())+ }+}++impl FromStr for KafkaProducerPartitioner {+ type Err = InvalidKafkaProducerPartitioner;++ fn from_str(value: &str) -> Result<Self, Self::Err> {+ match value {+ "murmur2_random" => Ok(Self::Murmur2Random),+ other => Err(InvalidKafkaProducerPartitioner(other.to_string())),+ }+ }+}++#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]+#[error("Kafka producer partitioner must be murmur2_random, got {0:?}")]+pub struct InvalidKafkaProducerPartitioner(String);++#[derive(Clone, Debug, Envconfig)]+pub struct Config {+ #[envconfig(default = "0.0.0.0")]+ pub bind_host: String,++ #[envconfig(default = "3324")]+ pub bind_port: u16,++ #[envconfig(default = "true")]+ pub export_prometheus: bool,++ #[envconfig(default = "localhost:9092")]+ pub kafka_hosts: String,++ #[envconfig(default = "false")]+ pub kafka_tls: bool,++ #[envconfig(default = "")]+ pub kafka_client_rack: String,++ #[envconfig(default = "")]+ pub kafka_client_id: String,++ #[envconfig(+ from = "COHORT_STREAM_SEED_EVENTS_TOPIC",+ default = "cohort_stream_seed_events"+ )]+ pub seed_events_topic: String,++ #[envconfig(default = "murmur2_random")]+ pub kafka_producer_partitioner: KafkaProducerPartitioner,++ /// The partition count every co-partitioned cohort topic must have — the consumer owns a+ /// person by `partition_for(key, COHORT_PARTITION_COUNT)`, so a seed topic provisioned with a+ /// different count would route a person's seed tiles to a worker that does not own them.+ /// Mirrors the processor's `COHORT_PARTITION_COUNT`; startup verifies the seed topic against it.+ #[envconfig(from = "COHORT_PARTITION_COUNT", default = "64")]+ pub cohort_partition_count: u32,++ #[envconfig(default = "none")]+ pub kafka_compression_codec: String,++ #[envconfig(default = "100")]+ pub kafka_producer_linger_ms: u32,++ #[envconfig(default = "64")]+ pub kafka_producer_queue_mib: u32,++ #[envconfig(default = "100000")]+ pub kafka_producer_queue_messages: u32,++ #[envconfig(default = "postgres://posthog:posthog@localhost:5432/posthog")]+ pub database_url: String,++ #[envconfig(default = "1")]+ pub min_pg_connections: u32,++ #[envconfig(default = "5")]+ pub max_pg_connections: u32,++ #[envconfig(default = "10")]+ pub pg_acquire_timeout_secs: u64,++ #[envconfig(default = "5000")]+ pub pg_statement_timeout_ms: u64,++ #[envconfig(default = "")]+ pub clickhouse_url: String,++ #[envconfig(default = "")]+ pub clickhouse_offline_cluster_host: String,++ #[envconfig(default = "localhost:8123")]+ pub clickhouse_host: String,++ #[envconfig(default = "default")]+ pub clickhouse_user: String,++ #[envconfig(default = "")]+ pub clickhouse_password: String,++ #[envconfig(default = "default")]+ pub clickhouse_database: String,++ #[envconfig(default = "false")]+ pub clickhouse_secure: bool,++ #[envconfig(from = "REALTIME_COHORT_TEAM_ALLOWLIST", default = "2")]+ pub team_allowlist: TeamAllowlist,++ #[envconfig(default = "15")]+ pub seeder_run_poll_secs: u64,++ #[envconfig(default = "1")]+ pub seeder_max_concurrent_chunks: usize,++ #[envconfig(default = "900")]+ pub seeder_chunk_lease_secs: u64,++ #[envconfig(default = "5")]+ pub seeder_max_chunk_attempts: u32,++ #[envconfig(default = "3000")]+ pub seeder_tiles_per_sec: u32,++ #[envconfig(default = "4000")]+ pub seeder_max_inflight_tiles: usize,++ #[envconfig(default = "400")]+ pub seeder_max_lookback_days: u32,++ /// Person-hash bands each planned day is split into, bounding one chunk's in-memory aggregate+ /// to roughly `uniq(person, condition) / bands`. Safe to raise mid-run: planning is idempotent+ /// per (run, day, band) and tile application is max-merge idempotent, so a re-planned day only+ /// adds narrower re-scans.+ #[envconfig(default = "1")]+ pub seeder_bands_per_day: u16,++ #[envconfig(default = "14400")]+ pub seeder_ch_max_execution_time_secs: u64,++ #[envconfig(default = "20000000000")]+ pub seeder_ch_max_bytes_before_external_group_by: u64,++ #[envconfig(default = "20000000000")]+ pub seeder_ch_max_bytes_before_external_sort: u64,++ #[envconfig(default = "grace_hash")]+ pub seeder_ch_join_algorithm: String,++ #[envconfig(default = "100")]+ pub seeder_queue_full_backoff_ms: u64,+}++impl Config {+ pub fn bind_address(&self) -> String {+ format!("{}:{}", self.bind_host, self.bind_port)+ }++ pub fn pool_config(&self) -> PoolConfig {+ PoolConfig {+ min_connections: self.min_pg_connections,+ max_connections: self.max_pg_connections,+ acquire_timeout: Duration::from_secs(self.pg_acquire_timeout_secs),+ idle_timeout: Some(Duration::from_secs(300)),+ test_before_acquire: true,+ statement_timeout_ms: (self.pg_statement_timeout_ms != 0)+ .then_some(self.pg_statement_timeout_ms),+ pool_name: Some(POOL_NAME.to_string()),+ }+ }++ pub fn build_kafka_config(&self) -> KafkaConfig {+ KafkaConfig {+ kafka_hosts: self.kafka_hosts.clone(),+ kafka_tls: self.kafka_tls,+ kafka_client_rack: self.kafka_client_rack.clone(),+ kafka_client_id: self.kafka_client_id.clone(),+ kafka_compression_codec: self.kafka_compression_codec.clone(),+ kafka_producer_partitioner: Some(self.kafka_producer_partitioner.as_str().to_string()),+ kafka_producer_linger_ms: self.kafka_producer_linger_ms,+ kafka_producer_queue_mib: self.kafka_producer_queue_mib,+ kafka_producer_queue_messages: self.kafka_producer_queue_messages,+ kafka_message_timeout_ms: 20_000,+ kafka_producer_batch_size: None,+ kafka_producer_batch_num_messages: None,+ kafka_producer_enable_idempotence: None,+ kafka_producer_max_in_flight_requests_per_connection: None,+ kafka_producer_topic_metadata_refresh_interval_ms: None,+ kafka_producer_message_max_bytes: None,+ kafka_producer_sticky_partitioning_linger_ms: None,+ }+ }++ pub fn tiles_per_second(&self) -> Result<NonZeroU32, ConfigValidationError> {+ NonZeroU32::new(self.seeder_tiles_per_sec).ok_or(ConfigValidationError::ZeroTileRate)+ }+}++#[derive(Debug, thiserror::Error)]+pub enum ConfigValidationError {+ #[error("seed tiles per second must be greater than zero")]+ ZeroTileRate,+}++#[cfg(test)]+mod tests {+ use std::collections::HashMap;++ use super::*;++ fn default_config() -> Config {+ Config::init_from_hashmap(&HashMap::new()).unwrap()+ }++ #[test]+ fn producer_partitioner_is_pinned_to_the_cohort_affinity_contract() {+ let config = Config::init_from_hashmap(&HashMap::new()).unwrap();+ assert_eq!(+ config.kafka_producer_partitioner,+ KafkaProducerPartitioner::Murmur2Random+ );+ assert_eq!(+ config+ .build_kafka_config()+ .kafka_producer_partitioner+ .as_deref(),+ Some("murmur2_random"),+ );+ }++ #[test]+ fn producer_partitioner_rejects_unsafe_environment_overrides() {+ for value in ["consistent_random", "random", ""] {+ let env =+ HashMap::from([("KAFKA_PRODUCER_PARTITIONER".to_string(), value.to_string())]);+ assert!(+ Config::init_from_hashmap(&env).is_err(),+ "accepted unsafe partitioner {value:?}"+ );+ }+ }++ #[test]+ fn partition_count_defaults_to_the_shared_cohort_contract() {+ assert_eq!(+ default_config().cohort_partition_count,+ cohort_core::partitioner::COHORT_PARTITION_COUNT,+ );+ let env = HashMap::from([("COHORT_PARTITION_COUNT".to_string(), "8".to_string())]);+ assert_eq!(+ Config::init_from_hashmap(&env)+ .unwrap()+ .cohort_partition_count,+ 8+ );+ }++ #[test]+ fn service_limits_reject_disabled_tile_rate() {+ let mut config = default_config();+ config.seeder_tiles_per_sec = 0;+ assert!(matches!(+ config.tiles_per_second(),+ Err(ConfigValidationError::ZeroTileRate)+ ));+ }+}diff --git a/rust/cohort-seeder/src/domain/aggregate.rs b/rust/cohort-seeder/src/domain/aggregate.rsnew file mode 100644index 000000000000..b835a3a4bf47--- /dev/null+++ b/rust/cohort-seeder/src/domain/aggregate.rs@@ -0,0 +1,465 @@+//! Domain layer: `ChunkAccumulator` — folds scanned events through the shared HogVM evaluator into+//! per-`(person, condition, day)` tiles. Depends on `plan`, `window`, `ids`, and `cohort-core`+//! (including its `seed::SeedTile` wire type).++use std::collections::hash_map::Entry;+use std::collections::HashMap;+use std::num::NonZeroU32;+use std::sync::Arc;++use cohort_core::events::CohortStreamEvent;+use cohort_core::filters::{TeamFilters, TeamId};+use cohort_core::hogvm::{+ build_behavioral_globals, classify_vm_error, CohortEvaluator, EvalOutcome, VmErrorClass,+};+use uuid::Uuid;++use super::ids::{ClaimEpoch, ConditionHash, RunId};+use super::plan::ActiveConditions;+use super::window::SeedDomain;+use cohort_core::seed::SeedTile;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum RecordOutcome {+ Evaluated(RecordStats),+ SkippedGlobals,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub struct RecordStats {+ pub matched: u32,+ pub non_matched: u32,+ pub unknown_functions: u32,+ pub vm_failures: VmFailureCounts,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct VmFailureCounts([u32; VmErrorClass::COUNT]);++impl Default for VmFailureCounts {+ fn default() -> Self {+ Self([0; VmErrorClass::COUNT])+ }+}++impl VmFailureCounts {+ pub fn get(&self, class: VmErrorClass) -> u32 {+ self.0.get(class.index()).copied().unwrap_or(0)+ }++ pub fn iter(&self) -> impl Iterator<Item = (VmErrorClass, u32)> + '_ {+ VmErrorClass::ALL+ .into_iter()+ .map(|class| (class, self.get(class)))+ }++ fn increment(&mut self, class: VmErrorClass) -> Result<(), AggregateError> {+ let count = self+ .0+ .get_mut(class.index())+ .ok_or(AggregateError::VmErrorClassInvariant(class))?;+ *count = count+ .checked_add(1)+ .ok_or(AggregateError::OutcomeCountOverflow(+ OutcomeKind::VmFailures,+ ))?;+ Ok(())+ }+}++struct ActiveCandidate {+ hash: ConditionHash,+ bytecode: Arc<Vec<serde_json::Value>>,+}++pub struct ChunkAccumulator {+ team_id: TeamId,+ active_by_event_name: HashMap<String, Vec<ActiveCandidate>>,+ evaluator: CohortEvaluator,+ counts: HashMap<(Uuid, ConditionHash), NonZeroU32>,+}++impl ChunkAccumulator {+ pub fn new(+ team_id: TeamId,+ filters: &TeamFilters,+ active: &ActiveConditions,+ ) -> Result<Self, AggregateError> {+ let active_by_event_name = filters+ .behavioral_by_event_name+ .iter()+ .map(|(event_name, candidates)| {+ let candidates = candidates+ .iter()+ .filter_map(|candidate| active.get(candidate).map(|hash| (candidate, hash)))+ .map(|(candidate, hash)| {+ let bytecode = filters+ .by_condition_to_bytecode+ .get(candidate)+ .map(Arc::clone)+ .ok_or(AggregateError::MissingBytecode(hash))?;+ Ok(ActiveCandidate { hash, bytecode })+ })+ .collect::<Result<Vec<_>, AggregateError>>()?;+ Ok((event_name.clone(), candidates))+ })+ .filter_map(|result| match result {+ Ok((_, candidates)) if candidates.is_empty() => None,+ other => Some(other),+ })+ .collect::<Result<HashMap<_, _>, AggregateError>>()?;+ Ok(Self {+ team_id,+ active_by_event_name,+ evaluator: CohortEvaluator::new(),+ counts: HashMap::new(),+ })+ }++ pub fn record_event(+ &mut self,+ event: &CohortStreamEvent,+ ) -> Result<RecordOutcome, AggregateError> {+ if event.team_id != self.team_id.0 {+ return Err(AggregateError::TeamMismatch {+ expected: self.team_id,+ actual: event.team_id,+ });+ }+ let person_id = Uuid::parse_str(&event.person_id).map_err(|source| {+ AggregateError::InvalidPersonId {+ value: event.person_id.clone(),+ source,+ }+ })?;+ if self.active_by_event_name.is_empty() {+ return Ok(RecordOutcome::Evaluated(RecordStats::default()));+ }+ let Ok(globals) = build_behavioral_globals(event) else {+ return Ok(RecordOutcome::SkippedGlobals);+ };+ self.evaluator.set_globals(globals);+ let candidates = self+ .active_by_event_name+ .get(&event.event)+ .map_or(&[][..], Vec::as_slice);+ let mut stats = RecordStats::default();+ for candidate in candidates {+ match self+ .evaluator+ .evaluate_detailed(Arc::clone(&candidate.bytecode))+ {+ EvalOutcome::Matched(true) => {+ increment_outcome(&mut stats.matched, OutcomeKind::Matched)?;+ }+ EvalOutcome::Matched(false) => {+ increment_outcome(&mut stats.non_matched, OutcomeKind::NonMatched)?;+ continue;+ }+ EvalOutcome::UnknownFunction(_) => {+ increment_outcome(&mut stats.unknown_functions, OutcomeKind::UnknownFunctions)?;+ continue;+ }+ EvalOutcome::VmError(error) => {+ stats.vm_failures.increment(classify_vm_error(&error))?;+ continue;+ }+ }+ match self.counts.entry((person_id, candidate.hash)) {+ Entry::Vacant(entry) => {+ entry.insert(NonZeroU32::MIN);+ }+ Entry::Occupied(mut entry) => {+ let next = entry+ .get()+ .checked_add(1)+ .ok_or(AggregateError::CountOverflow {+ person_id,+ hash: candidate.hash,+ })?;+ entry.insert(next);+ }+ }+ }+ Ok(RecordOutcome::Evaluated(stats))+ }++ pub fn entry_count(&self) -> usize {+ self.counts.len()+ }++ pub fn into_tiles(+ self,+ domain: &SeedDomain,+ run_id: RunId,+ claim_epoch: ClaimEpoch,+ ) -> Vec<SeedTile> {+ let mut counts = self.counts.into_iter().collect::<Vec<_>>();+ counts.sort_unstable_by_key(|((person_id, hash), _)| (*person_id, *hash));+ counts+ .into_iter()+ .map(|((person_id, hash), count)| {+ SeedTile::new(+ self.team_id,+ person_id,+ hash,+ count,+ domain.day(),+ domain.s_chunk(),+ run_id,+ claim_epoch,+ )+ })+ .collect()+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum OutcomeKind {+ Matched,+ NonMatched,+ UnknownFunctions,+ VmFailures,+}++impl OutcomeKind {+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::Matched => "matched",+ Self::NonMatched => "non_matched",+ Self::UnknownFunctions => "unknown_functions",+ Self::VmFailures => "vm_failures",+ }+ }+}++fn increment_outcome(value: &mut u32, kind: OutcomeKind) -> Result<(), AggregateError> {+ *value = value+ .checked_add(1)+ .ok_or(AggregateError::OutcomeCountOverflow(kind))?;+ Ok(())+}++#[derive(Debug, thiserror::Error)]+pub enum AggregateError {+ #[error("event team {actual} does not match accumulator team {}", .expected.0)]+ TeamMismatch { expected: TeamId, actual: i32 },+ #[error("invalid person UUID {value:?}: {source}")]+ InvalidPersonId {+ value: String,+ #[source]+ source: uuid::Error,+ },+ #[error("active condition {0} has no frozen bytecode")]+ MissingBytecode(ConditionHash),+ #[error("record outcome counter {} overflowed", .0.as_str())]+ OutcomeCountOverflow(OutcomeKind),+ #[error("VM error class {0:?} is outside the bounded counter set")]+ VmErrorClassInvariant(VmErrorClass),+ #[error("daily count overflowed for person {person_id}, condition {hash}")]+ CountOverflow {+ person_id: Uuid,+ hash: ConditionHash,+ },+}++#[cfg(test)]+mod tests {+ use chrono_tz::UTC;+ use cohort_core::filters::{CohortId, TeamFiltersBuilder};+ use proptest::prelude::*;+ use serde_json::json;++ use super::*;+ use crate::domain::{Boundary, SChunkMs, UtcMillis};++ const HASH_A: &str = "aaaaaaaaaaaaaaaa";+ const HASH_B: &str = "bbbbbbbbbbbbbbbb";+ const HASH_FALSE: &str = "ffffffffffffffff";+ const HASH_UNKNOWN: &str = "uuuuuuuuuuuuuuuu";+ const HASH_BROKEN: &str = "xxxxxxxxxxxxxxxx";++ fn filters() -> TeamFilters {+ let mut builder = TeamFiltersBuilder::default();+ builder+ .add_cohort(+ CohortId(1),+ TeamId(2),+ &json!({+ "properties": { "type": "AND", "values": [+ { "type": "behavioral", "value": "performed_event", "key": "a", "conditionHash": HASH_A, "time_value": 7, "time_interval": "day", "bytecode": ["_H", 1, 32, "a", 32, "event", 1, 1, 11] },+ { "type": "behavioral", "value": "performed_event", "key": "b", "conditionHash": HASH_B, "time_value": 7, "time_interval": "day", "bytecode": ["_H", 1, 32, "b", 32, "event", 1, 1, 11] },+ ]}+ }),+ )+ .unwrap();+ builder.freeze(UTC)+ }++ fn event(person: Uuid, event_name: &str) -> CohortStreamEvent {+ CohortStreamEvent {+ team_id: 2,+ person_id: person.to_string(),+ distinct_id: person.to_string(),+ uuid: Uuid::now_v7().to_string(),+ event: event_name.to_string(),+ timestamp: "2026-03-08 12:00:00.000000".to_string(),+ properties: Some("{}".to_string()),+ person_properties: Some("{}".to_string()),+ elements_chain: None,+ source_offset: 0,+ source_partition: -1,+ redirected_from: None,+ redirect_hops: 0,+ }+ }++ fn outcome_filters() -> TeamFilters {+ let mut builder = TeamFiltersBuilder::default();+ builder+ .add_cohort(+ CohortId(2),+ TeamId(2),+ &json!({+ "properties": { "type": "AND", "values": [+ { "type": "behavioral", "value": "performed_event", "key": "false", "conditionHash": HASH_FALSE, "time_value": 7, "time_interval": "day", "bytecode": ["_H", 1, 30] },+ { "type": "behavioral", "value": "performed_event", "key": "unknown", "conditionHash": HASH_UNKNOWN, "time_value": 7, "time_interval": "day", "bytecode": ["_H", 1, 2, "definitelyNotANative", 0] },+ { "type": "behavioral", "value": "performed_event", "key": "broken", "conditionHash": HASH_BROKEN, "time_value": 7, "time_interval": "day", "bytecode": [] },+ ]}+ }),+ )+ .unwrap();+ builder.freeze(UTC)+ }++ fn evaluated(outcome: RecordOutcome) -> RecordStats {+ match outcome {+ RecordOutcome::Evaluated(stats) => stats,+ RecordOutcome::SkippedGlobals => panic!("expected evaluated event"),+ }+ }++ fn active() -> ActiveConditions {+ ActiveConditions::new([+ ConditionHash::parse(HASH_A).unwrap(),+ ConditionHash::parse(HASH_B).unwrap(),+ ])+ }++ fn domain() -> SeedDomain {+ let boundary = Boundary::new(UtcMillis::new(20 * 86_400_000), UTC);+ SeedDomain::new(19, boundary, UTC, SChunkMs(boundary.at_ms().as_i64())).unwrap()+ }++ #[test]+ fn fold_counts_each_matching_event_condition_pair_once() {+ let filters = filters();+ let active = active();+ let mut accumulator = ChunkAccumulator::new(TeamId(2), &filters, &active).unwrap();+ let person = Uuid::from_u128(1);+ assert_eq!(+ evaluated(accumulator.record_event(&event(person, "a")).unwrap()).matched,+ 1+ );+ assert_eq!(+ evaluated(accumulator.record_event(&event(person, "a")).unwrap()).matched,+ 1+ );+ assert_eq!(+ evaluated(accumulator.record_event(&event(person, "b")).unwrap()).matched,+ 1+ );+ assert_eq!(+ evaluated(accumulator.record_event(&event(person, "other")).unwrap()),+ RecordStats::default()+ );++ let tiles = accumulator.into_tiles(&domain(), RunId(Uuid::nil()), ClaimEpoch(1));+ assert_eq!(tiles.iter().map(SeedTile::count).sum::<u32>(), 3);+ assert_eq!(tiles.len(), 2);+ assert_eq!(tiles[0].count(), 2);+ assert_eq!(tiles[1].count(), 1);+ }++ #[test]+ fn record_outcome_separates_false_unknown_function_and_vm_error() {+ let filters = outcome_filters();+ let active = ActiveConditions::new([+ ConditionHash::parse(HASH_FALSE).unwrap(),+ ConditionHash::parse(HASH_UNKNOWN).unwrap(),+ ConditionHash::parse(HASH_BROKEN).unwrap(),+ ]);+ let mut accumulator = ChunkAccumulator::new(TeamId(2), &filters, &active).unwrap();+ let person = Uuid::from_u128(1);++ let ordinary_false = evaluated(accumulator.record_event(&event(person, "false")).unwrap());+ assert_eq!(ordinary_false.non_matched, 1);+ assert_eq!(ordinary_false.unknown_functions, 0);+ assert_eq!(ordinary_false.vm_failures, VmFailureCounts::default());++ let unknown_function =+ evaluated(accumulator.record_event(&event(person, "unknown")).unwrap());+ assert_eq!(unknown_function.non_matched, 0);+ assert_eq!(unknown_function.unknown_functions, 1);+ assert_eq!(unknown_function.vm_failures, VmFailureCounts::default());++ let vm_error = evaluated(accumulator.record_event(&event(person, "broken")).unwrap());+ assert_eq!(vm_error.non_matched, 0);+ assert_eq!(vm_error.unknown_functions, 0);+ assert_eq!(vm_error.vm_failures.get(VmErrorClass::Program), 1);+ assert_eq!(accumulator.entry_count(), 0);+ }++ #[test]+ fn malformed_globals_skip_only_that_event_and_leave_counts_unchanged() {+ let filters = filters();+ let active = active();+ let mut accumulator = ChunkAccumulator::new(TeamId(2), &filters, &active).unwrap();+ let person = Uuid::from_u128(1);+ assert_eq!(+ evaluated(accumulator.record_event(&event(person, "a")).unwrap()).matched,+ 1+ );++ let mut malformed = event(person, "a");+ malformed.properties = Some("{".to_string());+ assert_eq!(+ accumulator.record_event(&malformed).unwrap(),+ RecordOutcome::SkippedGlobals+ );+ assert_eq!(accumulator.entry_count(), 1);+ assert_eq!(+ evaluated(accumulator.record_event(&event(person, "a")).unwrap()).matched,+ 1+ );++ let tiles = accumulator.into_tiles(&domain(), RunId(Uuid::nil()), ClaimEpoch(1));+ assert_eq!(tiles.iter().map(SeedTile::count).sum::<u32>(), 2);+ }++ proptest! {+ #[test]+ fn tile_sum_conserves_arbitrary_matched_pairs(+ stream in prop::collection::vec((0u8..16, 0u8..4), 0..500),+ ) {+ let filters = filters();+ let active = active();+ let mut accumulator = ChunkAccumulator::new(TeamId(2), &filters, &active).unwrap();+ let expected = stream.iter().filter(|(_, event_kind)| *event_kind < 2).count() as u32;+ for (person, event_kind) in stream {+ let event_name = match event_kind {+ 0 => "a",+ 1 => "b",+ _ => "other",+ };+ let outcome = accumulator+ .record_event(&event(Uuid::from_u128(u128::from(person) + 1), event_name))+ .unwrap();+ prop_assert!(matches!(outcome, RecordOutcome::Evaluated(_)));+ }+ let tiles = accumulator.into_tiles(&domain(), RunId(Uuid::nil()), ClaimEpoch(1));+ prop_assert_eq!(tiles.iter().map(SeedTile::count).sum::<u32>(), expected);+ prop_assert!(tiles.iter().all(|tile| tile.count() > 0));+ }+ }+}diff --git a/rust/cohort-seeder/src/domain/chunk.rs b/rust/cohort-seeder/src/domain/chunk.rsnew file mode 100644index 000000000000..1cc89e60a641--- /dev/null+++ b/rust/cohort-seeder/src/domain/chunk.rs@@ -0,0 +1,414 @@+//! Pure chunk typestates and vocabulary; depends only on `cohort-core` and sibling domain modules.+//!+//! The states hold data only — no pool, no store handle, no lease. DB-effecting transitions are+//! minted exclusively by [`crate::store::chunks`]; the pure transitions here consume `self`. This is+//! what makes "a chunk cannot be produced twice or confirmed unscanned" a compile-time property.++use std::collections::BTreeMap;+use std::num::NonZeroU32;+use std::str::FromStr;++use cohort_core::filters::TeamId;+use cohort_core::DayIdx;+use serde::{Deserialize, Serialize};++use super::ids::{ChunkId, ClaimEpoch, RunId, SChunkMs};+use super::window::DomainError;+use cohort_core::seed::SeedTile;++/// The lease coordinates that fence every chunk mutation: chunk identity + owning run + claim epoch.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct ChunkLease {+ chunk_id: ChunkId,+ run_id: RunId,+ epoch: ClaimEpoch,+}++impl ChunkLease {+ pub(crate) const fn new(chunk_id: ChunkId, run_id: RunId, epoch: ClaimEpoch) -> Self {+ Self {+ chunk_id,+ run_id,+ epoch,+ }+ }++ pub const fn chunk_id(self) -> ChunkId {+ self.chunk_id+ }++ pub const fn run_id(self) -> RunId {+ self.run_id+ }++ pub const fn epoch(self) -> ClaimEpoch {+ self.epoch+ }+}++/// The persisted chunk lifecycle vocabulary. `as_str`/`FromStr` are the single source of truth the+/// store's SQL binds against; the store's unit test scans its hoisted status fragments through+/// [`ChunkStatus::from_str`] so the two can never drift.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ChunkStatus {+ Pending,+ Scanning,+ Produced,+ Confirmed,+ Failed,+}++impl ChunkStatus {+ pub const ALL: [Self; 5] = [+ Self::Pending,+ Self::Scanning,+ Self::Produced,+ Self::Confirmed,+ Self::Failed,+ ];++ pub const fn as_str(self) -> &'static str {+ match self {+ Self::Pending => "pending",+ Self::Scanning => "scanning",+ Self::Produced => "produced",+ Self::Confirmed => "confirmed",+ Self::Failed => "failed",+ }+ }+}++impl FromStr for ChunkStatus {+ type Err = UnknownChunkStatus;++ fn from_str(value: &str) -> Result<Self, Self::Err> {+ match value {+ "pending" => Ok(Self::Pending),+ "scanning" => Ok(Self::Scanning),+ "produced" => Ok(Self::Produced),+ "confirmed" => Ok(Self::Confirmed),+ "failed" => Ok(Self::Failed),+ other => Err(UnknownChunkStatus(other.to_string())),+ }+ }+}++#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]+#[error("unknown chunk status {0:?}")]+pub struct UnknownChunkStatus(pub String);++/// Whether a claim took a fresh chunk or reclaimed one whose prior lease expired. The app emits+/// `CHUNKS_RECLAIMED` on [`ClaimKind::Reclaim`]; the store no longer touches that metric.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ClaimKind {+ Fresh,+ Reclaim,+}++impl ClaimKind {+ pub const fn from_was_reclaim(was_reclaim: bool) -> Self {+ if was_reclaim {+ Self::Reclaim+ } else {+ Self::Fresh+ }+ }+}++/// A band assignment proven in range at claim-row decode: `band < num_bands`, checked once.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct BandSpec {+ band: u32,+ num_bands: NonZeroU32,+}++impl BandSpec {+ pub fn new(band: i16, num_bands: i64) -> Result<Self, BandSpecError> {+ let num_bands = u32::try_from(num_bands)+ .ok()+ .and_then(NonZeroU32::new)+ .ok_or(BandSpecError::InvalidBandCount(num_bands))?;+ let band = u32::try_from(band).map_err(|_| BandSpecError::BandOutOfRange {+ band,+ num_bands: num_bands.get(),+ })?;+ if band >= num_bands.get() {+ return Err(BandSpecError::BandOutOfRange {+ band: band as i16,+ num_bands: num_bands.get(),+ });+ }+ Ok(Self { band, num_bands })+ }++ pub const fn band(self) -> u32 {+ self.band+ }++ pub const fn num_bands(self) -> NonZeroU32 {+ self.num_bands+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]+pub enum BandSpecError {+ #[error("claimed chunk reported invalid band count {0}")]+ InvalidBandCount(i64),+ #[error("claimed chunk band {band} is outside 0..{num_bands}")]+ BandOutOfRange { band: i16, num_bands: u32 },+}++/// The immutable coordinates carried through every chunk state. `Copy`, so a state can be consumed+/// while its spec is read back out (e.g. the store mints the next state from `chunk.spec()`).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct ChunkSpec {+ pub lease: ChunkLease,+ pub team_id: TeamId,+ pub day: DayIdx,+ pub band: BandSpec,+ pub s_chunk: SChunkMs,+}++/// Freshly claimed and locked; minted only by `store.claim_next` (or `test_support`).+#[derive(Debug)]+pub struct ClaimedChunk {+ spec: ChunkSpec,+}++impl ClaimedChunk {+ pub(crate) const fn new(spec: ChunkSpec) -> Self {+ Self { spec }+ }++ pub const fn spec(&self) -> ChunkSpec {+ self.spec+ }++ /// Pure transition: attach the scanned tiles. No DB effect.+ pub fn into_scanned(self, tiles: Vec<SeedTile>) -> ScannedChunk {+ ScannedChunk::new(self.spec, tiles)+ }+}++/// Scanned into tiles but not yet marked produced.+pub struct ScannedChunk {+ spec: ChunkSpec,+ tiles: Vec<SeedTile>,+}++impl ScannedChunk {+ pub(crate) fn new(spec: ChunkSpec, tiles: Vec<SeedTile>) -> Self {+ Self { spec, tiles }+ }++ pub const fn spec(&self) -> ChunkSpec {+ self.spec+ }++ pub fn tiles(&self) -> &[SeedTile] {+ &self.tiles+ }+}++impl std::fmt::Debug for ScannedChunk {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter+ .debug_struct("ScannedChunk")+ .field("spec", &self.spec)+ .field("tiles", &self.tiles.len())+ .finish()+ }+}++/// The `scanning`→`produced` CAS has committed; minted only by `store.mark_produced`.+#[derive(Debug)]+pub struct EnqueuedChunk {+ spec: ChunkSpec,+ tiles_produced: u64,+}++impl EnqueuedChunk {+ pub(crate) const fn new(spec: ChunkSpec, tiles_produced: u64) -> Self {+ Self {+ spec,+ tiles_produced,+ }+ }++ pub const fn spec(&self) -> ChunkSpec {+ self.spec+ }++ pub const fn tiles_produced(&self) -> u64 {+ self.tiles_produced+ }++ /// Pure transition: fold the observed delivery high-water marks in. No DB effect.+ pub fn into_produced(self, hwms: ProduceHwms) -> ProducedChunk {+ ProducedChunk {+ spec: self.spec,+ tiles_produced: self.tiles_produced,+ hwms,+ }+ }+}++/// All deliveries acknowledged; awaiting the terminal `confirm`.+#[derive(Debug)]+pub struct ProducedChunk {+ spec: ChunkSpec,+ tiles_produced: u64,+ hwms: ProduceHwms,+}++impl ProducedChunk {+ pub const fn spec(&self) -> ChunkSpec {+ self.spec+ }++ pub const fn tiles_produced(&self) -> u64 {+ self.tiles_produced+ }++ pub fn hwms(&self) -> &ProduceHwms {+ &self.hwms+ }+}++/// The run/team-mismatch and out-of-range-day checks the scanner runs before touching ClickHouse.+/// Named by the scanner (not the store), so the store never references a ClickHouse type.+#[derive(Debug, thiserror::Error)]+pub enum ChunkDomainError {+ #[error(+ "chunk run/team ({chunk_run_id:?}, {chunk_team_id}) does not match pinned run/team ({pinned_run_id:?}, {pinned_team_id})"+ )]+ RunMismatch {+ chunk_run_id: RunId,+ chunk_team_id: i32,+ pinned_run_id: RunId,+ pinned_team_id: i32,+ },+ #[error(transparent)]+ Domain(#[from] DomainError),+}++/// Why processing stopped without a terminal error the run should own. `Cancelled` distinguishes a+/// global shutdown from a lost lease; `Failed` carries the stage's own error.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum CancelCause {+ Shutdown,+ LeaseLost,+}++impl CancelCause {+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::Shutdown => "chunk processing stopped for shutdown",+ Self::LeaseLost => "chunk processing stopped after the lease was lost",+ }+ }+}++pub enum HaltReason<E> {+ Cancelled(CancelCause),+ Failed(E),+}++/// The one carrier the pipeline consumes when a store- or scan-gated step stops: it hands the state+/// back so the caller can release or fail the chunk. Deliberately not `std::error::Error`.+pub struct Halted<S, E> {+ pub state: S,+ pub reason: HaltReason<E>,+}++impl<S, E> Halted<S, E> {+ pub fn failed(state: S, error: E) -> Self {+ Self {+ state,+ reason: HaltReason::Failed(error),+ }+ }++ pub fn cancelled(state: S, cause: CancelCause) -> Self {+ Self {+ state,+ reason: HaltReason::Cancelled(cause),+ }+ }+}++/// Per-partition delivery high-water marks, persisted as JSON on confirm. Pure data.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(transparent)]+pub struct ProduceHwms(BTreeMap<i32, i64>);++impl ProduceHwms {+ pub fn observe(&mut self, partition: i32, offset: i64) {+ self.0+ .entry(partition)+ .and_modify(|current| *current = (*current).max(offset))+ .or_insert(offset);+ }++ pub fn get(&self, partition: i32) -> Option<i64> {+ self.0.get(&partition).copied()+ }++ pub fn is_empty(&self) -> bool {+ self.0.is_empty()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn chunk_status_round_trips_through_its_wire_vocabulary() {+ for status in ChunkStatus::ALL {+ assert_eq!(ChunkStatus::from_str(status.as_str()).unwrap(), status);+ }+ assert!(ChunkStatus::from_str("scan").is_err());+ }++ #[test]+ fn claim_kind_maps_the_prior_status_flag() {+ assert_eq!(ClaimKind::from_was_reclaim(true), ClaimKind::Reclaim);+ assert_eq!(ClaimKind::from_was_reclaim(false), ClaimKind::Fresh);+ }++ #[test]+ fn band_spec_admits_only_in_range_bands() {+ assert_eq!(BandSpec::new(3, 8).unwrap().band(), 3);+ assert!(matches!(+ BandSpec::new(8, 8),+ Err(BandSpecError::BandOutOfRange { .. })+ ));+ assert!(matches!(+ BandSpec::new(-1, 8),+ Err(BandSpecError::BandOutOfRange { .. })+ ));+ assert!(matches!(+ BandSpec::new(0, 0),+ Err(BandSpecError::InvalidBandCount(0))+ ));+ }++ #[test]+ fn produce_hwms_fold_by_partition_maximum() {+ let mut hwms = ProduceHwms::default();+ hwms.observe(2, 9);+ hwms.observe(1, 4);+ hwms.observe(2, 7);+ hwms.observe(1, 11);+ hwms.observe(3, 1);++ assert_eq!(hwms.get(1), Some(11));+ assert_eq!(hwms.get(2), Some(9));+ assert_eq!(hwms.get(3), Some(1));+ assert_eq!(+ serde_json::to_value(hwms).unwrap(),+ serde_json::json!({"1": 11, "2": 9, "3": 1})+ );+ }+}diff --git a/rust/cohort-seeder/src/domain/condition.rs b/rust/cohort-seeder/src/domain/condition.rsnew file mode 100644index 000000000000..5f1f9457b836--- /dev/null+++ b/rust/cohort-seeder/src/domain/condition.rs@@ -0,0 +1,77 @@+//! Domain layer: `Lookback`, `PinnedCondition`, and `EventNameSet` — the seed conditions, sited below+//! both `plan` and `pinned` to break their would-be cycle. Depends on `ids` and `cohort-core`.++use std::collections::BTreeSet;++use cohort_core::filters::CohortId;++use super::ids::{ConditionHash, DayIdx};++/// The scannable shape of a stored condition. Every variant maps to a concrete day range; the+/// unscannable cases are resolved away before storage (see [`super::pinned`]).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Lookback {+ SlidingDays(u32),+ SubDay,+ FixedRange {+ from_day: Option<DayIdx>,+ to_day: Option<DayIdx>,+ },+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct PinnedCondition {+ pub cohort_id: CohortId,+ pub hash: ConditionHash,+ pub event_name: String,+ pub lookback: Lookback,+}++/// The union of event names a run scans, sorted ascending and deduplicated by construction.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct EventNameSet(Vec<String>);++impl EventNameSet {+ pub fn new(names: impl IntoIterator<Item = String>) -> Self {+ Self(+ names+ .into_iter()+ .collect::<BTreeSet<_>>()+ .into_iter()+ .collect(),+ )+ }++ pub fn from_conditions(conditions: &[PinnedCondition]) -> Self {+ Self::new(+ conditions+ .iter()+ .map(|condition| condition.event_name.clone()),+ )+ }++ pub fn iter(&self) -> impl Iterator<Item = &String> {+ self.0.iter()+ }++ pub fn as_slice(&self) -> &[String] {+ &self.0+ }++ pub fn is_empty(&self) -> bool {+ self.0.is_empty()+ }++ pub fn into_vec(self) -> Vec<String> {+ self.0+ }+}++impl IntoIterator for EventNameSet {+ type Item = String;+ type IntoIter = std::vec::IntoIter<String>;++ fn into_iter(self) -> Self::IntoIter {+ self.0.into_iter()+ }+}diff --git a/rust/cohort-seeder/src/domain/ids.rs b/rust/cohort-seeder/src/domain/ids.rsnew file mode 100644index 000000000000..6ad2c7792323--- /dev/null+++ b/rust/cohort-seeder/src/domain/ids.rs@@ -0,0 +1,77 @@+//! Domain layer (base): the crate's newtyped ids, epochs, instants, and ranges. The ids that ride+//! the seed wire — `RunId`, `ClaimEpoch`, `SChunkMs`, `ConditionHash` — live in+//! `cohort_core::seed` (the processor consumes them too) and are re-exported here; the+//! seeder-internal `ChunkId`, `Band`, `UtcMillis`, and `UtcMsRange` are defined below. Every other+//! domain module builds on these.++use serde::{Deserialize, Serialize};+use sqlx::Type;+use uuid::Uuid;++pub use cohort_core::seed::{ClaimEpoch, ConditionHash, ConditionHashError, RunId, SChunkMs};+pub use cohort_core::DayIdx;++#[derive(+ Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Type,+)]+#[serde(transparent)]+#[sqlx(transparent)]+pub struct ChunkId(pub Uuid);++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Type)]+#[sqlx(transparent)]+pub struct Band(pub i16);++/// Epoch milliseconds (UTC): the crate's single instant type. Unwrap to `i64` only at cohort-core+/// calls, SQL rendering, and serde boundaries.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct UtcMillis(i64);++impl UtcMillis {+ pub const fn new(value: i64) -> Self {+ Self(value)+ }++ pub const fn as_i64(self) -> i64 {+ self.0+ }+}++/// A half-open `[start, end)` window of epoch milliseconds. The `start <= end` invariant is proven+/// by [`UtcMsRange::new`], so consumers never re-check it.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct UtcMsRange {+ start: UtcMillis,+ end: UtcMillis,+}++impl UtcMsRange {+ pub fn new(start: UtcMillis, end: UtcMillis) -> Result<Self, UtcRangeError> {+ if start.0 > end.0 {+ return Err(UtcRangeError {+ start: start.0,+ end: end.0,+ });+ }+ Ok(Self { start, end })+ }++ pub const fn start(self) -> UtcMillis {+ self.start+ }++ pub const fn end(self) -> UtcMillis {+ self.end+ }++ pub const fn is_empty(self) -> bool {+ self.start.0 == self.end.0+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]+#[error("UTC range start {start} exceeds end {end}")]+pub struct UtcRangeError {+ pub start: i64,+ pub end: i64,+}diff --git a/rust/cohort-seeder/src/domain/mod.rs b/rust/cohort-seeder/src/domain/mod.rsnew file mode 100644index 000000000000..9e4ff9ab4e0b--- /dev/null+++ b/rust/cohort-seeder/src/domain/mod.rs@@ -0,0 +1,36 @@+//! Pure domain layer for the cohort seeder; depends only on `cohort-core`.+//!+//! No module here reaches into PostgreSQL, ClickHouse, or Kafka. The internal+//! dependency order is strictly downward:+//! `ids` ← {`condition`, `window`} ← `chunk` ← {`plan`, `pinned`, `aggregate`}.+//! The seed wire contract (`SeedTile` and the ids that ride it) lives in+//! `cohort_core::seed` — shared with the processor — and is re-exported here.++pub mod aggregate;+pub mod chunk;+pub mod condition;+pub mod ids;+pub mod pinned;+pub mod plan;+pub mod window;++pub use aggregate::{+ AggregateError, ChunkAccumulator, OutcomeKind, RecordOutcome, RecordStats, VmFailureCounts,+};+pub use chunk::{+ BandSpec, BandSpecError, CancelCause, ChunkDomainError, ChunkLease, ChunkSpec, ChunkStatus,+ ClaimKind, ClaimedChunk, EnqueuedChunk, HaltReason, Halted, ProduceHwms, ProducedChunk,+ ScannedChunk, UnknownChunkStatus,+};+pub use cohort_core::seed::SeedTile;+pub use condition::{EventNameSet, Lookback, PinnedCondition};+pub use ids::{+ Band, ChunkId, ClaimEpoch, ConditionHash, ConditionHashError, DayIdx, RunId, SChunkMs,+ UtcMillis, UtcMsRange, UtcRangeError,+};+pub use pinned::{+ PinnedDropReason, PinnedError, PinnedParticipation, PinnedParticipationState, PinnedRun,+ PinnedRunSnapshot, PinnedWarning, TriggerKind, UnknownTriggerKind, ValidatedPinnedRun,+};+pub use plan::{bands_for_day, conditions_active_on, plan_days, ActiveConditions};+pub use window::{Boundary, DomainError, PlanCaps, SeedDomain};diff --git a/rust/cohort-seeder/src/domain/pinned.rs b/rust/cohort-seeder/src/domain/pinned.rsnew file mode 100644index 000000000000..40703224d51f--- /dev/null+++ b/rust/cohort-seeder/src/domain/pinned.rs@@ -0,0 +1,796 @@+//! Domain layer: the pinned run — lenient payload parse plus `PinnedRun`'s staged validation into a+//! typed, scannable run. Depends on `chunk`, `condition`, `window`, `ids`, and `cohort-core`.++use std::collections::HashMap;+use std::str::FromStr;+use std::sync::Arc;++use chrono_tz::Tz;+use cohort_core::filters::tree::{BehavioralLeafConfig, BehavioralValue};+use cohort_core::filters::{CohortId, FilterError, TeamFilters, TeamFiltersBuilder, TeamId};+use cohort_core::resolve_tz_or_utc;+use cohort_core::EvictionWindow;+use cohort_core::LeafStateKey;+use serde::{Deserialize, Deserializer};+use serde_json::Value;++use super::chunk::{ChunkDomainError, ChunkSpec};+use super::condition::{EventNameSet, Lookback, PinnedCondition};+use super::ids::{ConditionHash, ConditionHashError, RunId, UtcMillis};+use super::window::{Boundary, SeedDomain};++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum TriggerKind {+ TeamEnablement,+ CohortCreated,+ CohortEdited,+ DisasterRecovery,+}++impl TriggerKind {+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::TeamEnablement => "team_enablement",+ Self::CohortCreated => "cohort_created",+ Self::CohortEdited => "cohort_edited",+ Self::DisasterRecovery => "disaster_recovery",+ }+ }+}++impl FromStr for TriggerKind {+ type Err = UnknownTriggerKind;++ fn from_str(value: &str) -> Result<Self, Self::Err> {+ match value {+ "team_enablement" => Ok(Self::TeamEnablement),+ "cohort_created" => Ok(Self::CohortCreated),+ "cohort_edited" => Ok(Self::CohortEdited),+ "disaster_recovery" => Ok(Self::DisasterRecovery),+ other => Err(UnknownTriggerKind(other.to_string())),+ }+ }+}++#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]+#[error("unknown backfill trigger {0:?}")]+pub struct UnknownTriggerKind(pub String);++#[derive(Debug)]+pub struct PinnedRun {+ pub run_id: RunId,+ pub team_id: TeamId,+ pub trigger: TriggerKind,+ pub tz: Tz,+ pub boundary: Boundary,+ pub conditions: Vec<PinnedCondition>,+ pub event_names: EventNameSet,+ pub filters: TeamFilters,+}++#[derive(Debug)]+pub struct ValidatedPinnedRun {+ pub run: PinnedRun,+ pub warnings: Vec<PinnedWarning>,+}++/// A run proven `seeding` with an established boundary, ready for pinned-payload validation. The+/// `trigger`/`boundary_at_ms` are already typed and present — the store performs the sole+/// `Option`→value narrowing before building this.+#[derive(Debug)]+pub struct PinnedRunSnapshot {+ pub run_id: RunId,+ pub team_id: TeamId,+ pub trigger: TriggerKind,+ pub timezone: String,+ pub boundary_at_ms: i64,+ pub pinned: Value,+ pub participations: Vec<PinnedParticipation>,+}++#[derive(Debug)]+pub struct PinnedParticipation {+ pub cohort_id: CohortId,+ pub pinned_filters: Value,+ pub state: PinnedParticipationState,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PinnedParticipationState {+ Active,+ Superseded,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PinnedDropReason {+ ActionKeyed,+ AbsentFromFrozenCatalog,+}++impl PinnedDropReason {+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::ActionKeyed => "action_keyed",+ Self::AbsentFromFrozenCatalog => "absent_from_frozen_catalog",+ }+ }+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum PinnedWarning {+ TimezoneFallback {+ configured: String,+ },+ ConditionDropped {+ cohort_id: CohortId,+ hash: ConditionHash,+ reason: PinnedDropReason,+ },+ ConditionSuperseded {+ cohort_id: CohortId,+ hash: ConditionHash,+ },+ WindowDaysMismatch {+ cohort_id: CohortId,+ hash: ConditionHash,+ pinned: u32,+ derived: u32,+ },+}++#[derive(Debug, thiserror::Error)]+pub enum PinnedError {+ #[error("invalid pinned payload: {0}")]+ Payload(#[from] serde_json::Error),+ #[error("unsupported pinned schema version {0}")]+ SchemaVersion(u32),+ #[error("invalid conditionHash {value:?}: {source}")]+ InvalidConditionHash {+ value: String,+ #[source]+ source: ConditionHashError,+ },+ #[error("cohort {0} appears more than once in the pinned participations")]+ DuplicateParticipation(i32),+ #[error("pinned condition names cohort {0}, which is not an active participation")]+ MissingParticipation(i32),+ #[error(transparent)]+ Filters(#[from] FilterError),+ #[error("frozen catalog metadata is incomplete for condition {0}")]+ IncompleteMetadata(ConditionHash),+}++#[derive(Debug, Deserialize)]+struct PinnedPayload {+ schema_version: u32,+ conditions: Vec<RawPinnedCondition>,+}++#[derive(Debug, Deserialize)]+struct RawPinnedCondition {+ cohort_id: i32,+ condition_hash: String,+ value: Option<String>,+ #[serde(default, deserialize_with = "lenient_i32")]+ time_value: Option<i32>,+ #[serde(default, deserialize_with = "lenient_string")]+ time_interval: Option<String>,+ #[serde(default, deserialize_with = "lenient_string")]+ explicit_datetime: Option<String>,+ #[serde(default, deserialize_with = "lenient_string")]+ explicit_datetime_to: Option<String>,+ #[serde(default, deserialize_with = "lenient_string")]+ operator: Option<String>,+ #[serde(default, deserialize_with = "lenient_i32")]+ operator_value: Option<i32>,+ window_days: u32,+ event_name: Option<String>,+ is_action: bool,+}++/// Coerce a JSON scalar to `Some(i32)` only for an integer in `i32` range; anything else+/// (missing, null, string, float, bool, array, object, out-of-range) becomes `None`, never an+/// error. Replicates the former `json_i32` tolerance byte-for-byte — a plain `Option<i32>` would+/// instead reject a mistyped payload Django is allowed to send.+fn lenient_i32<'de, D>(deserializer: D) -> Result<Option<i32>, D::Error>+where+ D: Deserializer<'de>,+{+ let value = Option::<Value>::deserialize(deserializer)?;+ Ok(value+ .as_ref()+ .and_then(Value::as_i64)+ .and_then(|number| i32::try_from(number).ok()))+}++/// Coerce a JSON scalar to `Some(String)` only for a string; anything else becomes `None`, never+/// an error. Replicates the former `json_string` tolerance byte-for-byte.+fn lenient_string<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>+where+ D: Deserializer<'de>,+{+ let value = Option::<Value>::deserialize(deserializer)?;+ Ok(value.as_ref().and_then(Value::as_str).map(str::to_string))+}++impl PinnedRun {+ pub fn validate(snapshot: PinnedRunSnapshot) -> Result<ValidatedPinnedRun, PinnedError> {+ let payload = parse_payload(snapshot.pinned)?;+ let mut warnings = Vec::new();+ let tz = resolve_timezone(&snapshot.timezone, &mut warnings);+ let boundary = Boundary::new(UtcMillis::new(snapshot.boundary_at_ms), tz);+ let participation = ParticipationSet::build(snapshot.team_id, snapshot.participations, tz)?;+ let conditions = resolve_conditions(payload.conditions, &participation, &mut warnings)?;+ let event_names = EventNameSet::from_conditions(&conditions);++ Ok(ValidatedPinnedRun {+ run: PinnedRun {+ run_id: snapshot.run_id,+ team_id: snapshot.team_id,+ trigger: snapshot.trigger,+ tz,+ boundary,+ conditions,+ event_names,+ filters: participation.into_filters(),+ },+ warnings,+ })+ }++ /// The seed domain for a claimed chunk, after proving the chunk belongs to this run/team. Named+ /// here (not in the store) so the store never references a scan/ClickHouse type — cycle break.+ pub fn domain_for(&self, spec: &ChunkSpec) -> Result<SeedDomain, ChunkDomainError> {+ if self.run_id != spec.lease.run_id() || self.team_id != spec.team_id {+ return Err(ChunkDomainError::RunMismatch {+ chunk_run_id: spec.lease.run_id(),+ chunk_team_id: spec.team_id.0,+ pinned_run_id: self.run_id,+ pinned_team_id: self.team_id.0,+ });+ }+ Ok(SeedDomain::new(+ spec.day,+ self.boundary,+ self.tz,+ spec.s_chunk,+ )?)+ }+}++fn parse_payload(pinned: Value) -> Result<PinnedPayload, PinnedError> {+ let payload: PinnedPayload = serde_json::from_value(pinned)?;+ if payload.schema_version != 1 {+ return Err(PinnedError::SchemaVersion(payload.schema_version));+ }+ Ok(payload)+}++fn resolve_timezone(configured: &str, warnings: &mut Vec<PinnedWarning>) -> Tz {+ let tz = resolve_tz_or_utc(configured);+ if configured.parse::<Tz>().is_err() {+ warnings.push(PinnedWarning::TimezoneFallback {+ configured: configured.to_string(),+ });+ }+ tz+}++/// The participations of a run, indexed for dedup-checked lookup with the frozen filter catalog+/// already built from the active cohorts.+struct ParticipationSet {+ states: HashMap<CohortId, PinnedParticipationState>,+ filters: TeamFilters,+}++impl ParticipationSet {+ fn build(+ team_id: TeamId,+ participations: Vec<PinnedParticipation>,+ tz: Tz,+ ) -> Result<Self, PinnedError> {+ let mut states = HashMap::with_capacity(participations.len());+ let mut builder = TeamFiltersBuilder::default();+ for participation in participations {+ if states+ .insert(participation.cohort_id, participation.state)+ .is_some()+ {+ return Err(PinnedError::DuplicateParticipation(+ participation.cohort_id.0,+ ));+ }+ if participation.state == PinnedParticipationState::Active {+ builder.add_cohort(+ participation.cohort_id,+ team_id,+ &participation.pinned_filters,+ )?;+ }+ }+ Ok(Self {+ states,+ filters: builder.freeze(tz),+ })+ }++ fn state(&self, cohort_id: CohortId) -> Option<PinnedParticipationState> {+ self.states.get(&cohort_id).copied()+ }++ fn into_filters(self) -> TeamFilters {+ self.filters+ }+}++fn resolve_conditions(+ raw_conditions: Vec<RawPinnedCondition>,+ participation: &ParticipationSet,+ warnings: &mut Vec<PinnedWarning>,+) -> Result<Vec<PinnedCondition>, PinnedError> {+ let mut conditions = Vec::with_capacity(raw_conditions.len());+ for raw in raw_conditions {+ let cohort_id = CohortId(raw.cohort_id);+ let Some(state) = participation.state(cohort_id) else {+ return Err(PinnedError::MissingParticipation(raw.cohort_id));+ };+ let hash = ConditionHash::parse(&raw.condition_hash).map_err(|source| {+ PinnedError::InvalidConditionHash {+ value: raw.condition_hash.clone(),+ source,+ }+ })?;+ if state == PinnedParticipationState::Superseded {+ warnings.push(PinnedWarning::ConditionSuperseded { cohort_id, hash });+ continue;+ }+ let lookback = match derive_lookback(&raw, hash, &participation.filters)? {+ LookbackResolution::Dropped(reason) => {+ warnings.push(PinnedWarning::ConditionDropped {+ cohort_id,+ hash,+ reason,+ });+ continue;+ }+ LookbackResolution::Resolved(lookback) => lookback,+ };+ let derived = derived_window_days(lookback);+ if raw.window_days != derived {+ warnings.push(PinnedWarning::WindowDaysMismatch {+ cohort_id,+ hash,+ pinned: raw.window_days,+ derived,+ });+ }+ let event_name = raw+ .event_name+ .expect("a resolved condition always carries a concrete event name");+ conditions.push(PinnedCondition {+ cohort_id,+ hash,+ event_name,+ lookback,+ });+ }+ Ok(conditions)+}++const fn derived_window_days(lookback: Lookback) -> u32 {+ match lookback {+ Lookback::SlidingDays(days) => days,+ Lookback::SubDay | Lookback::FixedRange { .. } => 0,+ }+}++/// The outcome of resolving one raw condition against the frozen catalog: either a scannable+/// [`Lookback`] to store, or a drop reason surfaced as a warning and never stored.+enum LookbackResolution {+ Resolved(Lookback),+ Dropped(PinnedDropReason),+}++fn derive_lookback(+ raw: &RawPinnedCondition,+ hash: ConditionHash,+ filters: &TeamFilters,+) -> Result<LookbackResolution, PinnedError> {+ if raw.is_action {+ return Ok(LookbackResolution::Dropped(PinnedDropReason::ActionKeyed));+ }+ let Some(value) = raw.value.as_deref().and_then(BehavioralValue::from_wire) else {+ return Ok(LookbackResolution::Dropped(+ PinnedDropReason::AbsentFromFrozenCatalog,+ ));+ };+ let Some(event_name) = raw.event_name.as_ref() else {+ return Ok(LookbackResolution::Dropped(+ PinnedDropReason::AbsentFromFrozenCatalog,+ ));+ };+ let leaf = BehavioralLeafConfig {+ condition_hash: hash.as_bytes(),+ value,+ event_key: event_name.clone(),+ time_value: raw.time_value,+ operator_value: raw.operator_value,+ time_interval: raw.time_interval.clone(),+ operator: raw.operator.clone(),+ explicit_datetime: raw.explicit_datetime.clone(),+ explicit_datetime_to: raw.explicit_datetime_to.clone(),+ leaf_state_key: LeafStateKey([0; 16]),+ state_variant: None,+ bytecode: Arc::new(Vec::new()),+ negated: false,+ }+ .with_state_key();+ let Some(meta) = filters.by_lsk.get(&leaf.leaf_state_key) else {+ return Ok(LookbackResolution::Dropped(+ PinnedDropReason::AbsentFromFrozenCatalog,+ ));+ };+ if meta.condition_hash != hash.as_bytes() {+ return Err(PinnedError::IncompleteMetadata(hash));+ }+ let lookback = match (meta.window, meta.window_days) {+ (Some(EvictionWindow::RelativeDays { days }), _) => Lookback::SlidingDays(days),+ (Some(EvictionWindow::RelativeSeconds { .. }), _) => Lookback::SubDay,+ (Some(EvictionWindow::Explicit { from_day, to_day }), _) => {+ Lookback::FixedRange { from_day, to_day }+ }+ (None, Some(days)) => Lookback::SlidingDays(days),+ (None, None) => return Err(PinnedError::IncompleteMetadata(hash)),+ };+ Ok(LookbackResolution::Resolved(lookback))+}++#[cfg(test)]+mod tests {+ use chrono::NaiveDate;+ use chrono_tz::UTC;+ use cohort_core::day_idx_of_naive_date;+ use serde_json::json;+ use uuid::Uuid;++ use super::*;++ const BYTECODE: &[Value] = &[];++ fn bytecode(event: &str) -> Value {+ json!(["_H", 1, 32, event, 32, "event", 1, 1, 11])+ }++ fn condition(+ cohort_id: i32,+ hash: &str,+ value: &str,+ event_name: Option<&str>,+ window_days: u32,+ ) -> Value {+ json!({+ "cohort_id": cohort_id,+ "condition_hash": hash,+ "value": value,+ "time_value": null,+ "time_interval": null,+ "explicit_datetime": null,+ "explicit_datetime_to": null,+ "operator": null,+ "operator_value": null,+ "window_days": window_days,+ "event_name": event_name,+ "is_action": event_name.is_none(),+ })+ }++ fn snapshot(pinned: Value, participations: Vec<PinnedParticipation>) -> PinnedRunSnapshot {+ PinnedRunSnapshot {+ run_id: RunId(Uuid::nil()),+ team_id: TeamId(2),+ trigger: TriggerKind::TeamEnablement,+ timezone: "UTC".to_string(),+ boundary_at_ms: 1_800_000_000_000,+ pinned,+ participations,+ }+ }++ #[test]+ fn validation_rejects_unknown_schema_and_malformed_hashes() {+ let filters = json!({ "properties": { "type": "AND", "values": [] } });+ let participation = || PinnedParticipation {+ cohort_id: CohortId(1),+ pinned_filters: filters.clone(),+ state: PinnedParticipationState::Active,+ };+ let unknown = snapshot(+ json!({ "schema_version": 2, "conditions": [], "event_names": [] }),+ vec![participation()],+ );+ assert!(matches!(+ PinnedRun::validate(unknown),+ Err(PinnedError::SchemaVersion(2))+ ));++ for malformed in ["0123456789abcde", "0123456789abcdefg"] {+ let invalid = snapshot(+ json!({+ "schema_version": 1,+ "conditions": [condition(1, malformed, "performed_event", Some("x"), 0)],+ "event_names": ["x"],+ }),+ vec![participation()],+ );+ assert!(matches!(+ PinnedRun::validate(invalid),+ Err(PinnedError::InvalidConditionHash { .. })+ ));+ }+ }++ #[test]+ fn invalid_timezone_falls_back_once_and_keeps_the_run_loadable() {+ let mut input = snapshot(+ json!({ "schema_version": 1, "conditions": [], "event_names": [] }),+ vec![PinnedParticipation {+ cohort_id: CohortId(1),+ pinned_filters: json!({ "properties": { "type": "AND", "values": [] } }),+ state: PinnedParticipationState::Active,+ }],+ );+ input.timezone = "not/a-zone".to_string();+ let validated = PinnedRun::validate(input).unwrap();+ assert_eq!(validated.run.tz, UTC);+ assert_eq!(+ validated.warnings,+ vec![PinnedWarning::TimezoneFallback {+ configured: "not/a-zone".to_string(),+ }]+ );+ }++ #[test]+ fn lookbacks_come_from_the_frozen_catalog_across_all_participations() {+ let hashes = [+ "daily00000000000",+ "relative30d00000",+ "absolute00000000",+ "hourly0000000000",+ "action0000000000",+ "secondpart000000",+ ];+ assert!(hashes.iter().all(|hash| hash.len() == 16));+ let first_filters = json!({+ "properties": { "type": "AND", "values": [+ { "type": "behavioral", "value": "performed_event", "key": "daily", "conditionHash": hashes[0], "time_value": 7, "time_interval": "day", "bytecode": bytecode("daily") },+ { "type": "behavioral", "value": "performed_event", "key": "relative", "conditionHash": hashes[1], "explicit_datetime": "-30d", "bytecode": bytecode("relative") },+ { "type": "behavioral", "value": "performed_event", "key": "absolute", "conditionHash": hashes[2], "explicit_datetime": "2026-01-03", "explicit_datetime_to": "2026-01-05", "bytecode": bytecode("absolute") },+ { "type": "behavioral", "value": "performed_event", "key": "hourly", "conditionHash": hashes[3], "time_value": 5, "time_interval": "hour", "bytecode": bytecode("hourly") },+ { "type": "behavioral", "value": "performed_event", "key": 42, "conditionHash": hashes[4], "time_value": 7, "time_interval": "day", "bytecode": BYTECODE },+ ]}+ });+ let second_filters = json!({+ "properties": { "type": "AND", "values": [+ { "type": "behavioral", "value": "performed_event_multiple", "key": "second", "conditionHash": hashes[5], "time_value": 14, "time_interval": "day", "operator": "gte", "operator_value": 2, "bytecode": bytecode("second") },+ ]}+ });++ let mut conditions = vec![+ condition(1, hashes[0], "performed_event", Some("daily"), 7),+ condition(1, hashes[1], "performed_event", Some("relative"), 0),+ condition(1, hashes[2], "performed_event", Some("absolute"), 0),+ condition(1, hashes[3], "performed_event", Some("hourly"), 0),+ condition(1, hashes[4], "performed_event", None, 7),+ condition(2, hashes[5], "performed_event_multiple", Some("second"), 14),+ ];+ conditions[0]["time_value"] = json!(7);+ conditions[0]["time_interval"] = json!("day");+ conditions[1]["explicit_datetime"] = json!("-30d");+ conditions[2]["explicit_datetime"] = json!("2026-01-03");+ conditions[2]["explicit_datetime_to"] = json!("2026-01-05");+ conditions[3]["time_value"] = json!(5);+ conditions[3]["time_interval"] = json!("hour");+ conditions[5]["time_value"] = json!(14);+ conditions[5]["time_interval"] = json!("day");+ conditions[5]["operator"] = json!("gte");+ conditions[5]["operator_value"] = json!(2);++ let validated = PinnedRun::validate(snapshot(+ json!({+ "schema_version": 1,+ "conditions": conditions,+ "event_names": ["absolute", "daily", "hourly", "relative", "second"],+ }),+ vec![+ PinnedParticipation {+ cohort_id: CohortId(1),+ pinned_filters: first_filters,+ state: PinnedParticipationState::Active,+ },+ PinnedParticipation {+ cohort_id: CohortId(2),+ pinned_filters: second_filters,+ state: PinnedParticipationState::Active,+ },+ ],+ ))+ .unwrap();++ let day = |year, month, day| {+ day_idx_of_naive_date(NaiveDate::from_ymd_opt(year, month, day).unwrap())+ };+ // The action-keyed condition (`hashes[4]`, no event name) resolves to a drop and is absent+ // from the stored conditions; its `ConditionDropped` warning is asserted below.+ let expected = [+ Lookback::SlidingDays(7),+ Lookback::SlidingDays(30),+ Lookback::FixedRange {+ from_day: Some(day(2026, 1, 3)),+ to_day: Some(day(2026, 1, 5)),+ },+ Lookback::SubDay,+ Lookback::SlidingDays(14),+ ];+ assert_eq!(+ validated+ .run+ .conditions+ .iter()+ .map(|condition| condition.lookback)+ .collect::<Vec<_>>(),+ expected,+ );+ assert!(validated+ .run+ .filters+ .behavioral_by_event_name+ .contains_key("second"));+ assert!(validated+ .warnings+ .contains(&PinnedWarning::WindowDaysMismatch {+ cohort_id: CohortId(1),+ hash: ConditionHash::parse(hashes[1]).unwrap(),+ pinned: 0,+ derived: 30,+ }));+ assert!(validated+ .warnings+ .contains(&PinnedWarning::ConditionDropped {+ cohort_id: CohortId(1),+ hash: ConditionHash::parse(hashes[4]).unwrap(),+ reason: PinnedDropReason::ActionKeyed,+ }));+ }++ #[test]+ fn superseded_participations_are_known_but_excluded_from_the_scan_catalog() {+ let active_hash = "active0000000000";+ let superseded_hash = "superseded000000";+ let filters = |event_name: &str, hash: &str| {+ json!({+ "properties": { "type": "AND", "values": [{+ "type": "behavioral",+ "value": "performed_event",+ "key": event_name,+ "conditionHash": hash,+ "time_value": 7,+ "time_interval": "day",+ "bytecode": bytecode(event_name),+ }]}+ })+ };+ let mut active_condition =+ condition(1, active_hash, "performed_event", Some("active-event"), 7);+ active_condition["time_value"] = json!(7);+ active_condition["time_interval"] = json!("day");+ let mut superseded_condition = condition(+ 2,+ superseded_hash,+ "performed_event",+ Some("superseded-event"),+ 7,+ );+ superseded_condition["time_value"] = json!(7);+ superseded_condition["time_interval"] = json!("day");+ let payload = json!({+ "schema_version": 1,+ "conditions": [active_condition, superseded_condition],+ "event_names": ["active-event", "superseded-event"],+ });+ let participations = vec![+ PinnedParticipation {+ cohort_id: CohortId(1),+ pinned_filters: filters("active-event", active_hash),+ state: PinnedParticipationState::Active,+ },+ PinnedParticipation {+ cohort_id: CohortId(2),+ pinned_filters: filters("superseded-event", superseded_hash),+ state: PinnedParticipationState::Superseded,+ },+ ];++ let validated = PinnedRun::validate(snapshot(payload.clone(), participations)).unwrap();+ assert_eq!(validated.run.conditions.len(), 1);+ assert_eq!(validated.run.conditions[0].cohort_id, CohortId(1));+ assert_eq!(validated.run.event_names.as_slice(), &["active-event"]);+ assert!(validated+ .run+ .filters+ .behavioral_by_event_name+ .contains_key("active-event"));+ assert!(!validated+ .run+ .filters+ .behavioral_by_event_name+ .contains_key("superseded-event"));+ assert!(validated+ .warnings+ .contains(&PinnedWarning::ConditionSuperseded {+ cohort_id: CohortId(2),+ hash: ConditionHash::parse(superseded_hash).unwrap(),+ }));++ let unknown = PinnedRun::validate(snapshot(+ payload,+ vec![PinnedParticipation {+ cohort_id: CohortId(1),+ pinned_filters: filters("active-event", active_hash),+ state: PinnedParticipationState::Active,+ }],+ ));+ assert!(matches!(unknown, Err(PinnedError::MissingParticipation(2))));+ }++ #[test]+ fn lenient_serde_coerces_mistyped_scalars_to_none_without_failing_validation() {+ let hash = "lenient000000000";+ let catalog = json!({+ "properties": { "type": "AND", "values": [+ { "type": "behavioral", "value": "performed_event", "key": "evt", "conditionHash": hash, "time_value": 7, "time_interval": "day", "bytecode": bytecode("evt") },+ ]}+ });+ let validate = |condition: Value| {+ PinnedRun::validate(snapshot(+ json!({ "schema_version": 1, "conditions": [condition], "event_names": ["evt"] }),+ vec![PinnedParticipation {+ cohort_id: CohortId(1),+ pinned_filters: catalog.clone(),+ state: PinnedParticipationState::Active,+ }],+ ))+ };++ // Well-typed scalars resolve against the frozen catalog.+ let mut well_typed = condition(1, hash, "performed_event", Some("evt"), 7);+ well_typed["time_value"] = json!(7);+ well_typed["time_interval"] = json!("day");+ let resolved = validate(well_typed).unwrap();+ assert_eq!(+ resolved+ .run+ .conditions+ .iter()+ .map(|condition| condition.lookback)+ .collect::<Vec<_>>(),+ [Lookback::SlidingDays(7)],+ );++ // A string where an int is expected and a number where a string is expected coerce to None+ // exactly as json_i32/json_string did: validation still succeeds (a plain `Option<i32>`+ // would reject this payload), but the mistyped scalars change the leaf-state key, so the+ // condition drops out of the frozen catalog instead of erroring.+ let mut mistyped = condition(1, hash, "performed_event", Some("evt"), 7);+ mistyped["time_value"] = json!("7");+ mistyped["time_interval"] = json!(5);+ mistyped["operator_value"] = json!("2");+ let dropped = validate(mistyped).unwrap();+ assert!(dropped.run.conditions.is_empty());+ assert!(dropped.warnings.contains(&PinnedWarning::ConditionDropped {+ cohort_id: CohortId(1),+ hash: ConditionHash::parse(hash).unwrap(),+ reason: PinnedDropReason::AbsentFromFrozenCatalog,+ }));+ }+}diff --git a/rust/cohort-seeder/src/domain/plan.rs b/rust/cohort-seeder/src/domain/plan.rsnew file mode 100644index 000000000000..a03c7208b326--- /dev/null+++ b/rust/cohort-seeder/src/domain/plan.rs@@ -0,0 +1,233 @@+//! Domain layer: pure day/band planning — `plan_days`, `conditions_active_on`, `bands_for_day`.+//! Depends on `condition`, `window`, `ids`, and `cohort-core`.++use std::collections::BTreeSet;+use std::num::NonZeroU16;++use cohort_core::bucket_tz::window_start_for_now;++use super::condition::{Lookback, PinnedCondition};+use super::ids::{Band, ConditionHash, DayIdx};+use super::window::{Boundary, PlanCaps};++#[derive(Debug, Clone, PartialEq, Eq, Default)]+pub struct ActiveConditions(BTreeSet<ConditionHash>);++impl ActiveConditions {+ pub fn new(hashes: impl IntoIterator<Item = ConditionHash>) -> Self {+ Self(hashes.into_iter().collect())+ }++ pub fn contains(&self, hash: &ConditionHash) -> bool {+ self.0.contains(hash)+ }++ pub fn get(&self, hash: &[u8; 16]) -> Option<ConditionHash> {+ self.0.get(hash).copied()+ }++ pub fn is_empty(&self) -> bool {+ self.0.is_empty()+ }++ pub fn iter(&self) -> impl Iterator<Item = &ConditionHash> {+ self.0.iter()+ }+}++pub fn plan_days(+ conditions: &[PinnedCondition],+ boundary: Boundary,+ caps: &PlanCaps,+) -> BTreeSet<DayIdx> {+ let mut days = BTreeSet::new();+ let Some(last_historical_day) = boundary.day().checked_sub(1) else {+ return days;+ };+ let capped_start = window_start_for_now(boundary.day(), caps.max_lookback_days);++ for condition in conditions {+ let (start, end) = match condition.lookback {+ Lookback::SlidingDays(days) => {+ let effective_days = days.min(caps.max_lookback_days);+ if effective_days == 0 {+ continue;+ }+ (+ window_start_for_now(boundary.day(), effective_days),+ last_historical_day,+ )+ }+ Lookback::SubDay => {+ if caps.max_lookback_days == 0 {+ continue;+ }+ (last_historical_day, last_historical_day)+ }+ // `from_day` is clamped to the cap like sliding windows are: an explicit_datetime far+ // in the past would otherwise plan one chunk per day since that date, unbounded.+ Lookback::FixedRange { from_day, to_day } => (+ from_day.unwrap_or(capped_start).max(capped_start),+ to_day+ .unwrap_or(last_historical_day)+ .min(last_historical_day),+ ),+ };+ if start > end {+ continue;+ }+ days.extend(start..=end);+ }+ days+}++pub fn conditions_active_on(+ day: DayIdx,+ now_day: DayIdx,+ conditions: &[PinnedCondition],+) -> ActiveConditions {+ ActiveConditions::new(conditions.iter().filter_map(|condition| {+ let active = match condition.lookback {+ Lookback::SlidingDays(days) => {+ window_start_for_now(now_day, days) <= day && day <= now_day+ }+ Lookback::SubDay => window_start_for_now(now_day, 1) <= day && day <= now_day,+ Lookback::FixedRange { from_day, to_day } => {+ from_day.is_none_or(|from| day >= from) && to_day.is_none_or(|to| day <= to)+ }+ };+ active.then_some(condition.hash)+ }))+}++/// The person-hash bands a day is planned into. Each band scans `cityHash64(person) % n = band`,+/// so raising the count bounds one chunk's in-memory aggregate at the cost of re-reading the day's+/// rows per band. Settings validation keeps the count within `i16` (the `band` column's width).+pub fn bands_for_day(_day: DayIdx, bands_per_day: NonZeroU16) -> Vec<Band> {+ (0..bands_per_day.get())+ .map(|band| Band(i16::try_from(band).expect("bands_per_day is validated to fit i16")))+ .collect()+}++#[cfg(test)]+mod tests {+ use chrono_tz::UTC;+ use cohort_core::filters::CohortId;+ use proptest::prelude::*;++ use super::super::ids::UtcMillis;+ use super::*;++ fn condition(hash: &str, lookback: Lookback) -> PinnedCondition {+ PinnedCondition {+ cohort_id: CohortId(1),+ hash: ConditionHash::parse(hash).unwrap(),+ event_name: "event".to_string(),+ lookback,+ }+ }++ #[test]+ fn planning_intersects_ranges_with_the_cap_and_preserves_holes() {+ let boundary = Boundary::new(UtcMillis::new(100 * 86_400_000), UTC);+ let conditions = [+ condition(+ "unbounded0000000",+ Lookback::FixedRange {+ from_day: None,+ to_day: Some(94),+ },+ ),+ condition(+ "range00000000000",+ Lookback::FixedRange {+ from_day: Some(98),+ to_day: Some(99),+ },+ ),+ // Starts below the cap: clamped to the capped start, keeping only 90..=96.+ condition(+ "straddling000000",+ Lookback::FixedRange {+ from_day: Some(85),+ to_day: Some(96),+ },+ ),+ // Entirely below the cap: clamping empties it, so it plans nothing.+ condition(+ "ancient000000000",+ Lookback::FixedRange {+ from_day: Some(80),+ to_day: Some(82),+ },+ ),+ ];+ let caps = PlanCaps {+ max_lookback_days: 10,+ ..PlanCaps::default()+ };+ let expected = BTreeSet::from([90, 91, 92, 93, 94, 95, 96, 98, 99]);+ assert_eq!(plan_days(&conditions, boundary, &caps), expected);+ }++ #[test]+ fn bands_fan_out_zero_indexed() {+ assert_eq!(bands_for_day(0, NonZeroU16::MIN), vec![Band(0)]);+ assert_eq!(+ bands_for_day(5, NonZeroU16::new(3).unwrap()),+ vec![Band(0), Band(1), Band(2)]+ );+ }++ #[test]+ fn active_conditions_expire_sliding_days_and_keep_inclusive_fixed_bounds() {+ let sliding = condition("sliding000000000", Lookback::SlidingDays(2));+ let fixed = condition(+ "fixed00000000000",+ Lookback::FixedRange {+ from_day: Some(95),+ to_day: Some(97),+ },+ );+ let conditions = [sliding.clone(), fixed.clone()];++ let on_97 = conditions_active_on(97, 100, &conditions);+ assert!(!on_97.contains(&sliding.hash));+ assert!(on_97.contains(&fixed.hash));+ let on_98 = conditions_active_on(98, 100, &conditions);+ assert!(on_98.contains(&sliding.hash));+ assert!(!on_98.contains(&fixed.hash));+ }++ proptest! {+ #[test]+ fn planned_days_are_deterministic_and_stay_inside_the_capped_history(+ boundary_day in -20_000i32..20_000,+ cap in 0u16..500,+ windows in prop::collection::vec(0u16..1_000, 0..20),+ ranges in prop::collection::vec(+ (prop::option::of(-30_000i32..30_000), prop::option::of(-30_000i32..30_000)),+ 0..8,+ ),+ ) {+ let boundary = Boundary::new(UtcMillis::new(i64::from(boundary_day) * 86_400_000), UTC);+ let sliding = windows+ .into_iter()+ .map(|days| Lookback::SlidingDays(u32::from(days)));+ let fixed = ranges+ .into_iter()+ .map(|(from_day, to_day)| Lookback::FixedRange { from_day, to_day });+ let conditions = sliding+ .chain(fixed)+ .enumerate()+ .map(|(index, lookback)| condition(&format!("{index:016}"), lookback))+ .collect::<Vec<_>>();+ let caps = PlanCaps { max_lookback_days: u32::from(cap), ..PlanCaps::default() };+ let first = plan_days(&conditions, boundary, &caps);+ let second = plan_days(&conditions, boundary, &caps);+ prop_assert_eq!(&first, &second);+ let lower = window_start_for_now(boundary.day(), u32::from(cap));+ prop_assert!(first.iter().all(|day| lower <= *day && *day < boundary.day()));+ }+ }+}diff --git a/rust/cohort-seeder/src/domain/window.rs b/rust/cohort-seeder/src/domain/window.rsnew file mode 100644index 000000000000..f4f28365016a--- /dev/null+++ b/rust/cohort-seeder/src/domain/window.rs@@ -0,0 +1,247 @@+//! Domain layer: `Boundary`, `SeedDomain`, and `PlanCaps` — the tz-anchored seed window and its caps,+//! with validity proven in the constructors. Depends on `ids` and `cohort-core`'s tz math.++use std::num::NonZeroU16;++use chrono_tz::Tz;+use cohort_core::{day_idx_in_tz, start_of_day_ms_in_tz};++use super::ids::{DayIdx, SChunkMs, UtcMillis, UtcMsRange, UtcRangeError};++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Boundary {+ at_ms: UtcMillis,+ day: DayIdx,+}++impl Boundary {+ pub fn new(at_ms: UtcMillis, tz: Tz) -> Self {+ Self {+ at_ms,+ day: day_idx_in_tz(at_ms.as_i64(), tz),+ }+ }++ pub const fn at_ms(self) -> UtcMillis {+ self.at_ms+ }++ pub const fn day(self) -> DayIdx {+ self.day+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct PlanCaps {+ pub max_lookback_days: u32,+ /// Bands each planned day is split into: the scan hashes persons via `cityHash64 % bands`, so+ /// one chunk's in-memory aggregate holds roughly `uniq(person, condition) / bands` entries.+ pub bands_per_day: NonZeroU16,+}++impl Default for PlanCaps {+ fn default() -> Self {+ Self {+ max_lookback_days: 400,+ bands_per_day: NonZeroU16::MIN,+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct SeedDomain {+ day: DayIdx,+ tz: Tz,+ range: UtcMsRange,+ s_chunk: SChunkMs,+}++impl SeedDomain {+ pub fn new(+ day: DayIdx,+ boundary: Boundary,+ tz: Tz,+ s_chunk: SChunkMs,+ ) -> Result<Self, DomainError> {+ if day >= boundary.day {+ return Err(DomainError::AtOrAfterBoundary {+ day,+ boundary_day: boundary.day,+ });+ }+ let next_day = day.checked_add(1).ok_or(DomainError::DayOverflow(day))?;+ let range = UtcMsRange::new(+ UtcMillis::new(start_of_day_ms_in_tz(day, tz)),+ UtcMillis::new(start_of_day_ms_in_tz(next_day, tz)),+ )?;+ Ok(Self {+ day,+ tz,+ range,+ s_chunk,+ })+ }++ pub const fn day(&self) -> DayIdx {+ self.day+ }++ pub const fn s_chunk(&self) -> SChunkMs {+ self.s_chunk+ }++ pub const fn utc_range(&self) -> UtcMsRange {+ self.range+ }++ pub const fn is_empty(&self) -> bool {+ self.range.is_empty()+ }++ pub fn contains(&self, event_ts_ms: UtcMillis) -> bool {+ day_idx_in_tz(event_ts_ms.as_i64(), self.tz) == self.day+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]+pub enum DomainError {+ #[error("seed day {day} is not before boundary day {boundary_day}")]+ AtOrAfterBoundary { day: DayIdx, boundary_day: DayIdx },+ #[error("seed day {0} has no representable successor")]+ DayOverflow(DayIdx),+ #[error(transparent)]+ InvalidUtcRange(#[from] UtcRangeError),+}++#[cfg(test)]+mod tests {+ use chrono::{NaiveDate, TimeZone, Utc};+ use chrono_tz::America::New_York;+ use chrono_tz::Pacific::Apia;+ use cohort_core::day_idx_of_naive_date;+ use proptest::prelude::*;++ use super::*;++ #[test]+ fn seed_domain_excludes_the_boundary_day_and_uses_dst_exact_half_open_ranges() {+ let spring_day = day_idx_in_tz(+ Utc.with_ymd_and_hms(2026, 3, 8, 12, 0, 0)+ .unwrap()+ .timestamp_millis(),+ New_York,+ );+ let boundary = Boundary::new(+ UtcMillis::new(start_of_day_ms_in_tz(spring_day + 1, New_York)),+ New_York,+ );+ assert!(matches!(+ SeedDomain::new(+ boundary.day(),+ boundary,+ New_York,+ SChunkMs(boundary.at_ms().as_i64())+ ),+ Err(DomainError::AtOrAfterBoundary { .. })+ ));++ let domain = SeedDomain::new(+ spring_day,+ boundary,+ New_York,+ SChunkMs(boundary.at_ms().as_i64()),+ )+ .unwrap();+ let range = domain.utc_range();+ let (start, end) = (range.start().as_i64(), range.end().as_i64());+ assert_eq!(end - start, 23 * 3_600_000);+ assert!(domain.contains(UtcMillis::new(start)));+ assert!(domain.contains(UtcMillis::new(end - 1)));+ assert!(!domain.contains(UtcMillis::new(end)));+ }++ #[test]+ fn skipped_civil_day_is_vacuous_without_truncating_its_neighbors() {+ let day = |year, month, day| {+ day_idx_of_naive_date(NaiveDate::from_ymd_opt(year, month, day).unwrap())+ };+ let preceding = day(2011, 12, 29);+ let skipped = day(2011, 12, 30);+ let following = day(2011, 12, 31);+ let boundary = Boundary::new(+ UtcMillis::new(+ Utc.with_ymd_and_hms(2012, 1, 2, 0, 0, 0)+ .unwrap()+ .timestamp_millis(),+ ),+ Apia,+ );+ let domain = |day| {+ SeedDomain::new(day, boundary, Apia, SChunkMs(boundary.at_ms().as_i64())).unwrap()+ };++ let preceding_domain = domain(preceding);+ let skipped_domain = domain(skipped);+ let following_domain = domain(following);+ assert_eq!(+ preceding_domain.utc_range(),+ UtcMsRange::new(+ UtcMillis::new(+ Utc.with_ymd_and_hms(2011, 12, 29, 10, 0, 0)+ .unwrap()+ .timestamp_millis(),+ ),+ UtcMillis::new(+ Utc.with_ymd_and_hms(2011, 12, 30, 10, 0, 0)+ .unwrap()+ .timestamp_millis(),+ ),+ )+ .unwrap()+ );+ assert!(skipped_domain.is_empty());+ assert_eq!(+ skipped_domain.utc_range().start(),+ skipped_domain.utc_range().end()+ );+ assert!(!skipped_domain.contains(skipped_domain.utc_range().start()));+ assert_eq!(+ following_domain.utc_range(),+ UtcMsRange::new(+ UtcMillis::new(+ Utc.with_ymd_and_hms(2011, 12, 30, 10, 0, 0)+ .unwrap()+ .timestamp_millis(),+ ),+ UtcMillis::new(+ Utc.with_ymd_and_hms(2011, 12, 31, 10, 0, 0)+ .unwrap()+ .timestamp_millis(),+ ),+ )+ .unwrap()+ );+ }++ proptest! {+ #[test]+ fn contains_matches_timezone_bucketing_near_dst_transitions(+ fall_transition in any::<bool>(),+ delta_minutes in -2_880i64..2_880,+ ) {+ let center = if fall_transition {+ Utc.with_ymd_and_hms(2026, 11, 1, 6, 0, 0).unwrap().timestamp_millis()+ } else {+ Utc.with_ymd_and_hms(2026, 3, 8, 7, 0, 0).unwrap().timestamp_millis()+ };+ let day = day_idx_in_tz(center, New_York);+ let boundary = Boundary::new(+ UtcMillis::new(start_of_day_ms_in_tz(day + 2, New_York)),+ New_York,+ );+ let domain = SeedDomain::new(day, boundary, New_York, SChunkMs(center)).unwrap();+ let timestamp = center + delta_minutes * 60_000;+ prop_assert_eq!(domain.contains(UtcMillis::new(timestamp)), day_idx_in_tz(timestamp, New_York) == day);+ }+ }+}diff --git a/rust/cohort-seeder/src/kafka/mod.rs b/rust/cohort-seeder/src/kafka/mod.rsnew file mode 100644index 000000000000..b85706a2a0e9--- /dev/null+++ b/rust/cohort-seeder/src/kafka/mod.rs@@ -0,0 +1,8 @@+//! Kafka layer: the seed-tile producer client and the produce pacer. Depends only on `domain` (plus+//! the shared metric-name constants); never on `store`.++pub mod pacing;+pub mod producer;++pub use pacing::TilePacer;+pub use producer::{EnqueueError, SeedTileProducer};diff --git a/rust/cohort-seeder/src/kafka/pacing.rs b/rust/cohort-seeder/src/kafka/pacing.rsnew file mode 100644index 000000000000..ef86eac70435--- /dev/null+++ b/rust/cohort-seeder/src/kafka/pacing.rs@@ -0,0 +1,35 @@+//! Kafka layer: the per-tile rate limiter that paces produce throughput. Depends only on the shared+//! metric-name constants.++use std::num::NonZeroU32;+use std::sync::Arc;+use std::time::Instant;++use governor::clock::DefaultClock;+use governor::state::{InMemoryState, NotKeyed};+use governor::{Quota, RateLimiter};+use metrics::histogram;++use crate::observability::metrics::PACER_WAIT_SECONDS;++type DirectLimiter = RateLimiter<NotKeyed, InMemoryState, DefaultClock>;++#[derive(Clone)]+pub struct TilePacer {+ limiter: Arc<DirectLimiter>,+}++impl TilePacer {+ pub fn new(tiles_per_second: NonZeroU32) -> Self {+ let quota = Quota::per_second(tiles_per_second).allow_burst(NonZeroU32::MIN);+ Self {+ limiter: Arc::new(RateLimiter::direct(quota)),+ }+ }++ pub async fn until_ready(&self) {+ let started_at = Instant::now();+ self.limiter.until_ready().await;+ histogram!(PACER_WAIT_SECONDS).record(started_at.elapsed().as_secs_f64());+ }+}diff --git a/rust/cohort-seeder/src/kafka/producer.rs b/rust/cohort-seeder/src/kafka/producer.rsnew file mode 100644index 000000000000..b79ea0b73bf9--- /dev/null+++ b/rust/cohort-seeder/src/kafka/producer.rs@@ -0,0 +1,154 @@+//! Kafka layer: the seed-tile producer client. Depends only on `domain`; never on `store`.+//!+//! This is a thin client — `new`/`enqueue`/`flush` and the health reporter. The produce sequencing+//! (pacing, in-flight bound, mark-produced, delivery acks) lives above, in the orchestrator, so this+//! module carries no PostgreSQL dependency.++use std::time::Duration;++use common_kafka::config::KafkaConfig;+use common_kafka::kafka_producer::{create_kafka_producer, KafkaContext};+use common_liveness::SyncLivenessReporter;+use rdkafka::error::{KafkaError, RDKafkaErrorCode};+use rdkafka::producer::{DeliveryFuture, FutureProducer, FutureRecord, Producer};++use crate::domain::SeedTile;++#[derive(Debug, thiserror::Error)]+pub enum EnqueueError {+ #[error("producer queue full")]+ QueueFull,+ #[error("fatal enqueue error: {0}")]+ Fatal(KafkaError),+}++impl From<KafkaError> for EnqueueError {+ fn from(error: KafkaError) -> Self {+ match error {+ KafkaError::MessageProduction(RDKafkaErrorCode::QueueFull) => Self::QueueFull,+ other => Self::Fatal(other),+ }+ }+}++#[derive(Clone)]+pub struct SeedTileProducer {+ producer: FutureProducer<KafkaContext>,+ topic: String,+}++impl SeedTileProducer {+ pub async fn new(kafka_config: &KafkaConfig, topic: String) -> Result<Self, KafkaError> {+ let producer = create_kafka_producer(kafka_config, AlwaysHealthy).await?;+ Ok(Self { producer, topic })+ }++ /// Verify the seed topic's broker partition count equals the consumer's partitioner modulus.+ /// The producer routes with `murmur2_random` — `murmur2(key) % <broker partition count>` —+ /// while the consumer owns a person by `partition_for(key, COHORT_PARTITION_COUNT)`. The two+ /// agree only when the topic has exactly that many partitions; on any other count a person's+ /// seed tiles land on a worker that does not own their live-stream state, so startup must+ /// refuse to run. Blocking — call via `spawn_blocking` from async contexts.+ pub fn verify_partition_count(+ &self,+ expected: u32,+ timeout: Duration,+ ) -> Result<(), PartitionCountError> {+ let metadata = self+ .producer+ .client()+ .fetch_metadata(Some(&self.topic), timeout)+ .map_err(PartitionCountError::Metadata)?;+ let topic = metadata+ .topics()+ .iter()+ .find(|topic| topic.name() == self.topic)+ .ok_or_else(|| PartitionCountError::Missing {+ topic: self.topic.clone(),+ })?;+ if let Some(error) = topic.error() {+ return Err(PartitionCountError::Topic {+ topic: self.topic.clone(),+ code: error.into(),+ });+ }+ let actual = topic.partitions().len();+ if u64::try_from(actual) != Ok(u64::from(expected)) {+ return Err(PartitionCountError::Mismatch {+ topic: self.topic.clone(),+ actual,+ expected,+ });+ }+ Ok(())+ }++ pub fn enqueue(&self, tile: &SeedTile) -> Result<DeliveryFuture, EnqueueError> {+ let payload = serde_json::to_vec(tile).expect("SeedTile serialization cannot fail");+ let key = tile.partition_key();+ let record = FutureRecord::to(&self.topic).key(&key).payload(&payload);+ self.producer+ .send_result(record)+ .map_err(|(error, _)| error.into())+ }++ pub fn flush(&self, timeout: Duration) -> Result<(), KafkaError> {+ self.producer.flush(timeout)+ }+}++/// Why the seed topic failed its startup partition-count verification. Every variant is fatal:+/// producing to a mis-provisioned topic splits seeded membership from live state silently.+#[derive(Debug, thiserror::Error)]+pub enum PartitionCountError {+ #[error("fetching seed topic metadata")]+ Metadata(#[source] KafkaError),+ #[error("seed topic {topic:?} is not present in broker metadata")]+ Missing { topic: String },+ #[error("seed topic {topic:?} metadata reports {code}")]+ Topic {+ topic: String,+ code: RDKafkaErrorCode,+ },+ #[error(+ "seed topic {topic:?} has {actual} partitions, expected {expected}: seed tiles would land \+ on workers that do not own their person"+ )]+ Mismatch {+ topic: String,+ actual: usize,+ expected: u32,+ },+}++#[derive(Clone, Copy)]+struct AlwaysHealthy;++impl SyncLivenessReporter for AlwaysHealthy {+ fn report_healthy(&self) {}++ fn report_unhealthy(&self) {}+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn enqueue_error_splits_queue_full_from_fatal() {+ assert!(matches!(+ EnqueueError::from(KafkaError::MessageProduction(RDKafkaErrorCode::QueueFull)),+ EnqueueError::QueueFull+ ));+ assert!(matches!(+ EnqueueError::from(KafkaError::MessageProduction(+ RDKafkaErrorCode::MessageSizeTooLarge+ )),+ EnqueueError::Fatal(_)+ ));+ assert!(matches!(+ EnqueueError::from(KafkaError::Canceled),+ EnqueueError::Fatal(_)+ ));+ }+}diff --git a/rust/cohort-seeder/src/lib.rs b/rust/cohort-seeder/src/lib.rsnew file mode 100644index 000000000000..c3aa07e2cdb3--- /dev/null+++ b/rust/cohort-seeder/src/lib.rs@@ -0,0 +1,23 @@+//! The cohort seeder: backfills behavioral-cohort membership by replaying history.+//!+//! It claims day-chunks from PostgreSQL (`cohort_backfill_*`), scans each chunk's ClickHouse event+//! history, evaluates every event with `cohort-core`'s exact production Stage-1/HogVM code — so the+//! seed matches the live stream processor by construction — aggregates per-`(person, condition, day)`+//! tiles, and produces them paced to the `cohort_stream_seed_events` Kafka topic.+//!+//! Layers, with dependencies strictly downward and no module importing upward:+//! `domain` (pure, depends only on `cohort-core`) ← {`store` (PostgreSQL), `clickhouse`, `kafka`}+//! (IO, each depends on `domain`) ← `app` (the pipeline wiring the IO layers) ← `main`. `config` and+//! `observability` are leaves that the layers above draw on.++pub mod app;+pub mod clickhouse;+pub mod config;+pub mod domain;+pub mod kafka;+pub mod observability;+pub mod store;++#[cfg(feature = "pg-test-support")]+#[doc(hidden)]+pub mod test_support;diff --git a/rust/cohort-seeder/src/main.rs b/rust/cohort-seeder/src/main.rsnew file mode 100644index 000000000000..5c4bdc8535a4--- /dev/null+++ b/rust/cohort-seeder/src/main.rs@@ -0,0 +1,161 @@+//! Binary entry point: parses `Config`, builds the infra clients, and hands the wired orchestrator to+//! the `lifecycle::Manager`. Depends on `app`, `clickhouse`, `kafka`, `config`, and `observability` —+//! the composition root at the top of the stack.++use std::time::Duration;++use anyhow::{Context, Result};+use common_database::get_pool_with_config;+use envconfig::Envconfig;+use lifecycle::{ComponentOptions, Manager};+use tokio::net::TcpListener;+use tracing::info;+use tracing_subscriber::layer::SubscriberExt;+use tracing_subscriber::util::SubscriberInitExt;+use tracing_subscriber::{fmt, EnvFilter, Layer};++use cohort_seeder::app::{+ OrchestratorSettings, SeederOrchestrator, ORCHESTRATOR_LIVENESS_DEADLINE,+};+use cohort_seeder::clickhouse::client::build_client;+use cohort_seeder::clickhouse::scanner::ChunkScanner;+use cohort_seeder::config::Config;+use cohort_seeder::kafka::pacing::TilePacer;+use cohort_seeder::kafka::producer::SeedTileProducer;+use cohort_seeder::observability;++common_alloc::used!();++const SERVICE_NAME: &str = "cohort-seeder";+const PARTITION_VERIFY_TIMEOUT: Duration = Duration::from_secs(10);++fn main() -> Result<()> {+ let config = Config::init_from_env().context("loading cohort-seeder configuration")?;+ let runtime = tokio::runtime::Builder::new_multi_thread()+ .enable_all()+ .build()+ .context("building tokio runtime")?;+ runtime.block_on(async_main(config))+}++async fn async_main(config: Config) -> Result<()> {+ init_tracing();+ log_startup(&config);++ let mut manager = Manager::builder(SERVICE_NAME)+ .with_global_shutdown_timeout(Duration::from_secs(30))+ .build();+ let metrics_handle =+ manager.register("metrics", ComponentOptions::new().is_observability(true));+ let seeder_handle = manager.register(+ "seeder",+ ComponentOptions::new()+ .with_graceful_shutdown(Duration::from_secs(30))+ .with_liveness_deadline(ORCHESTRATOR_LIVENESS_DEADLINE)+ .with_stall_threshold(3),+ );+ let readiness = manager.readiness_handler();+ let liveness = manager.liveness_handler();+ let recorder = config+ .export_prometheus+ .then(observability::metrics::install_recorder)+ .transpose()+ .context("installing Prometheus recorder")?;++ let pool = get_pool_with_config(&config.database_url, config.pool_config())+ .context("creating cohort-seeder PostgreSQL pool")?;+ let scanner = ChunkScanner::new(build_client(&config).context("building ClickHouse client")?);+ let producer = SeedTileProducer::new(+ &config.build_kafka_config(),+ config.seed_events_topic.clone(),+ )+ .await+ .context("creating seed tile producer")?;+ let verify_producer = producer.clone();+ let expected_partitions = config.cohort_partition_count;+ tokio::task::spawn_blocking(move || {+ verify_producer.verify_partition_count(expected_partitions, PARTITION_VERIFY_TIMEOUT)+ })+ .await+ .context("joining seed topic verification task")?+ .context("verifying seed topic partition count")?;+ let pacer = TilePacer::new(+ config+ .tiles_per_second()+ .context("validating seed tile rate")?,+ );+ let settings =+ OrchestratorSettings::try_from(&config).context("validating orchestrator settings")?;+ let claimed_by = format!("cohort-seeder:{}", uuid::Uuid::now_v7());+ let orchestrator = SeederOrchestrator::new(+ pool,+ scanner,+ producer,+ pacer,+ config.team_allowlist.clone(),+ settings,+ seeder_handle,+ claimed_by,+ );++ let guard = manager.monitor_background();+ tokio::spawn(orchestrator.process());++ let app = observability::health::router(SERVICE_NAME, readiness, liveness, recorder);+ let bind = config.bind_address();+ info!(address = %bind, "observability server starting");+ let listener = TcpListener::bind(&bind)+ .await+ .with_context(|| format!("binding observability server to {bind}"))?;+ axum::serve(listener, app)+ .with_graceful_shutdown(metrics_handle.shutdown_signal())+ .await+ .context("serving observability endpoints")?;+ metrics_handle.work_completed();++ guard.wait().await?;+ info!(service = SERVICE_NAME, "service stopped");+ Ok(())+}++fn log_startup(config: &Config) {+ info!(+ service = SERVICE_NAME,+ seed_topic = %config.seed_events_topic,+ partitioner = %config.kafka_producer_partitioner,+ partition_count = config.cohort_partition_count,+ team_allowlist = ?config.team_allowlist,+ run_poll_secs = config.seeder_run_poll_secs,+ max_concurrent_chunks = config.seeder_max_concurrent_chunks,+ max_lookback_days = config.seeder_max_lookback_days,+ bands_per_day = config.seeder_bands_per_day,+ tiles_per_second = config.seeder_tiles_per_sec,+ max_inflight_tiles = config.seeder_max_inflight_tiles,+ "starting cohort-seeder",+ );+}++fn init_tracing() {+ let is_debug = std::env::var("RUST_LOG").is_ok_and(|value| value.contains("debug"));+ let filter = || {+ EnvFilter::builder()+ .with_default_directive(tracing::level_filters::LevelFilter::INFO.into())+ .from_env_lossy()+ };+ let log_layer = if is_debug {+ fmt::layer()+ .with_target(true)+ .with_level(true)+ .with_ansi(true)+ .with_filter(filter())+ .boxed()+ } else {+ fmt::layer()+ .json()+ .flatten_event(true)+ .with_current_span(true)+ .with_filter(filter())+ .boxed()+ };+ tracing_subscriber::registry().with(log_layer).init();+}diff --git a/rust/cohort-seeder/src/observability/health.rs b/rust/cohort-seeder/src/observability/health.rsnew file mode 100644index 000000000000..e219cc44c766--- /dev/null+++ b/rust/cohort-seeder/src/observability/health.rs@@ -0,0 +1,40 @@+//! Observability leaf: the liveness/readiness HTTP router served alongside the Prometheus scrape+//! endpoint. Depends on `lifecycle`, `axum`, and the Prometheus exporter, never on another seeder module.++use std::future::ready;++use axum::response::IntoResponse;+use axum::routing::get;+use axum::Router;+use lifecycle::{LivenessHandler, ReadinessHandler};+use metrics_exporter_prometheus::PrometheusHandle;++pub fn router(+ service_name: &'static str,+ readiness: ReadinessHandler,+ liveness: LivenessHandler,+ metrics: Option<PrometheusHandle>,+) -> Router {+ let mut app = Router::new()+ .route("/", get(move || async move { service_name }))+ .route(+ "/_health",+ get(move || {+ let liveness = liveness.clone();+ async move { liveness.check().into_response() }+ }),+ )+ .route(+ "/_ready",+ get(move || {+ let readiness = readiness.clone();+ async move { readiness.check().await }+ }),+ );++ if let Some(handle) = metrics {+ app = app.route("/metrics", get(move || ready(handle.render())));+ }++ app+}diff --git a/rust/cohort-seeder/src/observability/metrics.rs b/rust/cohort-seeder/src/observability/metrics.rsnew file mode 100644index 000000000000..f058f90279d3--- /dev/null+++ b/rust/cohort-seeder/src/observability/metrics.rs@@ -0,0 +1,40 @@+//! Observability leaf: the `seeder_*` metric-name constants (the seeder's metric manifest, which+//! dashboards depend on) and the Prometheus recorder installer. Depends on the metrics exporter only.++use metrics_exporter_prometheus::{BuildError, PrometheusBuilder, PrometheusHandle};++pub const RUNS_DISCOVERED: &str = "seeder_runs_discovered_total";+pub const BOUNDARY_ESTABLISHED: &str = "seeder_boundary_established_total";+pub const BOUNDARY_CAS_LOST: &str = "seeder_boundary_cas_lost_total";+pub const RUNS_WAITING_BOUNDARY: &str = "seeder_runs_waiting_boundary";+pub const RUN_VALIDATION_FAILURES: &str = "seeder_run_validation_failures_total";+pub const TZ_FALLBACK: &str = "seeder_tz_fallback_total";+pub const CONDITIONS_DROPPED: &str = "seeder_conditions_dropped_total";+pub const LOOKBACK_TRUNCATED: &str = "seeder_lookback_truncated_total";+pub const CHUNKS_PLANNED: &str = "seeder_chunks_planned_total";+pub const CHUNKS_CLAIMED: &str = "seeder_chunks_claimed_total";+pub const CHUNKS_RECLAIMED: &str = "seeder_chunks_reclaimed_total";+pub const CHUNKS_CONFIRMED: &str = "seeder_chunks_confirmed_total";+pub const CHUNKS_VACUOUS: &str = "seeder_chunks_vacuous_total";+pub const CHUNKS_FAILED: &str = "seeder_chunks_failed_total";+pub const CHUNKS_POISONED: &str = "seeder_chunks_poisoned_total";+pub const CHUNK_SCAN_DURATION_SECONDS: &str = "seeder_chunk_scan_duration_seconds";+pub const ROWS_SCANNED: &str = "seeder_rows_scanned_total";+pub const EVENTS_SKIPPED: &str = "seeder_events_skipped_total";+pub const CONDITIONS_EVALUATED: &str = "seeder_conditions_evaluated_total";+pub const HOGVM_ERRORS: &str = "seeder_hogvm_errors_total";+pub const AGGREGATE_ENTRIES: &str = "seeder_aggregate_entries";+pub const TILES_PRODUCED: &str = "seeder_tiles_produced_total";+pub const TILE_PRODUCE_QUEUE_FULL: &str = "seeder_tile_produce_queue_full_total";+pub const TILE_PRODUCE_ERRORS: &str = "seeder_tile_produce_errors_total";+pub const PRODUCE_ACK_SECONDS: &str = "seeder_produce_ack_seconds";+pub const PACER_WAIT_SECONDS: &str = "seeder_pacer_wait_seconds";+pub const LEASE_HEARTBEATS: &str = "seeder_lease_heartbeats_total";+pub const LEASE_LOST: &str = "seeder_lease_lost_total";+pub const RUN_CHUNKS_REMAINING: &str = "seeder_run_chunks_remaining";+pub const RUNS_WITHOUT_CHUNKS: &str = "seeder_runs_without_chunks";+pub const WINDOW_DAYS_MISMATCH: &str = "seeder_window_days_mismatch_total";++pub fn install_recorder() -> Result<PrometheusHandle, BuildError> {+ PrometheusBuilder::new().install_recorder()+}diff --git a/rust/cohort-seeder/src/observability/mod.rs b/rust/cohort-seeder/src/observability/mod.rsnew file mode 100644index 000000000000..42198731b7d5--- /dev/null+++ b/rust/cohort-seeder/src/observability/mod.rs@@ -0,0 +1,6 @@+//! Observability layer (leaf): the health HTTP router and the Prometheus metric surface. Depends on+//! `lifecycle`/`axum`/the metrics exporter only, never on another seeder module; every layer above+//! draws its metric-name constants from here.++pub mod health;+pub mod metrics;diff --git a/rust/cohort-seeder/src/store/chunks.rs b/rust/cohort-seeder/src/store/chunks.rsnew file mode 100644index 000000000000..f77dde9c20bd--- /dev/null+++ b/rust/cohort-seeder/src/store/chunks.rs@@ -0,0 +1,497 @@+//! The day-chunk claim/CAS ledger in PostgreSQL: the sole owner of the `cohort_backfill_chunks` SQL.+//!+//! Written chunk statuses bind [`ChunkStatus::as_str`] as a parameter; the two multi-status `IN`+//! predicates are hoisted into [`ACTIVE_STATUSES_SQL`]/[`RETRYABLE_STATUSES_SQL`], scanned by a unit+//! test through [`ChunkStatus::from_str`] so the SQL vocabulary can never drift from the enum.+//! Every claim charges an attempt (saturating at the cap) and bumps the fencing `claim_epoch`;+//! expired `produced` leases are reclaimable without an attempt cap (their tiles are already in+//! Kafka and must reach `confirmed`), while expired `scanning` leases are capped and dead-lettered+//! by [`PgChunkStore::reap_poisoned_chunks`] so a chunk that hard-crashes its worker cannot+//! re-scan forever. Depends on `domain` (the pure chunk states it mints and the typed ids) and+//! nothing above.++use chrono::NaiveDate;+use cohort_core::filters::TeamId;+use cohort_core::{day_idx_of_naive_date, DayIdx};+use sqlx::types::Json;+use sqlx::{FromRow, PgPool};+use std::fmt;+use std::num::NonZeroU16;+use uuid::Uuid;++use crate::domain::{+ bands_for_day, Band, BandSpec, BandSpecError, ChunkId, ChunkLease, ChunkSpec, ChunkStatus,+ ClaimEpoch, ClaimKind, ClaimedChunk, EnqueuedChunk, Halted, ProduceHwms, ProducedChunk, RunId,+ SChunkMs, ScannedChunk,+};++use super::lease::LeaseHandle;+use super::{Claimant, LeaseDuration, MaxAttempts, RenderedError, PERSISTED_ERROR_LIMIT};++/// Chunk statuses holding a live lease — the targets of the fenced heartbeat/fail/confirm writes.+const ACTIVE_STATUSES_SQL: &str = "('scanning', 'produced')";+/// Chunk statuses eligible for a fresh claim while under the attempt cap.+const RETRYABLE_STATUSES_SQL: &str = "('pending', 'failed')";++#[derive(Debug, Clone)]+pub struct PgChunkStore {+ pool: PgPool,+}++impl PgChunkStore {+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }++ pub async fn plan_chunks(+ &self,+ run_id: RunId,+ days: impl IntoIterator<Item = DayIdx>,+ bands_per_day: NonZeroU16,+ ) -> Result<PlanOutcome, ChunkStoreError> {+ let mut ids = Vec::new();+ let mut dates = Vec::new();+ let mut bands = Vec::new();+ for day in days {+ let date = date_for_day(day).ok_or(ChunkStoreError::InvalidDay(day))?;+ for band in bands_for_day(day, bands_per_day) {+ ids.push(Uuid::now_v7());+ dates.push(date);+ bands.push(band.0);+ }+ }+ if ids.is_empty() {+ return Ok(PlanOutcome::Planned { inserted: 0 });+ }++ let result = sqlx::query_as::<_, PlanRow>(+ r#"+ WITH target_run AS (+ SELECT id, team_id+ FROM cohort_backfill_runs+ WHERE id = $1 AND status = 'seeding'+ ), input AS (+ SELECT * FROM unnest($2::uuid[], $3::date[], $4::smallint[]) AS u(id, day, band)+ ), inserted AS (+ INSERT INTO cohort_backfill_chunks+ (id, run_id, team_id, day, band, status, claim_epoch, claimed_by, attempts,+ last_error, tiles_produced, created_at, updated_at)+ SELECT u.id, r.id, r.team_id, u.day, u.band, $5, 0, '', 0, '', 0,+ now(), now()+ FROM input u CROSS JOIN target_run r+ ON CONFLICT (run_id, day, band) DO NOTHING+ RETURNING id+ )+ SELECT EXISTS(SELECT 1 FROM target_run) AS run_seeding,+ count(*)::bigint AS inserted+ FROM inserted+ "#,+ )+ .bind(run_id)+ .bind(ids)+ .bind(dates)+ .bind(bands)+ .bind(ChunkStatus::Pending.as_str())+ .fetch_one(&self.pool)+ .await?;+ if !result.run_seeding {+ return Ok(PlanOutcome::RunNotSeeding);+ }+ let inserted = u64::try_from(result.inserted)+ .map_err(|_| ChunkStoreError::InvalidInsertedCount(result.inserted))?;+ Ok(PlanOutcome::Planned { inserted })+ }++ pub async fn claim_next(+ &self,+ run_ids: &[RunId],+ claimant: &Claimant,+ lease: LeaseDuration,+ max_attempts: MaxAttempts,+ ) -> Result<Option<Claim>, ChunkStoreError> {+ if run_ids.is_empty() {+ return Ok(None);+ }+ let run_ids = run_ids.iter().map(|run_id| run_id.0).collect::<Vec<_>>();+ let sql = format!(+ r#"+ WITH next_chunk AS (+ SELECT c.id, c.status IN {active} AS was_reclaim+ FROM cohort_backfill_chunks c+ JOIN cohort_backfill_runs r ON r.id = c.run_id+ WHERE c.run_id = ANY($1) AND r.status = 'seeding'+ AND ((c.status IN {retryable} AND c.attempts < $4)+ OR (c.status = $6 AND c.lease_expires_at < now())+ OR (c.status = $5 AND c.lease_expires_at < now() AND c.attempts < $4))+ ORDER BY c.day, c.band+ LIMIT 1+ FOR UPDATE OF c SKIP LOCKED+ )+ UPDATE cohort_backfill_chunks c+ SET status = $5, claim_epoch = c.claim_epoch + 1, claimed_by = $2,+ claimed_at = now(), lease_expires_at = now() + make_interval(secs => $3),+ s_chunk_at = now(),+ attempts = CASE WHEN c.attempts < $4 THEN c.attempts + 1 ELSE c.attempts END,+ updated_at = now()+ FROM next_chunk+ WHERE c.id = next_chunk.id+ RETURNING c.id, c.run_id, c.team_id, c.day, c.band, c.claim_epoch,+ (extract(epoch FROM c.s_chunk_at) * 1000)::bigint AS s_chunk_ms,+ (SELECT count(*) FROM cohort_backfill_chunks s+ WHERE s.run_id = c.run_id AND s.day = c.day) AS num_bands,+ next_chunk.was_reclaim+ "#,+ active = ACTIVE_STATUSES_SQL,+ retryable = RETRYABLE_STATUSES_SQL,+ );+ let row = sqlx::query_as::<_, ClaimedRow>(&sql)+ .bind(run_ids)+ .bind(claimant.as_str())+ .bind(lease.as_secs())+ .bind(max_attempts.get())+ .bind(ChunkStatus::Scanning.as_str())+ .bind(ChunkStatus::Produced.as_str())+ .fetch_optional(&self.pool)+ .await?;++ row.map(|row| self.assemble_claim(row, claimant, lease))+ .transpose()+ }++ /// Dead-letter `scanning` chunks whose lease expired at the attempt cap. A clean failure caps+ /// out through `fail` plus the claim gate, but a worker that dies without reaching `fail`+ /// (panic, OOM, SIGKILL) leaves its chunk `scanning`; once its attempts saturate, the claim+ /// predicate no longer reclaims it, and this sweep moves it to the same terminal `failed`+ /// state a clean cap-out reaches, so it surfaces to operators instead of stalling invisibly.+ /// Returns the number of chunks dead-lettered.+ pub async fn reap_poisoned_chunks(+ &self,+ run_ids: &[RunId],+ max_attempts: MaxAttempts,+ ) -> Result<u64, ChunkStoreError> {+ if run_ids.is_empty() {+ return Ok(0);+ }+ let run_ids = run_ids.iter().map(|run_id| run_id.0).collect::<Vec<_>>();+ let result = sqlx::query(+ r#"+ UPDATE cohort_backfill_chunks+ SET status = $3, last_error = left($4, $5), updated_at = now()+ WHERE run_id = ANY($1) AND status = $2+ AND lease_expires_at < now() AND attempts >= $6+ "#,+ )+ .bind(run_ids)+ .bind(ChunkStatus::Scanning.as_str())+ .bind(ChunkStatus::Failed.as_str())+ .bind("lease expired at the attempt cap without a clean failure; worker crash suspected")+ .bind(PERSISTED_ERROR_LIMIT)+ .bind(max_attempts.get())+ .execute(&self.pool)+ .await?;+ Ok(result.rows_affected())+ }++ pub async fn mark_produced(+ &self,+ chunk: ScannedChunk,+ ) -> Result<EnqueuedChunk, Halted<ScannedChunk, ChunkStoreError>> {+ let spec = chunk.spec();+ let tiles_produced = match u64::try_from(chunk.tiles().len()) {+ Ok(count) => count,+ Err(_) => {+ return Err(Halted::failed(+ chunk,+ ChunkStoreError::TilesProducedOutOfRange(u64::MAX),+ ));+ }+ };+ if let Err(error) = self.mark_produced_raw(spec.lease, tiles_produced).await {+ return Err(Halted::failed(chunk, error));+ }+ Ok(EnqueuedChunk::new(spec, tiles_produced))+ }++ pub async fn confirm(+ &self,+ chunk: ProducedChunk,+ ) -> Result<ChunkLease, Halted<ProducedChunk, ChunkStoreError>> {+ let spec = chunk.spec();+ if let Err(error) = self.confirm_raw(spec.lease, chunk.hwms()).await {+ return Err(Halted::failed(chunk, error));+ }+ Ok(spec.lease)+ }++ pub async fn fail(+ &self,+ lease: ChunkLease,+ error: &RenderedError,+ ) -> Result<(), ChunkStoreError> {+ let updated = sqlx::query_scalar::<_, ChunkId>(&format!(+ r#"+ UPDATE cohort_backfill_chunks+ SET status = $3, last_error = left($4, $5), updated_at = now()+ WHERE id = $1 AND claim_epoch = $2 AND status IN {active}+ RETURNING id+ "#,+ active = ACTIVE_STATUSES_SQL,+ ))+ .bind(lease.chunk_id())+ .bind(lease.epoch())+ .bind(ChunkStatus::Failed.as_str())+ .bind(error.as_str())+ .bind(PERSISTED_ERROR_LIMIT)+ .fetch_optional(&self.pool)+ .await?;+ fenced(updated, lease, ChunkOperation::Fail)+ }++ pub async fn unclaim(&self, lease: ChunkLease) -> Result<(), ChunkStoreError> {+ let updated = sqlx::query_scalar::<_, ChunkId>(+ r#"+ UPDATE cohort_backfill_chunks+ SET status = $3, claimed_by = '', claimed_at = NULL, lease_expires_at = NULL,+ attempts = GREATEST(attempts - 1, 0), updated_at = now()+ WHERE id = $1 AND claim_epoch = $2 AND status = 'scanning'+ RETURNING id+ "#,+ )+ .bind(lease.chunk_id())+ .bind(lease.epoch())+ .bind(ChunkStatus::Pending.as_str())+ .fetch_optional(&self.pool)+ .await?;+ fenced(updated, lease, ChunkOperation::Unclaim)+ }++ pub async fn remaining_chunks(&self, run_ids: &[RunId]) -> Result<u64, ChunkStoreError> {+ if run_ids.is_empty() {+ return Ok(0);+ }+ let run_ids = run_ids.iter().map(|run_id| run_id.0).collect::<Vec<_>>();+ let count: i64 = sqlx::query_scalar(+ r#"+ SELECT count(*)::bigint+ FROM cohort_backfill_chunks+ WHERE run_id = ANY($1) AND status <> $2+ "#,+ )+ .bind(run_ids)+ .bind(ChunkStatus::Confirmed.as_str())+ .fetch_one(&self.pool)+ .await?;+ u64::try_from(count).map_err(|_| ChunkStoreError::InvalidRemainingCount(count))+ }++ pub(crate) async fn heartbeat(+ &self,+ lease: ChunkLease,+ claimant: &Claimant,+ lease_duration: LeaseDuration,+ ) -> Result<(), ChunkStoreError> {+ let updated = sqlx::query_scalar::<_, ChunkId>(&format!(+ r#"+ UPDATE cohort_backfill_chunks c+ SET lease_expires_at = now() + make_interval(secs => $3), updated_at = now()+ FROM cohort_backfill_runs r+ WHERE c.id = $1 AND c.claim_epoch = $2 AND c.claimed_by = $4+ AND c.status IN {active}+ AND r.id = c.run_id AND r.status = 'seeding'+ RETURNING c.id+ "#,+ active = ACTIVE_STATUSES_SQL,+ ))+ .bind(lease.chunk_id())+ .bind(lease.epoch())+ .bind(lease_duration.as_secs())+ .bind(claimant.as_str())+ .fetch_optional(&self.pool)+ .await?;+ fenced(updated, lease, ChunkOperation::Heartbeat)+ }++ pub(crate) async fn mark_produced_raw(+ &self,+ lease: ChunkLease,+ tiles_produced: u64,+ ) -> Result<(), ChunkStoreError> {+ let tiles_produced = i64::try_from(tiles_produced)+ .map_err(|_| ChunkStoreError::TilesProducedOutOfRange(tiles_produced))?;+ let updated = sqlx::query_scalar::<_, ChunkId>(+ r#"+ UPDATE cohort_backfill_chunks+ SET status = $3, tiles_produced = $4, updated_at = now()+ WHERE id = $1 AND claim_epoch = $2 AND status = 'scanning'+ RETURNING id+ "#,+ )+ .bind(lease.chunk_id())+ .bind(lease.epoch())+ .bind(ChunkStatus::Produced.as_str())+ .bind(tiles_produced)+ .fetch_optional(&self.pool)+ .await?;+ fenced(updated, lease, ChunkOperation::MarkProduced)+ }++ pub(crate) async fn confirm_raw(+ &self,+ lease: ChunkLease,+ produce_hwms: &ProduceHwms,+ ) -> Result<(), ChunkStoreError> {+ let updated = sqlx::query_scalar::<_, ChunkId>(&format!(+ r#"+ UPDATE cohort_backfill_chunks+ SET status = $3, confirmed_at = now(), produce_hwms = $4, updated_at = now()+ WHERE id = $1 AND claim_epoch = $2 AND status IN {active}+ RETURNING id+ "#,+ active = ACTIVE_STATUSES_SQL,+ ))+ .bind(lease.chunk_id())+ .bind(lease.epoch())+ .bind(ChunkStatus::Confirmed.as_str())+ .bind(Json(produce_hwms))+ .fetch_optional(&self.pool)+ .await?;+ fenced(updated, lease, ChunkOperation::Confirm)+ }++ fn assemble_claim(+ &self,+ row: ClaimedRow,+ claimant: &Claimant,+ lease_duration: LeaseDuration,+ ) -> Result<Claim, ChunkStoreError> {+ let band = BandSpec::new(row.band.0, row.num_bands)?;+ let lease = ChunkLease::new(row.id, row.run_id, row.claim_epoch);+ let spec = ChunkSpec {+ lease,+ team_id: TeamId(row.team_id),+ day: day_idx_of_naive_date(row.day),+ band,+ s_chunk: SChunkMs(row.s_chunk_ms),+ };+ let handle = LeaseHandle::start(self.clone(), lease, claimant.clone(), lease_duration);+ Ok(Claim {+ chunk: ClaimedChunk::new(spec),+ kind: ClaimKind::from_was_reclaim(row.was_reclaim),+ lease: handle,+ })+ }+}++/// A freshly claimed chunk: its pure state, whether it was a reclaim (for the app's metric), and the+/// heartbeat handle to hold alongside it. Assembled entirely by the store — the pure state never+/// calls back into the store.+pub struct Claim {+ pub chunk: ClaimedChunk,+ pub kind: ClaimKind,+ pub lease: LeaseHandle,+}++/// The result of planning a run's day-chunks. `RunNotSeeding` is control flow (the run left the+/// `seeding` state between discovery and planning), not an error.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PlanOutcome {+ Planned { inserted: u64 },+ RunNotSeeding,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ChunkOperation {+ Heartbeat,+ MarkProduced,+ Confirm,+ Fail,+ Unclaim,+}++impl fmt::Display for ChunkOperation {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter.write_str(match self {+ Self::Heartbeat => "heartbeat",+ Self::MarkProduced => "mark-produced",+ Self::Confirm => "confirm",+ Self::Fail => "fail",+ Self::Unclaim => "unclaim",+ })+ }+}++#[derive(Debug, thiserror::Error)]+pub enum ChunkStoreError {+ #[error("PostgreSQL chunk operation failed")]+ Pg(#[from] sqlx::Error),+ #[error("chunk {lease:?} lost its lease during {operation}")]+ LeaseLost {+ lease: ChunkLease,+ operation: ChunkOperation,+ },+ #[error("tiles produced {0} exceeds PostgreSQL bigint range")]+ TilesProducedOutOfRange(u64),+ #[error("day index {0} is outside chrono's date range")]+ InvalidDay(DayIdx),+ #[error(transparent)]+ Band(#[from] BandSpecError),+ #[error("chunk planner returned invalid insert count {0}")]+ InvalidInsertedCount(i64),+ #[error("chunk counter returned invalid remaining count {0}")]+ InvalidRemainingCount(i64),+}++#[derive(Debug, FromRow)]+struct ClaimedRow {+ id: ChunkId,+ run_id: RunId,+ team_id: i32,+ day: NaiveDate,+ band: Band,+ claim_epoch: ClaimEpoch,+ s_chunk_ms: i64,+ num_bands: i64,+ was_reclaim: bool,+}++#[derive(Debug, FromRow)]+struct PlanRow {+ run_seeding: bool,+ inserted: i64,+}++fn fenced(+ updated: Option<ChunkId>,+ lease: ChunkLease,+ operation: ChunkOperation,+) -> Result<(), ChunkStoreError> {+ updated+ .map(|_| ())+ .ok_or(ChunkStoreError::LeaseLost { lease, operation })+}++fn date_for_day(day: DayIdx) -> Option<NaiveDate> {+ let epoch = NaiveDate::from_ymd_opt(1970, 1, 1)?;+ epoch.checked_add_signed(chrono::Duration::days(i64::from(day)))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn hoisted_status_fragments_only_name_live_chunk_statuses() {+ for fragment in [ACTIVE_STATUSES_SQL, RETRYABLE_STATUSES_SQL] {+ let statuses = fragment+ .trim_matches(|c| c == '(' || c == ')')+ .split(',')+ .map(|token| token.trim().trim_matches('\''));+ for status in statuses {+ assert!(+ status.parse::<ChunkStatus>().is_ok(),+ "SQL fragment names non-vocabulary status {status:?}"+ );+ }+ }+ }+}diff --git a/rust/cohort-seeder/src/store/lease.rs b/rust/cohort-seeder/src/store/lease.rsnew file mode 100644index 000000000000..688063ca1d10--- /dev/null+++ b/rust/cohort-seeder/src/store/lease.rs@@ -0,0 +1,186 @@+//! The lease-heartbeat handle held alongside a claimed chunk's pure state (PostgreSQL layer).+//!+//! A background ticker renews the lease every `lease / 3`; if a renewal fences out (a competing+//! reclaim bumped the epoch), it cancels the child token and publishes a [`LeaseFailure`]. `Drop`+//! aborts the task, so releasing the handle stops the heartbeats. Depends on `domain` (the lease+//! coordinates) and the sibling store SQL.++use std::sync::{Arc, Mutex};++use metrics::counter;+use tokio::sync::Notify;+use tokio::task::{AbortHandle, JoinError, JoinHandle};+use tokio_util::sync::CancellationToken;++use crate::domain::ChunkLease;+use crate::observability::metrics::{LEASE_HEARTBEATS, LEASE_LOST};++use super::chunks::{ChunkStoreError, PgChunkStore};+use super::{Claimant, LeaseDuration};++pub struct LeaseHandle {+ cancel: CancellationToken,+ signal: LeaseFailureSignal,+ worker_abort: AbortHandle,+ supervisor: JoinHandle<()>,+}++impl LeaseHandle {+ pub(crate) fn start(+ store: PgChunkStore,+ lease: ChunkLease,+ claimant: Claimant,+ lease_duration: LeaseDuration,+ ) -> Self {+ let cancel = CancellationToken::new();+ let worker_cancel = cancel.clone();+ let worker = tokio::spawn(async move {+ let _cancel_on_exit = CancelOnDrop(worker_cancel.clone());+ let mut ticker = tokio::time::interval(lease_duration.heartbeat_interval());+ ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);+ ticker.tick().await;+ loop {+ tokio::select! {+ biased;+ _ = worker_cancel.cancelled() => return Ok(()),+ _ = ticker.tick() => {+ match store.heartbeat(lease, &claimant, lease_duration).await {+ Ok(()) => counter!(LEASE_HEARTBEATS).increment(1),+ Err(error) => {+ counter!(LEASE_LOST).increment(1);+ return Err(error);+ }+ }+ }+ }+ }+ });+ Self::supervise(cancel, worker)+ }++ fn supervise(+ cancel: CancellationToken,+ worker: JoinHandle<Result<(), ChunkStoreError>>,+ ) -> Self {+ let worker_abort = worker.abort_handle();+ let signal = LeaseFailureSignal::new();+ let failure_state = Arc::clone(&signal.state);+ let supervisor = tokio::spawn(async move {+ match worker.await {+ Ok(Ok(())) => {}+ Ok(Err(error)) => failure_state.publish(LeaseFailure::Heartbeat(error)),+ Err(error) => failure_state.publish(LeaseFailure::Task(error)),+ }+ });+ Self {+ cancel,+ signal,+ worker_abort,+ supervisor,+ }+ }++ /// A child token cancelled when the lease is lost; the scan/produce loops select on it to abort.+ pub fn cancellation_token(&self) -> CancellationToken {+ self.cancel.child_token()+ }++ /// Resolves once the heartbeat task loses the lease or panics.+ pub async fn failure(&self) -> LeaseFailure {+ self.signal.wait().await+ }+}++impl Drop for LeaseHandle {+ fn drop(&mut self) {+ self.cancel.cancel();+ self.worker_abort.abort();+ self.supervisor.abort();+ }+}++#[derive(Debug, thiserror::Error)]+pub enum LeaseFailure {+ #[error("lease heartbeat failed")]+ Heartbeat(#[source] ChunkStoreError),+ #[error("lease heartbeat task failed")]+ Task(#[source] JoinError),+}++struct LeaseFailureState {+ failure: Mutex<Option<LeaseFailure>>,+ notify: Notify,+}++impl LeaseFailureState {+ fn publish(&self, failure: LeaseFailure) {+ *self+ .failure+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(failure);+ self.notify.notify_one();+ }+}++struct LeaseFailureSignal {+ state: Arc<LeaseFailureState>,+}++impl LeaseFailureSignal {+ fn new() -> Self {+ Self {+ state: Arc::new(LeaseFailureState {+ failure: Mutex::new(None),+ notify: Notify::new(),+ }),+ }+ }++ async fn wait(&self) -> LeaseFailure {+ loop {+ let notified = self.state.notify.notified();+ if let Some(failure) = self+ .state+ .failure+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .take()+ {+ return failure;+ }+ notified.await;+ }+ }+}++struct CancelOnDrop(CancellationToken);++impl Drop for CancelOnDrop {+ fn drop(&mut self) {+ self.0.cancel();+ }+}++#[cfg(test)]+mod tests {+ use std::time::Duration;++ use super::*;++ #[tokio::test]+ async fn lease_handle_surfaces_task_panics_and_cancels() {+ let cancel = CancellationToken::new();+ let worker_cancel = cancel.clone();+ let worker: JoinHandle<Result<(), ChunkStoreError>> = tokio::spawn(async move {+ let _cancel_on_exit = CancelOnDrop(worker_cancel);+ panic!("heartbeat panic")+ });+ let handle = LeaseHandle::supervise(cancel.clone(), worker);++ let failure = tokio::time::timeout(Duration::from_secs(1), handle.failure())+ .await+ .unwrap();+ assert!(matches!(failure, LeaseFailure::Task(error) if error.is_panic()));+ assert!(cancel.is_cancelled());+ }+}diff --git a/rust/cohort-seeder/src/store/mod.rs b/rust/cohort-seeder/src/store/mod.rsnew file mode 100644index 000000000000..4b2b1e6c6f58--- /dev/null+++ b/rust/cohort-seeder/src/store/mod.rs@@ -0,0 +1,184 @@+//! The sole owner of the seeder's PostgreSQL access: `sqlx` is confined to this module tree (and+//! `test_support`). Everything above receives typed rows and typed errors; nothing below leaks a DB+//! concept. Submodules: `chunks` (the day-chunk claim/CAS ledger), `runs` (run discovery + boundary+//! establishment + pinned load), `lease` (the heartbeat handle). Depends on `domain` (typed ids and+//! rows) and the `observability` metric constants — nothing else in the crate.++pub mod chunks;+pub mod lease;+pub mod runs;++use std::time::Duration;++/// The single character cap for every operator-facing error column (`chunk.last_error`,+/// `run.error`). Bound as `left($n, $m)` at each persistence site, and enforced again in Rust by+/// [`RenderedError`] so an un-truncated string can never reach the wire.+pub const PERSISTED_ERROR_LIMIT: i32 = 4096;++/// A validated worker identity, 1..=255 bytes — the width of `chunk.claimed_by`.+#[derive(Debug, Clone)]+pub struct Claimant(String);++impl Claimant {+ pub fn new(value: impl Into<String>) -> Result<Self, ClaimantError> {+ let value = value.into();+ let len = value.len();+ if !(1..=255).contains(&len) {+ return Err(ClaimantError(len));+ }+ Ok(Self(value))+ }++ pub fn as_str(&self) -> &str {+ &self.0+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]+#[error("claimant must contain 1 to 255 bytes, got {0}")]+pub struct ClaimantError(pub usize);++/// A lease length validated to the deliberate ≥3 s floor. Storing seconds pre-converted lets the+/// heartbeat interval be exactly `lease / 3` with no `.max(1s)` guard: `secs >= 3` ⇒ `secs / 3 >= 1`.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct LeaseDuration {+ secs: i64,+}++impl LeaseDuration {+ pub fn new(duration: Duration) -> Result<Self, LeaseDurationError> {+ if duration < Duration::from_secs(3) {+ return Err(LeaseDurationError::TooShort);+ }+ let secs = i64::try_from(duration.as_secs()).map_err(|_| LeaseDurationError::TooLong)?;+ Ok(Self { secs })+ }++ pub const fn as_secs(self) -> i64 {+ self.secs+ }++ pub fn heartbeat_interval(self) -> Duration {+ Duration::from_secs(u64::try_from(self.secs / 3).unwrap_or(1))+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]+pub enum LeaseDurationError {+ #[error("chunk lease must be at least three seconds")]+ TooShort,+ #[error("chunk lease exceeds PostgreSQL interval range")]+ TooLong,+}++/// A retry ceiling validated to 1..=i32::MAX (the width of `chunk.attempts`).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct MaxAttempts(i32);++impl MaxAttempts {+ pub fn new(value: u32) -> Result<Self, MaxAttemptsError> {+ if value == 0 {+ return Err(MaxAttemptsError::Zero);+ }+ let value = i32::try_from(value).map_err(|_| MaxAttemptsError::OutOfRange(value))?;+ Ok(Self(value))+ }++ pub const fn get(self) -> i32 {+ self.0+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]+pub enum MaxAttemptsError {+ #[error("maximum attempts must be greater than zero")]+ Zero,+ #[error("maximum attempts {0} exceeds PostgreSQL integer range")]+ OutOfRange(u32),+}++/// An error already flattened to its full cause chain and truncated at a character boundary. The+/// persistence sites (`store.fail`, `fail_run`) accept only this, so a bare `.to_string()` — which+/// loses source context — cannot reach the wire.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct RenderedError(String);++impl RenderedError {+ pub fn render(error: &dyn std::error::Error) -> Self {+ Self(render_error_chain(error))+ }++ pub fn from_message(message: impl Into<String>) -> Self {+ Self(truncate_chars(message.into(), PERSISTED_ERROR_LIMIT))+ }++ pub fn as_str(&self) -> &str {+ &self.0+ }+}++/// Flatten an error and its causes into `"top: cause: root"`, truncated to [`PERSISTED_ERROR_LIMIT`]+/// characters at a UTF-8 boundary.+pub fn render_error_chain(error: &dyn std::error::Error) -> String {+ let mut rendered = error.to_string();+ let mut source = error.source();+ while let Some(cause) = source {+ rendered.push_str(": ");+ rendered.push_str(&cause.to_string());+ source = cause.source();+ }+ truncate_chars(rendered, PERSISTED_ERROR_LIMIT)+}++fn truncate_chars(mut value: String, max_chars: i32) -> String {+ let max_chars = usize::try_from(max_chars).unwrap_or(0);+ if let Some((byte_idx, _)) = value.char_indices().nth(max_chars) {+ value.truncate(byte_idx);+ }+ value+}++#[cfg(test)]+mod tests {+ use std::time::Duration;++ use super::*;++ #[derive(Debug, thiserror::Error)]+ #[error("outer")]+ struct Outer(#[source] Inner);++ #[derive(Debug, thiserror::Error)]+ #[error("inner")]+ struct Inner;++ #[test]+ fn render_error_chain_joins_the_source_chain() {+ assert_eq!(render_error_chain(&Outer(Inner)), "outer: inner");+ }++ #[test]+ fn rendered_error_truncates_on_a_char_boundary() {+ let multibyte = "é".repeat(5_000);+ let rendered = RenderedError::from_message(multibyte);+ assert_eq!(rendered.as_str().chars().count(), 4_096);+ // Truncation kept whole `é`s: the byte length is exactly 2 per char, never a split byte.+ assert_eq!(rendered.as_str().len(), 4_096 * 2);+ }++ #[test]+ fn value_objects_reject_out_of_range_inputs() {+ assert!(Claimant::new("").is_err());+ assert!(Claimant::new("x".repeat(256)).is_err());+ assert!(Claimant::new("worker").is_ok());+ assert!(LeaseDuration::new(Duration::from_secs(2)).is_err());+ assert_eq!(+ LeaseDuration::new(Duration::from_secs(9))+ .unwrap()+ .heartbeat_interval(),+ Duration::from_secs(3)+ );+ assert!(matches!(MaxAttempts::new(0), Err(MaxAttemptsError::Zero)));+ assert_eq!(MaxAttempts::new(5).unwrap().get(), 5);+ }+}diff --git a/rust/cohort-seeder/src/store/runs.rs b/rust/cohort-seeder/src/store/runs.rsnew file mode 100644index 000000000000..bdf84253b864--- /dev/null+++ b/rust/cohort-seeder/src/store/runs.rs@@ -0,0 +1,525 @@+//! Run discovery, boundary establishment, and pinned-payload load in PostgreSQL. Owns the+//! `cohort_backfill_runs`/`cohort_backfill_run_cohorts` SQL (Q1/Q2/Q8 + warnings). Depends on `domain`.++use std::str::FromStr;++use chrono::{DateTime, Utc};+use cohort_core::filters::{CohortId, TeamId};+use common_types::cohort::TeamAllowlist;+use serde_json::Value;+use sqlx::types::Json;+use sqlx::{FromRow, PgPool};++use crate::domain::{+ PinnedError, PinnedParticipation, PinnedParticipationState, PinnedRun, PinnedRunSnapshot,+ RunId, TriggerKind, UtcMillis, ValidatedPinnedRun,+};++use super::{RenderedError, PERSISTED_ERROR_LIMIT};++/// The one run-column list the three run SELECTs share. A macro (not a `const`) so it can feed+/// `concat!`, which only accepts literals and macro expansions — the composed SQL text stays a+/// compile-time constant, byte-identical to the former inline lists and pinned by the pg test.+macro_rules! run_columns {+ () => {+ "id, team_id, cohort_id, trigger_kind, scope, status, timezone, boundary_at, pinned"+ };+}++const DISCOVER_ALL: &str = concat!(+ "\n SELECT ",+ run_columns!(),+ "\n FROM cohort_backfill_runs",+ "\n WHERE status IN ('awaiting_boundary', 'seeding')",+ "\n AND backfill_kind = 'behavioral'",+ "\n ORDER BY created_at\n"+);++const DISCOVER_ONLY: &str = concat!(+ "\n SELECT ",+ run_columns!(),+ "\n FROM cohort_backfill_runs",+ "\n WHERE status IN ('awaiting_boundary', 'seeding')",+ "\n AND backfill_kind = 'behavioral'",+ "\n AND team_id = ANY($1)",+ "\n ORDER BY created_at\n"+);++const READ_RUN: &str = concat!(+ "\n SELECT ",+ run_columns!(),+ "\n FROM cohort_backfill_runs",+ "\n WHERE id = $1 AND backfill_kind = 'behavioral'\n"+);++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum RunWarningNote {+ ConditionsDropped,+ LookbackTruncated,+}++impl RunWarningNote {+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::ConditionsDropped => "Seeder dropped unsupported pinned conditions.",+ Self::LookbackTruncated => {+ "Seeder truncated cohort history to the configured lookback."+ }+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum RunStatus {+ AwaitingBoundary,+ Blocked,+ Seeding,+ Reconciling,+ Completed,+ Superseded,+ Cancelled,+ Failed,+}++impl RunStatus {+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::AwaitingBoundary => "awaiting_boundary",+ Self::Blocked => "blocked",+ Self::Seeding => "seeding",+ Self::Reconciling => "reconciling",+ Self::Completed => "completed",+ Self::Superseded => "superseded",+ Self::Cancelled => "cancelled",+ Self::Failed => "failed",+ }+ }+}++impl FromStr for RunStatus {+ type Err = RunError;++ fn from_str(value: &str) -> Result<Self, Self::Err> {+ match value {+ "awaiting_boundary" => Ok(Self::AwaitingBoundary),+ "blocked" => Ok(Self::Blocked),+ "seeding" => Ok(Self::Seeding),+ "reconciling" => Ok(Self::Reconciling),+ "completed" => Ok(Self::Completed),+ "superseded" => Ok(Self::Superseded),+ "cancelled" => Ok(Self::Cancelled),+ "failed" => Ok(Self::Failed),+ other => Err(RunError::UnknownStatus(other.to_string())),+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum RunScope {+ Team,+ Cohort,+}++impl RunScope {+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::Team => "team",+ Self::Cohort => "cohort",+ }+ }+}++impl FromStr for RunScope {+ type Err = RunError;++ fn from_str(value: &str) -> Result<Self, Self::Err> {+ match value {+ "team" => Ok(Self::Team),+ "cohort" => Ok(Self::Cohort),+ other => Err(RunError::UnknownScope(other.to_string())),+ }+ }+}++#[derive(Debug, Clone)]+pub struct DiscoveredRun {+ pub run_id: RunId,+ pub team_id: TeamId,+ pub cohort_id: Option<CohortId>,+ pub trigger: TriggerKind,+ pub scope: RunScope,+ pub status: RunStatus,+ pub timezone: String,+ pub boundary_at: Option<DateTime<Utc>>,+ pub pinned: Value,+}++/// A run proven `seeding` with an established boundary — the only place the boundary `Option`+/// narrows to a value and the trigger stays typed all the way into [`PinnedRunSnapshot`]. Minted+/// only by [`establish_boundary`].+#[derive(Debug, Clone)]+pub struct SeedableRun {+ pub run_id: RunId,+ pub team_id: TeamId,+ pub trigger: TriggerKind,+ pub timezone: String,+ pub boundary_at: UtcMillis,+ pub pinned: Value,+}++impl SeedableRun {+ fn promote(run: DiscoveredRun, boundary_at: DateTime<Utc>) -> Self {+ Self {+ run_id: run.run_id,+ team_id: run.team_id,+ trigger: run.trigger,+ timezone: run.timezone,+ boundary_at: UtcMillis::new(boundary_at.timestamp_millis()),+ pinned: run.pinned,+ }+ }++ pub async fn load_pinned(&self, pool: &PgPool) -> Result<ValidatedPinnedRun, RunError> {+ let rows = sqlx::query_as::<_, ParticipationRow>(+ r#"+ SELECT team_id, cohort_id, filters_shape_hash, pinned_filters, superseded_at+ FROM cohort_backfill_run_cohorts+ WHERE run_id = $1+ ORDER BY cohort_id+ "#,+ )+ .bind(self.run_id)+ .fetch_all(pool)+ .await?;++ let mut participations = Vec::with_capacity(rows.len());+ for row in rows {+ if row.team_id != self.team_id.0 {+ return Err(RunError::CrossTeamParticipation {+ run_id: self.run_id,+ cohort_id: CohortId(row.cohort_id),+ expected_team_id: self.team_id.0,+ actual_team_id: row.team_id,+ });+ }+ participations.push(PinnedParticipation {+ cohort_id: CohortId(row.cohort_id),+ pinned_filters: row.pinned_filters.0,+ state: if row.superseded_at.is_some() {+ PinnedParticipationState::Superseded+ } else {+ PinnedParticipationState::Active+ },+ });+ }+ let snapshot = PinnedRunSnapshot {+ run_id: self.run_id,+ team_id: self.team_id,+ trigger: self.trigger,+ timezone: self.timezone.clone(),+ boundary_at_ms: self.boundary_at.as_i64(),+ pinned: self.pinned.clone(),+ participations,+ };+ Ok(PinnedRun::validate(snapshot)?)+ }+}++#[derive(Debug, Clone)]+pub enum BoundaryOutcome {+ Established(SeedableRun),+ AlreadyEstablished(SeedableRun),+ NoLongerSeedable { run_id: RunId, status: RunStatus },+}++#[derive(Debug, thiserror::Error)]+pub enum RunError {+ #[error("PostgreSQL run operation failed: {0}")]+ Pg(#[from] sqlx::Error),+ #[error(transparent)]+ Pinned(#[from] PinnedError),+ #[error("unknown backfill run status {0:?}")]+ UnknownStatus(String),+ #[error("unknown backfill scope {0:?}")]+ UnknownScope(String),+ #[error("run {run_id:?} has unknown backfill trigger {value:?}")]+ InvalidTrigger { run_id: RunId, value: String },+ #[error("run {run_id:?} has unknown backfill scope {value:?}")]+ InvalidScope { run_id: RunId, value: String },+ #[error("run {run_id:?} has unknown backfill status {value:?}")]+ InvalidStatus { run_id: RunId, value: String },+ #[error("run {0:?} was not found")]+ NotFound(RunId),+ #[error("disaster-recovery run {0:?} has no pinned boundary")]+ DisasterRecoveryBoundaryMissing(RunId),+ #[error("seeding run {0:?} has no established boundary")]+ SeedingBoundaryMissing(RunId),+ #[error("run {0:?} is no longer active and could not be failed")]+ NotActive(RunId),+ #[error(+ "run {run_id:?} team {expected_team_id} has cohort {cohort_id:?} stored under team {actual_team_id}"+ )]+ CrossTeamParticipation {+ run_id: RunId,+ cohort_id: CohortId,+ expected_team_id: i32,+ actual_team_id: i32,+ },+}++impl RunError {+ pub const fn run_id(&self) -> Option<RunId> {+ match self {+ Self::InvalidTrigger { run_id, .. }+ | Self::InvalidScope { run_id, .. }+ | Self::InvalidStatus { run_id, .. }+ | Self::NotFound(run_id)+ | Self::DisasterRecoveryBoundaryMissing(run_id)+ | Self::SeedingBoundaryMissing(run_id)+ | Self::NotActive(run_id)+ | Self::CrossTeamParticipation { run_id, .. } => Some(*run_id),+ Self::Pg(_) | Self::Pinned(_) | Self::UnknownStatus(_) | Self::UnknownScope(_) => None,+ }+ }+}++#[derive(Debug, FromRow)]+struct RunRow {+ id: RunId,+ team_id: i32,+ cohort_id: Option<i32>,+ trigger_kind: String,+ scope: String,+ status: String,+ timezone: String,+ boundary_at: Option<DateTime<Utc>>,+ pinned: Json<Value>,+}++impl TryFrom<RunRow> for DiscoveredRun {+ type Error = RunError;++ fn try_from(row: RunRow) -> Result<Self, Self::Error> {+ let trigger =+ row.trigger_kind+ .parse::<TriggerKind>()+ .map_err(|_| RunError::InvalidTrigger {+ run_id: row.id,+ value: row.trigger_kind.clone(),+ })?;+ let scope = row.scope.parse().map_err(|_| RunError::InvalidScope {+ run_id: row.id,+ value: row.scope.clone(),+ })?;+ let status = row.status.parse().map_err(|_| RunError::InvalidStatus {+ run_id: row.id,+ value: row.status.clone(),+ })?;+ Ok(Self {+ run_id: row.id,+ team_id: TeamId(row.team_id),+ cohort_id: row.cohort_id.map(CohortId),+ trigger,+ scope,+ status,+ timezone: row.timezone,+ boundary_at: row.boundary_at,+ pinned: row.pinned.0,+ })+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn malformed_discovered_rows_keep_the_run_capability_for_q8() {+ let run_id = RunId(uuid::Uuid::from_u128(1));+ let error = DiscoveredRun::try_from(RunRow {+ id: run_id,+ team_id: 2,+ cohort_id: None,+ trigger_kind: "invalid".to_string(),+ scope: "team".to_string(),+ status: "seeding".to_string(),+ timezone: "UTC".to_string(),+ boundary_at: Some(Utc::now()),+ pinned: Json(serde_json::json!({})),+ })+ .unwrap_err();++ assert!(matches!(+ &error,+ RunError::InvalidTrigger {+ run_id: observed,+ ..+ } if *observed == run_id+ ));+ assert_eq!(error.run_id(), Some(run_id));+ }+}++#[derive(Debug, FromRow)]+struct ParticipationRow {+ team_id: i32,+ cohort_id: i32,+ /// B5 CAS-readiness / reconcile seam: the filters shape hash read from+ /// `cohort_backfill_run_cohorts` for a future reconcile slice. Populated by Q1 (whose SQL stays+ /// frozen) but not yet read, so the attr suppresses the dead-field lint until that slice lands.+ #[allow(dead_code)]+ filters_shape_hash: String,+ pinned_filters: Json<Value>,+ superseded_at: Option<DateTime<Utc>>,+}++#[derive(Debug, FromRow)]+struct BoundaryRow {+ boundary_at: DateTime<Utc>,+}++pub async fn discover_runs(+ pool: &PgPool,+ allowlist: &TeamAllowlist,+) -> Result<Vec<DiscoveredRun>, RunError> {+ let rows = match allowlist {+ TeamAllowlist::All => {+ sqlx::query_as::<_, RunRow>(DISCOVER_ALL)+ .fetch_all(pool)+ .await?+ }+ TeamAllowlist::Only(team_ids) => {+ let mut team_ids = team_ids.iter().copied().collect::<Vec<_>>();+ team_ids.sort_unstable();+ sqlx::query_as::<_, RunRow>(DISCOVER_ONLY)+ .bind(team_ids)+ .fetch_all(pool)+ .await?+ }+ };+ rows.into_iter().map(DiscoveredRun::try_from).collect()+}++pub async fn establish_boundary(+ pool: &PgPool,+ run: DiscoveredRun,+) -> Result<BoundaryOutcome, RunError> {+ if run.status == RunStatus::Seeding {+ return match run.boundary_at {+ Some(boundary_at) => Ok(BoundaryOutcome::AlreadyEstablished(SeedableRun::promote(+ run,+ boundary_at,+ ))),+ None => Err(RunError::SeedingBoundaryMissing(run.run_id)),+ };+ }+ if run.trigger == TriggerKind::DisasterRecovery && run.boundary_at.is_none() {+ return Err(RunError::DisasterRecoveryBoundaryMissing(run.run_id));+ }++ let boundary = match run.trigger {+ TriggerKind::DisasterRecovery => {+ sqlx::query_as::<_, BoundaryRow>(+ r#"+ UPDATE cohort_backfill_runs+ SET status = 'seeding', boundary_established_at = now(), updated_at = now()+ WHERE id = $1 AND status = 'awaiting_boundary'+ AND trigger_kind = 'disaster_recovery' AND boundary_at IS NOT NULL+ RETURNING boundary_at+ "#,+ )+ .bind(run.run_id)+ .fetch_optional(pool)+ .await?+ }+ TriggerKind::TeamEnablement | TriggerKind::CohortCreated | TriggerKind::CohortEdited => {+ sqlx::query_as::<_, BoundaryRow>(+ r#"+ UPDATE cohort_backfill_runs+ SET status = 'seeding', boundary_at = now(), boundary_established_at = now(),+ updated_at = now()+ WHERE id = $1 AND status = 'awaiting_boundary' AND boundary_at IS NULL+ AND trigger_kind IN ('team_enablement', 'cohort_created', 'cohort_edited')+ RETURNING boundary_at+ "#,+ )+ .bind(run.run_id)+ .fetch_optional(pool)+ .await?+ }+ };++ if let Some(boundary) = boundary {+ return Ok(BoundaryOutcome::Established(SeedableRun::promote(+ run,+ boundary.boundary_at,+ )));+ }++ let current = read_run(pool, run.run_id).await?;+ if current.status == RunStatus::Seeding {+ match current.boundary_at {+ Some(boundary_at) => Ok(BoundaryOutcome::AlreadyEstablished(SeedableRun::promote(+ current,+ boundary_at,+ ))),+ None => Err(RunError::SeedingBoundaryMissing(current.run_id)),+ }+ } else {+ Ok(BoundaryOutcome::NoLongerSeedable {+ run_id: current.run_id,+ status: current.status,+ })+ }+}++pub async fn fail_run(pool: &PgPool, run_id: RunId, error: &RenderedError) -> Result<(), RunError> {+ let failed = sqlx::query_scalar::<_, RunId>(+ r#"+ UPDATE cohort_backfill_runs+ SET status = 'failed', error = left($2, $3), finished_at = now(), updated_at = now()+ WHERE id = $1 AND status IN ('awaiting_boundary', 'seeding')+ RETURNING id+ "#,+ )+ .bind(run_id)+ .bind(error.as_str())+ .bind(PERSISTED_ERROR_LIMIT)+ .fetch_optional(pool)+ .await?;+ failed.map(|_| ()).ok_or(RunError::NotActive(run_id))+}++pub async fn record_run_warning(+ pool: &PgPool,+ run_id: RunId,+ note: RunWarningNote,+) -> Result<bool, RunError> {+ let updated = sqlx::query_scalar::<_, RunId>(+ r#"+ UPDATE cohort_backfill_runs+ SET error = left(+ CASE WHEN error = '' THEN $2 ELSE $2 || E'\n' || error END,+ $3+ ),+ updated_at = now()+ WHERE id = $1 AND status = 'seeding' AND strpos(error, $2) = 0+ RETURNING id+ "#,+ )+ .bind(run_id)+ .bind(note.as_str())+ .bind(PERSISTED_ERROR_LIMIT)+ .fetch_optional(pool)+ .await?;+ Ok(updated.is_some())+}++async fn read_run(pool: &PgPool, run_id: RunId) -> Result<DiscoveredRun, RunError> {+ let row = sqlx::query_as::<_, RunRow>(READ_RUN)+ .bind(run_id)+ .fetch_optional(pool)+ .await?+ .ok_or(RunError::NotFound(run_id))?;+ row.try_into()+}diff --git a/rust/cohort-seeder/src/test_support.rs b/rust/cohort-seeder/src/test_support.rsnew file mode 100644index 000000000000..825f9e582f90--- /dev/null+++ b/rust/cohort-seeder/src/test_support.rs@@ -0,0 +1,52 @@+//! Feature-gated (`pg-test-support`) test hooks: mint pure chunk states without a claim, and drive+//! the store's lease-fenced SQL directly by [`ChunkLease`] so the integration test can exercise the+//! epoch fence in isolation. Not compiled into the shipping binary.++use crate::domain::{ChunkLease, ChunkSpec, ClaimedChunk, ProduceHwms, ScannedChunk, SeedTile};+use crate::store::chunks::{ChunkStoreError, PgChunkStore};+use crate::store::{Claimant, LeaseDuration, RenderedError};++pub fn claimed(spec: ChunkSpec) -> ClaimedChunk {+ ClaimedChunk::new(spec)+}++pub fn scanned(spec: ChunkSpec, tiles: Vec<SeedTile>) -> ScannedChunk {+ ScannedChunk::new(spec, tiles)+}++pub async fn heartbeat(+ store: &PgChunkStore,+ lease: ChunkLease,+ claimant: &Claimant,+ lease_duration: LeaseDuration,+) -> Result<(), ChunkStoreError> {+ store.heartbeat(lease, claimant, lease_duration).await+}++pub async fn mark_produced_raw(+ store: &PgChunkStore,+ lease: ChunkLease,+ tiles_produced: u64,+) -> Result<(), ChunkStoreError> {+ store.mark_produced_raw(lease, tiles_produced).await+}++pub async fn confirm_raw(+ store: &PgChunkStore,+ lease: ChunkLease,+ hwms: &ProduceHwms,+) -> Result<(), ChunkStoreError> {+ store.confirm_raw(lease, hwms).await+}++pub async fn fail(+ store: &PgChunkStore,+ lease: ChunkLease,+ error: &str,+) -> Result<(), ChunkStoreError> {+ store.fail(lease, &RenderedError::from_message(error)).await+}++pub async fn unclaim(store: &PgChunkStore, lease: ChunkLease) -> Result<(), ChunkStoreError> {+ store.unclaim(lease).await+}diff --git a/rust/cohort-seeder/tests/fixtures/cohort_backfill_0004.sql b/rust/cohort-seeder/tests/fixtures/cohort_backfill_0004.sqlnew file mode 100644index 000000000000..0a3befa1fc5f--- /dev/null+++ b/rust/cohort-seeder/tests/fixtures/cohort_backfill_0004.sql@@ -0,0 +1,73 @@+-- Snapshot pinned to products/cohorts/backend/migrations/0004_cohort_backfill_tables.py.+-- External Team/Cohort foreign keys are omitted so the contract test stays schema-local.++CREATE TABLE cohort_backfill_runs (+ id uuid PRIMARY KEY,+ created_by_id bigint,+ backfill_kind varchar(32) NOT NULL DEFAULT 'behavioral',+ trigger_kind varchar(32) NOT NULL,+ scope varchar(16) NOT NULL,+ status varchar(32) NOT NULL DEFAULT 'awaiting_boundary',+ timezone varchar(240) NOT NULL,+ boundary_at timestamptz,+ boundary_established_at timestamptz,+ pinned jsonb NOT NULL DEFAULT '{}'::jsonb,+ preconditions jsonb NOT NULL DEFAULT '{}'::jsonb,+ reconcile_hwms jsonb,+ blocked_reason text NOT NULL DEFAULT '',+ error text NOT NULL DEFAULT '',+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ finished_at timestamptz,+ cohort_id integer,+ superseded_by_id uuid REFERENCES cohort_backfill_runs(id),+ team_id integer NOT NULL+);++CREATE INDEX cohort_bfr_team_status_idx ON cohort_backfill_runs(team_id, status);+CREATE INDEX cohort_bfr_team_created_idx ON cohort_backfill_runs(team_id, created_at DESC);+CREATE UNIQUE INDEX cohort_bfr_active_cohort_uq+ ON cohort_backfill_runs(cohort_id)+ WHERE cohort_id IS NOT NULL+ AND status IN ('awaiting_boundary', 'blocked', 'seeding', 'reconciling');+CREATE UNIQUE INDEX cohort_bfr_active_team_uq+ ON cohort_backfill_runs(team_id)+ WHERE scope = 'team'+ AND status IN ('awaiting_boundary', 'blocked', 'seeding', 'reconciling');++CREATE TABLE cohort_backfill_chunks (+ id uuid PRIMARY KEY,+ day date NOT NULL,+ band smallint NOT NULL DEFAULT 0,+ status varchar(16) NOT NULL DEFAULT 'pending',+ claim_epoch integer NOT NULL DEFAULT 0,+ claimed_by varchar(255) NOT NULL DEFAULT '',+ claimed_at timestamptz,+ lease_expires_at timestamptz,+ s_chunk_at timestamptz,+ attempts integer NOT NULL DEFAULT 0,+ last_error text NOT NULL DEFAULT '',+ tiles_produced bigint NOT NULL DEFAULT 0,+ produce_hwms jsonb,+ confirmed_at timestamptz,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ team_id integer NOT NULL,+ run_id uuid NOT NULL REFERENCES cohort_backfill_runs(id),+ CONSTRAINT cohort_bfc_run_day_band_uq UNIQUE (run_id, day, band)+);++CREATE INDEX cohort_bfc_run_status_day_idx ON cohort_backfill_chunks(run_id, status, day);++CREATE TABLE cohort_backfill_run_cohorts (+ id uuid PRIMARY KEY,+ filters_shape_hash varchar(64) NOT NULL,+ pinned_filters jsonb NOT NULL,+ stamped_at timestamptz,+ superseded_at timestamptz,+ error text NOT NULL DEFAULT '',+ cohort_id integer NOT NULL,+ run_id uuid NOT NULL REFERENCES cohort_backfill_runs(id),+ team_id integer NOT NULL,+ CONSTRAINT cohort_bfrc_run_cohort_uq UNIQUE (run_id, cohort_id)+);diff --git a/rust/cohort-seeder/tests/pg_chunks.rs b/rust/cohort-seeder/tests/pg_chunks.rsnew file mode 100644index 000000000000..b3c75ad4f861--- /dev/null+++ b/rust/cohort-seeder/tests/pg_chunks.rs@@ -0,0 +1,718 @@+//! PostgreSQL contract for the seeder store, split into independent scenarios.+//!+//! Each `#[tokio::test]` connects its own schema-scoped database ([`support::with_db`]) and builds+//! only the minimal run/chunk state its invariant needs; setup duplication across scenarios is+//! deliberate and keeps them parallel-safe. Together they cover the same claim/lease/epoch-fence/CAS+//! guarantees the former single `exercise_contract` did — every assertion preserved, redistributed.++#![cfg(feature = "pg-test-support")]++use std::num::NonZeroU16;+use std::time::Duration;++use anyhow::{bail, ensure, Context, Result};+use cohort_core::filters::CohortId;+use cohort_seeder::domain::{ClaimEpoch, PinnedWarning, ProduceHwms};+use cohort_seeder::store::chunks::{ChunkStoreError, PgChunkStore, PlanOutcome};+use cohort_seeder::store::lease::LeaseFailure;+use cohort_seeder::store::runs::{+ discover_runs, establish_boundary, fail_run, record_run_warning, BoundaryOutcome, RunError,+ RunStatus, RunWarningNote,+};+use cohort_seeder::store::{Claimant, LeaseDuration, MaxAttempts, RenderedError};+use cohort_seeder::test_support;+use common_types::cohort::TeamAllowlist;+use serde_json::json;++mod support;+use support::{+ behavioral_filter, empty_pinned, ensure_lease_lost, insert_participation, insert_run,+ pinned_condition, planned_count, with_db, ACTIVE_HASH, SUPERSEDED_HASH,+};++const ONE_BAND: NonZeroU16 = NonZeroU16::MIN;++/// Discovery honors an `Only` allowlist (self team only) and `All` admits every eligible run+/// regardless of team, trigger, or already-seeding status.+#[tokio::test]+async fn discovery_scopes_to_the_allowlist_and_all_admits_every_run() -> Result<()> {+ with_db(|pool| async move {+ let self_run = insert_run(+ &pool,+ 2,+ "team_enablement",+ "awaiting_boundary",+ false,+ empty_pinned(),+ )+ .await?;+ let other_team_run = insert_run(+ &pool,+ 3,+ "team_enablement",+ "awaiting_boundary",+ false,+ empty_pinned(),+ )+ .await?;+ let dr_run = insert_run(+ &pool,+ 4,+ "disaster_recovery",+ "awaiting_boundary",+ false,+ empty_pinned(),+ )+ .await?;+ let cross_team_run =+ insert_run(&pool, 5, "team_enablement", "seeding", true, empty_pinned()).await?;++ let only_team_two: TeamAllowlist = "2".parse().map_err(anyhow::Error::msg)?;+ let discovered = discover_runs(&pool, &only_team_two).await?;+ ensure!(discovered.len() == 1);+ ensure!(discovered[0].run_id == self_run);++ let all_runs = discover_runs(&pool, &TeamAllowlist::All).await?;+ ensure!(all_runs.iter().any(|run| run.run_id == self_run));+ ensure!(all_runs.iter().any(|run| run.run_id == other_team_run));+ ensure!(all_runs.iter().any(|run| run.run_id == cross_team_run));+ ensure!(all_runs.iter().any(|run| run.run_id == dr_run));+ Ok(())+ })+ .await+}++/// Two racing `establish_boundary` calls on the same awaiting-boundary run: the CAS admits exactly+/// one `Established`, and the loser re-reads the now-seeding row as `AlreadyEstablished`.+#[tokio::test]+async fn concurrent_boundary_establishment_promotes_exactly_one_run() -> Result<()> {+ with_db(|pool| async move {+ insert_run(+ &pool,+ 2,+ "team_enablement",+ "awaiting_boundary",+ false,+ empty_pinned(),+ )+ .await?;++ let only_team_two: TeamAllowlist = "2".parse().map_err(anyhow::Error::msg)?;+ let discovered = discover_runs(&pool, &only_team_two).await?;+ let left = discovered[0].clone();+ let right = discovered[0].clone();+ let (left, right) = tokio::join!(+ establish_boundary(&pool, left),+ establish_boundary(&pool, right)+ );+ let outcomes = [left?, right?];++ ensure!(+ outcomes+ .iter()+ .filter(|outcome| matches!(outcome, BoundaryOutcome::Established(_)))+ .count()+ == 1+ );+ ensure!(+ outcomes+ .iter()+ .filter(|outcome| matches!(outcome, BoundaryOutcome::AlreadyEstablished(_)))+ .count()+ == 1+ );+ Ok(())+ })+ .await+}++/// Warning notes append newest-first, dedupe on repeat, truncate the `error` column to the limit,+/// and are refused once a run leaves the `seeding` state.+#[tokio::test]+async fn run_warnings_dedupe_append_truncate_and_skip_terminal_runs() -> Result<()> {+ with_db(|pool| async move {+ let seeding_run =+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;+ sqlx::query("UPDATE cohort_backfill_runs SET error = repeat('x', 5000) WHERE id = $1")+ .bind(seeding_run)+ .execute(&pool)+ .await?;++ ensure!(record_run_warning(&pool, seeding_run, RunWarningNote::ConditionsDropped).await?);+ ensure!(!record_run_warning(&pool, seeding_run, RunWarningNote::ConditionsDropped).await?);+ ensure!(record_run_warning(&pool, seeding_run, RunWarningNote::LookbackTruncated).await?);+ let run_warnings: String =+ sqlx::query_scalar("SELECT error FROM cohort_backfill_runs WHERE id = $1")+ .bind(seeding_run)+ .fetch_one(&pool)+ .await?;+ ensure!(run_warnings.len() == 4_096);+ ensure!(+ run_warnings+ .matches(RunWarningNote::ConditionsDropped.as_str())+ .count()+ == 1+ );+ ensure!(+ run_warnings+ .matches(RunWarningNote::LookbackTruncated.as_str())+ .count()+ == 1+ );++ let terminal_run =+ insert_run(&pool, 3, "team_enablement", "failed", false, empty_pinned()).await?;+ ensure!(!record_run_warning(&pool, terminal_run, RunWarningNote::ConditionsDropped).await?);+ Ok(())+ })+ .await+}++/// Loading the pinned payload drops superseded conditions (keeping only the live one plus a+/// `ConditionSuperseded` warning), rejects cohorts stored under another team, and refuses a+/// disaster-recovery run whose boundary was never pinned.+#[tokio::test]+async fn load_pinned_drops_superseded_and_rejects_cross_team_and_dr() -> Result<()> {+ with_db(|pool| async move {+ let pinned = json!({+ "schema_version": 1,+ "conditions": [+ pinned_condition(10, ACTIVE_HASH, "active-event"),+ pinned_condition(11, SUPERSEDED_HASH, "superseded-event"),+ ],+ "event_names": ["active-event", "superseded-event"],+ });+ let self_run = insert_run(+ &pool,+ 2,+ "team_enablement",+ "awaiting_boundary",+ false,+ pinned,+ )+ .await?;+ insert_participation(+ &pool,+ self_run,+ 2,+ 10,+ false,+ behavioral_filter(ACTIVE_HASH, "active-event"),+ )+ .await?;+ insert_participation(+ &pool,+ self_run,+ 2,+ 11,+ true,+ behavioral_filter(SUPERSEDED_HASH, "superseded-event"),+ )+ .await?;++ let dr_run = insert_run(+ &pool,+ 4,+ "disaster_recovery",+ "awaiting_boundary",+ false,+ empty_pinned(),+ )+ .await?;+ let cross_team_run =+ insert_run(&pool, 5, "team_enablement", "seeding", true, empty_pinned()).await?;+ insert_participation(+ &pool,+ cross_team_run,+ 999,+ 50,+ true,+ json!({"properties": {"type": "AND", "values": []}}),+ )+ .await?;++ let all_runs = discover_runs(&pool, &TeamAllowlist::All).await?;+ let self_discovered = all_runs+ .iter()+ .find(|run| run.run_id == self_run)+ .cloned()+ .context("self run was not discovered")?;+ let cross_team_discovered = all_runs+ .iter()+ .find(|run| run.run_id == cross_team_run)+ .cloned()+ .context("cross-team run was not discovered")?;+ let dr_discovered = all_runs+ .into_iter()+ .find(|run| run.run_id == dr_run)+ .context("DR run was not discovered")?;++ let seedable = match establish_boundary(&pool, self_discovered).await? {+ BoundaryOutcome::Established(run) | BoundaryOutcome::AlreadyEstablished(run) => run,+ BoundaryOutcome::NoLongerSeedable { .. } => bail!("self run was not seedable"),+ };+ let validated = seedable.load_pinned(&pool).await?;+ ensure!(validated.run.conditions.len() == 1);+ ensure!(validated.run.conditions[0].cohort_id == CohortId(10));+ ensure!(+ validated+ .run+ .event_names+ .iter()+ .map(String::as_str)+ .collect::<Vec<_>>()+ == ["active-event"]+ );+ ensure!(validated+ .run+ .filters+ .behavioral_by_event_name+ .contains_key("active-event"));+ ensure!(!validated+ .run+ .filters+ .behavioral_by_event_name+ .contains_key("superseded-event"));+ ensure!(validated.warnings.iter().any(|warning| matches!(+ warning,+ PinnedWarning::ConditionSuperseded { cohort_id, .. } if *cohort_id == CohortId(11)+ )));++ // Already seeding with a boundary, so it promotes to a SeedableRun without a DB write.+ let cross_team_seedable = match establish_boundary(&pool, cross_team_discovered).await? {+ BoundaryOutcome::Established(run) | BoundaryOutcome::AlreadyEstablished(run) => run,+ BoundaryOutcome::NoLongerSeedable { .. } => bail!("cross-team run was not seedable"),+ };+ ensure!(matches!(+ cross_team_seedable.load_pinned(&pool).await,+ Err(RunError::CrossTeamParticipation {+ actual_team_id: 999,+ ..+ })+ ));+ ensure!(matches!(+ establish_boundary(&pool, dr_discovered).await,+ Err(RunError::DisasterRecoveryBoundaryMissing(id)) if id == dr_run+ ));+ Ok(())+ })+ .await+}++/// Planning a seeding run's days is idempotent (re-planning inserts nothing), stamps the run's team+/// onto every chunk, and reports `RunNotSeeding` for a run that is not seeding.+#[tokio::test]+async fn planning_is_idempotent_scopes_team_and_gates_on_seeding() -> Result<()> {+ with_db(|pool| async move {+ let seeding_run =+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;+ let store = PgChunkStore::new(pool.clone());++ ensure!(planned_count(store.plan_chunks(seeding_run, [100, 101], ONE_BAND).await?)? == 2);+ ensure!(planned_count(store.plan_chunks(seeding_run, [100, 101], ONE_BAND).await?)? == 0);+ let chunk_teams_match: bool = sqlx::query_scalar(+ "SELECT bool_and(team_id = 2) FROM cohort_backfill_chunks WHERE run_id = $1",+ )+ .bind(seeding_run)+ .fetch_one(&pool)+ .await?;+ ensure!(chunk_teams_match);++ let idle_run = insert_run(+ &pool,+ 3,+ "team_enablement",+ "awaiting_boundary",+ false,+ empty_pinned(),+ )+ .await?;+ ensure!(matches!(+ store.plan_chunks(idle_run, [200], ONE_BAND).await?,+ PlanOutcome::RunNotSeeding+ ));+ Ok(())+ })+ .await+}++/// A multi-band plan fans a day into one chunk per band (idempotently), and a claim decodes the+/// band with the day's full band count so the scan predicate partitions persons correctly.+#[tokio::test]+async fn planning_fans_out_bands_and_claims_carry_the_band_count() -> Result<()> {+ with_db(|pool| async move {+ let seeding_run =+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;+ let store = PgChunkStore::new(pool.clone());+ let four_bands = NonZeroU16::new(4).context("four is non-zero")?;+ ensure!(planned_count(store.plan_chunks(seeding_run, [100], four_bands).await?)? == 4);+ ensure!(planned_count(store.plan_chunks(seeding_run, [100], four_bands).await?)? == 0);++ let lease60 = LeaseDuration::new(Duration::from_secs(60))?;+ let attempts5 = MaxAttempts::new(5)?;+ let claimed = store+ .claim_next(+ &[seeding_run],+ &Claimant::new("worker-a")?,+ lease60,+ attempts5,+ )+ .await?+ .context("claimant found no chunk")?;+ let band = claimed.chunk.spec().band;+ ensure!(band.num_bands().get() == 4);+ ensure!(band.band() < 4);+ drop(claimed);+ Ok(())+ })+ .await+}++/// Two racing claimants take disjoint chunks — `SKIP LOCKED` never hands the same chunk to both.+#[tokio::test]+async fn concurrent_claims_take_disjoint_chunks() -> Result<()> {+ with_db(|pool| async move {+ let seeding_run =+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;+ let store = PgChunkStore::new(pool.clone());+ ensure!(planned_count(store.plan_chunks(seeding_run, [100, 101], ONE_BAND).await?)? == 2);++ let lease60 = LeaseDuration::new(Duration::from_secs(60))?;+ let attempts5 = MaxAttempts::new(5)?;+ let run_ids = [seeding_run];+ let first_store = store.clone();+ let second_store = store.clone();+ let claimant_a = Claimant::new("worker-a")?;+ let claimant_b = Claimant::new("worker-b")?;+ let (first, second) = tokio::join!(+ first_store.claim_next(&run_ids, &claimant_a, lease60, attempts5),+ second_store.claim_next(&run_ids, &claimant_b, lease60, attempts5),+ );+ let first = first?.context("first claimant found no chunk")?;+ let second = second?.context("second claimant found no chunk")?;+ ensure!(first.chunk.spec().lease.chunk_id() != second.chunk.spec().lease.chunk_id());+ Ok(())+ })+ .await+}++/// An expired lease is reclaimed as the SAME chunk with a bumped epoch; the reclaim fences the stale+/// lease so every one of its fenced operations reports `LeaseLost`, while the fresh lease works.+#[tokio::test]+async fn expired_lease_reclaim_bumps_epoch_and_fences_the_stale_lease() -> Result<()> {+ with_db(|pool| async move {+ let seeding_run =+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;+ let store = PgChunkStore::new(pool.clone());+ ensure!(planned_count(store.plan_chunks(seeding_run, [100], ONE_BAND).await?)? == 1);++ let lease60 = LeaseDuration::new(Duration::from_secs(60))?;+ let attempts5 = MaxAttempts::new(5)?;+ let run_ids = [seeding_run];++ let first = store+ .claim_next(&run_ids, &Claimant::new("worker-a")?, lease60, attempts5)+ .await?+ .context("first claimant found no chunk")?;+ let stale = first.chunk.spec().lease;+ drop(first);+ sqlx::query(+ "UPDATE cohort_backfill_chunks SET lease_expires_at = now() - interval '1 second' WHERE id = $1",+ )+ .bind(stale.chunk_id())+ .execute(&pool)+ .await?;++ let reclaimed = store+ .claim_next(&run_ids, &Claimant::new("worker-c")?, lease60, attempts5)+ .await?+ .context("expired chunk was not reclaimed")?;+ let reclaimed_lease = reclaimed.chunk.spec().lease;+ ensure!(reclaimed_lease.chunk_id() == stale.chunk_id());+ ensure!(reclaimed_lease.epoch() == ClaimEpoch(stale.epoch().0 + 1));++ ensure_lease_lost(+ test_support::heartbeat(&store, stale, &Claimant::new("worker-a")?, lease60).await,+ )?;+ ensure_lease_lost(test_support::mark_produced_raw(&store, stale, 1).await)?;+ ensure_lease_lost(test_support::confirm_raw(&store, stale, &ProduceHwms::default()).await)?;+ ensure_lease_lost(test_support::fail(&store, stale, "stale failure").await)?;+ ensure_lease_lost(test_support::unclaim(&store, stale).await)?;++ // The fresh lease, in contrast, drives the chunk through mark-produced and confirm.+ let mut hwms = ProduceHwms::default();+ hwms.observe(3, 41);+ test_support::mark_produced_raw(&store, reclaimed_lease, 0).await?;+ test_support::confirm_raw(&store, reclaimed_lease, &hwms).await?;+ drop(reclaimed);+ Ok(())+ })+ .await+}++/// Unclaiming a scanning chunk returns it to `pending` and refunds the attempt the claim charged.+#[tokio::test]+async fn unclaim_returns_chunk_to_pending_and_refunds_one_attempt() -> Result<()> {+ with_db(|pool| async move {+ let seeding_run =+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;+ let store = PgChunkStore::new(pool.clone());+ ensure!(planned_count(store.plan_chunks(seeding_run, [100], ONE_BAND).await?)? == 1);++ let lease60 = LeaseDuration::new(Duration::from_secs(60))?;+ let attempts5 = MaxAttempts::new(5)?;+ let run_ids = [seeding_run];++ let claimed = store+ .claim_next(&run_ids, &Claimant::new("worker-a")?, lease60, attempts5)+ .await?+ .context("claimant found no chunk")?;+ let lease = claimed.chunk.spec().lease;+ let chunk_id = lease.chunk_id();+ sqlx::query("UPDATE cohort_backfill_chunks SET attempts = 5 WHERE id = $1")+ .bind(chunk_id)+ .execute(&pool)+ .await?;+ store.unclaim(lease).await?;+ drop(claimed);++ let (pending_status, refunded_attempts): (String, i32) =+ sqlx::query_as("SELECT status, attempts FROM cohort_backfill_chunks WHERE id = $1")+ .bind(chunk_id)+ .fetch_one(&pool)+ .await?;+ ensure!(pending_status == "pending");+ ensure!(refunded_attempts == 4);+ Ok(())+ })+ .await+}++/// The attempt cap is terminal for a `failed` chunk (no further claim), but an expired `produced`+/// chunk sitting AT the cap is still reclaimed with a bumped epoch — its tiles are already in+/// Kafka, so it must keep retrying until it reaches `confirmed`. Only `scanning` reclaims are+/// capped (see `expired_scanning_chunk_at_the_cap_is_reaped_not_reclaimed`).+#[tokio::test]+async fn attempt_cap_is_terminal_for_failed_but_reclaims_expired_produced() -> Result<()> {+ with_db(|pool| async move {+ let seeding_run =+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;+ let store = PgChunkStore::new(pool.clone());+ let lease60 = LeaseDuration::new(Duration::from_secs(60))?;+ let attempts5 = MaxAttempts::new(5)?;+ let run_ids = [seeding_run];++ // A chunk driven to the attempt cap by claiming, then failed, is not claimable again.+ ensure!(planned_count(store.plan_chunks(seeding_run, [100], ONE_BAND).await?)? == 1);+ sqlx::query("UPDATE cohort_backfill_chunks SET attempts = 4 WHERE run_id = $1")+ .bind(seeding_run)+ .execute(&pool)+ .await?;+ let retry = store+ .claim_next(&run_ids, &Claimant::new("worker-d")?, lease60, attempts5)+ .await?+ .context("chunk under the cap was not claimable")?;+ let retry_lease = retry.chunk.spec().lease;+ let reclaimed_attempts: i32 =+ sqlx::query_scalar("SELECT attempts FROM cohort_backfill_chunks WHERE id = $1")+ .bind(retry_lease.chunk_id())+ .fetch_one(&pool)+ .await?;+ ensure!(reclaimed_attempts == 5);+ store+ .fail(retry_lease, &RenderedError::from_message("terminal"))+ .await?;+ drop(retry);+ ensure!(store+ .claim_next(&run_ids, &Claimant::new("worker-terminal")?, lease60, attempts5)+ .await?+ .is_none());++ // A second chunk, marked produced then expired at the cap, IS reclaimed.+ ensure!(planned_count(store.plan_chunks(seeding_run, [101], ONE_BAND).await?)? == 1);+ let final_attempt = store+ .claim_next(&run_ids, &Claimant::new("worker-e")?, lease60, attempts5)+ .await?+ .context("second chunk was not claimable")?;+ let final_attempt_lease = final_attempt.chunk.spec().lease;+ test_support::mark_produced_raw(&store, final_attempt_lease, 1).await?;+ drop(final_attempt);+ sqlx::query(+ "UPDATE cohort_backfill_chunks SET attempts = 5, lease_expires_at = now() - interval '1 second' WHERE id = $1",+ )+ .bind(final_attempt_lease.chunk_id())+ .execute(&pool)+ .await?;++ let observed = store+ .claim_next(&run_ids, &Claimant::new("worker-f")?, lease60, attempts5)+ .await?+ .context("expired produced chunk at the attempt cap was not reclaimed")?;+ let observed_lease = observed.chunk.spec().lease;+ ensure!(observed_lease.chunk_id() == final_attempt_lease.chunk_id());+ ensure!(observed_lease.epoch() == ClaimEpoch(final_attempt_lease.epoch().0 + 1));+ let active_reclaim_attempts: i32 =+ sqlx::query_scalar("SELECT attempts FROM cohort_backfill_chunks WHERE id = $1")+ .bind(observed_lease.chunk_id())+ .fetch_one(&pool)+ .await?;+ ensure!(active_reclaim_attempts == 5);+ Ok(())+ })+ .await+}++/// A `scanning` chunk whose lease expires below the attempt cap is left for reclaim, but once its+/// attempts saturate it is neither reclaimed (no hard-crash loop) nor left invisible: the reaper+/// dead-letters it to `failed` — the same terminal state a clean cap-out reaches — exactly once.+#[tokio::test]+async fn expired_scanning_chunk_at_the_cap_is_reaped_not_reclaimed() -> Result<()> {+ with_db(|pool| async move {+ let seeding_run =+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;+ let store = PgChunkStore::new(pool.clone());+ ensure!(planned_count(store.plan_chunks(seeding_run, [100], ONE_BAND).await?)? == 1);++ let lease60 = LeaseDuration::new(Duration::from_secs(60))?;+ let attempts5 = MaxAttempts::new(5)?;+ let run_ids = [seeding_run];+ let claimed = store+ .claim_next(&run_ids, &Claimant::new("worker-a")?, lease60, attempts5)+ .await?+ .context("claimant found no chunk")?;+ let chunk_id = claimed.chunk.spec().lease.chunk_id();+ drop(claimed);++ // Expired below the cap: not reaped — the ordinary reclaim path still owns it.+ sqlx::query(+ "UPDATE cohort_backfill_chunks SET lease_expires_at = now() - interval '1 second' WHERE id = $1",+ )+ .bind(chunk_id)+ .execute(&pool)+ .await?;+ ensure!(store.reap_poisoned_chunks(&run_ids, attempts5).await? == 0);++ // A hard-crashed worker's residue: still `scanning`, attempts saturated, lease expired.+ sqlx::query("UPDATE cohort_backfill_chunks SET attempts = 5 WHERE id = $1")+ .bind(chunk_id)+ .execute(&pool)+ .await?;+ ensure!(store+ .claim_next(&run_ids, &Claimant::new("worker-b")?, lease60, attempts5)+ .await?+ .is_none());++ ensure!(store.reap_poisoned_chunks(&run_ids, attempts5).await? == 1);+ let (status, last_error): (String, String) =+ sqlx::query_as("SELECT status, last_error FROM cohort_backfill_chunks WHERE id = $1")+ .bind(chunk_id)+ .fetch_one(&pool)+ .await?;+ ensure!(status == "failed");+ ensure!(last_error.contains("attempt cap"));+ // Terminal: not claimable, and a second sweep is a no-op.+ ensure!(store+ .claim_next(&run_ids, &Claimant::new("worker-c")?, lease60, attempts5)+ .await?+ .is_none());+ ensure!(store.reap_poisoned_chunks(&run_ids, attempts5).await? == 0);+ Ok(())+ })+ .await+}++/// Both persisted error columns are truncated to the limit: `chunk.fail` clamps `last_error` and+/// `fail_run` clamps `run.error`, each flipping the row to `failed`.+#[tokio::test]+async fn fail_truncates_chunk_and_run_error_columns() -> Result<()> {+ with_db(|pool| async move {+ let seeding_run =+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;+ let store = PgChunkStore::new(pool.clone());+ ensure!(planned_count(store.plan_chunks(seeding_run, [100], ONE_BAND).await?)? == 1);++ let lease60 = LeaseDuration::new(Duration::from_secs(60))?;+ let attempts5 = MaxAttempts::new(5)?;+ let run_ids = [seeding_run];+ let claimed = store+ .claim_next(&run_ids, &Claimant::new("worker-a")?, lease60, attempts5)+ .await?+ .context("claimant found no chunk")?;+ let lease = claimed.chunk.spec().lease;+ let chunk_id = lease.chunk_id();+ store+ .fail(lease, &RenderedError::from_message("x".repeat(5_000)))+ .await?;+ drop(claimed);+ let (failed_status, error_length): (String, i32) = sqlx::query_as(+ "SELECT status, length(last_error)::integer FROM cohort_backfill_chunks WHERE id = $1",+ )+ .bind(chunk_id)+ .fetch_one(&pool)+ .await?;+ ensure!(failed_status == "failed");+ ensure!(error_length == 4_096);++ let active_run = insert_run(+ &pool,+ 3,+ "team_enablement",+ "awaiting_boundary",+ false,+ empty_pinned(),+ )+ .await?;+ fail_run(+ &pool,+ active_run,+ &RenderedError::from_message("y".repeat(5_000)),+ )+ .await?;+ let (run_status, run_error_length): (String, i32) = sqlx::query_as(+ "SELECT status, length(error)::integer FROM cohort_backfill_runs WHERE id = $1",+ )+ .bind(active_run)+ .fetch_one(&pool)+ .await?;+ ensure!(run_status == RunStatus::Failed.as_str());+ ensure!(run_error_length == 4_096);+ Ok(())+ })+ .await+}++/// Cancelling a run breaks its live leases: the claimed chunk's next heartbeat fences out, so the+/// lease surfaces `Heartbeat(LeaseLost)` and its cancellation token trips.+#[tokio::test]+async fn cancelling_a_run_kills_its_live_lease_via_the_heartbeat() -> Result<()> {+ with_db(|pool| async move {+ let seeding_run =+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;+ let store = PgChunkStore::new(pool.clone());+ ensure!(planned_count(store.plan_chunks(seeding_run, [100], ONE_BAND).await?)? == 1);++ let lease3 = LeaseDuration::new(Duration::from_secs(3))?;+ let attempts5 = MaxAttempts::new(5)?;+ let run_ids = [seeding_run];+ let observed = store+ .claim_next(&run_ids, &Claimant::new("worker-f")?, lease3, attempts5)+ .await?+ .context("claimant found no chunk")?;+ let cancelled = observed.lease.cancellation_token();+ sqlx::query(+ "UPDATE cohort_backfill_runs SET status = 'cancelled', updated_at = now() WHERE id = $1",+ )+ .bind(seeding_run)+ .execute(&pool)+ .await?;+ let failure =+ tokio::time::timeout(Duration::from_secs(3), observed.lease.failure()).await?;+ ensure!(matches!(+ failure,+ LeaseFailure::Heartbeat(ChunkStoreError::LeaseLost { .. })+ ));+ ensure!(cancelled.is_cancelled());+ Ok(())+ })+ .await+}diff --git a/rust/cohort-seeder/tests/support/mod.rs b/rust/cohort-seeder/tests/support/mod.rsnew file mode 100644index 000000000000..ce847ef8a7cc--- /dev/null+++ b/rust/cohort-seeder/tests/support/mod.rs@@ -0,0 +1,196 @@+//! Shared harness for the PostgreSQL contract tests.+//!+//! `TestDatabase` gives every scenario its own schema (created on connect, dropped on cleanup) so the+//! split `#[tokio::test]`s run in parallel without colliding on the `cohort_backfill_*` tables.+//! [`with_db`] mirrors the original single-test wrapper: connect, run the body, clean up, then+//! surface the body's result *after* the schema drop. The `insert_*`/`*_pinned`/`*_condition`/+//! `behavioral_filter` builders and the `ensure_lease_lost`/`planned_count` helpers are the shared+//! fixtures each scenario composes the minimal state it needs from.++use std::future::Future;+use std::str::FromStr;++use anyhow::{bail, Context, Result};+use cohort_seeder::domain::RunId;+use cohort_seeder::store::chunks::{ChunkStoreError, PlanOutcome};+use serde_json::{json, Value};+use sqlx::postgres::{PgConnectOptions, PgPoolOptions};+use sqlx::types::Json;+use sqlx::{Connection, PgConnection, PgPool};+use uuid::Uuid;++/// The `cohort_backfill_*` DDL, pinned to the Django migration, applied fresh into each test schema.+pub const DDL: &str = include_str!("../fixtures/cohort_backfill_0004.sql");+/// A live cohort condition hash used by the superseded-load fixtures.+pub const ACTIVE_HASH: &str = "active0000000000";+/// A superseded cohort condition hash used by the superseded-load fixtures.+pub const SUPERSEDED_HASH: &str = "superseded000000";++/// A private schema plus a search-path-scoped pool, torn down on [`TestDatabase::cleanup`].+pub struct TestDatabase {+ admin: PgConnection,+ pool: PgPool,+ schema: String,+}++impl TestDatabase {+ pub async fn connect(database_url: &str) -> Result<Self> {+ let options = PgConnectOptions::from_str(database_url)?;+ let mut admin = PgConnection::connect_with(&options).await?;+ let schema = format!("cohort_seeder_{}", Uuid::new_v4().simple());+ sqlx::query(&format!("CREATE SCHEMA {schema}"))+ .execute(&mut admin)+ .await?;++ let search_path = format!("SET search_path TO {schema}, public");+ let pool = PgPoolOptions::new()+ .max_connections(4)+ .after_connect(move |connection, _| {+ let search_path = search_path.clone();+ Box::pin(async move {+ sqlx::query(&search_path).execute(&mut *connection).await?;+ Ok(())+ })+ })+ .connect_with(options)+ .await?;+ sqlx::raw_sql(DDL).execute(&pool).await?;+ Ok(Self {+ admin,+ pool,+ schema,+ })+ }++ pub async fn cleanup(mut self) -> Result<()> {+ self.pool.close().await;+ sqlx::query(&format!("DROP SCHEMA {} CASCADE", self.schema))+ .execute(&mut self.admin)+ .await?;+ self.admin.close().await?;+ Ok(())+ }+}++/// Connect a fresh schema-scoped database, run `body` against its pool, then drop the schema. The+/// body's result is surfaced only after cleanup so a failing assertion never leaks a schema.+pub async fn with_db<F, Fut>(body: F) -> Result<()>+where+ F: FnOnce(PgPool) -> Fut,+ Fut: Future<Output = Result<()>>,+{+ let database_url = std::env::var("DATABASE_URL")+ .context("DATABASE_URL is required when pg-test-support is enabled")?;+ let database = TestDatabase::connect(&database_url).await?;+ let result = body(database.pool.clone()).await;+ let cleanup = database.cleanup().await;+ result?;+ cleanup+}++/// Assert a lease-fenced store op reported [`ChunkStoreError::LeaseLost`] rather than any other error.+pub fn ensure_lease_lost(result: std::result::Result<(), ChunkStoreError>) -> Result<()> {+ if matches!(result, Err(ChunkStoreError::LeaseLost { .. })) {+ return Ok(());+ }+ bail!("expected LeaseLost, got {result:?}")+}++/// Unwrap the inserted-chunk count, failing if the run was unexpectedly not seeding.+pub fn planned_count(outcome: PlanOutcome) -> Result<u64> {+ match outcome {+ PlanOutcome::Planned { inserted } => Ok(inserted),+ PlanOutcome::RunNotSeeding => bail!("run was unexpectedly not seeding"),+ }+}++pub async fn insert_run(+ pool: &PgPool,+ team_id: i32,+ trigger_kind: &str,+ status: &str,+ with_boundary: bool,+ pinned: Value,+) -> Result<RunId> {+ let run_id = RunId(Uuid::now_v7());+ sqlx::query(+ r#"+ INSERT INTO cohort_backfill_runs+ (id, team_id, backfill_kind, trigger_kind, scope, status, timezone, boundary_at,+ pinned, preconditions, created_at, updated_at)+ VALUES ($1, $2, 'behavioral', $3, 'team', $4, 'UTC',+ CASE WHEN $5 THEN now() ELSE NULL END,+ $6, '{}'::jsonb, now(), now())+ "#,+ )+ .bind(run_id)+ .bind(team_id)+ .bind(trigger_kind)+ .bind(status)+ .bind(with_boundary)+ .bind(Json(pinned))+ .execute(pool)+ .await?;+ Ok(run_id)+}++pub async fn insert_participation(+ pool: &PgPool,+ run_id: RunId,+ team_id: i32,+ cohort_id: i32,+ superseded: bool,+ filters: Value,+) -> Result<()> {+ sqlx::query(+ r#"+ INSERT INTO cohort_backfill_run_cohorts+ (id, run_id, team_id, cohort_id, filters_shape_hash, pinned_filters, superseded_at)+ VALUES ($1, $2, $3, $4, 'shape', $5, CASE WHEN $6 THEN now() ELSE NULL END)+ "#,+ )+ .bind(Uuid::now_v7())+ .bind(run_id)+ .bind(team_id)+ .bind(cohort_id)+ .bind(Json(filters))+ .bind(superseded)+ .execute(pool)+ .await?;+ Ok(())+}++pub fn empty_pinned() -> Value {+ json!({"schema_version": 1, "conditions": [], "event_names": []})+}++pub fn pinned_condition(cohort_id: i32, hash: &str, event_name: &str) -> Value {+ json!({+ "cohort_id": cohort_id,+ "condition_hash": hash,+ "value": "performed_event",+ "time_value": 7,+ "time_interval": "day",+ "explicit_datetime": null,+ "explicit_datetime_to": null,+ "operator": null,+ "operator_value": null,+ "window_days": 7,+ "event_name": event_name,+ "is_action": false,+ })+}++pub fn behavioral_filter(hash: &str, event_name: &str) -> Value {+ json!({+ "properties": {"type": "AND", "values": [{+ "type": "behavioral",+ "value": "performed_event",+ "key": event_name,+ "conditionHash": hash,+ "time_value": 7,+ "time_interval": "day",+ "bytecode": ["_H", 1, 32, event_name, 32, "event", 1, 1, 11],+ }]}+ })+}