Skip to content

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

feat(cohorts): diff the projected seeder scan against the wide one (#92892)

Matheus Batistad343cd72d955
diff --git a/rust/cohort-seeder/src/app/mod.rs b/rust/cohort-seeder/src/app/mod.rs
index 9ab8ef795320..40f5dd509571 100644
--- a/rust/cohort-seeder/src/app/mod.rs
+++ b/rust/cohort-seeder/src/app/mod.rs
@@ -9,6 +9,7 @@ mod orchestrator;
mod person_execute;
mod person_plan;
mod prepare;
+pub mod prime;
pub mod reconcile_dispatch;
pub mod settings;
pub mod watch;
@@ -22,6 +23,7 @@ pub use orchestrator::{
fail_exhausted_runs_of_kind, PersonComponents, SeederOrchestrator,
ORCHESTRATOR_LIVENESS_DEADLINE,
};
+pub use prime::prime_zero_series;
pub use settings::{OrchestratorSettings, PersonSettings};
pub use watch::{MarkerWatchTask, PgMarkerFlush, WatchDirectives, MARKER_WATCH_LIVENESS_DEADLINE};
diff --git a/rust/cohort-seeder/src/app/prime.rs b/rust/cohort-seeder/src/app/prime.rs
new file mode 100644
index 000000000000..5238ca6b1ae0
--- /dev/null
+++ b/rust/cohort-seeder/src/app/prime.rs
@@ -0,0 +1,67 @@
+//! Publishes at zero the counters a bounded validation run is gated on. Depends on the metric
+//! manifest plus the three modules that own the label vocabularies being primed.
+//!
+//! A counter that never fired is absent from `/metrics`, not zero, so a gate phrased "this stayed
+//! at zero" cannot separate a clean run from a broken exporter, a renamed label, or a code path
+//! that was never reached. Priming turns that reading into a provable one.
+//!
+//! Only counters a run is read against get primed, and each is primed across its whole label
+//! vocabulary rather than the one value a gate names — a `reason` or `class` panel that breaks
+//! them out should show every value it can ever show. That does put a flat zero line on those
+//! panels for values production never produces.
+//!
+//! The two `seeder_shadow_compare_*` counters solve the same problem without priming, which is why
+//! they are absent here. Their `team_id` label has no value until a chunk is scanned.
+//! `seeder_shadow_compare_total` then publishes one of a closed `result` vocabulary per chunk, so
+//! a clean run makes the family present, and `seeder_shadow_compare_legacy_skipped_total` is
+//! incremented by zero on every path that reaches it.
+
+use cohort_core::hogvm::VmErrorClass;
+use metrics::counter;
+
+use crate::clickhouse::ScanSkipReason;
+use crate::observability::metrics::{CHUNKS_POISONED, EVENTS_SKIPPED, HOGVM_ERRORS};
+use crate::store::runs::RunKind;
+
+/// Register every label value of the gated counters at zero. Call once, after the recorder is
+/// installed; without a recorder every call is a no-op.
+pub fn prime_zero_series() {
+ for reason in ScanSkipReason::ALL {
+ counter!(EVENTS_SKIPPED, "reason" => reason.as_str()).increment(0);
+ }
+ for class in VmErrorClass::ALL {
+ counter!(HOGVM_ERRORS, "class" => class.as_str()).increment(0);
+ }
+ for kind in RunKind::ALL {
+ counter!(CHUNKS_POISONED, "kind" => kind.as_str()).increment(0);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Renders through a real recorder rather than asserting on the loops above: whether a counter
+ /// touched only with a zero increment appears in the export at all is the exporter's behavior,
+ /// and that behavior is the whole point of the call.
+ #[test]
+ fn the_gated_counters_render_at_zero_before_anything_fires() {
+ let recorder = metrics_exporter_prometheus::PrometheusBuilder::new().build_recorder();
+ let handle = recorder.handle();
+ metrics::with_local_recorder(&recorder, prime_zero_series);
+ let rendered = handle.render();
+
+ // The three readings a validation run is gated on: malformed blobs skipped, HogVM aborts
+ // on an unresolvable reference, and chunks dead-lettered at the attempt cap.
+ for series in [
+ format!("{EVENTS_SKIPPED}{{reason=\"globals_parse_error\"}} 0"),
+ format!("{HOGVM_ERRORS}{{class=\"unknown_ref\"}} 0"),
+ format!("{CHUNKS_POISONED}{{kind=\"behavioral\"}} 0"),
+ ] {
+ assert!(
+ rendered.contains(&series),
+ "{series} is absent from the export:\n{rendered}"
+ );
+ }
+ }
+}
diff --git a/rust/cohort-seeder/src/clickhouse/log_comment.rs b/rust/cohort-seeder/src/clickhouse/log_comment.rs
index defe0eaf467a..4e4ba972874f 100644
--- a/rust/cohort-seeder/src/clickhouse/log_comment.rs
+++ b/rust/cohort-seeder/src/clickhouse/log_comment.rs
@@ -50,6 +50,12 @@ pub enum ScanLogComment {
spec: ChunkSpec,
cohort_id: Option<CohortId>,
},
+ /// The shadow compare's legacy wide re-scan of a behavioral chunk. Its own phase, so
+ /// `query_log_archive` separates the diagnostic's cost from the authoritative scan's.
+ BehavioralCompareChunk {
+ spec: ChunkSpec,
+ cohort_id: Option<CohortId>,
+ },
PersonChunk(ChunkSpec),
PersonBoundaries {
run_id: RunId,
@@ -61,6 +67,7 @@ impl ScanLogComment {
const fn phase(self) -> &'static str {
match self {
Self::BehavioralChunk { .. } => "behavioral",
+ Self::BehavioralCompareChunk { .. } => "behavioral_compare",
Self::PersonChunk(_) => "person_scan",
Self::PersonBoundaries { .. } => "person_boundaries",
}
@@ -71,7 +78,8 @@ impl ScanLogComment {
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 {
+ Self::BehavioralChunk { spec, cohort_id }
+ | Self::BehavioralCompareChunk { spec, cohort_id } => LogCommentFields {
cohort_id: cohort_id.map(|cohort_id| cohort_id.0),
day: Some(spec.day),
..LogCommentFields::for_chunk(phase, spec)
@@ -203,6 +211,18 @@ mod tests {
+ r#""phase":"behavioral","chunk":"00000000-0000-0000-0000-0000000000c0","#
+ r#""day":20000,"band":3,"num_bands":8,"epoch":7}"#
);
+ assert_eq!(
+ ScanLogComment::BehavioralCompareChunk {
+ 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_compare","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(),
@@ -236,6 +256,10 @@ mod tests {
spec: spec(None),
cohort_id: None,
},
+ ScanLogComment::BehavioralCompareChunk {
+ spec: spec(None),
+ cohort_id: None,
+ },
ScanLogComment::PersonChunk(spec(Some(range))),
ScanLogComment::PersonBoundaries {
run_id: RunId(Uuid::nil()),
diff --git a/rust/cohort-seeder/src/clickhouse/mod.rs b/rust/cohort-seeder/src/clickhouse/mod.rs
index 4be3462afd8d..babdf3b9ae36 100644
--- a/rust/cohort-seeder/src/clickhouse/mod.rs
+++ b/rust/cohort-seeder/src/clickhouse/mod.rs
@@ -18,4 +18,4 @@ 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};
+pub use scanner::{ChunkScanner, ScanError, ScanSkipReason};
diff --git a/rust/cohort-seeder/src/clickhouse/scan_volume.rs b/rust/cohort-seeder/src/clickhouse/scan_volume.rs
index c9ad6ab2eca7..6994750ab793 100644
--- a/rust/cohort-seeder/src/clickhouse/scan_volume.rs
+++ b/rust/cohort-seeder/src/clickhouse/scan_volume.rs
@@ -16,9 +16,15 @@ use crate::observability::metrics::{SCAN_DECODED_BYTES, SCAN_RECEIVED_BYTES};
/// 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.
+///
+/// [`ScanKind::BehavioralCompare`] is the shadow compare's wide re-scan of a behavioral chunk. It
+/// reads the same rows as `Behavioral` over the same table, so it is separate for the opposite
+/// reason: the authoritative series must stay clean while the knob is on, and the two side by side
+/// are the projection's measured win.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScanKind {
Behavioral,
+ BehavioralCompare,
Person,
PersonBoundaries,
}
@@ -27,6 +33,7 @@ impl ScanKind {
pub const fn as_str(self) -> &'static str {
match self {
Self::Behavioral => "behavioral",
+ Self::BehavioralCompare => "behavioral_compare",
Self::Person => "person",
Self::PersonBoundaries => "person_boundaries",
}
diff --git a/rust/cohort-seeder/src/clickhouse/scanner.rs b/rust/cohort-seeder/src/clickhouse/scanner.rs
index c23b02b85130..7b3620566095 100644
--- a/rust/cohort-seeder/src/clickhouse/scanner.rs
+++ b/rust/cohort-seeder/src/clickhouse/scanner.rs
@@ -15,22 +15,23 @@ use cohort_core::hogvm::VmErrorClass;
use common_types::cohort::TeamAllowlist;
use metrics::{counter, histogram};
use tokio_util::sync::CancellationToken;
-use tracing::info;
+use tracing::{info, warn};
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 super::sql::{plan_scan, scan_sql, ScanPlan, ScanSpec};
use crate::domain::{
- conditions_active_on, ActiveConditions, AggregateError, BlobSource, CancelCause,
- ChunkAccumulator, ChunkDomainError, ChunkProjection, ClaimedChunk, ConditionAnalyses, DayIdx,
- EventNameSet, Halted, PinnedCondition, PinnedRun, RecordOutcome, RecordStats, ScanVolume,
- ScannedChunk, SeedDomain, SeedTile, UtcMillis,
+ conditions_active_on, diff_tiles, ActiveConditions, AggregateError, BlobSource, CancelCause,
+ ChunkAccumulator, ChunkDomainError, ChunkProjection, ChunkSpec, ClaimedChunk,
+ ConditionAnalyses, DayIdx, EventNameSet, Halted, PinnedCondition, PinnedRun, RecordOutcome,
+ RecordStats, ScanVolume, ScannedChunk, SeedDomain, SeedTile, TileDiff, UtcMillis,
};
use crate::observability::metrics::{
team_label, MetricTimer, AGGREGATE_ENTRIES, CHUNKS_PROJECTED, CHUNKS_VACUOUS,
CHUNK_SCAN_DURATION_SECONDS, CONDITIONS_EVALUATED, EVENTS_SKIPPED, HOGVM_ERRORS,
- PROJECTION_KEYS, ROWS_SCANNED,
+ PROJECTION_KEYS, ROWS_SCANNED, SHADOW_COMPARE, SHADOW_COMPARE_DURATION_SECONDS,
+ SHADOW_COMPARE_LEGACY_SKIPPED,
};
#[derive(Clone)]
@@ -40,11 +41,22 @@ pub struct ChunkScanner {
/// admission decision from it — discovery already did, and re-deciding here would give one
/// chunk a second, quieter place to be dropped.
allowlist: TeamAllowlist,
+ /// `SEEDER_SCAN_SHADOW_COMPARE`: re-scan each chunk wide and diff the tiles. On by default and
+ /// diagnostic only — the projected arm's tiles are what the chunk returns either way.
+ ///
+ /// While it is on, a chunk's projected tiles stay live as the legacy aggregate is built, so
+ /// peak scan memory roughly doubles. A `SEEDER_BANDS_PER_DAY` sized against an observed
+ /// `seeder_aggregate_entries` has about half the headroom it had.
+ shadow_compare: bool,
}
impl ChunkScanner {
- pub fn new(client: clickhouse::Client, allowlist: TeamAllowlist) -> Self {
- Self { client, allowlist }
+ pub fn new(client: clickhouse::Client, allowlist: TeamAllowlist, shadow_compare: bool) -> Self {
+ Self {
+ client,
+ allowlist,
+ shadow_compare,
+ }
}
/// `analyses` is the run's, not the chunk's: it is a pure function of the pinned bytecode, so
@@ -97,7 +109,7 @@ impl ChunkScanner {
lease_cancel: &CancellationToken,
shutdown: &CancellationToken,
) -> Result<(Vec<SeedTile>, ScanVolume), ScanHalt> {
- let _timer = MetricTimer::start(CHUNK_SCAN_DURATION_SECONDS);
+ let timer = MetricTimer::start(CHUNK_SCAN_DURATION_SECONDS);
let spec = chunk.spec();
let domain = run.domain_for(&spec).map_err(ScanError::from)?;
let active = active_conditions_at(spec.day, run.tz, now_ms, &run.conditions);
@@ -121,41 +133,203 @@ impl ChunkScanner {
let projection = analyses.projection(&active);
self.record_projection(run.team_id, &projection);
- let mut cursor = self
- .client
- .query(&scan_sql(&scan_spec, &projection))
- .with_option(
- LOG_COMMENT_OPTION,
+ let (tiles, volume, projected_fold) = self
+ .scan_once(
+ spec,
+ run,
+ &domain,
+ &active,
+ &scan_spec,
+ &projection,
+ ScanKind::Behavioral,
ScanLogComment::BehavioralChunk {
spec,
cohort_id: run.sole_cohort_id(),
- }
- .to_string(),
+ },
+ lease_cancel,
+ shutdown,
)
+ .await?;
+ // Closed before the diagnostic arm, which must not lengthen the chunk's reported scan.
+ drop(timer);
+
+ if self.shadow_compare {
+ match CompareSkip::of(&projection, projected_fold) {
+ Some(skip) => {
+ let team = team_label(&self.allowlist, run.team_id);
+ counter!(SHADOW_COMPARE, "result" => skip.as_str(), "team_id" => team)
+ .increment(1);
+ }
+ None => {
+ self.compare_scan(
+ spec,
+ run,
+ &domain,
+ &active,
+ &scan_spec,
+ &tiles,
+ projected_fold,
+ lease_cancel,
+ shutdown,
+ )
+ .await?;
+ }
+ }
+ }
+ Ok((tiles, volume))
+ }
+
+ /// One rendering of this chunk's scan: build the cursor from [`scan_sql`], fold it through a
+ /// fresh accumulator, meter the moved bytes under `kind`, and return the sorted tiles.
+ ///
+ /// `kind` and `comment` co-vary at the two call sites. The per-row and per-chunk fold metrics
+ /// are emitted for the authoritative [`ScanKind::Behavioral`] arm only, so a diagnostic
+ /// re-scan of the same rows never doubles a throughput series.
+ #[allow(clippy::too_many_arguments)]
+ async fn scan_once(
+ &self,
+ spec: ChunkSpec,
+ run: &PinnedRun,
+ domain: &SeedDomain,
+ active: &ActiveConditions,
+ scan_spec: &ScanSpec,
+ projection: &ChunkProjection,
+ kind: ScanKind,
+ comment: ScanLogComment,
+ lease_cancel: &CancellationToken,
+ shutdown: &CancellationToken,
+ ) -> Result<(Vec<SeedTile>, ScanVolume, FoldSummary), ScanHalt> {
+ let mut cursor = self
+ .client
+ .query(&scan_sql(scan_spec, projection))
+ .with_option(LOG_COMMENT_OPTION, comment.to_string())
.fetch::<EventRow>()
.map_err(ScanError::Query)?;
let mut accumulator =
- ChunkAccumulator::new(run.team_id, &run.filters, &active).map_err(ScanError::from)?;
+ ChunkAccumulator::new(run.team_id, &run.filters, active).map_err(ScanError::from)?;
// 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,
+ domain,
run.team_id,
+ kind,
lease_cancel,
shutdown,
)
.await;
- let volume = scan_volume::observe(ScanKind::Behavioral, &cursor);
- if folded? == RowsSeen::None {
- counter!(CHUNKS_VACUOUS, "reason" => "no_rows").increment(1);
+ let volume = scan_volume::observe(kind, &cursor);
+ let summary = folded?;
+ if kind == ScanKind::Behavioral {
+ if summary.rows == RowsSeen::None {
+ counter!(CHUNKS_VACUOUS, "reason" => "no_rows").increment(1);
+ }
+ histogram!(AGGREGATE_ENTRIES).record(accumulator.entry_count() as f64);
}
+ Ok((
+ accumulator.into_tiles(domain, run.run_id, spec.lease.epoch()),
+ volume,
+ summary,
+ ))
+ }
- histogram!(AGGREGATE_ENTRIES).record(accumulator.entry_count() as f64);
- let tiles = accumulator.into_tiles(&domain, run.run_id, spec.lease.epoch());
- Ok((tiles, volume))
+ /// The diagnostic arm: re-scan the same chunk wide, diff the two tile vectors, meter the
+ /// verdict, and drop the legacy tiles. Called only for a chunk whose authoritative scan
+ /// narrowed, since a wide one would be compared against itself.
+ ///
+ /// A scan *failure* here is metered and swallowed: the diagnostic never fails a chunk. A
+ /// *cancellation* propagates and is then handled exactly as one raised during the projected
+ /// arm — so a lost lease still spends the attempt, and this arm widens the window in which
+ /// that can happen to a fully computed chunk. Swallowing it is worse: another worker reclaims
+ /// a `scanning` chunk once its lease expires (`store/chunks.rs`), so pressing on would produce
+ /// tiles for a chunk this worker no longer owns, alongside the worker that now does. A
+ /// shutdown must also stay prompt.
+ #[allow(clippy::too_many_arguments)]
+ async fn compare_scan(
+ &self,
+ spec: ChunkSpec,
+ run: &PinnedRun,
+ domain: &SeedDomain,
+ active: &ActiveConditions,
+ scan_spec: &ScanSpec,
+ projected_tiles: &[SeedTile],
+ projected_fold: FoldSummary,
+ lease_cancel: &CancellationToken,
+ shutdown: &CancellationToken,
+ ) -> Result<(), ScanHalt> {
+ let team = team_label(&self.allowlist, run.team_id);
+ // Spans the re-scan, its fold, and the diff. Records on every exit, so a cancelled or
+ // failed compare still reports the time it held the chunk's slot and lease.
+ let _timer = MetricTimer::start(SHADOW_COMPARE_DURATION_SECONDS);
+ let (legacy_tiles, legacy_fold) = match self
+ .scan_once(
+ spec,
+ run,
+ domain,
+ active,
+ scan_spec,
+ &ChunkProjection::FullColumns,
+ ScanKind::BehavioralCompare,
+ ScanLogComment::BehavioralCompareChunk {
+ spec,
+ cohort_id: run.sole_cohort_id(),
+ },
+ lease_cancel,
+ shutdown,
+ )
+ .await
+ {
+ Ok((tiles, _, legacy_fold)) => (tiles, legacy_fold),
+ Err(ScanHalt::Cancelled(cause)) => return Err(ScanHalt::Cancelled(cause)),
+ Err(ScanHalt::Failed(error)) => {
+ counter!(SHADOW_COMPARE, "result" => "error", "team_id" => team.clone())
+ .increment(1);
+ // Debug, not Display: the variant's message names the stage, and only its source
+ // chain carries what ClickHouse actually said.
+ warn!(
+ run_id = %run.run_id.0,
+ team_id = run.team_id.0,
+ chunk = %spec.lease.chunk_id().0,
+ day = spec.day,
+ band = spec.band.band(),
+ error = ?error,
+ "shadow compare scan failed; projected tiles emitted unverified"
+ );
+ return Ok(());
+ }
+ };
+ // The difference, not the wide arm's total: a blob kept whole or rebuilt from keys fails
+ // the same parse on both arms and explains no divergence. Recorded whatever the verdict,
+ // and at zero too, because on a blob the projection emptied this is the only count of
+ // malformed rows anything will ever take.
+ let diff = record_compare(
+ team,
+ projected_tiles,
+ &legacy_tiles,
+ projected_fold,
+ legacy_fold,
+ );
+ if diff.is_match() {
+ return Ok(());
+ }
+ warn!(
+ run_id = %run.run_id.0,
+ team_id = run.team_id.0,
+ chunk = %spec.lease.chunk_id().0,
+ day = spec.day,
+ band = spec.band.band(),
+ missing = diff.missing,
+ extra = diff.extra,
+ count_differs = diff.count_differs,
+ legacy_only_globals_parse_errors = legacy_fold.legacy_only_skips(projected_fold),
+ legacy_globals_parse_errors = legacy_fold.globals_parse_errors,
+ projected_globals_parse_errors = projected_fold.globals_parse_errors,
+ exemplars = ?diff.exemplars,
+ "shadow compare diverged between the projected and legacy scans"
+ );
+ Ok(())
}
/// Publish what this chunk's scan narrowed to, so a team that stops projecting is visible
@@ -191,14 +365,100 @@ fn record_projected_keys(blob: &'static str, source: &BlobSource, team: Arc<str>
histogram!(PROJECTION_KEYS, "blob" => blob, "team_id" => team).record(keys as f64);
}
+/// Why a chunk's compare is not worth issuing, when it is not. Each case would spend a second
+/// full-width ClickHouse query on a diff that can only agree, and the second query's right side is
+/// an unbounded `person_distinct_id_overrides` aggregate over the whole team.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum CompareSkip {
+ /// The authoritative scan read no rows. Both arms build their FROM, JOIN and WHERE from the
+ /// same [`ScanSpec`] and vary only in the SELECT list, so the wide arm has nothing to diff and
+ /// nothing to skip. Only the unfenced overrides join could put rows on one side, which is a
+ /// divergence with no projection defect behind it.
+ NoRows,
+ /// The authoritative scan was already wide, so `scan_sql` renders both arms identically and
+ /// the verdict is `match` by construction.
+ NotProjected,
+}
+
+impl CompareSkip {
+ /// `None` when the compare is worth running.
+ fn of(projection: &ChunkProjection, fold: FoldSummary) -> Option<Self> {
+ match (fold.rows, projection) {
+ (RowsSeen::None, _) => Some(Self::NoRows),
+ (RowsSeen::Some, ChunkProjection::FullColumns) => Some(Self::NotProjected),
+ (RowsSeen::Some, ChunkProjection::Projected(_)) => None,
+ }
+ }
+
+ const fn as_str(self) -> &'static str {
+ match self {
+ Self::NoRows => "no_rows",
+ Self::NotProjected => "not_projected",
+ }
+ }
+}
+
+/// Publish a chunk's compare verdict and the skips only its wide arm took, and hand back the diff
+/// the caller logs. Free-standing because [`ChunkScanner::compare_scan`] needs a ClickHouse cursor
+/// and this needs two tile vectors, which is what lets the verdict the backfill gate reads be
+/// tested at all.
+fn record_compare(
+ team: Arc<str>,
+ projected_tiles: &[SeedTile],
+ legacy_tiles: &[SeedTile],
+ projected_fold: FoldSummary,
+ legacy_fold: FoldSummary,
+) -> TileDiff {
+ counter!(SHADOW_COMPARE_LEGACY_SKIPPED, "team_id" => team.clone())
+ .increment(legacy_fold.legacy_only_skips(projected_fold));
+ let diff = diff_tiles(projected_tiles, legacy_tiles);
+ let result = if diff.is_match() { "match" } else { "diff" };
+ counter!(SHADOW_COMPARE, "result" => result, "team_id" => team).increment(1);
+ diff
+}
+
/// 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)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
enum RowsSeen {
+ #[default]
None,
Some,
}
+/// What a fold observed beyond the metrics it emitted.
+///
+/// `globals_parse_errors` is counted on every arm, metered or not. The two arms only treat a row
+/// differently where the projection emptied a blob, so it is the difference between the arms'
+/// counts that explains a divergence, never either count alone.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+struct FoldSummary {
+ rows: RowsSeen,
+ globals_parse_errors: u64,
+}
+
+impl FoldSummary {
+ /// Count the outcomes the two arms can disagree on, which is the malformed-blob skip alone:
+ /// both read the same rows with the same timestamps, and only the wide arm parses a blob the
+ /// projection replaced with an empty literal.
+ fn observe(&mut self, outcome: ScanEventOutcome) {
+ if outcome == ScanEventOutcome::Skipped(ScanSkipReason::GlobalsParseError) {
+ self.globals_parse_errors += 1;
+ }
+ }
+
+ /// Rows only this wide fold skipped, against the projected fold of the same chunk. A blob the
+ /// projection kept whole or rebuilt from keys fails the same parse on both arms, so the wide
+ /// arm's own total explains nothing; the difference does.
+ ///
+ /// Saturating, because the arms resolve identity independently: an override landing between
+ /// them can move a malformed row out of the scanned band and put the projected count ahead.
+ fn legacy_only_skips(self, projected: Self) -> u64 {
+ self.globals_parse_errors
+ .saturating_sub(projected.globals_parse_errors)
+ }
+}
+
/// 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(
@@ -206,10 +466,12 @@ async fn fold_cursor(
accumulator: &mut ChunkAccumulator,
domain: &SeedDomain,
team_id: TeamId,
+ kind: ScanKind,
lease_cancel: &CancellationToken,
shutdown: &CancellationToken,
-) -> Result<RowsSeen, ScanHalt> {
- let mut rows_seen = RowsSeen::None;
+) -> Result<FoldSummary, ScanHalt> {
+ let metered = kind == ScanKind::Behavioral;
+ let mut summary = FoldSummary::default();
loop {
let row = tokio::select! {
biased;
@@ -218,16 +480,23 @@ async fn fold_cursor(
row = cursor.next() => row.map_err(ScanError::Cursor)?,
};
let Some(row) = row else {
- return Ok(rows_seen);
+ return Ok(summary);
};
- 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);
+ summary.rows = RowsSeen::Some;
+ // The per-row series describe the authoritative scan. A diagnostic re-scan walks the same
+ // rows, so counting them again would double every reading a dashboard takes off these.
+ if metered {
+ counter!(ROWS_SCANNED).increment(1);
+ }
+ let outcome =
+ fold_event(domain, accumulator, row_to_event(team_id, row)).map_err(ScanError::from)?;
+ summary.observe(outcome);
+ if metered {
+ match outcome {
+ ScanEventOutcome::Evaluated(stats) => record_evaluation(stats),
+ ScanEventOutcome::Skipped(reason) => {
+ counter!(EVENTS_SKIPPED, "reason" => reason.as_str()).increment(1);
+ }
}
}
}
@@ -306,15 +575,24 @@ enum ScanEventOutcome {
Skipped(ScanSkipReason),
}
+/// Why a scanned row produced no evaluation. The closed `reason` vocabulary on
+/// `seeder_events_skipped_total`, which is why [`ScanSkipReason::ALL`] exists: a validation run
+/// gated on `globals_parse_error` staying at zero needs the series present before it reads it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum ScanSkipReason {
+pub enum ScanSkipReason {
TimestampParse,
DayMismatch,
GlobalsParseError,
}
impl ScanSkipReason {
- const fn as_str(self) -> &'static str {
+ pub const ALL: [Self; 3] = [
+ Self::TimestampParse,
+ Self::DayMismatch,
+ Self::GlobalsParseError,
+ ];
+
+ pub const fn as_str(self) -> &'static str {
match self {
Self::TimestampParse => "timestamp_parse",
Self::DayMismatch => "day_mismatch",
@@ -362,6 +640,7 @@ mod tests {
use uuid::Uuid;
use std::collections::BTreeSet;
+ use std::num::NonZeroU32;
use super::*;
use crate::domain::{
@@ -484,6 +763,7 @@ mod tests {
let scanner = ChunkScanner::new(
clickhouse::Client::default(),
TeamAllowlist::Only(std::collections::HashSet::from([2])),
+ false,
);
let recorder = metrics_exporter_prometheus::PrometheusBuilder::new().build_recorder();
let handle = recorder.handle();
@@ -540,6 +820,142 @@ mod tests {
}
}
+ /// The one number that separates a projection defect from the malformed-blob over-count
+ /// `sql::render_blob` documents, and the only reading a fully-`Empty` projection can ever
+ /// produce. It has to count the globals skip and nothing else.
+ #[test]
+ fn the_fold_summary_tallies_malformed_blobs_and_no_other_outcome() {
+ let mut summary = FoldSummary::default();
+ for outcome in [
+ ScanEventOutcome::Evaluated(RecordStats::default()),
+ ScanEventOutcome::Skipped(ScanSkipReason::TimestampParse),
+ ScanEventOutcome::Skipped(ScanSkipReason::DayMismatch),
+ ] {
+ summary.observe(outcome);
+ }
+ assert_eq!(summary.globals_parse_errors, 0);
+
+ summary.observe(ScanEventOutcome::Skipped(ScanSkipReason::GlobalsParseError));
+ summary.observe(ScanEventOutcome::Skipped(ScanSkipReason::GlobalsParseError));
+ assert_eq!(summary.globals_parse_errors, 2);
+ }
+
+ /// Publishing the wide arm's own total would attribute every shared parse failure to the
+ /// projection, which is the misreading the counter exists to prevent.
+ #[test]
+ fn only_the_skips_the_projection_caused_reach_the_compare_counter() {
+ let fold = |globals_parse_errors| FoldSummary {
+ rows: RowsSeen::Some,
+ globals_parse_errors,
+ };
+ // A blob kept whole or rebuilt from keys fails on both arms and explains no divergence.
+ assert_eq!(fold(7).legacy_only_skips(fold(7)), 0);
+ assert_eq!(fold(9).legacy_only_skips(fold(4)), 5);
+ // Override drift can put the projected arm ahead; the count floors instead of wrapping.
+ assert_eq!(fold(2).legacy_only_skips(fold(5)), 0);
+ }
+
+ fn tile(person: u128, count: u32) -> SeedTile {
+ SeedTile::new(
+ TeamId(2),
+ Uuid::from_u128(person),
+ ConditionHash::parse(HASH).unwrap(),
+ NonZeroU32::new(count).expect("a tile's count is non-zero by construction"),
+ 20_000,
+ SChunkMs(1),
+ RunId(Uuid::nil()),
+ ClaimEpoch(1),
+ )
+ }
+
+ fn fold(rows: RowsSeen, globals_parse_errors: u64) -> FoldSummary {
+ FoldSummary {
+ rows,
+ globals_parse_errors,
+ }
+ }
+
+ /// Each skip removes a full-width ClickHouse query. Issuing one anyway is invisible in the
+ /// output, since both arms agree on exactly these chunks, so nothing but this test says the
+ /// gate still holds.
+ #[test]
+ fn the_compare_is_issued_only_where_the_two_arms_can_disagree() {
+ let projected = ChunkProjection::Projected(ColumnPlan::full());
+ let cases = [
+ (
+ fold(RowsSeen::None, 0),
+ &projected,
+ Some(CompareSkip::NoRows),
+ ),
+ (
+ fold(RowsSeen::None, 0),
+ &ChunkProjection::FullColumns,
+ Some(CompareSkip::NoRows),
+ ),
+ (
+ fold(RowsSeen::Some, 0),
+ &ChunkProjection::FullColumns,
+ Some(CompareSkip::NotProjected),
+ ),
+ (fold(RowsSeen::Some, 0), &projected, None),
+ ];
+ for (summary, projection, expected) in cases {
+ assert_eq!(
+ CompareSkip::of(projection, summary),
+ expected,
+ "{summary:?} on {}",
+ projection.outcome()
+ );
+ }
+ }
+
+ /// The verdict the backfill gate reads. A change that inverts the match/diff choice, or drops
+ /// the skip increment, produces a clean-looking signal from a run that diverged, on a rebuild
+ /// no later run corrects.
+ #[test]
+ fn the_compare_verdict_and_the_skips_only_the_wide_arm_took_reach_prometheus() {
+ let recorder = metrics_exporter_prometheus::PrometheusBuilder::new().build_recorder();
+ let handle = recorder.handle();
+ metrics::with_local_recorder(&recorder, || {
+ let agreed = record_compare(
+ Arc::from("2"),
+ &[tile(1, 3)],
+ &[tile(1, 3)],
+ fold(RowsSeen::Some, 4),
+ fold(RowsSeen::Some, 9),
+ );
+ assert!(agreed.is_match());
+ let diverged = record_compare(
+ Arc::from("3"),
+ &[tile(1, 3)],
+ &[tile(1, 5)],
+ fold(RowsSeen::Some, 0),
+ fold(RowsSeen::Some, 0),
+ );
+ assert_eq!(diverged.count_differs, 1);
+ });
+ let rendered = handle.render();
+
+ // Each verdict is pinned to the team whose arms produced it. One shared label would let a
+ // swapped match/diff choice render the very same two series.
+ for (team, verdict) in [("2", "match"), ("3", "diff")] {
+ assert!(
+ rendered.contains(&format!(
+ "{SHADOW_COMPARE}{{result=\"{verdict}\",team_id=\"{team}\"}} 1"
+ )),
+ "team {team} did not publish {verdict}:\n{rendered}"
+ );
+ }
+ // 9 wide skips against 4 projected ones: only the 5 the projection caused are published,
+ // and the second call adds nothing, which is the "at zero as well" claim.
+ assert!(
+ rendered.contains(&format!(
+ "{SHADOW_COMPARE_LEGACY_SKIPPED}{{team_id=\"2\"}} 5"
+ )),
+ "the published skip count is not the difference between the arms:\n{rendered}"
+ );
+ }
+
#[test]
fn scan_time_rechecks_sliding_conditions_against_the_current_day() {
let hash = ConditionHash::parse(HASH).unwrap();
diff --git a/rust/cohort-seeder/src/config.rs b/rust/cohort-seeder/src/config.rs
index 30112e5fe7a1..e4dca1e4907c 100644
--- a/rust/cohort-seeder/src/config.rs
+++ b/rust/cohort-seeder/src/config.rs
@@ -257,6 +257,18 @@ pub struct Config {
#[envconfig(default = "true")]
pub seeder_person_emit_nonmatchers: bool,
+ /// Run the legacy wide scan alongside the projected scan and diff the resulting tiles.
+ ///
+ /// On by default, because taking this measurement is the only reason the layer exists and a
+ /// run that silently skipped it reads exactly like a clean one. Nothing downstream depends on
+ /// it either way: the projected arm's tiles are what a chunk emits regardless.
+ ///
+ /// Turn it off in charts to finish a long reseed at full speed once the measurement is in
+ /// hand, then delete the layer. While it is on a chunk pays its projected scan plus a full
+ /// wide one.
+ #[envconfig(default = "true")]
+ pub seeder_scan_shadow_compare: bool,
+
#[envconfig(default = "14400")]
pub seeder_ch_max_execution_time_secs: u64,
@@ -444,6 +456,15 @@ mod tests {
assert!(config.clickhouse_ca.is_empty());
}
+ /// A default of off would make the validation run a silent no-op: the compare emits nothing,
+ /// so its counters are absent rather than zero, and an unmeasured run is indistinguishable
+ /// from a clean one. The measurement is the whole point of the layer, so it is what a pod does
+ /// unless an operator says otherwise.
+ #[test]
+ fn the_shadow_compare_runs_unless_an_operator_turns_it_off() {
+ assert!(default_config().seeder_scan_shadow_compare);
+ }
+
#[test]
fn service_limits_reject_disabled_tile_rate() {
let mut config = default_config();
diff --git a/rust/cohort-seeder/src/domain/aggregate.rs b/rust/cohort-seeder/src/domain/aggregate.rs
index fbf1601102a7..d738a6b544c8 100644
--- a/rust/cohort-seeder/src/domain/aggregate.rs
+++ b/rust/cohort-seeder/src/domain/aggregate.rs
@@ -381,6 +381,33 @@ mod tests {
assert_eq!(tiles[1].count(), 1);
}
+ /// The seeder's shadow compare merges two of these vectors on `(person, condition)`, so this
+ /// sort is a contract rather than an ordering convenience: reorder it and the merge pairs
+ /// unrelated tiles, reporting byte-identical scans as thousands of divergences.
+ #[test]
+ fn tiles_come_out_sorted_by_person_then_condition() {
+ let filters = filters();
+ let active = active();
+ let mut accumulator = ChunkAccumulator::new(TeamId(2), &filters, &active).unwrap();
+ for person in [2, 1] {
+ for event_name in ["b", "a"] {
+ accumulator
+ .record_event(&event(Uuid::from_u128(person), event_name))
+ .unwrap();
+ }
+ }
+
+ let tiles = accumulator.into_tiles(&domain(), RunId(Uuid::nil()), ClaimEpoch(1));
+ assert_eq!(tiles.len(), 4);
+ assert!(
+ tiles
+ .windows(2)
+ .all(|pair| (pair[0].person_id(), pair[0].condition_hash())
+ < (pair[1].person_id(), pair[1].condition_hash())),
+ "tiles are not in merge order: {tiles:?}"
+ );
+ }
+
#[test]
fn record_outcome_separates_false_unknown_function_and_vm_error() {
let filters = outcome_filters();
diff --git a/rust/cohort-seeder/src/domain/compare.rs b/rust/cohort-seeder/src/domain/compare.rs
new file mode 100644
index 000000000000..8a3fb2b1a108
--- /dev/null
+++ b/rust/cohort-seeder/src/domain/compare.rs
@@ -0,0 +1,359 @@
+//! The shadow compare's tile diff: a sorted-merge over two scans' tile vectors, pure and
+//! deletable with the compare layer. Depends on `aggregate`'s output shape only.
+
+use std::cmp::Ordering;
+use std::fmt;
+
+use cohort_core::seed::SeedTile;
+use uuid::Uuid;
+
+use super::ids::ConditionHash;
+
+/// Cap on retained exemplars, counted per class: enough to characterize one, small enough to log.
+///
+/// Per class rather than shared, because a shared cap fills in merge order and can silence a whole
+/// class. Every class needs its own examples to be triaged at all, and the one that appears once is
+/// as likely to be the informative one as the one that appears ten thousand times.
+pub const MAX_EXEMPLARS_PER_CLASS: usize = 8;
+
+/// Which arm produced a divergent pair, and so which of the three totals counts it.
+///
+/// The classes describe one pair each. None of them is benign on its own: [`TileDiff::is_match`]
+/// rejects all three, so any of them raises `result="diff"`. Nor does a cause map onto a class —
+/// a row the wide arm skipped for a malformed blob lands in `Extra` when the pair has no other
+/// matching row in the chunk, in `CountDiffers` when it has one, and nowhere at all when the row
+/// matches no condition. Read the class as a shape and the skip counters as the cause.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum DivergenceClass {
+ /// The legacy arm produced the pair and the projected arm did not.
+ Missing,
+ /// The projected arm produced the pair and the legacy arm did not.
+ Extra,
+ /// Both arms produced the pair with different counts.
+ CountDiffers,
+}
+
+impl DivergenceClass {
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::Missing => "missing",
+ Self::Extra => "extra",
+ Self::CountDiffers => "count_differs",
+ }
+ }
+}
+
+/// One `(person, condition)` pair the two arms disagree on. A `0` count means that arm
+/// produced no tile for the pair.
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub struct Divergence {
+ pub class: DivergenceClass,
+ pub person: Uuid,
+ pub hash: ConditionHash,
+ pub projected: u32,
+ pub legacy: u32,
+}
+
+/// Hand-written because this is what an operator reads out of the divergence log, and
+/// [`ConditionHash`]'s derived `Debug` renders its sixteen bytes as decimal integers — a form
+/// nobody can grep for or paste into the chunk ledger. Its `Display` is the ASCII hash.
+impl fmt::Debug for Divergence {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(
+ formatter,
+ "{} person={} hash={} projected={} legacy={}",
+ self.class.as_str(),
+ self.person,
+ self.hash,
+ self.projected,
+ self.legacy
+ )
+ }
+}
+
+/// Per-class totals plus at most [`MAX_EXEMPLARS_PER_CLASS`] exemplars of each, in
+/// `(person, hash)` order.
+#[derive(Debug, Default, PartialEq, Eq)]
+pub struct TileDiff {
+ /// Pairs the legacy arm produced and the projected arm did not.
+ pub missing: u64,
+ /// Pairs the projected arm produced and the legacy arm did not.
+ pub extra: u64,
+ pub count_differs: u64,
+ pub exemplars: Vec<Divergence>,
+}
+
+impl TileDiff {
+ pub fn is_match(&self) -> bool {
+ self.missing == 0 && self.extra == 0 && self.count_differs == 0
+ }
+
+ fn only_in_projected(&mut self, tile: &SeedTile) {
+ self.extra += 1;
+ self.keep(divergence(DivergenceClass::Extra, tile, tile.count(), 0));
+ }
+
+ fn only_in_legacy(&mut self, tile: &SeedTile) {
+ self.missing += 1;
+ self.keep(divergence(DivergenceClass::Missing, tile, 0, tile.count()));
+ }
+
+ fn counts_differ(&mut self, projected: &SeedTile, legacy: &SeedTile) {
+ self.count_differs += 1;
+ self.keep(divergence(
+ DivergenceClass::CountDiffers,
+ projected,
+ projected.count(),
+ legacy.count(),
+ ));
+ }
+
+ /// The totals are exact whatever the cap does, so a chunk that diverged thousands of times
+ /// still reports how many — the exemplars only have to characterize each class's shape.
+ fn keep(&mut self, divergence: Divergence) {
+ let kept = self
+ .exemplars
+ .iter()
+ .filter(|other| other.class == divergence.class)
+ .count();
+ if kept < MAX_EXEMPLARS_PER_CLASS {
+ self.exemplars.push(divergence);
+ }
+ }
+}
+
+/// Diff two tile vectors from the same chunk scanned twice. Both inputs are `into_tiles`
+/// outputs, sorted by `(person_id, condition_hash)` by construction.
+///
+/// Every field the two arms build from shared arguments is identical, which leaves the count. The
+/// key is the exception: `person_id` comes from the unfenced `person_distinct_id_overrides` join,
+/// so a merge landing between the arms re-keys a row and shows up here as a paired `Missing` and
+/// `Extra` for one condition under two persons. That pair is override drift, not a projection
+/// defect, and it does not reproduce on a re-scan.
+pub fn diff_tiles(projected: &[SeedTile], legacy: &[SeedTile]) -> TileDiff {
+ let mut diff = TileDiff::default();
+ let (mut left, mut right) = (0, 0);
+ loop {
+ match (projected.get(left), legacy.get(right)) {
+ (None, None) => return diff,
+ (Some(tile), None) => {
+ diff.only_in_projected(tile);
+ left += 1;
+ }
+ (None, Some(tile)) => {
+ diff.only_in_legacy(tile);
+ right += 1;
+ }
+ (Some(projected_tile), Some(legacy_tile)) => {
+ match key(projected_tile).cmp(&key(legacy_tile)) {
+ Ordering::Less => {
+ diff.only_in_projected(projected_tile);
+ left += 1;
+ }
+ Ordering::Greater => {
+ diff.only_in_legacy(legacy_tile);
+ right += 1;
+ }
+ Ordering::Equal => {
+ if projected_tile.count() != legacy_tile.count() {
+ diff.counts_differ(projected_tile, legacy_tile);
+ }
+ left += 1;
+ right += 1;
+ }
+ }
+ }
+ }
+ }
+}
+
+/// The merge key, which is also `into_tiles`' sort key — the whole merge is only correct while the
+/// two agree, which `aggregate`'s own tests pin.
+fn key(tile: &SeedTile) -> (Uuid, ConditionHash) {
+ (tile.person_id(), tile.condition_hash())
+}
+
+fn divergence(class: DivergenceClass, tile: &SeedTile, projected: u32, legacy: u32) -> Divergence {
+ Divergence {
+ class,
+ person: tile.person_id(),
+ hash: tile.condition_hash(),
+ projected,
+ legacy,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::num::NonZeroU32;
+
+ use cohort_core::filters::TeamId;
+
+ use super::*;
+ use crate::domain::{ClaimEpoch, RunId, SChunkMs};
+
+ const HASH_A: &str = "aaaaaaaaaaaaaaaa";
+ const HASH_B: &str = "bbbbbbbbbbbbbbbb";
+ const HASH_C: &str = "cccccccccccccccc";
+
+ /// Every field but the key and the count is built from arguments both arms share, so the
+ /// builder fixes them: a difference the diff reported in one of them would be a bug in the
+ /// test, not a finding.
+ fn tile(person: u128, hash: &str, count: u32) -> SeedTile {
+ SeedTile::new(
+ TeamId(2),
+ Uuid::from_u128(person),
+ ConditionHash::parse(hash).unwrap(),
+ NonZeroU32::new(count).expect("a tile's count is non-zero by construction"),
+ 20_000,
+ SChunkMs(1_700_000_000_000),
+ RunId(Uuid::nil()),
+ ClaimEpoch(1),
+ )
+ }
+
+ fn exemplar(
+ class: DivergenceClass,
+ person: u128,
+ hash: &str,
+ counts: (u32, u32),
+ ) -> Divergence {
+ Divergence {
+ class,
+ person: Uuid::from_u128(person),
+ hash: ConditionHash::parse(hash).unwrap(),
+ projected: counts.0,
+ legacy: counts.1,
+ }
+ }
+
+ #[test]
+ fn arms_that_agree_report_a_match_and_no_exemplars() {
+ for (projected, legacy) in [
+ (Vec::new(), Vec::new()),
+ (
+ vec![tile(1, HASH_A, 2), tile(1, HASH_B, 1), tile(2, HASH_A, 7)],
+ vec![tile(1, HASH_A, 2), tile(1, HASH_B, 1), tile(2, HASH_A, 7)],
+ ),
+ ] {
+ let diff = diff_tiles(&projected, &legacy);
+ assert!(diff.is_match(), "{diff:?}");
+ assert_eq!(diff.exemplars, Vec::new());
+ }
+ }
+
+ /// The tail case is the merge's classic bug: once the projected side is exhausted, the rest of
+ /// the legacy side must still be walked rather than dropped.
+ #[test]
+ fn legacy_only_pairs_at_head_middle_and_tail_are_missing() {
+ let projected = [tile(1, HASH_B, 1), tile(2, HASH_A, 1)];
+ let legacy = [
+ tile(1, HASH_A, 4),
+ tile(1, HASH_B, 1),
+ tile(1, HASH_C, 5),
+ tile(2, HASH_A, 1),
+ tile(3, HASH_A, 6),
+ ];
+ let diff = diff_tiles(&projected, &legacy);
+ assert!(!diff.is_match());
+ assert_eq!((diff.missing, diff.extra, diff.count_differs), (3, 0, 0));
+ assert_eq!(
+ diff.exemplars,
+ vec![
+ exemplar(DivergenceClass::Missing, 1, HASH_A, (0, 4)),
+ exemplar(DivergenceClass::Missing, 1, HASH_C, (0, 5)),
+ exemplar(DivergenceClass::Missing, 3, HASH_A, (0, 6)),
+ ]
+ );
+ }
+
+ #[test]
+ fn projected_only_pairs_are_extra() {
+ let projected = [tile(1, HASH_A, 3), tile(1, HASH_B, 1), tile(2, HASH_A, 9)];
+ let legacy = [tile(1, HASH_B, 1)];
+ let diff = diff_tiles(&projected, &legacy);
+ assert!(!diff.is_match());
+ assert_eq!((diff.missing, diff.extra, diff.count_differs), (0, 2, 0));
+ assert_eq!(
+ diff.exemplars,
+ vec![
+ exemplar(DivergenceClass::Extra, 1, HASH_A, (3, 0)),
+ exemplar(DivergenceClass::Extra, 2, HASH_A, (9, 0)),
+ ]
+ );
+ }
+
+ #[test]
+ fn a_shared_pair_with_unequal_counts_carries_both_readings() {
+ let diff = diff_tiles(&[tile(1, HASH_A, 3)], &[tile(1, HASH_A, 5)]);
+ assert!(!diff.is_match());
+ assert_eq!((diff.missing, diff.extra, diff.count_differs), (0, 0, 1));
+ assert_eq!(
+ diff.exemplars,
+ vec![exemplar(DivergenceClass::CountDiffers, 1, HASH_A, (3, 5))]
+ );
+ }
+
+ /// A merge keyed on the person alone would pair person 1's `HASH_C` with its `HASH_B` and call
+ /// it a count difference, hiding one lost pair and one gained one behind a single class.
+ #[test]
+ fn the_merge_advances_on_the_hash_within_one_person() {
+ let projected = [tile(1, HASH_A, 1), tile(1, HASH_C, 2), tile(2, HASH_B, 1)];
+ let legacy = [tile(1, HASH_A, 1), tile(1, HASH_B, 4), tile(2, HASH_B, 1)];
+ let diff = diff_tiles(&projected, &legacy);
+ assert_eq!((diff.missing, diff.extra, diff.count_differs), (1, 1, 0));
+ assert_eq!(
+ diff.exemplars,
+ vec![
+ exemplar(DivergenceClass::Missing, 1, HASH_B, (0, 4)),
+ exemplar(DivergenceClass::Extra, 1, HASH_C, (2, 0)),
+ ]
+ );
+ }
+
+ /// The alarming class arrives last here, behind more benign ones than a shared cap would hold.
+ #[test]
+ fn the_exemplar_cap_keeps_every_class_and_leaves_the_totals_exact() {
+ let over = MAX_EXEMPLARS_PER_CLASS + 5;
+ let projected = (1..=over)
+ .map(|person| tile(person as u128, HASH_A, 1))
+ .collect::<Vec<_>>();
+ let legacy = [tile(over as u128 + 1, HASH_A, 4)];
+ let diff = diff_tiles(&projected, &legacy);
+
+ assert_eq!((diff.missing, diff.extra), (1, over as u64));
+ assert_eq!(
+ diff.exemplars
+ .iter()
+ .filter(|d| d.class == DivergenceClass::Extra)
+ .count(),
+ MAX_EXEMPLARS_PER_CLASS
+ );
+ assert_eq!(
+ diff.exemplars
+ .iter()
+ .filter(|d| d.class == DivergenceClass::Missing)
+ .collect::<Vec<_>>(),
+ vec![&exemplar(
+ DivergenceClass::Missing,
+ over as u128 + 1,
+ HASH_A,
+ (0, 4)
+ )]
+ );
+ }
+
+ /// The log line is the feature's only per-pair output, so its rendering is a contract: a
+ /// derived `Debug` prints the hash as sixteen decimal integers.
+ #[test]
+ fn an_exemplar_renders_its_hash_as_the_ascii_operators_search_for() {
+ assert_eq!(
+ format!(
+ "{:?}",
+ exemplar(DivergenceClass::Missing, 1, HASH_A, (0, 4))
+ ),
+ "missing person=00000000-0000-0000-0000-000000000001 \
+ hash=aaaaaaaaaaaaaaaa projected=0 legacy=4"
+ );
+ }
+}
diff --git a/rust/cohort-seeder/src/domain/mod.rs b/rust/cohort-seeder/src/domain/mod.rs
index 9f1aed65ce08..3d7f0c770c18 100644
--- a/rust/cohort-seeder/src/domain/mod.rs
+++ b/rust/cohort-seeder/src/domain/mod.rs
@@ -10,6 +10,7 @@
pub mod aggregate;
pub mod backoff;
pub mod chunk;
+pub mod compare;
pub mod completion;
pub mod condition;
pub mod condition_analysis;
@@ -35,6 +36,7 @@ pub use cohort_core::seed::{
BehavioralShapeHash, PersonSeed, PersonShapeHash, ReconcileCompleteMarker, ReconcileScope,
ReconcileTile, ScopeKind, SeedTile, ShapeHashError, UnknownScopeKind,
};
+pub use compare::{diff_tiles, Divergence, DivergenceClass, TileDiff, MAX_EXEMPLARS_PER_CLASS};
pub(crate) use completion::MARKER_WATCH_SCHEMA;
pub use completion::{
CommittedOffset, CompletionParts, CompletionPhase, CompletionStatus, DispatchEpoch,
diff --git a/rust/cohort-seeder/src/main.rs b/rust/cohort-seeder/src/main.rs
index 20f62dd40720..1992fa5d00e0 100644
--- a/rust/cohort-seeder/src/main.rs
+++ b/rust/cohort-seeder/src/main.rs
@@ -18,9 +18,9 @@ use tracing_subscriber::{fmt, EnvFilter, Layer};
use cohort_seeder::app::completion::verify_marker_topic;
use cohort_seeder::app::{
- AutoDispatchPolicy, CompletionDriver, KafkaCommittedOffsets, KafkaTopicOffsets,
- MarkerWatchTask, ObservePolicy, OrchestratorSettings, PersonComponents, PgMarkerFlush,
- SeederOrchestrator, WatchDirectives, MARKER_WATCH_LIVENESS_DEADLINE,
+ prime_zero_series, AutoDispatchPolicy, CompletionDriver, KafkaCommittedOffsets,
+ KafkaTopicOffsets, MarkerWatchTask, ObservePolicy, OrchestratorSettings, PersonComponents,
+ PgMarkerFlush, SeederOrchestrator, WatchDirectives, MARKER_WATCH_LIVENESS_DEADLINE,
ORCHESTRATOR_LIVENESS_DEADLINE,
};
use cohort_seeder::clickhouse::client::build_client;
@@ -88,11 +88,16 @@ async fn async_main(config: Config) -> Result<()> {
.then(observability::metrics::install_recorder)
.transpose()
.context("installing Prometheus recorder")?;
+ prime_zero_series();
let pool = get_pool_with_config(&config.database_url, config.pool_config())
.context("creating cohort-seeder PostgreSQL pool")?;
let clickhouse_client = build_client(&config).context("building ClickHouse client")?;
- let scanner = ChunkScanner::new(clickhouse_client.clone(), config.team_allowlist.clone());
+ let scanner = ChunkScanner::new(
+ clickhouse_client.clone(),
+ config.team_allowlist.clone(),
+ config.seeder_scan_shadow_compare,
+ );
let producer = SeedTileProducer::new(
&config.build_kafka_config(),
config.seed_events_topic.clone(),
@@ -319,6 +324,7 @@ fn log_startup(config: &Config) {
persons_per_chunk = config.seeder_persons_per_chunk,
person_max_concurrent_chunks = config.seeder_person_max_concurrent_chunks,
person_emit_nonmatchers = config.seeder_person_emit_nonmatchers,
+ scan_shadow_compare = config.seeder_scan_shadow_compare,
reconcile_auto_dispatch_enabled = config.seeder_reconcile_auto_dispatch_enabled,
confirm_register_backfilled = config.seeder_confirm_register_backfilled,
reconcile_max_concurrent_dispatches = config.seeder_reconcile_max_concurrent_dispatches,
diff --git a/rust/cohort-seeder/src/observability/metrics.rs b/rust/cohort-seeder/src/observability/metrics.rs
index 2488deee6522..958908388543 100644
--- a/rust/cohort-seeder/src/observability/metrics.rs
+++ b/rust/cohort-seeder/src/observability/metrics.rs
@@ -48,6 +48,36 @@ pub const CONDITIONS_UNANALYZABLE: &str = "seeder_conditions_unanalyzable_total"
/// object or escaped the static analysis, so the scan selects every column. A team sitting at
/// `full_columns` is the signal to read the run's census for which event names block it.
pub const CHUNKS_PROJECTED: &str = "seeder_chunks_projected_total";
+/// Shadow-compare verdicts per chunk, labelled by closed `result`
+/// (`match`/`diff`/`error`/`no_rows`/`not_projected`) and `team_id` (counter). Emitted only while
+/// `SEEDER_SCAN_SHADOW_COMPARE` is on, once per chunk that finishes its scan. A chunk cancelled by
+/// shutdown or a lost lease increments nothing and runs again later.
+///
+/// `diff` is the validation failure signal — the paired `warn!` carries the chunk attribution and
+/// exemplars. `error` means the diagnostic wide scan itself failed and the chunk's projected tiles
+/// were emitted unverified.
+///
+/// The last two values are chunks no second query was issued for, because it could only have
+/// agreed: `no_rows` where the authoritative scan read nothing, and `not_projected` where it was
+/// already wide. Neither is evidence about projecting, so read compare coverage as `match` and
+/// `diff` against their sum, not against the chunk count.
+pub const SHADOW_COMPARE: &str = "seeder_shadow_compare_total";
+/// Wall time of one chunk's diagnostic wide re-scan, including its fold and diff (histogram).
+///
+/// The compare arm runs after the authoritative scan on the same task, holding the chunk's worker
+/// slot and lease, and [`CHUNK_SCAN_DURATION_SECONDS`] deliberately closes before it. Without this
+/// series the arm's cost shows up only as slower chunk throughput, with nothing naming the cause —
+/// which is the reading behind the decision to turn the knob off for the rest of a long reseed.
+pub const SHADOW_COMPARE_DURATION_SECONDS: &str = "seeder_shadow_compare_duration_seconds";
+/// Rows only the shadow compare's legacy wide arm refused to build globals for, labelled by
+/// `team_id` (counter). Emitted only while `SEEDER_SCAN_SHADOW_COMPARE` is on, and at zero as well.
+///
+/// The difference between the two arms' skip counts, not the wide arm's total. A blob the
+/// projection keeps whole or rebuilds from keys fails the same parse on both arms and explains no
+/// divergence; only a blob the projection replaced with an empty literal is skipped on one side
+/// and evaluated on the other. That difference is what separates a projection defect from the
+/// over-count `sql::render_blob` documents, which lands in `result="diff"` indistinguishably.
+pub const SHADOW_COMPARE_LEGACY_SKIPPED: &str = "seeder_shadow_compare_legacy_skipped_total";
/// Top-level JSON keys a narrowed scan rebuilds one blob from, labelled by `blob`
/// (`properties`/`person_properties`) and `team_id` (histogram). Zero means the blob is not read at
/// all and the scan selects an empty literal for it.
@@ -272,6 +302,10 @@ const PROJECTION_KEYS_BUCKETS: &[f64] = &[0.0, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 6
const HISTOGRAM_LADDERS: &[(&str, &[f64])] = &[
(PROJECTION_KEYS, PROJECTION_KEYS_BUCKETS),
(CHUNK_SCAN_DURATION_SECONDS, SCAN_DURATION_SECONDS_BUCKETS),
+ (
+ SHADOW_COMPARE_DURATION_SECONDS,
+ SCAN_DURATION_SECONDS_BUCKETS,
+ ),
(
PERSON_CHUNK_SCAN_DURATION_SECONDS,
SCAN_DURATION_SECONDS_BUCKETS,
diff --git a/rust/cohort-seeder/src/store/runs.rs b/rust/cohort-seeder/src/store/runs.rs
index 0a2587589e1e..075217404b1f 100644
--- a/rust/cohort-seeder/src/store/runs.rs
+++ b/rust/cohort-seeder/src/store/runs.rs
@@ -170,6 +170,8 @@ pub enum RunKind {
}
impl RunKind {
+ pub const ALL: [Self; 2] = [Self::Behavioral, Self::PersonProperty];
+
pub const fn as_str(self) -> &'static str {
self.scope().as_str()
}