Diffinery

homeflare/celldpublic

celld/crates/logic/rebalance.rs
163 lines · 6.0 KBRaw History
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
10use crate::{CapacityPeer, NodeId};
11use 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.
18const DEADBAND_PERCENT: u128 = 2;
19
20struct Member<'a> {
21 peer: &'a CapacityPeer,
22 owned: u128,
23 weight: u128,
24}
25
26impl 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. The
33 /// plan and the executor share this rule, so a donor never releases a
34 /// cell it has nowhere to put.
35 fn receives_from(&self, self_node: &str) -> bool {
36 self.peer.node != self_node && !self.peer.draining && self.peer.restoring == 0
37 }
38
39 /// Owned cells per unit of weight, compared without division. The node
40 /// id breaks ties, so one sample elects exactly one donor.
41 fn denser(&self, other: &Self) -> Ordering {
42 (self.owned * other.weight)
43 .cmp(&(other.owned * self.weight))
44 .then_with(|| other.peer.node.cmp(&self.peer.node))
45 }
46}
47
48/// One consistent view of the live fleet.
49struct Fleet<'a> {
50 members: Vec<Member<'a>>,
51 owned: u128,
52 weight: u128,
53}
54
55impl<'a> Fleet<'a> {
56 /// `None` when a live lease is stale, predates ownership publication or
57 /// paced handoff, or carries an operator's pause: a mixed or paused
58 /// fleet moves nothing. `None` as well when a lease was sampled at or
59 /// before `since_ms`. The caller sets that to
60 /// the instant its last batch could have reached every lease, so a plan
61 /// never mixes counts from before a batch with counts from after it. A
62 /// mixed view shrinks the total, lowers every target, and moves cells
63 /// that then come straight back.
64 fn observe(
65 peers: &'a [CapacityPeer],
66 self_node: &str,
67 now_ms: u64,
68 max_age_ms: u64,
69 since_ms: u64,
70 ) -> Option<Self> {
71 let mut members = Vec::new();
72 for peer in peers.iter().filter(|peer| peer.expires_ms > now_ms) {
73 let fresh =
74 peer.sampled_ms > since_ms && now_ms.saturating_sub(peer.sampled_ms) <= max_age_ms;
75 if !fresh || !peer.paced_handoff || peer.rebalance_paused {
76 return None;
77 }
78 members.push(Member {
79 peer,
80 owned: peer.owned_cells? as u128,
81 weight: u128::from(peer.placement_weight?.max(1)),
82 });
83 }
84 if !members.iter().any(|member| member.peer.node == self_node) {
85 return None;
86 }
87 Some(Fleet {
88 owned: members.iter().map(|member| member.owned).sum(),
89 weight: members.iter().map(|member| member.weight).sum(),
90 members,
91 })
92 }
93
94 fn target(&self, member: &Member<'_>) -> u128 {
95 (self.owned * member.weight).div_ceil(self.weight)
96 }
97
98 /// The cells a member can still take before it reaches the deadband.
99 fn room(&self, member: &Member<'_>) -> u128 {
100 let target = self.target(member);
101 let deadband = (target * DEADBAND_PERCENT).div_ceil(100);
102 target.saturating_sub(deadband).saturating_sub(member.owned)
103 }
104}
105
106/// How many idle cells this node gives away now.
107///
108/// `Some` only on the densest live node, and only while it exceeds its
109/// target and a peer has room. The count never exceeds `batch` or the
110/// receivers' room, so one batch cannot push a peer above its own target.
111pub fn surplus(
112 peers: &[CapacityPeer],
113 self_node: &str,
114 now_ms: u64,
115 max_age_ms: u64,
116 since_ms: u64,
117 batch: usize,
118) -> Option<usize> {
119 let fleet = Fleet::observe(peers, self_node, now_ms, max_age_ms, since_ms)?;
120 let donor = fleet
121 .members
122 .iter()
123 .max_by(|left, right| left.denser(right))?;
124 if donor.peer.node != self_node {
125 return None;
126 }
127 let surplus = donor.owned.saturating_sub(fleet.target(donor));
128 let room: u128 = fleet
129 .members
130 .iter()
131 .filter(|member| member.receives_from(self_node))
132 .map(|member| fleet.room(member))
133 .sum();
134 let count = surplus.min(room).min(batch as u128);
135 (count > 0).then_some(count as usize)
136}
137
138/// The peers that can take a donated cell, least dense first. Every entry
139/// is below its target, so the executor never hands a cell to a node that
140/// would give it straight back. The planner bounds the count by the room
141/// under the deadband; the executor is more permissive by that deadband, so
142/// a receiver that fills between the plan and the release still accepts the
143/// planned cells instead of leaving them unowned.
144pub fn receivers(
145 peers: &[CapacityPeer],
146 self_node: &str,
147 now_ms: u64,
148 max_age_ms: u64,
149) -> Vec<NodeId> {
150 let Some(fleet) = Fleet::observe(peers, self_node, now_ms, max_age_ms, 0) else {
151 return Vec::new();
152 };
153 let mut receivers: Vec<&Member<'_>> = fleet
154 .members
155 .iter()
156 .filter(|member| member.receives_from(self_node) && member.owned < fleet.target(member))
157 .collect();
158 receivers.sort_by(|left, right| left.denser(right));
159 receivers
160 .into_iter()
161 .map(|member| member.peer.node.clone())
162 .collect()
163}