Skip to main content

zenkey_model/
freshness.rs

1//! `freshness.v1`: how long a value stays current
2//! (`spec/profiles/freshness/v1.md`, #720).
3//!
4//! The profile's session-free half: the horizon read from a resource's
5//! annotations (§2.1–§2.3), and the pure judgement of one observation of a
6//! member (§2.5–§2.8), three states and a reason, with the rule that
7//! combines several observations (§2.7).
8//!
9//! ```text
10//! horizon(kind, annotations) ─▶ Undeclared │ Ignored │ Invalid │ Never │ Within(ttl)
11//! judge(horizon, observation) ─▶ fresh │ stale │ unobservable │ not_asked, + reason
12//! combine(judged…)            ─▶ fresh > stale > unobservable > not_asked
13//! ```
14//!
15//! There is no I/O and no clock here. A reader measures what an observation
16//! holds (a delivery's age on its monotonic clock, a reply's stamp age
17//! against its wall clock, whether that clock is trusted to the delta) and
18//! hands it over as values. The owner's re-puts (§2.4) are the runtime's.
19//!
20//! **A reader's view** ([`View`], #978's F2): the members of one owner's
21//! collections for one interface as a reader heard them, and what that
22//! owner's heartbeats (core §7.5, [`crate::heartbeat`]) confirmed. A
23//! heartbeat whose section's digest is the view's confirms each member it
24//! vouches for at its arrival, so [`View::observation`] ages a member from
25//! the later of its last put and its last confirmation. `freshness.v2`
26//! (`spec/profiles/freshness/v2.md`, #978's F3) adopts the heartbeat: a
27//! contract that uses it is confirmed by its owner's heartbeats, never by
28//! re-puts ([`uses_v2`]), and its reader's rule is [`View::apply`]'s
29//! (`conformance/apply.json`). The judgement is §2.5's, unchanged.
30
31use std::collections::BTreeMap;
32use std::fmt;
33use std::time::{Duration, SystemTime};
34
35use serde_json::Value;
36
37use crate::authoring::Kind;
38use crate::contract::Resource;
39use crate::wire::Stamp;
40
41/// The profile's id, as a contract lists it in `uses`.
42pub const PROFILE: &str = "freshness.v1";
43
44/// `freshness.v2`'s id (#978's F3): a contract that lists it in `uses` is
45/// confirmed by its owner's heartbeats (core §7.5's form 6), one per
46/// interface, and its owner re-puts nothing to confirm it (v2 §2.4).
47pub const PROFILE_V2: &str = crate::heartbeat::PROFILE;
48
49/// Whether `c` uses `freshness.v2` (v2 §1): its owner confirms its
50/// collections by heartbeats, re-puts none of them, and puts them without
51/// a Zenoh timestamp, its replies carrying each member's last confirmation
52/// (core §4.3's table, row 1). A contract listing both texts is read
53/// under v2.
54#[must_use]
55pub fn uses_v2(c: &crate::contract::Contract) -> bool {
56    c.uses.iter().any(|u| u.to_string() == PROFILE_V2)
57}
58
59/// The profile's name, as an annotation key's prefix carries it.
60pub const NAME: &str = "freshness";
61
62/// The one annotation key (§4).
63pub const TTL_S: &str = "freshness.ttl_s";
64
65/// The published vocabulary (§4): the keys under `freshness.`, which W105
66/// reads in place of core Appendix D's interim row (core 0.21).
67pub const VOCABULARY: &[&str] = &["ttl_s"];
68
69/// The largest horizon, in seconds: 2^53−1, the canonical domain's bound
70/// (§2.1, core §9.5).
71pub const MAX_TTL_S: u64 = (1 << 53) - 1;
72
73/// The HLC's maximum delta unless the deployment configures another (core
74/// §4.1): what a GET reader's trusted clock is trusted to (§2.6).
75pub const DEFAULT_DELTA: Duration = Duration::from_millis(500);
76
77/// A resource's staleness horizon, read from its resolved annotations
78/// (§2.1–§2.3).
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub enum Horizon {
81    /// No `freshness.ttl_s`: freshness is not asked (§2.3).
82    Undeclared,
83    /// A horizon on an event or an operation, which have no freshness
84    /// (§2.2): ignored.
85    Ignored,
86    /// A `freshness.ttl_s` that is not a horizon (§2.1), as JSON text: the
87    /// resource's freshness is unobservable.
88    Invalid(String),
89    /// `0`: never stale (§2.3).
90    Never,
91    /// A horizon above 0.
92    Within(Duration),
93}
94
95impl Horizon {
96    /// The horizon, when it is one above 0.
97    #[must_use]
98    pub fn ttl(&self) -> Option<Duration> {
99        match self {
100            Self::Within(t) => Some(*t),
101            _ => None,
102        }
103    }
104
105    /// The owner's bound between two puts of a member (§2.4): ttl/2, when
106    /// the horizon is above 0.
107    #[must_use]
108    pub fn refresh_bound(&self) -> Option<Duration> {
109        self.ttl().map(|t| t / 2)
110    }
111}
112
113impl fmt::Display for Horizon {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        match self {
116            Self::Undeclared => f.write_str("no horizon"),
117            Self::Ignored => f.write_str("a horizon this kind ignores"),
118            Self::Invalid(v) => write!(f, "{v}, not a horizon"),
119            Self::Never => f.write_str("ttl_s = 0, never stale"),
120            Self::Within(t) => write!(f, "ttl_s = {}", t.as_secs()),
121        }
122    }
123}
124
125/// Reads the horizon of a resource of `kind` from its resolved annotations
126/// (§2.1, §2.2): `[defaults]`, then `[defaults.<kind>]`, then its own, as
127/// the contract model merges them (core §9.3).
128#[must_use]
129pub fn horizon(kind: Kind, annotations: &BTreeMap<String, Value>) -> Horizon {
130    let Some(v) = annotations.get(TTL_S) else {
131        return Horizon::Undeclared;
132    };
133    if matches!(kind, Kind::Event | Kind::Operation) {
134        return Horizon::Ignored;
135    }
136    match seconds(v) {
137        Some(0) => Horizon::Never,
138        Some(n) => Horizon::Within(Duration::from_secs(n)),
139        None => Horizon::Invalid(v.to_string()),
140    }
141}
142
143/// [`horizon`] of a resource of a contract.
144#[must_use]
145pub fn horizon_of(r: &Resource) -> Horizon {
146    horizon(r.kind, &r.annotations)
147}
148
149/// A whole number of seconds from 0 to 2^53−1, or `None` (§2.1). An
150/// integral float is that integer, as the canonical form writes it: `60.0`
151/// is 60, and `-0.0` is 0.
152fn seconds(v: &Value) -> Option<u64> {
153    let n = v.as_number()?;
154    if let Some(u) = n.as_u64() {
155        return (u <= MAX_TTL_S).then_some(u);
156    }
157    if n.is_i64() {
158        return None;
159    }
160    let f = n.as_f64()?;
161    // `-0.0 >= 0.0` holds: JCS writes it `0`.
162    let max = MAX_TTL_S as f64;
163    (f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= max).then_some(f as u64)
164}
165
166/// A reply stamp's age at the instant a reader judges it: its clock minus
167/// the stamp's time, negative when the stamp is ahead of the reader's clock
168/// (§2.6). Nanoseconds.
169#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
170pub struct StampAge(i128);
171
172impl StampAge {
173    /// The age at `now` of a stamp whose time is `stamp`.
174    #[must_use]
175    pub fn between(stamp: SystemTime, now: SystemTime) -> Self {
176        match now.duration_since(stamp) {
177            Ok(d) => Self::behind(d),
178            Err(e) => Self::ahead(e.duration()),
179        }
180    }
181
182    /// A stamp `d` before the reader's clock.
183    #[must_use]
184    pub fn behind(d: Duration) -> Self {
185        Self(d.as_nanos() as i128)
186    }
187
188    /// A stamp `d` ahead of the reader's clock.
189    #[must_use]
190    pub fn ahead(d: Duration) -> Self {
191        Self(-(d.as_nanos() as i128))
192    }
193
194    /// Seconds, rounded to the nanosecond: how the fixtures write it.
195    #[must_use]
196    pub fn from_secs_f64(s: f64) -> Self {
197        Self((s * 1e9).round() as i128)
198    }
199
200    #[must_use]
201    pub fn as_secs_f64(self) -> f64 {
202        self.0 as f64 / 1e9
203    }
204
205    /// Nanoseconds, negative when the stamp is ahead.
206    #[must_use]
207    pub fn nanos(self) -> i128 {
208        self.0
209    }
210}
211
212/// Whether a GET reader trusts its clock against the clock that stamped a
213/// reply (§2.6).
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215pub enum ClockTrust {
216    /// The two agree within `delta`: on the deployment's word, or measured.
217    Trusted { delta: Duration },
218    /// No ground to trust them: a reply's age is unobservable.
219    Untrusted,
220}
221
222/// What a reader measured of one stamping clock during a reading (§2.6,
223/// ground 2, 0.2): the offset closest to its own clock, since transit only
224/// adds to an offset, and the offset furthest ahead, since a stamp ahead of
225/// the reader's clock by more than the delta proves the clocks disagree
226/// whatever the transit.
227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228pub struct ClockMeasure {
229    closest: StampAge,
230    most_ahead: StampAge,
231}
232
233impl ClockMeasure {
234    /// A first measurement.
235    #[must_use]
236    pub fn new(offset: StampAge) -> Self {
237        Self {
238            closest: offset,
239            most_ahead: offset,
240        }
241    }
242
243    /// Another live put's offset, in the same reading.
244    pub fn record(&mut self, offset: StampAge) {
245        if offset.nanos().unsigned_abs() < self.closest.nanos().unsigned_abs() {
246            self.closest = offset;
247        }
248        if offset < self.most_ahead {
249            self.most_ahead = offset;
250        }
251    }
252
253    /// Two readers' measurements of one clock, as one reading's.
254    #[must_use]
255    pub fn merge(mut self, other: Self) -> Self {
256        self.record(other.closest);
257        self.record(other.most_ahead);
258        self
259    }
260
261    /// The offset closest to the reader's clock.
262    #[must_use]
263    pub fn closest(&self) -> StampAge {
264        self.closest
265    }
266
267    /// The offset furthest ahead (the most negative).
268    #[must_use]
269    pub fn most_ahead(&self) -> StampAge {
270        self.most_ahead
271    }
272
273    /// §2.6, ground 2 (0.2): trusted when the closest offset is within
274    /// `delta`, and no stamp was ahead by more than `delta`.
275    #[must_use]
276    pub fn trust(&self, delta: Duration) -> ClockTrust {
277        let d = delta.as_nanos() as i128;
278        if self.closest.nanos().unsigned_abs() <= delta.as_nanos() && self.most_ahead.nanos() >= -d
279        {
280            ClockTrust::Trusted { delta }
281        } else {
282            ClockTrust::Untrusted
283        }
284    }
285}
286
287impl ClockTrust {
288    /// §2.6, ground 2 (0.2), over a reading's measurements of one clock:
289    /// untrusted when there are none.
290    #[must_use]
291    pub fn from_offsets(offsets: impl IntoIterator<Item = StampAge>, delta: Duration) -> Self {
292        let mut it = offsets.into_iter();
293        let Some(first) = it.next() else {
294            return Self::Untrusted;
295        };
296        let mut m = ClockMeasure::new(first);
297        it.for_each(|o| m.record(o));
298        m.trust(delta)
299    }
300
301    /// §2.6, ground 2: a live put whose stamp was `offset` from the reader's
302    /// clock at receipt (the receipt minus the stamp) shows the clocks agree
303    /// within `delta` when the offset is within it, either way.
304    #[must_use]
305    pub fn measured(offset: StampAge, delta: Duration) -> Self {
306        if offset.0.unsigned_abs() <= delta.as_nanos() {
307            Self::Trusted { delta }
308        } else {
309            Self::Untrusted
310        }
311    }
312}
313
314/// A subscription's last delivery of a member, and how long ago it arrived
315/// on the subscriber's monotonic clock (§2.5).
316#[derive(Debug, Clone, Copy, PartialEq, Eq)]
317pub enum Last {
318    /// A put (a change or a re-put), or a stream sample.
319    Put(Duration),
320    /// A delete: the member has no value.
321    Delete(Duration),
322}
323
324/// The owner's reply for a member (§2.6).
325#[derive(Debug, Clone, Copy, PartialEq, Eq)]
326pub enum Reply {
327    /// A value, with its stamp's age at the instant of judgement, or `None`
328    /// when the reply carries no stamp (which breaks core S2).
329    Put { stamp_age: Option<StampAge> },
330    /// A `reply_del`: the member is deleted.
331    Delete,
332}
333
334/// One observation of one member, as a reader made it.
335#[derive(Debug, Clone, Copy, PartialEq, Eq)]
336pub enum Observation {
337    /// A subscription (§2.5): its last delivery of the member, how long it
338    /// has listened since it was declared, and whether it lost deliveries
339    /// (`complete` is false when it did).
340    Subscribed {
341        last: Option<Last>,
342        listened: Duration,
343        complete: bool,
344    },
345    /// A GET to the owner (§2.6): its reply for the member, or `None` when
346    /// none came within the timeout, and the reader's trust in its clock
347    /// against the reply's stamp.
348    Got {
349        reply: Option<Reply>,
350        clock: ClockTrust,
351    },
352    /// An archive's answer: last-known, never current (§2.8).
353    Archived,
354}
355
356/// What a GET reader read of one member from its collection's snapshot
357/// (`freshness.v2` §2.6, text 0.7; core §4.2).
358#[derive(Debug, Clone, Copy, PartialEq, Eq)]
359pub enum Entry {
360    /// The snapshot lists the member neither live nor as a tombstone.
361    Omitted,
362    /// A tombstone: a `reply_del`.
363    Tombstone,
364    /// A live entry, with its confirmation's age at the instant of
365    /// judgement: the snapshot's time for confirmation 1, the entry's conf
366    /// for 2. `None` for confirmation 0, or a time that is unknown: no
367    /// stamp.
368    Live { stamp_age: Option<StampAge> },
369}
370
371impl Observation {
372    /// A snapshot's `entry` of one member as a GET's observation (v2 §2.6):
373    /// an entry is judged as a reply, its confirmation's time as the stamp,
374    /// under the reader's trust in the owner's `clock`, which built the
375    /// snapshot. A member a `complete` snapshot omits is deleted, by core
376    /// §4.2's omission rule, and one an incomplete snapshot omits is
377    /// silent.
378    #[must_use]
379    pub fn of_entry(complete: bool, entry: Entry, clock: ClockTrust) -> Observation {
380        let reply = match entry {
381            Entry::Omitted if !complete => None,
382            Entry::Omitted | Entry::Tombstone => Some(Reply::Delete),
383            Entry::Live { stamp_age } => Some(Reply::Put { stamp_age }),
384        };
385        Observation::Got { reply, clock }
386    }
387}
388
389/// The answer to "is this member's value fresh?" (§5). Stale is the
390/// finding.
391#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
392pub enum Verdict {
393    Fresh,
394    Stale,
395    /// The question was put, and the observation could not answer it.
396    Unobservable,
397    /// Nobody put the question, or its premise does not hold (the reason
398    /// says which).
399    NotAsked,
400}
401
402impl Verdict {
403    /// The fixture's token.
404    #[must_use]
405    pub fn as_str(self) -> &'static str {
406        match self {
407            Self::Fresh => "fresh",
408            Self::Stale => "stale",
409            Self::Unobservable => "unobservable",
410            Self::NotAsked => "not_asked",
411        }
412    }
413}
414
415impl fmt::Display for Verdict {
416    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417        f.write_str(self.as_str())
418    }
419}
420
421/// Why a verdict is what it is: the fixture's reason class.
422#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
423pub enum Reason {
424    /// Fresh: confirmed within the horizon (§2.5, §2.6).
425    WithinHorizon,
426    /// Fresh: ttl 0 (§2.3).
427    NeverStale,
428    /// Stale: the last confirmation is older than the horizon.
429    BeyondHorizon,
430    /// Stale: nothing delivered while listening longer than the horizon.
431    NoDelivery,
432    /// Unobservable: the `freshness.ttl_s` is not a horizon (§2.1).
433    NotAHorizon,
434    /// Unobservable: nothing delivered, and listened the horizon or less.
435    ListenedTooShort,
436    /// Unobservable: deliveries were lost, and none fresh arrived.
437    Incomplete,
438    /// Unobservable: the GET drew no reply for the member.
439    Silent,
440    /// Unobservable: the reply carries no stamp.
441    NoStamp,
442    /// Unobservable: the reader's clock is not trusted to the delta.
443    ClockUntrusted,
444    /// Unobservable: the stamp is ahead of the reader's clock beyond the
445    /// delta.
446    ClockDisagrees,
447    /// Unobservable: the age is within the delta of the horizon.
448    NearHorizon,
449    /// Unobservable: no observation to judge.
450    NoObservation,
451    /// Not asked: no horizon (§2.3).
452    NoHorizon,
453    /// Not this profile's: an event or an operation (§2.2).
454    Kind,
455    /// Not asked: an archive's last-known value (§2.8).
456    LastKnown,
457    /// Not this profile's: the member is deleted.
458    Deleted,
459}
460
461impl Reason {
462    /// The fixture's token.
463    #[must_use]
464    pub fn as_str(self) -> &'static str {
465        match self {
466            Self::WithinHorizon => "within_horizon",
467            Self::NeverStale => "never_stale",
468            Self::BeyondHorizon => "beyond_horizon",
469            Self::NoDelivery => "no_delivery",
470            Self::NotAHorizon => "not_a_horizon",
471            Self::ListenedTooShort => "listened_too_short",
472            Self::Incomplete => "incomplete",
473            Self::Silent => "silent",
474            Self::NoStamp => "no_stamp",
475            Self::ClockUntrusted => "clock_untrusted",
476            Self::ClockDisagrees => "clock_disagrees",
477            Self::NearHorizon => "near_horizon",
478            Self::NoObservation => "no_observation",
479            Self::NoHorizon => "no_horizon",
480            Self::Kind => "kind",
481            Self::LastKnown => "last_known",
482            Self::Deleted => "deleted",
483        }
484    }
485
486    /// The reason in words, for a tool's message.
487    #[must_use]
488    pub fn says(self) -> &'static str {
489        match self {
490            Self::WithinHorizon => "confirmed within its horizon",
491            Self::NeverStale => "ttl_s = 0, never stale",
492            Self::BeyondHorizon => "not confirmed within its horizon",
493            Self::NoDelivery => "nothing delivered for longer than its horizon",
494            Self::NotAHorizon => "its freshness.ttl_s is not a horizon",
495            Self::ListenedTooShort => {
496                "nothing delivered, and not listened to for longer than its horizon"
497            }
498            Self::Incomplete => "deliveries were lost, and none within the horizon arrived",
499            Self::Silent => "no value was read",
500            Self::NoStamp => "the reply carries no stamp",
501            Self::ClockUntrusted => {
502                "this reader's clock is not trusted to the HLC delta against the stamping clock"
503            }
504            Self::ClockDisagrees => "the stamp is ahead of this reader's clock beyond the delta",
505            Self::NearHorizon => "the age is within the delta of the horizon",
506            Self::NoObservation => "nothing was observed",
507            Self::NoHorizon => "no freshness.ttl_s, so freshness is not asked",
508            Self::Kind => "an event or an operation has no freshness",
509            Self::LastKnown => "an archive's last-known value is never current",
510            Self::Deleted => "deleted, so no value",
511        }
512    }
513}
514
515impl fmt::Display for Reason {
516    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
517        f.write_str(self.as_str())
518    }
519}
520
521/// A verdict and its reason.
522#[derive(Debug, Clone, Copy, PartialEq, Eq)]
523pub struct Judged {
524    pub verdict: Verdict,
525    pub reason: Reason,
526}
527
528impl Judged {
529    const fn new(verdict: Verdict, reason: Reason) -> Self {
530        Self { verdict, reason }
531    }
532}
533
534/// Judges one observation of a member of a resource whose horizon is `h`,
535/// by the order of §2.7: the horizon (§2.3, §2.2), an archive (§2.8), a
536/// value that is no horizon (§2.1), then the observation (§2.5, §2.6).
537#[must_use]
538pub fn judge(h: &Horizon, o: &Observation) -> Judged {
539    use Reason as R;
540    use Verdict as V;
541    match h {
542        Horizon::Undeclared => return Judged::new(V::NotAsked, R::NoHorizon),
543        Horizon::Ignored => return Judged::new(V::NotAsked, R::Kind),
544        _ => {}
545    }
546    if matches!(o, Observation::Archived) {
547        return Judged::new(V::NotAsked, R::LastKnown);
548    }
549    let ttl = match h {
550        Horizon::Invalid(_) => return Judged::new(V::Unobservable, R::NotAHorizon),
551        Horizon::Never => None,
552        Horizon::Within(t) => Some(*t),
553        Horizon::Undeclared | Horizon::Ignored => unreachable!("returned above"),
554    };
555    match (*o, ttl) {
556        (Observation::Archived, _) => unreachable!("returned above"),
557        // §2.5.
558        (
559            Observation::Subscribed {
560                last: Some(Last::Delete(_)),
561                ..
562            },
563            _,
564        ) => Judged::new(V::NotAsked, R::Deleted),
565        (Observation::Subscribed { .. }, None) => Judged::new(V::Fresh, R::NeverStale),
566        (
567            Observation::Subscribed {
568                last,
569                listened,
570                complete,
571            },
572            Some(ttl),
573        ) => match last {
574            Some(Last::Put(a)) if a <= ttl => Judged::new(V::Fresh, R::WithinHorizon),
575            _ if !complete => Judged::new(V::Unobservable, R::Incomplete),
576            Some(_) => Judged::new(V::Stale, R::BeyondHorizon),
577            None if listened > ttl => Judged::new(V::Stale, R::NoDelivery),
578            None => Judged::new(V::Unobservable, R::ListenedTooShort),
579        },
580        // §2.6.
581        (Observation::Got { reply: None, .. }, _) => Judged::new(V::Unobservable, R::Silent),
582        (
583            Observation::Got {
584                reply: Some(Reply::Delete),
585                ..
586            },
587            _,
588        ) => Judged::new(V::NotAsked, R::Deleted),
589        (Observation::Got { .. }, None) => Judged::new(V::Fresh, R::NeverStale),
590        (
591            Observation::Got {
592                reply: Some(Reply::Put { stamp_age }),
593                clock,
594            },
595            Some(ttl),
596        ) => {
597            let Some(age) = stamp_age else {
598                return Judged::new(V::Unobservable, R::NoStamp);
599            };
600            let ClockTrust::Trusted { delta } = clock else {
601                return Judged::new(V::Unobservable, R::ClockUntrusted);
602            };
603            let (a, t, d) = (age.0, ttl.as_nanos() as i128, delta.as_nanos() as i128);
604            if a < -d {
605                Judged::new(V::Unobservable, R::ClockDisagrees)
606            } else if a + d <= t {
607                Judged::new(V::Fresh, R::WithinHorizon)
608            } else if a - d > t {
609                Judged::new(V::Stale, R::BeyondHorizon)
610            } else {
611                Judged::new(V::Unobservable, R::NearHorizon)
612            }
613        }
614    }
615}
616
617/// Combines the verdicts of several observations of one member (§2.7):
618/// fresh when any is fresh, else stale when any is, else unobservable when
619/// any is, else not asked. Among equal verdicts the first one's reason
620/// stands. No observation at all is unobservable.
621#[must_use]
622pub fn combine(judged: impl IntoIterator<Item = Judged>) -> Judged {
623    let rank = |v: Verdict| match v {
624        Verdict::Fresh => 0,
625        Verdict::Stale => 1,
626        Verdict::Unobservable => 2,
627        Verdict::NotAsked => 3,
628    };
629    judged
630        .into_iter()
631        .fold(None, |best: Option<Judged>, j| match best {
632            Some(b) if rank(b.verdict) <= rank(j.verdict) => Some(b),
633            _ => Some(j),
634        })
635        .unwrap_or(Judged::new(Verdict::Unobservable, Reason::NoObservation))
636}
637
638/// [`judge`] each observation, then [`combine`] them. With no observation,
639/// §2.7's steps that need none still answer (0.2): no horizon is not
640/// asked, an event or operation is not this profile's, a value that is no
641/// horizon is unobservable; only a member with a horizon is unobservable
642/// for want of an observation.
643#[must_use]
644pub fn judge_all(h: &Horizon, observations: &[Observation]) -> Judged {
645    if observations.is_empty() {
646        return match h {
647            Horizon::Undeclared => Judged::new(Verdict::NotAsked, Reason::NoHorizon),
648            Horizon::Ignored => Judged::new(Verdict::NotAsked, Reason::Kind),
649            Horizon::Invalid(_) => Judged::new(Verdict::Unobservable, Reason::NotAHorizon),
650            Horizon::Never | Horizon::Within(_) => {
651                Judged::new(Verdict::Unobservable, Reason::NoObservation)
652            }
653        };
654    }
655    combine(observations.iter().map(|o| judge(h, o)))
656}
657
658// --- #978's F2: a reader's view, as heartbeats confirm it ----------------------
659
660/// An instant on a reader's monotonic clock, as a [`View`] keeps it: a
661/// delivery's or a heartbeat's arrival.
662pub trait Arrival: Copy + Ord {
663    /// The time from `earlier` to this instant, zero when `earlier` is
664    /// later.
665    fn since(self, earlier: Self) -> Duration;
666}
667
668impl Arrival for std::time::Instant {
669    fn since(self, earlier: Self) -> Duration {
670        self.saturating_duration_since(earlier)
671    }
672}
673
674impl Arrival for crate::timing::Mono {
675    fn since(self, earlier: Self) -> Duration {
676        self.saturating_since(earlier)
677    }
678}
679
680/// One member as a [`View`] holds it.
681#[derive(Debug, Clone, Copy, PartialEq, Eq)]
682struct Held<T> {
683    collection: usize,
684    /// The last mutation's in-band stamp; `None` for a put that carried
685    /// none, which no digest can count, and for a delete.
686    stamp: Option<Stamp>,
687    deleted: bool,
688    /// The last mutation's arrival.
689    at: T,
690    /// The last heartbeat that vouched for it, since its last mutation.
691    confirmed: Option<T>,
692}
693
694/// What one section of a heartbeat did to the [`View`] (#978's design
695/// §1.5).
696#[derive(Debug, Clone, PartialEq, Eq)]
697pub enum SectionRead {
698    /// The view does not follow the collection: nothing read.
699    NotFollowed,
700    /// Its map bit is 0: nothing confirmed there.
701    Absent,
702    /// The digest, or the live count, is not the view's: nothing
703    /// confirmed in the collection.
704    Diverged,
705    /// The digest is the view's: each member vouched for is confirmed at
706    /// the heartbeat's arrival, these keys in key order.
707    Confirmed(Vec<String>),
708}
709
710impl SectionRead {
711    /// `not_followed`, `absent`, `diverged` or `confirmed`.
712    #[must_use]
713    pub fn as_str(&self) -> &'static str {
714        match self {
715            Self::NotFollowed => "not_followed",
716            Self::Absent => "absent",
717            Self::Diverged => "diverged",
718            Self::Confirmed(_) => "confirmed",
719        }
720    }
721}
722
723/// What a heartbeat did to the [`View`].
724#[derive(Debug, Clone, PartialEq, Eq)]
725pub enum Applied {
726    /// CH's tag is not the revision the view holds: nothing confirmed.
727    Revision,
728    /// The body was refused (core §7.5): nothing confirmed.
729    Refused(crate::heartbeat::BodyRefusal),
730    /// Its key's seq is not after the last heartbeat's, within one run:
731    /// nothing confirmed, nothing counted.
732    Older,
733    /// Read, each collection's section in map order. `gap` says the key's
734    /// seqs skipped since the last heartbeat: one or more were lost.
735    Read {
736        gap: bool,
737        sections: Vec<SectionRead>,
738    },
739}
740
741/// A reader's view of one owner's state for one interface, as its
742/// deliveries, its reads and that owner's heartbeats make it (core §7.5's
743/// heartbeat; #978's F2). No rule adopts the heartbeat yet, so nothing
744/// here changes a [`judge`]: a heartbeat that confirms a member is a
745/// confirmation of it, as a put is (§2.5), and [`View::observation`] ages
746/// the member from the later of the two.
747///
748/// - **The members** are each collection's that the reader heard: a put
749///   with its in-band stamp, a delete, or a read's answer
750///   ([`View::replace`]). A put older than the one held, within one run,
751///   is not taken.
752/// - **A heartbeat** ([`View::apply`]) confirms, in each collection the
753///   view follows ([`View::follow`]), each member vouched for, when the
754///   section's digest is the view's and its live count is too. A reader
755///   follows only a collection it hears whole: one whose template it
756///   subscribes with no parameter bound.
757/// - **A divergence** confirms nothing in its collection. After two in a
758///   row the collection is due a read ([`View::reread_due`]), whose answer
759///   replaces what the view holds.
760/// - **A gap** in the heartbeat key's seqs is a heartbeat lost: the
761///   view's members are incomplete until one arrives in sequence.
762#[derive(Debug, Clone)]
763pub struct View<T> {
764    layout: crate::heartbeat::Layout,
765    follows: Vec<bool>,
766    members: BTreeMap<String, Held<T>>,
767    diverged: Vec<u32>,
768    last: Option<Stamp>,
769    gap: bool,
770    time: Option<crate::heartbeat::Time>,
771    heartbeats: u64,
772}
773
774impl<T: Arrival> View<T> {
775    /// An empty view of a revision's collections, following none.
776    #[must_use]
777    pub fn new(layout: crate::heartbeat::Layout) -> Self {
778        let n = layout.collections.len();
779        Self {
780            layout,
781            follows: vec![false; n],
782            members: BTreeMap::new(),
783            diverged: vec![0; n],
784            last: None,
785            gap: false,
786            time: None,
787            heartbeats: 0,
788        }
789    }
790
791    /// The revision's layout.
792    #[must_use]
793    pub fn layout(&self) -> &crate::heartbeat::Layout {
794        &self.layout
795    }
796
797    /// Follows the collection at `index`; `false` when there is none.
798    pub fn follow(&mut self, index: usize) -> bool {
799        match self.follows.get_mut(index) {
800            Some(f) => {
801                *f = true;
802                true
803            }
804            None => false,
805        }
806    }
807
808    /// Follows the collection named `<kind token>/<template>`; `false`
809    /// when it is none.
810    pub fn follow_resource(&mut self, resource: &str) -> bool {
811        self.layout
812            .index_of(resource)
813            .is_some_and(|i| self.follow(i))
814    }
815
816    /// Whether it follows any collection.
817    #[must_use]
818    pub fn follows_any(&self) -> bool {
819        self.follows.iter().any(|f| *f)
820    }
821
822    /// A put of `key` heard at `at`, with its in-band stamp (`None` when it
823    /// carried none). A key of no collection is not held, and a put older
824    /// than the one held within one run is not taken.
825    pub fn put(&mut self, key: &str, stamp: Option<Stamp>, at: T) {
826        self.mutation(key, stamp, false, at);
827    }
828
829    /// A delete of `key` heard at `at`, with its in-band stamp where its
830    /// attachment carried one.
831    pub fn delete(&mut self, key: &str, stamp: Option<Stamp>, at: T) {
832        self.mutation(key, stamp, true, at);
833    }
834
835    fn mutation(&mut self, key: &str, stamp: Option<Stamp>, deleted: bool, at: T) {
836        let Some(k) = crate::heartbeat::base_relative(key) else {
837            return;
838        };
839        let Some(collection) = self.layout.collection_of(k) else {
840            return;
841        };
842        if let (Some(h), Some(s)) = (self.members.get(k).and_then(|h| h.stamp), stamp)
843            && h.run == s.run
844            && s.seq <= h.seq
845        {
846            return;
847        }
848        self.members.insert(
849            k.to_owned(),
850            Held {
851                collection,
852                stamp,
853                deleted,
854                at,
855                confirmed: None,
856            },
857        );
858    }
859
860    /// A complete read of the collection at `index` (S4's answer, or a
861    /// snapshot once #977 lands), at `at`: its live members replace the
862    /// view's, a member it left out leaving the view, and the collection
863    /// is no longer due a read. A put heard after the read was asked is
864    /// the caller's to apply again after it (core §4.2).
865    pub fn replace<'k>(
866        &mut self,
867        index: usize,
868        live: impl IntoIterator<Item = (&'k str, Option<Stamp>)>,
869        at: T,
870    ) {
871        self.members.retain(|_, h| h.collection != index);
872        for (key, stamp) in live {
873            let Some(k) = crate::heartbeat::base_relative(key) else {
874                continue;
875            };
876            if self.layout.collection_of(k) == Some(index) {
877                self.members.insert(
878                    k.to_owned(),
879                    Held {
880                        collection: index,
881                        stamp,
882                        deleted: false,
883                        at,
884                        confirmed: None,
885                    },
886                );
887            }
888        }
889        if let Some(d) = self.diverged.get_mut(index) {
890            *d = 0;
891        }
892    }
893
894    /// A re-read of the collection at `index` (`freshness.v2` §2.5): its
895    /// answer, asked at `asked` and arrived at `at`, merged with what the
896    /// view heard of the collection from `asked` on, as core §4.2 merges a
897    /// late joiner's seed. The answer replaces the collection
898    /// ([`View::replace`]); then each member heard live since `asked` is
899    /// kept where the answer has none of it, or holds a lower seq of its
900    /// run. Across two runs the answer's stands, as core §4.3's consumer
901    /// rule accepts another run.
902    pub fn reread<'k>(
903        &mut self,
904        index: usize,
905        live: impl IntoIterator<Item = (&'k str, Option<Stamp>)>,
906        asked: T,
907        at: T,
908    ) {
909        let heard: Vec<(String, Held<T>)> = self
910            .members
911            .iter()
912            .filter(|(_, h)| h.collection == index && h.at >= asked)
913            .map(|(k, h)| (k.clone(), *h))
914            .collect();
915        self.replace(index, live, at);
916        for (k, h) in heard {
917            let keep = match self.members.get(&k) {
918                None => true,
919                Some(answered) => match (h.stamp, answered.stamp) {
920                    (Some(mine), Some(theirs)) => mine.run == theirs.run && mine.seq > theirs.seq,
921                    _ => false,
922                },
923            };
924            if keep {
925                self.members.insert(k, h);
926            }
927        }
928    }
929
930    /// The live members of a collection the view holds, in key order.
931    fn live(&self, index: usize) -> impl Iterator<Item = (&String, &Held<T>)> {
932        self.members
933            .iter()
934            .filter(move |(_, h)| h.collection == index && !h.deleted)
935    }
936
937    /// The view's digest of a collection: `None` while it holds a live
938    /// member whose put carried no in-band stamp, which no digest counts.
939    #[must_use]
940    pub fn digest(&self, index: usize) -> Option<crate::heartbeat::Digest> {
941        let mut d = crate::heartbeat::Digest::EMPTY;
942        for (k, h) in self.live(index) {
943            d.toggle(k, h.stamp?);
944        }
945        Some(d)
946    }
947
948    /// A heartbeat heard at `at`: CH's tag, its stamp and its body. See
949    /// [`View`]'s doc for what it confirms.
950    pub fn apply(&mut self, tag: crate::wire::Tag, stamp: Stamp, body: &[u8], at: T) -> Applied {
951        use crate::heartbeat::{Heartbeat, Members};
952        if tag != self.layout.tag {
953            return Applied::Revision;
954        }
955        let hb = match Heartbeat::parse(body, &self.layout) {
956            Ok(hb) => hb,
957            Err(r) => return Applied::Refused(r),
958        };
959        let gap = match self.last {
960            Some(l) if l.run == stamp.run => {
961                match crate::seed::Order::Serial.seqs(l.seq, stamp.seq) {
962                    Some(std::cmp::Ordering::Greater) => {
963                        stamp.seq.get().wrapping_sub(l.seq.get()) & crate::wire::Seq::MAX.get() != 1
964                    }
965                    _ => return Applied::Older,
966                }
967            }
968            _ => false,
969        };
970        self.last = Some(stamp);
971        self.gap = gap;
972        self.time = Some(hb.time);
973        self.heartbeats += 1;
974        let mut sections = Vec::with_capacity(hb.sections.len());
975        for (i, section) in hb.sections.iter().enumerate() {
976            if !self.follows[i] {
977                sections.push(SectionRead::NotFollowed);
978                continue;
979            }
980            let Some(s) = section else {
981                self.diverged[i] = 0;
982                sections.push(SectionRead::Absent);
983                continue;
984            };
985            let keys: Vec<String> = self.live(i).map(|(k, _)| k.clone()).collect();
986            let same_count = match &s.members {
987                Members::One { .. } => keys.len() <= 1,
988                m => m.live() == Some(keys.len() as u64),
989            };
990            if self.digest(i) != Some(s.digest) || !same_count {
991                self.diverged[i] = self.diverged[i].saturating_add(1);
992                sections.push(SectionRead::Diverged);
993                continue;
994            }
995            self.diverged[i] = 0;
996            let vouched: Vec<String> = s
997                .members
998                .vouched()
999                .into_iter()
1000                .filter_map(|r| keys.get(usize::try_from(r).ok()?).cloned())
1001                .collect();
1002            for k in &vouched {
1003                if let Some(h) = self.members.get_mut(k) {
1004                    h.confirmed = Some(at);
1005                }
1006            }
1007            sections.push(SectionRead::Confirmed(vouched));
1008        }
1009        Applied::Read { gap, sections }
1010    }
1011
1012    /// A GET's snapshot vouched for `key`'s live value at `at` (v2 §2.6,
1013    /// text 0.7; core §7.5's confirmation): kept as a heartbeat's would be,
1014    /// when it is later than what the view held. A deleted member, or one
1015    /// the view does not hold, is left as it is.
1016    pub fn confirm(&mut self, key: &str, at: T) {
1017        let Some(k) = crate::heartbeat::base_relative(key) else {
1018            return;
1019        };
1020        if let Some(h) = self.members.get_mut(k)
1021            && !h.deleted
1022            && h.confirmed.is_none_or(|c| c < at)
1023        {
1024            h.confirmed = Some(at);
1025        }
1026    }
1027
1028    /// The last heartbeat that vouched for `key` since its last mutation.
1029    #[must_use]
1030    pub fn confirmed(&self, key: &str) -> Option<T> {
1031        let k = crate::heartbeat::base_relative(key)?;
1032        self.members.get(k).and_then(|h| h.confirmed)
1033    }
1034
1035    /// The collections due a read: two heartbeats in a row diverged there.
1036    #[must_use]
1037    pub fn reread_due(&self) -> Vec<usize> {
1038        (0..self.diverged.len())
1039            .filter(|i| self.follows[*i] && self.diverged[*i] >= 2)
1040            .collect()
1041    }
1042
1043    /// Whether the last heartbeat came after a gap in its key's seqs.
1044    #[must_use]
1045    pub fn gap(&self) -> bool {
1046        self.gap
1047    }
1048
1049    /// The owner's time in the last heartbeat applied.
1050    #[must_use]
1051    pub fn owner_time(&self) -> Option<crate::heartbeat::Time> {
1052        self.time
1053    }
1054
1055    /// The last heartbeat applied: its stamp.
1056    #[must_use]
1057    pub fn last_heartbeat(&self) -> Option<Stamp> {
1058        self.last
1059    }
1060
1061    /// How many heartbeats it applied.
1062    #[must_use]
1063    pub fn heartbeats(&self) -> u64 {
1064        self.heartbeats
1065    }
1066
1067    /// `key`'s last confirmation at `now` (§2.5): the later of its last
1068    /// mutation and the last heartbeat that vouched for it, as a [`Last`];
1069    /// `None` for a member the view does not hold.
1070    #[must_use]
1071    pub fn last(&self, key: &str, now: T) -> Option<Last> {
1072        let k = crate::heartbeat::base_relative(key)?;
1073        let h = self.members.get(k)?;
1074        Some(if h.deleted {
1075            Last::Delete(now.since(h.at))
1076        } else {
1077            Last::Put(now.since(h.confirmed.map_or(h.at, |c| c.max(h.at))))
1078        })
1079    }
1080
1081    /// `key` as a subscription's observation at `now` (§2.5), the view
1082    /// standing in for its deliveries: its last confirmation, how long the
1083    /// subscription has `listened`, and complete when the subscription
1084    /// lost nothing (`complete`) and no heartbeat was lost.
1085    #[must_use]
1086    pub fn observation(
1087        &self,
1088        key: &str,
1089        now: T,
1090        listened: Duration,
1091        complete: bool,
1092    ) -> Observation {
1093        Observation::Subscribed {
1094            last: self.last(key, now),
1095            listened,
1096            complete: complete && !self.gap,
1097        }
1098    }
1099}
1100
1101/// A subscription's last delivery of a member and, where a [`View`]
1102/// holds it, the last heartbeat that vouched for it: the later is its
1103/// last confirmation (§2.5). `delivered` is the subscription's own
1104/// [`Last`]; a delete stays a delete. A member never delivered that a
1105/// heartbeat confirmed, one a late joiner's read seeded (`freshness.v2`
1106/// §2.5), is confirmed then.
1107#[must_use]
1108pub fn confirmed_last(delivered: Option<Last>, heartbeat: Option<Duration>) -> Option<Last> {
1109    match (delivered, heartbeat) {
1110        (Some(Last::Put(a)), Some(h)) => Some(Last::Put(a.min(h))),
1111        (None, Some(h)) => Some(Last::Put(h)),
1112        (d, _) => d,
1113    }
1114}
1115
1116#[cfg(test)]
1117mod tests {
1118    use super::*;
1119    use serde_json::json;
1120
1121    fn ann(v: Value) -> BTreeMap<String, Value> {
1122        BTreeMap::from([(TTL_S.to_owned(), v)])
1123    }
1124
1125    #[test]
1126    fn the_horizon_is_a_whole_number_of_seconds() {
1127        let h = |v: Value| horizon(Kind::State, &ann(v));
1128        assert_eq!(h(json!(60)), Horizon::Within(Duration::from_secs(60)));
1129        assert_eq!(h(json!(60.0)), Horizon::Within(Duration::from_secs(60)));
1130        assert_eq!(h(json!(-0.0)), Horizon::Never);
1131        assert_eq!(h(json!(0)), Horizon::Never);
1132        assert!(matches!(h(json!(1.5)), Horizon::Invalid(_)));
1133        assert!(matches!(h(json!(-1)), Horizon::Invalid(_)));
1134        assert!(matches!(h(json!(MAX_TTL_S + 1)), Horizon::Invalid(_)));
1135        assert_eq!(
1136            horizon(Kind::Event, &ann(json!("x"))),
1137            Horizon::Ignored,
1138            "the kind first"
1139        );
1140        assert_eq!(horizon(Kind::State, &BTreeMap::new()), Horizon::Undeclared);
1141        assert_eq!(
1142            h(json!(61)).refresh_bound(),
1143            Some(Duration::from_millis(30_500))
1144        );
1145    }
1146
1147    #[test]
1148    fn a_trusted_reply_is_judged_in_the_band() {
1149        let h = Horizon::Within(Duration::from_secs(2));
1150        let got = |s: f64| Observation::Got {
1151            reply: Some(Reply::Put {
1152                stamp_age: Some(StampAge::from_secs_f64(s)),
1153            }),
1154            clock: ClockTrust::Trusted {
1155                delta: DEFAULT_DELTA,
1156            },
1157        };
1158        let v = |s: f64| judge(&h, &got(s)).reason;
1159        assert_eq!(v(1.5), Reason::WithinHorizon);
1160        assert_eq!(v(1.6), Reason::NearHorizon);
1161        assert_eq!(v(2.5), Reason::NearHorizon);
1162        assert_eq!(v(2.6), Reason::BeyondHorizon);
1163        assert_eq!(v(-0.5), Reason::WithinHorizon);
1164        assert_eq!(v(-0.6), Reason::ClockDisagrees);
1165    }
1166
1167    #[test]
1168    fn fresh_wins_then_stale_then_unobservable() {
1169        let j = |v, r| Judged::new(v, r);
1170        assert_eq!(
1171            combine([
1172                j(Verdict::Stale, Reason::NoDelivery),
1173                j(Verdict::Fresh, Reason::WithinHorizon)
1174            ])
1175            .verdict,
1176            Verdict::Fresh
1177        );
1178        assert_eq!(
1179            combine([
1180                j(Verdict::Unobservable, Reason::ClockUntrusted),
1181                j(Verdict::Stale, Reason::NoDelivery)
1182            ])
1183            .reason,
1184            Reason::NoDelivery
1185        );
1186        assert_eq!(combine([]).reason, Reason::NoObservation);
1187    }
1188
1189    mod view {
1190        use super::super::*;
1191        use crate::contract::load_str;
1192        use crate::heartbeat::{Digest, Heartbeat, Layout, Members, Section, Time};
1193        use crate::timing::Mono;
1194        use crate::wire::{Run, Seq, Tag};
1195
1196        const HB: &str = r#"
1197[interface]
1198name = "hb"
1199major = 1
1200minor = 0
1201uses = ["freshness.v1"]
1202[resources.link]
1203kind = "state"
1204type = { raw = "text/plain" }
1205annotations = { "freshness.ttl_s" = 2 }
1206[resources."peer/{peer}"]
1207kind = "state"
1208type = { raw = "text/plain" }
1209params = { peer = "string" }
1210cardinality = 5
1211annotations = { "freshness.ttl_s" = 2 }
1212"#;
1213        const LINK: &str = "zk2/lab/n1/hb.v1/state/link";
1214        const A: &str = "zk2/lab/n1/hb.v1/state/peer/a";
1215        const B: &str = "zk2/lab/n1/hb.v1/state/peer/b";
1216
1217        fn layout() -> Layout {
1218            let c = load_str(HB, std::path::Path::new("."), None)
1219                .contract
1220                .unwrap();
1221            Layout::of(&c)
1222        }
1223        fn st(run: u16, seq: u32) -> Stamp {
1224            Stamp {
1225                run: Run::U16(run),
1226                seq: Seq::new(seq).unwrap(),
1227            }
1228        }
1229        fn ms(n: u64) -> Mono {
1230            Mono::after(Duration::from_millis(n))
1231        }
1232        /// A heartbeat over (link, peer/*), its sections given.
1233        fn body(l: &Layout, link: Option<Section>, peers: Option<Section>) -> Vec<u8> {
1234            Heartbeat {
1235                time: Time::Unknown,
1236                sections: vec![link, peers],
1237            }
1238            .write(l)
1239            .unwrap()
1240        }
1241        fn view() -> View<Mono> {
1242            let mut v = View::new(layout());
1243            assert!(v.follow_resource("state/link"));
1244            assert!(v.follow_resource("state/peer/{peer}"));
1245            assert!(!v.follow_resource("state/nothing"));
1246            v
1247        }
1248
1249        #[test]
1250        fn a_heartbeat_whose_digest_is_the_views_confirms_what_it_vouches_for() {
1251            let l = layout();
1252            let mut v = view();
1253            v.put(LINK, Some(st(1, 1)), ms(0));
1254            v.put(A, Some(st(1, 2)), ms(0));
1255            v.put(B, Some(st(1, 3)), ms(0));
1256            let link = Section {
1257                digest: Digest::of([(LINK, st(1, 1))]),
1258                members: Members::One { vouched: true },
1259            };
1260            let peers = Section {
1261                digest: Digest::of([(A, st(1, 2)), (B, st(1, 3))]),
1262                members: Members::templated(2, [1]),
1263            };
1264            let got = v.apply(
1265                l.tag,
1266                st(9, 0),
1267                &body(&l, Some(link), Some(peers)),
1268                ms(1500),
1269            );
1270            assert_eq!(
1271                got,
1272                Applied::Read {
1273                    gap: false,
1274                    sections: vec![
1275                        SectionRead::Confirmed(vec![LINK.into()]),
1276                        SectionRead::Confirmed(vec![B.into()]),
1277                    ]
1278                }
1279            );
1280            assert_eq!(v.confirmed(B), Some(ms(1500)));
1281            assert_eq!(v.confirmed(A), None, "not vouched for");
1282            // At 3 s: the link put at 0 is 3 s old, confirmed 1.5 s ago.
1283            let h = Horizon::Within(Duration::from_secs(2));
1284            let j = |k: &str| {
1285                judge(
1286                    &h,
1287                    &v.observation(k, ms(3000), Duration::from_secs(3), true),
1288                )
1289            };
1290            assert_eq!(j(LINK).verdict, Verdict::Fresh);
1291            assert_eq!(j(B).verdict, Verdict::Fresh);
1292            assert_eq!(
1293                j(A).verdict,
1294                Verdict::Stale,
1295                "a cleared bit is no confirmation"
1296            );
1297            // A namespace in front reads as the base-relative key.
1298            assert_eq!(v.confirmed(&format!("prod/{LINK}")), Some(ms(1500)));
1299        }
1300
1301        #[test]
1302        fn a_missed_change_diverges_and_two_in_a_row_are_due_a_read() {
1303            let l = layout();
1304            let mut v = view();
1305            v.put(A, Some(st(1, 2)), ms(0));
1306            // The owner holds a's seq 5 and b: the view missed both.
1307            let owner = Digest::of([(A, st(1, 5)), (B, st(1, 6))]);
1308            let sec = || Section {
1309                digest: owner,
1310                members: Members::templated(2, [0, 1]),
1311            };
1312            for (seq, due) in [(0, false), (1, true)] {
1313                let got = v.apply(l.tag, st(9, seq), &body(&l, None, Some(sec())), ms(1000));
1314                assert_eq!(
1315                    got,
1316                    Applied::Read {
1317                        gap: false,
1318                        sections: vec![SectionRead::Absent, SectionRead::Diverged]
1319                    }
1320                );
1321                assert_eq!(v.reread_due() == vec![1], due);
1322            }
1323            assert_eq!(v.confirmed(A), None);
1324            // The read's answer replaces the view, and the next heartbeat confirms.
1325            v.replace(1, [(A, Some(st(1, 5))), (B, Some(st(1, 6)))], ms(1100));
1326            assert!(v.reread_due().is_empty());
1327            let got = v.apply(l.tag, st(9, 2), &body(&l, None, Some(sec())), ms(1200));
1328            assert_eq!(
1329                got,
1330                Applied::Read {
1331                    gap: false,
1332                    sections: vec![
1333                        SectionRead::Absent,
1334                        SectionRead::Confirmed(vec![A.into(), B.into()])
1335                    ]
1336                }
1337            );
1338        }
1339
1340        #[test]
1341        fn a_deleted_member_leaves_the_digest_and_a_stale_put_is_not_taken() {
1342            let mut v = view();
1343            v.put(A, Some(st(1, 4)), ms(0));
1344            v.put(A, Some(st(1, 3)), ms(10));
1345            assert_eq!(v.digest(1), Some(Digest::of([(A, st(1, 4))])));
1346            v.delete(A, Some(st(1, 5)), ms(20));
1347            assert_eq!(v.digest(1), Some(Digest::EMPTY));
1348            assert_eq!(
1349                v.last(A, ms(30)),
1350                Some(Last::Delete(Duration::from_millis(10)))
1351            );
1352            // Another run's put is taken whatever its seq.
1353            v.put(A, Some(st(2, 0)), ms(40));
1354            assert_eq!(v.digest(1), Some(Digest::of([(A, st(2, 0))])));
1355            // A put with no envelope leaves the collection with no digest.
1356            v.put(B, None, ms(50));
1357            assert_eq!(v.digest(1), None);
1358            // A key of no collection is not held.
1359            v.put("zk2/lab/n1/hb.v1/state/other", Some(st(1, 1)), ms(60));
1360            assert_eq!(v.last("zk2/lab/n1/hb.v1/state/other", ms(70)), None);
1361        }
1362
1363        #[test]
1364        fn a_gap_is_a_heartbeat_lost_and_the_tag_and_the_order_guard() {
1365            let l = layout();
1366            let mut v = view();
1367            v.put(LINK, Some(st(1, 1)), ms(0));
1368            let link = || {
1369                Some(Section {
1370                    digest: Digest::of([(LINK, st(1, 1))]),
1371                    members: Members::One { vouched: true },
1372                })
1373            };
1374            let b = body(&l, link(), None);
1375            let other = Tag::new((l.tag.get() + 1) % 16).unwrap();
1376            assert_eq!(v.apply(other, st(9, 0), &b, ms(100)), Applied::Revision);
1377            assert!(matches!(
1378                v.apply(l.tag, st(9, 0), &b, ms(100)),
1379                Applied::Read { gap: false, .. }
1380            ));
1381            assert!(matches!(
1382                v.apply(l.tag, st(9, 3), &b, ms(200)),
1383                Applied::Read { gap: true, .. }
1384            ));
1385            assert!(v.gap());
1386            let o = v.observation(LINK, ms(5000), Duration::from_secs(5), true);
1387            assert_eq!(
1388                judge(&Horizon::Within(Duration::from_secs(2)), &o).reason,
1389                Reason::Incomplete
1390            );
1391            assert_eq!(v.apply(l.tag, st(9, 3), &b, ms(300)), Applied::Older);
1392            assert_eq!(v.apply(l.tag, st(9, 1), &b, ms(300)), Applied::Older);
1393            assert!(matches!(
1394                v.apply(l.tag, st(9, 4), &b, ms(400)),
1395                Applied::Read { gap: false, .. }
1396            ));
1397            assert!(!v.gap());
1398            // A new run of the key is no gap, and its seq starts anew.
1399            assert!(matches!(
1400                v.apply(l.tag, st(10, 0), &b, ms(500)),
1401                Applied::Read { gap: false, .. }
1402            ));
1403            // A body cut short is refused, and counts as no heartbeat.
1404            assert!(matches!(
1405                v.apply(l.tag, st(10, 1), &b[..2], ms(600)),
1406                Applied::Refused(_)
1407            ));
1408            assert_eq!(v.heartbeats(), 4);
1409        }
1410    }
1411
1412    #[test]
1413    fn a_measured_offset_trusts_within_the_delta_either_way() {
1414        let d = DEFAULT_DELTA;
1415        assert!(matches!(
1416            ClockTrust::measured(StampAge::ahead(d), d),
1417            ClockTrust::Trusted { .. }
1418        ));
1419        assert_eq!(
1420            ClockTrust::measured(StampAge::behind(Duration::from_millis(501)), d),
1421            ClockTrust::Untrusted
1422        );
1423    }
1424}