: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
fix(personhog): make coordinator election failover fast and reliable (#71321)
Zach Brown32a7d759c9eb
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.ymlindex ad7aca9059fd..af419e8629b2 100644--- a/.github/workflows/ci-rust.yml+++ b/.github/workflows/ci-rust.yml@@ -588,6 +588,21 @@ jobs:--routers 2 --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 \+ --duration 15s --router-shutdown-after 4s --shutdown-after 8s++ # A true coordinator crash: no lease is revoked, so the survivor+ # is blind until the election and registration TTLs expire, and+ # the drain issued inside that window must complete once they do.+ - 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 \+ --duration 18s --router-kill-after 4s --router-kill-fast false --shutdown-after 8s+- name: Dump service logs on failureif: failure()run: |diff --git a/rust/personhog-coordination/src/coordinator.rs b/rust/personhog-coordination/src/coordinator.rsindex 6384a8499995..7437c5a065db 100644--- a/rust/personhog-coordination/src/coordinator.rs+++ b/rust/personhog-coordination/src/coordinator.rs@@ -42,9 +42,16 @@ impl Default for CoordinatorConfig {fn default() -> Self {Self {name: "coordinator-0".to_string(),- leader_lease_ttl: 15,- keepalive_interval: Duration::from_secs(5),- election_retry_interval: Duration::from_secs(5),+ // A crashed leader blocks every handoff until its election+ // lease expires and a survivor's next campaign fires, so the+ // worst-case coordinator outage is ttl + retry. 5s + 1s keeps+ // that near the pod-crash detection window, while the 1s+ // keepalive gives the leader several attempts within the TTL+ // before it abdicates. Graceful exits don't wait on any of+ // this — the lease is revoked on the way out.+ leader_lease_ttl: 5,+ keepalive_interval: Duration::from_secs(1),+ election_retry_interval: Duration::from_secs(1),rebalance_debounce_interval: Duration::from_secs(1),reconcile_interval: Duration::from_secs(5),}@@ -78,60 +85,92 @@ impl Coordinator {/// or cancellation is requested.pub async fn run(&self, cancel: CancellationToken) -> Result<()> {loop {+ if cancel.is_cancelled() {+ return Ok(());+ }+ // Awaited to completion, never raced against cancellation:+ // dropping try_lead mid-cleanup would strand the election+ // lease until TTL expiry, stalling every handoff while the+ // next coordinator's campaign waits it out. try_lead observes+ // `cancel` internally and returns promptly on shutdown.+ match self.try_lead(cancel.clone()).await {+ Ok(true) => tracing::info!(name = %self.config.name, "leadership ended normally"),+ Ok(false) => {}+ Err(e) => {+ tracing::warn!(name = %self.config.name, error = %e, "leader loop ended with error")+ }+ }tokio::select! {_ = cancel.cancelled() => return Ok(()),- result = self.try_lead(cancel.clone()) => {- match result {- Ok(()) => tracing::info!(name = %self.config.name, "leadership ended normally"),- Err(e) => tracing::warn!(name = %self.config.name, error = %e, "leader loop ended with error"),- }- tokio::select! {- _ = cancel.cancelled() => return Ok(()),- _ = tokio::time::sleep(self.config.election_retry_interval) => {}- }- }+ _ = tokio::time::sleep(self.config.election_retry_interval) => {}}}}- async fn try_lead(&self, cancel: CancellationToken) -> Result<()> {+ /// One leadership attempt; returns whether this candidate actually+ /// led. Always runs its cleanup — keepalive shutdown and election+ /// lease revoke — before returning, so a graceful exit frees the+ /// election immediately instead of stranding it until TTL expiry.+ /// `run` relies on that by awaiting this call to completion.+ async fn try_lead(&self, cancel: CancellationToken) -> Result<bool> {let lease_id = self.store.grant_lease(self.config.leader_lease_ttl).await?;- let acquired = self+ let acquired = match self.store.try_acquire_leadership(&self.config.name, lease_id)- .await?;+ .await+ {+ Ok(acquired) => acquired,+ Err(e) => {+ drop(self.store.revoke_lease(lease_id).await);+ return Err(e);+ }+ };if !acquired {tracing::debug!(name = %self.config.name, "another coordinator is leader, standing by");- return Ok(());+ // Nothing hangs off the lease; revoke it rather than leaking+ // one lease per election retry from every standby candidate.+ drop(self.store.revoke_lease(lease_id).await);+ return Ok(false);}tracing::info!(name = %self.config.name, "acquired leadership");- // Spawn lease keepalive+ // A failed keepalive means the lease is gone (or about to be) and+ // another candidate can win the election: abdicate rather than+ // keep coordinating as a zombie alongside the successor. The+ // successor's bootstrap reconciles in-flight state, and handoff+ // transitions are CAS-guarded against exactly this overlap.let keepalive_cancel = cancel.child_token();+ let lease_lost = CancellationToken::new();let keepalive_handle = {let store = Arc::clone(&self.store);let interval = self.config.keepalive_interval;let token = keepalive_cancel.clone();+ let lease_lost = lease_lost.clone();tokio::spawn(async move {if let Err(e) = util::run_lease_keepalive(store, lease_id, interval, token).await {- tracing::error!(error = %e, "keepalive failed");+ tracing::error!(error = %e, "election lease keepalive failed");+ lease_lost.cancel();}})};- let result = self.run_coordination_loop(cancel.clone()).await;+ let result = tokio::select! {+ _ = lease_lost.cancelled() => Err(Error::leadership_lost()),+ result = self.run_coordination_loop(cancel.clone()) => result,+ };// Clean up keepalivekeepalive_cancel.cancel();drop(keepalive_handle.await);- // Best-effort revoke so next leader can take over quickly+ // Revoke so the next candidate's campaign wins immediately instead+ // of waiting out the lease TTL.drop(self.store.revoke_lease(lease_id).await);- result+ result.map(|()| true)}async fn run_coordination_loop(&self, cancel: CancellationToken) -> Result<()> {diff --git a/rust/personhog-coordination/src/routing_table.rs b/rust/personhog-coordination/src/routing_table.rsindex 55554f546756..6ed668a8e863 100644--- a/rust/personhog-coordination/src/routing_table.rs+++ b/rust/personhog-coordination/src/routing_table.rs@@ -41,8 +41,12 @@ impl Default for RoutingTableConfig {fn default() -> Self {Self {router_name: "router-0".to_string(),- lease_ttl: 30,- heartbeat_interval: Duration::from_secs(10),+ // A crashed router stays in every freeze quorum until its+ // registration expires, stalling any handoff frozen in that+ // window — keep the TTL short (graceful exits deregister+ // immediately on the way out).+ lease_ttl: 10,+ heartbeat_interval: Duration::from_secs(3),}}}@@ -165,6 +169,12 @@ impl RoutingTable {// Abort and await all remaining tasks for clean shutdowntasks.shutdown().await;+ // Deregister so freeze quorums stop counting this router+ // immediately. Left to lease expiry, every handoff frozen in the+ // next TTL window stalls waiting for a freeze ack this router+ // will never write.+ drop(self.store.revoke_lease(lease_id).await);+result}diff --git a/rust/personhog-coordination/tests/integration.rs b/rust/personhog-coordination/tests/integration.rsindex 6d61449fdc2d..23ccb1ef13da 100644--- a/rust/personhog-coordination/tests/integration.rs+++ b/rust/personhog-coordination/tests/integration.rs@@ -8,8 +8,9 @@ use std::time::Duration;use common::{start_coordinator, start_coordinator_named, start_coordinator_with_debounce, start_pod,- start_pod_blocking, start_pod_slow, start_pod_with_lease_ttl, start_router, test_store,- wait_for_condition, HandoffEvent, PodHandles, POLL_INTERVAL, WAIT_TIMEOUT,+ start_pod_blocking, start_pod_slow, start_pod_with_lease_ttl, start_router,+ start_router_with_lease_ttl, test_store, wait_for_condition, HandoffEvent, PodHandles,+ POLL_INTERVAL, WAIT_TIMEOUT,};use personhog_coordination::strategy::{AssignmentStrategy, JumpHashStrategy, StickyBalancedStrategy,@@ -2590,3 +2591,73 @@ async fn handoff_delete_during_draining_drains_to_current_owner() {cancel.cancel();}++// ============================================================+// Graceful exits release etcd state immediately, never by TTL+// ============================================================++/// A cancelled coordinator must revoke its election lease on the way out.+/// With a 30s TTL, a pass that relied on lease expiry would blow the 3s+/// bound — this pins the awaited-to-completion cleanup in+/// `Coordinator::run`, which an unbiased select against cancellation used+/// to drop about half the time, stalling every handoff until the TTL ran+/// out.+#[tokio::test]+async fn graceful_coordinator_exit_releases_election_immediately() {+ let store = test_store("graceful-coordinator-release").await;+ let cancel = CancellationToken::new();+ let handle = start_coordinator_named(+ Arc::clone(&store),+ "coordinator-0",+ 30,+ Arc::new(StickyBalancedStrategy),+ cancel.clone(),+ );++ let check_store = Arc::clone(&store);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let store = Arc::clone(&check_store);+ async move { store.get_leader().await.ok().flatten().is_some() }+ })+ .await;++ cancel.cancel();+ drop(handle.await);++ let check_store = Arc::clone(&store);+ wait_for_condition(Duration::from_secs(3), POLL_INTERVAL, || {+ let store = Arc::clone(&check_store);+ async move { store.get_leader().await.ok().flatten().is_none() }+ })+ .await;+}++/// A cancelled routing table must deregister its router on the way out: a+/// lingering registration keeps the dead router in every freeze quorum,+/// stalling any handoff frozen inside the TTL window.+#[tokio::test]+async fn routing_table_deregisters_router_on_graceful_exit() {+ let store = test_store("graceful-router-deregister").await;+ let cancel = CancellationToken::new();+ let mut router =+ start_router_with_lease_ttl(Arc::clone(&store), "router-0", 30, cancel.clone());++ let check_store = Arc::clone(&store);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let store = Arc::clone(&check_store);+ async move { !store.list_routers().await.unwrap_or_default().is_empty() }+ })+ .await;++ cancel.cancel();+ if let Some(handle) = router.join_handle.take() {+ drop(handle.await);+ }++ let check_store = Arc::clone(&store);+ wait_for_condition(Duration::from_secs(3), POLL_INTERVAL, || {+ let store = Arc::clone(&check_store);+ async move { store.list_routers().await.unwrap_or_default().is_empty() }+ })+ .await;+}diff --git a/rust/personhog-coordination/tests/protocol_hardening.rs b/rust/personhog-coordination/tests/protocol_hardening.rsindex fc445ea3147d..a13d9f931e5a 100644--- a/rust/personhog-coordination/tests/protocol_hardening.rs+++ b/rust/personhog-coordination/tests/protocol_hardening.rs@@ -19,9 +19,9 @@ use tokio_util::sync::CancellationToken;use assignment_coordination::store::parse_watch_value;use async_trait::async_trait;use common::{- revoke_lease_of_key, start_coordinator, start_pod, start_pod_with_lease_ttl,- start_router_with_lease_ttl, test_store, test_store_with_prefix, wait_for_condition,- HandoffEvent, POLL_INTERVAL, WAIT_TIMEOUT,+ revoke_lease_of_key, start_coordinator, start_coordinator_named, start_pod,+ start_pod_with_lease_ttl, start_router_with_lease_ttl, test_store, test_store_with_prefix,+ wait_for_condition, HandoffEvent, POLL_INTERVAL, WAIT_TIMEOUT,};use personhog_coordination::error::Result;use personhog_coordination::routing_table::{RoutingTable, RoutingTableConfig, StashHandler};@@ -160,6 +160,52 @@ async fn router_exits_when_lease_revoked() {cancel.cancel();}+/// A leader whose election lease is revoked externally must abdicate and+/// re-campaign, not keep coordinating as a zombie on a dead lease. Unlike+/// pods and routers, the coordinator's run loop survives lease loss by+/// design — so the observable contract is in etcd: with a single+/// candidate, the leader key can only reappear if the old leader noticed+/// the loss and ran a fresh campaign; a zombie leaves it absent forever.+#[tokio::test]+async fn coordinator_abdicates_and_recampaigns_when_election_lease_revoked() {+ let (store, prefix) = test_store_with_prefix("coordinator-abdicate").await;+ let cancel = CancellationToken::new();++ // lease_ttl 5 → 1s keepalive, so the loss is observed within ~a second.+ let handle = start_coordinator_named(+ Arc::clone(&store),+ "abdicate-coordinator-0",+ 5,+ Arc::new(StickyBalancedStrategy),+ cancel.clone(),+ );++ let check_store = Arc::clone(&store);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let store = Arc::clone(&check_store);+ async move { store.get_leader().await.ok().flatten().is_some() }+ })+ .await;++ revoke_lease_of_key(&format!("{prefix}coordinator/leader")).await;++ // Keepalive notices within ~1s, abdication plus the 1s campaign retry+ // re-creates the key — well inside 10s against local etcd.+ let check_store = Arc::clone(&store);+ wait_for_condition(Duration::from_secs(10), POLL_INTERVAL, || {+ let store = Arc::clone(&check_store);+ async move { store.get_leader().await.ok().flatten().is_some() }+ })+ .await;++ cancel.cancel();+ tokio::time::timeout(Duration::from_secs(10), handle)+ .await+ .expect("coordinator must exit promptly on cancellation")+ .expect("coordinator task must not panic")+ .expect("graceful cancellation must exit cleanly after an abdication cycle");+}+// ============================================================// Cancelled handoffs converge on the durable state// ============================================================diff --git a/rust/personhog-router/src/config.rs b/rust/personhog-router/src/config.rsindex 7fdae6900257..9f77b777369d 100644--- a/rust/personhog-router/src/config.rs+++ b/rust/personhog-router/src/config.rs@@ -165,10 +165,13 @@ pub struct Config {#[envconfig(default = "router-0")]pub pod_name: String,- #[envconfig(default = "30")]+ /// Registration lease TTL. A crashed router stays in every freeze+ /// quorum until this expires, stalling any handoff frozen in that+ /// window — keep it short. Graceful exits deregister immediately.+ #[envconfig(default = "10")]pub lease_ttl: i64,- #[envconfig(default = "10")]+ #[envconfig(default = "3")]pub heartbeat_interval_secs: u64,/// Leader gRPC port used when resolving pod names to addresses@@ -209,16 +212,22 @@ pub struct Config {pub stash_drain_concurrency: usize,// ── coordinator (leader election among router-leader pods) ───- /// Lease TTL for the coordinator leader election- #[envconfig(default = "15")]+ /// 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+ /// the election retry interval. Graceful exits revoke the lease and+ /// fail over immediately.+ #[envconfig(default = "5")]pub coordinator_lease_ttl: i64,- /// Keepalive interval for the coordinator lease- #[envconfig(default = "5")]+ /// Keepalive interval for the coordinator lease. Several attempts+ /// must fit inside the TTL; a keepalive that reports the lease gone+ /// makes the leader abdicate.+ #[envconfig(default = "1")]pub coordinator_keepalive_secs: u64,- /// Retry interval when coordinator fails to acquire leadership- #[envconfig(default = "5")]+ /// Retry interval between a standby candidate's election campaigns.+ #[envconfig(default = "1")]pub coordinator_election_retry_secs: u64,/// Debounce interval (ms) for batching pod events before rebalancingdiff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rsindex 1226c7939c9f..b56ad9e5a595 100644--- a/rust/personhog-router/src/main.rs+++ b/rust/personhog-router/src/main.rs@@ -70,6 +70,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {.with_global_shutdown_timeout(Duration::from_secs(30)).build();+ // Shutdown order is the inverse of the leader's: the gRPC server+ // drains first (phase 0) while the routing table, coordinator, and+ // discovery stay alive to serve its in-flight requests and keep+ // acking freezes; they stop in phase 1, at which point the+ // coordinator exits cleanly and revokes the election lease so another+ // router takes over coordination immediately.let grpc_handle = manager.register("grpc-server",ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(15)),@@ -83,11 +89,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {let (routing_table_handle, coordinator_handle) = if config.router_mode == RouterMode::Leader {let rt = manager.register("routing-table",- ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(5)),+ ComponentOptions::new()+ .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)),+ ComponentOptions::new()+ .with_graceful_shutdown(Duration::from_secs(5))+ .with_shutdown_phase(1),);(Some(rt), Some(coord))} else {@@ -96,10 +106,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {// Register discovery handle before monitor_background() consumes the managerlet discovery_handle = if config.replica_discovery_mode == ReplicaDiscoveryMode::K8s {- Some(manager.register(- "replica-discovery",- ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(5)),- ))+ Some(+ manager.register(+ "replica-discovery",+ ComponentOptions::new()+ .with_graceful_shutdown(Duration::from_secs(5))+ .with_shutdown_phase(1),+ ),+ )} else {None};diff --git a/rust/personhog-test-harness/README.md b/rust/personhog-test-harness/README.mdindex e394ce61260e..f6ba5dfbaf8a 100644--- a/rust/personhog-test-harness/README.md+++ b/rust/personhog-test-harness/README.md@@ -112,11 +112,25 @@ The lifecycle crate now supports ordered shutdown phases (`ComponentOptions::wittarget/debug/personhog-test-harness gate --leaders 3 --duration 15s --shutdown-after 5s```-**A crashed coordinator blocks all handoffs for 10–20s — currently masked in the gate.**-The coordinator election is a lease-backed CAS (15s TTL, 5s keepalives, 5s campaign retry); a crash of the router holding it leaves the key in place until the lease expires, and no handoff can start until a survivor wins.-Leader crashes are usually unaffected (their own 30s registration lease gates discovery anyway), but a leader *drain* during the window stalls — which today, combined with the unordered-shutdown defect above, black-holes the draining pod's partitions for the whole gap (observed: 731 failed writes in ~10s at harness scale; one served strong read also returned NotFound for a person with acked writes, unreproduced and unexplained).-The gate's coordinator-kill scenario deliberately revokes the election lease to stay deterministic, so it does NOT exercise this window; the slow-failover variant is worth adding once the shutdown ordering is fixed and traffic survives the wait.-Fix direction: release the election on graceful exit reliably (the best-effort revoke can be dropped by the surrounding `select!` before it runs), and/or tune the election lease and retry intervals against the drain grace budget.+**A crashed or restarted coordinator blocked all handoffs for 10–30s — FIXED.**+Two leases gated failover and both could dangle. The election lease's revoke-on-exit could be dropped by an unbiased `select!` racing cancellation, so even graceful restarts stranded the election until its TTL; and a router never deregistered on exit, so freeze quorums kept counting it until its registration lease expired, stalling any handoff frozen in that window.+Graceful exits now run both revokes deterministically (measured handover: ~250ms), a failed election keepalive makes the leader abdicate instead of coordinating as a zombie beside its successor, and crash failover is bounded by tightened TTLs (election 5s + 1s campaign retry, registration 10s with 3s heartbeats).+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 \+ --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 \+ --router-kill-after 4s --router-kill-fast false --shutdown-after 8s+```++The one served strong read that returned NotFound during the original coordinator-less drain (pre-fix, compounded by unordered shutdown) has not reproduced across the newly covered slow-failover runs with probers active.**A drain overlapping a pod death wedged convergence for the drained pod's full lifecycle timeout — MOSTLY FIXED by the shutdown phases above.**The rebalance a drain triggers can race a concurrent pod death and create handoffs targeting the dead pod (self-healing: stale-handoff cleanup deletes them within a tick), and the re-drive rebalance still counts the *draining* pod as an assignment target — nothing marks it as leaving — handing partitions back to it.diff --git a/rust/personhog-test-harness/src/cli.rs b/rust/personhog-test-harness/src/cli.rsindex dbdec1872006..824daa1ac191 100644--- a/rust/personhog-test-harness/src/cli.rs+++ b/rust/personhog-test-harness/src/cli.rs@@ -218,6 +218,20 @@ pub struct GateArgs {#[arg(long, value_parser = humantime::parse_duration)]pub router_kill_after: Option<Duration>,+ /// With --router-kill-after: also revoke the router's registration and+ /// election leases so failover is immediate. Set false for a true+ /// crash — the survivor is blind until both leases expire, exercising+ /// the slow-failover window (election TTL + campaign retry).+ #[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.+ #[arg(long, value_parser = humantime::parse_duration)]+ pub router_shutdown_after: Option<Duration>,+/// After the first handoff-creating event (--shutdown-after or/// --scale-up-after) fires, watch for the resulting handoff and SIGKILL/// its target pod mid-handoff. Best effort: a handoff that completesdiff --git a/rust/personhog-test-harness/src/scenarios/gate.rs b/rust/personhog-test-harness/src/scenarios/gate.rsindex 9dbf32e3e7fc..e4e740ffd66c 100644--- a/rust/personhog-test-harness/src/scenarios/gate.rs+++ b/rust/personhog-test-harness/src/scenarios/gate.rs@@ -32,7 +32,8 @@ enum ChaosEvent {WriterCrash,WriterPause,WriterResume,- RouterKill,+ RouterKill { fast: bool },+ RouterShutdown,}impl fmt::Display for ChaosEvent {@@ -48,7 +49,11 @@ impl fmt::Display for ChaosEvent {ChaosEvent::WriterCrash => write!(f, "writer crash-restart"),ChaosEvent::WriterPause => write!(f, "writer pause (lag injection)"),ChaosEvent::WriterResume => write!(f, "writer resume"),- ChaosEvent::RouterKill => write!(f, "coordinator router kill"),+ ChaosEvent::RouterKill { fast: true } => write!(f, "coordinator router kill"),+ ChaosEvent::RouterKill { fast: false } => {+ write!(f, "coordinator router crash (lease TTL expiry)")+ }+ ChaosEvent::RouterShutdown => write!(f, "coordinator router graceful shutdown"),}}}@@ -84,7 +89,15 @@ fn chaos_timeline(args: &GateArgs) -> Vec<(Duration, ChaosEvent)> {events.push((after + args.writer_pause_duration, ChaosEvent::WriterResume));}if let Some(after) = args.router_kill_after {- events.push((after, ChaosEvent::RouterKill));+ events.push((+ after,+ ChaosEvent::RouterKill {+ fast: args.router_kill_fast,+ },+ ));+ }+ if let Some(after) = args.router_shutdown_after {+ events.push((after, ChaosEvent::RouterShutdown));}events.sort_by_key(|(after, _)| *after);events@@ -118,7 +131,9 @@ pub async fn run(args: GateArgs) -> Result<()> {if args.external_router_url.is_some() && (!chaos.is_empty() || args.kill_handoff_target) {bail!("chaos flags require a spawned stack; they cannot target --external-router-url");}- if args.router_kill_after.is_some() && args.routers < 2 {+ if (args.router_kill_after.is_some() || args.router_shutdown_after.is_some())+ && args.routers < 2+ {bail!("--router-kill-after requires --routers >= 2 (traffic targets the last router)");}if args.kill_handoff_target && args.shutdown_after.is_none() && args.scale_up_after.is_none() {@@ -247,7 +262,8 @@ pub async fn run(args: GateArgs) -> Result<()> {stack.resume_writer()?;None}- ChaosEvent::RouterKill => Some(stack.kill_coordinator_router().await?),+ ChaosEvent::RouterKill { fast } => Some(stack.kill_coordinator_router(fast).await?),+ ChaosEvent::RouterShutdown => Some(stack.shutdown_coordinator_router()?),};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.rsindex a87a630a595b..505e6b34025c 100644--- a/rust/personhog-test-harness/src/stack/mod.rs+++ b/rust/personhog-test-harness/src/stack/mod.rs@@ -354,17 +354,40 @@ impl Stack {/// 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 15s election TTL). Handoffs created after this run under- /// the new coordinator.- pub async fn kill_coordinator_router(&mut self) -> Result<String> {+ /// 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");}let (name, mut proc) = self.routers.remove(0);proc.kill_now().await;- etcd::revoke_router_lease(&self.store, &name).await?;- let held_election = etcd::revoke_coordinator_lease_if_held_by(&self.store, &name).await?;- tracing::info!(router = %name, held_election, "killed coordinator router");+ if fast {+ etcd::revoke_router_lease(&self.store, &name).await?;+ let held_election =+ etcd::revoke_coordinator_lease_if_held_by(&self.store, &name).await?;+ tracing::info!(router = %name, held_election, "killed coordinator router");+ } else {+ // Registration and election leases linger until their TTLs+ // expire: the survivor stays blind to the death, and no+ // handoff can start until the election lease frees up.+ tracing::info!(router = %name, "crashed coordinator router (leases left to expire)");+ }+ self.retired.push(proc);+ Ok(name)+ }++ /// SIGTERM the first router (the presumed coordinator) — 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");+ }+ let (name, proc) = self.routers.remove(0);+ proc.sigterm();+ tracing::info!(router = %name, "requested graceful shutdown of coordinator router");self.retired.push(proc);Ok(name)}