| 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 | } |
| 50 | |
| 51 | /// Created before the first fleet-durable ack. The open fragment begins at |
| 52 | /// the bucket's current end, so every frame a member will ever be asked |
| 53 | /// about is above what the bucket already holds. |
| 54 | pub fn create_record(ensemble: BTreeSet<NodeId>, bucket_end: Offset) -> Option<LogRecord> { |
| 55 | if ensemble.is_empty() { |
| 56 | return None; |
| 57 | } |
| 58 | Some(LogRecord { |
| 59 | epoch: 1, |
| 60 | ensemble, |
| 61 | tiered: bucket_end, |
| 62 | state: LogState::Open, |
| 63 | }) |
| 64 | } |
| 65 | |
| 66 | /// One follower's copy of one node log: the open fragment `(base, end]` at |
| 67 | /// its fragment epoch, plus the persisted seal mark. |
| 68 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 69 | pub struct FollowerLog { |
| 70 | pub fragment_epoch: Epoch, |
| 71 | pub base: Offset, |
| 72 | pub end: Offset, |
| 73 | /// Highest epoch sealed. Appends at or below it are refused forever. |
| 74 | pub sealed_to: Epoch, |
| 75 | } |
| 76 | |
| 77 | impl FollowerLog { |
| 78 | /// An empty joiner: covered by the bucket through `base`, holding |
| 79 | /// nothing. |
| 80 | pub fn join(fragment_epoch: Epoch, base: Offset) -> Self { |
| 81 | FollowerLog { |
| 82 | fragment_epoch, |
| 83 | base, |
| 84 | end: base, |
| 85 | sealed_to: 0, |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | /// Accept one frame. Refuses the wrong fragment epoch, anything at or |
| 90 | /// below the seal mark, and gaps — a fragment is contiguous or it is |
| 91 | /// not a fragment. |
| 92 | pub fn accept_append(&mut self, epoch: Epoch, offset: Offset) -> bool { |
| 93 | if epoch != self.fragment_epoch || epoch <= self.sealed_to || offset != self.end + 1 { |
| 94 | return false; |
| 95 | } |
| 96 | self.end = offset; |
| 97 | true |
| 98 | } |
| 99 | |
| 100 | /// Persist a seal through `epoch` and report the final contiguous end. |
| 101 | /// The fragment is frozen from here; write-all makes this one answer |
| 102 | /// sufficient to certify every acknowledged frame. |
| 103 | pub fn seal(&mut self, epoch: Epoch) -> Offset { |
| 104 | if epoch > self.sealed_to { |
| 105 | self.sealed_to = epoch; |
| 106 | } |
| 107 | self.end |
| 108 | } |
| 109 | |
| 110 | /// Drop frames the record already proves tiered. |
| 111 | pub fn truncate(&mut self, tiered: Offset) { |
| 112 | if tiered > self.base { |
| 113 | self.base = tiered; |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | /// The leader's believed (epoch, ensemble). Deliberately a belief: a fenced |
| 119 | /// leader still acts on it, and safety must come from seal marks and lost |
| 120 | /// CASes, not from wishful record reads on the ack path. |
| 121 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 122 | pub struct LeaderView { |
| 123 | pub epoch: Epoch, |
| 124 | pub ensemble: BTreeSet<NodeId>, |
| 125 | } |
| 126 | |
| 127 | /// Write-all, ack-all: `next` may acknowledge only when every ensemble |
| 128 | /// member has confirmed it at the leader's fragment epoch. `ends` carries |
| 129 | /// each member's confirmed contiguous end; a member missing from it has |
| 130 | /// confirmed nothing. |
| 131 | pub fn ack_fleet_allowed(view: &LeaderView, ends: &BTreeMap<NodeId, Offset>, next: Offset) -> bool { |
| 132 | !view.ensemble.is_empty() |
| 133 | && view |
| 134 | .ensemble |
| 135 | .iter() |
| 136 | .all(|member| ends.get(member).is_some_and(|end| *end >= next)) |
| 137 | } |
| 138 | |
| 139 | /// A reconfiguration the CAS may publish. `tier_through` must be durable in |
| 140 | /// the bucket before the CAS lands: the new members join empty, and the |
| 141 | /// bucket is the only thing covering their emptiness. |
| 142 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 143 | pub struct ReconfigPlan { |
| 144 | pub tier_through: Offset, |
| 145 | pub record: LogRecord, |
| 146 | } |
| 147 | |
| 148 | pub fn plan_reconfigure( |
| 149 | current: &LogRecord, |
| 150 | log_end: Offset, |
| 151 | ensemble: BTreeSet<NodeId>, |
| 152 | ) -> Option<ReconfigPlan> { |
| 153 | if current.state != LogState::Open || ensemble.is_empty() || ensemble == current.ensemble { |
| 154 | return None; |
| 155 | } |
| 156 | Some(ReconfigPlan { |
| 157 | tier_through: log_end, |
| 158 | record: LogRecord { |
| 159 | epoch: current.epoch + 1, |
| 160 | ensemble, |
| 161 | tiered: log_end, |
| 162 | state: LogState::Open, |
| 163 | }, |
| 164 | }) |
| 165 | } |
| 166 | |
| 167 | /// Recovery step one: fence via the record. S3 is the root of truth, so |
| 168 | /// this CAS is what makes every later tiering or reconfiguration attempt by |
| 169 | /// the old leader fail. Sealing followers comes after, never before. |
| 170 | pub fn start_recovery(record: &LogRecord) -> Option<LogRecord> { |
| 171 | if record.state != LogState::Open { |
| 172 | return None; |
| 173 | } |
| 174 | Some(LogRecord { |
| 175 | state: LogState::Recovering, |
| 176 | ..record.clone() |
| 177 | }) |
| 178 | } |
| 179 | |
| 180 | /// The certified cut: the final contiguous end of any sealed member, floored |
| 181 | /// at what is already tiered. Any one sealed member suffices for acked |
| 182 | /// frames (write-all); taking a longer end preserves acked-but-unconfirmed |
| 183 | /// frames, which is safe — delivering an unacknowledged write is allowed, |
| 184 | /// losing an acknowledged one is not. |
| 185 | pub fn certify(tiered: Offset, sealed_end: Offset) -> Offset { |
| 186 | tiered.max(sealed_end) |
| 187 | } |
| 188 | |
| 189 | /// Recovery final step: the certified tail is durable in the bucket, so the |
| 190 | /// record seals at the cut and every per-cell takeover may treat the bucket |
| 191 | /// as complete. |
| 192 | pub fn finish_recovery(record: &LogRecord, cert: Offset) -> Option<LogRecord> { |
| 193 | if record.state != LogState::Recovering { |
| 194 | return None; |
| 195 | } |
| 196 | Some(LogRecord { |
| 197 | tiered: cert, |
| 198 | state: LogState::Sealed, |
| 199 | ..record.clone() |
| 200 | }) |
| 201 | } |
| 202 | |
| 203 | /// May a per-cell takeover of this node's cells treat the bucket as |
| 204 | /// complete? Absence is a proof, not a guess: the record is created before |
| 205 | /// the first fleet-durable ack and never deleted, so no record means the |
| 206 | /// node never acknowledged anything the bucket does not hold. |
| 207 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 208 | pub enum TakeoverGate { |
| 209 | BucketComplete, |
| 210 | RecoverFirst, |
| 211 | } |
| 212 | |
| 213 | pub fn takeover_gate(record: Option<&LogRecord>) -> TakeoverGate { |
| 214 | match record { |
| 215 | None => TakeoverGate::BucketComplete, |
| 216 | Some(record) if record.state == LogState::Sealed => TakeoverGate::BucketComplete, |
| 217 | Some(_) => TakeoverGate::RecoverFirst, |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | /// What the maintenance loop must do with its OWN session's record before |
| 222 | /// it may open a fleet ensemble. The record is keyed by (node, |
| 223 | /// generation), so the only record this session can ever read here is one |
| 224 | /// it wrote itself: absent on the session's first open, present for a |
| 225 | /// within-session reconfiguration. A predecessor session's record is a |
| 226 | /// dead session's record like any other, recovered by the sweep or the |
| 227 | /// takeover interlock, never stepped past here — which is what deleted the |
| 228 | /// RecoverFirst arm, the revive/reopen guard, and the recovery epoch pin. |
| 229 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 230 | pub enum MaintainStep { |
| 231 | /// No record yet: create one before the first fleet-durable ack. |
| 232 | CreateFresh, |
| 233 | /// Our open (or, after a failed close, sealed) record: step the epoch |
| 234 | /// and reopen with a fresh ensemble. |
| 235 | Reopen(Epoch), |
| 236 | /// Our own record is mid-recovery: a rival is fencing this session, |
| 237 | /// which can only mean our lease looks expired from where it stands. |
| 238 | /// Reopening would race its seal CAS — both outcomes are safe under |
| 239 | /// write-all plus the seal marks, but the churn buys nothing. Hold |
| 240 | /// this tick; the next pass finds Sealed and reopens, or our own |
| 241 | /// lease loss fences us first. |
| 242 | Wait, |
| 243 | } |
| 244 | |
| 245 | pub fn maintain_step(record: Option<&LogRecord>) -> MaintainStep { |
| 246 | match record { |
| 247 | None => MaintainStep::CreateFresh, |
| 248 | Some(record) if record.state == LogState::Recovering => MaintainStep::Wait, |
| 249 | Some(record) => MaintainStep::Reopen(record.epoch + 1), |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | /// The graceful shutdown's seal guard — the only seal producer besides |
| 254 | /// recovery. The record must still be Open at the closing shipper's |
| 255 | /// epoch, no batch may sit between capture and credit, and every shipped |
| 256 | /// frame must live in the PER-CELL layout: a sealed record tells every |
| 257 | /// future recovery there is nothing to gather, so credited bundle |
| 258 | /// coverage must never satisfy this guard — the bundle-resident acked |
| 259 | /// tail would be orphaned behind the seal. Refusal is always safe: an |
| 260 | /// Open record just means the next incarnation's recovery drains the |
| 261 | /// bundles. |
| 262 | pub fn graceful_seal_allowed( |
| 263 | record: &LogRecord, |
| 264 | epoch: Epoch, |
| 265 | batch_in_flight: bool, |
| 266 | per_cell_complete: bool, |
| 267 | ) -> bool { |
| 268 | record.state == LogState::Open && record.epoch == epoch && !batch_in_flight && per_cell_complete |
| 269 | } |
| 270 | |
| 271 | /// A bundle flush may credit durability only if the record is still Open |
| 272 | /// at the shipper's epoch AFTER the PUT. The PUT itself is unconditional |
| 273 | /// and proves nothing: a healed zombie whose record a recoverer already |
| 274 | /// sealed can still land bundle objects, and crediting them would ack |
| 275 | /// rows no future takeover reads — the sealed record says the bucket is |
| 276 | /// complete, and takeovers read per-cell prefixes. |
| 277 | pub fn bundle_credit_allowed(record: Option<&LogRecord>, epoch: Epoch) -> bool { |
| 278 | record.is_some_and(|record| record.epoch == epoch && record.state == LogState::Open) |
| 279 | } |
| 280 | |
| 281 | /// A bundle object is deletable exactly when every row it carries is |
| 282 | /// covered by the per-cell layout — the watermark that keeps recovery's |
| 283 | /// whole-prefix gather bounded without ever deleting the only copy of an |
| 284 | /// acked row. `rows` pairs each row's TXID with the covered watermark of |
| 285 | /// its (cell, cell epoch). |
| 286 | pub fn bundle_deletable(rows: impl IntoIterator<Item = (u64, u64)>) -> bool { |
| 287 | rows.into_iter().all(|(txid, covered)| txid <= covered) |
| 288 | } |
| 289 | |
| 290 | /// A follower fragment is garbage exactly when its epoch is closed: the |
| 291 | /// record moved past it (a reconfiguration or a reopened incarnation), or |
| 292 | /// recovery sealed the record at it. An open current-epoch fragment is |
| 293 | /// the durability witness and must never be collected. |
| 294 | pub fn fragment_closed(record: &LogRecord, fragment_epoch: Epoch) -> bool { |
| 295 | record.epoch > fragment_epoch |
| 296 | || (record.epoch == fragment_epoch && record.state == LogState::Sealed) |
| 297 | } |
| 298 | |
| 299 | /// maintain()'s reconfiguration barrier: the epoch may step only when no |
| 300 | /// batch sits between capture and credit (its frames are invisible to the |
| 301 | /// coverage counters) and every fleet-shipped frame is bucket-covered — |
| 302 | /// the precondition that makes the old fragments abandonable garbage and |
| 303 | /// the new members' emptiness sound. |
| 304 | pub fn may_reconfigure(batch_in_flight: bool, all_shipped_covered: bool) -> bool { |
| 305 | !batch_in_flight && all_shipped_covered |
| 306 | } |
| 307 | |
| 308 | /// The ship loop's truncation ledger: outstanding batches oldest-first, |
| 309 | /// and the covered watermark that rides the next append as the followers' |
| 310 | /// `truncate_to`. Sequences restart with the epoch, so the ledger resets |
| 311 | /// with it — a covered watermark surviving an epoch swap instructs fresh |
| 312 | /// followers to delete entries they just fsync'd (review P0 #1). `Batch` |
| 313 | /// is whatever the executor needs to decide coverage; the ledger decides |
| 314 | /// only ordering, the watermark, and the reset. |
| 315 | #[derive(Debug)] |
| 316 | pub struct ShipLedger<Batch> { |
| 317 | epoch: Epoch, |
| 318 | covered_seq: Offset, |
| 319 | outstanding: std::collections::VecDeque<(Offset, Batch)>, |
| 320 | } |
| 321 | |
| 322 | impl<Batch> Default for ShipLedger<Batch> { |
| 323 | fn default() -> Self { |
| 324 | ShipLedger { |
| 325 | epoch: 0, |
| 326 | covered_seq: 0, |
| 327 | outstanding: std::collections::VecDeque::new(), |
| 328 | } |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | impl<Batch> ShipLedger<Batch> { |
| 333 | /// The stream identity check, before anything else each round: a new |
| 334 | /// epoch is a new sequence space and the ledger starts over. |
| 335 | pub fn observe_epoch(&mut self, epoch: Epoch) { |
| 336 | if epoch != self.epoch { |
| 337 | self.epoch = epoch; |
| 338 | self.outstanding.clear(); |
| 339 | self.covered_seq = 0; |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | /// A batch was acknowledged by every member through `last_seq`. |
| 344 | pub fn shipped(&mut self, last_seq: Offset, batch: Batch) { |
| 345 | self.outstanding.push_back((last_seq, batch)); |
| 346 | } |
| 347 | |
| 348 | /// Advance the covered watermark over every leading batch `covered` |
| 349 | /// accepts. `covered_seq` is the one way to read the result — the |
| 350 | /// followers' `truncate_to`. |
| 351 | pub fn advance(&mut self, mut covered: impl FnMut(&Batch) -> bool) { |
| 352 | while let Some((last_seq, batch)) = self.outstanding.front() { |
| 353 | if covered(batch) { |
| 354 | self.covered_seq = *last_seq; |
| 355 | self.outstanding.pop_front(); |
| 356 | } else { |
| 357 | break; |
| 358 | } |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | pub fn covered_seq(&self) -> Offset { |
| 363 | self.covered_seq |
| 364 | } |
| 365 | } |