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