| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! Ownership balancing after the fleet membership changes. |
| 4 | //! |
| 5 | //! The densest node gives a bounded batch of idle cells to the peers below |
| 6 | //! their weighted share. This module only counts. Every move still goes |
| 7 | //! through the release CAS and the signed successor acquire, so a wrong count |
| 8 | //! here costs movement, never authority. |
| 9 | |
| 10 | use crate::{CapacityPeer, NodeId}; |
| 11 | use std::cmp::Ordering; |
| 12 | |
| 13 | /// A receiver fills to this fraction below its target. A donor drains to its |
| 14 | /// target exactly, so the fleet cannot end short by one deadband per donor. |
| 15 | /// The receiver's margin absorbs the lease lag between a batch and its |
| 16 | /// publication: a stale count can overshoot by one batch, and the node it |
| 17 | /// came from has no room to take that batch straight back. |
| 18 | const DEADBAND_PERCENT: u128 = 2; |
| 19 | |
| 20 | struct Member<'a> { |
| 21 | peer: &'a CapacityPeer, |
| 22 | owned: u128, |
| 23 | weight: u128, |
| 24 | } |
| 25 | |
| 26 | impl Member<'_> { |
| 27 | /// Whether this member can take a donated cell from `self_node`. A |
| 28 | /// draining node gives its own cells away, and a node with cold |
| 29 | /// activations queued behind its ceiling would time the adoption out |
| 30 | /// behind them: an adoption is a record read and a CAS through that |
| 31 | /// same queue, and on the 2026-09-04 fleet a node that had just |
| 32 | /// returned, waking nine hundred rooms, let a batch of 21 time out. |
| 33 | /// |
| 34 | /// A memory-saturated node is excluded through the same predicate the |
| 35 | /// executor ranks candidates with, so the plan and the executor share |
| 36 | /// this rule and a donor never releases a cell it has nowhere to put. |
| 37 | fn receives_from(&self, self_node: &str) -> bool { |
| 38 | self.peer.node != self_node |
| 39 | && !self.peer.draining |
| 40 | && self.peer.restoring == 0 |
| 41 | && self.peer.reports_adoption_capacity() |
| 42 | } |
| 43 | |
| 44 | /// Owned cells per unit of weight, compared without division. The node |
| 45 | /// id breaks ties, so one sample elects exactly one donor. |
| 46 | fn denser(&self, other: &Self) -> Ordering { |
| 47 | (self.owned * other.weight) |
| 48 | .cmp(&(other.owned * self.weight)) |
| 49 | .then_with(|| other.peer.node.cmp(&self.peer.node)) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | /// One consistent view of the live fleet. |
| 54 | struct Fleet<'a> { |
| 55 | members: Vec<Member<'a>>, |
| 56 | owned: u128, |
| 57 | weight: u128, |
| 58 | } |
| 59 | |
| 60 | impl<'a> Fleet<'a> { |
| 61 | /// `None` when a live lease is stale, predates ownership publication or |
| 62 | /// paced handoff, or carries an operator's pause: a mixed or paused |
| 63 | /// fleet moves nothing. `None` as well when a lease was sampled at or |
| 64 | /// before `since_ms`. The caller sets that to |
| 65 | /// the instant its last batch could have reached every lease, so a plan |
| 66 | /// never mixes counts from before a batch with counts from after it. A |
| 67 | /// mixed view shrinks the total, lowers every target, and moves cells |
| 68 | /// that then come straight back. |
| 69 | fn observe( |
| 70 | peers: &'a [CapacityPeer], |
| 71 | self_node: &str, |
| 72 | now_ms: u64, |
| 73 | max_age_ms: u64, |
| 74 | since_ms: u64, |
| 75 | ) -> Option<Self> { |
| 76 | let mut members = Vec::new(); |
| 77 | for peer in peers.iter().filter(|peer| peer.expires_ms > now_ms) { |
| 78 | let fresh = |
| 79 | peer.sampled_ms > since_ms && now_ms.saturating_sub(peer.sampled_ms) <= max_age_ms; |
| 80 | if !fresh || !peer.paced_handoff || peer.rebalance_paused { |
| 81 | return None; |
| 82 | } |
| 83 | members.push(Member { |
| 84 | peer, |
| 85 | owned: peer.owned_cells? as u128, |
| 86 | weight: u128::from(peer.placement_weight?.max(1)), |
| 87 | }); |
| 88 | } |
| 89 | if !members.iter().any(|member| member.peer.node == self_node) { |
| 90 | return None; |
| 91 | } |
| 92 | Some(Fleet { |
| 93 | owned: members.iter().map(|member| member.owned).sum(), |
| 94 | weight: members.iter().map(|member| member.weight).sum(), |
| 95 | members, |
| 96 | }) |
| 97 | } |
| 98 | |
| 99 | fn target(&self, member: &Member<'_>) -> u128 { |
| 100 | (self.owned * member.weight).div_ceil(self.weight) |
| 101 | } |
| 102 | |
| 103 | /// The cells a member can still take before it reaches the deadband. |
| 104 | fn room(&self, member: &Member<'_>) -> u128 { |
| 105 | let target = self.target(member); |
| 106 | let deadband = (target * DEADBAND_PERCENT).div_ceil(100); |
| 107 | target.saturating_sub(deadband).saturating_sub(member.owned) |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | /// How many idle cells this node gives away now. |
| 112 | /// |
| 113 | /// `Some` only on the densest live node, and only while it exceeds its |
| 114 | /// target and a peer has room. The count never exceeds `batch` or the |
| 115 | /// receivers' room, so one batch cannot push a peer above its own target. |
| 116 | pub fn surplus( |
| 117 | peers: &[CapacityPeer], |
| 118 | self_node: &str, |
| 119 | now_ms: u64, |
| 120 | max_age_ms: u64, |
| 121 | since_ms: u64, |
| 122 | batch: usize, |
| 123 | ) -> Option<usize> { |
| 124 | let fleet = Fleet::observe(peers, self_node, now_ms, max_age_ms, since_ms)?; |
| 125 | let donor = fleet |
| 126 | .members |
| 127 | .iter() |
| 128 | .max_by(|left, right| left.denser(right))?; |
| 129 | if donor.peer.node != self_node { |
| 130 | return None; |
| 131 | } |
| 132 | let surplus = donor.owned.saturating_sub(fleet.target(donor)); |
| 133 | let room: u128 = fleet |
| 134 | .members |
| 135 | .iter() |
| 136 | .filter(|member| member.receives_from(self_node)) |
| 137 | .map(|member| fleet.room(member)) |
| 138 | .sum(); |
| 139 | let count = surplus.min(room).min(batch as u128); |
| 140 | (count > 0).then_some(count as usize) |
| 141 | } |
| 142 | |
| 143 | /// The peers that can take a donated cell, least dense first. Every entry |
| 144 | /// is below its target, so the executor never hands a cell to a node that |
| 145 | /// would give it straight back. The planner bounds the count by the room |
| 146 | /// under the deadband; the executor is more permissive by that deadband, so |
| 147 | /// a receiver that fills between the plan and the release still accepts the |
| 148 | /// planned cells instead of leaving them unowned. |
| 149 | pub fn receivers( |
| 150 | peers: &[CapacityPeer], |
| 151 | self_node: &str, |
| 152 | now_ms: u64, |
| 153 | max_age_ms: u64, |
| 154 | ) -> Vec<NodeId> { |
| 155 | let Some(fleet) = Fleet::observe(peers, self_node, now_ms, max_age_ms, 0) else { |
| 156 | return Vec::new(); |
| 157 | }; |
| 158 | let mut receivers: Vec<&Member<'_>> = fleet |
| 159 | .members |
| 160 | .iter() |
| 161 | .filter(|member| member.receives_from(self_node) && member.owned < fleet.target(member)) |
| 162 | .collect(); |
| 163 | receivers.sort_by(|left, right| left.denser(right)); |
| 164 | receivers |
| 165 | .into_iter() |
| 166 | .map(|member| member.peer.node.clone()) |
| 167 | .collect() |
| 168 | } |