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.

fix(personhog): make traffic bed instances overlap-safe and failure reasons truthful (#75717)

Zach Brown7e62a80974d2
diff --git a/rust/personhog-test-harness/src/scenarios/blast.rs b/rust/personhog-test-harness/src/scenarios/blast.rs
index 3cb4e978d8ca..88e6860e8c3b 100644
--- a/rust/personhog-test-harness/src/scenarios/blast.rs
+++ b/rust/personhog-test-harness/src/scenarios/blast.rs
@@ -133,19 +133,20 @@ pub async fn run_traffic(
let mut written = HashMap::new();
written.insert(key, serde_json::Value::String(value));
match resp.person {
- Some(person) => {
+ Some(person) if resp.updated => {
state.record_write(person_id, person.version, written).await
}
+ // A no-change ack (an at-least-once replay whose
+ // first application landed) echoes the current
+ // version, owned by some other write — assert
+ // the keys, claim no version.
+ Some(_) => state.record_write_no_change(person_id, written).await,
None => state.record_ack_anomaly(person_id, written).await,
}
}
Err(e) => {
collector.writes.record_failure();
- traffic_metrics::record_write_failed(
- traffic_metrics::LANE_BLAST,
- &e,
- stop.load(Ordering::Relaxed),
- );
+ traffic_metrics::record_write_failed(traffic_metrics::LANE_BLAST, &e);
// `{:#}` prints the full anyhow chain — the outer
// context alone hides the gRPC status underneath.
tracing::warn!(person_id, error = format!("{e:#}"), "write failed");
diff --git a/rust/personhog-test-harness/src/scenarios/consistency.rs b/rust/personhog-test-harness/src/scenarios/consistency.rs
index b902cef0e097..c43303d71bfc 100644
--- a/rust/personhog-test-harness/src/scenarios/consistency.rs
+++ b/rust/personhog-test-harness/src/scenarios/consistency.rs
@@ -226,11 +226,7 @@ pub async fn run_probers(
}
Err(e) => {
collector.writes.record_failure();
- traffic_metrics::record_write_failed(
- traffic_metrics::LANE_PROBER,
- &e,
- stop.load(Ordering::Relaxed),
- );
+ traffic_metrics::record_write_failed(traffic_metrics::LANE_PROBER, &e);
tracing::warn!(person_id, error = %e, "probe write failed");
continue;
}
@@ -238,9 +234,13 @@ pub async fn run_probers(
let mut written = HashMap::new();
written.insert(key.clone(), serde_json::Value::String(marker.clone()));
match response.person {
- Some(person) => {
+ Some(person) if response.updated => {
state.record_write(person_id, person.version, written).await;
}
+ // A no-change ack (an at-least-once replay whose first
+ // application landed) echoes a version owned by some
+ // other write — assert the keys, claim no version.
+ Some(_) => state.record_write_no_change(person_id, written).await,
None => {
// Already flagged as a violation by the journal; the
// keys still get end-of-run verification.
@@ -293,11 +293,7 @@ pub async fn run_probers(
collector.reads.record_failure();
traffic_metrics::record_read_failed(
traffic_metrics::LANE_PROBER,
- if stop.load(Ordering::Relaxed) {
- traffic_metrics::REASON_SHUTDOWN
- } else {
- traffic_metrics::status_reason(&e)
- },
+ traffic_metrics::status_reason(&e),
);
tracing::warn!(person_id, error = %e, "probe read failed");
}
diff --git a/rust/personhog-test-harness/src/scenarios/traffic.rs b/rust/personhog-test-harness/src/scenarios/traffic.rs
index 84e503b8fc50..e4d2abfc40ac 100644
--- a/rust/personhog-test-harness/src/scenarios/traffic.rs
+++ b/rust/personhog-test-harness/src/scenarios/traffic.rs
@@ -72,6 +72,12 @@ fn validate_args(args: &TrafficArgs) -> Result<()> {
seed::validate_table_name(&args.pg_target_table)
}
+/// How old a leftover row must be before the startup janitor reaps it.
+/// Far above any epoch length, so a live sibling pod's pool is never
+/// touched; far below forever, so crashed instances' rows don't
+/// accumulate.
+const STALE_ROW_AGE: Duration = Duration::from_secs(3600);
+
pub async fn run(args: TrafficArgs) -> Result<()> {
validate_args(&args)?;
@@ -95,11 +101,12 @@ pub async fn run(args: TrafficArgs) -> Result<()> {
// leader hasn't claimed partitions yet.
sentinel_round_trip(&client, &pool, &args.pg_target_table, args.team_id).await?;
- // A crashed prior run leaves rows behind (including the sentinel row
- // just written); both teams belong to the harness, so boot from a
- // clean slate.
+ // A crashed prior run leaves rows behind; reap the ones old enough
+ // that they cannot belong to a live sibling — a rolling restart
+ // briefly runs two bed pods against the same team, each on its own
+ // disjoint id pool, and a fresh row is the sibling's business.
for team in [args.team_id, args.hostile_team_id] {
- seed::cleanup_team(&pool, &args.pg_target_table, team).await?;
+ seed::reap_stale_team_rows(&pool, &args.pg_target_table, team, STALE_ROW_AGE).await?;
}
// Hostile targets live for the process lifetime: their documents stay
@@ -146,6 +153,16 @@ pub async fn run(args: TrafficArgs) -> Result<()> {
gauge!("personhog_traffic_epoch_target_rps").set(rate);
tracing::info!(epoch, rate = format!("{rate:.0}"), "epoch starting");
+ // The hostile pool outlives epochs; keep its liveness stamp fresh
+ // so a sibling pod's startup janitor never reaps it mid-use.
+ seed::refresh_created_at(
+ &pool,
+ &args.pg_target_table,
+ args.hostile_team_id,
+ &hostile_ids,
+ )
+ .await?;
+
let person_ids = Arc::new(
seed::seed_persons(&pool, &args.pg_target_table, args.team_id, args.pool_size).await?,
);
@@ -236,14 +253,19 @@ pub async fn run(args: TrafficArgs) -> Result<()> {
);
// Rotate the pool: delete this epoch's persons so the next epoch
- // starts from fresh documents.
- seed::cleanup_team(&pool, &args.pg_target_table, args.team_id).await?;
+ // starts from fresh documents. By id, not by team — a successor
+ // pod may already be running its own pool against this team.
+ seed::cleanup_persons(&pool, &args.pg_target_table, args.team_id, &person_ids).await?;
if shutdown.load(Ordering::SeqCst) {
tracing::info!("cleaning up and exiting");
- for team in [args.team_id, args.hostile_team_id] {
- seed::cleanup_team(&pool, &args.pg_target_table, team).await?;
- }
+ seed::cleanup_persons(
+ &pool,
+ &args.pg_target_table,
+ args.hostile_team_id,
+ &hostile_ids,
+ )
+ .await?;
return Ok(());
}
}
@@ -400,6 +422,14 @@ async fn sentinel_round_trip(
);
}
tracing::info!("sentinel round-trip verified: router and database agree");
+ sqlx::query(&format!(
+ "DELETE FROM {table} WHERE team_id = $1 AND id = $2"
+ ))
+ .bind(team)
+ .bind(person_id)
+ .execute(pool)
+ .await
+ .context("deleting the sentinel person")?;
Ok(())
}
diff --git a/rust/personhog-test-harness/src/seed.rs b/rust/personhog-test-harness/src/seed.rs
index 4f2651ad85ea..f076282dda70 100644
--- a/rust/personhog-test-harness/src/seed.rs
+++ b/rust/personhog-test-harness/src/seed.rs
@@ -1,3 +1,5 @@
+use std::time::Duration;
+
use anyhow::{bail, Context, Result};
use sqlx::postgres::PgPool;
@@ -74,6 +76,100 @@ pub async fn cleanup_team(pool: &PgPool, table: &str, team_id: i64) -> Result<u6
Ok(deleted)
}
+/// Delete exactly the given person rows. Instance-scoped cleanup for the
+/// traffic bed: a rolling restart briefly runs two bed pods against the
+/// same team, and a team-wide delete from either tears the other's live
+/// pool out from under it — manufacturing the exact failed-write spike
+/// the bed exists to catch in the stack. Each pod's pool is a disjoint
+/// id set, so deleting by id makes overlap harmless. Person rows only:
+/// the traffic path never creates distinct-id rows (those belong to the
+/// gate's identity-service create path).
+pub async fn cleanup_persons(pool: &PgPool, table: &str, team_id: i64, ids: &[i64]) -> Result<u64> {
+ validate_table_name(table)?;
+ if ids.is_empty() {
+ return Ok(0);
+ }
+ let team: i32 = team_id.try_into().context("team_id out of i32 range")?;
+ let deleted = sqlx::query(&format!(
+ "DELETE FROM {table} WHERE team_id = $1 AND id = ANY($2)"
+ ))
+ .bind(team)
+ .bind(ids)
+ .execute(pool)
+ .await
+ .with_context(|| format!("cleaning up persons in {table}"))?
+ .rows_affected();
+ Ok(deleted)
+}
+
+/// Re-stamp `created_at` on the given rows. The janitor's age guard
+/// reads `created_at` as a liveness stamp, so rows that live across
+/// epochs (the hostile pool) must be refreshed each epoch — otherwise a
+/// successor pod's janitor reaps them mid-use once their seeding time
+/// ages past the threshold, even though their owner is still running.
+pub async fn refresh_created_at(
+ pool: &PgPool,
+ table: &str,
+ team_id: i64,
+ ids: &[i64],
+) -> Result<()> {
+ validate_table_name(table)?;
+ if ids.is_empty() {
+ return Ok(());
+ }
+ let team: i32 = team_id.try_into().context("team_id out of i32 range")?;
+ sqlx::query(&format!(
+ "UPDATE {table} SET created_at = now() WHERE team_id = $1 AND id = ANY($2)"
+ ))
+ .bind(team)
+ .bind(ids)
+ .execute(pool)
+ .await
+ .with_context(|| format!("refreshing created_at in {table}"))?;
+ Ok(())
+}
+
+/// Reap a team's person rows older than `older_than` — the startup
+/// janitor for leftovers from crashed or killed instances. The age guard
+/// keeps it off a live sibling pod's fresh pool during a rolling-restart
+/// overlap, while dead instances' rows age into eligibility. The
+/// distinct-id tables are swept team-wide and unguarded: the traffic
+/// path never writes them, so any row there is a leftover from a gate
+/// run against this team. They go first — their FK references the person
+/// rows.
+pub async fn reap_stale_team_rows(
+ pool: &PgPool,
+ table: &str,
+ team_id: i64,
+ older_than: Duration,
+) -> Result<u64> {
+ validate_table_name(table)?;
+ let team: i32 = team_id.try_into().context("team_id out of i32 range")?;
+
+ sqlx::query("DELETE FROM posthog_persondistinctid WHERE team_id = $1")
+ .bind(team)
+ .execute(pool)
+ .await
+ .context("deleting distinct ids")?;
+ sqlx::query("DELETE FROM posthog_personlessdistinctid WHERE team_id = $1")
+ .bind(team)
+ .execute(pool)
+ .await
+ .context("deleting personless distinct ids")?;
+
+ let deleted = sqlx::query(&format!(
+ "DELETE FROM {table} \
+ WHERE team_id = $1 AND created_at < now() - make_interval(secs => $2)"
+ ))
+ .bind(team)
+ .bind(older_than.as_secs_f64())
+ .execute(pool)
+ .await
+ .with_context(|| format!("reaping stale rows in {table}"))?
+ .rows_affected();
+ Ok(deleted)
+}
+
/// The table name comes from the operator's CLI/env, but sanity-check it
/// anyway since it is interpolated into SQL (identifiers cannot be bound).
pub fn validate_table_name(table: &str) -> Result<()> {
diff --git a/rust/personhog-test-harness/src/state.rs b/rust/personhog-test-harness/src/state.rs
index 022bfe0a1720..abeee0107a90 100644
--- a/rust/personhog-test-harness/src/state.rs
+++ b/rust/personhog-test-harness/src/state.rs
@@ -47,6 +47,11 @@ impl PersonState {
}
}
+ /// Journal an ack that applied a change. Only these acks claim their
+ /// version: the leader assigns each applied update a fresh version
+ /// under the per-person lock, so two applied acks sharing one version
+ /// means two writes served from the same base state — the split-brain
+ /// signature the duplicate check exists to catch.
pub async fn record_write(
&self,
person_id: i64,
@@ -77,6 +82,32 @@ impl PersonState {
}
}
+ /// Journal an ack whose response reported no change applied. The data
+ /// is durable — the keys were already present, so they verify like any
+ /// other write — but the echoed version belongs to whichever earlier
+ /// write set it, not to this one, so no version is claimed. This is
+ /// the at-least-once replay shape: a redelivered write whose first
+ /// application succeeded echoes the person's current version, which a
+ /// concurrent writer may legitimately own.
+ pub async fn record_write_no_change(
+ &self,
+ person_id: i64,
+ properties: HashMap<String, serde_json::Value>,
+ ) {
+ let mut journal = self.inner.write().await;
+ let entry = journal
+ .persons
+ .entry(person_id)
+ .or_insert_with(|| ExpectedPerson {
+ written_properties: HashMap::new(),
+ last_version: 0,
+ acked_versions: HashSet::new(),
+ });
+ for (k, v) in properties {
+ entry.written_properties.insert(k, v);
+ }
+ }
+
/// 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
@@ -224,6 +255,35 @@ mod tests {
}
}
+ /// A no-change ack (an at-least-once replay echo) must journal its
+ /// keys without claiming the echoed version — otherwise a replay
+ /// racing a concurrent writer manufactures a false duplicate-version
+ /// violation. A real duplicate (two applied acks, one version) must
+ /// still be flagged.
+ #[tokio::test]
+ async fn no_change_acks_journal_keys_without_claiming_versions() {
+ let state = PersonState::new();
+ state.record_write(1, 41, props(&[("k1", "v1")])).await;
+ // The replay echo: version 41 is current, but this ack applied
+ // nothing. No violation, keys merged.
+ state
+ .record_write_no_change(1, props(&[("k2", "v2")]))
+ .await;
+ assert!(state.take_anomalies().await.is_empty());
+ let snapshot = state.snapshot().await;
+ let entry = &snapshot[&1];
+ assert_eq!(entry.written_properties.len(), 2);
+ assert_eq!(entry.last_version, 41);
+
+ // Two applied acks sharing a version stay a violation.
+ let state = PersonState::new();
+ state.record_write(2, 41, props(&[("a", "1")])).await;
+ state.record_write(2, 41, props(&[("b", "2")])).await;
+ let anomalies = state.take_anomalies().await;
+ assert_eq!(anomalies.len(), 1);
+ assert_eq!(anomalies[0].key, "__ack_version_duplicate");
+ }
+
#[tokio::test]
async fn journal_merges_keys_and_keeps_the_max_acked_version() {
let state = PersonState::new();
diff --git a/rust/personhog-test-harness/src/traffic_metrics.rs b/rust/personhog-test-harness/src/traffic_metrics.rs
index 7ca608b9a2e9..c4c11acbddf0 100644
--- a/rust/personhog-test-harness/src/traffic_metrics.rs
+++ b/rust/personhog-test-harness/src/traffic_metrics.rs
@@ -7,6 +7,7 @@
//! that a consistency violation becomes a page-shaped signal rather than
//! a process exit code.
+use std::error::Error as _;
use std::process;
use std::time::Duration;
@@ -27,11 +28,16 @@ pub const LANE_BLAST: &str = "blast";
pub const LANE_PROBER: &str = "prober";
pub const LANE_VERIFY: &str = "verify";
-/// Metric label for a failed request: the gRPC status code the client
-/// wrapped in anyhow context, in the shared vocabulary every personhog
-/// service labels with.
+/// Metric label for a failed request. A status the server actually sent
+/// arrives as a grpc-status trailer and keeps its code — a live server's
+/// verdict. A status tonic synthesized from a dead connection (stream
+/// reset, GOAWAY, broken transport) carries the transport error as its
+/// `source`, and the code tonic picks for it is arbitrary — those become
+/// "transport", so a killed connection can never masquerade as a
+/// server-side cancel or timeout.
pub fn status_reason(err: &anyhow::Error) -> &'static str {
match err.downcast_ref::<tonic::Status>() {
+ Some(status) if status.source().is_some() => "transport",
Some(status) => code_as_str(status.code()),
None => NON_STATUS,
}
@@ -57,19 +63,17 @@ pub fn record_write_ok(lane: &'static str, elapsed: Duration) {
/// Record a write the stack refused or dropped. Latency is deliberately
/// not recorded: a timeout's duration is the deadline, not the stack's
/// service time, and mixing the two distorts the percentiles.
-/// Reason label for failures observed after the shutdown signal: the
-/// harness's exit races its own in-flight requests (and any deploy
-/// rolling the stack under it), so these are quarantined under one
-/// reason instead of polluting the genuine failure reasons the
-/// dashboards are read by.
-pub const REASON_SHUTDOWN: &str = "shutdown";
-
-pub fn record_write_failed(lane: &'static str, err: &anyhow::Error, shutting_down: bool) {
+///
+/// The reason is always the request's true outcome, shutdown or not: the
+/// bed's own teardown completes in-flight requests rather than aborting
+/// them, so anything failing during a roll is stack signal — exactly the
+/// "deploys must not fail traffic" promise the bed exists to check.
+pub fn record_write_failed(lane: &'static str, err: &anyhow::Error) {
counter!(
"personhog_traffic_writes_total",
"lane" => lane,
"outcome" => "failed",
- "reason" => if shutting_down { REASON_SHUTDOWN } else { status_reason(err) },
+ "reason" => status_reason(err),
)
.increment(1);
}
@@ -150,7 +154,10 @@ pub fn record_violations(epoch: u64, violations: &[ConsistencyViolation]) {
#[cfg(test)]
mod tests {
+ use std::io::{Error as IoError, ErrorKind};
+
use serde_json::{json, Value};
+ use tonic::Status;
use super::*;
@@ -179,4 +186,24 @@ mod tests {
assert_eq!(violation_kind(&violation(key)), kind, "{key}");
}
}
+
+ /// A status the server sent over the wire keeps its code; one tonic
+ /// synthesized from a broken connection (it carries the transport
+ /// error as its `source`) must report as "transport" — otherwise a
+ /// killed connection is indistinguishable from a server-side cancel
+ /// or timeout on the dashboards.
+ #[test]
+ fn status_reason_separates_wire_statuses_from_transport_failures() {
+ let wire = anyhow::Error::new(Status::cancelled("server said stop"))
+ .context("UpdatePersonProperties failed");
+ assert_eq!(status_reason(&wire), "cancelled");
+
+ let reset = IoError::new(ErrorKind::ConnectionReset, "peer reset");
+ let synthesized = anyhow::Error::new(Status::from_error(Box::new(reset)))
+ .context("UpdatePersonProperties failed");
+ assert_eq!(status_reason(&synthesized), "transport");
+
+ let not_a_status = anyhow::anyhow!("connect refused before any rpc");
+ assert_eq!(status_reason(&not_a_status), NON_STATUS);
+ }
}