Diffinery

homeflare/celldpublic

celld/crates/logic/src/lifecycle.rs
437 lines · 18.1 KBRaw History
1//! The per-cell coordination lifecycle, reified sans-IO:
2//! `on_event(&mut Cell, now_mono, wall_ms, Event) -> Vec<Effect>`. This is the
3//! target production state machine that `ownership.rs` / the alarm scheduler
4//! execute, and that a deterministic executor drives.
5//!
6//! Topology: authority is a NODE concern. There is no
7//! per-cell renewal here — the node lease (`crate::lease`) is the single
8//! heartbeat, and a cell's cell/own.json record is write-once-then-CAS. The
9//! monotonic self-fence lives at the node level; a cell learns it lost
10//! authority two ways: `NodeFenced` (the node lease lapsed) or `CasRejected`
11//! (a competitor advanced this one cell's epoch).
12//!
13//! Alarms are celld's REAL mechanism, not an idealization: RUN-FIRST, not
14//! claim-then-run (`service_due_alarm` is cell-local — `begin_alarm_handler` is
15//! in-memory, the handler runs, then `finish_alarm_handler` deletes the row).
16//! At-most-once across owners is NOT a durable claim; it is the epoch-prefix
17//! restore (a superseded owner's writes land in a stale prefix, and restore
18//! takes the highest epoch). So alarms are at-least-once — a rerun is possible
19//! before the consume is durable — and I4' ("no rerun after DURABLE success")
20//! holds through the store, not the decision.
21//!
22//! Wake tiers + fail-closed hibernation (I6/I7) fold in next.
23use crate::alarm::alarm_retry;
24use crate::alarm::AlarmRetry;
25use crate::cell::acquire;
26use crate::cell::Acquire;
27use crate::cell::Owner;
28use crate::Etag;
29
30pub type Epoch = u64;
31pub type Gen = u64;
32pub type Ms = u64;
33
34/// The node's view of the cell's alarm row. `retry`/`counted_retry` mirror the
35/// persisted columns production keys its backoff and ceiling on
36/// (`storage.rs`): `retry` drives the exponential backoff, `counted_retry` is
37/// the subset counting toward abandonment. The policy itself is `alarm_retry`.
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub struct AlarmLocal {
40 pub gen: Gen,
41 pub due_wall_ms: Ms,
42 pub retry: u32,
43 pub counted_retry: u32,
44}
45
46#[derive(Clone, Debug, PartialEq, Eq)]
47pub enum Phase {
48 Idle,
49 Probing,
50 Claiming { epoch: Epoch },
51 Owned { epoch: Epoch, etag: Etag },
52 Fenced,
53}
54
55/// What the executor feeds back after performing an `Effect`.
56#[derive(Clone, Debug, PartialEq, Eq)]
57pub enum Event {
58 /// Demand: a request needs this cell resident on this node.
59 Activate,
60 /// Periodic tick (the clocks ride in `on_event`'s params).
61 Tick,
62 GetOwner { owner: Owner, etag: Etag },
63 GetMissing,
64 GetFailed,
65 OwnerLive { live: bool },
66 OwnerLeaseFailed,
67 CasOk { epoch: Epoch, etag: Etag },
68 CasRejected,
69 CasFailed,
70 /// Activation restore completed — the durable alarm truth at restore time
71 /// (None = no alarm, or not yet durable).
72 RestoreOk { alarm: Option<AlarmLocal> },
73 RestoreFailed,
74 /// The restored cell's isolate has completed startup. Startup includes
75 /// loading the deployment and restoring actor identity; neither ownership
76 /// nor a successful restore makes a cell routable.
77 RuntimeReady,
78 RuntimeFailed,
79 /// Publishing the live runtime in the local registry completed. This is
80 /// the activation commit point: only `PublishOk` makes the cell resident
81 /// and serving.
82 PublishOk,
83 PublishFailed,
84 /// User code on a resident cell called `setAlarm` (gen durably unique).
85 ArmAlarm { gen: Gen, due_wall_ms: Ms },
86 /// The handler finished (the executor sampled its outcome).
87 /// `counts_against_limit` is false for failures the caller excuses (e.g. a
88 /// shed under pressure), matching `finish_alarm_handler_with_retry_policy`.
89 AlarmOutcome { gen: Gen, ok: bool, counts_against_limit: bool },
90 /// The eviction sweep decided to hibernate this cell.
91 BeginHibernate,
92 /// The fail-closed hibernate hook's wake-entry PUT result.
93 WakeEntryOk,
94 WakeEntryFailed,
95 /// The node lease lapsed: drop this cell.
96 NodeFenced,
97}
98
99/// What the executor performs. No `CasRenew`: the node lease renews, not cells.
100#[derive(Clone, Debug, PartialEq, Eq)]
101pub enum Effect {
102 Get,
103 GetOwnerLease { node: String },
104 CasCreate { epoch: Epoch },
105 CasWrite { etag: Etag, epoch: Epoch, takeover: bool },
106 RestoreTruth { epoch: Epoch },
107 StartRuntime { epoch: Epoch },
108 PublishResident { epoch: Epoch },
109 StartServing { epoch: Epoch },
110 StopServing,
111 /// Write the alarm into the cell's replicated storage (lagged).
112 ArmDurable { gen: Gen, due_wall_ms: Ms },
113 /// Run the handler — the external effect. RUN-FIRST: no durable claim
114 /// precedes it; the epoch prefix is what makes it safe across owners.
115 RunAlarm { gen: Gen, retry: u32, epoch: Epoch },
116 /// Durable delete of a completed/abandoned alarm.
117 ConsumeAlarm { gen: Gen },
118 /// The fail-closed hibernate hook: publish a durable wake entry so a
119 /// hibernated alarm-bearing cell can be revived. Eviction waits on its OK.
120 PutWakeEntry { gen: Gen, due_wall_ms: Ms },
121 /// Activation consumed the hints — delete this cell's wake entries.
122 DeleteWakeEntries,
123}
124
125pub struct Cell {
126 pub node: String,
127 pub phase: Phase,
128 pub serving: bool,
129 /// Isolate live, truth loaded, and published in the local registry.
130 /// `Owned && !resident` is either hibernated-owned or activation debt.
131 pub resident: bool,
132 pub alarm: Option<AlarmLocal>,
133 /// A fail-closed wake-entry PUT is in flight (mid-hibernation).
134 pub hibernating: bool,
135 inflight: bool,
136 wake_pending: bool,
137 restore_inflight: bool,
138 runtime_start_inflight: bool,
139 publish_inflight: bool,
140 /// Handler in flight: no re-fire until the outcome lands.
141 running: Option<Gen>,
142 pending_owner: Option<(Owner, Etag)>,
143}
144
145impl Cell {
146 pub fn new(node: impl Into<String>) -> Self {
147 Cell {
148 node: node.into(),
149 phase: Phase::Idle,
150 serving: false,
151 resident: false,
152 alarm: None,
153 hibernating: false,
154 inflight: false,
155 wake_pending: false,
156 restore_inflight: false,
157 runtime_start_inflight: false,
158 publish_inflight: false,
159 running: None,
160 pending_owner: None,
161 }
162 }
163
164 /// A cell whose ownership is already held at `epoch` — the acquisition CAS
165 /// won, or a sticky tier-2 restore of retained ownership — positioned
166 /// exactly as the post-`CasOk` state (`Owned`, restore pending) so the
167 /// executor can drive it restore→resident without re-running the CAS.
168 /// Ownership is not in question here; that is the node lease's concern.
169 pub fn owned(node: impl Into<String>, epoch: Epoch, etag: impl Into<Etag>) -> Self {
170 let mut c = Cell::new(node);
171 c.phase = Phase::Owned { epoch, etag: etag.into() };
172 c.restore_inflight = true;
173 c
174 }
175
176 pub fn ready(&self) -> bool {
177 matches!(self.phase, Phase::Owned { .. }) && self.resident
178 }
179
180 fn epoch(&self) -> Option<Epoch> {
181 match self.phase {
182 Phase::Owned { epoch, .. } => Some(epoch),
183 _ => None,
184 }
185 }
186
187 /// The whole per-cell protocol — pure: no I/O, no awaits, no clock reads
188 /// (the clocks are injected). Both clocks are supplied for symmetry with the
189 /// executor's `Clock` port; `_now_mono` is currently unread (alarm backoff
190 /// is wall-scheduled since B1) and returns when the fence folds in.
191 pub fn on_event(&mut self, _now_mono: Ms, wall_ms: Ms, ev: Event) -> Vec<Effect> {
192 let mut out = Vec::new();
193
194 if ev == Event::NodeFenced {
195 return self.fence();
196 }
197
198 match (&self.phase, ev) {
199 (Phase::Idle, Event::Activate) => {
200 self.wake_pending = true;
201 if !self.inflight {
202 self.phase = Phase::Probing;
203 self.inflight = true;
204 out.push(Effect::Get);
205 }
206 }
207 (Phase::Probing, Event::GetMissing) => {
208 self.inflight = true;
209 self.phase = Phase::Claiming { epoch: 1 };
210 out.push(Effect::CasCreate { epoch: 1 });
211 }
212 (Phase::Probing, Event::GetOwner { owner, etag }) => {
213 self.inflight = false;
214 match acquire(Some(&owner), &self.node, None) {
215 Acquire::Take { epoch, takeover } => {
216 self.begin_claim(epoch, etag, takeover, &mut out);
217 }
218 Acquire::NeedLiveness => {
219 self.inflight = true;
220 let node = owner.node.clone();
221 self.pending_owner = Some((owner, etag));
222 out.push(Effect::GetOwnerLease { node });
223 }
224 Acquire::GiveUp | Acquire::Defer => self.give_up(),
225 }
226 }
227 (Phase::Probing, Event::OwnerLive { live }) => {
228 self.inflight = false;
229 if let Some((owner, etag)) = self.pending_owner.take() {
230 match acquire(Some(&owner), &self.node, Some(live)) {
231 Acquire::Take { epoch, takeover } => {
232 self.begin_claim(epoch, etag, takeover, &mut out);
233 }
234 Acquire::Defer | Acquire::GiveUp | Acquire::NeedLiveness => {
235 self.give_up();
236 }
237 }
238 }
239 }
240 (Phase::Probing, Event::GetFailed | Event::OwnerLeaseFailed) => {
241 self.pending_owner = None;
242 self.give_up();
243 }
244 (Phase::Claiming { epoch }, Event::CasOk { epoch: got, etag }) if *epoch == got => {
245 self.inflight = false;
246 self.phase = Phase::Owned { epoch: got, etag };
247 self.restore_inflight = true;
248 out.push(Effect::RestoreTruth { epoch: got });
249 }
250 (Phase::Claiming { .. }, Event::CasRejected | Event::CasFailed) => {
251 self.give_up();
252 }
253 (Phase::Owned { epoch, .. }, Event::RestoreOk { alarm }) if self.restore_inflight => {
254 self.restore_inflight = false;
255 self.alarm = alarm; // durable truth wins over any heap value
256 self.runtime_start_inflight = true;
257 out.push(Effect::StartRuntime { epoch: *epoch });
258 }
259 (Phase::Owned { epoch, .. }, Event::RuntimeReady)
260 if self.runtime_start_inflight =>
261 {
262 self.runtime_start_inflight = false;
263 self.publish_inflight = true;
264 out.push(Effect::PublishResident { epoch: *epoch });
265 }
266 (Phase::Owned { epoch, .. }, Event::PublishOk) if self.publish_inflight => {
267 self.publish_inflight = false;
268 self.resident = true;
269 self.serving = true;
270 self.wake_pending = false;
271 out.push(Effect::StartServing { epoch: *epoch });
272 out.push(Effect::DeleteWakeEntries);
273 }
274 // ---- fail-closed hibernation ----
275 (Phase::Owned { .. }, Event::BeginHibernate)
276 if self.resident && !self.hibernating && self.running.is_none() =>
277 {
278 match self.alarm {
279 // FAIL CLOSED: no eviction until the wake entry is durable.
280 Some(a) => {
281 self.hibernating = true;
282 out.push(Effect::PutWakeEntry { gen: a.gen, due_wall_ms: a.due_wall_ms });
283 }
284 // No alarm to wake for: hibernate immediately.
285 None => {
286 self.resident = false;
287 self.serving = false;
288 out.push(Effect::StopServing);
289 }
290 }
291 }
292 (Phase::Owned { .. }, Event::WakeEntryOk) if self.hibernating => {
293 self.hibernating = false;
294 // Re-check activity after the round trip; the alarm may have
295 // begun firing inside the window. The heap keeps `alarm` (tier-2).
296 if self.running.is_none() {
297 self.resident = false;
298 self.serving = false;
299 out.push(Effect::StopServing);
300 }
301 }
302 (Phase::Owned { .. }, Event::WakeEntryFailed) if self.hibernating => {
303 // The entry PUT failed: stay resident (the pin is the fallback).
304 // An executor that skipped this gate would evict and lose the wake.
305 self.hibernating = false;
306 }
307 (Phase::Owned { .. }, Event::RestoreFailed) => {
308 self.restore_inflight = false;
309 }
310 (Phase::Owned { .. }, Event::RuntimeFailed) => {
311 self.runtime_start_inflight = false;
312 }
313 (Phase::Owned { .. }, Event::PublishFailed) => {
314 self.publish_inflight = false;
315 }
316 (Phase::Owned { .. }, Event::CasRejected) => {
317 out = self.fence();
318 }
319 // ---- alarm: arm / run-first fire / consume ----
320 (Phase::Owned { .. }, Event::ArmAlarm { gen, due_wall_ms }) if self.resident => {
321 self.alarm = Some(AlarmLocal { gen, due_wall_ms, retry: 0, counted_retry: 0 });
322 out.push(Effect::ArmDurable { gen, due_wall_ms });
323 }
324 (Phase::Owned { epoch, .. }, Event::Tick) => {
325 let epoch = *epoch;
326 // tier-1 resident scheduler: RUN-FIRST when due (celld's real
327 // cell-local fire — no durable claim precedes the handler).
328 // Backoff is encoded in `due_wall_ms` (rescheduled forward on
329 // failure, as production reschedules `at_ms`), so the due gate
330 // is the only gate — no separate monotonic timer.
331 if self.resident && self.serving && self.running.is_none() {
332 if let Some(a) = self.alarm {
333 if wall_ms >= a.due_wall_ms {
334 self.running = Some(a.gen);
335 out.push(Effect::RunAlarm { gen: a.gen, retry: a.retry, epoch });
336 }
337 }
338 }
339 // tier-2: hibernated-owned with a due alarm re-activates. Sticky
340 // (same epoch): the node kept its lease and fenced epoch, so this
341 // is a local restore, not a re-acquisition.
342 let alarm_due = self.alarm.is_some_and(|a| wall_ms >= a.due_wall_ms);
343 if !self.resident
344 && !self.hibernating
345 && !self.restore_inflight
346 && !self.runtime_start_inflight
347 && !self.publish_inflight
348 && (self.wake_pending || alarm_due)
349 {
350 self.restore_inflight = true;
351 out.push(Effect::RestoreTruth { epoch });
352 }
353 }
354 (Phase::Owned { epoch, .. }, Event::Activate) => {
355 self.wake_pending = true;
356 if !self.resident
357 && !self.hibernating
358 && !self.restore_inflight
359 && !self.runtime_start_inflight
360 && !self.publish_inflight
361 {
362 self.restore_inflight = true;
363 out.push(Effect::RestoreTruth { epoch: *epoch });
364 }
365 }
366 (Phase::Owned { .. }, Event::AlarmOutcome { gen, ok, counts_against_limit }) => {
367 if self.running == Some(gen) {
368 self.running = None;
369 }
370 if let Some(mut a) = self.alarm {
371 if a.gen == gen {
372 // A failure reschedules by `alarm::alarm_retry` — the
373 // SAME schedule production persists (storage.rs) —
374 // bumping the counters, or abandons at the ceiling.
375 // Success consumes durably.
376 let retry = (!ok).then(|| {
377 alarm_retry(
378 wall_ms as i64,
379 a.retry as i64,
380 a.counted_retry as i64,
381 counts_against_limit,
382 )
383 });
384 match retry {
385 Some(AlarmRetry::Retry { at_ms }) => {
386 a.due_wall_ms = at_ms as Ms;
387 a.retry += 1;
388 a.counted_retry += u32::from(counts_against_limit);
389 self.alarm = Some(a);
390 }
391 // success, or the retry ceiling: abandon durably.
392 None | Some(AlarmRetry::GiveUp) => {
393 self.alarm = None;
394 out.push(Effect::ConsumeAlarm { gen });
395 }
396 }
397 }
398 }
399 }
400 _ => {}
401 }
402 out
403 }
404
405 fn begin_claim(&mut self, epoch: Epoch, etag: Etag, takeover: bool, out: &mut Vec<Effect>) {
406 self.phase = Phase::Claiming { epoch };
407 self.inflight = true;
408 out.push(Effect::CasWrite { etag, epoch, takeover });
409 }
410
411 fn give_up(&mut self) {
412 self.phase = Phase::Idle;
413 self.inflight = false;
414 self.wake_pending = false;
415 }
416
417 fn fence(&mut self) -> Vec<Effect> {
418 let was_serving = self.serving;
419 self.phase = Phase::Fenced;
420 self.serving = false;
421 self.resident = false;
422 self.hibernating = false;
423 self.restore_inflight = false;
424 self.runtime_start_inflight = false;
425 self.publish_inflight = false;
426 self.inflight = false;
427 self.wake_pending = false;
428 self.alarm = None;
429 self.running = None;
430 self.pending_owner = None;
431 if was_serving {
432 vec![Effect::StopServing]
433 } else {
434 vec![]
435 }
436 }
437}