Skip to main content

zenkey_model/
timing.rs

1//! `timing.v1`: a stream's cadence, its deadline and its lifespan
2//! (`spec/profiles/timing/v1.md`, #908).
3//!
4//! The profile's session-free half: the declaration read from a resolved
5//! resource (§2.2, §2.3), a reader's deadline tracker for one provider and
6//! resource (§2.5), the lifespan of each sample a reader judges (§2.6), the
7//! period over a tool's window (§2.7), and §5's three questions.
8//!
9//! ```text
10//! declaration(kind, annotations)        ─▶ declared {period, deadline, lifespan, below_period} │ invalid [reasons] │ ignored │ not this profile's
11//! Tracker::observe(at, event)           ─▶ missed {due, by, owner} │ met │ ended {gone, forgotten} │ beyond_bound     §2.5
12//!   events: start │ arrival(member, expired) │ owner(present, unconfirmed, absent) │ member_gone │ tick
13//! LifespanReader::judge(stamp)          ─▶ live │ expired │ unobservable │ not asked │ not this profile's, + reason  §2.6
14//! period_window(period, window, …)      ─▶ kept │ not_kept │ too_short │ not_heard                                 §2.7
15//! Holding::observe(tracker, reports, at) ─▶ each member's held time: while heard, missed or waited for, to its first end §2.7
16//! deadline_met / period_kept / lifespan_expired ─▶ yes │ no │ unobservable │ not_asked │ not_this_profiles        §5
17//! roll_up / roll_up_first               ─▶ a resource's or a run's answer, and its first member's reason          §5
18//! ```
19//!
20//! There is no I/O and no clock here. A reader takes each arrival's instant
21//! on its monotonic clock and each sample's age on its wall clock, follows
22//! its provider's presence, and hands them over as values: the runtime
23//! drives [`Tracker`] from its subscription and a one-shot timer at
24//! [`Tracker::next_due`], and a tool drives the same tracker over its
25//! window. A sample's age is
26//! [`freshness::StampAge`](crate::freshness::StampAge), and a clock that
27//! falsified the deployment's word is found as `freshness.v1` §2.6 finds
28//! one, with [`freshness::ClockMeasure`](crate::freshness::ClockMeasure).
29
30use std::collections::{BTreeMap, BTreeSet};
31use std::fmt;
32use std::time::Duration;
33
34use serde_json::Value;
35
36use crate::authoring::Kind;
37use crate::contract::Resource;
38use crate::freshness::{ClockMeasure, StampAge};
39
40/// The profile's id, as a contract lists it in `uses`.
41pub const PROFILE: &str = "timing.v1";
42
43/// The profile's name, as an annotation key's prefix carries it.
44pub const NAME: &str = "timing";
45
46/// `timing.period_ms` (§4).
47pub const PERIOD_MS: &str = "timing.period_ms";
48/// `timing.deadline_ms` (§4).
49pub const DEADLINE_MS: &str = "timing.deadline_ms";
50/// `timing.lifespan_ms` (§4).
51pub const LIFESPAN_MS: &str = "timing.lifespan_ms";
52
53/// The published vocabulary (§4): the keys under `timing.`, which W105
54/// reads in place of core Appendix D's interim row (core 0.53), unchanged.
55pub const VOCABULARY: &[&str] = &["period_ms", "deadline_ms", "lifespan_ms"];
56
57/// The largest value, in milliseconds: 2^53−1, the canonical domain's
58/// bound (§2.2, core §9.5).
59pub const MAX_MS: u64 = (1 << 53) - 1;
60
61/// How long after its last arrival a member that is not known, once
62/// missed, is forgotten (§2.5): an hour, core §2.7's liveness span of a
63/// stream member.
64pub const FORGET_AFTER: Duration = Duration::from_secs(3600);
65
66/// The floor of the detection bound (§2.5): 1 ms.
67pub const BOUND_FLOOR: Duration = Duration::from_millis(1);
68
69// --- §2.2, §2.3: the declaration ----------------------------------------------
70
71/// Why a declaration is invalid (§2.2), in the order checked.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
73pub enum Invalid {
74    PeriodValue,
75    DeadlineValue,
76    LifespanValue,
77}
78
79impl Invalid {
80    /// The fixture's token.
81    #[must_use]
82    pub fn as_str(self) -> &'static str {
83        match self {
84            Self::PeriodValue => "period_value",
85            Self::DeadlineValue => "deadline_value",
86            Self::LifespanValue => "lifespan_value",
87        }
88    }
89
90    /// The reason in words, for a linter's or a tool's message.
91    #[must_use]
92    pub fn says(self) -> &'static str {
93        match self {
94            Self::PeriodValue => {
95                "timing.period_ms is not a whole number of milliseconds from 1 to 2^53-1"
96            }
97            Self::DeadlineValue => {
98                "timing.deadline_ms is not a whole number of milliseconds from 1 to 2^53-1"
99            }
100            Self::LifespanValue => {
101                "timing.lifespan_ms is not a whole number of milliseconds from 1 to 2^53-1"
102            }
103        }
104    }
105}
106
107impl fmt::Display for Invalid {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        f.write_str(self.says())
110    }
111}
112
113/// A timed resource's values (§2.2), each `None` when its key is absent.
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
115pub struct Declared {
116    pub period: Option<Duration>,
117    pub deadline: Option<Duration>,
118    pub lifespan: Option<Duration>,
119}
120
121impl Declared {
122    /// Whether a period and a deadline are both declared and the deadline
123    /// is below the period: no deadline, which a linter warns of (§2.5).
124    #[must_use]
125    pub fn below_period(&self) -> bool {
126        matches!((self.period, self.deadline), (Some(p), Some(d)) if d < p)
127    }
128
129    /// The deadline a reader judges (§2.5): the declared one, unless it is
130    /// below the period.
131    #[must_use]
132    pub fn judged_deadline(&self) -> Option<Duration> {
133        if self.below_period() {
134            None
135        } else {
136            self.deadline
137        }
138    }
139}
140
141/// What a reader reads of a resolved resource or a requirement (§2.2,
142/// §2.3).
143#[derive(Debug, Clone, PartialEq, Eq)]
144pub enum Declaration {
145    /// No key of the vocabulary.
146    NotThisProfiles,
147    /// A key of the vocabulary, whatever its value, on a state, an event,
148    /// an operation or a requirement: it means nothing there, and a linter
149    /// warns of it (§2.3).
150    Ignored,
151    /// A stream whose values are not all valid: the reasons, in §2.2's
152    /// order. Every question of §5 is then unobservable.
153    Invalid(Vec<Invalid>),
154    /// A timed resource (§0).
155    Declared(Declared),
156}
157
158impl Declaration {
159    /// The fixture's token.
160    #[must_use]
161    pub fn as_str(&self) -> &'static str {
162        match self {
163            Self::NotThisProfiles => "not_this_profiles",
164            Self::Ignored => "ignored",
165            Self::Invalid(_) => "invalid",
166            Self::Declared(_) => "declared",
167        }
168    }
169
170    /// The values of a valid declaration.
171    #[must_use]
172    pub fn declared(&self) -> Option<&Declared> {
173        match self {
174            Self::Declared(d) => Some(d),
175            _ => None,
176        }
177    }
178}
179
180/// A whole number of milliseconds from 1 to 2^53−1, or `None` (§2.2). An
181/// integral float is that integer: `100.0` is 100, and `-0.0` is 0, which
182/// is no value.
183fn millis(v: &Value) -> Option<u64> {
184    let n = v.as_number()?;
185    if let Some(u) = n.as_u64() {
186        return (1..=MAX_MS).contains(&u).then_some(u);
187    }
188    if n.is_i64() {
189        return None;
190    }
191    let f = n.as_f64()?;
192    let max = MAX_MS as f64;
193    (f.is_finite() && f.fract() == 0.0 && f >= 1.0 && f <= max).then_some(f as u64)
194}
195
196fn any_key(annotations: &BTreeMap<String, Value>) -> bool {
197    [PERIOD_MS, DEADLINE_MS, LIFESPAN_MS]
198        .iter()
199        .any(|k| annotations.contains_key(*k))
200}
201
202/// Reads the declaration of a resource of `kind` from its resolved
203/// annotations (§2.2, §2.3): `[defaults]`, then `[defaults.<kind>]`, then
204/// its own, as the contract model merges them (core §9.3). The kind is read
205/// first, then each key alone. Another `timing.<key>` is W105's and plays
206/// no part.
207#[must_use]
208pub fn declaration(kind: Kind, annotations: &BTreeMap<String, Value>) -> Declaration {
209    if !any_key(annotations) {
210        return Declaration::NotThisProfiles;
211    }
212    if kind != Kind::Stream {
213        return Declaration::Ignored;
214    }
215    let mut why = Vec::new();
216    let mut read = |key: &str, wrong: Invalid| -> Option<Duration> {
217        let v = annotations.get(key)?;
218        let ms = millis(v);
219        if ms.is_none() {
220            why.push(wrong);
221        }
222        ms.map(Duration::from_millis)
223    };
224    let declared = Declared {
225        period: read(PERIOD_MS, Invalid::PeriodValue),
226        deadline: read(DEADLINE_MS, Invalid::DeadlineValue),
227        lifespan: read(LIFESPAN_MS, Invalid::LifespanValue),
228    };
229    if why.is_empty() {
230        Declaration::Declared(declared)
231    } else {
232        Declaration::Invalid(why)
233    }
234}
235
236/// [`declaration`] of a resource of a contract.
237#[must_use]
238pub fn declaration_of(r: &Resource) -> Declaration {
239    declaration(r.kind, &r.annotations)
240}
241
242/// The declaration of a requirement (`[requires.<role>]`) from its own
243/// annotations (§2.3): a key of the vocabulary there means nothing at this
244/// version, and a linter warns of it.
245#[must_use]
246pub fn requirement_declaration(annotations: &BTreeMap<String, Value>) -> Declaration {
247    if any_key(annotations) {
248        Declaration::Ignored
249    } else {
250        Declaration::NotThisProfiles
251    }
252}
253
254/// The tracker a reader judges a resource of `kind` and declaration `d`
255/// by (§2.2, §2.5): `None` when it judges no deadline, the resource not a
256/// stream, its declaration invalid, no deadline declared, or the deadline
257/// below the period (text 0.2, F-259). `bound` and `known` are
258/// [`Tracker::new`]'s.
259#[must_use]
260pub fn tracker_for<S: Into<String>>(
261    kind: Kind,
262    d: &Declaration,
263    bound: Option<u64>,
264    known: impl IntoIterator<Item = S>,
265) -> Option<Tracker> {
266    if kind != Kind::Stream {
267        return None;
268    }
269    let deadline = d.declared()?.judged_deadline()?;
270    Some(Tracker::new(deadline, bound, known))
271}
272
273/// The detection bound of a deadline (§2.5): max(deadline/50, 1 ms). A
274/// reader reports a miss at most this long after it is due.
275#[must_use]
276pub fn detection_bound(deadline: Duration) -> Duration {
277    (deadline / 50).max(BOUND_FLOOR)
278}
279
280// --- §2.5: the deadline -----------------------------------------------------------
281
282/// An instant on the reader's monotonic clock (§0): the time since an
283/// origin of the reader's choosing, which never steps backwards.
284#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
285pub struct Mono(Duration);
286
287impl Mono {
288    /// The origin.
289    pub const ZERO: Self = Self(Duration::ZERO);
290
291    /// The instant `d` after the origin.
292    #[must_use]
293    pub const fn after(d: Duration) -> Self {
294        Self(d)
295    }
296
297    /// The instant `ns` nanoseconds after the origin.
298    #[must_use]
299    pub const fn from_nanos(ns: u64) -> Self {
300        Self(Duration::from_nanos(ns))
301    }
302
303    /// The time since the origin.
304    #[must_use]
305    pub const fn since_origin(self) -> Duration {
306        self.0
307    }
308
309    /// This instant plus `d`, saturating.
310    #[must_use]
311    pub fn saturating_add(self, d: Duration) -> Self {
312        Self(self.0.saturating_add(d))
313    }
314
315    /// The time from `earlier` to this instant, zero when `earlier` is
316    /// later.
317    #[must_use]
318    pub fn saturating_since(self, earlier: Self) -> Duration {
319        self.0.saturating_sub(earlier.0)
320    }
321}
322
323/// The owner's token as the reader observes it (§0).
324#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
325pub enum OwnerState {
326    /// No state given yet: the reader follows no presence, or has read
327    /// none.
328    #[default]
329    Unseen,
330    /// The token held as seen: shown by a read or heard declared, and no
331    /// withdrawal of it heard since.
332    Present,
333    /// A withdrawal heard, and no read since (core §8.1, 0.37).
334    Unconfirmed,
335    /// A complete read showed no such token (core §8.1, 0.37).
336    Absent,
337}
338
339impl OwnerState {
340    /// The fixture's token.
341    #[must_use]
342    pub fn as_str(self) -> &'static str {
343        match self {
344            Self::Unseen => "unseen",
345            Self::Present => "present",
346            Self::Unconfirmed => "unconfirmed",
347            Self::Absent => "absent",
348        }
349    }
350
351    /// Parses the fixture's token.
352    #[must_use]
353    pub fn parse(s: &str) -> Option<Self> {
354        Some(match s {
355            "unseen" => Self::Unseen,
356            "present" => Self::Present,
357            "unconfirmed" => Self::Unconfirmed,
358            "absent" => Self::Absent,
359            _ => return None,
360        })
361    }
362}
363
364/// What a reader hands its tracker, at an instant (§2.5).
365#[derive(Debug, Clone, Copy, PartialEq, Eq)]
366pub enum Event<'a> {
367    /// The subscription declared: its start.
368    Start,
369    /// A sample of `member` (its resource chunks, or its whole key, as the
370    /// reader names members) that counts as one by §2.5: a put on a
371    /// concrete key. An `expired` one (§2.6) is no arrival.
372    Arrival { member: &'a str, expired: bool },
373    /// The owner's token as the reader now observes it.
374    Owner(OwnerState),
375    /// A member token of `member` seen (core §8.1): heard declared, heard
376    /// withdrawn, or shown by a read. On a template that declares `epoch`,
377    /// a known member is waited for from the first (§2.5, text 0.2,
378    /// F-261).
379    MemberSeen(&'a str),
380    /// A complete read shows no member token of `member` (core §8.1). On a
381    /// template that declares `epoch`, it ends a member only after a token
382    /// of it was seen (text 0.2, F-261).
383    MemberGone(&'a str),
384    /// An instant the reader judges at: its timer.
385    Tick,
386}
387
388/// Why a reader stopped judging a member (§2.5).
389#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
390pub enum EndReason {
391    /// Its member tokens are gone.
392    Gone,
393    /// Not known, missed, and silent for [`FORGET_AFTER`].
394    Forgotten,
395}
396
397impl EndReason {
398    /// The fixture's token.
399    #[must_use]
400    pub fn as_str(self) -> &'static str {
401        match self {
402            Self::Gone => "gone",
403            Self::Forgotten => "forgotten",
404        }
405    }
406}
407
408/// A report a tracker makes (§2.5).
409#[derive(Debug, Clone, PartialEq, Eq)]
410pub enum Report {
411    /// The member became missed. `due` is the instant from which the miss
412    /// holds (its last arrival, or the start of its wait, plus the
413    /// deadline); `by`, the latest instant a reader may report it, due plus
414    /// the detection bound; `owner`, the owner's state at the report.
415    Missed {
416        at: Mono,
417        member: String,
418        due: Mono,
419        by: Mono,
420        owner: OwnerState,
421    },
422    /// The member's next arrival after a miss.
423    Met { at: Mono, member: String },
424    /// The reader stopped judging a member it had heard or reported
425    /// missed.
426    Ended {
427        at: Mono,
428        member: String,
429        reason: EndReason,
430    },
431    /// A member first heard while the bound's members are held: not held,
432    /// and not judged, past the owner's bound (core §2.7).
433    BeyondBound { at: Mono, member: String },
434}
435
436impl Report {
437    /// The fixture's token.
438    #[must_use]
439    pub fn as_str(&self) -> &'static str {
440        match self {
441            Self::Missed { .. } => "missed",
442            Self::Met { .. } => "met",
443            Self::Ended { .. } => "ended",
444            Self::BeyondBound { .. } => "beyond_bound",
445        }
446    }
447
448    /// The member it is about.
449    #[must_use]
450    pub fn member(&self) -> &str {
451        match self {
452            Self::Missed { member, .. }
453            | Self::Met { member, .. }
454            | Self::Ended { member, .. }
455            | Self::BeyondBound { member, .. } => member,
456        }
457    }
458
459    /// The instant it was made.
460    #[must_use]
461    pub fn at(&self) -> Mono {
462        match self {
463            Self::Missed { at, .. }
464            | Self::Met { at, .. }
465            | Self::Ended { at, .. }
466            | Self::BeyondBound { at, .. } => *at,
467        }
468    }
469}
470
471/// Where a held member stands (§2.5).
472#[derive(Debug, Clone, Copy, PartialEq, Eq)]
473pub enum MemberState {
474    /// A known member neither heard nor waited for: before the start, its
475    /// owner not present, or after it ended (`after_end`), until its next
476    /// arrival.
477    Idle { after_end: bool },
478    /// A known member never heard, its owner present: missed once more than
479    /// the deadline has passed since `since`.
480    Waiting { since: Mono },
481    /// In time: its last arrival.
482    Heard { last: Mono },
483    /// Missed: its last arrival, `None` for a known member never heard.
484    Missed { last: Option<Mono> },
485}
486
487#[derive(Debug, Clone, Copy)]
488struct Held {
489    known: bool,
490    state: MemberState,
491}
492
493/// One reader's deadline tracker for one provider address and one resource
494/// (§2.5): a pure state machine over (instant, event) inputs. At each
495/// event it first judges every member it holds at that instant, then
496/// applies the event; [`Tracker::next_due`] is when a miss is next due, for
497/// a one-shot timer that meets the detection bound.
498#[derive(Debug, Clone)]
499pub struct Tracker {
500    deadline: Duration,
501    bound: Option<u64>,
502    start: Option<Mono>,
503    owner: OwnerState,
504    owner_since: Option<Mono>,
505    held: BTreeMap<String, Held>,
506    /// The template declares `epoch` (core §2.3): its members' tokens, not
507    /// the owner's presence, say when a known member exists (F-261).
508    epoch: bool,
509    /// The members a token of which was seen since they last ended, and
510    /// the instant the first was.
511    seen: BTreeMap<String, Mono>,
512    /// The members reported past the bound, until one is held (F-260).
513    beyond: BTreeSet<String>,
514}
515
516impl Tracker {
517    /// A tracker for a resource whose judged deadline is `deadline`
518    /// ([`Declared::judged_deadline`]) and whose bound is `bound` (core
519    /// §2.7: the instance's stated `cardinality`, else the contract's; 1 for
520    /// a template without parameters; `None` for no bound), holding the
521    /// `known` members (§0) from the first.
522    pub fn new<S: Into<String>>(
523        deadline: Duration,
524        bound: Option<u64>,
525        known: impl IntoIterator<Item = S>,
526    ) -> Self {
527        let held = known
528            .into_iter()
529            .map(|m| {
530                (
531                    m.into(),
532                    Held {
533                        known: true,
534                        state: MemberState::Idle { after_end: false },
535                    },
536                )
537            })
538            .collect();
539        Self {
540            deadline,
541            bound,
542            start: None,
543            owner: OwnerState::Unseen,
544            owner_since: None,
545            held,
546            epoch: false,
547            seen: BTreeMap::new(),
548            beyond: BTreeSet::new(),
549        }
550    }
551
552    /// The tracker of a template that declares `epoch` (core §2.3, §8.1;
553    /// §2.5, text 0.2, F-261): a known member is waited for from the
554    /// instant a member token of it is first seen, never from its owner's
555    /// presence, since a member exists from its owner's first declaration
556    /// of it; and its member tokens gone end it only after one was seen.
557    #[must_use]
558    pub fn with_epoch(mut self) -> Self {
559        self.epoch = true;
560        self
561    }
562
563    /// The deadline judged.
564    #[must_use]
565    pub fn deadline(&self) -> Duration {
566        self.deadline
567    }
568
569    /// The owner's state as last given.
570    #[must_use]
571    pub fn owner(&self) -> OwnerState {
572        self.owner
573    }
574
575    /// The members held, in member order.
576    pub fn held(&self) -> impl Iterator<Item = &str> {
577        self.held.keys().map(String::as_str)
578    }
579
580    /// Where a held member stands.
581    #[must_use]
582    pub fn state(&self, member: &str) -> Option<MemberState> {
583        self.held.get(member).map(|h| h.state)
584    }
585
586    /// The earliest instant at which a miss is due among the members heard
587    /// or waited for: a miss holds at any instant after it. `None` when no
588    /// member can become missed without an event.
589    #[must_use]
590    pub fn next_due(&self) -> Option<Mono> {
591        self.held
592            .values()
593            .filter_map(|h| match h.state {
594                MemberState::Heard { last } => Some(last),
595                MemberState::Waiting { since } => Some(since),
596                _ => None,
597            })
598            .min()
599            .map(|t| t.saturating_add(self.deadline))
600    }
601
602    /// Judges every member held at `at`, then applies `event` (§2.5).
603    /// Returns the reports, in order: the misses due and the members
604    /// forgotten, in member order, then the event's own.
605    pub fn observe(&mut self, at: Mono, event: Event<'_>) -> Vec<Report> {
606        let mut out = self.evaluate(at);
607        self.apply(at, event, &mut out);
608        out
609    }
610
611    fn evaluate(&mut self, at: Mono) -> Vec<Report> {
612        let (d, bound, owner) = (self.deadline, detection_bound(self.deadline), self.owner);
613        let mut out = Vec::new();
614        let mut forgotten = Vec::new();
615        for (name, h) in &mut self.held {
616            let from = match h.state {
617                MemberState::Heard { last } => Some((last, Some(last))),
618                MemberState::Waiting { since } => Some((since, None)),
619                _ => None,
620            };
621            if let Some((from, last)) = from {
622                let due = from.saturating_add(d);
623                if at > due {
624                    h.state = MemberState::Missed { last };
625                    out.push(Report::Missed {
626                        at,
627                        member: name.clone(),
628                        due,
629                        by: due.saturating_add(bound),
630                        owner,
631                    });
632                }
633            }
634            if !h.known
635                && let MemberState::Missed { last: Some(last) } = h.state
636                && at.saturating_since(last) >= FORGET_AFTER
637            {
638                forgotten.push(name.clone());
639                out.push(Report::Ended {
640                    at,
641                    member: name.clone(),
642                    reason: EndReason::Forgotten,
643                });
644            }
645        }
646        for name in forgotten {
647            self.held.remove(&name);
648        }
649        out
650    }
651
652    fn wait_known(&mut self, since: Mono) {
653        for h in self.held.values_mut() {
654            if h.known && h.state == (MemberState::Idle { after_end: false }) {
655                h.state = MemberState::Waiting { since };
656            }
657        }
658    }
659
660    fn apply(&mut self, at: Mono, event: Event<'_>, out: &mut Vec<Report>) {
661        match event {
662            Event::Start => {
663                if self.start.is_some() {
664                    return;
665                }
666                self.start = Some(at);
667                if self.epoch {
668                    for (name, h) in &mut self.held {
669                        if let Some(seen) = self.seen.get(name)
670                            && h.known
671                            && matches!(h.state, MemberState::Idle { .. })
672                        {
673                            h.state = MemberState::Waiting {
674                                since: (*seen).max(at),
675                            };
676                        }
677                    }
678                } else if self.owner == OwnerState::Present {
679                    let since = self.owner_since.map_or(at, |s| s.max(at));
680                    self.wait_known(since);
681                }
682            }
683            Event::Arrival { member, expired } => {
684                if self.start.is_none() || expired {
685                    return;
686                }
687                if let Some(h) = self.held.get_mut(member) {
688                    let was_missed = matches!(h.state, MemberState::Missed { .. });
689                    h.state = MemberState::Heard { last: at };
690                    if was_missed {
691                        out.push(Report::Met {
692                            at,
693                            member: member.to_owned(),
694                        });
695                    }
696                } else if self
697                    .bound
698                    .is_some_and(|b| u64::try_from(self.held.len()).unwrap_or(u64::MAX) >= b)
699                {
700                    // Once, at its first arrival past the bound (F-260).
701                    if self.beyond.insert(member.to_owned()) {
702                        out.push(Report::BeyondBound {
703                            at,
704                            member: member.to_owned(),
705                        });
706                    }
707                } else {
708                    self.beyond.remove(member);
709                    self.held.insert(
710                        member.to_owned(),
711                        Held {
712                            known: false,
713                            state: MemberState::Heard { last: at },
714                        },
715                    );
716                }
717            }
718            Event::Owner(state) => match (self.owner, state) {
719                (OwnerState::Unseen | OwnerState::Absent, OwnerState::Present) => {
720                    self.owner = OwnerState::Present;
721                    self.owner_since = Some(at);
722                    if let Some(start) = self.start
723                        && !self.epoch
724                    {
725                        self.wait_known(at.max(start));
726                    }
727                }
728                (OwnerState::Unconfirmed, OwnerState::Present)
729                | (OwnerState::Present, OwnerState::Unconfirmed) => self.owner = state,
730                (_, OwnerState::Absent) => {
731                    self.owner = OwnerState::Absent;
732                    self.owner_since = None;
733                    if !self.epoch {
734                        for h in self.held.values_mut() {
735                            if matches!(h.state, MemberState::Waiting { .. }) {
736                                h.state = MemberState::Idle { after_end: false };
737                            }
738                        }
739                    }
740                }
741                _ => {}
742            },
743            Event::MemberSeen(member) => {
744                if !self.epoch || self.seen.contains_key(member) {
745                    return;
746                }
747                self.seen.insert(member.to_owned(), at);
748                if self.start.is_some()
749                    && let Some(h) = self.held.get_mut(member)
750                    && h.known
751                    && matches!(h.state, MemberState::Idle { .. })
752                {
753                    h.state = MemberState::Waiting { since: at };
754                }
755            }
756            Event::MemberGone(member) => {
757                // A read that shows none before any was seen ends nothing
758                // (F-261).
759                if self.epoch && self.seen.remove(member).is_none() {
760                    return;
761                }
762                let Some(h) = self.held.get_mut(member) else {
763                    return;
764                };
765                if matches!(
766                    h.state,
767                    MemberState::Heard { .. } | MemberState::Missed { .. }
768                ) {
769                    out.push(Report::Ended {
770                        at,
771                        member: member.to_owned(),
772                        reason: EndReason::Gone,
773                    });
774                }
775                if h.known {
776                    h.state = MemberState::Idle { after_end: true };
777                } else {
778                    self.held.remove(member);
779                }
780            }
781            Event::Tick => {}
782        }
783    }
784}
785
786// --- §2.6: the lifespan -----------------------------------------------------------
787
788/// A zid's value from its text (core §3.3): 1 to 32 hexadecimal digits,
789/// case and leading zeros carrying no meaning.
790#[must_use]
791pub fn zid_value(s: &str) -> Option<u128> {
792    let ok = !s.is_empty() && s.len() <= 32 && s.bytes().all(|b| b.is_ascii_hexdigit());
793    if ok {
794        u128::from_str_radix(s, 16).ok()
795    } else {
796        None
797    }
798}
799
800/// A sample's stamp as a lifespan reader sees it (§2.6).
801#[derive(Debug, Clone, Copy, PartialEq, Eq)]
802pub struct Stamped {
803    /// The reader's wall clock at the arrival minus the stamp's time,
804    /// negative when the stamp is ahead.
805    pub age: StampAge,
806    /// The stamp's id, a zid's value ([`zid_value`]).
807    pub id: u128,
808}
809
810/// The answer of one sample's lifespan (§2.6).
811#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
812pub enum SampleVerdict {
813    Live,
814    Expired,
815    Unobservable,
816    NotAsked,
817    NotThisProfiles,
818}
819
820impl SampleVerdict {
821    /// The fixture's token.
822    #[must_use]
823    pub fn as_str(self) -> &'static str {
824        match self {
825            Self::Live => "live",
826            Self::Expired => "expired",
827            Self::Unobservable => "unobservable",
828            Self::NotAsked => "not_asked",
829            Self::NotThisProfiles => "not_this_profiles",
830        }
831    }
832
833    /// Parses the fixture's token.
834    #[must_use]
835    pub fn parse(s: &str) -> Option<Self> {
836        Some(match s {
837            "live" => Self::Live,
838            "expired" => Self::Expired,
839            "unobservable" => Self::Unobservable,
840            "not_asked" => Self::NotAsked,
841            "not_this_profiles" => Self::NotThisProfiles,
842            _ => return None,
843        })
844    }
845}
846
847/// Why an answer is what it is: the fixtures' reasons (§2.6, §5).
848#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
849pub enum Reason {
850    /// Not a stream (§2.3).
851    Kind,
852    /// The declaration is invalid (§2.2).
853    Invalid,
854    /// No `timing.deadline_ms`.
855    NoDeadline,
856    /// No `timing.period_ms`.
857    NoPeriod,
858    /// No `timing.lifespan_ms`.
859    NoLifespan,
860    /// The deadline is below the period: no deadline (§2.5).
861    BelowPeriod,
862    /// Read across a constrained face (§2.8).
863    AcrossFace,
864    /// A delivery lost, or the reader's receive path stalled (§2.7).
865    Lost,
866    /// A miss while the owner was present.
867    Missed,
868    /// A miss only while the owner was not present; or the period not
869    /// kept, the owner not present throughout.
870    OwnerNotPresent,
871    /// The member ended in the window.
872    Ended,
873    /// The member was never held in the window, or not heard.
874    NotHeard,
875    /// Held for the deadline or less, or a span under three periods.
876    WindowTooShort,
877    /// No miss, held long enough.
878    Met,
879    /// The period kept (§2.7).
880    Kept,
881    /// The period not kept.
882    NotKept,
883    /// A sample expired (§2.6).
884    Expired,
885    /// A sample live.
886    Live,
887    /// No ε stated: nothing discarded.
888    NoBound,
889    /// The sample carries no stamp.
890    Unstamped,
891    /// No `meta.zid` held of an instance of the provider's address.
892    Unattributed,
893    /// The stamp's id is no owner's `meta.zid`.
894    ForeignStamp,
895    /// The stamp's clock was seen ahead of the reader's by more than ε.
896    ClockDisagrees,
897    /// No sample of the member.
898    NoSample,
899}
900
901impl Reason {
902    /// The fixture's token.
903    #[must_use]
904    pub fn as_str(self) -> &'static str {
905        match self {
906            Self::Kind => "kind",
907            Self::Invalid => "invalid",
908            Self::NoDeadline => "no_deadline",
909            Self::NoPeriod => "no_period",
910            Self::NoLifespan => "no_lifespan",
911            Self::BelowPeriod => "below_period",
912            Self::AcrossFace => "across_face",
913            Self::Lost => "lost",
914            Self::Missed => "missed",
915            Self::OwnerNotPresent => "owner_not_present",
916            Self::Ended => "ended",
917            Self::NotHeard => "not_heard",
918            Self::WindowTooShort => "window_too_short",
919            Self::Met => "met",
920            Self::Kept => "kept",
921            Self::NotKept => "not_kept",
922            Self::Expired => "expired",
923            Self::Live => "live",
924            Self::NoBound => "no_bound",
925            Self::Unstamped => "unstamped",
926            Self::Unattributed => "unattributed",
927            Self::ForeignStamp => "foreign_stamp",
928            Self::ClockDisagrees => "clock_disagrees",
929            Self::NoSample => "no_sample",
930        }
931    }
932
933    /// Parses the fixture's token.
934    #[must_use]
935    pub fn parse(s: &str) -> Option<Self> {
936        [
937            Self::Kind,
938            Self::Invalid,
939            Self::NoDeadline,
940            Self::NoPeriod,
941            Self::NoLifespan,
942            Self::BelowPeriod,
943            Self::AcrossFace,
944            Self::Lost,
945            Self::Missed,
946            Self::OwnerNotPresent,
947            Self::Ended,
948            Self::NotHeard,
949            Self::WindowTooShort,
950            Self::Met,
951            Self::Kept,
952            Self::NotKept,
953            Self::Expired,
954            Self::Live,
955            Self::NoBound,
956            Self::Unstamped,
957            Self::Unattributed,
958            Self::ForeignStamp,
959            Self::ClockDisagrees,
960            Self::NoSample,
961        ]
962        .into_iter()
963        .find(|r| r.as_str() == s)
964    }
965
966    /// The reason in words, for a tool's message.
967    #[must_use]
968    pub fn says(self) -> &'static str {
969        match self {
970            Self::Kind => "only a stream has a period, a deadline or a lifespan",
971            Self::Invalid => "its timing declaration is invalid",
972            Self::NoDeadline => "no timing.deadline_ms",
973            Self::NoPeriod => "no timing.period_ms",
974            Self::NoLifespan => "no timing.lifespan_ms",
975            Self::BelowPeriod => "its deadline is below its period, so it is no deadline",
976            Self::AcrossFace => "read across a constrained face, where presence does not cross",
977            Self::Lost => "this reader lost a delivery, or stalled, in the window",
978            Self::Missed => "nothing arrived within its deadline while its owner was present",
979            Self::OwnerNotPresent => "its owner was not present throughout",
980            Self::Ended => "the member ended in the window",
981            Self::NotHeard => "the member was not heard in the window",
982            Self::WindowTooShort => "the window was too short to tell",
983            Self::Met => "every arrival within its deadline",
984            Self::Kept => "published at its period",
985            Self::NotKept => "fewer samples arrived than its period promises",
986            Self::Expired => "a sample arrived older than its lifespan",
987            Self::Live => "every sample arrived within its lifespan",
988            Self::NoBound => {
989                "the deployment states no bound on its clocks, so nothing is discarded"
990            }
991            Self::Unstamped => "the sample carries no stamp",
992            Self::Unattributed => {
993                "no meta.zid is held for the provider, so a stamp is unattributable"
994            }
995            Self::ForeignStamp => "the stamp is not the owner's: a router's, or another session's",
996            Self::ClockDisagrees => {
997                "the stamp's clock was seen ahead of this reader's by more than the stated bound"
998            }
999            Self::NoSample => "no sample was read",
1000        }
1001    }
1002}
1003
1004impl fmt::Display for Reason {
1005    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1006        f.write_str(self.as_str())
1007    }
1008}
1009
1010/// One sample's lifespan judgement (§2.6).
1011#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1012pub struct Sample {
1013    pub verdict: SampleVerdict,
1014    pub reason: Reason,
1015}
1016
1017impl Sample {
1018    const fn new(verdict: SampleVerdict, reason: Reason) -> Self {
1019        Self { verdict, reason }
1020    }
1021
1022    /// Whether a consumer discards the sample (§2.6): an expired one only.
1023    #[must_use]
1024    pub fn discarded(&self) -> bool {
1025        self.verdict == SampleVerdict::Expired
1026    }
1027}
1028
1029/// One reader's lifespan judgement over one reading of one provider's
1030/// resource (§2.6): the subscription's lifetime, or a tool's window. It
1031/// remembers, per stamping clock, the stamp furthest ahead, so that a clock
1032/// that falsified the deployment's word stays unobservable for the rest of
1033/// the reading.
1034#[derive(Debug, Clone)]
1035pub struct LifespanReader {
1036    premise: Result<Duration, Sample>,
1037    epsilon: Option<Duration>,
1038    owners: BTreeSet<u128>,
1039    clocks: BTreeMap<u128, ClockMeasure>,
1040}
1041
1042impl LifespanReader {
1043    /// A reader of a resource of `kind` and declaration `d`, under the
1044    /// deployment's stated bound `epsilon` (`None` when none is stated,
1045    /// never the HLC's delta), attributing stamps to the `owners`' zids:
1046    /// the `meta.zid` of each instance of the provider's address it holds a
1047    /// descriptor of.
1048    pub fn new(
1049        kind: Kind,
1050        d: &Declaration,
1051        epsilon: Option<Duration>,
1052        owners: impl IntoIterator<Item = u128>,
1053    ) -> Self {
1054        let premise = if kind != Kind::Stream {
1055            Err(Sample::new(SampleVerdict::NotThisProfiles, Reason::Kind))
1056        } else {
1057            match d {
1058                Declaration::Invalid(_) => {
1059                    Err(Sample::new(SampleVerdict::Unobservable, Reason::Invalid))
1060                }
1061                Declaration::Declared(Declared {
1062                    lifespan: Some(l), ..
1063                }) => Ok(*l),
1064                _ => Err(Sample::new(SampleVerdict::NotAsked, Reason::NoLifespan)),
1065            }
1066        };
1067        Self {
1068            premise,
1069            epsilon,
1070            owners: owners.into_iter().collect(),
1071            clocks: BTreeMap::new(),
1072        }
1073    }
1074
1075    /// The owners' zids now held, when the reader reads another descriptor.
1076    pub fn set_owners(&mut self, owners: impl IntoIterator<Item = u128>) {
1077        self.owners = owners.into_iter().collect();
1078    }
1079
1080    /// Judges one sample at its arrival (§2.6), by the first step that
1081    /// holds: the kind, the declaration, the key, ε, the stamp, its
1082    /// attribution, its clock's agreement with ε, then the band.
1083    pub fn judge(&mut self, stamp: Option<Stamped>) -> Sample {
1084        use Reason as R;
1085        use SampleVerdict as V;
1086        let lifespan = match self.premise {
1087            Ok(l) => l,
1088            Err(s) => return s,
1089        };
1090        let Some(eps) = self.epsilon else {
1091            return Sample::new(V::Unobservable, R::NoBound);
1092        };
1093        let Some(stamp) = stamp else {
1094            return Sample::new(V::Unobservable, R::Unstamped);
1095        };
1096        if self.owners.is_empty() {
1097            return Sample::new(V::Unobservable, R::Unattributed);
1098        }
1099        if !self.owners.contains(&stamp.id) {
1100            return Sample::new(V::Unobservable, R::ForeignStamp);
1101        }
1102        let m = self
1103            .clocks
1104            .entry(stamp.id)
1105            .and_modify(|m| m.record(stamp.age))
1106            .or_insert_with(|| ClockMeasure::new(stamp.age));
1107        let e = eps.as_nanos() as i128;
1108        if m.most_ahead().nanos() < -e {
1109            return Sample::new(V::Unobservable, R::ClockDisagrees);
1110        }
1111        if stamp.age.nanos() - e > lifespan.as_nanos() as i128 {
1112            Sample::new(V::Expired, R::Expired)
1113        } else {
1114            Sample::new(V::Live, R::Live)
1115        }
1116    }
1117}
1118
1119// --- §2.7: the period over a window -----------------------------------------------
1120
1121/// What one member's arrivals over a window say of its period (§2.7).
1122#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1123pub enum PeriodVerdict {
1124    /// Not known, and no arrival in the window: no member to ask about.
1125    NotHeard,
1126    /// A span under three periods.
1127    TooShort,
1128    /// (arrivals + 2) × period is at least the span.
1129    Kept,
1130    NotKept,
1131}
1132
1133impl PeriodVerdict {
1134    /// The fixture's token.
1135    #[must_use]
1136    pub fn as_str(self) -> &'static str {
1137        match self {
1138            Self::NotHeard => "not_heard",
1139            Self::TooShort => "too_short",
1140            Self::Kept => "kept",
1141            Self::NotKept => "not_kept",
1142        }
1143    }
1144
1145    /// Parses the fixture's token.
1146    #[must_use]
1147    pub fn parse(s: &str) -> Option<Self> {
1148        Some(match s {
1149            "not_heard" => Self::NotHeard,
1150            "too_short" => Self::TooShort,
1151            "kept" => Self::Kept,
1152            "not_kept" => Self::NotKept,
1153            _ => return None,
1154        })
1155    }
1156}
1157
1158/// [`period_window`]'s answer: the verdict, the arrivals in the span, and
1159/// the span's length (`None` when not heard).
1160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1161pub struct PeriodReading {
1162    pub verdict: PeriodVerdict,
1163    pub arrivals: u64,
1164    pub span: Option<Duration>,
1165}
1166
1167/// One member's period over a window from `from` to `to` (§2.7), on the
1168/// reader's monotonic clock: the span starts at `from` for a `known`
1169/// member, else at its first arrival within the window, and ends at
1170/// `ended` when the member ended within the window, else at `to`; its
1171/// arrivals are those within the span, both ends included.
1172#[must_use]
1173pub fn period_window(
1174    period: Duration,
1175    from: Mono,
1176    to: Mono,
1177    known: bool,
1178    ended: Option<Mono>,
1179    arrivals: &[Mono],
1180) -> PeriodReading {
1181    let start = if known {
1182        Some(from)
1183    } else {
1184        arrivals.iter().copied().find(|t| (from..=to).contains(t))
1185    };
1186    let Some(start) = start else {
1187        return PeriodReading {
1188            verdict: PeriodVerdict::NotHeard,
1189            arrivals: 0,
1190            span: None,
1191        };
1192    };
1193    let end = ended.unwrap_or(to);
1194    let span = end.saturating_since(start);
1195    let n = arrivals
1196        .iter()
1197        .filter(|t| (start..=end).contains(*t))
1198        .count() as u64;
1199    let (p, s) = (period.as_nanos(), span.as_nanos());
1200    let verdict = if s < 3 * p {
1201        PeriodVerdict::TooShort
1202    } else if (u128::from(n) + 2) * p >= s {
1203        PeriodVerdict::Kept
1204    } else {
1205        PeriodVerdict::NotKept
1206    };
1207    PeriodReading {
1208        verdict,
1209        arrivals: n,
1210        span: Some(span),
1211    }
1212}
1213
1214// --- §5: what a tool may conclude ---------------------------------------------------
1215
1216/// A question of §5, answered in the three states: a pole of each
1217/// established kind, and the unestablished kinds apart (core O5).
1218#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1219pub enum Answer {
1220    Yes,
1221    No,
1222    Unobservable,
1223    NotAsked,
1224    NotThisProfiles,
1225}
1226
1227impl Answer {
1228    /// The fixture's token.
1229    #[must_use]
1230    pub fn as_str(self) -> &'static str {
1231        match self {
1232            Self::Yes => "yes",
1233            Self::No => "no",
1234            Self::Unobservable => "unobservable",
1235            Self::NotAsked => "not_asked",
1236            Self::NotThisProfiles => "not_this_profiles",
1237        }
1238    }
1239}
1240
1241impl fmt::Display for Answer {
1242    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1243        f.write_str(self.as_str())
1244    }
1245}
1246
1247/// An answer and its reason.
1248#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1249pub struct Judged {
1250    pub answer: Answer,
1251    pub reason: Reason,
1252}
1253
1254impl Judged {
1255    const fn new(answer: Answer, reason: Reason) -> Self {
1256        Self { answer, reason }
1257    }
1258}
1259
1260/// What a tool's window establishes of every member (§2.7).
1261#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1262pub struct Window {
1263    /// Read through a constrained face (§2.8).
1264    pub across_face: bool,
1265    /// The tool knows it lost a delivery of the member, or its receive path
1266    /// stalled, in the window.
1267    pub lost: bool,
1268    /// The owner present (§0) at every instant of the window.
1269    pub owner_present: bool,
1270}
1271
1272/// The tracker's account of one member over the window (§2.7).
1273#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1274pub struct DeadlineAccount {
1275    /// How long the member was held in the window: its longest unbroken
1276    /// stretch, never the sum of its stretches (§2.7, text 0.5;
1277    /// [`Holding`]).
1278    pub held: Duration,
1279    /// Misses reported while the owner was present.
1280    pub missed_present: u32,
1281    /// Misses reported while it was unconfirmed, absent or unseen.
1282    pub missed_not_present: u32,
1283    /// Whether the member ended in the window.
1284    pub ended: bool,
1285}
1286
1287impl DeadlineAccount {
1288    /// Counts a miss the tracker reported.
1289    pub fn count(&mut self, r: &Report) {
1290        if let Report::Missed { owner, .. } = r {
1291            if *owner == OwnerState::Present {
1292                self.missed_present += 1;
1293            } else {
1294                self.missed_not_present += 1;
1295            }
1296        }
1297        if matches!(r, Report::Ended { .. }) {
1298            self.ended = true;
1299        }
1300    }
1301}
1302
1303/// How long a tool held one member in its window, so far (§2.7): its
1304/// longest unbroken stretch, see [`Holding`].
1305#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1306pub struct HeldSpan {
1307    /// The longest stretch that ended.
1308    longest: Duration,
1309    /// The instant the running stretch started, while one runs.
1310    from: Option<Mono>,
1311    /// Its first end in the window: no stretch starts after it (F-280).
1312    ended: Option<Mono>,
1313}
1314
1315impl HeldSpan {
1316    /// The time held up to `at`: the longest stretch, the running one
1317    /// included, never their sum (text 0.5).
1318    #[must_use]
1319    pub fn held_to(&self, at: Mono) -> Duration {
1320        self.longest
1321            .max(self.from.map_or(Duration::ZERO, |f| at.saturating_since(f)))
1322    }
1323
1324    /// Its first end in the window, when it ended.
1325    #[must_use]
1326    pub fn ended(&self) -> Option<Mono> {
1327        self.ended
1328    }
1329
1330    /// Whether the count runs.
1331    #[must_use]
1332    pub fn counting(&self) -> bool {
1333        self.from.is_some()
1334    }
1335
1336    fn run(&mut self, at: Mono) {
1337        if self.from.is_none() && self.ended.is_none() {
1338            self.from = Some(at);
1339        }
1340    }
1341
1342    fn stop(&mut self, at: Mono) {
1343        if let Some(f) = self.from.take() {
1344            self.longest = self.longest.max(at.saturating_since(f));
1345        }
1346    }
1347}
1348
1349/// How long a tool held each member of one tracker in its window (§2.7;
1350/// text 0.5, F-278, F-280): the account [`DeadlineAccount::held`] reads,
1351/// the **longest unbroken stretch** it held the member, never the sum of
1352/// its stretches.
1353///
1354/// Handed the tracker after each event it observed in the window, with the
1355/// reports it made, a member's stretch runs from the instant the tracker
1356/// holds it heard, missed or waited for, and stops at the instant it holds
1357/// it otherwise, or not at all:
1358/// - **a known member never heard is held only while it is waited for**
1359///   (§2.5): its owner's absence stops the stretch, a pause, and its
1360///   presence again starts a new one (F-278). A miss can only be reported
1361///   within one stretch, since each wait counts from its own start, so two
1362///   stretches each no longer than the deadline could not have shown one,
1363///   whatever their sum: §5 answers `window_too_short`, never `met`;
1364/// - **its first `ended` stops it for good** (F-280): a member heard again
1365///   after it ended is read over its first life, its held time and its span
1366///   ending at that first end.
1367///
1368/// The window runs from the tracker's start (§2.7: the window's start is
1369/// its subscription's start) to [`Holding::close`]: before its start a
1370/// tracker waits for nothing and takes no arrival, so nothing counts.
1371#[derive(Debug, Clone, Default)]
1372pub struct Holding {
1373    spans: BTreeMap<String, HeldSpan>,
1374    closed: bool,
1375}
1376
1377impl Holding {
1378    /// No member held yet.
1379    #[must_use]
1380    pub fn new() -> Self {
1381        Self::default()
1382    }
1383
1384    /// After `tracker` observed `event` at `at` and made `reports`: each
1385    /// member's count moved to where the tracker leaves it. Nothing after
1386    /// [`Holding::close`].
1387    ///
1388    /// An arrival, or a member token seen or gone, moves only its own
1389    /// member's count and those `reports` name: no other member enters or
1390    /// leaves a counting state at it, since only the start, the owner's
1391    /// state and a member's end do that, and an end is reported. So those
1392    /// cost one member each, and a start, an owner's move or a tick walks
1393    /// every member held (review-bot on PR #940).
1394    pub fn observe(&mut self, tracker: &Tracker, event: Event<'_>, reports: &[Report], at: Mono) {
1395        if self.closed {
1396            return;
1397        }
1398        for r in reports {
1399            if let Report::Ended { member, .. } = r {
1400                let s = self.spans.entry(member.clone()).or_default();
1401                s.stop(at);
1402                s.ended.get_or_insert(at);
1403            }
1404        }
1405        let touched = match event {
1406            Event::Arrival { member, .. }
1407            | Event::MemberSeen(member)
1408            | Event::MemberGone(member) => Some(member),
1409            Event::Start | Event::Owner(_) | Event::Tick => None,
1410        };
1411        match touched {
1412            Some(member) => {
1413                let mut names: Vec<&str> = vec![member];
1414                names.extend(reports.iter().map(Report::member));
1415                names.sort_unstable();
1416                names.dedup();
1417                for name in names {
1418                    self.move_one(tracker, name, at);
1419                }
1420            }
1421            None => {
1422                for name in tracker.held() {
1423                    self.move_one(tracker, name, at);
1424                }
1425                for (name, s) in &mut self.spans {
1426                    if s.counting() && tracker.state(name).is_none() {
1427                        s.stop(at);
1428                    }
1429                }
1430            }
1431        }
1432    }
1433
1434    /// `name`'s count moved to where the tracker leaves it: running while
1435    /// it is heard, missed or waited for, stopped otherwise or when the
1436    /// tracker no longer holds it.
1437    fn move_one(&mut self, tracker: &Tracker, name: &str, at: Mono) {
1438        let Some(state) = tracker.state(name) else {
1439            if let Some(s) = self.spans.get_mut(name) {
1440                s.stop(at);
1441            }
1442            return;
1443        };
1444        let counts = matches!(
1445            state,
1446            MemberState::Heard { .. } | MemberState::Missed { .. } | MemberState::Waiting { .. }
1447        );
1448        if !counts && !self.spans.contains_key(name) {
1449            // Held and not counted: listed, at nothing.
1450            self.spans.insert(name.to_owned(), HeldSpan::default());
1451            return;
1452        }
1453        let s = self.spans.entry(name.to_owned()).or_default();
1454        if counts {
1455            s.run(at);
1456        } else {
1457            s.stop(at);
1458        }
1459    }
1460
1461    /// The window's end at `at`: every count stops there, and nothing moves
1462    /// after.
1463    pub fn close(&mut self, at: Mono) {
1464        for s in self.spans.values_mut() {
1465            s.stop(at);
1466        }
1467        self.closed = true;
1468    }
1469
1470    /// Every member the tracker held in the window, in member order (byte
1471    /// order of the keys), with its span.
1472    pub fn spans(&self) -> impl Iterator<Item = (&str, &HeldSpan)> {
1473        self.spans.iter().map(|(k, s)| (k.as_str(), s))
1474    }
1475
1476    /// `member`'s span, when the tracker held it in the window.
1477    #[must_use]
1478    pub fn span(&self, member: &str) -> Option<&HeldSpan> {
1479        self.spans.get(member)
1480    }
1481}
1482
1483/// The premises every question reads first: the kind, then the declaration.
1484fn premise(kind: Kind, d: &Declaration) -> Result<Declared, Judged> {
1485    if kind != Kind::Stream {
1486        return Err(Judged::new(Answer::NotThisProfiles, Reason::Kind));
1487    }
1488    match d {
1489        Declaration::Invalid(_) => Err(Judged::new(Answer::Unobservable, Reason::Invalid)),
1490        Declaration::Declared(x) => Ok(*x),
1491        Declaration::NotThisProfiles | Declaration::Ignored => Ok(Declared::default()),
1492    }
1493}
1494
1495/// §5's first question: did this member meet its deadline over the window?
1496/// No is the finding.
1497#[must_use]
1498pub fn deadline_met(kind: Kind, d: &Declaration, w: &Window, a: &DeadlineAccount) -> Judged {
1499    use Answer as A;
1500    use Reason as R;
1501    let x = match premise(kind, d) {
1502        Ok(x) => x,
1503        Err(j) => return j,
1504    };
1505    let Some(deadline) = x.deadline else {
1506        return Judged::new(A::NotAsked, R::NoDeadline);
1507    };
1508    if x.below_period() {
1509        return Judged::new(A::Unobservable, R::BelowPeriod);
1510    }
1511    if w.across_face {
1512        return Judged::new(A::Unobservable, R::AcrossFace);
1513    }
1514    if a.missed_present > 0 {
1515        return if w.lost {
1516            Judged::new(A::Unobservable, R::Lost)
1517        } else {
1518            Judged::new(A::No, R::Missed)
1519        };
1520    }
1521    if a.missed_not_present > 0 {
1522        return Judged::new(A::Unobservable, R::OwnerNotPresent);
1523    }
1524    if a.ended {
1525        return Judged::new(A::NotAsked, R::Ended);
1526    }
1527    if a.held.is_zero() {
1528        return Judged::new(A::NotAsked, R::NotHeard);
1529    }
1530    if a.held <= deadline {
1531        return Judged::new(A::Unobservable, R::WindowTooShort);
1532    }
1533    Judged::new(A::Yes, R::Met)
1534}
1535
1536/// §5's second question: did the owner keep this member's period over the
1537/// window? No is the finding.
1538#[must_use]
1539pub fn period_kept(kind: Kind, d: &Declaration, w: &Window, p: PeriodVerdict) -> Judged {
1540    use Answer as A;
1541    use Reason as R;
1542    let x = match premise(kind, d) {
1543        Ok(x) => x,
1544        Err(j) => return j,
1545    };
1546    if x.period.is_none() {
1547        return Judged::new(A::NotAsked, R::NoPeriod);
1548    }
1549    if w.across_face {
1550        return Judged::new(A::Unobservable, R::AcrossFace);
1551    }
1552    match p {
1553        PeriodVerdict::NotHeard => Judged::new(A::NotAsked, R::NotHeard),
1554        PeriodVerdict::TooShort => Judged::new(A::Unobservable, R::WindowTooShort),
1555        PeriodVerdict::Kept => Judged::new(A::Yes, R::Kept),
1556        PeriodVerdict::NotKept if w.lost => Judged::new(A::Unobservable, R::Lost),
1557        PeriodVerdict::NotKept if !w.owner_present => {
1558            Judged::new(A::Unobservable, R::OwnerNotPresent)
1559        }
1560        PeriodVerdict::NotKept => Judged::new(A::No, R::NotKept),
1561    }
1562}
1563
1564/// §5's third question: did a sample of this member arrive expired? Yes is
1565/// the finding.
1566#[must_use]
1567pub fn lifespan_expired(kind: Kind, d: &Declaration, samples: &[Sample]) -> Judged {
1568    use Answer as A;
1569    use Reason as R;
1570    let x = match premise(kind, d) {
1571        Ok(x) => x,
1572        Err(j) => return j,
1573    };
1574    if x.lifespan.is_none() {
1575        return Judged::new(A::NotAsked, R::NoLifespan);
1576    }
1577    if samples.iter().any(|s| s.verdict == SampleVerdict::Expired) {
1578        return Judged::new(A::Yes, R::Expired);
1579    }
1580    if let Some(s) = samples
1581        .iter()
1582        .find(|s| s.verdict == SampleVerdict::Unobservable)
1583    {
1584        return Judged::new(A::Unobservable, s.reason);
1585    }
1586    if samples.iter().any(|s| s.verdict == SampleVerdict::Live) {
1587        return Judged::new(A::No, R::Live);
1588    }
1589    Judged::new(A::Unobservable, R::NoSample)
1590}
1591
1592/// §5's three questions, each with the pole that is its finding.
1593#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1594pub enum Question {
1595    /// Did this member meet its deadline? No is the finding.
1596    Deadline,
1597    /// Did the owner keep its period? No is the finding.
1598    Period,
1599    /// Did a sample arrive expired? Yes is the finding.
1600    Lifespan,
1601}
1602
1603impl Question {
1604    /// The fixture's token.
1605    #[must_use]
1606    pub fn as_str(self) -> &'static str {
1607        match self {
1608            Self::Deadline => "deadline",
1609            Self::Period => "period",
1610            Self::Lifespan => "lifespan",
1611        }
1612    }
1613
1614    /// Parses the fixture's token.
1615    #[must_use]
1616    pub fn parse(s: &str) -> Option<Self> {
1617        Some(match s {
1618            "deadline" => Self::Deadline,
1619            "period" => Self::Period,
1620            "lifespan" => Self::Lifespan,
1621            _ => return None,
1622        })
1623    }
1624
1625    /// The answer that is the finding.
1626    #[must_use]
1627    pub fn finding(self) -> Answer {
1628        match self {
1629            Self::Deadline | Self::Period => Answer::No,
1630            Self::Lifespan => Answer::Yes,
1631        }
1632    }
1633}
1634
1635/// §5's roll-up of one question over a resource or a run, read by its
1636/// finding (text 0.2, F-264), a member not asked, or not this profile's,
1637/// set aside: the finding when any member's answer is the finding; the
1638/// other pole when every member's answer is that pole or set aside, and at
1639/// least one is that pole; when every member is set aside, and there is at
1640/// least one, not this profile's when every one is, else not asked (text
1641/// 0.4, F-277); unobservable otherwise, an unobservable member and none the
1642/// finding, or no member at all.
1643#[must_use]
1644pub fn roll_up(question: Question, answers: impl IntoIterator<Item = Answer>) -> Answer {
1645    let finding = question.finding();
1646    let other = if finding == Answer::Yes {
1647        Answer::No
1648    } else {
1649        Answer::Yes
1650    };
1651    let (mut poles, mut unestablished) = (0u64, false);
1652    let (mut aside, mut not_asked) = (0u64, false);
1653    for a in answers {
1654        if a == finding {
1655            return finding;
1656        }
1657        match a {
1658            Answer::NotAsked => {
1659                aside += 1;
1660                not_asked = true;
1661            }
1662            Answer::NotThisProfiles => aside += 1,
1663            a if a == other => poles += 1,
1664            _ => unestablished = true,
1665        }
1666    }
1667    if unestablished {
1668        Answer::Unobservable
1669    } else if poles > 0 {
1670        other
1671    } else if aside == 0 {
1672        Answer::Unobservable
1673    } else if not_asked {
1674        Answer::NotAsked
1675    } else {
1676        Answer::NotThisProfiles
1677    }
1678}
1679
1680/// §5's roll-up with its reason (text 0.5, F-279): [`roll_up`]'s answer
1681/// over `members`, each its key, its answer and its reason, and the first
1682/// member giving that answer in byte order of the keys, with its reason,
1683/// whatever order they come in; `None` over no member. Over one member or
1684/// more the answer is always some member's: `unobservable` is the roll-up's
1685/// only when a member's is, or when there is none.
1686pub fn roll_up_first<K: AsRef<str>, R>(
1687    question: Question,
1688    members: impl IntoIterator<Item = (K, Answer, R)>,
1689) -> (Answer, Option<(K, R)>) {
1690    let members: Vec<(K, Answer, R)> = members.into_iter().collect();
1691    let answer = roll_up(question, members.iter().map(|(_, a, _)| *a));
1692    let first = members
1693        .into_iter()
1694        .filter(|(_, a, _)| *a == answer)
1695        .min_by(|(x, _, _), (y, _, _)| x.as_ref().as_bytes().cmp(y.as_ref().as_bytes()))
1696        .map(|(k, _, r)| (k, r));
1697    (answer, first)
1698}
1699
1700#[cfg(test)]
1701mod tests {
1702    use super::*;
1703    use serde_json::json;
1704
1705    fn ann(pairs: &[(&str, Value)]) -> BTreeMap<String, Value> {
1706        pairs
1707            .iter()
1708            .map(|(k, v)| ((*k).to_owned(), v.clone()))
1709            .collect()
1710    }
1711
1712    fn ms(n: u64) -> Mono {
1713        Mono::after(Duration::from_millis(n))
1714    }
1715
1716    #[test]
1717    fn a_value_is_a_whole_number_of_milliseconds_above_zero() {
1718        let d = |v: Value| declaration(Kind::Stream, &ann(&[(DEADLINE_MS, v)]));
1719        assert_eq!(
1720            d(json!(100)).declared().and_then(|x| x.deadline),
1721            Some(Duration::from_millis(100))
1722        );
1723        assert_eq!(
1724            d(json!(100.0)).declared().and_then(|x| x.deadline),
1725            Some(Duration::from_millis(100))
1726        );
1727        for bad in [
1728            json!(0),
1729            json!(-0.0),
1730            json!(-1),
1731            json!(1.5),
1732            json!(MAX_MS + 1),
1733        ] {
1734            assert_eq!(d(bad), Declaration::Invalid(vec![Invalid::DeadlineValue]));
1735        }
1736        assert_eq!(
1737            declaration(Kind::State, &ann(&[(DEADLINE_MS, json!("x"))])),
1738            Declaration::Ignored,
1739            "the kind first"
1740        );
1741    }
1742
1743    #[test]
1744    fn the_bound_has_a_millisecond_floor() {
1745        assert_eq!(
1746            detection_bound(Duration::from_millis(100)),
1747            Duration::from_millis(2)
1748        );
1749        assert_eq!(detection_bound(Duration::from_millis(30)), BOUND_FLOOR);
1750        assert_eq!(
1751            detection_bound(Duration::from_millis(75)),
1752            Duration::from_micros(1500)
1753        );
1754    }
1755
1756    #[test]
1757    fn a_paused_commander_is_missed_once_then_met() {
1758        let mut t = Tracker::new(Duration::from_millis(100), Some(1), ["cmd"]);
1759        t.observe(ms(0), Event::Owner(OwnerState::Present));
1760        t.observe(ms(0), Event::Start);
1761        let arrive = |t: &mut Tracker, at| {
1762            t.observe(
1763                ms(at),
1764                Event::Arrival {
1765                    member: "cmd",
1766                    expired: false,
1767                },
1768            )
1769        };
1770        assert!(arrive(&mut t, 10).is_empty());
1771        assert_eq!(t.next_due(), Some(ms(110)));
1772        let r = t.observe(ms(111), Event::Tick);
1773        assert_eq!(r.len(), 1);
1774        assert_eq!(r[0].as_str(), "missed");
1775        assert!(t.observe(ms(500), Event::Tick).is_empty(), "edge-triggered");
1776        let r = arrive(&mut t, 600);
1777        assert_eq!(r.len(), 1);
1778        assert_eq!(r[0].as_str(), "met");
1779    }
1780
1781    #[test]
1782    fn a_clock_ahead_beyond_epsilon_stays_unobservable() {
1783        let d = declaration(Kind::Stream, &ann(&[(LIFESPAN_MS, json!(100))]));
1784        let mut r = LifespanReader::new(Kind::Stream, &d, Some(Duration::from_millis(10)), [7]);
1785        let at = |s: f64| {
1786            Some(Stamped {
1787                age: StampAge::from_secs_f64(s),
1788                id: 7,
1789            })
1790        };
1791        assert_eq!(r.judge(at(0.05)).reason, Reason::Live);
1792        assert_eq!(r.judge(at(-0.05)).reason, Reason::ClockDisagrees);
1793        assert_eq!(r.judge(at(0.05)).reason, Reason::ClockDisagrees);
1794        assert_eq!(
1795            r.judge(Some(Stamped {
1796                age: StampAge::from_secs_f64(0.5),
1797                id: 8
1798            }))
1799            .reason,
1800            Reason::ForeignStamp
1801        );
1802    }
1803
1804    #[test]
1805    fn the_roll_up_reads_each_questions_finding() {
1806        let d = Question::Deadline;
1807        assert_eq!(roll_up(d, [Answer::Yes, Answer::NotAsked]), Answer::Yes);
1808        assert_eq!(
1809            roll_up(d, [Answer::Yes, Answer::Unobservable]),
1810            Answer::Unobservable
1811        );
1812        assert_eq!(roll_up(d, [Answer::Unobservable, Answer::No]), Answer::No);
1813        assert_eq!(roll_up(d, []), Answer::Unobservable);
1814        let l = Question::Lifespan;
1815        assert_eq!(roll_up(l, [Answer::No, Answer::Yes]), Answer::Yes, "F-264");
1816        assert_eq!(roll_up(l, [Answer::No, Answer::No]), Answer::No);
1817        // Every member set aside (text 0.4, F-277): nobody put the question.
1818        assert_eq!(roll_up(l, [Answer::NotAsked]), Answer::NotAsked);
1819        assert_eq!(
1820            roll_up(l, [Answer::NotThisProfiles, Answer::NotAsked]),
1821            Answer::NotAsked
1822        );
1823        assert_eq!(
1824            roll_up(Question::Period, [Answer::NotThisProfiles]),
1825            Answer::NotThisProfiles
1826        );
1827        assert_eq!(
1828            roll_up(d, [Answer::NotAsked, Answer::Unobservable]),
1829            Answer::Unobservable,
1830            "an unobservable member is never set aside"
1831        );
1832    }
1833
1834    /// Text 0.5, F-279: the first member giving the answer, in byte order
1835    /// of the keys, whatever order they come in; over no member, none.
1836    #[test]
1837    fn a_roll_ups_reason_is_its_first_members_in_byte_order() {
1838        let d = Question::Deadline;
1839        let (a, first) = roll_up_first(
1840            d,
1841            [
1842                ("axis/a", Answer::Unobservable, Reason::OwnerNotPresent),
1843                ("axis/B", Answer::Unobservable, Reason::WindowTooShort),
1844            ],
1845        );
1846        assert_eq!(
1847            (a, first),
1848            (
1849                Answer::Unobservable,
1850                Some(("axis/B", Reason::WindowTooShort))
1851            ),
1852            "B (0x42) before a (0x61): bytes, never a locale"
1853        );
1854        let (a, first) = roll_up_first(
1855            d,
1856            [
1857                ("axis/a", Answer::Unobservable, Reason::Lost),
1858                ("cmd", Answer::No, Reason::Missed),
1859            ],
1860        );
1861        assert_eq!(
1862            (a, first),
1863            (Answer::No, Some(("cmd", Reason::Missed))),
1864            "the first member giving the answer, not the first member"
1865        );
1866        let (a, first) = roll_up_first(
1867            Question::Lifespan,
1868            [
1869                ("a", Answer::NotThisProfiles, Reason::Kind),
1870                ("b", Answer::NotAsked, Reason::NoLifespan),
1871            ],
1872        );
1873        assert_eq!(
1874            (a, first),
1875            (Answer::NotAsked, Some(("b", Reason::NoLifespan)))
1876        );
1877        let (a, first) = roll_up_first(d, std::iter::empty::<(&str, Answer, Reason)>());
1878        assert_eq!((a, first), (Answer::Unobservable, None));
1879    }
1880
1881    fn holding_of(t: &mut Tracker, h: &mut Holding, at: u64, e: Event<'_>) -> Vec<Report> {
1882        let r = t.observe(ms(at), e);
1883        h.observe(t, e, &r, ms(at));
1884        r
1885    }
1886
1887    /// Text 0.5, F-278: a known member never heard is held only while it
1888    /// is waited for; its owner's absence stops the count, its presence
1889    /// again starts it.
1890    #[test]
1891    fn a_known_member_is_held_only_while_it_is_waited_for() {
1892        let mut t = Tracker::new(Duration::from_millis(500), Some(1), ["cmd"]);
1893        let mut h = Holding::new();
1894        holding_of(&mut t, &mut h, 0, Event::Owner(OwnerState::Present));
1895        holding_of(&mut t, &mut h, 0, Event::Start);
1896        holding_of(&mut t, &mut h, 150, Event::Owner(OwnerState::Unconfirmed));
1897        holding_of(&mut t, &mut h, 330, Event::Owner(OwnerState::Absent));
1898        let r = holding_of(&mut t, &mut h, 3000, Event::Tick);
1899        assert!(r.is_empty(), "no miss: the wait stopped before its due");
1900        h.close(ms(3000));
1901        assert_eq!(
1902            h.span("cmd").map(|s| s.held_to(ms(3000))),
1903            Some(Duration::from_millis(330)),
1904            "the unconfirmed while waits on (§2.5), the absence stops it"
1905        );
1906        // Present again: a new stretch, the longer one held (text 0.5).
1907        let mut t = Tracker::new(Duration::from_millis(500), Some(1), ["cmd"]);
1908        let mut h = Holding::new();
1909        holding_of(&mut t, &mut h, 0, Event::Owner(OwnerState::Present));
1910        holding_of(&mut t, &mut h, 0, Event::Start);
1911        holding_of(&mut t, &mut h, 330, Event::Owner(OwnerState::Absent));
1912        holding_of(&mut t, &mut h, 1000, Event::Owner(OwnerState::Present));
1913        let r = holding_of(&mut t, &mut h, 1501, Event::Tick);
1914        assert_eq!(r.len(), 1, "{r:?}");
1915        h.close(ms(2000));
1916        assert_eq!(
1917            h.span("cmd").map(|s| s.held_to(ms(2000))),
1918            Some(Duration::from_millis(1000))
1919        );
1920    }
1921
1922    /// Text 0.5, the maintainer's ruling on ME: two waits never sum. Each
1923    /// shorter than the deadline, 300 and 400 ms, 700 in all: neither could
1924    /// have shown a miss, so the member is held 400, `window_too_short`.
1925    #[test]
1926    fn two_short_waits_hold_the_longer_never_their_sum() {
1927        let mut t = Tracker::new(Duration::from_millis(500), Some(1), ["cmd"]);
1928        let mut h = Holding::new();
1929        holding_of(&mut t, &mut h, 0, Event::Owner(OwnerState::Present));
1930        holding_of(&mut t, &mut h, 0, Event::Start);
1931        holding_of(&mut t, &mut h, 300, Event::Owner(OwnerState::Absent));
1932        holding_of(&mut t, &mut h, 1000, Event::Owner(OwnerState::Present));
1933        holding_of(&mut t, &mut h, 1400, Event::Owner(OwnerState::Absent));
1934        let r = holding_of(&mut t, &mut h, 3000, Event::Tick);
1935        assert!(r.is_empty(), "no miss in either wait: {r:?}");
1936        h.close(ms(3000));
1937        let held = h.span("cmd").map(|s| s.held_to(ms(3000))).unwrap();
1938        assert_eq!(held, Duration::from_millis(400));
1939        let d = declaration(
1940            Kind::Stream,
1941            &ann(&[(DEADLINE_MS, json!(500)), (PERIOD_MS, json!(100))]),
1942        );
1943        let account = DeadlineAccount {
1944            held,
1945            ..DeadlineAccount::default()
1946        };
1947        let j = deadline_met(Kind::Stream, &d, &Window::default(), &account);
1948        assert_eq!(
1949            (j.answer, j.reason),
1950            (Answer::Unobservable, Reason::WindowTooShort)
1951        );
1952    }
1953
1954    /// Text 0.5, F-280: a member that ends and is heard again is held over
1955    /// its first life alone.
1956    #[test]
1957    fn a_member_heard_again_is_held_over_its_first_life() {
1958        let mut t =
1959            Tracker::new(Duration::from_millis(500), Some(4), Vec::<String>::new()).with_epoch();
1960        let mut h = Holding::new();
1961        holding_of(&mut t, &mut h, 0, Event::Owner(OwnerState::Present));
1962        holding_of(&mut t, &mut h, 0, Event::Start);
1963        holding_of(&mut t, &mut h, 0, Event::MemberSeen("axis/x"));
1964        let arrival = Event::Arrival {
1965            member: "axis/x",
1966            expired: false,
1967        };
1968        for at in [100, 500, 900] {
1969            holding_of(&mut t, &mut h, at, arrival);
1970        }
1971        let r = holding_of(&mut t, &mut h, 1100, Event::MemberGone("axis/x"));
1972        assert_eq!(r.len(), 1, "ended, and no miss: {r:?}");
1973        holding_of(&mut t, &mut h, 2000, Event::MemberSeen("axis/x"));
1974        holding_of(&mut t, &mut h, 2000, arrival);
1975        holding_of(&mut t, &mut h, 4000, arrival);
1976        h.close(ms(5000));
1977        let s = h.span("axis/x").copied().expect("held");
1978        assert_eq!(s.ended(), Some(ms(1100)));
1979        assert_eq!(s.held_to(ms(5000)), Duration::from_millis(1000));
1980    }
1981}