Diffinery

homeflare/celldpublic

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