Diffinery

homeflare/celldpublic

521 lines · 20.9 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).
16pub(crate) fn 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/// The due-minute floor a `YYYY-MM-DDTHH:MM` bucket names, in ms.
51fn parse_minute(minute: &str) -> Option<i64> {
52 if minute.len() != 16 {
53 return None;
54 }
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 Some((days_from_civil(y, mo, d) * 1440 + h * 60 + mi) * 60_000)
64}
65
66/// Inverse of `entry_key`: (due minute floor in ms, cell scope).
67///
68/// The scope is the remainder of a bucket key, so it is the one place a scope
69/// enters celld without passing a route. `due_scan` sends it as a `WakeHint`,
70/// which reaches the ownership CAS and `Effect::Restore` exactly as a request
71/// does, so it carries the same charset fence. An entry that fails the fence is
72/// ignored rather than repaired: it cannot name a cell this node can serve, and
73/// a bad entry left by an older node would otherwise replay on every tick.
74pub fn parse_entry_key(key: &str) -> Option<(i64, String)> {
75 let rest = key.strip_prefix("wake/")?;
76 let (minute, cell) = rest.split_at(rest.char_indices().nth(16)?.0);
77 let cell = cell.strip_prefix('/')?;
78 if !crate::cell::valid_cell_scope(cell) {
79 return None;
80 }
81 Some((parse_minute(minute)?, cell.to_string()))
82}
83
84/// The due minute a `wake/YYYY-MM-DDTHH:MM` bucket prefix names, in ms.
85///
86/// A delimiter listing answers with the buckets rather than the keys inside
87/// them, so the waker needs the minute without a cell attached to decide which
88/// buckets have come due.
89pub fn parse_minute_prefix(prefix: &str) -> Option<i64> {
90 parse_minute(prefix.strip_prefix("wake/")?)
91}
92
93/// What the bucket needs for one cell given its committed alarm — the pure
94/// transition's output, performed by `reconcile`.
95pub enum Op {
96 Put { key: String, due_ms: Ms },
97 Delete { key: String },
98}
99
100/// What the bucket is believed to hold for one cell.
101struct Entry {
102 due_ms: Ms,
103 key: String,
104 /// True once this core PUT the object and saw it succeed. An adopted entry
105 /// is believed-present but unproven: it may be deleted when its alarm is
106 /// consumed, but may never satisfy the fail-closed eviction gate.
107 verified: bool,
108 /// A consume-delete for this exact key has been DECIDED but not yet
109 /// handed to the executor. In that window an arm must not ride on an
110 /// entry that is about to vanish — that race acked alarms with no
111 /// durable entry. An arm during the
112 /// window cancels the delete instead.
113 delete_pending: bool,
114}
115
116/// The reified `WakeFlusher`: owned state, no lock, no I/O.
117#[derive(Default)]
118pub struct WakeCore {
119 flushed: HashMap<String, Entry>,
120 /// Keys whose DELETE was HANDED OUT (`take_delete` passed) and whose
121 /// store call has not reported back, per cell. Past the handout nothing
122 /// can cancel the delete, so an arm must not ride on the key either — it
123 /// pays a PUT, which the executor sequences after the delete settles
124 /// (concurrent same-key writes have no order at the store).
125 ///
126 /// Per cell rather than per entry: a MOVE-delete targets the key the
127 /// replacement PUT has already replaced in `flushed`, so the entry that
128 /// could carry the flag is gone by the time the delete is handed out. It
129 /// is exactly that delete which raced the arm PUT that re-tightened the
130 /// alarm back onto the old minute, deleting the entry of an alarm this
131 /// node had already acknowledged.
132 deleting: HashMap<String, HashSet<String>>,
133}
134
135impl WakeCore {
136 pub fn new() -> Self {
137 Self::default()
138 }
139
140 /// Is a DELETE of this exact key on the wire for this cell?
141 fn deleting_key(&self, cell: &str, key: &str) -> bool {
142 self.deleting
143 .get(cell)
144 .is_some_and(|keys| keys.contains(key))
145 }
146
147 /// Arm-time decision: the PUT that must land before this arm is acked to
148 /// the application, or `None` when the durable bound already covers it. A
149 /// proven entry at the same or an EARLIER minute suffices — a stale-early
150 /// entry costs one spurious wake, never a lost one — so recurring re-arms
151 /// within a covered minute and postponements are free; only tightening
152 /// pays the synchronous PUT.
153 pub fn arm(&mut self, cell: &str, next_alarm_ms: Ms) -> Option<Op> {
154 if next_alarm_ms < 0 {
155 return None; // deletes are never synchronous
156 }
157 let want = entry_key(next_alarm_ms, cell);
158 let vanishing = self
159 .flushed
160 .get(cell)
161 .is_some_and(|e| self.deleting_key(cell, &e.key));
162 match self.flushed.get_mut(cell) {
163 // The entry's delete is already on the wire: nothing can cancel
164 // it, so the entry covers nothing. Pay the PUT; the executor
165 // sequences it after the in-flight delete settles.
166 Some(_) if vanishing => Some(Op::Put {
167 key: want,
168 due_ms: next_alarm_ms,
169 }),
170 // Riding on an entry a consume is about to delete would ack an
171 // alarm that ends up entryless. Cancel that delete instead: this
172 // arm now owns the entry, and `take_delete` will refuse it.
173 Some(e) if e.verified && e.key <= want && e.delete_pending => {
174 e.delete_pending = false;
175 if e.key == want {
176 None
177 } else {
178 // The entry is stale-early: keep it (it still covers) but
179 // re-assert at the wanted key so coverage is exact and the
180 // cancelled delete cannot strand a later postponement.
181 Some(Op::Put {
182 key: want,
183 due_ms: next_alarm_ms,
184 })
185 }
186 }
187 Some(e) if e.verified && e.key <= want => None,
188 _ => Some(Op::Put {
189 key: want,
190 due_ms: next_alarm_ms,
191 }),
192 }
193 }
194
195 /// Pure transition behind [`WakeCore::reconcile_plan`]. The entry key,
196 /// not the exact due time, is an entry's identity: two alarms in one
197 /// minute share it.
198 ///
199 /// Ordering: a moved entry PUTs the new key before deleting the old one,
200 /// so no schedule point leaves an armed alarm entryless — a crash between
201 /// the two ops strands one extra entry (one spurious wake), never zero.
202 ///
203 /// `consume_durable` gates the final delete of a consumed alarm: false
204 /// while the consuming commit is not yet replicated, in which case the
205 /// entry must outlive the local commit — deleting it and then losing the
206 /// commit to the replication lag would leave replicated truth armed with
207 /// no entry, the one unrecoverable state.
208 pub fn decide(&mut self, cell: &str, next_alarm_ms: Ms, consume_durable: bool) -> Vec<Op> {
209 if next_alarm_ms < 0 {
210 let on_the_wire = self
211 .flushed
212 .get(cell)
213 .is_some_and(|e| self.deleting_key(cell, &e.key));
214 return match self.flushed.get_mut(cell) {
215 // `!on_the_wire`: the delete is already on the wire; a second
216 // one would race the first for nothing.
217 Some(e) if consume_durable && !on_the_wire => {
218 // Arm the guard: an arm before this delete lands cancels
219 // it, and `take_delete` re-checks at execution time.
220 e.delete_pending = true;
221 vec![Op::Delete { key: e.key.clone() }]
222 }
223 _ => vec![],
224 };
225 }
226 let held = self.flushed.get(cell);
227 let want = entry_key(next_alarm_ms, cell);
228 match held {
229 None => vec![Op::Put {
230 key: want,
231 due_ms: next_alarm_ms,
232 }],
233 // The tracked entry is vanishing: whatever its key, the armed
234 // alarm must be re-asserted. No delete op — one is in flight.
235 Some(e) if self.deleting_key(cell, &e.key) => vec![Op::Put {
236 key: want,
237 due_ms: next_alarm_ms,
238 }],
239 Some(e) if e.key != want => vec![
240 Op::Put {
241 key: want.clone(),
242 due_ms: next_alarm_ms,
243 },
244 Op::Delete { key: e.key.clone() },
245 ],
246 // adopted but never proven: assert it so the cell can be evicted
247 Some(e) if !e.verified => {
248 vec![Op::Put {
249 key: want,
250 due_ms: next_alarm_ms,
251 }]
252 }
253 Some(_) => vec![],
254 }
255 }
256
257 /// Take responsibility for the entry a restored alarm implies. Without
258 /// this, a cell revived anywhere but the process that evicted it has no
259 /// record to delete from: its entry outlives the alarm and re-wakes the
260 /// cell on every lease lapse.
261 pub fn adopt(&mut self, cell: &str, due_ms: Ms) {
262 if due_ms < 0 {
263 return;
264 }
265 self.flushed
266 .entry(cell.to_string())
267 .or_insert_with(|| Entry {
268 due_ms,
269 key: entry_key(due_ms, cell),
270 verified: false,
271 delete_pending: false,
272 });
273 }
274
275 /// Is this exact committed alarm durably covered by a proven entry? The
276 /// fail-closed gate: eviction of an alarm-bearing cell requires it.
277 pub fn covered(&self, cell: &str, next_alarm_ms: Ms) -> bool {
278 self.flushed.get(cell).is_some_and(|e| {
279 e.verified
280 && e.key == entry_key(next_alarm_ms, cell)
281 && !self.deleting_key(cell, &e.key)
282 })
283 }
284
285 /// Is any delete for this cell on the wire — a consume of the tracked
286 /// entry or a move-delete of a key it no longer tracks? Any PUT for the
287 /// cell must be sequenced after it settles: the store gives concurrent
288 /// same-key writes no order, so a PUT racing the DELETE can lose and
289 /// leave a confirmed belief with no entry.
290 ///
291 /// A caller that already knows its key must ask `key_delete_in_flight`
292 /// instead. This question is the conservative one, and only a caller
293 /// that cannot yet name its key needs it.
294 pub fn delete_in_flight(&self, cell: &str) -> bool {
295 self.deleting.get(cell).is_some_and(|keys| !keys.is_empty())
296 }
297
298 /// Is a delete of this exact key on the wire for this cell? The precise
299 /// question an arm can ask: only a delete of the key it is about to PUT
300 /// can race that PUT, so an arm gated on this waits for nothing else.
301 pub fn key_delete_in_flight(&self, cell: &str, key: &str) -> bool {
302 self.deleting_key(cell, key)
303 }
304
305 /// Entries whose cells this node evicted and whose due time has arrived.
306 /// Sorted, unlike production's `HashMap` walk, so the schedule is
307 /// reproducible — determinism the sans-IO core owes its executor.
308 pub fn due_cells(&self, now_ms: Ms) -> Vec<String> {
309 let mut due: Vec<String> = self
310 .flushed
311 .iter()
312 .filter(|(_, e)| e.due_ms <= now_ms)
313 .map(|(cell, _)| cell.clone())
314 .collect();
315 due.sort();
316 due
317 }
318
319 pub fn tracks(&self, cell: &str) -> bool {
320 self.flushed.contains_key(cell)
321 }
322
323 /// A PUT landed: the entry is now proven present. Called by the celld
324 /// binary's async executor (`WakeFlusher`) after a successful S3 PUT — a
325 /// separate crate, so this is `pub`.
326 pub fn confirm_put(&mut self, cell: &str, due_ms: Ms, key: String) {
327 self.flushed.insert(
328 cell.to_string(),
329 Entry {
330 due_ms,
331 key,
332 verified: true,
333 delete_pending: false,
334 },
335 );
336 }
337
338 /// Immediately before performing a delete: is it still wanted? False when
339 /// an arm rode in during the async window and cancelled it — performing
340 /// the delete then would strand that acked alarm.
341 ///
342 /// Every delete this answers for goes on the wire, so every one of them
343 /// is recorded: the move-delete below is safe only in the sense that the
344 /// replacement entry already exists, never in the sense that its key may
345 /// be written concurrently.
346 pub fn take_delete(&mut self, cell: &str, key: &str) -> bool {
347 let perform = match self.flushed.get_mut(cell) {
348 Some(e) if e.key == key && e.delete_pending => {
349 e.delete_pending = false;
350 true
351 }
352 // No entry (already retired) or a different key: the move-delete
353 // path, which is always safe — a new entry was PUT first.
354 None => true,
355 Some(e) => e.key != key,
356 };
357 if perform {
358 self.deleting
359 .entry(cell.to_string())
360 .or_default()
361 .insert(key.to_string());
362 }
363 perform
364 }
365
366 /// Stop tracking this cell — after a delete, or when a wake resolved to a
367 /// remote owner and its alarm is no longer ours.
368 pub fn forget(&mut self, cell: &str) {
369 self.flushed.remove(cell);
370 }
371
372 /// A delete of `key` settled — landed, or failed past its retries, which
373 /// is the same thing here: it is off the wire either way, and a PUT of
374 /// that key can no longer lose to it.
375 ///
376 /// Forget the cell only if that key is still the tracked entry: with
377 /// put-before-delete ordering, a moved entry's confirm already replaced
378 /// the tracked key, and deleting the old key must not drop belief in the
379 /// new one.
380 pub fn retire(&mut self, cell: &str, key: &str) {
381 if let Some(keys) = self.deleting.get_mut(cell) {
382 keys.remove(key);
383 if keys.is_empty() {
384 self.deleting.remove(cell);
385 }
386 }
387 if self.flushed.get(cell).is_some_and(|e| e.key == key) {
388 self.flushed.remove(cell);
389 }
390 }
391}
392
393/// One step of a reconcile the executor must perform.
394///
395/// `Put` carries its body so the entry's on-the-wire shape is decided once,
396/// here, rather than formatted independently by every executor.
397#[derive(Clone, Debug, PartialEq, Eq)]
398pub enum Step {
399 Put {
400 key: String,
401 due_ms: Ms,
402 body: String,
403 },
404 Delete {
405 key: String,
406 },
407}
408
409/// A reconcile in progress: the ordering rules, without the I/O.
410///
411/// The rules are small and both of them are easy to get wrong in a way
412/// nothing notices until an alarm is lost. A failed PUT abandons the rest of
413/// the batch, because a Delete later in it is only safe once the replacement
414/// entry exists. A Delete is re-checked against the core immediately before
415/// it is issued, because an arm may have cancelled it while it queued.
416///
417/// Holding them here means an executor cannot skip them: it asks for the next
418/// step and reports what happened. Production drives this against S3 and the
419/// simulation drives it against a fake store -- the same rules either way,
420/// which is the point.
421pub struct Reconcile {
422 cell: String,
423 steps: std::collections::VecDeque<Op>,
424}
425
426impl Reconcile {
427 /// The next step to perform, or `None` when the batch is finished.
428 ///
429 /// Deletes the core has since cancelled are dropped here rather than
430 /// handed out, so an executor that performs every step it is given is
431 /// automatically correct.
432 pub fn next(&mut self, core: &mut WakeCore) -> Option<Step> {
433 while let Some(op) = self.steps.pop_front() {
434 match op {
435 Op::Put { key, due_ms } => {
436 let cell = &self.cell;
437 return Some(Step::Put {
438 body: format!("{{\"cell\":{cell:?},\"due_ms\":{due_ms}}}"),
439 key,
440 due_ms,
441 });
442 }
443 Op::Delete { key } => {
444 if core.take_delete(&self.cell, &key) {
445 return Some(Step::Delete { key });
446 }
447 }
448 }
449 }
450 None
451 }
452
453 /// The PUT landed: the entry is present.
454 pub fn put_done(&mut self, core: &mut WakeCore, key: String, due_ms: Ms) {
455 core.confirm_put(&self.cell, due_ms, key);
456 }
457
458 /// The PUT did not land. Whatever remains depended on it.
459 pub fn put_failed(&mut self) {
460 self.steps.clear();
461 }
462
463 /// The DELETE landed, or the object was already gone.
464 pub fn delete_done(&mut self, core: &mut WakeCore, key: &str) {
465 core.retire(&self.cell, key);
466 }
467}
468
469impl WakeCore {
470 /// Plan the reconcile for one cell. See [`Reconcile`].
471 pub fn reconcile_plan(
472 &mut self,
473 cell: &str,
474 next_alarm_ms: Ms,
475 consume_durable: bool,
476 ) -> Reconcile {
477 Reconcile {
478 cell: cell.to_string(),
479 steps: self.decide(cell, next_alarm_ms, consume_durable).into(),
480 }
481 }
482}
483
484/// The sweep executor's per-cell hint decision, shared with production.
485///
486/// A cell revived by another process carries a wake entry this core never
487/// PUT; the activation hint (the alarm it restored with) is adopted so a
488/// consume deletes that entry instead of orphaning it. The hint is consumed
489/// EXACTLY ONCE: once the consumed cell is no longer tracked, a still-latched
490/// hint re-adopts a phantom entry every cycle and re-deletes it forever — an
491/// op-quiescence violation.
492pub fn should_adopt_hint(tracks: bool, hint_ms: Ms) -> bool {
493 !tracks && hint_ms >= 0
494}
495
496/// May this node take the singleton waker-role lease — because it already holds
497/// it, or the current holder's lease has expired? An exactly-expired lease MUST
498/// be claimable (`<=`, not `<`): the waker is a SINGLE role, so a claim that
499/// stalls on the boundary leaves every evicted cell's alarm unwoken until
500/// some other node happens to reclaim.
501pub fn waker_may_claim(held_by_us: bool, expires_ms: Ms, now_ms: Ms) -> bool {
502 held_by_us || expires_ms <= now_ms
503}
504
505/// The elected waker's decision for one due entry once it has read the
506/// cell's owner record: does this node need to send the `Fleet` hint?
507///
508/// A live owner fires its own alarms. A resident cell fires from the owner's
509/// timer, and a dormant one wakes from the owner's own due scan, which sends
510/// it an `Owned` hint. The elected waker's hint is for everything else: a
511/// cell nobody owns, a cell whose owner's lease has run out, and a cell this
512/// node owns itself. Hinting a live owner's cell risks nothing (the core never
513/// steals), but it costs the elected node an activation permit and an owner
514/// read per entry, for the whole fleet's due set, every tick.
515pub fn elected_hint_needed(owner: Option<&str>, node: &str, owner_live: bool) -> bool {
516 match owner {
517 None => true,
518 Some(owner) if owner == node => true,
519 Some(_) => !owner_live,
520 }
521}