ferravex_net/history.rs
1//! Bounded authority history and clock estimates; rendering and transport are independent.
2//!
3//! [`History::bracket_precise`] keeps tick identity as an integer. Its optional
4//! freshness cutoff is caller data, independent of the requested presentation
5//! time. Here a host supplies both times in the same nonwrapping session epoch:
6//!
7//! ```
8//! use ferravex_net::history::{History, HistoryBracket, HistoryEndpointPolicy};
9//! use ferravex_net::clock::{ClientClock, TickUnwrapper};
10//!
11//! #[derive(Debug, PartialEq)]
12//! struct Pose { x: f64 }
13//! let base = (1_u64 << 53) + 10;
14//! let mut history = History::new(2);
15//! assert!(history.push(base, Pose { x: 2.0 }));
16//! assert!(history.push(base + 1, Pose { x: 6.0 }));
17//! let now_tick = base + 2; // Supplied authority time, not a wall clock read.
18//! let minimum_newest_tick = Some(now_tick.saturating_sub(2));
19//! let query = |tick, fraction| history.bracket_precise(
20//! tick, fraction, HistoryEndpointPolicy::Reject, minimum_newest_tick);
21//! assert!(matches!(query(base + 1, 0.0)?,
22//! HistoryBracket::Exact { sample: (tick, pose) }
23//! if tick == base + 1 && pose.x == 6.0));
24//! let presented = match query(base, 0.25)? {
25//! HistoryBracket::Interpolated { before: (_, a), after: (_, b), alpha } => {
26//! Pose { x: a.x + (b.x - a.x) * alpha }
27//! }
28//! other => panic!("expected retained neighbors, got {other:?}"),
29//! };
30//! assert_eq!(presented, Pose { x: 3.0 });
31//! assert!(history.push(base + 2, Pose { x: 10.0 })); // Evicts base.
32//! assert!(matches!(history.bracket_precise(base, 0.5,
33//! HistoryEndpointPolicy::Reject, None)?, HistoryBracket::BeforeOldest { .. }));
34//! assert!(matches!(history.bracket_precise(base, 0.5,
35//! HistoryEndpointPolicy::Clamp, None)?,
36//! HistoryBracket::Clamped { sample: (tick, _) } if tick == base + 1));
37//! let later_now_tick = base + 6;
38//! assert!(matches!(history.bracket_precise(base + 1, 0.0,
39//! HistoryEndpointPolicy::Clamp, Some(later_now_tick - 2))?,
40//! HistoryBracket::Stale { newest: (tick, _), .. } if tick == base + 2));
41//!
42//! // At reconnect, first exclude old-session traffic at the transport boundary.
43//! // Clear retained poses and reset the separate clock/tick epochs together.
44//! let mut clock = ClientClock::default();
45//! let mut ticks = TickUnwrapper::default();
46//! ticks.observe(u32::MAX);
47//! history.clear();
48//! clock.reset();
49//! ticks.reset();
50//! assert_eq!(ticks.observe(1), Some(1));
51//! assert!(history.push(1, Pose { x: 20.0 })); // Lower new-session ticks now fit.
52//! assert_eq!(history.len(), 1);
53//! # Ok::<(), ferravex_net::history::HistoryQueryError>(())
54//! ```
55use std::collections::VecDeque;
56
57/// Treatment of valid queries outside retained samples. Neither policy extrapolates.
58#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
59#[non_exhaustive]
60pub enum HistoryEndpointPolicy {
61 /// Report [`HistoryBracket::BeforeOldest`] or [`HistoryBracket::AfterNewest`].
62 #[default]
63 Reject,
64 /// Explicitly select the nearest retained sample as [`HistoryBracket::Clamped`].
65 Clamp,
66}
67
68/// Placement within actual retained samples; states are borrowed without cloning.
69///
70/// See the [module recipe](self) for exact selection, pose interpolation, eviction,
71/// supplied-time staleness and reconnect. Only `Interpolated` supplies a weight;
72/// neither a rounded endpoint weight nor a clamped result implies exact identity.
73#[derive(Debug, PartialEq)]
74#[non_exhaustive]
75pub enum HistoryBracket<'a, T> {
76 /// No retained samples. No freshness claim can be made.
77 Empty,
78 /// The query's integer tick matches this sample and its normalized fraction is zero.
79 Exact { sample: (u64, &'a T) },
80 /// Consecutive retained samples strictly surround the query (including sparse gaps).
81 Interpolated {
82 before: (u64, &'a T),
83 after: (u64, &'a T),
84 /// Approximate weight in `[0, 1]`, computed from local integer differences.
85 ///
86 /// `f64` rounding may produce 0 or 1 for a strictly interior query over
87 /// large gaps. Exact tick identity is determined before this calculation.
88 alpha: f64,
89 },
90 /// Query is earlier than all retained samples; no state was selected.
91 BeforeOldest { oldest: (u64, &'a T) },
92 /// Query is later than all retained samples; no state was selected.
93 AfterNewest { newest: (u64, &'a T) },
94 /// Out-of-range query explicitly selected the nearest endpoint, without extrapolation.
95 Clamped { sample: (u64, &'a T) },
96 /// The newest retained tick is strictly below the caller's inclusive cutoff.
97 ///
98 /// This rejects the entire history before exact/range selection. It says
99 /// nothing about elapsed wall time, the query's age, or why updates stopped.
100 Stale {
101 newest: (u64, &'a T),
102 minimum_newest_tick: u64,
103 },
104}
105
106/// Invalid input to [`History::bracket_precise`], validated even for empty history.
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108#[non_exhaustive]
109pub enum HistoryQueryError {
110 /// Fraction is nonfinite or outside `[0, 1]`.
111 InvalidFraction,
112 /// Normalizing `(u64::MAX, 1.0)` would overflow the integer tick.
113 TickOverflow,
114}
115
116impl std::fmt::Display for HistoryQueryError {
117 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118 f.write_str(match self {
119 Self::InvalidFraction => "history fraction must be finite and in [0, 1]",
120 Self::TickOverflow => "history fraction carries beyond the maximum tick",
121 })
122 }
123}
124
125impl std::error::Error for HistoryQueryError {}
126
127#[derive(Clone, Debug)]
128pub struct History<T> {
129 samples: VecDeque<(u64, T)>,
130 capacity: usize,
131}
132impl<T> History<T> {
133 pub fn new(capacity: usize) -> Self {
134 assert!((1..=4096).contains(&capacity));
135 Self {
136 samples: VecDeque::with_capacity(capacity),
137 capacity,
138 }
139 }
140 pub fn push(&mut self, tick: u64, state: T) -> bool {
141 if self.samples.back().is_some_and(|(last, _)| tick <= *last) {
142 return false;
143 }
144 if self.samples.len() == self.capacity {
145 self.samples.pop_front();
146 }
147 self.samples.push_back((tick, state));
148 true
149 }
150 /// No extrapolation outside retained history: old/untrusted shot times are rejected.
151 pub fn bracket(&self, tick: f64) -> Option<(&T, &T, f32)> {
152 if !tick.is_finite()
153 || tick < self.samples.front()?.0 as f64
154 || tick > self.samples.back()?.0 as f64
155 {
156 return None;
157 }
158 for i in 0..self.samples.len() {
159 let (a, left) = &self.samples[i];
160 if tick == *a as f64 {
161 return Some((left, left, 0.0));
162 }
163 if let Some((b, right)) = self.samples.get(i + 1)
164 && tick < *b as f64
165 {
166 return Some((left, right, ((tick - *a as f64) / (*b - *a) as f64) as f32));
167 }
168 }
169 None
170 }
171 /// Locate `tick + fraction` while comparing integer tick components exactly.
172 ///
173 /// `fraction` must be finite and in `[0, 1]`. Exactly 1 carries to the next
174 /// integer tick; negative zero is zero. `(u64::MAX, 1)` is an overflow error,
175 /// while `(u64::MAX, fraction < 1)` is valid: a positive fraction there is
176 /// after every possible sample. Invalid inputs are never silently clamped.
177 ///
178 /// `minimum_newest_tick` is an optional inclusive freshness cutoff in the
179 /// same nonwrapping authority/session tick domain as the stored samples. A
180 /// host with supplied authority `now_tick` and an integer maximum age can
181 /// pass `Some(now_tick.saturating_sub(max_age_ticks))`. `None` disables this
182 /// check. The target tick is **not** assumed to be current server time. A
183 /// cutoff cannot detect mismatched sessions or clock domains.
184 ///
185 /// Precedence is input errors, empty, stale, then exact/interpolated/range
186 /// placement. Freshness equality passes. The endpoint policy only affects
187 /// out-of-range placement; it cannot override stale or invalid input.
188 ///
189 /// Lookup takes `O(log(len))` time across wrapped ring storage, allocates
190 /// nothing and leaves history unchanged. Strict insertion order makes each
191 /// interpolation gap positive. Subtraction occurs in ordered `u64` values
192 /// before conversion to `f64`, so short gaps at large ticks remain precise.
193 /// Weights are approximate over wide gaps; use the outcome for identity,
194 /// never `alpha == 0` or `alpha == 1`. See the runnable [module recipe](self).
195 pub fn bracket_precise(
196 &self,
197 tick: u64,
198 fraction: f64,
199 endpoints: HistoryEndpointPolicy,
200 minimum_newest_tick: Option<u64>,
201 ) -> Result<HistoryBracket<'_, T>, HistoryQueryError> {
202 if !(0.0..=1.0).contains(&fraction) {
203 return Err(HistoryQueryError::InvalidFraction);
204 }
205 let (tick, fraction) = if fraction == 1.0 {
206 (
207 tick.checked_add(1).ok_or(HistoryQueryError::TickOverflow)?,
208 0.0,
209 )
210 } else {
211 (tick, fraction)
212 };
213 let Some((newest_tick, newest)) = self.samples.back() else {
214 return Ok(HistoryBracket::Empty);
215 };
216 if let Some(minimum_newest_tick) = minimum_newest_tick
217 && *newest_tick < minimum_newest_tick
218 {
219 return Ok(HistoryBracket::Stale {
220 newest: (*newest_tick, newest),
221 minimum_newest_tick,
222 });
223 }
224 let after_index = match self
225 .samples
226 .binary_search_by_key(&tick, |(sample_tick, _)| *sample_tick)
227 {
228 Ok(index) if fraction == 0.0 => {
229 let (tick, state) = &self.samples[index];
230 return Ok(HistoryBracket::Exact {
231 sample: (*tick, state),
232 });
233 }
234 Ok(index) => index + 1,
235 Err(index) => index,
236 };
237 if after_index == 0 {
238 let (tick, state) = &self.samples[0];
239 let oldest = (*tick, state);
240 return Ok(match endpoints {
241 HistoryEndpointPolicy::Reject => HistoryBracket::BeforeOldest { oldest },
242 HistoryEndpointPolicy::Clamp => HistoryBracket::Clamped { sample: oldest },
243 });
244 }
245 let (before_tick, before) = &self.samples[after_index - 1];
246 if after_index == self.samples.len() {
247 let newest = (*before_tick, before);
248 return Ok(match endpoints {
249 HistoryEndpointPolicy::Reject => HistoryBracket::AfterNewest { newest },
250 HistoryEndpointPolicy::Clamp => HistoryBracket::Clamped { sample: newest },
251 });
252 }
253 let (after_tick, after) = &self.samples[after_index];
254 let alpha = ((tick - before_tick) as f64 + fraction) / (after_tick - before_tick) as f64;
255 Ok(HistoryBracket::Interpolated {
256 before: (*before_tick, before),
257 after: (*after_tick, after),
258 alpha,
259 })
260 }
261
262 /// Drop all retained states and forget insertion order, keeping allocated capacity.
263 ///
264 /// On return, a lower tick may start a new session. Clear this history at the
265 /// same reconnect boundary as [`crate::clock::ClientClock::reset`] and
266 /// [`crate::clock::TickUnwrapper::reset`], after excluding old-session traffic.
267 /// Neither clearing nor tick unwrapping authenticates a session. Old samples
268 /// cannot be recovered. A panic or side effect in `T::drop` is not rolled back;
269 /// allocation-free reuse assumes the states' destructors do not allocate.
270 /// The [module recipe](self) demonstrates lower-tick reuse after reconnect.
271 pub fn clear(&mut self) {
272 self.samples.clear();
273 }
274
275 pub fn iter(&self) -> impl Iterator<Item = (u64, &T)> {
276 self.samples.iter().map(|(t, v)| (*t, v))
277 }
278 pub fn first_tick(&self) -> Option<u64> {
279 self.samples.front().map(|s| s.0)
280 }
281 pub fn len(&self) -> usize {
282 self.samples.len()
283 }
284 pub fn is_empty(&self) -> bool {
285 self.samples.is_empty()
286 }
287}
288#[derive(Default, Clone, Copy, Debug)]
289pub struct ClockSync {
290 pub offset_seconds: f64,
291 pub rtt_seconds: f64,
292 samples: u32,
293}
294impl ClockSync {
295 /// NTP-style exchange: local send/receive and server receive/send timestamps.
296 pub fn observe(
297 &mut self,
298 local_send: f64,
299 server_receive: f64,
300 server_send: f64,
301 local_receive: f64,
302 ) -> bool {
303 if ![local_send, server_receive, server_send, local_receive]
304 .iter()
305 .all(|v| v.is_finite())
306 || local_receive < local_send
307 || server_send < server_receive
308 {
309 return false;
310 }
311 let rtt = (local_receive - local_send) - (server_send - server_receive);
312 if !(0.0..=5.0).contains(&rtt) {
313 return false;
314 }
315 let offset = ((server_receive - local_send) + (server_send - local_receive)) * 0.5;
316 let weight = if self.samples == 0 { 1.0 } else { 0.125 };
317 self.offset_seconds += (offset - self.offset_seconds) * weight;
318 self.rtt_seconds += (rtt - self.rtt_seconds) * weight;
319 self.samples = self.samples.saturating_add(1);
320 true
321 }
322 pub fn server_time(&self, local: f64) -> f64 {
323 local + self.offset_seconds
324 }
325}
326#[cfg(test)]
327mod tests {
328 use super::*;
329 #[test]
330 fn old_or_future_shots_are_rejected_and_history_interpolates() {
331 let mut h = History::new(3);
332 for i in 0..5 {
333 assert!(h.push(i, i as f32));
334 }
335 assert_eq!(h.len(), 3);
336 assert!(h.bracket(1.0).is_none());
337 assert!(h.bracket(5.0).is_none());
338 assert!(!h.push(3, 0.0));
339 assert_eq!(h.bracket(2.5), Some((&2.0, &3.0, 0.5)));
340 assert_eq!(h.bracket(4.0), Some((&4.0, &4.0, 0.0)));
341 }
342 #[test]
343 fn clock_offset_accounts_for_server_processing() {
344 let mut c = ClockSync::default();
345 assert!(c.observe(1.0, 11.1, 11.2, 1.3));
346 assert!((c.offset_seconds - 10.0).abs() < 1e-9);
347 assert!((c.rtt_seconds - 0.2).abs() < 1e-9);
348 assert!(!c.observe(f64::NAN, 0., 0., 0.));
349 }
350}