| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! The output gate: one choke point every egress passes through. |
| 4 | //! |
| 5 | //! # The rule |
| 6 | //! |
| 7 | //! Nothing that reveals a cell's state may leave this process while that cell |
| 8 | //! has a write it cannot prove durable. A client told about a write that a |
| 9 | //! crash then discards has been told something false, and no later message can |
| 10 | //! retract a side effect that has already left. |
| 11 | //! |
| 12 | //! # The implementation contract |
| 13 | //! |
| 14 | //! [`Channel`] enumerates every route that can reveal a cell's state. The shell |
| 15 | //! holds each effect and sends an [`Event::OutputAt`] with its route and the |
| 16 | //! release-time monotonic instant. This module |
| 17 | //! applies one durability rule to every route and returns the same route in an |
| 18 | //! [`Effect::Release`]. |
| 19 | //! |
| 20 | //! Each part of that contract has one implementation counterpart: |
| 21 | //! |
| 22 | //! | contract | implementation | |
| 23 | //! | --- | --- | |
| 24 | //! | enumerate every output route | the [`Channel`] enum | |
| 25 | //! | apply one rule to every route | the `channel` argument to [`State::output`] | |
| 26 | //! | bypass the gate when disabled | with `CELLD_OUTPUT_GATE=0`, the shell sends no [`Event::OutputAt`] | |
| 27 | //! | release only revealable state | the output's barrier, or the barrier it trails, has settled | |
| 28 | //! | let the held effect leave | [`Effect::Release`] with `Ok` | |
| 29 | //! |
| 30 | //! **The core does not read the channel.** It stores what the shell gave it and |
| 31 | //! hands the same value back. A `match` on [`Channel`] inside this module would |
| 32 | //! split the invariant into one independent rule per channel. Per-channel code |
| 33 | //! belongs in the shell and is limited to how an effect is held and how it is |
| 34 | //! released. |
| 35 | //! |
| 36 | //! # Why one choke point |
| 37 | //! |
| 38 | //! Earlier implementations split this rule between a core reader gate, a shell |
| 39 | //! WebSocket queue, and an in-handler position check. Each mechanism had a |
| 40 | //! different view of the outstanding writes, so one channel could miss a write |
| 41 | //! that another mechanism knew about. One core barrier map gives every channel |
| 42 | //! the same view. |
| 43 | //! |
| 44 | //! # The second way a barrier opens |
| 45 | //! |
| 46 | //! Every channel passes through [`State::output`]. Not every barrier is opened |
| 47 | //! by one: `alarm_finished` opens its own when a firing's consuming commit is |
| 48 | //! unproven, owned by [`GateOwner::Alarm`] rather than by an output. An alarm |
| 49 | //! is not a channel -- it settles by replay into the core, not by |
| 50 | //! release to the shell, so a [`Channel`] variant could not carry it -- but its |
| 51 | //! barrier lives in the same per-cell map, which is what matters here: a |
| 52 | //! read-only output trails the newest barrier on its cell without asking who |
| 53 | //! opened it, so it trails an alarm's unproven write exactly as it trails a |
| 54 | //! request's. |
| 55 | //! |
| 56 | //! An earlier alarm path proved its write inside [`Effect::FireAlarm`] without |
| 57 | //! registering a core barrier. A read-only output could therefore miss that |
| 58 | //! unproven write. The alarm now opens a barrier in the same map, so every |
| 59 | //! reader observes it. |
| 60 | //! |
| 61 | //! # A streamed body is more than one output |
| 62 | //! |
| 63 | //! The model treats a response as atomic, and for a complete response it is: |
| 64 | //! one release covers every byte. A response whose body streams is not atomic. |
| 65 | //! The head is released while nothing is pending, and the producer then keeps |
| 66 | //! running; a chunk it makes later can read a commit another event made after |
| 67 | //! that release. So the shell takes one ticket per chunk on |
| 68 | //! [`Channel::Response`], not one ticket for the response. The producer is a |
| 69 | //! single pump that awaits each chunk's ticket before it asks for the next |
| 70 | //! chunk, which is what keeps a held chunk from overtaking a released one. |
| 71 | |
| 72 | use crate::*; |
| 73 | |
| 74 | impl State { |
| 75 | /// **The output gate. Every channel passes through here.** |
| 76 | /// |
| 77 | /// The implementation contract is meant to be checked line by line: |
| 78 | /// |
| 79 | /// - `channel` names the route. This function stores it but does not branch |
| 80 | /// on it, so every channel uses one rule. |
| 81 | /// - with `CELLD_OUTPUT_GATE=0`, the shell never sends [`Event::OutputAt`]. |
| 82 | /// - no barrier means that no unproven write remains for this output to |
| 83 | /// reveal, so the core emits [`Effect::Release`] with `Ok`. |
| 84 | /// |
| 85 | /// A write opens its own barrier and waits for a proof that covers its |
| 86 | /// position. A read-only output that observed a committed write no |
| 87 | /// verified proof covers yet waits for that proof itself: the handler |
| 88 | /// that wrote takes its ticket only when it answers, so a reader that |
| 89 | /// answers before that finds no barrier for what it read. Otherwise a |
| 90 | /// read-only output joins the newest barrier open on its cell, because a |
| 91 | /// reader can start after a write commits and before its proof lands. |
| 92 | /// Comparing the reader's own start and end positions therefore decides |
| 93 | /// nothing. |
| 94 | pub(crate) fn output( |
| 95 | &mut self, |
| 96 | request: RequestId, |
| 97 | channel: Channel, |
| 98 | position: Option<u64>, |
| 99 | observed: Option<u64>, |
| 100 | epoch: Option<Epoch>, |
| 101 | effects: &mut Vec<Effect>, |
| 102 | ) { |
| 103 | let held = Held { request, channel }; |
| 104 | // Authority is checked here, not only at request start: a handler can |
| 105 | // start under a live node lease and reach its output after that lease |
| 106 | // expired. Releasing then would reveal work a successor owner can |
| 107 | // already have replaced. |
| 108 | if !self.node_authoritative() { |
| 109 | effects.push(Effect::Release { |
| 110 | request, |
| 111 | channel, |
| 112 | result: Err(RequestError::NodeFenced), |
| 113 | }); |
| 114 | return; |
| 115 | } |
| 116 | // A ticket sampled before its request pinned the cell names the epoch |
| 117 | // it sampled at. A reset between the sample and the pin discarded that |
| 118 | // epoch's unproven writes, and the pin then activated the next epoch: |
| 119 | // a proof there covers nothing the ticket asks about, so the ticket |
| 120 | // fails rather than acknowledge a discarded write. A request whose |
| 121 | // cell is not resident at all fails here too, rather than by the |
| 122 | // branch below: the write branch refuses that case itself, but the |
| 123 | // read-only branch releases an active request whatever its cell's |
| 124 | // phase, and a sampled epoch is a claim this check must settle |
| 125 | // instead of leaving it to the reset's request cleanup. |
| 126 | if let Some(sampled) = epoch { |
| 127 | if self |
| 128 | .resident_cell(request) |
| 129 | .is_none_or(|(_, current)| current != sampled) |
| 130 | { |
| 131 | effects.push(Effect::Release { |
| 132 | request, |
| 133 | channel, |
| 134 | result: Err(RequestError::DurabilityUnproven), |
| 135 | }); |
| 136 | return; |
| 137 | } |
| 138 | } |
| 139 | match (position, observed) { |
| 140 | (Some(position), _) => self.open_write_barrier(held, position, effects), |
| 141 | (None, Some(observed)) => match self.resident_cell(request) { |
| 142 | Some((cell, epoch)) if self.proven_covers(&cell, epoch, observed) => { |
| 143 | self.trail_open_barrier(held, effects) |
| 144 | } |
| 145 | Some((cell, epoch)) => self.hold_observed(held, cell, epoch, observed, effects), |
| 146 | // The ticket names a commit no proof covers, on a cell that is |
| 147 | // no longer resident to prove it. Fail closed, as a write in |
| 148 | // that state does, rather than release what a read-only |
| 149 | // ticket on a cell with nothing to prove would release. |
| 150 | None => effects.push(Effect::Release { |
| 151 | request, |
| 152 | channel, |
| 153 | result: Err(RequestError::DurabilityUnproven), |
| 154 | }), |
| 155 | }, |
| 156 | (None, None) => self.trail_open_barrier(held, effects), |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | /// Whether a verified proof of this residency, at `epoch`, already covers |
| 161 | /// `observed`. |
| 162 | fn proven_covers(&self, cell: &CellId, epoch: Epoch, observed: u64) -> bool { |
| 163 | self.cells |
| 164 | .get(cell) |
| 165 | .and_then(|record| record.proven_position) |
| 166 | .is_some_and(|(proven_at, proven)| proven_at == epoch && proven >= observed) |
| 167 | } |
| 168 | |
| 169 | /// Hold a read-only output that observed a committed write no verified |
| 170 | /// proof covers yet. It joins a barrier on its cell whose position covers |
| 171 | /// what it observed, and opens one at that position otherwise: the proof |
| 172 | /// is then the reader's own, and the writer's later ticket opens a barrier |
| 173 | /// a proof already satisfies. |
| 174 | fn hold_observed( |
| 175 | &mut self, |
| 176 | held: Held, |
| 177 | cell: CellId, |
| 178 | epoch: Epoch, |
| 179 | observed: u64, |
| 180 | effects: &mut Vec<Effect>, |
| 181 | ) { |
| 182 | if let Some((_, barrier)) = self.barriers.iter_mut().rev().find(|(_, barrier)| { |
| 183 | barrier.cell == cell && barrier.epoch == epoch && barrier.position >= observed |
| 184 | }) { |
| 185 | barrier.followers.push(held); |
| 186 | return; |
| 187 | } |
| 188 | self.open_write_barrier(held, observed, effects); |
| 189 | } |
| 190 | |
| 191 | /// Record a verified proof, so a later read-only output that observed no |
| 192 | /// more than `position` at this epoch releases without a proof of its own. |
| 193 | fn note_proven(&mut self, cell: &CellId, epoch: Epoch, position: u64) { |
| 194 | let Some(record) = self.cells.get_mut(cell) else { |
| 195 | return; |
| 196 | }; |
| 197 | record.proven_position = Some(match record.proven_position { |
| 198 | Some((proven_at, proven)) if proven_at == epoch => (epoch, proven.max(position)), |
| 199 | _ => (epoch, position), |
| 200 | }); |
| 201 | } |
| 202 | |
| 203 | /// Open the output gate for a local write: hold its output until the |
| 204 | /// cell's committed `position` is proven replicated. The request must still |
| 205 | /// be a live local activity on its cell, resident at the epoch that |
| 206 | /// committed the write; otherwise durability cannot be proven for it and |
| 207 | /// the output fails rather than falsely acknowledging the write. |
| 208 | fn open_write_barrier(&mut self, held: Held, position: u64, effects: &mut Vec<Effect>) { |
| 209 | let request = held.request; |
| 210 | let Some((cell, epoch)) = self.resident_cell(request) else { |
| 211 | effects.push(Effect::Release { |
| 212 | request, |
| 213 | channel: held.channel, |
| 214 | result: Err(RequestError::DurabilityUnproven), |
| 215 | }); |
| 216 | return; |
| 217 | }; |
| 218 | let op = self.op(); |
| 219 | self.barriers.insert( |
| 220 | op, |
| 221 | Barrier { |
| 222 | owner: GateOwner::Output(held), |
| 223 | cell: cell.clone(), |
| 224 | epoch, |
| 225 | position, |
| 226 | followers: Vec::new(), |
| 227 | }, |
| 228 | ); |
| 229 | effects.push(Effect::AwaitDurable { |
| 230 | op, |
| 231 | cell, |
| 232 | epoch, |
| 233 | position, |
| 234 | }); |
| 235 | } |
| 236 | |
| 237 | /// The cell a live local request runs against, and the epoch it is |
| 238 | /// resident at. `None` when the request is not active or its cell is not |
| 239 | /// resident. |
| 240 | fn resident_cell(&self, request: RequestId) -> Option<(CellId, Epoch)> { |
| 241 | self.active_requests.get(&request).and_then(|id| { |
| 242 | match self.cells.get(id).map(|cell| &cell.phase) { |
| 243 | Some(Phase::Resident { epoch }) => Some((id.clone(), *epoch)), |
| 244 | _ => None, |
| 245 | } |
| 246 | }) |
| 247 | } |
| 248 | |
| 249 | /// Hold a read-only output behind the newest barrier open on its cell. |
| 250 | /// |
| 251 | /// Residency is not required here, unlike a write: a read on a cell that |
| 252 | /// has left `Resident` has no barrier to find and no write of its own to |
| 253 | /// prove, so it releases rather than fails. |
| 254 | fn trail_open_barrier(&mut self, held: Held, effects: &mut Vec<Effect>) { |
| 255 | let Some(cell) = self.active_requests.get(&held.request).cloned() else { |
| 256 | effects.push(Effect::Release { |
| 257 | request: held.request, |
| 258 | channel: held.channel, |
| 259 | result: Err(RequestError::DurabilityUnproven), |
| 260 | }); |
| 261 | return; |
| 262 | }; |
| 263 | if let Some((_, barrier)) = self |
| 264 | .barriers |
| 265 | .iter_mut() |
| 266 | .rev() |
| 267 | .find(|(_, barrier)| barrier.cell == cell) |
| 268 | { |
| 269 | barrier.followers.push(held); |
| 270 | } else { |
| 271 | effects.push(Effect::Release { |
| 272 | request: held.request, |
| 273 | channel: held.channel, |
| 274 | result: Ok(()), |
| 275 | }); |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | /// A gated write's durability proof completed. Acknowledge the write only |
| 280 | /// when the replica proved a position that *covers* it — a shorter proof |
| 281 | /// (a lagging or lying replicator) fails it rather than acknowledging a |
| 282 | /// write the node cannot actually restore. Any error fails it. A completion |
| 283 | /// for a gate already drained (fence or deadline) is ignored — the |
| 284 | /// versioned-op discipline used throughout the core. |
| 285 | pub(crate) fn durable_reached( |
| 286 | &mut self, |
| 287 | op: OpId, |
| 288 | result: Result<u64, Failure>, |
| 289 | source: ProofSource, |
| 290 | effects: &mut Vec<Effect>, |
| 291 | ) { |
| 292 | let Some(gate) = self.barriers.get(&op) else { |
| 293 | return; |
| 294 | }; |
| 295 | let proven = matches!(result, Ok(durable) if durable >= gate.position); |
| 296 | // A bucket proof reveals nothing until an ownership read confirms the |
| 297 | // record still names this node at this epoch: "durable in `e<epoch>/`" is not |
| 298 | // durable if the prefix was orphaned, and the bucket cannot refuse a |
| 299 | // stale writer. A fleet proof needs no read — the ensemble |
| 300 | // arbitrated it: a takeover seals a member before restoring, so a |
| 301 | // stale owner's ack-all fails closed. |
| 302 | if proven && source == ProofSource::Bucket { |
| 303 | let (cell, epoch) = (gate.cell.clone(), gate.epoch); |
| 304 | effects.push(Effect::VerifyOwnership { op, cell, epoch }); |
| 305 | return; |
| 306 | } |
| 307 | self.settle_gate(op, proven, effects); |
| 308 | } |
| 309 | |
| 310 | /// Ownership verification for a bucket-proof gate. A record that no longer |
| 311 | /// names this node at this epoch fails the write exactly like an unproven |
| 312 | /// durability result: refuse and reset, never acknowledge into an |
| 313 | /// orphaned lineage. |
| 314 | pub(crate) fn ownership_verified( |
| 315 | &mut self, |
| 316 | op: OpId, |
| 317 | result: Result<(), Failure>, |
| 318 | effects: &mut Vec<Effect>, |
| 319 | ) { |
| 320 | if !self.barriers.contains_key(&op) { |
| 321 | return; |
| 322 | } |
| 323 | self.settle_gate(op, result.is_ok(), effects); |
| 324 | } |
| 325 | |
| 326 | /// Release one withheld output, unpinning it first so the cleanup that |
| 327 | /// ends -- shedding, eviction -- is queued ahead of the release. |
| 328 | pub(crate) fn release_held( |
| 329 | &mut self, |
| 330 | held: Held, |
| 331 | result: Result<(), RequestError>, |
| 332 | effects: &mut Vec<Effect>, |
| 333 | ) { |
| 334 | if self.gate_pinned.remove(&held.request) { |
| 335 | self.activity_finished(held.request, effects); |
| 336 | } |
| 337 | effects.push(Effect::Release { |
| 338 | request: held.request, |
| 339 | channel: held.channel, |
| 340 | result, |
| 341 | }); |
| 342 | } |
| 343 | |
| 344 | fn settle_gate(&mut self, op: OpId, proven: bool, effects: &mut Vec<Effect>) { |
| 345 | let Some(gate) = self.barriers.remove(&op) else { |
| 346 | return; |
| 347 | }; |
| 348 | let result = if proven { |
| 349 | self.note_proven(&gate.cell, gate.epoch, gate.position); |
| 350 | Ok(()) |
| 351 | } else { |
| 352 | Err(RequestError::DurabilityUnproven) |
| 353 | }; |
| 354 | match gate.owner { |
| 355 | // Unpin before releasing: the cleanup this ends -- shedding, |
| 356 | // eviction -- is queued ahead of the response, so a caller that |
| 357 | // sees its write acknowledged sees the residency it released too. |
| 358 | // `activity_finished` re-checks the barrier map, so a request |
| 359 | // holding a second gated write simply re-pins itself here. |
| 360 | GateOwner::Output(held) => self.release_held(held, result, effects), |
| 361 | // The alarm settles only now. A proven commit replays the |
| 362 | // observation the handler made, which routes through |
| 363 | // `alarm_observed` and orders the consume-side wake-entry delete |
| 364 | // -- after the proof, by construction. An unproven one takes the |
| 365 | // re-arm branch a failed handler takes, so the entry stays |
| 366 | // discoverable and at-least-once holds. The replay carries no |
| 367 | // position, so it settles rather than opening a second barrier. |
| 368 | GateOwner::Alarm { |
| 369 | alarm, |
| 370 | at_ms, |
| 371 | covered, |
| 372 | } => { |
| 373 | let outcome = if proven { |
| 374 | Ok((at_ms, covered, None)) |
| 375 | } else { |
| 376 | Err(Failure::Ambiguous) |
| 377 | }; |
| 378 | let (now_ms, now_mono_ms) = (self.now_ms, self.now_mono_ms); |
| 379 | self.alarm_finished( |
| 380 | alarm, |
| 381 | (gate.cell.clone(), gate.epoch), |
| 382 | now_ms, |
| 383 | now_mono_ms, |
| 384 | outcome, |
| 385 | effects, |
| 386 | ); |
| 387 | } |
| 388 | } |
| 389 | // A follower is always an output: an alarm opens a barrier, it never |
| 390 | // trails one. |
| 391 | for held in gate.followers { |
| 392 | self.release_held(held, result, effects); |
| 393 | } |
| 394 | if !proven { |
| 395 | let (id, epoch) = (gate.cell.clone(), gate.epoch); |
| 396 | self.reset_cell(&id, epoch, effects); |
| 397 | } |
| 398 | } |
| 399 | } |