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): make fence preconnect single-flight per partition (#81934)

Zach Brown64e7ca7263de
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 01591d29793f..a8157bbb93b2 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -8528,6 +8528,7 @@ dependencies = [
"prost 0.13.5",
"rdkafka",
"rustls 0.23.37",
+ "serde",
"serde_json",
"sqlx",
"tokio",
diff --git a/rust/personhog-leader/Cargo.toml b/rust/personhog-leader/Cargo.toml
index 0c91c865aacb..ec234a3c1ae8 100644
--- a/rust/personhog-leader/Cargo.toml
+++ b/rust/personhog-leader/Cargo.toml
@@ -31,6 +31,7 @@ foyer = "0.22.3"
metrics = { workspace = true }
prost = { workspace = true }
rdkafka = { workspace = true }
+serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
tokio = { workspace = true }
diff --git a/rust/personhog-leader/src/cache/partitioned.rs b/rust/personhog-leader/src/cache/partitioned.rs
index dda11894d505..f53a1c4e05f5 100644
--- a/rust/personhog-leader/src/cache/partitioned.rs
+++ b/rust/personhog-leader/src/cache/partitioned.rs
@@ -120,7 +120,7 @@ mod tests {
id: 1,
uuid: "abc-123".to_string(),
team_id: 42,
- properties: json!({"email": "[email protected]"}),
+ properties: serde_json::to_vec(&json!({"email": "[email protected]"})).unwrap(),
created_at: 1700000000,
version: 1,
is_identified: false,
diff --git a/rust/personhog-leader/src/cache/persons.rs b/rust/personhog-leader/src/cache/persons.rs
index c2f7d1c392fd..b0f929fd1767 100644
--- a/rust/personhog-leader/src/cache/persons.rs
+++ b/rust/personhog-leader/src/cache/persons.rs
@@ -12,27 +12,35 @@ pub struct PersonCacheKey {
pub person_id: i64,
}
-/// Fixed per-entry overhead charged on top of the serialized-properties
-/// estimate: the struct's scalar fields, the uuid, the key, and foyer's
+/// Fixed per-entry overhead charged on top of the stored properties
+/// bytes: the struct's scalar fields, the uuid, the key, and foyer's
/// record bookkeeping.
const PERSON_ENTRY_OVERHEAD_BYTES: usize = 256;
-/// The weight an entry contributes to the cache's byte capacity, from
-/// the serialized size of its properties at whichever boundary the
-/// person entered through. An estimate for eviction accounting — the
-/// point is that weight scales with document size, not that it matches
-/// the allocator byte for byte.
+/// The weight an entry contributes to the cache's byte capacity. The
+/// cache stores properties in serialized form, so this is the real
+/// allocation, not an estimate: entries held as parsed JSON trees cost
+/// a small multiple of their serialized size, and weighing those by
+/// serialized length let a "16MiB" cache hold ~2.7x that in heap.
pub fn approx_person_bytes(properties_serialized_len: usize) -> usize {
PERSON_ENTRY_OVERHEAD_BYTES + properties_serialized_len
}
-/// Cached person state with properties as a JSON map.
+/// Cached person state, with properties held in serialized JSON form.
+///
+/// Serialized rather than parsed for memory accounting: the cache weighs
+/// entries by byte length, and holding the bytes makes the charged
+/// weight the real allocation. Readers that need the map parse on
+/// access via [`CachedPerson::parse_properties`]; readers that need the
+/// wire form (proto responses, changelog records) take the bytes as
+/// they are.
#[derive(Debug, Clone)]
pub struct CachedPerson {
pub id: i64,
pub uuid: String,
pub team_id: i64,
- pub properties: serde_json::Value,
+ /// Properties as serialized JSON, validated at construction.
+ pub properties: Vec<u8>,
pub created_at: i64,
pub version: i64,
pub is_identified: bool,
@@ -51,19 +59,34 @@ pub struct CachedPerson {
// TODO: Add properties_last_updated_at and properties_last_operation
}
+impl CachedPerson {
+ /// Parse the stored properties into a JSON value. Construction
+ /// validates the bytes, so a failure here means the cache holds a
+ /// document no constructor produced.
+ pub fn parse_properties(&self) -> serde_json::Result<serde_json::Value> {
+ if self.properties.is_empty() {
+ return Ok(serde_json::Value::Object(serde_json::Map::new()));
+ }
+ serde_json::from_slice(&self.properties)
+ }
+}
+
/// Decodes a changelog `Person` record into cache form. The only fallible
-/// step is parsing the properties JSON; callers add their own context
-/// (offset, partition) to the error.
+/// step is validating the properties JSON — validated without building
+/// the tree, and stored as the record's own bytes.
impl TryFrom<Person> for CachedPerson {
type Error = serde_json::Error;
fn try_from(person: Person) -> Result<Self, Self::Error> {
+ if !person.properties.is_empty() {
+ serde_json::from_slice::<serde::de::IgnoredAny>(&person.properties)?;
+ }
let approx_bytes = approx_person_bytes(person.properties.len());
Ok(Self {
id: person.id,
uuid: person.uuid,
team_id: person.team_id,
- properties: serde_json::from_slice(&person.properties)?,
+ properties: person.properties,
created_at: person.created_at,
version: person.version,
is_identified: person.is_identified,
@@ -156,12 +179,34 @@ impl PersonCache {
mod tests {
use super::*;
+ /// Proto3 encodes an absent bytes field as empty, and every leader
+ /// write path serializes at least `{}` — so empty properties can
+ /// only arrive from records that predate this store, and rejecting
+ /// them would fail the warm over a document that is simply
+ /// property-less. This pins the lenient reading in both directions:
+ /// decode accepts, and parse yields the empty map.
+ #[test]
+ fn empty_properties_bytes_read_as_the_empty_map() {
+ let record = Person {
+ uuid: "00000000-0000-0000-0000-000000000001".to_string(),
+ properties: Vec::new(),
+ ..Default::default()
+ };
+ let cached = CachedPerson::try_from(record).expect("empty properties decode");
+ assert!(cached.properties.is_empty());
+ assert_eq!(
+ cached.parse_properties().unwrap(),
+ serde_json::Value::Object(serde_json::Map::new())
+ );
+ }
+
fn test_person() -> CachedPerson {
CachedPerson {
id: 1,
uuid: "abc-123".to_string(),
team_id: 42,
- properties: serde_json::json!({"email": "[email protected]"}),
+ properties: serde_json::to_vec(&serde_json::json!({"email": "[email protected]"}))
+ .unwrap(),
created_at: 1700000000,
version: 1,
is_identified: false,
@@ -190,7 +235,8 @@ mod tests {
for person_id in 0..128 {
let mut person = test_person();
person.id = person_id;
- person.properties = serde_json::json!({ "blob": blob.clone() });
+ person.properties =
+ serde_json::to_vec(&serde_json::json!({ "blob": blob.clone() })).unwrap();
person.approx_bytes = approx_person_bytes(1536);
cache.put(
PersonCacheKey {
@@ -237,7 +283,10 @@ mod tests {
assert_eq!(cached.id, 1);
assert_eq!(cached.uuid, "abc-123");
assert_eq!(cached.team_id, 42);
- assert_eq!(cached.properties["email"], "[email protected]");
+ assert_eq!(
+ cached.parse_properties().unwrap()["email"],
+ );
}
#[test]
@@ -267,11 +316,15 @@ mod tests {
let mut updated = test_person();
updated.version = 2;
- updated.properties = serde_json::json!({"email": "[email protected]"});
+ updated.properties =
+ serde_json::to_vec(&serde_json::json!({"email": "[email protected]"})).unwrap();
cache.put(key.clone(), updated);
let cached = cache.get(&key).unwrap();
assert_eq!(cached.version, 2);
- assert_eq!(cached.properties["email"], "[email protected]");
+ assert_eq!(
+ cached.parse_properties().unwrap()["email"],
+ );
}
}
diff --git a/rust/personhog-leader/src/fencing.rs b/rust/personhog-leader/src/fencing.rs
index 684cb90ab5c1..5349c9cf158d 100644
--- a/rust/personhog-leader/src/fencing.rs
+++ b/rust/personhog-leader/src/fencing.rs
@@ -27,13 +27,16 @@
//! aborted records (consumers run `read_committed`), so the coupling is
//! visible only as grouped retryable errors.
-use std::sync::atomic::{AtomicBool, Ordering};
+#[cfg(any(test, feature = "test-support"))]
+use std::sync::atomic::AtomicUsize;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use std::{fmt, mem};
use common_kafka::config::KafkaConfig;
use common_kafka::transaction::{ConnectedTransactionalProducer, TransactionalProducer};
+use dashmap::mapref::entry::Entry;
use dashmap::DashMap;
use metrics::{counter, histogram};
use prost::Message as ProtoMessage;
@@ -455,6 +458,27 @@ impl Drop for FenceGuard {
}
}
+/// A partition's slot in the pre-connect pipeline: claimed while a
+/// dial is in flight, then holding the parked connection.
+enum Prepared {
+ /// A preconnect owns the slot and is dialing. Concurrent
+ /// preconnects seeing this return immediately, so at most one dial
+ /// runs per partition. The claim is what bounds connection churn:
+ /// the trigger fires on every convergence pass through a drain
+ /// window, and without it those passes stack concurrent dials
+ /// until the pod runs out of memory.
+ ///
+ /// The token identifies the owning dial. A dial resolves only its
+ /// own claim: a stale dial whose claim was removed mid-flight (by
+ /// an acquire, a release, or the sweep) must neither usurp a
+ /// replacement dial's claim on success nor release it on failure —
+ /// either would let convergence start extra dials, which is the
+ /// churn the claim exists to prevent.
+ Connecting { token: u64, since: Instant },
+ /// A finished dial, parked for the next acquire to consume.
+ Ready(ConnectedTransactionalProducer),
+}
+
/// Per-partition fenced producers for the changelog. Constructed once
/// and shared; partitions are acquired at warm completion and released
/// with ownership.
@@ -491,7 +515,16 @@ pub struct FencedChangelogProducers {
/// 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>,
+ prepared: DashMap<u32, Prepared>,
+ /// Distinguishes dials, so each resolves only its own claim.
+ dial_token: AtomicU64,
+
+ /// Dials attempted, so tests can pin single-flight: the storm this
+ /// guards against is invisible through public behavior until the
+ /// pod is already dying.
+ #[cfg(any(test, feature = "test-support"))]
+ connect_attempts: AtomicUsize,
+
/// Outcomes a test stages for the next produce on a partition.
///
/// The uncertain outcomes need a broker fault landing inside a
@@ -542,6 +575,9 @@ impl FencedChangelogProducers {
partitions: DashMap::new(),
repair_nudge: None,
prepared: DashMap::new(),
+ dial_token: AtomicU64::new(0),
+ #[cfg(any(test, feature = "test-support"))]
+ connect_attempts: AtomicUsize::new(0),
#[cfg(any(test, feature = "test-support"))]
staged_failures: DashMap::new(),
}
@@ -570,7 +606,11 @@ impl FencedChangelogProducers {
// failing the acquisition.
let mut path = "cold";
let mut producer = None;
- if let Some((_, parked)) = self.prepared.remove(&partition) {
+ // The removal also clears a Connecting claim: acquisition is
+ // happening now, so a dial still in flight is too late to help,
+ // and losing its claim makes it discard on completion instead
+ // of parking a connection nothing will consume.
+ if let Some((_, Prepared::Ready(parked))) = self.prepared.remove(&partition) {
match init_producer(parked, timeout).await {
Ok(ready) => {
path = "prepared";
@@ -663,13 +703,28 @@ impl FencedChangelogProducers {
/// 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.
+ /// logged and counted, because the cold acquire path covers it.
+ /// Single-flight per partition: the slot is claimed before the dial
+ /// begins, so however often convergence fires this through a drain
+ /// window, one dial runs and the rest return as coalesced.
pub async fn preconnect(&self, partition: u32) {
- if self.prepared.contains_key(&partition) {
- return;
+ // The claim must precede the dial, and the entry guard must not
+ // be held across it: the guard holds a shard lock.
+ let token = self.dial_token.fetch_add(1, Ordering::Relaxed);
+ match self.prepared.entry(partition) {
+ Entry::Occupied(_) => {
+ // Another preconnect is dialing or already parked a
+ // connection; either way this call has nothing to add.
+ counter!("personhog_leader_fence_preconnect_total", "outcome" => "coalesced")
+ .increment(1);
+ return;
+ }
+ Entry::Vacant(slot) => {
+ slot.insert(Prepared::Connecting {
+ token,
+ since: Instant::now(),
+ });
+ }
}
let start = Instant::now();
match self.connect_producer(partition).await {
@@ -677,18 +732,40 @@ impl FencedChangelogProducers {
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));
- }
+ self.park(partition, token, connected);
}
Err(e) => {
counter!("personhog_leader_fence_preconnect_total", "outcome" => "error")
.increment(1);
warn!(partition, error = %e, "fence preconnect failed; acquisition will connect cold");
+ // Release the claim so a later preconnect can retry —
+ // but only this dial's own claim. A replacement dial's
+ // claim, or a parked connection, stays.
+ self.prepared.remove_if(
+ &partition,
+ |_, slot| matches!(slot, Prepared::Connecting { token: t, .. } if *t == token),
+ );
+ }
+ }
+ }
+
+ /// Park a finished dial, unless its claim is gone (a release, a
+ /// sweep, or an acquire that went cold discarded it): a discarded
+ /// partition must not resurrect, so the late connection is dropped
+ /// instead. The token check makes ownership exact — a stale dial
+ /// finding a replacement dial's claim here must not usurp it, or
+ /// the replacement's own park would discard the newer connection
+ /// while later convergence passes see whatever raced in.
+ fn park(&self, partition: u32, token: u64, connected: ConnectedTransactionalProducer) {
+ match self.prepared.entry(partition) {
+ Entry::Occupied(mut slot) if matches!(slot.get(), Prepared::Connecting { token: t, .. } if *t == token) =>
+ {
+ slot.insert(Prepared::Ready(connected));
+ }
+ _ => {
+ counter!("personhog_leader_fence_preconnect_total", "outcome" => "discarded")
+ .increment(1);
+ spawn_blocking(move || drop(connected));
}
}
}
@@ -699,6 +776,8 @@ impl FencedChangelogProducers {
&self,
partition: u32,
) -> Result<ConnectedTransactionalProducer, String> {
+ #[cfg(any(test, feature = "test-support"))]
+ self.connect_attempts.fetch_add(1, Ordering::SeqCst);
let kafka = self.kafka.clone();
let tid = transactional_id(&self.topic, partition);
let timeout = self.init_timeout;
@@ -717,9 +796,11 @@ impl FencedChangelogProducers {
}
/// Drop a parked connection on the blocking pool — librdkafka's
- /// client teardown blocks, same as a full fence's.
+ /// client teardown blocks, same as a full fence's. A Connecting
+ /// claim is removed without a drop: its dial discards on
+ /// completion once the claim is gone.
fn discard_prepared(&self, partition: u32) {
- if let Some((_, connected)) = self.prepared.remove(&partition) {
+ if let Some((_, Prepared::Ready(connected))) = self.prepared.remove(&partition) {
spawn_blocking(move || drop(connected));
}
}
@@ -734,16 +815,39 @@ impl FencedChangelogProducers {
/// 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));
+ // Every live dial is bounded by the init timeout, so a claim
+ // twice that old has no owner left to resolve it (its task
+ // panicked or was torn down). Clearing it un-wedges preconnect
+ // for the partition; correctness never depended on the claim,
+ // acquisition just goes cold.
+ let stale_claim_bound = self.init_timeout * 2;
+ let now = Instant::now();
+ let slots: Vec<u32> = self.prepared.iter().map(|entry| *entry.key()).collect();
+ for partition in slots {
+ // remove_if re-checks the slot under the shard lock, so a
+ // dial that parks between the scan and this removal is not
+ // swept as a stale claim.
+ match self.prepared.remove_if(&partition, |_, slot| match slot {
+ Prepared::Ready(_) => true,
+ Prepared::Connecting { since, .. } => {
+ now.duration_since(*since) > stale_claim_bound
+ }
+ }) {
+ Some((_, Prepared::Ready(connected))) => {
+ counter!("personhog_leader_fence_preconnect_total", "outcome" => "swept")
+ .increment(1);
+ warn!(
+ partition,
+ "swept a parked changelog connection nothing consumed"
+ );
+ spawn_blocking(move || drop(connected));
+ }
+ Some((_, Prepared::Connecting { .. })) => {
+ counter!("personhog_leader_fence_preconnect_total", "outcome" => "orphaned")
+ .increment(1);
+ warn!(partition, "cleared an orphaned preconnect claim");
+ }
+ None => {}
}
}
}
@@ -751,7 +855,37 @@ impl FencedChangelogProducers {
/// 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)
+ self.prepared
+ .get(&partition)
+ .is_some_and(|slot| matches!(*slot, Prepared::Ready(_)))
+ }
+
+ /// How many dials have been attempted.
+ #[cfg(any(test, feature = "test-support"))]
+ pub fn connect_attempts_for_test(&self) -> usize {
+ self.connect_attempts.load(Ordering::SeqCst)
+ }
+
+ /// Stage a Connecting claim of a given age, standing in for a dial
+ /// whose task died without resolving it.
+ #[cfg(any(test, feature = "test-support"))]
+ pub fn stage_connecting_for_test(&self, partition: u32, age: Duration) {
+ let token = self.dial_token.fetch_add(1, Ordering::Relaxed);
+ self.prepared.insert(
+ partition,
+ Prepared::Connecting {
+ token,
+ since: Instant::now() - age,
+ },
+ );
+ }
+
+ /// Whether a Connecting claim holds the partition's slot.
+ #[cfg(any(test, feature = "test-support"))]
+ pub fn has_connecting_claim_for_test(&self, partition: u32) -> bool {
+ self.prepared
+ .get(&partition)
+ .is_some_and(|slot| matches!(*slot, Prepared::Connecting { .. }))
}
/// Whether this pod holds a *usable* fence for the partition.
@@ -1591,7 +1725,15 @@ pub fn preregister_fencing_metrics(partitions: u32) {
}
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"] {
+ for outcome in [
+ "ok",
+ "error",
+ "coalesced",
+ "discarded",
+ "swept",
+ "orphaned",
+ "init_failed",
+ ] {
counter!("personhog_leader_fence_preconnect_total", "outcome" => outcome).increment(0);
}
// The healing counters fire exactly during the incidents an operator
diff --git a/rust/personhog-leader/src/kafka.rs b/rust/personhog-leader/src/kafka.rs
index bdca42f68211..c290d93da13f 100644
--- a/rust/personhog-leader/src/kafka.rs
+++ b/rust/personhog-leader/src/kafka.rs
@@ -1,7 +1,10 @@
+use std::time::Duration;
+
use common_kafka::kafka_producer::KafkaContext;
+use lifecycle::Handle;
use metrics::{counter, histogram};
use prost::Message;
-use rdkafka::producer::{FutureProducer, FutureRecord};
+use rdkafka::producer::{FutureProducer, FutureRecord, Producer};
use tracing::error;
use personhog_proto::personhog::types::v1::Person;
@@ -80,3 +83,57 @@ pub async fn produce_person_changelog(
}
}
}
+
+/// Completes the kafka-producer lifecycle component with a bounded
+/// flush instead of waiting for the last producer reference to drop.
+///
+/// The component's handle rides inside the producer context, which
+/// every clone of the producer shares — so without explicit shutdown
+/// work, the component completed only when everything holding the
+/// producer let go, and a queue wedged against a stalled broker held
+/// its shutdown phase to the global timeout. This task flushes what
+/// the queue holds within `bound` once the component's phase shuts
+/// down, then reports completion either way.
+///
+/// A timed-out flush drops only records nobody acked: the changelog
+/// path awaits each record's delivery before acking (so anything acked
+/// is already off the queue, and unacked writes retry via redelivery),
+/// and the rest of this producer's traffic is best-effort warnings.
+pub fn spawn_bounded_flush_on_shutdown(
+ producer: FutureProducer<KafkaContext>,
+ handle: Handle,
+ bound: Duration,
+) {
+ tokio::spawn(async move {
+ handle.shutdown_recv().await;
+ let queued = producer.in_flight_count();
+ // Flush blocks, and so can the producer teardown after it; both
+ // stay off the async workers. Completion is reported first, so
+ // a teardown that outlives the flush bound cannot hold the
+ // phase.
+ let flushed = tokio::task::spawn_blocking(move || {
+ let outcome = producer.flush(bound);
+ let remaining = producer.in_flight_count();
+ drop(producer);
+ (outcome, remaining)
+ })
+ .await;
+ match flushed {
+ Ok((Ok(()), _)) => {
+ tracing::info!(queued, "kafka producer flushed at shutdown");
+ }
+ Ok((Err(e), remaining)) => {
+ tracing::warn!(
+ queued,
+ remaining,
+ error = %e,
+ "kafka producer flush hit its shutdown bound; undelivered records dropped"
+ );
+ }
+ Err(e) => {
+ tracing::warn!(error = %e, "kafka producer shutdown flush task failed");
+ }
+ }
+ handle.work_completed();
+ });
+}
diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rs
index 57b51a296600..eca9756ee012 100644
--- a/rust/personhog-leader/src/main.rs
+++ b/rust/personhog-leader/src/main.rs
@@ -121,7 +121,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
);
let kafka_handle = manager.register(
"kafka-producer",
- ComponentOptions::new().with_shutdown_phase(1),
+ // The graceful window is the ceiling; the bounded flush task
+ // spawned after the producer is built normally completes well
+ // inside it.
+ ComponentOptions::new()
+ .with_graceful_shutdown(Duration::from_secs(15))
+ .with_shutdown_phase(1),
);
let authority_metrics_handle = manager.register(
@@ -248,13 +253,20 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Initialize partitioned cache and Kafka producer
let cache = Arc::new(PartitionedCache::new(config.cache_memory_capacity_bytes));
- let kafka_producer = match create_kafka_producer(&config.kafka, kafka_handle).await {
+ let kafka_producer = match create_kafka_producer(&config.kafka, kafka_handle.clone()).await {
Ok(producer) => producer,
Err(e) => {
tracing::error!(error = %e, "failed to create Kafka producer");
return Err(e.into());
}
};
+ // Runs at phase 1, after the coordination drain, so the drain's last
+ // records are in the queue it flushes.
+ personhog_leader::kafka::spawn_bounded_flush_on_shutdown(
+ kafka_producer.clone(),
+ kafka_handle,
+ Duration::from_secs(10),
+ );
// PG fallback pool for cache misses (optional, disabled if URL is empty)
let fallback = if config.fallback_database_url.is_empty() {
diff --git a/rust/personhog-leader/src/pg.rs b/rust/personhog-leader/src/pg.rs
index dd8e3582647f..fbe319d12801 100644
--- a/rust/personhog-leader/src/pg.rs
+++ b/rust/personhog-leader/src/pg.rs
@@ -69,13 +69,12 @@ pub async fn load_person_from_pg(
// Borrowed from the row buffer — no copy; parse cost matches what
// sqlx's own jsonb decode would spend on the same bytes.
let properties_text: &str = row.get("properties");
- let properties_text_len = properties_text.len();
let created_at: chrono::DateTime<chrono::Utc> = row.get("created_at");
let version: Option<i64> = row.get("version");
let is_identified: bool = row.get("is_identified");
let last_seen_at: Option<chrono::DateTime<chrono::Utc>> = row.get("last_seen_at");
- let properties = match serde_json::from_str(properties_text) {
+ let properties: serde_json::Value = match serde_json::from_str(properties_text) {
Ok(value) => value,
// Out-of-range numerics from other writers: rewrite to what
// JSON.parse would read (rounding, clamping beyond f64) instead
@@ -104,12 +103,17 @@ pub async fn load_person_from_pg(
counter!("personhog_leader_pg_fallback_total", "outcome" => "found").increment(1);
+ let properties_bytes = serde_json::to_vec(&properties).map_err(|e| {
+ sqlx::Error::Protocol(format!(
+ "person properties reserialize failed (team_id={team_id}, person_id={id}): {e}"
+ ))
+ })?;
Ok(Some(CachedPerson {
id,
uuid,
team_id: team_id as i64,
- approx_bytes: approx_person_bytes(properties_text_len),
- properties,
+ approx_bytes: approx_person_bytes(properties_bytes.len()),
+ properties: properties_bytes,
created_at: created_at.timestamp_millis(),
version: version.unwrap_or(0),
is_identified,
diff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rs
index 291fd34e6d13..3e4ee70e05c1 100644
--- a/rust/personhog-leader/src/service.rs
+++ b/rust/personhog-leader/src/service.rs
@@ -746,7 +746,7 @@ fn assert_writeable(p: &CachedPerson) -> Result<(), String> {
}
fn cached_person_to_proto(p: &CachedPerson) -> Person {
- let properties_bytes = serde_json::to_vec(&p.properties).unwrap_or_default();
+ let properties_bytes = p.properties.clone();
Person {
id: p.id,
uuid: p.uuid.clone(),
@@ -1051,13 +1051,19 @@ impl PersonHogLeader for PersonHogLeaderService {
return Err(Status::not_found("person is destroyed"));
}
+ // One parse per update: the cache stores properties serialized,
+ // and this handler reads them as a map throughout.
+ let person_properties = person
+ .parse_properties()
+ .map_err(|e| Status::internal(format!("cached properties unparseable: {e}")))?;
+
// Compute property updates
let updates = compute_event_property_updates(
&req.event_name,
&set_properties,
&set_once_properties,
&unset_properties,
- &person.properties,
+ &person_properties,
);
// OR-merge: identification never reverts through this RPC, so
@@ -1099,7 +1105,7 @@ impl PersonHogLeader for PersonHogLeaderService {
// Slow path: apply diffs and check if the values actually changed
// (has_changes can be true when $set sends the same value that already exists)
let (new_properties, actually_updated) =
- apply_property_updates(&updates, &person.properties);
+ apply_property_updates(&updates, &person_properties);
if !actually_updated && !identity_changed && !last_seen_changed {
counter!("personhog_leader_updates_total", "outcome" => "no_change").increment(1);
@@ -1146,9 +1152,9 @@ impl PersonHogLeader for PersonHogLeaderService {
// visible outcome where a silent trim would be arbitrary
// deferred data loss. Warnings and errors carry sizes, never
// property values.
- let existing_size = jsonb_column_size(&person.properties);
+ let existing_size = jsonb_column_size(&person_properties);
if existing_size >= self.size_limits.threshold {
- match trim_properties_to_fit_size(&person.properties, self.size_limits.trim_target)
+ match trim_properties_to_fit_size(&person_properties, self.size_limits.trim_target)
{
TrimResult::Trimmed(trimmed) => {
counter!("personhog_leader_properties_trimmed_total").increment(1);
@@ -1166,7 +1172,7 @@ impl PersonHogLeader for PersonHogLeaderService {
// the update still cannot apply — keep the stored
// state, discarding the update like the arm above.
TrimResult::Fits => {
- new_properties = person.properties.clone();
+ new_properties = person_properties.clone();
}
TrimResult::CannotFit => {
counter!(
@@ -1207,7 +1213,9 @@ impl PersonHogLeader for PersonHogLeaderService {
}
}
- let approx_bytes = approx_person_bytes(jsonb_column_size(&new_properties));
+ let properties_bytes = serde_json::to_vec(&new_properties)
+ .map_err(|e| Status::internal(format!("serialize updated properties: {e}")))?;
+ let approx_bytes = approx_person_bytes(properties_bytes.len());
// A version this pod already put on the wire is spent even when
// it never learned the outcome, so the next one has to clear that
// floor as well as the state it derived from. Reusing it produces
@@ -1220,7 +1228,7 @@ impl PersonHogLeader for PersonHogLeaderService {
id: person.id,
uuid: person.uuid.clone(),
team_id: person.team_id,
- properties: new_properties,
+ properties: properties_bytes,
created_at: person.created_at,
version: base_version + 1,
is_identified: identified_now,
@@ -1357,10 +1365,14 @@ impl PersonHogLeader for PersonHogLeaderService {
// still-absent keys in request order; then the merge event's $set
// overrides and $set_once fills. All inputs are sanitized, so the
// merged document is measured in stored form.
- let mut target_properties = if person.properties.is_object() {
- person.properties.clone()
- } else {
- serde_json::Value::Object(serde_json::Map::new())
+ let mut target_properties = match person.parse_properties() {
+ Ok(value) if value.is_object() => value,
+ Ok(_) => serde_json::Value::Object(serde_json::Map::new()),
+ Err(e) => {
+ return Err(Status::internal(format!(
+ "cached properties unparseable: {e}"
+ )))
+ }
};
// The cached state is an input like any other: rows loaded from
// Postgres or warmed from records that predate sanitization can
@@ -1538,12 +1550,14 @@ impl PersonHogLeader for PersonHogLeaderService {
Status::invalid_argument("sealed versions leave no room for the folded version")
})?;
- let approx_bytes = approx_person_bytes(jsonb_column_size(&folded));
+ let folded_bytes = serde_json::to_vec(&folded)
+ .map_err(|e| Status::internal(format!("serialize folded properties: {e}")))?;
+ let approx_bytes = approx_person_bytes(folded_bytes.len());
let folded_person = CachedPerson {
id: person.id,
uuid: person.uuid.clone(),
team_id: person.team_id,
- properties: folded,
+ properties: folded_bytes,
created_at,
version,
is_identified: true,
@@ -1834,7 +1848,7 @@ impl PersonHogLeader for PersonHogLeaderService {
id: req.person_id,
uuid: req.person_uuid.clone(),
team_id: req.team_id,
- properties: serde_json::Value::Object(serde_json::Map::new()),
+ properties: b"{}".to_vec(),
// The sealed value, not the cached one: cold and warm
// leaders must produce the same document.
created_at: req.created_at,
@@ -1842,9 +1856,7 @@ impl PersonHogLeader for PersonHogLeaderService {
is_identified: false,
is_deleted: true,
last_seen_at: None,
- approx_bytes: approx_person_bytes(jsonb_column_size(
- &serde_json::Value::Object(serde_json::Map::new()),
- )),
+ approx_bytes: approx_person_bytes(2),
};
self.commit_document(partition, &cache_key, death).await?;
// The death document stays in the cache (commit_document
@@ -2135,7 +2147,7 @@ mod tests {
id: person_id,
uuid: "00000000-0000-0000-0000-000000000007".to_string(),
team_id,
- properties: serde_json::json!({}),
+ properties: serde_json::to_vec(&serde_json::json!({})).unwrap(),
created_at: 0,
version: 1,
is_identified: false,
@@ -2201,7 +2213,7 @@ mod tests {
id: person_id,
uuid: "00000000-0000-0000-0000-000000000007".to_string(),
team_id,
- properties: serde_json::json!({}),
+ properties: serde_json::to_vec(&serde_json::json!({})).unwrap(),
created_at: 0,
version: 1,
is_identified: false,
@@ -2303,7 +2315,7 @@ mod tests {
id: person_id,
uuid: "00000000-0000-0000-0000-000000000007".to_string(),
team_id,
- properties: serde_json::json!({}),
+ properties: serde_json::to_vec(&serde_json::json!({})).unwrap(),
created_at: 0,
version: 1,
is_identified: false,
@@ -2349,7 +2361,7 @@ mod tests {
id: person_id,
uuid: "00000000-0000-0000-0000-000000000007".to_string(),
team_id,
- properties: serde_json::json!({}),
+ properties: serde_json::to_vec(&serde_json::json!({})).unwrap(),
created_at: 0,
version: 1,
is_identified: false,
diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rs
index 936e7e707cde..ca5da9bbddf1 100644
--- a/rust/personhog-leader/tests/common/mod.rs
+++ b/rust/personhog-leader/tests/common/mod.rs
@@ -564,7 +564,7 @@ pub fn test_cached_person() -> CachedPerson {
id: 42,
uuid: "00000000-0000-0000-0000-000000000042".to_string(),
team_id: 1,
- properties: serde_json::json!({"email": "[email protected]"}),
+ properties: serde_json::to_vec(&serde_json::json!({"email": "[email protected]"})).unwrap(),
created_at: 1700000000,
version: 1,
is_identified: false,
diff --git a/rust/personhog-leader/tests/fence_integration.rs b/rust/personhog-leader/tests/fence_integration.rs
index b13dcffcb7cd..465a6ca4ec70 100644
--- a/rust/personhog-leader/tests/fence_integration.rs
+++ b/rust/personhog-leader/tests/fence_integration.rs
@@ -1463,7 +1463,8 @@ async fn a_fold_applies_precedence_and_scalars_and_lands_in_the_changelog() {
let op = Uuid::now_v7();
let mut harness = start_marked_fold_harness(
CachedPerson {
- properties: serde_json::json!({"a": "target", "b": "target"}),
+ properties: serde_json::to_vec(&serde_json::json!({"a": "target", "b": "target"}))
+ .unwrap(),
created_at: 1_700_000_000,
version: 3,
is_identified: false,
@@ -1582,7 +1583,7 @@ async fn event_set_overrides_and_set_once_respects_snapshot_contributed_keys() {
let op = Uuid::now_v7();
let mut harness = start_marked_fold_harness(
CachedPerson {
- properties: serde_json::json!({"target_only": "t"}),
+ properties: serde_json::to_vec(&serde_json::json!({"target_only": "t"})).unwrap(),
version: 2,
..test_cached_person()
},
@@ -1629,7 +1630,7 @@ async fn fold_with_empty_target_properties_fills_from_snapshots_and_event() {
let op = Uuid::now_v7();
let mut harness = start_marked_fold_harness(
CachedPerson {
- properties: serde_json::json!({}),
+ properties: serde_json::to_vec(&serde_json::json!({})).unwrap(),
created_at: 1_700_000_000,
version: 10,
..test_cached_person()
@@ -1672,7 +1673,7 @@ async fn created_at_ignores_non_positive_snapshot_timestamps_and_target_can_be_e
let op = Uuid::now_v7();
let mut harness = start_marked_fold_harness(
CachedPerson {
- properties: serde_json::json!({}),
+ properties: serde_json::to_vec(&serde_json::json!({})).unwrap(),
created_at: 1_500_000_000,
version: 1,
..test_cached_person()
@@ -2017,7 +2018,8 @@ async fn an_oversized_fold_trims_the_contribution_not_the_targets_keys() {
let target_value = "x".repeat(500_000);
let mut harness = start_marked_fold_harness(
CachedPerson {
- properties: serde_json::json!({"aa_target": target_value.clone()}),
+ properties: serde_json::to_vec(&serde_json::json!({"aa_target": target_value.clone()}))
+ .unwrap(),
version: 3,
..test_cached_person()
},
@@ -2067,7 +2069,8 @@ async fn an_unremediable_fold_keeps_the_targets_document_untouched() {
let target_value = "x".repeat(600_000);
let mut harness = start_marked_fold_harness(
CachedPerson {
- properties: serde_json::json!({"tt_target": target_value.clone()}),
+ properties: serde_json::to_vec(&serde_json::json!({"tt_target": target_value.clone()}))
+ .unwrap(),
version: 3,
is_identified: false,
..test_cached_person()
@@ -2123,7 +2126,7 @@ async fn an_oversized_targets_fold_trims_to_the_hard_ceiling() {
CachedPerson {
// email is protected and alone overshoots the trim target;
// tt_target is trimmable overflow above the ceiling.
- properties: serde_json::json!({"email": email_value.clone(), "tt_target": "x".repeat(200_000)}),
+ properties: serde_json::to_vec(&serde_json::json!({"email": email_value.clone(), "tt_target": "x".repeat(200_000)})).unwrap(),
version: 3,
..test_cached_person()
},
@@ -2173,7 +2176,8 @@ async fn an_unapplyable_fold_completes_without_producing() {
let email_value = "e".repeat(700_000);
let mut harness = start_marked_fold_harness(
CachedPerson {
- properties: serde_json::json!({"email": email_value.clone()}),
+ properties: serde_json::to_vec(&serde_json::json!({"email": email_value.clone()}))
+ .unwrap(),
version: 3,
is_identified: false,
..test_cached_person()
@@ -2223,7 +2227,7 @@ async fn a_non_object_target_stays_an_object_through_the_unremediable_path() {
let op = Uuid::now_v7();
let mut harness = start_marked_fold_harness(
CachedPerson {
- properties: serde_json::json!("legacy-scalar"),
+ properties: serde_json::to_vec(&serde_json::json!("legacy-scalar")).unwrap(),
..test_cached_person()
},
&op,
@@ -2266,7 +2270,7 @@ async fn precedence_follows_ordinals_not_request_order() {
let op = Uuid::now_v7();
let mut harness = start_marked_fold_harness(
CachedPerson {
- properties: serde_json::json!({}),
+ properties: serde_json::to_vec(&serde_json::json!({})).unwrap(),
version: 1,
..test_cached_person()
},
@@ -2324,7 +2328,7 @@ async fn a_folds_target_cache_dirt_is_sanitized() {
let op = Uuid::now_v7();
let mut harness = start_marked_fold_harness(
CachedPerson {
- properties: serde_json::json!({"dirty": "a\u{0000}b"}),
+ properties: serde_json::to_vec(&serde_json::json!({"dirty": "a\u{0000}b"})).unwrap(),
..test_cached_person()
},
&op,
diff --git a/rust/personhog-leader/tests/fencing_integration.rs b/rust/personhog-leader/tests/fencing_integration.rs
index 77db127dad12..af1a0ff12fe7 100644
--- a/rust/personhog-leader/tests/fencing_integration.rs
+++ b/rust/personhog-leader/tests/fencing_integration.rs
@@ -186,6 +186,134 @@ async fn a_released_partition_discards_its_prepared_connection() {
);
}
+/// The trigger fires on every convergence pass through a drain window,
+/// so concurrent preconnects for one partition are the normal case, and
+/// each dial is a full TLS client. Without single-flight they stack
+/// until the pod runs out of memory; the claim must collapse them to
+/// one dial.
+#[tokio::test]
+async fn concurrent_preconnects_collapse_to_one_dial() {
+ let topic = format!("fence_prepared_{}", uuid::Uuid::new_v4().simple());
+ let producers = Arc::new(fenced_producers(&topic));
+
+ let calls: Vec<_> = (0..20)
+ .map(|_| {
+ let p = Arc::clone(&producers);
+ tokio::spawn(async move { p.preconnect(3).await })
+ })
+ .collect();
+ for call in calls {
+ call.await.unwrap();
+ }
+
+ assert_eq!(
+ producers.connect_attempts_for_test(),
+ 1,
+ "twenty concurrent preconnects must share one dial"
+ );
+ assert!(
+ producers.has_prepared(3),
+ "the one dial parks its connection"
+ );
+}
+
+/// A failed dial must release its claim: the claim exists to suppress
+/// concurrent dials, not to wedge the partition out of preconnecting
+/// after a broker hiccup.
+#[tokio::test]
+async fn a_failed_preconnect_releases_its_claim() {
+ let mut kafka = test_kafka_config();
+ // An unroutable broker fails the dial at its bounded metadata ping.
+ kafka.kafka_hosts = "127.0.0.1:1".to_string();
+ let producers = FencedChangelogProducers::new(FencedProducerConfig {
+ kafka,
+ topic: "fence_unroutable".to_string(),
+ init_timeout: Duration::from_secs(2),
+ commit_timeout: Duration::from_secs(2),
+ broker_txn_timeout: BROKER_TXN_TIMEOUT,
+ window: Duration::from_millis(5),
+ window_max_writes: 32,
+ settle_budget: Duration::from_secs(5),
+ });
+
+ producers.preconnect(0).await;
+ assert!(!producers.has_prepared(0), "a failed dial parks nothing");
+
+ producers.preconnect(0).await;
+ assert_eq!(
+ producers.connect_attempts_for_test(),
+ 2,
+ "the failed dial's claim must not block the retry"
+ );
+}
+
+/// A dial whose claim was removed mid-flight must not resolve the
+/// replacement claim that took its place: releasing another dial's
+/// claim lets convergence start yet more dials, recreating the churn
+/// single-flight exists to stop.
+#[tokio::test]
+async fn a_stale_dials_failure_leaves_the_replacements_claim() {
+ let mut kafka = test_kafka_config();
+ // An unroutable broker holds the dial open until its 2s bound, so
+ // the mid-flight claim churn below happens while it is in flight.
+ kafka.kafka_hosts = "127.0.0.1:1".to_string();
+ let producers = Arc::new(FencedChangelogProducers::new(FencedProducerConfig {
+ kafka,
+ topic: "fence_unroutable".to_string(),
+ init_timeout: Duration::from_secs(2),
+ commit_timeout: Duration::from_secs(2),
+ broker_txn_timeout: BROKER_TXN_TIMEOUT,
+ window: Duration::from_millis(5),
+ window_max_writes: 32,
+ settle_budget: Duration::from_secs(5),
+ }));
+
+ let dial = {
+ let p = Arc::clone(&producers);
+ tokio::spawn(async move { p.preconnect(0).await })
+ };
+ while !producers.has_connecting_claim_for_test(0) {
+ tokio::task::yield_now().await;
+ }
+ // Ownership churn mid-dial: the claim is discarded and a
+ // replacement dial claims the slot.
+ producers.release(0);
+ producers.stage_connecting_for_test(0, Duration::ZERO);
+
+ dial.await.unwrap();
+
+ assert!(
+ producers.has_connecting_claim_for_test(0),
+ "the stale dial's failure must not release the replacement's claim"
+ );
+}
+
+/// The sweep clears a claim only past the dial bound: an old claim has
+/// no live owner (its task died), and leaving it would silently disable
+/// preconnect for the partition, while a young claim is a live dial
+/// whose head start the sweep must not discard.
+#[tokio::test]
+async fn the_sweep_clears_orphaned_claims_but_not_live_ones() {
+ let topic = format!("fence_prepared_{}", uuid::Uuid::new_v4().simple());
+ let producers = fenced_producers(&topic);
+
+ producers.stage_connecting_for_test(1, Duration::from_secs(60));
+ producers.stage_connecting_for_test(2, Duration::from_secs(0));
+ producers.sweep_prepared();
+
+ producers.preconnect(1).await;
+ assert!(
+ producers.has_prepared(1),
+ "the orphaned claim must clear so preconnect works again"
+ );
+ producers.preconnect(2).await;
+ assert_eq!(
+ producers.connect_attempts_for_test(),
+ 1,
+ "the live claim must survive the sweep and keep coalescing"
+ );
+}
+
/// 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.
diff --git a/rust/personhog-leader/tests/integration.rs b/rust/personhog-leader/tests/integration.rs
index 44cf7d21248c..5bb01110b5ac 100644
--- a/rust/personhog-leader/tests/integration.rs
+++ b/rust/personhog-leader/tests/integration.rs
@@ -1089,8 +1089,11 @@ async fn kafka_produce_failure_leaves_cache_unchanged() {
panic!("expected original person in cache");
};
assert_eq!(cached.version, 1);
- assert_eq!(cached.properties["email"], "[email protected]");
- assert!(cached.properties.get("name").is_none());
+ assert_eq!(
+ cached.parse_properties().unwrap()["email"],
+ );
+ assert!(cached.parse_properties().unwrap().get("name").is_none());
// Clear errors and verify the service recovers
mock_cluster.clear_request_errors(RDKafkaApiKey::Produce);
@@ -1357,9 +1360,19 @@ async fn pg_fallback_reads_numerics_the_leaders_parser_rejects() {
// The representable sentinel reads as the exact double JS reads;
// beyond-f64 garbage clamps instead of poisoning the row; neighbors
// are untouched.
- assert_eq!(person.properties["credits"].as_f64().unwrap(), f64::MAX);
- assert_eq!(person.properties["overflow"].as_f64().unwrap(), 1e307);
- assert_eq!(person.properties["plan"], "pro");
+ assert_eq!(
+ person.parse_properties().unwrap()["credits"]
+ .as_f64()
+ .unwrap(),
+ f64::MAX
+ );
+ assert_eq!(
+ person.parse_properties().unwrap()["overflow"]
+ .as_f64()
+ .unwrap(),
+ 1e307
+ );
+ assert_eq!(person.parse_properties().unwrap()["plan"], "pro");
sqlx::query("DELETE FROM posthog_person WHERE team_id = $1")
.bind(team_id)
@@ -2255,9 +2268,10 @@ async fn oversize_updates_are_rejected_and_oversized_rows_remediated() {
oversized_partition,
CachedPerson {
id: OVERSIZED_PERSON_ID,
- properties: serde_json::json!({
+ properties: serde_json::to_vec(&serde_json::json!({
"email": "[email protected]", "custom_a": big, "custom_b": big,
- }),
+ }))
+ .unwrap(),
..test_cached_person()
},
);
@@ -2328,7 +2342,7 @@ async fn oversize_updates_are_rejected_and_oversized_rows_remediated() {
unremediable_partition,
CachedPerson {
id: UNREMEDIABLE_PERSON_ID,
- properties: serde_json::json!({ "email": huge_email }),
+ properties: serde_json::to_vec(&serde_json::json!({ "email": huge_email })).unwrap(),
..test_cached_person()
},
);
diff --git a/rust/personhog-leader/tests/producer_flush.rs b/rust/personhog-leader/tests/producer_flush.rs
new file mode 100644
index 000000000000..09ac9e81a8e2
--- /dev/null
+++ b/rust/personhog-leader/tests/producer_flush.rs
@@ -0,0 +1,105 @@
+//! The kafka-producer lifecycle component must complete its shutdown
+//! within its flush bound even when the broker is unreachable — a
+//! wedged queue previously held the shutdown phase until the global
+//! timeout, reporting every later phase as stuck along with it.
+
+use std::time::{Duration, Instant};
+
+use common_kafka::kafka_producer::KafkaContext;
+use lifecycle::{ComponentOptions, Manager};
+use personhog_leader::kafka::spawn_bounded_flush_on_shutdown;
+use rdkafka::producer::{FutureProducer, FutureRecord};
+use rdkafka::ClientConfig;
+
+#[tokio::test]
+async fn shutdown_flush_is_bounded_against_an_unreachable_broker() {
+ let mut manager = Manager::builder("producer-flush-test")
+ .with_global_shutdown_timeout(Duration::from_secs(10))
+ .build();
+ let handle = manager.register(
+ "kafka-producer",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(6)),
+ );
+ let monitor = manager.monitor_background();
+
+ // An unroutable broker, dialed directly so no startup ping rejects
+ // it. The long message timeout keeps the queued record stuck for
+ // the whole test: the flush must give up on its own bound, not on
+ // the record expiring.
+ let producer: FutureProducer<KafkaContext> = ClientConfig::new()
+ .set("bootstrap.servers", "127.0.0.1:1")
+ .set("message.timeout.ms", "60000")
+ .create_with_context(KafkaContext::new(handle.clone()))
+ .expect("producer builds without a broker");
+ producer
+ .send_result(FutureRecord::<(), _>::to("flush_test").payload(b"stuck"))
+ .expect("record queues locally");
+
+ spawn_bounded_flush_on_shutdown(producer, handle.clone(), Duration::from_secs(1));
+
+ let start = Instant::now();
+ handle.request_shutdown();
+ monitor
+ .wait()
+ .await
+ .expect("shutdown must conclude cleanly, not time out");
+ assert!(
+ start.elapsed() < Duration::from_secs(4),
+ "shutdown took {:?}: the flush bound, not the graceful ceiling or the global \
+ timeout, must end the wait",
+ start.elapsed()
+ );
+}
+
+/// The incident's failure mode was a stalled broker, not an absent one:
+/// the connection succeeds and requests hang. The flush must give up on
+/// its own bound there too — librdkafka's broker state differs from the
+/// unroutable case (a live socket it waits on, not a connect it
+/// retries), so the unroutable test alone does not cover it.
+#[tokio::test]
+async fn shutdown_flush_is_bounded_against_a_stalled_broker() {
+ // Accept connections and never respond, holding each socket open:
+ // the shape of a broker that is up but not answering.
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind stall listener");
+ let addr = listener.local_addr().expect("listener addr");
+ tokio::spawn(async move {
+ let mut held = Vec::new();
+ while let Ok((socket, _)) = listener.accept().await {
+ held.push(socket);
+ }
+ });
+
+ let mut manager = Manager::builder("producer-flush-stall-test")
+ .with_global_shutdown_timeout(Duration::from_secs(10))
+ .build();
+ let handle = manager.register(
+ "kafka-producer",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(6)),
+ );
+ let monitor = manager.monitor_background();
+
+ let producer: FutureProducer<KafkaContext> = ClientConfig::new()
+ .set("bootstrap.servers", addr.to_string())
+ .set("message.timeout.ms", "60000")
+ .create_with_context(KafkaContext::new(handle.clone()))
+ .expect("producer builds against the stalled listener");
+ producer
+ .send_result(FutureRecord::<(), _>::to("flush_test").payload(b"stuck"))
+ .expect("record queues locally");
+
+ spawn_bounded_flush_on_shutdown(producer, handle.clone(), Duration::from_secs(1));
+
+ let start = Instant::now();
+ handle.request_shutdown();
+ monitor
+ .wait()
+ .await
+ .expect("shutdown must conclude cleanly, not time out");
+ assert!(
+ start.elapsed() < Duration::from_secs(4),
+ "shutdown took {:?} against a stalled broker: the flush bound must end the wait",
+ start.elapsed()
+ );
+}
diff --git a/rust/personhog-leader/tests/warming_integration.rs b/rust/personhog-leader/tests/warming_integration.rs
index 85e2f75a2844..eecb5de9c587 100644
--- a/rust/personhog-leader/tests/warming_integration.rs
+++ b/rust/personhog-leader/tests/warming_integration.rs
@@ -441,7 +441,8 @@ async fn warming_preserves_last_write_for_same_key() {
"cache must reflect the latest update's version"
);
assert_eq!(
- entry.properties["email"], "[email protected]",
+ entry.parse_properties().unwrap()["email"],
"cache must reflect the latest update's properties"
);
}