Skip to main content

zenkey_model/redundancy/
fence.rs

1//! The follower's fence (v2 §2.10, §2.17; v1 §2.10), over either major:
2//! the holders of a governed interface's token at each address, what each
3//! instance's descriptors stated, and the samples it cannot attribute yet,
4//! held for one read of the descriptors. Moved from
5//! `zenkey_model::arbitration::Incumbents` (#909's BC), which is this
6//! type, so that a follower of `redundancy.v2`, arbitration's outcome 6
7//! and a tool's view fence alike (#987's N1).
8//!
9//! ```text
10//! hear(holding) / read_ended(descriptors) ─▶ the holders, the lowest the incumbent        v1 §2.3, §2.10
11//! describe(instance, major, run, zid)     ─▶ its runs, kept while the address is followed v2 §2.10
12//! judge(sample)                           ─▶ accepted │ discarded {no_incumbent, no_run,
13//!                                              not_incumbent, unattributed, no_stamp} │ pending
14//! offer(sample, member, item)             ─▶ the item decided, or held for one read       v2 §2.10
15//! ```
16//!
17//! A follower of a `redundancy.v1` incumbent reads its samples' Zenoh
18//! timestamp ids against its `meta.zid`, by value (v1 §2.10); of a
19//! `redundancy.v2` one, or one whose major it does not know, their runs
20//! against the runs its descriptors stated (v2 §2.10). It follows its
21//! incumbent's revision, and changes as its incumbent does (v2 §2.17).
22//!
23//! There is no I/O here. The runtime hands the fence each presence event
24//! ([`Fence::hear`]), each descriptor it reads or hears put
25//! ([`Fence::describe`]), each sample ([`Fence::offer`]), and, when an
26//! [`Outcome`] says `asks_read`, makes one read of the address's
27//! descriptors and hands its end back ([`Fence::read_ended`]).
28//!
29//! **A read never undoes a token heard since it was asked** (observer
30//! §3.6, 0.38). The read and the watch ride two sessions, which no router
31//! orders. So the runtime asks the fence when it asks a presence read
32//! ([`Fence::ask`]), and the read carries that [`Asked`] back
33//! ([`Holding::Read`]): it applies to no instance whose token the watch
34//! heard declared or withdrawn since.
35
36use std::collections::{BTreeMap, BTreeSet};
37use std::fmt;
38
39use super::Major;
40use crate::grammar::{Addr, InstanceId};
41use crate::wire::{Run, Stamp};
42
43/// A presence event as the fence follows it (v1 §2.10, v2 §2.10): kept
44/// through a move of the watch session, as arbitration's
45/// [`crate::arbitration::Arbiter`] keeps its own (`arbitration.v1` §2.8).
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum Holding {
48    /// The watch heard an interface token declared.
49    Declared(Addr, InstanceId),
50    /// The watch heard one withdrawn.
51    Withdrawn(Addr, InstanceId),
52    /// A read: when it was asked ([`Fence::ask`]), whether it is
53    /// complete, and the instances it shows holding the interface's token
54    /// at the address.
55    Read(Addr, Asked, bool, BTreeSet<InstanceId>),
56}
57
58/// When a presence read was asked, among the token events a reader heard
59/// ([`Fence::ask`], [`crate::arbitration::Arbiter::ask`]). The read
60/// establishes nothing of a token the watch heard since (observer §3.6).
61#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
62pub struct Asked(pub(crate) u64);
63
64/// How many instances no longer held a reader remembers hearing, per
65/// address, beyond those held: a read asked before the oldest of them
66/// ended long since.
67const HEARD_KEPT: usize = 64;
68
69/// When the watch last heard each instance's token at one address,
70/// declared or withdrawn, numbered among the reader's token events
71/// (observer §3.6). Every instance held is kept, and the last
72/// [`HEARD_KEPT`] others.
73#[derive(Debug, Clone, Default)]
74pub(crate) struct Heard(BTreeMap<InstanceId, u64>);
75
76impl Heard {
77    /// The watch heard `instance`'s token declared or withdrawn, the
78    /// reader's event `n`; `held` the instances held now.
79    pub(crate) fn note(&mut self, instance: InstanceId, n: u64, held: &BTreeSet<InstanceId>) {
80        self.0.insert(instance, n);
81        while self.0.len() > HEARD_KEPT + held.len() {
82            let oldest = self
83                .0
84                .iter()
85                .filter(|(i, _)| !held.contains(*i))
86                .min_by_key(|(_, n)| **n)
87                .map(|(i, _)| i.clone());
88            match oldest {
89                Some(i) => self.0.remove(&i),
90                None => break,
91            };
92        }
93    }
94
95    fn since(&self, instance: &InstanceId, asked: Asked) -> bool {
96        self.0.get(instance).is_some_and(|n| *n > asked.0)
97    }
98
99    /// A read asked at `asked` into `known` (observer §3.6): a complete
100    /// read removes each instance it does not show, one not complete none,
101    /// and either adds each it shows. Neither touches an instance whose
102    /// token the watch heard since the read was asked: the read
103    /// establishes nothing of it.
104    pub(crate) fn read_into(
105        &self,
106        known: &mut BTreeSet<InstanceId>,
107        asked: Asked,
108        complete: bool,
109        held: BTreeSet<InstanceId>,
110    ) {
111        if complete {
112            known.retain(|i| held.contains(i) || self.since(i, asked));
113        }
114        known.extend(held.into_iter().filter(|i| !self.since(i, asked)));
115    }
116}
117
118/// What one descriptor of an instance says, as the fence reads it.
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
120pub struct Described {
121    /// The major of the revision its entry names, `None` where its
122    /// contract was not read: then read by run, as `redundancy.v2`'s.
123    pub major: Option<Major>,
124    /// The run it states ([`super::read_descriptor`]), `None` for none.
125    pub run: Option<Run>,
126    /// The `meta.zid` it states, which a `redundancy.v1` incumbent is
127    /// followed by.
128    pub zid: Option<u128>,
129}
130
131/// One sample as the fence reads it (v2 §2.10's table).
132#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
133pub struct Sample {
134    /// The in-band stamp its form carries: a put's envelope's, a delete's
135    /// attachment's, a snapshot's header's for every entry it lists, an
136    /// event's key's occurrence chunk's, a call's reply's as-of mark. `None`
137    /// for a sample with no envelope, which has no run.
138    pub stamp: Option<Stamp>,
139    /// Its Zenoh timestamp's id, where it carries one: what a
140    /// `redundancy.v1` incumbent is followed by.
141    pub timestamp_id: Option<u128>,
142}
143
144impl Sample {
145    /// Its run, `None` with no envelope.
146    #[must_use]
147    pub fn run(&self) -> Option<Run> {
148        self.stamp.map(|s| s.run)
149    }
150}
151
152/// What a sample is to the fence while it is held (v2 §2.10): a state
153/// member keeps one held value, the one core §4.3's consumer rule would
154/// keep; anything else is held alone.
155#[derive(Debug, Clone, PartialEq, Eq)]
156pub enum Member {
157    /// A state member, by its key: one held value.
158    Key(String),
159    /// A stream sample, an event, a heartbeat or a reply: each held alone.
160    /// A follower MAY drop a stream's instead.
161    Alone,
162}
163
164/// Why the fence discards a sample (v2 §2.10, v1 §2.10).
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
166pub enum Discard {
167    /// No incumbent seen: what the follower holds is the last incumbent's
168    /// last word.
169    NoIncumbent,
170    /// A `redundancy.v2` incumbent, and a sample with no envelope.
171    NoRun,
172    /// Another instance's: its run is one another instance's descriptor
173    /// stated, or, under a `redundancy.v1` incumbent, its stamp's id is
174    /// not the incumbent's `meta.zid`.
175    NotIncumbent,
176    /// No descriptor the follower holds states its run, once a read asked
177    /// after it arrived has ended; or a `redundancy.v1` incumbent whose
178    /// `meta.zid` is not held.
179    Unattributed,
180    /// A `redundancy.v1` incumbent, and a sample with no Zenoh timestamp.
181    NoStamp,
182}
183
184impl Discard {
185    /// The fixture's token.
186    #[must_use]
187    pub const fn as_str(self) -> &'static str {
188        match self {
189            Discard::NoIncumbent => "no_incumbent",
190            Discard::NoRun => "no_run",
191            Discard::NotIncumbent => "not_incumbent",
192            Discard::Unattributed => "unattributed",
193            Discard::NoStamp => "no_stamp",
194        }
195    }
196}
197
198impl fmt::Display for Discard {
199    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200        f.write_str(self.as_str())
201    }
202}
203
204/// What the rule decides of one sample (v2 §2.10).
205#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
206pub enum Fenced {
207    /// The incumbent's.
208    Accepted,
209    Discarded(Discard),
210    /// Unattributed, while no read of the address's descriptors asked
211    /// after it arrived has ended: the follower MUST NOT discard it yet.
212    Pending,
213}
214
215impl Fenced {
216    /// The fixture's decision: `accept`, `discard` or `pending`.
217    #[must_use]
218    pub const fn decision(self) -> &'static str {
219        match self {
220            Fenced::Accepted => "accept",
221            Fenced::Discarded(_) => "discard",
222            Fenced::Pending => "pending",
223        }
224    }
225
226    /// The fixture's reason: `incumbent` for an accepted one,
227    /// `unattributed` for a pending one, else the discard's.
228    #[must_use]
229    pub const fn reason(self) -> &'static str {
230        match self {
231            Fenced::Accepted => "incumbent",
232            Fenced::Discarded(d) => d.as_str(),
233            Fenced::Pending => "unattributed",
234        }
235    }
236}
237
238/// What one call to the fence decided, of the item it was given and of
239/// those it held (v2 §2.10; `v2/fences.json`'s sequences).
240#[derive(Debug, Clone, PartialEq, Eq)]
241pub struct Outcome<T> {
242    /// Accepted, in arrival order.
243    pub accepted: Vec<T>,
244    /// Discarded, in arrival order, each with its reason.
245    pub discarded: Vec<(T, Discard)>,
246    /// The item [`Fence::offer`] was given is held.
247    pub held: bool,
248    /// A state member's held value replaced by a newer one, or a new one
249    /// not kept beside the held: within one run the higher seq is kept,
250    /// across two the later arrival.
251    pub superseded: Vec<T>,
252    /// Make one read of the address's descriptors, and hand its end to
253    /// [`Fence::read_ended`].
254    pub asks_read: bool,
255}
256
257impl<T> Default for Outcome<T> {
258    fn default() -> Self {
259        Outcome {
260            accepted: Vec::new(),
261            discarded: Vec::new(),
262            held: false,
263            superseded: Vec::new(),
264            asks_read: false,
265        }
266    }
267}
268
269impl<T> Outcome<T> {
270    fn decide(&mut self, item: T, fenced: Fenced) {
271        match fenced {
272            Fenced::Accepted => self.accepted.push(item),
273            Fenced::Discarded(d) => self.discarded.push((item, d)),
274            Fenced::Pending => unreachable!("a pending sample is held, never decided"),
275        }
276    }
277}
278
279/// What the descriptors of one instance stated, as the follower read them:
280/// each run, kept for as long as it follows the address (v2 §2.10).
281#[derive(Debug, Clone, Default)]
282struct Known {
283    major: Option<Major>,
284    runs: Vec<Run>,
285    zid: Option<u128>,
286}
287
288#[derive(Debug, Clone)]
289struct Held<T> {
290    /// When it arrived, among every sample offered.
291    arrival: u64,
292    member: Member,
293    sample: Sample,
294    item: T,
295}
296
297/// One address as the fence follows it.
298#[derive(Debug, Clone)]
299struct Followed<T> {
300    holders: BTreeSet<InstanceId>,
301    /// When the watch last heard each instance's token.
302    heard: Heard,
303    known: BTreeMap<InstanceId, Known>,
304    /// In arrival order.
305    held: Vec<Held<T>>,
306    /// The outstanding read, asked once the samples before this arrival
307    /// had arrived.
308    asked: Option<u64>,
309}
310
311impl<T> Default for Followed<T> {
312    fn default() -> Self {
313        Followed {
314            holders: BTreeSet::new(),
315            heard: Heard::default(),
316            known: BTreeMap::new(),
317            held: Vec::new(),
318            asked: None,
319        }
320    }
321}
322
323impl<T> Followed<T> {
324    fn learn(&mut self, instance: InstanceId, d: Described) {
325        let k = self.known.entry(instance).or_default();
326        if d.major.is_some() {
327            k.major = d.major;
328        }
329        if d.zid.is_some() {
330            k.zid = d.zid;
331        }
332        if let Some(run) = d.run
333            && !k.runs.contains(&run)
334        {
335            k.runs.push(run);
336        }
337    }
338
339    /// v2 §2.10's rule, the first step that holds: no incumbent; a
340    /// `redundancy.v1` incumbent, by `meta.zid`; no run; the incumbent's
341    /// run; another instance's; unattributed, discarded once `ended`.
342    fn judge(&self, s: &Sample, ended: bool) -> Fenced {
343        use Discard::{NoIncumbent, NoRun, NoStamp, NotIncumbent, Unattributed};
344        let Some(incumbent) = self.holders.iter().next() else {
345            return Fenced::Discarded(NoIncumbent);
346        };
347        let known = self.known.get(incumbent);
348        if let Some(k) = known.filter(|k| k.major == Some(Major::V1)) {
349            let Some(id) = s.timestamp_id else {
350                return Fenced::Discarded(NoStamp);
351            };
352            let Some(zid) = k.zid else {
353                return Fenced::Discarded(Unattributed);
354            };
355            return if id == zid {
356                Fenced::Accepted
357            } else {
358                Fenced::Discarded(NotIncumbent)
359            };
360        }
361        let Some(run) = s.run() else {
362            return Fenced::Discarded(NoRun);
363        };
364        if known.is_some_and(|k| k.runs.contains(&run)) {
365            return Fenced::Accepted;
366        }
367        if self
368            .known
369            .iter()
370            .any(|(i, k)| i != incumbent && k.runs.contains(&run))
371        {
372            return Fenced::Discarded(NotIncumbent);
373        }
374        if ended {
375            Fenced::Discarded(Unattributed)
376        } else {
377            Fenced::Pending
378        }
379    }
380}
381
382/// The incumbent of each address a follower follows, and what it fences
383/// by (v2 §2.10, §2.17; v1 §2.10): the lowest instance holding the
384/// interface's token, as the watch and the reads show it, the major, the
385/// runs and the `meta.zid` each instance's descriptors stated, and the
386/// samples held for one read. `T` is what the runtime holds of a sample;
387/// `arbitration::Incumbents` is `Fence<()>`.
388///
389/// **The hold** (v2 §2.10). A sample whose run no descriptor states is
390/// held, never discarded, until a read of the address's descriptors asked
391/// after it arrived has ended. One read runs at a time: the fence asks one
392/// when it holds a sample and none is outstanding, and asks the next as
393/// that one ends while any is still held. A held sample is decided as soon
394/// as a descriptor read or heard states its run, and every held one when
395/// the read ends, only those that arrived before that read was asked being
396/// discarded `unattributed`. A presence event decides none.
397///
398/// **A read never undoes a token heard since it was asked** (observer
399/// §3.6). Each token the watch hears is numbered as it is heard, kept
400/// through a move or not, and a read applies to no instance heard since
401/// its [`Asked`].
402#[derive(Debug, Clone)]
403pub struct Fence<T = ()> {
404    addrs: BTreeMap<Addr, Followed<T>>,
405    kept: Vec<Holding>,
406    arrivals: u64,
407    /// The token events heard, counted.
408    heard: u64,
409}
410
411impl<T> Default for Fence<T> {
412    fn default() -> Self {
413        Fence {
414            addrs: BTreeMap::new(),
415            kept: Vec::new(),
416            arrivals: 0,
417            heard: 0,
418        }
419    }
420}
421
422impl<T> Fence<T> {
423    /// A presence read is asked now: what it carries back in
424    /// [`Holding::Read`], so it applies to no token heard since.
425    #[must_use]
426    pub fn ask(&self) -> Asked {
427        Asked(self.heard)
428    }
429
430    /// A presence event: kept while a move is pending (`moving`, the
431    /// arbiter's [`crate::arbitration::Arbiter::moving`] before the event),
432    /// else applied. A token declared or withdrawn counts as heard now,
433    /// kept or not.
434    pub fn hear(&mut self, h: Holding, moving: bool) {
435        if let Holding::Declared(a, i) | Holding::Withdrawn(a, i) = &h {
436            self.heard += 1;
437            let f = self.addrs.entry(a.clone()).or_default();
438            f.heard.note(i.clone(), self.heard, &f.holders);
439        }
440        if moving {
441            self.kept.push(h);
442        } else {
443            self.apply(h);
444        }
445    }
446
447    /// The round trip after a move stands: what was kept, applied in the
448    /// order heard (`arbitration.v1` §2.8).
449    pub fn stood(&mut self) {
450        for h in std::mem::take(&mut self.kept) {
451            self.apply(h);
452        }
453    }
454
455    fn apply(&mut self, h: Holding) {
456        match h {
457            Holding::Declared(a, i) => {
458                self.addrs.entry(a).or_default().holders.insert(i);
459            }
460            Holding::Withdrawn(a, i) => {
461                self.addrs.entry(a).or_default().holders.remove(&i);
462            }
463            Holding::Read(a, asked, complete, held) => {
464                let f = self.addrs.entry(a).or_default();
465                f.heard.read_into(&mut f.holders, asked, complete, held);
466            }
467        }
468    }
469
470    /// The incumbent the fence follows at `addr`: the lowest holder (v1
471    /// §2.3), `None` with none seen.
472    #[must_use]
473    pub fn incumbent(&self, addr: &Addr) -> Option<&InstanceId> {
474        self.addrs.get(addr)?.holders.iter().next()
475    }
476
477    /// A descriptor of `instance` read or heard put (v2 §2.10): its major,
478    /// its run, kept beside those read before, and its `meta.zid`. Decides
479    /// each held sample whose run it states.
480    pub fn describe(&mut self, addr: &Addr, instance: InstanceId, d: Described) -> Outcome<T> {
481        let f = self.addrs.entry(addr.clone()).or_default();
482        f.learn(instance, d);
483        let mut out = Outcome::default();
484        let Some(run) = d.run else {
485            return out;
486        };
487        for h in std::mem::take(&mut f.held) {
488            if h.sample.run() != Some(run) {
489                f.held.push(h);
490                continue;
491            }
492            match f.judge(&h.sample, false) {
493                Fenced::Pending => f.held.push(h),
494                v => out.decide(h.item, v),
495            }
496        }
497        out
498    }
499
500    /// The `meta.zid` a `redundancy.v1` instance's descriptor states (v1
501    /// §2.10): [`Fence::describe`] with that major and no run, which
502    /// decides no held sample.
503    pub fn described(&mut self, addr: Addr, instance: InstanceId, zid: u128) {
504        self.describe(
505            &addr,
506            instance,
507            Described {
508                major: Some(Major::V1),
509                run: None,
510                zid: Some(zid),
511            },
512        );
513    }
514
515    /// What v2 §2.10's rule decides of `sample` at `addr`, a read asked
516    /// after it arrived having `ended` or not. Holds nothing.
517    #[must_use]
518    pub fn judge(&self, addr: &Addr, sample: &Sample, ended: bool) -> Fenced {
519        match self.addrs.get(addr) {
520            Some(f) => f.judge(sample, ended),
521            None => Fenced::Discarded(Discard::NoIncumbent),
522        }
523    }
524
525    /// Whether a sample of `addr` stamped by the clock `id` is a
526    /// `redundancy.v1` incumbent's (v1 §2.10): `id` the lowest holder's
527    /// `meta.zid`, by value. Nothing is accepted with no incumbent seen, no
528    /// `meta.zid` held of it, or no stamp.
529    #[must_use]
530    pub fn accepts(&self, addr: &Addr, id: Option<u128>) -> bool {
531        let Some(f) = self.addrs.get(addr) else {
532            return false;
533        };
534        let Some(lowest) = f.holders.iter().next() else {
535            return false;
536        };
537        let Some(zid) = f.known.get(lowest).and_then(|k| k.zid) else {
538            return false;
539        };
540        id == Some(zid)
541    }
542
543    /// The holders of whom no descriptor is held: whose descriptor to get.
544    #[must_use]
545    pub fn undescribed(&self) -> Vec<(Addr, InstanceId)> {
546        self.addrs
547            .iter()
548            .flat_map(|(a, f)| {
549                f.holders
550                    .iter()
551                    .filter(|i| !f.known.contains_key(*i))
552                    .map(move |i| (a.clone(), i.clone()))
553            })
554            .collect()
555    }
556
557    /// Whether a read of `addr`'s descriptors the fence asked for is
558    /// outstanding.
559    #[must_use]
560    pub fn reading(&self, addr: &Addr) -> bool {
561        self.addrs.get(addr).is_some_and(|f| f.asked.is_some())
562    }
563
564    /// One sample of `addr`, `item` being what the runtime holds of it
565    /// (v2 §2.10): decided at once, or held, a state member's one held
566    /// value replacing another's by core §4.3's consumer rule. Asks a read
567    /// when it holds the item and none is outstanding.
568    pub fn offer(&mut self, addr: &Addr, sample: Sample, member: Member, item: T) -> Outcome<T> {
569        let arrival = self.arrivals;
570        self.arrivals += 1;
571        let next = self.arrivals;
572        let f = self.addrs.entry(addr.clone()).or_default();
573        let mut out = Outcome::default();
574        match f.judge(&sample, false) {
575            Fenced::Pending => {}
576            v => {
577                out.decide(item, v);
578                return out;
579            }
580        }
581        if let Member::Key(key) = &member
582            && let Some(at) = f
583                .held
584                .iter()
585                .position(|h| matches!(&h.member, Member::Key(k) if k == key))
586        {
587            let newer = match (f.held[at].sample.stamp, sample.stamp) {
588                (Some(old), Some(new)) if old.run == new.run => new.seq > old.seq,
589                _ => true,
590            };
591            if !newer {
592                out.superseded.push(item);
593                return out;
594            }
595            out.superseded.push(f.held.remove(at).item);
596        }
597        f.held.push(Held {
598            arrival,
599            member,
600            sample,
601            item,
602        });
603        out.held = true;
604        if f.asked.is_none() {
605            f.asked = Some(next);
606            out.asks_read = true;
607        }
608        out
609    }
610
611    /// The end of the read [`Fence::offer`] or a read's end asked for, and
612    /// the descriptors it read (v2 §2.10): each learnt, then every held
613    /// sample decided, those that arrived before the read was asked and
614    /// are still unattributed discarded so. Asks the next read while any
615    /// is still held.
616    pub fn read_ended(
617        &mut self,
618        addr: &Addr,
619        descriptors: impl IntoIterator<Item = (InstanceId, Described)>,
620    ) -> Outcome<T> {
621        let next = self.arrivals;
622        let f = self.addrs.entry(addr.clone()).or_default();
623        for (i, d) in descriptors {
624            f.learn(i, d);
625        }
626        let asked = f.asked.take();
627        let mut out = Outcome::default();
628        for h in std::mem::take(&mut f.held) {
629            let before = asked.is_some_and(|a| h.arrival < a);
630            match f.judge(&h.sample, before) {
631                Fenced::Pending => f.held.push(h),
632                v => out.decide(h.item, v),
633            }
634        }
635        if !f.held.is_empty() {
636            f.asked = Some(next);
637            out.asks_read = true;
638        }
639        out
640    }
641}
642
643#[cfg(test)]
644mod tests {
645    use super::*;
646    use crate::wire::Seq;
647
648    fn id(n: u64) -> InstanceId {
649        format!("{n:016x}").parse().unwrap()
650    }
651
652    fn addr() -> Addr {
653        "lab/ledger".parse().unwrap()
654    }
655
656    fn put(run: u32, seq: u32, zid: Option<u128>) -> Sample {
657        Sample {
658            stamp: Some(Stamp {
659                run: Run::U32(run),
660                seq: Seq::new(seq).unwrap(),
661            }),
662            timestamp_id: zid,
663        }
664    }
665
666    /// `arbitration::Incumbents`' reading, kept (v1 §2.10): the lowest
667    /// holder's `meta.zid`, by value; nothing without one held.
668    #[test]
669    fn a_v1_incumbent_is_followed_by_its_zid() {
670        let mut f: Fence = Fence::default();
671        let a = addr();
672        f.hear(Holding::Declared(a.clone(), id(0xb)), false);
673        f.hear(Holding::Declared(a.clone(), id(0xa)), false);
674        assert_eq!(
675            f.undescribed(),
676            [(a.clone(), id(0xa)), (a.clone(), id(0xb))]
677        );
678        assert!(!f.accepts(&a, Some(0xa1)), "no meta.zid held");
679        f.described(a.clone(), id(0xa), 0xa1);
680        f.described(a.clone(), id(0xb), 0xb1);
681        assert!(f.undescribed().is_empty());
682        assert!(f.accepts(&a, Some(0xa1)));
683        assert!(!f.accepts(&a, Some(0xb1)), "a split: the lowest holder's");
684        assert!(!f.accepts(&a, None));
685        assert_eq!(f.judge(&a, &put(7, 0, Some(0xa1)), false), Fenced::Accepted);
686        f.hear(Holding::Withdrawn(a.clone(), id(0xa)), false);
687        assert!(f.accepts(&a, Some(0xb1)), "it changes with its incumbent");
688    }
689
690    /// What a move keeps is applied when it stands (`arbitration.v1` §2.8).
691    #[test]
692    fn presence_heard_during_a_move_waits_for_it_to_stand() {
693        let mut f: Fence = Fence::default();
694        let a = addr();
695        f.hear(
696            Holding::Read(a.clone(), f.ask(), true, [id(1)].into()),
697            true,
698        );
699        assert_eq!(f.incumbent(&a), None);
700        f.stood();
701        assert_eq!(f.incumbent(&a), Some(&id(1)));
702    }
703
704    /// A read never undoes a token heard since it was asked (observer §3.6,
705    /// 0.38; round 128's F-629). A's withdrawal leaves none, and the read
706    /// asked after it comes back complete without B, whose token the watch
707    /// heard declared meanwhile: B stays the incumbent. A token heard
708    /// withdrawn meanwhile is not brought back either. A read asked after
709    /// both decides each.
710    #[test]
711    fn a_read_never_undoes_a_token_heard_since_it_was_asked() {
712        let mut f: Fence = Fence::default();
713        let a = addr();
714        f.hear(Holding::Declared(a.clone(), id(0xa)), false);
715        f.hear(Holding::Withdrawn(a.clone(), id(0xa)), false);
716        let asked = f.ask();
717        f.hear(Holding::Declared(a.clone(), id(0xb)), false);
718        f.hear(
719            Holding::Read(a.clone(), asked, true, BTreeSet::new()),
720            false,
721        );
722        assert_eq!(
723            f.incumbent(&a),
724            Some(&id(0xb)),
725            "the read says nothing of B"
726        );
727        let asked = f.ask();
728        f.hear(Holding::Withdrawn(a.clone(), id(0xb)), false);
729        f.hear(
730            Holding::Read(a.clone(), asked, true, [id(0xb)].into()),
731            false,
732        );
733        assert_eq!(f.incumbent(&a), None, "nor brings B back");
734        f.hear(Holding::Declared(a.clone(), id(0xc)), false);
735        let asked = f.ask();
736        f.hear(
737            Holding::Read(a.clone(), asked, true, [id(0xd)].into()),
738            false,
739        );
740        assert_eq!(
741            f.incumbent(&a),
742            Some(&id(0xd)),
743            "asked after C: C read gone, D read held"
744        );
745        // Not complete: it adds, and removes nothing.
746        let asked = f.ask();
747        f.hear(
748            Holding::Read(a.clone(), asked, false, [id(0x9)].into()),
749            false,
750        );
751        assert_eq!(f.incumbent(&a), Some(&id(0x9)));
752    }
753
754    /// Through a move (`arbitration.v1` §2.8), in either order kept: a
755    /// token heard declared after the read was asked stands.
756    #[test]
757    fn a_read_kept_through_a_move_never_undoes_a_token_heard_since() {
758        for read_first in [true, false] {
759            let mut f: Fence = Fence::default();
760            let a = addr();
761            f.hear(Holding::Declared(a.clone(), id(0xa)), false);
762            f.hear(Holding::Withdrawn(a.clone(), id(0xa)), true);
763            let asked = f.ask();
764            let read = Holding::Read(a.clone(), asked, true, BTreeSet::new());
765            if read_first {
766                f.hear(read, true);
767                f.hear(Holding::Declared(a.clone(), id(0xb)), true);
768            } else {
769                f.hear(Holding::Declared(a.clone(), id(0xb)), true);
770                f.hear(read, true);
771            }
772            f.stood();
773            assert_eq!(f.incumbent(&a), Some(&id(0xb)), "read first: {read_first}");
774        }
775    }
776
777    /// What the fence remembers hearing is bounded, every holder's kept:
778    /// a holder heard since a read was asked stands however many others
779    /// came and went meanwhile.
780    #[test]
781    fn a_holder_heard_since_stands_past_the_bound() {
782        let mut f: Fence = Fence::default();
783        let a = addr();
784        let asked = f.ask();
785        f.hear(Holding::Declared(a.clone(), id(0xffff)), false);
786        for n in 1..=(3 * HEARD_KEPT as u64) {
787            f.hear(Holding::Declared(a.clone(), id(n)), false);
788            f.hear(Holding::Withdrawn(a.clone(), id(n)), false);
789        }
790        assert!(f.addrs[&a].heard.0.len() <= HEARD_KEPT + 1);
791        f.hear(
792            Holding::Read(a.clone(), asked, true, BTreeSet::new()),
793            false,
794        );
795        assert_eq!(f.incumbent(&a), Some(&id(0xffff)));
796    }
797
798    /// A follower reads its incumbent's revision (v2 §2.17): a v1 one by
799    /// zid, whatever the run, then a v2 one by run, whatever the stamp.
800    #[test]
801    fn a_follower_follows_each_incumbent_by_its_own_major() {
802        let mut f: Fence<&str> = Fence::default();
803        let a = addr();
804        f.hear(
805            Holding::Read(a.clone(), f.ask(), true, [id(1)].into()),
806            false,
807        );
808        let v1 = Described {
809            major: Some(Major::V1),
810            run: Some(Run::U32(0x11)),
811            zid: Some(0x1),
812        };
813        let v2 = Described {
814            major: Some(Major::V2),
815            run: Some(Run::U32(0x22)),
816            zid: Some(0x2),
817        };
818        f.describe(&a, id(1), v1);
819        f.describe(&a, id(2), v2);
820        let out = f.offer(&a, put(0x22, 0, Some(0x1)), Member::Alone, "v1 stamp");
821        assert_eq!(out.accepted, ["v1 stamp"], "the run is not read");
822        f.hear(Holding::Declared(a.clone(), id(2)), false);
823        f.hear(Holding::Withdrawn(a.clone(), id(1)), false);
824        let out = f.offer(&a, put(0x22, 1, Some(0x1)), Member::Alone, "v2 run");
825        assert_eq!(out.accepted, ["v2 run"], "the stamp is not read");
826        let out = f.offer(&a, put(0x11, 2, None), Member::Alone, "v1 run");
827        assert_eq!(out.discarded, [("v1 run", Discard::NotIncumbent)]);
828    }
829
830    /// A held sample waits for the read; a sample that is decided at once
831    /// asks none (v2 §2.10).
832    #[test]
833    fn only_a_held_sample_asks_a_read() {
834        let mut f: Fence<u8> = Fence::default();
835        let a = addr();
836        f.hear(
837            Holding::Read(a.clone(), f.ask(), true, [id(1)].into()),
838            false,
839        );
840        f.describe(
841            &a,
842            id(1),
843            Described {
844                major: Some(Major::V2),
845                run: Some(Run::U32(1)),
846                zid: None,
847            },
848        );
849        let out = f.offer(&a, put(1, 0, None), Member::Key("balance".into()), 0);
850        assert_eq!((out.accepted, out.asks_read), (vec![0], false));
851        assert!(!f.reading(&a));
852        let out = f.offer(&a, put(9, 0, None), Member::Key("balance".into()), 1);
853        assert!(out.held && out.asks_read);
854        assert!(f.reading(&a));
855        let out = f.read_ended(&a, []);
856        assert_eq!(out.discarded, [(1, Discard::Unattributed)]);
857        assert!(!out.asks_read && !f.reading(&a));
858    }
859}