Diffinery

homeflare/celldpublic

172 lines · 7.1 KBRaw History
1//! The node-lease lifecycle decision, reified sans-IO.
2//!
3//! `ownership.rs`'s `renewal_loop` is a tokio task that reads the monotonic
4//! clock, CAS-renews an S3 object, and calls `std::process::exit(3)` inline
5//! when the lease lapses. The DECISION buried in it — hold / renew / fence /
6//! release — is a pure function of a few scalars; only the clock read and the
7//! effects are I/O. Here that decision is extracted so it runs identically in
8//! production (executor: tokio renew, real `process::exit`) and under a
9//! deterministic executor (a state transition, no process dies).
10//!
11//! Authority is modeled at the NODE level, as production ships it: one lease
12//! per node, and a lapse fences every cell the node owns at once. This is the
13//! topology a per-cell CAS model idealizes away.
14
15/// The monotonic, already-sampled inputs to one renewal tick. The clock reads
16/// (`Instant::elapsed`) happen at the edge; the core sees only deltas, so it is
17/// pure and replayable.
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub struct LeaseTick {
20 /// Is a lease currently held? (`lease.as_ref().is_some()`)
21 pub lease_held: bool,
22 /// Cells this node is actively serving — the fence blast radius.
23 pub active_cells: usize,
24 /// `active_cells == 0 && idle >= linger`: a lazy node may shed here.
25 pub idle_long_enough: bool,
26 /// Monotonic ms since the last SUCCESSFUL renewal — the fence is measured
27 /// on this, never the wall clock (a backward wall step must not suppress it).
28 pub elapsed_since_ok_ms: u64,
29 /// Monotonic ms since the last renewal ATTEMPT (renewal cadence is ttl/3).
30 pub elapsed_since_renew_ms: u64,
31 pub ttl_ms: u64,
32 /// Lazy mode releases an idle lease instead of holding it; Continuous and
33 /// Shadow both fence on lapse and never lazily release.
34 pub lazy: bool,
35}
36
37/// What the executor must perform this tick. `Fence` is the effect that was
38/// `std::process::exit(3)` inline; the core names it instead of causing it.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum LeaseAction {
41 /// No lease held — nothing to do.
42 NoLease,
43 /// Nothing this tick: lease is live and not yet due for renewal.
44 Hold,
45 /// CAS-renew the lease now.
46 Renew,
47 /// Drop the lease gracefully (idle lazy node, or a lapsed lease on a lazy
48 /// node with nothing to protect). No halt.
49 Release,
50 /// Halt: authority was lost while cells still depend on it. In production
51 /// the executor turns this into `process::exit(3)`.
52 Fence,
53}
54
55/// The pre-renewal decision — a total function of one tick.
56pub fn decide(t: &LeaseTick) -> LeaseAction {
57 if !t.lease_held {
58 return LeaseAction::NoLease;
59 }
60 // A lazy node with no active cells past its linger sheds proactively.
61 if t.lazy && t.idle_long_enough {
62 return LeaseAction::Release;
63 }
64 // Monotonic self-fence: too long since our own last successful renewal.
65 if t.elapsed_since_ok_ms > t.ttl_ms {
66 return fence_or_release(t.active_cells, t.lazy);
67 }
68 if t.elapsed_since_renew_ms >= t.ttl_ms / 3 {
69 return LeaseAction::Renew;
70 }
71 LeaseAction::Hold
72}
73
74/// A renewal CAS returned 412 — another process holds our node id. Same choice
75/// as a fence: halt if anything depends on us, else release quietly. Called by
76/// the executor after it performs a `Renew` and sees the rejection.
77pub fn on_renew_rejected(active_cells: usize, lazy: bool) -> LeaseAction {
78 fence_or_release(active_cells, lazy)
79}
80
81/// Lost authority: fence when cells depend on it (any active cell, or a
82/// non-lazy node that must stay authoritative), otherwise release.
83fn fence_or_release(active_cells: usize, lazy: bool) -> LeaseAction {
84 if active_cells > 0 || !lazy {
85 LeaseAction::Fence
86 } else {
87 LeaseAction::Release
88 }
89}
90
91/// Whether a node-session lease is still live at `now_ms` — the one comparison
92/// the whole fleet shares (`ownership.rs`): a lease is live strictly while its
93/// expiry is in the future.
94pub fn lease_live(expires_ms: u64, now_ms: u64) -> bool {
95 expires_ms > now_ms
96}
97
98/// A peer node-session record as dead-node reconciliation reads it. Built
99/// from the bucket `NodeRec` at the edge; the core sees only these fields.
100pub struct NodeRecord<'a> {
101 pub expires_ms: u64,
102 /// The node id the record claims — may differ from the key's node after a
103 /// session-id reuse, in which case its ownership generation is not this
104 /// key's to inherit.
105 pub node: &'a str,
106 pub ownership_index_generation: &'a str,
107}
108
109/// Classification of one `nodes/<key_node>.json` record during dead-node
110/// reconciliation.
111#[derive(Clone, Debug, PartialEq, Eq)]
112pub enum NodeLiveness {
113 /// The lease is still in the future — leave it alone.
114 Live,
115 /// Lapsed or absent: its cells may hold an armed alarm with no wake entry.
116 /// The generation is the dead node's own, or empty when a different (reused)
117 /// session wrote the record.
118 Dead { ownership_index_generation: String },
119}
120
121/// `record` is the read of the node key (`None` if absent — also dead).
122pub fn node_liveness(
123 record: Option<NodeRecord>,
124 key_node: &str,
125 now_ms: u64,
126) -> NodeLiveness {
127 match record {
128 Some(r) if lease_live(r.expires_ms, now_ms) => NodeLiveness::Live,
129 Some(r) => NodeLiveness::Dead {
130 ownership_index_generation: if r.node == key_node {
131 r.ownership_index_generation.to_string()
132 } else {
133 String::new()
134 },
135 },
136 None => NodeLiveness::Dead { ownership_index_generation: String::new() },
137 }
138}
139
140/// Storage-timeout budgets a node must satisfy for its self-fence to mean
141/// what it claims. Reified here because the relationship between celld's
142/// SDK timeouts and its lease TTL is a correctness property, not a tuning
143/// preference, and nothing asserted it before 2026-08-01.
144#[derive(Clone, Copy, Debug)]
145pub struct FenceBudget {
146 /// Longest a single storage attempt may run.
147 pub attempt_timeout_ms: u64,
148 /// Longest a storage call may run including retries.
149 pub operation_timeout_ms: u64,
150 /// The node lease TTL — the deadline the self-fence enforces.
151 pub ttl_ms: u64,
152 /// Does the fence run independently of the renewal's I/O (its own
153 /// watchdog), or only after the renewal call returns?
154 pub fence_is_independent: bool,
155}
156
157/// Can this configuration fence within its TTL, whatever storage does?
158///
159/// The 2026-08-01 lab partition is the case: a black-holed endpoint made a
160/// renewal wait unboundedly, and because the fence ran only after that call
161/// returned, a 10-second TTL was exceeded by 124 seconds. Either the fence
162/// is independent of the call (a watchdog), or every storage call must
163/// finish well inside the TTL. celld now does BOTH; this states why either
164/// alone is insufficient.
165pub fn fence_is_timely(b: &FenceBudget) -> bool {
166 if b.fence_is_independent {
167 return true;
168 }
169 // Without independence the fence inherits the call's worst case, and it
170 // must still leave room to act before the TTL expires.
171 b.operation_timeout_ms < b.ttl_ms && b.attempt_timeout_ms < b.ttl_ms
172}