Diffinery

homeflare/celldpublic

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