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    /// In a group of an owner heartbeat, a followed collection that is not
701    /// of the key's class: not read, whatever its map bit says (v2 §2.5).
702    /// A heartbeat's own section is never this.
703    OtherClass,
704    /// Its map bit is 0: nothing confirmed there.
705    Absent,
706    /// The digest, or the live count, is not the view's: nothing
707    /// confirmed in the collection.
708    Diverged,
709    /// The digest is the view's: each member vouched for is confirmed at
710    /// the heartbeat's arrival, these keys in key order.
711    Confirmed(Vec<String>),
712}
713
714impl SectionRead {
715    /// `not_followed`, `other_class`, `absent`, `diverged` or `confirmed`.
716    #[must_use]
717    pub fn as_str(&self) -> &'static str {
718        match self {
719            Self::NotFollowed => "not_followed",
720            Self::OtherClass => "other_class",
721            Self::Absent => "absent",
722            Self::Diverged => "diverged",
723            Self::Confirmed(_) => "confirmed",
724        }
725    }
726}
727
728/// What a heartbeat did to the [`View`].
729#[derive(Debug, Clone, PartialEq, Eq)]
730pub enum Applied {
731    /// CH's tag is not the revision the view holds: nothing confirmed.
732    Revision,
733    /// The body was refused (core §7.5): nothing confirmed.
734    Refused(crate::heartbeat::BodyRefusal),
735    /// Its key's seq is not after the last heartbeat's, within one run:
736    /// nothing confirmed, nothing counted.
737    Older,
738    /// Read, each collection's section in map order. `gap` says the key's
739    /// seqs skipped since the last heartbeat: one or more were lost.
740    Read {
741        gap: bool,
742        sections: Vec<SectionRead>,
743    },
744}
745
746/// One heartbeat key's sequence, as a reader counts it (v2 §2.5): the
747/// stamp of the last heartbeat read on the key, and whether that one
748/// followed a lost one. A heartbeat key has one, and so has each owner
749/// heartbeat key, whatever its groups cover: older and lost are the
750/// key's, never an interface's.
751#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
752pub struct Sequence {
753    last: Option<Stamp>,
754    gap: bool,
755}
756
757/// What [`Sequence::read`] says of a heartbeat that is not older.
758#[derive(Debug, Clone, Copy, PartialEq, Eq)]
759pub struct Sequenced {
760    /// Within one run, its seq is not the last read one's plus 1: one or
761    /// more were lost.
762    pub gap: bool,
763    /// It is of another run than the last read one: the sequence starts
764    /// again. `false` for the first one read.
765    pub run: bool,
766}
767
768impl Sequence {
769    /// A heartbeat about to be read on the key, one core §7.5 did not
770    /// refuse: `None` when, within one run, its seq is not after the last
771    /// read one's by core §4.3's serial order (`older`), which moves
772    /// nothing; else the sequence moves to it.
773    pub fn read(&mut self, stamp: Stamp) -> Option<Sequenced> {
774        let read = match self.last {
775            Some(l) if l.run == stamp.run => {
776                match crate::seed::Order::Serial.seqs(l.seq, stamp.seq) {
777                    Some(std::cmp::Ordering::Greater) => Sequenced {
778                        gap: stamp.seq.get().wrapping_sub(l.seq.get())
779                            & crate::wire::Seq::MAX.get()
780                            != 1,
781                        run: false,
782                    },
783                    _ => return None,
784                }
785            }
786            Some(_) => Sequenced {
787                gap: false,
788                run: true,
789            },
790            None => Sequenced {
791                gap: false,
792                run: false,
793            },
794        };
795        self.last = Some(stamp);
796        self.gap = read.gap;
797        Some(read)
798    }
799
800    /// The last heartbeat read on the key: its stamp.
801    #[must_use]
802    pub fn last(&self) -> Option<Stamp> {
803        self.last
804    }
805
806    /// Whether the last heartbeat read on the key followed a lost one.
807    #[must_use]
808    pub fn gap(&self) -> bool {
809        self.gap
810    }
811}
812
813/// What one group of an owner heartbeat did to a reader's views (v2
814/// §2.5's "An owner heartbeat", step 3), the first of these that answers.
815/// Only [`GroupRead::Read`] counts toward a collection's divergences in a
816/// row.
817#[derive(Debug, Clone, PartialEq, Eq)]
818pub enum GroupRead {
819    /// Core §8.6 refuses its index (`unknown_catalog`, `unknown_index`),
820    /// or, after the two readings below, core §7.5 its sections (`short`,
821    /// `code`, `trailing`): the group confirms nothing.
822    Refused(crate::heartbeat::GroupRefusal),
823    /// The reader follows no collection of the interface its index names:
824    /// skipped.
825    NotFollowed,
826    /// The revision its index names is not the one the reader holds, or
827    /// its tag is not that revision's: the group confirms nothing.
828    Revision,
829    /// Read, each collection of its interface in map order.
830    Read(Vec<SectionRead>),
831}
832
833/// One group of a read owner heartbeat: its index, the interface the
834/// index names where core §8.6 resolved it, and what it did.
835#[derive(Debug, Clone, PartialEq, Eq)]
836pub struct GroupApplied {
837    pub index: u16,
838    pub iface: Option<crate::grammar::IfaceId>,
839    pub read: GroupRead,
840}
841
842/// What an owner heartbeat did to a reader's [`Views`].
843#[derive(Debug, Clone, PartialEq, Eq)]
844pub enum OwnerApplied {
845    /// Core §7.5 refuses it whole, before any group's sections are read:
846    /// nothing confirmed, nothing counted.
847    Refused(crate::heartbeat::OwnerRefusal),
848    /// Its key's seq is not after the last read owner heartbeat's on that
849    /// key, within one run: nothing confirmed, nothing counted.
850    Older,
851    /// Read, each group alone, in order. `gap` says the key's seqs skipped
852    /// since the last one read on it: one or more were lost, for every
853    /// collection the key covers.
854    Read {
855        gap: bool,
856        groups: Vec<GroupApplied>,
857    },
858}
859
860/// A reader's view of one owner's state for one interface, as its
861/// deliveries, its reads and that owner's heartbeats make it (core §7.5's
862/// heartbeat; #978's F2). No rule adopts the heartbeat yet, so nothing
863/// here changes a [`judge`]: a heartbeat that confirms a member is a
864/// confirmation of it, as a put is (§2.5), and [`View::observation`] ages
865/// the member from the later of the two.
866///
867/// - **The members** are each collection's that the reader heard: a put
868///   with its in-band stamp, a delete, or a read's answer
869///   ([`View::replace`]). A put older than the one held, within one run,
870///   is not taken.
871/// - **A heartbeat** ([`View::apply`]) confirms, in each collection the
872///   view follows ([`View::follow`]), each member vouched for, when the
873///   section's digest is the view's and its live count is too. A reader
874///   follows only a collection it hears whole: one whose template it
875///   subscribes with no parameter bound.
876/// - **A divergence** confirms nothing in its collection. After two in a
877///   row the collection is due a read ([`View::reread_due`]), whose answer
878///   replaces what the view holds.
879/// - **A gap** in the heartbeat key's seqs is a heartbeat lost: the
880///   view's members are incomplete until one arrives in sequence.
881#[derive(Debug, Clone)]
882pub struct View<T> {
883    layout: crate::heartbeat::Layout,
884    follows: Vec<bool>,
885    members: BTreeMap<String, Held<T>>,
886    diverged: Vec<u32>,
887    /// Its heartbeat key's sequence. An owner heartbeat key's is
888    /// [`Views`]'s.
889    seq: Sequence,
890    time: Option<crate::heartbeat::Time>,
891    heartbeats: u64,
892}
893
894impl<T: Arrival> View<T> {
895    /// An empty view of a revision's collections, following none.
896    #[must_use]
897    pub fn new(layout: crate::heartbeat::Layout) -> Self {
898        let n = layout.collections.len();
899        Self {
900            layout,
901            follows: vec![false; n],
902            members: BTreeMap::new(),
903            diverged: vec![0; n],
904            seq: Sequence::default(),
905            time: None,
906            heartbeats: 0,
907        }
908    }
909
910    /// The revision's layout.
911    #[must_use]
912    pub fn layout(&self) -> &crate::heartbeat::Layout {
913        &self.layout
914    }
915
916    /// Follows the collection at `index`; `false` when there is none.
917    pub fn follow(&mut self, index: usize) -> bool {
918        match self.follows.get_mut(index) {
919            Some(f) => {
920                *f = true;
921                true
922            }
923            None => false,
924        }
925    }
926
927    /// Follows the collection named `<kind token>/<template>`; `false`
928    /// when it is none.
929    pub fn follow_resource(&mut self, resource: &str) -> bool {
930        self.layout
931            .index_of(resource)
932            .is_some_and(|i| self.follow(i))
933    }
934
935    /// Whether it follows any collection.
936    #[must_use]
937    pub fn follows_any(&self) -> bool {
938        self.follows.iter().any(|f| *f)
939    }
940
941    /// A put of `key` heard at `at`, with its in-band stamp (`None` when it
942    /// carried none). A key of no collection is not held, and a put older
943    /// than the one held within one run is not taken.
944    pub fn put(&mut self, key: &str, stamp: Option<Stamp>, at: T) {
945        self.mutation(key, stamp, false, at);
946    }
947
948    /// A delete of `key` heard at `at`, with its in-band stamp where its
949    /// attachment carried one.
950    pub fn delete(&mut self, key: &str, stamp: Option<Stamp>, at: T) {
951        self.mutation(key, stamp, true, at);
952    }
953
954    fn mutation(&mut self, key: &str, stamp: Option<Stamp>, deleted: bool, at: T) {
955        let Some(k) = crate::heartbeat::base_relative(key) else {
956            return;
957        };
958        let Some(collection) = self.layout.collection_of(k) else {
959            return;
960        };
961        if let (Some(h), Some(s)) = (self.members.get(k).and_then(|h| h.stamp), stamp)
962            && h.run == s.run
963            && s.seq <= h.seq
964        {
965            return;
966        }
967        self.members.insert(
968            k.to_owned(),
969            Held {
970                collection,
971                stamp,
972                deleted,
973                at,
974                confirmed: None,
975            },
976        );
977    }
978
979    /// A complete read of the collection at `index` (S4's answer, or a
980    /// snapshot once #977 lands), at `at`: its live members replace the
981    /// view's, a member it left out leaving the view, and the collection
982    /// is no longer due a read. A put heard after the read was asked is
983    /// the caller's to apply again after it (core §4.2).
984    pub fn replace<'k>(
985        &mut self,
986        index: usize,
987        live: impl IntoIterator<Item = (&'k str, Option<Stamp>)>,
988        at: T,
989    ) {
990        self.members.retain(|_, h| h.collection != index);
991        for (key, stamp) in live {
992            let Some(k) = crate::heartbeat::base_relative(key) else {
993                continue;
994            };
995            if self.layout.collection_of(k) == Some(index) {
996                self.members.insert(
997                    k.to_owned(),
998                    Held {
999                        collection: index,
1000                        stamp,
1001                        deleted: false,
1002                        at,
1003                        confirmed: None,
1004                    },
1005                );
1006            }
1007        }
1008        if let Some(d) = self.diverged.get_mut(index) {
1009            *d = 0;
1010        }
1011    }
1012
1013    /// A re-read of the collection at `index` (`freshness.v2` §2.5): its
1014    /// answer, asked at `asked` and arrived at `at`, merged with what the
1015    /// view heard of the collection from `asked` on, as core §4.2 merges a
1016    /// late joiner's seed. The answer replaces the collection
1017    /// ([`View::replace`]); then each member heard live since `asked` is
1018    /// kept where the answer has none of it, or holds a lower seq of its
1019    /// run. Across two runs the answer's stands, as core §4.3's consumer
1020    /// rule accepts another run.
1021    pub fn reread<'k>(
1022        &mut self,
1023        index: usize,
1024        live: impl IntoIterator<Item = (&'k str, Option<Stamp>)>,
1025        asked: T,
1026        at: T,
1027    ) {
1028        let heard: Vec<(String, Held<T>)> = self
1029            .members
1030            .iter()
1031            .filter(|(_, h)| h.collection == index && h.at >= asked)
1032            .map(|(k, h)| (k.clone(), *h))
1033            .collect();
1034        self.replace(index, live, at);
1035        for (k, h) in heard {
1036            let keep = match self.members.get(&k) {
1037                None => true,
1038                Some(answered) => match (h.stamp, answered.stamp) {
1039                    (Some(mine), Some(theirs)) => mine.run == theirs.run && mine.seq > theirs.seq,
1040                    _ => false,
1041                },
1042            };
1043            if keep {
1044                self.members.insert(k, h);
1045            }
1046        }
1047    }
1048
1049    /// The live members of a collection the view holds, in key order.
1050    fn live(&self, index: usize) -> impl Iterator<Item = (&String, &Held<T>)> {
1051        self.members
1052            .iter()
1053            .filter(move |(_, h)| h.collection == index && !h.deleted)
1054    }
1055
1056    /// The view's digest of a collection: `None` while it holds a live
1057    /// member whose put carried no in-band stamp, which no digest counts.
1058    #[must_use]
1059    pub fn digest(&self, index: usize) -> Option<crate::heartbeat::Digest> {
1060        let mut d = crate::heartbeat::Digest::EMPTY;
1061        for (k, h) in self.live(index) {
1062            d.toggle(k, h.stamp?);
1063        }
1064        Some(d)
1065    }
1066
1067    /// A heartbeat heard at `at`: CH's tag, its stamp and its body. See
1068    /// [`View`]'s doc for what it confirms.
1069    pub fn apply(&mut self, tag: crate::wire::Tag, stamp: Stamp, body: &[u8], at: T) -> Applied {
1070        use crate::heartbeat::Heartbeat;
1071        if tag != self.layout.tag {
1072            return Applied::Revision;
1073        }
1074        let hb = match Heartbeat::parse(body, &self.layout) {
1075            Ok(hb) => hb,
1076            Err(r) => return Applied::Refused(r),
1077        };
1078        let Some(read) = self.seq.read(stamp) else {
1079            return Applied::Older;
1080        };
1081        self.time = Some(hb.time);
1082        self.heartbeats += 1;
1083        let mut sections = Vec::with_capacity(hb.sections.len());
1084        for (i, section) in hb.sections.iter().enumerate() {
1085            sections.push(if self.follows[i] {
1086                self.read_section(i, section.as_ref(), at)
1087            } else {
1088                SectionRead::NotFollowed
1089            });
1090        }
1091        Applied::Read {
1092            gap: read.gap,
1093            sections,
1094        }
1095    }
1096
1097    /// One followed collection's section, read against the view (v2 §2.5,
1098    /// step 4): a map bit of 0 ends a row of divergences, a digest or a
1099    /// live count that is not the view's adds one, and a section in step
1100    /// confirms each member it vouches for at `at`.
1101    fn read_section(
1102        &mut self,
1103        i: usize,
1104        section: Option<&crate::heartbeat::Section>,
1105        at: T,
1106    ) -> SectionRead {
1107        use crate::heartbeat::Members;
1108        let Some(s) = section else {
1109            self.diverged[i] = 0;
1110            return SectionRead::Absent;
1111        };
1112        let keys: Vec<String> = self.live(i).map(|(k, _)| k.clone()).collect();
1113        let same_count = match &s.members {
1114            Members::One { .. } => keys.len() <= 1,
1115            m => m.live() == Some(keys.len() as u64),
1116        };
1117        if self.digest(i) != Some(s.digest) || !same_count {
1118            self.diverged[i] = self.diverged[i].saturating_add(1);
1119            return SectionRead::Diverged;
1120        }
1121        self.diverged[i] = 0;
1122        let vouched: Vec<String> = s
1123            .members
1124            .vouched()
1125            .into_iter()
1126            .filter_map(|r| keys.get(usize::try_from(r).ok()?).cloned())
1127            .collect();
1128        for k in &vouched {
1129            if let Some(h) = self.members.get_mut(k) {
1130                h.confirmed = Some(at);
1131            }
1132        }
1133        SectionRead::Confirmed(vouched)
1134    }
1135
1136    /// One group of a read owner heartbeat of `class`, heard at `at` (v2
1137    /// §2.5's "An owner heartbeat", step 3 from "Not followed" on): `entry`
1138    /// is what core §8.6 read its index as ([`crate::heartbeat::Group::entry`]),
1139    /// and `time` the owner heartbeat's. The caller has read the owner
1140    /// heartbeat on its key first ([`Views::apply_owner`] does both): this
1141    /// moves no sequence.
1142    ///
1143    /// - **Not followed:** the entry names another interface, or the view
1144    ///   follows no collection.
1145    /// - **Another revision:** the entry's revision is not the view's, or
1146    ///   the group's tag is not that revision's.
1147    /// - **Refused:** core §7.5 refuses its sections, parsed whole, the
1148    ///   other class's too.
1149    /// - **Read:** each followed collection of `class` as a heartbeat's
1150    ///   section is read, on the collection's one count of divergences in
1151    ///   a row; a followed one of the other class is
1152    ///   [`SectionRead::OtherClass`], unread and uncounted. The group is a
1153    ///   heartbeat applied ([`View::heartbeats`], [`View::owner_time`])
1154    ///   only when a section was read: one on the other class's key reads
1155    ///   none.
1156    pub fn apply_group(
1157        &mut self,
1158        class: crate::heartbeat::Class,
1159        entry: &crate::catalog::Entry,
1160        group: &crate::heartbeat::Group,
1161        time: crate::heartbeat::Time,
1162        at: T,
1163    ) -> GroupRead {
1164        if entry.iface != self.layout.iface || !self.follows_any() {
1165            return GroupRead::NotFollowed;
1166        }
1167        if entry.contract != self.layout.fingerprint || !group.tag_is(&self.layout) {
1168            return GroupRead::Revision;
1169        }
1170        let read = match group.read(&self.layout) {
1171            Ok(s) => s,
1172            Err(r) => return GroupRead::Refused(r),
1173        };
1174        let mut sections = Vec::with_capacity(read.len());
1175        for (i, section) in read.iter().enumerate() {
1176            sections.push(if !self.follows[i] {
1177                SectionRead::NotFollowed
1178            } else if self.layout.collections[i].class != class {
1179                SectionRead::OtherClass
1180            } else {
1181                self.read_section(i, section.as_ref(), at)
1182            });
1183        }
1184        // v2 §2.5: what counts for a collection is "the groups whose
1185        // sections were read for its interface, on its own class's key". A
1186        // group on the other class's key reads no section of the view, so
1187        // it is no heartbeat applied to it: neither its count nor the
1188        // owner's time moves (review of #1137).
1189        if sections
1190            .iter()
1191            .any(|s| !matches!(s, SectionRead::NotFollowed | SectionRead::OtherClass))
1192        {
1193            self.time = Some(time);
1194            self.heartbeats += 1;
1195        }
1196        GroupRead::Read(sections)
1197    }
1198
1199    /// A GET's snapshot vouched for `key`'s live value at `at` (v2 §2.6,
1200    /// text 0.7; core §7.5's confirmation): kept as a heartbeat's would be,
1201    /// when it is later than what the view held. A deleted member, or one
1202    /// the view does not hold, is left as it is.
1203    pub fn confirm(&mut self, key: &str, at: T) {
1204        let Some(k) = crate::heartbeat::base_relative(key) else {
1205            return;
1206        };
1207        if let Some(h) = self.members.get_mut(k)
1208            && !h.deleted
1209            && h.confirmed.is_none_or(|c| c < at)
1210        {
1211            h.confirmed = Some(at);
1212        }
1213    }
1214
1215    /// The last heartbeat that vouched for `key` since its last mutation.
1216    #[must_use]
1217    pub fn confirmed(&self, key: &str) -> Option<T> {
1218        let k = crate::heartbeat::base_relative(key)?;
1219        self.members.get(k).and_then(|h| h.confirmed)
1220    }
1221
1222    /// The collections due a read: two heartbeats in a row diverged there.
1223    #[must_use]
1224    pub fn reread_due(&self) -> Vec<usize> {
1225        (0..self.diverged.len())
1226            .filter(|i| self.follows[*i] && self.diverged[*i] >= 2)
1227            .collect()
1228    }
1229
1230    /// Whether the last heartbeat came after a gap in its key's seqs: the
1231    /// interface's own heartbeat key's. A gap on an owner heartbeat key is
1232    /// [`Views::gap`]'s.
1233    #[must_use]
1234    pub fn gap(&self) -> bool {
1235        self.seq.gap()
1236    }
1237
1238    /// Whether it follows the collection at `index`.
1239    #[must_use]
1240    pub fn follows(&self, index: usize) -> bool {
1241        self.follows.get(index).copied().unwrap_or(false)
1242    }
1243
1244    /// The classes of the collections it follows, `link` first: the
1245    /// provider's owner heartbeat keys a subscriber subscribes to beside
1246    /// its heartbeat key (v2 §2.5, "Both forms").
1247    #[must_use]
1248    pub fn classes(&self) -> Vec<crate::heartbeat::Class> {
1249        crate::heartbeat::Class::ALL
1250            .into_iter()
1251            .filter(|c| {
1252                self.layout
1253                    .collections
1254                    .iter()
1255                    .zip(&self.follows)
1256                    .any(|(x, f)| *f && x.class == *c)
1257            })
1258            .collect()
1259    }
1260
1261    /// The owner's time in the last heartbeat applied, or in the last
1262    /// owner heartbeat a group of which read a section of a followed
1263    /// collection.
1264    #[must_use]
1265    pub fn owner_time(&self) -> Option<crate::heartbeat::Time> {
1266        self.time
1267    }
1268
1269    /// The last heartbeat applied on the interface's own heartbeat key:
1270    /// its stamp. An owner heartbeat's is its key's ([`Views::last`]).
1271    #[must_use]
1272    pub fn last_heartbeat(&self) -> Option<Stamp> {
1273        self.seq.last()
1274    }
1275
1276    /// How many heartbeats it applied, each group among them that read a
1277    /// section of a followed collection, on its class's key.
1278    #[must_use]
1279    pub fn heartbeats(&self) -> u64 {
1280        self.heartbeats
1281    }
1282
1283    /// `key`'s last confirmation at `now` (§2.5): the later of its last
1284    /// mutation and the last heartbeat that vouched for it, as a [`Last`];
1285    /// `None` for a member the view does not hold.
1286    #[must_use]
1287    pub fn last(&self, key: &str, now: T) -> Option<Last> {
1288        let k = crate::heartbeat::base_relative(key)?;
1289        let h = self.members.get(k)?;
1290        Some(if h.deleted {
1291            Last::Delete(now.since(h.at))
1292        } else {
1293            Last::Put(now.since(h.confirmed.map_or(h.at, |c| c.max(h.at))))
1294        })
1295    }
1296
1297    /// `key` as a subscription's observation at `now` (§2.5), the view
1298    /// standing in for its deliveries: its last confirmation, how long the
1299    /// subscription has `listened`, and complete when the subscription
1300    /// lost nothing (`complete`) and no heartbeat was lost.
1301    #[must_use]
1302    pub fn observation(
1303        &self,
1304        key: &str,
1305        now: T,
1306        listened: Duration,
1307        complete: bool,
1308    ) -> Observation {
1309        Observation::Subscribed {
1310            last: self.last(key, now),
1311            listened,
1312            complete: complete && !self.seq.gap(),
1313        }
1314    }
1315}
1316
1317/// What a reader reads a group's index through (core §8.6): the catalogs
1318/// it holds, and the one the owner names in its descriptor, `None` where
1319/// it names none, which refuses every index (`unknown_catalog`).
1320#[derive(Debug, Clone, Copy)]
1321pub struct Catalogs<'a> {
1322    pub held: &'a [crate::catalog::Catalog],
1323    pub named: Option<crate::catalog::CatalogId>,
1324}
1325
1326/// One owner heartbeat key's state, as a reader holds it.
1327#[derive(Debug, Clone, Default)]
1328struct ClassKey {
1329    seq: Sequence,
1330    /// The interfaces a group on the key has named within the run: whose
1331    /// collections of the key's class it covers, to this reader.
1332    named: std::collections::BTreeSet<crate::grammar::IfaceId>,
1333    read: u64,
1334}
1335
1336/// One provider's views as one reader holds them, an interface each, with
1337/// a [`Sequence`] per owner heartbeat key in front of them (`freshness.v2`
1338/// §2.5, text 0.9; #1110's H2a). A heartbeat is still its interface's
1339/// view's ([`Views::view_mut`], [`View::apply`]); an owner heartbeat is
1340/// read here ([`Views::apply_owner`]), since its sequence is its key's and
1341/// its groups are several views'.
1342///
1343/// - **Older and lost are per key.** Each class's key has one sequence. A
1344///   gap on it is one owner heartbeat lost for every collection the key
1345///   covers: those of the key's class, in each interface a group on the
1346///   key has named within the run ([`Views::lost`]). It says nothing of
1347///   the other class's key, nor of an interface confirmed by its own
1348///   heartbeat.
1349/// - **Divergences are per collection.** A collection has one count, its
1350///   view's, which a heartbeat's section and a read group's move alike.
1351/// - **A reader bound to one interface** holds one view here, and reads
1352///   the other groups as not followed, by their sizes.
1353#[derive(Debug, Clone)]
1354pub struct Views<T> {
1355    views: BTreeMap<crate::grammar::IfaceId, View<T>>,
1356    keys: BTreeMap<crate::heartbeat::Class, ClassKey>,
1357}
1358
1359impl<T> Default for Views<T> {
1360    fn default() -> Self {
1361        Self {
1362            views: BTreeMap::new(),
1363            keys: BTreeMap::new(),
1364        }
1365    }
1366}
1367
1368impl<T: Arrival> Views<T> {
1369    /// No view, and no owner heartbeat read.
1370    #[must_use]
1371    pub fn new() -> Self {
1372        Self::default()
1373    }
1374
1375    /// Holds `view` as its interface's, in place of any view held for it.
1376    pub fn insert(&mut self, view: View<T>) -> Option<View<T>> {
1377        self.views.insert(view.layout().iface.clone(), view)
1378    }
1379
1380    /// The view of an interface.
1381    #[must_use]
1382    pub fn view(&self, iface: &crate::grammar::IfaceId) -> Option<&View<T>> {
1383        self.views.get(iface)
1384    }
1385
1386    /// The view of an interface, to hear a mutation, a read's answer or
1387    /// the interface's own heartbeat with.
1388    pub fn view_mut(&mut self, iface: &crate::grammar::IfaceId) -> Option<&mut View<T>> {
1389        self.views.get_mut(iface)
1390    }
1391
1392    /// The view of the interface a state key is of, namespace in front or
1393    /// none.
1394    #[must_use]
1395    pub fn view_of(&self, key: &str) -> Option<&View<T>> {
1396        self.views.get(&iface_of(key)?)
1397    }
1398
1399    /// As [`Views::view_of`], to change it.
1400    pub fn view_of_mut(&mut self, key: &str) -> Option<&mut View<T>> {
1401        self.views.get_mut(&iface_of(key)?)
1402    }
1403
1404    /// Every view, in order of its interface.
1405    pub fn iter(&self) -> impl Iterator<Item = &View<T>> {
1406        self.views.values()
1407    }
1408
1409    /// The classes of the collections the views follow, `link` first: the
1410    /// provider's owner heartbeat keys to subscribe to (v2 §2.5, "Both
1411    /// forms").
1412    #[must_use]
1413    pub fn classes(&self) -> Vec<crate::heartbeat::Class> {
1414        crate::heartbeat::Class::ALL
1415            .into_iter()
1416            .filter(|c| self.views.values().any(|v| v.classes().contains(c)))
1417            .collect()
1418    }
1419
1420    /// The horizon of the provider's owner heartbeat key of `class`, as
1421    /// this reader can tell it (core §8.5): the shortest among the
1422    /// collections of that class in the revisions it holds a view of,
1423    /// `None` with none. A reader across a face declares the key's
1424    /// subscription again after two of them of silence.
1425    #[must_use]
1426    pub fn class_horizon(&self, class: crate::heartbeat::Class) -> Option<Duration> {
1427        self.views
1428            .values()
1429            .filter_map(|v| v.layout().class_horizon(class))
1430            .min()
1431    }
1432
1433    /// An owner heartbeat heard at `at` on the key of `class`: CH's tag,
1434    /// its stamp and its body, read through the catalog its owner names
1435    /// among those the reader holds (`through`), by v2 §2.5's steps.
1436    ///
1437    /// 1. **Refused:** core §7.5 refuses it whole.
1438    /// 2. **Older:** within one run, its seq is not after the last read
1439    ///    one's on this key.
1440    /// 3. **Read:** each group alone, in order: no index
1441    ///    ([`GroupRead::Refused`]), then as its interface's view reads it
1442    ///    ([`View::apply_group`]), not followed where no view is held for
1443    ///    the interface. A group that confirms nothing takes nothing from
1444    ///    the groups beside it.
1445    ///
1446    /// One stopped at step 1 or 2 moves neither the key's sequence nor a
1447    /// count of divergences, and names no interface.
1448    pub fn apply_owner(
1449        &mut self,
1450        class: crate::heartbeat::Class,
1451        tag: crate::wire::Tag,
1452        stamp: Stamp,
1453        body: &[u8],
1454        through: Catalogs<'_>,
1455        at: T,
1456    ) -> OwnerApplied {
1457        let hb = match crate::heartbeat::OwnerHeartbeat::parse(tag, body) {
1458            Ok(hb) => hb,
1459            Err(r) => return OwnerApplied::Refused(r),
1460        };
1461        let key = self.keys.entry(class).or_default();
1462        let Some(read) = key.seq.read(stamp) else {
1463            return OwnerApplied::Older;
1464        };
1465        if read.run {
1466            // Another run starts the sequence again, and its covered
1467            // collections with it.
1468            key.named.clear();
1469        }
1470        key.read += 1;
1471        let mut groups = Vec::with_capacity(hb.groups.len());
1472        for g in &hb.groups {
1473            let entry = match g.entry(through.held, through.named) {
1474                Ok(e) => e,
1475                Err(r) => {
1476                    groups.push(GroupApplied {
1477                        index: g.index,
1478                        iface: None,
1479                        read: GroupRead::Refused(r),
1480                    });
1481                    continue;
1482                }
1483            };
1484            // A group names an interface once its index is read, whatever
1485            // becomes of it after.
1486            key.named.insert(entry.iface.clone());
1487            let read = match self.views.get_mut(&entry.iface) {
1488                Some(v) => v.apply_group(class, entry, g, hb.time, at),
1489                None => GroupRead::NotFollowed,
1490            };
1491            groups.push(GroupApplied {
1492                index: g.index,
1493                iface: Some(entry.iface.clone()),
1494                read,
1495            });
1496        }
1497        OwnerApplied::Read {
1498            gap: read.gap,
1499            groups,
1500        }
1501    }
1502
1503    /// Whether the last owner heartbeat read on the key of `class`
1504    /// followed a gap in that key's seqs; `None` while none was read on
1505    /// it.
1506    #[must_use]
1507    pub fn gap(&self, class: crate::heartbeat::Class) -> Option<bool> {
1508        let k = self.keys.get(&class)?;
1509        k.seq.last().map(|_| k.seq.gap())
1510    }
1511
1512    /// The last owner heartbeat read on the key of `class`: its stamp.
1513    #[must_use]
1514    pub fn last(&self, class: crate::heartbeat::Class) -> Option<Stamp> {
1515        self.keys.get(&class)?.seq.last()
1516    }
1517
1518    /// How many owner heartbeats were read on the key of `class`, whatever
1519    /// became of their groups.
1520    #[must_use]
1521    pub fn owner_heartbeats(&self, class: crate::heartbeat::Class) -> u64 {
1522        self.keys.get(&class).map_or(0, |k| k.read)
1523    }
1524
1525    /// Whether the followed collection at `index` of `iface` is read as a
1526    /// lost delivery (v1 §2.5 rule 3): its interface's heartbeat key's
1527    /// last heartbeat followed a gap, or its class's owner heartbeat key's
1528    /// did and a group on that key has named the interface within the
1529    /// run. Until one arrives in sequence on that key, or one of another
1530    /// run does.
1531    #[must_use]
1532    pub fn is_lost(&self, iface: &crate::grammar::IfaceId, index: usize) -> bool {
1533        let Some(v) = self.views.get(iface) else {
1534            return false;
1535        };
1536        if !v.follows(index) {
1537            return false;
1538        }
1539        v.gap()
1540            || self
1541                .keys
1542                .get(&v.layout().collections[index].class)
1543                .is_some_and(|k| k.seq.gap() && k.named.contains(iface))
1544    }
1545
1546    /// Every followed collection read as a lost delivery
1547    /// ([`Views::is_lost`]), by interface, then in map order.
1548    #[must_use]
1549    pub fn lost(&self) -> Vec<(crate::grammar::IfaceId, usize)> {
1550        self.views
1551            .iter()
1552            .flat_map(|(iface, v)| {
1553                (0..v.layout().collections.len())
1554                    .filter(|i| self.is_lost(iface, *i))
1555                    .map(|i| (iface.clone(), i))
1556            })
1557            .collect()
1558    }
1559
1560    /// `key` as a subscription's observation at `now` (§2.5), as
1561    /// [`View::observation`], complete only while its collection is read
1562    /// as no lost delivery on either key that confirms it
1563    /// ([`Views::is_lost`]). `None` for a key of no view held.
1564    #[must_use]
1565    pub fn observation(
1566        &self,
1567        key: &str,
1568        now: T,
1569        listened: Duration,
1570        complete: bool,
1571    ) -> Option<Observation> {
1572        let v = self.view_of(key)?;
1573        let lost = crate::heartbeat::base_relative(key)
1574            .and_then(|k| v.layout().collection_of(k))
1575            .is_some_and(|i| self.is_lost(&v.layout().iface, i));
1576        Some(v.observation(key, now, listened, complete && !lost))
1577    }
1578}
1579
1580/// The interface a data key is of, namespace in front or none.
1581fn iface_of(key: &str) -> Option<crate::grammar::IfaceId> {
1582    match crate::grammar::parse(crate::heartbeat::base_relative(key)?) {
1583        Ok(crate::grammar::ZkKey::Data { iface, .. }) => Some(iface),
1584        _ => None,
1585    }
1586}
1587
1588/// A subscription's last delivery of a member and, where a [`View`]
1589/// holds it, the last heartbeat that vouched for it: the later is its
1590/// last confirmation (§2.5). `delivered` is the subscription's own
1591/// [`Last`]; a delete stays a delete. A member never delivered that a
1592/// heartbeat confirmed, one a late joiner's read seeded (`freshness.v2`
1593/// §2.5), is confirmed then.
1594#[must_use]
1595pub fn confirmed_last(delivered: Option<Last>, heartbeat: Option<Duration>) -> Option<Last> {
1596    match (delivered, heartbeat) {
1597        (Some(Last::Put(a)), Some(h)) => Some(Last::Put(a.min(h))),
1598        (None, Some(h)) => Some(Last::Put(h)),
1599        (d, _) => d,
1600    }
1601}
1602
1603#[cfg(test)]
1604mod tests {
1605    use super::*;
1606    use serde_json::json;
1607
1608    fn ann(v: Value) -> BTreeMap<String, Value> {
1609        BTreeMap::from([(TTL_S.to_owned(), v)])
1610    }
1611
1612    #[test]
1613    fn the_horizon_is_a_whole_number_of_seconds() {
1614        let h = |v: Value| horizon(Kind::State, &ann(v));
1615        assert_eq!(h(json!(60)), Horizon::Within(Duration::from_secs(60)));
1616        assert_eq!(h(json!(60.0)), Horizon::Within(Duration::from_secs(60)));
1617        assert_eq!(h(json!(-0.0)), Horizon::Never);
1618        assert_eq!(h(json!(0)), Horizon::Never);
1619        assert!(matches!(h(json!(1.5)), Horizon::Invalid(_)));
1620        assert!(matches!(h(json!(-1)), Horizon::Invalid(_)));
1621        assert!(matches!(h(json!(MAX_TTL_S + 1)), Horizon::Invalid(_)));
1622        assert_eq!(
1623            horizon(Kind::Event, &ann(json!("x"))),
1624            Horizon::Ignored,
1625            "the kind first"
1626        );
1627        assert_eq!(horizon(Kind::State, &BTreeMap::new()), Horizon::Undeclared);
1628        assert_eq!(
1629            h(json!(61)).refresh_bound(),
1630            Some(Duration::from_millis(30_500))
1631        );
1632    }
1633
1634    #[test]
1635    fn a_trusted_reply_is_judged_in_the_band() {
1636        let h = Horizon::Within(Duration::from_secs(2));
1637        let got = |s: f64| Observation::Got {
1638            reply: Some(Reply::Put {
1639                stamp_age: Some(StampAge::from_secs_f64(s)),
1640            }),
1641            clock: ClockTrust::Trusted {
1642                delta: DEFAULT_DELTA,
1643            },
1644        };
1645        let v = |s: f64| judge(&h, &got(s)).reason;
1646        assert_eq!(v(1.5), Reason::WithinHorizon);
1647        assert_eq!(v(1.6), Reason::NearHorizon);
1648        assert_eq!(v(2.5), Reason::NearHorizon);
1649        assert_eq!(v(2.6), Reason::BeyondHorizon);
1650        assert_eq!(v(-0.5), Reason::WithinHorizon);
1651        assert_eq!(v(-0.6), Reason::ClockDisagrees);
1652    }
1653
1654    #[test]
1655    fn fresh_wins_then_stale_then_unobservable() {
1656        let j = |v, r| Judged::new(v, r);
1657        assert_eq!(
1658            combine([
1659                j(Verdict::Stale, Reason::NoDelivery),
1660                j(Verdict::Fresh, Reason::WithinHorizon)
1661            ])
1662            .verdict,
1663            Verdict::Fresh
1664        );
1665        assert_eq!(
1666            combine([
1667                j(Verdict::Unobservable, Reason::ClockUntrusted),
1668                j(Verdict::Stale, Reason::NoDelivery)
1669            ])
1670            .reason,
1671            Reason::NoDelivery
1672        );
1673        assert_eq!(combine([]).reason, Reason::NoObservation);
1674    }
1675
1676    mod view {
1677        use super::super::*;
1678        use crate::contract::load_str;
1679        use crate::heartbeat::{Digest, Heartbeat, Layout, Members, Section, Time};
1680        use crate::timing::Mono;
1681        use crate::wire::{Run, Seq, Tag};
1682
1683        const HB: &str = r#"
1684[interface]
1685name = "hb"
1686major = 1
1687minor = 0
1688uses = ["freshness.v1"]
1689[resources.link]
1690kind = "state"
1691type = { raw = "text/plain" }
1692annotations = { "freshness.ttl_s" = 2 }
1693[resources."peer/{peer}"]
1694kind = "state"
1695type = { raw = "text/plain" }
1696params = { peer = "string" }
1697cardinality = 5
1698annotations = { "freshness.ttl_s" = 2 }
1699"#;
1700        const LINK: &str = "zk2/lab/n1/hb.v1/state/link";
1701        const A: &str = "zk2/lab/n1/hb.v1/state/peer/a";
1702        const B: &str = "zk2/lab/n1/hb.v1/state/peer/b";
1703
1704        fn layout() -> Layout {
1705            let c = load_str(HB, std::path::Path::new("."), None)
1706                .contract
1707                .unwrap();
1708            Layout::of(&c)
1709        }
1710        fn st(run: u16, seq: u32) -> Stamp {
1711            Stamp {
1712                run: Run::U16(run),
1713                seq: Seq::new(seq).unwrap(),
1714            }
1715        }
1716        fn ms(n: u64) -> Mono {
1717            Mono::after(Duration::from_millis(n))
1718        }
1719        /// A heartbeat over (link, peer/*), its sections given.
1720        fn body(l: &Layout, link: Option<Section>, peers: Option<Section>) -> Vec<u8> {
1721            Heartbeat {
1722                time: Time::Unknown,
1723                sections: vec![link, peers],
1724            }
1725            .write(l)
1726            .unwrap()
1727        }
1728        fn view() -> View<Mono> {
1729            let mut v = View::new(layout());
1730            assert!(v.follow_resource("state/link"));
1731            assert!(v.follow_resource("state/peer/{peer}"));
1732            assert!(!v.follow_resource("state/nothing"));
1733            v
1734        }
1735
1736        #[test]
1737        fn a_heartbeat_whose_digest_is_the_views_confirms_what_it_vouches_for() {
1738            let l = layout();
1739            let mut v = view();
1740            v.put(LINK, Some(st(1, 1)), ms(0));
1741            v.put(A, Some(st(1, 2)), ms(0));
1742            v.put(B, Some(st(1, 3)), ms(0));
1743            let link = Section {
1744                digest: Digest::of([(LINK, st(1, 1))]),
1745                members: Members::One { vouched: true },
1746            };
1747            let peers = Section {
1748                digest: Digest::of([(A, st(1, 2)), (B, st(1, 3))]),
1749                members: Members::templated(2, [1]),
1750            };
1751            let got = v.apply(
1752                l.tag,
1753                st(9, 0),
1754                &body(&l, Some(link), Some(peers)),
1755                ms(1500),
1756            );
1757            assert_eq!(
1758                got,
1759                Applied::Read {
1760                    gap: false,
1761                    sections: vec![
1762                        SectionRead::Confirmed(vec![LINK.into()]),
1763                        SectionRead::Confirmed(vec![B.into()]),
1764                    ]
1765                }
1766            );
1767            assert_eq!(v.confirmed(B), Some(ms(1500)));
1768            assert_eq!(v.confirmed(A), None, "not vouched for");
1769            // At 3 s: the link put at 0 is 3 s old, confirmed 1.5 s ago.
1770            let h = Horizon::Within(Duration::from_secs(2));
1771            let j = |k: &str| {
1772                judge(
1773                    &h,
1774                    &v.observation(k, ms(3000), Duration::from_secs(3), true),
1775                )
1776            };
1777            assert_eq!(j(LINK).verdict, Verdict::Fresh);
1778            assert_eq!(j(B).verdict, Verdict::Fresh);
1779            assert_eq!(
1780                j(A).verdict,
1781                Verdict::Stale,
1782                "a cleared bit is no confirmation"
1783            );
1784            // A namespace in front reads as the base-relative key.
1785            assert_eq!(v.confirmed(&format!("prod/{LINK}")), Some(ms(1500)));
1786        }
1787
1788        #[test]
1789        fn a_missed_change_diverges_and_two_in_a_row_are_due_a_read() {
1790            let l = layout();
1791            let mut v = view();
1792            v.put(A, Some(st(1, 2)), ms(0));
1793            // The owner holds a's seq 5 and b: the view missed both.
1794            let owner = Digest::of([(A, st(1, 5)), (B, st(1, 6))]);
1795            let sec = || Section {
1796                digest: owner,
1797                members: Members::templated(2, [0, 1]),
1798            };
1799            for (seq, due) in [(0, false), (1, true)] {
1800                let got = v.apply(l.tag, st(9, seq), &body(&l, None, Some(sec())), ms(1000));
1801                assert_eq!(
1802                    got,
1803                    Applied::Read {
1804                        gap: false,
1805                        sections: vec![SectionRead::Absent, SectionRead::Diverged]
1806                    }
1807                );
1808                assert_eq!(v.reread_due() == vec![1], due);
1809            }
1810            assert_eq!(v.confirmed(A), None);
1811            // The read's answer replaces the view, and the next heartbeat confirms.
1812            v.replace(1, [(A, Some(st(1, 5))), (B, Some(st(1, 6)))], ms(1100));
1813            assert!(v.reread_due().is_empty());
1814            let got = v.apply(l.tag, st(9, 2), &body(&l, None, Some(sec())), ms(1200));
1815            assert_eq!(
1816                got,
1817                Applied::Read {
1818                    gap: false,
1819                    sections: vec![
1820                        SectionRead::Absent,
1821                        SectionRead::Confirmed(vec![A.into(), B.into()])
1822                    ]
1823                }
1824            );
1825        }
1826
1827        #[test]
1828        fn a_deleted_member_leaves_the_digest_and_a_stale_put_is_not_taken() {
1829            let mut v = view();
1830            v.put(A, Some(st(1, 4)), ms(0));
1831            v.put(A, Some(st(1, 3)), ms(10));
1832            assert_eq!(v.digest(1), Some(Digest::of([(A, st(1, 4))])));
1833            v.delete(A, Some(st(1, 5)), ms(20));
1834            assert_eq!(v.digest(1), Some(Digest::EMPTY));
1835            assert_eq!(
1836                v.last(A, ms(30)),
1837                Some(Last::Delete(Duration::from_millis(10)))
1838            );
1839            // Another run's put is taken whatever its seq.
1840            v.put(A, Some(st(2, 0)), ms(40));
1841            assert_eq!(v.digest(1), Some(Digest::of([(A, st(2, 0))])));
1842            // A put with no envelope leaves the collection with no digest.
1843            v.put(B, None, ms(50));
1844            assert_eq!(v.digest(1), None);
1845            // A key of no collection is not held.
1846            v.put("zk2/lab/n1/hb.v1/state/other", Some(st(1, 1)), ms(60));
1847            assert_eq!(v.last("zk2/lab/n1/hb.v1/state/other", ms(70)), None);
1848        }
1849
1850        #[test]
1851        fn a_gap_is_a_heartbeat_lost_and_the_tag_and_the_order_guard() {
1852            let l = layout();
1853            let mut v = view();
1854            v.put(LINK, Some(st(1, 1)), ms(0));
1855            let link = || {
1856                Some(Section {
1857                    digest: Digest::of([(LINK, st(1, 1))]),
1858                    members: Members::One { vouched: true },
1859                })
1860            };
1861            let b = body(&l, link(), None);
1862            let other = Tag::new((l.tag.get() + 1) % 16).unwrap();
1863            assert_eq!(v.apply(other, st(9, 0), &b, ms(100)), Applied::Revision);
1864            assert!(matches!(
1865                v.apply(l.tag, st(9, 0), &b, ms(100)),
1866                Applied::Read { gap: false, .. }
1867            ));
1868            assert!(matches!(
1869                v.apply(l.tag, st(9, 3), &b, ms(200)),
1870                Applied::Read { gap: true, .. }
1871            ));
1872            assert!(v.gap());
1873            let o = v.observation(LINK, ms(5000), Duration::from_secs(5), true);
1874            assert_eq!(
1875                judge(&Horizon::Within(Duration::from_secs(2)), &o).reason,
1876                Reason::Incomplete
1877            );
1878            assert_eq!(v.apply(l.tag, st(9, 3), &b, ms(300)), Applied::Older);
1879            assert_eq!(v.apply(l.tag, st(9, 1), &b, ms(300)), Applied::Older);
1880            assert!(matches!(
1881                v.apply(l.tag, st(9, 4), &b, ms(400)),
1882                Applied::Read { gap: false, .. }
1883            ));
1884            assert!(!v.gap());
1885            // A new run of the key is no gap, and its seq starts anew.
1886            assert!(matches!(
1887                v.apply(l.tag, st(10, 0), &b, ms(500)),
1888                Applied::Read { gap: false, .. }
1889            ));
1890            // A body cut short is refused, and counts as no heartbeat.
1891            assert!(matches!(
1892                v.apply(l.tag, st(10, 1), &b[..2], ms(600)),
1893                Applied::Refused(_)
1894            ));
1895            assert_eq!(v.heartbeats(), 4);
1896        }
1897    }
1898
1899    /// `freshness.v2` §2.5's owner heartbeat, where `apply.json` leaves a
1900    /// reading unpinned: what a key covers, and a group's steps one by one.
1901    mod views {
1902        use super::super::*;
1903        use crate::catalog::Catalog;
1904        use crate::contract::load_str;
1905        use crate::heartbeat::{
1906            Class, Digest, Group, GroupRefusal, Layout, Members, OwnerHeartbeat, Section, Time,
1907        };
1908        use crate::timing::Mono;
1909        use crate::wire::{Run, Seq, Tag};
1910
1911        const MIXED: &str = r#"
1912[interface]
1913name = "mixed"
1914major = 1
1915minor = 0
1916uses = ["freshness.v2", "link.v1"]
1917[resources."peer/{peer}"]
1918kind = "state"
1919type = { raw = "text/plain" }
1920params = { peer = "string" }
1921cardinality = 8
1922annotations = { "freshness.ttl_s" = 120 }
1923[resources.status]
1924kind = "state"
1925type = { raw = "text/plain" }
1926annotations = { "freshness.ttl_s" = 60, "link.exposure" = "link" }
1927"#;
1928        const VITAL: &str = r#"
1929[interface]
1930name = "vital"
1931major = 1
1932minor = 0
1933uses = ["freshness.v2"]
1934[resources.status]
1935kind = "state"
1936type = { raw = "text/plain" }
1937annotations = { "freshness.ttl_s" = 60 }
1938"#;
1939        const PEER: &str = "zk2/lab/n1/mixed.v1/state/peer/p1";
1940        const STATUS: &str = "zk2/lab/n1/mixed.v1/state/status";
1941        const VITALS: &str = "zk2/lab/n1/vital.v1/state/status";
1942
1943        fn layout(text: &str) -> Layout {
1944            Layout::of(
1945                &load_str(text, std::path::Path::new("."), None)
1946                    .contract
1947                    .unwrap(),
1948            )
1949        }
1950        fn st(run: u16, seq: u32) -> Stamp {
1951            Stamp {
1952                run: Run::U16(run),
1953                seq: Seq::new(seq).unwrap(),
1954            }
1955        }
1956        fn ms(n: u64) -> Mono {
1957            Mono::after(Duration::from_millis(n))
1958        }
1959        /// mixed.v1 at index 0 and vital.v1 at index 1.
1960        fn catalog(mixed: &Layout, vital: &Layout) -> Catalog {
1961            let mut c = Catalog::new(0).unwrap();
1962            c.push(mixed.iface.clone(), mixed.fingerprint.clone())
1963                .unwrap();
1964            c.push(vital.iface.clone(), vital.fingerprint.clone())
1965                .unwrap();
1966            c
1967        }
1968        fn one(key: &str, stamp: Stamp) -> Option<Section> {
1969            Some(Section {
1970                digest: Digest::of([(key, stamp)]),
1971                members: Members::One { vouched: true },
1972            })
1973        }
1974        /// mixed.v1's group on the `host` key: `peer/p1` vouched for, and
1975        /// no bit for `status`, a `link` collection.
1976        fn mixed_host(l: &Layout) -> Group {
1977            let peers = Section {
1978                digest: Digest::of([(PEER, st(1, 1))]),
1979                members: Members::templated(1, [0]),
1980            };
1981            Group::of(0, l, &[Some(peers), None]).unwrap()
1982        }
1983        fn vital_host(l: &Layout) -> Group {
1984            Group::of(1, l, &[one(VITALS, st(1, 3))]).unwrap()
1985        }
1986        fn body(groups: Vec<Group>) -> Vec<u8> {
1987            OwnerHeartbeat {
1988                time: Time::Unknown,
1989                groups,
1990            }
1991            .write()
1992            .unwrap()
1993        }
1994        /// Both views, every collection followed, a member in each.
1995        fn views(mixed: &Layout, vital: &Layout) -> Views<Mono> {
1996            let mut vs = Views::new();
1997            for l in [mixed, vital] {
1998                let mut v = View::new(l.clone());
1999                for i in 0..l.collections.len() {
2000                    assert!(v.follow(i));
2001                }
2002                assert!(vs.insert(v).is_none());
2003            }
2004            vs.view_of_mut(PEER)
2005                .unwrap()
2006                .put(PEER, Some(st(1, 1)), ms(0));
2007            vs.view_of_mut(STATUS)
2008                .unwrap()
2009                .put(STATUS, Some(st(1, 2)), ms(0));
2010            vs.view_of_mut(VITALS)
2011                .unwrap()
2012                .put(VITALS, Some(st(1, 3)), ms(0));
2013            vs
2014        }
2015
2016        #[test]
2017        fn a_class_is_the_exposure_and_a_key_is_one_classs() {
2018            let (mixed, vital) = (layout(MIXED), layout(VITAL));
2019            assert_eq!(
2020                mixed
2021                    .collections
2022                    .iter()
2023                    .map(|c| c.class)
2024                    .collect::<Vec<_>>(),
2025                vec![Class::Host, Class::Link]
2026            );
2027            assert_eq!(mixed.classes(), vec![Class::Link, Class::Host]);
2028            assert_eq!(vital.classes(), vec![Class::Host]);
2029            assert_eq!(
2030                mixed.class_horizon(Class::Link),
2031                Some(Duration::from_secs(60))
2032            );
2033            assert_eq!(
2034                mixed.class_horizon(Class::Host),
2035                Some(Duration::from_secs(120))
2036            );
2037            assert_eq!(vital.class_horizon(Class::Link), None);
2038            // A subscriber subscribes to the keys of the classes it follows.
2039            let mut v = View::<Mono>::new(mixed.clone());
2040            assert!(v.classes().is_empty());
2041            assert!(v.follow_resource("state/status"));
2042            assert_eq!(v.classes(), vec![Class::Link]);
2043            let vs = views(&mixed, &vital);
2044            assert_eq!(vs.classes(), vec![Class::Link, Class::Host]);
2045        }
2046
2047        /// A group on the other class's key reads no section of the view,
2048        /// so it is no heartbeat applied to it: v2 §2.5 counts "the groups
2049        /// whose sections were read for its interface, on its own class's
2050        /// key" (review of #1137). The owner heartbeat itself is read and
2051        /// counted on its key.
2052        #[test]
2053        fn a_group_on_the_other_classs_key_is_no_heartbeat_applied() {
2054            let (mixed, vital) = (layout(MIXED), layout(VITAL));
2055            let cat = catalog(&mixed, &vital);
2056            let through = Catalogs {
2057                held: std::slice::from_ref(&cat),
2058                named: Some(cat.id()),
2059            };
2060            // A reader of mixed.v1's `status` alone, its `link` collection.
2061            let mut v = View::new(mixed.clone());
2062            assert!(v.follow_resource("state/status"));
2063            v.put(STATUS, Some(st(1, 2)), ms(0));
2064            let mut vs = Views::new();
2065            vs.insert(v);
2066            let known = Time::At { secs: 7, ms: 0 };
2067            let put = |g: Group| {
2068                OwnerHeartbeat {
2069                    time: known,
2070                    groups: vec![g],
2071                }
2072                .write()
2073                .unwrap()
2074            };
2075            // On the `host` key, mixed.v1's group holds `peer` alone.
2076            let host = vs.apply_owner(
2077                Class::Host,
2078                Tag::new(0).unwrap(),
2079                st(9, 0),
2080                &put(mixed_host(&mixed)),
2081                through,
2082                ms(10),
2083            );
2084            let OwnerApplied::Read { groups, .. } = host else {
2085                panic!("read: {host:?}");
2086            };
2087            assert_eq!(
2088                groups[0].read,
2089                GroupRead::Read(vec![SectionRead::NotFollowed, SectionRead::OtherClass])
2090            );
2091            let view = vs.view(&mixed.iface).unwrap();
2092            assert_eq!(view.heartbeats(), 0, "no section read, none applied");
2093            assert_eq!(view.owner_time(), None);
2094            assert_eq!(vs.owner_heartbeats(Class::Host), 1, "read on its key");
2095            // On the `link` key, its group reads `status`: one applied.
2096            let link = Group::of(0, &mixed, &[None, one(STATUS, st(1, 2))]).unwrap();
2097            let applied = vs.apply_owner(
2098                Class::Link,
2099                Tag::new(0).unwrap(),
2100                st(9, 0),
2101                &put(link),
2102                through,
2103                ms(20),
2104            );
2105            let OwnerApplied::Read { groups, .. } = applied else {
2106                panic!("read: {applied:?}");
2107            };
2108            assert_eq!(
2109                groups[0].read,
2110                GroupRead::Read(vec![
2111                    SectionRead::NotFollowed,
2112                    SectionRead::Confirmed(vec![STATUS.to_owned()])
2113                ])
2114            );
2115            let view = vs.view(&mixed.iface).unwrap();
2116            assert_eq!(view.heartbeats(), 1);
2117            assert_eq!(view.owner_time(), Some(known));
2118            // A map bit of 0 on the collection's own key is a section read
2119            // (`absent`), so its group is applied.
2120            let absent = Group::of(0, &mixed, &[None, None]).unwrap();
2121            vs.apply_owner(
2122                Class::Link,
2123                Tag::new(0).unwrap(),
2124                st(9, 1),
2125                &put(absent),
2126                through,
2127                ms(30),
2128            );
2129            assert_eq!(vs.view(&mixed.iface).unwrap().heartbeats(), 2);
2130        }
2131
2132        #[test]
2133        fn a_sequence_is_its_keys_alone() {
2134            let mut s = Sequence::default();
2135            let first = s.read(st(9, 5)).unwrap();
2136            assert!(!first.gap && !first.run);
2137            assert_eq!(s.read(st(9, 5)), None, "the same seq");
2138            assert_eq!(s.read(st(9, 4)), None, "an earlier one");
2139            assert_eq!(s.read(st(9, 5 + (1 << 23))), None, "2^23 ahead, unordered");
2140            assert_eq!(s.last(), Some(st(9, 5)), "an older one moves nothing");
2141            assert!(!s.read(st(9, 6)).unwrap().gap);
2142            assert!(s.read(st(9, 8)).unwrap().gap);
2143            assert!(s.gap());
2144            let other = s.read(st(10, 3)).unwrap();
2145            assert!(other.run && !other.gap, "another run starts it again");
2146            assert!(!s.gap());
2147            // The seq wraps in serial order.
2148            let mut s = Sequence::default();
2149            s.read(st(9, Seq::MAX.get())).unwrap();
2150            assert!(!s.read(st(9, 0)).unwrap().gap);
2151        }
2152
2153        #[test]
2154        fn a_gap_loses_what_a_group_on_the_key_named_within_the_run() {
2155            let (mixed, vital) = (layout(MIXED), layout(VITAL));
2156            let held = [catalog(&mixed, &vital)];
2157            let named = Some(held[0].id());
2158            let mut vs = views(&mixed, &vital);
2159            let alone = body(vec![mixed_host(&mixed)]);
2160            let both = body(vec![mixed_host(&mixed), vital_host(&vital)]);
2161            let through = Catalogs { held: &held, named };
2162            let host = |vs: &mut Views<Mono>, stamp, body: &[u8], at| match vs.apply_owner(
2163                Class::Host,
2164                Tag::NONE,
2165                stamp,
2166                body,
2167                through,
2168                ms(at),
2169            ) {
2170                OwnerApplied::Read { gap, .. } => gap,
2171                other => panic!("{other:?}"),
2172            };
2173            let lost = |vs: &Views<Mono>| -> Vec<(String, usize)> {
2174                vs.lost()
2175                    .into_iter()
2176                    .map(|(i, c)| (i.to_string(), c))
2177                    .collect()
2178            };
2179            // mixed.v1's group alone, then a gap: vital.v1 was never named
2180            // on the key, so its collection is no lost delivery.
2181            assert!(!host(&mut vs, st(9, 0), &alone, 100));
2182            assert!(host(&mut vs, st(9, 2), &alone, 200));
2183            assert_eq!(lost(&vs), vec![("mixed.v1".to_owned(), 0)]);
2184            assert!(vs.is_lost(&mixed.iface, 0));
2185            assert!(!vs.is_lost(&mixed.iface, 1), "a `link` collection");
2186            assert!(!vs.is_lost(&vital.iface, 0), "not named on the key");
2187            // The member is read as a lost delivery: incomplete.
2188            let o = |vs: &Views<Mono>, key| {
2189                let o = vs
2190                    .observation(key, ms(250), Duration::from_secs(1), true)
2191                    .unwrap();
2192                matches!(o, Observation::Subscribed { complete: true, .. })
2193            };
2194            assert!(!o(&vs, PEER));
2195            assert!(o(&vs, STATUS));
2196            assert!(o(&vs, VITALS));
2197            assert_eq!(vs.gap(Class::Host), Some(true));
2198            assert_eq!(vs.gap(Class::Link), None, "nothing read on the `link` key");
2199            // One in sequence ends it, and names vital.v1.
2200            assert!(!host(&mut vs, st(9, 3), &both, 300));
2201            assert!(lost(&vs).is_empty());
2202            // The next gap on the key covers both, though the owner
2203            // heartbeat after it holds mixed.v1's group alone.
2204            assert!(host(&mut vs, st(9, 5), &alone, 400));
2205            assert_eq!(
2206                lost(&vs),
2207                vec![("mixed.v1".to_owned(), 0), ("vital.v1".to_owned(), 0)]
2208            );
2209            // Another run starts the sequence again, and what the key
2210            // covers with it.
2211            assert!(!host(&mut vs, st(10, 0), &alone, 500));
2212            assert!(lost(&vs).is_empty());
2213            assert!(host(&mut vs, st(10, 2), &alone, 600));
2214            assert_eq!(lost(&vs), vec![("mixed.v1".to_owned(), 0)]);
2215            assert_eq!(vs.owner_heartbeats(Class::Host), 6);
2216            assert_eq!(vs.last(Class::Host), Some(st(10, 2)));
2217            // A key of no view held has no observation.
2218            assert!(
2219                vs.observation(
2220                    "zk2/lab/n1/other.v1/state/x",
2221                    ms(700),
2222                    Duration::from_secs(1),
2223                    true
2224                )
2225                .is_none()
2226            );
2227        }
2228
2229        #[test]
2230        fn a_group_stops_at_the_first_step_that_answers() {
2231            let (mixed, vital) = (layout(MIXED), layout(VITAL));
2232            let cat = catalog(&mixed, &vital);
2233            let (e_mixed, e_vital) = (cat.entry(0).unwrap(), cat.entry(1).unwrap());
2234            let mut v = View::<Mono>::new(vital.clone());
2235            let g = vital_host(&vital);
2236            // Not followed: the view follows no collection yet, or the
2237            // index names another interface.
2238            assert_eq!(
2239                v.apply_group(Class::Host, e_vital, &g, Time::Unknown, ms(1)),
2240                GroupRead::NotFollowed
2241            );
2242            assert!(v.follow(0));
2243            v.put(VITALS, Some(st(1, 3)), ms(0));
2244            assert_eq!(
2245                v.apply_group(Class::Host, e_mixed, &g, Time::Unknown, ms(1)),
2246                GroupRead::NotFollowed
2247            );
2248            // Another revision: by the catalog's word, or by the tag.
2249            let elsewhere = crate::catalog::Entry {
2250                iface: vital.iface.clone(),
2251                contract: mixed.fingerprint.clone(),
2252            };
2253            assert_eq!(
2254                v.apply_group(Class::Host, &elsewhere, &g, Time::Unknown, ms(1)),
2255                GroupRead::Revision
2256            );
2257            let mut retagged = g.clone();
2258            retagged.tag = Tag::new((vital.tag.get() + 1) % 16).unwrap();
2259            assert_eq!(
2260                v.apply_group(Class::Host, e_vital, &retagged, Time::Unknown, ms(1)),
2261                GroupRead::Revision
2262            );
2263            // Refused: its sections, here cut one bit short. Counted for
2264            // nothing: the divergence before it and the one after are two
2265            // in a row.
2266            let diverged = Group::of(1, &vital, &[one(VITALS, st(1, 4))]).unwrap();
2267            assert_eq!(
2268                v.apply_group(Class::Host, e_vital, &diverged, Time::Unknown, ms(2)),
2269                GroupRead::Read(vec![SectionRead::Diverged])
2270            );
2271            let mut short = g.clone();
2272            short.sections.bits -= 1;
2273            assert_eq!(
2274                v.apply_group(Class::Host, e_vital, &short, Time::Unknown, ms(3)),
2275                GroupRead::Refused(GroupRefusal::Short)
2276            );
2277            assert!(v.reread_due().is_empty());
2278            assert_eq!(
2279                v.apply_group(Class::Host, e_vital, &diverged, Time::Unknown, ms(4)),
2280                GroupRead::Read(vec![SectionRead::Diverged])
2281            );
2282            assert_eq!(v.reread_due(), vec![0]);
2283            // Read, and on the other class's key not read at all: the
2284            // count of divergences stands.
2285            assert_eq!(
2286                v.apply_group(Class::Link, e_vital, &g, Time::Unknown, ms(5)),
2287                GroupRead::Read(vec![SectionRead::OtherClass])
2288            );
2289            assert_eq!(v.reread_due(), vec![0]);
2290            assert_eq!(v.confirmed(VITALS), None);
2291            assert_eq!(
2292                v.apply_group(Class::Host, e_vital, &g, Time::Unknown, ms(6)),
2293                GroupRead::Read(vec![SectionRead::Confirmed(vec![VITALS.to_owned()])])
2294            );
2295            assert_eq!(v.confirmed(VITALS), Some(ms(6)));
2296            assert!(v.reread_due().is_empty());
2297            // Its own heartbeat key heard nothing through all this.
2298            assert_eq!(v.last_heartbeat(), None);
2299            assert!(!v.gap());
2300        }
2301
2302        #[test]
2303        fn an_owner_heartbeat_key_names_its_class() {
2304            use crate::heartbeat::{covered, owner_class, owner_key};
2305            let k = owner_key("lab", "n1", Class::Link);
2306            assert_eq!(k, "zk2/lab/n1/freshness.v2/stream/heartbeats/link");
2307            let (addr, class) = owner_class(&format!("ns/{k}")).unwrap();
2308            assert_eq!((addr.to_string().as_str(), class), ("lab/n1", Class::Link));
2309            assert_eq!(
2310                owner_class("zk2/lab/n1/freshness.v2/stream/heartbeats/host").map(|x| x.1),
2311                Some(Class::Host)
2312            );
2313            // No other chunk is a class, and neither key reads as the other.
2314            assert!(owner_class("zk2/lab/n1/freshness.v2/stream/heartbeats/near").is_none());
2315            assert!(owner_class("zk2/lab/n1/freshness.v2/stream/heartbeat/link.v1").is_none());
2316            assert!(covered(&k).is_none());
2317        }
2318    }
2319
2320    #[test]
2321    fn a_measured_offset_trusts_within_the_delta_either_way() {
2322        let d = DEFAULT_DELTA;
2323        assert!(matches!(
2324            ClockTrust::measured(StampAge::ahead(d), d),
2325            ClockTrust::Trusted { .. }
2326        ));
2327        assert_eq!(
2328            ClockTrust::measured(StampAge::behind(Duration::from_millis(501)), d),
2329            ClockTrust::Untrusted
2330        );
2331    }
2332}