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): stop fenced writes waiting on the previous commit (#100633)

Zach Brown53973ed7f06b
diff --git a/rust/common/kafka/src/transaction.rs b/rust/common/kafka/src/transaction.rs
index 372511c658de..5d3d26c95a8c 100644
--- a/rust/common/kafka/src/transaction.rs
+++ b/rust/common/kafka/src/transaction.rs
@@ -159,13 +159,33 @@ impl ConnectedTransactionalProducer<DefaultClientContext> {
transactional_id: &str,
timeout: Duration,
broker_txn_timeout: Duration,
+ ) -> Result<Self, KafkaError> {
+ Self::connect_bounded_with_context(
+ config,
+ transactional_id,
+ timeout,
+ broker_txn_timeout,
+ DefaultClientContext,
+ )
+ }
+}
+
+impl<C: ClientContext + 'static> ConnectedTransactionalProducer<C> {
+ /// [`Self::connect_bounded`] with a caller-supplied client context, for
+ /// a caller that consumes librdkafka's statistics or logs.
+ pub fn connect_bounded_with_context(
+ config: &KafkaConfig,
+ transactional_id: &str,
+ timeout: Duration,
+ broker_txn_timeout: Duration,
+ context: C,
) -> Result<Self, KafkaError> {
let inner = connect(
config,
transactional_id,
timeout,
Some(broker_txn_timeout),
- DefaultClientContext,
+ context,
)?;
Ok(ConnectedTransactionalProducer { inner })
}
diff --git a/rust/personhog-coordination/README.md b/rust/personhog-coordination/README.md
index d5160a097992..a098d9395673 100644
--- a/rust/personhog-coordination/README.md
+++ b/rust/personhog-coordination/README.md
@@ -108,12 +108,12 @@ Several failure modes are handled explicitly:
**The double-zombie residual — status by half.** A lease-expired router (excluded from the freeze quorum, still routing on a stale table) feeding a lease-expired pod (coordination loop dead, never fenced) can ack a write after the partition's new owner warmed; the write lands beyond the warm HWM, invisible to the new owner forever. Both zombie windows are bounded by lease self-fencing to roughly one heartbeat tick, so the loss needs both to coincide — but nothing rejects the zombie's produce at the broker. The stateright model reproduces the exact interleaving (`current_protocol_double_zombie_loses_acked_writes`) and machine-validates the fix (`Variant::EpochFenced`). Where each piece stands, one bullet per residual:
-- **Zombie writes: closed behind `KAFKA_TRANSACTIONAL_FENCING` (default off).** A partition's owner acquires its transactional id before the warm read, so a predecessor that missed its drain is fenced at the broker and its produce fails instead of landing. Changelog consumers read `read_committed`, so aborted windows are never visible. The guarantee binds per binary, not per flag flip: a pod still running the old build produces non-transactionally and no epoch can fence it, so enable the flag only once the whole fleet is on a build that carries it — which the default-off flag and enable-after-rollout ordering already encode.
+- **Zombie writes: closed behind `KAFKA_TRANSACTIONAL_FENCING` (default off).** A partition's owner acquires its transactional id before the warm read, so a predecessor that missed its drain is fenced at the broker and its produce fails instead of landing. Changelog consumers read `read_committed`, so aborted windows are never visible. The guarantee binds per binary, not per flag flip: a pod still running the old build produces non-transactionally and no epoch can fence it, so enable the flag only once the whole fleet is on a build that carries it — which the default-off flag and enable-after-rollout ordering already encode. The lane count (`FENCING_LANES`) binds the same way: a takeover fences one transactional id per lane, so while a roll mixes lane counts, a successor on the smaller count leaves a predecessor's extra lanes unfenced, and only the lease gate bounds what those lanes can still commit.
- **Zombie reads: closed behind `LEASE_GATED_AUTHORITY` (default off).** The keepalive publishes its last confirmed renewal and the request path refuses once that stamp is older than the renewal margin — checked at admission and again before answering, since the claim can lapse while a read is served. A stalled keepalive therefore fences implicitly. The model confirms fencing and the gate are complementary rather than alternative: each alone leaves stale reads; only together does every safety property hold.
- *Residual, recorded because the model's `serve_read` points here:* the closure is only as prompt as the claim's lapse. Natural expiry always lapses the stamp before etcd deletes anything, but an out-of-band *revocation* removes the registration while the stamp is still fresh, and only the deliberately best-effort registration watch converts that into an immediate surrender. With the watch dead, the stamp stays valid for up to one heartbeat (`prompt_detection_is_what_makes_the_read_gate_hold` pins exactly this). No production path revokes another pod's lease, so reaching the window takes an operator.
- **Acquisition is gated on the same claim.** A zombie waking inside its lease window would otherwise re-acquire the partition's transactional id on its way to noticing it is dead, fencing the legitimate owner — the broker grants the epoch to whoever initializes last. Warming and resume consult the authority stamp before acquiring and again after, dropping the fence rather than building on a claim they no longer hold. The e2e zombie gate manufactures the waking-zombie shape and asserts by consequence; the per-arm rejection coverage lives in the deterministic fencing integration tests. Because the two mechanisms only work together, `KAFKA_TRANSACTIONAL_FENCING` is refused at startup without `LEASE_GATED_AUTHORITY`.
- **A condemned producer heals in place.** An abort that did not land, or a commit whose outcome stayed unknown, leaves a producer no later window can be begun from. It is condemned and given up on the next write, which answers as unowned (`FailedPrecondition`, the router's bounce class) rather than as a retryable failure, and the serving-side verification re-acquires on the next convergence tick — gated on the authority stamp, which is what gives a pod the standing to bump the epoch.
-- **The drain commits its own window when it can.** A request cancelled mid-produce takes its handler — and the drain's in-flight count — with it, leaving the record it enqueued in a window nobody waits on; the drain waits (bounded, best-effort, never failing the drain) for that window to commit before acking, landing the cancelled write below the successor's cutoff. The successor's `init_transactions` aborts whatever could not settle — safe in either ordering, because the transaction coordinator serializes the in-flight commit against the successor's init on the shared transactional id.
+- **A commit outlives the request that started it.** A request cancelled mid-produce loses its handler, but the produce runs as its own task holding the person lock and the drain's in-flight count, so the record lands in the cache in version order and the drain waits for it like any other write. The drain still settles (bounded, best-effort, never failing the drain) a window nobody waits on before acking, which a failed send leaves behind for the committer to abort; the successor's `init_transactions` aborts whatever could not settle — safe in either ordering, because the transaction coordinator serializes the in-flight commit against the successor's init on the shared transactional id.
- **Writer progress is coupled to leader transaction liveness.** `read_committed` means the writer cannot advance past an open window: a leader that stops mid-window holds every `read_committed` consumer of that partition at the last stable offset until the broker abandons the transaction — bounded by the derived broker transaction timeout (about 6s at the production lease). The price of aborted windows never reaching Postgres.
**Rollout placement residuals** (`k8s_awareness_enabled`, default off). During a Deployment rollout the coordinator holds old-generation Ready pods and caps incoming pods at their final share, keyed on departing-generation registrations rather than the transient k8s rollout flag. Placement-behavior residuals, none affecting write safety (the handoff protocol is unchanged):
@@ -121,7 +121,7 @@ Several failure modes are handled explicitly:
- **Some partitions move twice.** Orphans that overflow onto Hold members when no capped pod has room move again when capacity appears, and ceil-rounded caps can leave the final balance one leveling move away. The cost of every partition always having an owner.
- **Intent loss degrades to policy-free planning.** A Deployment deleted mid-rollout, a watcher stream dying between evaluations (stale intent until the lazy rewatch reports), or the k8s API being down all fall back to plain balanced placement — availability over placement. A freshly elected coordinator bound-waits (`FIRST_INTENT_WAIT`) for its first intent per controller, so failover mid-rollout does not plan policy-free unless the API server is actually unreachable.
- **A capped pod's in-flight steal counts against its cap before it lands.** Planning attributes pinned handoffs to their targets, so a capped member briefly under-fills while its steal is in flight; the next evaluation after completion levels it.
-- **With `KAFKA_TRANSACTIONAL_FENCING` off there is no settle equivalent.** Nothing forces a queued record to the broker before the drain acks, so it can land above the new owner's warm cutoff, and a later write for that person re-derives the same version — where the writer's first-wins guard keeps the record nobody acked and discards the one that was. The unfenced path is slated for removal once fencing proves out.
+- **With `KAFKA_TRANSACTIONAL_FENCING` off there is no settle equivalent.** The commit task holds the in-flight slot through the delivery, so the drain waits for every send; what survives is a delivery that timed out after the broker may already have appended the record, which can then land above the new owner's warm cutoff, invisible to it until a later write for that person, whose version the floor keeps past the lost one. The unfenced path is slated for removal once fencing proves out.
**Assignment strategies are minimal**: The two bundled strategies (`JumpHashStrategy` and `StickyBalancedStrategy`) are basic implementations meant to exercise the coordination layer. `JumpHashStrategy` is stateless and deterministic but ignores current assignments entirely, causing unnecessary partition movement on every rebalance. `StickyBalancedStrategy` minimizes movement but uses a naive greedy approach without considering locality, rack awareness, or weighted pods. Both are placeholders to be replaced with a production-grade strategy as requirements become clearer.
diff --git a/rust/personhog-leader/src/config.rs b/rust/personhog-leader/src/config.rs
index 8bb795bea5f4..0d482a5d50e3 100644
--- a/rust/personhog-leader/src/config.rs
+++ b/rust/personhog-leader/src/config.rs
@@ -48,6 +48,13 @@ pub struct Config {
#[envconfig(default = "32")]
pub fencing_window_max_writes: usize,
+ /// Transactional producers per partition; writes rotate across them.
+ /// A takeover fences one id per lane, so the count binds fleet-wide:
+ /// a successor on a smaller count leaves a predecessor's extra lanes
+ /// unfenced.
+ #[envconfig(default = "4")]
+ pub fencing_lanes: usize,
+
/// Timeout for transactional init (fencing acquisition) and
/// commit/abort operations.
#[envconfig(default = "0")]
@@ -411,6 +418,10 @@ pub const FENCING_ABORT_ATTEMPTS: u32 = 1;
/// from this, so the two cannot drift apart.
pub const FENCING_TXN_CALLS: u32 = FENCING_COMMIT_ATTEMPTS + FENCING_ABORT_ATTEMPTS;
+/// Sanity ceiling on lanes: each is a producer, a connection and a thread
+/// per acquisition.
+pub const MAX_FENCING_LANES: usize = 64;
+
/// librdkafka's documented minimum for `transaction.timeout.ms`.
const MIN_TXN_TIMEOUT: Duration = Duration::from_millis(1000);
/// A floor for the send timeout; zero means *no timeout* to librdkafka,
@@ -482,7 +493,8 @@ impl Config {
/// So the budget is the aggregate, divided. The floor keeps a
/// high-partition-count deployment from starving any single producer
/// below a workable depth; it trades the guarantee for a bound that
- /// is still far under the un-divided figure.
+ /// is still far under the un-divided figure. Each share must still
+ /// hold one window of records; raise the aggregate if it cannot.
pub fn fencing_queue_mib(&self, partitions: u32) -> u32 {
// The floor cannot be unconditional: above roughly fifty
// partitions it would start multiplying again, and the aggregate
@@ -499,13 +511,20 @@ impl Config {
// multiplies back up, which is the defect this division exists to
// remove. The honest bound is the aggregate, and one MiB is the
// smallest queue librdkafka will take.
- (self.kafka.kafka_producer_queue_mib / partitions.max(1)).max(1)
+ (self.kafka.kafka_producer_queue_mib / self.fenced_producers(partitions)).max(1)
}
/// The same division for the message-count limit, which bounds the
/// queue independently of record size.
pub fn fencing_queue_messages(&self, partitions: u32) -> u32 {
- (self.kafka.kafka_producer_queue_messages / partitions.max(1)).max(1)
+ (self.kafka.kafka_producer_queue_messages / self.fenced_producers(partitions)).max(1)
+ }
+
+ /// Producers the aggregate queue budget is divided among: one per
+ /// lane per partition.
+ fn fenced_producers(&self, partitions: u32) -> u32 {
+ let lanes = u32::try_from(self.fencing_lanes.max(1)).unwrap_or(u32::MAX);
+ partitions.max(1).saturating_mul(lanes)
}
/// How long fence acquisition may take.
@@ -696,6 +715,15 @@ impl Config {
if !self.kafka_transactional_fencing {
return Ok(());
}
+ if self.fencing_lanes < 1 {
+ return Err("FENCING_LANES must be at least 1".to_string());
+ }
+ if self.fencing_lanes > MAX_FENCING_LANES {
+ return Err(format!(
+ "FENCING_LANES ({}) must be at most {MAX_FENCING_LANES}",
+ self.fencing_lanes
+ ));
+ }
// Fencing without the lease gate is the combination the e2e
// zombie scenario breaks: acquisition takes the partition's epoch
// from whoever holds it, so a pod waking inside its lease window
@@ -1228,10 +1256,11 @@ mod fencing_timescale_tests {
#[test]
fn a_high_partition_count_still_leaves_a_workable_queue() {
let config = fenced(30);
- // The division alone leaves a workable depth at the deployed
- // shape, and never rounds to a value librdkafka would reject.
- assert_eq!(config.fencing_queue_mib(16), 25);
- assert_eq!(config.fencing_queue_messages(16), 625_000);
+ // The budget is divided among every fenced producer, four lanes
+ // per partition at the default, and never rounds to a value
+ // librdkafka would reject.
+ assert_eq!(config.fencing_queue_mib(16), 6);
+ assert_eq!(config.fencing_queue_messages(16), 156_250);
assert!(config.fencing_queue_mib(1024) >= 1);
assert!(config.fencing_queue_messages(1024) >= 1);
assert!(
@@ -1240,6 +1269,20 @@ mod fencing_timescale_tests {
);
}
+ /// Zero lanes would leave a partition with nothing to produce on, and
+ /// an absurd count would open that many connections per acquisition.
+ #[test]
+ fn a_lane_count_outside_its_bounds_is_refused() {
+ for lanes in [0, MAX_FENCING_LANES + 1] {
+ let mut config = fenced(30);
+ config.fencing_lanes = lanes;
+ let err = config
+ .validate_fencing_timescales()
+ .expect_err("a lane count outside its bounds must be refused");
+ assert!(err.contains("FENCING_LANES"), "{err}");
+ }
+ }
+
/// A lease TTL long enough to derive past the broker's own ceiling
/// must be refused at startup, not discovered as an acquisition that
/// fails on every partition with only a counter to explain it.
diff --git a/rust/personhog-leader/src/coordination/mod.rs b/rust/personhog-leader/src/coordination/mod.rs
index 316e328b9513..769c22d27798 100644
--- a/rust/personhog-leader/src/coordination/mod.rs
+++ b/rust/personhog-leader/src/coordination/mod.rs
@@ -229,12 +229,10 @@ impl HandoffHandler for LeaderHandoffHandler {
self.inflight
.wait_until_empty(partition, DRAIN_POLL_INTERVAL)
.await;
- // A request cancelled mid-produce takes its handler — and the
- // count above — with it, leaving the record it enqueued in a
- // window nobody is waiting on. Committing that window here lands
- // the cancelled write below the cutoff the successor is about to
- // read, rather than leaving it to be aborted by whichever side
- // acts first.
+ // The count above covers every write through its outcome, a
+ // cancelled request's included: its commit task holds the slot.
+ // What can still be open here is a window nobody waits on, one a
+ // failed send poisoned and the committer has yet to abort.
//
// Best-effort by construction, and the drain proceeds either way:
// the successor's `init_transactions` aborts whatever is left,
diff --git a/rust/personhog-leader/src/emitted.rs b/rust/personhog-leader/src/emitted.rs
index 31bc252deb81..b1e9b4898d47 100644
--- a/rust/personhog-leader/src/emitted.rs
+++ b/rust/personhog-leader/src/emitted.rs
@@ -1,11 +1,9 @@
//! Versions this pod put on the wire but never heard the outcome of.
//!
//! A changelog record can become durable without the write that produced
-//! it learning so. A request cancelled while its send is in flight leaves
-//! the record to ride its window's commit; a request cancelled while
-//! waiting on that commit has already been counted, and the commit lands
-//! with nobody to tell; and a commit whose outcome stays unknown is, by
-//! construction, a record that may or may not exist.
+//! it learning so: a commit whose outcome stays unknown is, by
+//! construction, a record that may or may not exist, and a commit task
+//! that unwinds or is torn down at shutdown never hears its outcome.
//!
//! In each case the version is spent. The cache still holds the version
//! before the write, so the next write for that person derives the same
diff --git a/rust/personhog-leader/src/fencing.rs b/rust/personhog-leader/src/fencing.rs
index 82050405ba0a..3ff76490084b 100644
--- a/rust/personhog-leader/src/fencing.rs
+++ b/rust/personhog-leader/src/fencing.rs
@@ -1,13 +1,15 @@
//! Broker-enforced epoch fencing for the changelog, via per-partition
//! transactional producers.
//!
-//! Each partition's owner holds a producer whose `transactional.id` is
-//! derived from the partition alone. Taking ownership initializes
-//! transactions for that id, which bumps the broker-side producer epoch
-//! and fences every predecessor: a zombie old owner that missed its own
-//! drain can no longer append to the changelog — its next produce or
-//! commit fails with a fenced error at the broker, loudly, instead of
-//! silently corrupting the partition's history.
+//! Each partition's owner holds one transactional producer per lane. Taking
+//! ownership initializes every lane's id, which bumps the broker-side
+//! epochs and fences every predecessor: a zombie owner's next produce or
+//! 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.
//!
//! Writes are grouped into transaction windows rather than one
//! transaction each. A transactional producer admits one open
@@ -30,12 +32,18 @@
#[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::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant};
use std::{fmt, mem};
use common_kafka::config::KafkaConfig;
use common_kafka::transaction::{ConnectedTransactionalProducer, TransactionalProducer};
+
+use crate::producer_stats::FencedProducerContext;
+
+/// The fenced producers report their statistics through one context.
+type ConnectedFencedProducer = ConnectedTransactionalProducer<FencedProducerContext>;
+type FencedProducer = TransactionalProducer<FencedProducerContext>;
use dashmap::mapref::entry::Entry;
use dashmap::DashMap;
use metrics::{counter, histogram};
@@ -57,9 +65,9 @@ use crate::inflight::InflightTracker;
use crate::kafka::changelog_message_key;
/// The fencing scope is the partition: every owner of partition `p`
-/// shares this id, so a new owner's init fences the old one.
-fn transactional_id(topic: &str, partition: u32) -> String {
- format!("personhog-changelog-{topic}-p{partition}")
+/// shares its lane ids, so a new owner's init fences the old one.
+fn transactional_id(topic: &str, partition: u32, lane: usize) -> String {
+ format!("personhog-changelog-{topic}-p{partition}-l{lane}")
}
#[derive(Debug)]
@@ -156,22 +164,73 @@ impl Gate {
}
}
-/// 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,
+struct Dial {
+ kafka: KafkaConfig,
+ topic: String,
+ partition: u32,
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}"))
+ broker_txn_timeout: Duration,
+ #[cfg(any(test, feature = "test-support"))]
+ attempts: Arc<AtomicUsize>,
+}
+
+/// Connect one lane's producer, with no transactional state yet.
+fn connect_lane(dial: &Dial, lane: usize) -> Result<ConnectedFencedProducer, String> {
+ #[cfg(any(test, feature = "test-support"))]
+ dial.attempts.fetch_add(1, Ordering::SeqCst);
+ let tid = transactional_id(&dial.topic, dial.partition, lane);
+ ConnectedFencedProducer::connect_bounded_with_context(
+ &dial.kafka,
+ &tid,
+ dial.timeout,
+ dial.broker_txn_timeout,
+ FencedProducerContext::default(),
+ )
+ .map_err(|e| format!("lane {lane} connect: {e}"))
+}
+
+/// Claim one lane's id, which fences its previous owners. A parked
+/// connection whose init fails gets one fresh connect-and-init rather
+/// than failing the claim, and sets `fell_back`.
+fn claim_lane(
+ dial: &Dial,
+ lane: usize,
+ parked: Option<ConnectedFencedProducer>,
+ fell_back: &AtomicBool,
+) -> Result<FencedProducer, String> {
+ if let Some(parked) = parked {
+ match parked.init(dial.timeout) {
+ Ok(ready) => return Ok(ready),
+ Err((e, _)) => {
+ fell_back.store(true, Ordering::Relaxed);
+ warn!(
+ partition = dial.partition,
+ lane,
+ error = %e,
+ "prepared connection failed to init; connecting fresh"
+ );
+ }
}
- Err(e) => Err(format!("fence init join: {e}")),
}
+ connect_lane(dial, lane)?
+ .init(dial.timeout)
+ .map_err(|(e, _)| format!("lane {lane} init: {e}"))
+}
+
+/// One blocking job per lane on its own thread; results in lane order.
+fn per_lane<I: Send, T: Send>(inputs: Vec<I>, job: impl Fn(usize, I) -> T + Sync) -> Vec<T> {
+ let job = &job;
+ std::thread::scope(|scope| {
+ let handles: Vec<_> = inputs
+ .into_iter()
+ .enumerate()
+ .map(|(lane, input)| scope.spawn(move || job(lane, input)))
+ .collect();
+ handles
+ .into_iter()
+ .map(|handle| handle.join().expect("a lane job must not panic"))
+ .collect()
+ })
}
/// Send a fence to the blocking pool to die. Dropping the last
@@ -180,12 +239,42 @@ async fn init_producer(
/// run on async workers. Best-effort: a caller (an in-flight write, the
/// settle wait) still holding the Arc pays the destroy wherever it drops
/// last, which is rarer than the common case this moves.
-fn drop_fence_off_worker(fence: Arc<PartitionFence>) {
- tokio::task::spawn_blocking(move || drop(fence));
+fn drop_off_worker<T: Send + 'static>(value: T) {
+ tokio::task::spawn_blocking(move || drop(value));
}
+/// Carries a value a cancelled future would otherwise drop on a runtime
+/// worker, and sends it to the blocking pool instead.
+struct DropOffWorker<T: Send + 'static>(Option<T>);
+
+impl<T: Send + 'static> DropOffWorker<T> {
+ fn take(mut self) -> T {
+ self.0.take().expect("taken once")
+ }
+}
+
+impl<T: Send + 'static> Drop for DropOffWorker<T> {
+ fn drop(&mut self) {
+ if let Some(value) = self.0.take() {
+ drop_off_worker(value);
+ }
+ }
+}
+
+/// Stamps a lane when its commit finishes, so selection can order lanes.
+static COMMIT_CLOCK: AtomicU64 = AtomicU64::new(0);
+
struct PartitionFence {
- producer: TransactionalProducer,
+ producer: FencedProducer,
+ lane: usize,
+ /// The commit clock at this lane's last finished commit; zero until then.
+ last_commit_end: AtomicU64,
+ /// Writers waiting on this lane's window to close.
+ #[cfg(any(test, feature = "test-support"))]
+ parked: AtomicUsize,
+ /// Set by a heal before it re-acquires, so a fence this lane then
+ /// reports counts as the pod's own doing rather than a new owner's.
+ superseded_by_heal: AtomicBool,
/// Makes the next commit task panic, so tests can reach the arm that
/// handles a committer which never reports. Scoped to the fence
/// rather than a global: the tests in this binary run concurrently.
@@ -230,7 +319,9 @@ impl PartitionFence {
.increment(1);
error!(
partition,
- reason, "changelog producer left unusable; awaiting re-acquisition"
+ lane = self.lane,
+ reason,
+ "changelog producer left unusable; awaiting re-acquisition"
);
// The only way back is a heal on a convergence to Serving, and
// the reconcile tick that would otherwise carry it is seconds
@@ -247,15 +338,88 @@ impl PartitionFence {
fn is_usable(&self) -> bool {
!self.unusable.load(Ordering::Relaxed)
}
+
+ fn fence_cause(&self) -> &'static str {
+ if self.superseded_by_heal.load(Ordering::Relaxed) {
+ "heal"
+ } else {
+ "takeover"
+ }
+ }
+
+ fn stamp_commit_end(&self) {
+ self.last_commit_end.store(
+ COMMIT_CLOCK.fetch_add(1, Ordering::Relaxed) + 1,
+ Ordering::Relaxed,
+ );
+ }
+}
+
+/// A partition's transactional producers. The coordinator refuses a
+/// producer's next transaction for a while after it commits, so a write
+/// takes the lane least likely to be held.
+struct PartitionLanes {
+ lanes: Vec<Arc<PartitionFence>>,
+}
+
+impl PartitionLanes {
+ /// One condemned lane condemns the partition: repair re-acquires
+ /// whole partitions, which aborts the other lanes' open windows, and
+ /// their writers answer as fenced and retry.
+ fn is_usable(&self) -> bool {
+ self.lanes.iter().all(|lane| lane.is_usable())
+ }
+
+ fn contains(&self, fence: &Arc<PartitionFence>) -> bool {
+ self.lanes.iter().any(|lane| Arc::ptr_eq(lane, fence))
+ }
+
+ /// The lane a write takes, or none when a gate is poisoned: that lane
+ /// is condemned, so the partition heals like any dead producer.
+ fn pick(&self, partition: u32) -> Option<Arc<PartitionFence>> {
+ let mut states = Vec::with_capacity(self.lanes.len());
+ for lane in &self.lanes {
+ let Ok(gate) = lane.gate.lock() else {
+ lane.condemn(partition, "gate_poisoned");
+ return None;
+ };
+ states.push(LaneState {
+ committing: gate.committing,
+ last_commit_end: lane.last_commit_end.load(Ordering::Relaxed),
+ });
+ }
+ Some(Arc::clone(&self.lanes[pick_lane(&states)]))
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+struct LaneState {
+ 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.
+fn pick_lane(states: &[LaneState]) -> usize {
+ let oldest = |committing: bool| {
+ states
+ .iter()
+ .enumerate()
+ .filter(|(_, state)| state.committing == committing)
+ .map(|(index, state)| (state.last_commit_end, index))
+ .min()
+ .map(|(_, index)| index)
+ };
+ oldest(false).or_else(|| oldest(true)).unwrap_or(0)
}
/// One seat in the open window, released on drop.
///
-/// A request can vanish at any await — tonic drops the handler future
-/// when the client's deadline expires or its stream resets — and the
-/// seat has to come back even then, or the committer waits on an
-/// in-flight count that never reaches zero and every later write on the
-/// partition parks forever behind it.
+/// A produce future can be dropped at any await — a task unwinding, the
+/// runtime shutting down, a caller giving up — and the seat has to come
+/// back even then, or the committer waits on an in-flight count that
+/// never reaches zero and every later write on the partition parks
+/// forever behind it.
struct WindowSlot {
fence: Arc<PartitionFence>,
released: bool,
@@ -315,7 +479,7 @@ impl WindowSlot {
impl Drop for WindowSlot {
fn drop(&mut self) {
if !self.released {
- // A cancelled request: release the seat but do not poison.
+ // A dropped produce: release the seat but do not poison.
// Its record may already be enqueued and will ride the
// commit; nobody is waiting for the ack, and failing the
// window would punish the writes that are still waiting.
@@ -412,7 +576,7 @@ pub struct FenceGuard {
/// alone would drop whatever happens to be installed at drop time,
/// which after a release and a re-acquire is somebody else's
/// producer — the same hazard `forget_fence` checks for.
- taken: Option<Arc<PartitionFence>>,
+ taken: Option<Arc<PartitionLanes>>,
/// Names the work the fence was taken for, so an abandon names the
/// path that dropped mid-flight.
context: &'static str,
@@ -475,8 +639,9 @@ enum Prepared {
/// 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),
+ /// A finished dial, one connection per lane, parked for the next
+ /// acquire to consume.
+ Ready(Vec<ConnectedFencedProducer>),
}
/// Per-partition fenced producers for the changelog. Constructed once
@@ -503,14 +668,19 @@ pub struct FencedChangelogProducers {
/// drain, so a shutdown with an open window does not truncate here
/// and report a failed drain.
settle_budget: Duration,
- partitions: DashMap<u32, Arc<PartitionFence>>,
+ /// Transactional producers per partition.
+ lanes: usize,
+ /// Ceiling on one produce, past every stage's own timeout, so a
+ /// wedged lane cannot hold a write's lock and in-flight slot forever.
+ produce_bound: Duration,
+ partitions: DashMap<u32, Arc<PartitionLanes>>,
/// Nudged on condemnation, so the coordination loop can run a
/// repair pass now instead of on its next reconcile tick. Carries no
/// 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
+ /// Connected-but-uninitialized producers, one set 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
@@ -523,7 +693,7 @@ pub struct FencedChangelogProducers {
/// guards against is invisible through public behavior until the
/// pod is already dying.
#[cfg(any(test, feature = "test-support"))]
- connect_attempts: AtomicUsize,
+ connect_attempts: Arc<AtomicUsize>,
/// Outcomes a test stages for the next produce on a partition.
///
@@ -549,6 +719,7 @@ pub struct FencedProducerConfig {
pub window: Duration,
pub window_max_writes: usize,
pub settle_budget: Duration,
+ pub lanes: usize,
}
impl FencedChangelogProducers {
@@ -562,7 +733,12 @@ impl FencedChangelogProducers {
window,
window_max_writes,
settle_budget,
+ lanes,
} = config;
+ assert!(lanes >= 1, "a partition needs at least one lane");
+ // Two queued writes' worth of window, send and commit attempts,
+ // the same shape the config sizes the lease runway against.
+ let produce_bound = (window + commit_timeout * (COMMIT_RETRIES as u32 + 2)) * 2;
Self {
kafka,
topic,
@@ -572,12 +748,14 @@ impl FencedChangelogProducers {
window,
window_max_writes,
settle_budget,
+ lanes,
+ produce_bound,
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),
+ connect_attempts: Arc::new(AtomicUsize::new(0)),
#[cfg(any(test, feature = "test-support"))]
staged_failures: DashMap::new(),
}
@@ -592,117 +770,162 @@ impl FencedChangelogProducers {
self
}
- /// Take the partition's fence: create the transactional producer and
- /// initialize transactions, which fences every previous owner of the
- /// 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 timeout = self.init_timeout;
- 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;
+ /// Take the partition's fence: claim every lane's id, which fences
+ /// every previous owner of them. The claims run as one blocking task
+ /// and their producers travel back in a guard, so a cancelled acquire
+ /// never destroys a producer on a runtime worker.
+ async fn acquire_installed(&self, partition: u32) -> Result<Arc<PartitionLanes>, String> {
+ let start = Instant::now();
// 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";
- 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 mut parked: Vec<Option<ConnectedFencedProducer>> =
+ match self.prepared.remove(&partition) {
+ Some((_, Prepared::Ready(parked))) => parked.into_iter().map(Some).collect(),
+ _ => Vec::new(),
+ };
+ let path = if parked.is_empty() {
+ "cold"
+ } else {
+ "prepared"
+ };
+ parked.resize_with(self.lanes, || None);
+ let dial = self.dial(partition);
+ let claimed = spawn_blocking(move || {
+ let mut producers = Vec::with_capacity(parked.len());
+ let mut failure = None;
+ let fell_back = AtomicBool::new(false);
+ let results = per_lane(parked, |lane, parked| {
+ claim_lane(&dial, lane, parked, &fell_back)
+ });
+ if fell_back.load(Ordering::Relaxed) {
+ counter!("personhog_leader_fence_preconnect_total", "outcome" => "init_failed")
+ .increment(1);
+ }
+ for (lane, result) in results.into_iter().enumerate() {
+ match result {
+ Ok(producer) => producers.push(producer),
+ Err(e) => {
+ warn!(partition, lane, error = %e, "lane claim failed");
+ failure.get_or_insert(e);
+ }
}
}
- }
- 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)?
+ match failure {
+ Some(e) => Err(e),
+ None => Ok(DropOffWorker(Some(producers))),
+ }
+ })
+ .await;
+ let producers = match claimed {
+ Ok(Ok(producers)) => producers.take(),
+ Ok(Err(e)) => {
+ counter!("personhog_leader_fence_init_total", "outcome" => "error").increment(1);
+ return Err(e);
+ }
+ Err(join) => {
+ counter!("personhog_leader_fence_init_total", "outcome" => "error").increment(1);
+ return Err(format!("fence claim join: {join}"));
}
};
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 installed = Arc::new(PartitionFence {
- producer,
- gate: Mutex::new(Gate {
- open: false,
- in_flight: 0,
- joined: 0,
- fill_tx: None,
- poisoned: false,
- committing: false,
- waiters: Vec::new(),
- }),
- sends_settled: Notify::new(),
- window_closed: Notify::new(),
- #[cfg(any(test, feature = "test-support"))]
- panic_next_commit: AtomicBool::new(false),
- unusable: AtomicBool::new(false),
- commit_timeout: self.commit_timeout,
- repair_nudge: self.repair_nudge.clone(),
- });
+ let lanes = producers
+ .into_iter()
+ .enumerate()
+ .map(|(lane, producer)| {
+ Arc::new(PartitionFence {
+ producer,
+ lane,
+ last_commit_end: AtomicU64::new(0),
+ #[cfg(any(test, feature = "test-support"))]
+ parked: AtomicUsize::new(0),
+ superseded_by_heal: AtomicBool::new(false),
+ gate: Mutex::new(Gate {
+ open: false,
+ in_flight: 0,
+ joined: 0,
+ fill_tx: None,
+ poisoned: false,
+ committing: false,
+ waiters: Vec::new(),
+ }),
+ sends_settled: Notify::new(),
+ window_closed: Notify::new(),
+ #[cfg(any(test, feature = "test-support"))]
+ panic_next_commit: AtomicBool::new(false),
+ unusable: AtomicBool::new(false),
+ commit_timeout: self.commit_timeout,
+ repair_nudge: self.repair_nudge.clone(),
+ })
+ })
+ .collect();
+ let installed = Arc::new(PartitionLanes { lanes });
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
// clones — making this insert the last reference and its
// drop a blocking librdkafka destroy. Send it to the
// blocking pool like every other eviction site.
- drop_fence_off_worker(replaced);
+ drop_off_worker(replaced);
}
Ok(installed)
}
+ fn dial(&self, partition: u32) -> Dial {
+ Dial {
+ kafka: self.kafka.clone(),
+ topic: self.topic.clone(),
+ partition,
+ timeout: self.init_timeout,
+ broker_txn_timeout: self.broker_txn_timeout,
+ #[cfg(any(test, feature = "test-support"))]
+ attempts: Arc::clone(&self.connect_attempts),
+ }
+ }
+
/// Take the partition's fence, discarding the handle. The caller
/// relies on the map rather than on holding the fence itself.
pub async fn acquire(&self, partition: u32) -> Result<(), String> {
self.acquire_installed(partition).await.map(|_| ())
}
- /// The fence currently installed for a partition, if any.
- fn installed(&self, partition: u32) -> Option<Arc<PartitionFence>> {
+ /// Mark the installed lanes as about to be fenced by this pod's own
+ /// re-acquisition, so the fences their writers then see count as a
+ /// heal rather than a takeover.
+ pub fn expect_self_fence(&self, partition: u32) {
+ if let Some(lanes) = self.installed(partition) {
+ for lane in &lanes.lanes {
+ lane.superseded_by_heal.store(true, Ordering::Relaxed);
+ }
+ }
+ }
+
+ /// The lanes currently installed for a partition, if any.
+ fn installed(&self, partition: u32) -> Option<Arc<PartitionLanes>> {
self.partitions.get(&partition).map(|f| Arc::clone(&f))
}
+ #[cfg(any(test, feature = "test-support"))]
+ fn lane(&self, partition: u32, lane: usize) -> Option<Arc<PartitionFence>> {
+ self.installed(partition)
+ .map(|lanes| Arc::clone(&lanes.lanes[lane]))
+ }
+
/// Drop the partition's fence with ownership. The broker-side epoch
/// survives; only a future owner's init advances it.
pub fn release(&self, partition: u32) {
- if let Some((_, fence)) = self.partitions.remove(&partition) {
- drop_fence_off_worker(fence);
+ if let Some((_, lanes)) = self.partitions.remove(&partition) {
+ drop_off_worker(lanes);
}
self.discard_prepared(partition);
}
- /// Connect the partition's producer ahead of acquisition, so the
+ /// Connect the partition's producers 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
+ /// connections on the blocking pool and parks them; a failure is only
/// 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
@@ -727,7 +950,19 @@ impl FencedChangelogProducers {
}
}
let start = Instant::now();
- match self.connect_producer(partition).await {
+ let dial = self.dial(partition);
+ let lanes = self.lanes;
+ let dialed = spawn_blocking(move || {
+ // All or nothing: each connection carries its own lane's id.
+ let mut connected = Vec::with_capacity(lanes);
+ for result in per_lane(vec![(); lanes], |lane, ()| connect_lane(&dial, lane)) {
+ connected.push(result?);
+ }
+ Ok(connected)
+ })
+ .await
+ .unwrap_or_else(|join| Err(format!("fence dial join: {join}")));
+ match dialed {
Ok(connected) => {
counter!("personhog_leader_fence_preconnect_total", "outcome" => "ok").increment(1);
histogram!("personhog_leader_fence_preconnect_ms")
@@ -756,7 +991,7 @@ impl FencedChangelogProducers {
/// 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) {
+ fn park(&self, partition: u32, token: u64, connected: Vec<ConnectedFencedProducer>) {
match self.prepared.entry(partition) {
Entry::Occupied(mut slot) if matches!(slot.get(), Prepared::Connecting { token: t, .. } if *t == token) =>
{
@@ -770,31 +1005,6 @@ impl FencedChangelogProducers {
}
}
- /// Build the partition's connected-but-uninitialized producer on the
- /// blocking pool.
- async fn connect_producer(
- &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;
- 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. A Connecting
/// claim is removed without a drop: its dial discards on
@@ -898,7 +1108,7 @@ impl FencedChangelogProducers {
pub fn holds(&self, partition: u32) -> bool {
self.partitions
.get(&partition)
- .is_some_and(|fence| fence.is_usable())
+ .is_some_and(|lanes| lanes.is_usable())
}
/// Commit the partition's open window before its owner gives it up.
@@ -921,7 +1131,7 @@ impl FencedChangelogProducers {
/// there is no branch that un-fences one whose handoff never
/// completed.
pub async fn settle(&self, partition: u32) {
- let Some(fence) = self.installed(partition) else {
+ let Some(lanes) = self.installed(partition) else {
// A write that met a condemned producer already gave the
// fence up, which is the ordinary shape after a condemnation
// — recorded rather than silent, or the series has no
@@ -940,28 +1150,45 @@ impl FencedChangelogProducers {
// reaches about 6s at the production TTL, so every shutdown with an
// open window would truncate here and report a failed drain.
let budget = self.settle_budget;
+ // Every lane waits under the one budget at once, so a lane stuck
+ // in its commit cannot spend it before the others are looked at.
+ let settled: Vec<AtomicBool> = lanes.lanes.iter().map(|_| AtomicBool::new(false)).collect();
let waited = timeout(budget, async {
- loop {
- // Register before inspecting, or a close landing between
- // the two is lost and this waits on a wakeup already
- // spent.
- let closed = fence.window_closed.notified();
- tokio::pin!(closed);
- closed.as_mut().enable();
- {
- let gate = fence.gate.lock().unwrap();
- if !gate.open && !gate.committing && gate.in_flight == 0 {
- return;
+ let waits = lanes
+ .lanes
+ .iter()
+ .zip(&settled)
+ .map(|(fence, settled)| async move {
+ loop {
+ // Register before inspecting, or a close landing
+ // between the two is lost and this waits on a wakeup
+ // already spent.
+ let closed = fence.window_closed.notified();
+ tokio::pin!(closed);
+ closed.as_mut().enable();
+ {
+ let gate = fence.gate.lock().unwrap_or_else(PoisonError::into_inner);
+ if !gate.open && !gate.committing && gate.in_flight == 0 {
+ break;
+ }
+ }
+ closed.await;
}
- }
- closed.await;
- }
+ settled.store(true, Ordering::Relaxed);
+ });
+ futures::future::join_all(waits).await;
})
.await;
+ let unsettled: Vec<usize> = settled
+ .iter()
+ .enumerate()
+ .filter(|(_, settled)| !settled.load(Ordering::Relaxed))
+ .map(|(lane, _)| lane)
+ .collect();
let outcome = if waited.is_err() {
"timeout"
- } else if !fence.is_usable() {
+ } else if !lanes.is_usable() {
// Condemned somewhere in this partition's history, so this
// producer has nothing left to give the changelog.
"unusable"
@@ -973,6 +1200,7 @@ impl FencedChangelogProducers {
warn!(
partition,
outcome,
+ unsettled_lanes = ?unsettled,
"changelog window did not settle before the drain; leaving what remains to the \
incoming owner's init"
);
@@ -995,24 +1223,63 @@ impl FencedChangelogProducers {
/// gate directly is what makes the interleaving deterministic rather
/// than statistical.
#[cfg(any(test, feature = "test-support"))]
- pub fn begin_committing_for_test(&self, partition: u32) {
- if let Some(fence) = self.partitions.get(&partition) {
+ pub fn begin_committing_for_test(&self, partition: u32, lane: usize) {
+ if let Some(fence) = self.lane(partition, lane) {
let mut gate = fence.gate.lock().unwrap();
gate.open = false;
gate.committing = true;
}
}
- /// Release that gate and wake the parked writers, as a finishing
- /// commit does.
+ /// Release that gate, stamp the lane's commit clock, and wake the
+ /// parked writers, as a finishing commit does.
#[cfg(any(test, feature = "test-support"))]
- pub fn finish_committing_for_test(&self, partition: u32) {
- if let Some(fence) = self.partitions.get(&partition) {
+ 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();
fence.window_closed.notify_waiters();
}
}
+ /// Close the lane's open window now, as its fill threshold would.
+ #[cfg(any(test, feature = "test-support"))]
+ pub fn close_window_for_test(&self, partition: u32, lane: usize) {
+ if let Some(fence) = self.lane(partition, lane) {
+ if let Some(fill) = fence.gate.lock().unwrap().fill_tx.take() {
+ let _ = fill.send(());
+ }
+ }
+ }
+
+ /// Poison a lane's gate, as a panic under its lock would.
+ #[cfg(any(test, feature = "test-support"))]
+ pub fn poison_gate_for_test(&self, partition: u32, lane: usize) {
+ if let Some(fence) = self.lane(partition, lane) {
+ let poisoner = std::thread::spawn(move || {
+ let _held = fence.gate.lock().unwrap();
+ panic!("poisoning the gate");
+ });
+ assert!(poisoner.join().is_err(), "the poisoner must panic");
+ }
+ }
+
+ /// Writers parked on a lane's window closing.
+ #[cfg(any(test, feature = "test-support"))]
+ pub fn parked_writers_for_test(&self, partition: u32, lane: usize) -> usize {
+ self.lane(partition, lane)
+ .map(|fence| fence.parked.load(Ordering::SeqCst))
+ .unwrap_or(0)
+ }
+
+ /// Writers subscribed to a lane's open window for its commit outcome.
+ #[cfg(any(test, feature = "test-support"))]
+ pub fn waiting_writers_for_test(&self, partition: u32, lane: usize) -> usize {
+ self.lane(partition, lane)
+ .map(|fence| fence.gate.lock().unwrap().waiters.len())
+ .unwrap_or(0)
+ }
+
/// Poison the partition's open window, as a send that failed inside
/// it does.
///
@@ -1022,7 +1289,7 @@ impl FencedChangelogProducers {
/// window is the whole reason the flag exists.
#[cfg(any(test, feature = "test-support"))]
pub fn poison_window_for_test(&self, partition: u32) {
- if let Some(fence) = self.installed(partition) {
+ if let Some(fence) = self.lane(partition, 0) {
fence.gate.lock().unwrap().poisoned = true;
}
}
@@ -1033,7 +1300,7 @@ impl FencedChangelogProducers {
/// stageable deterministically; what matters is the mark's cleanup.
#[cfg(any(test, feature = "test-support"))]
pub fn orphan_committer_for_test(&self, partition: u32) {
- if let Some(fence) = self.installed(partition) {
+ if let Some(fence) = self.lane(partition, 0) {
let mark = CommittingMark::take(Arc::clone(&fence), partition);
let (tx, _rx) = oneshot::channel();
fence.gate.lock().unwrap().waiters.push(tx);
@@ -1046,7 +1313,7 @@ impl FencedChangelogProducers {
/// can arrange against a live producer.
#[cfg(any(test, feature = "test-support"))]
pub fn panic_next_commit_for_test(&self, partition: u32) {
- if let Some(fence) = self.installed(partition) {
+ if let Some(fence) = self.lane(partition, 0) {
fence.panic_next_commit.store(true, Ordering::SeqCst);
}
}
@@ -1057,7 +1324,7 @@ impl FencedChangelogProducers {
/// dropped, so the commit it was running may well have landed.
#[cfg(any(test, feature = "test-support"))]
pub fn abandon_waiters_for_test(&self, partition: u32) {
- if let Some(fence) = self.partitions.get(&partition) {
+ if let Some(fence) = self.lane(partition, 0) {
let taken = mem::take(&mut fence.gate.lock().unwrap().waiters);
drop(taken);
}
@@ -1070,14 +1337,45 @@ impl FencedChangelogProducers {
}
#[cfg(any(test, feature = "test-support"))]
- pub fn condemn_for_test(&self, partition: u32) {
- if let Some(fence) = self.partitions.get(&partition) {
+ pub fn condemn_for_test(&self, partition: u32, lane: usize) {
+ if let Some(fence) = self.lane(partition, lane) {
fence.condemn(partition, "test");
}
}
- /// Produce one changelog record inside the partition's current
- /// transaction window, returning its offset once the window commits.
+ /// Produce on a specific lane, bypassing selection.
+ #[cfg(any(test, feature = "test-support"))]
+ pub async fn produce_on_lane_for_test(
+ &self,
+ partition: u32,
+ lane: usize,
+ person: &Person,
+ ) -> Result<i64, FencedProduceError> {
+ let lanes = self
+ .installed(partition)
+ .ok_or(FencedProduceError::NotAcquired)?;
+ let fence = Arc::clone(&lanes.lanes[lane]);
+ self.produce_on(partition, lanes, Some(fence), person).await
+ }
+
+ /// Each lane's commit clock stamp; zero for a lane that never
+ /// committed.
+ #[cfg(any(test, feature = "test-support"))]
+ pub fn lane_commit_marks_for_test(&self, partition: u32) -> Vec<u64> {
+ self.installed(partition)
+ .map(|lanes| {
+ lanes
+ .lanes
+ .iter()
+ .map(|lane| lane.last_commit_end.load(Ordering::Relaxed))
+ .collect()
+ })
+ .unwrap_or_default()
+ }
+
+ /// Produce one changelog record inside a transaction window on one of
+ /// the partition's lanes, returning its offset once the window
+ /// commits.
pub async fn produce(
&self,
partition: u32,
@@ -1087,20 +1385,49 @@ impl FencedChangelogProducers {
if let Some((_, staged)) = self.staged_failures.remove(&partition) {
return Err(staged);
}
+ let lanes = self.installed(partition).ok_or_else(|| {
+ counter!("personhog_leader_kafka_produce_errors_total").increment(1);
+ FencedProduceError::NotAcquired
+ })?;
+ match timeout(
+ self.produce_bound,
+ self.produce_on(partition, lanes, None, person),
+ )
+ .await
+ {
+ Ok(outcome) => outcome,
+ // The record may be enqueued or committed by now, so the
+ // outcome is unknown rather than failed.
+ Err(_) => {
+ counter!("personhog_leader_fence_produce_bound_exceeded_total").increment(1);
+ error!(
+ partition,
+ bound_ms = self.produce_bound.as_millis() as u64,
+ "changelog produce exceeded its bound; outcome unknown"
+ );
+ Err(FencedProduceError::Indeterminate(
+ "produce exceeded its bound".to_string(),
+ ))
+ }
+ }
+ }
+
+ /// Produce on the partition, picking a lane per attempt unless one is
+ /// pinned.
+ async fn produce_on(
+ &self,
+ partition: u32,
+ lanes: Arc<PartitionLanes>,
+ pinned: Option<Arc<PartitionFence>>,
+ person: &Person,
+ ) -> Result<i64, FencedProduceError> {
let durable_start = Instant::now();
- let fence = self
- .partitions
- .get(&partition)
- .map(|f| Arc::clone(&f))
- .ok_or_else(|| {
- counter!("personhog_leader_kafka_produce_errors_total").increment(1);
- FencedProduceError::NotAcquired
- })?;
// Join the open window, or open one. A window mid-commit admits
- // no joiners; wait for it to close and retry.
+ // no joiners; wait for it to close and pick again, since the lane
+ // that just committed is the one the coordinator is holding.
let join_start = Instant::now();
- let opened = loop {
+ let (fence, opened) = loop {
// Checked every iteration, not only on the way in. A
// condemned producer cannot begin another transaction, and
// the commit that condemns it is the same one whose end wakes
@@ -1109,11 +1436,22 @@ impl FencedChangelogProducers {
// opens a window on a dead producer and answers with a
// retryable failure instead of the ownership bounce that gets
// the partition re-acquired.
- if !fence.is_usable() {
- self.forget_fence(partition, &fence);
+ if !lanes.is_usable() {
+ self.forget_fence(partition, &lanes);
counter!("personhog_leader_kafka_produce_errors_total").increment(1);
return Err(FencedProduceError::NotAcquired);
}
+ let fence = match &pinned {
+ Some(fence) => Arc::clone(fence),
+ None => match lanes.pick(partition) {
+ Some(fence) => fence,
+ None => {
+ self.forget_fence(partition, &lanes);
+ counter!("personhog_leader_kafka_produce_errors_total").increment(1);
+ return Err(FencedProduceError::NotAcquired);
+ }
+ },
+ };
// Register interest before inspecting the gate: a close that
// fires between the check and the await must not be lost.
let closed = fence.window_closed.notified();
@@ -1129,7 +1467,9 @@ impl FencedChangelogProducers {
if gate.open {
gate.in_flight += 1;
gate.admit(self.window_max_writes);
- break None;
+ counter!("personhog_leader_fence_lane_choices_total", "choice" => "join")
+ .increment(1);
+ break (Arc::clone(&fence), None);
}
if !gate.committing && gate.in_flight == 0 && gate.waiters.is_empty() {
// Idle: open a new window. BeginTxn is a local
@@ -1143,7 +1483,9 @@ impl FencedChangelogProducers {
gate.poisoned = false;
gate.fill_tx = Some(fill_tx);
gate.admit(self.window_max_writes);
- break Some(fill_rx);
+ counter!("personhog_leader_fence_lane_choices_total", "choice" => "open")
+ .increment(1);
+ break (Arc::clone(&fence), Some(fill_rx));
}
Err(e) => Some(e),
}
@@ -1155,7 +1497,12 @@ impl FencedChangelogProducers {
counter!("personhog_leader_kafka_produce_errors_total").increment(1);
return Err(self.classify(&fence, partition, e));
}
+ counter!("personhog_leader_fence_lane_choices_total", "choice" => "park").increment(1);
+ #[cfg(any(test, feature = "test-support"))]
+ fence.parked.fetch_add(1, Ordering::SeqCst);
closed.await;
+ #[cfg(any(test, feature = "test-support"))]
+ fence.parked.fetch_sub(1, Ordering::SeqCst);
};
// Near-zero when a window was open or the producer idle; the tail
// is time parked behind a draining or committing window — the
@@ -1266,7 +1613,7 @@ impl FencedChangelogProducers {
e,
FencedProduceError::Fenced | FencedProduceError::FencedUncertain(_)
) {
- self.forget_fence(partition, &fence);
+ self.forget_lane(partition, &fence);
}
Err(e)
}
@@ -1296,17 +1643,21 @@ impl FencedChangelogProducers {
e: KafkaError,
) -> FencedProduceError {
if is_fenced(&e) || producer_fenced(fence.producer.inner()) {
+ let cause = fence.fence_cause();
counter!(
"personhog_leader_produce_fenced_total",
- "partition" => partition.to_string()
+ "partition" => partition.to_string(),
+ "cause" => cause
)
.increment(1);
error!(
partition,
+ lane = fence.lane,
+ cause,
error = %e,
- "changelog producer fenced by a newer owner — this pod's claim is stale"
+ "changelog producer fenced by a newer claim on its id"
);
- self.forget_fence(partition, fence);
+ self.forget_lane(partition, fence);
FencedProduceError::Fenced
} else {
FencedProduceError::Failed(e.to_string())
@@ -1317,12 +1668,22 @@ impl FencedChangelogProducers {
/// one installed: a write can be in flight across a release and a
/// re-acquire, and the stale producer's failure must not evict its
/// live replacement.
- fn forget_fence(&self, partition: u32, fence: &Arc<PartitionFence>) {
+ fn forget_fence(&self, partition: u32, lanes: &Arc<PartitionLanes>) {
+ self.evict(partition, |installed| Arc::ptr_eq(installed, lanes));
+ }
+
+ /// [`Self::forget_fence`] for the lane that reported the fence: a
+ /// newer owner claimed the partition's ids, so the whole set is stale.
+ fn forget_lane(&self, partition: u32, fence: &Arc<PartitionFence>) {
+ self.evict(partition, |installed| installed.contains(fence));
+ }
+
+ fn evict(&self, partition: u32, stale: impl Fn(&Arc<PartitionLanes>) -> bool) {
let removed = self
.partitions
- .remove_if(&partition, |_, installed| Arc::ptr_eq(installed, fence));
+ .remove_if(&partition, |_, installed| stale(installed));
if let Some((_, evicted)) = removed {
- drop_fence_off_worker(evicted);
+ drop_off_worker(evicted);
// The escalation signal for a partition giving up its fence
// outside the orderly release path — the series exists so a
// deploy-window burst of these is visible.
@@ -1390,13 +1751,14 @@ enum WindowVerdict {
/// preregistration below cannot drift from the call sites: a reason
/// missing here first appears as a brand-new series mid-incident instead
/// of rising from zero.
-const CONDEMN_REASONS: [&str; 6] = [
+const CONDEMN_REASONS: [&str; 7] = [
"abort_fenced",
"abort_failed",
"commit_fenced",
"commit_indeterminate",
"commit_task_lost",
"committer_unwound",
+ "gate_poisoned",
];
/// Why a window's outcome leaves the producer unusable, if it does.
@@ -1630,17 +1992,21 @@ async fn commit_window_after(
fence.condemn(partition, reason);
}
let verdict = window_verdict(outcome, fenced_now);
+ let cause = fence.fence_cause();
if verdict == WindowVerdict::FencedUncertain {
counter!(
"personhog_leader_produce_fenced_total",
- "partition" => partition.to_string()
+ "partition" => partition.to_string(),
+ "cause" => cause
)
.increment(1);
error!(
partition,
+ lane = fence.lane,
+ cause,
topic,
error = %e,
- "changelog window fenced by a newer owner, with its own outcome unknown"
+ "changelog window fenced by a newer claim on its id, with its own outcome unknown"
);
Err(FencedProduceError::FencedUncertain(e.to_string()))
} else if verdict == WindowVerdict::Fenced {
@@ -1650,15 +2016,18 @@ async fn commit_window_after(
if !poisoned {
counter!(
"personhog_leader_produce_fenced_total",
- "partition" => partition.to_string()
+ "partition" => partition.to_string(),
+ "cause" => cause
)
.increment(1);
}
error!(
partition,
+ lane = fence.lane,
+ cause,
topic,
error = %e,
- "changelog window fenced by a newer owner — this pod's claim is stale"
+ "changelog window fenced by a newer claim on its id"
);
Err(FencedProduceError::Fenced)
} else if verdict == WindowVerdict::Aborted {
@@ -1667,7 +2036,13 @@ async fn commit_window_after(
"partition" => partition.to_string()
)
.increment(1);
- error!(partition, topic, error = %e, "changelog window aborted");
+ error!(
+ partition,
+ lane = fence.lane,
+ topic,
+ error = %e,
+ "changelog window aborted"
+ );
Err(FencedProduceError::Failed(format!("aborted: {e}")))
} else {
// Retries are exhausted and the transaction's fate is
@@ -1681,6 +2056,7 @@ async fn commit_window_after(
.increment(1);
error!(
partition,
+ lane = fence.lane,
topic,
error = %e,
"changelog commit outcome unknown; the window may or may not have committed"
@@ -1702,6 +2078,7 @@ 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.
@@ -1730,6 +2107,9 @@ 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 choice in ["join", "open", "park"] {
+ counter!("personhog_leader_fence_lane_choices_total", "choice" => choice).increment(0);
+ }
for outcome in [
"ok",
"error",
@@ -1776,8 +2156,16 @@ pub fn preregister_fencing_metrics(partitions: u32) {
"partition" => p.clone()
)
.increment(0);
- counter!("personhog_leader_produce_fenced_total", "partition" => p).increment(0);
+ for cause in ["takeover", "heal"] {
+ counter!(
+ "personhog_leader_produce_fenced_total",
+ "partition" => p.clone(),
+ "cause" => cause
+ )
+ .increment(0);
+ }
}
+ counter!("personhog_leader_fence_produce_bound_exceeded_total").increment(0);
// Histograms are deliberately absent: the Prometheus exporter
// renders one only once it has a sample, so there is nothing a
// startup call can materialize.
@@ -1844,6 +2232,7 @@ pub async fn heal_fence(
if lost_standing || fenced.holds(partition) || inflight.is_fenced(partition) {
return Ok(HealOutcome::Intact);
}
+ fenced.expect_self_fence(partition);
let taken = match fenced.acquire_installed(partition).await {
Ok(taken) => taken,
Err(e) => {
@@ -1942,6 +2331,18 @@ mod tests {
);
}
+ #[test]
+ fn a_write_takes_the_lane_that_committed_longest_ago() {
+ let lane = |committing, last_commit_end| LaneState {
+ committing,
+ 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);
+ }
+
/// A condemn reason absent from the preregistration list first
/// appears as a new series mid-incident instead of rising from zero.
#[test]
diff --git a/rust/personhog-leader/src/inflight.rs b/rust/personhog-leader/src/inflight.rs
index 2f80f9de4059..01d3cd946492 100644
--- a/rust/personhog-leader/src/inflight.rs
+++ b/rust/personhog-leader/src/inflight.rs
@@ -19,10 +19,10 @@ use dashmap::{DashMap, DashSet};
/// stale view — accepting it would advance the Kafka HWM past the point
/// warming snapshots, silently losing the write from the new owner.
///
-/// Callers obtain a guard via `begin(partition)` and drop it when the
-/// handler completes; the handoff protocol fences the partition, then
-/// calls `wait_until_empty(partition)` to block until all inflight
-/// handlers have returned.
+/// Callers obtain a guard via `begin(partition)` and drop it once the
+/// write's outcome is known; the handoff protocol fences the partition,
+/// then calls `wait_until_empty(partition)` to block until every inflight
+/// write has resolved.
#[derive(Default)]
pub struct InflightTracker {
partitions: DashMap<u32, Arc<AtomicUsize>>,
diff --git a/rust/personhog-leader/src/lib.rs b/rust/personhog-leader/src/lib.rs
index c4d724e94fcb..f2de61a2ae30 100644
--- a/rust/personhog-leader/src/lib.rs
+++ b/rust/personhog-leader/src/lib.rs
@@ -8,6 +8,7 @@ pub mod inflight;
pub mod kafka;
pub mod person_update;
pub mod pg;
+pub mod producer_stats;
pub mod recovery;
pub mod service;
pub mod settle;
diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rs
index ea4d0737b74c..1269e0a1f4da 100644
--- a/rust/personhog-leader/src/main.rs
+++ b/rust/personhog-leader/src/main.rs
@@ -211,6 +211,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Matcher::Full("personhog_leader_fallback_pool_acquire_ms".into()),
WRITE_PATH_LATENCY_BUCKETS_MS,
),
+ (
+ Matcher::Full("personhog_leader_fenced_producer_window_ms".into()),
+ WRITE_PATH_LATENCY_BUCKETS_MS,
+ ),
(
Matcher::Full("grpc_server_request_duration_ms".into()),
WRITE_PATH_LATENCY_BUCKETS_MS,
@@ -398,9 +402,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// shared one: its writes must resolve inside the lease runway.
let fencing_kafka = common_kafka::config::KafkaConfig {
kafka_message_timeout_ms: config.fencing_message_timeout().as_millis() as u32,
- // One producer per owned partition, so the shared producer's
- // queue limits are an aggregate to divide rather than a
- // per-producer figure to copy.
+ // One producer per lane per owned partition, so the shared
+ // producer's queue limits are an aggregate to divide rather
+ // than a per-producer figure to copy.
kafka_producer_queue_mib: config.fencing_queue_mib(num_partitions),
kafka_producer_queue_messages: config.fencing_queue_messages(num_partitions),
..config.kafka.clone()
@@ -415,6 +419,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
window: Duration::from_millis(config.fencing_window_ms),
window_max_writes: config.fencing_window_max_writes,
settle_budget: config.fencing_settle_budget(),
+ lanes: config.fencing_lanes,
})
.with_repair_nudge(repair_nudge),
))
diff --git a/rust/personhog-leader/src/producer_stats.rs b/rust/personhog-leader/src/producer_stats.rs
new file mode 100644
index 000000000000..2498fe78145b
--- /dev/null
+++ b/rust/personhog-leader/src/producer_stats.rs
@@ -0,0 +1,178 @@
+//! librdkafka's statistics from the fenced changelog producers, exported
+//! as metrics so a slow produce can be split between the socket, the
+//! broker, and the client's own queues.
+
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
+
+use metrics::{counter, histogram};
+use rdkafka::client::ClientContext;
+use rdkafka::statistics::{Broker, Statistics, Window};
+
+const WINDOW_MS: &str = "personhog_leader_fenced_producer_window_ms";
+const REQUESTS_TOTAL: &str = "personhog_leader_fenced_producer_requests_total";
+const BROKER_EVENTS_TOTAL: &str = "personhog_leader_fenced_producer_broker_events_total";
+
+/// Consumes the statistics callbacks of one fenced producer. The counters
+/// in a callback are cumulative for the client's lifetime, so the context
+/// keeps the last values and reports the deltas.
+#[derive(Default)]
+pub struct FencedProducerContext {
+ last: Mutex<HashMap<String, i64>>,
+}
+
+impl ClientContext for FencedProducerContext {
+ fn stats(&self, stats: Statistics) {
+ let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner());
+ for broker in stats.brokers.values() {
+ let node: Arc<str> = Arc::from(broker_label(broker));
+ record_window(&node, "rtt", broker.rtt.as_ref(), 1000.0);
+ record_window(&node, "throttle", broker.throttle.as_ref(), 1.0);
+ record_window(&node, "int_latency", broker.int_latency.as_ref(), 1000.0);
+ record_window(
+ &node,
+ "outbuf_latency",
+ broker.outbuf_latency.as_ref(),
+ 1000.0,
+ );
+ for (request, delta) in request_deltas(&mut last, broker) {
+ counter!(REQUESTS_TOTAL, "broker" => node.clone(), "type" => request)
+ .increment(delta);
+ }
+ for (event, delta) in event_deltas(&mut last, broker) {
+ counter!(BROKER_EVENTS_TOTAL, "broker" => node.clone(), "event" => event)
+ .increment(delta);
+ }
+ }
+ }
+}
+
+/// The node id of a real broker, the logical name of a coordinator
+/// connection, which is where the transaction requests are counted, or
+/// one bucket for the bootstrap addresses.
+fn broker_label(broker: &Broker) -> String {
+ if broker.nodeid >= 0 {
+ broker.nodeid.to_string()
+ } else if matches!(broker.name.as_str(), "GroupCoordinator" | "TxnCoordinator") {
+ broker.name.clone()
+ } else {
+ "bootstrap".to_string()
+ }
+}
+
+/// One window's average and maximum, in milliseconds. librdkafka reports
+/// latencies in microseconds and throttling in milliseconds.
+fn record_window(node: &Arc<str>, window: &'static str, stats: Option<&Window>, per_ms: f64) {
+ let Some(stats) = stats else {
+ return;
+ };
+ if stats.cnt == 0 {
+ return;
+ }
+ for (agg, value) in [("avg", stats.avg), ("max", stats.max)] {
+ histogram!(WINDOW_MS, "broker" => node.clone(), "window" => window, "agg" => agg)
+ .record(value as f64 / per_ms);
+ }
+}
+
+/// Requests sent to the broker since the last callback, by request type.
+fn request_deltas(last: &mut HashMap<String, i64>, broker: &Broker) -> Vec<(Arc<str>, u64)> {
+ let mut deltas: Vec<(Arc<str>, u64)> = broker
+ .req
+ .iter()
+ .filter_map(|(request, &count)| {
+ let delta = advance(last, format!("{}/req/{request}", broker.name), count);
+ (delta > 0).then(|| (Arc::from(request.as_str()), delta))
+ })
+ .collect();
+ deltas.sort();
+ deltas
+}
+
+/// Retries, timeouts, errors, and disconnects since the last callback.
+fn event_deltas(last: &mut HashMap<String, i64>, broker: &Broker) -> Vec<(&'static str, u64)> {
+ [
+ ("tx_retry", broker.txretries as i64),
+ ("req_timeout", broker.req_timeouts as i64),
+ ("tx_error", broker.txerrs as i64),
+ ("rx_error", broker.rxerrs as i64),
+ ("disconnect", broker.disconnects.unwrap_or(0)),
+ ]
+ .into_iter()
+ .filter_map(|(event, count)| {
+ let delta = advance(last, format!("{}/event/{event}", broker.name), count);
+ (delta > 0).then_some((event, delta))
+ })
+ .collect()
+}
+
+/// The increase of a cumulative counter since its last value.
+fn advance(last: &mut HashMap<String, i64>, key: String, current: i64) -> u64 {
+ let previous = last.insert(key, current).unwrap_or(0);
+ current.saturating_sub(previous).max(0) as u64
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn broker(nodeid: i32, produce: i64, retries: u64) -> Broker {
+ Broker {
+ name: format!("broker-{nodeid}"),
+ nodeid,
+ req: HashMap::from([("Produce".to_string(), produce)]),
+ txretries: retries,
+ ..Broker::default()
+ }
+ }
+
+ #[test]
+ fn deltas_report_only_the_increase_since_the_last_callback() {
+ let mut last = HashMap::new();
+ assert_eq!(
+ request_deltas(&mut last, &broker(1, 10, 2)),
+ vec![(Arc::from("Produce"), 10)]
+ );
+ assert_eq!(
+ event_deltas(&mut last, &broker(1, 10, 2)),
+ vec![("tx_retry", 2)]
+ );
+ assert_eq!(
+ request_deltas(&mut last, &broker(1, 13, 2)),
+ vec![(Arc::from("Produce"), 3)]
+ );
+ assert!(event_deltas(&mut last, &broker(1, 13, 2)).is_empty());
+ }
+
+ #[test]
+ fn coordinator_connections_are_labeled_by_name() {
+ assert_eq!(broker_label(&broker(2, 0, 0)), "2");
+ let coordinator = Broker {
+ name: "TxnCoordinator".to_string(),
+ nodeid: -1,
+ ..Broker::default()
+ };
+ assert_eq!(broker_label(&coordinator), "TxnCoordinator");
+ for name in [
+ "ssl://broker.example:9096/bootstrap",
+ "ssl://TxnCoordinator.example:9096/bootstrap",
+ ] {
+ let bootstrap = Broker {
+ name: name.to_string(),
+ nodeid: -1,
+ ..Broker::default()
+ };
+ assert_eq!(broker_label(&bootstrap), "bootstrap", "{name}");
+ }
+ }
+
+ #[test]
+ fn brokers_keep_separate_counters() {
+ let mut last = HashMap::new();
+ request_deltas(&mut last, &broker(1, 10, 0));
+ assert_eq!(
+ request_deltas(&mut last, &broker(2, 4, 0)),
+ vec![(Arc::from("Produce"), 4)]
+ );
+ }
+}
diff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rs
index 13c2fbd5f083..c814bfa278c6 100644
--- a/rust/personhog-leader/src/service.rs
+++ b/rust/personhog-leader/src/service.rs
@@ -12,7 +12,7 @@ use personhog_proto::personhog::types::v1::{
SealedSourceSnapshot, UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,
};
use rdkafka::producer::FutureProducer;
-use tokio::sync::Mutex;
+use tokio::sync::{Mutex, OwnedMutexGuard};
use tonic::{Request, Response, Status};
use uuid::Uuid;
@@ -29,7 +29,7 @@ use crate::fence::{
fenced_status, semantic_refusal, target_mark_status, FenceHealer, FenceMap, FenceState,
};
use crate::fencing::{FencedChangelogProducers, FencedProduceError};
-use crate::inflight::InflightTracker;
+use crate::inflight::{InflightGuard, InflightTracker};
use crate::kafka::produce_person_changelog;
use crate::person_update::{apply_property_updates, compute_event_property_updates};
use crate::pg::{load_person_from_pg, PgFallback};
@@ -75,14 +75,33 @@ impl PropertySizeLimits {
}
}
+/// Lands a document in the changelog and then the cache, as its own task,
+/// so a handler dropped by its client cannot leave a record in flight
+/// without the person lock or committed without the cache update.
+struct Committer {
+ cache: Arc<PartitionedCache>,
+ dirty_index: Arc<DirtyIndex>,
+ emitted_versions: Arc<EmittedVersions>,
+ producer: FutureProducer<KafkaContext>,
+ changelog_topic: String,
+ fenced: Option<Arc<FencedChangelogProducers>>,
+}
+
+/// A committed document, with the locks the handler took for it, so the
+/// handler keeps them until it is done with the document.
+struct Committed {
+ proto: Person,
+ _lock: OwnedMutexGuard<()>,
+ _inflight: InflightGuard,
+}
+
pub struct PersonHogLeaderService {
+ committer: Arc<Committer>,
cache: Arc<PartitionedCache>,
/// Per-key locks to serialize concurrent updates for the same person.
/// Prevents lost updates from concurrent get -> compute -> produce -> put
/// sequences, and thundering herd on PG fallback.
locks: Arc<DashMap<PersonCacheKey, Arc<Mutex<()>>>>,
- producer: FutureProducer<KafkaContext>,
- changelog_topic: String,
/// Read-only PG fallback (pool + the table it reads) for cache miss.
fallback: Option<PgFallback>,
/// Per-partition inflight counter used to drive the handoff drain phase.
@@ -111,9 +130,6 @@ pub struct PersonHogLeaderService {
/// config for the full policy): at this many live fences, FencePerson
/// sheds new fences with RESOURCE_EXHAUSTED.
fence_map_max_entries: usize,
- /// Present when broker-enforced epoch fencing is on; the write
- /// path produces through the partition's transaction window.
- fenced: Option<Arc<FencedChangelogProducers>>,
/// This pod's claim to serve, consulted before answering a strong
/// read. Present only when lease-gated reads are enabled.
authority: Option<Arc<AuthorityClock>>,
@@ -207,11 +223,18 @@ impl PersonHogLeaderService {
authority: Option<Arc<AuthorityClock>>,
emitted_versions: Arc<EmittedVersions>,
) -> Self {
+ let committer = Arc::new(Committer {
+ cache: Arc::clone(&cache),
+ dirty_index: Arc::clone(&dirty_index),
+ emitted_versions: Arc::clone(&emitted_versions),
+ producer,
+ changelog_topic,
+ fenced,
+ });
Self {
+ committer,
cache,
locks,
- producer,
- changelog_topic,
fence_healer: fallback
.as_ref()
.map(|f| Arc::new(FenceHealer::new(f.clone(), Arc::clone(&fences)))),
@@ -223,7 +246,6 @@ impl PersonHogLeaderService {
size_limits,
warnings,
fences,
- fenced,
authority,
emitted_versions,
fence_map_max_entries: DEFAULT_FENCE_MAP_MAX_ENTRIES,
@@ -476,17 +498,18 @@ impl PersonHogLeaderService {
}
/// The shared tail of every document write: refuse unapplyable records,
- /// produce to Kafka first, then dirty-mark and update the cache — so
- /// readers only ever see durably committed state. The mark precedes the
- /// cache insert: a reader that misses the cache in the gap sees the
- /// mark and recovers this exact record from the changelog. Assumes the
- /// caller holds the per-key lock.
+ /// produce to Kafka first, then dirty-mark and update the cache, so
+ /// readers only ever see durably committed state. The person lock and
+ /// the in-flight slot travel with the commit and come back with the
+ /// document.
async fn commit_document(
&self,
partition: u32,
cache_key: &PersonCacheKey,
person: CachedPerson,
- ) -> Result<Person, Status> {
+ lock: OwnedMutexGuard<()>,
+ inflight: InflightGuard,
+ ) -> Result<Committed, Status> {
// A record the writer cannot bind must never reach the changelog —
// no consumer downstream can apply or repair it.
if let Err(reason) = assert_writeable(&person) {
@@ -515,9 +538,46 @@ impl PersonHogLeaderService {
self.check_authority(partition)?;
// From here the record may reach the changelog whatever happens
- // to this request — including the request simply ceasing to exist
- // when the client's deadline expires. The guard is what makes the
- // version un-reusable in that case.
+ // to this request, including the request ceasing to exist when
+ // the client's deadline expires, so the rest runs as its own
+ // task: it finishes under the person lock, lands the record in
+ // the cache, and only then lets the lock go.
+ let committer = Arc::clone(&self.committer);
+ let (team_id, person_id) = (cache_key.team_id, cache_key.person_id);
+ let cache_key = cache_key.clone();
+ tokio::spawn(async move {
+ committer
+ .commit(partition, cache_key, person, proto, lock, inflight)
+ .await
+ })
+ .await
+ .unwrap_or_else(|e| {
+ // The floor stays raised through the unwind, so the version
+ // is spent; what is lost is only the outcome.
+ tracing::error!(
+ team_id,
+ person_id,
+ partition,
+ error = %e,
+ "commit task ended without reporting an outcome"
+ );
+ Err(Status::internal(format!("commit task: {e}")))
+ })
+ }
+}
+
+impl Committer {
+ async fn commit(
+ &self,
+ partition: u32,
+ cache_key: PersonCacheKey,
+ person: CachedPerson,
+ proto: Person,
+ lock: OwnedMutexGuard<()>,
+ inflight: InflightGuard,
+ ) -> Result<Committed, Status> {
+ // The guard is what makes the version un-reusable if this task
+ // never reports.
let mut emitted = EmittedVersionGuard::new(
Arc::clone(&self.emitted_versions),
partition,
@@ -704,13 +764,19 @@ impl PersonHogLeaderService {
is_deleted: person.is_deleted,
},
);
- self.cache.put(partition, cache_key.clone(), person);
+ self.cache.put(partition, cache_key, person);
// The cache carries the version now, so the floor has nothing
// left to say.
emitted.resolved();
- Ok(proto)
+ Ok(Committed {
+ proto,
+ _lock: lock,
+ _inflight: inflight,
+ })
}
+}
+impl PersonHogLeaderService {
/// The write path's fence conditional: an in-memory lookup and nothing
/// else. The map is authoritative here — a fence that outlives its op
/// is not the leader's to detect, because the op being unfinished is
@@ -957,10 +1023,9 @@ impl PersonHogLeader for PersonHogLeaderService {
// — the frozen state stays the latest until cutover. The handoff
// protocol waits for the per-partition inflight count to drop to
// zero before advancing; combined with sync-acked produces, a zero
- // count implies every acked write is durable in Kafka. Using a
- // non-`_` prefixed binding so the RAII guard is held for the full
- // handler lifetime (see the `let_underscore_drop` lint).
- let Some(_inflight_guard) = self.inflight.try_begin(partition) else {
+ // count implies every acked write is durable in Kafka. The guard
+ // moves into the commit, which holds it through the outcome.
+ let Some(inflight_guard) = self.inflight.try_begin(partition) else {
return Err(Status::failed_precondition(format!(
"partition {partition} is fenced for handoff; writes are rejected"
)));
@@ -1031,7 +1096,7 @@ impl PersonHogLeader for PersonHogLeaderService {
.value()
.clone();
let lock_wait = std::time::Instant::now();
- let _guard = mutex.lock().await;
+ let guard = mutex.lock_owned().await;
histogram!("personhog_leader_person_lock_wait_ms")
.record(lock_wait.elapsed().as_secs_f64() * 1000.0);
@@ -1271,13 +1336,13 @@ impl PersonHogLeader for PersonHogLeaderService {
approx_bytes,
};
- let proto = self
- .commit_document(partition, &cache_key, updated_person)
+ let committed = self
+ .commit_document(partition, &cache_key, updated_person, guard, inflight_guard)
.await?;
counter!("personhog_leader_updates_total", "outcome" => "updated").increment(1);
Ok(Response::new(UpdatePersonPropertiesResponse {
- person: Some(proto),
+ person: Some(committed.proto),
updated: true,
}))
}
@@ -1299,7 +1364,7 @@ impl PersonHogLeader for PersonHogLeaderService {
));
}
- let Some(_inflight_guard) = self.inflight.try_begin(partition) else {
+ let Some(inflight_guard) = self.inflight.try_begin(partition) else {
return Err(Status::failed_precondition(format!(
"partition {partition} is fenced for handoff; writes are rejected"
)));
@@ -1333,7 +1398,7 @@ impl PersonHogLeader for PersonHogLeaderService {
.value()
.clone();
let lock_wait = std::time::Instant::now();
- let _guard = mutex.lock().await;
+ let guard = mutex.lock_owned().await;
histogram!("personhog_leader_person_lock_wait_ms")
.record(lock_wait.elapsed().as_secs_f64() * 1000.0);
@@ -1610,15 +1675,15 @@ impl PersonHogLeader for PersonHogLeaderService {
approx_bytes,
};
- let proto = self
- .commit_document(partition, &cache_key, folded_person)
+ let committed = self
+ .commit_document(partition, &cache_key, folded_person, guard, inflight_guard)
.await?;
counter!("personhog_leader_folds_total", "outcome" => fold_outcome).increment(1);
self.authoritative_ok(
partition,
FoldPersonDocumentResponse {
- person: Some(proto),
+ person: Some(committed.proto),
},
)
}
diff --git a/rust/personhog-leader/src/service/lifecycle.rs b/rust/personhog-leader/src/service/lifecycle.rs
index 194135d67578..0b1d39a59270 100644
--- a/rust/personhog-leader/src/service/lifecycle.rs
+++ b/rust/personhog-leader/src/service/lifecycle.rs
@@ -141,7 +141,7 @@ impl PersonHogLeaderService {
.value()
.clone();
let lock_started = Instant::now();
- let _guard = mutex.lock().await;
+ let guard = mutex.lock_owned().await;
record_release_phase("lock_wait", lock_started);
// Releasing another op's fence would break that op's seal.
@@ -247,9 +247,14 @@ impl PersonHogLeaderService {
approx_bytes: approx_person_bytes(2),
};
let produce_started = Instant::now();
- let committed = self.commit_document(partition, &cache_key, death).await;
+ // The RPC's own guard admitted the batch; this one rides the
+ // commit through its outcome.
+ let inflight = self.inflight.begin(partition);
+ let committed = self
+ .commit_document(partition, &cache_key, death, guard, inflight)
+ .await;
record_release_phase("produce", produce_started);
- committed?;
+ let _committed = committed?;
// The death document stays cached while its mark stands, answering
// not-found from memory; the prune-time settle drops it once the
// writer confirms, and PG answers from then on.
diff --git a/rust/personhog-leader/tests/commit_integration.rs b/rust/personhog-leader/tests/commit_integration.rs
new file mode 100644
index 000000000000..3d3c74c6fff3
--- /dev/null
+++ b/rust/personhog-leader/tests/commit_integration.rs
@@ -0,0 +1,223 @@
+//! The write path's commit outlives the handler that started it.
+
+mod common;
+
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use common::{
+ create_local_kafka_producer, seed_person, test_cached_person, test_kafka_config, test_recovery,
+ unique_team_id, KAFKA_BOOTSTRAP,
+};
+use dashmap::DashMap;
+use personhog_common::partitioning::partition_for_person;
+use personhog_leader::cache::{DirtyIndex, PartitionedCache, PersonCacheKey};
+use personhog_leader::emitted::EmittedVersions;
+use personhog_leader::fencing::{FencedChangelogProducers, FencedProducerConfig};
+use personhog_leader::inflight::InflightTracker;
+use personhog_leader::service::{PersonHogLeaderService, PropertySizeLimits};
+use personhog_leader::warnings::WarningsProducer;
+use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeader;
+use personhog_proto::personhog::types::v1::{
+ UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,
+};
+use tokio::sync::Mutex;
+use tokio::task::JoinHandle;
+use tonic::{Request, Response, Status};
+
+/// One partition, so the auto-created topic holds the person's partition.
+const NUM_PARTITIONS: u32 = 1;
+
+/// Two lanes, so a write that ignored the person lock could take the
+/// other lane.
+const LANES: usize = 2;
+
+/// Comfortably above the test config's 5s `message.timeout.ms`, which
+/// librdkafka requires the broker bound to cover.
+const BROKER_TXN_TIMEOUT: Duration = Duration::from_secs(30);
+
+type Write = JoinHandle<Result<Response<UpdatePersonPropertiesResponse>, Status>>;
+
+struct Harness {
+ service: Arc<PersonHogLeaderService>,
+ fenced: Arc<FencedChangelogProducers>,
+ cache: Arc<PartitionedCache>,
+ locks: Arc<DashMap<PersonCacheKey, Arc<Mutex<()>>>>,
+ key: PersonCacheKey,
+ partition: u32,
+}
+
+/// A leader service over real fenced producers, with windows the test
+/// closes itself so nothing here depends on a timer.
+async fn start_harness() -> Harness {
+ let topic = format!("commit_test_{}", uuid::Uuid::new_v4().simple());
+ let mut kafka = test_kafka_config();
+ kafka.kafka_hosts = KAFKA_BOOTSTRAP.to_string();
+ let fenced = Arc::new(FencedChangelogProducers::new(FencedProducerConfig {
+ kafka,
+ topic: topic.clone(),
+ init_timeout: Duration::from_secs(10),
+ commit_timeout: Duration::from_secs(10),
+ broker_txn_timeout: BROKER_TXN_TIMEOUT,
+ window: Duration::from_secs(20),
+ window_max_writes: 32,
+ settle_budget: Duration::from_secs(5),
+ lanes: LANES,
+ }));
+
+ let mut seed = test_cached_person();
+ seed.team_id = unique_team_id();
+ let key = PersonCacheKey {
+ team_id: seed.team_id,
+ person_id: seed.id,
+ };
+ let partition = partition_for_person(key.team_id, key.person_id, NUM_PARTITIONS);
+ fenced.acquire(partition).await.expect("acquire the fence");
+
+ let cache = Arc::new(PartitionedCache::new(1 << 20));
+ cache.create_partition(partition);
+ seed_person(&cache, partition, seed);
+ let locks = Arc::new(DashMap::new());
+ let producer = create_local_kafka_producer().await;
+ let service = Arc::new(PersonHogLeaderService::new(
+ Arc::clone(&cache),
+ producer.clone(),
+ topic,
+ None,
+ Arc::clone(&locks),
+ Arc::new(InflightTracker::new()),
+ NUM_PARTITIONS,
+ Arc::new(DirtyIndex::new(1_000_000)),
+ test_recovery(KAFKA_BOOTSTRAP),
+ PropertySizeLimits::new(655360, 524288),
+ WarningsProducer::new(producer, "clickhouse_ingestion_warnings".to_string()),
+ Arc::new(DashMap::new()),
+ Some(Arc::clone(&fenced)),
+ None,
+ Arc::new(EmittedVersions::new(1_000_000)),
+ ));
+ Harness {
+ service,
+ fenced,
+ cache,
+ locks,
+ key,
+ partition,
+ }
+}
+
+impl Harness {
+ fn spawn_write(&self, properties: serde_json::Value) -> Write {
+ let mut request = Request::new(UpdatePersonPropertiesRequest {
+ force_update: false,
+ team_id: self.key.team_id,
+ person_id: self.key.person_id,
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(&properties).unwrap(),
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ is_identified: None,
+ last_seen_at: None,
+ });
+ request
+ .metadata_mut()
+ .insert("x-partition", self.partition.to_string().parse().unwrap());
+ let service = Arc::clone(&self.service);
+ tokio::spawn(async move { service.update_person_properties(request).await })
+ }
+
+ fn waiting_writers(&self) -> usize {
+ (0..LANES)
+ .map(|lane| self.fenced.waiting_writers_for_test(self.partition, lane))
+ .sum()
+ }
+
+ /// Close whichever lane holds the open window.
+ fn close_windows(&self) {
+ for lane in 0..LANES {
+ self.fenced.close_window_for_test(self.partition, lane);
+ }
+ }
+
+ fn person_lock_is_held(&self) -> bool {
+ self.locks
+ .get(&self.key)
+ .expect("the write took the person lock")
+ .try_lock()
+ .is_err()
+ }
+
+ /// Wait until the write's record is in a window awaiting the commit,
+ /// the point a client deadline interrupts.
+ async fn wait_for_ack_wait(&self, write: &mut Write) {
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while self.waiting_writers() == 0 {
+ if write.is_finished() {
+ let outcome = write.await;
+ panic!("the write ended before its ack wait: {outcome:?}");
+ }
+ assert!(
+ Instant::now() < deadline,
+ "the write never reached its ack wait"
+ );
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+ }
+}
+
+async fn wait_until(what: &str, condition: impl Fn() -> bool) {
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while !condition() {
+ assert!(Instant::now() < deadline, "{what}");
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+}
+
+/// A write whose client gives up between the send and the ack keeps the
+/// person lock until its outcome, lands in the cache, and the next write
+/// for the person builds on it rather than on the state before it.
+#[tokio::test]
+async fn a_cancelled_handlers_write_keeps_the_lock_and_lands() {
+ let harness = start_harness().await;
+
+ let mut first = harness.spawn_write(serde_json::json!({"a": 1}));
+ harness.wait_for_ack_wait(&mut first).await;
+ first.abort();
+ assert!(first.await.unwrap_err().is_cancelled());
+ assert!(
+ harness.person_lock_is_held(),
+ "the person lock must stay held by the commit after its handler is cancelled"
+ );
+
+ // Started while the first write's window is still open: it can only
+ // get past the lock once that window has resolved.
+ let mut second = harness.spawn_write(serde_json::json!({"b": 2}));
+ harness.close_windows();
+ wait_until("the cancelled write must land in the cache", || {
+ harness
+ .cache
+ .peek(harness.partition, &harness.key)
+ .is_some_and(|person| person.version == 2)
+ })
+ .await;
+
+ harness.wait_for_ack_wait(&mut second).await;
+ harness.close_windows();
+ let second = second
+ .await
+ .expect("the write task must not panic")
+ .expect("the write after the cancelled one succeeds")
+ .into_inner()
+ .person
+ .expect("the response carries the person");
+ let properties: serde_json::Value = serde_json::from_slice(&second.properties).unwrap();
+ assert_eq!(
+ second.version, 3,
+ "versions advance past the cancelled write's"
+ );
+ assert_eq!(
+ properties["a"], 1,
+ "the cancelled write's property must be in the next document"
+ );
+ assert_eq!(properties["b"], 2);
+}
diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rs
index ab5e6dd4c001..62b036e994c0 100644
--- a/rust/personhog-leader/tests/common/mod.rs
+++ b/rust/personhog-leader/tests/common/mod.rs
@@ -666,6 +666,7 @@ pub fn fenced_producers_for(topic: &str) -> personhog_leader::fencing::FencedCha
broker_txn_timeout: BROKER_TXN_TIMEOUT,
window: Duration::from_millis(5),
window_max_writes: 32,
+ lanes: 1,
settle_budget: Duration::from_secs(5),
},
)
diff --git a/rust/personhog-leader/tests/fencing_integration.rs b/rust/personhog-leader/tests/fencing_integration.rs
index af1a0ff12fe7..e77fd60f6c94 100644
--- a/rust/personhog-leader/tests/fencing_integration.rs
+++ b/rust/personhog-leader/tests/fencing_integration.rs
@@ -73,10 +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_and_fill(
+fn fenced_producers_with(
topic: &str,
window: Duration,
window_max_writes: usize,
+ lanes: usize,
) -> FencedChangelogProducers {
let mut kafka = test_kafka_config();
kafka.kafka_hosts = KAFKA_BOOTSTRAP.to_string();
@@ -89,26 +90,12 @@ fn fenced_producers_with_window_and_fill(
window,
window_max_writes,
settle_budget: window + Duration::from_secs(5),
+ lanes,
})
}
-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();
- FencedChangelogProducers::new(FencedProducerConfig {
- kafka,
- topic: topic.to_string(),
- init_timeout: Duration::from_secs(10),
- 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),
- })
+fn fenced_producers(topic: &str, lanes: usize) -> FencedChangelogProducers {
+ fenced_producers_with(topic, Duration::from_millis(5), 32, lanes)
}
/// The prepared path must fence exactly as the cold path does: a
@@ -119,14 +106,14 @@ fn fenced_producers(topic: &str) -> FencedChangelogProducers {
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);
+ let first = fenced_producers(&topic, 1);
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);
+ let second = fenced_producers(&topic, 1);
second.preconnect(0).await;
assert!(second.has_prepared(0), "preconnect parks a connection");
// The property the phase split exists for: the parked connection has
@@ -158,7 +145,7 @@ async fn a_prepared_connection_still_fences_the_previous_owner() {
#[tokio::test]
async fn the_sweep_discards_parked_connections() {
let topic = format!("fence_prepared_{}", uuid::Uuid::new_v4().simple());
- let producers = fenced_producers(&topic);
+ let producers = fenced_producers(&topic, 1);
producers.preconnect(6).await;
assert!(producers.has_prepared(6), "preconnect parks a connection");
@@ -176,7 +163,7 @@ async fn the_sweep_discards_parked_connections() {
#[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);
+ let producers = fenced_producers(&topic, 1);
producers.preconnect(5).await;
assert!(producers.has_prepared(5), "preconnect parks a connection");
producers.release(5);
@@ -194,7 +181,7 @@ async fn a_released_partition_discards_its_prepared_connection() {
#[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 producers = Arc::new(fenced_producers(&topic, 1));
let calls: Vec<_> = (0..20)
.map(|_| {
@@ -233,6 +220,7 @@ async fn a_failed_preconnect_releases_its_claim() {
broker_txn_timeout: BROKER_TXN_TIMEOUT,
window: Duration::from_millis(5),
window_max_writes: 32,
+ lanes: 1,
settle_budget: Duration::from_secs(5),
});
@@ -265,6 +253,7 @@ async fn a_stale_dials_failure_leaves_the_replacements_claim() {
broker_txn_timeout: BROKER_TXN_TIMEOUT,
window: Duration::from_millis(5),
window_max_writes: 32,
+ lanes: 1,
settle_budget: Duration::from_secs(5),
}));
@@ -295,7 +284,7 @@ async fn a_stale_dials_failure_leaves_the_replacements_claim() {
#[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);
+ let producers = fenced_producers(&topic, 1);
producers.stage_connecting_for_test(1, Duration::from_secs(60));
producers.stage_connecting_for_test(2, Duration::from_secs(0));
@@ -326,14 +315,14 @@ async fn second_acquisition_fences_the_first_producer() {
tokio::time::timeout(Duration::from_secs(60), async {
let topic = format!("fence_test_{}", uuid::Uuid::new_v4().simple());
- let first = fenced_producers(&topic);
+ let first = fenced_producers(&topic, 1);
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);
+ let second = fenced_producers(&topic, 1);
second.acquire(0).await.expect("second owner acquires");
second
.produce(0, &test_person(2))
@@ -349,13 +338,218 @@ async fn second_acquisition_fences_the_first_producer() {
.expect("writes parked forever — a window_closed wakeup was lost");
}
+/// Successive writes on a partition rotate across its lanes, so the
+/// second does not wait on the coordinator finishing the first's commit
+/// on the same transactional id.
+#[tokio::test]
+async fn successive_writes_rotate_across_lanes() {
+ tokio::time::timeout(Duration::from_secs(60), async {
+ let topic = format!("fence_test_{}", uuid::Uuid::new_v4().simple());
+ let producers = fenced_producers(&topic, 2);
+ producers.acquire(0).await.expect("acquires");
+ producers
+ .produce(0, &test_person(1))
+ .await
+ .expect("first write");
+ producers
+ .produce(0, &test_person(2))
+ .await
+ .expect("second write");
+ let marks = producers.lane_commit_marks_for_test(0);
+ assert_eq!(marks.len(), 2);
+ assert!(
+ marks.iter().all(|mark| *mark > 0),
+ "each write committed on its own lane: {marks:?}"
+ );
+ })
+ .await
+ .expect("writes parked forever — a window_closed wakeup was lost");
+}
+
+/// A successor claims every lane's id, not only the first, so a
+/// predecessor's producer on a higher lane is fenced too, and one fenced
+/// lane takes the predecessor's whole set with it.
+#[tokio::test]
+async fn a_successor_fences_every_lane_of_the_predecessor() {
+ tokio::time::timeout(Duration::from_secs(60), async {
+ let topic = format!("fence_test_{}", uuid::Uuid::new_v4().simple());
+
+ let first = fenced_producers(&topic, 2);
+ first.acquire(0).await.expect("first owner acquires");
+ first
+ .produce_on_lane_for_test(0, 1, &test_person(1))
+ .await
+ .expect("first owner produces on lane 1 while unfenced");
+
+ let second = fenced_producers(&topic, 2);
+ second.acquire(0).await.expect("second owner acquires");
+
+ match first.produce_on_lane_for_test(0, 1, &test_person(2)).await {
+ Err(FencedProduceError::Fenced)
+ | Err(FencedProduceError::FencedUncertain(_))
+ | Err(FencedProduceError::NotAcquired) => {}
+ other => panic!("the stale lane must be fenced, got {other:?}"),
+ }
+ assert!(
+ !first.holds(0),
+ "a fenced lane must give up the partition's whole set"
+ );
+ })
+ .await
+ .expect("writes parked forever — a window_closed wakeup was lost");
+}
+
+/// 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.
+#[tokio::test]
+async fn a_parked_writer_picks_again_when_it_wakes() {
+ let topic = format!("fence_repick_{}", 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);
+ producers.begin_committing_for_test(0, 1);
+ let write = {
+ let p = Arc::clone(&producers);
+ tokio::spawn(async move { p.produce(0, &test_person(1)).await })
+ };
+ // Neither lane has ever committed, so the tie parks the writer on
+ // lane 0.
+ 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 on lane 0");
+
+ // Lane 1 finishes first, so it is the lane idle longest when lane 0's
+ // finish wakes the writer.
+ producers.finish_committing_for_test(0, 1);
+ 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 must succeed");
+ let marks = producers.lane_commit_marks_for_test(0);
+ assert!(
+ marks[1] > marks[0],
+ "the woken writer must take the lane idle longest, not the one that woke it: {marks:?}"
+ );
+}
+
+/// Preconnect dials one connection per lane, so the acquire that follows
+/// pays only the init round trips.
+#[tokio::test]
+async fn preconnect_dials_every_lane() {
+ let topic = format!("fence_preconnect_lanes_{}", uuid::Uuid::new_v4().simple());
+ let producers = fenced_producers(&topic, 2);
+
+ producers.preconnect(0).await;
+ assert!(
+ producers.has_prepared(0),
+ "preconnect parks the connections"
+ );
+ assert_eq!(
+ producers.connect_attempts_for_test(),
+ 2,
+ "one dial per lane"
+ );
+
+ producers.acquire(0).await.expect("acquire the fence");
+ assert_eq!(
+ producers.connect_attempts_for_test(),
+ 2,
+ "a prepared acquire dials nothing"
+ );
+}
+
+/// A poisoned gate condemns its lane instead of taking every write on the
+/// partition down with a panic, so the partition heals like any other
+/// dead producer.
+#[tokio::test]
+async fn a_poisoned_gate_gives_up_the_partition() {
+ let topic = format!("fence_poisoned_gate_{}", uuid::Uuid::new_v4().simple());
+ let producers = fenced_producers(&topic, 2);
+ producers.acquire(0).await.expect("acquire the fence");
+
+ producers.poison_gate_for_test(0, 1);
+
+ match producers.produce(0, &test_person(1)).await {
+ Err(FencedProduceError::NotAcquired) => {}
+ other => panic!("a poisoned gate must answer as unowned, got {other:?}"),
+ }
+ assert!(
+ !producers.holds(0),
+ "a poisoned gate must stop the partition counting as fenced"
+ );
+}
+
+/// A write parked behind windows that never close is bounded, so a wedged
+/// lane cannot hold its lock and in-flight slot forever.
+#[tokio::test]
+async fn a_write_parked_forever_is_bounded() {
+ let topic = format!("fence_bound_{}", uuid::Uuid::new_v4().simple());
+ let mut kafka = test_kafka_config();
+ kafka.kafka_hosts = KAFKA_BOOTSTRAP.to_string();
+ let producers = FencedChangelogProducers::new(FencedProducerConfig {
+ kafka,
+ topic,
+ init_timeout: Duration::from_secs(10),
+ // Sizes the produce bound well under the test's own patience.
+ commit_timeout: Duration::from_millis(100),
+ broker_txn_timeout: BROKER_TXN_TIMEOUT,
+ window: Duration::from_millis(5),
+ window_max_writes: 32,
+ settle_budget: Duration::from_secs(5),
+ lanes: 1,
+ });
+ producers.acquire(0).await.expect("acquire the fence");
+
+ producers.begin_committing_for_test(0, 0);
+ let outcome = tokio::time::timeout(
+ Duration::from_secs(5),
+ producers.produce(0, &test_person(1)),
+ )
+ .await
+ .expect("the produce must return inside its bound");
+ match outcome {
+ Err(FencedProduceError::Indeterminate(_)) => {}
+ other => panic!("a bounded produce must report its outcome as unknown, got {other:?}"),
+ }
+ producers.finish_committing_for_test(0, 0);
+}
+
+/// A condemned lane above zero gives up the partition the same way lane
+/// zero does: the fence reports missing and writes answer as unowned.
+#[tokio::test]
+async fn a_condemned_lane_above_zero_gives_up_the_partition() {
+ let topic = format!("fence_condemned_lane_{}", uuid::Uuid::new_v4().simple());
+ let producers = fenced_producers(&topic, 2);
+ producers.acquire(0).await.expect("acquire the fence");
+
+ producers.condemn_for_test(0, 1);
+
+ assert!(
+ !producers.holds(0),
+ "a condemned lane must stop the partition counting as fenced"
+ );
+ match producers.produce(0, &test_person(1)).await {
+ Err(FencedProduceError::NotAcquired) => {}
+ other => panic!("a condemned lane must not answer as a live fence, got {other:?}"),
+ }
+}
+
/// Concurrent same-partition writes share a transaction window: both
/// succeed with distinct offsets, through one producer, without
/// serializing on per-write commits.
#[tokio::test]
async fn concurrent_writes_share_a_window() {
let topic = format!("fence_test_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers(&topic));
+ let producers = Arc::new(fenced_producers(&topic, 1));
producers.acquire(0).await.expect("acquire");
let a = {
@@ -377,11 +571,7 @@ async fn concurrent_writes_share_a_window() {
#[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,
- ));
+ let producers = Arc::new(fenced_producers_with(&topic, Duration::from_secs(60), 3, 1));
producers.acquire(0).await.expect("acquire");
let writes: Vec<_> = (1..=3i64)
@@ -412,7 +602,7 @@ async fn sustained_writes_across_window_boundaries() {
// failure.
tokio::time::timeout(Duration::from_secs(60), async {
let topic = format!("fence_test_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers(&topic));
+ let producers = Arc::new(fenced_producers(&topic, 1));
producers.acquire(0).await.expect("acquire");
let writes: Vec<_> = (0..200i64)
@@ -449,9 +639,11 @@ async fn a_committer_that_vanishes_leaves_the_outcome_in_doubt() {
let topic = format!("fence_orphan_{}", uuid::Uuid::new_v4().simple());
// A long window keeps the committer asleep, so the write is parked on
// an outcome that is still nobody's to report.
- let producers = Arc::new(fenced_producers_with_window(
+ let producers = Arc::new(fenced_producers_with(
&topic,
Duration::from_secs(30),
+ 32,
+ 1,
));
producers.acquire(0).await.expect("acquire the fence");
@@ -459,7 +651,13 @@ async fn a_committer_that_vanishes_leaves_the_outcome_in_doubt() {
let p = Arc::clone(&producers);
tokio::spawn(async move { p.produce(0, &test_person(1)).await })
};
- sleep(Duration::from_millis(300)).await;
+ tokio::time::timeout(Duration::from_secs(10), async {
+ while producers.waiting_writers_for_test(0, 0) == 0 {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("the write must be waiting on the window's outcome");
producers.abandon_waiters_for_test(0);
@@ -479,7 +677,7 @@ async fn a_committer_that_vanishes_leaves_the_outcome_in_doubt() {
#[tokio::test]
async fn a_cancelled_produce_does_not_wedge_the_partition() {
let topic = format!("fence_cancel_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers(&topic));
+ let producers = Arc::new(fenced_producers(&topic, 1));
producers.acquire(0).await.expect("acquire");
{
@@ -521,7 +719,7 @@ async fn a_successors_init_aborts_the_predecessors_open_window() {
// has taken the epoch, because "invisible while uncommitted" proves
// nothing. What has to be shown is that the record can never become
// visible once the successor owns the partition.
- let first = Arc::new(fenced_producers_with_window(&topic, Duration::from_secs(1)));
+ let first = Arc::new(fenced_producers_with(&topic, Duration::from_secs(1), 32, 1));
first.acquire(0).await.expect("first owner acquires");
{
let p = Arc::clone(&first);
@@ -535,7 +733,7 @@ async fn a_successors_init_aborts_the_predecessors_open_window() {
// Successor takes the partition before that window closes, as a
// warming new owner does.
- let second = fenced_producers(&topic);
+ let second = fenced_producers(&topic, 1);
second.acquire(0).await.expect("successor acquires");
// Now let the predecessor's committer run. This is the moment the
@@ -556,9 +754,11 @@ async fn a_successors_init_aborts_the_predecessors_open_window() {
// record arriving. Otherwise this test passes just as well when the
// send never left the client.
let control_topic = format!("fence_abort_control_{}", uuid::Uuid::new_v4().simple());
- let lone = Arc::new(fenced_producers_with_window(
+ let lone = Arc::new(fenced_producers_with(
&control_topic,
Duration::from_secs(1),
+ 32,
+ 1,
));
lone.acquire(0).await.expect("control owner acquires");
{
@@ -588,7 +788,7 @@ async fn a_successors_init_aborts_the_predecessors_open_window() {
#[tokio::test]
async fn a_fence_taken_for_an_unfinished_warm_is_given_back() {
let topic = format!("fence_guard_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers(&topic));
+ let producers = Arc::new(fenced_producers(&topic, 1));
{
producers.acquire(0).await.expect("acquire");
@@ -607,7 +807,7 @@ async fn a_fence_taken_for_an_unfinished_warm_is_given_back() {
#[tokio::test]
async fn a_completed_warm_keeps_its_fence() {
let topic = format!("fence_guard_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers(&topic));
+ let producers = Arc::new(fenced_producers(&topic, 1));
producers.acquire(0).await.expect("acquire");
FenceGuard::new(Arc::clone(&producers), 0, "warm").keep();
@@ -627,17 +827,17 @@ async fn a_completed_warm_keeps_its_fence() {
async fn a_condemnation_nudges_repair_once() {
let topic = format!("fence_repair_{}", uuid::Uuid::new_v4().simple());
let nudge = Arc::new(Notify::new());
- let producers = fenced_producers(&topic).with_repair_nudge(Arc::clone(&nudge));
+ let producers = fenced_producers(&topic, 1).with_repair_nudge(Arc::clone(&nudge));
producers.acquire(3).await.expect("acquire the fence");
- producers.condemn_for_test(3);
+ producers.condemn_for_test(3, 0);
tokio::time::timeout(Duration::from_secs(5), nudge.notified())
.await
.expect("a condemnation must nudge the repair pass");
// The permit was consumed above; a second condemnation of the same
// producer takes the unusable-swap early exit and stores no new one.
- producers.condemn_for_test(3);
+ producers.condemn_for_test(3, 0);
assert!(
tokio::time::timeout(Duration::from_millis(250), nudge.notified())
.await
@@ -659,14 +859,14 @@ async fn a_condemnation_nudges_repair_once() {
#[tokio::test]
async fn a_condemned_producer_stops_claiming_the_partition() {
let topic = format!("fence_condemned_{}", uuid::Uuid::new_v4().simple());
- let producers = fenced_producers(&topic);
+ let producers = fenced_producers(&topic, 1);
producers.acquire(0).await.expect("acquire the fence");
producers
.produce(0, &test_person(1))
.await
.expect("a healthy fence writes");
- producers.condemn_for_test(0);
+ producers.condemn_for_test(0, 0);
match producers.produce(0, &test_person(2)).await {
Err(FencedProduceError::NotAcquired) => {}
@@ -692,7 +892,7 @@ async fn a_condemned_producer_stops_claiming_the_partition() {
#[tokio::test]
async fn an_abandoned_guard_does_not_evict_its_replacement() {
let topic = format!("fence_guard_id_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers(&topic));
+ let producers = Arc::new(fenced_producers(&topic, 1));
producers.acquire(0).await.expect("first acquire");
// A warm takes the fence, then never finishes.
@@ -719,7 +919,7 @@ async fn an_abandoned_guard_does_not_evict_its_replacement() {
#[tokio::test]
async fn healing_retakes_a_fence_for_a_served_partition() {
let topic = format!("fence_heal_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers(&topic));
+ let producers = Arc::new(fenced_producers(&topic, 1));
let inflight = InflightTracker::new();
let clock = AuthorityClock::unclaimed();
clock.begin_session(Duration::from_secs(30), std::time::Instant::now());
@@ -753,7 +953,7 @@ async fn healing_without_standing_does_not_steal_the_epoch() {
let inflight = InflightTracker::new();
// The partition's real owner, holding a working fence.
- let owner = Arc::new(fenced_producers(&topic));
+ let owner = Arc::new(fenced_producers(&topic, 1));
owner.acquire(0).await.expect("the owner takes its fence");
owner
.produce(0, &test_person(1))
@@ -761,7 +961,7 @@ async fn healing_without_standing_does_not_steal_the_epoch() {
.expect("the owner can write");
// A pod whose claim is gone tries to heal the same partition.
- let zombie = Arc::new(fenced_producers(&topic));
+ let zombie = Arc::new(fenced_producers(&topic, 1));
let lapsed = AuthorityClock::unclaimed();
lapsed.begin_session(Duration::from_secs(30), std::time::Instant::now());
lapsed.surrender();
@@ -781,10 +981,10 @@ async fn healing_skips_a_partition_under_handoff() {
let topic = format!("fence_heal_{}", uuid::Uuid::new_v4().simple());
let inflight = InflightTracker::new();
- let owner = Arc::new(fenced_producers(&topic));
+ let owner = Arc::new(fenced_producers(&topic, 1));
owner.acquire(0).await.expect("the owner takes its fence");
- let other = Arc::new(fenced_producers(&topic));
+ let other = Arc::new(fenced_producers(&topic, 1));
let valid = AuthorityClock::unclaimed();
valid.begin_session(Duration::from_secs(30), std::time::Instant::now());
inflight.fence(0);
@@ -805,7 +1005,7 @@ async fn healing_skips_a_partition_under_handoff() {
#[tokio::test]
async fn healing_gives_back_a_fence_it_lost_standing_for() {
let topic = format!("fence_heal_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers(&topic));
+ let producers = Arc::new(fenced_producers(&topic, 1));
let inflight = InflightTracker::new();
let clock = Arc::new(AuthorityClock::unclaimed());
@@ -839,22 +1039,28 @@ async fn healing_gives_back_a_fence_it_lost_standing_for() {
#[tokio::test]
async fn a_writer_woken_onto_a_condemned_producer_is_bounced() {
let topic = format!("fence_woken_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers(&topic));
+ let producers = Arc::new(fenced_producers(&topic, 1));
producers.acquire(0).await.expect("acquire the fence");
// Stage the gate exactly as a commit in flight leaves it, so the
// write below parks rather than opening its own window.
- producers.begin_committing_for_test(0);
+ producers.begin_committing_for_test(0, 0);
let parked = {
let p = Arc::clone(&producers);
tokio::spawn(async move { p.produce(0, &test_person(1)).await })
};
- tokio::time::sleep(Duration::from_millis(100)).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 the committing window");
// The commit resolves badly and condemns the producer, then releases
// the gate and wakes the parked writer — production's exact order.
- producers.condemn_for_test(0);
- producers.finish_committing_for_test(0);
+ producers.condemn_for_test(0, 0);
+ producers.finish_committing_for_test(0, 0);
match parked.await.expect("the parked task must not panic") {
Err(FencedProduceError::NotAcquired) => {}
@@ -875,9 +1081,11 @@ async fn a_writer_woken_onto_a_condemned_producer_is_bounced() {
#[tokio::test]
async fn healing_leaves_a_fence_it_already_holds_alone() {
let topic = format!("fence_heal_noop_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers_with_window(
+ let producers = Arc::new(fenced_producers_with(
&topic,
Duration::from_millis(600),
+ 32,
+ 1,
));
let inflight = InflightTracker::new();
let clock = AuthorityClock::unclaimed();
@@ -915,7 +1123,7 @@ async fn healing_leaves_a_fence_it_already_holds_alone() {
#[tokio::test]
async fn a_committer_that_never_reports_condemns_its_producer() {
let topic = format!("fence_lost_commit_{}", uuid::Uuid::new_v4().simple());
- let producers = fenced_producers(&topic);
+ let producers = fenced_producers(&topic, 1);
producers.acquire(0).await.expect("acquire the fence");
producers.panic_next_commit_for_test(0);
@@ -952,9 +1160,11 @@ async fn a_committer_that_never_reports_condemns_its_producer() {
async fn settling_commits_an_abandoned_record_before_the_handoff_advances() {
let topic = format!("fence_settle_{}", uuid::Uuid::new_v4().simple());
- let first = Arc::new(fenced_producers_with_window(
+ let first = Arc::new(fenced_producers_with(
&topic,
Duration::from_secs(15),
+ 32,
+ 1,
));
first.acquire(0).await.expect("first owner acquires");
{
@@ -990,7 +1200,7 @@ async fn settling_commits_an_abandoned_record_before_the_handoff_advances() {
// And it settled before the successor existed, which is what makes
// the ack a boundary rather than the start of a race.
- let second = fenced_producers(&topic);
+ let second = fenced_producers(&topic, 1);
second.acquire(0).await.expect("successor acquires");
assert_eq!(
read_committed_count(&topic).await,
@@ -1019,9 +1229,11 @@ async fn a_resume_does_not_fence_the_window_its_own_warm_admitted() {
// Long enough that the write is still sitting in an open window when
// the resume runs — a window that closed first would be committed
// already and could not be fenced.
- let producers = Arc::new(fenced_producers_with_window(
+ let producers = Arc::new(fenced_producers_with(
&topic,
Duration::from_secs(10),
+ 32,
+ 1,
));
let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));
@@ -1066,7 +1278,7 @@ async fn a_resume_does_not_fence_the_window_its_own_warm_admitted() {
#[tokio::test]
async fn a_poisoned_window_is_aborted_rather_than_committed() {
let topic = format!("fence_poison_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers_with_window(&topic, Duration::from_secs(1)));
+ let producers = Arc::new(fenced_producers_with(&topic, Duration::from_secs(1), 32, 1));
producers.acquire(0).await.expect("acquire the fence");
let writing = {
@@ -1110,7 +1322,7 @@ async fn a_poisoned_window_is_aborted_rather_than_committed() {
#[tokio::test]
async fn a_window_that_cannot_settle_still_lets_the_handoff_proceed() {
let topic = format!("fence_unsettled_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers(&topic));
+ let producers = Arc::new(fenced_producers(&topic, 1));
producers.acquire(0).await.expect("acquire the fence");
producers
.produce(0, &test_person(1))
@@ -1119,7 +1331,7 @@ async fn a_window_that_cannot_settle_still_lets_the_handoff_proceed() {
// The state an abort that never landed, or a commit whose outcome
// stayed unknown, leaves behind.
- producers.condemn_for_test(0);
+ producers.condemn_for_test(0, 0);
let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));
handler
@@ -1138,9 +1350,11 @@ async fn a_window_that_cannot_settle_still_lets_the_handoff_proceed() {
#[tokio::test]
async fn a_repeated_resume_does_not_fence_the_window_the_first_one_admitted() {
let topic = format!("fence_resume_twice_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers_with_window(
+ let producers = Arc::new(fenced_producers_with(
&topic,
Duration::from_secs(10),
+ 32,
+ 1,
));
let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));
@@ -1169,8 +1383,8 @@ async fn a_repeated_resume_does_not_fence_the_window_the_first_one_admitted() {
);
}
-/// A drain that arrives while the window's commit is already running must
-/// wait for it.
+/// A drain that arrives while a window's commit is already running must
+/// wait for it, on whichever lane the commit runs.
///
/// At that point the gate reads idle in every field but `committing`: the
/// window is closed to joiners and no sends are outstanding, yet
@@ -1181,11 +1395,11 @@ async fn a_repeated_resume_does_not_fence_the_window_the_first_one_admitted() {
#[tokio::test]
async fn a_drain_waits_for_a_commit_that_is_already_running() {
let topic = format!("fence_settle_mid_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers(&topic));
+ let producers = Arc::new(fenced_producers(&topic, 2));
producers.acquire(0).await.expect("acquire the fence");
- // The gate a commit in flight leaves behind.
- producers.begin_committing_for_test(0);
+ // The gate a commit in flight leaves behind, on the second lane.
+ producers.begin_committing_for_test(0, 1);
let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));
let draining = tokio::spawn(async move { handler.drain_partition_inflight(0).await });
@@ -1195,7 +1409,7 @@ async fn a_drain_waits_for_a_commit_that_is_already_running() {
"the drain acked while this window's commit was still in flight"
);
- producers.finish_committing_for_test(0);
+ producers.finish_committing_for_test(0, 1);
tokio::time::timeout(Duration::from_secs(10), draining)
.await
.expect("the drain must return once the commit finishes")
@@ -1214,9 +1428,11 @@ async fn a_drain_waits_for_a_commit_that_is_already_running() {
#[tokio::test]
async fn a_resume_that_took_the_fence_itself_does_not_take_it_again() {
let topic = format!("fence_resume_own_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers_with_window(
+ let producers = Arc::new(fenced_producers_with(
&topic,
Duration::from_secs(10),
+ 32,
+ 1,
));
let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));
@@ -1253,7 +1469,7 @@ async fn a_resume_that_took_the_fence_itself_does_not_take_it_again() {
#[tokio::test]
async fn warming_without_a_confirmed_lease_does_not_take_the_epoch() {
let topic = format!("fence_warm_auth_{}", uuid::Uuid::new_v4().simple());
- let owner = Arc::new(fenced_producers(&topic));
+ let owner = Arc::new(fenced_producers(&topic, 1));
owner.acquire(0).await.expect("the owner takes its fence");
owner
.produce(0, &test_person(1))
@@ -1262,7 +1478,7 @@ async fn warming_without_a_confirmed_lease_does_not_take_the_epoch() {
let lapsed = common::live_authority();
lapsed.surrender();
- let zombie = Arc::new(fenced_producers(&topic));
+ let zombie = Arc::new(fenced_producers(&topic, 1));
let handler = common::test_handoff_handler_with_authority(&topic, Arc::clone(&zombie), lapsed);
handler
.warm_partition(0)
@@ -1280,7 +1496,7 @@ async fn warming_without_a_confirmed_lease_does_not_take_the_epoch() {
#[tokio::test]
async fn a_resume_without_a_confirmed_lease_does_not_take_the_epoch() {
let topic = format!("fence_resume_auth_{}", uuid::Uuid::new_v4().simple());
- let owner = Arc::new(fenced_producers(&topic));
+ let owner = Arc::new(fenced_producers(&topic, 1));
owner.acquire(0).await.expect("the owner takes its fence");
owner
.produce(0, &test_person(1))
@@ -1289,7 +1505,7 @@ async fn a_resume_without_a_confirmed_lease_does_not_take_the_epoch() {
let lapsed = common::live_authority();
lapsed.surrender();
- let zombie = Arc::new(fenced_producers(&topic));
+ let zombie = Arc::new(fenced_producers(&topic, 1));
let handler = common::test_handoff_handler_with_authority(&topic, Arc::clone(&zombie), lapsed);
handler
.resume_partition(0)
@@ -1313,11 +1529,11 @@ async fn a_warm_that_loses_its_claim_mid_acquire_gives_the_fence_back() {
// Seeded through a separate owner so the warm below is a real one: a
// warm that fails for want of a topic would leave the fence behind
// through its guard and prove nothing about this branch.
- let seed = fenced_producers(&topic);
+ let seed = fenced_producers(&topic, 1);
seed.acquire(0).await.expect("seed the topic");
seed.produce(0, &test_person(1)).await.expect("seed record");
- let producers = Arc::new(fenced_producers(&topic));
+ let producers = Arc::new(fenced_producers(&topic, 1));
let clock = common::live_authority();
let handler = common::test_handoff_handler_with_authority(
&topic,
@@ -1361,7 +1577,7 @@ async fn a_warm_that_loses_its_claim_mid_acquire_gives_the_fence_back() {
#[tokio::test]
async fn a_resume_that_loses_its_claim_mid_acquire_gives_the_fence_back() {
let topic = format!("fence_resume_midauth_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers(&topic));
+ let producers = Arc::new(fenced_producers(&topic, 1));
let clock = common::live_authority();
let handler = common::test_handoff_handler_with_authority(
&topic,
@@ -1406,7 +1622,7 @@ async fn a_resume_that_loses_its_claim_mid_acquire_gives_the_fence_back() {
#[tokio::test]
async fn the_drain_refuses_new_writes_while_it_is_still_waiting() {
let topic = format!("fence_drain_order_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers(&topic));
+ let producers = Arc::new(fenced_producers(&topic, 1));
let inflight = Arc::new(InflightTracker::new());
producers.acquire(0).await.expect("acquire the fence");
@@ -1442,7 +1658,7 @@ async fn the_drain_refuses_new_writes_while_it_is_still_waiting() {
#[tokio::test]
async fn releasing_a_partition_retires_its_fresh_fence_mark() {
let topic = format!("fence_release_mark_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers(&topic));
+ let producers = Arc::new(fenced_producers(&topic, 1));
let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));
producers.acquire(0).await.expect("seed the topic");
@@ -1472,12 +1688,12 @@ async fn releasing_a_partition_retires_its_fresh_fence_mark() {
#[tokio::test]
async fn verifying_a_served_partition_retakes_a_condemned_fence() {
let topic = format!("fence_verify_heal_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers(&topic));
+ let producers = Arc::new(fenced_producers(&topic, 1));
let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));
producers.acquire(0).await.expect("acquire the fence");
// The state a failed abort or an unknown commit leaves behind.
- producers.condemn_for_test(0);
+ producers.condemn_for_test(0, 0);
assert!(
!producers.holds(0),
"a condemned producer must not still claim the partition"
@@ -1518,6 +1734,7 @@ async fn a_heal_that_cannot_acquire_does_not_fail_the_run() {
broker_txn_timeout: BROKER_TXN_TIMEOUT,
window: Duration::from_millis(5),
window_max_writes: 32,
+ lanes: 1,
settle_budget: Duration::from_secs(1),
}));
let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));
@@ -1540,9 +1757,11 @@ async fn a_heal_that_cannot_acquire_does_not_fail_the_run() {
#[tokio::test]
async fn a_healed_fence_is_not_reacquired_by_the_same_convergences_resume() {
let topic = format!("fence_heal_mark_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers_with_window(
+ let producers = Arc::new(fenced_producers_with(
&topic,
Duration::from_millis(600),
+ 32,
+ 1,
));
let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));
@@ -1584,7 +1803,7 @@ async fn a_healed_fence_is_not_reacquired_by_the_same_convergences_resume() {
#[tokio::test]
async fn an_unwound_committer_condemns_rather_than_stranding_its_waiters() {
let topic = format!("fence_orphan_{}", uuid::Uuid::new_v4().simple());
- let producers = Arc::new(fenced_producers(&topic));
+ let producers = Arc::new(fenced_producers(&topic, 1));
producers.acquire(0).await.expect("acquire the fence");
producers
.produce(0, &test_person(1))
@@ -1639,6 +1858,7 @@ async fn the_derived_production_timescales_compose_against_a_real_broker() {
window: Duration::from_millis(config.fencing_window_ms),
window_max_writes: config.fencing_window_max_writes,
settle_budget: config.fencing_settle_budget(),
+ lanes: config.fencing_lanes,
}));
producers
.acquire(0)