Skip to main content

zenkey_model/
seed.rs

1//! A late joiner's merge (core §4.2, §4.3): per key, which arriving
2//! sample a late joiner keeps, whichever path — S4's GET or its
3//! subscription — brought it.
4//!
5//! **In-band stamps** (core §4.3): an owner's sample carries a zk2c
6//! envelope (core §7.5, [`crate::wire::carries`]), and is ordered by its
7//! envelope's run and seq, never by a Zenoh timestamp it may also carry on
8//! a resource §4.3's table lists ([`Mark::of`]). [`versus_in`] compares two
9//! marks of one key, in the [`Order`] its kind picks:
10//!
11//! ```text
12//! held        incoming    versus_in
13//! run r · s   run r · s'  Plain (state, events): s' > s Newer, s' = s Same, s' < s Older
14//!                         Serial (a stream key): d = (s' − s) mod 2^24;
15//!                           d = 0 Same, 1 ≤ d < 2^23 Newer, d > 2^23 Older, d = 2^23 Unordered
16//! run r       run r'≠r    Unordered: nothing orders two runs, two widths of one value included
17//! Zenoh       in-band     Unordered, either way round: a sample with no envelope beside one
18//! Zenoh t·i   Zenoh t'·i' the Stamp order below
19//! ```
20//!
21//! An equal seq is the same value: S2's reply is the stored bytes. An
22//! unordered arrival is accepted wherever an older one is refused: a
23//! tool's merge keeps the later arrival ([`admits_mark_in`], observer
24//! §4.1), a consumer takes it as §4.3 takes another run
25//! ([`consumer_accepts`]), and an archive records it, refusing an outdated
26//! put only within a run. [`versus`], [`admits_mark`] and
27//! [`in_band_order`] are the plain order's, which state keeps: a
28//! consumer's rule and an archive read state alone.
29//!
30//! **A sample with no envelope** (core §4.2) — an `@stream` sample, a
31//! foreign key's (§1.7), or one whose owner broke §4.3 — is ordered among
32//! samples with no envelope by its Zenoh timestamp:
33//!
34//! ```text
35//! Stamp { time, id }        an NTP64 time, and the 128-bit id of the HLC
36//!                           that issued it (a session's zid)
37//! Stamp ordering            time first; on equal times, the id's 16 bytes
38//!                           little-endian, compared from the first: zenoh's
39//!                           `Timestamp` order, not the ids' integer order
40//! admits(held, incoming)    whether the sample replaces what the key holds
41//! ```
42//!
43//! That rule is zenoh's `Latest` consolidation (§4.1) read as a merge:
44//!
45//! - a stamped sample is kept when the key holds nothing, an unstamped
46//!   sample, or a lower stamp; an equal stamp is the same mutation, kept
47//!   once; a higher one held makes it stale;
48//! - an unstamped sample — an `@stream` sample or a foreign key's, from a
49//!   session with no HLC through no router that stamps — ranks below every
50//!   stamped one, an in-band stamp included, as `Latest` ranks an
51//!   unstamped reply lowest: kept when the key holds nothing or only
52//!   unstamped samples, the later arrival replacing the earlier, and never
53//!   over a stamped one.
54//!
55//! A deletion (a live delete, or a `reply_del` with its stamp) merges as a
56//! put does: the kind never decides. Pure: the fixtures in
57//! `spec/conformance/seed/` pin it (`inband.json`, `merge.json`), and a
58//! tool hands its samples' stamps over as values.
59//!
60//! **A conditional read** (core 0.110 §4.2; #986's J1): a reader that holds
61//! a member's value asks for it again and names the mutation it holds
62//! ([`held_stamp`], never anything but that mutation's in-band stamp). Its
63//! GET is an [`Asked`], on one concrete key ([`is_concrete`], read from its
64//! selector's key expression, [`selector_key`]); a held stamp among its arrivals is the owner's
65//! answer only as [`Asked::read`] says, [`HeldRead::Unchanged`], and any
66//! other is refused `held`. An answer merges nothing: [`unchanged`] says
67//! what it finds the reader holding, the mutation heard again (for
68//! [`apply_snapshot`]'s guard, [`HeldMember::heard_after`]), a later value
69//! that stands, or nothing, where the reader reads again.
70//! `spec/conformance/seed/held.json` pins it.
71
72use std::cmp::Ordering;
73use std::fmt;
74
75use crate::grammar::KindToken;
76use crate::wire;
77
78/// A Zenoh timestamp as the merge compares it (§4.1, Appendix B): its
79/// time, an NTP64 value whose unit is 2^−32 s, and the id of the HLC that
80/// issued it, a 128-bit value (the issuing session's zid).
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
82pub struct Stamp {
83    /// The NTP64 time.
84    pub time: u64,
85    /// The HLC id, as its 128-bit value. Written as lowercase hexadecimal
86    /// without leading zeros, as zenoh writes an id and a zid.
87    pub id: u128,
88}
89
90impl Stamp {
91    /// A stamp from its NTP64 time and its id as zenoh writes it: lowercase
92    /// hexadecimal, no leading zeros, not 0. `None` for any other spelling.
93    #[must_use]
94    pub fn parse(time: u64, id: &str) -> Option<Stamp> {
95        let valid = !id.is_empty()
96            && id.len() <= 32
97            && !id.starts_with('0')
98            && id
99                .bytes()
100                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
101        if !valid {
102            return None;
103        }
104        let id = u128::from_str_radix(id, 16).ok()?;
105        Some(Stamp { time, id })
106    }
107}
108
109impl fmt::Display for Stamp {
110    /// zenoh's own spelling: the time in decimal, `/`, the id in hex.
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        write!(f, "{}/{:x}", self.time, self.id)
113    }
114}
115
116impl Ord for Stamp {
117    /// zenoh's `Timestamp` order (uhlc 0.8): by time; on equal times, by
118    /// the id's 16 bytes little-endian — least significant first —
119    /// compared from the first byte. So the least significant byte that
120    /// differs decides, and `100` (hex) orders below `2`, which their
121    /// values would not.
122    fn cmp(&self, other: &Self) -> Ordering {
123        self.time
124            .cmp(&other.time)
125            .then_with(|| self.id.to_le_bytes().cmp(&other.id.to_le_bytes()))
126    }
127}
128
129impl PartialOrd for Stamp {
130    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
131        Some(self.cmp(other))
132    }
133}
134
135/// What orders a sample of a key: an envelope's in-band stamp (core §7.5)
136/// when it carried one, else its Zenoh timestamp.
137#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
138pub enum Mark {
139    /// A Zenoh timestamp, on a sample with no envelope.
140    Zenoh(Stamp),
141    /// An envelope's run and seq.
142    InBand(wire::Stamp),
143}
144
145impl Mark {
146    /// A sample's mark: its in-band stamp when it carried an envelope, its
147    /// Zenoh timestamp otherwise, `None` when it carried neither. An
148    /// enveloped sample's Zenoh timestamp is its time where a profile
149    /// reads one, never its order.
150    #[must_use]
151    pub fn of(inband: Option<wire::Stamp>, zenoh: Option<Stamp>) -> Option<Mark> {
152        inband.map(Mark::InBand).or_else(|| zenoh.map(Mark::Zenoh))
153    }
154}
155
156/// How an arrival marked `incoming` compares with what a key holds, marked
157/// `held`. See the module doc's table.
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159pub enum Versus {
160    /// Newer: it replaces what is held.
161    Newer,
162    /// The same mutation, kept once: an equal Zenoh stamp, or an equal seq
163    /// within a run.
164    Same,
165    /// Older: refused or ignored wherever an older stamp is.
166    Older,
167    /// Not comparable: in-band stamps of two runs, or an in-band stamp
168    /// beside a Zenoh one. Accepted, as a value under another id is.
169    Unordered,
170}
171
172/// How two seqs of one key, within one run, compare (core §4.3): by the
173/// key's kind.
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
175pub enum Order {
176    /// A state's or an event's seqs, as integers. The owner keeps one seq
177    /// per run for its state and events, which never wraps: within a run a
178    /// key's held seq can trail a newer one by more than 2^23, which serial
179    /// order would read as older.
180    #[default]
181    Plain,
182    /// A stream key's seqs, by serial arithmetic over 24 bits (RFC 1982):
183    /// each stream key's seq is its own, and wraps modulo 2^24.
184    Serial,
185}
186
187impl Order {
188    /// The order a kind's seqs take: a stream's (`stream`, `@stream`) is
189    /// serial, every other kind's plain. An `@stream` sample carries no
190    /// envelope at core 0.73; a reader that meets one orders it as a
191    /// stream key's.
192    #[must_use]
193    pub const fn of_kind(kind: KindToken) -> Order {
194        match kind {
195            KindToken::Stream | KindToken::ExplicitStream => Order::Serial,
196            _ => Order::Plain,
197        }
198    }
199
200    /// The order of `key`'s seqs, by its kind token as the grammar reads it
201    /// ([`wire::enveloped_kind`]); plain for a key whose samples carry no
202    /// envelope, whose marks are never in-band.
203    #[must_use]
204    pub fn of_key(key: &str) -> Order {
205        wire::enveloped_kind(key).map_or(Order::Plain, Order::of_kind)
206    }
207
208    /// `incoming` against `held`, two seqs of one run: `Greater` when it is
209    /// newer, `Equal` when it is the same, `Less` when it is older, and
210    /// `None` when serial order leaves them unordered, exactly 2^23 apart.
211    #[must_use]
212    pub fn seqs(self, held: wire::Seq, incoming: wire::Seq) -> Option<Ordering> {
213        match self {
214            Order::Plain => Some(incoming.get().cmp(&held.get())),
215            Order::Serial => {
216                const HALF: u32 = 1 << 23;
217                let d = incoming.get().wrapping_sub(held.get()) & wire::Seq::MAX.get();
218                match d {
219                    0 => Some(Ordering::Equal),
220                    d if d < HALF => Some(Ordering::Greater),
221                    d if d > HALF => Some(Ordering::Less),
222                    _ => None,
223                }
224            }
225        }
226    }
227}
228
229/// Two in-band stamps of one key, in the plain order: within one run (the
230/// same width and the same value), the higher seq is newer and an equal
231/// seq is the same value; across two runs, `None`, since nothing orders
232/// them.
233#[must_use]
234pub fn in_band_order(held: wire::Stamp, incoming: wire::Stamp) -> Option<Ordering> {
235    in_band_order_in(Order::Plain, held, incoming)
236}
237
238/// [`in_band_order`], in the order `order` (a stream key's is serial).
239#[must_use]
240pub fn in_band_order_in(
241    order: Order,
242    held: wire::Stamp,
243    incoming: wire::Stamp,
244) -> Option<Ordering> {
245    if held.run == incoming.run {
246        order.seqs(held.seq, incoming.seq)
247    } else {
248        None
249    }
250}
251
252/// `incoming` against `held`, by the module doc's table, in the plain
253/// order: a state's.
254#[must_use]
255pub fn versus(held: Mark, incoming: Mark) -> Versus {
256    versus_in(Order::Plain, held, incoming)
257}
258
259/// `incoming` against `held`, two marks of one key whose seqs take
260/// `order` ([`Order::of_key`]), by the module doc's table.
261#[must_use]
262pub fn versus_in(order: Order, held: Mark, incoming: Mark) -> Versus {
263    let ordering = match (held, incoming) {
264        (Mark::Zenoh(h), Mark::Zenoh(i)) => Some(i.cmp(&h)),
265        (Mark::InBand(h), Mark::InBand(i)) => in_band_order_in(order, h, i),
266        (Mark::Zenoh(_), Mark::InBand(_)) | (Mark::InBand(_), Mark::Zenoh(_)) => None,
267    };
268    match ordering {
269        Some(Ordering::Greater) => Versus::Newer,
270        Some(Ordering::Equal) => Versus::Same,
271        Some(Ordering::Less) => Versus::Older,
272        None => Versus::Unordered,
273    }
274}
275
276/// §4.3's consumer rule over marks, for a state key: within one run by
277/// seq, a value of another run accepted, as is one beside a value held
278/// under a Zenoh timestamp; a value with no envelope by time within one
279/// timestamp id, a value under another id accepted. `held` is the mark of
280/// the value the key holds, `None` for nothing.
281#[must_use]
282pub fn consumer_accepts(held: Option<Mark>, incoming: Mark) -> bool {
283    match (held, incoming) {
284        (None, _) => true,
285        (Some(Mark::Zenoh(h)), Mark::Zenoh(i)) if h.id != i.id => true,
286        (Some(h), i) => matches!(versus(h, i), Versus::Newer | Versus::Unordered),
287    }
288}
289
290/// What a late joiner holds of one key.
291#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
292pub enum Held {
293    /// Nothing yet.
294    #[default]
295    Nothing,
296    /// Only unstamped samples.
297    Unstamped,
298    /// A stamped sample, with the greatest stamp kept.
299    Stamped(Stamp),
300    /// A sample with an in-band stamp (core §7.5): the last kept.
301    InBand(wire::Stamp),
302}
303
304impl Held {
305    /// What the key holds once a sample with `incoming`'s stamp is kept.
306    #[must_use]
307    pub fn after(self, incoming: Option<Stamp>) -> Held {
308        self.after_mark(incoming.map(Mark::Zenoh))
309    }
310
311    /// [`Held::after`], for a sample marked `incoming`.
312    #[must_use]
313    pub fn after_mark(self, incoming: Option<Mark>) -> Held {
314        match incoming {
315            Some(Mark::Zenoh(s)) => Held::Stamped(s),
316            Some(Mark::InBand(s)) => Held::InBand(s),
317            None => match self.mark() {
318                Some(_) => self,
319                None => Held::Unstamped,
320            },
321        }
322    }
323
324    /// The mark of what is held, `None` for nothing or only unstamped
325    /// samples.
326    #[must_use]
327    pub fn mark(self) -> Option<Mark> {
328        match self {
329            Held::Nothing | Held::Unstamped => None,
330            Held::Stamped(s) => Some(Mark::Zenoh(s)),
331            Held::InBand(s) => Some(Mark::InBand(s)),
332        }
333    }
334}
335
336/// Whether a late joiner keeps a sample stamped `incoming` (`None`:
337/// unstamped) over what its key holds (core §4.2, 0.27). See the module
338/// doc for the rule.
339#[must_use]
340pub fn admits(held: Held, incoming: Option<Stamp>) -> bool {
341    admits_mark(held, incoming.map(Mark::Zenoh))
342}
343
344/// [`admits`], for a sample marked `incoming`, in the plain order: a
345/// newer mark is kept, an equal or older one is not, and an unordered one
346/// is, so across two runs (or two wires) a tool's merge keeps the later
347/// arrival, there being no time to keep the later of. An unstamped sample
348/// ranks below every mark, an in-band one included.
349#[must_use]
350pub fn admits_mark(held: Held, incoming: Option<Mark>) -> bool {
351    admits_mark_in(Order::Plain, held, incoming)
352}
353
354/// [`admits_mark`], for a key whose seqs take `order` ([`Order::of_key`]):
355/// a tool's merge of a stream key keeps a sample across its seq's wrap,
356/// and the later arrival of two exactly 2^23 apart.
357#[must_use]
358pub fn admits_mark_in(order: Order, held: Held, incoming: Option<Mark>) -> bool {
359    match (held.mark(), incoming) {
360        (None, _) => true,
361        (Some(_), None) => false,
362        (Some(h), Some(i)) => matches!(versus_in(order, h, i), Versus::Newer | Versus::Unordered),
363    }
364}
365
366/// One key's arrivals, merged in arrival order: which ones are kept.
367#[must_use]
368pub fn merge(arrivals: &[Option<Stamp>]) -> Vec<bool> {
369    let mut held = Held::Nothing;
370    arrivals
371        .iter()
372        .map(|incoming| {
373            let kept = admits(held, *incoming);
374            if kept {
375                held = held.after(*incoming);
376            }
377            kept
378        })
379        .collect()
380}
381
382/// The held stamp a reader may send for a member (core §4.2, "What a
383/// reader sends"): the in-band stamp of the mutation it holds, as the owner
384/// wrote it, where `holds` is that mutation's mark. That is its put's
385/// envelope's, its delete's attachment's, or its snapshot entry's, the
386/// entry's own run or the header's and the entry's seq
387/// ([`crate::collection::Member::stamp`]). `None` for a reader that holds
388/// nothing for the member, and for a value with no envelope: never a held
389/// stamp made of a Zenoh timestamp, of a snapshot's asof, or of another
390/// key's stamp.
391#[must_use]
392pub fn held_stamp(holds: Option<Mark>) -> Option<wire::HeldStamp> {
393    match holds {
394        Some(Mark::InBand(stamp)) => Some(wire::HeldStamp::new(stamp)),
395        Some(Mark::Zenoh(_)) | None => None,
396    }
397}
398
399/// The key expression of a GET's selector: everything before its first
400/// `?`, where zenoh's parameters begin, and the whole selector where it has
401/// none. A reply rides a key, never the parameters, and an owner reads the
402/// key alone, so the parameters decide neither whether a GET is on one
403/// concrete key nor which key its answer comes on.
404#[must_use]
405pub fn selector_key(selector: &str) -> &str {
406    selector.split_once('?').map_or(selector, |(key, _)| key)
407}
408
409/// Whether a GET's selector is one concrete key (core §4.2, "A conditional
410/// read"): its key expression ([`selector_key`]) has no wildcard, so no
411/// `*`, no `**` and no `$*` chunk. The text counts chunks, which a
412/// selector's parameters are not: a `*` after the `?` is no wildcard, and
413/// `…/plans/vehicle-01?_time=*` is one concrete key.
414#[must_use]
415pub fn is_concrete(selector: &str) -> bool {
416    !selector_key(selector).contains('*')
417}
418
419/// A reader's state GET, as it reads a held stamp among its arrivals (core
420/// §4.2, "A held stamp in answer"): its selector, and the held stamp it
421/// carried, `None` for a GET with no payload.
422#[derive(Debug, Clone, Copy, PartialEq, Eq)]
423pub struct Asked<'a> {
424    /// The GET's selector, as its reader's session spells the keys it
425    /// hears: base-relative in a namespace, a wire key in none. It may
426    /// carry parameters after a `?`, which are not part of its key
427    /// ([`selector_key`]).
428    pub key: &'a str,
429    /// The held stamp the GET carried.
430    pub held: Option<wire::Stamp>,
431}
432
433/// How a held stamp among a reader's arrivals reads ([`Asked::read`]).
434#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
435pub enum HeldRead {
436    /// The owner's answer: when it answered, the member's last mutation
437    /// was the one the stamp names. It merges nothing ([`unchanged`]).
438    Unchanged,
439    /// No owner's answer: it establishes nothing, merges nothing, counts
440    /// as nothing heard, and is counted undecodable, refused as `held`
441    /// ([`wire::Refusal::Held`]).
442    Refused,
443}
444
445impl HeldRead {
446    /// `unchanged`, or the refusal's token `held`, as
447    /// `spec/conformance/seed/held.json` spells them.
448    #[must_use]
449    pub const fn token(self) -> &'static str {
450        match self {
451            HeldRead::Unchanged => "unchanged",
452            HeldRead::Refused => "held",
453        }
454    }
455}
456
457impl Asked<'_> {
458    /// Whether the GET is a conditional read as its reader made it: it
459    /// carried a held stamp on one concrete key.
460    #[must_use]
461    pub fn is_conditional(&self) -> bool {
462        self.held.is_some() && is_concrete(self.key)
463    }
464
465    /// A held stamp that arrived on `key` carrying `stamp`, by this GET
466    /// (`by_get`) or on a subscription: the owner's answer only as a reply
467    /// to the GET that carried the same one, on that GET's one concrete
468    /// key, its selector's key expression ([`selector_key`]). The same one
469    /// has the same run, in width and value, and the same seq. A consumer
470    /// or a tool MUST NOT read any other as unchanged.
471    #[must_use]
472    pub fn read(&self, by_get: bool, key: &str, stamp: wire::Stamp) -> HeldRead {
473        if by_get
474            && self.is_conditional()
475            && key == selector_key(self.key)
476            && self.held == Some(stamp)
477        {
478            HeldRead::Unchanged
479        } else {
480            HeldRead::Refused
481        }
482    }
483}
484
485/// What an owner's unchanged answer finds its reader holding for the
486/// member ([`unchanged`]). The answer carries no value and merges none.
487#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
488pub enum Unchanged {
489    /// The reader still holds the mutation the stamp names: the answer
490    /// counts as that mutation heard again, by the GET. The omission
491    /// rule's guard reads it so ([`HeldMember::heard_after`]): another
492    /// run's snapshot that lists no entry for it then spares it.
493    HeardAgain,
494    /// The reader holds another value by then, heard while its GET was
495    /// out: that value stands. An answer never steps a member back.
496    Stands,
497    /// The reader holds nothing for the member by then: its GET gave it no
498    /// value. It reads again, with no held stamp.
499    ReadAgain,
500}
501
502/// What an unchanged answer naming `answer` finds, where the reader holds
503/// `held` for the member as the answer arrives (core §4.2, "What unchanged
504/// says").
505#[must_use]
506pub fn unchanged(held: Held, answer: wire::Stamp) -> Unchanged {
507    match held {
508        Held::Nothing => Unchanged::ReadAgain,
509        Held::InBand(s) if s == answer => Unchanged::HeardAgain,
510        Held::InBand(_) | Held::Stamped(_) | Held::Unstamped => Unchanged::Stands,
511    }
512}
513
514/// What a late joiner holds of one key as a snapshot completes, for the
515/// omission rule ([`apply_snapshot`]): the key, the mark of the value or
516/// deletion it holds, and whether it heard that after it asked the GET, by
517/// either path (an arrival with that same mark heard again counts).
518#[derive(Debug, Clone, Copy, PartialEq, Eq)]
519pub struct HeldMember<'a> {
520    pub key: &'a str,
521    pub mark: Option<Mark>,
522    pub heard_after: bool,
523}
524
525/// The omission rule (core §4.2; #977's E2 defines it, E3's readers apply
526/// it, through [`crate::collection::omit`]): a late joiner holds `snapshot`
527/// complete, heard on `key`, its collection's snapshot key or a member's
528/// key. Each member of the collection at `key` or under it
529/// (`of_collection` says which keys are its members) that the snapshot
530/// lists neither live nor as a tombstone has no value, unless what the
531/// late joiner holds of it is newer than the snapshot:
532///
533/// - a value under the snapshot's run with a seq above its asof;
534/// - a value under another run, or with no in-band stamp, that it heard
535///   after it asked the GET.
536///
537/// Returns the keys of `held` it drops, in `held`'s order. An incomplete
538/// snapshot drops nothing, which is the caller's to know: it calls this
539/// once [`crate::collection::Heard::complete`] says so. So a delete the
540/// owner made beyond its window still reaches the late joiner.
541pub fn apply_snapshot<'a>(
542    snapshot: &crate::collection::Snapshot,
543    key: &str,
544    of_collection: impl Fn(&str) -> bool,
545    held: impl IntoIterator<Item = HeldMember<'a>>,
546) -> Vec<&'a str> {
547    let listed: std::collections::BTreeSet<String> = snapshot
548        .live
549        .iter()
550        .map(|e| e.id.as_str())
551        .chain(snapshot.tombs.iter().map(|t| t.id.as_str()))
552        .map(|id| crate::collection::member_key(key, id))
553        .collect();
554    let at_or_under = |k: &str| {
555        k == key
556            || k.strip_prefix(key)
557                .is_some_and(|rest| rest.starts_with('/'))
558    };
559    held.into_iter()
560        .filter(|h| at_or_under(h.key) && of_collection(h.key) && !listed.contains(h.key))
561        .filter(|h| match h.mark {
562            Some(Mark::InBand(s)) if s.run == snapshot.run => s.seq <= snapshot.asof,
563            _ => !h.heard_after,
564        })
565        .map(|h| h.key)
566        .collect()
567}
568
569#[cfg(test)]
570mod tests {
571    use super::*;
572
573    fn s(time: u64, id: &str) -> Option<Stamp> {
574        Some(Stamp::parse(time, id).expect("a stamp"))
575    }
576
577    #[test]
578    fn stamps_order_by_time_then_by_the_ids_bytes_from_the_least_significant() {
579        assert!(s(2, "1") > s(1, "ff"));
580        assert!(s(5, "2") > s(5, "100"), "the low byte decides: 02 > 00");
581        assert!(
582            s(5, "102") > s(5, "201"),
583            "low bytes 02 > 01, whatever the high ones"
584        );
585        assert!(s(5, "1ff") > s(5, "2fe"), "ff > fe");
586        assert_eq!(s(5, "ab").cmp(&s(5, "ab")), Ordering::Equal);
587        assert_eq!(Stamp::parse(7, "1bc0").unwrap().to_string(), "7/1bc0");
588        for bad in ["", "0", "01", "AB", "g", &"f".repeat(33)] {
589            assert_eq!(Stamp::parse(1, bad), None, "{bad:?}");
590        }
591    }
592
593    #[test]
594    fn the_merge_is_latest_read_as_a_merge() {
595        // A newer stamp replaces; an older or equal one is not kept.
596        assert_eq!(
597            merge(&[s(1, "a"), s(2, "a"), s(2, "a"), s(1, "a")]),
598            [true, true, false, false]
599        );
600        // Unstamped below every stamp, replacing only another unstamped.
601        assert_eq!(
602            merge(&[None, None, s(1, "a"), None]),
603            [true, true, true, false]
604        );
605        assert_eq!(merge(&[s(1, "a"), None]), [true, false]);
606        // Equal times: the ids as zenoh compares them.
607        assert_eq!(merge(&[s(9, "2"), s(9, "100")]), [true, false]);
608        assert_eq!(merge(&[s(9, "100"), s(9, "2")]), [true, true]);
609    }
610
611    fn ib(run: wire::Run, seq: u32) -> Mark {
612        Mark::InBand(wire::Stamp {
613            run,
614            seq: wire::Seq::new(seq).expect("a seq"),
615        })
616    }
617
618    /// Rule 4 (#976's A2): within one run, the higher seq is newer and an
619    /// equal seq is the same value (S2's reply is the stored bytes).
620    #[test]
621    fn within_a_run_the_higher_seq_is_newer() {
622        use wire::Run::{U16, U32};
623        assert_eq!(versus(ib(U16(5), 7), ib(U16(5), 8)), Versus::Newer);
624        assert_eq!(versus(ib(U16(5), 7), ib(U16(5), 7)), Versus::Same);
625        assert_eq!(versus(ib(U16(5), 7), ib(U16(5), 6)), Versus::Older);
626        assert_eq!(versus(ib(U32(5), 0), ib(U32(5), 0xff_ffff)), Versus::Newer);
627        // The merge: a live sample and a reply of one mutation kept once,
628        // an older seq never over a newer.
629        let held = Held::default().after_mark(Some(ib(U16(5), 7)));
630        assert_eq!(
631            held,
632            Held::InBand(wire::Stamp {
633                run: U16(5),
634                seq: wire::Seq::new(7).unwrap()
635            })
636        );
637        assert!(admits_mark(held, Some(ib(U16(5), 8))));
638        assert!(!admits_mark(held, Some(ib(U16(5), 7))));
639        assert!(!admits_mark(held, Some(ib(U16(5), 6))));
640        // Unstamped below every mark, an in-band one included.
641        assert!(!admits_mark(held, None));
642        assert_eq!(held.after_mark(None), held);
643        assert!(admits_mark(Held::Unstamped, Some(ib(U16(5), 0))));
644        // A consumer orders a run as a tool does.
645        assert!(consumer_accepts(None, ib(U16(5), 0)));
646        assert!(consumer_accepts(Some(ib(U16(5), 7)), ib(U16(5), 8)));
647        assert!(!consumer_accepts(Some(ib(U16(5), 7)), ib(U16(5), 7)));
648        assert!(!consumer_accepts(Some(ib(U16(5), 7)), ib(U16(5), 6)));
649    }
650
651    /// Rule 5: nothing orders two runs. A run is its width and its value,
652    /// so a 16-bit run 5 is not the 32-bit run 5. A tool's merge keeps the
653    /// later arrival, and a consumer accepts it as it accepts another id.
654    #[test]
655    fn across_runs_nothing_is_ordered_and_the_arrival_is_kept() {
656        use wire::Run::{U16, U32};
657        for (a, b) in [
658            (ib(U16(5), 7), ib(U16(6), 1)),
659            (ib(U16(6), 1), ib(U16(5), 7)),
660            (ib(U16(5), 7), ib(U32(5), 7)),
661            (ib(U32(9), 0), ib(U32(8), 0xff_ffff)),
662        ] {
663            assert_eq!(versus(a, b), Versus::Unordered, "{a:?} {b:?}");
664            let held = Held::default().after_mark(Some(a));
665            assert!(admits_mark(held, Some(b)), "the later arrival: {a:?} {b:?}");
666            assert!(consumer_accepts(Some(a), b), "{a:?} {b:?}");
667        }
668        // And within the new run, by seq from then on.
669        let held = Held::default()
670            .after_mark(Some(ib(U16(5), 7)))
671            .after_mark(Some(ib(U16(6), 1)));
672        assert!(!admits_mark(held, Some(ib(U16(6), 0))));
673        assert!(
674            admits_mark(held, Some(ib(U16(5), 3))),
675            "§4.3's residual risk"
676        );
677    }
678
679    /// Core §4.3's serial order for a stream key's seqs, and the plain
680    /// order a state's keep.
681    #[test]
682    fn a_stream_keys_seqs_are_serial_and_a_states_plain() {
683        use wire::Run::U16;
684        let s = |v| wire::Seq::new(v).expect("a seq");
685        const HALF: u32 = 1 << 23;
686        const TOP: u32 = (1 << 24) - 1;
687        let serial = Order::Serial;
688        assert_eq!(
689            serial.seqs(s(TOP), s(0)),
690            Some(Ordering::Greater),
691            "the wrap"
692        );
693        assert_eq!(serial.seqs(s(0), s(TOP)), Some(Ordering::Less));
694        assert_eq!(serial.seqs(s(5), s(5)), Some(Ordering::Equal));
695        assert_eq!(serial.seqs(s(5), s(5 + HALF - 1)), Some(Ordering::Greater));
696        assert_eq!(serial.seqs(s(5), s(5 + HALF)), None, "exactly 2^23");
697        assert_eq!(serial.seqs(s(5 + HALF), s(5)), None);
698        assert_eq!(serial.seqs(s(5), s(5 + HALF + 1)), Some(Ordering::Less));
699        let plain = Order::Plain;
700        assert_eq!(plain.seqs(s(0), s(TOP)), Some(Ordering::Greater));
701        assert_eq!(plain.seqs(s(5), s(5 + HALF)), Some(Ordering::Greater));
702        // The kind picks the order.
703        for (key, order) in [
704            ("zk2/h/s/i.v1/stream/pose", Order::Serial),
705            ("prod/zk2/h/s/i.v1/@stream/frames/f1", Order::Serial),
706            ("zk2/h/s/i.v1/state/mode", Order::Plain),
707            ("zk2/h/s/i.v1/@state/tracks/t1", Order::Plain),
708            ("zk2/h/s/i.v1/events/fault/002g0009", Order::Plain),
709            ("demo/tick", Order::Plain),
710        ] {
711            assert_eq!(Order::of_key(key), order, "{key}");
712        }
713        // A tool's merge of a stream key keeps a sample across the wrap,
714        // and the later arrival of two 2^23 apart; a state's merge orders
715        // the same seqs as integers.
716        let held = Held::default().after_mark(Some(ib(U16(5), TOP)));
717        assert!(admits_mark_in(serial, held, Some(ib(U16(5), 0))));
718        assert!(!admits_mark(held, Some(ib(U16(5), 0))), "plain: 0 < TOP");
719        let held = Held::default().after_mark(Some(ib(U16(5), 5)));
720        assert!(admits_mark_in(serial, held, Some(ib(U16(5), 5 + HALF))));
721        assert!(!admits_mark_in(serial, held, Some(ib(U16(5), 5))));
722        assert_eq!(
723            versus_in(serial, ib(U16(5), 9), ib(U16(6), 0)),
724            Versus::Unordered,
725            "two runs, whatever the order"
726        );
727        assert_eq!(versus(ib(U16(5), 0), ib(U16(5), 9_000_000)), Versus::Newer);
728        assert_eq!(
729            versus_in(serial, ib(U16(5), 0), ib(U16(5), 9_000_000)),
730            Versus::Older
731        );
732    }
733
734    /// Core §4.2, "A conditional read": one concrete key is a selector
735    /// whose key expression has no wildcard chunk. A selector's parameters
736    /// are no chunks: they neither make a GET wild nor change the key its
737    /// answer comes on, so a conditional read asked with parameters still
738    /// reads its owner's answer as unchanged. `seed/held.json` has no case
739    /// with parameters.
740    #[test]
741    fn a_selectors_parameters_are_no_part_of_its_one_concrete_key() {
742        const KEY: &str = "zk2/ground/fleet-mgr/mission_plan.v1/state/plans/vehicle-01";
743        assert_eq!(selector_key(KEY), KEY);
744        assert_eq!(selector_key(&format!("{KEY}?_time=[now(-1h)..]")), KEY);
745        assert_eq!(
746            selector_key(&format!("{KEY}?a=1?b=*")),
747            KEY,
748            "the first `?`"
749        );
750        assert_eq!(selector_key(&format!("{KEY}?")), KEY);
751        for (selector, concrete) in [
752            (KEY.to_owned(), true),
753            (format!("{KEY}?x=*"), true),
754            (format!("{KEY}?_anyke"), true),
755            (
756                "zk2/ground/fleet-mgr/mission_plan.v1/state/plans/*".to_owned(),
757                false,
758            ),
759            (
760                "zk2/ground/fleet-mgr/mission_plan.v1/state/plans/**".to_owned(),
761                false,
762            ),
763            (
764                "zk2/ground/fleet-mgr/mission_plan.v1/state/plans/v$*".to_owned(),
765                false,
766            ),
767            (
768                "zk2/ground/fleet-mgr/mission_plan.v1/state/plans/*?x=1".to_owned(),
769                false,
770            ),
771        ] {
772            assert_eq!(is_concrete(&selector), concrete, "{selector}");
773        }
774        let stamp = wire::Stamp {
775            run: wire::Run::U16(5),
776            seq: wire::Seq::new(7).unwrap(),
777        };
778        let other = wire::Stamp {
779            run: wire::Run::U16(5),
780            seq: wire::Seq::new(8).unwrap(),
781        };
782        let with_parameters = format!("{KEY}?x=*");
783        for selector in [KEY, with_parameters.as_str()] {
784            let asked = Asked {
785                key: selector,
786                held: Some(stamp),
787            };
788            assert!(asked.is_conditional(), "{selector}");
789            assert_eq!(
790                asked.read(true, KEY, stamp),
791                HeldRead::Unchanged,
792                "{selector}"
793            );
794            // Any other is refused: another stamp, another key, the
795            // selector itself where it is no key, a subscription's.
796            assert_eq!(asked.read(true, KEY, other), HeldRead::Refused);
797            assert_eq!(
798                asked.read(true, &format!("{KEY}0"), stamp),
799                HeldRead::Refused
800            );
801            assert_eq!(asked.read(false, KEY, stamp), HeldRead::Refused);
802        }
803        let asked = Asked {
804            key: &with_parameters,
805            held: Some(stamp),
806        };
807        assert_eq!(
808            asked.read(true, &with_parameters, stamp),
809            HeldRead::Refused,
810            "a reply rides a key, never a selector's parameters"
811        );
812        // A wildcard in the key expression, parameters or none, and a GET
813        // that carried no held stamp: no conditional read.
814        let wild = format!("{}/*?x=1", KEY.rsplit_once('/').unwrap().0);
815        for (selector, held) in [
816            (wild.as_str(), Some(stamp)),
817            (with_parameters.as_str(), None),
818        ] {
819            let asked = Asked {
820                key: selector,
821                held,
822            };
823            assert!(!asked.is_conditional(), "{selector}");
824            assert_eq!(
825                asked.read(true, KEY, stamp),
826                HeldRead::Refused,
827                "{selector}"
828            );
829        }
830    }
831
832    /// Rule 6: a Zenoh-stamped held value and an in-band arrival, either
833    /// way round, are read as across runs.
834    #[test]
835    fn a_zenoh_stamp_and_an_in_band_one_are_read_as_across_runs() {
836        use wire::Run::U16;
837        let z = Mark::Zenoh(s(9, "a").unwrap());
838        let i = ib(U16(1), 0);
839        assert_eq!(versus(z, i), Versus::Unordered);
840        assert_eq!(versus(i, z), Versus::Unordered);
841        assert!(admits_mark(Held::default().after_mark(Some(z)), Some(i)));
842        assert!(admits_mark(Held::default().after_mark(Some(i)), Some(z)));
843        assert!(consumer_accepts(Some(z), i));
844        assert!(consumer_accepts(Some(i), z));
845        // Two Zenoh stamps keep core §4.2's orders: the merge's by time across
846        // ids, the consumer's by time within one id only.
847        let later_other = Mark::Zenoh(s(5, "b").unwrap());
848        assert_eq!(versus(z, later_other), Versus::Older);
849        assert!(consumer_accepts(Some(z), later_other));
850        assert!(!consumer_accepts(Some(z), Mark::Zenoh(s(8, "a").unwrap())));
851        // An enveloped sample is ordered by its in-band stamp, whatever
852        // Zenoh timestamp it also carries.
853        let both = Mark::of(
854            Some(wire::Stamp {
855                run: U16(1),
856                seq: wire::Seq::new(0).unwrap(),
857            }),
858            s(9, "a"),
859        );
860        assert_eq!(both, Some(i));
861        assert_eq!(Mark::of(None, s(9, "a")), Some(z));
862        assert_eq!(Mark::of(None, None), None);
863    }
864}