zenkey-model 0.23.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
//! `health.v1`: how well a service serves
//! (`spec/profiles/health/v1.md`, #721).
//!
//! The profile's session-free half: the levels and their order (§2.1,
//! §2.6), the fault codes (§2.10), and the pure judgement of one reading of
//! one service (§2.11), built on [`freshness::judge_all`] for the status,
//! with a tool's roll-up of many (§2.2) and §5's other two questions.
//!
//! ```text
//! Read::from_wire(n)  ─▶ Level(OK < DEGRADED < FAILED) │ Unspecified │ Unlisted(n) │ Undecodable
//! judge(reading)      ─▶ healthy │ unhealthy │ stale │ unobservable │ not_asked, + reason, + level
//! rollup(judged…)     ─▶ the worst established level, every verdict counted
//! agrees(judged, read)─▶ §5 "does its status agree with its checks?": yes │ no │ unestablished
//! clock_ahead(p, heard)─▶ §5 "is its clock ahead?": yes │ no │ unestablished
//! code(s)             ─▶ profile │ application │ malformed
//! ```
//!
//! There is no I/O and no clock here. A reader observes presence, the
//! descriptor, the status (as [`freshness::Observation`]s, plus the level
//! of the latest value) and the checks, and hands them over as values. The
//! owner's puts, its heartbeats and its `clock_ahead` fault are the
//! runtime's.
//!
//! **Two majors** (#986's Q1). [`v2`] is `health.v2`'s
//! (`spec/profiles/health/v2.md`): packed records, words by table, and a
//! clock question a heartbeat answers alone. It restates this text by
//! reference, so what a reader concludes is one set for both:
//!
//! ```text
//! Major::of(interfaces)  ─▶ the major a descriptor's reading is judged under: v2 where it lists both
//! judge_status(…)        ─▶ §2.11's five steps from the status's freshness as judged, either major's
//! rollup · agrees        ─▶ over verdicts and levels of either major
//! ```
//!
//! A `health.v2` record's `unknown` is [`Read::Unspecified`], and one a
//! reader refuses [`Read::Undecodable`] ([`v2::level_read`]): unknown is
//! never `OK` under either. The clock question is each major's own
//! ([`clock_ahead`], [`v2::clock_ahead`]).

pub mod v2;

use std::fmt;
use std::time::Duration;

use crate::freshness::{self, Horizon, Observation};

/// The profile's name, as an annotation key's prefix carries it. Only
/// `health.v2` publishes a vocabulary ([`v2::VOCABULARY`]).
pub const NAME: &str = "health";

/// The profile's id, which is also its standard contract's interface id.
pub const PROFILE: &str = "health.v1";

/// The standard contract's interface id (§3).
pub const IFACE: &str = "health.v1";

/// The status's template (§3): `state/status`.
pub const STATUS: &str = "status";

/// The checks' template (§3): `state/checks/{check}`.
pub const CHECKS: &str = "checks/{check}";

/// The faults' template (§3): `stream/faults`.
pub const FAULTS: &str = "faults";

/// The status's horizon, the contract's `freshness.ttl_s` (§2.4).
pub const STATUS_TTL: Duration = Duration::from_secs(60);

/// The owner's bound between two confirmations of its status, ttl/2
/// (`freshness.v1` §2.4).
pub const STATUS_REFRESH: Duration = Duration::from_secs(30);

/// The contract's bound on an owner's checks (§2.3).
pub const MAX_CHECKS: u64 = 64;

/// The profile's code for a clock running ahead (§2.5, §2.10).
pub const CLOCK_AHEAD: &str = "clock_ahead";

/// The profile's table of fault codes (§2.10).
pub const CODES: &[&str] = &[CLOCK_AHEAD];

/// The status's horizon, as `freshness.v1` reads it.
#[must_use]
pub fn status_horizon() -> Horizon {
    Horizon::Within(STATUS_TTL)
}

/// Which major of the profile a service's health is read under
/// (`health.v2` §2.11's step 2, §2.12). The two are two interfaces: an
/// instance implements one, and a reader reads either.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Major {
    /// `health.v1`: protobuf records with free text.
    V1,
    /// `health.v2`: packed records, their words numbers ([`v2`]).
    V2,
}

impl Major {
    /// The major's interface id, which is its standard contract's.
    #[must_use]
    pub const fn iface(self) -> &'static str {
        match self {
            Major::V1 => IFACE,
            Major::V2 => v2::IFACE,
        }
    }

    /// The major an interface id names: the deployment's word across a
    /// constrained face, where no descriptor crosses (§2.8). `None` for
    /// any other interface.
    #[must_use]
    pub fn named(iface: &str) -> Option<Major> {
        [Major::V2, Major::V1]
            .into_iter()
            .find(|m| m.iface() == iface)
    }

    /// The major a descriptor is read by, from the interface ids its
    /// `interfaces` holds: `health.v2` where it lists it, `health.v1`
    /// where it lists that and not `health.v2`, and `None` where it lists
    /// neither, which is not asked (`not_listed`). One that lists both
    /// breaks `health.v2` §2.3, and is read as `health.v2`.
    #[must_use]
    pub fn of<'a>(interfaces: impl IntoIterator<Item = &'a str>) -> Option<Major> {
        let mut found = None;
        for iface in interfaces {
            match Major::named(iface) {
                Some(Major::V2) => return Some(Major::V2),
                Some(Major::V1) => found = Some(Major::V1),
                None => {}
            }
        }
        found
    }
}

/// A level (§2.1). The order is the declaration's: `Ok` < `Degraded` <
/// `Failed`, a later level being worse. `UNSPECIFIED` is not one (§2.6).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Level {
    Ok,
    Degraded,
    Failed,
}

impl Level {
    /// The enum's number on the wire (`health.v1.Level`).
    #[must_use]
    pub fn wire(self) -> i32 {
        match self {
            Self::Ok => 1,
            Self::Degraded => 2,
            Self::Failed => 3,
        }
    }

    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Ok => "ok",
            Self::Degraded => "degraded",
            Self::Failed => "failed",
        }
    }
}

impl fmt::Display for Level {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Ok => "OK",
            Self::Degraded => "DEGRADED",
            Self::Failed => "FAILED",
        })
    }
}

/// A level as a reader read it from a payload: a level, or unknown (§2.6).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Read {
    /// `OK`, `DEGRADED` or `FAILED`.
    Level(Level),
    /// `LEVEL_UNSPECIFIED`, 0: unknown, never `OK`. A `health.v2` record's
    /// `unknown` is this (`health.v2` §0, §2.6).
    Unspecified,
    /// A number the enum does not list, which proto3 keeps (its enums are
    /// open): unknown, never `OK`.
    Unlisted(i32),
    /// A payload that does not decode as the message: unknown. So is a
    /// `health.v2` record its reader refuses (`health.v2` §2.6).
    Undecodable,
}

impl Read {
    /// The enum's number as decoded.
    #[must_use]
    pub fn from_wire(n: i32) -> Self {
        match n {
            0 => Self::Unspecified,
            1 => Self::Level(Level::Ok),
            2 => Self::Level(Level::Degraded),
            3 => Self::Level(Level::Failed),
            n => Self::Unlisted(n),
        }
    }

    /// The level, when it is one.
    #[must_use]
    pub fn level(self) -> Option<Level> {
        match self {
            Self::Level(l) => Some(l),
            _ => None,
        }
    }
}

/// The worst of the levels among `checks`, with the index of the first
/// check at it; a check at an unknown level bounds nothing (§2.2).
#[must_use]
pub fn worst_check(checks: &[Read]) -> Option<(usize, Level)> {
    checks
        .iter()
        .enumerate()
        .filter_map(|(i, r)| r.level().map(|l| (i, l)))
        .fold(None, |best, (i, l)| match best {
            Some((_, b)) if b >= l => best,
            _ => Some((i, l)),
        })
}

/// §2.2: whether a status at `status` is no better than its worst current
/// check. A status may be worse.
#[must_use]
pub fn consistent(status: Level, checks: &[Read]) -> bool {
    worst_check(checks).is_none_or(|(_, w)| w <= status)
}

/// What the descriptor of a present service says (§2.7).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Listing {
    /// Its `interfaces` list `health.v1`, with its `"token"`: `false` for an
    /// interface in the tokenless set. The token plays no part in a verdict.
    Listed { token: bool },
    /// Its `interfaces` do not list `health.v1`.
    NotListed,
    /// The descriptor could not be read.
    Unread,
}

/// A service's presence, as the reader saw it (core §8.1, §8.5).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Presence {
    /// Its instance token was seen, with what its descriptor says.
    Present(Listing),
    /// A complete read held no instance token of it.
    Absent,
    /// Its token was not seen, in a read possibly incomplete or refused.
    Incomplete,
    /// Across a constrained face, where tokens and descriptors do not
    /// cross, and the deployment's word says the service implements
    /// `health.v1` (core R7): whether the face lets `state/status` cross.
    AcrossFace { status_crosses: bool },
}

/// One reading of one service (§0, §2.11).
#[derive(Debug, Clone, Copy)]
pub struct Reading<'a> {
    pub presence: Presence,
    /// The observations of `state/status`, judged as `freshness.v1` judges
    /// them, at [`STATUS_TTL`].
    pub status: &'a [Observation],
    /// The level of the latest status value read, or `None` when no value
    /// was read.
    pub level: Option<Read>,
    /// The levels of the checks the owner answered, or `None` when the
    /// checks were not read.
    pub checks: Option<&'a [Read]>,
}

/// The answer to "is this service healthy?" (§5). Unhealthy and stale are
/// findings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Verdict {
    Healthy,
    Unhealthy,
    /// The status was not confirmed within its horizon: a finding of its
    /// own, never a level (§2.4).
    Stale,
    /// The question was put, and the reading could not answer it.
    Unobservable,
    /// Nobody put the question, or its premise does not hold (the reason
    /// says which).
    NotAsked,
}

impl Verdict {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Healthy => "healthy",
            Self::Unhealthy => "unhealthy",
            Self::Stale => "stale",
            Self::Unobservable => "unobservable",
            Self::NotAsked => "not_asked",
        }
    }

    /// Whether the verdict is a finding (§5's polarity).
    #[must_use]
    pub fn is_finding(self) -> bool {
        matches!(self, Self::Unhealthy | Self::Stale)
    }
}

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 (§2.11).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Reason {
    /// Healthy: a fresh status at `OK`, no current check worse.
    Ok,
    /// Unhealthy: a fresh status at `DEGRADED`.
    Degraded,
    /// Unhealthy: a fresh status at `FAILED`.
    Failed,
    /// Unhealthy: a current check worse than the status, which breaks §2.2;
    /// read at the check's level.
    Inconsistent,
    /// Unhealthy: the status's level unknown, and a current check
    /// `DEGRADED` or `FAILED`.
    Check,
    /// Unobservable: the status's level is unknown (§2.6).
    UnknownLevel,
    /// Unobservable: the status's payload did not decode (§2.6).
    Undecodable,
    /// Unobservable: the owner deleted its status, which §2.3 forbids.
    Deleted,
    /// Unobservable: its token not seen, in a read possibly incomplete.
    PresenceIncomplete,
    /// Unobservable: the descriptor could not be read (§2.7).
    NoDescriptor,
    /// Unobservable: across a face that does not let the status cross
    /// (§2.8).
    FaceClosed,
    /// Unobservable: across a face that lets the status cross, nothing of
    /// it arrived, so no status is known to exist (§2.8, `freshness.v1`
    /// §2.5).
    NothingCrossed,
    /// Not asked: absent, presence's word (§2.1).
    Absent,
    /// Not asked: the descriptor does not list `health.v1` (§2.7).
    NotListed,
    /// Not asked: only an archive's status was read, last-known (core S6).
    LastKnown,
    /// Unobservable, for §5's second question only ([`agrees`]): the checks
    /// were not read, so whether one is worse than the status is not known.
    ChecksUnread,
    /// Stale or unobservable: the status's freshness, `freshness.v1`'s
    /// reason.
    Freshness(freshness::Reason),
}

impl Reason {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Ok => "ok",
            Self::Degraded => "degraded",
            Self::Failed => "failed",
            Self::Inconsistent => "inconsistent",
            Self::Check => "check",
            Self::UnknownLevel => "unknown_level",
            Self::Undecodable => "undecodable",
            Self::Deleted => "deleted",
            Self::PresenceIncomplete => "presence_incomplete",
            Self::NoDescriptor => "no_descriptor",
            Self::FaceClosed => "face_closed",
            Self::NothingCrossed => "nothing_crossed",
            Self::Absent => "absent",
            Self::NotListed => "not_listed",
            Self::LastKnown => "last_known",
            Self::ChecksUnread => "checks_unread",
            Self::Freshness(r) => r.as_str(),
        }
    }

    /// The reason in words, for a tool's message.
    #[must_use]
    pub fn says(self) -> &'static str {
        match self {
            Self::Ok => "its status is OK and confirmed, and no check is worse",
            Self::Degraded => "its status is DEGRADED",
            Self::Failed => "its status is FAILED",
            Self::Inconsistent => "a check is worse than its status, which health.v1 §2.2 forbids",
            Self::Check => "its status's level is unknown, and a check is DEGRADED or FAILED",
            Self::UnknownLevel => "its status's level is unknown",
            Self::Undecodable => "its status does not decode",
            Self::Deleted => "its owner deleted its status",
            Self::PresenceIncomplete => {
                "its token was not seen, and the presence read may be incomplete or refused"
            }
            Self::NoDescriptor => "its descriptor could not be read",
            Self::FaceClosed => "the constrained face does not let its status cross",
            Self::NothingCrossed => {
                "nothing of its status has crossed the constrained face, so none is known to exist"
            }
            Self::Absent => "it is absent: presence's word, not a level",
            Self::NotListed => "its descriptor does not list health.v1",
            Self::LastKnown => "only an archive's last-known status was read, never current",
            Self::ChecksUnread => "its checks were not read",
            Self::Freshness(r) => r.says(),
        }
    }
}

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 for healthy and unhealthy the level it rests
/// on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Judged {
    pub verdict: Verdict,
    pub reason: Reason,
    pub level: Option<Level>,
}

impl Judged {
    const fn new(verdict: Verdict, reason: Reason, level: Option<Level>) -> Self {
        Self {
            verdict,
            reason,
            level,
        }
    }

    const fn unobservable(reason: Reason) -> Self {
        Self::new(Verdict::Unobservable, reason, None)
    }

    const fn not_asked(reason: Reason) -> Self {
        Self::new(Verdict::NotAsked, reason, None)
    }

    const fn unhealthy(reason: Reason, level: Level) -> Self {
        Self::new(Verdict::Unhealthy, reason, Some(level))
    }
}

/// Judges one reading by §2.11's order: presence, the descriptor, the
/// status's freshness ([`freshness::judge_all`] at [`STATUS_TTL`]), its
/// level, then the checks it vouches for.
#[must_use]
pub fn judge(r: &Reading<'_>) -> Judged {
    let status = freshness::judge_all(&status_horizon(), r.status);
    judge_status(r.presence, status, r.level, r.checks)
}

/// §2.11's five steps from the status's freshness as judged, for a reader
/// that holds `freshness.v2`'s verdict over its observations of
/// `state/status` at the standard contract's horizon rather than the
/// observations: presence, the descriptor, that verdict, the level of the
/// latest status read (`None` where no value was read), then the checks
/// the owner answered (`None` where they were not read).
///
/// Either major's reading is judged so (`health.v2` §2.11): the steps,
/// the verdicts and the reasons are one set. For `health.v2` the
/// presence's [`Listing`] says whether the descriptor lists a major
/// ([`Major::of`]), and a level is read from a record
/// ([`v2::level_read`]).
#[must_use]
pub fn judge_status(
    presence: Presence,
    status: freshness::Judged,
    level: Option<Read>,
    checks: Option<&[Read]>,
) -> Judged {
    use Reason as R;
    // 1. Presence; 2. the descriptor.
    match presence {
        Presence::Absent => return Judged::not_asked(R::Absent),
        Presence::Incomplete => return Judged::unobservable(R::PresenceIncomplete),
        Presence::AcrossFace {
            status_crosses: false,
        } => return Judged::unobservable(R::FaceClosed),
        Presence::Present(Listing::NotListed) => return Judged::not_asked(R::NotListed),
        Presence::Present(Listing::Unread) => return Judged::unobservable(R::NoDescriptor),
        Presence::AcrossFace {
            status_crosses: true,
        }
        | Presence::Present(Listing::Listed { .. }) => {}
    }
    // 3. The status's freshness.
    let f = status;
    match f.verdict {
        freshness::Verdict::Fresh => {}
        // A present, listed owner holds a status (§2.3), so silence ages
        // it. Across a face nothing says one exists until something
        // crosses (`freshness.v1` §2.5, "a member it knows").
        freshness::Verdict::Stale
            if f.reason == freshness::Reason::NoDelivery
                && matches!(presence, Presence::AcrossFace { .. }) =>
        {
            return Judged::unobservable(R::NothingCrossed);
        }
        freshness::Verdict::Stale => {
            return Judged::new(Verdict::Stale, R::Freshness(f.reason), None);
        }
        freshness::Verdict::Unobservable => return Judged::unobservable(R::Freshness(f.reason)),
        freshness::Verdict::NotAsked => {
            return match f.reason {
                freshness::Reason::Deleted => Judged::unobservable(R::Deleted),
                freshness::Reason::LastKnown => Judged::not_asked(R::LastKnown),
                // No horizon, or a kind without one: not at the status's
                // fixed horizon, but kept apart rather than guessed.
                other => Judged::not_asked(R::Freshness(other)),
            };
        }
    }
    // 4. The status's level; 5. the checks, current with a fresh status.
    let worst = worst_check(checks.unwrap_or(&[])).map(|(_, l)| l);
    match level.and_then(Read::level) {
        Some(status) => match worst {
            Some(w) if w > status => Judged::unhealthy(R::Inconsistent, w),
            _ => match status {
                Level::Ok => Judged::new(Verdict::Healthy, R::Ok, Some(Level::Ok)),
                Level::Degraded => Judged::unhealthy(R::Degraded, Level::Degraded),
                Level::Failed => Judged::unhealthy(R::Failed, Level::Failed),
            },
        },
        None => match worst {
            Some(w) if w > Level::Ok => Judged::unhealthy(R::Check, w),
            _ => Judged::unobservable(match level {
                Some(Read::Unspecified | Read::Unlisted(_)) => R::UnknownLevel,
                // A fresh status always carries a value; a level not read
                // from it is a payload not read.
                _ => R::Undecodable,
            }),
        },
    }
}

/// A tool's roll-up of many services (§2.2, §5).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Rollup {
    /// The worst level among the established verdicts, healthy and
    /// unhealthy; `None` when none is established.
    pub worst: Option<Level>,
    pub healthy: usize,
    pub unhealthy: usize,
    pub stale: usize,
    pub unobservable: usize,
    pub not_asked: usize,
}

/// Rolls up judged readings: the worst established level, with every
/// verdict counted, and stale, unobservable and not asked never folded into
/// a level (§2.2).
#[must_use]
pub fn rollup(judged: impl IntoIterator<Item = Judged>) -> Rollup {
    let mut r = Rollup::default();
    for j in judged {
        match j.verdict {
            Verdict::Healthy => r.healthy += 1,
            Verdict::Unhealthy => r.unhealthy += 1,
            Verdict::Stale => r.stale += 1,
            Verdict::Unobservable => r.unobservable += 1,
            Verdict::NotAsked => r.not_asked += 1,
        }
        if matches!(j.verdict, Verdict::Healthy | Verdict::Unhealthy) {
            r.worst = r.worst.max(j.level);
        }
    }
    r
}

/// A yes-or-no question of §5, answered in the three states: a pole of each
/// Established kind, and the two Unestablished kinds apart (core O5).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Answer {
    Yes,
    No,
    /// The question was put, and the reading could not answer it.
    Unobservable,
    /// Nobody put the question, or its premise does not hold.
    NotAsked,
}

impl Answer {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Yes => "yes",
            Self::No => "no",
            Self::Unobservable => "unobservable",
            Self::NotAsked => "not_asked",
        }
    }
}

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

/// §5's second question, "does its status agree with its checks?" (§2.2),
/// for one reading, and its reason in [`Reason`]'s vocabulary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Agreement {
    pub answer: Answer,
    pub reason: Reason,
}

/// §5's second question over one reading, from what [`judge`] concluded of
/// it and whether its checks were read: *yes* for a fresh status at a level
/// with no current check worse; *no* for a current check worse than that
/// status ([`Reason::Inconsistent`], the finding about the owner, which a
/// tool reports only from two readings a grace apart, §2.2); not asked as
/// the first question's not asked; unobservable when the status is not
/// fresh, its level is unknown, or the checks were not read.
#[must_use]
pub fn agrees(judged: Judged, checks_read: bool) -> Agreement {
    let a = |answer, reason| Agreement { answer, reason };
    match (judged.verdict, judged.reason) {
        (Verdict::NotAsked, r) => a(Answer::NotAsked, r),
        (_, Reason::Inconsistent) => a(Answer::No, Reason::Inconsistent),
        (
            Verdict::Healthy | Verdict::Unhealthy,
            r @ (Reason::Ok | Reason::Degraded | Reason::Failed),
        ) => {
            if checks_read {
                a(Answer::Yes, r)
            } else {
                a(Answer::Unobservable, Reason::ChecksUnread)
            }
        }
        // A status at an unknown level bounds nothing (§2.6), so whether a
        // check is worse than it has no answer.
        (Verdict::Unhealthy, Reason::Check) => a(Answer::Unobservable, Reason::UnknownLevel),
        (_, r) => a(Answer::Unobservable, r),
    }
}

/// One delivery a subscriber heard of one service during its reading, as
/// §5's last question reads it.
///
/// Since text 0.9 (#978's F6) the clock guard holds no write of the
/// status, which carries no Zenoh timestamp, and the heartbeat goes on
/// vouching while it holds. So the evidence that the guard does not hold is
/// a heartbeat's time, known, never a confirmation of the status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Heard {
    /// A heartbeat covering `health.v1`, its status's section read in step
    /// with the reader's view (`freshness.v2` §2.5, `confirmed`, its bit
    /// set or clear), whose time is known: the guard did not hold when the
    /// owner wrote it (`freshness.v2` §2.10).
    Heartbeat,
    /// The same, whose time is no instant: the ahead time, as while the
    /// guard holds (core §7.5, `freshness.v2` §2.10), or the unknown time,
    /// all ones. Under this major neither answers alone: the fault does
    /// (text 0.11; `health.v2` §2.5 reads the ahead time as a yes).
    HeartbeatHeld,
    /// A put of `state/status`: the guard does not hold it, so it says
    /// nothing of the clock.
    StatusPut,
    /// A delete of `state/status`, which §2.3 forbids: nothing of the
    /// clock.
    StatusDeleted,
    /// A `faults` sample whose code is `clock_ahead` (§2.5, §2.10).
    ClockAhead,
    /// A `faults` sample with any other code, which says nothing of the
    /// clock.
    Fault,
}

impl Heard {
    /// A heartbeat read in step, by the time it carries (core §7.5):
    /// [`Heard::Heartbeat`] for an instant, [`Heard::HeartbeatHeld`] for
    /// the ahead time and for the unknown time. Under this major the ahead
    /// time is read exactly as the unknown time it replaced was, so core
    /// 0.113 moved no answer of [`clock_ahead`] (text 0.11).
    #[must_use]
    pub fn heartbeat(time: crate::heartbeat::Time) -> Heard {
        if time.is_instant() {
            Heard::Heartbeat
        } else {
            Heard::HeartbeatHeld
        }
    }
}

/// Why §5's last question has its answer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClockReason {
    /// Yes, under `health.v2` alone ([`v2::clock_of`]): the last heartbeat
    /// read carries the ahead time, so its owner's guard held when it
    /// wrote it (`health.v2` §2.5).
    Ahead,
    /// Yes: a `clock_ahead` fault, and no heartbeat whose time is known
    /// heard since.
    ClockAhead,
    /// No: the last heartbeat heard has its time known, and came after the
    /// last `clock_ahead` fault, or with none heard. Its guard did not hold
    /// when the owner wrote it.
    Confirmed,
    /// Unobservable: no `clock_ahead` fault heard since the last heartbeat
    /// whose time is known, and the last heartbeat's time no instant,
    /// ahead or unknown.
    TimeUnknown,
    /// Unobservable: no `clock_ahead` fault and no heartbeat heard within
    /// the reader's window. Never "no" from the faults' silence.
    NothingHeard,
    /// Not asked: absent, presence's word (§2.1).
    Absent,
    /// Not asked: the descriptor does not list `health.v1` (§2.7).
    NotListed,
}

impl ClockReason {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Ahead => "ahead",
            Self::ClockAhead => "clock_ahead",
            Self::Confirmed => "confirmed",
            Self::TimeUnknown => "time_unknown",
            Self::NothingHeard => "nothing_heard",
            Self::Absent => "absent",
            Self::NotListed => "not_listed",
        }
    }

    /// The reason in words, for a tool's message.
    #[must_use]
    pub fn says(self) -> &'static str {
        match self {
            Self::Ahead => "its last heartbeat's time was ahead: its clock guard held",
            Self::ClockAhead => {
                "a clock_ahead fault was heard, and no heartbeat with its time known since"
            }
            Self::Confirmed => {
                "its last heartbeat had its time known, after its last clock_ahead fault or with \
                 none heard"
            }
            Self::TimeUnknown => {
                "its last heartbeat's time was no instant, ahead or unknown, and no clock_ahead \
                 fault was heard since one with its time known"
            }
            Self::NothingHeard => "no clock_ahead fault and no heartbeat was heard in the window",
            Self::Absent => "it is absent: presence's word",
            Self::NotListed => "its descriptor does not list health.v1",
        }
    }
}

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

/// §5's last question, "is this service's clock ahead?" (§2.5), and why.
/// Yes is the finding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Clock {
    pub answer: Answer,
    pub reason: ClockReason,
}

/// §5's last question from what one subscriber heard of one service in its
/// window, in arrival order: *yes* on a `clock_ahead` fault with no
/// heartbeat whose time is known heard since; *no* when the last heartbeat
/// heard has its time known and came after the last fault, or with none
/// heard; unobservable otherwise, since the faults' silence is their
/// normal state (core O5) and a time that is no instant, ahead or unknown,
/// answers nothing alone under this major. A put
/// or a delete of the status says nothing of the clock: the guard holds
/// neither (§2.5). Not asked as the first question's: absent, or not
/// listing `health.v1`. Whatever else presence says, a fault heard is the
/// service's own word, and answers. Nothing rests on a fault's stamp, nor
/// its level (§2.5).
#[must_use]
pub fn clock_ahead(presence: Presence, heard: &[Heard]) -> Clock {
    let c = |answer, reason| Clock { answer, reason };
    match presence {
        Presence::Absent => return c(Answer::NotAsked, ClockReason::Absent),
        Presence::Present(Listing::NotListed) => {
            return c(Answer::NotAsked, ClockReason::NotListed);
        }
        _ => {}
    }
    let last = |h: Heard| heard.iter().rposition(|x| *x == h);
    let fault = last(Heard::ClockAhead);
    let known = last(Heard::Heartbeat);
    let unknown = last(Heard::HeartbeatHeld);
    match (fault, known, unknown) {
        (Some(f), k, _) if k.is_none_or(|k| k < f) => c(Answer::Yes, ClockReason::ClockAhead),
        (_, Some(k), u) if u.is_none_or(|u| u < k) => c(Answer::No, ClockReason::Confirmed),
        (_, _, Some(_)) => c(Answer::Unobservable, ClockReason::TimeUnknown),
        _ => c(Answer::Unobservable, ClockReason::NothingHeard),
    }
}

/// A fault's code, read by §2.10.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Code<'a> {
    /// A code of the profile's table ([`CODES`]).
    Profile(&'static str),
    /// Any other code of the form `[a-z][a-z0-9_]*`: an application's.
    Application(&'a str),
    /// Not of that form: still an occurrence, shown verbatim.
    Malformed(&'a str),
}

impl Code<'_> {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Profile(_) => "profile",
            Self::Application(_) => "application",
            Self::Malformed(_) => "malformed",
        }
    }
}

/// Whether `s` has a code's form (§2.10): `[a-z][a-z0-9_]*`, the whole
/// of it. `health.v2`'s names have it too ([`v2::is_name`]).
#[must_use]
pub fn is_code_form(s: &str) -> bool {
    let mut bytes = s.bytes();
    bytes.next().is_some_and(|b| b.is_ascii_lowercase())
        && bytes.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
}

/// Reads a fault's code (§2.10), exactly: no trimming, no case folding.
#[must_use]
pub fn code(s: &str) -> Code<'_> {
    if !is_code_form(s) {
        return Code::Malformed(s);
    }
    match CODES.iter().find(|c| **c == s) {
        Some(c) => Code::Profile(c),
        None => Code::Application(s),
    }
}

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

    fn fresh() -> [Observation; 1] {
        [Observation::Subscribed {
            last: Some(Last::Put(Duration::from_secs(10))),
            listened: Duration::from_secs(120),
            complete: true,
        }]
    }

    fn present() -> Presence {
        Presence::Present(Listing::Listed { token: false })
    }

    #[test]
    fn the_levels_are_ordered_and_unspecified_is_none_of_them() {
        assert!(Level::Ok < Level::Degraded && Level::Degraded < Level::Failed);
        for l in [Level::Ok, Level::Degraded, Level::Failed] {
            assert_eq!(Read::from_wire(l.wire()), Read::Level(l));
        }
        assert_eq!(Read::from_wire(0), Read::Unspecified);
        assert_eq!(Read::from_wire(4), Read::Unlisted(4));
        assert_eq!(Read::Unspecified.level(), None);
    }

    #[test]
    fn the_worst_check_is_the_first_at_the_worst_known_level() {
        let checks = [
            Read::Level(Level::Degraded),
            Read::Unlisted(9),
            Read::Level(Level::Failed),
            Read::Level(Level::Failed),
        ];
        assert_eq!(worst_check(&checks), Some((2, Level::Failed)));
        assert_eq!(worst_check(&[Read::Unspecified]), None);
        assert!(consistent(Level::Failed, &checks));
        assert!(!consistent(Level::Degraded, &checks));
        assert!(consistent(Level::Ok, &[]));
    }

    #[test]
    fn a_fresh_status_vouches_for_its_checks_and_a_stale_one_does_not() {
        let o = fresh();
        let checks = [Read::Level(Level::Failed)];
        let mut r = Reading {
            presence: present(),
            status: &o,
            level: Some(Read::Level(Level::Ok)),
            checks: Some(&checks),
        };
        assert_eq!(
            judge(&r),
            Judged::unhealthy(Reason::Inconsistent, Level::Failed)
        );
        let stale = [Observation::Subscribed {
            last: Some(Last::Put(Duration::from_secs(61))),
            listened: Duration::from_secs(120),
            complete: true,
        }];
        r.status = &stale;
        assert_eq!(judge(&r).verdict, Verdict::Stale);
    }

    #[test]
    fn a_rollup_never_folds_stale_into_a_level() {
        let stale = Judged::new(
            Verdict::Stale,
            Reason::Freshness(freshness::Reason::BeyondHorizon),
            None,
        );
        let r = rollup([
            stale,
            Judged::new(Verdict::Healthy, Reason::Ok, Some(Level::Ok)),
        ]);
        assert_eq!(r.worst, Some(Level::Ok));
        assert_eq!((r.healthy, r.stale), (1, 1));
        assert_eq!(rollup([stale]).worst, None);
    }

    #[test]
    fn the_status_agrees_with_its_checks_only_when_fresh_at_a_level_and_read() {
        let j = |verdict, reason, level| Judged::new(verdict, reason, level);
        let ok = j(Verdict::Healthy, Reason::Ok, Some(Level::Ok));
        assert_eq!(agrees(ok, true).answer, Answer::Yes);
        assert_eq!(
            agrees(ok, false),
            Agreement {
                answer: Answer::Unobservable,
                reason: Reason::ChecksUnread
            }
        );
        let liar = Judged::unhealthy(Reason::Inconsistent, Level::Failed);
        assert_eq!(agrees(liar, true).answer, Answer::No);
        let frank = Judged::unhealthy(Reason::Failed, Level::Failed);
        assert_eq!(agrees(frank, true).answer, Answer::Yes, "worse is allowed");
        let unknown = Judged::unhealthy(Reason::Check, Level::Failed);
        assert_eq!(agrees(unknown, true).reason, Reason::UnknownLevel);
        let stale = j(
            Verdict::Stale,
            Reason::Freshness(freshness::Reason::BeyondHorizon),
            None,
        );
        assert_eq!(agrees(stale, true).answer, Answer::Unobservable);
        let absent = Judged::not_asked(Reason::Absent);
        assert_eq!(agrees(absent, true).answer, Answer::NotAsked);
    }

    #[test]
    fn the_clock_is_ahead_on_a_fault_no_heartbeat_with_its_time_followed() {
        use Heard::{ClockAhead, Fault, Heartbeat, HeartbeatHeld, StatusDeleted, StatusPut};
        let p = present();
        let a = |heard: &[Heard]| clock_ahead(p, heard).answer;
        assert_eq!(a(&[ClockAhead]), Answer::Yes);
        assert_eq!(a(&[Heartbeat, ClockAhead]), Answer::Yes);
        assert_eq!(a(&[ClockAhead, Heartbeat]), Answer::No);
        assert_eq!(a(&[ClockAhead, StatusDeleted]), Answer::Yes);
        assert_eq!(
            a(&[ClockAhead, StatusPut]),
            Answer::Yes,
            "the guard holds no put"
        );
        assert_eq!(a(&[ClockAhead, HeartbeatHeld]), Answer::Yes);
        assert_eq!(a(&[Heartbeat]), Answer::No);
        assert_eq!(a(&[StatusPut]), Answer::Unobservable);
        assert_eq!(
            clock_ahead(p, &[Heartbeat, HeartbeatHeld]).reason,
            ClockReason::TimeUnknown,
            "a time unknown since: no longer no, and no fault to say yes"
        );
        assert_eq!(a(&[ClockAhead, HeartbeatHeld, Heartbeat]), Answer::No);
        // Core 0.113's ahead time reads as the unknown time did (text
        // 0.11): no instant, so no evidence either way under this major.
        use crate::heartbeat::Time;
        assert_eq!(Heard::heartbeat(Time::Ahead), HeartbeatHeld);
        assert_eq!(Heard::heartbeat(Time::Unknown), HeartbeatHeld);
        assert_eq!(Heard::heartbeat(Time::At { secs: 7, ms: 0 }), Heartbeat);
        assert_eq!(
            clock_ahead(p, &[Heartbeat, Heard::heartbeat(Time::Ahead)]).reason,
            ClockReason::TimeUnknown,
            "the ahead time alone answers nothing under health.v1"
        );
        assert_eq!(a(&[Fault]), Answer::Unobservable, "never from silence");
        assert_eq!(a(&[]), Answer::Unobservable);
        assert_eq!(
            clock_ahead(Presence::Absent, &[ClockAhead]).answer,
            Answer::NotAsked
        );
    }

    /// `health.v2` §2.11's step 2 and §2.12: a reader reads a service by
    /// the major its descriptor lists, `health.v2` where it lists both.
    #[test]
    fn a_descriptor_is_read_by_the_major_it_lists_and_v2_where_it_lists_both() {
        assert_eq!(Major::of(["freshness.v2", "health.v1"]), Some(Major::V1));
        assert_eq!(Major::of(["health.v2", "freshness.v2"]), Some(Major::V2));
        assert_eq!(Major::of(["health.v1", "health.v2"]), Some(Major::V2));
        assert_eq!(Major::of(["health.v2", "health.v1"]), Some(Major::V2));
        assert_eq!(Major::of(["tc.v1"]), None, "not listed: not asked");
        assert_eq!(Major::of([]), None);
        assert_eq!(Major::named("health.v2"), Some(Major::V2));
        assert_eq!(Major::named("health.v3"), None);
        assert_eq!((Major::V1.iface(), Major::V2.iface()), (IFACE, v2::IFACE));
    }

    /// A status's freshness as judged gives what its observations give:
    /// [`judge`] is [`judge_status`] over `freshness.v2`'s verdict.
    #[test]
    fn a_reading_is_judged_alike_from_its_observations_and_from_their_verdict() {
        let o = fresh();
        let status = freshness::judge_all(&status_horizon(), &o);
        assert_eq!(status.verdict, freshness::Verdict::Fresh);
        let checks = [Read::Level(Level::Degraded)];
        for level in [
            Some(Read::Level(Level::Ok)),
            Some(Read::Unspecified),
            Some(Read::Undecodable),
            None,
        ] {
            let r = Reading {
                presence: present(),
                status: &o,
                level,
                checks: Some(&checks),
            };
            assert_eq!(
                judge(&r),
                judge_status(present(), status, level, Some(&checks))
            );
        }
        // A `health.v2` record at `unknown`, and one refused: never ok.
        let unknown = judge_status(present(), status, Some(Read::Unspecified), None);
        assert_eq!(
            (unknown.verdict, unknown.reason),
            (Verdict::Unobservable, Reason::UnknownLevel)
        );
        let refused = judge_status(present(), status, Some(Read::Undecodable), None);
        assert_eq!(
            (refused.verdict, refused.reason),
            (Verdict::Unobservable, Reason::Undecodable)
        );
    }

    #[test]
    fn codes_are_lowercase_ascii_and_the_table_is_the_profiles() {
        assert_eq!(code("clock_ahead"), Code::Profile(CLOCK_AHEAD));
        assert_eq!(code("tc_netns_gone"), Code::Application("tc_netns_gone"));
        assert_eq!(code(""), Code::Malformed(""));
        assert_eq!(code("_x"), Code::Malformed("_x"));
        assert_eq!(code("Clock_ahead").as_str(), "malformed");
    }
}