:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(personhog): broker-enforced epoch fencing via transaction windows (#76100)
Zach Brown1cabb66a12d5
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.ymlindex 60120aabcc4c..75213d5c3b31 100644--- a/.github/workflows/ci-rust.yml+++ b/.github/workflows/ci-rust.yml@@ -611,7 +611,7 @@ jobs:run: |./target/debug/personhog-test-harness gate \--leaders 3 --partitions 8 --persons 50 --concurrency 10 --duration 15s \- --cache-capacity 10 --writer-pause-after 3s --writer-pause-duration 8s+ --cache-capacity 4096 --writer-pause-after 3s --writer-pause-duration 8s- name: Run the e2e gate under chaos (kill + scale-up)run: |@@ -626,6 +626,45 @@ 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.+ #+ # 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 the broker fence is+ # never 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.+ ./target/debug/personhog-test-harness gate \+ --leader-env KAFKA_TRANSACTIONAL_FENCING=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+- name: Run the e2e gate under chaos (TTL-expiry kill + restarts)run: |./target/debug/personhog-test-harness gate \diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 259074e8b0a4..052f4cd8106b 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -8538,6 +8538,7 @@ dependencies = ["metrics","personhog-common","personhog-coordination",+ "personhog-leader","personhog-proto","prost 0.13.5","rdkafka",diff --git a/rust/common/kafka/src/transaction.rs b/rust/common/kafka/src/transaction.rsindex 765bfe5031d9..ae5db75b493c 100644--- a/rust/common/kafka/src/transaction.rs+++ b/rust/common/kafka/src/transaction.rs@@ -18,6 +18,104 @@ use crate::{},};+/// Startup metadata-ping bound for producers built without a broker+/// transaction bound — the value this call used before the bound+/// existed, kept so unrelated services' startup behavior is unchanged.+const UNBOUNDED_PING_TIMEOUT: Duration = Duration::from_secs(15);++/// The `ClientConfig` for a transactional producer: the shared+/// producer's tuning, the transactional id, and — when the caller+/// controls the broker-side bound — `transaction.timeout.ms`.+///+/// A pure function so what the fenced producer inherits is assertable.+/// It previously carried only a fixed subset of the shared tuning, so a+/// deployment that set `message.max.bytes` or batch tuning got two+/// producers behaving differently depending on which flag arm built+/// them.+///+/// Four knobs are deliberately not copied even when configured, because+/// the transactional contract pins them: transactions require+/// idempotence, and idempotence requires `acks=all`, retries above+/// zero, and at most five in-flight requests. librdkafka refuses to+/// build a producer configured against any of those, so a shared+/// override of `enable.idempotence`, `acks`, `retries`, or+/// `max.in.flight.requests.per.connection` must not reach this one.+fn transactional_client_config(+ config: &KafkaConfig,+ transactional_id: &str,+ broker_txn_timeout: Option<Duration>,+) -> Result<ClientConfig, KafkaError> {+ let mut client_config = ClientConfig::new();+ client_config+ .set("bootstrap.servers", &config.kafka_hosts)+ .set("statistics.interval.ms", "10000")+ .set("linger.ms", config.kafka_producer_linger_ms.to_string())+ .set(+ "message.timeout.ms",+ config.kafka_message_timeout_ms.to_string(),+ )+ .set(+ "compression.codec",+ config.kafka_compression_codec.to_owned(),+ )+ .set(+ "queue.buffering.max.kbytes",+ (config.kafka_producer_queue_mib * 1024).to_string(),+ )+ .set(+ "queue.buffering.max.messages",+ config.kafka_producer_queue_messages.to_string(),+ )+ .set("transactional.id", transactional_id);++ if !config.kafka_client_id.is_empty() {+ client_config.set("client.id", &config.kafka_client_id);+ }+ if let Some(v) = config.kafka_producer_batch_size {+ client_config.set("batch.size", v.to_string());+ }+ if let Some(v) = config.kafka_producer_batch_num_messages {+ client_config.set("batch.num.messages", v.to_string());+ }+ if let Some(v) = config.kafka_producer_topic_metadata_refresh_interval_ms {+ client_config.set("topic.metadata.refresh.interval.ms", v.to_string());+ }+ if let Some(v) = config.kafka_producer_message_max_bytes {+ client_config.set("message.max.bytes", v.to_string());+ }+ if let Some(v) = config.kafka_producer_sticky_partitioning_linger_ms {+ client_config.set("sticky.partitioning.linger.ms", v.to_string());+ }+ if let Some(ref v) = config.kafka_producer_partitioner {+ client_config.set("partitioner", v);+ }++ if let Some(broker_txn_timeout) = broker_txn_timeout {+ let message_timeout_ms = u128::from(config.kafka_message_timeout_ms);+ if message_timeout_ms > broker_txn_timeout.as_millis() {+ // librdkafka reports this as a bare string from+ // `rd_kafka_new`; say which two knobs disagree instead.+ return Err(KafkaError::ClientCreation(format!(+ "message.timeout.ms ({message_timeout_ms}) exceeds the requested \+ transaction.timeout.ms ({}) for transactional id {transactional_id}",+ broker_txn_timeout.as_millis(),+ )));+ }+ client_config.set(+ "transaction.timeout.ms",+ broker_txn_timeout.as_millis().to_string(),+ );+ }++ if config.kafka_tls {+ client_config+ .set("security.protocol", "ssl")+ .set("enable.ssl.certificate.verification", "false");+ };++ Ok(client_config)+}+// TODO - it's kinda gross to leak the underlying producer context type here, makes for a really gross API. We should// probably figure out some trait to abstract over itpub struct TransactionalProducer<C = DefaultClientContext>@@ -37,6 +135,36 @@ impl TransactionalProducer<DefaultClientContext> {) -> Result<Self, KafkaError> {Self::with_context(config, transactional_id, timeout, DefaultClientContext)}++ /// A producer whose open transactions the broker abandons after+ /// `broker_txn_timeout`, rather than after librdkafka's default+ /// minute.+ ///+ /// This is a different quantity from `timeout`, which bounds how long+ /// *this process* waits on a blocking transactional call. The broker+ /// bound matters to everyone else: until an abandoned transaction+ /// expires, the partition's last-stable-offset does not advance and+ /// every `read_committed` consumer stalls behind it.+ ///+ /// Only a caller that also controls `message.timeout.ms` can set it,+ /// because librdkafka requires `message.timeout.ms <=+ /// transaction.timeout.ms` and refuses to build the producer at all+ /// otherwise — which is why this is opt-in rather than derived from+ /// the operation timeout.+ pub fn from_config_bounded(+ config: &KafkaConfig,+ transactional_id: &str,+ timeout: Duration,+ broker_txn_timeout: Duration,+ ) -> Result<Self, KafkaError> {+ Self::build(+ config,+ transactional_id,+ timeout,+ Some(broker_txn_timeout),+ DefaultClientContext,+ )+ }}impl<C: ClientContext> TransactionalProducer<C> {@@ -46,43 +174,34 @@ impl<C: ClientContext> TransactionalProducer<C> {timeout: Duration,context: C,) -> Result<Self, KafkaError> {- let mut client_config = ClientConfig::new();- client_config- .set("bootstrap.servers", &config.kafka_hosts)- .set("statistics.interval.ms", "10000")- .set("linger.ms", config.kafka_producer_linger_ms.to_string())- .set(- "message.timeout.ms",- config.kafka_message_timeout_ms.to_string(),- )- .set(- "compression.codec",- config.kafka_compression_codec.to_owned(),- )- .set(- "queue.buffering.max.kbytes",- (config.kafka_producer_queue_mib * 1024).to_string(),- )- .set(- "queue.buffering.max.messages",- config.kafka_producer_queue_messages.to_string(),- )- .set("transactional.id", transactional_id);-- if config.kafka_tls {- client_config- .set("security.protocol", "ssl")- .set("enable.ssl.certificate.verification", "false");- };+ Self::build(config, transactional_id, timeout, None, context)+ }++ fn build(+ config: &KafkaConfig,+ transactional_id: &str,+ timeout: Duration,+ broker_txn_timeout: Option<Duration>,+ context: C,+ ) -> Result<Self, KafkaError> {+ let client_config =+ transactional_client_config(config, transactional_id, broker_txn_timeout)?;debug!("rdkafka configuration: {:?}", client_config);let api: FutureProducer<C> = client_config.create_with_context(context)?;- // "Ping" the Kafka brokers by requesting metadata- match api- .client()- .fetch_metadata(None, std::time::Duration::from_secs(15))- {+ // "Ping" the Kafka brokers by requesting metadata. On the+ // broker-bounded (partition-acquisition) path the ping is bounded+ // by the caller's timeout — an unbounded stall there holds a warm+ // slot and delays a handoff. Everywhere else the historical fixed+ // bound is kept, so services that never opted into broker bounds+ // keep their startup behavior.+ let ping_timeout = if broker_txn_timeout.is_some() {+ timeout+ } else {+ UNBOUNDED_PING_TIMEOUT+ };+ match api.client().fetch_metadata(None, ping_timeout) {Ok(metadata) => {info!("Successfully connected to Kafka brokers. Found {} topics.",@@ -225,3 +344,132 @@ fn to_topic_partition_list(offsets: Vec<Offset>) -> Result<TopicPartitionList, KTopicPartitionList::from_topic_map(&topic_map)}++#[cfg(test)]+mod tests {+ use super::*;++ /// librdkafka refuses to build a transactional producer whose+ /// `message.timeout.ms` exceeds its `transaction.timeout.ms`, and the+ /// two are set from different places: the message timeout comes from+ /// the shared `KafkaConfig`, the transaction timeout from whoever asks+ /// for a bounded producer. A caller that sets only the latter gets a+ /// producer that cannot be constructed at all — which is a startup+ /// crash loop, not a degraded mode.+ ///+ /// `Duration::from_secs(10)` against the default 20s message timeout+ /// is the combination that shape belongs to; the bounded constructor+ /// has to reject it by name rather than let librdkafka reject it by+ /// string.+ #[test]+ fn a_broker_bound_under_the_message_timeout_is_refused_by_name() {+ let config = KafkaConfig {+ kafka_message_timeout_ms: 20_000,+ ..KafkaConfig::default()+ };+ let Err(err) = TransactionalProducer::from_config_bounded(+ &config,+ "test-txn-id",+ Duration::from_secs(10),+ Duration::from_secs(10),+ ) else {+ panic!("a broker bound below the message timeout must not build a producer");+ };+ // Deliberately asserting on the values, not the knob names:+ // librdkafka's own rejection string names both knobs too, so a+ // name-only assertion would pass just as well with this check+ // removed and the failure left to the C library.+ let message = err.to_string();+ assert!(+ message.contains("20000") && message.contains("10000"),+ "the error should report the two timeouts that disagree, got: {message}"+ );+ }++ /// The unbounded constructors must not set `transaction.timeout.ms` at+ /// all, so a caller whose message timeout exceeds its operation+ /// timeout keeps librdkafka's default rather than inheriting a bound+ /// it never asked for.+ #[test]+ fn an_unbounded_producer_does_not_inherit_the_operation_timeout() {+ let config = KafkaConfig {+ kafka_message_timeout_ms: 20_000,+ ..KafkaConfig::default()+ };+ let client_config = transactional_client_config(&config, "test-txn-id", None)+ .expect("an unbounded config always builds");+ assert_eq!(+ client_config.get("transaction.timeout.ms"),+ None,+ "no broker bound was requested, so none may be set"+ );+ assert_eq!(client_config.get("message.timeout.ms"), Some("20000"));+ }++ /// The fenced producer must carry the shared producer's tuning, not a+ /// fixed subset of it: a deployment that raises `message.max.bytes`+ /// or sets batch or metadata-refresh tuning would otherwise get two+ /// producers behaving differently depending on which flag arm built+ /// them — most consequentially the message ceiling, since the leader+ /// admits person properties within a whisker of librdkafka's default.+ #[test]+ fn the_fenced_producer_inherits_the_shared_tuning() {+ let config = KafkaConfig {+ kafka_client_id: "leader-changelog".to_string(),+ kafka_producer_batch_size: Some(524_288),+ kafka_producer_batch_num_messages: Some(1_000),+ kafka_producer_topic_metadata_refresh_interval_ms: Some(30_000),+ kafka_producer_message_max_bytes: Some(2_097_152),+ kafka_producer_sticky_partitioning_linger_ms: Some(25),+ kafka_producer_partitioner: Some("murmur2_random".to_string()),+ ..KafkaConfig::default()+ };+ let client_config = transactional_client_config(&config, "test-txn-id", None)+ .expect("a compatible config builds");+ for (key, value) in [+ ("client.id", "leader-changelog"),+ ("batch.size", "524288"),+ ("batch.num.messages", "1000"),+ ("topic.metadata.refresh.interval.ms", "30000"),+ ("message.max.bytes", "2097152"),+ ("sticky.partitioning.linger.ms", "25"),+ ("partitioner", "murmur2_random"),+ ] {+ assert_eq!(+ client_config.get(key),+ Some(value),+ "the fenced producer dropped the shared `{key}` tuning"+ );+ }+ }++ /// The four knobs the transactional contract pins must not be copied+ /// even when the shared config sets them: transactions require+ /// idempotence, and idempotence requires acks=all, retries above+ /// zero, and at most five in-flight requests — librdkafka refuses to+ /// build a producer configured against any of those.+ #[test]+ fn the_transactional_contract_pins_its_knobs() {+ let config = KafkaConfig {+ kafka_producer_enable_idempotence: Some(false),+ kafka_producer_acks: Some("1".to_string()),+ kafka_producer_retries: Some(0),+ kafka_producer_max_in_flight_requests_per_connection: Some(50),+ ..KafkaConfig::default()+ };+ let client_config = transactional_client_config(&config, "test-txn-id", None)+ .expect("pinned knobs are dropped, not refused");+ for key in [+ "enable.idempotence",+ "acks",+ "retries",+ "max.in.flight.requests.per.connection",+ ] {+ assert_eq!(+ client_config.get(key),+ None,+ "`{key}` is pinned by the transactional contract and must not be copied"+ );+ }+ }+}diff --git a/rust/personhog-coordination/README.md b/rust/personhog-coordination/README.mdindex a8f88a30e952..e8d77984d1f2 100644--- a/rust/personhog-coordination/README.md+++ b/rust/personhog-coordination/README.md@@ -64,7 +64,7 @@ If a single phase served both purposes (router stash *and* old-owner drain in paSeveral failure modes are handled explicitly:-- **Dead `new_owner`**: If the new owner's etcd registration disappears (lease expired, deregistered) before it can ack warming, `cleanup_stale_handoffs` deletes the handoff — this is the *only* condition that triggers cleanup. The delete re-reads the handoff under its `mod_revision` and removes the handoff plus all of its acks in a single guarded transaction, so a concurrent cleanup (pod watch, handoff watch, reconcile tick, or a coordinator failing over) can never destroy a successor handoff recreated at the same key. A subsequent rebalance picks a fresh new owner.+- **Dead `new_owner`**: If the new owner's etcd registration disappears (lease expired, deregistered) before it can ack warming, the planner cancels the handoff **by replacement**, never by naked deletion: it picks a replacement owner and rewrites the record toward it, reaffirms the current owner (`old_owner: None`, phase `Complete`) when the partition should stay put, and only deletes — handoff plus all of its acks in one transaction guarded on the record's `mod_revision` — when nothing is placeable at all. The same machinery serves the second cancellation trigger, a handoff that outstays its phase deadline (`past_phase_deadline`). Either way a concurrent actor loses the CAS cleanly, and routers never observe a gap between owners.- **Dead `old_owner`**: A dead old owner is deliberately *not* grounds for cleanup. A pod that is no longer registered can't produce writes, so the drain requirement is vacuously satisfied — `check_phase_advance` treats a handoff whose `old_owner` is absent from the registered set as drained and advances it in place toward `Complete`. An `old_owner` that is still registered must write its `DrainedAck` before the handoff advances.- **Cancellation by replacement**: A handoff record is never deleted while non-terminal. To cancel one — its new owner's registration disappeared, or it outstayed its phase's deadline — the planner atomically *replaces* the record, under its `mod_revision` and with the predecessor's acks deleted in the same transaction, with whatever resolves the routers' stashes: a successor `Freezing` handoff when the plan re-places the partition (stashes ride into it without observing a gap), or a reaffirm — `Complete` toward the live current owner, `old_owner: None` — when the placement stands (stashes drain home through the ordinary Complete path, and the owner pod converges back to serving). Only when neither exists (owner dead, nothing placeable) is the record deleted, which is safe fail-closed. A deletion event therefore has exactly one protocol meaning — cleanup after `Complete` — and routers treat it as inert. The cancellation log and a `freeze_ack_missing_total{router}` counter name the required routers whose acks never arrived, so a freeze wedge attributes itself to the non-participating router.- **Phase-aware deadline**: Time-in-phase is bounded, not total age — wedged is a property of a phase. Freezing and Draining wait only on acknowledgements and share a tight budget (`COORDINATOR_HANDOFF_DEADLINE_SECS`, default 120 s); Warming replays a changelog whose length scales with the partition and gets its own generous budget (`COORDINATOR_WARMING_DEADLINE_SECS`, default 1800 s, 0 disables). A total-age deadline would cancel a legitimately long warm and restart it from zero, forever. The reconcile tick detects both cancellation triggers and wakes the planning loop; the replacement itself is a planning decision.@@ -73,7 +73,7 @@ Several failure modes are handled explicitly:- **Warm provenance**: A pod records what each partition warm was installed for (serving, or a specific handoff id). Warming honors only a warm installed for the *current* handoff — one left over from an earlier ownership era is released and rebuilt, because its cache can hold values that predate writes the changelog accepted since, and a fresh warm replays only from the writer's committed offset. Without this, a returning owner whose `Released` convergence never ran could ack a warm it never performed and lose acknowledged writes — a counterexample the stateright model found and now pins.- **Coordinator restart**: On startup, the coordinator runs `reconcile_pending_handoffs`. For every existing handoff it applies cleanup if `Complete`, otherwise calls `check_phase_advance` to nudge the state machine. This handles the case where acks were written before the coordinator was up — the ack-watch only fires on Put events, so without reconcile those acks would be invisible.- **Reconcile tick**: Beyond the startup reconcile, the coordinator re-evaluates every in-flight handoff on a fixed interval (`reconcile_interval`, default 5 s). This is the liveness backstop for state changes that fire no watched event — e.g. a router departing (nothing watches router registrations) newly satisfying a freeze quorum. Everything the tick drives is idempotent: phase transitions use CAS and cleanup tolerates already-deleted records.-- **Lease loss (self-fencing)**: Connection trouble and lease loss are different things. A broken or silent keepalive stream is a fact about one connection — the lease lives in etcd's replicated keyspace and stays valid until its TTL passes without renewal — so ambiguous keepalive failures rebuild the stream and retry (a fresh connection through the service reaches a healthy member) for as long as the last confirmed renewal is recent; a routine single-member restart costs some retries (`personhog_coordination_keepalive_retries_total{component}`), not a fence. The keepalive declares loss on exactly two signals: etcd answering a round with TTL ≤ 0 (authoritative — the lease is revoked or expired), or the renewal margin running out (two thirds of the TTL without a confirmed renewal — the final third is reserved so the fence completes before the coordinator can possibly treat the lease as expired; retrying past it would gamble split-brain against availability). On loss the component ends the coordination attempt immediately, skipping the graceful drain: the coordinator already considers it dead and is reassigning its partitions via the dead-owner path, so a graceful drain would only race that. A pod self-fences *locally* before anything else: every held partition is released (dropping its cache and serving authority — re-acquisition always re-warms), so a zombie owner can never keep serving partitions the protocol has reassigned; if that local fence itself fails, in-place recovery is refused and the process restarts. Lease loss is observed at every await the session makes while holding a lease — the attempt select, the backoff nap between failed attempts, and the graceful drain all race the keepalive — so once the keepalive declares loss, the fence is never deferred by supervisor state. Every other session end fences too — budget exhaustion and shutdown revoke the lease, which deletes the registration instantly, so the local fence runs first (a no-op after a completed graceful drain) and the dead-owner path never meets a still-serving owner. On lease loss the fence's drain budget is the runway the keepalive margin reserved (a third of the TTL), not the full graceful drain timeout; overshoot poisons recovery and the process restart clears stragglers by death.+- **Lease loss (self-fencing)**: Connection trouble and lease loss are different things. A broken or silent keepalive stream is a fact about one connection — the lease lives in etcd's replicated keyspace and stays valid until its TTL passes without renewal — so ambiguous keepalive failures rebuild the stream and retry (a fresh connection through the service reaches a healthy member) for as long as the last confirmed renewal is recent; a routine single-member restart costs some retries (`personhog_coordination_keepalive_retries_total{component}`), not a fence. The keepalive declares loss on exactly two signals: etcd answering a round with TTL ≤ 0 (authoritative — the lease is revoked or expired), or the renewal margin running out (two thirds of the TTL without a confirmed renewal — the final third is reserved so the fence completes before the coordinator can possibly treat the lease as expired; retrying past it would gamble split-brain against availability). On loss the component ends the coordination attempt immediately, skipping the graceful drain: the coordinator already considers it dead and is reassigning its partitions via the dead-owner path, so a graceful drain would only race that. A pod self-fences *locally* before anything else: every held partition is drained and, once quiesced, released (dropping its cache and serving authority — re-acquisition always re-warms). A partition whose drain cannot quiesce is deliberately **not** released — release is what unfences admissions and drops the cache, and a leaseless pod must do neither over live in-flight work — so it stays fenced and held, in-place recovery is refused, and the process restart clears it by death. A zombie owner therefore never keeps serving partitions the protocol has reassigned beyond the window that restart closes. Lease loss is observed at every await the session makes while holding a lease — the attempt select, the backoff nap between failed attempts, and the graceful drain all race the keepalive — so once the keepalive declares loss, the fence is never deferred by supervisor state. Every other session end fences too — budget exhaustion and shutdown revoke the lease, which deletes the registration instantly, so the local fence runs first (a no-op after a completed graceful drain) and the dead-owner path never meets a still-serving owner. On lease loss the fence's drain budget is the runway the keepalive margin reserved (a third of the TTL), not the full graceful drain timeout; overshoot poisons recovery and the process restart clears stragglers by death.- **Supervised coordination runs (etcd resilience)**: A failed coordination attempt — a broken watch stream, a failed etcd write, an exhausted reconcile budget — no longer kills the process; the run supervisors tear the attempt down cleanly, back off exponentially, and rebuild through the same bootstrap that recovers a restarted process, while the data plane keeps serving. The two participant classes recover *differently*, on purpose. A **router** sheds its registration on every failed attempt (its registration is a freeze-quorum vote, and a registered but non-acking router would stall every quorum until the phase deadline); serving through its gap is safe because handoffs created while it is unregistered exclude it from their quorums and the leader-side fences reject its stale forwards. A **pod** does the opposite: its lease session (grant, register, heartbeat) lives *above* the attempt loop and survives attempt failures, so the coordinator keeps seeing a live pod and never runs the dead-owner path against a process that is still serving — the invariant is that serving authority is held exactly as long as the lease-backed registration behind it. This matters because the dead-owner path has no fence: its safety rests entirely on a deregistered owner being unable to produce, so a pod must never voluntarily deregister while it still serves. Only lease loss ends a pod session, self-fencing locally (every held partition released; re-acquisition re-warms) before a fresh session registers anew. A consecutive-failure budget (`ROUTER_RUN_RETRY_BUDGET`, default 10; same default on pods) keeps a genuinely wedged participant on the process-restart path; an attempt that made real progress — a convergence applied, a reconcile pass completed — resets the count, and the reset is keyed on measured progress rather than elapsed time because a time threshold silently exempts every failure detector slower than it (the reconcile budget and the stall watchdog both take a minute to fire), and `personhog_coordination_run_restarts_total{component}` counts every rebuild.### Concurrency and atomicity@@ -81,11 +81,19 @@ Several failure modes are handled explicitly:- All phase advancement uses `cas_handoff_phase`, a CAS on the handoff key's `mod_revision`. Two watchers racing to advance the same handoff cannot both succeed; the loser observes `false` and leaves the work to the Put event from the winner. (`mod_revision` rather than per-key `version`: `version` resets to 1 when a key is deleted and recreated, so a stale guard could match a different incarnation of the handoff.)- Every snapshot read that seeds a watch is revision-anchored: the read returns the etcd revision it was served at, and the watch starts at `revision + 1`. An event landing between the snapshot and the watch attaching is replayed rather than lost. When two snapshot reads feed one watch (e.g. a pod's startup reconcile reads assignments and handoffs), the watch anchors to the *lower* of the two revisions so nothing between them is skipped.- Advancing to `Complete` uses an atomic etcd transaction that writes both `phase=Complete` and the new `PartitionAssignment` together. Routers can never observe a torn state where the phase has advanced but the assignment hasn't (or vice versa).-- Routing changes flow exclusively through handoff `Complete` events. There is no separate assignment watch — anything that mutates `assignments/{partition}` outside the handoff protocol is invisible to routers by design.+- Routing changes flow through handoff `Complete` events; there is no separate assignment watch. An out-of-band write to `assignments/{partition}` is not invisible, though — the reconcile pass converges the table against the assignment keys every tick, so it flips routing within seconds, with no freeze, no drain, and no fence in front of it. That is exactly why nothing may mutate those keys outside the handoff protocol.## Known limitations-**The double-zombie residual is open — the one known acked-write-loss path.** 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: per-partition Kafka transactional producers, where warming bumps the broker's producer epoch and stale-epoch produces are rejected (`Variant::EpochFenced`). The fix is designed and verified but not yet implemented in the leader.+**The double-zombie residual — status by half.** A lease-expired router (excluded from the freeze quorum, still routing on a stale table) feeding a lease-expired pod (coordination loop dead, never fenced) can ack a write after the partition's new owner warmed; the write lands beyond the warm HWM, invisible to the new owner forever. Both zombie windows are bounded by lease self-fencing to roughly one heartbeat tick, so the loss needs both to coincide — but nothing rejects the zombie's produce at the broker. The stateright model reproduces the exact interleaving (`current_protocol_double_zombie_loses_acked_writes`) and machine-validates the fix (`Variant::EpochFenced`). Where each piece stands, one bullet per residual:++- **Zombie writes: closed here, behind `KAFKA_TRANSACTIONAL_FENCING` (default off).** A partition's owner acquires its transactional id before the warm read, so a predecessor that missed its drain is fenced at the broker and its produce fails instead of landing. Changelog consumers read `read_committed`, so aborted windows are never visible. The guarantee binds per binary, not per flag flip: a pod still running the old build produces non-transactionally and no epoch can fence it, so enable the flag only once the whole fleet is on a build that carries it — which the default-off flag and enable-after-rollout ordering already encode.+- **Zombie reads: open on this branch.** Fencing rejects a zombie's writes, not its reads: a zombie pod whose coordination loop is wedged keeps answering strong reads from a cache the new owner is already mutating, and the model still reports `strong_reads_complete` violated under the double zombie with fencing on. Closing it needs a lease-validity check on read admission — the keepalive publishing its last confirmed renewal, and the read path refusing once that stamp is older than the renewal margin. The model confirms the two are complementary rather than alternative: with a read gate but no fencing, stale reads persist because the *legitimate* owner is the one missing the zombie's lost write.+- **Acquisition is not gated on holding the lease — the reason this flag must not be enabled from this branch alone.** A zombie waking inside its lease window re-acquires the partition's transactional id on its way to noticing it is dead, which fences the legitimate owner: the broker grants the epoch to whoever initializes last, not to whoever the protocol says owns the partition. The legitimate owner's writes then bounce until a handoff moves the partition. The e2e zombie gate reproduces this. The same lease-validity publication that closes the stale-read half also gates acquisition; both ship on the stacked lease-validity branch, which additionally refuses `KAFKA_TRANSACTIONAL_FENCING` at startup without the gate. Enable the flag only with both branches deployed.+- **A condemned producer stays down until a restart or handoff, on this branch.** 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 — but nothing on this branch re-acquires in place; the serving-side re-acquisition ships with the stacked branch, gated on the authority stamp that gives it standing.+- **The drain commits its own window when it can.** A request cancelled mid-produce takes its handler — and the drain's in-flight count — with it, leaving the record it enqueued in a window nobody waits on; the drain waits (bounded, best-effort, never failing the drain) for that window to commit before acking, landing the cancelled write below the successor's cutoff. The successor's `init_transactions` aborts whatever could not settle — safe in either ordering, because the transaction coordinator serializes the in-flight commit against the successor's init on the shared transactional id.+- **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.+- **With `KAFKA_TRANSACTIONAL_FENCING` off there is no settle equivalent.** Nothing forces a queued record to the broker before the drain acks, so it can land above the new owner's warm cutoff, and a later write for that person re-derives the same version — where the writer's first-wins guard keeps the record nobody acked and discards the one that was. The unfenced path is slated for removal once fencing proves out.**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-coordination/src/coordinator.rs b/rust/personhog-coordination/src/coordinator.rsindex 745c0d3c9fce..37042b2be4c8 100644--- a/rust/personhog-coordination/src/coordinator.rs+++ b/rust/personhog-coordination/src/coordinator.rs@@ -1155,7 +1155,7 @@ impl Coordinator {handoff: &HandoffState,) -> Result<()> {if handoff.phase == HandoffPhase::Complete {- // Same guarded-delete discipline as `cleanup_stale_handoffs`:+ // Same guarded-delete discipline as the dead-new-owner cancellation:// the Complete observation may be stale by the time we act on// it, and the record at this key may already be a successor// handoff.diff --git a/rust/personhog-coordination/src/pod.rs b/rust/personhog-coordination/src/pod.rsindex de0139a45bff..d4e5aad286d8 100644--- a/rust/personhog-coordination/src/pod.rs+++ b/rust/personhog-coordination/src/pod.rs@@ -610,17 +610,22 @@ impl PodHandle {/// ownership state. Purely local: no etcd writes, callable with no/// lease.///- /// The order per partition is load-bearing: `release_partition`- /// unfences and drops the cache without waiting, so releasing first- /// would let a write admitted before the lease was lost complete- /// its produce and ack after the replacement owner's warm — an- /// acked write the new owner never sees. Draining first (fence,- /// then wait for the inflight counter) guarantees that once this- /// returns, nothing this pod admitted can ack. Each drain is- /// bounded by the drain timeout; a partition that cannot quiesce- /// fails the fence, which the caller poisons — the process restart- /// then clears the stuck in-flight work by death, exactly as the- /// pre-supervisor design did. The window before the lease loss is+ /// The order per partition is load-bearing for what release+ /// exposes, not for the writes already in flight: an admitted write+ /// completes its produce and acks whatever this function does —+ /// neither the fence nor a withheld release can stop it. Draining+ /// first (fence, then wait for the inflight counter) means the+ /// release that follows unfences a partition with nothing left in+ /// flight — no fresh admission lands on a leaseless pod, and the+ /// cache is not dropped out from under a handler still using it —+ /// and once this returns cleanly, everything this pod admitted had+ /// acked before any partition was let go. Each drain is bounded by+ /// the drain timeout; a partition that cannot quiesce stays fenced,+ /// held, and unreleased — its in-flight work's fate belongs to the+ /// broker (fenced, or committed below the successor's cutoff; with+ /// fencing off it is the documented unfenced residual) — and the+ /// caller poisons the run so the process restart clears it by+ /// death, exactly as the pre-supervisor design did. The window before the lease loss is/// even *detected* (up to one heartbeat tick) remains the/// documented zombie residual; this closes only the part the local/// fence itself controls.@@ -652,23 +657,68 @@ impl PodHandle {Error::invalid_state(format!("self-fence drain timed out for partition {partition}"))- })?+ })??;+ Ok::<u32, Error>(partition)});}+ // Failures are collected rather than propagated. This runs+ // because the pod has lost the right to serve, so giving the+ // partitions up matters more than reporting why one of them+ // resisted — returning on the first error would leave every+ // other partition still served by a pod with no lease, which is+ // the zombie this function exists to prevent.+ let mut failures: Vec<String> = Vec::new();+ let mut quiesced: HashSet<u32> = HashSet::new();while let Some(joined) = drains.join_next().await {- joined- .map_err(|e| Error::invalid_state(format!("self-fence drain panicked: {e}")))??;+ match joined {+ Ok(Ok(partition)) => {+ quiesced.insert(partition);+ }+ Ok(Err(e)) => failures.push(e.to_string()),+ Err(e) => failures.push(format!("self-fence drain panicked: {e}")),+ }}- // Phase 2: with nothing in flight anywhere, release each- // partition (dropping cache and serving authority) and clear- // the local ownership state.+ // Phase 2: release each partition that quiesced — dropping its+ // cache and serving authority — and clear the local ownership+ // state for it.+ //+ // Only the ones that quiesced. A write still in flight acks+ // whether or not its partition is released — nothing can stop+ // it — so what releasing an un-quiesced partition would actually+ // do is unfence fresh admissions on a pod with no lease, drop+ // the cache out from under the handlers still using it, and+ // erase the record that the partition was never given up. One+ // left fenced and unreleased stays that way until the process+ // restarts, which is the outcome its drain timing out already+ // implies.for partition in held {- self.handler.release_partition(partition).await?;+ if !quiesced.contains(&partition) {+ continue;+ }+ if let Err(e) = self.handler.release_partition(partition).await {+ failures.push(format!("release of partition {partition}: {e}"));+ // Still held: the handler may retain the cache and the+ // serving authority, so forgetting it here would make the+ // closing gauge read a partition as given up that was+ // not. The run is about to end poisoned either way.+ continue;+ }self.warmed_partitions.lock().await.remove(&partition);self.fenced_partitions.lock().await.remove(&partition);}- gauge!("personhog_coordination_partitions_held").set(0.0);+ // Whatever is left, not zero. A partition whose drain never+ // quiesced is still held, and reporting none held would hide it+ // at the one moment the count is worth reading.+ gauge!("personhog_coordination_partitions_held")+ .set(self.held_partition_count().await as f64);+ if !failures.is_empty() {+ return Err(Error::invalid_state(format!(+ "self-fence completed with {} failure(s): {}",+ failures.len(),+ failures.join("; ")+ )));+ }Ok(())}@@ -901,9 +951,16 @@ impl PodHandle {// admission depend on an undocumented handler side// effect. Resuming after a warm that already unfenced is// an idempotent no-op.- if self.fenced_partitions.lock().await.remove(&partition) {+ // Clear the local record only once the handler has+ // actually resumed: `resume_partition` can fail (it may+ // re-take broker-side state), and forgetting the fence+ // first would leave the data plane fenced with no branch+ // left to re-enter — writes rejected forever while the+ // convergence reports success.+ if self.fenced_partitions.lock().await.contains(&partition) {tracing::info!(pod, partition, "converging to Serving: resuming writes");self.handler.resume_partition(partition).await?;+ self.fenced_partitions.lock().await.remove(&partition);did_work = true;}}@@ -919,6 +976,13 @@ impl PodHandle {tracing::info!(pod, partition, "converging to Drained: fencing + draining");did_work = true;}+ // Recorded before the handler runs, not after. The+ // handler fences the data plane as its first act and can+ // fail afterwards; a record written only on success would+ // leave writes fenced with no branch left to re-enter,+ // since `resume_partition` below is reachable only+ // through this set.+ self.fenced_partitions.lock().await.insert(partition);let start = Instant::now();self.handler.drain_partition_inflight(partition).await?;if newly_fencing {@@ -928,7 +992,6 @@ impl PodHandle {histogram!("personhog_coordination_partition_drain_ms").record(start.elapsed().as_secs_f64() * 1000.0);}- self.fenced_partitions.lock().await.insert(partition);if ack {let handoff = handoff.expect("Drained state only derives from a handoff");self.store@@ -999,16 +1062,21 @@ impl PodHandle {tracing::info!(pod, partition, "warmed ack written");}DesiredState::Released => {- let was_warmed = self- .warmed_partitions- .lock()- .await- .remove(&partition)- .is_some();- let was_fenced = self.fenced_partitions.lock().await.remove(&partition);+ // Forgotten only after the handler returns, matching the+ // discipline the other arms document. Removing first put+ // a suspension point between forgetting and releasing: a+ // lane dropped there — or a release that failed — left+ // the partition in neither map, so no convergence ever+ // dispatched for it again and its cache, floors, and+ // producer leaked for the life of the process. Release is+ // idempotent, so a retry that re-runs it costs nothing.+ let was_warmed = self.warmed_partitions.lock().await.contains_key(&partition);+ let was_fenced = self.fenced_partitions.lock().await.contains(&partition);if was_warmed || was_fenced {tracing::info!(pod, partition, "converging to Released: releasing");self.handler.release_partition(partition).await?;+ self.warmed_partitions.lock().await.remove(&partition);+ self.fenced_partitions.lock().await.remove(&partition);counter!("personhog_coordination_partition_releases_total").increment(1);self.drain_notify.notify_one();did_work = true;diff --git a/rust/personhog-coordination/src/routing_table.rs b/rust/personhog-coordination/src/routing_table.rsindex 1a46abe5f02c..a914b55e6781 100644--- a/rust/personhog-coordination/src/routing_table.rs+++ b/rust/personhog-coordination/src/routing_table.rs@@ -1112,11 +1112,11 @@ impl RoutingTable {}// Pre-update the routing table before draining so that any- // new request arriving between drain and the independent- // assignment-watch dispatch routes to the new owner rather- // than to the old owner (which has already released). The- // assignment watch will later re-set the same value- // idempotently.+ // new request arriving mid-drain routes to the new owner+ // rather than to the old owner (which has already+ // released). The reconcile pass converges the table+ // against the assignment keys each tick and re-sets the+ // same value idempotently.table.write().awaitdiff --git a/rust/personhog-coordination/tests/common/mod.rs b/rust/personhog-coordination/tests/common/mod.rsindex 7b3e07035120..a1505bf7e7da 100644--- a/rust/personhog-coordination/tests/common/mod.rs+++ b/rust/personhog-coordination/tests/common/mod.rs@@ -75,6 +75,33 @@ wherepanic!("condition not met within {timeout:?}");}+/// `wait_for_condition` with a description of what is being waited on.+///+/// A bare timeout reports "condition not met", which names nothing —+/// and for tests whose whole assertion *is* the wait, that is the entire+/// failure message. Worth using wherever the timeout is the assertion+/// rather than a setup step. (`#[track_caller]` would be the zero-churn+/// answer, but it is a no-op on async fns.)+#[allow(dead_code)]+pub async fn wait_for_condition_named<F, Fut>(+ timeout: Duration,+ interval: Duration,+ what: &str,+ f: F,+) where+ F: Fn() -> Fut,+ Fut: Future<Output = bool>,+{+ let start = Instant::now();+ while start.elapsed() < timeout {+ if f().await {+ return;+ }+ tokio::time::sleep(interval).await;+ }+ panic!("timed out after {timeout:?} waiting for {what}");+}+// ── Component builders ──────────────────────────────────────────pub fn start_coordinator(@@ -185,6 +212,420 @@ pub fn start_pod_with_address(}}+/// A handler whose `resume_partition` fails a fixed number of times+/// before succeeding — the shape of a resume that has to take broker+/// state and hits a transient error.+pub struct FlakyResumeHandler {+ pub events: Arc<Mutex<Vec<HandoffEvent>>>,+ remaining_failures: AtomicUsize,+}++#[async_trait]+impl HandoffHandler for FlakyResumeHandler {+ async fn drain_partition_inflight(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Drained(partition));+ Ok(())+ }++ async fn warm_partition(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Warmed(partition));+ Ok(())+ }++ async fn release_partition(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Released(partition));+ Ok(())+ }++ async fn resume_partition(&self, partition: u32) -> Result<()> {+ if self.remaining_failures.load(Ordering::SeqCst) > 0 {+ self.remaining_failures.fetch_sub(1, Ordering::SeqCst);+ return Err(personhog_coordination::error::Error::invalid_state(+ "resume failed (test)",+ ));+ }+ self.events+ .lock()+ .await+ .push(HandoffEvent::Resumed(partition));+ Ok(())+ }+}++/// Start a pod whose first `failures` resume attempts fail.+pub fn start_pod_with_flaky_resume(+ store: Arc<PersonhogStore>,+ name: &str,+ failures: usize,+ cancel: CancellationToken,+) -> PodHandles {+ let events = Arc::new(Mutex::new(Vec::new()));+ let handler = FlakyResumeHandler {+ events: Arc::clone(&events),+ remaining_failures: AtomicUsize::new(failures),+ };+ let pod = PodHandle::new(+ store,+ PodConfig {+ pod_name: name.to_string(),+ lease_ttl: 10,+ heartbeat_interval: Duration::from_secs(3),+ advertise_address: None,+ reconcile_interval: Duration::from_secs(86_400),+ ..Default::default()+ },+ Arc::new(handler),+ None,+ );+ let token = cancel.child_token();+ let join_handle = tokio::spawn(async move { pod.run(token).await });+ PodHandles {+ events,+ join_handle: Some(join_handle),+ }+}++/// A handler whose first `failures` release attempts fail — the shape of+/// a release that has to give back broker state and hits a transient+/// error.+pub struct FlakyReleaseHandler {+ pub events: Arc<Mutex<Vec<HandoffEvent>>>,+ remaining_failures: AtomicUsize,+}++#[async_trait]+impl HandoffHandler for FlakyReleaseHandler {+ async fn drain_partition_inflight(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Drained(partition));+ Ok(())+ }++ async fn warm_partition(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Warmed(partition));+ Ok(())+ }++ async fn release_partition(&self, partition: u32) -> Result<()> {+ if self.remaining_failures.load(Ordering::SeqCst) > 0 {+ self.remaining_failures.fetch_sub(1, Ordering::SeqCst);+ return Err(personhog_coordination::error::Error::invalid_state(+ "release failed (test)",+ ));+ }+ self.events+ .lock()+ .await+ .push(HandoffEvent::Released(partition));+ Ok(())+ }++ async fn resume_partition(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Resumed(partition));+ Ok(())+ }+}++/// Start a pod whose first `failures` release attempts fail.+pub fn start_pod_with_flaky_release(+ store: Arc<PersonhogStore>,+ name: &str,+ failures: usize,+ cancel: CancellationToken,+) -> PodHandles {+ let events = Arc::new(Mutex::new(Vec::new()));+ let handler = FlakyReleaseHandler {+ events: Arc::clone(&events),+ remaining_failures: AtomicUsize::new(failures),+ };+ let pod = PodHandle::new(+ store,+ PodConfig {+ pod_name: name.to_string(),+ lease_ttl: 10,+ heartbeat_interval: Duration::from_secs(3),+ advertise_address: None,+ reconcile_interval: Duration::from_secs(86_400),+ ..Default::default()+ },+ Arc::new(handler),+ None,+ );+ let token = cancel.child_token();+ let join_handle = tokio::spawn(async move { pod.run(token).await });+ PodHandles {+ events,+ join_handle: Some(join_handle),+ }+}++/// A handler whose `drain_partition_inflight` always fails for one+/// partition — the shape of a drain that cannot quiesce whatever the+/// pod does.+pub struct StuckDrainHandler {+ pub events: Arc<Mutex<Vec<HandoffEvent>>>,+ stuck: u32,+}++#[async_trait]+impl HandoffHandler for StuckDrainHandler {+ async fn drain_partition_inflight(&self, partition: u32) -> Result<()> {+ if partition == self.stuck {+ self.events+ .lock()+ .await+ .push(HandoffEvent::DrainFailed(partition));+ return Err(personhog_coordination::error::Error::invalid_state(+ format!("drain refuses for partition {partition}"),+ ));+ }+ self.events+ .lock()+ .await+ .push(HandoffEvent::Drained(partition));+ Ok(())+ }++ async fn warm_partition(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Warmed(partition));+ Ok(())+ }++ async fn release_partition(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Released(partition));+ Ok(())+ }++ async fn resume_partition(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Resumed(partition));+ Ok(())+ }+}++/// Start a pod whose drain refuses for exactly one partition.+pub fn start_pod_with_stuck_drain(+ store: Arc<PersonhogStore>,+ name: &str,+ stuck: u32,+ lease_ttl: i64,+ cancel: CancellationToken,+) -> PodHandles {+ let events = Arc::new(Mutex::new(Vec::new()));+ let handler = StuckDrainHandler {+ events: Arc::clone(&events),+ stuck,+ };+ let pod = PodHandle::new(+ store,+ PodConfig {+ pod_name: name.to_string(),+ lease_ttl,+ heartbeat_interval: Duration::from_secs((lease_ttl / 5).max(1) as u64),+ advertise_address: None,+ reconcile_interval: Duration::from_secs(86_400),+ ..Default::default()+ },+ Arc::new(handler),+ None,+ );+ let token = cancel.child_token();+ let join_handle = tokio::spawn(async move { pod.run(token).await });+ PodHandles {+ events,+ join_handle: Some(join_handle),+ }+}++/// A handler whose `drain_partition_inflight` hangs forever for one+/// partition — the shape of in-flight work that never quiesces, which+/// only the self-fence's own timeout can end.+pub struct HangingDrainHandler {+ pub events: Arc<Mutex<Vec<HandoffEvent>>>,+ hung: u32,+}++#[async_trait]+impl HandoffHandler for HangingDrainHandler {+ async fn drain_partition_inflight(&self, partition: u32) -> Result<()> {+ if partition == self.hung {+ pending::<()>().await;+ }+ self.events+ .lock()+ .await+ .push(HandoffEvent::Drained(partition));+ Ok(())+ }++ async fn warm_partition(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Warmed(partition));+ Ok(())+ }++ async fn release_partition(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Released(partition));+ Ok(())+ }++ async fn resume_partition(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Resumed(partition));+ Ok(())+ }+}++/// Start a pod whose drain hangs forever for exactly one partition.+pub fn start_pod_with_hanging_drain(+ store: Arc<PersonhogStore>,+ name: &str,+ hung: u32,+ lease_ttl: i64,+ cancel: CancellationToken,+) -> PodHandles {+ let events = Arc::new(Mutex::new(Vec::new()));+ let handler = HangingDrainHandler {+ events: Arc::clone(&events),+ hung,+ };+ let pod = PodHandle::new(+ store,+ PodConfig {+ pod_name: name.to_string(),+ lease_ttl,+ heartbeat_interval: Duration::from_secs((lease_ttl / 5).max(1) as u64),+ advertise_address: None,+ reconcile_interval: Duration::from_secs(86_400),+ ..Default::default()+ },+ Arc::new(handler),+ None,+ );+ let token = cancel.child_token();+ let join_handle = tokio::spawn(async move { pod.run(token).await });+ PodHandles {+ events,+ join_handle: Some(join_handle),+ }+}++/// A handler whose `release_partition` always fails, recording every+/// partition it was asked to give up before it does.+///+/// Failing for *every* partition is what makes the attempt log+/// order-independent: the release loop walks a `HashSet`, so a handler+/// that failed for only one would prove nothing when that one happened to+/// be walked last.+pub struct FailingReleaseHandler {+ pub events: Arc<Mutex<Vec<HandoffEvent>>>,+ attempts: Arc<Mutex<Vec<u32>>>,+}++#[async_trait]+impl HandoffHandler for FailingReleaseHandler {+ async fn drain_partition_inflight(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Drained(partition));+ Ok(())+ }++ async fn warm_partition(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Warmed(partition));+ Ok(())+ }++ async fn release_partition(&self, partition: u32) -> Result<()> {+ self.attempts.lock().await.push(partition);+ Err(personhog_coordination::error::Error::invalid_state(+ format!("release refuses for partition {partition}"),+ ))+ }++ async fn resume_partition(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Resumed(partition));+ Ok(())+ }+}++/// Start a pod whose every release fails, alongside the log of which+/// partitions it was asked to release.+pub fn start_pod_with_failing_release(+ store: Arc<PersonhogStore>,+ name: &str,+ lease_ttl: i64,+ cancel: CancellationToken,+) -> (PodHandles, Arc<Mutex<Vec<u32>>>) {+ let events = Arc::new(Mutex::new(Vec::new()));+ let attempts = Arc::new(Mutex::new(Vec::new()));+ let handler = FailingReleaseHandler {+ events: Arc::clone(&events),+ attempts: Arc::clone(&attempts),+ };+ let pod = PodHandle::new(+ store,+ PodConfig {+ pod_name: name.to_string(),+ lease_ttl,+ heartbeat_interval: Duration::from_secs((lease_ttl / 5).max(1) as u64),+ advertise_address: None,+ reconcile_interval: Duration::from_secs(86_400),+ ..Default::default()+ },+ Arc::new(handler),+ None,+ );+ let token = cancel.child_token();+ let join_handle = tokio::spawn(async move { pod.run(token).await });+ (+ PodHandles {+ events,+ join_handle: Some(join_handle),+ },+ attempts,+ )+}+/// Start a pod whose warm_partition blocks forever. Useful for testing/// crashes during the Warming phase.pub fn start_pod_blocking(@@ -422,6 +863,10 @@ impl Drop for FlakyProxy {#[derive(Debug, Clone, PartialEq, Eq)]pub enum HandoffEvent {Drained(u32),+ /// A drain attempt that returned an error — pushed by handlers whose+ /// failures are the scenario, so tests can sequence on the attempt+ /// having happened rather than racing the watch.+ DrainFailed(u32),Warmed(u32),Released(u32),Resumed(u32),diff --git a/rust/personhog-coordination/tests/integration.rs b/rust/personhog-coordination/tests/integration.rsindex f1e8b862eaaa..448ba252e119 100644--- a/rust/personhog-coordination/tests/integration.rs+++ b/rust/personhog-coordination/tests/integration.rs@@ -2272,7 +2272,7 @@ async fn draining_old_owner_does_not_trigger_cleanup() {store.put_handoff(&handoff).await.unwrap();// Start the coordinator and a real pod. The new pod registering- // triggers a pod-change event and runs `cleanup_stale_handoffs`,+ // triggers a pod-change event and runs the dead-new-owner cancellation,// which must leave the handoff alone: the new owner is live, and the// old owner's state is not cleanup's concern.let strategy: Arc<dyn AssignmentStrategy> = Arc::new(StickyBalancedStrategy);@@ -2414,7 +2414,7 @@ async fn freezing_blocks_until_routers_ack_before_draining() {store.set_total_partitions(NUM_PARTITIONS).await.unwrap();- // Register both owner pods: the new owner so `cleanup_stale_handoffs`+ // Register both owner pods: the new owner so the dead-new-owner cancellation// doesn't delete the injected handoff, the old owner so the scenario// matches a live in-flight handoff. They don't run real handlers — we// just need their etcd registrations to exist.@@ -2531,7 +2531,7 @@ async fn initial_assignment_skips_draining_phase() {store.set_total_partitions(NUM_PARTITIONS).await.unwrap();- // Register the new_owner pod so `cleanup_stale_handoffs` doesn't+ // Register the new_owner pod so the dead-new-owner cancellation doesn't// delete the injected handoff for missing-target reasons.let lease = store.grant_lease(60).await.unwrap();let new_pod = RegisteredPod {diff --git a/rust/personhog-coordination/tests/protocol_hardening.rs b/rust/personhog-coordination/tests/protocol_hardening.rsindex 97a69a74270b..14e82ade80df 100644--- a/rust/personhog-coordination/tests/protocol_hardening.rs+++ b/rust/personhog-coordination/tests/protocol_hardening.rs@@ -22,10 +22,12 @@ use assignment_coordination::store::parse_watch_value;use async_trait::async_trait;use common::{revoke_lease_of_key, start_coordinator, start_coordinator_named,- start_coordinator_reconcile_parked, start_pod, start_pod_gated, start_pod_with_lease_ttl,- start_router_with_lease_ttl, store_at, test_store, test_store_with_prefix, wait_for_condition,- CutoverEvent, FlakyProxy, HandoffEvent, MockCutoverHandler, MockHandoffHandler, ETCD_ENDPOINT,- POLL_INTERVAL, WAIT_TIMEOUT,+ start_coordinator_reconcile_parked, start_pod, start_pod_gated, start_pod_with_failing_release,+ start_pod_with_flaky_release, start_pod_with_flaky_resume, start_pod_with_hanging_drain,+ start_pod_with_lease_ttl, start_pod_with_stuck_drain, start_router_with_lease_ttl, store_at,+ test_store, test_store_with_prefix, wait_for_condition, wait_for_condition_named, CutoverEvent,+ FlakyProxy, HandoffEvent, MockCutoverHandler, MockHandoffHandler, ETCD_ENDPOINT, POLL_INTERVAL,+ WAIT_TIMEOUT,};use personhog_coordination::error::Result;use personhog_coordination::routing_table::{RoutingTable, RoutingTableConfig, StashHandler};@@ -133,20 +135,25 @@ async fn pod_self_fences_locally_and_rejoins_after_lease_loss() {// Lease loss must self-fence: the held partition is released// locally before any rejoin, because the coordinator already treats// the expired lease as death and may be reassigning. The fence must- // drain before it releases — release alone unfences and drops the- // cache without waiting, letting an already-admitted write ack- // after the replacement owner's warm — so `Drained` must precede- // `Released` in the fence sequence.- wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {- let events = Arc::clone(&events);- async move {- events- .lock()- .await- .iter()- .any(|e| matches!(e, HandoffEvent::Released(0)))- }- })+ // drain before it releases — draining leaves nothing in flight, so+ // the release that follows unfences a partition with no admitted+ // write remaining and drops a cache no handler is still using — so+ // `Drained` must precede `Released` in the fence sequence.+ wait_for_condition_named(+ WAIT_TIMEOUT,+ POLL_INTERVAL,+ "the lease-loss self-fence to release the held partition",+ || {+ let events = Arc::clone(&events);+ async move {+ events+ .lock()+ .await+ .iter()+ .any(|e| matches!(e, HandoffEvent::Released(0)))+ }+ },+ ).await;{let events = events.lock().await;@@ -3135,3 +3142,486 @@ async fn budget_exhaustion_fences_before_deregistering() {"the teardown must deregister on the way out");}++/// A resume that fails must leave the partition still marked fenced, so+/// a later convergence retries it. Clearing the local fence before the+/// handler succeeds strands the data plane fenced with no branch left to+/// re-enter: writes rejected forever while every convergence reports+/// success and no budget escalates.+#[tokio::test]+async fn pod_retries_resume_after_a_failed_attempt() {+ let store = test_store("handoff-cancel-resume-retry").await;+ let cancel = CancellationToken::new();++ let pod = start_pod_with_flaky_resume(Arc::clone(&store), "resume-flaky-a", 1, cancel.clone());++ let check_store = Arc::clone(&store);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let store = Arc::clone(&check_store);+ async move {+ store+ .list_pods()+ .await+ .map(|pods| pods.iter().any(|p| p.pod_name == "resume-flaky-a"))+ .unwrap_or(false)+ }+ })+ .await;++ put_handoff(&store, 0, None, "resume-flaky-a", HandoffPhase::Warming).await;+ wait_for_event(&pod.events, HandoffEvent::Warmed(0)).await;+ assert!(store.complete_handoff(0).await.expect("complete"));+ store.delete_handoff(0).await.expect("cleanup");++ put_handoff(+ &store,+ 0,+ Some("resume-flaky-a"),+ "resume-flaky-b",+ HandoffPhase::Draining,+ )+ .await;+ wait_for_event(&pod.events, HandoffEvent::Drained(0)).await;++ // Cancel the handoff. The first resume fails; the pod must come back+ // to it rather than treating the partition as resumed.+ store.delete_handoff(0).await.expect("delete handoff");+ wait_for_event(&pod.events, HandoffEvent::Resumed(0)).await;++ cancel.cancel();+}++/// A drain that cannot quiesce must not keep the pod serving everything+/// else it no longer owns.+///+/// Self-fencing runs because the pod has lost the right to serve, so the+/// release is the point of it. Returning on the first drain failure left+/// every other held partition still served by a pod with no lease —+/// precisely the zombie the fence exists to prevent.+#[tokio::test]+async fn a_stuck_drain_does_not_strand_the_other_partitions_on_lease_loss() {+ let (store, prefix) = test_store_with_prefix("stuck-drain-fence").await;+ let cancel = CancellationToken::new();+ let pod = start_pod_with_stuck_drain(Arc::clone(&store), "stuck-pod-0", 1, 5, cancel.clone());++ let check_store = Arc::clone(&store);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let store = Arc::clone(&check_store);+ async move {+ store+ .list_pods()+ .await+ .map(|pods| pods.iter().any(|p| p.pod_name == "stuck-pod-0"))+ .unwrap_or(false)+ }+ })+ .await;++ // Two partitions: one whose drain refuses, one ordinary.+ for partition in [0, 1] {+ put_handoff(+ &store,+ partition,+ None,+ "stuck-pod-0",+ HandoffPhase::Warming,+ )+ .await;+ }+ let events = Arc::clone(&pod.events);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let events = Arc::clone(&events);+ async move {+ let seen = events.lock().await;+ [0u32, 1u32].iter().all(|p| {+ seen.iter()+ .any(|e| matches!(e, HandoffEvent::Warmed(w) if w == p))+ })+ }+ })+ .await;++ revoke_lease_of_key(&format!("{prefix}pods/stuck-pod-0")).await;++ // Partition 0's drain succeeds and 1's never will, so 0 must still+ // be given up.+ wait_for_condition_named(+ WAIT_TIMEOUT,+ POLL_INTERVAL,+ "partition 0 to be released despite partition 1's drain refusing",+ || {+ let events = Arc::clone(&events);+ async move {+ events+ .lock()+ .await+ .iter()+ .any(|e| matches!(e, HandoffEvent::Released(0)))+ }+ },+ )+ .await;++ // And 1 must not be. Its writes are still in flight and will ack+ // whatever we do — so releasing would unfence fresh admissions on a+ // leaseless pod, drop the cache out from under those handlers, and+ // erase the one record that the partition was never given up.+ assert!(+ !events+ .lock()+ .await+ .iter()+ .any(|e| matches!(e, HandoffEvent::Released(1))),+ "a partition whose drain never quiesced must stay held, not be released"+ );++ cancel.cancel();+}++/// A drain that outlives the self-fence's bound is a failure, not a+/// quiesce.+///+/// The timeout arm is the only exit for in-flight work that never+/// finishes, and it must not count the partition as drained: its writes+/// are still in flight and will ack whatever happens next, so releasing+/// would unfence fresh admissions on a leaseless pod, drop the cache+/// out from under the handlers still using it, and erase the one record+/// that the partition was never given up. The timed-out partition stays+/// held, and the recorded failure ends the run so the process restart+/// clears the stuck work by death.+#[tokio::test]+async fn a_drain_that_times_out_is_a_failure_not_a_quiesce() {+ let (store, prefix) = test_store_with_prefix("hung-drain-fence").await;+ let cancel = CancellationToken::new();+ let mut pod =+ start_pod_with_hanging_drain(Arc::clone(&store), "hung-pod-0", 1, 5, cancel.clone());++ let check_store = Arc::clone(&store);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let store = Arc::clone(&check_store);+ async move {+ store+ .list_pods()+ .await+ .map(|pods| pods.iter().any(|p| p.pod_name == "hung-pod-0"))+ .unwrap_or(false)+ }+ })+ .await;++ // Two partitions: one whose drain hangs past the bound, one ordinary.+ for partition in [0, 1] {+ put_handoff(&store, partition, None, "hung-pod-0", HandoffPhase::Warming).await;+ }+ let events = Arc::clone(&pod.events);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let events = Arc::clone(&events);+ async move {+ let seen = events.lock().await;+ [0u32, 1u32].iter().all(|p| {+ seen.iter()+ .any(|e| matches!(e, HandoffEvent::Warmed(w) if w == p))+ })+ }+ })+ .await;++ revoke_lease_of_key(&format!("{prefix}pods/hung-pod-0")).await;++ // The run must end: a partition it could neither drain nor release+ // still has its cache and authority, so in-place recovery is refused.+ // Under a timeout that counts as a quiesce there is no failure to+ // report, the pod starts a new session, and this bound expires.+ let run = pod.join_handle.take().expect("the pod is running");+ let outcome = tokio::time::timeout(WAIT_TIMEOUT, run)+ .await+ .expect("a pod whose drain timed out must stop rather than start a new session")+ .expect("the pod task must not panic");+ assert!(+ outcome.is_err(),+ "a drain cut off by the self-fence bound must end the run, not recover in place"+ );++ // The ordinary partition was still given up, and the hung one was+ // not: release without a quiesce is the acked-write loss the drain+ // phase exists to prevent.+ let seen = events.lock().await;+ assert!(+ seen.iter().any(|e| matches!(e, HandoffEvent::Released(0))),+ "partition 0 quiesced and must be released despite partition 1 hanging: {seen:?}"+ );+ assert!(+ !seen.iter().any(|e| matches!(e, HandoffEvent::Released(1))),+ "a partition whose drain timed out must stay held, not be released: {seen:?}"+ );+ drop(seen);++ cancel.cancel();+}++/// A drain that fails must still leave the partition recorded as fenced.+///+/// The handler fences the data plane as its first act and can fail+/// afterwards. `resume_partition` — the only branch that lifts that+/// fence — is reachable only through `fenced_partitions`, so a record+/// written only on success leaves writes rejected with no branch left to+/// re-enter, while reads carry on and the convergence reports healthy.+#[tokio::test]+async fn a_failed_drain_still_leaves_a_partition_that_can_be_resumed() {+ let (store, _prefix) = test_store_with_prefix("failed-drain-resume").await;+ let cancel = CancellationToken::new();+ let pod = start_pod_with_stuck_drain(Arc::clone(&store), "stuck-pod-1", 0, 30, cancel.clone());++ let check_store = Arc::clone(&store);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let store = Arc::clone(&check_store);+ async move {+ store+ .list_pods()+ .await+ .map(|pods| pods.iter().any(|p| p.pod_name == "stuck-pod-1"))+ .unwrap_or(false)+ }+ })+ .await;++ // Own it, then start a handoff away whose drain refuses.+ put_handoff(&store, 0, None, "stuck-pod-1", HandoffPhase::Warming).await;+ let events = Arc::clone(&pod.events);+ wait_for_event(&events, HandoffEvent::Warmed(0)).await;+ put_handoff(+ &store,+ 0,+ Some("stuck-pod-1"),+ "other-pod",+ HandoffPhase::Draining,+ )+ .await;++ // Sequence on the failed attempt, not the write: overwriting the+ // handoff before the pod has observed Draining would skip the drain+ // entirely, and with it the fence record this test exists to check.+ wait_for_condition_named(+ WAIT_TIMEOUT,+ POLL_INTERVAL,+ "the pod to attempt (and fail) the drain, recording the partition as fenced",+ || {+ let events = Arc::clone(&events);+ async move {+ events+ .lock()+ .await+ .iter()+ .any(|e| matches!(e, HandoffEvent::DrainFailed(0)))+ }+ },+ )+ .await;++ // Cancel the handoff. The pod is serving again, so it must resume —+ // which it can only do if the failed drain was still recorded.+ put_handoff(&store, 0, None, "stuck-pod-1", HandoffPhase::Complete).await;+ wait_for_condition_named(+ WAIT_TIMEOUT,+ POLL_INTERVAL,+ "the partition to resume, which needs the failed drain to have been recorded as fenced",+ || {+ let events = Arc::clone(&events);+ async move {+ events+ .lock()+ .await+ .iter()+ .any(|e| matches!(e, HandoffEvent::Resumed(0)))+ }+ },+ )+ .await;++ cancel.cancel();+}++/// A release that fails must not stop the pod giving up the rest.+///+/// Phase 2 is the point of self-fencing: it drops each partition's cache+/// and serving authority. Returning on the first release failure leaves+/// every partition after it in the loop still served by a pod with no+/// lease — the same zombie the drain phase collects its failures to+/// avoid, one phase later.+#[tokio::test]+async fn a_failing_release_does_not_stop_the_pod_giving_up_the_rest() {+ let (store, prefix) = test_store_with_prefix("failing-release-fence").await;+ let cancel = CancellationToken::new();+ let (pod, attempts) =+ start_pod_with_failing_release(Arc::clone(&store), "failing-rel-0", 5, cancel.clone());++ let check_store = Arc::clone(&store);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let store = Arc::clone(&check_store);+ async move {+ store+ .list_pods()+ .await+ .map(|pods| pods.iter().any(|p| p.pod_name == "failing-rel-0"))+ .unwrap_or(false)+ }+ })+ .await;++ for partition in [0, 1] {+ put_handoff(+ &store,+ partition,+ None,+ "failing-rel-0",+ HandoffPhase::Warming,+ )+ .await;+ }+ let events = Arc::clone(&pod.events);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let events = Arc::clone(&events);+ async move {+ let seen = events.lock().await;+ [0u32, 1u32].iter().all(|p| {+ seen.iter()+ .any(|e| matches!(e, HandoffEvent::Warmed(w) if w == p))+ })+ }+ })+ .await;++ revoke_lease_of_key(&format!("{prefix}pods/failing-rel-0")).await;++ // Both partitions must be asked, not just whichever the release loop+ // reached first. Polled by hand rather than through+ // `wait_for_condition` so the failure names what was missing instead+ // of reporting a bare timeout.+ let mut tried = Vec::new();+ for _ in 0..(WAIT_TIMEOUT.as_millis() / POLL_INTERVAL.as_millis()) {+ tried = attempts.lock().await.clone();+ if tried.contains(&0) && tried.contains(&1) {+ break;+ }+ tokio::time::sleep(POLL_INTERVAL).await;+ }+ assert!(+ tried.contains(&0) && tried.contains(&1),+ "a failed release must not strand the partitions after it; only {tried:?} of [0, 1] \+ were ever attempted"+ );++ cancel.cancel();+}++/// A self-fence that could not finish must refuse in-place recovery.+///+/// The pod's serving state no longer matches what it owns — a partition+/// it could neither drain nor release still has its cache and its+/// authority. Starting a fresh session on top of that is the zombie the+/// fence exists to prevent, so the run has to end and let the process+/// restart clear it. Reporting the failure is what sets that flag; the+/// release loop above runs first precisely so the report is not what+/// stops it.+#[tokio::test]+async fn a_self_fence_that_could_not_finish_refuses_in_place_recovery() {+ let (store, prefix) = test_store_with_prefix("poisoned-self-fence").await;+ let cancel = CancellationToken::new();+ let mut pod =+ start_pod_with_stuck_drain(Arc::clone(&store), "poisoned-pod-0", 0, 5, cancel.clone());++ let check_store = Arc::clone(&store);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let store = Arc::clone(&check_store);+ async move {+ store+ .list_pods()+ .await+ .map(|pods| pods.iter().any(|p| p.pod_name == "poisoned-pod-0"))+ .unwrap_or(false)+ }+ })+ .await;++ put_handoff(&store, 0, None, "poisoned-pod-0", HandoffPhase::Warming).await;+ let events = Arc::clone(&pod.events);+ wait_for_event(&events, HandoffEvent::Warmed(0)).await;++ revoke_lease_of_key(&format!("{prefix}pods/poisoned-pod-0")).await;++ let run = pod.join_handle.take().expect("the pod is running");+ let outcome = tokio::time::timeout(WAIT_TIMEOUT, run)+ .await+ .expect("a pod whose self-fence failed must stop rather than start a new session")+ .expect("the pod task must not panic");+ assert!(+ outcome.is_err(),+ "a pod that could not give up a partition must end its run, not recover in place"+ );++ cancel.cancel();+}++/// A release that fails must leave the pod still remembering it holds+/// the partition, so the retry can release it.+///+/// The arm used to forget first — remove from both ownership maps, then+/// call the handler — so a failed (or torn-down) release left the+/// partition in neither map, where no convergence ever dispatched for it+/// again: its cache, version floors, and installed producer leaked for+/// the life of the process, and a stale-tabled router was served from+/// the leaked cache instead of the bounce dropping it exists to produce.+#[tokio::test]+async fn a_failed_release_is_retried_rather_than_forgotten() {+ let (store, _prefix) = test_store_with_prefix("flaky-release").await;+ let cancel = CancellationToken::new();+ let pod =+ start_pod_with_flaky_release(Arc::clone(&store), "flaky-release-pod", 1, cancel.clone());++ let check_store = Arc::clone(&store);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let store = Arc::clone(&check_store);+ async move {+ store+ .list_pods()+ .await+ .map(|pods| pods.iter().any(|p| p.pod_name == "flaky-release-pod"))+ .unwrap_or(false)+ }+ })+ .await;++ put_handoff(&store, 0, None, "flaky-release-pod", HandoffPhase::Warming).await;+ wait_for_event(&pod.events, HandoffEvent::Warmed(0)).await;++ put_handoff(+ &store,+ 0,+ Some("flaky-release-pod"),+ "other-pod",+ HandoffPhase::Complete,+ )+ .await;++ // The first attempt fails and the convergence retries. The retry can+ // only release what the pod still remembers holding.+ wait_for_condition_named(+ WAIT_TIMEOUT,+ POLL_INTERVAL,+ "the retried release to succeed, which needs the failed attempt to not have \+ forgotten the partition",+ || {+ let events = Arc::clone(&pod.events);+ async move {+ events+ .lock()+ .await+ .iter()+ .any(|e| matches!(e, HandoffEvent::Released(0)))+ }+ },+ )+ .await;++ cancel.cancel();+}diff --git a/rust/personhog-leader/Cargo.toml b/rust/personhog-leader/Cargo.tomlindex d620acb2202c..2de039cce3ad 100644--- a/rust/personhog-leader/Cargo.toml+++ b/rust/personhog-leader/Cargo.toml@@ -40,8 +40,15 @@ tracing = { workspace = true }tracing-subscriber = { workspace = true }uuid = { workspace = true }+[features]+# Adversarial states the integration tests need to construct but that no+# production caller may reach — a producer condemned by a failed abort,+# for instance, which otherwise takes a broker fault to reproduce.+test-support = []+[dev-dependencies]health = { path = "../common/health" }+personhog-leader = { path = ".", features = ["test-support"] }tokio = { workspace = true, features = ["test-util"] }tokio-stream = "0.1"tokio-util = { workspace = true }diff --git a/rust/personhog-leader/src/config.rs b/rust/personhog-leader/src/config.rsindex 2ea96b87e084..72b1c61cae8d 100644--- a/rust/personhog-leader/src/config.rs+++ b/rust/personhog-leader/src/config.rs@@ -20,6 +20,31 @@ 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. Amortizes the commit round trip across+ /// concurrent same-partition writes.+ #[envconfig(default = "5")]+ pub fencing_window_ms: u64,++ /// Timeout for transactional init (fencing acquisition) and+ /// commit/abort operations.+ #[envconfig(default = "0")]+ pub fencing_txn_timeout_ms: u64,++ /// `message.timeout.ms` for the fenced changelog producer only. It is+ /// separate from the shared producer's because a fenced write's total+ /// must fit inside the lease self-fence runway — see+ /// [`Config::validate_fencing_timescales`].+ #[envconfig(default = "0")]+ pub fencing_message_timeout_ms: u32,+#[envconfig(default = "9102")]pub metrics_port: u16,@@ -52,8 +77,10 @@ pub struct Config {pub grpc_max_connection_age_secs: u64,/// Maximum concurrent in-flight gRPC requests before the server sheds- /// load with RESOURCE_EXHAUSTED so the router retries on another pod.- /// 0 = disabled.+ /// load with RESOURCE_EXHAUSTED. That code is terminal end to end —+ /// the router treats a delivered response as an outcome and the+ /// client does not retry it — so this is backpressure to the caller,+ /// not a redirect. 0 = disabled.#[envconfig(default = "0")]pub max_concurrent_requests: usize,@@ -198,6 +225,17 @@ pub struct Config {#[envconfig(default = "10000000")]pub dirty_index_max_entries: usize,+ /// Bound on the unresolved-version floors, its own knob rather than+ /// borrowing the dirty index's. The two grow under different+ /// failures: dirty marks accumulate whenever the writer lags, floors+ /// only when writes end without an answer — cancellations and+ /// ambiguous commits — which is orders of magnitude rarer. Past the+ /// bound, floors spill to one coarse per-partition value (safety+ /// survives; precision degrades), so this sizes memory, not+ /// correctness. The default is a fraction of the dirty index's.+ #[envconfig(default = "1000000")]+ pub emitted_versions_max_entries: usize,+// ── PG fallback ───────────────────────────────────────────────/// Postgres URL for cache miss fallback. If empty, cache misses/// return NotFound without querying PG. Must point at the primary:@@ -262,7 +300,299 @@ pub struct Config {pub heartbeat_interval_secs: u64,}+/// A fenced write must resolve inside the runway the lease keepalive+/// reserves for self-fencing (a third of the TTL). The bound is on the+/// *queued* write, not the lucky one: an arrival can park behind a+/// window that is already committing, so it pays that window's send and+/// commit before its own — hence the factor of two below.+///+/// A commit may also be re-attempted, and the shares are sized so that+/// every attempt the code will make still fits. The alternative was a+/// bound that quietly assumed a single attempt while the retry loop+/// spent three times it: an assertion the runway could not honour is+/// worse than a tighter timeout, because the whole point of deriving+/// these from the lease is that a write cannot outlive the fence that+/// ends its session.+///+/// librdkafka additionally requires `message.timeout.ms <= transaction+/// .timeout.ms`, and rejects a `transaction.timeout.ms` under a second.+/// Deriving both from the runway satisfies every relation by+/// construction wherever the lease TTL leaves room, and+/// [`Config::validate_fencing_timescales`] refuses the configurations+/// where it does not.+const FENCING_MESSAGE_SHARE: u32 = 1;+const FENCING_TXN_SHARE: u32 = 3;+const FENCING_SHARE_BASE: u32 = 10;++/// How many times a window's commit is attempted in total, counting the+/// first.+pub const FENCING_COMMIT_ATTEMPTS: u32 = 2;++/// How many times a window's abort is attempted in total.+///+/// One, deliberately. An abort that does not land leaves the producer in+/// a state it cannot begin another transaction from — which is a+/// condemned fence, given up on the next write and re-taken by a fresh+/// acquisition, whose `init_transactions` aborts the pending transaction+/// at the broker as a side effect. Retrying the abort is therefore a+/// slower, less reliable version of a recovery that already exists, and+/// it is not free: every attempt is bounded by the transaction timeout+/// and has to fit the same runway.+pub const FENCING_ABORT_ATTEMPTS: u32 = 1;++/// Every call bounded by the transaction timeout that one window can+/// make. Both the runway bound and the broker's own patience are sized+/// from this, so the two cannot drift apart.+pub const FENCING_TXN_CALLS: u32 = FENCING_COMMIT_ATTEMPTS + FENCING_ABORT_ATTEMPTS;++/// librdkafka's documented minimum for `transaction.timeout.ms`.+const MIN_TXN_TIMEOUT: Duration = Duration::from_millis(1000);+/// A floor for the send timeout; zero means *no timeout* to librdkafka,+/// the opposite of what this bound exists to express.+const MIN_MESSAGE_TIMEOUT: Duration = Duration::from_millis(250);++/// Apache Kafka's default `transaction.max.timeout.ms`. A producer that+/// asks for longer is refused at `init_transactions` rather than trimmed.+const MAX_BROKER_TXN_TIMEOUT: Duration = Duration::from_secs(900);+impl Config {+ /// The runway the keepalive reserves for the local fence: it+ /// declares lease loss after two thirds of the TTL, leaving the+ /// final third for the fence to land before the coordinator can+ /// treat the lease as expired.+ pub fn lease_fence_runway(&self) -> Duration {+ Duration::from_millis((self.lease_ttl.max(0) as u64).saturating_mul(1000) / 3)+ }++ /// Slack the drain spends outside the writes themselves: the settle+ /// wait that follows `wait_until_empty`, plus one poll interval of+ /// granularity on the wait (the coordination drain polls at 50ms).+ /// Subtracted from the runway before sizing the write budget — sizing+ /// against the full runway left the lease-loss drain oversubscribed+ /// by construction, so worst-case queueing failed the drain and cost+ /// a restart to load rather than to failure.+ fn fencing_drain_slack(&self) -> Duration {+ self.fencing_settle_budget() + Duration::from_millis(50)+ }++ /// The budget one write may spend, derived so that a write queued+ /// behind another — and the settle that follows the queue draining —+ /// still finishes inside the runway.+ fn fencing_budget(&self) -> Duration {+ self.lease_fence_runway()+ .saturating_sub(Duration::from_millis(self.fencing_window_ms))+ .saturating_sub(self.fencing_drain_slack())+ / 2+ }++ /// How long a fenced send may take.+ pub fn fencing_message_timeout(&self) -> Duration {+ if self.fencing_message_timeout_ms > 0 {+ return Duration::from_millis(u64::from(self.fencing_message_timeout_ms));+ }+ (self.fencing_budget() * FENCING_MESSAGE_SHARE / FENCING_SHARE_BASE)+ .max(MIN_MESSAGE_TIMEOUT)+ }++ /// How long a transaction init, commit, or abort may take.+ pub fn fencing_txn_timeout(&self) -> Duration {+ if self.fencing_txn_timeout_ms > 0 {+ return Duration::from_millis(self.fencing_txn_timeout_ms);+ }+ (self.fencing_budget() * FENCING_TXN_SHARE / FENCING_SHARE_BASE).max(MIN_TXN_TIMEOUT)+ }++ /// The producer queue each fenced producer gets, in MiB.+ ///+ /// The shared producer's queue is sized for one client; the fenced+ /// path creates one producer *per owned partition*, so inheriting+ /// that figure multiplies it by the partition count. A lone survivor+ /// owning every partition would be entitled to the whole product,+ /// which for the deployed shape is several gigabytes against a pod+ /// sized for one — a client spreading large property updates across+ /// partitions while Kafka is slow could fill the independent queues+ /// and exhaust the leader.+ ///+ /// So the budget is the aggregate, divided. The floor keeps a+ /// high-partition-count deployment from starving any single producer+ /// below a workable depth; it trades the guarantee for a bound that+ /// is still far under the un-divided figure.+ pub fn fencing_queue_mib(&self, partitions: u32) -> u32 {+ // The floor cannot be unconditional: above roughly fifty+ // partitions it would start multiplying again, and the aggregate+ // this exists to bound would scale with partition count exactly+ // as it did before. So it applies only while it stays inside the+ // aggregate, and past that point the division wins and each+ // producer gets a shallow queue — which is the honest answer for+ // a deployment with more partitions than a producer's worth of+ // memory to give them.+ // No floor. One was tried and was dead code: inside a guard that+ // only admits it when `MIN * partitions <= aggregate`, the+ // division already yields at least `MIN`, so the `max` never+ // fired. Applying it *outside* such a guard is worse — it+ // multiplies back up, which is the defect this division exists to+ // remove. The honest bound is the aggregate, and one MiB is the+ // smallest queue librdkafka will take.+ (self.kafka.kafka_producer_queue_mib / partitions.max(1)).max(1)+ }++ /// The same division for the message-count limit, which bounds the+ /// queue independently of record size.+ pub fn fencing_queue_messages(&self, partitions: u32) -> u32 {+ (self.kafka.kafka_producer_queue_messages / partitions.max(1)).max(1)+ }++ /// How long fence acquisition may take.+ ///+ /// Deliberately not the transaction timeout. That one is sized so+ /// that a *queued write* still resolves inside the lease runway, and+ /// acquisition is neither queued nor a write — it is two broker round+ /// trips, one of which makes the coordinator abort a predecessor's+ /// open transaction. Tying it to the runway meant re-budgeting the+ /// write path silently tightened acquisition, and acquisition happens+ /// fleet-wide during a deploy, which is the worst moment to have+ /// shortened it.+ ///+ /// It still has to fit inside the runway as a whole: a warm that+ /// outlives the lease it is warming for has nothing to serve.+ pub fn fencing_init_timeout(&self) -> Duration {+ const MIN_INIT_TIMEOUT: Duration = Duration::from_secs(2);+ self.fencing_txn_timeout()+ .max(MIN_INIT_TIMEOUT)+ .min(self.lease_fence_runway())+ }++ /// Ceiling on the drain's wait for an open window to commit.+ ///+ /// The wait exists to catch a committer about to fire anyway — it+ /// sleeps for the window, then commits — so a longer budget only+ /// helps when the commit is retrying, which is the case where the+ /// successor's abort is the right answer regardless.+ ///+ /// Absolute rather than derived from the lease, because what it has+ /// to fit inside is absolute: the pre-revoke self-fence allows three+ /// seconds for a whole drain. Bounding it by the broker's own+ /// patience instead would be inert — `fencing_txn_timeout` floors at+ /// a second and the window can make three such calls, so that bound+ /// never falls below four and a half, and every accepted lease would+ /// leave the cap doing all the work. Before the drain slack was paid+ /// out of the write budget it sat at 7.5s at the production lease+ /// (about 6s now), truncating on every shutdown with an open window+ /// and reporting the drain as failed.+ ///+ /// Residual: a `drain_timeout` configured under two seconds shrinks+ /// that allowance below this budget, and the leader cannot see the+ /// coordination-side value to derive against. Truncating is safe —+ /// the wait is best-effort — so the cost is a spurious drain+ /// failure, not a correctness one.+ pub fn fencing_settle_budget(&self) -> Duration {+ Duration::from_secs(2)+ }++ /// How long the broker may hold one of this pod's transactions open+ /// before abandoning it.+ ///+ /// A window lives from `begin_transaction` through its admission+ /// interval, its sends, and its commit, so the broker's patience has+ /// to cover all three — bounding it by the commit alone would let the+ /// broker abort a window this pod is still legitimately filling, and+ /// the resulting epoch bump reads exactly like a fence from a real+ /// successor.+ pub fn fencing_broker_txn_timeout(&self) -> Duration {+ // Every transaction-timeout-bounded call the window can make, not+ // just the first: a commit that retries, or a commit followed by+ // an abort, keeps the transaction open for all of them. A bound+ // that covers only one call lets the broker abandon a window this+ // pod is still legitimately working, and that epoch bump is+ // indistinguishable from a real successor's fence — so a+ // retriable blip would read as "this pod's claim is stale" and+ // cost the partition its fence.+ //+ // Half again on top, because the arithmetic is a floor: the+ // window sleep can overshoot and each blocking call waits its+ // turn on the blocking pool.+ let lifetime = Duration::from_millis(self.fencing_window_ms)+ + self.fencing_message_timeout()+ + self.fencing_txn_timeout() * FENCING_TXN_CALLS;+ lifetime + lifetime / 2+ }++ /// Every relation the fenced produce path depends on, checked at+ /// 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(());+ }+ let (message, txn, runway, window) = (+ self.fencing_message_timeout(),+ self.fencing_txn_timeout(),+ self.lease_fence_runway(),+ Duration::from_millis(self.fencing_window_ms),+ );+ // librdkafka fails `init_transactions` outright when this+ // exceeds the broker's `transaction.max.timeout.ms`, and it does+ // so on every partition, forever, with nothing but a heal-failure+ // counter to say why. The default broker ceiling is fifteen+ // minutes; a lease TTL of an hour or more derives past it.+ let broker_txn = self.fencing_broker_txn_timeout();+ if broker_txn > MAX_BROKER_TXN_TIMEOUT {+ return Err(format!(+ "the derived broker transaction timeout ({broker_txn:?}) exceeds the usual \+ broker ceiling ({MAX_BROKER_TXN_TIMEOUT:?} = transaction.max.timeout.ms): \+ init_transactions would fail on every partition; lower LEASE_TTL"+ ));+ }+ if txn < MIN_TXN_TIMEOUT {+ return Err(format!(+ "fencing transaction timeout ({txn:?}) is below librdkafka's minimum \+ ({MIN_TXN_TIMEOUT:?}); the producer would not start"+ ));+ }+ if message < MIN_MESSAGE_TIMEOUT {+ return Err(format!(+ "fencing message timeout ({message:?}) is below {MIN_MESSAGE_TIMEOUT:?}; \+ zero means no timeout at all to librdkafka"+ ));+ }+ if message > txn {+ return Err(format!(+ "fencing message timeout ({message:?}) exceeds the transaction timeout \+ ({txn:?}); librdkafka rejects the producer outright"+ ));+ }+ // Acquisition spends its timeout twice — once on the metadata+ // ping, once on init_transactions — and both have to land inside+ // the runway the keepalive reserves. The queued-write bound below+ // caps the derived value transitively at the defaults, but an+ // override can move the inputs, so the two-call bound is checked+ // by name.+ if self.fencing_init_timeout() * 2 > runway {+ return Err(format!(+ "fencing acquisition spends its timeout ({:?}) on two broker calls, which \+ does not fit the lease fence runway ({runway:?}); raise LEASE_TTL or lower \+ the transaction-timeout override",+ self.fencing_init_timeout()+ ));+ }+ // A write parked behind a committing window pays that window's+ // send and commit before its own, so the runway has to cover+ // two — each of them including every commit attempt the code+ // will make, not just the first.+ let queued_worst_case = window + (message + txn * FENCING_TXN_CALLS) * 2;+ let drain_room = runway.saturating_sub(self.fencing_drain_slack());+ if queued_worst_case > drain_room {+ return Err(format!(+ "a fenced write queued behind another can take {queued_worst_case:?} \+ (window {window:?} + 2 × (send {message:?} + {FENCING_TXN_CALLS} × commit/abort \+ {txn:?})), longer than the lease self-fence runway ({runway:?} = LEASE_TTL \+ {}s / 3); raise LEASE_TTL or lower the fencing timeouts",+ self.lease_ttl,+ ));+ }+ Ok(())+ }+pub fn grpc_keepalive_interval(&self) -> Option<Duration> {if self.grpc_keepalive_interval_secs == 0 {None@@ -359,3 +689,309 @@ mod tests {assert!(derive_advertise_address(&wildcard6, "").is_err());}}++#[cfg(test)]+mod fencing_timescale_tests {+ use super::*;++ fn fenced(lease_ttl: i64) -> Config {+ let mut config = Config::init_from_env().expect("defaults");+ config.kafka_transactional_fencing = true;+ config.lease_ttl = lease_ttl;+ config.fencing_txn_timeout_ms = 0;+ config.fencing_message_timeout_ms = 0;+ config+ }++ /// At any lease TTL the derivation must either satisfy every+ /// relation or be rejected — never produce a config that starts and+ /// then violates the runway, and never one librdkafka refuses.+ #[test]+ fn derived_timeouts_are_either_valid_or_rejected() {+ // 16 and 20 are the band where the bound's attempt count is the+ // only thing that decides acceptance — without them the sweep+ // cannot tell a two-call model from a three-call one.+ for lease_ttl in [0, 1, 5, 10, 16, 20, 21, 30, 60, 300] {+ let config = fenced(lease_ttl);+ if config.validate_fencing_timescales().is_ok() {+ let (message, txn) = (+ config.fencing_message_timeout(),+ config.fencing_txn_timeout(),+ );+ assert!(txn >= MIN_TXN_TIMEOUT, "LEASE_TTL={lease_ttl}");+ assert!(message >= MIN_MESSAGE_TIMEOUT, "LEASE_TTL={lease_ttl}");+ assert!(message <= txn, "LEASE_TTL={lease_ttl}");+ // Mirrors the production bound, retries included: a+ // check that models fewer attempts than the code makes+ // would accept exactly the configurations that break it.+ let queued = Duration::from_millis(config.fencing_window_ms)+ + (message + txn * FENCING_TXN_CALLS) * 2;+ assert!(+ queued <= config.lease_fence_runway(),+ "LEASE_TTL={lease_ttl}: queued worst case {queued:?} exceeds runway"+ );+ }+ }+ }++ /// The retry budget and the timeout shares are one decision split+ /// across two constants. Raising the attempt count without shrinking+ /// the shares puts the code back outside the runway it validates+ /// against — silently, because every existing test would still pass.+ #[test]+ fn the_production_ttl_affords_every_transaction_call() {+ let config = fenced(30);+ let (message, txn, runway, window) = (+ config.fencing_message_timeout(),+ config.fencing_txn_timeout(),+ config.lease_fence_runway(),+ Duration::from_millis(config.fencing_window_ms),+ );+ let queued = window + (message + txn * FENCING_TXN_CALLS) * 2;+ assert!(+ queued <= runway,+ "{FENCING_TXN_CALLS} transaction calls need {queued:?}, runway is {runway:?}: \+ lower FENCING_TXN_SHARE / FENCING_MESSAGE_SHARE, or lower the attempt counts"+ );+ // And it must be the attempts that are tight, not the shares+ // being trivially small: a budget that fits ten attempts would+ // mean the timeouts had collapsed toward their floors.+ let one_more = window + (message + txn * (FENCING_TXN_CALLS + 1)) * 2;+ assert!(+ one_more > runway,+ "the shares leave room for more attempts than are configured; raise \+ the attempt counts or the shares rather than leaving runway unused"+ );+ }++ /// The broker's patience has to cover the whole window, not the first+ /// call into it. A bound shorter than the lifetime lets the broker+ /// abandon a window this pod is still working, and that epoch bump+ /// is indistinguishable from a real successor's fence — so a+ /// retriable blip would cost the partition its fence and read as a+ /// stale claim.+ #[test]+ fn the_broker_waits_out_the_whole_window() {+ for lease_ttl in [21, 30, 60, 300] {+ let config = fenced(lease_ttl);+ if config.validate_fencing_timescales().is_err() {+ continue;+ }+ let lifetime = Duration::from_millis(config.fencing_window_ms)+ + config.fencing_message_timeout()+ + config.fencing_txn_timeout() * FENCING_TXN_CALLS;+ assert!(+ config.fencing_broker_txn_timeout() >= lifetime + lifetime / 2,+ "LEASE_TTL={lease_ttl}: broker bound {:?} leaves no slack over the window's \+ own worst case {lifetime:?} — the sleep overshoots and each blocking call \+ waits its turn on the pool",+ config.fencing_broker_txn_timeout(),+ );+ }+ }++ /// The fenced path creates one producer per owned partition, so the+ /// shared producer's queue limits are an aggregate to divide rather+ /// than a per-producer figure to copy. Inheriting them let a lone+ /// survivor owning every partition claim the whole product — several+ /// gigabytes on a pod sized for one — which a client can reach by+ /// spreading large property updates across partitions while Kafka is+ /// slow.+ #[test]+ fn fenced_producer_queues_do_not_scale_with_partition_count() {+ let config = fenced(30);+ let shared_mib = config.kafka.kafka_producer_queue_mib;+ let shared_messages = config.kafka.kafka_producer_queue_messages;++ for partitions in [1, 8, 16, 50, 64, 256, 1024, 4096] {+ let per_partition_mib = config.fencing_queue_mib(partitions);+ let per_partition_messages = config.fencing_queue_messages(partitions);+ assert!(+ per_partition_mib <= shared_mib,+ "partitions={partitions}: a single fenced producer must never be entitled \+ to more than the shared producer's whole queue"+ );+ // The aggregate is the invariant: every individual value+ // looked reasonable while the total scaled with the partition+ // count, which is how the original defect hid.+ // Either the whole fleet of producers fits the aggregate, or+ // every one of them is already at the smallest queue+ // librdkafka will take — past that point the budget cannot be+ // honoured at all, and the honest answer is the floor rather+ // than a number that quietly multiplies.+ let aggregate_mib = per_partition_mib * partitions;+ assert!(+ aggregate_mib <= shared_mib || per_partition_mib == 1,+ "partitions={partitions}: fenced producers together claim {aggregate_mib} MiB \+ against a shared budget of {shared_mib} MiB, with room to divide further"+ );+ let aggregate_messages = per_partition_messages as u64 * partitions as u64;+ assert!(+ aggregate_messages <= shared_messages as u64 || per_partition_messages == 1,+ "partitions={partitions}: fenced producers together claim \+ {aggregate_messages} queued messages against {shared_messages}"+ );+ }+ }++ /// Dividing must not round a producer down to a depth that cannot+ /// hold a window's worth of writes.+ /// Overrides are the only way to reach the librdkafka limits the+ /// derivation floors away from, so they are the only way these two+ /// checks ever fire — and without them a pod starts with a producer+ /// librdkafka refuses to create, or with no send timeout at all.+ #[test]+ fn overrides_outside_librdkafkas_limits_are_refused() {+ for (txn_ms, message_ms, fragment) in [+ (500u64, 0u32, "below librdkafka's minimum"),+ (2000, 100, "is below"),+ ] {+ let mut config = fenced(30);+ config.fencing_txn_timeout_ms = txn_ms;+ config.fencing_message_timeout_ms = message_ms;+ let err = config+ .validate_fencing_timescales()+ .expect_err("an override outside librdkafka's limits must not start");+ assert!(+ err.contains(fragment),+ "the refusal must say which limit it trips, got: {err}"+ );+ }+ }++ /// The pre-revoke self-fence allows three seconds for a whole drain,+ /// and the drain is `wait_until_empty` *then* this wait. A budget+ /// that ate the whole allowance would turn every shutdown with an+ /// open window into a reported drain failure — while a budget under+ /// the admission window cannot outwait the window it exists to+ /// settle.+ #[test]+ fn settling_fits_inside_the_shutdown_fence_bound() {+ for lease_ttl in [21, 30, 60, 300, 3599] {+ let config = fenced(lease_ttl);+ if config.validate_fencing_timescales().is_err() {+ continue;+ }+ assert!(+ config.fencing_settle_budget() < Duration::from_secs(3),+ "LEASE_TTL={lease_ttl}: settle budget {:?} does not leave the drain room \+ inside the self-fence's three-second allowance",+ config.fencing_settle_budget()+ );+ // The wait exists to catch a committer that sleeps for the+ // window and then commits, so a budget at or under the window+ // can never see one fire: every drain with an open window+ // would abandon the records it was meant to commit.+ assert!(+ config.fencing_settle_budget() > Duration::from_millis(config.fencing_window_ms),+ "LEASE_TTL={lease_ttl}: settle budget {:?} cannot outwait the {}ms admission \+ window it exists to settle",+ config.fencing_settle_budget(),+ config.fencing_window_ms+ );+ }+ }++ /// Acquisition is two broker round trips and happens fleet-wide+ /// during a deploy. Nothing asserted on its budget, and tying it to+ /// the write path's once already shortened it by a quarter as a side+ /// effect of re-budgeting writes.+ #[test]+ fn acquisition_keeps_its_own_budget() {+ for lease_ttl in [21, 30, 60, 300] {+ let config = fenced(lease_ttl);+ if config.validate_fencing_timescales().is_err() {+ continue;+ }+ assert!(+ config.fencing_init_timeout() >= Duration::from_secs(2),+ "LEASE_TTL={lease_ttl}: acquisition needs room for a broker round trip"+ );+ // The timeout bounds each of the two calls acquisition makes+ // — `fetch_metadata` then `init_transactions` — so the budget+ // the lease has to cover is twice what it names.+ assert!(+ config.fencing_init_timeout() * 2 <= config.lease_fence_runway(),+ "LEASE_TTL={lease_ttl}: a warm cannot outlive the lease it warms for"+ );+ }+ }++ #[test]+ fn a_high_partition_count_still_leaves_a_workable_queue() {+ let config = fenced(30);+ // The division alone leaves a workable depth at the deployed+ // shape, and never rounds to a value librdkafka would reject.+ assert_eq!(config.fencing_queue_mib(16), 25);+ assert_eq!(config.fencing_queue_messages(16), 625_000);+ assert!(config.fencing_queue_mib(1024) >= 1);+ assert!(config.fencing_queue_messages(1024) >= 1);+ assert!(+ config.fencing_queue_mib(0) >= 1,+ "partitions=0 must not divide by zero"+ );+ }++ /// A lease TTL long enough to derive past the broker's own ceiling+ /// must be refused at startup, not discovered as an acquisition that+ /// fails on every partition with only a counter to explain it.+ #[test]+ fn a_lease_ttl_that_outruns_the_broker_ceiling_is_refused() {+ let err = fenced(3607)+ .validate_fencing_timescales()+ .expect_err("an hour-long lease derives a transaction timeout no broker accepts");+ assert!(+ err.contains("transaction.max.timeout.ms"),+ "the refusal must name the broker setting it would trip, got: {err}"+ );+ // The band's edges, both sides: the last accepted TTL under the+ // broker ceiling, and the first accepted one above the librdkafka+ // floors once the drain slack is paid.+ fenced(3606)+ .validate_fencing_timescales()+ .expect("LEASE_TTL=3606 sits just inside the broker ceiling");+ fenced(27)+ .validate_fencing_timescales()+ .expect("LEASE_TTL=27 is the acceptance floor");+ assert!(+ fenced(26).validate_fencing_timescales().is_err(),+ "below the floor, the librdkafka minimums cannot fit the drain room"+ );+ // And the production value must stay comfortably inside it.+ fenced(30)+ .validate_fencing_timescales()+ .expect("LEASE_TTL=30 must remain usable");+ }++ /// The production lease TTL must actually be usable with fencing on,+ /// or the flag could never be enabled.+ #[test]+ fn the_production_lease_ttl_supports_fencing() {+ fenced(30)+ .validate_fencing_timescales()+ .expect("LEASE_TTL=30 must support fencing with derived timeouts");+ }++ #[test]+ fn a_lease_ttl_too_short_for_fencing_is_rejected() {+ assert!(fenced(5).validate_fencing_timescales().is_err());+ }++ #[test]+ fn an_override_that_can_outlive_the_fence_is_rejected() {+ let mut config = fenced(30);+ config.fencing_txn_timeout_ms = 60_000;+ assert!(config.validate_fencing_timescales().is_err());+ }++ #[test]+ fn an_override_librdkafka_would_reject_is_caught() {+ let mut config = fenced(30);+ config.fencing_txn_timeout_ms = 1_000;+ config.fencing_message_timeout_ms = 2_000;+ let err = config+ .validate_fencing_timescales()+ .expect_err("must reject");+ assert!(err.contains("librdkafka"), "got: {err}");+ }+}diff --git a/rust/personhog-leader/src/coordination/mod.rs b/rust/personhog-leader/src/coordination/mod.rsindex aa9e484c4d8f..9115e8cdf36e 100644--- a/rust/personhog-leader/src/coordination/mod.rs+++ b/rust/personhog-leader/src/coordination/mod.rs@@ -2,11 +2,13 @@ use std::sync::Arc;use std::time::Duration;use async_trait::async_trait;-use personhog_coordination::error::Result;+use personhog_coordination::error::{Error, Result};use personhog_coordination::pod::HandoffHandler;use tracing::info;use crate::cache::{DirtyIndex, PartitionedCache};+use crate::emitted::EmittedVersions;+use crate::fencing::{FenceGuard, FencedChangelogProducers};use crate::inflight::InflightTracker;use crate::warming::{warm_from_kafka, WarmClientPools, WarmingConfig};@@ -46,6 +48,22 @@ pub struct LeaderHandoffHandler {dirty_index: Arc<DirtyIndex>,warming: WarmingConfig,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>>,+ /// Shared with the service, so that giving up a partition also gives+ /// up the version floors held for its persons.+ emitted_versions: Arc<EmittedVersions>,+ /// Partitions whose fence this pod took during the convergence that+ /// is still running.+ ///+ /// A convergence to `Serving` can both warm and resume, in that+ /// order, and warming re-admits writes as its last act. Without this,+ /// the resume that follows re-acquires and bumps the epoch out from+ /// under every write admitted in between — the pod fencing its own+ /// live window.+ freshly_fenced: Arc<dashmap::DashSet<u32>>,}impl LeaderHandoffHandler {@@ -55,6 +73,8 @@ impl LeaderHandoffHandler {dirty_index: Arc<DirtyIndex>,warming: WarmingConfig,pools: Arc<WarmClientPools>,+ fenced: Option<Arc<FencedChangelogProducers>>,+ emitted_versions: Arc<EmittedVersions>,) -> Self {Self {cache,@@ -62,12 +82,29 @@ impl LeaderHandoffHandler {dirty_index,warming,pools,+ fenced,+ emitted_versions,+ freshly_fenced: Arc::new(dashmap::DashSet::new()),}}pub fn owns_partition(&self, partition: u32) -> bool {self.cache.has_partition(partition)}+ /// Stage the mark warming leaves behind. Warming itself needs a+ /// broker, and what these tests pin is the mark's lifetime across the+ /// convergences that follow, not how it comes to exist.+ #[cfg(test)]+ fn mark_freshly_fenced_for_test(&self, partition: u32) {+ self.freshly_fenced.insert(partition);+ }++ /// Whether a resume would take the fence rather than trust an earlier+ /// acquisition — the decision the mark exists to make.+ #[cfg(test)]+ fn would_reacquire_on_resume(&self, partition: u32) -> bool {+ !self.freshly_fenced.contains(&partition)+ }}#[async_trait]@@ -79,15 +116,65 @@ impl HandoffHandler for LeaderHandoffHandler {// DrainedAck where a late write could advance the Kafka HWM past// the point warming snapshots.self.inflight.fence(partition);+ // From here the partition is moving, so a fence taken by an+ // earlier convergence stops counting as fresh: the incoming owner+ // can take the epoch before the handoff is cancelled, and a+ // resume that skipped its re-acquire on the strength of that+ // stale mark would re-admit writes onto a producer the broker has+ // already moved past.+ self.freshly_fenced.remove(&partition);self.inflight.wait_until_empty(partition, DRAIN_POLL_INTERVAL).await;+ // A request cancelled mid-produce takes its handler — and the+ // count above — with it, leaving the record it enqueued in a+ // window nobody is waiting on. Committing that window here lands+ // the cancelled write below the cutoff the successor is about to+ // read, rather than leaving it to be aborted by whichever side+ // acts first.+ //+ // Best-effort by construction, and the drain proceeds either way:+ // 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;+ }info!(partition, "inflight drained; writes fenced");Ok(())}async fn warm_partition(&self, partition: u32) -> Result<()> {info!(partition, "warming partition cache from kafka");+ // Broker-side fencing before the warm read, not after: acquiring+ // the fence bumps the producer epoch and aborts any in-flight+ // transaction from a predecessor, so every write a stale owner+ // ever committed sits below the watermark the warm is about to+ // read. Fencing after the read would leave a gap where a zombie+ // commits an acked write the warm never sees.+ // Deliberately re-acquired even when this pod already holds a+ // fence from a convergence torn down before it could record the+ // warm. Skipping would spare the writes that warm admitted, but+ // it leaves this pod's own uncommitted records between the read+ // and the high watermark, and the warm below then waits for+ // 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)?;+ 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))+ } else {+ None+ };warm_from_kafka(&self.warming,&self.pools,@@ -100,23 +187,69 @@ 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);+ }info!(partition, "partition warmed");Ok(())}async fn release_partition(&self, partition: u32) -> Result<()> {info!(partition, "releasing partition");+ if let Some(fenced) = &self.fenced {+ fenced.release(partition);+ }self.inflight.unfence(partition);self.cache.drop_partition(partition);// The new owner's warming rebuilds its own marks; stale marks here// would only pin memory for a partition this pod no longer serves.self.dirty_index.clear_partition(partition);+ // The incoming owner derives versions from the changelog, which+ // is the authority these floors stood in for; carrying them would+ // only constrain a partition this pod no longer serves.+ self.emitted_versions.clear_partition(partition);+ self.freshly_fenced.remove(&partition);info!(partition, "partition released");Ok(())}async fn resume_partition(&self, partition: u32) -> Result<()> {info!(partition, "handoff cancelled; re-admitting writes");+ // The cancelled handoff's target may have gotten as far as+ // acquiring the changelog fence, which leaves this pod's producer+ // epoch-stale — every write would fail as fenced until the next+ // handoff. Re-acquiring bumps the epoch back to this pod before+ // writes are re-admitted. (No acked write can predate this: the+ // target never serves before the assignment flips.)+ //+ // Unless this convergence already took the fence on its way here.+ // Warming re-admits writes as its last act, so acquiring again+ // would bump the epoch out from under everything admitted since —+ // the pod fencing its own live window, and handing the successor+ // of a genuinely moved partition an epoch nobody asked for.+ if self.freshly_fenced.contains(&partition) {+ info!(+ partition,+ "fence already taken by this convergence; not re-acquiring on resume"+ );+ self.inflight.unfence(partition);+ return Ok(());+ }+ if let Some(fenced) = &self.fenced {+ fenced+ .acquire(partition)+ .await+ .map_err(Error::invalid_state)?;+ // 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.inflight.unfence(partition);Ok(())}@@ -176,6 +309,8 @@ mod tests {},},pools,+ None,+ Arc::new(EmittedVersions::new(1_000_000)),)}@@ -192,6 +327,28 @@ mod tests {assert!(!handler.owns_partition(42));}+ /// The incoming owner derives versions from the changelog, which is+ /// the authority these floors stand in for. Carrying one across a+ /// release would constrain a partition this pod no longer serves.+ #[tokio::test]+ async fn releasing_a_partition_forgets_the_versions_it_emitted() {+ let handler = handler();+ handler.cache.create_partition(3);+ let key = crate::cache::PersonCacheKey {+ team_id: 1,+ person_id: 7,+ };+ handler.emitted_versions.raise_for_test(3, key.clone(), 900);++ handler.release_partition(3).await.unwrap();++ assert_eq!(+ handler.emitted_versions.floor_for(3, &key, 5),+ 5,+ "a departed owner's floor must not survive the release"+ );+ }+#[tokio::test]async fn release_partition_is_idempotent_for_unknown_partition() {let handler = handler();@@ -228,4 +385,40 @@ mod tests {// received traffic between Freezing and the actual drain call.handler.drain_partition_inflight(7).await.unwrap();}++ /// A fence taken while warming only licenses skipping the re-acquire+ /// for the convergence that took it. Once a handoff drains the+ /// partition it is moving, and the incoming owner can take the epoch+ /// before the handoff is cancelled — so a resume that still trusted+ /// that mark would re-admit writes onto a producer the broker has+ /// moved past, which is exactly what the re-acquire exists to stop.+ #[tokio::test]+ async fn a_handoff_drain_retires_an_earlier_convergences_fence() {+ let handler = handler();+ handler.mark_freshly_fenced_for_test(7);+ assert!(+ !handler.would_reacquire_on_resume(7),+ "the convergence that just warmed holds a current fence"+ );++ handler.drain_partition_inflight(7).await.unwrap();++ assert!(+ handler.would_reacquire_on_resume(7),+ "a resume after a handoff drain must take the fence again"+ );+ }++ /// The mark is per partition: draining one must not force an unrelated+ /// partition's resume to bump its own epoch out from under live writes.+ #[tokio::test]+ async fn a_drain_retires_only_its_own_partitions_fence() {+ let handler = handler();+ handler.mark_freshly_fenced_for_test(7);+ handler.mark_freshly_fenced_for_test(8);++ handler.drain_partition_inflight(7).await.unwrap();++ assert!(!handler.would_reacquire_on_resume(8));+ }}diff --git a/rust/personhog-leader/src/emitted.rs b/rust/personhog-leader/src/emitted.rsnew file mode 100644index 000000000000..31bc252deb81--- /dev/null+++ b/rust/personhog-leader/src/emitted.rs@@ -0,0 +1,382 @@+//! Versions this pod put on the wire but never heard the outcome of.+//!+//! A changelog record can become durable without the write that produced+//! it learning so. A request cancelled while its send is in flight leaves+//! the record to ride its window's commit; a request cancelled while+//! waiting on that commit has already been counted, and the commit lands+//! with nobody to tell; and a commit whose outcome stays unknown is, by+//! construction, a record that may or may not exist.+//!+//! In each case the version is spent. The cache still holds the version+//! before the write, so the next write for that person derives the same+//! number again and produces a second record carrying it. The writer+//! keeps whichever of the two arrived first and discards the other — and+//! when the discarded one is the acked write, the acknowledgement was a+//! lie.+//!+//! Recording a floor costs nothing on the path that succeeds: the guard+//! is a stack value that only writes to the map when it is dropped+//! without an answer.++use std::sync::Arc;++use dashmap::DashMap;+use metrics::{counter, gauge};++use crate::cache::PersonCacheKey;++/// The highest version this pod emitted for a person without confirming+/// what became of it.+#[derive(Default)]+pub struct EmittedVersions {+ floors: DashMap<(u32, PersonCacheKey), i64>,+ /// The coarse fallback once `floors` is full: one spent version per+ /// partition rather than per person.+ ///+ /// A floor is only ever cleared by a later successful write for the+ /// same person, so persons written once and abandoned leave entries+ /// nothing collects — and a client can manufacture exactly that by+ /// updating unique persons while produce latency sits above its own+ /// deadline. Refusing writes at the bound would answer a memory+ /// exhaustion with an availability one, and these entries do not+ /// drain, so the refusal would never lift.+ ///+ /// Spilling keeps the safety property and gives up only precision:+ /// every person in the partition derives past the spilled version, so+ /// versions jump once and stay monotonic. A spilled floor is also+ /// never lowered — only `clear_partition` drops it, on release —+ /// which is safe for the same reason the jump is: nothing downstream+ /// reads a version as a count. The writer's guard is a strict+ /// greater-than, and ClickHouse collapses person rows by the highest+ /// version; both are indifferent to gaps of any size.+ partition_floors: DashMap<u32, i64>,+ capacity: usize,+}++impl EmittedVersions {+ pub fn new(capacity: usize) -> Self {+ Self {+ capacity,+ ..Default::default()+ }+ }++ /// The version a write for this person must exceed: whatever the+ /// caller derived from cached or recovered state, or an unresolved+ /// emission, whichever is further ahead.+ pub fn floor_for(&self, partition: u32, key: &PersonCacheKey, known: i64) -> i64 {+ let per_key = self+ .floors+ .get(&(partition, key.clone()))+ .map(|floor| *floor)+ .unwrap_or(known);+ let per_partition = self+ .partition_floors+ .get(&partition)+ .map(|floor| *floor)+ .unwrap_or(known);+ known.max(per_key).max(per_partition)+ }++ fn raise(&self, partition: u32, key: PersonCacheKey, version: i64) {+ // At the bound, spill to the partition rather than admit an entry+ // nothing will collect. Keys already tracked keep their precise+ // floor, so the degradation only reaches persons arriving after+ // the map is full.+ if self.floors.len() >= self.capacity+ && !self.floors.contains_key(&(partition, key.clone()))+ {+ {+ let mut entry = self.partition_floors.entry(partition).or_insert(version);+ if *entry < version {+ *entry = version;+ }+ }+ counter!("personhog_leader_unresolved_versions_spilled_total").increment(1);+ return;+ }+ // The entry guard holds a write lock on its shard, and `len`+ // walks every shard — including that one. Anything that reads the+ // map as a whole has to wait until the guard is gone.+ {+ let mut entry = self.floors.entry((partition, key)).or_insert(version);+ if *entry < version {+ *entry = version;+ }+ }+ counter!("personhog_leader_unresolved_versions_total").increment(1);+ gauge!("personhog_leader_unresolved_versions").set(self.floors.len() as f64);+ }++ /// Forget a person's floor: the cache now holds a version at least+ /// this high, so it already carries the constraint.+ fn resolve(&self, partition: u32, key: &PersonCacheKey, version: i64) {+ // Same discipline as `raise`: settle the map first, then read it.+ let removed = self+ .floors+ .remove_if(&(partition, key.clone()), |_, floor| *floor <= version)+ .is_some();+ if removed {+ gauge!("personhog_leader_unresolved_versions").set(self.floors.len() as f64);+ }+ }++ /// Drop every floor for a partition's persons. Ownership is leaving,+ /// and the incoming owner derives versions from the changelog, which+ /// is the authority these floors stand in for.+ pub fn clear_partition(&self, partition: u32) {+ self.floors.retain(|(owner, _), _| *owner != partition);+ self.partition_floors.remove(&partition);+ gauge!("personhog_leader_unresolved_versions").set(self.floors.len() as f64);+ }++ /// Stage the state a cancelled or indeterminate write leaves behind.+ ///+ /// The real path needs a request to vanish mid-produce or a broker to+ /// fail a commit ambiguously; neither is stageable against a healthy+ /// cluster, and what matters is that the *derivation* consults the+ /// floor afterwards.+ #[cfg(any(test, feature = "test-support"))]+ pub fn raise_for_test(&self, partition: u32, key: PersonCacheKey, version: i64) {+ self.raise(partition, key, version);+ }++ #[cfg(test)]+ fn len(&self) -> usize {+ self.floors.len()+ }+}++/// Holds a version open until the write that emitted it is answered for.+///+/// Dropped without a call to [`EmittedVersionGuard::resolved`] — a+/// cancelled request, or a commit whose fate is unknown — the version is+/// recorded as spent so no later write can reuse it.+pub struct EmittedVersionGuard {+ versions: Arc<EmittedVersions>,+ partition: u32,+ key: PersonCacheKey,+ version: i64,+ settled: bool,+}++impl EmittedVersionGuard {+ pub fn new(+ versions: Arc<EmittedVersions>,+ partition: u32,+ key: PersonCacheKey,+ version: i64,+ ) -> Self {+ Self {+ versions,+ partition,+ key,+ version,+ settled: true,+ }+ }++ /// Arm the guard: from here the record may exist, so an unanswered+ /// drop has to assume it does.+ pub fn emitting(&mut self) {+ self.settled = false;+ }++ /// The write resolved and the cache carries the version now.+ pub fn resolved(mut self) {+ self.settled = true;+ self.versions+ .resolve(self.partition, &self.key, self.version);+ }++ /// The record is known not to exist — the window aborted, or the send+ /// never reached the broker. The version is free again.+ pub fn discarded(mut self) {+ self.settled = true;+ }+}++impl Drop for EmittedVersionGuard {+ fn drop(&mut self) {+ if !self.settled {+ self.versions+ .raise(self.partition, self.key.clone(), self.version);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn key(person_id: i64) -> PersonCacheKey {+ PersonCacheKey {+ team_id: 1,+ person_id,+ }+ }++ /// The whole point: a write that is never answered for spends its+ /// version, so the next write derives past it instead of colliding.+ #[test]+ fn an_unanswered_emission_raises_the_floor() {+ let versions = Arc::new(EmittedVersions::new(8));+ let mut guard = EmittedVersionGuard::new(Arc::clone(&versions), 0, key(1), 5);+ guard.emitting();+ drop(guard);++ assert_eq!(versions.floor_for(0, &key(1), 4), 5);+ }++ /// A resolved write needs no floor: the cache holds the version, so+ /// the ordinary derivation already accounts for it.+ #[test]+ fn a_resolved_emission_leaves_no_floor() {+ let versions = Arc::new(EmittedVersions::new(8));+ let mut guard = EmittedVersionGuard::new(Arc::clone(&versions), 0, key(1), 5);+ guard.emitting();+ guard.resolved();++ assert_eq!(versions.floor_for(0, &key(1), 4), 4);+ assert_eq!(versions.len(), 0);+ }++ /// A window that demonstrably aborted frees its version, so ordinary+ /// retryable failures do not march the counter forward.+ #[test]+ fn a_discarded_emission_leaves_no_floor() {+ let versions = Arc::new(EmittedVersions::new(8));+ let mut guard = EmittedVersionGuard::new(Arc::clone(&versions), 0, key(1), 5);+ guard.emitting();+ guard.discarded();++ assert_eq!(versions.floor_for(0, &key(1), 4), 4);+ }++ /// A guard that never armed covers a write rejected before anything+ /// could reach the broker.+ #[test]+ fn an_unarmed_guard_records_nothing() {+ let versions = Arc::new(EmittedVersions::new(8));+ drop(EmittedVersionGuard::new(+ Arc::clone(&versions),+ 0,+ key(1),+ 5,+ ));++ assert_eq!(versions.floor_for(0, &key(1), 4), 4);+ }++ /// A floor only ever moves up. A later unresolved emission at a+ /// *lower* version must not lower it, because the higher one is the+ /// constraint — losing it lets a subsequent write reuse a version+ /// already on the wire. `only_a_version_that_covers_the_floor_clears_it`+ /// pins the same asymmetry on the resolve side.+ #[test]+ fn a_lower_emission_does_not_lower_the_floor() {+ let versions = Arc::new(EmittedVersions::new(8));+ versions.raise_for_test(0, key(1), 9);+ versions.raise_for_test(0, key(1), 4);+ assert_eq!(+ versions.floor_for(0, &key(1), 0),+ 9,+ "a lower unresolved emission must not lower the floor"+ );+ }++ /// The complement: a second unresolved emission has to move the floor+ /// forward. Leaving it where the first one put it hands the second+ /// write's version back for reuse, and the writer's first-wins guard+ /// then keeps whichever record arrived first — discarding the acked+ /// one.+ #[test]+ fn a_later_emission_raises_the_floor_it_finds() {+ let versions = Arc::new(EmittedVersions::new(8));+ versions.raise_for_test(0, key(1), 5);+ versions.raise_for_test(0, key(1), 7);+ assert_eq!(+ versions.floor_for(0, &key(1), 0),+ 7,+ "a later unresolved emission must raise the floor"+ );+ }++ /// A floor is only cleared by a later successful write for the same+ /// person, so persons written once and abandoned leave entries+ /// nothing collects — and a client can manufacture exactly that by+ /// updating unique persons while produce latency sits above its own+ /// deadline, one entry per person, indefinitely.+ ///+ /// At the bound the state stops growing, and the safety property+ /// survives the degradation: a version spilled to the partition is+ /// still a version no later write can reuse.+ #[test]+ fn unresolved_versions_stop_growing_at_the_bound() {+ let versions = Arc::new(EmittedVersions::new(4));+ for person_id in 0..64 {+ let mut guard =+ EmittedVersionGuard::new(Arc::clone(&versions), 0, key(person_id), 100 + person_id);+ guard.emitting();+ }+ assert!(+ versions.len() <= 4,+ "unresolved versions grew to {} against a bound of 4",+ versions.len()+ );++ // Every spilled version is still refused to a later write, for+ // every person in the partition — that is what makes shedding+ // safe rather than a silent reopening of the collision.+ let highest = 100 + 63;+ for person_id in 0..64 {+ assert!(+ versions.floor_for(0, &key(person_id), 0) >= highest,+ "person {person_id} could reuse a version the pod already emitted"+ );+ }+ }++ /// The spill is scoped to its partition: an unrelated one must not+ /// inherit a floor, or one attacked partition would inflate versions+ /// across the whole pod.+ #[test]+ fn a_spilled_floor_does_not_cross_partitions() {+ let versions = Arc::new(EmittedVersions::new(1));+ for person_id in 0..8 {+ let mut guard = EmittedVersionGuard::new(Arc::clone(&versions), 0, key(person_id), 500);+ guard.emitting();+ }+ assert_eq!(versions.floor_for(1, &key(0), 3), 3);+ }++ /// Releasing a partition drops its coarse floor as well as its+ /// precise ones, or a re-acquisition would derive past a version the+ /// changelog has already settled.+ #[test]+ fn releasing_a_partition_drops_its_spilled_floor() {+ let versions = Arc::new(EmittedVersions::new(1));+ for person_id in 0..8 {+ let mut guard = EmittedVersionGuard::new(Arc::clone(&versions), 0, key(person_id), 500);+ guard.emitting();+ }+ versions.clear_partition(0);+ assert_eq!(versions.floor_for(0, &key(0), 3), 3);+ }++ /// Later state supersedes the floor; an older confirmation must not+ /// clear a newer doubt.+ #[test]+ fn only_a_version_that_covers_the_floor_clears_it() {+ let versions = Arc::new(EmittedVersions::new(8));+ let mut guard = EmittedVersionGuard::new(Arc::clone(&versions), 0, key(1), 9);+ guard.emitting();+ drop(guard);++ versions.resolve(0, &key(1), 7);+ assert_eq!(versions.floor_for(0, &key(1), 0), 9, "a stale confirmation");++ versions.resolve(0, &key(1), 9);+ assert_eq!(versions.floor_for(0, &key(1), 0), 0, "the covering one");+ }+}diff --git a/rust/personhog-leader/src/fencing.rs b/rust/personhog-leader/src/fencing.rsnew file mode 100644index 000000000000..9a400b73e31d--- /dev/null+++ b/rust/personhog-leader/src/fencing.rs@@ -0,0 +1,1385 @@+//! Broker-enforced epoch fencing for the changelog, via per-partition+//! transactional producers.+//!+//! Each partition's owner holds a producer whose `transactional.id` is+//! derived from the partition alone. Taking ownership initializes+//! transactions for that id, which bumps the broker-side producer epoch+//! and fences every predecessor: a zombie old owner that missed its own+//! drain can no longer append to the changelog — its next produce or+//! commit fails with a fenced error at the broker, loudly, instead of+//! silently corrupting the partition's history.+//!+//! Writes are grouped into transaction windows rather than one+//! transaction each. A transactional producer admits one open+//! transaction at a time, so per-write transactions would serialize a+//! partition's writes on the commit round trip. A window opens on the+//! first write, admits concurrent writes for a short interval (their+//! records ride librdkafka's normal batching), then commits once and+//! resolves every waiter. Under light load a window holds one write and+//! costs one commit; under load the commit amortizes across the window.+//!+//! The price of sharing a transaction is shared failure: an aborted+//! window fails all of its writes together. Readers never observe+//! aborted records (consumers run `read_committed`), so the coupling is+//! visible only as grouped retryable errors.++use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};+use std::{fmt, mem};++use common_kafka::config::KafkaConfig;+use common_kafka::transaction::TransactionalProducer;+use dashmap::DashMap;+use metrics::{counter, histogram};+use prost::Message as ProtoMessage;+use rdkafka::client::ClientContext;+use rdkafka::error::{KafkaError, RDKafkaErrorCode};+use rdkafka::producer::{FutureProducer, FutureRecord, Producer};+use tokio::sync::{oneshot, Notify};+use tokio::task::spawn_blocking;+use tokio::time::{sleep, timeout};+use tracing::{debug, error, warn};++use personhog_proto::personhog::types::v1::Person;++use crate::config::{FENCING_ABORT_ATTEMPTS, FENCING_COMMIT_ATTEMPTS};+use crate::kafka::changelog_message_key;++/// The fencing scope is the partition: every owner of partition `p`+/// shares this id, so a new owner's init fences the old one.+fn transactional_id(topic: &str, partition: u32) -> String {+ format!("personhog-changelog-{topic}-p{partition}")+}++#[derive(Debug)]+pub enum FencedProduceError {+ /// This pod holds no fenced producer for the partition — ownership+ /// was never taken or was released.+ NotAcquired,+ /// The broker fenced this producer: a newer owner has initialized+ /// the partition's transactional id. This pod's claim is stale, and+ /// the records demonstrably never became visible.+ Fenced,+ /// Fenced, but the window's own outcome was never settled — so the+ /// partition has moved *and* whether these records landed is unknown.+ ///+ /// The two are independent facts and the caller needs both: the+ /// router still wants the ownership answer, while the version must+ /// stay spent because a commit that was re-issued may have succeeded+ /// on an earlier attempt. Collapsing this into `Fenced` is what let a+ /// committed record's version be handed back for reuse.+ FencedUncertain(String),+ /// Send or commit failed for an ordinary, retryable reason; the+ /// window was aborted and no record became visible.+ Failed(String),+ /// The commit neither succeeded nor demonstrably aborted, so whether+ /// the records became visible is unknown.+ ///+ /// This is not the same as failure and must not be reported as one.+ /// A caller told "aborted" retries against a cache still holding the+ /// pre-write version, and produces a second record carrying the same+ /// version as the one that may already have committed — which the+ /// writer's strict version guard resolves in favour of whichever+ /// arrived first, discarding the acked one.+ Indeterminate(String),+}++impl fmt::Display for FencedProduceError {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ FencedProduceError::NotAcquired => write!(f, "partition fence not acquired"),+ FencedProduceError::Fenced => {+ write!(f, "producer fenced by a newer owner of the partition")+ }+ FencedProduceError::FencedUncertain(e) => write!(+ f,+ "producer fenced by a newer owner; this window's outcome is unknown: {e}"+ ),+ FencedProduceError::Failed(e) => write!(f, "fenced produce failed: {e}"),+ FencedProduceError::Indeterminate(e) => {+ write!(f, "changelog commit outcome unknown: {e}")+ }+ }+ }+}++/// State of a partition's current transaction window.+struct Gate {+ /// A window is open and accepting joiners.+ open: bool,+ /// Sends still in flight for the open window; the committer waits+ /// for zero before committing so no record can miss its own commit.+ in_flight: usize,+ /// A send in this window failed; the committer aborts instead of+ /// committing, and every waiter fails together.+ poisoned: bool,+ /// The committer is between closing the window and finishing the+ /// commit. Once it drains `in_flight` and takes `waiters`, the other+ /// fields read as idle even though `commit_transaction` is still+ /// running — this flag keeps the next window from beginning until+ /// the producer is actually free.+ committing: bool,+ /// Commit-outcome subscribers for the open window.+ waiters: Vec<oneshot::Sender<Result<(), FencedProduceError>>>,+}++/// Send a fence to the blocking pool to die. Dropping the last+/// reference runs librdkafka's destroy, which blocks while the client+/// tears down — up to hundreds of milliseconds — and both removal sites+/// run on async workers. Best-effort: a caller (an in-flight write, the+/// settle wait) still holding the Arc pays the destroy wherever it drops+/// last, which is rarer than the common case this moves.+fn drop_fence_off_worker(fence: Arc<PartitionFence>) {+ tokio::task::spawn_blocking(move || drop(fence));+}++struct PartitionFence {+ producer: TransactionalProducer,+ /// Makes the next commit task panic, so tests can reach the arm that+ /// handles a committer which never reports. Scoped to the fence+ /// rather than a global: the tests in this binary run concurrently.+ #[cfg(any(test, feature = "test-support"))]+ panic_next_commit: AtomicBool,+ /// A std mutex, deliberately: every critical section is a handful of+ /// field updates with no await inside, and `WindowSlot`'s `Drop` must+ /// be able to release its seat synchronously.+ gate: Mutex<Gate>,+ /// Signalled when `in_flight` reaches zero.+ sends_settled: Notify,+ /// Signalled when a committing window finishes, letting blocked+ /// writers open the next one.+ window_closed: Notify,+ /// Set when the producer is left in a transaction state no later+ /// `begin_transaction` can recover from — an abort that did not land,+ /// or a commit whose outcome stayed unknown.+ ///+ /// Such a producer is still installed, so presence alone cannot tell+ /// a working fence from a dead one. This flag is what makes the+ /// distinction visible: a condemned partition answers as unowned so+ /// the router bounces instead of retrying a dead producer. On this+ /// branch nothing re-acquires in place — recovery is a process+ /// restart or the partition moving — and the stacked lease-validity+ /// branch adds the serving-side re-acquisition, which consults this+ /// flag and needs the authority stamp it introduces for the standing+ /// to bump the epoch.+ unusable: AtomicBool,+ commit_timeout: Duration,+}++impl PartitionFence {+ /// Retire the producer: writes stop attempting it and the partition+ /// stops counting as fenced by this pod.+ fn condemn(&self, partition: u32, reason: &'static str) {+ if !self.unusable.swap(true, Ordering::Relaxed) {+ counter!(+ "personhog_leader_fence_condemned_total",+ "reason" => reason+ )+ .increment(1);+ error!(+ partition,+ reason, "changelog producer left unusable; awaiting re-acquisition"+ );+ }+ }++ fn is_usable(&self) -> bool {+ !self.unusable.load(Ordering::Relaxed)+ }+}++/// One seat in the open window, released on drop.+///+/// A request can vanish at any await — tonic drops the handler future+/// when the client's deadline expires or its stream resets — and the+/// seat has to come back even then, or the committer waits on an+/// in-flight count that never reaches zero and every later write on the+/// partition parks forever behind it.+struct WindowSlot {+ fence: Arc<PartitionFence>,+ released: bool,+}++impl WindowSlot {+ /// Take a seat in a window already counted as in-flight.+ fn held(fence: Arc<PartitionFence>) -> Self {+ Self {+ fence,+ released: false,+ }+ }++ /// Release the seat, optionally poisoning the window, and report+ /// whether the window is now settled.+ fn release_inner(&mut self, poison: bool) -> bool {+ let mut gate = self.fence.gate.lock().unwrap();+ gate.in_flight -= 1;+ if poison {+ gate.poisoned = true;+ }+ let settled = gate.in_flight == 0;+ drop(gate);+ if settled {+ self.fence.sends_settled.notify_waiters();+ }+ self.released = true;+ settled+ }++ /// Subscribe to the window's commit outcome and release the seat in+ /// one critical section. Both must be atomic: if the committer could+ /// take the waiter list between them, this write's record would be+ /// committed with no one left to tell.+ fn subscribe(mut self) -> oneshot::Receiver<Result<(), FencedProduceError>> {+ let (tx, rx) = oneshot::channel();+ let mut gate = self.fence.gate.lock().unwrap();+ gate.waiters.push(tx);+ gate.in_flight -= 1;+ let settled = gate.in_flight == 0;+ drop(gate);+ if settled {+ self.fence.sends_settled.notify_waiters();+ }+ self.released = true;+ rx+ }++ /// Release the seat after a failed send: the window aborts, failing+ /// this write and its window-mates together.+ fn poison(mut self) {+ self.release_inner(true);+ }+}++impl Drop for WindowSlot {+ fn drop(&mut self) {+ if !self.released {+ // A cancelled request: release the seat but do not poison.+ // Its record may already be enqueued and will ride the+ // commit; nobody is waiting for the ack, and failing the+ // window would punish the writes that are still waiting.+ //+ // The record therefore becomes durable without ever being+ // acked, and it can still sit in an open window when the+ // partition moves. That is safe because the new owner+ // acquires this partition's transactional id before reading+ // the changelog: the abandoned window can no longer commit,+ // so the record is either already below the new owner's+ // cutoff or never visible at all.+ counter!("personhog_leader_fence_slots_abandoned_total").increment(1);+ self.release_inner(false);+ }+ }+}++/// Marks a window as committing, and clears the mark on drop.+///+/// Between closing a window and finishing its commit the gate reads as+/// idle — `in_flight` is zero and the waiters have been taken — so only+/// this mark keeps the next writer from beginning a transaction the+/// producer is not free for. If the committer unwinds while it is set,+/// nothing else ever clears it: every later write parks on+/// `window_closed` until its own deadline expires, forever, and no+/// repair path looks at a gate.+struct CommittingMark {+ fence: Arc<PartitionFence>,+ partition: u32,+}++impl CommittingMark {+ fn take(fence: Arc<PartitionFence>, partition: u32) -> Self {+ {+ let mut gate = fence.gate.lock().unwrap();+ gate.open = false;+ gate.committing = true;+ }+ Self { fence, partition }+ }+}++impl Drop for CommittingMark {+ fn drop(&mut self) {+ // Deliberately tolerant of a poisoned gate: the mark existing is+ // what wedges the partition, so it has to come off even when the+ // lock's last holder panicked.+ let orphans = match self.fence.gate.lock() {+ Ok(mut gate) => {+ gate.committing = false;+ mem::take(&mut gate.waiters)+ }+ Err(poisoned) => {+ let mut gate = poisoned.into_inner();+ gate.committing = false;+ mem::take(&mut gate.waiters)+ }+ };+ // On the ordinary path the committer took the waiters before this+ // drops, so the list is empty. Waiters still here mean the+ // committer unwound between taking the mark and answering anyone+ // — their outcomes are unobservable, and leaving them queued+ // would park every later write forever: nothing can open a window+ // while waiters remain, and nothing would notify again. Dropping+ // their senders answers each with the doubt it earned (a closed+ // channel reads as an unobserved commit), and condemning routes+ // the partition into the same bounce-and-recover story as every+ // other producer no window can be begun from.+ if !orphans.is_empty() {+ self.fence.condemn(self.partition, "committer_unwound");+ }+ drop(orphans);+ self.fence.window_closed.notify_waiters();+ }+}++/// Holds a freshly acquired fence until the work that justified taking+/// it succeeds, and gives it back otherwise.+///+/// A warm can end without returning — its future is dropped when the+/// pod's coordination attempt is torn down, which is exactly what a lost+/// lease does. The pod records a partition as held only once the warm+/// returns, so a fence taken by a warm that never finishes belongs to no+/// partition the local self-fence knows to release: the process would+/// keep the partition's broker epoch while owning nothing, and the real+/// owner's writes would fail as fenced until it re-acquired.+pub struct FenceGuard {+ fenced: Arc<FencedChangelogProducers>,+ partition: u32,+ /// The fence this guard is answerable for. Releasing by partition+ /// alone would drop whatever happens to be installed at drop time,+ /// which after a release and a re-acquire is somebody else's+ /// producer — the same hazard `forget_fence` checks for.+ taken: Option<Arc<PartitionFence>>,+ armed: bool,+}++impl FenceGuard {+ pub fn new(fenced: Arc<FencedChangelogProducers>, partition: u32) -> Self {+ let taken = fenced.installed(partition);+ Self {+ fenced,+ partition,+ taken,+ armed: true,+ }+ }++ /// The work succeeded; the fence is now the caller's to hold.+ pub fn keep(mut self) {+ self.armed = false;+ }+}++impl Drop for FenceGuard {+ fn drop(&mut self) {+ if self.armed {+ counter!("personhog_leader_fence_abandoned_total").increment(1);+ warn!(+ partition = self.partition,+ "releasing a fence taken for a warm that did not finish"+ );+ match &self.taken {+ Some(fence) => self.fenced.forget_fence(self.partition, fence),+ None => self.fenced.release(self.partition),+ }+ }+ }+}++/// Per-partition fenced producers for the changelog. Constructed once+/// and shared; partitions are acquired at warm completion and released+/// with ownership.+pub struct FencedChangelogProducers {+ kafka: KafkaConfig,+ topic: String,+ init_timeout: Duration,+ commit_timeout: Duration,+ /// How long the broker keeps one of our windows open before+ /// abandoning it; distinct from `commit_timeout`, which bounds only+ /// this process's wait on the commit call.+ broker_txn_timeout: Duration,+ /// How long an open window admits joiners before committing.+ window: Duration,+ /// Ceiling on the drain's wait for an open window to commit. Set+ /// well under the pre-revoke self-fence's allowance for a whole+ /// drain, so a shutdown with an open window does not truncate here+ /// and report a failed drain.+ settle_budget: Duration,+ partitions: DashMap<u32, Arc<PartitionFence>>,+ /// Outcomes a test stages for the next produce on a partition.+ ///+ /// The uncertain outcomes need a broker fault landing inside a+ /// transaction, which no test can stage against a healthy cluster —+ /// but what the caller *does* with them is the reason they are+ /// distinguished at all, so the answers have to be reachable.+ #[cfg(any(test, feature = "test-support"))]+ staged_failures: DashMap<u32, FencedProduceError>,+}++/// Construction parameters for [`FencedChangelogProducers`], named+/// because five of them are `Duration`s: a transposed pair at a call+/// site compiles, and `main`'s wiring is executed by no test — a swapped+/// window and settle budget would ship as a 2s admission window on+/// every fenced write.+pub struct FencedProducerConfig {+ pub kafka: KafkaConfig,+ pub topic: String,+ pub init_timeout: Duration,+ pub commit_timeout: Duration,+ pub broker_txn_timeout: Duration,+ pub window: Duration,+ pub settle_budget: Duration,+}++impl FencedChangelogProducers {+ pub fn new(config: FencedProducerConfig) -> Self {+ let FencedProducerConfig {+ kafka,+ topic,+ init_timeout,+ commit_timeout,+ broker_txn_timeout,+ window,+ settle_budget,+ } = config;+ Self {+ kafka,+ topic,+ init_timeout,+ commit_timeout,+ broker_txn_timeout,+ window,+ settle_budget,+ partitions: DashMap::new(),+ #[cfg(any(test, feature = "test-support"))]+ staged_failures: DashMap::new(),+ }+ }++ /// Take the partition's fence: create the transactional producer and+ /// initialize transactions, which fences every previous owner of the+ /// partition's transactional id. Runs on the blocking pool — init is+ /// a synchronous broker round trip.+ pub async fn acquire(&self, partition: u32) -> Result<(), String> {+ let kafka = self.kafka.clone();+ let tid = transactional_id(&self.topic, partition);+ let timeout = self.init_timeout;+ let broker_txn_timeout = self.broker_txn_timeout;+ let start = Instant::now();+ let producer = spawn_blocking(move || {+ TransactionalProducer::from_config_bounded(&kafka, &tid, timeout, broker_txn_timeout)+ })+ .await+ .map_err(|e| format!("fence init join: {e}"))?+ .map_err(|e| {+ counter!("personhog_leader_fence_init_total", "outcome" => "error").increment(1);+ format!("fence init: {e}")+ })?;+ counter!("personhog_leader_fence_init_total", "outcome" => "ok").increment(1);+ histogram!("personhog_leader_fence_init_ms").record(start.elapsed().as_secs_f64() * 1000.0);+ self.partitions.insert(+ partition,+ Arc::new(PartitionFence {+ producer,+ gate: Mutex::new(Gate {+ open: false,+ in_flight: 0,+ poisoned: false,+ committing: false,+ waiters: Vec::new(),+ }),+ sends_settled: Notify::new(),+ window_closed: Notify::new(),+ #[cfg(any(test, feature = "test-support"))]+ panic_next_commit: AtomicBool::new(false),+ unusable: AtomicBool::new(false),+ commit_timeout: self.commit_timeout,+ }),+ );+ Ok(())+ }++ /// The fence currently installed for a partition, if any.+ fn installed(&self, partition: u32) -> Option<Arc<PartitionFence>> {+ self.partitions.get(&partition).map(|f| Arc::clone(&f))+ }++ /// Drop the partition's fence with ownership. The broker-side epoch+ /// survives; only a future owner's init advances it.+ pub fn release(&self, partition: u32) {+ if let Some((_, fence)) = self.partitions.remove(&partition) {+ drop_fence_off_worker(fence);+ }+ }++ /// Commit the partition's open window before its owner gives it up.+ ///+ /// A request cancelled mid-produce takes its handler — and the+ /// drain's in-flight count — with it, leaving the record it enqueued+ /// in a window nobody is waiting on. Left alone, that window's fate+ /// falls to whichever acts first: this pod's own committer, or the+ /// successor's `init_transactions` aborting it at the broker. Waiting+ /// here settles it in the successor's favour, so a cancelled client's+ /// changes land instead of being discarded by a race.+ ///+ /// Deliberately best-effort. Refusing to hand over a partition whose+ /// window did not settle would buy nothing: a producer that cannot+ /// report its outcome is a producer the broker will not accept+ /// another record from, so the records cannot grow after this point+ /// whatever we do — and the successor's init aborts what is left,+ /// exactly as it did before this wait existed. What refusing *does*+ /// cost is the partition: the drain has already fenced writes, and+ /// there is no branch that un-fences one whose handoff never+ /// completed.+ pub async fn settle(&self, partition: u32) {+ let Some(fence) = self.installed(partition) else {+ // A write that met a condemned producer already gave the+ // fence up, which is the ordinary shape after a condemnation+ // — recorded rather than silent, or the series has no+ // denominator.+ counter!("personhog_leader_fence_settle_total", "outcome" => "absent").increment(1);+ return;+ };+ // Bounded well under the broker's own patience for the window.+ // The wait exists to catch a committer that is about to fire+ // anyway — it sleeps for the window, five milliseconds by+ // default, then commits — so seconds of budget only help when+ // the commit is retrying, which is the case where the+ // successor's abort is the right answer regardless. The cap+ // matters because the pre-revoke self-fence allows three seconds+ // for a whole drain: a budget derived from the lease alone+ // reaches about 6s at the production TTL, so every shutdown with an+ // open window would truncate here and report a failed drain.+ let budget = self.settle_budget;+ let waited = timeout(budget, async {+ loop {+ // Register before inspecting, or a close landing between+ // the two is lost and this waits on a wakeup already+ // spent.+ let closed = fence.window_closed.notified();+ tokio::pin!(closed);+ closed.as_mut().enable();+ {+ let gate = fence.gate.lock().unwrap();+ if !gate.open && !gate.committing && gate.in_flight == 0 {+ return;+ }+ }+ closed.await;+ }+ })+ .await;++ let outcome = if waited.is_err() {+ "timeout"+ } else if !fence.is_usable() {+ // Condemned somewhere in this partition's history, so this+ // producer has nothing left to give the changelog.+ "unusable"+ } else {+ "settled"+ };+ counter!("personhog_leader_fence_settle_total", "outcome" => outcome).increment(1);+ if outcome != "settled" {+ warn!(+ partition,+ outcome,+ "changelog window did not settle before the drain; leaving what remains to the \+ incoming owner's init"+ );+ }+ }++ /// Put the partition's producer into the state a failed abort or an+ /// unknown commit leaves it in.+ ///+ /// Reaching that state for real takes a broker fault landing inside a+ /// transaction, which no test can stage against a healthy cluster —+ /// but what happens *afterwards* is the entire reason the state is+ /// tracked, so the aftermath has to be reachable.+ /// Hold the partition's gate in the state a commit in flight leaves+ /// it, so a writer arriving now parks instead of opening a window.+ ///+ /// The wake path is otherwise unreachable from a test: parking+ /// requires arriving inside the commit's own round trip, which is+ /// milliseconds wide and not something a test can aim at. Staging the+ /// gate directly is what makes the interleaving deterministic rather+ /// than statistical.+ #[cfg(any(test, feature = "test-support"))]+ pub fn begin_committing_for_test(&self, partition: u32) {+ if let Some(fence) = self.partitions.get(&partition) {+ let mut gate = fence.gate.lock().unwrap();+ gate.open = false;+ gate.committing = true;+ }+ }++ /// Release that gate and wake the parked writers, as a finishing+ /// commit does.+ #[cfg(any(test, feature = "test-support"))]+ pub fn finish_committing_for_test(&self, partition: u32) {+ if let Some(fence) = self.partitions.get(&partition) {+ fence.gate.lock().unwrap().committing = false;+ fence.window_closed.notify_waiters();+ }+ }++ /// Poison the partition's open window, as a send that failed inside+ /// it does.+ ///+ /// A real poisoning needs a produce to fail mid-window against a+ /// broker that is otherwise healthy enough to have opened one, which+ /// is not stageable — but what the commit path does with a poisoned+ /// window is the whole reason the flag exists.+ #[cfg(any(test, feature = "test-support"))]+ pub fn poison_window_for_test(&self, partition: u32) {+ if let Some(fence) = self.installed(partition) {+ fence.gate.lock().unwrap().poisoned = true;+ }+ }++ /// Stage a committer that unwound between taking the mark and+ /// answering its subscribers — the shape a runtime teardown or a+ /// panic in the settle wait leaves behind. Real unwinds are not+ /// stageable deterministically; what matters is the mark's cleanup.+ #[cfg(any(test, feature = "test-support"))]+ pub fn orphan_committer_for_test(&self, partition: u32) {+ if let Some(fence) = self.installed(partition) {+ let mark = CommittingMark::take(Arc::clone(&fence), partition);+ let (tx, _rx) = oneshot::channel();+ fence.gate.lock().unwrap().waiters.push(tx);+ drop(mark);+ }+ }++ /// Stage a committer that never reports its outcome. The real path+ /// needs the runtime to tear the task down mid-commit, which no test+ /// can arrange against a live producer.+ #[cfg(any(test, feature = "test-support"))]+ pub fn panic_next_commit_for_test(&self, partition: u32) {+ if let Some(fence) = self.installed(partition) {+ fence.panic_next_commit.store(true, Ordering::SeqCst);+ }+ }++ /// Drop the open window's commit-outcome subscribers without+ /// answering them, as a committer that vanished mid-commit leaves+ /// them. `spawn_blocking` work is not cancelled when its handle is+ /// dropped, so the commit it was running may well have landed.+ #[cfg(any(test, feature = "test-support"))]+ pub fn abandon_waiters_for_test(&self, partition: u32) {+ if let Some(fence) = self.partitions.get(&partition) {+ let taken = mem::take(&mut fence.gate.lock().unwrap().waiters);+ drop(taken);+ }+ }++ /// Make the next produce on this partition answer with `outcome`.+ #[cfg(any(test, feature = "test-support"))]+ pub fn stage_failure_for_test(&self, partition: u32, outcome: FencedProduceError) {+ self.staged_failures.insert(partition, outcome);+ }++ #[cfg(any(test, feature = "test-support"))]+ pub fn condemn_for_test(&self, partition: u32) {+ if let Some(fence) = self.partitions.get(&partition) {+ fence.condemn(partition, "test");+ }+ }++ /// Produce one changelog record inside the partition's current+ /// transaction window, returning its offset once the window commits.+ pub async fn produce(+ &self,+ partition: u32,+ person: &Person,+ ) -> Result<i64, FencedProduceError> {+ #[cfg(any(test, feature = "test-support"))]+ if let Some((_, staged)) = self.staged_failures.remove(&partition) {+ return Err(staged);+ }+ let durable_start = Instant::now();+ let fence = self+ .partitions+ .get(&partition)+ .map(|f| Arc::clone(&f))+ .ok_or_else(|| {+ counter!("personhog_leader_kafka_produce_errors_total").increment(1);+ FencedProduceError::NotAcquired+ })?;++ // Join the open window, or open one. A window mid-commit admits+ // no joiners; wait for it to close and retry.+ let join_start = Instant::now();+ let opened = loop {+ // Checked every iteration, not only on the way in. A+ // condemned producer cannot begin another transaction, and+ // the commit that condemns it is the same one whose end wakes+ // whoever is parked below — so a check placed after the park+ // is skipped by exactly the writer it exists for, which then+ // opens a window on a dead producer and answers with a+ // retryable failure instead of the ownership bounce that gets+ // the partition re-acquired.+ if !fence.is_usable() {+ self.forget_fence(partition, &fence);+ counter!("personhog_leader_kafka_produce_errors_total").increment(1);+ return Err(FencedProduceError::NotAcquired);+ }+ // Register interest before inspecting the gate: a close that+ // fires between the check and the await must not be lost.+ let closed = fence.window_closed.notified();+ tokio::pin!(closed);+ closed.as_mut().enable();+ // Only the gate's own fields are touched under its lock.+ // Classifying a failure consults the producer's fatal state+ // and can evict the fence, so it happens after the guard is+ // gone: the gate is a std mutex, and a panic while it is held+ // poisons it for every writer on the partition.+ let begin_failed = {+ let mut gate = fence.gate.lock().unwrap();+ if gate.open {+ gate.in_flight += 1;+ break false;+ }+ if !gate.committing && gate.in_flight == 0 && gate.waiters.is_empty() {+ // Idle: open a new window. BeginTxn is a local+ // librdkafka state transition, safe inline.+ match fence.producer.inner().begin_transaction() {+ Ok(()) => {+ gate.open = true;+ gate.in_flight = 1;+ gate.poisoned = false;+ break true;+ }+ Err(e) => Some(e),+ }+ } else {+ None+ }+ };+ if let Some(e) = begin_failed {+ counter!("personhog_leader_kafka_produce_errors_total").increment(1);+ return Err(self.classify(&fence, partition, e));+ }+ closed.await;+ };+ // Near-zero when a window was open or the producer idle; the tail+ // is time parked behind a draining or committing window — the+ // queueing term of the fencing tax, and the first thing to grow+ // if commits slow down.+ // From here the window counts this write as in flight; the slot+ // returns the seat on every exit, including cancellation.+ let slot = WindowSlot::held(Arc::clone(&fence));+ histogram!("personhog_leader_fence_window_wait_ms", "partition" => partition.to_string())+ .record(join_start.elapsed().as_secs_f64() * 1000.0);++ if opened {+ let fence_for_commit = Arc::clone(&fence);+ let window = self.window;+ let topic = self.topic.clone();+ let part = partition;+ tokio::spawn(async move {+ commit_window_after(fence_for_commit, window, topic, part).await;+ });+ }++ // Send within the open window; the record rides librdkafka's+ // ordinary batching alongside its window-mates.+ let key = changelog_message_key(person.team_id, person.id);+ let payload = person.encode_to_vec();+ let record = FutureRecord::to(&self.topic)+ .partition(partition as i32)+ .key(&key)+ .payload(&payload);+ let produce_start = Instant::now();+ let delivery = fence.producer.inner().send_result(record);++ let offset = match delivery {+ Ok(fut) => match fut.await {+ Ok(Ok((_, offset))) => {+ histogram!("personhog_leader_fence_send_ms")+ .record(produce_start.elapsed().as_secs_f64() * 1000.0);+ Ok(offset)+ }+ // These fire per write, and a broker outage fails every+ // write, so the aggregate is the useful signal and the+ // per-request detail belongs at debug. The caller logs+ // the classified outcome, and the counters below carry+ // the rate.+ Ok(Err((e, _))) => {+ debug!(partition, error = %e, "fenced send delivery failed");+ Err(Some(e))+ }+ Err(_cancelled) => {+ debug!(partition, "fenced send cancelled");+ Err(None)+ }+ },+ Err((e, _)) => {+ debug!(partition, error = %e, "fenced send enqueue failed");+ Err(Some(e))+ }+ };++ // A failed send poisons the window (the committer aborts it) and+ // returns immediately with its own classified error — a fenced+ // rejection must surface as `Fenced`, not as the window's+ // generic abort.+ if let Err(send_err) = offset {+ counter!("personhog_leader_kafka_produce_errors_total").increment(1);+ slot.poison();+ return Err(match send_err {+ Some(e) => self.classify(&fence, partition, e),+ None => FencedProduceError::Failed("send cancelled (timeout)".to_string()),+ });+ }+ let offset = offset.expect("checked above");++ let rx = slot.subscribe();++ // The record exists but is invisible until the window commits;+ // the ack must wait for the commit outcome. Together with the+ // window-wait and send spans this completes the caller-visible+ // decomposition of a fenced produce.+ let ack_wait_start = Instant::now();+ let outcome = rx.await;+ histogram!("personhog_leader_fence_ack_wait_ms", "partition" => partition.to_string())+ .record(ack_wait_start.elapsed().as_secs_f64() * 1000.0);+ match outcome {+ Ok(Ok(())) => {+ counter!("personhog_leader_kafka_produces_total").increment(1);+ // The same series the unfenced path records: time from+ // entering produce to a durable record, so the two flag+ // arms stay comparable.+ histogram!("personhog_leader_kafka_produce_duration_ms")+ .record(durable_start.elapsed().as_secs_f64() * 1000.0);+ Ok(offset)+ }+ Ok(Err(e)) => {+ counter!("personhog_leader_kafka_produce_errors_total").increment(1);+ // The commit reported the fence, so the eviction has to+ // happen here: `commit_window_after` runs detached and+ // holds no handle to the fence map. Without this the dead+ // producer stays installed, later writes discover the+ // fence one failed `begin_transaction` at a time, and+ // `holds()` reports authority this pod no longer has.+ if matches!(+ e,+ FencedProduceError::Fenced | FencedProduceError::FencedUncertain(_)+ ) {+ self.forget_fence(partition, &fence);+ }+ Err(e)+ }+ // The committer dropped its senders without answering, so+ // nobody observed whether the commit landed — and+ // `spawn_blocking` work is not cancelled when its handle is+ // dropped, so it may well have. Reporting a definite abort+ // here frees a version whose record may exist.+ Err(_) => {+ counter!("personhog_leader_kafka_produce_errors_total").increment(1);+ Err(FencedProduceError::Indeterminate(+ "commit task dropped without reporting an outcome".to_string(),+ ))+ }+ }+ }++ /// Classify a transaction error, removing the fence on a broker+ /// fence rejection so subsequent writes fail fast as stale. The+ /// fenced signal often hides behind a local symptom — librdkafka+ /// purges queued messages once the producer turns fatal — so the+ /// producer's fatal error is consulted alongside the surface error.+ fn classify(+ &self,+ fence: &Arc<PartitionFence>,+ partition: u32,+ e: KafkaError,+ ) -> FencedProduceError {+ if is_fenced(&e) || producer_fenced(fence.producer.inner()) {+ counter!(+ "personhog_leader_produce_fenced_total",+ "partition" => partition.to_string()+ )+ .increment(1);+ error!(+ partition,+ error = %e,+ "changelog producer fenced by a newer owner — this pod's claim is stale"+ );+ self.forget_fence(partition, fence);+ FencedProduceError::Fenced+ } else {+ FencedProduceError::Failed(e.to_string())+ }+ }++ /// Drop a fence that the broker rejected, but only if it is still the+ /// one installed: a write can be in flight across a release and a+ /// re-acquire, and the stale producer's failure must not evict its+ /// live replacement.+ fn forget_fence(&self, partition: u32, fence: &Arc<PartitionFence>) {+ let removed = self+ .partitions+ .remove_if(&partition, |_, installed| Arc::ptr_eq(installed, fence));+ if let Some((_, evicted)) = removed {+ drop_fence_off_worker(evicted);+ // The escalation signal for a partition giving up its fence+ // outside the orderly release path — the series exists so a+ // deploy-window burst of these is visible.+ counter!(+ "personhog_leader_fenced_partition_drops_total",+ "partition" => partition.to_string()+ )+ .increment(1);+ }+ }+}++/// How many times a retriable commit is re-attempted before its outcome+/// is declared unknown.+///+/// Derived from the attempt budget the lease runway affords, rather than+/// chosen independently: `validate_fencing_timescales` sizes the fencing+/// timeouts so that exactly this many attempts still fit inside the+/// window the keepalive reserves for self-fencing.+const COMMIT_RETRIES: usize = FENCING_COMMIT_ATTEMPTS as usize - 1;++/// What is known about a window's records after a failed commit, and+/// whether the producer survived learning it.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum CommitOutcome {+ /// The transaction is definitely aborted; nothing became visible.+ Aborted,+ /// Definitely aborted, but the abort never landed, so the producer is+ /// stuck in a state it cannot begin another transaction from.+ AbortedProducerDead,+ /// Whether the records committed is not known.+ ///+ /// There is no healthy-producer form of this: a commit fails without+ /// a definite outcome only when the error is neither retriable nor+ /// abort-requiring, which is librdkafka's fatal class, or when the+ /// follow-up abort itself failed. Both leave the producer unusable.+ Unknown,+}++/// What a failed window means for its writers.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum WindowVerdict {+ /// A newer owner holds the partition; the records never landed.+ Fenced,+ /// A newer owner holds the partition and the records' fate is+ /// unknown — both facts, because they answer different questions.+ FencedUncertain,+ /// The window aborted for an ordinary reason; safe to retry.+ Aborted,+ /// Whether the records landed is unknown.+ Indeterminate,+}++/// Whether the partition moved and whether the records landed are+/// independent, so the verdict carries both.+///+/// A commit can time out, be re-issued by librdkafka itself, and only+/// then report the fence — by which point an earlier attempt may already+/// have succeeded. Reporting that as a plain fence tells the caller the+/// record does not exist, which frees its version and puts a second+/// record at the same number behind one that may be committed. Reporting+/// it as merely indeterminate throws away the ownership answer the router+/// bounces on. `FencedUncertain` is both.+/// Why a window's outcome leaves the producer unusable, if it does.+///+/// Extracted so the arrow *into* the condemned state is reachable: the+/// tests could reach the aftermath through a staging hook, but the branch+/// that decides it could be deleted outright with the suite still green,+/// and it is the only path in production that ever sets the flag.+fn condemn_reason(outcome: CommitOutcome) -> Option<&'static str> {+ match outcome {+ CommitOutcome::Aborted => None,+ CommitOutcome::AbortedProducerDead => Some("abort_failed"),+ CommitOutcome::Unknown => Some("commit_indeterminate"),+ }+}++fn window_verdict(outcome: CommitOutcome, fenced: bool) -> WindowVerdict {+ match (outcome.is_aborted(), fenced) {+ (true, true) => WindowVerdict::Fenced,+ (false, true) => WindowVerdict::FencedUncertain,+ (true, false) => WindowVerdict::Aborted,+ (false, false) => WindowVerdict::Indeterminate,+ }+}++impl CommitOutcome {+ /// Whether the records are known not to have become visible.+ fn is_aborted(self) -> bool {+ matches!(self, Self::Aborted | Self::AbortedProducerDead)+ }+}++fn is_fenced(e: &KafkaError) -> bool {+ matches!(+ e.rdkafka_error_code(),+ Some(RDKafkaErrorCode::Fenced) | Some(RDKafkaErrorCode::ProducerFenced)+ )+}++/// Whether the producer has entered the fatally-fenced state. Once a+/// newer owner initializes the transactional id, librdkafka marks this+/// client fatal and individual operations report local symptoms (purged+/// queues, aborted transactions) rather than the fence itself.+fn producer_fenced<C: ClientContext>(producer: &FutureProducer<C>) -> bool {+ producer+ .client()+ .fatal_error()+ .map(|(code, _)| {+ matches!(+ code,+ RDKafkaErrorCode::Fenced | RDKafkaErrorCode::ProducerFenced+ )+ })+ .unwrap_or(false)+}++/// Abort the window, up to the number of attempts the lease runway was+/// sized for.+///+/// Derived from the constant rather than written out, so that raising the+/// budget raises the attempts and vice versa. The two drifted apart once+/// already: the loop spent four transaction timeouts while the bound that+/// had to contain them counted one.+fn abort_window<C: ClientContext>(+ producer: &FutureProducer<C>,+ timeout: Duration,+) -> Result<(), KafkaError> {+ let mut last = producer.abort_transaction(timeout);+ let mut spent = 1;+ while last.is_err() && spent < FENCING_ABORT_ATTEMPTS {+ last = producer.abort_transaction(timeout);+ spent += 1;+ }+ last+}++/// Close the window after its admission interval: stop admitting, wait+/// for in-flight sends to settle, then commit (or abort a poisoned+/// window) and resolve every waiter with the shared outcome.+async fn commit_window_after(+ fence: Arc<PartitionFence>,+ window: Duration,+ topic: String,+ partition: u32,+) {+ sleep(window).await;++ // Stop admitting joiners, then wait for outstanding sends. The mark+ // holds until this function returns — by any path — so no writer can+ // begin the next transaction while this one is still resolving, and+ // none is stranded if it unwinds.+ let _committing = CommittingMark::take(Arc::clone(&fence), partition);+ loop {+ // Register interest before inspecting the gate: a settle that+ // fires between the check and the await must not be lost.+ let settled = fence.sends_settled.notified();+ tokio::pin!(settled);+ settled.as_mut().enable();+ {+ let gate = fence.gate.lock().unwrap();+ if gate.in_flight == 0 {+ break;+ }+ }+ settled.await;+ }++ let (waiters, poisoned) = {+ let mut gate = fence.gate.lock().unwrap();+ (mem::take(&mut gate.waiters), gate.poisoned)+ };+ histogram!("personhog_leader_fence_window_writes", "partition" => partition.to_string())+ .record(waiters.len() as f64);++ // Commit and abort block up to the transaction timeout; keep them+ // off the runtime threads.+ let producer = fence.producer.inner().clone();+ let timeout = fence.commit_timeout;+ let commit_start = Instant::now();+ #[cfg(any(test, feature = "test-support"))]+ let panic_next = fence.panic_next_commit.swap(false, Ordering::SeqCst);+ let result = spawn_blocking(move || {+ #[cfg(any(test, feature = "test-support"))]+ if panic_next {+ panic!("staged commit task failure");+ }+ if poisoned {+ // One attempt. A producer left in its abortable state fails+ // every later `begin_transaction`, so a failed abort costs+ // the producer itself rather than just this window — and the+ // recovery for that is re-acquisition, whose init aborts the+ // pending transaction at the broker anyway.+ match abort_window(&producer, timeout) {+ Ok(()) => Err((KafkaError::Canceled, CommitOutcome::Aborted)),+ // The records are still definitely not visible — an abort+ // that did not land leaves the transaction open, and open+ // is not committed. What is lost is the producer: it stays+ // in its abortable state, where every later+ // `begin_transaction` fails.+ Err(e) => {+ counter!("personhog_leader_fence_abort_failed_total").increment(1);+ Err((e, CommitOutcome::AbortedProducerDead))+ }+ }+ } else {+ // A commit that fails is not the same as a commit that did+ // not happen. librdkafka distinguishes three cases and the+ // caller's correct behaviour differs for each: a retriable+ // failure leaves the outcome unknown and must be re-attempted+ // (commit is idempotent within the transaction); an+ // abort-requiring failure is a definite abort once the abort+ // is issued; anything else leaves the fate of the records in+ // doubt, which is a distinct answer from "failed".+ let mut attempt = producer.commit_transaction(timeout);+ for _ in 0..COMMIT_RETRIES {+ match &attempt {+ Err(KafkaError::Transaction(e)) if e.is_retriable() => {+ counter!("personhog_leader_fence_commit_retries_total").increment(1);+ warn!(error = %e, "changelog commit failed; retrying");+ attempt = producer.commit_transaction(timeout);+ }+ _ => break,+ }+ }+ match attempt {+ Ok(()) => Ok(()),+ Err(KafkaError::Transaction(e)) if e.txn_requires_abort() => {+ match abort_window(&producer, timeout) {+ Ok(()) => Err((KafkaError::Transaction(e), CommitOutcome::Aborted)),+ // The abort itself is now in doubt, so the+ // records are too.+ Err(abort_err) => Err((abort_err, CommitOutcome::Unknown)),+ }+ }+ // Neither retriable nor abort-requiring is librdkafka's+ // fatal class, which includes the fence. The transaction+ // is left open with its fate unknown and this producer+ // has no way back to a state where it can begin another;+ // whether it was *also* fenced is answered separately,+ // by the verdict, because the two facts serve different+ // callers.+ //+ // Deliberately not inferring "the first attempt cannot+ // have landed" from this loop never re-issuing:+ // `commit_transaction` re-sends EndTxn internally, so one+ // call here is not one round trip at the broker.+ Err(e) => Err((e, CommitOutcome::Unknown)),+ }+ }+ })+ .await;++ let outcome: Result<(), FencedProduceError> = match result {+ Ok(Ok(())) => {+ histogram!("personhog_leader_fence_commit_ms", "outcome" => "committed")+ .record(commit_start.elapsed().as_secs_f64() * 1000.0);+ Ok(())+ }+ Ok(Err((e, outcome))) => {+ histogram!("personhog_leader_fence_commit_ms", "outcome" => "failed")+ .record(commit_start.elapsed().as_secs_f64() * 1000.0);+ if let Some(reason) = condemn_reason(outcome) {+ fence.condemn(partition, reason);+ }+ let fenced_now = is_fenced(&e) || producer_fenced(fence.producer.inner());+ let verdict = window_verdict(outcome, fenced_now);+ if verdict == WindowVerdict::FencedUncertain {+ counter!(+ "personhog_leader_produce_fenced_total",+ "partition" => partition.to_string()+ )+ .increment(1);+ error!(+ partition,+ topic,+ error = %e,+ "changelog window fenced by a newer owner, with its own outcome unknown"+ );+ Err(FencedProduceError::FencedUncertain(e.to_string()))+ } else if verdict == WindowVerdict::Fenced {+ // A poisoned window's fence was already classified and+ // counted where the send failed; counting again here+ // would report two fences for one event.+ if !poisoned {+ counter!(+ "personhog_leader_produce_fenced_total",+ "partition" => partition.to_string()+ )+ .increment(1);+ }+ error!(+ partition,+ topic,+ error = %e,+ "changelog window fenced by a newer owner — this pod's claim is stale"+ );+ Err(FencedProduceError::Fenced)+ } else if verdict == WindowVerdict::Aborted {+ counter!(+ "personhog_leader_fence_aborts_total",+ "partition" => partition.to_string()+ )+ .increment(1);+ error!(partition, topic, error = %e, "changelog window aborted");+ Err(FencedProduceError::Failed(format!("aborted: {e}")))+ } else {+ // Retries are exhausted and the transaction's fate is+ // unknown. Saying "aborted" here would invite a retry+ // that collides with a record that may already be+ // committed, so the doubt is reported as doubt.+ counter!(+ "personhog_leader_fence_commit_indeterminate_total",+ "partition" => partition.to_string()+ )+ .increment(1);+ error!(+ partition,+ topic,+ error = %e,+ "changelog commit outcome unknown; the window may or may not have committed"+ );+ Err(FencedProduceError::Indeterminate(e.to_string()))+ }+ }+ // The commit task itself vanished, so nothing observed the+ // transaction's fate — which leaves the transaction open and this+ // producer unable to begin another. Condemning it is what stops+ // the partition counting as fenced; without it every later write+ // retries a producer that cannot serve one, for the life of the+ // process, with nothing to escalate.+ Err(join) => {+ fence.condemn(partition, "commit_task_lost");+ Err(FencedProduceError::Indeterminate(format!(+ "commit join: {join}"+ )))+ }+ };++ for waiter in waiters {+ // A dropped receiver means the writer's request already ended;+ // nothing to deliver.+ waiter.send(clone_outcome(&outcome)).ok();+ }+}++/// Materialize every fencing series at startup so deploy-window bursts+/// land in an already-scraped series instead of being swallowed by+/// first-increment lazy registration — fence acquisition in particular+/// fires exactly during deploys. A touched histogram renders with zero+/// count until its first sample.+pub fn preregister_fencing_metrics(partitions: u32) {+ for outcome in ["ok", "error"] {+ counter!("personhog_leader_fence_init_total", "outcome" => outcome).increment(0);+ }+ // Settling fires only during handoffs, so every one of its samples+ // lands in a deploy window — the case this preregistration exists+ // for.+ for outcome in ["settled", "timeout", "unusable", "absent"] {+ counter!("personhog_leader_fence_settle_total", "outcome" => outcome).increment(0);+ }+ counter!("personhog_leader_fence_slots_abandoned_total").increment(0);+ counter!("personhog_leader_fence_abandoned_total").increment(0);+ counter!("personhog_leader_fence_abort_failed_total").increment(0);+ for reason in ["abort_failed", "commit_indeterminate", "commit_task_lost"] {+ counter!("personhog_leader_fence_condemned_total", "reason" => reason).increment(0);+ }+ counter!("personhog_leader_fence_commit_retries_total").increment(0);+ counter!("personhog_leader_fenced_partition_drops_total").increment(0);+ counter!("personhog_leader_kafka_produce_errors_total").increment(0);+ for partition in 0..partitions {+ let p = partition.to_string();+ counter!("personhog_leader_fence_aborts_total", "partition" => p.clone()).increment(0);+ counter!(+ "personhog_leader_fence_commit_indeterminate_total",+ "partition" => p.clone()+ )+ .increment(0);+ counter!("personhog_leader_produce_fenced_total", "partition" => p).increment(0);+ }+ // Histograms are deliberately absent: the Prometheus exporter+ // renders one only once it has a sample, so there is nothing a+ // startup call can materialize.+}++/// `FencedProduceError` holds a String and cannot derive Clone cheaply+/// through the oneshot fan-out; rebuild the outcome per waiter.+fn clone_outcome(outcome: &Result<(), FencedProduceError>) -> Result<(), FencedProduceError> {+ match outcome {+ Ok(()) => Ok(()),+ Err(FencedProduceError::NotAcquired) => Err(FencedProduceError::NotAcquired),+ Err(FencedProduceError::Fenced) => Err(FencedProduceError::Fenced),+ Err(FencedProduceError::FencedUncertain(e)) => {+ Err(FencedProduceError::FencedUncertain(e.clone()))+ }+ Err(FencedProduceError::Failed(e)) => Err(FencedProduceError::Failed(e.clone())),+ Err(FencedProduceError::Indeterminate(e)) => {+ Err(FencedProduceError::Indeterminate(e.clone()))+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// The verdict the caller acts on, as a truth table over the two+ /// independent facts it combines.+ ///+ /// The cell that matters is (unknown, fenced). A commit that timed+ /// out, was re-issued — by librdkafka itself, not just by this loop —+ /// and only then discovered the fence may already have landed. Its+ /// own verdict keeps both facts: the router still gets the ownership+ /// answer it bounces on, and the version stays spent. Collapsing it+ /// into `Fenced` frees a version whose record may be committed, and+ /// collapsing it into `Indeterminate` throws away the bounce.+ /// The arrow *into* the condemned state. A producer left in a+ /// transaction it cannot leave must be given up, or the partition+ /// keeps counting as fenced and every later write retries a producer+ /// that cannot serve one, for the life of the process.+ #[test]+ fn a_producer_that_cannot_begin_another_window_is_condemned() {+ assert_eq!(condemn_reason(CommitOutcome::Aborted), None);+ assert_eq!(+ condemn_reason(CommitOutcome::AbortedProducerDead),+ Some("abort_failed")+ );+ assert_eq!(+ condemn_reason(CommitOutcome::Unknown),+ Some("commit_indeterminate")+ );+ }++ #[test]+ fn a_fence_only_settles_the_records_when_the_window_also_aborted() {+ for (outcome, fenced, expected) in [+ (CommitOutcome::Aborted, true, WindowVerdict::Fenced),+ (+ CommitOutcome::AbortedProducerDead,+ true,+ WindowVerdict::Fenced,+ ),+ (CommitOutcome::Aborted, false, WindowVerdict::Aborted),+ (+ CommitOutcome::AbortedProducerDead,+ false,+ WindowVerdict::Aborted,+ ),+ (CommitOutcome::Unknown, true, WindowVerdict::FencedUncertain),+ (CommitOutcome::Unknown, false, WindowVerdict::Indeterminate),+ ] {+ assert_eq!(+ window_verdict(outcome, fenced),+ expected,+ "outcome={outcome:?} fenced={fenced}"+ );+ }+ }+}diff --git a/rust/personhog-leader/src/lib.rs b/rust/personhog-leader/src/lib.rsindex 5d68386cdff5..59c43ae4c77d 100644--- a/rust/personhog-leader/src/lib.rs+++ b/rust/personhog-leader/src/lib.rs@@ -1,6 +1,8 @@pub mod cache;pub mod config;pub mod coordination;+pub mod emitted;+pub mod fencing;pub mod inflight;pub mod kafka;pub mod person_update;diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rsindex 667b2b13fbc2..3d9f2085c311 100644--- a/rust/personhog-leader/src/main.rs+++ b/rust/personhog-leader/src/main.rs@@ -29,6 +29,9 @@ use metrics::{counter, gauge};use personhog_leader::cache::{DirtyIndex, PartitionedCache};use personhog_leader::config::Config;use personhog_leader::coordination::LeaderHandoffHandler;+use personhog_leader::fencing::{+ preregister_fencing_metrics, FencedChangelogProducers, FencedProducerConfig,+};use personhog_leader::inflight::InflightTracker;use personhog_leader::pg::{validate_table_name, PgFallback};use personhog_leader::recovery::{ChangelogRecovery, RecoveryConfig};@@ -51,7 +54,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {.expect("failed to install rustls ring CryptoProvider");let config = Config::init_from_env().expect("Invalid configuration");- preregister_metrics();+ config+ .validate_fencing_timescales()+ .expect("Invalid fencing configuration");validate_table_name(&config.fallback_table).expect("Invalid FALLBACK_TABLE");// Initialize tracing@@ -118,22 +123,29 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {let monitor_guard = manager.monitor_background();- // Metrics/health HTTP server+ // Metrics/health HTTP server. The router is built here rather than+ // inside the task because `setup_metrics_routes` is what installs the+ // process-wide recorder: anything preregistered before it lands in a+ // no-op recorder and never becomes a series.let metrics_port = config.metrics_port;+ let health_router = Router::new()+ .route(+ "/_readiness",+ get(move || {+ let r = readiness.clone();+ async move { r.check().await }+ }),+ )+ .route("/_liveness", get(move || async move { liveness.check() }));+ let metrics_router = setup_metrics_routes(health_router);+ preregister_metrics();+ counter!("personhog_leader_unresolved_versions_total").increment(0);+ counter!("personhog_leader_unresolved_versions_spilled_total").increment(0);+ gauge!("personhog_leader_unresolved_versions").set(0.0);+tokio::spawn(async move {let _guard = metrics_handle.process_scope();- let health_router = Router::new()- .route(- "/_readiness",- get(move || {- let r = readiness.clone();- async move { r.check().await }- }),- )- .route("/_liveness", get(move || async move { liveness.check() }));- let metrics_router = setup_metrics_routes(health_router);-let bind = format!("0.0.0.0:{metrics_port}");let listener = tokio::net::TcpListener::bind(&bind).await@@ -200,6 +212,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {let locks = Arc::new(DashMap::new());let inflight = Arc::new(InflightTracker::new());let dirty_index = Arc::new(DirtyIndex::new(config.dirty_index_max_entries));+ // One per pod, shared by the service that raises floors and the+ // handler that drops them with the partition. The same bound the+ // dirty index uses: both hold one entry per person written but not+ // yet settled, and both are attackable the same way.+ let emitted_versions = Arc::new(personhog_leader::emitted::EmittedVersions::new(+ config.emitted_versions_max_entries,+ ));let recovery = Arc::new(ChangelogRecovery::new(RecoveryConfig {kafka: config.kafka.clone(),@@ -214,6 +233,46 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {kafka_producer.clone(),config.ingestion_warnings_topic.clone(),);+ 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);+ // 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 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),+ settle_budget: config.fencing_settle_budget(),+ },+ )))+ } else {+ None+ };+let service = PersonHogLeaderService::new(Arc::clone(&cache),kafka_producer.clone(),@@ -229,6 +288,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {config.properties_trim_target,),warnings.clone(),+ fenced.clone(),+ Arc::clone(&emitted_versions),);let warm_pools = Arc::new(WarmClientPools::new(@@ -260,6 +321,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {},},Arc::clone(&warm_pools),+ fenced,+ Arc::clone(&emitted_versions),);let advertise_address =personhog_leader::config::derive_advertise_address(&config.grpc_address, &config.pod_ip)@@ -542,6 +605,11 @@ async fn discover_own_controller(/// already inside it, and no rate function can recover a delta that/// precedes a series' first sample.fn preregister_metrics() {+ for fenced in ["true", "false"] {+ counter!("personhog_leader_indeterminate_outcomes_total", "fenced" => fenced).increment(0);+ }+ counter!("personhog_leader_unresolved_versions_total").increment(0);+ gauge!("personhog_leader_unresolved_versions").set(0.0);counter!("personhog_leader_warmed_messages_total").increment(0);counter!("personhog_leader_warm_retries_exhausted_total", "stage" => "committed_offset").increment(0);diff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rsindex d2eb8bf17efc..d92550219a88 100644--- a/rust/personhog-leader/src/service.rs+++ b/rust/personhog-leader/src/service.rs@@ -20,6 +20,8 @@ use crate::cache::{approx_person_bytes, CacheLookup, CachedPerson, DirtyIndex, DirtyMark, PartitionedCache,PersonCacheKey,};+use crate::emitted::{EmittedVersionGuard, EmittedVersions};+use crate::fencing::{FencedChangelogProducers, FencedProduceError};use crate::inflight::InflightTracker;use crate::kafka::produce_person_changelog;use crate::person_update::{apply_property_updates, compute_event_property_updates};@@ -82,6 +84,12 @@ pub struct PersonHogLeaderService {recovery: Arc<ChangelogRecovery>,size_limits: PropertySizeLimits,warnings: WarningsProducer,+ /// Present when broker-enforced epoch fencing is on; the write+ /// path produces through the partition's transaction window.+ fenced: Option<Arc<FencedChangelogProducers>>,+ /// Versions emitted without a confirmed outcome, so a later write for+ /// the same person cannot reuse one.+ emitted_versions: Arc<EmittedVersions>,}impl PersonHogLeaderService {@@ -98,6 +106,8 @@ impl PersonHogLeaderService {recovery: Arc<ChangelogRecovery>,size_limits: PropertySizeLimits,warnings: WarningsProducer,+ fenced: Option<Arc<FencedChangelogProducers>>,+ emitted_versions: Arc<EmittedVersions>,) -> Self {Self {cache,@@ -111,6 +121,8 @@ impl PersonHogLeaderService {recovery,size_limits,warnings,+ fenced,+ emitted_versions,}}@@ -666,13 +678,21 @@ impl PersonHogLeader for PersonHogLeaderService {}let approx_bytes = approx_person_bytes(jsonb_column_size(&new_properties));+ // A version this pod already put on the wire is spent even when+ // it never learned the outcome, so the next one has to clear that+ // floor as well as the state it derived from. Reusing it produces+ // a second record at the same version, and the writer's strict+ // guard keeps only whichever arrived first.+ let base_version = self+ .emitted_versions+ .floor_for(partition, &cache_key, person.version);let updated_person = CachedPerson {id: person.id,uuid: person.uuid.clone(),team_id: person.team_id,properties: new_properties,created_at: person.created_at,- version: person.version + 1,+ version: base_version + 1,is_identified: person.is_identified,approx_bytes,};@@ -696,27 +716,183 @@ impl PersonHogLeader for PersonHogLeaderService {let proto = cached_person_to_proto(&updated_person);+ // From here the record may reach the changelog whatever happens+ // to this request — including the request simply ceasing to exist+ // when the client's deadline expires. The guard is what makes the+ // version un-reusable in that case.+ let mut emitted = EmittedVersionGuard::new(+ Arc::clone(&self.emitted_versions),+ partition,+ cache_key.clone(),+ updated_person.version,+ );+ emitted.emitting();+// Produce to Kafka first, then update the cache on success.// Readers only ever see durably committed state.- let offset = match produce_person_changelog(- &self.producer,- &self.changelog_topic,- partition,- &proto,- )- .await- {- Ok(offset) => offset,- Err(e) => {- 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}"- )));+ 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. Giving+ // up the partition here takes it out of service with+ // nothing to put it back — convergence sees it warmed+ // and unfenced, so no branch re-warms it. On this+ // branch that leaves writes bouncing until a restart+ // or a handoff moves the partition; the stacked+ // lease-validity branch closes it with a serving-side+ // re-acquisition, gated on the authority stamp that+ // gives a pod the standing to bump the epoch. Reads+ // stay served until the lease machinery settles+ // ownership; refusing them needs a lease-validity+ // check on the read path, closed on the same branch.+ 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}"+ )));+ }+ }+ } 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}"+ )));+ }}};@@ -733,6 +909,9 @@ impl PersonHogLeader for PersonHogLeaderService {},);self.cache.put(partition, cache_key, updated_person);+ // The cache carries the version now, so the floor has nothing+ // left to say.+ emitted.resolved();counter!("personhog_leader_updates_total", "outcome" => "updated").increment(1);Ok(Response::new(UpdatePersonPropertiesResponse {@@ -805,6 +984,8 @@ mod tests {),PropertySizeLimits::new(655360, 524288),WarningsProducer::new(producer, "clickhouse_ingestion_warnings".to_string()),+ None,+ Arc::new(EmittedVersions::new(1_000_000)),)}diff --git a/rust/personhog-leader/src/warming.rs b/rust/personhog-leader/src/warming.rsindex c57c0d4959fc..aadd1678de48 100644--- a/rust/personhog-leader/src/warming.rs+++ b/rust/personhog-leader/src/warming.rs@@ -124,7 +124,11 @@ pub(crate) fn make_consumer(.set("group.id", group_id).set("enable.auto.commit", "false").set("enable.auto.offset.store", "false")- .set("auto.offset.reset", "earliest");+ .set("auto.offset.reset", "earliest")+ // Only committed transactions: with fencing on, aborted windows+ // and zombie leftovers must never reach the cache. Identical+ // behavior on a topic without transactional records.+ .set("isolation.level", "read_committed");if kafka.kafka_tls {cfg.set("security.protocol", "ssl").set("enable.ssl.certificate.verification", "false");@@ -473,19 +477,40 @@ pub async fn warm_from_kafka(let mut buffered: Vec<(PersonCacheKey, CachedPerson, i64)> = Vec::new();let mut last_offset: i64 = -1;+ // A transactionally-produced range can end in control records+ // (commit/abort markers) that `recv` never delivers, so reaching the+ // HWM is only observable through the fetch position advancing past+ // them. Poll in short slices and consult the position when quiet;+ // `cfg.recv_timeout` still bounds the total quiet time before the+ // warm is declared stalled.+ let poll_slice = Duration::from_millis(100).min(cfg.recv_timeout);+ let mut quiet_since = Instant::now();+loop {- let msg = match timeout(cfg.recv_timeout, consumer.recv()).await {+ let msg = match timeout(poll_slice, consumer.recv()).await {Ok(Ok(m)) => m,Ok(Err(e)) => {return Err(CoordError::invalid_state(format!("warm recv: {e}")));}Err(_) => {- return Err(CoordError::invalid_state(format!(- "warm timeout; consumed {count} msgs, last_offset={last_offset}, hwm={hwm}",- count = buffered.len()- )));+ let position_reached = consumer+ .position()+ .map_err(|e| CoordError::invalid_state(format!("warm position: {e}")))?+ .find_partition(&cfg.topic, partition_i32)+ .is_some_and(|elem| matches!(elem.offset(), Offset::Offset(p) if p >= hwm));+ if position_reached {+ break;+ }+ if quiet_since.elapsed() >= cfg.recv_timeout {+ return Err(CoordError::invalid_state(format!(+ "warm timeout; consumed {count} msgs, last_offset={last_offset}, hwm={hwm}",+ count = buffered.len()+ )));+ }+ continue;}};+ quiet_since = Instant::now();let offset = msg.offset();last_offset = offset;diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rsindex e2ec7c5ed9ed..d0efbab2d8c0 100644--- a/rust/personhog-leader/tests/common/mod.rs+++ b/rust/personhog-leader/tests/common/mod.rs@@ -344,6 +344,11 @@ pub async fn start_leader_pod(// One dirty index per pod, shared by handler and service exactly as// main.rs wires them: warming seeds the marks the service consults.let dirty_index = Arc::new(DirtyIndex::new(1_000_000));+ // One per pod, shared by handler and service exactly as main.rs+ // wires them: otherwise `release_partition` clears a map the+ // 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));// 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());@@ -358,6 +363,8 @@ pub async fn start_leader_pod(Arc::clone(&dirty_index),warming,pools,+ None,+ std::sync::Arc::clone(&emitted_versions),);let pod = PodHandle::new(store,@@ -387,6 +394,8 @@ pub async fn start_leader_pod(recovery,PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),+ None,+ std::sync::Arc::clone(&emitted_versions),);let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();let leader_addr = listener.local_addr().unwrap();@@ -425,6 +434,11 @@ pub async fn start_leader_pod_with_lease_ttl(let heartbeat_secs = (lease_ttl as u64 / 3).max(1);let inflight = Arc::new(InflightTracker::new());let dirty_index = Arc::new(DirtyIndex::new(1_000_000));+ // One per pod, shared by handler and service exactly as main.rs+ // wires them: otherwise `release_partition` clears a map the+ // 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 pools = Arc::new(WarmClientPools::new(@@ -438,6 +452,8 @@ pub async fn start_leader_pod_with_lease_ttl(Arc::clone(&dirty_index),warming,pools,+ None,+ std::sync::Arc::clone(&emitted_versions),);let pod = PodHandle::new(store,@@ -468,6 +484,8 @@ pub async fn start_leader_pod_with_lease_ttl(recovery,PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),+ None,+ std::sync::Arc::clone(&emitted_versions),);let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();let leader_addr = listener.local_addr().unwrap();@@ -556,6 +574,8 @@ pub async fn start_leader_with_pg_fallback(test_recovery(&mock_cluster.bootstrap_servers()),PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),+ None,+ std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();@@ -576,3 +596,79 @@ pub async fn start_leader_with_pg_fallback((addr, cache, mock_cluster)}++/// Comfortably above the test config's `message.timeout.ms`, which+/// librdkafka requires the broker bound to cover.+pub const BROKER_TXN_TIMEOUT: Duration = Duration::from_secs(30);++/// Fenced producers pointed at the local broker.+///+/// Lives here rather than beside the fencing tests because the *service*+/// needs it too: without a way to build `PersonHogLeaderService` with+/// fencing on, its entire fenced write arm — the version settlement, the+/// cache eviction, the four-way error mapping — is unreachable from any+/// test.+pub fn fenced_producers_for(topic: &str) -> personhog_leader::fencing::FencedChangelogProducers {+ let mut kafka = test_kafka_config();+ kafka.kafka_hosts = KAFKA_BOOTSTRAP.to_string();+ personhog_leader::fencing::FencedChangelogProducers::new(+ personhog_leader::fencing::FencedProducerConfig {+ kafka,+ topic: topic.to_string(),+ init_timeout: Duration::from_secs(10),+ commit_timeout: Duration::from_secs(10),+ broker_txn_timeout: BROKER_TXN_TIMEOUT,+ window: Duration::from_millis(5),+ settle_budget: Duration::from_secs(5),+ },+ )+}++/// A handoff handler sharing an inflight tracker with the caller, for+/// the drain's own admission fence.+#[allow(dead_code)]+pub fn test_handoff_handler_with_inflight(+ topic: &str,+ fenced: Arc<personhog_leader::fencing::FencedChangelogProducers>,+ inflight: Arc<personhog_leader::inflight::InflightTracker>,+) -> personhog_leader::coordination::LeaderHandoffHandler {+ let mut warming = test_warming_config("test", KAFKA_BOOTSTRAP);+ warming.topic = topic.to_string();+ personhog_leader::coordination::LeaderHandoffHandler::new(+ Arc::new(PartitionedCache::new(1 << 20)),+ inflight,+ Arc::new(DirtyIndex::new(1_000_000)),+ warming,+ Arc::new(personhog_leader::warming::WarmClientPools::new(+ &test_kafka_config(),+ "test",+ "personhog-writer",+ )),+ Some(fenced),+ Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),+ )+}++/// A handoff handler wired to real fenced producers, for the convergence+/// steps whose whole point is what they do to the broker's epoch.+#[allow(dead_code)]+pub fn test_handoff_handler(+ topic: &str,+ fenced: Arc<personhog_leader::fencing::FencedChangelogProducers>,+) -> personhog_leader::coordination::LeaderHandoffHandler {+ let mut warming = test_warming_config("test", KAFKA_BOOTSTRAP);+ warming.topic = topic.to_string();+ personhog_leader::coordination::LeaderHandoffHandler::new(+ Arc::new(PartitionedCache::new(1 << 20)),+ Arc::new(personhog_leader::inflight::InflightTracker::new()),+ Arc::new(DirtyIndex::new(1_000_000)),+ warming,+ Arc::new(personhog_leader::warming::WarmClientPools::new(+ &test_kafka_config(),+ "test",+ "personhog-writer",+ )),+ Some(fenced),+ Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),+ )+}diff --git a/rust/personhog-leader/tests/fencing_integration.rs b/rust/personhog-leader/tests/fencing_integration.rsnew file mode 100644index 000000000000..657a0da14c06--- /dev/null+++ b/rust/personhog-leader/tests/fencing_integration.rs@@ -0,0 +1,994 @@+//! Broker-enforced fencing, proven against a real broker: a partition's+//! new owner initializing its transactional id must make the previous+//! owner's producer unusable. Without the fence, a stale owner's writes+//! land in the changelog silently — the exact zombie hazard this+//! mechanism exists to close.++mod common;++use std::sync::Arc;+use std::time::Duration;++use envconfig::Envconfig;+use personhog_coordination::pod::HandoffHandler;+use personhog_leader::fencing::{+ FenceGuard, FencedChangelogProducers, FencedProduceError, FencedProducerConfig,+};+use personhog_leader::inflight::InflightTracker;+use personhog_proto::personhog::types::v1::Person;+use tokio::time::sleep;++use common::{test_kafka_config, KAFKA_BOOTSTRAP};++fn test_person(version: i64) -> Person {+ Person {+ id: 7,+ uuid: "00000000-0000-0000-0000-000000000007".to_string(),+ team_id: 1,+ properties: b"{}".to_vec(),+ version,+ ..Default::default()+ }+}++/// Count the records a `read_committed` consumer can see on partition 0+/// — the same isolation the warming path uses.+async fn read_committed_count(topic: &str) -> usize {+ use rdkafka::consumer::{Consumer, StreamConsumer};+ use rdkafka::{ClientConfig, Message, Offset, TopicPartitionList};++ let consumer: StreamConsumer = ClientConfig::new()+ .set("bootstrap.servers", KAFKA_BOOTSTRAP)+ .set(+ "group.id",+ format!("fence-abort-probe-{}", uuid::Uuid::new_v4()),+ )+ .set("enable.auto.commit", "false")+ .set("auto.offset.reset", "earliest")+ .set("isolation.level", "read_committed")+ .create()+ .expect("probe consumer");+ let mut tpl = TopicPartitionList::new();+ tpl.add_partition_offset(topic, 0, Offset::Beginning)+ .expect("assign");+ consumer.assign(&tpl).expect("assign");++ let mut seen = 0;+ // Anything committed is available immediately; the quiet period only+ // has to outlast delivery, not a transaction timeout.+ while let Ok(Ok(message)) =+ tokio::time::timeout(Duration::from_millis(750), consumer.recv()).await+ {+ if message.payload().is_some() {+ seen += 1;+ }+ }+ seen+}++/// Comfortably above the test config's 5s `message.timeout.ms`, which+/// librdkafka requires the broker bound to cover.+const BROKER_TXN_TIMEOUT: Duration = Duration::from_secs(30);++fn fenced_producers_with_window(topic: &str, window: Duration) -> FencedChangelogProducers {+ let mut kafka = test_kafka_config();+ kafka.kafka_hosts = KAFKA_BOOTSTRAP.to_string();+ FencedChangelogProducers::new(FencedProducerConfig {+ kafka,+ topic: topic.to_string(),+ init_timeout: Duration::from_secs(10),+ commit_timeout: Duration::from_secs(10),+ broker_txn_timeout: BROKER_TXN_TIMEOUT,+ window,+ settle_budget: window + Duration::from_secs(5),+ })+}++fn fenced_producers(topic: &str) -> FencedChangelogProducers {+ let mut kafka = test_kafka_config();+ kafka.kafka_hosts = KAFKA_BOOTSTRAP.to_string();+ FencedChangelogProducers::new(FencedProducerConfig {+ kafka,+ topic: topic.to_string(),+ init_timeout: Duration::from_secs(10),+ commit_timeout: Duration::from_secs(10),+ broker_txn_timeout: BROKER_TXN_TIMEOUT,+ window: Duration::from_millis(5),+ settle_budget: Duration::from_secs(5),+ })+}++/// The core fencing guarantee: after a second owner acquires the+/// partition, the first owner's produce fails as fenced instead of+/// landing in the changelog.+#[tokio::test]+async fn second_acquisition_fences_the_first_producer() {+ // Bounded for the same reason as the turnover test below: a write+ // that parks instead of answering reports as a stuck runner rather+ // than a failure, and the stale owner's produce is exactly the call+ // that would park.+ tokio::time::timeout(Duration::from_secs(60), async {+ let topic = format!("fence_test_{}", uuid::Uuid::new_v4().simple());++ let first = fenced_producers(&topic);+ first.acquire(0).await.expect("first owner acquires");+ first+ .produce(0, &test_person(1))+ .await+ .expect("first owner produces while unfenced");++ let second = fenced_producers(&topic);+ second.acquire(0).await.expect("second owner acquires");+ second+ .produce(0, &test_person(2))+ .await+ .expect("new owner produces");++ match first.produce(0, &test_person(3)).await {+ Err(FencedProduceError::Fenced) | Err(FencedProduceError::NotAcquired) => {}+ other => panic!("stale owner must be fenced, got {other:?}"),+ }+ })+ .await+ .expect("writes parked forever — a window_closed wakeup was lost");+}++/// Concurrent same-partition writes share a transaction window: both+/// succeed with distinct offsets, through one producer, without+/// serializing on per-write commits.+#[tokio::test]+async fn concurrent_writes_share_a_window() {+ let topic = format!("fence_test_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers(&topic));+ producers.acquire(0).await.expect("acquire");++ let a = {+ let p = Arc::clone(&producers);+ tokio::spawn(async move { p.produce(0, &test_person(1)).await })+ };+ let b = {+ let p = Arc::clone(&producers);+ tokio::spawn(async move { p.produce(0, &test_person(2)).await })+ };+ let (a, b) = (a.await.unwrap().unwrap(), b.await.unwrap().unwrap());+ assert_ne!(a, b, "each write must get its own offset");+}++/// Sustained open-loop arrivals across many window turnovers: every+/// write must land and every waiter must be woken through dozens of+/// open → drain → commit cycles. A lost `window_closed` wakeup or a+/// dropped commit-outcome waiter hangs this test; the single-window+/// tests above never exercise turnover.+#[tokio::test]+async fn sustained_writes_across_window_boundaries() {+ // Bounded: a lost `window_closed` wakeup parks every writer forever,+ // and an unbounded test reports that as a stuck runner rather than a+ // failure.+ tokio::time::timeout(Duration::from_secs(60), async {+ let topic = format!("fence_test_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers(&topic));+ producers.acquire(0).await.expect("acquire");++ let writes: Vec<_> = (0..200i64)+ .map(|k| {+ let p = Arc::clone(&producers);+ tokio::spawn(async move {+ sleep(Duration::from_millis(((k * 7) % 97) as u64)).await;+ p.produce(0, &test_person(k)).await+ })+ })+ .collect();+ for write in writes {+ write+ .await+ .unwrap()+ .expect("every write must land across window boundaries");+ }+ })+ .await+ .expect("writes parked forever — a window_closed wakeup was lost");+}++/// A commit nobody observed is not a commit that did not happen.+///+/// The committer can stop without answering — its task dropped at runtime+/// teardown, or unwound — and `spawn_blocking` work is not cancelled when+/// its handle is dropped, so the commit it was running may well have+/// landed. Reporting that as a definite abort frees a version whose record+/// may exist: the retry derives the same number, and the writer's+/// first-wins guard then discards whichever record arrived second, which+/// is the acked one.+#[tokio::test]+async fn a_committer_that_vanishes_leaves_the_outcome_in_doubt() {+ let topic = format!("fence_orphan_{}", uuid::Uuid::new_v4().simple());+ // A long window keeps the committer asleep, so the write is parked on+ // an outcome that is still nobody's to report.+ let producers = Arc::new(fenced_producers_with_window(+ &topic,+ Duration::from_secs(30),+ ));+ producers.acquire(0).await.expect("acquire the fence");++ let writing = {+ let p = Arc::clone(&producers);+ tokio::spawn(async move { p.produce(0, &test_person(1)).await })+ };+ sleep(Duration::from_millis(300)).await;++ producers.abandon_waiters_for_test(0);++ match writing.await.expect("the write task must not panic") {+ Err(FencedProduceError::Indeterminate(_)) => {}+ other => {+ panic!("an unobserved commit must not be reported as a definite abort, got {other:?}")+ }+ }+}++/// A request that vanishes mid-produce — tonic drops the handler future+/// when the client's deadline expires — must return its seat in the+/// window. Without that, the committer waits on an in-flight count that+/// never reaches zero and every later write on the partition parks+/// forever behind it.+#[tokio::test]+async fn a_cancelled_produce_does_not_wedge_the_partition() {+ let topic = format!("fence_cancel_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers(&topic));+ producers.acquire(0).await.expect("acquire");++ {+ let p = Arc::clone(&producers);+ let mut inflight = Box::pin(async move { p.produce(0, &test_person(1)).await });+ // Far too little time to finish: the future is dropped mid-send.+ tokio::time::timeout(Duration::from_micros(200), &mut inflight)+ .await+ .ok();+ }++ tokio::time::timeout(+ Duration::from_secs(10),+ producers.produce(0, &test_person(2)),+ )+ .await+ .expect("a later write must not hang behind the cancelled one")+ .expect("and must succeed");+}++/// Does a successor's `init_transactions` abort the predecessor's open+/// transaction, or merely stop it from committing?+///+/// The drain does not wait for open transaction windows, which is only+/// safe if a record abandoned in one cannot become visible after the+/// partition moves. This pins that: the successor's acquire — which+/// precedes its warm read — leaves the predecessor unable to commit.+///+/// Without this guarantee the drain would have to wait out every open+/// window before acking, so the assertion is load-bearing rather than+/// incidental.+#[tokio::test]+async fn a_successors_init_aborts_the_predecessors_open_window() {+ let topic = format!("fence_abort_{}", uuid::Uuid::new_v4().simple());++ // Predecessor: open a window and get a record enqueued into it, then+ // abandon it exactly as a cancelled request would. The window is+ // short on purpose — its committer must fire *after* the successor+ // has taken the epoch, because "invisible while uncommitted" proves+ // nothing. What has to be shown is that the record can never become+ // visible once the successor owns the partition.+ let first = Arc::new(fenced_producers_with_window(&topic, Duration::from_secs(1)));+ first.acquire(0).await.expect("first owner acquires");+ {+ let p = Arc::clone(&first);+ let mut inflight = Box::pin(async move { p.produce(0, &test_person(1)).await });+ // Long enough for the send to reach the broker, far too short+ // for the window to close.+ tokio::time::timeout(Duration::from_millis(200), &mut inflight)+ .await+ .ok();+ }++ // Successor takes the partition before that window closes, as a+ // warming new owner does.+ let second = fenced_producers(&topic);+ second.acquire(0).await.expect("successor acquires");++ // Now let the predecessor's committer run. This is the moment the+ // drain's wait exists to prevent: an abandoned record committing+ // after the successor is already the owner.+ tokio::time::sleep(Duration::from_secs(3)).await;++ // Read the partition the way warming does.+ let visible = read_committed_count(&topic).await;+ assert_eq!(+ visible, 0,+ "an abandoned record must not become readable after the successor's init — \+ if this fails, the drain must wait for open windows before acking"+ );++ // Zero is also what a partition nothing was ever produced to looks+ // like, so the same sequence without a successor has to show the+ // record arriving. Otherwise this test passes just as well when the+ // send never left the client.+ let control_topic = format!("fence_abort_control_{}", uuid::Uuid::new_v4().simple());+ let lone = Arc::new(fenced_producers_with_window(+ &control_topic,+ Duration::from_secs(1),+ ));+ lone.acquire(0).await.expect("control owner acquires");+ {+ let p = Arc::clone(&lone);+ let mut inflight = Box::pin(async move { p.produce(0, &test_person(1)).await });+ tokio::time::timeout(Duration::from_millis(200), &mut inflight)+ .await+ .ok();+ }+ tokio::time::sleep(Duration::from_secs(3)).await;+ assert_eq!(+ read_committed_count(&control_topic).await,+ 1,+ "with no successor the abandoned record commits — without this the assertion \+ above cannot tell an aborted window from a send that never happened"+ );+}++/// A warm that never finishes must not leave this process holding the+/// partition's broker epoch.+///+/// The pod records a partition as held only once the warm returns, so a+/// fence taken by a warm whose future is dropped — what a lost lease+/// does to an in-flight attempt — belongs to no partition the local+/// self-fence knows to release. The process would keep the epoch while+/// owning nothing, and the real owner's writes would fail as fenced.+#[tokio::test]+async fn a_fence_taken_for_an_unfinished_warm_is_given_back() {+ let topic = format!("fence_guard_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers(&topic));++ {+ producers.acquire(0).await.expect("acquire");+ let _guard = FenceGuard::new(Arc::clone(&producers), 0);+ // The warm ends here without returning, as a torn-down attempt+ // does.+ }++ match producers.produce(0, &test_person(1)).await {+ Err(FencedProduceError::NotAcquired) => {}+ other => panic!("the fence should have been given back, got {other:?}"),+ }+}++/// A warm that finishes keeps what it took.+#[tokio::test]+async fn a_completed_warm_keeps_its_fence() {+ let topic = format!("fence_guard_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers(&topic));++ producers.acquire(0).await.expect("acquire");+ FenceGuard::new(Arc::clone(&producers), 0).keep();++ producers+ .produce(0, &test_person(1))+ .await+ .expect("a completed warm keeps a usable fence");+}++/// A producer whose abort exhausted its retries, or whose commit outcome+/// stayed unknown, is left in a transaction state it cannot begin another+/// window from. It is still installed, so nothing that checks for the+/// *presence* of a fence can tell it apart from a working one.+///+/// The partition must therefore stop reporting itself as fenced and start+/// answering writes as an ownership question, which is what a router can+/// act on and what a repair pass looks for. Reporting a retryable failure+/// instead leaves every write on the partition failing for as long as the+/// process lives, with reads still served and nothing to escalate.+#[tokio::test]+async fn a_condemned_producer_stops_claiming_the_partition() {+ let topic = format!("fence_condemned_{}", uuid::Uuid::new_v4().simple());+ let producers = fenced_producers(&topic);+ producers.acquire(0).await.expect("acquire the fence");+ producers+ .produce(0, &test_person(1))+ .await+ .expect("a healthy fence writes");++ producers.condemn_for_test(0);++ match producers.produce(0, &test_person(2)).await {+ Err(FencedProduceError::NotAcquired) => {}+ other => panic!("a condemned producer must not answer as a live fence, got {other:?}"),+ }++ // And it must have been given up rather than merely refused once: a+ // re-acquisition is the only thing that makes the partition writable+ // again, and it can only run against a partition this pod no longer+ // claims to fence.+ producers.acquire(0).await.expect("re-acquire the fence");+ producers+ .produce(0, &test_person(3))+ .await+ .expect("a re-acquired fence writes again");+}++/// A guard outlives the fence it was taken for when a warm is abandoned+/// and the partition is re-acquired before the guard drops. Releasing by+/// partition alone would then evict the *replacement* — a live fence, on+/// a partition this pod legitimately owns — and every write would fail as+/// unowned until something re-acquired again.+#[tokio::test]+async fn an_abandoned_guard_does_not_evict_its_replacement() {+ let topic = format!("fence_guard_id_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers(&topic));+ producers.acquire(0).await.expect("first acquire");++ // A warm takes the fence, then never finishes.+ let stale = FenceGuard::new(Arc::clone(&producers), 0);++ // Meanwhile the partition is released and taken again, so what is+ // installed is no longer what the guard is answerable for.+ producers.release(0);+ producers.acquire(0).await.expect("re-acquire");++ drop(stale);++ producers+ .produce(0, &test_person(1))+ .await+ .expect("the replacement fence must survive the stale guard");+}++/// A writer parked behind a committing window is woken by the very commit+/// that condemns the producer. Checking usability only before the park+/// skips exactly that writer: it wakes, finds the gate idle, and opens a+/// window on a producer that cannot begin one — answering with a+/// retryable failure the client retries against a pod that cannot write+/// the partition, instead of the ownership bounce that moves it.+#[tokio::test]+async fn a_writer_woken_onto_a_condemned_producer_is_bounced() {+ let topic = format!("fence_woken_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers(&topic));+ producers.acquire(0).await.expect("acquire the fence");++ // Stage the gate exactly as a commit in flight leaves it, so the+ // write below parks rather than opening its own window.+ producers.begin_committing_for_test(0);+ let parked = {+ let p = Arc::clone(&producers);+ tokio::spawn(async move { p.produce(0, &test_person(1)).await })+ };+ tokio::time::sleep(Duration::from_millis(100)).await;++ // The commit resolves badly and condemns the producer, then releases+ // the gate and wakes the parked writer — production's exact order.+ producers.condemn_for_test(0);+ producers.finish_committing_for_test(0);++ match parked.await.expect("the parked task must not panic") {+ Err(FencedProduceError::NotAcquired) => {}+ other => {+ panic!("a writer woken onto a condemned producer must answer as unowned, got {other:?}")+ }+ }+}++/// A commit task that never reports its outcome must condemn the producer.+///+/// `spawn_blocking` work is not cancelled when its handle drops, so the+/// commit may well have landed — the caller therefore learns nothing, and+/// the version stays spent. What matters here is the producer: its+/// transaction is left open, and without the condemn `holds()` keeps+/// answering yes, the repair pass sees nothing to do, and every later+/// write for the partition fails for the life of the process.+#[tokio::test]+async fn a_committer_that_never_reports_condemns_its_producer() {+ let topic = format!("fence_lost_commit_{}", uuid::Uuid::new_v4().simple());+ let producers = fenced_producers(&topic);+ producers.acquire(0).await.expect("acquire the fence");++ producers.panic_next_commit_for_test(0);++ match producers.produce(0, &test_person(1)).await {+ Err(FencedProduceError::Indeterminate(_)) => {}+ other => panic!("a lost committer settles nothing, got {other:?}"),+ }++ // The partition must now read as unfenced, which is what lets the+ // repair pass re-acquire it.+ match producers.produce(0, &test_person(2)).await {+ Err(FencedProduceError::NotAcquired) => {}+ other => {+ panic!("a producer with an open transaction still claimed the partition: {other:?}")+ }+ }+}++/// Settling before the drained ack lands a cancelled write instead of+/// leaving it to the successor to abort.+///+/// `a_successors_init_aborts_the_predecessors_open_window` shows the+/// safety net: an abandoned record can never become visible once the+/// successor owns the partition. This shows the boundary the drain is+/// supposed to be — the record is committed *before* the handoff+/// advances, so the successor reads it as ordinary history rather than+/// racing the predecessor's committer for it.+///+/// The window is far longer than the reads below take. A shorter one+/// closes on its own while the consumer is starting up, and then the+/// test passes whether or not the settle does anything.+#[tokio::test]+async fn settling_commits_an_abandoned_record_before_the_handoff_advances() {+ let topic = format!("fence_settle_{}", uuid::Uuid::new_v4().simple());++ let first = Arc::new(fenced_producers_with_window(+ &topic,+ Duration::from_secs(15),+ ));+ first.acquire(0).await.expect("first owner acquires");+ {+ let p = Arc::clone(&first);+ let mut inflight = Box::pin(async move { p.produce(0, &test_person(1)).await });+ tokio::time::timeout(Duration::from_millis(200), &mut inflight)+ .await+ .ok();+ }++ // Nothing is readable yet: the record sits in an open window.+ assert_eq!(+ read_committed_count(&topic).await,+ 0,+ "the record must still be uncommitted, or this proves nothing"+ );++ // Through the drain, not `settle` directly: the wiring is the part+ // that can be deleted, and calling the method under test by hand+ // proves only that the method exists.+ let handler = common::test_handoff_handler(&topic, Arc::clone(&first));+ handler+ .drain_partition_inflight(0)+ .await+ .expect("the drain must not fail");++ assert_eq!(+ read_committed_count(&topic).await,+ 1,+ "a settled drain must leave the abandoned record committed, not waiting on a \+ successor to decide its fate"+ );++ // And it settled before the successor existed, which is what makes+ // the ack a boundary rather than the start of a race.+ let second = fenced_producers(&topic);+ second.acquire(0).await.expect("successor acquires");+ assert_eq!(+ read_committed_count(&topic).await,+ 1,+ "the successor's init must find nothing left to abort"+ );+}++/// A resume must not take the fence its own convergence's warm already+/// took.+///+/// Warming acquires the partition's transactional id and then re-admits+/// writes as its last act. The resume that can follow in the same+/// convergence exists for a cancelled handoff whose target got as far as+/// taking the epoch — but if it runs after this pod's own warm, its+/// `init_transactions` bumps the epoch out from under every write the+/// warm just admitted, and the pod fences its own live window.+///+/// The mark that prevents this has two halves, and either one alone is+/// useless: warming records the fence it took, and the resume honours+/// that record. This covers both — delete either and the in-flight write+/// below is fenced by its own pod.+#[tokio::test]+async fn a_resume_does_not_fence_the_window_its_own_warm_admitted() {+ let topic = format!("fence_resume_{}", uuid::Uuid::new_v4().simple());+ // Long enough that the write is still sitting in an open window when+ // the resume runs — a window that closed first would be committed+ // already and could not be fenced.+ let producers = Arc::new(fenced_producers_with_window(+ &topic,+ Duration::from_secs(10),+ ));+ let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));++ // A record for the warm to read, which also brings the topic into+ // existence — `fetch_watermarks` has nothing to answer for a topic+ // no one has produced to.+ producers.acquire(0).await.expect("seed the topic");+ producers+ .produce(0, &test_person(1))+ .await+ .expect("seed record");++ // Warming takes the epoch and admits writes on the way out, which is+ // the pair of facts the resume below has to respect.+ handler.warm_partition(0).await.expect("warm the partition");++ let writing = {+ let p = Arc::clone(&producers);+ tokio::spawn(async move { p.produce(0, &test_person(2)).await })+ };+ // Long enough for the send to reach the broker and open the window.+ sleep(Duration::from_millis(300)).await;++ handler.resume_partition(0).await.expect("resume");++ let result = writing.await.expect("the write task must not panic");+ assert!(+ result.is_ok(),+ "a resume must not fence the window this convergence's own warm \+ admitted, got {result:?}"+ );+}++/// A poisoned window must be aborted, and a failed abort must condemn.+///+/// A send that fails inside a window leaves records the transaction can+/// never be allowed to commit, so the commit path aborts instead. Skip+/// the abort and the producer is left in its abortable state — where+/// every later `begin_transaction` fails — while the code reports a+/// clean abort, so nothing condemns it and nothing re-acquires. The+/// partition then refuses every write for the life of the process.+#[tokio::test]+async fn a_poisoned_window_is_aborted_rather_than_committed() {+ let topic = format!("fence_poison_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers_with_window(&topic, Duration::from_secs(1)));+ producers.acquire(0).await.expect("acquire the fence");++ let writing = {+ let p = Arc::clone(&producers);+ tokio::spawn(async move { p.produce(0, &test_person(1)).await })+ };+ sleep(Duration::from_millis(300)).await;+ producers.poison_window_for_test(0);++ match writing.await.expect("the write task must not panic") {+ Err(FencedProduceError::Failed(_)) => {}+ other => panic!("a poisoned window must not report success, got {other:?}"),+ }++ // The abort landed, so the records are definitively not in the log+ // and the producer is still usable for the next window.+ assert_eq!(+ read_committed_count(&topic).await,+ 0,+ "a poisoned window's records must never become visible"+ );+ producers+ .produce(0, &test_person(2))+ .await+ .expect("an aborted window leaves the producer able to open another");+}++/// A window that cannot be settled must not hold the partition hostage.+///+/// The drain fences writes as its first act, and the only branch that+/// lifts that fence runs after the handoff completes — which needs the+/// ack this drain is about to write. So a drain that refuses to ack over+/// an unsettled window strands the partition rejecting every write for+/// the life of the process, while reads carry on and the convergence+/// reports success.+///+/// Refusing would buy nothing anyway: a producer that cannot report its+/// outcome is one the broker accepts no further record from, and the+/// incoming owner's `init_transactions` aborts whatever is left, exactly+/// as it did before the drain waited at all.+#[tokio::test]+async fn a_window_that_cannot_settle_still_lets_the_handoff_proceed() {+ let topic = format!("fence_unsettled_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers(&topic));+ producers.acquire(0).await.expect("acquire the fence");+ producers+ .produce(0, &test_person(1))+ .await+ .expect("a healthy fence writes");++ // The state an abort that never landed, or a commit whose outcome+ // stayed unknown, leaves behind.+ producers.condemn_for_test(0);++ let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));+ handler+ .drain_partition_inflight(0)+ .await+ .expect("a condemned producer must not fail the drain");+}++/// A resume that skipped its acquire must leave the mark for the retry.+///+/// The skip branch consumed the mark, so a convergence torn down after+/// the resume returned — but before `apply` recorded it — retried with+/// the partition still listed as fenced and nothing to say the fence was+/// already held. That retry re-acquires and bumps the epoch out from+/// under the writes the first resume admitted.+#[tokio::test]+async fn a_repeated_resume_does_not_fence_the_window_the_first_one_admitted() {+ let topic = format!("fence_resume_twice_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers_with_window(+ &topic,+ Duration::from_secs(10),+ ));+ let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));++ producers.acquire(0).await.expect("seed the topic");+ producers+ .produce(0, &test_person(1))+ .await+ .expect("seed record");+ handler.warm_partition(0).await.expect("warm the partition");+ handler.resume_partition(0).await.expect("first resume");++ let writing = {+ let p = Arc::clone(&producers);+ tokio::spawn(async move { p.produce(0, &test_person(2)).await })+ };+ sleep(Duration::from_millis(300)).await;++ // The convergence was torn down before it could record the resume,+ // so the same one runs again.+ handler.resume_partition(0).await.expect("retried resume");++ let result = writing.await.expect("the write task must not panic");+ assert!(+ result.is_ok(),+ "a retried resume must not fence the window the first one admitted, got {result:?}"+ );+}+/// A drain that arrives while the window's commit is already running must+/// wait for it.+///+/// At that point the gate reads idle in every field but `committing`: the+/// window is closed to joiners and no sends are outstanding, yet+/// `commit_transaction` is still mid round trip. A settle that asked only+/// whether the window was open would return there and let the drain ack,+/// handing the successor a partition whose last records are still racing+/// its `init_transactions` — the race settling exists to end.+#[tokio::test]+async fn a_drain_waits_for_a_commit_that_is_already_running() {+ let topic = format!("fence_settle_mid_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers(&topic));+ producers.acquire(0).await.expect("acquire the fence");++ // The gate a commit in flight leaves behind.+ producers.begin_committing_for_test(0);++ let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));+ let draining = tokio::spawn(async move { handler.drain_partition_inflight(0).await });+ sleep(Duration::from_millis(300)).await;+ assert!(+ !draining.is_finished(),+ "the drain acked while this window's commit was still in flight"+ );++ producers.finish_committing_for_test(0);+ tokio::time::timeout(Duration::from_secs(10), draining)+ .await+ .expect("the drain must return once the commit finishes")+ .expect("the drain task must not panic")+ .expect("the drain must not fail");+}++/// A resume records the fence it took itself, not only the one warming+/// left behind.+///+/// A handoff cancelled after the drain reaches `resume_partition` with no+/// mark — the drain retires it — so this resume acquires. A convergence+/// torn down before `apply` files the resume runs the same one again, and+/// without a mark of its own that retry re-acquires, bumping the epoch out+/// from under everything the first resume just admitted.+#[tokio::test]+async fn a_resume_that_took_the_fence_itself_does_not_take_it_again() {+ let topic = format!("fence_resume_own_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers_with_window(+ &topic,+ Duration::from_secs(10),+ ));+ let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));++ producers.acquire(0).await.expect("seed the topic");+ // Handed away, then cancelled: the drain retires the mark and the+ // resume has to take the fence — and record it — on its own.+ handler+ .drain_partition_inflight(0)+ .await+ .expect("the drain must not fail");+ handler.resume_partition(0).await.expect("first resume");++ let writing = {+ let p = Arc::clone(&producers);+ tokio::spawn(async move { p.produce(0, &test_person(1)).await })+ };+ sleep(Duration::from_millis(300)).await;++ handler.resume_partition(0).await.expect("retried resume");++ let result = writing.await.expect("the write task must not panic");+ assert!(+ result.is_ok(),+ "a resume must record the fence it took itself, or the retry fences the window it \+ admitted, got {result:?}"+ );+}++/// The drain closes admissions before it waits, not after.+///+/// Waiting first leaves a window where a request admitted during the wait+/// acks after the count reached zero — a write landing above the watermark+/// the successor's warm is about to read, which is the loss the drain+/// exists to prevent.+#[tokio::test]+async fn the_drain_refuses_new_writes_while_it_is_still_waiting() {+ let topic = format!("fence_drain_order_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers(&topic));+ let inflight = Arc::new(InflightTracker::new());+ producers.acquire(0).await.expect("acquire the fence");++ let handler = common::test_handoff_handler_with_inflight(+ &topic,+ Arc::clone(&producers),+ Arc::clone(&inflight),+ );+ // One request in flight, so the drain cannot get past its wait.+ let seat = inflight.begin(0);+ let draining = tokio::spawn(async move { handler.drain_partition_inflight(0).await });+ sleep(Duration::from_millis(200)).await;++ assert!(+ inflight.try_begin(0).is_none(),+ "the drain admitted a write while it was still waiting for the last one"+ );++ drop(seat);+ tokio::time::timeout(Duration::from_secs(10), draining)+ .await+ .expect("the drain must finish once its last request leaves")+ .expect("the drain task must not panic")+ .expect("the drain must not fail");+}++/// Releasing a partition retires its fresh-fence mark.+///+/// The mark says "this convergence already holds the epoch". Left behind+/// across a release — which drops the producer — a later resume trusts it,+/// skips the acquire, and re-admits writes to a partition with no fence+/// installed at all.+#[tokio::test]+async fn releasing_a_partition_retires_its_fresh_fence_mark() {+ let topic = format!("fence_release_mark_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers(&topic));+ let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));++ producers.acquire(0).await.expect("seed the topic");+ producers+ .produce(0, &test_person(1))+ .await+ .expect("seed record");+ handler.warm_partition(0).await.expect("warm the partition");+ handler+ .release_partition(0)+ .await+ .expect("release the partition");+ handler.resume_partition(0).await.expect("resume it again");++ producers+ .produce(0, &test_person(2))+ .await+ .expect("a resume after a release must take the fence again");+}++/// A committer that unwinds with subscribers still queued must condemn+/// the producer, not strand them.+///+/// The mark's drop used to clear `committing` and nothing else: the+/// orphaned waiter list blocked every later window (nothing opens while+/// waiters remain) while `is_usable` kept reporting the fence healthy —+/// every write on the partition parked until its own deadline, silently,+/// forever. Condemning routes it into the same bounce-and-recover story+/// as every other producer no window can be begun from.+#[tokio::test]+async fn an_unwound_committer_condemns_rather_than_stranding_its_waiters() {+ let topic = format!("fence_orphan_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers(&topic));+ producers.acquire(0).await.expect("acquire the fence");+ producers+ .produce(0, &test_person(1))+ .await+ .expect("a healthy fence writes");++ producers.orphan_committer_for_test(0);++ // Bounded: the pre-fix behavior parks this produce forever, and a+ // hung test reports a stuck runner rather than the defect.+ let outcome = tokio::time::timeout(+ Duration::from_secs(5),+ producers.produce(0, &test_person(2)),+ )+ .await+ .expect("a write after an unwound committer must answer, not park");+ match outcome {+ Err(FencedProduceError::NotAcquired) => {}+ other => panic!("an unwound committer's partition must answer as unowned, got {other:?}"),+ }+}++/// One run of the whole composition at the values production derives,+/// not the test constants: window 5ms, txn ~1.2s, settle 2s, broker+/// patience ~6s at the production lease. The per-arm tests pin each+/// mechanism with generous constants; this pins that the *derived*+/// numbers compose against a real broker — windows turn over, commits+/// land inside their budgets, and a drain (with its settle) finishes+/// inside the lease runway the arithmetic promises.+#[tokio::test]+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_ttl = 30;+ config.fencing_txn_timeout_ms = 0;+ config.fencing_message_timeout_ms = 0;+ config+ .validate_fencing_timescales()+ .expect("the production lease supports fencing");++ let topic = format!("fence_derived_{}", uuid::Uuid::new_v4().simple());+ let mut kafka = test_kafka_config();+ kafka.kafka_hosts = KAFKA_BOOTSTRAP.to_string();+ let producers = Arc::new(FencedChangelogProducers::new(FencedProducerConfig {+ kafka,+ topic: 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),+ settle_budget: config.fencing_settle_budget(),+ }));+ producers+ .acquire(0)+ .await+ .expect("acquire at derived init timeout");++ // Sustained concurrent writes across many real 5ms window turnovers.+ let mut writers = Vec::new();+ for w in 0..4 {+ let p = Arc::clone(&producers);+ writers.push(tokio::spawn(async move {+ let mut acked = 0u32;+ for i in 0..25 {+ p.produce(0, &test_person(i64::from(w * 100 + i)))+ .await+ .expect("a write inside the derived budgets must ack");+ acked += 1;+ }+ acked+ }));+ }+ let mut acked = 0;+ for writer in writers {+ acked += writer.await.expect("writer task");+ }+ assert_eq!(acked, 100);++ // The drain — wait plus settle — must fit the runway the validator+ // sized it against.+ let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));+ let drain_started = std::time::Instant::now();+ handler+ .drain_partition_inflight(0)+ .await+ .expect("the drain succeeds at derived timescales");+ assert!(+ drain_started.elapsed() < config.lease_fence_runway(),+ "the drain must fit the lease runway it is budgeted for, took {:?} of {:?}",+ drain_started.elapsed(),+ config.lease_fence_runway()+ );++ // Everything acked is committed and visible to a read_committed+ // consumer, which is the property every consumer relies on.+ assert_eq!(+ read_committed_count(&topic).await,+ 100,+ "every acked write must be committed once the drain settles"+ );+}diff --git a/rust/personhog-leader/tests/integration.rs b/rust/personhog-leader/tests/integration.rsindex 132bf0f7fe49..692939778a57 100644--- a/rust/personhog-leader/tests/integration.rs+++ b/rust/personhog-leader/tests/integration.rs@@ -26,6 +26,7 @@ use personhog_leader::inflight::InflightTracker;use personhog_leader::service::{PersonHogLeaderService, PropertySizeLimits};use personhog_leader::warming::WarmClientPools;use personhog_leader::warnings::WarningsProducer;+use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeader;use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeaderServer;use personhog_proto::personhog::types::v1::{GetPersonRequest, Person, UpdatePersonPropertiesRequest,@@ -185,6 +186,8 @@ async fn unowned_partition_returns_failed_precondition() {test_recovery(KAFKA_BOOTSTRAP),PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),+ None,+ std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();@@ -263,6 +266,8 @@ async fn missing_partition_metadata_returns_invalid_argument() {test_recovery(KAFKA_BOOTSTRAP),PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),+ None,+ std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);// Warm the partition and seed the person so the only failure mode@@ -344,6 +349,8 @@ async fn mismatched_partition_metadata_returns_invalid_argument() {test_recovery(KAFKA_BOOTSTRAP),PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),+ None,+ std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);// Key (1, 42) hashes to some true partition; pick a different one and@@ -431,6 +438,8 @@ async fn writes_fenced_after_drain_reads_still_served() {Arc::clone(&recovery),PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),+ None,+ 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.@@ -446,6 +455,8 @@ async fn writes_fenced_after_drain_reads_still_served() {Arc::clone(&dirty_index),warming,pools,+ None,+ std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);cache.create_partition(0);@@ -549,6 +560,8 @@ async fn drain_fences_before_waiting_on_inflight() {Arc::clone(&recovery),PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),+ None,+ std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);let warming = test_warming_config("fence-race-pod", KAFKA_BOOTSTRAP);let pools = Arc::new(WarmClientPools::new(@@ -562,6 +575,8 @@ async fn drain_fences_before_waiting_on_inflight() {Arc::clone(&dirty_index),warming,pools,+ None,+ std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),));cache.create_partition(0);@@ -865,6 +880,8 @@ async fn update_produces_person_state_to_kafka() {test_recovery(KAFKA_BOOTSTRAP),PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),+ None,+ std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);cache.create_partition(routing_partition);@@ -975,6 +992,8 @@ async fn kafka_produce_failure_leaves_cache_unchanged() {test_recovery(KAFKA_BOOTSTRAP),PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),+ None,+ std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);cache.create_partition(0);@@ -1056,7 +1075,19 @@ async fn kafka_produce_failure_leaves_cache_unchanged() {let result = response.into_inner();assert!(result.updated);- assert_eq!(result.person.unwrap().version, 2);+ // 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.+ assert_eq!(+ result.person.unwrap().version,+ 3,+ "a version put on the wire must not be reused, even when the write failed"+ );cancel.cancel();}@@ -1083,6 +1114,8 @@ async fn e2e_update_produces_to_local_kafka() {test_recovery(KAFKA_BOOTSTRAP),PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),+ None,+ std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);cache.create_partition(0);@@ -1413,6 +1446,8 @@ async fn evicted_dirty_person_recovers_from_changelog() {Arc::clone(&recovery),PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),+ None,+ std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);cache.create_partition(routing_partition);@@ -1511,6 +1546,8 @@ async fn dirty_person_with_failed_recovery_is_unavailable_not_stale() {Arc::clone(&recovery),PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),+ None,+ std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);cache.create_partition(routing_partition);@@ -1615,6 +1652,8 @@ async fn writes_shed_when_dirty_index_is_full() {test_recovery(&mock_cluster.bootstrap_servers()),PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),+ None,+ std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);cache.create_partition(partition);@@ -1710,6 +1749,8 @@ async fn recovery_fails_when_record_version_disagrees_with_the_mark() {Arc::clone(&recovery),PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),+ None,+ std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);cache.create_partition(routing_partition);@@ -1815,6 +1856,8 @@ async fn recovery_reuses_the_partition_consumer_across_fetches() {Arc::clone(&recovery),PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),+ None,+ std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);cache.create_partition(partition);@@ -2031,6 +2074,8 @@ async fn oversize_updates_are_rejected_and_oversized_rows_remediated() {"clickhouse_ingestion_warnings".to_string(),WarningThrottle::new(DEFAULT_THROTTLE_PERIOD, NonZeroU32::new(2).unwrap()),),+ None,+ std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);cache.create_partition(routing_partition);@@ -2431,3 +2476,289 @@ async fn oversize_updates_are_rejected_and_oversized_rows_remediated() {cancel.cancel();}++// ============================================================+// A version this pod emitted without hearing the outcome is spent+// ============================================================++/// A cancelled request, or a commit whose fate stayed unknown, can leave a+/// record on the changelog that this pod never learned about. The cache+/// still holds the version from before that write, so the next update for+/// the same person would derive the same number again — and the writer's+/// strict version guard keeps whichever of the two records arrived first,+/// discarding the other. When the discarded one is the acked write, the+/// acknowledgement was a lie.+///+/// Driving the RPC rather than the derivation: the floor existing is not+/// the property that matters, the write path consulting it is.+#[tokio::test]+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;+ 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),+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),+ None,+ Arc::clone(&emitted_versions),+ );++ cache.create_partition(0);+ let person = test_cached_person();+ let cached_version = person.version;+ seed_person(&cache, 0, person);++ // The state a write that was never answered for leaves behind: the+ // cache is untouched, but versions up to this one may already exist.+ let spent = cached_version + 4;+ emitted_versions.raise_for_test(+ 0,+ PersonCacheKey {+ team_id: 1,+ person_id: 42,+ },+ spent,+ );++ let response = service+ .update_person_properties(with_partition(+ UpdatePersonPropertiesRequest {+ team_id: 1,+ person_id: 42,+ event_name: "$set".to_string(),+ set_properties: serde_json::to_vec(&serde_json::json!({"name": "Updated"}))+ .unwrap(),+ set_once_properties: vec![],+ unset_properties: vec![],+ },+ 0,+ ))+ .await+ .expect("the update itself must still succeed");++ assert_eq!(+ response.into_inner().person.unwrap().version,+ spent + 1,+ "the write must derive past every version this pod already emitted, \+ not merely past the one its cache happens to hold"+ );+}++// ============================================================+// The fenced write path, driven through the RPC+// ============================================================++/// Nothing constructed the service with fencing on, so its entire fenced+/// arm was unreachable: a `panic!` at the top of it left the whole suite+/// green. That arm decides, for every failure mode, whether the write's+/// version is handed back for reuse — and handing back a version whose+/// record may be on the changelog is the acked-write loss the floors+/// exist to prevent.+///+/// This drives the real RPC against a real broker with fencing enabled,+/// and asserts the two answers that matter: a fenced partition bounces,+/// and the version it consumed is *not* reused afterwards.+#[tokio::test]+async fn a_fenced_write_that_bounces_does_not_hand_its_version_back() {+ let topic = format!("fenced_svc_{}", uuid::Uuid::new_v4().simple());+ let cache = Arc::new(PartitionedCache::new(1 << 20));+ let (_mock_cluster, kafka_producer) = create_test_kafka().await;+ let fenced = Arc::new(common::fenced_producers_for(&topic));++ 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),+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),+ Some(Arc::clone(&fenced)),+ std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),+ );++ cache.create_partition(0);+ let person = test_cached_person();+ let base_version = person.version;+ seed_person(&cache, 0, person);+ fenced.acquire(0).await.expect("take the partition's fence");++ // Each call must change something, or the handler takes its+ // no-change fast path and never reaches the produce at all.+ let update = |n: i64| {+ let mut request = Request::new(UpdatePersonPropertiesRequest {+ team_id: 1,+ person_id: 42,+ event_name: "$set".to_string(),+ set_properties: serde_json::to_vec(&serde_json::json!({"n": n})).unwrap(),+ set_once_properties: vec![],+ unset_properties: vec![],+ });+ request+ .metadata_mut()+ .insert("x-partition", "0".parse().unwrap());+ request+ };++ // A healthy fenced write goes through the transaction window.+ let first = service+ .update_person_properties(update(1))+ .await+ .expect("a fenced write with a held fence must succeed");+ assert_eq!(first.into_inner().person.unwrap().version, base_version + 1);++ // Give the fence up beneath the service: the next write has no+ // producer and must answer as unowned so the router re-resolves.+ fenced.release(0);+ let bounced = service+ .update_person_properties(update(2))+ .await+ .expect_err("a write with no fence must not be acked");+ assert_eq!(+ bounced.code(),+ tonic::Code::FailedPrecondition,+ "an unowned partition is the router's bounce class, not a retryable failure"+ );++ // The bounced write never reached the broker, so its version is free+ // to derive again — the next successful write must land exactly one+ // past the first, not two.+ fenced.acquire(0).await.expect("re-take the fence");+ let third = service+ .update_person_properties(update(3))+ .await+ .expect("a re-acquired fence writes again");+ assert_eq!(+ third.into_inner().person.unwrap().version,+ base_version + 2,+ "a write that provably never left the pod must not burn its version"+ );+}++/// A window fenced with its own outcome unknown answers two questions at+/// once, and the handler has to honour both: the router gets the+/// ownership bounce, and the version stays spent because the commit may+/// have landed on an attempt librdkafka re-issued internally. Handing the+/// version back would put a second record at the same number behind one+/// that may be committed, and the writer's first-wins guard then discards+/// whichever arrived second — which is the acked one.+///+/// The cached entry stays. Evicting it resolves nothing, since recovery+/// reads the last *marked* offset — the previous write that did succeed —+/// and it would answer NOT_FOUND outright once that mark is pruned on a+/// pod with no fallback pool configured.+#[tokio::test]+async fn a_fence_with_an_unknown_outcome_keeps_both_its_version_and_its_cache_entry() {+ for (staged, expected) in [+ (+ personhog_leader::fencing::FencedProduceError::FencedUncertain("staged".to_string()),+ tonic::Code::FailedPrecondition,+ ),+ (+ personhog_leader::fencing::FencedProduceError::Indeterminate("staged".to_string()),+ tonic::Code::Unknown,+ ),+ ] {+ an_unknown_outcome_keeps_its_version(staged, expected).await;+ }+}++/// Both doubt arms carry the same obligation: the record may be in the+/// log, so the version stays spent and the cached entry stays put. They+/// differ only in what the caller is told — an ownership bounce when the+/// partition also moved, plain doubt when it did not.+async fn an_unknown_outcome_keeps_its_version(+ staged: personhog_leader::fencing::FencedProduceError,+ expected: tonic::Code,+) {+ let topic = format!("fenced_uncertain_{}", uuid::Uuid::new_v4().simple());+ let cache = Arc::new(PartitionedCache::new(1 << 20));+ let (_mock_cluster, kafka_producer) = create_test_kafka().await;+ let fenced = Arc::new(common::fenced_producers_for(&topic));+ let emitted_versions = Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000));++ 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),+ PropertySizeLimits::new(655360, 524288),+ WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),+ Some(Arc::clone(&fenced)),+ Arc::clone(&emitted_versions),+ );++ cache.create_partition(0);+ let person = test_cached_person();+ let base_version = person.version;+ seed_person(&cache, 0, person);+ fenced.acquire(0).await.expect("take the partition's fence");++ let cache_key = PersonCacheKey {+ team_id: 1,+ person_id: 42,+ };+ let update = |n: i64| {+ let mut request = Request::new(UpdatePersonPropertiesRequest {+ team_id: 1,+ person_id: 42,+ event_name: "$set".to_string(),+ set_properties: serde_json::to_vec(&serde_json::json!({"n": n})).unwrap(),+ set_once_properties: vec![],+ unset_properties: vec![],+ });+ request+ .metadata_mut()+ .insert("x-partition", "0".parse().unwrap());+ request+ };++ service+ .update_person_properties(update(1))+ .await+ .expect("a fenced write with a held fence must succeed");++ // The outcome a broker fault inside a transaction would produce.+ fenced.stage_failure_for_test(0, staged);+ let bounced = service+ .update_person_properties(update(2))+ .await+ .expect_err("an uncertain fence must not be acked");+ assert_eq!(+ bounced.code(),+ expected,+ "the caller's answer: {}",+ bounced.message()+ );++ assert_eq!(+ emitted_versions.floor_for(0, &cache_key, 0),+ base_version + 2,+ "a version whose record may be committed must stay spent"+ );+ assert!(+ matches!(+ cache.get(0, &cache_key),+ personhog_leader::cache::CacheLookup::Found(_)+ ),+ "the entry must survive, or a pruned mark leaves the person unreadable"+ );+}diff --git a/rust/personhog-router/src/backend/leader.rs b/rust/personhog-router/src/backend/leader.rsindex a5686cf62cdd..1baaa290725c 100644--- a/rust/personhog-router/src/backend/leader.rs+++ b/rust/personhog-router/src/backend/leader.rs@@ -127,6 +127,22 @@ pub struct LeaderBackend {stash: StashTable,}+/// Whether a bounce leaves the write's fate in doubt.+///+/// Only a transport failure does: the leader may have applied the frame+/// before the connection broke. Every other bounce is a refusal the+/// leader made before touching anything — including the fenced class,+/// which carries one exception (a window fenced with its own commit+/// outcome unknown) that is deliberately not counted here, since+/// admission refusals are the ordinary traffic of every handoff and+/// counting the class would swamp the signal.+pub(crate) fn counts_as_possibly_applied(reason: BounceReason) -> bool {+ match reason {+ BounceReason::Transport => true,+ BounceReason::Fenced | BounceReason::Unrouted => false,+ }+}+impl LeaderBackend {pub fn new(routing_table: Arc<RwLock<HashMap<u32, String>>>,@@ -302,9 +318,15 @@ impl LeaderBackend {.await{// Every leader use of FailedPrecondition is a routing-race- // rejection at admission ("fenced for handoff", "partition- // not owned") — never a semantic client error — so it- // classifies as a bounce rather than an outcome.+ // rejection ("fenced for handoff", "partition not owned") —+ // never a semantic client error — so it classifies as a+ // bounce rather than an outcome. Almost all are refusals at+ // admission, where nothing was attempted; the exception is a+ // window fenced with its own commit outcome unknown, whose+ // record may already be in the changelog. That case is not+ // counted as a possible replay: admission refusals are the+ // ordinary traffic of every handoff, so counting the class+ // would swamp the signal it exists to carry.Ok((response, _call_ms))if grpc_status_code(&response) == Some(Code::FailedPrecondition as i32) =>{@@ -398,7 +420,7 @@ impl LeaderBackend {return (response, Some(call_ms));}ForwardDecision::Bounced(reason) => {- if reason == BounceReason::Transport {+ if counts_as_possibly_applied(reason) {possibly_applied = true;}consecutive_bounces += 1;@@ -427,6 +449,20 @@ impl LeaderBackend {#[cfg(test)]mod tests {+ use super::{counts_as_possibly_applied, BounceReason};++ /// Only a transport failure leaves the write's fate in doubt, and+ /// the distinction drives the replay counter operators consult when+ /// deciding whether a duplicate write is possible. It had no test at+ /// all while it lived inline in the forward loop, where reaching it+ /// needs a live leader and a metrics recorder.+ #[test]+ fn only_a_transport_bounce_leaves_the_write_in_doubt() {+ assert!(counts_as_possibly_applied(BounceReason::Transport));+ assert!(!counts_as_possibly_applied(BounceReason::Fenced));+ assert!(!counts_as_possibly_applied(BounceReason::Unrouted));+ }+use super::*;fn test_config(num_partitions: u32) -> LeaderBackendConfig {diff --git a/rust/personhog-router/src/backend/mod.rs b/rust/personhog-router/src/backend/mod.rsindex 66ddc4ea128b..2224219774fd 100644--- a/rust/personhog-router/src/backend/mod.rs+++ b/rust/personhog-router/src/backend/mod.rs@@ -3,6 +3,7 @@ mod leader;mod replica;mod stash;+pub(crate) use leader::counts_as_possibly_applied;pub use leader::{AddressResolver, BounceReason, ForwardDecision, ForwardPath, LeaderBackend, LeaderBackendConfig,};diff --git a/rust/personhog-router/src/stash_handler.rs b/rust/personhog-router/src/stash_handler.rsindex e5f5b777fa80..2d3f83e0896b 100644--- a/rust/personhog-router/src/stash_handler.rs+++ b/rust/personhog-router/src/stash_handler.rs@@ -11,8 +11,8 @@ use tokio_util::sync::CancellationToken;use tonic::Code;use crate::backend::{- BounceReason, DrainSession, ForwardDecision, ForwardPath, LeaderBackend, StashKey,- StashedRequest, TakenKeyRun, BOUNCE_BACKOFF, MAX_CONSECUTIVE_BOUNCES,+ counts_as_possibly_applied, BounceReason, DrainSession, ForwardDecision, ForwardPath,+ LeaderBackend, StashKey, StashedRequest, TakenKeyRun, BOUNCE_BACKOFF, MAX_CONSECUTIVE_BOUNCES,};use crate::grpc_http::{grpc_error_response, is_grpc_error_response};@@ -272,7 +272,7 @@ async fn forward_key_run(outcome.completed += 1;}Disposition::Bounce(reason) => {- if matches!(reason, BounceReason::Transport) {+ if counts_as_possibly_applied(reason) {entry.item.possibly_applied = true;}metrics::counter!(diff --git a/rust/personhog-stateright/README.md b/rust/personhog-stateright/README.mdindex d41b42acc547..0828e92fd3a2 100644--- a/rust/personhog-stateright/README.md+++ b/rust/personhog-stateright/README.md@@ -37,7 +37,7 @@ minimum viable scale or not at all. Measured sizes (release mode):| 2 pods / 2 routers / 2 partitions, 2 failures | ~8.9M | 110s || 3 pods / 2 routers / 2 partitions, 2 failures | ~24M | 300s |-The test suite (twelve scenarios, ~2min total in release) runs the full+The test suite (twenty-odd scenarios; the heavy double-zombie pair dominates the runtime) runs the fullverdict matrix — the 1-partition scenarios, the 2-partition casesincluding both double-zombie verdicts, the 3-pod rejoin, and thereachability probes. Two partitions matter for the coordinator's@@ -66,7 +66,7 @@ queue — mapped to named production behavior for review:| Model | Production behavior modeled ||---|---|-| `Action::CleanupStale` | `cleanup_stale_handoffs` (mod_revision-guarded delete, modeled as atomic check-and-delete) |+| `Action::CancelDeadNewOwner` / `Action::Cancel` / `Action::CleanupComplete` | the planner's cancellation-by-replacement and mod_revision-guarded Complete cleanup, modeled as atomic check-and-swap / check-and-delete || `Action::AdvancePhase` Warming→Complete | `complete_handoff` (phase write + assignment flip as one txn) || `Action::Converge` effect application | `PodHandle::apply` (warm installs at HWM and unfences, drain fences, acks echo the handoff id and are phase-gated) || `Action::Observe` | Router watch handlers: `begin_stash` + FreezeAck (Freezing only), cutover + stash drain at Complete, drain-back on cancellation |@@ -136,13 +136,13 @@ open scenarios the small configs can't reach?" with checker facts:**concurrent handoffs are reachable** (one rebalance transaction createsa handoff per moved/fresh partition, and safety is verified at everysuch state), and **a dual-role pod — drain-side of one handoff while-warm-side of another — is machine-proven unreachable** under the-shipped protocol, even with crash-and-rejoin churn at 3 pods / 3-partitions: within one plan the sticky strategy never takes from and-gives to the same pod, and the rebalance deferral gate keeps handoffs-from different plans from coexisting. If a strategy or gate change ever-makes it reachable, the probe test fails and the dual-role case needs-explicit analysis. The rejoin scenario runs at 3 pods because that is+warm-side of another — is machine-proven reachable and safe**. Under+the old global rebalance gate it was unreachable; partial rebalancing+(in-flight partitions pinned, everything else planned) deliberately+lets handoffs from different plans coexist, so the probe that once+proved unreachability now pins the state as reached — and the same run+verifies every safety property across those interleavings, which holds+because every mechanism the two roles touch is partition-scoped. The rejoin scenario runs at 3 pods because that isthe smallest scale where the strategy genuinely chooses a placementtarget rather than having it forced — the one axis a 2-pod worldunder-exercises; the per-partition safety relations themselves arediff --git a/rust/personhog-stateright/src/main.rs b/rust/personhog-stateright/src/main.rsindex 868a52023169..7707e4e27999 100644--- a/rust/personhog-stateright/src/main.rs+++ b/rust/personhog-stateright/src/main.rs@@ -11,7 +11,7 @@use clap::{Parser, ValueEnum};-use personhog_stateright::model::{HandoffModel, Variant};+use personhog_stateright::model::{HandoffModel, Variant, WarmOrder};use stateright::Model;#[derive(Parser)]@@ -28,14 +28,18 @@ enum Scenario {CurrentZombie,/// The epoch-fencing fix.EpochFenced,+ /// The rejected warm ordering (read before fence), with+ /// counterexamples.+ EpochFencedReadFirst,}fn main() {let args = Args::parse();- let (variant, crashes, zombie_window) = match args.scenario {- Scenario::Current => (Variant::Current, 1, 0),- Scenario::CurrentZombie => (Variant::Current, 1, 1),- Scenario::EpochFenced => (Variant::EpochFenced, 1, 1),+ 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 model = HandoffModel {@@ -44,6 +48,7 @@ fn main() {late_routers: 0,partitions: 1,variant,+ warm_order,writes: 2,reads: 1,crashes,diff --git a/rust/personhog-stateright/src/model.rs b/rust/personhog-stateright/src/model.rsindex 482a1956c667..2c9caf7f4a0f 100644--- a/rust/personhog-stateright/src/model.rs+++ b/rust/personhog-stateright/src/model.rs@@ -19,8 +19,8 @@ use personhog_coordination::types::{use stateright::{Model, Property};use crate::types::{- Action, Changelog, Handoff, Partition, Phase, Pod, PodId, Router, RouterId, StashedRequest,- SystemState, WarmState,+ Action, Changelog, Handoff, HandoffId, Partition, PendingWarm, Phase, Pod, PodId, Router,+ RouterId, StashedRequest, SystemState, WarmState,};/// Deterministic names bridging the model's compact u8 ids to the@@ -73,6 +73,16 @@ pub enum Variant {EpochFenced,}+/// 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.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum WarmOrder {+ FenceFirst,+ ReadFirst,+}+/// Model parameters. Small numbers — state spaces explode; protocol bugs/// are structural and show up at minimum viable scale.#[derive(Clone, Debug)]@@ -84,6 +94,9 @@ pub struct HandoffModel {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.+ pub warm_order: WarmOrder,/// Total client writes the checker may inject.pub writes: u8,/// Total strong reads the checker may inject.@@ -190,6 +203,120 @@ impl HandoffModel {}}+ /// One step of `warm_partition` for pod `x` on `partition`. Under+ /// `Current` the warm is a single atomic install — there is no+ /// broker step to separate from the read. Under `EpochFenced` it is+ /// two steps whose order is `self.warm_order`, with the in-between+ /// state held in `pending_warm` so the checker interleaves every+ /// other action against the gap.+ fn warm_step(+ &self,+ state: &mut SystemState,+ x: PodId,+ partition: Partition,+ for_handoff: Option<HandoffId>,+ ) {+ // Both orderings are two steps in production, but only one of+ // them is *observably* two steps. Acquiring the fence first bumps+ // the epoch before the read, and an append requires an installed+ // warm carrying the current epoch — which no pod has during the+ // gap, this one included. The changelog therefore cannot grow+ // between the two steps, so the cutoff read at acquire time and+ // at install time are the same value and no interleaving can tell+ // them apart. Collapsing that case keeps the state space at the+ // size it had before the decomposition; `ReadFirst`, where the+ // gap is the entire point, stays split.+ //+ // Be precise about what that buys: the checker *proves* ReadFirst+ // unsafe by exploring its gap, and never explores FenceFirst's —+ // FenceFirst's safety rests on the argument above, not on+ // 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;+ if !observable_gap {+ let warm = {+ let log = state.changelogs.get_mut(&partition).unwrap();+ if self.variant == Variant::EpochFenced {+ log.epoch = log.epoch.wrapping_add(1);+ }+ WarmState {+ for_handoff,+ epoch: log.epoch,+ cutoff: log.len,+ accepted: 0,+ }+ };+ let pod = state.pods.get_mut(&x).unwrap();+ pod.warmed.insert(partition, warm);+ pod.fenced.remove(&partition);+ return;+ }+ match state.pods[&x].pending_warm.get(&partition).copied() {+ None => {+ // The rejected ordering: the changelog read runs to the+ // current HWM while the fence — and thus the rejection of+ // a zombie's write — does not exist yet.+ let pending = PendingWarm {+ cutoff: state.changelogs[&partition].len,+ };+ state+ .pods+ .get_mut(&x)+ .unwrap()+ .pending_warm+ .insert(partition, pending);+ }+ Some(PendingWarm { cutoff }) => {+ // The cutoff predates the fence: anything committed in+ // the gap sits beyond it, invisible forever.+ let warm = {+ let log = state.changelogs.get_mut(&partition).unwrap();+ log.epoch = log.epoch.wrapping_add(1);+ WarmState {+ for_handoff,+ epoch: log.epoch,+ cutoff,+ accepted: 0,+ }+ };+ let pod = state.pods.get_mut(&x).unwrap();+ pod.pending_warm.remove(&partition);+ pod.warmed.insert(partition, warm);+ pod.fenced.remove(&partition);+ }+ }+ }++ /// Whether the handoff's new owner has fixed the cutoff it will+ /// serve with: a warm installed for *this* handoff, or a mid-warm+ /// read already taken (a pending warm always belongs to the current+ /// attempt — cancellation requires the target unregistered, which+ /// wipes its process memory). An earlier-era warm does NOT freeze+ /// the cutoff: the Acquiring convergence releases and rebuilds it.+ fn handoff_cutoff_frozen(+ &self,+ state: &SystemState,+ h: &Handoff,+ partition: Partition,+ ) -> bool {+ let pod = &state.pods[&h.new_owner];+ match pod.warmed.get(&partition) {+ Some(w) => w.for_handoff == Some(h.id),+ None => pod.pending_warm.contains_key(&partition),+ }+ }++ /// Whether the assignment owner has fixed its serving cutoff — the+ /// Serving convergence honors any installed warm (an owner's warm+ /// cannot go stale while ownership is continuous), so any warm or a+ /// taken mid-warm read freezes it.+ fn owner_cutoff_frozen(&self, state: &SystemState, x: PodId, partition: Partition) -> bool {+ let pod = &state.pods[&x];+ pod.warmed.contains_key(&partition) || pod.pending_warm.contains_key(&partition)+ }+/// Serve a strong read at pod `x`, if it can (running, partition/// warmed). Sets the staleness flag when the pod's visible prefix/// (warm cutoff + own accepted writes) is behind the changelog — the@@ -213,21 +340,14 @@ impl HandoffModel {/// Append one acked write to the changelog, tracking the loss flag:/// if the protocol has designated a *different* pod as the (incoming- /// or current) owner and that pod has already warmed, this write sits- /// beyond its warm cutoff and is invisible to it forever.+ /// or current) owner and that pod's warm cutoff is already fixed,+ /// this write sits beyond the cutoff and is invisible to it forever.fn accept_write(&self, state: &mut SystemState, x: PodId, partition: Partition) {let designated_other = match state.handoffs.get(&partition) {- // A handoff-designated pod's warm hides this write forever- // only if that warm will actually be honored — i.e. it was- // installed for this handoff. A stale-era warm is released- // and rebuilt at Acquiring, which picks the write up.- Some(h) if h.new_owner != x => state.pods[&h.new_owner]- .warmed- .get(&partition)- .is_some_and(|w| w.for_handoff == Some(h.id)),+ Some(h) if h.new_owner != x => self.handoff_cutoff_frozen(state, h, partition),Some(_) => false,None => match state.assignments.get(&partition) {- Some(owner) if *owner != x => state.pods[owner].warmed.contains_key(&partition),+ Some(owner) if *owner != x => self.owner_cutoff_frozen(state, *owner, partition),_ => false,},};@@ -369,6 +489,7 @@ impl Model for HandoffModel {running: true,warmed: BTreeMap::new(),fenced: BTreeSet::new(),+ pending_warm: BTreeMap::new(),zombie_writes_left: 0,},)@@ -716,28 +837,30 @@ impl Model for HandoffModel {DesiredState::Serving => {let pod = &state.pods[&x];if !pod.warmed.contains_key(&p) {- // `warm_partition`: atomic install at the- // current HWM; unfences. Under EpochFenced,- // warming is also `init_transactions`, which- // bumps the broker epoch and fences every- // earlier producer for the partition.- let warm = {- let log = state.changelogs.get_mut(&p).unwrap();- if self.variant == Variant::EpochFenced {- log.epoch = log.epoch.wrapping_add(1);- }- WarmState {- for_handoff: None,- epoch: log.epoch,- cutoff: log.len,- accepted: 0,- }- };- let pod = state.pods.get_mut(&x).unwrap();- pod.warmed.insert(p, warm);- pod.fenced.remove(&p);+ // `warm_partition`, one step at a time (see+ // `warm_step` for the two orderings under+ // EpochFenced).+ self.warm_step(&mut state, x, p, None);} else if pod.fenced.contains(&p) {- // `resume_partition`.+ // `resume_partition`. Under EpochFenced the+ // cancelled handoff's target may have bumped+ // the broker epoch past this pod's producer;+ // production re-acquires the fence before+ // re-admitting writes, or every write would+ // fail as fenced until the next handoff.+ if self.variant == Variant::EpochFenced {+ let log = state.changelogs.get_mut(&p).unwrap();+ log.epoch = log.epoch.wrapping_add(1);+ let epoch = log.epoch;+ state+ .pods+ .get_mut(&x)+ .unwrap()+ .warmed+ .get_mut(&p)+ .unwrap()+ .epoch = epoch;+ }state.pods.get_mut(&x).unwrap().fenced.remove(&p);} else {return None;@@ -747,48 +870,49 @@ impl Model for HandoffModel {let h_id = state.handoffs[&p].id;let pod = state.pods.get_mut(&x).unwrap();let newly_fenced = pod.fenced.insert(p);+ // The flip to Drained abandons an in-flight warm:+ // the production warm future is dropped, and any+ // later warm re-acquires the fence rather than+ // resuming this attempt's stale init.+ let dropped_pending = pod.pending_warm.remove(&p).is_some();// `put_drained_ack`, only while the phase is// Draining, echoing the handoff id.let ack_needed = ack && state.drained_acks.get(&(p, x)) != Some(&h_id);if ack_needed {state.drained_acks.insert((p, x), h_id);}- if !newly_fenced && !ack_needed {+ if !newly_fenced && !ack_needed && !dropped_pending {return None;}}DesiredState::Acquiring => {let h_id = state.handoffs[&p].id;let mut changed = false;- // Mirror of the pod's `WarmProvenance` check: only- // a warm installed for this handoff satisfies its- // warming — a leftover from an earlier era (the- // intervening Released convergence never ran) is- // released and rebuilt at the current HWM.+ // Only a warm installed for *this* handoff+ // satisfies its warming; one from an earlier era+ // is released and rebuilt (its cutoff can+ // predate writes accepted since — the+ // `WarmProvenance` guard in the production+ // Acquiring arm).let valid = state.pods[&x].warmed.get(&p).is_some_and(|w| w.for_handoff == Some(h_id));if !valid {- let warm = {- let log = state.changelogs.get_mut(&p).unwrap();- if self.variant == Variant::EpochFenced {- log.epoch = log.epoch.wrapping_add(1);- }- WarmState {- for_handoff: Some(h_id),- epoch: log.epoch,- cutoff: log.len,- accepted: 0,- }- };- let pod = state.pods.get_mut(&x).unwrap();- pod.warmed.insert(p, warm);- pod.fenced.remove(&p);+ // Release a warm from an earlier era, then+ // `warm_partition`, one step at a time.+ state.pods.get_mut(&x).unwrap().warmed.remove(&p);+ self.warm_step(&mut state, x, p, Some(h_id));changed = true;}- // `put_warmed_ack`, echoing the handoff id.- if state.warmed_acks.get(&(p, x)) != Some(&h_id) {+ // `put_warmed_ack`, echoing the handoff id —+ // only once this handoff's warm has installed.+ if state.pods[&x]+ .warmed+ .get(&p)+ .is_some_and(|w| w.for_handoff == Some(h_id))+ && state.warmed_acks.get(&(p, x)) != Some(&h_id)+ {state.warmed_acks.insert((p, x), h_id);changed = true;}@@ -800,7 +924,10 @@ impl Model for HandoffModel {let pod = state.pods.get_mut(&x).unwrap();let held = pod.warmed.remove(&p).is_some();let fenced = pod.fenced.remove(&p);- if !held && !fenced {+ // `release_partition` also drops a mid-warm+ // fence producer.+ let pending = pod.pending_warm.remove(&p).is_some();+ if !held && !fenced && !pending {return None;}}@@ -972,6 +1099,7 @@ impl Model for HandoffModel {pod.running = true;pod.warmed.clear();pod.fenced.clear();+ pod.pending_warm.clear();pod.zombie_writes_left = 0;}Action::CrashRestartWithinTtl(x) => {@@ -983,6 +1111,7 @@ impl Model for HandoffModel {let pod = state.pods.get_mut(&x).unwrap();pod.warmed.clear();pod.fenced.clear();+ pod.pending_warm.clear();}Action::LeaseExpire(x) => {let pod = &state.pods[&x];@@ -1006,6 +1135,7 @@ impl Model for HandoffModel {pod.running = false;pod.warmed.clear();pod.fenced.clear();+ pod.pending_warm.clear();pod.zombie_writes_left = 0;}Action::RouterLeaseExpire(r) => {@@ -1151,11 +1281,15 @@ impl Model for HandoffModel {};let assigned = s.assignments.get(&p) == Some(&target);let pod = &s.pods[&target];+ // `write_capable` (not just warmed ++ // unfenced) so a stale producer epoch —+ // the fenced-wedge a resume without+ // re-acquisition would leave — fails+ // stability rather than passing it.assigned&& pod.running&& pod.registered- && pod.warmed.contains_key(&p)- && !pod.fenced.contains(&p)+ && m.write_capable(s, target, p)})))&& m.router_ids().all(|r| {let router = &s.routers[&r];diff --git a/rust/personhog-stateright/src/types.rs b/rust/personhog-stateright/src/types.rsindex 8b22c44dfbc7..1aa8846aed02 100644--- a/rust/personhog-stateright/src/types.rs+++ b/rust/personhog-stateright/src/types.rs@@ -62,6 +62,21 @@ pub struct WarmState {pub accepted: u8,}+/// A warm caught between its two steps, under the rejected read-first+/// ordering: the changelog read is taken while the fence — and with it+/// the rejection of a stale owner's write — does not exist yet, so a+/// write can be acked into the gap and sit above the cutoff forever.+///+/// Fence-first needs no such state. Its epoch bump precedes the read and+/// an append requires an installed warm carrying the current epoch, so+/// nothing can append between the two steps and the model installs the+/// warm atomically.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct PendingWarm {+ /// The changelog length captured before the fence existed.+ pub cutoff: u8,+}+/// One leader pod. `registered` is the etcd lease-bound registration key;/// everything else is process memory and dies with the process.#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]@@ -73,6 +88,10 @@ pub struct Pod {/// Partitions warmed by this process incarnation (production:/// `warmed_partitions` on the pod handle).pub warmed: BTreeMap<Partition, WarmState>,+ /// Warms mid-flight under `EpochFenced` — one step of+ /// `warm_partition` done, the other not (empty under `Current`,+ /// whose warm has no broker step to separate from the read).+ pub pending_warm: BTreeMap<Partition, PendingWarm>,/// Write-fenced partitions (production: `InflightTracker` fences +/// the pod handle's `fenced_partitions`).pub fenced: BTreeSet<Partition>,diff --git a/rust/personhog-stateright/tests/model_tests.rs b/rust/personhog-stateright/tests/model_tests.rsindex fba99020de9d..030e5a6765f9 100644--- a/rust/personhog-stateright/tests/model_tests.rs+++ b/rust/personhog-stateright/tests/model_tests.rs@@ -10,6 +10,11 @@//! | 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@@ -22,7 +27,7 @@use std::time::Instant;-use personhog_stateright::model::{HandoffModel, Variant};+use personhog_stateright::model::{HandoffModel, Variant, WarmOrder};use stateright::{Checker, Model};/// Every checker explores in parallel: stateright defaults to a single@@ -44,6 +49,7 @@ fn base() -> HandoffModel {late_routers: 0,partitions: 1,variant: Variant::Current,+ warm_order: WarmOrder::FenceFirst,writes: 2,reads: 1,crashes: 0,@@ -128,9 +134,16 @@ fn current_protocol_double_zombie_loses_acked_writes() {);}-/// Epoch fencing closes the residual: warming bumps the broker's-/// producer epoch, so the zombie's produce is rejected before any ack.-/// All safety properties hold again, zombie window and all.+/// 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 on the read path rejects them. Closing that needs a+/// lease-validity check on read admission — see the residual ledger in+/// `personhog-coordination/README.md`.#[test]fn epoch_fenced_double_zombie_is_safe() {let checker = model(Variant::EpochFenced, 2, 1)@@ -152,6 +165,58 @@ fn epoch_fenced_double_zombie_is_safe() {);}+/// The rejected warm ordering — changelog read before fence acquisition+/// — loses acked writes: a still-unfenced zombie commits a write after+/// the new owner's cutoff is captured but before the epoch bump exists+/// to reject it. This is the machine-checked reason `warm_partition`+/// acquires the fence before the warm read; the FenceFirst tests above+/// prove the shipped ordering closes the gap under the same budget.+#[test]+fn epoch_fenced_read_first_ordering_loses_acked_writes() {+ let checker = HandoffModel {+ warm_order: WarmOrder::ReadFirst,+ ..model(Variant::EpochFenced, 2, 1)+ }+ .checker()+ .threads(parallelism())+ .spawn_bfs()+ .join();+ assert!(+ checker.discovery("no_lost_acked_write").is_some(),+ "read-before-fence must produce an acked-write-loss counterexample"+ );+}++/// A cancelled handoff whose target already acquired the fence leaves+/// the resuming old owner's producer epoch-stale; `resume_partition`+/// re-acquires before re-admitting writes, or the partition wedges with+/// every write rejected as fenced. The stability property requires+/// `write_capable` (not merely warmed + unfenced), so a model without+/// the resume re-acquisition fails liveness here. The pod churn+/// (expire, rejoin, expire mid-warm) is what manufactures a registered+/// old owner whose handoff target dies after the fence bump — two+/// partitions because a move handoff from a registered old owner only+/// arises from imbalance, and the minimum router/workload budgets keep+/// the churn-heavy space tractable (no zombie half is needed here).+#[test]+fn epoch_fenced_resume_after_cancelled_handoff_stays_live() {+ HandoffModel {+ routers: 1,+ partitions: 2,+ variant: Variant::EpochFenced,+ writes: 1,+ reads: 0,+ crashes: 2,+ rejoins: 1,+ ..base()+ }+ .checker()+ .threads(parallelism())+ .spawn_bfs()+ .join()+ .assert_properties();+}+/// Two partitions bring the cross-partition coordinator logic into/// play: rebalancing defers while any handoff is in flight, so one/// partition's failure handling gates the other's reassignment. All@@ -679,3 +744,31 @@ fn rejoin_two_partitions_without_cancellation() {.join().assert_properties();}++/// Fencing under handoff cancellation: every safety and liveness+/// property must hold when the cancellation budget and the fencing+/// variant are combined, a pairing no other verdict test covers.+///+/// This is breadth, not a pin: it passes with or without the resume's+/// epoch re-acquisition, because the interleaving that strands a+/// resuming owner on a stale epoch needs the cancelled target to have+/// warmed first, which this configuration does not force.+/// `epoch_fenced_resume_after_cancelled_handoff_stays_live` is the+/// red-checked pin for that fix.+#[test]+fn epoch_fenced_under_cancellation_is_safe_and_live() {+ HandoffModel {+ routers: 1,+ partitions: 2,+ variant: Variant::EpochFenced,+ writes: 1,+ reads: 0,+ cancels: 1,+ ..base()+ }+ .checker()+ .threads(parallelism())+ .spawn_bfs()+ .join()+ .assert_properties();+}diff --git a/rust/personhog-test-harness/README.md b/rust/personhog-test-harness/README.mdindex c2cc7c2f994a..1bd2f17c2e23 100644--- a/rust/personhog-test-harness/README.md+++ b/rust/personhog-test-harness/README.md@@ -116,13 +116,13 @@ Four real leader-path bugs surfaced under specific gate configurations; two areThey are documented here so red or noisy runs read as signal, not harness flakiness.**Cache eviction under writer lag loses acked writes — FIXED, now a CI regression gate.**-`--cache-capacity` sets the leader cache size in entries; below `--persons` it forces eviction of dirty entries whose writes the writer has not yet flushed.+`--cache-capacity` sets the leader cache budget in bytes (entries are weighed by serialized size); set it below the seeded pool's footprint to force eviction of dirty entries whose writes the writer has not yet flushed.Every operation used to reload the stale Postgres row on the next miss, later merges built on the stale base, and acked writes disappeared (this exact configuration once produced 4,886 violations).The leader now marks every acked produce in a dirty index and recovers evicted marked persons from their changelog record instead of trusting PG; the scenario runs in CI (with a writer pause to guarantee the lag) and must stay green:```bashtarget/debug/personhog-test-harness gate --leaders 3 --partitions 8 --persons 50 \- --cache-capacity 10 --duration 15s --writer-pause-after 3s --writer-pause-duration 8s+ --cache-capacity 4096 --duration 15s --writer-pause-after 3s --writer-pause-duration 8s```**Graceful shutdown black-holes the leader's partitions — FIXED via lifecycle shutdown phases.**diff --git a/rust/personhog-test-harness/src/cli.rs b/rust/personhog-test-harness/src/cli.rsindex eb734ee9252b..1bb351f1e534 100644--- a/rust/personhog-test-harness/src/cli.rs+++ b/rust/personhog-test-harness/src/cli.rs@@ -124,6 +124,12 @@ 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.+ #[arg(long = "leader-env", value_parser = parse_env_pair)]+ pub leader_env: Vec<(String, String)>,+/// Target an already-running stack at this router URL instead of/// spawning one. When unset, the harness spawns its own isolated stack/// (replica, leaders, leader-mode router, writer) against the@@ -256,9 +262,10 @@ pub struct GateArgs {#[arg(long, default_value_t = false)]pub kill_handoff_target: bool,- /// Leader cache capacity in entries. Set below --persons to put the- /// cache under eviction pressure.- #[arg(long, default_value_t = 100_000)]+ /// Leader per-partition cache budget in bytes (CACHE_MEMORY_CAPACITY_BYTES).+ /// Set below the seeded pool's footprint to put the cache under+ /// eviction pressure. Default matches the dev deployment (16 MiB).+ #[arg(long, default_value_t = 16_777_216)]pub cache_capacity: usize,/// Recovery consumer pool size for spawned leaders@@ -432,3 +439,38 @@ pub struct TrafficArgs {#[arg(long, env = "CHAOS_ETCD_NAMESPACE")]pub chaos_etcd_namespace: Option<String>,}++/// Environment the stack assigns per leader; overriding any of these+/// would break pod identity or point a spawned leader at the wrong+/// topic or table, and the resulting run would look like a real result.+const RESERVED_LEADER_ENV: &[&str] = &[+ "POD_NAME",+ "GRPC_ADDRESS",+ "METRICS_PORT",+ "ETCD_ENDPOINTS",+ "ETCD_PREFIX",+ "KAFKA_PERSON_STATE_TOPIC",+ "FALLBACK_TABLE",+ "FALLBACK_DATABASE_URL",+ "WRITER_CONSUMER_GROUP",+ // Derived fencing timeouts scale off the lease TTL, so overriding it+ // here would silently contradict --leader-lease-ttl and can leave a+ // fenced leader unable to start.+ "LEASE_TTL",+];++/// Parse a `KEY=VALUE` pair for environment passthrough arguments.+fn parse_env_pair(s: &str) -> Result<(String, String), String> {+ let (key, value) = s+ .split_once('=')+ .ok_or_else(|| format!("expected KEY=VALUE, got {s:?}"))?;+ if key.is_empty() {+ return Err(format!("empty environment variable name in {s:?}"));+ }+ if RESERVED_LEADER_ENV.contains(&key) {+ return Err(format!(+ "{key} is assigned per leader by the harness and cannot be overridden"+ ));+ }+ Ok((key.to_string(), value.to_string()))+}diff --git a/rust/personhog-test-harness/src/scenarios/gate.rs b/rust/personhog-test-harness/src/scenarios/gate.rsindex f39c99bd3f92..93dd4d3456d7 100644--- a/rust/personhog-test-harness/src/scenarios/gate.rs+++ b/rust/personhog-test-harness/src/scenarios/gate.rs@@ -130,6 +130,9 @@ pub async fn run(args: GateArgs) -> Result<()> {if args.external_router_url.is_some() && (!chaos.is_empty() || args.kill_handoff_target) {bail!("chaos flags require a spawned stack; they cannot target --external-router-url");}+ if args.external_router_url.is_some() && !args.leader_env.is_empty() {+ bail!("--leader-env requires a spawned stack; it cannot target --external-router-url");+ }if args.create_via_identity&& args.external_router_url.is_some()&& args.external_identity_url.is_none()@@ -171,6 +174,7 @@ pub async fn run(args: GateArgs) -> Result<()> {writer_flush_interval_ms: 1000,pg_target_table: args.pg_target_table.clone(),cache_memory_capacity: args.cache_capacity,+ extra_leader_env: args.leader_env.clone(),recovery_pool_size: args.recovery_pool_size,leader_lease_ttl: args.leader_lease_ttl,spawn_identity: args.create_via_identity,diff --git a/rust/personhog-test-harness/src/stack/mod.rs b/rust/personhog-test-harness/src/stack/mod.rsindex 480d05de62a0..b54cb8f35ff9 100644--- a/rust/personhog-test-harness/src/stack/mod.rs+++ b/rust/personhog-test-harness/src/stack/mod.rs@@ -52,9 +52,13 @@ pub struct StackConfig {pub writer_flush_interval_ms: u64,/// The table the writer upserts into.pub pg_target_table: String,- /// Leader in-memory cache capacity (entries). Lower it below the seeded- /// person count to put the cache under eviction pressure.+ /// Leader per-partition cache budget in bytes (entries are weighed+ /// by serialized size). Lower it below the seeded pool's footprint+ /// to put the cache under eviction pressure.pub cache_memory_capacity: usize,+ /// Extra environment for spawned leaders, appended after the+ /// standard set (so it can override any of it).+ pub extra_leader_env: Vec<(String, String)>,pub recovery_pool_size: usize,/// etcd lease TTL for leaders, in seconds. Bounds how long a crashed/// (unrevoked) leader stays the registered owner.@@ -279,7 +283,7 @@ impl Stack {// Heartbeats must land well inside the lease window or a healthy// pod's lease expires between renewals.let heartbeat_secs = (self.config.leader_lease_ttl / 3).max(1);- let proc = ServiceProcess::spawn(+ let proc = ServiceProcess::spawn_with_extra(&format!("leader-{index}"),&self.config.bin_dir.join("personhog-leader"),&[@@ -288,7 +292,7 @@ impl Stack {("LEASE_TTL", self.config.leader_lease_ttl.to_string()),("HEARTBEAT_INTERVAL_SECS", heartbeat_secs.to_string()),(- "CACHE_MEMORY_CAPACITY",+ "CACHE_MEMORY_CAPACITY_BYTES",self.config.cache_memory_capacity.to_string(),),(@@ -316,6 +320,7 @@ impl Stack {(LEADER_METRICS_BASE_PORT + index as u16).to_string(),),],+ &self.config.extra_leader_env,&self.log_dir,)?;diff --git a/rust/personhog-test-harness/src/stack/process.rs b/rust/personhog-test-harness/src/stack/process.rsindex 0c0412067c9f..4da2c62ca134 100644--- a/rust/personhog-test-harness/src/stack/process.rs+++ b/rust/personhog-test-harness/src/stack/process.rs@@ -69,6 +69,18 @@ impl ServiceProcess {binary: &Path,envs: &[(&str, String)],log_dir: &Path,+ ) -> Result<Self> {+ Self::spawn_with_extra(name, binary, envs, &[], log_dir)+ }++ /// Like `spawn`, with caller-supplied environment appended after the+ /// standard set so it can override any of it.+ pub fn spawn_with_extra(+ name: &str,+ binary: &Path,+ envs: &[(&str, String)],+ extra: &[(String, String)],+ log_dir: &Path,) -> Result<Self> {let spec = ServiceSpec {name: name.to_string(),@@ -76,6 +88,7 @@ impl ServiceProcess {envs: envs.iter().map(|(k, v)| (k.to_string(), v.clone()))+ .chain(extra.iter().cloned()).collect(),log_path: log_dir.join(format!("{name}.log")),};diff --git a/rust/personhog-writer/src/kafka.rs b/rust/personhog-writer/src/kafka.rsindex 9adca5b80e7f..9f53957db985 100644--- a/rust/personhog-writer/src/kafka.rs+++ b/rust/personhog-writer/src/kafka.rs@@ -28,6 +28,16 @@ impl PersonConsumer {.set("auto.offset.reset", offset_reset).set("enable.auto.commit", "false").set("enable.auto.offset.store", "false")+ // Only committed transactions: with the leader's epoch fencing+ // on, aborted windows and zombie leftovers must never reach+ // Postgres. Identical behavior on a non-transactional topic.+ // The price is a liveness coupling: this consumer cannot+ // advance past an open window, so a leader that stops+ // mid-window holds the partition at its last stable offset+ // until the broker abandons the transaction — bounded by the+ // leader's derived broker transaction timeout (about 6s at+ // the production lease).+ .set("isolation.level", "read_committed")// Cooperative-sticky: during scale events, only partitions that need// to move are revoked. Non-moving partitions keep being consumed..set("partition.assignment.strategy", "cooperative-sticky");