use std::collections::{BTreeMap, BTreeSet};
#[cfg(test)]
use nibkeep_base::SpaceId;
use nibkeep_base::cbor;
#[cfg(test)]
use nibkeep_base::small::SmallSet;
use nibkeep_base::{EntityId, Hash, StatementId};
use nibkeep_log::{History, Log, SpaceState};
use nibkeep_model::storage::Statements;
use nibkeep_model::{FieldName, Operation, Statement, Value, fields};
use unicode_normalization::UnicodeNormalization;
use unicode_normalization::char::is_combining_mark;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Found {
pub entity: EntityId,
pub matching: usize,
}
const PREFIX_READ_FACTOR: usize = 4;
pub(crate) trait Postings {
type Error;
type Key: Copy + Ord;
fn indexed(&self, id: StatementId) -> Result<Option<Indexed>, Self::Error>;
fn insert(&self, id: StatementId, indexed: &Indexed) -> Result<(), Self::Error>;
fn remove(&self, id: StatementId) -> Result<(), Self::Error>;
fn clear(&self) -> Result<(), Self::Error>;
fn with_word(&self, word: &str) -> Result<Vec<(Self::Key, EntityId)>, Self::Error>;
fn word_count(&self, word: &str) -> Result<usize, Self::Error>;
fn with_prefix(&self, prefix: &str) -> Result<Vec<(Self::Key, EntityId)>, Self::Error>;
fn prefix_count(&self, prefix: &str, at_most: usize) -> Result<usize, Self::Error>;
fn shown_with_prefix(
&self,
entity: EntityId,
prefix: &str,
) -> Result<Vec<Self::Key>, Self::Error>;
fn with_value(&self, field: &FieldName, value: &Hash) -> Result<Vec<EntityId>, Self::Error>;
fn with_name(&self, lowered: &str) -> Result<Vec<EntityId>, Self::Error>;
fn of_shown(&self, entity: EntityId) -> Result<Vec<(StatementId, Indexed)>, Self::Error>;
fn set_deleted(&self, entity: EntityId, deleted: bool) -> Result<(), Self::Error>;
fn remove_field(&self, field: &FieldName) -> Result<(), Self::Error>;
}
#[derive(Default)]
struct Shown(BTreeMap<EntityId, (EntityId, bool)>);
impl Shown {
fn of<S: Statements>(
&mut self,
state: &SpaceState<S>,
entity: EntityId,
) -> Result<(EntityId, bool), S::Error> {
if let Some(&known) = self.0.get(&entity) {
return Ok(known);
}
let canonical = state.canonical(entity)?;
let known = (canonical, state.is_deleted(canonical)?);
self.0.insert(entity, known);
Ok(known)
}
}
#[derive(Clone, Copy)]
pub(crate) struct Fields<'a> {
pub(crate) secret: &'a BTreeSet<FieldName>,
pub(crate) last_writer_wins: &'a BTreeSet<FieldName>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Indexed {
pub(crate) entity: EntityId,
pub(crate) shown: EntityId,
pub(crate) deleted: bool,
pub(crate) words: Vec<String>,
pub(crate) name: Option<String>,
pub(crate) value: (FieldName, Hash),
}
#[derive(Default)]
struct LastWritten(BTreeMap<(EntityId, FieldName), Option<StatementId>>);
impl LastWritten {
fn of<S: Statements>(
&mut self,
state: &SpaceState<S>,
statement: &Statement,
) -> Result<Option<StatementId>, S::Error> {
let key = (state.canonical(statement.entity)?, statement.field.clone());
if let Some(written) = self.0.get(&key) {
return Ok(*written);
}
let written = state
.last_written(statement.entity, &statement.field)?
.map(|last| last.id);
self.0.insert(key, written);
Ok(written)
}
}
pub(crate) fn build<S, H, P>(
log: &Log<S, H>,
postings: &P,
fields: Fields<'_>,
) -> Result<(), S::Error>
where
S: Statements,
H: History<Error = S::Error>,
P: Postings<Error = S::Error>,
{
let state = log.state();
postings.clear()?;
let mut shown = Shown::default();
let mut last = LastWritten::default();
for statement in state.statements()? {
if fields.last_writer_wins.contains(&statement.field)
&& last.of(state, &statement)? != Some(statement.id)
{
continue;
}
add(log, postings, fields, &mut shown, &statement)?;
}
Ok(())
}
pub(crate) fn rebuild_fields<S, H, P>(
log: &Log<S, H>,
postings: &P,
was: Fields<'_>,
fields: Fields<'_>,
) -> Result<(), S::Error>
where
S: Statements,
H: History<Error = S::Error>,
P: Postings<Error = S::Error>,
{
let state = log.state();
let mut shown = Shown::default();
let mut last = LastWritten::default();
let changed: BTreeSet<&FieldName> = was
.secret
.symmetric_difference(fields.secret)
.chain(
was.last_writer_wins
.symmetric_difference(fields.last_writer_wins),
)
.collect();
for field in changed {
postings.remove_field(field)?;
if fields.secret.contains(field) {
continue;
}
let last_wins = fields.last_writer_wins.contains(field);
for recorded in state.storage().current_in_field(field)? {
let statement = &recorded.statement;
if last_wins && last.of(state, statement)? != Some(statement.id) {
continue;
}
add(log, postings, fields, &mut shown, statement)?;
}
}
Ok(())
}
#[derive(Default)]
struct Touched {
last_writer_wins: BTreeSet<(EntityId, FieldName)>,
deletions: BTreeSet<EntityId>,
merged: BTreeSet<EntityId>,
merged_into: BTreeSet<EntityId>,
merged_under: BTreeSet<EntityId>,
}
impl Touched {
fn field(
&mut self,
fields: Fields<'_>,
entity: EntityId,
field: &FieldName,
other: Option<EntityId>,
) {
if *field == fields::DELETED {
self.deletions.insert(entity);
}
if *field == fields::MERGED_INTO {
self.merged.insert(entity);
self.merged_into.extend(other);
}
if fields.last_writer_wins.contains(field) {
self.last_writer_wins.insert((entity, field.clone()));
}
}
fn statement(&mut self, fields: Fields<'_>, statement: &Statement) {
self.field(
fields,
statement.entity,
&statement.field,
statement.value.as_reference(),
);
}
fn indexed(&mut self, fields: Fields<'_>, indexed: &Indexed) {
self.field(fields, indexed.entity, &indexed.value.0, None);
if indexed.value.0 == fields::MERGED_INTO {
self.merged_under.insert(indexed.shown);
}
}
}
pub(crate) fn apply<'a, S, H, P>(
log: &Log<S, H>,
postings: &P,
fields: Fields<'_>,
operations: impl IntoIterator<Item = &'a Operation>,
) -> Result<(), S::Error>
where
S: Statements,
H: History<Error = S::Error>,
P: Postings<Error = S::Error>,
{
let state = log.state();
let mut shown = Shown::default();
let mut touched = Touched::default();
let mut fresh = BTreeSet::new();
for operation in operations {
match operation {
Operation::Assert {
statement,
supersedes,
..
} => {
touched.statement(fields, statement);
if let Some(kept) = state.statement(statement.id)? {
touched.statement(fields, &kept);
}
if let Some(indexed) = take_out(postings, statement.id)? {
touched.indexed(fields, &indexed);
}
if state.is_current(statement.id)?
&& let Some(current) = state.statement(statement.id)?
&& !fields.last_writer_wins.contains(¤t.field)
{
add(log, postings, fields, &mut shown, ¤t)?;
fresh.insert(current.id);
}
for id in supersedes {
if state.is_current(*id)? {
continue;
}
if let Some(superseded) = state.statement(*id)? {
touched.statement(fields, &superseded);
}
if let Some(indexed) = take_out(postings, *id)? {
touched.indexed(fields, &indexed);
}
}
}
Operation::Retract { statements, .. } | Operation::RetractSecret { statements } => {
for id in statements {
if state.is_current(*id)? {
continue;
}
if let Some(retracted) = state.statement(*id)? {
touched.statement(fields, &retracted);
}
if let Some(indexed) = take_out(postings, *id)? {
touched.indexed(fields, &indexed);
}
}
}
Operation::Unknown(_) => {}
}
}
if !touched.merged.is_empty()
&& !move_merged(log, postings, fields, &mut shown, &mut touched, &fresh)?
{
return build(log, postings, fields);
}
for entity in touched.deletions {
let entity = state.canonical(entity)?;
postings.set_deleted(entity, state.is_deleted(entity)?)?;
}
let mut pending: Vec<(EntityId, FieldName)> = touched.last_writer_wins.into_iter().collect();
let mut done = BTreeSet::new();
while let Some((entity, field)) = pending.pop() {
if !done.insert((state.canonical(entity)?, field.clone())) {
continue;
}
for statement in state.current(entity, &field)? {
if let Some(indexed) = postings.indexed(statement.id)? {
if indexed.entity != statement.entity || indexed.value.0 != statement.field {
return build(log, postings, fields);
}
if fields.last_writer_wins.contains(&indexed.value.0) {
pending.push((indexed.entity, indexed.value.0.clone()));
}
}
postings.remove(statement.id)?;
}
if let Some(last) = state.last_written(entity, &field)? {
add(log, postings, fields, &mut shown, &last)?;
}
}
Ok(())
}
fn move_merged<S, H, P>(
log: &Log<S, H>,
postings: &P,
fields: Fields<'_>,
shown: &mut Shown,
touched: &mut Touched,
fresh: &BTreeSet<StatementId>,
) -> Result<bool, S::Error>
where
S: Statements,
H: History<Error = S::Error>,
P: Postings<Error = S::Error>,
{
let state = log.state();
let Touched {
merged,
merged_into,
merged_under,
last_writer_wins,
..
} = touched;
let mut candidates = BTreeSet::new();
let mut under = merged_under.clone();
for &entity in merged.iter() {
candidates.insert(entity);
under.insert(entity);
for (field, ids) in state.storage().of_entity(entity)? {
for id in ids {
if fresh.contains(&id) {
continue;
}
if let Some(indexed) = postings.indexed(id)? {
if indexed.entity != entity || indexed.value.0 != field {
return Ok(false);
}
under.insert(indexed.shown);
}
}
}
}
for &shown_under in &under {
for (_, indexed) in postings.of_shown(shown_under)? {
if shown.of(state, indexed.entity)?.0 != shown_under {
candidates.insert(indexed.entity);
}
}
}
let mut lww_fields = BTreeSet::new();
for candidate in candidates {
let (canonical, deleted) = shown.of(state, candidate)?;
for (field, ids) in state.storage().of_entity(candidate)? {
let last_wins = fields.last_writer_wins.contains(&field);
if last_wins {
last_writer_wins.insert((candidate, field.clone()));
lww_fields.insert(field.clone());
}
for id in ids {
if fresh.contains(&id) {
continue;
}
let Some(indexed) = postings.indexed(id)? else {
continue;
};
if indexed.entity != candidate || indexed.value.0 != field {
return Ok(false);
}
if indexed.shown == canonical && indexed.deleted == deleted {
continue;
}
postings.remove(id)?;
if last_wins {
continue;
}
if state.is_current(id)?
&& let Some(statement) = state.statement(id)?
{
add(log, postings, fields, shown, &statement)?;
}
}
}
}
for &entity in merged_into.iter().chain(under.iter()) {
for field in &lww_fields {
last_writer_wins.insert((entity, field.clone()));
}
}
Ok(true)
}
pub(crate) fn search<P: Postings>(postings: &P, query: &str) -> Result<Vec<Found>, P::Error> {
let words = words(query);
let Some(last) = words.len().checked_sub(1) else {
return Ok(Vec::new());
};
let mut counts = Vec::new();
for word in &words[..last] {
counts.push((postings.word_count(word)?, Some(word.as_str())));
}
let prefix_read = match counts.iter().map(|(count, _)| *count).min() {
None => {
counts.push((0, None));
true
}
Some(rarest) => {
let most = rarest.saturating_mul(PREFIX_READ_FACTOR);
let beginning = postings.prefix_count(&words[last], most.saturating_add(1))?;
let read = beginning <= most;
if read {
counts.push((beginning, None));
}
read
}
};
counts.sort_by_key(|(count, _)| *count);
let mut candidates: Option<BTreeMap<EntityId, BTreeSet<P::Key>>> = None;
for (_, word) in counts {
let held = match word {
Some(word) => postings.with_word(word)?,
None => postings.with_prefix(&words[last])?,
};
let mut holding: BTreeMap<EntityId, BTreeSet<P::Key>> = BTreeMap::new();
for (statement, entity) in held {
if candidates
.as_ref()
.is_none_or(|known| known.contains_key(&entity))
{
holding.entry(entity).or_default().insert(statement);
}
}
if let Some(known) = candidates {
for (entity, statements) in &mut holding {
statements.extend(&known[entity]);
}
}
if holding.is_empty() {
return Ok(Vec::new());
}
candidates = Some(holding);
}
let mut found = Vec::new();
for (entity, mut statements) in candidates.unwrap_or_default() {
if !prefix_read {
let holding = postings.shown_with_prefix(entity, &words[last])?;
if holding.is_empty() {
continue;
}
statements.extend(holding);
}
found.push(Found {
entity,
matching: statements.len(),
});
}
found.sort_by(|a, b| b.matching.cmp(&a.matching).then(a.entity.cmp(&b.entity)));
Ok(found)
}
pub(crate) fn find<P: Postings>(
postings: &P,
field: &FieldName,
value: &Value,
) -> Result<Vec<EntityId>, P::Error> {
let entities: BTreeSet<EntityId> = postings
.with_value(field, &Hash::of(&cbor::to_vec(value)))?
.into_iter()
.collect();
Ok(entities.into_iter().collect())
}
fn take_out<P: Postings>(postings: &P, id: StatementId) -> Result<Option<Indexed>, P::Error> {
let indexed = postings.indexed(id)?;
if indexed.is_some() {
postings.remove(id)?;
}
Ok(indexed)
}
fn add<S, H, P>(
log: &Log<S, H>,
postings: &P,
fields: Fields<'_>,
shown: &mut Shown,
statement: &Statement,
) -> Result<(), P::Error>
where
S: Statements,
H: History<Error = S::Error>,
P: Postings<Error = S::Error>,
{
if fields.secret.contains(&statement.field) || log.is_sealed(statement.id)? {
return Ok(());
}
let mut words: Vec<String> = if fields::has_words(&statement.field) {
statement
.value
.searchable_texts()
.into_iter()
.flat_map(self::words)
.collect()
} else {
Vec::new()
};
words.sort_unstable();
words.dedup();
let name = fields::name_key(&statement.field, &statement.value);
let (shown_under, deleted) = shown.of(log.state(), statement.entity)?;
postings.insert(
statement.id,
&Indexed {
entity: statement.entity,
shown: shown_under,
deleted,
words,
name,
value: (
statement.field.clone(),
Hash::of(&cbor::to_vec(&statement.value)),
),
},
)
}
#[cfg(test)]
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct MemoryPostings(std::cell::RefCell<Maps>);
#[cfg(test)]
#[derive(Debug, Default)]
struct Maps {
words: BTreeMap<String, SmallSet<StatementId>>,
values: BTreeMap<(FieldName, Hash), SmallSet<StatementId>>,
shown: BTreeMap<EntityId, SmallSet<StatementId>>,
names: BTreeMap<String, SmallSet<StatementId>>,
indexed: BTreeMap<StatementId, Indexed>,
touched: BTreeSet<StatementId>,
cleared: usize,
}
#[cfg(test)]
impl PartialEq for Maps {
fn eq(&self, other: &Self) -> bool {
self.words == other.words
&& self.values == other.values
&& self.shown == other.shown
&& self.names == other.names
&& self.indexed == other.indexed
}
}
#[cfg(test)]
impl Eq for Maps {}
#[cfg(test)]
impl Postings for MemoryPostings {
type Error = std::convert::Infallible;
type Key = StatementId;
fn indexed(&self, id: StatementId) -> Result<Option<Indexed>, Self::Error> {
Ok(self.0.borrow().indexed.get(&id).cloned())
}
fn insert(&self, id: StatementId, indexed: &Indexed) -> Result<(), Self::Error> {
Postings::remove(self, id)?;
let mut maps = self.0.borrow_mut();
maps.touched.insert(id);
for word in &indexed.words {
maps.words.entry(word.clone()).or_default().insert(id);
}
maps.values
.entry(indexed.value.clone())
.or_default()
.insert(id);
maps.shown.entry(indexed.shown).or_default().insert(id);
if let Some(name) = &indexed.name {
maps.names.entry(name.clone()).or_default().insert(id);
}
maps.indexed.insert(id, indexed.clone());
Ok(())
}
fn remove(&self, id: StatementId) -> Result<(), Self::Error> {
let mut maps = self.0.borrow_mut();
let Some(indexed) = maps.indexed.remove(&id) else {
return Ok(());
};
maps.touched.insert(id);
for word in &indexed.words {
remove_from(&mut maps.words, word, id);
}
remove_from(&mut maps.values, &indexed.value, id);
remove_from(&mut maps.shown, &indexed.shown, id);
if let Some(name) = &indexed.name {
remove_from(&mut maps.names, name, id);
}
Ok(())
}
fn clear(&self) -> Result<(), Self::Error> {
let mut maps = self.0.borrow_mut();
*maps = Maps {
touched: std::mem::take(&mut maps.touched),
cleared: maps.cleared + 1,
..Maps::default()
};
Ok(())
}
fn with_word(&self, word: &str) -> Result<Vec<(Self::Key, EntityId)>, Self::Error> {
let maps = self.0.borrow();
Ok(maps
.words
.get(word)
.into_iter()
.flatten()
.filter(|id| !maps.indexed[id].deleted)
.map(|id| (*id, maps.indexed[id].shown))
.collect())
}
fn word_count(&self, word: &str) -> Result<usize, Self::Error> {
Ok(self.0.borrow().words.get(word).map_or(0, SmallSet::len))
}
fn with_prefix(&self, prefix: &str) -> Result<Vec<(Self::Key, EntityId)>, Self::Error> {
let maps = self.0.borrow();
let ids: BTreeSet<StatementId> = maps
.words
.range(prefix.to_owned()..)
.take_while(|(word, _)| word.starts_with(prefix))
.flat_map(|(_, ids)| ids.iter().copied())
.collect();
Ok(ids
.into_iter()
.filter(|id| !maps.indexed[id].deleted)
.map(|id| (id, maps.indexed[&id].shown))
.collect())
}
fn prefix_count(&self, prefix: &str, at_most: usize) -> Result<usize, Self::Error> {
let count: usize = self
.0
.borrow()
.words
.range(prefix.to_owned()..)
.take_while(|(word, _)| word.starts_with(prefix))
.map(|(_, ids)| ids.len())
.sum();
Ok(count.min(at_most))
}
fn shown_with_prefix(
&self,
entity: EntityId,
prefix: &str,
) -> Result<Vec<Self::Key>, Self::Error> {
let maps = self.0.borrow();
Ok(maps
.shown
.get(&entity)
.into_iter()
.flatten()
.filter(|id| {
maps.indexed[id]
.words
.iter()
.any(|word| word.starts_with(prefix))
})
.copied()
.collect())
}
fn with_value(&self, field: &FieldName, value: &Hash) -> Result<Vec<EntityId>, Self::Error> {
let maps = self.0.borrow();
Ok(maps
.values
.get(&(field.clone(), *value))
.into_iter()
.flatten()
.filter(|id| !maps.indexed[id].deleted)
.map(|id| maps.indexed[id].shown)
.collect())
}
fn with_name(&self, lowered: &str) -> Result<Vec<EntityId>, Self::Error> {
let maps = self.0.borrow();
let entities: BTreeSet<EntityId> = maps
.names
.get(lowered)
.into_iter()
.flatten()
.map(|id| maps.indexed[id].shown)
.collect();
Ok(entities.into_iter().collect())
}
fn of_shown(&self, entity: EntityId) -> Result<Vec<(StatementId, Indexed)>, Self::Error> {
let maps = self.0.borrow();
Ok(maps
.shown
.get(&entity)
.into_iter()
.flatten()
.map(|id| (*id, maps.indexed[id].clone()))
.collect())
}
fn remove_field(&self, field: &FieldName) -> Result<(), Self::Error> {
let ids: Vec<StatementId> = self
.0
.borrow()
.indexed
.iter()
.filter(|(_, indexed)| indexed.value.0 == *field)
.map(|(id, _)| *id)
.collect();
for id in ids {
self.remove(id)?;
}
Ok(())
}
fn set_deleted(&self, entity: EntityId, deleted: bool) -> Result<(), Self::Error> {
let mut maps = self.0.borrow_mut();
let ids: Vec<StatementId> = maps
.shown
.get(&entity)
.into_iter()
.flatten()
.copied()
.collect();
for id in ids {
if let Some(indexed) = maps.indexed.get_mut(&id) {
indexed.deleted = deleted;
}
}
Ok(())
}
}
#[cfg(test)]
fn remove_from<K: Ord>(map: &mut BTreeMap<K, SmallSet<StatementId>>, key: &K, id: StatementId) {
if let Some(ids) = map.get_mut(key) {
ids.remove(&id);
if ids.is_empty() {
map.remove(key);
}
}
}
#[must_use]
pub fn holds_words(text: &str, query: &str) -> bool {
let wanted = words(query);
let Some((last, whole)) = wanted.split_last() else {
return false;
};
let held = words(text);
whole.iter().all(|word| held.contains(word))
&& held.iter().any(|word| word.starts_with(last.as_str()))
}
fn words(text: &str) -> Vec<String> {
let folded: String = text
.nfkd()
.flat_map(char::to_lowercase)
.collect::<String>()
.nfkd()
.filter(|&character| !is_combining_mark(character))
.collect();
folded
.split(|character: char| !character.is_alphanumeric())
.filter(|word| !word.is_empty())
.map(str::to_owned)
.collect()
}
#[cfg(test)]
mod tests {
use std::fs;
use nibkeep_crypto::SigningKey;
use nibkeep_log::{Log, Parcel, Received, SpaceKeys};
use nibkeep_model::storage::Infallibly;
use nibkeep_testkit::{TestRng, millis_at};
use nibkeep_time::Clock;
use proptest::prelude::*;
use super::*;
use crate::StateFile;
const DRIFT: u64 = 3_600_000;
const WORDS: [&str; 6] = ["ada", "adam", "lovelace", "Café", "cafe", "zoë"];
#[derive(Clone, Debug)]
enum Step {
Assert {
writer: usize,
entity: usize,
field: usize,
words: Vec<usize>,
replaces: Vec<usize>,
reuses: Option<usize>,
},
Retract {
writer: usize,
statements: Vec<usize>,
},
Merge {
writer: usize,
entity: usize,
into: usize,
},
Delete { writer: usize, entity: usize },
}
fn step() -> impl Strategy<Value = Step> {
prop_oneof![
6 => (
0..3_usize,
0..3_usize,
0..2_usize,
prop::collection::vec(0..WORDS.len(), 1..3),
prop::collection::vec(0..16_usize, 0..2),
prop::option::weighted(0.1, 0..16_usize),
)
.prop_map(|(writer, entity, field, words, replaces, reuses)| Step::Assert {
writer,
entity,
field,
words,
replaces,
reuses,
}),
2 => (0..3_usize, prop::collection::vec(0..16_usize, 1..3))
.prop_map(|(writer, statements)| Step::Retract { writer, statements }),
1 => (0..3_usize, 0..3_usize, 0..3_usize)
.prop_map(|(writer, entity, into)| Step::Merge { writer, entity, into }),
1 => (0..3_usize, 0..3_usize)
.prop_map(|(writer, entity)| Step::Delete { writer, entity }),
]
}
fn shuffle(changes: &mut [Parcel], mut seed: u64) {
for last in (1..changes.len()).rev() {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
let other = usize::try_from(seed % (last as u64 + 1)).expect("small");
changes.swap(last, other);
}
}
fn every_statement(state: &SpaceState, fields: Fields<'_>, query: &str) -> Vec<Found> {
let words = words(query);
let Some(last) = words.len().checked_sub(1) else {
return Vec::new();
};
let mut entities: BTreeMap<EntityId, (Vec<bool>, BTreeSet<StatementId>)> = BTreeMap::new();
for statement in state.statements().infallible() {
let Value::Text(text) = &statement.value else {
continue;
};
if fields::is_reserved(&statement.field) {
continue;
}
if fields.last_writer_wins.contains(&statement.field)
&& state
.last_written(statement.entity, &statement.field)
.infallible()
.is_none_or(|last| last.id != statement.id)
{
continue;
}
let held = self::words(text);
let (matched, statements) = entities
.entry(state.canonical(statement.entity).infallible())
.or_insert_with(|| (vec![false; words.len()], BTreeSet::new()));
for (index, word) in words.iter().enumerate() {
if held
.iter()
.any(|held| held == word || (index == last && held.starts_with(word.as_str())))
{
matched[index] = true;
statements.insert(statement.id);
}
}
}
let mut found: Vec<Found> = entities
.into_iter()
.filter(|(entity, (matched, _))| {
matched.iter().all(|&matched| matched) && !state.is_deleted(*entity).infallible()
})
.map(|(entity, (_, statements))| Found {
entity,
matching: statements.len(),
})
.collect();
found.sort_by(|a, b| b.matching.cmp(&a.matching).then(a.entity.cmp(&b.entity)));
found
}
fn every_name(state: &SpaceState, fields: Fields<'_>, lowered: &str) -> Vec<EntityId> {
let mut named = BTreeSet::new();
for statement in state.statements().infallible() {
if fields::name_key(&statement.field, &statement.value).as_deref() == Some(lowered)
&& (!fields.last_writer_wins.contains(&statement.field)
|| state
.last_written(statement.entity, &statement.field)
.infallible()
.is_some_and(|last| last.id == statement.id))
{
named.insert(state.canonical(statement.entity).infallible());
}
}
named.into_iter().collect()
}
struct Writer {
log: Log,
author: SigningKey,
keys: SpaceKeys,
wall: u64,
rng: TestRng,
}
impl Writer {
fn new(name: &str) -> Self {
let mut rng = TestRng::new(name);
Self {
log: Log::new(rng.space_id(), Clock::new(DRIFT)),
author: rng.signing_key(),
keys: SpaceKeys::new(0, rng.key()),
wall: millis_at("2026-10-12", 10, 0),
rng,
}
}
fn statement(&mut self, entity: EntityId, field: &FieldName, value: Value) -> Statement {
Statement::new(self.rng.statement_id(), entity, field.clone(), value)
}
fn commit<P: Postings<Error = std::convert::Infallible>>(
&mut self,
postings: &P,
fields: Fields<'_>,
operation: Operation,
) {
self.wall += 1_000;
self.log
.commit(
&self.author,
&self.keys,
vec![operation],
self.wall,
&mut self.rng,
)
.expect("commits");
for (_, payload) in self.log.take_applied() {
apply(&self.log, postings, fields, payload.all_operations()).infallible();
}
}
}
#[test]
fn a_merge_moves_only_the_statements_of_the_entity_merged() {
let mut writer = Writer::new("a merge moves statements");
let title: FieldName = "org.nibkeep.title".parse().expect("a field name");
let (secret, last_writer_wins) = (BTreeSet::new(), BTreeSet::new());
let fields = Fields {
secret: &secret,
last_writer_wins: &last_writer_wins,
};
let index = MemoryPostings::default();
let [apart, from, into] = [
writer.rng.entity_id(),
writer.rng.entity_id(),
writer.rng.entity_id(),
];
let mut titles = BTreeMap::new();
for (entity, text) in [(apart, "Zoë"), (from, "Ada"), (into, "Lovelace")] {
let statement = writer.statement(entity, &title, Value::Text(text.to_owned()));
titles.insert(entity, statement.id);
writer.commit(&index, fields, Operation::assert(statement));
}
index.0.borrow_mut().touched.clear();
let merge = writer.statement(from, &fields::MERGED_INTO, Value::Reference(into));
let merged = merge.id;
writer.commit(&index, fields, Operation::assert(merge));
{
let maps = index.0.borrow();
assert_eq!(maps.cleared, 0, "nothing is built anew");
assert!(maps.touched.contains(&titles[&from]) && maps.touched.contains(&merged));
assert!(
!maps.touched.contains(&titles[&into]) && !maps.touched.contains(&titles[&apart]),
"the entity merged into, and an entity apart, are left alone"
);
}
let built = MemoryPostings::default();
build(&writer.log, &built, fields).infallible();
assert_eq!(index, built);
assert_eq!(
search(&index, "ada").infallible(),
vec![Found {
entity: into,
matching: 1,
}]
);
}
#[test]
fn a_merge_shows_the_value_written_last_among_the_entities_merged() {
let mut writer = Writer::new("a merge and the last writer");
let title: FieldName = "org.nibkeep.title".parse().expect("a field name");
let secret = BTreeSet::new();
let last_writer_wins = BTreeSet::from([title.clone()]);
let fields = Fields {
secret: &secret,
last_writer_wins: &last_writer_wins,
};
let index = MemoryPostings::default();
let [from, into] = [writer.rng.entity_id(), writer.rng.entity_id()];
let mut titles = BTreeMap::new();
for (entity, text) in [(from, "Ada"), (into, "Lovelace")] {
let statement = writer.statement(entity, &title, Value::Text(text.to_owned()));
titles.insert(entity, statement.id);
writer.commit(&index, fields, Operation::assert(statement));
}
let merge = writer.statement(from, &fields::MERGED_INTO, Value::Reference(into));
let merged = merge.id;
writer.commit(&index, fields, Operation::assert(merge));
let built = MemoryPostings::default();
build(&writer.log, &built, fields).infallible();
assert_eq!(index, built);
nibkeep_testkit::assert_empty!(search(&index, "ada").infallible());
assert_eq!(
search(&index, "lovelace").infallible(),
vec![Found {
entity: into,
matching: 1,
}]
);
writer.commit(&index, fields, Operation::retract(from, [merged]));
let built = MemoryPostings::default();
build(&writer.log, &built, fields).infallible();
assert_eq!(index, built);
assert_eq!(
search(&index, "ada").infallible(),
vec![Found {
entity: from,
matching: 1,
}]
);
}
#[derive(Default)]
struct Counting {
postings: MemoryPostings,
prefixes_read: std::cell::Cell<usize>,
candidates_checked: std::cell::Cell<usize>,
}
impl Postings for Counting {
type Error = std::convert::Infallible;
type Key = StatementId;
fn indexed(&self, id: StatementId) -> Result<Option<Indexed>, Self::Error> {
self.postings.indexed(id)
}
fn insert(&self, id: StatementId, indexed: &Indexed) -> Result<(), Self::Error> {
self.postings.insert(id, indexed)
}
fn remove(&self, id: StatementId) -> Result<(), Self::Error> {
self.postings.remove(id)
}
fn clear(&self) -> Result<(), Self::Error> {
self.postings.clear()
}
fn with_word(&self, word: &str) -> Result<Vec<(StatementId, EntityId)>, Self::Error> {
self.postings.with_word(word)
}
fn word_count(&self, word: &str) -> Result<usize, Self::Error> {
self.postings.word_count(word)
}
fn with_prefix(&self, prefix: &str) -> Result<Vec<(StatementId, EntityId)>, Self::Error> {
self.prefixes_read.set(self.prefixes_read.get() + 1);
self.postings.with_prefix(prefix)
}
fn prefix_count(&self, prefix: &str, at_most: usize) -> Result<usize, Self::Error> {
self.postings.prefix_count(prefix, at_most)
}
fn shown_with_prefix(
&self,
entity: EntityId,
prefix: &str,
) -> Result<Vec<StatementId>, Self::Error> {
self.candidates_checked
.set(self.candidates_checked.get() + 1);
self.postings.shown_with_prefix(entity, prefix)
}
fn with_value(
&self,
field: &FieldName,
value: &Hash,
) -> Result<Vec<EntityId>, Self::Error> {
self.postings.with_value(field, value)
}
fn with_name(&self, lowered: &str) -> Result<Vec<EntityId>, Self::Error> {
self.postings.with_name(lowered)
}
fn of_shown(&self, entity: EntityId) -> Result<Vec<(StatementId, Indexed)>, Self::Error> {
self.postings.of_shown(entity)
}
fn set_deleted(&self, entity: EntityId, deleted: bool) -> Result<(), Self::Error> {
self.postings.set_deleted(entity, deleted)
}
fn remove_field(&self, field: &FieldName) -> Result<(), Self::Error> {
self.postings.remove_field(field)
}
}
#[test]
fn the_last_word_is_read_unless_it_starts_many_more_statements_than_the_rarest_word() {
let mut writer = Writer::new("the last word is read");
let title: FieldName = "org.nibkeep.title".parse().expect("a field name");
let (secret, last_writer_wins) = (BTreeSet::new(), BTreeSet::new());
let fields = Fields {
secret: &secret,
last_writer_wins: &last_writer_wins,
};
let index = Counting::default();
let texts = ["Ada Lovelace", "Lovelace"]
.into_iter()
.chain(std::iter::repeat_n("Adam", 3))
.chain(std::iter::repeat_n("Adler", 10));
for text in texts {
let entity = writer.rng.entity_id();
let statement = writer.statement(entity, &title, Value::Text(text.to_owned()));
writer.commit(&index, fields, Operation::assert(statement));
}
for (query, read) in [("lovelace ada", true), ("lovelace ad", false)] {
index.prefixes_read.set(0);
index.candidates_checked.set(0);
let found = search(&index, query).infallible();
assert_eq!(found, every_statement(writer.log.state(), fields, query));
assert_eq!(found.len(), 1, "{query}");
assert_eq!(index.prefixes_read.get(), usize::from(read), "{query}");
assert_eq!(
index.candidates_checked.get(),
if read { 0 } else { 2 },
"{query}: each entity that holds the whole word is checked"
);
}
}
#[test]
fn a_text_holds_the_words_of_a_query_the_last_as_a_beginning() {
let path = "/home/anna/Pictures/Été 2019/IMG_0042.JPG on Anna's laptop";
assert!(holds_words(path, "ete img_0042"));
assert!(holds_words(path, "pictures 2019 lap"));
assert!(holds_words(path, "anna"));
assert!(!holds_words(path, "pict 2019"));
assert!(!holds_words(path, "pictures phone"));
assert!(!holds_words(path, " ,. "));
}
#[test]
fn words_are_compared_without_case_or_accents() {
assert_eq!(words("Café Bleu, ZOË"), ["cafe", "bleu", "zoe"]);
assert_eq!(words("Radio 5㎒ İstanbul"), ["radio", "5mhz", "istanbul"]);
assert_eq!(words("netflix.com/ada"), ["netflix", "com", "ada"]);
nibkeep_testkit::assert_empty!(words(" -- "));
}
fn differences(index: &MemoryPostings, built: &MemoryPostings) -> String {
use std::fmt::Write as _;
let (index, built) = (index.0.borrow(), built.0.borrow());
let mut report = String::new();
for id in index
.indexed
.keys()
.chain(built.indexed.keys())
.collect::<BTreeSet<_>>()
{
let (kept, expected) = (index.indexed.get(id), built.indexed.get(id));
if kept != expected {
let _ = write!(report, "\n{id}: indexed as {kept:?}, built as {expected:?}");
}
}
report
}
fn read(
log: &mut Log,
index: &MemoryPostings,
fields: Fields<'_>,
keys: &SpaceKeys,
changes: Vec<Parcel>,
wall: u64,
) {
for change in changes {
let received = log.receive(change, keys, wall).expect("accepts");
if let Received::Accepted(_) = received {
for (_, payload) in log.take_applied() {
apply(log, index, fields, payload.all_operations()).infallible();
}
let built = MemoryPostings::default();
build(log, &built, fields).infallible();
assert!(
*index == built,
"the index follows the log{}",
differences(index, &built)
);
}
}
}
fn written(
steps: Vec<Step>,
space: SpaceId,
keys: &SpaceKeys,
entities: &[EntityId],
rng: &mut TestRng,
) -> (Vec<Parcel>, u64) {
let title: FieldName = "org.nibkeep.title".parse().expect("a field name");
let tag: FieldName = "org.nibkeep.tag".parse().expect("a field name");
let mut writers: Vec<(SigningKey, Log)> = (0..3)
.map(|_| (rng.signing_key(), Log::new(space, Clock::new(DRIFT))))
.collect();
let mut wall = millis_at("2026-10-12", 10, 0);
let mut asserted: Vec<StatementId> = Vec::new();
let mut of_entity: BTreeMap<StatementId, EntityId> = BTreeMap::new();
let mut changes = Vec::new();
for step in steps {
let (writer, operation) = match step {
Step::Assert {
writer,
entity,
field,
words,
replaces,
reuses,
} => {
let text: Vec<&str> = words.iter().map(|&word| WORDS[word]).collect();
let replaced: Vec<StatementId> = replaces
.iter()
.filter_map(|&index| asserted.get(index).copied())
.collect();
let id = match reuses.and_then(|index| asserted.get(index)) {
Some(&id) => id,
None => rng.statement_id(),
};
asserted.push(id);
of_entity.insert(id, entities[entity]);
let statement = Statement::new(
id,
entities[entity],
if field == 0 {
title.clone()
} else {
tag.clone()
},
Value::Text(text.join(" ")),
);
(writer, Operation::replace(statement, replaced))
}
Step::Merge {
writer,
entity,
into,
} => {
let id = rng.statement_id();
asserted.push(id);
of_entity.insert(id, entities[entity]);
let statement = Statement::new(
id,
entities[entity],
fields::MERGED_INTO,
Value::Reference(entities[into]),
);
(writer, Operation::assert(statement))
}
Step::Delete { writer, entity } => {
let id = rng.statement_id();
asserted.push(id);
of_entity.insert(id, entities[entity]);
let statement =
Statement::new(id, entities[entity], fields::DELETED, Value::Boolean(true));
(writer, Operation::assert(statement))
}
Step::Retract { writer, statements } => {
let ids: Vec<StatementId> = statements
.iter()
.filter_map(|&index| asserted.get(index).copied())
.collect();
let entity = ids
.first()
.and_then(|id| of_entity.get(id))
.copied()
.unwrap_or(entities[0]);
(writer, Operation::retract(entity, ids))
}
};
wall += 1_000;
let (author, log) = &mut writers[writer];
if let Ok(change) = log.commit(author, keys, vec![operation], wall, rng) {
changes.push(change);
}
}
(changes, wall)
}
fn follows(steps: Vec<Step>, seed: u64, last_writer_wins: bool) -> Result<(), TestCaseError> {
let mut rng = TestRng::new("the index follows changes");
let space = rng.space_id();
let keys = SpaceKeys::new(0, rng.key());
let entities: Vec<EntityId> = (0..3).map(|_| rng.entity_id()).collect();
let secret = BTreeSet::new();
let last_writer_wins: BTreeSet<FieldName> = last_writer_wins
.then(|| "org.nibkeep.title".parse().expect("a field name"))
.into_iter()
.collect();
let fields = Fields {
secret: &secret,
last_writer_wins: &last_writer_wins,
};
let (changes, wall) = written(steps, space, &keys, &entities, &mut rng);
let mut in_order = (
Log::new(space, Clock::new(DRIFT)),
MemoryPostings::default(),
);
read(
&mut in_order.0,
&in_order.1,
fields,
&keys,
changes.clone(),
wall,
);
let for_state_file = changes.clone();
let mut shuffled = changes;
shuffle(&mut shuffled, seed);
let mut out_of_order = (
Log::new(space, Clock::new(DRIFT)),
MemoryPostings::default(),
);
read(
&mut out_of_order.0,
&out_of_order.1,
fields,
&keys,
shuffled,
wall,
);
let built = MemoryPostings::default();
build(&in_order.0, &built, fields).infallible();
prop_assert_eq!(&in_order.1, &built);
prop_assert_eq!(&out_of_order.1, &built);
for query in [
"ada",
"ad",
"cafe",
"zoe lovelace",
"CAF",
"ada a",
"lovelace ad",
] {
let expected = every_statement(in_order.0.state(), fields, query);
prop_assert_eq!(search(&in_order.1, query).infallible(), expected.clone());
prop_assert_eq!(search(&out_of_order.1, query).infallible(), expected);
}
for name in ["ada", "ada lovelace", "café", "cafe zoë", "lovelace ada"] {
let expected = every_name(in_order.0.state(), fields, name);
prop_assert_eq!(in_order.1.with_name(name).infallible(), expected.clone());
prop_assert_eq!(out_of_order.1.with_name(name).infallible(), expected);
}
let received = (space, &keys, for_state_file, wall);
same_postings(received, &built, fields, &entities)
}
fn numbered<T: Ord>(state: &StateFile, found: Vec<(StatementId, T)>) -> Vec<(i64, T)> {
sorted(
found
.into_iter()
.map(|(id, value)| {
let number = state.statement_number(id).expect("reads");
(number.expect("held"), value)
})
.collect(),
)
}
fn sorted<T: Ord>(mut found: Vec<T>) -> Vec<T> {
found.sort();
found
}
static STATE_FILES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
fn same_postings(
(space, keys, changes, wall): (SpaceId, &SpaceKeys, Vec<Parcel>, u64),
built: &MemoryPostings,
fields: Fields<'_>,
entities: &[EntityId],
) -> Result<(), TestCaseError> {
let case = STATE_FILES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let directory = nibkeep_testkit::empty_directory(
std::env::temp_dir(),
&format!("nibkeep-index-state-file-{}-{case}", std::process::id()),
);
let mut rng = TestRng::new("an index in a state file");
let state = StateFile::open(&directory.join("state"), &rng.key(), rng).expect("opens");
let mut log = Log::with_storage(space, Clock::new(DRIFT), state);
log.storage_mut().begin().expect("begins");
for change in changes {
log.receive(change, keys, wall).expect("accepts");
let _ = log.take_applied();
}
let postings = log.state().storage().ordinary();
build(&log, postings, fields).expect("builds");
let checked = (|| {
for query in ["ada", "ad", "cafe", "zoe lovelace", "CAF", "ada a"] {
prop_assert_eq!(
search(postings, query).expect("searches"),
search(built, query).infallible()
);
}
for name in ["ada", "ada lovelace", "café", "lovelace ada"] {
prop_assert_eq!(
postings.with_name(name).expect("finds"),
built.with_name(name).infallible()
);
}
for word in WORDS.iter().flat_map(|word| words(word)) {
prop_assert_eq!(
sorted(postings.with_word(&word).expect("finds")),
numbered(postings, built.with_word(&word).infallible())
);
}
for prefix in ["a", "ad", "caf", "zoe", "lovelaces", ""] {
prop_assert_eq!(
sorted(postings.with_prefix(prefix).expect("finds")),
numbered(postings, built.with_prefix(prefix).infallible())
);
for at_most in [0, 1, 3, usize::MAX] {
prop_assert_eq!(
postings.prefix_count(prefix, at_most).expect("counts"),
built.prefix_count(prefix, at_most).infallible()
);
}
}
for &entity in entities {
for prefix in ["a", "ad", "caf", "zoe", "lovelaces", ""] {
let shown = |found: Vec<StatementId>| found.into_iter().map(|id| (id, ()));
prop_assert_eq!(
sorted(postings.shown_with_prefix(entity, prefix).expect("finds")),
numbered(
postings,
shown(built.shown_with_prefix(entity, prefix).infallible()).collect()
)
.into_iter()
.map(|(number, ())| number)
.collect::<Vec<_>>()
);
}
let sorted = |mut found: Vec<(StatementId, Indexed)>| {
found.sort_by_key(|(id, _)| *id);
found
};
prop_assert_eq!(
sorted(postings.of_shown(entity).expect("finds")),
sorted(built.of_shown(entity).infallible())
);
}
Ok(())
})();
drop(log);
let _ = fs::remove_dir_all(directory);
checked
}
fn special(title_wins: bool, tag_secret: bool) -> (BTreeSet<FieldName>, BTreeSet<FieldName>) {
let title: FieldName = "org.nibkeep.title".parse().expect("a field name");
let tag: FieldName = "org.nibkeep.tag".parse().expect("a field name");
(
tag_secret.then_some(tag).into_iter().collect(),
title_wins.then_some(title).into_iter().collect(),
)
}
fn follows_fields(
steps: Vec<Step>,
(was_wins, was_secret): (bool, bool),
(now_wins, now_secret): (bool, bool),
) -> Result<(), TestCaseError> {
let mut rng = TestRng::new("the indexes follow the fields");
let space = rng.space_id();
let keys = SpaceKeys::new(0, rng.key());
let entities: Vec<EntityId> = (0..3).map(|_| rng.entity_id()).collect();
let (was, now) = (special(was_wins, was_secret), special(now_wins, now_secret));
let was = Fields {
secret: &was.0,
last_writer_wins: &was.1,
};
let now = Fields {
secret: &now.0,
last_writer_wins: &now.1,
};
let (changes, wall) = written(steps, space, &keys, &entities, &mut rng);
let mut log = Log::new(space, Clock::new(DRIFT));
let index = MemoryPostings::default();
read(&mut log, &index, was, &keys, changes, wall);
for (from, to) in [(was, now), (now, was)] {
rebuild_fields(&log, &index, from, to).infallible();
let built = MemoryPostings::default();
build(&log, &built, to).infallible();
prop_assert_eq!(
&index,
&built,
"from {:?} to {:?}",
from.last_writer_wins,
to.last_writer_wins
);
}
Ok(())
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(64))]
#[test]
fn the_index_follows_changes_in_any_order(
steps in prop::collection::vec(step(), 1..16),
seed in 1..u64::MAX,
last_writer_wins in any::<bool>(),
) {
follows(steps, seed, last_writer_wins)?;
}
#[test]
fn the_indexes_follow_the_fields(
steps in prop::collection::vec(step(), 1..16),
was in (any::<bool>(), any::<bool>()),
now in (any::<bool>(), any::<bool>()),
) {
follows_fields(steps, was, now)?;
}
}
}