Skip to main content

zenkey_model/
arbitration.rs

1//! `arbitration.v1`: one commander at a time, in the binding's order
2//! (`spec/profiles/arbitration/v1.md`, #909).
3//!
4//! The profile's session-free half: a role's declaration read from its
5//! contract's requirement and the revision of the required interface the
6//! consumer holds (§2.2, §2.3), the first profile to read a requirement's
7//! annotations; the ranking of a binding's providers (§2.4); one role's
8//! arbitration as a pure state machine, which the runtime and the tools
9//! both drive (§2.5 to §2.11); and §5's three questions, which never fold
10//! an unestablished answer into no (§2.14).
11//!
12//! | Rule | Item |
13//! |---|---|
14//! | §2.2 the declaration: arbitrated, invalid, unread | [`declaration`], [`declaration_of`], [`Declaration`], [`Invalid`], [`Role`], [`Revision`] |
15//! | §2.3 the deadline, from the revision held | [`deadline_of`], [`Arbitrated::deadline`], [`crate::timing`]'s declaration |
16//! | §2.4 the ranking, wildcards, shadowed entries | [`Binding`], [`Entry`], [`Rank`] |
17//! | §2.5 samples and who sent them | [`Arbiter::identify`], [`Sample`], [`Outcome`] |
18//! | §2.5's outcome 6, a governed interface's incumbents (`redundancy.v1` §2.10), [`crate::redundancy::Fence`] since #987's N1 | [`Incumbents`], [`Holding`] |
19//! | §2.6 to §2.8 eligibility, withdrawals, a move | [`Arbiter`], [`Event`] |
20//! | §2.7 a read again, and observer §3.6 (0.38): a read never undoes a token heard since it was asked | [`Arbiter::ask`], [`Asked`], carried by [`Event::Read`] |
21//! | §2.9 to §2.11 selection, switches, the dead-man | [`Arbiter::observe`], [`Step`], [`Switch`], [`Cause`] |
22//! | §2.14, §5 what a tool concludes | [`judge_declaration`], [`judge_selection`], [`judge_binding`], [`held_over`] |
23//!
24//! ```text
25//! declaration(role, revision held, params) ─▶ arbitrated {priority, stream, deadline} │ invalid [reasons] │ unread │ not arbitrated   §2.2
26//! Binding::rank(address)                   ─▶ (entry, system, service), compared in that order                          §2.4
27//! Arbiter::start / observe(at, event)      ─▶ switches {start│sample│deadline│withdrawn}, an outcome, reads again        §2.5–§2.11
28//! Arbiter::due()                           ─▶ the instant to arm the timer for: the active provider's deadline
29//! judge_declaration / _selection / _binding ─▶ §5's questions, in five states                                         §2.14
30//! ```
31//!
32//! There is no I/O and no clock here. Every instant is a [`Mono`], a
33//! reading of the consumer's monotonic clock (`timing.v1` §2.5's deadline
34//! runs on it). A consumer's runtime starts the
35//! [`Arbiter`] at its start, hands it each sample of the role's
36//! subscription ([`Event::Sample`]), each interface token its watch hears
37//! declared or withdrawn ([`Event::Declared`], [`Event::Withdrawn`]), each
38//! move of the watch session's transport and the round trip after it
39//! ([`Event::Moved`], [`Event::Stood`]), and its timer ([`Event::Tick`]),
40//! armed for [`Arbiter::due`]; it reads again each address a [`Step`]
41//! names in `reread` and hands the read back ([`Event::Read`]), with the
42//! [`Asked`] [`Arbiter::ask`] gave when it asked it, so the read applies
43//! to no token heard since (observer §3.6, 0.38); it
44//! delivers a sample whose [`Outcome`] is [`Outcome::Delivered`], and
45//! tells its application of each [`Switch`].
46//!
47//! The deadline is `timing.v1`'s, never restated: [`deadline_of`] reads it
48//! through [`crate::timing::declaration`] (`timing.v1` §2.2, §2.3, §2.5),
49//! and the [`Arbiter`] judges each provider's one key with a
50//! [`crate::timing::Tracker`] of its own, eligible while that tracker holds
51//! it heard and not missed.
52
53use std::collections::{BTreeMap, BTreeSet};
54use std::fmt;
55use std::time::Duration;
56
57use serde_json::Value;
58
59use crate::authoring::{Kind, RequireCardinality};
60use crate::contract::{Contract, Requirement};
61use crate::grammar::{Addr, IfaceId, InstanceId, KeyError, KindToken, Name, ZkKey, parse};
62use crate::redundancy::Heard;
63use crate::template::Template;
64use crate::timing::{self, MemberState, Mono, Tracker};
65
66/// The profile's id, as a contract lists it in `uses`.
67pub const PROFILE: &str = "arbitration.v1";
68
69/// The profile's name, as an annotation key's prefix carries it.
70pub const NAME: &str = "arbitration";
71
72/// `arbitration.policy` (§4), on a requirement.
73pub const POLICY: &str = "arbitration.policy";
74
75/// The published vocabulary (§4): the keys under `arbitration.`, which
76/// W105 reads in place of core Appendix D's interim row (core 0.54), the
77/// same key.
78pub const VOCABULARY: &[&str] = &["policy"];
79
80// --- §2.2: the declaration -------------------------------------------------------
81
82/// How a consumer chooses among a role's providers (§4). 1.0 defines one.
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
84pub enum Policy {
85    /// The first eligible provider in the binding's order (§2.4 to §2.11).
86    Priority,
87}
88
89impl Policy {
90    /// The vocabulary's value, and the fixture's token.
91    #[must_use]
92    pub fn as_str(self) -> &'static str {
93        match self {
94            Self::Priority => "priority",
95        }
96    }
97}
98
99impl fmt::Display for Policy {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        f.write_str(self.as_str())
102    }
103}
104
105/// Why a declaration is invalid (§2.2), in the order checked.
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
107pub enum Invalid {
108    /// The policy carried, and the declaring contract's `uses` naming no
109    /// major of the profile (core E020's).
110    NotUsed,
111    /// A component's manifest declares the role.
112    ManifestRole,
113    /// `freshest` or `lease`, reserved (§4).
114    PolicyUnsupported,
115    /// Not one of the strings `priority`, `freshest`, `lease`.
116    Value,
117    /// The role's cardinality is not `many`.
118    Cardinality,
119    /// The role does not consume exactly one stream.
120    Resource,
121    /// That stream has no deadline as `timing.v1` reads it.
122    NoDeadline,
123    /// A parameter of that stream's template is not bound (core R2).
124    ParamsUnbound,
125    /// The role consumes a frame resource (core §7.7) and no stream that
126    /// is not one: a frame is never an arbitrated role's stream (text 0.6).
127    Framed,
128}
129
130impl Invalid {
131    /// The fixture's token.
132    #[must_use]
133    pub fn as_str(self) -> &'static str {
134        match self {
135            Self::NotUsed => "not_used",
136            Self::ManifestRole => "manifest_role",
137            Self::PolicyUnsupported => "policy_unsupported",
138            Self::Value => "value",
139            Self::Cardinality => "cardinality",
140            Self::Resource => "resource",
141            Self::NoDeadline => "no_deadline",
142            Self::ParamsUnbound => "params_unbound",
143            Self::Framed => "framed",
144        }
145    }
146
147    /// What it says, for a linter's line or a refusal.
148    #[must_use]
149    pub fn says(self) -> &'static str {
150        match self {
151            Self::NotUsed => "arbitration.policy is written, and uses does not list arbitration.v1",
152            Self::ManifestRole => {
153                "only a contract's role is arbitrated: a manifest's role reaches no descriptor with its policy"
154            }
155            Self::PolicyUnsupported => {
156                "freshest and lease are reserved; arbitration.v1 1.0 defines priority only"
157            }
158            Self::Value => "arbitration.policy is the string priority",
159            Self::Cardinality => "an arbitrated role has cardinality many",
160            Self::Resource => "an arbitrated role consumes exactly one stream resource",
161            Self::NoDeadline => {
162                "the role's stream declares a timing.v1 deadline, at or above its period"
163            }
164            Self::ParamsUnbound => {
165                "every parameter of the role's stream is bound by the role's parameter bindings"
166            }
167            Self::Framed => {
168                "a frame resource is never an arbitrated role's stream: its put carries several records"
169            }
170        }
171    }
172}
173
174impl fmt::Display for Invalid {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        f.write_str(self.says())
177    }
178}
179
180/// A valid declaration (§2.2): what an [`Arbiter`] needs of the role.
181#[derive(Debug, Clone, PartialEq, Eq)]
182pub struct Arbitrated {
183    pub policy: Policy,
184    /// The required interface.
185    pub iface: IfaceId,
186    /// The role's stream: its kind token (`stream` or `@stream`) and its
187    /// template.
188    pub token: KindToken,
189    pub template: Template,
190    /// The stream's deadline in the revision held (§2.3).
191    pub deadline: Duration,
192    /// Its period, when written.
193    pub period: Option<Duration>,
194}
195
196impl Arbitrated {
197    /// The stream as the fixture writes it, `<token>/<template>`.
198    #[must_use]
199    pub fn resource(&self) -> String {
200        format!("{}/{}", self.token.as_str(), self.template.as_str())
201    }
202}
203
204/// A role's declaration (§2.2).
205#[derive(Debug, Clone, PartialEq, Eq)]
206pub enum Declaration {
207    /// No `arbitration.policy`, or another major's: not this profile's. A
208    /// `many` role receives from every bound provider, merged (core §3.2).
209    NotArbitrated,
210    /// No revision of the required interface held, checks 1 to 5 passing.
211    Unread,
212    /// The reasons, in the order checked.
213    Invalid(Vec<Invalid>),
214    /// Arbitrated.
215    Arbitrated(Arbitrated),
216}
217
218impl Declaration {
219    /// The fixture's token.
220    #[must_use]
221    pub fn as_str(&self) -> &'static str {
222        match self {
223            Self::NotArbitrated => "not_arbitrated",
224            Self::Unread => "unread",
225            Self::Invalid(_) => "invalid",
226            Self::Arbitrated(_) => "arbitrated",
227        }
228    }
229
230    /// The valid declaration, if it is one.
231    #[must_use]
232    pub fn arbitrated(&self) -> Option<&Arbitrated> {
233        match self {
234            Self::Arbitrated(a) => Some(a),
235            _ => None,
236        }
237    }
238
239    /// Whether the role carries a policy: arbitrated, invalid or unread.
240    #[must_use]
241    pub fn carries_policy(&self) -> bool {
242        !matches!(self, Self::NotArbitrated)
243    }
244}
245
246/// A role, as §2.2 reads it.
247#[derive(Debug, Clone, Copy)]
248pub struct Role<'a> {
249    /// The declaring contract's `uses`, or `None` for a role a component's
250    /// manifest declares.
251    pub declared_by: Option<&'a [IfaceId]>,
252    /// The requirement's `resources` (templates), or `None`: every one.
253    pub resources: Option<&'a [String]>,
254    pub cardinality: RequireCardinality,
255    pub annotations: &'a BTreeMap<String, Value>,
256}
257
258impl<'a> Role<'a> {
259    /// A role its contract declares.
260    #[must_use]
261    pub fn of(declaring: &'a Contract, req: &'a Requirement) -> Self {
262        Self {
263            declared_by: Some(declaring.uses.as_slice()),
264            resources: req.resources.as_deref(),
265            cardinality: req.cardinality,
266            annotations: &req.annotations,
267        }
268    }
269
270    /// A role a component's manifest declares.
271    #[must_use]
272    pub fn of_manifest(req: &'a Requirement) -> Self {
273        Self {
274            declared_by: None,
275            resources: req.resources.as_deref(),
276            cardinality: req.cardinality,
277            annotations: &req.annotations,
278        }
279    }
280}
281
282/// One resource of the required interface's revision, as §2.2 reads it.
283#[derive(Debug, Clone, Copy)]
284pub struct Offered<'a> {
285    pub token: KindToken,
286    pub template: &'a Template,
287    /// Its resolved annotations (core §9.3).
288    pub annotations: &'a BTreeMap<String, Value>,
289    /// Whether it is a frame resource (core §7.7), which §2.2's check 6
290    /// counts as none and check 9 refuses.
291    pub frame: bool,
292}
293
294/// The revision of the required interface a reader holds (§2.3).
295#[derive(Debug, Clone)]
296pub struct Revision<'a> {
297    pub iface: &'a IfaceId,
298    pub resources: Vec<Offered<'a>>,
299}
300
301impl<'a> Revision<'a> {
302    /// A contract's revision.
303    #[must_use]
304    pub fn of(c: &'a Contract) -> Self {
305        Self {
306            iface: &c.iface,
307            resources: c
308                .resources
309                .iter()
310                .map(|r| Offered {
311                    token: r.token,
312                    template: &r.template,
313                    annotations: &r.annotations,
314                    frame: matches!(&r.body, crate::contract::Body::Data(d) if d.frame.is_some()),
315                })
316                .collect(),
317        }
318    }
319}
320
321/// The resource kind a kind token carries (core §1.3).
322fn kind_of(token: KindToken) -> Kind {
323    match token {
324        KindToken::Stream | KindToken::ExplicitStream => Kind::Stream,
325        KindToken::State | KindToken::ExplicitState => Kind::State,
326        KindToken::Events => Kind::Event,
327        KindToken::Op => Kind::Operation,
328    }
329}
330
331/// The deadline and the period of one resource of a revision, as
332/// `timing.v1` reads them (§2.3, §2.2 check 7): its declaration
333/// ([`timing::declaration`], `timing.v1` §2.2, §2.3) valid, and its judged
334/// deadline ([`timing::Declared::judged_deadline`], `timing.v1` §2.5) one:
335/// declared, and not below its period. `None` is no deadline: none
336/// declared, one below the period, or a declaration invalid whole.
337#[must_use]
338pub fn deadline_of(r: &Offered<'_>) -> Option<(Duration, Option<Duration>)> {
339    let d = match timing::declaration(kind_of(r.token), r.annotations) {
340        timing::Declaration::Declared(d) => d,
341        _ => return None,
342    };
343    Some((d.judged_deadline()?, d.period))
344}
345
346/// Reads a role's declaration (§2.2) from the role, the revision of the
347/// required interface held (`None`: none held), and the role's parameter
348/// bindings as configured (core R2). Each check runs alone, in §2.2's
349/// order; checks 7 and 8 only when check 6 passes, and 6 to 8 only with a
350/// revision held.
351#[must_use]
352pub fn declaration(
353    role: &Role<'_>,
354    provider: Option<&Revision<'_>>,
355    params: &BTreeMap<String, String>,
356) -> Declaration {
357    let Some(policy) = role.annotations.get(POLICY) else {
358        return Declaration::NotArbitrated;
359    };
360    let mut why = Vec::new();
361    match role.declared_by {
362        Some(uses) => {
363            let v1 = uses.iter().any(|u| u.name() == NAME && u.major() == 1);
364            let any = uses.iter().any(|u| u.name() == NAME);
365            if any && !v1 {
366                // Another major's text: its key is its own.
367                return Declaration::NotArbitrated;
368            }
369            if !any {
370                why.push(Invalid::NotUsed);
371            }
372        }
373        None => why.push(Invalid::ManifestRole),
374    }
375    match policy.as_str() {
376        Some("priority") => {}
377        Some("freshest" | "lease") => why.push(Invalid::PolicyUnsupported),
378        _ => why.push(Invalid::Value),
379    }
380    if role.cardinality != RequireCardinality::Many {
381        why.push(Invalid::Cardinality);
382    }
383    let Some(rev) = provider else {
384        return if why.is_empty() {
385            Declaration::Unread
386        } else {
387            Declaration::Invalid(why)
388        };
389    };
390    let consumed: Vec<&Offered<'_>> = rev
391        .resources
392        .iter()
393        .filter(|r| match role.resources {
394            None => true,
395            Some(names) => names.iter().any(|n| n == r.template.as_str()),
396        })
397        .collect();
398    // Check 6 counts no frame resource (text 0.6): a role on a frame and
399    // one plain stream is read over the stream.
400    let counted: Vec<&Offered<'_>> = consumed.iter().copied().filter(|r| !r.frame).collect();
401    let one = match counted.as_slice() {
402        [r] if matches!(r.token, KindToken::Stream | KindToken::ExplicitStream) => Some(*r),
403        _ => {
404            why.push(Invalid::Resource);
405            None
406        }
407    };
408    let mut deadline = None;
409    if let Some(r) = one {
410        deadline = deadline_of(r);
411        if deadline.is_none() {
412            why.push(Invalid::NoDeadline);
413        }
414        if r.template.params().any(|(p, _)| !params.contains_key(p)) {
415            why.push(Invalid::ParamsUnbound);
416        }
417    }
418    // Check 9: a frame consumed, and no stream that is not one.
419    let plain_stream = counted
420        .iter()
421        .any(|r| matches!(r.token, KindToken::Stream | KindToken::ExplicitStream));
422    if consumed.iter().any(|r| r.frame) && !plain_stream {
423        why.push(Invalid::Framed);
424    }
425    match (one, deadline) {
426        (Some(r), Some((deadline, period))) if why.is_empty() => {
427            Declaration::Arbitrated(Arbitrated {
428                policy: Policy::Priority,
429                iface: rev.iface.clone(),
430                token: r.token,
431                template: r.template.clone(),
432                deadline,
433                period,
434            })
435        }
436        _ => Declaration::Invalid(why),
437    }
438}
439
440/// [`declaration`] of the role `role` of the contract `declaring`, over the
441/// revision `provider` of its required interface (`None`: none held).
442/// `None` when the contract declares no such role.
443#[must_use]
444pub fn declaration_of(
445    declaring: &Contract,
446    role: &str,
447    provider: Option<&Contract>,
448    params: &BTreeMap<String, String>,
449) -> Option<Declaration> {
450    let req = declaring.requires.get(role)?;
451    let rev = provider.map(Revision::of);
452    Some(declaration(&Role::of(declaring, req), rev.as_ref(), params))
453}
454
455// --- §2.4: the ranking -----------------------------------------------------------
456
457/// One entry of a binding: `<system>/<service>`, each chunk a plain chunk
458/// or `*` (core §1.2, D009), a `self.system` already resolved (core §3.2).
459#[derive(Debug, Clone, PartialEq, Eq, Hash)]
460pub struct Entry {
461    /// `None` is `*`.
462    system: Option<Name>,
463    service: Option<Name>,
464}
465
466impl Entry {
467    /// Parses an entry.
468    pub fn parse(s: &str) -> Result<Self, KeyError> {
469        let (sys, svc) = s.split_once('/').ok_or(KeyError::Shape(
470            s.to_owned(),
471            "a binding entry is <system>/<service>",
472        ))?;
473        let chunk = |what: &'static str, c: &str| -> Result<Option<Name>, KeyError> {
474            if c == "*" {
475                Ok(None)
476            } else {
477                Name::new(what, c).map(Some)
478            }
479        };
480        Ok(Self {
481            system: chunk("system", sys)?,
482            service: chunk("service", svc)?,
483        })
484    }
485
486    /// Whether either chunk is `*`.
487    #[must_use]
488    pub fn is_wildcard(&self) -> bool {
489        self.system.is_none() || self.service.is_none()
490    }
491
492    /// The address of an exact entry.
493    #[must_use]
494    pub fn exact(&self) -> Option<Addr> {
495        Some(Addr {
496            system: self.system.clone()?,
497            service: self.service.clone()?,
498        })
499    }
500
501    /// Whether it matches an address: each chunk `*` or equal (§0).
502    #[must_use]
503    pub fn matches(&self, a: &Addr) -> bool {
504        self.system.as_ref().is_none_or(|s| *s == a.system)
505            && self.service.as_ref().is_none_or(|s| *s == a.service)
506    }
507
508    /// Whether it matches every address `later` does: each of its chunks
509    /// `*` or equal to `later`'s (§2.4, a shadowed entry).
510    #[must_use]
511    pub fn covers(&self, later: &Entry) -> bool {
512        fn chunk(a: Option<&Name>, b: Option<&Name>) -> bool {
513            match (a, b) {
514                (None, _) => true,
515                (Some(a), Some(b)) => a == b,
516                (Some(_), None) => false,
517            }
518        }
519        chunk(self.system.as_ref(), later.system.as_ref())
520            && chunk(self.service.as_ref(), later.service.as_ref())
521    }
522}
523
524impl fmt::Display for Entry {
525    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
526        let c = |n: &Option<Name>| n.as_ref().map_or("*", Name::as_str).to_owned();
527        write!(f, "{}/{}", c(&self.system), c(&self.service))
528    }
529}
530
531/// A provider's rank (§2.4): the position of the first entry matching it,
532/// then its system, then its service, each compared byte by byte. Lower is
533/// higher priority.
534#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
535pub struct Rank {
536    entry: usize,
537    system: String,
538    service: String,
539}
540
541impl Rank {
542    /// The 0-based position of the entry it ranks at.
543    #[must_use]
544    pub fn entry(&self) -> usize {
545        self.entry
546    }
547}
548
549/// A role's binding, its entries in their configured order (core R1, R3).
550#[derive(Debug, Clone, PartialEq, Eq, Default)]
551pub struct Binding {
552    entries: Vec<Entry>,
553}
554
555impl Binding {
556    /// Parses a binding as a descriptor lists it.
557    pub fn parse<S: AsRef<str>>(entries: &[S]) -> Result<Self, KeyError> {
558        Ok(Self {
559            entries: entries
560                .iter()
561                .map(|e| Entry::parse(e.as_ref()))
562                .collect::<Result<_, _>>()?,
563        })
564    }
565
566    /// The entries, in order.
567    #[must_use]
568    pub fn entries(&self) -> &[Entry] {
569        &self.entries
570    }
571
572    /// Whether it has no entry: an unbound role.
573    #[must_use]
574    pub fn is_empty(&self) -> bool {
575        self.entries.is_empty()
576    }
577
578    /// An address's rank, `None` when no entry matches it (§2.4).
579    #[must_use]
580    pub fn rank(&self, a: &Addr) -> Option<Rank> {
581        let entry = self.entries.iter().position(|e| e.matches(a))?;
582        Some(Rank {
583            entry,
584            system: a.system.as_str().to_owned(),
585            service: a.service.as_str().to_owned(),
586        })
587    }
588
589    /// The providers in rank order: every exact entry's address, heard or
590    /// not, and every heard address an entry matches, once each (§2.4).
591    #[must_use]
592    pub fn ranked<'a, I: IntoIterator<Item = &'a Addr>>(&self, heard: I) -> Vec<Addr> {
593        let mut by: BTreeMap<Rank, Addr> = BTreeMap::new();
594        let mut add = |a: &Addr| {
595            if let Some(r) = self.rank(a) {
596                by.entry(r).or_insert_with(|| a.clone());
597            }
598        };
599        for a in self.entries.iter().filter_map(Entry::exact) {
600            add(&a);
601        }
602        for a in heard {
603            add(a);
604        }
605        by.into_values().collect()
606    }
607
608    /// The heard addresses no entry matches, by system then service, once
609    /// each.
610    #[must_use]
611    pub fn unbound<'a, I: IntoIterator<Item = &'a Addr>>(&self, heard: I) -> Vec<Addr> {
612        heard
613            .into_iter()
614            .filter(|a| self.rank(a).is_none())
615            .cloned()
616            .collect::<BTreeSet<_>>()
617            .into_iter()
618            .collect()
619    }
620
621    /// The 0-based positions of the wildcard entries.
622    #[must_use]
623    pub fn wildcards(&self) -> Vec<usize> {
624        self.entries
625            .iter()
626            .enumerate()
627            .filter(|(_, e)| e.is_wildcard())
628            .map(|(i, _)| i)
629            .collect()
630    }
631
632    /// The 0-based positions of the shadowed entries: an entry an earlier
633    /// one covers (§2.4).
634    #[must_use]
635    pub fn shadowed(&self) -> Vec<usize> {
636        (0..self.entries.len())
637            .filter(|&j| self.entries[..j].iter().any(|e| e.covers(&self.entries[j])))
638            .collect()
639    }
640}
641
642// --- §2.5 to §2.11: one role's arbitration -----------------------------------------
643
644/// What became of a sample (§2.5, §2.9).
645#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
646pub enum Outcome {
647    /// An arrival of the active provider: delivered.
648    Delivered,
649    /// An arrival of another provider: counted, never delivered.
650    NotActive,
651    /// Its key is not concrete (core R6).
652    Wild,
653    /// Not the role's stream's key at any address.
654    Unresolved,
655    /// No entry matches its address.
656    Unbound,
657    /// A delete sample: no arrival (`timing.v1` §2.5).
658    Deleted,
659    /// `timing.v1` reads it expired: no arrival (`timing.v1` §2.6).
660    Expired,
661    /// A governed interface's sample `redundancy.v1` §2.10 does not
662    /// accept: no arrival.
663    NotIncumbent,
664}
665
666impl Outcome {
667    /// The fixture's token.
668    #[must_use]
669    pub fn as_str(self) -> &'static str {
670        match self {
671            Self::Delivered => "delivered",
672            Self::NotActive => "not_active",
673            Self::Wild => "wild",
674            Self::Unresolved => "unresolved",
675            Self::Unbound => "unbound",
676            Self::Deleted => "deleted",
677            Self::Expired => "expired",
678            Self::NotIncumbent => "not_incumbent",
679        }
680    }
681
682    /// Whether the sample is delivered to the application.
683    #[must_use]
684    pub fn delivered(self) -> bool {
685        self == Self::Delivered
686    }
687}
688
689/// A sample of the role's subscription, as the runtime hands it over.
690#[derive(Debug, Clone, Copy, PartialEq, Eq)]
691pub struct Sample<'a> {
692    /// Its key, base-relative (core §1.6).
693    pub key: &'a str,
694    /// A delete sample, which is no arrival (`timing.v1` §2.5).
695    pub delete: bool,
696    /// `timing.v1` reads it expired, on the deployment's stated bound
697    /// (`timing.v1` §2.6).
698    pub expired: bool,
699    /// The required interface is governed, and `redundancy.v1` §2.10 does
700    /// not accept it.
701    pub not_incumbent: bool,
702}
703
704impl<'a> Sample<'a> {
705    /// A put sample, neither expired nor refused by `redundancy.v1`.
706    #[must_use]
707    pub fn new(key: &'a str) -> Self {
708        Self {
709            key,
710            delete: false,
711            expired: false,
712            not_incumbent: false,
713        }
714    }
715}
716
717/// Why a switch happened (§2.10).
718#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
719pub enum Cause {
720    /// The consumer's start: the dead-man, from none.
721    Start,
722    /// An arrival made its provider active.
723    Sample,
724    /// The active provider missed its deadline.
725    Deadline,
726    /// The active provider was withdrawn.
727    Withdrawn,
728}
729
730impl Cause {
731    /// The fixture's token.
732    #[must_use]
733    pub fn as_str(self) -> &'static str {
734        match self {
735            Self::Start => "start",
736            Self::Sample => "sample",
737            Self::Deadline => "deadline",
738            Self::Withdrawn => "withdrawn",
739        }
740    }
741}
742
743impl fmt::Display for Cause {
744    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
745        f.write_str(self.as_str())
746    }
747}
748
749/// A switch (§2.10): `None` is no provider, the dead-man.
750#[derive(Debug, Clone, PartialEq, Eq)]
751pub struct Switch {
752    pub from: Option<Addr>,
753    pub to: Option<Addr>,
754    pub cause: Cause,
755    /// `from`'s last arrival, `None` when `from` is: what a consumer prints
756    /// beside the switch as `last_ms` (`scenarios.md`, its conventions).
757    pub last: Option<Mono>,
758}
759
760/// What the runtime tells an [`Arbiter`], each at its instant.
761#[derive(Debug, Clone, PartialEq, Eq)]
762pub enum Event<'a> {
763    /// A sample of the role's subscription (§2.5).
764    Sample(Sample<'a>),
765    /// The watch heard an interface token declared: its key (§2.7).
766    Declared(&'a str),
767    /// The watch heard an interface token withdrawn: its key (§2.7).
768    Withdrawn(&'a str),
769    /// A read of an address's presence: when it was asked
770    /// ([`Arbiter::ask`]), whether it is complete (core §8.1), and the
771    /// instances it shows holding the required interface's token there
772    /// (§2.7). It applies to no instance whose token the watch heard since
773    /// it was asked (observer §3.6).
774    Read {
775        address: Addr,
776        asked: Asked,
777        complete: bool,
778        held: BTreeSet<InstanceId>,
779    },
780    /// The watch session's transport closed or opened (§2.8).
781    Moved,
782    /// The round trip asked after the last move stands (§2.8).
783    Stood,
784    /// The timer fired (§2.9).
785    Tick,
786}
787
788/// What an [`Arbiter`] decided at one event.
789#[derive(Debug, Clone, Default, PartialEq, Eq)]
790pub struct Step {
791    /// At most two: the active provider's miss (cause `deadline`), then
792    /// the event's own (§2.9, §2.10).
793    pub switches: Vec<Switch>,
794    /// For a sample: what became of it.
795    pub outcome: Option<Outcome>,
796    /// The addresses to read again (§2.7), in rank order: the reference
797    /// reads each 0.1 s later, one read for a burst.
798    pub reread: Vec<Addr>,
799}
800
801/// A provider's counts of the samples counted for it (§2.5).
802#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
803pub struct Counts {
804    pub delivered: u64,
805    pub not_active: u64,
806    pub deleted: u64,
807    pub expired: u64,
808    pub not_incumbent: u64,
809}
810
811/// The counts of the samples with no provider (§2.5).
812#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
813pub struct Discards {
814    pub wild: u64,
815    pub unresolved: u64,
816    pub unbound: u64,
817}
818
819/// The member a provider's tracker holds: its one key in the role (§2.2
820/// check 8), so a provider's deadline is `timing.v1` §2.5's per (address,
821/// key).
822const MEMBER: &str = "key";
823
824/// A deadline tracker for one provider's one key (`timing.v1` §2.5), its
825/// bound one member, started at `start` when given: a tracker counts no
826/// arrival before its start.
827fn tracker(deadline: Duration, start: Option<Mono>) -> Tracker {
828    let mut t = Tracker::new(deadline, Some(1), [MEMBER]);
829    if let Some(at) = start {
830        t.observe(at, timing::Event::Start);
831    }
832    t
833}
834
835#[derive(Debug, Clone)]
836struct Provider {
837    addr: Addr,
838    /// Its key's deadline (`timing.v1` §2.5): its arrivals since its last
839    /// re-admission, a withdrawal starting it anew (§2.6, §2.7).
840    tracker: Tracker,
841    withdrawn: bool,
842    /// The instances known holding the required interface's token (§2.7).
843    held: BTreeSet<InstanceId>,
844    /// When the watch last heard each instance's token (observer §3.6).
845    heard: Heard,
846    counts: Counts,
847    /// Its last arrival its tracker took, kept across a withdrawal: a
848    /// switch's `last` (never a decision's input).
849    arrived: Option<Mono>,
850}
851
852impl Provider {
853    fn new(addr: Addr, deadline: Duration, start: Option<Mono>) -> Self {
854        Self {
855            addr,
856            tracker: tracker(deadline, start),
857            withdrawn: false,
858            held: BTreeSet::new(),
859            heard: Heard::default(),
860            counts: Counts::default(),
861            arrived: None,
862        }
863    }
864
865    /// Withdrawn: ineligible, its arrivals forgotten (§2.7).
866    fn withdraw(&mut self, deadline: Duration, at: Mono) {
867        self.withdrawn = true;
868        self.tracker = tracker(deadline, Some(at));
869    }
870
871    /// Its last arrival, while its key is in time or not yet judged missed.
872    fn last(&self) -> Option<Mono> {
873        match self.tracker.state(MEMBER) {
874            Some(MemberState::Heard { last }) => Some(last),
875            _ => None,
876        }
877    }
878}
879
880/// A presence event kept from a move until its round trip stands (§2.8).
881#[derive(Debug, Clone)]
882enum Kept {
883    Declared(Rank, InstanceId),
884    Withdrawn(Rank, InstanceId),
885    Read(Rank, Asked, bool, BTreeSet<InstanceId>),
886}
887
888/// One consumer's arbitration of one role (§2.5 to §2.11): a pure state
889/// machine over events that carry their instants, with no clock and no
890/// I/O. It asks reads ([`Step::reread`]) and is told what they found
891/// ([`Event::Read`]); it is told of a move ([`Event::Moved`]) and of the
892/// round trip after it ([`Event::Stood`]). A restart is a new `Arbiter`.
893#[derive(Debug, Clone)]
894pub struct Arbiter {
895    iface: IfaceId,
896    token: KindToken,
897    template: Template,
898    params: BTreeMap<String, String>,
899    deadline: Duration,
900    binding: Binding,
901    /// Every provider known, in rank order.
902    providers: BTreeMap<Rank, Provider>,
903    active: Option<Rank>,
904    started: bool,
905    /// A move pending: from [`Event::Moved`] until [`Event::Stood`].
906    moving: bool,
907    kept: Vec<Kept>,
908    discards: Discards,
909    /// The instant of the last event, which no later one may precede.
910    last: Option<Mono>,
911    /// The interface tokens heard, counted (observer §3.6).
912    heard: u64,
913}
914
915impl Arbiter {
916    /// The arbitration of a role declared `declared`, bound by `binding`,
917    /// its parameter bindings `params` resolved (a `self.system` or
918    /// `self.service` replaced by the consumer's own; core R2). It holds
919    /// nothing until [`Arbiter::start`].
920    #[must_use]
921    pub fn new(declared: &Arbitrated, binding: Binding, params: BTreeMap<String, String>) -> Self {
922        let providers = binding
923            .entries()
924            .iter()
925            .filter_map(Entry::exact)
926            .filter_map(|a| Some((binding.rank(&a)?, Provider::new(a, declared.deadline, None))))
927            .collect();
928        Self {
929            iface: declared.iface.clone(),
930            token: declared.token,
931            template: declared.template.clone(),
932            params,
933            deadline: declared.deadline,
934            binding,
935            providers,
936            active: None,
937            started: false,
938            moving: false,
939            kept: Vec::new(),
940            discards: Discards::default(),
941            last: None,
942            heard: 0,
943        }
944    }
945
946    /// A presence read is asked now: what it carries back in
947    /// [`Event::Read`], so it applies to no token heard since (observer
948    /// §3.6).
949    #[must_use]
950    pub fn ask(&self) -> Asked {
951        Asked(self.heard)
952    }
953
954    /// The deadline it judges by (§2.3).
955    #[must_use]
956    pub fn deadline(&self) -> Duration {
957        self.deadline
958    }
959
960    /// Its binding.
961    #[must_use]
962    pub fn binding(&self) -> &Binding {
963        &self.binding
964    }
965
966    /// The active provider, `None` in the dead-man (§2.9, §2.11).
967    #[must_use]
968    pub fn active(&self) -> Option<&Addr> {
969        self.active
970            .as_ref()
971            .and_then(|r| self.providers.get(r))
972            .map(|p| &p.addr)
973    }
974
975    /// Whether it holds the dead-man (§2.11).
976    #[must_use]
977    pub fn dead_man(&self) -> bool {
978        self.active.is_none()
979    }
980
981    /// The active provider's due instant: its last arrival plus the
982    /// deadline, after which it has missed (`timing.v1` §2.5). The runtime
983    /// arms its timer to fire after it, within the detection bound. `None`
984    /// in the dead-man, where only an arrival can make a provider eligible
985    /// (§2.9).
986    #[must_use]
987    pub fn due(&self) -> Option<Mono> {
988        let p = self.providers.get(self.active.as_ref()?)?;
989        Some(p.last()?.saturating_add(self.deadline))
990    }
991
992    /// Whether a move is pending (§2.8).
993    #[must_use]
994    pub fn moving(&self) -> bool {
995        self.moving
996    }
997
998    /// The providers known, in rank order (§2.4).
999    pub fn providers(&self) -> impl Iterator<Item = &Addr> {
1000        self.providers.values().map(|p| &p.addr)
1001    }
1002
1003    /// The counts of a provider's samples (§2.5).
1004    #[must_use]
1005    pub fn counts(&self, a: &Addr) -> Counts {
1006        self.binding
1007            .rank(a)
1008            .and_then(|r| self.providers.get(&r))
1009            .map(|p| p.counts)
1010            .unwrap_or_default()
1011    }
1012
1013    /// The counts of the samples with no provider (§2.5).
1014    #[must_use]
1015    pub fn discards(&self) -> Discards {
1016        self.discards
1017    }
1018
1019    /// Whether a provider is withdrawn (§2.7).
1020    #[must_use]
1021    pub fn withdrawn(&self, a: &Addr) -> bool {
1022        self.binding
1023            .rank(a)
1024            .and_then(|r| self.providers.get(&r))
1025            .is_some_and(|p| p.withdrawn)
1026    }
1027
1028    /// The provider a sample's key names, or why it has none (§2.5's
1029    /// outcomes 1 to 3): never from the payload.
1030    pub fn identify(&self, key: &str) -> Result<Addr, Outcome> {
1031        if key.contains('*') {
1032            return Err(Outcome::Wild);
1033        }
1034        let Ok(ZkKey::Data {
1035            addr,
1036            iface,
1037            kind,
1038            resource,
1039        }) = parse(key)
1040        else {
1041            return Err(Outcome::Unresolved);
1042        };
1043        if iface != self.iface || kind != self.token {
1044            return Err(Outcome::Unresolved);
1045        }
1046        let chunks: Vec<&str> = resource.iter().map(String::as_str).collect();
1047        let Some(values) = self.template.matches(&chunks) else {
1048            return Err(Outcome::Unresolved);
1049        };
1050        for (name, vs) in &values {
1051            match (self.params.get(name), vs.as_slice()) {
1052                (Some(p), [v]) if p == v => {}
1053                _ => return Err(Outcome::Unresolved),
1054            }
1055        }
1056        if self.binding.rank(&addr).is_none() {
1057            return Err(Outcome::Unbound);
1058        }
1059        Ok(addr)
1060    }
1061
1062    /// Starts: the dead-man, cause `start` (§2.11), every provider's
1063    /// tracker started (`timing.v1` §2.5). Called once.
1064    pub fn start(&mut self, at: Mono) -> Step {
1065        if self.started {
1066            return Step::default();
1067        }
1068        self.started = true;
1069        self.active = None;
1070        self.last = Some(at);
1071        for p in self.providers.values_mut() {
1072            p.tracker.observe(at, timing::Event::Start);
1073        }
1074        Step {
1075            switches: vec![Switch {
1076                from: None,
1077                to: None,
1078                cause: Cause::Start,
1079                last: None,
1080            }],
1081            ..Step::default()
1082        }
1083    }
1084
1085    /// Hands it an event at instant `at`, never before the last one's: it
1086    /// decides the time first, then the event, then selects (§2.9).
1087    pub fn observe(&mut self, at: Mono, event: Event<'_>) -> Step {
1088        let mut step = Step::default();
1089        if !self.started {
1090            return step;
1091        }
1092        debug_assert!(
1093            self.last.is_none_or(|l| at >= l),
1094            "an event at {at:?} precedes the last one, at {:?}",
1095            self.last
1096        );
1097        self.last = Some(at);
1098        // The time first: the active provider's miss at or before `at`.
1099        if let Some(r) = self.active.clone()
1100            && !self.eligible(&r, at)
1101        {
1102            let next = self.select(at);
1103            step.switches.push(self.switch_to(next, Cause::Deadline));
1104        }
1105        let mut reread = Vec::new();
1106        let mut arrival = None;
1107        match event {
1108            Event::Sample(s) => match self.identify(s.key) {
1109                Err(o) => {
1110                    match o {
1111                        Outcome::Wild => self.discards.wild += 1,
1112                        Outcome::Unbound => self.discards.unbound += 1,
1113                        _ => self.discards.unresolved += 1,
1114                    }
1115                    step.outcome = Some(o);
1116                }
1117                Ok(addr) => {
1118                    // `identify` found an entry matching it, so `provider`
1119                    // knows it from here on.
1120                    if let Some(r) = self.provider(addr, at)
1121                        && let Some(p) = self.providers.get_mut(&r)
1122                    {
1123                        if s.delete {
1124                            p.counts.deleted += 1;
1125                            step.outcome = Some(Outcome::Deleted);
1126                        } else if s.expired {
1127                            p.counts.expired += 1;
1128                            step.outcome = Some(Outcome::Expired);
1129                        } else if s.not_incumbent {
1130                            p.counts.not_incumbent += 1;
1131                            step.outcome = Some(Outcome::NotIncumbent);
1132                        } else {
1133                            if !p.withdrawn {
1134                                p.tracker.observe(
1135                                    at,
1136                                    timing::Event::Arrival {
1137                                        member: MEMBER,
1138                                        expired: false,
1139                                    },
1140                                );
1141                                p.arrived = Some(at);
1142                            }
1143                            arrival = Some(r);
1144                        }
1145                    }
1146                }
1147            },
1148            Event::Declared(key) => {
1149                if let Some((r, i)) = self.token(key, at) {
1150                    self.note(&r, &i);
1151                    if self.moving {
1152                        self.kept.push(Kept::Declared(r, i));
1153                    } else if let Some(p) = self.providers.get_mut(&r) {
1154                        p.held.insert(i);
1155                        p.withdrawn = false;
1156                    }
1157                }
1158            }
1159            Event::Withdrawn(key) => {
1160                if let Some((r, i)) = self.token(key, at) {
1161                    self.note(&r, &i);
1162                    if self.moving {
1163                        self.kept.push(Kept::Withdrawn(r, i));
1164                    } else if let Some(p) = self.providers.get_mut(&r) {
1165                        p.held.remove(&i);
1166                        if p.held.is_empty() {
1167                            p.withdraw(self.deadline, at);
1168                            reread.push(r);
1169                        }
1170                    }
1171                }
1172            }
1173            Event::Read {
1174                address,
1175                asked,
1176                complete,
1177                held,
1178            } => {
1179                if let Some(r) = self.provider(address, at) {
1180                    if self.moving {
1181                        self.kept.push(Kept::Read(r, asked, complete, held));
1182                    } else if let Some(p) = self.providers.get_mut(&r) {
1183                        p.heard.read_into(&mut p.held, asked, complete, held);
1184                        if !p.held.is_empty() {
1185                            p.withdrawn = false;
1186                        }
1187                    }
1188                }
1189            }
1190            Event::Moved => self.moving = true,
1191            Event::Stood => {
1192                if self.moving {
1193                    self.stand(at, &mut reread);
1194                }
1195            }
1196            Event::Tick => {}
1197        }
1198        let next = self.select(at);
1199        if next != self.active {
1200            let cause = if arrival.is_some() && next == arrival {
1201                Cause::Sample
1202            } else {
1203                // Only a withdrawal makes the active provider ineligible
1204                // within an event (§2.10): the time is settled above, and
1205                // an arrival makes no provider ineligible.
1206                debug_assert!(
1207                    self.active
1208                        .as_ref()
1209                        .and_then(|r| self.providers.get(r))
1210                        .is_some_and(|p| p.withdrawn),
1211                    "a switch at {at:?} that is no arrival's, from a provider not withdrawn"
1212                );
1213                Cause::Withdrawn
1214            };
1215            step.switches.push(self.switch_to(next, cause));
1216        }
1217        if let Some(r) = arrival {
1218            let delivered = self.active.as_ref() == Some(&r);
1219            if let Some(p) = self.providers.get_mut(&r) {
1220                step.outcome = Some(if delivered {
1221                    p.counts.delivered += 1;
1222                    Outcome::Delivered
1223                } else {
1224                    p.counts.not_active += 1;
1225                    Outcome::NotActive
1226                });
1227            }
1228        }
1229        reread.sort();
1230        reread.dedup();
1231        step.reread = reread
1232            .iter()
1233            .filter_map(|r| self.providers.get(r))
1234            .map(|p| p.addr.clone())
1235            .collect();
1236        step
1237    }
1238
1239    /// Whether a provider is eligible at `at` (§2.6): not withdrawn, and
1240    /// its key heard and not missed, a miss holding once more than the
1241    /// deadline has passed since its last arrival (`timing.v1` §2.5).
1242    fn eligible(&self, r: &Rank, at: Mono) -> bool {
1243        self.providers.get(r).is_some_and(|p| {
1244            !p.withdrawn
1245                && p.last()
1246                    .is_some_and(|l| at <= l.saturating_add(self.deadline))
1247        })
1248    }
1249
1250    /// The eligible provider of highest rank at `at` (§2.9).
1251    fn select(&self, at: Mono) -> Option<Rank> {
1252        self.providers
1253            .keys()
1254            .find(|r| self.eligible(r, at))
1255            .cloned()
1256    }
1257
1258    fn switch_to(&mut self, next: Option<Rank>, cause: Cause) -> Switch {
1259        let addr = |r: &Option<Rank>| {
1260            r.as_ref()
1261                .and_then(|r| self.providers.get(r))
1262                .map(|p| p.addr.clone())
1263        };
1264        let switch = Switch {
1265            from: addr(&self.active),
1266            to: addr(&next),
1267            cause,
1268            last: self
1269                .active
1270                .as_ref()
1271                .and_then(|r| self.providers.get(r))
1272                .and_then(|p| p.arrived),
1273        };
1274        self.active = next;
1275        switch
1276    }
1277
1278    /// A bound address's provider, known from now on (§2.4): one first
1279    /// heard at `at` has its tracker started then. `None` for an address
1280    /// no entry matches, which is no provider.
1281    fn provider(&mut self, addr: Addr, at: Mono) -> Option<Rank> {
1282        let r = self.binding.rank(&addr)?;
1283        let deadline = self.deadline;
1284        self.providers
1285            .entry(r.clone())
1286            .or_insert_with(|| Provider::new(addr, deadline, Some(at)));
1287        Some(r)
1288    }
1289
1290    /// An interface token of the required interface at a bound address:
1291    /// its provider and its instance. Any other key is ignored (§2.7).
1292    fn token(&mut self, key: &str, at: Mono) -> Option<(Rank, InstanceId)> {
1293        let Ok(ZkKey::Alive {
1294            addr,
1295            iface,
1296            instance,
1297            ..
1298        }) = parse(key)
1299        else {
1300            return None;
1301        };
1302        if iface != self.iface {
1303            return None;
1304        }
1305        Some((self.provider(addr, at)?, instance))
1306    }
1307
1308    /// The watch heard `i`'s token at `r`'s address, declared or withdrawn:
1309    /// numbered now, kept through a move or not (observer §3.6).
1310    fn note(&mut self, r: &Rank, i: &InstanceId) {
1311        self.heard += 1;
1312        if let Some(p) = self.providers.get_mut(r) {
1313            p.heard.note(i.clone(), self.heard, &p.held);
1314        }
1315    }
1316
1317    /// The round trip after the last move stands: what was kept, applied in
1318    /// order as one change (§2.8).
1319    fn stand(&mut self, at: Mono, reread: &mut Vec<Rank>) {
1320        self.moving = false;
1321        // Per provider: withdrawn before, and whether a withdrawal was kept.
1322        let mut touched: BTreeMap<Rank, (bool, bool)> = BTreeMap::new();
1323        for k in std::mem::take(&mut self.kept) {
1324            let r = match &k {
1325                Kept::Declared(r, _) | Kept::Withdrawn(r, _) | Kept::Read(r, ..) => r.clone(),
1326            };
1327            let Some(p) = self.providers.get_mut(&r) else {
1328                continue;
1329            };
1330            let t = touched.entry(r).or_insert((p.withdrawn, false));
1331            match k {
1332                Kept::Declared(_, i) => {
1333                    p.held.insert(i);
1334                }
1335                Kept::Withdrawn(_, i) => {
1336                    p.held.remove(&i);
1337                    t.1 = true;
1338                }
1339                Kept::Read(_, asked, complete, held) => {
1340                    p.heard.read_into(&mut p.held, asked, complete, held);
1341                }
1342            }
1343        }
1344        for (r, (before, withdrawal)) in touched {
1345            let Some(p) = self.providers.get_mut(&r) else {
1346                continue;
1347            };
1348            if p.held.is_empty() && withdrawal {
1349                p.withdraw(self.deadline, at);
1350                reread.push(r);
1351            } else if !p.held.is_empty() && before {
1352                p.withdrawn = false;
1353            }
1354        }
1355    }
1356}
1357
1358// --- §2.5's outcome 6: a governed interface's incumbents ------------------------------
1359
1360/// The holders of a governed required interface's token, as the watch and
1361/// the reads show them (§2.5, outcome 6): `redundancy`'s presence event,
1362/// moved there with [`Incumbents`] (#987's N1).
1363pub use crate::redundancy::{Asked, Holding};
1364
1365impl Holding {
1366    /// An interface token of `iface` at an address `binding` ranks,
1367    /// declared (`put`) or withdrawn; `None` for any other key.
1368    #[must_use]
1369    pub fn of_token(key: &str, put: bool, iface: &IfaceId, binding: &Binding) -> Option<Self> {
1370        let Ok(ZkKey::Alive {
1371            addr,
1372            iface: i,
1373            instance,
1374            ..
1375        }) = parse(key)
1376        else {
1377            return None;
1378        };
1379        if i != *iface || binding.rank(&addr).is_none() {
1380            return None;
1381        }
1382        Some(if put {
1383            Self::Declared(addr, instance)
1384        } else {
1385            Self::Withdrawn(addr, instance)
1386        })
1387    }
1388}
1389
1390/// The incumbent of each provider of a governed required interface (§2.5,
1391/// outcome 6; `redundancy.v1` §2.10, `redundancy.v2` §2.10): the lowest
1392/// instance holding the interface's token, as the watch and the reads show
1393/// it, and what its descriptors state. Session-free, so that a consumer's
1394/// runtime and a tool's view (#909's BC) follow it alike: moved here from
1395/// `zenkey::arbitration` at BC, and to [`crate::redundancy::Fence`] at
1396/// #987's N1, which fences by `meta.zid` or by run.
1397pub type Incumbents = crate::redundancy::Fence;
1398
1399// --- §2.14, §5: what a tool may conclude ---------------------------------------------
1400
1401/// A question of §5, answered in its states (core O5).
1402#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1403pub enum Answer {
1404    Yes,
1405    No,
1406    /// The question was put, and the reading could not answer it.
1407    Unobservable,
1408    /// Nobody put the question.
1409    NotAsked,
1410    /// The role carries no policy.
1411    NotThisProfiles,
1412}
1413
1414impl Answer {
1415    /// The fixture's token.
1416    #[must_use]
1417    pub fn as_str(self) -> &'static str {
1418        match self {
1419            Self::Yes => "yes",
1420            Self::No => "no",
1421            Self::Unobservable => "unobservable",
1422            Self::NotAsked => "not_asked",
1423            Self::NotThisProfiles => "not_this_profiles",
1424        }
1425    }
1426}
1427
1428impl fmt::Display for Answer {
1429    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1430        f.write_str(self.as_str())
1431    }
1432}
1433
1434/// Why an answer is what it is: the fixture's reason (§2.14).
1435#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1436pub enum Reason {
1437    NoContract,
1438    NotArbitrated,
1439    RevisionsDisagree,
1440    NoProviderContract,
1441    Invalid,
1442    Valid,
1443    Unbound,
1444    NotListened,
1445    Lost,
1446    Selected,
1447    Listening,
1448    DeadMan,
1449    Wildcard,
1450    Shadowed,
1451    Exact,
1452    /// The tool read no consumer's descriptor: no binding, and no view
1453    /// (text 0.2, F-272).
1454    NoDescriptor,
1455}
1456
1457impl Reason {
1458    /// The fixture's token.
1459    #[must_use]
1460    pub fn as_str(self) -> &'static str {
1461        match self {
1462            Self::NoContract => "no_contract",
1463            Self::NotArbitrated => "not_arbitrated",
1464            Self::RevisionsDisagree => "revisions_disagree",
1465            Self::NoProviderContract => "no_provider_contract",
1466            Self::Invalid => "invalid",
1467            Self::Valid => "valid",
1468            Self::Unbound => "unbound",
1469            Self::NotListened => "not_listened",
1470            Self::Lost => "lost",
1471            Self::Selected => "selected",
1472            Self::Listening => "listening",
1473            Self::DeadMan => "dead_man",
1474            Self::Wildcard => "wildcard",
1475            Self::Shadowed => "shadowed",
1476            Self::Exact => "exact",
1477            Self::NoDescriptor => "no_descriptor",
1478        }
1479    }
1480}
1481
1482impl fmt::Display for Reason {
1483    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1484        f.write_str(self.as_str())
1485    }
1486}
1487
1488/// An answer and its reason.
1489#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1490pub struct Judged {
1491    pub answer: Answer,
1492    pub reason: Reason,
1493}
1494
1495impl Judged {
1496    const fn new(answer: Answer, reason: Reason) -> Self {
1497        Self { answer, reason }
1498    }
1499}
1500
1501/// What a tool holds of a role's declaration (§2.14).
1502#[derive(Debug, Clone, PartialEq, Eq)]
1503pub enum Held {
1504    /// The declaring contract not held.
1505    NoContract,
1506    /// The revisions of the required interface held give two declarations.
1507    RevisionsDisagree,
1508    /// The one declaration they give, unread when none is held. A
1509    /// manifest's role, whose policy no tool sees, is
1510    /// [`Declaration::NotArbitrated`].
1511    Read(Declaration),
1512}
1513
1514/// §2.14's declaration over every revision of the required interface a
1515/// tool holds: the one they all give, [`Held::RevisionsDisagree`] when two
1516/// differ, unread when none is held.
1517#[must_use]
1518pub fn held_over(
1519    role: &Role<'_>,
1520    revisions: &[Revision<'_>],
1521    params: &BTreeMap<String, String>,
1522) -> Held {
1523    let mut seen: Option<Declaration> = None;
1524    for rev in revisions {
1525        let d = declaration(role, Some(rev), params);
1526        match &seen {
1527            None => seen = Some(d),
1528            Some(s) if *s == d => {}
1529            Some(_) => return Held::RevisionsDisagree,
1530        }
1531    }
1532    Held::Read(seen.unwrap_or_else(|| declaration(role, None, params)))
1533}
1534
1535/// A tool's own view of a role (§2.14): never the consumer's.
1536#[derive(Debug, Clone, PartialEq, Eq)]
1537pub struct View {
1538    /// How long it has listened.
1539    pub listened: Duration,
1540    /// Whether it knows it lost a sample within the last deadline.
1541    pub lost: bool,
1542    /// The provider its own [`Arbiter`] selects, `None` in the dead-man.
1543    pub active: Option<Addr>,
1544}
1545
1546/// What a tool read of one consumer's role (§2.14).
1547#[derive(Debug, Clone, PartialEq, Eq)]
1548pub struct Reading {
1549    pub declaration: Held,
1550    /// The descriptor's binding, in order; `None` when the tool read no
1551    /// consumer's descriptor, a contract read offline with no consumer
1552    /// (text 0.2, F-272).
1553    pub binding: Option<Binding>,
1554    /// Its own view, `None` when it did not listen.
1555    pub view: Option<View>,
1556}
1557
1558/// The premises every row reads first (§5): the contract held, and the
1559/// role carrying a policy.
1560fn premises(r: &Reading) -> Result<(), Judged> {
1561    match &r.declaration {
1562        Held::NoContract => Err(Judged::new(Answer::Unobservable, Reason::NoContract)),
1563        Held::Read(Declaration::NotArbitrated) => {
1564            Err(Judged::new(Answer::NotThisProfiles, Reason::NotArbitrated))
1565        }
1566        _ => Ok(()),
1567    }
1568}
1569
1570/// §5's first question, "is the role's declaration valid?" (§2.14), with
1571/// the reasons of an invalid one. No is the finding.
1572#[must_use]
1573pub fn judge_declaration(r: &Reading) -> (Judged, Vec<Invalid>) {
1574    match &r.declaration {
1575        Held::NoContract => (
1576            Judged::new(Answer::Unobservable, Reason::NoContract),
1577            Vec::new(),
1578        ),
1579        Held::Read(Declaration::NotArbitrated) => (
1580            Judged::new(Answer::NotThisProfiles, Reason::NotArbitrated),
1581            Vec::new(),
1582        ),
1583        Held::RevisionsDisagree => (
1584            Judged::new(Answer::Unobservable, Reason::RevisionsDisagree),
1585            Vec::new(),
1586        ),
1587        Held::Read(Declaration::Unread) => (
1588            Judged::new(Answer::Unobservable, Reason::NoProviderContract),
1589            Vec::new(),
1590        ),
1591        Held::Read(Declaration::Invalid(why)) => {
1592            (Judged::new(Answer::No, Reason::Invalid), why.clone())
1593        }
1594        Held::Read(Declaration::Arbitrated(_)) => {
1595            (Judged::new(Answer::Yes, Reason::Valid), Vec::new())
1596        }
1597    }
1598}
1599
1600/// §5's second question, "which provider does the tool's view select?"
1601/// (§2.14), with the provider when it selects one. Its answer is the
1602/// tool's own view, never the consumer's. With no consumer's descriptor
1603/// read, after the premises, it is not asked (text 0.2, F-272).
1604#[must_use]
1605pub fn judge_selection(r: &Reading) -> (Judged, Option<Addr>) {
1606    if let Err(j) = premises(r) {
1607        return (j, None);
1608    }
1609    let Some(binding) = &r.binding else {
1610        return (Judged::new(Answer::NotAsked, Reason::NoDescriptor), None);
1611    };
1612    let deadline = match &r.declaration {
1613        Held::Read(Declaration::Arbitrated(a)) => a.deadline,
1614        Held::Read(Declaration::Invalid(_)) => {
1615            return (Judged::new(Answer::Unobservable, Reason::Invalid), None);
1616        }
1617        // The premises, and a declaration not read: the first question's
1618        // answer, without its reasons.
1619        _ => return (judge_declaration(r).0, None),
1620    };
1621    if binding.is_empty() {
1622        return (Judged::new(Answer::No, Reason::Unbound), None);
1623    }
1624    let Some(view) = &r.view else {
1625        return (Judged::new(Answer::NotAsked, Reason::NotListened), None);
1626    };
1627    if view.lost {
1628        return (Judged::new(Answer::Unobservable, Reason::Lost), None);
1629    }
1630    if let Some(a) = &view.active {
1631        return (Judged::new(Answer::Yes, Reason::Selected), Some(a.clone()));
1632    }
1633    if view.listened < deadline {
1634        return (Judged::new(Answer::Unobservable, Reason::Listening), None);
1635    }
1636    (Judged::new(Answer::No, Reason::DeadMan), None)
1637}
1638
1639/// §5's third question, "does the binding leave a priority to an order
1640/// nobody chose?" (§2.4, §2.14), with the wildcard and the shadowed
1641/// entries' positions. Yes is the finding, a warning. With no consumer's
1642/// descriptor read, after the premises, it is not asked (text 0.2, F-272).
1643#[must_use]
1644pub fn judge_binding(r: &Reading) -> (Judged, Vec<usize>, Vec<usize>) {
1645    if let Err(j) = premises(r) {
1646        return (j, Vec::new(), Vec::new());
1647    }
1648    let Some(binding) = &r.binding else {
1649        return (
1650            Judged::new(Answer::NotAsked, Reason::NoDescriptor),
1651            Vec::new(),
1652            Vec::new(),
1653        );
1654    };
1655    let wild = binding.wildcards();
1656    let shadowed = binding.shadowed();
1657    if !wild.is_empty() {
1658        return (Judged::new(Answer::Yes, Reason::Wildcard), wild, shadowed);
1659    }
1660    if !shadowed.is_empty() {
1661        return (
1662            Judged::new(Answer::Yes, Reason::Shadowed),
1663            Vec::new(),
1664            shadowed,
1665        );
1666    }
1667    (
1668        Judged::new(Answer::No, Reason::Exact),
1669        Vec::new(),
1670        Vec::new(),
1671    )
1672}
1673
1674#[cfg(test)]
1675mod tests {
1676    use super::*;
1677
1678    fn arbitrated(deadline_ms: u64) -> Arbitrated {
1679        Arbitrated {
1680            policy: Policy::Priority,
1681            iface: "steer.v1".parse().unwrap(),
1682            token: KindToken::Stream,
1683            template: Template::parse("cmd").unwrap(),
1684            deadline: Duration::from_millis(deadline_ms),
1685            period: None,
1686        }
1687    }
1688
1689    fn arbiter() -> Arbiter {
1690        Arbiter::new(
1691            &arbitrated(300),
1692            Binding::parse(&["lab/safety", "lab/teleop"]).unwrap(),
1693            BTreeMap::new(),
1694        )
1695    }
1696
1697    const SAFETY: &str = "zk2/lab/safety/steer.v1/stream/cmd";
1698
1699    /// Before its start an arbiter decides nothing, and it starts once.
1700    #[test]
1701    fn nothing_before_the_start_and_one_start() {
1702        let mut a = arbiter();
1703        let ms = |n| Mono::after(Duration::from_millis(n));
1704        assert_eq!(
1705            a.observe(ms(0), Event::Sample(Sample::new(SAFETY))),
1706            Step::default()
1707        );
1708        assert_eq!(a.start(ms(1)).switches.len(), 1);
1709        assert_eq!(a.start(ms(2)), Step::default());
1710        assert!(a.dead_man());
1711        let s = a.observe(ms(3), Event::Sample(Sample::new(SAFETY)));
1712        assert_eq!(s.outcome, Some(Outcome::Delivered));
1713        assert_eq!(a.due(), Some(ms(303)));
1714        assert_eq!(a.counts(&"lab/safety".parse().unwrap()).delivered, 1);
1715    }
1716
1717    /// A switch carries `from`'s last arrival, kept across its withdrawal;
1718    /// none from the dead-man.
1719    #[test]
1720    fn a_switch_carries_its_froms_last_arrival() {
1721        let mut a = arbiter();
1722        let ms = |n| Mono::after(Duration::from_millis(n));
1723        assert_eq!(a.start(ms(0)).switches[0].last, None);
1724        let s = a.observe(ms(10), Event::Sample(Sample::new(SAFETY)));
1725        assert_eq!(s.switches[0].last, None, "from the dead-man");
1726        a.observe(ms(20), Event::Sample(Sample::new(SAFETY)));
1727        let s = a.observe(ms(400), Event::Tick);
1728        assert_eq!(s.switches[0].cause, Cause::Deadline);
1729        assert_eq!(s.switches[0].last, Some(ms(20)));
1730        a.observe(ms(410), Event::Sample(Sample::new(SAFETY)));
1731        let s = a.observe(
1732            ms(420),
1733            Event::Withdrawn("zk2/lab/safety/@zk/alive/steer.v1/000000000000000a/0123456789abcdef"),
1734        );
1735        assert_eq!(s.switches[0].cause, Cause::Withdrawn);
1736        assert_eq!(
1737            s.switches[0].last,
1738            Some(ms(410)),
1739            "kept across the withdrawal"
1740        );
1741    }
1742
1743    /// A read never undoes a token heard since it was asked (observer §3.6,
1744    /// 0.38; round 128's F-629): through a move, A's withdrawal and B's
1745    /// declaration kept, the read asked between them comes back complete
1746    /// without B. When the move stands, B holds and the provider stays
1747    /// eligible: no switch. A read asked after B decides it.
1748    #[test]
1749    fn a_read_never_undoes_a_token_heard_since_it_was_asked() {
1750        let mut a = arbiter();
1751        let ms = |n| Mono::after(Duration::from_millis(n));
1752        let safety: Addr = "lab/safety".parse().unwrap();
1753        let alive = |i: u64| format!("zk2/lab/safety/@zk/alive/steer.v1/{i:016x}/0123456789abcdef");
1754        let (ka, kb) = (alive(0xa), alive(0xb));
1755        a.start(ms(0));
1756        a.observe(ms(10), Event::Declared(&ka));
1757        a.observe(ms(20), Event::Sample(Sample::new(SAFETY)));
1758        assert_eq!(a.active(), Some(&safety));
1759        a.observe(ms(30), Event::Moved);
1760        a.observe(ms(40), Event::Withdrawn(&ka));
1761        let asked = a.ask();
1762        a.observe(ms(50), Event::Declared(&kb));
1763        let read = |asked| Event::Read {
1764            address: safety.clone(),
1765            asked,
1766            complete: true,
1767            held: BTreeSet::new(),
1768        };
1769        a.observe(ms(60), read(asked));
1770        let s = a.observe(ms(70), Event::Stood);
1771        assert!(s.switches.is_empty(), "{:?}", s.switches);
1772        assert!(
1773            !a.withdrawn(&safety),
1774            "B holds: the read says nothing of it"
1775        );
1776        assert_eq!(a.active(), Some(&safety));
1777        // Asked after B, the read decides it: gone, though no withdrawal
1778        // makes it ineligible (§2.7).
1779        let asked = a.ask();
1780        a.observe(ms(80), read(asked));
1781        let s = a.observe(ms(90), Event::Withdrawn(&ka));
1782        assert!(
1783            a.withdrawn(&safety),
1784            "none held once A's stale withdrawal is heard"
1785        );
1786        assert_eq!(s.reread, [safety]);
1787    }
1788
1789    /// An event before the last one's instant is the runtime's fault: a
1790    /// debug build says so.
1791    #[test]
1792    #[cfg(debug_assertions)]
1793    #[should_panic(expected = "precedes the last one")]
1794    fn an_event_never_goes_back_in_time() {
1795        let mut a = arbiter();
1796        let ms = |n| Mono::after(Duration::from_millis(n));
1797        a.start(ms(10));
1798        a.observe(ms(5), Event::Tick);
1799    }
1800
1801    /// An entry's text round-trips, `*` included; a malformed one is
1802    /// refused.
1803    #[test]
1804    fn entries_parse_and_print() {
1805        for e in ["lab/safety", "lab/*", "*/teleop", "*/*"] {
1806            assert_eq!(Entry::parse(e).unwrap().to_string(), e);
1807        }
1808        for bad in ["lab", "lab/Safety", "lab/**", "/x"] {
1809            assert!(Entry::parse(bad).is_err(), "{bad}");
1810        }
1811    }
1812}