Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(personhog): chunk plan application to the etcd txn budget (#89036)

José Sequeirae17e4db89274
diff --git a/rust/common/assignment-coordination/src/store.rs b/rust/common/assignment-coordination/src/store.rs
index 575c8611a90d..9b1e4a33f77f 100644
--- a/rust/common/assignment-coordination/src/store.rs
+++ b/rust/common/assignment-coordination/src/store.rs
@@ -214,6 +214,24 @@ impl EtcdStore {
.collect())
}
+ /// Like `list_keys`, with each key's mod_revision — for callers that
+ /// guard a later write on the key being unchanged since this look.
+ pub async fn list_keys_with_mod_revisions(&self, prefix: &str) -> Result<Vec<(String, i64)>> {
+ let _t = OpTimer::new("list_keys_with_mod_revisions");
+ let options = GetOptions::new().with_prefix().with_keys_only();
+ let resp = self.client.clone().get(prefix, Some(options)).await?;
+ record_payload_bytes("list_keys_with_mod_revisions", kvs_bytes(resp.kvs()));
+ Ok(resp
+ .kvs()
+ .iter()
+ .filter_map(|kv| {
+ kv.key_str()
+ .ok()
+ .map(|k| (k.to_string(), kv.mod_revision()))
+ })
+ .collect())
+ }
+
/// Like `list`, but also returns the etcd store revision the snapshot
/// was taken at. Pair with `watch_from(prefix, revision + 1)` for a
/// gap-free snapshot-then-watch handshake: every event at or before
diff --git a/rust/personhog-coordination/README.md b/rust/personhog-coordination/README.md
index dc013c817dac..d5160a097992 100644
--- a/rust/personhog-coordination/README.md
+++ b/rust/personhog-coordination/README.md
@@ -87,6 +87,7 @@ Several failure modes are handled explicitly:
- **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.
+- **Chunked plan application**: A plan is applied in transactions sized to etcd's `--max-txn-ops` (`ETCD_MAX_TXN_OPS`, default 128); an unchunked over-budget plan would be rejected outright and retried forever. Atomicity is per partition — each unit keeps its guards and writes in one transaction — so a conflicted unit stands down alone and a partially applied plan is placement drift the next replan heals. Stateright explores partial application (`chunked_plans`).
- **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.
- **Participant stall watchdog**: A router's registration is lease-backed, and the lease keepalive is its own task — so a router whose handoff watch loop has stalled would stay registered (counted in freeze quorums) while never acking. The watch loop stamps a progress marker from a ticker arm inside its own select; a watchdog task fails the run when the stamp goes stale (`ROUTER_PARTICIPANT_STALL_SECS`, default 60 s), deregistering the router on the way down so quorums stop counting it and the process supervisor restarts a healthy participant. Pods deliberately get no such watchdog: their converge loop legitimately blocks for warm-duration, and a pod that stops acking is routed *around* by the phase deadline and replacement instead of being restarted mid-warm.
- **Level-triggered reconciliation everywhere**: Watches are the latency path; every participant also has a truth path that re-derives its state from a fresh snapshot. The coordinator's tick re-evaluates handoffs; the router's reconcile pass (an arm of its watch loop, `ROUTER_RECONCILE_SECS`, default 5 s) re-asserts stashes and freeze acks, converges its table to the assignment authority, and drains any stash whose partition has no handoff to the assignment owner — which heals a missed Complete, a silently dead watch stream, or an out-of-protocol raw deletion; the pod's tick re-converges every involved partition, including locally-held state the durable world no longer mentions. Every reconcile action is idempotent against the event path. Reconcile failures are tolerated, not fatal: a failed pass leaves the participant exactly as stale as the previous tick (the watch-driven steady state), so brief etcd blips never restart the fleet — sustained outage self-fences through the lease keepalive instead. A consecutive-failure budget (`ROUTER_RECONCILE_FAILURE_BUDGET`, default 12 ticks; same default on pods) bounds the partial mode where snapshot reads fail while the lease stays healthy, and `personhog_coordination_reconcile_failures_total{component}` counts every failure.
@@ -124,6 +125,8 @@ Several failure modes are handled explicitly:
**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.
+**A late plan chunk can install an owner that just deregistered.** Chunked replacement units (successors, reaffirms) are guarded on their records, not on pod liveness, so a unit applied after its plan's snapshot can complete toward a pod that died in between — routers cut over and fail closed until the next replan moves the partition; nothing is acked and lost. The window predates chunking (plan-to-apply was already seconds wide) and grows with plan size under it. The stateright `chunked_plans` mode covers chunked creations; extending it to replacement units is open.
+
**Mid-stream watch reconnects don't replay missed events — bounded by reconciliation**: The snapshot-to-watch-attach gap is closed (watches are revision-anchored to the snapshot that seeded them), but if an *established* etcd watch stream drops and the underlying client reconnects, events that fired during the disconnect are not replayed. Every participant now bounds the resulting staleness with its level-triggered truth path — the coordinator's tick (which also wakes the planner unconditionally), the router's reconcile pass, and the pod's converge-all tick — so a missed event costs at most one reconcile interval, not correctness.
## Modules
diff --git a/rust/personhog-coordination/src/coordinator.rs b/rust/personhog-coordination/src/coordinator.rs
index 2e23cfb36b03..3a463d2acad8 100644
--- a/rust/personhog-coordination/src/coordinator.rs
+++ b/rust/personhog-coordination/src/coordinator.rs
@@ -85,6 +85,11 @@ pub struct CoordinatorConfig {
/// could never complete: cancel, replan, warm from zero, forever.
/// Zero disables the Warming budget entirely.
pub warming_deadline: Duration,
+ /// The plan-transaction budget, mirroring the server's
+ /// `--max-txn-ops`: plans are applied in chunks that fit it. Must
+ /// not exceed the server's value — a larger transaction is refused
+ /// outright, and the planner would retry it forever.
+ pub max_txn_ops: usize,
}
impl Default for CoordinatorConfig {
@@ -108,6 +113,9 @@ impl Default for CoordinatorConfig {
reconcile_interval: Duration::from_secs(5),
handoff_deadline: Duration::from_secs(120),
warming_deadline: Duration::from_secs(1800),
+ // etcd's own default; deployments that raise the server
+ // flag raise this with it from the same chart value.
+ max_txn_ops: 128,
}
}
}
@@ -658,6 +666,7 @@ impl Coordinator {
let k8s_awareness = self.k8s_awareness.clone();
let debounce_interval = self.config.rebalance_debounce_interval;
let deadlines = self.config.phase_deadlines();
+ let max_txn_ops = self.config.max_txn_ops;
let replan = Arc::clone(&replan);
let token = cancel.child_token();
tasks.spawn(async move {
@@ -667,6 +676,7 @@ impl Coordinator {
k8s_awareness,
debounce_interval,
deadlines,
+ max_txn_ops,
replan,
token,
pods_stream,
@@ -680,6 +690,7 @@ impl Coordinator {
let strategy = Arc::clone(&self.strategy);
let k8s_awareness = self.k8s_awareness.clone();
let deadlines = self.config.phase_deadlines();
+ let max_txn_ops = self.config.max_txn_ops;
let token = cancel.child_token();
tasks.spawn(async move {
Self::watch_handoffs_loop(
@@ -687,6 +698,7 @@ impl Coordinator {
strategy,
k8s_awareness,
deadlines,
+ max_txn_ops,
token,
handoffs_stream,
)
@@ -763,6 +775,7 @@ impl Coordinator {
k8s_awareness: Option<Arc<K8sAwareness>>,
debounce_interval: Duration,
deadlines: PhaseDeadlines,
+ max_txn_ops: usize,
replan: Arc<Notify>,
cancel: CancellationToken,
mut stream: WatchStream,
@@ -798,6 +811,7 @@ impl Coordinator {
strategy.as_ref(),
k8s_awareness.as_deref(),
deadlines,
+ max_txn_ops,
)
.await?;
}
@@ -817,6 +831,7 @@ impl Coordinator {
strategy: Arc<dyn AssignmentStrategy>,
k8s_awareness: Option<Arc<K8sAwareness>>,
deadlines: PhaseDeadlines,
+ max_txn_ops: usize,
cancel: CancellationToken,
mut stream: WatchStream,
) -> Result<()> {
@@ -857,6 +872,7 @@ impl Coordinator {
strategy.as_ref(),
k8s_awareness.as_deref(),
deadlines,
+ max_txn_ops,
)
.await?;
}
@@ -945,9 +961,11 @@ impl Coordinator {
tokio::select! {
_ = cancel.cancelled() => return Ok(()),
_ = tick.tick() => {
- // INVARIANT: listed before the handoffs — a
- // membership written after this read is not a
- // candidate, so the sweep cannot collect a record a
+ // INVARIANT: listed before the handoffs, and each
+ // delete is guarded on the mod_revision read here —
+ // a membership written (or re-put by a plan chunk)
+ // after this read is not a candidate and fails the
+ // guard, so the sweep cannot collect a record a
// newer handoff refers to.
let quorum_candidates = store.list_freeze_quorum_ids().await;
let handoffs = store.list_handoffs().await?;
@@ -996,16 +1014,15 @@ impl Coordinator {
}
}
- /// Delete the freeze-quorum records no live handoff refers to.
- /// Housekeeping without a transaction: a record left behind costs
- /// kilobytes until the next tick, and one deleted in error only
- /// makes its handoff fall back to requiring every live router —
- /// neither can advance a handoff early. A wrong delete surfaces in
- /// `unresolved_freeze_quorums_total` only from a process that has
- /// to read; a cached coordinator neutralizes it silently.
+ /// Delete the freeze-quorum records no live handoff refers to. Each
+ /// delete is guarded on the record's listed mod_revision: a chunked
+ /// plan re-puts its record with every chunk, so a chunk landing
+ /// after the sweep's read bumps the revision and the delete stands
+ /// down — and a chunk landing after a delete re-creates the record,
+ /// so a referencing handoff can never be left dangling.
async fn collect_stale_freeze_quorums(
store: &PersonhogStore,
- candidates: Result<Vec<String>>,
+ candidates: Result<Vec<(String, i64)>>,
handoffs: &[HandoffState],
) {
let candidates = match candidates {
@@ -1026,12 +1043,15 @@ impl Coordinator {
.iter()
.filter_map(|h| h.freeze_quorum_ref.as_deref())
.collect();
- for id in candidates
+ for (id, mod_revision) in candidates
.iter()
- .filter(|id| !referenced.contains(id.as_str()))
+ .filter(|(id, _)| !referenced.contains(id.as_str()))
{
- match store.delete_freeze_quorum(id).await {
- Ok(()) => {
+ match store
+ .delete_freeze_quorum_if_unchanged(id, *mod_revision)
+ .await
+ {
+ Ok(true) => {
// The cheap half of the sweep's observability: a
// rate here that outpaces plan creation is the shape
// a sweep collecting records it should have spared
@@ -1039,6 +1059,12 @@ impl Coordinator {
counter!("personhog_coordination_freeze_quorums_collected_total").increment(1);
tracing::debug!(quorum_id = %id, "collected unreferenced freeze quorum");
}
+ Ok(false) => {
+ tracing::debug!(
+ quorum_id = %id,
+ "freeze quorum changed since the sweep's read (re-put or already collected); skipped"
+ );
+ }
Err(e) => {
// Counted, not only logged: the router runs at INFO,
// so a sweep whose every delete fails is otherwise
@@ -1242,6 +1268,7 @@ impl Coordinator {
self.strategy.as_ref(),
self.k8s_awareness.as_deref(),
self.config.phase_deadlines(),
+ self.config.max_txn_ops,
)
.await
}
@@ -1251,6 +1278,7 @@ impl Coordinator {
strategy: &dyn AssignmentStrategy,
k8s_awareness: Option<&K8sAwareness>,
deadlines: PhaseDeadlines,
+ max_txn_ops: usize,
) -> Result<()> {
let pods = store.list_pods().await?;
let total_partitions = match store.get_total_partitions().await {
@@ -1376,14 +1404,15 @@ impl Coordinator {
let mut creations: Vec<HandoffState> = Vec::new();
let mut replacements: Vec<HandoffReplacement> = Vec::new();
let mut fallback_deletes: Vec<FallbackDelete> = Vec::new();
- let mut replaced_dispositions: Vec<&'static str> = Vec::new();
- // Held until the plan transaction lands; see `Cancellation`.
- let mut planned_cancellations: Vec<Cancellation> = Vec::new();
+ let mut replaced_dispositions: Vec<(u32, &'static str)> = Vec::new();
+ // Held until the plan transactions land; see `Cancellation`.
+ let mut planned_cancellations: Vec<(u32, Cancellation)> = Vec::new();
for handoff in handoff_objects {
match cancelled_by_partition.remove(&handoff.partition) {
Some((predecessor, mod_revision)) => {
- planned_cancellations.push(
+ planned_cancellations.push((
+ handoff.partition,
Self::describe_cancellation(
store,
&routers,
@@ -1392,12 +1421,12 @@ impl Coordinator {
"successor",
)
.await,
- );
+ ));
+ replaced_dispositions.push((handoff.partition, "successor"));
replacements.push(HandoffReplacement {
handoff,
expected_mod_revision: mod_revision,
});
- replaced_dispositions.push("successor");
}
None => creations.push(handoff),
}
@@ -1408,7 +1437,8 @@ impl Coordinator {
.filter(|owner| registered.contains(owner.as_str()));
match owner {
Some(owner) => {
- planned_cancellations.push(
+ planned_cancellations.push((
+ predecessor.partition,
Self::describe_cancellation(
store,
&routers,
@@ -1417,7 +1447,7 @@ impl Coordinator {
"reaffirm",
)
.await,
- );
+ ));
replacements.push(HandoffReplacement {
handoff: HandoffState {
partition: predecessor.partition,
@@ -1441,7 +1471,7 @@ impl Coordinator {
},
expected_mod_revision: mod_revision,
});
- replaced_dispositions.push("reaffirm");
+ replaced_dispositions.push((predecessor.partition, "reaffirm"));
}
None => {
let cancellation = Self::describe_cancellation(
@@ -1461,19 +1491,8 @@ impl Coordinator {
}
}
- let moves = creations
- .iter()
- .chain(replacements.iter().map(|r| &r.handoff))
- .filter(|h| h.phase == HandoffPhase::Freezing && h.old_owner.is_some())
- .count();
- let freezing_total = creations.len()
- + replacements
- .iter()
- .filter(|r| r.handoff.phase == HandoffPhase::Freezing)
- .count();
tracing::info!(
- reassignments = moves,
- fresh = freezing_total - moves,
+ creations = creations.len(),
replaced = replacements.len(),
"creating handoffs"
);
@@ -1502,8 +1521,10 @@ impl Coordinator {
.iter()
.chain(replacements.iter().map(|r| &r.handoff))
.any(|handoff| handoff.freeze_quorum_ref.is_some());
- if (!creations.is_empty() || !replacements.is_empty())
- && !store
+ let application = if creations.is_empty() && replacements.is_empty() {
+ crate::store::PlanApplication::default()
+ } else {
+ store
.apply_plan(
&[],
&creations,
@@ -1516,20 +1537,26 @@ impl Coordinator {
// for the next sweep to delete, during the mass
// cancellation when etcd is least well.
references_quorum.then_some((&freeze_quorum_id, &freeze_quorum)),
+ max_txn_ops,
)
.await?
- {
+ };
+ if !application.conflicted.is_empty() {
// A concurrent invocation (the empty-set re-trigger racing a
- // pod event, or a failing-over coordinator) created a handoff
- // first. Its plan acted on fresher state than ours; whatever
- // this plan wanted beyond it is replanned by the next pod
- // event or the final sweep.
- tracing::info!("concurrent plan won handoff creation; standing down");
- return Ok(());
+ // pod event, or a failing-over coordinator) got to these
+ // partitions first. Its plan acted on fresher state than
+ // ours; whatever this plan wanted beyond it is replanned by
+ // the next pod event or the final sweep.
+ tracing::info!(
+ conflicted = application.conflicted.len(),
+ "concurrent plans won some partitions; standing those down"
+ );
}
+ let applied: HashSet<u32> = application.applied.iter().copied().collect();
for handoff in creations
.iter()
.chain(replacements.iter().map(|r| &r.handoff))
+ .filter(|h| applied.contains(&h.partition))
{
tracing::info!(
partition = handoff.partition,
@@ -1540,15 +1567,19 @@ impl Coordinator {
"handoff created"
);
}
- for cancellation in &planned_cancellations {
- cancellation.record();
+ for (partition, cancellation) in &planned_cancellations {
+ if applied.contains(partition) {
+ cancellation.record();
+ }
}
- for disposition in &replaced_dispositions {
- counter!(
- "personhog_coordination_handoffs_replaced_total",
- "disposition" => *disposition,
- )
- .increment(1);
+ for (partition, disposition) in &replaced_dispositions {
+ if applied.contains(partition) {
+ counter!(
+ "personhog_coordination_handoffs_replaced_total",
+ "disposition" => *disposition,
+ )
+ .increment(1);
+ }
}
// The fallback deletes are per-partition guarded transactions
@@ -1573,10 +1604,21 @@ impl Coordinator {
}
}
+ let (mut moves, mut fresh) = (0u64, 0u64);
+ for handoff in creations
+ .iter()
+ .chain(replacements.iter().map(|r| &r.handoff))
+ .filter(|h| h.phase == HandoffPhase::Freezing && applied.contains(&h.partition))
+ {
+ match handoff.old_owner {
+ Some(_) => moves += 1,
+ None => fresh += 1,
+ }
+ }
counter!("personhog_coordination_handoffs_created_total", "kind" => "move")
- .increment(moves as u64);
+ .increment(moves);
counter!("personhog_coordination_handoffs_created_total", "kind" => "fresh")
- .increment((freezing_total - moves) as u64);
+ .increment(fresh);
// Nudge advancement for handoffs whose preconditions are already
// satisfied at creation time (no old_owner, dead old_owner, vacuous
@@ -1586,6 +1628,7 @@ impl Coordinator {
for handoff in creations
.iter()
.chain(replacements.iter().map(|r| &r.handoff))
+ .filter(|h| applied.contains(&h.partition))
{
Self::check_phase_advance(store, handoff.partition, AdvanceTrigger::Other).await?;
}
diff --git a/rust/personhog-coordination/src/store.rs b/rust/personhog-coordination/src/store.rs
index eda453731cd9..d4b978f998fa 100644
--- a/rust/personhog-coordination/src/store.rs
+++ b/rust/personhog-coordination/src/store.rs
@@ -84,17 +84,13 @@ impl StoreKey<'_> {
#[derive(Clone)]
pub struct PersonhogStore {
inner: EtcdStore,
- /// Freeze-quorum memberships already read, by record id. Records
- /// are written once and only ever deleted, so an id identifies one
- /// immutable value and caching cannot go stale; a plan's handoffs
- /// share one id, so this turns a few hundred reads per reconcile
- /// pass into one.
- ///
- /// INVARIANT: the cached value keeps `Some` (recorded membership)
- /// distinct from `None` (record absent — requires every live
- /// router). Flattening them would advance a handoff no router had
- /// stopped routing for.
- freeze_quorums: Arc<StdMutex<HashMap<String, Option<Vec<String>>>>>,
+ /// Freeze-quorum memberships already read, by record id. An id
+ /// names one immutable value (a chunked plan re-puts it only
+ /// byte-identically), so a recorded membership cannot go stale; a
+ /// plan's handoffs share one id, so this turns a few hundred reads
+ /// per reconcile pass into one. Absence is never cached — the
+ /// sweep can delete a record a later chunk re-creates.
+ freeze_quorums: Arc<StdMutex<HashMap<String, Vec<String>>>>,
}
/// Counts store calls by the method that made them. The shared etcd
@@ -106,6 +102,98 @@ pub(crate) fn count_call(site: &'static str) {
metrics::counter!("personhog_coordination_store_calls_total", "site" => site).increment(1);
}
+/// How a plan application ended, per partition.
+#[derive(Debug, Default)]
+pub struct PlanApplication {
+ /// Partitions whose disposition landed.
+ pub applied: Vec<u32>,
+ /// Partitions whose guards failed — a record changed between the
+ /// planner's read and the write; the next plan re-reads them.
+ pub conflicted: Vec<u32>,
+ /// Chunks the server refused as too large and that applied per
+ /// unit instead: the configured budget exceeds the server's.
+ pub over_budget_chunks: usize,
+}
+
+/// One partition's slice of a plan: the guards that make its
+/// disposition safe and the ops that apply it. Chunking never splits a
+/// unit, so a partition's disposition stays atomic across any split.
+struct PlanUnit {
+ partition: u32,
+ guards: Vec<UnitGuard>,
+ ops: Vec<UnitOp>,
+ bytes: usize,
+ references_quorum: bool,
+}
+
+enum UnitGuard {
+ /// The key was never created (create_revision 0).
+ Absent(String),
+ /// The key's mod_revision is exactly this.
+ ModRevision(String, i64),
+}
+
+impl UnitGuard {
+ fn key(&self) -> &str {
+ match self {
+ UnitGuard::Absent(key) | UnitGuard::ModRevision(key, _) => key,
+ }
+ }
+}
+
+enum UnitOp {
+ Put(String, Vec<u8>),
+ DeletePrefix(String),
+}
+
+/// Whether etcd refused a transaction for its size — past
+/// `--max-txn-ops` (`ErrGRPCTooManyOps`) or `--max-request-bytes`
+/// (`ErrGRPCRequestTooLarge`). Matched on the message: the gRPC code
+/// is a generic InvalidArgument.
+fn is_txn_too_large(e: &Error) -> bool {
+ matches!(
+ e,
+ Error::Store(assignment_coordination::error::Error::Etcd(
+ etcd_client::Error::GRpcStatus(status)
+ )) if status.message().contains("too many operations")
+ || status.message().contains("request is too large")
+ )
+}
+
+/// Greedy chunk boundaries over per-unit `(guards, ops)` costs: a chunk
+/// takes units while its compare list and its op list both stay within
+/// `budget` — etcd checks the two lists separately against
+/// `--max-txn-ops`. `reserve_ops` holds back room in every chunk for
+/// ops added on top of its units (the freeze-quorum write).
+fn plan_chunk_ranges(
+ costs: &[(usize, usize)],
+ budget: usize,
+ reserve_ops: usize,
+) -> Vec<std::ops::Range<usize>> {
+ let budget = budget.max(1);
+ let mut ranges = Vec::new();
+ let mut start = 0;
+ let (mut guards, mut ops) = (0, 0);
+ for (i, &(g, o)) in costs.iter().enumerate() {
+ let fits = guards + g <= budget && ops + o + reserve_ops <= budget;
+ // A chunk always takes at least one unit, so a budget below a
+ // single unit's cost still makes progress and lets the server
+ // be the judge.
+ if i > start && !fits {
+ ranges.push(start..i);
+ start = i;
+ guards = 0;
+ ops = 0;
+ }
+ guards += g;
+ ops += o;
+ }
+ if start < costs.len() {
+ ranges.push(start..costs.len());
+ }
+ ranges
+}
+
impl PersonhogStore {
pub fn new(inner: EtcdStore) -> Self {
Self {
@@ -591,8 +679,9 @@ impl PersonhogStore {
// ── Transactional operations ────────────────────────────────
/// Atomically write assignments and create handoff states.
- /// Returns whether the transaction applied. Guarded so a plan only
- /// lands if the world it was computed from is still the world:
+ /// Returns whether every disposition applied. Each partition's unit
+ /// is guarded so it only lands if the world it was computed from is
+ /// still the world (an assignment-only unit carries no guard):
///
/// * every handoff key must be absent — concurrent planners (the pod
/// watch racing the handoff watch's re-trigger, or a failing-over
@@ -605,10 +694,6 @@ impl PersonhogStore {
/// passes the absence guard and drains the wrong pod, leaving the
/// real owner unfenced beside the new owner's warm cutoff.
///
- /// All-or-nothing on purpose — a plan is one consistent placement
- /// computation, and the losing caller replans off the winner's writes
- /// rather than applying a half-stale plan.
- ///
/// `replacements` carry cancellations-by-replacement: each swaps the
/// record at its partition's key — guarded on the `mod_revision` the
/// planner read — for the successor (or reaffirm) record, deleting
@@ -620,75 +705,79 @@ impl PersonhogStore {
assignments: &[PartitionAssignment],
handoffs: &[HandoffState],
preconditions: &[AssignmentPrecondition],
+ max_txn_ops: usize,
) -> Result<bool> {
// The handoffs come ready-made, so there is no shared
// membership to write alongside them.
- self.apply_plan(assignments, handoffs, &[], preconditions, None)
- .await
+ let application = self
+ .apply_plan(assignments, handoffs, &[], preconditions, None, max_txn_ops)
+ .await?;
+ Ok(application.conflicted.is_empty())
}
- /// The full plan-application transaction: creations (absent-guarded)
- /// plus cancellations-by-replacement (mod_revision-guarded), all or
- /// nothing.
+ /// Apply a plan — creations (absent-guarded) plus
+ /// cancellations-by-replacement (mod_revision-guarded) — in
+ /// transactions sized to `max_txn_ops`, the server's txn budget.
+ ///
+ /// Atomicity is per partition, not per plan: every guard protects
+ /// one partition's disposition, so a partition's guards and writes
+ /// share one transaction, but the plan itself may split. An
+ /// unchunked plan past `--max-txn-ops` is rejected as a hard error,
+ /// and a coordinator retrying it re-earns the same rejection
+ /// forever. A partially applied plan is placement drift the next
+ /// reconcile-tick replan heals.
pub async fn apply_plan(
&self,
assignments: &[PartitionAssignment],
handoffs: &[HandoffState],
replacements: &[HandoffReplacement],
preconditions: &[AssignmentPrecondition],
- // The membership every handoff in this plan refers to, written
- // in the same transaction so no handoff is ever durable with a
- // reference to a record that does not exist.
+ // The membership the plan's handoffs refer to, re-put
+ // (idempotently) in every chunk that references it so no
+ // handoff is ever durable with a dangling reference.
freeze_quorum: Option<(&str, &[String])>,
- ) -> Result<bool> {
+ max_txn_ops: usize,
+ ) -> Result<PlanApplication> {
count_call("apply_plan");
- let mut guards: Vec<Compare> =
- Vec::with_capacity(handoffs.len() + replacements.len() + preconditions.len());
- let mut ops: Vec<TxnOp> =
- Vec::with_capacity(assignments.len() + handoffs.len() + replacements.len() * 4);
- // A plan is one gRPC request and one raft entry, so its size is
- // bounded by etcd's `--max-request-bytes` however small the
- // individual records are. Both terms scale with the fleet, so
- // they are measured rather than assumed — and the measurement
- // counts every key the request carries, guards and deletes
- // included, since a total that omits them reads low against the
- // exact limit it exists to warn about.
- let mut plan_bytes = 0usize;
-
- if let Some((id, members)) = freeze_quorum {
- let key = self.key(StoreKey::FreezeQuorum(id));
- let value = serde_json::to_vec(members)?;
- plan_bytes += key.len() + value.len();
- ops.push(TxnOp::put(key, value, None));
+ let mut units: HashMap<u32, PlanUnit> = HashMap::new();
+ fn unit(units: &mut HashMap<u32, PlanUnit>, partition: u32) -> &mut PlanUnit {
+ units.entry(partition).or_insert_with(|| PlanUnit {
+ partition,
+ guards: Vec::new(),
+ ops: Vec::new(),
+ bytes: 0,
+ references_quorum: false,
+ })
}
+
for a in assignments {
let key = self.key(StoreKey::Assignment(a.partition));
let value = serde_json::to_vec(a)?;
- plan_bytes += key.len() + value.len();
- ops.push(TxnOp::put(key, value, None));
+ let u = unit(&mut units, a.partition);
+ u.bytes += key.len() + value.len();
+ u.ops.push(UnitOp::Put(key, value));
}
for h in handoffs {
let key = self.key(StoreKey::Handoff(h.partition));
let value = serde_json::to_vec(h)?;
- plan_bytes += key.len() + value.len();
+ let u = unit(&mut units, h.partition);
+ u.bytes += key.len() + value.len();
// A key that was never created has create_revision 0 — the
// canonical etcd existence guard.
- plan_bytes += key.len();
- guards.push(Compare::create_revision(key.clone(), CompareOp::Equal, 0));
- ops.push(TxnOp::put(key, value, None));
+ u.bytes += key.len();
+ u.guards.push(UnitGuard::Absent(key.clone()));
+ u.ops.push(UnitOp::Put(key, value));
+ u.references_quorum |= h.freeze_quorum_ref.is_some();
}
- let prefix_delete = || Some(DeleteOptions::new().with_prefix());
for r in replacements {
let partition = r.handoff.partition;
let key = self.key(StoreKey::Handoff(partition));
let value = serde_json::to_vec(&r.handoff)?;
- plan_bytes += key.len() + value.len();
- plan_bytes += key.len();
- guards.push(Compare::mod_revision(
- key.clone(),
- CompareOp::Equal,
- r.expected_mod_revision,
- ));
+ let u = unit(&mut units, partition);
+ u.bytes += key.len() + value.len();
+ u.bytes += key.len();
+ u.guards
+ .push(UnitGuard::ModRevision(key.clone(), r.expected_mod_revision));
for acks in [
self.key(StoreKey::FreezeAcksForPartition(partition)),
self.key(StoreKey::DrainedAcksForPartition(partition)),
@@ -696,39 +785,147 @@ impl PersonhogStore {
] {
// A prefix delete carries `range_end` as well as the
// key, and they are the same length.
- plan_bytes += acks.len() * 2;
- ops.push(TxnOp::delete(acks, prefix_delete()));
+ u.bytes += acks.len() * 2;
+ u.ops.push(UnitOp::DeletePrefix(acks));
}
- ops.push(TxnOp::put(key, value, None));
+ u.ops.push(UnitOp::Put(key, value));
+ u.references_quorum |= r.handoff.freeze_quorum_ref.is_some();
}
for precondition in preconditions {
- match precondition {
+ let (partition, guard) = match precondition {
AssignmentPrecondition::UnchangedSince {
partition,
mod_revision,
- } => {
- let key = self.key(StoreKey::Assignment(*partition));
- plan_bytes += key.len();
- guards.push(Compare::mod_revision(key, CompareOp::Equal, *mod_revision));
- }
- AssignmentPrecondition::Absent { partition } => {
- let key = self.key(StoreKey::Assignment(*partition));
- plan_bytes += key.len();
- guards.push(Compare::create_revision(key, CompareOp::Equal, 0));
- }
- }
+ } => (
+ *partition,
+ UnitGuard::ModRevision(
+ self.key(StoreKey::Assignment(*partition)),
+ *mod_revision,
+ ),
+ ),
+ AssignmentPrecondition::Absent { partition } => (
+ *partition,
+ UnitGuard::Absent(self.key(StoreKey::Assignment(*partition))),
+ ),
+ };
+ let u = unit(&mut units, partition);
+ u.bytes += guard.key().len();
+ u.guards.push(guard);
}
- // Both lists count toward the request etcd sizes against
- // `--max-request-bytes`, and each is checked separately against
- // `--max-txn-ops`, so a sum could not be compared to either
- // limit or say which list was close to it.
+ // Partition order, so chunk composition is a function of the
+ // plan alone rather than of map iteration.
+ let mut units: Vec<PlanUnit> = units.into_values().collect();
+ units.sort_by_key(|u| u.partition);
+
+ let quorum = match freeze_quorum {
+ Some((id, members)) => Some((
+ self.key(StoreKey::FreezeQuorum(id)),
+ serde_json::to_vec(members)?,
+ )),
+ None => None,
+ };
+
+ // Totals across chunks, keys and deletes included, so the
+ // series keeps its meaning from the one-transaction era.
+ let plan_bytes: usize = units.iter().map(|u| u.bytes).sum::<usize>()
+ + quorum.as_ref().map_or(0, |(k, v)| k.len() + v.len());
+ let total_guards: usize = units.iter().map(|u| u.guards.len()).sum();
+ let total_ops: usize = units.iter().map(|u| u.ops.len()).sum();
metrics::histogram!("personhog_coordination_plan_bytes").record(plan_bytes as f64);
metrics::histogram!("personhog_coordination_plan_ops", "list" => "guards")
- .record(guards.len() as f64);
+ .record(total_guards as f64);
metrics::histogram!("personhog_coordination_plan_ops", "list" => "ops")
- .record(ops.len() as f64);
+ .record(total_ops as f64);
+
+ let costs: Vec<(usize, usize)> = units
+ .iter()
+ .map(|u| (u.guards.len(), u.ops.len()))
+ .collect();
+ let reserve_ops = usize::from(quorum.is_some());
+ let ranges = plan_chunk_ranges(&costs, max_txn_ops, reserve_ops);
+ metrics::histogram!("personhog_coordination_plan_chunks").record(ranges.len() as f64);
+
+ let mut application = PlanApplication::default();
+ for range in ranges {
+ let chunk = &units[range];
+ match self.apply_units(chunk, &quorum).await {
+ Ok(true) => {
+ application
+ .applied
+ .extend(chunk.iter().map(|u| u.partition));
+ continue;
+ }
+ Ok(false) => {}
+ // The server's effective --max-txn-ops can sit below the
+ // configured budget (values drift, a member not yet
+ // restarted with a raised flag). Degrade to the per-unit
+ // path — under any workable server limit — instead of
+ // handing back a rejection the planner retries forever.
+ Err(e) if chunk.len() > 1 && is_txn_too_large(&e) => {
+ application.over_budget_chunks += 1;
+ metrics::counter!("personhog_coordination_plan_chunk_over_server_budget_total")
+ .increment(1);
+ tracing::warn!(
+ units = chunk.len(),
+ max_txn_ops,
+ error = %e,
+ "plan chunk exceeds the server txn budget; applying per unit"
+ );
+ }
+ Err(e) => return Err(e),
+ }
+ // A failed guard names no key, so retry the chunk one
+ // partition at a time: the concurrent write that broke the
+ // chunk stands down only the units it actually touched.
+ for u in chunk {
+ if self.apply_units(std::slice::from_ref(u), &quorum).await? {
+ application.applied.push(u.partition);
+ } else {
+ metrics::counter!("personhog_coordination_plan_units_conflicted_total")
+ .increment(1);
+ application.conflicted.push(u.partition);
+ }
+ }
+ }
+ Ok(application)
+ }
+ /// One plan chunk as one transaction: the units' guards and ops,
+ /// plus the freeze-quorum write when any unit references it.
+ /// Returns whether the transaction applied.
+ async fn apply_units(
+ &self,
+ chunk: &[PlanUnit],
+ quorum: &Option<(String, Vec<u8>)>,
+ ) -> Result<bool> {
+ let mut guards: Vec<Compare> = Vec::new();
+ let mut ops: Vec<TxnOp> = Vec::new();
+ if let Some((key, value)) = quorum {
+ if chunk.iter().any(|u| u.references_quorum) {
+ ops.push(TxnOp::put(key.clone(), value.clone(), None));
+ }
+ }
+ for u in chunk {
+ for g in &u.guards {
+ guards.push(match g {
+ UnitGuard::Absent(key) => {
+ Compare::create_revision(key.clone(), CompareOp::Equal, 0)
+ }
+ UnitGuard::ModRevision(key, rev) => {
+ Compare::mod_revision(key.clone(), CompareOp::Equal, *rev)
+ }
+ });
+ }
+ for op in &u.ops {
+ ops.push(match op {
+ UnitOp::Put(key, value) => TxnOp::put(key.clone(), value.clone(), None),
+ UnitOp::DeletePrefix(key) => {
+ TxnOp::delete(key.clone(), Some(DeleteOptions::new().with_prefix()))
+ }
+ });
+ }
+ }
let txn = Txn::new().when(guards).and_then(ops);
let resp = self.inner.txn(txn).await?;
Ok(resp.succeeded())
@@ -832,10 +1029,7 @@ impl PersonhogStore {
match &handoff.freeze_quorum_ref {
Some(id) => {
// A hit answers from memory: confirming against etcd
- // would cost the read this cache removes, to observe a
- // case it already neutralizes. A hit that resolved to
- // nothing still counts, so the signal persists while
- // the condition does.
+ // would cost the read this cache removes.
let cached = self
.freeze_quorums
.lock()
@@ -843,38 +1037,38 @@ impl PersonhogStore {
.get(id)
.cloned();
if let Some(members) = cached {
- if members.is_none() {
- crate::util::record_unresolved_freeze_quorum();
- }
- return Ok(members);
+ return Ok(Some(members));
}
let members = self.get_freeze_quorum(id).await?;
- // A miss is cached too: an id that resolves to nothing
- // resolves to nothing forever, and a lost record would
- // otherwise cost a read per frozen partition per pass.
- {
- let mut cache = self
- .freeze_quorums
- .lock()
- .expect("freeze quorum cache lock poisoned");
- // Sized for a rolling deploy (plans in flight, not
- // one). Evicting the oldest — ids lead with
- // milliseconds, so smallest is oldest — keeps the
- // working set.
- if cache.len() >= 32 {
- if let Some(oldest) = cache.keys().min().cloned() {
- cache.remove(&oldest);
+ match &members {
+ Some(recorded) => {
+ let mut cache = self
+ .freeze_quorums
+ .lock()
+ .expect("freeze quorum cache lock poisoned");
+ // Sized for a rolling deploy (plans in flight,
+ // not one). Evicting the oldest — ids lead with
+ // milliseconds, so smallest is oldest — keeps
+ // the working set.
+ if cache.len() >= 32 {
+ if let Some(oldest) = cache.keys().min().cloned() {
+ cache.remove(&oldest);
+ }
}
+ cache.insert(id.clone(), recorded.clone());
+ }
+ // Never cached: a chunked plan's re-puts can
+ // re-create a swept record, so absence is not
+ // permanent — and pinning it would hold every later
+ // resolution on the every-live-router fallback.
+ None => {
+ crate::util::record_unresolved_freeze_quorum();
+ tracing::warn!(
+ partition = handoff.partition,
+ quorum_id = %id,
+ "freeze quorum record is missing; requiring every live router"
+ );
}
- cache.insert(id.clone(), members.clone());
- }
- if members.is_none() {
- crate::util::record_unresolved_freeze_quorum();
- tracing::warn!(
- partition = handoff.partition,
- quorum_id = %id,
- "freeze quorum record is missing; requiring every live router"
- );
}
Ok(members)
}
@@ -882,22 +1076,42 @@ impl PersonhogStore {
}
}
- /// The ids of every membership record currently stored.
- pub async fn list_freeze_quorum_ids(&self) -> Result<Vec<String>> {
+ /// The ids of every membership record currently stored, each with
+ /// its mod_revision for the sweep's guarded delete.
+ pub async fn list_freeze_quorum_ids(&self) -> Result<Vec<(String, i64)>> {
count_call("list_freeze_quorum_ids");
let prefix = self.key(StoreKey::FreezeQuorumsPrefix);
- let keys = self.inner.list_keys(&prefix).await?;
+ let keys = self.inner.list_keys_with_mod_revisions(&prefix).await?;
Ok(keys
.iter()
- .filter_map(|key| key.strip_prefix(prefix.as_str()))
- .map(str::to_string)
+ .filter_map(|(key, rev)| {
+ key.strip_prefix(prefix.as_str())
+ .map(|id| (id.to_string(), *rev))
+ })
.collect())
}
- pub async fn delete_freeze_quorum(&self, id: &str) -> Result<()> {
+ /// Delete a membership record only if unchanged since `mod_revision`.
+ /// A chunked plan re-puts its record with every chunk, so a re-put
+ /// after the sweep's read bumps the revision and the delete loses —
+ /// otherwise the sweep could collect a record a chunk it never saw
+ /// still references.
+ pub async fn delete_freeze_quorum_if_unchanged(
+ &self,
+ id: &str,
+ mod_revision: i64,
+ ) -> Result<bool> {
count_call("delete_freeze_quorum");
let key = self.key(StoreKey::FreezeQuorum(id));
- Ok(self.inner.delete(&key).await?)
+ let txn = Txn::new()
+ .when(vec![Compare::mod_revision(
+ key.clone(),
+ CompareOp::Equal,
+ mod_revision,
+ )])
+ .and_then(vec![TxnOp::delete(key, None)]);
+ let resp = self.inner.txn(txn).await?;
+ Ok(resp.succeeded())
}
// ── Leader election ─────────────────────────────────────────
@@ -1030,3 +1244,71 @@ pub fn extract_partition_from_ack_key(key: &str) -> Option<u32> {
None
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::plan_chunk_ranges;
+
+ /// Every unit lands in exactly one chunk, in order — chunking must
+ /// never drop or reorder a partition's disposition.
+ fn assert_contiguous_cover(ranges: &[std::ops::Range<usize>], len: usize) {
+ let mut next = 0;
+ for r in ranges {
+ assert_eq!(r.start, next, "chunks must be contiguous");
+ assert!(r.end > r.start, "chunks must be non-empty");
+ next = r.end;
+ }
+ assert_eq!(next, len, "chunks must cover every unit");
+ }
+
+ /// The 256→1 collapse shape: 256 creations of (2 guards, 1 op)
+ /// against etcd's default budget. The compare list is what binds —
+ /// an unchunked plan carries 512 compares and is rejected outright.
+ #[test]
+ fn creations_chunk_on_the_compare_list() {
+ let costs = vec![(2, 1); 256];
+ let ranges = plan_chunk_ranges(&costs, 128, 1);
+ assert_contiguous_cover(&ranges, costs.len());
+ for r in &ranges {
+ let guards: usize = costs[r.clone()].iter().map(|c| c.0).sum();
+ let ops: usize = costs[r.clone()].iter().map(|c| c.1).sum();
+ assert!(guards <= 128, "chunk carries {guards} compares");
+ assert!(ops < 128, "chunk carries {ops} ops plus the quorum write");
+ }
+ assert_eq!(
+ ranges.len(),
+ 4,
+ "512 compares over a 128 budget is 4 chunks"
+ );
+ }
+
+ /// The mass-cancellation shape: replacements cost (2 guards, 4 ops),
+ /// so the op list binds, and the reserved quorum write counts
+ /// against every chunk.
+ #[test]
+ fn replacements_chunk_on_the_op_list_with_the_reserve() {
+ let costs = vec![(2, 4); 256];
+ let ranges = plan_chunk_ranges(&costs, 128, 1);
+ assert_contiguous_cover(&ranges, costs.len());
+ for r in &ranges {
+ let ops: usize = costs[r.clone()].iter().map(|c| c.1).sum();
+ assert!(ops < 128, "chunk carries {ops} ops plus the quorum write");
+ }
+ }
+
+ /// A plan that fits stays one transaction — chunking must not tax
+ /// the healthy case with extra round trips.
+ #[test]
+ fn a_fitting_plan_is_one_chunk() {
+ let costs = vec![(2, 1); 60];
+ assert_eq!(plan_chunk_ranges(&costs, 128, 1), vec![0..60]);
+ }
+
+ /// A budget below a single unit's cost still emits that unit alone:
+ /// the packer must make progress and let the server be the judge.
+ #[test]
+ fn an_oversized_unit_is_its_own_chunk() {
+ let costs = vec![(2, 4), (2, 4)];
+ assert_eq!(plan_chunk_ranges(&costs, 1, 0), vec![0..1, 1..2]);
+ }
+}
diff --git a/rust/personhog-coordination/tests/common/mod.rs b/rust/personhog-coordination/tests/common/mod.rs
index 67f5b84ce420..334d3a25c9eb 100644
--- a/rust/personhog-coordination/tests/common/mod.rs
+++ b/rust/personhog-coordination/tests/common/mod.rs
@@ -159,6 +159,7 @@ pub fn start_coordinator_with_deadline(
// explicitly.
handoff_deadline,
warming_deadline: Duration::from_secs(86_400),
+ max_txn_ops: 128,
},
strategy,
None,
diff --git a/rust/personhog-coordination/tests/integration.rs b/rust/personhog-coordination/tests/integration.rs
index 9786fefae333..ff2916d8b4de 100644
--- a/rust/personhog-coordination/tests/integration.rs
+++ b/rust/personhog-coordination/tests/integration.rs
@@ -3121,10 +3121,10 @@ async fn stuck_handoff_defers_only_its_own_partition() {
}
/// Concurrent planners can both read a partition as unpinned and plan it;
-/// handoff creation is guarded create-if-absent so the second plan's txn
-/// fails whole instead of replacing the first handoff and orphaning its
-/// acks. The losing plan's writes — including its innocent assignments —
-/// must not land either: it was computed against a stale snapshot.
+/// handoff creation is guarded create-if-absent so the second plan
+/// cannot replace the first handoff and orphan its acks. Atomicity is
+/// per partition: the losing plan's uncontested writes still land, and
+/// only the contested partition stands down.
#[tokio::test]
async fn conflicting_plan_cannot_replace_an_in_flight_handoff() {
use personhog_coordination::types::{
@@ -3147,7 +3147,7 @@ async fn conflicting_plan_cannot_replace_an_in_flight_handoff() {
new_owner_address: None,
};
assert!(store
- .create_assignments_and_handoffs(&[], std::slice::from_ref(&first), &[])
+ .create_assignments_and_handoffs(&[], std::slice::from_ref(&first), &[], 128)
.await
.unwrap());
@@ -3173,17 +3173,19 @@ async fn conflicting_plan_cannot_replace_an_in_flight_handoff() {
advertise_address: None,
};
assert!(!store
- .create_assignments_and_handoffs(&[stable], &[competing], &[])
+ .create_assignments_and_handoffs(&[stable], &[competing], &[], 128)
.await
.unwrap());
- // The in-flight handoff survives with its original identity, and the
- // losing plan's assignment never landed.
+ // The in-flight handoff survives with its original identity; the
+ // losing plan's uncontested assignment landed on its own.
let handoffs = store.list_handoffs().await.unwrap();
assert_eq!(handoffs.len(), 1);
assert_eq!(handoffs[0].handoff_id, "first");
assert_eq!(handoffs[0].new_owner, "writer-1");
- assert!(store.list_assignments().await.unwrap().is_empty());
+ let assignments = store.list_assignments().await.unwrap();
+ assert_eq!(assignments.len(), 1);
+ assert_eq!(assignments[0].partition, 1);
}
/// The reviewer's stale-plan scenario at the store level: a plan whose
@@ -3221,7 +3223,7 @@ async fn stale_plan_is_rejected_when_the_assignment_moved() {
// The world the stale planner reads: partition 0 owned by A.
assert!(store
- .create_assignments_and_handoffs(&[assignment("pod-a")], &[], &[])
+ .create_assignments_and_handoffs(&[assignment("pod-a")], &[], &[], 128)
.await
.unwrap());
let snapshot = store.list_assignments_with_mod_revisions().await.unwrap();
@@ -3230,7 +3232,7 @@ async fn stale_plan_is_rejected_when_the_assignment_moved() {
// Concurrently, a full move to B lands: by the time the stale plan's
// txn arrives, the handoff key is gone and only the assignment moved.
assert!(store
- .create_assignments_and_handoffs(&[assignment("pod-b")], &[], &[])
+ .create_assignments_and_handoffs(&[assignment("pod-b")], &[], &[], 128)
.await
.unwrap());
@@ -3244,6 +3246,7 @@ async fn stale_plan_is_rejected_when_the_assignment_moved() {
partition: 0,
mod_revision: stale_revision,
}],
+ 128,
)
.await
.unwrap();
@@ -3265,6 +3268,7 @@ async fn stale_plan_is_rejected_when_the_assignment_moved() {
partition: 0,
mod_revision: *fresh_revision,
}],
+ 128
)
.await
.unwrap());
@@ -3276,8 +3280,8 @@ async fn stale_plan_is_rejected_when_the_assignment_moved() {
/// A fresh-partition handoff asserts the assignment is still absent: if
/// one appeared since the snapshot (the partition got born through a
/// concurrent handoff's completion), the plan's old_owner: None is a lie
-/// and the plan must be rejected — and one stale precondition rejects the
-/// whole plan, valid handoffs included.
+/// and that partition must be rejected — alone: a stale precondition
+/// stands down its own partition, not the plan's valid handoffs.
#[tokio::test]
async fn fresh_plan_is_rejected_when_an_assignment_appeared() {
use personhog_coordination::types::{
@@ -3311,13 +3315,15 @@ async fn fresh_plan_is_rejected_when_an_assignment_appeared() {
}],
&[],
&[],
+ 128
)
.await
.unwrap());
// The plan carries one stale fresh-handoff (partition 0) and one
- // genuinely fresh one (partition 1): all-or-nothing rejection.
- let rejected = store
+ // genuinely fresh one (partition 1): the stale partition stands
+ // down alone, the innocent one applies.
+ let all_applied = store
.create_assignments_and_handoffs(
&[],
&[fresh_handoff(0, "stale"), fresh_handoff(1, "innocent")],
@@ -3325,22 +3331,15 @@ async fn fresh_plan_is_rejected_when_an_assignment_appeared() {
AssignmentPrecondition::Absent { partition: 0 },
AssignmentPrecondition::Absent { partition: 1 },
],
+ 128,
)
.await
.unwrap();
- assert!(!rejected);
- assert!(store.list_handoffs().await.unwrap().is_empty());
-
- // Replanned against reality, partition 1 alone applies.
- assert!(store
- .create_assignments_and_handoffs(
- &[],
- &[fresh_handoff(1, "replanned")],
- &[AssignmentPrecondition::Absent { partition: 1 }],
- )
- .await
- .unwrap());
- assert_eq!(store.list_handoffs().await.unwrap().len(), 1);
+ assert!(!all_applied);
+ let handoffs = store.list_handoffs().await.unwrap();
+ assert_eq!(handoffs.len(), 1);
+ assert_eq!(handoffs[0].partition, 1);
+ assert_eq!(handoffs[0].handoff_id, "innocent");
}
/// The rebalance must never write assignment records — handoff completion
diff --git a/rust/personhog-coordination/tests/protocol_hardening.rs b/rust/personhog-coordination/tests/protocol_hardening.rs
index 9b329ce87ddc..557744d7544a 100644
--- a/rust/personhog-coordination/tests/protocol_hardening.rs
+++ b/rust/personhog-coordination/tests/protocol_hardening.rs
@@ -1531,6 +1531,7 @@ async fn late_joining_router_stashes_before_populating_table() {
}],
&[],
&[],
+ 128
)
.await
.expect("write assignment"));
@@ -1600,6 +1601,7 @@ async fn start_router_with_frozen_handoff(
}],
&[],
&[],
+ 128
)
.await
.expect("write assignment"));
@@ -1749,6 +1751,7 @@ async fn a_blocked_drain_does_not_stall_freeze_acks_for_other_partitions() {
}],
&[],
&[],
+ 128
)
.await
.expect("write assignment"));
@@ -1966,6 +1969,7 @@ async fn start_reconciling_router(
}],
&[],
&[],
+ 128
)
.await
.expect("write assignment"));
@@ -2276,6 +2280,7 @@ async fn start_flaky_router(
}],
&[],
&[],
+ 128
)
.await
.expect("write assignment"));
@@ -2515,6 +2520,7 @@ async fn the_reconcile_pass_skips_drains_for_settled_partitions() {
}],
&[],
&[],
+ 128
)
.await
.expect("write assignment"));
@@ -5496,8 +5502,8 @@ async fn a_cached_absent_membership_still_requires_every_live_router() {
handoff_id: handoff.handoff_id.clone(),
}];
- // Resolve twice: the first read populates the cache, the second is
- // answered from it. Both must say the same thing.
+ // Resolve twice: absence is never cached, so both are reads — and
+ // both must say the same thing.
for pass in 1..=2 {
let quorum = store
.resolve_freeze_quorum(&handoff)
@@ -5605,10 +5611,17 @@ async fn a_membership_already_read_is_answered_without_reading_again() {
"the first resolution reads the record"
);
- store
- .delete_freeze_quorum(id)
+ let (_, mod_revision) = store
+ .list_freeze_quorum_ids()
+ .await
+ .expect("list memberships")
+ .into_iter()
+ .find(|(listed, _)| listed == id)
+ .expect("the membership is listed");
+ assert!(store
+ .delete_freeze_quorum_if_unchanged(id, mod_revision)
.await
- .expect("delete the membership");
+ .expect("delete the membership"));
assert!(
store
.get_freeze_quorum(id)
@@ -5627,3 +5640,307 @@ async fn a_membership_already_read_is_answered_without_reading_again() {
"the second resolution must come from memory, not from etcd"
);
}
+
+// ── Plan chunking against the server txn budget ─────────────────────
+
+/// The 256→1 collapse shape: a plan of 256 creations carries two
+/// compares per partition, quadruple etcd's default `--max-txn-ops` of
+/// 128 (which this suite's etcd runs). Unchunked, the server rejects
+/// the transaction outright — a hard error, not a failed guard — and a
+/// coordinator retrying the same plan re-earns it forever, with every
+/// partition unassigned. Chunked to the budget, every handoff lands.
+#[tokio::test]
+async fn a_plan_past_the_server_txn_budget_still_applies() {
+ use personhog_coordination::types::AssignmentPrecondition;
+
+ let store = test_store("plan-past-txn-budget").await;
+ let total: u32 = 256;
+
+ let quorum_id = "large-plan-quorum";
+ let quorum = vec!["router-0".to_string()];
+ let now = 1_000_i64;
+ let handoffs: Vec<HandoffState> = (0..total)
+ .map(|partition| HandoffState {
+ partition,
+ old_owner: Some(format!("pod-{partition}")),
+ new_owner: "pod-survivor".to_string(),
+ new_owner_address: None,
+ phase: HandoffPhase::Freezing,
+ started_at: now,
+ handoff_id: format!("handoff-{partition}"),
+ freeze_quorum: None,
+ freeze_quorum_ref: Some(quorum_id.to_string()),
+ created_at_ms: now * 1000,
+ phase_entered_at_ms: now * 1000,
+ })
+ .collect();
+ let preconditions: Vec<AssignmentPrecondition> = (0..total)
+ .map(|partition| AssignmentPrecondition::Absent { partition })
+ .collect();
+
+ let application = store
+ .apply_plan(
+ &[],
+ &handoffs,
+ &[],
+ &preconditions,
+ Some((quorum_id, &quorum)),
+ 128,
+ )
+ .await
+ .expect("a plan larger than the server txn budget must apply in chunks");
+
+ assert_eq!(application.applied.len(), total as usize);
+ assert!(application.conflicted.is_empty());
+ let written = store.list_handoffs().await.unwrap();
+ assert_eq!(
+ written.len(),
+ total as usize,
+ "every handoff must be durable"
+ );
+ assert_eq!(
+ store.get_freeze_quorum(quorum_id).await.unwrap().as_deref(),
+ Some(quorum.as_slice()),
+ "the shared quorum record must be durable alongside its handoffs"
+ );
+}
+
+/// Guards keep their bite across chunks: a partition whose handoff key
+/// already exists stands down alone, without dragging the rest of its
+/// chunk — or the plan — with it.
+#[tokio::test]
+async fn a_conflicted_partition_stands_down_alone() {
+ use personhog_coordination::types::AssignmentPrecondition;
+
+ let store = test_store("plan-conflict-isolated").await;
+ let total: u32 = 100;
+
+ let make = |partition: u32, id: &str| HandoffState {
+ partition,
+ old_owner: None,
+ new_owner: "pod-survivor".to_string(),
+ new_owner_address: None,
+ phase: HandoffPhase::Freezing,
+ started_at: 1_000,
+ handoff_id: id.to_string(),
+ freeze_quorum: Some(Vec::new()),
+ freeze_quorum_ref: None,
+ created_at_ms: 1_000_000,
+ phase_entered_at_ms: 1_000_000,
+ };
+
+ // Partition 40 already has a handoff — a concurrent planner won it.
+ let winner = make(40, "handoff-winner");
+ let first = store
+ .apply_plan(&[], std::slice::from_ref(&winner), &[], &[], None, 128)
+ .await
+ .unwrap();
+ assert_eq!(first.applied, vec![40]);
+
+ let handoffs: Vec<HandoffState> = (0..total)
+ .map(|p| make(p, &format!("handoff-{p}")))
+ .collect();
+ let preconditions: Vec<AssignmentPrecondition> = (0..total)
+ .map(|partition| AssignmentPrecondition::Absent { partition })
+ .collect();
+ let application = store
+ .apply_plan(&[], &handoffs, &[], &preconditions, None, 128)
+ .await
+ .unwrap();
+
+ assert_eq!(
+ application.conflicted,
+ vec![40],
+ "only the won partition stands down"
+ );
+ assert_eq!(application.applied.len(), (total - 1) as usize);
+ let ids: HashMap<u32, String> = store
+ .list_handoffs()
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|h| (h.partition, h.handoff_id))
+ .collect();
+ assert_eq!(
+ ids[&40], "handoff-winner",
+ "the winner's record must survive"
+ );
+ assert_eq!(ids.len(), total as usize);
+}
+
+/// The stale-quorum sweep's delete is guarded on the revision it listed:
+/// a chunked plan re-puts its record with every chunk, and a re-put
+/// after the sweep's read must win — otherwise the sweep collects a
+/// record the chunk it never saw still references.
+#[tokio::test]
+async fn a_swept_quorum_delete_loses_to_a_concurrent_re_put() {
+ use personhog_coordination::types::AssignmentPrecondition;
+
+ let store = test_store("quorum-sweep-guarded").await;
+ let quorum_id = "shared-quorum";
+ let quorum = vec!["router-0".to_string()];
+ let handoff = |partition: u32| HandoffState {
+ partition,
+ old_owner: None,
+ new_owner: "pod-new".to_string(),
+ new_owner_address: None,
+ phase: HandoffPhase::Freezing,
+ started_at: 0,
+ handoff_id: format!("handoff-{partition}"),
+ freeze_quorum: None,
+ freeze_quorum_ref: Some(quorum_id.to_string()),
+ created_at_ms: 0,
+ phase_entered_at_ms: 0,
+ };
+ let listed_revision = |store: Arc<personhog_coordination::store::PersonhogStore>| async move {
+ store
+ .list_freeze_quorum_ids()
+ .await
+ .unwrap()
+ .into_iter()
+ .find(|(id, _)| id == quorum_id)
+ .map(|(_, rev)| rev)
+ };
+
+ // The sweep's read: the first chunk wrote the record.
+ store
+ .apply_plan(
+ &[],
+ &[handoff(0)],
+ &[],
+ &[AssignmentPrecondition::Absent { partition: 0 }],
+ Some((quorum_id, &quorum)),
+ 128,
+ )
+ .await
+ .unwrap();
+ let swept = listed_revision(Arc::clone(&store)).await.expect("listed");
+
+ // A later chunk re-puts it before the sweep deletes.
+ store
+ .apply_plan(
+ &[],
+ &[handoff(1)],
+ &[],
+ &[AssignmentPrecondition::Absent { partition: 1 }],
+ Some((quorum_id, &quorum)),
+ 128,
+ )
+ .await
+ .unwrap();
+
+ assert!(
+ !store
+ .delete_freeze_quorum_if_unchanged(quorum_id, swept)
+ .await
+ .unwrap(),
+ "a delete guarded on the pre-chunk revision must lose"
+ );
+ assert_eq!(
+ store.get_freeze_quorum(quorum_id).await.unwrap(),
+ Some(quorum.clone()),
+ "the record the later chunk references must survive"
+ );
+
+ let current = listed_revision(Arc::clone(&store)).await.expect("listed");
+ assert!(
+ store
+ .delete_freeze_quorum_if_unchanged(quorum_id, current)
+ .await
+ .unwrap(),
+ "a delete guarded on the current revision applies"
+ );
+}
+
+/// A missing membership record is not remembered as missing: a chunked
+/// plan can re-create a swept record, and a pinned absence would hold
+/// every later resolution on the every-live-router fallback.
+#[tokio::test]
+async fn a_missing_membership_is_resolved_again_once_written() {
+ use personhog_coordination::types::AssignmentPrecondition;
+
+ let store = test_store("quorum-absence-not-cached").await;
+ let quorum_id = "late-written";
+ let quorum = vec!["router-0".to_string()];
+ let handoff = HandoffState {
+ partition: 0,
+ old_owner: None,
+ new_owner: "pod-new".to_string(),
+ new_owner_address: None,
+ phase: HandoffPhase::Freezing,
+ started_at: 0,
+ handoff_id: "handoff-late".to_string(),
+ freeze_quorum: None,
+ freeze_quorum_ref: Some(quorum_id.to_string()),
+ created_at_ms: 0,
+ phase_entered_at_ms: 0,
+ };
+
+ assert!(store
+ .resolve_freeze_quorum(&handoff)
+ .await
+ .unwrap()
+ .is_none());
+
+ store
+ .apply_plan(
+ &[],
+ std::slice::from_ref(&handoff),
+ &[],
+ &[AssignmentPrecondition::Absent { partition: 0 }],
+ Some((quorum_id, &quorum)),
+ 128,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ store.resolve_freeze_quorum(&handoff).await.unwrap(),
+ Some(quorum),
+ "a record written after a miss must resolve on the next look"
+ );
+}
+
+/// A configured budget above the server's live `--max-txn-ops` (values
+/// drift, a member not yet restarted with the raised flag) must degrade
+/// to per-partition transactions rather than hand the planner a
+/// rejection it would retry forever.
+#[tokio::test]
+async fn an_over_server_budget_chunk_degrades_to_per_unit_transactions() {
+ use personhog_coordination::types::AssignmentPrecondition;
+
+ let store = test_store("plan-over-server-budget").await;
+ let total: u32 = 100;
+ let handoffs: Vec<HandoffState> = (0..total)
+ .map(|partition| HandoffState {
+ partition,
+ old_owner: None,
+ new_owner: "pod-survivor".to_string(),
+ new_owner_address: None,
+ phase: HandoffPhase::Freezing,
+ started_at: 0,
+ handoff_id: format!("handoff-{partition}"),
+ freeze_quorum: Some(Vec::new()),
+ freeze_quorum_ref: None,
+ created_at_ms: 0,
+ phase_entered_at_ms: 0,
+ })
+ .collect();
+ let preconditions: Vec<AssignmentPrecondition> = (0..total)
+ .map(|partition| AssignmentPrecondition::Absent { partition })
+ .collect();
+
+ // 200 compares in one chunk against the suite's default-limits etcd.
+ let application = store
+ .apply_plan(&[], &handoffs, &[], &preconditions, None, 100_000)
+ .await
+ .expect("an over-budget chunk must fall back, not fail");
+
+ assert_eq!(
+ application.over_budget_chunks, 1,
+ "the server must have refused the single chunk, or this test pins nothing"
+ );
+ assert_eq!(application.applied.len(), total as usize);
+ assert!(application.conflicted.is_empty());
+ assert_eq!(store.list_handoffs().await.unwrap().len(), total as usize);
+}
diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rs
index b11db3e258ac..77f32b0188eb 100644
--- a/rust/personhog-leader/tests/common/mod.rs
+++ b/rust/personhog-leader/tests/common/mod.rs
@@ -112,6 +112,7 @@ pub fn start_coordinator(
// state under test.
handoff_deadline: Duration::from_secs(86_400),
warming_deadline: Duration::from_secs(86_400),
+ max_txn_ops: 128,
},
strategy,
None,
diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rs
index 28bb83d22835..93a604a35483 100644
--- a/rust/personhog-router/src/main.rs
+++ b/rust/personhog-router/src/main.rs
@@ -356,6 +356,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
reconcile_interval: config.coordinator_reconcile_interval(),
handoff_deadline: config.coordinator_handoff_deadline(),
warming_deadline: config.coordinator_warming_deadline(),
+ // The same server limit the routing table's ack
+ // batches mirror: one env, one `--max-txn-ops`.
+ max_txn_ops: config.etcd_max_txn_ops,
},
Arc::new(StickyBalancedStrategy),
k8s_awareness,
diff --git a/rust/personhog-stateright/src/main.rs b/rust/personhog-stateright/src/main.rs
index e001576694f9..d7639c3f56ef 100644
--- a/rust/personhog-stateright/src/main.rs
+++ b/rust/personhog-stateright/src/main.rs
@@ -60,6 +60,7 @@ fn main() {
zombie_window,
hold_pods: 0,
cancels: 0,
+ chunked_plans: false,
probes: false,
};
println!("exploring {:?} at http://localhost:3000 …", args.scenario);
diff --git a/rust/personhog-stateright/src/model.rs b/rust/personhog-stateright/src/model.rs
index d9cee87dd5fe..762d6575c914 100644
--- a/rust/personhog-stateright/src/model.rs
+++ b/rust/personhog-stateright/src/model.rs
@@ -9,7 +9,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap};
use personhog_coordination::pod::{desired_state, DesiredState};
use personhog_coordination::protocol::{
- drain_satisfied, freeze_quorum_met, plan_partial_rebalance, warm_satisfied,
+ drain_satisfied, freeze_quorum_met, plan_partial_rebalance, warm_satisfied, PlannedHandoff,
};
use personhog_coordination::strategy::{AssignmentStrategy, Member, StickyBalancedStrategy};
use personhog_coordination::types::{
@@ -19,8 +19,8 @@ use personhog_coordination::types::{
use stateright::{Model, Property};
use crate::types::{
- Action, Changelog, Handoff, HandoffId, Partition, PendingWarm, Phase, Pod, PodId, Router,
- RouterId, StashedRequest, SystemState, WarmState,
+ Action, Changelog, Handoff, HandoffId, Partition, PendingUnit, PendingWarm, Phase, Pod, PodId,
+ Router, RouterId, StashedRequest, SystemState, WarmState,
};
/// Deterministic names bridging the model's compact u8 ids to the
@@ -153,6 +153,10 @@ pub struct HandoffModel {
/// share (the coordinator's rollout policies). Zero models the
/// steady state, where every pod is an uncapped active member.
pub hold_pods: u8,
+ /// Apply rebalance plans in chunks (production: `apply_plan` past
+ /// the txn budget): the first planned handoff lands with the plan,
+ /// the rest apply later through `ApplyPendingUnit`.
+ pub chunked_plans: bool,
/// Adds reachability probes (`sometimes` properties) for scenario
/// shapes that only exist at larger scale — used to measure, rather
/// than assume, which configurations actually reach them. Off in the
@@ -604,6 +608,11 @@ impl HandoffModel {
// Decided in the arm: enablement is "the planner produced a
// non-empty plan", which costs a full placement computation.
Action::Rebalance => true,
+ // One pending suffix at a time: chunks of one plan apply
+ // sequentially in production; a competing plan is the
+ // Rebalance interleavings.
+ Action::RebalanceChunked => self.chunked_plans && state.pending_plan.is_empty(),
+ Action::ApplyPendingUnit => !state.pending_plan.is_empty(),
Action::CancelDeadNewOwner(p) => matches!(
state.handoffs.get(&p),
@@ -688,22 +697,31 @@ fn mutate(last: &SystemState, apply: impl FnOnce(&mut SystemState)) -> Option<Sy
/// `enabled` — each derives it from `last` and clones only once a
/// successor is certain.
impl HandoffModel {
- /// The rebalance half of `handle_pod_change`: when the planner has
- /// work, create Freezing handoffs for every assignment diff in one
- /// transaction. In-flight handoffs pin their partitions — the
- /// production `protocol::plan_partial_rebalance` excludes them from
- /// the plan and attributes each to its target for the placement
- /// computation — so rebalancing is enabled in every state and the
- /// checker explores a rebalance racing every handoff phase. Only the
- /// etcd writes are applied model-side, and assignments for
- /// moved/fresh partitions are deferred until Complete
- /// (`create_assignments_and_handoffs`). This action is atomic (plan
- /// and apply in one transition); production earns that abstraction by
- /// guarding the apply txn on its read-set — handoff keys still
- /// absent, and each touched partition's assignment unchanged since the
- /// snapshot — so a stale plan fails instead of replacing an in-flight
- /// handoff or draining a superseded owner.
+ /// The rebalance half of `handle_pod_change`, applied in one
+ /// transition. In-flight handoffs pin their partitions
+ /// (`plan_partial_rebalance`), so rebalancing is enabled in every
+ /// state and races every handoff phase. Production guards each
+ /// partition's unit on its read-set, so a stale unit stands down
+ /// instead of clobbering an in-flight handoff; plans past the txn
+ /// budget apply in chunks, which `rebalance_chunked` explores.
fn rebalance(&self, last: &SystemState) -> Option<SystemState> {
+ let (handoffs, quorum) = self.planned_handoffs(last)?;
+ mutate(last, |state| {
+ for planned in &handoffs {
+ Self::create_planned_handoff(state, planned, &quorum);
+ }
+ })
+ }
+
+ /// The planner's decision, shared by both apply shapes: the sorted
+ /// plan and the freeze quorum snapshotted with it. `None` when the
+ /// plan is empty — an empty plan is a no-op successor the checker
+ /// would dedup anyway, and deciding it before the clone skips the
+ /// clone-and-hash per state.
+ fn planned_handoffs(
+ &self,
+ last: &SystemState,
+ ) -> Option<(Vec<PlannedHandoff>, BTreeSet<RouterId>)> {
let current: HashMap<u32, String> = last
.assignments
.iter()
@@ -723,10 +741,6 @@ impl HandoffModel {
self.partitions as u32,
);
if plan.handoffs.is_empty() {
- // An empty plan is a no-op successor the checker would dedup
- // anyway; deciding it before the clone skips the
- // clone-and-hash per state, which dominates once Rebalance is
- // enabled everywhere.
return None;
}
// The plan's order follows HashMap iteration; sort so sequential
@@ -740,31 +754,104 @@ impl HandoffModel {
.router_ids()
.filter(|r| last.routers[r].registered)
.collect();
+ Some((plan.handoffs, quorum))
+ }
+
+ /// One planned creation landing (the atomic-apply path, where guards
+ /// trivially hold within the transition).
+ fn create_planned_handoff(
+ state: &mut SystemState,
+ planned: &PlannedHandoff,
+ quorum: &BTreeSet<RouterId>,
+ ) {
+ let id = state.next_handoff_id;
+ state.next_handoff_id += 1;
+ let clobbered = state
+ .handoffs
+ .insert(
+ planned.partition as Partition,
+ Handoff {
+ id,
+ old_owner: planned.old_owner.as_deref().map(pod_id),
+ new_owner: pod_id(&planned.new_owner),
+ phase: Phase::Freezing,
+ quorum: quorum.clone(),
+ },
+ )
+ .is_some();
+ if clobbered {
+ // Planning a pinned partition would destroy its
+ // in-flight handoff (and orphan its acks); the
+ // always-property flags any interleaving where the
+ // exclusion fails to prevent that.
+ state.double_planned_handoff = true;
+ }
+ }
+
+ /// `rebalance` applying its plan the way `apply_plan` does past the
+ /// txn budget: the first handoff lands now, the rest wait as
+ /// pending units carrying their plan-time guards. Only offered when
+ /// the plan actually splits — a one-handoff plan is `Rebalance`.
+ fn rebalance_chunked(&self, last: &SystemState) -> Option<SystemState> {
+ let (handoffs, quorum) = self.planned_handoffs(last)?;
+ let (first, rest) = handoffs.split_first()?;
+ if rest.is_empty() {
+ return None;
+ }
mutate(last, |state| {
- for planned in plan.handoffs {
- let id = state.next_handoff_id;
- state.next_handoff_id += 1;
- let clobbered = state
- .handoffs
- .insert(
- planned.partition as Partition,
- Handoff {
- id,
- old_owner: planned.old_owner.as_deref().map(pod_id),
- new_owner: pod_id(&planned.new_owner),
- phase: Phase::Freezing,
- quorum: quorum.clone(),
- },
- )
- .is_some();
- if clobbered {
- // Planning a pinned partition would destroy its
- // in-flight handoff (and orphan its acks); the
- // always-property flags any interleaving where the
- // exclusion fails to prevent that.
- state.double_planned_handoff = true;
- }
+ Self::create_planned_handoff(state, first, &quorum);
+ state.pending_plan = rest
+ .iter()
+ .map(|planned| {
+ let partition = planned.partition as Partition;
+ PendingUnit {
+ partition,
+ old_owner: planned.old_owner.as_deref().map(pod_id),
+ new_owner: pod_id(&planned.new_owner),
+ quorum: quorum.clone(),
+ expected_assignment_version: state
+ .assignment_versions
+ .get(&partition)
+ .copied()
+ .unwrap_or(0),
+ }
+ })
+ .collect();
+ })
+ }
+
+ /// A later chunk landing: the front pending unit applies if its
+ /// plan-time guards still hold — handoff key absent, assignment
+ /// version unchanged — and is dropped (stood down) otherwise, as a
+ /// conflicted chunk unit is in production.
+ fn apply_pending_unit(&self, last: &SystemState) -> Option<SystemState> {
+ let unit = last.pending_plan.first()?.clone();
+ mutate(last, |state| {
+ state.pending_plan.remove(0);
+ let version = state
+ .assignment_versions
+ .get(&unit.partition)
+ .copied()
+ .unwrap_or(0);
+ if state.handoffs.contains_key(&unit.partition)
+ || version != unit.expected_assignment_version
+ {
+ state.pending_unit_dropped = true;
+ return;
}
+ let id = state.next_handoff_id;
+ state.next_handoff_id += 1;
+ state.handoffs.insert(
+ unit.partition,
+ Handoff {
+ id,
+ old_owner: unit.old_owner,
+ new_owner: unit.new_owner,
+ phase: Phase::Freezing,
+ quorum: unit.quorum,
+ },
+ );
+ state.pending_unit_applied = true;
})
}
@@ -873,6 +960,12 @@ impl HandoffModel {
// `complete_handoff`: phase write and assignment flip are
// one etcd transaction.
state.assignments.insert(p, new_owner);
+ if self.chunked_plans {
+ // The mod_revision a pending unit's precondition
+ // compares; maintained only where something reads it,
+ // so other configs don't split states by history.
+ *state.assignment_versions.entry(p).or_insert(0) += 1;
+ }
}
})
}
@@ -1146,6 +1239,8 @@ impl Model for HandoffModel {
drained_acks: BTreeMap::new(),
warmed_acks: BTreeMap::new(),
next_handoff_id: 0,
+ pending_plan: Vec::new(),
+ assignment_versions: BTreeMap::new(),
pods,
routers,
changelogs,
@@ -1162,6 +1257,8 @@ impl Model for HandoffModel {
reaffirmed: false,
replaced_with_successor: false,
cancelled_while_stash_parked: false,
+ pending_unit_applied: false,
+ pending_unit_dropped: false,
}]
}
@@ -1177,6 +1274,8 @@ impl Model for HandoffModel {
}
};
offer(Action::Rebalance);
+ offer(Action::RebalanceChunked);
+ offer(Action::ApplyPendingUnit);
for p in self.partition_ids() {
offer(Action::CancelDeadNewOwner(p));
offer(Action::Cancel(p));
@@ -1232,6 +1331,8 @@ impl Model for HandoffModel {
match action {
// ── coordinator ────────────────────────────────────
Action::Rebalance => self.rebalance(last),
+ Action::RebalanceChunked => self.rebalance_chunked(last),
+ Action::ApplyPendingUnit => self.apply_pending_unit(last),
Action::AdvancePhase(p) => self.advance_phase(last, p),
// The dead-new-owner arm of the coordinator's cleanup, now a
@@ -1490,7 +1591,7 @@ impl Model for HandoffModel {
// explored state, and the placement computation below is
// the one expensive part — it must stay behind the
// conjuncts that reject most states outright.
- if !s.handoffs.is_empty() {
+ if !s.handoffs.is_empty() || !s.pending_plan.is_empty() {
return false;
}
let no_capacity = s.pods.values().all(|p| !p.registered);
@@ -1600,6 +1701,21 @@ impl Model for HandoffModel {
},
));
}
+ if self.probes && self.chunked_plans {
+ // Both fates of a chunked plan's suffix are genuinely
+ // reachable: a late unit landing after other actions
+ // interleaved, and one stood down by a failed guard. The
+ // safety properties judge every interleaving that reaches
+ // them.
+ props.push(Property::<Self>::sometimes(
+ "chunked_pending_unit_applied",
+ |_, s| s.pending_unit_applied,
+ ));
+ props.push(Property::<Self>::sometimes(
+ "chunked_pending_unit_dropped",
+ |_, s| s.pending_unit_dropped,
+ ));
+ }
props
}
}
diff --git a/rust/personhog-stateright/src/types.rs b/rust/personhog-stateright/src/types.rs
index ec3288050220..f75d296ccb26 100644
--- a/rust/personhog-stateright/src/types.rs
+++ b/rust/personhog-stateright/src/types.rs
@@ -169,6 +169,21 @@ pub struct Changelog {
pub epoch_holder: Option<PodId>,
}
+/// One planned-but-unapplied handoff from a chunked plan: the placement
+/// decision plus its plan-time guards (production: a later `apply_plan`
+/// chunk, applied without re-reading).
+#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct PendingUnit {
+ pub partition: Partition,
+ pub old_owner: Option<PodId>,
+ pub new_owner: PodId,
+ /// Freeze requirement snapshotted at plan time.
+ pub quorum: BTreeSet<RouterId>,
+ /// Assignment version at plan time (production: the mod_revision
+ /// its `AssignmentPrecondition` compares; 0 = Absent).
+ pub expected_assignment_version: u8,
+}
+
/// The entire distributed system. One value = one node in the explored
/// state graph.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
@@ -188,6 +203,13 @@ pub struct SystemState {
pub warmed_acks: BTreeMap<(Partition, PodId), HandoffId>,
/// Monotonic handoff id allocator (production: `new_handoff_id`).
pub next_handoff_id: HandoffId,
+ /// Unapplied suffix of a chunked plan, front unit next
+ /// (production: `apply_plan`'s later chunks).
+ pub pending_plan: Vec<PendingUnit>,
+ /// partition → count of assignment writes (production: the
+ /// mod_revision an `AssignmentPrecondition` compares). Only
+ /// maintained under `chunked_plans`.
+ pub assignment_versions: BTreeMap<Partition, u8>,
// ── processes ──────────────────────────────────────────────
pub pods: BTreeMap<PodId, Pod>,
@@ -238,6 +260,10 @@ pub struct SystemState {
/// for the partition — the composition the replacement design must
/// keep safe and live.
pub cancelled_while_stash_parked: bool,
+ /// A pending chunk unit applied after its plan's first transaction.
+ pub pending_unit_applied: bool,
+ /// A pending chunk unit dropped by a failed plan-time guard.
+ pub pending_unit_dropped: bool,
}
/// Everything that can happen, from every actor, including failures.
@@ -269,6 +295,13 @@ pub enum Action {
/// in flight, create Freezing handoffs for every assignment diff in
/// one transaction.
Rebalance,
+ /// The same rebalance applying its plan in chunks (production:
+ /// `apply_plan` past the txn budget): the first planned handoff
+ /// lands now, the rest wait in `pending_plan`.
+ RebalanceChunked,
+ /// Apply the front `pending_plan` unit — or drop it when its
+ /// plan-time guards no longer hold (a conflicted unit standing down).
+ ApplyPendingUnit,
/// `check_phase_advance` for one partition (watch nudge or tick).
AdvancePhase(Partition),
/// Post-Complete cleanup: delete the handoff record and its acks
diff --git a/rust/personhog-stateright/tests/model_tests.rs b/rust/personhog-stateright/tests/model_tests.rs
index 8ab7a586133a..d3d5f349751c 100644
--- a/rust/personhog-stateright/tests/model_tests.rs
+++ b/rust/personhog-stateright/tests/model_tests.rs
@@ -131,6 +131,7 @@ fn base() -> HandoffModel {
zombie_window: 0,
hold_pods: 0,
cancels: 0,
+ chunked_plans: false,
probes: false,
}
}
@@ -868,3 +869,56 @@ fn rollout_quota_mode_is_safe_and_live() {
.explore("rollout_quota_mode_is_safe_and_live")
.assert_properties();
}
+
+/// Chunked plan application (production: `apply_plan` past the etcd txn
+/// budget): a plan's later units land against a world that kept moving —
+/// phase advances, crashes, cancellations, competing rebalances — each
+/// guarded on its plan-time snapshot. Every safety property must hold
+/// across those interleavings and every full run must still converge.
+#[test]
+fn chunked_plan_application_is_safe_and_live() {
+ HandoffModel {
+ partitions: 2,
+ chunked_plans: true,
+ crashes: 1,
+ cancels: 1,
+ writes: 1,
+ reads: 0,
+ ..base()
+ }
+ .explore("chunked_plan_application_is_safe_and_live")
+ .assert_properties();
+}
+
+/// Both fates of a pending unit are genuinely reachable — applied after
+/// other actions interleaved, and dropped by a failed plan-time guard —
+/// and no interleaving that reaches them loses an acked write or
+/// double-plans a partition.
+#[test]
+fn probe_chunked_pending_units_reach_both_fates_safely() {
+ let checker = HandoffModel {
+ partitions: 2,
+ chunked_plans: true,
+ crashes: 1,
+ cancels: 1,
+ writes: 1,
+ reads: 0,
+ probes: true,
+ ..base()
+ }
+ .explore("probe_chunked_pending_units_reach_both_fates_safely");
+ assert!(
+ checker.discovery("chunked_pending_unit_applied").is_some(),
+ "a pending unit must be able to land after its plan's first transaction"
+ );
+ assert!(
+ checker.discovery("chunked_pending_unit_dropped").is_some(),
+ "a failed plan-time guard must be able to stand a pending unit down"
+ );
+ for safety in ["no_lost_acked_write", "no_double_planned_handoff"] {
+ assert!(
+ checker.discovery(safety).is_none(),
+ "{safety} must hold across chunked application"
+ );
+ }
+}
diff --git a/rust/personhog-test-harness/README.md b/rust/personhog-test-harness/README.md
index 6a27b360894c..76622e805bf3 100644
--- a/rust/personhog-test-harness/README.md
+++ b/rust/personhog-test-harness/README.md
@@ -180,10 +180,6 @@ target/debug/personhog-test-harness gate --routers 3 --leaders 3 --duration 18s
Verification still waits for convergence (bounded at 30s — 2x the slow-crash TTL chain, the slowest legitimate recovery) before asserting strong reads; red here means convergence itself failed.
The two follow-ups once listed here are resolved: draining pods were never actually rebalance targets (`active_pod_names` has filtered to `Ready` pods since the original PoC — the earlier claim misread the wedge, whose real mechanism was the shutdown ordering fixed above), and a stuck handoff now defers only its own partition (the coordinator pins in-flight partitions and rebalances the rest — see `plan_partial_rebalance`).
-**Follow-up: the guarded rebalance transaction has a partition-count budget.**
-Plan application guards every handoff with two etcd compares (handoff-key absence + assignment precondition), and etcd's default `--max-txn-ops` of 128 caps the compare list — so a full-fleet plan (bootstrap, mass failover) fits in one transaction only up to 64 partitions; beyond that etcd rejects it with a hard error, not a guard failure.
-Every environment today runs well under the bound, but it must be resolved as part of choosing the prod partition count: either an explicitly-set shared chart value rendered into both etcd's `--max-txn-ops` and a coordinator plan budget (so the two validate against each other), or chunked plan application — which must not ship without stateright coverage of partial application and harness scenarios at that scale.
-
**Follow-up: coalesce changelog recovery fetches if the pool ever queues.**
Recoveries check out one pooled consumer per person, so N concurrent misses on genuinely-behind persons cost N sequential Kafka point-reads once the pool saturates.
The changelog is offset-ordered, so a batch executor could assign one consumer at the lowest pending offset per partition and satisfy every waiter it passes in a single sweep (group-commit shape; bound the sweep span so sparse marks don't degenerate into scanning the gap between them).