openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

Inverted index for cross-thread search in memory_conversations

Open mysma-9403 opened this issue 6 months ago • 0 comments

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 match Krakowa.
  • 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 (cat does not retrieve a message containing concatenate).

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 vs String.
  • docs: Vec<Option<DocEntry>> — tombstoned, so doc-ids in posting lists remain valid after deletes.
  • DocEntry::thread_id and role are interned Arc<str> — N messages on one thread share a single backing allocation. Significant resident-set savings at scale.

Query pipeline:

  1. 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.
  2. 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.
  3. Phase 2: exact substring verification on the normalized content. Score matched_terms / total_terms is preserved bit-for-bit with the legacy linear scan, including the created_at tiebreaker.

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_thread keep 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_at tiebreaker).
  • [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.

mysma-9403 avatar May 27 '26 11:05 mysma-9403