rusty_time_core/discipline.rs
1//! The clock-discipline loop: turn estimates into clock commands.
2//!
3//! The platform driver (or the simulator) executes [`ClockCommand`]s; this module
4//! only decides. Frequency corrections come straight from the regression slope —
5//! the estimator measures frequency directly, so no PLL time constant is needed
6//! (this is the chrony approach, and the reason for its fast convergence).
7
8/// Configuration mirroring the chrony.conf directives we honor.
9#[derive(Clone, Copy, Debug, PartialEq)]
10pub struct DisciplineConfig {
11 /// Step (rather than slew) when |offset| exceeds this, during the first
12 /// `makestep_limit` updates. `None` = never step.
13 pub makestep_threshold: Option<f64>,
14 pub makestep_limit: u32,
15 /// Cap on offset-correction slew rate, ppm.
16 pub max_slew_ppm: f64,
17 /// Cap on the absolute frequency correction we will command, ppm.
18 pub max_freq_ppm: f64,
19 /// log2 seconds.
20 pub min_poll: i8,
21 pub max_poll: i8,
22 /// Send an initial burst of quick polls to converge fast (chrony `iburst`).
23 pub iburst: bool,
24 /// Gain of the integral trim on the frequency estimate. 0 disables it,
25 /// leaving a purely proportional loop. See `FREQ_INTEGRAL_GAIN`.
26 pub freq_integral_gain: f64,
27 /// Step the poll interval back DOWN when `|offset| > this * noise`.
28 ///
29 /// This is the packet budget, and the packet budget is most of the
30 /// accuracy: offset error falls as 1/sqrt(N). Measured on the seeded rig,
31 /// clknetsim's own packet counters, same poll bounds for both arms:
32 ///
33 /// ```text
34 /// mean poll median |e| S1 per packet spent
35 /// chrony 33.9 s 1.52 us (baseline)
36 /// rusty_time 40.1 s 1.47 us x1.05
37 /// ```
38 ///
39 /// So the estimator was never the deficit — at equal cost it is at parity
40 /// on S1 and slightly ahead on S8 (x0.96). We were simply buying fewer
41 /// samples. See `POLL_DOWN_NOISE_RATIO`.
42 pub poll_down_noise_ratio: f64,
43 /// Consecutive stable samples required before the poll interval doubles.
44 ///
45 /// This, not the dead band, is what sets the packet budget. Sweeping
46 /// `poll_down_noise_ratio` from 10 down to 3 moved the mean poll by 0.3 s
47 /// and the accuracy not at all, because the step-DOWN branch only runs
48 /// when `|offset| >= 2 * noise` and a converged loop is almost never
49 /// there. It is always "stable", so it always climbs, and it pins at
50 /// maxpoll. The climb rate is the only term with any authority.
51 pub poll_up_streak: u32,
52 /// Width of the regression's weight floor, as a fraction of the minimum
53 /// observed delay. See `rusty_time_core::filter::WEIGHT_FLOOR_RATIO`.
54 ///
55 /// This is the one knob that can improve accuracy WITHOUT spending more
56 /// packets, which is why it is worth a sweep: buying accuracy with poll
57 /// rate leaves per-packet efficiency exactly where it was.
58 pub weight_floor_ratio: f64,
59 /// Weight-floor width for the OFFSET alone; the slope keeps
60 /// `weight_floor_ratio`. Equal values reproduce the single-weight fit.
61 pub offset_weight_floor_ratio: f64,
62}
63
64impl Default for DisciplineConfig {
65 fn default() -> Self {
66 DisciplineConfig {
67 makestep_threshold: Some(1.0),
68 makestep_limit: 3,
69 max_slew_ppm: 83_333.0,
70 max_freq_ppm: 500.0,
71 min_poll: 6,
72 max_poll: 10,
73 iburst: true,
74 freq_integral_gain: FREQ_INTEGRAL_GAIN,
75 poll_down_noise_ratio: POLL_DOWN_NOISE_RATIO,
76 poll_up_streak: POLL_UP_STREAK,
77 weight_floor_ratio: crate::filter::WEIGHT_FLOOR_RATIO,
78 offset_weight_floor_ratio: crate::filter::OFFSET_WEIGHT_FLOOR_RATIO,
79 }
80 }
81}
82
83/// What the platform driver should do right now.
84#[derive(Clone, Copy, Debug, PartialEq)]
85pub enum ClockCommand {
86 /// Add this many seconds to the clock immediately.
87 Step { add_seconds: f64 },
88 /// Run at `freq_ppm` (absolute correction vs the undisciplined clock) and
89 /// additionally drain `drain_offset` seconds at up to `drain_rate_ppm`.
90 Slew {
91 freq_ppm: f64,
92 drain_offset: f64,
93 drain_rate_ppm: f64,
94 },
95}
96
97#[derive(Clone, Copy, Debug, PartialEq)]
98pub struct Plan {
99 pub command: ClockCommand,
100 /// Seconds until the next poll.
101 pub next_poll_s: f64,
102 /// The sample register is invalid after a step; caller must shift or clear it.
103 pub reset_register: bool,
104}
105
106/// Number of quick polls in an iburst, and their spacing.
107const IBURST_COUNT: u32 = 4;
108const IBURST_SPACING_S: f64 = 2.0;
109/// Drain a measured offset over roughly this many poll intervals.
110const CORR_TIME_RATIO: f64 = 3.0;
111/// Correction time, in poll intervals, for an offset that is plainly real.
112/// One means "finish before the next sample arrives".
113const ACQUIRE_CORR_RATIO: f64 = 1.0;
114/// How far outside the noise an offset must sit to be treated as real.
115const ACQUIRE_NOISE_MULTIPLE: f64 = 10.0;
116/// How many updates count as acquisition.
117///
118/// Acquisition is a *phase*, not a magnitude. Gating the fast correction on
119/// "the offset is much larger than the noise" looked equivalent and is not:
120/// a loop that is confidently wrong reports a small `offset_sd` beside a large
121/// error, so the test fires in steady state exactly when it should not. The
122/// in-house S6 scenario is such a case — a deliberately noisy path where the
123/// estimator's own confidence outruns its accuracy — and gating on magnitude
124/// alone took its steady error from 2.54 ms to 10.83 ms while the low-noise
125/// clknetsim rig showed only the improvement. Counting updates cannot be
126/// fooled that way: after this many the loop is no longer starting up,
127/// whatever it believes about itself.
128const ACQUIRE_UPDATES: u32 = 8;
129/// The most of the slew budget the fast correction may ask for.
130///
131/// Leaving headroom is the point. A correction that consumes the whole budget
132/// pins the clock at maximum rate for the entire interval, and the frequency
133/// estimator then has to infer a drift from samples taken while the clock was
134/// being hauled — which it does badly enough to leave a permanently worse
135/// steady state. A quarter keeps the fast path for offsets it can absorb and
136/// hands genuinely large cold starts back to the gentle drain.
137const ACQUIRE_SLEW_SHARE: f64 = 0.25;
138/// How many times the noise an offset must exceed before the clock may be
139/// hauled at the full slew ceiling.
140const ACQUIRE_FULL_SPEED_CONFIDENCE: f64 = 10_000.0;
141/// Above this share of the slew ceiling, the clock is being *hauled*, and a
142/// frequency measured across that haul is not a measurement of the
143/// oscillator.
144///
145/// The regression fits a slope through stored samples, and `slew_samples`
146/// re-expresses that history for corrections already applied. That accounting
147/// is exact for a gentle drain. It is not robust to a correction running at
148/// most of the slew ceiling: any small mismatch between the rate commanded and
149/// the rate delivered is multiplied by the poll interval and lands in the
150/// slope, and the loop then carries a frequency error it never measured. The
151/// offset drain has feedback and recovers; the frequency term accumulates and
152/// does not.
153///
154/// So during a haul the offset is still corrected at full speed — the clock is
155/// visibly wrong and the fix is not in doubt — but the frequency estimate is
156/// left alone until the samples describe a clock that is merely running.
157const FREQ_TRUST_SLEW_SHARE: f64 = 0.25;
158/// Most polls the acquisition burst may take before it must slow down.
159///
160/// The burst normally ends after `IBURST_COUNT` samples, and the poll then
161/// jumps straight to `min_poll`. That is the whole S6 gap: the offset drain is
162/// sized to finish within one poll interval, so ending the burst with a large
163/// correction still outstanding hands the remainder a 16 s deadline instead of
164/// a 2 s one. Measured against chrony, chrony had a 500 ms cold start gone in
165/// about 7 s at close to its slew ceiling, while this loop cleared 500 ms down
166/// to 89 ms in the burst and then spent a further 16 s on what was left.
167///
168/// So the burst ends when the offset is small, not when a counter runs out.
169/// The cap is what stops that becoming an unbounded fast poll against someone
170/// else's server: a client that cannot converge is a client that must back off
171/// anyway, not one that should keep asking every two seconds.
172const MAX_ACQUIRE_BURST: u32 = 16;
173/// How much of an implied frequency error to absorb per update.
174///
175/// **Why there is an integral term at all.** The offset drain is proportional:
176/// each plan removes `offset / (CORR_TIME_RATIO * poll)` per second. Against a
177/// constant unmodelled drift `F`, that settles at an equilibrium rather than at
178/// zero -- removal balances accumulation when
179///
180/// ```text
181/// offset = CORR_TIME_RATIO * poll * F
182/// ```
183///
184/// which is a *standing error the loop maintains on purpose*. Measured on the
185/// in-house corpus it is the whole story: S1 sat at 200 us on a 0.039 ppm
186/// residual and a 1024 s poll, and 3 * 1024 * 0.039e-6 is 120 us. A
187/// proportional controller cannot remove it; only integral action can.
188///
189/// The frequency term comes from the regression slope, which is a
190/// *measurement*. If that measurement carries any bias, the equilibrium above
191/// stands forever and no amount of averaging removes it. So the loop reads the
192/// standing offset as evidence in its own right: invert the relation, and a
193/// persistent offset **is** a frequency error, expressed in seconds.
194///
195/// **Measured and rejected. The default is 0 — the trim is OFF.**
196///
197/// The reasoning above is sound and the result still went the other way. On a
198/// SEEDED rig, twenty worlds per arm, paired seed by seed:
199///
200/// ```text
201/// S8 gain=0.0 median |e| 4.78 us 8/20 wins vs chrony z=-0.89 not resolved
202/// S8 gain=0.1 median |e| 6.20 us 5/20 wins vs chrony z=-2.24 RESOLVED, chrony ahead
203/// S1 gain=0.0 median |e| 1.47 us
204/// S1 gain=0.1 median |e| 1.98 us
205/// ```
206///
207/// Turning the trim on is the only *resolved* accuracy result in that sweep,
208/// and it is a regression. An earlier single unpaired run had read it as an
209/// improvement on both scenarios; it was the draw, not the code.
210///
211/// Why it fails, as best the data supports: the standing offset is not a
212/// frequency error here. It is sampling error in the delay draws — it changes
213/// SIGN with the seed. Integrating it feeds noise into the frequency estimate,
214/// and on S8, whose oscillator already wanders, that is the last thing the
215/// loop needs.
216///
217/// Kept as a field rather than deleted so re-testing costs one flag if the
218/// estimator's own bias ever shrinks below this effect.
219const FREQ_INTEGRAL_GAIN: f64 = 0.0;
220
221/// How far outside the noise an offset must sit before the poll interval is
222/// stepped back down — the default for `DisciplineConfig::poll_down_noise_ratio`.
223///
224/// An offset below `2 * noise` counts as stable and, after three such samples,
225/// doubles the interval. Between that and this ratio the loop does neither, so
226/// this number IS the width of the dead band, and a wide dead band pins the
227/// client at maxpoll: at 10x it effectively never came back down.
228///
229/// The value is measured, not chosen — see the sweep in `DisciplineConfig`.
230const POLL_DOWN_NOISE_RATIO: f64 = 10.0;
231
232/// Consecutive stable samples before the poll interval doubles — the default
233/// for `DisciplineConfig::poll_up_streak`.
234const POLL_UP_STREAK: u32 = 3;
235/// Weight of the newest offset in the persistence average. Low, because the
236/// signal being extracted is the part that does *not* change.
237const OFFSET_EWMA_ALPHA: f64 = 0.25;
238
239/// The offset at which acquisition is finished and the burst may end.
240///
241/// Tied to what "converged" means rather than to a multiple of the noise. The
242/// noise-multiple test was tried first and fails at exactly the wrong moment:
243/// on S6 the burst had hauled 500 ms down to 9.8 ms, `10 x noise` came out at
244/// about 10 ms, the test went false, the poll jumped 2 s -> 16 s, and the last
245/// 9.8 ms was handed a 16 s deadline. Those 16 s were the whole difference
246/// against chrony. Floored at twice the noise so a genuinely noisy path is not
247/// polled fast in pursuit of an offset it cannot resolve.
248const ACQUIRE_DONE_S: f64 = 1e-3;
249
250#[derive(Clone, Debug)]
251pub struct Discipline {
252 cfg: DisciplineConfig,
253 freq_ppm: f64,
254 updates: u32,
255 poll: i8,
256 stable_streak: u32,
257 iburst_left: u32,
258 /// Drain rate the previous plan commanded, as a share of the ceiling.
259 /// Samples taken since then were taken while the clock moved at that rate.
260 last_drain_share: f64,
261 /// Burst polls used, including any the acquisition extension granted.
262 burst_used: u32,
263 /// Slow average of recent offset estimates.
264 ///
265 /// A *persistent* offset is the signature of a frequency error the
266 /// regression has not measured, and it is the thing that decides
267 /// steady-state accuracy. See `integral_trim`.
268 offset_ewma: f64,
269 /// Whether `offset_ewma` has been seeded.
270 ewma_seeded: bool,
271}
272
273impl Discipline {
274 pub fn new(cfg: DisciplineConfig) -> Self {
275 let iburst_left = if cfg.iburst { IBURST_COUNT } else { 0 };
276 Discipline {
277 cfg,
278 freq_ppm: 0.0,
279 updates: 0,
280 poll: cfg.min_poll,
281 stable_streak: 0,
282 iburst_left,
283 last_drain_share: 0.0,
284 burst_used: 0,
285 offset_ewma: 0.0,
286 ewma_seeded: false,
287 }
288 }
289
290 /// How much of the slew budget an acquisition correction may use, given
291 /// how well the offset is known.
292 ///
293 /// How fast the clock may be hauled should depend on how sure we are where
294 /// it is going. A 500 ms offset on a path with microseconds of jitter is
295 /// known to five decimal places and can be cleared at the ceiling; the same
296 /// 500 ms on a path with a millisecond of jitter is a much rougher number,
297 /// and committing to it at full speed writes the roughness into the clock.
298 ///
299 /// Both rigs demanded this. On clknetsim, restricting the share left S6 at
300 /// 18 s against chrony's 12 s; on the in-house corpus, whose S6 models a
301 /// 0.74 ms-jitter path, allowing the full share took its steady error from
302 /// 1.5 ms to 5.9 ms. Neither constant satisfies both, because the two rigs
303 /// differ by two orders of magnitude in exactly the quantity that should
304 /// decide it.
305 fn acquire_share(&self, offset: f64, noise: f64) -> f64 {
306 let confidence = offset.abs() / noise.max(1e-9);
307 if confidence >= ACQUIRE_FULL_SPEED_CONFIDENCE {
308 1.0
309 } else {
310 ACQUIRE_SLEW_SHARE
311 }
312 }
313
314 /// Current commanded frequency correction, ppm.
315 pub fn freq_ppm(&self) -> f64 {
316 self.freq_ppm
317 }
318
319 pub fn poll_log2(&self) -> i8 {
320 self.poll
321 }
322
323 /// Feed the latest combined estimate.
324 ///
325 /// * `offset` — seconds to add to the local clock, now.
326 /// * `freq_ppm_meas` — residual frequency error from the regression (ppm,
327 /// positive = local slow), if trusted.
328 /// * `offset_sd` — residual noise of the estimate.
329 pub fn on_estimate(&mut self, offset: f64, freq_ppm_meas: Option<f64>, offset_sd: f64) -> Plan {
330 self.updates += 1;
331
332 // Step epoch: large offsets early on are stepped away, chrony `makestep`.
333 if let Some(threshold) = self.cfg.makestep_threshold
334 && offset.abs() > threshold
335 && self.updates <= self.cfg.makestep_limit
336 {
337 self.stable_streak = 0;
338 return Plan {
339 command: ClockCommand::Step {
340 add_seconds: offset,
341 },
342 next_poll_s: self.take_poll_interval(),
343 reset_register: true,
344 };
345 }
346
347 // Frequency: the regression slope is a direct measurement of the residual
348 // frequency error of the *disciplined* clock, so accumulate it fully --
349 // unless these samples were taken while the clock was being hauled, in
350 // which case the slope is mostly the haul.
351 let hauling = self.last_drain_share > FREQ_TRUST_SLEW_SHARE;
352 if let Some(fm) = freq_ppm_meas
353 && !hauling
354 {
355 self.freq_ppm =
356 (self.freq_ppm + fm).clamp(-self.cfg.max_freq_ppm, self.cfg.max_freq_ppm);
357 }
358
359 // Poll adaptation first: lengthen when quiet, shorten when the offset is
360 // loud relative to the noise floor. Runs before the drain computation so
361 // the drain rate is sized for the interval the plan will actually use.
362 let noise = offset_sd.max(1e-7);
363
364 // Integral trim: read a standing offset as the frequency error it
365 // implies, and absorb a fraction of it. Only once acquisition is over
366 // -- during acquisition the offset is large for reasons that have
367 // nothing to do with drift, and feeding that in would be nonsense.
368 if self.ewma_seeded {
369 self.offset_ewma =
370 (1.0 - OFFSET_EWMA_ALPHA) * self.offset_ewma + OFFSET_EWMA_ALPHA * offset;
371 } else {
372 self.offset_ewma = offset;
373 self.ewma_seeded = true;
374 }
375 // ...and only when the standing offset is larger than the noise that
376 // could have produced it. Below that line the average is a sample of
377 // jitter, and feeding jitter into the frequency term writes it into the
378 // clock permanently -- the offset drain can recover from a bad estimate,
379 // the frequency term accumulates it. Measured: without this gate S1
380 // went from 199.7 us to 231.5 us while its frequency residual did not
381 // move at all, which is exactly what integrating noise looks like.
382 if self.cfg.freq_integral_gain != 0.0
383 && self.updates > ACQUIRE_UPDATES
384 && self.offset_ewma.abs() > noise
385 {
386 let poll_now = self.peek_poll_interval();
387 let implied_freq_ppm = (self.offset_ewma / (CORR_TIME_RATIO * poll_now)) * 1e6;
388 self.freq_ppm = (self.freq_ppm + self.cfg.freq_integral_gain * implied_freq_ppm)
389 .clamp(-self.cfg.max_freq_ppm, self.cfg.max_freq_ppm);
390 }
391 if offset.abs() < 2.0 * noise {
392 self.stable_streak += 1;
393 if self.stable_streak >= self.cfg.poll_up_streak && self.poll < self.cfg.max_poll {
394 self.poll += 1;
395 self.stable_streak = 0;
396 }
397 } else {
398 self.stable_streak = 0;
399 if offset.abs() > self.cfg.poll_down_noise_ratio * noise
400 && self.poll > self.cfg.min_poll
401 {
402 self.poll -= 1;
403 }
404 }
405
406 // Offset: drain over ~CORR_TIME_RATIO poll intervals, capped by maxslewrate.
407 //
408 // ...except while the offset is unambiguous. The loop re-plans on every
409 // sample, so a drain sized to finish in three poll intervals only ever
410 // runs for one of them before being replaced: the offset decays by a
411 // third per poll, giving a time constant three times longer than the
412 // ratio suggests. In steady state that is exactly the wanted
413 // behaviour — it is what stops sample noise being written into the
414 // clock. During acquisition it is not: a 10 ms startup offset is a
415 // hundred times the noise floor, it is not in dispute, and decaying it
416 // by a third per 16 s poll leaves the clock wrong for a minute.
417 // Measured against chrony under clknetsim, chrony had removed the same
418 // offset within about two seconds while this loop was still 40 s away.
419 //
420 // The test is the one the poll adaptation already uses: an offset far
421 // outside the noise is a real error, not a noisy reading, so correct
422 // it within the interval. Once it is comparable to the noise the
423 // gentle ratio takes over again, and steady-state accuracy — which is
424 // at parity with chrony — is untouched.
425 // Keep the acquisition burst going while a correction is still
426 // outstanding. The drain is sized to finish within one poll interval,
427 // so ending the burst early does not merely delay the next
428 // measurement — it stretches the correction itself from two seconds to
429 // sixteen. On S6 that single step was the entire gap against chrony:
430 // the burst hauled 500 ms down to 9.8 ms by t=10.5 s, then handed what
431 // was left a 16 s deadline and finished at t=26 s where chrony
432 // finished at t=12 s.
433 if self.iburst_left == 0
434 && self.cfg.iburst
435 && self.burst_used < MAX_ACQUIRE_BURST
436 && offset.abs() > ACQUIRE_DONE_S.max(2.0 * noise)
437 {
438 self.iburst_left = 1;
439 }
440
441 let poll_s = self.peek_poll_interval();
442 //
443 // The fast path's premise is "finish this correction before the next
444 // sample". If the rate that would take is above the slew ceiling, the
445 // correction cannot finish within the interval, the premise is false,
446 // and asking for it anyway just pins the clock at maximum slew for the
447 // whole interval — which is how a 500 ms cold start went from a 2.54 ms
448 // steady error to 10.83 ms on the noisy in-house rig while the
449 // low-noise one showed only the improvement. So the fast ratio applies
450 // only when it is actually achievable, and a correction too large to
451 // finish is drained gently, as before.
452 let acquiring = self.updates <= ACQUIRE_UPDATES;
453 // Rate: gentle by default, faster while acquiring.
454 //
455 // The rate stays tied to the poll interval even though drains are now
456 // budgeted and stop when spent. Untying it was tried — "clear any
457 // acquisition offset in ACQUIRE_TARGET_S seconds" — and it is worse:
458 // with a 16 s poll it corrects the whole of each noisy estimate in two
459 // seconds and then coasts for fourteen, which chases noise instead of
460 // averaging it. Scaling with the poll is what makes the correction
461 // proportional to how often the loop actually gets to look.
462 //
463 // What the budget buys is not a faster rate here. It is that the rate
464 // is now free to be chosen at all: an over-fast drain no longer sails
465 // past the offset, it stops at it. Measured on the same binary, the
466 // same discipline with budgets unenforced settles at 579 us on S6 and
467 // with them enforced at 130 us.
468 let wanted_rate_ppm = if acquiring && offset.abs() > ACQUIRE_NOISE_MULTIPLE * noise {
469 // Move at the fastest rate allowed and stop when the offset is
470 // gone. This is only expressible because the drain carries a
471 // budget: without one, a rate this high would not stop at the
472 // offset, it would sail past it, so the rate had to be "the offset
473 // divided by the poll interval" and a cold start's remainder was
474 // handed the poll's deadline. That is what put S6 at 26 s against
475 // chrony's 12 s.
476 // Scales with the poll, so a long interval gets a gentle rate and
477 // the loop averages noise instead of chasing it. A fixed clearing
478 // time was tried and is wrong for exactly that reason: at a 64 s
479 // poll, "clear it in 2 s" is thirty times more aggressive than the
480 // interval warrants, and the in-house S6 steady error went from
481 // 1.5 ms to 9 ms.
482 //
483 // The ceiling is the whole slew budget rather than a quarter of
484 // it. That is safe only because the drain stops when spent: an
485 // over-fast rate now runs out at the offset instead of sailing
486 // past it, and what it delivered is booked even if the caller wakes
487 // late. Without those two properties this cap had to stay low.
488 // Poll-scaled, with a ceiling that depends on how well the offset
489 // is known.
490 //
491 // Untying the rate from the poll entirely -- "clear it in
492 // ACQUIRE_TARGET_S" -- was tried twice and measured worse both
493 // times: 16 s on S6 against 14 s here, and on the noisy rig a fixed
494 // clearing time at a 64 s poll is thirty times more aggressive than
495 // the interval warrants, which chases jitter instead of averaging
496 // it. Scaling with the poll is what keeps the correction
497 // proportional to how often the loop gets to look.
498 ((offset.abs() / (ACQUIRE_CORR_RATIO * poll_s)) * 1e6)
499 .min(self.cfg.max_slew_ppm * self.acquire_share(offset, noise))
500 } else {
501 (offset.abs() / (CORR_TIME_RATIO * poll_s)) * 1e6
502 };
503 let drain_rate_ppm = wanted_rate_ppm.min(self.cfg.max_slew_ppm);
504 self.last_drain_share = if self.cfg.max_slew_ppm > 0.0 {
505 drain_rate_ppm / self.cfg.max_slew_ppm
506 } else {
507 0.0
508 };
509
510 Plan {
511 command: ClockCommand::Slew {
512 freq_ppm: self.freq_ppm,
513 drain_offset: offset,
514 drain_rate_ppm,
515 },
516 next_poll_s: self.take_poll_interval(),
517 reset_register: false,
518 }
519 }
520
521 /// How long to wait before trying again when an exchange yields nothing —
522 /// lost, or rejected because the server was not yet usable.
523 ///
524 /// This is the iburst spacing while the burst budget lasts, *not* the poll
525 /// interval. A server that has only just started answers its first requests
526 /// with the unsynchronised leap indicator, which a client must refuse; if
527 /// that refusal then costs a full poll interval, a cold start is delayed by
528 /// 16 seconds before the first usable sample. Measured against chrony under
529 /// clknetsim, that single wait was most of an 8x convergence gap.
530 ///
531 /// Nothing is consumed here: a failed exchange must not spend burst budget,
532 /// or a few early losses would silently end the burst.
533 pub fn retry_interval_s(&self) -> f64 {
534 self.peek_poll_interval()
535 }
536
537 /// The interval the *next* plan will use, without consuming iburst budget.
538 fn peek_poll_interval(&self) -> f64 {
539 if self.iburst_left > 0 {
540 IBURST_SPACING_S
541 } else {
542 2f64.powi(self.poll as i32)
543 }
544 }
545
546 /// Consume one poll slot — called exactly once per emitted Plan.
547 fn take_poll_interval(&mut self) -> f64 {
548 if self.iburst_left > 0 {
549 self.iburst_left -= 1;
550 self.burst_used += 1;
551 IBURST_SPACING_S
552 } else {
553 2f64.powi(self.poll as i32)
554 }
555 }
556}
557
558#[cfg(test)]
559mod acquisition_tests {
560 use super::*;
561
562 fn acquiring() -> Discipline {
563 Discipline::new(DisciplineConfig {
564 makestep_threshold: None,
565 min_poll: 4, // 16 s
566 iburst: true,
567 ..DisciplineConfig::default()
568 })
569 }
570
571 #[test]
572 fn the_burst_continues_while_a_correction_is_outstanding() {
573 // The drain is sized to finish within one poll interval, so ending the
574 // burst with an offset still outstanding does not just delay the next
575 // measurement — it stretches the correction from 2 s to 16 s. Against
576 // chrony on S6 that one step was the whole gap: 500 ms was hauled down
577 // to 9.8 ms by the burst, and the remainder then took another 16 s.
578 let mut d = acquiring();
579 let mut plan = None;
580 for _ in 0..IBURST_COUNT + 3 {
581 // A 10 ms offset, far above both the 1 ms target and the noise.
582 plan = Some(d.on_estimate(0.010, None, 1e-6));
583 }
584 let next = plan.expect("a plan").next_poll_s;
585 assert!(
586 next <= IBURST_SPACING_S,
587 "burst ended with 10 ms still outstanding: next poll {next} s"
588 );
589 }
590
591 #[test]
592 fn the_burst_ends_once_the_offset_is_small() {
593 // ...and it must end, or a converged client polls a stranger's server
594 // every two seconds forever.
595 let mut d = acquiring();
596 let mut plan = None;
597 for _ in 0..IBURST_COUNT + 3 {
598 plan = Some(d.on_estimate(1e-6, None, 1e-6));
599 }
600 let next = plan.expect("a plan").next_poll_s;
601 assert!(
602 next > IBURST_SPACING_S,
603 "burst kept running on a converged clock: next poll {next} s"
604 );
605 }
606
607 #[test]
608 fn the_extended_burst_is_bounded() {
609 // A client that never converges must back off rather than keep asking.
610 let mut d = acquiring();
611 let mut plan = None;
612 for _ in 0..MAX_ACQUIRE_BURST * 3 {
613 plan = Some(d.on_estimate(0.010, None, 1e-6));
614 }
615 let next = plan.expect("a plan").next_poll_s;
616 assert!(
617 next > IBURST_SPACING_S,
618 "burst never backed off despite never converging: next poll {next} s"
619 );
620 }
621}
622
623#[cfg(test)]
624mod tests {
625 use super::*;
626
627 #[test]
628 fn big_initial_offset_is_stepped() {
629 let mut d = Discipline::new(DisciplineConfig::default());
630 let plan = d.on_estimate(120.0, None, 1e-4);
631 assert!(matches!(
632 plan.command,
633 ClockCommand::Step { add_seconds } if (add_seconds - 120.0).abs() < 1e-9
634 ));
635 assert!(plan.reset_register);
636 }
637
638 #[test]
639 fn step_window_closes() {
640 let mut d = Discipline::new(DisciplineConfig::default());
641 for _ in 0..3 {
642 let _ = d.on_estimate(0.0001, None, 1e-4);
643 }
644 // Fourth update: even a huge offset must slew, not step.
645 let plan = d.on_estimate(5.0, None, 1e-4);
646 assert!(matches!(plan.command, ClockCommand::Slew { .. }));
647 }
648
649 #[test]
650 fn freq_accumulates_and_clamps() {
651 let mut d = Discipline::new(DisciplineConfig::default());
652 let _ = d.on_estimate(1e-4, Some(100.0), 1e-4);
653 assert!((d.freq_ppm() - 100.0).abs() < 1e-9);
654 let _ = d.on_estimate(1e-4, Some(1000.0), 1e-4);
655 assert!((d.freq_ppm() - 500.0).abs() < 1e-9, "clamped at max_freq");
656 }
657
658 #[test]
659 fn iburst_then_normal_cadence() {
660 let mut d = Discipline::new(DisciplineConfig::default());
661 let mut intervals = Vec::new();
662 for _ in 0..6 {
663 let plan = d.on_estimate(1e-5, None, 1e-4);
664 intervals.push(plan.next_poll_s);
665 }
666 assert!(intervals[..4].iter().all(|&i| i == 2.0), "{intervals:?}");
667 assert!(intervals[4] >= 64.0, "{intervals:?}");
668 }
669
670 #[test]
671 fn closed_loop_converges() {
672 // A toy plant: local clock 40 ppm fast, 30 ms ahead. The discipline reads
673 // perfect estimates each poll; assert the loop pulls both to ~zero.
674 let mut d = Discipline::new(DisciplineConfig {
675 iburst: false,
676 makestep_threshold: None,
677 ..DisciplineConfig::default()
678 });
679 let mut clock_err_s = 0.030_f64; // local - true
680 let base_freq_ppm = 40.0;
681 let mut t = 0.0;
682 for _ in 0..60 {
683 // The measured offset is what we should ADD: -(clock_err).
684 let offset = -clock_err_s;
685 // Perfect freq measurement: the regression slope is dθ/dt, and
686 // θ = -err, so the slope is -(base + applied).
687 let slope_ppm = -(base_freq_ppm + d.freq_ppm());
688 let plan = d.on_estimate(offset, Some(slope_ppm), 1e-5);
689 let dt = plan.next_poll_s;
690 if let ClockCommand::Slew {
691 freq_ppm,
692 drain_offset,
693 drain_rate_ppm,
694 } = plan.command
695 {
696 // Plant integration over dt: positive applied freq speeds the
697 // local clock (raises err); the drain adds θ toward zero err.
698 let drift = (base_freq_ppm + freq_ppm) * 1e-6 * dt;
699 let max_drain = drain_rate_ppm * 1e-6 * dt;
700 let drain = drain_offset.abs().min(max_drain) * drain_offset.signum();
701 clock_err_s += drift + drain;
702 }
703 t += dt;
704 }
705 assert!(
706 clock_err_s.abs() < 1e-4,
707 "did not converge: err {clock_err_s} at t {t}"
708 );
709 assert!(
710 (d.freq_ppm() + 40.0).abs() < 2.0,
711 "freq not learned (want ~-40): {}",
712 d.freq_ppm()
713 );
714 }
715}