| 1 | //! Alarm-wake entry reconciliation, sans-IO — plus the wake key scheme. |
| 2 | //! |
| 3 | //! `WakeCore`'s `decide` is a pure transition; `reconcile` drives it against an |
| 4 | //! `ObjectStore` port, so the identical logic runs against real S3 in production |
| 5 | //! (`crate::wake::WakeFlusher` wraps it) or any other `ObjectStore`. The key |
| 6 | //! scheme (`entry_key` / `parse_entry_key`) lives here so both sides share one |
| 7 | //! definition. |
| 8 | use super::Ms; |
| 9 | use super::ObjectStore; |
| 10 | use super::StoreError; |
| 11 | use std::collections::HashMap; |
| 12 | |
| 13 | /// Civil date from days since 1970-01-01 (Howard Hinnant's algorithm). |
| 14 | fn civil_from_days(z: i64) -> (i64, u32, u32) { |
| 15 | let z = z + 719_468; |
| 16 | let era = if z >= 0 { z } else { z - 146_096 } / 146_097; |
| 17 | let doe = z - era * 146_097; |
| 18 | let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; |
| 19 | let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); |
| 20 | let mp = (5 * doy + 2) / 153; |
| 21 | let d = (doy - (153 * mp + 2) / 5 + 1) as u32; |
| 22 | let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; |
| 23 | (yoe + era * 400 + i64::from(m <= 2), m, d) |
| 24 | } |
| 25 | |
| 26 | /// The time bucket a due timestamp falls in: minute precision, UTC, |
| 27 | /// lexicographically ordered so the waker LISTs due buckets in order. |
| 28 | fn minute_bucket(due_ms: i64) -> String { |
| 29 | let mins = due_ms.div_euclid(60_000); |
| 30 | let (y, mo, d) = civil_from_days(mins.div_euclid(1440)); |
| 31 | let m = mins.rem_euclid(1440); |
| 32 | format!("{y:04}-{mo:02}-{d:02}T{:02}:{:02}", m / 60, m % 60) |
| 33 | } |
| 34 | |
| 35 | pub fn entry_key(due_ms: i64, cell: &str) -> String { |
| 36 | format!("wake/{}/{}", minute_bucket(due_ms), cell) |
| 37 | } |
| 38 | |
| 39 | fn days_from_civil(y: i64, m: u32, d: u32) -> i64 { |
| 40 | let y = y - i64::from(m <= 2); |
| 41 | let era = if y >= 0 { y } else { y - 399 } / 400; |
| 42 | let yoe = y - era * 400; |
| 43 | let mp = i64::from(if m > 2 { m - 3 } else { m + 9 }); |
| 44 | let doy = (153 * mp + 2) / 5 + i64::from(d) - 1; |
| 45 | era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468 |
| 46 | } |
| 47 | |
| 48 | /// Inverse of `entry_key`: (due minute floor in ms, cell scope). |
| 49 | pub fn parse_entry_key(key: &str) -> Option<(i64, String)> { |
| 50 | let rest = key.strip_prefix("wake/")?; |
| 51 | let (minute, cell) = rest.split_at(rest.char_indices().nth(16)?.0); |
| 52 | let cell = cell.strip_prefix('/')?; |
| 53 | let y: i64 = minute.get(0..4)?.parse().ok()?; |
| 54 | let mo: u32 = minute.get(5..7)?.parse().ok()?; |
| 55 | let d: u32 = minute.get(8..10)?.parse().ok()?; |
| 56 | let h: i64 = minute.get(11..13)?.parse().ok()?; |
| 57 | let mi: i64 = minute.get(14..16)?.parse().ok()?; |
| 58 | if minute.get(4..5)? != "-" || minute.get(10..11)? != "T" { |
| 59 | return None; |
| 60 | } |
| 61 | let mins = days_from_civil(y, mo, d) * 1440 + h * 60 + mi; |
| 62 | Some((mins * 60_000, cell.to_string())) |
| 63 | } |
| 64 | |
| 65 | /// What the bucket needs for one cell given its committed alarm — the pure |
| 66 | /// transition's output, performed by `reconcile`. |
| 67 | pub enum Op { |
| 68 | Put { key: String, due_ms: Ms }, |
| 69 | Delete { key: String }, |
| 70 | } |
| 71 | |
| 72 | /// What the bucket is believed to hold for one cell. |
| 73 | struct Entry { |
| 74 | due_ms: Ms, |
| 75 | key: String, |
| 76 | /// True once this core PUT the object and saw it succeed. An adopted entry |
| 77 | /// is believed-present but unproven: it may be deleted when its alarm is |
| 78 | /// consumed, but may never satisfy the fail-closed eviction gate. |
| 79 | verified: bool, |
| 80 | /// A consume-delete for this exact key has been DECIDED but not yet |
| 81 | /// performed. The executor's delete is asynchronous, and in that window |
| 82 | /// an arm must not ride on an entry that is about to vanish — that race |
| 83 | /// acked alarms with no durable entry (the SIGKILL deep-gate failure). |
| 84 | /// An arm during the window cancels the delete instead. |
| 85 | delete_pending: bool, |
| 86 | } |
| 87 | |
| 88 | /// The reified `WakeFlusher`: owned state, no lock, no I/O. |
| 89 | #[derive(Default)] |
| 90 | pub struct WakeCore { |
| 91 | flushed: HashMap<String, Entry>, |
| 92 | } |
| 93 | |
| 94 | impl WakeCore { |
| 95 | pub fn new() -> Self { |
| 96 | Self::default() |
| 97 | } |
| 98 | |
| 99 | /// Arm-time decision: the PUT that must land before this arm is acked to |
| 100 | /// the application, or `None` when the durable bound already covers it. A |
| 101 | /// proven entry at the same or an EARLIER minute suffices — a stale-early |
| 102 | /// entry costs one spurious wake, never a lost one — so recurring re-arms |
| 103 | /// within a covered minute and postponements are free; only tightening |
| 104 | /// pays the synchronous PUT. |
| 105 | pub fn arm(&mut self, cell: &str, next_alarm_ms: Ms) -> Option<Op> { |
| 106 | if next_alarm_ms < 0 { |
| 107 | return None; // deletes are never synchronous |
| 108 | } |
| 109 | let want = entry_key(next_alarm_ms, cell); |
| 110 | match self.flushed.get_mut(cell) { |
| 111 | // Riding on an entry a consume is about to delete would ack an |
| 112 | // alarm that ends up entryless. Cancel that delete instead: this |
| 113 | // arm now owns the entry, and `take_delete` will refuse it. |
| 114 | Some(e) if e.verified && e.key <= want && e.delete_pending => { |
| 115 | e.delete_pending = false; |
| 116 | if e.key == want { |
| 117 | None |
| 118 | } else { |
| 119 | // The entry is stale-early: keep it (it still covers) but |
| 120 | // re-assert at the wanted key so coverage is exact and the |
| 121 | // cancelled delete cannot strand a later postponement. |
| 122 | Some(Op::Put { key: want, due_ms: next_alarm_ms }) |
| 123 | } |
| 124 | } |
| 125 | Some(e) if e.verified && e.key <= want => None, |
| 126 | _ => Some(Op::Put { key: want, due_ms: next_alarm_ms }), |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | /// Pure transition — byte-for-byte `WakeFlusher::ops`. The entry key, not |
| 131 | /// the exact due time, is an entry's identity: two alarms in one minute |
| 132 | /// share it. |
| 133 | /// |
| 134 | /// Ordering: a moved entry PUTs the new key before deleting the old one, |
| 135 | /// so no schedule point leaves an armed alarm entryless — a crash between |
| 136 | /// the two ops strands one extra entry (one spurious wake), never zero. |
| 137 | /// |
| 138 | /// `consume_durable` gates the final delete of a consumed alarm: false |
| 139 | /// while the consuming commit is not yet replicated, in which case the |
| 140 | /// entry must outlive the local commit — deleting it and then losing the |
| 141 | /// commit to the replication lag would leave replicated truth armed with |
| 142 | /// no entry, the one unrecoverable state. |
| 143 | pub fn decide( |
| 144 | &mut self, |
| 145 | cell: &str, |
| 146 | next_alarm_ms: Ms, |
| 147 | consume_durable: bool, |
| 148 | ) -> Vec<Op> { |
| 149 | if next_alarm_ms < 0 { |
| 150 | return match self.flushed.get_mut(cell) { |
| 151 | Some(e) if consume_durable => { |
| 152 | // Arm the guard: an arm before this delete lands cancels |
| 153 | // it, and `take_delete` re-checks at execution time. |
| 154 | e.delete_pending = true; |
| 155 | vec![Op::Delete { key: e.key.clone() }] |
| 156 | } |
| 157 | _ => vec![], |
| 158 | }; |
| 159 | } |
| 160 | let held = self.flushed.get(cell); |
| 161 | let want = entry_key(next_alarm_ms, cell); |
| 162 | match held { |
| 163 | None => vec![Op::Put { key: want, due_ms: next_alarm_ms }], |
| 164 | Some(e) if e.key != want => vec![ |
| 165 | Op::Put { key: want.clone(), due_ms: next_alarm_ms }, |
| 166 | Op::Delete { key: e.key.clone() }, |
| 167 | ], |
| 168 | // adopted but never proven: assert it so the cell can hibernate |
| 169 | Some(e) if !e.verified => { |
| 170 | vec![Op::Put { key: want, due_ms: next_alarm_ms }] |
| 171 | } |
| 172 | Some(_) => vec![], |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | /// Take responsibility for the entry a restored alarm implies. Without |
| 177 | /// this, a cell revived anywhere but the process that hibernated it has no |
| 178 | /// record to delete from: its entry outlives the alarm and re-wakes the |
| 179 | /// cell on every lease lapse. |
| 180 | pub fn adopt(&mut self, cell: &str, due_ms: Ms) { |
| 181 | if due_ms < 0 { |
| 182 | return; |
| 183 | } |
| 184 | self.flushed.entry(cell.to_string()).or_insert_with(|| Entry { |
| 185 | due_ms, |
| 186 | key: entry_key(due_ms, cell), |
| 187 | verified: false, |
| 188 | delete_pending: false, |
| 189 | }); |
| 190 | } |
| 191 | |
| 192 | /// Is this exact committed alarm durably covered by a proven entry? The |
| 193 | /// fail-closed gate: eviction of an alarm-bearing cell requires it. |
| 194 | pub fn covered(&self, cell: &str, next_alarm_ms: Ms) -> bool { |
| 195 | self.flushed |
| 196 | .get(cell) |
| 197 | .is_some_and(|e| e.verified && e.key == entry_key(next_alarm_ms, cell)) |
| 198 | } |
| 199 | |
| 200 | /// Entries whose cells this node hibernated and whose due time has arrived. |
| 201 | /// Sorted, unlike production's `HashMap` walk, so the schedule is |
| 202 | /// reproducible — determinism the sans-IO core owes its executor. |
| 203 | pub fn due_cells(&self, now_ms: Ms) -> Vec<String> { |
| 204 | let mut due: Vec<String> = self |
| 205 | .flushed |
| 206 | .iter() |
| 207 | .filter(|(_, e)| e.due_ms <= now_ms) |
| 208 | .map(|(cell, _)| cell.clone()) |
| 209 | .collect(); |
| 210 | due.sort(); |
| 211 | due |
| 212 | } |
| 213 | |
| 214 | pub fn tracks(&self, cell: &str) -> bool { |
| 215 | self.flushed.contains_key(cell) |
| 216 | } |
| 217 | |
| 218 | /// A PUT landed: the entry is now proven present. Called by the celld |
| 219 | /// binary's async executor (`WakeFlusher`) after a successful S3 PUT — a |
| 220 | /// separate crate, so this is `pub`. |
| 221 | pub fn confirm_put(&mut self, cell: &str, due_ms: Ms, key: String) { |
| 222 | self.flushed.insert( |
| 223 | cell.to_string(), |
| 224 | Entry { due_ms, key, verified: true, delete_pending: false }, |
| 225 | ); |
| 226 | } |
| 227 | |
| 228 | /// Immediately before performing a consume-delete: is it still wanted? |
| 229 | /// False when an arm rode in during the async window and cancelled it — |
| 230 | /// performing the delete then would strand that acked alarm. |
| 231 | pub fn take_delete(&mut self, cell: &str, key: &str) -> bool { |
| 232 | match self.flushed.get_mut(cell) { |
| 233 | Some(e) if e.key == key && e.delete_pending => { |
| 234 | e.delete_pending = false; |
| 235 | true |
| 236 | } |
| 237 | // No entry (already retired) or a different key: the move-delete |
| 238 | // path, which is always safe — a new entry was PUT first. |
| 239 | None => true, |
| 240 | Some(e) => e.key != key, |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | /// Stop tracking this cell — after a delete, or when a wake resolved to a |
| 245 | /// remote owner and its alarm is no longer ours. |
| 246 | pub fn forget(&mut self, cell: &str) { |
| 247 | self.flushed.remove(cell); |
| 248 | } |
| 249 | |
| 250 | /// A delete of `key` was performed. Forget the cell only if that key is |
| 251 | /// still the tracked entry: with put-before-delete ordering, a moved |
| 252 | /// entry's confirm already replaced the tracked key, and deleting the old |
| 253 | /// key must not drop belief in the new one. |
| 254 | pub fn retire(&mut self, cell: &str, key: &str) { |
| 255 | if self.flushed.get(cell).is_some_and(|e| e.key == key) { |
| 256 | self.flushed.remove(cell); |
| 257 | } |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | /// The sweep executor's per-cell hint decisions, shared with production. |
| 262 | /// |
| 263 | /// A cell revived by another process carries a wake entry this core never |
| 264 | /// PUT; the activation hint (the alarm it restored with) is adopted so a |
| 265 | /// consume deletes that entry instead of orphaning it. The hint is consumed |
| 266 | /// EXACTLY ONCE: once the consumed cell is no longer tracked, a still-latched |
| 267 | /// hint re-adopts a phantom entry every cycle and re-deletes it forever — |
| 268 | /// the op-quiescence violation `sweep_cell`'s test pins. |
| 269 | pub fn should_adopt_hint(tracks: bool, hint_ms: Ms) -> bool { |
| 270 | !tracks && hint_ms >= 0 |
| 271 | } |
| 272 | |
| 273 | /// After the cycle's ops ran: is the activation hint spent? True exactly when |
| 274 | /// the committed alarm is consumed and nothing is tracked anymore. |
| 275 | pub fn hint_consumed(mirror_ms: Ms, tracks_after: bool) -> bool { |
| 276 | mirror_ms < 0 && !tracks_after |
| 277 | } |
| 278 | |
| 279 | /// May this node take the singleton waker-role lease — because it already holds |
| 280 | /// it, or the current holder's lease has expired? An exactly-expired lease MUST |
| 281 | /// be claimable (`<=`, not `<`): the waker is a SINGLE role, so a claim that |
| 282 | /// stalls on the boundary leaves every hibernated cell's alarm unwoken until |
| 283 | /// some other node happens to reclaim. |
| 284 | pub fn waker_may_claim(held_by_us: bool, expires_ms: Ms, now_ms: Ms) -> bool { |
| 285 | held_by_us || expires_ms <= now_ms |
| 286 | } |
| 287 | |
| 288 | /// One maintenance cycle for one cell — the sans-IO twin of the production |
| 289 | /// flush loop. Returns the updated activation hint (`-1` once consumed). |
| 290 | pub fn sweep_cell<S: ObjectStore>( |
| 291 | core: &mut WakeCore, |
| 292 | store: &mut S, |
| 293 | cell: &str, |
| 294 | mirror_ms: Ms, |
| 295 | hint_ms: Ms, |
| 296 | consume_durable: bool, |
| 297 | ) -> Ms { |
| 298 | if should_adopt_hint(core.tracks(cell), hint_ms) { |
| 299 | core.adopt(cell, hint_ms); |
| 300 | } |
| 301 | reconcile(core, store, cell, mirror_ms, consume_durable); |
| 302 | if hint_consumed(mirror_ms, core.tracks(cell)) { |
| 303 | -1 |
| 304 | } else { |
| 305 | hint_ms |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | /// Reconcile one cell against the store — the sans-IO executor for wake. This |
| 310 | /// is `WakeFlusher::reconcile` with `aws_sdk_s3::Client` replaced by an |
| 311 | /// `ObjectStore` port: identical control flow, two backends. Failed PUTs keep |
| 312 | /// local state unchanged so the next tick retries (an entry may be late, never |
| 313 | /// silently absent); failed deletes drop matching state anyway — a stale |
| 314 | /// entry is one spurious wake, the cheaper error. |
| 315 | pub fn reconcile<S: ObjectStore>( |
| 316 | core: &mut WakeCore, |
| 317 | store: &mut S, |
| 318 | cell: &str, |
| 319 | next_alarm_ms: Ms, |
| 320 | consume_durable: bool, |
| 321 | ) { |
| 322 | for op in core.decide(cell, next_alarm_ms, consume_durable) { |
| 323 | match op { |
| 324 | Op::Put { key, due_ms } => { |
| 325 | let body = format!("{{\"cell\":{cell:?},\"due_ms\":{due_ms}}}"); |
| 326 | match store.put(&key, body.as_bytes()) { |
| 327 | Ok(_) => core.confirm_put(cell, due_ms, key), |
| 328 | // A later Delete in this batch depends on this PUT: with |
| 329 | // the new entry absent, deleting the old one would leave |
| 330 | // the armed alarm entryless. Abort; the next tick retries. |
| 331 | Err(StoreError::Precondition | StoreError::Transient) => return, |
| 332 | } |
| 333 | } |
| 334 | Op::Delete { key } => { |
| 335 | // Re-check under the core's state: an arm may have cancelled |
| 336 | // this delete while it was queued. |
| 337 | if core.take_delete(cell, &key) { |
| 338 | let _ = store.delete(&key); |
| 339 | core.retire(cell, &key); |
| 340 | } |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | } |