legit_hamming/search.rs
1//! The trait every variant implements, and the search that runs it.
2
3use std::fmt;
4use std::ops::Range;
5use std::thread;
6use std::time::{Duration, Instant};
7
8use crate::kernel::Hit;
9use crate::value::Value;
10
11/// A searchable set of records: one of the crate's variants, or one of your own.
12///
13/// A variant does one thing, [`collect`](Self::collect): for each query, push the position and
14/// distance of every record within the radius. [`search`] and [`search_batch`] build on it: they
15/// split the work across threads, apply the caller's limits, and resolve positions into ids and
16/// values. Every variant of the crate collects exactly the positions [`Reference`] collects; the
17/// test suite checks it.
18///
19/// [`Reference`]: crate::Reference
20pub trait Search<V: Value>: Send + Sync + fmt::Debug {
21 /// A short name for reports, such as `scan/avx512` or `multi-index/4x16`.
22 fn variant(&self) -> String;
23
24 /// How many records the set holds.
25 fn len(&self) -> usize;
26
27 /// Whether the set holds no records.
28 fn is_empty(&self) -> bool {
29 self.len() == 0
30 }
31
32 /// Whether the records carry ids.
33 fn has_ids(&self) -> bool;
34
35 /// The id of the record at `position`, if the records carry ids.
36 ///
37 /// # Panics
38 ///
39 /// May panic if `position` is past the end.
40 fn id(&self, position: usize) -> Option<u64>;
41
42 /// The value of the record at `position`.
43 ///
44 /// # Panics
45 ///
46 /// May panic if `position` is past the end.
47 fn value(&self, position: usize) -> V;
48
49 /// The memory the set and its index take.
50 fn memory(&self) -> Memory;
51
52 /// Push to `out[i]` every record within `radius` of `queries[i]`, for this share of the work.
53 ///
54 /// The shares `0..share.count` of one call together push every record within the radius
55 /// exactly once: no record is missed, and none is pushed twice, whether by two shares or by
56 /// one. After each run of pushes onto a list, call [`HitList::trim`], which keeps the list
57 /// within the caller's bound. Each [`HitList`] also counts the candidates its query cost: records whose distance was
58 /// computed, or for an index, the entries it read. Returns whether `stop` cut the work short,
59 /// in which case the hits are those found before it did.
60 ///
61 /// A list may carry the [`Plan`] that [`plan`](Self::plan) chose for its query
62 /// ([`HitList::plan`]); a variant that plans follows it, and plans the query itself when the
63 /// list carries none.
64 fn collect(&self, queries: &[V], radius: u32, share: Share, stop: &Stop, out: &mut [HitList<'_>]) -> bool;
65
66 /// Decide how to answer each of `queries` within `radius`, and on how many of the `threads`
67 /// given, at least 1. [`search_batch`] calls it once a call, before any `collect`, hands each
68 /// query's plan to `collect` on its [`HitList`], and reports it in [`Found::plan`].
69 ///
70 /// Planning is part of the search: a variant whose planning takes work watches `stop`, the
71 /// deadline of the search it plans for, and once it has passed leaves the queries it hasn't
72 /// planned without an estimate, so the search stops cut by time.
73 ///
74 /// The default plans nothing and uses every thread given: a variant with one way to answer a
75 /// query has nothing to choose. [`Planned`](crate::Planned) chooses between a scan and its
76 /// tables per query, and the threads from the work it expects.
77 fn plan(&self, queries: &[V], radius: u32, threads: usize, stop: &Stop) -> Planning {
78 let _ = (queries, radius, stop);
79 Planning::unplanned(threads)
80 }
81}
82
83/// How a query is answered.
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
85#[non_exhaustive]
86pub enum Strategy {
87 /// Every record compared with the query.
88 Scan,
89 /// The multi-index tables probed with every key near the query's chunks, and each record
90 /// they hold under those keys compared with the query.
91 MultiIndex,
92}
93
94impl Strategy {
95 /// The strategy's name in a report: `scan` or `multi-index`.
96 #[must_use]
97 pub const fn name(self) -> &'static str {
98 match self {
99 Self::Scan => "scan",
100 Self::MultiIndex => "multi-index",
101 }
102 }
103}
104
105impl fmt::Display for Strategy {
106 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107 f.write_str(self.name())
108 }
109}
110
111/// What a query was expected to cost each way, in records scanned: the numbers a plan was chosen
112/// by.
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
114#[non_exhaustive]
115pub struct Estimate {
116 /// The keys a probe of the tables looks up.
117 pub keys: u64,
118 /// The table entries those keys hold, which a probe reads and compares with the query: the
119 /// sum of the tables' own bucket sizes, so exact when [`counted`](Self::counted) is true.
120 pub candidates: u64,
121 /// Whether [`candidates`](Self::candidates) is the full count. Counting stops as soon as the
122 /// probe is sure to cost more than a scan, and doesn't start when the keys alone outnumber
123 /// the records; the count is then a lower bound.
124 pub counted: bool,
125 /// The probe's cost: its keys, plus its candidates times
126 /// [`Planned::CANDIDATE_COST`](crate::Planned::CANDIDATE_COST).
127 pub probe_cost: u64,
128 /// A scan's cost: the records.
129 pub scan_cost: u64,
130}
131
132/// The plan a query ran with: its strategy, and the estimate that chose it.
133#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
134#[non_exhaustive]
135pub struct Plan {
136 /// How the query was answered.
137 pub strategy: Strategy,
138 /// The costs compared to choose it, or `None` where there was nothing to compare: a variant
139 /// with no tables, a [`MultiIndex`](crate::MultiIndex), which scans only when its keys
140 /// outnumber its records, or a query whose planning the search's time budget cut short.
141 pub estimate: Option<Estimate>,
142 /// Whether the strategy was forced rather than chosen by the estimate.
143 pub forced: bool,
144}
145
146impl Plan {
147 /// A plan of `strategy`, chosen by `estimate` unless `forced`.
148 #[must_use]
149 pub const fn new(strategy: Strategy, estimate: Option<Estimate>, forced: bool) -> Self {
150 Self {
151 strategy,
152 estimate,
153 forced,
154 }
155 }
156}
157
158/// The plans for one call of a search, and the threads it runs on: what [`Search::plan`]
159/// returns.
160#[derive(Debug, Clone, PartialEq, Eq)]
161#[non_exhaustive]
162pub struct Planning {
163 /// A plan for each query, in query order, or none at all.
164 pub plans: Vec<Plan>,
165 /// The threads to split the call across, at least 1.
166 pub threads: usize,
167}
168
169impl Planning {
170 /// One plan a query, on `threads` threads.
171 #[must_use]
172 pub fn new(plans: Vec<Plan>, threads: usize) -> Self {
173 Self {
174 plans,
175 threads: threads.max(1),
176 }
177 }
178
179 /// No plans, on `threads` threads.
180 #[must_use]
181 pub fn unplanned(threads: usize) -> Self {
182 Self::new(Vec::new(), threads)
183 }
184}
185
186/// One share of a search split across threads: share `index` of `count`.
187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
188pub struct Share {
189 /// Which share, from 0.
190 pub index: usize,
191 /// How many shares there are, at least 1.
192 pub count: usize,
193}
194
195impl Share {
196 /// All the work, in one share.
197 pub const WHOLE: Self = Self { index: 0, count: 1 };
198
199 /// This share's part of `0..length`: the shares split it into consecutive ranges, each but
200 /// the last a multiple of 64 long.
201 #[must_use]
202 pub fn range(self, length: usize) -> Range<usize> {
203 let count = self.count.max(1) as u64;
204 let bound = |share: u64| {
205 if share >= count {
206 length
207 } else {
208 ((length as u64 * share / count) & !63) as usize
209 }
210 };
211 bound(self.index as u64)..bound(self.index as u64 + 1)
212 }
213}
214
215/// When to stop collecting candidates: never, or at a deadline.
216///
217/// A search looks at it between runs of work (see [`Search::collect`]): past the deadline it
218/// collects no more, and the matches it has are merged, cut by time, and returned. The merging,
219/// and what the caller does with the result, come after the deadline, not within it.
220#[derive(Debug, Clone, Copy)]
221pub struct Stop {
222 deadline: Option<Instant>,
223 /// Where the time is read: [`Instant::now`], or in the crate's own tests a clock they drive.
224 now: fn() -> Instant,
225}
226
227impl PartialEq for Stop {
228 fn eq(&self, other: &Self) -> bool {
229 self.deadline == other.deadline
230 }
231}
232
233impl Eq for Stop {}
234
235impl Default for Stop {
236 fn default() -> Self {
237 Self::never()
238 }
239}
240
241impl Stop {
242 /// Never stop early.
243 #[must_use]
244 pub const fn never() -> Self {
245 Self::at_on(None, Instant::now)
246 }
247
248 /// Stop at `deadline`.
249 #[must_use]
250 pub const fn at(deadline: Instant) -> Self {
251 Self::at_on(Some(deadline), Instant::now)
252 }
253
254 /// Stop `budget` after now, read from `now`; never, for no budget or one too long to add to
255 /// the clock.
256 pub(crate) fn after(budget: Option<Duration>, now: fn() -> Instant) -> Self {
257 Self::at_on(budget.and_then(|budget| now().checked_add(budget)), now)
258 }
259
260 /// Stop at `deadline`, if any, reading the time from `now`.
261 pub(crate) const fn at_on(deadline: Option<Instant>, now: fn() -> Instant) -> Self {
262 Self { deadline, now }
263 }
264
265 /// Whether the deadline has passed. Reads the clock only when there is one.
266 #[must_use]
267 pub fn reached(&self) -> bool {
268 self.deadline.is_some_and(|deadline| (self.now)() >= deadline)
269 }
270
271 /// Whether there is a deadline at all.
272 #[must_use]
273 pub const fn is_set(&self) -> bool {
274 self.deadline.is_some()
275 }
276}
277
278/// Reads the clock for a deadline after every [`EVERY`](Self::EVERY) units of work, a unit being
279/// a record compared or a posting read, and a key probed counting as [`KEY`](Self::KEY). A search
280/// notices its deadline within about a thousand records' work, however that work is split
281/// between queries, tiles and keys, and reads the clock no more than once a thousand records.
282pub(crate) struct Clock<'a> {
283 stop: &'a Stop,
284 spent: usize,
285}
286
287impl<'a> Clock<'a> {
288 /// The work between two reads of the clock.
289 pub(crate) const EVERY: usize = 1024;
290 /// What probing one key counts as: a hash lookup, worth many postings.
291 pub(crate) const KEY: usize = 64;
292
293 pub(crate) const fn new(stop: &'a Stop) -> Self {
294 Self { stop, spent: 0 }
295 }
296
297 /// Count `work` units, and say whether the deadline has passed if it is time to look.
298 pub(crate) fn spend(&mut self, work: usize) -> bool {
299 if !self.stop.is_set() {
300 return false;
301 }
302 self.spent += work;
303 if self.spent < Self::EVERY {
304 return false;
305 }
306 self.spent = 0;
307 self.stop.reached()
308 }
309}
310
311/// The hits one share collected for one query, held within a bound.
312///
313/// A variant pushes each record within the radius onto [`hits`](Self::hits) and calls
314/// [`trim`](Self::trim) after every run of pushes: after each [`TRIM_RUN`] records a scan
315/// compares, or each record an index reads. `trim` costs a comparison until the list passes its
316/// bound, and then brings it back under:
317///
318/// - with a limit or a size budget of `k` (see [`Options`]), it keeps the `k` nearest by distance
319/// and then position, drops the rest, and notes that it dropped some. The crate's variants push
320/// at most [`TRIM_RUN`] hits between two trims and grow the list no further than that needs, so
321/// a list never holds more than [`max_hits`]`(k)`, `2k + 5,119` hits, its capacity included,
322/// however many records match;
323/// - with records left out (all-zero values, or those [`search_batch_excluding`] names), it drops
324/// them first, so they don't count against the bound;
325/// - for [`neighbour_table`](crate::neighbour_table), it adds the hits to a count by distance and
326/// empties the list, so the list never holds more than [`max_hits`]`(0)` hits.
327///
328/// A list with no bound keeps every hit, and `trim` does nothing. A variant that never calls
329/// `trim` still returns the right result: the bound is applied when the search finishes. It only
330/// loses the bound on memory. A variant of your own that pushes more than [`TRIM_RUN`] hits
331/// between two trims holds more, and a trim gives back the capacity grown past [`max_hits`].
332#[derive(Clone)]
333pub struct HitList<'a> {
334 /// Records within the radius, by position, in no particular order.
335 pub hits: Vec<Hit>,
336 /// The candidates the query cost: records whose distance was computed, or index entries read.
337 pub candidates: u64,
338 /// Trim when `hits` reaches this length; `usize::MAX` when there is no bound.
339 trim_at: usize,
340 /// The hits a bounded list keeps when it trims.
341 keep: Option<usize>,
342 /// Whether trimming has dropped a hit that was within the radius and not left out.
343 dropped: bool,
344 /// Whether the record at a position is to be left out of the results.
345 exclude: Option<&'a (dyn Fn(u32) -> bool + Sync)>,
346 /// For a histogram: the count of hits at each distance, and a position not to count.
347 histogram: Option<(Vec<u64>, Option<u32>)>,
348 /// The plan chosen for the query, if the variant plans.
349 plan: Option<Plan>,
350}
351
352/// How far past twice the hits it keeps a list may grow before [`HitList::trim`] brings it back.
353const SLACK: usize = 4096;
354
355/// The most records a variant of this crate compares for one query between two calls of
356/// [`HitList::trim`], and so the most hits it pushes between them: a scan cuts each tile into runs
357/// of this many. Small beside a tile, so a dense tile can't swell a list, and large enough that the
358/// calls cost nothing beside the comparisons.
359pub const TRIM_RUN: usize = 1024;
360
361/// The most hits a list that keeps the nearest `keep` holds at any moment, its capacity included,
362/// when the variant filling it pushes at most [`TRIM_RUN`] hits between trims, as every variant of
363/// this crate does: `2 × keep + 4,096`, the length at which it trims, plus one run less one. A list
364/// that counts a histogram holds at most `max_hits(0)`.
365///
366/// ```
367/// assert_eq!(legit_hamming::max_hits(1), 5_121);
368/// ```
369#[must_use]
370pub const fn max_hits(keep: usize) -> usize {
371 keep.saturating_mul(2)
372 .saturating_add(SLACK)
373 .saturating_add(TRIM_RUN - 1)
374}
375
376impl<'a> HitList<'a> {
377 /// A list that keeps every hit.
378 #[must_use]
379 pub const fn new() -> Self {
380 Self {
381 hits: Vec::new(),
382 candidates: 0,
383 trim_at: usize::MAX,
384 keep: None,
385 dropped: false,
386 exclude: None,
387 histogram: None,
388 plan: None,
389 }
390 }
391
392 /// The plan [`Search::plan`] chose for this list's query, if the variant plans and the list
393 /// came from [`search`], [`search_batch`] or [`neighbour_table`](crate::neighbour_table).
394 #[must_use]
395 pub const fn plan(&self) -> Option<Plan> {
396 self.plan
397 }
398
399 /// The list, carrying `plan`.
400 pub(crate) const fn with_plan(mut self, plan: Option<Plan>) -> Self {
401 self.plan = plan;
402 self
403 }
404
405 /// A list that keeps the `keep` nearest hits, if `keep` is given, and leaves out the records
406 /// for which `exclude` is true, if it is given.
407 pub(crate) fn bounded(keep: Option<usize>, exclude: Option<&'a (dyn Fn(u32) -> bool + Sync)>) -> Self {
408 let trim_at = match (keep, exclude) {
409 (Some(keep), _) => keep.saturating_mul(2).saturating_add(SLACK),
410 (None, Some(_)) => SLACK,
411 (None, None) => usize::MAX,
412 };
413 Self {
414 trim_at,
415 keep,
416 exclude,
417 ..Self::new()
418 }
419 }
420
421 /// A list that counts its hits by distance, up to `max_distance`, instead of keeping them,
422 /// and doesn't count the record at `skip`.
423 pub(crate) fn histogram(max_distance: u32, skip: Option<u32>) -> Self {
424 Self {
425 trim_at: SLACK,
426 histogram: Some((vec![0; max_distance as usize + 1], skip)),
427 ..Self::new()
428 }
429 }
430
431 /// Bring the list back within its bound, if it has passed it. Call it after every run of
432 /// pushes onto [`hits`](Self::hits).
433 #[inline]
434 pub fn trim(&mut self) {
435 if self.hits.len() >= self.trim_at {
436 self.compact();
437 }
438 }
439
440 /// Whether the list has a bound its hits are held to: a limit or size budget, or a histogram.
441 const fn is_bounded(&self) -> bool {
442 self.keep.is_some() || self.histogram.is_some()
443 }
444
445 /// The most hits the list holds, its capacity included: [`max_hits`] of what it keeps, or
446 /// `usize::MAX` when it has no bound.
447 fn most(&self) -> usize {
448 if self.is_bounded() {
449 max_hits(self.keep.unwrap_or(0))
450 } else {
451 usize::MAX
452 }
453 }
454
455 /// Make room for `run` more hits, at most [`TRIM_RUN`]: call it before a run of pushes. A
456 /// bounded list grows by doubling, as a `Vec` does, but never past [`max_hits`], under which a
457 /// list shorter than its trimming length always has room for a run.
458 #[inline]
459 pub(crate) fn prepare(&mut self, run: usize) {
460 let need = self.hits.len().saturating_add(run);
461 let capacity = self.hits.capacity();
462 if need <= capacity {
463 return;
464 }
465 let grown = need.max(capacity.saturating_mul(2)).max(64).min(self.most()).max(need);
466 self.hits.reserve_exact(grown - self.hits.len());
467 }
468
469 /// Push one hit and trim: for a variant that finds its hits one at a time.
470 #[inline]
471 pub(crate) fn push(&mut self, hit: Hit) {
472 self.prepare(1);
473 self.hits.push(hit);
474 self.trim();
475 }
476
477 fn compact(&mut self) {
478 if let Some((counts, skip)) = &mut self.histogram {
479 for hit in self.hits.drain(..) {
480 if Some(hit.position) != *skip
481 && let Some(count) = counts.get_mut(hit.distance as usize)
482 {
483 *count += 1;
484 }
485 }
486 return;
487 }
488 if let Some(exclude) = self.exclude {
489 self.hits.retain(|hit| !exclude(hit.position));
490 }
491 if let Some(keep) = self.keep
492 && self.hits.len() > keep
493 {
494 if keep > 0 {
495 self.hits
496 .select_nth_unstable_by_key(keep - 1, |hit| (hit.distance, hit.position));
497 }
498 self.hits.truncate(keep);
499 self.dropped = true;
500 }
501 // With nothing kept beyond the excluded records, grow the threshold so a list that keeps
502 // everything is not re-scanned after every run.
503 if self.keep.is_none() {
504 self.trim_at = self.hits.len().saturating_mul(2).max(SLACK);
505 }
506 // A variant that pushed more than a run between trims gives back what it grew past the
507 // bound...
508 if self.hits.capacity() > self.most() {
509 self.hits.shrink_to(self.most());
510 }
511 }
512
513 /// Add another share's list for the same query to this one. A bounded list is brought down to
514 /// what it keeps on both sides first, so the two together stay within its bound.
515 fn absorb(&mut self, mut other: Self) {
516 self.candidates += other.candidates;
517 if self.is_bounded() {
518 self.compact();
519 other.compact();
520 }
521 self.dropped |= other.dropped;
522 if let (Some((counts, _)), Some((other_counts, _))) = (&mut self.histogram, &other.histogram) {
523 for (count, other) in counts.iter_mut().zip(other_counts) {
524 *count += other;
525 }
526 }
527 if self.hits.is_empty() {
528 self.hits = other.hits;
529 } else {
530 self.prepare(other.hits.len());
531 self.hits.extend(other.hits);
532 }
533 self.trim();
534 }
535
536 /// The counts by distance of a histogram list, with every hit still held counted.
537 pub(crate) fn into_counts(mut self) -> Vec<u64> {
538 self.compact();
539 self.histogram.map(|(counts, _)| counts).unwrap_or_default()
540 }
541}
542
543impl Default for HitList<'_> {
544 fn default() -> Self {
545 Self::new()
546 }
547}
548
549impl fmt::Debug for HitList<'_> {
550 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
551 f.debug_struct("HitList")
552 .field("hits", &self.hits.len())
553 .field("candidates", &self.candidates)
554 .field("keep", &self.keep)
555 .field("dropped", &self.dropped)
556 .field("histogram", &self.histogram.as_ref().map(|(counts, _)| counts))
557 .field("plan", &self.plan)
558 .finish_non_exhaustive()
559 }
560}
561
562/// The memory a variant takes, in bytes.
563#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
564pub struct Memory {
565 /// The records, ids and values, held in memory. A variant that shares its records with others
566 /// counts them in full.
567 pub records: usize,
568 /// The index built over the records, beyond the records themselves.
569 pub index: usize,
570 /// Files mapped into memory: the operating system pages them in as a search reads them.
571 pub mapped: usize,
572}
573
574/// How to run a search.
575#[derive(Debug, Clone, PartialEq, Eq)]
576#[non_exhaustive]
577pub struct Options {
578 /// Every record within this Hamming distance of the query is a match.
579 pub radius: u32,
580 /// Return only the nearest `limit` matches by distance. `None` returns all.
581 pub limit: Option<usize>,
582 /// A size budget: hold at most this many matches per query, the nearest by distance. It bounds
583 /// the memory a search holds as well as the result: at most [`max_hits`] of it, about twice
584 /// this many, hits a query and thread.
585 pub max_matches: Option<usize>,
586 /// A search budget: the search stops collecting candidates once this much time has passed,
587 /// and keeps only the matches at distance 0 it found, the only ones proven nearest (see
588 /// [`Found::cut_by`]); the result follows as soon as what was collected is merged. The clock
589 /// is read between runs of about a thousand records' work, so collecting stops within one run
590 /// of the deadline; merging, sorting and building the result come after it. A budget too long
591 /// to add to the clock is no budget.
592 pub time_budget: Option<Duration>,
593 /// Threads to split the search across; 0 counts as 1. A variant that plans may use fewer for
594 /// a call it expects to be short: see [`Search::plan`].
595 pub threads: usize,
596 /// Leave records whose value is all zeros out of the results.
597 pub exclude_zero: bool,
598}
599
600impl Options {
601 /// Every match within `radius`, on one thread, with no budget.
602 #[must_use]
603 pub const fn new(radius: u32) -> Self {
604 Self {
605 radius,
606 limit: None,
607 max_matches: None,
608 time_budget: None,
609 threads: 1,
610 exclude_zero: false,
611 }
612 }
613
614 /// Return only the nearest `limit` matches.
615 #[must_use]
616 pub const fn limit(mut self, limit: usize) -> Self {
617 self.limit = Some(limit);
618 self
619 }
620
621 /// Hold at most `max_matches` matches per query.
622 #[must_use]
623 pub const fn max_matches(mut self, max_matches: usize) -> Self {
624 self.max_matches = Some(max_matches);
625 self
626 }
627
628 /// Stop after `budget`.
629 #[must_use]
630 pub const fn time_budget(mut self, budget: Duration) -> Self {
631 self.time_budget = Some(budget);
632 self
633 }
634
635 /// Split the search across `threads` threads.
636 #[must_use]
637 pub const fn threads(mut self, threads: usize) -> Self {
638 self.threads = threads;
639 self
640 }
641
642 /// Leave all-zero values out of the results.
643 #[must_use]
644 pub const fn exclude_zero(mut self, exclude: bool) -> Self {
645 self.exclude_zero = exclude;
646 self
647 }
648}
649
650/// A stored record within the radius of a query.
651#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
652pub struct Match<V> {
653 /// The record's position in the set searched, from 0. Positions rise with ids.
654 pub position: u32,
655 /// The record's id, if the set's records carry ids.
656 pub id: Option<u64>,
657 /// The record's value.
658 pub value: V,
659 /// How many bits differ from the query.
660 pub distance: u32,
661}
662
663/// What cut a result short.
664#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
665#[non_exhaustive]
666pub enum Cut {
667 /// The caller's [`Options::limit`].
668 Limit,
669 /// The time budget, [`Options::time_budget`].
670 Time,
671 /// The size budget, [`Options::max_matches`].
672 Size,
673}
674
675impl Cut {
676 /// The name the service contract uses: `limit`, `time` or `size`.
677 #[must_use]
678 pub const fn name(self) -> &'static str {
679 match self {
680 Self::Limit => "limit",
681 Self::Time => "time",
682 Self::Size => "size",
683 }
684 }
685}
686
687/// The result of one query.
688#[derive(Debug, Clone, PartialEq, Eq)]
689#[non_exhaustive]
690pub struct Found<V> {
691 /// The matches, by distance and then by id (or position, for a set without ids).
692 pub matches: Vec<Match<V>>,
693 /// What cut the list short, or `None` if it is every match within the radius.
694 ///
695 /// Whatever cut it, the list holds the nearest matches: every record nearer than the farthest
696 /// one returned is returned. A limit or a size budget keeps the nearest that many. A time
697 /// budget stops collecting before the search has reached every record, and any record it
698 /// didn't reach could be nearer than a match it found, so it returns only the matches at
699 /// distance 0, which nothing is nearer than, and none if it found none.
700 pub cut_by: Option<Cut>,
701 /// The candidates the query cost: records whose distance was computed, or index entries read.
702 pub candidates: u64,
703 /// The plan the query ran with, for a variant that plans: [`Planned`](crate::Planned), or a
704 /// [`MultiIndex`](crate::MultiIndex), which says when it scanned. `None` for a variant with
705 /// one way to answer.
706 pub plan: Option<Plan>,
707}
708
709impl<V> Found<V> {
710 /// Whether the list is every match within the radius.
711 #[must_use]
712 pub const fn is_complete(&self) -> bool {
713 self.cut_by.is_none()
714 }
715}
716
717/// Search for one query.
718///
719/// # Panics
720///
721/// Panics if the variant panics on one of the threads.
722pub fn search<V: Value>(index: &(impl Search<V> + ?Sized), query: V, options: &Options) -> Found<V> {
723 search_batch(index, &[query], options)
724 .pop()
725 .expect("one result a query")
726}
727
728/// Search for many queries in one call: a scan reads each part of the set once for all of them.
729/// The results are in the order of the queries.
730///
731/// # Panics
732///
733/// Panics if the variant panics on one of the threads.
734pub fn search_batch<V: Value>(index: &(impl Search<V> + ?Sized), queries: &[V], options: &Options) -> Vec<Found<V>> {
735 search_batch_with(index, queries, options, None)
736}
737
738/// [`search_batch`], leaving out every record at a position for which `exclude` is true, as if
739/// the set didn't hold it.
740///
741/// The records are left out where the hits are kept, before any limit or size budget trims a
742/// list, so a query cut by `limit` still returns the nearest `limit` records that aren't left
743/// out, and says it was cut only when more than that many are within the radius. It's what a set
744/// that masks some of its records needs, such as a snapshot under a table of later changes:
745/// filtering the result afterwards would return fewer than `limit` matches when more exist.
746/// `exclude` is called for records within the radius only, from several threads at once.
747///
748/// ```
749/// use std::sync::Arc;
750///
751/// use legit_hamming::{Options, Planned, Records, search_batch_excluding};
752///
753/// let records = Records::from_records([(1, 0b0001u64), (2, 0b0011), (3, 0b0111)])?;
754/// let index = Planned::new(Arc::new(records), 64 << 20, 1);
755/// // The nearest record is position 0, left out: the limit of 1 keeps the next nearest...
756/// let found = search_batch_excluding(&index, &[0b0001], &Options::new(4).limit(1), &|position| position == 0);
757/// assert_eq!(found[0].matches[0].id, Some(2));
758/// assert!(!found[0].is_complete());
759/// # Ok::<(), legit_hamming::Error>(())
760/// ```
761///
762/// # Panics
763///
764/// Panics if the variant or `exclude` panics on one of the threads.
765pub fn search_batch_excluding<V: Value>(
766 index: &(impl Search<V> + ?Sized),
767 queries: &[V],
768 options: &Options,
769 exclude: &(dyn Fn(u32) -> bool + Sync),
770) -> Vec<Found<V>> {
771 search_batch_with(index, queries, options, Some(exclude))
772}
773
774fn search_batch_with<V: Value>(
775 index: &(impl Search<V> + ?Sized),
776 queries: &[V],
777 options: &Options,
778 excluded: Option<&(dyn Fn(u32) -> bool + Sync)>,
779) -> Vec<Found<V>> {
780 let stop = Stop::after(options.time_budget, Instant::now);
781 search_batch_until(index, queries, options, excluded, &stop)
782}
783
784/// [`search_batch_excluding`], or with no `excluded` [`search_batch`], collecting until `stop`
785/// rather than within [`Options::time_budget`], which it doesn't read.
786pub(crate) fn search_batch_until<V: Value>(
787 index: &(impl Search<V> + ?Sized),
788 queries: &[V],
789 options: &Options,
790 excluded: Option<&(dyn Fn(u32) -> bool + Sync)>,
791 stop: &Stop,
792) -> Vec<Found<V>> {
793 let keep = match (options.limit, options.max_matches) {
794 (Some(limit), Some(max)) => Some(limit.min(max)),
795 (limit, max) => limit.or(max),
796 };
797 let left_out = |position: u32| {
798 (options.exclude_zero && index.value(position as usize).is_zero())
799 || excluded.is_some_and(|excluded| excluded(position))
800 };
801 let exclude: Option<&(dyn Fn(u32) -> bool + Sync)> =
802 (options.exclude_zero || excluded.is_some()).then_some(&left_out);
803 let planning = index.plan(queries, options.radius, options.threads.max(1), stop);
804 let plans = &planning.plans;
805 let (lists, stopped) = collect_all(index, queries, options.radius, planning.threads, stop, |query| {
806 HitList::bounded(keep, exclude).with_plan(plans.get(query).copied())
807 });
808 lists
809 .into_iter()
810 .map(|list| finish(index, list, options, exclude, stopped))
811 .collect()
812}
813
814/// Run `collect` over every share, on as many threads, into the lists `list` makes for each query
815/// by its index, and gather each query's shares into one list.
816pub(crate) fn collect_all<'a, V: Value>(
817 index: &(impl Search<V> + ?Sized),
818 queries: &[V],
819 radius: u32,
820 threads: usize,
821 stop: &Stop,
822 list: impl Fn(usize) -> HitList<'a> + Sync,
823) -> (Vec<HitList<'a>>, bool) {
824 let threads = threads.max(1);
825 let mut lists: Vec<HitList<'a>> = (0..queries.len()).map(&list).collect();
826 if threads == 1 {
827 let stopped = index.collect(queries, radius, Share::WHOLE, stop, &mut lists);
828 return (lists, stopped);
829 }
830 let mut stopped = false;
831 thread::scope(|scope| {
832 let workers: Vec<_> = (0..threads)
833 .map(|share| {
834 let list = &list;
835 scope.spawn(move || {
836 let mut part: Vec<HitList<'a>> = (0..queries.len()).map(list).collect();
837 let share = Share {
838 index: share,
839 count: threads,
840 };
841 let stopped = index.collect(queries, radius, share, stop, &mut part);
842 (part, stopped)
843 })
844 })
845 .collect();
846 for worker in workers {
847 let (part, share_stopped) = worker.join().unwrap_or_else(|panic| std::panic::resume_unwind(panic));
848 stopped |= share_stopped;
849 for (list, part) in lists.iter_mut().zip(part) {
850 list.absorb(part);
851 }
852 }
853 });
854 (lists, stopped)
855}
856
857fn finish<V: Value>(
858 index: &(impl Search<V> + ?Sized),
859 list: HitList<'_>,
860 options: &Options,
861 exclude: Option<&(dyn Fn(u32) -> bool + Sync)>,
862 stopped: bool,
863) -> Found<V> {
864 let dropped = list.dropped;
865 let mut hits = list.hits;
866 // A list trims, and so leaves out, only once it passes its bound: the rest go here...
867 if let Some(exclude) = exclude {
868 hits.retain(|hit| !exclude(hit.position));
869 }
870 let key = |hit: &Hit| (hit.distance, hit.position);
871 let mut cut_by = None;
872 if stopped {
873 // The search didn't reach every record, so any of them may be nearer than a match it
874 // found, except a match at distance 0: nothing is nearer. Those are all that are proven.
875 hits.retain(|hit| hit.distance == 0);
876 cut_by = Some(Cut::Time);
877 }
878 let keep = match (options.limit, options.max_matches) {
879 (Some(limit), Some(max)) if max < limit => Some((max, Cut::Size)),
880 (Some(limit), _) => Some((limit, Cut::Limit)),
881 (None, Some(max)) => Some((max, Cut::Size)),
882 (None, None) => None,
883 };
884 if let Some((keep, cut)) = keep
885 && (dropped || hits.len() > keep)
886 {
887 if keep > 0 && hits.len() > keep {
888 hits.select_nth_unstable_by_key(keep - 1, key);
889 }
890 hits.truncate(keep);
891 cut_by.get_or_insert(cut);
892 }
893 hits.sort_unstable_by_key(key);
894 let matches = hits
895 .into_iter()
896 .map(|hit| {
897 let position = hit.position as usize;
898 Match {
899 position: hit.position,
900 id: index.id(position),
901 value: index.value(position),
902 distance: hit.distance,
903 }
904 })
905 .collect();
906 Found {
907 matches,
908 cut_by,
909 candidates: list.candidates,
910 plan: list.plan,
911 }
912}
913
914/// A clock for the crate's tests that moves on a millisecond each time it is read, on the thread
915/// reading it: a search on one thread reads it at the same points every run, so a test can place
916/// its deadline between any two of them.
917#[cfg(test)]
918pub(crate) mod ticking {
919 use std::cell::Cell;
920 use std::sync::OnceLock;
921 use std::time::{Duration, Instant};
922
923 thread_local! {
924 static READS: Cell<u64> = const { Cell::new(0) };
925 }
926
927 /// The time: a millisecond on from the last read on this thread.
928 pub(crate) fn now() -> Instant {
929 static START: OnceLock<Instant> = OnceLock::new();
930 let reads = READS.with(|reads| {
931 reads.set(reads.get() + 1);
932 reads.get()
933 });
934 *START.get_or_init(Instant::now) + Duration::from_millis(reads)
935 }
936
937 /// Start this thread's clock again.
938 pub(crate) fn reset() {
939 READS.with(|reads| reads.set(0));
940 }
941}