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
//! The index that chooses, query by query, between a scan and its multi-index tables.

use std::fmt::Write as _;
use std::sync::Arc;

use crate::cpu::Isa;
use crate::error::{Error, Result};
use crate::multi_index::MultiIndex;
use crate::records::Records;
use crate::scan::scan_tiles;
use crate::search::{Clock, Estimate, HitList, Memory, Plan, Planning, Search, Share, Stop, Strategy};
use crate::value::Value;

/// A set of records that answers each query the cheaper way: a scan of every record, or a probe of
/// its multi-index tables, chosen by an estimate of each.
///
/// It owns the records and, if they fit in the memory budget it is given, multi-index tables of
/// 16-bit chunks over them: 4 at 64 bits, 16 at 256 ([`table_bytes`](Self::table_bytes) says how
/// much they take). For each query it counts what a probe would read, the keys it looks up and the
/// entries those keys hold, from the tables' own bucket sizes for that query's keys, and compares
/// it with what a scan reads, every record:
///
/// - a probe costs its keys plus [`CANDIDATE_COST`](Self::CANDIDATE_COST) times its candidates;
/// - a scan costs its records;
/// - the cheaper runs, and a tie scans.
///
/// Counting stops as soon as the probe is sure to cost more, so it never costs more than a small
/// part of the scan it avoids, and it isn't started when the keys alone outnumber the records,
/// the rule a [`MultiIndex`] scans by. With no tables, every query scans.
///
/// Its threads follow from the same estimate: a call gets one thread for every
/// [`WORK_PER_THREAD`](Self::WORK_PER_THREAD) of the work it expects, at least 1 and at most the
/// threads given, so a single query expected to finish in well under a millisecond runs on one
/// thread, and a scan of a large set or a large batch on every thread given.
///
/// Every query returns exactly the reference's matches whichever way it runs: the choice changes
/// only the cost. [`Found::plan`](crate::Found::plan) says which plan ran and the estimate that
/// chose it, and [`force`](Self::force) fixes the plan, for tests and measurement.
///
/// ```
/// use std::sync::Arc;
///
/// use legit_hamming::{Options, Planned, Records, Strategy, search};
///
/// let values = (0..100_000u64).map(|i| i.wrapping_mul(0x9e37_79b9_7f4a_7c15));
/// let records = Arc::new(Records::from_records((1..).zip(values))?);
/// let planned = Planned::new(Arc::clone(&records), 64 << 20, 1);
/// assert!(planned.has_tables());
///
/// // A near query at a small radius reads a few table entries...
/// let near = search(&planned, records.value(7) ^ 0b101, &Options::new(4));
/// assert_eq!(near.plan.map(|plan| plan.strategy), Some(Strategy::MultiIndex));
/// assert_eq!(near.matches[0].id, Some(8));
///
/// // ...and a radius at which a probe would read most of the set scans it.
/// let wide = search(&planned, 0, &Options::new(24));
/// assert_eq!(wide.plan.map(|plan| plan.strategy), Some(Strategy::Scan));
/// # Ok::<(), legit_hamming::Error>(())
/// ```
#[derive(Debug, Clone)]
pub struct Planned<V> {
    records: Arc<Records<V>>,
    index: Option<MultiIndex<V>>,
    isa: Isa,
    force: Option<Strategy>,
}

impl<V: Value> Planned<V> {
    /// What reading one table entry costs, in records scanned: the constant a probe's candidates
    /// are weighed by against a scan's records.
    ///
    /// Measured on an Intel Xeon Gold 5412U, one thread, as the time a multi-index query took per
    /// candidate over the time the best scan took per record, at the radii where candidates
    /// dominate. The radius sweep on synthetic records gave 31 to 51: 32 at 10 million 256-bit
    /// records (53 ns a candidate against 1.7 ns a record, radius 48 to 96), 39 to 45 at 1 million,
    /// 40 to 48 at 1 million 64-bit records and about 50 at 10 million. About 90 million real 64-bit
    /// perceptual hashes of one image collection gave 17 (7.3 ns against 0.43 ns at radius 8), their
    /// near neighbours sitting closer together in the tables. 32 is the low end of the synthetic
    /// range, within twice both it and the real values, so a plan chosen wrongly costs at most about
    /// twice the other; on those real values, swept from radius 0 to 16, the plan it gives took the
    /// faster way at every radius.
    pub const CANDIDATE_COST: u64 = 32;

    /// The work, in 64-bit words scanned, that pays for one more thread: a call expecting `w`
    /// words of work runs on `w / WORK_PER_THREAD` threads, at least 1 and at most those given.
    /// A probe's work is its cost times the value's words.
    ///
    /// 250,000 words is about 0.11 ms on one core of an Intel Xeon Gold 5412U with AVX-512.
    /// There, splitting a single query that took 0.04 ms across 2 threads cut its rate from 22,639
    /// to 13,921 a second (1 million records, multi-index, radius 8), a scan of 1 million 64-bit
    /// records ran fastest on 4 threads and lost on 16, and a query of 2 ms on about 90 million real
    /// 64-bit perceptual hashes of one image collection gained 2.4 times on 4 threads.
    pub const WORK_PER_THREAD: u64 = 250_000;

    /// Own `records`, with multi-index tables over them if they take at most `budget` bytes,
    /// built on up to `threads` threads; scan on [`Isa::best_for`].
    ///
    /// # Panics
    ///
    /// Panics if a thread building a table panics, or the allocator won't give the tables their
    /// memory: [`try_new`](Self::try_new) says so instead.
    #[must_use]
    pub fn new(records: Arc<Records<V>>, budget: usize, threads: usize) -> Self {
        Self::try_new(records, budget, threads).expect("the tables' memory is given")
    }

    /// [`new`](Self::new), telling a table the allocator won't give its memory as an error.
    ///
    /// # Errors
    ///
    /// [`Error::OutOfMemory`](crate::Error::OutOfMemory) when a table's memory can't be had.
    ///
    /// # Panics
    ///
    /// Panics if a thread building a table panics.
    pub fn try_new(records: Arc<Records<V>>, budget: usize, threads: usize) -> Result<Self> {
        let chunks = V::BITS / 16;
        // 16-bit chunks split either width, so the only error is the memory's...
        let index = if Self::table_bytes(records.len()) <= budget {
            Some(MultiIndex::new(Arc::clone(&records), chunks, threads)?)
        } else {
            None
        };
        Ok(Self {
            records,
            index,
            isa: Isa::best_for::<V>(),
            force: None,
        })
    }

    /// Own `records` with no tables: every query scans.
    #[must_use]
    pub fn scan_only(records: Arc<Records<V>>) -> Self {
        Self {
            records,
            index: None,
            isa: Isa::best_for::<V>(),
            force: None,
        }
    }

    /// The bytes the tables over `records` records take, beyond the records: 4 bytes a record for
    /// each 16-bit chunk, 4 chunks at 64 bits and 16 at 256, plus 256 KiB a chunk.
    #[must_use]
    pub fn table_bytes(records: usize) -> usize {
        MultiIndex::<V>::table_bytes(records, V::BITS / 16).unwrap_or(usize::MAX)
    }

    /// Scan on the path `isa` rather than the best.
    ///
    /// # Errors
    ///
    /// [`Error::IsaUnavailable`] if this CPU can't run it.
    pub fn with_isa(mut self, isa: Isa) -> Result<Self> {
        self.isa = isa.require()?;
        Ok(self)
    }

    /// Answer every query with `strategy`, whatever the estimate, or choose again with `None`.
    /// The estimate is still made and reported.
    ///
    /// # Errors
    ///
    /// [`Error::NoTables`] to force [`Strategy::MultiIndex`] without tables.
    pub fn force(mut self, strategy: Option<Strategy>) -> Result<Self> {
        if strategy == Some(Strategy::MultiIndex) && self.index.is_none() {
            return Err(Error::NoTables);
        }
        self.force = strategy;
        Ok(self)
    }

    /// Whether the tables were built: whether they fitted the budget.
    #[must_use]
    pub const fn has_tables(&self) -> bool {
        self.index.is_some()
    }

    /// The tables, if they were built.
    #[must_use]
    pub const fn index(&self) -> Option<&MultiIndex<V>> {
        self.index.as_ref()
    }

    /// The records.
    #[must_use]
    pub const fn records(&self) -> &Arc<Records<V>> {
        &self.records
    }

    /// The path a scan runs on.
    #[must_use]
    pub const fn isa(&self) -> Isa {
        self.isa
    }

    /// The plan for `query` within `radius`: the strategy, and the estimate that chose it.
    #[must_use]
    pub fn plan_query(&self, query: &V, radius: u32) -> Plan {
        let never = Stop::never();
        // With no deadline, planning is never cut short...
        self.plan_within(query, radius, &mut Clock::new(&never))
            .unwrap_or_else(|| self.unplanned())
    }

    /// The plan for a query whose planning `clock`'s deadline cut short: the forced strategy, or a
    /// scan, with no estimate. The search it belongs to has run out of time, and stops as soon as
    /// it starts.
    fn unplanned(&self) -> Plan {
        Plan::new(self.force.unwrap_or(Strategy::Scan), None, self.force.is_some())
    }

    /// The plan for `query` within `radius`, or `None` if `clock`'s deadline passed while its
    /// candidates were being counted.
    fn plan_within(&self, query: &V, radius: u32, clock: &mut Clock<'_>) -> Option<Plan> {
        let forced = self.force.is_some();
        let Some(index) = &self.index else {
            return Some(Plan::new(Strategy::Scan, None, forced));
        };
        let records = self.records.len() as u64;
        let cost = |keys: u64, candidates: u64| keys.saturating_add(candidates.saturating_mul(Self::CANDIDATE_COST));
        let estimate = if index.scans_at(radius) {
            let keys = index.probes(radius);
            Estimate {
                keys,
                candidates: 0,
                counted: false,
                probe_cost: keys,
                scan_cost: records,
            }
        } else {
            let mut expired = false;
            let (keys, candidates, counted) = index.count_probe(query, radius, |keys, candidates| {
                // A key's bucket size is two offsets read: one unit of a clock's work...
                expired = clock.spend(1);
                expired || cost(keys, candidates) > records
            });
            if expired {
                return None;
            }
            Estimate {
                keys,
                candidates,
                counted,
                probe_cost: cost(keys, candidates),
                scan_cost: records,
            }
        };
        let strategy = self.force.unwrap_or(if estimate.probe_cost < estimate.scan_cost {
            Strategy::MultiIndex
        } else {
            Strategy::Scan
        });
        Some(Plan::new(strategy, Some(estimate), forced))
    }

    /// The strategy a list's query runs with: the one it carries, or a fresh plan, made within
    /// `clock`'s deadline. Once `expired` is set, by the caller or by a plan the deadline cut
    /// short, it stays set and no further query is counted.
    fn strategy(
        &self,
        query: &V,
        radius: u32,
        list: &HitList<'_>,
        clock: &mut Clock<'_>,
        expired: &mut bool,
    ) -> Strategy {
        if self.index.is_none() {
            return Strategy::Scan;
        }
        list.plan()
            .or_else(|| {
                if *expired {
                    return None;
                }
                let plan = self.plan_within(query, radius, clock);
                *expired = plan.is_none();
                plan
            })
            .unwrap_or_else(|| self.unplanned())
            .strategy
    }

    /// The threads a call with these plans runs on, from `threads` given.
    fn threads_for(&self, plans: &[Plan], radius: u32, threads: usize) -> usize {
        let records = self.records.len() as u64;
        let work = plans
            .iter()
            .map(|plan| match (plan.strategy, plan.estimate) {
                (Strategy::MultiIndex, Some(estimate)) => estimate.probe_cost,
                _ => records,
            })
            .fold(0u64, u64::saturating_add)
            .saturating_mul(V::WORDS as u64);
        let mut wanted = usize::try_from(work / Self::WORK_PER_THREAD).unwrap_or(usize::MAX);
        if let Some(index) = &self.index
            && plans.iter().all(|plan| plan.strategy == Strategy::MultiIndex)
        {
            // A probe splits its queries between threads, or one query's tables: no more threads
            // than that have work...
            wanted = wanted.min(plans.len().max(index.tables_probed(radius)));
        }
        wanted.clamp(1, threads.max(1))
    }
}

impl<V: Value> Search<V> for Planned<V> {
    fn variant(&self) -> String {
        let mut name = format!("planned/{}", self.isa);
        if let Some(index) = &self.index {
            let _ = write!(name, "+{}x{}", index.chunks(), index.chunk_bits());
        }
        if let Some(strategy) = self.force {
            let _ = write!(name, " forced {strategy}");
        }
        name
    }

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

    fn has_ids(&self) -> bool {
        self.records.has_ids()
    }

    fn id(&self, position: usize) -> Option<u64> {
        self.records.id(position)
    }

    fn value(&self, position: usize) -> V {
        self.records.value(position)
    }

    fn memory(&self) -> Memory {
        Memory {
            records: self.records.heap_bytes(),
            index: self.index.as_ref().map_or(0, |index| index.memory().index),
            mapped: 0,
        }
    }

    /// The queries planned to scan are scanned together, each share a range of the records, and
    /// those planned to probe are probed, each share some of the queries or tables.
    fn collect(&self, queries: &[V], radius: u32, share: Share, stop: &Stop, out: &mut [HitList<'_>]) -> bool {
        // A list from a caller that doesn't plan, such as a set wrapping this one, carries no
        // plan: each is planned here, within the deadline, and none once it has passed...
        let mut clock = Clock::new(stop);
        let mut expired = stop.reached();
        let probes: Vec<bool> = queries
            .iter()
            .zip(out.iter())
            .map(|(query, list)| self.strategy(query, radius, list, &mut clock, &mut expired) == Strategy::MultiIndex)
            .collect();
        let range = share.range(self.records.len());
        let Some(index) = self.index.as_ref().filter(|_| probes.contains(&true)) else {
            return scan_tiles(self.isa, &self.records, range, 0, queries, radius, stop, out);
        };
        if !probes.contains(&false) {
            return index.probe(queries, radius, share, stop, out);
        }
        let (mut scan_queries, mut scan_lists, mut probe_queries, mut probe_lists) =
            (Vec::new(), Vec::new(), Vec::new(), Vec::new());
        for ((query, list), &probe) in queries.iter().zip(out.iter_mut()).zip(&probes) {
            if probe {
                probe_queries.push(*query);
                probe_lists.push(std::mem::take(list));
            } else {
                scan_queries.push(*query);
                scan_lists.push(std::mem::take(list));
            }
        }
        let stopped = scan_tiles(
            self.isa,
            &self.records,
            range,
            0,
            &scan_queries,
            radius,
            stop,
            &mut scan_lists,
        ) || index.probe(&probe_queries, radius, share, stop, &mut probe_lists);
        let (mut scanned, mut probed) = (scan_lists.into_iter(), probe_lists.into_iter());
        for (list, &probe) in out.iter_mut().zip(&probes) {
            let next = if probe { probed.next() } else { scanned.next() };
            *list = next.expect("one list a query, taken and returned in order");
        }
        stopped
    }

    /// Each query's plan from [`plan_query`](Self::plan_query), and the threads from the work they
    /// expect: see [`WORK_PER_THREAD`](Self::WORK_PER_THREAD).
    ///
    /// Counting watches `stop`'s deadline, as a search does: once it has passed, no more buckets
    /// are counted, and every query not yet planned gets the forced strategy, or a scan, with no
    /// estimate. The search then stops as soon as it starts, cut by time.
    fn plan(&self, queries: &[V], radius: u32, threads: usize, stop: &Stop) -> Planning {
        let mut clock = Clock::new(stop);
        let mut expired = stop.reached();
        let plans: Vec<Plan> = queries
            .iter()
            .map(|query| {
                if !expired
                    && !clock.spend(Clock::KEY)
                    && let Some(plan) = self.plan_within(query, radius, &mut clock)
                {
                    return plan;
                }
                expired = true;
                self.unplanned()
            })
            .collect();
        let threads = self.threads_for(&plans, radius, threads);
        Planning::new(plans, threads)
    }
}