legit-hamming 0.1.1

Exact Hamming radius search over 64-bit and 256-bit hashes in memory: a scan or multi-index hashing, chosen per query, checked against one reference, and a search service over snapshots
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
//! The set a request searches: a loaded snapshot, and over it the changes logged since, searched
//! as one set.
//!
//! The snapshot's records and their tables are a [`Planned`] set. The changes are a table keyed by
//! id, held as a few immutable levels, each sorted by id, a newer level's entry for an id masking
//! an older one's: a value, or a removal. A level's entry masks the snapshot's record of its id
//! too. A search is the snapshot's search with its masked records left out where the hits are
//! kept ([`search_batch_excluding`]), and a scan of each level's values with the values a newer
//! level masks left out the same way; the lists are then merged by distance and id, keeping what
//! a limit, a size budget or a time budget keeps of one search over the snapshot with every change
//! applied. Nothing is filtered after a list was bounded, so a cut list still holds the nearest
//! matches of that set.
//!
//! A set is immutable: a change makes a new one, which shares the snapshot and the levels it
//! didn't touch, so a search runs on one consistent set from start to end, and the `seq` it
//! reports is the last change applied in it.

use std::sync::Arc;

use super::log::Entry;
use crate::neighbours::{NeighbourTable, neighbour_table};
use crate::planned::Planned;
use crate::records::Records;
use crate::scan::Scan;
use crate::search::{Cut, Found, Match, Memory, Options, Search, Stop, search_batch_until};
use crate::value::Value;

/// The values a level holds from which its scan is split across the threads a search was given:
/// about a quarter of a millisecond of scanning on one core.
const SPLIT_LEVEL: usize = 1 << 20;

#[cfg(test)]
thread_local! {
    /// The levels built on this thread: what a test of a refused change counts.
    pub(crate) static LEVELS_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// A level of changes: every id it holds, a value or a removal, in rising id order.
#[derive(Debug)]
pub(crate) struct Level<V> {
    /// The ids that hold a value, with their values, scanned on the best path.
    values: Scan<V>,
    records: Arc<Records<V>>,
    /// The ids removed, rising.
    removed: Vec<u64>,
}

impl<V: Value> Level<V> {
    /// A level of `changes`: each id once, in rising id order, set to a value or removed.
    fn new(changes: impl IntoIterator<Item = (u64, Option<V>)>) -> Self {
        #[cfg(test)]
        LEVELS_BUILT.with(|built| built.set(built.get() + 1));
        let mut records = Records::with_ids();
        let mut removed = Vec::new();
        for (id, value) in changes {
            match value {
                Some(value) => records
                    .push(id, value)
                    .expect("ids rise, and a level is far below 2³² records"),
                None => removed.push(id),
            }
        }
        let records = Arc::new(records);
        Self {
            values: Scan::new(Arc::clone(&records)),
            records,
            removed,
        }
    }

    fn len(&self) -> usize {
        self.records.len() + self.removed.len()
    }

    fn ids(&self) -> &[u64] {
        self.records.ids().unwrap_or_default()
    }

    /// What this level says of `id`: `Some(Some(value))`, `Some(None)` for a removal, or `None`
    /// when it holds no change of it.
    fn get(&self, id: u64) -> Option<Option<V>> {
        if let Ok(position) = self.ids().binary_search(&id) {
            return Some(Some(self.records.value(position)));
        }
        self.removed.binary_search(&id).ok().map(|_| None)
    }

    fn holds(&self, id: u64) -> bool {
        self.ids().binary_search(&id).is_ok() || self.removed.binary_search(&id).is_ok()
    }

    /// Every change, in rising id order.
    fn changes(&self) -> impl Iterator<Item = (u64, Option<V>)> + '_ {
        let mut values = self.ids().iter().enumerate().peekable();
        let mut removed = self.removed.iter().peekable();
        std::iter::from_fn(move || match (values.peek(), removed.peek()) {
            (Some(&(position, &id)), Some(&&gone)) if id < gone => {
                values.next();
                Some((id, Some(self.records.value(position))))
            }
            (Some(&(position, &id)), None) => {
                values.next();
                Some((id, Some(self.records.value(position))))
            }
            (_, Some(&&gone)) => {
                removed.next();
                Some((gone, None))
            }
            (None, None) => None,
        })
    }

    fn heap_bytes(&self) -> usize {
        self.records.heap_bytes() + self.removed.capacity() * 8
    }
}

/// The changes over a snapshot: levels, oldest first, and how many ids hold a value or a removal.
#[derive(Debug)]
pub(crate) struct Overlay<V> {
    levels: Vec<Arc<Level<V>>>,
    values: usize,
    removals: usize,
}

impl<V> Default for Overlay<V> {
    fn default() -> Self {
        Self {
            levels: Vec::new(),
            values: 0,
            removals: 0,
        }
    }
}

impl<V: Value> Overlay<V> {
    /// What the changes say of `id`: `Some(Some(value))`, `Some(None)` when it was removed, or
    /// `None` when they don't touch it and the snapshot's record stands.
    pub(crate) fn get(&self, id: u64) -> Option<Option<V>> {
        self.levels.iter().rev().find_map(|level| level.get(id))
    }

    /// Whether the changes touch `id`, masking the snapshot's record of it.
    fn masks(&self, id: u64) -> bool {
        self.levels.iter().any(|level| level.holds(id))
    }

    /// The ids holding a value and the ids removed.
    pub(crate) const fn counts(&self) -> (usize, usize) {
        (self.values, self.removals)
    }

    /// The bytes the levels take.
    pub(crate) fn heap_bytes(&self) -> usize {
        self.levels.iter().map(|level| level.heap_bytes()).sum()
    }

    /// These changes and then `changes`, each id once, in rising id order: a new overlay sharing
    /// every level it doesn't merge. Levels merge while the one below is no more than twice the
    /// size of the newest, which keeps their number to about the logarithm of the changes held and
    /// copies each change about that many times.
    pub(crate) fn with(&self, changes: &[(u64, Option<V>)]) -> Self {
        let (mut values, mut removals) = (self.values, self.removals);
        for (id, value) in changes {
            match self.get(*id) {
                Some(Some(_)) => values -= 1,
                Some(None) => removals -= 1,
                None => {}
            }
            match value {
                Some(_) => values += 1,
                None => removals += 1,
            }
        }
        let mut levels = self.levels.clone();
        levels.push(Arc::new(Level::new(changes.iter().copied())));
        while let [.., older, newer] = levels.as_slice()
            && older.len() <= newer.len().saturating_mul(2)
        {
            let merged = Arc::new(merge(older, newer));
            levels.truncate(levels.len() - 2);
            levels.push(merged);
        }
        Self {
            levels,
            values,
            removals,
        }
    }

    /// The overlay of `changes` over `base`, each id once in rising id order, leaving out each
    /// change that leaves `base`'s record of the id as it is: what replaying a log over a new
    /// snapshot holds.
    pub(crate) fn over(base: &Records<V>, changes: impl IntoIterator<Item = (u64, Option<V>)>) -> Self {
        let ids = base.ids().unwrap_or_default();
        let changes: Vec<(u64, Option<V>)> = changes
            .into_iter()
            .filter(|&(id, value)| {
                let held = ids.binary_search(&id).ok().map(|position| base.value(position));
                held != value
            })
            .collect();
        Self::default().with(&changes)
    }
}

/// One level of `older`'s changes and `newer`'s, `newer`'s winning for an id both hold.
fn merge<V: Value>(older: &Level<V>, newer: &Level<V>) -> Level<V> {
    let mut olds = older.changes().peekable();
    let mut news = newer.changes().peekable();
    Level::new(std::iter::from_fn(move || match (olds.peek(), news.peek()) {
        (Some(&(old, _)), Some(&(new, _))) if old < new => olds.next(),
        (Some(&(old, _)), Some(&(new, _))) if old == new => {
            olds.next();
            news.next()
        }
        (_, Some(_)) => news.next(),
        (Some(_), None) => olds.next(),
        (None, None) => None,
    }))
}

/// The changes of `entries`, applied in order, as each id's last change, in rising id order.
pub(crate) fn collapse<V: Value>(entries: &[Entry]) -> Vec<(u64, Option<V>)> {
    let mut last: Vec<(u64, usize)> = entries.iter().enumerate().map(|(at, entry)| (entry.id, at)).collect();
    // By id, then the latest entry first, so `dedup` keeps the last change of each id...
    last.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));
    last.dedup_by_key(|(id, _)| *id);
    last.into_iter()
        .map(|(id, at)| (id, entries[at].value::<V>()))
        .collect()
}

/// A loaded snapshot and the changes over it, searched exactly.
#[derive(Debug, Clone)]
pub(crate) struct SearchSet<V: Value> {
    planned: Arc<Planned<V>>,
    overlay: Arc<Overlay<V>>,
    seq: u64,
}

impl<V: Value> SearchSet<V> {
    /// A snapshot with no changes over it.
    pub(crate) fn new(planned: Planned<V>) -> Self {
        Self {
            planned: Arc::new(planned),
            overlay: Arc::new(Overlay::default()),
            seq: 0,
        }
    }

    /// The same snapshot under `overlay`, the changes to `seq`.
    pub(crate) fn with_changes(&self, overlay: Overlay<V>, seq: u64) -> Self {
        Self {
            planned: Arc::clone(&self.planned),
            overlay: Arc::new(overlay),
            seq,
        }
    }

    /// The snapshot's records.
    pub(crate) fn records(&self) -> &Records<V> {
        self.planned.records()
    }

    /// The changes over the snapshot.
    pub(crate) fn overlay(&self) -> &Overlay<V> {
        &self.overlay
    }

    /// What the set holds for `id`: its value, or `None` when it holds no record of it.
    pub(crate) fn get(&self, id: u64) -> Option<V> {
        self.overlay.get(id).unwrap_or_else(|| {
            let records = self.planned.records();
            records
                .ids()
                .and_then(|ids| ids.binary_search(&id).ok())
                .map(|position| records.value(position))
        })
    }

    /// Every record within the radius of each query, over the snapshot with the changes applied:
    /// what [`search_batch`] gives over one set holding exactly those records, whole or cut as it
    /// says, ties broken by id. [`Options::time_budget`] is a budget for collecting, from now.
    ///
    /// [`search_batch`]: crate::search_batch
    #[cfg(test)]
    pub(crate) fn search(&self, queries: &[V], options: &Options) -> Vec<Found<V>> {
        self.search_until(
            queries,
            options,
            &Stop::after(options.time_budget, std::time::Instant::now),
        )
    }

    /// [`search`](Self::search), collecting until `stop` rather than within the time budget.
    ///
    /// The snapshot is searched, then each level, oldest first, each part's lists merged into one
    /// list a query as it comes, held to what a limit or the size budget keeps. A part isn't
    /// started once `stop` has passed, and `stop` is looked at once more when every part has run: a
    /// deadline that passed while a part ran too short to read the clock still cuts the result by
    /// time, so no candidate collected after the deadline is reported as a whole search.
    pub(crate) fn search_until(&self, queries: &[V], options: &Options, stop: &Stop) -> Vec<Found<V>> {
        let keep = keep(options);
        let levels = &self.overlay.levels;
        let planned = &self.planned;
        let masked = |position: u32| planned.id(position as usize).is_some_and(|id| self.overlay.masks(id));
        let masked: Option<&(dyn Fn(u32) -> bool + Sync)> = if levels.is_empty() { None } else { Some(&masked) };
        let mut merged: Vec<Merged<V>> = search_batch_until(&**planned, queries, options, masked, stop)
            .into_iter()
            .map(|found| Merged::new(found, keep))
            .collect();
        for (at, level) in levels.iter().enumerate() {
            if stop.reached() {
                break;
            }
            let newer = &levels[at + 1..];
            let ids = level.ids();
            let superseded = |position: u32| {
                let id = ids[position as usize];
                newer.iter().any(|level| level.holds(id))
            };
            // A level smaller than this scans faster on one thread than split...
            let options = Options {
                threads: if level.records.len() >= SPLIT_LEVEL {
                    options.threads
                } else {
                    1
                },
                ..options.clone()
            };
            let found = search_batch_until(&level.values, queries, &options, Some(&superseded), stop);
            for (merged, found) in merged.iter_mut().zip(found) {
                merged.add(found, keep);
            }
        }
        let late = stop.reached();
        merged
            .into_iter()
            .map(|mut merged| {
                if late {
                    merged.time = true;
                    merged.settle(keep);
                }
                merged.finish(options)
            })
            .collect()
    }

    /// The last change applied: 0 before the first.
    pub(crate) const fn seq(&self) -> u64 {
        self.seq
    }

    pub(crate) fn len(&self) -> usize {
        self.planned.len()
    }

    pub(crate) fn has_ids(&self) -> bool {
        self.planned.has_ids()
    }

    pub(crate) fn has_tables(&self) -> bool {
        self.planned.has_tables()
    }

    pub(crate) fn memory(&self) -> Memory {
        self.planned.memory()
    }

    /// The neighbour table of the snapshot alone: the changes over it don't count.
    pub(crate) fn neighbours(&self, sample: usize, seed: u64, max_distance: u32, threads: usize) -> NeighbourTable {
        neighbour_table(&*self.planned, sample, seed, max_distance, threads)
    }
}

/// The matches a query keeps, and the cut that names keeping them: the tighter of the caller's
/// `limit` and the size budget, as [`search_batch`](crate::search_batch) keeps.
fn keep(options: &Options) -> Option<(usize, Cut)> {
    match (options.limit, options.max_matches) {
        (Some(limit), Some(max)) if max < limit => Some((max, Cut::Size)),
        (Some(limit), _) => Some((limit, Cut::Limit)),
        (None, Some(max)) => Some((max, Cut::Size)),
        (None, None) => None,
    }
}

/// One query's lists from the parts searched so far, merged into what one search over all their
/// records gives: sorted by distance and id, held to what is kept, every part's cut honoured. A
/// part cut by time stands for a search that didn't reach every record, so only the matches at
/// distance 0 are kept, as a search cut by time keeps; a part cut by a limit or the size budget
/// held only its nearest, so the merged list is cut to the same number.
///
/// Merging part by part keeps the same list as merging every part at once: the nearest `k` of
/// all the parts are the nearest `k` of the nearest `k` so far and the next part's. It holds at
/// most twice the kept matches between parts, not every part's.
struct Merged<V> {
    matches: Vec<Match<V>>,
    /// Whether a part was cut by time, or the deadline passed before the search ended.
    time: bool,
    /// Whether a part was cut by a limit or the size budget.
    bounded: bool,
    /// Whether merging dropped a match past what is kept, and whether one of them was at
    /// distance 0: a cut by time keeps those alone, and was cut short only if one was dropped.
    dropped: bool,
    dropped_zero: bool,
    candidates: u64,
    plan: Option<crate::search::Plan>,
}

impl<V: Value> Merged<V> {
    /// The snapshot's part.
    fn new(found: Found<V>, keep: Option<(usize, Cut)>) -> Self {
        let mut merged = Self {
            matches: Vec::new(),
            time: false,
            bounded: false,
            dropped: false,
            dropped_zero: false,
            candidates: 0,
            plan: found.plan,
        };
        merged.add(found, keep);
        merged
    }

    /// Merge the next part's list in.
    fn add(&mut self, found: Found<V>, keep: Option<(usize, Cut)>) {
        self.candidates = self.candidates.saturating_add(found.candidates);
        match found.cut_by {
            Some(Cut::Time) => self.time = true,
            Some(_) => self.bounded = true,
            None => {}
        }
        self.matches.extend(found.matches);
        self.settle(keep);
    }

    /// Keep the matches a cut by time keeps, if there was one, sorted, and no more than are kept.
    fn settle(&mut self, keep: Option<(usize, Cut)>) {
        if self.time {
            self.matches.retain(|found| found.distance == 0);
        }
        // By id, which no two parts share; a subset has none, and one part, ordered by position...
        self.matches
            .sort_unstable_by_key(|found| (found.distance, found.id, found.position));
        if let Some((keep, _)) = keep
            && self.matches.len() > keep
        {
            self.dropped = true;
            self.dropped_zero |= self.matches[keep].distance == 0;
            self.matches.truncate(keep);
        }
    }

    fn finish(self, options: &Options) -> Found<V> {
        let mut cut_by = self.time.then_some(Cut::Time);
        let dropped = if self.time { self.dropped_zero } else { self.dropped };
        if let Some((_, cut)) = keep(options)
            && (dropped || self.bounded)
        {
            cut_by.get_or_insert(cut);
        }
        Found {
            matches: self.matches,
            cut_by,
            candidates: self.candidates,
            plan: self.plan,
        }
    }
}

/// A loaded set at either width.
#[derive(Debug, Clone)]
pub(crate) enum Sets {
    W64(SearchSet<u64>),
    W256(SearchSet<[u64; 4]>),
}

impl Sets {
    pub(crate) const fn width(&self) -> u32 {
        match self {
            Self::W64(_) => 64,
            Self::W256(_) => 256,
        }
    }

    pub(crate) fn len(&self) -> usize {
        match self {
            Self::W64(set) => set.len(),
            Self::W256(set) => set.len(),
        }
    }

    pub(crate) fn has_ids(&self) -> bool {
        match self {
            Self::W64(set) => set.has_ids(),
            Self::W256(set) => set.has_ids(),
        }
    }

    pub(crate) fn has_tables(&self) -> bool {
        match self {
            Self::W64(set) => set.has_tables(),
            Self::W256(set) => set.has_tables(),
        }
    }

    pub(crate) fn memory(&self) -> Memory {
        match self {
            Self::W64(set) => set.memory(),
            Self::W256(set) => set.memory(),
        }
    }

    pub(crate) const fn seq(&self) -> u64 {
        match self {
            Self::W64(set) => set.seq(),
            Self::W256(set) => set.seq(),
        }
    }

    /// The ids holding a changed value, the ids removed, and the bytes the changes take.
    pub(crate) fn changes(&self) -> (usize, usize, usize) {
        match self {
            Self::W64(set) => {
                let (values, removals) = set.overlay().counts();
                (values, removals, set.overlay().heap_bytes())
            }
            Self::W256(set) => {
                let (values, removals) = set.overlay().counts();
                (values, removals, set.overlay().heap_bytes())
            }
        }
    }

    pub(crate) fn neighbours(&self, sample: usize, seed: u64, max_distance: u32, threads: usize) -> NeighbourTable {
        match self {
            Self::W64(set) => set.neighbours(sample, seed, max_distance, threads),
            Self::W256(set) => set.neighbours(sample, seed, max_distance, threads),
        }
    }
}

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

    use super::*;

    fn set() -> SearchSet<u64> {
        let records = Records::from_records([(1, 0b0u64), (2, 0b1), (3, 0b11), (6, 0b111)]).expect("ids rise");
        let set = SearchSet::new(Planned::new(Arc::new(records), usize::MAX, 1));
        let overlay = set.overlay().with(&[(2, None), (4, Some(0)), (5, Some(0b1))]);
        let set = set.with_changes(overlay, 3);
        // A newer level over the first: 5 moved, 6 removed...
        let overlay = set.overlay().with(&[(5, Some(0b1111)), (6, None)]);
        set.with_changes(overlay, 5)
    }

    fn ids(found: &Found<u64>) -> Vec<(Option<u64>, u32)> {
        found.matches.iter().map(|found| (found.id, found.distance)).collect()
    }

    #[test]
    fn a_search_reads_the_snapshot_through_every_level() {
        let found = &set().search(&[0], &Options::new(64))[0];
        assert_eq!(ids(found), [(Some(1), 0), (Some(4), 0), (Some(3), 2), (Some(5), 4)]);
        assert!(found.is_complete());
        // A limit keeps the nearest, ties by id, whichever part they come from...
        let found = &set().search(&[0], &Options::new(64).limit(3))[0];
        assert_eq!(ids(found), [(Some(1), 0), (Some(4), 0), (Some(3), 2)]);
        assert_eq!(found.cut_by, Some(Cut::Limit));
        let found = &set().search(&[0], &Options::new(64).limit(2).max_matches(1))[0];
        assert_eq!((ids(found), found.cut_by), (vec![(Some(1), 0)], Some(Cut::Size)));
        let found = &set().search(&[0], &Options::new(64).exclude_zero(true))[0];
        assert_eq!(ids(found), [(Some(3), 2), (Some(5), 4)]);
    }

    #[test]
    fn a_time_cut_keeps_only_matches_at_distance_zero() {
        // Enough records that the search looks at its clock...
        let records = Records::from_records((0..50_000u64).map(|id| (id, id % 3))).expect("ids rise");
        let set = SearchSet::new(Planned::scan_only(Arc::new(records)));
        let set = set.with_changes(set.overlay().with(&[(7, Some(5)), (60_000, Some(0))]), 2);
        let found = &set.search(&[0], &Options::new(64).time_budget(Duration::ZERO))[0];
        assert_eq!(found.cut_by, Some(Cut::Time));
        assert!(found.matches.iter().all(|found| found.distance == 0));
        let whole = &set.search(&[0], &Options::new(64))[0];
        assert!(whole.is_complete());
        assert_eq!(whole.matches.len(), 50_001);
    }

    /// What a search of `set` for 0 within 2 gave at each budget from 0 ms on, on the ticking clock:
    /// its candidates, its cut, and the distances it returned.
    fn by_budget(set: &SearchSet<u64>) -> Vec<(u64, Option<Cut>, Vec<u32>)> {
        (0..30)
            .map(|budget| {
                crate::search::ticking::reset();
                let options = Options::new(2).time_budget(Duration::from_millis(budget));
                let stop = Stop::after(options.time_budget, crate::search::ticking::now);
                let found = set.search_until(&[0], &options, &stop).remove(0);
                let distances = found.matches.iter().map(|found| found.distance).collect();
                (found.candidates, found.cut_by, distances)
            })
            .collect()
    }

    #[test]
    fn a_deadline_passed_in_a_small_level_or_before_the_merge_cuts_by_time() {
        // A snapshot and two levels, each too small to read the clock while it is scanned, each
        // with matches at distance 0 and beyond...
        let records = Records::from_records((0..600u64).map(|id| (id * 2, id % 3))).expect("ids rise");
        let set = SearchSet::new(Planned::scan_only(Arc::new(records)));
        let older: Vec<(u64, Option<u64>)> = (0..100u64).map(|id| (id * 2 + 1, Some(id % 3))).collect();
        let set = set.with_changes(set.overlay().with(&older), 100);
        let newer: Vec<(u64, Option<u64>)> = (0..10u64).map(|id| (5_000 + id, Some(id % 3))).collect();
        let set = set.with_changes(set.overlay().with(&newer), 110);
        assert_eq!(set.overlay().levels.len(), 2);
        let runs = by_budget(&set);
        let (whole, cut_by, _) = runs.last().expect("runs").clone();
        assert_eq!((whole, cut_by), (710, None), "a budget long enough finishes");
        let cut = |candidates: u64| {
            runs.iter()
                .find(|(seen, cut_by, _)| *seen == candidates && *cut_by == Some(Cut::Time))
                .unwrap_or_else(|| panic!("no budget was cut by time after {candidates} candidates: {runs:?}"))
        };
        // The deadline passed while the older level was scanned: the newer one isn't started...
        let (_, _, distances) = cut(700);
        assert!(!distances.is_empty() && distances.iter().all(|&distance| distance == 0));
        // ...and while the newer one was, or after: every part ran, but past the deadline.
        let (_, _, distances) = cut(710);
        assert!(!distances.is_empty() && distances.iter().all(|&distance| distance == 0));
        assert_eq!(distances.len(), 200 + 34 + 4);
    }

    #[test]
    fn parts_merged_one_by_one_keep_what_one_merge_keeps() {
        let records = Records::from_records((0..3_000u64).map(|id| (id * 3, id % 5))).expect("ids rise");
        let mut set = SearchSet::new(Planned::scan_only(Arc::new(records)));
        let mut truth: std::collections::BTreeMap<u64, u64> = (0..3_000u64).map(|id| (id * 3, id % 5)).collect();
        for (level, size) in [(0u64, 800u64), (1, 300), (2, 90), (3, 20)] {
            let changes: Vec<(u64, Option<u64>)> = (0..size)
                .map(|at| {
                    let id = at * 7 + level;
                    (id, (at % 4 != 0).then_some((at + level) % 6))
                })
                .collect();
            for &(id, value) in &changes {
                match value {
                    Some(value) => truth.insert(id, value),
                    None => truth.remove(&id),
                };
            }
            set = set.with_changes(set.overlay().with(&changes), level + 1);
        }
        assert!(set.overlay().levels.len() > 1);
        let mut all: Vec<(u32, u64)> = truth.iter().map(|(&id, &value)| (value.count_ones(), id)).collect();
        all.retain(|&(distance, _)| distance <= 2);
        all.sort_unstable();
        for (limit, max) in [
            (None, None),
            (Some(1), None),
            (Some(37), None),
            (Some(500), Some(40)),
            (None, Some(5)),
        ] {
            let mut options = Options::new(2);
            options.limit = limit;
            options.max_matches = max;
            let found = set.search(&[0], &options).remove(0);
            let keep = limit.into_iter().chain(max).min().unwrap_or(usize::MAX);
            let expected: Vec<(u32, u64)> = all.iter().copied().take(keep).collect();
            let got: Vec<(u32, u64)> = found
                .matches
                .iter()
                .map(|found| (found.distance, found.id.expect("ids")))
                .collect();
            assert_eq!(got, expected, "{limit:?} {max:?}");
            let cut = match (limit, max) {
                (Some(limit), Some(max)) if max < limit => Some(Cut::Size),
                (Some(_), _) => Some(Cut::Limit),
                (None, Some(_)) => Some(Cut::Size),
                (None, None) => None,
            };
            assert_eq!(found.cut_by, cut.filter(|_| all.len() > keep), "{limit:?} {max:?}");
        }
    }

    #[test]
    fn the_overlay_counts_what_it_holds() {
        let set = set();
        assert_eq!(set.overlay().counts(), (2, 2));
        assert_eq!(
            (set.get(2), set.get(5), set.get(6), set.get(3)),
            (None, Some(0b1111), None, Some(0b11))
        );
    }
}