Inverted index for cross-thread search in memory_conversations
Summary
Replace the current O(threads × messages) linear scan in ConversationStore::search_cross_thread_messages with a character-n-gram inverted index, with first-class multilingual support (CJK, Arabic, Polish/Latin diacritics).
Problem
ConversationStore::search_cross_thread_messages (src/openhuman/memory_conversations/store.rs) is invoked by the agent's memory loader (src/openhuman/agent/memory_loader.rs:311) on every chat turn to surface cross-thread context. The current implementation walks every JSONL file in the workspace and does a per-message to_lowercase().contains(term) linear scan.
This costs O(N) per query where N is the total message count for the user. At a few hundred messages it is unnoticeable; at tens of thousands it adds tens to hundreds of ms to every chat turn, on top of the disk-IO cost of re-reading every JSONL on every search.
Additionally, the current code only does ASCII-style lowercase + literal substring match, which has subtle multilingual failures:
- Querying without Polish diacritics (
krakow) does not matchKrakowa. - Querying Arabic without harakat (
كتب) does not match the same word with vocalization (كَتَبَ). - Half-width and full-width CJK forms are treated as distinct strings.
- Tokens on word boundaries miss substring-inside-word cases (
catdoes not retrieve a message containingconcatenate).
Solution
Two-phase character-n-gram inverted index, lazy-built from the JSONL source of truth and cached per workspace.
Normalization pipeline (shared by indexing and query):
- NFKD decomposition → strip combining marks via
canonical_combining_class→ lowercase → NFKC recompose. - Small fold table for letters NFKD leaves unchanged:
ł → l,ø → o,ß → ss,æ → ae,œ → oe,þ → th,ð → d,đ → d,ħ → h,ı → i,ŋ → n.
Tokenization:
- Trigrams for non-CJK runs (Latin, Cyrillic, Arabic, …).
- Bigrams for CJK runs (Han, Hiragana, Katakana, Hangul) — keeps the posting dictionary bounded across the tens of thousands of CJK characters.
Index data structures (in-memory, per workspace):
postings: HashMap<Box<str>, BTreeSet<u32>>—Box<str>keys to save 8 bytes per entry vsString.docs: Vec<Option<DocEntry>>— tombstoned, so doc-ids in posting lists remain valid after deletes.DocEntry::thread_idandroleare internedArc<str>— N messages on one thread share a single backing allocation. Significant resident-set savings at scale.
Query pipeline:
- Phase 1: for each query term, intersect ngram posting lists with a two-pointer sort-merge over a single
Vec<u32>accumulator — zero allocations per intersected ngram. - Pathological short-circuit: if any term's Phase 1 set exceeds 10k, skip Phase 2 and return recency-ordered results. The check fires before the substring loop so it genuinely caps tail latency.
- Phase 2: exact substring verification on the normalized content. Score
matched_terms / total_termsis preserved bit-for-bit with the legacy linear scan, including thecreated_attiebreaker.
Cache and persistence:
- The JSONL files remain the source of truth; the index is a derived cache rebuilt lazily on first access (also after
purge_threads). append_message/delete_threadkeep the cache incrementally in sync without rebuilding.- Cache is keyed by workspace path; protected by an inner mutex that is strictly nested inside
CONVERSATION_STORE_LOCK(lock-ordering invariant documented at the static).
Background and prior art
Approach informed by a deep-research review of indexing strategies. Long-term destination (deferred to follow-up PRs once benchmarks justify the complexity): Roaring Bitmaps for posting lists, FST + LSM-style persisted segments with mmap, BM25 with recency decay, query-side term ordering by selectivity, and lock-free reads via arc-swap.
Acceptance criteria
- [x] Inverted index replaces the linear scan in
search_cross_thread_messages. - [x] Multilingual normalization: Polish/Latin diacritics, Arabic harakat, CJK half/full-width unification, ł/ß/ø/æ/þ/ð folding.
- [x] CJK bigram tokenization keeps posting dictionary bounded.
- [x] Lock-ordering invariant documented; lazy cache rebuild from JSONL on first access.
- [x] Score semantics preserved (legacy
matched_terms / total_terms+created_attiebreaker). - [x] Diff coverage ≥ 80% — implementing PR adds 14 new unit/integration tests (Polish, Japanese, Arabic, intern pool, sort-merge intersect, on-disk rebuild, pathological short-circuit).
Related
Implementing PR: see linked PR below.