diff --git a/CHANGELOG.md b/CHANGELOG.md index 5591089..5db106e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ internal versions are summarized under 0.3.33. ## [Unreleased] ### Fixed -- `query_terms()` now preserves 3–4 character all-uppercase acronyms (such as `HIV` and `EGFR`) instead of lowercasing tokens before checking case. (#9) +- `query_terms()`, `find_rare_terms()`, and Stage-2 lexical front-loading now retain 3–4 character all-uppercase acronyms (such as `HIV`, `EGFR`, and `ALL`, plus plurals like `TLRs`) with word-boundary matching that still accepts plural, numbered, and inhibitor forms (`RNAs`, `TLR4`, `ACEi`), prioritize digit/hyphen and long-term matches ahead of acronyms, and normalize SQLite-compatible dashes and subscripts before tokenizing. All-caps prose such as `WHAT IS THE ROLE OF RNA` does not turn ordinary words into acronyms, while all-caps keyword queries such as `EGFR NSCLC` keep theirs. (#9) ## [0.3.36] - 2026-11-30 diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index 20ffc5a..32abc74 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -5,55 +5,149 @@ """ from __future__ import annotations -import os import re import unicodedata from pathlib import Path - # Stopwords for query term filtering _STOPWORDS = { "the", "and", "for", "with", "that", "this", "from", "into", "your", "about", "does", "what", "when", "where", "which", "who", "whom", "whose", "why", "how", "are", "is", "was", "were", "be", "been", "being", "of", "on", "in", "to", "a", "an", "as", "by", "at", "it", - "its", "their", "them", "we", "you", "i", + "its", "their", "them", "we", "you", "i", "can", "did", "not", "may", + "has", "had", "but", "one", "use", "will", } +# "all" is deliberately absent: as "ALL" it is acute lymphoblastic leukemia. + +_ACRONYM_MAX_LEN = 4 +_ALPHA_WORD_RE = re.compile(r"[A-Za-z]+") +# Lowercase plural "s" on an all-caps token ("TLRs", "RCTs", "CD4s"). +_CAPS_PLURAL_S_RE = re.compile(r"(?<=[A-Z0-9])s\b") +# In all-caps text, a word this long with 2+ vowels reads as ordinary prose +# (LYMPHOMA, SIGNALING, CANCER), while long acronyms are usually vowel-poor +# (CRISPR, NSCLC, VEGFR). Five-letter words are ambiguous (COVID vs TUMOR), so +# they are not evidence either way. +_PROSE_WORD_MIN_LEN = 6 +_VOWELS = frozenset("AEIOU") +_TOKEN_RE = re.compile(r"[A-Za-z0-9]+(?:[-_][A-Za-z0-9]+)*") +_EN_FIGURE_DASH_BETWEEN_ALNUM_RE = re.compile(r"(?<=[A-Za-z0-9])[\u2012\u2013](?=[A-Za-z0-9])") + +# Single source of truth shared by sqlite_norm_expr() and normalize_for_search_py(). +_SQLITE_NORM_REPLACEMENTS: tuple[tuple[str, str], ...] = ( + ("\u00ad", ""), # soft hyphen (strip) + ("\u2010", "-"), # hyphen + ("\u2011", "-"), # non-breaking hyphen + ("\u2012", "-"), # figure dash + ("\u2013", "-"), # en dash + ("\u2014", "-"), # em dash + ("\u2212", "-"), # minus sign + *zip("₀₁₂₃₄₅₆₇₈₉", "0123456789", strict=True), +) +_SQLITE_NORM_TRANS = str.maketrans(dict(_SQLITE_NORM_REPLACEMENTS)) + +# Tokenization mapping derived from _SQLITE_NORM_REPLACEMENTS (no NFKC until #20): +# em dashes separate words instead of joining them, and en/figure dashes are handled +# contextually so "Michaelis–Menten" joins while "cells – specifically" splits. +_TOKENIZE_TRANS = str.maketrans( + { + **{ + ch: repl + for ch, repl in _SQLITE_NORM_REPLACEMENTS + if ch not in ("\u2012", "\u2013", "\u2014") + }, + "\u2014": " ", + } +) + + +def _normalize_for_tokenize(s: str) -> str: + """Normalize SQLite-compatible dashes/subscripts without fusing prose.""" + out = s.translate(_TOKENIZE_TRANS) + out = _EN_FIGURE_DASH_BETWEEN_ALNUM_RE.sub("-", out) + return out.replace("\u2012", " ").replace("\u2013", " ") + + +def _is_prose_word(word: str) -> bool: + """Whether an all-caps word reads as ordinary prose rather than an acronym.""" + lowered = word.lower() + if lowered in _STOPWORDS and lowered != "and": + return True + return len(word) >= _PROSE_WORD_MIN_LEN and sum(ch in _VOWELS for ch in word.upper()) >= 2 + + +def _is_all_caps_prose(s: str) -> bool: + """Detect all-caps sentences/headings where uppercase does not mark acronyms. + + True only when the text has no lowercase ASCII letters (ignoring the plural + "s" of tokens like "TLRs") and contains a stopword or a long, vowel-rich word: + "WHAT IS THE ROLE OF RNA" and "B CELL LYMPHOMA" are prose, while keyword + queries such as "EGFR NSCLC" or "HIV CRISPR" keep their acronyms. + """ + if any(ch.isascii() and ch.islower() for ch in _CAPS_PLURAL_S_RE.sub("", s)): + return False + return any(_is_prose_word(w) for w in _ALPHA_WORD_RE.findall(s) if len(w) >= 2) + + +def _acronym_stem(token: str) -> str | None: + """Return the 3-4 character all-caps acronym in a token, or None. + + A lowercase plural "s" is dropped ("TLRs" -> "TLR") so the term also matches + the singular and numbered forms in the corpus. + """ + stem = token[:-1] if len(token) > 3 and token.endswith("s") else token + if 3 <= len(stem) <= _ACRONYM_MAX_LEN and stem.isupper(): + return stem + return None + + +def _extract_query_terms(s: str) -> list[tuple[str, bool]]: + """Extract normalized query terms paired with an acronym flag. + + Applies SQLite-compatible dash and subscript normalization (without NFKC) + before tokenizing ASCII alphanumeric/hyphen/underscore words of at least 3 + characters, checking uppercase status before lowercasing. All-uppercase + 3-4 character tokens, and their lowercase-"s" plurals, are flagged as + acronyms unless the input is all-caps prose. + """ + normalized = _normalize_for_tokenize(s) + allow_acronyms = not _is_all_caps_prose(normalized) + out: list[tuple[str, bool]] = [] + seen: set[str] = set() + for w in _TOKEN_RE.findall(normalized): + if len(w) < 3: + continue + stem = _acronym_stem(w) if allow_acronyms else None + term = (stem or w).lower() + if term in _STOPWORDS or term in seen: + continue + is_acronym = stem is not None + if len(w) >= 5 or is_acronym or any(ch.isdigit() for ch in w) or "_" in w or "-" in w: + seen.add(term) + out.append((term, is_acronym)) + return out def query_terms(s: str) -> list[str]: """Extract meaningful query terms from a string. - - Extracts alphanumeric tokens, lowercases them, and filters out - short/common words. Keeps tokens that are: + + Normalizes SQLite-compatible dashes and subscript digits, extracts + hyphen/underscore-joined ASCII alphanumeric tokens of 3+ characters, + filters out stopwords, and lowercases kept terms while preserving order. + Keeps tokens that are: - 5+ characters long - - All uppercase and 3+ chars + - 3-4 character all-uppercase acronyms, plural "s" dropped (unless input + is all-caps prose) - Contain digits - Contain underscores or hyphens - + Args: s: Input string (typically a question) - + Returns: List of unique query terms in original order """ - words = re.findall(r"[A-Za-z0-9_-]{3,}", s) - out = [] - seen = set() - for w in words: - lowered = w.lower() - if lowered in _STOPWORDS or lowered in seen: - continue - if ( - len(w) >= 5 - or (w.isupper() and len(w) >= 3) - or any(ch.isdigit() for ch in w) - or "_" in w - or "-" in w - ): - seen.add(lowered) - out.append(lowered) - return out + return [term for term, _ in _extract_query_terms(s)] def sqlite_norm_expr(field: str = "text") -> str: @@ -71,21 +165,8 @@ def sqlite_norm_expr(field: str = "text") -> str: SQL expression string """ f = f"lower({field})" - # Hyphen/minus variants: U+2010..U+2014, U+2212, plus soft hyphen - for ch, repl in [ - ("\u00ad", ""), # soft hyphen (strip) - ("\u2010", "-"), # hyphen - ("\u2011", "-"), # non-breaking hyphen - ("\u2012", "-"), # figure dash - ("\u2013", "-"), # en dash - ("\u2014", "-"), # em dash - ("\u2212", "-"), # minus sign - ]: + for ch, repl in _SQLITE_NORM_REPLACEMENTS: f = f"replace({f}, '{ch}', '{repl}')" - # Subscript digits → ASCII - subs = "₀₁₂₃₄₅₆₇₈₉" - for d_sub, d in zip(subs, "0123456789", strict=False): - f = f"replace({f}, '{d_sub}', '{d}')" return f @@ -118,19 +199,7 @@ def normalize_for_search_py(s: str) -> str: Returns: Normalized string """ - s = unicodedata.normalize("NFKC", s).lower() - for ch, repl in [ - ("\u00ad", ""), - ("\u2010", "-"), - ("\u2011", "-"), - ("\u2012", "-"), - ("\u2013", "-"), - ("\u2014", "-"), - ("\u2212", "-"), - ]: - s = s.replace(ch, repl) - trans = str.maketrans("₀₁₂₃₄₅₆₇₈₉", "0123456789") - return s.translate(trans) + return unicodedata.normalize("NFKC", s).lower().translate(_SQLITE_NORM_TRANS) def avg_chunks_for_papers( diff --git a/src/litkit/retrieval/lexical.py b/src/litkit/retrieval/lexical.py index 84964d2..f2a1343 100644 --- a/src/litkit/retrieval/lexical.py +++ b/src/litkit/retrieval/lexical.py @@ -4,6 +4,7 @@ Lexical front-loading improves recall for queries containing: - Technical terms with digits (e.g., "H1N1", "SARS-CoV-2", "IL-6") - Hyphenated compound terms (e.g., "angiotensin-converting") +- All-uppercase acronyms (e.g., "HIV", "EGFR") - Very long specific terms (e.g., "methyltransferase") These terms often have exact matches in the corpus that ANN may miss. @@ -20,28 +21,50 @@ import re import sqlite3 from dataclasses import dataclass, field +from functools import lru_cache from typing import TYPE_CHECKING, Protocol from litkit.retrieval.helpers import ( - query_terms, - sqlite_norm_expr, + _ACRONYM_MAX_LEN, + _extract_query_terms, escape_like, normalize_for_search_py, + sqlite_norm_expr, ) -from litkit.progress import eprint as _eprint if TYPE_CHECKING: from sqlite3 import Connection -# Stopwords for query term filtering (shared with helpers.py) -_STOPWORDS = { - "the", "and", "for", "with", "that", "this", "from", "into", "your", - "about", "does", "what", "when", "where", "which", "who", "whom", - "whose", "why", "how", "are", "is", "was", "were", "be", "been", - "being", "of", "on", "in", "to", "a", "an", "as", "by", "at", "it", - "its", "their", "them", "we", "you", "i", -} +@lru_cache(maxsize=256) +def _word_boundary_re(term: str) -> re.Pattern[str]: + # ASCII alphanumeric boundaries (matching _TOKEN_RE), so 'rna' matches + # 'RNA-seq', '(RNA)' and 'TNFα' but not 'journal' or 'internal'. An + # optional plural "s", inhibitor "i", or number (plus one letter) suffix keeps + # forms such as 'RNAs', 'RNAi', 'ACEi', 'TLR4', 'JAK2/STAT3' and 'STAT5a'. + # IGNORECASE with ASCII mirrors SQLite's ASCII-only lower(). + return re.compile( + rf"(? int: + """SQLite function: 1 if ``term`` occurs in ``text`` on word boundaries, else 0. + + Takes the raw column so SQLite evaluates the sqlite_norm_expr() chain only + once per row (for the LIKE prefilter). Of that chain, only soft-hyphen + removal can change which characters are adjacent to a term, so it is the + only replacement repeated here; Unicode dashes and subscript digits act as + boundaries either way. + """ + if not isinstance(text, str) or not isinstance(term, str) or not text or not term: + return 0 + return 1 if _word_boundary_re(term).search(text.replace("\u00ad", "")) else 0 + + +def _needs_word_boundary(norm_term: str) -> bool: + return norm_term.isascii() and norm_term.isalpha() and len(norm_term) <= _ACRONYM_MAX_LEN @dataclass @@ -60,7 +83,7 @@ class LexicalConfig: allow_global: Force global scope (ignore candidate filter) min_term_length: Threshold for long-term fallback max_terms: Cap # of rare terms to use - require_rare_terms: If False, allow long-only matches + require_rare_terms: Ignored; the long-term fallback runs whenever no digit or hyphen/underscore terms are found """ enabled: bool = True cap: int | None = None @@ -114,40 +137,41 @@ def search( def find_rare_terms(question: str, config: LexicalConfig) -> list[str]: """Extract rare/technical terms that benefit from exact match. - + This is a pure function - no DB dependencies, easy to test. - + Prioritizes: - 1. Terms with digits (H1N1, IL-6, CD4) - 2. Terms with LIKE-sensitive chars (hyphens, underscores, %, \\) - 3. Very long terms (config.min_term_length+) as fallback - + 1. Terms with digits (H1N1, IL-6, CD4) or hyphens/underscores (P-gp, a_b) + 2. Long terms (config.min_term_length+) as fallback when tier 1 is empty + 3. 3-4 character all-uppercase acronyms (HIV, EGFR; TLRs -> tlr), ordered after higher + tiers so they never crowd out digit/hyphen terms or disable fallback + Args: question: The user's question config: LexicalConfig with min_term_length and max_terms - + Returns: List of rare terms, capped at config.max_terms """ - # Use shared query_terms for base extraction - terms = query_terms(question) - - # Find "rare" terms: digits or LIKE-sensitive chars - rare = [ - t for t in terms - if any(ch.isdigit() for ch in t) - or any(ch in "-_%\\" for ch in t) - ] - - # Fallback: long terms if no rare terms and not requiring rare - if not rare: - if config.require_rare_terms: - # Still try long terms as fallback - rare = [t for t in terms if len(t) >= config.min_term_length] - else: - rare = [t for t in terms if len(t) >= config.min_term_length] - - return rare[:config.max_terms] + # Use shared extraction so acronym flags are preserved before lowercasing + terms = _extract_query_terms(question) + + # Priority 1: digits or hyphens/underscores + primary = [t for t, _ in terms if any(ch.isdigit() for ch in t) or any(ch in "-_" for ch in t)] + primary_set = set(primary) + + # Priority 3: 3-4 char all-uppercase acronyms not already in priority 1 + acronyms = [t for t, is_acronym in terms if is_acronym and t not in primary_set] + + if primary: + rare = primary + acronyms + else: + # Priority 2 fallback: long terms still run even when acronyms are present + long_terms = [t for t, _ in terms if len(t) >= config.min_term_length] + long_set = set(long_terms) + rare = long_terms + [t for t in acronyms if t not in long_set] + + return rare[: config.max_terms] class SqliteLexicalBackend: @@ -173,6 +197,7 @@ def __init__( self.db_conn = db_conn self.load_temp_candidates = load_temp_candidates self._warn_once = False + self.db_conn.create_function("litkit_word_match", 2, _word_match, deterministic=True) def search( self, @@ -194,22 +219,40 @@ def search( scope = "global" if candidate_papers is None else "candidates" - # Build LIKE clause with normalization - norm = sqlite_norm_expr("text") - like_parts = [f"{norm} LIKE ? ESCAPE '\\'"] * len(terms) + # Build LIKE clause with normalization; short alphabetic terms (such as + # 3-4 char acronyms) also require word boundaries so 'rna' does not + # match 'journal' or 'internal'. + norm = sqlite_norm_expr("c.text") + like_parts: list[str] = [] + params: list[object] = [] + for t in terms: + nt = normalize_for_search_py(t) + like_param = f"%{escape_like(nt)}%" + if _needs_word_boundary(nt): + like_parts.append( + f"({norm} LIKE ? ESCAPE '\\' AND litkit_word_match(c.text, ?))" + ) + params.extend([like_param, nt]) + else: + like_parts.append(f"{norm} LIKE ? ESCAPE '\\'") + params.append(like_param) like_clause = " OR ".join(like_parts) - params = [ - f"%{escape_like(normalize_for_search_py(t))}%" - for t in terms - ] - + # Title hint for sorting (prefer chunks from papers with matching title) title_hint = normalize_for_search_py(terms[0] if terms else "") - title_like_param = f"%{escape_like(title_hint)}%" if title_hint else "%" - + title_norm = sqlite_norm_expr("p.title") + if title_hint and _needs_word_boundary(title_hint): + title_expr = ( + f"({title_norm} LIKE ? ESCAPE '\\' AND litkit_word_match(p.title, ?))" + ) + title_params: list[object] = [f"%{escape_like(title_hint)}%", title_hint] + else: + title_expr = f"{title_norm} LIKE ? ESCAPE '\\'" + title_params = [f"%{escape_like(title_hint)}%" if title_hint else "%"] + cur = self.db_conn.cursor() chunk_ids: list[int] = [] - + try: if scope == "global": cur.execute( @@ -217,15 +260,15 @@ def search( SELECT c.id FROM chunks c JOIN papers p ON p.id = c.paper_id - WHERE ({like_clause.replace('text', 'c.text')}) + WHERE ({like_clause}) ORDER BY (c.ord = -1) DESC, - ({sqlite_norm_expr('p.title')} LIKE ? ESCAPE '\\') DESC, + ({title_expr}) DESC, (p.pmid IS NOT NULL) DESC, (p.pmcid IS NOT NULL) DESC, c.id ASC LIMIT ? """, - params + [title_like_param, config.limit], + params + title_params + [config.limit], ) else: # Scope to candidate papers @@ -235,16 +278,16 @@ def search( SELECT c.id FROM chunks c JOIN papers p ON p.id = c.paper_id - WHERE ({like_clause.replace('text', 'c.text')}) + WHERE ({like_clause}) AND c.paper_id IN (SELECT id FROM cand_papers) ORDER BY (c.ord = -1) DESC, - ({sqlite_norm_expr('p.title')} LIKE ? ESCAPE '\\') DESC, + ({title_expr}) DESC, (p.pmid IS NOT NULL) DESC, (p.pmcid IS NOT NULL) DESC, c.id ASC LIMIT ? """, - params + [title_like_param, config.limit], + params + title_params + [config.limit], ) chunk_ids = [row[0] for row in cur.fetchall()] diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index 9de26f5..0c43de6 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -3,11 +3,15 @@ import sqlite3 +import faiss +import numpy as np import pytest -from litkit.db import connect_db, init_db, load_temp_candidates +from litkit.db import chunk_ids_to_paper_ids, connect_db, init_db, load_temp_candidates from litkit.frontload.cap import cap_chunks_per_paper +from litkit.index import flat_ip_index from litkit.index.search import pick_nprobe +from litkit.retrieval import search_chunks_constrained from litkit.retrieval.helpers import ( escape_like, normalize_for_search_py, @@ -40,9 +44,53 @@ def test_query_terms_keeps_short_hyphen_and_underscore_terms(): def test_query_terms_keeps_uppercase_acronyms(): assert query_terms("Does HIV bind CD4 via EGFR?") == ["hiv", "cd4", "egfr"] # Uppercase stopwords are still filtered; title/lowercase short words are dropped; - # uppercase acronyms are lowercased and deduplicated. + # uppercase acronyms are lowercased and deduplicated regardless of order. assert query_terms("HOW DOES HIV AND EGFR act in the body?") == ["hiv", "egfr"] assert query_terms("Can hiv and HIV bind RNA or rna?") == ["hiv", "rna"] + assert query_terms("HIV and hiv; METHYLTRANSFERASE and methyltransferase") == [ + "hiv", + "methyltransferase", + ] + # ALL (acute lymphoblastic leukemia) is an acronym, not a stopword. + assert query_terms("ALL") == ["all"] + # Plural acronyms keep their 3-4 letter stem, so they also match singular forms. + assert query_terms("Do TLRs, RCTs and GPCRs agree?") == ["tlr", "rct", "gpcr", "agree"] + assert query_terms("HIV and HIVs") == ["hiv"] + + +def test_query_terms_handles_edge_cases_and_unicode(): + assert query_terms("") == [] + assert query_terms(" ") == [] + assert query_terms("HOW DOES THE") == [] + # Mixed-case 3-4 letter terms are not treated as all-uppercase acronyms. + assert query_terms("Does mRNA or IgG bind Hiv?") == [] + # All-caps prose does not turn ordinary 3-4 letter words into acronyms. + assert query_terms("HOW DOES HIV AND EGFR ACT IN THE BODY?") == [] + assert query_terms("WHAT IS THE ROLE OF RNA IN CELL SIGNALING?") == ["signaling"] + # Punctuation-only sequences are ignored; trailing hyphens before non-ASCII are dropped. + assert query_terms("--- ___ TNF-α") == ["tnf"] + # Em dashes and spaced en dashes separate words; non-spaced en dashes join compounds. + assert query_terms("What causes fibrosis\u2014specifically methyltransferase?") == [ + "causes", + "fibrosis", + "specifically", + "methyltransferase", + ] + assert query_terms("HIV\u2014a retrovirus") == ["hiv", "retrovirus"] + assert query_terms("Michaelis\u2013Menten and cells \u2013 specifically") == [ + "michaelis-menten", + "cells", + "specifically", + ] + # SQLite-supported hyphens and subscripts normalize; superscripts (no NFKC in SQL) do not. + assert query_terms("Is IL\u20116 and IC\u2085\u2080 of CO\u2082 raised?") == [ + "il-6", + "ic50", + "co2", + "raised", + ] + assert query_terms("concentration 10\u207b\u00b3 M") == ["concentration"] + assert query_terms("Ca\u00b2\u207a signaling") == ["signaling"] def test_find_rare_terms_prefers_digits_and_hyphens(): @@ -53,8 +101,67 @@ def test_find_rare_terms_prefers_digits_and_hyphens(): ] +def test_find_rare_terms_keeps_uppercase_acronyms(): + cfg = LexicalConfig() + # Tier 1 (digits/hyphens) precedes tier 2 (3-4 char acronyms) before max_terms. + assert find_rare_terms("Does HIV bind CD4 via EGFR?", cfg) == ["cd4", "hiv", "egfr"] + assert find_rare_terms("How does HIV infect cells?", cfg) == ["hiv"] + assert find_rare_terms("HOW DOES HIV AND EGFR act in the body?", cfg) == ["hiv", "egfr"] + # Acronyms do not push digit/hyphen terms past max_terms. + assert find_rare_terms( + "Do TNF, IFN, VEGF, EGFR, KRAS, BRAF, PTEN, MYC and IL-6 interact?", cfg + ) == ["il-6", "tnf", "ifn", "vegf", "egfr", "kras", "braf", "pten"] + # Acronyms do not suppress the long-term fallback when no tier-1 terms exist. + assert find_rare_terms("How does HIV integrase use methyltransferase activity?", cfg) == [ + "integrase", + "methyltransferase", + "hiv", + ] + assert find_rare_terms("Does ACE inhibition reduce fibrosis?", cfg) == ["inhibition", "ace"] + # All-caps prose and headings do not turn ordinary 3-4 letter words into acronyms. + assert find_rare_terms("HOW DOES HIV AND EGFR ACT IN THE BODY?", cfg) == [] + assert find_rare_terms("WHAT IS THE ROLE OF RNA IN CELL SIGNALING?", cfg) == ["signaling"] + assert find_rare_terms("WHAT IS THE ROLE OF TNF\u03b1 IN CELL SIGNALING?", cfg) == ["signaling"] + assert find_rare_terms("CAN HIV BIND EGFR?", cfg) == [] + assert find_rare_terms("B CELL LYMPHOMA", cfg) == [] + # All-caps keyword queries keep their acronyms: long acronyms are vowel-poor + # (NSCLC, VEGFR, CRISPR), so unlike LYMPHOMA they do not mark the text as prose. + assert find_rare_terms("EGFR NSCLC", cfg) == ["egfr"] + assert find_rare_terms("VEGFR HCC", cfg) == ["hcc"] + assert find_rare_terms("HIV CRISPR", cfg) == ["hiv"] + # A plural acronym's lowercase "s" does not make all-caps prose look mixed-case. + assert find_rare_terms("WHAT IS THE ROLE OF TLRs IN SEPSIS?", cfg) == [] + assert find_rare_terms("Roles of PROTEIN KINASE in CANCER", cfg) == [] + assert find_rare_terms("CANCER and cancer", cfg) == [] + assert find_rare_terms("cancer and CANCER", cfg) == [] + # Mixed-case queries starting with "A "/"I " or with 5+ char acronyms still keep acronyms. + assert find_rare_terms("A DNA/RNA assay", cfg) == ["dna", "rna"] + assert find_rare_terms("A JAK/STAT pathway", cfg) == ["jak", "stat"] + assert find_rare_terms("I study HIV and RNA", cfg) == ["hiv", "rna"] + assert find_rare_terms("CRISPR ELISA HIV assay", cfg) == ["hiv"] + # ALL (acute lymphoblastic leukemia) is searched like any other acronym. + assert find_rare_terms("What is the prognosis of pediatric ALL?", cfg) == [ + "prognosis", + "pediatric", + "all", + ] + assert find_rare_terms("ALL vs AML outcomes", cfg) == ["all", "aml"] + # Plural acronyms in the question are searched by their stem. + assert find_rare_terms("Do TLRs sense RNA viruses?", cfg) == ["tlr", "rna"] + # Known limitation: a 3-4 letter word written in caps for emphasis in a mixed-case + # question cannot be told apart from an acronym, so it is searched (word-bounded). + assert find_rare_terms("What is the ROLE of HIV?", cfg) == ["role", "hiv"] + # Em dashes and superscripts do not create bogus rare terms that kill fallback. + assert find_rare_terms( + "What causes fibrosis\u2014specifically methyltransferase dysregulation?", cfg + ) == ["specifically", "methyltransferase", "dysregulation"] + assert find_rare_terms("HIV\u2014a retrovirus", cfg) == ["retrovirus", "hiv"] + assert find_rare_terms("concentration 10\u207b\u00b3 M", cfg) == ["concentration"] + assert find_rare_terms("Ca\u00b2\u207a signaling", cfg) == ["signaling"] + + def test_find_rare_terms_falls_back_to_long_terms_and_caps(): - # No digits or hyphens: terms of min_term_length (9) or more are used. + # No digits, hyphens, or acronyms: terms of min_term_length (9) or more are used. assert find_rare_terms("explain methyltransferase pathways", LexicalConfig()) == [ "methyltransferase" ] @@ -182,6 +289,117 @@ def test_lexical_search_respects_limit_and_disable(lexical_db): assert backend.search([], None, LexicalConfig()).chunk_ids == [] +def test_lexical_search_word_boundaries_for_short_acronyms(tmp_path): + """Short alphabetic terms must match on word boundaries, not inside other words.""" + conn = init_db(tmp_path / "acronyms.sqlite3") + conn.executemany( + "INSERT INTO papers(id, doc_id, pmid, pmcid, title) VALUES (?, ?, ?, ?, ?)", + [ + (1, "d1", "1", "PMC1", "Journal of Internal Medicine"), + (2, "d2", "2", "PMC2", "RNA splicing mechanisms"), + ], + ) + conn.executemany( + "INSERT INTO chunks(id, paper_id, ord, text) VALUES (?, ?, ?, ?)", + [ + (10, 1, -1, "Published in this journal as an internal alternative control."), + (11, 1, 0, "Carcinoma and cardiac carbon statistics on archived surface data."), + (12, 2, 0, "RNA-seq confirms RNA splicing in CAR T cells."), + (13, 2, 1, "ACE inhibition blocks (HIV) and HIV-1 entry."), + (14, 2, 2, "TNF\u03b1 and IFN\u03b3 regulate signaling."), + # Plural, numbered, and inhibitor forms of an acronym still match. + (15, 2, 3, "JAK2/STAT3 and TLR4 signaling drive CARs."), + (16, 2, 4, "Long noncoding RNAs, RNAi, HIV1 isolates and ACEi therapy."), + # A soft hyphen inside the acronym is ignored, as in sqlite_norm_expr(); + # a lowercase prefix ("mRNA") is a different word. + (17, 2, 5, "mRNA vaccines elicit anti\u2011H\u00adIV responses."), + ], + ) + conn.commit() + try: + backend = SqliteLexicalBackend(conn, load_temp_candidates) + + def ids(term): + return backend.search([term], None, LexicalConfig()).chunk_ids + + assert ids("rna") == [12, 16] + assert ids("car") == [12, 15] + assert ids("hiv") == [13, 16, 17] + assert ids("ace") == [13, 16] + assert ids("tnf") == [14] + assert ids("ifn") == [14] + assert ids("jak") == [15] + assert ids("stat") == [15] + assert ids("tlr") == [15] + finally: + conn.close() + + +def test_stage2_lexical_frontloads_uppercase_acronyms(tmp_path): + """Acronym queries front-load true word matches, not substring false positives.""" + db_path = tmp_path / "stage2.sqlite3" + conn = init_db(db_path) + conn.execute( + "INSERT INTO papers(id, doc_id, pmid, pmcid, title) VALUES (?, ?, ?, ?, ?)", + (1, "d1", "1", "PMC1", "Retrovirus interactions"), + ) + conn.executemany( + "INSERT INTO chunks(id, paper_id, ord, text) VALUES (?, ?, ?, ?)", + [ + (10, 1, 0, "unrelated background text"), + (11, 1, 1, "HIV binds EGFR on target cells"), + (12, 1, 2, "published in an internal journal with archived records"), + ], + ) + conn.commit() + conn.close() + + index_path = tmp_path / "chunks.index" + index = faiss.IndexIDMap2(flat_ip_index(4)) + # Chunk 10 aligns with the query vector; chunks 11 and 12 are orthogonal so ANN puts 10 first. + vecs = np.array( + [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], + dtype=np.float32, + ) + index.add_with_ids(vecs, np.array([10, 11, 12], dtype=np.int64)) + faiss.write_index(index, str(index_path)) + + class _QueryEmbedder: + def encode(self, texts): + return np.array([[1.0, 0.0, 0.0, 0.0]], dtype=np.float32) + + # Positive case: HIV/EGFR chunk (11) is front-loaded ahead of ANN winner (10); + # "archived" in chunk 12 does not match "hiv". + chunk_ids, _ = search_chunks_constrained( + "Does HIV bind EGFR?", + candidate_papers=[1], + k=2, + chunk_index_path=index_path, + db_path=db_path, + embedder=_QueryEmbedder(), + connect_db=connect_db, + load_temp_candidates=load_temp_candidates, + chunk_ids_to_paper_ids=chunk_ids_to_paper_ids, + min_chunks_per_paper=1.0, + ) + assert chunk_ids == [11, 10] + + # Negative case: "journal"/"internal" in chunk 12 must not be front-loaded for "RNA". + rna_ids, _ = search_chunks_constrained( + "How does RNA work?", + candidate_papers=[1], + k=1, + chunk_index_path=index_path, + db_path=db_path, + embedder=_QueryEmbedder(), + connect_db=connect_db, + load_temp_candidates=load_temp_candidates, + chunk_ids_to_paper_ids=chunk_ids_to_paper_ids, + min_chunks_per_paper=1.0, + ) + assert rna_ids == [10] + + # ------------------------------------------------------------------- merging