: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
chore(personhog): bound the traffic bed's person property growth (#82562)
José Sequeira465f7cf799b7
diff --git a/rust/personhog-test-harness/src/cli.rs b/rust/personhog-test-harness/src/cli.rsindex b39a405fb056..16514973ee7e 100644--- a/rust/personhog-test-harness/src/cli.rs+++ b/rust/personhog-test-harness/src/cli.rs@@ -9,6 +9,10 @@ pub const DEFAULT_PERSONS_DB_URL: &str =/// The dev-stack leader-mode router (bin/mprocs.yaml `personhog-router-leader`).pub const DEV_STACK_ROUTER_URL: &str = "http://127.0.0.1:50054";+/// Keys a traffic lane holds a person's document at. The changelog carries+/// the whole document per update, so this multiplies the bed's byte rate.+pub const DEFAULT_KEYS_PER_PERSON: u64 = 64;+#[derive(Parser)]#[command(name = "personhog-test-harness",@@ -92,6 +96,12 @@ pub struct BlastArgs {#[arg(long, default_value = "harness_")]pub property_prefix: String,+ /// Distinct property keys a person's document settles at. Workers+ /// share this budget, so the document holds its size as concurrency+ /// changes.+ #[arg(long, default_value_t = DEFAULT_KEYS_PER_PERSON)]+ pub property_keys_per_person: u64,+/// Read back each person with STRONG consistency after the blast and/// verify that every acked write is present.#[arg(long, default_value_t = true, action = clap::ArgAction::Set)]@@ -379,11 +389,21 @@ pub struct TrafficArgs {)]pub pg_target_table: String,- /// Persons seeded per epoch. The pool rotates every epoch so journal- /// keys never grow a document toward the admission size ceiling.+ /// Persons seeded per epoch, rotated at epoch close.#[arg(long, env = "TRAFFIC_POOL_SIZE", default_value_t = 200)]pub pool_size: u32,+ /// Distinct property keys a person's document settles at. Rotation+ /// alone does not bound it: writes per person scale with the drawn+ /// rate, so a high enough rate reaches the admission ceiling inside+ /// one epoch.+ #[arg(+ long,+ env = "TRAFFIC_PROPERTY_KEYS_PER_PERSON",+ default_value_t = DEFAULT_KEYS_PER_PERSON+ )]+ pub property_keys_per_person: u64,+/// Verification epoch length: traffic runs, then the epoch's acked/// writes are verified against strong reads and Postgres, then the/// person pool rotates.diff --git a/rust/personhog-test-harness/src/scenarios/blast.rs b/rust/personhog-test-harness/src/scenarios/blast.rsindex 88e6860e8c3b..32a0874b722a 100644--- a/rust/personhog-test-harness/src/scenarios/blast.rs+++ b/rust/personhog-test-harness/src/scenarios/blast.rs@@ -37,7 +37,11 @@ pub async fn run(args: BlastArgs) -> Result<()> {args.duration,args.concurrency,None,- &args.property_prefix,+ &PropertyPlan::new(+ args.property_prefix.clone(),+ args.property_keys_per_person,+ args.concurrency,+ ),&collector,&state,Arc::new(AtomicBool::new(false)),@@ -64,6 +68,38 @@ pub async fn run(args: BlastArgs) -> Result<()> {Ok(())}+/// A fixed set of property keys a traffic lane picks from at random.+///+/// A key per write instead grows the document without limit, and since+/// every update ships the whole person to the changelog, the byte rate+/// then grows quadratically in the writes a person has taken. Worker id+/// stays in the key: two workers sharing one would race, because acks are+/// journaled in arrival order, not application order.+#[derive(Clone)]+pub struct PropertyPlan {+ prefix: String,+ keys_per_worker: u64,+}++impl PropertyPlan {+ /// Splits the budget across workers so document size holds still when+ /// concurrency changes. Every worker needs a key of its own, so the+ /// floor is one each: a budget under the worker count delivers+ /// `concurrency` keys per person, and traffic mode refuses it.+ pub fn new(prefix: String, keys_per_person: u64, concurrency: usize) -> Self {+ let keys_per_worker = (keys_per_person.max(1) / concurrency.max(1) as u64).max(1);+ Self {+ prefix,+ keys_per_worker,+ }+ }++ fn key(&self, worker_id: usize, rng: &mut impl Rng) -> String {+ let slot = rng.gen_range(0..self.keys_per_worker);+ format!("{}{worker_id}_{slot}", self.prefix)+ }+}+/// Drive concurrent property updates against random targets until the/// duration elapses, journaling every acked write into `state`.///@@ -82,7 +118,7 @@ pub async fn run_traffic(duration: Duration,concurrency: usize,rate_per_sec: Option<f64>,- property_prefix: &str,+ property_plan: &PropertyPlan,collector: &Arc<StatsCollector>,state: &PersonState,stop: Arc<AtomicBool>,@@ -96,11 +132,10 @@ pub async fn run_traffic(let collector = collector.clone();let state = state.clone();let person_ids = person_ids.clone();- let prefix = property_prefix.to_string();+ let plan = property_plan.clone();let stop = stop.clone();handles.push(tokio::spawn(async move {- let mut counter: u64 = 0;let mut rng = rand::rngs::StdRng::from_entropy();let mut pacer = worker_tick.map(|tick| {let mut ticker = interval(tick);@@ -113,9 +148,8 @@ pub async fn run_traffic(pacer.tick().await;}let person_id = person_ids[rng.gen_range(0..person_ids.len())];- counter += 1;- let key = format!("{prefix}{worker_id}_{counter}");+ let key = plan.key(worker_id, &mut rng);let value = Uuid::new_v4().to_string();let props = json!({ &key: &value });@@ -147,6 +181,7 @@ pub async fn run_traffic(Err(e) => {collector.writes.record_failure();traffic_metrics::record_write_failed(traffic_metrics::LANE_BLAST, &e);+ state.record_write_uncertain(person_id, &key).await;// `{:#}` prints the full anyhow chain — the outer// context alone hides the gRPC status underneath.tracing::warn!(person_id, error = format!("{e:#}"), "write failed");@@ -251,4 +286,53 @@ mod tests {assert!(per_worker_tick(0.0, 10) <= Duration::from_secs(3600));assert!(per_worker_tick(10.0, 0) <= Duration::from_secs(1));}++ /// The document bound is the whole point: a person may never collect+ /// more distinct keys than the budget, however long the run goes.+ #[test]+ fn workers_never_exceed_their_share_of_the_key_budget() {+ let mut rng = rand::rngs::StdRng::seed_from_u64(7);+ let plan = PropertyPlan::new("p_".to_string(), 64, 8);++ let mut keys = std::collections::HashSet::new();+ for _ in 0..100_000 {+ keys.insert(plan.key(3, &mut rng));+ keys.insert(plan.key(5, &mut rng));+ }++ // 64 across 8 workers is 8 each, and the two workers never collide.+ assert_eq!(keys.len(), 16);+ assert!(keys+ .iter()+ .all(|k| k.starts_with("p_3_") || k.starts_with("p_5_")));+ }++ /// Splitting by concurrency is what keeps the bound stable while the+ /// bed scales workers, so the per-person total must not track it.+ #[test]+ fn the_key_budget_holds_as_concurrency_changes() {+ for concurrency in [1usize, 4, 16, 64] {+ let mut rng = rand::rngs::StdRng::seed_from_u64(11);+ let plan = PropertyPlan::new("p_".to_string(), 64, concurrency);+ let mut distinct = std::collections::HashSet::new();+ for worker_id in 0..concurrency {+ for _ in 0..5_000 {+ distinct.insert(plan.key(worker_id, &mut rng));+ }+ }+ assert_eq!(distinct.len(), 64, "concurrency={concurrency}");+ }+ // Below the worker count the budget cannot be honoured: each+ // worker still takes one key, so the person collects `concurrency`+ // of them. Traffic mode rejects that configuration outright.+ let mut rng = rand::rngs::StdRng::seed_from_u64(13);+ let plan = PropertyPlan::new("p_".to_string(), 2, 8);+ let mut distinct = std::collections::HashSet::new();+ for worker_id in 0..8 {+ for _ in 0..100 {+ distinct.insert(plan.key(worker_id, &mut rng));+ }+ }+ assert_eq!(distinct.len(), 8);+ }}diff --git a/rust/personhog-test-harness/src/scenarios/gate.rs b/rust/personhog-test-harness/src/scenarios/gate.rsindex c8767131cec2..9120927421f3 100644--- a/rust/personhog-test-harness/src/scenarios/gate.rs+++ b/rust/personhog-test-harness/src/scenarios/gate.rs@@ -10,7 +10,7 @@ use sqlx::postgres::PgPool;use personhog_proto::personhog::identity::v1::GetOrCreatePersonEntry;-use crate::cli::GateArgs;+use crate::cli::{GateArgs, DEFAULT_KEYS_PER_PERSON};use crate::client::{HarnessClient, IdentityClient};use crate::report::print_report;use crate::scenarios::{blast, consistency};@@ -279,7 +279,11 @@ pub async fn run(args: GateArgs) -> Result<()> {duration,concurrency,None,- "harness_gate_",+ &blast::PropertyPlan::new(+ "harness_gate_".to_string(),+ DEFAULT_KEYS_PER_PERSON,+ concurrency,+ ),&collector,&state,Arc::new(AtomicBool::new(false)),diff --git a/rust/personhog-test-harness/src/scenarios/traffic.rs b/rust/personhog-test-harness/src/scenarios/traffic.rsindex d970a54815ae..396e5e3a146e 100644--- a/rust/personhog-test-harness/src/scenarios/traffic.rs+++ b/rust/personhog-test-harness/src/scenarios/traffic.rs@@ -73,6 +73,16 @@ fn validate_args(args: &TrafficArgs) -> Result<()> {args.probers);}+ if args.property_keys_per_person < args.concurrency as u64 {+ // Workers cannot share a key without racing the journal, so each+ // holds at least one and a smaller budget would quietly deliver+ // `concurrency` keys per person instead of what was asked for.+ bail!(+ "property_keys_per_person ({}) must be at least concurrency ({})",+ args.property_keys_per_person,+ args.concurrency+ );+ }if args.team_ids.is_empty() {bail!("team_ids must not be empty");}@@ -273,7 +283,11 @@ pub async fn run(args: TrafficArgs) -> Result<()> {let collector = collector.clone();let state = state.clone();let (duration, concurrency) = (args.epoch, args.concurrency);- let prefix = format!("traffic_e{epoch}_");+ let plan = blast::PropertyPlan::new(+ format!("traffic_e{epoch}_"),+ args.property_keys_per_person,+ concurrency,+ );let stop = shutdown.clone();tokio::spawn(async move {blast::run_traffic(@@ -283,7 +297,7 @@ pub async fn run(args: TrafficArgs) -> Result<()> {duration,concurrency,Some(lane_rate),- &prefix,+ &plan,&collector,&state,stop,@@ -804,6 +818,7 @@ async fn shutdown_signal() {#[cfg(test)]mod tests {use super::*;+ use crate::cli::DEFAULT_KEYS_PER_PERSON;/// Needs the CI gate's etcd; run explicitly with `--ignored`.#[tokio::test]@@ -854,6 +869,7 @@ mod tests {persons_db_url: "postgres://unused".to_string(),pg_target_table: "personhog_person_tmp".to_string(),pool_size: 200,+ property_keys_per_person: DEFAULT_KEYS_PER_PERSON,epoch: Duration::from_secs(300),rate_min: 50.0,rate_max: 500.0,@@ -912,6 +928,12 @@ mod tests {probers: 0,..valid.clone()},+ // Fewer keys than workers cannot be honoured: each worker+ // needs its own, so the person would collect `concurrency`.+ TrafficArgs {+ property_keys_per_person: valid.concurrency as u64 - 1,+ ..valid.clone()+ },TrafficArgs {rate_min: 0.0,..valid.clone()diff --git a/rust/personhog-test-harness/src/state.rs b/rust/personhog-test-harness/src/state.rsindex f27656641814..002184e3ce47 100644--- a/rust/personhog-test-harness/src/state.rs+++ b/rust/personhog-test-harness/src/state.rs@@ -7,9 +7,12 @@ use tokio::sync::RwLock;use crate::report::ConsistencyViolation;/// Journal of acked writes. Every property write acked by the leader path is-/// recorded here; verification asserts each one is visible afterwards. Keys-/// are unique per write, so the final state must contain every acked key-/// regardless of the interleaving of concurrent writers.+/// recorded here; verification asserts each one is visible afterwards.+///+/// Keys are reused, so the journal is only authoritative because each key+/// belongs to one worker and workers write sequentially. A write whose+/// outcome is unknown breaks that and drops its key — see+/// [`PersonState::record_write_uncertain`].#[derive(Clone)]pub struct PersonState {inner: Arc<RwLock<Journal>>,@@ -146,6 +149,16 @@ impl PersonState {}}+ /// Drop a key whose write errored: it may still have applied, so the+ /// journalled value could be superseded and asserting it would fail a+ /// correct stack. The next ack for the key restores coverage.+ pub async fn record_write_uncertain(&self, person_id: i64, key: &str) {+ let mut journal = self.inner.write().await;+ if let Some(entry) = journal.persons.get_mut(&person_id) {+ entry.written_properties.remove(key);+ }+ }+/// Journal an ack whose response carried no person body. The write is/// acked, so its keys must still be verified like any other — but the/// response contract (updates return the updated person) broke, which@@ -418,6 +431,41 @@ mod tests {assert!(snapshot[&1].written_properties.contains_key("k3"));}+ /// With keys reused, a write that errored but still applied would+ /// overwrite a journalled value and manufacture a violation against a+ /// correct stack. Dropping the key is what makes reuse safe, and the+ /// next ack has to bring it back or coverage decays over a run.+ #[tokio::test]+ async fn an_uncertain_write_drops_its_key_until_the_next_ack() {+ let state = PersonState::new();+ state+ .record_write(1, 1, props(&[("k1", "v1"), ("k2", "v2")]))+ .await;++ state.record_write_uncertain(1, "k1").await;+ // k1 can no longer be asserted; k2 is untouched.+ assert!(state+ .verify(1, &json!({"k1": "raced", "k2": "v2"}), 1)+ .await+ .is_empty());+ assert_eq!(+ violation_keys(state.verify(1, &json!({"k1": "raced"}), 1).await),+ vec!["k2"]+ );++ // A later ack restores the key, and it verifies again.+ state.record_write(1, 2, props(&[("k1", "v3")])).await;+ assert_eq!(+ violation_keys(+ state+ .verify(1, &json!({"k1": "stale", "k2": "v2"}), 2)+ .await+ ),+ vec!["k1"]+ );+ assert!(state.take_anomalies().await.is_empty());+ }+#[tokio::test]async fn strong_read_below_max_acked_version_is_a_violation() {let state = PersonState::new();