: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-leader): close fencing windows early at a fill threshold (#81921)
Zach Brown1bd367fcf653
diff --git a/rust/personhog-leader/src/config.rs b/rust/personhog-leader/src/config.rsindex c4839432ca69..e4143cce28e7 100644--- a/rust/personhog-leader/src/config.rs+++ b/rust/personhog-leader/src/config.rs@@ -29,11 +29,22 @@ pub struct Config {pub kafka_transactional_fencing: bool,/// How long a fencing transaction window admits joining writes- /// before committing. Amortizes the commit round trip across- /// concurrent same-partition writes.+ /// before committing, when it does not fill first (see+ /// FENCING_WINDOW_MAX_WRITES). Amortizes the commit round trip+ /// across concurrent same-partition writes.#[envconfig(default = "5")]pub fencing_window_ms: u64,+ /// Closes a fencing window early once this many writes have joined,+ /// rather than holding it open for the rest of FENCING_WINDOW_MS.+ /// Under a backlog, windows fill and commit at once, so a drain+ /// cycle is bounded by the commit round trip instead of the window;+ /// the window still bounds ack latency at light load. A close+ /// trigger, not a hard cap: writes arriving while the close+ /// propagates still ride the window.+ #[envconfig(default = "32")]+ pub fencing_window_max_writes: usize,+/// Timeout for transactional init (fencing acquisition) and/// commit/abort operations.#[envconfig(default = "0")]@@ -593,6 +604,14 @@ impl Config {.to_string(),);}+ if self.fencing_window_max_writes == 0 {+ return Err(+ "FENCING_WINDOW_MAX_WRITES must be at least 1: zero would close every \+ window at its first write, which is the per-write-commit shape the \+ window exists to avoid"+ .to_string(),+ );+ }let (message, txn, runway, window) = (self.fencing_message_timeout(),self.fencing_txn_timeout(),diff --git a/rust/personhog-leader/src/fencing.rs b/rust/personhog-leader/src/fencing.rsindex bab152380590..684cb90ab5c1 100644--- a/rust/personhog-leader/src/fencing.rs+++ b/rust/personhog-leader/src/fencing.rs@@ -13,10 +13,14 @@//! transaction each. A transactional producer admits one open//! transaction at a time, so per-write transactions would serialize a//! partition's writes on the commit round trip. A window opens on the-//! first write, admits concurrent writes for a short interval (their-//! records ride librdkafka's normal batching), then commits once and-//! resolves every waiter. Under light load a window holds one write and-//! costs one commit; under load the commit amortizes across the window.+//! first write, admits concurrent writes (their records ride+//! librdkafka's normal batching), then commits once and resolves every+//! waiter. The window closes on whichever comes first: its timer, which+//! bounds ack latency at light load, or its fill threshold, so a+//! backlog commits at once instead of idling out the timer. Under light+//! load a window holds one write and costs one commit; under load the+//! commit amortizes across the window and a drain cycle is bounded by+//! the commit round trip rather than the window.//!//! The price of sharing a transaction is shared failure: an aborted//! window fails all of its writes together. Readers never observe@@ -125,6 +129,28 @@ struct Gate {committing: bool,/// Commit-outcome subscribers for the open window.waiters: Vec<oneshot::Sender<Result<(), FencedProduceError>>>,+ /// Writes admitted to the open window. Counted against the fill+ /// threshold; unlike `in_flight` it never decrements, so a window+ /// whose early writes settle quickly still fills.+ joined: usize,+ /// Fires the open window's fill close. Armed at open, consumed by+ /// the seat that reaches the threshold, cleared when the window+ /// closes.+ fill_tx: Option<oneshot::Sender<()>>,+}++impl Gate {+ /// Count a seat toward the fill threshold, closing the window early+ /// when it is reached. A close trigger, not a hard cap: seats taken+ /// while the close propagates still ride the window.+ fn admit(&mut self, fill_threshold: usize) {+ self.joined += 1;+ if self.joined >= fill_threshold {+ if let Some(tx) = self.fill_tx.take() {+ let _ = tx.send(());+ }+ }+ }}/// Initialize a connected producer on the blocking pool, claiming the@@ -324,6 +350,9 @@ impl CommittingMark {let mut gate = fence.gate.lock().unwrap();gate.open = false;gate.committing = true;+ // The window is closed; an unfired fill sender is stale and+ // must not linger into the next window's gate state.+ gate.fill_tx = None;}Self { fence, partition }}@@ -438,8 +467,13 @@ pub struct FencedChangelogProducers {/// abandoning it; distinct from `commit_timeout`, which bounds only/// this process's wait on the commit call.broker_txn_timeout: Duration,- /// How long an open window admits joiners before committing.+ /// How long an open window admits joiners before committing, when+ /// it does not fill first.window: Duration,+ /// Fill threshold: joiners that close the window early. Bounds a+ /// backlog's drain cycle by the commit round trip instead of the+ /// window.+ window_max_writes: usize,/// Ceiling on the drain's wait for an open window to commit. Set/// well under the pre-revoke self-fence's allowance for a whole/// drain, so a shutdown with an open window does not truncate here@@ -480,6 +514,7 @@ pub struct FencedProducerConfig {pub commit_timeout: Duration,pub broker_txn_timeout: Duration,pub window: Duration,+ pub window_max_writes: usize,pub settle_budget: Duration,}@@ -492,6 +527,7 @@ impl FencedChangelogProducers {commit_timeout,broker_txn_timeout,window,+ window_max_writes,settle_budget,} = config;Self {@@ -501,6 +537,7 @@ impl FencedChangelogProducers {commit_timeout,broker_txn_timeout,window,+ window_max_writes,settle_budget,partitions: DashMap::new(),repair_nudge: None,@@ -578,6 +615,8 @@ impl FencedChangelogProducers {gate: Mutex::new(Gate {open: false,in_flight: 0,+ joined: 0,+ fill_tx: None,poisoned: false,committing: false,waiters: Vec::new(),@@ -955,17 +994,22 @@ impl FencedChangelogProducers {let mut gate = fence.gate.lock().unwrap();if gate.open {gate.in_flight += 1;- break false;+ gate.admit(self.window_max_writes);+ break None;}if !gate.committing && gate.in_flight == 0 && gate.waiters.is_empty() {// Idle: open a new window. BeginTxn is a local// librdkafka state transition, safe inline.match fence.producer.inner().begin_transaction() {Ok(()) => {+ let (fill_tx, fill_rx) = oneshot::channel();gate.open = true;gate.in_flight = 1;+ gate.joined = 0;gate.poisoned = false;- break true;+ gate.fill_tx = Some(fill_tx);+ gate.admit(self.window_max_writes);+ break Some(fill_rx);}Err(e) => Some(e),}@@ -989,13 +1033,13 @@ impl FencedChangelogProducers {histogram!("personhog_leader_fence_window_wait_ms", "partition" => partition.to_string()).record(join_start.elapsed().as_secs_f64() * 1000.0);- if opened {+ if let Some(fill) = opened {let fence_for_commit = Arc::clone(&fence);let window = self.window;let topic = self.topic.clone();let part = partition;tokio::spawn(async move {- commit_window_after(fence_for_commit, window, topic, part).await;+ commit_window_after(fence_for_commit, window, fill, topic, part).await;});}@@ -1309,10 +1353,24 @@ fn abort_window<C: ClientContext>(async fn commit_window_after(fence: Arc<PartitionFence>,window: Duration,+ fill: oneshot::Receiver<()>,topic: String,partition: u32,) {- sleep(window).await;+ // The fill branch also covers the sender dropping unfired, which+ // cannot happen while this window is open: the sender lives in the+ // gate of a fence this task holds, and nothing replaces it until+ // the CommittingMark below has been dropped.+ tokio::select! {+ _ = sleep(window) => {+ counter!("personhog_leader_fence_window_closed_total", "reason" => "timer")+ .increment(1);+ }+ _ = fill => {+ counter!("personhog_leader_fence_window_closed_total", "reason" => "filled")+ .increment(1);+ }+ }// Stop admitting joiners, then wait for outstanding sends. The mark// holds until this function returns — by any path — so no writer can@@ -1528,6 +1586,9 @@ pub fn preregister_fencing_metrics(partitions: u32) {counter!("personhog_leader_fence_settle_total", "outcome" => outcome).increment(0);}counter!("personhog_leader_fence_slots_abandoned_total").increment(0);+ for reason in ["timer", "filled"] {+ counter!("personhog_leader_fence_window_closed_total", "reason" => reason).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"] {diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rsindex a89104196e83..57b51a296600 100644--- a/rust/personhog-leader/src/main.rs+++ b/rust/personhog-leader/src/main.rs@@ -362,6 +362,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {commit_timeout: config.fencing_txn_timeout(),broker_txn_timeout: config.fencing_broker_txn_timeout(),window: Duration::from_millis(config.fencing_window_ms),+ window_max_writes: config.fencing_window_max_writes,settle_budget: config.fencing_settle_budget(),}).with_repair_nudge(repair_nudge),diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rsindex 8a6b55418dd1..936e7e707cde 100644--- a/rust/personhog-leader/tests/common/mod.rs+++ b/rust/personhog-leader/tests/common/mod.rs@@ -656,6 +656,7 @@ pub fn fenced_producers_for(topic: &str) -> personhog_leader::fencing::FencedChacommit_timeout: Duration::from_secs(10),broker_txn_timeout: BROKER_TXN_TIMEOUT,window: Duration::from_millis(5),+ window_max_writes: 32,settle_budget: Duration::from_secs(5),},)diff --git a/rust/personhog-leader/tests/fencing_integration.rs b/rust/personhog-leader/tests/fencing_integration.rsindex bb18863c094d..77db127dad12 100644--- a/rust/personhog-leader/tests/fencing_integration.rs+++ b/rust/personhog-leader/tests/fencing_integration.rs@@ -73,7 +73,11 @@ async fn read_committed_count(topic: &str) -> usize {/// librdkafka requires the broker bound to cover.const BROKER_TXN_TIMEOUT: Duration = Duration::from_secs(30);-fn fenced_producers_with_window(topic: &str, window: Duration) -> FencedChangelogProducers {+fn fenced_producers_with_window_and_fill(+ topic: &str,+ window: Duration,+ window_max_writes: usize,+) -> FencedChangelogProducers {let mut kafka = test_kafka_config();kafka.kafka_hosts = KAFKA_BOOTSTRAP.to_string();FencedChangelogProducers::new(FencedProducerConfig {@@ -83,10 +87,15 @@ fn fenced_producers_with_window(topic: &str, window: Duration) -> FencedChangelocommit_timeout: Duration::from_secs(10),broker_txn_timeout: BROKER_TXN_TIMEOUT,window,+ window_max_writes,settle_budget: window + Duration::from_secs(5),})}+fn fenced_producers_with_window(topic: &str, window: Duration) -> FencedChangelogProducers {+ fenced_producers_with_window_and_fill(topic, window, 32)+}+fn fenced_producers(topic: &str) -> FencedChangelogProducers {let mut kafka = test_kafka_config();kafka.kafka_hosts = KAFKA_BOOTSTRAP.to_string();@@ -97,6 +106,7 @@ fn fenced_producers(topic: &str) -> FencedChangelogProducers {commit_timeout: Duration::from_secs(10),broker_txn_timeout: BROKER_TXN_TIMEOUT,window: Duration::from_millis(5),+ window_max_writes: 32,settle_budget: Duration::from_secs(5),})}@@ -232,6 +242,36 @@ async fn concurrent_writes_share_a_window() {assert_ne!(a, b, "each write must get its own offset");}+/// A window that reaches its fill threshold commits immediately rather+/// than holding for its timer. The window here is far longer than the+/// test's own bound, so the acks can only arrive through the fill+/// close.+#[tokio::test]+async fn a_filled_window_commits_before_its_timer() {+ let topic = format!("fence_test_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers_with_window_and_fill(+ &topic,+ Duration::from_secs(60),+ 3,+ ));+ producers.acquire(0).await.expect("acquire");++ let writes: Vec<_> = (1..=3i64)+ .map(|v| {+ let p = Arc::clone(&producers);+ tokio::spawn(async move { p.produce(0, &test_person(v)).await })+ })+ .collect();+ tokio::time::timeout(Duration::from_secs(20), async {+ for write in writes {+ write.await.unwrap().expect("a filled window must commit");+ }+ })+ .await+ .expect("acks waited on the 60s timer — the fill close never fired");+ assert_eq!(read_committed_count(&topic).await, 3);+}+/// Sustained open-loop arrivals across many window turnovers: every/// write must land and every waiter must be woken through dozens of/// open → drain → commit cycles. A lost `window_closed` wakeup or a@@ -1349,6 +1389,7 @@ async fn a_heal_that_cannot_acquire_does_not_fail_the_run() {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(1),}));let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));@@ -1468,6 +1509,7 @@ async fn the_derived_production_timescales_compose_against_a_real_broker() {commit_timeout: config.fencing_txn_timeout(),broker_txn_timeout: config.fencing_broker_txn_timeout(),window: Duration::from_millis(config.fencing_window_ms),+ window_max_writes: config.fencing_window_max_writes,settle_budget: config.fencing_settle_budget(),}));producers