Skip to main content

zenkey_model/alarms/
v2.rs

1//! `alarms.v2`: the active alarms of one service, in slots
2//! (`spec/profiles/alarms/v2.md`, text 0.1, #984's S1).
3//!
4//! The profile's session-free half. It restates `alarms.v1` by reference,
5//! so the alert key, the sanitizing step, the severities, §2.6's table and
6//! "is anything firing?" are [`super`]'s, over either major. What this
7//! module adds is what the major replaces:
8//!
9//! ```text
10//! Record                      ─▶ the packed `Alarm` (§2.4, §3): write, put, read; core §7.6's refusals, then key_with_rule, key_missing
11//! slot_of · alarm_key · …     ─▶ §2.2, §2.12: a slot is the key's last chunk, and a reference names a collection read
12//! Rule, declaration(…)        ─▶ §4: a contract's `alarms.rules`: none │ a list │ one of eight findings; lint_contract
13//! instance_table(named…)      ─▶ the one table among the revisions a descriptor names: none │ a list │ differ
14//! write_alarm · Record::name  ─▶ words ⇄ a rule's index, its labels' codes and its argument, or by words with the alert key
15//! Slots                       ─▶ §2.2, §2.8, §2.9: the slot an identity takes, the bound's refusal, a restart's adoption
16//! taken(seen, run)            ─▶ §2.6: which of two slots a reader takes for one identity, none with no run; §2.2's break
17//! Words, words_taken          ─▶ §2.4: `words/{slot}`, taken only where they derive the record's key
18//! Track::apply(sample)        ─▶ §2.6: one slot read by identity: rebound │ replaced │ dropped, then v1's table
19//! Dating, acknowledged        ─▶ §2.5: `at`, new at a transition, a second at a time, and the acknowledgement it carries
20//! Seed::of(replies)           ─▶ a late joiner's snapshot, entry by entry (§3, core §7.5)
21//! firing · stale_firing       ─▶ §2.14, with `rebound`; the state is the record's, never a bit's or a count's (§2.7)
22//! owner_set(p, read, since)   ─▶ §2.15: established by one complete snapshot, with an entry or with none
23//! ```
24//!
25//! **No I/O, no clock, and no file.** The standard schema is restated here
26//! as a declaration ([`layout`]), since no crate may read `spec/`;
27//! `tests/profiles/alarms_v2.rs` holds it to
28//! `spec/profiles/alarms/alarms.v2.json`'s layout, its form's hash and its
29//! tag. The owner's puts and its record file are the runtime's, and the
30//! readers on a bus the fleet's (#984's S2 and S3).
31
32use std::collections::BTreeMap;
33use std::sync::OnceLock;
34
35use serde_json::{Map, Value, json};
36
37use super::{
38    Answer, Asked, Judged, Presence, PutFacts, Reason, SetJudged, SetVerdict, Severity, State,
39    Step5, Transition,
40};
41use crate::collection::{self, Confirmation, Page};
42use crate::contract::Contract;
43use crate::freshness;
44use crate::grammar::{self, Addr, IfaceId, Key, KeyError, KindToken, ZkKey};
45use crate::heartbeat;
46use crate::packed::{self, Decimal, Fixed, Layout, ReadRefusal, WriteRefusal};
47use crate::template::Template;
48use crate::wire::{Envelope, Run, Seq, Stamp, Tag};
49use crate::words;
50
51/// The profile's id, which is also its standard contract's interface id.
52pub const PROFILE: &str = "alarms.v2";
53
54/// The standard contract's interface id (§3).
55pub const IFACE: &str = "alarms.v2";
56
57/// Revision 2.0 of the standard contract (§3), `alarms.v2.toml`: its
58/// fingerprint's hex. Its heartbeat's tag is its last hex digit, 7 (core
59/// §7.5).
60pub const FINGERPRINT: &str = "2292477cadf555dd09b07499ca048add4e48c63d60a209c13eaf543988c32cb7";
61
62/// The two standard schemas' stem (§3): `alarms.v2.json`, the packed file
63/// and the JSON Schema under `schemas/`.
64pub const SCHEMA_STEM: &str = "alarms.v2";
65
66/// The standard schemas' artifact ids the profile publishes (§3), oldest
67/// first: text 0.1's packed `Alarm`, then its JSON `alarms.v2.Words`.
68pub const PUBLISHED: &[&str] = &[
69    "sha256:fe59e748fc957322428ac633a0908d09aa8b6c66952f7a9cdd8608db715a2b2a",
70    "sha256:a3515ad47772ac778ccfbad3850a086ac18c28a9975eb7c8288c3437db9b99de",
71];
72
73/// Whether `id` is one of the standard schemas' published artifact ids.
74#[must_use]
75pub fn is_published(id: &str) -> bool {
76    PUBLISHED.contains(&id)
77}
78
79/// The annotation keys' names (§4): what W105 reads for a contract that
80/// lists `alarms.v2` (core §10). `alarms.v1`'s table stays empty.
81pub const VOCABULARY: &[&str] = &["rules"];
82
83/// The one annotation key (§4): a service's own table.
84pub const RULES: &str = "alarms.rules";
85
86/// The records' template (§3): `state/alarms/{slot}`.
87pub const ALARMS: &str = "alarms/{slot}";
88
89/// The words' template (§3): `state/words/{slot}`.
90pub const WORDS: &str = "words/{slot}";
91
92const ALARMS_CHUNK: &str = "alarms";
93const WORDS_CHUNK: &str = "words";
94
95/// The collection's index of `state/alarms/{slot}` in a snapshot (§3): the
96/// contract's `state` resources in the canonical form's order.
97pub const ALARMS_COLL: u32 = 0;
98
99/// The collection's index of `state/words/{slot}` in a snapshot (§3).
100pub const WORDS_COLL: u32 = 1;
101
102/// The packed `Alarm`'s tag (§3, core §7.6): never 0, the tag a type of
103/// any other kind carries.
104pub const TAG: u8 = 11;
105
106/// The contract's bound on one service's firing alarms, and the number of
107/// its slots (§2.2, §2.8): a descriptor may lower it.
108pub const MAX_SLOTS: u16 = 256;
109
110/// The most rules a table holds (§4): a record's `rule` has the indices 0
111/// to 254.
112pub const MAX_RULES: usize = 255;
113
114/// The greatest index of a table's rule.
115const MAX_INDEX: u8 = 254;
116
117/// The most bits a rule's labels take (§4).
118pub const LABELS_BITS: u32 = 24;
119
120/// The class of the alarms' collection (§2.7, `freshness.v2` §2.4): the
121/// standard contract exposes nothing `link`, so an owner heartbeat that
122/// covers the alarms is the `host` key's.
123pub const CLASS: heartbeat::Class = heartbeat::Class::Host;
124
125/// Whether a contract lists `alarms.v2` in `uses`: one that may declare
126/// the service's own table (§4).
127#[must_use]
128pub fn uses_v2(c: &Contract) -> bool {
129    words::uses(c, PROFILE)
130}
131
132fn iface() -> IfaceId {
133    IfaceId::new(super::NAME, 2).expect("alarms.v2 is an interface id")
134}
135
136// --- §2.2, §2.12: slots and keys ---------------------------------------------
137
138/// A key's chunk read as a slot (§2.2): a number from 0 to 255, written in
139/// decimal with no leading zero, as core §2.2 writes a `uint`. `None` for
140/// any other chunk, which is on no slot.
141#[must_use]
142pub fn parse_slot(chunk: &str) -> Option<u8> {
143    let digits = !chunk.is_empty() && chunk.bytes().all(|b| b.is_ascii_digit());
144    if !digits || (chunk.len() > 1 && chunk.starts_with('0')) {
145        return None;
146    }
147    chunk.parse().ok()
148}
149
150/// An owner and one of its slots, as a key of either template names them.
151#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
152pub struct SlotKey {
153    pub system: String,
154    pub service: String,
155    pub slot: u8,
156}
157
158fn slot_under(key: &str, chunk: &str) -> Option<SlotKey> {
159    let ZkKey::Data {
160        addr,
161        iface,
162        kind: KindToken::State,
163        resource,
164    } = grammar::parse(key).ok()?
165    else {
166        return None;
167    };
168    if iface.to_string() != IFACE {
169        return None;
170    }
171    let [lit, slot] = resource.as_slice() else {
172        return None;
173    };
174    if lit != chunk {
175        return None;
176    }
177    Some(SlotKey {
178        system: addr.system.as_str().to_owned(),
179        service: addr.service.as_str().to_owned(),
180        slot: parse_slot(slot)?,
181    })
182}
183
184/// The owner and the slot a record's key names (§2.2), `None` for a key
185/// that is no `alarms.v2/state/alarms/<slot>`: a reader reads nothing from
186/// such a member.
187#[must_use]
188pub fn slot_of(key: &str) -> Option<SlotKey> {
189    slot_under(key, ALARMS_CHUNK)
190}
191
192/// The same for `alarms.v2/state/words/<slot>` (§2.4).
193#[must_use]
194pub fn words_slot_of(key: &str) -> Option<SlotKey> {
195    slot_under(key, WORDS_CHUNK)
196}
197
198fn key_under(system: &str, service: &str, chunk: &str, slot: u8) -> Result<Key, KeyError> {
199    let addr = Addr::new(system, service)?;
200    grammar::data_key(
201        &addr,
202        &iface(),
203        KindToken::State,
204        &[chunk, &slot.to_string()],
205    )
206}
207
208/// A slot's record's key (§2.2):
209/// `zk2/<system>/<service>/alarms.v2/state/alarms/<slot>`.
210///
211/// # Errors
212/// [`KeyError`] when the system or the service is not a name (core §1.2).
213pub fn alarm_key(system: &str, service: &str, slot: u8) -> Result<Key, KeyError> {
214    key_under(system, service, ALARMS_CHUNK, slot)
215}
216
217/// A slot's words' key (§2.4):
218/// `zk2/<system>/<service>/alarms.v2/state/words/<slot>`.
219///
220/// # Errors
221/// As [`alarm_key`].
222pub fn words_key(system: &str, service: &str, slot: u8) -> Result<Key, KeyError> {
223    key_under(system, service, WORDS_CHUNK, slot)
224}
225
226/// Where a reference's alarm is found (§2.12): the selector of the
227/// collection read of its owner's records, and the snapshot key its answer
228/// comes on (core §4.2). A reference names no key and never a slot: the
229/// alarm is the one among those records that derives its alert key.
230#[derive(Debug, Clone, PartialEq, Eq)]
231pub struct CollectionRead {
232    pub selector: String,
233    pub snapshot_key: String,
234}
235
236/// [`CollectionRead`] for an owner's alarms.
237///
238/// # Errors
239/// As [`alarm_key`].
240pub fn collection_read(system: &str, service: &str) -> Result<CollectionRead, KeyError> {
241    let addr = Addr::new(system, service)?;
242    let template = Template::parse(ALARMS).expect("the standard template parses");
243    let members = grammar::template_selector(&addr, &iface(), KindToken::State, &template);
244    let selector = collection::collection_read(&members, &template)
245        .expect("a template whose first chunk is a literal has a snapshot key");
246    let snapshot_key =
247        grammar::data_key(&addr, &iface(), KindToken::State, &[ALARMS_CHUNK])?.to_string();
248    Ok(CollectionRead {
249        selector,
250        snapshot_key,
251    })
252}
253
254// --- §2.4, §3: the record -----------------------------------------------------
255
256/// The record's name for a `rule` or an `argument` that is none (core
257/// §7.6's reserved code).
258pub const NOT_AVAILABLE: &str = "not_available";
259
260/// A record's `rule` (§2.4): the index of the alarm's rule in its owner's
261/// table, or `not_available` for an alarm by words.
262#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
263pub enum RuleIndex {
264    /// A table's rule, by its index from 0 to 254.
265    Table(u8),
266    /// No table names the alarm: its words are on `words/<slot>`, and its
267    /// record carries `key`.
268    NotAvailable,
269}
270
271impl RuleIndex {
272    /// The index `i`, from 0 to 254; `None` for 255, which is no index but
273    /// `not_available`'s code.
274    #[must_use]
275    pub const fn new(i: u8) -> Option<RuleIndex> {
276        if i <= MAX_INDEX {
277            Some(RuleIndex::Table(i))
278        } else {
279            None
280        }
281    }
282
283    /// A rule's place in its table as a record carries it
284    /// ([`words::Index`]): a place the record has no code for is by words.
285    #[must_use]
286    pub const fn of(index: words::Index) -> RuleIndex {
287        match index {
288            words::Index::At(i) => RuleIndex::Table(i),
289            words::Index::OutOfRange => RuleIndex::NotAvailable,
290        }
291    }
292
293    /// Core §7.6's JSON reading: the number, or the reserved code's name.
294    #[must_use]
295    pub fn to_json(self) -> Value {
296        match self {
297            RuleIndex::Table(i) => json!(i),
298            RuleIndex::NotAvailable => json!(NOT_AVAILABLE),
299        }
300    }
301
302    /// [`RuleIndex::to_json`] read back; `None` for anything else.
303    #[must_use]
304    pub fn of_json(v: &Value) -> Option<RuleIndex> {
305        match v {
306            Value::String(s) if s == NOT_AVAILABLE => Some(RuleIndex::NotAvailable),
307            v => RuleIndex::new(u8::try_from(v.as_u64()?).ok()?),
308        }
309    }
310}
311
312/// A record's `argument` (§2.4, §4): the rule's own number as a code, read
313/// through the rule's declaration ([`Rule::reading`]).
314#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
315pub enum Argument {
316    /// A code from 0 to 1,048,574.
317    Code(u32),
318    /// The rule declares none, the reading has no code, or there is none.
319    NotAvailable,
320}
321
322impl Argument {
323    /// The largest code that is a value, 1,048,574.
324    pub const MAX: u32 = 1_048_574;
325
326    /// The code `n`, from 0 to 1,048,574; `None` above.
327    #[must_use]
328    pub const fn new(n: u32) -> Option<Argument> {
329        if n <= Argument::MAX {
330            Some(Argument::Code(n))
331        } else {
332            None
333        }
334    }
335
336    /// Core §7.6's JSON reading: the number, or the reserved code's name.
337    #[must_use]
338    pub fn to_json(self) -> Value {
339        match self {
340            Argument::Code(n) => json!(n),
341            Argument::NotAvailable => json!(NOT_AVAILABLE),
342        }
343    }
344
345    /// [`Argument::to_json`] read back; `None` for anything else.
346    #[must_use]
347    pub fn of_json(v: &Value) -> Option<Argument> {
348        match v {
349            Value::String(s) if s == NOT_AVAILABLE => Some(Argument::NotAvailable),
350            v => Argument::new(u32::try_from(v.as_u64()?).ok()?),
351        }
352    }
353}
354
355/// The standard schema's one packed type, without its descriptions, which
356/// are no part of a layout (core §7.6):
357/// `spec/profiles/alarms/alarms.v2.json`'s fields, in order.
358fn schema() -> Value {
359    json!({"types": {"Alarm": {"fields": [
360        {"name": "state", "type": "enum", "values": ["firing", "resolved"]},
361        {"name": "severity", "type": "enum", "values": ["info", "warning", "critical"],
362         "escape": true},
363        {"name": "rule", "type": "int", "minimum": 0, "maximum": MAX_INDEX,
364         "reserved": [NOT_AVAILABLE]},
365        {"name": "at", "type": "time", "optional": true},
366        {"name": "labels", "type": "int", "minimum": 0, "maximum": (1u32 << LABELS_BITS) - 1,
367         "optional": true},
368        {"name": "argument", "type": "int", "minimum": 0, "maximum": Argument::MAX,
369         "reserved": [NOT_AVAILABLE]},
370        {"name": "key", "type": "counter", "width": 64, "optional": true},
371        packed::MARKER,
372    ]}}})
373}
374
375/// The packed type's name in the standard schema (§3).
376pub const TYPE: &str = "Alarm";
377
378/// The `Alarm`'s layout (§3): 35 bits with no optional field, 67 with its
379/// time, and its tag 11.
380#[must_use]
381pub fn layout() -> &'static Layout {
382    static LAYOUT: OnceLock<Layout> = OnceLock::new();
383    LAYOUT.get_or_init(|| {
384        packed::layout_in(&schema(), TYPE).expect("the standard schema's declaration reads")
385    })
386}
387
388/// The time an owner writes as a record's `at` (§2.4), in whole seconds
389/// since the Unix epoch, for its clock reading `unix_ms` under the
390/// deployment epoch `epoch` in seconds: `None` where that instant has no
391/// code, before the epoch or 2^32 seconds or more after it, and the owner
392/// writes none. A device with no real-time clock at boot reads 1970, which
393/// a catalog's later epoch does not code.
394#[must_use]
395pub fn time_at(unix_ms: i128, epoch: i64) -> Option<i64> {
396    packed::time_code(unix_ms, Some(epoch), false).ok()?;
397    i64::try_from(unix_ms.div_euclid(1000)).ok()
398}
399
400/// Why a writer refuses a record (§2.4): core §7.6's refusal of the value,
401/// then this text's, for a value the core writes.
402#[derive(Debug, Clone, Copy, PartialEq, Eq)]
403pub enum Refused {
404    /// Core §7.6's: `missing`, `unknown`, `value` or `range`.
405    Core(WriteRefusal),
406    /// `key` given under a table's rule: a reader reads it undecodable.
407    KeyWithRule,
408    /// No `key` under `not_available`: the same.
409    KeyMissing,
410    /// `labels` given, or an `argument` other than `not_available`, under
411    /// `not_available`: an alarm by words has both in its words.
412    ByWordsFields,
413}
414
415impl Refused {
416    /// The fixture's token.
417    #[must_use]
418    pub fn token(self) -> &'static str {
419        match self {
420            Self::Core(r) => r.token(),
421            Self::KeyWithRule => "key_with_rule",
422            Self::KeyMissing => "key_missing",
423            Self::ByWordsFields => "by_words_fields",
424        }
425    }
426}
427
428impl std::fmt::Display for Refused {
429    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
430        match self {
431            Self::Core(r) => r.fmt(f),
432            Self::KeyWithRule => f.write_str("key_with_rule: `key` beside a table's rule"),
433            Self::KeyMissing => f.write_str("key_missing: no `key` under a rule not_available"),
434            Self::ByWordsFields => {
435                f.write_str("by_words_fields: `labels` or an `argument` under a rule not_available")
436            }
437        }
438    }
439}
440
441impl std::error::Error for Refused {}
442
443impl From<WriteRefusal> for Refused {
444    fn from(r: WriteRefusal) -> Self {
445        Refused::Core(r)
446    }
447}
448
449/// Why a reader reads a record as undecodable (§2.4), the first that
450/// applies: it is then never read at a severity or in a state.
451#[derive(Debug, Clone, Copy, PartialEq, Eq)]
452pub enum Undecodable {
453    /// Core §7.6's reading refuses it: by its `tag`, its `length` or its
454    /// `pad`. No field has an unused code, and the layout ends at its
455    /// marker, so none is refused `code` or `extension`.
456    Core(ReadRefusal),
457    /// `key` is present and `rule` is a table's.
458    KeyWithRule,
459    /// `key` is absent and `rule` is `not_available`.
460    KeyMissing,
461}
462
463impl Undecodable {
464    /// The fixture's token.
465    #[must_use]
466    pub fn token(self) -> &'static str {
467        match self {
468            Self::Core(r) => r.token(),
469            Self::KeyWithRule => "key_with_rule",
470            Self::KeyMissing => "key_missing",
471        }
472    }
473}
474
475impl std::fmt::Display for Undecodable {
476    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
477        match self {
478            Self::Core(r) => r.fmt(f),
479            Self::KeyWithRule => f.write_str("key_with_rule: `key` beside a table's rule"),
480            Self::KeyMissing => f.write_str("key_missing: no `key` under a rule not_available"),
481        }
482    }
483}
484
485impl std::error::Error for Undecodable {}
486
487impl From<ReadRefusal> for Undecodable {
488    fn from(r: ReadRefusal) -> Self {
489        Undecodable::Core(r)
490    }
491}
492
493/// One alarm's record, the packed `Alarm` on `alarms/<slot>` (§2.4, §3).
494/// The slot is not in it: it is the key's last chunk.
495#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
496pub struct Record {
497    pub state: State,
498    /// `None`: the record's escape, a severity a later text names, read as
499    /// no severity known.
500    pub severity: Option<Severity>,
501    pub rule: RuleIndex,
502    /// When the alarm's latest transition happened, on the owner's clock,
503    /// in whole seconds since the Unix epoch; absent while that clock reads
504    /// no instant the epoch codes (§2.5). It is the acknowledgement
505    /// identity ([`acknowledged`]).
506    pub at: Option<i64>,
507    /// The codes of the rule's labels as one integer below 2^24 (§4):
508    /// present exactly where the rule declares a label.
509    pub labels: Option<u32>,
510    pub argument: Argument,
511    /// The alert key's 64 bits: present exactly for an alarm by words.
512    pub key: Option<u64>,
513}
514
515/// A record's time as core §7.6's reading spells it, milliseconds since
516/// the Unix epoch, from whole seconds since it.
517fn time_json(seconds: i64) -> Value {
518    json!(i128::from(seconds) * 1000)
519}
520
521fn time_of_json(v: &Value) -> Option<i64> {
522    let ms = match v {
523        Value::Number(n) => n
524            .as_i64()
525            .map(i128::from)
526            .or_else(|| n.as_u64().map(i128::from))?,
527        _ => return None,
528    };
529    i64::try_from(ms.div_euclid(1000)).ok()
530}
531
532impl Record {
533    /// The record of an alarm in `state` at `severity`, with the fields
534    /// that name it ([`write_alarm`]) and the `at` of its latest
535    /// transition ([`Dating`]).
536    #[must_use]
537    pub fn new(state: State, severity: Severity, fields: Fields, at: Option<i64>) -> Record {
538        Record {
539            state,
540            severity: Some(severity),
541            rule: fields.rule,
542            at,
543            labels: fields.labels,
544            argument: fields.argument,
545            key: fields.key,
546        }
547    }
548
549    /// Whether the record is an alarm's by words: its `rule` is
550    /// `not_available`.
551    #[must_use]
552    pub const fn is_by_words(&self) -> bool {
553        matches!(self.rule, RuleIndex::NotAvailable)
554    }
555
556    /// The record's value in core §7.6's JSON reading: a severity its
557    /// name, or null for the escape; `rule` and `argument` a number or
558    /// `not_available`; `at` in milliseconds since the Unix epoch; `key`
559    /// an integer; an absent optional field no member.
560    #[must_use]
561    pub fn to_json(&self) -> Value {
562        let mut m = Map::new();
563        m.insert("state".into(), json!(self.state.as_str()));
564        m.insert(
565            "severity".into(),
566            self.severity.map_or(Value::Null, |s| json!(s.as_str())),
567        );
568        m.insert("rule".into(), self.rule.to_json());
569        if let Some(t) = self.at {
570            m.insert("at".into(), time_json(t));
571        }
572        if let Some(l) = self.labels {
573            m.insert("labels".into(), json!(l));
574        }
575        m.insert("argument".into(), self.argument.to_json());
576        if let Some(k) = self.key {
577            m.insert("key".into(), json!(k));
578        }
579        Value::Object(m)
580    }
581
582    /// A value [`Layout::read`] gave for the type; `None` for any other.
583    #[must_use]
584    pub fn of_json(v: &Value) -> Option<Record> {
585        let state = match v.get("state")?.as_str()? {
586            "firing" => State::Firing,
587            "resolved" => State::Resolved,
588            _ => return None,
589        };
590        let severity = match v.get("severity")? {
591            Value::Null => None,
592            s => Some(Severity::parse(s.as_str()?)?),
593        };
594        let optional = |name: &str| v.get(name);
595        Some(Record {
596            state,
597            severity,
598            rule: RuleIndex::of_json(v.get("rule")?)?,
599            at: match optional("at") {
600                None => None,
601                Some(t) => Some(time_of_json(t)?),
602            },
603            labels: match optional("labels") {
604                None => None,
605                Some(l) => Some(u32::try_from(l.as_u64()?).ok()?),
606            },
607            argument: Argument::of_json(v.get("argument")?)?,
608            key: match optional("key") {
609                None => None,
610                Some(k) => Some(k.as_u64()?),
611            },
612        })
613    }
614
615    /// What a reader refuses of a record that core §7.6 reads (§2.4): a
616    /// `key` beside a table's rule, or none under `not_available`.
617    ///
618    /// # Errors
619    /// [`Undecodable::KeyWithRule`] or [`Undecodable::KeyMissing`].
620    pub fn check(&self) -> Result<(), Undecodable> {
621        match (self.rule, self.key) {
622            (RuleIndex::Table(_), Some(_)) => Err(Undecodable::KeyWithRule),
623            (RuleIndex::NotAvailable, None) => Err(Undecodable::KeyMissing),
624            _ => Ok(()),
625        }
626    }
627
628    /// The record's bytes, its `at` counted from the deployment epoch
629    /// `epoch` in seconds (0 where the owner is given no catalog).
630    ///
631    /// # Errors
632    /// [`Refused`]: core §7.6's `range` for an `at` the epoch does not
633    /// code (an owner writes none, [`time_at`]), for labels of 2^24 or
634    /// more; then what no owner writes, since a reader of this text reads
635    /// it undecodable or ignores it.
636    pub fn write(&self, epoch: i64) -> Result<packed::Record, Refused> {
637        write_value(&self.to_json(), epoch)
638    }
639
640    /// A put's payload under the owner's own `stamp`: CH (form 0, the
641    /// stamp's width bit, the type's tag), the run, the seq, the record.
642    ///
643    /// # Errors
644    /// As [`Record::write`].
645    pub fn put(&self, stamp: Stamp, epoch: i64) -> Result<Vec<u8>, Refused> {
646        let record = self.write(epoch)?;
647        let tag = Tag::new(TAG).expect("a tag of four bits");
648        Ok(Envelope::mutation(tag, stamp, &record.bytes).write())
649    }
650
651    /// Reads a record under the tag its envelope's CH carries, or its
652    /// snapshot page's (§2.4): core §7.6's reading, a later text's fields
653    /// behind the marker ignored, then the record's `key` against its
654    /// `rule`. `labels` and `argument` under `not_available` are kept as
655    /// read, and a reader ignores them.
656    ///
657    /// # Errors
658    /// [`Undecodable`], the first that applies.
659    pub fn read(tag: u8, bytes: &[u8], epoch: i64) -> Result<Record, Undecodable> {
660        let value = layout().read(tag, bytes, Some(epoch))?;
661        // Every value the layout reads is one the type declares.
662        let record = Record::of_json(&value).ok_or(ReadRefusal::Code)?;
663        record.check()?;
664        Ok(record)
665    }
666}
667
668/// Writes a record from its value in core §7.6's JSON reading
669/// ([`Record::to_json`]), under the deployment epoch `epoch` in seconds.
670///
671/// # Errors
672/// [`Refused`]: core §7.6's refusal of the value first, then
673/// `key_with_rule`, `key_missing` and `by_words_fields`.
674pub fn write_value(value: &Value, epoch: i64) -> Result<packed::Record, Refused> {
675    let record = layout().write(value, Some(epoch))?;
676    // The core wrote it, so it reads back as a record.
677    let r = Record::of_json(value).ok_or(WriteRefusal::Value)?;
678    match r.check() {
679        Err(Undecodable::KeyWithRule) => return Err(Refused::KeyWithRule),
680        Err(_) => return Err(Refused::KeyMissing),
681        Ok(()) => {}
682    }
683    if r.is_by_words() && (r.labels.is_some() || r.argument != Argument::NotAvailable) {
684        return Err(Refused::ByWordsFields);
685    }
686    Ok(record)
687}
688
689// --- §2.5: `at`, and the acknowledgement it carries ---------------------------
690
691/// An owner's act on one alarm (§2.5's table).
692#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
693pub enum Act {
694    Raise,
695    Escalate,
696    Refresh,
697    Resolve,
698}
699
700impl Act {
701    /// Whether the act is a transition, which takes a new `at`: a raise,
702    /// an escalation or a resolve. A refresh keeps the one its record
703    /// holds.
704    #[must_use]
705    pub const fn is_transition(self) -> bool {
706        !matches!(self, Act::Refresh)
707    }
708}
709
710/// The `at` of one identity's transitions (§2.5): the greatest `at` its
711/// owner knows it wrote for the identity, so that each transition's is
712/// later than the one before it, whatever the clock does.
713#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
714pub struct Dating {
715    greatest: Option<i64>,
716}
717
718impl Dating {
719    /// An identity whose `at` the owner knows of from before: an adopted
720    /// alarm's (§2.9), `None` where it carried none.
721    #[must_use]
722    pub const fn known(at: Option<i64>) -> Dating {
723        Dating { greatest: at }
724    }
725
726    /// The greatest `at` written for the identity, in whole seconds since
727    /// the Unix epoch.
728    #[must_use]
729    pub const fn greatest(&self) -> Option<i64> {
730        self.greatest
731    }
732
733    /// A transition's new `at` (§2.5), the owner's clock reading
734    /// `clock_ms` in milliseconds since the Unix epoch under the
735    /// deployment epoch `epoch` in seconds: the clock in whole seconds,
736    /// or one second after the greatest `at` written where the clock is
737    /// not later than it. `None`, and no `at` is written, while the clock
738    /// reads no instant the epoch codes, and where the new `at` would have
739    /// no code.
740    pub fn transition(&mut self, clock_ms: i128, epoch: i64) -> Option<i64> {
741        let clock = time_at(clock_ms, epoch)?;
742        let new = match self.greatest {
743            Some(g) if clock <= g => g.checked_add(1)?,
744            _ => clock,
745        };
746        time_at(i128::from(new) * 1000, epoch)?;
747        self.greatest = Some(new);
748        Some(new)
749    }
750
751    /// The `at` the record of `act` carries: a new one at a transition
752    /// ([`Dating::transition`]), and `held`, the one its record holds, at
753    /// a refresh.
754    pub fn at(&mut self, act: Act, held: Option<i64>, clock_ms: i128, epoch: i64) -> Option<i64> {
755        if act.is_transition() {
756            self.transition(clock_ms, epoch)
757        } else {
758            held
759        }
760    }
761}
762
763/// Whether an acknowledgement applies to an alarm (§2.5): while the
764/// alarm's `at`, in whole seconds since the Unix epoch, is at most the
765/// acknowledged instant, in milliseconds since it. Never with no `at` on
766/// either side: the alarm is then told again. An acknowledgement made
767/// against `alarms.v1`'s `timestamp` is compared as it is, so it still
768/// applies to the alarm adopted ([`adopted_at`]).
769#[must_use]
770pub fn acknowledged(acked_at_ms: Option<i128>, at: Option<i64>) -> bool {
771    match (acked_at_ms, at) {
772        (Some(acked), Some(at)) => i128::from(at) * 1000 <= acked,
773        _ => false,
774    }
775}
776
777/// The `at` of an alarm adopted from `alarms.v1` (§2.9): its document's
778/// `timestamp` in whole seconds, `None` where that instant has no code
779/// under the deployment epoch.
780#[must_use]
781pub fn adopted_at(timestamp_ms: u64, epoch: i64) -> Option<i64> {
782    time_at(i128::from(timestamp_ms), epoch)
783}
784
785// --- §4: the table --------------------------------------------------------------
786
787/// How a rule's `argument` reads (§4): `minimum` + code × `resolution`,
788/// two decimal strings as core §7.6 writes them, the resolution above 0.
789#[derive(Debug, Clone, PartialEq, Eq, Hash)]
790pub struct ArgumentDecl {
791    minimum: String,
792    resolution: String,
793}
794
795impl ArgumentDecl {
796    /// A declaration of two decimal strings, `None` where either is none
797    /// or the resolution is not above 0.
798    #[must_use]
799    pub fn new(minimum: &str, resolution: &str) -> Option<ArgumentDecl> {
800        Decimal::parse(minimum)?;
801        if Decimal::parse(resolution)? <= Decimal::from(0) {
802            return None;
803        }
804        Some(ArgumentDecl {
805            minimum: minimum.to_owned(),
806            resolution: resolution.to_owned(),
807        })
808    }
809
810    /// The declaration's `minimum`, as written.
811    #[must_use]
812    pub fn minimum(&self) -> &str {
813        &self.minimum
814    }
815
816    /// The declaration's `resolution`, as written.
817    #[must_use]
818    pub fn resolution(&self) -> &str {
819        &self.resolution
820    }
821
822    fn fixed(&self) -> Fixed {
823        Fixed::new(
824            &self.minimum,
825            &self.resolution,
826            u128::from(Argument::MAX) + 1,
827        )
828    }
829
830    fn of_json(v: &Value) -> Option<ArgumentDecl> {
831        let o = v.as_object()?;
832        if o.len() != 2 {
833            return None;
834        }
835        ArgumentDecl::new(o.get("minimum")?.as_str()?, o.get("resolution")?.as_str()?)
836    }
837}
838
839/// A label's values (§4).
840#[derive(Debug, Clone, PartialEq, Eq, Hash)]
841pub enum LabelValues {
842    /// `values`: one or more strings, a value's code its index.
843    List(Vec<String>),
844    /// `minimum` and `maximum`: the integers from one to the other, a
845    /// value's code the integer less `minimum`.
846    Range { minimum: i128, maximum: i128 },
847}
848
849/// One discriminating label of a rule (§4).
850#[derive(Debug, Clone, PartialEq, Eq, Hash)]
851pub struct Label {
852    pub name: String,
853    pub values: LabelValues,
854}
855
856impl Label {
857    /// How many values the label has.
858    #[must_use]
859    pub fn count(&self) -> u128 {
860        match &self.values {
861            LabelValues::List(l) => l.len() as u128,
862            LabelValues::Range { minimum, maximum } => {
863                u128::try_from(maximum - minimum).map_or(0, |d| d + 1)
864            }
865        }
866    }
867
868    /// The bits the label's code takes (§4): ⌈log₂ n⌉ for n values, so
869    /// none for a label of one value.
870    #[must_use]
871    pub fn width(&self) -> u32 {
872        match self.count() {
873            0 | 1 => 0,
874            n => u128::BITS - (n - 1).leading_zeros(),
875        }
876    }
877
878    /// The code of the value `text` (§4): its index in `values`, or its
879    /// integer less `minimum`, the integer written in decimal with `-` for
880    /// a negative one and no leading zero. `None` for a text that is no
881    /// value of the label.
882    #[must_use]
883    pub fn code(&self, text: &str) -> Option<u64> {
884        match &self.values {
885            LabelValues::List(l) => l.iter().position(|v| v == text).map(|i| i as u64),
886            LabelValues::Range { minimum, maximum } => {
887                let n: i128 = text.parse().ok()?;
888                if n.to_string() != text || n < *minimum || n > *maximum {
889                    return None;
890                }
891                u64::try_from(n - minimum).ok()
892            }
893        }
894    }
895
896    /// The text of the value at `code` (§4), `None` for a code the label
897    /// does not have.
898    #[must_use]
899    pub fn text(&self, code: u64) -> Option<String> {
900        if u128::from(code) >= self.count() {
901            return None;
902        }
903        match &self.values {
904            LabelValues::List(l) => l.get(usize::try_from(code).ok()?).cloned(),
905            LabelValues::Range { minimum, .. } => Some((minimum + i128::from(code)).to_string()),
906        }
907    }
908
909    fn of_json(v: &Value) -> Option<Label> {
910        let o = v.as_object()?;
911        let name = o.get("name")?.as_str()?.to_owned();
912        let values = match (o.get("values"), o.get("minimum"), o.get("maximum")) {
913            (Some(list), None, None) if o.len() == 2 => {
914                let list = words::list(list, usize::MAX, |_| true, false)?;
915                if list.is_empty() {
916                    return None;
917                }
918                LabelValues::List(list)
919            }
920            (None, Some(minimum), Some(maximum)) if o.len() == 3 => {
921                let minimum = packed::json_integer(minimum).ok()?;
922                let maximum = packed::json_integer(maximum).ok()?;
923                if minimum > maximum {
924                    return None;
925                }
926                LabelValues::Range { minimum, maximum }
927            }
928            _ => return None,
929        };
930        Some(Label { name, values })
931    }
932
933    fn to_json(&self) -> Value {
934        match &self.values {
935            LabelValues::List(l) => json!({"name": self.name, "values": l}),
936            LabelValues::Range { minimum, maximum } => {
937                // An integer a contract holds is within −2^63 to 2^64 − 1.
938                let n = |x: i128| {
939                    i64::try_from(x)
940                        .map(Value::from)
941                        .or_else(|_| u64::try_from(x).map(Value::from))
942                        .unwrap_or(Value::Null)
943                };
944                json!({"name": self.name, "minimum": n(*minimum), "maximum": n(*maximum)})
945            }
946        }
947    }
948}
949
950/// One rule of a service's table (§4): the rule at index i is the one a
951/// record's `rule` i names.
952#[derive(Debug, Clone, PartialEq, Eq, Hash)]
953pub struct Rule {
954    /// The rule's name: v1 §2.4's `rule`, and the recipe's first input.
955    pub name: String,
956    /// A template: the alarm's one line for a person ([`Rule::summary`]).
957    pub summary: String,
958    /// v1 §2.4's `category`, the same for every alarm of the rule.
959    pub category: Option<String>,
960    pub argument: Option<ArgumentDecl>,
961    /// The rule's discriminating labels, in the order their codes are
962    /// written. Empty for a rule that declares none.
963    pub labels: Vec<Label>,
964}
965
966impl AsRef<str> for Rule {
967    /// The rule's name: what [`words::write`] finds a rule by.
968    fn as_ref(&self) -> &str {
969        &self.name
970    }
971}
972
973/// One piece of a summary's template (§4).
974enum Piece<'a> {
975    Text(&'a str),
976    /// A placeholder, by its name.
977    Placeholder(&'a str),
978    /// A `{` with no `}` after it, or a `}` outside a placeholder.
979    Stray,
980}
981
982/// A summary's template in pieces: a `{` opens a placeholder, which ends
983/// at the next `}`.
984fn pieces(summary: &str) -> Vec<Piece<'_>> {
985    let mut out = Vec::new();
986    let mut rest = summary;
987    while !rest.is_empty() {
988        match rest.find(['{', '}']) {
989            None => {
990                out.push(Piece::Text(rest));
991                break;
992            }
993            Some(i) => {
994                if i > 0 {
995                    out.push(Piece::Text(&rest[..i]));
996                }
997                if rest[i..].starts_with('}') {
998                    out.push(Piece::Stray);
999                    rest = &rest[i + 1..];
1000                } else if let Some(end) = rest[i + 1..].find('}') {
1001                    out.push(Piece::Placeholder(&rest[i + 1..i + 1 + end]));
1002                    rest = &rest[i + end + 2..];
1003                } else {
1004                    out.push(Piece::Stray);
1005                    break;
1006                }
1007            }
1008        }
1009    }
1010    out
1011}
1012
1013impl Rule {
1014    /// The bits the rule's labels take: their widths' sum.
1015    #[must_use]
1016    pub fn labels_width(&self) -> u32 {
1017        self.labels.iter().map(Label::width).sum()
1018    }
1019
1020    /// The record's `labels` for an alarm whose labels are `labels`, each
1021    /// a name and its text (§2.4, §4): `Some(None)` for a rule that
1022    /// declares none, `Some(Some(codes))` for one that does, the first
1023    /// label in the most significant bits. `None` where the alarm is not
1024    /// the table's: its discriminating labels, host-scoped ones left out,
1025    /// are not exactly the rule's, or a text has no code.
1026    #[must_use]
1027    pub fn encode<'a>(
1028        &self,
1029        labels: impl IntoIterator<Item = (&'a str, &'a str)>,
1030    ) -> Option<Option<u32>> {
1031        let given: Vec<(&str, &str)> = labels
1032            .into_iter()
1033            .filter(|(n, _)| !super::is_host_scoped(n))
1034            .collect();
1035        if given.len() != self.labels.len() || self.labels_width() > LABELS_BITS {
1036            return None;
1037        }
1038        let mut codes: u64 = 0;
1039        for label in &self.labels {
1040            let mut of_name = given.iter().filter(|(n, _)| *n == label.name);
1041            let (_, text) = of_name.next()?;
1042            if of_name.next().is_some() {
1043                return None;
1044            }
1045            codes = (codes << label.width()) | label.code(text)?;
1046        }
1047        if self.labels.is_empty() {
1048            return Some(None);
1049        }
1050        Some(Some(u32::try_from(codes).ok()?))
1051    }
1052
1053    /// The labels a record's `labels` names, each its name and its text,
1054    /// in the rule's order (§2.4). `None` where they name none: `labels`
1055    /// present where the rule declares no label, absent where it declares
1056    /// one, or holding a code a label does not have, a value at or above
1057    /// 2^w among them.
1058    #[must_use]
1059    pub fn decode(&self, labels: Option<u32>) -> Option<Vec<(String, String)>> {
1060        let Some(codes) = labels else {
1061            return self.labels.is_empty().then(Vec::new);
1062        };
1063        let width = self.labels_width();
1064        if self.labels.is_empty() || width > LABELS_BITS || u64::from(codes) >> width != 0 {
1065            return None;
1066        }
1067        let mut left = width;
1068        let mut out = Vec::with_capacity(self.labels.len());
1069        for label in &self.labels {
1070            let w = label.width();
1071            left -= w;
1072            let code = (u64::from(codes) >> left) & ((1u64 << w) - 1);
1073            out.push((label.name.clone(), label.text(code)?));
1074        }
1075        Some(out)
1076    }
1077
1078    /// The code an owner writes for a reading (§4): round((reading −
1079    /// `minimum`) / `resolution`), a tie to the even code, as core §7.6
1080    /// writes a `fixed`. `not_available` for a reading whose code is
1081    /// outside 0 to 1,048,574, for none, and under a rule that declares no
1082    /// argument. The alarm still fires.
1083    #[must_use]
1084    pub fn argument(&self, reading: Option<&Decimal>) -> Argument {
1085        let (Some(decl), Some(reading)) = (&self.argument, reading) else {
1086            return Argument::NotAvailable;
1087        };
1088        decl.fixed()
1089            .code(reading)
1090            .ok()
1091            .and_then(|c| Argument::new(u32::try_from(c).ok()?))
1092            .unwrap_or(Argument::NotAvailable)
1093    }
1094
1095    /// What a record's `argument` reads as (§4): `minimum` + code ×
1096    /// `resolution`, exactly, shown in its shortest form by its `Display`.
1097    /// `None` for `not_available`, and under a rule that declares no
1098    /// argument, where a reader ignores any code.
1099    #[must_use]
1100    pub fn reading(&self, argument: Argument) -> Option<Decimal> {
1101        let (Some(decl), Argument::Code(code)) = (&self.argument, argument) else {
1102            return None;
1103        };
1104        decl.fixed().value(u64::from(code)).ok()
1105    }
1106
1107    /// The alarm's summary (§4): the rule's template with `{argument}`
1108    /// replaced by the argument's reading, or by `?` where there is none,
1109    /// and `{<label>}` by that label's text.
1110    #[must_use]
1111    pub fn summary(&self, labels: &[(String, String)], argument: Argument) -> String {
1112        let mut out = String::new();
1113        for piece in pieces(&self.summary) {
1114            match piece {
1115                Piece::Text(t) => out.push_str(t),
1116                Piece::Stray => {}
1117                Piece::Placeholder("argument") if self.argument.is_some() => {
1118                    match self.reading(argument) {
1119                        Some(r) => out.push_str(&r.to_string()),
1120                        None => out.push('?'),
1121                    }
1122                }
1123                Piece::Placeholder(name) => {
1124                    if let Some((_, text)) = labels.iter().find(|(n, _)| n == name) {
1125                        out.push_str(text);
1126                    }
1127                }
1128            }
1129        }
1130        out
1131    }
1132
1133    fn of_json(v: &Value) -> Option<Rule> {
1134        const MEMBERS: [&str; 5] = ["name", "summary", "category", "argument", "labels"];
1135        let o = v.as_object()?;
1136        if o.keys().any(|k| !MEMBERS.contains(&k.as_str())) {
1137            return None;
1138        }
1139        Some(Rule {
1140            name: o.get("name")?.as_str()?.to_owned(),
1141            summary: o.get("summary")?.as_str()?.to_owned(),
1142            category: match o.get("category") {
1143                None => None,
1144                Some(c) => Some(c.as_str()?.to_owned()),
1145            },
1146            argument: match o.get("argument") {
1147                None => None,
1148                Some(a) => Some(ArgumentDecl::of_json(a)?),
1149            },
1150            labels: match o.get("labels") {
1151                None => Vec::new(),
1152                Some(l) => {
1153                    let l = l.as_array().filter(|l| !l.is_empty())?;
1154                    l.iter().map(Label::of_json).collect::<Option<_>>()?
1155                }
1156            },
1157        })
1158    }
1159
1160    /// The rule as its contract writes it (§4).
1161    #[must_use]
1162    pub fn to_json(&self) -> Value {
1163        let mut m = Map::new();
1164        m.insert("name".into(), json!(self.name));
1165        m.insert("summary".into(), json!(self.summary));
1166        if let Some(c) = &self.category {
1167            m.insert("category".into(), json!(c));
1168        }
1169        if let Some(a) = &self.argument {
1170            m.insert(
1171                "argument".into(),
1172                json!({"minimum": a.minimum, "resolution": a.resolution}),
1173            );
1174        }
1175        if !self.labels.is_empty() {
1176            m.insert(
1177                "labels".into(),
1178                Value::Array(self.labels.iter().map(Label::to_json).collect()),
1179            );
1180        }
1181        Value::Object(m)
1182    }
1183}
1184
1185/// A table as its contract writes it: [`Rule::to_json`], in order.
1186#[must_use]
1187pub fn table_json(table: &[Rule]) -> Value {
1188    Value::Array(table.iter().map(Rule::to_json).collect())
1189}
1190
1191/// A value of §4's shape: a list of at most 255 rules, each with the
1192/// members the text names and no other. `None` for any other value. A
1193/// list of the shape may still draw a finding ([`declaration`]).
1194#[must_use]
1195pub fn rules(v: &Value) -> Option<Vec<Rule>> {
1196    let list = v.as_array()?;
1197    if list.len() > MAX_RULES {
1198        return None;
1199    }
1200    list.iter().map(Rule::of_json).collect()
1201}
1202
1203/// Why a contract's declaration of its table is invalid (§4), the first
1204/// that applies. An invalid declaration holds no table.
1205#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1206pub enum Invalid {
1207    /// A resource carries the key, and the contract's `uses` does not list
1208    /// `alarms.v2`.
1209    NotUsed,
1210    /// A resource's value is not a list of at most 255 rules of §4's
1211    /// shape.
1212    Value,
1213    /// A rule's name is empty, holds a newline, or is another rule's.
1214    RuleName,
1215    /// A label's name is empty, is `argument`, holds a newline, `=`, `{`
1216    /// or `}`, or is another label's of its rule; or one of its values
1217    /// holds a newline, or comes twice.
1218    Label,
1219    /// A rule's labels take more than 24 bits.
1220    LabelsWidth,
1221    /// A label's name is host-scoped (v1 §2.2).
1222    HostLabel,
1223    /// A summary holds a `{` with no `}` after it, a `}` outside a
1224    /// placeholder, or a placeholder whose name is neither a label of its
1225    /// rule nor `argument` under a rule that declares one.
1226    Placeholder,
1227    /// Two resources carry two different lists.
1228    Disagrees,
1229}
1230
1231impl Invalid {
1232    /// The fixture's token.
1233    #[must_use]
1234    pub fn as_str(self) -> &'static str {
1235        match self {
1236            Self::NotUsed => "not_used",
1237            Self::Value => "value",
1238            Self::RuleName => "rule_name",
1239            Self::Label => "label",
1240            Self::LabelsWidth => "labels_width",
1241            Self::HostLabel => "host_label",
1242            Self::Placeholder => "placeholder",
1243            Self::Disagrees => "disagrees",
1244        }
1245    }
1246
1247    /// The reason in words, for a linter's message.
1248    #[must_use]
1249    pub fn says(self) -> &'static str {
1250        match self {
1251            Self::NotUsed => "the contract's `uses` does not list alarms.v2",
1252            Self::Value => {
1253                "its value is not a list of at most 255 rules: name, summary, and optionally \
1254                 category, argument { minimum, resolution } and labels"
1255            }
1256            Self::RuleName => "a rule's name is empty, holds a newline, or is another rule's",
1257            Self::Label => {
1258                "a label's name is empty, `argument`, holds a newline, `=`, `{` or `}`, or comes \
1259                 twice in its rule; or a value holds a newline or comes twice"
1260            }
1261            Self::LabelsWidth => "a rule's labels take more than 24 bits",
1262            Self::HostLabel => "a label's name is host-scoped: the key's system names the host",
1263            Self::Placeholder => {
1264                "a summary holds an unclosed `{`, a stray `}`, or a placeholder that is neither \
1265                 a label of its rule nor its `argument`"
1266            }
1267            Self::Disagrees => {
1268                "two resources carry two different lists: write the key once, on [defaults]"
1269            }
1270        }
1271    }
1272
1273    /// Whether a list of §4's shape draws this finding. `not_used`,
1274    /// `value` and `disagrees` are no list's alone.
1275    fn found_in(self, table: &[Rule]) -> bool {
1276        let labels = || table.iter().flat_map(|r| r.labels.iter());
1277        match self {
1278            Self::NotUsed | Self::Value | Self::Disagrees => false,
1279            Self::RuleName => table.iter().enumerate().any(|(i, r)| {
1280                r.name.is_empty()
1281                    || r.name.contains('\n')
1282                    || table[..i].iter().any(|before| before.name == r.name)
1283            }),
1284            Self::Label => table.iter().any(|r| {
1285                r.labels.iter().enumerate().any(|(i, l)| {
1286                    l.name.is_empty()
1287                        || l.name == "argument"
1288                        || l.name.contains(['\n', '=', '{', '}'])
1289                        || r.labels[..i].iter().any(|before| before.name == l.name)
1290                        || match &l.values {
1291                            LabelValues::List(values) => values
1292                                .iter()
1293                                .enumerate()
1294                                .any(|(j, v)| v.contains('\n') || values[..j].contains(v)),
1295                            LabelValues::Range { .. } => false,
1296                        }
1297                })
1298            }),
1299            Self::LabelsWidth => table.iter().any(|r| r.labels_width() > LABELS_BITS),
1300            Self::HostLabel => labels().any(|l| super::is_host_scoped(&l.name)),
1301            Self::Placeholder => table.iter().any(|r| {
1302                pieces(&r.summary).iter().any(|p| match p {
1303                    Piece::Text(_) => false,
1304                    Piece::Stray => true,
1305                    Piece::Placeholder(name) => {
1306                        !(r.labels.iter().any(|l| l.name == *name)
1307                            || (*name == "argument" && r.argument.is_some()))
1308                    }
1309                })
1310            }),
1311        }
1312    }
1313}
1314
1315impl std::fmt::Display for Invalid {
1316    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1317        f.write_str(self.as_str())
1318    }
1319}
1320
1321/// The findings a list of §4's shape can draw, in §4's order.
1322const OF_A_LIST: [Invalid; 5] = [
1323    Invalid::RuleName,
1324    Invalid::Label,
1325    Invalid::LabelsWidth,
1326    Invalid::HostLabel,
1327    Invalid::Placeholder,
1328];
1329
1330/// The table a contract holds (§4).
1331#[derive(Debug, Clone, PartialEq, Eq)]
1332pub enum Declared {
1333    /// No resource carries the key.
1334    None,
1335    /// The one list its resources carry.
1336    Table(Vec<Rule>),
1337    /// An invalid declaration, which holds none.
1338    Invalid(Invalid),
1339}
1340
1341impl Declared {
1342    /// The table it holds, none where none is declared or the declaration
1343    /// is invalid.
1344    #[must_use]
1345    pub fn table(&self) -> Option<&[Rule]> {
1346        match self {
1347            Declared::Table(t) => Some(t),
1348            Declared::None | Declared::Invalid(_) => None,
1349        }
1350    }
1351}
1352
1353/// [`declaration`], with the place of the value that made it invalid: its
1354/// index among the values given. Each finding is looked for over the whole
1355/// of every list carried before the next.
1356fn declared<'v>(
1357    uses_v2: bool,
1358    carried: impl IntoIterator<Item = &'v Value>,
1359) -> (Declared, Option<usize>) {
1360    let carried: Vec<&Value> = carried.into_iter().collect();
1361    if carried.is_empty() {
1362        return (Declared::None, None);
1363    }
1364    if !uses_v2 {
1365        return (Declared::Invalid(Invalid::NotUsed), Some(0));
1366    }
1367    let mut lists = Vec::with_capacity(carried.len());
1368    for (i, v) in carried.iter().enumerate() {
1369        match rules(v) {
1370            Some(list) => lists.push(list),
1371            None => return (Declared::Invalid(Invalid::Value), Some(i)),
1372        }
1373    }
1374    for finding in OF_A_LIST {
1375        if let Some(i) = lists.iter().position(|l| finding.found_in(l)) {
1376            return (Declared::Invalid(finding), Some(i));
1377        }
1378    }
1379    if let Some(i) = lists.iter().position(|l| *l != lists[0]) {
1380        return (Declared::Invalid(Invalid::Disagrees), Some(i));
1381    }
1382    (Declared::Table(lists.swap_remove(0)), None)
1383}
1384
1385/// A contract's table (§4), from whether its `uses` lists `alarms.v2` and
1386/// the value of `alarms.rules` on each resource that carries it. A
1387/// resource that does not carry the key takes no part.
1388#[must_use]
1389pub fn declaration<'v>(uses_v2: bool, carried: impl IntoIterator<Item = &'v Value>) -> Declared {
1390    declared(uses_v2, carried).0
1391}
1392
1393/// [`declaration`] over a loaded contract's resolved annotations, where
1394/// the canonical form carries a key written on `[defaults]` (core §9.5).
1395#[must_use]
1396pub fn declaration_of(c: &Contract) -> Declared {
1397    declaration(
1398        uses_v2(c),
1399        c.resources.iter().filter_map(|r| r.annotations.get(RULES)),
1400    )
1401}
1402
1403/// The table a contract holds, an invalid declaration holding none.
1404#[must_use]
1405pub fn table_of(c: &Contract) -> Option<Vec<Rule>> {
1406    declaration_of(c).table().map(<[Rule]>::to_vec)
1407}
1408
1409/// An instance's table (§4): the one table among the contracts it
1410/// implements ([`words::Instance`]). With none, or where two hold two
1411/// different lists (`differ`), its owner writes every alarm by words.
1412pub type Instance = words::Instance<Rule>;
1413
1414/// An instance's table, from the table of each revision its descriptor
1415/// names that the reader holds (`None`: that revision holds none, or its
1416/// declaration is invalid). Never a revision the descriptor does not
1417/// name: a table read under the wrong revision gives a wrong name over a
1418/// right state and severity.
1419#[must_use]
1420pub fn instance_table<'a>(named: impl IntoIterator<Item = Option<&'a [Rule]>>) -> Instance {
1421    words::instance_table(named)
1422}
1423
1424/// How a table moved from one revision to the next (§4): a table grows by
1425/// appending.
1426#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1427pub enum Growth {
1428    /// The same list.
1429    Same,
1430    /// Every rule of the old list is at its index in the new, with its
1431    /// name and its labels: every index and every code keeps its words.
1432    /// Rules may follow, and a summary, a category or an argument may
1433    /// differ.
1434    Kept,
1435    /// Some index names another rule, other labels, or none.
1436    Moved,
1437}
1438
1439impl Growth {
1440    /// The fixture's token.
1441    #[must_use]
1442    pub fn as_str(self) -> &'static str {
1443        match self {
1444            Self::Same => "same",
1445            Self::Kept => "kept",
1446            Self::Moved => "moved",
1447        }
1448    }
1449}
1450
1451/// [`Growth`] of a table from `old` to `new`.
1452#[must_use]
1453pub fn growth(old: &[Rule], new: &[Rule]) -> Growth {
1454    if old == new {
1455        Growth::Same
1456    } else if old.len() <= new.len()
1457        && old
1458            .iter()
1459            .zip(new)
1460            .all(|(o, n)| o.name == n.name && o.labels == n.labels)
1461    {
1462        Growth::Kept
1463    } else {
1464        Growth::Moved
1465    }
1466}
1467
1468/// One finding of [`lint_contract`]: [`crate::words`]'s shape, which
1469/// `desired.v2` and `health.v2` share.
1470pub use crate::words::Lint;
1471
1472/// What a linter reports of a contract that lists `alarms.v2` (§4): its
1473/// table's finding, at the first resource whose list draws it, or the
1474/// first whose list differs from the one before it. None for any other
1475/// contract: `alarms.v1` defines no key, and a key of a profile `uses`
1476/// does not list is core E020's.
1477#[must_use]
1478pub fn lint_contract(c: &Contract) -> Vec<Lint> {
1479    if !uses_v2(c) {
1480        return Vec::new();
1481    }
1482    let carrying: Vec<_> = c
1483        .resources
1484        .iter()
1485        .filter(|r| r.annotations.contains_key(RULES))
1486        .collect();
1487    let values = carrying.iter().map(|r| &r.annotations[RULES]);
1488    match declared(true, values) {
1489        (Declared::Invalid(reason), Some(i)) => vec![Lint {
1490            profile: PROFILE,
1491            at: Lint::place(carrying[i]),
1492            key: Some(RULES),
1493            token: reason.as_str(),
1494            says: reason.says(),
1495        }],
1496        _ => Vec::new(),
1497    }
1498}
1499
1500// --- §2.4, §4: an alarm's words, and a record's fields ---------------------------
1501
1502/// The fields of a record that name its alarm (§2.4).
1503#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1504pub struct Fields {
1505    pub rule: RuleIndex,
1506    pub labels: Option<u32>,
1507    pub argument: Argument,
1508    pub key: Option<u64>,
1509}
1510
1511impl Fields {
1512    /// Core §7.6's JSON reading of these fields, as [`Record::to_json`]
1513    /// has them.
1514    #[must_use]
1515    pub fn to_json(&self) -> Value {
1516        let mut m = Map::new();
1517        m.insert("rule".into(), self.rule.to_json());
1518        if let Some(l) = self.labels {
1519            m.insert("labels".into(), json!(l));
1520        }
1521        m.insert("argument".into(), self.argument.to_json());
1522        if let Some(k) = self.key {
1523            m.insert("key".into(), json!(k));
1524        }
1525        Value::Object(m)
1526    }
1527}
1528
1529/// The fields an owner writes for an alarm (§2.4, §4), from its rule's
1530/// name, its labels as text (host-scoped ones included), its reading and
1531/// its instance's `table`, none where it has none or two revisions differ
1532/// ([`Instance::table`]).
1533///
1534/// **By the table** where the table names the alarm: it holds the rule's
1535/// name at an index a record codes, the alarm's discriminating labels are
1536/// exactly the labels that rule declares, and each one's text has a code.
1537/// Host-scoped labels are not written. **By words** for any other alarm:
1538/// `rule` and `argument` `not_available`, no `labels`, and `key` the alert
1539/// key, v1's recipe through its sanitizing step.
1540#[must_use]
1541pub fn write_alarm<'a>(
1542    table: Option<&[Rule]>,
1543    rule: &str,
1544    labels: impl IntoIterator<Item = (&'a str, &'a str)>,
1545    reading: Option<&Decimal>,
1546) -> Fields {
1547    let labels: Vec<(&str, &str)> = labels.into_iter().collect();
1548    let by_table = table.and_then(|t| {
1549        let RuleIndex::Table(i) = RuleIndex::of(words::write(t, rule, MAX_INDEX)) else {
1550            return None;
1551        };
1552        let r = &t[usize::from(i)];
1553        Some(Fields {
1554            rule: RuleIndex::Table(i),
1555            labels: r.encode(labels.iter().copied())?,
1556            argument: r.argument(reading),
1557            key: None,
1558        })
1559    });
1560    by_table.unwrap_or_else(|| Fields {
1561        rule: RuleIndex::NotAvailable,
1562        labels: None,
1563        argument: Argument::NotAvailable,
1564        key: Some(super::derive(rule, labels).integer()),
1565    })
1566}
1567
1568/// Why a reader cannot turn a record's numbers into words (§2.4), the
1569/// first that applies. The alarm's state, its severity and its time are
1570/// read all the same. Its identity is not: the reader has no alert key
1571/// for it, and shows its numbers.
1572#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1573pub enum Unnamed {
1574    /// The reader holds no table of the alarm's owner (§4).
1575    NoTable,
1576    /// The table holds no rule at the record's index.
1577    Rule,
1578    /// `labels` is present where the rule declares no label, absent where
1579    /// it declares one, or holds a code a label does not have.
1580    Labels,
1581}
1582
1583impl Unnamed {
1584    /// The fixture's token.
1585    #[must_use]
1586    pub fn as_str(self) -> &'static str {
1587        match self {
1588            Self::NoTable => "no_table",
1589            Self::Rule => "rule",
1590            Self::Labels => "labels",
1591        }
1592    }
1593}
1594
1595/// A table's alarm, named (§2.4, §4).
1596#[derive(Debug, Clone, PartialEq, Eq)]
1597pub struct Named<'t> {
1598    /// The rule's index, and the rule.
1599    pub index: u8,
1600    pub rule: &'t Rule,
1601    /// Each label's name and its text, in the rule's order.
1602    pub labels: Vec<(String, String)>,
1603    /// The alert key v1's recipe derives from the rule's name and those
1604    /// labels.
1605    pub alert_key: u64,
1606    /// The rule's template with each placeholder replaced.
1607    pub summary: String,
1608    /// The argument's reading, where the rule declares one and the record
1609    /// carries a code.
1610    pub argument: Option<Decimal>,
1611}
1612
1613/// What a reader reads of a record's numbers, with the table it holds of
1614/// the record's owner (§2.4).
1615#[derive(Debug, Clone, PartialEq, Eq)]
1616pub enum Naming<'t> {
1617    /// A table's rule, in words.
1618    Named(Named<'t>),
1619    /// A table's rule the reader cannot name. Unnamed is not undecodable.
1620    Unnamed(Unnamed),
1621    /// An alarm by words: the record carries its alert key, whatever
1622    /// table is held, and its words are on `words/<slot>`.
1623    ByWords { alert_key: u64 },
1624}
1625
1626impl Naming<'_> {
1627    /// The alert key the reader has for the alarm: a named alarm's, `None`
1628    /// for an unnamed one.
1629    #[must_use]
1630    pub fn alert_key(&self) -> Option<u64> {
1631        match self {
1632            Naming::Named(n) => Some(n.alert_key),
1633            Naming::ByWords { alert_key } => Some(*alert_key),
1634            Naming::Unnamed(_) => None,
1635        }
1636    }
1637}
1638
1639impl Record {
1640    /// Reads the record's numbers into words (§2.4) with the instance's
1641    /// `table` as the reader holds it, none where it holds none or two
1642    /// revisions differ ([`Instance::table`]): never a table of a revision
1643    /// the owner's descriptor does not name.
1644    ///
1645    /// The record is one [`Record::read`] gave, so under `not_available`
1646    /// it carries its key.
1647    #[must_use]
1648    pub fn name<'t>(&self, table: Option<&'t [Rule]>) -> Naming<'t> {
1649        let index = match (self.rule, self.key) {
1650            (RuleIndex::NotAvailable, Some(alert_key)) => return Naming::ByWords { alert_key },
1651            // No index, and no key: a record no reader reads.
1652            (RuleIndex::NotAvailable, None) => return Naming::Unnamed(Unnamed::Rule),
1653            (RuleIndex::Table(i), _) => i,
1654        };
1655        let Some(table) = table else {
1656            return Naming::Unnamed(Unnamed::NoTable);
1657        };
1658        let Some(rule) = table.get(usize::from(index)) else {
1659            return Naming::Unnamed(Unnamed::Rule);
1660        };
1661        let Some(labels) = rule.decode(self.labels) else {
1662            return Naming::Unnamed(Unnamed::Labels);
1663        };
1664        let alert_key = super::derive(
1665            &rule.name,
1666            labels.iter().map(|(n, v)| (n.as_str(), v.as_str())),
1667        )
1668        .integer();
1669        Naming::Named(Named {
1670            index,
1671            rule,
1672            summary: rule.summary(&labels, self.argument),
1673            argument: rule.reading(self.argument),
1674            labels,
1675            alert_key,
1676        })
1677    }
1678}
1679
1680// --- §2.2, §2.8, §2.9: which slot -------------------------------------------------
1681
1682/// What a raise does (§2.2, §2.5, §2.8).
1683#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1684pub enum Raise {
1685    /// The record is put firing on this slot: the one its instance holds a
1686    /// record of the identity on, else the lowest on which it holds no
1687    /// firing record.
1688    Put(u8),
1689    /// A duplicate observation of a firing alarm: no act.
1690    Firing,
1691    /// Every slot below the bound fires: the raise is refused, nothing is
1692    /// put, and no alarm is resolved or put over for room.
1693    Refused,
1694}
1695
1696/// What a resolve does (§2.5).
1697#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1698pub enum Resolve {
1699    /// The record is put resolved on its slot, where it stays: no delete.
1700    Put(u8),
1701    /// The identity does not fire: no act.
1702    NotFiring,
1703}
1704
1705/// One entry of the record an owner's previous instance left (§2.9), as
1706/// its new instance reads it.
1707#[derive(Debug, Clone, PartialEq, Eq)]
1708pub struct Left<I> {
1709    pub id: I,
1710    pub state: State,
1711    /// Whether the entry reads.
1712    pub reads: bool,
1713    /// Whether its words derive its alert key.
1714    pub derives: bool,
1715    /// Whether the new instance still evaluates its rule.
1716    pub evaluated: bool,
1717}
1718
1719/// What a new instance does with one slot of that record (§2.9).
1720#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1721pub enum Adoption {
1722    /// At or above the new bound: neither put nor resolved.
1723    Left,
1724    /// Resolved, or it does not read, or its words do not derive its key:
1725    /// nothing is put, and the slot is free.
1726    Free,
1727    /// Firing, under a rule the owner no longer evaluates: put resolved,
1728    /// on its slot.
1729    Resolved,
1730    /// Firing otherwise: put again on its slot, its `at` kept, under the
1731    /// new run.
1732    Adopted,
1733}
1734
1735impl Adoption {
1736    /// The fixture's token.
1737    #[must_use]
1738    pub fn as_str(self) -> &'static str {
1739        match self {
1740            Self::Left => "left",
1741            Self::Free => "free",
1742            Self::Resolved => "resolved",
1743            Self::Adopted => "adopted",
1744        }
1745    }
1746}
1747
1748/// The records one instance holds on its slots (§2.2), by identity: an
1749/// alert key, or anything that stands for one. An instance holds a record
1750/// on a slot from its put of it, until it puts another identity's there.
1751#[derive(Debug, Clone, PartialEq, Eq)]
1752pub struct Slots<I> {
1753    bound: u16,
1754    held: BTreeMap<u8, (I, State)>,
1755}
1756
1757impl<I: Clone + Eq> Slots<I> {
1758    /// An instance that holds nothing, under `bound`: 256, or the
1759    /// cardinality its descriptor states (§2.8).
1760    #[must_use]
1761    pub fn new(bound: u16) -> Self {
1762        Slots {
1763            bound: bound.min(MAX_SLOTS),
1764            held: BTreeMap::new(),
1765        }
1766    }
1767
1768    /// The instance's bound.
1769    #[must_use]
1770    pub fn bound(&self) -> u16 {
1771        self.bound
1772    }
1773
1774    /// The records held, by slot.
1775    pub fn held(&self) -> impl Iterator<Item = (u8, &I, State)> {
1776        self.held
1777            .iter()
1778            .map(|(slot, (id, state))| (*slot, id, *state))
1779    }
1780
1781    /// The slot the instance holds a record of `id` on, firing or
1782    /// resolved.
1783    #[must_use]
1784    pub fn slot_of(&self, id: &I) -> Option<(u8, State)> {
1785        self.held
1786            .iter()
1787            .find(|(_, (held, _))| held == id)
1788            .map(|(slot, (_, state))| (*slot, *state))
1789    }
1790
1791    /// The lowest slot below the bound on which the instance holds no
1792    /// firing record: one it holds nothing on, or one whose record is
1793    /// resolved.
1794    fn lowest_free(&self) -> Option<u8> {
1795        (0..self.bound)
1796            .filter_map(|s| u8::try_from(s).ok())
1797            .find(|s| !matches!(self.held.get(s), Some((_, State::Firing))))
1798    }
1799
1800    /// The condition of `id` is found (§2.2): the slot its record is put
1801    /// firing on, and the instance holds it there.
1802    pub fn raise(&mut self, id: &I) -> Raise {
1803        let slot = match self.slot_of(id) {
1804            Some((_, State::Firing)) => return Raise::Firing,
1805            Some((slot, State::Resolved)) => slot,
1806            None => match self.lowest_free() {
1807                Some(slot) => slot,
1808                None => return Raise::Refused,
1809            },
1810        };
1811        self.held.insert(slot, (id.clone(), State::Firing));
1812        Raise::Put(slot)
1813    }
1814
1815    /// The condition of `id` cleared (§2.5): its record is put resolved on
1816    /// its slot, which is free for another identity at once.
1817    pub fn resolve(&mut self, id: &I) -> Resolve {
1818        match self.slot_of(id) {
1819            Some((slot, State::Firing)) => {
1820                self.held.insert(slot, (id.clone(), State::Resolved));
1821                Resolve::Put(slot)
1822            }
1823            _ => Resolve::NotFiring,
1824        }
1825    }
1826
1827    /// The instance holds nothing on `slot` any more: a put of it that
1828    /// did not go out, or a resolved record a new instance does not hold
1829    /// (§2.9). The slot is free.
1830    pub fn forget(&mut self, slot: u8) {
1831        self.held.remove(&slot);
1832    }
1833
1834    /// A new instance under `bound`, with the record its previous instance
1835    /// left, by slot (§2.9); empty with no source. For each slot, what the
1836    /// new instance does, and it holds what it put and nothing else.
1837    ///
1838    /// An identity the record holds firing on two slots breaks §2.2: it is
1839    /// adopted on the lowest, and nothing is put on the others, which are
1840    /// free.
1841    #[must_use]
1842    pub fn restart(
1843        left: impl IntoIterator<Item = (u8, Left<I>)>,
1844        bound: u16,
1845    ) -> (Self, BTreeMap<u8, Adoption>) {
1846        let mut slots = Slots::new(bound);
1847        let left: BTreeMap<u8, Left<I>> = left.into_iter().collect();
1848        let mut did = BTreeMap::new();
1849        for (slot, entry) in left {
1850            let adoption = if u16::from(slot) >= slots.bound {
1851                Adoption::Left
1852            } else if entry.state == State::Resolved
1853                || !entry.reads
1854                || !entry.derives
1855                // One identity, one slot: the lowest was taken.
1856                || slots.slot_of(&entry.id).is_some()
1857            {
1858                Adoption::Free
1859            } else if !entry.evaluated {
1860                slots.held.insert(slot, (entry.id, State::Resolved));
1861                Adoption::Resolved
1862            } else {
1863                slots.held.insert(slot, (entry.id, State::Firing));
1864                Adoption::Adopted
1865            };
1866            did.insert(slot, adoption);
1867        }
1868        (slots, did)
1869    }
1870}
1871
1872/// One slot's record as a reader holds it of one owner (§2.6): the stamp
1873/// of the put that carried it, and the alert key the reader has for it,
1874/// `None` for an unnamed alarm.
1875#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1876pub struct Seen {
1877    pub slot: u8,
1878    pub stamp: Stamp,
1879    pub alert_key: Option<u64>,
1880}
1881
1882/// Which slot a reader takes for each identity (§2.6, "one identity on two
1883/// slots").
1884#[derive(Debug, Clone, Default, PartialEq, Eq)]
1885pub struct Taken {
1886    /// For each alert key, the slot the reader takes it on: the one under
1887    /// the run its owner's present descriptor states, the later by seq of
1888    /// two under it, and `None` where none is under it, each then an
1889    /// earlier instance's last word, or where no run is stated.
1890    pub takes: BTreeMap<u64, Option<u8>>,
1891    /// The alert keys two slots of the present run name: the break of
1892    /// §2.2 a tool may report (§5).
1893    pub double: Vec<u64>,
1894}
1895
1896/// [`Taken`] over what a reader holds of one owner, `present` being the
1897/// run that owner's present descriptor states (core §3.3). A slot is taken
1898/// only under it, so with none stated, as across a face, no slot is
1899/// taken. Unnamed alarms are not compared: two slots with no alert key
1900/// are two alarms.
1901#[must_use]
1902pub fn taken(seen: &[Seen], present: Option<Run>) -> Taken {
1903    let mut out = Taken::default();
1904    let mut best: BTreeMap<u64, Seq> = BTreeMap::new();
1905    for s in seen {
1906        let Some(key) = s.alert_key else { continue };
1907        let take = out.takes.entry(key).or_insert(None);
1908        if Some(s.stamp.run) != present {
1909            continue;
1910        }
1911        match best.get(&key) {
1912            Some(seq) => {
1913                if !out.double.contains(&key) {
1914                    out.double.push(key);
1915                }
1916                if s.stamp.seq.get() > seq.get() {
1917                    best.insert(key, s.stamp.seq);
1918                    *take = Some(s.slot);
1919                }
1920            }
1921            None => {
1922                best.insert(key, s.stamp.seq);
1923                *take = Some(s.slot);
1924            }
1925        }
1926    }
1927    out.double.sort_unstable();
1928    out
1929}
1930
1931/// §5's fourth question, "does this owner hold each identity on one
1932/// slot?" (§2.2): unobservable while its alarms are not established
1933/// ([`owner_set`]), else no where two slots of its present run name one
1934/// alert key ([`Taken::double`]), a finding about the owner.
1935#[must_use]
1936pub fn one_slot_each(set: SetVerdict, taken: &Taken) -> Answer {
1937    match set {
1938        SetVerdict::Established if taken.double.is_empty() => Answer::Yes,
1939        SetVerdict::Established => Answer::No,
1940        SetVerdict::Unobservable | SetVerdict::NotAsked => Answer::Unobservable,
1941    }
1942}
1943
1944// --- §2.4: words on `words/<slot>` -------------------------------------------------
1945
1946/// The words of an alarm no table names, `alarms.v2.Words` on
1947/// `words/<slot>` (§2.4): v1's document without `timestamp`,
1948/// `observed_at_ms`, `severity` and `state`. Members the schema does not
1949/// name are ignored when read.
1950#[derive(Debug, Clone, PartialEq, Eq)]
1951pub struct Words {
1952    pub rule: String,
1953    /// Every label, host-scoped ones included.
1954    pub labels: BTreeMap<String, String>,
1955    pub summary: String,
1956    pub category: Option<String>,
1957}
1958
1959/// Why a payload is no words a reader can read (§2.4).
1960#[derive(Debug, Clone, PartialEq, Eq)]
1961pub enum WordsInvalid {
1962    /// Not strict JSON, as v1 §2.4 reads a payload, with why.
1963    Json(String),
1964    /// Outside the `Words` schema, with where and why.
1965    Schema(String),
1966}
1967
1968impl std::fmt::Display for WordsInvalid {
1969    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1970        match self {
1971            Self::Json(why) => write!(f, "not strict JSON: {why}"),
1972            Self::Schema(why) => write!(f, "outside alarms.v2.Words: {why}"),
1973        }
1974    }
1975}
1976
1977impl Words {
1978    /// Reads a decoded payload: the schema's members and their types.
1979    ///
1980    /// # Errors
1981    /// [`WordsInvalid::Schema`].
1982    pub fn from_json(v: &Value) -> Result<Words, WordsInvalid> {
1983        let schema = |why: String| WordsInvalid::Schema(why);
1984        let Value::Object(o) = v else {
1985            return Err(schema("not an object".into()));
1986        };
1987        let string = |m: &str, required: bool| -> Result<Option<String>, WordsInvalid> {
1988            match o.get(m) {
1989                None if required => Err(WordsInvalid::Schema(format!("/{m}: missing"))),
1990                None => Ok(None),
1991                Some(Value::String(s)) => Ok(Some(s.clone())),
1992                Some(_) => Err(WordsInvalid::Schema(format!("/{m}: not a string"))),
1993            }
1994        };
1995        let rule = string("rule", true)?.unwrap_or_default();
1996        let summary = string("summary", true)?.unwrap_or_default();
1997        let category = string("category", false)?;
1998        let mut labels = BTreeMap::new();
1999        match o.get("labels") {
2000            None => {}
2001            Some(Value::Object(l)) => {
2002                for (n, v) in l {
2003                    let Value::String(v) = v else {
2004                        return Err(schema(format!("/labels/{n}: not a string")));
2005                    };
2006                    labels.insert(n.clone(), v.clone());
2007                }
2008            }
2009            Some(_) => return Err(schema("/labels: not an object".into())),
2010        }
2011        Ok(Words {
2012            rule,
2013            labels,
2014            summary,
2015            category,
2016        })
2017    }
2018
2019    /// Reads a payload's bytes (§2.4): strict JSON first, as v1 §2.4 reads
2020    /// a payload ([`super::decode`]), then [`Words::from_json`].
2021    ///
2022    /// # Errors
2023    /// [`WordsInvalid`].
2024    pub fn decode(bytes: &[u8]) -> Result<Words, WordsInvalid> {
2025        let text = std::str::from_utf8(bytes)
2026            .map_err(|e| WordsInvalid::Json(format!("not UTF-8: {e}")))?;
2027        let v = crate::strict::parse_json(text).map_err(|e| WordsInvalid::Json(e.to_string()))?;
2028        Words::from_json(&v)
2029    }
2030
2031    /// The document, as an owner puts it.
2032    #[must_use]
2033    pub fn to_json(&self) -> Value {
2034        let mut m = Map::new();
2035        m.insert("rule".into(), json!(self.rule));
2036        if !self.labels.is_empty() {
2037            m.insert("labels".into(), json!(self.labels));
2038        }
2039        m.insert("summary".into(), json!(self.summary));
2040        if let Some(c) = &self.category {
2041            m.insert("category".into(), json!(c));
2042        }
2043        Value::Object(m)
2044    }
2045
2046    /// What a reader derives from the words (v1 §2.3): the alert key,
2047    /// through the sanitizing step, and whether the strict recipe gives
2048    /// it.
2049    #[must_use]
2050    pub fn derive(&self) -> super::Derived {
2051        super::derive(
2052            &self.rule,
2053            self.labels.iter().map(|(n, v)| (n.as_str(), v.as_str())),
2054        )
2055    }
2056}
2057
2058/// How a reader takes a slot's words as its alarm's (§2.4).
2059#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2060pub enum How {
2061    /// v1's recipe gives the record's `key` from the words as they are.
2062    Strict,
2063    /// Only its sanitizing step does, which a tool MAY report.
2064    Sanitized,
2065}
2066
2067impl How {
2068    /// The fixture's token.
2069    #[must_use]
2070    pub fn as_str(self) -> &'static str {
2071        match self {
2072            Self::Strict => "strict",
2073            Self::Sanitized => "sanitized",
2074        }
2075    }
2076}
2077
2078/// Why a reader takes no words for a slot's alarm (§2.4), the first that
2079/// applies. An alarm by words is then shown by its alert key.
2080#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2081pub enum NotTaken {
2082    /// It holds no record on the slot.
2083    NoRecord,
2084    /// The record does not read.
2085    Undecodable,
2086    /// The record names a table's rule: the slot's words are an earlier
2087    /// alarm's.
2088    Table,
2089    /// It read no words.
2090    NoWords,
2091    /// The words do not read.
2092    Unreadable,
2093    /// The recipe gives another key: the words are another alarm's, or
2094    /// none's.
2095    Mismatch,
2096}
2097
2098impl NotTaken {
2099    /// The fixture's token.
2100    #[must_use]
2101    pub fn as_str(self) -> &'static str {
2102        self.reason().as_str()
2103    }
2104
2105    /// The reason §5's third question gives.
2106    #[must_use]
2107    pub fn reason(self) -> Reason {
2108        match self {
2109            Self::NoRecord => Reason::NoRecord,
2110            Self::Undecodable => Reason::Undecodable,
2111            Self::Table => Reason::Table,
2112            Self::NoWords => Reason::NoWords,
2113            Self::Unreadable => Reason::Unreadable,
2114            Self::Mismatch => Reason::Mismatch,
2115        }
2116    }
2117}
2118
2119/// Whether a reader takes a slot's words as the words of the slot's alarm
2120/// (§2.4), from what it holds on the slot: its record (`None` for none,
2121/// `Err` for one that does not read) and its words (the same). It takes
2122/// them while the record reads with a `rule` of `not_available`, the words
2123/// read, and v1's recipe over them, through the sanitizing step, gives the
2124/// record's `key`.
2125///
2126/// # Errors
2127/// [`NotTaken`], the first that applies.
2128pub fn words_taken<E, F>(
2129    record: Option<&Result<Record, E>>,
2130    words: Option<&Result<Words, F>>,
2131) -> Result<How, NotTaken> {
2132    let record = match record {
2133        None => return Err(NotTaken::NoRecord),
2134        Some(Err(_)) => return Err(NotTaken::Undecodable),
2135        Some(Ok(r)) => r,
2136    };
2137    let key = match (record.rule, record.key) {
2138        (RuleIndex::NotAvailable, Some(key)) => key,
2139        (RuleIndex::NotAvailable, None) => return Err(NotTaken::Undecodable),
2140        (RuleIndex::Table(_), _) => return Err(NotTaken::Table),
2141    };
2142    let words = match words {
2143        None => return Err(NotTaken::NoWords),
2144        Some(Err(_)) => return Err(NotTaken::Unreadable),
2145        Some(Ok(w)) => w,
2146    };
2147    let derived = words.derive();
2148    if derived.integer() != key {
2149        Err(NotTaken::Mismatch)
2150    } else if derived.framed {
2151        Ok(How::Strict)
2152    } else {
2153        Ok(How::Sanitized)
2154    }
2155}
2156
2157/// §5's third question, "do this slot's words derive its record's key?"
2158/// (§2.4), over [`words_taken`]: yes, `strict` or `sanitized`; no,
2159/// `mismatch`, a finding about the owner only while it lasts, since words
2160/// are put before their record; not asked for `table`, `no_words` and
2161/// `no_record`; unobservable for `unreadable` and `undecodable`.
2162#[must_use]
2163pub fn words_derive(taken: Result<How, NotTaken>) -> Judged {
2164    match taken {
2165        Ok(How::Strict) => Judged::new(Answer::Yes, Reason::Strict),
2166        Ok(How::Sanitized) => Judged::new(Answer::Yes, Reason::Sanitized),
2167        Err(why) => Judged::new(
2168            match why {
2169                NotTaken::Mismatch => Answer::No,
2170                NotTaken::Table | NotTaken::NoWords | NotTaken::NoRecord => Answer::NotAsked,
2171                NotTaken::Unreadable | NotTaken::Undecodable => Answer::Unobservable,
2172            },
2173            why.reason(),
2174        ),
2175    }
2176}
2177
2178// --- §2.6: transitions, by identity ---------------------------------------------
2179
2180/// The record a reader holds on a slot (§2.6): with the run of the put
2181/// that carried it, its envelope's or its snapshot entry's, and the alert
2182/// key the reader has for it ([`Naming::alert_key`]), `None` for an
2183/// unnamed alarm.
2184#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2185pub struct Held {
2186    pub record: Record,
2187    pub run: Run,
2188    pub alert_key: Option<u64>,
2189}
2190
2191impl Held {
2192    /// Whether two records of one slot have one identity (§2.6): each has
2193    /// an alert key, and the two are equal; or either is unnamed, and
2194    /// their `rule` and their `labels` are equal, an absent `labels` equal
2195    /// only to an absent one.
2196    #[must_use]
2197    pub fn same_identity(&self, other: &Held) -> bool {
2198        match (self.alert_key, other.alert_key) {
2199            (Some(a), Some(b)) => a == b,
2200            _ => self.record.rule == other.record.rule && self.record.labels == other.record.labels,
2201        }
2202    }
2203
2204    fn facts(&self) -> PutFacts<Option<Severity>, Option<i64>> {
2205        PutFacts {
2206            state: self.record.state,
2207            severity: self.record.severity,
2208            at: self.record.at,
2209        }
2210    }
2211}
2212
2213/// One sample of one slot's key, in the owner's order (core §4.2).
2214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2215pub enum Sample {
2216    /// A put whose record reads.
2217    Put(Held),
2218    /// A put that does not read (§2.4).
2219    Unreadable,
2220    /// A delete, or a tombstone. No rule here has an owner send one.
2221    Delete,
2222}
2223
2224/// What becomes of a held record of another identity when a put takes its
2225/// slot (§2.6).
2226#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2227pub enum Displaced {
2228    /// It fired, under the put's run. An owner never takes a slot whose
2229    /// record fires, so the held alarm resolved, and the reader lost that
2230    /// put: it reads resolved.
2231    Rebound,
2232    /// It was resolved, under the put's run: nothing to read.
2233    Replaced,
2234    /// It was under another run: an earlier run's last word, of which
2235    /// nothing is known.
2236    Dropped,
2237}
2238
2239impl Displaced {
2240    /// The fixture's token.
2241    #[must_use]
2242    pub fn as_str(self) -> &'static str {
2243        match self {
2244            Self::Rebound => "rebound",
2245            Self::Replaced => "replaced",
2246            Self::Dropped => "dropped",
2247        }
2248    }
2249}
2250
2251/// A change a notifier reports (§2.16), where every answer of §2.14
2252/// follows the slot's records alone: its owner present and listed,
2253/// nothing lost, each firing record fresh.
2254#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2255pub enum Change {
2256    /// The alarm's answer moved to yes, or its severity moved while yes.
2257    Firing,
2258    /// It moved from yes to no: a resolved record, a delete or `rebound`.
2259    Resolved,
2260}
2261
2262impl Change {
2263    /// The fixture's token.
2264    #[must_use]
2265    pub fn as_str(self) -> &'static str {
2266        match self {
2267            Self::Firing => "firing",
2268            Self::Resolved => "resolved",
2269        }
2270    }
2271}
2272
2273/// One [`Change`], of the alarm with this alert key; `None` for an
2274/// unnamed alarm, which a tool reports by its owner, its slot and its
2275/// `at`.
2276#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2277pub struct Report {
2278    pub change: Change,
2279    pub alert_key: Option<u64>,
2280}
2281
2282/// What a reader reads of one sample of a slot (§2.6).
2283#[derive(Debug, Clone, PartialEq, Eq)]
2284pub struct Applied {
2285    /// A held record of another identity, and what became of it. `None`
2286    /// where nothing was held, or the same identity was.
2287    pub displaced: Option<(Displaced, Held)>,
2288    /// The sample's own reading, by v1's table.
2289    pub reads: Transition,
2290    /// What a notifier reports after the sample (§2.16): a `rebound`
2291    /// alarm resolved first, then the sample's own change. A record
2292    /// `replaced` or `dropped`, and an unreadable put, report nothing of
2293    /// the alarm held before.
2294    pub reports: Vec<Report>,
2295}
2296
2297/// One slot's record as a reader follows it (§2.6): what it holds, and
2298/// what each sample reads as.
2299#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2300pub struct Track {
2301    /// The record held: `None` before any, after a delete, and after a put
2302    /// that did not read.
2303    pub held: Option<Held>,
2304}
2305
2306impl Track {
2307    /// Reads one sample, the next in the owner's order, against the
2308    /// record held on the slot.
2309    pub fn apply(&mut self, sample: Sample) -> Applied {
2310        let held = self.held.take();
2311        let was_firing = |h: &Held| h.record.state == State::Firing;
2312        let mut reports = Vec::new();
2313        let new = match sample {
2314            Sample::Unreadable => {
2315                return Applied {
2316                    displaced: None,
2317                    reads: Transition::Unreadable,
2318                    reports,
2319                };
2320            }
2321            Sample::Delete => {
2322                let reads = super::delete_reads(held.map(|h| h.record.state));
2323                if let Some(h) = held.filter(was_firing) {
2324                    reports.push(Report {
2325                        change: Change::Resolved,
2326                        alert_key: h.alert_key,
2327                    });
2328                }
2329                return Applied {
2330                    displaced: None,
2331                    reads,
2332                    reports,
2333                };
2334            }
2335            Sample::Put(new) => new,
2336        };
2337        self.held = Some(new);
2338        let (same, displaced) = match held {
2339            Some(h) if h.same_identity(&new) => (Some(h), None),
2340            Some(h) => {
2341                let what = if h.run != new.run {
2342                    Displaced::Dropped
2343                } else if was_firing(&h) {
2344                    Displaced::Rebound
2345                } else {
2346                    Displaced::Replaced
2347                };
2348                (None, Some((what, h)))
2349            }
2350            None => (None, None),
2351        };
2352        if let Some((Displaced::Rebound, h)) = displaced {
2353            reports.push(Report {
2354                change: Change::Resolved,
2355                alert_key: h.alert_key,
2356            });
2357        }
2358        let reads = super::put_reads(
2359            same.as_ref().map(Held::facts),
2360            new.facts(),
2361            same.is_some_and(|h| h.record == new.record),
2362        );
2363        let fired = same.as_ref().is_some_and(was_firing);
2364        let change = match reads {
2365            // A raise of an alarm already firing at its severity, whose
2366            // `at` moved with no resolve heard, is not told again.
2367            Transition::Raised if !fired => Some(Change::Firing),
2368            Transition::Escalated => Some(Change::Firing),
2369            Transition::Resolved if fired => Some(Change::Resolved),
2370            _ => None,
2371        };
2372        reports.extend(change.map(|change| Report {
2373            change,
2374            alert_key: new.alert_key,
2375        }));
2376        Applied {
2377            displaced,
2378            reads,
2379            reports,
2380        }
2381    }
2382}
2383
2384// --- §3, core §7.5: a late joiner's snapshot -------------------------------------
2385
2386/// Which of the standard contract's two collections a snapshot is of
2387/// (§3).
2388#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2389pub enum Collection {
2390    /// `state/alarms/{slot}`: one entry per slot that has a value, its id
2391    /// the slot, on `…/state/alarms`, collection 0.
2392    Alarms,
2393    /// `state/words/{slot}`: the same on `…/state/words`, collection 1.
2394    /// Never exposed across a face (§2.11).
2395    Words,
2396}
2397
2398impl Collection {
2399    /// The collection's index in a snapshot ([`ALARMS_COLL`],
2400    /// [`WORDS_COLL`]).
2401    #[must_use]
2402    pub const fn coll(self) -> u32 {
2403        match self {
2404            Collection::Alarms => ALARMS_COLL,
2405            Collection::Words => WORDS_COLL,
2406        }
2407    }
2408
2409    /// The key a reply's snapshot of this collection is on, below the
2410    /// owner: the template's fixed chunks (core §4.2).
2411    #[must_use]
2412    pub const fn suffix(self) -> &'static str {
2413        match self {
2414            Collection::Alarms => "alarms.v2/state/alarms",
2415            Collection::Words => "alarms.v2/state/words",
2416        }
2417    }
2418
2419    /// The collection a page read on `key` is of, where its `coll` is that
2420    /// collection's: `None` for a key that is neither's, and for an index
2421    /// the standard contract does not give that key.
2422    #[must_use]
2423    pub fn of(key: &str, coll: u32) -> Option<Collection> {
2424        [Collection::Alarms, Collection::Words]
2425            .into_iter()
2426            .find(|c| {
2427                key.strip_suffix(c.suffix())
2428                    .is_some_and(|rest| rest.is_empty() || rest.ends_with('/'))
2429                    && c.coll() == coll
2430            })
2431    }
2432}
2433
2434/// One snapshot as a late joiner holds it (core §7.5): its header, and
2435/// whether it holds every page.
2436#[derive(Debug, Clone, PartialEq, Eq)]
2437pub struct Heard {
2438    /// A page of each index up to one whose more bit is 0.
2439    pub complete: bool,
2440    /// CH's tag, under which each entry's record is read.
2441    pub tag: Tag,
2442    pub run: Run,
2443    pub asof: Seq,
2444    /// The snapshot's time, on the owner's clock.
2445    pub time: collection::Time,
2446}
2447
2448/// One live entry of a snapshot, read.
2449#[derive(Debug, Clone, PartialEq, Eq)]
2450pub struct Entry<R> {
2451    /// The entry's id, and the slot it names: `None` for an id that is no
2452    /// slot, from which a reader reads nothing (§2.2).
2453    pub id: String,
2454    pub slot: Option<u8>,
2455    /// Its put's stamp: the entry's own run where it states one, else the
2456    /// snapshot's. A record is held with this run (§2.6).
2457    pub stamp: Stamp,
2458    pub confirmation: Confirmation,
2459    /// When the owner last vouched for it (`freshness.v2` §2.4): the
2460    /// snapshot's time for confirmation 1, its `conf` for 2, none for 0
2461    /// and for a time that is unknown. A GET reader ages a firing entry
2462    /// from it (§2.15).
2463    pub confirmed_at: Option<collection::Time>,
2464    /// Its record, read under the page's tag, or why it does not read; for
2465    /// the words, the document.
2466    pub record: R,
2467}
2468
2469/// One collection's snapshot, read: every live entry in the order read,
2470/// and each tombstone within the window.
2471#[derive(Debug, Clone, PartialEq, Eq)]
2472pub struct Snapshot<R> {
2473    pub heard: Heard,
2474    pub live: Vec<Entry<R>>,
2475    /// Each tombstone: its id and its delete's stamp.
2476    pub retired: Vec<(String, Stamp)>,
2477}
2478
2479/// A late joiner's reading of one owner's answer to a collection read of
2480/// its `alarms.v2/state/**` (§2.15, core §4.2): the alarms' snapshot and
2481/// the words', each none where no page of it was read.
2482#[derive(Debug, Clone, Default, PartialEq, Eq)]
2483pub struct Seed {
2484    pub alarms: Option<Snapshot<Result<Record, Undecodable>>>,
2485    pub words: Option<Snapshot<Result<Words, WordsInvalid>>>,
2486    /// A page of a second snapshot of one collection was read, under
2487    /// another header than its first: left out, and the alarms are then
2488    /// not read whole ([`Seed::snapshot`]).
2489    pub mixed: bool,
2490}
2491
2492/// One collection's pages as they arrive: the first snapshot heard, and
2493/// its pages in the order read.
2494struct Pages {
2495    heard: collection::Heard,
2496    pages: Vec<Page>,
2497}
2498
2499fn stamp_of(run: Option<Run>, seq: Seq, header: Run) -> Stamp {
2500    Stamp {
2501        run: run.unwrap_or(header),
2502        seq,
2503    }
2504}
2505
2506fn snapshot_of<R>(p: &Pages, read: impl Fn(&Page, &[u8]) -> R) -> Snapshot<R> {
2507    let entry = |e: &collection::Entry, page: &Page| {
2508        let confirmed_at = match e.confirmation {
2509            Confirmation::None => None,
2510            Confirmation::AtTime => Some(page.time),
2511            Confirmation::At(t) => Some(t),
2512        }
2513        .filter(|t| *t != collection::Time::Unknown);
2514        Entry {
2515            id: e.id.clone(),
2516            slot: parse_slot(&e.id),
2517            stamp: stamp_of(e.run, e.seq, page.run),
2518            confirmation: e.confirmation,
2519            confirmed_at,
2520            record: read(page, &e.record),
2521        }
2522    };
2523    Snapshot {
2524        heard: Heard {
2525            complete: p.heard.complete(),
2526            tag: p.heard.tag,
2527            run: p.heard.run,
2528            asof: p.heard.asof,
2529            time: p.heard.time,
2530        },
2531        live: p
2532            .pages
2533            .iter()
2534            .flat_map(|page| page.live.iter().map(move |e| (e, page)))
2535            .map(|(e, page)| entry(e, page))
2536            .collect(),
2537        retired: p
2538            .pages
2539            .iter()
2540            .flat_map(|page| {
2541                page.tombs
2542                    .iter()
2543                    .map(|t| (t.id.clone(), stamp_of(t.run, t.seq, page.run)))
2544            })
2545            .collect(),
2546    }
2547}
2548
2549impl Seed {
2550    /// Reads a GET's replies, each its key and its payload, in the order
2551    /// they arrived, under the deployment epoch `epoch` in seconds. A
2552    /// reply that is no page core §7.5 accepts, and a page that is of
2553    /// neither collection of the standard contract ([`Collection::of`]),
2554    /// takes no part.
2555    #[must_use]
2556    pub fn of<'a>(replies: impl IntoIterator<Item = (&'a str, &'a [u8])>, epoch: i64) -> Seed {
2557        let mut held: [Option<Pages>; 2] = [None, None];
2558        let mut mixed = false;
2559        for (key, payload) in replies {
2560            let Ok(page) = Page::parse(payload) else {
2561                continue;
2562            };
2563            let Some(c) = Collection::of(key, page.coll) else {
2564                continue;
2565            };
2566            let slot = &mut held[c as usize];
2567            match slot {
2568                Some(p) if p.heard.holds(key, &page) => {
2569                    if p.heard.add(&page) {
2570                        p.pages.push(page);
2571                    }
2572                }
2573                Some(_) => mixed = true,
2574                None => {
2575                    let mut heard = collection::Heard::of(key, &page);
2576                    heard.add(&page);
2577                    *slot = Some(Pages {
2578                        heard,
2579                        pages: vec![page],
2580                    });
2581                }
2582            }
2583        }
2584        let [alarms, words] = held;
2585        Seed {
2586            alarms: alarms
2587                .map(|p| snapshot_of(&p, |page, bytes| Record::read(page.tag.get(), bytes, epoch))),
2588            words: words.map(|p| snapshot_of(&p, |_, bytes| Words::decode(bytes))),
2589            mixed,
2590        }
2591    }
2592
2593    /// The alarms' snapshot as §2.15 judges it ([`owner_set`]), `stated`
2594    /// being the runs the owner's present descriptors state (core §3.3),
2595    /// empty where none states one and across a face, where the
2596    /// deployment's word stands for the descriptor and no run is
2597    /// compared. `None` where no page of it was read. A reading that mixed
2598    /// two snapshots is not complete.
2599    #[must_use]
2600    pub fn snapshot(&self, stated: &[Run]) -> Option<SnapshotRead> {
2601        let alarms = self.alarms.as_ref()?;
2602        Some(SnapshotRead {
2603            complete: alarms.heard.complete && !self.mixed,
2604            run: SnapshotRun::of(alarms.heard.run, stated),
2605        })
2606    }
2607}
2608
2609// --- §2.14, §2.15, §5: what a tool may conclude -----------------------------------
2610
2611/// The latest sample a reader holds of one alarm, as §2.6 reads it
2612/// (§2.14's step 5). The state is the record's, never the sample's kind, a
2613/// heartbeat's bit or a count (§2.6, §2.7).
2614#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2615pub enum Latest {
2616    /// A firing record.
2617    Firing,
2618    /// A resolved record: answered at step 5, whatever its age.
2619    Resolved,
2620    /// Its record was replaced on its slot by another identity's, under
2621    /// its run, while it fired ([`Displaced::Rebound`]).
2622    Rebound,
2623    /// A delete, or a tombstone.
2624    Deleted,
2625    /// A put that does not read (§2.4).
2626    Undecodable,
2627}
2628
2629impl Latest {
2630    /// The latest sample a held record is, or one that does not read.
2631    #[must_use]
2632    pub fn of<E>(record: &Result<Record, E>) -> Latest {
2633        match record {
2634            Ok(r) if r.state == State::Firing => Latest::Firing,
2635            Ok(_) => Latest::Resolved,
2636            Err(_) => Latest::Undecodable,
2637        }
2638    }
2639}
2640
2641/// One reading of one alarm (§2.14): an alarm the reader holds on a slot,
2642/// or one asked by reference, which is the one whose record derives that
2643/// alert key. An unnamed alarm is answered as any other, by its slot.
2644#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2645pub struct Reading {
2646    /// [`Presence::Present`] with [`super::Listing::Listed`] for a
2647    /// descriptor whose `interfaces` holds `alarms.v2`
2648    /// ([`super::Major::of`]), `NotListed` for one that holds neither
2649    /// major. One that holds `alarms.v1` alone is [`super::firing`]'s.
2650    pub presence: Presence,
2651    /// `freshness.v2`'s verdict over the slot's observations, at the
2652    /// horizon of the revision its owner names (§2.7, text 0.2): the
2653    /// standard revision's is 900 s ([`super::TTL`]). `None` where nothing
2654    /// was observed, which judges the same at any horizon.
2655    pub freshness: Option<freshness::Judged>,
2656    /// The latest sample; `None` where the reader holds nothing of the
2657    /// alarm: never read, or its record `replaced` or `dropped`.
2658    pub latest: Option<Latest>,
2659    /// The reader's subscription lost a delivery, and since then no GET
2660    /// has answered this slot.
2661    pub lost: bool,
2662    /// The latest put is attributed to an earlier instance: a snapshot's
2663    /// entry under a run no present descriptor states.
2664    pub previous_instance: bool,
2665    /// The owner's alarms are established in this reading ([`owner_set`]).
2666    pub held_whole: bool,
2667    /// The read that established them listed the alarm's slot neither
2668    /// live nor as a tombstone, and nothing of it arrived after that read
2669    /// was asked. With [`Reading::held_whole`] it makes any held sample
2670    /// none, and heals [`Reading::lost`].
2671    pub left_out: bool,
2672}
2673
2674impl Reading {
2675    fn asked(&self) -> Asked {
2676        Asked {
2677            presence: self.presence,
2678            freshness: self
2679                .freshness
2680                .unwrap_or_else(|| freshness::judge_all(&super::horizon(), &[])),
2681            lost: self.lost,
2682            latest: self.latest.map(|l| match l {
2683                Latest::Firing => Step5::Firing,
2684                Latest::Undecodable => Step5::Undecodable,
2685                Latest::Resolved => Step5::Not(Reason::Resolved),
2686                Latest::Rebound => Step5::Not(Reason::Rebound),
2687                Latest::Deleted => Step5::Not(Reason::Deleted),
2688            }),
2689            previous_instance: self.previous_instance,
2690            held_whole: self.held_whole,
2691            left_out: self.left_out,
2692        }
2693    }
2694}
2695
2696/// §5's first question, "is this alarm firing?", by v1 §2.14's steps over
2697/// this major's records (§2.14): presence, the descriptor, an archive
2698/// alone, a loss, the latest sample, `rebound` among them, then its
2699/// freshness at its revision's horizon ([`Reading::freshness`]). Yes is the
2700/// finding.
2701#[must_use]
2702pub fn firing(r: &Reading) -> Judged {
2703    super::firing_asked(&r.asked())
2704}
2705
2706/// §5's last question, "is this firing alarm past its horizon, its owner
2707/// present?", over the reading [`firing`] takes, with `rebound` beside a
2708/// resolved record: not asked, `not_firing`.
2709#[must_use]
2710pub fn stale_firing(r: &Reading) -> Judged {
2711    super::stale_firing_asked(&r.asked())
2712}
2713
2714/// A snapshot's run against the runs the owner's present descriptors
2715/// state (§2.15, core §3.3).
2716#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2717pub enum SnapshotRun {
2718    /// A present descriptor states it.
2719    Stated,
2720    /// One states a run, and none states this one: an earlier instance
2721    /// built the snapshot.
2722    Other,
2723    /// No present descriptor states a run, or the owner is across a face:
2724    /// nothing to compare.
2725    Unstated,
2726}
2727
2728impl SnapshotRun {
2729    /// `run` against the runs `stated`, empty where none is.
2730    #[must_use]
2731    pub fn of(run: Run, stated: &[Run]) -> SnapshotRun {
2732        if stated.is_empty() {
2733            SnapshotRun::Unstated
2734        } else if stated.contains(&run) {
2735            SnapshotRun::Stated
2736        } else {
2737            SnapshotRun::Other
2738        }
2739    }
2740}
2741
2742/// The alarms' snapshot a collection read drew (§2.15).
2743#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2744pub struct SnapshotRead {
2745    /// Whether the reader holds every page of it (core §7.5), with any
2746    /// number of entries or none.
2747    pub complete: bool,
2748    pub run: SnapshotRun,
2749}
2750
2751/// How a reader's latest collection read of an owner's
2752/// `alarms.v2/state/alarms/**` ended (§2.15).
2753#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2754pub enum Read {
2755    /// At its final reply, with no error reply, with the snapshot it drew:
2756    /// `None` where it drew no page, which is silence and never "nothing
2757    /// fires".
2758    Complete(Option<SnapshotRead>),
2759    /// At its timeout, or with an error reply.
2760    Incomplete,
2761}
2762
2763/// What a reader's subscription saw since its read was asked (§2.15).
2764#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2765pub struct Since {
2766    /// It lost no delivery.
2767    pub lossless: bool,
2768    /// No gap in the owner's presence: its instance token not withdrawn,
2769    /// and no new instance's appearing. Not asked across a face, where
2770    /// presence does not cross.
2771    pub present_throughout: bool,
2772}
2773
2774/// Whether an owner's alarms are known whole (§2.15), by the first of its
2775/// order that answers: v1 §2.14's steps 1 and 2, with their reasons; the
2776/// read (`no_seed`, `seed_incomplete`); since the read, for a reader that
2777/// subscribes (`window_lost`, then `owner_gap`, never asked across a
2778/// face); the snapshot (`snapshot_incomplete`, then `snapshot_run`, never
2779/// asked across a face nor where no run is stated); otherwise
2780/// established, `snapshot`. `since` is `None` for a reader that does not
2781/// subscribe.
2782///
2783/// One complete snapshot establishes them, with an entry or with none: a
2784/// snapshot with no entry is the owner's word that nothing fires. It does
2785/// not lapse.
2786#[must_use]
2787pub fn owner_set(presence: Presence, read: Option<Read>, since: Option<Since>) -> SetJudged {
2788    let j = |verdict, reason| SetJudged { verdict, reason };
2789    use SetVerdict::{Established, NotAsked, Unobservable};
2790    if let Some(p) = super::premises(presence) {
2791        return j(
2792            match p.answer {
2793                Answer::NotAsked => NotAsked,
2794                _ => Unobservable,
2795            },
2796            p.reason,
2797        );
2798    }
2799    let snapshot = match read {
2800        None => return j(Unobservable, Reason::NoSeed),
2801        Some(Read::Incomplete) => return j(Unobservable, Reason::SeedIncomplete),
2802        Some(Read::Complete(snapshot)) => snapshot,
2803    };
2804    let across = matches!(presence, Presence::AcrossFace { .. });
2805    if let Some(s) = since {
2806        if !s.lossless {
2807            return j(Unobservable, Reason::WindowLost);
2808        }
2809        if !s.present_throughout && !across {
2810            return j(Unobservable, Reason::OwnerGap);
2811        }
2812    }
2813    match snapshot {
2814        None
2815        | Some(SnapshotRead {
2816            complete: false, ..
2817        }) => j(Unobservable, Reason::SnapshotIncomplete),
2818        Some(SnapshotRead {
2819            run: SnapshotRun::Other,
2820            ..
2821        }) if !across => j(Unobservable, Reason::SnapshotRun),
2822        Some(_) => j(Established, Reason::Snapshot),
2823    }
2824}
2825
2826#[cfg(test)]
2827mod tests {
2828    use super::*;
2829
2830    fn table() -> Vec<Rule> {
2831        rules(&json!([
2832            {"name": "hot", "category": "sensor_health", "summary": "Temperature {argument} C",
2833             "argument": {"minimum": "-40", "resolution": "0.1"}},
2834            {"name": "link_down", "summary": "Link to {peer} on {port} is down",
2835             "labels": [{"name": "peer", "values": ["r1", "r2", "r3"]},
2836                        {"name": "port", "values": ["eth0", "eth1"]}]},
2837            {"name": "sensor_lost", "summary": "Sensor {sensor} lost",
2838             "labels": [{"name": "sensor", "minimum": 0, "maximum": 63}]},
2839        ]))
2840        .expect("the text's table")
2841    }
2842
2843    fn stamp(run: u16, seq: u32) -> Stamp {
2844        Stamp {
2845            run: Run::U16(run),
2846            seq: Seq::new(seq).unwrap(),
2847        }
2848    }
2849
2850    #[test]
2851    fn the_layout_is_nine_bytes_for_the_usual_record_and_its_tag_is_eleven() {
2852        let l = layout();
2853        assert_eq!((l.tag(), l.min_bits(), l.max_bits()), (TAG, 35, 155));
2854        let epoch = 1_767_225_600;
2855        let r = Record {
2856            state: State::Firing,
2857            severity: Some(Severity::Critical),
2858            rule: RuleIndex::Table(3),
2859            at: Some(1_794_062_759),
2860            labels: None,
2861            argument: Argument::NotAvailable,
2862            key: None,
2863        };
2864        let written = r.write(epoch).unwrap();
2865        assert_eq!(
2866            written.bytes,
2867            [0x40, 0x70, 0x19, 0x98, 0x0a, 0x77, 0xff, 0xff, 0x80]
2868        );
2869        assert_eq!(Record::read(TAG, &written.bytes, epoch), Ok(r));
2870        let put = r.put(stamp(3, 5), epoch).unwrap();
2871        assert_eq!(put[0], 0x0b, "form 0, a 16-bit run, tag 11");
2872        assert_eq!(put.len(), 15);
2873        // A JSON payload's tag is 0: refused before a bit is read.
2874        assert_eq!(
2875            Record::read(0, &written.bytes, epoch),
2876            Err(Undecodable::Core(ReadRefusal::Tag))
2877        );
2878        // No `at`: 5 bytes.
2879        let bare = Record { at: None, ..r };
2880        assert_eq!(bare.write(epoch).unwrap().bytes.len(), 5);
2881    }
2882
2883    #[test]
2884    fn a_key_goes_with_not_available_and_with_nothing_else() {
2885        let epoch = 0;
2886        let by_words = Record {
2887            state: State::Firing,
2888            severity: Some(Severity::Warning),
2889            rule: RuleIndex::NotAvailable,
2890            at: None,
2891            labels: None,
2892            argument: Argument::NotAvailable,
2893            key: Some(0xa659_f813_308a_d1da),
2894        };
2895        assert_eq!(by_words.write(epoch).unwrap().bytes.len(), 13);
2896        let no_key = Record {
2897            key: None,
2898            ..by_words
2899        };
2900        assert_eq!(no_key.write(epoch), Err(Refused::KeyMissing));
2901        let both = Record {
2902            rule: RuleIndex::Table(1),
2903            ..by_words
2904        };
2905        assert_eq!(both.write(epoch), Err(Refused::KeyWithRule));
2906        let labelled = Record {
2907            labels: Some(2),
2908            ..by_words
2909        };
2910        assert_eq!(labelled.write(epoch), Err(Refused::ByWordsFields));
2911        assert_eq!(RuleIndex::new(255), None);
2912        assert_eq!(Argument::new(1_048_575), None);
2913    }
2914
2915    #[test]
2916    fn an_alarm_is_written_by_its_table_or_by_words_and_read_back() {
2917        let t = table();
2918        let f = write_alarm(
2919            Some(&t),
2920            "link_down",
2921            [("port", "eth0"), ("peer", "r2"), ("host", "h-3fa9c2d41b7e")],
2922            None,
2923        );
2924        assert_eq!(
2925            (f.rule, f.labels, f.key),
2926            (RuleIndex::Table(1), Some(2), None)
2927        );
2928        let record = Record::new(State::Firing, Severity::Warning, f, None);
2929        let Naming::Named(n) = record.name(Some(&t)) else {
2930            panic!("named")
2931        };
2932        assert_eq!(super::super::key_hex(n.alert_key), "a659f813308ad1da");
2933        assert_eq!(n.summary, "Link to r2 on eth0 is down");
2934        // A value no table lists: by words, with v1's alert key.
2935        let w = write_alarm(
2936            Some(&t),
2937            "link_down",
2938            [("peer", "r4"), ("port", "eth0")],
2939            None,
2940        );
2941        assert_eq!(w.rule, RuleIndex::NotAvailable);
2942        assert!(w.key.is_some() && w.labels.is_none());
2943        // No table in hand: numbers, never another revision's name.
2944        assert_eq!(record.name(None), Naming::Unnamed(Unnamed::NoTable));
2945        // The argument: a tie to the even code, and `?` for none.
2946        let hot = &t[0];
2947        let reading = |s: &str| hot.argument(Decimal::parse_input(s).as_ref());
2948        assert_eq!(reading("21.55"), Argument::Code(616));
2949        assert_eq!(reading("-40.2"), Argument::NotAvailable);
2950        assert_eq!(hot.summary(&[], Argument::Code(615)), "Temperature 21.5 C");
2951        assert_eq!(hot.summary(&[], Argument::NotAvailable), "Temperature ? C");
2952    }
2953
2954    #[test]
2955    fn a_tables_findings_come_in_the_texts_order() {
2956        let t = table_json(&table());
2957        assert_eq!(declaration(true, [&t]), Declared::Table(table()));
2958        assert_eq!(
2959            declaration(false, [&t]),
2960            Declared::Invalid(Invalid::NotUsed)
2961        );
2962        let twice = json!([{"name": "a", "summary": "{x}"}, {"name": "a", "summary": "s"}]);
2963        assert_eq!(
2964            declaration(true, [&twice]),
2965            Declared::Invalid(Invalid::RuleName),
2966            "before the placeholder"
2967        );
2968        let other = json!([{"name": "a", "summary": "s"}]);
2969        assert_eq!(
2970            declaration(true, [&t, &other]),
2971            Declared::Invalid(Invalid::Disagrees)
2972        );
2973        assert_eq!(
2974            declaration(true, [&t, &twice]),
2975            Declared::Invalid(Invalid::RuleName),
2976            "a finding of any list stands before `disagrees`"
2977        );
2978        assert_eq!(growth(&table()[..2], &table()), Growth::Kept);
2979        assert_eq!(growth(&table(), &table()[..2]), Growth::Moved);
2980    }
2981
2982    #[test]
2983    fn an_identity_takes_its_own_slot_else_the_lowest_that_does_not_fire() {
2984        let mut s: Slots<&str> = Slots::new(2);
2985        assert_eq!(s.raise(&"a"), Raise::Put(0));
2986        assert_eq!(s.raise(&"a"), Raise::Firing);
2987        assert_eq!(s.raise(&"b"), Raise::Put(1));
2988        assert_eq!(s.raise(&"c"), Raise::Refused, "never over a firing record");
2989        assert_eq!(s.resolve(&"a"), Resolve::Put(0));
2990        assert_eq!(s.resolve(&"a"), Resolve::NotFiring);
2991        assert_eq!(s.raise(&"a"), Raise::Put(0), "a re-raise keeps its slot");
2992        assert_eq!(s.resolve(&"b"), Resolve::Put(1));
2993        assert_eq!(s.raise(&"c"), Raise::Put(1), "a resolved slot retaken");
2994        assert_eq!(s.slot_of(&"b"), None);
2995    }
2996
2997    #[test]
2998    fn at_moves_a_second_at_a_time_and_an_acknowledgement_follows_it() {
2999        let epoch = 1_767_225_600;
3000        let mut d = Dating::default();
3001        assert_eq!(d.transition(1_794_062_759_100, epoch), Some(1_794_062_759));
3002        assert_eq!(d.transition(1_794_062_759_200, epoch), Some(1_794_062_760));
3003        assert_eq!(d.transition(5000, epoch), None, "1970 has no code");
3004        assert_eq!(d.at(Act::Refresh, None, 1_794_062_800_000, epoch), None);
3005        assert_eq!(d.transition(1_794_062_759_300, epoch), Some(1_794_062_761));
3006        assert!(acknowledged(Some(1_794_062_759_123), Some(1_794_062_759)));
3007        assert!(!acknowledged(Some(1_794_062_759_000), Some(1_794_062_760)));
3008        assert!(!acknowledged(Some(1_794_062_759_000), None));
3009        assert!(!acknowledged(None, None));
3010    }
3011
3012    #[test]
3013    fn another_identity_on_a_firing_slot_is_a_resolve_the_reader_lost() {
3014        let record = |rule, state| Record {
3015            state,
3016            severity: Some(Severity::Warning),
3017            rule: RuleIndex::Table(rule),
3018            at: Some(1),
3019            labels: None,
3020            argument: Argument::NotAvailable,
3021            key: None,
3022        };
3023        let held = |rule, state, run, key| Held {
3024            record: record(rule, state),
3025            run: Run::U16(run),
3026            alert_key: Some(key),
3027        };
3028        let mut t = Track::default();
3029        assert_eq!(
3030            t.apply(Sample::Put(held(1, State::Firing, 3, 10))).reads,
3031            Transition::Raised
3032        );
3033        let a = t.apply(Sample::Put(held(2, State::Firing, 3, 20)));
3034        assert_eq!(a.displaced.map(|d| d.0), Some(Displaced::Rebound));
3035        assert_eq!(
3036            a.reports.iter().map(|r| r.change).collect::<Vec<_>>(),
3037            [Change::Resolved, Change::Firing]
3038        );
3039        let b = t.apply(Sample::Put(held(1, State::Firing, 4, 10)));
3040        assert_eq!(b.displaced.map(|d| d.0), Some(Displaced::Dropped));
3041        assert_eq!(
3042            b.reports.len(),
3043            1,
3044            "an earlier run's last word resolves nothing"
3045        );
3046        assert_eq!(t.apply(Sample::Delete).reads, Transition::Resolved);
3047        assert_eq!(t.held, None);
3048    }
3049
3050    #[test]
3051    fn one_complete_snapshot_establishes_an_owners_alarms_with_no_entry() {
3052        let listed = Presence::Present(super::super::Listing::Listed { token: false });
3053        let whole = Read::Complete(Some(SnapshotRead {
3054            complete: true,
3055            run: SnapshotRun::Stated,
3056        }));
3057        let set = owner_set(listed, Some(whole), None);
3058        assert_eq!(
3059            (set.verdict, set.reason),
3060            (SetVerdict::Established, Reason::Snapshot)
3061        );
3062        assert_eq!(
3063            owner_set(listed, Some(Read::Complete(None)), None).reason,
3064            Reason::SnapshotIncomplete,
3065            "no page is silence"
3066        );
3067        let r = Reading {
3068            presence: listed,
3069            freshness: None,
3070            latest: Some(Latest::Rebound),
3071            lost: false,
3072            previous_instance: false,
3073            held_whole: true,
3074            left_out: false,
3075        };
3076        assert_eq!(firing(&r), Judged::new(Answer::No, Reason::Rebound));
3077        assert_eq!(
3078            stale_firing(&r),
3079            Judged::new(Answer::NotAsked, Reason::NotFiring)
3080        );
3081    }
3082}