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