Skip to main content

zenkey_model/
budget.rs

1//! The population budget (core §2.7, 0.24; #735): a templated resource's
2//! bound in one instance, what its members and its live members are, what
3//! an event's `rate` bounds, and the pure judgement of a reading against
4//! them, in four states and a reason.
5//!
6//! ```text
7//! bound(contract, stated…)              ─▶ Untemplated │ NoCeiling │ Of(n)
8//! lossless(delivery)                    ─▶ lossless or not, + reason (0.25)
9//! population(kind, bound, retention, r) ─▶ exceeds │ within │ unobservable │ not_asked, + reason
10//! rate(rate, occurrences)               ─▶ the same four, + reason
11//! ```
12//!
13//! Each judgement answers "does this instance exceed its budget here?", so
14//! its finding is the yes: [`Verdict::Exceeds`]. There is no I/O and no
15//! clock here. A reader counts what it read (the keys an owner's GET
16//! answered with a value and whether it ran to its end; the instants a
17//! window heard each member, how long it listened, what it lost and
18//! whether the owner stayed present) and hands it over as values; the
19//! fixtures in `spec/conformance/budget/` pin the rest.
20//!
21//! **"Lost no delivery" is established, never assumed** (0.25, #740): a
22//! reader can know that it lost a delivery, never that it lost none.
23//! [`lossless`] decides it from the resource's declared QoS, the reader's
24//! own loss, whether its receive path stalled (0.27, #753) and miss
25//! detection; a window's `lossless` and an occurrence set's are its
26//! answer.
27
28use std::collections::BTreeMap;
29use std::fmt;
30use std::time::Duration;
31
32use crate::authoring::{Congestion, Kind, Reliability};
33use crate::contract::{Body, Rate, Resource};
34
35/// The no-ceiling cardinality, 2^32−1 (§2.2): no bound, never a population
36/// to budget with.
37pub const NO_CEILING: u64 = 4_294_967_295;
38
39/// How long a stream member stays live after the owner last published on
40/// it (§2.7): an hour.
41pub const STREAM_LIVENESS: Duration = Duration::from_secs(3600);
42
43/// zenoh 1.10.1's default link lease (`transport/link/tx/lease`, 10 s;
44/// zm-1.10.2-r1's too): a link gone silent withdraws the owner's token only when it runs out
45/// (Appendix B). A window's owner must stay present for one lease after
46/// the window's end (§2.7, 0.25), and a tool watches its tokens past the
47/// end for the longer of the lease and `wait_before_close`, plus the reply
48/// timeout ([`presence_tail`], observer §5.2).
49pub const DEFAULT_LEASE: Duration = Duration::from_secs(10);
50
51/// zenoh 1.10.1's default keep-alive (`transport/link/tx/keep_alive`, 4;
52/// zm-1.10.2-r1's too): a session sends a keep-alive every lease ÷ 4 when it has nothing else to
53/// send, so a peer that stops hearing from it closes the transport once a
54/// lease passes (§2.7, 0.27).
55pub const DEFAULT_KEEP_ALIVE: u32 = 4;
56
57/// zenoh 1.10.1's default `wait_before_close`
58/// (`transport/link/tx/queue/congestion_control/block/wait_before_close`,
59/// 5 s): how long a router's push of a `reliable`, `block` sample waits for
60/// room in a reader's queue before it closes the transport (Appendix B).
61///
62/// A deployment on another binding states its own: zm-1.10.2-r1, the fork
63/// zenoh-modem builds on, defaults to 10 s, its lease (#1011). A tool takes
64/// the deployment's word for it (zenctl's `--wait-before-close`, or the
65/// `[transport]` of the routers' `link.v2` face policy: [`Routers::of`]),
66/// never its own session's configuration, which states how long the
67/// tool's own pushes wait and says nothing of its routers'.
68pub const DEFAULT_WAIT_BEFORE_CLOSE: Duration = Duration::from_secs(5);
69
70/// The routers' link settings a window's reader reads by (§2.7, observer
71/// §5.2): their lease, keep-alives and `wait_before_close`. The
72/// deployment's word: a `link.v2` face policy's `[transport]`, which its
73/// routers run (`link.v2` §2.16; [`Routers::of`]), and zenoh 1.10.1's
74/// defaults where it gives none ([`Routers::default`], #1011's item 3).
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub struct Routers {
77    pub lease: Duration,
78    pub keep_alive: u32,
79    pub wait_before_close: Duration,
80}
81
82impl Default for Routers {
83    /// zenoh 1.10.1's: a 10 s lease, 4 keep-alives, a 5 s
84    /// `wait_before_close`.
85    fn default() -> Self {
86        Routers {
87            lease: DEFAULT_LEASE,
88            keep_alive: DEFAULT_KEEP_ALIVE,
89            wait_before_close: DEFAULT_WAIT_BEFORE_CLOSE,
90        }
91    }
92}
93
94impl Routers {
95    /// What routers that run `transport` run: a face policy's
96    /// `[transport]`, every key resolved (`link.v2` §2.1).
97    #[must_use]
98    pub fn of(transport: &crate::link::Transport) -> Routers {
99        Routers {
100            lease: Duration::from_millis(transport.lease_ms),
101            keep_alive: u32::try_from(transport.keep_alive).unwrap_or(u32::MAX),
102            wait_before_close: Duration::from_millis(transport.wait_before_close_ms),
103        }
104    }
105
106    /// [`stall_bound`] of these routers.
107    #[must_use]
108    pub fn stall_bound(&self) -> Duration {
109        stall_bound(self.wait_before_close, self.lease, self.keep_alive)
110    }
111
112    /// [`presence_tail`] of these routers, with the reader's `timeout`.
113    #[must_use]
114    pub fn presence_tail(&self, timeout: Duration) -> Duration {
115        presence_tail(self.lease, self.wait_before_close, timeout)
116    }
117}
118
119/// The longest a window's reader may stall without a router giving up on
120/// it (§2.7, 0.27): the transport's `wait_before_close`, or its lease less
121/// one keep-alive interval when that is shorter — the longest a router
122/// waits on the reader's full queue, and the longest it may hear nothing
123/// from the reader before its lease runs out. 5 s with zenoh 1.10.1's
124/// defaults (and 7.5 s for the lease); 7.5 s, the lease's, with
125/// zm-1.10.2-r1's, whose `wait_before_close` is 10 s. The interval is rounded up to a whole
126/// millisecond, which shortens the bound; a `keep_alive` of 0 is taken as
127/// 1.
128#[must_use]
129pub fn stall_bound(wait_before_close: Duration, lease: Duration, keep_alive: u32) -> Duration {
130    let interval = lease.as_millis().div_ceil(u128::from(keep_alive.max(1)));
131    let interval = Duration::from_millis(u64::try_from(interval).unwrap_or(u64::MAX));
132    wait_before_close.min(lease.saturating_sub(interval))
133}
134
135/// How long after a window's end a tool watches the owner's instance
136/// tokens (observer §5.2, `[Sc: budget.md §2]`): the longer of one lease
137/// and the routers' `wait_before_close`, plus the reply timeout.
138///
139/// A link gone silent withdraws the owner's token one lease after it went
140/// silent, and a push that cannot queue within `wait_before_close` closes
141/// its transport (Appendix B), so a router that waits that long before it
142/// closes one tells the withdrawal that late. The reply timeout allows for
143/// the withdrawal's transit. With zenoh 1.10.1's defaults, a 10 s lease
144/// against a 5 s `wait_before_close`, it is the lease plus the timeout; a
145/// 1 s lease beside that `wait_before_close` watches 5 s plus the timeout
146/// (observer text 0.6, zk2py round 85's F-320). zm-1.10.2-r1's 10 s
147/// `wait_before_close` beside a 1 s lease watches 10 s plus the timeout, so
148/// a deployment on it states its `wait_before_close` (#1011).
149#[must_use]
150pub fn presence_tail(lease: Duration, wait_before_close: Duration, timeout: Duration) -> Duration {
151    lease.max(wait_before_close).saturating_add(timeout)
152}
153
154/// What a window's path declares and what its reader saw of it, for "lost
155/// no delivery" (§2.7, 0.25).
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157pub struct Delivery {
158    /// The resource's declared reliability (§2.4).
159    pub reliability: Reliability,
160    /// The resource's declared congestion control (§2.4).
161    pub congestion: Congestion,
162    /// Deliveries the window's own reader lost: its queue overflowed or
163    /// fell behind, or a cap kept them out of its count.
164    pub reader_lost: u64,
165    /// Whether the reader's receive path stopped long enough for a router
166    /// to give up on it, over the window and one lease after it (0.27).
167    pub stall: ReaderStall,
168    pub miss_detection: MissDetection,
169}
170
171/// What a window's reader saw of its own receive path, over the window and
172/// one lease after it (§2.7, 0.27, #753). A reader stalled longer than the
173/// transport's `wait_before_close` loses what its router queued for it,
174/// and may never see the owner's token withdrawn: only a token it had
175/// received is withdrawn when its own transport closes (Appendix B).
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
177pub struct ReaderStall {
178    /// The greatest gap between two ticks of the reader's monotonic ticker,
179    /// the gap still open when it was read included: how long its process
180    /// stopped at most. A ticker on a thread of its own does not see
181    /// zenoh's receive threads blocked while the rest of the process runs.
182    pub gap: Duration,
183    /// The longest stall the window tolerates: [`stall_bound`].
184    pub bound: Duration,
185    /// Whether the reader's session saw one of its own transports close:
186    /// zenoh's transport events (unstable in 1.10.1). It sees a router
187    /// giving up on a reader whose receive threads were blocked, which no
188    /// ticker sees. `false` where the reader does not observe them.
189    pub transport_closed: bool,
190}
191
192impl ReaderStall {
193    /// Stalled: a transport of the reader's session closed, or its ticker
194    /// saw a gap longer than the bound. A gap of exactly the bound is not.
195    #[must_use]
196    pub fn stalled(&self) -> bool {
197        self.transport_closed || self.gap > self.bound
198    }
199}
200
201/// Miss detection over a window (§2.5, §2.7): counted only where the
202/// resource declares it and the window's subscription uses it.
203#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
204pub struct MissDetection {
205    /// The resource declares `history.miss_detection_ms`: its owner numbers
206    /// its samples.
207    pub declared: bool,
208    /// The window's subscription detects misses.
209    pub used: bool,
210    /// How many misses it detected.
211    pub misses: u64,
212}
213
214/// Why a window is, or is not, shown to have lost no delivery: the
215/// fixture's reason class, in the order [`lossless`] chooses it.
216#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
217pub enum LossReason {
218    /// Not lossless: the reader itself lost deliveries.
219    ReaderLost,
220    /// Not lossless: the reader's receive path stalled longer than its
221    /// router waits on it, or its own transport closed (0.27).
222    ReaderStalled,
223    /// Not lossless: the subscription detected missed samples.
224    MissesDetected,
225    /// Not lossless: best effort, so a sample dropped anywhere on the path
226    /// leaves no trace, whatever the congestion control.
227    BestEffort,
228    /// Not lossless: reliable with `drop`, so a full queue drops a sample
229    /// and leaves no trace.
230    CongestionDrop,
231    /// Lossless: reliable with `block`, which no router queue drops; a
232    /// failed push closes the transport, and the owner's token goes.
233    ReliableBlock,
234}
235
236impl LossReason {
237    /// The fixture's token.
238    #[must_use]
239    pub fn as_str(self) -> &'static str {
240        match self {
241            Self::ReaderLost => "reader_lost",
242            Self::ReaderStalled => "reader_stalled",
243            Self::MissesDetected => "misses_detected",
244            Self::BestEffort => "best_effort",
245            Self::CongestionDrop => "congestion_drop",
246            Self::ReliableBlock => "reliable_block",
247        }
248    }
249
250    /// Whether this reason makes the window lossless.
251    #[must_use]
252    pub fn is_lossless(self) -> bool {
253        self == Self::ReliableBlock
254    }
255}
256
257impl fmt::Display for LossReason {
258    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259        f.write_str(self.as_str())
260    }
261}
262
263/// "Did this window lose no delivery?" (§2.7, 0.25), from what its reader
264/// can see. Lossless only when its reader lost none — nothing lost in its
265/// own queue or past a cap, and its receive path not stalled (0.27) — and
266/// the path could not drop one silently: the resource is `reliable` with
267/// `block`. A detected miss is a loss; none detected establishes nothing,
268/// since zenoh-ext takes a publisher's first sample heard as its start
269/// (Appendix B), and counts only where the resource declares miss
270/// detection and the subscription uses it.
271///
272/// The order a reason is chosen in: the reader's own loss; the reader
273/// stalled; a miss detected; best effort; reliable with `drop`; else
274/// lossless, reliable with `block`.
275#[must_use]
276pub fn lossless(d: &Delivery) -> LossReason {
277    let m = d.miss_detection;
278    if d.reader_lost > 0 {
279        LossReason::ReaderLost
280    } else if d.stall.stalled() {
281        LossReason::ReaderStalled
282    } else if m.declared && m.used && m.misses > 0 {
283        LossReason::MissesDetected
284    } else if d.reliability == Reliability::BestEffort {
285        LossReason::BestEffort
286    } else if d.congestion == Congestion::Drop {
287        LossReason::CongestionDrop
288    } else {
289        LossReason::ReliableBlock
290    }
291}
292
293/// The [`Delivery`] of a stream, state or event resource, from its
294/// declared QoS and `history`, with what the reader lost, what it saw of
295/// its own receive path, and what its subscription detected (`misses`:
296/// `None` when it does not detect misses). `None` for an operation.
297#[must_use]
298pub fn delivery_of(
299    r: &Resource,
300    reader_lost: u64,
301    stall: ReaderStall,
302    misses: Option<u64>,
303) -> Option<Delivery> {
304    match &r.body {
305        Body::Data(d) => Some(Delivery {
306            reliability: d.reliability,
307            congestion: d.congestion,
308            reader_lost,
309            stall,
310            miss_detection: MissDetection {
311                declared: d
312                    .history
313                    .as_ref()
314                    .is_some_and(|h| h.miss_detection_ms.is_some()),
315                used: misses.is_some(),
316                misses: misses.unwrap_or(0),
317            },
318        }),
319        Body::Operation(_) => None,
320    }
321}
322
323/// A templated resource's bound in an instance (§2.7).
324#[derive(Debug, Clone, Copy, PartialEq, Eq)]
325pub enum Bound {
326    /// The template has no parameters, so no `cardinality`: one member by
327    /// construction, and nothing to budget.
328    Untemplated,
329    /// The no-ceiling value, from the contract or a descriptor (§2.2).
330    NoCeiling,
331    /// A bound of `n` live members.
332    Of(u64),
333}
334
335impl Bound {
336    /// The fixture's form: an integer, `"no_ceiling"` or `"untemplated"`.
337    #[must_use]
338    pub fn token(self) -> String {
339        match self {
340            Self::Untemplated => "untemplated".to_owned(),
341            Self::NoCeiling => "no_ceiling".to_owned(),
342            Self::Of(n) => n.to_string(),
343        }
344    }
345
346    /// The bound, when it is one.
347    #[must_use]
348    pub fn limit(self) -> Option<u64> {
349        match self {
350            Self::Of(n) => Some(n),
351            _ => None,
352        }
353    }
354}
355
356impl fmt::Display for Bound {
357    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
358        match self {
359            Self::Untemplated => f.write_str("no bound (a template without parameters)"),
360            Self::NoCeiling => f.write_str("no ceiling (4294967295)"),
361            Self::Of(n) => write!(f, "{n}"),
362        }
363    }
364}
365
366/// The bound of a resource whose contract declares `contract`, across the
367/// instances exposing it, each stating its own lowered value or none
368/// (`stated`, one entry per instance; core §2.7, §3.3).
369///
370/// - A stated value from 1 to the contract's applies to its instance;
371///   any other is D007's, and the contract's applies instead.
372/// - Several instances (a re-mint's overlap) share one population, since a
373///   key names no instance: the greatest of their bounds applies, so a
374///   finding never rests on a bound one of them did not state.
375/// - No instance: the contract's.
376/// - 4294967295, whichever source gives it, is no ceiling.
377#[must_use]
378pub fn bound(contract: Option<u64>, stated: impl IntoIterator<Item = Option<u64>>) -> Bound {
379    let Some(c) = contract else {
380        return Bound::Untemplated;
381    };
382    let n = stated
383        .into_iter()
384        .map(|s| match s {
385            Some(n) if (1..=c).contains(&n) => n,
386            _ => c,
387        })
388        .max()
389        .unwrap_or(c);
390    if n == NO_CEILING {
391        Bound::NoCeiling
392    } else {
393        Bound::Of(n)
394    }
395}
396
397/// [`bound`] of a resource of a contract.
398#[must_use]
399pub fn bound_of(r: &Resource, stated: impl IntoIterator<Item = Option<u64>>) -> Bound {
400    bound(r.cardinality, stated)
401}
402
403/// An event's retention, when the resource declares one.
404#[must_use]
405pub fn retention_of(r: &Resource) -> Option<Duration> {
406    match &r.body {
407        Body::Data(d) => d.retention_s.map(Duration::from_secs),
408        Body::Operation(_) => None,
409    }
410}
411
412/// An event's rate, when the resource declares one.
413#[must_use]
414pub fn rate_of(r: &Resource) -> Option<Rate> {
415    match &r.body {
416        Body::Data(d) => d.rate,
417        Body::Operation(_) => None,
418    }
419}
420
421impl Rate {
422    /// What the rate allows per member (§2.7): at most `n` occurrences
423    /// within any period this long.
424    #[must_use]
425    pub fn limit(self) -> (u32, Duration) {
426        const HOUR: Duration = Duration::from_secs(3600);
427        match self {
428            Self::Rare => (1, HOUR),
429            Self::Low => (1, Duration::from_secs(60)),
430            Self::Burst(n) => (n, HOUR),
431        }
432    }
433}
434
435/// How long a member of a resource of `kind` stays live after its last
436/// put or occurrence (§2.7): a stream's for an hour, an event's for its
437/// retention. A state member is live while its key has a value, which a
438/// window cannot see; an operation has no live member a reading counts.
439#[must_use]
440pub fn liveness(kind: Kind, retention: Option<Duration>) -> Option<Duration> {
441    match kind {
442        Kind::Stream => Some(STREAM_LIVENESS),
443        Kind::Event => retention,
444        Kind::State | Kind::Operation => None,
445    }
446}
447
448/// What a reader read of a resource's members (§2.7).
449#[derive(Debug, Clone, PartialEq, Eq)]
450pub enum Reading {
451    /// An owner's S4 GET over a state resource (core §4.2): how many keys
452    /// it answered with a value (a `reply_del` is no member), and whether
453    /// it ran to its final reply, with no error reply, a timeout included.
454    Get { members: u64, complete: bool },
455    /// A subscription window over a stream or an event.
456    Window(Window),
457}
458
459/// A subscription window over a stream or an event, as a population
460/// reading (§2.7). It is complete — it heard every member live at its end —
461/// when it lasted at least one liveness span, lost no delivery, and the
462/// owner was present throughout.
463#[derive(Debug, Clone, PartialEq, Eq, Default)]
464pub struct Window {
465    /// The instants each member was heard, on one clock (the reader's
466    /// receive clock), from any origin. An event's member is its key
467    /// without its last chunk, its occurrence chunk (core §2.7).
468    pub heard: BTreeMap<String, Vec<Duration>>,
469    /// How long the window listened, counted from when its subscription is
470    /// taken to have reached the owner: its declaration plus the reader's
471    /// reply timeout (0.25).
472    pub listened: Duration,
473    /// Whether it is shown to have lost no delivery: [`lossless`]'s answer
474    /// (0.25).
475    pub lossless: bool,
476    /// Whether the owner was present, an instance token of its held, from
477    /// the window's start until one lease after its end (0.25): false when
478    /// it joined, left or re-minted, or a path to it failed.
479    pub present: bool,
480}
481
482/// The occurrences of an event a window heard, for its `rate` (§2.7), with
483/// the window's premises as a [`Window`] has them.
484#[derive(Debug, Clone, PartialEq, Eq, Default)]
485pub struct Occurrences {
486    /// How long the window listened, counted as [`Window::listened`] is.
487    pub listened: Duration,
488    /// Whether it is shown to have lost no delivery: [`lossless`]'s answer
489    /// (0.25).
490    pub lossless: bool,
491    /// Whether the owner was present from the window's start until one
492    /// lease after its end (0.25).
493    pub present: bool,
494    /// Per member, the instants of its occurrences, measured between the
495    /// occurrences' stamps of one clock, or on the reader's receive clock.
496    pub members: BTreeMap<String, Vec<Duration>>,
497}
498
499/// The answer to "does this instance exceed its budget here?" (§2.7). The
500/// finding is the yes.
501#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
502pub enum Verdict {
503    /// The finding: more live members than the bound, or an event's
504    /// occurrences beyond its rate.
505    Exceeds,
506    /// Clean: a reading that can show the budget kept shows it kept.
507    Within,
508    /// The question was put, and the reading could not answer it.
509    Unobservable,
510    /// Nobody put the question, or it has no premise here.
511    NotAsked,
512}
513
514impl Verdict {
515    /// The fixture's token.
516    #[must_use]
517    pub fn as_str(self) -> &'static str {
518        match self {
519            Self::Exceeds => "exceeds",
520            Self::Within => "within",
521            Self::Unobservable => "unobservable",
522            Self::NotAsked => "not_asked",
523        }
524    }
525}
526
527impl fmt::Display for Verdict {
528    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
529        f.write_str(self.as_str())
530    }
531}
532
533/// Why a verdict is what it is: the fixture's reason class.
534#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
535pub enum Reason {
536    /// Exceeds: more members than the bound, in any reading.
537    OverBound,
538    /// Exceeds: `n + 1` occurrences of one member less than the period
539    /// apart.
540    RateExceeded,
541    /// Within: a complete reading — a GET that ran to its final reply, or a
542    /// window of a whole liveness span, lossless, the owner present
543    /// throughout — counted at least one member, and no more than the
544    /// bound.
545    Complete,
546    /// Within: a window of at least one period, nothing lost, an
547    /// occurrence heard, none beyond the rate.
548    RateKept,
549    /// Unobservable: no member, or no occurrence, was read: an empty reply
550    /// set is never a verdict (core O5).
551    Empty,
552    /// Unobservable: the GET ended at its timeout, or with an error reply.
553    Incomplete,
554    /// Unobservable: the window is not shown to have lost no delivery
555    /// ([`lossless`]: its reader lost one, a miss was detected, or its QoS
556    /// drops silently).
557    Lossy,
558    /// Unobservable: the window was shorter than the rate's period, or than
559    /// the population's liveness span.
560    WindowTooShort,
561    /// Unobservable: the owner was not present throughout the window and
562    /// one lease after it: it joined, left or re-minted while the window
563    /// listened, or a path to it failed.
564    OwnerAbsent,
565    /// Unobservable: a reading that does not count this kind's members (a
566    /// window of a state, a GET of a stream or an event).
567    ReadingKind,
568    /// Not asked: the no-ceiling bound.
569    NoCeiling,
570    /// Not asked: a template without parameters.
571    Untemplated,
572    /// Not asked: an operation, whose members no reading counts.
573    Kind,
574    /// Not asked: no `rate`, so not an event.
575    NoRate,
576}
577
578impl Reason {
579    /// The fixture's token.
580    #[must_use]
581    pub fn as_str(self) -> &'static str {
582        match self {
583            Self::OverBound => "over_bound",
584            Self::RateExceeded => "rate_exceeded",
585            Self::Complete => "complete",
586            Self::RateKept => "rate_kept",
587            Self::Empty => "empty",
588            Self::Incomplete => "incomplete",
589            Self::Lossy => "lossy",
590            Self::WindowTooShort => "window_too_short",
591            Self::OwnerAbsent => "owner_absent",
592            Self::ReadingKind => "reading_kind",
593            Self::NoCeiling => "no_ceiling",
594            Self::Untemplated => "untemplated",
595            Self::Kind => "kind",
596            Self::NoRate => "no_rate",
597        }
598    }
599}
600
601impl fmt::Display for Reason {
602    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
603        f.write_str(self.as_str())
604    }
605}
606
607/// A verdict, its reason, and what it counted.
608#[derive(Debug, Clone, Copy, PartialEq, Eq)]
609pub struct Judged {
610    pub verdict: Verdict,
611    pub reason: Reason,
612    /// The members counted against the bound (the most within one liveness
613    /// period, for a window), or, for a rate, the most occurrences of one
614    /// member within one period. 0 when nothing was counted.
615    pub counted: u64,
616}
617
618impl Judged {
619    fn new(verdict: Verdict, reason: Reason, counted: u64) -> Self {
620        Self {
621            verdict,
622            reason,
623            counted,
624        }
625    }
626}
627
628/// The most distinct members heard within any span shorter than `period`:
629/// the members a window shows live at once (§2.7). Without a period, every
630/// member heard.
631#[must_use]
632pub fn most_within(heard: &BTreeMap<String, Vec<Duration>>, period: Option<Duration>) -> u64 {
633    let Some(period) = period else {
634        return heard.values().filter(|v| !v.is_empty()).count() as u64;
635    };
636    let mut at: Vec<(Duration, &str)> = heard
637        .iter()
638        .flat_map(|(m, ts)| ts.iter().map(move |t| (*t, m.as_str())))
639        .collect();
640    at.sort();
641    let mut inside: BTreeMap<&str, usize> = BTreeMap::new();
642    let (mut best, mut end) = (0usize, 0usize);
643    for start in 0..at.len() {
644        while end < at.len() && at[end].0 < at[start].0 + period {
645            *inside.entry(at[end].1).or_default() += 1;
646            end += 1;
647        }
648        best = best.max(inside.len());
649        let m = at[start].1;
650        if let Some(n) = inside.get_mut(m) {
651            *n -= 1;
652            if *n == 0 {
653                inside.remove(m);
654            }
655        }
656    }
657    best as u64
658}
659
660/// "Does this instance hold more live members than its bound?" (§2.7),
661/// for a resource of `kind` with `bound` and, for an event, `retention`.
662///
663/// The order a reason is chosen in: not asked (an operation; no ceiling;
664/// no parameters); a reading this kind does not count; more members than
665/// the bound, in any reading (a lower bound already exceeds it); an
666/// incomplete reading — a GET that did not run to its final reply, or a
667/// window that lost a delivery, was shorter than one liveness span, or over
668/// which the owner was not present throughout, in that order; no member at
669/// all (O5); else within.
670#[must_use]
671pub fn population(
672    kind: Kind,
673    bound: Bound,
674    retention: Option<Duration>,
675    reading: &Reading,
676) -> Judged {
677    use Verdict::{Exceeds, NotAsked, Unobservable, Within};
678    if kind == Kind::Operation {
679        return Judged::new(NotAsked, Reason::Kind, 0);
680    }
681    let n = match bound {
682        Bound::Untemplated => return Judged::new(NotAsked, Reason::Untemplated, 0),
683        Bound::NoCeiling => return Judged::new(NotAsked, Reason::NoCeiling, 0),
684        Bound::Of(n) => n,
685    };
686    let span = liveness(kind, retention);
687    let (counted, short_of) = match (kind, reading) {
688        (Kind::State, Reading::Get { members, complete }) => {
689            (*members, (!complete).then_some(Reason::Incomplete))
690        }
691        (Kind::Stream | Kind::Event, Reading::Window(w)) => {
692            let short = span.is_none_or(|span| w.listened < span);
693            let why = if !w.lossless {
694                Some(Reason::Lossy)
695            } else if short {
696                Some(Reason::WindowTooShort)
697            } else if !w.present {
698                Some(Reason::OwnerAbsent)
699            } else {
700                None
701            };
702            (most_within(&w.heard, span), why)
703        }
704        _ => return Judged::new(Unobservable, Reason::ReadingKind, 0),
705    };
706    if counted > n {
707        return Judged::new(Exceeds, Reason::OverBound, counted);
708    }
709    if let Some(why) = short_of {
710        return Judged::new(Unobservable, why, counted);
711    }
712    if counted == 0 {
713        return Judged::new(Unobservable, Reason::Empty, 0);
714    }
715    Judged::new(Within, Reason::Complete, counted)
716}
717
718/// "Does an event publish beyond its rate?" (§2.7), per member: at most
719/// `n` occurrences of one member within any period, so `n + 1` less than
720/// the period apart are the finding, in a window of any length.
721///
722/// The order a reason is chosen in: not asked (no rate); beyond the rate;
723/// not shown lossless; a window shorter than one period; the owner not
724/// present throughout (0.25); no occurrence heard (O5); else kept.
725#[must_use]
726pub fn rate(rate: Option<Rate>, o: &Occurrences) -> Judged {
727    use Verdict::{Exceeds, NotAsked, Unobservable, Within};
728    let Some(rate) = rate else {
729        return Judged::new(NotAsked, Reason::NoRate, 0);
730    };
731    let (n, period) = rate.limit();
732    let n = n as usize;
733    let mut most = 0usize;
734    for ts in o.members.values() {
735        let mut ts = ts.clone();
736        ts.sort();
737        let mut end = 0usize;
738        for start in 0..ts.len() {
739            while end < ts.len() && ts[end] < ts[start] + period {
740                end += 1;
741            }
742            most = most.max(end - start);
743        }
744    }
745    if most > n {
746        return Judged::new(Exceeds, Reason::RateExceeded, most as u64);
747    }
748    if !o.lossless {
749        return Judged::new(Unobservable, Reason::Lossy, most as u64);
750    }
751    if o.listened < period {
752        return Judged::new(Unobservable, Reason::WindowTooShort, most as u64);
753    }
754    if !o.present {
755        return Judged::new(Unobservable, Reason::OwnerAbsent, most as u64);
756    }
757    if most == 0 {
758        return Judged::new(Unobservable, Reason::Empty, 0);
759    }
760    Judged::new(Within, Reason::RateKept, most as u64)
761}
762
763#[cfg(test)]
764mod tests {
765    use super::*;
766
767    fn s(secs: f64) -> Duration {
768        Duration::from_secs_f64(secs)
769    }
770
771    fn heard(of: &[(&str, &[f64])]) -> BTreeMap<String, Vec<Duration>> {
772        of.iter()
773            .map(|(m, ts)| ((*m).to_owned(), ts.iter().map(|t| s(*t)).collect()))
774            .collect()
775    }
776
777    #[test]
778    fn the_bound_is_the_greatest_valid_one_stated() {
779        assert_eq!(bound(None, []), Bound::Untemplated);
780        assert_eq!(bound(Some(64), []), Bound::Of(64));
781        assert_eq!(bound(Some(64), [Some(32)]), Bound::Of(32));
782        assert_eq!(bound(Some(64), [Some(16), Some(32)]), Bound::Of(32));
783        assert_eq!(bound(Some(64), [Some(32), None]), Bound::Of(64));
784        assert_eq!(bound(Some(64), [Some(128)]), Bound::Of(64), "D007's");
785        assert_eq!(bound(Some(64), [Some(0)]), Bound::Of(64), "D007's");
786        assert_eq!(bound(Some(NO_CEILING), []), Bound::NoCeiling);
787        assert_eq!(bound(Some(NO_CEILING), [Some(500)]), Bound::Of(500));
788        assert_eq!(
789            bound(Some(NO_CEILING), [Some(NO_CEILING)]),
790            Bound::NoCeiling
791        );
792    }
793
794    #[test]
795    fn a_window_counts_the_members_live_at_once() {
796        let h = heard(&[("a", &[0.0]), ("b", &[10.0]), ("c", &[4000.0])]);
797        assert_eq!(most_within(&h, Some(STREAM_LIVENESS)), 2);
798        assert_eq!(most_within(&h, None), 3);
799        // Exactly one period apart is not within one period.
800        let h = heard(&[("a", &[0.0]), ("b", &[3600.0])]);
801        assert_eq!(most_within(&h, Some(STREAM_LIVENESS)), 1);
802        // A member heard twice counts once.
803        let h = heard(&[("a", &[0.0, 1.0, 2.0]), ("b", &[1.5])]);
804        assert_eq!(most_within(&h, Some(STREAM_LIVENESS)), 2);
805        assert_eq!(most_within(&BTreeMap::new(), Some(STREAM_LIVENESS)), 0);
806    }
807
808    #[test]
809    fn population_poles() {
810        let get = |members, complete| Reading::Get { members, complete };
811        let j = |kind, bound, r: &Reading| {
812            let j = population(kind, bound, Some(s(60.0)), r);
813            (j.verdict, j.reason)
814        };
815        use Reason as R;
816        use Verdict as V;
817        assert_eq!(
818            j(Kind::State, Bound::Of(2), &get(3, false)),
819            (V::Exceeds, R::OverBound)
820        );
821        assert_eq!(
822            j(Kind::State, Bound::Of(2), &get(2, true)),
823            (V::Within, R::Complete)
824        );
825        assert_eq!(
826            j(Kind::State, Bound::Of(2), &get(2, false)),
827            (V::Unobservable, R::Incomplete)
828        );
829        assert_eq!(
830            j(Kind::State, Bound::Of(2), &get(0, true)),
831            (V::Unobservable, R::Empty)
832        );
833        assert_eq!(
834            j(Kind::State, Bound::NoCeiling, &get(9, true)),
835            (V::NotAsked, R::NoCeiling)
836        );
837        assert_eq!(
838            j(Kind::State, Bound::Of(2), &get(0, false)),
839            (V::Unobservable, R::Incomplete)
840        );
841        let w = |listened: f64, lossless, present, of: &[(&str, &[f64])]| {
842            Reading::Window(Window {
843                heard: heard(of),
844                listened: s(listened),
845                lossless,
846                present,
847            })
848        };
849        let two: &[(&str, &[f64])] = &[("a", &[0.0]), ("b", &[1.0])];
850        // Above the bound: the finding, from any window.
851        assert_eq!(
852            j(Kind::Stream, Bound::Of(1), &w(5.0, false, false, two)),
853            (V::Exceeds, R::OverBound)
854        );
855        // Within it: complete only over an hour, lossless, owner present.
856        assert_eq!(
857            j(Kind::Stream, Bound::Of(2), &w(3600.0, true, true, two)),
858            (V::Within, R::Complete)
859        );
860        assert_eq!(
861            j(Kind::Stream, Bound::Of(2), &w(3599.0, true, true, two)),
862            (V::Unobservable, R::WindowTooShort)
863        );
864        assert_eq!(
865            j(Kind::Stream, Bound::Of(2), &w(3600.0, false, true, two)),
866            (V::Unobservable, R::Lossy)
867        );
868        assert_eq!(
869            j(Kind::Stream, Bound::Of(2), &w(3600.0, true, false, two)),
870            (V::Unobservable, R::OwnerAbsent)
871        );
872        assert_eq!(
873            j(Kind::Stream, Bound::Of(2), &w(3600.0, true, true, &[])),
874            (V::Unobservable, R::Empty)
875        );
876        assert_eq!(
877            j(Kind::State, Bound::Of(2), &w(3600.0, true, true, two)),
878            (V::Unobservable, R::ReadingKind)
879        );
880        assert_eq!(
881            j(Kind::Operation, Bound::Of(2), &w(3600.0, true, true, two)),
882            (V::NotAsked, R::Kind)
883        );
884        // An event's members are live for its retention (60 s here).
885        let apart: &[(&str, &[f64])] = &[("a", &[0.0]), ("b", &[61.0])];
886        assert_eq!(
887            j(Kind::Event, Bound::Of(1), &w(120.0, true, true, apart)),
888            (V::Within, R::Complete)
889        );
890        assert_eq!(
891            j(Kind::Event, Bound::Of(1), &w(59.0, true, true, apart)),
892            (V::Unobservable, R::WindowTooShort)
893        );
894    }
895
896    #[test]
897    fn a_face_policys_transport_is_what_its_routers_run() {
898        let s = Duration::from_secs;
899        let t = crate::link::Transport {
900            lease_ms: 240_000,
901            keep_alive: 4,
902            wait_before_close_ms: 240_000,
903            sequence: crate::link::Sequence::Bit16,
904            batch_bytes: 222,
905            open_timeout_ms: 10_000,
906            accept_timeout_ms: 10_000,
907            interests_timeout_ms: 10_000,
908        };
909        let rf = Routers::of(&t);
910        assert_eq!(rf.wait_before_close, s(240));
911        assert_eq!(
912            rf.presence_tail(s(15)),
913            s(255),
914            "RF: 240 s and the reply timeout"
915        );
916        assert_eq!(
917            rf.stall_bound(),
918            s(180),
919            "the lease less one 60-s keep-alive"
920        );
921        let sbd = Routers::of(&crate::link::Transport {
922            lease_ms: 3_600_000,
923            keep_alive: 2,
924            wait_before_close_ms: 3_600_000,
925            ..t
926        });
927        assert_eq!(sbd.stall_bound(), s(1800), "SBD's two keep-alives");
928        assert_eq!(
929            Routers::default().presence_tail(s(1)),
930            presence_tail(DEFAULT_LEASE, DEFAULT_WAIT_BEFORE_CLOSE, s(1)),
931            "given no policy, zenoh 1.10.1's"
932        );
933    }
934
935    #[test]
936    fn the_presence_tail_is_the_longer_of_the_lease_and_wait_before_close() {
937        let s = Duration::from_secs;
938        assert_eq!(
939            presence_tail(DEFAULT_LEASE, DEFAULT_WAIT_BEFORE_CLOSE, s(1)),
940            s(11),
941            "zenoh 1.10.1's defaults: the 10 s lease, then the timeout"
942        );
943        assert_eq!(
944            presence_tail(s(1), DEFAULT_WAIT_BEFORE_CLOSE, s(1)),
945            s(6),
946            "wait_before_close above the lease is the longer one: budget.md §1's 1 s lease"
947        );
948        assert_eq!(
949            presence_tail(s(1), s(10), s(1)),
950            s(11),
951            "zm-1.10.2-r1's 10 s wait_before_close beside a 1 s lease (#1011)"
952        );
953        assert_eq!(presence_tail(s(5), s(5), s(2)), s(7), "equal: either");
954        assert_eq!(
955            presence_tail(s(3), Duration::ZERO, Duration::ZERO),
956            s(3),
957            "no wait and no timeout: the lease alone"
958        );
959    }
960
961    #[test]
962    fn the_stall_bound_is_the_lesser_of_the_queue_and_the_lease() {
963        let s = Duration::from_secs;
964        assert_eq!(
965            stall_bound(DEFAULT_WAIT_BEFORE_CLOSE, DEFAULT_LEASE, DEFAULT_KEEP_ALIVE),
966            s(5),
967            "zenoh 1.10.1's defaults: 5 s, against 7.5 s for the lease"
968        );
969        assert_eq!(
970            stall_bound(s(10), DEFAULT_LEASE, DEFAULT_KEEP_ALIVE),
971            Duration::from_millis(7500),
972            "zm-1.10.2-r1's defaults: the lease's 7.5 s, against 10 s for the queue (#1011)"
973        );
974        assert_eq!(
975            stall_bound(DEFAULT_WAIT_BEFORE_CLOSE, s(1), DEFAULT_KEEP_ALIVE),
976            Duration::from_millis(750),
977            "a 1 s lease: its last keep-alive may be a quarter old"
978        );
979        assert_eq!(stall_bound(s(20), s(30), 3), s(20));
980        assert_eq!(
981            stall_bound(s(20), s(10), 0),
982            Duration::ZERO,
983            "keep_alive 0 as 1"
984        );
985    }
986
987    #[test]
988    fn lossless_rests_on_the_reader_and_the_qos() {
989        use LossReason as L;
990        let d = |reliability, congestion, reader_lost, declared, used, misses| Delivery {
991            reliability,
992            congestion,
993            reader_lost,
994            stall: ReaderStall {
995                gap: Duration::from_millis(50),
996                bound: DEFAULT_WAIT_BEFORE_CLOSE,
997                transport_closed: false,
998            },
999            miss_detection: MissDetection {
1000                declared,
1001                used,
1002                misses,
1003            },
1004        };
1005        let (re, be) = (Reliability::Reliable, Reliability::BestEffort);
1006        let (block, drop) = (Congestion::Block, Congestion::Drop);
1007        assert_eq!(
1008            lossless(&d(re, block, 0, false, false, 0)),
1009            L::ReliableBlock
1010        );
1011        assert!(L::ReliableBlock.is_lossless());
1012        assert_eq!(lossless(&d(re, block, 1, false, false, 0)), L::ReaderLost);
1013        assert_eq!(lossless(&d(be, drop, 0, false, false, 0)), L::BestEffort);
1014        assert_eq!(lossless(&d(be, block, 0, false, false, 0)), L::BestEffort);
1015        assert_eq!(
1016            lossless(&d(re, drop, 0, false, false, 0)),
1017            L::CongestionDrop
1018        );
1019        // A detected miss is a loss; none detected establishes nothing.
1020        assert_eq!(lossless(&d(re, block, 0, true, true, 1)), L::MissesDetected);
1021        assert_eq!(lossless(&d(be, drop, 0, true, true, 0)), L::BestEffort);
1022        // Counted only where declared and used.
1023        assert_eq!(lossless(&d(re, block, 0, false, true, 3)), L::ReliableBlock);
1024        assert_eq!(lossless(&d(re, block, 0, true, false, 3)), L::ReliableBlock);
1025        // The reader's own loss first.
1026        assert_eq!(lossless(&d(re, block, 2, true, true, 5)), L::ReaderLost);
1027        // 0.27: a reader whose transport closed, or whose ticker stopped
1028        // longer than the bound, lost what its router queued for it —
1029        // after its own counted loss, before a miss and the QoS.
1030        let stalled = |gap_ms, closed, base: Delivery| Delivery {
1031            stall: ReaderStall {
1032                gap: Duration::from_millis(gap_ms),
1033                bound: DEFAULT_WAIT_BEFORE_CLOSE,
1034                transport_closed: closed,
1035            },
1036            ..base
1037        };
1038        let clean = d(re, block, 0, false, false, 0);
1039        assert_eq!(lossless(&stalled(50, true, clean)), L::ReaderStalled);
1040        assert_eq!(lossless(&stalled(7000, false, clean)), L::ReaderStalled);
1041        assert_eq!(lossless(&stalled(5000, false, clean)), L::ReliableBlock);
1042        assert_eq!(
1043            lossless(&stalled(7000, false, d(re, block, 1, false, false, 0))),
1044            L::ReaderLost
1045        );
1046        assert_eq!(
1047            lossless(&stalled(50, true, d(re, block, 0, true, true, 2))),
1048            L::ReaderStalled
1049        );
1050        assert_eq!(
1051            lossless(&stalled(50, true, d(be, drop, 0, false, false, 0))),
1052            L::ReaderStalled
1053        );
1054        for r in [
1055            L::ReaderLost,
1056            L::ReaderStalled,
1057            L::MissesDetected,
1058            L::BestEffort,
1059            L::CongestionDrop,
1060        ] {
1061            assert!(!r.is_lossless(), "{r}");
1062        }
1063    }
1064
1065    #[test]
1066    fn rate_poles() {
1067        let o = |listened, lossless, of: &[(&str, &[f64])]| Occurrences {
1068            listened: s(listened),
1069            lossless,
1070            present: true,
1071            members: heard(of),
1072        };
1073        let j = |r, o: &Occurrences| {
1074            let j = rate(r, o);
1075            (j.verdict, j.reason)
1076        };
1077        use Reason as R;
1078        use Verdict as V;
1079        let low = Some(Rate::Low);
1080        assert_eq!(
1081            j(low, &o(5.0, true, &[("a", &[0.0, 59.9])])),
1082            (V::Exceeds, R::RateExceeded)
1083        );
1084        assert_eq!(
1085            j(low, &o(120.0, true, &[("a", &[0.0, 60.0])])),
1086            (V::Within, R::RateKept)
1087        );
1088        assert_eq!(
1089            j(low, &o(30.0, true, &[("a", &[0.0])])),
1090            (V::Unobservable, R::WindowTooShort)
1091        );
1092        assert_eq!(
1093            j(low, &o(120.0, false, &[("a", &[0.0])])),
1094            (V::Unobservable, R::Lossy)
1095        );
1096        assert_eq!(j(low, &o(120.0, true, &[])), (V::Unobservable, R::Empty));
1097        // Per member: two members once each is no excess.
1098        assert_eq!(
1099            j(low, &o(120.0, true, &[("a", &[0.0]), ("b", &[1.0])])),
1100            (V::Within, R::RateKept)
1101        );
1102        let burst = Some(Rate::Burst(3));
1103        assert_eq!(
1104            j(
1105                burst,
1106                &o(3600.0, true, &[("a", &[0.0, 1200.0, 2400.0, 3599.0])])
1107            ),
1108            (V::Exceeds, R::RateExceeded)
1109        );
1110        assert_eq!(
1111            j(
1112                burst,
1113                &o(3600.0, true, &[("a", &[0.0, 1200.0, 2400.0, 3600.0])])
1114            ),
1115            (V::Within, R::RateKept)
1116        );
1117        assert_eq!(j(None, &o(120.0, true, &[])), (V::NotAsked, R::NoRate));
1118        // The owner not present throughout (0.25): after too short, before
1119        // empty, and no excess hidden.
1120        let absent = |listened, of: &[(&str, &[f64])]| Occurrences {
1121            present: false,
1122            ..o(listened, true, of)
1123        };
1124        assert_eq!(
1125            j(low, &absent(120.0, &[("a", &[0.0])])),
1126            (V::Unobservable, R::OwnerAbsent)
1127        );
1128        assert_eq!(
1129            j(low, &absent(120.0, &[])),
1130            (V::Unobservable, R::OwnerAbsent)
1131        );
1132        assert_eq!(
1133            j(low, &absent(30.0, &[("a", &[0.0])])),
1134            (V::Unobservable, R::WindowTooShort)
1135        );
1136        assert_eq!(
1137            j(low, &absent(120.0, &[("a", &[0.0, 1.0])])),
1138            (V::Exceeds, R::RateExceeded)
1139        );
1140    }
1141}