Skip to main content

schedr_agent/
master_time.rs

1//! What a worker knows of master time (B225, B228): the leading master's monotonic clock, on
2//! which every deadline the master and its workers must agree on is set.
3//!
4//! Every master message carries the master's clock (`MasterClock`): its timeline, master time
5//! when it was sent, and the latest heartbeat the master had heard on this stream. That
6//! heartbeat (or the `Register`, number 0) was sent before the message, so master time
7//! `master_ms` happened after the worker sent it: master time `X` is reached no earlier than
8//! the send time plus `X - master_ms` (Cristian's bound), less what the two clocks' rates may
9//! differ by. The worker keeps the tightest such sample and decides by it, never by its own idea
10//! of when the master sent something, and never by a wall clock.
11//!
12//! The tightest sample is taken over a window (decision 447: 10 minutes by default): an older
13//! one, however tight, drifts its 0.1 % from further back.
14//!
15//! The worker's own clock is the one that keeps counting through a suspend (`CLOCK_BOOTTIME`):
16//! one that stopped would make it late. A pause that stops even that one (a frozen VM) shows
17//! as its wall clock running ahead of it, one machine's two clocks compared: the worker then
18//! counts any deadline as passed.
19
20use std::collections::VecDeque;
21use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
22use std::time::{Duration, SystemTime};
23
24use schedr_proto::pb;
25
26/// How much the master's and the worker's clocks may differ in rate, per thousand: Linux slews
27/// a clock by at most 500 ppm, so two of them by at most 1000 ppm.
28const DRIFT_PER_MILLE: u32 = 1;
29
30/// The wall clock running this much ahead of the boot clock since the sample, plus
31/// [`PAUSE_PER_MILLE`] of the time since, means a pause the boot clock didn't count.
32const PAUSE_SLACK: Duration = Duration::from_secs(1);
33
34/// The part of the time since the sample the two clocks may drift apart by, per thousand.
35const PAUSE_PER_MILLE: u32 = 2;
36
37/// At most so many messages wait to be heard of (the oldest dropped first): a session that
38/// silent has ended. Every message is numbered (B240), so it is bounded by what a session sends
39/// over a round trip; dropped, the master's naming one finds nothing, and its cutoff counts
40/// from an earlier send (sooner, never later).
41pub const SENT_KEPT: usize = 100_000;
42
43/// How far back the tightest sample is looked for (decision 447,
44/// `SCHEDR_HIDDEN__WORKER__MASTER_SAMPLE_WINDOW`).
45pub const DEFAULT_SAMPLE_WINDOW: Duration = Duration::from_mins(10);
46
47/// The wall-clock difference from the master, beyond the round trip, that a worker warns
48/// about (decision 449, B232; `SCHEDR_HIDDEN__WORKER__CLOCK_SKEW_WARNING`).
49pub const DEFAULT_SKEW_WARNING: Duration = Duration::from_secs(2);
50
51/// The worker's clocks at one moment.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub struct Local {
54    /// Its boot clock (counts through suspend).
55    pub boot: Duration,
56    /// Its wall clock: only to see a pause the boot clock didn't count.
57    pub wall: SystemTime,
58}
59
60impl Local {
61    /// The clocks now.
62    #[must_use]
63    pub fn now() -> Self {
64        Self {
65            boot: boot_now(),
66            wall: SystemTime::now(),
67        }
68    }
69}
70
71/// The boot clock: time since boot, suspend included. Linux's `CLOCK_BOOTTIME`; elsewhere
72/// (macOS) `CLOCK_MONOTONIC`, which counts a suspend there too.
73#[must_use]
74pub fn boot_now() -> Duration {
75    #[cfg(any(target_os = "linux", target_os = "android"))]
76    let clock = rustix::time::ClockId::Boottime;
77    #[cfg(not(any(target_os = "linux", target_os = "android")))]
78    let clock = rustix::time::ClockId::Monotonic;
79    let now = rustix::time::clock_gettime(clock);
80    Duration::new(
81        u64::try_from(now.tv_sec).unwrap_or(0),
82        u32::try_from(now.tv_nsec).unwrap_or(0),
83    )
84}
85
86/// Whether the worker was paused between `then` and `now` without its boot clock counting it:
87/// its wall clock ran ahead of it by more than the two may drift apart.
88fn paused(then: Local, now: Local) -> bool {
89    let since = now.boot.saturating_sub(then.boot);
90    let walked = now.wall.duration_since(then.wall).unwrap_or_default();
91    walked > since + PAUSE_SLACK + since / 1000 * PAUSE_PER_MILLE
92}
93
94/// A master message's clock paired with when the worker sent what it had heard, and when the
95/// message arrived.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97struct Sample {
98    timeline: u64,
99    sent: Local,
100    master_ms: i64,
101    arrived: Local,
102}
103
104impl Sample {
105    /// Whether this sample bounds every master time after it at least as late as `older`
106    /// does (Grok's review of D442): its bound for `X` is `sent + (X - master_ms)` less the
107    /// drift allowance, so it is when `sent - older.sent >= (master_ms - older.master_ms)`
108    /// less that allowance, whatever `X`. An equally tight later sample so replaces an old one,
109    /// and the allowance counts from a recent sample, not from the session's first.
110    fn at_least_as_tight_as(&self, older: &Self) -> bool {
111        let sent = i128::try_from(self.sent.boot.as_nanos()).unwrap_or(i128::MAX)
112            - i128::try_from(older.sent.boot.as_nanos()).unwrap_or(i128::MAX);
113        let master = (i128::from(self.master_ms) - i128::from(older.master_ms)) * 1_000_000;
114        let allowed = master - master / 1000 * i128::from(DRIFT_PER_MILLE);
115        sent >= allowed
116    }
117}
118
119impl Sample {
120    /// Half its round trip: how far its estimate of master time may be off, but for drift.
121    fn half_round_trip(&self) -> Duration {
122        self.arrived.boot.saturating_sub(self.sent.boot) / 2
123    }
124
125    /// Whether this later sample estimates master time from now on at least as closely as
126    /// `older`: its half round trip within `older`'s plus the drift allowance since `older`.
127    fn places_as_closely_as(&self, older: &Self) -> bool {
128        let since = self.sent.boot.saturating_sub(older.sent.boot);
129        self.half_round_trip() <= older.half_round_trip() + since / 1000 * DRIFT_PER_MILLE
130    }
131}
132
133/// How far `master_ms` (Unix milliseconds) lies outside `from..=to`: zero inside it.
134fn wall_skew(master_ms: i64, from: SystemTime, to: SystemTime) -> Duration {
135    let master = SystemTime::UNIX_EPOCH
136        + Duration::from_millis(u64::try_from(master_ms).unwrap_or_default());
137    master
138        .duration_since(to)
139        .or_else(|_| from.duration_since(master))
140        .unwrap_or_default()
141}
142
143/// The latest master message's stamp: its master time and wall clock, and when it arrived.
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub struct LastStamp {
146    /// Master time on it.
147    pub master_ms: i64,
148    /// The master's wall clock on it, Unix milliseconds.
149    pub wall_ms: i64,
150    /// When it arrived.
151    pub arrived: Local,
152}
153
154/// What the best sample says now (for metrics, decision 448).
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156pub struct SampleReading {
157    /// How long ago its heartbeat was sent.
158    pub age: Duration,
159    /// Its heartbeat's round trip: sent to the stamped answer's arrival.
160    pub round_trip: Duration,
161}
162
163/// What a session sent that the master hasn't named as heard yet, and the latest of the
164/// master's messages it has handled (B240). Shared by [`MasterTime`], which reads the sends
165/// when a stamp names one, and the session's sender, which numbers and stamps each message as
166/// it queues it.
167#[derive(Debug, Clone)]
168pub struct Outbox {
169    /// What it sent and the master hasn't shown it heard: number, when sent.
170    sent: VecDeque<(u64, Local)>,
171    /// The next message's number (the `Register` is 0).
172    next: u64,
173    /// The highest `MasterClock.sequence` handled.
174    handled: u64,
175    /// The most messages kept waiting to be heard of (`SENT_KEPT` by default).
176    kept: usize,
177}
178
179impl Default for Outbox {
180    fn default() -> Self {
181        Self {
182            sent: VecDeque::new(),
183            next: 0,
184            handled: 0,
185            kept: SENT_KEPT,
186        }
187    }
188}
189
190impl Outbox {
191    /// A message leaves after `at`: its number.
192    pub fn sent(&mut self, at: Local) -> u64 {
193        let sequence = self.next;
194        self.next += 1;
195        if self.sent.len() >= self.kept {
196            self.sent.pop_front();
197        }
198        self.sent.push_back((sequence, at));
199        sequence
200    }
201
202    /// The stamp of a message leaving after `at`: its number, and what was handled of the
203    /// master's messages before it.
204    pub fn stamp(&mut self, at: Local) -> pb::WorkerClock {
205        pb::WorkerClock {
206            sequence: self.sent(at),
207            heard_sequence: self.handled,
208        }
209    }
210
211    /// The master's message numbered `sequence` was handled: everything sent while handling it
212    /// is queued already.
213    pub fn handled(&mut self, sequence: u64) {
214        self.handled = self.handled.max(sequence);
215    }
216}
217
218/// A session's [`Outbox`], shared.
219pub type SharedOutbox = Arc<Mutex<Outbox>>;
220
221/// The outbox, locked (a panic while it was held left nothing half-done that matters).
222pub fn lock(outbox: &SharedOutbox) -> MutexGuard<'_, Outbox> {
223    outbox.lock().unwrap_or_else(PoisonError::into_inner)
224}
225
226/// Master time as this worker knows it, for one session.
227#[derive(Debug)]
228pub struct MasterTime {
229    /// What the session sent, shared with its sender.
230    outbox: SharedOutbox,
231    /// Samples of the master's current timeline over the window, each looser than the one
232    /// before it and later: the first is the tightest (a monotonic queue).
233    samples: VecDeque<Sample>,
234    /// The sample that places master time now most closely (M5.1m): the narrowest round trip,
235    /// its error growing with the drift allowance as it ages.
236    narrowest: Option<Sample>,
237    /// How far back the tightest sample is looked for.
238    window: Duration,
239    /// The latest master message's stamp.
240    last: Option<LastStamp>,
241    /// When this session sent the latest heartbeat a stamp said the master had heard (B233):
242    /// the master counts a worker lost from the last message it heard, received no earlier.
243    heard_sent: Option<Local>,
244}
245
246impl Clone for MasterTime {
247    /// A copy that goes its own way: its outbox copied, not shared.
248    fn clone(&self) -> Self {
249        Self {
250            outbox: Arc::new(Mutex::new(lock(&self.outbox).clone())),
251            samples: self.samples.clone(),
252            narrowest: self.narrowest,
253            window: self.window,
254            last: self.last,
255            heard_sent: self.heard_sent,
256        }
257    }
258}
259
260impl Default for MasterTime {
261    fn default() -> Self {
262        Self::with_window(DEFAULT_SAMPLE_WINDOW)
263    }
264}
265
266impl MasterTime {
267    /// This, keeping at most `most` messages waiting to be heard of
268    /// (`SCHEDR_HIDDEN__WORKER__UNACKED_MESSAGES_KEPT`).
269    #[must_use]
270    pub fn keeping(self, most: usize) -> Self {
271        self.outbox
272            .lock()
273            .unwrap_or_else(std::sync::PoisonError::into_inner)
274            .kept = most.max(1);
275        self
276    }
277
278    /// Nothing known yet; the tightest sample looked for over `window`.
279    #[must_use]
280    pub fn with_window(window: Duration) -> Self {
281        Self {
282            outbox: SharedOutbox::default(),
283            samples: VecDeque::new(),
284            narrowest: None,
285            window,
286            last: None,
287            heard_sent: None,
288        }
289    }
290
291    /// A session opens: a new outbox, its first message (the `Register`) numbered 0 as the
292    /// session's sender queues it. Returns now on the agent's own timer clock, the session's
293    /// opening.
294    pub fn open(&mut self) -> tokio::time::Instant {
295        let opened = tokio::time::Instant::now();
296        *self = Self::with_window(self.window);
297        opened
298    }
299
300    /// The session's outbox, for its sender.
301    #[must_use]
302    pub fn outbox(&self) -> SharedOutbox {
303        Arc::clone(&self.outbox)
304    }
305
306    /// The tightest sample of the window.
307    fn best(&self) -> Option<Sample> {
308        self.samples.front().copied()
309    }
310
311    /// The latest master message's stamp.
312    #[must_use]
313    pub const fn last(&self) -> Option<LastStamp> {
314        self.last
315    }
316
317    /// Master time at `now` as the narrowest sample says (M5.1m): its stamp was made after the
318    /// worker sent what it heard and before it arrived, so master time now is within
319    /// `master_ms + (now - arrived)` and `master_ms + (now - sent)`; the middle, with its
320    /// timeline. `None` without a sample, or after a pause the boot clock didn't count.
321    /// (Not the tightest lower bound's sample: a reply stamped at once and delivered late is
322    /// that, and its middle lies half the late return behind; Grok's review of M5.1m.)
323    #[must_use]
324    pub fn estimate(&self, now: Local) -> Option<(u64, i64)> {
325        let best = self.narrowest?;
326        if paused(best.sent, now) {
327            return None;
328        }
329        let middle = best.sent.boot + best.arrived.boot.saturating_sub(best.sent.boot) / 2;
330        let since = i64::try_from(now.boot.saturating_sub(middle).as_millis()).ok()?;
331        Some((best.timeline, best.master_ms.checked_add(since)?))
332    }
333
334    /// The best sample's age and round trip at `now`; `None` without one.
335    #[must_use]
336    pub fn reading(&self, now: Local) -> Option<SampleReading> {
337        let best = self.best()?;
338        Some(SampleReading {
339            age: now.boot.saturating_sub(best.sent.boot),
340            round_trip: best.arrived.boot.saturating_sub(best.sent.boot),
341        })
342    }
343
344    /// A message leaves after `at`: its number (as [`Outbox::sent`]).
345    pub fn sent(&mut self, at: Local) -> u64 {
346        lock(&self.outbox).sent(at)
347    }
348
349    /// A master message's clock, arrived at `now`: a sample if it names what this session
350    /// sent. For a sample, how far the master's wall clock on it lies outside this worker's
351    /// over the round trip, the heartbeat's send to now (decision 449: for a warning only).
352    pub fn heard(&mut self, clock: &pb::MasterClock, now: Local) -> Option<Duration> {
353        self.last = Some(LastStamp {
354            master_ms: clock.master_ms,
355            wall_ms: clock.wall_ms,
356            arrived: now,
357        });
358        if self
359            .best()
360            .is_some_and(|best| best.timeline != clock.timeline)
361        {
362            self.samples.clear();
363            self.narrowest = None;
364        }
365        // Those before it won't be named again: the master's messages come in order.
366        let (number, sent) = {
367            let mut outbox = lock(&self.outbox);
368            while outbox
369                .sent
370                .front()
371                .is_some_and(|(number, _)| *number < clock.heard_sequence)
372            {
373                outbox.sent.pop_front();
374            }
375            *outbox.sent.front()?
376        };
377        if number != clock.heard_sequence {
378            return None;
379        }
380        self.heard_sent = Some(sent);
381        let sample = Sample {
382            timeline: clock.timeline,
383            sent,
384            master_ms: clock.master_ms,
385            arrived: now,
386        };
387        // A pause since the samples (the wall clock ran ahead of the boot clock) leaves them
388        // unusable: the new one replaces them, tighter or not.
389        if self.best().is_some_and(|best| paused(best.sent, sent)) {
390            self.samples.clear();
391        }
392        if self
393            .narrowest
394            .is_none_or(|old| paused(old.sent, sent) || sample.places_as_closely_as(&old))
395        {
396            self.narrowest = Some(sample);
397        }
398        // Those it is at least as tight as are never the tightest again; those older than the
399        // window are past it (the newest always stays).
400        while self
401            .samples
402            .back()
403            .is_some_and(|last| sample.at_least_as_tight_as(last))
404        {
405            self.samples.pop_back();
406        }
407        self.samples.push_back(sample);
408        while self
409            .samples
410            .front()
411            .is_some_and(|first| sent.boot.saturating_sub(first.sent.boot) > self.window)
412        {
413            self.samples.pop_front();
414        }
415        Some(wall_skew(clock.wall_ms, sent.wall, now.wall))
416    }
417
418    /// How long from `now` until the master may count this worker lost: the earlier of master
419    /// time passing the latest stamp's plus `lease` (decision 445) and `lease` after the send
420    /// of the latest heartbeat a stamp said the master had heard, on this clock less the drift
421    /// allowance (B233: the master counts its lease from what it last heard, which a one-way
422    /// cut leaves behind the stamps still arriving). `None` without a stamp and a sample.
423    #[must_use]
424    pub fn cutoff_in(&self, lease: Duration, now: Local) -> Option<Duration> {
425        let last = self.last?;
426        self.best()?;
427        let lease_ms = i64::try_from(lease.as_millis()).unwrap_or(i64::MAX);
428        let by_stamp = self.until(last.master_ms.saturating_add(lease_ms), now);
429        let by_heard = self.heard_sent.map(|sent| {
430            if paused(sent, now) {
431                return Duration::ZERO;
432            }
433            let at = sent.boot + lease.saturating_sub(lease / 1000 * DRIFT_PER_MILLE);
434            at.saturating_sub(now.boot)
435        });
436        Some(by_heard.map_or(by_stamp, |heard| heard.min(by_stamp)))
437    }
438
439    /// How long from `now` until master time `by_ms` may be reached, by the same bound as
440    /// [`Self::past`]: zero when it may be already (no sample, a pause, the bound past).
441    #[must_use]
442    pub fn until(&self, by_ms: i64, now: Local) -> Duration {
443        self.reached_at(by_ms, now)
444            .map_or(Duration::ZERO, |at| at.saturating_sub(now.boot))
445    }
446
447    /// On the boot clock, the earliest master time `by_ms` may be reached; `None` when it may
448    /// be already at `now`.
449    fn reached_at(&self, by_ms: i64, now: Local) -> Option<Duration> {
450        let best = self.best()?;
451        if paused(best.sent, now) {
452            return None;
453        }
454        // The stamp is master time rounded down to the millisecond: up to 1 ms later in fact.
455        let ahead = Duration::from_millis(u64::try_from(by_ms - best.master_ms - 1).ok()?);
456        Some(best.sent.boot + ahead.saturating_sub(ahead / 1000 * DRIFT_PER_MILLE))
457    }
458
459    /// Whether master time `by_ms` may have been reached at `now`, `reserve` before it: no
460    /// sample, a pause the boot clock didn't count, or the bound past.
461    #[must_use]
462    pub fn past(&self, by_ms: i64, reserve: Duration, now: Local) -> bool {
463        self.slack(by_ms, reserve, now).is_none()
464    }
465
466    /// How long before master time `by_ms`, `reserve` kept, there is still at `now`: `None` once
467    /// [`Self::past`] (for the metrics too, decision 448).
468    #[must_use]
469    pub fn slack(&self, by_ms: i64, reserve: Duration, now: Local) -> Option<Duration> {
470        let at = self.reached_at(by_ms, now)?.saturating_sub(reserve);
471        at.checked_sub(now.boot).filter(|left| !left.is_zero())
472    }
473}
474
475#[cfg(test)]
476mod tests {
477    use super::*;
478
479    fn at(boot_ms: u64) -> Local {
480        Local {
481            boot: Duration::from_millis(boot_ms),
482            wall: SystemTime::UNIX_EPOCH + Duration::from_millis(boot_ms),
483        }
484    }
485
486    fn clock(timeline: u64, master_ms: i64, heard: u64) -> pb::MasterClock {
487        pb::MasterClock {
488            timeline,
489            master_ms,
490            heard_sequence: heard,
491            wall_ms: 0,
492            lease_epoch: 0,
493            sequence: 0,
494        }
495    }
496
497    fn opened(register_at: u64) -> MasterTime {
498        let mut time = MasterTime::default();
499        assert_eq!(time.sent(at(register_at)), 0, "the Register");
500        time
501    }
502
503    #[test]
504    fn a_deadline_counts_from_the_send_of_what_the_master_had_heard() {
505        // Register sent at 1000 ms; the master stamped 50 000 on its answer.
506        let mut time = opened(1000);
507        assert!(time.past(60_000, Duration::ZERO, at(1001)), "no sample yet");
508        time.heard(&clock(7, 50_000, 0), at(0));
509        // Master time 60 000 is no earlier than 1000 + 10 000, less 0.1 %: 10 990.
510        assert!(!time.past(60_000, Duration::ZERO, at(10_989)));
511        assert!(time.past(60_000, Duration::ZERO, at(10_990)));
512        // Two seconds kept for `Started`.
513        assert!(time.past(60_000, Duration::from_secs(2), at(8_990)));
514        // A deadline already behind the sample: passed.
515        assert!(time.past(49_000, Duration::ZERO, at(1001)));
516    }
517
518    #[test]
519    fn master_time_now_is_estimated_from_the_middle_of_the_best_samples_round_trip() {
520        // M5.1m: the Register sent at 1000 ms, the master's 50 000 arrived at 1200: its stamp
521        // was made between them, so 2000 ms after their middle it is about 52 000.
522        let mut time = opened(1000);
523        assert_eq!(time.estimate(at(1001)), None, "no sample yet");
524        time.heard(&clock(7, 50_000, 0), at(1200));
525        assert_eq!(time.estimate(at(3100)), Some((7, 52_000)));
526        // A pause the boot clock didn't count (the wall clock ran far ahead): no estimate.
527        let paused = Local {
528            boot: Duration::from_millis(3100),
529            wall: SystemTime::UNIX_EPOCH + Duration::from_secs(3600),
530        };
531        assert_eq!(time.estimate(paused), None);
532    }
533
534    #[test]
535    fn the_estimate_takes_the_narrowest_round_trip_not_the_tightest_lower_bound() {
536        // Grok's review of M5.1m: the Register stamped at once (master 100) and delivered
537        // late (boot 10 000) stays the tightest lower bound; a heartbeat sent at 11 000,
538        // stamped 11 200 and back at 11 100 places master time far better.
539        let mut time = opened(0);
540        time.heard(&clock(7, 100, 0), at(10_000));
541        assert_eq!(time.estimate(at(10_000)), Some((7, 5100)));
542        assert_eq!(time.sent(at(11_000)), 1);
543        time.heard(&clock(7, 11_200, 1), at(11_100));
544        assert_eq!(time.estimate(at(20_000)), Some((7, 20_150)));
545        // A wider one later doesn't replace it; the deadlines still use the lower bound.
546        assert_eq!(time.sent(at(12_000)), 2);
547        time.heard(&clock(7, 12_400, 2), at(12_600));
548        assert_eq!(time.estimate(at(20_000)), Some((7, 20_150)));
549        assert_eq!(time.best().map(|b| b.master_ms), Some(100));
550    }
551
552    #[test]
553    fn the_tightest_sample_counts_and_one_naming_nothing_sent_changes_nothing() {
554        let mut time = opened(0);
555        let one = time.sent(at(1000));
556        let two = time.sent(at(2000));
557        assert_eq!((one, two), (1, 2));
558        // Heard 1 at master 10 000: lead 1000 - 10 000 = -9000 ms.
559        time.heard(&clock(7, 10_000, 1), at(0));
560        // Heard 2 at master 12 500 (a slow answer): lead -10 500, looser: kept the first.
561        time.heard(&clock(7, 12_500, 2), at(0));
562        assert!(!time.past(20_000, Duration::ZERO, at(10_989)));
563        assert!(time.past(20_000, Duration::ZERO, at(10_990)));
564        // A number never sent, or one heard already: nothing.
565        time.heard(&clock(7, 1, 9), at(0));
566        time.heard(&clock(7, 1, 1), at(0));
567        assert!(!time.past(20_000, Duration::ZERO, at(10_989)));
568    }
569
570    #[test]
571    fn another_timeline_drops_what_was_known() {
572        let mut time = opened(0);
573        time.heard(&clock(7, 10_000, 0), at(0));
574        let beat = time.sent(at(1000));
575        // A new master: its first answer names a heartbeat of this stream.
576        time.heard(&clock(8, 3_000, beat), at(0));
577        // From the new sample only: 1000 + (5000 - 3000), less 0.1 %.
578        assert!(!time.past(5_000, Duration::ZERO, at(2_997)));
579        assert!(time.past(5_000, Duration::ZERO, at(2_998)));
580    }
581
582    #[test]
583    fn a_pause_the_boot_clock_didnt_count_makes_every_deadline_passed() {
584        let mut time = opened(1000);
585        time.heard(&clock(7, 0, 0), at(0));
586        // 2 s on the boot clock, 10 s on the wall clock: frozen meanwhile.
587        let paused = Local {
588            boot: Duration::from_millis(3000),
589            wall: SystemTime::UNIX_EPOCH + Duration::from_secs(11),
590        };
591        assert!(time.past(60_000, Duration::ZERO, paused));
592        // The same within the slack: running.
593        let running = Local {
594            boot: Duration::from_millis(3000),
595            wall: SystemTime::UNIX_EPOCH + Duration::from_millis(3_900),
596        };
597        assert!(!time.past(60_000, Duration::ZERO, running));
598    }
599
600    #[test]
601    fn after_a_pause_the_next_sample_replaces_the_old_one() {
602        let mut time = opened(1000);
603        time.heard(&clock(7, 0, 0), at(0));
604        // Frozen: 2 s on the boot clock, 10 s on the wall clock; then a heartbeat, answered.
605        let after = Local {
606            boot: Duration::from_millis(3000),
607            wall: SystemTime::UNIX_EPOCH + Duration::from_secs(11),
608        };
609        let beat = time.sent(after);
610        // Master time moved 10 s meanwhile: a looser sample than the first, yet it counts.
611        time.heard(&clock(7, 10_000, beat), at(0));
612        let later = Local {
613            boot: Duration::from_millis(3500),
614            wall: SystemTime::UNIX_EPOCH + Duration::from_millis(11_500),
615        };
616        // Due at master time 12 000: no earlier than 3000 + 2000, less 0.1 %.
617        assert!(!time.past(12_000, Duration::ZERO, later));
618        assert!(time.past(
619            12_000,
620            Duration::ZERO,
621            Local {
622                boot: Duration::from_millis(4998),
623                wall: SystemTime::UNIX_EPOCH + Duration::from_millis(12_998),
624            }
625        ));
626    }
627
628    #[test]
629    fn an_equally_tight_later_sample_replaces_an_hours_old_one() {
630        // Grok's review: kept for 40 000 s, the old sample's drift allowance (0.1 % of the
631        // span) ate a whole lease.
632        let mut time = opened(0);
633        time.heard(&clock(7, 0, 0), at(0));
634        let hours = 40_000_000;
635        let deadline = hours + 60_000;
636        let now = at(u64::try_from(hours).unwrap());
637        assert!(
638            time.past(deadline, Duration::from_secs(20), now),
639            "the old one alone"
640        );
641        let beat = time.sent(now);
642        time.heard(&clock(7, hours, beat), at(0));
643        assert!(!time.past(deadline, Duration::from_secs(20), now));
644        // A looser later one doesn't replace it: 1 s slower than the clocks' rates allow.
645        let mut time = opened(0);
646        time.heard(&clock(7, 0, 0), at(0));
647        let beat = time.sent(at(10_000));
648        time.heard(&clock(7, 11_000, beat), at(0));
649        assert!(!time.past(20_000, Duration::ZERO, at(19_979)));
650        assert!(time.past(20_000, Duration::ZERO, at(19_980)));
651    }
652
653    #[test]
654    fn the_boot_clock_reads() {
655        let first = boot_now();
656        assert!(boot_now() >= first);
657    }
658}
659
660#[cfg(test)]
661mod window_tests {
662    use super::*;
663
664    fn at(boot_ms: u64) -> Local {
665        Local {
666            boot: Duration::from_millis(boot_ms),
667            wall: SystemTime::UNIX_EPOCH + Duration::from_millis(boot_ms),
668        }
669    }
670
671    fn clock(master_ms: i64, heard: u64) -> pb::MasterClock {
672        pb::MasterClock {
673            timeline: 7,
674            master_ms,
675            heard_sequence: heard,
676            wall_ms: master_ms,
677            lease_epoch: 0,
678            sequence: 0,
679        }
680    }
681
682    #[test]
683    fn the_tightest_sample_is_taken_over_the_window() {
684        // Decision 447: a 10 s window. The first sample is tight (lead -10 000), the next
685        // looser (a slow answer); once the first is older than the window, the looser counts.
686        let mut time = MasterTime::with_window(Duration::from_secs(10));
687        time.open();
688        let one = time.sent(at(1_000));
689        time.heard(&clock(11_000, one), at(1_010));
690        let two = time.sent(at(5_000));
691        time.heard(&clock(16_000, two), at(5_600));
692        // Master time 30 000 by the first: 1000 + 19 000, less the stamp's rounding (1 ms) and
693        // 0.1 %: 19 980.001.
694        assert_eq!(
695            time.until(30_000, at(9_000)),
696            Duration::from_micros(10_980_001)
697        );
698        let reading = time.reading(at(9_000)).unwrap();
699        assert_eq!(
700            (reading.age, reading.round_trip),
701            (Duration::from_secs(8), Duration::from_millis(10))
702        );
703        // 12 s on: the first is out of the window; the second (5000 + 14 000, less 0.1 %)
704        // counts, the third being looser still.
705        let three = time.sent(at(12_000));
706        time.heard(&clock(24_000, three), at(12_900));
707        assert_eq!(
708            time.until(30_000, at(9_000)),
709            Duration::from_micros(9_985_001)
710        );
711        assert!(time.slack(30_000, Duration::ZERO, at(18_986)).is_none());
712        assert!(time.slack(30_000, Duration::ZERO, at(18_985)).is_some());
713        assert_eq!(time.last().unwrap().wall_ms, 24_000);
714    }
715
716    #[test]
717    fn the_cutoff_counts_from_the_last_stamp_on_master_time() {
718        // Decision 445: Register sent at 1000, answered at master 50 000; a later message stamped
719        // 55 000 arrives at 9000 (held on its way). The lease (10 s) after master time 55 000 may
720        // be reached at 1000 + 15 000, less 1 ms (the stamp's rounding) and 0.1 %: 15 984.001,
721        // sooner than 9000 + 10 000 by receipt. With only the Register heard, B233's bound (lease
722        // after its send, less 0.1 %: 10 990) is sooner still.
723        let mut time = MasterTime::with_window(Duration::from_secs(600));
724        assert_eq!(
725            time.cutoff_in(Duration::from_secs(10), at(0)),
726            None,
727            "nothing heard"
728        );
729        time.sent(at(1_000));
730        time.heard(&clock(50_000, 0), at(1_100));
731        let mut pushed = time.clone();
732        pushed.heard(&clock(55_000, 0), at(9_000));
733        assert_eq!(
734            pushed.cutoff_in(Duration::from_secs(10), at(9_000)),
735            Some(Duration::from_millis(1_990))
736        );
737        // A heartbeat sent at 8000 heard: the stamp's bound (master time read by that sample,
738        // 17 989.001) is 1 ms sooner than B233's (17 990), for the stamp's rounding.
739        time.sent(at(8_000));
740        time.heard(&clock(55_000, 1), at(9_000));
741        assert_eq!(
742            time.cutoff_in(Duration::from_secs(10), at(9_000)),
743            Some(Duration::from_micros(8_989_001))
744        );
745        assert_eq!(
746            time.cutoff_in(Duration::from_secs(10), at(17_990)),
747            Some(Duration::ZERO)
748        );
749    }
750
751    #[test]
752    fn the_cutoff_counts_from_the_send_of_what_the_master_last_heard() {
753        // B233: heartbeat 0 sent at 1000, heard and answered at master 50 000; the worker's
754        // messages are lost from then on, but the master's still arrive, the last stamped at
755        // master 80 000 at 31 000. The master counts its lease from what it last heard: it may
756        // lose the worker a lease after 1000, so the worker stops by 1000 + 60 000, less 0.1 %
757        // (60 940), not by the last stamp's 80 000 + 60 000 (about 59.9 s on).
758        let mut time = MasterTime::with_window(Duration::from_secs(600));
759        time.sent(at(1_000));
760        time.heard(&clock(50_000, 0), at(1_100));
761        time.sent(at(11_000));
762        time.heard(&clock(80_000, 0), at(31_000));
763        assert_eq!(
764            time.cutoff_in(Duration::from_secs(60), at(31_000)),
765            Some(Duration::from_millis(29_940))
766        );
767    }
768
769    #[test]
770    fn the_masters_wall_clock_is_compared_over_the_round_trip() {
771        // Decision 449: sent at wall 1 s, answered at 1.5 s; the master's wall clock on it
772        // anywhere between is no skew, 3.5 s is 2 s ahead, 0.2 s is 0.8 s behind.
773        let skew = |wall_ms| {
774            let mut time = MasterTime::default();
775            time.sent(at(1_000));
776            time.heard(
777                &pb::MasterClock {
778                    wall_ms,
779                    ..clock(5_000, 0)
780                },
781                at(1_500),
782            )
783        };
784        assert_eq!(skew(1_200), Some(Duration::ZERO));
785        assert_eq!(skew(3_500), Some(Duration::from_secs(2)));
786        assert_eq!(skew(200), Some(Duration::from_millis(800)));
787        let mut time = MasterTime::default();
788        assert_eq!(
789            time.heard(&clock(5_000, 3), at(1_500)),
790            None,
791            "not a sample"
792        );
793    }
794
795    #[test]
796    fn messages_never_answered_dont_hold_back_the_count() {
797        // B225 (Grok's review), every message numbered since B240: messages 0 to 4 unanswered
798        // (a paused master), then one naming 5 is the sample: sent at 6000, not at 1000.
799        let mut time = MasterTime::with_window(Duration::from_secs(600));
800        for n in 0..6 {
801            assert_eq!(time.sent(at(1_000 + n * 1_000)), n);
802        }
803        time.heard(&clock(50_000, 5), at(6_100));
804        assert_eq!(
805            time.reading(at(6_100)).map(|r| r.round_trip),
806            Some(Duration::from_millis(100))
807        );
808    }
809
810    #[test]
811    fn the_outbox_numbers_each_message_and_echoes_what_was_handled() {
812        // B240: the Register is 0; each message after it the next number, naming the master's
813        // latest message handled before it was queued.
814        let mut outbox = Outbox::default();
815        let register = outbox.stamp(at(1_000));
816        assert_eq!((register.sequence, register.heard_sequence), (0, 0));
817        outbox.handled(1);
818        let started = outbox.stamp(at(1_010));
819        outbox.handled(4);
820        outbox.handled(3);
821        let beat = outbox.stamp(at(1_020));
822        assert_eq!(
823            [
824                (started.sequence, started.heard_sequence),
825                (beat.sequence, beat.heard_sequence)
826            ],
827            [(1, 1), (2, 4)],
828            "the highest handled, never lower"
829        );
830    }
831
832    #[test]
833    fn a_copy_of_master_time_goes_its_own_way() {
834        // Its outbox copied, not shared: what the copy sends isn't the original's.
835        let mut time = MasterTime::default();
836        time.sent(at(1_000));
837        let mut copy = time.clone();
838        assert_eq!(copy.sent(at(2_000)), 1);
839        assert_eq!(time.sent(at(3_000)), 1);
840    }
841
842    #[test]
843    fn a_tighter_sample_drops_the_looser_ones_before_it() {
844        let mut time = MasterTime::with_window(Duration::from_secs(600));
845        time.open();
846        let one = time.sent(at(1_000));
847        time.heard(&clock(12_000, one), at(1_500));
848        let two = time.sent(at(2_000));
849        time.heard(&clock(12_000, two), at(2_001));
850        // The second (lead -10 000) is tighter than the first (-11 000): it alone remains.
851        assert_eq!(time.samples.len(), 1);
852        assert_eq!(
853            time.until(13_000, at(2_000)),
854            Duration::from_micros(998_001)
855        );
856    }
857}