| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! Decision core for the in-fleet replicated log tier (design stage; not |
| 4 | //! yet wired into the engine). |
| 5 | //! |
| 6 | //! One write-ahead log per node, streamed to a small follower ensemble. A |
| 7 | //! durable write acknowledges when every member holds it — write-all, |
| 8 | //! ack-all — and the bucket record `log/<node>.json` is the CAS-guarded |
| 9 | //! root of truth for membership, epoch, and the tiered-through offset. |
| 10 | //! Nothing here performs I/O: the executor feeds these decisions facts and |
| 11 | //! performs the returned intents. |
| 12 | //! |
| 13 | //! The safety rules, each load-bearing: |
| 14 | //! - a follower's (ensemble, epoch) view changes only with the record, |
| 15 | //! never on the leader's stream alone; |
| 16 | //! - a follower refuses appends at or below its persisted seal mark; |
| 17 | //! - reconfiguration force-tiers the open fragment through the new |
| 18 | //! fragment base before the CAS, so an empty joiner is covered entirely |
| 19 | //! by the bucket; |
| 20 | //! - recovery seals before it certifies, and certifies from a sealed |
| 21 | //! member only; |
| 22 | //! - the record is created before the first fleet-durable ack and never |
| 23 | //! deleted, so record absence proves the bucket is complete. |
| 24 | |
| 25 | use std::collections::BTreeMap; |
| 26 | use std::collections::BTreeSet; |
| 27 | |
| 28 | use crate::Epoch; |
| 29 | use crate::NodeId; |
| 30 | |
| 31 | pub type Offset = u64; |
| 32 | |
| 33 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 34 | pub enum LogState { |
| 35 | Open, |
| 36 | Recovering, |
| 37 | Sealed, |
| 38 | } |
| 39 | |
| 40 | /// `log/<node>.json`. Every mutation is a conditional write; the executor |
| 41 | /// must treat a lost CAS as anothers' turn, never retry blindly. |
| 42 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 43 | pub struct LogRecord { |
| 44 | pub epoch: Epoch, |
| 45 | pub ensemble: BTreeSet<NodeId>, |
| 46 | /// Offsets at or below this are durable in the bucket. |
| 47 | pub tiered: Offset, |
| 48 | pub state: LogState, |
| 49 | /// The node recovering this log while `state` is `Recovering`, and the |
| 50 | /// last instant it said so. A recovery reads every retained bundle of |
| 51 | /// the dead session, which takes minutes on a loaded fleet, and every |
| 52 | /// other node used to take the claim over after a fixed wait and repeat |
| 53 | /// the same gather: on 2026-09-03 three peers and the restarting node |
| 54 | /// fetched the same 209 bundles at once. A claimant that keeps its |
| 55 | /// heartbeat fresh is left alone; only a stale one is taken over. |
| 56 | pub claimant: Option<NodeId>, |
| 57 | pub claimed_ms: Option<u64>, |
| 58 | } |
| 59 | |
| 60 | /// Created before the first fleet-durable ack. The open fragment begins at |
| 61 | /// the bucket's current end, so every frame a member will ever be asked |
| 62 | /// about is above what the bucket already holds. |
| 63 | pub fn create_record(ensemble: BTreeSet<NodeId>, bucket_end: Offset) -> Option<LogRecord> { |
| 64 | if ensemble.is_empty() { |
| 65 | return None; |
| 66 | } |
| 67 | Some(LogRecord { |
| 68 | epoch: 1, |
| 69 | ensemble, |
| 70 | tiered: bucket_end, |
| 71 | state: LogState::Open, |
| 72 | claimant: None, |
| 73 | claimed_ms: None, |
| 74 | }) |
| 75 | } |
| 76 | |
| 77 | /// One follower's copy of one node log: the open fragment `(base, end]` at |
| 78 | /// its fragment epoch, plus the persisted seal mark. |
| 79 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 80 | pub struct FollowerLog { |
| 81 | pub fragment_epoch: Epoch, |
| 82 | pub base: Offset, |
| 83 | pub end: Offset, |
| 84 | /// Highest epoch sealed. Appends at or below it are refused forever. |
| 85 | pub sealed_to: Epoch, |
| 86 | } |
| 87 | |
| 88 | impl FollowerLog { |
| 89 | /// An empty joiner: covered by the bucket through `base`, holding |
| 90 | /// nothing. |
| 91 | pub fn join(fragment_epoch: Epoch, base: Offset) -> Self { |
| 92 | FollowerLog { |
| 93 | fragment_epoch, |
| 94 | base, |
| 95 | end: base, |
| 96 | sealed_to: 0, |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | /// Accept one frame. Refuses the wrong fragment epoch, anything at or |
| 101 | /// below the seal mark, and gaps — a fragment is contiguous or it is |
| 102 | /// not a fragment. |
| 103 | pub fn accept_append(&mut self, epoch: Epoch, offset: Offset) -> bool { |
| 104 | if epoch != self.fragment_epoch || epoch <= self.sealed_to || offset != self.end + 1 { |
| 105 | return false; |
| 106 | } |
| 107 | self.end = offset; |
| 108 | true |
| 109 | } |
| 110 | |
| 111 | /// Persist a seal through `epoch` and report the final contiguous end. |
| 112 | /// The fragment is frozen from here; write-all makes this one answer |
| 113 | /// sufficient to certify every acknowledged frame. |
| 114 | pub fn seal(&mut self, epoch: Epoch) -> Offset { |
| 115 | if epoch > self.sealed_to { |
| 116 | self.sealed_to = epoch; |
| 117 | } |
| 118 | self.end |
| 119 | } |
| 120 | |
| 121 | /// Drop frames the record already proves tiered. |
| 122 | pub fn truncate(&mut self, tiered: Offset) { |
| 123 | if tiered > self.base { |
| 124 | self.base = tiered; |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | /// The leader's believed (epoch, ensemble). Deliberately a belief: a fenced |
| 130 | /// leader still acts on it, and safety must come from seal marks and lost |
| 131 | /// CASes, not from wishful record reads on the ack path. |
| 132 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 133 | pub struct LeaderView { |
| 134 | pub epoch: Epoch, |
| 135 | pub ensemble: BTreeSet<NodeId>, |
| 136 | } |
| 137 | |
| 138 | /// Write-all, ack-all: `next` may acknowledge only when every ensemble |
| 139 | /// member has confirmed it at the leader's fragment epoch. `ends` carries |
| 140 | /// each member's confirmed contiguous end; a member missing from it has |
| 141 | /// confirmed nothing. |
| 142 | pub fn ack_fleet_allowed(view: &LeaderView, ends: &BTreeMap<NodeId, Offset>, next: Offset) -> bool { |
| 143 | !view.ensemble.is_empty() |
| 144 | && view |
| 145 | .ensemble |
| 146 | .iter() |
| 147 | .all(|member| ends.get(member).is_some_and(|end| *end >= next)) |
| 148 | } |
| 149 | |
| 150 | /// A reconfiguration the CAS may publish. `tier_through` must be durable in |
| 151 | /// the bucket before the CAS lands: the new members join empty, and the |
| 152 | /// bucket is the only thing covering their emptiness. |
| 153 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 154 | pub struct ReconfigPlan { |
| 155 | pub tier_through: Offset, |
| 156 | pub record: LogRecord, |
| 157 | } |
| 158 | |
| 159 | pub fn plan_reconfigure( |
| 160 | current: &LogRecord, |
| 161 | log_end: Offset, |
| 162 | ensemble: BTreeSet<NodeId>, |
| 163 | ) -> Option<ReconfigPlan> { |
| 164 | if current.state != LogState::Open || ensemble.is_empty() || ensemble == current.ensemble { |
| 165 | return None; |
| 166 | } |
| 167 | Some(ReconfigPlan { |
| 168 | tier_through: log_end, |
| 169 | record: LogRecord { |
| 170 | epoch: current.epoch + 1, |
| 171 | ensemble, |
| 172 | tiered: log_end, |
| 173 | state: LogState::Open, |
| 174 | claimant: None, |
| 175 | claimed_ms: None, |
| 176 | }, |
| 177 | }) |
| 178 | } |
| 179 | |
| 180 | /// Recovery step one: fence via the record. S3 is the root of truth, so |
| 181 | /// this CAS is what makes every later tiering or reconfiguration attempt by |
| 182 | /// the old leader fail. Sealing followers comes after, never before. |
| 183 | pub fn start_recovery(record: &LogRecord, claimant: &str, now_ms: u64) -> Option<LogRecord> { |
| 184 | if record.state != LogState::Open { |
| 185 | return None; |
| 186 | } |
| 187 | Some(LogRecord { |
| 188 | state: LogState::Recovering, |
| 189 | claimant: Some(claimant.to_string()), |
| 190 | claimed_ms: Some(now_ms), |
| 191 | ..record.clone() |
| 192 | }) |
| 193 | } |
| 194 | |
| 195 | /// Whether `claimant` owns the recovery in progress. |
| 196 | pub fn recovery_claimed_by(record: &LogRecord, claimant: &str) -> bool { |
| 197 | record.state == LogState::Recovering && record.claimant.as_deref() == Some(claimant) |
| 198 | } |
| 199 | |
| 200 | /// Whether another node's claim is fresh: its last heartbeat is younger |
| 201 | /// than `stale_after_ms`. A record from before claims carried a heartbeat |
| 202 | /// reads as stale, so an upgrade never waits on a claim it cannot judge. |
| 203 | pub fn recovery_claim_live(record: &LogRecord, now_ms: u64, stale_after_ms: u64) -> bool { |
| 204 | record.state == LogState::Recovering |
| 205 | && record.claimant.is_some() |
| 206 | && record |
| 207 | .claimed_ms |
| 208 | .is_some_and(|claimed| now_ms.saturating_sub(claimed) < stale_after_ms) |
| 209 | } |
| 210 | |
| 211 | /// The claimant's heartbeat. `None` when the claim is no longer this |
| 212 | /// node's: the recovery was taken over and this node must stop. |
| 213 | pub fn refresh_recovery(record: &LogRecord, claimant: &str, now_ms: u64) -> Option<LogRecord> { |
| 214 | if !recovery_claimed_by(record, claimant) { |
| 215 | return None; |
| 216 | } |
| 217 | Some(LogRecord { |
| 218 | claimed_ms: Some(now_ms), |
| 219 | ..record.clone() |
| 220 | }) |
| 221 | } |
| 222 | |
| 223 | /// Take a recovery over from a claimant whose heartbeat went stale. `None` |
| 224 | /// while the claim is live or the log is not recovering. |
| 225 | pub fn take_over_recovery( |
| 226 | record: &LogRecord, |
| 227 | claimant: &str, |
| 228 | now_ms: u64, |
| 229 | stale_after_ms: u64, |
| 230 | ) -> Option<LogRecord> { |
| 231 | if record.state != LogState::Recovering || recovery_claim_live(record, now_ms, stale_after_ms) { |
| 232 | return None; |
| 233 | } |
| 234 | Some(LogRecord { |
| 235 | claimant: Some(claimant.to_string()), |
| 236 | claimed_ms: Some(now_ms), |
| 237 | ..record.clone() |
| 238 | }) |
| 239 | } |
| 240 | |
| 241 | /// The certified cut: the final contiguous end of any sealed member, floored |
| 242 | /// at what is already tiered. Any one sealed member suffices for acked |
| 243 | /// frames (write-all); taking a longer end preserves acked-but-unconfirmed |
| 244 | /// frames, which is safe — delivering an unacknowledged write is allowed, |
| 245 | /// losing an acknowledged one is not. |
| 246 | pub fn certify(tiered: Offset, sealed_end: Offset) -> Offset { |
| 247 | tiered.max(sealed_end) |
| 248 | } |
| 249 | |
| 250 | /// Recovery final step: the certified tail is durable in the bucket, so the |
| 251 | /// record seals at the cut and every per-cell takeover may treat the bucket |
| 252 | /// as complete. |
| 253 | pub fn finish_recovery(record: &LogRecord, cert: Offset) -> Option<LogRecord> { |
| 254 | if record.state != LogState::Recovering { |
| 255 | return None; |
| 256 | } |
| 257 | Some(LogRecord { |
| 258 | tiered: cert, |
| 259 | state: LogState::Sealed, |
| 260 | claimant: None, |
| 261 | claimed_ms: None, |
| 262 | ..record.clone() |
| 263 | }) |
| 264 | } |
| 265 | |
| 266 | /// May a per-cell takeover of this node's cells treat the bucket as |
| 267 | /// complete? Absence is a proof, not a guess: the record is created before |
| 268 | /// the first fleet-durable ack and never deleted, so no record means the |
| 269 | /// node never acknowledged anything the bucket does not hold. |
| 270 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 271 | pub enum TakeoverGate { |
| 272 | BucketComplete, |
| 273 | RecoverFirst, |
| 274 | } |
| 275 | |
| 276 | pub fn takeover_gate(record: Option<&LogRecord>) -> TakeoverGate { |
| 277 | match record { |
| 278 | None => TakeoverGate::BucketComplete, |
| 279 | Some(record) if record.state == LogState::Sealed => TakeoverGate::BucketComplete, |
| 280 | Some(_) => TakeoverGate::RecoverFirst, |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | /// What the maintenance loop must do with its OWN session's record before |
| 285 | /// it may open a fleet ensemble. The record is keyed by (node, |
| 286 | /// generation), so the only record this session can ever read here is one |
| 287 | /// it wrote itself: absent on the session's first open, present for a |
| 288 | /// within-session reconfiguration. A predecessor session's record is a |
| 289 | /// dead session's record like any other, recovered by the sweep or the |
| 290 | /// takeover interlock, never stepped past here — which is what deleted the |
| 291 | /// RecoverFirst arm, the revive/reopen guard, and the recovery epoch pin. |
| 292 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 293 | pub enum MaintainStep { |
| 294 | /// No record yet: create one before the first fleet-durable ack. |
| 295 | CreateFresh, |
| 296 | /// Our open (or, after a failed close, sealed) record: step the epoch |
| 297 | /// and reopen with a fresh ensemble. |
| 298 | Reopen(Epoch), |
| 299 | /// Our own record is mid-recovery: a rival is fencing this session, |
| 300 | /// which can only mean our lease looks expired from where it stands. |
| 301 | /// Reopening would race its seal CAS — both outcomes are safe under |
| 302 | /// write-all plus the seal marks, but the churn buys nothing. Hold |
| 303 | /// this tick; the next pass finds Sealed and reopens, or our own |
| 304 | /// lease loss fences us first. |
| 305 | Wait, |
| 306 | } |
| 307 | |
| 308 | pub fn maintain_step(record: Option<&LogRecord>) -> MaintainStep { |
| 309 | match record { |
| 310 | None => MaintainStep::CreateFresh, |
| 311 | Some(record) if record.state == LogState::Recovering => MaintainStep::Wait, |
| 312 | Some(record) => MaintainStep::Reopen(record.epoch + 1), |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | /// The graceful shutdown's seal guard — the only seal producer besides |
| 317 | /// recovery. The record must still be Open at the closing shipper's |
| 318 | /// epoch, no batch may sit between capture and credit, and every shipped |
| 319 | /// frame must live in the PER-CELL layout: a sealed record tells every |
| 320 | /// future recovery there is nothing to gather, so credited bundle |
| 321 | /// coverage must never satisfy this guard — the bundle-resident acked |
| 322 | /// tail would be orphaned behind the seal. Refusal is always safe: an |
| 323 | /// Open record just means the next incarnation's recovery drains the |
| 324 | /// bundles. |
| 325 | pub fn graceful_seal_allowed( |
| 326 | record: &LogRecord, |
| 327 | epoch: Epoch, |
| 328 | batch_in_flight: bool, |
| 329 | per_cell_complete: bool, |
| 330 | ) -> bool { |
| 331 | record.state == LogState::Open && record.epoch == epoch && !batch_in_flight && per_cell_complete |
| 332 | } |
| 333 | |
| 334 | /// A bundle flush may credit durability only if the record is still Open |
| 335 | /// at the shipper's epoch AFTER the PUT. The PUT itself is unconditional |
| 336 | /// and proves nothing: a healed zombie whose record a recoverer already |
| 337 | /// sealed can still land bundle objects, and crediting them would ack |
| 338 | /// rows no future takeover reads — the sealed record says the bucket is |
| 339 | /// complete, and takeovers read per-cell prefixes. |
| 340 | pub fn bundle_credit_allowed(record: Option<&LogRecord>, epoch: Epoch) -> bool { |
| 341 | record.is_some_and(|record| record.epoch == epoch && record.state == LogState::Open) |
| 342 | } |
| 343 | |
| 344 | /// A bundle object is deletable exactly when every row it carries is |
| 345 | /// covered by the per-cell layout — the watermark that keeps recovery's |
| 346 | /// whole-prefix gather bounded without ever deleting the only copy of an |
| 347 | /// acked row. `rows` pairs each row's TXID with the covered watermark of |
| 348 | /// its (cell, cell epoch). |
| 349 | pub fn bundle_deletable(rows: impl IntoIterator<Item = (u64, u64)>) -> bool { |
| 350 | rows.into_iter().all(|(txid, covered)| txid <= covered) |
| 351 | } |
| 352 | |
| 353 | /// A follower fragment is garbage exactly when its epoch is closed: the |
| 354 | /// record moved past it (a reconfiguration or a reopened incarnation), or |
| 355 | /// recovery sealed the record at it. An open current-epoch fragment is |
| 356 | /// the durability witness and must never be collected. |
| 357 | pub fn fragment_closed(record: &LogRecord, fragment_epoch: Epoch) -> bool { |
| 358 | record.epoch > fragment_epoch |
| 359 | || (record.epoch == fragment_epoch && record.state == LogState::Sealed) |
| 360 | } |
| 361 | |
| 362 | /// maintain()'s reconfiguration barrier: the epoch may step only when no |
| 363 | /// batch sits between capture and credit (its frames are invisible to the |
| 364 | /// coverage counters) and every fleet-shipped frame is bucket-covered — |
| 365 | /// the precondition that makes the old fragments abandonable garbage and |
| 366 | /// the new members' emptiness sound. |
| 367 | pub fn may_reconfigure(batch_in_flight: bool, all_shipped_covered: bool) -> bool { |
| 368 | !batch_in_flight && all_shipped_covered |
| 369 | } |
| 370 | |
| 371 | /// The ship loop's truncation ledger: outstanding batches oldest-first, |
| 372 | /// and the covered watermark that rides the next append as the followers' |
| 373 | /// `truncate_to`. Sequences restart with the epoch, so the ledger resets |
| 374 | /// with it — a covered watermark surviving an epoch swap instructs fresh |
| 375 | /// followers to delete entries they just fsync'd. `Batch` |
| 376 | /// is whatever the executor needs to decide coverage; the ledger decides |
| 377 | /// only ordering, the watermark, and the reset. |
| 378 | #[derive(Debug)] |
| 379 | pub struct ShipLedger<Batch> { |
| 380 | epoch: Epoch, |
| 381 | covered_seq: Offset, |
| 382 | outstanding: std::collections::VecDeque<(Offset, Batch)>, |
| 383 | } |
| 384 | |
| 385 | impl<Batch> Default for ShipLedger<Batch> { |
| 386 | fn default() -> Self { |
| 387 | ShipLedger { |
| 388 | epoch: 0, |
| 389 | covered_seq: 0, |
| 390 | outstanding: std::collections::VecDeque::new(), |
| 391 | } |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | impl<Batch> ShipLedger<Batch> { |
| 396 | /// The stream identity check, before anything else each round: a new |
| 397 | /// epoch is a new sequence space and the ledger starts over. |
| 398 | pub fn observe_epoch(&mut self, epoch: Epoch) { |
| 399 | if epoch != self.epoch { |
| 400 | self.epoch = epoch; |
| 401 | self.outstanding.clear(); |
| 402 | self.covered_seq = 0; |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | /// A batch was acknowledged by every member through `last_seq`. |
| 407 | pub fn shipped(&mut self, last_seq: Offset, batch: Batch) { |
| 408 | self.outstanding.push_back((last_seq, batch)); |
| 409 | } |
| 410 | |
| 411 | /// Advance the covered watermark over every leading batch `covered` |
| 412 | /// accepts. `covered_seq` is the one way to read the result — the |
| 413 | /// followers' `truncate_to`. |
| 414 | pub fn advance(&mut self, mut covered: impl FnMut(&Batch) -> bool) { |
| 415 | while let Some((last_seq, batch)) = self.outstanding.front() { |
| 416 | if covered(batch) { |
| 417 | self.covered_seq = *last_seq; |
| 418 | self.outstanding.pop_front(); |
| 419 | } else { |
| 420 | break; |
| 421 | } |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | pub fn covered_seq(&self) -> Offset { |
| 426 | self.covered_seq |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | /// Why a node that wants the fleet posture is not serving fleet |
| 431 | /// acknowledgements. |
| 432 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 433 | pub enum Shortfall { |
| 434 | /// No live peer exists. An ordinary single-node fleet: the write waits |
| 435 | /// for the bucket because there is nobody to replicate to. |
| 436 | NoPeer, |
| 437 | /// Live peers exist and none can be recruited. An operator can act on |
| 438 | /// this; a single-node fleet is not a fault. |
| 439 | NoEligiblePeer, |
| 440 | } |
| 441 | |
| 442 | /// Should the node report its fleet shortfall now? |
| 443 | /// |
| 444 | /// `maintain` runs on a ticker and returns as soon as it finds no member to |
| 445 | /// recruit, so a fleet that never formed an ensemble reported nothing at all: |
| 446 | /// `log ensemble degraded` fires only when an ensemble that existed was lost. |
| 447 | /// A single-node fleet therefore ran the default fleet posture on bucket |
| 448 | /// acknowledgements forever, with no line explaining the latency or naming |
| 449 | /// the fix. Legible failure is the point; silence is the defect. |
| 450 | /// |
| 451 | /// The interval bounds the repetition, and `last_ms` of `None` reports at |
| 452 | /// once so the first tick after a start says what the node is doing. |
| 453 | pub fn fleet_shortfall( |
| 454 | live_peers: usize, |
| 455 | now_ms: u64, |
| 456 | last_ms: Option<u64>, |
| 457 | interval_ms: u64, |
| 458 | ) -> Option<Shortfall> { |
| 459 | if let Some(last) = last_ms { |
| 460 | if now_ms.saturating_sub(last) < interval_ms { |
| 461 | return None; |
| 462 | } |
| 463 | } |
| 464 | Some(if live_peers == 0 { |
| 465 | Shortfall::NoPeer |
| 466 | } else { |
| 467 | Shortfall::NoEligiblePeer |
| 468 | }) |
| 469 | } |