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(personhog): run harness lifecycles through identity and the saga (#81462)

Zach Brownc4775d7c1cb9
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.yml
index 0327336a70ac..b73147236a6e 100644
--- a/.github/workflows/ci-rust.yml
+++ b/.github/workflows/ci-rust.yml
@@ -576,23 +576,28 @@ jobs:
# Unit tests for the harness's own verification logic — a
# false-negative verifier would pass gates that lost data.
+ # Ignored tests need the etcd this job already started, so
+ # they run here rather than in the plain test job.
- name: Test the harness verification logic
- run: cargo test -p personhog-test-harness
+ run: cargo test -p personhog-test-harness -- --include-ignored
- name: Run the e2e gate
run: |
./target/debug/personhog-test-harness gate \
--leaders 2 --partitions 4 --persons 100 --concurrency 10 --duration 10s
- # The identity-service create path: persons are created through
- # GetOrCreatePersonsByDistinctIds (stub insert on the primary,
- # then initial properties through the router to the owning
- # leader) and then updated through the router. Create acks are
- # journaled and held to the same visibility invariant as update
- # acks, through a leader kill and a scale-up. The identity
- # service writes the real posthog_person table (its distinct id
- # FKs require it), so the whole stack targets it here instead of
- # the default personhog_person_tmp.
+ # The identity-service lifecycle path: persons are created
+ # through GetOrCreatePersonsByDistinctIds (stub insert on the
+ # primary, then initial properties through the router to the
+ # owning leader), updated through the router, and finally
+ # deleted through the lifecycle saga, whose outcomes the gate
+ # asserts (all deleted, then all not_found on a re-delete
+ # under a fresh op id). Create acks are journaled and held to
+ # the same visibility invariant as update acks, through a
+ # leader kill and a scale-up. The identity service writes the
+ # real posthog_person table (its distinct id FKs require it),
+ # so the whole stack targets it here instead of the default
+ # personhog_person_tmp.
- name: Run the e2e gate creating persons via the identity service
run: |
./target/debug/personhog-test-harness gate \
diff --git a/rust/common/assignment-coordination/src/store.rs b/rust/common/assignment-coordination/src/store.rs
index 1188c256e044..de8d05ac55f8 100644
--- a/rust/common/assignment-coordination/src/store.rs
+++ b/rust/common/assignment-coordination/src/store.rs
@@ -1,8 +1,8 @@
use std::time::Duration;
use etcd_client::{
- Client, ConnectOptions, DeleteOptions, GetOptions, PutOptions, Txn, TxnResponse, WatchOptions,
- WatchStream,
+ Client, Compare, CompareOp, ConnectOptions, DeleteOptions, GetOptions, PutOptions, Txn, TxnOp,
+ TxnResponse, WatchOptions, WatchStream,
};
use serde::de::DeserializeOwned;
use serde::Serialize;
@@ -260,6 +260,23 @@ impl EtcdStore {
Ok(self.client.clone().txn(txn).await?)
}
+ /// Atomically create `key` bound to `lease_id`, only if it does not
+ /// exist; returns whether this call created it. The building block
+ /// for single-holder claims: the key lives and dies with the lease,
+ /// so revocation or expiry frees the claim for the next contender.
+ pub async fn put_if_absent(&self, key: &str, value: Vec<u8>, lease_id: i64) -> Result<bool> {
+ let _t = OpTimer::new("put_if_absent");
+ let txn = Txn::new()
+ .when(vec![Compare::version(key, CompareOp::Equal, 0)])
+ .and_then(vec![TxnOp::put(
+ key,
+ value,
+ Some(PutOptions::new().with_lease(lease_id)),
+ )]);
+ let resp = self.client.clone().txn(txn).await?;
+ Ok(resp.succeeded())
+ }
+
// ── Lease operations ─────────────────────────────────────────
pub async fn grant_lease(&self, ttl: i64) -> Result<i64> {
diff --git a/rust/personhog-test-harness/src/cli.rs b/rust/personhog-test-harness/src/cli.rs
index c6178dd5529d..ed9a3c82465f 100644
--- a/rust/personhog-test-harness/src/cli.rs
+++ b/rust/personhog-test-harness/src/cli.rs
@@ -335,6 +335,12 @@ pub struct TrafficArgs {
#[arg(long, env = "TRAFFIC_ROUTER_URL")]
pub router_url: String,
+ /// Identity service under test: the epoch pool is created through
+ /// get-or-create and rotated through the lifecycle delete saga, both
+ /// served on this address.
+ #[arg(long, env = "TRAFFIC_IDENTITY_URL")]
+ pub identity_url: String,
+
/// Master toggle. When false the process starts fully (guard, metrics,
/// liveness) but idles instead of driving traffic — so a deployed-but-
/// disabled harness is observably "off on purpose" rather than absent.
diff --git a/rust/personhog-test-harness/src/client.rs b/rust/personhog-test-harness/src/client.rs
index 841ad55a2966..c5cbb83e8818 100644
--- a/rust/personhog-test-harness/src/client.rs
+++ b/rust/personhog-test-harness/src/client.rs
@@ -7,6 +7,10 @@ use personhog_proto::personhog::{
person_hog_identity_client::PersonHogIdentityClient, GetOrCreatePersonEntry,
GetOrCreatePersonResult, GetOrCreatePersonsByDistinctIdsRequest,
},
+ lifecycle::v1::{
+ person_hog_lifecycle_client::PersonHogLifecycleClient, DeletePersonOutcome,
+ DeletePersonsRequest,
+ },
types::v1::{
ConsistencyLevel, FencePersonRequest, FencePersonResponse, LifecycleOpType, Person,
ReleaseFenceRequest, ReleaseOutcome, UpdatePersonPropertiesRequest,
@@ -143,3 +147,52 @@ impl IdentityClient {
Ok(resp.into_inner().results)
}
}
+
+/// Client for the lifecycle saga service, co-served on the identity
+/// server's address.
+#[derive(Clone)]
+pub struct LifecycleClient {
+ inner: PersonHogLifecycleClient<Channel>,
+}
+
+impl LifecycleClient {
+ pub async fn connect(url: &str) -> Result<Self> {
+ let channel = Channel::from_shared(url.to_string())
+ .context("invalid lifecycle URL")?
+ .timeout(REQUEST_TIMEOUT)
+ .connect_timeout(Duration::from_secs(5))
+ .tcp_nodelay(true)
+ .connect_lazy();
+
+ Ok(Self {
+ inner: PersonHogLifecycleClient::new(channel),
+ })
+ }
+
+ /// Destroy persons through the durable delete saga, returning each
+ /// person's outcome. The op id is scoped to this attempt — never
+ /// derived from the rows, which revive with the same id.
+ pub async fn delete_persons(
+ &self,
+ team_id: i64,
+ person_ids: Vec<i64>,
+ op_id: &uuid::Uuid,
+ ) -> Result<Vec<(i64, DeletePersonOutcome)>> {
+ let resp = self
+ .inner
+ .clone()
+ .delete_persons(Request::new(DeletePersonsRequest {
+ team_id,
+ person_ids,
+ op_id: op_id.to_string(),
+ }))
+ .await
+ .context("DeletePersons failed")?;
+ Ok(resp
+ .into_inner()
+ .results
+ .into_iter()
+ .map(|result| (result.person_id, result.outcome()))
+ .collect())
+ }
+}
diff --git a/rust/personhog-test-harness/src/scenarios/gate.rs b/rust/personhog-test-harness/src/scenarios/gate.rs
index 39ee7c331e7c..c8767131cec2 100644
--- a/rust/personhog-test-harness/src/scenarios/gate.rs
+++ b/rust/personhog-test-harness/src/scenarios/gate.rs
@@ -516,6 +516,20 @@ pub async fn run(args: GateArgs) -> Result<()> {
&violations,
);
+ // The delete leg of the identity path: persons created through
+ // get-or-create leave through the lifecycle saga, and both the
+ // outcomes and the saga's idempotence are gate assertions — every
+ // created person deletes exactly once, and a second attempt under a
+ // fresh op id answers not_found for all of them.
+ if let Some(url) = &identity_url {
+ if !args.keep_data {
+ println!("Deleting persons through the lifecycle saga...");
+ let lifecycle = crate::client::LifecycleClient::connect(url).await?;
+ verify_lifecycle_delete(&lifecycle, args.team_id, &person_ids).await?;
+ println!("Lifecycle delete verified: all deleted, re-delete answers not_found");
+ }
+ }
+
if !args.keep_data {
let persons = seed::cleanup_team(&pool, &args.pg_target_table, args.team_id).await?;
println!("Cleaned up {persons} persons");
@@ -548,6 +562,40 @@ pub async fn run(args: GateArgs) -> Result<()> {
Ok(())
}
+/// Delete `person_ids` through the lifecycle saga and hold the answers
+/// to the gate's standard: every id deleted on the first attempt, every
+/// id not_found on a second attempt under a fresh op id (deleting a
+/// tombstone is a no-op, never an error, never a false success).
+async fn verify_lifecycle_delete(
+ lifecycle: &crate::client::LifecycleClient,
+ team_id: i64,
+ person_ids: &[i64],
+) -> Result<()> {
+ use personhog_proto::personhog::lifecycle::v1::DeletePersonOutcome;
+
+ for (attempt, expected) in [
+ (1, DeletePersonOutcome::Deleted),
+ (2, DeletePersonOutcome::NotFound),
+ ] {
+ // The lifecycle service caps batches at 250 person ids.
+ for chunk in person_ids.chunks(200) {
+ let op_id = uuid::Uuid::new_v4();
+ let outcomes = lifecycle
+ .delete_persons(team_id, chunk.to_vec(), &op_id)
+ .await?;
+ for (person_id, outcome) in outcomes {
+ if outcome != expected {
+ bail!(
+ "lifecycle delete attempt {attempt}: person {person_id} answered \
+ {outcome:?}, expected {expected:?}"
+ );
+ }
+ }
+ }
+ }
+ Ok(())
+}
+
/// Create the traffic-target persons through the identity service's batch
/// get-or-create, with one seed property per person. The create ack covers
/// both planes (stub committed in Postgres, initial properties durable in
diff --git a/rust/personhog-test-harness/src/scenarios/traffic.rs b/rust/personhog-test-harness/src/scenarios/traffic.rs
index e4d2abfc40ac..24995a7a6e0d 100644
--- a/rust/personhog-test-harness/src/scenarios/traffic.rs
+++ b/rust/personhog-test-harness/src/scenarios/traffic.rs
@@ -29,7 +29,8 @@ use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use anyhow::{bail, Context, Result};
-use metrics::{counter, gauge};
+use assignment_coordination::store::{EtcdStore, StoreConfig};
+use metrics::{counter, gauge, histogram};
use personhog_proto::personhog::types::v1::ConsistencyLevel;
use rand::{Rng, SeedableRng};
use serde_json::{json, Value};
@@ -41,6 +42,7 @@ use uuid::Uuid;
use crate::cli::TrafficArgs;
use crate::client::HarnessClient;
+use crate::client::{IdentityClient, LifecycleClient};
use crate::scenarios::chaos::{self, ChaosConfig, TargetKind, TargetSpec};
use crate::scenarios::{blast, consistency};
use crate::seed;
@@ -81,6 +83,14 @@ const STALE_ROW_AGE: Duration = Duration::from_secs(3600);
pub async fn run(args: TrafficArgs) -> Result<()> {
validate_args(&args)?;
+ let team_id = args.team_id;
+ let hostile_team_id = args.hostile_team_id;
+ // Instances share the team pair; disjointness comes from the boot
+ // nonce in every distinct id, so verification (id-scoped) and the
+ // janitor (age-guarded) never cross instances.
+ let nonce = format!("{:08x}", rand::random::<u32>());
+ tracing::info!(%nonce, team_id, hostile_team_id, "instance identity");
+
traffic_metrics::spawn_server(args.metrics_port)?;
gauge!("personhog_traffic_enabled").set(if args.enabled { 1.0 } else { 0.0 });
if !args.enabled {
@@ -91,6 +101,8 @@ pub async fn run(args: TrafficArgs) -> Result<()> {
return Ok(());
}
let client = HarnessClient::connect(&args.router_url).await?;
+ let identity = IdentityClient::connect(&args.identity_url).await?;
+ let lifecycle = LifecycleClient::connect(&args.identity_url).await?;
let pool = PgPool::connect(&args.persons_db_url)
.await
.context("connecting to persons DB")?;
@@ -99,13 +111,13 @@ pub async fn run(args: TrafficArgs) -> Result<()> {
// this database. On failure the process exits and the Deployment's
// restart loop retries — which also rides out startup races where the
// leader hasn't claimed partitions yet.
- sentinel_round_trip(&client, &pool, &args.pg_target_table, args.team_id).await?;
+ sentinel_round_trip(&client, &pool, &args.pg_target_table, team_id).await?;
// 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] {
+ for team in [team_id, hostile_team_id] {
seed::reap_stale_team_rows(&pool, &args.pg_target_table, team, STALE_ROW_AGE).await?;
}
@@ -113,7 +125,12 @@ pub async fn run(args: TrafficArgs) -> Result<()> {
// small (fixed keys, no journal growth) and their outcomes are only
// observed, never verified.
let hostile_ids = if args.hostile_rate > 0.0 {
- Arc::new(seed::seed_persons(&pool, &args.pg_target_table, args.hostile_team_id, 4).await?)
+ // Nonce'd ids: a restart must insert fresh hostile rows, not
+ // revive the previous boot's tombstones, and a sibling instance
+ // must never resolve onto this one's rows.
+ let distinct_ids: Vec<String> =
+ (0..4).map(|i| format!("bed-hostile-{nonce}-{i}")).collect();
+ Arc::new(seed::seed_persons_via_identity(&identity, hostile_team_id, &distinct_ids).await?)
} else {
Arc::new(Vec::new())
};
@@ -133,14 +150,15 @@ pub async fn run(args: TrafficArgs) -> Result<()> {
});
}
- gauge!("personhog_traffic_chaos_enabled").set(if args.chaos_enabled { 1.0 } else { 0.0 });
+ // Chaos is a singleton: N instances compounding kill cadences would
+ // roll the stack permanently, so a Postgres advisory lock elects
+ // exactly one killer and the rest stay candidates.
+ gauge!("personhog_traffic_chaos_enabled").set(0.0);
if args.chaos_enabled {
- // Chaos runs for the process lifetime, independent of epochs:
- // the bed is expected to stay correct while pods die under load.
- let cfg = chaos_config(&args);
+ let args = args.clone();
let shutdown = shutdown.clone();
tokio::spawn(async move {
- chaos::run(cfg, shutdown).await;
+ chaos_singleton(&args, shutdown).await;
});
}
@@ -155,17 +173,26 @@ pub async fn run(args: TrafficArgs) -> Result<()> {
// 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?;
+ seed::refresh_created_at(&pool, &args.pg_target_table, 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?,
- );
+ // The per-epoch janitor: crashed-run leftovers and the
+ // tombstones lifecycle rotation leaves behind both age into
+ // eligibility; without this the table grows one pool per epoch
+ // for the life of the deployment.
+ for team in [team_id, hostile_team_id] {
+ seed::reap_stale_team_rows(&pool, &args.pg_target_table, team, STALE_ROW_AGE).await?;
+ }
+
+ // Fresh ids every epoch, nonce'd per instance: each create
+ // inserts a new row rather than reviving a tombstone, and
+ // sibling instances on the shared team never resolve onto each
+ // other's rows.
+ let distinct_ids: Vec<String> = (0..args.pool_size)
+ .map(|i| format!("bed-{nonce}-e{epoch}-p{i}"))
+ .collect();
+ let person_ids =
+ Arc::new(seed::seed_persons_via_identity(&identity, team_id, &distinct_ids).await?);
let collector = Arc::new(StatsCollector::new());
let state = PersonState::new();
@@ -174,7 +201,7 @@ pub async fn run(args: TrafficArgs) -> Result<()> {
let person_ids = person_ids.clone();
let collector = collector.clone();
let state = state.clone();
- let (team_id, duration, concurrency) = (args.team_id, args.epoch, args.concurrency);
+ let (team_id, duration, concurrency) = (team_id, args.epoch, args.concurrency);
let prefix = format!("traffic_e{epoch}_");
let stop = shutdown.clone();
tokio::spawn(async move {
@@ -198,7 +225,7 @@ pub async fn run(args: TrafficArgs) -> Result<()> {
let person_ids = person_ids.clone();
let collector = collector.clone();
let state = state.clone();
- let (team_id, duration, prober_count) = (args.team_id, args.epoch, args.probers);
+ let (team_id, duration, prober_count) = (team_id, args.epoch, args.probers);
let stop = shutdown.clone();
tokio::spawn(async move {
consistency::run_probers(
@@ -217,7 +244,7 @@ pub async fn run(args: TrafficArgs) -> Result<()> {
let hostile = {
let client = client.clone();
let hostile_ids = hostile_ids.clone();
- let (team_id, duration, rate) = (args.hostile_team_id, args.epoch, args.hostile_rate);
+ let (team_id, duration, rate) = (hostile_team_id, args.epoch, args.hostile_rate);
let stop = shutdown.clone();
tokio::spawn(async move {
run_hostile(&client, team_id, hostile_ids, duration, rate, stop).await
@@ -231,10 +258,9 @@ pub async fn run(args: TrafficArgs) -> Result<()> {
// Close the epoch: everything acked in it must now be visible.
let mut violations = prober_violations;
violations.extend(state.take_anomalies().await);
- violations.extend(blast::verify_strong(&client, &collector, &state, args.team_id).await?);
+ violations.extend(blast::verify_strong(&client, &collector, &state, team_id).await?);
let journal = state.snapshot().await;
- violations
- .extend(verify_postgres(&pool, &args.pg_target_table, args.team_id, &journal).await?);
+ violations.extend(verify_postgres(&pool, &args.pg_target_table, team_id, &journal).await?);
traffic_metrics::record_violations(epoch, &violations);
let writes = collector.writes.snapshot();
@@ -252,20 +278,15 @@ pub async fn run(args: TrafficArgs) -> Result<()> {
"epoch closed"
);
- // Rotate the pool: delete this epoch's persons so the next epoch
- // starts from fresh documents. By id, not by team — a successor
+ // Rotate the pool through the lifecycle delete saga: the same
+ // path production deletes take, exercised every epoch under
+ // whatever chaos is running. 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?;
+ delete_pool(&lifecycle, team_id, &person_ids).await?;
if shutdown.load(Ordering::SeqCst) {
tracing::info!("cleaning up and exiting");
- seed::cleanup_persons(
- &pool,
- &args.pg_target_table,
- args.hostile_team_id,
- &hostile_ids,
- )
- .await?;
+ delete_pool(&lifecycle, hostile_team_id, &hostile_ids).await?;
return Ok(());
}
}
@@ -280,6 +301,160 @@ pub async fn run(args: TrafficArgs) -> Result<()> {
/// personhog charts follow: `app.kubernetes.io/name` equals the release
/// (and namespace) name, and `component=app` excludes the pgbouncer
/// sidecars sharing the namespace.
+/// The lease TTL bounding both sides of the chaos election: a dead
+/// holder's claim expires within this window, and a live holder demotes
+/// on its first unconfirmed keepalive, well inside it.
+const CHAOS_LEASE_TTL: Duration = Duration::from_secs(30);
+const CHAOS_KEEPALIVE_TICK: Duration = Duration::from_secs(10);
+const CHAOS_KEEPALIVE_TIMEOUT: Duration = Duration::from_secs(5);
+// The demotion bound. Anchor at S, the send instant of the last
+// confirmed keepalive: etcd expires the key no earlier than S + TTL,
+// while the holder's next round starts within timeout + tick of S and
+// concludes (send and read each bounded by the timeout) within another
+// 2 * timeout. So the holder is demoted before the key can expire and
+// admit a successor, and two concurrent chaos runners are impossible.
+const _: () = assert!(
+ CHAOS_KEEPALIVE_TICK.as_secs() + 3 * CHAOS_KEEPALIVE_TIMEOUT.as_secs()
+ < CHAOS_LEASE_TTL.as_secs()
+);
+
+/// Lease-backed chaos election on the coordination etcd. The winner
+/// claims `{prefix}chaos_leader` under a lease it keeps alive; losers
+/// retry on a slow cadence. Without etcd endpoints there is nothing to
+/// elect against, so a single instance is assumed and chaos runs
+/// directly.
+async fn chaos_singleton(args: &TrafficArgs, shutdown: Arc<AtomicBool>) {
+ const RETRY: Duration = Duration::from_secs(30);
+
+ let Some(endpoints) = args.chaos_etcd_endpoints.clone() else {
+ tracing::warn!("chaos enabled without etcd endpoints; running unelected");
+ gauge!("personhog_traffic_chaos_enabled").set(1.0);
+ chaos::run(chaos_config(args), shutdown).await;
+ return;
+ };
+
+ while !shutdown.load(Ordering::SeqCst) {
+ if let Err(error) = campaign(args, &endpoints, &shutdown).await {
+ tracing::warn!(%error, "chaos election attempt failed; retrying");
+ }
+ tokio::time::sleep(RETRY).await;
+ }
+}
+
+/// One election attempt: claim the leader key, and while the claim
+/// holds, run chaos. Returns after losing the campaign, demoting, or
+/// shutdown; the caller paces the next attempt.
+async fn campaign(args: &TrafficArgs, endpoints: &str, shutdown: &Arc<AtomicBool>) -> Result<()> {
+ let store = EtcdStore::connect(StoreConfig {
+ endpoints: endpoints.split(',').map(String::from).collect(),
+ prefix: args.chaos_etcd_prefix.clone(),
+ })
+ .await
+ .context("connecting to etcd for the chaos election")?;
+ let key = format!("{}chaos_leader", store.prefix());
+
+ let lease_id = store.grant_lease(CHAOS_LEASE_TTL.as_secs() as i64).await?;
+ if !store
+ .put_if_absent(&key, b"held".to_vec(), lease_id)
+ .await?
+ {
+ store.revoke_lease(lease_id).await.ok();
+ return Ok(());
+ }
+
+ gauge!("personhog_traffic_chaos_enabled").set(1.0);
+ tracing::info!("chaos leadership claimed; this instance runs chaos");
+ let result = hold_and_run(args, &store, lease_id, shutdown).await;
+ gauge!("personhog_traffic_chaos_enabled").set(0.0);
+ // Free the key immediately on a clean exit so a successor need not
+ // wait out the TTL. Best-effort: expiry covers an unreachable etcd.
+ store.revoke_lease(lease_id).await.ok();
+ result
+}
+
+/// Runs chaos while keepalives confirm the lease, demoting on the
+/// first doubt: a send or read failure, a timeout, or a keepalive
+/// answered with TTL 0 (etcd already expired the lease). Doubt is
+/// cheap because the failure direction is one-sided — the key outlives
+/// the hold until revoke or expiry, so a spurious demotion costs a
+/// short chaos gap, never a second runner. Chaos's own etcd bounce
+/// lands here too: the holder demotes and re-campaigns once the
+/// cluster settles.
+async fn hold_and_run(
+ args: &TrafficArgs,
+ store: &EtcdStore,
+ lease_id: i64,
+ shutdown: &Arc<AtomicBool>,
+) -> Result<()> {
+ let chaos = chaos::run(chaos_config(args), shutdown.clone());
+ tokio::pin!(chaos);
+ let (mut keeper, mut stream) = store.keep_alive(lease_id).await?;
+ let mut tick = tokio::time::interval(CHAOS_KEEPALIVE_TICK);
+ tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
+ loop {
+ tokio::select! {
+ _ = &mut chaos => return Ok(()),
+ _ = tick.tick() => {
+ let confirmed = async {
+ tokio::time::timeout(CHAOS_KEEPALIVE_TIMEOUT, keeper.keep_alive())
+ .await
+ .ok()?
+ .ok()?;
+ let resp = tokio::time::timeout(CHAOS_KEEPALIVE_TIMEOUT, stream.message())
+ .await
+ .ok()?
+ .ok()??;
+ (resp.ttl() > 0).then_some(())
+ }
+ .await;
+ if confirmed.is_none() {
+ tracing::warn!("chaos lease unconfirmed; demoting");
+ return Ok(());
+ }
+ }
+ }
+ }
+}
+
+/// Delete the epoch's pool through the saga and account for every
+/// outcome. `deleted` is the expected answer; `not_found` means someone
+/// else already removed the row (a startup janitor's reap, never a
+/// second bed — pools are id-disjoint) and is counted, not fatal;
+/// `skipped_conflict` means a lifecycle operation is stuck holding a
+/// pool person, which the bed exists to surface, so it fails the run.
+async fn delete_pool(lifecycle: &LifecycleClient, team_id: i64, person_ids: &[i64]) -> Result<()> {
+ use personhog_proto::personhog::lifecycle::v1::DeletePersonOutcome;
+
+ // The lifecycle service caps batches at 250 person ids.
+ for chunk in person_ids.chunks(200) {
+ let op_id = uuid::Uuid::new_v4();
+ let started = std::time::Instant::now();
+ let outcomes = lifecycle
+ .delete_persons(team_id, chunk.to_vec(), &op_id)
+ .await?;
+ histogram!("personhog_traffic_pool_delete_duration_ms")
+ .record(started.elapsed().as_secs_f64() * 1000.0);
+ for (person_id, outcome) in outcomes {
+ let label = match outcome {
+ DeletePersonOutcome::Deleted => "deleted",
+ DeletePersonOutcome::NotFound => "not_found",
+ DeletePersonOutcome::SkippedConflict => "skipped_conflict",
+ DeletePersonOutcome::Unspecified => "unspecified",
+ };
+ counter!("personhog_traffic_pool_delete_total", "outcome" => label).increment(1);
+ if matches!(
+ outcome,
+ DeletePersonOutcome::SkippedConflict | DeletePersonOutcome::Unspecified
+ ) {
+ anyhow::bail!(
+ "pool rotation delete returned {label} for person {person_id} on team {team_id}"
+ );
+ }
+ }
+ }
+ Ok(())
+}
+
fn chaos_config(args: &TrafficArgs) -> ChaosConfig {
let target = |kind: TargetKind, namespace: &str| TargetSpec {
kind,
@@ -454,11 +629,49 @@ async fn shutdown_signal() {
mod tests {
use super::*;
+ /// Needs the CI gate's etcd; run explicitly with `--ignored`.
+ #[tokio::test]
+ #[ignore = "needs a local etcd"]
+ async fn chaos_claim_is_exclusive_and_freed_by_lease_revoke() {
+ let endpoints =
+ std::env::var("ETCD_ENDPOINTS").unwrap_or_else(|_| "http://localhost:2379".to_string());
+ let store = EtcdStore::connect(StoreConfig {
+ endpoints: endpoints.split(',').map(String::from).collect(),
+ prefix: "/personhog-harness-test/".to_string(),
+ })
+ .await
+ .unwrap();
+ // A per-run key: a crashed prior run's claim lives only as long
+ // as its lease, but a fresh key avoids waiting that out.
+ let key = format!("{}chaos_leader_{}", store.prefix(), Uuid::new_v4());
+
+ let holder = store.grant_lease(30).await.unwrap();
+ let contender = store.grant_lease(30).await.unwrap();
+ assert!(store
+ .put_if_absent(&key, b"a".to_vec(), holder)
+ .await
+ .unwrap());
+ assert!(!store
+ .put_if_absent(&key, b"b".to_vec(), contender)
+ .await
+ .unwrap());
+
+ // Revoking the holder's lease deletes the key with it, freeing
+ // the claim immediately.
+ store.revoke_lease(holder).await.unwrap();
+ assert!(store
+ .put_if_absent(&key, b"b".to_vec(), contender)
+ .await
+ .unwrap());
+ store.revoke_lease(contender).await.unwrap();
+ }
+
#[test]
fn vacuous_or_panicking_configurations_are_rejected() {
let valid = TrafficArgs {
chaos_etcd_namespace: None,
router_url: "http://localhost:1".to_string(),
+ identity_url: "http://localhost:2".to_string(),
enabled: true,
team_id: 900_101,
hostile_team_id: 900_102,
diff --git a/rust/personhog-test-harness/src/seed.rs b/rust/personhog-test-harness/src/seed.rs
index 3b411fc796fa..5ae753c973be 100644
--- a/rust/personhog-test-harness/src/seed.rs
+++ b/rust/personhog-test-harness/src/seed.rs
@@ -1,8 +1,12 @@
use std::time::Duration;
-use anyhow::{Context, Result};
+use anyhow::{bail, Context, Result};
+use metrics::{counter, histogram};
+use personhog_proto::personhog::identity::v1::GetOrCreatePersonEntry;
use sqlx::postgres::PgPool;
+use crate::client::IdentityClient;
+
/// Seed `count` persons for `team_id` directly in `table` and return their
/// ids, assigned by the table's own id default so they spread across
/// leader partitions exactly like organic ids.
@@ -48,21 +52,74 @@ pub async fn seed_persons(
Ok(ids)
}
-/// The distinct id tables to sweep for a team: always the real mapping
-/// table, plus the tmp mirror when the harness targets the validation
-/// person table — identity writes its mappings there, and the mirror's FK
-/// blocks the person delete until they go.
+/// The mapping table paired with a person table — the one identity
+/// writes and whose FK blocks the person delete. Cleanup stays inside
+/// the person table's own namespace: targeting the validation set must
+/// never delete from the real tables.
fn distinct_id_tables_for(person_table: &str) -> &'static [&'static str] {
if person_table == "personhog_person_tmp" {
- &["posthog_persondistinctid", "personhog_persondistinctid_tmp"]
+ &["personhog_persondistinctid_tmp"]
} else {
&["posthog_persondistinctid"]
}
}
-/// Delete all of `team_id`'s rows from `table`, plus the distinct id and
-/// personless rows the identity-service create path writes. The harness
-/// owns its team ids outright, so team-wide deletes are the whole cleanup.
+/// Create (or revive) one person per distinct id through the identity
+/// service and return their row ids in entry order. This is the bed's
+/// seeding path: creation runs the same get-or-create the ingestion
+/// store uses, so `created_at`, uuids, and mapping rows are all
+/// server-authoritative — the harness can no longer invent a timestamp
+/// the stack must survive. Recycled distinct ids resolve to tombstoned
+/// rows and exercise the revival branch, counted separately from fresh
+/// creates.
+pub async fn seed_persons_via_identity(
+ identity: &IdentityClient,
+ team_id: i64,
+ distinct_ids: &[String],
+) -> Result<Vec<i64>> {
+ let mut ids = Vec::with_capacity(distinct_ids.len());
+ // The identity service caps batches at 250 entries.
+ for chunk in distinct_ids.chunks(200) {
+ let started = std::time::Instant::now();
+ let entries = chunk
+ .iter()
+ .map(|distinct_id| GetOrCreatePersonEntry {
+ team_id,
+ distinct_id: distinct_id.clone(),
+ extra_distinct_ids: vec![],
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(
+ &serde_json::json!({ "harness_seed": distinct_id }),
+ )
+ .expect("seed properties serialize"),
+ ..Default::default()
+ })
+ .collect();
+ let results = identity.get_or_create_persons(entries).await?;
+ histogram!("personhog_traffic_pool_seed_duration_ms")
+ .record(started.elapsed().as_secs_f64() * 1000.0);
+ for result in results {
+ if let Some(error) = &result.error {
+ bail!("get-or-create rejected a seed entry: {error:?}");
+ }
+ let person = result
+ .person
+ .context("get-or-create returned no person for a seed entry")?;
+ let outcome = if result.created {
+ "created"
+ } else {
+ "resolved"
+ };
+ counter!("personhog_traffic_pool_seed_total", "outcome" => outcome).increment(1);
+ ids.push(person.id);
+ }
+ }
+ Ok(ids)
+}
+
+/// Delete all of `team_id`'s rows from `table`, plus the distinct id
+/// mappings the identity-service create path writes. The harness owns
+/// its team ids outright, so team-wide deletes are the whole cleanup.
/// Distinct id rows go first: their FK references the person rows.
pub async fn cleanup_team(pool: &PgPool, table: &str, team_id: i64) -> Result<u64> {
validate_table_name(table)?;
@@ -75,11 +132,6 @@ pub async fn cleanup_team(pool: &PgPool, table: &str, team_id: i64) -> Result<u6
.await
.with_context(|| format!("deleting distinct ids from {pdi_table}"))?;
}
- 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"))
.bind(team)
@@ -90,32 +142,6 @@ 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
@@ -146,11 +172,10 @@ pub async fn refresh_created_at(
/// 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.
+/// overlap, while dead instances' rows age into eligibility. Every
+/// delete is scoped to rows the harness's own write path produces:
+/// tables it never writes (the personless table) are never touched,
+/// however stray their contents look.
pub async fn reap_stale_team_rows(
pool: &PgPool,
table: &str,
@@ -160,19 +185,29 @@ pub async fn reap_stale_team_rows(
validate_table_name(table)?;
let team: i32 = team_id.try_into().context("team_id out of i32 range")?;
+ // Mapping rows scoped to the person rows being reaped: the bed's
+ // identity-service seeding writes live mappings for its current
+ // pool, so a team-wide sweep here would tear them out from under a
+ // running sibling. Lifecycle deletes leave tombstoned mappings on
+ // aged rows, and those go with their persons.
for pdi_table in distinct_id_tables_for(table) {
- sqlx::query(&format!("DELETE FROM {pdi_table} WHERE team_id = $1"))
- .bind(team)
- .execute(pool)
- .await
- .with_context(|| format!("deleting distinct ids from {pdi_table}"))?;
- }
- sqlx::query("DELETE FROM posthog_personlessdistinctid WHERE team_id = $1")
+ sqlx::query(&format!(
+ "DELETE FROM {pdi_table} \
+ WHERE team_id = $1 AND person_id IN ( \
+ SELECT id 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
- .context("deleting personless distinct ids")?;
+ .with_context(|| format!("deleting distinct ids from {pdi_table}"))?;
+ }
+ // Age-guarded and deliberately blind to is_deleted: it purges both
+ // crashed-run leftovers and the tombstones lifecycle deletes leave
+ // behind, which would otherwise grow the table by one pool per
+ // epoch forever.
let deleted = sqlx::query(&format!(
"DELETE FROM {table} \
WHERE team_id = $1 AND created_at < now() - make_interval(secs => $2)"
diff --git a/rust/personhog-test-harness/src/traffic_metrics.rs b/rust/personhog-test-harness/src/traffic_metrics.rs
index 2d47570a9aa6..f9ae378bd3ab 100644
--- a/rust/personhog-test-harness/src/traffic_metrics.rs
+++ b/rust/personhog-test-harness/src/traffic_metrics.rs
@@ -121,6 +121,16 @@ pub fn spawn_server(port: u16) -> Result<()> {
common_metrics::Matcher::Full("personhog_traffic_read_duration_ms".into()),
WRITE_PATH_LATENCY_BUCKETS_MS,
),
+ // Batched identity/lifecycle RPCs: one sample per batch call,
+ // same ladder — their cost is a handful of round trips.
+ (
+ common_metrics::Matcher::Full("personhog_traffic_pool_seed_duration_ms".into()),
+ WRITE_PATH_LATENCY_BUCKETS_MS,
+ ),
+ (
+ common_metrics::Matcher::Full("personhog_traffic_pool_delete_duration_ms".into()),
+ WRITE_PATH_LATENCY_BUCKETS_MS,
+ ),
],
);
let bind = format!("0.0.0.0:{port}");