:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(capture-load-gen): verify merges by what each backend could have written (#104757)
Zach Brownbffe27e65a38
diff --git a/rust/capture-load-gen/README.md b/rust/capture-load-gen/README.mdindex ec0fb76fa415..479536966c37 100644--- a/rust/capture-load-gen/README.md+++ b/rust/capture-load-gen/README.md@@ -41,7 +41,7 @@ requests.| `--percent-attaches` | `0` | Percentage of events that are an `$identify` of a fresh anon distinct id || `--percent-person-merges` | `0` | Percentage of events spent on merges of two persons (a seed event, then its `$identify`) || `--person-merge-delay` | `10s` | How long a seeded anon id waits before its `$identify` |-| `--percent-dangerous-merges` | `0` | Percentage of events that are `$merge_dangerously` between paired pool users |+| `--percent-dangerous-merges` | `0` | Percentage of events that are `$merge_dangerously` from the even user of each pair || `--dry-run` | off | Print one sample batch as JSON and exit |The `--percent-*` flags must sum to at most 100;@@ -51,7 +51,9 @@ The three identity flags exercise different paths:- `--percent-attaches` claims an anonymous id that never sent an event. It has no person, so the `$identify` only attaches the id to the pool user.- `--percent-person-merges` gives the anonymous id a person first. A seed event from the id carries a `$set`, and its `$identify` follows after `--person-merge-delay`, so one person folds into another. The two events use different partitions, so an `$identify` that still arrives first attaches instead. When the load ends, the run waits out the delay and claims every id still seeded, so it finishes up to one delay after `--duration` and sends those `$identify` events on top of `--count`.-- `--percent-dangerous-merges` sends `$merge_dangerously` from a pool user with its partner as `alias`. Users pair off (`0` with `1`, `2` with `3`), which bounds a person to two pool users. The merged-away user keeps receiving events.+- `--percent-dangerous-merges` sends `$merge_dangerously` from the even user of each pair (`0` merges `1`, `2` merges `3`) with the partner as `alias`, so a pair has one survivor on every backend and a person never grows past two pool users. The merged-away user keeps receiving events.++The seed event writes two properties: `loadgen_anon_seed`, which every seed that merges into a person overwrites, and `loadgen_anon_seed_<anon id>`, written once. Verify compares all properties except the shared key exactly, and accepts any shared-key value that one of the person's own per-id keys carries, because which seed wrote last is decided by arrival order on each backend.Output is a once-per-second throughput line plus a final summary withHdrHistogram latency percentiles (p50/p95/p99).diff --git a/rust/capture-load-gen/src/event.rs b/rust/capture-load-gen/src/event.rsindex ca88ff51c7d8..0800dd504f22 100644--- a/rust/capture-load-gen/src/event.rs+++ b/rust/capture-load-gen/src/event.rs@@ -110,14 +110,18 @@ impl EventFactory {}share += u16::from(self.mix.dangerous_merges);if roll < share {- // Fixed pairs bound a person to two pool users; the last user of an odd pool has no partner.- return match self.distinct_ids.get(index ^ 1) {- Some(partner) => Self::dangerous_merge_event(base, partner),- None => RawEvent {+ // Fixed pairs bound a person to two pool users. Only the even user+ // merges, so the pair has one survivor on every backend.+ let pairs = self.distinct_ids.len() / 2;+ if pairs == 0 {+ return RawEvent {event: self.random_event_name(rng),..base- },- };+ };+ }+ let even = 2 * rng.gen_range(0..pairs);+ let sender = self.base_event(&self.distinct_ids[even]);+ return Self::dangerous_merge_event(sender, &self.distinct_ids[even + 1]);}let event = self.random_event_name(rng);share += u16::from(self.mix.person_updates);@@ -156,10 +160,17 @@ impl EventFactory {seeded.push_back((anon_id.clone(), Instant::now()));anon_id};+ // The shared key is contested between the seed and the survivor; the+ // per-id key has one writer and names which seeds reached the person.+ let seed_value = Uuid::now_v7().to_string();let mut set = HashMap::new();set.insert("loadgen_anon_seed".to_string(),- Value::String(Uuid::now_v7().to_string()),+ Value::String(seed_value.clone()),+ );+ set.insert(+ format!("loadgen_anon_seed_{seed_id}"),+ Value::String(seed_value),);RawEvent {event: self.random_event_name(rng),@@ -404,7 +415,12 @@ mod tests {let (seed, claim) = (&batch[0], &batch[1]);assert!(distinct_id(seed).starts_with("loadgen-anon-"));assert_ne!(seed.event, "$identify");- assert!(seed.set.as_ref().unwrap().contains_key("loadgen_anon_seed"));+ let seed_set = seed.set.as_ref().unwrap();+ assert!(seed_set.contains_key("loadgen_anon_seed"));+ assert_eq!(+ seed_set[&format!("loadgen_anon_seed_{}", distinct_id(seed))],+ seed_set["loadgen_anon_seed"]+ );assert_eq!(claim.event, "$identify");assert!(distinct_id(claim).starts_with("loadgen-user-"));@@ -480,10 +496,14 @@ mod tests {.unwrap()};- for event in f.batch(50, &mut rng) {+ for event in f.batch(200, &mut rng) {assert_eq!(event.event, "$merge_dangerously");- let partner = event.properties["alias"].as_str().unwrap();- assert_eq!(index(partner), index(distinct_id(&event)) ^ 1);+ let sender = index(distinct_id(&event));+ assert_eq!(sender % 2, 0, "only the even user of a pair merges");+ assert_eq!(+ index(event.properties["alias"].as_str().unwrap()),+ sender + 1+ );}}diff --git a/rust/capture-load-gen/src/main.rs b/rust/capture-load-gen/src/main.rsindex 1c5a423780f9..30cacb8ba4b7 100644--- a/rust/capture-load-gen/src/main.rs+++ b/rust/capture-load-gen/src/main.rs@@ -393,7 +393,7 @@ async fn main() -> Result<()> {// A missing verify prerequisite must fail here, not after the load.let verify_cfg = if should_verify {- Some(verify_config(&cli)?)+ Some(verify_config(&cli, duration)?)} else {None};@@ -485,8 +485,10 @@ fn spawn_metrics_server(port: u16) {});}-/// The verify flags as a config, failing on the one without a default.-fn verify_config(cli: &Cli) -> Result<verify::VerifyConfig> {+/// The verify flags as a config, failing on the one without a default. A+/// rate run's deadline is at least its own length plus the merge delay,+/// so a long run is not cut off while its last claims still land.+fn verify_config(cli: &Cli, duration: Option<Duration>) -> Result<verify::VerifyConfig> {let database_url = cli.database_url.clone()@@ -497,7 +499,9 @@ fn verify_config(cli: &Cli) -> Result<verify::VerifyConfig> {team_id,tmp_person_table: cli.tmp_person_table.clone(),tmp_pdi_table: cli.tmp_pdi_table.clone(),- deadline: cli.verify_timeout,+ deadline: duration.map_or(cli.verify_timeout, |run| {+ cli.verify_timeout.max(run + cli.person_merge_delay)+ }),})}@@ -543,6 +547,31 @@ mod tests {assert_eq!(parts.iter().filter(|&&p| p == 0).count(), 5);}+ #[test]+ fn verify_deadline_outlasts_a_long_run() {+ let cli = Cli::parse_from([+ "loadgen",+ "--token",+ "t",+ "--database-url",+ "d",+ "--team-id",+ "1",+ "--rate",+ "1",+ "--duration",+ "20m",+ "--verify-timeout",+ "5m",+ "--person-merge-delay",+ "10s",+ ]);+ let long_run = verify_config(&cli, Some(Duration::from_secs(20 * 60))).unwrap();+ assert_eq!(long_run.deadline, Duration::from_secs(20 * 60 + 10));+ let short_run = verify_config(&cli, Some(Duration::from_secs(60))).unwrap();+ assert_eq!(short_run.deadline, Duration::from_secs(5 * 60));+ }+#[test]fn verify_config_requires_a_team_id() {let cli = Cli::parse_from([@@ -554,7 +583,7 @@ mod tests {"--count","0",]);- assert!(verify_config(&cli).is_err());+ assert!(verify_config(&cli, None).is_err());}#[test]diff --git a/rust/capture-load-gen/src/verify.rs b/rust/capture-load-gen/src/verify.rsindex 5a2a4e5af5e6..5a1bfd0c3e76 100644--- a/rust/capture-load-gen/src/verify.rs+++ b/rust/capture-load-gen/src/verify.rs@@ -32,6 +32,7 @@ pub struct Counts {pub extra_shadow: i64,pub uuid: i64,pub properties: i64,+ pub contested: i64,pub is_identified: i64,pub created_at: i64,}@@ -46,6 +47,7 @@ impl Counts {extra_shadow: row.get("extra_shadow"),uuid: row.get("uuid"),properties: row.get("properties"),+ contested: row.get("contested"),is_identified: row.get("is_identified"),created_at: row.get("created_at"),}@@ -133,7 +135,17 @@ impl Verifier {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,+ -- Keys every merged-in person also wrote take whichever value arrived last on+ -- each backend, so they are checked by candidate below, not by value.+ (m.properties - '{{loadgen_anon_seed,$creator_event_uuid}}'::text[])+ IS DISTINCT FROM (s.properties - '{{loadgen_anon_seed,$creator_event_uuid}}'::text[]) AS properties_diff,+ -- The seed key has a candidate set: the per-id keys of the seeds that reached the person.+ (m.properties ? 'loadgen_anon_seed' AND NOT EXISTS (+ SELECT 1 FROM jsonb_each_text(m.properties) kv+ WHERE left(kv.key, 18) = 'loadgen_anon_seed_' AND kv.value = m.properties->>'loadgen_anon_seed'))+ OR (s.properties ? 'loadgen_anon_seed' AND NOT EXISTS (+ SELECT 1 FROM jsonb_each_text(s.properties) kv+ WHERE left(kv.key, 18) = 'loadgen_anon_seed_' AND kv.value = s.properties->>'loadgen_anon_seed')) AS contested_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_diffFROM main m FULL OUTER JOIN shadow s ON m.distinct_id = s.distinct_id@@ -142,11 +154,12 @@ impl Verifier {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,+ OR properties_diff OR contested_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 contested_diff AND NOT missing_shadow AND NOT extra_shadow) AS contested,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_atFROM j"@@ -233,6 +246,7 @@ fn report_failure(cfg: &VerifyConfig, counts: &Counts) {extra_shadow = counts.extra_shadow,uuid = counts.uuid,properties = counts.properties,+ contested = counts.contested,is_identified = counts.is_identified,created_at = counts.created_at,deadline_secs,