Diffinery

homeflare/celldpublic

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