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;
#[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> {
pub const CANDIDATE_COST: u64 = 32;
pub const WORK_PER_THREAD: u64 = 250_000;
#[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")
}
pub fn try_new(records: Arc<Records<V>>, budget: usize, threads: usize) -> Result<Self> {
let chunks = V::BITS / 16;
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,
})
}
#[must_use]
pub fn scan_only(records: Arc<Records<V>>) -> Self {
Self {
records,
index: None,
isa: Isa::best_for::<V>(),
force: None,
}
}
#[must_use]
pub fn table_bytes(records: usize) -> usize {
MultiIndex::<V>::table_bytes(records, V::BITS / 16).unwrap_or(usize::MAX)
}
pub fn with_isa(mut self, isa: Isa) -> Result<Self> {
self.isa = isa.require()?;
Ok(self)
}
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)
}
#[must_use]
pub const fn has_tables(&self) -> bool {
self.index.is_some()
}
#[must_use]
pub const fn index(&self) -> Option<&MultiIndex<V>> {
self.index.as_ref()
}
#[must_use]
pub const fn records(&self) -> &Arc<Records<V>> {
&self.records
}
#[must_use]
pub const fn isa(&self) -> Isa {
self.isa
}
#[must_use]
pub fn plan_query(&self, query: &V, radius: u32) -> Plan {
let never = Stop::never();
self.plan_within(query, radius, &mut Clock::new(&never))
.unwrap_or_else(|| self.unplanned())
}
fn unplanned(&self) -> Plan {
Plan::new(self.force.unwrap_or(Strategy::Scan), None, self.force.is_some())
}
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| {
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))
}
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
}
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)
{
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,
}
}
fn collect(&self, queries: &[V], radius: u32, share: Share, stop: &Stop, out: &mut [HitList<'_>]) -> bool {
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
}
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)
}
}