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.

perf(cohorts): attribute seeder scans and back off failed chunk reclaims (#91389)

Matheus Batistadf60c06e50ec
diff --git a/.github/rust-images.yml b/.github/rust-images.yml
index 0dee081df674..499cd4806d14 100644
--- a/.github/rust-images.yml
+++ b/.github/rust-images.yml
@@ -71,6 +71,11 @@
- image: cohort-seeder
dockerfile: ./rust/Dockerfile
project: vglf58qgzw
+ # Frame pointers and unwind tables so the profiler can walk seeder stacks on
+ # aarch64, including native dependency frames (see rust/Dockerfile). The scan
+ # hot path is CPU-bound, so a profile that cannot unwind it is unreadable.
+ extra_rustflags: -C force-frame-pointers=yes -C force-unwind-tables=yes
+ extra_cflags: -fno-omit-frame-pointer -fasynchronous-unwind-tables
- image: cohort-stream-processor
dockerfile: ./rust/Dockerfile
diff --git a/products/cohorts/backend/backfill/observe.py b/products/cohorts/backend/backfill/observe.py
index 0b2b55ccc68e..626f5b5f61a1 100644
--- a/products/cohorts/backend/backfill/observe.py
+++ b/products/cohorts/backend/backfill/observe.py
@@ -134,9 +134,14 @@ def _publish(result: ObservationPass, registry: CollectorRegistry) -> None:
)
chunks_failed = Gauge(
"posthog_cohort_backfill_chunks_failed",
- # Retry churn, not wedged work: a chunk under the attempt cap is reclaimed and retried, and
- # one past it takes its whole run out of the active set within a poll. A run wedged that way
- # surfaces as `runs_recent{status="failed"}`.
+ # Retry churn, not wedged work: a chunk under the attempt cap is retried once its backoff
+ # elapses, and one past it takes its whole run out of the active set within a poll. A run
+ # wedged that way surfaces as `runs_recent{status="failed"}`.
+ #
+ # The seeder holds a failed chunk in this status for its whole retry wait, which grows per
+ # attempt up to SEEDER_RETRY_BACKOFF_CAP_SECS. So this reads higher than the failure rate
+ # alone would suggest, and a slow rise can mean waits getting longer rather than more
+ # chunks failing.
"Chunks in `failed` status on a still-active run, by backfill kind — retry activity",
["kind"],
registry=registry,
diff --git a/products/cohorts/backend/migrations/0012_cohortbackfillchunk_next_attempt_at_and_more.py b/products/cohorts/backend/migrations/0012_cohortbackfillchunk_next_attempt_at_and_more.py
new file mode 100644
index 000000000000..cd04846c666f
--- /dev/null
+++ b/products/cohorts/backend/migrations/0012_cohortbackfillchunk_next_attempt_at_and_more.py
@@ -0,0 +1,39 @@
+# Generated by Django 5.2.17 on 2026-08-30 14:30
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("cohorts", "0011_cohort_import_resolution_counts"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="cohortbackfillchunk",
+ name="next_attempt_at",
+ field=models.DateTimeField(
+ blank=True,
+ help_text="Earliest instant the Rust seeder may claim this chunk again after a failure, stamped by its retry backoff. Null means claimable now; every claim clears it.",
+ null=True,
+ ),
+ ),
+ migrations.AddField(
+ model_name="cohortbackfillchunk",
+ name="scan_decoded_bytes",
+ field=models.BigIntegerField(
+ db_default=0,
+ default=0,
+ help_text="Bytes the chunk's ClickHouse scan decompressed, written by the Rust seeder.",
+ ),
+ ),
+ migrations.AddField(
+ model_name="cohortbackfillchunk",
+ name="scan_received_bytes",
+ field=models.BigIntegerField(
+ db_default=0,
+ default=0,
+ help_text="Bytes the chunk's ClickHouse scan received off the wire, written by the Rust seeder.",
+ ),
+ ),
+ ]
diff --git a/products/cohorts/backend/migrations/max_migration.txt b/products/cohorts/backend/migrations/max_migration.txt
index a58f93c81a99..312ff35f23b9 100644
--- a/products/cohorts/backend/migrations/max_migration.txt
+++ b/products/cohorts/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0011_cohort_import_resolution_counts
+0012_cohortbackfillchunk_next_attempt_at_and_more
diff --git a/products/cohorts/backend/models/backfill.py b/products/cohorts/backend/models/backfill.py
index b5685dd7844a..943fb189b0b1 100644
--- a/products/cohorts/backend/models/backfill.py
+++ b/products/cohorts/backend/models/backfill.py
@@ -170,8 +170,28 @@ class CohortBackfillChunk(TeamScopedRootMixin, UUIDModel):
person_range_lo = models.UUIDField(null=True, blank=True)
person_range_hi = models.UUIDField(null=True, blank=True)
attempts = models.IntegerField(default=0)
+ next_attempt_at = models.DateTimeField(
+ null=True,
+ blank=True,
+ help_text=(
+ "Earliest instant the Rust seeder may claim this chunk again after a failure, stamped "
+ "by its retry backoff. Null means claimable now; every claim clears it."
+ ),
+ )
last_error = models.TextField(blank=True, default="")
tiles_produced = models.BigIntegerField(default=0)
+ # db_default, not only default: the Rust seeder raw-INSERTs an explicit column list, so a
+ # Python-side default leaves these NOT NULL columns unfilled by an old image during a rollout.
+ scan_received_bytes = models.BigIntegerField(
+ default=0,
+ db_default=0,
+ help_text="Bytes the chunk's ClickHouse scan received off the wire, written by the Rust seeder.",
+ )
+ scan_decoded_bytes = models.BigIntegerField(
+ default=0,
+ db_default=0,
+ help_text="Bytes the chunk's ClickHouse scan decompressed, written by the Rust seeder.",
+ )
produce_hwms = models.JSONField(null=True, blank=True)
confirmed_at = models.DateTimeField(null=True, blank=True)
created_at = models.DateTimeField(default=django_timezone.now)
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 10d187ec9eef..d0163dde8da1 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2657,6 +2657,7 @@ dependencies = [
"metrics",
"metrics-exporter-prometheus",
"proptest",
+ "rand 0.8.5",
"rdkafka",
"rustls 0.23.37",
"serde",
diff --git a/rust/cohort-seeder/Cargo.toml b/rust/cohort-seeder/Cargo.toml
index 3945551a0bf8..39ba70b48c15 100644
--- a/rust/cohort-seeder/Cargo.toml
+++ b/rust/cohort-seeder/Cargo.toml
@@ -37,6 +37,7 @@ hyper-util = { workspace = true, features = ["client-legacy"] }
lifecycle = { path = "../common/lifecycle" }
metrics = { workspace = true }
metrics-exporter-prometheus = { workspace = true }
+rand = { workspace = true }
rdkafka = { workspace = true }
rustls = { workspace = true }
serde = { workspace = true }
diff --git a/rust/cohort-seeder/src/app/execute.rs b/rust/cohort-seeder/src/app/execute.rs
index ed5f5663681f..2323b1f3ae94 100644
--- a/rust/cohort-seeder/src/app/execute.rs
+++ b/rust/cohort-seeder/src/app/execute.rs
@@ -7,6 +7,7 @@
//! retry — encoded once in [`FailureDisposition::resolve`] and pinned by its unit test.
use std::sync::Arc;
+use std::time::Duration;
use metrics::counter;
use tokio_util::sync::CancellationToken;
@@ -15,7 +16,7 @@ use tracing::{info, warn};
use crate::clickhouse::scanner::ChunkScanner;
use crate::domain::{
ChunkLease, ChunkSpec, ClaimedChunk, EnqueuedChunk, HaltReason, Halted, PinnedRun,
- ProducedChunk, ScannedChunk, StreamedChunk,
+ ProducedChunk, RetryBackoffPolicy, ScannedChunk, StreamedChunk,
};
use crate::kafka::pacing::TilePacer;
use crate::kafka::producer::SeedTileProducer;
@@ -38,6 +39,7 @@ pub(super) struct ChunkTaskContext {
pub(super) producer: SeedTileProducer,
pub(super) pacer: TilePacer,
pub(super) producer_settings: ProducerSettings,
+ pub(super) retry_backoff: RetryBackoffPolicy,
}
pub(super) async fn execute_chunk(
@@ -53,13 +55,14 @@ pub(super) async fn execute_chunk(
producer,
pacer,
producer_settings,
+ retry_backoff,
} = ctx;
let lease_cancel = lease.cancellation_token();
// PreMark: scan history into tiles.
let scanned = match scanner.scan(chunk, &run, &lease_cancel, &shutdown).await {
Ok(scanned) => scanned,
- Err(halt) => return resolve_halt(&store, halt, &shutdown).await,
+ Err(halt) => return resolve_halt(&store, halt, &shutdown, retry_backoff).await,
};
// PreMark: pace and enqueue every tile, holding the in-flight deliveries.
let (scanned, inflight) = match deliver::enqueue_tiles(
@@ -73,12 +76,14 @@ pub(super) async fn execute_chunk(
.await
{
Ok(pair) => pair,
- Err(halt) => return resolve_halt(&store, halt, &shutdown).await,
+ Err(halt) => return resolve_halt(&store, halt, &shutdown, retry_backoff).await,
};
// PreMark: CAS `scanning`→`produced` — the row is still `scanning` on failure.
let enqueued = match store.mark_produced(scanned).await {
Ok(enqueued) => enqueued,
- Err(halt) => return resolve_halt(&store, mark_produced_halt(halt), &shutdown).await,
+ Err(halt) => {
+ return resolve_halt(&store, mark_produced_halt(halt), &shutdown, retry_backoff).await
+ }
};
// PostMark: drain the remaining delivery acks and fold the high-water marks.
let produced = match deliver::await_deliveries(enqueued, inflight, &lease_cancel).await {
@@ -86,7 +91,7 @@ pub(super) async fn execute_chunk(
counter!(TILES_PRODUCED).increment(produced.tiles_produced());
produced
}
- Err(halt) => return resolve_halt(&store, halt, &shutdown).await,
+ Err(halt) => return resolve_halt(&store, halt, &shutdown, retry_backoff).await,
};
// PostMark: the terminal confirm — on failure the row is `produced`, so it is failed for retry.
let lease = produced.spec().lease;
@@ -96,7 +101,7 @@ pub(super) async fn execute_chunk(
lease,
tiles_produced,
},
- Err(halt) => resolve_halt(&store, halt, &shutdown).await,
+ Err(halt) => resolve_halt(&store, halt, &shutdown, retry_backoff).await,
}
}
@@ -172,12 +177,18 @@ 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.
+///
+/// The retry wait is drawn from the chunk's own attempt count, so a chunk failing repeatedly waits
+/// longer each time while a first failure retries almost immediately. An unclaim draws none: it
+/// refunds the attempt and is not a failure.
pub(super) async fn resolve_halt<S: ChunkState, E: std::error::Error>(
store: &PgChunkStore,
halt: Halted<S, E>,
shutdown: &CancellationToken,
+ retry_backoff: RetryBackoffPolicy,
) -> ChunkOutcome {
- let lease = halt.state.spec().lease;
+ let spec = halt.state.spec();
+ let lease = spec.lease;
let detail = render_reason(&halt.reason);
match FailureDisposition::resolve(S::STAGE, shutdown.is_cancelled()) {
FailureDisposition::Unclaim => match store.unclaim(lease).await {
@@ -188,17 +199,21 @@ pub(super) async fn resolve_halt<S: ChunkState, E: std::error::Error>(
recovery,
},
},
- FailureDisposition::Fail => match store.fail(lease, &detail).await {
- Ok(()) => ChunkOutcome::Failed {
- lease,
- detail: detail.as_str().to_string(),
- },
- Err(recovery) => ChunkOutcome::RecoveryFailed {
- lease,
- detail: detail.as_str().to_string(),
- recovery,
- },
- },
+ FailureDisposition::Fail => {
+ let retry_delay = retry_backoff.delay_after(spec.attempt);
+ match store.fail(lease, &detail, retry_delay).await {
+ Ok(()) => ChunkOutcome::Failed {
+ lease,
+ detail: detail.as_str().to_string(),
+ retry_delay,
+ },
+ Err(recovery) => ChunkOutcome::RecoveryFailed {
+ lease,
+ detail: detail.as_str().to_string(),
+ recovery,
+ },
+ }
+ }
}
}
@@ -229,6 +244,7 @@ pub(super) enum ChunkOutcome {
Failed {
lease: ChunkLease,
detail: String,
+ retry_delay: Duration,
},
Unclaimed {
lease: ChunkLease,
@@ -252,9 +268,18 @@ pub(super) fn record_task_result(
counter!(CHUNKS_CONFIRMED, "kind" => kind.as_str()).increment(1);
info!(?lease, tiles_produced, "chunk confirmed");
}
- Ok(ChunkOutcome::Failed { lease, detail }) => {
+ Ok(ChunkOutcome::Failed {
+ lease,
+ detail,
+ retry_delay,
+ }) => {
counter!(CHUNKS_FAILED, "kind" => kind.as_str()).increment(1);
- warn!(?lease, error = %detail, "chunk failed and was released for retry");
+ warn!(
+ ?lease,
+ error = %detail,
+ retry_delay_secs = retry_delay.as_secs_f64(),
+ "chunk failed and was released for retry"
+ );
}
Ok(ChunkOutcome::Unclaimed { lease }) => {
info!(?lease, "chunk unclaimed during shutdown");
diff --git a/rust/cohort-seeder/src/app/mod.rs b/rust/cohort-seeder/src/app/mod.rs
index 4e89cebb1920..9ab8ef795320 100644
--- a/rust/cohort-seeder/src/app/mod.rs
+++ b/rust/cohort-seeder/src/app/mod.rs
@@ -24,3 +24,34 @@ pub use orchestrator::{
};
pub use settings::{OrchestratorSettings, PersonSettings};
pub use watch::{MarkerWatchTask, PgMarkerFlush, WatchDirectives, MARKER_WATCH_LIVENESS_DEADLINE};
+
+/// Fail a claimed chunk through the executor's recovery path, and report the wait it drew.
+///
+/// The store's `fail` takes the delay as an argument, so a test that calls it directly pins nothing
+/// about where the delay comes from. This drives the one production call site instead: the resolver
+/// that reads the chunk's attempt count and asks the policy for a wait.
+///
+/// It lives here rather than in `test_support` because [`execute`]'s recovery types are
+/// `pub(super)`. Reaching them from a crate-root sibling means `pub(crate)`, which would let any
+/// module drive the recovery matrix directly, a wider contract than one test needs.
+#[cfg(feature = "pg-test-support")]
+#[doc(hidden)]
+pub async fn fail_via_recovery(
+ store: &crate::store::chunks::PgChunkStore,
+ chunk: crate::domain::ClaimedChunk,
+ message: &str,
+ retry_backoff: crate::domain::RetryBackoffPolicy,
+) -> Option<std::time::Duration> {
+ #[derive(Debug, thiserror::Error)]
+ #[error("{0}")]
+ struct RecoveryTestError(String);
+
+ let halt = crate::domain::Halted::failed(chunk, RecoveryTestError(message.to_owned()));
+ // Not cancelled: a pre-mark halt during shutdown unclaims instead of failing, which draws no
+ // wait at all.
+ let shutdown = tokio_util::sync::CancellationToken::new();
+ match execute::resolve_halt(store, halt, &shutdown, retry_backoff).await {
+ execute::ChunkOutcome::Failed { retry_delay, .. } => Some(retry_delay),
+ _ => None,
+ }
+}
diff --git a/rust/cohort-seeder/src/app/orchestrator.rs b/rust/cohort-seeder/src/app/orchestrator.rs
index be6124152b04..fcd8d9fb8f6c 100644
--- a/rust/cohort-seeder/src/app/orchestrator.rs
+++ b/rust/cohort-seeder/src/app/orchestrator.rs
@@ -383,6 +383,7 @@ impl SeederOrchestrator {
producer: self.producer.clone(),
pacer: self.pacer.clone(),
producer_settings: self.settings.producer,
+ retry_backoff: self.settings.retry_backoff,
};
let shutdown = shutdown.clone();
tasks.spawn(async move { execute_chunk(ctx, shutdown).await });
@@ -408,6 +409,7 @@ impl SeederOrchestrator {
pacer: person.pacer.clone(),
producer_settings: self.settings.producer,
emit_nonmatchers: person_settings.emit_nonmatchers,
+ retry_backoff: self.settings.retry_backoff,
};
let shutdown = shutdown.clone();
person_tasks.spawn(async move { execute_person_chunk(ctx, shutdown).await });
diff --git a/rust/cohort-seeder/src/app/person_execute.rs b/rust/cohort-seeder/src/app/person_execute.rs
index 36a02878c497..5efdb7d0847d 100644
--- a/rust/cohort-seeder/src/app/person_execute.rs
+++ b/rust/cohort-seeder/src/app/person_execute.rs
@@ -13,11 +13,14 @@ use tokio_util::sync::CancellationToken;
use cohort_core::hogvm::VmErrorClass;
-use crate::clickhouse::person_scanner::{PersonScanError, PersonScanner};
+use clickhouse::query::RowCursor;
+
+use crate::clickhouse::person_scanner::{PersonRow, PersonScanError, PersonScanner};
use crate::clickhouse::person_sql::PersonScanSpec;
+use crate::clickhouse::scan_volume::{self, ScanKind};
use crate::domain::{
CancelCause, ClaimedChunk, Halted, PersonChunkSpecError, PersonEvaluator, PersonRowOutcome,
- PersonSeedContext, PinnedPersonRun, RecordStats, StreamedChunk,
+ PersonSeedContext, PinnedPersonRun, RecordStats, RetryBackoffPolicy, StreamedChunk,
};
use crate::kafka::pacing::TilePacer;
use crate::kafka::producer::SeedTileProducer;
@@ -43,6 +46,7 @@ pub(super) struct PersonChunkTaskContext {
pub(super) pacer: TilePacer,
pub(super) producer_settings: ProducerSettings,
pub(super) emit_nonmatchers: bool,
+ pub(super) retry_backoff: RetryBackoffPolicy,
}
pub(super) async fn execute_person_chunk(
@@ -59,6 +63,7 @@ pub(super) async fn execute_person_chunk(
pacer,
producer_settings,
emit_nonmatchers,
+ retry_backoff,
} = ctx;
let lease_cancel = lease.cancellation_token();
@@ -77,17 +82,19 @@ pub(super) async fn execute_person_chunk(
.await
{
Ok(pair) => pair,
- Err(halt) => return resolve_halt(&store, halt, &shutdown).await,
+ Err(halt) => return resolve_halt(&store, halt, &shutdown, retry_backoff).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,
+ Err(halt) => {
+ return resolve_halt(&store, mark_produced_halt(halt), &shutdown, retry_backoff).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,
+ Err(halt) => return resolve_halt(&store, halt, &shutdown, retry_backoff).await,
};
let lease = produced.spec().lease;
let seeds_produced = produced.tiles_produced();
@@ -96,7 +103,7 @@ pub(super) async fn execute_person_chunk(
lease,
tiles_produced: seeds_produced,
},
- Err(halt) => resolve_halt(&store, halt, &shutdown).await,
+ Err(halt) => resolve_halt(&store, halt, &shutdown, retry_backoff).await,
}
}
@@ -117,7 +124,7 @@ async fn stream_chunk(
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) {
+ let mut cursor = match scanner.scan_rows(&scan_spec, chunk.spec()) {
Ok(cursor) => cursor,
Err(error) => return Err(Halted::failed(chunk, PersonChunkError::Scan(error))),
};
@@ -134,33 +141,70 @@ async fn stream_chunk(
// near-zero samples.
let _timer = MetricTimer::start(PERSON_CHUNK_SCAN_DURATION_SECONDS);
+ // Every way out of the fold funnels back here, so the volume is metered once whether the scan
+ // finished, was cancelled, or failed mid-stream.
+ let folded = fold_person_rows(
+ &mut cursor,
+ &mut evaluator,
+ &seed_ctx,
+ producer,
+ &mut inflight,
+ pacer,
+ settings,
+ &mut seeds_produced,
+ lease_cancel,
+ shutdown,
+ )
+ .await;
+ let volume = scan_volume::observe(ScanKind::Person, &cursor);
+ match folded {
+ Ok(()) => Ok((chunk.into_streamed(seeds_produced, volume), inflight)),
+ Err(stop) => Err(stop.into_halt(chunk)),
+ }
+}
+
+/// Drive the person cursor into the evaluator and the paced producer until it is exhausted,
+/// cancelled, or fails. Returns rather than metering, so the caller owns the single recording site.
+#[allow(clippy::too_many_arguments)]
+async fn fold_person_rows(
+ cursor: &mut RowCursor<PersonRow>,
+ evaluator: &mut PersonEvaluator,
+ seed_ctx: &PersonSeedContext,
+ producer: &SeedTileProducer,
+ inflight: &mut InFlight,
+ pacer: &TilePacer,
+ settings: ProducerSettings,
+ seeds_produced: &mut u64,
+ lease_cancel: &CancellationToken,
+ shutdown: &CancellationToken,
+) -> Result<(), PersonStreamStop> {
loop {
let row = tokio::select! {
biased;
_ = shutdown.cancelled() => {
- return Err(Halted::cancelled(chunk, CancelCause::Shutdown));
+ return Err(PersonStreamStop::Cancelled(CancelCause::Shutdown));
}
_ = lease_cancel.cancelled() => {
- return Err(Halted::cancelled(chunk, CancelCause::LeaseLost));
+ return Err(PersonStreamStop::Cancelled(CancelCause::LeaseLost));
}
row = cursor.next() => match row {
Ok(row) => row,
Err(error) => {
- return Err(Halted::failed(chunk, PersonChunkError::Cursor(error)));
+ return Err(PersonStreamStop::Failed(PersonChunkError::Cursor(error)));
}
},
};
let Some(row) = row else {
- break;
+ return Ok(());
};
counter!(PERSONS_SCANNED).increment(1);
- let (outcome, stats) = evaluator.evaluate_row(&row.id, &row.properties, &seed_ctx);
+ 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,
+ inflight,
pacer,
settings,
lease_cancel,
@@ -168,9 +212,9 @@ async fn stream_chunk(
)
.await
{
- return Err(produce_halt(chunk, stop));
+ return Err(stop.into());
}
- seeds_produced += 1;
+ *seeds_produced += 1;
counter!(PERSON_SEEDS_PRODUCED).increment(1);
}
PersonRowOutcome::NonMatcher => {
@@ -181,14 +225,30 @@ async fn stream_chunk(
}
}
}
+}
- Ok((chunk.into_streamed(seeds_produced), inflight))
+/// Why the person fold stopped, carried without the chunk so the caller can meter the cursor before
+/// giving the chunk up to [`Halted`].
+enum PersonStreamStop {
+ Cancelled(CancelCause),
+ Failed(PersonChunkError),
}
-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)),
+impl PersonStreamStop {
+ fn into_halt(self, chunk: ClaimedChunk) -> Halted<ClaimedChunk, PersonChunkError> {
+ match self {
+ Self::Cancelled(cause) => Halted::cancelled(chunk, cause),
+ Self::Failed(error) => Halted::failed(chunk, error),
+ }
+ }
+}
+
+impl From<ProduceStop> for PersonStreamStop {
+ fn from(stop: ProduceStop) -> Self {
+ match stop {
+ ProduceStop::Cancelled(cause) => Self::Cancelled(cause),
+ ProduceStop::Failed(error) => Self::Failed(PersonChunkError::Produce(error)),
+ }
}
}
diff --git a/rust/cohort-seeder/src/app/person_plan.rs b/rust/cohort-seeder/src/app/person_plan.rs
index 30d0d2b80e17..d0dac6b06b77 100644
--- a/rust/cohort-seeder/src/app/person_plan.rs
+++ b/rust/cohort-seeder/src/app/person_plan.rs
@@ -91,7 +91,13 @@ async fn plan_claimed_run(
let timer = MetricTimer::start(PERSON_PLANNING_DURATION_SECONDS);
let boundaries = match scanner
- .boundaries(run.team_id, run.scan_since, persons_per_chunk, shutdown)
+ .boundaries(
+ run_id,
+ run.team_id,
+ run.scan_since,
+ persons_per_chunk,
+ shutdown,
+ )
.await
{
Ok(boundaries) => boundaries,
diff --git a/rust/cohort-seeder/src/app/settings.rs b/rust/cohort-seeder/src/app/settings.rs
index 3f07ae27e81d..a573f4fbda1c 100644
--- a/rust/cohort-seeder/src/app/settings.rs
+++ b/rust/cohort-seeder/src/app/settings.rs
@@ -6,7 +6,7 @@ use std::num::{NonZeroU16, NonZeroU32, NonZeroU64, NonZeroUsize};
use std::time::Duration;
use crate::config::Config;
-use crate::domain::PlanCaps;
+use crate::domain::{BackoffPolicyError, PlanCaps, RetryBackoffPolicy};
use crate::store::runs::RunKind;
use crate::store::{LeaseDuration, LeaseDurationError, MaxAttempts, MaxAttemptsError};
@@ -60,6 +60,7 @@ pub struct OrchestratorSettings {
pub(super) max_concurrent_chunks: NonZeroUsize,
pub(super) chunk_lease: LeaseDuration,
pub(super) max_chunk_attempts: MaxAttempts,
+ pub(super) retry_backoff: RetryBackoffPolicy,
pub(super) plan_caps: PlanCaps,
pub(super) producer: ProducerSettings,
pub(super) person: Option<PersonSettings>,
@@ -72,6 +73,7 @@ impl OrchestratorSettings {
max_concurrent_chunks: usize,
chunk_lease: Duration,
max_chunk_attempts: u32,
+ retry_backoff: RetryBackoffPolicy,
max_lookback_days: u32,
bands_per_day: u16,
producer: ProducerSettings,
@@ -103,6 +105,7 @@ impl OrchestratorSettings {
max_concurrent_chunks,
chunk_lease,
max_chunk_attempts,
+ retry_backoff,
plan_caps: PlanCaps {
max_lookback_days,
bands_per_day,
@@ -164,11 +167,17 @@ impl TryFrom<&Config> for OrchestratorSettings {
Ok::<_, OrchestratorSettingsError>(person)
})
.transpose()?;
+ let retry_backoff = RetryBackoffPolicy::new(
+ Duration::from_secs(config.seeder_retry_backoff_base_secs),
+ Duration::from_secs(config.seeder_retry_backoff_cap_secs),
+ )
+ .map_err(OrchestratorSettingsError::RetryBackoff)?;
Ok(Self::new(
Duration::from_secs(config.seeder_run_poll_secs),
config.seeder_max_concurrent_chunks,
Duration::from_secs(config.seeder_chunk_lease_secs),
config.seeder_max_chunk_attempts,
+ retry_backoff,
config.seeder_max_lookback_days,
config.seeder_bands_per_day,
producer,
@@ -195,6 +204,8 @@ pub enum OrchestratorSettingsError {
MaxAttemptsOutOfRange,
#[error("bands per day must be between 1 and 32767")]
BandsPerDayOutOfRange,
+ #[error(transparent)]
+ RetryBackoff(#[from] BackoffPolicyError),
#[error("person seeds per second must be greater than zero")]
ZeroPersonSeedRate,
#[error("persons per chunk must be greater than zero")]
@@ -267,6 +278,10 @@ mod tests {
ProducerSettings::new(1, Duration::from_millis(1)).unwrap()
}
+ fn backoff() -> RetryBackoffPolicy {
+ RetryBackoffPolicy::new(Duration::from_secs(30), Duration::from_secs(1800)).unwrap()
+ }
+
#[test]
fn producer_settings_reject_unbounded_bounds() {
assert_eq!(
@@ -294,6 +309,7 @@ mod tests {
1,
Duration::from_secs(3),
1,
+ backoff(),
400,
1,
producer_settings(),
@@ -307,6 +323,7 @@ mod tests {
1,
Duration::from_secs(3),
1,
+ backoff(),
400,
1,
producer_settings(),
@@ -320,6 +337,7 @@ mod tests {
0,
Duration::from_secs(3),
1,
+ backoff(),
400,
1,
producer_settings(),
@@ -333,6 +351,7 @@ mod tests {
1,
Duration::from_secs(2),
1,
+ backoff(),
400,
1,
producer_settings(),
@@ -346,6 +365,7 @@ mod tests {
1,
Duration::from_secs(3),
0,
+ backoff(),
400,
1,
producer_settings(),
@@ -359,6 +379,7 @@ mod tests {
1,
Duration::from_secs(3),
1,
+ backoff(),
400,
0,
producer_settings(),
@@ -372,6 +393,7 @@ mod tests {
1,
Duration::from_secs(3),
1,
+ backoff(),
400,
u16::MAX,
producer_settings(),
@@ -477,6 +499,35 @@ mod tests {
));
}
+ /// A backoff pair that cannot space retries must fail at startup. Accepting it would leave the
+ /// claim gate stamping a zero or shrinking wait, which is the reclaim storm the policy exists
+ /// to stop, and nothing downstream would report it.
+ #[test]
+ fn retry_backoff_is_parsed_from_config_and_rejected_when_it_cannot_space_retries() {
+ let config = Config::init_from_hashmap(&HashMap::new()).unwrap();
+ let settings = OrchestratorSettings::try_from(&config).unwrap();
+ assert_eq!(settings.retry_backoff.base(), Duration::from_secs(30));
+ assert_eq!(settings.retry_backoff.cap(), Duration::from_secs(1800));
+
+ let mut zero_base = config.clone();
+ zero_base.seeder_retry_backoff_base_secs = 0;
+ assert!(matches!(
+ OrchestratorSettings::try_from(&zero_base),
+ Err(SettingsError::Orchestrator(
+ OrchestratorSettingsError::RetryBackoff(BackoffPolicyError::ZeroBase)
+ ))
+ ));
+
+ let mut cap_below_base = config.clone();
+ cap_below_base.seeder_retry_backoff_cap_secs = 29;
+ assert!(matches!(
+ OrchestratorSettings::try_from(&cap_below_base),
+ Err(SettingsError::Orchestrator(
+ OrchestratorSettingsError::RetryBackoff(BackoffPolicyError::CapBelowBase)
+ ))
+ ));
+ }
+
#[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/log_comment.rs b/rust/cohort-seeder/src/clickhouse/log_comment.rs
new file mode 100644
index 000000000000..defe0eaf467a
--- /dev/null
+++ b/rust/cohort-seeder/src/clickhouse/log_comment.rs
@@ -0,0 +1,262 @@
+//! The `log_comment` ClickHouse query setting the seeder stamps on every scan, so a row in
+//! `system.query_log` names the run, chunk, and claim epoch that issued it. Depends on `domain`;
+//! never on `store` or `kafka`.
+//!
+//! ClickHouse copies `log_comment` verbatim into `system.query_log.log_comment`, which is how an
+//! operator joins a slow or killed query back to the chunk ledger. That join only works while every
+//! call site renders the same field vocabulary, so this type is the sole writer: a scanner picks a
+//! variant, never a format string.
+//!
+//! The rendering is a JSON object because `system.query_log` has short retention and the durable
+//! record is `query_log_archive`, which extracts its columns with `JSONExtract*` over
+//! `log_comment` — `team_id`, `product`, `feature`, and `cohort_id` among them. A non-JSON comment
+//! extracts to defaults, so every seeder scan would archive under team 0. The key vocabulary is
+//! `posthog/clickhouse/query_tagging.py`'s, so the seeder's rows read the same as Django's.
+
+use std::fmt;
+
+use cohort_core::filters::{CohortId, TeamId};
+use serde::Serialize;
+use uuid::Uuid;
+
+use crate::domain::{ChunkSpec, DayIdx, RunId};
+
+/// The setting name ClickHouse reads. Bound through `Query::with_option`, which URL-encodes the
+/// value, so the rendered comment needs no escaping of its own.
+pub const LOG_COMMENT_OPTION: &str = "log_comment";
+
+/// The `kind` every seeder comment carries, in the same slot `query_tagging.py` gives `"temporal"`
+/// and `"dagster"`: the process that issued the query. This is what an operator filters the
+/// archive on to select the seeder's work.
+const SEEDER_KIND: &str = "cohort_seeder";
+
+/// `Product.COHORTS` and `Feature.BEHAVIORAL_COHORTS` from `query_tagging.py`. Repeated here rather
+/// than generated, because the Python enum is not reachable from Rust; the archive's `lc_product`
+/// and `lc_feature` columns are what tie the two spellings together.
+const COHORTS_PRODUCT: &str = "cohorts";
+const BEHAVIORAL_COHORTS_FEATURE: &str = "behavioral_cohorts";
+
+/// One scan's attribution. Each variant carries only what identifies that query's work:
+/// a person chunk has no meaningful `day` (person runs are planned under a far-future sentinel day
+/// that would read as a real date in `query_log`), and a boundary aggregation runs before any chunk
+/// exists. An absent field is omitted rather than rendered empty, so `JSONExtract*` returns its
+/// default and the archive column reads as "not applicable to this phase".
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ScanLogComment {
+ /// `cohort_id` is present only when every pinned condition on the run belongs to one cohort —
+ /// the save-triggered shape. A team-enablement run spans cohorts, and naming any one of them
+ /// would misattribute the scan's cost to it.
+ BehavioralChunk {
+ spec: ChunkSpec,
+ cohort_id: Option<CohortId>,
+ },
+ PersonChunk(ChunkSpec),
+ PersonBoundaries {
+ run_id: RunId,
+ team_id: TeamId,
+ },
+}
+
+impl ScanLogComment {
+ const fn phase(self) -> &'static str {
+ match self {
+ Self::BehavioralChunk { .. } => "behavioral",
+ Self::PersonChunk(_) => "person_scan",
+ Self::PersonBoundaries { .. } => "person_boundaries",
+ }
+ }
+
+ fn fields(self) -> LogCommentFields {
+ let phase = self.phase();
+ match self {
+ // `day` is the seeder's day index, the same value its logs and its chunk planner carry,
+ // so an operator matches a `query_log` row to a log line without converting anything.
+ Self::BehavioralChunk { spec, cohort_id } => LogCommentFields {
+ cohort_id: cohort_id.map(|cohort_id| cohort_id.0),
+ day: Some(spec.day),
+ ..LogCommentFields::for_chunk(phase, spec)
+ },
+ Self::PersonChunk(spec) => LogCommentFields::for_chunk(phase, spec),
+ Self::PersonBoundaries { run_id, team_id } => {
+ LogCommentFields::for_run(phase, team_id, run_id)
+ }
+ }
+ }
+}
+
+/// The rendered object. Field order is declaration order, which is what makes the byte-pinning
+/// test below a contract rather than a snapshot of whatever order a map happened to produce.
+#[derive(Debug, Serialize)]
+struct LogCommentFields {
+ kind: &'static str,
+ product: &'static str,
+ feature: &'static str,
+ team_id: i32,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ cohort_id: Option<i32>,
+ run_id: Uuid,
+ phase: &'static str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ chunk: Option<Uuid>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ day: Option<DayIdx>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ band: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ num_bands: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ epoch: Option<i32>,
+}
+
+impl LogCommentFields {
+ /// The attribution every phase carries. The three constant keys are set here rather than
+ /// defaulted, so a new variant cannot render an unattributed comment by forgetting them.
+ fn for_run(phase: &'static str, team_id: TeamId, run_id: RunId) -> Self {
+ Self {
+ kind: SEEDER_KIND,
+ product: COHORTS_PRODUCT,
+ feature: BEHAVIORAL_COHORTS_FEATURE,
+ team_id: team_id.0,
+ cohort_id: None,
+ run_id: run_id.0,
+ phase,
+ chunk: None,
+ day: None,
+ band: None,
+ num_bands: None,
+ epoch: None,
+ }
+ }
+
+ fn for_chunk(phase: &'static str, spec: ChunkSpec) -> Self {
+ Self {
+ chunk: Some(spec.lease.chunk_id().0),
+ band: Some(spec.band.band()),
+ num_bands: Some(spec.band.num_bands().get()),
+ epoch: Some(spec.lease.epoch().0),
+ ..Self::for_run(phase, spec.team_id, spec.lease.run_id())
+ }
+ }
+}
+
+impl fmt::Display for ScanLogComment {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ // Every value is an integer, a UUID, or one of this module's static strings, so the only
+ // way `to_string` fails is a serde bug. Rendering nothing would silently un-attribute the
+ // scan, so the error surfaces as a formatting error instead.
+ let json = serde_json::to_string(&self.fields()).map_err(|_| fmt::Error)?;
+ formatter.write_str(&json)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use uuid::Uuid;
+
+ use super::*;
+ use crate::domain::{
+ AttemptCount, BandSpec, ChunkId, ChunkLease, ClaimEpoch, PersonRange, SChunkMs,
+ };
+
+ fn spec(person_range: Option<PersonRange>) -> ChunkSpec {
+ ChunkSpec {
+ lease: ChunkLease::new(
+ ChunkId(Uuid::from_u128(0xC0)),
+ RunId(Uuid::from_u128(0x2A)),
+ ClaimEpoch(7),
+ ),
+ team_id: TeamId(2),
+ day: 20_000,
+ band: BandSpec::new(3, 8).unwrap(),
+ s_chunk: SChunkMs(1_700_000_000_000),
+ person_range,
+ attempt: AttemptCount::from_row(1),
+ }
+ }
+
+ /// The rendered text is the join key an operator types into `system.query_log`, and the shape
+ /// `query_log_archive` extracts its columns from, so it is pinned byte for byte: a renamed or
+ /// reordered field silently breaks every saved query against it.
+ #[test]
+ fn each_scan_phase_renders_its_pinned_field_vocabulary() {
+ assert_eq!(
+ ScanLogComment::BehavioralChunk {
+ spec: spec(None),
+ cohort_id: None,
+ }
+ .to_string(),
+ r#"{"kind":"cohort_seeder","product":"cohorts","feature":"behavioral_cohorts","#
+ .to_owned()
+ + r#""team_id":2,"run_id":"00000000-0000-0000-0000-00000000002a","#
+ + r#""phase":"behavioral","chunk":"00000000-0000-0000-0000-0000000000c0","#
+ + r#""day":20000,"band":3,"num_bands":8,"epoch":7}"#
+ );
+ assert_eq!(
+ ScanLogComment::BehavioralChunk {
+ spec: spec(None),
+ cohort_id: Some(CohortId(91)),
+ }
+ .to_string(),
+ r#"{"kind":"cohort_seeder","product":"cohorts","feature":"behavioral_cohorts","#
+ .to_owned()
+ + r#""team_id":2,"cohort_id":91,"run_id":"00000000-0000-0000-0000-00000000002a","#
+ + r#""phase":"behavioral","chunk":"00000000-0000-0000-0000-0000000000c0","#
+ + r#""day":20000,"band":3,"num_bands":8,"epoch":7}"#
+ );
+ let range = PersonRange::new(Uuid::from_u128(1), Some(Uuid::from_u128(2))).unwrap();
+ assert_eq!(
+ ScanLogComment::PersonChunk(spec(Some(range))).to_string(),
+ r#"{"kind":"cohort_seeder","product":"cohorts","feature":"behavioral_cohorts","#
+ .to_owned()
+ + r#""team_id":2,"run_id":"00000000-0000-0000-0000-00000000002a","#
+ + r#""phase":"person_scan","chunk":"00000000-0000-0000-0000-0000000000c0","#
+ + r#""band":3,"num_bands":8,"epoch":7}"#
+ );
+ assert_eq!(
+ ScanLogComment::PersonBoundaries {
+ run_id: RunId(Uuid::from_u128(0x2A)),
+ team_id: TeamId(2),
+ }
+ .to_string(),
+ r#"{"kind":"cohort_seeder","product":"cohorts","feature":"behavioral_cohorts","#
+ .to_owned()
+ + r#""team_id":2,"run_id":"00000000-0000-0000-0000-00000000002a","#
+ + r#""phase":"person_boundaries"}"#
+ );
+ }
+
+ /// `query_log_archive` reads these four keys with `JSONExtract*`, and `team_id` is the archive
+ /// table's own sort key. A phase that dropped one would archive unattributed — under team 0,
+ /// which reads as a bug in someone else's product.
+ #[test]
+ fn every_phase_archives_under_its_team_product_and_feature() {
+ let range = PersonRange::new(Uuid::from_u128(1), None).unwrap();
+ for comment in [
+ ScanLogComment::BehavioralChunk {
+ spec: spec(None),
+ cohort_id: None,
+ },
+ ScanLogComment::PersonChunk(spec(Some(range))),
+ ScanLogComment::PersonBoundaries {
+ run_id: RunId(Uuid::nil()),
+ team_id: TeamId(2),
+ },
+ ] {
+ let rendered = comment.to_string();
+ let parsed: serde_json::Value =
+ serde_json::from_str(&rendered).expect("the comment is JSON");
+ assert_eq!(parsed["team_id"], 2, "{rendered} lost its team");
+ assert_eq!(parsed["kind"], SEEDER_KIND, "{rendered} lost its kind");
+ assert_eq!(parsed["product"], "cohorts", "{rendered} lost its product");
+ assert_eq!(
+ parsed["feature"], "behavioral_cohorts",
+ "{rendered} lost its feature"
+ );
+ assert_eq!(
+ parsed["phase"],
+ comment.phase(),
+ "{rendered} lost its phase"
+ );
+ }
+ }
+}
diff --git a/rust/cohort-seeder/src/clickhouse/mod.rs b/rust/cohort-seeder/src/clickhouse/mod.rs
index 63961d5c0b84..4be3462afd8d 100644
--- a/rust/cohort-seeder/src/clickhouse/mod.rs
+++ b/rust/cohort-seeder/src/clickhouse/mod.rs
@@ -1,17 +1,21 @@
-//! 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`.
+//! ClickHouse layer: scan planning, row decoding, query attribution, 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 log_comment;
pub mod person_scanner;
pub mod person_sql;
pub mod row;
+pub mod scan_volume;
pub mod scanner;
pub mod sql;
pub use client::{
build_client, ClickHouseClientError, ClickHouseEndpoint, ClickHouseJoinAlgorithm,
};
+pub use log_comment::{ScanLogComment, LOG_COMMENT_OPTION};
pub use person_scanner::{PersonRow, PersonScanError, PersonScanner};
pub use person_sql::PersonScanSpec;
+pub use scan_volume::ScanKind;
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
index ca27bea238e0..308d46169913 100644
--- a/rust/cohort-seeder/src/clickhouse/person_scanner.rs
+++ b/rust/cohort-seeder/src/clickhouse/person_scanner.rs
@@ -12,8 +12,10 @@ use tokio_util::sync::CancellationToken;
use tracing::warn;
use uuid::Uuid;
+use super::log_comment::{ScanLogComment, LOG_COMMENT_OPTION};
use super::person_sql::{person_boundaries_sql, person_scan_sql, PersonScanSpec};
-use crate::domain::{UtcMillis, MAX_PERSON_CHUNKS};
+use super::scan_volume::{self, ScanKind};
+use crate::domain::{ChunkSpec, RunId, UtcMillis, MAX_PERSON_CHUNKS};
/// One scanned person's latest row: the id and its `argMax(properties, version)` payload.
#[derive(Debug, Row, Deserialize)]
@@ -43,6 +45,7 @@ impl PersonScanner {
/// scan stops early rather than failing a run over a column-width constraint.
pub async fn boundaries(
&self,
+ run_id: RunId,
team_id: TeamId,
scan_since: UtcMillis,
persons_per_chunk: NonZeroU64,
@@ -51,42 +54,68 @@ impl PersonScanner {
let mut cursor = self
.client
.query(&person_boundaries_sql(team_id, scan_since))
+ .with_option(
+ LOG_COMMENT_OPTION,
+ ScanLogComment::PersonBoundaries { run_id, team_id }.to_string(),
+ )
.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;
- }
- }
+ // Every way out of the fold funnels back here, so the volume is metered once whether the
+ // scan finished, saturated, or failed mid-stream. This is a whole-team scan, so a run that
+ // dies planning still reports what it moved.
+ let folded = fold_boundaries(&mut cursor, &mut keeper, team_id, shutdown).await;
+ scan_volume::observe(ScanKind::PersonBoundaries, &cursor);
+ folded?;
Ok(keeper.into_boundaries())
}
- /// The streaming cursor over one chunk's UUID range; the caller owns the fold.
+ /// The streaming cursor over one chunk's UUID range; the caller owns the fold. `chunk` is the
+ /// claim the range came from, and is used only to attribute the query in `system.query_log`.
pub fn scan_rows(
&self,
spec: &PersonScanSpec,
+ chunk: ChunkSpec,
) -> Result<RowCursor<PersonRow>, PersonScanError> {
self.client
.query(&person_scan_sql(spec))
+ .with_option(
+ LOG_COMMENT_OPTION,
+ ScanLogComment::PersonChunk(chunk).to_string(),
+ )
.fetch::<PersonRow>()
.map_err(PersonScanError::Query)
}
}
+/// Drive the boundary cursor into the keeper until it is exhausted, saturated, cancelled, or fails.
+/// Returns rather than metering, so the caller owns the single recording site.
+async fn fold_boundaries(
+ cursor: &mut RowCursor<PersonIdRow>,
+ keeper: &mut BoundaryKeeper,
+ team_id: TeamId,
+ shutdown: &CancellationToken,
+) -> Result<(), PersonScanError> {
+ 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 {
+ return Ok(());
+ };
+ if keeper.observe(row.id)? == BoundaryScanStep::Saturated {
+ warn!(
+ team_id = team_id.0,
+ persons_per_chunk = keeper.stride,
+ "person chunk ceiling saturated; the final chunk absorbs the remainder"
+ );
+ return Ok(());
+ }
+ }
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BoundaryScanStep {
Continue,
diff --git a/rust/cohort-seeder/src/clickhouse/scan_volume.rs b/rust/cohort-seeder/src/clickhouse/scan_volume.rs
new file mode 100644
index 000000000000..c9ad6ab2eca7
--- /dev/null
+++ b/rust/cohort-seeder/src/clickhouse/scan_volume.rs
@@ -0,0 +1,46 @@
+//! Reads a finished scan cursor's byte counters and meters them. Depends on `domain` and the
+//! `clickhouse` crate; never on `store` or `kafka`.
+//!
+//! All three scan paths call [`observe`] at exactly one place, after their cursor loop has stopped
+//! for any reason, so the counters cover halts and failures as well as clean exhaustion. That is
+//! the point: a chunk that died at the ClickHouse execution-time limit still moved bytes, and those
+//! are the chunks worth sizing.
+
+use clickhouse::query::RowCursor;
+use metrics::counter;
+
+use crate::domain::ScanVolume;
+use crate::observability::metrics::{SCAN_DECODED_BYTES, SCAN_RECEIVED_BYTES};
+
+/// Which scan a volume came from. The paths read different tables with different row shapes, so one
+/// series would average them into a number describing neither. [`ScanKind::PersonBoundaries`] is
+/// separate again because it is one whole-team scan per run rather than one per chunk: folding it
+/// into `Person` would put a run's largest single scan in the same series as its smallest.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ScanKind {
+ Behavioral,
+ Person,
+ PersonBoundaries,
+}
+
+impl ScanKind {
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::Behavioral => "behavioral",
+ Self::Person => "person",
+ Self::PersonBoundaries => "person_boundaries",
+ }
+ }
+}
+
+/// Read what the cursor moved and add it to the counters.
+///
+/// The cursor counts only what the client actually pulled, so a scan cancelled by shutdown or a
+/// lost lease reports less than the query would have returned. That is the intended reading: these
+/// counters measure transferred bytes, not query result size.
+pub fn observe<T>(kind: ScanKind, cursor: &RowCursor<T>) -> ScanVolume {
+ let volume = ScanVolume::new(cursor.received_bytes(), cursor.decoded_bytes());
+ counter!(SCAN_RECEIVED_BYTES, "kind" => kind.as_str()).increment(volume.received_bytes());
+ counter!(SCAN_DECODED_BYTES, "kind" => kind.as_str()).increment(volume.decoded_bytes());
+ volume
+}
diff --git a/rust/cohort-seeder/src/clickhouse/scanner.rs b/rust/cohort-seeder/src/clickhouse/scanner.rs
index 28de9fc73d61..8abc991322f4 100644
--- a/rust/cohort-seeder/src/clickhouse/scanner.rs
+++ b/rust/cohort-seeder/src/clickhouse/scanner.rs
@@ -4,20 +4,24 @@
use chrono::Utc;
use chrono_tz::Tz;
+use clickhouse::query::RowCursor;
use cohort_core::clickhouse_timestamp_to_millis;
use cohort_core::day_idx_in_tz;
use cohort_core::events::CohortStreamEvent;
+use cohort_core::filters::TeamId;
use cohort_core::hogvm::VmErrorClass;
use metrics::{counter, histogram};
use tokio_util::sync::CancellationToken;
use tracing::info;
+use super::log_comment::{ScanLogComment, LOG_COMMENT_OPTION};
use super::row::{row_to_event, EventRow};
+use super::scan_volume::{self, ScanKind};
use super::sql::{plan_scan, scan_sql, ScanPlan};
use crate::domain::{
conditions_active_on, ActiveConditions, AggregateError, CancelCause, ChunkAccumulator,
ChunkDomainError, ClaimedChunk, DayIdx, EventNameSet, Halted, PinnedCondition, PinnedRun,
- RecordOutcome, RecordStats, ScannedChunk, SeedDomain, SeedTile, UtcMillis,
+ RecordOutcome, RecordStats, ScanVolume, ScannedChunk, SeedDomain, SeedTile, UtcMillis,
};
use crate::observability::metrics::{
MetricTimer, AGGREGATE_ENTRIES, CHUNKS_VACUOUS, CHUNK_SCAN_DURATION_SECONDS,
@@ -63,7 +67,7 @@ impl ChunkScanner {
.scan_tiles(&chunk, run, now_ms, lease_cancel, shutdown)
.await
{
- Ok(tiles) => Ok(chunk.into_scanned(tiles)),
+ Ok((tiles, volume)) => Ok(chunk.into_scanned(tiles, volume)),
Err(ScanHalt::Cancelled(cause)) => Err(Halted::cancelled(chunk, cause)),
Err(ScanHalt::Failed(source)) => Err(Halted::failed(chunk, source)),
}
@@ -76,7 +80,7 @@ impl ChunkScanner {
now_ms: i64,
lease_cancel: &CancellationToken,
shutdown: &CancellationToken,
- ) -> Result<Vec<SeedTile>, ScanHalt> {
+ ) -> Result<(Vec<SeedTile>, ScanVolume), ScanHalt> {
let _timer = MetricTimer::start(CHUNK_SCAN_DURATION_SECONDS);
let spec = chunk.spec();
let domain = run.domain_for(&spec).map_err(ScanError::from)?;
@@ -88,54 +92,94 @@ impl ChunkScanner {
"chunk skipped: every referencing window has slid past this day"
);
counter!(CHUNKS_VACUOUS, "reason" => "window_expired").increment(1);
- return Ok(Vec::new());
+ return Ok((Vec::new(), ScanVolume::default()));
}
let event_names = active_event_names(run, &active);
let scan_spec = match plan_scan(spec.team_id, &domain, &event_names, spec.band) {
ScanPlan::Scan(scan_spec) => scan_spec,
ScanPlan::Vacuous => {
counter!(CHUNKS_VACUOUS, "reason" => "empty_scan").increment(1);
- return Ok(Vec::new());
+ return Ok((Vec::new(), ScanVolume::default()));
}
};
let mut cursor = self
.client
.query(&scan_sql(&scan_spec))
+ .with_option(
+ LOG_COMMENT_OPTION,
+ ScanLogComment::BehavioralChunk {
+ spec,
+ cohort_id: run.sole_cohort_id(),
+ }
+ .to_string(),
+ )
.fetch::<EventRow>()
.map_err(ScanError::Query)?;
let mut accumulator =
ChunkAccumulator::new(run.team_id, &run.filters, &active).map_err(ScanError::from)?;
- let mut saw_row = false;
-
- loop {
- let row = tokio::select! {
- biased;
- _ = shutdown.cancelled() => return Err(ScanHalt::Cancelled(CancelCause::Shutdown)),
- _ = lease_cancel.cancelled() => return Err(ScanHalt::Cancelled(CancelCause::LeaseLost)),
- row = cursor.next() => row.map_err(ScanError::Cursor)?,
- };
- let Some(row) = row else {
- break;
- };
- saw_row = true;
- counter!(ROWS_SCANNED).increment(1);
- match fold_event(&domain, &mut accumulator, row_to_event(run.team_id, row))
- .map_err(ScanError::from)?
- {
- ScanEventOutcome::Evaluated(stats) => record_evaluation(stats),
- ScanEventOutcome::Skipped(reason) => {
- counter!(EVENTS_SKIPPED, "reason" => reason.as_str()).increment(1);
- }
- }
- }
- if !saw_row {
+
+ // Every way out of the fold funnels back here, so the volume is metered once whether the
+ // scan finished, was cancelled, or failed mid-stream.
+ let folded = fold_cursor(
+ &mut cursor,
+ &mut accumulator,
+ &domain,
+ run.team_id,
+ lease_cancel,
+ shutdown,
+ )
+ .await;
+ let volume = scan_volume::observe(ScanKind::Behavioral, &cursor);
+ if folded? == RowsSeen::None {
counter!(CHUNKS_VACUOUS, "reason" => "no_rows").increment(1);
}
histogram!(AGGREGATE_ENTRIES).record(accumulator.entry_count() as f64);
let tiles = accumulator.into_tiles(&domain, run.run_id, spec.lease.epoch());
- Ok(tiles)
+ Ok((tiles, volume))
+ }
+}
+
+/// Whether the cursor yielded anything, which is what separates a chunk with no matching history
+/// from one that produced no tiles for another reason.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum RowsSeen {
+ None,
+ Some,
+}
+
+/// Drive the cursor into the accumulator until it is exhausted, cancelled, or fails. Returns rather
+/// than metering, so the caller owns the single recording site.
+async fn fold_cursor(
+ cursor: &mut RowCursor<EventRow>,
+ accumulator: &mut ChunkAccumulator,
+ domain: &SeedDomain,
+ team_id: TeamId,
+ lease_cancel: &CancellationToken,
+ shutdown: &CancellationToken,
+) -> Result<RowsSeen, ScanHalt> {
+ let mut rows_seen = RowsSeen::None;
+ loop {
+ let row = tokio::select! {
+ biased;
+ _ = shutdown.cancelled() => return Err(ScanHalt::Cancelled(CancelCause::Shutdown)),
+ _ = lease_cancel.cancelled() => return Err(ScanHalt::Cancelled(CancelCause::LeaseLost)),
+ row = cursor.next() => row.map_err(ScanError::Cursor)?,
+ };
+ let Some(row) = row else {
+ return Ok(rows_seen);
+ };
+ rows_seen = RowsSeen::Some;
+ counter!(ROWS_SCANNED).increment(1);
+ match fold_event(domain, accumulator, row_to_event(team_id, row))
+ .map_err(ScanError::from)?
+ {
+ ScanEventOutcome::Evaluated(stats) => record_evaluation(stats),
+ ScanEventOutcome::Skipped(reason) => {
+ counter!(EVENTS_SKIPPED, "reason" => reason.as_str()).increment(1);
+ }
+ }
}
}
diff --git a/rust/cohort-seeder/src/config.rs b/rust/cohort-seeder/src/config.rs
index 542e66fe2099..30112e5fe7a1 100644
--- a/rust/cohort-seeder/src/config.rs
+++ b/rust/cohort-seeder/src/config.rs
@@ -161,6 +161,34 @@ pub struct Config {
#[envconfig(default = "5")]
pub seeder_max_chunk_attempts: u32,
+ /// The first retry's wait ceiling after a chunk fails; it doubles per attempt up to
+ /// [`Config::seeder_retry_backoff_cap_secs`]. Without a wait, the poll loop re-claims a chunk
+ /// that failed for a durable reason within seconds and spends its whole attempt budget on the
+ /// same failure, which fails the run.
+ #[envconfig(default = "30")]
+ pub seeder_retry_backoff_base_secs: u64,
+
+ /// The longest a failed chunk waits before it is claimable again.
+ ///
+ /// This bounds how long a durably-failing chunk holds its run open, and the bound is a sum over
+ /// attempts rather than the cap alone: the ceilings double from
+ /// [`Config::seeder_retry_backoff_base_secs`] until they reach the cap, and the jitter draws
+ /// uniformly from `[0, ceiling]`, so the expected drain is half the worst case. At the defaults
+ /// (base 30s, cap 1800s) the doubling reaches the cap on the 7th attempt, so the sum is about
+ /// 15 minutes at 5 attempts and 3.5 hours at 12 — the cap times the attempt count is a real
+ /// upper bound but a loose one, and reading it as the answer overstates a small budget by an
+ /// order of magnitude.
+ ///
+ /// A run cannot complete until every chunk is `confirmed`, so that whole window is time the run
+ /// holds its cohort's uniqueness slot against every future backfill for that cohort.
+ /// `charts/apps/cohort-seeder/values.prod-us.yaml` is where the deployed
+ /// `SEEDER_MAX_CHUNK_ATTEMPTS` lives; the two must be sized together.
+ ///
+ /// The chunk lease budget is not the comparison to make. A `failed` chunk holds no lease and
+ /// cannot heartbeat, so the two quantities never meet in any predicate.
+ #[envconfig(default = "1800")]
+ pub seeder_retry_backoff_cap_secs: u64,
+
#[envconfig(default = "3000")]
pub seeder_tiles_per_sec: u32,
diff --git a/rust/cohort-seeder/src/domain/backoff.rs b/rust/cohort-seeder/src/domain/backoff.rs
new file mode 100644
index 000000000000..82099e021c7f
--- /dev/null
+++ b/rust/cohort-seeder/src/domain/backoff.rs
@@ -0,0 +1,225 @@
+//! Domain layer (pure): how long a failed chunk waits before it is claimable again. Depends on
+//! nothing above `domain`.
+//!
+//! Without a wait, a chunk that fails for a durable reason (a ClickHouse memory limit, a poisoned
+//! row) is re-claimed by the next poll tick and fails the same way, so it burns its whole attempt
+//! budget in minutes and takes its run down with it. The policy spends the same budget over a much
+//! longer window, which is what gives a transient cause time to clear.
+
+use std::time::Duration;
+
+use rand::Rng;
+
+/// The chunk's `attempts` column, as the claim `RETURNING` reports it. One is the first attempt, so
+/// the first retry waits exactly [`RetryBackoffPolicy::base`].
+///
+/// This tracks claims only while the chunk is under the attempt cap. The claim `CASE` stops
+/// incrementing at the cap, so a `produced` chunk that keeps being reclaimed there is claimed more
+/// times than this counts — deliberately, since it retries a Kafka write that is already done and
+/// must not be spaced out further.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub struct AttemptCount(u32);
+
+impl AttemptCount {
+ /// Read the `attempts` column. The claim UPDATE increments before it returns, so a live value
+ /// is always at least one; a zero or negative value can only come from a hand-edited row, and
+ /// is read as the first attempt rather than as "no wait at all".
+ pub fn from_row(attempts: i32) -> Self {
+ Self(u32::try_from(attempts).map_or(1, |count| count.max(1)))
+ }
+
+ pub const fn get(self) -> u32 {
+ self.0
+ }
+}
+
+/// Exponential backoff with full jitter, bounded by a cap. Copy, so it threads through the chunk
+/// pipeline as a value rather than a shared handle.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct RetryBackoffPolicy {
+ base: Duration,
+ cap: Duration,
+}
+
+/// The widest wait the policy accepts. Any real backoff is minutes, so this is not a tuning bound:
+/// it keeps the delay inside what `make_interval(secs => …)` can add to a timestamp. A wider value
+/// would make the store's `fail` write throw, and a failed `fail` leaves the chunk holding its lease
+/// in `scanning` until the poisoned-chunk sweep reaches it at the attempt cap, so every failure
+/// fleet-wide would look like a crashed worker.
+///
+/// A configured cap above 6 hours would collide with the Django inventory's stall detector, which
+/// classifies a run untouched for that long as `seeding-stalled` and terminalizes it by default. A
+/// run merely waiting out one backoff would then be a cancel target. The shipped 1800s is far
+/// inside that; anything approaching 6 h needs the detector's side changed first.
+pub const MAX_RETRY_BACKOFF_CAP: Duration = Duration::from_secs(24 * 60 * 60);
+
+impl RetryBackoffPolicy {
+ pub fn new(base: Duration, cap: Duration) -> Result<Self, BackoffPolicyError> {
+ if base.is_zero() {
+ return Err(BackoffPolicyError::ZeroBase);
+ }
+ if cap < base {
+ return Err(BackoffPolicyError::CapBelowBase);
+ }
+ if cap > MAX_RETRY_BACKOFF_CAP {
+ return Err(BackoffPolicyError::CapTooLarge);
+ }
+ Ok(Self { base, cap })
+ }
+
+ pub const fn base(self) -> Duration {
+ self.base
+ }
+
+ pub const fn cap(self) -> Duration {
+ self.cap
+ }
+
+ /// The longest a chunk waits after its `attempt`-th claim failed: `base * 2^(attempt - 1)`,
+ /// clamped to `cap`.
+ ///
+ /// The doubling count is itself clamped to the width of the multiplier, so an attempts column
+ /// raised to an absurd value cannot wrap the shift into a short wait. That clamp also bounds
+ /// the ceiling at `base * 2^31` when `cap` is larger, which no configured cap reaches.
+ pub fn ceiling(self, attempt: AttemptCount) -> Duration {
+ let doublings = attempt.get().saturating_sub(1).min(u32::BITS - 1);
+ self.base.saturating_mul(1 << doublings).min(self.cap)
+ }
+
+ /// A uniformly random wait in the closed interval `[0, ceiling]`. Full jitter, not a fixed
+ /// ceiling: several replicas that failed the same chunk from one shared cause would otherwise
+ /// become claimable at the same instant and collide again on every retry. The expected wait is
+ /// half the ceiling, so the spacing still doubles per attempt.
+ pub fn delay_after(self, attempt: AttemptCount) -> Duration {
+ // The ceiling is bounded by `MAX_RETRY_BACKOFF_CAP`, so the millisecond narrowing is always
+ // in range. It saturates rather than panicking anyway, because a panic here would take down
+ // a chunk worker over a configuration value.
+ let ceiling_ms = u64::try_from(self.ceiling(attempt).as_millis()).unwrap_or(u64::MAX);
+ Duration::from_millis(rand::thread_rng().gen_range(0..=ceiling_ms))
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+pub enum BackoffPolicyError {
+ #[error("retry backoff base must be greater than zero")]
+ ZeroBase,
+ #[error("retry backoff cap must be at least the base")]
+ CapBelowBase,
+ #[error("retry backoff cap must be at most 24 hours")]
+ CapTooLarge,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn policy() -> RetryBackoffPolicy {
+ RetryBackoffPolicy::new(Duration::from_secs(30), Duration::from_secs(1800)).unwrap()
+ }
+
+ #[test]
+ fn the_ceiling_doubles_each_attempt_until_it_reaches_the_cap() {
+ let policy = policy();
+ let ceiling = |attempt| policy.ceiling(AttemptCount::from_row(attempt));
+ assert_eq!(ceiling(1), Duration::from_secs(30));
+ assert_eq!(ceiling(2), Duration::from_secs(60));
+ assert_eq!(ceiling(3), Duration::from_secs(120));
+ assert_eq!(ceiling(6), Duration::from_secs(960));
+ // 30s * 2^6 is 1920s, past the 1800s cap.
+ assert_eq!(ceiling(7), Duration::from_secs(1800));
+ assert_eq!(ceiling(8), Duration::from_secs(1800));
+ }
+
+ /// An attempts column raised far past the cap must still land on `cap`. A multiplier that
+ /// wrapped would hand a wedged chunk a near-zero wait, which is the storm this policy exists to
+ /// stop.
+ #[test]
+ fn an_absurd_attempt_count_saturates_onto_the_cap() {
+ let policy = policy();
+ for attempts in [31, 32, 33, 64, 1_000, i32::MAX] {
+ assert_eq!(
+ policy.ceiling(AttemptCount::from_row(attempts)),
+ Duration::from_secs(1800),
+ "attempt {attempts} escaped the cap"
+ );
+ }
+ }
+
+ #[test]
+ fn the_attempt_count_reads_a_non_positive_column_as_the_first_attempt() {
+ assert_eq!(AttemptCount::from_row(0).get(), 1);
+ assert_eq!(AttemptCount::from_row(-4).get(), 1);
+ assert_eq!(AttemptCount::from_row(1).get(), 1);
+ assert_eq!(AttemptCount::from_row(9).get(), 9);
+ }
+
+ #[test]
+ fn every_sampled_delay_lands_inside_its_attempt_ceiling() {
+ let policy = policy();
+ for attempts in 1..=10 {
+ let attempt = AttemptCount::from_row(attempts);
+ let ceiling = policy.ceiling(attempt);
+ for _ in 0..64 {
+ let delay = policy.delay_after(attempt);
+ assert!(
+ delay <= ceiling,
+ "attempt {attempts} drew {delay:?} past its {ceiling:?} ceiling"
+ );
+ }
+ }
+ }
+
+ /// Full jitter draws from `[0, ceiling]`, so short waits are common. The half-jitter variant
+ /// (`ceiling/2 + random(ceiling/2)`) never draws below half the ceiling, and would leave every
+ /// replica that failed together still bunched into the same half-window. Over 512 draws the
+ /// chance that none lands in the bottom tenth is about 1e-24, so this does not flake.
+ #[test]
+ fn the_jitter_reaches_down_to_short_waits_rather_than_only_the_top_half() {
+ let policy = policy();
+ let attempt = AttemptCount::from_row(4);
+ let ceiling = policy.ceiling(attempt);
+ let shortest = (0..512)
+ .map(|_| policy.delay_after(attempt))
+ .min()
+ .expect("512 draws are not empty");
+ assert!(
+ shortest <= ceiling / 10,
+ "the shortest of 512 draws was {shortest:?}, never near the bottom of {ceiling:?}"
+ );
+ }
+
+ /// The cap has an upper bound, and every accepted policy produces a wait Postgres can add to a
+ /// timestamp. Without the bound, `fail` would throw on the interval, and a failed `fail` leaves
+ /// the chunk holding its lease in `scanning` rather than releasing it for retry.
+ #[test]
+ fn a_cap_wider_than_postgres_can_add_to_a_timestamp_is_refused() {
+ for cap in [
+ MAX_RETRY_BACKOFF_CAP + Duration::from_secs(1),
+ Duration::from_secs(u64::MAX),
+ Duration::MAX,
+ ] {
+ assert_eq!(
+ RetryBackoffPolicy::new(Duration::from_secs(30), cap),
+ Err(BackoffPolicyError::CapTooLarge),
+ "{cap:?} was accepted"
+ );
+ }
+ let widest =
+ RetryBackoffPolicy::new(Duration::from_secs(30), MAX_RETRY_BACKOFF_CAP).unwrap();
+ assert!(widest.delay_after(AttemptCount::from_row(64)) <= MAX_RETRY_BACKOFF_CAP);
+ }
+
+ #[test]
+ fn a_policy_that_could_not_space_retries_is_rejected() {
+ assert_eq!(
+ RetryBackoffPolicy::new(Duration::ZERO, Duration::from_secs(1)),
+ Err(BackoffPolicyError::ZeroBase)
+ );
+ assert_eq!(
+ RetryBackoffPolicy::new(Duration::from_secs(30), Duration::from_secs(29)),
+ Err(BackoffPolicyError::CapBelowBase)
+ );
+ // A cap equal to the base is a deliberate constant wait, not a misconfiguration.
+ assert!(RetryBackoffPolicy::new(Duration::from_secs(30), Duration::from_secs(30)).is_ok());
+ }
+}
diff --git a/rust/cohort-seeder/src/domain/chunk.rs b/rust/cohort-seeder/src/domain/chunk.rs
index ff0d9cb57f94..5e62d23c8915 100644
--- a/rust/cohort-seeder/src/domain/chunk.rs
+++ b/rust/cohort-seeder/src/domain/chunk.rs
@@ -12,6 +12,7 @@ use cohort_core::filters::TeamId;
use cohort_core::DayIdx;
use serde::{Deserialize, Serialize};
+use super::backoff::AttemptCount;
use super::ids::{ChunkId, ClaimEpoch, RunId, SChunkMs};
use super::person::PersonRange;
use super::window::DomainError;
@@ -170,6 +171,38 @@ pub struct ChunkSpec {
pub s_chunk: SChunkMs,
/// `Some` ⇔ person chunk (behavioral chunks never write the range columns).
pub person_range: Option<PersonRange>,
+ /// This claim's attempt number, as the claim UPDATE returned it. Recovery reads it to size the
+ /// chunk's retry wait, so the wait grows with the failures this chunk has actually taken.
+ pub attempt: AttemptCount,
+}
+
+/// How many bytes one chunk's ClickHouse scan moved: `received` off the wire (still compressed) and
+/// `decoded` after decompression. The pair is what turns a slow chunk into a diagnosis, because it
+/// separates a scan that read a lot of data from one that read little and spent its time on CPU.
+///
+/// A scan that halts mid-stream reports only what it had already read, which is the honest number:
+/// bytes the client never pulled were never transferred.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct ScanVolume {
+ received_bytes: u64,
+ decoded_bytes: u64,
+}
+
+impl ScanVolume {
+ pub const fn new(received_bytes: u64, decoded_bytes: u64) -> Self {
+ Self {
+ received_bytes,
+ decoded_bytes,
+ }
+ }
+
+ pub const fn received_bytes(self) -> u64 {
+ self.received_bytes
+ }
+
+ pub const fn decoded_bytes(self) -> u64 {
+ self.decoded_bytes
+ }
}
/// Freshly claimed and locked; minted only by `store.claim_next` (or `test_support`).
@@ -187,17 +220,18 @@ impl ClaimedChunk {
self.spec
}
- /// Pure transition: attach the scanned tiles. No DB effect.
- pub fn into_scanned(self, tiles: Vec<SeedTile>) -> ScannedChunk {
- ScannedChunk::new(self.spec, tiles)
+ /// Pure transition: attach the scanned tiles and the volume the scan moved. No DB effect.
+ pub fn into_scanned(self, tiles: Vec<SeedTile>, volume: ScanVolume) -> ScannedChunk {
+ ScannedChunk::new(self.spec, tiles, volume)
}
/// 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 {
+ /// scanned, so only the count and the volume remain. No DB effect.
+ pub fn into_streamed(self, seeds_produced: u64, volume: ScanVolume) -> StreamedChunk {
StreamedChunk {
spec: self.spec,
seeds_produced,
+ volume,
}
}
}
@@ -208,6 +242,7 @@ impl ClaimedChunk {
pub struct StreamedChunk {
spec: ChunkSpec,
seeds_produced: u64,
+ volume: ScanVolume,
}
impl StreamedChunk {
@@ -218,17 +253,26 @@ impl StreamedChunk {
pub const fn seeds_produced(&self) -> u64 {
self.seeds_produced
}
+
+ pub const fn volume(&self) -> ScanVolume {
+ self.volume
+ }
}
/// Scanned into tiles but not yet marked produced.
pub struct ScannedChunk {
spec: ChunkSpec,
tiles: Vec<SeedTile>,
+ volume: ScanVolume,
}
impl ScannedChunk {
- pub(crate) fn new(spec: ChunkSpec, tiles: Vec<SeedTile>) -> Self {
- Self { spec, tiles }
+ pub(crate) fn new(spec: ChunkSpec, tiles: Vec<SeedTile>, volume: ScanVolume) -> Self {
+ Self {
+ spec,
+ tiles,
+ volume,
+ }
}
pub const fn spec(&self) -> ChunkSpec {
@@ -238,6 +282,10 @@ impl ScannedChunk {
pub fn tiles(&self) -> &[SeedTile] {
&self.tiles
}
+
+ pub const fn volume(&self) -> ScanVolume {
+ self.volume
+ }
}
impl std::fmt::Debug for ScannedChunk {
@@ -246,6 +294,7 @@ impl std::fmt::Debug for ScannedChunk {
.debug_struct("ScannedChunk")
.field("spec", &self.spec)
.field("tiles", &self.tiles.len())
+ .field("volume", &self.volume)
.finish()
}
}
diff --git a/rust/cohort-seeder/src/domain/mod.rs b/rust/cohort-seeder/src/domain/mod.rs
index 8d1dec5d1863..56ee7a3e938b 100644
--- a/rust/cohort-seeder/src/domain/mod.rs
+++ b/rust/cohort-seeder/src/domain/mod.rs
@@ -8,6 +8,7 @@
//! `cohort_core::seed` — shared with the processor — and is re-exported here.
pub mod aggregate;
+pub mod backoff;
pub mod chunk;
pub mod completion;
pub mod condition;
@@ -22,10 +23,11 @@ pub mod window;
pub use aggregate::{
AggregateError, ChunkAccumulator, OutcomeKind, RecordOutcome, RecordStats, VmFailureCounts,
};
+pub use backoff::{AttemptCount, BackoffPolicyError, RetryBackoffPolicy};
pub use chunk::{
BandSpec, BandSpecError, CancelCause, ChunkDomainError, ChunkLease, ChunkSpec, ChunkStatus,
ClaimKind, ClaimedChunk, EnqueuedChunk, HaltReason, Halted, ProduceHwms, ProducedChunk,
- ScannedChunk, StreamedChunk, UnknownChunkStatus,
+ ScanVolume, ScannedChunk, StreamedChunk, UnknownChunkStatus,
};
pub use cohort_core::seed::{
BehavioralShapeHash, PersonSeed, PersonShapeHash, ReconcileCompleteMarker, ReconcileScope,
diff --git a/rust/cohort-seeder/src/domain/person.rs b/rust/cohort-seeder/src/domain/person.rs
index 7724dba0325d..72010f601f08 100644
--- a/rust/cohort-seeder/src/domain/person.rs
+++ b/rust/cohort-seeder/src/domain/person.rs
@@ -453,6 +453,7 @@ mod tests {
use proptest::prelude::*;
use serde_json::json;
+ use super::super::backoff::AttemptCount;
use super::super::chunk::BandSpec;
use super::super::ids::{ChunkId, SChunkMs};
use super::*;
@@ -775,6 +776,7 @@ mod tests {
band: BandSpec::new(0, 1).unwrap(),
s_chunk: SChunkMs(CLAIM_STAMP_MS),
person_range,
+ attempt: AttemptCount::from_row(1),
}
}
diff --git a/rust/cohort-seeder/src/domain/pinned.rs b/rust/cohort-seeder/src/domain/pinned.rs
index 0ce4b63d59c2..2b06c6e87a91 100644
--- a/rust/cohort-seeder/src/domain/pinned.rs
+++ b/rust/cohort-seeder/src/domain/pinned.rs
@@ -252,6 +252,19 @@ impl PinnedRun {
})
}
+ /// The one cohort every surviving condition belongs to, or `None` when the run spans several.
+ ///
+ /// A save-triggered run carries exactly one cohort, and naming it lets `query_log_archive`
+ /// attribute the scan's cost to that cohort. A team-enablement run spans the team's cohorts,
+ /// where any single id would be a misattribution rather than a partial one.
+ pub fn sole_cohort_id(&self) -> Option<CohortId> {
+ let mut cohort_ids = self.conditions.iter().map(|condition| condition.cohort_id);
+ let first = cohort_ids.next()?;
+ cohort_ids
+ .all(|cohort_id| cohort_id == first)
+ .then_some(first)
+ }
+
/// The seed domain for a claimed chunk, after proving the chunk belongs to this run/team. Named
/// here (not in the store) so the store never references a scan/ClickHouse type — cycle break.
pub fn domain_for(&self, spec: &ChunkSpec) -> Result<SeedDomain, ChunkDomainError> {
@@ -831,6 +844,77 @@ mod tests {
// Cohort 1's surviving condition would satisfy a run-wide check while cohort 2 gets nothing.
assert_eq!(validated.run.conditions.len(), 1);
assert_eq!(validated.uncovered_cohorts, vec![CohortId(2)]);
+ // A dropped condition does not make its cohort a second claimant on the scan's cost.
+ assert_eq!(validated.run.sole_cohort_id(), Some(CohortId(1)));
+ }
+
+ /// A validated run carrying one 7-day `performed_event` condition per `(cohort, event)` pair,
+ /// every named cohort active.
+ fn run_over(conditions: &[(i32, &str)]) -> PinnedRun {
+ let mut payload_conditions = Vec::new();
+ let mut values_by_cohort: HashMap<i32, Vec<Value>> = HashMap::new();
+ for (cohort_id, event_name) in conditions {
+ let hash = format!("{event_name:0<16}");
+ let mut raw = condition(*cohort_id, &hash, "performed_event", Some(event_name), 7);
+ raw["time_value"] = json!(7);
+ raw["time_interval"] = json!("day");
+ payload_conditions.push(raw);
+ values_by_cohort.entry(*cohort_id).or_default().push(json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": event_name,
+ "conditionHash": hash,
+ "time_value": 7,
+ "time_interval": "day",
+ "bytecode": bytecode(event_name),
+ }));
+ }
+ let participations = values_by_cohort
+ .into_iter()
+ .map(|(cohort_id, values)| PinnedParticipation {
+ cohort_id: CohortId(cohort_id),
+ pinned_filters: json!({ "properties": { "type": "AND", "values": values } }),
+ state: PinnedParticipationState::Active,
+ })
+ .collect();
+ let event_names = conditions
+ .iter()
+ .map(|(_, event_name)| *event_name)
+ .collect::<Vec<_>>();
+ PinnedRun::validate(snapshot(
+ json!({
+ "schema_version": 1,
+ "conditions": payload_conditions,
+ "event_names": event_names,
+ }),
+ participations,
+ ))
+ .expect("the fixture run validates")
+ .run
+ }
+
+ /// `sole_cohort_id` picks the cohort a scan's `log_comment` is charged to, so it must name one
+ /// only when every surviving condition agrees. Naming a cohort on a run that spans two would
+ /// charge one cohort for the other's scan cost in `query_log_archive`.
+ #[test]
+ fn a_cohort_is_named_only_when_every_surviving_condition_shares_it() {
+ assert_eq!(
+ run_over(&[(1, "alpha"), (1, "beta")]).sole_cohort_id(),
+ Some(CohortId(1)),
+ "several conditions on one cohort still name that cohort"
+ );
+ assert_eq!(
+ run_over(&[(1, "alpha"), (2, "beta")]).sole_cohort_id(),
+ None,
+ "a run spanning two cohorts must name neither"
+ );
+ // A run with nothing left to scan attributes to no cohort. This falls out of `next()?` on
+ // an empty iterator rather than from a branch, so it is pinned here on purpose.
+ assert_eq!(
+ run_over(&[]).sole_cohort_id(),
+ None,
+ "a run with no surviving conditions must name no cohort"
+ );
}
#[test]
diff --git a/rust/cohort-seeder/src/main.rs b/rust/cohort-seeder/src/main.rs
index b8dd5e5eb3ab..2267c4d3a916 100644
--- a/rust/cohort-seeder/src/main.rs
+++ b/rust/cohort-seeder/src/main.rs
@@ -307,6 +307,9 @@ fn log_startup(config: &Config) {
team_allowlist = ?config.team_allowlist,
run_poll_secs = config.seeder_run_poll_secs,
max_concurrent_chunks = config.seeder_max_concurrent_chunks,
+ max_chunk_attempts = config.seeder_max_chunk_attempts,
+ retry_backoff_base_secs = config.seeder_retry_backoff_base_secs,
+ retry_backoff_cap_secs = config.seeder_retry_backoff_cap_secs,
max_lookback_days = config.seeder_max_lookback_days,
bands_per_day = config.seeder_bands_per_day,
tiles_per_second = config.seeder_tiles_per_sec,
diff --git a/rust/cohort-seeder/src/observability/metrics.rs b/rust/cohort-seeder/src/observability/metrics.rs
index e73c1486f934..9c314478c325 100644
--- a/rust/cohort-seeder/src/observability/metrics.rs
+++ b/rust/cohort-seeder/src/observability/metrics.rs
@@ -5,7 +5,7 @@
use std::time::{Duration, Instant};
use metrics::histogram;
-use metrics_exporter_prometheus::{BuildError, PrometheusBuilder, PrometheusHandle};
+use metrics_exporter_prometheus::{BuildError, Matcher, PrometheusBuilder, PrometheusHandle};
pub const RUNS_DISCOVERED: &str = "seeder_runs_discovered_total";
pub const BOUNDARY_ESTABLISHED: &str = "seeder_boundary_established_total";
@@ -28,6 +28,12 @@ pub const CHUNKS_POISONED: &str = "seeder_chunks_poisoned_total";
/// which is what an operator reads once this counter points them at a run.
pub const RUNS_FAILED_EXHAUSTED_CHUNKS: &str = "seeder_runs_failed_exhausted_chunks_total";
pub const CHUNK_SCAN_DURATION_SECONDS: &str = "seeder_chunk_scan_duration_seconds";
+/// Compressed bytes a scan cursor read off the wire, labelled by `kind` (counter). Paired with
+/// [`SCAN_DECODED_BYTES`], it tells a slow scan that moved a lot of data apart from one that moved
+/// little and spent its time on CPU.
+pub const SCAN_RECEIVED_BYTES: &str = "seeder_scan_received_bytes_total";
+/// Decompressed bytes a scan cursor produced, labelled by `kind` (counter).
+pub const SCAN_DECODED_BYTES: &str = "seeder_scan_decoded_bytes_total";
pub const ROWS_SCANNED: &str = "seeder_rows_scanned_total";
pub const EVENTS_SKIPPED: &str = "seeder_events_skipped_total";
pub const CONDITIONS_EVALUATED: &str = "seeder_conditions_evaluated_total";
@@ -94,6 +100,10 @@ pub const PERSON_NONMATCHERS_SKIPPED: &str = "seeder_person_nonmatchers_skipped_
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";
+/// One run's person planning pass, end to end: the ClickHouse boundaries scan plus the Postgres
+/// `plan_person_chunks` insert. Two databases under one timer, so a slow reading names neither on
+/// its own — read it with `seeder_scan_received_bytes_total{kind="person_boundaries"}` to tell a
+/// heavy scan from a slow insert.
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
@@ -127,6 +137,207 @@ impl Drop for MetricTimer {
}
}
+/// Bucket ladder for every seeder histogram that measures a short wall-clock span in seconds:
+/// [`PRODUCE_ACK_SECONDS`], [`PACER_WAIT_SECONDS`], and
+/// [`RECONCILE_OBSERVATION_PASS_SECONDS`]. It is installed as the recorder-wide default, so a new
+/// histogram inherits a real bucketed histogram instead of a rolling-window summary. A future
+/// histogram measuring anything other than seconds needs its own
+/// [`PrometheusBuilder::set_buckets_for_metric`] entry, or its samples land in the wrong ladder.
+///
+/// The recorder is process-wide, so this also shapes histograms from linked crates. The only one
+/// the seeder reaches is `lifecycle`'s component shutdown duration, which is in seconds and well
+/// inside the 60s top bucket; the shared `common-metrics` builder every other service installs
+/// already renders it as a histogram too, on a millisecond ladder.
+const DEFAULT_SECONDS_BUCKETS: &[f64] = &[
+ 0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0,
+];
+
+/// Bucket ladder for the two ClickHouse-bound chunk scan spans. The top bucket is
+/// `SEEDER_CH_MAX_EXECUTION_TIME_SECS`, because a scan cannot outlive the server-side
+/// execution-time budget: a chunk that reaches the last bucket was killed by ClickHouse. The value
+/// is repeated here rather than read from `Config` so this module stays a leaf that no other seeder
+/// module can pull a dependency through; a test binds it back to the config default. That binding
+/// covers the default only, so a deployment that raises the budget by environment leaves this
+/// ladder short and the last bucket stops meaning "killed".
+const SCAN_DURATION_SECONDS_BUCKETS: &[f64] = &[
+ 1.0, 5.0, 15.0, 30.0, 60.0, 120.0, 300.0, 600.0, 1200.0, 1800.0, 3600.0, 7200.0, 14400.0,
+];
+
+/// Bucket ladder for [`PERSON_PLANNING_DURATION_SECONDS`], which spans two databases: the
+/// ClickHouse boundaries scan and the Postgres `plan_person_chunks` insert. ClickHouse's
+/// execution-time budget governs only the first, so the top bucket is not the scan ceiling — an
+/// operator reading `+Inf` here must be able to suspect either database. The floor is milliseconds
+/// because a small team's planning finishes well inside a second, and the scan ladder's 1.0s floor
+/// erased that whole range.
+const PERSON_PLANNING_SECONDS_BUCKETS: &[f64] = &[
+ 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 15.0, 60.0, 300.0, 900.0, 1800.0, 3600.0, 14400.0,
+];
+
+/// Bucket ladder for [`AGGREGATE_ENTRIES`], which counts `(person, condition)` pairs held in one
+/// chunk's in-memory aggregate. It is a cardinality, not a duration, so it needs its own ladder;
+/// the top bucket is the scale at which an operator should raise `SEEDER_BANDS_PER_DAY` to split
+/// the day further.
+const AGGREGATE_ENTRIES_BUCKETS: &[f64] = &[
+ 100.0,
+ 1_000.0,
+ 10_000.0,
+ 50_000.0,
+ 100_000.0,
+ 250_000.0,
+ 500_000.0,
+ 1_000_000.0,
+ 2_500_000.0,
+ 5_000_000.0,
+ 10_000_000.0,
+];
+
+/// Every seeder histogram that overrides the recorder-wide default, paired with its ladder. This is
+/// the single source: [`configured_builder`] installs from it and the test iterates it, so a
+/// histogram cannot be given a ladder in one place and checked against another. A histogram absent
+/// from this table inherits [`DEFAULT_SECONDS_BUCKETS`], which is correct only if it measures a
+/// short span in seconds.
+const HISTOGRAM_LADDERS: &[(&str, &[f64])] = &[
+ (CHUNK_SCAN_DURATION_SECONDS, SCAN_DURATION_SECONDS_BUCKETS),
+ (
+ PERSON_CHUNK_SCAN_DURATION_SECONDS,
+ SCAN_DURATION_SECONDS_BUCKETS,
+ ),
+ (
+ PERSON_PLANNING_DURATION_SECONDS,
+ PERSON_PLANNING_SECONDS_BUCKETS,
+ ),
+ (AGGREGATE_ENTRIES, AGGREGATE_ENTRIES_BUCKETS),
+];
+
+/// The recorder configuration shared by [`install_recorder`] and its test.
+///
+/// Without `set_buckets` the exporter renders every histogram as a rolling-window summary, whose
+/// quantiles read 0 once a rare long recording ages out of the window. That is exactly the shape of
+/// the scan metrics, where one multi-hour chunk per hour is the signal.
+///
+/// The two `seeder_reconcile_*` lag and age metrics take no entry on purpose: they are gauges, and
+/// a bucket ladder would not apply to them.
+fn configured_builder() -> Result<PrometheusBuilder, BuildError> {
+ let mut builder = PrometheusBuilder::new().set_buckets(DEFAULT_SECONDS_BUCKETS)?;
+ for (name, ladder) in HISTOGRAM_LADDERS {
+ builder = builder.set_buckets_for_metric(Matcher::Full((*name).to_owned()), ladder)?;
+ }
+ Ok(builder)
+}
+
pub fn install_recorder() -> Result<PrometheusHandle, BuildError> {
- PrometheusBuilder::new().install_recorder()
+ configured_builder()?.install_recorder()
+}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::HashMap;
+
+ use envconfig::Envconfig;
+ use metrics::histogram;
+
+ use super::*;
+
+ /// The histograms that deliberately take no [`HISTOGRAM_LADDERS`] entry, because
+ /// [`DEFAULT_SECONDS_BUCKETS`] already describes them. Listed so the test still proves they
+ /// render as histograms rather than summaries.
+ const DEFAULT_LADDER_HISTOGRAMS: &[&str] = &[
+ PRODUCE_ACK_SECONDS,
+ PACER_WAIT_SECONDS,
+ RECONCILE_OBSERVATION_PASS_SECONDS,
+ ];
+
+ /// Renders one sample per histogram through the configured recorder.
+ fn render_one_sample_each() -> String {
+ let recorder = configured_builder()
+ .expect("the configured bucket ladders are non-empty")
+ .build_recorder();
+ let handle = recorder.handle();
+ metrics::with_local_recorder(&recorder, || {
+ for (name, _) in HISTOGRAM_LADDERS {
+ histogram!(*name).record(1.0);
+ }
+ for name in DEFAULT_LADDER_HISTOGRAMS {
+ histogram!(*name).record(1.0);
+ }
+ });
+ handle.render()
+ }
+
+ /// The exporter renders bucket bounds with `f64::to_string`, so an integral bound loses its
+ /// fractional part: 14400.0 is `le="14400"`.
+ fn top_bucket_label(ladder: &[f64]) -> String {
+ ladder
+ .last()
+ .expect("every ladder has at least one bucket")
+ .to_string()
+ }
+
+ /// A histogram with no ladder renders as a summary, so its rare long recordings age out of the
+ /// rolling window and its quantiles read 0. Asserting the exact top bucket of each ladder also
+ /// pins that the per-metric overrides beat the recorder-wide default: the exporter's own
+ /// `set_buckets_for_metric` documentation claims the opposite, while its implementation
+ /// consults the overrides first. A dependency bump that makes the documentation true would
+ /// collapse the scan metrics onto the 60s default ladder, and this test is what catches it.
+ #[test]
+ fn every_histogram_renders_with_its_own_bucket_ladder() {
+ let rendered = render_one_sample_each();
+ let expected = HISTOGRAM_LADDERS
+ .iter()
+ .map(|(name, ladder)| (*name, top_bucket_label(ladder)))
+ .chain(
+ DEFAULT_LADDER_HISTOGRAMS
+ .iter()
+ .map(|name| (*name, top_bucket_label(DEFAULT_SECONDS_BUCKETS))),
+ );
+ for (name, top_bucket) in expected {
+ assert!(
+ rendered.contains(&format!("{name}_bucket{{le=\"{top_bucket}\"}}")),
+ "{name} is missing its le={top_bucket} bucket:\n{rendered}"
+ );
+ assert!(
+ !rendered.contains(&format!("{name}{{quantile=")),
+ "{name} rendered as a summary instead of a histogram:\n{rendered}"
+ );
+ }
+ }
+
+ /// The person planning timer spans a ClickHouse scan and a Postgres insert, so it must not
+ /// share the scan ladder, whose 1.0s floor erases every sub-second planning pass. Two teams
+ /// apart in size have to land in different buckets for the metric to say anything.
+ #[test]
+ fn person_planning_resolves_spans_below_the_scan_ladders_floor() {
+ let floor = PERSON_PLANNING_SECONDS_BUCKETS[0];
+ let scan_floor = SCAN_DURATION_SECONDS_BUCKETS[0];
+ assert!(
+ floor < scan_floor,
+ "the planning ladder starts at {floor}, no finer than the scan ladder's {scan_floor}"
+ );
+ let sub_second = PERSON_PLANNING_SECONDS_BUCKETS
+ .iter()
+ .filter(|bound| **bound < 1.0)
+ .count();
+ assert!(
+ sub_second >= 3,
+ "only {sub_second} sub-second buckets; a fast planning pass has nowhere to land"
+ );
+ }
+
+ /// The scan ladder's top bucket carries a claim — that a chunk reaching it was killed by
+ /// ClickHouse — and that claim holds only while the bucket matches the execution-time budget.
+ /// The ladder repeats the number rather than reading `Config`, so nothing but this ties the two
+ /// together. A test module may import `Config` without the production module depending on it,
+ /// which keeps `metrics` a leaf.
+ #[test]
+ fn the_scan_ladder_tops_out_at_the_clickhouse_execution_budget() {
+ let config = crate::config::Config::init_from_hashmap(&HashMap::new())
+ .expect("every seeder config field carries a default");
+ assert_eq!(
+ *SCAN_DURATION_SECONDS_BUCKETS
+ .last()
+ .expect("the scan ladder is non-empty"),
+ config.seeder_ch_max_execution_time_secs as f64,
+ "the scan ladder no longer tops out at the ClickHouse execution-time budget"
+ );
+ }
}
diff --git a/rust/cohort-seeder/src/store/chunks.rs b/rust/cohort-seeder/src/store/chunks.rs
index b5d85bc2cb84..d48656ade587 100644
--- a/rust/cohort-seeder/src/store/chunks.rs
+++ b/rust/cohort-seeder/src/store/chunks.rs
@@ -1,14 +1,15 @@
//! The day-chunk claim/CAS ledger in PostgreSQL: the sole owner of the `cohort_backfill_chunks` SQL.
//!
-//! Written chunk statuses bind [`ChunkStatus::as_str`] as a parameter; the two multi-status `IN`
-//! predicates are hoisted into [`ACTIVE_STATUSES_SQL`]/[`RETRYABLE_STATUSES_SQL`], scanned by a unit
-//! test through [`ChunkStatus::from_str`] so the SQL vocabulary can never drift from the enum.
+//! Written chunk statuses bind [`ChunkStatus::as_str`] as a parameter; the one multi-status `IN`
+//! predicate is hoisted into [`ACTIVE_STATUSES_SQL`], scanned by a unit test through
+//! [`ChunkStatus::from_str`] so the SQL vocabulary can never drift from the enum.
//! Every claim charges an attempt (saturating at the cap) and bumps the fencing `claim_epoch`;
//! expired `produced` leases are reclaimable without an attempt cap (their tiles are already in
//! Kafka and must reach `confirmed`), while expired `scanning` leases are capped and dead-lettered
//! by [`PgChunkStore::reap_poisoned_chunks`] so a chunk that hard-crashes its worker cannot
-//! re-scan forever. Depends on `domain` (the pure chunk states it mints and the typed ids) and
-//! nothing above.
+//! re-scan forever. A `failed` chunk additionally waits out the retry backoff its
+//! [`PgChunkStore::fail`] stamped, which is the only claim arm that reads `next_attempt_at`.
+//! Depends on `domain` (the pure chunk states it mints and the typed ids) and nothing above.
use chrono::NaiveDate;
use cohort_core::filters::TeamId;
@@ -17,13 +18,14 @@ use sqlx::types::Json;
use sqlx::{Connection, FromRow, PgPool};
use std::fmt;
use std::num::NonZeroU16;
+use std::time::Duration;
use uuid::Uuid;
use crate::domain::{
- 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,
+ bands_for_day, person_chunk_sentinel_day, AttemptCount, Band, BandSpec, BandSpecError, ChunkId,
+ ChunkLease, ChunkSpec, ChunkStatus, ClaimEpoch, ClaimKind, ClaimedChunk, EnqueuedChunk, Halted,
+ PersonRange, PersonRangeError, ProduceHwms, ProducedChunk, RunId, SChunkMs, ScanVolume,
+ ScannedChunk, StreamedChunk,
};
use super::lease::LeaseHandle;
@@ -31,8 +33,6 @@ use super::{Claimant, LeaseDuration, MaxAttempts, RenderedError, PERSISTED_ERROR
/// Chunk statuses holding a live lease — the targets of the fenced heartbeat/fail/confirm writes.
const ACTIVE_STATUSES_SQL: &str = "('scanning', 'produced')";
-/// Chunk statuses eligible for a fresh claim while under the attempt cap.
-const RETRYABLE_STATUSES_SQL: &str = "('pending', 'failed')";
#[derive(Debug, Clone)]
pub struct PgChunkStore {
@@ -240,7 +240,12 @@ impl PgChunkStore {
FROM cohort_backfill_chunks c
JOIN cohort_backfill_runs r ON r.id = c.run_id
WHERE c.run_id = ANY($1) AND r.status = 'seeding'
- AND ((c.status IN {retryable} AND c.attempts < $4)
+ AND ((c.status = $7 AND c.attempts < $4)
+ -- Only the failed→claim transition is gated on the backoff stamp. A chunk
+ -- that never ran (`pending`) and an expired lease reclaim both stay
+ -- immediate: neither is the tight failure loop the wait exists to break.
+ OR (c.status = $8 AND c.attempts < $4
+ AND (c.next_attempt_at IS NULL OR c.next_attempt_at <= now()))
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
@@ -253,12 +258,12 @@ impl PgChunkStore {
UPDATE cohort_backfill_chunks c
SET status = $5, claim_epoch = c.claim_epoch + 1, claimed_by = $2,
claimed_at = now(), lease_expires_at = now() + make_interval(secs => $3),
- s_chunk_at = now(),
+ s_chunk_at = now(), next_attempt_at = NULL,
attempts = CASE WHEN c.attempts < $4 THEN c.attempts + 1 ELSE c.attempts END,
updated_at = now()
FROM next_chunk
WHERE c.id = next_chunk.id
- RETURNING c.id, c.run_id, c.team_id, c.day, c.band, c.claim_epoch,
+ RETURNING c.id, c.run_id, c.team_id, c.day, c.band, c.claim_epoch, c.attempts,
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
@@ -266,7 +271,6 @@ impl PgChunkStore {
next_chunk.was_reclaim
"#,
active = ACTIVE_STATUSES_SQL,
- retryable = RETRYABLE_STATUSES_SQL,
);
let row = sqlx::query_as::<_, ClaimedRow>(&sql)
.bind(run_ids)
@@ -275,6 +279,8 @@ impl PgChunkStore {
.bind(max_attempts.get())
.bind(ChunkStatus::Scanning.as_str())
.bind(ChunkStatus::Produced.as_str())
+ .bind(ChunkStatus::Pending.as_str())
+ .bind(ChunkStatus::Failed.as_str())
.fetch_optional(&self.pool)
.await?;
@@ -361,7 +367,11 @@ impl PgChunkStore {
) -> 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 {
+ let volume = chunk.volume();
+ if let Err(error) = self
+ .mark_produced_raw(spec.lease, seeds_produced, volume)
+ .await
+ {
return Err(Halted::failed(chunk, error));
}
Ok(EnqueuedChunk::new(spec, seeds_produced))
@@ -381,7 +391,11 @@ impl PgChunkStore {
));
}
};
- if let Err(error) = self.mark_produced_raw(spec.lease, tiles_produced).await {
+ let volume = chunk.volume();
+ if let Err(error) = self
+ .mark_produced_raw(spec.lease, tiles_produced, volume)
+ .await
+ {
return Err(Halted::failed(chunk, error));
}
Ok(EnqueuedChunk::new(spec, tiles_produced))
@@ -398,15 +412,26 @@ impl PgChunkStore {
Ok(spec.lease)
}
+ /// Fail a chunk for retry, holding it out of the claim gate for `retry_delay`.
+ ///
+ /// A post-mark failure is stamped too, so a chunk whose `confirm` lost a race waits before it
+ /// retries. The wait is not free: it is added to the run's wall-clock, and the run cannot
+ /// complete until every chunk is `confirmed`. It is charged anyway because the retry re-scans
+ /// from the start rather than re-running the failed write, and a `confirm` that failed once is
+ /// likely to fail again immediately. At the first attempts the wait is small next to the day
+ /// band it spaces out; by the time it reaches the cap it plausibly exceeds that scan, which is
+ /// the point at which the attempt budget, not the wait, is what should stop the chunk.
pub async fn fail(
&self,
lease: ChunkLease,
error: &RenderedError,
+ retry_delay: Duration,
) -> Result<(), ChunkStoreError> {
let updated = sqlx::query_scalar::<_, ChunkId>(&format!(
r#"
UPDATE cohort_backfill_chunks
- SET status = $3, last_error = left($4, $5), updated_at = now()
+ SET status = $3, last_error = left($4, $5),
+ next_attempt_at = now() + make_interval(secs => $6), updated_at = now()
WHERE id = $1 AND claim_epoch = $2 AND status IN {active}
RETURNING id
"#,
@@ -417,6 +442,7 @@ impl PgChunkStore {
.bind(ChunkStatus::Failed.as_str())
.bind(error.as_str())
.bind(PERSISTED_ERROR_LIMIT)
+ .bind(retry_delay.as_secs_f64())
.fetch_optional(&self.pool)
.await?;
fenced(updated, lease, ChunkOperation::Fail)
@@ -512,17 +538,32 @@ impl PgChunkStore {
fenced(updated, lease, ChunkOperation::Heartbeat)
}
+ /// The `scanning`→`produced` CAS, recording what the chunk produced and what its scan moved.
+ ///
+ /// Only this transition writes the byte columns, matching `tiles_produced`: a failed or
+ /// cancelled chunk is re-scanned from the start, so persisting a partial volume against it
+ /// would double-count once the retry succeeds. The counters still cover those scans.
+ ///
+ /// A retry that turns out vacuous — every referencing window slid past the day, or the plan
+ /// resolved to no scan at all — reports zero and overwrites whatever the earlier attempt
+ /// measured. The ledger row then reads like a chunk that never moved anything. That is the same
+ /// trade `tiles_produced` already makes, and the counters keep the real bytes; only the
+ /// per-chunk column loses them.
pub(crate) async fn mark_produced_raw(
&self,
lease: ChunkLease,
tiles_produced: u64,
+ volume: ScanVolume,
) -> Result<(), ChunkStoreError> {
let tiles_produced = i64::try_from(tiles_produced)
.map_err(|_| ChunkStoreError::TilesProducedOutOfRange(tiles_produced))?;
+ let received_bytes = scan_bytes_column(volume.received_bytes())?;
+ let decoded_bytes = scan_bytes_column(volume.decoded_bytes())?;
let updated = sqlx::query_scalar::<_, ChunkId>(
r#"
UPDATE cohort_backfill_chunks
- SET status = $3, tiles_produced = $4, updated_at = now()
+ SET status = $3, tiles_produced = $4, scan_received_bytes = $5,
+ scan_decoded_bytes = $6, updated_at = now()
WHERE id = $1 AND claim_epoch = $2 AND status = 'scanning'
RETURNING id
"#,
@@ -531,6 +572,8 @@ impl PgChunkStore {
.bind(lease.epoch())
.bind(ChunkStatus::Produced.as_str())
.bind(tiles_produced)
+ .bind(received_bytes)
+ .bind(decoded_bytes)
.fetch_optional(&self.pool)
.await?;
fenced(updated, lease, ChunkOperation::MarkProduced)
@@ -580,6 +623,7 @@ impl PgChunkStore {
band,
s_chunk: SChunkMs(row.s_chunk_ms),
person_range,
+ attempt: AttemptCount::from_row(row.attempts),
};
let handle = LeaseHandle::start(self.clone(), lease, claimant.clone(), lease_duration);
Ok(Claim {
@@ -662,6 +706,8 @@ pub enum ChunkStoreError {
},
#[error("tiles produced {0} exceeds PostgreSQL bigint range")]
TilesProducedOutOfRange(u64),
+ #[error("scan byte count {0} exceeds PostgreSQL bigint range")]
+ ScanBytesOutOfRange(u64),
#[error("day index {0} is outside chrono's date range")]
InvalidDay(DayIdx),
#[error(transparent)]
@@ -744,6 +790,7 @@ struct ClaimedRow {
day: NaiveDate,
band: Band,
claim_epoch: ClaimEpoch,
+ attempts: i32,
person_range_lo: Option<Uuid>,
person_range_hi: Option<Uuid>,
s_chunk_ms: i64,
@@ -773,6 +820,10 @@ fn fenced(
.ok_or(ChunkStoreError::LeaseLost { lease, operation })
}
+fn scan_bytes_column(bytes: u64) -> Result<i64, ChunkStoreError> {
+ i64::try_from(bytes).map_err(|_| ChunkStoreError::ScanBytesOutOfRange(bytes))
+}
+
fn date_for_day(day: DayIdx) -> Option<NaiveDate> {
let epoch = NaiveDate::from_ymd_opt(1970, 1, 1)?;
epoch.checked_add_signed(chrono::Duration::days(i64::from(day)))
@@ -784,17 +835,15 @@ mod tests {
#[test]
fn hoisted_status_fragments_only_name_live_chunk_statuses() {
- for fragment in [ACTIVE_STATUSES_SQL, RETRYABLE_STATUSES_SQL] {
- let statuses = fragment
- .trim_matches(|c| c == '(' || c == ')')
- .split(',')
- .map(|token| token.trim().trim_matches('\''));
- for status in statuses {
- assert!(
- status.parse::<ChunkStatus>().is_ok(),
- "SQL fragment names non-vocabulary status {status:?}"
- );
- }
+ let statuses = ACTIVE_STATUSES_SQL
+ .trim_matches(|c| c == '(' || c == ')')
+ .split(',')
+ .map(|token| token.trim().trim_matches('\''));
+ for status in statuses {
+ assert!(
+ status.parse::<ChunkStatus>().is_ok(),
+ "SQL fragment names non-vocabulary status {status:?}"
+ );
}
}
}
diff --git a/rust/cohort-seeder/src/test_support.rs b/rust/cohort-seeder/src/test_support.rs
index c56b9b055cd8..224b4c008dba 100644
--- a/rust/cohort-seeder/src/test_support.rs
+++ b/rust/cohort-seeder/src/test_support.rs
@@ -2,21 +2,28 @@
//! the store's lease-fenced SQL directly by [`ChunkLease`] so the integration test can exercise the
//! epoch fence in isolation. Not compiled into the shipping binary.
+use std::time::Duration;
+
use chrono::{DateTime, Utc};
use sqlx::PgPool;
use crate::domain::{
- ChunkLease, ChunkSpec, ClaimedChunk, DispatchEpoch, ProduceHwms, RunId, ScannedChunk, SeedTile,
+ ChunkLease, ChunkSpec, ClaimedChunk, DispatchEpoch, ProduceHwms, RunId, ScanVolume,
+ ScannedChunk, SeedTile,
};
use crate::store::chunks::{ChunkStoreError, PgChunkStore};
use crate::store::{Claimant, LeaseDuration, RenderedError};
+/// Drive the executor's recovery path, so a test exercises the wiring that sizes a retry wait from
+/// the chunk's attempt count rather than supplying a delay of its own.
+pub use crate::app::fail_via_recovery;
+
pub fn claimed(spec: ChunkSpec) -> ClaimedChunk {
ClaimedChunk::new(spec)
}
-pub fn scanned(spec: ChunkSpec, tiles: Vec<SeedTile>) -> ScannedChunk {
- ScannedChunk::new(spec, tiles)
+pub fn scanned(spec: ChunkSpec, tiles: Vec<SeedTile>, volume: ScanVolume) -> ScannedChunk {
+ ScannedChunk::new(spec, tiles, volume)
}
pub async fn heartbeat(
@@ -32,8 +39,9 @@ pub async fn mark_produced_raw(
store: &PgChunkStore,
lease: ChunkLease,
tiles_produced: u64,
+ volume: ScanVolume,
) -> Result<(), ChunkStoreError> {
- store.mark_produced_raw(lease, tiles_produced).await
+ store.mark_produced_raw(lease, tiles_produced, volume).await
}
pub async fn confirm_raw(
@@ -48,8 +56,11 @@ pub async fn fail(
store: &PgChunkStore,
lease: ChunkLease,
error: &str,
+ retry_delay: Duration,
) -> Result<(), ChunkStoreError> {
- store.fail(lease, &RenderedError::from_message(error)).await
+ store
+ .fail(lease, &RenderedError::from_message(error), retry_delay)
+ .await
}
pub async fn unclaim(store: &PgChunkStore, lease: ChunkLease) -> Result<(), ChunkStoreError> {
diff --git a/rust/cohort-seeder/tests/fixtures/cohort_backfill_0009.sql b/rust/cohort-seeder/tests/fixtures/cohort_backfill_0012.sql
similarity index 75%
rename from rust/cohort-seeder/tests/fixtures/cohort_backfill_0009.sql
rename to rust/cohort-seeder/tests/fixtures/cohort_backfill_0012.sql
index 3b797ea6419b..a008141397fd 100644
--- a/rust/cohort-seeder/tests/fixtures/cohort_backfill_0009.sql
+++ b/rust/cohort-seeder/tests/fixtures/cohort_backfill_0012.sql
@@ -1,7 +1,16 @@
--- Snapshot pinned to products/cohorts/backend/migrations/0009_cohort_backfill_per_kind_uniqueness.py,
--- the last migration that changed this DDL. 0010 alters only `marker_watch`'s help_text, which emits
--- no SQL.
+-- Snapshot pinned to
+-- products/cohorts/backend/migrations/0012_cohortbackfillchunk_next_attempt_at_and_more.py, the last
+-- migration that changed this DDL. 0010 alters only `marker_watch`'s help_text, which emits no SQL,
+-- and 0011 touches posthog_cohort columns this projection does not carry.
-- External Team/Cohort foreign keys are omitted so the contract test stays schema-local.
+--
+-- Nothing enforces this snapshot against Django. No test diffs it with `sqlmigrate`, and the
+-- filename appears at one call site, so a later migration that changes these tables and forgets
+-- this file passes CI and diverges from production. Re-derive it by hand when you touch the
+-- `cohort_backfill_*` DDL: `python manage.py sqlmigrate cohorts <number>` prints the statements the
+-- migration emits (CI runs the same command to post migration SQL on a PR). Fold them in, drop the
+-- external Team/Cohort foreign key lines to keep the projection schema-local, and rename this file
+-- and its `include_str!` to the new number.
CREATE TABLE cohort_backfill_runs (
id uuid PRIMARY KEY,
@@ -59,8 +68,13 @@ CREATE TABLE cohort_backfill_chunks (
person_range_lo uuid,
person_range_hi uuid,
attempts integer NOT NULL DEFAULT 0,
+ next_attempt_at timestamptz,
last_error text NOT NULL DEFAULT '',
tiles_produced bigint NOT NULL DEFAULT 0,
+ -- 0012 scan-volume columns. The DEFAULT is the contract `plan_chunks` leans on: it inserts an
+ -- explicit column list that names neither, so dropping the default would break planning.
+ scan_received_bytes bigint NOT NULL DEFAULT 0,
+ scan_decoded_bytes bigint NOT NULL DEFAULT 0,
produce_hwms jsonb,
confirmed_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
diff --git a/rust/cohort-seeder/tests/pg_chunks.rs b/rust/cohort-seeder/tests/pg_chunks.rs
index 643639ab555b..cc40fccf7a5d 100644
--- a/rust/cohort-seeder/tests/pg_chunks.rs
+++ b/rust/cohort-seeder/tests/pg_chunks.rs
@@ -18,7 +18,8 @@ use cohort_seeder::app::reconcile_dispatch::{
RegisterBackfillConfirmation,
};
use cohort_seeder::domain::{
- tile_ranges, ClaimEpoch, PersonRunValidation, PinnedWarning, ProduceHwms, ScopeKind,
+ tile_ranges, AttemptCount, ClaimEpoch, PersonRunValidation, PinnedWarning, ProduceHwms,
+ RetryBackoffPolicy, ScanVolume, ScopeKind,
};
use cohort_seeder::store::chunks::{ChunkStoreError, PgChunkStore, PlanOutcome, NO_ERROR_RECORDED};
use cohort_seeder::store::lease::LeaseFailure;
@@ -40,6 +41,9 @@ use support::{
};
const ONE_BAND: NonZeroU16 = NonZeroU16::MIN;
+/// Fail a chunk without holding it out of the claim gate, for the scenarios that assert on
+/// something other than the backoff and want the chunk claimable on the next call.
+const NO_BACKOFF: Duration = Duration::ZERO;
/// Discovery honors an `Only` allowlist (self team only) and `All` admits every eligible run
/// regardless of team, trigger, or already-seeding status.
@@ -617,15 +621,15 @@ async fn expired_lease_reclaim_bumps_epoch_and_fences_the_stale_lease() -> Resul
ensure_lease_lost(
test_support::heartbeat(&store, stale, &Claimant::new("worker-a")?, lease60).await,
)?;
- ensure_lease_lost(test_support::mark_produced_raw(&store, stale, 1).await)?;
+ ensure_lease_lost(test_support::mark_produced_raw(&store, stale, 1, ScanVolume::default()).await)?;
ensure_lease_lost(test_support::confirm_raw(&store, stale, &ProduceHwms::default()).await)?;
- ensure_lease_lost(test_support::fail(&store, stale, "stale failure").await)?;
+ ensure_lease_lost(test_support::fail(&store, stale, "stale failure", NO_BACKOFF).await)?;
ensure_lease_lost(test_support::unclaim(&store, stale).await)?;
// The fresh lease, in contrast, drives the chunk through mark-produced and confirm.
let mut hwms = ProduceHwms::default();
hwms.observe(3, 41);
- test_support::mark_produced_raw(&store, reclaimed_lease, 0).await?;
+ test_support::mark_produced_raw(&store, reclaimed_lease, 0, ScanVolume::default()).await?;
test_support::confirm_raw(&store, reclaimed_lease, &hwms).await?;
drop(reclaimed);
Ok(())
@@ -671,6 +675,293 @@ async fn unclaim_returns_chunk_to_pending_and_refunds_one_attempt() -> Result<()
.await
}
+/// A failed chunk is held out of the claim gate until the wait `fail` stamped has elapsed, then
+/// becomes claimable again with the stamp cleared. Without the hold, the poll loop re-claims a
+/// chunk failing for a durable reason within seconds and burns its whole attempt budget on the same
+/// failure, which is the reclaim storm this gate exists to break.
+#[tokio::test]
+async fn a_failed_chunk_waits_out_its_backoff_before_it_is_claimable_again() -> Result<()> {
+ with_db(|pool| async move {
+ let seeding_run =
+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;
+ let store = PgChunkStore::new(pool.clone());
+ ensure!(planned_count(store.plan_chunks(seeding_run, [100], ONE_BAND).await?)? == 1);
+
+ let lease60 = LeaseDuration::new(Duration::from_secs(60))?;
+ let attempts5 = MaxAttempts::new(5)?;
+ let run_ids = [seeding_run];
+
+ let claimed = store
+ .claim_next(&run_ids, &Claimant::new("worker-a")?, lease60, attempts5)
+ .await?
+ .context("claimant found no chunk")?;
+ let lease = claimed.chunk.spec().lease;
+ let chunk_id = lease.chunk_id();
+ // The claim reports the attempt the backoff is sized from.
+ ensure!(claimed.chunk.spec().attempt.get() == 1);
+ store
+ .fail(
+ lease,
+ &RenderedError::from_message("transient"),
+ Duration::from_secs(600),
+ )
+ .await?;
+ drop(claimed);
+
+ // The stamp is `now() + delay`, so the remaining wait is the delay minus test runtime.
+ let remaining_secs: f64 = sqlx::query_scalar(
+ "SELECT extract(epoch FROM next_attempt_at - now())::float8
+ FROM cohort_backfill_chunks WHERE id = $1",
+ )
+ .bind(chunk_id)
+ .fetch_one(&pool)
+ .await?;
+ ensure!(
+ (540.0..=600.0).contains(&remaining_secs),
+ "expected a ~600s hold, got {remaining_secs}s"
+ );
+ ensure!(store
+ .claim_next(&run_ids, &Claimant::new("worker-b")?, lease60, attempts5)
+ .await?
+ .is_none());
+
+ // Once the wait has passed the chunk is claimable, and the claim clears the stamp so a
+ // later failure is not gated by a stale one.
+ sqlx::query(
+ "UPDATE cohort_backfill_chunks SET next_attempt_at = now() - interval '1 second' WHERE id = $1",
+ )
+ .bind(chunk_id)
+ .execute(&pool)
+ .await?;
+ let retried = store
+ .claim_next(&run_ids, &Claimant::new("worker-c")?, lease60, attempts5)
+ .await?
+ .context("chunk past its backoff was not claimable")?;
+ ensure!(retried.chunk.spec().attempt.get() == 2);
+ let stamp: Option<chrono::DateTime<chrono::Utc>> =
+ sqlx::query_scalar("SELECT next_attempt_at FROM cohort_backfill_chunks WHERE id = $1")
+ .bind(chunk_id)
+ .fetch_one(&pool)
+ .await?;
+ ensure!(stamp.is_none(), "the claim left a stale backoff stamp");
+ Ok(())
+ })
+ .await
+}
+
+/// The recovery path sizes the wait from the chunk's own attempt count, and that wait is what
+/// reaches `next_attempt_at`.
+///
+/// The store's `fail` takes the delay as an argument, so every other test here supplies its own and
+/// proves nothing about where a real one comes from. A recovery path that always asked for the
+/// first attempt's wait would hold every chunk a flat `base` forever — defeating the whole feature
+/// — while the policy's own unit tests and the gate test above all stayed green.
+///
+/// The chunks start one attempt below the cap, so the claim reports an attempt whose ceiling has
+/// saturated at 1800s while a first attempt's is 1s. Full jitter draws from `[0, ceiling]`, so one
+/// sample could still land low; over four chunks the chance that all four fall inside the first
+/// attempt's 1s bound is about (1/1800)^4, which does not flake.
+#[tokio::test]
+async fn the_recovery_path_draws_its_wait_from_the_chunks_attempt_count() -> Result<()> {
+ with_db(|pool| async move {
+ let seeding_run =
+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;
+ let store = PgChunkStore::new(pool.clone());
+ let lease60 = LeaseDuration::new(Duration::from_secs(60))?;
+ let attempts50 = MaxAttempts::new(50)?;
+ let run_ids = [seeding_run];
+ let policy =
+ RetryBackoffPolicy::new(Duration::from_secs(1), Duration::from_secs(1800)).unwrap();
+
+ let days = [100, 101, 102, 103];
+ ensure!(planned_count(store.plan_chunks(seeding_run, days, ONE_BAND).await?)? == 4);
+ sqlx::query("UPDATE cohort_backfill_chunks SET attempts = 48 WHERE run_id = $1")
+ .bind(seeding_run)
+ .execute(&pool)
+ .await?;
+
+ let mut longest_wait = Duration::ZERO;
+ for day in days {
+ let claimed = store
+ .claim_next(&run_ids, &Claimant::new("worker-a")?, lease60, attempts50)
+ .await?
+ .context("a chunk under the cap was not claimable")?;
+ let chunk = claimed.chunk;
+ let lease = claimed.lease;
+ let chunk_id = chunk.spec().lease.chunk_id();
+ ensure!(chunk.spec().attempt.get() == 49, "day {day}");
+ let drawn =
+ test_support::fail_via_recovery(&store, chunk, "clickhouse memory limit", policy)
+ .await
+ .context("the recovery path did not fail the chunk")?;
+ drop(lease);
+
+ // The stamp is `now() + delay`, so the remaining wait is the delay minus test runtime.
+ let remaining_secs: f64 = sqlx::query_scalar(
+ "SELECT extract(epoch FROM next_attempt_at - now())::float8
+ FROM cohort_backfill_chunks WHERE id = $1",
+ )
+ .bind(chunk_id)
+ .fetch_one(&pool)
+ .await?;
+ ensure!(
+ remaining_secs <= drawn.as_secs_f64(),
+ "day {day} stamped {remaining_secs}s, more than the {drawn:?} the path drew"
+ );
+ longest_wait = longest_wait.max(drawn);
+ }
+
+ ensure!(
+ longest_wait > policy.ceiling(AttemptCount::from_row(1)),
+ "the longest of four near-cap waits was {longest_wait:?}, inside the first attempt's \
+ ceiling — the recovery path is not reading the attempt count"
+ );
+ Ok(())
+ })
+ .await
+}
+
+/// Only the failed→claim transition reads the backoff stamp. A `pending` chunk has not failed, and
+/// an expired `produced` lease must reclaim immediately because its tiles are already in Kafka and
+/// the run cannot complete until it reaches `confirmed`. Gating either would stall a run on a
+/// column that describes neither.
+///
+/// The two lease legs are a guard rail, not a live bug. The claim `UPDATE` sets `next_attempt_at`
+/// to NULL in the same statement that writes `scanning`, so no reclaimable row carries a stale
+/// stamp today and the arms would pass with or without their gate. Each leg stamps one by hand, so
+/// a later edit that widens the gate onto a lease arm is caught here instead of stalling a run in
+/// production.
+#[tokio::test]
+async fn the_backoff_gate_applies_only_to_the_failed_claim_arm() -> Result<()> {
+ with_db(|pool| async move {
+ let seeding_run =
+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;
+ let store = PgChunkStore::new(pool.clone());
+ let lease60 = LeaseDuration::new(Duration::from_secs(60))?;
+ let attempts5 = MaxAttempts::new(5)?;
+ let run_ids = [seeding_run];
+
+ // A pending chunk carrying a future stamp is still claimable.
+ ensure!(planned_count(store.plan_chunks(seeding_run, [100], ONE_BAND).await?)? == 1);
+ sqlx::query(
+ "UPDATE cohort_backfill_chunks SET next_attempt_at = now() + interval '1 hour' WHERE run_id = $1",
+ )
+ .bind(seeding_run)
+ .execute(&pool)
+ .await?;
+ let pending = store
+ .claim_next(&run_ids, &Claimant::new("worker-a")?, lease60, attempts5)
+ .await?
+ .context("a pending chunk was gated by the backoff stamp")?;
+ let pending_lease = pending.chunk.spec().lease;
+
+ // An unclaim returns it to `pending`, and it stays claimable however the stamp reads.
+ store.unclaim(pending_lease).await?;
+ drop(pending);
+ sqlx::query(
+ "UPDATE cohort_backfill_chunks SET next_attempt_at = now() + interval '1 hour' WHERE id = $1",
+ )
+ .bind(pending_lease.chunk_id())
+ .execute(&pool)
+ .await?;
+ let reclaimed = store
+ .claim_next(&run_ids, &Claimant::new("worker-b")?, lease60, attempts5)
+ .await?
+ .context("an unclaimed chunk was gated by the backoff stamp")?;
+
+ // A produced chunk whose lease expired reclaims regardless of the stamp.
+ let produced_lease = reclaimed.chunk.spec().lease;
+ test_support::mark_produced_raw(&store, produced_lease, 1, ScanVolume::default()).await?;
+ drop(reclaimed);
+ sqlx::query(
+ "UPDATE cohort_backfill_chunks
+ SET lease_expires_at = now() - interval '1 second',
+ next_attempt_at = now() + interval '1 hour'
+ WHERE id = $1",
+ )
+ .bind(produced_lease.chunk_id())
+ .execute(&pool)
+ .await?;
+ let produced_reclaim = store
+ .claim_next(&run_ids, &Claimant::new("worker-c")?, lease60, attempts5)
+ .await?
+ .context("an expired produced lease was gated by the backoff stamp")?;
+
+ // A scanning chunk whose lease expired reclaims too. It is left `scanning` rather than
+ // marked produced, which is the shape of a worker that died before it reached `fail`, so
+ // nothing sized a wait for it and nothing should hold it back.
+ let scanning_lease = produced_reclaim.chunk.spec().lease;
+ drop(produced_reclaim);
+ sqlx::query(
+ "UPDATE cohort_backfill_chunks
+ SET lease_expires_at = now() - interval '1 second',
+ next_attempt_at = now() + interval '1 hour'
+ WHERE id = $1",
+ )
+ .bind(scanning_lease.chunk_id())
+ .execute(&pool)
+ .await?;
+ ensure!(store
+ .claim_next(&run_ids, &Claimant::new("worker-d")?, lease60, attempts5)
+ .await?
+ .is_some());
+ Ok(())
+ })
+ .await
+}
+
+/// The `scanning`→`produced` CAS records what the scan moved, and planning leaves the byte columns
+/// at the database-side default. The default is load-bearing: `plan_chunks` inserts an explicit
+/// column list that names neither column, so a Django-only default would make every planning insert
+/// violate NOT NULL during a rollout.
+#[tokio::test]
+async fn mark_produced_records_the_scan_byte_volume_that_planning_defaults_to_zero() -> Result<()> {
+ with_db(|pool| async move {
+ let seeding_run =
+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;
+ let store = PgChunkStore::new(pool.clone());
+ ensure!(planned_count(store.plan_chunks(seeding_run, [100], ONE_BAND).await?)? == 1);
+
+ let planned: (i64, i64) = sqlx::query_as(
+ "SELECT scan_received_bytes, scan_decoded_bytes FROM cohort_backfill_chunks WHERE run_id = $1",
+ )
+ .bind(seeding_run)
+ .fetch_one(&pool)
+ .await?;
+ ensure!(planned == (0, 0));
+
+ let claimed = store
+ .claim_next(
+ &[seeding_run],
+ &Claimant::new("worker-a")?,
+ LeaseDuration::new(Duration::from_secs(60))?,
+ MaxAttempts::new(5)?,
+ )
+ .await?
+ .context("claimant found no chunk")?;
+ let lease = claimed.chunk.spec().lease;
+ test_support::mark_produced_raw(
+ &store,
+ lease,
+ 7,
+ ScanVolume::new(9_876_543_210, 41_234_567_890),
+ )
+ .await?;
+ drop(claimed);
+
+ let stored: (i64, i64, i64) = sqlx::query_as(
+ "SELECT tiles_produced, scan_received_bytes, scan_decoded_bytes
+ FROM cohort_backfill_chunks WHERE id = $1",
+ )
+ .bind(lease.chunk_id())
+ .fetch_one(&pool)
+ .await?;
+ ensure!(stored == (7, 9_876_543_210, 41_234_567_890));
+ Ok(())
+ })
+ .await
+}
+
/// The attempt cap is terminal for a `failed` chunk (no further claim), but an expired `produced`
/// chunk sitting AT the cap is still reclaimed with a bumped epoch — its tiles are already in
/// Kafka, so it must keep retrying until it reaches `confirmed`. Only `scanning` reclaims are
@@ -703,7 +994,7 @@ async fn attempt_cap_is_terminal_for_failed_but_reclaims_expired_produced() -> R
.await?;
ensure!(reclaimed_attempts == 5);
store
- .fail(retry_lease, &RenderedError::from_message("terminal"))
+ .fail(retry_lease, &RenderedError::from_message("terminal"), NO_BACKOFF)
.await?;
drop(retry);
ensure!(store
@@ -718,7 +1009,7 @@ async fn attempt_cap_is_terminal_for_failed_but_reclaims_expired_produced() -> R
.await?
.context("second chunk was not claimable")?;
let final_attempt_lease = final_attempt.chunk.spec().lease;
- test_support::mark_produced_raw(&store, final_attempt_lease, 1).await?;
+ test_support::mark_produced_raw(&store, final_attempt_lease, 1, ScanVolume::default()).await?;
drop(final_attempt);
sqlx::query(
"UPDATE cohort_backfill_chunks SET attempts = 5, lease_expires_at = now() - interval '1 second' WHERE id = $1",
@@ -740,6 +1031,10 @@ async fn attempt_cap_is_terminal_for_failed_but_reclaims_expired_produced() -> R
.fetch_one(&pool)
.await?;
ensure!(active_reclaim_attempts == 5);
+ // The claim `CASE` stops incrementing at the cap, so this is the arm where the count the
+ // spec reports and the number of claims diverge. The spec must still carry the column, not
+ // the claim tally: the retry backoff is sized from it.
+ ensure!(observed.chunk.spec().attempt.get() == 5);
Ok(())
})
.await
@@ -1032,7 +1327,11 @@ async fn fail_truncates_chunk_and_run_error_columns() -> Result<()> {
let lease = claimed.chunk.spec().lease;
let chunk_id = lease.chunk_id();
store
- .fail(lease, &RenderedError::from_message("x".repeat(5_000)))
+ .fail(
+ lease,
+ &RenderedError::from_message("x".repeat(5_000)),
+ NO_BACKOFF,
+ )
.await?;
drop(claimed);
let (failed_status, error_length): (String, i32) = sqlx::query_as(
diff --git a/rust/cohort-seeder/tests/support/mod.rs b/rust/cohort-seeder/tests/support/mod.rs
index a095232594e1..e4aabe91693e 100644
--- a/rust/cohort-seeder/tests/support/mod.rs
+++ b/rust/cohort-seeder/tests/support/mod.rs
@@ -25,8 +25,8 @@ use sqlx::{Connection, PgConnection, PgPool};
use uuid::Uuid;
/// The `cohort_backfill_*` DDL (plus a schema-local `posthog_cohort` projection), pinned to Django
-/// migration 0009, applied fresh into each test schema.
-pub const DDL: &str = include_str!("../fixtures/cohort_backfill_0009.sql");
+/// migration 0012, applied fresh into each test schema.
+pub const DDL: &str = include_str!("../fixtures/cohort_backfill_0012.sql");
/// A live cohort condition hash used by the superseded-load fixtures.
pub const ACTIVE_HASH: &str = "active0000000000";
/// A superseded cohort condition hash used by the superseded-load fixtures.