use std::fmt;
use std::ops::Range;
use std::thread;
use std::time::{Duration, Instant};
use crate::kernel::Hit;
use crate::value::Value;
pub trait Search<V: Value>: Send + Sync + fmt::Debug {
fn variant(&self) -> String;
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn has_ids(&self) -> bool;
fn id(&self, position: usize) -> Option<u64>;
fn value(&self, position: usize) -> V;
fn memory(&self) -> Memory;
fn collect(&self, queries: &[V], radius: u32, share: Share, stop: &Stop, out: &mut [HitList<'_>]) -> bool;
fn plan(&self, queries: &[V], radius: u32, threads: usize, stop: &Stop) -> Planning {
let _ = (queries, radius, stop);
Planning::unplanned(threads)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Strategy {
Scan,
MultiIndex,
}
impl Strategy {
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Scan => "scan",
Self::MultiIndex => "multi-index",
}
}
}
impl fmt::Display for Strategy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Estimate {
pub keys: u64,
pub candidates: u64,
pub counted: bool,
pub probe_cost: u64,
pub scan_cost: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Plan {
pub strategy: Strategy,
pub estimate: Option<Estimate>,
pub forced: bool,
}
impl Plan {
#[must_use]
pub const fn new(strategy: Strategy, estimate: Option<Estimate>, forced: bool) -> Self {
Self {
strategy,
estimate,
forced,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Planning {
pub plans: Vec<Plan>,
pub threads: usize,
}
impl Planning {
#[must_use]
pub fn new(plans: Vec<Plan>, threads: usize) -> Self {
Self {
plans,
threads: threads.max(1),
}
}
#[must_use]
pub fn unplanned(threads: usize) -> Self {
Self::new(Vec::new(), threads)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Share {
pub index: usize,
pub count: usize,
}
impl Share {
pub const WHOLE: Self = Self { index: 0, count: 1 };
#[must_use]
pub fn range(self, length: usize) -> Range<usize> {
let count = self.count.max(1) as u64;
let bound = |share: u64| {
if share >= count {
length
} else {
((length as u64 * share / count) & !63) as usize
}
};
bound(self.index as u64)..bound(self.index as u64 + 1)
}
}
#[derive(Debug, Clone, Copy)]
pub struct Stop {
deadline: Option<Instant>,
now: fn() -> Instant,
}
impl PartialEq for Stop {
fn eq(&self, other: &Self) -> bool {
self.deadline == other.deadline
}
}
impl Eq for Stop {}
impl Default for Stop {
fn default() -> Self {
Self::never()
}
}
impl Stop {
#[must_use]
pub const fn never() -> Self {
Self::at_on(None, Instant::now)
}
#[must_use]
pub const fn at(deadline: Instant) -> Self {
Self::at_on(Some(deadline), Instant::now)
}
pub(crate) fn after(budget: Option<Duration>, now: fn() -> Instant) -> Self {
Self::at_on(budget.and_then(|budget| now().checked_add(budget)), now)
}
pub(crate) const fn at_on(deadline: Option<Instant>, now: fn() -> Instant) -> Self {
Self { deadline, now }
}
#[must_use]
pub fn reached(&self) -> bool {
self.deadline.is_some_and(|deadline| (self.now)() >= deadline)
}
#[must_use]
pub const fn is_set(&self) -> bool {
self.deadline.is_some()
}
}
pub(crate) struct Clock<'a> {
stop: &'a Stop,
spent: usize,
}
impl<'a> Clock<'a> {
pub(crate) const EVERY: usize = 1024;
pub(crate) const KEY: usize = 64;
pub(crate) const fn new(stop: &'a Stop) -> Self {
Self { stop, spent: 0 }
}
pub(crate) fn spend(&mut self, work: usize) -> bool {
if !self.stop.is_set() {
return false;
}
self.spent += work;
if self.spent < Self::EVERY {
return false;
}
self.spent = 0;
self.stop.reached()
}
}
#[derive(Clone)]
pub struct HitList<'a> {
pub hits: Vec<Hit>,
pub candidates: u64,
trim_at: usize,
keep: Option<usize>,
dropped: bool,
exclude: Option<&'a (dyn Fn(u32) -> bool + Sync)>,
histogram: Option<(Vec<u64>, Option<u32>)>,
plan: Option<Plan>,
}
const SLACK: usize = 4096;
pub const TRIM_RUN: usize = 1024;
#[must_use]
pub const fn max_hits(keep: usize) -> usize {
keep.saturating_mul(2)
.saturating_add(SLACK)
.saturating_add(TRIM_RUN - 1)
}
impl<'a> HitList<'a> {
#[must_use]
pub const fn new() -> Self {
Self {
hits: Vec::new(),
candidates: 0,
trim_at: usize::MAX,
keep: None,
dropped: false,
exclude: None,
histogram: None,
plan: None,
}
}
#[must_use]
pub const fn plan(&self) -> Option<Plan> {
self.plan
}
pub(crate) const fn with_plan(mut self, plan: Option<Plan>) -> Self {
self.plan = plan;
self
}
pub(crate) fn bounded(keep: Option<usize>, exclude: Option<&'a (dyn Fn(u32) -> bool + Sync)>) -> Self {
let trim_at = match (keep, exclude) {
(Some(keep), _) => keep.saturating_mul(2).saturating_add(SLACK),
(None, Some(_)) => SLACK,
(None, None) => usize::MAX,
};
Self {
trim_at,
keep,
exclude,
..Self::new()
}
}
pub(crate) fn histogram(max_distance: u32, skip: Option<u32>) -> Self {
Self {
trim_at: SLACK,
histogram: Some((vec![0; max_distance as usize + 1], skip)),
..Self::new()
}
}
#[inline]
pub fn trim(&mut self) {
if self.hits.len() >= self.trim_at {
self.compact();
}
}
const fn is_bounded(&self) -> bool {
self.keep.is_some() || self.histogram.is_some()
}
fn most(&self) -> usize {
if self.is_bounded() {
max_hits(self.keep.unwrap_or(0))
} else {
usize::MAX
}
}
#[inline]
pub(crate) fn prepare(&mut self, run: usize) {
let need = self.hits.len().saturating_add(run);
let capacity = self.hits.capacity();
if need <= capacity {
return;
}
let grown = need.max(capacity.saturating_mul(2)).max(64).min(self.most()).max(need);
self.hits.reserve_exact(grown - self.hits.len());
}
#[inline]
pub(crate) fn push(&mut self, hit: Hit) {
self.prepare(1);
self.hits.push(hit);
self.trim();
}
fn compact(&mut self) {
if let Some((counts, skip)) = &mut self.histogram {
for hit in self.hits.drain(..) {
if Some(hit.position) != *skip
&& let Some(count) = counts.get_mut(hit.distance as usize)
{
*count += 1;
}
}
return;
}
if let Some(exclude) = self.exclude {
self.hits.retain(|hit| !exclude(hit.position));
}
if let Some(keep) = self.keep
&& self.hits.len() > keep
{
if keep > 0 {
self.hits
.select_nth_unstable_by_key(keep - 1, |hit| (hit.distance, hit.position));
}
self.hits.truncate(keep);
self.dropped = true;
}
if self.keep.is_none() {
self.trim_at = self.hits.len().saturating_mul(2).max(SLACK);
}
if self.hits.capacity() > self.most() {
self.hits.shrink_to(self.most());
}
}
fn absorb(&mut self, mut other: Self) {
self.candidates += other.candidates;
if self.is_bounded() {
self.compact();
other.compact();
}
self.dropped |= other.dropped;
if let (Some((counts, _)), Some((other_counts, _))) = (&mut self.histogram, &other.histogram) {
for (count, other) in counts.iter_mut().zip(other_counts) {
*count += other;
}
}
if self.hits.is_empty() {
self.hits = other.hits;
} else {
self.prepare(other.hits.len());
self.hits.extend(other.hits);
}
self.trim();
}
pub(crate) fn into_counts(mut self) -> Vec<u64> {
self.compact();
self.histogram.map(|(counts, _)| counts).unwrap_or_default()
}
}
impl Default for HitList<'_> {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for HitList<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HitList")
.field("hits", &self.hits.len())
.field("candidates", &self.candidates)
.field("keep", &self.keep)
.field("dropped", &self.dropped)
.field("histogram", &self.histogram.as_ref().map(|(counts, _)| counts))
.field("plan", &self.plan)
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Memory {
pub records: usize,
pub index: usize,
pub mapped: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Options {
pub radius: u32,
pub limit: Option<usize>,
pub max_matches: Option<usize>,
pub time_budget: Option<Duration>,
pub threads: usize,
pub exclude_zero: bool,
}
impl Options {
#[must_use]
pub const fn new(radius: u32) -> Self {
Self {
radius,
limit: None,
max_matches: None,
time_budget: None,
threads: 1,
exclude_zero: false,
}
}
#[must_use]
pub const fn limit(mut self, limit: usize) -> Self {
self.limit = Some(limit);
self
}
#[must_use]
pub const fn max_matches(mut self, max_matches: usize) -> Self {
self.max_matches = Some(max_matches);
self
}
#[must_use]
pub const fn time_budget(mut self, budget: Duration) -> Self {
self.time_budget = Some(budget);
self
}
#[must_use]
pub const fn threads(mut self, threads: usize) -> Self {
self.threads = threads;
self
}
#[must_use]
pub const fn exclude_zero(mut self, exclude: bool) -> Self {
self.exclude_zero = exclude;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Match<V> {
pub position: u32,
pub id: Option<u64>,
pub value: V,
pub distance: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Cut {
Limit,
Time,
Size,
}
impl Cut {
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Limit => "limit",
Self::Time => "time",
Self::Size => "size",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Found<V> {
pub matches: Vec<Match<V>>,
pub cut_by: Option<Cut>,
pub candidates: u64,
pub plan: Option<Plan>,
}
impl<V> Found<V> {
#[must_use]
pub const fn is_complete(&self) -> bool {
self.cut_by.is_none()
}
}
pub fn search<V: Value>(index: &(impl Search<V> + ?Sized), query: V, options: &Options) -> Found<V> {
search_batch(index, &[query], options)
.pop()
.expect("one result a query")
}
pub fn search_batch<V: Value>(index: &(impl Search<V> + ?Sized), queries: &[V], options: &Options) -> Vec<Found<V>> {
search_batch_with(index, queries, options, None)
}
pub fn search_batch_excluding<V: Value>(
index: &(impl Search<V> + ?Sized),
queries: &[V],
options: &Options,
exclude: &(dyn Fn(u32) -> bool + Sync),
) -> Vec<Found<V>> {
search_batch_with(index, queries, options, Some(exclude))
}
fn search_batch_with<V: Value>(
index: &(impl Search<V> + ?Sized),
queries: &[V],
options: &Options,
excluded: Option<&(dyn Fn(u32) -> bool + Sync)>,
) -> Vec<Found<V>> {
let stop = Stop::after(options.time_budget, Instant::now);
search_batch_until(index, queries, options, excluded, &stop)
}
pub(crate) fn search_batch_until<V: Value>(
index: &(impl Search<V> + ?Sized),
queries: &[V],
options: &Options,
excluded: Option<&(dyn Fn(u32) -> bool + Sync)>,
stop: &Stop,
) -> Vec<Found<V>> {
let keep = match (options.limit, options.max_matches) {
(Some(limit), Some(max)) => Some(limit.min(max)),
(limit, max) => limit.or(max),
};
let left_out = |position: u32| {
(options.exclude_zero && index.value(position as usize).is_zero())
|| excluded.is_some_and(|excluded| excluded(position))
};
let exclude: Option<&(dyn Fn(u32) -> bool + Sync)> =
(options.exclude_zero || excluded.is_some()).then_some(&left_out);
let planning = index.plan(queries, options.radius, options.threads.max(1), stop);
let plans = &planning.plans;
let (lists, stopped) = collect_all(index, queries, options.radius, planning.threads, stop, |query| {
HitList::bounded(keep, exclude).with_plan(plans.get(query).copied())
});
lists
.into_iter()
.map(|list| finish(index, list, options, exclude, stopped))
.collect()
}
pub(crate) fn collect_all<'a, V: Value>(
index: &(impl Search<V> + ?Sized),
queries: &[V],
radius: u32,
threads: usize,
stop: &Stop,
list: impl Fn(usize) -> HitList<'a> + Sync,
) -> (Vec<HitList<'a>>, bool) {
let threads = threads.max(1);
let mut lists: Vec<HitList<'a>> = (0..queries.len()).map(&list).collect();
if threads == 1 {
let stopped = index.collect(queries, radius, Share::WHOLE, stop, &mut lists);
return (lists, stopped);
}
let mut stopped = false;
thread::scope(|scope| {
let workers: Vec<_> = (0..threads)
.map(|share| {
let list = &list;
scope.spawn(move || {
let mut part: Vec<HitList<'a>> = (0..queries.len()).map(list).collect();
let share = Share {
index: share,
count: threads,
};
let stopped = index.collect(queries, radius, share, stop, &mut part);
(part, stopped)
})
})
.collect();
for worker in workers {
let (part, share_stopped) = worker.join().unwrap_or_else(|panic| std::panic::resume_unwind(panic));
stopped |= share_stopped;
for (list, part) in lists.iter_mut().zip(part) {
list.absorb(part);
}
}
});
(lists, stopped)
}
fn finish<V: Value>(
index: &(impl Search<V> + ?Sized),
list: HitList<'_>,
options: &Options,
exclude: Option<&(dyn Fn(u32) -> bool + Sync)>,
stopped: bool,
) -> Found<V> {
let dropped = list.dropped;
let mut hits = list.hits;
if let Some(exclude) = exclude {
hits.retain(|hit| !exclude(hit.position));
}
let key = |hit: &Hit| (hit.distance, hit.position);
let mut cut_by = None;
if stopped {
hits.retain(|hit| hit.distance == 0);
cut_by = Some(Cut::Time);
}
let keep = 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,
};
if let Some((keep, cut)) = keep
&& (dropped || hits.len() > keep)
{
if keep > 0 && hits.len() > keep {
hits.select_nth_unstable_by_key(keep - 1, key);
}
hits.truncate(keep);
cut_by.get_or_insert(cut);
}
hits.sort_unstable_by_key(key);
let matches = hits
.into_iter()
.map(|hit| {
let position = hit.position as usize;
Match {
position: hit.position,
id: index.id(position),
value: index.value(position),
distance: hit.distance,
}
})
.collect();
Found {
matches,
cut_by,
candidates: list.candidates,
plan: list.plan,
}
}
#[cfg(test)]
pub(crate) mod ticking {
use std::cell::Cell;
use std::sync::OnceLock;
use std::time::{Duration, Instant};
thread_local! {
static READS: Cell<u64> = const { Cell::new(0) };
}
pub(crate) fn now() -> Instant {
static START: OnceLock<Instant> = OnceLock::new();
let reads = READS.with(|reads| {
reads.set(reads.get() + 1);
reads.get()
});
*START.get_or_init(Instant::now) + Duration::from_millis(reads)
}
pub(crate) fn reset() {
READS.with(|reads| reads.set(0));
}
}