Skip to main content

zenkey_model/
redundancy.rs

1//! `redundancy`: one instance serves, the others stand by. `redundancy.v1`
2//! (`spec/profiles/redundancy/v1.md`, #841), and `redundancy.v2` (`v2.md`,
3//! #987's N1), which keeps v1's election whole and replaces its stamps:
4//! no session HLC, and a follower that fences by the incumbent's runs.
5//!
6//! The profile's session-free half: the declaration read from a contract
7//! (§2.2), how instance ids compare (§2.3), the descriptor's standby mark
8//! read and checked (§2.4, §2.14, core §3.3), the election's decision over
9//! one read (§2.5, §2.11), the heal's over two (§2.9), one candidate's
10//! election as a pure state machine, two-phase like
11//! [`crate::config::Owner`] (§2.5 to §2.11), and §5's four questions as
12//! judgements that never fold an unestablished answer into no (§2.15).
13//! Both majors share all of it: v2 restates §2.3 to §2.9 and §2.11 to §2.15
14//! by reference. What v2 replaces is beside it: its declaration
15//! ([`v2::declaration`]), a follower's read of a descriptor
16//! ([`read_descriptor`]), the fence over either major ([`Fence`]), the draw
17//! ([`draw_again`]), and an address's governance from its candidates'
18//! revisions of either major ([`governance`]).
19//!
20//! | Rule | Item |
21//! |---|---|
22//! | §2.2 the declaration: governed, the election, invalid | [`declaration`], [`declaration_of`], [`Declaration`], [`Invalid`] |
23//! | v2 §2.2 the declaration of either major, `majors`, `explicit_stream` | [`Major`], [`is_governed`], [`v2::declaration`], [`v2::declaration_of`], [`either_declaration_of`] |
24//! | v2 §2.2 a linter's warnings, either major | [`lint_contract`], [`Warning`] |
25//! | v2 §2.2, §2.15 an address's governance from its revisions | [`governance`], [`Revision`] |
26//! | v2 §2.10, §2.14 a follower's read of a descriptor: its run and the mark | [`read_descriptor`], [`DescriptorRead`] |
27//! | v2 §2.10 the fence by run, v1 §2.10's by zid, the hold for one read | [`Fence`], [`Holding`], [`Sample`], [`Fenced`], [`Discard`], [`Outcome`] |
28//! | observer §3.6 (0.38): a read never undoes a token heard since it was asked | [`Fence::ask`], [`Asked`], carried by [`Holding::Read`] |
29//! | v2 §2.10 a run no other states: the draw | [`draw_again`] |
30//! | §2.3 the claim set, the incumbent, ids compared | [`Read`], [`Seen`], [`Listing`], [`Read::holders`], [`lower`] |
31//! | §2.4, §2.14 the standby mark and its checks | [`Mark`], [`mark`], [`read_mark`], [`MarkFinding`] |
32//! | §2.5 the election under `claim` | [`elect`], [`Decision`], [`Why`] |
33//! | §2.6, §2.8 taking over, a vacancy | [`Elector`], [`Step::TakeOver`], [`Event::Withdrawn`] |
34//! | §2.7 following the address, what is heard while a read runs (0.2) | [`Event::Appeared`], [`Event::Withdrawn`] (the runtime's watch), kept by the [`Elector`] |
35//! | §2.7 a poll's reads compared with the last's (0.3) | [`poll`], [`Poll`] |
36//! | §2.9 healing a split, a heal read not complete (0.2) | [`heal`], [`Heal`], [`Step::StepDown`], [`Step::Retry`] |
37//! | §2.9 a candidate's own re-mint (0.2) | [`Event::Reminted`], [`Elector::is_own`] |
38//! | §2.11 `election = "external"` | [`Election::External`], [`Event::Lock`] |
39//! | §2.15, §5 what a tool concludes | [`one_incumbent`], [`vacancy`], [`standbys`], [`twin`] |
40//!
41//! ```text
42//! declaration(uses, annotations, tokenless) ─▶ governed {claim│external} │ invalid [reasons] │ not governed   §2.2
43//! read_mark(entry json, governance)        ─▶ standby │ serving │ malformed, with findings                  §2.4, §2.14
44//! elect(own, read)                         ─▶ take over │ stand by {incumbent, incomplete, own claim missing,
45//!                                               descriptor unread, lower candidate}                      §2.5
46//! heal(own, election, first, second)       ─▶ step down {lower holder} │ stay {external, not holding,
47//!                                               no split, lowest}                                        §2.9
48//! Elector::start / observe(event) / finish ─▶ claim │ read │ grace │ retry │ stand by │ take over │ step down │ nothing
49//! one_incumbent / vacancy / standbys / twin ─▶ §5's questions, in five states                            §2.15
50//! ```
51//!
52//! There is no I/O and no clock here. A candidate's runtime declares what
53//! [`Step::Claim`] says, makes each read [`Step::Read`] asks for and hands
54//! it back as [`Event::Read`], arms the retry timer when a
55//! [`Step::StandBy`] says `retry` or on a [`Step::Retry`], and the grace
56//! timer on [`Step::Grace`], hands each to [`Elector::observe`] as
57//! [`Event::Timer`], tells it what its watch hears ([`Event::Appeared`],
58//! [`Event::Withdrawn`]), its own re-mint ([`Event::Reminted`]) and, under
59//! `external`, its lock ([`Event::Lock`]); after a [`Step::Claim`], a
60//! [`Step::TakeOver`] or a [`Step::StepDown`] it acts, in core §8.2's order
61//! or its reverse, then calls [`Elector::finish`].
62
63use std::collections::BTreeSet;
64use std::fmt;
65
66use serde_json::Value;
67
68use crate::contract::Contract;
69use crate::descriptor::InterfaceEntry;
70use crate::grammar::{IfaceId, InstanceId, KindToken};
71use crate::wire::Run;
72
73mod fence;
74pub mod v2;
75
76pub(crate) use fence::Heard;
77pub use fence::{Asked, Described, Discard, Fence, Fenced, Holding, Member, Outcome, Sample};
78
79/// `redundancy.v1`'s id, as a contract lists it in `uses`.
80pub const PROFILE: &str = "redundancy.v1";
81
82/// The profile's name, as an annotation key's prefix carries it.
83pub const NAME: &str = "redundancy";
84
85/// `redundancy.election` (§4).
86pub const ELECTION: &str = "redundancy.election";
87
88/// The published vocabulary (§4): the keys under `redundancy.`, which W105
89/// reads in place of core Appendix D's interim row (core 0.39), the same
90/// key.
91pub const VOCABULARY: &[&str] = &["election"];
92
93/// A major of the profile (v2 §2.17). The election is one text, which both
94/// share; each candidate stamps, answers a GET and is followed as its own
95/// revision's major says.
96#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
97pub enum Major {
98    /// `redundancy.v1`: the candidate's session stamps every write, and a
99    /// follower reads the stamp's id against `meta.zid` (v1 §2.10).
100    V1,
101    /// `redundancy.v2`: no session stamp, and a follower reads the run its
102    /// descriptors state (v2 §2.10).
103    V2,
104}
105
106impl Major {
107    /// Both, in order.
108    pub const ALL: [Major; 2] = [Major::V1, Major::V2];
109
110    /// The major's id, as a contract lists it in `uses`.
111    #[must_use]
112    pub const fn profile(self) -> &'static str {
113        match self {
114            Major::V1 => PROFILE,
115            Major::V2 => v2::PROFILE,
116        }
117    }
118
119    /// The major's number.
120    #[must_use]
121    pub const fn number(self) -> u32 {
122        match self {
123            Major::V1 => 1,
124            Major::V2 => 2,
125        }
126    }
127
128    /// The major numbered `n`, `None` for any this crate does not read.
129    #[must_use]
130    pub const fn from_number(n: u32) -> Option<Major> {
131        match n {
132            1 => Some(Major::V1),
133            2 => Some(Major::V2),
134            _ => None,
135        }
136    }
137
138    /// The major a contract's `uses` is read by, as a reader of both reads
139    /// it (v2 §2.2): `redundancy.v2` where it lists it, `redundancy.v1`
140    /// where it lists that and not `redundancy.v2`, `None` where it lists
141    /// neither. One that lists both is `redundancy.v2`'s, which reads it
142    /// `majors`.
143    #[must_use]
144    pub fn of<'a>(uses: impl IntoIterator<Item = &'a IfaceId>) -> Option<Major> {
145        let mut found = None;
146        for u in uses {
147            if u.name() != NAME {
148                continue;
149            }
150            match Major::from_number(u.major()) {
151                Some(Major::V2) => return Some(Major::V2),
152                Some(Major::V1) => found = Some(Major::V1),
153                None => {}
154            }
155        }
156        found
157    }
158}
159
160impl fmt::Display for Major {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        f.write_str(self.profile())
163    }
164}
165
166// --- §2.2: the declaration -----------------------------------------------------
167
168/// How a governed interface's serving instance is chosen (§4).
169#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
170pub enum Election {
171    /// This profile's protocol (§2.5 to §2.9), the default.
172    Claim,
173    /// A lock outside the bus (§2.11).
174    External,
175}
176
177impl Election {
178    /// The vocabulary's value, and the fixture's token.
179    #[must_use]
180    pub fn as_str(self) -> &'static str {
181        match self {
182            Self::Claim => "claim",
183            Self::External => "external",
184        }
185    }
186
187    /// Reads an annotation's value: the string `claim` or `external`, and
188    /// nothing else.
189    #[must_use]
190    pub fn parse(v: &Value) -> Option<Self> {
191        match v.as_str() {
192            Some("claim") => Some(Self::Claim),
193            Some("external") => Some(Self::External),
194            _ => None,
195        }
196    }
197}
198
199impl fmt::Display for Election {
200    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201        f.write_str(self.as_str())
202    }
203}
204
205/// Why a declaration is invalid (§2.2), in the order checked. `Majors` and
206/// `ExplicitStream` are `redundancy.v2`'s alone (v2 §2.2): the first before
207/// v1's four, the second after them.
208#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
209pub enum Invalid {
210    /// `uses` lists `redundancy.v2` and another major of the profile (v2
211    /// §2.2; core E002 to a linter). The interface is read as governed for
212    /// the checks after it.
213    Majors,
214    /// `redundancy.election` carried, and `uses` names no major of the
215    /// profile (core E020's).
216    NotUsed,
217    /// A value that is not the string `claim` or `external`.
218    Value,
219    /// Two resources resolve to two elections.
220    Disagrees,
221    /// The interface is governed, and the deployment's tokenless set names
222    /// it (§2.14).
223    Tokenless,
224    /// The interface is governed by `redundancy.v2`, and declares a
225    /// `stream` resource with `explicit = true`: its samples carry no
226    /// envelope, so no run a follower can fence (v2 §2.2).
227    ExplicitStream,
228}
229
230impl Invalid {
231    /// The fixture's token.
232    #[must_use]
233    pub fn as_str(self) -> &'static str {
234        match self {
235            Self::Majors => "majors",
236            Self::NotUsed => "not_used",
237            Self::Value => "value",
238            Self::Disagrees => "disagrees",
239            Self::Tokenless => "tokenless",
240            Self::ExplicitStream => "explicit_stream",
241        }
242    }
243
244    /// What it says, for a linter's line.
245    #[must_use]
246    pub fn says(self) -> &'static str {
247        match self {
248            Self::Majors => "uses lists redundancy.v2 and another major of redundancy",
249            Self::NotUsed => "redundancy.election is written, and uses does not list redundancy.v1",
250            Self::Value => "redundancy.election is the string claim or external",
251            Self::Disagrees => "every resource of a governed interface resolves to one election",
252            Self::Tokenless => {
253                "a governed interface is never tokenless: its incumbent is the holder of its token"
254            }
255            Self::ExplicitStream => {
256                "an explicit stream's samples carry no envelope, so no run a follower can fence: \
257                 a redundancy.v2 interface declares none"
258            }
259        }
260    }
261}
262
263impl fmt::Display for Invalid {
264    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265        f.write_str(self.says())
266    }
267}
268
269/// An interface's declaration (§2.2).
270#[derive(Debug, Clone, PartialEq, Eq)]
271pub enum Declaration {
272    /// `uses` lists no `redundancy.v1`: not this profile's.
273    NotGoverned,
274    /// The reasons, in the order checked.
275    Invalid(Vec<Invalid>),
276    /// Governed, with its election.
277    Governed(Election),
278}
279
280impl Declaration {
281    /// The fixture's token.
282    #[must_use]
283    pub fn as_str(&self) -> &'static str {
284        match self {
285            Self::NotGoverned => "not_governed",
286            Self::Invalid(_) => "invalid",
287            Self::Governed(_) => "governed",
288        }
289    }
290
291    /// The election of a valid declaration.
292    #[must_use]
293    pub fn election(&self) -> Option<Election> {
294        match self {
295            Self::Governed(e) => Some(*e),
296            _ => None,
297        }
298    }
299}
300
301/// Reads an interface's declaration as `redundancy.v1` alone reads it
302/// (§2.2; v1's `declarations.json`) from its contract's `uses`, the
303/// resolved annotations of each of its resources (core §9.3, in any
304/// order), and whether the deployment's tokenless set names it. Each check
305/// runs alone; a resource whose value is found wrong takes no part in
306/// `disagrees`, and one carrying none reads as `claim`. A contract listing
307/// `redundancy.v1` beside another major is v1's here; a reader of both
308/// majors reads it `majors` ([`either_declaration_of`]).
309#[must_use]
310pub fn declaration<'a, U, A>(uses: U, annotations: A, tokenless: bool) -> Declaration
311where
312    U: IntoIterator<Item = &'a IfaceId>,
313    A: IntoIterator<Item = &'a std::collections::BTreeMap<String, Value>>,
314{
315    let mut governed = false;
316    let mut another_major = false;
317    for u in uses {
318        if u.name() == NAME {
319            if u.major() == 1 {
320                governed = true;
321            } else {
322                another_major = true;
323            }
324        }
325    }
326    if another_major && !governed {
327        // Another major's text: its key is its own.
328        return Declaration::NotGoverned;
329    }
330    let values: Vec<Option<&Value>> = annotations.into_iter().map(|a| a.get(ELECTION)).collect();
331    let carried = values.iter().any(Option::is_some);
332    if !governed && !carried {
333        return Declaration::NotGoverned;
334    }
335    let mut why = Vec::new();
336    if !governed {
337        why.push(Invalid::NotUsed);
338    }
339    let election = elections(&values, &mut why);
340    if governed && tokenless {
341        why.push(Invalid::Tokenless);
342    }
343    if why.is_empty() {
344        Declaration::Governed(election)
345    } else {
346        Declaration::Invalid(why)
347    }
348}
349
350/// §2.2's `value` and `disagrees`, which both majors check alike, pushed
351/// onto `why` in that order: a resource carrying none reads as `claim`, and
352/// one found `value` takes no part in `disagrees`. Returns the one election
353/// the valid resources resolve to, `claim` with none.
354pub(crate) fn elections(values: &[Option<&Value>], why: &mut Vec<Invalid>) -> Election {
355    let mut elections = BTreeSet::new();
356    let mut wrong = false;
357    for v in values {
358        match v {
359            None => {
360                elections.insert(Election::Claim);
361            }
362            Some(v) => match Election::parse(v) {
363                Some(e) => {
364                    elections.insert(e);
365                }
366                None => wrong = true,
367            },
368        }
369    }
370    if wrong {
371        why.push(Invalid::Value);
372    }
373    if elections.len() > 1 {
374        why.push(Invalid::Disagrees);
375    }
376    elections.into_iter().next().unwrap_or(Election::Claim)
377}
378
379/// [`declaration`] of a contract, `tokenless` saying whether the
380/// deployment's tokenless set names its interface: `redundancy.v1`'s
381/// reading alone.
382#[must_use]
383pub fn declaration_of(c: &Contract, tokenless: bool) -> Declaration {
384    declaration(
385        &c.uses,
386        c.resources.iter().map(|r| &r.annotations),
387        tokenless,
388    )
389}
390
391/// A contract's declaration as a reader of both majors reads it (v2 §2.2):
392/// [`v2::declaration_of`] where its `uses` lists `redundancy.v2`, and
393/// [`declaration_of`], `redundancy.v1`'s, otherwise. The major of a
394/// governed one is [`Major::of`] its `uses`.
395#[must_use]
396pub fn either_declaration_of(c: &Contract, tokenless: bool) -> Declaration {
397    if Major::of(&c.uses) == Some(Major::V2) {
398        v2::declaration_of(c, tokenless)
399    } else {
400        declaration_of(c, tokenless)
401    }
402}
403
404/// Whether a contract governs its interface: its `uses` lists
405/// `redundancy.v1` or `redundancy.v2` (§2.2, v2 §2.2), governed by either
406/// major. [`Major::of`] says which.
407#[must_use]
408pub fn is_governed(c: &Contract) -> bool {
409    Major::of(&c.uses).is_some()
410}
411
412/// One finding a contract linter warns of (v1 §2.2, v2 §2.2): `value`,
413/// `disagrees`, and under `redundancy.v2` `explicit_stream`. Each is an
414/// invalid declaration, which a runtime refuses to start; the core has no
415/// code for any, so a linter warns. `majors` and `not_used` are core E002
416/// and E020, which refuse the contract's load, and `tokenless` is the
417/// deployment's, never the contract's.
418#[derive(Debug, Clone, PartialEq, Eq)]
419pub struct Warning {
420    /// The major whose text the reason is under.
421    pub major: Major,
422    /// The resource it is of, as [`crate::words::Lint::place`] names one,
423    /// or the interface id for `disagrees`.
424    pub at: String,
425    pub reason: Invalid,
426}
427
428impl fmt::Display for Warning {
429    /// A linter's line: `warning[<profile> <token>] <at>: <says>`.
430    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
431        write!(
432            f,
433            "warning[{} {}] {}: {}",
434            self.major.profile(),
435            self.reason.as_str(),
436            self.at,
437            self.reason.says()
438        )
439    }
440}
441
442/// A contract's declaration findings a linter warns of (v1 §2.2, v2 §2.2),
443/// read by the major [`Major::of`] its `uses` names: each resource whose
444/// `redundancy.election` is `value`, the interface once for `disagrees`,
445/// and each explicit stream of a `redundancy.v2` one. None for a contract
446/// governed by neither major.
447#[must_use]
448pub fn lint_contract(c: &Contract) -> Vec<Warning> {
449    let Some(major) = Major::of(&c.uses) else {
450        return Vec::new();
451    };
452    let Declaration::Invalid(why) = either_declaration_of(c, false) else {
453        return Vec::new();
454    };
455    let warn = |at: String, reason| Warning { major, at, reason };
456    let mut out = Vec::new();
457    for reason in why {
458        match reason {
459            Invalid::Value => out.extend(
460                c.resources
461                    .iter()
462                    .filter(|r| {
463                        r.annotations
464                            .get(ELECTION)
465                            .is_some_and(|v| Election::parse(v).is_none())
466                    })
467                    .map(|r| warn(crate::words::Lint::place(r), reason)),
468            ),
469            Invalid::Disagrees => out.push(warn(c.iface.to_string(), reason)),
470            Invalid::ExplicitStream => out.extend(
471                c.resources
472                    .iter()
473                    .filter(|r| r.token == KindToken::ExplicitStream)
474                    .map(|r| warn(crate::words::Lint::place(r), reason)),
475            ),
476            Invalid::Majors | Invalid::NotUsed | Invalid::Tokenless => {}
477        }
478    }
479    out
480}
481
482// --- §2.3: ids, the claim set, the incumbent ----------------------------------------
483
484/// Whether `a` is lower than `b` (§2.3): their 16 lowercase hexadecimal
485/// digits compared character by character, which is their order as
486/// unsigned 64-bit integers.
487#[must_use]
488pub fn lower(a: &InstanceId, b: &InstanceId) -> bool {
489    a.as_str() < b.as_str()
490}
491
492/// What an instance's descriptor says of the governed interface, as a read
493/// found it (§2.3).
494#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
495pub enum Listing {
496    /// Its descriptor was not read.
497    Unread,
498    /// It does not list the interface: no candidate.
499    NotListed,
500    /// It lists the interface, marked standby or not (core §3.3).
501    Listed { standby: bool },
502}
503
504impl Listing {
505    /// Whether the instance is a candidate (§2.3).
506    #[must_use]
507    pub fn lists(self) -> bool {
508        matches!(self, Self::Listed { .. })
509    }
510}
511
512/// One instance of the address, as a read found it.
513#[derive(Debug, Clone, PartialEq, Eq)]
514pub struct Seen {
515    pub id: InstanceId,
516    /// It holds the governed interface's token, at any revision.
517    pub token: bool,
518    pub descriptor: Listing,
519}
520
521/// One read of the address (§0): its instances, with their tokens and
522/// descriptors, and whether it is complete (core §8.1).
523#[derive(Debug, Clone, PartialEq, Eq, Default)]
524pub struct Read {
525    pub complete: bool,
526    pub instances: Vec<Seen>,
527}
528
529impl Read {
530    /// The incumbents: the instances holding the interface's token,
531    /// lowest first, each once (§2.3).
532    #[must_use]
533    pub fn holders(&self) -> Vec<&InstanceId> {
534        let set: BTreeSet<&InstanceId> = self
535            .instances
536            .iter()
537            .filter(|s| s.token)
538            .map(|s| &s.id)
539            .collect();
540        set.into_iter().collect()
541    }
542
543    /// What the read found of `id`, if it found it.
544    #[must_use]
545    pub fn get(&self, id: &InstanceId) -> Option<&Seen> {
546        self.instances.iter().find(|s| &s.id == id)
547    }
548
549    fn holders_owned(&self) -> Vec<InstanceId> {
550        self.holders().into_iter().cloned().collect()
551    }
552}
553
554// --- §2.4, §2.14: the standby mark ------------------------------------------------
555
556/// What an interface entry says the instance does with the interface (core
557/// §3.3, 0.39).
558#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
559pub enum Mark {
560    /// Unmarked: it serves the interface, or claims to.
561    Serving,
562    /// `"standby": true`: it exposes nothing of it and holds none of its
563    /// tokens (core §6).
564    Standby,
565}
566
567impl Mark {
568    /// The fixture's token.
569    #[must_use]
570    pub fn as_str(self) -> &'static str {
571        match self {
572            Self::Serving => "serving",
573            Self::Standby => "standby",
574        }
575    }
576}
577
578/// The mark of a parsed entry.
579#[must_use]
580pub fn mark(e: &InterfaceEntry) -> Mark {
581    if e.standby {
582        Mark::Standby
583    } else {
584        Mark::Serving
585    }
586}
587
588/// What a reader knows of an interface's governance (§2.15 premise 3).
589#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
590pub enum Governance {
591    /// Governed, by contracts read and agreeing, with their election.
592    Governed(Election),
593    /// No candidate's contract uses the profile: not this profile's.
594    NotGoverned,
595    /// A candidate's contract was not read.
596    NoContract,
597    /// The candidates' revisions disagree on governance or the election
598    /// (§2.2).
599    Disagree,
600}
601
602impl Governance {
603    /// The fixture's token.
604    #[must_use]
605    pub fn as_str(self) -> &'static str {
606        match self {
607            Self::Governed(e) => e.as_str(),
608            Self::NotGoverned => "not_governed",
609            Self::NoContract => "no_contract",
610            Self::Disagree => "disagree",
611        }
612    }
613
614    /// Reads a fixture's token.
615    #[must_use]
616    pub fn parse(s: &str) -> Option<Self> {
617        match s {
618            "claim" => Some(Self::Governed(Election::Claim)),
619            "external" => Some(Self::Governed(Election::External)),
620            "not_governed" => Some(Self::NotGoverned),
621            "no_contract" => Some(Self::NoContract),
622            "disagree" => Some(Self::Disagree),
623            _ => None,
624        }
625    }
626}
627
628/// What a reader finds of an entry's mark (§2.14), in this order.
629#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
630pub enum MarkFinding {
631    /// `standby` or `token` present and not a boolean, or the entry not an
632    /// object: not the record's shape (core D000). Nothing else is read.
633    Malformed,
634    /// Marked `"standby": true` and `"token": false` (core D012).
635    StandbyTokenless,
636    /// Marked `"token": false`, the interface governed (§2.14).
637    GovernedTokenless,
638    /// Marked standby, the interface not governed: the mark says what core
639    /// §6 says, and none of §5's questions is this profile's.
640    NotGoverned,
641}
642
643impl MarkFinding {
644    /// The fixture's token.
645    #[must_use]
646    pub fn as_str(self) -> &'static str {
647        match self {
648            Self::Malformed => "malformed",
649            Self::StandbyTokenless => "standby_tokenless",
650            Self::GovernedTokenless => "governed_tokenless",
651            Self::NotGoverned => "not_governed",
652        }
653    }
654}
655
656/// An entry's mark, `None` when it is malformed, and the findings.
657#[derive(Debug, Clone, PartialEq, Eq)]
658pub struct MarkRead {
659    pub mark: Option<Mark>,
660    pub findings: Vec<MarkFinding>,
661}
662
663/// Reads the mark of an interface entry as JSON (core §3.3, §2.14):
664/// `standby` absent is serving, `token` absent is `true`.
665#[must_use]
666pub fn read_mark(entry: &Value, governance: Governance) -> MarkRead {
667    let malformed = MarkRead {
668        mark: None,
669        findings: vec![MarkFinding::Malformed],
670    };
671    let Some(o) = entry.as_object() else {
672        return malformed;
673    };
674    let flag = |name: &str, absent: bool| match o.get(name) {
675        None => Some(absent),
676        Some(Value::Bool(b)) => Some(*b),
677        Some(_) => None,
678    };
679    let (Some(standby), Some(token)) = (flag("standby", false), flag("token", true)) else {
680        return malformed;
681    };
682    let mut findings = Vec::new();
683    if standby && !token {
684        findings.push(MarkFinding::StandbyTokenless);
685    }
686    if matches!(governance, Governance::Governed(_)) && !token {
687        findings.push(MarkFinding::GovernedTokenless);
688    }
689    if standby && governance == Governance::NotGoverned {
690        findings.push(MarkFinding::NotGoverned);
691    }
692    MarkRead {
693        mark: Some(if standby {
694            Mark::Standby
695        } else {
696            Mark::Serving
697        }),
698        findings,
699    }
700}
701
702/// What a follower reads of one descriptor (v2 §2.10, §2.14;
703/// `v2/descriptors.json`): the instance's run, and the governed
704/// interface's entry, its mark and the findings.
705#[derive(Debug, Clone, PartialEq, Eq)]
706pub struct DescriptorRead {
707    /// The run the descriptor states, `None` where it states none or
708    /// spells it otherwise than 4 or 8 lowercase hexadecimal digits (core
709    /// D000, D002): the follower then holds no run from it. Read whatever
710    /// the governance and the listing.
711    pub run: Option<Run>,
712    /// Whether an entry of `interfaces` is the interface's. An entry that
713    /// is not an object is read as the interface's, malformed.
714    pub listed: bool,
715    /// The entry's mark ([`read_mark`]), `None` unlisted or malformed.
716    pub mark: Option<Mark>,
717    /// [`read_mark`]'s findings, none unlisted.
718    pub findings: Vec<MarkFinding>,
719}
720
721/// Reads a descriptor, as JSON, for the interface `iface` whose governance
722/// the reader knows as `governance` (v2 §2.10, §2.14): its run, and the
723/// first entry of `interfaces` that is `iface`'s or is not an object, read
724/// by [`read_mark`]. `meta.zid` is not read: `redundancy.v2`'s fence reads
725/// no zid.
726#[must_use]
727pub fn read_descriptor(descriptor: &Value, iface: &str, governance: Governance) -> DescriptorRead {
728    let run = descriptor
729        .get("run")
730        .and_then(Value::as_str)
731        .and_then(Run::from_hex);
732    let entry = descriptor
733        .get("interfaces")
734        .and_then(Value::as_array)
735        .into_iter()
736        .flatten()
737        .find(|e| {
738            e.as_object()
739                .is_none_or(|o| o.get("iface").and_then(Value::as_str) == Some(iface))
740        });
741    match entry {
742        Some(e) => {
743            let m = read_mark(e, governance);
744            DescriptorRead {
745                run,
746                listed: true,
747                mark: m.mark,
748                findings: m.findings,
749            }
750        }
751        None => DescriptorRead {
752            run,
753            listed: false,
754            mark: None,
755            findings: Vec::new(),
756        },
757    }
758}
759
760/// Whether a candidate draws a new run before it serves (v2 §2.10, a
761/// SHOULD): its own run, by width and value, is among the runs it read in
762/// other instances' descriptors of its address. A new run is core §4.3's:
763/// the candidate puts its descriptor again before it writes under it.
764#[must_use]
765pub fn draw_again(own: Run, read: impl IntoIterator<Item = Run>) -> bool {
766    read.into_iter().any(|r| r == own)
767}
768
769/// What one candidate's revision of the interface declares, as a tool
770/// reads it for an address's governance (v2 §2.2 "Across revisions",
771/// §2.15; `v2/declarations.json`'s `addresses`).
772#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
773pub enum Revision {
774    /// Governed by `major`, with its election.
775    Governed(Major, Election),
776    NotGoverned,
777    /// Invalid: it gives no election.
778    Invalid,
779    /// Its contract not read.
780    Unread,
781}
782
783impl Revision {
784    /// The revision of `c`, as a reader of both majors reads it
785    /// ([`either_declaration_of`], no tokenless set).
786    #[must_use]
787    pub fn of(c: &Contract) -> Revision {
788        match (either_declaration_of(c, false), Major::of(&c.uses)) {
789            (Declaration::Governed(e), Some(m)) => Revision::Governed(m, e),
790            (Declaration::Governed(_) | Declaration::NotGoverned, _) => Revision::NotGoverned,
791            (Declaration::Invalid(_), _) => Revision::Invalid,
792        }
793    }
794}
795
796/// The governance a tool reads of an address from the revisions its
797/// candidates' descriptors name, one entry a revision (v2 §2.2, §2.15):
798/// `no_contract` where none is given, or one is unread or invalid; else
799/// `not_governed` where none is governed; else `disagree` where one is not
800/// governed, or the governed ones give two elections; else their one
801/// election. The major of a governed revision takes no part: a
802/// `redundancy.v1` candidate and a `redundancy.v2` one with one election
803/// are one election.
804#[must_use]
805pub fn governance(revisions: impl IntoIterator<Item = Revision>) -> Governance {
806    let mut any = false;
807    let mut elections = BTreeSet::new();
808    let mut not_governed = false;
809    for r in revisions {
810        any = true;
811        match r {
812            Revision::Unread | Revision::Invalid => return Governance::NoContract,
813            Revision::NotGoverned => not_governed = true,
814            Revision::Governed(_, e) => {
815                elections.insert(e);
816            }
817        }
818    }
819    if !any {
820        return Governance::NoContract;
821    }
822    match (elections.len(), not_governed) {
823        (0, _) => Governance::NotGoverned,
824        (1, false) => Governance::Governed(*elections.iter().next().expect("one")),
825        _ => Governance::Disagree,
826    }
827}
828
829// --- §2.5, §2.11: the election over one read -----------------------------------------
830
831/// Why an instance stands by (§2.5, §2.11).
832#[derive(Debug, Clone, PartialEq, Eq, Hash)]
833pub enum Why {
834    /// Another instance holds the interface's token: a live incumbent wins.
835    Incumbent(InstanceId),
836    /// The read was not complete.
837    Incomplete,
838    /// The read did not show the instance's own claim.
839    OwnClaimMissing,
840    /// A lower instance's descriptor was not read.
841    DescriptorUnread(InstanceId),
842    /// A lower candidate is in the claim set.
843    LowerCandidate(InstanceId),
844    /// `external`: the instance does not hold the lock.
845    NoLock,
846}
847
848impl Why {
849    /// The fixture's token.
850    #[must_use]
851    pub fn as_str(&self) -> &'static str {
852        match self {
853            Self::Incumbent(_) => "incumbent",
854            Self::Incomplete => "incomplete",
855            Self::OwnClaimMissing => "own_claim_missing",
856            Self::DescriptorUnread(_) => "descriptor_unread",
857            Self::LowerCandidate(_) => "lower_candidate",
858            Self::NoLock => "no_lock",
859        }
860    }
861
862    /// The instance it names, if it names one.
863    #[must_use]
864    pub fn instance(&self) -> Option<&InstanceId> {
865        match self {
866            Self::Incumbent(i) | Self::DescriptorUnread(i) | Self::LowerCandidate(i) => Some(i),
867            Self::Incomplete | Self::OwnClaimMissing | Self::NoLock => None,
868        }
869    }
870
871    /// Whether the instance campaigns again after its retry interval
872    /// (§2.5): when it saw no incumbent, whose withdrawal its watch would
873    /// hear, and holds its lock where one elects.
874    #[must_use]
875    pub fn retries(&self) -> bool {
876        !matches!(self, Self::Incumbent(_) | Self::NoLock)
877    }
878}
879
880/// What one read decides (§2.5).
881#[derive(Debug, Clone, PartialEq, Eq)]
882pub enum Decision {
883    TakeOver,
884    StandBy(Why),
885}
886
887impl Decision {
888    /// The fixture's token.
889    #[must_use]
890    pub fn as_str(&self) -> &'static str {
891        match self {
892            Self::TakeOver => "take_over",
893            Self::StandBy(_) => "stand_by",
894        }
895    }
896}
897
898/// §2.5 steps 2 and 3's first two conditions, shared by both elections:
899/// an incumbent, then the read's completeness and the instance's own claim.
900fn premises(own: &InstanceId, read: &Read) -> Option<Why> {
901    if let Some(h) = read.holders().into_iter().find(|h| *h != own) {
902        return Some(Why::Incumbent(h.clone()));
903    }
904    if !read.complete {
905        return Some(Why::Incomplete);
906    }
907    if read.get(own).is_none() {
908        return Some(Why::OwnClaimMissing);
909    }
910    None
911}
912
913/// What a candidate whose election is `claim` does with one read (§2.5,
914/// steps 2 to 4): stand by for a live incumbent, whatever the read's
915/// completeness; for a read not complete, or missing its own claim; for
916/// the lowest instance below its own that lists the interface (a lower
917/// candidate) or whose descriptor was not read; and otherwise take over.
918#[must_use]
919pub fn elect(own: &InstanceId, read: &Read) -> Decision {
920    if let Some(why) = premises(own, read) {
921        return Decision::StandBy(why);
922    }
923    let lowest = read
924        .instances
925        .iter()
926        .filter(|s| lower(&s.id, own) && s.descriptor != Listing::NotListed)
927        .min_by(|a, b| a.id.cmp(&b.id));
928    match lowest {
929        Some(s) if s.descriptor == Listing::Unread => {
930            Decision::StandBy(Why::DescriptorUnread(s.id.clone()))
931        }
932        Some(s) => Decision::StandBy(Why::LowerCandidate(s.id.clone())),
933        None => Decision::TakeOver,
934    }
935}
936
937/// What a candidate whose election is `external`, holding its lock, does
938/// with one read (§2.11): §2.5's step 2 and step 3's first two conditions,
939/// never step 4, since the lock decided.
940#[must_use]
941pub fn elect_external(own: &InstanceId, read: &Read) -> Decision {
942    match premises(own, read) {
943        Some(why) => Decision::StandBy(why),
944        None => Decision::TakeOver,
945    }
946}
947
948// --- §2.9: the heal ------------------------------------------------------------------
949
950/// Why an incumbent stays (§2.9).
951#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
952pub enum Stay {
953    /// `external`: never by this rule (§2.11).
954    External,
955    /// It holds no token in the second read.
956    NotHolding,
957    /// Fewer than two holders in one of the reads: no split.
958    NoSplit,
959    /// It is the lowest holder of the second read.
960    Lowest,
961}
962
963impl Stay {
964    /// The fixture's token.
965    #[must_use]
966    pub fn as_str(self) -> &'static str {
967        match self {
968            Self::External => "external",
969            Self::NotHolding => "not_holding",
970            Self::NoSplit => "no_split",
971            Self::Lowest => "lowest",
972        }
973    }
974}
975
976/// What two reads a grace apart decide for an incumbent (§2.9).
977#[derive(Debug, Clone, PartialEq, Eq)]
978pub enum Heal {
979    /// Step down: the second read shows this lower holder.
980    StepDown(InstanceId),
981    Stay(Stay),
982}
983
984/// Decides a heal for `own` from the holders of two reads a grace apart,
985/// `first` then `second` (§2.9): under `claim`, an incumbent of a split,
986/// two or more holders in both reads, steps down when the second read
987/// shows a holder lower than itself. A read's completeness plays no part: a
988/// read cannot invent a holder.
989#[must_use]
990pub fn heal(
991    own: &InstanceId,
992    election: Election,
993    first: &[InstanceId],
994    second: &[InstanceId],
995) -> Heal {
996    if election == Election::External {
997        return Heal::Stay(Stay::External);
998    }
999    let first: BTreeSet<&InstanceId> = first.iter().collect();
1000    let second: BTreeSet<&InstanceId> = second.iter().collect();
1001    if !second.contains(own) {
1002        return Heal::Stay(Stay::NotHolding);
1003    }
1004    if first.len() < 2 || second.len() < 2 {
1005        return Heal::Stay(Stay::NoSplit);
1006    }
1007    match second.into_iter().next() {
1008        Some(low) if lower(low, own) => Heal::StepDown(low.clone()),
1009        _ => Heal::Stay(Stay::Lowest),
1010    }
1011}
1012
1013// --- §2.7: a poll ----------------------------------------------------------------------
1014
1015/// What one read of a poll found, compared with the last's (§2.7; text
1016/// 0.3, F-215).
1017#[derive(Debug, Clone, Default, PartialEq, Eq)]
1018pub struct Poll {
1019    /// The holders it shows that the last's did not: appearances.
1020    pub appeared: Vec<InstanceId>,
1021    /// The last's holders it shows gone, a complete read only:
1022    /// withdrawals.
1023    pub withdrawn: Vec<InstanceId>,
1024    /// What the next read is compared with: a complete read's holders, or,
1025    /// from a read not complete, the last's with the new ones added, since
1026    /// it removes none.
1027    pub next: BTreeSet<InstanceId>,
1028}
1029
1030/// One read of a poll compared with `last`, the holders the read before it
1031/// left (§2.7; text 0.3, F-215): a holder it shows that is new is an
1032/// appearance, and only a complete read can show one gone, so a read not
1033/// complete removes no holder from the last's. The first read is compared
1034/// with no holder.
1035#[must_use]
1036pub fn poll(last: &BTreeSet<InstanceId>, complete: bool, holders: &BTreeSet<InstanceId>) -> Poll {
1037    let appeared = holders.difference(last).cloned().collect();
1038    if complete {
1039        Poll {
1040            appeared,
1041            withdrawn: last.difference(holders).cloned().collect(),
1042            next: holders.clone(),
1043        }
1044    } else {
1045        Poll {
1046            appeared,
1047            withdrawn: Vec::new(),
1048            next: last.union(holders).cloned().collect(),
1049        }
1050    }
1051}
1052
1053// --- §2.5 to §2.11: one candidate's election -----------------------------------------
1054
1055/// What the runtime tells an [`Elector`].
1056#[derive(Debug, Clone, PartialEq, Eq)]
1057pub enum Event {
1058    /// The read a [`Step::Read`] asked for (§2.5, §2.8, §2.9).
1059    Read(Read),
1060    /// The watch heard an interface token of the interface appear at the
1061    /// address, held by this instance (§2.7, §2.9).
1062    Appeared(InstanceId),
1063    /// The watch heard the address's interface tokens withdrawn, leaving
1064    /// none held: one event for a burst (§2.8).
1065    Withdrawn,
1066    /// The timer the last step armed fired: the retry interval, or the
1067    /// grace.
1068    Timer,
1069    /// `external`: the deployment's lock taken (`true`) or lost (§2.11).
1070    Lock(bool),
1071    /// The candidate's own re-mint (core §1.5, §8.1; text 0.2, F-209): the
1072    /// new id is its own from then on, and every former id is its own,
1073    /// never another holder or another candidate. The runtime tells it
1074    /// before the new id's token is declared, in every state.
1075    Reminted(InstanceId),
1076}
1077
1078/// Why an incumbent steps down (§2.9, §2.11).
1079#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1080pub enum StepDownWhy {
1081    /// Under `claim`, a split whose second read shows this lower holder.
1082    LowerHolder(InstanceId),
1083    /// Under `external`, the lock lost.
1084    LockLost,
1085}
1086
1087impl StepDownWhy {
1088    /// The fixture's token.
1089    #[must_use]
1090    pub fn as_str(&self) -> &'static str {
1091        match self {
1092            Self::LowerHolder(_) => "lower_holder",
1093            Self::LockLost => "lock_lost",
1094        }
1095    }
1096}
1097
1098/// What an [`Elector`] asks its runtime to do.
1099#[derive(Debug, Clone, PartialEq, Eq)]
1100pub enum Step {
1101    /// Put the descriptor, the interface marked standby, declare the
1102    /// instance token and the watch with its round trip (§2.5 step 1,
1103    /// §2.7), then call [`Elector::finish`].
1104    Claim,
1105    /// Make one read of the address (§0), then hand it back as
1106    /// [`Event::Read`].
1107    Read,
1108    /// Arm the grace timer, then hand it back as [`Event::Timer`] (§2.9).
1109    Grace,
1110    /// Stand by (§2.4), following the address; arm the retry timer when
1111    /// `retry` (§2.5).
1112    StandBy { why: Why, retry: bool },
1113    /// Serving, arm the retry timer, then hand it back as [`Event::Timer`]:
1114    /// a heal's read not complete showing fewer than two holders, which
1115    /// ends nothing (§2.9; text 0.2, F-199).
1116    Retry,
1117    /// Take over in core §8.2's order (§2.6), then call
1118    /// [`Elector::finish`].
1119    TakeOver,
1120    /// Step down in the reverse order (§2.9), then call
1121    /// [`Elector::finish`].
1122    StepDown(StepDownWhy),
1123    /// Nothing to do.
1124    Nothing,
1125}
1126
1127impl Step {
1128    /// The fixture's token.
1129    #[must_use]
1130    pub fn as_str(&self) -> &'static str {
1131        match self {
1132            Self::Claim => "claim",
1133            Self::Read => "read",
1134            Self::Grace => "grace",
1135            Self::StandBy { .. } => "stand_by",
1136            Self::Retry => "retry",
1137            Self::TakeOver => "take_over",
1138            Self::StepDown(_) => "step_down",
1139            Self::Nothing => "nothing",
1140        }
1141    }
1142}
1143
1144/// What the instance's descriptor says of the interface now.
1145#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1146pub enum Role {
1147    /// Not claimed yet.
1148    Unclaimed,
1149    /// Marked standby: campaigning, standing by, or taking over.
1150    Standby,
1151    /// Serving: an incumbent, healing, or stepping down.
1152    Serving,
1153}
1154
1155impl Role {
1156    /// The fixture's token.
1157    #[must_use]
1158    pub fn as_str(self) -> &'static str {
1159        match self {
1160            Self::Unclaimed => "unclaimed",
1161            Self::Standby => "standby",
1162            Self::Serving => "serving",
1163        }
1164    }
1165}
1166
1167#[derive(Debug, Clone, PartialEq, Eq)]
1168enum Phase {
1169    New,
1170    Claiming,
1171    Campaigning,
1172    Standby {
1173        retry: bool,
1174    },
1175    TakingOver,
1176    Serving,
1177    HealFirst,
1178    HealGrace(Vec<InstanceId>),
1179    HealSecond(Vec<InstanceId>),
1180    /// A heal read not complete showing fewer than two holders: read again
1181    /// after the retry interval, the second read again when the first is
1182    /// held (F-199).
1183    HealRetry(Option<Vec<InstanceId>>),
1184    SteppingDown(StepDownWhy),
1185}
1186
1187/// What the watch heard while a read was asked or an act ran, kept to be
1188/// decided once it ends (text 0.2, F-199).
1189#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1190struct Kept {
1191    appeared: bool,
1192    withdrawn: bool,
1193}
1194
1195/// One candidate's election on one governed interface (§2.5 to §2.11): a
1196/// pure state machine, two-phase like [`crate::config::Owner`]. A restart
1197/// is a new `Elector`, and a new instance id; a re-mint in the same run is
1198/// [`Event::Reminted`].
1199///
1200/// **What is heard meanwhile is kept** (text 0.2, F-199). An appearance of
1201/// another holder's token, or a withdrawal, heard while a read is asked
1202/// (campaigning or healing) or while an act runs (taking over or stepping
1203/// down) is kept, and decided once the read's decision or the act's finish
1204/// is made, as if heard then, in the state it leaves: an appearance kept
1205/// through a takeover reads for a heal once it serves, a withdrawal kept
1206/// past a stand-by on an incumbent reads again, one kept through a
1207/// step-down campaigns once it stands by (under `external`, only with the
1208/// lock, F-207). A timer or a read nothing waits for is ignored.
1209#[derive(Debug, Clone)]
1210pub struct Elector {
1211    own: InstanceId,
1212    /// Its own former ids, after a re-mint (F-209).
1213    former: BTreeSet<InstanceId>,
1214    election: Election,
1215    phase: Phase,
1216    lock: bool,
1217    kept: Kept,
1218}
1219
1220impl Elector {
1221    /// An instance `own` of an interface whose election is `election`,
1222    /// before its claim. Under `external`, it holds no lock until told.
1223    #[must_use]
1224    pub fn new(own: InstanceId, election: Election) -> Self {
1225        Self {
1226            own,
1227            former: BTreeSet::new(),
1228            election,
1229            phase: Phase::New,
1230            lock: false,
1231            kept: Kept::default(),
1232        }
1233    }
1234
1235    /// This instance's id: the last one it was told of (F-209).
1236    #[must_use]
1237    pub fn own(&self) -> &InstanceId {
1238        &self.own
1239    }
1240
1241    /// Whether `id` is this instance's: its id, or one it held before a
1242    /// re-mint (F-209).
1243    #[must_use]
1244    pub fn is_own(&self, id: &InstanceId) -> bool {
1245        *id == self.own || self.former.contains(id)
1246    }
1247
1248    /// The interface's election.
1249    #[must_use]
1250    pub fn election(&self) -> Election {
1251        self.election
1252    }
1253
1254    /// What its descriptor says now.
1255    #[must_use]
1256    pub fn role(&self) -> Role {
1257        match self.phase {
1258            Phase::New | Phase::Claiming => Role::Unclaimed,
1259            Phase::Campaigning | Phase::Standby { .. } | Phase::TakingOver => Role::Standby,
1260            Phase::Serving
1261            | Phase::HealFirst
1262            | Phase::HealGrace(_)
1263            | Phase::HealSecond(_)
1264            | Phase::HealRetry(_)
1265            | Phase::SteppingDown(_) => Role::Serving,
1266        }
1267    }
1268
1269    /// Whether it serves the interface: an incumbent, which its role says.
1270    #[must_use]
1271    pub fn serving(&self) -> bool {
1272        self.role() == Role::Serving
1273    }
1274
1275    /// Whether it holds the lock, as last told (`external`).
1276    #[must_use]
1277    pub fn lock(&self) -> bool {
1278        self.lock
1279    }
1280
1281    /// Starts: claim before reading (§2.5 step 1). Called once.
1282    pub fn start(&mut self) -> Step {
1283        if self.phase != Phase::New {
1284            return Step::Nothing;
1285        }
1286        self.phase = Phase::Claiming;
1287        Step::Claim
1288    }
1289
1290    /// The act a [`Step::Claim`], a [`Step::TakeOver`] or a
1291    /// [`Step::StepDown`] asked for is done: the next step.
1292    pub fn finish(&mut self) -> Step {
1293        let step = match std::mem::replace(&mut self.phase, Phase::New) {
1294            Phase::Claiming => {
1295                // Nothing is kept before the claim's end: the first read
1296                // asks the bus whole.
1297                self.kept = Kept::default();
1298                return self.campaign();
1299            }
1300            Phase::TakingOver => {
1301                self.phase = Phase::Serving;
1302                match self.election {
1303                    Election::External if !self.lock => {
1304                        self.kept = Kept::default();
1305                        return self.step_down(StepDownWhy::LockLost);
1306                    }
1307                    _ => Step::Nothing,
1308                }
1309            }
1310            Phase::SteppingDown(_) => {
1311                self.phase = Phase::Standby { retry: false };
1312                Step::Nothing
1313            }
1314            other => {
1315                self.phase = other;
1316                return Step::Nothing;
1317            }
1318        };
1319        self.decide_kept(step)
1320    }
1321
1322    /// Hands it an event: the next step.
1323    pub fn observe(&mut self, event: Event) -> Step {
1324        match event {
1325            Event::Read(r) => {
1326                let r = self.normalized(&r);
1327                self.on_read(&r)
1328            }
1329            Event::Appeared(id) => {
1330                if self.is_own(&id) {
1331                    return Step::Nothing;
1332                }
1333                self.on_appeared()
1334            }
1335            Event::Withdrawn => self.on_withdrawn(),
1336            Event::Timer => self.on_timer(),
1337            Event::Lock(held) => self.on_lock(held),
1338            Event::Reminted(id) => {
1339                // F-209: no appearance, no step; the new id is its own from
1340                // here on, the old one too.
1341                if id != self.own {
1342                    let old = std::mem::replace(&mut self.own, id);
1343                    self.former.insert(old);
1344                    // A re-mint back to a former id: that id is its own
1345                    // again, never a former one beside itself.
1346                    self.former.remove(&self.own);
1347                }
1348                Step::Nothing
1349            }
1350        }
1351    }
1352
1353    /// A read with every former id of its own read as its own (F-209): one
1354    /// entry, holding the token when any of them does.
1355    fn normalized(&self, r: &Read) -> Read {
1356        if self.former.is_empty() {
1357            return r.clone();
1358        }
1359        let mut instances = Vec::with_capacity(r.instances.len());
1360        let mut own: Option<Seen> = None;
1361        for s in &r.instances {
1362            if !self.is_own(&s.id) {
1363                instances.push(s.clone());
1364                continue;
1365            }
1366            match &mut own {
1367                None => {
1368                    own = Some(Seen {
1369                        id: self.own.clone(),
1370                        token: s.token,
1371                        descriptor: s.descriptor,
1372                    });
1373                }
1374                Some(o) => {
1375                    o.token |= s.token;
1376                    if s.id == self.own {
1377                        o.descriptor = s.descriptor;
1378                    }
1379                }
1380            }
1381        }
1382        instances.extend(own);
1383        Read {
1384            complete: r.complete,
1385            instances,
1386        }
1387    }
1388
1389    /// Decides what was kept, in the state `step` leaves (F-199): the
1390    /// first kept event that asks something replaces a step that is no act
1391    /// (a stand-by, nothing); an act keeps what its own phase keeps.
1392    fn decide_kept(&mut self, step: Step) -> Step {
1393        fn replace(step: &mut Step, next: Step) {
1394            if next != Step::Nothing && matches!(step, Step::Nothing | Step::StandBy { .. }) {
1395                *step = next;
1396            }
1397        }
1398        let kept = std::mem::take(&mut self.kept);
1399        let mut step = step;
1400        if kept.appeared {
1401            let next = self.on_appeared();
1402            replace(&mut step, next);
1403        }
1404        if kept.withdrawn {
1405            let next = self.on_withdrawn();
1406            replace(&mut step, next);
1407        }
1408        step
1409    }
1410
1411    /// A campaign: a read, but under `external` without the lock.
1412    fn campaign(&mut self) -> Step {
1413        if self.election == Election::External && !self.lock {
1414            return self.stand_by(Why::NoLock);
1415        }
1416        self.phase = Phase::Campaigning;
1417        Step::Read
1418    }
1419
1420    fn stand_by(&mut self, why: Why) -> Step {
1421        let retry = why.retries();
1422        self.phase = Phase::Standby { retry };
1423        Step::StandBy { why, retry }
1424    }
1425
1426    fn step_down(&mut self, why: StepDownWhy) -> Step {
1427        self.phase = Phase::SteppingDown(why.clone());
1428        Step::StepDown(why)
1429    }
1430
1431    /// A heal read's holders, its own counted: it knows it holds.
1432    fn holding(&self, r: &Read) -> Vec<InstanceId> {
1433        let mut h = r.holders_owned();
1434        if !h.contains(&self.own) {
1435            h.push(self.own.clone());
1436            h.sort();
1437        }
1438        h
1439    }
1440
1441    fn on_read(&mut self, r: &Read) -> Step {
1442        let step = match self.phase.clone() {
1443            Phase::Campaigning => {
1444                let decision = match self.election {
1445                    Election::Claim => elect(&self.own, r),
1446                    Election::External if !self.lock => Decision::StandBy(Why::NoLock),
1447                    Election::External => elect_external(&self.own, r),
1448                };
1449                match decision {
1450                    Decision::TakeOver => {
1451                        self.phase = Phase::TakingOver;
1452                        Step::TakeOver
1453                    }
1454                    Decision::StandBy(why) => self.stand_by(why),
1455                }
1456            }
1457            Phase::HealFirst => {
1458                let holders = self.holding(r);
1459                if holders.len() >= 2 {
1460                    self.phase = Phase::HealGrace(holders);
1461                    Step::Grace
1462                } else if r.complete {
1463                    self.phase = Phase::Serving;
1464                    Step::Nothing
1465                } else {
1466                    // F-199: a read not complete showing one holder ends
1467                    // nothing.
1468                    self.phase = Phase::HealRetry(None);
1469                    Step::Retry
1470                }
1471            }
1472            Phase::HealSecond(first) => {
1473                let second = self.holding(r);
1474                match heal(&self.own, self.election, &first, &second) {
1475                    Heal::StepDown(low) => self.step_down(StepDownWhy::LowerHolder(low)),
1476                    Heal::Stay(Stay::NoSplit) if !r.complete => {
1477                        self.phase = Phase::HealRetry(Some(first));
1478                        Step::Retry
1479                    }
1480                    Heal::Stay(_) => {
1481                        self.phase = Phase::Serving;
1482                        Step::Nothing
1483                    }
1484                }
1485            }
1486            _ => return Step::Nothing,
1487        };
1488        self.decide_kept(step)
1489    }
1490
1491    /// Another instance's interface token appeared (after the own-id
1492    /// filter).
1493    fn on_appeared(&mut self) -> Step {
1494        if self.election != Election::Claim {
1495            return Step::Nothing;
1496        }
1497        match self.phase {
1498            Phase::Serving => {
1499                self.phase = Phase::HealFirst;
1500                Step::Read
1501            }
1502            Phase::Campaigning | Phase::TakingOver | Phase::HealFirst | Phase::HealSecond(_) => {
1503                self.kept.appeared = true;
1504                Step::Nothing
1505            }
1506            _ => Step::Nothing,
1507        }
1508    }
1509
1510    fn on_withdrawn(&mut self) -> Step {
1511        match self.phase {
1512            Phase::Standby { .. } => {
1513                if self.election == Election::External && !self.lock {
1514                    Step::Nothing
1515                } else {
1516                    self.campaign()
1517                }
1518            }
1519            Phase::Campaigning
1520            | Phase::SteppingDown(_)
1521            | Phase::HealFirst
1522            | Phase::HealSecond(_) => {
1523                self.kept.withdrawn = true;
1524                Step::Nothing
1525            }
1526            _ => Step::Nothing,
1527        }
1528    }
1529
1530    fn on_timer(&mut self) -> Step {
1531        match self.phase.clone() {
1532            Phase::Standby { retry: true } => self.campaign(),
1533            Phase::HealGrace(first) => {
1534                self.phase = Phase::HealSecond(first);
1535                Step::Read
1536            }
1537            Phase::HealRetry(first) => {
1538                self.phase = match first {
1539                    None => Phase::HealFirst,
1540                    Some(first) => Phase::HealSecond(first),
1541                };
1542                Step::Read
1543            }
1544            _ => Step::Nothing,
1545        }
1546    }
1547
1548    fn on_lock(&mut self, held: bool) -> Step {
1549        if self.election != Election::External {
1550            return Step::Nothing;
1551        }
1552        self.lock = held;
1553        match self.phase {
1554            Phase::Standby { .. } if held => self.campaign(),
1555            Phase::Serving if !held => self.step_down(StepDownWhy::LockLost),
1556            _ => Step::Nothing,
1557        }
1558    }
1559}
1560
1561// --- §2.15, §5: what a tool may conclude ---------------------------------------------
1562
1563/// What a tool read of an address and a governed interface (§2.15): two
1564/// reads a grace apart.
1565#[derive(Debug, Clone, PartialEq, Eq)]
1566pub struct Reading {
1567    /// Across a constrained face, where presence does not cross (§2.13).
1568    pub across_face: bool,
1569    pub governance: Governance,
1570    pub first: Read,
1571    pub second: Read,
1572}
1573
1574/// A question of §5, answered in its states (core O5).
1575#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1576pub enum Answer {
1577    Yes,
1578    No,
1579    /// The question was put, and the reading could not answer it.
1580    Unobservable,
1581    /// Nobody put the question.
1582    NotAsked,
1583    /// The interface is not governed.
1584    NotThisProfiles,
1585}
1586
1587impl Answer {
1588    /// The fixture's token.
1589    #[must_use]
1590    pub fn as_str(self) -> &'static str {
1591        match self {
1592            Self::Yes => "yes",
1593            Self::No => "no",
1594            Self::Unobservable => "unobservable",
1595            Self::NotAsked => "not_asked",
1596            Self::NotThisProfiles => "not_this_profiles",
1597        }
1598    }
1599}
1600
1601impl fmt::Display for Answer {
1602    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1603        f.write_str(self.as_str())
1604    }
1605}
1606
1607/// Why an answer is what it is: the fixture's reason (§2.15).
1608#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1609pub enum Reason {
1610    AcrossFace,
1611    NotGoverned,
1612    NoContract,
1613    RevisionsDisagree,
1614    Absent,
1615    PresenceIncomplete,
1616    Split,
1617    InTransition,
1618    One,
1619    NoDescriptor,
1620    NoCandidate,
1621    Vacant,
1622    Held,
1623    Lasting,
1624    StandingBy,
1625    NoneStanding,
1626    SplitLowest,
1627    NotACandidate,
1628    Unlisted,
1629    Incumbent,
1630    MarkedHolding,
1631    Standby,
1632    Unmarked,
1633}
1634
1635impl Reason {
1636    /// The fixture's token.
1637    #[must_use]
1638    pub fn as_str(self) -> &'static str {
1639        match self {
1640            Self::AcrossFace => "across_face",
1641            Self::NotGoverned => "not_governed",
1642            Self::NoContract => "no_contract",
1643            Self::RevisionsDisagree => "revisions_disagree",
1644            Self::Absent => "absent",
1645            Self::PresenceIncomplete => "presence_incomplete",
1646            Self::Split => "split",
1647            Self::InTransition => "in_transition",
1648            Self::One => "one",
1649            Self::NoDescriptor => "no_descriptor",
1650            Self::NoCandidate => "no_candidate",
1651            Self::Vacant => "vacant",
1652            Self::Held => "held",
1653            Self::Lasting => "lasting",
1654            Self::StandingBy => "standing_by",
1655            Self::NoneStanding => "none",
1656            Self::SplitLowest => "split_lowest",
1657            Self::NotACandidate => "not_a_candidate",
1658            Self::Unlisted => "unlisted",
1659            Self::Incumbent => "incumbent",
1660            Self::MarkedHolding => "marked_holding",
1661            Self::Standby => "standby",
1662            Self::Unmarked => "unmarked",
1663        }
1664    }
1665}
1666
1667impl fmt::Display for Reason {
1668    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1669        f.write_str(self.as_str())
1670    }
1671}
1672
1673/// An answer and its reason.
1674#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1675pub struct Judged {
1676    pub answer: Answer,
1677    pub reason: Reason,
1678}
1679
1680impl Judged {
1681    const fn new(answer: Answer, reason: Reason) -> Self {
1682        Self { answer, reason }
1683    }
1684}
1685
1686/// How many stand by (§2.15): exact, or a lower bound.
1687#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1688pub struct Count {
1689    pub count: usize,
1690    pub exact: bool,
1691}
1692
1693/// §2.15's premises, in order: a face, the presence of the address (or of
1694/// one instance) in the second read, the governance.
1695fn premises_of(r: &Reading, present: bool) -> Result<(), Judged> {
1696    use Answer::{NotAsked, NotThisProfiles, Unobservable};
1697    if r.across_face {
1698        return Err(Judged::new(Unobservable, Reason::AcrossFace));
1699    }
1700    if !present {
1701        return Err(if r.second.complete {
1702            Judged::new(NotAsked, Reason::Absent)
1703        } else {
1704            Judged::new(Unobservable, Reason::PresenceIncomplete)
1705        });
1706    }
1707    match r.governance {
1708        Governance::Governed(_) => Ok(()),
1709        Governance::NotGoverned => Err(Judged::new(NotThisProfiles, Reason::NotGoverned)),
1710        Governance::NoContract => Err(Judged::new(Unobservable, Reason::NoContract)),
1711        Governance::Disagree => Err(Judged::new(Unobservable, Reason::RevisionsDisagree)),
1712    }
1713}
1714
1715fn address_premises(r: &Reading) -> Result<(), Judged> {
1716    premises_of(r, !r.second.instances.is_empty())
1717}
1718
1719/// A read with no candidate: `no_descriptor` when a descriptor in it was
1720/// not read, else `no_candidate`. `None` when it holds a candidate.
1721fn no_candidate(read: &Read) -> Option<Judged> {
1722    if read.instances.iter().any(|s| s.descriptor.lists()) {
1723        return None;
1724    }
1725    Some(
1726        if read
1727            .instances
1728            .iter()
1729            .any(|s| s.descriptor == Listing::Unread)
1730        {
1731            Judged::new(Answer::Unobservable, Reason::NoDescriptor)
1732        } else {
1733            Judged::new(Answer::NotAsked, Reason::NoCandidate)
1734        },
1735    )
1736}
1737
1738/// §5's first question, "is the address served by exactly one
1739/// incumbent?" (§2.15). No is the finding.
1740#[must_use]
1741pub fn one_incumbent(r: &Reading) -> Judged {
1742    use Answer::{No, Unobservable, Yes};
1743    if let Err(j) = address_premises(r) {
1744        return j;
1745    }
1746    let h1 = r.first.holders().len();
1747    let h2 = r.second.holders().len();
1748    if h1 >= 2 && h2 >= 2 {
1749        return Judged::new(No, Reason::Split);
1750    }
1751    if h2 >= 2 {
1752        return Judged::new(Unobservable, Reason::InTransition);
1753    }
1754    if h2 == 1 {
1755        return if r.second.complete {
1756            Judged::new(Yes, Reason::One)
1757        } else {
1758            Judged::new(Unobservable, Reason::PresenceIncomplete)
1759        };
1760    }
1761    if !r.second.complete {
1762        return Judged::new(Unobservable, Reason::PresenceIncomplete);
1763    }
1764    if let Some(j) = no_candidate(&r.second) {
1765        return j;
1766    }
1767    if h1 >= 1 {
1768        return Judged::new(Unobservable, Reason::InTransition);
1769    }
1770    if !r.first.complete {
1771        return Judged::new(Unobservable, Reason::PresenceIncomplete);
1772    }
1773    Judged::new(No, Reason::Vacant)
1774}
1775
1776/// §5's second question, "is there a vacancy?" (§2.15). Yes, `lasting`, is
1777/// the finding; `vacant` is a takeover due.
1778#[must_use]
1779pub fn vacancy(r: &Reading) -> Judged {
1780    use Answer::{No, Unobservable, Yes};
1781    if let Err(j) = address_premises(r) {
1782        return j;
1783    }
1784    if !r.second.holders().is_empty() {
1785        return Judged::new(No, Reason::Held);
1786    }
1787    if !r.second.complete {
1788        return Judged::new(Unobservable, Reason::PresenceIncomplete);
1789    }
1790    if let Some(j) = no_candidate(&r.second) {
1791        return j;
1792    }
1793    if r.first.complete && r.first.holders().is_empty() {
1794        Judged::new(Yes, Reason::Lasting)
1795    } else {
1796        Judged::new(Yes, Reason::Vacant)
1797    }
1798}
1799
1800/// §5's third question, "does any instance stand by, and how many?"
1801/// (§2.15): the instances of the second read marked standby and holding no
1802/// token. Informative.
1803#[must_use]
1804pub fn standbys(r: &Reading) -> (Judged, Count) {
1805    use Answer::{No, Unobservable, Yes};
1806    let unknown = Count {
1807        count: 0,
1808        exact: false,
1809    };
1810    if let Err(j) = address_premises(r) {
1811        return (j, unknown);
1812    }
1813    let read = &r.second;
1814    let n = read
1815        .instances
1816        .iter()
1817        .filter(|s| !s.token && s.descriptor == Listing::Listed { standby: true })
1818        .count();
1819    let unread = read
1820        .instances
1821        .iter()
1822        .any(|s| s.descriptor == Listing::Unread);
1823    if n >= 1 {
1824        return (
1825            Judged::new(Yes, Reason::StandingBy),
1826            Count {
1827                count: n,
1828                exact: read.complete && !unread,
1829            },
1830        );
1831    }
1832    if !read.complete {
1833        return (
1834            Judged::new(Unobservable, Reason::PresenceIncomplete),
1835            unknown,
1836        );
1837    }
1838    if unread {
1839        return (Judged::new(Unobservable, Reason::NoDescriptor), unknown);
1840    }
1841    (
1842        Judged::new(No, Reason::NoneStanding),
1843        Count {
1844            count: 0,
1845            exact: true,
1846        },
1847    )
1848}
1849
1850/// §5's fourth question, "is this instance a standby, or a twin?"
1851/// (§2.15). Yes, a twin, is the finding.
1852#[must_use]
1853pub fn twin(r: &Reading, x: &InstanceId) -> Judged {
1854    use Answer::{No, NotAsked, Unobservable, Yes};
1855    let x2 = r.second.get(x);
1856    if let Err(j) = premises_of(r, x2.is_some()) {
1857        return j;
1858    }
1859    let Some(x2) = x2 else {
1860        return Judged::new(NotAsked, Reason::Absent);
1861    };
1862    let x1 = r.first.get(x);
1863    let h1 = r.first.holders();
1864    let h2 = r.second.holders();
1865    let same = x1.is_some_and(|a| a.token == x2.token && a.descriptor == x2.descriptor);
1866    if x2.token && x1.is_some_and(|a| a.token) && h1.len() >= 2 && h2.len() >= 2 {
1867        return if h2.first() == Some(&x) {
1868            Judged::new(Yes, Reason::SplitLowest)
1869        } else {
1870            Judged::new(Yes, Reason::Split)
1871        };
1872    }
1873    match x2.descriptor {
1874        Listing::Unread => Judged::new(Unobservable, Reason::NoDescriptor),
1875        Listing::NotListed if !x2.token => Judged::new(NotAsked, Reason::NotACandidate),
1876        Listing::NotListed if same => Judged::new(Yes, Reason::Unlisted),
1877        Listing::NotListed => Judged::new(Unobservable, Reason::InTransition),
1878        Listing::Listed { standby } if x2.token => {
1879            if h2.len() >= 2 {
1880                Judged::new(Unobservable, Reason::InTransition)
1881            } else if standby {
1882                if same {
1883                    Judged::new(Yes, Reason::MarkedHolding)
1884                } else {
1885                    Judged::new(Unobservable, Reason::InTransition)
1886                }
1887            } else if r.second.complete {
1888                Judged::new(No, Reason::Incumbent)
1889            } else {
1890                Judged::new(Unobservable, Reason::PresenceIncomplete)
1891            }
1892        }
1893        Listing::Listed { standby: true } => {
1894            if r.second.complete {
1895                Judged::new(No, Reason::Standby)
1896            } else {
1897                Judged::new(Unobservable, Reason::PresenceIncomplete)
1898            }
1899        }
1900        Listing::Listed { standby: false } => {
1901            if !same {
1902                Judged::new(Unobservable, Reason::InTransition)
1903            } else if r.first.complete && r.second.complete {
1904                Judged::new(Yes, Reason::Unmarked)
1905            } else {
1906                Judged::new(Unobservable, Reason::PresenceIncomplete)
1907            }
1908        }
1909    }
1910}
1911
1912#[cfg(test)]
1913mod tests {
1914    use super::*;
1915
1916    fn id(n: u64) -> InstanceId {
1917        InstanceId::from_u64(n)
1918    }
1919
1920    fn seen(n: u64, token: bool, descriptor: Listing) -> Seen {
1921        Seen {
1922            id: id(n),
1923            token,
1924            descriptor,
1925        }
1926    }
1927
1928    const STANDBY: Listing = Listing::Listed { standby: true };
1929    const SERVING: Listing = Listing::Listed { standby: false };
1930
1931    fn read(complete: bool, instances: Vec<Seen>) -> Read {
1932        Read {
1933            complete,
1934            instances,
1935        }
1936    }
1937
1938    #[test]
1939    fn ids_compare_as_unsigned_integers() {
1940        assert!(lower(&id(0x9), &id(0xa)));
1941        assert!(lower(&id(0xff), &id(0x100)));
1942        assert!(!lower(&id(5), &id(5)));
1943    }
1944
1945    #[test]
1946    fn a_live_incumbent_wins_whatever_the_read() {
1947        let r = read(false, vec![seen(9, true, Listing::Unread)]);
1948        assert_eq!(elect(&id(1), &r), Decision::StandBy(Why::Incumbent(id(9))));
1949    }
1950
1951    #[test]
1952    fn the_lowest_candidate_wins_a_complete_read() {
1953        let own = id(5);
1954        let r = read(true, vec![seen(5, false, STANDBY), seen(7, false, STANDBY)]);
1955        assert_eq!(elect(&own, &r), Decision::TakeOver);
1956        let r = read(
1957            true,
1958            vec![
1959                seen(2, false, Listing::NotListed),
1960                seen(3, false, STANDBY),
1961                seen(5, false, STANDBY),
1962            ],
1963        );
1964        assert_eq!(
1965            elect(&own, &r),
1966            Decision::StandBy(Why::LowerCandidate(id(3)))
1967        );
1968        let r = read(true, vec![seen(3, false, STANDBY)]);
1969        assert_eq!(elect(&own, &r), Decision::StandBy(Why::OwnClaimMissing));
1970    }
1971
1972    #[test]
1973    fn a_split_leaves_the_lowest() {
1974        let two = [id(2), id(8)];
1975        assert_eq!(
1976            heal(&id(8), Election::Claim, &two, &two),
1977            Heal::StepDown(id(2))
1978        );
1979        assert_eq!(
1980            heal(&id(2), Election::Claim, &two, &two),
1981            Heal::Stay(Stay::Lowest)
1982        );
1983        assert_eq!(
1984            heal(&id(8), Election::External, &two, &two),
1985            Heal::Stay(Stay::External)
1986        );
1987        assert_eq!(
1988            heal(&id(8), Election::Claim, &[id(8)], &two),
1989            Heal::Stay(Stay::NoSplit)
1990        );
1991    }
1992
1993    #[test]
1994    fn a_standby_takes_over_at_a_vacancy_and_steps_down_to_a_lower_one() {
1995        let mut e = Elector::new(id(8), Election::Claim);
1996        assert_eq!(e.start(), Step::Claim);
1997        assert_eq!(e.finish(), Step::Read);
1998        let incumbent = read(true, vec![seen(4, true, SERVING), seen(8, false, STANDBY)]);
1999        assert_eq!(
2000            e.observe(Event::Read(incumbent)),
2001            Step::StandBy {
2002                why: Why::Incumbent(id(4)),
2003                retry: false
2004            }
2005        );
2006        assert_eq!(e.role(), Role::Standby);
2007        assert_eq!(e.observe(Event::Timer), Step::Nothing);
2008        assert_eq!(e.observe(Event::Withdrawn), Step::Read);
2009        let vacant = read(true, vec![seen(8, false, STANDBY)]);
2010        assert_eq!(e.observe(Event::Read(vacant)), Step::TakeOver);
2011        assert_eq!(e.finish(), Step::Nothing);
2012        assert!(e.serving());
2013        assert_eq!(e.observe(Event::Appeared(id(2))), Step::Read);
2014        let split = read(false, vec![seen(2, true, SERVING), seen(8, true, SERVING)]);
2015        assert_eq!(e.observe(Event::Read(split.clone())), Step::Grace);
2016        assert_eq!(e.observe(Event::Timer), Step::Read);
2017        assert_eq!(
2018            e.observe(Event::Read(split)),
2019            Step::StepDown(StepDownWhy::LowerHolder(id(2)))
2020        );
2021        assert_eq!(e.finish(), Step::Nothing);
2022        assert_eq!(e.role(), Role::Standby);
2023    }
2024
2025    #[test]
2026    fn external_serves_only_with_its_lock() {
2027        let mut e = Elector::new(id(1), Election::External);
2028        assert_eq!(e.start(), Step::Claim);
2029        assert_eq!(
2030            e.finish(),
2031            Step::StandBy {
2032                why: Why::NoLock,
2033                retry: false
2034            }
2035        );
2036        assert_eq!(e.observe(Event::Withdrawn), Step::Nothing);
2037        assert_eq!(e.observe(Event::Lock(true)), Step::Read);
2038        let alone = read(true, vec![seen(1, false, STANDBY), seen(9, false, STANDBY)]);
2039        assert_eq!(e.observe(Event::Read(alone)), Step::TakeOver);
2040        assert_eq!(e.finish(), Step::Nothing);
2041        assert_eq!(e.observe(Event::Appeared(id(0))), Step::Nothing);
2042        assert_eq!(
2043            e.observe(Event::Lock(false)),
2044            Step::StepDown(StepDownWhy::LockLost)
2045        );
2046    }
2047
2048    /// A read asked is never asked again, nor dropped, before its answer
2049    /// (#841 RB's review): from every state the machine reaches, while a
2050    /// read it asked is unanswered, every event but that read's answer
2051    /// returns `nothing`, so a runtime never holds two reads at once and no
2052    /// phase waiting on a read (campaigning, a heal's first or second read)
2053    /// is stranded. Explored breadth-first over every reachable state, for
2054    /// both elections; after an act (a claim, a takeover, a step-down) the
2055    /// runtime's next call is `finish`, as the reference's loop makes it.
2056    #[test]
2057    fn a_read_asked_is_never_asked_again_before_its_answer() {
2058        use std::collections::{HashSet, VecDeque};
2059        let own = id(0xb);
2060        let reads = [
2061            read(true, vec![seen(0xb, false, STANDBY)]),
2062            read(
2063                true,
2064                vec![seen(0xa, true, SERVING), seen(0xb, false, STANDBY)],
2065            ),
2066            read(false, vec![]),
2067            read(
2068                true,
2069                vec![seen(0xa, true, SERVING), seen(0xb, true, SERVING)],
2070            ),
2071            read(false, vec![seen(0xb, true, SERVING)]),
2072            read(
2073                true,
2074                vec![seen(0x1, false, STANDBY), seen(0xb, false, STANDBY)],
2075            ),
2076            read(true, vec![seen(0xb, true, SERVING)]),
2077        ];
2078        let others = [
2079            Event::Appeared(id(0xa)),
2080            Event::Appeared(own.clone()),
2081            Event::Withdrawn,
2082            Event::Timer,
2083            Event::Lock(true),
2084            Event::Lock(false),
2085            Event::Reminted(id(0xc)),
2086        ];
2087        for election in [Election::Claim, Election::External] {
2088            let mut e = Elector::new(own.clone(), election);
2089            assert_eq!(e.start(), Step::Claim);
2090            // (machine, a read asked and unanswered, an act to finish)
2091            let mut queue = VecDeque::from([(e.clone(), false, true)]);
2092            let mut seen_states = HashSet::new();
2093            let mut asked_states = 0;
2094            while let Some((e, asked, acting)) = queue.pop_front() {
2095                if !seen_states.insert(format!("{e:?} {asked} {acting}")) {
2096                    continue;
2097                }
2098                let mut next = |e: Elector, step: Step, was_asked: bool| {
2099                    let act = matches!(step, Step::Claim | Step::TakeOver | Step::StepDown(_));
2100                    let asks = step == Step::Read;
2101                    assert!(
2102                        !(was_asked && asks),
2103                        "{election}: a second read asked while one runs: {e:?}"
2104                    );
2105                    queue.push_back((e, was_asked || asks, act));
2106                };
2107                if acting {
2108                    let mut e2 = e.clone();
2109                    let step = e2.finish();
2110                    next(e2, step, asked);
2111                    continue;
2112                }
2113                if asked {
2114                    asked_states += 1;
2115                    for ev in &others {
2116                        let mut e2 = e.clone();
2117                        let step = e2.observe(ev.clone());
2118                        assert_eq!(
2119                            step,
2120                            Step::Nothing,
2121                            "{election}: {ev:?} while a read runs, in {e:?}"
2122                        );
2123                        assert_eq!(e2.finish(), Step::Nothing, "no act runs while a read does");
2124                        next(e2, Step::Nothing, true);
2125                    }
2126                    for r in &reads {
2127                        let mut e2 = e.clone();
2128                        let step = e2.observe(Event::Read(r.clone()));
2129                        // The answer is taken: a phase waiting on it moves on.
2130                        next(e2, step, false);
2131                    }
2132                } else {
2133                    for ev in &others {
2134                        let mut e2 = e.clone();
2135                        let step = e2.observe(ev.clone());
2136                        next(e2, step, false);
2137                    }
2138                }
2139            }
2140            assert!(
2141                asked_states > 0,
2142                "{election}: the exploration reached reads asked"
2143            );
2144        }
2145    }
2146
2147    #[test]
2148    fn a_tool_tells_a_standby_from_a_twin() {
2149        let one = read(true, vec![seen(4, true, SERVING), seen(8, false, STANDBY)]);
2150        let r = Reading {
2151            across_face: false,
2152            governance: Governance::Governed(Election::Claim),
2153            first: one.clone(),
2154            second: one,
2155        };
2156        assert_eq!(one_incumbent(&r).reason, Reason::One);
2157        assert_eq!(vacancy(&r).reason, Reason::Held);
2158        assert_eq!(
2159            standbys(&r).1,
2160            Count {
2161                count: 1,
2162                exact: true
2163            }
2164        );
2165        assert_eq!(twin(&r, &id(4)).reason, Reason::Incumbent);
2166        assert_eq!(twin(&r, &id(8)).reason, Reason::Standby);
2167        let split = read(false, vec![seen(4, true, SERVING), seen(8, true, SERVING)]);
2168        let r = Reading {
2169            first: split.clone(),
2170            second: split,
2171            ..r
2172        };
2173        assert_eq!(one_incumbent(&r).reason, Reason::Split);
2174        assert_eq!(twin(&r, &id(4)).reason, Reason::SplitLowest);
2175        assert_eq!(twin(&r, &id(8)).reason, Reason::Split);
2176    }
2177}