use std::collections::{HashMap, HashSet};
use std::ops::Range;
use std::sync::Arc;
use rusqlite::{Connection, OptionalExtension};
use super::analyzer::{self, Word};
use super::clusters::{self, Phase, Probe};
use super::correct::Corrector;
use super::execute::{Fetch, List, best, best_of, held_by_all};
use super::filter::{self, Docs, Reader};
use super::hybrid::{self, HALF};
use super::kept::{Chunk, Gone, Kept, Moment, NORMS};
use super::layouts;
use super::matches::{Ask, Sought};
use super::pack::{Stored, read_list};
use super::postings::{Posting, decode_directory, unpack, unpack_inline};
use super::score::{PREFIXED, Part, average, idf, score};
use super::settings::Settings;
use super::vectors::{self, Among, Question, Scan};
use crate::sqlite::sql_error;
use crate::sync::lock;
use crate::{Error, Memory, Result};
const READ_INDEX: &str =
"select documents, normed, gone_version, words_version from _tinystore_search_indexes where id = ?1";
const READ_PARTS: &str = "select part, tokens from _tinystore_search_parts where index_id = ?1";
const FIND_KEY: &str =
"select id, documents from _tinystore_search_keys where index_id = ?1 and part = ?2 and term = ?3";
const FIND_PREFIXED: &str = "select id, documents, term from _tinystore_search_keys
where index_id = ?1 and part = ?2 and term > ?3 and term < ?4 and documents > 0
order by documents desc, term limit cast(?5 as integer)";
const BEGINS_A_WORD: &str = "select exists (select 1 from _tinystore_search_keys
where index_id = ?1 and part = ?2 and term > ?3 and term < ?4 and documents > 0)";
const READ_HEAD: &str = "select doc, tf, len from _tinystore_search_head where index_id = ?1 and key = ?2 order by doc";
pub(super) const READ_BLOCK: &str = "select payload from _tinystore_search_blocks where key = ?1 and first = ?2";
const READ_BLOCKS: &str =
"select first, payload from _tinystore_search_blocks where key = ?1 and first >= ?2 and first <= ?3 order by first";
const READ_HIT: &str = "select id, value from _tinystore_search_docs where index_id = ?1 and doc = ?2";
const AHEAD: usize = 8;
const MOST_PREFIXED: usize = 64;
const LEAST_PREFIX: usize = 2;
const MOST_PREFIXES: usize = 8;
const NARROW_WORDS: u64 = 32;
const NARROW_VECTORS: u64 = 4;
#[derive(Debug)]
pub(crate) struct Query {
pub(crate) normal: String,
pub(crate) words: Vec<Word>,
pub(crate) vector: Option<Question>,
pub(crate) vector_weight: Option<f64>,
pub(crate) rerank: bool,
pub(crate) prefix: Prefix,
pub(crate) matches: Option<Ask>,
pub(crate) filter: Option<filter::Asked>,
pub(crate) offset: usize,
pub(crate) limit: usize,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum Prefix {
#[default]
Whole,
Last,
Every,
}
#[derive(Debug)]
pub(crate) struct Asked<'a> {
pub(crate) index: i64,
pub(crate) settings: &'a Settings,
pub(crate) kept: &'a Kept,
pub(crate) memory: &'a Arc<Memory>,
pub(crate) query: Query,
}
#[derive(Debug)]
pub(crate) struct Answer {
pub(crate) hits: Vec<(String, Vec<u8>, f64)>,
pub(crate) corrected: Option<String>,
pub(crate) behind: bool,
pub(crate) sought: Option<Sought>,
}
#[derive(Clone, Copy, Debug)]
enum Mode {
Words,
Vector,
Sum(f64),
Rerank,
}
pub(crate) fn search(connection: &Connection, mut asked: Asked<'_>) -> Result<Answer> {
let (moment, documents, words_version) = moment(connection, asked.index)?;
let mode = mode(&asked)?;
let mut behind = false;
let swapped = layouts::swap(connection, &mut asked)?;
let corrected = correct(connection, &mut asked, (words_version, &mut behind), swapped)?;
let k = asked.query.offset + asked.query.limit;
let both = k.max(HALF);
let passing = passing(connection, &asked, moment)?;
let held = Held { moment, documents, passing: passing.as_deref() };
let ranked = match mode {
Mode::Words => by_words(connection, &asked, held, k)?,
Mode::Vector => by_vector(connection, &asked, held, k)?,
Mode::Sum(weight) => {
let words = by_words(connection, &asked, held, both)?;
hybrid::fuse(&words, &by_vector(connection, &asked, held, both)?, weight)
}
Mode::Rerank => {
let words = by_words(connection, &asked, held, both)?;
let docs: Vec<u32> = words.iter().map(|(_, doc)| *doc).collect();
hybrid::rerank(&words, &vectors::cosines(connection, asked.index, question(&asked)?, &docs)?)
}
};
let page = ranked.into_iter().skip(asked.query.offset).take(asked.query.limit);
let hits = page.map(|(score, doc)| hit(connection, asked.index, doc, score)).collect::<Result<_>>()?;
let sought = match &asked.query.matches {
Some(ask) if !matches!(mode, Mode::Vector) => Some(sought(connection, &asked, ask)?),
_ => None,
};
Ok(Answer { hits, corrected, behind, sought })
}
fn sought(connection: &Connection, asked: &Asked<'_>, ask: &Ask) -> Result<Sought> {
let mut sought = Sought::new(ask.clone(), &asked.settings.fields);
for (at, word) in asked.query.words.iter().enumerate() {
for form in forms(std::slice::from_ref(word), asked.settings) {
sought.key(form, at);
}
}
for at in prefixes(&asked.query) {
let word = &asked.query.words[at];
let Some(past) = past(&word.text) else { continue };
let typed = (at, word.text.chars().count());
for field in &asked.settings.fields {
let part = Part::written(field.number);
for term in terms_starting(connection, asked.index, part, (&word.text, &past))? {
sought.begun((part, term), typed);
}
}
}
Ok(sought)
}
fn mode(asked: &Asked<'_>) -> Result<Mode> {
let query = &asked.query;
let Some(question) = &query.vector else { return Ok(Mode::Words) };
let Some(vectors) = asked.settings.vectors else {
return Err(Error::invalid("a search by a vector of an index without vectors"));
};
if question.dimensions() != vectors.dimensions {
return Err(Error::invalid(format!(
"a vector of {} dimensions where the index holds {}",
question.dimensions(),
vectors.dimensions
)));
}
if query.words.is_empty() && !query.rerank {
return Ok(Mode::Vector);
}
let hybrid = asked.settings.hybrid;
let weight = match query.vector_weight {
Some(weight) => weight,
None if query.rerank || hybrid.rerank => return Ok(Mode::Rerank),
None => hybrid.vector_weight,
};
Ok(match weight {
0.0 => Mode::Words,
1.0 => Mode::Vector,
weight => Mode::Sum(weight),
})
}
fn question<'a>(asked: &'a Asked<'_>) -> Result<&'a Question> {
asked.query.vector.as_ref().ok_or_else(|| Error::internal("a search by its vector has none"))
}
#[derive(Clone, Copy)]
struct Held<'a> {
moment: Moment,
documents: u64,
passing: Option<&'a [u32]>,
}
fn passing(connection: &Connection, asked: &Asked<'_>, moment: Moment) -> Result<Option<Vec<u32>>> {
let Some(conditions) = &asked.query.filter else { return Ok(None) };
let gone = asked.kept.gone(connection, moment)?;
let reader = Reader { connection, index: asked.index, settings: asked.settings, gone: &gone.docs };
Ok(match reader.passing(conditions)? {
Docs::All => None,
Docs::Only(docs) => Some(docs),
})
}
fn narrow(passing: usize, documents: u64, share: u64) -> bool {
#[cfg(test)]
if let Some(narrow) = NARROW.get() {
return narrow;
}
(passing as u64).saturating_mul(share) <= documents
}
#[cfg(test)]
thread_local! {
pub(crate) static NARROW: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
}
fn by_words(connection: &Connection, asked: &Asked<'_>, held: Held<'_>, k: usize) -> Result<Vec<(f64, u32)>> {
let Held { moment, documents, .. } = held;
let stats =
Stats { documents, tokens: tokens(connection, asked.index)?, gone: asked.kept.gone(connection, moment)? };
let mut source = Source::new(connection, asked, moment, &stats);
let Lists { mut lists, words } = lists(connection, asked, &stats, &mut source)?;
let found = match asked.query.prefix {
Prefix::Every => holding_every_word_first((&mut lists, &words), &mut source, held, k)?,
Prefix::Whole | Prefix::Last => ranked(&mut lists, &mut source, held, k)?,
};
#[cfg(test)]
check(connection, asked, (&stats, held), (&found, k))?;
Ok(found.into_iter().map(|(points, doc)| (score(points), doc)).collect())
}
fn ranked(lists: &mut [List], source: &mut Source<'_>, held: Held<'_>, k: usize) -> Result<Vec<(u64, u32)>> {
match held.passing {
Some(docs) if narrow(docs.len(), held.documents, NARROW_WORDS) => best_of(lists, source, docs, k),
passing => best(lists, source, k, passing),
}
}
fn holding_every_word_first(
(lists, words): (&mut [List], &[Vec<usize>]),
source: &mut Source<'_>,
held: Held<'_>,
k: usize,
) -> Result<Vec<(u64, u32)>> {
let above = lists.iter().fold(0_u64, |sum, list| sum.saturating_add(list.most()));
let raised = |found: Vec<(u64, u32)>| found.into_iter().map(|(points, doc)| (points.saturating_add(above), doc));
if words.len() < 2 {
return Ok(raised(ranked(lists, source, held, k)?).collect());
}
let every = held_by_all(lists, words, source, held.passing)?;
let holding = Held { passing: Some(&every), ..held };
let mut first: Vec<(u64, u32)> = raised(ranked(&mut lists.to_vec(), source, holding, k)?).collect();
if first.len() < k {
let rest = ranked(lists, source, held, k)?.into_iter().filter(|(_, doc)| every.binary_search(doc).is_err());
first.extend(rest.take(k - every.len()));
}
Ok(first)
}
fn by_clusters(
connection: &Connection,
asked: &Asked<'_>,
held: Held<'_>,
k: usize,
) -> Result<Option<Vec<(f64, u32)>>> {
let Some(vectors) = asked.settings.vectors.filter(|vectors| vectors.recall.is_some()) else { return Ok(None) };
let state = clusters::state(connection, asked.index)?;
if state.phase != Phase::Serving || state.probes <= 0 {
return Ok(None);
}
let at = (asked.index, state.version, vectors.dimensions);
let kept = clusters::kept(&asked.kept.clusters, connection, at)?;
let question = question(asked)?;
let probe = Probe {
index: asked.index,
clusters: &kept,
question,
k,
probes: state.probes as usize,
rescored: state.rescored as usize,
passing: held.passing,
};
clusters::best(connection, &probe).map(Some)
}
fn by_vector(connection: &Connection, asked: &Asked<'_>, held: Held<'_>, k: usize) -> Result<Vec<(f64, u32)>> {
let among = match held.passing {
None => Among::Every,
Some(docs) if narrow(docs.len(), held.documents, NARROW_VECTORS) => Among::Only(docs),
Some(docs) => Among::Crossed(docs),
};
if !matches!(among, Among::Only(_))
&& let Some(found) = by_clusters(connection, asked, held, k)?
{
return Ok(found);
}
let scan = Scan { index: asked.index, question: question(asked)?, k, among };
let found = vectors::best(connection, &scan)?;
#[cfg(test)]
if CHECKED.get() {
let every = vectors::every(connection, &scan)?;
if every != found {
return Err(Error::internal(format!("found {found:?} where every vector gives {every:?}")));
}
}
Ok(found)
}
fn moment(connection: &Connection, index: i64) -> Result<(Moment, u64, i64)> {
let mut select = connection.prepare_cached(READ_INDEX).map_err(|error| sql_error("read an index", error))?;
let row = select.query_row([index], |row| {
let moment = Moment { index, normed: row.get(1)?, gone_version: row.get(2)? };
Ok((moment, row.get::<_, i64>(0)?.max(0) as u64, row.get(3)?))
});
row.map_err(|error| sql_error("read an index", error))
}
struct Stats {
documents: u64,
tokens: HashMap<Part, u64>,
gone: Arc<Gone>,
}
struct Lists {
lists: Vec<List>,
words: Vec<Vec<usize>>,
}
fn lists(connection: &Connection, asked: &Asked<'_>, stats: &Stats, source: &mut Source<'_>) -> Result<Lists> {
let mut found = keyed_lists(connection, asked, stats)?;
let mut begun: HashMap<&str, Vec<usize>> = HashMap::new();
for at in prefixes(&asked.query) {
let text = asked.query.words[at].text.as_str();
if !begun.contains_key(text) {
let mut places = Vec::new();
for field in &asked.settings.fields {
let part = Part::written(field.number);
if let Some(list) = prefixed(connection, asked, (stats, &mut *source), (part, text))? {
places.push(found.lists.len());
found.lists.push(list);
}
}
begun.insert(text, places);
}
found.words[at].extend(&begun[text]);
}
Ok(found)
}
fn keyed_lists(connection: &Connection, asked: &Asked<'_>, stats: &Stats) -> Result<Lists> {
let mut lists = Vec::new();
let mut placed: HashMap<(Part, String), usize> = HashMap::new();
for form in forms(&asked.query.words, asked.settings) {
if let Some(list) = list(connection, asked, stats, &form)? {
placed.insert(form, lists.len());
lists.push(list);
}
}
let finding = |word: &Word| {
forms(std::slice::from_ref(word), asked.settings).iter().filter_map(|form| placed.get(form).copied()).collect()
};
Ok(Lists { lists, words: asked.query.words.iter().map(finding).collect() })
}
pub(super) fn prefixes(query: &Query) -> Vec<usize> {
let words = &query.words;
match query.prefix {
Prefix::Whole => Vec::new(),
Prefix::Last => {
words.len().checked_sub(1).filter(|last| halfway(&words[*last], &query.normal)).into_iter().collect()
}
Prefix::Every => (0..words.len()).filter(|at| long_enough(&words[*at])).take(MOST_PREFIXES).collect(),
}
}
pub(super) fn halfway(word: &Word, normal: &str) -> bool {
word.at.end == normal.len() && long_enough(word)
}
pub(super) fn long_enough(word: &Word) -> bool {
word.text.chars().count() >= LEAST_PREFIX
}
#[cfg(test)]
thread_local! {
static CHECKED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
#[cfg(test)]
pub(crate) fn checked<T>(run: impl FnOnce() -> T) -> T {
CHECKED.set(true);
let ran = run();
CHECKED.set(false);
ran
}
#[cfg(test)]
fn check(
connection: &Connection,
asked: &Asked<'_>,
(stats, held): (&Stats, Held<'_>),
(found, k): (&[(u64, u32)], usize),
) -> Result<()> {
if !CHECKED.get() {
return Ok(());
}
let mut source = Source::new(connection, asked, held.moment, stats);
let Lists { mut lists, words } = lists(connection, asked, stats, &mut source)?;
let every = match asked.query.prefix {
Prefix::Every => every_by_words(&mut lists, &words, &mut source, (held.passing, k))?,
Prefix::Whole | Prefix::Last => super::execute::every(&mut lists, &mut source, k, held.passing)?,
};
if every != found {
return Err(Error::internal(format!("found {found:?} where every posting gives {every:?}")));
}
Ok(())
}
#[cfg(test)]
fn every_by_words(
lists: &mut [List],
words: &[Vec<usize>],
source: &mut Source<'_>,
(passing, k): (Option<&[u32]>, usize),
) -> Result<Vec<(u64, u32)>> {
let above = lists.iter().fold(0_u64, |sum, list| sum.saturating_add(list.most()));
let mut holding: Option<HashSet<u32>> = None;
for word in words {
let mut docs = HashSet::new();
for &at in word {
docs.extend(lists[at].clone().into_postings(source)?.into_iter().map(|posting| posting.doc));
}
holding = Some(match holding {
Some(held) => held.intersection(&docs).copied().collect(),
None => docs,
});
}
let holding = holding.unwrap_or_default();
let mut every = super::execute::every(lists, source, usize::MAX, passing)?;
for (points, doc) in &mut every {
if holding.contains(doc) {
*points = points.saturating_add(above);
}
}
every.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
every.truncate(k);
Ok(every)
}
fn tokens(connection: &Connection, index: i64) -> Result<HashMap<Part, u64>> {
let failed = |error| sql_error("read an index's lengths", error);
let mut select = connection.prepare_cached(READ_PARTS).map_err(failed)?;
let rows = select.query_map([index], |row| Ok((Part(row.get(0)?), row.get::<_, i64>(1)?.max(0) as u64)));
rows.and_then(Iterator::collect).map_err(failed)
}
pub(super) fn forms(words: &[Word], settings: &Settings) -> Vec<(Part, String)> {
let mut forms: Vec<(Part, String)> = Vec::new();
for word in words {
let stem = word.stem.as_deref().unwrap_or(&word.text);
for field in &settings.fields {
let (written, stems) = (Part::written(field.number), Part::stems(field.number));
forms.push((written, word.text.clone()));
forms.push((stems, stem.to_owned()));
if word.stem.is_some() {
forms.push((written, stem.to_owned()));
}
}
}
let mut seen = HashSet::new();
forms.retain(|form| seen.insert(form.clone()));
forms
}
fn find(connection: &Connection, index: i64, part: Part, term: &str) -> Result<Option<(i64, u64)>> {
let mut select = connection.prepare_cached(FIND_KEY).map_err(|error| sql_error("find a key", error))?;
let found = select.query_row((index, part.0, term), |row| Ok((row.get(0)?, row.get::<_, i64>(1)?.max(0) as u64)));
let found = found.optional();
found.map_err(|error| sql_error("find a key", error))
}
pub(super) fn held(connection: &Connection, asked: &Asked<'_>, word: &Word) -> Result<u64> {
let mut documents = 0;
for (part, term) in forms(std::slice::from_ref(word), asked.settings) {
let found = find(connection, asked.index, part, &term)?;
documents += found.map_or(0, |(_, documents)| documents);
}
Ok(documents)
}
fn correct(
connection: &Connection,
asked: &mut Asked<'_>,
(version, behind): (i64, &mut bool),
swapped: bool,
) -> Result<Option<String>> {
if !asked.settings.typo_tolerance {
return Ok(swapped.then(|| asked.query.normal.clone()));
}
let mut replaced = Vec::new();
let prefixes = prefixes(&asked.query);
for at in 0..asked.query.words.len() {
let word = &asked.query.words[at];
if word.text.chars().count() < 5 || held(connection, asked, word)? > 0 {
continue;
}
if prefixes.contains(&at) && begins_a_word(connection, asked, &word.text)? {
continue;
}
let corrector = corrector(connection, asked, version, behind)?;
let mut chosen: Option<(u64, Word)> = None;
for candidate in corrector.candidates(&word.text) {
let read = Word { stem: analyzer::stem(&candidate), text: candidate, at: word.at.clone() };
let documents = held(connection, asked, &read)?;
if documents > chosen.as_ref().map_or(0, |(most, _)| *most) {
chosen = Some((documents, read));
}
}
if let Some((_, read)) = chosen {
replaced.push((read.at.clone(), read.text.clone()));
asked.query.words[at] = read;
}
}
if replaced.is_empty() && !swapped {
return Ok(None);
}
Ok(Some(written(&asked.query.normal, replaced)))
}
fn written(normal: &str, replaced: Vec<(Range<usize>, String)>) -> String {
let mut apart: Vec<(Range<usize>, String)> = Vec::with_capacity(replaced.len());
for (at, word) in replaced {
if apart.last().is_none_or(|(last, _)| last.end <= at.start) {
apart.push((at, word));
}
}
let mut text = normal.to_owned();
for (at, word) in apart.into_iter().rev() {
text.replace_range(at, &word);
}
text
}
fn corrector(connection: &Connection, asked: &Asked<'_>, version: i64, behind: &mut bool) -> Result<Arc<Corrector>> {
if let Some(kept) = lock(&asked.kept.corrector).as_ref() {
*behind = kept.version != version;
return Ok(Arc::clone(kept));
}
let parts: Vec<Part> = asked.settings.fields.iter().map(|field| Part::written(field.number)).collect();
let built = Arc::new(Corrector::build(connection, asked.index, version, &parts)?);
*lock(&asked.kept.corrector) = Some(Arc::clone(&built));
Ok(built)
}
fn list(
connection: &Connection,
asked: &Asked<'_>,
stats: &Stats,
(part, term): &(Part, String),
) -> Result<Option<List>> {
let Some(found) = find(connection, asked.index, *part, term)? else { return Ok(None) };
keyed(connection, asked, stats, (*part, found))
}
fn keyed(
connection: &Connection,
asked: &Asked<'_>,
stats: &Stats,
(part, (key, holding)): (Part, (i64, u64)),
) -> Result<Option<List>> {
let Some(weight) = asked.settings.weight(part.field()) else { return Ok(None) };
if holding == 0 {
return Ok(None);
}
let tokens = stats.tokens.get(&part).copied().unwrap_or(0);
let scale = part.weight(weight) * idf(stats.documents, holding);
let mut list = List::new(key, part, scale, average(tokens, stats.documents), Vec::new());
let gone = &stats.gone.docs;
let within = |error: Error| error.within(format!("key {key}"));
match read_list(connection, key).map_err(within)? {
Stored::Blocks(directory) => {
for entry in decode_directory(&directory).map_err(within)? {
list.push(list.stored(entry.first, entry.last, entry.most_tf, entry.least_len));
}
}
Stored::Inline(inline) => push_held(&mut list, unpack_inline(&inline).map_err(within)?, gone),
Stored::Nothing => {}
}
push_held(&mut list, head(connection, asked.index, key)?, gone);
Ok((!list.is_empty()).then_some(list))
}
fn prefixed(
connection: &Connection,
asked: &Asked<'_>,
(stats, source): (&Stats, &mut Source<'_>),
(part, prefix): (Part, &str),
) -> Result<Option<List>> {
let Some(weight) = asked.settings.weight(part.field()) else { return Ok(None) };
let Some(past) = past(prefix) else { return Ok(None) };
let mut postings = Vec::new();
for found in words_starting(connection, asked.index, part, (prefix, &past))? {
if let Some(list) = keyed(connection, asked, stats, (part, found))? {
postings.extend(list.into_postings(source)?);
}
}
let joined = joined(postings);
if joined.is_empty() {
return Ok(None);
}
let tokens = stats.tokens.get(&part).copied().unwrap_or(0);
let scale = weight * PREFIXED * idf(stats.documents, joined.len() as u64);
Ok(Some(List::joined(part, scale, average(tokens, stats.documents), joined)))
}
fn joined(mut postings: Vec<Posting>) -> Vec<Posting> {
postings.sort_unstable_by_key(|posting| posting.doc);
let mut joined: Vec<Posting> = Vec::with_capacity(postings.len());
for posting in postings {
match joined.last_mut() {
Some(last) if last.doc == posting.doc => last.tf = last.tf.saturating_add(posting.tf),
_ => joined.push(posting),
}
}
joined
}
fn words_starting(
connection: &Connection,
index: i64,
part: Part,
(prefix, past): (&str, &str),
) -> Result<Vec<(i64, u64)>> {
let failed = |error| sql_error("find the words a prefix begins", error);
let mut select = connection.prepare_cached(FIND_PREFIXED).map_err(failed)?;
let most = MOST_PREFIXED as i64;
let rows = select
.query_map((index, part.0, prefix, past, most), |row| Ok((row.get(0)?, row.get::<_, i64>(1)?.max(0) as u64)));
rows.and_then(Iterator::collect).map_err(failed)
}
fn terms_starting(
connection: &Connection,
index: i64,
part: Part,
(prefix, past): (&str, &str),
) -> Result<Vec<String>> {
let failed = |error| sql_error("find the words a prefix begins", error);
let mut select = connection.prepare_cached(FIND_PREFIXED).map_err(failed)?;
let most = MOST_PREFIXED as i64;
let rows = select.query_map((index, part.0, prefix, past, most), |row| row.get(2));
rows.and_then(Iterator::collect).map_err(failed)
}
pub(super) fn begins_a_word(connection: &Connection, asked: &Asked<'_>, prefix: &str) -> Result<bool> {
let Some(past) = past(prefix) else { return Ok(false) };
let failed = |error| sql_error("find a word a prefix begins", error);
let mut select = connection.prepare_cached(BEGINS_A_WORD).map_err(failed)?;
for field in &asked.settings.fields {
let part = Part::written(field.number);
if select.query_row((asked.index, part.0, prefix, &past), |row| row.get(0)).map_err(failed)? {
return Ok(true);
}
}
Ok(false)
}
fn past(prefix: &str) -> Option<String> {
let mut letters: Vec<char> = prefix.chars().collect();
while let Some(last) = letters.pop() {
if let Some(next) = (u32::from(last) + 1..=u32::from(char::MAX)).find_map(char::from_u32) {
letters.push(next);
return Some(letters.into_iter().collect());
}
}
None
}
fn push_held(list: &mut List, mut postings: Vec<Posting>, gone: &HashSet<u32>) {
postings.retain(|posting| !gone.contains(&posting.doc));
if !postings.is_empty() {
let block = list.in_hand(postings);
list.push(block);
}
}
fn head(connection: &Connection, index: i64, key: i64) -> Result<Vec<Posting>> {
let failed = |error| sql_error(format!("read key {key}'s head"), error);
let mut select = connection.prepare_cached(READ_HEAD).map_err(failed)?;
let rows =
select.query_map((index, key), |row| Ok(Posting { doc: row.get(0)?, tf: row.get(1)?, len: row.get(2)? }));
rows.and_then(Iterator::collect).map_err(failed)
}
fn hit(connection: &Connection, index: i64, doc: u32, score: f64) -> Result<(String, Vec<u8>, f64)> {
let failed = |error| sql_error(format!("read document {doc}"), error);
let mut select = connection.prepare_cached(READ_HIT).map_err(failed)?;
let found = select.query_row((index, doc), |row| Ok((row.get(0)?, row.get(1)?))).optional().map_err(failed)?;
let (id, value) = found.ok_or_else(|| Error::corrupt(format!("document {doc} a search found is not kept")))?;
Ok((id, value, score))
}
struct Source<'a> {
connection: &'a Connection,
asked: &'a Asked<'a>,
moment: Moment,
gone: &'a HashSet<u32>,
chunks: HashMap<(Part, u32), Arc<Chunk>>,
ahead: HashMap<(i64, usize), Vec<Posting>>,
}
impl Fetch for Source<'_> {
fn block(&mut self, list: &List, index: usize) -> Result<Vec<Posting>> {
if let Some(postings) = self.ahead.remove(&(list.key, index)) {
return Ok(postings);
}
let last = if list.in_order(index) { list.stored_after(index, AHEAD - 1) } else { index };
let payloads = self.payloads(list, index, last).map_err(|error| error.within(format!("key {}", list.key)))?;
let mut wanted = Vec::new();
for (offset, payload) in payloads.into_iter().enumerate() {
let postings = self.postings(list.part, &payload).map_err(|error| {
error.within(format!("key {}: block at document {}", list.key, list.first_of(index + offset)))
})?;
if offset == 0 {
wanted = postings;
} else {
self.ahead.insert((list.key, index + offset), postings);
}
}
Ok(wanted)
}
}
impl<'a> Source<'a> {
fn new(connection: &'a Connection, asked: &'a Asked<'a>, moment: Moment, stats: &'a Stats) -> Source<'a> {
Source { connection, asked, moment, gone: &stats.gone.docs, chunks: HashMap::new(), ahead: HashMap::new() }
}
fn payloads(&self, list: &List, index: usize, last: usize) -> Result<Vec<Vec<u8>>> {
let failed = |error| sql_error("read a block", error);
let missing =
|| Error::corrupt(format!("block at document {} its directory names is missing", list.first_of(index)));
if last == index {
let mut select = self.connection.prepare_cached(READ_BLOCK).map_err(failed)?;
let payload = select.query_row((list.key, list.first_of(index)), |row| row.get(0)).optional();
return Ok(vec![payload.map_err(failed)?.ok_or_else(missing)?]);
}
let mut select = self.connection.prepare_cached(READ_BLOCKS).map_err(failed)?;
let range = (list.key, list.first_of(index), list.first_of(last));
let rows = select.query_map(range, |row| Ok((row.get::<_, u32>(0)?, row.get::<_, Vec<u8>>(1)?)));
let rows: Vec<(u32, Vec<u8>)> = rows.and_then(Iterator::collect).map_err(failed)?;
let named = rows.iter().zip(index..=last).all(|((first, _), at)| *first == list.first_of(at));
if rows.len() != last - index + 1 || !named {
return Err(missing());
}
Ok(rows.into_iter().map(|(_, payload)| payload).collect())
}
fn postings(&mut self, part: Part, payload: &[u8]) -> Result<Vec<Posting>> {
let mut postings = Vec::with_capacity(super::postings::BLOCK);
let mut chunk: Option<(u32, Arc<Chunk>)> = None;
for (doc, tf) in unpack(payload)? {
if self.gone.contains(&doc) {
continue;
}
if chunk.as_ref().is_none_or(|(at, _)| *at != doc / NORMS) {
chunk = Some((doc / NORMS, self.chunk(part, doc / NORMS)?));
}
let len = chunk.as_ref().map_or(0, |(_, lengths)| lengths.length(doc));
postings.push(Posting { doc, tf, len });
}
Ok(postings)
}
fn chunk(&mut self, part: Part, chunk: u32) -> Result<Arc<Chunk>> {
if let Some(read) = self.chunks.get(&(part, chunk)) {
return Ok(Arc::clone(read));
}
let read = self.asked.kept.chunk(self.connection, self.asked.memory, self.moment, (part, chunk))?;
self.chunks.insert((part, chunk), Arc::clone(&read));
Ok(read)
}
}
#[cfg(test)]
mod tests {
use super::past;
#[test]
fn past_a_prefix_is_the_least_text_no_word_it_begins_reaches() {
assert_eq!(past("crypt").as_deref(), Some("crypu"));
assert_eq!(past("крипто").as_deref(), Some("криптп"));
assert_eq!(past("\u{d7ff}").as_deref(), Some("\u{e000}"));
assert_eq!(past("a\u{10ffff}").as_deref(), Some("b"));
assert_eq!(past("\u{10ffff}"), None);
let begun = ["crypt", "cryptography", "crypt\u{10ffff}"];
assert!(begun.iter().all(|word| *word < past("crypt").unwrap().as_str()));
}
}