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.

feat(personhog): always fence the changelog and gate on the lease (#102560)

Zach Brown2d2fdd09bf32
diff --git a/.agents/skills/reviewing-personhog-protocol/references/personhog-invariants.md b/.agents/skills/reviewing-personhog-protocol/references/personhog-invariants.md
index e2ed4fe62e2a..0615e90165f4 100644
--- a/.agents/skills/reviewing-personhog-protocol/references/personhog-invariants.md
+++ b/.agents/skills/reviewing-personhog-protocol/references/personhog-invariants.md
@@ -48,7 +48,8 @@ code and its README are authoritative.
reads. Reconcile-failure tolerance bounds staleness at one tick per
count and must not be exempt from escalation via its own detection
duration.
-10. **Known residuals are documented, not denied.** The double-zombie
- write-loss path (pending epoch fencing), the pre-detection window of
- at most one keepalive round, and the in-flight-at-dead-owner-warm
- race are accepted, stated in the README, and must not silently widen.
+10. **Known residuals are documented, not denied.** The pre-detection
+ window of at most one keepalive round and the
+ in-flight-at-dead-owner-warm race are accepted, stated in the README,
+ and must not silently widen. The double-zombie write-loss path is
+ closed by epoch fencing, which every build now runs.
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.yml
index e9da72bc5369..d5b8f83e2eff 100644
--- a/.github/workflows/ci-rust.yml
+++ b/.github/workflows/ci-rust.yml
@@ -764,56 +764,26 @@ jobs:
--shutdown-after 3s --zombie-after 8s --zombie-duration 6s \
--writer-pause-after 4s --writer-pause-duration 6s
- # Broker-enforced epoch fencing, on the scenario it exists for:
- # a SIGSTOPped leader whose lease is revoked wakes inside its
- # own window and tries to append. Everything else in this file
- # runs the flag off, so without this step the entire fenced
- # arm — warm-time acquisition, the transaction windows, the
- # write path's error mapping — ships with no end-to-end
- # coverage at all.
- #
- # The gate rides along because startup refuses fencing without
- # it: acquisition moves a partition's broker epoch, and a pod
- # that has stopped renewing has no standing to do that.
- #
- # Guarded on the flag existing so a branch that predates
- # --leader-env skips it rather than failing before its own
- # tests run.
- - name: Run the e2e gate with epoch fencing (zombie + writer lag)
- run: |
- if ! ./target/debug/personhog-test-harness gate --help | grep -q -- --leader-env; then
- # Graceful degradation for unrebased branches (see the
- # CI back-compat rule) — but loud, so a harness
- # regression that drops the flag cannot silently
- # retire this gate.
- echo "::warning title=fenced e2e gate skipped::harness predates --leader-env; the fenced gate did not run"
- exit 0
- fi
- # The freeze has to outlive the lease, or the woken pod
- # still holds a valid claim and neither the lease gate
- # nor the broker fence is ever asked anything. 27s is
- # the lowest TTL validate_fencing_timescales accepts
- # with fencing on (the write budget pays the drain's
- # settle slack first), so the freeze runs past it and
- # the run is sized to leave the woken zombie time to
- # try. The gate asserts rejection by consequence (an
- # unfenced landing fails the verifier; a crash fails
- # the liveness check), not by scraping fence metrics —
- # the deterministic fencing_integration tests carry the
- # per-arm coverage.
+ # The freeze has to outlive the lease, or the woken pod still
+ # holds a valid claim and nothing is ever asked. 27s is the
+ # lowest TTL validate_fencing_timescales accepts, so the
+ # freeze runs past it. Rejection is asserted by consequence:
+ # an unfenced landing fails the verifier.
+ - name: Run the e2e gate under chaos (zombie + writer lag)
+ run: |
./target/debug/personhog-test-harness gate \
- --leader-env KAFKA_TRANSACTIONAL_FENCING=true \
- --leader-env LEASE_GATED_AUTHORITY=true \
--leaders 3 --partitions 8 --persons 100 --concurrency 10 --duration 45s \
--leader-lease-ttl 27 \
--zombie-after 5s --zombie-duration 32s \
--writer-pause-after 4s --writer-pause-duration 6s
+ # A fenced write's budget rules out the short TTL this used
+ # to run, so the run is lengthened to keep the expiry inside.
- name: Run the e2e gate under chaos (TTL-expiry kill + restarts)
run: |
./target/debug/personhog-test-harness gate \
- --leaders 3 --partitions 8 --persons 100 --concurrency 10 --duration 18s \
- --leader-lease-ttl 5 --kill-after 4s --kill-fast false \
+ --leaders 3 --partitions 8 --persons 100 --concurrency 10 --duration 45s \
+ --leader-lease-ttl 27 --kill-after 4s --kill-fast false \
--writer-crash-after 9s --restart-after 12s
- name: Run the e2e gate under chaos (coordinator failover + mid-handoff kill)
diff --git a/rust/.config/nextest.toml b/rust/.config/nextest.toml
index aabdb79a06df..37f60cbe493d 100644
--- a/rust/.config/nextest.toml
+++ b/rust/.config/nextest.toml
@@ -40,11 +40,7 @@ retries = 1
[profile.ci.junit]
path = "junit.xml"
-# Same reservation under the CI profile. Its sibling
-# `two_partitions_double_zombie_loses_acked_writes` used to be reserved too,
-# but it only asserts a counterexample exists and now stops at one, which
-# leaves it a few seconds long — reserving the machine for it just serialized
-# it against the rest of the suite for nothing.
+# Same reservation under the CI profile.
[[profile.ci.overrides]]
filter = 'package(personhog-stateright) and test(epoch_fenced_two_partitions_double_zombie_is_safe)'
threads-required = "num-cpus"
diff --git a/rust/personhog-coordination/README.md b/rust/personhog-coordination/README.md
index 7724175f3218..b4b011127a83 100644
--- a/rust/personhog-coordination/README.md
+++ b/rust/personhog-coordination/README.md
@@ -106,23 +106,16 @@ Several failure modes are handled explicitly:
## Known limitations
-**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:
+**The double zombie is closed.** A lease-expired router feeding a lease-expired pod could once ack a write the partition's new owner never saw. Epoch fencing rejects that pod's produce at the broker, the lease gate stops it answering reads, and acquisition is gated on the same claim so a waking zombie cannot take the epoch from the real owner on its way to noticing it is dead. Every build runs all three; the stateright model checks them together. Two consequences are worth knowing:
-- **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.
-- **A release's mark check leans on the gate too.** The leader answers a committed release from the op's mark snapshot for a fence it sealed before the snapshot was read. A zombie's sealed fences and snapshot outlive its authority, so with the gate off a release it should no longer serve can trust a pre-settle snapshot where the row would have said deleted; with the gate on, admission refuses it.
-- **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.
-- **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.
+- *The read gate is only as prompt as the claim's lapse.* Natural expiry 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 best-effort registration watch turns 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 this). No production path revokes another pod's lease, so reaching the window takes an operator.
+- *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 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):
- **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.** 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/README.md b/rust/personhog-leader/README.md
index 9d7a25446c57..35b1dbff1877 100644
--- a/rust/personhog-leader/README.md
+++ b/rust/personhog-leader/README.md
@@ -28,8 +28,7 @@ platform has always had — and its planned closure is operation
identity: the router stamps each logical request with an op id, the
leader keeps a short ring of recently applied ids on the cached person
entry, and the id rides the produced record so warming rebuilds the
-ring on a new owner (scoped with the epoch-fencing work; the stamp and
-the ring land together).
+ring on a new owner (the stamp and the ring land together).
Future RPCs must clear the same bar: convergent under redelivery
(tombstone-style deletes, max-merge version floors, re-appliable
@@ -212,15 +211,19 @@ via `LeaderHandoffHandler` (see `src/coordination/mod.rs`):
"no in-flight" implies "every acked write durable in Kafka."
Reads are never fenced — until cutover the frozen cache state is
still the latest.
-- `warm_partition` (Warming): see the section above. Also lifts any
- fence left over from a previous ownership of the same partition.
-- `release_partition` (Complete): lifts the write fence and drops the
- partition's cache slot via `PartitionedCache::drop_partition` once
- the routing table has flipped to the new owner.
+- `warm_partition` (Warming): see the section above. Takes the
+ partition's changelog epoch before the warm read, which fences every
+ predecessor at the broker, and lifts any write fence left over from a
+ previous ownership of the same partition.
+- `release_partition` (Complete): lifts the write fence, gives the
+ changelog epoch back, and drops the partition's cache slot via
+ `PartitionedCache::drop_partition` once the routing table has flipped
+ to the new owner.
- `resume_partition` (handoff cancelled): a handoff deleted before
`Complete` while this pod still owns the partition is a
- cancellation — lifts the write fence so the partition serves writes
- again.
+ cancellation — re-takes the changelog epoch, which the cancelled
+ handoff's target may have taken, then lifts the write fence so the
+ partition serves writes again.
#### Request Path
diff --git a/rust/personhog-leader/src/config.rs b/rust/personhog-leader/src/config.rs
index 51dffcfb5f35..8e369129b7bb 100644
--- a/rust/personhog-leader/src/config.rs
+++ b/rust/personhog-leader/src/config.rs
@@ -24,13 +24,6 @@ pub struct Config {
#[envconfig(default = "16777216")]
pub cache_memory_capacity_bytes: usize,
- /// Broker-enforced epoch fencing: the changelog is produced through
- /// per-partition transactional producers, so a new owner's
- /// acquisition fences every predecessor at the broker. Off by
- /// default while the latency cost is being measured.
- #[envconfig(default = "false")]
- pub kafka_transactional_fencing: bool,
-
/// How long a fencing transaction window admits joining writes
/// before committing, when it does not fill first (see
/// FENCING_WINDOW_MAX_WRITES). Amortizes the commit round trip
@@ -335,13 +328,6 @@ pub struct Config {
#[envconfig(default = "")]
pub k8s_namespace: String,
- /// Refuse strong reads and fence acquisition once this pod's lease
- /// may have expired, instead of serving until the keepalive notices.
- /// Trades availability during an etcd outage for never answering as
- /// an owner the protocol may already have replaced.
- #[envconfig(default = "false")]
- pub lease_gated_authority: bool,
-
#[envconfig(default = "30")]
pub lease_ttl: i64,
@@ -691,9 +677,6 @@ impl Config {
/// startup: the derivation satisfies them wherever the lease TTL
/// leaves room, and an operator can override either knob.
pub fn validate_fencing_timescales(&self) -> Result<(), String> {
- if !self.kafka_transactional_fencing {
- return Ok(());
- }
if self.fencing_lanes < 1 {
return Err("FENCING_LANES must be at least 1".to_string());
}
@@ -703,20 +686,6 @@ impl Config {
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
- // fences the legitimate owner on its way to noticing it is dead.
- // The gate is what gives acquisition the standing to be safe, so
- // the dependency is refused at startup rather than documented.
- if !self.lease_gated_authority {
- return Err(
- "KAFKA_TRANSACTIONAL_FENCING requires LEASE_GATED_AUTHORITY: unless \
- acquisition is gated on holding the lease, a pod whose lease has lapsed \
- can take the changelog fence away from the partition's real owner"
- .to_string(),
- );
- }
if self.fencing_window_max_writes == 0 {
return Err(
"FENCING_WINDOW_MAX_WRITES must be at least 1: zero would close every \
@@ -954,8 +923,6 @@ mod fencing_timescale_tests {
fn fenced(lease_ttl: i64) -> Config {
let mut config =
Config::init_from_hashmap(&std::collections::HashMap::new()).expect("defaults");
- config.kafka_transactional_fencing = true;
- config.lease_gated_authority = true;
config.lease_ttl = lease_ttl;
config.fencing_txn_timeout_ms = 0;
config.fencing_message_timeout_ms = 0;
@@ -1328,17 +1295,4 @@ mod fencing_timescale_tests {
.expect_err("must reject");
assert!(err.contains("librdkafka"), "got: {err}");
}
-
- /// The dependency is a startup failure, not a comment: fencing on a
- /// pod that will acquire without checking its lease is the shape the
- /// zombie gate reproduces.
- #[test]
- fn fencing_without_the_lease_gate_is_refused() {
- let mut config = fenced(30);
- config.lease_gated_authority = false;
- let err = config
- .validate_fencing_timescales()
- .expect_err("fencing must require the gate");
- assert!(err.contains("LEASE_GATED_AUTHORITY"), "got: {err}");
- }
}
diff --git a/rust/personhog-leader/src/coordination/mod.rs b/rust/personhog-leader/src/coordination/mod.rs
index 769c22d27798..f551de223726 100644
--- a/rust/personhog-leader/src/coordination/mod.rs
+++ b/rust/personhog-leader/src/coordination/mod.rs
@@ -11,6 +11,8 @@ use tracing::{error, info};
use crate::cache::{DirtyIndex, PartitionedCache};
use crate::emitted::EmittedVersions;
use crate::fence::{drop_partition_fences, rebuild_partition_fences, FenceMap};
+#[cfg(test)]
+use crate::fencing::FencedProducerConfig;
use crate::fencing::{heal_fence, FenceGuard, FencedChangelogProducers, HealOutcome};
use crate::inflight::InflightTracker;
use crate::pg::PgFallback;
@@ -59,17 +61,13 @@ pub struct LeaderHandoffHandler {
fence_scan: Option<PgFallback>,
num_partitions: u32,
pools: Arc<WarmClientPools>,
- /// Present when broker-enforced epoch fencing is on: acquiring a
- /// partition initializes its transactional producer (fencing every
- /// predecessor), and releasing it drops the producer.
- fenced: Option<Arc<FencedChangelogProducers>>,
- /// Present when lease-gated authority is on. Acquiring a fence takes
- /// the partition's epoch away from whoever holds it, so a pod whose
- /// lease may have lapsed must not do it: the broker grants the epoch
- /// to whoever initializes last, not to whoever the protocol says
- /// owns the partition, so an unchecked acquire lets a zombie waking
- /// inside its lease window fence the legitimate owner.
- authority: Option<Arc<AuthorityClock>>,
+ /// Acquiring a partition initializes its transactional producer,
+ /// fencing every predecessor; releasing it drops the producer.
+ fenced: Arc<FencedChangelogProducers>,
+ /// The broker grants the epoch to whoever initializes last, so a pod
+ /// whose lease may have lapsed must not acquire: it would fence the
+ /// partition's real owner.
+ authority: Arc<AuthorityClock>,
/// Shared with the service, so that giving up a partition also gives
/// up the version floors held for its persons.
emitted_versions: Arc<EmittedVersions>,
@@ -95,8 +93,8 @@ impl LeaderHandoffHandler {
fence_scan: Option<PgFallback>,
num_partitions: u32,
pools: Arc<WarmClientPools>,
- fenced: Option<Arc<FencedChangelogProducers>>,
- authority: Option<Arc<AuthorityClock>>,
+ fenced: Arc<FencedChangelogProducers>,
+ authority: Arc<AuthorityClock>,
emitted_versions: Arc<EmittedVersions>,
) -> Self {
Self {
@@ -145,9 +143,7 @@ impl LeaderHandoffHandler {
let Err(e) = self.check_authority(partition, phase) else {
return Ok(());
};
- if let Some(fenced) = &self.fenced {
- fenced.release(partition);
- }
+ self.fenced.release(partition);
counter!(
"personhog_leader_authority_lapsed_mid_acquire_total",
"phase" => phase
@@ -161,9 +157,7 @@ impl LeaderHandoffHandler {
}
fn check_authority(&self, partition: u32, phase: &'static str) -> Result<()> {
- let Some(authority) = &self.authority else {
- return Ok(());
- };
+ let authority = &self.authority;
if authority.is_valid() {
return Ok(());
}
@@ -206,10 +200,8 @@ impl HandoffHandler for LeaderHandoffHandler {
// consumes is discarded on release or by the periodic sweep —
// a cancelled inbound handoff leaves no convergence behind, so
// the sweep is the only path that reaches its leftovers.
- if let Some(fenced) = &self.fenced {
- let fenced = Arc::clone(fenced);
- tokio::spawn(async move { fenced.preconnect(partition).await });
- }
+ let fenced = Arc::clone(&self.fenced);
+ tokio::spawn(async move { fenced.preconnect(partition).await });
}
async fn drain_partition_inflight(&self, partition: u32) -> Result<()> {
@@ -238,9 +230,7 @@ impl HandoffHandler for LeaderHandoffHandler {
// the successor's `init_transactions` aborts whatever is left,
// exactly as it did before this wait existed — pinned by
// `a_successors_init_aborts_the_predecessors_open_window`.
- if let Some(fenced) = &self.fenced {
- fenced.settle(partition).await;
- }
+ self.fenced.settle(partition).await;
info!(partition, "inflight drained; writes fenced");
Ok(())
}
@@ -285,22 +275,15 @@ impl HandoffHandler for LeaderHandoffHandler {
// records it can never read. Re-acquiring aborts that window,
// which is what lets the read complete; the admitted writes fail
// as fenced and their versions stay spent.
- let fence_guard = if let Some(fenced) = &self.fenced {
- fenced
- .acquire(partition)
- .await
- .map_err(Error::invalid_state)?;
- self.check_authority_after_acquire(partition, "warm")?;
- info!(partition, "changelog fence acquired");
- // From here the fence is held for a warm that has not
- // happened yet. If the warm fails — or never returns,
- // because the attempt was torn down by a lost lease — the
- // guard gives the epoch back rather than leaving this
- // process holding a partition it does not own.
- Some(FenceGuard::new(Arc::clone(fenced), partition, "warm"))
- } else {
- None
- };
+ self.fenced
+ .acquire(partition)
+ .await
+ .map_err(Error::invalid_state)?;
+ self.check_authority_after_acquire(partition, "warm")?;
+ info!(partition, "changelog fence acquired");
+ // The guard gives the epoch back if the warm fails or never
+ // returns, rather than holding a partition this pod lost.
+ let fence_guard = FenceGuard::new(Arc::clone(&self.fenced), partition, "warm");
warm_from_kafka(
&self.warming,
&self.pools,
@@ -313,10 +296,8 @@ impl HandoffHandler for LeaderHandoffHandler {
// the partition (a drain whose handoff never completed); taking
// ownership through a fresh warm re-admits writes.
self.inflight.unfence(partition);
- if let Some(guard) = fence_guard {
- guard.keep();
- self.freshly_fenced.insert(partition);
- }
+ fence_guard.keep();
+ self.freshly_fenced.insert(partition);
info!(partition, "partition warmed");
Ok(())
}
@@ -335,10 +316,7 @@ impl HandoffHandler for LeaderHandoffHandler {
/// applied work, so a repairing pod's budgets reset like any other
/// progress.
async fn verify_serving(&self, partition: u32) -> Result<bool> {
- let Some(fenced) = &self.fenced else {
- return Ok(false);
- };
- match heal_fence(fenced, &self.inflight, self.authority.as_deref(), partition).await {
+ match heal_fence(&self.fenced, &self.inflight, &self.authority, partition).await {
Ok(HealOutcome::Healed) => {
// The epoch just moved. Mark it like every other
// acquisition site, so the resume step of this same
@@ -357,9 +335,7 @@ impl HandoffHandler for LeaderHandoffHandler {
// growing SHUTDOWN_FENCE_BOUND.
async fn release_partition(&self, partition: u32) -> Result<()> {
info!(partition, "releasing partition");
- if let Some(fenced) = &self.fenced {
- fenced.release(partition);
- }
+ self.fenced.release(partition);
self.inflight.unfence(partition);
self.cache.drop_partition(partition);
// The new owner's warming rebuilds its own marks; stale marks here
@@ -400,21 +376,15 @@ impl HandoffHandler for LeaderHandoffHandler {
self.inflight.unfence(partition);
return Ok(());
}
- if let Some(fenced) = &self.fenced {
- fenced
- .acquire(partition)
- .await
- .map_err(Error::invalid_state)?;
- self.check_authority_after_acquire(partition, "resume")?;
- // Mark it the same way warming does. A convergence torn down
- // between here and the point `apply` records the resume
- // retries with the partition still listed as fenced, and
- // without this mark that retry would acquire again — this
- // time bumping the epoch out from under the writes the line
- // below is about to admit.
- self.freshly_fenced.insert(partition);
- info!(partition, "changelog fence re-acquired on resume");
- }
+ self.fenced
+ .acquire(partition)
+ .await
+ .map_err(Error::invalid_state)?;
+ self.check_authority_after_acquire(partition, "resume")?;
+ // Marked like warming: without it a retried resume would acquire
+ // again, bumping the epoch out from under the writes below.
+ self.freshly_fenced.insert(partition);
+ info!(partition, "changelog fence re-acquired on resume");
self.inflight.unfence(partition);
Ok(())
}
@@ -454,6 +424,7 @@ mod tests {
kafka_producer_retries: None,
};
let pools = Arc::new(WarmClientPools::new(&kafka, "test", "personhog-writer"));
+ let fencing_kafka = kafka.clone();
LeaderHandoffHandler::new(
Arc::new(PartitionedCache::new(1 << 20)),
Arc::new(InflightTracker::new()),
@@ -477,12 +448,31 @@ mod tests {
None,
4,
pools,
- None,
- None,
+ // Lazily built: these tests never acquire a partition, so
+ // nothing here reaches a broker.
+ Arc::new(FencedChangelogProducers::new(FencedProducerConfig {
+ kafka: fencing_kafka,
+ topic: "personhog_updates".to_string(),
+ init_timeout: Duration::from_secs(1),
+ commit_timeout: Duration::from_secs(1),
+ broker_txn_timeout: Duration::from_secs(10),
+ window: Duration::from_millis(5),
+ window_max_writes: 32,
+ settle_budget: Duration::from_secs(1),
+ lanes: 1,
+ })),
+ test_authority(),
Arc::new(EmittedVersions::new(1_000_000)),
)
}
+ /// A claim that stays valid for the whole of any test.
+ fn test_authority() -> Arc<AuthorityClock> {
+ let clock = Arc::new(AuthorityClock::unclaimed());
+ clock.begin_session(Duration::from_secs(3600), std::time::Instant::now());
+ clock
+ }
+
#[tokio::test]
async fn release_partition_drops_cache_entry() {
let handler = handler();
diff --git a/rust/personhog-leader/src/fencing.rs b/rust/personhog-leader/src/fencing.rs
index e55193665456..cfb8b08faa3f 100644
--- a/rust/personhog-leader/src/fencing.rs
+++ b/rust/personhog-leader/src/fencing.rs
@@ -2254,10 +2254,10 @@ pub enum HealOutcome {
pub async fn heal_fence(
fenced: &Arc<FencedChangelogProducers>,
inflight: &InflightTracker,
- authority: Option<&AuthorityClock>,
+ authority: &AuthorityClock,
partition: u32,
) -> Result<HealOutcome, String> {
- let lost_standing = authority.is_some_and(|a| !a.is_valid());
+ let lost_standing = !authority.is_valid();
if lost_standing || fenced.holds(partition) || inflight.is_fenced(partition) {
return Ok(HealOutcome::Intact);
}
@@ -2292,7 +2292,7 @@ pub async fn heal_fence(
// the broker epoch rather than re-checking the claim, so a request
// landing here would ack a mutation with an epoch taken from the
// partition's real owner.
- let lost_standing = authority.is_some_and(|a| !a.is_valid());
+ let lost_standing = !authority.is_valid();
if lost_standing || inflight.is_fenced(partition) {
guard.keep();
// The fence this call installed, not whatever is installed now:
diff --git a/rust/personhog-leader/src/kafka.rs b/rust/personhog-leader/src/kafka.rs
index 4fa6e82f6515..272006289561 100644
--- a/rust/personhog-leader/src/kafka.rs
+++ b/rust/personhog-leader/src/kafka.rs
@@ -2,12 +2,7 @@ use std::time::Duration;
use common_kafka::kafka_producer::KafkaContext;
use lifecycle::Handle;
-use metrics::{counter, histogram};
-use prost::Message;
-use rdkafka::producer::{FutureProducer, FutureRecord, Producer};
-use tracing::error;
-
-use personhog_proto::personhog::types::v1::Person;
+use rdkafka::producer::{FutureProducer, Producer};
/// Formats the Kafka message key for person state changelog messages.
/// The topic must include `compact` in its `cleanup.policy` so Kafka
@@ -19,74 +14,6 @@ pub fn changelog_message_key(team_id: i64, person_id: i64) -> String {
format!("{team_id}:{person_id}")
}
-/// Produce a person state changelog message to Kafka.
-///
-/// Encodes the `Person` proto as the message payload and uses
-/// `{team_id}:{person_id}` as the key for compaction. The message is
-/// produced to an explicit partition — the person's routing partition —
-/// rather than relying on the producer's key partitioner. Warming rebuilds
-/// one routing partition's cache by consuming the same-numbered Kafka
-/// partition, so the two numbering schemes must agree; producing explicitly
-/// makes that alignment structural instead of depending on the partitioner
-/// config matching the router's murmur2 (librdkafka's default partitioner
-/// is CRC32-based and routes keys differently). A partition-count mismatch
-/// fails loudly at produce time instead of silently mis-sharding.
-/// Returns the record's changelog offset on successful delivery — the
-/// dirty index records it so an evicted entry can be recovered from the
-/// changelog later — or an error string on failure.
-///
-/// The handoff protocol relies on "handler returned Ok == message durable in Kafka."
-/// That requires the delivery future to be awaited before returning (done here) and
-/// `acks=all` on the producer. We rely on librdkafka's default (`acks=-1`) for the
-/// latter; if that default ever changes, the drain-inflight step in
-/// `coordination::LeaderHandoffHandler::drain_partition_inflight` becomes unsafe.
-pub async fn produce_person_changelog(
- producer: &FutureProducer<KafkaContext>,
- topic: &str,
- partition: u32,
- person: &Person,
-) -> Result<i64, String> {
- let key = changelog_message_key(person.team_id, person.id);
- let payload = person.encode_to_vec();
- // Recorded before the send so a payload rejected by the broker
- // (message.max.bytes) still shows up in the distribution.
- histogram!("personhog_leader_kafka_produce_bytes").record(payload.len() as f64);
-
- let record = FutureRecord::to(topic)
- .partition(partition as i32)
- .key(&key)
- .payload(&payload);
-
- // Time-to-durable for the changelog append: every acked write waits
- // on this, so it is the broker's direct contribution to write latency.
- let start = std::time::Instant::now();
- match producer.send_result(record) {
- Ok(delivery_future) => match delivery_future.await {
- Ok(Ok((_, offset))) => {
- counter!("personhog_leader_kafka_produces_total").increment(1);
- histogram!("personhog_leader_kafka_produce_duration_ms")
- .record(start.elapsed().as_secs_f64() * 1000.0);
- Ok(offset)
- }
- Ok(Err((kafka_err, _))) => {
- counter!("personhog_leader_kafka_produce_errors_total").increment(1);
- error!(error = %kafka_err, "kafka delivery failed");
- Err(format!("kafka delivery failed: {kafka_err}"))
- }
- Err(_cancelled) => {
- counter!("personhog_leader_kafka_produce_errors_total").increment(1);
- error!("kafka produce cancelled (timeout)");
- Err("kafka produce cancelled (timeout)".to_string())
- }
- },
- Err((kafka_err, _)) => {
- counter!("personhog_leader_kafka_produce_errors_total").increment(1);
- error!(error = %kafka_err, "kafka send_result failed");
- Err(format!("kafka enqueue failed: {kafka_err}"))
- }
- }
-}
-
/// Completes the kafka-producer lifecycle component with a bounded
/// flush instead of waiting for the last producer reference to drop.
///
diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rs
index 1269e0a1f4da..306c1321dc76 100644
--- a/rust/personhog-leader/src/main.rs
+++ b/rust/personhog-leader/src/main.rs
@@ -378,54 +378,46 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
config.ingestion_warnings_topic.clone(),
);
let fence_scan = fallback.clone();
- let mut fence_repair_nudge: Option<Arc<Notify>> = None;
- let fenced = if config.kafka_transactional_fencing {
- // Every one of these is derived from LEASE_TTL rather than set
- // directly, so an operator debugging a fenced-write timeout has
- // no way to recover them without re-running the derivation by
- // hand.
- tracing::info!(
- window_ms = config.fencing_window_ms,
- message_timeout_ms = config.fencing_message_timeout().as_millis(),
- txn_timeout_ms = config.fencing_txn_timeout().as_millis(),
- broker_txn_timeout_ms = config.fencing_broker_txn_timeout().as_millis(),
- lease_runway_ms = config.lease_fence_runway().as_millis(),
- "broker-enforced epoch fencing enabled for the changelog"
- );
- preregister_fencing_metrics(num_partitions);
- // A condemned producer's repair otherwise waits for the next
- // reconcile tick; this nudge lets the condemnation itself
- // trigger the repair pass that heals it.
- let repair_nudge = Arc::new(Notify::new());
- fence_repair_nudge = Some(Arc::clone(&repair_nudge));
- // The fenced producer runs on a tighter message timeout than the
- // 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 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()
- };
- Some(Arc::new(
- FencedChangelogProducers::new(FencedProducerConfig {
- kafka: fencing_kafka,
- topic: config.kafka_person_state_topic.clone(),
- init_timeout: config.fencing_init_timeout(),
- commit_timeout: config.fencing_txn_timeout(),
- broker_txn_timeout: config.fencing_broker_txn_timeout(),
- window: Duration::from_millis(config.fencing_window_ms),
- window_max_writes: config.fencing_window_max_writes,
- settle_budget: config.fencing_settle_budget(),
- lanes: config.fencing_lanes,
- })
- .with_repair_nudge(repair_nudge),
- ))
- } else {
- None
+ // All derived from LEASE_TTL, so an operator debugging a timeout
+ // cannot recover them without redoing the derivation.
+ tracing::info!(
+ window_ms = config.fencing_window_ms,
+ message_timeout_ms = config.fencing_message_timeout().as_millis(),
+ txn_timeout_ms = config.fencing_txn_timeout().as_millis(),
+ broker_txn_timeout_ms = config.fencing_broker_txn_timeout().as_millis(),
+ lease_runway_ms = config.lease_fence_runway().as_millis(),
+ "producing the changelog through per-partition transactional producers"
+ );
+ preregister_fencing_metrics(num_partitions);
+ // A condemned producer's repair otherwise waits for the next
+ // reconcile tick; this nudge lets the condemnation itself
+ // trigger the repair pass that heals it.
+ let fence_repair_nudge = Arc::new(Notify::new());
+ // The fenced producer runs on a tighter message timeout than the
+ // 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 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()
};
+ let fenced = Arc::new(
+ FencedChangelogProducers::new(FencedProducerConfig {
+ kafka: fencing_kafka,
+ topic: config.kafka_person_state_topic.clone(),
+ init_timeout: config.fencing_init_timeout(),
+ commit_timeout: config.fencing_txn_timeout(),
+ broker_txn_timeout: config.fencing_broker_txn_timeout(),
+ window: Duration::from_millis(config.fencing_window_ms),
+ window_max_writes: config.fencing_window_max_writes,
+ settle_budget: config.fencing_settle_budget(),
+ lanes: config.fencing_lanes,
+ })
+ .with_repair_nudge(Arc::clone(&fence_repair_nudge)),
+ );
// One clock for the process: the coordination session claims and
// surrenders it, the data plane reads it per request.
@@ -474,20 +466,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
});
}
- let gated_authority = if config.lease_gated_authority {
- tracing::info!(
- "lease-gated authority enabled: reads and fence acquisition require a \
- confirmed lease renewal within the keepalive margin"
- );
- Some(Arc::clone(&authority))
- } else {
- None
- };
-
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- config.kafka_person_state_topic.clone(),
fallback,
Arc::clone(&locks),
Arc::clone(&inflight),
@@ -500,8 +480,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
),
warnings.clone(),
Arc::clone(&fences),
- fenced.clone(),
- gated_authority.clone(),
+ Arc::clone(&fenced),
+ Arc::clone(&authority),
Arc::clone(&emitted_versions),
)
.with_fence_capacity(config.fence_map_max_entries);
@@ -538,8 +518,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
fence_scan,
num_partitions,
Arc::clone(&warm_pools),
- fenced.clone(),
- gated_authority.clone(),
+ Arc::clone(&fenced),
+ Arc::clone(&authority),
Arc::clone(&emitted_versions),
);
let advertise_address =
@@ -634,9 +614,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
k8s_awareness,
Arc::clone(&authority),
);
- if let Some(nudge) = fence_repair_nudge.take() {
- pod = pod.with_repair_nudge(nudge);
- }
+ pod = pod.with_repair_nudge(fence_repair_nudge);
tokio::spawn(async move {
let _guard = coordination_handle.process_scope();
@@ -650,16 +628,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// inbound handoff leaves no convergence behind to discard them).
let sweep_locks = Arc::clone(&locks);
let sweep_warnings = warnings.clone();
- let sweep_fenced = fenced.clone();
+ let sweep_fenced = Arc::clone(&fenced);
tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(60));
loop {
interval.tick().await;
sweep_idle_locks(&sweep_locks);
sweep_warnings.sweep_throttle();
- if let Some(fenced) = &sweep_fenced {
- fenced.sweep_prepared();
- }
+ sweep_fenced.sweep_prepared();
}
});
diff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rs
index 0a6016e49650..60e1a10ed55b 100644
--- a/rust/personhog-leader/src/service.rs
+++ b/rust/personhog-leader/src/service.rs
@@ -1,7 +1,6 @@
use std::sync::Arc;
use std::time::Instant;
-use common_kafka::kafka_producer::KafkaContext;
use dashmap::DashMap;
use metrics::{counter, histogram};
use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeader;
@@ -11,7 +10,6 @@ use personhog_proto::personhog::types::v1::{
Person, ReleaseFenceRequest, ReleaseFenceResponse, ReleaseFencesRequest, ReleaseFencesResponse,
SealedSourceSnapshot, UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,
};
-use rdkafka::producer::FutureProducer;
use tokio::sync::{Mutex, OwnedMutexGuard};
use tonic::{Request, Response, Status};
use uuid::Uuid;
@@ -29,9 +27,10 @@ use crate::fence::{
fenced_status, semantic_refusal, target_mark_status, FenceHealer, FenceMap, FenceState,
MarkVerifier,
};
+#[cfg(test)]
+use crate::fencing::FencedProducerConfig;
use crate::fencing::{FencedChangelogProducers, FencedProduceError};
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};
use crate::recovery::ChangelogRecovery;
@@ -83,9 +82,7 @@ struct Committer {
cache: Arc<PartitionedCache>,
dirty_index: Arc<DirtyIndex>,
emitted_versions: Arc<EmittedVersions>,
- producer: FutureProducer<KafkaContext>,
- changelog_topic: String,
- fenced: Option<Arc<FencedChangelogProducers>>,
+ fenced: Arc<FencedChangelogProducers>,
}
/// A committed document, with the locks the handler took for it, so the
@@ -134,9 +131,8 @@ 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,
- /// This pod's claim to serve, consulted before answering a strong
- /// read. Present only when lease-gated reads are enabled.
- authority: Option<Arc<AuthorityClock>>,
+ /// This pod's claim to serve, consulted before answering a strong read.
+ authority: Arc<AuthorityClock>,
/// Versions emitted without a confirmed outcome, so a later write for
/// the same person cannot reuse one.
emitted_versions: Arc<EmittedVersions>,
@@ -161,9 +157,7 @@ impl PersonHogLeaderService {
/// actually owns the partition.
#[allow(clippy::result_large_err)]
fn check_authority(&self, partition: u32) -> Result<(), Status> {
- let Some(authority) = &self.authority else {
- return Ok(());
- };
+ let authority = &self.authority;
if authority.is_valid() {
return Ok(());
}
@@ -212,8 +206,6 @@ impl PersonHogLeaderService {
#[allow(clippy::too_many_arguments)]
pub fn new(
cache: Arc<PartitionedCache>,
- producer: FutureProducer<KafkaContext>,
- changelog_topic: String,
fallback: Option<PgFallback>,
locks: Arc<DashMap<PersonCacheKey, Arc<Mutex<()>>>>,
inflight: Arc<InflightTracker>,
@@ -223,16 +215,14 @@ impl PersonHogLeaderService {
size_limits: PropertySizeLimits,
warnings: WarningsProducer,
fences: FenceMap,
- fenced: Option<Arc<FencedChangelogProducers>>,
- authority: Option<Arc<AuthorityClock>>,
+ fenced: Arc<FencedChangelogProducers>,
+ authority: 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 {
@@ -593,166 +583,100 @@ impl Committer {
// Produce to Kafka first, then update the cache on success.
// Readers only ever see durably committed state.
- let offset = if let Some(fenced) = &self.fenced {
- match fenced.produce(partition, &proto).await {
- Ok(offset) => offset,
- // The broker fenced this pod: a newer owner holds the
- // partition, so this claim is stale. FailedPrecondition
- // is the admission fence's own vocabulary — the router
- // classifies it as a bounce and re-resolves toward the
- // real owner.
- Err(e @ FencedProduceError::Fenced) => {
- // Rejected at the broker, so the record does not
- // exist and its version is free.
- emitted.discarded();
- tracing::error!(
- team_id = cache_key.team_id,
- person_id = cache_key.person_id,
- partition,
- "changelog producer fenced; rejecting write as stale owner"
- );
- // Deliberately no local reaction beyond failing the
- // write. A broker fence proves *someone* newer
- // initialized the transactional id, not that this pod
- // lost the partition: a zombie waking inside its
- // lease window re-acquires on the way to noticing it
- // is dead, which fences the legitimate owner. So the
- // fence is given up here as unusable and nothing
- // more; `heal_fence`, on the next convergence to
- // Serving, re-takes the epoch once the authority
- // stamp confirms this pod's standing. Reads stay
- // served meanwhile under the same stamp — the
- // `check_authority` calls at admission and before
- // answering are what refuse them once the claim
- // lapses.
- return Err(Status::failed_precondition(format!(
- "partition ownership fenced: {e}"
- )));
- }
- // This pod holds no producer for the partition — an
- // ownership statement, in the same vocabulary the
- // admission fence uses, so the router bounces and
- // re-resolves instead of surfacing a hard error.
- // The partition moved *and* this window's outcome was
- // never settled. The router still needs the ownership
- // answer, but the version cannot be handed back: the
- // commit may have succeeded on an attempt librdkafka
- // re-issued internally.
- Err(e @ FencedProduceError::FencedUncertain(_)) => {
- // Deliberately not settled: the partition moved and
- // the window's own outcome never came back, so the
- // record may or may not be in the log. Keeping the
- // version spent is the whole of what safety needs.
- counter!(
- "personhog_leader_indeterminate_outcomes_total",
- "fenced" => "true"
- )
- .increment(1);
- tracing::error!(
- team_id = cache_key.team_id,
- person_id = cache_key.person_id,
- partition,
- error = %e,
- "changelog producer fenced with an unknown outcome; version kept spent"
- );
- return Err(Status::failed_precondition(format!(
- "partition ownership fenced: {e}"
- )));
- }
- Err(e @ FencedProduceError::NotAcquired) => {
- emitted.discarded();
- tracing::warn!(
- team_id = cache_key.team_id,
- person_id = cache_key.person_id,
- partition,
- "no changelog fence held for partition; rejecting write"
- );
- return Err(Status::failed_precondition(format!(
- "partition fence not held: {e}"
- )));
- }
- // The commit's outcome is unknown, so this pod cannot
- // say whether the record became visible. A caller
- // retrying against a cache still holding the pre-write
- // version would produce a second record at the same
- // version as the one that may already have committed,
- // and the writer's strict guard keeps whichever arrived
- // first — which the floor prevents by holding the
- // version spent.
- Err(e @ FencedProduceError::Indeterminate(_)) => {
- // Deliberately not settled: whether the record exists
- // is exactly what is unknown, so the version stays
- // spent and the retry derives past it.
- counter!(
- "personhog_leader_indeterminate_outcomes_total",
- "fenced" => "false"
- )
- .increment(1);
- tracing::error!(
- team_id = cache_key.team_id,
- person_id = cache_key.person_id,
- partition,
- error = %e,
- "changelog commit outcome unknown; version kept spent"
- );
- return Err(Status::unknown(format!(
- "person state may or may not have been stored: {e}"
- )));
- }
- // The window aborted, so no record became visible: the
- // write is safe to retry, and ABORTED is the code the
- // clients actually retry on.
- Err(e) => {
- // The window aborted, so no record became visible and
- // the version can be derived again.
- emitted.discarded();
- tracing::error!(
- team_id = cache_key.team_id,
- person_id = cache_key.person_id,
- error = %e,
- "failed to produce person state changelog (fenced path)"
- );
- return Err(Status::aborted(format!(
- "failed to durably store person state: {e}"
- )));
- }
+ let offset = match self.fenced.produce(partition, &proto).await {
+ Ok(offset) => offset,
+ // The broker fenced this pod: a newer owner holds the
+ // partition, so this claim is stale. FailedPrecondition
+ // is the admission fence's own vocabulary — the router
+ // classifies it as a bounce and re-resolves toward the
+ // real owner.
+ Err(e @ FencedProduceError::Fenced) => {
+ // Rejected at the broker, so the record does not
+ // exist and its version is free.
+ emitted.discarded();
+ tracing::error!(
+ team_id = cache_key.team_id,
+ person_id = cache_key.person_id,
+ partition,
+ "changelog producer fenced; rejecting write as stale owner"
+ );
+ // No local reaction beyond failing the write: a fence
+ // proves someone newer took the id, not that this pod
+ // lost the partition. `heal_fence` re-takes the epoch
+ // on the next convergence, once the stamp allows it.
+ return Err(Status::failed_precondition(format!(
+ "partition ownership fenced: {e}"
+ )));
}
- } else {
- match produce_person_changelog(&self.producer, &self.changelog_topic, partition, &proto)
- .await
- {
- Ok(offset) => offset,
- Err(e) => {
- // Deliberately not settled. This path collapses an
- // enqueue that never left the client with a delivery
- // that timed out after the broker may already have
- // appended it, and idempotence is off by default, so
- // the record's fate is genuinely unknown. Freeing the
- // version here let a retry derive the same number and
- // put a second record behind one that may be in the
- // log — the writer's strict guard then keeps whichever
- // arrived first and discards the acked one.
- //
- // The floor alone carries that: the next write
- // derives past it whether or not the cache still
- // holds the pre-write state. The entry stays, so
- // reads may answer with a version older than the
- // changelog until a later write for this person
- // settles one. Evicting instead would resolve
- // nothing — recovery reads the last *marked* offset,
- // which is the previous write that did succeed — and
- // would answer NOT_FOUND outright once that mark is
- // pruned and no fallback pool is configured.
- tracing::error!(
- team_id = cache_key.team_id,
- person_id = cache_key.person_id,
- error = %e,
- "failed to produce person state changelog"
- );
- return Err(Status::internal(format!(
- "failed to durably store person state: {e}"
- )));
- }
+ // The partition moved and this window's outcome never
+ // came back, so the router gets its ownership answer but
+ // the version cannot be handed back.
+ Err(e @ FencedProduceError::FencedUncertain(_)) => {
+ // The record may or may not be in the log, so the
+ // version stays spent.
+ counter!(
+ "personhog_leader_indeterminate_outcomes_total",
+ "fenced" => "true"
+ )
+ .increment(1);
+ tracing::error!(
+ team_id = cache_key.team_id,
+ person_id = cache_key.person_id,
+ partition,
+ error = %e,
+ "changelog producer fenced with an unknown outcome; version kept spent"
+ );
+ return Err(Status::failed_precondition(format!(
+ "partition ownership fenced: {e}"
+ )));
+ }
+ Err(e @ FencedProduceError::NotAcquired) => {
+ emitted.discarded();
+ tracing::warn!(
+ team_id = cache_key.team_id,
+ person_id = cache_key.person_id,
+ partition,
+ "no changelog fence held for partition; rejecting write"
+ );
+ return Err(Status::failed_precondition(format!(
+ "partition fence not held: {e}"
+ )));
+ }
+ // Whether the record became visible is unknown, so the
+ // version stays spent: a retry reusing it would race a
+ // record that may already have committed.
+ Err(e @ FencedProduceError::Indeterminate(_)) => {
+ // The retry derives past the spent version.
+ counter!(
+ "personhog_leader_indeterminate_outcomes_total",
+ "fenced" => "false"
+ )
+ .increment(1);
+ tracing::error!(
+ team_id = cache_key.team_id,
+ person_id = cache_key.person_id,
+ partition,
+ error = %e,
+ "changelog commit outcome unknown; version kept spent"
+ );
+ return Err(Status::unknown(format!(
+ "person state may or may not have been stored: {e}"
+ )));
+ }
+ // The window aborted, so nothing became visible and
+ // ABORTED is the code clients retry on.
+ Err(e) => {
+ // Nothing became visible, so the version is free.
+ emitted.discarded();
+ tracing::error!(
+ team_id = cache_key.team_id,
+ person_id = cache_key.person_id,
+ error = %e,
+ "failed to produce person state changelog"
+ );
+ return Err(Status::aborted(format!(
+ "failed to durably store person state: {e}"
+ )));
}
};
@@ -1873,14 +1797,14 @@ mod tests {
let liveness = HealthRegistry::new("test")
.register("kafka".to_string(), Duration::from_secs(60))
.await;
- let producer: rdkafka::producer::FutureProducer<KafkaContext> = ClientConfig::new()
+ let producer: rdkafka::producer::FutureProducer<
+ common_kafka::kafka_producer::KafkaContext,
+ > = ClientConfig::new()
.set("bootstrap.servers", "127.0.0.1:1")
- .create_with_context(KafkaContext::from(liveness))
+ .create_with_context(common_kafka::kafka_producer::KafkaContext::from(liveness))
.unwrap();
PersonHogLeaderService::new(
Arc::new(PartitionedCache::new(16)),
- producer.clone(),
- "personhog_updates".to_string(),
None,
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
@@ -1899,12 +1823,31 @@ mod tests {
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- None,
- None,
+ // Lazily built: nothing here connects until a write acquires
+ // a partition, which these tests never do.
+ Arc::new(FencedChangelogProducers::new(FencedProducerConfig {
+ kafka: KafkaConfig::init_from_hashmap(&HashMap::new()).unwrap(),
+ topic: "personhog_updates".to_string(),
+ init_timeout: Duration::from_secs(1),
+ commit_timeout: Duration::from_secs(1),
+ broker_txn_timeout: Duration::from_secs(10),
+ window: Duration::from_millis(5),
+ window_max_writes: 32,
+ settle_budget: Duration::from_secs(1),
+ lanes: 1,
+ })),
+ test_authority(),
Arc::new(EmittedVersions::new(1_000_000)),
)
}
+ /// A claim that stays valid for the whole of any test.
+ fn test_authority() -> Arc<AuthorityClock> {
+ let clock = Arc::new(AuthorityClock::unclaimed());
+ clock.begin_session(Duration::from_secs(3600), Instant::now());
+ clock
+ }
+
/// The guarantee the clock exists for: a pod whose renewals have
/// stopped refuses to answer as the partition's owner, without
/// anything running to notice they stopped. The keepalive being
@@ -1920,7 +1863,7 @@ mod tests {
margin + Duration::from_secs(1),
));
let service = PersonHogLeaderService {
- authority: Some(Arc::clone(&clock)),
+ authority: Arc::clone(&clock),
..make_test_service().await
};
@@ -1942,7 +1885,7 @@ mod tests {
let clock = Arc::new(AuthorityClock::unclaimed());
clock.begin_session(Duration::from_secs(30), Instant::now());
let service = PersonHogLeaderService {
- authority: Some(Arc::clone(&clock)),
+ authority: Arc::clone(&clock),
..make_test_service().await
};
@@ -1970,7 +1913,7 @@ mod tests {
margin + Duration::from_secs(1),
));
let service = PersonHogLeaderService {
- authority: Some(Arc::clone(&clock)),
+ authority: Arc::clone(&clock),
..make_test_service().await
};
// The fixture's single partition makes 0 the only routing answer.
@@ -2029,7 +1972,7 @@ mod tests {
margin + Duration::from_secs(1),
));
let service = PersonHogLeaderService {
- authority: Some(Arc::clone(&clock)),
+ authority: Arc::clone(&clock),
..make_test_service().await
};
let (team_id, person_id) = (7, 42);
@@ -2088,7 +2031,7 @@ mod tests {
margin + Duration::from_secs(1),
));
let service = PersonHogLeaderService {
- authority: Some(Arc::clone(&clock)),
+ authority: Arc::clone(&clock),
..make_test_service().await
};
let (team_id, person_id) = (7, 42);
@@ -2129,7 +2072,7 @@ mod tests {
let clock = Arc::new(AuthorityClock::unclaimed());
clock.begin_session(Duration::from_secs(30), Instant::now());
let service = Arc::new(PersonHogLeaderService {
- authority: Some(Arc::clone(&clock)),
+ authority: Arc::clone(&clock),
..make_test_service().await
});
let (team_id, person_id) = (7, 42);
@@ -2201,7 +2144,7 @@ mod tests {
let clock = Arc::new(AuthorityClock::unclaimed());
clock.begin_session(Duration::from_secs(30), Instant::now());
let service = Arc::new(PersonHogLeaderService {
- authority: Some(Arc::clone(&clock)),
+ authority: Arc::clone(&clock),
..make_test_service().await
});
let (team_id, person_id) = (7, 42);
@@ -2261,7 +2204,7 @@ mod tests {
let clock = Arc::new(AuthorityClock::unclaimed());
clock.begin_session(Duration::from_secs(30), Instant::now());
let service = Arc::new(PersonHogLeaderService {
- authority: Some(Arc::clone(&clock)),
+ authority: Arc::clone(&clock),
..make_test_service().await
});
let (team_id, person_id) = (7, 42);
@@ -2323,7 +2266,7 @@ mod tests {
let clock = Arc::new(AuthorityClock::unclaimed());
clock.begin_session(Duration::from_secs(30), Instant::now());
let service = Arc::new(PersonHogLeaderService {
- authority: Some(Arc::clone(&clock)),
+ authority: Arc::clone(&clock),
..make_test_service().await
});
let (team_id, person_id) = (7, 42);
@@ -2379,7 +2322,7 @@ mod tests {
let clock = Arc::new(AuthorityClock::unclaimed());
clock.begin_session(Duration::from_secs(30), Instant::now());
let service = Arc::new(PersonHogLeaderService {
- authority: Some(Arc::clone(&clock)),
+ authority: Arc::clone(&clock),
..make_test_service().await
});
let (team_id, person_id) = (7, 42);
@@ -2449,7 +2392,7 @@ mod tests {
let clock = Arc::new(AuthorityClock::unclaimed());
clock.begin_session(Duration::from_secs(30), Instant::now());
let service = Arc::new(PersonHogLeaderService {
- authority: Some(Arc::clone(&clock)),
+ authority: Arc::clone(&clock),
..make_test_service().await
});
let (team_id, person_id) = (7, 42);
@@ -2593,7 +2536,7 @@ mod tests {
let clock = Arc::new(AuthorityClock::unclaimed());
clock.begin_session(Duration::from_secs(30), Instant::now());
let service = PersonHogLeaderService {
- authority: Some(Arc::clone(&clock)),
+ authority: Arc::clone(&clock),
..make_test_service().await
};
let (team_id, person_id) = (7, 42);
@@ -2666,7 +2609,7 @@ mod tests {
let clock = Arc::new(AuthorityClock::unclaimed());
clock.begin_session(Duration::from_secs(30), Instant::now());
let service = Arc::new(PersonHogLeaderService {
- authority: Some(Arc::clone(&clock)),
+ authority: Arc::clone(&clock),
..make_test_service().await
});
let (team_id, person_id) = (7, 42);
@@ -2741,7 +2684,7 @@ mod tests {
let clock = Arc::new(AuthorityClock::unclaimed());
clock.begin_session(Duration::from_secs(30), Instant::now());
let service = Arc::new(PersonHogLeaderService {
- authority: Some(Arc::clone(&clock)),
+ authority: Arc::clone(&clock),
..make_test_service().await
});
let (team_id, person_id) = (7, 42);
@@ -2824,7 +2767,7 @@ mod tests {
let clock = Arc::new(AuthorityClock::unclaimed());
clock.begin_session(Duration::from_secs(30), Instant::now());
let service = Arc::new(PersonHogLeaderService {
- authority: Some(Arc::clone(&clock)),
+ authority: Arc::clone(&clock),
..make_test_service().await
});
let (team_id, person_id) = (7, 42);
@@ -2882,15 +2825,6 @@ mod tests {
assert_eq!(err.code(), Code::FailedPrecondition);
}
- /// With the gate off the pod serves exactly as before, so the flag
- /// is a real off switch rather than a partial one.
- #[tokio::test]
- async fn an_ungated_service_serves_regardless_of_renewals() {
- let service = make_test_service().await;
- assert!(service.authority.is_none());
- service.check_authority(0).expect("no gate, no refusal");
- }
-
#[test]
#[should_panic(expected = "must not exceed")]
fn inverted_size_limits_refuse_to_construct() {
diff --git a/rust/personhog-leader/tests/commit_integration.rs b/rust/personhog-leader/tests/commit_integration.rs
index 3d3c74c6fff3..2a6852d2e36d 100644
--- a/rust/personhog-leader/tests/commit_integration.rs
+++ b/rust/personhog-leader/tests/commit_integration.rs
@@ -81,19 +81,17 @@ async fn start_harness() -> Harness {
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),
+ test_recovery(&topic, KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- Some(Arc::clone(&fenced)),
- None,
+ Arc::clone(&fenced),
+ common::live_authority(),
Arc::new(EmittedVersions::new(1_000_000)),
));
Harness {
diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rs
index 62b036e994c0..c8ebb7947f74 100644
--- a/rust/personhog-leader/tests/common/mod.rs
+++ b/rust/personhog-leader/tests/common/mod.rs
@@ -21,8 +21,12 @@ use personhog_coordination::pod::{PodConfig, PodHandle};
use personhog_coordination::routing_table::{RoutingTable, RoutingTableConfig, StashHandler};
use personhog_coordination::store::PersonhogStore;
use personhog_coordination::strategy::AssignmentStrategy;
+use rdkafka::admin::{AdminClient, AdminOptions, NewTopic, TopicReplication};
+use rdkafka::client::DefaultClientContext;
use rdkafka::mocking::MockCluster;
use rdkafka::producer::{DefaultProducerContext, FutureProducer};
+use rdkafka::types::RDKafkaErrorCode;
+use rdkafka::ClientConfig;
use assignment_coordination::store::{EtcdStore, StoreConfig};
use personhog_common::partitioning::partition_for_person;
@@ -199,8 +203,8 @@ pub const CHANGELOG_TOPIC: &str = "personhog_updates";
pub struct LeaderPodHandles {
pub cache: Arc<PartitionedCache>,
pub leader_addr: SocketAddr,
- // Kept alive so the mock Kafka cluster stays running for the test duration
- pub _mock_cluster: MockCluster<'static, DefaultProducerContext>,
+ /// Kept alive so the topic outlives the test that reads it.
+ pub topic: TestTopic,
}
/// Kafka config pointing at local kafka for e2e tests. Used for both the
@@ -236,13 +240,14 @@ pub fn test_kafka_config() -> KafkaConfig {
/// with real local Kafka, `KAFKA_BOOTSTRAP`.
pub fn test_warming_config(
pod_name: &str,
+ topic: &str,
kafka_bootstrap: &str,
) -> personhog_leader::warming::WarmingConfig {
let mut kafka = test_kafka_config();
kafka.kafka_hosts = kafka_bootstrap.to_string();
personhog_leader::warming::WarmingConfig {
kafka,
- topic: CHANGELOG_TOPIC.to_string(),
+ topic: topic.to_string(),
pod_name: pod_name.to_string(),
writer_consumer_group: "personhog-writer".to_string(),
lookback_offsets: 0,
@@ -259,13 +264,13 @@ pub fn test_warming_config(
/// Recovery pointed at the given broker. A short receive timeout keeps
/// tests that exercise failed recoveries fast.
-pub fn test_recovery(kafka_bootstrap: &str) -> Arc<ChangelogRecovery> {
+pub fn test_recovery(topic: &str, kafka_bootstrap: &str) -> Arc<ChangelogRecovery> {
let mut kafka = test_kafka_config();
kafka.kafka_hosts = kafka_bootstrap.to_string();
Arc::new(
ChangelogRecovery::new(RecoveryConfig {
kafka,
- topic: CHANGELOG_TOPIC.to_string(),
+ topic: topic.to_string(),
pod_name: "test-pod".to_string(),
recv_timeout: Duration::from_secs(2),
pool_size: 2,
@@ -306,23 +311,59 @@ pub async fn create_local_kafka_producer() -> FutureProducer<KafkaContext> {
.expect("failed to connect to local Kafka")
}
-/// Create a mock Kafka cluster and producer for tests. The mock topic is
-/// pre-created with `NUM_PARTITIONS` partitions so the warming pipeline's
-/// `fetch_watermarks` calls succeed for every partition the test exercises;
-/// otherwise warming aborts trying to query a non-existent partition and
-/// the handoff stalls.
-pub async fn create_test_kafka() -> (
+/// One test's changelog topic: two tests acquiring the same partition
+/// of a shared one would fence each other.
+pub struct TestTopic {
+ pub topic: String,
+}
+
+impl TestTopic {
+ /// The shape `MockCluster` offered, so call sites keep working.
+ pub fn bootstrap_servers(&self) -> String {
+ KAFKA_BOOTSTRAP.to_string()
+ }
+}
+
+/// The broker caps partitions per shard, so a topic per test has to be a
+/// topic per test run too. Deleted on its own thread and runtime: the
+/// test's runtime is being torn down around this drop.
+impl Drop for TestTopic {
+ fn drop(&mut self) {
+ let topic = self.topic.clone();
+ let cleanup = std::thread::spawn(move || {
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("cleanup runtime");
+ runtime.block_on(delete_broker_topic(&topic));
+ });
+ drop(cleanup.join());
+ }
+}
+
+/// Best effort: a leftover topic costs the next run partitions, not
+/// correctness, and a failing test has already said what went wrong.
+pub async fn delete_broker_topic(topic: &str) {
+ let Ok(admin) = ClientConfig::new()
+ .set("bootstrap.servers", KAFKA_BOOTSTRAP)
+ .create::<AdminClient<DefaultClientContext>>()
+ else {
+ return;
+ };
+ drop(admin.delete_topics(&[topic], &AdminOptions::new()).await);
+}
+
+/// For suites that only produce and read back: a service's write path
+/// needs a broker with transactions.
+pub async fn create_mock_kafka() -> (
MockCluster<'static, DefaultProducerContext>,
FutureProducer<KafkaContext>,
) {
- create_test_kafka_with_partitions(NUM_PARTITIONS as i32).await
+ create_mock_kafka_with_partitions(NUM_PARTITIONS as i32).await
}
-/// Variant of `create_test_kafka` that lets a test pin the topic to a
-/// specific partition count. Use this for tests that exercise the
-/// producer's partition-routing behavior — they need a topology they
-/// control, not the default warming-friendly multi-partition setup.
-pub async fn create_test_kafka_with_partitions(
+/// `create_mock_kafka` with a partition count the caller pins.
+pub async fn create_mock_kafka_with_partitions(
partitions: i32,
) -> (
MockCluster<'static, DefaultProducerContext>,
@@ -335,6 +376,75 @@ pub async fn create_test_kafka_with_partitions(
(cluster, producer)
}
+/// A changelog topic and a producer for it, with `NUM_PARTITIONS`
+/// partitions so warming can fetch every partition's watermarks.
+pub async fn create_test_kafka() -> (TestTopic, FutureProducer<KafkaContext>) {
+ create_test_kafka_with_partitions(NUM_PARTITIONS as i32).await
+}
+
+/// `create_test_kafka` with a partition count the caller pins.
+pub async fn create_test_kafka_with_partitions(
+ partitions: i32,
+) -> (TestTopic, FutureProducer<KafkaContext>) {
+ let topic = unique_topic();
+ create_broker_topic(&topic, partitions).await;
+ let producer = create_local_kafka_producer().await;
+ (TestTopic { topic }, producer)
+}
+
+/// A topic of this test's own, deleted when the handle drops.
+pub async fn owned_broker_topic(partitions: i32) -> TestTopic {
+ let topic = unique_topic();
+ create_broker_topic(&topic, partitions).await;
+ TestTopic { topic }
+}
+
+/// A topic name no other test shares.
+pub fn unique_topic() -> String {
+ format!("personhog_updates_{}", uuid::Uuid::new_v4().simple())
+}
+
+/// Auto-creation would use the broker's default partition count, which
+/// is not the one routing and warming expect.
+pub async fn create_broker_topic(topic: &str, partitions: i32) {
+ let admin: AdminClient<DefaultClientContext> = ClientConfig::new()
+ .set("bootstrap.servers", KAFKA_BOOTSTRAP)
+ .create()
+ .expect("admin client");
+ let new_topic = NewTopic::new(topic, partitions, TopicReplication::Fixed(1));
+ let results = admin
+ .create_topics([&new_topic], &AdminOptions::new())
+ .await
+ .expect("create topic");
+ for result in results {
+ match result {
+ Ok(_) => {}
+ Err((_, RDKafkaErrorCode::TopicAlreadyExists)) => {}
+ Err((name, code)) => panic!("failed to create topic {name}: {code}"),
+ }
+ }
+}
+
+/// Producers holding every partition's transactional id, the state a
+/// served partition is in. Concurrent because each is a round trip.
+pub async fn fenced_producers_acquired(
+ topic: &str,
+ partitions: i32,
+) -> Arc<personhog_leader::fencing::FencedChangelogProducers> {
+ let fenced = Arc::new(fenced_producers_for(topic));
+ let acquires = (0..partitions as u32).map(|partition| {
+ let fenced = Arc::clone(&fenced);
+ async move {
+ fenced
+ .acquire(partition)
+ .await
+ .expect("acquiring the changelog fence")
+ }
+ });
+ futures::future::join_all(acquires).await;
+ fenced
+}
+
/// Start a leader pod with real `LeaderHandoffHandler` + `PersonHogLeaderService`
/// sharing the same `PartitionedCache`. Returns handles for test assertions.
pub async fn start_leader_pod(
@@ -359,13 +469,19 @@ pub async fn start_leader_pod(
// while production drops them.
let emitted_versions = Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000));
// Recovery must read the broker the service produces to.
- let recovery = test_recovery(&mock_cluster.bootstrap_servers());
- let warming = test_warming_config(name, &mock_cluster.bootstrap_servers());
+ let recovery = test_recovery(&mock_cluster.topic, &mock_cluster.bootstrap_servers());
+ let warming = test_warming_config(name, &mock_cluster.topic, &mock_cluster.bootstrap_servers());
let pools = Arc::new(WarmClientPools::new(
&warming.kafka,
name,
&warming.writer_consumer_group,
));
+ // One clock and one producer set for the whole pod: a second of
+ // either would fence the first, and a clock nothing else holds
+ // cannot gate anything. Left unacquired, because warming is what
+ // takes each partition's epoch here, as it does in production.
+ let authority = Arc::new(AuthorityClock::unclaimed());
+ let fenced = Arc::new(fenced_producers_for(&mock_cluster.topic));
let handler = LeaderHandoffHandler::new(
Arc::clone(&cache),
Arc::clone(&inflight),
@@ -375,11 +491,10 @@ pub async fn start_leader_pod(
None,
NUM_PARTITIONS,
pools,
- None,
- None,
+ Arc::clone(&fenced),
+ Arc::clone(&authority),
std::sync::Arc::clone(&emitted_versions),
);
- let authority = Arc::new(AuthorityClock::unclaimed());
let pod = PodHandle::new(
store,
PodConfig {
@@ -391,7 +506,7 @@ pub async fn start_leader_pod(
},
Arc::new(handler),
None,
- authority,
+ Arc::clone(&authority),
);
let pod_token = cancel.child_token();
tokio::spawn(async move { pod.run(pod_token).await });
@@ -399,8 +514,6 @@ pub async fn start_leader_pod(
// gRPC leader service sharing the same cache
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
Arc::clone(&inflight),
@@ -410,11 +523,8 @@ pub async fn start_leader_pod(
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(dashmap::DashMap::new()),
- None,
- // A live claim rather than none, so the lease gate on the read
- // and write paths is exercised by every test built on this
- // fixture instead of being skipped by all of them.
- Some(live_authority()),
+ Arc::clone(&fenced),
+ Arc::clone(&authority),
std::sync::Arc::clone(&emitted_versions),
);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
@@ -437,7 +547,7 @@ pub async fn start_leader_pod(
LeaderPodHandles {
cache,
leader_addr,
- _mock_cluster: mock_cluster,
+ topic: mock_cluster,
}
}
@@ -459,13 +569,19 @@ pub async fn start_leader_pod_with_lease_ttl(
// service never reads, and the floors survive a handoff in tests
// while production drops them.
let emitted_versions = Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000));
- let recovery = test_recovery(&mock_cluster.bootstrap_servers());
- let warming = test_warming_config(name, &mock_cluster.bootstrap_servers());
+ let recovery = test_recovery(&mock_cluster.topic, &mock_cluster.bootstrap_servers());
+ let warming = test_warming_config(name, &mock_cluster.topic, &mock_cluster.bootstrap_servers());
let pools = Arc::new(WarmClientPools::new(
&warming.kafka,
name,
&warming.writer_consumer_group,
));
+ // One clock and one producer set for the whole pod: a second of
+ // either would fence the first, and a clock nothing else holds
+ // cannot gate anything. Left unacquired, because warming is what
+ // takes each partition's epoch here, as it does in production.
+ let authority = Arc::new(AuthorityClock::unclaimed());
+ let fenced = Arc::new(fenced_producers_for(&mock_cluster.topic));
let handler = LeaderHandoffHandler::new(
Arc::clone(&cache),
Arc::clone(&inflight),
@@ -475,11 +591,10 @@ pub async fn start_leader_pod_with_lease_ttl(
None,
NUM_PARTITIONS,
pools,
- None,
- None,
+ Arc::clone(&fenced),
+ Arc::clone(&authority),
std::sync::Arc::clone(&emitted_versions),
);
- let authority = Arc::new(AuthorityClock::unclaimed());
let pod = PodHandle::new(
store,
PodConfig {
@@ -493,15 +608,13 @@ pub async fn start_leader_pod_with_lease_ttl(
},
Arc::new(handler),
None,
- authority,
+ Arc::clone(&authority),
);
let pod_token = cancel.child_token();
tokio::spawn(async move { pod.run(pod_token).await });
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
Arc::clone(&inflight),
@@ -511,8 +624,8 @@ pub async fn start_leader_pod_with_lease_ttl(
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(dashmap::DashMap::new()),
- None,
- None,
+ Arc::clone(&fenced),
+ Arc::clone(&authority),
std::sync::Arc::clone(&emitted_versions),
);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
@@ -535,7 +648,7 @@ pub async fn start_leader_pod_with_lease_ttl(
LeaderPodHandles {
cache,
leader_addr,
- _mock_cluster: mock_cluster,
+ topic: mock_cluster,
}
}
@@ -593,19 +706,13 @@ pub async fn create_persons_pool() -> sqlx::postgres::PgPool {
/// Returns the gRPC address and the shared cache for assertions.
pub async fn start_leader_with_pg_fallback(
cancel: CancellationToken,
-) -> (
- SocketAddr,
- Arc<PartitionedCache>,
- MockCluster<'static, DefaultProducerContext>,
-) {
+) -> (SocketAddr, Arc<PartitionedCache>, TestTopic) {
let cache = Arc::new(PartitionedCache::new(1 << 20));
let (mock_cluster, kafka_producer) = create_test_kafka().await;
let pool = create_persons_pool().await;
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
Some(PgFallback {
pool,
table: "posthog_person".to_string(),
@@ -615,12 +722,12 @@ pub async fn start_leader_with_pg_fallback(
Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
Arc::new(DirtyIndex::new(1_000_000)),
- test_recovery(&mock_cluster.bootstrap_servers()),
+ test_recovery(&mock_cluster.topic, &mock_cluster.bootstrap_servers()),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(dashmap::DashMap::new()),
- None,
- None,
+ fenced_producers_acquired(&mock_cluster.topic, NUM_PARTITIONS as i32).await,
+ live_authority(),
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
);
@@ -737,7 +844,7 @@ fn handoff_handler_with(
inflight: Arc<personhog_leader::inflight::InflightTracker>,
authority: Arc<AuthorityClock>,
) -> personhog_leader::coordination::LeaderHandoffHandler {
- let mut warming = test_warming_config("test", KAFKA_BOOTSTRAP);
+ let mut warming = test_warming_config("test", topic, KAFKA_BOOTSTRAP);
warming.topic = topic.to_string();
personhog_leader::coordination::LeaderHandoffHandler::new(
Arc::new(PartitionedCache::new(1 << 20)),
@@ -752,8 +859,8 @@ fn handoff_handler_with(
"test",
"personhog-writer",
)),
- Some(fenced),
- Some(authority),
+ fenced,
+ authority,
Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
)
}
diff --git a/rust/personhog-leader/tests/fence_integration.rs b/rust/personhog-leader/tests/fence_integration.rs
index 3ce09c6a4dc8..eedc7d682717 100644
--- a/rust/personhog-leader/tests/fence_integration.rs
+++ b/rust/personhog-leader/tests/fence_integration.rs
@@ -11,7 +11,7 @@ use dashmap::DashMap;
use common::{
create_leader_client, create_test_kafka, seed_person, test_cached_person, test_recovery,
- unique_team_id, CHANGELOG_TOPIC, NUM_PARTITIONS,
+ unique_team_id, NUM_PARTITIONS,
};
use personhog_common::partitioning::partition_for_person;
use personhog_leader::cache::{
@@ -90,8 +90,8 @@ struct FenceHarness {
locks: Arc<DashMap<PersonCacheKey, Arc<tokio::sync::Mutex<()>>>>,
fences: FenceMap,
_cancel: CancellationToken,
- _mock_cluster:
- rdkafka::mocking::MockCluster<'static, rdkafka::producer::DefaultProducerContext>,
+ /// Kept alive so the topic outlives the test that reads it.
+ topic: common::TestTopic,
}
async fn start_fence_harness(mut seed: CachedPerson, fallback: Option<PgFallback>) -> FenceHarness {
@@ -112,23 +112,21 @@ async fn start_fence_harness(mut seed: CachedPerson, fallback: Option<PgFallback
let dirty_index = Arc::new(DirtyIndex::new(1_000_000));
let locks = Arc::new(DashMap::new());
let fences: FenceMap = Arc::new(DashMap::new());
- // Recovery consumes the same mock cluster so a post-death cache miss
- // can recover the death document.
+ // Recovery consumes the same topic so a post-death cache miss can
+ // recover the death document.
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
fallback,
Arc::clone(&locks),
Arc::clone(&inflight),
NUM_PARTITIONS,
Arc::clone(&dirty_index),
- test_recovery(&bootstrap),
+ test_recovery(&mock_cluster.topic, &bootstrap),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::clone(&fences),
- None,
- None,
+ common::fenced_producers_acquired(&mock_cluster.topic, NUM_PARTITIONS as i32).await,
+ common::live_authority(),
Arc::clone(&emitted_versions),
);
@@ -164,7 +162,7 @@ async fn start_fence_harness(mut seed: CachedPerson, fallback: Option<PgFallback
locks,
fences,
_cancel: cancel,
- _mock_cluster: mock_cluster,
+ topic: mock_cluster,
}
}
@@ -177,7 +175,7 @@ fn changelog_records(harness: &FenceHarness) -> Vec<Person> {
.expect("failed to create consumer");
let mut tpl = TopicPartitionList::new();
tpl.add_partition_offset(
- CHANGELOG_TOPIC,
+ &harness.topic.topic,
harness.partition as i32,
rdkafka::Offset::Beginning,
)
@@ -1445,19 +1443,17 @@ async fn at_capacity_new_fences_shed_but_reseals_succeed() {
let (_mock_cluster, kafka_producer) = create_test_kafka().await;
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
Arc::new(DirtyIndex::new(1_000_000)),
- test_recovery(&_mock_cluster.bootstrap_servers()),
+ test_recovery(&_mock_cluster.topic, &_mock_cluster.bootstrap_servers()),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- None,
- None,
+ common::fenced_producers_acquired(&_mock_cluster.topic, NUM_PARTITIONS as i32).await,
+ common::live_authority(),
Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
)
.with_fence_capacity(1);
diff --git a/rust/personhog-leader/tests/fencing_integration.rs b/rust/personhog-leader/tests/fencing_integration.rs
index 82dff0cd4d68..dcc250f4c6cc 100644
--- a/rust/personhog-leader/tests/fencing_integration.rs
+++ b/rust/personhog-leader/tests/fencing_integration.rs
@@ -962,7 +962,7 @@ async fn healing_retakes_a_fence_for_a_served_partition() {
let clock = AuthorityClock::unclaimed();
clock.begin_session(Duration::from_secs(30), std::time::Instant::now());
- let outcome = heal_fence(&producers, &inflight, Some(&clock), 0).await;
+ let outcome = heal_fence(&producers, &inflight, &clock, 0).await;
assert_eq!(
outcome,
Ok(HealOutcome::Healed),
@@ -1003,7 +1003,7 @@ async fn healing_without_standing_does_not_steal_the_epoch() {
let lapsed = AuthorityClock::unclaimed();
lapsed.begin_session(Duration::from_secs(30), std::time::Instant::now());
lapsed.surrender();
- let outcome = heal_fence(&zombie, &inflight, Some(&lapsed), 0).await;
+ let outcome = heal_fence(&zombie, &inflight, &lapsed, 0).await;
assert_eq!(outcome, Ok(HealOutcome::Intact));
owner
@@ -1026,7 +1026,7 @@ async fn healing_skips_a_partition_under_handoff() {
let valid = AuthorityClock::unclaimed();
valid.begin_session(Duration::from_secs(30), std::time::Instant::now());
inflight.fence(0);
- let outcome = heal_fence(&other, &inflight, Some(&valid), 0).await;
+ let outcome = heal_fence(&other, &inflight, &valid, 0).await;
assert_eq!(outcome, Ok(HealOutcome::Intact));
owner
@@ -1054,7 +1054,7 @@ async fn healing_gives_back_a_fence_it_lost_standing_for() {
losing.surrender();
});
- let outcome = heal_fence(&producers, &inflight, Some(&clock), 0).await;
+ let outcome = heal_fence(&producers, &inflight, &clock, 0).await;
assert_ne!(
outcome,
Ok(HealOutcome::Healed),
@@ -1139,7 +1139,7 @@ async fn healing_leaves_a_fence_it_already_holds_alone() {
tokio::time::sleep(Duration::from_millis(100)).await;
// A reconcile tick with everything healthy.
- let outcome = heal_fence(&producers, &inflight, Some(&clock), 0).await;
+ let outcome = heal_fence(&producers, &inflight, &clock, 0).await;
assert_eq!(outcome, Ok(HealOutcome::Intact));
let result = writing.await.expect("the write task must not panic");
@@ -1875,8 +1875,6 @@ async fn an_unwound_committer_condemns_rather_than_stranding_its_waiters() {
async fn the_derived_production_timescales_compose_against_a_real_broker() {
let mut config =
personhog_leader::config::Config::init_from_env().expect("defaults are constructible");
- config.kafka_transactional_fencing = true;
- config.lease_gated_authority = true;
config.lease_ttl = 30;
config.fencing_txn_timeout_ms = 0;
config.fencing_message_timeout_ms = 0;
diff --git a/rust/personhog-leader/tests/integration.rs b/rust/personhog-leader/tests/integration.rs
index 8192ac582cfa..f9f5b6ae9547 100644
--- a/rust/personhog-leader/tests/integration.rs
+++ b/rust/personhog-leader/tests/integration.rs
@@ -13,7 +13,7 @@ use common::{
create_test_kafka_with_partitions, person_id_for_partition, seed_person, start_coordinator,
start_leader_pod, start_leader_pod_with_lease_ttl, start_leader_with_pg_fallback, start_router,
test_cached_person, test_recovery, test_store, test_warming_config, wait_for_condition,
- CHANGELOG_TOPIC, KAFKA_BOOTSTRAP, NUM_PARTITIONS, POLL_INTERVAL, WAIT_TIMEOUT,
+ KAFKA_BOOTSTRAP, NUM_PARTITIONS, POLL_INTERVAL, WAIT_TIMEOUT,
};
use personhog_common::partitioning::partition_for_person;
use personhog_coordination::pod::HandoffHandler;
@@ -33,7 +33,6 @@ use personhog_proto::personhog::types::v1::{
};
use prost::Message;
use rdkafka::consumer::{BaseConsumer, Consumer};
-use rdkafka::types::{RDKafkaApiKey, RDKafkaRespErr};
use rdkafka::{ClientConfig, Message as KafkaMessage, TopicPartitionList};
use tokio::net::TcpListener;
use tokio_util::sync::CancellationToken;
@@ -177,21 +176,22 @@ async fn unowned_partition_returns_failed_precondition() {
// Create service + cache directly, no coordination
let cache = Arc::new(PartitionedCache::new(1 << 20));
let (_mock_cluster, kafka_producer) = create_test_kafka().await;
+ // One set for both: a second would fence the first at the broker.
+ let fenced =
+ common::fenced_producers_acquired(&_mock_cluster.topic, NUM_PARTITIONS as i32).await;
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
Arc::new(DirtyIndex::new(1_000_000)),
- test_recovery(KAFKA_BOOTSTRAP),
+ test_recovery(&_mock_cluster.topic, KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- None,
- None,
+ Arc::clone(&fenced),
+ common::live_authority(),
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
);
@@ -262,21 +262,22 @@ async fn unowned_partition_returns_failed_precondition() {
async fn missing_partition_metadata_returns_invalid_argument() {
let cache = Arc::new(PartitionedCache::new(1 << 20));
let (_mock_cluster, kafka_producer) = create_test_kafka().await;
+ // One set for both: a second would fence the first at the broker.
+ let fenced =
+ common::fenced_producers_acquired(&_mock_cluster.topic, NUM_PARTITIONS as i32).await;
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
Arc::new(DirtyIndex::new(1_000_000)),
- test_recovery(KAFKA_BOOTSTRAP),
+ test_recovery(&_mock_cluster.topic, KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- None,
- None,
+ Arc::clone(&fenced),
+ common::live_authority(),
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
);
@@ -350,21 +351,22 @@ async fn missing_partition_metadata_returns_invalid_argument() {
async fn mismatched_partition_metadata_returns_invalid_argument() {
let cache = Arc::new(PartitionedCache::new(1 << 20));
let (_mock_cluster, kafka_producer) = create_test_kafka().await;
+ // One set for both: a second would fence the first at the broker.
+ let fenced =
+ common::fenced_producers_acquired(&_mock_cluster.topic, NUM_PARTITIONS as i32).await;
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
Arc::new(DirtyIndex::new(1_000_000)),
- test_recovery(KAFKA_BOOTSTRAP),
+ test_recovery(&_mock_cluster.topic, KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- None,
- None,
+ Arc::clone(&fenced),
+ common::live_authority(),
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
);
@@ -443,11 +445,12 @@ async fn writes_fenced_after_drain_reads_still_served() {
let (_mock_cluster, kafka_producer) = create_test_kafka().await;
let inflight = Arc::new(InflightTracker::new());
let dirty_index = Arc::new(DirtyIndex::new(1_000_000));
- let recovery = test_recovery(KAFKA_BOOTSTRAP);
+ let recovery = test_recovery(&_mock_cluster.topic, KAFKA_BOOTSTRAP);
+ // One set for both: a second would fence the first at the broker.
+ let fenced =
+ common::fenced_producers_acquired(&_mock_cluster.topic, NUM_PARTITIONS as i32).await;
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
Arc::clone(&inflight),
@@ -457,13 +460,13 @@ async fn writes_fenced_after_drain_reads_still_served() {
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- None,
- None,
+ Arc::clone(&fenced),
+ common::live_authority(),
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
);
// The handler shares the cache, inflight tracker, dirty index, and
// recovery pool with the service, exactly as main.rs wires them.
- let warming = test_warming_config("fence-pod", KAFKA_BOOTSTRAP);
+ let warming = test_warming_config("fence-pod", &_mock_cluster.topic, KAFKA_BOOTSTRAP);
let pools = Arc::new(WarmClientPools::new(
&warming.kafka,
"fence-pod",
@@ -478,8 +481,8 @@ async fn writes_fenced_after_drain_reads_still_served() {
None,
NUM_PARTITIONS,
pools,
- None,
- None,
+ Arc::clone(&fenced),
+ common::live_authority(),
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
);
@@ -548,11 +551,16 @@ async fn writes_fenced_after_drain_reads_still_served() {
serde_json::from_slice(&response.into_inner().person.unwrap().properties).unwrap();
assert_eq!(props["email"], "[email protected]");
- // Releasing clears the fence along with the partition: when the same
- // pod later re-acquires the partition (fresh warm), writes flow again.
+ // Releasing clears the fence along with the partition. The warm is
+ // stood in for, epoch included, since warming needs a changelog this
+ // test never writes.
handler.release_partition(0).await.unwrap();
cache.create_partition(0);
seed_person(&cache, 0, test_cached_person());
+ fenced
+ .acquire(0)
+ .await
+ .expect("the re-warm takes the epoch");
let response = client
.update_person_properties(update("[email protected]"))
.await
@@ -574,11 +582,12 @@ async fn drain_fences_before_waiting_on_inflight() {
let (_mock_cluster, kafka_producer) = create_test_kafka().await;
let inflight = Arc::new(InflightTracker::new());
let dirty_index = Arc::new(DirtyIndex::new(1_000_000));
- let recovery = test_recovery(KAFKA_BOOTSTRAP);
+ let recovery = test_recovery(&_mock_cluster.topic, KAFKA_BOOTSTRAP);
+ // One set for both: a second would fence the first at the broker.
+ let fenced =
+ common::fenced_producers_acquired(&_mock_cluster.topic, NUM_PARTITIONS as i32).await;
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
Arc::clone(&inflight),
@@ -588,11 +597,11 @@ async fn drain_fences_before_waiting_on_inflight() {
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- None,
- None,
+ Arc::clone(&fenced),
+ common::live_authority(),
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
);
- let warming = test_warming_config("fence-race-pod", KAFKA_BOOTSTRAP);
+ let warming = test_warming_config("fence-race-pod", &_mock_cluster.topic, KAFKA_BOOTSTRAP);
let pools = Arc::new(WarmClientPools::new(
&warming.kafka,
"fence-race-pod",
@@ -607,8 +616,8 @@ async fn drain_fences_before_waiting_on_inflight() {
None,
NUM_PARTITIONS,
pools,
- None,
- None,
+ Arc::clone(&fenced),
+ common::live_authority(),
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
));
@@ -906,19 +915,17 @@ async fn update_produces_person_state_to_kafka() {
let cache = Arc::new(PartitionedCache::new(1 << 20));
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
Arc::new(DirtyIndex::new(1_000_000)),
- test_recovery(KAFKA_BOOTSTRAP),
+ test_recovery(&mock_cluster.topic, KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- None,
- None,
+ common::fenced_producers_acquired(&mock_cluster.topic, 4).await,
+ common::live_authority(),
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
);
@@ -982,7 +989,7 @@ async fn update_produces_person_state_to_kafka() {
let mut tpl = TopicPartitionList::new();
tpl.add_partition_offset(
- CHANGELOG_TOPIC,
+ &mock_cluster.topic,
routing_partition as i32,
rdkafka::Offset::Beginning,
)
@@ -1012,30 +1019,30 @@ async fn update_produces_person_state_to_kafka() {
}
// ============================================================
-// Test 6: Kafka produce failure leaves cache unchanged and returns error
-// (no etcd needed)
+// Test 6: a changelog write this pod cannot land leaves the cache
+// unchanged and returns an error (no etcd needed)
// ============================================================
#[tokio::test]
async fn kafka_produce_failure_leaves_cache_unchanged() {
let cache = Arc::new(PartitionedCache::new(1 << 20));
let (mock_cluster, kafka_producer) = create_test_kafka().await;
+ let fenced =
+ common::fenced_producers_acquired(&mock_cluster.topic, NUM_PARTITIONS as i32).await;
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
Arc::new(DirtyIndex::new(1_000_000)),
- test_recovery(KAFKA_BOOTSTRAP),
+ test_recovery(&mock_cluster.topic, KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- None,
- None,
+ Arc::clone(&fenced),
+ common::live_authority(),
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
);
@@ -1060,9 +1067,10 @@ async fn kafka_produce_failure_leaves_cache_unchanged() {
});
tokio::time::sleep(Duration::from_millis(10)).await;
- // Inject a Kafka produce error
- let err = [RDKafkaRespErr::RD_KAFKA_RESP_ERR__BAD_MSG; 1];
- mock_cluster.request_errors(RDKafkaApiKey::Produce, &err);
+ // A successor takes the partition's transactional id, which is what
+ // a changelog write this pod cannot land looks like.
+ let successor =
+ common::fenced_producers_acquired(&mock_cluster.topic, NUM_PARTITIONS as i32).await;
let mut client = create_leader_client(addr).await;
@@ -1086,7 +1094,11 @@ async fn kafka_produce_failure_leaves_cache_unchanged() {
.await;
assert!(result.is_err());
- assert_eq!(result.unwrap_err().code(), tonic::Code::Internal);
+ assert_eq!(
+ result.unwrap_err().code(),
+ tonic::Code::FailedPrecondition,
+ "a fenced pod answers in the ownership vocabulary, so the router re-resolves"
+ );
// Cache was never updated since the produce failed before the cache write
let cache_key = PersonCacheKey {
@@ -1103,8 +1115,13 @@ async fn kafka_produce_failure_leaves_cache_unchanged() {
);
assert!(cached.parse_properties().unwrap().get("name").is_none());
- // Clear errors and verify the service recovers
- mock_cluster.clear_request_errors(RDKafkaApiKey::Produce);
+ // This pod re-takes the epoch, as the convergence heal does.
+ drop(successor);
+ fenced.expect_self_fence(0);
+ fenced
+ .acquire(0)
+ .await
+ .expect("this pod re-takes the fence");
let response = client
.update_person_properties(with_partition(
@@ -1127,18 +1144,12 @@ async fn kafka_produce_failure_leaves_cache_unchanged() {
let result = response.into_inner();
assert!(result.updated);
- // Three, not two: the failed write's version is spent. The produce
- // path cannot tell an enqueue that never left the client from a
- // delivery that timed out after the broker appended it, and
- // idempotence is off by default — so reusing that number would put a
- // second record behind one that may be in the log, and the writer's
- // strict guard keeps whichever arrived first. Burning a version on a
- // write that genuinely never landed is the cheap side of that trade:
- // versions are a monotonic counter with no meaning attached to gaps.
+ // Two, not three: a record the broker refused never existed, so its
+ // version is free again.
assert_eq!(
result.person.unwrap().version,
- 3,
- "a version put on the wire must not be reused, even when the write failed"
+ 2,
+ "a version the broker refused is not spent"
);
cancel.cancel();
@@ -1151,24 +1162,24 @@ async fn kafka_produce_failure_leaves_cache_unchanged() {
#[tokio::test]
async fn e2e_update_produces_to_local_kafka() {
+ let owned = common::owned_broker_topic(NUM_PARTITIONS as i32).await;
+ let topic = owned.topic.clone();
let cache = Arc::new(PartitionedCache::new(1 << 20));
let kafka_producer = create_local_kafka_producer().await;
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
Arc::new(DirtyIndex::new(1_000_000)),
- test_recovery(KAFKA_BOOTSTRAP),
+ test_recovery(&topic, KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- None,
- None,
+ common::fenced_producers_acquired(&topic, NUM_PARTITIONS as i32).await,
+ common::live_authority(),
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
);
@@ -1226,26 +1237,15 @@ async fn e2e_update_produces_to_local_kafka() {
.create()
.expect("failed to create local Kafka consumer");
+ // From the beginning: counting back from the end lands on the
+ // transaction's commit marker, which no consumer is handed.
let mut tpl = TopicPartitionList::new();
- tpl.add_partition_offset(CHANGELOG_TOPIC, 0, rdkafka::Offset::End)
+ tpl.add_partition_offset(&topic, 0, rdkafka::Offset::Beginning)
.unwrap();
consumer.assign(&tpl).unwrap();
- // Seek back one message from the end to read what we just produced.
- // End offset points past the last message, so we query it and subtract 1.
- let (_, high_watermark) = consumer
- .fetch_watermarks(CHANGELOG_TOPIC, 0, Duration::from_secs(5))
- .expect("failed to fetch watermarks");
- let target_offset = (high_watermark - 1).max(0);
-
- let mut seek_tpl = TopicPartitionList::new();
- seek_tpl
- .add_partition_offset(CHANGELOG_TOPIC, 0, rdkafka::Offset::Offset(target_offset))
- .unwrap();
- consumer.assign(&seek_tpl).unwrap();
-
let msg = consumer
- .poll(Duration::from_secs(5))
+ .poll(Duration::from_secs(10))
.expect("no message received from local Kafka")
.expect("kafka error");
@@ -1503,11 +1503,9 @@ async fn evicted_dirty_person_recovers_from_changelog() {
// Recovery reads from the same mock broker the update produces to.
// Deliberately no PG pool: a recovery path that (wrongly) fell back to
// PG would return NotFound and fail the final assertion.
- let recovery = test_recovery(&mock_cluster.bootstrap_servers());
+ let recovery = test_recovery(&mock_cluster.topic, &mock_cluster.bootstrap_servers());
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
@@ -1517,8 +1515,8 @@ async fn evicted_dirty_person_recovers_from_changelog() {
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- None,
- None,
+ common::fenced_producers_acquired(&mock_cluster.topic, 4).await,
+ common::live_authority(),
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
);
@@ -1608,11 +1606,9 @@ async fn dirty_person_with_failed_recovery_is_unavailable_not_stale() {
let cache = Arc::new(PartitionedCache::new(1 << 20));
let dirty_index = Arc::new(DirtyIndex::new(1_000_000));
- let recovery = test_recovery(&mock_cluster.bootstrap_servers());
+ let recovery = test_recovery(&mock_cluster.topic, &mock_cluster.bootstrap_servers());
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
@@ -1622,8 +1618,8 @@ async fn dirty_person_with_failed_recovery_is_unavailable_not_stale() {
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- None,
- None,
+ common::fenced_producers_acquired(&mock_cluster.topic, 4).await,
+ common::live_authority(),
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
);
@@ -1723,19 +1719,17 @@ async fn writes_shed_when_dirty_index_is_full() {
let dirty_index = Arc::new(DirtyIndex::new(1));
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
Arc::clone(&dirty_index),
- test_recovery(&mock_cluster.bootstrap_servers()),
+ test_recovery(&mock_cluster.topic, &mock_cluster.bootstrap_servers()),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- None,
- None,
+ common::fenced_producers_acquired(&mock_cluster.topic, 4).await,
+ common::live_authority(),
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
);
@@ -1822,11 +1816,9 @@ async fn recovery_fails_when_record_version_disagrees_with_the_mark() {
let cache = Arc::new(PartitionedCache::new(1 << 20));
let dirty_index = Arc::new(DirtyIndex::new(1_000_000));
- let recovery = test_recovery(&mock_cluster.bootstrap_servers());
+ let recovery = test_recovery(&mock_cluster.topic, &mock_cluster.bootstrap_servers());
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
@@ -1836,8 +1828,8 @@ async fn recovery_fails_when_record_version_disagrees_with_the_mark() {
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- None,
- None,
+ common::fenced_producers_acquired(&mock_cluster.topic, 4).await,
+ common::live_authority(),
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
);
@@ -1934,11 +1926,9 @@ async fn recovery_reuses_the_partition_consumer_across_fetches() {
let (mock_cluster, kafka_producer) = create_test_kafka_with_partitions(4).await;
let cache = Arc::new(PartitionedCache::new(1 << 20));
let dirty_index = Arc::new(DirtyIndex::new(1_000_000));
- let recovery = test_recovery(&mock_cluster.bootstrap_servers());
+ let recovery = test_recovery(&mock_cluster.topic, &mock_cluster.bootstrap_servers());
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
@@ -1948,8 +1938,8 @@ async fn recovery_reuses_the_partition_consumer_across_fetches() {
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- None,
- None,
+ common::fenced_producers_acquired(&mock_cluster.topic, 4).await,
+ common::live_authority(),
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
);
@@ -2064,7 +2054,7 @@ async fn cancelled_recovery_returns_its_consumer_to_the_pool() {
// pool_size 1: a single leaked consumer exhausts the pool.
let recovery = ChangelogRecovery::new(RecoveryConfig {
kafka,
- topic: CHANGELOG_TOPIC.to_string(),
+ topic: mock_cluster.topic.clone(),
pod_name: "cancel-pod".to_string(),
recv_timeout: Duration::from_secs(2),
pool_size: 1,
@@ -2115,7 +2105,7 @@ async fn cancelled_recovery_returns_its_consumer_to_the_pool() {
let payload = person.encode_to_vec();
producer
.send(
- FutureRecord::to(CHANGELOG_TOPIC)
+ FutureRecord::to(&mock_cluster.topic)
.key("1:7")
.partition(0)
.payload(&payload),
@@ -2144,19 +2134,15 @@ async fn oversize_updates_are_rejected_and_oversized_rows_remediated() {
const PERSON_ID: i64 = 9;
let routing_partition: u32 = partition_for_person(1, PERSON_ID, NUM_PARTITIONS);
let (mock_cluster, kafka_producer) = create_test_kafka_with_partitions(4).await;
- // The warnings topic is not auto-created; the fire-and-forget emit
- // would silently drop without it.
- mock_cluster
- .create_topic("clickhouse_ingestion_warnings", 1, 1)
- .unwrap();
+ // This test reads its warnings back, so they must be its own: on a
+ // shared topic it would collect whichever two arrived first.
+ let warnings_topic = common::owned_broker_topic(1).await;
let cache = Arc::new(PartitionedCache::new(1 << 20));
let dirty_index = Arc::new(DirtyIndex::new(1_000_000));
- let recovery = test_recovery(&mock_cluster.bootstrap_servers());
+ let recovery = test_recovery(&mock_cluster.topic, &mock_cluster.bootstrap_servers());
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
@@ -2169,12 +2155,12 @@ async fn oversize_updates_are_rejected_and_oversized_rows_remediated() {
// exercises suppression.
WarningsProducer::with_throttle(
kafka_producer,
- "clickhouse_ingestion_warnings".to_string(),
+ warnings_topic.topic.clone(),
WarningThrottle::new(DEFAULT_THROTTLE_PERIOD, NonZeroU32::new(2).unwrap()),
),
Arc::new(DashMap::new()),
- None,
- None,
+ common::fenced_producers_acquired(&mock_cluster.topic, 4).await,
+ common::live_authority(),
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
);
@@ -2399,12 +2385,8 @@ async fn oversize_updates_are_rejected_and_oversized_rows_remediated() {
.create()
.unwrap();
let mut tpl = TopicPartitionList::new();
- tpl.add_partition_offset(
- "clickhouse_ingestion_warnings",
- 0,
- rdkafka::Offset::Beginning,
- )
- .unwrap();
+ tpl.add_partition_offset(&warnings_topic.topic, 0, rdkafka::Offset::Beginning)
+ .unwrap();
consumer.assign(&tpl).unwrap();
let mut warnings = Vec::new();
let deadline = Instant::now() + Duration::from_secs(10);
@@ -2620,22 +2602,23 @@ async fn oversize_updates_are_rejected_and_oversized_rows_remediated() {
async fn an_unresolved_version_is_never_reused() {
let cache = Arc::new(PartitionedCache::new(1 << 20));
let (_mock_cluster, kafka_producer) = create_test_kafka().await;
+ // One set for both: a second would fence the first at the broker.
+ let fenced =
+ common::fenced_producers_acquired(&_mock_cluster.topic, NUM_PARTITIONS as i32).await;
let emitted_versions = Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000));
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- CHANGELOG_TOPIC.to_string(),
None,
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
Arc::new(DirtyIndex::new(1_000_000)),
- test_recovery(KAFKA_BOOTSTRAP),
+ test_recovery(&_mock_cluster.topic, KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- None,
- None,
+ Arc::clone(&fenced),
+ common::live_authority(),
Arc::clone(&emitted_versions),
);
@@ -2706,19 +2689,17 @@ async fn a_fenced_write_that_bounces_does_not_hand_its_version_back() {
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- topic.clone(),
None,
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
Arc::new(DirtyIndex::new(1_000_000)),
- test_recovery(KAFKA_BOOTSTRAP),
+ test_recovery(&_mock_cluster.topic, KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- Some(Arc::clone(&fenced)),
- None,
+ Arc::clone(&fenced),
+ common::live_authority(),
std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),
);
@@ -2827,19 +2808,17 @@ async fn an_unknown_outcome_keeps_its_version(
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- topic.clone(),
None,
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
Arc::new(DirtyIndex::new(1_000_000)),
- test_recovery(KAFKA_BOOTSTRAP),
+ test_recovery(&_mock_cluster.topic, KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- Some(Arc::clone(&fenced)),
- None,
+ Arc::clone(&fenced),
+ common::live_authority(),
Arc::clone(&emitted_versions),
);
@@ -2917,19 +2896,17 @@ async fn scalar_fields_merge_rather_than_assign() {
let service = PersonHogLeaderService::new(
Arc::clone(&cache),
- kafka_producer.clone(),
- topic.clone(),
None,
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
Arc::new(DirtyIndex::new(1_000_000)),
- test_recovery(KAFKA_BOOTSTRAP),
+ test_recovery(&_mock_cluster.topic, KAFKA_BOOTSTRAP),
PropertySizeLimits::new(655360, 524288),
WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),
Arc::new(DashMap::new()),
- None,
- None,
+ common::fenced_producers_acquired(&topic, NUM_PARTITIONS as i32).await,
+ common::live_authority(),
Arc::clone(&emitted_versions),
);
diff --git a/rust/personhog-leader/tests/warming_integration.rs b/rust/personhog-leader/tests/warming_integration.rs
index 901806879b4e..9536e172cd0c 100644
--- a/rust/personhog-leader/tests/warming_integration.rs
+++ b/rust/personhog-leader/tests/warming_integration.rs
@@ -7,7 +7,7 @@ mod common;
use std::sync::Arc;
use std::time::Duration;
-use common::{create_test_kafka, test_warming_config, CHANGELOG_TOPIC, NUM_PARTITIONS};
+use common::{create_mock_kafka, test_warming_config, CHANGELOG_TOPIC, NUM_PARTITIONS};
use personhog_leader::cache::{CacheLookup, DirtyIndex, PartitionedCache, PersonCacheKey};
use personhog_leader::warming::{warm_from_kafka, WarmClientPools, WarmingConfig};
use personhog_proto::personhog::types::v1::Person;
@@ -85,7 +85,7 @@ fn warming_config_for(
pod_name: &str,
cluster: &MockCluster<'static, DefaultProducerContext>,
) -> (WarmingConfig, WarmClientPools) {
- let cfg = test_warming_config(pod_name, &cluster.bootstrap_servers());
+ let cfg = test_warming_config(pod_name, CHANGELOG_TOPIC, &cluster.bootstrap_servers());
let pools = WarmClientPools::new(&cfg.kafka, pod_name, &cfg.writer_consumer_group);
(cfg, pools)
}
@@ -96,7 +96,7 @@ fn warming_config_for(
/// distinct `person_id`s produce distinct entries that we can count.
#[tokio::test]
async fn warming_populates_cache_from_kafka() {
- let (cluster, producer) = create_test_kafka().await;
+ let (cluster, producer) = create_mock_kafka().await;
// Produce 5 records to partition 0.
for person_id in 1..=5 {
@@ -134,7 +134,7 @@ async fn warming_populates_cache_from_kafka() {
/// owned (so future routes find a cache entry) but with no records.
#[tokio::test]
async fn warming_handles_empty_partition() {
- let (cluster, _producer) = create_test_kafka().await;
+ let (cluster, _producer) = create_mock_kafka().await;
let cache = PartitionedCache::new(1 << 20);
let (cfg, pools) = warming_config_for("warmer-empty", &cluster);
@@ -175,7 +175,7 @@ async fn warming_handles_empty_partition() {
/// is correctly scoped.
#[tokio::test]
async fn warming_only_populates_target_partition() {
- let (cluster, producer) = create_test_kafka().await;
+ let (cluster, producer) = create_mock_kafka().await;
// Produce one record to partition 0 and one to partition 1.
produce_person_to_partition(&producer, 0, &make_person(1, 100)).await;
@@ -209,7 +209,7 @@ async fn warming_only_populates_target_partition() {
/// before the bad one) would silently mask PG fallback reads.
#[tokio::test]
async fn warming_fails_loudly_on_decode_error_and_leaves_cache_clean() {
- let (cluster, producer) = create_test_kafka().await;
+ let (cluster, producer) = create_mock_kafka().await;
// Produce a valid record, then a garbage one. Warming should buffer
// the valid record locally, hit the garbage on the next iteration,
@@ -236,7 +236,7 @@ async fn warming_fails_loudly_on_decode_error_and_leaves_cache_clean() {
/// per-partition consumer setup leaks state across calls.
#[tokio::test]
async fn warming_works_across_all_partitions() {
- let (cluster, producer) = create_test_kafka().await;
+ let (cluster, producer) = create_mock_kafka().await;
// Produce one record to each partition with a partition-specific
// person_id so we can verify the right record landed in each cache
@@ -300,7 +300,7 @@ fn commit_writer_offset_at(
/// assert only records with offsets ≥ 5 land in the cache.
#[tokio::test]
async fn warming_starts_from_writer_committed_offset() {
- let (cluster, producer) = create_test_kafka().await;
+ let (cluster, producer) = create_mock_kafka().await;
// Produce 8 records to partition 0. person_id matches offset for
// easy assertion (offset N → person_id N+1).
@@ -358,7 +358,7 @@ async fn warming_starts_from_writer_committed_offset() {
/// only exercises the proto branch.
#[tokio::test]
async fn warming_fails_loudly_on_properties_json_error() {
- let (cluster, producer) = create_test_kafka().await;
+ let (cluster, producer) = create_mock_kafka().await;
// Valid record first so warming actually enters the consume loop
// and buffers something before hitting the failure.
@@ -419,7 +419,7 @@ async fn warming_fails_loudly_on_properties_json_error() {
/// version field, which the writer increments per update.
#[tokio::test]
async fn warming_preserves_last_write_for_same_key() {
- let (cluster, producer) = create_test_kafka().await;
+ let (cluster, producer) = create_mock_kafka().await;
// Three sequential updates for the same person, each with an
// incrementing version. Producing in order to the same partition
@@ -475,7 +475,7 @@ async fn warming_preserves_last_write_for_same_key() {
/// unapplied ones would reopen the stale-fallback hole.
#[tokio::test]
async fn warming_seeds_dirty_index_only_at_or_past_the_committed_offset() {
- let (cluster, producer) = create_test_kafka().await;
+ let (cluster, producer) = create_mock_kafka().await;
// Offset N → person_id N+1.
for i in 0..8 {
@@ -527,7 +527,7 @@ async fn warming_seeds_dirty_index_only_at_or_past_the_committed_offset() {
/// applied record of another key still warms.
#[tokio::test]
async fn warming_skips_applied_death_records() {
- let (cluster, producer) = create_test_kafka().await;
+ let (cluster, producer) = create_mock_kafka().await;
// Key 1: live then death. Key 2: live only. Key 3: live, death,
// then a revival record.
@@ -624,7 +624,7 @@ async fn warming_skips_applied_death_records() {
/// trusting a PG row the writer never wrote.
#[tokio::test]
async fn warming_seeds_dirty_index_when_writer_has_no_commits() {
- let (cluster, producer) = create_test_kafka().await;
+ let (cluster, producer) = create_mock_kafka().await;
for person_id in 1..=3 {
let person = make_person(1, person_id);
@@ -654,7 +654,7 @@ async fn warming_seeds_dirty_index_when_writer_has_no_commits() {
/// created-count stays at pool size while operations keep flowing.
#[tokio::test]
async fn sequential_warms_reuse_pooled_clients() {
- let (cluster, producer) = create_test_kafka().await;
+ let (cluster, producer) = create_mock_kafka().await;
for person_id in 1..=3 {
let person = make_person(1, person_id);
@@ -691,7 +691,7 @@ async fn sequential_warms_reuse_pooled_clients() {
/// handoff path.
#[tokio::test]
async fn warm_up_fills_every_slot() {
- let (cluster, _producer) = create_test_kafka().await;
+ let (cluster, _producer) = create_mock_kafka().await;
let (_cfg, pools) = warming_config_for("warmer-prewarm", &cluster);
pools.warming.warm_up(3).await;
@@ -711,7 +711,7 @@ async fn warm_up_fills_every_slot() {
/// tore down every partition that pod was converging.
#[tokio::test]
async fn warming_tolerates_a_transient_consumer_error() {
- let (cluster, producer) = create_test_kafka().await;
+ let (cluster, producer) = create_mock_kafka().await;
for person_id in 1..=3 {
let person = make_person(1, person_id);
@@ -755,7 +755,7 @@ async fn warming_tolerates_a_transient_consumer_error() {
/// publish a partial cache.
#[tokio::test]
async fn warming_still_fails_on_a_persistent_stop_class_error() {
- let (cluster, producer) = create_test_kafka().await;
+ let (cluster, producer) = create_mock_kafka().await;
for person_id in 1..=3 {
let person = make_person(1, person_id);
@@ -797,7 +797,7 @@ async fn warming_still_fails_on_a_persistent_stop_class_error() {
/// warm survive a backlog-sized range without holding it in memory.
#[tokio::test]
async fn warming_a_range_larger_than_the_budget_marks_every_person() {
- let (cluster, producer) = create_test_kafka().await;
+ let (cluster, producer) = create_mock_kafka().await;
// Forty persons with ~4KB of properties each — far past the tiny
// budget below — with no writer committed offset, so every record
@@ -848,7 +848,7 @@ async fn warming_a_range_larger_than_the_budget_marks_every_person() {
/// warming partition keeps its marks until publish.
#[tokio::test]
async fn the_prune_tick_settles_published_partitions_only() {
- let (cluster, _producer) = create_test_kafka().await;
+ let (cluster, _producer) = create_mock_kafka().await;
let (_cfg, pools) = warming_config_for("prune-tick", &cluster);
let cache = PartitionedCache::new(1 << 20);
@@ -928,7 +928,7 @@ async fn the_prune_tick_settles_published_partitions_only() {
/// loop must run to exhaustion, not stop after the first slice.
#[tokio::test]
async fn the_prune_tick_drains_a_multi_chunk_death_backlog() {
- let (cluster, _producer) = create_test_kafka().await;
+ let (cluster, _producer) = create_mock_kafka().await;
let (_cfg, pools) = warming_config_for("prune-tick-backlog", &cluster);
let cache = PartitionedCache::new(1 << 20);
diff --git a/rust/personhog-stateright/README.md b/rust/personhog-stateright/README.md
index 2ed49d20932b..9104c4068684 100644
--- a/rust/personhog-stateright/README.md
+++ b/rust/personhog-stateright/README.md
@@ -28,25 +28,24 @@ web explorer.
Configurations are deliberately small — state spaces grow
combinatorially, and protocol bugs are structural, showing up at
minimum viable scale or not at all.
-The suite explores ~24M states across 31 runs.
-Its long pole is the two-partition epoch-fenced double zombie, which is more than half the wall clock on its own:
+The suite explores ~28.5M states across 28 runs.
+Its long pole is the two-partition epoch-fenced double zombie, which is about half the wall clock on its own:
| Scenario | Unique states | Wall time |
|---|---|---|
-| `epoch_fenced_two_partitions_double_zombie_is_safe` | 13.1M | 19s |
-| `two_partitions_double_zombie_loses_acked_writes` | 3.7M | 4.0s |
-| `cancellation_with_live_owner_reaffirms_and_resumes` | 2.6M | 3.9s |
-| `current_two_partitions_single_zombie_is_safe` | 0.9M | 1.4s |
-| `probe_dual_role_pod_is_reachable_and_safe` | 0.7M | 1.2s |
-| *everything else (26 runs)* | 3.4M | 4s |
+| `epoch_fenced_two_partitions_double_zombie_is_safe` | 13.1M | 19.1s |
+| `rollout_quota_mode_is_safe_and_live` | 3.5M | 5.1s |
+| `cancellation_with_live_owner_reaffirms_and_resumes` | 3.2M | 4.2s |
+| `chunked_plan_application_is_safe_and_live` | 2.1M | 2.7s |
+| `probe_chunked_pending_units_reach_both_fates_safely` | 2.1M | 3.2s |
+| *everything else (23 runs)* | 4.4M | 6s |
Roughly: a second partition costs ~20x, a second failure in the budget ~10x, a third pod ~2x.
-Times are release mode, one scenario at a time on 14 cores — a CI runner with 4 slower cores is several times that, so treat them as ratios rather than absolutes.
+Times are release mode, one scenario at a time on 12 cores — a CI runner with 4 slower cores is several times that, so treat them as ratios rather than absolutes.
-The test suite (twenty-odd scenarios; the heavy double-zombie pair dominates the runtime) runs the full
-verdict matrix — the 1-partition scenarios, the 2-partition cases
-including both double-zombie verdicts, the 3-pod rejoin, and the
-reachability probes. Two partitions matter for the coordinator's
+The test suite (twenty-odd scenarios; the two-partition double zombie dominates the runtime) runs the full
+verdict matrix — the 1-partition scenarios, the 2-partition cases, the
+3-pod rejoin, and the reachability probes. Two partitions matter for the coordinator's
cross-partition scheduling (rebalancing defers while any handoff is in
flight); the safety invariants themselves are per-partition, which is
why every violation class reproduces at one.
@@ -121,7 +120,7 @@ queue — mapped to named production behavior for review:
| `Action::ClientWrite` | The raw proxy leader path: stash if stashing, else forward to the table entry; leader admission = warmed + unfenced (`try_begin`) |
| `Action::CrashRestartWithinTtl` | Process death + same-name restart before lease expiry: registration and assignments survive, memory wiped |
| `Action::LeaseExpire` / `SelfFence` | Lease loss with the bounded zombie window before the keepalive self-fences (fix 1); same pair for routers, where lease loss also drops them from the freeze quorum |
-| `Changelog.epoch_holder` under `Variant::EpochFenced` | Kafka transactional-producer fencing: warming = `init_transactions`, which takes the fence from whoever held it; a produce from a fenced-out producer is rejected before any client ack |
+| `Changelog.epoch_holder` | Kafka transactional-producer fencing: warming = `init_transactions`, which takes the fence from whoever held it; a produce from a fenced-out producer is rejected before any client ack |
Full elimination of the second table would mean deterministic
simulation — a trait seam over `PersonhogStore` with an in-memory
@@ -142,13 +141,12 @@ implementation so the model executes `converge` and
| Scenario | `no_lost_acked_write` | `no_split_write_acceptance` | `strong_reads_complete` |
|---|---|---|---|
-| Current protocol, no failures | holds | holds | holds |
-| Current, crash-restart within TTL / clean lease expiry | holds | holds | holds |
-| Current, pod death past TTL + rejoin (3 pods) | holds | holds | holds |
-| Current, single zombie pod | **holds** | **holds** | holds |
-| Current, double zombie (router + pod) | **violated** — counterexample found | **violated** | — |
-| Epoch-fenced, double zombie | holds | holds | holds |
-| Current, strong reads + one failure | holds | holds | holds |
+| No failures | holds | holds | holds |
+| Crash-restart within TTL / clean lease expiry | holds | holds | holds |
+| Pod death past TTL + rejoin (3 pods) | holds | holds | holds |
+| Single zombie pod | **holds** | **holds** | holds |
+| Double zombie (router + pod) | holds | holds | holds |
+| Strong reads + one failure | holds | holds | holds |
Two results worth calling out:
@@ -162,10 +160,12 @@ below the warm HWM and is captured. The checker sharpened the
documented residual from "a zombie pod" to "a zombie router feeding a
zombie pod, simultaneously."
-**Epoch fencing closes the double zombie.** Under the `EpochFenced`
-variant, warming bumps the broker's producer epoch, and the zombie's
-produce is rejected before any client ack. This is the design
-validation gating the transactional-producer implementation.
+**Epoch fencing closes the double zombie.** Warming bumps the broker's
+producer epoch, and the zombie's produce is rejected before any client
+ack. The model carried an unfenced variant until the leader stopped
+being able to run one; the counterexample it produced is the reason the
+protocol is shaped this way, and it lives in this repository's history
+rather than in a checked property.
**Read stashing was machine-validated before it shipped.** A
direct-read variant of this model (strong reads forwarding to the table
@@ -208,13 +208,13 @@ cargo test -p personhog-stateright --release
STATERIGHT_REPORT=1 cargo test -p personhog-stateright --release -- --nocapture --test-threads=1
# Interactive state-space explorer (http://localhost:3000), for
-# stepping through the double-zombie counterexample trace:
-cargo run -p personhog-stateright --release -- current-zombie
+# stepping through a trace state by state:
+cargo run -p personhog-stateright --release -- fenced-zombie
```
-Explorer variants: `current` (failures without zombie windows),
-`current-zombie` (the residual, with counterexamples), `epoch-fenced`
-(the fix).
+Explorer scenarios: `fenced` (failures without zombie windows),
+`fenced-zombie` (a zombie window), `fenced-read-first` (the rejected
+warm ordering, with counterexamples).
## Coverage notes
diff --git a/rust/personhog-stateright/src/main.rs b/rust/personhog-stateright/src/main.rs
index d7639c3f56ef..859084d8d190 100644
--- a/rust/personhog-stateright/src/main.rs
+++ b/rust/personhog-stateright/src/main.rs
@@ -1,9 +1,9 @@
//! Interactive explorer for the handoff-protocol model.
//!
//! ```sh
-//! cargo run -p personhog-stateright -- current
-//! cargo run -p personhog-stateright -- current-zombie
-//! cargo run -p personhog-stateright -- epoch-fenced
+//! cargo run -p personhog-stateright -- fenced
+//! cargo run -p personhog-stateright -- fenced-zombie
+//! cargo run -p personhog-stateright -- fenced-read-first
//! ```
//!
//! Serves the Stateright web UI at http://localhost:3000 for stepping
@@ -11,7 +11,7 @@
use clap::{Parser, ValueEnum};
-use personhog_stateright::model::{ClaimDetection, HandoffModel, Variant, WarmOrder};
+use personhog_stateright::model::{ClaimDetection, HandoffModel, WarmOrder};
use stateright::Model;
#[derive(Parser)]
@@ -23,23 +23,20 @@ struct Args {
#[derive(Clone, Copy, Debug, ValueEnum)]
enum Scenario {
/// Failures without zombie windows.
- Current,
- /// The double-zombie residual, with counterexamples.
- CurrentZombie,
- /// The epoch-fencing fix.
- EpochFenced,
+ Fenced,
+ /// A zombie window, which epoch fencing closes.
+ FencedZombie,
/// The rejected warm ordering (read before fence), with
/// counterexamples.
- EpochFencedReadFirst,
+ FencedReadFirst,
}
fn main() {
let args = Args::parse();
- let (variant, warm_order, crashes, zombie_window) = match args.scenario {
- Scenario::Current => (Variant::Current, WarmOrder::FenceFirst, 1, 0),
- Scenario::CurrentZombie => (Variant::Current, WarmOrder::FenceFirst, 1, 1),
- Scenario::EpochFenced => (Variant::EpochFenced, WarmOrder::FenceFirst, 1, 1),
- Scenario::EpochFencedReadFirst => (Variant::EpochFenced, WarmOrder::ReadFirst, 2, 1),
+ let (warm_order, crashes, zombie_window) = match args.scenario {
+ Scenario::Fenced => (WarmOrder::FenceFirst, 1, 0),
+ Scenario::FencedZombie => (WarmOrder::FenceFirst, 1, 1),
+ Scenario::FencedReadFirst => (WarmOrder::ReadFirst, 2, 1),
};
let model = HandoffModel {
@@ -47,9 +44,8 @@ fn main() {
routers: 2,
late_routers: 0,
partitions: 1,
- variant,
warm_order,
- lease_gated_reads: false,
+ claim_lapses: true,
claim_recovers: true,
claim_detection: ClaimDetection::Prompt,
writes: 2,
diff --git a/rust/personhog-stateright/src/model.rs b/rust/personhog-stateright/src/model.rs
index 762d6575c914..25cb1a6b123f 100644
--- a/rust/personhog-stateright/src/model.rs
+++ b/rust/personhog-stateright/src/model.rs
@@ -68,18 +68,6 @@ fn production_quorum(h: &Handoff) -> Vec<String> {
h.quorum.iter().map(|r| router_name(*r)).collect()
}
-/// Which produce-path protection the model runs with.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum Variant {
- /// The shipped protocol: leases + self-fencing bound the zombie
- /// window but nothing rejects a zombie's produce at the broker.
- Current,
- /// The proposed fix: per-partition Kafka transactional producers.
- /// Warming bumps the broker's producer epoch (`init_transactions`),
- /// and the broker rejects produces bearing a stale epoch.
- EpochFenced,
-}
-
/// How promptly a pod learns that its lease is gone.
///
/// The keepalive only finds out on its next round, so a revoked lease
@@ -95,10 +83,8 @@ pub enum ClaimDetection {
Delayed,
}
-/// Which side of the warm read acquires the broker fence, under
-/// `Variant::EpochFenced`. `warm_partition` ships `FenceFirst`;
-/// `ReadFirst` is the rejected ordering, kept checkable as the machine
-/// record of why the fence must precede the read.
+/// Which side of the warm read takes the broker fence. `warm_partition`
+/// ships `FenceFirst`; `ReadFirst` is kept as the record of why.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WarmOrder {
FenceFirst,
@@ -115,18 +101,15 @@ pub struct HandoffModel {
/// they exist only to `RouterJoin` mid-run.
pub late_routers: u8,
pub partitions: u8,
- pub variant: Variant,
/// Fence-vs-read ordering of the decomposed warm; ignored under
- /// `Variant::Current`, whose warm is a single atomic step.
+ /// a warm that is a single atomic step.
pub warm_order: WarmOrder,
/// How promptly a pod notices its lease is gone; only meaningful
- /// with `lease_gated_reads`, since nothing else consults the claim.
+ /// since the read gate is the only thing that consults the claim.
pub claim_detection: ClaimDetection,
- /// Whether a pod consults its lease before serving a strong read
- /// (production: the leader's `LEASE_GATED_AUTHORITY`). Without it a
- /// pod that has lost its registration keeps answering out of a cache
- /// the new owner is already changing.
- pub lease_gated_reads: bool,
+ /// Whether a registered pod's claim may lapse. Only the read gate and
+ /// `converges_to_stable` read the claim, so off is safe elsewhere.
+ pub claim_lapses: bool,
/// Whether a lapsed claim can come back without the session ending
/// (production: the keepalive confirming a renewal again). Turning it
/// off is what makes the black hole permanent, which is the only way
@@ -293,14 +276,11 @@ impl HandoffModel {
if pod.fenced.contains(&partition) {
return false;
}
- match self.variant {
- Variant::Current => true,
- // The broker accepts one producer per partition — whichever
- // acquired the fence most recently. A warmed pod that is no
- // longer the holder would be producing under a fenced-out
- // producer, and the broker rejects it before any client ack.
- Variant::EpochFenced => state.changelogs[&partition].epoch_holder == Some(x),
- }
+ // The broker accepts one producer per partition, whichever
+ // acquired the fence most recently. A warmed pod that is no
+ // longer the holder would be producing under a fenced-out
+ // producer, and the broker rejects it before any client ack.
+ state.changelogs[&partition].epoch_holder == Some(x)
}
/// One step of `warm_partition` for pod `x` on `partition`. Under
@@ -333,14 +313,11 @@ impl HandoffModel {
// enumeration. If the no-observable-gap argument ever stops
// holding (an append path that does not require an installed
// warm), this collapse is the assumption to revisit first.
- let observable_gap =
- self.variant == Variant::EpochFenced && self.warm_order == WarmOrder::ReadFirst;
+ let observable_gap = self.warm_order == WarmOrder::ReadFirst;
if !observable_gap {
let warm = {
let log = state.changelogs.get_mut(&partition).unwrap();
- if self.variant == Variant::EpochFenced {
- log.epoch_holder = Some(x);
- }
+ log.epoch_holder = Some(x);
WarmState {
for_handoff,
visible: log.len,
@@ -436,7 +413,7 @@ impl HandoffModel {
// that window, and the property holding here does not cover it —
// it is recorded as a residual in the coordination README rather
// than claimed as closed.
- if self.lease_gated_reads && !pod.claims_authority {
+ if !pod.claims_authority {
return false;
}
let Some(warm) = pod.warmed.get(&partition) else {
@@ -988,15 +965,12 @@ impl HandoffModel {
mutate(last, |state| self.warm_step(state, x, p, None))
} else if pod.fenced.contains(&p) {
mutate(last, |state| {
- // `resume_partition`. Under EpochFenced the
- // cancelled handoff's target may have taken the
- // broker fence from this pod's producer;
- // production re-acquires it before re-admitting
- // writes, or every write would fail as fenced
- // until the next handoff.
- if self.variant == Variant::EpochFenced {
- state.changelogs.get_mut(&p).unwrap().epoch_holder = Some(x);
- }
+ // `resume_partition`. The cancelled handoff's
+ // target may have taken the broker fence from
+ // this pod's producer; production re-acquires it
+ // before re-admitting writes, or every write
+ // would fail as fenced until the next handoff.
+ state.changelogs.get_mut(&p).unwrap().epoch_holder = Some(x);
state.pods.get_mut(&x).unwrap().fenced.remove(&p);
})
} else {
@@ -1302,10 +1276,7 @@ impl Model for HandoffModel {
if self.claim_detection == ClaimDetection::Delayed {
offer(Action::NoticeLeaseLoss(pod));
}
- // Only meaningful when something consults the claim, and the
- // state space is expensive enough that exploring it in
- // configurations that ignore the claim would buy nothing.
- if self.lease_gated_reads {
+ if self.claim_lapses {
offer(Action::AuthorityLapse(pod));
if self.claim_recovers {
offer(Action::AuthorityRenew(pod));
@@ -1502,10 +1473,8 @@ impl Model for HandoffModel {
fn properties(&self) -> Vec<Property<Self>> {
let mut props = vec![
- // The acked-write-loss invariant the drain/fence/HWM
- // machinery exists to uphold. Expected to FAIL under
- // Variant::Current with a zombie window (the documented
- // residual) and PASS under Variant::EpochFenced.
+ // The acked-write-loss invariant the drain, fence and HWM
+ // machinery exists to uphold.
Property::<Self>::always("no_lost_acked_write", |_, s| !s.lost_acked_write),
// Rebalancing is enabled concurrently with in-flight handoffs;
// pinning must keep it from ever planning one of their
@@ -1622,7 +1591,7 @@ impl Model for HandoffModel {
// reads is a black hole the coordinator
// will not reassign, because it still
// looks alive.
- && (!m.lease_gated_reads || pod.claims_authority)
+ && pod.claims_authority
})
});
owners_converged
diff --git a/rust/personhog-stateright/src/types.rs b/rust/personhog-stateright/src/types.rs
index f75d296ccb26..8e6bc803fb52 100644
--- a/rust/personhog-stateright/src/types.rs
+++ b/rust/personhog-stateright/src/types.rs
@@ -155,10 +155,9 @@ pub enum StashedRequest {
pub struct Changelog {
/// Number of records appended (the HWM).
pub len: u8,
- /// The pod whose transactional producer the broker currently accepts,
- /// under `Variant::EpochFenced` (production: the latest
- /// `init_transactions` wins and every earlier producer is fenced out).
- /// Always `None` under `Current`, which has no broker-side fence.
+ /// The pod whose transactional producer the broker currently accepts:
+ /// the latest `init_transactions` wins and every earlier producer is
+ /// fenced out.
///
/// This is an owner rather than an epoch number because nothing
/// compares epochs for order — the single consumer asks whether *this*
diff --git a/rust/personhog-stateright/tests/model_tests.rs b/rust/personhog-stateright/tests/model_tests.rs
index d3d5f349751c..1c4274a3ec1b 100644
--- a/rust/personhog-stateright/tests/model_tests.rs
+++ b/rust/personhog-stateright/tests/model_tests.rs
@@ -1,33 +1,10 @@
-//! Exhaustive model-checking runs with the expected verdicts per
-//! variant. These are the durable record of what the protocol does and
-//! does not guarantee:
-//!
-//! | scenario | no_lost_acked_write | no_split_acceptance |
-//! |------------------------------|---------------------|----------------------|
-//! | Current, no failures | holds | holds |
-//! | Current, crash/lease loss | holds | holds |
-//! | Current, single zombie pod | holds | holds |
-//! | Current, double zombie | VIOLATED (residual) | VIOLATED (residual) |
-//! | EpochFenced, double zombie | holds | holds |
-//!
-//! Every row above is about *write* safety. Stale strong reads from a
-//! zombie pod are a separate, still-open residual that fencing does not
-//! address; only the configurations without a zombie window uphold
-//! `strong_reads_complete`.
-//!
-//! The single-zombie row is a result the checker sharpened beyond what
-//! the manual review claimed: a zombie *pod* alone cannot lose an acked
-//! write, because the identity freeze quorum has every registered router
-//! stashing before the drain (no honest router routes to the zombie
-//! post-warm) and anything the zombie accepts pre-warm sits below the
-//! warm HWM and is captured. Loss requires the double zombie — a
-//! lease-expired router (outside the quorum, stale table) feeding a
-//! lease-expired pod. That is the documented residual epoch fencing
-//! closes; the checker finds the exact interleaving as a counterexample.
+//! Exhaustive model-checking runs and their verdicts. Each test's doc
+//! comment states what its configuration proves; the README carries the
+//! verdict table and the state-space sizes.
use std::time::Instant;
-use personhog_stateright::model::{ClaimDetection, HandoffModel, Variant, WarmOrder};
+use personhog_stateright::model::{ClaimDetection, HandoffModel, WarmOrder};
use stateright::{Checker, HasDiscoveries, Model};
/// Every checker explores in parallel: stateright defaults to a single
@@ -118,9 +95,8 @@ fn base() -> HandoffModel {
routers: 2,
late_routers: 0,
partitions: 1,
- variant: Variant::Current,
warm_order: WarmOrder::FenceFirst,
- lease_gated_reads: false,
+ claim_lapses: false,
claim_recovers: true,
claim_detection: ClaimDetection::Prompt,
writes: 2,
@@ -136,9 +112,8 @@ fn base() -> HandoffModel {
}
}
-fn model(variant: Variant, crashes: u8, zombie_window: u8) -> HandoffModel {
+fn model(crashes: u8, zombie_window: u8) -> HandoffModel {
HandoffModel {
- variant,
crashes,
zombie_window,
..base()
@@ -149,9 +124,9 @@ fn model(variant: Variant, crashes: u8, zombie_window: u8) -> HandoffModel {
/// every reachable state, the liveness property holds on every full run,
/// and the interesting states are genuinely reachable.
#[test]
-fn current_protocol_without_failures_is_safe_and_live() {
- model(Variant::Current, 0, 0)
- .explore("current_protocol_without_failures_is_safe_and_live")
+fn the_protocol_without_failures_is_safe_and_live() {
+ model(0, 0)
+ .explore("the_protocol_without_failures_is_safe_and_live")
.assert_properties();
}
@@ -159,9 +134,9 @@ fn current_protocol_without_failures_is_safe_and_live() {
/// data plane): the convergence machinery repairs wiped pod memory and
/// the dead-owner paths reassign, with no safety violation anywhere.
#[test]
-fn current_protocol_with_crashes_is_safe_and_live() {
- model(Variant::Current, 1, 0)
- .explore("current_protocol_with_crashes_is_safe_and_live")
+fn the_protocol_with_crashes_is_safe_and_live() {
+ model(1, 0)
+ .explore("the_protocol_with_crashes_is_safe_and_live")
.assert_properties();
}
@@ -171,58 +146,30 @@ fn current_protocol_with_crashes_is_safe_and_live() {
/// below the warm HWM. This is a stronger guarantee than the manual
/// review claimed — found by the checker refusing to produce a
/// counterexample for the weaker claim.
+/// Refusing reads is the kind of change that can starve liveness, so this
+/// clears every property, not only the safety ones.
#[test]
-fn current_protocol_single_zombie_pod_is_safe() {
- model(Variant::Current, 1, 1)
- .explore("current_protocol_single_zombie_pod_is_safe")
- .assert_properties();
-}
-
-/// The documented residual, now precisely characterized: a lease-expired
-/// router (excluded from the freeze quorum, never stashing, stale table)
-/// routes a write to a lease-expired pod (coordination loop dead, never
-/// fenced) after the partition's new owner warmed — the write is acked
-/// but sits beyond the warm HWM, invisible to the new owner forever.
-#[test]
-fn current_protocol_double_zombie_loses_acked_writes() {
- let checker = model(Variant::Current, 2, 1).explore_until(
- "current_protocol_double_zombie_loses_acked_writes",
- &["no_lost_acked_write", "no_split_write_acceptance"],
- );
- assert!(
- checker.discovery("no_lost_acked_write").is_some(),
- "the double zombie must produce an acked-write-loss counterexample"
- );
- assert!(
- checker.discovery("no_split_write_acceptance").is_some(),
- "the double zombie must produce a dual-capability counterexample"
- );
+fn a_single_zombie_pod_is_safe() {
+ HandoffModel {
+ claim_lapses: true,
+ ..model(1, 1)
+ }
+ .explore("a_single_zombie_pod_is_safe")
+ .assert_properties();
}
-/// Epoch fencing closes the *write* half of the residual: warming bumps
-/// the broker's producer epoch, so the zombie's produce is rejected
-/// before any ack. Acked-write loss, split acceptance, and drain-ack
-/// finality all hold again, zombie window and all.
-///
-/// `strong_reads_complete` is deliberately not asserted here: it still
-/// fails, because a zombie pod serves reads from its stale cache and
-/// nothing rejects them when the read gate is off. Turning it on closes
-/// that — see `fencing_and_lease_gated_reads_together_close_the_double_zombie`.
+/// The double zombie, closed by both halves at once: fencing rejects the
+/// zombie's produce before any ack, and the read gate stops it answering
+/// from a cache the new owner is already changing. Every property holds,
+/// including the stale-read one that fencing alone used to leave broken.
#[test]
fn epoch_fenced_double_zombie_is_safe() {
- let checker = model(Variant::EpochFenced, 2, 1).explore("epoch_fenced_double_zombie_is_safe");
- assert!(
- checker.discovery("no_lost_acked_write").is_none(),
- "epoch fencing must eliminate acked-write loss"
- );
- assert!(
- checker.discovery("no_split_write_acceptance").is_none(),
- "epoch fencing must restore single-writer capability"
- );
- assert!(
- checker.discovery("drained_ack_is_final").is_none(),
- "a drained ack must remain final under fencing"
- );
+ HandoffModel {
+ claim_lapses: true,
+ ..model(2, 1)
+ }
+ .explore("epoch_fenced_double_zombie_is_safe")
+ .assert_properties();
}
/// The rejected warm ordering — changelog read before fence acquisition
@@ -235,7 +182,7 @@ fn epoch_fenced_double_zombie_is_safe() {
fn epoch_fenced_read_first_ordering_loses_acked_writes() {
let checker = HandoffModel {
warm_order: WarmOrder::ReadFirst,
- ..model(Variant::EpochFenced, 2, 1)
+ ..model(2, 1)
}
.explore_until(
"epoch_fenced_read_first_ordering_loses_acked_writes",
@@ -263,7 +210,6 @@ fn epoch_fenced_resume_after_cancelled_handoff_stays_live() {
HandoffModel {
routers: 1,
partitions: 2,
- variant: Variant::EpochFenced,
writes: 1,
reads: 0,
crashes: 2,
@@ -280,14 +226,14 @@ fn epoch_fenced_resume_after_cancelled_handoff_stays_live() {
/// safety and liveness properties must still hold, including under a
/// single zombie.
#[test]
-fn current_two_partitions_single_zombie_is_safe() {
+fn two_partitions_single_zombie_is_safe() {
HandoffModel {
partitions: 2,
crashes: 1,
zombie_window: 1,
..base()
}
- .explore("current_two_partitions_single_zombie_is_safe")
+ .explore("two_partitions_single_zombie_is_safe")
.assert_properties();
}
@@ -331,25 +277,6 @@ fn strong_reads_are_complete_across_cutover() {
.assert_properties();
}
-/// The double-zombie residual must also reproduce at two partitions —
-/// guards against the cross-partition coordinator logic (rebalance
-/// deferral, per-partition cleanup) accidentally masking or altering the
-/// single-partition verdict.
-#[test]
-fn two_partitions_double_zombie_loses_acked_writes() {
- let checker = HandoffModel {
- partitions: 2,
- crashes: 2,
- zombie_window: 1,
- ..base()
- }
- .explore_until(
- "two_partitions_double_zombie_loses_acked_writes",
- &["no_lost_acked_write"],
- );
- assert!(checker.discovery("no_lost_acked_write").is_some());
-}
-
/// Epoch fencing must close the residual at two partitions too — each
/// partition's producer epoch is independent, and this pins that the
/// fix doesn't rely on single-partition structure.
@@ -357,7 +284,6 @@ fn two_partitions_double_zombie_loses_acked_writes() {
fn epoch_fenced_two_partitions_double_zombie_is_safe() {
let checker = HandoffModel {
partitions: 2,
- variant: Variant::EpochFenced,
crashes: 2,
zombie_window: 1,
..base()
@@ -524,7 +450,6 @@ fn probe_divergent_quorums_are_reachable_and_safe() {
#[test]
fn epoch_fenced_double_zombie_with_late_joiner_is_safe() {
let checker = HandoffModel {
- variant: Variant::EpochFenced,
routers: 1,
late_routers: 1,
router_joins: 1,
@@ -696,7 +621,6 @@ fn epoch_fenced_under_cancellation_is_safe_and_live() {
HandoffModel {
routers: 1,
partitions: 2,
- variant: Variant::EpochFenced,
writes: 1,
reads: 0,
cancels: 1,
@@ -706,73 +630,6 @@ fn epoch_fenced_under_cancellation_is_safe_and_live() {
.assert_properties();
}
-/// Fencing and the read gate are complementary, not alternative.
-///
-/// Fencing alone leaves `strong_reads_complete` violated under the
-/// double zombie: it rejects a zombie's writes, not its reads, and the
-/// zombie keeps answering from a cache the new owner is already
-/// changing. The gate alone does not close it either — without fencing
-/// the zombie's write is lost, so the *legitimate* owner is the one
-/// serving a read missing an acked write. Only both together hold every
-/// safety property, which is why the leader's read gate is a
-/// prerequisite for enabling fencing rather than an independent
-/// improvement.
-#[test]
-fn fencing_and_lease_gated_reads_together_close_the_double_zombie() {
- let cfg = |variant, gated| HandoffModel {
- variant,
- lease_gated_reads: gated,
- claim_recovers: true,
- crashes: 2,
- zombie_window: 1,
- ..base()
- };
- // The two arms below that expect a stale read stop at it; the arm that
- // asserts none exists has to explore everything. Each arm reports under
- // its own label, so their state counts stay comparable separately.
- let stale_reads_reachable = |scenario, variant, gated| {
- cfg(variant, gated)
- .explore_until(scenario, &["strong_reads_complete"])
- .discovery("strong_reads_complete")
- .is_some()
- };
-
- assert!(
- stale_reads_reachable("read_gate_alone", Variant::Current, true),
- "the read gate alone must not close it: the honest owner serves a read missing the \
- zombie's lost write"
- );
- assert!(
- stale_reads_reachable("fencing_alone", Variant::EpochFenced, false),
- "fencing alone must not close it: the zombie still answers reads"
- );
- assert!(
- cfg(Variant::EpochFenced, true)
- .explore("fencing_and_read_gate_together")
- .discovery("strong_reads_complete")
- .is_none(),
- "together they must close it"
- );
-}
-
-/// The gate makes pods refuse reads, which is exactly the kind of change
-/// that can starve liveness — so a gated configuration has to clear
-/// every property, not just the stale-read one the complementarity
-/// verdict inspects.
-#[test]
-fn a_lease_gated_fleet_is_safe_and_live() {
- HandoffModel {
- variant: Variant::EpochFenced,
- lease_gated_reads: true,
- claim_recovers: true,
- crashes: 1,
- zombie_window: 1,
- ..base()
- }
- .explore("a_lease_gated_fleet_is_safe_and_live")
- .assert_properties();
-}
-
/// The state the stability property's claim conjunct exists for, made
/// reachable and then made permanent.
///
@@ -790,8 +647,7 @@ fn a_lease_gated_fleet_is_safe_and_live() {
#[test]
fn a_lapsed_claim_that_never_returns_fails_stability() {
let checker = HandoffModel {
- variant: Variant::EpochFenced,
- lease_gated_reads: true,
+ claim_lapses: true,
claim_recovers: false,
crashes: 1,
zombie_window: 1,
@@ -819,8 +675,7 @@ fn a_lapsed_claim_that_never_returns_fails_stability() {
#[test]
fn prompt_detection_is_what_makes_the_read_gate_hold() {
let cfg = |detection| HandoffModel {
- variant: Variant::EpochFenced,
- lease_gated_reads: true,
+ claim_lapses: true,
claim_recovers: true,
claim_detection: detection,
crashes: 2,
diff --git a/rust/personhog-test-harness/src/cli.rs b/rust/personhog-test-harness/src/cli.rs
index 278983452237..218e20e19ed6 100644
--- a/rust/personhog-test-harness/src/cli.rs
+++ b/rust/personhog-test-harness/src/cli.rs
@@ -144,8 +144,8 @@ pub struct ConsistencyArgs {
#[derive(Args, Clone)]
pub struct GateArgs {
/// Extra KEY=VALUE environment for spawned leaders — the lever for
- /// benchmarking leader features (e.g. KAFKA_TRANSACTIONAL_FENCING)
- /// without a harness change per flag. Repeatable.
+ /// benchmarking leader knobs (e.g. FENCING_LANES) without a harness
+ /// change per knob. Repeatable.
#[arg(long = "leader-env", value_parser = parse_env_pair)]
pub leader_env: Vec<(String, String)>,