Skip to content

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

feat(cohorts): person-prop run execution (#75201)

Matheus Batista366c5aaf2c03
diff --git a/rust/cohort-core/src/filters/mod.rs b/rust/cohort-core/src/filters/mod.rs
index f299cfb735c2..b9e1bb6bfdbd 100644
--- a/rust/cohort-core/src/filters/mod.rs
+++ b/rust/cohort-core/src/filters/mod.rs
@@ -10,7 +10,7 @@ use thiserror::Error;
pub use catalog::{FilterCatalog, Generation};
pub use leaf_classifier::{classify_leaf, LeafClass, LeafDropReason};
pub use loader::{build_catalog_from_rows, load_realtime_cohorts, CohortRow, REALTIME_COHORTS_SQL};
-pub use reverse_index::{TeamFilters, TeamFiltersBuilder};
+pub use reverse_index::{LeafStateMeta, TeamFilters, TeamFiltersBuilder};
pub use tree::{
parse_cohort_tree, BehavioralLeafConfig, BehavioralValue, BoolOp, CohortLeaf,
CohortRefLeafConfig, CohortTree, FilterNode, LeafSink, PersonLeafConfig,
diff --git a/rust/cohort-core/src/hogvm/globals.rs b/rust/cohort-core/src/hogvm/globals.rs
index e59172e9d891..0cb1690c6f1c 100644
--- a/rust/cohort-core/src/hogvm/globals.rs
+++ b/rust/cohort-core/src/hogvm/globals.rs
@@ -3,8 +3,10 @@
use chrono::{DateTime, NaiveDateTime};
use metrics::counter;
use serde_json::{json, Value};
+use uuid::Uuid;
use crate::events::CohortStreamEvent;
+use crate::filters::TeamId;
use crate::metrics::STAGE1_GLOBALS_PARSE_ERROR;
/// A malformed `properties`/`person_properties` JSON payload.
@@ -61,22 +63,56 @@ pub fn build_behavioral_globals(event: &CohortStreamEvent) -> Result<Value, Glob
pub fn build_person_property_globals(event: &CohortStreamEvent) -> Result<Value, GlobalsError> {
let person_properties =
parse_optional_json(event.person_properties.as_deref(), "person_properties")?;
+ Ok(person_scope_globals(
+ event.team_id,
+ event.person_id.as_str(),
+ person_properties,
+ ))
+}
- Ok(json!({
- "person": { "id": event.person_id.as_str(), "properties": person_properties },
- "project": { "id": event.team_id },
- }))
+/// Globals for a persons-table scan row — no event exists, only the person's latest properties.
+/// Funnels through the same shape core as [`build_person_property_globals`], so the seeder's
+/// person-property evaluation is byte-identical to the live event path's.
+pub fn build_person_scan_globals(
+ team_id: TeamId,
+ person_id: Uuid,
+ properties: &str,
+) -> Result<Value, GlobalsError> {
+ // Quiet parse: a seeder scan failure must not increment the stream processor's Stage 1
+ // counter — the seeder meters its own skipped rows.
+ let person_properties = parse_optional_json_quiet(Some(properties), "person_properties")?;
+ Ok(person_scope_globals(
+ team_id.0,
+ &person_id.to_string(),
+ person_properties,
+ ))
+}
+
+/// The one constructor of the `{"person":{"id","properties"},"project":{"id"}}` shape.
+fn person_scope_globals(team_id: i32, person_id: &str, person_properties: Value) -> Value {
+ json!({
+ "person": { "id": person_id, "properties": person_properties },
+ "project": { "id": team_id },
+ })
}
-/// Parse a raw JSON payload, treating `None` or empty string as `{}`.
+/// Parse a raw JSON payload, treating `None` or empty string as `{}`, counting failures on the
+/// Stage 1 metric — the live event paths' behavior.
fn parse_optional_json(raw: Option<&str>, field: &'static str) -> Result<Value, GlobalsError> {
+ parse_optional_json_quiet(raw, field).inspect_err(|_| {
+ counter!(STAGE1_GLOBALS_PARSE_ERROR, "field" => field).increment(1);
+ })
+}
+
+/// The metric-free parse core, for callers that meter failures themselves.
+fn parse_optional_json_quiet(
+ raw: Option<&str>,
+ field: &'static str,
+) -> Result<Value, GlobalsError> {
let Some(raw) = raw.filter(|s| !s.is_empty()) else {
return Ok(json!({}));
};
- serde_json::from_str(raw).map_err(|source| {
- counter!(STAGE1_GLOBALS_PARSE_ERROR, "field" => field).increment(1);
- GlobalsError { field, source }
- })
+ serde_json::from_str(raw).map_err(|source| GlobalsError { field, source })
}
/// `event.elements_chain ?? properties['$elements_chain'] ?? null`
@@ -237,6 +273,30 @@ mod tests {
assert_eq!(globals["person"]["properties"], json!({}));
}
+ /// Shape lock: the scan builder and the live event builder must produce byte-equal globals for
+ /// equal inputs — the correctness anchor that keeps seeder evals equivalent to live evals.
+ #[test]
+ fn scan_globals_are_byte_equal_to_event_globals_for_equal_inputs() {
+ let person_id = Uuid::parse_str("01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee").unwrap();
+ for properties in [r#"{"email":"[email protected]","plan":"paid"}"#, "", "{}"] {
+ let mut e = event();
+ e.team_id = 42;
+ e.person_id = person_id.to_string();
+ e.person_properties = Some(properties.to_string());
+ let from_event = build_person_property_globals(&e).unwrap();
+ let from_scan = build_person_scan_globals(TeamId(42), person_id, properties).unwrap();
+ assert_eq!(
+ serde_json::to_string(&from_scan).unwrap(),
+ serde_json::to_string(&from_event).unwrap(),
+ );
+ }
+ assert_eq!(
+ build_person_scan_globals(TeamId(42), person_id, "").unwrap()["person"]["properties"],
+ json!({})
+ );
+ assert!(build_person_scan_globals(TeamId(42), person_id, "{not json").is_err());
+ }
+
#[test]
fn malformed_properties_is_an_error() {
let mut e = event();
diff --git a/rust/cohort-core/src/hogvm/mod.rs b/rust/cohort-core/src/hogvm/mod.rs
index 7e9acb16f19d..c3938e4d95de 100644
--- a/rust/cohort-core/src/hogvm/mod.rs
+++ b/rust/cohort-core/src/hogvm/mod.rs
@@ -16,4 +16,7 @@ mod globals;
pub use executor::{
classify_vm_error, evaluate_detailed, CohortEvaluator, EvalOutcome, VmErrorClass,
};
-pub use globals::{build_behavioral_globals, build_person_property_globals, GlobalsError};
+pub use globals::{
+ build_behavioral_globals, build_person_property_globals, build_person_scan_globals,
+ GlobalsError,
+};
diff --git a/rust/cohort-seeder/src/app/deliver.rs b/rust/cohort-seeder/src/app/deliver.rs
index fd6dc6f534ed..37f1ae4f2e27 100644
--- a/rust/cohort-seeder/src/app/deliver.rs
+++ b/rust/cohort-seeder/src/app/deliver.rs
@@ -18,7 +18,7 @@ use crate::domain::{CancelCause, EnqueuedChunk, Halted, ProduceHwms, ProducedChu
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,
+ PRODUCE_ACK_SECONDS, TILE_PRODUCE_ERRORS, TILE_PRODUCE_QUEUE_FULL,
};
use crate::store::chunks::ChunkStoreError;
@@ -34,6 +34,68 @@ pub(super) struct InFlight {
hwms: ProduceHwms,
}
+impl InFlight {
+ pub(super) fn new(max_inflight: usize) -> Self {
+ Self {
+ pending: VecDeque::with_capacity(max_inflight),
+ hwms: ProduceHwms::default(),
+ }
+ }
+}
+
+/// The per-message enqueue step both produce paths share: pacer waited exactly once per message
+/// (never re-waited in the queue-full loop), backoff reset per message with the queue-full counter
+/// emitted before each backoff wait, then pop-then-observe at the in-flight `>=` bound.
+pub(super) async fn enqueue_one(
+ enqueue: impl Fn() -> Result<DeliveryFuture, EnqueueError>,
+ inflight: &mut InFlight,
+ pacer: &TilePacer,
+ settings: ProducerSettings,
+ lease_cancel: &CancellationToken,
+ shutdown: &CancellationToken,
+) -> Result<(), ProduceStop> {
+ wait_for_pacer(pacer, shutdown, lease_cancel)
+ .await
+ .map_err(ProduceStop::Cancelled)?;
+ let mut backoff = settings.queue_full_backoff;
+ loop {
+ match enqueue() {
+ Ok(delivery) => {
+ inflight.pending.push_back(PendingDelivery {
+ delivery,
+ sent_at: Instant::now(),
+ });
+ break;
+ }
+ Err(EnqueueError::QueueFull) => {
+ counter!(TILE_PRODUCE_QUEUE_FULL).increment(1);
+ wait_for_backoff(backoff, shutdown, lease_cancel)
+ .await
+ .map_err(ProduceStop::Cancelled)?;
+ backoff = next_queue_full_backoff(backoff);
+ }
+ Err(EnqueueError::Fatal(error)) => {
+ counter!(TILE_PRODUCE_ERRORS).increment(1);
+ return Err(ProduceStop::Failed(ProduceError::Enqueue(error)));
+ }
+ }
+ }
+
+ if inflight.pending.len() >= settings.max_inflight.get() {
+ let delivery = inflight
+ .pending
+ .pop_front()
+ .expect("the in-flight bound guarantees one delivery");
+ if let Err(stop) =
+ observe_delivery_before_mark(delivery, &mut inflight.hwms, shutdown, lease_cancel).await
+ {
+ counter!(TILE_PRODUCE_ERRORS).increment(1);
+ return Err(stop);
+ }
+ }
+ Ok(())
+}
+
/// 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.
@@ -45,55 +107,26 @@ pub(super) async fn enqueue_tiles(
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();
-
+ let mut inflight = InFlight::new(settings.max_inflight.get());
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));
- }
+ if let Err(stop) = enqueue_one(
+ || producer.enqueue(tile),
+ &mut inflight,
+ pacer,
+ settings,
+ lease_cancel,
+ shutdown,
+ )
+ .await
+ {
+ return Err(stop.into_halted(chunk));
}
}
-
- Ok((chunk, InFlight { pending, hwms }))
+ Ok((chunk, inflight))
}
-/// 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.
+/// Phase two (post-mark): drain the remaining acks into the HWMs and fold them onto the marked
+/// chunk. A delivery failure hands the [`EnqueuedChunk`] back for fail-on-retry.
pub(super) async fn await_deliveries(
enqueued: EnqueuedChunk,
inflight: InFlight,
@@ -111,9 +144,7 @@ pub(super) async fn await_deliveries(
}
}
- let produced = enqueued.into_produced(hwms);
- counter!(TILES_PRODUCED).increment(produced.tiles_produced());
- Ok(produced)
+ Ok(enqueued.into_produced(hwms))
}
struct PendingDelivery {
@@ -121,14 +152,14 @@ struct PendingDelivery {
sent_at: Instant,
}
-/// A stop signal from awaiting one delivery: a cancellation cause or a terminal delivery error.
-enum ProduceStop {
+/// A stop signal from one produce step: a cancellation cause or a terminal delivery error.
+pub(super) enum ProduceStop {
Cancelled(CancelCause),
Failed(ProduceError),
}
impl ProduceStop {
- fn into_halted<S>(self, state: S) -> Halted<S, ProduceError> {
+ pub(super) 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),
diff --git a/rust/cohort-seeder/src/app/execute.rs b/rust/cohort-seeder/src/app/execute.rs
index 3238f79830b0..ed5f5663681f 100644
--- a/rust/cohort-seeder/src/app/execute.rs
+++ b/rust/cohort-seeder/src/app/execute.rs
@@ -15,13 +15,14 @@ use tracing::{info, warn};
use crate::clickhouse::scanner::ChunkScanner;
use crate::domain::{
ChunkLease, ChunkSpec, ClaimedChunk, EnqueuedChunk, HaltReason, Halted, PinnedRun,
- ProducedChunk, ScannedChunk,
+ ProducedChunk, ScannedChunk, StreamedChunk,
};
use crate::kafka::pacing::TilePacer;
use crate::kafka::producer::SeedTileProducer;
-use crate::observability::metrics::{CHUNKS_CONFIRMED, CHUNKS_FAILED};
+use crate::observability::metrics::{CHUNKS_CONFIRMED, CHUNKS_FAILED, TILES_PRODUCED};
use crate::store::chunks::{ChunkStoreError, PgChunkStore};
use crate::store::lease::LeaseHandle;
+use crate::store::runs::RunKind;
use crate::store::RenderedError;
use super::deliver::{self, ProduceError};
@@ -81,7 +82,10 @@ pub(super) async fn execute_chunk(
};
// 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,
+ Ok(produced) => {
+ counter!(TILES_PRODUCED).increment(produced.tiles_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.
@@ -99,13 +103,13 @@ pub(super) async fn execute_chunk(
/// 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 {
+pub(super) enum FailureStage {
PreMark,
PostMark,
}
/// The pipeline states seen by recovery: their [`FailureStage`] and their lease-bearing spec.
-trait ChunkState {
+pub(super) trait ChunkState {
const STAGE: FailureStage;
fn spec(&self) -> ChunkSpec;
}
@@ -124,6 +128,15 @@ impl ChunkState for ScannedChunk {
}
}
+/// Pre-mark like [`ScannedChunk`]: a pre-mark unclaim with already-enqueued seeds keeps the same
+/// at-least-once semantics — the consumer's LWW/idempotent apply absorbs the re-scan.
+impl ChunkState for StreamedChunk {
+ const STAGE: FailureStage = FailureStage::PreMark;
+ fn spec(&self) -> ChunkSpec {
+ self.spec()
+ }
+}
+
impl ChunkState for EnqueuedChunk {
const STAGE: FailureStage = FailureStage::PostMark;
fn spec(&self) -> ChunkSpec {
@@ -159,7 +172,7 @@ impl FailureDisposition {
/// 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>(
+pub(super) async fn resolve_halt<S: ChunkState, E: std::error::Error>(
store: &PgChunkStore,
halt: Halted<S, E>,
shutdown: &CancellationToken,
@@ -191,9 +204,7 @@ async fn resolve_halt<S: ChunkState, E: std::error::Error>(
/// 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> {
+pub(super) fn mark_produced_halt<S>(halt: Halted<S, ChunkStoreError>) -> Halted<S, ProduceError> {
let Halted { state, reason } = halt;
let reason = match reason {
HaltReason::Failed(error) => HaltReason::Failed(ProduceError::MarkProduced(error)),
@@ -229,17 +240,20 @@ pub(super) enum ChunkOutcome {
},
}
-pub(super) fn record_task_result(result: Result<ChunkOutcome, tokio::task::JoinError>) {
+pub(super) fn record_task_result(
+ result: Result<ChunkOutcome, tokio::task::JoinError>,
+ kind: RunKind,
+) {
match result {
Ok(ChunkOutcome::Confirmed {
lease,
tiles_produced,
}) => {
- counter!(CHUNKS_CONFIRMED).increment(1);
+ counter!(CHUNKS_CONFIRMED, "kind" => kind.as_str()).increment(1);
info!(?lease, tiles_produced, "chunk confirmed");
}
Ok(ChunkOutcome::Failed { lease, detail }) => {
- counter!(CHUNKS_FAILED).increment(1);
+ counter!(CHUNKS_FAILED, "kind" => kind.as_str()).increment(1);
warn!(?lease, error = %detail, "chunk failed and was released for retry");
}
Ok(ChunkOutcome::Unclaimed { lease }) => {
@@ -250,11 +264,11 @@ pub(super) fn record_task_result(result: Result<ChunkOutcome, tokio::task::JoinE
detail,
recovery,
}) => {
- counter!(CHUNKS_FAILED).increment(1);
+ counter!(CHUNKS_FAILED, "kind" => kind.as_str()).increment(1);
warn!(?lease, error = %detail, recovery_error = %recovery, "chunk recovery update did not apply");
}
Err(error) => {
- counter!(CHUNKS_FAILED).increment(1);
+ counter!(CHUNKS_FAILED, "kind" => kind.as_str()).increment(1);
warn!(error = %error, "chunk task failed unexpectedly");
}
}
@@ -264,6 +278,18 @@ pub(super) fn record_task_result(result: Result<ChunkOutcome, tokio::task::JoinE
mod tests {
use super::*;
+ /// Which stage a state declares is the other half of the matrix, and the half the matrix test
+ /// cannot see: flipping [`StreamedChunk`] to `PostMark` would fail every person chunk caught by
+ /// a shutdown instead of unclaiming it, with the matrix test still green.
+ #[test]
+ fn chunk_states_declare_their_recovery_stage() {
+ assert_eq!(<ClaimedChunk as ChunkState>::STAGE, FailureStage::PreMark);
+ assert_eq!(<ScannedChunk as ChunkState>::STAGE, FailureStage::PreMark);
+ assert_eq!(<StreamedChunk as ChunkState>::STAGE, FailureStage::PreMark);
+ assert_eq!(<EnqueuedChunk as ChunkState>::STAGE, FailureStage::PostMark);
+ assert_eq!(<ProducedChunk as ChunkState>::STAGE, FailureStage::PostMark);
+ }
+
#[test]
fn failure_disposition_encodes_the_recovery_matrix() {
assert_eq!(
diff --git a/rust/cohort-seeder/src/app/mod.rs b/rust/cohort-seeder/src/app/mod.rs
index d37bbc50d02c..7e0554e6c43b 100644
--- a/rust/cohort-seeder/src/app/mod.rs
+++ b/rust/cohort-seeder/src/app/mod.rs
@@ -6,6 +6,8 @@ mod deliver;
mod execute;
pub mod observe;
mod orchestrator;
+mod person_execute;
+mod person_plan;
mod prepare;
pub mod reconcile_dispatch;
pub mod settings;
@@ -16,6 +18,6 @@ pub use completion::{
ObservePolicyError,
};
pub use observe::{KafkaCommittedOffsets, KafkaTopicOffsets};
-pub use orchestrator::{SeederOrchestrator, ORCHESTRATOR_LIVENESS_DEADLINE};
-pub use settings::OrchestratorSettings;
+pub use orchestrator::{PersonComponents, SeederOrchestrator, ORCHESTRATOR_LIVENESS_DEADLINE};
+pub use settings::{OrchestratorSettings, PersonSettings};
pub use watch::{MarkerWatchTask, PgMarkerFlush, WatchDirectives, MARKER_WATCH_LIVENESS_DEADLINE};
diff --git a/rust/cohort-seeder/src/app/orchestrator.rs b/rust/cohort-seeder/src/app/orchestrator.rs
index 39a9253ed47b..ab3f2a2ec6cb 100644
--- a/rust/cohort-seeder/src/app/orchestrator.rs
+++ b/rust/cohort-seeder/src/app/orchestrator.rs
@@ -1,10 +1,10 @@
//! 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`.
+//! Depends on `store`, `clickhouse`, `kafka`, `domain`, and its `app` siblings (`prepare`,
+//! `execute`, `person_execute`, `person_plan`, `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 std::time::{Duration, Instant};
use common_types::cohort::TeamAllowlist;
use lifecycle::Handle;
@@ -14,21 +14,68 @@ use tokio::task::JoinSet;
use tokio_util::sync::CancellationToken;
use tracing::{info, warn};
+use crate::clickhouse::person_scanner::PersonScanner;
use crate::clickhouse::scanner::ChunkScanner;
-use crate::domain::{ClaimKind, PinnedRun, RunId};
+use crate::domain::{ClaimKind, 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::runs::RunKind;
use crate::store::Claimant;
use super::completion::CompletionDriver;
use super::execute::{execute_chunk, record_task_result, ChunkOutcome, ChunkTaskContext};
-use super::prepare::refresh_runs;
+use super::person_execute::{execute_person_chunk, PersonChunkTaskContext};
+use super::person_plan::{plan_person_run, PersonPlanAttempt, PersonPlanRequest};
+use super::prepare::{refresh_runs, run_ids_of_kind, PreparedRun, RefreshOutcome};
use super::settings::OrchestratorSettings;
const PRODUCER_FLUSH_TIMEOUT: Duration = Duration::from_secs(5);
pub const ORCHESTRATOR_LIVENESS_DEADLINE: Duration = Duration::from_secs(60);
+/// One planning scan at a time: it streams a team's whole live person-id set from ClickHouse.
+const MAX_CONCURRENT_PLANNING_SCANS: usize = 1;
+/// How long a run whose planning attempt failed sits out before this replica retries — the
+/// boundary scan is a full-table aggregation on shared ClickHouse, so a failure must not be
+/// re-issued at the poll cadence. It also keeps one perpetually failing run from monopolizing the
+/// planning slot: backed-off runs cede it to the next candidate.
+const PERSON_PLANNING_RETRY_BACKOFF: Duration = Duration::from_secs(300);
+
+/// The person path's infra clients, present only when `SEEDER_PERSON_SEEDS_ENABLED` is on. The
+/// pacer is separate from the behavioral tile pacer so the two throughputs tune independently.
+pub struct PersonComponents {
+ pub scanner: PersonScanner,
+ pub pacer: TilePacer,
+}
+
+/// The planning slot's bookkeeping: which runs a spawned task covers (keyed by task id, so a
+/// panicked task un-tracks only itself) and when each run's last attempt failed.
+#[derive(Default)]
+struct PlanningState {
+ inflight: HashMap<tokio::task::Id, RunId>,
+ failed_at: HashMap<RunId, Instant>,
+}
+
+impl PlanningState {
+ fn is_inflight(&self, run_id: RunId) -> bool {
+ self.inflight.values().any(|inflight| *inflight == run_id)
+ }
+
+ fn in_backoff(&self, run_id: RunId) -> bool {
+ self.failed_at
+ .get(&run_id)
+ .is_some_and(|failed_at| failed_at.elapsed() < PERSON_PLANNING_RETRY_BACKOFF)
+ }
+
+ /// Drop cool-downs that have run their course, bounding the failure map. Keyed on age, never on
+ /// the pass's request set: `refresh_runs` yields no requests at all when discovery errors, and
+ /// reading that as "nothing needs planning" would refund every cool-down and put a persistently
+ /// failing run straight back into the sole planning slot.
+ fn expire_backoffs(&mut self) {
+ self.failed_at
+ .retain(|_, failed_at| failed_at.elapsed() < PERSON_PLANNING_RETRY_BACKOFF);
+ }
+}
pub struct SeederOrchestrator {
pool: PgPool,
@@ -41,6 +88,7 @@ pub struct SeederOrchestrator {
handle: Handle,
claimant: Claimant,
completion_driver: Option<CompletionDriver>,
+ person: Option<PersonComponents>,
}
impl SeederOrchestrator {
@@ -55,6 +103,7 @@ impl SeederOrchestrator {
handle: Handle,
claimed_by: String,
completion_driver: Option<CompletionDriver>,
+ person: Option<PersonComponents>,
) -> Self {
let claimant =
Claimant::new(claimed_by).expect("seeder claimant is 1..=255 bytes by construction");
@@ -69,6 +118,7 @@ impl SeederOrchestrator {
handle,
claimant,
completion_driver,
+ person,
}
}
@@ -78,6 +128,9 @@ impl SeederOrchestrator {
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 person_tasks = JoinSet::new();
+ let mut planning: JoinSet<(RunId, PersonPlanAttempt)> = JoinSet::new();
+ let mut planning_state = PlanningState::default();
let mut eligible_runs = HashMap::new();
let mut reported_runs = HashSet::new();
self.handle.report_healthy();
@@ -88,21 +141,52 @@ impl SeederOrchestrator {
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;
+ record_task_result(result, RunKind::Behavioral);
+ self.fill_claim_slots(&eligible_runs, &mut tasks, &mut person_tasks, &shutdown)
+ .await;
+ self.handle.report_healthy();
+ }
+ Some(result) = person_tasks.join_next(), if !person_tasks.is_empty() => {
+ record_task_result(result, RunKind::PersonProperty);
+ self.fill_claim_slots(&eligible_runs, &mut tasks, &mut person_tasks, &shutdown)
+ .await;
+ self.handle.report_healthy();
+ }
+ Some(result) = planning.join_next_with_id(), if !planning.is_empty() => {
+ match result {
+ Ok((task_id, (run_id, attempt))) => {
+ planning_state.inflight.remove(&task_id);
+ if attempt == PersonPlanAttempt::Failed {
+ planning_state.failed_at.insert(run_id, Instant::now());
+ }
+ }
+ Err(error) => {
+ planning_state.inflight.remove(&error.id());
+ warn!(error = %error, "person planning task failed unexpectedly");
+ }
+ }
self.handle.report_healthy();
}
_ = poll.tick() => {
- eligible_runs = refresh_runs(
+ let RefreshOutcome { eligible, planning: requests } = refresh_runs(
&self.pool,
&self.store,
&self.allowlist,
+ self.settings.discovery_kinds(),
self.settings.plan_caps,
&mut reported_runs,
)
.await;
+ eligible_runs = eligible;
+ self.spawn_person_planning(
+ requests,
+ &mut planning,
+ &mut planning_state,
+ &shutdown,
+ );
self.reap_poisoned_chunks(&eligible_runs).await;
- self.fill_claim_slots(&eligible_runs, &mut tasks, &shutdown).await;
+ self.fill_claim_slots(&eligible_runs, &mut tasks, &mut person_tasks, &shutdown)
+ .await;
if let Some(driver) = &self.completion_driver {
// Dispatch work is spawned off this tick, but observation runs inline: a few
// DB reads per reconciling run, plus at most one OffsetFetch and one
@@ -116,12 +200,18 @@ impl SeederOrchestrator {
}
}
+ // The planning insert is a single statement, so aborting a planner mid-scan leaves either
+ // zero chunks or all chunks.
+ planning.shutdown().await;
info!(
- active_chunks = tasks.len(),
+ active_chunks = tasks.len() + person_tasks.len(),
"stopping claims and draining active chunks"
);
while let Some(result) = tasks.join_next().await {
- record_task_result(result);
+ record_task_result(result, RunKind::Behavioral);
+ }
+ while let Some(result) = person_tasks.join_next().await {
+ record_task_result(result, RunKind::PersonProperty);
}
let producer = self.producer.clone();
@@ -133,41 +223,95 @@ impl SeederOrchestrator {
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() {
+ fn spawn_person_planning(
+ &self,
+ requests: Vec<PersonPlanRequest>,
+ planning: &mut JoinSet<(RunId, PersonPlanAttempt)>,
+ state: &mut PlanningState,
+ shutdown: &CancellationToken,
+ ) {
+ let (Some(person), Some(person_settings)) = (&self.person, self.settings.person) else {
return;
+ };
+ state.expire_backoffs();
+ for request in requests {
+ if planning.len() >= MAX_CONCURRENT_PLANNING_SCANS || shutdown.is_cancelled() {
+ return;
+ }
+ let run_id = request.run.run_id;
+ if state.is_inflight(run_id) || state.in_backoff(run_id) {
+ continue;
+ }
+ let handle = planning.spawn(plan_person_run(
+ self.pool.clone(),
+ self.store.clone(),
+ person.scanner.clone(),
+ person_settings.persons_per_chunk,
+ request,
+ shutdown.clone(),
+ ));
+ state.inflight.insert(handle.id(), run_id);
}
- 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"
- );
+ }
+
+ /// 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, PreparedRun>) {
+ for kind in [RunKind::Behavioral, RunKind::PersonProperty] {
+ let run_ids = run_ids_of_kind(eligible_runs, kind);
+ if run_ids.is_empty() {
+ continue;
+ }
+ match self
+ .store
+ .reap_poisoned_chunks(&run_ids, self.settings.max_chunk_attempts)
+ .await
+ {
+ Ok(0) => {}
+ Ok(reaped) => {
+ counter!(CHUNKS_POISONED, "kind" => kind.as_str()).increment(reaped);
+ warn!(
+ reaped,
+ kind = kind.as_str(),
+ "dead-lettered scanning chunks whose lease expired at the attempt cap"
+ );
+ }
+ Err(error) => warn!(error = %error, "reaping poisoned chunks failed"),
}
- Err(error) => warn!(error = %error, "reaping poisoned chunks failed"),
}
}
+ /// Claim work for whichever kind still has slot capacity. The claimable run-id set is
+ /// recomputed per claim from the remaining capacity, so a person chunk can never occupy a
+ /// behavioral slot (or vice versa) — the two budgets are independent by construction.
async fn fill_claim_slots(
&self,
- eligible_runs: &HashMap<RunId, Arc<PinnedRun>>,
+ eligible_runs: &HashMap<RunId, PreparedRun>,
tasks: &mut JoinSet<ChunkOutcome>,
+ person_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() {
+ loop {
+ if eligible_runs.is_empty() || shutdown.is_cancelled() {
+ return;
+ }
+ let behavioral_room = tasks.len() < self.settings.max_concurrent_chunks.get();
+ let person_room = self.settings.person.is_some_and(|person_settings| {
+ person_tasks.len() < person_settings.max_concurrent_chunks.get()
+ });
+ let mut run_ids = Vec::with_capacity(eligible_runs.len());
+ for (run_id, prepared) in eligible_runs {
+ let admitted = match prepared {
+ PreparedRun::Behavioral(_) => behavioral_room,
+ PreparedRun::Person(_) => person_room,
+ };
+ if admitted {
+ run_ids.push(*run_id);
+ }
+ }
+ if run_ids.is_empty() {
+ return;
+ }
let claim = match self
.store
.claim_next(
@@ -187,39 +331,83 @@ impl SeederOrchestrator {
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;
+ let chunk_lease = chunk.spec().lease;
+ let Some(prepared) = eligible_runs.get(&chunk_lease.run_id()) else {
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 {
+ match prepared {
+ PreparedRun::Behavioral(run) => {
+ record_claim(kind, RunKind::Behavioral);
+ let ctx = ChunkTaskContext {
chunk,
lease,
- run,
- store,
- scanner,
- producer,
- pacer,
- producer_settings,
- },
- shutdown,
- )
- .await
- });
+ run: run.clone(),
+ store: self.store.clone(),
+ scanner: self.scanner.clone(),
+ producer: self.producer.clone(),
+ pacer: self.pacer.clone(),
+ producer_settings: self.settings.producer,
+ };
+ let shutdown = shutdown.clone();
+ tasks.spawn(async move { execute_chunk(ctx, shutdown).await });
+ }
+ PreparedRun::Person(run) => {
+ // Unreachable while the gate is off: discovery never yields person runs then.
+ let (Some(person), Some(person_settings)) =
+ (&self.person, self.settings.person)
+ else {
+ if let Err(error) = self.store.unclaim(chunk_lease).await {
+ warn!(?chunk_lease, error = %error, "person chunk claimed with the person path disabled and could not be unclaimed");
+ }
+ continue;
+ };
+ record_claim(kind, RunKind::PersonProperty);
+ let ctx = PersonChunkTaskContext {
+ chunk,
+ lease,
+ run: run.clone(),
+ store: self.store.clone(),
+ scanner: person.scanner.clone(),
+ producer: self.producer.clone(),
+ pacer: person.pacer.clone(),
+ producer_settings: self.settings.producer,
+ emit_nonmatchers: person_settings.emit_nonmatchers,
+ };
+ let shutdown = shutdown.clone();
+ person_tasks.spawn(async move { execute_person_chunk(ctx, shutdown).await });
+ }
+ }
}
}
}
+
+fn record_claim(claim_kind: ClaimKind, run_kind: RunKind) {
+ counter!(CHUNKS_CLAIMED, "kind" => run_kind.as_str()).increment(1);
+ if claim_kind == ClaimKind::Reclaim {
+ counter!(CHUNKS_RECLAIMED, "kind" => run_kind.as_str()).increment(1);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use uuid::Uuid;
+
+ use super::*;
+
+ /// A bookkeeping pass must never refund an unexpired cool-down. Pruning against the pass's
+ /// request set did: a discovery blip yields an empty set, which read as "no run needs
+ /// planning" and handed a persistently failing run the planning slot again on the next tick.
+ #[test]
+ fn expiring_backoffs_keeps_an_unexpired_cooldown() {
+ let mut state = PlanningState::default();
+ let run_id = RunId(Uuid::nil());
+ state.failed_at.insert(run_id, Instant::now());
+
+ state.expire_backoffs();
+
+ assert!(state.in_backoff(run_id));
+ }
+}
diff --git a/rust/cohort-seeder/src/app/person_execute.rs b/rust/cohort-seeder/src/app/person_execute.rs
new file mode 100644
index 000000000000..36a02878c497
--- /dev/null
+++ b/rust/cohort-seeder/src/app/person_execute.rs
@@ -0,0 +1,215 @@
+//! App layer: one person chunk's `stream-scan → eval → paced enqueue → mark → await → confirm`
+//! pipeline. Depends on `clickhouse`, `kafka`, `store`, `domain`, and its `app` siblings.
+//!
+//! The scan is interleaved, never buffered: each row is evaluated and its seed enqueued before the
+//! next row is read, so a chunk's memory stays constant. At stream end the chunk CASes
+//! `scanning`→`produced` with the emitted count, then the remaining acks drain and the terminal
+//! confirm runs — the behavioral post-mark machinery reused verbatim.
+
+use std::sync::Arc;
+
+use metrics::counter;
+use tokio_util::sync::CancellationToken;
+
+use cohort_core::hogvm::VmErrorClass;
+
+use crate::clickhouse::person_scanner::{PersonScanError, PersonScanner};
+use crate::clickhouse::person_sql::PersonScanSpec;
+use crate::domain::{
+ CancelCause, ClaimedChunk, Halted, PersonChunkSpecError, PersonEvaluator, PersonRowOutcome,
+ PersonSeedContext, PinnedPersonRun, RecordStats, StreamedChunk,
+};
+use crate::kafka::pacing::TilePacer;
+use crate::kafka::producer::SeedTileProducer;
+use crate::observability::metrics::{
+ MetricTimer, PERSONS_SCANNED, PERSON_CHUNK_SCAN_DURATION_SECONDS, PERSON_HOGVM_ERRORS,
+ PERSON_NONMATCHERS_SKIPPED, PERSON_ROWS_SKIPPED, PERSON_SEEDS_PRODUCED,
+};
+use crate::store::chunks::PgChunkStore;
+use crate::store::lease::LeaseHandle;
+
+use super::deliver::{self, InFlight, ProduceError, ProduceStop};
+use super::execute::{mark_produced_halt, resolve_halt, ChunkOutcome};
+use super::settings::ProducerSettings;
+
+/// The owned inputs to one person chunk's processing task.
+pub(super) struct PersonChunkTaskContext {
+ pub(super) chunk: ClaimedChunk,
+ pub(super) lease: LeaseHandle,
+ pub(super) run: Arc<PinnedPersonRun>,
+ pub(super) store: PgChunkStore,
+ pub(super) scanner: PersonScanner,
+ pub(super) producer: SeedTileProducer,
+ pub(super) pacer: TilePacer,
+ pub(super) producer_settings: ProducerSettings,
+ pub(super) emit_nonmatchers: bool,
+}
+
+pub(super) async fn execute_person_chunk(
+ ctx: PersonChunkTaskContext,
+ shutdown: CancellationToken,
+) -> ChunkOutcome {
+ let PersonChunkTaskContext {
+ chunk,
+ lease,
+ run,
+ store,
+ scanner,
+ producer,
+ pacer,
+ producer_settings,
+ emit_nonmatchers,
+ } = ctx;
+ let lease_cancel = lease.cancellation_token();
+
+ // PreMark: stream the range scan, evaluating and enqueueing one seed per emitted person.
+ let (streamed, inflight) = match stream_chunk(
+ chunk,
+ &run,
+ &scanner,
+ &producer,
+ &pacer,
+ producer_settings,
+ emit_nonmatchers,
+ &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_streamed(streamed).await {
+ Ok(enqueued) => enqueued,
+ Err(halt) => return resolve_halt(&store, mark_produced_halt(halt), &shutdown).await,
+ };
+ // PostMark: drain the remaining delivery acks, then the terminal confirm.
+ let produced = match deliver::await_deliveries(enqueued, inflight, &lease_cancel).await {
+ Ok(produced) => produced,
+ Err(halt) => return resolve_halt(&store, halt, &shutdown).await,
+ };
+ let lease = produced.spec().lease;
+ let seeds_produced = produced.tiles_produced();
+ match store.confirm(produced).await {
+ Ok(_) => ChunkOutcome::Confirmed {
+ lease,
+ tiles_produced: seeds_produced,
+ },
+ Err(halt) => resolve_halt(&store, halt, &shutdown).await,
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+async fn stream_chunk(
+ chunk: ClaimedChunk,
+ run: &PinnedPersonRun,
+ scanner: &PersonScanner,
+ producer: &SeedTileProducer,
+ pacer: &TilePacer,
+ settings: ProducerSettings,
+ emit_nonmatchers: bool,
+ lease_cancel: &CancellationToken,
+ shutdown: &CancellationToken,
+) -> Result<(StreamedChunk, InFlight), Halted<ClaimedChunk, PersonChunkError>> {
+ let spec = match run.chunk_spec(&chunk.spec()) {
+ Ok(spec) => spec,
+ Err(error) => return Err(Halted::failed(chunk, PersonChunkError::Spec(error))),
+ };
+ let scan_spec = PersonScanSpec::new(spec.team_id, run.scan_since, spec.range);
+ let mut cursor = match scanner.scan_rows(&scan_spec) {
+ Ok(cursor) => cursor,
+ Err(error) => return Err(Halted::failed(chunk, PersonChunkError::Scan(error))),
+ };
+ let mut evaluator =
+ PersonEvaluator::new(spec.team_id, run.conditions.clone(), emit_nonmatchers);
+ let seed_ctx = PersonSeedContext {
+ scanned_at: spec.scanned_at,
+ run_id: spec.lease.run_id(),
+ claim_epoch: spec.lease.epoch(),
+ };
+ let mut inflight = InFlight::new(settings.max_inflight.get());
+ let mut seeds_produced: u64 = 0;
+ // Started after setup so the spec/cursor early returns don't seed the histogram with
+ // near-zero samples.
+ let _timer = MetricTimer::start(PERSON_CHUNK_SCAN_DURATION_SECONDS);
+
+ loop {
+ let row = tokio::select! {
+ biased;
+ _ = shutdown.cancelled() => {
+ return Err(Halted::cancelled(chunk, CancelCause::Shutdown));
+ }
+ _ = lease_cancel.cancelled() => {
+ return Err(Halted::cancelled(chunk, CancelCause::LeaseLost));
+ }
+ row = cursor.next() => match row {
+ Ok(row) => row,
+ Err(error) => {
+ return Err(Halted::failed(chunk, PersonChunkError::Cursor(error)));
+ }
+ },
+ };
+ let Some(row) = row else {
+ break;
+ };
+ counter!(PERSONS_SCANNED).increment(1);
+ let (outcome, stats) = evaluator.evaluate_row(&row.id, &row.properties, &seed_ctx);
+ record_row_stats(stats);
+ match outcome {
+ PersonRowOutcome::Seed(seed) => {
+ if let Err(stop) = deliver::enqueue_one(
+ || producer.enqueue_person(&seed),
+ &mut inflight,
+ pacer,
+ settings,
+ lease_cancel,
+ shutdown,
+ )
+ .await
+ {
+ return Err(produce_halt(chunk, stop));
+ }
+ seeds_produced += 1;
+ counter!(PERSON_SEEDS_PRODUCED).increment(1);
+ }
+ PersonRowOutcome::NonMatcher => {
+ counter!(PERSON_NONMATCHERS_SKIPPED).increment(1);
+ }
+ PersonRowOutcome::Skipped(skip) => {
+ counter!(PERSON_ROWS_SKIPPED, "reason" => skip.as_str()).increment(1);
+ }
+ }
+ }
+
+ Ok((chunk.into_streamed(seeds_produced), inflight))
+}
+
+fn produce_halt(chunk: ClaimedChunk, stop: ProduceStop) -> Halted<ClaimedChunk, PersonChunkError> {
+ match stop {
+ ProduceStop::Cancelled(cause) => Halted::cancelled(chunk, cause),
+ ProduceStop::Failed(error) => Halted::failed(chunk, PersonChunkError::Produce(error)),
+ }
+}
+
+fn record_row_stats(stats: RecordStats) {
+ if stats.unknown_functions > 0 {
+ counter!(PERSON_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!(PERSON_HOGVM_ERRORS, "class" => class.as_str()).increment(u64::from(count));
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+enum PersonChunkError {
+ #[error("resolving the person chunk spec")]
+ Spec(#[from] PersonChunkSpecError),
+ #[error(transparent)]
+ Scan(#[from] PersonScanError),
+ #[error("streaming ClickHouse person scan cursor")]
+ Cursor(#[source] clickhouse::error::Error),
+ #[error(transparent)]
+ Produce(ProduceError),
+}
diff --git a/rust/cohort-seeder/src/app/person_plan.rs b/rust/cohort-seeder/src/app/person_plan.rs
new file mode 100644
index 000000000000..30d0d2b80e17
--- /dev/null
+++ b/rust/cohort-seeder/src/app/person_plan.rs
@@ -0,0 +1,152 @@
+//! App layer: the one-shot person planning scan, spawned off the orchestrator's poll loop so the
+//! ClickHouse boundary stream never runs inside the liveness deadline. Depends on `clickhouse`,
+//! `store`, `domain`, and its `app` siblings.
+//!
+//! Planning is claimed cluster-wide (a per-run advisory lock) before ClickHouse is touched, so R
+//! replicas never run R copies of the full-table boundary aggregation; a failed attempt reports
+//! [`PersonPlanAttempt::Failed`] so the orchestrator backs the run off instead of re-issuing the
+//! scan on the next poll tick.
+
+use std::num::NonZeroU64;
+
+use metrics::counter;
+use sqlx::PgPool;
+use tokio_util::sync::CancellationToken;
+use tracing::{info, warn};
+
+use crate::clickhouse::person_scanner::{PersonScanError, PersonScanner};
+use crate::domain::{tile_ranges, PinnedPersonRun, RunId};
+use crate::observability::metrics::{
+ MetricTimer, CHUNKS_PLANNED, PERSON_BOUNDARIES_PLANNED, PERSON_PLANNING_DURATION_SECONDS,
+ RUNS_PLANNING_STAMPED,
+};
+use crate::store::chunks::{PgChunkStore, PlanOutcome};
+use crate::store::completion::{mark_chunks_planned, PlanningStampOutcome};
+use crate::store::runs::{fail_run, RunKind};
+use crate::store::RenderedError;
+
+use std::sync::Arc;
+
+/// A person run whose chunks do not exist yet, handed from `prepare` to the orchestrator's
+/// planning slot. Coverage travels along so the planner can withhold the stamp.
+pub(super) struct PersonPlanRequest {
+ pub(super) run: Arc<PinnedPersonRun>,
+ pub(super) coverage_complete: bool,
+}
+
+/// How one planning attempt ended, for the orchestrator's backoff bookkeeping. Only `Failed`
+/// triggers a backoff — a lost claim, a shutdown, or a completed plan needs no cool-down.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(super) enum PersonPlanAttempt {
+ Done,
+ Failed,
+}
+
+/// Plan one person run: claim → boundary scan → range tiling → all-or-nothing insert → planning
+/// stamp. Failures are logged and left for a backed-off retry, except a deterministic tiling
+/// overflow, which fails the run. Returns the run id so the orchestrator can release its
+/// planning-in-flight slot.
+pub(super) async fn plan_person_run(
+ pool: PgPool,
+ store: PgChunkStore,
+ scanner: PersonScanner,
+ persons_per_chunk: NonZeroU64,
+ request: PersonPlanRequest,
+ shutdown: CancellationToken,
+) -> (RunId, PersonPlanAttempt) {
+ let run_id = request.run.run_id;
+ let claim = match store.try_claim_person_planning(run_id).await {
+ Ok(Some(claim)) => claim,
+ // Another replica is planning this run; its outcome surfaces on a later poll.
+ Ok(None) => return (run_id, PersonPlanAttempt::Done),
+ Err(error) => {
+ warn!(?run_id, error = %error, "claiming the person planning slot failed");
+ return (run_id, PersonPlanAttempt::Failed);
+ }
+ };
+ let attempt = plan_claimed_run(
+ &pool,
+ &store,
+ &scanner,
+ persons_per_chunk,
+ request,
+ &shutdown,
+ )
+ .await;
+ claim.release().await;
+ (run_id, attempt)
+}
+
+async fn plan_claimed_run(
+ pool: &PgPool,
+ store: &PgChunkStore,
+ scanner: &PersonScanner,
+ persons_per_chunk: NonZeroU64,
+ request: PersonPlanRequest,
+ shutdown: &CancellationToken,
+) -> PersonPlanAttempt {
+ let run = request.run;
+ let run_id = run.run_id;
+ // Failed attempts are exactly the durations worth watching, so the timer records every exit.
+ let timer = MetricTimer::start(PERSON_PLANNING_DURATION_SECONDS);
+
+ let boundaries = match scanner
+ .boundaries(run.team_id, run.scan_since, persons_per_chunk, shutdown)
+ .await
+ {
+ Ok(boundaries) => boundaries,
+ Err(PersonScanError::Cancelled) => return PersonPlanAttempt::Done,
+ Err(error) => {
+ warn!(?run_id, error = %error, "person boundary scan failed");
+ return PersonPlanAttempt::Failed;
+ }
+ };
+ counter!(PERSON_BOUNDARIES_PLANNED).increment(boundaries.len() as u64);
+ let ranges = match tile_ranges(&boundaries) {
+ Ok(ranges) => ranges,
+ Err(error) => {
+ // Unreachable while the boundary keeper saturates at the ceiling; deterministic, so
+ // retrying would tile the same overflow forever.
+ if let Err(failure) = fail_run(pool, run_id, &RenderedError::render(&error)).await {
+ warn!(?run_id, error = %failure, "failing over-tiled person run did not apply");
+ }
+ return PersonPlanAttempt::Done;
+ }
+ };
+ match store.plan_person_chunks(run_id, &ranges).await {
+ Ok(PlanOutcome::Planned { inserted }) => {
+ counter!(CHUNKS_PLANNED, "kind" => RunKind::PersonProperty.as_str())
+ .increment(inserted);
+ info!(
+ ?run_id,
+ chunks = inserted,
+ horizon_days = run.horizon_days,
+ elapsed_secs = timer.elapsed().as_secs_f64(),
+ "person chunks planned"
+ );
+ }
+ // Chunks already exist (a prior attempt landed them): leave the stamp to the next prepare
+ // tick, which re-derives coverage from the database instead of this attempt's snapshot.
+ Ok(PlanOutcome::AlreadyPlanned) => return PersonPlanAttempt::Done,
+ Ok(PlanOutcome::RunNotSeeding) => return PersonPlanAttempt::Done,
+ Err(error) => {
+ warn!(?run_id, error = %error, "person chunk planning failed");
+ return PersonPlanAttempt::Failed;
+ }
+ }
+
+ // Without the proof an uncovered cohort could stamp readiness on zero seeded persons.
+ if request.coverage_complete {
+ match mark_chunks_planned(pool, run_id, RunKind::PersonProperty).await {
+ Ok(PlanningStampOutcome::Stamped) => {
+ counter!(RUNS_PLANNING_STAMPED, "kind" => RunKind::PersonProperty.as_str())
+ .increment(1);
+ }
+ Ok(PlanningStampOutcome::Skipped) => {}
+ Err(error) => {
+ warn!(?run_id, error = %error, "stamping the person planning proof failed");
+ }
+ }
+ }
+ PersonPlanAttempt::Done
+}
diff --git a/rust/cohort-seeder/src/app/prepare.rs b/rust/cohort-seeder/src/app/prepare.rs
index 86b85babedea..b05f9f7bd373 100644
--- a/rust/cohort-seeder/src/app/prepare.rs
+++ b/rust/cohort-seeder/src/app/prepare.rs
@@ -1,19 +1,26 @@
//! 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.
+//! [`refresh_runs`] is the thin fold over discovered runs; [`prepare_run`] dispatches each on its
+//! kind — behavioral runs plan inline (cheap day arithmetic), person runs surface a
+//! [`PersonPlanRequest`] for the orchestrator's spawned planning slot, since their planning needs a
+//! ClickHouse scan that must not run inside the poll loop's liveness deadline. Every behavioral
+//! 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 cohort_core::filters::CohortId;
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::domain::{
+ plan_days, Lookback, PersonRunValidation, PinnedPersonRun, PinnedRun, PinnedWarning, PlanCaps,
+ RunId,
+};
use crate::observability::metrics::{
BOUNDARY_CAS_LOST, BOUNDARY_ESTABLISHED, CHUNKS_PLANNED, CONDITIONS_DROPPED,
LOOKBACK_TRUNCATED, RUNS_DISCOVERED, RUNS_PLANNING_STAMPED, RUNS_PLANNING_WITHHELD,
@@ -21,62 +28,103 @@ use crate::observability::metrics::{
TZ_FALLBACK, WINDOW_DAYS_MISMATCH,
};
use crate::store::chunks::{PgChunkStore, PlanOutcome};
-use crate::store::completion::{mark_chunks_planned, PlanningStampOutcome};
+use crate::store::completion::{mark_chunks_planned, read_planning_stamp, PlanningStampOutcome};
use crate::store::runs::{
discover_runs, establish_boundary, fail_run, record_run_warning, BoundaryOutcome,
- DiscoveredRun, RunError, RunStatus, RunWarningNote,
+ DiscoveredRun, RunError, RunKind, RunStatus, RunWarningNote, SeedableRun,
};
use crate::store::RenderedError;
+use super::person_plan::PersonPlanRequest;
+
+/// A run validated to the point of claim eligibility, by kind.
+pub(super) enum PreparedRun {
+ Behavioral(Arc<PinnedRun>),
+ Person(Arc<PinnedPersonRun>),
+}
+
+/// One refresh pass's result: the claim-eligible runs plus the person runs still needing their
+/// planning scan.
+pub(super) struct RefreshOutcome {
+ pub(super) eligible: HashMap<RunId, PreparedRun>,
+ pub(super) planning: Vec<PersonPlanRequest>,
+}
+
/// One discovered run's classification after its boundary/validate/plan pipeline.
enum PrepareOutcome {
- Eligible(Arc<PinnedRun>),
+ Eligible(PreparedRun),
WaitingBoundary,
NoChunks,
Skipped,
+ PlanningNeeded(PersonPlanRequest),
}
pub(super) async fn refresh_runs(
pool: &PgPool,
store: &PgChunkStore,
allowlist: &TeamAllowlist,
+ kinds: &[RunKind],
plan_caps: PlanCaps,
reported_runs: &mut HashSet<RunId>,
-) -> HashMap<RunId, Arc<PinnedRun>> {
- let discovered = match discover_runs(pool, allowlist).await {
+) -> RefreshOutcome {
+ let discovered = match discover_runs(pool, allowlist, kinds).await {
Ok(runs) => runs,
Err(error) => {
let run_id = error.run_id();
handle_run_error(pool, run_id, error).await;
- return HashMap::new();
+ return RefreshOutcome {
+ eligible: HashMap::new(),
+ planning: Vec::new(),
+ };
}
};
let mut eligible = HashMap::with_capacity(discovered.len());
+ let mut planning = Vec::new();
let mut seen_runs = HashSet::with_capacity(discovered.len());
let mut waiting_boundary = 0_u64;
- let mut without_chunks = 0_u64;
+ let mut without_chunks: HashMap<RunKind, u64> = HashMap::new();
for run in discovered {
seen_runs.insert(run.run_id);
+ let kind = run.kind;
match prepare_run(pool, store, plan_caps, reported_runs, run).await {
- PrepareOutcome::Eligible(pinned) => {
- eligible.insert(pinned.run_id, pinned);
+ PrepareOutcome::Eligible(prepared) => {
+ let run_id = match &prepared {
+ PreparedRun::Behavioral(run) => run.run_id,
+ PreparedRun::Person(run) => run.run_id,
+ };
+ eligible.insert(run_id, prepared);
}
PrepareOutcome::WaitingBoundary => waiting_boundary += 1,
- PrepareOutcome::NoChunks => without_chunks += 1,
+ PrepareOutcome::NoChunks => *without_chunks.entry(kind).or_default() += 1,
PrepareOutcome::Skipped => {}
+ PrepareOutcome::PlanningNeeded(request) => {
+ *without_chunks.entry(kind).or_default() += 1;
+ planning.push(request);
+ }
}
}
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"),
+ for kind in [RunKind::Behavioral, RunKind::PersonProperty] {
+ let count = without_chunks.get(&kind).copied().unwrap_or(0);
+ gauge!(RUNS_WITHOUT_CHUNKS, "kind" => kind.as_str()).set(count as f64);
+ // Split by kind too: a person run's chunk count tracks its team's person volume, on a
+ // scale unrelated to behavioral day-bands, so one series would bury the other's burn-down.
+ match store
+ .remaining_chunks(&run_ids_of_kind(&eligible, kind))
+ .await
+ {
+ Ok(remaining) => {
+ gauge!(RUN_CHUNKS_REMAINING, "kind" => kind.as_str()).set(remaining as f64);
+ }
+ Err(error) => {
+ warn!(error = %error, kind = kind.as_str(), "counting remaining chunks failed");
+ }
+ }
}
reported_runs.retain(|run_id| seen_runs.contains(run_id));
- eligible
+ RefreshOutcome { eligible, planning }
}
async fn prepare_run(
@@ -86,31 +134,60 @@ async fn prepare_run(
reported_runs: &mut HashSet<RunId>,
run: DiscoveredRun,
) -> PrepareOutcome {
- counter!(RUNS_DISCOVERED, "status" => run.status.as_str()).increment(1);
+ counter!(RUNS_DISCOVERED, "status" => run.status.as_str(), "kind" => run.kind.as_str())
+ .increment(1);
+
+ let kind = run.kind;
+ let Some(boundary) = resolve_boundary(pool, run).await else {
+ return PrepareOutcome::Skipped;
+ };
+ let Resolved::Seedable(boundary) = boundary else {
+ return PrepareOutcome::WaitingBoundary;
+ };
+ match kind {
+ RunKind::Behavioral => {
+ prepare_behavioral(pool, store, plan_caps, reported_runs, boundary).await
+ }
+ RunKind::PersonProperty => prepare_person(pool, store, reported_runs, boundary).await,
+ }
+}
+enum Resolved {
+ Seedable(SeedableRun),
+ WaitingBoundary,
+}
+
+/// Establish (or re-read) the run's boundary; `None` means the run was skipped.
+async fn resolve_boundary(pool: &PgPool, run: DiscoveredRun) -> Option<Resolved> {
let was_awaiting_boundary = run.status == RunStatus::AwaitingBoundary;
let discovered_run_id = run.run_id;
- let boundary = match establish_boundary(pool, run).await {
+ match establish_boundary(pool, run).await {
Ok(BoundaryOutcome::Established(run)) => {
counter!(BOUNDARY_ESTABLISHED, "trigger" => run.trigger.as_str()).increment(1);
- run
+ Some(Resolved::Seedable(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;
+ Some(Resolved::Seedable(run))
}
+ Ok(BoundaryOutcome::NoLongerSeedable { .. }) => None,
+ Err(RunError::DisasterRecoveryBoundaryMissing(_)) => Some(Resolved::WaitingBoundary),
Err(error) => {
handle_run_error(pool, Some(discovered_run_id), error).await;
- return PrepareOutcome::Skipped;
+ None
}
- };
+ }
+}
+async fn prepare_behavioral(
+ pool: &PgPool,
+ store: &PgChunkStore,
+ plan_caps: PlanCaps,
+ reported_runs: &mut HashSet<RunId>,
+ boundary: SeedableRun,
+) -> PrepareOutcome {
let run_id = boundary.run_id;
let validated = match boundary.load_pinned(pool).await {
Ok(validated) => validated,
@@ -139,15 +216,8 @@ async fn prepare_run(
// Without the proof the run never dispatches, so an uncovered cohort can never stamp readiness
// on zero seeded history. Siblings still get planned and seeded.
- let coverage_complete = validated.uncovered_cohorts.is_empty();
- if !coverage_complete {
- counter!(RUNS_PLANNING_WITHHELD).increment(1);
- warn!(
- run_id = ?run_id,
- uncovered_cohorts = ?validated.uncovered_cohorts,
- "active participations have no surviving pinned condition; withholding the planning proof"
- );
- }
+ let coverage_complete =
+ record_coverage(run_id, RunKind::Behavioral, &validated.uncovered_cohorts);
let days = plan_days(
&validated.run.conditions,
@@ -158,7 +228,7 @@ async fn prepare_run(
if coverage_complete {
// A legitimately zero-chunk run still needs the proof, or it stalls waiting for chunks
// that will never exist.
- stamp_planning(pool, run_id).await;
+ stamp_planning(pool, run_id, RunKind::Behavioral).await;
}
return PrepareOutcome::NoChunks;
}
@@ -167,25 +237,142 @@ async fn prepare_run(
.await
{
Ok(PlanOutcome::Planned { inserted }) => {
- counter!(CHUNKS_PLANNED).increment(inserted);
+ counter!(CHUNKS_PLANNED, "kind" => RunKind::Behavioral.as_str()).increment(inserted);
if coverage_complete {
- stamp_planning(pool, run_id).await;
+ stamp_planning(pool, run_id, RunKind::Behavioral).await;
}
}
Ok(PlanOutcome::RunNotSeeding) => return PrepareOutcome::Skipped,
+ Ok(PlanOutcome::AlreadyPlanned) => {
+ // Behavioral planning never takes the all-or-nothing gate; reaching this means the
+ // store contract changed underneath this caller.
+ warn!(
+ ?run_id,
+ "behavioral planning unexpectedly reported AlreadyPlanned"
+ );
+ 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))
+ PrepareOutcome::Eligible(PreparedRun::Behavioral(Arc::new(validated.run)))
+}
+
+/// The person pipeline: validate the pinned payload (zero surviving hashes with an active
+/// participation fails the run inside `handle_run_error`; all-superseded retires as zero-work),
+/// then classify by planning state — the stamp or existing chunks make the run claim-eligible;
+/// otherwise it needs its planning scan.
+async fn prepare_person(
+ pool: &PgPool,
+ store: &PgChunkStore,
+ reported_runs: &mut HashSet<RunId>,
+ boundary: SeedableRun,
+) -> PrepareOutcome {
+ let run_id = boundary.run_id;
+ let validated = match boundary.load_person_pinned(pool).await {
+ Ok(PersonRunValidation::Seedable(validated)) => validated,
+ Ok(PersonRunValidation::Retired { warnings }) => {
+ if reported_runs.insert(run_id) {
+ record_pinned_warnings(&warnings);
+ }
+ // Nothing expects coverage, so the zero-chunk proof lets the run finish as zero-work
+ // downstream — the behavioral zero-condition retirement, kind-adjusted.
+ stamp_planning(pool, run_id, RunKind::PersonProperty).await;
+ return PrepareOutcome::NoChunks;
+ }
+ Err(error) => {
+ handle_run_error(pool, Some(run_id), error).await;
+ return PrepareOutcome::Skipped;
+ }
+ };
+ if reported_runs.insert(run_id) {
+ record_pinned_warnings(&validated.warnings);
+ }
+ if validated
+ .warnings
+ .iter()
+ .any(|warning| matches!(warning, PinnedWarning::ConditionDropped { .. }))
+ {
+ persist_run_warning(pool, run_id, RunWarningNote::ConditionsDropped).await;
+ }
+ let coverage_complete = record_coverage(
+ run_id,
+ RunKind::PersonProperty,
+ &validated.uncovered_cohorts,
+ );
+
+ let stamped = match read_planning_stamp(pool, run_id, RunKind::PersonProperty).await {
+ Ok(stamp) => stamp.is_some(),
+ Err(error) => {
+ warn!(?run_id, error = %error, "reading the person planning stamp failed");
+ return PrepareOutcome::Skipped;
+ }
+ };
+ let run = Arc::new(validated.run);
+ if stamped {
+ return PrepareOutcome::Eligible(PreparedRun::Person(run));
+ }
+ match store.chunk_progress(run_id).await {
+ Ok(progress) if progress.total() > 0 => {
+ // Planned but not yet stamped — the planner left the stamp to this pass (its coverage
+ // snapshot could predate a supersession). Coverage here is fresh from the database.
+ if coverage_complete {
+ stamp_planning(pool, run_id, RunKind::PersonProperty).await;
+ }
+ PrepareOutcome::Eligible(PreparedRun::Person(run))
+ }
+ Ok(_) => PrepareOutcome::PlanningNeeded(PersonPlanRequest {
+ run,
+ coverage_complete,
+ }),
+ Err(error) => {
+ warn!(?run_id, error = %error, "reading person chunk progress failed");
+ PrepareOutcome::Skipped
+ }
+ }
+}
+
+/// The eligible run ids of one kind — the per-kind label on every shared chunk metric resolves
+/// through here, so the mapping lives in one place.
+pub(super) fn run_ids_of_kind(
+ eligible_runs: &HashMap<RunId, PreparedRun>,
+ kind: RunKind,
+) -> Vec<RunId> {
+ eligible_runs
+ .iter()
+ .filter(|(_, prepared)| {
+ matches!(
+ (prepared, kind),
+ (PreparedRun::Behavioral(_), RunKind::Behavioral)
+ | (PreparedRun::Person(_), RunKind::PersonProperty)
+ )
+ })
+ .map(|(run_id, _)| *run_id)
+ .collect()
+}
+
+fn record_coverage(run_id: RunId, kind: RunKind, uncovered_cohorts: &[CohortId]) -> bool {
+ let coverage_complete = uncovered_cohorts.is_empty();
+ if !coverage_complete {
+ counter!(RUNS_PLANNING_WITHHELD, "kind" => kind.as_str()).increment(1);
+ warn!(
+ run_id = ?run_id,
+ uncovered_cohorts = ?uncovered_cohorts,
+ "active participations have no surviving pinned condition; withholding the planning proof"
+ );
+ }
+ coverage_complete
}
/// Stamp the planning proof once planning has run. A failure is logged but never changes the prepare
/// outcome — the run keeps seeding and the next pass re-stamps.
-async fn stamp_planning(pool: &PgPool, run_id: RunId) {
- match mark_chunks_planned(pool, run_id).await {
- Ok(PlanningStampOutcome::Stamped) => counter!(RUNS_PLANNING_STAMPED).increment(1),
+async fn stamp_planning(pool: &PgPool, run_id: RunId, kind: RunKind) {
+ match mark_chunks_planned(pool, run_id, kind).await {
+ Ok(PlanningStampOutcome::Stamped) => {
+ counter!(RUNS_PLANNING_STAMPED, "kind" => kind.as_str()).increment(1);
+ }
Ok(PlanningStampOutcome::Skipped) => {}
Err(error) => warn!(run_id = ?run_id, error = %error, "stamping the planning proof failed"),
}
@@ -266,7 +453,8 @@ fn run_error_disposition(run_id: Option<RunId>, error: &RunError) -> RunErrorDis
reason: "missing_boundary",
},
RunError::DisasterRecoveryBoundaryMissing(_) => RunErrorDisposition::Retry,
- RunError::InvalidTrigger { run_id, .. }
+ RunError::InvalidKind { run_id, .. }
+ | RunError::InvalidTrigger { run_id, .. }
| RunError::InvalidScope { run_id, .. }
| RunError::InvalidStatus { run_id, .. } => RunErrorDisposition::Fail {
run_id: *run_id,
diff --git a/rust/cohort-seeder/src/app/reconcile_dispatch.rs b/rust/cohort-seeder/src/app/reconcile_dispatch.rs
index e74ab815278e..fd5f954bde92 100644
--- a/rust/cohort-seeder/src/app/reconcile_dispatch.rs
+++ b/rust/cohort-seeder/src/app/reconcile_dispatch.rs
@@ -18,7 +18,7 @@ use crate::kafka::producer::{
};
use crate::store::chunks::{ChunkStoreError, PgChunkStore};
use crate::store::completion::{read_planning_stamp, CompletionStoreError};
-use crate::store::runs::{load_reconcile_run, ReconcileRun, ReconcileRunError, RunStatus};
+use crate::store::runs::{load_reconcile_run, ReconcileRun, ReconcileRunError, RunKind, RunStatus};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompletionRequirement {
@@ -142,7 +142,9 @@ pub async fn prepare_reconcile_dispatch(
let progress = PgChunkStore::new(pool.clone())
.chunk_progress(run_id)
.await?;
- let planning_proven = read_planning_stamp(pool, run_id).await?.is_some();
+ let planning_proven = read_planning_stamp(pool, run_id, RunKind::Behavioral)
+ .await?
+ .is_some();
validate_completion(run_id, progress.remaining(), planning_proven, completion)?;
let prepared = PreparedReconcileDispatch {
run,
diff --git a/rust/cohort-seeder/src/app/settings.rs b/rust/cohort-seeder/src/app/settings.rs
index 166553b57431..5d055e80f046 100644
--- a/rust/cohort-seeder/src/app/settings.rs
+++ b/rust/cohort-seeder/src/app/settings.rs
@@ -2,16 +2,54 @@
//! `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::num::{NonZeroU16, NonZeroU32, NonZeroU64, NonZeroUsize};
use std::time::Duration;
use crate::config::Config;
use crate::domain::PlanCaps;
+use crate::store::runs::RunKind;
use crate::store::{LeaseDuration, LeaseDurationError, MaxAttempts, MaxAttemptsError};
use super::deliver::QUEUE_FULL_BACKOFF_CAP;
use super::orchestrator::ORCHESTRATOR_LIVENESS_DEADLINE;
+/// The person seed path's tunables. `OrchestratorSettings.person` is `None` when
+/// `SEEDER_PERSON_SEEDS_ENABLED` is off — the type encodes "person path off".
+#[derive(Debug, Clone, Copy)]
+pub struct PersonSettings {
+ pub seeds_per_sec: NonZeroU32,
+ pub persons_per_chunk: NonZeroU64,
+ /// The person path's own slot budget: a person chunk never occupies a behavioral slot, so a
+ /// long person scan cannot stall live behavioral seeding.
+ pub max_concurrent_chunks: NonZeroUsize,
+ pub emit_nonmatchers: bool,
+}
+
+impl PersonSettings {
+ /// The pacer is shared across concurrent person chunks, so one chunk's floor wall-clock is
+ /// `persons_per_chunk / (seeds_per_sec / concurrency)` — and the ClickHouse cursor stays open
+ /// across the paced produce, counting client read time against `max_execution_time`. Refuse a
+ /// combination that would eat more than half that budget at startup rather than at hour four.
+ fn validate_scan_budget(
+ &self,
+ ch_max_execution_time_secs: u64,
+ ) -> Result<(), OrchestratorSettingsError> {
+ let projected_secs = self
+ .persons_per_chunk
+ .get()
+ .saturating_mul(self.max_concurrent_chunks.get() as u64)
+ / u64::from(self.seeds_per_sec.get());
+ let budget_secs = ch_max_execution_time_secs / 2;
+ if projected_secs > budget_secs {
+ return Err(OrchestratorSettingsError::PersonChunkExceedsScanBudget {
+ projected_secs,
+ budget_secs,
+ });
+ }
+ Ok(())
+ }
+}
+
#[derive(Debug, Clone, Copy)]
pub struct OrchestratorSettings {
pub(super) run_poll_interval: Duration,
@@ -20,9 +58,11 @@ pub struct OrchestratorSettings {
pub(super) max_chunk_attempts: MaxAttempts,
pub(super) plan_caps: PlanCaps,
pub(super) producer: ProducerSettings,
+ pub(super) person: Option<PersonSettings>,
}
impl OrchestratorSettings {
+ #[allow(clippy::too_many_arguments)]
pub fn new(
run_poll_interval: Duration,
max_concurrent_chunks: usize,
@@ -31,6 +71,7 @@ impl OrchestratorSettings {
max_lookback_days: u32,
bands_per_day: u16,
producer: ProducerSettings,
+ person: Option<PersonSettings>,
) -> Result<Self, OrchestratorSettingsError> {
if run_poll_interval.is_zero() {
return Err(OrchestratorSettingsError::ZeroPollInterval);
@@ -63,8 +104,23 @@ impl OrchestratorSettings {
bands_per_day,
},
producer,
+ person,
})
}
+
+ pub fn person(&self) -> Option<&PersonSettings> {
+ self.person.as_ref()
+ }
+
+ /// The backfill kinds discovery binds. With the person gate off this is `['behavioral']`, so
+ /// the running binary's behavior is identical to today's.
+ pub(super) fn discovery_kinds(&self) -> &'static [RunKind] {
+ if self.person.is_some() {
+ &[RunKind::Behavioral, RunKind::PersonProperty]
+ } else {
+ &[RunKind::Behavioral]
+ }
+ }
}
impl TryFrom<&Config> for OrchestratorSettings {
@@ -75,6 +131,24 @@ impl TryFrom<&Config> for OrchestratorSettings {
config.seeder_max_inflight_tiles,
Duration::from_millis(config.seeder_queue_full_backoff_ms),
)?;
+ let person = config
+ .seeder_person_seeds_enabled
+ .then(|| {
+ let person = PersonSettings {
+ seeds_per_sec: NonZeroU32::new(config.seeder_person_seeds_per_sec)
+ .ok_or(OrchestratorSettingsError::ZeroPersonSeedRate)?,
+ persons_per_chunk: NonZeroU64::new(config.seeder_persons_per_chunk)
+ .ok_or(OrchestratorSettingsError::ZeroPersonsPerChunk)?,
+ max_concurrent_chunks: NonZeroUsize::new(
+ config.seeder_person_max_concurrent_chunks,
+ )
+ .ok_or(OrchestratorSettingsError::ZeroPersonConcurrency)?,
+ emit_nonmatchers: config.seeder_person_emit_nonmatchers,
+ };
+ person.validate_scan_budget(config.seeder_ch_max_execution_time_secs)?;
+ Ok::<_, OrchestratorSettingsError>(person)
+ })
+ .transpose()?;
Ok(Self::new(
Duration::from_secs(config.seeder_run_poll_secs),
config.seeder_max_concurrent_chunks,
@@ -83,6 +157,7 @@ impl TryFrom<&Config> for OrchestratorSettings {
config.seeder_max_lookback_days,
config.seeder_bands_per_day,
producer,
+ person,
)?)
}
}
@@ -105,6 +180,21 @@ pub enum OrchestratorSettingsError {
MaxAttemptsOutOfRange,
#[error("bands per day must be between 1 and 32767")]
BandsPerDayOutOfRange,
+ #[error("person seeds per second must be greater than zero")]
+ ZeroPersonSeedRate,
+ #[error("persons per chunk must be greater than zero")]
+ ZeroPersonsPerChunk,
+ #[error("person max concurrent chunks must be greater than zero")]
+ ZeroPersonConcurrency,
+ #[error(
+ "one person chunk needs ~{projected_secs}s at the configured rate and concurrency, over \
+ the {budget_secs}s scan budget (half of SEEDER_CH_MAX_EXECUTION_TIME_SECS); shrink \
+ SEEDER_PERSONS_PER_CHUNK or raise SEEDER_PERSON_SEEDS_PER_SEC"
+ )]
+ PersonChunkExceedsScanBudget {
+ projected_secs: u64,
+ budget_secs: u64,
+ },
}
/// The produce sequencing's tunables: the in-flight delivery bound and the queue-full backoff (capped
@@ -192,6 +282,7 @@ mod tests {
400,
1,
producer_settings(),
+ None,
),
OrchestratorSettingsError::PollIntervalExceedsLivenessDeadline,
),
@@ -204,6 +295,7 @@ mod tests {
400,
1,
producer_settings(),
+ None,
),
OrchestratorSettingsError::ZeroPollInterval,
),
@@ -216,6 +308,7 @@ mod tests {
400,
1,
producer_settings(),
+ None,
),
OrchestratorSettingsError::ZeroConcurrency,
),
@@ -228,6 +321,7 @@ mod tests {
400,
1,
producer_settings(),
+ None,
),
OrchestratorSettingsError::LeaseTooShort,
),
@@ -240,6 +334,7 @@ mod tests {
400,
1,
producer_settings(),
+ None,
),
OrchestratorSettingsError::ZeroMaxAttempts,
),
@@ -252,6 +347,7 @@ mod tests {
400,
0,
producer_settings(),
+ None,
),
OrchestratorSettingsError::BandsPerDayOutOfRange,
),
@@ -264,6 +360,7 @@ mod tests {
400,
u16::MAX,
producer_settings(),
+ None,
),
OrchestratorSettingsError::BandsPerDayOutOfRange,
),
@@ -273,6 +370,71 @@ mod tests {
}
}
+ /// Dark-by-default: with the gate off discovery binds behavioral only; enabling it validates
+ /// the person rates the way `ZeroTileRate` guards the behavioral pacer.
+ #[test]
+ fn person_settings_are_gated_and_validated() {
+ let config = Config::init_from_hashmap(&HashMap::new()).unwrap();
+ let dark = OrchestratorSettings::try_from(&config).unwrap();
+ assert!(dark.person().is_none());
+ assert_eq!(dark.discovery_kinds(), &[RunKind::Behavioral]);
+
+ let mut enabled = config.clone();
+ enabled.seeder_person_seeds_enabled = true;
+ let lit = OrchestratorSettings::try_from(&enabled).unwrap();
+ assert!(lit.person().is_some());
+ assert_eq!(
+ lit.discovery_kinds(),
+ &[RunKind::Behavioral, RunKind::PersonProperty]
+ );
+
+ enabled.seeder_person_seeds_per_sec = 0;
+ assert!(matches!(
+ OrchestratorSettings::try_from(&enabled),
+ Err(SettingsError::Orchestrator(
+ OrchestratorSettingsError::ZeroPersonSeedRate
+ ))
+ ));
+ enabled.seeder_person_seeds_per_sec = 2000;
+ enabled.seeder_persons_per_chunk = 0;
+ assert!(matches!(
+ OrchestratorSettings::try_from(&enabled),
+ Err(SettingsError::Orchestrator(
+ OrchestratorSettingsError::ZeroPersonsPerChunk
+ ))
+ ));
+ enabled.seeder_persons_per_chunk = 1_000_000;
+ enabled.seeder_person_max_concurrent_chunks = 0;
+ assert!(matches!(
+ OrchestratorSettings::try_from(&enabled),
+ Err(SettingsError::Orchestrator(
+ OrchestratorSettingsError::ZeroPersonConcurrency
+ ))
+ ));
+ }
+
+ /// A chunk whose floor wall-clock (shared pacer, concurrency multiplier) would eat more than
+ /// half the ClickHouse execution-time budget must refuse at startup, not at hour four.
+ #[test]
+ fn person_chunk_sizing_must_fit_the_clickhouse_scan_budget() {
+ let mut config = Config::init_from_hashmap(&HashMap::new()).unwrap();
+ config.seeder_person_seeds_enabled = true;
+ assert!(OrchestratorSettings::try_from(&config).is_ok());
+
+ // 5M persons at 2000/s across 6 concurrent chunks ⇒ 15000s > 14400/2.
+ config.seeder_persons_per_chunk = 5_000_000;
+ config.seeder_person_max_concurrent_chunks = 6;
+ assert!(matches!(
+ OrchestratorSettings::try_from(&config),
+ Err(SettingsError::Orchestrator(
+ OrchestratorSettingsError::PersonChunkExceedsScanBudget {
+ projected_secs: 15_000,
+ budget_secs: 7_200,
+ }
+ ))
+ ));
+ }
+
#[test]
fn try_from_config_rejects_disabled_concurrency() {
let mut config = Config::init_from_hashmap(&HashMap::new()).unwrap();
diff --git a/rust/cohort-seeder/src/clickhouse/client.rs b/rust/cohort-seeder/src/clickhouse/client.rs
index 297f0cbe3b66..d11b743a5246 100644
--- a/rust/cohort-seeder/src/clickhouse/client.rs
+++ b/rust/cohort-seeder/src/clickhouse/client.rs
@@ -300,6 +300,10 @@ pub fn build_client(config: &Config) -> Result<clickhouse::Client, ClickHouseCli
"max_bytes_before_external_sort",
config.seeder_ch_max_bytes_before_external_sort.to_string(),
)
+ .with_option(
+ "max_bytes_in_set",
+ config.seeder_ch_max_bytes_in_set.to_string(),
+ )
.with_option("join_algorithm", join_algorithm.as_str()))
}
diff --git a/rust/cohort-seeder/src/clickhouse/mod.rs b/rust/cohort-seeder/src/clickhouse/mod.rs
index d9f208a85f1d..63961d5c0b84 100644
--- a/rust/cohort-seeder/src/clickhouse/mod.rs
+++ b/rust/cohort-seeder/src/clickhouse/mod.rs
@@ -1,7 +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`.
+//! ClickHouse layer: scan planning, row decoding, the streaming scanners (behavioral events and
+//! person rows), and the client builder. Depends only on `domain` and `config` (plus the
+//! `clickhouse` crate); never on `store` or `kafka`.
pub mod client;
+pub mod person_scanner;
+pub mod person_sql;
pub mod row;
pub mod scanner;
pub mod sql;
@@ -9,4 +12,6 @@ pub mod sql;
pub use client::{
build_client, ClickHouseClientError, ClickHouseEndpoint, ClickHouseJoinAlgorithm,
};
+pub use person_scanner::{PersonRow, PersonScanError, PersonScanner};
+pub use person_sql::PersonScanSpec;
pub use scanner::{ChunkScanner, ScanError};
diff --git a/rust/cohort-seeder/src/clickhouse/person_scanner.rs b/rust/cohort-seeder/src/clickhouse/person_scanner.rs
new file mode 100644
index 000000000000..ca27bea238e0
--- /dev/null
+++ b/rust/cohort-seeder/src/clickhouse/person_scanner.rs
@@ -0,0 +1,201 @@
+//! The streaming person scanner: the one-shot boundary scan planning tiles a run's UUID space
+//! from, and the per-chunk range-scan cursor the person executor folds row by row. Depends on
+//! `domain` and the sibling `person_sql`; never on `store` or `kafka`.
+
+use std::num::NonZeroU64;
+
+use clickhouse::query::RowCursor;
+use clickhouse::Row;
+use cohort_core::filters::TeamId;
+use serde::Deserialize;
+use tokio_util::sync::CancellationToken;
+use tracing::warn;
+use uuid::Uuid;
+
+use super::person_sql::{person_boundaries_sql, person_scan_sql, PersonScanSpec};
+use crate::domain::{UtcMillis, MAX_PERSON_CHUNKS};
+
+/// One scanned person's latest row: the id and its `argMax(properties, version)` payload.
+#[derive(Debug, Row, Deserialize)]
+pub struct PersonRow {
+ pub id: String,
+ pub properties: String,
+}
+
+#[derive(Debug, Row, Deserialize)]
+struct PersonIdRow {
+ id: String,
+}
+
+#[derive(Clone)]
+pub struct PersonScanner {
+ client: clickhouse::Client,
+}
+
+impl PersonScanner {
+ pub fn new(client: clickhouse::Client) -> Self {
+ Self { client }
+ }
+
+ /// Stream the run's live person ids in ClickHouse order, keeping the first id of every new
+ /// chunk as a range boundary — memory is bounded by the chunk-count ceiling, never the table
+ /// size. When the ceiling saturates, the final unbounded range absorbs the remainder and the
+ /// scan stops early rather than failing a run over a column-width constraint.
+ pub async fn boundaries(
+ &self,
+ team_id: TeamId,
+ scan_since: UtcMillis,
+ persons_per_chunk: NonZeroU64,
+ shutdown: &CancellationToken,
+ ) -> Result<Vec<Uuid>, PersonScanError> {
+ let mut cursor = self
+ .client
+ .query(&person_boundaries_sql(team_id, scan_since))
+ .fetch::<PersonIdRow>()
+ .map_err(PersonScanError::Query)?;
+ let mut keeper = BoundaryKeeper::new(persons_per_chunk);
+ loop {
+ let row = tokio::select! {
+ biased;
+ _ = shutdown.cancelled() => return Err(PersonScanError::Cancelled),
+ row = cursor.next() => row.map_err(PersonScanError::Cursor)?,
+ };
+ let Some(row) = row else {
+ break;
+ };
+ if keeper.observe(row.id)? == BoundaryScanStep::Saturated {
+ warn!(
+ team_id = team_id.0,
+ persons_per_chunk = persons_per_chunk.get(),
+ "person chunk ceiling saturated; the final chunk absorbs the remainder"
+ );
+ break;
+ }
+ }
+ Ok(keeper.into_boundaries())
+ }
+
+ /// The streaming cursor over one chunk's UUID range; the caller owns the fold.
+ pub fn scan_rows(
+ &self,
+ spec: &PersonScanSpec,
+ ) -> Result<RowCursor<PersonRow>, PersonScanError> {
+ self.client
+ .query(&person_scan_sql(spec))
+ .fetch::<PersonRow>()
+ .map_err(PersonScanError::Query)
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum BoundaryScanStep {
+ Continue,
+ /// The chunk-count ceiling is reached: no further boundary can be kept, so the remaining rows
+ /// all fall into the final unbounded range and the scan may stop.
+ Saturated,
+}
+
+/// The pure boundary-selection fold: a boundary is the *first* id of each new chunk (not the last
+/// of the completed one), so every chunk — including the first — holds `stride` persons.
+struct BoundaryKeeper {
+ stride: u64,
+ seen: u64,
+ boundaries: Vec<Uuid>,
+}
+
+impl BoundaryKeeper {
+ fn new(stride: NonZeroU64) -> Self {
+ Self {
+ stride: stride.get(),
+ seen: 0,
+ boundaries: Vec::new(),
+ }
+ }
+
+ fn observe(&mut self, id: String) -> Result<BoundaryScanStep, PersonScanError> {
+ self.seen += 1;
+ if self.seen > 1 && (self.seen - 1).is_multiple_of(self.stride) {
+ // Ranges = boundaries + 1, and `band` is a smallint.
+ if self.boundaries.len() + 1 >= MAX_PERSON_CHUNKS {
+ return Ok(BoundaryScanStep::Saturated);
+ }
+ let boundary = Uuid::parse_str(&id)
+ .map_err(|source| PersonScanError::InvalidPersonBoundary { value: id, source })?;
+ self.boundaries.push(boundary);
+ }
+ Ok(BoundaryScanStep::Continue)
+ }
+
+ fn into_boundaries(self) -> Vec<Uuid> {
+ self.boundaries
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum PersonScanError {
+ #[error("building ClickHouse person scan cursor")]
+ Query(#[source] clickhouse::error::Error),
+ #[error("streaming ClickHouse person scan cursor")]
+ Cursor(#[source] clickhouse::error::Error),
+ #[error("person boundary id {value:?} is not a UUID: {source}")]
+ InvalidPersonBoundary {
+ value: String,
+ #[source]
+ source: uuid::Error,
+ },
+ #[error("person scan cancelled by shutdown")]
+ Cancelled,
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::domain::tile_ranges;
+
+ use super::*;
+
+ fn feed(keeper: &mut BoundaryKeeper, rows: u128) -> Vec<BoundaryScanStep> {
+ (1..=rows)
+ .map(|row| keeper.observe(Uuid::from_u128(row).to_string()).unwrap())
+ .collect()
+ }
+
+ /// Every chunk — the first included — holds exactly `stride` persons; only the final chunk
+ /// carries a remainder.
+ #[test]
+ fn boundaries_start_each_new_chunk_so_every_chunk_holds_the_stride() {
+ // 7 rows at stride 3: boundaries are rows 4 and 7 (the first of chunks 2 and 3), giving
+ // range populations 3, 3, 1.
+ let mut keeper = BoundaryKeeper::new(NonZeroU64::new(3).unwrap());
+ feed(&mut keeper, 7);
+ assert_eq!(
+ keeper.into_boundaries(),
+ vec![Uuid::from_u128(4), Uuid::from_u128(7)]
+ );
+
+ // An exact multiple emits no trailing boundary: 6 rows at stride 3 → chunks of 3 and 3.
+ let mut keeper = BoundaryKeeper::new(NonZeroU64::new(3).unwrap());
+ feed(&mut keeper, 6);
+ assert_eq!(keeper.into_boundaries(), vec![Uuid::from_u128(4)]);
+
+ // Stride 1: the first chunk holds row 1, not zero rows.
+ let mut keeper = BoundaryKeeper::new(NonZeroU64::MIN);
+ feed(&mut keeper, 3);
+ assert_eq!(
+ keeper.into_boundaries(),
+ vec![Uuid::from_u128(2), Uuid::from_u128(3)]
+ );
+ }
+
+ /// The keeper saturates at the band column's ceiling instead of overflowing: the tiling stays
+ /// inside `MAX_PERSON_CHUNKS` and the final unbounded range absorbs the remainder.
+ #[test]
+ fn boundary_count_saturates_at_the_chunk_ceiling() {
+ let mut keeper = BoundaryKeeper::new(NonZeroU64::MIN);
+ let rows = MAX_PERSON_CHUNKS as u128 + 5;
+ let steps = feed(&mut keeper, rows);
+ assert!(steps.contains(&BoundaryScanStep::Saturated));
+ let boundaries = keeper.into_boundaries();
+ assert_eq!(boundaries.len(), MAX_PERSON_CHUNKS - 1);
+ assert_eq!(tile_ranges(&boundaries).unwrap().len(), MAX_PERSON_CHUNKS);
+ }
+}
diff --git a/rust/cohort-seeder/src/clickhouse/person_sql.rs b/rust/cohort-seeder/src/clickhouse/person_sql.rs
new file mode 100644
index 000000000000..6cc975e593b2
--- /dev/null
+++ b/rust/cohort-seeder/src/clickhouse/person_sql.rs
@@ -0,0 +1,119 @@
+//! ClickHouse person-scan SQL: the byte-frozen renderers for the boundary and range scans over the
+//! `person` table. Depends on `domain`; never on `store`.
+//!
+//! Both queries read the ReplacingMergeTree's latest row per person (`GROUP BY id` + `argMax(…,
+//! version)`) with `team_id` equality-fixed. Range predicates are defined in ClickHouse's UUID
+//! order. The horizon appears twice on purpose: the `id IN (…)` prefilter keeps the `_timestamp`
+//! minmax skip index usable (a bare `HAVING` would decompress every historical version of every
+//! person), while the `HAVING` clause states the update-recency semantics against the group —
+//! `argMax` still sees all versions of the surviving ids. That prefilter is the one unbounded
+//! structure here: the boundary query's set spans a whole team, so the client caps it with
+//! `max_bytes_in_set`. `optimize_aggregation_in_order = 1` keeps the streaming aggregation
+//! bounded; the client's external-group-by spill guard backstops a silent optimizer fallback. Only
+//! the boundary query orders its output — the range scan's fold is order-independent, and an
+//! unneeded `ORDER BY` would materialize the whole chunk result.
+
+use cohort_core::filters::TeamId;
+
+use crate::domain::{PersonRange, UtcMillis};
+
+/// The rendered person scan's inputs, constructed only from already-proven types.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct PersonScanSpec {
+ team_id: TeamId,
+ scan_since_ms: i64,
+ range: PersonRange,
+}
+
+impl PersonScanSpec {
+ pub fn new(team_id: TeamId, scan_since: UtcMillis, range: PersonRange) -> Self {
+ Self {
+ team_id,
+ scan_since_ms: scan_since.as_i64(),
+ range,
+ }
+ }
+}
+
+pub fn person_boundaries_sql(team_id: TeamId, scan_since: UtcMillis) -> String {
+ format!(
+ "SELECT toString(id) AS id\nFROM person\nWHERE team_id = {team} AND id IN (\n SELECT id FROM person\n WHERE team_id = {team} AND _timestamp >= fromUnixTimestamp64Milli({since})\n)\nGROUP BY id\nHAVING argMax(is_deleted, version) = 0 AND max(_timestamp) >= fromUnixTimestamp64Milli({since})\nORDER BY id\nSETTINGS optimize_aggregation_in_order = 1",
+ team = team_id.0,
+ since = scan_since.as_i64(),
+ )
+}
+
+pub fn person_scan_sql(spec: &PersonScanSpec) -> String {
+ // `lo` is always rendered — band 0 carries the nil UUID, a tautology under any byte ordering —
+ // so the predicate shape is uniform across bands. The prefilter carries the same range so the
+ // primary key prunes it too.
+ let hi_predicate = spec
+ .range
+ .hi()
+ .map(|hi| format!(" AND id < toUUID('{hi}')"))
+ .unwrap_or_default();
+ format!(
+ "SELECT toString(id) AS id, argMax(properties, version) AS properties\nFROM person\nWHERE team_id = {team} AND id >= toUUID('{lo}'){hi} AND id IN (\n SELECT id FROM person\n WHERE team_id = {team} AND id >= toUUID('{lo}'){hi}\n AND _timestamp >= fromUnixTimestamp64Milli({since})\n)\nGROUP BY id\nHAVING argMax(is_deleted, version) = 0 AND max(_timestamp) >= fromUnixTimestamp64Milli({since})\nSETTINGS optimize_aggregation_in_order = 1",
+ team = spec.team_id.0,
+ lo = spec.range.lo(),
+ hi = hi_predicate,
+ since = spec.scan_since_ms,
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use uuid::Uuid;
+
+ use super::*;
+
+ const SINCE: UtcMillis = UtcMillis::new(1_780_000_000_000);
+
+ fn range(lo: Uuid, hi: Option<Uuid>) -> PersonRange {
+ PersonRange::new(lo, hi).unwrap()
+ }
+
+ #[test]
+ fn boundaries_sql_is_byte_frozen() {
+ assert_eq!(
+ person_boundaries_sql(TeamId(2), SINCE),
+ "SELECT toString(id) AS id\nFROM person\nWHERE team_id = 2 AND id IN (\n SELECT id FROM person\n WHERE team_id = 2 AND _timestamp >= fromUnixTimestamp64Milli(1780000000000)\n)\nGROUP BY id\nHAVING argMax(is_deleted, version) = 0 AND max(_timestamp) >= fromUnixTimestamp64Milli(1780000000000)\nORDER BY id\nSETTINGS optimize_aggregation_in_order = 1"
+ );
+ }
+
+ #[test]
+ fn scan_sql_is_byte_frozen_for_every_range_shape() {
+ let boundary_a = Uuid::parse_str("01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee").unwrap();
+ let boundary_b = Uuid::parse_str("7f000000-0000-0000-0000-000000000001").unwrap();
+
+ // Band 0: nil lo (tautology) with a bounded hi.
+ assert_eq!(
+ person_scan_sql(&PersonScanSpec::new(
+ TeamId(2),
+ SINCE,
+ range(Uuid::nil(), Some(boundary_a)),
+ )),
+ "SELECT toString(id) AS id, argMax(properties, version) AS properties\nFROM person\nWHERE team_id = 2 AND id >= toUUID('00000000-0000-0000-0000-000000000000') AND id < toUUID('01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee') AND id IN (\n SELECT id FROM person\n WHERE team_id = 2 AND id >= toUUID('00000000-0000-0000-0000-000000000000') AND id < toUUID('01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee')\n AND _timestamp >= fromUnixTimestamp64Milli(1780000000000)\n)\nGROUP BY id\nHAVING argMax(is_deleted, version) = 0 AND max(_timestamp) >= fromUnixTimestamp64Milli(1780000000000)\nSETTINGS optimize_aggregation_in_order = 1"
+ );
+
+ // Interior band: both bounds present.
+ assert_eq!(
+ person_scan_sql(&PersonScanSpec::new(
+ TeamId(2),
+ SINCE,
+ range(boundary_a, Some(boundary_b)),
+ )),
+ "SELECT toString(id) AS id, argMax(properties, version) AS properties\nFROM person\nWHERE team_id = 2 AND id >= toUUID('01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee') AND id < toUUID('7f000000-0000-0000-0000-000000000001') AND id IN (\n SELECT id FROM person\n WHERE team_id = 2 AND id >= toUUID('01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee') AND id < toUUID('7f000000-0000-0000-0000-000000000001')\n AND _timestamp >= fromUnixTimestamp64Milli(1780000000000)\n)\nGROUP BY id\nHAVING argMax(is_deleted, version) = 0 AND max(_timestamp) >= fromUnixTimestamp64Milli(1780000000000)\nSETTINGS optimize_aggregation_in_order = 1"
+ );
+
+ // Last band: unbounded high.
+ assert_eq!(
+ person_scan_sql(&PersonScanSpec::new(
+ TeamId(2),
+ SINCE,
+ range(boundary_b, None)
+ )),
+ "SELECT toString(id) AS id, argMax(properties, version) AS properties\nFROM person\nWHERE team_id = 2 AND id >= toUUID('7f000000-0000-0000-0000-000000000001') AND id IN (\n SELECT id FROM person\n WHERE team_id = 2 AND id >= toUUID('7f000000-0000-0000-0000-000000000001')\n AND _timestamp >= fromUnixTimestamp64Milli(1780000000000)\n)\nGROUP BY id\nHAVING argMax(is_deleted, version) = 0 AND max(_timestamp) >= fromUnixTimestamp64Milli(1780000000000)\nSETTINGS optimize_aggregation_in_order = 1"
+ );
+ }
+}
diff --git a/rust/cohort-seeder/src/clickhouse/scanner.rs b/rust/cohort-seeder/src/clickhouse/scanner.rs
index f658821435b8..28de9fc73d61 100644
--- a/rust/cohort-seeder/src/clickhouse/scanner.rs
+++ b/rust/cohort-seeder/src/clickhouse/scanner.rs
@@ -2,8 +2,6 @@
//! 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;
@@ -22,8 +20,8 @@ use crate::domain::{
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,
+ MetricTimer, AGGREGATE_ENTRIES, CHUNKS_VACUOUS, CHUNK_SCAN_DURATION_SECONDS,
+ CONDITIONS_EVALUATED, EVENTS_SKIPPED, HOGVM_ERRORS, ROWS_SCANNED,
};
#[derive(Clone)]
@@ -79,7 +77,7 @@ impl ChunkScanner {
lease_cancel: &CancellationToken,
shutdown: &CancellationToken,
) -> Result<Vec<SeedTile>, ScanHalt> {
- let _timer = ScanTimer::start();
+ let _timer = MetricTimer::start(CHUNK_SCAN_DURATION_SECONDS);
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);
@@ -250,20 +248,6 @@ fn record_evaluation(stats: RecordStats) {
}
}
-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")]
diff --git a/rust/cohort-seeder/src/config.rs b/rust/cohort-seeder/src/config.rs
index 1c7bc9b9ef3e..150417e5d2b6 100644
--- a/rust/cohort-seeder/src/config.rs
+++ b/rust/cohort-seeder/src/config.rs
@@ -177,6 +177,33 @@ pub struct Config {
#[envconfig(default = "1")]
pub seeder_bands_per_day: u16,
+ /// Enable the person-property seed path: discovery widens to `person_property` runs and the
+ /// planning/scan/emission pipeline arms. Default off — the processor's decode arm and
+ /// `COHORT_SEED_PERSON_APPLY_ENABLED` must be deployed everywhere first, or an old processor
+ /// skip-and-commits the seeds.
+ #[envconfig(default = "false")]
+ pub seeder_person_seeds_enabled: bool,
+
+ /// Person-seed produce rate, shared across concurrent person chunks and separate from
+ /// `seeder_tiles_per_sec` so the two throughputs tune independently.
+ #[envconfig(default = "2000")]
+ pub seeder_person_seeds_per_sec: u32,
+
+ /// Target persons per planned UUID-range chunk; the planning scan keeps every Nth id as a
+ /// range boundary. Sized so one chunk's paced emission completes in single-digit minutes —
+ /// settings validation refuses a value the ClickHouse execution-time budget cannot cover.
+ #[envconfig(default = "1000000")]
+ pub seeder_persons_per_chunk: u64,
+
+ /// The person path's own chunk-slot budget, so a person scan never occupies a behavioral slot.
+ #[envconfig(default = "1")]
+ pub seeder_person_max_concurrent_chunks: usize,
+
+ /// Emit empty-`matched` seeds for scanned non-matchers. They heal stale-TRUE state and cost
+ /// only a point-read on absent records (the consumer's no-create rule).
+ #[envconfig(default = "true")]
+ pub seeder_person_emit_nonmatchers: bool,
+
#[envconfig(default = "14400")]
pub seeder_ch_max_execution_time_secs: u64,
@@ -186,6 +213,13 @@ pub struct Config {
#[envconfig(default = "20000000000")]
pub seeder_ch_max_bytes_before_external_sort: u64,
+ /// Runaway guard on sets built from `IN (SELECT …)` subqueries, which nothing else bounds — the
+ /// person boundary scan's horizon prefilter builds one id set covering a whole team, unchunked.
+ /// Exceeding it throws a set-size error naming the limit rather than pushing the server toward
+ /// an OOM that takes unrelated queries down with it.
+ #[envconfig(default = "20000000000")]
+ pub seeder_ch_max_bytes_in_set: u64,
+
#[envconfig(default = "grace_hash")]
pub seeder_ch_join_algorithm: String,
diff --git a/rust/cohort-seeder/src/domain/aggregate.rs b/rust/cohort-seeder/src/domain/aggregate.rs
index b835a3a4bf47..fbf1601102a7 100644
--- a/rust/cohort-seeder/src/domain/aggregate.rs
+++ b/rust/cohort-seeder/src/domain/aggregate.rs
@@ -53,7 +53,7 @@ impl VmFailureCounts {
.map(|class| (class, self.get(class)))
}
- fn increment(&mut self, class: VmErrorClass) -> Result<(), AggregateError> {
+ pub(super) fn increment(&mut self, class: VmErrorClass) -> Result<(), AggregateError> {
let count = self
.0
.get_mut(class.index())
diff --git a/rust/cohort-seeder/src/domain/chunk.rs b/rust/cohort-seeder/src/domain/chunk.rs
index 1cc89e60a641..ff0d9cb57f94 100644
--- a/rust/cohort-seeder/src/domain/chunk.rs
+++ b/rust/cohort-seeder/src/domain/chunk.rs
@@ -13,6 +13,7 @@ use cohort_core::DayIdx;
use serde::{Deserialize, Serialize};
use super::ids::{ChunkId, ClaimEpoch, RunId, SChunkMs};
+use super::person::PersonRange;
use super::window::DomainError;
use cohort_core::seed::SeedTile;
@@ -167,6 +168,8 @@ pub struct ChunkSpec {
pub day: DayIdx,
pub band: BandSpec,
pub s_chunk: SChunkMs,
+ /// `Some` ⇔ person chunk (behavioral chunks never write the range columns).
+ pub person_range: Option<PersonRange>,
}
/// Freshly claimed and locked; minted only by `store.claim_next` (or `test_support`).
@@ -188,6 +191,33 @@ impl ClaimedChunk {
pub fn into_scanned(self, tiles: Vec<SeedTile>) -> ScannedChunk {
ScannedChunk::new(self.spec, tiles)
}
+
+ /// Pure transition for the person path: the chunk's seeds were streamed out as they were
+ /// scanned, so only the count remains. No DB effect.
+ pub fn into_streamed(self, seeds_produced: u64) -> StreamedChunk {
+ StreamedChunk {
+ spec: self.spec,
+ seeds_produced,
+ }
+ }
+}
+
+/// A person chunk whose seeds were interleaved scan→enqueue — never buffered — awaiting the
+/// `scanning`→`produced` CAS.
+#[derive(Debug)]
+pub struct StreamedChunk {
+ spec: ChunkSpec,
+ seeds_produced: u64,
+}
+
+impl StreamedChunk {
+ pub const fn spec(&self) -> ChunkSpec {
+ self.spec
+ }
+
+ pub const fn seeds_produced(&self) -> u64 {
+ self.seeds_produced
+ }
}
/// Scanned into tiles but not yet marked produced.
diff --git a/rust/cohort-seeder/src/domain/ids.rs b/rust/cohort-seeder/src/domain/ids.rs
index 6ad2c7792323..69594b892ce8 100644
--- a/rust/cohort-seeder/src/domain/ids.rs
+++ b/rust/cohort-seeder/src/domain/ids.rs
@@ -8,7 +8,9 @@ use serde::{Deserialize, Serialize};
use sqlx::Type;
use uuid::Uuid;
-pub use cohort_core::seed::{ClaimEpoch, ConditionHash, ConditionHashError, RunId, SChunkMs};
+pub use cohort_core::seed::{
+ ClaimEpoch, ConditionHash, ConditionHashError, RunId, SChunkMs, ScannedAtMs,
+};
pub use cohort_core::DayIdx;
#[derive(
diff --git a/rust/cohort-seeder/src/domain/mod.rs b/rust/cohort-seeder/src/domain/mod.rs
index b70b716ae2ed..2251f6d89149 100644
--- a/rust/cohort-seeder/src/domain/mod.rs
+++ b/rust/cohort-seeder/src/domain/mod.rs
@@ -2,8 +2,9 @@
//!
//! 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
+//! `ids` ← {`condition`, `window`} ← `chunk` ← {`plan`, `pinned`, `aggregate`} ← `person`,
+//! except that `chunk` reaches back into `person` for the `PersonRange` vocabulary its spec
+//! carries. The seed wire contract (`SeedTile`/`PersonSeed` and the ids that ride them) lives in
//! `cohort_core::seed` — shared with the processor — and is re-exported here.
pub mod aggregate;
@@ -13,6 +14,7 @@ pub mod condition;
pub mod ids;
pub mod ledger;
pub mod partition;
+pub mod person;
pub mod pinned;
pub mod plan;
pub mod window;
@@ -23,10 +25,11 @@ pub use aggregate::{
pub use chunk::{
BandSpec, BandSpecError, CancelCause, ChunkDomainError, ChunkLease, ChunkSpec, ChunkStatus,
ClaimKind, ClaimedChunk, EnqueuedChunk, HaltReason, Halted, ProduceHwms, ProducedChunk,
- ScannedChunk, UnknownChunkStatus,
+ ScannedChunk, StreamedChunk, UnknownChunkStatus,
};
pub use cohort_core::seed::{
- BehavioralShapeHash, BehavioralShapeHashError, ReconcileCompleteMarker, ReconcileTile, SeedTile,
+ BehavioralShapeHash, BehavioralShapeHashError, PersonSeed, ReconcileCompleteMarker,
+ ReconcileTile, SeedTile,
};
pub(crate) use completion::MARKER_WATCH_SCHEMA;
pub use completion::{
@@ -39,10 +42,16 @@ pub use completion::{
pub use condition::{EventNameSet, Lookback, PinnedCondition};
pub use ids::{
Band, ChunkId, ClaimEpoch, ConditionHash, ConditionHashError, DayIdx, RunId, SChunkMs,
- UtcMillis, UtcMsRange, UtcRangeError,
+ ScannedAtMs, UtcMillis, UtcMsRange, UtcRangeError,
};
pub use ledger::{MarkerFold, MarkerLedger, SettledVerdict};
pub use partition::{SeedPartition, SeedPartitionCountError, SeedPartitions};
+pub use person::{
+ person_chunk_sentinel_day, tile_ranges, EvaluatedConditions, PersonChunkSpec,
+ PersonChunkSpecError, PersonEvaluator, PersonPinnedSnapshot, PersonPlanError, PersonRange,
+ PersonRangeError, PersonRowOutcome, PersonRowSkip, PersonRunValidation, PersonSeedContext,
+ PinnedPersonRun, ValidatedPinnedPersonRun, MAX_PERSON_CHUNKS,
+};
pub use pinned::{
PinnedDropReason, PinnedError, PinnedParticipation, PinnedParticipationState, PinnedRun,
PinnedRunSnapshot, PinnedWarning, TriggerKind, UnknownTriggerKind, ValidatedPinnedRun,
diff --git a/rust/cohort-seeder/src/domain/person.rs b/rust/cohort-seeder/src/domain/person.rs
new file mode 100644
index 000000000000..7724dba0325d
--- /dev/null
+++ b/rust/cohort-seeder/src/domain/person.rs
@@ -0,0 +1,950 @@
+//! Domain layer: the person-property run — run kinds, UUID-range chunk tiling, pinned-payload
+//! validation into [`PinnedPersonRun`], and the pure per-row evaluation fold. Depends on `chunk`,
+//! `pinned`, `aggregate`, `ids`, and `cohort-core`.
+//!
+//! Range semantics (owned by this module): a person run's chunks tile the full UUID space in
+//! **ClickHouse's UUID order** — boundaries arrive from a `GROUP BY id … ORDER BY id` stream and are
+//! opaque here. Rust never sorts or compares person UUIDs beyond byte equality: a Rust-side
+//! reordering would produce overlapping ranges in ClickHouse semantics, and an ordering check on
+//! decode would strand claimed chunks `scanning`.
+
+use std::collections::{BTreeMap, HashSet};
+use std::sync::Arc;
+
+use chrono::NaiveDate;
+use cohort_core::filters::{CohortId, TeamFilters, TeamId};
+use cohort_core::hogvm::{
+ build_person_scan_globals, classify_vm_error, CohortEvaluator, EvalOutcome,
+};
+use cohort_core::seed::PersonSeed;
+use cohort_core::{LeafStateKey, StateVariant};
+use serde::Deserialize;
+use serde_json::Value;
+use uuid::Uuid;
+
+use super::aggregate::RecordStats;
+use super::chunk::{ChunkLease, ChunkSpec};
+use super::ids::{ClaimEpoch, ConditionHash, RunId, ScannedAtMs, UtcMillis};
+use super::pinned::{
+ resolve_timezone, ParticipationSet, PinnedDropReason, PinnedError, PinnedParticipation,
+ PinnedParticipationState, PinnedWarning,
+};
+
+/// The wire cap a single seed's `evaluated` list admits; validation enforces it run-wide.
+pub use cohort_core::seed::MAX_PERSON_SEED_HASHES;
+
+/// The fixed far-future `day` every person chunk is planned under. `claim_next` orders by
+/// `(day, band)`, so behavioral chunks (readiness-gating, fence-sensitive) always claim first.
+pub fn person_chunk_sentinel_day() -> NaiveDate {
+ NaiveDate::from_ymd_opt(9999, 1, 1).expect("9999-01-01 is a valid date")
+}
+
+/// One person chunk's UUID range: `lo` inclusive (always present — the nil UUID is minimal under
+/// any byte-permutation ordering, so band 0's `id >= nil` is a tautology), `hi` exclusive (`None`
+/// only on the last band). Both endpoints are opaque ClickHouse-order boundaries.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct PersonRange {
+ lo: Uuid,
+ hi: Option<Uuid>,
+}
+
+impl PersonRange {
+ /// Rejects only a byte-equal `lo`/`hi` pair (a provably empty range); deliberately no ordering
+ /// check — the ordering lives in ClickHouse.
+ pub fn new(lo: Uuid, hi: Option<Uuid>) -> Result<Self, PersonRangeError> {
+ if hi == Some(lo) {
+ return Err(PersonRangeError(lo));
+ }
+ Ok(Self { lo, hi })
+ }
+
+ pub const fn lo(self) -> Uuid {
+ self.lo
+ }
+
+ pub const fn hi(self) -> Option<Uuid> {
+ self.hi
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+#[error("person range with lo == hi == {0} is empty")]
+pub struct PersonRangeError(pub Uuid);
+
+/// The chunk-count ceiling: `band` is a PostgreSQL `smallint`.
+pub const MAX_PERSON_CHUNKS: usize = i16::MAX as usize;
+
+/// Tile the full UUID space from an in-order boundary stream: positional and order-preserving —
+/// adjacent byte-equal boundaries (and a leading nil) are dropped, nothing is sorted. Every person,
+/// including one inserted after planning, falls into exactly one range.
+pub fn tile_ranges(boundaries: &[Uuid]) -> Result<Vec<PersonRange>, PersonPlanError> {
+ let mut ranges = Vec::with_capacity(boundaries.len() + 1);
+ let mut lo = Uuid::nil();
+ for boundary in boundaries {
+ if *boundary == lo {
+ continue;
+ }
+ ranges.push(PersonRange {
+ lo,
+ hi: Some(*boundary),
+ });
+ lo = *boundary;
+ }
+ ranges.push(PersonRange { lo, hi: None });
+ if ranges.len() > MAX_PERSON_CHUNKS {
+ return Err(PersonPlanError::TooManyChunks(ranges.len()));
+ }
+ Ok(ranges)
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+pub enum PersonPlanError {
+ #[error(
+ "person planning produced {0} chunks; the band column holds at most {MAX_PERSON_CHUNKS}"
+ )]
+ TooManyChunks(usize),
+}
+
+/// A claimed chunk narrowed to the person path: the range is proven present and the claim stamp is
+/// re-typed as the seed's LWW instant.
+#[derive(Debug, Clone, Copy)]
+pub struct PersonChunkSpec {
+ pub lease: ChunkLease,
+ pub team_id: TeamId,
+ pub range: PersonRange,
+ pub scanned_at: ScannedAtMs,
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum PersonChunkSpecError {
+ #[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("chunk {0:?} carries no person range; it does not belong to a person run")]
+ MissingRange(RunId),
+}
+
+/// A person run's participation rows and pinned payload, assembled by the store for validation.
+#[derive(Debug)]
+pub struct PersonPinnedSnapshot {
+ pub run_id: RunId,
+ pub team_id: TeamId,
+ pub timezone: String,
+ pub person_scan_since: Option<UtcMillis>,
+ pub pinned: Value,
+ pub participations: Vec<PinnedParticipation>,
+}
+
+/// A person run proven scannable: `scan_since` present, at least one condition surviving.
+#[derive(Debug)]
+pub struct PinnedPersonRun {
+ pub run_id: RunId,
+ pub team_id: TeamId,
+ pub scan_since: UtcMillis,
+ pub conditions: EvaluatedConditions,
+ pub horizon_days: u32,
+}
+
+#[derive(Debug)]
+pub struct ValidatedPinnedPersonRun {
+ pub run: PinnedPersonRun,
+ pub warnings: Vec<PinnedWarning>,
+ /// Active participations left with no surviving condition, ascending — they withhold the
+ /// planning proof exactly as behavioral uncovered cohorts do.
+ pub uncovered_cohorts: Vec<CohortId>,
+}
+
+/// A person run's validation outcome. `Retired` mirrors the behavioral zero-condition retirement:
+/// with every participation superseded, nothing expects coverage, so the run finishes as zero-work
+/// instead of failing.
+#[derive(Debug)]
+pub enum PersonRunValidation {
+ Seedable(ValidatedPinnedPersonRun),
+ Retired { warnings: Vec<PinnedWarning> },
+}
+
+#[derive(Debug, Deserialize)]
+struct PersonPinnedPayload {
+ schema_version: u32,
+ conditions: Vec<RawPersonPinnedCondition>,
+ person_horizon_days: u32,
+}
+
+#[derive(Debug, Deserialize)]
+struct RawPersonPinnedCondition {
+ cohort_id: i32,
+ condition_hash: String,
+}
+
+impl PinnedPersonRun {
+ pub fn validate(snapshot: PersonPinnedSnapshot) -> Result<PersonRunValidation, PinnedError> {
+ let payload: PersonPinnedPayload = serde_json::from_value(snapshot.pinned)?;
+ if payload.schema_version != 1 {
+ return Err(PinnedError::SchemaVersion(payload.schema_version));
+ }
+ let scan_since = snapshot
+ .person_scan_since
+ .ok_or(PinnedError::MissingPersonScanSince)?;
+ let mut warnings = Vec::new();
+ let tz = resolve_timezone(&snapshot.timezone, &mut warnings);
+ let participation = ParticipationSet::build(snapshot.team_id, snapshot.participations, tz)?;
+
+ let mut surviving: BTreeMap<ConditionHash, Arc<Vec<Value>>> = BTreeMap::new();
+ let mut covered: HashSet<CohortId> = HashSet::new();
+ for raw in payload.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;
+ }
+ match classify_person_condition(hash, participation.filters()) {
+ PersonSurvival::Survives(bytecode) => {
+ surviving.entry(hash).or_insert(bytecode);
+ covered.insert(cohort_id);
+ }
+ PersonSurvival::Dropped(reason) => {
+ warnings.push(PinnedWarning::ConditionDropped {
+ cohort_id,
+ hash,
+ reason,
+ });
+ }
+ }
+ }
+ let uncovered_cohorts = participation.uncovered_from(&covered);
+ if surviving.is_empty() && uncovered_cohorts.is_empty() {
+ // No active participation expects coverage (all superseded or none exist): retire.
+ // Zero survivors with an active participation stays terminal below — that cohort's
+ // pinned conditions dropped from the catalog, which is a genuine data problem.
+ return Ok(PersonRunValidation::Retired { warnings });
+ }
+ let conditions = EvaluatedConditions::new(surviving)?;
+
+ Ok(PersonRunValidation::Seedable(ValidatedPinnedPersonRun {
+ run: PinnedPersonRun {
+ run_id: snapshot.run_id,
+ team_id: snapshot.team_id,
+ scan_since,
+ conditions,
+ horizon_days: payload.person_horizon_days,
+ },
+ warnings,
+ uncovered_cohorts,
+ }))
+ }
+
+ /// Narrow a claimed chunk to the person path, after proving it belongs to this run/team. This
+ /// is the one deliberate `SChunkMs` → [`ScannedAtMs`] bridge: the claim stamp becomes the
+ /// seed's LWW instant, and re-claims re-stamp so LWW converges to the fresher snapshot.
+ pub fn chunk_spec(&self, spec: &ChunkSpec) -> Result<PersonChunkSpec, PersonChunkSpecError> {
+ if self.run_id != spec.lease.run_id() || self.team_id != spec.team_id {
+ return Err(PersonChunkSpecError::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,
+ });
+ }
+ let range = spec
+ .person_range
+ .ok_or(PersonChunkSpecError::MissingRange(spec.lease.run_id()))?;
+ Ok(PersonChunkSpec {
+ lease: spec.lease,
+ team_id: spec.team_id,
+ range,
+ scanned_at: ScannedAtMs(spec.s_chunk.0),
+ })
+ }
+}
+
+/// Whether one pinned hash survives against the frozen catalog — the structural mirror of the
+/// processor's `effective_hashes` projection.
+enum PersonSurvival {
+ Survives(Arc<Vec<Value>>),
+ Dropped(PinnedDropReason),
+}
+
+fn classify_person_condition(hash: ConditionHash, filters: &TeamFilters) -> PersonSurvival {
+ let bytes = hash.as_bytes();
+ if !filters.person_property_conditions.contains(&bytes) {
+ return PersonSurvival::Dropped(PinnedDropReason::AbsentFromFrozenCatalog);
+ }
+ match filters
+ .by_lsk
+ .get(&LeafStateKey::for_person_property(&bytes))
+ .map(|meta| meta.variant)
+ {
+ Some(StateVariant::PersonProperty) => {}
+ Some(_) => return PersonSurvival::Dropped(PinnedDropReason::VariantMismatch),
+ None => return PersonSurvival::Dropped(PinnedDropReason::AbsentFromFrozenCatalog),
+ }
+ match filters.by_condition_to_bytecode.get(&bytes) {
+ Some(bytecode) => PersonSurvival::Survives(Arc::clone(bytecode)),
+ None => PersonSurvival::Dropped(PinnedDropReason::AbsentFromFrozenCatalog),
+ }
+}
+
+/// The surviving person conditions: non-empty, sorted-distinct by hash, each with its frozen
+/// bytecode — so an empty `evaluated` or a hash/bytecode mismatch is unrepresentable at eval time.
+#[derive(Debug, Clone)]
+pub struct EvaluatedConditions(Vec<(ConditionHash, Arc<Vec<Value>>)>);
+
+// Non-empty by construction, so an `is_empty` would be a method whose contract is "never call me".
+#[allow(clippy::len_without_is_empty)]
+impl EvaluatedConditions {
+ fn new(surviving: BTreeMap<ConditionHash, Arc<Vec<Value>>>) -> Result<Self, PinnedError> {
+ if surviving.is_empty() {
+ return Err(PinnedError::NoSurvivingPersonConditions);
+ }
+ if surviving.len() > MAX_PERSON_SEED_HASHES {
+ return Err(PinnedError::PersonConditionsOverCap(surviving.len()));
+ }
+ Ok(Self(surviving.into_iter().collect()))
+ }
+
+ pub fn len(&self) -> usize {
+ self.0.len()
+ }
+
+ pub fn iter(&self) -> impl Iterator<Item = &(ConditionHash, Arc<Vec<Value>>)> {
+ self.0.iter()
+ }
+}
+
+/// The mint constants a chunk's seeds share.
+#[derive(Debug, Clone, Copy)]
+pub struct PersonSeedContext {
+ pub scanned_at: ScannedAtMs,
+ pub run_id: RunId,
+ pub claim_epoch: ClaimEpoch,
+}
+
+/// One scanned person's outcome.
+#[derive(Debug, PartialEq, Eq)]
+pub enum PersonRowOutcome {
+ Seed(PersonSeed),
+ /// Evaluated fully, nothing matched, and non-matcher emission is off.
+ NonMatcher,
+ Skipped(PersonRowSkip),
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PersonRowSkip {
+ InvalidPersonId,
+ InvalidProperties,
+ /// Every condition failed to evaluate; asserting FALSE for hashes the VM never answered would
+ /// mint wrong `Left`s, so the row emits nothing.
+ NothingEvaluated,
+}
+
+impl PersonRowSkip {
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::InvalidPersonId => "invalid_person_id",
+ Self::InvalidProperties => "invalid_properties",
+ Self::NothingEvaluated => "nothing_evaluated",
+ }
+ }
+}
+
+/// The pure per-row fold: build scan globals, run every surviving condition through the shared
+/// evaluator, and mint at most one [`PersonSeed`]. Unit-testable without ClickHouse or Kafka.
+pub struct PersonEvaluator {
+ team_id: TeamId,
+ conditions: EvaluatedConditions,
+ evaluator: CohortEvaluator,
+ emit_nonmatchers: bool,
+}
+
+impl PersonEvaluator {
+ pub fn new(team_id: TeamId, conditions: EvaluatedConditions, emit_nonmatchers: bool) -> Self {
+ Self {
+ team_id,
+ conditions,
+ evaluator: CohortEvaluator::new(),
+ emit_nonmatchers,
+ }
+ }
+
+ pub fn evaluate_row(
+ &mut self,
+ person_id: &str,
+ properties: &str,
+ ctx: &PersonSeedContext,
+ ) -> (PersonRowOutcome, RecordStats) {
+ let mut stats = RecordStats::default();
+ let Ok(person_id) = Uuid::parse_str(person_id) else {
+ return (
+ PersonRowOutcome::Skipped(PersonRowSkip::InvalidPersonId),
+ stats,
+ );
+ };
+ let Ok(globals) = build_person_scan_globals(self.team_id, person_id, properties) else {
+ return (
+ PersonRowOutcome::Skipped(PersonRowSkip::InvalidProperties),
+ stats,
+ );
+ };
+ self.evaluator.set_globals(globals);
+
+ let mut evaluated = Vec::with_capacity(self.conditions.len());
+ let mut matched = Vec::new();
+ for (hash, bytecode) in self.conditions.iter() {
+ match self.evaluator.evaluate_detailed(Arc::clone(bytecode)) {
+ EvalOutcome::Matched(true) => {
+ evaluated.push(*hash);
+ matched.push(*hash);
+ stats.matched += 1;
+ }
+ EvalOutcome::Matched(false) => {
+ evaluated.push(*hash);
+ stats.non_matched += 1;
+ }
+ // A hash the VM never answered is excluded from `evaluated`: its absence from
+ // `matched` would otherwise assert FALSE and mint a wrong `Left`.
+ EvalOutcome::UnknownFunction(_) => stats.unknown_functions += 1,
+ EvalOutcome::VmError(error) => stats
+ .vm_failures
+ .increment(classify_vm_error(&error))
+ .expect("per-row VM failure counts are bounded by the condition cap"),
+ }
+ }
+ if evaluated.is_empty() {
+ return (
+ PersonRowOutcome::Skipped(PersonRowSkip::NothingEvaluated),
+ stats,
+ );
+ }
+ if matched.is_empty() && !self.emit_nonmatchers {
+ return (PersonRowOutcome::NonMatcher, stats);
+ }
+ let seed = PersonSeed::new(
+ self.team_id,
+ person_id,
+ evaluated,
+ matched,
+ ctx.scanned_at,
+ ctx.run_id,
+ ctx.claim_epoch,
+ )
+ .expect("sorted-distinct subset by construction with a positive claim stamp");
+ (PersonRowOutcome::Seed(seed), stats)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use cohort_core::filters::LeafStateMeta;
+ use proptest::prelude::*;
+ use serde_json::json;
+
+ use super::super::chunk::BandSpec;
+ use super::super::ids::{ChunkId, SChunkMs};
+ use super::*;
+
+ fn hash(value: &str) -> ConditionHash {
+ ConditionHash::parse(value).unwrap()
+ }
+
+ fn person_bytecode(key: &str, value: &str) -> Value {
+ json!([
+ "_H",
+ 1,
+ 32,
+ value,
+ 32,
+ key,
+ 32,
+ "properties",
+ 32,
+ "person",
+ 1,
+ 3,
+ 11
+ ])
+ }
+
+ fn person_filter_leaves(leaves: &[(&str, &str, &str)]) -> Value {
+ let values = leaves
+ .iter()
+ .map(|(hash, key, value)| {
+ json!({
+ "type": "person",
+ "key": key,
+ "value": value,
+ "operator": "exact",
+ "conditionHash": hash,
+ "bytecode": person_bytecode(key, value),
+ })
+ })
+ .collect::<Vec<_>>();
+ json!({ "properties": { "type": "AND", "values": values } })
+ }
+
+ fn participation(cohort_id: i32, filters: Value, superseded: bool) -> PinnedParticipation {
+ PinnedParticipation {
+ cohort_id: CohortId(cohort_id),
+ pinned_filters: filters,
+ state: if superseded {
+ PinnedParticipationState::Superseded
+ } else {
+ PinnedParticipationState::Active
+ },
+ }
+ }
+
+ fn pinned(conditions: &[(i32, &str)]) -> Value {
+ let conditions = conditions
+ .iter()
+ .map(|(cohort_id, hash)| json!({ "cohort_id": cohort_id, "condition_hash": hash }))
+ .collect::<Vec<_>>();
+ json!({ "schema_version": 1, "conditions": conditions, "person_horizon_days": 30 })
+ }
+
+ fn snapshot(pinned: Value, participations: Vec<PinnedParticipation>) -> PersonPinnedSnapshot {
+ PersonPinnedSnapshot {
+ run_id: RunId(Uuid::nil()),
+ team_id: TeamId(2),
+ timezone: "UTC".to_string(),
+ person_scan_since: Some(UtcMillis::new(1_780_000_000_000)),
+ pinned,
+ participations,
+ }
+ }
+
+ const HASH_A: &str = "aaaaaaaaaaaaaaaa";
+ const HASH_B: &str = "bbbbbbbbbbbbbbbb";
+
+ fn seedable(validation: Result<PersonRunValidation, PinnedError>) -> ValidatedPinnedPersonRun {
+ match validation.unwrap() {
+ PersonRunValidation::Seedable(validated) => validated,
+ PersonRunValidation::Retired { .. } => panic!("expected a seedable run"),
+ }
+ }
+
+ #[test]
+ fn tile_ranges_covers_the_full_space_for_no_boundaries() {
+ let ranges = tile_ranges(&[]).unwrap();
+ assert_eq!(ranges.len(), 1);
+ assert_eq!(ranges[0].lo(), Uuid::nil());
+ assert_eq!(ranges[0].hi(), None);
+ }
+
+ proptest! {
+ /// Structural tiling only — no ordering assertions, by design: boundaries are opaque
+ /// ClickHouse-order values and the tiling must preserve their arrival order.
+ #[test]
+ fn tile_ranges_is_structural_and_order_preserving(
+ raw in prop::collection::vec(any::<u128>(), 0..64),
+ duplicate_at in any::<prop::sample::Index>(),
+ ) {
+ let mut boundaries: Vec<Uuid> = raw.iter().copied().map(Uuid::from_u128).collect();
+ if !boundaries.is_empty() {
+ let index = duplicate_at.index(boundaries.len());
+ boundaries.insert(index, boundaries[index]);
+ }
+ let ranges = tile_ranges(&boundaries).unwrap();
+
+ prop_assert_eq!(ranges[0].lo(), Uuid::nil());
+ prop_assert_eq!(ranges[ranges.len() - 1].hi(), None);
+ prop_assert!(ranges.len() <= boundaries.len() + 1);
+ for pair in ranges.windows(2) {
+ prop_assert_eq!(pair[0].hi(), Some(pair[1].lo()));
+ }
+ // The kept boundaries appear as endpoints in their arrival order.
+ let mut endpoints = ranges.iter().filter_map(|range| range.hi());
+ let mut previous = Uuid::nil();
+ for boundary in &boundaries {
+ if *boundary == previous {
+ continue;
+ }
+ prop_assert_eq!(endpoints.next(), Some(*boundary));
+ previous = *boundary;
+ }
+ prop_assert!(ranges.iter().all(|range| range.hi() != Some(range.lo())));
+ }
+ }
+
+ #[test]
+ fn validate_covers_survival_drops_and_terminal_failures() {
+ let active = person_filter_leaves(&[(HASH_A, "email", "[email protected]")]);
+
+ // Wrong schema version.
+ let mut wrong_schema = pinned(&[(1, HASH_A)]);
+ wrong_schema["schema_version"] = json!(2);
+ assert!(matches!(
+ PinnedPersonRun::validate(snapshot(
+ wrong_schema,
+ vec![participation(1, active.clone(), false)]
+ )),
+ Err(PinnedError::SchemaVersion(2))
+ ));
+
+ // Missing person_scan_since is terminal.
+ let mut no_since = snapshot(
+ pinned(&[(1, HASH_A)]),
+ vec![participation(1, active.clone(), false)],
+ );
+ no_since.person_scan_since = None;
+ assert!(matches!(
+ PinnedPersonRun::validate(no_since),
+ Err(PinnedError::MissingPersonScanSince)
+ ));
+
+ // A hash absent from the frozen catalog warns, drops, and leaves the cohort uncovered.
+ let validated = seedable(PinnedPersonRun::validate(snapshot(
+ pinned(&[(1, HASH_A), (2, HASH_B)]),
+ vec![
+ participation(1, active.clone(), false),
+ participation(
+ 2,
+ json!({ "properties": { "type": "AND", "values": [] } }),
+ false,
+ ),
+ ],
+ )));
+ assert_eq!(
+ validated
+ .run
+ .conditions
+ .iter()
+ .map(|(hash, _)| *hash)
+ .collect::<Vec<_>>(),
+ vec![hash(HASH_A)]
+ );
+ assert_eq!(validated.uncovered_cohorts, vec![CohortId(2)]);
+ assert!(validated
+ .warnings
+ .contains(&PinnedWarning::ConditionDropped {
+ cohort_id: CohortId(2),
+ hash: hash(HASH_B),
+ reason: PinnedDropReason::AbsentFromFrozenCatalog,
+ }));
+ assert_eq!(validated.run.horizon_days, 30);
+
+ // A superseded cohort's hash warns distinctly and expects no coverage.
+ let validated = seedable(PinnedPersonRun::validate(snapshot(
+ pinned(&[(1, HASH_A), (2, HASH_B)]),
+ vec![
+ participation(1, active.clone(), false),
+ participation(2, person_filter_leaves(&[(HASH_B, "plan", "paid")]), true),
+ ],
+ )));
+ assert_eq!(validated.run.conditions.len(), 1);
+ assert!(validated.uncovered_cohorts.is_empty());
+ assert!(validated
+ .warnings
+ .contains(&PinnedWarning::ConditionSuperseded {
+ cohort_id: CohortId(2),
+ hash: hash(HASH_B),
+ }));
+
+ // A condition naming a cohort outside the participations is a hard error.
+ assert!(matches!(
+ PinnedPersonRun::validate(snapshot(
+ pinned(&[(9, HASH_A)]),
+ vec![participation(1, active.clone(), false)],
+ )),
+ Err(PinnedError::MissingParticipation(9))
+ ));
+
+ // Cross-cohort duplicate hashes dedup to one evaluated condition covering both cohorts.
+ let validated = seedable(PinnedPersonRun::validate(snapshot(
+ pinned(&[(1, HASH_A), (2, HASH_A)]),
+ vec![
+ participation(1, active.clone(), false),
+ participation(
+ 2,
+ person_filter_leaves(&[(HASH_A, "email", "[email protected]")]),
+ false,
+ ),
+ ],
+ )));
+ assert_eq!(validated.run.conditions.len(), 1);
+ assert!(validated.uncovered_cohorts.is_empty());
+
+ // Zero surviving hashes with an active participation is terminal — that cohort's pinned
+ // conditions dropped from the catalog, a genuine data problem.
+ assert!(matches!(
+ PinnedPersonRun::validate(snapshot(
+ pinned(&[(1, HASH_B)]),
+ vec![participation(1, active.clone(), false)],
+ )),
+ Err(PinnedError::NoSurvivingPersonConditions)
+ ));
+
+ // Every participation superseded: nothing expects coverage, so the run retires as
+ // zero-work instead of failing (the behavioral zero-condition semantics).
+ assert!(matches!(
+ PinnedPersonRun::validate(snapshot(
+ pinned(&[(1, HASH_A)]),
+ vec![participation(1, active, true)],
+ )),
+ Ok(PersonRunValidation::Retired { warnings })
+ if warnings.contains(&PinnedWarning::ConditionSuperseded {
+ cohort_id: CohortId(1),
+ hash: hash(HASH_A),
+ })
+ ));
+ }
+
+ #[test]
+ fn validate_enforces_the_seed_hash_cap() {
+ let leaves: Vec<(String, String)> = (0..=MAX_PERSON_SEED_HASHES)
+ .map(|index| (format!("{index:016}"), format!("key{index}")))
+ .collect();
+ let leaf_refs: Vec<(&str, &str, &str)> = leaves
+ .iter()
+ .map(|(hash, key)| (hash.as_str(), key.as_str(), "v"))
+ .collect();
+ let conditions: Vec<(i32, &str)> =
+ leaves.iter().map(|(hash, _)| (1, hash.as_str())).collect();
+ assert!(matches!(
+ PinnedPersonRun::validate(snapshot(
+ pinned(&conditions),
+ vec![participation(1, person_filter_leaves(&leaf_refs), false)],
+ )),
+ Err(PinnedError::PersonConditionsOverCap(count)) if count == MAX_PERSON_SEED_HASHES + 1
+ ));
+ }
+
+ /// A hash present in the person-condition set whose leaf-state entry resolves to a behavioral
+ /// variant must drop with the distinct reason — the mirror of the processor's projection.
+ #[test]
+ fn a_variant_mismatched_hash_drops_distinctly() {
+ let mut filters = TeamFilters::default();
+ let bytes = hash(HASH_A).as_bytes();
+ filters.person_property_conditions.insert(bytes);
+ filters.by_lsk.insert(
+ LeafStateKey::for_person_property(&bytes),
+ LeafStateMeta {
+ variant: StateVariant::BehavioralSingle,
+ condition_hash: bytes,
+ window: None,
+ window_days: None,
+ predicate_op: None,
+ },
+ );
+ assert!(matches!(
+ classify_person_condition(hash(HASH_A), &filters),
+ PersonSurvival::Dropped(PinnedDropReason::VariantMismatch)
+ ));
+ }
+
+ fn seedable_run() -> ValidatedPinnedPersonRun {
+ seedable(PinnedPersonRun::validate(snapshot(
+ pinned(&[(1, HASH_A), (1, HASH_B)]),
+ vec![participation(
+ 1,
+ person_filter_leaves(&[(HASH_A, "email", "[email protected]"), (HASH_B, "plan", "paid")]),
+ false,
+ )],
+ )))
+ }
+
+ fn build_evaluator(emit_nonmatchers: bool) -> PersonEvaluator {
+ PersonEvaluator::new(TeamId(2), seedable_run().run.conditions, emit_nonmatchers)
+ }
+
+ const CLAIM_STAMP_MS: i64 = 1_783_470_000_000;
+
+ fn claimed_spec(
+ run_id: RunId,
+ team_id: TeamId,
+ person_range: Option<PersonRange>,
+ ) -> ChunkSpec {
+ ChunkSpec {
+ lease: ChunkLease::new(ChunkId(Uuid::from_u128(11)), run_id, ClaimEpoch(3)),
+ team_id,
+ day: 0,
+ band: BandSpec::new(0, 1).unwrap(),
+ s_chunk: SChunkMs(CLAIM_STAMP_MS),
+ person_range,
+ }
+ }
+
+ /// The narrowing guard fences the scan: a chunk from another run or team must never be scanned
+ /// against this run's conditions, and a chunk with no range is a behavioral chunk — scanning it
+ /// would sweep the entire UUID space. The accepted case pins the one deliberate claim-stamp →
+ /// `scanned_at` bridge.
+ #[test]
+ fn chunk_spec_admits_only_this_runs_ranged_chunks() {
+ let run = seedable_run().run;
+ let range = PersonRange::new(Uuid::nil(), None).unwrap();
+
+ assert!(matches!(
+ run.chunk_spec(&claimed_spec(
+ RunId(Uuid::from_u128(9)),
+ run.team_id,
+ Some(range)
+ )),
+ Err(PersonChunkSpecError::RunMismatch { .. })
+ ));
+ assert!(matches!(
+ run.chunk_spec(&claimed_spec(run.run_id, TeamId(3), Some(range))),
+ Err(PersonChunkSpecError::RunMismatch { .. })
+ ));
+ assert!(matches!(
+ run.chunk_spec(&claimed_spec(run.run_id, run.team_id, None)),
+ Err(PersonChunkSpecError::MissingRange(_))
+ ));
+
+ let spec = run
+ .chunk_spec(&claimed_spec(run.run_id, run.team_id, Some(range)))
+ .unwrap();
+ assert_eq!(spec.range, range);
+ assert_eq!(spec.scanned_at, ScannedAtMs(CLAIM_STAMP_MS));
+ }
+
+ fn context() -> PersonSeedContext {
+ PersonSeedContext {
+ scanned_at: ScannedAtMs(1_783_470_000_000),
+ run_id: RunId(Uuid::nil()),
+ claim_epoch: ClaimEpoch(1),
+ }
+ }
+
+ #[test]
+ fn evaluate_row_mints_sorted_subset_seeds_and_classifies_skips() {
+ let person = Uuid::from_u128(7).to_string();
+ let ctx = context();
+
+ // One matching condition of two: evaluated carries both, matched the sorted subset.
+ let mut evaluator = build_evaluator(true);
+ let (outcome, stats) =
+ evaluator.evaluate_row(&person, r#"{"email":"[email protected]","plan":"free"}"#, &ctx);
+ let PersonRowOutcome::Seed(seed) = outcome else {
+ panic!("expected a seed, got {outcome:?}");
+ };
+ assert_eq!(seed.evaluated(), &[hash(HASH_A), hash(HASH_B)]);
+ assert_eq!(seed.matched(), &[hash(HASH_A)]);
+ assert_eq!(seed.scanned_at_ms(), ctx.scanned_at);
+ assert_eq!((stats.matched, stats.non_matched), (1, 1));
+
+ // Non-matcher with emission on: an empty-matched healing seed.
+ let (outcome, _) = evaluator.evaluate_row(&person, r#"{"email":"x"}"#, &ctx);
+ let PersonRowOutcome::Seed(seed) = outcome else {
+ panic!("expected a healing seed, got {outcome:?}");
+ };
+ assert!(seed.matched().is_empty());
+
+ // Non-matcher with emission off: skipped.
+ let mut quiet = build_evaluator(false);
+ let (outcome, stats) = quiet.evaluate_row(&person, r#"{"email":"x"}"#, &ctx);
+ assert_eq!(outcome, PersonRowOutcome::NonMatcher);
+ assert_eq!(stats.non_matched, 2);
+
+ // Invalid person id and malformed properties are classified, never minted.
+ let mut evaluator = build_evaluator(true);
+ let (outcome, _) = evaluator.evaluate_row("not-a-uuid", "{}", &ctx);
+ assert_eq!(
+ outcome,
+ PersonRowOutcome::Skipped(PersonRowSkip::InvalidPersonId)
+ );
+ let (outcome, _) = evaluator.evaluate_row(&person, "{not json", &ctx);
+ assert_eq!(
+ outcome,
+ PersonRowOutcome::Skipped(PersonRowSkip::InvalidProperties)
+ );
+ }
+
+ /// Live-equivalence anchor: for identical person properties, the scan fold reaches exactly the
+ /// verdict the live event path reaches through `build_person_property_globals` (byte-equal
+ /// globals are pinned in cohort-core; this pins the verdict end to end).
+ #[test]
+ fn evaluate_row_matches_the_live_event_paths_verdict() {
+ use cohort_core::events::CohortStreamEvent;
+ use cohort_core::hogvm::build_person_property_globals;
+
+ let person = Uuid::from_u128(7);
+ let ctx = context();
+ for properties in [r#"{"email":"[email protected]","plan":"paid"}"#, r#"{"email":"x"}"#] {
+ let event = CohortStreamEvent {
+ team_id: 2,
+ person_id: person.to_string(),
+ distinct_id: person.to_string(),
+ uuid: Uuid::from_u128(1).to_string(),
+ event: "$pageview".to_string(),
+ timestamp: "2026-05-26 12:34:56.789000".to_string(),
+ properties: Some("{}".to_string()),
+ person_properties: Some(properties.to_string()),
+ elements_chain: None,
+ source_offset: 0,
+ source_partition: -1,
+ redirected_from: None,
+ redirect_hops: 0,
+ };
+ let globals = build_person_property_globals(&event).unwrap();
+ let mut evaluator = build_evaluator(true);
+ let (outcome, _) = evaluator.evaluate_row(&person.to_string(), properties, &ctx);
+ let PersonRowOutcome::Seed(seed) = outcome else {
+ panic!("expected a seed, got {outcome:?}");
+ };
+ for (hash, bytecode) in build_evaluator(true).conditions.iter() {
+ let live = matches!(
+ cohort_core::hogvm::evaluate_detailed(bytecode, globals.clone()),
+ EvalOutcome::Matched(true)
+ );
+ assert_eq!(seed.matched().contains(hash), live, "hash {hash} diverged");
+ }
+ }
+ }
+
+ /// A condition whose bytecode fails the VM is excluded from `evaluated` — the seed must never
+ /// assert FALSE for a hash the VM never answered — and an all-failure row emits nothing.
+ #[test]
+ fn vm_failures_drop_hashes_from_evaluated_rather_than_asserting_false() {
+ let broken = json!([]);
+ let mut leaves = person_filter_leaves(&[(HASH_A, "email", "[email protected]")]);
+ leaves["properties"]["values"]
+ .as_array_mut()
+ .unwrap()
+ .push(json!({
+ "type": "person",
+ "key": "plan",
+ "value": "paid",
+ "operator": "exact",
+ "conditionHash": HASH_B,
+ "bytecode": broken,
+ }));
+ let validated = seedable(PinnedPersonRun::validate(snapshot(
+ pinned(&[(1, HASH_A), (1, HASH_B)]),
+ vec![participation(1, leaves, false)],
+ )));
+ let mut evaluator = PersonEvaluator::new(TeamId(2), validated.run.conditions, true);
+ let ctx = context();
+
+ let (outcome, stats) = evaluator.evaluate_row(
+ &Uuid::from_u128(7).to_string(),
+ r#"{"email":"[email protected]"}"#,
+ &ctx,
+ );
+ let PersonRowOutcome::Seed(seed) = outcome else {
+ panic!("expected a seed, got {outcome:?}");
+ };
+ assert_eq!(seed.evaluated(), &[hash(HASH_A)]);
+ assert_eq!(
+ stats
+ .vm_failures
+ .iter()
+ .map(|(_, count)| count)
+ .sum::<u32>(),
+ 1
+ );
+ }
+}
diff --git a/rust/cohort-seeder/src/domain/pinned.rs b/rust/cohort-seeder/src/domain/pinned.rs
index 8443bb920c36..0ce4b63d59c2 100644
--- a/rust/cohort-seeder/src/domain/pinned.rs
+++ b/rust/cohort-seeder/src/domain/pinned.rs
@@ -108,6 +108,8 @@ pub enum PinnedParticipationState {
pub enum PinnedDropReason {
ActionKeyed,
AbsentFromFrozenCatalog,
+ /// Person runs only: the frozen catalog resolves the hash to a non-person-property leaf.
+ VariantMismatch,
}
impl PinnedDropReason {
@@ -115,6 +117,7 @@ impl PinnedDropReason {
match self {
Self::ActionKeyed => "action_keyed",
Self::AbsentFromFrozenCatalog => "absent_from_frozen_catalog",
+ Self::VariantMismatch => "variant_mismatch",
}
}
}
@@ -161,6 +164,12 @@ pub enum PinnedError {
Filters(#[from] FilterError),
#[error("frozen catalog metadata is incomplete for condition {0}")]
IncompleteMetadata(ConditionHash),
+ #[error("person run has no pinned person_scan_since")]
+ MissingPersonScanSince,
+ #[error("no pinned person condition survived validation; nothing would be seeded")]
+ NoSurvivingPersonConditions,
+ #[error("surviving person conditions exceed the per-seed hash cap: {0}")]
+ PersonConditionsOverCap(usize),
}
#[derive(Debug, Deserialize)]
@@ -271,7 +280,7 @@ fn parse_payload(pinned: Value) -> Result<PinnedPayload, PinnedError> {
Ok(payload)
}
-fn resolve_timezone(configured: &str, warnings: &mut Vec<PinnedWarning>) -> Tz {
+pub(super) 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 {
@@ -282,14 +291,14 @@ fn resolve_timezone(configured: &str, warnings: &mut Vec<PinnedWarning>) -> Tz {
}
/// The participations of a run, indexed for dedup-checked lookup with the frozen filter catalog
-/// already built from the active cohorts.
-struct ParticipationSet {
+/// already built from the active cohorts. Shared with the sibling person-run validation.
+pub(super) struct ParticipationSet {
states: HashMap<CohortId, PinnedParticipationState>,
filters: TeamFilters,
}
impl ParticipationSet {
- fn build(
+ pub(super) fn build(
team_id: TeamId,
participations: Vec<PinnedParticipation>,
tz: Tz,
@@ -319,10 +328,14 @@ impl ParticipationSet {
})
}
- fn state(&self, cohort_id: CohortId) -> Option<PinnedParticipationState> {
+ pub(super) fn state(&self, cohort_id: CohortId) -> Option<PinnedParticipationState> {
self.states.get(&cohort_id).copied()
}
+ pub(super) fn filters(&self) -> &TeamFilters {
+ &self.filters
+ }
+
/// The active cohorts no surviving condition references, ascending. Conditions drop per cohort
/// (`ActionKeyed`, `AbsentFromFrozenCatalog`), independently of participation state.
fn uncovered_cohorts(&self, conditions: &[PinnedCondition]) -> Vec<CohortId> {
@@ -330,6 +343,11 @@ impl ParticipationSet {
.iter()
.map(|condition| condition.cohort_id)
.collect();
+ self.uncovered_from(&covered)
+ }
+
+ /// The active cohorts absent from `covered`, ascending.
+ pub(super) fn uncovered_from(&self, covered: &HashSet<CohortId>) -> Vec<CohortId> {
let mut uncovered = self
.states
.iter()
diff --git a/rust/cohort-seeder/src/kafka/producer.rs b/rust/cohort-seeder/src/kafka/producer.rs
index e6a3a90dccf9..0877e15c5a5b 100644
--- a/rust/cohort-seeder/src/kafka/producer.rs
+++ b/rust/cohort-seeder/src/kafka/producer.rs
@@ -12,7 +12,9 @@ use common_liveness::SyncLivenessReporter;
use rdkafka::error::{KafkaError, RDKafkaErrorCode};
use rdkafka::producer::{DeliveryFuture, FutureProducer, FutureRecord, Producer};
-use crate::domain::{MembershipPartition, NextOffset, ReconcileTile, SeedTile, WatchPositions};
+use crate::domain::{
+ MembershipPartition, NextOffset, PersonSeed, ReconcileTile, SeedTile, WatchPositions,
+};
pub use crate::domain::partition::{SeedPartition, SeedPartitionCountError, SeedPartitions};
@@ -94,6 +96,15 @@ impl SeedTileProducer {
.map_err(|(error, _)| error.into())
}
+ pub fn enqueue_person(&self, seed: &PersonSeed) -> Result<DeliveryFuture, EnqueueError> {
+ let payload = serde_json::to_vec(seed).expect("PersonSeed serialization cannot fail");
+ let key = seed.partition_key();
+ let record = FutureRecord::to(&self.topic).key(&key).payload(&payload);
+ self.producer
+ .send_result(record)
+ .map_err(|(error, _)| error.into())
+ }
+
pub fn enqueue_reconcile(
&self,
tile: &ReconcileTile,
diff --git a/rust/cohort-seeder/src/main.rs b/rust/cohort-seeder/src/main.rs
index 83f6437d55bb..da86d8a96b73 100644
--- a/rust/cohort-seeder/src/main.rs
+++ b/rust/cohort-seeder/src/main.rs
@@ -18,10 +18,12 @@ use tracing_subscriber::{fmt, EnvFilter, Layer};
use cohort_seeder::app::{
AutoDispatchPolicy, CompletionDriver, KafkaCommittedOffsets, KafkaTopicOffsets,
- MarkerWatchTask, ObservePolicy, OrchestratorSettings, PgMarkerFlush, SeederOrchestrator,
- WatchDirectives, MARKER_WATCH_LIVENESS_DEADLINE, ORCHESTRATOR_LIVENESS_DEADLINE,
+ MarkerWatchTask, ObservePolicy, OrchestratorSettings, PersonComponents, PgMarkerFlush,
+ SeederOrchestrator, WatchDirectives, MARKER_WATCH_LIVENESS_DEADLINE,
+ ORCHESTRATOR_LIVENESS_DEADLINE,
};
use cohort_seeder::clickhouse::client::build_client;
+use cohort_seeder::clickhouse::person_scanner::PersonScanner;
use cohort_seeder::clickhouse::scanner::ChunkScanner;
use cohort_seeder::config::Config;
use cohort_seeder::kafka::committed::SeedGroupOffsetReader;
@@ -87,7 +89,8 @@ async fn async_main(config: Config) -> Result<()> {
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 clickhouse_client = build_client(&config).context("building ClickHouse client")?;
+ let scanner = ChunkScanner::new(clickhouse_client.clone());
let producer = SeedTileProducer::new(
&config.build_kafka_config(),
config.seed_events_topic.clone(),
@@ -109,6 +112,11 @@ async fn async_main(config: Config) -> Result<()> {
);
let settings =
OrchestratorSettings::try_from(&config).context("validating orchestrator settings")?;
+ // Shares the built ClickHouse client with the behavioral scanner.
+ let person = settings.person().map(|person_settings| PersonComponents {
+ scanner: PersonScanner::new(clickhouse_client),
+ pacer: TilePacer::new(person_settings.seeds_per_sec),
+ });
let completion = build_completion(&config, &pool, &producer, observe_policy, watch_handle)
.await
.context("validating completion driver policies")?;
@@ -123,6 +131,7 @@ async fn async_main(config: Config) -> Result<()> {
seeder_handle,
claimed_by,
completion.driver,
+ person,
);
let guard = manager.monitor_background();
@@ -295,6 +304,11 @@ fn log_startup(config: &Config) {
bands_per_day = config.seeder_bands_per_day,
tiles_per_second = config.seeder_tiles_per_sec,
max_inflight_tiles = config.seeder_max_inflight_tiles,
+ person_seeds_enabled = config.seeder_person_seeds_enabled,
+ person_seeds_per_sec = config.seeder_person_seeds_per_sec,
+ persons_per_chunk = config.seeder_persons_per_chunk,
+ person_max_concurrent_chunks = config.seeder_person_max_concurrent_chunks,
+ person_emit_nonmatchers = config.seeder_person_emit_nonmatchers,
reconcile_auto_dispatch_enabled = config.seeder_reconcile_auto_dispatch_enabled,
confirm_register_backfilled = config.seeder_confirm_register_backfilled,
reconcile_max_concurrent_dispatches = config.seeder_reconcile_max_concurrent_dispatches,
diff --git a/rust/cohort-seeder/src/observability/metrics.rs b/rust/cohort-seeder/src/observability/metrics.rs
index bf90e9512f74..f7f3c904fe70 100644
--- a/rust/cohort-seeder/src/observability/metrics.rs
+++ b/rust/cohort-seeder/src/observability/metrics.rs
@@ -1,6 +1,10 @@
//! 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.
+//! dashboards depend on), the shared RAII duration timer, and the Prometheus recorder installer.
+//! Depends on the metrics crates only.
+use std::time::{Duration, Instant};
+
+use metrics::histogram;
use metrics_exporter_prometheus::{BuildError, PrometheusBuilder, PrometheusHandle};
pub const RUNS_DISCOVERED: &str = "seeder_runs_discovered_total";
@@ -58,6 +62,45 @@ pub const RECONCILE_OBSERVATION_STALLED_AGE_SECONDS: &str =
pub const RECONCILE_OBSERVATION_PASS_SECONDS: &str = "seeder_reconcile_observation_pass_seconds";
pub const RECONCILE_OBSERVE_ERRORS: &str = "seeder_reconcile_observe_errors_total";
pub const RECONCILE_RUNS_UNDISPATCHED: &str = "seeder_reconcile_runs_undispatched";
+// Person-property seed path.
+pub const PERSONS_SCANNED: &str = "seeder_persons_scanned_total";
+pub const PERSON_SEEDS_PRODUCED: &str = "seeder_person_seeds_produced_total";
+pub const PERSON_NONMATCHERS_SKIPPED: &str = "seeder_person_nonmatchers_skipped_total";
+pub const PERSON_ROWS_SKIPPED: &str = "seeder_person_rows_skipped_total";
+pub const PERSON_HOGVM_ERRORS: &str = "seeder_person_hogvm_errors_total";
+pub const PERSON_BOUNDARIES_PLANNED: &str = "seeder_person_boundaries_planned_total";
+pub const PERSON_PLANNING_DURATION_SECONDS: &str = "seeder_person_planning_duration_seconds";
+/// Deliberately its own metric rather than [`CHUNK_SCAN_DURATION_SECONDS`] under a `kind` label:
+/// the person path interleaves scan, evaluation, and paced enqueue into one inseparable loop, so
+/// this spans all three, where the behavioral metric times the ClickHouse scan alone and accounts
+/// delivery separately. One name across both would compare unlike spans.
+pub const PERSON_CHUNK_SCAN_DURATION_SECONDS: &str = "seeder_person_chunk_scan_duration_seconds";
+
+/// Records its lifetime into `metric` on drop, so every exit — early return, halt, cancellation —
+/// is sampled without a recording site per path.
+pub struct MetricTimer {
+ metric: &'static str,
+ started: Instant,
+}
+
+impl MetricTimer {
+ pub fn start(metric: &'static str) -> Self {
+ Self {
+ metric,
+ started: Instant::now(),
+ }
+ }
+
+ pub fn elapsed(&self) -> Duration {
+ self.started.elapsed()
+ }
+}
+
+impl Drop for MetricTimer {
+ fn drop(&mut self) {
+ histogram!(self.metric).record(self.started.elapsed().as_secs_f64());
+ }
+}
pub fn install_recorder() -> Result<PrometheusHandle, BuildError> {
PrometheusBuilder::new().install_recorder()
diff --git a/rust/cohort-seeder/src/store/chunks.rs b/rust/cohort-seeder/src/store/chunks.rs
index 77fa5d79795c..6d637aaad833 100644
--- a/rust/cohort-seeder/src/store/chunks.rs
+++ b/rust/cohort-seeder/src/store/chunks.rs
@@ -14,15 +14,16 @@ 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 sqlx::{Connection, 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,
+ bands_for_day, person_chunk_sentinel_day, Band, BandSpec, BandSpecError, ChunkId, ChunkLease,
+ ChunkSpec, ChunkStatus, ClaimEpoch, ClaimKind, ClaimedChunk, EnqueuedChunk, Halted,
+ PersonRange, PersonRangeError, ProduceHwms, ProducedChunk, RunId, SChunkMs, ScannedChunk,
+ StreamedChunk,
};
use super::lease::LeaseHandle;
@@ -106,6 +107,121 @@ impl PgChunkStore {
Ok(PlanOutcome::Planned { inserted })
}
+ /// Try to claim the cluster-wide planning slot for one person run, so at most one replica runs
+ /// the full-table ClickHouse boundary aggregation per run. The claim is a session advisory
+ /// lock on a connection detached from the pool: releasing (or crashing — the socket closes)
+ /// frees it, and it can never leak back into the pool still holding the lock.
+ pub async fn try_claim_person_planning(
+ &self,
+ run_id: RunId,
+ ) -> Result<Option<PersonPlanningClaim>, ChunkStoreError> {
+ let mut connection = self.pool.acquire().await?.detach();
+ let claimed = sqlx::query_scalar::<_, bool>(PERSON_PLANNING_LOCK_SQL)
+ .bind(run_id)
+ .fetch_one(&mut connection)
+ .await;
+ match claimed {
+ Ok(true) => Ok(Some(PersonPlanningClaim {
+ connection: Some(connection),
+ run_id,
+ })),
+ Ok(false) => {
+ connection.close().await.ok();
+ Ok(None)
+ }
+ Err(error) => {
+ connection.close().await.ok();
+ Err(error.into())
+ }
+ }
+ }
+
+ /// Plan a person run's UUID-range chunks under one all-or-nothing statement: `FOR UPDATE` on
+ /// the `seeding` run row plus a `NOT EXISTS` chunks gate, one row per range under the
+ /// far-future sentinel day with `band` = ordinal. Deliberately no `ON CONFLICT`: under READ
+ /// COMMITTED a lock-waiting loser re-checks only the locked row against its stale snapshot, so
+ /// its `NOT EXISTS` can pass after the winner commits — but band 0 always exists, so the
+ /// `(run, day, band)` unique constraint aborts the loser atomically. Mixing two planners'
+ /// boundary sets is thereby impossible.
+ pub async fn plan_person_chunks(
+ &self,
+ run_id: RunId,
+ ranges: &[PersonRange],
+ ) -> Result<PlanOutcome, ChunkStoreError> {
+ if ranges.is_empty() {
+ return Ok(PlanOutcome::Planned { inserted: 0 });
+ }
+ let mut ids = Vec::with_capacity(ranges.len());
+ let mut bands = Vec::with_capacity(ranges.len());
+ let mut lows = Vec::with_capacity(ranges.len());
+ let mut highs: Vec<Option<Uuid>> = Vec::with_capacity(ranges.len());
+ for (ordinal, range) in ranges.iter().enumerate() {
+ let band =
+ i16::try_from(ordinal).map_err(|_| ChunkStoreError::PersonBandOverflow(ordinal))?;
+ ids.push(Uuid::now_v7());
+ bands.push(band);
+ lows.push(range.lo());
+ highs.push(range.hi());
+ }
+
+ 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'
+ FOR UPDATE
+ ), input AS (
+ SELECT * FROM unnest($2::uuid[], $3::smallint[], $4::uuid[], $5::uuid[])
+ AS u(id, band, lo, hi)
+ ), inserted AS (
+ INSERT INTO cohort_backfill_chunks
+ (id, run_id, team_id, day, band, person_range_lo, person_range_hi, status,
+ claim_epoch, claimed_by, attempts, last_error, tiles_produced,
+ created_at, updated_at)
+ SELECT u.id, r.id, r.team_id, $6, u.band, u.lo, u.hi, $7, 0, '', 0, '', 0,
+ now(), now()
+ FROM input u CROSS JOIN target_run r
+ WHERE NOT EXISTS (SELECT 1 FROM cohort_backfill_chunks WHERE run_id = $1)
+ RETURNING id
+ )
+ SELECT EXISTS(SELECT 1 FROM target_run) AS run_seeding,
+ count(*)::bigint AS inserted
+ FROM inserted
+ "#,
+ )
+ .bind(run_id)
+ .bind(ids)
+ .bind(bands)
+ .bind(lows)
+ .bind(highs)
+ .bind(person_chunk_sentinel_day())
+ .bind(ChunkStatus::Pending.as_str())
+ .fetch_one(&self.pool)
+ .await;
+ let result = match result {
+ Ok(result) => result,
+ // Only the (run, day, band) constraint means "another planner won"; any other unique
+ // violation must surface rather than be misread as an idempotent no-op.
+ Err(sqlx::Error::Database(error))
+ if error.code().as_deref() == Some("23505")
+ && error.constraint() == Some("cohort_bfc_run_day_band_uq") =>
+ {
+ return Ok(PlanOutcome::AlreadyPlanned);
+ }
+ Err(error) => return Err(error.into()),
+ };
+ if !result.run_seeding {
+ return Ok(PlanOutcome::RunNotSeeding);
+ }
+ if result.inserted == 0 {
+ return Ok(PlanOutcome::AlreadyPlanned);
+ }
+ 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],
@@ -127,6 +243,9 @@ impl PgChunkStore {
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))
+ -- Cross-kind priority rides on this ordering: person chunks are planned under a
+ -- far-future sentinel day, so behavioral work (readiness-gating, fence-sensitive)
+ -- always drains first. Reordering here silently inverts that.
ORDER BY c.day, c.band
LIMIT 1
FOR UPDATE OF c SKIP LOCKED
@@ -140,6 +259,7 @@ impl PgChunkStore {
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,
+ c.person_range_lo, c.person_range_hi,
(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,
@@ -196,6 +316,20 @@ impl PgChunkStore {
Ok(result.rows_affected())
}
+ /// The person path's mark: seeds were already streamed to Kafka during the scan, so only the
+ /// count crosses the `scanning`→`produced` CAS.
+ pub async fn mark_produced_streamed(
+ &self,
+ chunk: StreamedChunk,
+ ) -> Result<EnqueuedChunk, Halted<StreamedChunk, ChunkStoreError>> {
+ let spec = chunk.spec();
+ let seeds_produced = chunk.seeds_produced();
+ if let Err(error) = self.mark_produced_raw(spec.lease, seeds_produced).await {
+ return Err(Halted::failed(chunk, error));
+ }
+ Ok(EnqueuedChunk::new(spec, seeds_produced))
+ }
+
pub async fn mark_produced(
&self,
chunk: ScannedChunk,
@@ -396,12 +530,19 @@ impl PgChunkStore {
) -> 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);
+ // `lo IS NOT NULL` ⇔ person chunk. Beyond the empty `lo == hi` shape, the decode must not
+ // reject ranges (no ordering checks) — a rejected claim strands the chunk `scanning`.
+ let person_range = row
+ .person_range_lo
+ .map(|lo| PersonRange::new(lo, row.person_range_hi))
+ .transpose()?;
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),
+ person_range,
};
let handle = LeaseHandle::start(self.clone(), lease, claimant.clone(), lease_duration);
Ok(Claim {
@@ -421,12 +562,35 @@ pub struct Claim {
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.
+const PERSON_PLANNING_LOCK_SQL: &str = "SELECT pg_try_advisory_lock(hashtextextended($1::text, 0))";
+
+/// The held cluster-wide planning claim; release explicitly, or drop to free via connection close.
+pub struct PersonPlanningClaim {
+ connection: Option<sqlx::PgConnection>,
+ run_id: RunId,
+}
+
+impl PersonPlanningClaim {
+ pub async fn release(mut self) {
+ if let Some(mut connection) = self.connection.take() {
+ sqlx::query("SELECT pg_advisory_unlock(hashtextextended($1::text, 0))")
+ .bind(self.run_id)
+ .execute(&mut connection)
+ .await
+ .ok();
+ connection.close().await.ok();
+ }
+ }
+}
+
+/// The result of planning a run's chunks. `RunNotSeeding` is control flow (the run left the
+/// `seeding` state between discovery and planning), not an error; `AlreadyPlanned` is the person
+/// planner's all-or-nothing gate reporting another planner won.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlanOutcome {
Planned { inserted: u64 },
RunNotSeeding,
+ AlreadyPlanned,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -465,6 +629,10 @@ pub enum ChunkStoreError {
InvalidDay(DayIdx),
#[error(transparent)]
Band(#[from] BandSpecError),
+ #[error(transparent)]
+ PersonRange(#[from] PersonRangeError),
+ #[error("person chunk ordinal {0} exceeds the band column's smallint range")]
+ PersonBandOverflow(usize),
#[error("chunk planner returned invalid insert count {0}")]
InvalidInsertedCount(i64),
#[error("chunk counter returned invalid remaining count {0}")]
@@ -497,6 +665,8 @@ struct ClaimedRow {
day: NaiveDate,
band: Band,
claim_epoch: ClaimEpoch,
+ person_range_lo: Option<Uuid>,
+ person_range_hi: Option<Uuid>,
s_chunk_ms: i64,
num_bands: i64,
was_reclaim: bool,
diff --git a/rust/cohort-seeder/src/store/completion.rs b/rust/cohort-seeder/src/store/completion.rs
index 94ef4f0d52b2..b59b1b5ee795 100644
--- a/rust/cohort-seeder/src/store/completion.rs
+++ b/rust/cohort-seeder/src/store/completion.rs
@@ -23,6 +23,8 @@ use crate::domain::{
PartitionBitmapError, ReconcileHwms, RunId, WatchPositions, MARKER_WATCH_SCHEMA,
};
+use super::runs::RunKind;
+
use super::{RenderedError, PERSISTED_ERROR_LIMIT};
/// The completion columns the two discovery SELECTs share, kept in a macro so both queries stay
@@ -266,23 +268,27 @@ impl ReconcilingClaim {
}
/// Stamp the planning proof (`chunks_planned_at`) exactly once for a seeding run — the durable
-/// evidence that day-chunk planning ran, which distinguishes a legitimately zero-chunk run from one
-/// whose planning has not yet happened. Re-filters `backfill_kind` like every entry point here, so a
-/// `person_property` run id handed in by a caller can never enter this protocol.
+/// evidence that chunk planning ran, which distinguishes a legitimately zero-chunk run from one
+/// whose planning has not yet happened. The stamp pair is the one kind-parameterized exception to
+/// this module's hardcoded behavioral filters: person runs earn their planning proof here too,
+/// while every other entry point stays behavioral-only, so a `person_property` run id handed to
+/// the reconcile protocol can never enter it.
pub async fn mark_chunks_planned(
pool: &PgPool,
run_id: RunId,
+ kind: RunKind,
) -> Result<PlanningStampOutcome, CompletionStoreError> {
let stamped = sqlx::query_scalar::<_, RunId>(
r#"
UPDATE cohort_backfill_runs
SET chunks_planned_at = now(), updated_at = now()
- WHERE id = $1 AND backfill_kind = 'behavioral' AND status = 'seeding'
+ WHERE id = $1 AND backfill_kind = $2 AND status = 'seeding'
AND chunks_planned_at IS NULL
RETURNING id
"#,
)
.bind(run_id)
+ .bind(kind.as_str())
.fetch_optional(pool)
.await?;
Ok(if stamped.is_some() {
@@ -297,12 +303,14 @@ pub async fn mark_chunks_planned(
pub async fn read_planning_stamp(
pool: &PgPool,
run_id: RunId,
+ kind: RunKind,
) -> Result<Option<DateTime<Utc>>, CompletionStoreError> {
let stamp: Option<Option<DateTime<Utc>>> = sqlx::query_scalar(
"SELECT chunks_planned_at FROM cohort_backfill_runs \
- WHERE id = $1 AND backfill_kind = 'behavioral'",
+ WHERE id = $1 AND backfill_kind = $2",
)
.bind(run_id)
+ .bind(kind.as_str())
.fetch_optional(pool)
.await?;
Ok(stamp.flatten())
diff --git a/rust/cohort-seeder/src/store/runs.rs b/rust/cohort-seeder/src/store/runs.rs
index 0148123c6acf..0d1baa292b31 100644
--- a/rust/cohort-seeder/src/store/runs.rs
+++ b/rust/cohort-seeder/src/store/runs.rs
@@ -11,28 +11,31 @@ use sqlx::types::Json;
use sqlx::{FromRow, PgPool};
use crate::domain::{
- BehavioralShapeHash, BehavioralShapeHashError, PinnedError, PinnedParticipation,
- PinnedParticipationState, PinnedRun, PinnedRunSnapshot, ReconcileTile, RunId, TriggerKind,
- UtcMillis, ValidatedPinnedRun,
+ BehavioralShapeHash, BehavioralShapeHashError, PersonPinnedSnapshot, PersonRunValidation,
+ PinnedError, PinnedParticipation, PinnedParticipationState, PinnedPersonRun, PinnedRun,
+ PinnedRunSnapshot, ReconcileTile, 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.
+/// compile-time constant, pinned by the pg test.
macro_rules! run_columns {
() => {
- "id, team_id, cohort_id, trigger_kind, scope, status, timezone, boundary_at, pinned"
+ "id, team_id, cohort_id, trigger_kind, scope, status, timezone, boundary_at, pinned, \
+ backfill_kind, person_scan_since"
};
}
+// The kind predicate binds the caller's allowed-kind set: with the person gate off, discovery
+// binds `['behavioral']`, which keeps the person path inert without a second query text.
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 AND backfill_kind = ANY($1)",
"\n ORDER BY created_at\n"
);
@@ -41,7 +44,7 @@ const DISCOVER_ONLY: &str = concat!(
run_columns!(),
"\n FROM cohort_backfill_runs",
"\n WHERE status IN ('awaiting_boundary', 'seeding')",
- "\n AND backfill_kind = 'behavioral'",
+ "\n AND backfill_kind = ANY($2)",
"\n AND team_id = ANY($1)",
"\n ORDER BY created_at\n"
);
@@ -50,7 +53,7 @@ const READ_RUN: &str = concat!(
"\n SELECT ",
run_columns!(),
"\n FROM cohort_backfill_runs",
- "\n WHERE id = $1 AND backfill_kind = 'behavioral'\n"
+ "\n WHERE id = $1 AND backfill_kind = $2\n"
);
const READ_ACTIVE_RECONCILE_PARTICIPATIONS: &str = r#"
@@ -149,16 +152,50 @@ impl FromStr for RunScope {
}
}
+/// The `cohort_backfill_runs.backfill_kind` vocabulary. Fail-closed: an unknown kind never decodes.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum RunKind {
+ Behavioral,
+ PersonProperty,
+}
+
+impl RunKind {
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::Behavioral => "behavioral",
+ Self::PersonProperty => "person_property",
+ }
+ }
+}
+
+impl FromStr for RunKind {
+ type Err = UnknownRunKind;
+
+ fn from_str(value: &str) -> Result<Self, Self::Err> {
+ match value {
+ "behavioral" => Ok(Self::Behavioral),
+ "person_property" => Ok(Self::PersonProperty),
+ other => Err(UnknownRunKind(other.to_string())),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+#[error("unknown backfill kind {0:?}")]
+pub struct UnknownRunKind(pub String);
+
#[derive(Debug, Clone)]
pub struct DiscoveredRun {
pub run_id: RunId,
pub team_id: TeamId,
pub cohort_id: Option<CohortId>,
+ pub kind: RunKind,
pub trigger: TriggerKind,
pub scope: RunScope,
pub status: RunStatus,
pub timezone: String,
pub boundary_at: Option<DateTime<Utc>>,
+ pub person_scan_since: Option<UtcMillis>,
pub pinned: Value,
}
@@ -169,9 +206,11 @@ pub struct DiscoveredRun {
pub struct SeedableRun {
pub run_id: RunId,
pub team_id: TeamId,
+ pub kind: RunKind,
pub trigger: TriggerKind,
pub timezone: String,
pub boundary_at: UtcMillis,
+ pub person_scan_since: Option<UtcMillis>,
pub pinned: Value,
}
@@ -180,14 +219,46 @@ impl SeedableRun {
Self {
run_id: run.run_id,
team_id: run.team_id,
+ kind: run.kind,
trigger: run.trigger,
timezone: run.timezone,
boundary_at: UtcMillis::new(boundary_at.timestamp_millis()),
+ person_scan_since: run.person_scan_since,
pinned: run.pinned,
}
}
pub async fn load_pinned(&self, pool: &PgPool) -> Result<ValidatedPinnedRun, RunError> {
+ let participations = self.fetch_participations(pool).await?;
+ 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)?)
+ }
+
+ pub async fn load_person_pinned(&self, pool: &PgPool) -> Result<PersonRunValidation, RunError> {
+ let participations = self.fetch_participations(pool).await?;
+ let snapshot = PersonPinnedSnapshot {
+ run_id: self.run_id,
+ team_id: self.team_id,
+ timezone: self.timezone.clone(),
+ person_scan_since: self.person_scan_since,
+ pinned: self.pinned.clone(),
+ participations,
+ };
+ Ok(PinnedPersonRun::validate(snapshot)?)
+ }
+
+ async fn fetch_participations(
+ &self,
+ pool: &PgPool,
+ ) -> Result<Vec<PinnedParticipation>, RunError> {
let rows = sqlx::query_as::<_, PinnedParticipationRow>(
r#"
SELECT team_id, cohort_id, pinned_filters, superseded_at
@@ -220,16 +291,7 @@ impl SeedableRun {
},
});
}
- 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)?)
+ Ok(participations)
}
}
@@ -319,6 +381,8 @@ pub enum RunError {
UnknownStatus(String),
#[error("unknown backfill scope {0:?}")]
UnknownScope(String),
+ #[error("run {run_id:?} has unknown backfill kind {value:?}")]
+ InvalidKind { run_id: RunId, value: 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:?}")]
@@ -347,7 +411,8 @@ pub enum RunError {
impl RunError {
pub const fn run_id(&self) -> Option<RunId> {
match self {
- Self::InvalidTrigger { run_id, .. }
+ Self::InvalidKind { run_id, .. }
+ | Self::InvalidTrigger { run_id, .. }
| Self::InvalidScope { run_id, .. }
| Self::InvalidStatus { run_id, .. }
| Self::NotFound(run_id)
@@ -365,11 +430,13 @@ struct RunRow {
id: RunId,
team_id: i32,
cohort_id: Option<i32>,
+ backfill_kind: String,
trigger_kind: String,
scope: String,
status: String,
timezone: String,
boundary_at: Option<DateTime<Utc>>,
+ person_scan_since: Option<DateTime<Utc>>,
pinned: Json<Value>,
}
@@ -377,6 +444,13 @@ impl TryFrom<RunRow> for DiscoveredRun {
type Error = RunError;
fn try_from(row: RunRow) -> Result<Self, Self::Error> {
+ let kind = row
+ .backfill_kind
+ .parse::<RunKind>()
+ .map_err(|_| RunError::InvalidKind {
+ run_id: row.id,
+ value: row.backfill_kind.clone(),
+ })?;
let trigger =
row.trigger_kind
.parse::<TriggerKind>()
@@ -396,11 +470,15 @@ impl TryFrom<RunRow> for DiscoveredRun {
run_id: row.id,
team_id: TeamId(row.team_id),
cohort_id: row.cohort_id.map(CohortId),
+ kind,
trigger,
scope,
status,
timezone: row.timezone,
boundary_at: row.boundary_at,
+ person_scan_since: row
+ .person_scan_since
+ .map(|at| UtcMillis::new(at.timestamp_millis())),
pinned: row.pinned.0,
})
}
@@ -410,6 +488,15 @@ impl TryFrom<RunRow> for DiscoveredRun {
mod tests {
use super::*;
+ #[test]
+ fn run_kind_round_trips_and_fails_closed() {
+ for kind in [RunKind::Behavioral, RunKind::PersonProperty] {
+ assert_eq!(kind.as_str().parse::<RunKind>().unwrap(), kind);
+ }
+ assert!("person".parse::<RunKind>().is_err());
+ assert!("".parse::<RunKind>().is_err());
+ }
+
#[test]
fn malformed_discovered_rows_keep_the_run_capability_for_q8() {
let run_id = RunId(uuid::Uuid::from_u128(1));
@@ -417,11 +504,13 @@ mod tests {
id: run_id,
team_id: 2,
cohort_id: None,
+ backfill_kind: "behavioral".to_string(),
trigger_kind: "invalid".to_string(),
scope: "team".to_string(),
status: "seeding".to_string(),
timezone: "UTC".to_string(),
boundary_at: Some(Utc::now()),
+ person_scan_since: None,
pinned: Json(serde_json::json!({})),
})
.unwrap_err();
@@ -460,10 +549,16 @@ struct BoundaryRow {
pub async fn discover_runs(
pool: &PgPool,
allowlist: &TeamAllowlist,
+ kinds: &[RunKind],
) -> Result<Vec<DiscoveredRun>, RunError> {
+ let kinds = kinds
+ .iter()
+ .map(|kind| kind.as_str().to_string())
+ .collect::<Vec<_>>();
let rows = match allowlist {
TeamAllowlist::All => {
sqlx::query_as::<_, RunRow>(DISCOVER_ALL)
+ .bind(kinds)
.fetch_all(pool)
.await?
}
@@ -472,6 +567,7 @@ pub async fn discover_runs(
team_ids.sort_unstable();
sqlx::query_as::<_, RunRow>(DISCOVER_ONLY)
.bind(team_ids)
+ .bind(kinds)
.fetch_all(pool)
.await?
}
@@ -483,7 +579,8 @@ pub async fn load_reconcile_run(
pool: &PgPool,
run_id: RunId,
) -> Result<ReconcileRun, ReconcileRunError> {
- let run = read_run(pool, run_id).await?;
+ // Reconcile stays behavioral-only: a person run id can never enter this protocol.
+ let run = read_run(pool, run_id, RunKind::Behavioral).await?;
if !matches!(run.status, RunStatus::Seeding | RunStatus::Reconciling) {
return Err(ReconcileRunError::Status {
run_id,
@@ -537,6 +634,7 @@ pub async fn establish_boundary(
pool: &PgPool,
run: DiscoveredRun,
) -> Result<BoundaryOutcome, RunError> {
+ let kind = run.kind;
if run.status == RunStatus::Seeding {
return match run.boundary_at {
Some(boundary_at) => Ok(BoundaryOutcome::AlreadyEstablished(SeedableRun::promote(
@@ -589,7 +687,7 @@ pub async fn establish_boundary(
)));
}
- let current = read_run(pool, run.run_id).await?;
+ let current = read_run(pool, run.run_id, kind).await?;
if current.status == RunStatus::Seeding {
match current.boundary_at {
Some(boundary_at) => Ok(BoundaryOutcome::AlreadyEstablished(SeedableRun::promote(
@@ -648,9 +746,10 @@ pub async fn record_run_warning(
Ok(updated.is_some())
}
-async fn read_run(pool: &PgPool, run_id: RunId) -> Result<DiscoveredRun, RunError> {
+async fn read_run(pool: &PgPool, run_id: RunId, kind: RunKind) -> Result<DiscoveredRun, RunError> {
let row = sqlx::query_as::<_, RunRow>(READ_RUN)
.bind(run_id)
+ .bind(kind.as_str())
.fetch_optional(pool)
.await?
.ok_or(RunError::NotFound(run_id))?;
diff --git a/rust/cohort-seeder/tests/pg_chunks.rs b/rust/cohort-seeder/tests/pg_chunks.rs
index 010ec65b238e..13e0617aa57f 100644
--- a/rust/cohort-seeder/tests/pg_chunks.rs
+++ b/rust/cohort-seeder/tests/pg_chunks.rs
@@ -16,22 +16,26 @@ use cohort_seeder::app::reconcile_dispatch::{
prepare_reconcile_dispatch, CompletionRequirement, PrepareReconcileDispatchError,
RegisterBackfillConfirmation,
};
-use cohort_seeder::domain::{ClaimEpoch, PinnedWarning, ProduceHwms};
+use cohort_seeder::domain::{
+ tile_ranges, ClaimEpoch, PersonRunValidation, 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, load_reconcile_run, record_run_warning,
- BoundaryOutcome, ReconcileRunError, RunError, RunStatus, RunWarningNote,
+ BoundaryOutcome, ReconcileRunError, RunError, RunKind, RunStatus, RunWarningNote,
};
use cohort_seeder::store::{Claimant, LeaseDuration, MaxAttempts, RenderedError};
use cohort_seeder::test_support;
use common_types::cohort::TeamAllowlist;
use serde_json::json;
+use uuid::Uuid;
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,
+ behavioral_filter, empty_pinned, ensure_lease_lost, insert_participation, insert_person_run,
+ insert_run, person_filter, person_pinned, pinned_condition, planned_count, with_db,
+ ACTIVE_HASH, SUPERSEDED_HASH,
};
const ONE_BAND: NonZeroU16 = NonZeroU16::MIN;
@@ -72,11 +76,11 @@ async fn discovery_scopes_to_the_allowlist_and_all_admits_every_run() -> Result<
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?;
+ let discovered = discover_runs(&pool, &only_team_two, &[RunKind::Behavioral]).await?;
ensure!(discovered.len() == 1);
ensure!(discovered[0].run_id == self_run);
- let all_runs = discover_runs(&pool, &TeamAllowlist::All).await?;
+ let all_runs = discover_runs(&pool, &TeamAllowlist::All, &[RunKind::Behavioral]).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));
@@ -102,7 +106,7 @@ async fn concurrent_boundary_establishment_promotes_exactly_one_run() -> Result<
.await?;
let only_team_two: TeamAllowlist = "2".parse().map_err(anyhow::Error::msg)?;
- let discovered = discover_runs(&pool, &only_team_two).await?;
+ let discovered = discover_runs(&pool, &only_team_two, &[RunKind::Behavioral]).await?;
let left = discovered[0].clone();
let right = discovered[0].clone();
let (left, right) = tokio::join!(
@@ -235,7 +239,7 @@ async fn load_pinned_drops_superseded_and_rejects_cross_team_and_dr() -> Result<
)
.await?;
- let all_runs = discover_runs(&pool, &TeamAllowlist::All).await?;
+ let all_runs = discover_runs(&pool, &TeamAllowlist::All, &[RunKind::Behavioral]).await?;
let self_discovered = all_runs
.iter()
.find(|run| run.run_id == self_run)
@@ -858,6 +862,242 @@ async fn fail_truncates_chunk_and_run_error_columns() -> Result<()> {
.await
}
+/// The dark-by-default proof: discovery with `kinds = [Behavioral]` (the gate-off binding) never
+/// yields a person run, while widening the kind set surfaces it with its kind and pinned
+/// `person_scan_since` decoded, and the pinned load validates the person payload.
+#[tokio::test]
+async fn discovery_is_kind_gated_and_person_pinned_load_validates() -> Result<()> {
+ with_db(|pool| async move {
+ let behavioral_run =
+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;
+ let person_run = insert_person_run(
+ &pool,
+ 2,
+ "seeding",
+ true,
+ person_pinned(&[(10, ACTIVE_HASH), (11, SUPERSEDED_HASH)]),
+ )
+ .await?;
+ insert_participation(
+ &pool,
+ person_run,
+ 2,
+ 10,
+ false,
+ person_filter(ACTIVE_HASH, "email"),
+ )
+ .await?;
+ insert_participation(
+ &pool,
+ person_run,
+ 2,
+ 11,
+ true,
+ person_filter(SUPERSEDED_HASH, "plan"),
+ )
+ .await?;
+
+ let behavioral_only =
+ discover_runs(&pool, &TeamAllowlist::All, &[RunKind::Behavioral]).await?;
+ ensure!(behavioral_only.iter().all(|run| run.run_id != person_run));
+ ensure!(behavioral_only
+ .iter()
+ .any(|run| run.run_id == behavioral_run));
+
+ let both_kinds = discover_runs(
+ &pool,
+ &TeamAllowlist::All,
+ &[RunKind::Behavioral, RunKind::PersonProperty],
+ )
+ .await?;
+ let discovered = both_kinds
+ .iter()
+ .find(|run| run.run_id == person_run)
+ .cloned()
+ .context("person run was not discovered with the widened kind set")?;
+ ensure!(discovered.kind == RunKind::PersonProperty);
+ ensure!(discovered.person_scan_since.is_some());
+ let behavioral = both_kinds
+ .iter()
+ .find(|run| run.run_id == behavioral_run)
+ .context("behavioral run missing from the widened discovery")?;
+ ensure!(behavioral.kind == RunKind::Behavioral);
+
+ let seedable = match establish_boundary(&pool, discovered).await? {
+ BoundaryOutcome::Established(run) | BoundaryOutcome::AlreadyEstablished(run) => run,
+ BoundaryOutcome::NoLongerSeedable { .. } => bail!("person run was not seedable"),
+ };
+ let PersonRunValidation::Seedable(validated) = seedable.load_person_pinned(&pool).await?
+ else {
+ bail!("person run with an active participation unexpectedly retired");
+ };
+ ensure!(validated.run.conditions.len() == 1);
+ ensure!(validated.run.horizon_days == 30);
+ ensure!(validated.uncovered_cohorts.is_empty());
+ ensure!(validated.warnings.iter().any(|warning| matches!(
+ warning,
+ PinnedWarning::ConditionSuperseded { cohort_id, .. } if *cohort_id == CohortId(11)
+ )));
+ Ok(())
+ })
+ .await
+}
+
+/// The cluster-wide planning claim is exclusive per run and frees on release, so at most one
+/// replica ever runs a run's boundary scan.
+#[tokio::test]
+async fn person_planning_claim_is_exclusive_per_run_until_released() -> Result<()> {
+ with_db(|pool| async move {
+ let run = insert_person_run(&pool, 2, "seeding", true, person_pinned(&[])).await?;
+ let other_run = insert_person_run(&pool, 3, "seeding", true, person_pinned(&[])).await?;
+ let store = PgChunkStore::new(pool.clone());
+
+ let held = store
+ .try_claim_person_planning(run)
+ .await?
+ .context("first claim should win")?;
+ ensure!(store.try_claim_person_planning(run).await?.is_none());
+ // Claims are per run: a different run's planner is unaffected.
+ let other = store
+ .try_claim_person_planning(other_run)
+ .await?
+ .context("a different run's claim should win")?;
+
+ held.release().await;
+ other.release().await;
+ let reclaimed = store
+ .try_claim_person_planning(run)
+ .await?
+ .context("a released claim should be reclaimable")?;
+ reclaimed.release().await;
+ Ok(())
+ })
+ .await
+}
+
+/// Person planning is all-or-nothing: one racing planner wins and inserts every range under the
+/// sentinel day with ordinal bands, the loser and any re-plan report `AlreadyPlanned`, and a
+/// non-seeding run refuses.
+#[tokio::test]
+async fn person_planning_is_all_or_nothing_and_idempotent() -> Result<()> {
+ with_db(|pool| async move {
+ let run = insert_person_run(&pool, 2, "seeding", true, person_pinned(&[])).await?;
+ let store = PgChunkStore::new(pool.clone());
+ let boundaries = [Uuid::from_u128(0x10), Uuid::from_u128(0x20)];
+ let ranges = tile_ranges(&boundaries)?;
+ ensure!(ranges.len() == 3);
+
+ let (left, right) = tokio::join!(
+ store.plan_person_chunks(run, &ranges),
+ store.plan_person_chunks(run, &ranges),
+ );
+ let outcomes = [left?, right?];
+ ensure!(
+ outcomes
+ .iter()
+ .filter(|outcome| matches!(outcome, PlanOutcome::Planned { inserted: 3 }))
+ .count()
+ == 1,
+ "expected exactly one winning planner, got {outcomes:?}"
+ );
+ ensure!(
+ outcomes
+ .iter()
+ .filter(|outcome| matches!(outcome, PlanOutcome::AlreadyPlanned))
+ .count()
+ == 1,
+ "expected the losing planner to observe AlreadyPlanned, got {outcomes:?}"
+ );
+ ensure!(matches!(
+ store.plan_person_chunks(run, &ranges).await?,
+ PlanOutcome::AlreadyPlanned
+ ));
+
+ let rows: Vec<(String, i16, Option<Uuid>, Option<Uuid>)> = sqlx::query_as(
+ "SELECT day::text, band, person_range_lo, person_range_hi \
+ FROM cohort_backfill_chunks WHERE run_id = $1 ORDER BY band",
+ )
+ .bind(run)
+ .fetch_all(&pool)
+ .await?;
+ ensure!(rows.len() == 3);
+ ensure!(rows.iter().all(|(day, ..)| day == "9999-01-01"));
+ ensure!(rows.iter().map(|(_, band, ..)| *band).eq(0..3));
+ ensure!(rows[0].2 == Some(Uuid::nil()));
+ ensure!(rows[0].3 == Some(boundaries[0]));
+ ensure!(rows[1].2 == Some(boundaries[0]));
+ ensure!(rows[1].3 == Some(boundaries[1]));
+ ensure!(rows[2].2 == Some(boundaries[1]));
+ ensure!(rows[2].3.is_none());
+
+ let idle =
+ insert_person_run(&pool, 3, "awaiting_boundary", false, person_pinned(&[])).await?;
+ ensure!(matches!(
+ store.plan_person_chunks(idle, &ranges).await?,
+ PlanOutcome::RunNotSeeding
+ ));
+ Ok(())
+ })
+ .await
+}
+
+/// The sentinel day makes person chunks claim strictly after behavioral days on the shared claim
+/// loop, and a person claim decodes its range with `num_bands` = the run's chunk count.
+#[tokio::test]
+async fn person_chunks_claim_after_behavioral_days_and_carry_ranges() -> Result<()> {
+ with_db(|pool| async move {
+ let behavioral_run =
+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;
+ let person_run = insert_person_run(&pool, 2, "seeding", true, person_pinned(&[])).await?;
+ let store = PgChunkStore::new(pool.clone());
+ ensure!(planned_count(store.plan_chunks(behavioral_run, [100], ONE_BAND).await?)? == 1);
+ let boundary = Uuid::from_u128(0x42);
+ let ranges = tile_ranges(&[boundary])?;
+ ensure!(planned_count(store.plan_person_chunks(person_run, &ranges).await?)? == 2);
+
+ let lease60 = LeaseDuration::new(Duration::from_secs(60))?;
+ let attempts5 = MaxAttempts::new(5)?;
+ let run_ids = [behavioral_run, person_run];
+ let claimant = Claimant::new("worker-a")?;
+
+ let first = store
+ .claim_next(&run_ids, &claimant, lease60, attempts5)
+ .await?
+ .context("behavioral chunk was not claimed first")?;
+ ensure!(first.chunk.spec().lease.run_id() == behavioral_run);
+ ensure!(first.chunk.spec().person_range.is_none());
+
+ let second = store
+ .claim_next(&run_ids, &claimant, lease60, attempts5)
+ .await?
+ .context("first person chunk was not claimed")?;
+ let second_spec = second.chunk.spec();
+ ensure!(second_spec.lease.run_id() == person_run);
+ ensure!(second_spec.band.band() == 0);
+ ensure!(second_spec.band.num_bands().get() == 2);
+ let second_range = second_spec
+ .person_range
+ .context("person claim lost its range")?;
+ ensure!(second_range.lo() == Uuid::nil());
+ ensure!(second_range.hi() == Some(boundary));
+
+ let third = store
+ .claim_next(&run_ids, &claimant, lease60, attempts5)
+ .await?
+ .context("second person chunk was not claimed")?;
+ let third_range = third
+ .chunk
+ .spec()
+ .person_range
+ .context("person claim lost its range")?;
+ ensure!(third_range.lo() == boundary);
+ ensure!(third_range.hi().is_none());
+ drop((first, second, third));
+ 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]
diff --git a/rust/cohort-seeder/tests/pg_completion.rs b/rust/cohort-seeder/tests/pg_completion.rs
index 6f9c27f953e1..669549915828 100644
--- a/rust/cohort-seeder/tests/pg_completion.rs
+++ b/rust/cohort-seeder/tests/pg_completion.rs
@@ -25,10 +25,11 @@ use cohort_seeder::store::completion::{
cas_run_reconciling, confirm_reconciling, discover_completions, load_current_behavioral_hashes,
load_observation_participations, mark_chunks_planned, mark_participation_completed,
mark_run_observed, mark_run_observed_unreconcilable, persist_marker_observations,
- persist_observation_ends, record_participation_partial, record_participation_shortfall,
- runs_with_all_chunks_confirmed, CompletionStoreError, CurrentBehavioralHash,
- PlanningStampOutcome,
+ persist_observation_ends, read_planning_stamp, record_participation_partial,
+ record_participation_shortfall, runs_with_all_chunks_confirmed, CompletionStoreError,
+ CurrentBehavioralHash, PlanningStampOutcome,
};
+use cohort_seeder::store::runs::RunKind;
use cohort_seeder::store::RenderedError;
use cohort_seeder::test_support;
use common_types::cohort::TeamAllowlist;
@@ -37,8 +38,8 @@ use sqlx::PgPool;
mod support;
use support::{
- empty_pinned, ensure_fence_lost, insert_cohort, insert_participation, insert_reconciling_run,
- insert_run, set_marker_bits, with_db,
+ empty_pinned, ensure_fence_lost, insert_cohort, insert_participation, insert_person_run,
+ insert_reconciling_run, insert_run, person_pinned, set_marker_bits, with_db,
};
const ONE_BAND: NonZeroU16 = NonZeroU16::MIN;
@@ -80,17 +81,17 @@ async fn planning_stamp_is_idempotent_and_refuses_non_seeding() -> Result<()> {
let seeding =
insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;
ensure!(matches!(
- mark_chunks_planned(&pool, seeding).await?,
+ mark_chunks_planned(&pool, seeding, RunKind::Behavioral).await?,
PlanningStampOutcome::Stamped
));
ensure!(matches!(
- mark_chunks_planned(&pool, seeding).await?,
+ mark_chunks_planned(&pool, seeding, RunKind::Behavioral).await?,
PlanningStampOutcome::Skipped
));
let reconciling = insert_reconciling_run(&pool, 3).await?;
ensure!(matches!(
- mark_chunks_planned(&pool, reconciling).await?,
+ mark_chunks_planned(&pool, reconciling, RunKind::Behavioral).await?,
PlanningStampOutcome::Skipped
));
Ok(())
@@ -98,6 +99,46 @@ async fn planning_stamp_is_idempotent_and_refuses_non_seeding() -> Result<()> {
.await
}
+/// The person-kind inertness contract: `discover_completions` never surfaces a person run — the
+/// reconcile protocol stays behavioral-only by design — while the kind-parameterized stamp pair
+/// lets a person run earn its planning proof and refuses the wrong kind.
+#[tokio::test]
+async fn completion_discovery_excludes_person_runs_but_the_stamp_is_kind_aware() -> Result<()> {
+ with_db(|pool| async move {
+ let person_run = insert_person_run(&pool, 2, "seeding", true, person_pinned(&[])).await?;
+
+ ensure!(discover_completions(&pool, &TeamAllowlist::All)
+ .await?
+ .iter()
+ .all(|completion| completion.run_id != person_run));
+
+ ensure!(matches!(
+ mark_chunks_planned(&pool, person_run, RunKind::Behavioral).await?,
+ PlanningStampOutcome::Skipped
+ ));
+ ensure!(
+ read_planning_stamp(&pool, person_run, RunKind::PersonProperty)
+ .await?
+ .is_none()
+ );
+ ensure!(matches!(
+ mark_chunks_planned(&pool, person_run, RunKind::PersonProperty).await?,
+ PlanningStampOutcome::Stamped
+ ));
+ ensure!(
+ read_planning_stamp(&pool, person_run, RunKind::PersonProperty)
+ .await?
+ .is_some()
+ );
+ // The behavioral-filtered read still refuses to see it.
+ ensure!(read_planning_stamp(&pool, person_run, RunKind::Behavioral)
+ .await?
+ .is_none());
+ Ok(())
+ })
+ .await
+}
+
/// The CAS admits exactly one winner, and refuses a run that has not planned or still has an
/// unconfirmed chunk.
#[tokio::test]
@@ -106,7 +147,7 @@ async fn cas_reconciling_is_single_winner_and_gated_on_planned_and_confirmed() -
// Planned, no chunks: two racing CAS attempts, exactly one wins.
let ready =
insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;
- mark_chunks_planned(&pool, ready).await?;
+ mark_chunks_planned(&pool, ready, RunKind::Behavioral).await?;
let (left, right) = tokio::join!(
cas_run_reconciling(&pool, ready),
cas_run_reconciling(&pool, ready)
@@ -125,7 +166,7 @@ async fn cas_reconciling_is_single_winner_and_gated_on_planned_and_confirmed() -
// Planned but with an unconfirmed chunk: CAS refused.
let pending =
insert_run(&pool, 4, "team_enablement", "seeding", true, empty_pinned()).await?;
- mark_chunks_planned(&pool, pending).await?;
+ mark_chunks_planned(&pool, pending, RunKind::Behavioral).await?;
PgChunkStore::new(pool.clone())
.plan_chunks(pending, [100], ONE_BAND)
.await?;
@@ -681,7 +722,7 @@ async fn discovery_classifies_each_phase_including_undispatched_rows() -> Result
let planned =
insert_run(&pool, 3, "team_enablement", "seeding", true, empty_pinned()).await?;
- mark_chunks_planned(&pool, planned).await?;
+ mark_chunks_planned(&pool, planned, RunKind::Behavioral).await?;
let dispatched = insert_reconciling_run(&pool, 4).await?;
insert_participation(&pool, dispatched, 4, 401, false, empty_pinned()).await?;
diff --git a/rust/cohort-seeder/tests/support/mod.rs b/rust/cohort-seeder/tests/support/mod.rs
index 5f51fb3aff01..b24f3e1daf82 100644
--- a/rust/cohort-seeder/tests/support/mod.rs
+++ b/rust/cohort-seeder/tests/support/mod.rs
@@ -173,11 +173,12 @@ pub async fn insert_cohort(
Ok(())
}
-/// Unwrap the inserted-chunk count, failing if the run was unexpectedly not seeding.
+/// Unwrap the inserted-chunk count, failing if the run was unexpectedly not seeding or planned.
pub fn planned_count(outcome: PlanOutcome) -> Result<u64> {
match outcome {
PlanOutcome::Planned { inserted } => Ok(inserted),
PlanOutcome::RunNotSeeding => bail!("run was unexpectedly not seeding"),
+ PlanOutcome::AlreadyPlanned => bail!("run was unexpectedly already planned"),
}
}
@@ -239,10 +240,60 @@ pub async fn insert_participation(
Ok(())
}
+/// Insert a `person_property` run with a pinned `person_scan_since` 30 days back.
+pub async fn insert_person_run(
+ pool: &PgPool,
+ team_id: i32,
+ 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,
+ person_scan_since, pinned, preconditions, created_at, updated_at)
+ VALUES ($1, $2, 'person_property', 'cohort_created', 'cohort', $3, 'UTC',
+ CASE WHEN $4 THEN now() ELSE NULL END,
+ now() - interval '30 days', $5, '{}'::jsonb, now(), now())
+ "#,
+ )
+ .bind(run_id)
+ .bind(team_id)
+ .bind(status)
+ .bind(with_boundary)
+ .bind(Json(pinned))
+ .execute(pool)
+ .await?;
+ Ok(run_id)
+}
+
pub fn empty_pinned() -> Value {
json!({"schema_version": 1, "conditions": [], "event_names": []})
}
+pub fn person_pinned(conditions: &[(i32, &str)]) -> Value {
+ let conditions = conditions
+ .iter()
+ .map(|(cohort_id, hash)| json!({"cohort_id": cohort_id, "condition_hash": hash}))
+ .collect::<Vec<_>>();
+ json!({"schema_version": 1, "conditions": conditions, "person_horizon_days": 30})
+}
+
+pub fn person_filter(hash: &str, key: &str) -> Value {
+ json!({
+ "properties": {"type": "AND", "values": [{
+ "type": "person",
+ "key": key,
+ "value": "expected",
+ "operator": "exact",
+ "conditionHash": hash,
+ "bytecode": ["_H", 1, 32, "expected", 32, key, 32, "properties", 32, "person", 1, 3, 11],
+ }]}
+ })
+}
+
pub fn pinned_condition(cohort_id: i32, hash: &str, event_name: &str) -> Value {
json!({
"cohort_id": cohort_id,