Diffinery

homeflare/celldpublic

413 lines · 16.5 KBRaw History
1//! Alarm-wake entry reconciliation, sans-IO — plus the wake key scheme.
2//!
3//! `WakeCore`'s `decide` is a pure transition; [`Reconcile`] holds the
4//! ordering rules an executor must obey while performing it. Any executor —
5//! production's async S3 flusher or a deterministic fake — asks for steps and
6//! reports outcomes, so the rules cannot diverge between them. The key scheme
7//! (`entry_key` / `parse_entry_key`) lives here so both sides share one
8//! definition.
9use super::Ms;
10use std::collections::HashMap;
11
12/// Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).
13fn civil_from_days(z: i64) -> (i64, u32, u32) {
14 let z = z + 719_468;
15 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
16 let doe = z - era * 146_097;
17 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
18 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
19 let mp = (5 * doy + 2) / 153;
20 let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
21 let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
22 (yoe + era * 400 + i64::from(m <= 2), m, d)
23}
24
25/// The time bucket a due timestamp falls in: minute precision, UTC,
26/// lexicographically ordered so the waker LISTs due buckets in order.
27fn minute_bucket(due_ms: i64) -> String {
28 let mins = due_ms.div_euclid(60_000);
29 let (y, mo, d) = civil_from_days(mins.div_euclid(1440));
30 let m = mins.rem_euclid(1440);
31 format!("{y:04}-{mo:02}-{d:02}T{:02}:{:02}", m / 60, m % 60)
32}
33
34pub fn entry_key(due_ms: i64, cell: &str) -> String {
35 format!("wake/{}/{}", minute_bucket(due_ms), cell)
36}
37
38fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
39 let y = y - i64::from(m <= 2);
40 let era = if y >= 0 { y } else { y - 399 } / 400;
41 let yoe = y - era * 400;
42 let mp = i64::from(if m > 2 { m - 3 } else { m + 9 });
43 let doy = (153 * mp + 2) / 5 + i64::from(d) - 1;
44 era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468
45}
46
47/// Inverse of `entry_key`: (due minute floor in ms, cell scope).
48pub fn parse_entry_key(key: &str) -> Option<(i64, String)> {
49 let rest = key.strip_prefix("wake/")?;
50 let (minute, cell) = rest.split_at(rest.char_indices().nth(16)?.0);
51 let cell = cell.strip_prefix('/')?;
52 let y: i64 = minute.get(0..4)?.parse().ok()?;
53 let mo: u32 = minute.get(5..7)?.parse().ok()?;
54 let d: u32 = minute.get(8..10)?.parse().ok()?;
55 let h: i64 = minute.get(11..13)?.parse().ok()?;
56 let mi: i64 = minute.get(14..16)?.parse().ok()?;
57 if minute.get(4..5)? != "-" || minute.get(10..11)? != "T" {
58 return None;
59 }
60 let mins = days_from_civil(y, mo, d) * 1440 + h * 60 + mi;
61 Some((mins * 60_000, cell.to_string()))
62}
63
64/// What the bucket needs for one cell given its committed alarm — the pure
65/// transition's output, performed by `reconcile`.
66pub enum Op {
67 Put { key: String, due_ms: Ms },
68 Delete { key: String },
69}
70
71/// What the bucket is believed to hold for one cell.
72struct Entry {
73 due_ms: Ms,
74 key: String,
75 /// True once this core PUT the object and saw it succeed. An adopted entry
76 /// is believed-present but unproven: it may be deleted when its alarm is
77 /// consumed, but may never satisfy the fail-closed eviction gate.
78 verified: bool,
79 /// A consume-delete for this exact key has been DECIDED but not yet
80 /// handed to the executor. In that window an arm must not ride on an
81 /// entry that is about to vanish — that race acked alarms with no
82 /// durable entry (the SIGKILL deep-gate failure). An arm during the
83 /// window cancels the delete instead.
84 delete_pending: bool,
85 /// The consume-delete was HANDED OUT (`take_delete` passed) and its
86 /// store call is in flight. Past this point nothing can cancel it, so
87 /// an arm must not ride on the entry either — it pays a PUT, which the
88 /// executor sequences after the delete settles (concurrent same-key
89 /// writes have no order at the store).
90 deleting: bool,
91}
92
93/// The reified `WakeFlusher`: owned state, no lock, no I/O.
94#[derive(Default)]
95pub struct WakeCore {
96 flushed: HashMap<String, Entry>,
97}
98
99impl WakeCore {
100 pub fn new() -> Self {
101 Self::default()
102 }
103
104 /// Arm-time decision: the PUT that must land before this arm is acked to
105 /// the application, or `None` when the durable bound already covers it. A
106 /// proven entry at the same or an EARLIER minute suffices — a stale-early
107 /// entry costs one spurious wake, never a lost one — so recurring re-arms
108 /// within a covered minute and postponements are free; only tightening
109 /// pays the synchronous PUT.
110 pub fn arm(&mut self, cell: &str, next_alarm_ms: Ms) -> Option<Op> {
111 if next_alarm_ms < 0 {
112 return None; // deletes are never synchronous
113 }
114 let want = entry_key(next_alarm_ms, cell);
115 match self.flushed.get_mut(cell) {
116 // The entry's delete is already on the wire: nothing can cancel
117 // it, so the entry covers nothing. Pay the PUT; the executor
118 // sequences it after the in-flight delete settles.
119 Some(e) if e.deleting => Some(Op::Put {
120 key: want,
121 due_ms: next_alarm_ms,
122 }),
123 // Riding on an entry a consume is about to delete would ack an
124 // alarm that ends up entryless. Cancel that delete instead: this
125 // arm now owns the entry, and `take_delete` will refuse it.
126 Some(e) if e.verified && e.key <= want && e.delete_pending => {
127 e.delete_pending = false;
128 if e.key == want {
129 None
130 } else {
131 // The entry is stale-early: keep it (it still covers) but
132 // re-assert at the wanted key so coverage is exact and the
133 // cancelled delete cannot strand a later postponement.
134 Some(Op::Put {
135 key: want,
136 due_ms: next_alarm_ms,
137 })
138 }
139 }
140 Some(e) if e.verified && e.key <= want => None,
141 _ => Some(Op::Put {
142 key: want,
143 due_ms: next_alarm_ms,
144 }),
145 }
146 }
147
148 /// Pure transition behind [`WakeCore::reconcile_plan`]. The entry key,
149 /// not the exact due time, is an entry's identity: two alarms in one
150 /// minute share it.
151 ///
152 /// Ordering: a moved entry PUTs the new key before deleting the old one,
153 /// so no schedule point leaves an armed alarm entryless — a crash between
154 /// the two ops strands one extra entry (one spurious wake), never zero.
155 ///
156 /// `consume_durable` gates the final delete of a consumed alarm: false
157 /// while the consuming commit is not yet replicated, in which case the
158 /// entry must outlive the local commit — deleting it and then losing the
159 /// commit to the replication lag would leave replicated truth armed with
160 /// no entry, the one unrecoverable state.
161 pub fn decide(&mut self, cell: &str, next_alarm_ms: Ms, consume_durable: bool) -> Vec<Op> {
162 if next_alarm_ms < 0 {
163 return match self.flushed.get_mut(cell) {
164 // `!deleting`: the delete is already on the wire; a second
165 // one would race the first for nothing.
166 Some(e) if consume_durable && !e.deleting => {
167 // Arm the guard: an arm before this delete lands cancels
168 // it, and `take_delete` re-checks at execution time.
169 e.delete_pending = true;
170 vec![Op::Delete { key: e.key.clone() }]
171 }
172 _ => vec![],
173 };
174 }
175 let held = self.flushed.get(cell);
176 let want = entry_key(next_alarm_ms, cell);
177 match held {
178 None => vec![Op::Put {
179 key: want,
180 due_ms: next_alarm_ms,
181 }],
182 // The tracked entry is vanishing: whatever its key, the armed
183 // alarm must be re-asserted. No delete op — one is in flight.
184 Some(e) if e.deleting => vec![Op::Put {
185 key: want,
186 due_ms: next_alarm_ms,
187 }],
188 Some(e) if e.key != want => vec![
189 Op::Put {
190 key: want.clone(),
191 due_ms: next_alarm_ms,
192 },
193 Op::Delete { key: e.key.clone() },
194 ],
195 // adopted but never proven: assert it so the cell can hibernate
196 Some(e) if !e.verified => {
197 vec![Op::Put {
198 key: want,
199 due_ms: next_alarm_ms,
200 }]
201 }
202 Some(_) => vec![],
203 }
204 }
205
206 /// Take responsibility for the entry a restored alarm implies. Without
207 /// this, a cell revived anywhere but the process that hibernated it has no
208 /// record to delete from: its entry outlives the alarm and re-wakes the
209 /// cell on every lease lapse.
210 pub fn adopt(&mut self, cell: &str, due_ms: Ms) {
211 if due_ms < 0 {
212 return;
213 }
214 self.flushed
215 .entry(cell.to_string())
216 .or_insert_with(|| Entry {
217 due_ms,
218 key: entry_key(due_ms, cell),
219 verified: false,
220 delete_pending: false,
221 deleting: false,
222 });
223 }
224
225 /// Is this exact committed alarm durably covered by a proven entry? The
226 /// fail-closed gate: eviction of an alarm-bearing cell requires it.
227 pub fn covered(&self, cell: &str, next_alarm_ms: Ms) -> bool {
228 self.flushed.get(cell).is_some_and(|e| {
229 e.verified && !e.deleting && e.key == entry_key(next_alarm_ms, cell)
230 })
231 }
232
233 /// Is a consume-delete for this cell's tracked entry on the wire? Any
234 /// PUT for the cell must be sequenced after it settles: the store gives
235 /// concurrent same-key writes no order, so a PUT racing the DELETE can
236 /// lose and leave a confirmed belief with no entry.
237 pub fn delete_in_flight(&self, cell: &str) -> bool {
238 self.flushed.get(cell).is_some_and(|e| e.deleting)
239 }
240
241 /// Entries whose cells this node hibernated and whose due time has arrived.
242 /// Sorted, unlike production's `HashMap` walk, so the schedule is
243 /// reproducible — determinism the sans-IO core owes its executor.
244 pub fn due_cells(&self, now_ms: Ms) -> Vec<String> {
245 let mut due: Vec<String> = self
246 .flushed
247 .iter()
248 .filter(|(_, e)| e.due_ms <= now_ms)
249 .map(|(cell, _)| cell.clone())
250 .collect();
251 due.sort();
252 due
253 }
254
255 pub fn tracks(&self, cell: &str) -> bool {
256 self.flushed.contains_key(cell)
257 }
258
259 /// A PUT landed: the entry is now proven present. Called by the celld
260 /// binary's async executor (`WakeFlusher`) after a successful S3 PUT — a
261 /// separate crate, so this is `pub`.
262 pub fn confirm_put(&mut self, cell: &str, due_ms: Ms, key: String) {
263 self.flushed.insert(
264 cell.to_string(),
265 Entry {
266 due_ms,
267 key,
268 verified: true,
269 delete_pending: false,
270 deleting: false,
271 },
272 );
273 }
274
275 /// Immediately before performing a consume-delete: is it still wanted?
276 /// False when an arm rode in during the async window and cancelled it —
277 /// performing the delete then would strand that acked alarm.
278 pub fn take_delete(&mut self, cell: &str, key: &str) -> bool {
279 match self.flushed.get_mut(cell) {
280 Some(e) if e.key == key && e.delete_pending => {
281 e.delete_pending = false;
282 e.deleting = true;
283 true
284 }
285 // No entry (already retired) or a different key: the move-delete
286 // path, which is always safe — a new entry was PUT first.
287 None => true,
288 Some(e) => e.key != key,
289 }
290 }
291
292 /// Stop tracking this cell — after a delete, or when a wake resolved to a
293 /// remote owner and its alarm is no longer ours.
294 pub fn forget(&mut self, cell: &str) {
295 self.flushed.remove(cell);
296 }
297
298 /// A delete of `key` was performed. Forget the cell only if that key is
299 /// still the tracked entry: with put-before-delete ordering, a moved
300 /// entry's confirm already replaced the tracked key, and deleting the old
301 /// key must not drop belief in the new one.
302 pub fn retire(&mut self, cell: &str, key: &str) {
303 if self.flushed.get(cell).is_some_and(|e| e.key == key) {
304 self.flushed.remove(cell);
305 }
306 }
307}
308
309/// One step of a reconcile the executor must perform.
310///
311/// `Put` carries its body so the entry's on-the-wire shape is decided once,
312/// here, rather than formatted independently by every executor.
313#[derive(Clone, Debug, PartialEq, Eq)]
314pub enum Step {
315 Put { key: String, due_ms: Ms, body: String },
316 Delete { key: String },
317}
318
319/// A reconcile in progress: the ordering rules, without the I/O.
320///
321/// The rules are small and both of them are easy to get wrong in a way
322/// nothing notices until an alarm is lost. A failed PUT abandons the rest of
323/// the batch, because a Delete later in it is only safe once the replacement
324/// entry exists. A Delete is re-checked against the core immediately before
325/// it is issued, because an arm may have cancelled it while it queued.
326///
327/// Holding them here means an executor cannot skip them: it asks for the next
328/// step and reports what happened. Production drives this against S3 and the
329/// simulation drives it against a fake store -- the same rules either way,
330/// which is the point.
331pub struct Reconcile {
332 cell: String,
333 steps: std::collections::VecDeque<Op>,
334}
335
336impl Reconcile {
337 /// The next step to perform, or `None` when the batch is finished.
338 ///
339 /// Deletes the core has since cancelled are dropped here rather than
340 /// handed out, so an executor that performs every step it is given is
341 /// automatically correct.
342 pub fn next(&mut self, core: &mut WakeCore) -> Option<Step> {
343 while let Some(op) = self.steps.pop_front() {
344 match op {
345 Op::Put { key, due_ms } => {
346 let cell = &self.cell;
347 return Some(Step::Put {
348 body: format!("{{\"cell\":{cell:?},\"due_ms\":{due_ms}}}"),
349 key,
350 due_ms,
351 });
352 }
353 Op::Delete { key } => {
354 if core.take_delete(&self.cell, &key) {
355 return Some(Step::Delete { key });
356 }
357 }
358 }
359 }
360 None
361 }
362
363 /// The PUT landed: the entry is present.
364 pub fn put_done(&mut self, core: &mut WakeCore, key: String, due_ms: Ms) {
365 core.confirm_put(&self.cell, due_ms, key);
366 }
367
368 /// The PUT did not land. Whatever remains depended on it.
369 pub fn put_failed(&mut self) {
370 self.steps.clear();
371 }
372
373 /// The DELETE landed, or the object was already gone.
374 pub fn delete_done(&mut self, core: &mut WakeCore, key: &str) {
375 core.retire(&self.cell, key);
376 }
377}
378
379impl WakeCore {
380 /// Plan the reconcile for one cell. See [`Reconcile`].
381 pub fn reconcile_plan(
382 &mut self,
383 cell: &str,
384 next_alarm_ms: Ms,
385 consume_durable: bool,
386 ) -> Reconcile {
387 Reconcile {
388 cell: cell.to_string(),
389 steps: self.decide(cell, next_alarm_ms, consume_durable).into(),
390 }
391 }
392}
393
394/// The sweep executor's per-cell hint decision, shared with production.
395///
396/// A cell revived by another process carries a wake entry this core never
397/// PUT; the activation hint (the alarm it restored with) is adopted so a
398/// consume deletes that entry instead of orphaning it. The hint is consumed
399/// EXACTLY ONCE: once the consumed cell is no longer tracked, a still-latched
400/// hint re-adopts a phantom entry every cycle and re-deletes it forever — an
401/// op-quiescence violation.
402pub fn should_adopt_hint(tracks: bool, hint_ms: Ms) -> bool {
403 !tracks && hint_ms >= 0
404}
405
406/// May this node take the singleton waker-role lease — because it already holds
407/// it, or the current holder's lease has expired? An exactly-expired lease MUST
408/// be claimable (`<=`, not `<`): the waker is a SINGLE role, so a claim that
409/// stalls on the boundary leaves every hibernated cell's alarm unwoken until
410/// some other node happens to reclaim.
411pub fn waker_may_claim(held_by_us: bool, expires_ms: Ms, now_ms: Ms) -> bool {
412 held_by_us || expires_ms <= now_ms
413}