Diffinery

homeflare/celldpublic

celld/crates/logic/drain.rs
154 lines · 5.9 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. Correctness never depends on it: a donor that
14//! cannot claim it within a bounded wait proceeds unserialized, a fresh
15//! node's gate falls open after a bounded wait, and a dead holder's claim
16//! lapses by TTL. Every failure path degrades to the unserialized behavior
17//! that existed before the token, never to something worse.
18
19/// The fleet drain token as stored at its well-known bucket key.
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub struct DrainToken {
22 pub node: String,
23 pub expires_ms: u64,
24}
25
26/// Whether another node holds a live claim. A claim is live while
27/// `expires_ms > now_ms`, matching the node-lease liveness rule.
28pub fn held_by_another(existing: Option<&DrainToken>, node: &str, now_ms: u64) -> bool {
29 existing.is_some_and(|token| token.node != node && token.expires_ms > now_ms)
30}
31
32/// Whether a draining node may claim the token: it is absent, expired, or
33/// already its own, so a restarted logical node resumes its earlier claim.
34pub fn may_claim(existing: Option<&DrainToken>, node: &str, now_ms: u64) -> bool {
35 !held_by_another(existing, node, now_ms)
36}
37
38/// Why the first-readiness gate cannot open yet.
39#[derive(Clone, Debug, PartialEq, Eq)]
40pub enum FleetUnsettled {
41 Drain,
42 Unreadable,
43 SelfUnpublished,
44 MemoryHeadroom { node: String },
45 Restoration { current: u64, maximum: u64 },
46 OwnershipSkew { current: usize, maximum: usize },
47}
48
49/// Whether the joining node can receive ownership during the next paced
50/// drain. The node contributes only when its lease is live, it advertises the
51/// handoff protocol, and it owns less than the busiest incumbent.
52pub fn joining_contributes_successor_capacity(
53 peers: &[crate::CapacityPeer],
54 node: &str,
55 now_ms: u64,
56) -> bool {
57 let live = peers
58 .iter()
59 .filter(|peer| peer.expires_ms > now_ms)
60 .collect::<Vec<_>>();
61 live.iter()
62 .find(|peer| peer.node == node)
63 .is_some_and(|joining| {
64 joining.paced_handoff
65 && live
66 .iter()
67 .filter(|peer| peer.node != node)
68 .map(|peer| peer.resident_cells)
69 .max()
70 .is_some_and(|maximum| joining.resident_cells < maximum)
71 })
72}
73
74/// Evaluate the drain token and the successor capacity published in live node
75/// leases. The joining node must publish itself. Every live peer must have
76/// memory headroom, the fleet restore backlog must be bounded, and incumbent
77/// ownership must fit the successor-share envelope.
78pub fn fleet_status(
79 existing: Option<&DrainToken>,
80 node: &str,
81 now_ms: u64,
82 peers: &[crate::CapacityPeer],
83 max_restoring: u64,
84) -> Result<(), FleetUnsettled> {
85 if held_by_another(existing, node, now_ms) {
86 return Err(FleetUnsettled::Drain);
87 }
88
89 let live = peers
90 .iter()
91 .filter(|peer| peer.expires_ms > now_ms)
92 .collect::<Vec<_>>();
93 if !live.iter().any(|peer| peer.node == node) {
94 return Err(FleetUnsettled::SelfUnpublished);
95 }
96 if let Some(node) = live
97 .iter()
98 .filter(|peer| peer.pressured || peer.memory_headroom == Some(false))
99 .map(|peer| &peer.node)
100 .min()
101 {
102 return Err(FleetUnsettled::MemoryHeadroom { node: node.clone() });
103 }
104
105 let restoring = live
106 .iter()
107 .fold(0_u64, |sum, peer| sum.saturating_add(peer.restoring));
108 if restoring > max_restoring {
109 return Err(FleetUnsettled::Restoration {
110 current: restoring,
111 maximum: max_restoring,
112 });
113 }
114
115 // A paced joining node publishes its peer endpoint before readiness and
116 // accepts ownership-only handoffs without restoring a runtime. When that
117 // node holds less ownership than the busiest incumbent, it is usable
118 // successor capacity for the next donor. Requiring the incumbents to
119 // rebalance first creates a closed loop: idle fleets move ownership only
120 // during a handoff, while the orchestrator waits for readiness before it
121 // starts that handoff.
122 let joining_can_absorb_skew = joining_contributes_successor_capacity(peers, node, now_ms);
123
124 // An unpaced or already-full joining node cannot repair ownership during
125 // the next drain. Its incumbents must therefore remain within one equal
126 // successor share above their mean.
127 let incumbents = live
128 .iter()
129 .filter(|peer| peer.node != node)
130 .collect::<Vec<_>>();
131 let count = incumbents.len();
132 if count > 1 {
133 let total = incumbents
134 .iter()
135 .fold(0_usize, |sum, peer| sum.saturating_add(peer.resident_cells));
136 let count = count as u128;
137 let numerator = (total as u128).saturating_mul(count.saturating_add(1));
138 let denominator = count.saturating_mul(count);
139 let maximum = numerator
140 .saturating_add(denominator - 1)
141 .checked_div(denominator)
142 .unwrap_or_default()
143 .min(usize::MAX as u128) as usize;
144 let current = incumbents
145 .iter()
146 .map(|peer| peer.resident_cells)
147 .max()
148 .unwrap_or_default();
149 if current > maximum && !joining_can_absorb_skew {
150 return Err(FleetUnsettled::OwnershipSkew { current, maximum });
151 }
152 }
153 Ok(())
154}