aboutsummaryrefslogtreecommitdiffstats
path: root/src/federation/store/set.rs
blob: b03392731882a460c092e1a59f2d5686136b403c (plain)
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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
//! A set of events: the store's own document (`docs/document.md`, A set of events), the
//! kind `events`. A store (`memory`), and beside it what the store itself lets go of
//! and its node still gives to others:
//!
//! * events whose history takes them and the node doesn't, by what it took before or as
//!   its operator had it drop them: other nodes take them;
//! * events that build on such: the node can't judge them, as it holds no history to
//!   judge them at, and others may take them. No more than `UNJUDGED` of them, the
//!   oldest going first: whoever mints events can mint these;
//! * what a move to a checkpoint forgot, for as long as the node's operator says: a node
//!   still before the checkpoint builds it from them.
//!
//! And each member's entry (`entry`): its node's newest, and none of a node the store
//! doesn't name a member as it reads now.
//!
//! What the fold refuses at its history, and what isn't one of its events, is held by
//! nobody.

use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::time::{Duration, Instant};

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use super::entry::Entry;
use super::memory::{Gone, Offered, Refusal, Store};
use super::{Fold, Id, Refused};
use crate::document::ranges::{Name, Names};

/// The kind, as nodes name it where they meet.
pub(crate) const KIND: &str = "events";

/// The most events held unjudged, and the most bytes of them.
const UNJUDGED: usize = 1024;
const UNJUDGED_BYTES: usize = 16 << 20;

/// Why the document holds an event its store doesn't.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Beside {
    /// Its history takes it, and the node doesn't.
    Own,
    /// It builds on one the node doesn't take, and wasn't judged.
    Unjudged,
    /// A move to a checkpoint forgot it, then.
    Forgotten(Instant),
}

/// The most events the store has wait for what they build on.
const WAITS: usize = 1024;

/// The most names of strangers' entries remembered.
const STRANGERS: usize = 1024;

/// What became of an entry put.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Put {
    /// It is its node's entry now.
    Taken,
    /// It is its node's entry already.
    Held,
    /// The document holds a newer one of its node.
    Older,
    /// Its node is no member, as the store reads now.
    Stranger,
    /// It is no entry of this store, and why.
    Refused(&'static str),
}

/// The nodes that carry `store`, as it reads now.
fn members_of<F: Fold>(store: &Store<F>) -> BTreeSet<String> {
    F::members(store.state())
        .into_iter()
        .map(|(node, _)| node)
        .collect()
}

/// What a document's file begins with.
const FILE: &[u8] = b"continuum-events/1\n";

/// A document as its file holds it (`Set::save`).
#[derive(Serialize, Deserialize)]
struct Saved {
    store: [u8; 32],
    #[serde(with = "serde_bytes")]
    checkpoint: Vec<u8>,
    kept: Vec<serde_bytes::ByteBuf>,
    taken: Vec<serde_bytes::ByteBuf>,
    own: Vec<[u8; 32]>,
    dropped: Vec<[u8; 32]>,
    writes: Vec<([u8; 32], [u8; 32])>,
    beside: Vec<(serde_bytes::ByteBuf, SavedBeside)>,
    entries: Vec<serde_bytes::ByteBuf>,
}

/// Why a document holds an event beside its store, as its file says it: what a
/// checkpoint forgot, with how many seconds ago.
#[derive(Serialize, Deserialize)]
enum SavedBeside {
    Own,
    Unjudged,
    Forgotten(u64),
}

/// Where `store` stands: of its checkpoint and its heads, the same on every node
/// whose store holds the same.
fn stands_of<F: Fold>(store: &Store<F>) -> [u8; 32] {
    let mut hasher = Sha256::new();
    hasher.update(Id::of(store.checkpoint()).0);
    // In one order on every node: a store says its heads as it took them.
    let mut heads = store.heads();
    heads.sort();
    for head in heads {
        hasher.update(head.0);
    }
    hasher.finalize().into()
}

/// A set of events, of a fold `F`.
pub(crate) struct Set<F: Fold> {
    store: Store<F>,
    /// What is held beside the store, by ID.
    beside: BTreeMap<Id, (Vec<u8>, Beside)>,
    /// The unjudged among them, the oldest first, and their bytes in all.
    unjudged: VecDeque<Id>,
    unjudged_bytes: usize,
    /// For how long what a checkpoint forgot is kept.
    keeps_forgotten: Duration,
    /// Who carries the store, as it reads now (`Fold::members`).
    members: BTreeSet<String>,
    /// Each member's entry, by its node.
    entries: BTreeMap<String, Entry>,
    /// Entries of nodes that are no members, by name: not asked for again until who is
    /// one changes. No more than `STRANGERS`.
    strangers: BTreeSet<Name>,
    /// The names of all the document gives to others, kept as it changes.
    names: Names,
    /// The entries' names, each with its node.
    entry_names: BTreeMap<Name, String>,
    /// Where the store stands: of its checkpoint and its heads, read anew where it
    /// changed.
    stands: [u8; 32],
}

impl<F: Fold> Set<F> {
    /// The document of `store`, keeping what a checkpoint forgot for `keeps_forgotten`.
    pub(crate) fn new(store: Store<F>, keeps_forgotten: Duration) -> Self {
        let members = members_of::<F>(&store);
        let stands = stands_of(&store);
        let names = store
            .taken()
            .iter()
            .map(|id| id.0)
            .chain(store.kept().iter().map(|bytes| Id::of(bytes).0))
            .collect();
        Self {
            store: store.telling().waiting_no_more_than(WAITS),
            beside: BTreeMap::new(),
            unjudged: VecDeque::new(),
            unjudged_bytes: 0,
            keeps_forgotten,
            members,
            entries: BTreeMap::new(),
            strangers: BTreeSet::new(),
            names,
            entry_names: BTreeMap::new(),
            stands,
        }
    }

    /// Takes a member's entry, where it is its node's newest: of a higher count than the
    /// one held, or of the same and a lower name.
    pub(crate) fn put_entry(&mut self, entry: Entry) -> Put {
        if let Err(why) = entry.checks(&self.store.id()) {
            return Put::Refused(why);
        }
        let node = entry.node();
        if !self.members.contains(&node) {
            if self.strangers.len() < STRANGERS {
                self.strangers.insert(entry.name());
            }
            return Put::Stranger;
        }
        match self.entries.get(&node) {
            Some(held) if *held == entry => Put::Held,
            Some(held)
                if held.count() > entry.count()
                    || (held.count() == entry.count() && held.name() < entry.name()) =>
            {
                Put::Older
            }
            _ => {
                let name = entry.name();
                self.names.insert(name);
                self.entry_names.insert(name, node.clone());
                if let Some(older) = self.entries.insert(node, entry) {
                    let older = older.name();
                    self.names.remove(&older);
                    self.entry_names.remove(&older);
                }
                #[cfg(test)]
                self.check();
                Put::Taken
            }
        }
    }

    /// The entry of the member `node`, where the document holds one.
    pub(crate) fn entry(&self, node: &str) -> Option<&Entry> {
        self.entries.get(node)
    }

    /// The members' entries, in the order of their nodes.
    pub(crate) fn entries(&self) -> impl Iterator<Item = &Entry> {
        self.entries.values()
    }

    /// The entry named `name`, where the document holds it.
    pub(crate) fn entry_named(&self, name: &Name) -> Option<&Entry> {
        self.entry_names
            .get(name)
            .and_then(|node| self.entries.get(node))
    }

    /// Whether the document would have what is named `name`, which a peer holds: not
    /// what it holds, what its store refused, waits for or let go of, nor an entry of a
    /// node that is no member.
    pub(crate) fn wants(&self, name: &Name) -> bool {
        !self.store.knows(&Id(*name))
            && !self.beside.contains_key(&Id(*name))
            && !self.strangers.contains(name)
            && self.entry_named(name).is_none()
    }

    /// Where the store stands (`stands_of`).
    pub(crate) fn stands(&self) -> [u8; 32] {
        self.stands
    }

    /// The store: what the node reads.
    pub(crate) fn store(&self) -> &Store<F> {
        &self.store
    }

    /// Offers an event to the store, at `now`; what the store lets go of by it, the
    /// document keeps as far as it gives it to others.
    pub(crate) fn offer(&mut self, bytes: Vec<u8>, now: Instant) -> Offered {
        let offered = self.store.offer(bytes);
        self.settle(now);
        offered
    }

    /// Offers events to the store, at `now`, as `offer` does each: those the store took
    /// by them, in the order taken.
    pub(crate) fn offer_all(
        &mut self,
        events: impl IntoIterator<Item = Vec<u8>>,
        now: Instant,
    ) -> Vec<Id> {
        let mut taken = Vec::new();
        for bytes in events {
            if let Offered::Taken(ids) = self.store.offer(bytes) {
                taken.extend(ids);
            }
        }
        self.settle(now);
        taken
    }

    /// Reads anew who is a member, and lets go of the entries of those who aren't.
    fn members_anew(&mut self) {
        let members = members_of::<F>(&self.store);
        if members != self.members {
            let (names, entry_names) = (&mut self.names, &mut self.entry_names);
            self.entries.retain(|node, entry| {
                let member = members.contains(node);
                if !member {
                    let name = entry.name();
                    names.remove(&name);
                    entry_names.remove(&name);
                }
                member
            });
            self.strangers.clear();
            self.members = members;
        }
    }

    /// Has the store drop events it took (`Store::drop_taken`), at `now`: the document
    /// holds them on, for others.
    pub(crate) fn drop_taken(&mut self, ids: &[Id], now: Instant) -> Result<Vec<Id>, Refused> {
        let dropped = self.store.drop_taken(ids);
        self.settle(now);
        dropped
    }

    /// Has the store take back what the node refused of its own (`Store::allow`), and
    /// offers it what the document held of that, at `now`.
    pub(crate) fn allow(&mut self, ids: &[Id], now: Instant) {
        self.store.allow(ids);
        let again: Vec<Id> = self
            .beside
            .iter()
            .filter(|(id, (_, why))| {
                matches!(why, Beside::Own | Beside::Unjudged) && self.store.refusal(id).is_none()
            })
            .map(|(id, _)| *id)
            .collect();
        // Each after what it builds on, as far as that is among them: offered in any
        // order, the store has what comes early wait.
        for id in again {
            if let Some((bytes, why)) = self.beside.remove(&id) {
                self.names.remove(&id.0);
                if why == Beside::Unjudged {
                    self.unjudged.retain(|other| *other != id);
                    self.unjudged_bytes -= bytes.len();
                }
                self.store.offer(bytes);
            }
        }
        self.settle(now);
    }

    /// Takes in what the store let go of.
    fn settle(&mut self, now: Instant) {
        let took = self.store.took();
        let gone = self.store.let_go();
        // Who is a member is the fold's to say of the store's state, and costs what
        // reading that costs: asked only where the store changed.
        if !took.is_empty() || !gone.is_empty() {
            self.members_anew();
            self.stands = stands_of(&self.store);
        }
        for id in took {
            self.names.insert(id.0);
        }
        for (id, bytes, gone) in gone {
            let why = match gone {
                Gone::Forgotten => Beside::Forgotten(now),
                Gone::Own => Beside::Own,
                Gone::NotAbove => {
                    self.names.remove(&id.0);
                    continue;
                }
                Gone::BuiltOn(on) => {
                    if !self.own(&on) {
                        self.names.remove(&id.0);
                        continue;
                    }
                    Beside::Unjudged
                }
            };
            if why == Beside::Unjudged {
                self.unjudged.push_back(id);
                self.unjudged_bytes += bytes.len();
            }
            self.names.insert(id.0);
            self.beside.insert(id, (bytes, why));
        }
        while self.unjudged.len() > UNJUDGED || self.unjudged_bytes > UNJUDGED_BYTES {
            let Some(oldest) = self.unjudged.pop_front() else {
                break;
            };
            if let Some((bytes, _)) = self.beside.remove(&oldest) {
                self.names.remove(&oldest.0);
                self.unjudged_bytes -= bytes.len();
            }
        }
        // What the store holds again, it holds: taken after all, or kept by a checkpoint.
        let store = &self.store;
        let (unjudged, unjudged_bytes) = (&mut self.unjudged, &mut self.unjudged_bytes);
        self.beside.retain(|id, (bytes, why)| {
            let held = store.get(id).is_some();
            if held && *why == Beside::Unjudged {
                unjudged.retain(|other| other != id);
                *unjudged_bytes -= bytes.len();
            }
            !held
        });
        #[cfg(test)]
        self.check();
    }

    /// Whether the store refuses `id` as the node's own, or for building on such: what
    /// builds on it, others may take.
    fn own(&self, id: &Id) -> bool {
        let mut id = *id;
        // A chain of refusals ends: each names one refused before it.
        for _ in 0..=UNJUDGED {
            match self.store.refusal(&id) {
                Some(Refusal::Own | Refusal::Dropped) => return true,
                Some(Refusal::BuiltOn(on)) => {
                    // One held unjudged builds on the node's own; one not held was let
                    // go as building on what every node refuses, or fell out.
                    if self.beside.contains_key(&id) {
                        return true;
                    }
                    id = *on;
                }
                _ => return false,
            }
        }
        false
    }

    /// Lets go of what a checkpoint forgot longer ago than the document keeps it, at
    /// `now`. Whether it let go of anything.
    pub(crate) fn expire(&mut self, now: Instant) -> bool {
        let keeps = self.keeps_forgotten;
        let before = self.beside.len();
        let names = &mut self.names;
        self.beside.retain(|id, (_, why)| {
            let keep = match why {
                Beside::Forgotten(since) => now.saturating_duration_since(*since) < keeps,
                _ => true,
            };
            if !keep {
                names.remove(&id.0);
            }
            keep
        });
        #[cfg(test)]
        self.check();
        self.beside.len() != before
    }

    /// The bytes of an event the document gives to others: one its store holds, or one
    /// held beside it.
    pub(crate) fn get(&self, id: &Id) -> Option<&[u8]> {
        self.store
            .get(id)
            .or_else(|| self.beside.get(id).map(|(bytes, _)| bytes.as_slice()))
    }

    /// Why the document holds `id` beside its store, where it does.
    pub(crate) fn beside(&self, id: &Id) -> Option<Beside> {
        self.beside.get(id).map(|(_, why)| *why)
    }

    /// The document as bytes, at `now`: what its file holds. All it holds but what waits
    /// for what it builds on, which comes again; and what its node refuses of its own,
    /// which a store read anew is told before anything is offered to it.
    pub(crate) fn save(&self, now: Instant) -> Vec<u8> {
        let (own, dropped) = self.store.own();
        let saved = Saved {
            store: self.store.id().0,
            checkpoint: self.store.checkpoint().to_vec(),
            kept: self.store.kept().into_iter().map(Into::into).collect(),
            taken: self
                .store
                .taken()
                .iter()
                .filter_map(|id| self.store.get(id))
                .map(|bytes| bytes.to_vec().into())
                .collect(),
            own: own.iter().map(|id| id.0).collect(),
            dropped: dropped.iter().map(|id| id.0).collect(),
            writes: self
                .store
                .dropped_writes()
                .iter()
                .map(|(id, writes)| (id.0, writes.0))
                .collect(),
            beside: self
                .beside
                .values()
                .map(|(bytes, why)| {
                    let why = match why {
                        Beside::Own => SavedBeside::Own,
                        Beside::Unjudged => SavedBeside::Unjudged,
                        Beside::Forgotten(since) => {
                            SavedBeside::Forgotten(now.saturating_duration_since(*since).as_secs())
                        }
                    };
                    (bytes.clone().into(), why)
                })
                .collect(),
            entries: self
                .entries
                .values()
                .map(|entry| entry.encode().into())
                .collect(),
        };
        let mut out = FILE.to_vec();
        rmp_serde::encode::write(&mut out, &saved).expect("a document encodes");
        out
    }

    /// The document from the bytes of its file (`save`), at `now`, keeping what a
    /// checkpoint forgot for `keeps_forgotten`. Every event is offered to a store anew,
    /// and every entry checked: what the bytes hold that the store wouldn't take, it
    /// doesn't.
    pub(crate) fn load(
        bytes: &[u8],
        keeps_forgotten: Duration,
        now: Instant,
    ) -> Result<Self, Refused> {
        let body = bytes
            .strip_prefix(FILE)
            .ok_or_else(|| Refused::new("no document of a set of events"))?;
        let saved: Saved =
            rmp_serde::from_slice(body).map_err(|error| Refused::new(error.to_string()))?;
        let id = Id(saved.store);
        let kept: Vec<Vec<u8>> = saved
            .kept
            .into_iter()
            .map(|bytes| bytes.into_vec())
            .collect();
        let store = if Id::of(&saved.checkpoint) == id {
            Store::new(saved.checkpoint, kept)?
        } else {
            Store::pinned(id, saved.checkpoint, kept)?
        };
        let ids = |ids: &[[u8; 32]]| ids.iter().map(|id| Id(*id)).collect::<Vec<Id>>();
        let writes: Vec<(Id, Id)> = saved
            .writes
            .iter()
            .map(|(id, writes)| (Id(*id), Id(*writes)))
            .collect();
        let store = store.refusing(&ids(&saved.own), &ids(&saved.dropped), &writes);
        let mut set = Self::new(store, keeps_forgotten);
        for event in saved.taken {
            set.store.offer(event.into_vec());
        }
        set.settle(now);
        for (bytes, why) in saved.beside {
            let bytes = bytes.into_vec();
            let id = Id::of(&bytes);
            if bytes.len() > F::LARGEST || set.store.get(&id).is_some() {
                continue;
            }
            let why = match why {
                SavedBeside::Own => Beside::Own,
                SavedBeside::Unjudged => {
                    set.unjudged.push_back(id);
                    set.unjudged_bytes += bytes.len();
                    Beside::Unjudged
                }
                // As long ago as the file says, as far as this clock goes back.
                SavedBeside::Forgotten(ago) => {
                    Beside::Forgotten(now.checked_sub(Duration::from_secs(ago)).unwrap_or(now))
                }
            };
            set.names.insert(id.0);
            set.beside.insert(id, (bytes, why));
        }
        set.settle(now);
        set.expire(now);
        for entry in saved.entries {
            if let Some(entry) = Entry::decode(&entry) {
                set.put_entry(entry);
            }
        }
        Ok(set)
    }

    /// That the names kept are those of what the document holds: looked at each time
    /// while they are few, and now and then when many.
    #[cfg(test)]
    fn check(&self) {
        assert_eq!(
            self.stands,
            stands_of(&self.store),
            "where the store stands"
        );
        assert!(
            self.entries.len() == self.entry_names.len()
                && self
                    .entries
                    .iter()
                    .all(|(node, entry)| self.entry_names.get(&entry.name()) == Some(node)),
            "the entries' names"
        );
        if self.names.len() > 256 && !self.names.len().is_multiple_of(61) {
            return;
        }
        assert!(
            self.names.iter().eq(self.named().iter()),
            "the names kept aren't what the document holds"
        );
    }

    /// The names of all the document gives to others, to catch up by
    /// (`document::ranges`): what its store took and what its checkpoint keeps, and what
    /// it holds beside.
    pub(crate) fn names(&self) -> &Names {
        &self.names
    }

    /// The names anew, from what the document holds: what `names` keeps.
    #[cfg(test)]
    pub(crate) fn named(&self) -> BTreeSet<Name> {
        self.store
            .taken()
            .iter()
            .map(|id| id.0)
            .chain(self.store.kept().iter().map(|bytes| Id::of(bytes).0))
            .chain(self.beside.keys().map(|id| id.0))
            .chain(self.entries.values().map(Entry::name))
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::super::testfold::{self, TestFold};
    use super::*;

    const KEEPS: Duration = Duration::from_secs(60);

    fn set() -> Set<TestFold> {
        Set::new(
            Store::new(testfold::root("tests"), Vec::new()).expect("a root"),
            KEEPS,
        )
    }

    fn taken(offered: Offered) -> Id {
        match offered {
            Offered::Taken(ids) => ids[0],
            other => panic!("not taken: {other:?}"),
        }
    }

    #[test]
    fn what_the_store_takes_is_the_stores() {
        let mut set = set();
        let now = Instant::now();
        let root = set.store().id();
        let put = testfold::put(&[root], "a", "1");
        let id = taken(set.offer(put.clone(), now));
        assert_eq!(set.get(&id), Some(put.as_slice()));
        assert_eq!(set.beside(&id), None);
        assert_eq!(set.named(), BTreeSet::from([id.0]));
    }

    #[test]
    fn what_the_fold_refuses_is_held_by_nobody() {
        let mut set = set();
        let now = Instant::now();
        let root = set.store().id();
        let junk = testfold::junk(&[root]);
        let id = Id::of(&junk);
        assert!(matches!(
            set.offer(junk, now),
            Offered::Refused(Refusal::Judged(_))
        ));
        // Nor what builds on it, nor what is no event.
        let on = testfold::put(&[id], "a", "1");
        let on_id = Id::of(&on);
        assert_eq!(set.offer(on, now), Offered::Refused(Refusal::BuiltOn(id)));
        assert_eq!(
            set.offer(b"no event".to_vec(), now),
            Offered::Refused(Refusal::None)
        );
        assert_eq!(set.get(&id), None);
        assert_eq!(set.get(&on_id), None);
        assert!(set.names().is_empty());
    }

    #[test]
    fn what_the_node_refuses_of_its_own_it_gives_to_others() {
        let mut set = set();
        let now = Instant::now();
        let root = set.store().id();
        taken(set.offer(testfold::era(&[root], 1, "one"), now));
        let other = testfold::era(&[root], 1, "other");
        let other_id = Id::of(&other);
        assert_eq!(
            set.offer(other.clone(), now),
            Offered::Refused(Refusal::Own)
        );
        assert_eq!(set.get(&other_id), Some(other.as_slice()));
        assert_eq!(set.beside(&other_id), Some(Beside::Own));
        // And what builds on it, unjudged; and on that.
        let on = testfold::put(&[other_id], "a", "1");
        let on_id = Id::of(&on);
        assert_eq!(
            set.offer(on.clone(), now),
            Offered::Refused(Refusal::BuiltOn(other_id))
        );
        assert_eq!(set.beside(&on_id), Some(Beside::Unjudged));
        let further = testfold::put(&[on_id], "a", "2");
        let further_id = Id::of(&further);
        set.offer(further, now);
        assert_eq!(set.beside(&further_id), Some(Beside::Unjudged));
        assert!(set.names().contains(&other_id.0));
        assert!(set.names().contains(&further_id.0));
        // Offered again, it is as it was.
        assert_eq!(set.offer(other, now), Offered::Refused(Refusal::Own));
        assert_eq!(set.beside(&other_id), Some(Beside::Own));
    }

    #[test]
    fn what_waited_on_the_nodes_own_is_held_unjudged() {
        let mut set = set();
        let now = Instant::now();
        let root = set.store().id();
        taken(set.offer(testfold::era(&[root], 1, "one"), now));
        let other = testfold::era(&[root], 1, "other");
        let other_id = Id::of(&other);
        // What builds on it comes first, and waits.
        let on = testfold::put(&[other_id], "a", "1");
        let on_id = Id::of(&on);
        assert_eq!(set.offer(on, now), Offered::Waiting);
        assert_eq!(set.beside(&on_id), None);
        set.offer(other, now);
        assert_eq!(set.beside(&on_id), Some(Beside::Unjudged));
    }

    #[test]
    fn no_more_is_held_unjudged_than_the_bound() {
        let mut set = set();
        let now = Instant::now();
        let root = set.store().id();
        taken(set.offer(testfold::era(&[root], 1, "one"), now));
        let other = testfold::era(&[root], 1, "other");
        let other_id = Id::of(&other);
        set.offer(other, now);
        let mut ids = Vec::new();
        for n in 0..UNJUDGED + 10 {
            let on = testfold::put(&[other_id], "a", &n.to_string());
            ids.push(Id::of(&on));
            set.offer(on, now);
        }
        // The oldest went; the node's own stays.
        assert_eq!(set.beside(&ids[0]), None);
        assert_eq!(set.beside(&ids[9]), None);
        assert_eq!(set.beside(&ids[10]), Some(Beside::Unjudged));
        assert_eq!(
            set.beside(ids.last().expect("some")),
            Some(Beside::Unjudged)
        );
        assert_eq!(set.beside(&other_id), Some(Beside::Own));
        assert_eq!(set.unjudged.len(), UNJUDGED);
    }

    #[test]
    fn what_an_operator_drops_is_given_to_others_and_taken_when_allowed() {
        let mut set = set();
        let now = Instant::now();
        let root = set.store().id();
        let one = testfold::era(&[root], 1, "one");
        let one_id = taken(set.offer(one.clone(), now));
        let on = testfold::put(&[one_id], "a", "1");
        let on_id = taken(set.offer(on, now));
        assert_eq!(set.drop_taken(&[one_id], now), Ok(vec![one_id, on_id]));
        assert_eq!(set.beside(&one_id), Some(Beside::Own));
        assert_eq!(set.beside(&on_id), Some(Beside::Unjudged));
        assert_eq!(set.get(&one_id), Some(one.as_slice()));
        assert!(set.store().taken().is_empty());
        // Allowed again, the store takes both, and the document holds neither beside.
        set.allow(&[one_id], now);
        assert_eq!(set.beside(&one_id), None);
        assert_eq!(set.beside(&on_id), None);
        assert_eq!(set.store().taken().len(), 2);
        assert!(set.unjudged.is_empty());
        assert_eq!(set.unjudged_bytes, 0);
    }

    #[test]
    fn what_a_checkpoint_forgot_is_kept_for_a_while() {
        let mut set = set();
        let now = Instant::now();
        let root = set.store().id();
        let first = testfold::put(&[root], "a", "1");
        let first_id = taken(set.offer(first.clone(), now));
        let second = taken(set.offer(testfold::put(&[first_id], "a", "2"), now));
        let lock = taken(set.offer(testfold::lock(&[second], "b"), now));
        let before = set.named();
        taken(set.offer(testfold::cut(&[lock], 1, &[lock]), now));
        // The store moved, and forgot the first put; the document didn't.
        assert_eq!(set.store().get(&first_id), None);
        assert_eq!(set.get(&first_id), Some(first.as_slice()));
        assert_eq!(set.beside(&first_id), Some(Beside::Forgotten(now)));
        assert!(set.named().is_superset(&before));
        // Until its time is up.
        assert!(!set.expire(now + KEEPS - Duration::from_secs(1)));
        assert_eq!(set.get(&first_id), Some(first.as_slice()));
        assert!(set.expire(now + KEEPS));
        assert_eq!(set.get(&first_id), None);
        assert!(!set.names().contains(&first_id.0));
    }

    fn key(seed: u8) -> crate::identity::NodeKey {
        crate::identity::NodeKey::from_seed([seed; 32])
    }

    /// Makes the node of `key` a member of group `group` (none: no member), on `on`.
    fn member(set: &mut Set<TestFold>, on: Id, key: u8, group: &str) -> Id {
        let node = self::key(key).id();
        taken(set.offer(
            testfold::put(&[on], &format!("node:{node}"), group),
            Instant::now(),
        ))
    }

    fn entry(set: &Set<TestFold>, key: u8, count: u64, alias: &str) -> Entry {
        Entry::new(
            &set.store().id(),
            &self::key(key),
            count,
            &serde_json::json!({ "alias": alias }),
        )
    }

    #[test]
    fn a_members_newest_entry_is_its_entry() {
        let mut set = set();
        let root = set.store().id();
        member(&mut set, root, 1, "a");
        let node = key(1).id();
        let first = entry(&set, 1, 1, "one");
        assert_eq!(set.put_entry(first.clone()), Put::Taken);
        assert_eq!(set.put_entry(first.clone()), Put::Held);
        assert_eq!(set.entry(&node), Some(&first));
        assert!(set.names().contains(&first.name()));
        assert!(!set.wants(&first.name()));
        let second = entry(&set, 1, 2, "two");
        assert!(set.wants(&second.name()));
        assert_eq!(set.put_entry(second.clone()), Put::Taken);
        assert_eq!(set.put_entry(first.clone()), Put::Older);
        assert_eq!(set.entry(&node), Some(&second));
        assert!(!set.names().contains(&first.name()));
        assert_eq!(set.entry_named(&second.name()), Some(&second));
        assert_eq!(set.entries().count(), 1);
    }

    #[test]
    fn of_two_entries_of_one_count_the_lower_name_is_kept() {
        let mut set = set();
        let root = set.store().id();
        member(&mut set, root, 1, "a");
        let (one, other) = (entry(&set, 1, 1, "one"), entry(&set, 1, 1, "other"));
        let (low, high) = if one.name() < other.name() {
            (one, other)
        } else {
            (other, one)
        };
        // Whichever comes first.
        assert_eq!(set.put_entry(high.clone()), Put::Taken);
        assert_eq!(set.put_entry(low.clone()), Put::Taken);
        assert_eq!(set.put_entry(high), Put::Older);
        assert_eq!(set.entry(&key(1).id()), Some(&low));
    }

    #[test]
    fn an_entry_of_no_member_is_held_by_nobody() {
        let mut set = set();
        let root = set.store().id();
        let stranger = entry(&set, 2, 1, "stranger");
        assert_eq!(set.put_entry(stranger.clone()), Put::Stranger);
        assert_eq!(set.entry(&key(2).id()), None);
        // Not asked for again, until who is a member changes.
        assert!(!set.wants(&stranger.name()));
        let made = member(&mut set, root, 2, "a");
        assert!(set.wants(&stranger.name()));
        assert_eq!(set.put_entry(stranger.clone()), Put::Taken);
        // And gone with its node.
        member(&mut set, made, 2, "");
        assert_eq!(set.entry(&key(2).id()), None);
        assert!(!set.names().contains(&stranger.name()));
    }

    #[test]
    fn an_entry_of_another_store_or_changed_is_refused() {
        let mut set = set();
        let root = set.store().id();
        member(&mut set, root, 1, "a");
        let other = Entry::new(
            &Id::of(b"another store"),
            &key(1),
            1,
            &serde_json::json!({}),
        );
        assert!(matches!(set.put_entry(other), Put::Refused(_)));
        assert_eq!(set.entries().count(), 0);
    }

    #[test]
    fn what_the_store_has_seen_isnt_wanted() {
        let mut set = set();
        let now = Instant::now();
        let root = set.store().id();
        let put = testfold::put(&[root], "a", "1");
        let junk = testfold::junk(&[root]);
        let waits = testfold::put(&[Id::of(b"nowhere")], "a", "1");
        for bytes in [&put, &junk, &waits] {
            assert!(set.wants(&Id::of(bytes).0));
            set.offer(bytes.clone(), now);
            assert!(!set.wants(&Id::of(bytes).0));
        }
        assert!(!set.wants(&root.0));
    }

    #[test]
    fn a_document_reads_back_from_its_file() {
        let mut set = set();
        let now = Instant::now();
        let root = set.store().id();
        // A member and its entry; an era, and one the node refuses of its own, with what
        // builds on it; puts, a lock, and a cut that forgets the first of them.
        let made = member(&mut set, root, 1, "a");
        let entry = entry(&set, 1, 1, "one");
        set.put_entry(entry.clone());
        let era = taken(set.offer(testfold::era(&[made], 1, "one"), now));
        let other = testfold::era(&[made], 1, "other");
        let other_id = Id::of(&other);
        set.offer(other, now);
        let on = testfold::put(&[other_id], "x", "1");
        let on_id = Id::of(&on);
        set.offer(on, now);
        let first = taken(set.offer(testfold::put(&[era], "a", "1"), now));
        let second = taken(set.offer(testfold::put(&[first], "a", "2"), now));
        let lock = taken(set.offer(testfold::lock(&[second], "b"), now));
        taken(set.offer(testfold::cut(&[lock], 1, &[lock]), now));
        let after = taken(set.offer(testfold::put(&set.store().heads(), "c", "1"), now));
        assert!(matches!(set.beside(&first), Some(Beside::Forgotten(_))));

        let later = now + Duration::from_secs(10);
        let read = Set::<TestFold>::load(&set.save(later), KEEPS, later).expect("a document");
        assert_eq!(read.named(), set.named());
        assert_eq!(read.store().id(), set.store().id());
        assert_eq!(read.store().checkpoint(), set.store().checkpoint());
        assert_eq!(read.store().taken(), set.store().taken());
        assert_eq!(read.store().state().counts(), set.store().state().counts());
        assert!(read.store().get(&after).is_some());
        assert_eq!(read.beside(&other_id), Some(Beside::Own));
        assert_eq!(read.beside(&on_id), Some(Beside::Unjudged));
        assert_eq!(read.entry(&key(1).id()), Some(&entry));
        assert_eq!(read.unjudged_bytes, set.unjudged_bytes);
        // The node refuses its own as before, offered again.
        let mut read = read;
        assert_eq!(
            read.offer(testfold::era(&[made], 1, "other"), later),
            Offered::Refused(Refusal::Own)
        );
        // What the checkpoint forgot is kept for what is left of its time.
        assert!(read.get(&first).is_some());
        assert!(!read.expire(later + KEEPS - Duration::from_secs(11)));
        assert!(read.expire(later + KEEPS - Duration::from_secs(10)));
        assert!(read.get(&first).is_none());
    }

    #[test]
    fn a_file_past_its_time_holds_nothing_forgotten() {
        let mut set = set();
        let now = Instant::now();
        let root = set.store().id();
        let first = taken(set.offer(testfold::put(&[root], "a", "1"), now));
        let second = taken(set.offer(testfold::put(&[first], "a", "2"), now));
        let lock = taken(set.offer(testfold::lock(&[second], "b"), now));
        taken(set.offer(testfold::cut(&[lock], 1, &[lock]), now));
        let later = now + KEEPS;
        let read = Set::<TestFold>::load(&set.save(later), KEEPS, later).expect("a document");
        assert!(read.get(&first).is_none());
        assert_eq!(read.store().taken(), set.store().taken());
    }

    #[test]
    fn what_is_no_document_isnt_read() {
        assert!(Set::<TestFold>::load(b"something else", KEEPS, Instant::now()).is_err());
        let mut cut = set().save(Instant::now());
        cut.truncate(cut.len() - 3);
        assert!(Set::<TestFold>::load(&cut, KEEPS, Instant::now()).is_err());
    }

    #[test]
    fn what_a_move_leaves_beside_the_heads_is_held_no_more() {
        let mut set = set();
        let now = Instant::now();
        let root = set.store().id();
        let first = taken(set.offer(testfold::put(&[root], "a", "1"), now));
        let lock = taken(set.offer(testfold::lock(&[first], "b"), now));
        // Written beside the lock, on the first put: not above the heads to come.
        let beside = taken(set.offer(testfold::put(&[first], "c", "1"), now));
        assert!(set.names().contains(&beside.0));
        taken(set.offer(testfold::cut(&[lock], 1, &[lock]), now));
        assert_eq!(set.get(&beside), None);
        assert!(!set.names().contains(&beside.0));
        assert!(!set.wants(&beside.0));
    }

    #[test]
    fn no_more_wait_than_the_bound() {
        let mut set = set();
        let now = Instant::now();
        let mut waiting = Vec::new();
        for n in 0..WAITS + 5 {
            let on = Id::of(format!("nowhere {n}").as_bytes());
            let put = testfold::put(&[on], "a", "1");
            waiting.push(Id::of(&put));
            assert_eq!(set.offer(put, now), Offered::Waiting);
        }
        // The ones waiting longest went, as if they had never come: wanted again.
        assert!(set.wants(&waiting[0].0));
        assert!(set.wants(&waiting[4].0));
        assert!(!set.wants(&waiting[5].0));
        assert!(!set.wants(&waiting[WAITS + 4].0));
        assert_eq!(set.store().lacks().len(), WAITS);
    }
}