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(capture-load-gen): verify shadow-mode person parity after a run (#95390)

Zach Brown2bd173dbf031
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index aa52f4dc59ab..ea3a658e4ec0 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2259,16 +2259,20 @@ name = "capture-load-gen"
version = "0.1.0"
dependencies = [
"anyhow",
+ "axum 0.7.9",
"clap",
+ "common-metrics",
"common-types",
"flate2",
"governor",
"hdrhistogram",
"humantime",
+ "metrics",
"rand 0.8.5",
"reqwest 0.12.28",
"serde",
"serde_json",
+ "sqlx",
"tokio",
"tracing",
"tracing-subscriber",
diff --git a/rust/capture-load-gen/Cargo.toml b/rust/capture-load-gen/Cargo.toml
index 2fdb79ea5970..9bb71a34ed62 100644
--- a/rust/capture-load-gen/Cargo.toml
+++ b/rust/capture-load-gen/Cargo.toml
@@ -8,17 +8,21 @@ publish = false
workspace = true
[dependencies]
+common-metrics = { path = "../common/metrics" }
common-types = { path = "../common/types" }
anyhow = { workspace = true }
+axum = { workspace = true }
clap = { workspace = true, features = ["env"] }
flate2 = { workspace = true }
governor = { workspace = true }
hdrhistogram = { workspace = true }
humantime = { workspace = true }
+metrics = { workspace = true }
rand = { workspace = true }
reqwest = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
+sqlx = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
diff --git a/rust/capture-load-gen/src/lib.rs b/rust/capture-load-gen/src/lib.rs
new file mode 100644
index 000000000000..4b402dc73f39
--- /dev/null
+++ b/rust/capture-load-gen/src/lib.rs
@@ -0,0 +1,5 @@
+pub mod client;
+pub mod event;
+pub mod reset;
+pub mod stats;
+pub mod verify;
diff --git a/rust/capture-load-gen/src/main.rs b/rust/capture-load-gen/src/main.rs
index cfffae463b51..868fad7a8784 100644
--- a/rust/capture-load-gen/src/main.rs
+++ b/rust/capture-load-gen/src/main.rs
@@ -1,7 +1,3 @@
-mod client;
-mod event;
-mod stats;
-
use std::num::NonZeroU32;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
@@ -17,9 +13,10 @@ use rand::rngs::StdRng;
use rand::SeedableRng;
use tokio::sync::Notify;
-use crate::client::CaptureClient;
-use crate::event::{BatchPayload, EventFactory};
-use crate::stats::Counters;
+use capture_load_gen::client::CaptureClient;
+use capture_load_gen::event::{BatchPayload, EventFactory};
+use capture_load_gen::stats::{self, Counters};
+use capture_load_gen::{reset, verify};
type Limiter = RateLimiter<NotKeyed, InMemoryState, DefaultClock>;
@@ -108,6 +105,42 @@ struct Cli {
/// Print one sample batch as JSON and exit without sending anything.
#[arg(long)]
dry_run: bool,
+
+ /// After the load, poll until the Postgres and personhog graphs agree on
+ /// the team's person graph, exiting nonzero on a mismatch that outlasts the
+ /// deadline. Only shard 0 verifies; --count 0 verifies without load.
+ #[arg(long)]
+ verify: bool,
+
+ /// Delete the team's person rows from both graphs and exit, so a run
+ /// starts clean. Requires --team-id and --database-url.
+ #[arg(long)]
+ reset_team: bool,
+
+ /// Persons database URL, required by --verify and --reset-team.
+ #[arg(long, env = "DATABASE_URL")]
+ database_url: Option<String>,
+
+ /// How long the graphs get to agree.
+ #[arg(long, value_parser = humantime::parse_duration, default_value = "5m")]
+ verify_timeout: Duration,
+
+ /// The personhog writer's person table.
+ #[arg(long, default_value = "personhog_person_tmp")]
+ tmp_person_table: String,
+
+ /// The personhog writer's distinct-id table.
+ #[arg(long, default_value = "personhog_persondistinctid_tmp")]
+ tmp_pdi_table: String,
+
+ /// The team whose person graph verify compares. Its rows are the run's
+ /// cohort; the workflow wipes them before the load.
+ #[arg(long)]
+ team_id: Option<i64>,
+
+ /// Port serving /metrics and /_liveness while verifying.
+ #[arg(long, default_value_t = 9090)]
+ metrics_port: u16,
}
/// Arcs shared by every worker.
@@ -163,6 +196,18 @@ fn resolve_shard(cli: &Cli) -> Result<(u64, u64)> {
Ok((index, total))
}
+/// (sends load, verifies) for this shard. A zero-share shard still verifies
+/// when it is shard 0, so `--count 0 --verify` checks without sending.
+fn shard_plan(
+ rate_share: Option<u64>,
+ count_share: Option<u64>,
+ verify: bool,
+ index: u64,
+) -> (bool, bool) {
+ let has_load = rate_share.or(count_share).unwrap_or(0) > 0;
+ (has_load, verify && index == 0)
+}
+
/// Claim up to `batch` events from the shared remaining counter (count mode).
fn claim(remaining: &AtomicU64, batch: usize) -> u64 {
let mut cur = remaining.load(Ordering::Relaxed);
@@ -242,6 +287,10 @@ async fn main() -> Result<()> {
)
.init();
+ if cli.reset_team {
+ return reset::reset_team(&reset_config(&cli)?).await;
+ }
+
if cli.batch_size == 0 {
bail!("--batch-size must be > 0");
}
@@ -280,20 +329,6 @@ async fn main() -> Result<()> {
}
let (index, total) = resolve_shard(&cli)?;
- let batch_n = NonZeroU32::new(cli.batch_size as u32).context("batch size too large")?;
-
- let client = Arc::new(CaptureClient::new(
- &cli.endpoint,
- cli.token.clone(),
- !cli.no_gzip,
- Duration::from_secs(cli.timeout_secs),
- )?);
- let counters = Arc::new(Counters::default());
- let shared = Shared {
- client,
- factory,
- counters: counters.clone(),
- };
// Validate mode selection up front.
let duration = match (cli.rate, cli.count) {
@@ -306,66 +341,131 @@ async fn main() -> Result<()> {
(None, None) => bail!("specify either --rate (+ --duration) or --count"),
};
- // Shared mode state.
- let limiter: Option<Arc<Limiter>> = cli.rate.map(|rate| {
- let local_rate = split(u64::from(rate), total, index).max(1) as u32;
- let burst = local_rate.max(cli.batch_size as u32);
- let quota = Quota::per_second(NonZeroU32::new(local_rate).unwrap())
- .allow_burst(NonZeroU32::new(burst).unwrap());
- Arc::new(RateLimiter::direct(quota))
- });
- let remaining: Option<Arc<AtomicU64>> = cli
- .count
- .map(|count| Arc::new(AtomicU64::new(split(count, total, index))));
+ let rate_share = cli.rate.map(|rate| split(u64::from(rate), total, index));
+ let count_share = cli.count.map(|count| split(count, total, index));
+ let (has_load, should_verify) = shard_plan(rate_share, count_share, cli.verify, index);
- // Nothing to do for this shard (e.g. rate < shard count).
- if cli.rate.is_some() && split(u64::from(cli.rate.unwrap()), total, index) == 0 {
- println!("[load] shard {index}/{total} has no work (rate too low to split)");
- return Ok(());
- }
- if let Some(rem) = &remaining {
- if rem.load(Ordering::Relaxed) == 0 {
- println!("[load] shard {index}/{total} has no work (count too low to split)");
- return Ok(());
+ // A missing verify prerequisite must fail here, not after the load.
+ let verify_cfg = if should_verify {
+ Some(verify_config(&cli)?)
+ } else {
+ None
+ };
+
+ if has_load {
+ let batch_n = NonZeroU32::new(cli.batch_size as u32).context("batch size too large")?;
+ let client = Arc::new(CaptureClient::new(
+ &cli.endpoint,
+ cli.token.clone(),
+ !cli.no_gzip,
+ Duration::from_secs(cli.timeout_secs),
+ )?);
+ let counters = Arc::new(Counters::default());
+ let shared = Shared {
+ client,
+ factory,
+ counters: counters.clone(),
+ };
+
+ let limiter: Option<Arc<Limiter>> = rate_share.map(|share| {
+ let local_rate = share as u32;
+ let burst = local_rate.max(cli.batch_size as u32);
+ let quota = Quota::per_second(NonZeroU32::new(local_rate).unwrap())
+ .allow_burst(NonZeroU32::new(burst).unwrap());
+ Arc::new(RateLimiter::direct(quota))
+ });
+ let remaining: Option<Arc<AtomicU64>> =
+ count_share.map(|share| Arc::new(AtomicU64::new(share)));
+
+ let stop = Arc::new(Notify::new());
+ let reporter = tokio::spawn(stats::report_loop(counters.clone(), stop.clone()));
+
+ let started = Instant::now();
+ let deadline = duration.map(|d| tokio::time::Instant::now() + d);
+
+ let mut handles = Vec::with_capacity(cli.concurrency);
+ for _ in 0..cli.concurrency {
+ let mode = match (&limiter, &remaining) {
+ (Some(limiter), _) => Mode::Rate {
+ limiter: limiter.clone(),
+ batch_n,
+ deadline: deadline.expect("rate mode has deadline"),
+ batch_size: cli.batch_size,
+ },
+ (None, Some(remaining)) => Mode::Count {
+ remaining: remaining.clone(),
+ batch_size: cli.batch_size,
+ },
+ (None, None) => unreachable!("mode validated above"),
+ };
+ handles.push(tokio::spawn(run_worker(shared.clone(), mode)));
}
- }
- let stop = Arc::new(Notify::new());
- let reporter = tokio::spawn(stats::report_loop(counters.clone(), stop.clone()));
+ let mut merged = stats::new_histogram();
+ for handle in handles {
+ if let Ok(hist) = handle.await {
+ merged.add(&hist).ok();
+ }
+ }
- let started = Instant::now();
- let deadline = duration.map(|d| tokio::time::Instant::now() + d);
+ stop.notify_one();
+ reporter.await.ok();
- let mut handles = Vec::with_capacity(cli.concurrency);
- for _ in 0..cli.concurrency {
- let mode = match (&limiter, &remaining) {
- (Some(limiter), _) => Mode::Rate {
- limiter: limiter.clone(),
- batch_n,
- deadline: deadline.expect("rate mode has deadline"),
- batch_size: cli.batch_size,
- },
- (None, Some(remaining)) => Mode::Count {
- remaining: remaining.clone(),
- batch_size: cli.batch_size,
- },
- (None, None) => unreachable!("mode validated above"),
- };
- handles.push(tokio::spawn(run_worker(shared.clone(), mode)));
+ stats::print_summary(&counters, &merged, started.elapsed());
+ } else {
+ println!("[load] shard {index}/{total} has no work");
}
- let mut merged = stats::new_histogram();
- for handle in handles {
- if let Ok(hist) = handle.await {
- merged.add(&hist).ok();
+ if let Some(cfg) = verify_cfg {
+ spawn_metrics_server(cli.metrics_port);
+ let verifier = verify::Verifier::connect(&cfg).await?;
+ if !verifier.run(&cfg).await? {
+ bail!("shadow parity verification failed");
}
}
+ Ok(())
+}
- stop.notify_one();
- reporter.await.ok();
+/// Serve /metrics and /_liveness so the verify gauges can be scraped.
+fn spawn_metrics_server(port: u16) {
+ let router = axum::Router::new().route("/_liveness", axum::routing::get(|| async { "ok" }));
+ let router = common_metrics::setup_metrics_routes(router);
+ let bind = format!("0.0.0.0:{port}");
+ tokio::spawn(async move {
+ if let Err(error) = common_metrics::serve(router, &bind).await {
+ tracing::error!(%error, "metrics server failed; verification continues without gauges");
+ }
+ });
+}
- stats::print_summary(&counters, &merged, started.elapsed());
- Ok(())
+/// The verify flags as a config, failing on the one without a default.
+fn verify_config(cli: &Cli) -> Result<verify::VerifyConfig> {
+ let database_url = cli
+ .database_url
+ .clone()
+ .context("--verify requires --database-url or DATABASE_URL")?;
+ let team_id = cli.team_id.context("--verify requires --team-id")?;
+ Ok(verify::VerifyConfig {
+ database_url,
+ team_id,
+ tmp_person_table: cli.tmp_person_table.clone(),
+ tmp_pdi_table: cli.tmp_pdi_table.clone(),
+ deadline: cli.verify_timeout,
+ })
+}
+
+fn reset_config(cli: &Cli) -> Result<reset::ResetConfig> {
+ let database_url = cli
+ .database_url
+ .clone()
+ .context("--reset-team requires --database-url or DATABASE_URL")?;
+ let team_id = cli.team_id.context("--reset-team requires --team-id")?;
+ Ok(reset::ResetConfig {
+ database_url,
+ team_id,
+ tmp_person_table: cli.tmp_person_table.clone(),
+ tmp_pdi_table: cli.tmp_pdi_table.clone(),
+ })
}
#[cfg(test)]
@@ -396,6 +496,45 @@ mod tests {
assert_eq!(parts.iter().filter(|&&p| p == 0).count(), 5);
}
+ #[test]
+ fn verify_config_requires_a_team_id() {
+ let cli = Cli::parse_from([
+ "loadgen",
+ "--token",
+ "t",
+ "--database-url",
+ "d",
+ "--count",
+ "0",
+ ]);
+ assert!(verify_config(&cli).is_err());
+ }
+
+ #[test]
+ fn reset_config_requires_a_team_id() {
+ let cli = Cli::parse_from([
+ "loadgen",
+ "--token",
+ "t",
+ "--database-url",
+ "d",
+ "--reset-team",
+ ]);
+ assert!(reset_config(&cli).is_err());
+ }
+
+ #[test]
+ fn zero_share_shard_zero_still_verifies() {
+ assert_eq!(shard_plan(None, Some(0), true, 0), (false, true));
+ assert_eq!(shard_plan(Some(0), None, true, 0), (false, true));
+ }
+
+ #[test]
+ fn only_shard_zero_verifies() {
+ assert_eq!(shard_plan(None, Some(10), true, 3), (true, false));
+ assert_eq!(shard_plan(None, Some(10), false, 0), (true, false));
+ }
+
#[test]
fn claim_drains_the_counter_exactly() {
let remaining = AtomicU64::new(250);
diff --git a/rust/capture-load-gen/src/reset.rs b/rust/capture-load-gen/src/reset.rs
new file mode 100644
index 000000000000..821084f7694f
--- /dev/null
+++ b/rust/capture-load-gen/src/reset.rs
@@ -0,0 +1,77 @@
+//! Deletes one team's rows from the Postgres person graph and the personhog
+//! writer's temp tables, so a run starts from a clean slate.
+
+use anyhow::{Context, Result};
+use sqlx::postgres::PgPoolOptions;
+use sqlx::{Executor, PgPool};
+
+/// So one chunk's delete fails fast on a lock instead of hanging the step.
+const STATEMENT_TIMEOUT_MS: u64 = 30_000;
+/// Rows deleted per statement.
+const RESET_CHUNK: i64 = 10_000;
+
+pub struct ResetConfig {
+ pub database_url: String,
+ pub team_id: i64,
+ pub tmp_person_table: String,
+ pub tmp_pdi_table: String,
+}
+
+pub async fn reset_team(cfg: &ResetConfig) -> Result<()> {
+ let pool = PgPoolOptions::new()
+ .max_connections(1)
+ .after_connect(|conn, _meta| {
+ Box::pin(async move {
+ conn.execute(format!("SET statement_timeout = {STATEMENT_TIMEOUT_MS}").as_str())
+ .await?;
+ Ok(())
+ })
+ })
+ .connect(&cfg.database_url)
+ .await
+ .context("connecting to the persons database")?;
+ reset_team_on_pool(
+ &pool,
+ cfg.team_id,
+ &cfg.tmp_person_table,
+ &cfg.tmp_pdi_table,
+ RESET_CHUNK,
+ )
+ .await
+}
+
+pub async fn reset_team_on_pool(
+ pool: &PgPool,
+ team_id: i64,
+ tmp_person_table: &str,
+ tmp_pdi_table: &str,
+ chunk: i64,
+) -> Result<()> {
+ // Distinct-id rows reference persons, so delete them first.
+ for table in [
+ "posthog_persondistinctid",
+ tmp_pdi_table,
+ "posthog_person",
+ tmp_person_table,
+ ] {
+ // Chunk the delete so millions of rows stay bounded and index-driven.
+ let mut total = 0u64;
+ loop {
+ let deleted = sqlx::query(&format!(
+ "DELETE FROM {table} WHERE team_id = $1 AND id IN \
+ (SELECT id FROM {table} WHERE team_id = $1 LIMIT {chunk})"
+ ))
+ .bind(team_id)
+ .execute(pool)
+ .await
+ .with_context(|| format!("resetting {table}"))?
+ .rows_affected();
+ total += deleted;
+ if (deleted as i64) < chunk {
+ break;
+ }
+ }
+ tracing::info!(table, team_id, deleted = total, "reset team rows");
+ }
+ Ok(())
+}
diff --git a/rust/capture-load-gen/src/verify.rs b/rust/capture-load-gen/src/verify.rs
new file mode 100644
index 000000000000..5a2a4e5af5e6
--- /dev/null
+++ b/rust/capture-load-gen/src/verify.rs
@@ -0,0 +1,256 @@
+//! Compares the Postgres person graph against the personhog writer's temp
+//! tables for one team. One full outer join counts the per-field diffs in the
+//! database and returns only the tallies. It polls until the graphs agree on a
+//! drained cohort or the deadline passes.
+
+use std::time::Duration;
+
+use anyhow::{Context, Result};
+use metrics::gauge;
+use sqlx::postgres::{PgPoolOptions, PgRow};
+use sqlx::{Executor, PgPool, Row};
+
+const SWEEP_INTERVAL: Duration = Duration::from_secs(5);
+/// Caps one comparison well under the verify deadline.
+const STATEMENT_TIMEOUT_MS: u64 = 120_000;
+
+pub struct VerifyConfig {
+ pub database_url: String,
+ pub team_id: i64,
+ pub tmp_person_table: String,
+ pub tmp_pdi_table: String,
+ pub deadline: Duration,
+}
+
+/// Tallies for one comparison. Field diffs count only ids present in both
+/// graphs; a one-sided id is missing_shadow or extra_shadow instead.
+pub struct Counts {
+ pub main: i64,
+ pub cohort: i64,
+ pub mismatched: i64,
+ pub missing_shadow: i64,
+ pub extra_shadow: i64,
+ pub uuid: i64,
+ pub properties: i64,
+ pub is_identified: i64,
+ pub created_at: i64,
+}
+
+impl Counts {
+ fn read(row: &PgRow) -> Self {
+ Self {
+ main: row.get("main_count"),
+ cohort: row.get("cohort"),
+ mismatched: row.get("mismatched"),
+ missing_shadow: row.get("missing_shadow"),
+ extra_shadow: row.get("extra_shadow"),
+ uuid: row.get("uuid"),
+ properties: row.get("properties"),
+ is_identified: row.get("is_identified"),
+ created_at: row.get("created_at"),
+ }
+ }
+}
+
+/// Parity holds once the graphs agree on a non-empty authoritative cohort that
+/// has stopped growing. A stable main count means ingestion drained; a zero
+/// count means nothing landed, which is a failed run, not a pass.
+fn is_pass(mismatched: i64, main_count: i64, prev_main: Option<i64>) -> bool {
+ mismatched == 0 && main_count > 0 && prev_main == Some(main_count)
+}
+
+/// Both legs project the fields compared for parity. created_at is truncated to
+/// whole ms (the writer stores it at ms resolution), so sub-ms is not drift.
+fn person_projection() -> &'static str {
+ "d.distinct_id, p.uuid, p.properties, p.is_identified,
+ date_trunc('milliseconds', p.created_at) AS created_at_ms"
+}
+
+pub struct Verifier {
+ pool: PgPool,
+ team_id: i64,
+ tmp_person_table: String,
+ tmp_pdi_table: String,
+}
+
+impl Verifier {
+ pub async fn connect(cfg: &VerifyConfig) -> Result<Self> {
+ let pool = PgPoolOptions::new()
+ .max_connections(2)
+ .after_connect(|conn, _meta| {
+ Box::pin(async move {
+ conn.execute(
+ format!("SET statement_timeout = {STATEMENT_TIMEOUT_MS}").as_str(),
+ )
+ .await?;
+ Ok(())
+ })
+ })
+ .connect(&cfg.database_url)
+ .await
+ .context("connecting to the persons database")?;
+ Ok(Self::from_pool(
+ pool,
+ cfg.team_id,
+ cfg.tmp_person_table.clone(),
+ cfg.tmp_pdi_table.clone(),
+ ))
+ }
+
+ pub fn from_pool(
+ pool: PgPool,
+ team_id: i64,
+ tmp_person_table: String,
+ tmp_pdi_table: String,
+ ) -> Self {
+ Self {
+ pool,
+ team_id,
+ tmp_person_table,
+ tmp_pdi_table,
+ }
+ }
+
+ /// One full outer join of the two legs, counting differences by kind. Each
+ /// leg is the team's live persons keyed by distinct id; `team_id = $1` on
+ /// the `(team_id, distinct_id)` and PK indexes keeps both legs index scans
+ /// over just the team's rows. Binds $1 team.
+ fn comparison_sql(&self) -> String {
+ let leg = |pdi: &str, person: &str| {
+ format!(
+ "SELECT {projection}
+ FROM {pdi} d
+ JOIN {person} p ON p.id = d.person_id AND p.team_id = d.team_id
+ WHERE d.team_id = $1 AND d.is_deleted = false AND p.is_deleted = false",
+ projection = person_projection()
+ )
+ };
+ let main = leg("posthog_persondistinctid", "posthog_person");
+ let shadow = leg(&self.tmp_pdi_table, &self.tmp_person_table);
+ format!(
+ "WITH main AS ({main}), shadow AS ({shadow}), j AS (
+ SELECT
+ m.distinct_id IS NULL AS extra_shadow,
+ s.distinct_id IS NULL AS missing_shadow,
+ m.uuid IS DISTINCT FROM s.uuid AS uuid_diff,
+ m.properties IS DISTINCT FROM s.properties AS properties_diff,
+ m.is_identified IS DISTINCT FROM s.is_identified AS is_identified_diff,
+ m.created_at_ms IS DISTINCT FROM s.created_at_ms AS created_at_diff
+ FROM main m FULL OUTER JOIN shadow s ON m.distinct_id = s.distinct_id
+ )
+ SELECT
+ count(*) FILTER (WHERE NOT extra_shadow) AS main_count,
+ count(*) AS cohort,
+ count(*) FILTER (WHERE extra_shadow OR missing_shadow OR uuid_diff
+ OR properties_diff OR is_identified_diff OR created_at_diff) AS mismatched,
+ count(*) FILTER (WHERE missing_shadow) AS missing_shadow,
+ count(*) FILTER (WHERE extra_shadow) AS extra_shadow,
+ count(*) FILTER (WHERE uuid_diff AND NOT missing_shadow AND NOT extra_shadow) AS uuid,
+ count(*) FILTER (WHERE properties_diff AND NOT missing_shadow AND NOT extra_shadow) AS properties,
+ count(*) FILTER (WHERE is_identified_diff AND NOT missing_shadow AND NOT extra_shadow) AS is_identified,
+ count(*) FILTER (WHERE created_at_diff AND NOT missing_shadow AND NOT extra_shadow) AS created_at
+ FROM j"
+ )
+ }
+
+ /// One comparison of the whole team cohort.
+ pub async fn sweep(&self) -> Result<Counts> {
+ let row = sqlx::query(&self.comparison_sql())
+ .bind(self.team_id)
+ .fetch_one(&self.pool)
+ .await
+ .context("comparing the cohort")?;
+ Ok(Counts::read(&row))
+ }
+
+ fn export_gauges(&self, counts: &Counts) {
+ gauge!("capture_loadgen_parity_cohort_size").set(counts.cohort as f64);
+ gauge!("capture_loadgen_parity_authoritative_cohort").set(counts.main as f64);
+ gauge!("capture_loadgen_parity_mismatched").set(counts.mismatched as f64);
+ gauge!("capture_loadgen_parity_clean").set(if counts.mismatched == 0 { 1.0 } else { 0.0 });
+ gauge!("capture_loadgen_parity_last_sweep_timestamp_seconds")
+ .set(common_metrics::get_current_timestamp_seconds());
+ }
+
+ /// Polls until the graphs agree on a stable, drained cohort or the deadline
+ /// passes. A transient query error retries; only a divergence that outlasts
+ /// the deadline fails.
+ pub async fn run(&self, cfg: &VerifyConfig) -> Result<bool> {
+ let deadline = tokio::time::Instant::now() + cfg.deadline;
+ let mut prev_main: Option<i64> = None;
+ loop {
+ let counts = match self.sweep().await {
+ Ok(counts) => counts,
+ Err(error) => {
+ if tokio::time::Instant::now() >= deadline {
+ return Err(error).context("sweep failed at the deadline");
+ }
+ tracing::warn!(error = format!("{error:#}"), "sweep failed; retrying");
+ tokio::time::sleep(SWEEP_INTERVAL).await;
+ continue;
+ }
+ };
+ self.export_gauges(&counts);
+ tracing::info!(
+ cohort = counts.cohort,
+ main_count = counts.main,
+ mismatched = counts.mismatched,
+ "sweep complete"
+ );
+ if is_pass(counts.mismatched, counts.main, prev_main) {
+ tracing::info!(
+ cohort = counts.cohort,
+ "shadow graphs agree on a stable, drained cohort"
+ );
+ return Ok(true);
+ }
+ if tokio::time::Instant::now() >= deadline {
+ report_failure(cfg, &counts);
+ return Ok(false);
+ }
+ prev_main = Some(counts.main);
+ tokio::time::sleep(SWEEP_INTERVAL).await;
+ }
+ }
+}
+
+fn report_failure(cfg: &VerifyConfig, counts: &Counts) {
+ let deadline_secs = cfg.deadline.as_secs();
+ if counts.mismatched == 0 {
+ tracing::warn!(
+ cohort = counts.cohort,
+ main_count = counts.main,
+ deadline_secs,
+ "verification expired without a divergence: the authoritative cohort never \
+ stabilized at a non-zero size; ingestion is likely still draining, or nothing landed"
+ );
+ return;
+ }
+ tracing::warn!(
+ cohort = counts.cohort,
+ mismatched = counts.mismatched,
+ missing_shadow = counts.missing_shadow,
+ extra_shadow = counts.extra_shadow,
+ uuid = counts.uuid,
+ properties = counts.properties,
+ is_identified = counts.is_identified,
+ created_at = counts.created_at,
+ deadline_secs,
+ "shadow parity verification failed; the diverging rows stay in the team until the \
+ next run resets it, so query them there by team_id"
+ );
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_pass_needs_no_mismatch_and_a_stable_non_empty_cohort() {
+ assert!(is_pass(0, 100, Some(100)));
+ assert!(!is_pass(1, 100, Some(100)));
+ assert!(!is_pass(0, 100, None));
+ assert!(!is_pass(0, 100, Some(90)));
+ assert!(!is_pass(0, 0, Some(0)));
+ }
+}
diff --git a/rust/capture-load-gen/tests/parity.rs b/rust/capture-load-gen/tests/parity.rs
new file mode 100644
index 000000000000..6d6011cbac33
--- /dev/null
+++ b/rust/capture-load-gen/tests/parity.rs
@@ -0,0 +1,238 @@
+use anyhow::Result;
+use capture_load_gen::reset::reset_team_on_pool;
+use capture_load_gen::verify::Verifier;
+use sqlx::{PgPool, Row};
+
+const TEAM: i64 = 5163;
+const TMP_PERSON: &str = "personhog_person_tmp";
+const TMP_PDI: &str = "personhog_persondistinctid_tmp";
+
+async fn create_schema(pool: &PgPool) -> Result<()> {
+ for stmt in [
+ "CREATE TABLE posthog_person (id bigint, team_id bigint, uuid text, \
+ properties jsonb, is_identified boolean, is_deleted boolean, \
+ created_at timestamptz, PRIMARY KEY (team_id, id))",
+ "CREATE TABLE posthog_persondistinctid (id bigint PRIMARY KEY, team_id bigint, \
+ distinct_id text, person_id bigint, is_deleted boolean)",
+ "CREATE TABLE personhog_person_tmp (LIKE posthog_person INCLUDING ALL)",
+ "CREATE TABLE personhog_persondistinctid_tmp (LIKE posthog_persondistinctid INCLUDING ALL)",
+ ] {
+ sqlx::query(stmt).execute(pool).await?;
+ }
+ Ok(())
+}
+
+async fn insert_person(
+ pool: &PgPool,
+ table: &str,
+ team: i64,
+ id: i64,
+ identified: bool,
+) -> Result<()> {
+ sqlx::query(&format!(
+ "INSERT INTO {table} (id, team_id, uuid, properties, is_identified, is_deleted, created_at) \
+ VALUES ($1, $2, $3, '{{}}'::jsonb, $4, false, to_timestamp(1700000000))"
+ ))
+ .bind(id)
+ .bind(team)
+ .bind(format!("uuid-{id}"))
+ .bind(identified)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+async fn insert_pdi(
+ pool: &PgPool,
+ table: &str,
+ team: i64,
+ id: i64,
+ distinct_id: &str,
+ person_id: i64,
+) -> Result<()> {
+ sqlx::query(&format!(
+ "INSERT INTO {table} (id, team_id, distinct_id, person_id, is_deleted) \
+ VALUES ($1, $2, $3, $4, false)"
+ ))
+ .bind(id)
+ .bind(team)
+ .bind(distinct_id)
+ .bind(person_id)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+async fn seed_leg(
+ pool: &PgPool,
+ person_table: &str,
+ pdi_table: &str,
+ team: i64,
+ id: i64,
+ distinct_id: &str,
+) -> Result<()> {
+ insert_person(pool, person_table, team, id, true).await?;
+ insert_pdi(pool, pdi_table, team, id, distinct_id, id).await
+}
+
+async fn count_for_team(pool: &PgPool, table: &str, team: i64) -> Result<i64> {
+ let row = sqlx::query(&format!(
+ "SELECT count(*) AS n FROM {table} WHERE team_id = $1"
+ ))
+ .bind(team)
+ .fetch_one(pool)
+ .await?;
+ Ok(row.get::<i64, _>("n"))
+}
+
+fn verifier(pool: &PgPool) -> Verifier {
+ Verifier::from_pool(pool.clone(), TEAM, TMP_PERSON.into(), TMP_PDI.into())
+}
+
+#[sqlx::test]
+async fn identical_graphs_report_no_mismatch(pool: PgPool) -> Result<()> {
+ create_schema(&pool).await?;
+ for (id, d) in [(1, "a"), (2, "b"), (3, "c")] {
+ seed_leg(
+ &pool,
+ "posthog_person",
+ "posthog_persondistinctid",
+ TEAM,
+ id,
+ d,
+ )
+ .await?;
+ seed_leg(&pool, TMP_PERSON, TMP_PDI, TEAM, id, d).await?;
+ }
+ let counts = verifier(&pool).sweep().await?;
+ assert_eq!(counts.mismatched, 0);
+ assert_eq!(counts.main, 3);
+ assert_eq!(counts.cohort, 3);
+ Ok(())
+}
+
+#[sqlx::test]
+async fn a_person_missing_from_shadow_is_reported(pool: PgPool) -> Result<()> {
+ create_schema(&pool).await?;
+ seed_leg(
+ &pool,
+ "posthog_person",
+ "posthog_persondistinctid",
+ TEAM,
+ 1,
+ "a",
+ )
+ .await?;
+ let counts = verifier(&pool).sweep().await?;
+ assert_eq!(counts.mismatched, 1);
+ assert_eq!(counts.missing_shadow, 1);
+ Ok(())
+}
+
+#[sqlx::test]
+async fn sub_millisecond_created_at_is_not_a_divergence(pool: PgPool) -> Result<()> {
+ create_schema(&pool).await?;
+ // Authoritative keeps microseconds; the writer stores the same instant at
+ // millisecond resolution. They must compare equal.
+ sqlx::query(
+ "INSERT INTO posthog_person (id, team_id, uuid, properties, is_identified, is_deleted, created_at) \
+ VALUES (1, $1, 'u', '{}'::jsonb, true, false, '2023-11-14 22:13:20.123456+00')",
+ )
+ .bind(TEAM)
+ .execute(&pool)
+ .await?;
+ insert_pdi(&pool, "posthog_persondistinctid", TEAM, 1, "a", 1).await?;
+ sqlx::query(
+ "INSERT INTO personhog_person_tmp (id, team_id, uuid, properties, is_identified, is_deleted, created_at) \
+ VALUES (1, $1, 'u', '{}'::jsonb, true, false, '2023-11-14 22:13:20.123+00')",
+ )
+ .bind(TEAM)
+ .execute(&pool)
+ .await?;
+ insert_pdi(&pool, TMP_PDI, TEAM, 1, "a", 1).await?;
+ let counts = verifier(&pool).sweep().await?;
+ assert_eq!(counts.created_at, 0, "sub-ms difference must not be drift");
+ assert_eq!(counts.mismatched, 0);
+ Ok(())
+}
+
+#[sqlx::test]
+async fn a_dangling_id_does_not_hide_other_drift(pool: PgPool) -> Result<()> {
+ create_schema(&pool).await?;
+ // A shadow distinct id whose person is absent yields no join row.
+ insert_pdi(&pool, TMP_PDI, TEAM, 10, "a", 999).await?;
+ // A real divergence must still be counted alongside it.
+ seed_leg(
+ &pool,
+ "posthog_person",
+ "posthog_persondistinctid",
+ TEAM,
+ 2,
+ "b",
+ )
+ .await?;
+ let counts = verifier(&pool).sweep().await?;
+ assert_eq!(
+ counts.missing_shadow, 1,
+ "the divergence must still be found"
+ );
+ Ok(())
+}
+
+#[sqlx::test]
+async fn reset_clears_the_team_and_leaves_others(pool: PgPool) -> Result<()> {
+ create_schema(&pool).await?;
+ for id in 1..=5 {
+ let d = format!("d{id}");
+ seed_leg(
+ &pool,
+ "posthog_person",
+ "posthog_persondistinctid",
+ TEAM,
+ id,
+ &d,
+ )
+ .await?;
+ seed_leg(&pool, TMP_PERSON, TMP_PDI, TEAM, id, &d).await?;
+ }
+ // Another team, including a person whose id collides with this team's
+ // cohort (person id is unique only per team), must survive the reset.
+ seed_leg(
+ &pool,
+ "posthog_person",
+ "posthog_persondistinctid",
+ 999,
+ 100,
+ "z",
+ )
+ .await?;
+ seed_leg(&pool, TMP_PERSON, TMP_PDI, 999, 100, "z").await?;
+ insert_person(&pool, "posthog_person", 999, 1, true).await?;
+ insert_person(&pool, TMP_PERSON, 999, 1, true).await?;
+
+ reset_team_on_pool(&pool, TEAM, TMP_PERSON, TMP_PDI, 2).await?;
+
+ for table in [
+ "posthog_person",
+ "posthog_persondistinctid",
+ TMP_PERSON,
+ TMP_PDI,
+ ] {
+ assert_eq!(
+ count_for_team(&pool, table, TEAM).await?,
+ 0,
+ "{table} not cleared"
+ );
+ }
+ assert_eq!(
+ count_for_team(&pool, "posthog_person", 999).await?,
+ 2,
+ "other team wiped"
+ );
+ assert_eq!(
+ count_for_team(&pool, TMP_PERSON, 999).await?,
+ 2,
+ "other team's tmp wiped"
+ );
+ Ok(())
+}