: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
feat(capture-load-gen): generate merges that fold one person into another (#104085)
Zach Brown551d597bedad
diff --git a/rust/capture-load-gen/README.md b/rust/capture-load-gen/README.mdindex 94e60f3eaa5b..ec0fb76fa415 100644--- a/rust/capture-load-gen/README.md+++ b/rust/capture-load-gen/README.md@@ -38,13 +38,20 @@ requests.| `--event-name` | `$pageview`, `$autocapture`, `custom_event` | Event names to pick from (repeatable) || `--prop-bytes` | `256` | Approx filler bytes per event || `--percent-person-updates` | `0` | Percentage of events carrying a `$set` payload (person update) |-| `--percent-merges` | `0` | Percentage of events that are `$identify` merges of a fresh anon distinct id |+| `--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 || `--dry-run` | off | Print one sample batch as JSON and exit |-`--percent-person-updates` and `--percent-merges` must sum to at most 100;+The `--percent-*` flags must sum to at most 100;the rest of the events are plain (no person-pipeline work beyond creation).-Each merge claims a unique anonymous distinct id, so every `$identify` exercises-the merge path instead of re-merging an already-folded pair.++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.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 2c9554c85567..ca88ff51c7d8 100644--- a/rust/capture-load-gen/src/event.rs+++ b/rust/capture-load-gen/src/event.rs@@ -1,4 +1,6 @@-use std::collections::HashMap;+use std::collections::{HashMap, VecDeque};+use std::sync::Mutex;+use std::time::{Duration, Instant};use common_types::RawEvent;use rand::Rng;@@ -6,19 +8,51 @@ use serde::Serialize;use serde_json::Value;use uuid::Uuid;+/// Share of events, in percent, spent on each kind of person-pipeline work.+#[derive(Clone, Copy, Debug, Default)]+pub struct TrafficMix {+ /// Regular events carrying a `$set` payload.+ pub person_updates: u8,+ /// `$identify` claiming a fresh anonymous id, which attaches the id to the pool user.+ pub attaches: u8,+ /// `$identify` claiming an anonymous id that has a person, which merges two persons.+ pub person_merges: u8,+ /// `$merge_dangerously` between a pool user and its partner.+ pub dangerous_merges: u8,+}++impl TrafficMix {+ pub fn total(&self) -> u16 {+ [+ self.person_updates,+ self.attaches,+ self.person_merges,+ self.dangerous_merges,+ ]+ .into_iter()+ .map(u16::from)+ .sum()+ }+}+/// Generates synthetic [`RawEvent`]s shaped like real capture traffic.////// Distinct IDs are drawn from a fixed pool so person cardinality is/// controllable, and each event is padded with filler properties to roughly/// match a target serialized size. A configurable share of events exercises-/// the person pipeline: person updates carry a `$set` payload, merges are-/// `$identify` events claiming a fresh anonymous distinct id.+/// the person pipeline; see [`TrafficMix`].pub struct EventFactory {distinct_ids: Vec<String>,event_names: Vec<String>,filler: String,- person_update_pct: u8,- merge_pct: u8,+ mix: TrafficMix,+ person_merge_delay: Duration,+ /// Anonymous ids that sent an event of their own, oldest first, awaiting their `$identify`.+ seeded_anon_ids: Mutex<VecDeque<(String, Instant)>>,+}++fn fresh_anon_id() -> String {+ format!("loadgen-anon-{}", Uuid::now_v7())}impl EventFactory {@@ -26,8 +60,8 @@ impl EventFactory {distinct_ids: u64,event_names: Vec<String>,prop_bytes: usize,- person_update_pct: u8,- merge_pct: u8,+ mix: TrafficMix,+ person_merge_delay: Duration,) -> Self {let distinct_ids = (0..distinct_ids.max(1)).map(|i| format!("loadgen-user-{i}"))@@ -36,52 +70,136 @@ impl EventFactory {distinct_ids,event_names,filler: "x".repeat(prop_bytes),- person_update_pct,- merge_pct,+ mix,+ person_merge_delay,+ seeded_anon_ids: Mutex::new(VecDeque::new()),}}- fn next(&self, rng: &mut impl Rng) -> RawEvent {- let distinct_id = &self.distinct_ids[rng.gen_range(0..self.distinct_ids.len())];-+ fn base_event(&self, distinct_id: &str) -> RawEvent {let mut properties: HashMap<String, Value> = HashMap::new();properties.insert("$lib".to_string(), Value::String("capture-load-gen".into()));if !self.filler.is_empty() {properties.insert("filler".to_string(), Value::String(self.filler.clone()));}- let base = RawEvent {- distinct_id: Some(Value::String(distinct_id.clone())),+ RawEvent {+ distinct_id: Some(Value::String(distinct_id.to_string())),uuid: Some(Uuid::now_v7()),properties,..Default::default()- };+ }+ }++ fn random_event_name(&self, rng: &mut impl Rng) -> String {+ self.event_names[rng.gen_range(0..self.event_names.len())].clone()+ }- let roll = rng.gen_range(0..100u8);- if roll < self.merge_pct {- return self.merge_event(base);+ fn next(&self, rng: &mut impl Rng) -> RawEvent {+ let index = rng.gen_range(0..self.distinct_ids.len());+ let base = self.base_event(&self.distinct_ids[index]);++ let roll = u16::from(rng.gen_range(0..100u8));+ let mut share = u16::from(self.mix.attaches);+ if roll < share {+ return Self::identify_event(base, fresh_anon_id());+ }+ share += u16::from(self.mix.person_merges);+ if roll < share {+ return self.person_merge_event(base, rng);}- let event = self.event_names[rng.gen_range(0..self.event_names.len())].clone();- if roll < self.merge_pct + self.person_update_pct {+ 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 {+ event: self.random_event_name(rng),+ ..base+ },+ };+ }+ let event = self.random_event_name(rng);+ share += u16::from(self.mix.person_updates);+ if roll < share {return Self::person_update_event(base, event);}RawEvent { event, ..base }}- /// A merge: `$identify` folding a fresh anonymous distinct id into the- /// pool user. The anon id is unique per event so every merge exercises- /// the merge path instead of re-merging an already-folded pair.- fn merge_event(&self, mut base: RawEvent) -> RawEvent {- base.properties.insert(- "$anon_distinct_id".to_string(),- Value::String(format!("loadgen-anon-{}", Uuid::now_v7())),- );+ /// `$identify` folding an anonymous distinct id into the pool user. An id with no+ /// person only attaches; one that sent its own event first merges two persons.+ fn identify_event(mut base: RawEvent, anon_id: String) -> RawEvent {+ base.properties+ .insert("$anon_distinct_id".to_string(), Value::String(anon_id));RawEvent {event: "$identify".to_string(),..base}}+ /// One of the two events a person merge takes: the seed gives a fresh anonymous id+ /// a person, and the claim is the `$identify` for the oldest id that waited out the delay.+ fn person_merge_event(&self, base: RawEvent, rng: &mut impl Rng) -> RawEvent {+ let seed_id = {+ let mut seeded = self+ .seeded_anon_ids+ .lock()+ .expect("seeded anon ids lock poisoned");+ let ripe = seeded+ .front()+ .is_some_and(|(_, seeded_at)| seeded_at.elapsed() >= self.person_merge_delay);+ if let Some((anon_id, _)) = ripe.then(|| seeded.pop_front()).flatten() {+ return Self::identify_event(base, anon_id);+ }+ let anon_id = fresh_anon_id();+ seeded.push_back((anon_id.clone(), Instant::now()));+ anon_id+ };+ let mut set = HashMap::new();+ set.insert(+ "loadgen_anon_seed".to_string(),+ Value::String(Uuid::now_v7().to_string()),+ );+ RawEvent {+ event: self.random_event_name(rng),+ set: Some(set),+ ..self.base_event(&seed_id)+ }+ }++ /// The `$identify` for every id still seeded, and how long until the youngest has+ /// waited out the delay, so a run can finish the person merges it started.+ pub fn drain_person_merges(&self, rng: &mut impl Rng) -> (Vec<RawEvent>, Duration) {+ let seeded = std::mem::take(+ &mut *self+ .seeded_anon_ids+ .lock()+ .expect("seeded anon ids lock poisoned"),+ );+ let wait = seeded.back().map_or(Duration::ZERO, |(_, seeded_at)| {+ self.person_merge_delay.saturating_sub(seeded_at.elapsed())+ });+ let claims = seeded+ .into_iter()+ .map(|(anon_id, _)| {+ let index = rng.gen_range(0..self.distinct_ids.len());+ Self::identify_event(self.base_event(&self.distinct_ids[index]), anon_id)+ })+ .collect();+ (claims, wait)+ }++ /// `$merge_dangerously` folding the partner's person into the pool user's, identified or not.+ fn dangerous_merge_event(mut base: RawEvent, partner: &str) -> RawEvent {+ base.properties+ .insert("alias".to_string(), Value::String(partner.to_string()));+ RawEvent {+ event: "$merge_dangerously".to_string(),+ ..base+ }+ }+/// A person update: a regular event carrying a `$set` payload. The value/// is unique per event so every update actually changes the person.fn person_update_event(base: RawEvent, event: String) -> RawEvent {@@ -118,7 +236,27 @@ mod tests {use rand::SeedableRng;fn factory() -> EventFactory {- EventFactory::new(100, vec!["a".into(), "b".into()], 32, 0, 0)+ EventFactory::new(+ 100,+ vec!["a".into(), "b".into()],+ 32,+ TrafficMix::default(),+ Duration::ZERO,+ )+ }++ fn factory_with(pool: u64, mix: TrafficMix, person_merge_delay: Duration) -> EventFactory {+ EventFactory::new(+ pool,+ vec!["a".into(), "b".into()],+ 0,+ mix,+ person_merge_delay,+ )+ }++ fn distinct_id(event: &RawEvent) -> &str {+ event.distinct_id.as_ref().unwrap().as_str().unwrap()}#[test]@@ -158,15 +296,25 @@ mod tests {#[test]fn zero_prop_bytes_omits_filler() {- let f = EventFactory::new(10, vec!["x".into()], 0, 0, 0);+ let f = EventFactory::new(+ 10,+ vec!["x".into()],+ 0,+ TrafficMix::default(),+ Duration::ZERO,+ );let mut rng = StdRng::seed_from_u64(3);let batch = f.batch(1, &mut rng);assert!(!batch[0].properties.contains_key("filler"));}#[test]- fn merge_events_are_identifies_with_fresh_anon_ids() {- let f = EventFactory::new(10, vec!["x".into()], 0, 0, 100);+ fn attach_events_are_identifies_with_fresh_anon_ids() {+ let mix = TrafficMix {+ attaches: 100,+ ..Default::default()+ };+ let f = factory_with(10, mix, Duration::ZERO);let mut rng = StdRng::seed_from_u64(4);let batch = f.batch(20, &mut rng);@@ -185,13 +333,17 @@ mod tests {assert_eq!(anon_ids.len(),20,- "every merge should claim a fresh anon id"+ "every attach should claim a fresh anon id");}#[test]fn person_update_events_carry_a_changing_set_payload() {- let f = EventFactory::new(10, vec!["a".into(), "b".into()], 0, 100, 0);+ let mix = TrafficMix {+ person_updates: 100,+ ..Default::default()+ };+ let f = factory_with(10, mix, Duration::ZERO);let mut rng = StdRng::seed_from_u64(5);let batch = f.batch(20, &mut rng);@@ -209,17 +361,144 @@ mod tests {#[test]fn mix_roughly_matches_the_configured_percentages() {- let f = EventFactory::new(100, vec!["a".into()], 0, 30, 20);+ let mix = TrafficMix {+ person_updates: 30,+ attaches: 20,+ person_merges: 10,+ dangerous_merges: 10,+ };+ // The delay outlasts the test, so every person merge is a seed and none an `$identify`.+ let f = factory_with(100, mix, Duration::from_secs(3600));let mut rng = StdRng::seed_from_u64(6);let batch = f.batch(2000, &mut rng);- let merges = batch.iter().filter(|e| e.event == "$identify").count();- let updates = batch.iter().filter(|e| e.set.is_some()).count();- let plain = batch.len() - merges - updates;+ let count =+ |matches: &dyn Fn(&RawEvent) -> bool| batch.iter().filter(|e| matches(e)).count();+ let attaches = count(&|e| e.event == "$identify");+ let seeds = count(&|e| distinct_id(e).starts_with("loadgen-anon-"));+ let dangerous = count(&|e| e.event == "$merge_dangerously");+ let updates = count(&|e| e.set.is_some()) - seeds;+ let plain = batch.len() - attaches - seeds - dangerous - updates;// Percentages are drawn per event; allow ±5 points on 2000 samples.- assert!((merges as i64 - 400).abs() < 100, "merges: {merges}");+ assert!((attaches as i64 - 400).abs() < 100, "attaches: {attaches}");+ assert!((seeds as i64 - 200).abs() < 100, "seeds: {seeds}");+ assert!(+ (dangerous as i64 - 200).abs() < 100,+ "dangerous: {dangerous}"+ );assert!((updates as i64 - 600).abs() < 100, "updates: {updates}");- assert!((plain as i64 - 1000).abs() < 100, "plain: {plain}");+ assert!((plain as i64 - 600).abs() < 100, "plain: {plain}");+ }++ #[test]+ fn a_person_merge_seeds_an_anonymous_person_then_claims_it() {+ let mix = TrafficMix {+ person_merges: 100,+ ..Default::default()+ };+ let f = factory_with(10, mix, Duration::ZERO);+ let mut rng = StdRng::seed_from_u64(7);+ let batch = f.batch(2, &mut rng);++ 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"));++ assert_eq!(claim.event, "$identify");+ assert!(distinct_id(claim).starts_with("loadgen-user-"));+ assert_eq!(+ claim.properties["$anon_distinct_id"].as_str().unwrap(),+ distinct_id(seed)+ );+ }++ #[test]+ fn a_seeded_id_is_not_claimed_before_its_delay() {+ let mix = TrafficMix {+ person_merges: 100,+ ..Default::default()+ };+ let f = factory_with(10, mix, Duration::from_secs(3600));+ let mut rng = StdRng::seed_from_u64(8);+ let batch = f.batch(5, &mut rng);++ assert!(batch.iter().all(|e| e.event != "$identify"));+ }++ #[test]+ fn draining_claims_every_seeded_id_once() {+ let mix = TrafficMix {+ person_merges: 100,+ ..Default::default()+ };+ let delay = Duration::from_secs(3600);+ let f = factory_with(10, mix, delay);+ let mut rng = StdRng::seed_from_u64(11);+ let mut seeded: Vec<String> = f+ .batch(5, &mut rng)+ .iter()+ .map(|e| distinct_id(e).to_string())+ .collect();++ let (claims, wait) = f.drain_person_merges(&mut rng);++ let mut claimed: Vec<String> = claims+ .iter()+ .map(|e| {+ assert_eq!(e.event, "$identify");+ assert!(distinct_id(e).starts_with("loadgen-user-"));+ e.properties["$anon_distinct_id"]+ .as_str()+ .unwrap()+ .to_string()+ })+ .collect();+ seeded.sort();+ claimed.sort();+ assert_eq!(claimed, seeded);+ assert!(wait > Duration::ZERO && wait <= delay, "wait: {wait:?}");++ let (again, no_wait) = f.drain_person_merges(&mut rng);+ assert!(again.is_empty());+ assert_eq!(no_wait, Duration::ZERO);+ }++ #[test]+ fn dangerous_merges_pair_each_user_with_one_partner() {+ let mix = TrafficMix {+ dangerous_merges: 100,+ ..Default::default()+ };+ let f = factory_with(10, mix, Duration::ZERO);+ let mut rng = StdRng::seed_from_u64(9);+ let index = |id: &str| {+ id.strip_prefix("loadgen-user-")+ .unwrap()+ .parse::<u64>()+ .unwrap()+ };++ for event in f.batch(50, &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);+ }+ }++ #[test]+ fn a_user_without_a_partner_sends_a_plain_event() {+ let mix = TrafficMix {+ dangerous_merges: 100,+ ..Default::default()+ };+ let f = factory_with(1, mix, Duration::ZERO);+ let mut rng = StdRng::seed_from_u64(10);++ for event in f.batch(5, &mut rng) {+ assert!(["a", "b"].contains(&event.event.as_str()));+ assert!(!event.properties.contains_key("alias"));+ }}}diff --git a/rust/capture-load-gen/src/main.rs b/rust/capture-load-gen/src/main.rsindex 868fad7a8784..1c5a423780f9 100644--- a/rust/capture-load-gen/src/main.rs+++ b/rust/capture-load-gen/src/main.rs@@ -14,7 +14,7 @@ use rand::SeedableRng;use tokio::sync::Notify;use capture_load_gen::client::CaptureClient;-use capture_load_gen::event::{BatchPayload, EventFactory};+use capture_load_gen::event::{BatchPayload, EventFactory, TrafficMix};use capture_load_gen::stats::{self, Counters};use capture_load_gen::{reset, verify};@@ -81,14 +81,31 @@ struct Cli {prop_bytes: usize,/// Percentage of events that are person updates (carry a `$set` payload).- /// Together with `--percent-merges` must not exceed 100.+ /// The `--percent-*` flags together must not exceed 100.#[arg(long, default_value_t = 0, value_parser = clap::value_parser!(u8).range(0..=100))]percent_person_updates: u8,- /// Percentage of events that are merges (`$identify` folding a fresh- /// anonymous distinct id into a pool user).+ /// Percentage of events that are attaches: an `$identify` claiming a fresh+ /// anonymous distinct id, which has no person, so it joins the pool user's.#[arg(long, default_value_t = 0, value_parser = clap::value_parser!(u8).range(0..=100))]- percent_merges: u8,+ percent_attaches: u8,++ /// Percentage of events spent on person merges. Each takes two events: a+ /// fresh anonymous id sends one of its own, then an `$identify` claims it,+ /// so the merge folds one person into another. Ids still unclaimed when the+ /// load ends are claimed then, on top of `--count` and after `--duration`.+ #[arg(long, default_value_t = 0, value_parser = clap::value_parser!(u8).range(0..=100))]+ percent_person_merges: u8,++ /// How long a seeded anonymous id waits for its `$identify`, so ingestion+ /// has usually created its person first, e.g. "10s".+ #[arg(long, value_parser = humantime::parse_duration, default_value = "10s")]+ person_merge_delay: Duration,++ /// Percentage of events that are `$merge_dangerously` between a pool user+ /// and its fixed partner; a pair already merged is a no-op.+ #[arg(long, default_value_t = 0, value_parser = clap::value_parser!(u8).range(0..=100))]+ percent_dangerous_merges: u8,/// Per-request HTTP timeout in seconds.#[arg(long, default_value_t = 30)]@@ -224,6 +241,34 @@ fn claim(remaining: &AtomicU64, batch: usize) -> u64 {}}+/// Claims the anonymous ids still seeded when the load ends, so no person merge is left half done.+async fn drain_person_merges(shared: &Shared, batch_size: usize, hist: &mut Histogram<u64>) {+ let mut rng = StdRng::from_entropy();+ let (claims, wait) = shared.factory.drain_person_merges(&mut rng);+ if claims.is_empty() {+ return;+ }+ println!(+ "[load] claiming {} seeded anonymous ids in {:.1}s",+ claims.len(),+ wait.as_secs_f64()+ );+ tokio::time::sleep(wait).await;+ for batch in claims.chunks(batch_size) {+ let body = match shared.client.encode(batch) {+ Ok(body) => body,+ Err(e) => {+ tracing::warn!("encode error: {e:#}");+ shared.counters.record(false, 0);+ continue;+ }+ };+ let result = shared.client.send(body).await;+ hist.saturating_record(result.latency.as_micros() as u64);+ shared.counters.record(result.ok, batch.len() as u64);+ }+}+async fn run_worker(shared: Shared, mode: Mode) -> Histogram<u64> {let mut hist = stats::new_histogram();let mut rng = StdRng::from_entropy();@@ -297,15 +342,16 @@ async fn main() -> Result<()> {if cli.concurrency == 0 {bail!("--concurrency must be > 0");}- if cli- .percent_person_updates- .saturating_add(cli.percent_merges)- > 100- {+ let mix = TrafficMix {+ person_updates: cli.percent_person_updates,+ attaches: cli.percent_attaches,+ person_merges: cli.percent_person_merges,+ dangerous_merges: cli.percent_dangerous_merges,+ };+ if mix.total() > 100 {bail!(- "--percent-person-updates ({}) + --percent-merges ({}) must not exceed 100",- cli.percent_person_updates,- cli.percent_merges+ "the --percent-* flags sum to {} and must not exceed 100",+ mix.total());}@@ -313,8 +359,8 @@ async fn main() -> Result<()> {cli.distinct_ids,cli.event_names.clone(),cli.prop_bytes,- cli.percent_person_updates,- cli.percent_merges,+ mix,+ cli.person_merge_delay,));if cli.dry_run {@@ -407,6 +453,7 @@ async fn main() -> Result<()> {merged.add(&hist).ok();}}+ drain_person_merges(&shared, cli.batch_size, &mut merged).await;stop.notify_one();reporter.await.ok();