zenkey-model 0.21.0

zk2 keys and contracts without a Zenoh session: the key grammar, the contract authoring format, canonical form, fingerprints and bundles
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
//! The population budget (core ยง2.7, 0.24; #735): a templated resource's
//! bound in one instance, what its members and its live members are, what
//! an event's `rate` bounds, and the pure judgement of a reading against
//! them, in four states and a reason.
//!
//! ```text
//! bound(contract, statedโ€ฆ)              โ”€โ–ถ Untemplated โ”‚ NoCeiling โ”‚ Of(n)
//! lossless(delivery)                    โ”€โ–ถ lossless or not, + reason (0.25)
//! population(kind, bound, retention, r) โ”€โ–ถ exceeds โ”‚ within โ”‚ unobservable โ”‚ not_asked, + reason
//! rate(rate, occurrences)               โ”€โ–ถ the same four, + reason
//! ```
//!
//! Each judgement answers "does this instance exceed its budget here?", so
//! its finding is the yes: [`Verdict::Exceeds`]. There is no I/O and no
//! clock here. A reader counts what it read (the keys an owner's GET
//! answered with a value and whether it ran to its end; the instants a
//! window heard each member, how long it listened, what it lost and
//! whether the owner stayed present) and hands it over as values; the
//! fixtures in `spec/conformance/budget/` pin the rest.
//!
//! **"Lost no delivery" is established, never assumed** (0.25, #740): a
//! reader can know that it lost a delivery, never that it lost none.
//! [`lossless`] decides it from the resource's declared QoS, the reader's
//! own loss, whether its receive path stalled (0.27, #753) and miss
//! detection; a window's `lossless` and an occurrence set's are its
//! answer.

use std::collections::BTreeMap;
use std::fmt;
use std::time::Duration;

use crate::authoring::{Congestion, Kind, Reliability};
use crate::contract::{Body, Rate, Resource};

/// The no-ceiling cardinality, 2^32โˆ’1 (ยง2.2): no bound, never a population
/// to budget with.
pub const NO_CEILING: u64 = 4_294_967_295;

/// How long a stream member stays live after the owner last published on
/// it (ยง2.7): an hour.
pub const STREAM_LIVENESS: Duration = Duration::from_secs(3600);

/// zenoh 1.10.1's default link lease (`transport/link/tx/lease`, 10 s;
/// zm-1.10.2-r1's too): a link gone silent withdraws the owner's token only when it runs out
/// (Appendix B). A window's owner must stay present for one lease after
/// the window's end (ยง2.7, 0.25), and a tool watches its tokens past the
/// end for the longer of the lease and `wait_before_close`, plus the reply
/// timeout ([`presence_tail`], observer ยง5.2).
pub const DEFAULT_LEASE: Duration = Duration::from_secs(10);

/// zenoh 1.10.1's default keep-alive (`transport/link/tx/keep_alive`, 4;
/// zm-1.10.2-r1's too): a session sends a keep-alive every lease รท 4 when it has nothing else to
/// send, so a peer that stops hearing from it closes the transport once a
/// lease passes (ยง2.7, 0.27).
pub const DEFAULT_KEEP_ALIVE: u32 = 4;

/// zenoh 1.10.1's default `wait_before_close`
/// (`transport/link/tx/queue/congestion_control/block/wait_before_close`,
/// 5 s): how long a router's push of a `reliable`, `block` sample waits for
/// room in a reader's queue before it closes the transport (Appendix B).
///
/// A deployment on another binding states its own: zm-1.10.2-r1, the fork
/// zenoh-modem builds on, defaults to 10 s, its lease (#1011). A tool takes
/// the deployment's word for it (zenctl's `--wait-before-close`, or the
/// `[transport]` of the routers' `link.v2` face policy: [`Routers::of`]),
/// never its own session's configuration, which states how long the
/// tool's own pushes wait and says nothing of its routers'.
pub const DEFAULT_WAIT_BEFORE_CLOSE: Duration = Duration::from_secs(5);

/// The routers' link settings a window's reader reads by (ยง2.7, observer
/// ยง5.2): their lease, keep-alives and `wait_before_close`. The
/// deployment's word: a `link.v2` face policy's `[transport]`, which its
/// routers run (`link.v2` ยง2.16; [`Routers::of`]), and zenoh 1.10.1's
/// defaults where it gives none ([`Routers::default`], #1011's item 3).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Routers {
    pub lease: Duration,
    pub keep_alive: u32,
    pub wait_before_close: Duration,
}

impl Default for Routers {
    /// zenoh 1.10.1's: a 10 s lease, 4 keep-alives, a 5 s
    /// `wait_before_close`.
    fn default() -> Self {
        Routers {
            lease: DEFAULT_LEASE,
            keep_alive: DEFAULT_KEEP_ALIVE,
            wait_before_close: DEFAULT_WAIT_BEFORE_CLOSE,
        }
    }
}

impl Routers {
    /// What routers that run `transport` run: a face policy's
    /// `[transport]`, every key resolved (`link.v2` ยง2.1).
    #[must_use]
    pub fn of(transport: &crate::link::Transport) -> Routers {
        Routers {
            lease: Duration::from_millis(transport.lease_ms),
            keep_alive: u32::try_from(transport.keep_alive).unwrap_or(u32::MAX),
            wait_before_close: Duration::from_millis(transport.wait_before_close_ms),
        }
    }

    /// [`stall_bound`] of these routers.
    #[must_use]
    pub fn stall_bound(&self) -> Duration {
        stall_bound(self.wait_before_close, self.lease, self.keep_alive)
    }

    /// [`presence_tail`] of these routers, with the reader's `timeout`.
    #[must_use]
    pub fn presence_tail(&self, timeout: Duration) -> Duration {
        presence_tail(self.lease, self.wait_before_close, timeout)
    }
}

/// The longest a window's reader may stall without a router giving up on
/// it (ยง2.7, 0.27): the transport's `wait_before_close`, or its lease less
/// one keep-alive interval when that is shorter โ€” the longest a router
/// waits on the reader's full queue, and the longest it may hear nothing
/// from the reader before its lease runs out. 5 s with zenoh 1.10.1's
/// defaults (and 7.5 s for the lease); 7.5 s, the lease's, with
/// zm-1.10.2-r1's, whose `wait_before_close` is 10 s. The interval is rounded up to a whole
/// millisecond, which shortens the bound; a `keep_alive` of 0 is taken as
/// 1.
#[must_use]
pub fn stall_bound(wait_before_close: Duration, lease: Duration, keep_alive: u32) -> Duration {
    let interval = lease.as_millis().div_ceil(u128::from(keep_alive.max(1)));
    let interval = Duration::from_millis(u64::try_from(interval).unwrap_or(u64::MAX));
    wait_before_close.min(lease.saturating_sub(interval))
}

/// How long after a window's end a tool watches the owner's instance
/// tokens (observer ยง5.2, `[Sc: budget.md ยง2]`): the longer of one lease
/// and the routers' `wait_before_close`, plus the reply timeout.
///
/// A link gone silent withdraws the owner's token one lease after it went
/// silent, and a push that cannot queue within `wait_before_close` closes
/// its transport (Appendix B), so a router that waits that long before it
/// closes one tells the withdrawal that late. The reply timeout allows for
/// the withdrawal's transit. With zenoh 1.10.1's defaults, a 10 s lease
/// against a 5 s `wait_before_close`, it is the lease plus the timeout; a
/// 1 s lease beside that `wait_before_close` watches 5 s plus the timeout
/// (observer text 0.6, zk2py round 85's F-320). zm-1.10.2-r1's 10 s
/// `wait_before_close` beside a 1 s lease watches 10 s plus the timeout, so
/// a deployment on it states its `wait_before_close` (#1011).
#[must_use]
pub fn presence_tail(lease: Duration, wait_before_close: Duration, timeout: Duration) -> Duration {
    lease.max(wait_before_close).saturating_add(timeout)
}

/// What a window's path declares and what its reader saw of it, for "lost
/// no delivery" (ยง2.7, 0.25).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Delivery {
    /// The resource's declared reliability (ยง2.4).
    pub reliability: Reliability,
    /// The resource's declared congestion control (ยง2.4).
    pub congestion: Congestion,
    /// Deliveries the window's own reader lost: its queue overflowed or
    /// fell behind, or a cap kept them out of its count.
    pub reader_lost: u64,
    /// Whether the reader's receive path stopped long enough for a router
    /// to give up on it, over the window and one lease after it (0.27).
    pub stall: ReaderStall,
    pub miss_detection: MissDetection,
}

/// What a window's reader saw of its own receive path, over the window and
/// one lease after it (ยง2.7, 0.27, #753). A reader stalled longer than the
/// transport's `wait_before_close` loses what its router queued for it,
/// and may never see the owner's token withdrawn: only a token it had
/// received is withdrawn when its own transport closes (Appendix B).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ReaderStall {
    /// The greatest gap between two ticks of the reader's monotonic ticker,
    /// the gap still open when it was read included: how long its process
    /// stopped at most. A ticker on a thread of its own does not see
    /// zenoh's receive threads blocked while the rest of the process runs.
    pub gap: Duration,
    /// The longest stall the window tolerates: [`stall_bound`].
    pub bound: Duration,
    /// Whether the reader's session saw one of its own transports close:
    /// zenoh's transport events (unstable in 1.10.1). It sees a router
    /// giving up on a reader whose receive threads were blocked, which no
    /// ticker sees. `false` where the reader does not observe them.
    pub transport_closed: bool,
}

impl ReaderStall {
    /// Stalled: a transport of the reader's session closed, or its ticker
    /// saw a gap longer than the bound. A gap of exactly the bound is not.
    #[must_use]
    pub fn stalled(&self) -> bool {
        self.transport_closed || self.gap > self.bound
    }
}

/// Miss detection over a window (ยง2.5, ยง2.7): counted only where the
/// resource declares it and the window's subscription uses it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct MissDetection {
    /// The resource declares `history.miss_detection_ms`: its owner numbers
    /// its samples.
    pub declared: bool,
    /// The window's subscription detects misses.
    pub used: bool,
    /// How many misses it detected.
    pub misses: u64,
}

/// Why a window is, or is not, shown to have lost no delivery: the
/// fixture's reason class, in the order [`lossless`] chooses it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LossReason {
    /// Not lossless: the reader itself lost deliveries.
    ReaderLost,
    /// Not lossless: the reader's receive path stalled longer than its
    /// router waits on it, or its own transport closed (0.27).
    ReaderStalled,
    /// Not lossless: the subscription detected missed samples.
    MissesDetected,
    /// Not lossless: best effort, so a sample dropped anywhere on the path
    /// leaves no trace, whatever the congestion control.
    BestEffort,
    /// Not lossless: reliable with `drop`, so a full queue drops a sample
    /// and leaves no trace.
    CongestionDrop,
    /// Lossless: reliable with `block`, which no router queue drops; a
    /// failed push closes the transport, and the owner's token goes.
    ReliableBlock,
}

impl LossReason {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::ReaderLost => "reader_lost",
            Self::ReaderStalled => "reader_stalled",
            Self::MissesDetected => "misses_detected",
            Self::BestEffort => "best_effort",
            Self::CongestionDrop => "congestion_drop",
            Self::ReliableBlock => "reliable_block",
        }
    }

    /// Whether this reason makes the window lossless.
    #[must_use]
    pub fn is_lossless(self) -> bool {
        self == Self::ReliableBlock
    }
}

impl fmt::Display for LossReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// "Did this window lose no delivery?" (ยง2.7, 0.25), from what its reader
/// can see. Lossless only when its reader lost none โ€” nothing lost in its
/// own queue or past a cap, and its receive path not stalled (0.27) โ€” and
/// the path could not drop one silently: the resource is `reliable` with
/// `block`. A detected miss is a loss; none detected establishes nothing,
/// since zenoh-ext takes a publisher's first sample heard as its start
/// (Appendix B), and counts only where the resource declares miss
/// detection and the subscription uses it.
///
/// The order a reason is chosen in: the reader's own loss; the reader
/// stalled; a miss detected; best effort; reliable with `drop`; else
/// lossless, reliable with `block`.
#[must_use]
pub fn lossless(d: &Delivery) -> LossReason {
    let m = d.miss_detection;
    if d.reader_lost > 0 {
        LossReason::ReaderLost
    } else if d.stall.stalled() {
        LossReason::ReaderStalled
    } else if m.declared && m.used && m.misses > 0 {
        LossReason::MissesDetected
    } else if d.reliability == Reliability::BestEffort {
        LossReason::BestEffort
    } else if d.congestion == Congestion::Drop {
        LossReason::CongestionDrop
    } else {
        LossReason::ReliableBlock
    }
}

/// The [`Delivery`] of a stream, state or event resource, from its
/// declared QoS and `history`, with what the reader lost, what it saw of
/// its own receive path, and what its subscription detected (`misses`:
/// `None` when it does not detect misses). `None` for an operation.
#[must_use]
pub fn delivery_of(
    r: &Resource,
    reader_lost: u64,
    stall: ReaderStall,
    misses: Option<u64>,
) -> Option<Delivery> {
    match &r.body {
        Body::Data(d) => Some(Delivery {
            reliability: d.reliability,
            congestion: d.congestion,
            reader_lost,
            stall,
            miss_detection: MissDetection {
                declared: d
                    .history
                    .as_ref()
                    .is_some_and(|h| h.miss_detection_ms.is_some()),
                used: misses.is_some(),
                misses: misses.unwrap_or(0),
            },
        }),
        Body::Operation(_) => None,
    }
}

/// A templated resource's bound in an instance (ยง2.7).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Bound {
    /// The template has no parameters, so no `cardinality`: one member by
    /// construction, and nothing to budget.
    Untemplated,
    /// The no-ceiling value, from the contract or a descriptor (ยง2.2).
    NoCeiling,
    /// A bound of `n` live members.
    Of(u64),
}

impl Bound {
    /// The fixture's form: an integer, `"no_ceiling"` or `"untemplated"`.
    #[must_use]
    pub fn token(self) -> String {
        match self {
            Self::Untemplated => "untemplated".to_owned(),
            Self::NoCeiling => "no_ceiling".to_owned(),
            Self::Of(n) => n.to_string(),
        }
    }

    /// The bound, when it is one.
    #[must_use]
    pub fn limit(self) -> Option<u64> {
        match self {
            Self::Of(n) => Some(n),
            _ => None,
        }
    }
}

impl fmt::Display for Bound {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Untemplated => f.write_str("no bound (a template without parameters)"),
            Self::NoCeiling => f.write_str("no ceiling (4294967295)"),
            Self::Of(n) => write!(f, "{n}"),
        }
    }
}

/// The bound of a resource whose contract declares `contract`, across the
/// instances exposing it, each stating its own lowered value or none
/// (`stated`, one entry per instance; core ยง2.7, ยง3.3).
///
/// - A stated value from 1 to the contract's applies to its instance;
///   any other is D007's, and the contract's applies instead.
/// - Several instances (a re-mint's overlap) share one population, since a
///   key names no instance: the greatest of their bounds applies, so a
///   finding never rests on a bound one of them did not state.
/// - No instance: the contract's.
/// - 4294967295, whichever source gives it, is no ceiling.
#[must_use]
pub fn bound(contract: Option<u64>, stated: impl IntoIterator<Item = Option<u64>>) -> Bound {
    let Some(c) = contract else {
        return Bound::Untemplated;
    };
    let n = stated
        .into_iter()
        .map(|s| match s {
            Some(n) if (1..=c).contains(&n) => n,
            _ => c,
        })
        .max()
        .unwrap_or(c);
    if n == NO_CEILING {
        Bound::NoCeiling
    } else {
        Bound::Of(n)
    }
}

/// [`bound`] of a resource of a contract.
#[must_use]
pub fn bound_of(r: &Resource, stated: impl IntoIterator<Item = Option<u64>>) -> Bound {
    bound(r.cardinality, stated)
}

/// An event's retention, when the resource declares one.
#[must_use]
pub fn retention_of(r: &Resource) -> Option<Duration> {
    match &r.body {
        Body::Data(d) => d.retention_s.map(Duration::from_secs),
        Body::Operation(_) => None,
    }
}

/// An event's rate, when the resource declares one.
#[must_use]
pub fn rate_of(r: &Resource) -> Option<Rate> {
    match &r.body {
        Body::Data(d) => d.rate,
        Body::Operation(_) => None,
    }
}

impl Rate {
    /// What the rate allows per member (ยง2.7): at most `n` occurrences
    /// within any period this long.
    #[must_use]
    pub fn limit(self) -> (u32, Duration) {
        const HOUR: Duration = Duration::from_secs(3600);
        match self {
            Self::Rare => (1, HOUR),
            Self::Low => (1, Duration::from_secs(60)),
            Self::Burst(n) => (n, HOUR),
        }
    }
}

/// How long a member of a resource of `kind` stays live after its last
/// put or occurrence (ยง2.7): a stream's for an hour, an event's for its
/// retention. A state member is live while its key has a value, which a
/// window cannot see; an operation has no live member a reading counts.
#[must_use]
pub fn liveness(kind: Kind, retention: Option<Duration>) -> Option<Duration> {
    match kind {
        Kind::Stream => Some(STREAM_LIVENESS),
        Kind::Event => retention,
        Kind::State | Kind::Operation => None,
    }
}

/// What a reader read of a resource's members (ยง2.7).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Reading {
    /// An owner's S4 GET over a state resource (core ยง4.2): how many keys
    /// it answered with a value (a `reply_del` is no member), and whether
    /// it ran to its final reply, with no error reply, a timeout included.
    Get { members: u64, complete: bool },
    /// A subscription window over a stream or an event.
    Window(Window),
}

/// A subscription window over a stream or an event, as a population
/// reading (ยง2.7). It is complete โ€” it heard every member live at its end โ€”
/// when it lasted at least one liveness span, lost no delivery, and the
/// owner was present throughout.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Window {
    /// The instants each member was heard, on one clock (the reader's
    /// receive clock), from any origin. An event's member is its key
    /// without the ULID chunk.
    pub heard: BTreeMap<String, Vec<Duration>>,
    /// How long the window listened, counted from when its subscription is
    /// taken to have reached the owner: its declaration plus the reader's
    /// reply timeout (0.25).
    pub listened: Duration,
    /// Whether it is shown to have lost no delivery: [`lossless`]'s answer
    /// (0.25).
    pub lossless: bool,
    /// Whether the owner was present, an instance token of its held, from
    /// the window's start until one lease after its end (0.25): false when
    /// it joined, left or re-minted, or a path to it failed.
    pub present: bool,
}

/// The occurrences of an event a window heard, for its `rate` (ยง2.7), with
/// the window's premises as a [`Window`] has them.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Occurrences {
    /// How long the window listened, counted as [`Window::listened`] is.
    pub listened: Duration,
    /// Whether it is shown to have lost no delivery: [`lossless`]'s answer
    /// (0.25).
    pub lossless: bool,
    /// Whether the owner was present from the window's start until one
    /// lease after its end (0.25).
    pub present: bool,
    /// Per member, the instants of its occurrences, measured between the
    /// occurrences' stamps of one clock, or on the reader's receive clock.
    pub members: BTreeMap<String, Vec<Duration>>,
}

/// The answer to "does this instance exceed its budget here?" (ยง2.7). The
/// finding is the yes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Verdict {
    /// The finding: more live members than the bound, or an event's
    /// occurrences beyond its rate.
    Exceeds,
    /// Clean: a reading that can show the budget kept shows it kept.
    Within,
    /// The question was put, and the reading could not answer it.
    Unobservable,
    /// Nobody put the question, or it has no premise here.
    NotAsked,
}

impl Verdict {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Exceeds => "exceeds",
            Self::Within => "within",
            Self::Unobservable => "unobservable",
            Self::NotAsked => "not_asked",
        }
    }
}

impl fmt::Display for Verdict {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Why a verdict is what it is: the fixture's reason class.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Reason {
    /// Exceeds: more members than the bound, in any reading.
    OverBound,
    /// Exceeds: `n + 1` occurrences of one member less than the period
    /// apart.
    RateExceeded,
    /// Within: a complete reading โ€” a GET that ran to its final reply, or a
    /// window of a whole liveness span, lossless, the owner present
    /// throughout โ€” counted at least one member, and no more than the
    /// bound.
    Complete,
    /// Within: a window of at least one period, nothing lost, an
    /// occurrence heard, none beyond the rate.
    RateKept,
    /// Unobservable: no member, or no occurrence, was read: an empty reply
    /// set is never a verdict (core O5).
    Empty,
    /// Unobservable: the GET ended at its timeout, or with an error reply.
    Incomplete,
    /// Unobservable: the window is not shown to have lost no delivery
    /// ([`lossless`]: its reader lost one, a miss was detected, or its QoS
    /// drops silently).
    Lossy,
    /// Unobservable: the window was shorter than the rate's period, or than
    /// the population's liveness span.
    WindowTooShort,
    /// Unobservable: the owner was not present throughout the window and
    /// one lease after it: it joined, left or re-minted while the window
    /// listened, or a path to it failed.
    OwnerAbsent,
    /// Unobservable: a reading that does not count this kind's members (a
    /// window of a state, a GET of a stream or an event).
    ReadingKind,
    /// Not asked: the no-ceiling bound.
    NoCeiling,
    /// Not asked: a template without parameters.
    Untemplated,
    /// Not asked: an operation, whose members no reading counts.
    Kind,
    /// Not asked: no `rate`, so not an event.
    NoRate,
}

impl Reason {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::OverBound => "over_bound",
            Self::RateExceeded => "rate_exceeded",
            Self::Complete => "complete",
            Self::RateKept => "rate_kept",
            Self::Empty => "empty",
            Self::Incomplete => "incomplete",
            Self::Lossy => "lossy",
            Self::WindowTooShort => "window_too_short",
            Self::OwnerAbsent => "owner_absent",
            Self::ReadingKind => "reading_kind",
            Self::NoCeiling => "no_ceiling",
            Self::Untemplated => "untemplated",
            Self::Kind => "kind",
            Self::NoRate => "no_rate",
        }
    }
}

impl fmt::Display for Reason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A verdict, its reason, and what it counted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Judged {
    pub verdict: Verdict,
    pub reason: Reason,
    /// The members counted against the bound (the most within one liveness
    /// period, for a window), or, for a rate, the most occurrences of one
    /// member within one period. 0 when nothing was counted.
    pub counted: u64,
}

impl Judged {
    fn new(verdict: Verdict, reason: Reason, counted: u64) -> Self {
        Self {
            verdict,
            reason,
            counted,
        }
    }
}

/// The most distinct members heard within any span shorter than `period`:
/// the members a window shows live at once (ยง2.7). Without a period, every
/// member heard.
#[must_use]
pub fn most_within(heard: &BTreeMap<String, Vec<Duration>>, period: Option<Duration>) -> u64 {
    let Some(period) = period else {
        return heard.values().filter(|v| !v.is_empty()).count() as u64;
    };
    let mut at: Vec<(Duration, &str)> = heard
        .iter()
        .flat_map(|(m, ts)| ts.iter().map(move |t| (*t, m.as_str())))
        .collect();
    at.sort();
    let mut inside: BTreeMap<&str, usize> = BTreeMap::new();
    let (mut best, mut end) = (0usize, 0usize);
    for start in 0..at.len() {
        while end < at.len() && at[end].0 < at[start].0 + period {
            *inside.entry(at[end].1).or_default() += 1;
            end += 1;
        }
        best = best.max(inside.len());
        let m = at[start].1;
        if let Some(n) = inside.get_mut(m) {
            *n -= 1;
            if *n == 0 {
                inside.remove(m);
            }
        }
    }
    best as u64
}

/// "Does this instance hold more live members than its bound?" (ยง2.7),
/// for a resource of `kind` with `bound` and, for an event, `retention`.
///
/// The order a reason is chosen in: not asked (an operation; no ceiling;
/// no parameters); a reading this kind does not count; more members than
/// the bound, in any reading (a lower bound already exceeds it); an
/// incomplete reading โ€” a GET that did not run to its final reply, or a
/// window that lost a delivery, was shorter than one liveness span, or over
/// which the owner was not present throughout, in that order; no member at
/// all (O5); else within.
#[must_use]
pub fn population(
    kind: Kind,
    bound: Bound,
    retention: Option<Duration>,
    reading: &Reading,
) -> Judged {
    use Verdict::{Exceeds, NotAsked, Unobservable, Within};
    if kind == Kind::Operation {
        return Judged::new(NotAsked, Reason::Kind, 0);
    }
    let n = match bound {
        Bound::Untemplated => return Judged::new(NotAsked, Reason::Untemplated, 0),
        Bound::NoCeiling => return Judged::new(NotAsked, Reason::NoCeiling, 0),
        Bound::Of(n) => n,
    };
    let span = liveness(kind, retention);
    let (counted, short_of) = match (kind, reading) {
        (Kind::State, Reading::Get { members, complete }) => {
            (*members, (!complete).then_some(Reason::Incomplete))
        }
        (Kind::Stream | Kind::Event, Reading::Window(w)) => {
            let short = span.is_none_or(|span| w.listened < span);
            let why = if !w.lossless {
                Some(Reason::Lossy)
            } else if short {
                Some(Reason::WindowTooShort)
            } else if !w.present {
                Some(Reason::OwnerAbsent)
            } else {
                None
            };
            (most_within(&w.heard, span), why)
        }
        _ => return Judged::new(Unobservable, Reason::ReadingKind, 0),
    };
    if counted > n {
        return Judged::new(Exceeds, Reason::OverBound, counted);
    }
    if let Some(why) = short_of {
        return Judged::new(Unobservable, why, counted);
    }
    if counted == 0 {
        return Judged::new(Unobservable, Reason::Empty, 0);
    }
    Judged::new(Within, Reason::Complete, counted)
}

/// "Does an event publish beyond its rate?" (ยง2.7), per member: at most
/// `n` occurrences of one member within any period, so `n + 1` less than
/// the period apart are the finding, in a window of any length.
///
/// The order a reason is chosen in: not asked (no rate); beyond the rate;
/// not shown lossless; a window shorter than one period; the owner not
/// present throughout (0.25); no occurrence heard (O5); else kept.
#[must_use]
pub fn rate(rate: Option<Rate>, o: &Occurrences) -> Judged {
    use Verdict::{Exceeds, NotAsked, Unobservable, Within};
    let Some(rate) = rate else {
        return Judged::new(NotAsked, Reason::NoRate, 0);
    };
    let (n, period) = rate.limit();
    let n = n as usize;
    let mut most = 0usize;
    for ts in o.members.values() {
        let mut ts = ts.clone();
        ts.sort();
        let mut end = 0usize;
        for start in 0..ts.len() {
            while end < ts.len() && ts[end] < ts[start] + period {
                end += 1;
            }
            most = most.max(end - start);
        }
    }
    if most > n {
        return Judged::new(Exceeds, Reason::RateExceeded, most as u64);
    }
    if !o.lossless {
        return Judged::new(Unobservable, Reason::Lossy, most as u64);
    }
    if o.listened < period {
        return Judged::new(Unobservable, Reason::WindowTooShort, most as u64);
    }
    if !o.present {
        return Judged::new(Unobservable, Reason::OwnerAbsent, most as u64);
    }
    if most == 0 {
        return Judged::new(Unobservable, Reason::Empty, 0);
    }
    Judged::new(Within, Reason::RateKept, most as u64)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn s(secs: f64) -> Duration {
        Duration::from_secs_f64(secs)
    }

    fn heard(of: &[(&str, &[f64])]) -> BTreeMap<String, Vec<Duration>> {
        of.iter()
            .map(|(m, ts)| ((*m).to_owned(), ts.iter().map(|t| s(*t)).collect()))
            .collect()
    }

    #[test]
    fn the_bound_is_the_greatest_valid_one_stated() {
        assert_eq!(bound(None, []), Bound::Untemplated);
        assert_eq!(bound(Some(64), []), Bound::Of(64));
        assert_eq!(bound(Some(64), [Some(32)]), Bound::Of(32));
        assert_eq!(bound(Some(64), [Some(16), Some(32)]), Bound::Of(32));
        assert_eq!(bound(Some(64), [Some(32), None]), Bound::Of(64));
        assert_eq!(bound(Some(64), [Some(128)]), Bound::Of(64), "D007's");
        assert_eq!(bound(Some(64), [Some(0)]), Bound::Of(64), "D007's");
        assert_eq!(bound(Some(NO_CEILING), []), Bound::NoCeiling);
        assert_eq!(bound(Some(NO_CEILING), [Some(500)]), Bound::Of(500));
        assert_eq!(
            bound(Some(NO_CEILING), [Some(NO_CEILING)]),
            Bound::NoCeiling
        );
    }

    #[test]
    fn a_window_counts_the_members_live_at_once() {
        let h = heard(&[("a", &[0.0]), ("b", &[10.0]), ("c", &[4000.0])]);
        assert_eq!(most_within(&h, Some(STREAM_LIVENESS)), 2);
        assert_eq!(most_within(&h, None), 3);
        // Exactly one period apart is not within one period.
        let h = heard(&[("a", &[0.0]), ("b", &[3600.0])]);
        assert_eq!(most_within(&h, Some(STREAM_LIVENESS)), 1);
        // A member heard twice counts once.
        let h = heard(&[("a", &[0.0, 1.0, 2.0]), ("b", &[1.5])]);
        assert_eq!(most_within(&h, Some(STREAM_LIVENESS)), 2);
        assert_eq!(most_within(&BTreeMap::new(), Some(STREAM_LIVENESS)), 0);
    }

    #[test]
    fn population_poles() {
        let get = |members, complete| Reading::Get { members, complete };
        let j = |kind, bound, r: &Reading| {
            let j = population(kind, bound, Some(s(60.0)), r);
            (j.verdict, j.reason)
        };
        use Reason as R;
        use Verdict as V;
        assert_eq!(
            j(Kind::State, Bound::Of(2), &get(3, false)),
            (V::Exceeds, R::OverBound)
        );
        assert_eq!(
            j(Kind::State, Bound::Of(2), &get(2, true)),
            (V::Within, R::Complete)
        );
        assert_eq!(
            j(Kind::State, Bound::Of(2), &get(2, false)),
            (V::Unobservable, R::Incomplete)
        );
        assert_eq!(
            j(Kind::State, Bound::Of(2), &get(0, true)),
            (V::Unobservable, R::Empty)
        );
        assert_eq!(
            j(Kind::State, Bound::NoCeiling, &get(9, true)),
            (V::NotAsked, R::NoCeiling)
        );
        assert_eq!(
            j(Kind::State, Bound::Of(2), &get(0, false)),
            (V::Unobservable, R::Incomplete)
        );
        let w = |listened: f64, lossless, present, of: &[(&str, &[f64])]| {
            Reading::Window(Window {
                heard: heard(of),
                listened: s(listened),
                lossless,
                present,
            })
        };
        let two: &[(&str, &[f64])] = &[("a", &[0.0]), ("b", &[1.0])];
        // Above the bound: the finding, from any window.
        assert_eq!(
            j(Kind::Stream, Bound::Of(1), &w(5.0, false, false, two)),
            (V::Exceeds, R::OverBound)
        );
        // Within it: complete only over an hour, lossless, owner present.
        assert_eq!(
            j(Kind::Stream, Bound::Of(2), &w(3600.0, true, true, two)),
            (V::Within, R::Complete)
        );
        assert_eq!(
            j(Kind::Stream, Bound::Of(2), &w(3599.0, true, true, two)),
            (V::Unobservable, R::WindowTooShort)
        );
        assert_eq!(
            j(Kind::Stream, Bound::Of(2), &w(3600.0, false, true, two)),
            (V::Unobservable, R::Lossy)
        );
        assert_eq!(
            j(Kind::Stream, Bound::Of(2), &w(3600.0, true, false, two)),
            (V::Unobservable, R::OwnerAbsent)
        );
        assert_eq!(
            j(Kind::Stream, Bound::Of(2), &w(3600.0, true, true, &[])),
            (V::Unobservable, R::Empty)
        );
        assert_eq!(
            j(Kind::State, Bound::Of(2), &w(3600.0, true, true, two)),
            (V::Unobservable, R::ReadingKind)
        );
        assert_eq!(
            j(Kind::Operation, Bound::Of(2), &w(3600.0, true, true, two)),
            (V::NotAsked, R::Kind)
        );
        // An event's members are live for its retention (60 s here).
        let apart: &[(&str, &[f64])] = &[("a", &[0.0]), ("b", &[61.0])];
        assert_eq!(
            j(Kind::Event, Bound::Of(1), &w(120.0, true, true, apart)),
            (V::Within, R::Complete)
        );
        assert_eq!(
            j(Kind::Event, Bound::Of(1), &w(59.0, true, true, apart)),
            (V::Unobservable, R::WindowTooShort)
        );
    }

    #[test]
    fn a_face_policys_transport_is_what_its_routers_run() {
        let s = Duration::from_secs;
        let t = crate::link::Transport {
            lease_ms: 240_000,
            keep_alive: 4,
            wait_before_close_ms: 240_000,
            sequence: crate::link::Sequence::Bit16,
            batch_bytes: 222,
            open_timeout_ms: 10_000,
            accept_timeout_ms: 10_000,
            interests_timeout_ms: 10_000,
        };
        let rf = Routers::of(&t);
        assert_eq!(rf.wait_before_close, s(240));
        assert_eq!(
            rf.presence_tail(s(15)),
            s(255),
            "RF: 240 s and the reply timeout"
        );
        assert_eq!(
            rf.stall_bound(),
            s(180),
            "the lease less one 60-s keep-alive"
        );
        let sbd = Routers::of(&crate::link::Transport {
            lease_ms: 3_600_000,
            keep_alive: 2,
            wait_before_close_ms: 3_600_000,
            ..t
        });
        assert_eq!(sbd.stall_bound(), s(1800), "SBD's two keep-alives");
        assert_eq!(
            Routers::default().presence_tail(s(1)),
            presence_tail(DEFAULT_LEASE, DEFAULT_WAIT_BEFORE_CLOSE, s(1)),
            "given no policy, zenoh 1.10.1's"
        );
    }

    #[test]
    fn the_presence_tail_is_the_longer_of_the_lease_and_wait_before_close() {
        let s = Duration::from_secs;
        assert_eq!(
            presence_tail(DEFAULT_LEASE, DEFAULT_WAIT_BEFORE_CLOSE, s(1)),
            s(11),
            "zenoh 1.10.1's defaults: the 10 s lease, then the timeout"
        );
        assert_eq!(
            presence_tail(s(1), DEFAULT_WAIT_BEFORE_CLOSE, s(1)),
            s(6),
            "wait_before_close above the lease is the longer one: budget.md ยง1's 1 s lease"
        );
        assert_eq!(
            presence_tail(s(1), s(10), s(1)),
            s(11),
            "zm-1.10.2-r1's 10 s wait_before_close beside a 1 s lease (#1011)"
        );
        assert_eq!(presence_tail(s(5), s(5), s(2)), s(7), "equal: either");
        assert_eq!(
            presence_tail(s(3), Duration::ZERO, Duration::ZERO),
            s(3),
            "no wait and no timeout: the lease alone"
        );
    }

    #[test]
    fn the_stall_bound_is_the_lesser_of_the_queue_and_the_lease() {
        let s = Duration::from_secs;
        assert_eq!(
            stall_bound(DEFAULT_WAIT_BEFORE_CLOSE, DEFAULT_LEASE, DEFAULT_KEEP_ALIVE),
            s(5),
            "zenoh 1.10.1's defaults: 5 s, against 7.5 s for the lease"
        );
        assert_eq!(
            stall_bound(s(10), DEFAULT_LEASE, DEFAULT_KEEP_ALIVE),
            Duration::from_millis(7500),
            "zm-1.10.2-r1's defaults: the lease's 7.5 s, against 10 s for the queue (#1011)"
        );
        assert_eq!(
            stall_bound(DEFAULT_WAIT_BEFORE_CLOSE, s(1), DEFAULT_KEEP_ALIVE),
            Duration::from_millis(750),
            "a 1 s lease: its last keep-alive may be a quarter old"
        );
        assert_eq!(stall_bound(s(20), s(30), 3), s(20));
        assert_eq!(
            stall_bound(s(20), s(10), 0),
            Duration::ZERO,
            "keep_alive 0 as 1"
        );
    }

    #[test]
    fn lossless_rests_on_the_reader_and_the_qos() {
        use LossReason as L;
        let d = |reliability, congestion, reader_lost, declared, used, misses| Delivery {
            reliability,
            congestion,
            reader_lost,
            stall: ReaderStall {
                gap: Duration::from_millis(50),
                bound: DEFAULT_WAIT_BEFORE_CLOSE,
                transport_closed: false,
            },
            miss_detection: MissDetection {
                declared,
                used,
                misses,
            },
        };
        let (re, be) = (Reliability::Reliable, Reliability::BestEffort);
        let (block, drop) = (Congestion::Block, Congestion::Drop);
        assert_eq!(
            lossless(&d(re, block, 0, false, false, 0)),
            L::ReliableBlock
        );
        assert!(L::ReliableBlock.is_lossless());
        assert_eq!(lossless(&d(re, block, 1, false, false, 0)), L::ReaderLost);
        assert_eq!(lossless(&d(be, drop, 0, false, false, 0)), L::BestEffort);
        assert_eq!(lossless(&d(be, block, 0, false, false, 0)), L::BestEffort);
        assert_eq!(
            lossless(&d(re, drop, 0, false, false, 0)),
            L::CongestionDrop
        );
        // A detected miss is a loss; none detected establishes nothing.
        assert_eq!(lossless(&d(re, block, 0, true, true, 1)), L::MissesDetected);
        assert_eq!(lossless(&d(be, drop, 0, true, true, 0)), L::BestEffort);
        // Counted only where declared and used.
        assert_eq!(lossless(&d(re, block, 0, false, true, 3)), L::ReliableBlock);
        assert_eq!(lossless(&d(re, block, 0, true, false, 3)), L::ReliableBlock);
        // The reader's own loss first.
        assert_eq!(lossless(&d(re, block, 2, true, true, 5)), L::ReaderLost);
        // 0.27: a reader whose transport closed, or whose ticker stopped
        // longer than the bound, lost what its router queued for it โ€”
        // after its own counted loss, before a miss and the QoS.
        let stalled = |gap_ms, closed, base: Delivery| Delivery {
            stall: ReaderStall {
                gap: Duration::from_millis(gap_ms),
                bound: DEFAULT_WAIT_BEFORE_CLOSE,
                transport_closed: closed,
            },
            ..base
        };
        let clean = d(re, block, 0, false, false, 0);
        assert_eq!(lossless(&stalled(50, true, clean)), L::ReaderStalled);
        assert_eq!(lossless(&stalled(7000, false, clean)), L::ReaderStalled);
        assert_eq!(lossless(&stalled(5000, false, clean)), L::ReliableBlock);
        assert_eq!(
            lossless(&stalled(7000, false, d(re, block, 1, false, false, 0))),
            L::ReaderLost
        );
        assert_eq!(
            lossless(&stalled(50, true, d(re, block, 0, true, true, 2))),
            L::ReaderStalled
        );
        assert_eq!(
            lossless(&stalled(50, true, d(be, drop, 0, false, false, 0))),
            L::ReaderStalled
        );
        for r in [
            L::ReaderLost,
            L::ReaderStalled,
            L::MissesDetected,
            L::BestEffort,
            L::CongestionDrop,
        ] {
            assert!(!r.is_lossless(), "{r}");
        }
    }

    #[test]
    fn rate_poles() {
        let o = |listened, lossless, of: &[(&str, &[f64])]| Occurrences {
            listened: s(listened),
            lossless,
            present: true,
            members: heard(of),
        };
        let j = |r, o: &Occurrences| {
            let j = rate(r, o);
            (j.verdict, j.reason)
        };
        use Reason as R;
        use Verdict as V;
        let low = Some(Rate::Low);
        assert_eq!(
            j(low, &o(5.0, true, &[("a", &[0.0, 59.9])])),
            (V::Exceeds, R::RateExceeded)
        );
        assert_eq!(
            j(low, &o(120.0, true, &[("a", &[0.0, 60.0])])),
            (V::Within, R::RateKept)
        );
        assert_eq!(
            j(low, &o(30.0, true, &[("a", &[0.0])])),
            (V::Unobservable, R::WindowTooShort)
        );
        assert_eq!(
            j(low, &o(120.0, false, &[("a", &[0.0])])),
            (V::Unobservable, R::Lossy)
        );
        assert_eq!(j(low, &o(120.0, true, &[])), (V::Unobservable, R::Empty));
        // Per member: two members once each is no excess.
        assert_eq!(
            j(low, &o(120.0, true, &[("a", &[0.0]), ("b", &[1.0])])),
            (V::Within, R::RateKept)
        );
        let burst = Some(Rate::Burst(3));
        assert_eq!(
            j(
                burst,
                &o(3600.0, true, &[("a", &[0.0, 1200.0, 2400.0, 3599.0])])
            ),
            (V::Exceeds, R::RateExceeded)
        );
        assert_eq!(
            j(
                burst,
                &o(3600.0, true, &[("a", &[0.0, 1200.0, 2400.0, 3600.0])])
            ),
            (V::Within, R::RateKept)
        );
        assert_eq!(j(None, &o(120.0, true, &[])), (V::NotAsked, R::NoRate));
        // The owner not present throughout (0.25): after too short, before
        // empty, and no excess hidden.
        let absent = |listened, of: &[(&str, &[f64])]| Occurrences {
            present: false,
            ..o(listened, true, of)
        };
        assert_eq!(
            j(low, &absent(120.0, &[("a", &[0.0])])),
            (V::Unobservable, R::OwnerAbsent)
        );
        assert_eq!(
            j(low, &absent(120.0, &[])),
            (V::Unobservable, R::OwnerAbsent)
        );
        assert_eq!(
            j(low, &absent(30.0, &[("a", &[0.0])])),
            (V::Unobservable, R::WindowTooShort)
        );
        assert_eq!(
            j(low, &absent(120.0, &[("a", &[0.0, 1.0])])),
            (V::Exceeds, R::RateExceeded)
        );
    }
}