zenkey-model 0.25.0

zk2 keys and contracts without a Zenoh session: the key grammar, the contract authoring format, canonical form, fingerprints and bundles
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
//! A late joiner's merge (core §4.2, §4.3): per key, which arriving
//! sample a late joiner keeps, whichever path — S4's GET or its
//! subscription — brought it.
//!
//! **In-band stamps** (core §4.3): an owner's sample carries a zk2c
//! envelope (core §7.5, [`crate::wire::carries`]), and is ordered by its
//! envelope's run and seq, never by a Zenoh timestamp it may also carry on
//! a resource §4.3's table lists ([`Mark::of`]). [`versus_in`] compares two
//! marks of one key, in the [`Order`] its kind picks:
//!
//! ```text
//! held        incoming    versus_in
//! run r · s   run r · s'  Plain (state, events): s' > s Newer, s' = s Same, s' < s Older
//!                         Serial (a stream key): d = (s' − s) mod 2^24;
//!                           d = 0 Same, 1 ≤ d < 2^23 Newer, d > 2^23 Older, d = 2^23 Unordered
//! run r       run r'≠r    Unordered: nothing orders two runs, two widths of one value included
//! Zenoh       in-band     Unordered, either way round: a sample with no envelope beside one
//! Zenoh t·i   Zenoh t'·i' the Stamp order below
//! ```
//!
//! An equal seq is the same value: S2's reply is the stored bytes. An
//! unordered arrival is accepted wherever an older one is refused: a
//! tool's merge keeps the later arrival ([`admits_mark_in`], observer
//! §4.1), a consumer takes it as §4.3 takes another run
//! ([`consumer_accepts`]), and an archive records it, refusing an outdated
//! put only within a run. [`versus`], [`admits_mark`] and
//! [`in_band_order`] are the plain order's, which state keeps: a
//! consumer's rule and an archive read state alone.
//!
//! **A sample with no envelope** (core §4.2) — an `@stream` sample, a
//! foreign key's (§1.7), or one whose owner broke §4.3 — is ordered among
//! samples with no envelope by its Zenoh timestamp:
//!
//! ```text
//! Stamp { time, id }        an NTP64 time, and the 128-bit id of the HLC
//!                           that issued it (a session's zid)
//! Stamp ordering            time first; on equal times, the id's 16 bytes
//!                           little-endian, compared from the first: zenoh's
//!                           `Timestamp` order, not the ids' integer order
//! admits(held, incoming)    whether the sample replaces what the key holds
//! ```
//!
//! That rule is zenoh's `Latest` consolidation (§4.1) read as a merge:
//!
//! - a stamped sample is kept when the key holds nothing, an unstamped
//!   sample, or a lower stamp; an equal stamp is the same mutation, kept
//!   once; a higher one held makes it stale;
//! - an unstamped sample — an `@stream` sample or a foreign key's, from a
//!   session with no HLC through no router that stamps — ranks below every
//!   stamped one, an in-band stamp included, as `Latest` ranks an
//!   unstamped reply lowest: kept when the key holds nothing or only
//!   unstamped samples, the later arrival replacing the earlier, and never
//!   over a stamped one.
//!
//! A deletion (a live delete, or a `reply_del` with its stamp) merges as a
//! put does: the kind never decides. Pure: the fixtures in
//! `spec/conformance/seed/` pin it (`inband.json`, `merge.json`), and a
//! tool hands its samples' stamps over as values.
//!
//! **A conditional read** (core 0.110 §4.2; #986's J1): a reader that holds
//! a member's value asks for it again and names the mutation it holds
//! ([`held_stamp`], never anything but that mutation's in-band stamp). Its
//! GET is an [`Asked`], on one concrete key ([`is_concrete`], read from its
//! selector's key expression, [`selector_key`]); a held stamp among its arrivals is the owner's
//! answer only as [`Asked::read`] says, [`HeldRead::Unchanged`], and any
//! other is refused `held`. An answer merges nothing: [`unchanged`] says
//! what it finds the reader holding, the mutation heard again (for
//! [`apply_snapshot`]'s guard, [`HeldMember::heard_after`]), a later value
//! that stands, or nothing, where the reader reads again.
//! `spec/conformance/seed/held.json` pins it.

use std::cmp::Ordering;
use std::fmt;

use crate::grammar::KindToken;
use crate::wire;

/// A Zenoh timestamp as the merge compares it (§4.1, Appendix B): its
/// time, an NTP64 value whose unit is 2^−32 s, and the id of the HLC that
/// issued it, a 128-bit value (the issuing session's zid).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Stamp {
    /// The NTP64 time.
    pub time: u64,
    /// The HLC id, as its 128-bit value. Written as lowercase hexadecimal
    /// without leading zeros, as zenoh writes an id and a zid.
    pub id: u128,
}

impl Stamp {
    /// A stamp from its NTP64 time and its id as zenoh writes it: lowercase
    /// hexadecimal, no leading zeros, not 0. `None` for any other spelling.
    #[must_use]
    pub fn parse(time: u64, id: &str) -> Option<Stamp> {
        let valid = !id.is_empty()
            && id.len() <= 32
            && !id.starts_with('0')
            && id
                .bytes()
                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
        if !valid {
            return None;
        }
        let id = u128::from_str_radix(id, 16).ok()?;
        Some(Stamp { time, id })
    }
}

impl fmt::Display for Stamp {
    /// zenoh's own spelling: the time in decimal, `/`, the id in hex.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}/{:x}", self.time, self.id)
    }
}

impl Ord for Stamp {
    /// zenoh's `Timestamp` order (uhlc 0.8): by time; on equal times, by
    /// the id's 16 bytes little-endian — least significant first —
    /// compared from the first byte. So the least significant byte that
    /// differs decides, and `100` (hex) orders below `2`, which their
    /// values would not.
    fn cmp(&self, other: &Self) -> Ordering {
        self.time
            .cmp(&other.time)
            .then_with(|| self.id.to_le_bytes().cmp(&other.id.to_le_bytes()))
    }
}

impl PartialOrd for Stamp {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// What orders a sample of a key: an envelope's in-band stamp (core §7.5)
/// when it carried one, else its Zenoh timestamp.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Mark {
    /// A Zenoh timestamp, on a sample with no envelope.
    Zenoh(Stamp),
    /// An envelope's run and seq.
    InBand(wire::Stamp),
}

impl Mark {
    /// A sample's mark: its in-band stamp when it carried an envelope, its
    /// Zenoh timestamp otherwise, `None` when it carried neither. An
    /// enveloped sample's Zenoh timestamp is its time where a profile
    /// reads one, never its order.
    #[must_use]
    pub fn of(inband: Option<wire::Stamp>, zenoh: Option<Stamp>) -> Option<Mark> {
        inband.map(Mark::InBand).or_else(|| zenoh.map(Mark::Zenoh))
    }
}

/// How an arrival marked `incoming` compares with what a key holds, marked
/// `held`. See the module doc's table.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Versus {
    /// Newer: it replaces what is held.
    Newer,
    /// The same mutation, kept once: an equal Zenoh stamp, or an equal seq
    /// within a run.
    Same,
    /// Older: refused or ignored wherever an older stamp is.
    Older,
    /// Not comparable: in-band stamps of two runs, or an in-band stamp
    /// beside a Zenoh one. Accepted, as a value under another id is.
    Unordered,
}

/// How two seqs of one key, within one run, compare (core §4.3): by the
/// key's kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Order {
    /// A state's or an event's seqs, as integers. The owner keeps one seq
    /// per run for its state and events, which never wraps: within a run a
    /// key's held seq can trail a newer one by more than 2^23, which serial
    /// order would read as older.
    #[default]
    Plain,
    /// A stream key's seqs, by serial arithmetic over 24 bits (RFC 1982):
    /// each stream key's seq is its own, and wraps modulo 2^24.
    Serial,
}

impl Order {
    /// The order a kind's seqs take: a stream's (`stream`, `@stream`) is
    /// serial, every other kind's plain. An `@stream` sample carries no
    /// envelope at core 0.73; a reader that meets one orders it as a
    /// stream key's.
    #[must_use]
    pub const fn of_kind(kind: KindToken) -> Order {
        match kind {
            KindToken::Stream | KindToken::ExplicitStream => Order::Serial,
            _ => Order::Plain,
        }
    }

    /// The order of `key`'s seqs, by its kind token as the grammar reads it
    /// ([`wire::enveloped_kind`]); plain for a key whose samples carry no
    /// envelope, whose marks are never in-band.
    #[must_use]
    pub fn of_key(key: &str) -> Order {
        wire::enveloped_kind(key).map_or(Order::Plain, Order::of_kind)
    }

    /// `incoming` against `held`, two seqs of one run: `Greater` when it is
    /// newer, `Equal` when it is the same, `Less` when it is older, and
    /// `None` when serial order leaves them unordered, exactly 2^23 apart.
    #[must_use]
    pub fn seqs(self, held: wire::Seq, incoming: wire::Seq) -> Option<Ordering> {
        match self {
            Order::Plain => Some(incoming.get().cmp(&held.get())),
            Order::Serial => {
                const HALF: u32 = 1 << 23;
                let d = incoming.get().wrapping_sub(held.get()) & wire::Seq::MAX.get();
                match d {
                    0 => Some(Ordering::Equal),
                    d if d < HALF => Some(Ordering::Greater),
                    d if d > HALF => Some(Ordering::Less),
                    _ => None,
                }
            }
        }
    }
}

/// Two in-band stamps of one key, in the plain order: within one run (the
/// same width and the same value), the higher seq is newer and an equal
/// seq is the same value; across two runs, `None`, since nothing orders
/// them.
#[must_use]
pub fn in_band_order(held: wire::Stamp, incoming: wire::Stamp) -> Option<Ordering> {
    in_band_order_in(Order::Plain, held, incoming)
}

/// [`in_band_order`], in the order `order` (a stream key's is serial).
#[must_use]
pub fn in_band_order_in(
    order: Order,
    held: wire::Stamp,
    incoming: wire::Stamp,
) -> Option<Ordering> {
    if held.run == incoming.run {
        order.seqs(held.seq, incoming.seq)
    } else {
        None
    }
}

/// `incoming` against `held`, by the module doc's table, in the plain
/// order: a state's.
#[must_use]
pub fn versus(held: Mark, incoming: Mark) -> Versus {
    versus_in(Order::Plain, held, incoming)
}

/// `incoming` against `held`, two marks of one key whose seqs take
/// `order` ([`Order::of_key`]), by the module doc's table.
#[must_use]
pub fn versus_in(order: Order, held: Mark, incoming: Mark) -> Versus {
    let ordering = match (held, incoming) {
        (Mark::Zenoh(h), Mark::Zenoh(i)) => Some(i.cmp(&h)),
        (Mark::InBand(h), Mark::InBand(i)) => in_band_order_in(order, h, i),
        (Mark::Zenoh(_), Mark::InBand(_)) | (Mark::InBand(_), Mark::Zenoh(_)) => None,
    };
    match ordering {
        Some(Ordering::Greater) => Versus::Newer,
        Some(Ordering::Equal) => Versus::Same,
        Some(Ordering::Less) => Versus::Older,
        None => Versus::Unordered,
    }
}

/// §4.3's consumer rule over marks, for a state key: within one run by
/// seq, a value of another run accepted, as is one beside a value held
/// under a Zenoh timestamp; a value with no envelope by time within one
/// timestamp id, a value under another id accepted. `held` is the mark of
/// the value the key holds, `None` for nothing.
#[must_use]
pub fn consumer_accepts(held: Option<Mark>, incoming: Mark) -> bool {
    match (held, incoming) {
        (None, _) => true,
        (Some(Mark::Zenoh(h)), Mark::Zenoh(i)) if h.id != i.id => true,
        (Some(h), i) => matches!(versus(h, i), Versus::Newer | Versus::Unordered),
    }
}

/// What a late joiner holds of one key.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Held {
    /// Nothing yet.
    #[default]
    Nothing,
    /// Only unstamped samples.
    Unstamped,
    /// A stamped sample, with the greatest stamp kept.
    Stamped(Stamp),
    /// A sample with an in-band stamp (core §7.5): the last kept.
    InBand(wire::Stamp),
}

impl Held {
    /// What the key holds once a sample with `incoming`'s stamp is kept.
    #[must_use]
    pub fn after(self, incoming: Option<Stamp>) -> Held {
        self.after_mark(incoming.map(Mark::Zenoh))
    }

    /// [`Held::after`], for a sample marked `incoming`.
    #[must_use]
    pub fn after_mark(self, incoming: Option<Mark>) -> Held {
        match incoming {
            Some(Mark::Zenoh(s)) => Held::Stamped(s),
            Some(Mark::InBand(s)) => Held::InBand(s),
            None => match self.mark() {
                Some(_) => self,
                None => Held::Unstamped,
            },
        }
    }

    /// The mark of what is held, `None` for nothing or only unstamped
    /// samples.
    #[must_use]
    pub fn mark(self) -> Option<Mark> {
        match self {
            Held::Nothing | Held::Unstamped => None,
            Held::Stamped(s) => Some(Mark::Zenoh(s)),
            Held::InBand(s) => Some(Mark::InBand(s)),
        }
    }
}

/// Whether a late joiner keeps a sample stamped `incoming` (`None`:
/// unstamped) over what its key holds (core §4.2, 0.27). See the module
/// doc for the rule.
#[must_use]
pub fn admits(held: Held, incoming: Option<Stamp>) -> bool {
    admits_mark(held, incoming.map(Mark::Zenoh))
}

/// [`admits`], for a sample marked `incoming`, in the plain order: a
/// newer mark is kept, an equal or older one is not, and an unordered one
/// is, so across two runs (or two wires) a tool's merge keeps the later
/// arrival, there being no time to keep the later of. An unstamped sample
/// ranks below every mark, an in-band one included.
#[must_use]
pub fn admits_mark(held: Held, incoming: Option<Mark>) -> bool {
    admits_mark_in(Order::Plain, held, incoming)
}

/// [`admits_mark`], for a key whose seqs take `order` ([`Order::of_key`]):
/// a tool's merge of a stream key keeps a sample across its seq's wrap,
/// and the later arrival of two exactly 2^23 apart.
#[must_use]
pub fn admits_mark_in(order: Order, held: Held, incoming: Option<Mark>) -> bool {
    match (held.mark(), incoming) {
        (None, _) => true,
        (Some(_), None) => false,
        (Some(h), Some(i)) => matches!(versus_in(order, h, i), Versus::Newer | Versus::Unordered),
    }
}

/// One key's arrivals, merged in arrival order: which ones are kept.
#[must_use]
pub fn merge(arrivals: &[Option<Stamp>]) -> Vec<bool> {
    let mut held = Held::Nothing;
    arrivals
        .iter()
        .map(|incoming| {
            let kept = admits(held, *incoming);
            if kept {
                held = held.after(*incoming);
            }
            kept
        })
        .collect()
}

/// The held stamp a reader may send for a member (core §4.2, "What a
/// reader sends"): the in-band stamp of the mutation it holds, as the owner
/// wrote it, where `holds` is that mutation's mark. That is its put's
/// envelope's, its delete's attachment's, or its snapshot entry's, the
/// entry's own run or the header's and the entry's seq
/// ([`crate::collection::Member::stamp`]). `None` for a reader that holds
/// nothing for the member, and for a value with no envelope: never a held
/// stamp made of a Zenoh timestamp, of a snapshot's asof, or of another
/// key's stamp.
#[must_use]
pub fn held_stamp(holds: Option<Mark>) -> Option<wire::HeldStamp> {
    match holds {
        Some(Mark::InBand(stamp)) => Some(wire::HeldStamp::new(stamp)),
        Some(Mark::Zenoh(_)) | None => None,
    }
}

/// The key expression of a GET's selector: everything before its first
/// `?`, where zenoh's parameters begin, and the whole selector where it has
/// none. A reply rides a key, never the parameters, and an owner reads the
/// key alone, so the parameters decide neither whether a GET is on one
/// concrete key nor which key its answer comes on.
#[must_use]
pub fn selector_key(selector: &str) -> &str {
    selector.split_once('?').map_or(selector, |(key, _)| key)
}

/// Whether a GET's selector is one concrete key (core §4.2, "A conditional
/// read"): its key expression ([`selector_key`]) has no wildcard, so no
/// `*`, no `**` and no `$*` chunk. The text counts chunks, which a
/// selector's parameters are not: a `*` after the `?` is no wildcard, and
/// `…/plans/vehicle-01?_time=*` is one concrete key.
#[must_use]
pub fn is_concrete(selector: &str) -> bool {
    !selector_key(selector).contains('*')
}

/// A reader's state GET, as it reads a held stamp among its arrivals (core
/// §4.2, "A held stamp in answer"): its selector, and the held stamp it
/// carried, `None` for a GET with no payload.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Asked<'a> {
    /// The GET's selector, as its reader's session spells the keys it
    /// hears: base-relative in a namespace, a wire key in none. It may
    /// carry parameters after a `?`, which are not part of its key
    /// ([`selector_key`]).
    pub key: &'a str,
    /// The held stamp the GET carried.
    pub held: Option<wire::Stamp>,
}

/// How a held stamp among a reader's arrivals reads ([`Asked::read`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum HeldRead {
    /// The owner's answer: when it answered, the member's last mutation
    /// was the one the stamp names. It merges nothing ([`unchanged`]).
    Unchanged,
    /// No owner's answer: it establishes nothing, merges nothing, counts
    /// as nothing heard, and is counted undecodable, refused as `held`
    /// ([`wire::Refusal::Held`]).
    Refused,
}

impl HeldRead {
    /// `unchanged`, or the refusal's token `held`, as
    /// `spec/conformance/seed/held.json` spells them.
    #[must_use]
    pub const fn token(self) -> &'static str {
        match self {
            HeldRead::Unchanged => "unchanged",
            HeldRead::Refused => "held",
        }
    }
}

impl Asked<'_> {
    /// Whether the GET is a conditional read as its reader made it: it
    /// carried a held stamp on one concrete key.
    #[must_use]
    pub fn is_conditional(&self) -> bool {
        self.held.is_some() && is_concrete(self.key)
    }

    /// A held stamp that arrived on `key` carrying `stamp`, by this GET
    /// (`by_get`) or on a subscription: the owner's answer only as a reply
    /// to the GET that carried the same one, on that GET's one concrete
    /// key, its selector's key expression ([`selector_key`]). The same one
    /// has the same run, in width and value, and the same seq. A consumer
    /// or a tool MUST NOT read any other as unchanged.
    #[must_use]
    pub fn read(&self, by_get: bool, key: &str, stamp: wire::Stamp) -> HeldRead {
        if by_get
            && self.is_conditional()
            && key == selector_key(self.key)
            && self.held == Some(stamp)
        {
            HeldRead::Unchanged
        } else {
            HeldRead::Refused
        }
    }
}

/// What an owner's unchanged answer finds its reader holding for the
/// member ([`unchanged`]). The answer carries no value and merges none.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Unchanged {
    /// The reader still holds the mutation the stamp names: the answer
    /// counts as that mutation heard again, by the GET. The omission
    /// rule's guard reads it so ([`HeldMember::heard_after`]): another
    /// run's snapshot that lists no entry for it then spares it.
    HeardAgain,
    /// The reader holds another value by then, heard while its GET was
    /// out: that value stands. An answer never steps a member back.
    Stands,
    /// The reader holds nothing for the member by then: its GET gave it no
    /// value. It reads again, with no held stamp.
    ReadAgain,
}

/// What an unchanged answer naming `answer` finds, where the reader holds
/// `held` for the member as the answer arrives (core §4.2, "What unchanged
/// says").
#[must_use]
pub fn unchanged(held: Held, answer: wire::Stamp) -> Unchanged {
    match held {
        Held::Nothing => Unchanged::ReadAgain,
        Held::InBand(s) if s == answer => Unchanged::HeardAgain,
        Held::InBand(_) | Held::Stamped(_) | Held::Unstamped => Unchanged::Stands,
    }
}

/// What a late joiner holds of one key as a snapshot completes, for the
/// omission rule ([`apply_snapshot`]): the key, the mark of the value or
/// deletion it holds, and whether it heard that after it asked the GET, by
/// either path (an arrival with that same mark heard again counts).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HeldMember<'a> {
    pub key: &'a str,
    pub mark: Option<Mark>,
    pub heard_after: bool,
}

/// The omission rule (core §4.2; #977's E2 defines it, E3's readers apply
/// it, through [`crate::collection::omit`]): a late joiner holds `snapshot`
/// complete, heard on `key`, its collection's snapshot key or a member's
/// key. Each member of the collection at `key` or under it
/// (`of_collection` says which keys are its members) that the snapshot
/// lists neither live nor as a tombstone has no value, unless what the
/// late joiner holds of it is newer than the snapshot:
///
/// - a value under the snapshot's run with a seq above its asof;
/// - a value under another run, or with no in-band stamp, that it heard
///   after it asked the GET.
///
/// Returns the keys of `held` it drops, in `held`'s order. An incomplete
/// snapshot drops nothing, which is the caller's to know: it calls this
/// once [`crate::collection::Heard::complete`] says so. So a delete the
/// owner made beyond its window still reaches the late joiner.
pub fn apply_snapshot<'a>(
    snapshot: &crate::collection::Snapshot,
    key: &str,
    of_collection: impl Fn(&str) -> bool,
    held: impl IntoIterator<Item = HeldMember<'a>>,
) -> Vec<&'a str> {
    let listed: std::collections::BTreeSet<String> = snapshot
        .live
        .iter()
        .map(|e| e.id.as_str())
        .chain(snapshot.tombs.iter().map(|t| t.id.as_str()))
        .map(|id| crate::collection::member_key(key, id))
        .collect();
    let at_or_under = |k: &str| {
        k == key
            || k.strip_prefix(key)
                .is_some_and(|rest| rest.starts_with('/'))
    };
    held.into_iter()
        .filter(|h| at_or_under(h.key) && of_collection(h.key) && !listed.contains(h.key))
        .filter(|h| match h.mark {
            Some(Mark::InBand(s)) if s.run == snapshot.run => s.seq <= snapshot.asof,
            _ => !h.heard_after,
        })
        .map(|h| h.key)
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn s(time: u64, id: &str) -> Option<Stamp> {
        Some(Stamp::parse(time, id).expect("a stamp"))
    }

    #[test]
    fn stamps_order_by_time_then_by_the_ids_bytes_from_the_least_significant() {
        assert!(s(2, "1") > s(1, "ff"));
        assert!(s(5, "2") > s(5, "100"), "the low byte decides: 02 > 00");
        assert!(
            s(5, "102") > s(5, "201"),
            "low bytes 02 > 01, whatever the high ones"
        );
        assert!(s(5, "1ff") > s(5, "2fe"), "ff > fe");
        assert_eq!(s(5, "ab").cmp(&s(5, "ab")), Ordering::Equal);
        assert_eq!(Stamp::parse(7, "1bc0").unwrap().to_string(), "7/1bc0");
        for bad in ["", "0", "01", "AB", "g", &"f".repeat(33)] {
            assert_eq!(Stamp::parse(1, bad), None, "{bad:?}");
        }
    }

    #[test]
    fn the_merge_is_latest_read_as_a_merge() {
        // A newer stamp replaces; an older or equal one is not kept.
        assert_eq!(
            merge(&[s(1, "a"), s(2, "a"), s(2, "a"), s(1, "a")]),
            [true, true, false, false]
        );
        // Unstamped below every stamp, replacing only another unstamped.
        assert_eq!(
            merge(&[None, None, s(1, "a"), None]),
            [true, true, true, false]
        );
        assert_eq!(merge(&[s(1, "a"), None]), [true, false]);
        // Equal times: the ids as zenoh compares them.
        assert_eq!(merge(&[s(9, "2"), s(9, "100")]), [true, false]);
        assert_eq!(merge(&[s(9, "100"), s(9, "2")]), [true, true]);
    }

    fn ib(run: wire::Run, seq: u32) -> Mark {
        Mark::InBand(wire::Stamp {
            run,
            seq: wire::Seq::new(seq).expect("a seq"),
        })
    }

    /// Rule 4 (#976's A2): within one run, the higher seq is newer and an
    /// equal seq is the same value (S2's reply is the stored bytes).
    #[test]
    fn within_a_run_the_higher_seq_is_newer() {
        use wire::Run::{U16, U32};
        assert_eq!(versus(ib(U16(5), 7), ib(U16(5), 8)), Versus::Newer);
        assert_eq!(versus(ib(U16(5), 7), ib(U16(5), 7)), Versus::Same);
        assert_eq!(versus(ib(U16(5), 7), ib(U16(5), 6)), Versus::Older);
        assert_eq!(versus(ib(U32(5), 0), ib(U32(5), 0xff_ffff)), Versus::Newer);
        // The merge: a live sample and a reply of one mutation kept once,
        // an older seq never over a newer.
        let held = Held::default().after_mark(Some(ib(U16(5), 7)));
        assert_eq!(
            held,
            Held::InBand(wire::Stamp {
                run: U16(5),
                seq: wire::Seq::new(7).unwrap()
            })
        );
        assert!(admits_mark(held, Some(ib(U16(5), 8))));
        assert!(!admits_mark(held, Some(ib(U16(5), 7))));
        assert!(!admits_mark(held, Some(ib(U16(5), 6))));
        // Unstamped below every mark, an in-band one included.
        assert!(!admits_mark(held, None));
        assert_eq!(held.after_mark(None), held);
        assert!(admits_mark(Held::Unstamped, Some(ib(U16(5), 0))));
        // A consumer orders a run as a tool does.
        assert!(consumer_accepts(None, ib(U16(5), 0)));
        assert!(consumer_accepts(Some(ib(U16(5), 7)), ib(U16(5), 8)));
        assert!(!consumer_accepts(Some(ib(U16(5), 7)), ib(U16(5), 7)));
        assert!(!consumer_accepts(Some(ib(U16(5), 7)), ib(U16(5), 6)));
    }

    /// Rule 5: nothing orders two runs. A run is its width and its value,
    /// so a 16-bit run 5 is not the 32-bit run 5. A tool's merge keeps the
    /// later arrival, and a consumer accepts it as it accepts another id.
    #[test]
    fn across_runs_nothing_is_ordered_and_the_arrival_is_kept() {
        use wire::Run::{U16, U32};
        for (a, b) in [
            (ib(U16(5), 7), ib(U16(6), 1)),
            (ib(U16(6), 1), ib(U16(5), 7)),
            (ib(U16(5), 7), ib(U32(5), 7)),
            (ib(U32(9), 0), ib(U32(8), 0xff_ffff)),
        ] {
            assert_eq!(versus(a, b), Versus::Unordered, "{a:?} {b:?}");
            let held = Held::default().after_mark(Some(a));
            assert!(admits_mark(held, Some(b)), "the later arrival: {a:?} {b:?}");
            assert!(consumer_accepts(Some(a), b), "{a:?} {b:?}");
        }
        // And within the new run, by seq from then on.
        let held = Held::default()
            .after_mark(Some(ib(U16(5), 7)))
            .after_mark(Some(ib(U16(6), 1)));
        assert!(!admits_mark(held, Some(ib(U16(6), 0))));
        assert!(
            admits_mark(held, Some(ib(U16(5), 3))),
            "§4.3's residual risk"
        );
    }

    /// Core §4.3's serial order for a stream key's seqs, and the plain
    /// order a state's keep.
    #[test]
    fn a_stream_keys_seqs_are_serial_and_a_states_plain() {
        use wire::Run::U16;
        let s = |v| wire::Seq::new(v).expect("a seq");
        const HALF: u32 = 1 << 23;
        const TOP: u32 = (1 << 24) - 1;
        let serial = Order::Serial;
        assert_eq!(
            serial.seqs(s(TOP), s(0)),
            Some(Ordering::Greater),
            "the wrap"
        );
        assert_eq!(serial.seqs(s(0), s(TOP)), Some(Ordering::Less));
        assert_eq!(serial.seqs(s(5), s(5)), Some(Ordering::Equal));
        assert_eq!(serial.seqs(s(5), s(5 + HALF - 1)), Some(Ordering::Greater));
        assert_eq!(serial.seqs(s(5), s(5 + HALF)), None, "exactly 2^23");
        assert_eq!(serial.seqs(s(5 + HALF), s(5)), None);
        assert_eq!(serial.seqs(s(5), s(5 + HALF + 1)), Some(Ordering::Less));
        let plain = Order::Plain;
        assert_eq!(plain.seqs(s(0), s(TOP)), Some(Ordering::Greater));
        assert_eq!(plain.seqs(s(5), s(5 + HALF)), Some(Ordering::Greater));
        // The kind picks the order.
        for (key, order) in [
            ("zk2/h/s/i.v1/stream/pose", Order::Serial),
            ("prod/zk2/h/s/i.v1/@stream/frames/f1", Order::Serial),
            ("zk2/h/s/i.v1/state/mode", Order::Plain),
            ("zk2/h/s/i.v1/@state/tracks/t1", Order::Plain),
            ("zk2/h/s/i.v1/events/fault/002g0009", Order::Plain),
            ("demo/tick", Order::Plain),
        ] {
            assert_eq!(Order::of_key(key), order, "{key}");
        }
        // A tool's merge of a stream key keeps a sample across the wrap,
        // and the later arrival of two 2^23 apart; a state's merge orders
        // the same seqs as integers.
        let held = Held::default().after_mark(Some(ib(U16(5), TOP)));
        assert!(admits_mark_in(serial, held, Some(ib(U16(5), 0))));
        assert!(!admits_mark(held, Some(ib(U16(5), 0))), "plain: 0 < TOP");
        let held = Held::default().after_mark(Some(ib(U16(5), 5)));
        assert!(admits_mark_in(serial, held, Some(ib(U16(5), 5 + HALF))));
        assert!(!admits_mark_in(serial, held, Some(ib(U16(5), 5))));
        assert_eq!(
            versus_in(serial, ib(U16(5), 9), ib(U16(6), 0)),
            Versus::Unordered,
            "two runs, whatever the order"
        );
        assert_eq!(versus(ib(U16(5), 0), ib(U16(5), 9_000_000)), Versus::Newer);
        assert_eq!(
            versus_in(serial, ib(U16(5), 0), ib(U16(5), 9_000_000)),
            Versus::Older
        );
    }

    /// Core §4.2, "A conditional read": one concrete key is a selector
    /// whose key expression has no wildcard chunk. A selector's parameters
    /// are no chunks: they neither make a GET wild nor change the key its
    /// answer comes on, so a conditional read asked with parameters still
    /// reads its owner's answer as unchanged. `seed/held.json` has no case
    /// with parameters.
    #[test]
    fn a_selectors_parameters_are_no_part_of_its_one_concrete_key() {
        const KEY: &str = "zk2/ground/fleet-mgr/mission_plan.v1/state/plans/vehicle-01";
        assert_eq!(selector_key(KEY), KEY);
        assert_eq!(selector_key(&format!("{KEY}?_time=[now(-1h)..]")), KEY);
        assert_eq!(
            selector_key(&format!("{KEY}?a=1?b=*")),
            KEY,
            "the first `?`"
        );
        assert_eq!(selector_key(&format!("{KEY}?")), KEY);
        for (selector, concrete) in [
            (KEY.to_owned(), true),
            (format!("{KEY}?x=*"), true),
            (format!("{KEY}?_anyke"), true),
            (
                "zk2/ground/fleet-mgr/mission_plan.v1/state/plans/*".to_owned(),
                false,
            ),
            (
                "zk2/ground/fleet-mgr/mission_plan.v1/state/plans/**".to_owned(),
                false,
            ),
            (
                "zk2/ground/fleet-mgr/mission_plan.v1/state/plans/v$*".to_owned(),
                false,
            ),
            (
                "zk2/ground/fleet-mgr/mission_plan.v1/state/plans/*?x=1".to_owned(),
                false,
            ),
        ] {
            assert_eq!(is_concrete(&selector), concrete, "{selector}");
        }
        let stamp = wire::Stamp {
            run: wire::Run::U16(5),
            seq: wire::Seq::new(7).unwrap(),
        };
        let other = wire::Stamp {
            run: wire::Run::U16(5),
            seq: wire::Seq::new(8).unwrap(),
        };
        let with_parameters = format!("{KEY}?x=*");
        for selector in [KEY, with_parameters.as_str()] {
            let asked = Asked {
                key: selector,
                held: Some(stamp),
            };
            assert!(asked.is_conditional(), "{selector}");
            assert_eq!(
                asked.read(true, KEY, stamp),
                HeldRead::Unchanged,
                "{selector}"
            );
            // Any other is refused: another stamp, another key, the
            // selector itself where it is no key, a subscription's.
            assert_eq!(asked.read(true, KEY, other), HeldRead::Refused);
            assert_eq!(
                asked.read(true, &format!("{KEY}0"), stamp),
                HeldRead::Refused
            );
            assert_eq!(asked.read(false, KEY, stamp), HeldRead::Refused);
        }
        let asked = Asked {
            key: &with_parameters,
            held: Some(stamp),
        };
        assert_eq!(
            asked.read(true, &with_parameters, stamp),
            HeldRead::Refused,
            "a reply rides a key, never a selector's parameters"
        );
        // A wildcard in the key expression, parameters or none, and a GET
        // that carried no held stamp: no conditional read.
        let wild = format!("{}/*?x=1", KEY.rsplit_once('/').unwrap().0);
        for (selector, held) in [
            (wild.as_str(), Some(stamp)),
            (with_parameters.as_str(), None),
        ] {
            let asked = Asked {
                key: selector,
                held,
            };
            assert!(!asked.is_conditional(), "{selector}");
            assert_eq!(
                asked.read(true, KEY, stamp),
                HeldRead::Refused,
                "{selector}"
            );
        }
    }

    /// Rule 6: a Zenoh-stamped held value and an in-band arrival, either
    /// way round, are read as across runs.
    #[test]
    fn a_zenoh_stamp_and_an_in_band_one_are_read_as_across_runs() {
        use wire::Run::U16;
        let z = Mark::Zenoh(s(9, "a").unwrap());
        let i = ib(U16(1), 0);
        assert_eq!(versus(z, i), Versus::Unordered);
        assert_eq!(versus(i, z), Versus::Unordered);
        assert!(admits_mark(Held::default().after_mark(Some(z)), Some(i)));
        assert!(admits_mark(Held::default().after_mark(Some(i)), Some(z)));
        assert!(consumer_accepts(Some(z), i));
        assert!(consumer_accepts(Some(i), z));
        // Two Zenoh stamps keep core §4.2's orders: the merge's by time across
        // ids, the consumer's by time within one id only.
        let later_other = Mark::Zenoh(s(5, "b").unwrap());
        assert_eq!(versus(z, later_other), Versus::Older);
        assert!(consumer_accepts(Some(z), later_other));
        assert!(!consumer_accepts(Some(z), Mark::Zenoh(s(8, "a").unwrap())));
        // An enveloped sample is ordered by its in-band stamp, whatever
        // Zenoh timestamp it also carries.
        let both = Mark::of(
            Some(wire::Stamp {
                run: U16(1),
                seq: wire::Seq::new(0).unwrap(),
            }),
            s(9, "a"),
        );
        assert_eq!(both, Some(i));
        assert_eq!(Mark::of(None, s(9, "a")), Some(z));
        assert_eq!(Mark::of(None, None), None);
    }
}