Skip to main content

nibkeep_store/
index.rs

1//! Indexes and search of a space's current statements, kept in the state file.
2
3use std::collections::{BTreeMap, BTreeSet};
4
5#[cfg(test)]
6use nibkeep_base::SpaceId;
7use nibkeep_base::cbor;
8#[cfg(test)]
9use nibkeep_base::small::SmallSet;
10use nibkeep_base::{EntityId, Hash, StatementId};
11use nibkeep_log::{History, Log, SpaceState};
12use nibkeep_model::storage::Statements;
13use nibkeep_model::{FieldName, Operation, Statement, Value, fields};
14use unicode_normalization::UnicodeNormalization;
15use unicode_normalization::char::is_combining_mark;
16
17/// An entity that a search found.
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct Found {
20	/// The entity, or of entities merged together, the one they were merged into.
21	pub entity: EntityId,
22	/// How many current statements of the entity, and of the entities merged with it, hold
23	/// words of the search in their values.
24	pub matching: usize,
25}
26
27/// How many times as many statements as the rarest whole word the beginning of the last
28/// word may start, at most, for its statements to be read with the whole words', rather
29/// than looked for in each candidate's own: reading a statement of a word costs a fraction
30/// of checking a candidate, so for a common last word, such as `of` in `wizard of`, reading
31/// costs less even when it holds a few times as many statements.
32const PREFIX_READ_FACTOR: usize = 4;
33
34/// The indexes of a space's ordinary current statements: by the words of their text, and
35/// by their values. Secret statements are left out: those the log holds sealed, and those
36/// of fields that are secret on this replica. So are the older values of fields whose last
37/// writer wins, which no one sees: of those, only the value written last is indexed. The
38/// fields that NibKeep reserves for its own structure, such as the types of entities, and
39/// those that hold keys and positions, are found by value but not by their words.
40///
41/// The ordinary statements change only through the operations of accepted changes, so
42/// taking in those operations keeps the indexes exact. Opening and forgetting secret
43/// statements does not touch them.
44///
45/// The indexes are kept in postings: in the state file, or in memory. Writing them takes
46/// `&self`, as the postings of the state file are kept by the storage that the state reads.
47pub(crate) trait Postings {
48	/// Why reading or writing failed.
49	type Error;
50
51	/// What tells statements apart in a search, which never needs their IDs: a number the
52	/// postings give each statement, or its ID.
53	type Key: Copy + Ord;
54
55	/// What is indexed of a statement.
56	fn indexed(&self, id: StatementId) -> Result<Option<Indexed>, Self::Error>;
57
58	/// Indexes a statement.
59	fn insert(&self, id: StatementId, indexed: &Indexed) -> Result<(), Self::Error>;
60
61	/// Takes a statement out of the indexes, if it is in them.
62	fn remove(&self, id: StatementId) -> Result<(), Self::Error>;
63
64	/// Empties the indexes.
65	fn clear(&self) -> Result<(), Self::Error>;
66
67	/// The statements whose text holds a word, with the entities they show under, of those
68	/// that are not deleted.
69	fn with_word(&self, word: &str) -> Result<Vec<(Self::Key, EntityId)>, Self::Error>;
70
71	/// How many statements hold a word.
72	fn word_count(&self, word: &str) -> Result<usize, Self::Error>;
73
74	/// The statements whose text holds a word that starts with `prefix`, each once, with the
75	/// entities they show under, of those that are not deleted.
76	fn with_prefix(&self, prefix: &str) -> Result<Vec<(Self::Key, EntityId)>, Self::Error>;
77
78	/// How many statements hold each word that starts with `prefix`, added together, or
79	/// `at_most` if they are more: counting stops there, as a short beginning can start a
80	/// great many words.
81	fn prefix_count(&self, prefix: &str, at_most: usize) -> Result<usize, Self::Error>;
82
83	/// The indexed statements that show under an entity whose text holds a word that starts
84	/// with `prefix`.
85	fn shown_with_prefix(
86		&self,
87		entity: EntityId,
88		prefix: &str,
89	) -> Result<Vec<Self::Key>, Self::Error>;
90
91	/// The entities that the statements of a field with a value show under, of those that
92	/// are not deleted, by the hash of the value's canonical CBOR.
93	fn with_value(&self, field: &FieldName, value: &Hash) -> Result<Vec<EntityId>, Self::Error>;
94
95	/// The entities that the statements of fields that name entities, with a name that is
96	/// `lowered` once lowercased, show under, deleted ones included.
97	fn with_name(&self, lowered: &str) -> Result<Vec<EntityId>, Self::Error>;
98
99	/// The indexed statements that show under an entity.
100	fn of_shown(&self, entity: EntityId) -> Result<Vec<(StatementId, Indexed)>, Self::Error>;
101
102	/// Marks the statements that show under an entity as deleted, or not.
103	fn set_deleted(&self, entity: EntityId, deleted: bool) -> Result<(), Self::Error>;
104
105	/// Takes the statements of a field, of every entity, out of the indexes.
106	fn remove_field(&self, field: &FieldName) -> Result<(), Self::Error>;
107}
108
109/// The entities that statements show under, and whether they are deleted, as the state
110/// says, kept for a call that indexes many statements of one entity.
111#[derive(Default)]
112struct Shown(BTreeMap<EntityId, (EntityId, bool)>);
113
114impl Shown {
115	/// The entity that an entity's statements show under: its own, or the one it was merged
116	/// into; and whether that one is deleted.
117	fn of<S: Statements>(
118		&mut self,
119		state: &SpaceState<S>,
120		entity: EntityId,
121	) -> Result<(EntityId, bool), S::Error> {
122		if let Some(&known) = self.0.get(&entity) {
123			return Ok(known);
124		}
125		let canonical = state.canonical(entity)?;
126		let known = (canonical, state.is_deleted(canonical)?);
127		self.0.insert(entity, known);
128		Ok(known)
129	}
130}
131
132/// Which fields a space treats specially: those that are secret on this replica, and those
133/// whose last writer wins.
134#[derive(Clone, Copy)]
135pub(crate) struct Fields<'a> {
136	pub(crate) secret: &'a BTreeSet<FieldName>,
137	pub(crate) last_writer_wins: &'a BTreeSet<FieldName>,
138}
139
140/// What is indexed of a statement.
141#[derive(Clone, Debug, PartialEq, Eq)]
142pub(crate) struct Indexed {
143	pub(crate) entity: EntityId,
144	/// The entity it shows under: its own, or the one that it was merged into.
145	pub(crate) shown: EntityId,
146	/// Whether that entity is deleted.
147	pub(crate) deleted: bool,
148	/// The words of its text, sorted, without duplicates.
149	pub(crate) words: Vec<String>,
150	/// Of a field that names entities, the name it holds, lowercased.
151	pub(crate) name: Option<String>,
152	pub(crate) value: (FieldName, Hash),
153}
154
155/// Of each field whose last writer wins, the value written last, worked out once for every
156/// entity, or of entities merged together, once for all of them.
157#[derive(Default)]
158struct LastWritten(BTreeMap<(EntityId, FieldName), Option<StatementId>>);
159
160impl LastWritten {
161	/// The value written last of the field of a statement, for the statement's entity and
162	/// those merged with it: the statement is shown if it is that one.
163	fn of<S: Statements>(
164		&mut self,
165		state: &SpaceState<S>,
166		statement: &Statement,
167	) -> Result<Option<StatementId>, S::Error> {
168		let key = (state.canonical(statement.entity)?, statement.field.clone());
169		if let Some(written) = self.0.get(&key) {
170			return Ok(*written);
171		}
172		let written = state
173			.last_written(statement.entity, &statement.field)?
174			.map(|last| last.id);
175		self.0.insert(key, written);
176		Ok(written)
177	}
178}
179
180/// Builds the indexes of a log's current state anew in `postings`.
181pub(crate) fn build<S, H, P>(
182	log: &Log<S, H>,
183	postings: &P,
184	fields: Fields<'_>,
185) -> Result<(), S::Error>
186where
187	S: Statements,
188	H: History<Error = S::Error>,
189	P: Postings<Error = S::Error>,
190{
191	let state = log.state();
192	postings.clear()?;
193	let mut shown = Shown::default();
194	let mut last = LastWritten::default();
195	for statement in state.statements()? {
196		if fields.last_writer_wins.contains(&statement.field)
197			&& last.of(state, &statement)? != Some(statement.id)
198		{
199			continue;
200		}
201		add(log, postings, fields, &mut shown, &statement)?;
202	}
203	Ok(())
204}
205
206/// Brings the indexes of a log's current state in `postings` from the fields they were built
207/// with, `was`, to the fields that are special now, `fields`: the statements of a field that
208/// became secret leave; those of a field that is no longer secret come in; of a field whose
209/// last writer wins now, only the value written last of each entity, or of entities merged
210/// together, stays; and every current statement of a field whose last writer no longer wins
211/// comes in. The other fields stay as they are.
212pub(crate) fn rebuild_fields<S, H, P>(
213	log: &Log<S, H>,
214	postings: &P,
215	was: Fields<'_>,
216	fields: Fields<'_>,
217) -> Result<(), S::Error>
218where
219	S: Statements,
220	H: History<Error = S::Error>,
221	P: Postings<Error = S::Error>,
222{
223	let state = log.state();
224	let mut shown = Shown::default();
225	let mut last = LastWritten::default();
226	let changed: BTreeSet<&FieldName> = was
227		.secret
228		.symmetric_difference(fields.secret)
229		.chain(
230			was.last_writer_wins
231				.symmetric_difference(fields.last_writer_wins),
232		)
233		.collect();
234	for field in changed {
235		postings.remove_field(field)?;
236		if fields.secret.contains(field) {
237			continue;
238		}
239		let last_wins = fields.last_writer_wins.contains(field);
240		for recorded in state.storage().current_in_field(field)? {
241			let statement = &recorded.statement;
242			if last_wins && last.of(state, statement)? != Some(statement.id) {
243				continue;
244			}
245			add(log, postings, fields, &mut shown, statement)?;
246		}
247	}
248	Ok(())
249}
250
251/// What the operations of a change touch, noted as they are taken in: what is looked at
252/// again once they all are.
253#[derive(Default)]
254struct Touched {
255	/// The fields whose last writer wins that changed, with their entities.
256	last_writer_wins: BTreeSet<(EntityId, FieldName)>,
257	/// The entities whose deletion changed.
258	deletions: BTreeSet<EntityId>,
259	/// The entities whose merges changed.
260	merged: BTreeSet<EntityId>,
261	/// The entities they were, or are, merged into.
262	merged_into: BTreeSet<EntityId>,
263	/// The entities that merges taken out of the indexes showed under: where the statements
264	/// of the entities merged showed before.
265	merged_under: BTreeSet<EntityId>,
266}
267
268impl Touched {
269	/// Notes a field of an entity that an operation touched, and for a merge, the entity it
270	/// leads to: the one it refers to, or the one its statement was indexed under.
271	fn field(
272		&mut self,
273		fields: Fields<'_>,
274		entity: EntityId,
275		field: &FieldName,
276		other: Option<EntityId>,
277	) {
278		if *field == fields::DELETED {
279			self.deletions.insert(entity);
280		}
281		if *field == fields::MERGED_INTO {
282			self.merged.insert(entity);
283			self.merged_into.extend(other);
284		}
285		if fields.last_writer_wins.contains(field) {
286			self.last_writer_wins.insert((entity, field.clone()));
287		}
288	}
289
290	/// Notes a statement that an operation asserts, supersedes or retracts, or that the state
291	/// holds under its ID.
292	fn statement(&mut self, fields: Fields<'_>, statement: &Statement) {
293		self.field(
294			fields,
295			statement.entity,
296			&statement.field,
297			statement.value.as_reference(),
298		);
299	}
300
301	/// Notes a statement taken out of the indexes, as it was indexed.
302	fn indexed(&mut self, fields: Fields<'_>, indexed: &Indexed) {
303		self.field(fields, indexed.entity, &indexed.value.0, None);
304		if indexed.value.0 == fields::MERGED_INTO {
305			self.merged_under.insert(indexed.shown);
306		}
307	}
308}
309
310/// Takes in the operations of a change after the log accepted it. A statement is indexed
311/// once it is asserted, unless it is superseded already, and taken out once it is
312/// superseded, which is for good. Of a field whose last writer wins, the value written last
313/// is indexed again whenever the field changes. A merge of entities moves the statements of
314/// the entities merged to the entity they show under now, looks again at every field whose
315/// last writer wins of the entities merged together, and leaves the other statements alone.
316pub(crate) fn apply<'a, S, H, P>(
317	log: &Log<S, H>,
318	postings: &P,
319	fields: Fields<'_>,
320	operations: impl IntoIterator<Item = &'a Operation>,
321) -> Result<(), S::Error>
322where
323	S: Statements,
324	H: History<Error = S::Error>,
325	P: Postings<Error = S::Error>,
326{
327	let state = log.state();
328	let mut shown = Shown::default();
329	let mut touched = Touched::default();
330	// The statements indexed by this call, which show under the right entity already.
331	let mut fresh = BTreeSet::new();
332	for operation in operations {
333		match operation {
334			Operation::Assert {
335				statement,
336				supersedes,
337				..
338			} => {
339				touched.statement(fields, statement);
340				// The state keeps one statement of an ID that was asserted twice: the one it
341				// had, perhaps recorded anew, or this one, which may replace the one indexed,
342				// of another entity or field. The fields of all three are looked at again.
343				if let Some(kept) = state.statement(statement.id)? {
344					touched.statement(fields, &kept);
345				}
346				if let Some(indexed) = take_out(postings, statement.id)? {
347					touched.indexed(fields, &indexed);
348				}
349				if state.is_current(statement.id)?
350					&& let Some(current) = state.statement(statement.id)?
351					&& !fields.last_writer_wins.contains(&current.field)
352				{
353					add(log, postings, fields, &mut shown, &current)?;
354					fresh.insert(current.id);
355				}
356				for id in supersedes {
357					// One of another entity is not superseded.
358					if state.is_current(*id)? {
359						continue;
360					}
361					if let Some(superseded) = state.statement(*id)? {
362						touched.statement(fields, &superseded);
363					}
364					if let Some(indexed) = take_out(postings, *id)? {
365						touched.indexed(fields, &indexed);
366					}
367				}
368			}
369			// A retraction of secret statements leaves an ordinary statement with one of
370			// their IDs current, which is then left as it is.
371			Operation::Retract { statements, .. } | Operation::RetractSecret { statements } => {
372				for id in statements {
373					if state.is_current(*id)? {
374						continue;
375					}
376					if let Some(retracted) = state.statement(*id)? {
377						touched.statement(fields, &retracted);
378					}
379					if let Some(indexed) = take_out(postings, *id)? {
380						touched.indexed(fields, &indexed);
381					}
382				}
383			}
384			Operation::Unknown(_) => {}
385		}
386	}
387	if !touched.merged.is_empty()
388		&& !move_merged(log, postings, fields, &mut shown, &mut touched, &fresh)?
389	{
390		return build(log, postings, fields);
391	}
392	// What shows under a deleted or restored entity is marked so.
393	for entity in touched.deletions {
394		let entity = state.canonical(entity)?;
395		postings.set_deleted(entity, state.is_deleted(entity)?)?;
396	}
397	// The state holds every change applied at once, so a statement taken out here may be
398	// indexed as another entity's or field's, whose value written last is then looked at
399	// again too.
400	let mut pending: Vec<(EntityId, FieldName)> = touched.last_writer_wins.into_iter().collect();
401	let mut done = BTreeSet::new();
402	while let Some((entity, field)) = pending.pop() {
403		if !done.insert((state.canonical(entity)?, field.clone())) {
404			continue;
405		}
406		for statement in state.current(entity, &field)? {
407			if let Some(indexed) = postings.indexed(statement.id)? {
408				if indexed.entity != statement.entity || indexed.value.0 != statement.field {
409					return build(log, postings, fields);
410				}
411				if fields.last_writer_wins.contains(&indexed.value.0) {
412					pending.push((indexed.entity, indexed.value.0.clone()));
413				}
414			}
415			postings.remove(statement.id)?;
416		}
417		if let Some(last) = state.last_written(entity, &field)? {
418			add(log, postings, fields, &mut shown, &last)?;
419		}
420	}
421	Ok(())
422}
423
424/// Moves the statements that merges moved: those of the entities merged, `touched.merged`,
425/// and of the entities merged into them, which show under another entity now, or under one
426/// that is deleted where theirs was not. The entities they were merged into keep what they
427/// show, and so do the statements in `fresh`, indexed by this change. Of every field whose
428/// last writer wins of an entity moved, the value written last among the entities merged
429/// together may have changed, for the entities merged into too: `touched` notes those
430/// fields, for the caller to look at again.
431///
432/// Returns `false` if a statement turns out indexed as another entity's or field's than the
433/// state's statement of its ID: two different statements with one ID, which only a faulty
434/// replica makes, and which an earlier change applied with this one may have swapped in the
435/// indexes unnoticed. The caller then builds the indexes anew.
436fn move_merged<S, H, P>(
437	log: &Log<S, H>,
438	postings: &P,
439	fields: Fields<'_>,
440	shown: &mut Shown,
441	touched: &mut Touched,
442	fresh: &BTreeSet<StatementId>,
443) -> Result<bool, S::Error>
444where
445	S: Statements,
446	H: History<Error = S::Error>,
447	P: Postings<Error = S::Error>,
448{
449	let state = log.state();
450	let Touched {
451		merged,
452		merged_into,
453		merged_under,
454		last_writer_wins,
455		..
456	} = touched;
457	// Whose statements may have moved: the entities merged, and the entities that showed
458	// under them, under what their merges showed under, or under the same entities as their
459	// statements did before this change, and show under another now: the rest of their old
460	// groups.
461	let mut candidates = BTreeSet::new();
462	let mut under = merged_under.clone();
463	for &entity in merged.iter() {
464		candidates.insert(entity);
465		under.insert(entity);
466		for (field, ids) in state.storage().of_entity(entity)? {
467			for id in ids {
468				if fresh.contains(&id) {
469					continue;
470				}
471				if let Some(indexed) = postings.indexed(id)? {
472					if indexed.entity != entity || indexed.value.0 != field {
473						return Ok(false);
474					}
475					under.insert(indexed.shown);
476				}
477			}
478		}
479	}
480	for &shown_under in &under {
481		for (_, indexed) in postings.of_shown(shown_under)? {
482			if shown.of(state, indexed.entity)?.0 != shown_under {
483				candidates.insert(indexed.entity);
484			}
485		}
486	}
487	// Each statement is looked at on its own: an earlier change applied with this one may
488	// have indexed some of an entity's statements where they show now, and not others.
489	let mut lww_fields = BTreeSet::new();
490	for candidate in candidates {
491		let (canonical, deleted) = shown.of(state, candidate)?;
492		for (field, ids) in state.storage().of_entity(candidate)? {
493			let last_wins = fields.last_writer_wins.contains(&field);
494			if last_wins {
495				last_writer_wins.insert((candidate, field.clone()));
496				lww_fields.insert(field.clone());
497			}
498			for id in ids {
499				if fresh.contains(&id) {
500					continue;
501				}
502				let Some(indexed) = postings.indexed(id)? else {
503					continue;
504				};
505				if indexed.entity != candidate || indexed.value.0 != field {
506					return Ok(false);
507				}
508				if indexed.shown == canonical && indexed.deleted == deleted {
509					continue;
510				}
511				postings.remove(id)?;
512				// Of a field whose last writer wins, the caller indexes the value written last.
513				if last_wins {
514					continue;
515				}
516				if state.is_current(id)?
517					&& let Some(statement) = state.statement(id)?
518				{
519					add(log, postings, fields, shown, &statement)?;
520				}
521			}
522		}
523	}
524	// What was written last of those fields may have changed for the entities merged into,
525	// and for those that the statements moved showed under before: a value that shows only
526	// while another entity is merged with them, or one of theirs that such a value hid.
527	for &entity in merged_into.iter().chain(under.iter()) {
528		for field in &lww_fields {
529			last_writer_wins.insert((entity, field.clone()));
530		}
531	}
532	Ok(true)
533}
534
535/// Finds the entities whose current values hold every word of `query`. The last word also
536/// matches the start of a longer word, so that results appear while typing. Entities with
537/// more matching values come first, deleted ones not at all.
538///
539/// The candidates are the entities that hold every whole word, and the beginning of the
540/// last one too unless it starts more than [`PREFIX_READ_FACTOR`] times as many statements
541/// as the rarest whole word; their own statements are then checked for the beginning.
542pub(crate) fn search<P: Postings>(postings: &P, query: &str) -> Result<Vec<Found>, P::Error> {
543	let words = words(query);
544	let Some(last) = words.len().checked_sub(1) else {
545		return Ok(Vec::new());
546	};
547	// Every word must be held by the entity or one merged with it, so the candidates are
548	// the entities that the statements of every whole word belong to, starting with the
549	// word held least. Reading a word's statements costs as much as there are, so the
550	// last word, the beginning of words, joins them only when it does not start many more
551	// statements than the rarest whole word holds.
552	let mut counts = Vec::new();
553	for word in &words[..last] {
554		counts.push((postings.word_count(word)?, Some(word.as_str())));
555	}
556	let prefix_read = match counts.iter().map(|(count, _)| *count).min() {
557		None => {
558			counts.push((0, None));
559			true
560		}
561		Some(rarest) => {
562			let most = rarest.saturating_mul(PREFIX_READ_FACTOR);
563			let beginning = postings.prefix_count(&words[last], most.saturating_add(1))?;
564			let read = beginning <= most;
565			if read {
566				counts.push((beginning, None));
567			}
568			read
569		}
570	};
571	counts.sort_by_key(|(count, _)| *count);
572	// For each candidate, the statements that hold the words read so far.
573	let mut candidates: Option<BTreeMap<EntityId, BTreeSet<P::Key>>> = None;
574	for (_, word) in counts {
575		let held = match word {
576			Some(word) => postings.with_word(word)?,
577			None => postings.with_prefix(&words[last])?,
578		};
579		let mut holding: BTreeMap<EntityId, BTreeSet<P::Key>> = BTreeMap::new();
580		for (statement, entity) in held {
581			if candidates
582				.as_ref()
583				.is_none_or(|known| known.contains_key(&entity))
584			{
585				holding.entry(entity).or_default().insert(statement);
586			}
587		}
588		if let Some(known) = candidates {
589			for (entity, statements) in &mut holding {
590				statements.extend(&known[entity]);
591			}
592		}
593		if holding.is_empty() {
594			return Ok(Vec::new());
595		}
596		candidates = Some(holding);
597	}
598	let mut found = Vec::new();
599	for (entity, mut statements) in candidates.unwrap_or_default() {
600		// The beginning of the last word, if it was not read with the others, is looked for
601		// in the candidates' own statements.
602		if !prefix_read {
603			let holding = postings.shown_with_prefix(entity, &words[last])?;
604			if holding.is_empty() {
605				continue;
606			}
607			statements.extend(holding);
608		}
609		found.push(Found {
610			entity,
611			matching: statements.len(),
612		});
613	}
614	found.sort_by(|a, b| b.matching.cmp(&a.matching).then(a.entity.cmp(&b.entity)));
615	Ok(found)
616}
617
618/// The entities whose field `field` has the current value `value`, exactly, ordered by ID.
619/// Of entities merged together, the one they were merged into is given, and deleted ones
620/// not at all.
621pub(crate) fn find<P: Postings>(
622	postings: &P,
623	field: &FieldName,
624	value: &Value,
625) -> Result<Vec<EntityId>, P::Error> {
626	let entities: BTreeSet<EntityId> = postings
627		.with_value(field, &Hash::of(&cbor::to_vec(value)))?
628		.into_iter()
629		.collect();
630	Ok(entities.into_iter().collect())
631}
632
633/// Takes a statement out of the indexes, if it is in them, and says what was indexed of it,
634/// for the caller to look at its entity and field again: the state, which holds every change
635/// applied at once, may already hold another statement of the same ID.
636fn take_out<P: Postings>(postings: &P, id: StatementId) -> Result<Option<Indexed>, P::Error> {
637	let indexed = postings.indexed(id)?;
638	if indexed.is_some() {
639		postings.remove(id)?;
640	}
641	Ok(indexed)
642}
643
644/// Indexes a statement, unless it is secret. Of a field whose last writer wins, the caller
645/// adds only the value written last.
646fn add<S, H, P>(
647	log: &Log<S, H>,
648	postings: &P,
649	fields: Fields<'_>,
650	shown: &mut Shown,
651	statement: &Statement,
652) -> Result<(), P::Error>
653where
654	S: Statements,
655	H: History<Error = S::Error>,
656	P: Postings<Error = S::Error>,
657{
658	if fields.secret.contains(&statement.field) || log.is_sealed(statement.id)? {
659		return Ok(());
660	}
661	let mut words: Vec<String> = if fields::has_words(&statement.field) {
662		statement
663			.value
664			.searchable_texts()
665			.into_iter()
666			.flat_map(self::words)
667			.collect()
668	} else {
669		Vec::new()
670	};
671	words.sort_unstable();
672	words.dedup();
673	let name = fields::name_key(&statement.field, &statement.value);
674	let (shown_under, deleted) = shown.of(log.state(), statement.entity)?;
675	postings.insert(
676		statement.id,
677		&Indexed {
678			entity: statement.entity,
679			shown: shown_under,
680			deleted,
681			words,
682			name,
683			value: (
684				statement.field.clone(),
685				Hash::of(&cbor::to_vec(&statement.value)),
686			),
687		},
688	)
689}
690
691/// The indexes in memory, for tests.
692#[cfg(test)]
693#[derive(Debug, Default, PartialEq, Eq)]
694pub(crate) struct MemoryPostings(std::cell::RefCell<Maps>);
695
696/// The maps of indexes in memory, and what was done to them, which tests look at.
697#[cfg(test)]
698#[derive(Debug, Default)]
699struct Maps {
700	/// For each word, the statements whose text holds it.
701	words: BTreeMap<String, SmallSet<StatementId>>,
702	/// For each field and hash of a value in canonical CBOR, the statements that hold it.
703	values: BTreeMap<(FieldName, Hash), SmallSet<StatementId>>,
704	/// The indexed statements that show under each entity.
705	shown: BTreeMap<EntityId, SmallSet<StatementId>>,
706	/// For each name, lowercased, the statements that hold it.
707	names: BTreeMap<String, SmallSet<StatementId>>,
708	/// What is indexed of each statement, so that it can be taken out again.
709	indexed: BTreeMap<StatementId, Indexed>,
710	/// The statements indexed or taken out so far.
711	touched: BTreeSet<StatementId>,
712	/// How often the indexes were emptied.
713	cleared: usize,
714}
715
716/// Two sets of indexes are equal when they hold the same, whatever was done to them.
717#[cfg(test)]
718impl PartialEq for Maps {
719	fn eq(&self, other: &Self) -> bool {
720		self.words == other.words
721			&& self.values == other.values
722			&& self.shown == other.shown
723			&& self.names == other.names
724			&& self.indexed == other.indexed
725	}
726}
727
728#[cfg(test)]
729impl Eq for Maps {}
730
731#[cfg(test)]
732impl Postings for MemoryPostings {
733	type Error = std::convert::Infallible;
734	type Key = StatementId;
735
736	fn indexed(&self, id: StatementId) -> Result<Option<Indexed>, Self::Error> {
737		Ok(self.0.borrow().indexed.get(&id).cloned())
738	}
739
740	fn insert(&self, id: StatementId, indexed: &Indexed) -> Result<(), Self::Error> {
741		Postings::remove(self, id)?;
742		let mut maps = self.0.borrow_mut();
743		maps.touched.insert(id);
744		for word in &indexed.words {
745			maps.words.entry(word.clone()).or_default().insert(id);
746		}
747		maps.values
748			.entry(indexed.value.clone())
749			.or_default()
750			.insert(id);
751		maps.shown.entry(indexed.shown).or_default().insert(id);
752		if let Some(name) = &indexed.name {
753			maps.names.entry(name.clone()).or_default().insert(id);
754		}
755		maps.indexed.insert(id, indexed.clone());
756		Ok(())
757	}
758
759	fn remove(&self, id: StatementId) -> Result<(), Self::Error> {
760		let mut maps = self.0.borrow_mut();
761		let Some(indexed) = maps.indexed.remove(&id) else {
762			return Ok(());
763		};
764		maps.touched.insert(id);
765		for word in &indexed.words {
766			remove_from(&mut maps.words, word, id);
767		}
768		remove_from(&mut maps.values, &indexed.value, id);
769		remove_from(&mut maps.shown, &indexed.shown, id);
770		if let Some(name) = &indexed.name {
771			remove_from(&mut maps.names, name, id);
772		}
773		Ok(())
774	}
775
776	fn clear(&self) -> Result<(), Self::Error> {
777		let mut maps = self.0.borrow_mut();
778		*maps = Maps {
779			touched: std::mem::take(&mut maps.touched),
780			cleared: maps.cleared + 1,
781			..Maps::default()
782		};
783		Ok(())
784	}
785
786	fn with_word(&self, word: &str) -> Result<Vec<(Self::Key, EntityId)>, Self::Error> {
787		let maps = self.0.borrow();
788		Ok(maps
789			.words
790			.get(word)
791			.into_iter()
792			.flatten()
793			.filter(|id| !maps.indexed[id].deleted)
794			.map(|id| (*id, maps.indexed[id].shown))
795			.collect())
796	}
797
798	fn word_count(&self, word: &str) -> Result<usize, Self::Error> {
799		Ok(self.0.borrow().words.get(word).map_or(0, SmallSet::len))
800	}
801
802	fn with_prefix(&self, prefix: &str) -> Result<Vec<(Self::Key, EntityId)>, Self::Error> {
803		let maps = self.0.borrow();
804		let ids: BTreeSet<StatementId> = maps
805			.words
806			.range(prefix.to_owned()..)
807			.take_while(|(word, _)| word.starts_with(prefix))
808			.flat_map(|(_, ids)| ids.iter().copied())
809			.collect();
810		Ok(ids
811			.into_iter()
812			.filter(|id| !maps.indexed[id].deleted)
813			.map(|id| (id, maps.indexed[&id].shown))
814			.collect())
815	}
816
817	fn prefix_count(&self, prefix: &str, at_most: usize) -> Result<usize, Self::Error> {
818		let count: usize = self
819			.0
820			.borrow()
821			.words
822			.range(prefix.to_owned()..)
823			.take_while(|(word, _)| word.starts_with(prefix))
824			.map(|(_, ids)| ids.len())
825			.sum();
826		Ok(count.min(at_most))
827	}
828
829	fn shown_with_prefix(
830		&self,
831		entity: EntityId,
832		prefix: &str,
833	) -> Result<Vec<Self::Key>, Self::Error> {
834		let maps = self.0.borrow();
835		Ok(maps
836			.shown
837			.get(&entity)
838			.into_iter()
839			.flatten()
840			.filter(|id| {
841				maps.indexed[id]
842					.words
843					.iter()
844					.any(|word| word.starts_with(prefix))
845			})
846			.copied()
847			.collect())
848	}
849
850	fn with_value(&self, field: &FieldName, value: &Hash) -> Result<Vec<EntityId>, Self::Error> {
851		let maps = self.0.borrow();
852		Ok(maps
853			.values
854			.get(&(field.clone(), *value))
855			.into_iter()
856			.flatten()
857			.filter(|id| !maps.indexed[id].deleted)
858			.map(|id| maps.indexed[id].shown)
859			.collect())
860	}
861
862	fn with_name(&self, lowered: &str) -> Result<Vec<EntityId>, Self::Error> {
863		let maps = self.0.borrow();
864		let entities: BTreeSet<EntityId> = maps
865			.names
866			.get(lowered)
867			.into_iter()
868			.flatten()
869			.map(|id| maps.indexed[id].shown)
870			.collect();
871		Ok(entities.into_iter().collect())
872	}
873
874	fn of_shown(&self, entity: EntityId) -> Result<Vec<(StatementId, Indexed)>, Self::Error> {
875		let maps = self.0.borrow();
876		Ok(maps
877			.shown
878			.get(&entity)
879			.into_iter()
880			.flatten()
881			.map(|id| (*id, maps.indexed[id].clone()))
882			.collect())
883	}
884
885	fn remove_field(&self, field: &FieldName) -> Result<(), Self::Error> {
886		let ids: Vec<StatementId> = self
887			.0
888			.borrow()
889			.indexed
890			.iter()
891			.filter(|(_, indexed)| indexed.value.0 == *field)
892			.map(|(id, _)| *id)
893			.collect();
894		for id in ids {
895			self.remove(id)?;
896		}
897		Ok(())
898	}
899
900	fn set_deleted(&self, entity: EntityId, deleted: bool) -> Result<(), Self::Error> {
901		let mut maps = self.0.borrow_mut();
902		let ids: Vec<StatementId> = maps
903			.shown
904			.get(&entity)
905			.into_iter()
906			.flatten()
907			.copied()
908			.collect();
909		for id in ids {
910			if let Some(indexed) = maps.indexed.get_mut(&id) {
911				indexed.deleted = deleted;
912			}
913		}
914		Ok(())
915	}
916}
917
918/// Takes a statement out of the set of a key, and the key out with its last statement.
919#[cfg(test)]
920fn remove_from<K: Ord>(map: &mut BTreeMap<K, SmallSet<StatementId>>, key: &K, id: StatementId) {
921	if let Some(ids) = map.get_mut(key) {
922		ids.remove(&id);
923		if ids.is_empty() {
924			map.remove(key);
925		}
926	}
927}
928
929/// Whether a text holds every word of `query` as a search compares them: without regard to
930/// case or accents, each a whole word of the text, but the last, which may also start a
931/// longer one. A query without words is held by no text.
932#[must_use]
933pub fn holds_words(text: &str, query: &str) -> bool {
934	let wanted = words(query);
935	let Some((last, whole)) = wanted.split_last() else {
936		return false;
937	};
938	let held = words(text);
939	whole.iter().all(|word| held.contains(word))
940		&& held.iter().any(|word| word.starts_with(last.as_str()))
941}
942
943/// The words of a text, compared without regard to case or accents: decomposed, so that
944/// characters such as `㎒` become letters, lowercased, without combining marks, and split
945/// at every character that is not a letter or a digit.
946fn words(text: &str) -> Vec<String> {
947	let folded: String = text
948		.nfkd()
949		.flat_map(char::to_lowercase)
950		.collect::<String>()
951		.nfkd()
952		.filter(|&character| !is_combining_mark(character))
953		.collect();
954	folded
955		.split(|character: char| !character.is_alphanumeric())
956		.filter(|word| !word.is_empty())
957		.map(str::to_owned)
958		.collect()
959}
960
961#[cfg(test)]
962mod tests {
963	use std::fs;
964
965	use nibkeep_crypto::SigningKey;
966	use nibkeep_log::{Log, Parcel, Received, SpaceKeys};
967	use nibkeep_model::storage::Infallibly;
968	use nibkeep_testkit::{TestRng, millis_at};
969	use nibkeep_time::Clock;
970	use proptest::prelude::*;
971
972	use super::*;
973	use crate::StateFile;
974
975	const DRIFT: u64 = 3_600_000;
976
977	const WORDS: [&str; 6] = ["ada", "adam", "lovelace", "Café", "cafe", "zoë"];
978
979	/// What one of the writers does: asserts a text of some words on one of a few entities,
980	/// replacing some statements, or retracts some. Statements are named by the order in
981	/// which they were asserted, by any writer, so writers can supersede each other's
982	/// statements, also before those arrive.
983	#[derive(Clone, Debug)]
984	enum Step {
985		/// Asserts a text on a field of an entity, under a new statement ID or, rarely,
986		/// under the ID of an earlier statement, as two replicas could by chance.
987		Assert {
988			writer: usize,
989			entity: usize,
990			field: usize,
991			words: Vec<usize>,
992			replaces: Vec<usize>,
993			reuses: Option<usize>,
994		},
995		Retract {
996			writer: usize,
997			statements: Vec<usize>,
998		},
999		/// Merges one entity into another.
1000		Merge {
1001			writer: usize,
1002			entity: usize,
1003			into: usize,
1004		},
1005		/// Deletes an entity, which retracting the statement restores.
1006		Delete { writer: usize, entity: usize },
1007	}
1008
1009	fn step() -> impl Strategy<Value = Step> {
1010		prop_oneof![
1011			6 => (
1012				0..3_usize,
1013				0..3_usize,
1014				0..2_usize,
1015				prop::collection::vec(0..WORDS.len(), 1..3),
1016				prop::collection::vec(0..16_usize, 0..2),
1017				prop::option::weighted(0.1, 0..16_usize),
1018			)
1019				.prop_map(|(writer, entity, field, words, replaces, reuses)| Step::Assert {
1020					writer,
1021					entity,
1022					field,
1023					words,
1024					replaces,
1025					reuses,
1026				}),
1027			2 => (0..3_usize, prop::collection::vec(0..16_usize, 1..3))
1028				.prop_map(|(writer, statements)| Step::Retract { writer, statements }),
1029			1 => (0..3_usize, 0..3_usize, 0..3_usize)
1030				.prop_map(|(writer, entity, into)| Step::Merge { writer, entity, into }),
1031			1 => (0..3_usize, 0..3_usize)
1032				.prop_map(|(writer, entity)| Step::Delete { writer, entity }),
1033		]
1034	}
1035
1036	/// Shuffles changes with a seed, so that a reader receives them in another order.
1037	fn shuffle(changes: &mut [Parcel], mut seed: u64) {
1038		for last in (1..changes.len()).rev() {
1039			seed ^= seed << 13;
1040			seed ^= seed >> 7;
1041			seed ^= seed << 17;
1042			let other = usize::try_from(seed % (last as u64 + 1)).expect("small");
1043			changes.swap(last, other);
1044		}
1045	}
1046
1047	/// A search that looks at every current statement, to compare the index with: of a
1048	/// field whose last writer wins, at the one written last.
1049	fn every_statement(state: &SpaceState, fields: Fields<'_>, query: &str) -> Vec<Found> {
1050		let words = words(query);
1051		let Some(last) = words.len().checked_sub(1) else {
1052			return Vec::new();
1053		};
1054		let mut entities: BTreeMap<EntityId, (Vec<bool>, BTreeSet<StatementId>)> = BTreeMap::new();
1055		for statement in state.statements().infallible() {
1056			let Value::Text(text) = &statement.value else {
1057				continue;
1058			};
1059			if fields::is_reserved(&statement.field) {
1060				continue;
1061			}
1062			if fields.last_writer_wins.contains(&statement.field)
1063				&& state
1064					.last_written(statement.entity, &statement.field)
1065					.infallible()
1066					.is_none_or(|last| last.id != statement.id)
1067			{
1068				continue;
1069			}
1070			let held = self::words(text);
1071			let (matched, statements) = entities
1072				.entry(state.canonical(statement.entity).infallible())
1073				.or_insert_with(|| (vec![false; words.len()], BTreeSet::new()));
1074			for (index, word) in words.iter().enumerate() {
1075				if held
1076					.iter()
1077					.any(|held| held == word || (index == last && held.starts_with(word.as_str())))
1078				{
1079					matched[index] = true;
1080					statements.insert(statement.id);
1081				}
1082			}
1083		}
1084		let mut found: Vec<Found> = entities
1085			.into_iter()
1086			.filter(|(entity, (matched, _))| {
1087				matched.iter().all(|&matched| matched) && !state.is_deleted(*entity).infallible()
1088			})
1089			.map(|(entity, (_, statements))| Found {
1090				entity,
1091				matching: statements.len(),
1092			})
1093			.collect();
1094		found.sort_by(|a, b| b.matching.cmp(&a.matching).then(a.entity.cmp(&b.entity)));
1095		found
1096	}
1097
1098	/// The entities that a name finds, looked for in every current statement: of a field
1099	/// whose last writer wins, in the one written last.
1100	fn every_name(state: &SpaceState, fields: Fields<'_>, lowered: &str) -> Vec<EntityId> {
1101		let mut named = BTreeSet::new();
1102		for statement in state.statements().infallible() {
1103			if fields::name_key(&statement.field, &statement.value).as_deref() == Some(lowered)
1104				&& (!fields.last_writer_wins.contains(&statement.field)
1105					|| state
1106						.last_written(statement.entity, &statement.field)
1107						.infallible()
1108						.is_some_and(|last| last.id == statement.id))
1109			{
1110				named.insert(state.canonical(statement.entity).infallible());
1111			}
1112		}
1113		named.into_iter().collect()
1114	}
1115
1116	/// A writer of a space, whose changes postings take in as it commits them.
1117	struct Writer {
1118		log: Log,
1119		author: SigningKey,
1120		keys: SpaceKeys,
1121		wall: u64,
1122		rng: TestRng,
1123	}
1124
1125	impl Writer {
1126		fn new(name: &str) -> Self {
1127			let mut rng = TestRng::new(name);
1128			Self {
1129				log: Log::new(rng.space_id(), Clock::new(DRIFT)),
1130				author: rng.signing_key(),
1131				keys: SpaceKeys::new(0, rng.key()),
1132				wall: millis_at("2026-10-12", 10, 0),
1133				rng,
1134			}
1135		}
1136
1137		/// A statement of an entity's field, with a new ID.
1138		fn statement(&mut self, entity: EntityId, field: &FieldName, value: Value) -> Statement {
1139			Statement::new(self.rng.statement_id(), entity, field.clone(), value)
1140		}
1141
1142		/// Commits an operation, a second after the one before, and takes it into `postings`.
1143		fn commit<P: Postings<Error = std::convert::Infallible>>(
1144			&mut self,
1145			postings: &P,
1146			fields: Fields<'_>,
1147			operation: Operation,
1148		) {
1149			self.wall += 1_000;
1150			self.log
1151				.commit(
1152					&self.author,
1153					&self.keys,
1154					vec![operation],
1155					self.wall,
1156					&mut self.rng,
1157				)
1158				.expect("commits");
1159			for (_, payload) in self.log.take_applied() {
1160				apply(&self.log, postings, fields, payload.all_operations()).infallible();
1161			}
1162		}
1163	}
1164
1165	#[test]
1166	fn a_merge_moves_only_the_statements_of_the_entity_merged() {
1167		let mut writer = Writer::new("a merge moves statements");
1168		let title: FieldName = "org.nibkeep.title".parse().expect("a field name");
1169		let (secret, last_writer_wins) = (BTreeSet::new(), BTreeSet::new());
1170		let fields = Fields {
1171			secret: &secret,
1172			last_writer_wins: &last_writer_wins,
1173		};
1174		let index = MemoryPostings::default();
1175		let [apart, from, into] = [
1176			writer.rng.entity_id(),
1177			writer.rng.entity_id(),
1178			writer.rng.entity_id(),
1179		];
1180		let mut titles = BTreeMap::new();
1181		for (entity, text) in [(apart, "Zoë"), (from, "Ada"), (into, "Lovelace")] {
1182			let statement = writer.statement(entity, &title, Value::Text(text.to_owned()));
1183			titles.insert(entity, statement.id);
1184			writer.commit(&index, fields, Operation::assert(statement));
1185		}
1186		index.0.borrow_mut().touched.clear();
1187		let merge = writer.statement(from, &fields::MERGED_INTO, Value::Reference(into));
1188		let merged = merge.id;
1189		writer.commit(&index, fields, Operation::assert(merge));
1190		{
1191			let maps = index.0.borrow();
1192			assert_eq!(maps.cleared, 0, "nothing is built anew");
1193			assert!(maps.touched.contains(&titles[&from]) && maps.touched.contains(&merged));
1194			assert!(
1195				!maps.touched.contains(&titles[&into]) && !maps.touched.contains(&titles[&apart]),
1196				"the entity merged into, and an entity apart, are left alone"
1197			);
1198		}
1199		let built = MemoryPostings::default();
1200		build(&writer.log, &built, fields).infallible();
1201		assert_eq!(index, built);
1202		assert_eq!(
1203			search(&index, "ada").infallible(),
1204			vec![Found {
1205				entity: into,
1206				matching: 1,
1207			}]
1208		);
1209	}
1210
1211	#[test]
1212	fn a_merge_shows_the_value_written_last_among_the_entities_merged() {
1213		let mut writer = Writer::new("a merge and the last writer");
1214		let title: FieldName = "org.nibkeep.title".parse().expect("a field name");
1215		let secret = BTreeSet::new();
1216		let last_writer_wins = BTreeSet::from([title.clone()]);
1217		let fields = Fields {
1218			secret: &secret,
1219			last_writer_wins: &last_writer_wins,
1220		};
1221		let index = MemoryPostings::default();
1222		let [from, into] = [writer.rng.entity_id(), writer.rng.entity_id()];
1223		let mut titles = BTreeMap::new();
1224		// The title of the entity merged into is written last.
1225		for (entity, text) in [(from, "Ada"), (into, "Lovelace")] {
1226			let statement = writer.statement(entity, &title, Value::Text(text.to_owned()));
1227			titles.insert(entity, statement.id);
1228			writer.commit(&index, fields, Operation::assert(statement));
1229		}
1230		let merge = writer.statement(from, &fields::MERGED_INTO, Value::Reference(into));
1231		let merged = merge.id;
1232		writer.commit(&index, fields, Operation::assert(merge));
1233		let built = MemoryPostings::default();
1234		build(&writer.log, &built, fields).infallible();
1235		assert_eq!(index, built);
1236		nibkeep_testkit::assert_empty!(search(&index, "ada").infallible());
1237		assert_eq!(
1238			search(&index, "lovelace").infallible(),
1239			vec![Found {
1240				entity: into,
1241				matching: 1,
1242			}]
1243		);
1244		// Undone, each shows its own title again.
1245		writer.commit(&index, fields, Operation::retract(from, [merged]));
1246		let built = MemoryPostings::default();
1247		build(&writer.log, &built, fields).infallible();
1248		assert_eq!(index, built);
1249		assert_eq!(
1250			search(&index, "ada").infallible(),
1251			vec![Found {
1252				entity: from,
1253				matching: 1,
1254			}]
1255		);
1256	}
1257
1258	/// Postings that count how often each word's and each beginning's statements are read,
1259	/// and each candidate's own statements.
1260	#[derive(Default)]
1261	struct Counting {
1262		postings: MemoryPostings,
1263		prefixes_read: std::cell::Cell<usize>,
1264		candidates_checked: std::cell::Cell<usize>,
1265	}
1266
1267	impl Postings for Counting {
1268		type Error = std::convert::Infallible;
1269		type Key = StatementId;
1270
1271		fn indexed(&self, id: StatementId) -> Result<Option<Indexed>, Self::Error> {
1272			self.postings.indexed(id)
1273		}
1274		fn insert(&self, id: StatementId, indexed: &Indexed) -> Result<(), Self::Error> {
1275			self.postings.insert(id, indexed)
1276		}
1277		fn remove(&self, id: StatementId) -> Result<(), Self::Error> {
1278			self.postings.remove(id)
1279		}
1280		fn clear(&self) -> Result<(), Self::Error> {
1281			self.postings.clear()
1282		}
1283		fn with_word(&self, word: &str) -> Result<Vec<(StatementId, EntityId)>, Self::Error> {
1284			self.postings.with_word(word)
1285		}
1286		fn word_count(&self, word: &str) -> Result<usize, Self::Error> {
1287			self.postings.word_count(word)
1288		}
1289		fn with_prefix(&self, prefix: &str) -> Result<Vec<(StatementId, EntityId)>, Self::Error> {
1290			self.prefixes_read.set(self.prefixes_read.get() + 1);
1291			self.postings.with_prefix(prefix)
1292		}
1293		fn prefix_count(&self, prefix: &str, at_most: usize) -> Result<usize, Self::Error> {
1294			self.postings.prefix_count(prefix, at_most)
1295		}
1296		fn shown_with_prefix(
1297			&self,
1298			entity: EntityId,
1299			prefix: &str,
1300		) -> Result<Vec<StatementId>, Self::Error> {
1301			self.candidates_checked
1302				.set(self.candidates_checked.get() + 1);
1303			self.postings.shown_with_prefix(entity, prefix)
1304		}
1305		fn with_value(
1306			&self,
1307			field: &FieldName,
1308			value: &Hash,
1309		) -> Result<Vec<EntityId>, Self::Error> {
1310			self.postings.with_value(field, value)
1311		}
1312		fn with_name(&self, lowered: &str) -> Result<Vec<EntityId>, Self::Error> {
1313			self.postings.with_name(lowered)
1314		}
1315		fn of_shown(&self, entity: EntityId) -> Result<Vec<(StatementId, Indexed)>, Self::Error> {
1316			self.postings.of_shown(entity)
1317		}
1318		fn set_deleted(&self, entity: EntityId, deleted: bool) -> Result<(), Self::Error> {
1319			self.postings.set_deleted(entity, deleted)
1320		}
1321		fn remove_field(&self, field: &FieldName) -> Result<(), Self::Error> {
1322			self.postings.remove_field(field)
1323		}
1324	}
1325
1326	#[test]
1327	fn the_last_word_is_read_unless_it_starts_many_more_statements_than_the_rarest_word() {
1328		let mut writer = Writer::new("the last word is read");
1329		let title: FieldName = "org.nibkeep.title".parse().expect("a field name");
1330		let (secret, last_writer_wins) = (BTreeSet::new(), BTreeSet::new());
1331		let fields = Fields {
1332			secret: &secret,
1333			last_writer_wins: &last_writer_wins,
1334		};
1335		let index = Counting::default();
1336		// Two entities hold "lovelace", one of them "ada" too; three more hold "adam", and ten
1337		// "adler".
1338		let texts = ["Ada Lovelace", "Lovelace"]
1339			.into_iter()
1340			.chain(std::iter::repeat_n("Adam", 3))
1341			.chain(std::iter::repeat_n("Adler", 10));
1342		for text in texts {
1343			let entity = writer.rng.entity_id();
1344			let statement = writer.statement(entity, &title, Value::Text(text.to_owned()));
1345			writer.commit(&index, fields, Operation::assert(statement));
1346		}
1347		// Two statements hold the rarest whole word, so a beginning that starts at most eight
1348		// is read: "ada" starts four, "ad" fourteen.
1349		for (query, read) in [("lovelace ada", true), ("lovelace ad", false)] {
1350			index.prefixes_read.set(0);
1351			index.candidates_checked.set(0);
1352			let found = search(&index, query).infallible();
1353			assert_eq!(found, every_statement(writer.log.state(), fields, query));
1354			assert_eq!(found.len(), 1, "{query}");
1355			assert_eq!(index.prefixes_read.get(), usize::from(read), "{query}");
1356			assert_eq!(
1357				index.candidates_checked.get(),
1358				if read { 0 } else { 2 },
1359				"{query}: each entity that holds the whole word is checked"
1360			);
1361		}
1362	}
1363
1364	#[test]
1365	fn a_text_holds_the_words_of_a_query_the_last_as_a_beginning() {
1366		let path = "/home/anna/Pictures/Été 2019/IMG_0042.JPG on Anna's laptop";
1367		assert!(holds_words(path, "ete img_0042"));
1368		assert!(holds_words(path, "pictures 2019 lap"));
1369		assert!(holds_words(path, "anna"));
1370		// Whole words but the last.
1371		assert!(!holds_words(path, "pict 2019"));
1372		assert!(!holds_words(path, "pictures phone"));
1373		assert!(!holds_words(path, " ,. "));
1374	}
1375
1376	#[test]
1377	fn words_are_compared_without_case_or_accents() {
1378		assert_eq!(words("Café Bleu, ZOË"), ["cafe", "bleu", "zoe"]);
1379		assert_eq!(words("Radio 5㎒ İstanbul"), ["radio", "5mhz", "istanbul"]);
1380		assert_eq!(words("netflix.com/ada"), ["netflix", "com", "ada"]);
1381		nibkeep_testkit::assert_empty!(words(" -- "));
1382	}
1383
1384	/// Where two indexes differ: the statements indexed in one and not the other, or
1385	/// differently, for a report.
1386	fn differences(index: &MemoryPostings, built: &MemoryPostings) -> String {
1387		use std::fmt::Write as _;
1388
1389		let (index, built) = (index.0.borrow(), built.0.borrow());
1390		let mut report = String::new();
1391		for id in index
1392			.indexed
1393			.keys()
1394			.chain(built.indexed.keys())
1395			.collect::<BTreeSet<_>>()
1396		{
1397			let (kept, expected) = (index.indexed.get(id), built.indexed.get(id));
1398			if kept != expected {
1399				let _ = write!(report, "\n{id}: indexed as {kept:?}, built as {expected:?}");
1400			}
1401		}
1402		report
1403	}
1404
1405	/// Receives changes in order, keeping an index of the state up to date and checking it
1406	/// against one built anew.
1407	fn read(
1408		log: &mut Log,
1409		index: &MemoryPostings,
1410		fields: Fields<'_>,
1411		keys: &SpaceKeys,
1412		changes: Vec<Parcel>,
1413		wall: u64,
1414	) {
1415		for change in changes {
1416			let received = log.receive(change, keys, wall).expect("accepts");
1417			if let Received::Accepted(_) = received {
1418				for (_, payload) in log.take_applied() {
1419					apply(log, index, fields, payload.all_operations()).infallible();
1420				}
1421				// Several changes can apply at once, and the index takes them in one by one
1422				// against the state that holds them all; after each batch it is exact.
1423				let built = MemoryPostings::default();
1424				build(log, &built, fields).infallible();
1425				assert!(
1426					*index == built,
1427					"the index follows the log{}",
1428					differences(index, &built)
1429				);
1430			}
1431		}
1432	}
1433
1434	/// The changes that three writers make through `steps` in a space, and the time of the
1435	/// last: statements are named by the order in which they were asserted, by any writer,
1436	/// merges among them since 2026-10-24, so the regression cases saved before then replay
1437	/// other steps than they were saved for.
1438	fn written(
1439		steps: Vec<Step>,
1440		space: SpaceId,
1441		keys: &SpaceKeys,
1442		entities: &[EntityId],
1443		rng: &mut TestRng,
1444	) -> (Vec<Parcel>, u64) {
1445		let title: FieldName = "org.nibkeep.title".parse().expect("a field name");
1446		let tag: FieldName = "org.nibkeep.tag".parse().expect("a field name");
1447		let mut writers: Vec<(SigningKey, Log)> = (0..3)
1448			.map(|_| (rng.signing_key(), Log::new(space, Clock::new(DRIFT))))
1449			.collect();
1450		let mut wall = millis_at("2026-10-12", 10, 0);
1451		let mut asserted: Vec<StatementId> = Vec::new();
1452		let mut of_entity: BTreeMap<StatementId, EntityId> = BTreeMap::new();
1453		let mut changes = Vec::new();
1454		for step in steps {
1455			let (writer, operation) = match step {
1456				Step::Assert {
1457					writer,
1458					entity,
1459					field,
1460					words,
1461					replaces,
1462					reuses,
1463				} => {
1464					let text: Vec<&str> = words.iter().map(|&word| WORDS[word]).collect();
1465					let replaced: Vec<StatementId> = replaces
1466						.iter()
1467						.filter_map(|&index| asserted.get(index).copied())
1468						.collect();
1469					let id = match reuses.and_then(|index| asserted.get(index)) {
1470						Some(&id) => id,
1471						None => rng.statement_id(),
1472					};
1473					asserted.push(id);
1474					of_entity.insert(id, entities[entity]);
1475					let statement = Statement::new(
1476						id,
1477						entities[entity],
1478						if field == 0 {
1479							title.clone()
1480						} else {
1481							tag.clone()
1482						},
1483						Value::Text(text.join(" ")),
1484					);
1485					(writer, Operation::replace(statement, replaced))
1486				}
1487				Step::Merge {
1488					writer,
1489					entity,
1490					into,
1491				} => {
1492					// A merge can be retracted and replaced, as the others can.
1493					let id = rng.statement_id();
1494					asserted.push(id);
1495					of_entity.insert(id, entities[entity]);
1496					let statement = Statement::new(
1497						id,
1498						entities[entity],
1499						fields::MERGED_INTO,
1500						Value::Reference(entities[into]),
1501					);
1502					(writer, Operation::assert(statement))
1503				}
1504				Step::Delete { writer, entity } => {
1505					let id = rng.statement_id();
1506					asserted.push(id);
1507					of_entity.insert(id, entities[entity]);
1508					let statement =
1509						Statement::new(id, entities[entity], fields::DELETED, Value::Boolean(true));
1510					(writer, Operation::assert(statement))
1511				}
1512				Step::Retract { writer, statements } => {
1513					let ids: Vec<StatementId> = statements
1514						.iter()
1515						.filter_map(|&index| asserted.get(index).copied())
1516						.collect();
1517					// A retraction names the entity of its first statement: those of others it
1518					// names are not superseded.
1519					let entity = ids
1520						.first()
1521						.and_then(|id| of_entity.get(id))
1522						.copied()
1523						.unwrap_or(entities[0]);
1524					(writer, Operation::retract(entity, ids))
1525				}
1526			};
1527			wall += 1_000;
1528			let (author, log) = &mut writers[writer];
1529			// A writer's own log may refuse a step, such as an ID it holds already.
1530			if let Ok(change) = log.commit(author, keys, vec![operation], wall, rng) {
1531				changes.push(change);
1532			}
1533		}
1534		(changes, wall)
1535	}
1536
1537	/// Checks that an index kept up to date through `steps`, received in order and in the
1538	/// order that `seed` shuffles them into, equals one built anew, and that searches and
1539	/// names answer as looking at every statement does.
1540	fn follows(steps: Vec<Step>, seed: u64, last_writer_wins: bool) -> Result<(), TestCaseError> {
1541		let mut rng = TestRng::new("the index follows changes");
1542		let space = rng.space_id();
1543		let keys = SpaceKeys::new(0, rng.key());
1544		let entities: Vec<EntityId> = (0..3).map(|_| rng.entity_id()).collect();
1545		let secret = BTreeSet::new();
1546		let last_writer_wins: BTreeSet<FieldName> = last_writer_wins
1547			.then(|| "org.nibkeep.title".parse().expect("a field name"))
1548			.into_iter()
1549			.collect();
1550		let fields = Fields {
1551			secret: &secret,
1552			last_writer_wins: &last_writer_wins,
1553		};
1554		let (changes, wall) = written(steps, space, &keys, &entities, &mut rng);
1555		let mut in_order = (
1556			Log::new(space, Clock::new(DRIFT)),
1557			MemoryPostings::default(),
1558		);
1559		read(
1560			&mut in_order.0,
1561			&in_order.1,
1562			fields,
1563			&keys,
1564			changes.clone(),
1565			wall,
1566		);
1567		let for_state_file = changes.clone();
1568		let mut shuffled = changes;
1569		shuffle(&mut shuffled, seed);
1570		let mut out_of_order = (
1571			Log::new(space, Clock::new(DRIFT)),
1572			MemoryPostings::default(),
1573		);
1574		read(
1575			&mut out_of_order.0,
1576			&out_of_order.1,
1577			fields,
1578			&keys,
1579			shuffled,
1580			wall,
1581		);
1582
1583		let built = MemoryPostings::default();
1584		build(&in_order.0, &built, fields).infallible();
1585		prop_assert_eq!(&in_order.1, &built);
1586		prop_assert_eq!(&out_of_order.1, &built);
1587		for query in [
1588			"ada",
1589			"ad",
1590			"cafe",
1591			"zoe lovelace",
1592			"CAF",
1593			"ada a",
1594			"lovelace ad",
1595		] {
1596			let expected = every_statement(in_order.0.state(), fields, query);
1597			prop_assert_eq!(search(&in_order.1, query).infallible(), expected.clone());
1598			prop_assert_eq!(search(&out_of_order.1, query).infallible(), expected);
1599		}
1600		for name in ["ada", "ada lovelace", "café", "cafe zoë", "lovelace ada"] {
1601			let expected = every_name(in_order.0.state(), fields, name);
1602			prop_assert_eq!(in_order.1.with_name(name).infallible(), expected.clone());
1603			prop_assert_eq!(out_of_order.1.with_name(name).infallible(), expected);
1604		}
1605		let received = (space, &keys, for_state_file, wall);
1606		same_postings(received, &built, fields, &entities)
1607	}
1608
1609	/// What postings in memory give, `found`, with each statement's number in a state file
1610	/// in place of its ID, sorted: the state file tells statements apart by those numbers.
1611	fn numbered<T: Ord>(state: &StateFile, found: Vec<(StatementId, T)>) -> Vec<(i64, T)> {
1612		sorted(
1613			found
1614				.into_iter()
1615				.map(|(id, value)| {
1616					let number = state.statement_number(id).expect("reads");
1617					(number.expect("held"), value)
1618				})
1619				.collect(),
1620		)
1621	}
1622
1623	fn sorted<T: Ord>(mut found: Vec<T>) -> Vec<T> {
1624		found.sort();
1625		found
1626	}
1627
1628	/// Each case of a state file gets a directory of its own.
1629	static STATE_FILES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1630
1631	/// Checks that the indexes that a state file builds of a log that has received
1632	/// `changes`, in one transaction, answer as those built in memory do, `built`. The file
1633	/// is in a directory of its own, removed once it is closed.
1634	fn same_postings(
1635		(space, keys, changes, wall): (SpaceId, &SpaceKeys, Vec<Parcel>, u64),
1636		built: &MemoryPostings,
1637		fields: Fields<'_>,
1638		entities: &[EntityId],
1639	) -> Result<(), TestCaseError> {
1640		let case = STATE_FILES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1641		let directory = nibkeep_testkit::empty_directory(
1642			std::env::temp_dir(),
1643			&format!("nibkeep-index-state-file-{}-{case}", std::process::id()),
1644		);
1645		let mut rng = TestRng::new("an index in a state file");
1646		let state = StateFile::open(&directory.join("state"), &rng.key(), rng).expect("opens");
1647		let mut log = Log::with_storage(space, Clock::new(DRIFT), state);
1648		log.storage_mut().begin().expect("begins");
1649		for change in changes {
1650			log.receive(change, keys, wall).expect("accepts");
1651			let _ = log.take_applied();
1652		}
1653		let postings = log.state().storage().ordinary();
1654		build(&log, postings, fields).expect("builds");
1655		let checked = (|| {
1656			for query in ["ada", "ad", "cafe", "zoe lovelace", "CAF", "ada a"] {
1657				prop_assert_eq!(
1658					search(postings, query).expect("searches"),
1659					search(built, query).infallible()
1660				);
1661			}
1662			for name in ["ada", "ada lovelace", "café", "lovelace ada"] {
1663				prop_assert_eq!(
1664					postings.with_name(name).expect("finds"),
1665					built.with_name(name).infallible()
1666				);
1667			}
1668			for word in WORDS.iter().flat_map(|word| words(word)) {
1669				prop_assert_eq!(
1670					sorted(postings.with_word(&word).expect("finds")),
1671					numbered(postings, built.with_word(&word).infallible())
1672				);
1673			}
1674			for prefix in ["a", "ad", "caf", "zoe", "lovelaces", ""] {
1675				prop_assert_eq!(
1676					sorted(postings.with_prefix(prefix).expect("finds")),
1677					numbered(postings, built.with_prefix(prefix).infallible())
1678				);
1679				for at_most in [0, 1, 3, usize::MAX] {
1680					prop_assert_eq!(
1681						postings.prefix_count(prefix, at_most).expect("counts"),
1682						built.prefix_count(prefix, at_most).infallible()
1683					);
1684				}
1685			}
1686			for &entity in entities {
1687				for prefix in ["a", "ad", "caf", "zoe", "lovelaces", ""] {
1688					let shown = |found: Vec<StatementId>| found.into_iter().map(|id| (id, ()));
1689					prop_assert_eq!(
1690						sorted(postings.shown_with_prefix(entity, prefix).expect("finds")),
1691						numbered(
1692							postings,
1693							shown(built.shown_with_prefix(entity, prefix).infallible()).collect()
1694						)
1695						.into_iter()
1696						.map(|(number, ())| number)
1697						.collect::<Vec<_>>()
1698					);
1699				}
1700				let sorted = |mut found: Vec<(StatementId, Indexed)>| {
1701					found.sort_by_key(|(id, _)| *id);
1702					found
1703				};
1704				prop_assert_eq!(
1705					sorted(postings.of_shown(entity).expect("finds")),
1706					sorted(built.of_shown(entity).infallible())
1707				);
1708			}
1709			Ok(())
1710		})();
1711		// Closed first: Windows does not delete a file that is open.
1712		drop(log);
1713		let _ = fs::remove_dir_all(directory);
1714		checked
1715	}
1716
1717	/// The special fields of a case: the title's last writer wins, or not, and the tag is
1718	/// secret, or not.
1719	fn special(title_wins: bool, tag_secret: bool) -> (BTreeSet<FieldName>, BTreeSet<FieldName>) {
1720		let title: FieldName = "org.nibkeep.title".parse().expect("a field name");
1721		let tag: FieldName = "org.nibkeep.tag".parse().expect("a field name");
1722		(
1723			tag_secret.then_some(tag).into_iter().collect(),
1724			title_wins.then_some(title).into_iter().collect(),
1725		)
1726	}
1727
1728	/// Checks that indexes built with one set of special fields and brought to another equal
1729	/// indexes built anew with the other, and back.
1730	fn follows_fields(
1731		steps: Vec<Step>,
1732		(was_wins, was_secret): (bool, bool),
1733		(now_wins, now_secret): (bool, bool),
1734	) -> Result<(), TestCaseError> {
1735		let mut rng = TestRng::new("the indexes follow the fields");
1736		let space = rng.space_id();
1737		let keys = SpaceKeys::new(0, rng.key());
1738		let entities: Vec<EntityId> = (0..3).map(|_| rng.entity_id()).collect();
1739		let (was, now) = (special(was_wins, was_secret), special(now_wins, now_secret));
1740		let was = Fields {
1741			secret: &was.0,
1742			last_writer_wins: &was.1,
1743		};
1744		let now = Fields {
1745			secret: &now.0,
1746			last_writer_wins: &now.1,
1747		};
1748		let (changes, wall) = written(steps, space, &keys, &entities, &mut rng);
1749		let mut log = Log::new(space, Clock::new(DRIFT));
1750		let index = MemoryPostings::default();
1751		read(&mut log, &index, was, &keys, changes, wall);
1752		for (from, to) in [(was, now), (now, was)] {
1753			rebuild_fields(&log, &index, from, to).infallible();
1754			let built = MemoryPostings::default();
1755			build(&log, &built, to).infallible();
1756			prop_assert_eq!(
1757				&index,
1758				&built,
1759				"from {:?} to {:?}",
1760				from.last_writer_wins,
1761				to.last_writer_wins
1762			);
1763		}
1764		Ok(())
1765	}
1766
1767	proptest! {
1768		// Every case makes and receives signed, encrypted changes, so fewer cases are run.
1769		#![proptest_config(ProptestConfig::with_cases(64))]
1770
1771		#[test]
1772		fn the_index_follows_changes_in_any_order(
1773			steps in prop::collection::vec(step(), 1..16),
1774			seed in 1..u64::MAX,
1775			last_writer_wins in any::<bool>(),
1776		) {
1777			follows(steps, seed, last_writer_wins)?;
1778		}
1779
1780		#[test]
1781		fn the_indexes_follow_the_fields(
1782			steps in prop::collection::vec(step(), 1..16),
1783			was in (any::<bool>(), any::<bool>()),
1784			now in (any::<bool>(), any::<bool>()),
1785		) {
1786			follows_fields(steps, was, now)?;
1787		}
1788	}
1789}