| 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::Output`] with its route. This module |
| 16 | //! applies one durability rule to every route and returns the same route in an |
| 17 | //! [`Effect::Release`]. |
| 18 | //! |
| 19 | //! Each part of that contract has one implementation counterpart: |
| 20 | //! |
| 21 | //! | contract | implementation | |
| 22 | //! | --- | --- | |
| 23 | //! | enumerate every output route | the [`Channel`] enum | |
| 24 | //! | apply one rule to every route | the `channel` argument to [`State::output`] | |
| 25 | //! | bypass the gate when disabled | with `CELLD_OUTPUT_GATE=0`, the shell sends no [`Event::Output`] | |
| 26 | //! | release only revealable state | the output's barrier, or the barrier it trails, has settled | |
| 27 | //! | let the held effect leave | [`Effect::Release`] with `Ok` | |
| 28 | //! |
| 29 | //! **The core does not read the channel.** It stores what the shell gave it and |
| 30 | //! hands the same value back. A `match` on [`Channel`] inside this module would |
| 31 | //! split the invariant into six independent rules. Per-channel code belongs in |
| 32 | //! the shell and is limited to how an effect is held and how it is released. |
| 33 | //! |
| 34 | //! # Why one choke point |
| 35 | //! |
| 36 | //! Earlier implementations split this rule between a core reader gate, a shell |
| 37 | //! WebSocket queue, and an in-handler position check. Each mechanism had a |
| 38 | //! different view of the outstanding writes, so one channel could miss a write |
| 39 | //! that another mechanism knew about. One core barrier map gives every channel |
| 40 | //! the same view. |
| 41 | //! |
| 42 | //! # The second way a barrier opens |
| 43 | //! |
| 44 | //! Every channel passes through [`State::output`]. Not every barrier is opened |
| 45 | //! by one: `alarm_finished` opens its own when a firing's consuming commit is |
| 46 | //! unproven, owned by [`GateOwner::Alarm`] rather than by an output. An alarm |
| 47 | //! is not a seventh channel -- it settles by replay into the core, not by |
| 48 | //! release to the shell, so a [`Channel`] variant could not carry it -- but its |
| 49 | //! barrier lives in the same per-cell map, which is what matters here: a |
| 50 | //! read-only output trails the newest barrier on its cell without asking who |
| 51 | //! opened it, so it trails an alarm's unproven write exactly as it trails a |
| 52 | //! request's. |
| 53 | //! |
| 54 | //! An earlier alarm path proved its write inside [`Effect::FireAlarm`] without |
| 55 | //! registering a core barrier. A read-only output could therefore miss that |
| 56 | //! unproven write. The alarm now opens a barrier in the same map, so every |
| 57 | //! reader observes it. |
| 58 | //! |
| 59 | //! # Boundary |
| 60 | //! |
| 61 | //! A response body that streams is gated once, when the response is released. |
| 62 | //! Later chunks do not pass again. The model treats a response as atomic, so it |
| 63 | //! does not see this either. |
| 64 | |
| 65 | use crate::*; |
| 66 | |
| 67 | impl State { |
| 68 | /// **The output gate. Every channel passes through here.** |
| 69 | /// |
| 70 | /// The implementation contract is meant to be checked line by line: |
| 71 | /// |
| 72 | /// - `channel` names the route. This function stores it but does not branch |
| 73 | /// on it, so all six channels use one rule. |
| 74 | /// - with `CELLD_OUTPUT_GATE=0`, the shell never sends [`Event::Output`]. |
| 75 | /// - no barrier means that no unproven write remains for this output to |
| 76 | /// reveal, so the core emits [`Effect::Release`] with `Ok`. |
| 77 | /// |
| 78 | /// A write opens its own barrier and waits for a proof that covers its |
| 79 | /// position. A read-only output joins the newest barrier open on its cell, |
| 80 | /// because a reader can start after a write commits and before its proof |
| 81 | /// lands. Comparing the reader's own start and end positions therefore |
| 82 | /// decides nothing. |
| 83 | pub(crate) fn output( |
| 84 | &mut self, |
| 85 | request: RequestId, |
| 86 | channel: Channel, |
| 87 | position: Option<u64>, |
| 88 | effects: &mut Vec<Effect>, |
| 89 | ) { |
| 90 | let held = Held { request, channel }; |
| 91 | match position { |
| 92 | Some(position) => self.open_write_barrier(held, position, effects), |
| 93 | None => self.trail_open_barrier(held, effects), |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | /// Open the output gate for a local write: hold its output until the |
| 98 | /// cell's committed `position` is proven replicated. The request must still |
| 99 | /// be a live local activity on its cell, resident at the epoch that |
| 100 | /// committed the write; otherwise durability cannot be proven for it and |
| 101 | /// the output fails rather than falsely acknowledging the write. |
| 102 | fn open_write_barrier(&mut self, held: Held, position: u64, effects: &mut Vec<Effect>) { |
| 103 | let request = held.request; |
| 104 | let resident = self.active_requests.get(&request).and_then(|id| { |
| 105 | match self.cells.get(id).map(|cell| &cell.phase) { |
| 106 | Some(Phase::Resident { epoch }) => Some((id.clone(), *epoch)), |
| 107 | _ => None, |
| 108 | } |
| 109 | }); |
| 110 | let Some((cell, epoch)) = resident else { |
| 111 | effects.push(Effect::Release { |
| 112 | request, |
| 113 | channel: held.channel, |
| 114 | result: Err(RequestError::DurabilityUnproven), |
| 115 | }); |
| 116 | return; |
| 117 | }; |
| 118 | let op = self.op(); |
| 119 | self.barriers.insert( |
| 120 | op, |
| 121 | Barrier { |
| 122 | owner: GateOwner::Output(held), |
| 123 | cell: cell.clone(), |
| 124 | epoch, |
| 125 | position, |
| 126 | followers: Vec::new(), |
| 127 | }, |
| 128 | ); |
| 129 | effects.push(Effect::AwaitDurable { |
| 130 | op, |
| 131 | cell, |
| 132 | epoch, |
| 133 | position, |
| 134 | }); |
| 135 | } |
| 136 | |
| 137 | /// Hold a read-only output behind the newest barrier open on its cell. |
| 138 | /// |
| 139 | /// Residency is not required here, unlike a write: a read on a cell that |
| 140 | /// has left `Resident` has no barrier to find and no write of its own to |
| 141 | /// prove, so it releases rather than fails. |
| 142 | fn trail_open_barrier(&mut self, held: Held, effects: &mut Vec<Effect>) { |
| 143 | let Some(cell) = self.active_requests.get(&held.request).cloned() else { |
| 144 | effects.push(Effect::Release { |
| 145 | request: held.request, |
| 146 | channel: held.channel, |
| 147 | result: Err(RequestError::DurabilityUnproven), |
| 148 | }); |
| 149 | return; |
| 150 | }; |
| 151 | if let Some((_, barrier)) = self |
| 152 | .barriers |
| 153 | .iter_mut() |
| 154 | .rev() |
| 155 | .find(|(_, barrier)| barrier.cell == cell) |
| 156 | { |
| 157 | barrier.followers.push(held); |
| 158 | } else { |
| 159 | effects.push(Effect::Release { |
| 160 | request: held.request, |
| 161 | channel: held.channel, |
| 162 | result: Ok(()), |
| 163 | }); |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | /// A gated write's durability proof completed. Acknowledge the write only |
| 168 | /// when the replica proved a position that *covers* it — a shorter proof |
| 169 | /// (a lagging or lying replicator) fails it rather than acknowledging a |
| 170 | /// write the node cannot actually restore. Any error fails it. A completion |
| 171 | /// for a gate already drained (fence or deadline) is ignored — the |
| 172 | /// versioned-op discipline used throughout the core. |
| 173 | pub(crate) fn durable_reached( |
| 174 | &mut self, |
| 175 | op: OpId, |
| 176 | result: Result<u64, Failure>, |
| 177 | source: ProofSource, |
| 178 | effects: &mut Vec<Effect>, |
| 179 | ) { |
| 180 | let Some(gate) = self.barriers.get(&op) else { |
| 181 | return; |
| 182 | }; |
| 183 | let proven = matches!(result, Ok(durable) if durable >= gate.position); |
| 184 | // A bucket proof reveals nothing until an ownership read confirms the |
| 185 | // record still names this node at this epoch: "durable in `e<epoch>/`" is not |
| 186 | // durable if the prefix was orphaned, and the bucket cannot refuse a |
| 187 | // stale writer. A fleet proof needs no read — the ensemble |
| 188 | // arbitrated it: a takeover seals a member before restoring, so a |
| 189 | // stale owner's ack-all fails closed. |
| 190 | if proven && source == ProofSource::Bucket { |
| 191 | let (cell, epoch) = (gate.cell.clone(), gate.epoch); |
| 192 | effects.push(Effect::VerifyOwnership { op, cell, epoch }); |
| 193 | return; |
| 194 | } |
| 195 | self.settle_gate(op, proven, effects); |
| 196 | } |
| 197 | |
| 198 | /// Ownership verification for a bucket-proof gate. A record that no longer |
| 199 | /// names this node at this epoch fails the write exactly like an unproven |
| 200 | /// durability result: refuse and reset, never acknowledge into an |
| 201 | /// orphaned lineage. |
| 202 | pub(crate) fn ownership_verified( |
| 203 | &mut self, |
| 204 | op: OpId, |
| 205 | result: Result<(), Failure>, |
| 206 | effects: &mut Vec<Effect>, |
| 207 | ) { |
| 208 | if !self.barriers.contains_key(&op) { |
| 209 | return; |
| 210 | } |
| 211 | self.settle_gate(op, result.is_ok(), effects); |
| 212 | } |
| 213 | |
| 214 | /// Release one withheld output, unpinning it first so the cleanup that |
| 215 | /// ends -- shedding, eviction -- is queued ahead of the release. |
| 216 | fn release_held( |
| 217 | &mut self, |
| 218 | held: Held, |
| 219 | result: Result<(), RequestError>, |
| 220 | effects: &mut Vec<Effect>, |
| 221 | ) { |
| 222 | if self.gate_pinned.remove(&held.request) { |
| 223 | self.activity_finished(held.request, effects); |
| 224 | } |
| 225 | effects.push(Effect::Release { |
| 226 | request: held.request, |
| 227 | channel: held.channel, |
| 228 | result, |
| 229 | }); |
| 230 | } |
| 231 | |
| 232 | fn settle_gate(&mut self, op: OpId, proven: bool, effects: &mut Vec<Effect>) { |
| 233 | let Some(gate) = self.barriers.remove(&op) else { |
| 234 | return; |
| 235 | }; |
| 236 | let result = if proven { |
| 237 | Ok(()) |
| 238 | } else { |
| 239 | Err(RequestError::DurabilityUnproven) |
| 240 | }; |
| 241 | match gate.owner { |
| 242 | // Unpin before releasing: the cleanup this ends -- shedding, |
| 243 | // eviction -- is queued ahead of the response, so a caller that |
| 244 | // sees its write acknowledged sees the residency it released too. |
| 245 | // `activity_finished` re-checks the barrier map, so a request |
| 246 | // holding a second gated write simply re-pins itself here. |
| 247 | GateOwner::Output(held) => self.release_held(held, result, effects), |
| 248 | // The alarm settles only now. A proven commit replays the |
| 249 | // observation the handler made, which routes through |
| 250 | // `alarm_observed` and orders the consume-side wake-entry delete |
| 251 | // -- after the proof, by construction. An unproven one takes the |
| 252 | // re-arm branch a failed handler takes, so the entry stays |
| 253 | // discoverable and at-least-once holds. The replay carries no |
| 254 | // position, so it settles rather than opening a second barrier. |
| 255 | GateOwner::Alarm { |
| 256 | alarm, |
| 257 | at_ms, |
| 258 | covered, |
| 259 | } => { |
| 260 | let outcome = if proven { |
| 261 | Ok((at_ms, covered, None)) |
| 262 | } else { |
| 263 | Err(Failure::Ambiguous) |
| 264 | }; |
| 265 | let (now_ms, now_mono_ms) = (self.now_ms, self.now_mono_ms); |
| 266 | self.alarm_finished( |
| 267 | alarm, |
| 268 | (gate.cell.clone(), gate.epoch), |
| 269 | now_ms, |
| 270 | now_mono_ms, |
| 271 | outcome, |
| 272 | effects, |
| 273 | ); |
| 274 | } |
| 275 | } |
| 276 | // A follower is always an output: an alarm opens a barrier, it never |
| 277 | // trails one. |
| 278 | for held in gate.followers { |
| 279 | self.release_held(held, result, effects); |
| 280 | } |
| 281 | if !proven { |
| 282 | let (id, epoch) = (gate.cell.clone(), gate.epoch); |
| 283 | self.reset_cell(&id, epoch, effects); |
| 284 | } |
| 285 | } |
| 286 | } |