aboutsummaryrefslogtreecommitdiffstats
path: root/src/federation/store/passing.rs
blob: 2e69a96368bacf04670d4be8a853df312f101b4a (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
//! Passing a set of events on (`docs/document.md`, A set of events, Passing on): what
//! two nodes say to each other of their sets, and what a node makes of what it is told.
//! A node keeps nothing of a peer between messages: each message is answered by what the
//! node holds as it comes.
//!
//! * Where a node stands (`Stamp`), said now and then: its store's checkpoint and
//!   heads, which are the same exactly where two stores hold the same; and the
//!   fingerprint of all its names, events and entries.
//! * Fingerprints differ: the two find what differs by ranges (`document::ranges`),
//!   and each asks for the names it lacks and would have (`Set::wants`).
//! * Fingerprints the same and heads not: either the two refuse differently of their
//!   own and hold the same all the same, or someone made fingerprints collide. A node
//!   says its heads, and the other asks for those it doesn't know.
//! * What is asked for by name is sent, as far as it is held; what comes is offered to
//!   the store, or put as an entry; and for what the store then waits on and doesn't
//!   hold, the node asks in turn, back to what both hold.

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

use serde::{Deserialize, Serialize};

use super::entry::Entry;

use super::Refused;
use super::memory::Store;
use super::set::{Put, Set};
use super::{Fold, Id};
use crate::document::ranges::{self, Name};

/// The most names a message of ranges holds, and the most a node asks for at once.
const NAMES: usize = 4096;

/// The most bytes of events and entries in one message.
const BYTES: usize = 1 << 20;

/// Where a node's set stands.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct Stamp {
    /// Of its store's checkpoint and heads.
    heads: [u8; 32],
    /// The fingerprint of all its names.
    names: ranges::Fingerprint,
}

/// An event or an entry, as passed on.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum Unit {
    Event(#[serde(with = "serde_bytes")] Vec<u8>),
    Entry(#[serde(with = "serde_bytes")] Vec<u8>),
    /// The checkpoint the sender's store holds, a root among them: for a node that
    /// starts with nothing but its name (`Start`).
    Checkpoint(#[serde(with = "serde_bytes")] Vec<u8>),
}

/// What one node says to another of its set.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum Message {
    /// Where it stands.
    Stamp(Stamp),
    /// Its store's heads.
    Heads(Vec<Name>),
    /// Ranges of its names, and their fingerprints or the names.
    Ranges(ranges::Message),
    /// Names it lacks and would have.
    Wants(Vec<Name>),
    /// Events and entries: asked for, or new.
    Units(Vec<Unit>),
}

/// A set to be: what a node that starts with nothing gathers of its peers, to begin
/// its store's set from (`docs/document.md`, A set of events, Passing on). It knows its
/// store by its ID, and where it starts by a name: the store's root, which is the
/// store's ID, or a checkpoint its operator pins. It asks for the checkpoint of that
/// name, then for the events that one keeps; each is what its name says, or not
/// taken.
pub(crate) struct Start<F: Fold> {
    store: Id,
    at: Id,
    keeps_forgotten: Duration,
    /// The checkpoint named `at`, once it came, and the events it keeps, by name.
    checkpoint: Option<(Vec<u8>, Vec<Id>)>,
    kept: BTreeMap<Id, Vec<u8>>,
    /// What its node refused of its own, what its operator had it drop, and what the
    /// dropped write (`Store::refusing`): of a set the node held before.
    own: Vec<Id>,
    dropped: Vec<Id>,
    writes: Vec<(Id, Id)>,
    fold: std::marker::PhantomData<F>,
}

impl<F: Fold> Start<F> {
    /// A set of the store `store` to be, starting at the checkpoint named `at`.
    pub(crate) fn new(store: Id, at: Id, keeps_forgotten: Duration) -> Self {
        Self {
            store,
            at,
            keeps_forgotten,
            checkpoint: None,
            kept: BTreeMap::new(),
            own: Vec::new(),
            dropped: Vec::new(),
            writes: Vec::new(),
            fold: std::marker::PhantomData,
        }
    }

    /// Itself, its store to refuse what `held`, a set the node held before, refuses of
    /// its node's own and as its operator had it drop: a node that begins anew from
    /// another checkpoint keeps what it refused.
    pub(crate) fn refusing_as(mut self, held: &Set<F>) -> Self {
        (self.own, self.dropped) = held.store().own();
        self.writes = held.store().dropped_writes();
        self
    }

    /// The store it is to hold.
    pub(crate) fn store(&self) -> Id {
        self.store
    }

    /// The names it asks a peer for now.
    pub(crate) fn wants(&self) -> Vec<Name> {
        match &self.checkpoint {
            None => vec![self.at.0],
            Some((_, keeps)) => keeps
                .iter()
                .filter(|id| !self.kept.contains_key(id))
                .map(|id| id.0)
                .take(NAMES)
                .collect(),
        }
    }

    /// Takes what a peer sent of what it asked for. The set, once it has all it
    /// begins from; a checkpoint that is none of the fold's, or that the store doesn't
    /// begin from, is let go of, to be asked for again.
    pub(crate) fn take(&mut self, units: Vec<Unit>) -> Option<Set<F>> {
        for unit in units {
            match unit {
                Unit::Checkpoint(bytes)
                    if self.checkpoint.is_none() && Id::of(&bytes) == self.at =>
                {
                    if let Some((_, keeps)) = F::parts(&bytes) {
                        self.checkpoint = Some((bytes, keeps));
                    }
                }
                Unit::Event(bytes) if bytes.len() <= F::LARGEST => {
                    let id = Id::of(&bytes);
                    let kept = self
                        .checkpoint
                        .as_ref()
                        .is_some_and(|(_, keeps)| keeps.contains(&id));
                    if kept {
                        self.kept.insert(id, bytes);
                    }
                }
                _ => {}
            }
        }
        let (checkpoint, keeps) = self.checkpoint.as_ref()?;
        if keeps.iter().any(|id| !self.kept.contains_key(id)) {
            return None;
        }
        let kept: Vec<Vec<u8>> = self.kept.values().cloned().collect();
        let store: Result<Store<F>, Refused> = if self.at == self.store {
            Store::new(checkpoint.clone(), kept)
        } else {
            Store::pinned(self.store, checkpoint.clone(), kept)
        };
        match store {
            Ok(store) => Some(
                Set::new(
                    store.refusing(&self.own, &self.dropped, &self.writes),
                    self.keeps_forgotten,
                )
                .pinned_at((self.at != self.store).then_some(self.at)),
            ),
            Err(_) => {
                self.checkpoint = None;
                self.kept.clear();
                None
            }
        }
    }
}

/// What a node took of a message.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct Took {
    /// The events its store took, in the order taken.
    pub(crate) events: Vec<Id>,
    /// The members whose entry it took.
    pub(crate) entries: Vec<String>,
}

impl Took {
    pub(crate) fn is_empty(&self) -> bool {
        self.events.is_empty() && self.entries.is_empty()
    }
}

/// Where `set` stands.
pub(crate) fn stamp<F: Fold>(set: &Set<F>) -> Stamp {
    Stamp {
        heads: set.stands(),
        names: set.names().fingerprint(),
    }
}

/// The unit named `name`, where `set` holds it: an event, an entry, or the checkpoint
/// its store holds.
pub(crate) fn unit<F: Fold>(set: &Set<F>, name: &Name) -> Option<Unit> {
    let checkpoint = set.store().checkpoint();
    if Id::of(checkpoint).0 == *name {
        return Some(Unit::Checkpoint(checkpoint.to_vec()));
    }
    set.get(&Id(*name))
        .map(|bytes| Unit::Event(bytes.to_vec()))
        .or_else(|| {
            set.entry_named(name)
                .map(|entry| Unit::Entry(entry.encode()))
        })
}

/// What `set` makes of `message`, at `now`: what to say back, and what it took.
pub(crate) fn receive<F: Fold>(
    set: &mut Set<F>,
    message: Message,
    now: Instant,
) -> (Vec<Message>, Took) {
    let mut replies = Vec::new();
    let mut took = Took::default();
    match message {
        Message::Stamp(theirs) => {
            let ours = stamp(set);
            if theirs.names != ours.names {
                replies.push(Message::Ranges(ranges::open(set.names())));
            } else if theirs.heads != ours.heads {
                replies.push(Message::Heads(
                    set.store().heads().iter().map(|id| id.0).collect(),
                ));
            }
        }
        Message::Heads(heads) => ask(set, heads, &mut replies),
        Message::Ranges(theirs) => {
            let answer = ranges::answer(set.names(), &theirs, NAMES, salt());
            ask(set, answer.lacking, &mut replies);
            if let Some(reply) = answer.reply {
                replies.push(Message::Ranges(reply));
            }
        }
        Message::Wants(names) => {
            let mut units = Vec::new();
            let mut bytes = 0;
            for name in names.iter().take(NAMES) {
                let Some(unit) = unit(set, name) else {
                    continue;
                };
                let size = match &unit {
                    Unit::Event(bytes) | Unit::Entry(bytes) | Unit::Checkpoint(bytes) => {
                        bytes.len()
                    }
                };
                // What doesn't fit, the peer asks for again.
                if bytes + size > BYTES && !units.is_empty() {
                    break;
                }
                bytes += size;
                units.push(unit);
            }
            if !units.is_empty() {
                replies.push(Message::Units(units));
            }
        }
        Message::Units(units) => {
            // The events at once, then the entries: who is a member may be among the
            // events.
            let mut events = Vec::new();
            let mut entries = Vec::new();
            for unit in units {
                match unit {
                    Unit::Event(bytes) => events.push(bytes),
                    Unit::Entry(bytes) => entries.push(bytes),
                    // A node holding a set built its checkpoint itself.
                    Unit::Checkpoint(_) => {}
                }
            }
            took.events = set.offer_all(events, now);
            for bytes in entries {
                if let Some(entry) = Entry::decode(&bytes) {
                    let node = entry.node();
                    if set.put_entry(entry) == Put::Taken {
                        took.entries.push(node);
                    }
                }
            }
            // What the store waits on now and doesn't hold: back to what both hold.
            let lacks = set.store().lacks().iter().map(|id| id.0).collect();
            ask(set, lacks, &mut replies);
        }
    }
    (replies, took)
}

/// A number nobody knows beforehand, to split ranges by (`ranges::answer`).
fn salt() -> u64 {
    let mut bytes = [0; 8];
    // Without randomness, the same each time: ranges are compared all the same.
    let _ = getrandom::fill(&mut bytes);
    u64::from_le_bytes(bytes)
}

/// Asks for those of `names` that `set` would have.
fn ask<F: Fold>(set: &Set<F>, names: Vec<Name>, replies: &mut Vec<Message>) {
    let wanted: Vec<Name> = names
        .into_iter()
        .filter(|name| set.wants(name))
        .take(NAMES)
        .collect();
    if !wanted.is_empty() {
        replies.push(Message::Wants(wanted));
    }
}

#[cfg(test)]
mod tests {
    use std::collections::VecDeque;
    use std::time::Duration;

    use super::super::memory::{Offered, Store};
    use super::super::testfold::{self, TestFold};
    use super::*;
    use crate::testrand::{Rng, for_seeds};

    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 key(seed: u8) -> crate::identity::NodeKey {
        crate::identity::NodeKey::from_seed([seed; 32])
    }

    /// Has every node tell every other where it stands, and all that follows from it
    /// delivered, in an order `rng` chooses, losing none; the messages that went.
    fn settle(sets: &mut [Set<TestFold>], rng: &mut Rng, now: Instant) -> usize {
        let mut queue: VecDeque<(usize, usize, Message)> = VecDeque::new();
        for from in 0..sets.len() {
            for to in 0..sets.len() {
                if from != to {
                    queue.push_back((from, to, Message::Stamp(stamp(&sets[from]))));
                }
            }
        }
        let mut messages = 0;
        while !queue.is_empty() {
            let at = rng.below(queue.len());
            let (from, to, message) = queue.remove(at).expect("one queued");
            messages += 1;
            assert!(messages < 100_000, "passing on doesn't end");
            let (replies, _) = receive(&mut sets[to], message, now);
            for reply in replies {
                queue.push_back((to, from, reply));
            }
        }
        messages
    }

    /// Rounds of `settle` until a round changes nothing; how many it took.
    fn settled(sets: &mut [Set<TestFold>], rng: &mut Rng, now: Instant) -> usize {
        for round in 1..=20 {
            let before: Vec<_> = sets.iter().map(|set| set.named()).collect();
            settle(sets, rng, now);
            if sets.iter().map(|set| set.named()).collect::<Vec<_>>() == before {
                return round;
            }
        }
        panic!("the sets don't settle");
    }

    #[test]
    fn two_that_stand_alike_say_nothing_more() {
        let mut sets = [set(), set()];
        let now = Instant::now();
        let root = sets[0].store().id();
        for set in &mut sets {
            set.offer(testfold::put(&[root], "a", "1"), now);
        }
        assert_eq!(stamp(&sets[0]), stamp(&sets[1]));
        let mut rng = Rng::new(1);
        assert_eq!(settle(&mut sets, &mut rng, now), 2);
    }

    #[test]
    fn one_behind_catches_up() {
        let mut sets = [set(), set()];
        let now = Instant::now();
        let root = sets[0].store().id();
        let mut on = root;
        for n in 0..200 {
            let put = testfold::put(&[on], "a", &n.to_string());
            on = Id::of(&put);
            sets[0].offer(put, now);
        }
        let mut rng = Rng::new(2);
        settle(&mut sets, &mut rng, now);
        assert_eq!(sets[1].store().taken(), sets[0].store().taken());
        assert_eq!(stamp(&sets[0]), stamp(&sets[1]));
    }

    #[test]
    fn nodes_that_wrote_apart_come_to_hold_the_same() {
        for_seeds(30, |rng| {
            let now = Instant::now();
            let count = rng.between(2, 5);
            let mut sets: Vec<Set<TestFold>> = (0..count).map(|_| set()).collect();
            let root = sets[0].store().id();
            // The members, known to all; then each writes on what it holds, apart.
            let mut on = root;
            for node in 0..count {
                let member = testfold::put(&[on], &format!("node:{}", key(node as u8).id()), "a");
                on = Id::of(&member);
                for set in &mut sets {
                    set.offer(member.clone(), now);
                }
            }
            for (node, set) in sets.iter_mut().enumerate() {
                let mut on = on;
                for n in 0..rng.between(0, 40) {
                    let put = testfold::put(&[on], &format!("k{}", rng.below(5)), &n.to_string());
                    on = Id::of(&put);
                    set.offer(put, now);
                }
                let entry = Entry::new(
                    &root,
                    &key(node as u8),
                    rng.between(1, 3) as u64,
                    &serde_json::json!({ "alias": node }),
                );
                assert_eq!(set.put_entry(entry), Put::Taken);
            }
            settled(&mut sets, rng, now);
            let first = &sets[0];
            for set in &sets[1..] {
                assert_eq!(stamp(set), stamp(first));
                assert_eq!(set.named(), first.named());
                assert_eq!(set.store().state().counts(), first.store().state().counts());
                assert_eq!(set.entries().count(), count);
            }
        });
    }

    #[test]
    fn what_one_refuses_of_its_own_still_reaches_the_others_through_it() {
        // b took the other era, and stands between a, which wrote on the one, and c.
        let (mut a, mut b, c) = (set(), set(), set());
        let now = Instant::now();
        let root = a.store().id();
        let other = testfold::era(&[root], 1, "other");
        b.offer(other, now);
        let one = testfold::era(&[root], 1, "one");
        let one_id = Id::of(&one);
        a.offer(one, now);
        let on = testfold::put(&[one_id], "a", "1");
        let on_id = Id::of(&on);
        a.offer(on, now);
        let mut rng = Rng::new(3);
        // a and b; then b and c: never a and c.
        let mut pair = [a, b];
        settled(&mut pair, &mut rng, now);
        let [a, b] = pair;
        assert!(b.store().get(&one_id).is_none());
        assert!(b.get(&one_id).is_some());
        assert!(b.get(&on_id).is_some());
        let mut pair = [b, c];
        settled(&mut pair, &mut rng, now);
        let [b, c] = pair;
        // c takes whichever era came first of b: both reached it.
        assert!(c.get(&one_id).is_some());
        assert!(c.get(&on_id).is_some());
        assert_eq!(c.named(), b.named());
        assert_eq!(a.names().len(), 3);
    }

    #[test]
    fn what_is_asked_for_and_held_is_sent_within_the_bound() {
        let mut set = set();
        let now = Instant::now();
        let root = set.store().id();
        let large = "x".repeat(40_000);
        let mut names = vec![[9; 32]];
        for n in 0..40 {
            let put = testfold::put(&[root], &format!("k{n}"), &large);
            names.push(Id::of(&put).0);
            assert!(matches!(set.offer(put, now), Offered::Taken(_)));
        }
        let (replies, took) = receive(&mut set, Message::Wants(names.clone()), now);
        assert!(took.is_empty());
        let [Message::Units(units)] = replies.as_slice() else {
            panic!("no units: {replies:?}");
        };
        let sizes: Vec<usize> = units
            .iter()
            .map(|unit| match unit {
                Unit::Event(bytes) | Unit::Entry(bytes) | Unit::Checkpoint(bytes) => bytes.len(),
            })
            .collect();
        assert!(sizes.iter().sum::<usize>() <= BYTES);
        assert!(
            units.len() > 20 && units.len() < 40,
            "{} units",
            units.len()
        );
        // Those asked for first, as far as held.
        assert_eq!(units[0], unit(&set, &names[1]).expect("held"));
    }

    #[test]
    fn a_node_asks_back_for_what_an_event_builds_on() {
        // Told a head alone, a node asks for it, and then for what it builds on.
        let mut ahead = set();
        let mut behind = set();
        let now = Instant::now();
        let root = ahead.store().id();
        let first = testfold::put(&[root], "a", "1");
        let first_id = Id::of(&first);
        let second = testfold::put(&[first_id], "a", "2");
        let second_id = Id::of(&second);
        ahead.offer(first, now);
        ahead.offer(second, now);
        let (replies, _) = receive(&mut behind, Message::Heads(vec![second_id.0]), now);
        assert_eq!(replies, vec![Message::Wants(vec![second_id.0])]);
        let (units, _) = receive(&mut ahead, replies[0].clone(), now);
        let (replies, took) = receive(&mut behind, units[0].clone(), now);
        assert!(took.is_empty());
        assert_eq!(replies, vec![Message::Wants(vec![first_id.0])]);
        let (units, _) = receive(&mut ahead, replies[0].clone(), now);
        let (replies, took) = receive(&mut behind, units[0].clone(), now);
        assert!(replies.is_empty());
        assert_eq!(took.events, vec![first_id, second_id]);
    }

    #[test]
    fn messages_read_back_from_their_bytes() {
        let set = set();
        for message in [
            Message::Stamp(stamp(&set)),
            Message::Heads(vec![[1; 32]]),
            Message::Ranges(ranges::open(set.names())),
            Message::Wants(vec![[2; 32]]),
            Message::Units(vec![Unit::Event(vec![1, 2]), Unit::Entry(vec![3])]),
        ] {
            let bytes = rmp_serde::to_vec(&message).expect("a message encodes");
            assert_eq!(
                rmp_serde::from_slice::<Message>(&bytes).expect("a message"),
                message
            );
        }
    }

    #[test]
    fn a_node_with_nothing_begins_its_set_from_what_peers_give_by_name() {
        // A store that moved to a checkpoint, which keeps an event.
        let mut ahead = set();
        let now = Instant::now();
        let root = ahead.store().id();
        let first = testfold::put(&[root], "a", "1");
        let first_id = Id::of(&first);
        let second = testfold::put(&[first_id], "a", "2");
        let second_id = Id::of(&second);
        let lock = testfold::lock(&[second_id], "b");
        let lock_id = Id::of(&lock);
        let cut = testfold::cut(&[lock_id], 1, &[lock_id]);
        for event in [first, second, lock, cut.clone()] {
            assert!(matches!(ahead.offer(event, now), Offered::Taken(_)));
        }
        let pinned = Id::of(ahead.store().checkpoint());
        assert_ne!(pinned, root);

        // From the root: the checkpoint named by the store's ID, were it still held.
        let mut from_root = Start::<TestFold>::new(root, root, KEEPS);
        assert_eq!(from_root.wants(), vec![root.0]);
        assert_eq!(unit(&ahead, &root.0), None);
        let fresh = set();
        let Some(Unit::Checkpoint(bytes)) = unit(&fresh, &root.0) else {
            panic!("no root");
        };
        let begun = from_root
            .take(vec![Unit::Checkpoint(bytes)])
            .expect("a set, the root keeping nothing");
        assert_eq!(begun.store().id(), root);
        assert_eq!(begun.pinned(), None);

        // From a checkpoint its operator pins: that, then what it keeps; and refusing
        // what a set the node held before refused as its operator had it drop.
        let mut held = set();
        let dropped = match held.offer(testfold::put(&[root], "c", "1"), now) {
            Offered::Taken(ids) => ids[0],
            other => panic!("not taken: {other:?}"),
        };
        held.drop_taken(&[dropped], now).expect("dropped");
        let mut start = Start::<TestFold>::new(root, pinned, KEEPS).refusing_as(&held);
        assert_eq!(start.wants(), vec![pinned.0]);
        // What isn't what its name says isn't taken.
        assert!(
            start
                .take(vec![Unit::Checkpoint(b"another".to_vec())])
                .is_none()
        );
        assert_eq!(start.wants(), vec![pinned.0]);
        let checkpoint = unit(&ahead, &pinned.0).expect("its checkpoint");
        assert!(matches!(checkpoint, Unit::Checkpoint(_)));
        assert!(start.take(vec![checkpoint]).is_none());
        let wanted = start.wants();
        assert!(!wanted.is_empty() && !wanted.contains(&pinned.0));
        let kept: Vec<Unit> = wanted
            .iter()
            .map(|name| unit(&ahead, name).expect("kept"))
            .collect();
        let begun = start.take(kept).expect("a set");
        assert_eq!(begun.store().id(), root);
        assert_eq!(begun.store().checkpoint(), ahead.store().checkpoint());
        assert_eq!(begun.store().own(), (Vec::new(), vec![dropped]));
        // Its file says which checkpoint was pinned.
        assert_eq!(begun.pinned(), Some(pinned));
        let read = Set::<TestFold>::load(&begun.save(now), KEEPS, now).expect("it reads");
        assert_eq!(read.pinned(), Some(pinned));
        // And it goes on as any set: what the other holds after the checkpoint comes.
        let mut sets = [ahead, begun];
        let mut rng = Rng::new(9);
        settle(&mut sets, &mut rng, now);
        assert!(sets[1].store().get(&Id::of(&cut)).is_some());
        assert_eq!(sets[1].store().taken(), sets[0].store().taken());
    }
}