Diffinery

homeflare/celldpublic

celld/crates/logic/drain.rs
177 lines · 7.2 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3//! Sans-I/O policy for the fleet drain token.
4//!
5//! One well-known bucket object serializes concurrent donors: a draining
6//! node claims the token before it releases cells, so simultaneous stop
7//! signals (a node drain, a cluster upgrade, a spot reclaim) hand off one
8//! node at a time instead of flooding the survivors. A fresh node combines the
9//! token with the load in live node leases for its first readiness. The gate
10//! requires successor publication, memory headroom, bounded restoration, and
11//! bounded ownership skew before the fleet loses another node.
12//!
13//! The token is advisory for donor serialization. A donor that cannot claim it
14//! within a bounded wait proceeds unserialized, and a dead holder's claim
15//! lapses by TTL. Readiness stays fail-closed when the token or fleet capacity
16//! is unsettled, so the orchestrator's rollout deadline bounds that wait.
17
18/// The fleet drain token as stored at its well-known bucket key.
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub struct DrainToken {
21 pub node: String,
22 pub expires_ms: u64,
23 /// The live nodes' cold-work levels immediately before this donor began.
24 /// A released token keeps this snapshot for the replacement readiness gate.
25 pub restoration_baseline: Vec<RestorationBaseline>,
26}
27
28#[derive(Clone, Debug, PartialEq, Eq)]
29pub struct RestorationBaseline {
30 pub node: String,
31 pub restoring: u64,
32}
33
34/// Whether another node holds a live claim. A claim is live while
35/// `expires_ms > now_ms`, matching the node-lease liveness rule.
36pub fn held_by_another(existing: Option<&DrainToken>, node: &str, now_ms: u64) -> bool {
37 existing.is_some_and(|token| token.node != node && token.expires_ms > now_ms)
38}
39
40/// Whether a draining node may claim the token: it is absent, expired, or
41/// already its own, so a restarted logical node resumes its earlier claim.
42pub fn may_claim(existing: Option<&DrainToken>, node: &str, now_ms: u64) -> bool {
43 !held_by_another(existing, node, now_ms)
44}
45
46/// Why the first-readiness gate cannot open yet.
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub enum FleetUnsettled {
49 Drain,
50 Unreadable,
51 SelfUnpublished,
52 MemoryHeadroom { node: String },
53 Restoration { current: u64, maximum: u64 },
54 OwnershipSkew { current: usize, maximum: usize },
55}
56
57/// Whether the joining node can receive ownership during the next paced
58/// drain. The node contributes only when its lease is live, it advertises the
59/// handoff protocol, and it owns less than the busiest incumbent.
60pub fn joining_contributes_successor_capacity(
61 peers: &[crate::CapacityPeer],
62 node: &str,
63 now_ms: u64,
64) -> bool {
65 let live = peers
66 .iter()
67 .filter(|peer| peer.expires_ms > now_ms)
68 .collect::<Vec<_>>();
69 live.iter()
70 .find(|peer| peer.node == node)
71 .is_some_and(|joining| {
72 joining.paced_handoff
73 && live
74 .iter()
75 .filter(|peer| peer.node != node)
76 .map(|peer| peer.resident_cells)
77 .max()
78 .is_some_and(|maximum| joining.resident_cells < maximum)
79 })
80}
81
82/// Evaluate the drain token and the successor capacity published in live node
83/// leases. The joining node must publish itself. Every live peer must have
84/// memory headroom, each live node must return to its pre-donor restore
85/// baseline, and incumbent ownership must fit the successor-share envelope.
86pub fn fleet_status(
87 existing: Option<&DrainToken>,
88 node: &str,
89 now_ms: u64,
90 peers: &[crate::CapacityPeer],
91 max_restoring: u64,
92) -> Result<(), FleetUnsettled> {
93 if held_by_another(existing, node, now_ms) {
94 return Err(FleetUnsettled::Drain);
95 }
96
97 let live = peers
98 .iter()
99 .filter(|peer| peer.expires_ms > now_ms)
100 .collect::<Vec<_>>();
101 if !live.iter().any(|peer| peer.node == node) {
102 return Err(FleetUnsettled::SelfUnpublished);
103 }
104 if let Some(node) = live
105 .iter()
106 .filter(|peer| peer.pressured || peer.memory_headroom == Some(false))
107 .map(|peer| &peer.node)
108 .min()
109 {
110 return Err(FleetUnsettled::MemoryHeadroom { node: node.clone() });
111 }
112
113 // `restoring` includes ordinary cold activations, and their healthy level
114 // can be nonzero under continuous load. With no token there was no donor,
115 // so there is no rollout recovery backlog to gate. A donor snapshots the
116 // healthy level before it releases ownership. Its replacement gets one
117 // local activation budget of slack above each node's baseline; anything
118 // more must settle before the fleet spends another donor. An older token
119 // has an empty snapshot and therefore retains the conservative zero
120 // baseline during a mixed-version rollout.
121 let blocked_restoration = existing.and_then(|token| {
122 live.iter()
123 .filter_map(|peer| {
124 let baseline = token
125 .restoration_baseline
126 .iter()
127 .find(|baseline| baseline.node == peer.node)
128 .map_or(0, |baseline| baseline.restoring);
129 let maximum = baseline.saturating_add(max_restoring);
130 (peer.restoring > maximum).then_some((&peer.node, peer.restoring, maximum))
131 })
132 .min_by(|left, right| left.0.cmp(right.0))
133 });
134 if let Some((_, current, maximum)) = blocked_restoration {
135 return Err(FleetUnsettled::Restoration { current, maximum });
136 }
137
138 // A paced joining node publishes its peer endpoint before readiness and
139 // accepts ownership-only handoffs without restoring a runtime. When that
140 // node holds less ownership than the busiest incumbent, it is usable
141 // successor capacity for the next donor. Requiring the incumbents to
142 // rebalance first creates a closed loop: idle fleets move ownership only
143 // during a handoff, while the orchestrator waits for readiness before it
144 // starts that handoff.
145 let joining_can_absorb_skew = joining_contributes_successor_capacity(peers, node, now_ms);
146
147 // An unpaced or already-full joining node cannot repair ownership during
148 // the next drain. Its incumbents must therefore remain within one equal
149 // successor share above their mean.
150 let incumbents = live
151 .iter()
152 .filter(|peer| peer.node != node)
153 .collect::<Vec<_>>();
154 let count = incumbents.len();
155 if count > 1 {
156 let total = incumbents
157 .iter()
158 .fold(0_usize, |sum, peer| sum.saturating_add(peer.resident_cells));
159 let count = count as u128;
160 let numerator = (total as u128).saturating_mul(count.saturating_add(1));
161 let denominator = count.saturating_mul(count);
162 let maximum = numerator
163 .saturating_add(denominator - 1)
164 .checked_div(denominator)
165 .unwrap_or_default()
166 .min(usize::MAX as u128) as usize;
167 let current = incumbents
168 .iter()
169 .map(|peer| peer.resident_cells)
170 .max()
171 .unwrap_or_default();
172 if current > maximum && !joining_can_absorb_skew {
173 return Err(FleetUnsettled::OwnershipSkew { current, maximum });
174 }
175 }
176 Ok(())
177}