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): run one fenced window at a time per partition (#101321)

Zach Browne19cecf81892
diff --git a/rust/personhog-leader/src/config.rs b/rust/personhog-leader/src/config.rs
index 0d482a5d50e3..51dffcfb5f35 100644
--- a/rust/personhog-leader/src/config.rs
+++ b/rust/personhog-leader/src/config.rs
@@ -373,30 +373,6 @@ pub struct Config {
pub global_shutdown_timeout_secs: u64,
}
-/// A fenced write must resolve inside the runway the lease keepalive
-/// reserves for self-fencing (a third of the TTL). The bound is on the
-/// *queued* write, not the lucky one: an arrival can park behind a
-/// window that is already committing, so it pays that window's send and
-/// commit before its own — hence the factor of two below.
-///
-/// A commit may also be re-attempted, and the shares are sized so that
-/// every attempt the code will make still fits. The alternative was a
-/// bound that quietly assumed a single attempt while the retry loop
-/// spent three times it: an assertion the runway could not honour is
-/// worse than a tighter timeout, because the whole point of deriving
-/// these from the lease is that a write cannot outlive the fence that
-/// ends its session.
-///
-/// librdkafka additionally requires `message.timeout.ms <= transaction
-/// .timeout.ms`, and rejects a `transaction.timeout.ms` under a second.
-/// Deriving both from the runway satisfies every relation by
-/// construction wherever the lease TTL leaves room, and
-/// [`Config::validate_fencing_timescales`] refuses the configurations
-/// where it does not.
-const FENCING_MESSAGE_SHARE: u32 = 1;
-const FENCING_TXN_SHARE: u32 = 3;
-const FENCING_SHARE_BASE: u32 = 10;
-
/// How many times a window's commit is attempted in total, counting the
/// first.
pub const FENCING_COMMIT_ATTEMPTS: u32 = 2;
@@ -452,9 +428,10 @@ impl Config {
self.fencing_settle_budget() + Duration::from_millis(50)
}
- /// The budget one write may spend, derived so that a write queued
- /// behind another — and the settle that follows the queue draining —
- /// still finishes inside the runway.
+ /// What one fenced write may spend and still resolve inside the runway
+ /// the lease reserves for self-fencing: net of the settle that follows
+ /// a drain, and halved, because a write can park behind a committing
+ /// window and pay that window's send and commit before its own.
fn fencing_budget(&self) -> Duration {
self.lease_fence_runway()
.saturating_sub(Duration::from_millis(self.fencing_window_ms))
@@ -462,21 +439,23 @@ impl Config {
/ 2
}
- /// How long a fenced send may take.
+ /// How long a fenced send may take: what the transaction calls leave.
pub fn fencing_message_timeout(&self) -> Duration {
if self.fencing_message_timeout_ms > 0 {
return Duration::from_millis(u64::from(self.fencing_message_timeout_ms));
}
- (self.fencing_budget() * FENCING_MESSAGE_SHARE / FENCING_SHARE_BASE)
+ self.fencing_budget()
+ .saturating_sub(self.fencing_txn_timeout() * FENCING_TXN_CALLS)
.max(MIN_MESSAGE_TIMEOUT)
}
- /// How long a transaction init, commit, or abort may take.
+ /// How long a transaction init, commit, or abort may take: an even
+ /// share of the budget with the send, never under librdkafka's floor.
pub fn fencing_txn_timeout(&self) -> Duration {
if self.fencing_txn_timeout_ms > 0 {
return Duration::from_millis(self.fencing_txn_timeout_ms);
}
- (self.fencing_budget() * FENCING_TXN_SHARE / FENCING_SHARE_BASE).max(MIN_TXN_TIMEOUT)
+ (self.fencing_budget() / (FENCING_TXN_CALLS + 1)).max(MIN_TXN_TIMEOUT)
}
/// The producer queue each fenced producer gets, in MiB.
@@ -1014,10 +993,8 @@ mod fencing_timescale_tests {
}
}
- /// The retry budget and the timeout shares are one decision split
- /// across two constants. Raising the attempt count without shrinking
- /// the shares puts the code back outside the runway it validates
- /// against — silently, because every existing test would still pass.
+ /// The attempt count decides the split, so budget the calls do not
+ /// spend is a derivation bug, not slack.
#[test]
fn the_production_ttl_affords_every_transaction_call() {
let config = fenced(30);
@@ -1031,16 +1008,22 @@ mod fencing_timescale_tests {
assert!(
queued <= runway,
"{FENCING_TXN_CALLS} transaction calls need {queued:?}, runway is {runway:?}: \
- lower FENCING_TXN_SHARE / FENCING_MESSAGE_SHARE, or lower the attempt counts"
+ lower the attempt counts"
+ );
+ assert_eq!(
+ message + txn * FENCING_TXN_CALLS,
+ config.fencing_budget(),
+ "the derivation leaves budget unspent"
);
- // And it must be the attempts that are tight, not the shares
- // being trivially small: a budget that fits ten attempts would
- // mean the timeouts had collapsed toward their floors.
- let one_more = window + (message + txn * (FENCING_TXN_CALLS + 1)) * 2;
+ }
+
+ /// The transaction calls take only their floor; the send gets the rest.
+ #[test]
+ fn the_send_gets_what_the_transaction_calls_leave() {
+ let txn = fenced(30).fencing_txn_timeout();
assert!(
- one_more > runway,
- "the shares leave room for more attempts than are configured; raise \
- the attempt counts or the shares rather than leaving runway unused"
+ txn <= MIN_TXN_TIMEOUT + MIN_TXN_TIMEOUT / 10,
+ "transaction timeout {txn:?} sits well above the floor; that runway belongs to the send"
);
}
@@ -1301,11 +1284,11 @@ mod fencing_timescale_tests {
fenced(3606)
.validate_fencing_timescales()
.expect("LEASE_TTL=3606 sits just inside the broker ceiling");
- fenced(27)
+ fenced(26)
.validate_fencing_timescales()
- .expect("LEASE_TTL=27 is the acceptance floor");
+ .expect("LEASE_TTL=26 is the acceptance floor");
assert!(
- fenced(26).validate_fencing_timescales().is_err(),
+ fenced(25).validate_fencing_timescales().is_err(),
"below the floor, the librdkafka minimums cannot fit the drain room"
);
// And the production value must stay comfortably inside it.
diff --git a/rust/personhog-leader/src/fencing.rs b/rust/personhog-leader/src/fencing.rs
index 3ff76490084b..e55193665456 100644
--- a/rust/personhog-leader/src/fencing.rs
+++ b/rust/personhog-leader/src/fencing.rs
@@ -7,9 +7,9 @@
//! commit fails at the broker instead of landing.
//!
//! Lanes exist because the coordinator holds a producer's next transaction
-//! until its previous commit finishes, so a write takes the lane whose last
-//! commit is oldest. Each write keeps its person's lock through the ack,
-//! so ordering is unchanged.
+//! until its previous commit finishes, so consecutive windows rotate across
+//! lanes; a partition still runs one window at a time. Each write keeps its
+//! person's lock through the ack, so ordering is unchanged.
//!
//! Writes are grouped into transaction windows rather than one
//! transaction each. A transactional producer admits one open
@@ -269,6 +269,8 @@ struct PartitionFence {
lane: usize,
/// The commit clock at this lane's last finished commit; zero until then.
last_commit_end: AtomicU64,
+ /// The partition's turn, shared by its lanes; see [`PartitionLanes::turn`].
+ turn: Arc<Mutex<()>>,
/// Writers waiting on this lane's window to close.
#[cfg(any(test, feature = "test-support"))]
parked: AtomicUsize,
@@ -360,6 +362,10 @@ impl PartitionFence {
/// takes the lane least likely to be held.
struct PartitionLanes {
lanes: Vec<Arc<PartitionFence>>,
+ /// Serializes lane decisions: a writer holds it from reading the gates
+ /// to moving one, and a committer while it clears `committing`, so a
+ /// lane seen idle stays idle until the writer has chosen.
+ turn: Arc<Mutex<()>>,
}
impl PartitionLanes {
@@ -384,6 +390,7 @@ impl PartitionLanes {
return None;
};
states.push(LaneState {
+ open: gate.open,
committing: gate.committing,
last_commit_end: lane.last_commit_end.load(Ordering::Relaxed),
});
@@ -394,23 +401,28 @@ impl PartitionLanes {
#[derive(Clone, Copy, Debug)]
struct LaneState {
+ open: bool,
committing: bool,
last_commit_end: u64,
}
-/// The lane a write takes: among lanes not mid-commit, the one whose last
-/// commit is oldest; when every lane is committing, the oldest.
+/// One window at a time per partition: join an open one, park behind a
+/// committing one, else open on the lane whose last commit is oldest.
+/// Concurrent commits on one partition stretch the coordinator's hold.
fn pick_lane(states: &[LaneState]) -> usize {
- let oldest = |committing: bool| {
+ let oldest = |wanted: fn(&LaneState) -> bool| {
states
.iter()
.enumerate()
- .filter(|(_, state)| state.committing == committing)
+ .filter(|(_, state)| wanted(state))
.map(|(index, state)| (state.last_commit_end, index))
.min()
.map(|(_, index)| index)
};
- oldest(false).or_else(|| oldest(true)).unwrap_or(0)
+ oldest(|state| state.open)
+ .or_else(|| oldest(|state| state.committing))
+ .or_else(|| oldest(|_| true))
+ .unwrap_or(0)
}
/// One seat in the open window, released on drop.
@@ -527,6 +539,14 @@ impl CommittingMark {
impl Drop for CommittingMark {
fn drop(&mut self) {
+ // Stamped and cleared in one turn, so a writer that finds this
+ // lane idle also finds it the newest commit.
+ let turn = self
+ .fence
+ .turn
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner);
+ self.fence.stamp_commit_end();
// Deliberately tolerant of a poisoned gate: the mark existing is
// what wedges the partition, so it has to come off even when the
// lock's last holder panicked.
@@ -541,6 +561,7 @@ impl Drop for CommittingMark {
mem::take(&mut gate.waiters)
}
};
+ drop(turn);
// On the ordinary path the committer took the waiters before this
// drops, so the list is empty. Waiters still here mean the
// committer unwound between taking the mark and answering anyone
@@ -832,6 +853,7 @@ impl FencedChangelogProducers {
counter!("personhog_leader_fence_init_total", "outcome" => "ok").increment(1);
histogram!("personhog_leader_fence_init_ms", "path" => path)
.record(start.elapsed().as_secs_f64() * 1000.0);
+ let turn = Arc::new(Mutex::new(()));
let lanes = producers
.into_iter()
.enumerate()
@@ -840,6 +862,7 @@ impl FencedChangelogProducers {
producer,
lane,
last_commit_end: AtomicU64::new(0),
+ turn: Arc::clone(&turn),
#[cfg(any(test, feature = "test-support"))]
parked: AtomicUsize::new(0),
superseded_by_heal: AtomicBool::new(false),
@@ -862,7 +885,7 @@ impl FencedChangelogProducers {
})
})
.collect();
- let installed = Arc::new(PartitionLanes { lanes });
+ let installed = Arc::new(PartitionLanes { lanes, turn });
if let Some(replaced) = self.partitions.insert(partition, Arc::clone(&installed)) {
// The heal path installs over a still-present condemned
// fence, and by then the commit task has usually dropped its
@@ -1236,8 +1259,11 @@ impl FencedChangelogProducers {
#[cfg(any(test, feature = "test-support"))]
pub fn finish_committing_for_test(&self, partition: u32, lane: usize) {
if let Some(fence) = self.lane(partition, lane) {
- fence.gate.lock().unwrap().committing = false;
- fence.stamp_commit_end();
+ {
+ let _turn = fence.turn.lock().unwrap_or_else(PoisonError::into_inner);
+ fence.stamp_commit_end();
+ fence.gate.lock().unwrap().committing = false;
+ }
fence.window_closed.notify_waiters();
}
}
@@ -1441,6 +1467,9 @@ impl FencedChangelogProducers {
counter!("personhog_leader_kafka_produce_errors_total").increment(1);
return Err(FencedProduceError::NotAcquired);
}
+ // Held until this writer has joined, opened, or decided to
+ // park: no lane can open or finish a commit in between.
+ let turn = lanes.turn.lock().unwrap_or_else(PoisonError::into_inner);
let fence = match &pinned {
Some(fence) => Arc::clone(fence),
None => match lanes.pick(partition) {
@@ -1493,6 +1522,7 @@ impl FencedChangelogProducers {
None
}
};
+ drop(turn);
if let Some(e) = begin_failed {
counter!("personhog_leader_kafka_produce_errors_total").increment(1);
return Err(self.classify(&fence, partition, e));
@@ -2078,7 +2108,6 @@ async fn commit_window_after(
}
};
- fence.stamp_commit_end();
for waiter in waiters {
// A dropped receiver means the writer's request already ended;
// nothing to deliver.
@@ -2332,15 +2361,30 @@ mod tests {
}
#[test]
- fn a_write_takes_the_lane_that_committed_longest_ago() {
- let lane = |committing, last_commit_end| LaneState {
- committing,
+ fn a_partition_runs_one_window_at_a_time_across_its_lanes() {
+ let idle = |last_commit_end| LaneState {
+ open: false,
+ committing: false,
+ last_commit_end,
+ };
+ let open = |last_commit_end| LaneState {
+ open: true,
+ committing: false,
+ last_commit_end,
+ };
+ let committing = |last_commit_end| LaneState {
+ open: false,
+ committing: true,
last_commit_end,
};
- assert_eq!(pick_lane(&[lane(false, 5), lane(false, 2)]), 1);
- assert_eq!(pick_lane(&[lane(true, 1), lane(false, 9)]), 1);
- assert_eq!(pick_lane(&[lane(true, 4), lane(true, 2)]), 1);
- assert_eq!(pick_lane(&[lane(false, 0)]), 0);
+ // Idle partition: the lane that committed longest ago.
+ assert_eq!(pick_lane(&[idle(5), idle(2)]), 1);
+ assert_eq!(pick_lane(&[idle(0)]), 0);
+ // An open window is joined even on the lane that committed last.
+ assert_eq!(pick_lane(&[idle(1), open(9)]), 1);
+ // A committing lane parks the write instead of opening another lane.
+ assert_eq!(pick_lane(&[committing(1), idle(9)]), 0);
+ assert_eq!(pick_lane(&[idle(9), committing(4), committing(2)]), 2);
}
/// A condemn reason absent from the preregistration list first
diff --git a/rust/personhog-leader/tests/fencing_integration.rs b/rust/personhog-leader/tests/fencing_integration.rs
index e77fd60f6c94..82dff0cd4d68 100644
--- a/rust/personhog-leader/tests/fencing_integration.rs
+++ b/rust/personhog-leader/tests/fencing_integration.rs
@@ -399,6 +399,44 @@ async fn a_successor_fences_every_lane_of_the_predecessor() {
.expect("writes parked forever — a window_closed wakeup was lost");
}
+/// A write that arrives while another lane commits parks behind it
+/// instead of opening a second window; the next window opens on the
+/// lane idle longest once that commit ends.
+#[tokio::test]
+async fn a_write_parks_behind_a_commit_on_another_lane() {
+ let topic = format!("fence_serial_{}", uuid::Uuid::new_v4().simple());
+ let producers = Arc::new(fenced_producers(&topic, 2));
+ producers.acquire(0).await.expect("acquire the fence");
+ producers.begin_committing_for_test(0, 0);
+ let write = {
+ let p = Arc::clone(&producers);
+ tokio::spawn(async move { p.produce(0, &test_person(1)).await })
+ };
+ tokio::time::timeout(Duration::from_secs(5), async {
+ while producers.parked_writers_for_test(0, 0) == 0 {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("the writer must park behind lane 0's commit, not open lane 1");
+ assert_eq!(
+ producers.lane_commit_marks_for_test(0),
+ vec![0, 0],
+ "nothing commits while lane 0's commit is in flight"
+ );
+ producers.finish_committing_for_test(0, 0);
+ tokio::time::timeout(Duration::from_secs(10), write)
+ .await
+ .expect("the woken writer must commit")
+ .expect("the writer task must not panic")
+ .expect("the write lands");
+ let marks = producers.lane_commit_marks_for_test(0);
+ assert!(
+ marks[1] > marks[0],
+ "the write commits on lane 1 after lane 0's commit ends: {marks:?}"
+ );
+}
+
/// A writer that parked because every lane was committing picks again
/// when it wakes: the lane whose commit just finished is the one the
/// coordinator is holding, and another lane may have finished earlier.