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
//! A request answered: the search or the stats, as the contract's result object.

use std::sync::Arc;
use std::time::Instant;

use serde::Serialize;

use super::FORMAT;
use super::catalog::{Catalog, Generation, Slot, Writer};
use super::error::{ErrorType, ServiceError};
use super::limits::{Lane, Limits};
use super::log::ChangeName;
use super::memory::{available_memory, process_rss};
use super::request::{self, Values};
use super::set::{SearchSet, Sets};
use super::time::rfc3339;
use crate::search::{Cut, Found, Options, Stop};
use crate::value::Value;

/// The queries of a bulk task searched in one call. A longer task is searched in turns of this
/// many, so the hits it holds while it runs stay within `256 × threads ×`
/// [`max_hits`](crate::max_hits)`(kept)` whatever its length, at the cost of reading the records
/// once a turn rather than once.
pub const BULK_TURN: usize = 256;

/// The most bytes a result's fixed part takes: `format`, the names, the snapshot and `seq`.
const HEADER_BYTES: usize = 512;
/// The most bytes a query's entry takes besides its matches.
const QUERY_BYTES: usize = 96;

/// The most bytes a result of `queries` queries with `matches` matches each takes, at `width`
/// bits, with ids or without: what a result is sized by before the search.
pub(crate) const fn result_bytes(width: u32, ids: bool, queries: usize, matches: usize) -> usize {
    HEADER_BYTES
        .saturating_add(queries.saturating_mul(QUERY_BYTES))
        .saturating_add(queries.saturating_mul(matches).saturating_mul(match_bytes(width, ids)))
}

/// The most bytes one match takes in a result: `{"id":<20 digits>,"value":"<hex>","distance":256},`.
const fn match_bytes(width: u32, ids: bool) -> usize {
    (width as usize / 4) + 30 + if ids { 26 } else { 0 }
}

/// What a request cost, for a heartbeat.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct Counts {
    /// Query values searched.
    pub queries: u64,
    /// Candidates read: records compared, or table entries read.
    pub candidates: u64,
    /// Queries cut by the caller's `limit`.
    pub cut_limit: u64,
    /// Queries cut by the time budget.
    pub cut_time: u64,
    /// Queries cut by the size budget.
    pub cut_size: u64,
    /// Matches returned, over every query.
    pub matches: u64,
}

/// A search answered: its result object as JSON, and what it cost.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Answer {
    /// The result object, the line `query` writes and the `result` field of a stream's result.
    pub json: String,
    /// What it cost.
    pub counts: Counts,
}

/// The service: a catalog searched within limits.
#[derive(Debug)]
pub struct Service {
    catalog: Arc<Catalog>,
    limits: Limits,
    threads: usize,
    /// Where a search reads the time: [`Instant::now`], or in the crate's tests a clock they drive.
    now: fn() -> Instant,
}

#[derive(Serialize)]
struct SearchObject<'a> {
    format: u32,
    index: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    subset: Option<&'a str>,
    snapshot: &'a str,
    seq: u64,
    exact: bool,
    queries: Vec<QueryObject>,
}

#[derive(Serialize)]
struct QueryObject {
    matches: Vec<MatchObject>,
    complete: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    cut_by: Option<&'static str>,
    plan: &'static str,
}

#[derive(Serialize)]
struct MatchObject {
    #[serde(skip_serializing_if = "Option::is_none")]
    id: Option<u64>,
    value: String,
    distance: u32,
}

impl Service {
    /// A service over `catalog`, within `limits`, a bulk task searching on `threads` threads.
    #[must_use]
    pub const fn new(catalog: Arc<Catalog>, limits: Limits, threads: usize) -> Self {
        Self {
            catalog,
            limits,
            threads,
            now: Instant::now,
        }
    }

    /// [`new`](Self::new), its searches reading the time from `now`: a clock a test drives.
    #[cfg(test)]
    pub(crate) const fn with_clock(
        catalog: Arc<Catalog>,
        limits: Limits,
        threads: usize,
        now: fn() -> Instant,
    ) -> Self {
        Self {
            catalog,
            limits,
            threads,
            now,
        }
    }

    /// The catalog it searches.
    #[must_use]
    pub const fn catalog(&self) -> &Arc<Catalog> {
        &self.catalog
    }

    /// Its limits.
    #[must_use]
    pub const fn limits(&self) -> &Limits {
        &self.limits
    }

    /// The threads a bulk task's search runs on.
    #[must_use]
    pub const fn threads(&self) -> usize {
        self.threads
    }

    /// Answer a search's `options`, JSON text, on `lane`.
    ///
    /// Every check comes before the search: the size of `options`, its keys and types, the
    /// number of values for the lane, the radius bound for the width, each value's hex, then
    /// whether the index and subset are served and loaded and of the request's width. The matches
    /// each query may keep are then fixed from `max_matches` and the result budget, and the search
    /// runs, a quick request on one thread and a bulk task across the service's threads, in turns
    /// of 256 queries. The lane's time budget is a search budget: the search stops collecting
    /// candidates once it has passed, and the reply follows as soon as what was collected is
    /// merged and written, cut by time. It runs on the snapshot served when it starts, whatever
    /// replaces it meanwhile, and the result names that snapshot.
    ///
    /// # Errors
    ///
    /// A [`ServiceError`] with the contract's code: see [`ErrorType`].
    pub fn search(&self, options: &str, lane: Lane) -> Result<Answer, ServiceError> {
        self.search_within(options, lane, self.limits.max_result_bytes)
    }

    /// [`search`](Self::search), with the result object held to `max_bytes` as well as to
    /// [`Limits::max_result_bytes`]: for a worker whose result entry also carries what the task
    /// echoes, so the result is sized to the room actually left, before the search.
    ///
    /// # Errors
    ///
    /// As [`search`](Self::search), and [`ErrorType::TooManyValues`], before the search, when the
    /// room can't hold even an empty entry for each of the request's values.
    pub fn search_within(&self, options: &str, lane: Lane, max_bytes: usize) -> Result<Answer, ServiceError> {
        let budget = self.limits.max_result_bytes.min(max_bytes);
        let request = request::search(options, &self.limits, lane)?;
        let slot = self.catalog.find(&request.index, request.subset.as_deref())?;
        let generation = slot.ready()?;
        let width = generation.set.width();
        if width != request.width {
            return Err(ServiceError::new(
                ErrorType::WidthMismatch,
                format!(
                    "`{}` holds {width}-bit values; the request gives `width` {}",
                    slot.label(),
                    request.width
                ),
            ));
        }
        let queries = request.values.len();
        let fixed = result_bytes(width, false, queries, 0);
        if fixed > budget {
            return Err(ServiceError::new(
                ErrorType::TooManyValues,
                format!(
                    "a result of {queries} queries takes at least {fixed} bytes; {budget} are left for it beside \
                     what the task echoes"
                ),
            ));
        }
        let room = budget - fixed;
        let by_size = room
            / queries
                .max(1)
                .saturating_mul(match_bytes(width, generation.set.has_ids()));
        let options = Options {
            radius: request.radius,
            limit: request.limit,
            max_matches: Some(self.limits.max_matches.min(by_size)),
            time_budget: Some(self.limits.query_time(lane)),
            threads: match lane {
                Lane::Fast => 1,
                Lane::Bulk => self.threads,
            },
            exclude_zero: request.exclude_zero,
        };
        let mut counts = Counts {
            queries: queries as u64,
            ..Counts::default()
        };
        let queries = match (&generation.set, &request.values) {
            (Sets::W64(set), Values::W64(values)) => run(set, values, &options, self.now, &mut counts),
            (Sets::W256(set), Values::W256(values)) => run(set, values, &options, self.now, &mut counts),
            _ => return Err(ServiceError::new(ErrorType::Internal, "the widths disagree")),
        };
        let object = SearchObject {
            format: FORMAT,
            index: &slot.index,
            subset: slot.subset.as_deref(),
            snapshot: &generation.snapshot,
            seq: generation.set.seq(),
            exact: true,
            queries,
        };
        let json = serde_json::to_string(&object)
            .map_err(|error| ServiceError::new(ErrorType::Internal, error.to_string()))?;
        Ok(Answer { json, counts })
    }

    /// Whether it takes change tasks: whether its catalog writes a change log, as `serve
    /// --state-dir` does.
    #[must_use]
    pub fn takes_changes(&self) -> bool {
        let config = self.catalog.config();
        config.state_dir.is_some() && config.write_changes
    }

    /// Apply a change task, `append`, `replace` or `remove`, of `task_id` with its `options`, and
    /// return its result object: `format`, `index`, `seq` (the log's position after the task's
    /// last entry), and the records `added`, `changed`, `removed` and `unchanged`.
    ///
    /// The checks come first: the `task_id`, 1 to 64 of `A-Z`, `a-z`, `0-9`, `_` and `-`, as the
    /// stream contract's are; that the service takes changes, the size of `options`, its keys and
    /// types, the number of records against [`Limits::max_change_records`] or
    /// [`Limits::max_remove_ids`], each record, then whether the index is served, loaded and of
    /// the task's width. Then the task is written to the index's change log and made durable,
    /// then made searchable, and only then answered. A `task_id` the log holds is answered as it
    /// was the first time, and changes nothing.
    ///
    /// # Errors
    ///
    /// [`ErrorType::InvalidTask`] for another `task_name`, a `task_id` the log can't hold, or a
    /// service that keeps no change log;
    /// [`ErrorType::Conflict`] for an `append` that meets an id held with another value, which
    /// applies nothing; [`ErrorType::LogFull`] when the log would pass its bound; and the codes a
    /// search's options and index give.
    pub fn change(&self, task_id: &str, task_name: &str, options: &str) -> Result<String, ServiceError> {
        let name = match task_name {
            "append" => ChangeName::Append,
            "replace" => ChangeName::Replace,
            "remove" => ChangeName::Remove,
            _ => {
                return Err(ServiceError::new(
                    ErrorType::InvalidTask,
                    "a change task is `append`, `replace` or `remove`",
                ));
            }
        };
        if !super::log::is_valid_task_id(task_id) {
            return Err(super::catalog::invalid_task_id());
        }
        if !self.takes_changes() {
            return Err(ServiceError::new(
                ErrorType::InvalidTask,
                "this service keeps no change log: changes are taken by `serve --state-dir`",
            ));
        }
        let request = request::change(options, &self.limits, name)?;
        self.catalog.change(task_id, request, &self.limits)
    }

    /// Answer a `stats` request's `options`: the state of the index or subset, the snapshot
    /// served, a load in progress, the last failed load, the neighbour table, memory, and the
    /// limits.
    ///
    /// # Errors
    ///
    /// [`ErrorType::InvalidOptions`], [`ErrorType::UnknownIndex`] or
    /// [`ErrorType::UnknownSubset`]. An index that isn't ready is reported, not refused.
    pub fn stats(&self, options: &str) -> Result<String, ServiceError> {
        let request = request::stats(options, &self.limits)?;
        let slot = self.catalog.find(&request.index, request.subset.as_deref())?;
        serde_json::to_string(&self.stats_object(slot))
            .map_err(|error| ServiceError::new(ErrorType::Internal, error.to_string()))
    }

    /// The stats of every index and subset, one JSON object each, indexes first.
    #[must_use]
    pub fn all_stats(&self) -> Vec<String> {
        self.catalog
            .slots()
            .iter()
            .map(|slot| serde_json::to_string(&self.stats_object(slot)).unwrap_or_default())
            .collect()
    }

    fn stats_object<'a>(&'a self, slot: &'a Slot) -> StatsObject<'a> {
        let view = slot.view();
        let state = match (&view.current, &view.loading, &view.log_refused) {
            (_, _, Some(_)) => "refused",
            (Some(_), _, _) => "ready",
            (None, Some(_), _) => "loading",
            (None, None, None) => "empty",
        };
        let (rss, peak) = process_rss().unzip();
        StatsObject {
            format: FORMAT,
            index: &slot.index,
            subset: slot.subset.as_deref(),
            state,
            refused: view.log_refused.as_ref().map(|refused| refused.message.clone()),
            refused_code: view.log_refused.as_ref().map(|refused| refused.code),
            seq: view.current.as_ref().map_or(0, |current| current.set.seq()),
            snapshot: view.current.as_deref().map(snapshot_object),
            loading: view.loading.as_ref().map(|loading| LoadingObject {
                snapshot: loading.snapshot.clone(),
                fraction: loading.fraction(),
                bytes_read: loading.read.load(std::sync::atomic::Ordering::Relaxed),
                bytes: loading.total,
            }),
            last_failure: view.failed.as_ref().map(|failed| FailureObject {
                snapshot: failed.snapshot.clone(),
                code: failed.code,
                reason: failed.reason.clone(),
                at: rfc3339(failed.at),
            }),
            changes: view.log.map(|log| {
                let (values, removals, bytes) =
                    view.current.as_ref().map_or((0, 0, 0), |current| current.set.changes());
                ChangesObject {
                    writer: view.writer.map(|writer| match writer {
                        Writer::Ok => "ok",
                        Writer::Broken(_) => "broken",
                    }),
                    writer_reason: match view.writer {
                        Some(Writer::Broken(code)) => Some(code),
                        _ => None,
                    },
                    remembered: view.remembered,
                    log: LogObject {
                        tasks: log.tasks,
                        entries: log.entries,
                        bytes: log.bytes,
                        first_seq: log.first_seq,
                        last_seq: log.last_seq,
                        base_seq: log.base_seq,
                    },
                    held: HeldObject {
                        values,
                        removals,
                        bytes: bytes as u64,
                    },
                }
            }),
            neighbours: view.current.as_deref().map(|current| self.neighbours_object(current)),
            memory: MemoryObject {
                records: view
                    .current
                    .as_ref()
                    .map_or(0, |current| current.set.memory().records as u64),
                tables: view
                    .current
                    .as_ref()
                    .map_or(0, |current| current.set.memory().index as u64),
                process_rss: rss,
                process_peak_rss: peak,
                available: available_memory(),
            },
            limits: &self.limits,
            threads: self.threads,
        }
    }

    fn neighbours_object(&self, generation: &Generation) -> NeighboursObject {
        let config = self.catalog.config();
        match generation.neighbours.get() {
            Some(neighbours) => NeighboursObject {
                state: "measured",
                sample: Some(neighbours.table.sample),
                seed: Some(neighbours.table.seed),
                max_distance: Some(neighbours.max_distance),
                counts: Some(neighbours.table.counts.clone()),
                ms: Some(neighbours.ms),
            },
            None => NeighboursObject {
                state: if config.neighbours { "measuring" } else { "off" },
                sample: None,
                seed: None,
                max_distance: None,
                counts: None,
                ms: None,
            },
        }
    }
}

fn snapshot_object(generation: &Generation) -> SnapshotObject {
    SnapshotObject {
        name: generation.snapshot.clone(),
        width: generation.set.width(),
        ids: generation.set.has_ids(),
        records: generation.set.len(),
        loaded_at: rfc3339(generation.loaded_at),
        covers_seq: generation.covers_seq,
        tables: generation.set.has_tables(),
        table_bytes: generation.table_bytes,
        table_budget: generation.table_budget,
        load_ms: generation.load_ms,
        build_ms: generation.build_ms,
        replayed: generation.replayed,
        replay_ms: generation.replay_ms,
    }
}

/// Search `values` on `set` in turns, collecting within one deadline read from `now`, and shape
/// each query's entry.
fn run<V: Value>(
    set: &SearchSet<V>,
    values: &[V],
    options: &Options,
    now: fn() -> Instant,
    counts: &mut Counts,
) -> Vec<QueryObject> {
    let stop = Stop::after(options.time_budget, now);
    let mut entries = Vec::with_capacity(values.len());
    for turn in values.chunks(BULK_TURN) {
        for found in set.search_until(turn, options, &stop) {
            entries.push(entry(found, counts));
        }
    }
    entries
}

fn entry<V: Value>(found: Found<V>, counts: &mut Counts) -> QueryObject {
    counts.candidates = counts.candidates.saturating_add(found.candidates);
    match found.cut_by {
        Some(Cut::Limit) => counts.cut_limit += 1,
        Some(Cut::Time) => counts.cut_time += 1,
        Some(Cut::Size) => counts.cut_size += 1,
        _ => {}
    }
    counts.matches = counts.matches.saturating_add(found.matches.len() as u64);
    QueryObject {
        complete: found.is_complete(),
        cut_by: found.cut_by.map(Cut::name),
        plan: found.plan.map_or("scan", |plan| plan.strategy.name()),
        matches: found
            .matches
            .into_iter()
            .map(|found| MatchObject {
                id: found.id,
                value: found.value.to_hex(),
                distance: found.distance,
            })
            .collect(),
    }
}

#[derive(Serialize)]
struct StatsObject<'a> {
    format: u32,
    index: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    subset: Option<&'a str>,
    state: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    refused: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    refused_code: Option<&'static str>,
    seq: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    snapshot: Option<SnapshotObject>,
    #[serde(skip_serializing_if = "Option::is_none")]
    loading: Option<LoadingObject>,
    #[serde(skip_serializing_if = "Option::is_none")]
    last_failure: Option<FailureObject>,
    #[serde(skip_serializing_if = "Option::is_none")]
    changes: Option<ChangesObject>,
    #[serde(skip_serializing_if = "Option::is_none")]
    neighbours: Option<NeighboursObject>,
    memory: MemoryObject,
    limits: &'a Limits,
    threads: usize,
}

#[derive(Serialize)]
struct SnapshotObject {
    name: String,
    width: u32,
    ids: bool,
    records: usize,
    loaded_at: String,
    covers_seq: Option<u64>,
    tables: bool,
    table_bytes: u64,
    table_budget: Option<u64>,
    load_ms: u64,
    build_ms: u64,
    replayed: usize,
    replay_ms: u64,
}

#[derive(Serialize)]
struct ChangesObject {
    log: LogObject,
    held: HeldObject,
    /// `ok`, or `broken` once this process stopped writing the log, when it writes it.
    #[serde(skip_serializing_if = "Option::is_none")]
    writer: Option<&'static str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    writer_reason: Option<&'static str>,
    /// The change tasks whose answers are remembered for a repeat.
    remembered: usize,
}

#[derive(Serialize)]
struct LogObject {
    tasks: usize,
    entries: usize,
    bytes: u64,
    first_seq: Option<u64>,
    last_seq: u64,
    base_seq: u64,
}

#[derive(Serialize)]
struct HeldObject {
    values: usize,
    removals: usize,
    bytes: u64,
}

#[derive(Serialize)]
struct LoadingObject {
    snapshot: String,
    fraction: Option<f64>,
    bytes_read: u64,
    bytes: u64,
}

#[derive(Serialize)]
struct FailureObject {
    snapshot: String,
    code: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    reason: Option<String>,
    at: String,
}

#[derive(Serialize)]
struct NeighboursObject {
    state: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    sample: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    seed: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    max_distance: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    counts: Option<Vec<u64>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    ms: Option<u64>,
}

#[derive(Serialize)]
struct MemoryObject {
    records: u64,
    tables: u64,
    process_rss: Option<u64>,
    process_peak_rss: Option<u64>,
    available: Option<u64>,
}

#[cfg(test)]
mod tests {
    use serde_json::Value as Json;

    use super::*;
    use crate::Records;
    use crate::search::ticking;
    use crate::service::{LoadConfig, SetSpec};
    use crate::snapshot;

    #[test]
    fn a_search_whose_deadline_passed_before_its_result_was_built_is_cut_by_time() {
        let dir = std::env::temp_dir().join(format!("legit-hamming-answer-clock-{}", std::process::id()));
        let records = Records::from_records((0..900u64).map(|id| (id, id % 4))).expect("ids rise");
        snapshot::write(&dir.join("first"), &records, 1_000).expect("written");
        std::fs::write(dir.join("CURRENT"), "first\n").expect("written");
        let config = LoadConfig {
            neighbours: false,
            table_memory: crate::service::TableMemory::Bytes(0),
            ..LoadConfig::default()
        };
        let catalog = Arc::new(Catalog::new(vec![SetSpec::index("images", &dir)], config).expect("a catalog"));
        catalog.refresh(&mut |_| {});
        let options = r#"{"format":1,"index":"images","width":64,"radius":1,"values":["0000000000000000"]}"#;
        let mut runs = Vec::new();
        for budget in 1..30 {
            let mut limits = Limits::new();
            limits.query_time_fast_ms = budget;
            let service = Service::with_clock(Arc::clone(&catalog), limits, 1, ticking::now);
            ticking::reset();
            let answer = service.search(options, Lane::Fast).expect("an answer");
            let json: Json = serde_json::from_str(&answer.json).expect("JSON");
            runs.push((answer.counts, json["queries"][0].clone()));
        }
        std::fs::remove_dir_all(&dir).ok();
        let (counts, query) = runs.last().expect("runs");
        assert_eq!((counts.candidates, counts.cut_time), (900, 0));
        assert_eq!(query["matches"].as_array().map(Vec::len), Some(675));
        // Every record compared, but the clock read once the comparing ended was past the
        // deadline: the reply keeps only what a cut by time keeps...
        let (_, query) = runs
            .iter()
            .find(|(counts, _)| counts.candidates == 900 && counts.cut_time == 1)
            .expect("a budget that ended between the last comparison and the result");
        assert_eq!(query["cut_by"], "time");
        let matches = query["matches"].as_array().expect("matches");
        assert_eq!(matches.len(), 225);
        assert!(matches.iter().all(|found| found["distance"] == 0));
    }
}