: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): complete the handoff that was verified, not the one at the key (#76358)
Zach Brownadc74ebe7a30
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 1c21f58c4c29..f2d0bba8ec6f 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -8477,6 +8477,7 @@ dependencies = ["k8s-openapi","kube","metrics",+ "personhog-coordination","serde","serde_json","serial_test",diff --git a/rust/personhog-coordination/Cargo.toml b/rust/personhog-coordination/Cargo.tomlindex c83b99d0e2e9..7752bf1b9525 100644--- a/rust/personhog-coordination/Cargo.toml+++ b/rust/personhog-coordination/Cargo.toml@@ -19,15 +19,18 @@ tokio-util = { version = "0.7", features = ["rt"] }tracing = { workspace = true }uuid = { workspace = true }-[features]-# States the tests need to construct but that no production caller may-# reach — an authority clock whose renewals stopped long enough ago to-# have lapsed, which otherwise takes a real wait to reproduce.-# Consumed by personhog-leader's dev-dependency on this crate.+# States and operations tests need but that no production caller may+# reach: an authority clock whose renewals stopped long enough ago to+# have lapsed (otherwise a real wait to reproduce), and the store+# operations that bypass the protocol — writing an assignment owner+# directly, putting or deleting a handoff record — which adversarial+# tests use to construct states production must never enter. Consumed+# by this crate's own dev-dependency and by personhog-leader's.test-support = [][dev-dependencies]+personhog-coordination = { path = ".", features = ["test-support"] }k8s-openapi = { version = "0.24", features = ["latest"] }kube = { version = "0.98", features = ["client"] }serial_test = "3"diff --git a/rust/personhog-coordination/src/coordinator.rs b/rust/personhog-coordination/src/coordinator.rsindex a1f0c8758c52..283544259a66 100644--- a/rust/personhog-coordination/src/coordinator.rs+++ b/rust/personhog-coordination/src/coordinator.rs@@ -673,7 +673,12 @@ impl Coordinator {Some(_) => HandoffPhase::Draining,};let advanced = store- .cas_handoff_phase(partition, HandoffPhase::Freezing, target)+ .cas_handoff_phase(+ partition,+ &handoff.handoff_id,+ HandoffPhase::Freezing,+ target,+ ).await?;if advanced {record_phase_advance(&handoff, target);@@ -713,7 +718,12 @@ impl Coordinator {let drained_acks = store.list_drained_acks(partition).await?;if drain_satisfied(&pods, &drained_acks, &handoff) {let advanced = store- .cas_handoff_phase(partition, HandoffPhase::Draining, HandoffPhase::Warming)+ .cas_handoff_phase(+ partition,+ &handoff.handoff_id,+ HandoffPhase::Draining,+ HandoffPhase::Warming,+ ).await?;if advanced {record_phase_advance(&handoff, HandoffPhase::Warming);@@ -739,7 +749,10 @@ impl Coordinator {new_owner = %handoff.new_owner,"new owner warmed, completing handoff");- match store.complete_handoff(partition).await {+ match store+ .complete_handoff(partition, &handoff.handoff_id, HandoffPhase::Warming)+ .await+ {Ok(true) => {record_phase_advance(&handoff, HandoffPhase::Complete);if trigger == AdvanceTrigger::Ack {diff --git a/rust/personhog-coordination/src/pod.rs b/rust/personhog-coordination/src/pod.rsindex 89fa6adf2e9b..ca239a2ef97a 100644--- a/rust/personhog-coordination/src/pod.rs+++ b/rust/personhog-coordination/src/pod.rs@@ -1096,12 +1096,13 @@ impl PodHandle {tracing::info!(pod, partition, "converging to Drained: fencing + draining");did_work = true;}- // Recorded before the handler runs, not after. The- // handler fences the data plane as its first act and can- // fail afterwards; a record written only on success would- // leave writes fenced with no branch left to re-enter,- // since `resume_partition` below is reachable only- // through this set.+ // Record the fence before the call that applies it. The+ // handler fences as its first action and only then waits,+ // so a failure after that point would otherwise leave the+ // data plane fenced with nothing here to say so — and a+ // later convergence to Serving, seeing no fence recorded,+ // would skip the resume that lifts it. Recording early+ // only risks a redundant resume, which is a no-op.self.fenced_partitions.lock().await.insert(partition);let start = Instant::now();self.handler.drain_partition_inflight(partition).await?;@@ -1143,19 +1144,14 @@ impl PodHandle {},);if !valid {- if self- .warmed_partitions- .lock()- .await- .remove(&partition)- .is_some()- {+ if self.warmed_partitions.lock().await.contains_key(&partition) {tracing::info!(pod,partition,"converging to Acquiring: releasing a warm from an earlier era");self.handler.release_partition(partition).await?;+ self.warmed_partitions.lock().await.remove(&partition);}tracing::info!(pod, partition, "converging to Acquiring: warming");let _warm_slot = self.acquire_warm_slot().await?;@@ -1169,6 +1165,9 @@ impl PodHandle {);did_work = true;}+ // The warm above re-admits writes for this partition as+ // part of taking ownership, so clearing the record here+ // matches the data plane rather than diverging from it.self.fenced_partitions.lock().await.remove(&partition);self.store.put_warmed_ack(&PodWarmedAck {@@ -1612,6 +1611,19 @@ mod tests {Some(handoff(Some(POD), OTHER, Complete)),Released,),+ (+ // A cancelled handoff is replaced by a reaffirm toward+ // the current owner, and the coordinator deliberately+ // leaves `old_owner` unset on it: naming this pod on+ // both sides would match the old-owner arm first and+ // release the partition instead of resuming it. That is+ // a silent partition drop, so the shape is pinned here+ // rather than left to a comment.+ "reaffirmed owner resumes rather than releasing",+ Some(assignment(POD)),+ Some(handoff(None, POD, Complete)),+ Serving,+ ),("new owner must not hold the partition in Freezing",Some(assignment(OTHER)),diff --git a/rust/personhog-coordination/src/store.rs b/rust/personhog-coordination/src/store.rsindex 858c9ef7ec45..fc590fb8c582 100644--- a/rust/personhog-coordination/src/store.rs+++ b/rust/personhog-coordination/src/store.rs@@ -111,6 +111,8 @@ impl PersonhogStore {Ok(self.inner.get(&key).await?)}+ /// Bypasses the protocol: see the crate's `test-support` feature.+ #[cfg(any(test, feature = "test-support"))]pub async fn delete_pod(&self, pod_name: &str) -> Result<()> {let key = self.key(StoreKey::Pod(pod_name));Ok(self.inner.delete(&key).await?)@@ -213,6 +215,8 @@ impl PersonhogStore {Ok(self.inner.list_with_mod_revisions(&key).await?)}+ /// Bypasses the protocol: see the crate's `test-support` feature.+ #[cfg(any(test, feature = "test-support"))]pub async fn put_assignments(&self, assignments: &[PartitionAssignment]) -> Result<()> {if assignments.is_empty() {return Ok(());@@ -258,6 +262,8 @@ impl PersonhogStore {Ok(self.inner.list_with_mod_revisions(&key).await?)}+ /// Bypasses the protocol: see the crate's `test-support` feature.+ #[cfg(any(test, feature = "test-support"))]pub async fn put_handoff(&self, handoff: &HandoffState) -> Result<()> {let key = self.key(StoreKey::Handoff(handoff.partition));Ok(self.inner.put(&key, handoff, None).await?)@@ -274,9 +280,16 @@ impl PersonhogStore {/// Used by `check_phase_advance` to avoid duplicate phase writes when/// multiple watch loops fire `check_phase_advance` concurrently for the/// same partition.+ /// `expected_id` names the handoff attempt the caller validated. The+ /// key can be replaced between that validation and this write —+ /// cancellation swaps in a successor and deletes the old acks in one+ /// transaction — and a `mod_revision` guard taken on a re-read here+ /// would not notice, because it only proves nothing changed since+ /// *this* function looked.pub async fn cas_handoff_phase(&self,partition: u32,+ expected_id: &str,expected: crate::types::HandoffPhase,new_phase: crate::types::HandoffPhase,) -> Result<bool> {@@ -288,7 +301,7 @@ impl PersonhogStore {else {return Ok(false);};- if handoff.phase != expected {+ if handoff.phase != expected || handoff.handoff_id != expected_id {return Ok(false);}handoff.phase = new_phase;@@ -359,6 +372,8 @@ impl PersonhogStore {Ok(resp.succeeded())}+ /// Bypasses the protocol: see the crate's `test-support` feature.+ #[cfg(any(test, feature = "test-support"))]pub async fn delete_handoff(&self, partition: u32) -> Result<()> {let key = self.key(StoreKey::Handoff(partition));Ok(self.inner.delete(&key).await?)@@ -595,7 +610,18 @@ impl PersonhogStore {/// writes (e.g. if another actor already completed or deleted the handoff/// between our read and write).///- /// Returns `Ok(false)` if the handoff was modified concurrently (CAS failed).+ /// Returns `Ok(false)` if the handoff was modified concurrently (CAS failed),+ /// or if the record at the key is no longer the attempt the caller+ /// validated.+ ///+ /// The `expected_*` arguments are what make the second case+ /// detectable, and they are not optional rigour. Completion is the+ /// step that writes the assignment, so completing the wrong record+ /// hands the partition to a pod that never froze, drained, or warmed+ /// — while the old owner is still admitting writes — and routers cut+ /// over to it. A `mod_revision` guard alone cannot catch that: it+ /// proves nothing changed since this function's own re-read, not that+ /// the record is the one whose warm was verified.////// **Invariant:** this is the only code path that ever *changes* an/// assignment's `owner`. Routers rely on observing handoff Complete@@ -604,7 +630,12 @@ impl PersonhogStore {/// of this method will be invisible to routers. If we ever need a/// force-reassignment ops tool, it should create a handoff record and/// let the protocol advance it, not write to the assignment key.- pub async fn complete_handoff(&self, partition: u32) -> Result<bool> {+ pub async fn complete_handoff(+ &self,+ partition: u32,+ expected_id: &str,+ expected_phase: crate::types::HandoffPhase,+ ) -> Result<bool> {let handoff_key = self.key(StoreKey::Handoff(partition));let (mut handoff, mod_revision) = self@@ -613,6 +644,10 @@ impl PersonhogStore {.await?.ok_or_else(|| Error::NotFound(format!("handoff for partition {partition}")))?;+ if handoff.handoff_id != expected_id || handoff.phase != expected_phase {+ return Ok(false);+ }+handoff.phase = crate::types::HandoffPhase::Complete;handoff.phase_entered_at_ms = assignment_coordination::util::now_millis();diff --git a/rust/personhog-coordination/tests/protocol_hardening.rs b/rust/personhog-coordination/tests/protocol_hardening.rsindex f8b603d56555..a5ee44d7c5e5 100644--- a/rust/personhog-coordination/tests/protocol_hardening.rs+++ b/rust/personhog-coordination/tests/protocol_hardening.rs@@ -323,8 +323,16 @@ async fn pod_resumes_partition_when_cancelled_handoff_leaves_it_assigned() {// (which writes the assignment atomically) and clean up the record.put_handoff(&store, 0, None, "resume-pod-a", HandoffPhase::Warming).await;wait_for_event(&pod.events, HandoffEvent::Warmed(0)).await;+ let warming = store+ .get_handoff(0)+ .await+ .expect("get handoff")+ .expect("handoff exists");assert!(- store.complete_handoff(0).await.expect("complete"),+ store+ .complete_handoff(0, &warming.handoff_id, HandoffPhase::Warming)+ .await+ .expect("complete"),"complete_handoff must succeed");store.delete_handoff(0).await.expect("cleanup");@@ -3178,7 +3186,15 @@ async fn pod_retries_resume_after_a_failed_attempt() {put_handoff(&store, 0, None, "resume-flaky-a", HandoffPhase::Warming).await;wait_for_event(&pod.events, HandoffEvent::Warmed(0)).await;- assert!(store.complete_handoff(0).await.expect("complete"));+ let warmed = store+ .get_handoff(0)+ .await+ .expect("get handoff")+ .expect("handoff exists");+ assert!(store+ .complete_handoff(0, &warmed.handoff_id, HandoffPhase::Warming)+ .await+ .expect("complete"));store.delete_handoff(0).await.expect("cleanup");put_handoff(@@ -3984,3 +4000,89 @@ async fn a_failed_release_is_retried_rather_than_forgotten() {cancel.cancel();}++/// Completion must apply to the handoff whose warm was verified, not to+/// whatever record is at the key when the write lands.+///+/// The coordinator reads a handoff, checks its warmed acks, and then+/// completes it. In between, cancellation can replace the record with a+/// successor and delete the old acks in one transaction. Completing that+/// successor would write the assignment to a pod that never froze,+/// drained, or warmed — while the old owner is still admitting writes —+/// and routers would cut over to it. A `mod_revision` guard cannot see+/// this: it only proves nothing changed since the store's own re-read.+#[tokio::test]+async fn completion_refuses_a_handoff_that_was_replaced() {+ let store = test_store("complete-replaced").await;++ // The attempt the caller validated.+ put_handoff(&store, 0, Some("pod-a"), "pod-b", HandoffPhase::Warming).await;+ let validated = store+ .get_handoff(0)+ .await+ .expect("get handoff")+ .expect("handoff exists");++ // Cancellation replaces it with a successor carrying a fresh id,+ // exactly as `handle_pod_change_static` does.+ store.delete_handoff(0).await.expect("delete");+ put_handoff_with_id(&store, 0, "pod-c", HandoffPhase::Freezing, "successor").await;++ let completed = store+ .complete_handoff(0, &validated.handoff_id, HandoffPhase::Warming)+ .await+ .expect("complete_handoff");+ assert!(+ !completed,+ "a replaced handoff must not be completed by its predecessor's verification"+ );++ // The successor must still be Freezing, and no assignment written.+ let current = store+ .get_handoff(0)+ .await+ .expect("get handoff")+ .expect("handoff exists");+ assert_eq!(current.phase, HandoffPhase::Freezing);+ assert!(+ store+ .get_assignment(0)+ .await+ .expect("get assignment")+ .is_none(),+ "no assignment may be written for a handoff that never completed"+ );+}++/// The same guard on the phase advances: a successor at the same phase+/// must not inherit its predecessor's verification.+#[tokio::test]+async fn phase_advance_refuses_a_handoff_that_was_replaced() {+ let store = test_store("advance-replaced").await;++ put_handoff(&store, 0, Some("pod-a"), "pod-b", HandoffPhase::Freezing).await;+ let validated = store+ .get_handoff(0)+ .await+ .expect("get handoff")+ .expect("handoff exists");++ store.delete_handoff(0).await.expect("delete");+ // Same phase, different attempt: the id is the only thing that can+ // tell them apart, which is the point.+ put_handoff_with_id(&store, 0, "pod-c", HandoffPhase::Freezing, "successor").await;++ let advanced = store+ .cas_handoff_phase(+ 0,+ &validated.handoff_id,+ HandoffPhase::Freezing,+ HandoffPhase::Draining,+ )+ .await+ .expect("cas_handoff_phase");+ assert!(+ !advanced,+ "a replaced handoff must not be advanced by its predecessor's quorum"+ );+}