: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
feat(personhog): pre-connect the fence producer (#80827)
Zach Brown208c61454f09
diff --git a/rust/common/kafka/src/transaction.rs b/rust/common/kafka/src/transaction.rsindex ae5db75b493c..372511c658de 100644--- a/rust/common/kafka/src/transaction.rs+++ b/rust/common/kafka/src/transaction.rs@@ -126,44 +126,119 @@ wheretimeout: Duration,}-impl TransactionalProducer<DefaultClientContext> {- // Create a transactional producer, with a default context- pub fn from_config(- config: &KafkaConfig,- transactional_id: &str,- timeout: Duration,- ) -> Result<Self, KafkaError> {- Self::with_context(config, transactional_id, timeout, DefaultClientContext)- }+/// A transactional producer that is connected but not yet initialized:+/// the client exists with its connections and metadata warm, and no+/// broker-side transactional state has been touched. `init_transactions`+/// is the fencing action — it bumps the transactional id's epoch and+/// cuts off every previous owner — so it belongs to the moment authority+/// is taken, not to construction. Splitting the phases lets a caller pay+/// the connection cost ahead of that moment.+pub struct ConnectedTransactionalProducer<C = DefaultClientContext>+where+ C: ClientContext + 'static,+{+ inner: FutureProducer<C>,+}- /// A producer whose open transactions the broker abandons after- /// `broker_txn_timeout`, rather than after librdkafka's default- /// minute.- ///- /// This is a different quantity from `timeout`, which bounds how long- /// *this process* waits on a blocking transactional call. The broker- /// bound matters to everyone else: until an abandoned transaction- /// expires, the partition's last-stable-offset does not advance and- /// every `read_committed` consumer stalls behind it.+impl ConnectedTransactionalProducer<DefaultClientContext> {+ /// Create the client and ping the brokers, bounded by `timeout`,+ /// without initializing transactions — a producer whose open+ /// transactions the broker abandons after `broker_txn_timeout`,+ /// rather than after librdkafka's default minute.///- /// Only a caller that also controls `message.timeout.ms` can set it,- /// because librdkafka requires `message.timeout.ms <=- /// transaction.timeout.ms` and refuses to build the producer at all- /// otherwise — which is why this is opt-in rather than derived from- /// the operation timeout.- pub fn from_config_bounded(+ /// The broker bound is a different quantity from `timeout`, which+ /// bounds how long *this process* waits on a blocking call. It+ /// matters to everyone else: until an abandoned transaction expires,+ /// the partition's last-stable-offset does not advance and every+ /// `read_committed` consumer stalls behind it. Only a caller that+ /// also controls `message.timeout.ms` can set it, because librdkafka+ /// requires `message.timeout.ms <= transaction.timeout.ms` and+ /// refuses to build the producer at all otherwise.+ pub fn connect_bounded(config: &KafkaConfig,transactional_id: &str,timeout: Duration,broker_txn_timeout: Duration,) -> Result<Self, KafkaError> {- Self::build(+ let inner = connect(config,transactional_id,timeout,Some(broker_txn_timeout),DefaultClientContext,- )+ )?;+ Ok(ConnectedTransactionalProducer { inner })+ }+}++impl<C: ClientContext> ConnectedTransactionalProducer<C> {+ /// Claim the transactional id: one `init_transactions` round trip,+ /// which fences every previous owner of the id.+ pub fn init(+ self,+ timeout: Duration,+ ) -> Result<TransactionalProducer<C>, (KafkaError, ConnectedTransactionalProducer<C>)> {+ match self.inner.init_transactions(timeout) {+ Ok(()) => Ok(TransactionalProducer {+ inner: self.inner,+ timeout,+ }),+ // Hand the connection back with the error: a timed-out init+ // does not invalidate the client, and the caller decides+ // whether to retry on it or discard it.+ Err(e) => Err((e, self)),+ }+ }+}++/// Create the client and ping the brokers: everything construction does+/// short of `init_transactions`.+fn connect<C: ClientContext>(+ config: &KafkaConfig,+ transactional_id: &str,+ timeout: Duration,+ broker_txn_timeout: Option<Duration>,+ context: C,+) -> Result<FutureProducer<C>, KafkaError> {+ let client_config = transactional_client_config(config, transactional_id, broker_txn_timeout)?;++ debug!("rdkafka configuration: {:?}", client_config);+ let api: FutureProducer<C> = client_config.create_with_context(context)?;++ // "Ping" the Kafka brokers by requesting metadata. On the+ // broker-bounded (partition-acquisition) path the ping is bounded+ // by the caller's timeout — an unbounded stall there holds a warm+ // slot and delays a handoff. Everywhere else the historical fixed+ // bound is kept, so services that never opted into broker bounds+ // keep their startup behavior.+ let ping_timeout = if broker_txn_timeout.is_some() {+ timeout+ } else {+ UNBOUNDED_PING_TIMEOUT+ };+ match api.client().fetch_metadata(None, ping_timeout) {+ Ok(metadata) => {+ info!(+ "Successfully connected to Kafka brokers. Found {} topics.",+ metadata.topics().len()+ );+ }+ Err(error) => {+ error!("Failed to fetch metadata from Kafka brokers: {:?}", error);+ return Err(error);+ }+ }+ Ok(api)+}++impl TransactionalProducer<DefaultClientContext> {+ // Create a transactional producer, with a default context+ pub fn from_config(+ config: &KafkaConfig,+ transactional_id: &str,+ timeout: Duration,+ ) -> Result<Self, KafkaError> {+ Self::with_context(config, transactional_id, timeout, DefaultClientContext)}}@@ -184,38 +259,14 @@ impl<C: ClientContext> TransactionalProducer<C> {broker_txn_timeout: Option<Duration>,context: C,) -> Result<Self, KafkaError> {- let client_config =- transactional_client_config(config, transactional_id, broker_txn_timeout)?;-- debug!("rdkafka configuration: {:?}", client_config);- let api: FutureProducer<C> = client_config.create_with_context(context)?;-- // "Ping" the Kafka brokers by requesting metadata. On the- // broker-bounded (partition-acquisition) path the ping is bounded- // by the caller's timeout — an unbounded stall there holds a warm- // slot and delays a handoff. Everywhere else the historical fixed- // bound is kept, so services that never opted into broker bounds- // keep their startup behavior.- let ping_timeout = if broker_txn_timeout.is_some() {- timeout- } else {- UNBOUNDED_PING_TIMEOUT- };- match api.client().fetch_metadata(None, ping_timeout) {- Ok(metadata) => {- info!(- "Successfully connected to Kafka brokers. Found {} topics.",- metadata.topics().len()- );- }- Err(error) => {- error!("Failed to fetch metadata from Kafka brokers: {:?}", error);- return Err(error);- }- }-+ let api = connect(+ config,+ transactional_id,+ timeout,+ broker_txn_timeout,+ context,+ )?;api.init_transactions(timeout)?;-Ok(TransactionalProducer {inner: api,timeout,@@ -367,7 +418,7 @@ mod tests {kafka_message_timeout_ms: 20_000,..KafkaConfig::default()};- let Err(err) = TransactionalProducer::from_config_bounded(+ let Err(err) = ConnectedTransactionalProducer::connect_bounded(&config,"test-txn-id",Duration::from_secs(10),diff --git a/rust/personhog-coordination/src/pod.rs b/rust/personhog-coordination/src/pod.rsindex 77767336cd08..8d2dc10e00f0 100644--- a/rust/personhog-coordination/src/pod.rs+++ b/rust/personhog-coordination/src/pod.rs@@ -147,6 +147,16 @@ pub trait HandoffHandler: Send + Sync {Ok(false)}+ /// The handoff names this pod as the incoming owner, but acquisition+ /// is not yet permitted (the old owner is still freezing or+ /// draining). A hint, not a phase: implementations may use the+ /// window to prepare state whose setup touches nothing shared — the+ /// leader pre-connects its changelog producer here so the fence+ /// acquisition inside the warm pays only the init round trip. Called+ /// on every convergence observing that window, so implementations+ /// must be idempotent and must not block: spawn and return.+ async fn prepare_acquire(&self, _partition: u32) {}+/// Old owner: release the partition from this pod's local state (drop cache,/// close consumers, etc.).///@@ -1056,6 +1066,21 @@ impl PodHandle {let desired = desired_state(pod, assignment, handoff);let mut did_work = false;+ // The pending-ownership window: this pod will be told to warm+ // once the drain completes, and everything the warm needs that+ // touches no shared state can get ready now. Deliberately not a+ // DesiredState — the derivation stays a pure ownership answer —+ // and deliberately not `did_work`: preparation is a hint, and+ // counting it as progress would let a pod that only ever+ // prepares look healthy to the budgets.+ if let Some(h) = handoff {+ if h.new_owner == *pod+ && matches!(h.phase, HandoffPhase::Freezing | HandoffPhase::Draining)+ {+ self.handler.prepare_acquire(partition).await;+ }+ }+match desired {DesiredState::Serving => {if !self.warmed_partitions.lock().await.contains_key(&partition) {diff --git a/rust/personhog-coordination/tests/protocol_hardening.rs b/rust/personhog-coordination/tests/protocol_hardening.rsindex 93fc414a0bc2..d64d41324df4 100644--- a/rust/personhog-coordination/tests/protocol_hardening.rs+++ b/rust/personhog-coordination/tests/protocol_hardening.rs@@ -4221,3 +4221,120 @@ async fn a_repair_nudge_converges_without_waiting_for_reconcile() {cancel.cancel();}++/// Records `prepare_acquire` calls — the pending-ownership hint.+struct PrepareProbeHandler {+ events: Arc<Mutex<Vec<HandoffEvent>>>,+ prepared: Arc<AtomicUsize>,+}++#[async_trait]+impl personhog_coordination::pod::HandoffHandler for PrepareProbeHandler {+ async fn drain_partition_inflight(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Drained(partition));+ Ok(())+ }++ async fn warm_partition(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Warmed(partition));+ Ok(())+ }++ async fn prepare_acquire(&self, _partition: u32) {+ self.prepared.fetch_add(1, Ordering::SeqCst);+ }++ async fn release_partition(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Released(partition));+ Ok(())+ }++ async fn resume_partition(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Resumed(partition));+ Ok(())+ }+}++/// The incoming owner of a handoff still freezing or draining must see+/// the pending-ownership hint — the window where connection setup can+/// run ahead of the fence — while warming stays forbidden until the+/// phase says the HWM is stable.+#[tokio::test]+async fn a_pending_new_owner_is_hinted_but_not_warmed() {+ let store = test_store("pending-owner-hint").await;+ let cancel = CancellationToken::new();++ store+ .put_assignments(&[PartitionAssignment {+ partition: 0,+ owner: "old-pod".to_string(),+ status: AssignmentStatus::Active,+ advertise_address: None,+ }])+ .await+ .expect("write assignment");++ let events: Arc<Mutex<Vec<HandoffEvent>>> = Arc::new(Mutex::new(Vec::new()));+ let prepared = Arc::new(AtomicUsize::new(0));+ let handler = PrepareProbeHandler {+ events: Arc::clone(&events),+ prepared: Arc::clone(&prepared),+ };+ let pod = personhog_coordination::pod::PodHandle::new(+ Arc::clone(&store),+ personhog_coordination::pod::PodConfig {+ pod_name: "pre-pod".to_string(),+ lease_ttl: 30,+ heartbeat_interval: Duration::from_secs(10),+ reconcile_interval: Duration::from_secs(86_400),+ ..Default::default()+ },+ Arc::new(handler),+ None,+ Arc::new(AuthorityClock::unclaimed()),+ );+ let token = cancel.child_token();+ tokio::spawn(async move { pod.run(token).await });++ put_handoff(+ &store,+ 0,+ Some("old-pod"),+ "pre-pod",+ HandoffPhase::Draining,+ )+ .await;++ wait_for_condition_named(+ WAIT_TIMEOUT,+ POLL_INTERVAL,+ "pending new owner receives the prepare hint",+ || {+ let prepared = Arc::clone(&prepared);+ async move { prepared.load(Ordering::SeqCst) >= 1 }+ },+ )+ .await;+ assert!(+ !events+ .lock()+ .await+ .iter()+ .any(|e| matches!(e, HandoffEvent::Warmed(0))),+ "a draining handoff must hint the new owner without warming it"+ );++ cancel.cancel();+}diff --git a/rust/personhog-leader/src/coordination/mod.rs b/rust/personhog-leader/src/coordination/mod.rsindex d36538520e6b..e95784d2251d 100644--- a/rust/personhog-leader/src/coordination/mod.rs+++ b/rust/personhog-leader/src/coordination/mod.rs@@ -198,6 +198,20 @@ impl LeaderHandoffHandler {#[async_trait]impl HandoffHandler for LeaderHandoffHandler {+ async fn prepare_acquire(&self, partition: u32) {+ // Spawned: the convergence must not wait on a broker connect,+ // and `preconnect` is single-flight per partition, so repeated+ // convergences through the drain window cost one spawn each and+ // one client total. A parked connection the acquire never+ // consumes is discarded on release or by the periodic sweep —+ // a cancelled inbound handoff leaves no convergence behind, so+ // the sweep is the only path that reaches its leftovers.+ if let Some(fenced) = &self.fenced {+ let fenced = Arc::clone(fenced);+ tokio::spawn(async move { fenced.preconnect(partition).await });+ }+ }+async fn drain_partition_inflight(&self, partition: u32) -> Result<()> {info!(partition, "fencing writes and draining inflight handlers");// Fence before waiting: fencing only after the wait would leave adiff --git a/rust/personhog-leader/src/fencing.rs b/rust/personhog-leader/src/fencing.rsindex 2d66f29c4a2d..bab152380590 100644--- a/rust/personhog-leader/src/fencing.rs+++ b/rust/personhog-leader/src/fencing.rs@@ -29,7 +29,7 @@ use std::time::{Duration, Instant};use std::{fmt, mem};use common_kafka::config::KafkaConfig;-use common_kafka::transaction::TransactionalProducer;+use common_kafka::transaction::{ConnectedTransactionalProducer, TransactionalProducer};use dashmap::DashMap;use metrics::{counter, histogram};use prost::Message as ProtoMessage;@@ -127,6 +127,24 @@ struct Gate {waiters: Vec<oneshot::Sender<Result<(), FencedProduceError>>>,}+/// Initialize a connected producer on the blocking pool, claiming the+/// partition's transactional id. On failure the connection is discarded+/// there too — librdkafka teardown blocks — and only the error comes+/// back.+async fn init_producer(+ connected: ConnectedTransactionalProducer,+ timeout: Duration,+) -> Result<TransactionalProducer, String> {+ match spawn_blocking(move || connected.init(timeout)).await {+ Ok(Ok(ready)) => Ok(ready),+ Ok(Err((e, connected))) => {+ spawn_blocking(move || drop(connected));+ Err(format!("fence init: {e}"))+ }+ Err(e) => Err(format!("fence init join: {e}")),+ }+}+/// Send a fence to the blocking pool to die. Dropping the last/// reference runs librdkafka's destroy, which blocks while the client/// tears down — up to hundreds of milliseconds — and both removal sites@@ -433,6 +451,13 @@ pub struct FencedChangelogProducers {/// payload: the pass re-derives what needs converging, the same way/// the tick does. `None` leaves repair to the tick alone.repair_nudge: Option<Arc<Notify>>,+ /// Connected-but-uninitialized producers, one per partition at most,+ /// parked by `preconnect` for a later `acquire` to claim. Connection+ /// setup is the slow half of acquisition and touches no broker+ /// transactional state, so it can run ahead of the authority+ /// transition; `init_transactions` — the fencing action — still+ /// happens only inside `acquire`.+ prepared: DashMap<u32, ConnectedTransactionalProducer>,/// Outcomes a test stages for the next produce on a partition.////// The uncertain outcomes need a broker fault landing inside a@@ -479,6 +504,7 @@ impl FencedChangelogProducers {settle_budget,partitions: DashMap::new(),repair_nudge: None,+ prepared: DashMap::new(),#[cfg(any(test, feature = "test-support"))]staged_failures: DashMap::new(),}@@ -498,22 +524,55 @@ impl FencedChangelogProducers {/// partition's transactional id. Runs on the blocking pool — init is/// a synchronous broker round trip.async fn acquire_installed(&self, partition: u32) -> Result<Arc<PartitionFence>, String> {- let kafka = self.kafka.clone();- let tid = transactional_id(&self.topic, partition);let timeout = self.init_timeout;- let broker_txn_timeout = self.broker_txn_timeout;- let start = Instant::now();- let producer = spawn_blocking(move || {- TransactionalProducer::from_config_bounded(&kafka, &tid, timeout, broker_txn_timeout)- })- .await- .map_err(|e| format!("fence init join: {e}"))?- .map_err(|e| {- counter!("personhog_leader_fence_init_total", "outcome" => "error").increment(1);- format!("fence init: {e}")- })?;+ let mut start = Instant::now();+ // The two acquisition shapes differ only in when the connect+ // happened: a parked connection pays only the init round trip+ // here, and one whose init fails (it may simply have gone+ // stale) gets a single fresh connect-and-init rather than+ // failing the acquisition.+ let mut path = "cold";+ let mut producer = None;+ if let Some((_, parked)) = self.prepared.remove(&partition) {+ match init_producer(parked, timeout).await {+ Ok(ready) => {+ path = "prepared";+ producer = Some(ready);+ }+ Err(e) => {+ counter!("personhog_leader_fence_preconnect_total", "outcome" => "init_failed")+ .increment(1);+ warn!(+ partition,+ error = %e,+ "prepared connection failed to init; connecting fresh"+ );+ }+ }+ }+ let producer = match producer {+ Some(ready) => ready,+ None => {+ // Timed from here so a failed prepared attempt cannot+ // contaminate the cold path's histogram.+ start = Instant::now();+ let count_error = |e: String| {+ counter!("personhog_leader_fence_init_total", "outcome" => "error")+ .increment(1);+ e+ };+ let connected = self+ .connect_producer(partition)+ .await+ .map_err(count_error)?;+ init_producer(connected, timeout)+ .await+ .map_err(count_error)?+ }+ };counter!("personhog_leader_fence_init_total", "outcome" => "ok").increment(1);- histogram!("personhog_leader_fence_init_ms").record(start.elapsed().as_secs_f64() * 1000.0);+ histogram!("personhog_leader_fence_init_ms", "path" => path)+ .record(start.elapsed().as_secs_f64() * 1000.0);let installed = Arc::new(PartitionFence {producer,gate: Mutex::new(Gate {@@ -559,6 +618,101 @@ impl FencedChangelogProducers {if let Some((_, fence)) = self.partitions.remove(&partition) {drop_fence_off_worker(fence);}+ self.discard_prepared(partition);+ }++ /// Connect the partition's producer ahead of acquisition, so the+ /// acquire that follows pays only the init round trip. Runs the+ /// connection on the blocking pool and parks it; a failure is only+ /// logged and counted, because the cold acquire path covers it. At+ /// most one parked connection survives per partition — concurrent+ /// preconnects are possible through the pending-ownership window,+ /// and the loser is discarded and counted.+ pub async fn preconnect(&self, partition: u32) {+ if self.prepared.contains_key(&partition) {+ return;+ }+ let start = Instant::now();+ match self.connect_producer(partition).await {+ Ok(connected) => {+ counter!("personhog_leader_fence_preconnect_total", "outcome" => "ok").increment(1);+ histogram!("personhog_leader_fence_preconnect_ms")+ .record(start.elapsed().as_secs_f64() * 1000.0);+ if let Some(displaced) = self.prepared.insert(partition, connected) {+ // A racing preconnect parked first; one connection is+ // as good as the other, keep the newer.+ counter!("personhog_leader_fence_preconnect_total", "outcome" => "duplicate")+ .increment(1);+ spawn_blocking(move || drop(displaced));+ }+ }+ Err(e) => {+ counter!("personhog_leader_fence_preconnect_total", "outcome" => "error")+ .increment(1);+ warn!(partition, error = %e, "fence preconnect failed; acquisition will connect cold");+ }+ }+ }++ /// Build the partition's connected-but-uninitialized producer on the+ /// blocking pool.+ async fn connect_producer(+ &self,+ partition: u32,+ ) -> Result<ConnectedTransactionalProducer, String> {+ let kafka = self.kafka.clone();+ let tid = transactional_id(&self.topic, partition);+ let timeout = self.init_timeout;+ let broker_txn_timeout = self.broker_txn_timeout;+ spawn_blocking(move || {+ ConnectedTransactionalProducer::connect_bounded(+ &kafka,+ &tid,+ timeout,+ broker_txn_timeout,+ )+ })+ .await+ .map_err(|e| format!("fence connect join: {e}"))?+ .map_err(|e| format!("fence connect: {e}"))+ }++ /// Drop a parked connection on the blocking pool — librdkafka's+ /// client teardown blocks, same as a full fence's.+ fn discard_prepared(&self, partition: u32) {+ if let Some((_, connected)) = self.prepared.remove(&partition) {+ spawn_blocking(move || drop(connected));+ }+ }++ /// Discard every parked connection. A connection is normally+ /// consumed within its drain window, seconds after parking; one+ /// still here at the periodic sweep belongs to an acquire that went+ /// cold first or to a cancelled inbound handoff — and a cancelled+ /// inbound handoff leaves no convergence behind to notice it, so+ /// the sweep is the only owner its lifetime has. A drain window+ /// that happens to straddle the sweep tick loses its head start and+ /// acquires cold, which is the behavior this whole path improves on+ /// rather than a failure.+ pub fn sweep_prepared(&self) {+ let parked: Vec<u32> = self.prepared.iter().map(|entry| *entry.key()).collect();+ for partition in parked {+ if let Some((_, connected)) = self.prepared.remove(&partition) {+ counter!("personhog_leader_fence_preconnect_total", "outcome" => "swept")+ .increment(1);+ warn!(+ partition,+ "swept a parked changelog connection nothing consumed"+ );+ spawn_blocking(move || drop(connected));+ }+ }+ }++ /// Whether a parked connection exists for the partition.+ #[cfg(any(test, feature = "test-support"))]+ pub fn has_prepared(&self, partition: u32) -> bool {+ self.prepared.contains_key(&partition)}/// Whether this pod holds a *usable* fence for the partition.@@ -1376,6 +1530,9 @@ pub fn preregister_fencing_metrics(partitions: u32) {counter!("personhog_leader_fence_slots_abandoned_total").increment(0);counter!("personhog_leader_fence_abandoned_total").increment(0);counter!("personhog_leader_fence_abort_failed_total").increment(0);+ for outcome in ["ok", "error", "duplicate", "swept", "init_failed"] {+ counter!("personhog_leader_fence_preconnect_total", "outcome" => outcome).increment(0);+ }// The healing counters fire exactly during the incidents an operator// would reach for them in, and rarely enough that lazy registration// can swallow the first burst between scrapes.diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rsindex acbf5bab8caa..a89104196e83 100644--- a/rust/personhog-leader/src/main.rs+++ b/rust/personhog-leader/src/main.rs@@ -590,15 +590,21 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {}});- // Periodic sweep of idle per-key locks and refilled warning-throttle keys+ // Periodic sweep of idle per-key locks, refilled warning-throttle+ // keys, and parked fence connections nothing consumed (a cancelled+ // inbound handoff leaves no convergence behind to discard them).let sweep_locks = Arc::clone(&locks);let sweep_warnings = warnings.clone();+ let sweep_fenced = fenced.clone();tokio::spawn(async move {let mut interval = tokio::time::interval(Duration::from_secs(60));loop {interval.tick().await;sweep_idle_locks(&sweep_locks);sweep_warnings.sweep_throttle();+ if let Some(fenced) = &sweep_fenced {+ fenced.sweep_prepared();+ }}});diff --git a/rust/personhog-leader/tests/fencing_integration.rs b/rust/personhog-leader/tests/fencing_integration.rsindex 5a7709e1e0e7..bb18863c094d 100644--- a/rust/personhog-leader/tests/fencing_integration.rs+++ b/rust/personhog-leader/tests/fencing_integration.rs@@ -101,6 +101,81 @@ fn fenced_producers(topic: &str) -> FencedChangelogProducers {})}+/// The prepared path must fence exactly as the cold path does: a+/// connection built ahead of acquisition carries no broker transactional+/// state, so the epoch bump happens at `acquire` — and the previous+/// owner must find itself fenced by it.+#[tokio::test]+async fn a_prepared_connection_still_fences_the_previous_owner() {+ let topic = format!("fence_prepared_{}", uuid::Uuid::new_v4().simple());++ let first = fenced_producers(&topic);+ first.acquire(0).await.expect("first owner acquires");+ first+ .produce(0, &test_person(1))+ .await+ .expect("first owner produces while unfenced");++ let second = fenced_producers(&topic);+ second.preconnect(0).await;+ assert!(second.has_prepared(0), "preconnect parks a connection");+ // The property the phase split exists for: the parked connection has+ // touched no broker transactional state, so the serving owner is+ // still unfenced. Only the acquire below may cut it off.+ first+ .produce(0, &test_person(10))+ .await+ .expect("a parked connection must not fence the serving owner");+ second.acquire(0).await.expect("second owner acquires");+ assert!(+ !second.has_prepared(0),+ "acquisition consumes the parked connection"+ );+ second+ .produce(0, &test_person(2))+ .await+ .expect("an acquisition through a prepared connection serves writes");++ match first.produce(0, &test_person(3)).await {+ Err(FencedProduceError::Fenced) | Err(FencedProduceError::NotAcquired) => {}+ other => panic!("the prepared path must still fence the stale owner, got {other:?}"),+ }+}++/// A parked connection nothing consumed must not outlive the sweep: a+/// cancelled inbound handoff leaves no convergence behind to discard it,+/// so the periodic sweep is the only owner its lifetime has.+#[tokio::test]+async fn the_sweep_discards_parked_connections() {+ let topic = format!("fence_prepared_{}", uuid::Uuid::new_v4().simple());+ let producers = fenced_producers(&topic);+ producers.preconnect(6).await;+ assert!(producers.has_prepared(6), "preconnect parks a connection");++ producers.sweep_prepared();++ assert!(+ !producers.has_prepared(6),+ "the sweep must discard a parked connection"+ );+}++/// A partition released with a connection still parked must not keep the+/// client alive: release is the one moment ownership says the connection+/// has no future consumer.+#[tokio::test]+async fn a_released_partition_discards_its_prepared_connection() {+ let topic = format!("fence_prepared_{}", uuid::Uuid::new_v4().simple());+ let producers = fenced_producers(&topic);+ producers.preconnect(5).await;+ assert!(producers.has_prepared(5), "preconnect parks a connection");+ producers.release(5);+ assert!(+ !producers.has_prepared(5),+ "release must discard the parked connection"+ );+}+/// The core fencing guarantee: after a second owner acquires the/// partition, the first owner's produce fails as fenced instead of/// landing in the changelog.