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): chaos always kills the real coordinator, never a standby (#71761)

Zach Browne4333da7fddb
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.yml
index 2c36f80cf4bf..0b3f4783776d 100644
--- a/.github/workflows/ci-rust.yml
+++ b/.github/workflows/ci-rust.yml
@@ -590,13 +590,13 @@ jobs:
- name: Run the e2e gate under chaos (coordinator failover + mid-handoff kill)
run: |
./target/debug/personhog-test-harness gate \
- --routers 2 --leaders 3 --partitions 8 --persons 100 --concurrency 10 \
+ --routers 3 --leaders 3 --partitions 8 --persons 100 --concurrency 10 \
--duration 18s --router-kill-after 4s --shutdown-after 8s --kill-handoff-target
- name: Run the e2e gate under chaos (graceful coordinator handover + drain)
run: |
./target/debug/personhog-test-harness gate \
- --routers 2 --leaders 3 --partitions 8 --persons 100 --concurrency 10 \
+ --routers 3 --leaders 3 --partitions 8 --persons 100 --concurrency 10 \
--duration 15s --router-shutdown-after 4s --shutdown-after 8s
# A true coordinator crash: no lease is revoked, so the survivor
@@ -605,7 +605,7 @@ jobs:
- name: Run the e2e gate under chaos (coordinator crash, slow failover + drain)
run: |
./target/debug/personhog-test-harness gate \
- --routers 2 --leaders 3 --partitions 8 --persons 100 --concurrency 10 \
+ --routers 3 --leaders 3 --partitions 8 --persons 100 --concurrency 10 \
--duration 18s --router-kill-after 4s --router-kill-fast false --shutdown-after 8s
- name: Dump service logs on failure
diff --git a/rust/personhog-router/src/config.rs b/rust/personhog-router/src/config.rs
index 9f77b777369d..d149a21a7402 100644
--- a/rust/personhog-router/src/config.rs
+++ b/rust/personhog-router/src/config.rs
@@ -212,6 +212,15 @@ pub struct Config {
pub stash_drain_concurrency: usize,
// ── coordinator (leader election among router-leader pods) ───
+ /// Whether this leader-mode router campaigns for the coordinator
+ /// election. Disabled, the router still registers in the routing
+ /// table, serves traffic, and acks freezes — it just never
+ /// coordinates. Production leaves this on everywhere; the test
+ /// harness disables it on its traffic router so chaos targeting
+ /// "the coordinator" can never land on the traffic path.
+ #[envconfig(default = "true")]
+ pub coordinator_enabled: bool,
+
/// Lease TTL for the coordinator leader election. A crashed leader
/// blocks every handoff until this expires and a survivor's campaign
/// fires, so the worst-case coordinator outage is roughly this plus
diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rs
index b56ad9e5a595..18074f15f1d2 100644
--- a/rust/personhog-router/src/main.rs
+++ b/rust/personhog-router/src/main.rs
@@ -93,13 +93,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.with_graceful_shutdown(Duration::from_secs(5))
.with_shutdown_phase(1),
);
- let coord = manager.register(
- "coordinator",
- ComponentOptions::new()
- .with_graceful_shutdown(Duration::from_secs(5))
- .with_shutdown_phase(1),
- );
- (Some(rt), Some(coord))
+ let coord = config.coordinator_enabled.then(|| {
+ manager.register(
+ "coordinator",
+ ComponentOptions::new()
+ .with_graceful_shutdown(Duration::from_secs(5))
+ .with_shutdown_phase(1),
+ )
+ });
+ (Some(rt), coord)
} else {
(None, None)
};
@@ -314,50 +316,54 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
});
- // K8s awareness (optional)
- let k8s_cancel = CancellationToken::new();
- let k8s_awareness = if config.k8s_awareness_enabled {
- let namespace = config
- .resolve_k8s_namespace()
- .expect("k8s awareness enabled but namespace resolution failed");
- let client = kube::Client::try_default()
- .await
- .expect("failed to create K8s client");
- tracing::info!(%namespace, "K8s awareness enabled");
- Some(Arc::new(K8sAwareness::new(
- client,
- namespace,
- k8s_cancel.child_token(),
- )))
- } else {
- tracing::info!("K8s awareness disabled");
- None
- };
-
- // Start coordinator (leader election + partition assignment)
- let coordinator_handle =
- coordinator_handle.expect("coordinator handle must be registered in leader mode");
- let coordinator = Coordinator::new(
- store,
- CoordinatorConfig {
- name: config.pod_name.clone(),
- leader_lease_ttl: config.coordinator_lease_ttl,
- keepalive_interval: config.coordinator_keepalive_interval(),
- election_retry_interval: config.coordinator_election_retry_interval(),
- rebalance_debounce_interval: config.coordinator_rebalance_debounce_interval(),
- reconcile_interval: config.coordinator_reconcile_interval(),
- },
- Arc::new(StickyBalancedStrategy),
- k8s_awareness,
- );
+ // Start coordinator (leader election + partition assignment),
+ // unless this router opted out of candidacy. K8s awareness only
+ // feeds the coordinator's placement decisions, so it starts (and
+ // stops) with it.
+ if let Some(coordinator_handle) = coordinator_handle {
+ let k8s_cancel = CancellationToken::new();
+ let k8s_awareness = if config.k8s_awareness_enabled {
+ let namespace = config
+ .resolve_k8s_namespace()
+ .expect("k8s awareness enabled but namespace resolution failed");
+ let client = kube::Client::try_default()
+ .await
+ .expect("failed to create K8s client");
+ tracing::info!(%namespace, "K8s awareness enabled");
+ Some(Arc::new(K8sAwareness::new(
+ client,
+ namespace,
+ k8s_cancel.child_token(),
+ )))
+ } else {
+ tracing::info!("K8s awareness disabled");
+ None
+ };
+
+ let coordinator = Coordinator::new(
+ store,
+ CoordinatorConfig {
+ name: config.pod_name.clone(),
+ leader_lease_ttl: config.coordinator_lease_ttl,
+ keepalive_interval: config.coordinator_keepalive_interval(),
+ election_retry_interval: config.coordinator_election_retry_interval(),
+ rebalance_debounce_interval: config.coordinator_rebalance_debounce_interval(),
+ reconcile_interval: config.coordinator_reconcile_interval(),
+ },
+ Arc::new(StickyBalancedStrategy),
+ k8s_awareness,
+ );
- tokio::spawn(async move {
- let _guard = coordinator_handle.process_scope();
- if let Err(e) = coordinator.run(coordinator_handle.shutdown_token()).await {
- coordinator_handle.signal_failure(format!("Coordinator error: {e}"));
- }
- k8s_cancel.cancel();
- });
+ tokio::spawn(async move {
+ let _guard = coordinator_handle.process_scope();
+ if let Err(e) = coordinator.run(coordinator_handle.shutdown_token()).await {
+ coordinator_handle.signal_failure(format!("Coordinator error: {e}"));
+ }
+ k8s_cancel.cancel();
+ });
+ } else {
+ tracing::info!("coordinator election disabled; this router never campaigns");
+ }
Some(leader_backend)
} else {
diff --git a/rust/personhog-test-harness/README.md b/rust/personhog-test-harness/README.md
index f6ba5dfbaf8a..2c7e063847e3 100644
--- a/rust/personhog-test-harness/README.md
+++ b/rust/personhog-test-harness/README.md
@@ -75,10 +75,11 @@ target/debug/personhog-test-harness gate --leaders 3 --duration 15s --restart-af
target/debug/personhog-test-harness gate --duration 15s --writer-crash-after 5s
target/debug/personhog-test-harness gate --duration 15s --writer-pause-after 3s --writer-pause-duration 8s
-# Kill the coordinator: bring-up guarantees the first router holds the
-# election, traffic targets the last; the kill revokes the election lease so
-# failover is immediate and a later handoff runs under the new coordinator
-target/debug/personhog-test-harness gate --leaders 3 --routers 2 --duration 20s \
+# Kill the coordinator: the kill resolves the live election holder from etcd
+# (the traffic router never campaigns, so it can never be the target),
+# revokes the election lease so failover is immediate, and a later handoff
+# runs under the new coordinator
+target/debug/personhog-test-harness gate --leaders 3 --routers 3 --duration 20s \
--router-kill-after 5s --shutdown-after 9s
# Compound: kill the target pod of an in-flight handoff (best-effort timing —
@@ -120,13 +121,13 @@ Both paths are gated in CI and the slow-failover window is finally exercised:
```bash
# Graceful handover: SIGTERM the coordinator, then drain a leader under
# the successor. Settles in ~0s with zero failed writes.
-target/debug/personhog-test-harness gate --routers 2 --leaders 3 --duration 15s \
+target/debug/personhog-test-harness gate --routers 3 --leaders 3 --duration 15s \
--router-shutdown-after 4s --shutdown-after 8s
# True crash: no lease revoked, the survivor is blind until the TTLs
# expire; a drain issued inside the window completes once they do. The
# phased leader shutdown keeps the drained pod serving throughout.
-target/debug/personhog-test-harness gate --routers 2 --leaders 3 --duration 18s \
+target/debug/personhog-test-harness gate --routers 3 --leaders 3 --duration 18s \
--router-kill-after 4s --router-kill-fast false --shutdown-after 8s
```
@@ -138,7 +139,7 @@ Before ordered shutdown, that wedged everything: the draining pod's coordination
With phased shutdown, coordination survives the whole drain and acks promptly — the composite below now settles in ~0s with only the killed pod's own crash window as failures.
```bash
-target/debug/personhog-test-harness gate --routers 2 --leaders 3 --duration 18s \
+target/debug/personhog-test-harness gate --routers 3 --leaders 3 --duration 18s \
--router-kill-after 4s --shutdown-after 8s --kill-handoff-target
```
diff --git a/rust/personhog-test-harness/src/cli.rs b/rust/personhog-test-harness/src/cli.rs
index 824daa1ac191..cfcbfb856e50 100644
--- a/rust/personhog-test-harness/src/cli.rs
+++ b/rust/personhog-test-harness/src/cli.rs
@@ -127,9 +127,11 @@ pub struct GateArgs {
#[arg(long, default_value_t = 2)]
pub leaders: u32,
- /// Number of leader-mode routers to spawn (each is a coordinator
- /// candidate). Traffic targets the last one, so a coordinator kill —
- /// which targets the first — leaves the traffic path intact.
+ /// Number of leader-mode routers to spawn. Traffic targets the last
+ /// one, which (with 2+ routers) opts out of election candidacy —
+ /// coordinator chaos resolves the live election holder and can never
+ /// land on the traffic path. Use 3+ so a crash leaves a standby
+ /// candidate to win the election.
#[arg(long, default_value_t = 1)]
pub routers: u32,
@@ -213,8 +215,8 @@ pub struct GateArgs {
#[arg(long, default_value = "10s", value_parser = humantime::parse_duration)]
pub writer_pause_duration: Duration,
- /// SIGKILL the first router (the presumed coordinator) this long into
- /// the traffic phase. Requires --routers >= 2.
+ /// SIGKILL the router holding the coordinator election this long
+ /// into the traffic phase. Requires --routers >= 3.
#[arg(long, value_parser = humantime::parse_duration)]
pub router_kill_after: Option<Duration>,
@@ -225,10 +227,10 @@ pub struct GateArgs {
#[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
pub router_kill_fast: bool,
- /// Gracefully shut down (SIGTERM) the first router (the presumed
- /// coordinator) this long into the traffic phase: the election must
- /// hand over to a survivor immediately via the revoke-on-exit path,
- /// not by waiting out the lease TTL. Requires --routers >= 2.
+ /// Gracefully shut down (SIGTERM) the router holding the coordinator
+ /// election this long into the traffic phase: the election must hand
+ /// over to a survivor immediately via the revoke-on-exit path, not by
+ /// waiting out the lease TTL. Requires --routers >= 3.
#[arg(long, value_parser = humantime::parse_duration)]
pub router_shutdown_after: Option<Duration>,
diff --git a/rust/personhog-test-harness/src/scenarios/gate.rs b/rust/personhog-test-harness/src/scenarios/gate.rs
index e4e740ffd66c..e6060ccb1484 100644
--- a/rust/personhog-test-harness/src/scenarios/gate.rs
+++ b/rust/personhog-test-harness/src/scenarios/gate.rs
@@ -132,9 +132,13 @@ pub async fn run(args: GateArgs) -> Result<()> {
bail!("chaos flags require a spawned stack; they cannot target --external-router-url");
}
if (args.router_kill_after.is_some() || args.router_shutdown_after.is_some())
- && args.routers < 2
+ && args.routers < 3
{
- bail!("--router-kill-after requires --routers >= 2 (traffic targets the last router)");
+ bail!(
+ "coordinator chaos requires --routers >= 3: traffic targets the last router, \
+ which never campaigns, so two routers leave no standby to win the failover \
+ election"
+ );
}
if args.kill_handoff_target && args.shutdown_after.is_none() && args.scale_up_after.is_none() {
bail!("--kill-handoff-target needs a handoff-creating event (--shutdown-after or --scale-up-after)");
@@ -263,7 +267,7 @@ pub async fn run(args: GateArgs) -> Result<()> {
None
}
ChaosEvent::RouterKill { fast } => Some(stack.kill_coordinator_router(fast).await?),
- ChaosEvent::RouterShutdown => Some(stack.shutdown_coordinator_router()?),
+ ChaosEvent::RouterShutdown => Some(stack.shutdown_coordinator_router().await?),
};
println!(
"Chaos at {:.1}s: {event} → pod {} | {}",
diff --git a/rust/personhog-test-harness/src/stack/mod.rs b/rust/personhog-test-harness/src/stack/mod.rs
index 505e6b34025c..7be31652c4b2 100644
--- a/rust/personhog-test-harness/src/stack/mod.rs
+++ b/rust/personhog-test-harness/src/stack/mod.rs
@@ -159,15 +159,20 @@ impl Stack {
&log_dir,
)?);
- // The first router must win the coordinator election so chaos that
- // targets "the coordinator" is deterministic: spawn it alone, wait
- // for it to acquire leadership, then bring up the rest.
+ // The first router must win the coordinator election so bring-up
+ // is deterministic: spawn it alone, wait for it to acquire
+ // leadership, then bring up the rest. With two or more routers,
+ // traffic targets the LAST one and that router opts out of
+ // election candidacy entirely — so no matter how leadership
+ // migrates later, coordinator chaos can never be forced to choose
+ // between killing the traffic path and killing a standby.
let mut routers = Vec::new();
for i in 0..config.routers {
if i == 1 {
etcd::wait_for_leader(&store, "harness-router-0", Duration::from_secs(15)).await?;
}
let name = format!("harness-router-{i}");
+ let is_traffic_router = config.routers >= 2 && i == config.routers - 1;
let proc = ServiceProcess::spawn(
&name,
&config.bin_dir.join("personhog-router"),
@@ -185,6 +190,7 @@ impl Stack {
("ETCD_PREFIX", ETCD_PREFIX.to_string()),
("BACKEND_TIMEOUT_MS", "5000".to_string()),
("POD_NAME", name.clone()),
+ ("COORDINATOR_ENABLED", (!is_traffic_router).to_string()),
(
"METRICS_PORT",
(ROUTER_METRICS_BASE_PORT + i as u16).to_string(),
@@ -195,9 +201,6 @@ impl Stack {
routers.push((name, proc));
}
- // Traffic targets the last router: the first spawned usually wins
- // the coordinator election, so a coordinator kill (which targets
- // the first) leaves the traffic path intact.
let traffic_router_port = ROUTER_GRPC_BASE_PORT + (config.routers - 1) as u16;
let router_url = format!("http://127.0.0.1:{traffic_router_port}");
@@ -350,18 +353,56 @@ impl Stack {
Ok(pod_name)
}
- /// SIGKILL the first-spawned router — the coordinator, since bring-up
- /// waits for it to win the election — and revoke both its registration
- /// lease (so freeze quorums stop counting it) and its election lease
- /// (so a surviving router takes over immediately instead of waiting
- /// out the election TTL). Handoffs created after this run under the
- /// new coordinator. With `fast` false, neither lease is revoked — a
- /// true crash whose failover waits out both TTLs.
+ /// Index of the router currently holding the coordinator election,
+ /// resolved live from etcd so chaos targets the actual coordinator
+ /// even if leadership migrated after bring-up. Never guesses: lookup
+ /// errors propagate (steering a kill off a failed read could target a
+ /// standby and pass the gate vacuously), and a vacant election is
+ /// polled until a winner emerges — with the 1s campaign retry, well
+ /// inside the deadline. Bails if the holder is the traffic router:
+ /// candidacy is disabled there, so this can only mean the opt-out
+ /// broke — a loud failure here is the regression signal for that
+ /// wiring.
+ async fn coordinator_router_index(&self) -> Result<usize> {
+ let traffic_router = format!("harness-router-{}", self.config.routers - 1);
+ let deadline = std::time::Instant::now() + Duration::from_secs(5);
+ let holder = loop {
+ if let Some(leader) = self.store.get_leader().await? {
+ break leader.holder;
+ }
+ if std::time::Instant::now() >= deadline {
+ bail!("no coordinator elected within 5s; cannot target coordinator chaos");
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ };
+ if holder == traffic_router {
+ bail!(
+ "election held by the traffic router {traffic_router}, which must never \
+ campaign (COORDINATOR_ENABLED=false) — candidacy opt-out is broken"
+ );
+ }
+ self.routers
+ .iter()
+ .position(|(name, _)| *name == holder)
+ .with_context(|| format!("election holder {holder} is not a live router"))
+ }
+
+ /// SIGKILL the router holding the coordinator election and revoke
+ /// both its registration lease (so freeze quorums stop counting it)
+ /// and its election lease (so a surviving candidate takes over
+ /// immediately instead of waiting out the election TTL). Handoffs
+ /// created after this run under the new coordinator. With `fast`
+ /// false, neither lease is revoked — a true crash whose failover
+ /// waits out both TTLs.
pub async fn kill_coordinator_router(&mut self, fast: bool) -> Result<String> {
- if self.routers.len() < 2 {
- bail!("coordinator kill requires at least 2 routers");
+ if self.routers.len() < 3 {
+ bail!(
+ "coordinator kill requires at least 3 routers: the traffic router never \
+ campaigns, so 2 leaves no standby to win the failover election"
+ );
}
- let (name, mut proc) = self.routers.remove(0);
+ let index = self.coordinator_router_index().await?;
+ let (name, mut proc) = self.routers.remove(index);
proc.kill_now().await;
if fast {
etcd::revoke_router_lease(&self.store, &name).await?;
@@ -378,14 +419,18 @@ impl Stack {
Ok(name)
}
- /// SIGTERM the first router (the presumed coordinator) — a graceful
+ /// SIGTERM the router holding the coordinator election — a graceful
/// exit whose election handover must come from the revoke-on-exit
/// path, immediately, never from waiting out the lease TTL.
- pub fn shutdown_coordinator_router(&mut self) -> Result<String> {
- if self.routers.len() < 2 {
- bail!("coordinator shutdown requires at least 2 routers");
+ pub async fn shutdown_coordinator_router(&mut self) -> Result<String> {
+ if self.routers.len() < 3 {
+ bail!(
+ "coordinator shutdown requires at least 3 routers: the traffic router never \
+ campaigns, so 2 leaves no standby to win the failover election"
+ );
}
- let (name, proc) = self.routers.remove(0);
+ let index = self.coordinator_router_index().await?;
+ let (name, proc) = self.routers.remove(index);
proc.sigterm();
tracing::info!(router = %name, "requested graceful shutdown of coordinator router");
self.retired.push(proc);