Skip to main content

ozzy_replication/
driver.rs

1//! Deterministic normal-to-election scheduling with explicit durable completions.
2//!
3//! The adapter supplies monotonic process-relative time and authenticated,
4//! wire-validated controls. One poll emits at most one action; broadcast has
5//! exactly two destinations. Keep outbound work bounded and independently retry
6//! sends without blocking receive, timers, or disk completion. Poll again after
7//! each action/completion, subject to the adapter's count/byte scheduling budget.
8//! Selection and pinned history lookup remain explicit adapter work. The driver
9//! owns in-flight installation while the adapter stages and publishes on its disk
10//! worker. This driver does not itself enable networked process failover.
11
12mod deadline;
13mod exit_view;
14mod installation;
15mod poll;
16mod receive;
17mod storage;
18mod validation;
19
20pub use installation::ActivationTicket;
21pub use validation::ValidationTicket;
22
23use std::time::Duration;
24
25use ozzy_proto::NodeId;
26
27use crate::wire::Control;
28use crate::{
29    Configuration, Digest, InstallingView, LogSource, NormalReplica, OpNumber, Prefix,
30    PromiseTicket, ReplicaSnapshot, ReplicationError, Scope, SelectedView, Status, ViewChange,
31    ViewChangeError, VoterIndex, VoterSet, Voters,
32};
33
34/// Independent heartbeat, progress, and election retry intervals.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct Timing {
37    /// Period between primary idle commit announcements.
38    pub heartbeat: Duration,
39    /// Maximum primary silence, missing commit progress, or stalled local persistence.
40    pub primary_timeout: Duration,
41    /// Minimum interval between repeated first/second-phase election sends.
42    pub retransmit: Duration,
43    /// Initial deadline for election, selected-log publication, or tail activation.
44    pub election_timeout: Duration,
45    /// Ceiling when doubling the deadline after unsuccessful election timeouts.
46    pub max_election_timeout: Duration,
47}
48
49impl Timing {
50    fn validate(self, now: Duration) -> Result<(), DriverError> {
51        if self.heartbeat.is_zero()
52            || self.retransmit.is_zero()
53            || self.heartbeat >= self.primary_timeout
54            || self.retransmit >= self.election_timeout
55            || self.election_timeout > self.max_election_timeout
56        {
57            return Err(DriverError::InvalidTiming);
58        }
59        if now
60            .checked_add(self.max_election_timeout.max(self.primary_timeout))
61            .is_none()
62        {
63            return Err(DriverError::TimeExhausted);
64        }
65        Ok(())
66    }
67}
68
69/// One bounded network or storage request. Not evidence of its completion.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum Action {
72    /// Send to both other configured voters, never to the local voter.
73    Broadcast(Control),
74    /// Send to one configured voter.
75    Send {
76        /// Configured destination identity, not a socket routing identity.
77        to: NodeId,
78        /// Control message to encode in that peer's established session.
79        message: Control,
80    },
81    /// Persist the exact frozen history and view promise on the disk worker.
82    PersistPromise(PromiseTicket),
83}
84
85/// Owned protocol phase; extracting it does not establish installation authority.
86#[derive(Debug)]
87#[expect(
88    clippy::large_enum_variant,
89    reason = "move preallocated roles without boxing"
90)]
91pub enum Role {
92    /// Existing normal state, including any fault/fence status.
93    Normal(NormalReplica),
94    /// Fenced old state and bounded election evidence.
95    ViewChanging(ViewChange),
96    /// Owned selected-log publication; no normal authority until exact completion.
97    Installing(InstallingView),
98    /// A consuming transition failed and took the previous phase with it.
99    /// Every event fails closed; only restart recovery resumes this voter.
100    Fenced(Scope),
101}
102
103/// Timer and election-message driver for one fixed three-voter group.
104///
105/// No clocks, allocations, I/O, or automatic durability assertions on transitions.
106/// Old writes must settle before a promise; a pending promise survives later views.
107#[derive(Debug)]
108pub struct ReplicaDriver {
109    role: Role,
110    configuration: Configuration,
111    local: VoterIndex,
112    timing: Timing,
113    now: Duration,
114    contact_deadline: Duration,
115    progress_deadline: Duration,
116    persistence_deadline: Duration,
117    /// When busy local storage last completed work; `None` while idle.
118    storage_busy_since: Option<Duration>,
119    election_deadline: Duration,
120    election_delay: Duration,
121    retry_at: Duration,
122    start_pending: bool,
123    report_pending: bool,
124    commit_pending: bool,
125    // At most one selected-tail activation response per remote voter. A late
126    // installed voter cannot receive fresh payload until that tail is applied.
127    activation_pending: VoterSet,
128    /// Current-view timeout suspicions. Never durable or history-selection votes.
129    exit_votes: VoterSet,
130    /// When each peer's suspicion of the current view last arrived.
131    exit_heard_at: Voters<Duration>,
132    /// `None` means local suspicion is inactive or was withdrawn after progress.
133    exit_retry_at: Option<Duration>,
134    /// An older view peers still ask to leave, and which voters asked. This
135    /// voter already left it.
136    exit_echo: Option<(Scope, VoterSet)>,
137    /// Earliest next answer to each voter's request to leave an older view.
138    exit_echo_at: Voters<Duration>,
139}
140
141impl ReplicaDriver {
142    /// Attach scheduling to a bootstrapped or completely installed normal core.
143    /// Intact restart must instead enter the existing nonvoting recovery path.
144    pub fn from_normal(
145        normal: NormalReplica,
146        now: Duration,
147        timing: Timing,
148    ) -> Result<Self, DriverError> {
149        let (configuration, local) = normal.driver_identity();
150        Self::new(Role::Normal(normal), configuration, local, now, timing)
151    }
152
153    /// Resume scheduling after intact-disk recovery or a superseded installation.
154    /// The supplied core is already fenced and cannot restore old normal authority.
155    pub fn from_view_change(
156        changing: ViewChange,
157        now: Duration,
158        timing: Timing,
159    ) -> Result<Self, DriverError> {
160        let configuration = changing.configuration;
161        let local = changing.local;
162        Self::new(
163            Role::ViewChanging(changing),
164            configuration,
165            local,
166            now,
167            timing,
168        )
169    }
170
171    fn new(
172        role: Role,
173        configuration: Configuration,
174        local: VoterIndex,
175        now: Duration,
176        timing: Timing,
177    ) -> Result<Self, DriverError> {
178        timing.validate(now)?;
179        let changing = matches!(role, Role::ViewChanging(_));
180        let activating =
181            matches!(&role, Role::Normal(normal) if !normal.snapshot().ready_for_appends);
182        Ok(Self {
183            role,
184            configuration,
185            local,
186            timing,
187            now,
188            contact_deadline: now.saturating_add(timing.primary_timeout),
189            persistence_deadline: now.saturating_add(timing.primary_timeout),
190            storage_busy_since: None,
191            progress_deadline: now
192                + if activating {
193                    timing.election_timeout
194                } else {
195                    timing.primary_timeout
196                },
197            election_deadline: now.saturating_add(timing.election_timeout),
198            election_delay: timing.election_timeout,
199            retry_at: now
200                + if changing {
201                    timing.retransmit
202                } else {
203                    timing.heartbeat
204                },
205            start_pending: changing,
206            report_pending: changing,
207            commit_pending: false,
208            activation_pending: VoterSet::EMPTY,
209            exit_votes: VoterSet::EMPTY,
210            exit_heard_at: Voters::splat(Duration::ZERO),
211            exit_retry_at: None,
212            exit_echo: None,
213            exit_echo_at: Voters::splat(Duration::ZERO),
214        })
215    }
216
217    /// Inspect normal evidence. No mutable access can bypass scheduling/fencing.
218    pub fn normal(&self) -> Option<&NormalReplica> {
219        match &self.role {
220            Role::Normal(normal) => Some(normal),
221            Role::ViewChanging(_) | Role::Installing(_) | Role::Fenced(_) => None,
222        }
223    }
224
225    /// A fenced old view needs an actual barrier before publishing its promise.
226    pub fn election_needs_sync(&self) -> bool {
227        let Role::ViewChanging(changing) = &self.role else {
228            return false;
229        };
230        let journal = changing.normal_snapshot().journal;
231        journal.written == journal.accepted && journal.written > journal.durable
232    }
233
234    /// Current normal or proposed election scope, not necessarily durable.
235    pub fn scope(&self) -> Scope {
236        match &self.role {
237            Role::Normal(normal) => normal.scope(),
238            Role::ViewChanging(changing) => changing.scope(),
239            Role::Installing(installing) => installing.requested_scope(),
240            Role::Fenced(scope) => *scope,
241        }
242    }
243
244    /// Extract phase ownership. Pending I/O still must settle; a replacement driver
245    /// must preserve newer-view fencing rather than resume an old normal role.
246    pub fn into_role(self) -> Role {
247        self.role
248    }
249
250    /// Select after collecting reports, using only nonblocking pinned-history lookup.
251    /// Missing history/quorum is recoverable. Success is not installed authority.
252    pub fn select(
253        &mut self,
254        lookup: impl FnMut(LogSource, Prefix) -> Option<Digest>,
255    ) -> Result<SelectedView, DriverError> {
256        Ok(self.changing()?.select(lookup)?)
257    }
258
259    /// Frozen election sources; their bytes still require exact-tail verification.
260    pub fn history_sources(&self) -> [Option<LogSource>; 3] {
261        match &self.role {
262            Role::ViewChanging(changing) => changing.history_sources(),
263            Role::Normal(_) | Role::Installing(_) | Role::Fenced(_) => [None; 3],
264        }
265    }
266
267    /// Operations whose prefixes this election may look up in its chosen
268    /// source. One lookup scan can verify each one it passes.
269    pub fn lookup_ops(&self) -> [Option<OpNumber>; 8] {
270        match &self.role {
271            Role::ViewChanging(changing) => changing.lookup_ops(),
272            Role::Normal(_) | Role::Installing(_) | Role::Fenced(_) => [None; 8],
273        }
274    }
275
276    fn changing(&mut self) -> Result<&mut ViewChange, DriverError> {
277        match &mut self.role {
278            Role::ViewChanging(changing) => Ok(changing),
279            Role::Normal(_) | Role::Installing(_) => Err(ReplicationError::WrongRole.into()),
280            Role::Fenced(_) => Err(ViewChangeError::Faulted.into()),
281        }
282    }
283
284    fn require_normal(&self) -> Result<&NormalReplica, DriverError> {
285        Ok(self.normal().ok_or(ReplicationError::NotNormal)?)
286    }
287
288    /// Reject events once storage, lineage, or a failed transition faulted this voter.
289    fn require_healthy(&self) -> Result<(), DriverError> {
290        match &self.role {
291            Role::Normal(normal) if normal.snapshot().status == Status::Faulted => {
292                Err(ViewChangeError::Faulted.into())
293            }
294            Role::ViewChanging(changing)
295                if changing.normal_snapshot().status == Status::Faulted =>
296            {
297                Err(ViewChangeError::Faulted.into())
298            }
299            Role::Installing(installing) => Ok(installing.require_pending()?),
300            Role::Fenced(_) => Err(ViewChangeError::Faulted.into()),
301            Role::Normal(_) | Role::ViewChanging(_) => Ok(()),
302        }
303    }
304
305    /// Take the role for a consuming transition. The driver stays fenced until
306    /// the caller installs the next role; a failed transition leaves it fenced.
307    fn take_role(&mut self) -> Role {
308        let fenced = Role::Fenced(self.scope());
309        std::mem::replace(&mut self.role, fenced)
310    }
311
312    fn observe_time(&mut self, now: Duration) -> Result<(), DriverError> {
313        if now < self.now {
314            return Err(DriverError::ClockRegressed);
315        }
316        self.timing.validate(now)?;
317        self.now = now;
318        Ok(())
319    }
320
321    fn progress_timeout(&self) -> Duration {
322        if self
323            .normal()
324            .is_some_and(|normal| normal.snapshot().ready_for_appends)
325        {
326            self.timing.primary_timeout
327        } else {
328            self.election_delay
329        }
330    }
331
332    fn observe_normal_progress(
333        &mut self,
334        previous: &ReplicaSnapshot,
335        current: &ReplicaSnapshot,
336        now: Duration,
337    ) {
338        if current.committed != previous.committed {
339            self.progress_deadline = now.saturating_add(self.progress_timeout());
340        }
341        if current.journal.durable > previous.journal.durable {
342            self.persistence_deadline = now.saturating_add(self.timing.primary_timeout);
343        }
344    }
345
346    fn normal_timed_out(&self, snapshot: &ReplicaSnapshot) -> bool {
347        let primary = VoterIndex::primary(snapshot.scope.view) == self.local;
348        let outstanding = snapshot.accepted != snapshot.committed || !snapshot.ready_for_appends;
349        (!primary && self.now >= self.contact_deadline)
350            || (outstanding && self.now >= self.progress_deadline)
351            || (snapshot.accepted.op > snapshot.journal.durable
352                && self.now >= self.persistence_deadline)
353            || self
354                .storage_busy_since
355                .is_some_and(|since| self.now >= since.saturating_add(self.timing.primary_timeout))
356    }
357
358    fn next_view(&mut self) -> Result<(), DriverError> {
359        let view = self
360            .scope()
361            .view
362            .checked_add(1)
363            .ok_or(ViewChangeError::ViewExhausted)?;
364        self.change_view(view)
365    }
366
367    fn change_view(&mut self, view: u64) -> Result<(), DriverError> {
368        match &mut self.role {
369            Role::ViewChanging(changing) => changing.advance_view(view)?,
370            Role::Installing(installing) => installing.request_view(view)?,
371            Role::Normal(normal) if normal.snapshot().status == Status::Faulted => {
372                return Err(ViewChangeError::Faulted.into());
373            }
374            Role::Normal(_) => {
375                let Role::Normal(normal) = self.take_role() else {
376                    return Err(ViewChangeError::Faulted.into());
377                };
378                self.role = Role::ViewChanging(normal.into_view_change(view)?);
379            }
380            Role::Fenced(_) => return Err(ViewChangeError::Faulted.into()),
381        }
382        self.exit_votes = VoterSet::EMPTY;
383        self.exit_retry_at = None;
384        self.election_deadline = self.now.saturating_add(self.election_delay);
385        self.retry_at = self.now.saturating_add(self.timing.retransmit);
386        self.start_pending = true;
387        self.report_pending = true;
388        self.commit_pending = false;
389        self.activation_pending = VoterSet::EMPTY;
390        Ok(())
391    }
392}
393
394/// Rejected scheduler event. No clock or packet can bypass core authority checks.
395#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
396pub enum DriverError {
397    /// Intervals must be positive and retries shorter than their failure deadlines.
398    #[error("invalid replica timing intervals")]
399    InvalidTiming,
400    /// The adapter's process-relative monotonic clock moved backward.
401    #[error("replica clock regressed")]
402    ClockRegressed,
403    /// A deadline cannot be represented without wrapping.
404    #[error("replica clock exhausted")]
405    TimeExhausted,
406    /// Worker-side validation used a different voter, writer, role, or application prefix.
407    #[error("stale replica application validation")]
408    StaleValidation,
409    /// Normal membership, lineage, status, or journal rejection.
410    #[error(transparent)]
411    Replication(#[from] ReplicationError),
412    /// View-change promise, selection, or storage rejection.
413    #[error(transparent)]
414    ViewChange(#[from] ViewChangeError),
415}