From 69dbc8e8e63cba96cce5eb6c6d3e95ecf0eb73b1 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 12:56:27 -0700 Subject: [PATCH 01/21] Normalize Unicode lexical matches and keep ANN widening inside the shortlist Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 2 + src/litkit/cli.py | 1 + src/litkit/db/connection.py | 3 + src/litkit/db/normalization.py | 32 +++++ src/litkit/db/schema.py | 4 + src/litkit/retrieval/__init__.py | 2 + src/litkit/retrieval/helpers.py | 100 ++++----------- src/litkit/retrieval/lexical.py | 43 +++---- src/litkit/retrieval/stages.py | 117 ++++++----------- tests/integration/test_build_and_query.py | 19 ++- tests/test_retrieval.py | 148 +++++++++++++++++++++- 11 files changed, 287 insertions(+), 184 deletions(-) create mode 100644 src/litkit/db/normalization.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 569d190..64f383f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ internal versions are summarized under 0.3.33. ## [Unreleased] ### Fixed +- Keyword search now matches Unicode forms such as `fibrosis`, `CD4`, and `marker²` in existing indexes. Applications executing `sqlite_norm_expr()` on their own SQLite connections can call `litkit.retrieval.register_search_normalizer(conn)` once. LitKit connections and the lexical backend register it automatically. (#20) +- Capped Stage-2 searches keep newly fetched chunks inside the paper shortlist. Sparse-shortlist fallback and explicit global lexical searches can still return other papers. (#25) - Corpus manifests accept dotted shard names without a tar extension. The CLI reports entries it cannot resolve. (#19) - Archive scans release processed headers. Parallel parsing keeps a bounded window and continues in order after empty articles. Compressed archives can contain rootless XML members without stopping the build. (#12, #24) - IVF-PQ training saves a flat chunk index when the corpus has no training text. Builds also recognize untrained indexes created by `--init-indices-only` and persist the training result before updating its marker. (#11) diff --git a/src/litkit/cli.py b/src/litkit/cli.py index 263cb6b..3e75200 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -1716,6 +1716,7 @@ def main(): ap.add_argument( "--allow-global-lexical", action="store_true", + default=None, help="Allow lexical boost without a candidate-paper filter (also respects LITKIT_ALLOW_GLOBAL_LEXICAL=1).", ) ap.add_argument( diff --git a/src/litkit/db/connection.py b/src/litkit/db/connection.py index 8e7e24a..202914c 100644 --- a/src/litkit/db/connection.py +++ b/src/litkit/db/connection.py @@ -8,6 +8,8 @@ from pathlib import Path from typing import TYPE_CHECKING +from litkit.db.normalization import register_search_normalizer + if TYPE_CHECKING: from litkit.config.paths import WorkspacePaths @@ -64,6 +66,7 @@ def connect_db( check_same_thread=False, isolation_level=isolation, ) + register_search_normalizer(conn) conn.execute(f"PRAGMA busy_timeout={busy_timeout_ms}") return conn diff --git a/src/litkit/db/normalization.py b/src/litkit/db/normalization.py new file mode 100644 index 0000000..b9b93b9 --- /dev/null +++ b/src/litkit/db/normalization.py @@ -0,0 +1,32 @@ +"""Unicode text normalization shared by SQLite and lexical queries.""" + +import sqlite3 +import unicodedata + + +def fold_search_dashes(text: str) -> str: + """Fold dash variants after NFKC and remove discretionary hyphens.""" + for dash in "‐‒–—−": + text = text.replace(dash, "-") + return text.replace("\u00ad", "") + + +def normalize_for_search_py(text: str) -> str: + """Normalize compatibility characters, case and dashes for lexical matching.""" + if text.isascii(): + return text.lower() + return fold_search_dashes(unicodedata.normalize("NFKC", text).lower()) + + +def _sqlite_normalize(text: str | None) -> str | None: + return None if text is None else normalize_for_search_py(text) + + +def register_search_normalizer(conn: sqlite3.Connection) -> None: + """Enable sqlite_norm_expr() on a caller-supplied SQLite connection.""" + conn.create_function("litkit_normalize", 1, _sqlite_normalize, deterministic=True) + + +def sqlite_norm_expr(field: str = "text") -> str: + """SQL for normalized text on a LitKit connection or one with register_search_normalizer().""" + return f"litkit_normalize(CAST({field} AS TEXT))" diff --git a/src/litkit/db/schema.py b/src/litkit/db/schema.py index a889ab7..167cbab 100644 --- a/src/litkit/db/schema.py +++ b/src/litkit/db/schema.py @@ -7,6 +7,8 @@ import sys from pathlib import Path +from litkit.db.normalization import register_search_normalizer + # --------------------------------------------------------------------------- # Schema Definition (matches cli.py exactly) # --------------------------------------------------------------------------- @@ -123,6 +125,7 @@ def init_db( db_path.parent.mkdir(parents=True, exist_ok=True) conn = sqlite3.connect(str(db_path), isolation_level="DEFERRED", timeout=busy_timeout_ms / 1000.0) + register_search_normalizer(conn) mode = (journal_mode or "TRUNCATE").upper() supported = {"TRUNCATE", "WAL"} @@ -179,6 +182,7 @@ def init_shard_db( _eprint(f"[db] Producer shard {shard_id}: using {shard_path}") conn = sqlite3.connect(str(shard_path), isolation_level="DEFERRED", timeout=busy_timeout_ms / 1000.0) + register_search_normalizer(conn) mode = (journal_mode or "TRUNCATE").upper() conn.execute(f"PRAGMA journal_mode={mode};") diff --git a/src/litkit/retrieval/__init__.py b/src/litkit/retrieval/__init__.py index f73564a..c1f9afd 100644 --- a/src/litkit/retrieval/__init__.py +++ b/src/litkit/retrieval/__init__.py @@ -9,6 +9,7 @@ than relying on cli.py globals. """ +from litkit.db.normalization import register_search_normalizer from litkit.retrieval.stages import ( shortlist_papers, search_chunks_constrained, @@ -45,6 +46,7 @@ "sqlite_norm_expr", "escape_like", "normalize_for_search_py", + "register_search_normalizer", "avg_chunks_for_papers", # FAISS search "faiss_search", diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index 32abc74..afcae77 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -9,6 +9,10 @@ import unicodedata from pathlib import Path +from litkit.db.normalization import fold_search_dashes +from litkit.db.normalization import normalize_for_search_py as normalize_for_search_py +from litkit.db.normalization import sqlite_norm_expr as sqlite_norm_expr + # Stopwords for query term filtering _STOPWORDS = { "the", "and", "for", "with", "that", "this", "from", "into", "your", @@ -30,42 +34,22 @@ # 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": " ", - } -) +_TOKEN_RE = re.compile(r"[^\W_]+(?:[-_][^\W_]+)*") +_EN_FIGURE_DASH_BETWEEN_ALNUM_RE = re.compile(r"(?<=[^\W_])[‒–](?=[^\W_])") +# A signed exponent or ionic charge must not turn into a high-priority query +# term ("10⁻³", "Ca²⁺") and displace the longer descriptive words. +_SUPERSCRIPTS_RE = re.compile(r"[⁰¹²³⁴⁵⁶⁷⁸⁹⁺⁻]+") +# Preserve the acronym used to search Greek variants such as TNF-α and IFNγ. +_GREEK_ACRONYM_SUFFIX = re.compile(r"([A-Z]{3,4})-?[α-ωΑ-Ω]") 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", " ") + """Normalize compatibility characters while preserving acronym case and prose boundaries.""" + if "⁺" in s or "⁻" in s: + s = _SUPERSCRIPTS_RE.sub(lambda m: " " if "⁺" in m[0] or "⁻" in m[0] else m[0], s) + s = unicodedata.normalize("NFKC", s).replace("\u00ad", "") + s = _EN_FIGURE_DASH_BETWEEN_ALNUM_RE.sub("-", s) + return fold_search_dashes(s.replace("‒", " ").replace("–", " ").replace("—", " ")) def _is_prose_word(word: str) -> bool: @@ -96,7 +80,7 @@ def _acronym_stem(token: str) -> str | None: 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(): + if 3 <= len(stem) <= _ACRONYM_MAX_LEN and stem.isascii() and stem.isupper(): return stem return None @@ -104,8 +88,8 @@ def _acronym_stem(token: str) -> str | 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 + Applies Unicode and dash normalization before tokenizing + 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. @@ -115,6 +99,9 @@ def _extract_query_terms(s: str) -> list[tuple[str, bool]]: out: list[tuple[str, bool]] = [] seen: set[str] = set() for w in _TOKEN_RE.findall(normalized): + variant = _GREEK_ACRONYM_SUFFIX.fullmatch(w) + if variant: + w = variant[1] if len(w) < 3: continue stem = _acronym_stem(w) if allow_acronyms else None @@ -131,8 +118,8 @@ def _extract_query_terms(s: str) -> list[tuple[str, bool]]: def query_terms(s: str) -> list[str]: """Extract meaningful query terms from a string. - Normalizes SQLite-compatible dashes and subscript digits, extracts - hyphen/underscore-joined ASCII alphanumeric tokens of 3+ characters, + Applies NFKC and dash normalization, extracts hyphen/underscore-joined + alphanumeric tokens of 3+ characters, filters out stopwords, and lowercases kept terms while preserving order. Keeps tokens that are: - 5+ characters long @@ -150,26 +137,6 @@ def query_terms(s: str) -> list[str]: return [term for term, _ in _extract_query_terms(s)] -def sqlite_norm_expr(field: str = "text") -> str: - """Build a SQL expression that normalizes unicode variants. - - Normalizes: - - Hyphen/minus variants to ASCII '-' - - Subscript digits to ASCII digits - - Lowercase - - Args: - field: SQL column name to wrap - - Returns: - SQL expression string - """ - f = f"lower({field})" - for ch, repl in _SQLITE_NORM_REPLACEMENTS: - f = f"replace({f}, '{ch}', '{repl}')" - return f - - def escape_like(s: str, esc: str = "\\") -> str: """Escape special characters for SQL LIKE patterns. @@ -187,21 +154,6 @@ def escape_like(s: str, esc: str = "\\") -> str: return s -def normalize_for_search_py(s: str) -> str: - """Python-side text normalization matching SQLite normalization. - - Applies the same transformations as sqlite_norm_expr() but in Python, - ensuring query terms match what's in the database. - - Args: - s: Input string - - Returns: - Normalized string - """ - return unicodedata.normalize("NFKC", s).lower().translate(_SQLITE_NORM_TRANS) - - def avg_chunks_for_papers( pids: list[int], *, @@ -233,6 +185,6 @@ def avg_chunks_for_papers( GROUP BY cp.id """ ).fetchall() - return 0.0 if not rows else (sum(n for _, n in rows) / float(len(pids))) + return sum(n for _, n in rows) / len(rows) if rows else 0.0 finally: conn.close() diff --git a/src/litkit/retrieval/lexical.py b/src/litkit/retrieval/lexical.py index f2a1343..a30ab17 100644 --- a/src/litkit/retrieval/lexical.py +++ b/src/litkit/retrieval/lexical.py @@ -24,6 +24,7 @@ from functools import lru_cache from typing import TYPE_CHECKING, Protocol +from litkit.db.normalization import register_search_normalizer from litkit.retrieval.helpers import ( _ACRONYM_MAX_LEN, _extract_query_terms, @@ -38,29 +39,20 @@ @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 + # ASCII alphanumeric boundaries allow matches in 'RNA-seq', '(RNA)' and + # 'TNFα' while excluding substrings in '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: + """Match an acronym and its accepted suffixes in normalized SQLite text.""" + if not isinstance(text, str) or not isinstance(term, str) or term not in text: return 0 - return 1 if _word_boundary_re(term).search(text.replace("\u00ad", "")) else 0 + return int(_word_boundary_re(term).search(text) is not None) def _needs_word_boundary(norm_term: str) -> bool: @@ -197,7 +189,13 @@ 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) + # SQLite rejects replacing a function while a caller has an active cursor. + # Connections supplied by a library client may still need both functions. + functions = {(row[0], row[4]) for row in db_conn.execute("PRAGMA function_list")} + if ("litkit_normalize", 1) not in functions: + register_search_normalizer(db_conn) + if ("litkit_word_match", 2) not in functions: + db_conn.create_function("litkit_word_match", 2, _word_match, deterministic=True) def search( self, @@ -227,25 +225,20 @@ def search( 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]) + like_parts.append(f"litkit_word_match({norm}, ?)") + params.append(nt) else: like_parts.append(f"{norm} LIKE ? ESCAPE '\\'") - params.append(like_param) + params.append(f"%{escape_like(nt)}%") like_clause = " OR ".join(like_parts) # Title hint for sorting (prefer chunks from papers with matching title) title_hint = normalize_for_search_py(terms[0] if terms 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] + title_expr = f"litkit_word_match({title_norm}, ?)" + title_params: list[object] = [title_hint] else: title_expr = f"{title_norm} LIKE ? ESCAPE '\\'" title_params = [f"%{escape_like(title_hint)}%" if title_hint else "%"] diff --git a/src/litkit/retrieval/stages.py b/src/litkit/retrieval/stages.py index 75c3d65..582d209 100644 --- a/src/litkit/retrieval/stages.py +++ b/src/litkit/retrieval/stages.py @@ -9,7 +9,7 @@ import logging import os import sqlite3 -from collections import defaultdict +from collections import Counter from pathlib import Path from typing import TYPE_CHECKING, Any @@ -17,6 +17,7 @@ import numpy as np from litkit.db.schema import citation_columns +from litkit.frontload.cap import cap_chunks_per_paper from litkit.retrieval.helpers import ( avg_chunks_for_papers, ) @@ -120,8 +121,6 @@ def search_chunks_constrained( Returns: (chunk_ids, meta) where meta has effective search params """ - global _LEXICAL_WARN_ONCE - enc = embedder q = enc.encode([question]).astype("float32", copy=False) faiss.normalize_L2(q) @@ -131,11 +130,10 @@ def search_chunks_constrained( if not ids: return [], meta - ranked = list(zip(ids, dists, strict=False)) db_conn = connect_db(db_path) try: - cand: set | None = None + cand: set[int] | None = None did_fallback = False env_thr = float(os.environ.get("LITKIT_MIN_CHUNKS_PER_PAPER", "2.0")) @@ -160,13 +158,20 @@ def search_chunks_constrained( cand = None did_fallback = cand is None - if cand: - ann_chunk_to_paper = chunk_ids_to_paper_ids(db_conn, ids) - ranked = [ - (cid, dist) for cid, dist in ranked - if ann_chunk_to_paper.get(cid) in cand + paper_by_chunk: dict[int, int] = {} + + def scoped_ann_hits(hits: list[tuple[int, float]]) -> list[tuple[int, float]]: + if cand is None and not per_paper_cap: + return hits + paper_by_chunk.update(chunk_ids_to_paper_ids(db_conn, [cid for cid, _ in hits])) + return [ + (cid, dist) + for cid, dist in hits + if cid in paper_by_chunk and (cand is None or paper_by_chunk[cid] in cand) ] + ranked = scoped_ann_hits(list(zip(ids, dists, strict=True))) + # Lexical front-loading via modular lexical module force_global = ( allow_global_lexical @@ -209,80 +214,42 @@ def search_chunks_constrained( # Per-paper cap if per_paper_cap: - def _batched_map(ids_list: list[int]) -> dict[int, int]: - if not ids_list: - return {} - out_map: dict[int, int] = {} - B = 800 - cur = db_conn.cursor() - for s in range(0, len(ids_list), B): - batch = ids_list[s:s + B] - qmarks = ",".join("?" for _ in batch) - rows = cur.execute( - f"SELECT id, paper_id FROM chunks WHERE id IN ({qmarks})", - batch - ).fetchall() - out_map.update({row[0]: row[1] for row in rows}) - return out_map - - from litkit.frontload.cap import cap_chunks_per_paper - - selected_chunk_to_paper: dict[int, int] = _batched_map(out) if out else {} - if out: - out = cap_chunks_per_paper( - out, selected_chunk_to_paper, max_per_paper=per_paper_cap - ) - - def _top_up_from_ann(ann_ranked: list[tuple[int, float]]) -> None: - nonlocal out - selected = set(out) - ann_pool = [cid for (cid, _) in ann_ranked if cid not in selected] - if not ann_pool or len(out) >= k: - return - pool_map = _batched_map(ann_pool) - - counts = defaultdict(int) - for cid in out: - pid = selected_chunk_to_paper.get(cid) - if pid is not None: - counts[pid] += 1 - - for cid in ann_pool: + # A lexical hit can be outside the ANN pool, including when global + # lexical search was explicitly requested for a constrained shortlist. + missing = [cid for cid in out if cid not in paper_by_chunk] + if missing: + paper_by_chunk.update(chunk_ids_to_paper_ids(db_conn, missing)) + out = [cid for cid in out if cid in paper_by_chunk] + out = cap_chunks_per_paper(out, paper_by_chunk, max_per_paper=per_paper_cap) + selected = set(out) + counts = Counter(paper_by_chunk[cid] for cid in out) + + def top_up(hits: list[tuple[int, float]]) -> None: + for cid, _ in hits: if len(out) >= k: break - pid = pool_map.get(cid) - if pid is None: - continue - if counts[pid] < per_paper_cap: + pid = paper_by_chunk[cid] + if cid not in selected and counts[pid] < per_paper_cap: out.append(cid) + selected.add(cid) counts[pid] += 1 - if cid not in selected_chunk_to_paper and pid is not None: - selected_chunk_to_paper[cid] = pid - - if len(out) < k: - _top_up_from_ann(ranked) - # Widen search if still short - widen_rounds = 2 - seen_ranked_ids = {cid for (cid, _) in ranked} - curK = K - for _ in range(widen_rounds): - if len(out) >= k: + top_up(ranked) + seen_ann = set(ids) + for _ in range(2): + if len(out) >= k or K >= 10000: break - curK = min(curK * 2, 10000) - more_ids, more_dists, _ = faiss_search( - chunk_index_path, q, curK, nprobe=nprobe - ) - new_ranked = [ + K = min(K * 2, 10000) + more_ids, more_dists, _ = faiss_search(chunk_index_path, q, K, nprobe=nprobe) + new_hits = [ (cid, dist) - for cid, dist in zip(more_ids, more_dists, strict=False) - if cid not in seen_ranked_ids + for cid, dist in zip(more_ids, more_dists, strict=True) + if cid not in seen_ann ] - if not new_ranked: + if not new_hits: break - ranked.extend(new_ranked) - seen_ranked_ids.update(cid for cid, _ in new_ranked) - _top_up_from_ann(new_ranked) + seen_ann.update(more_ids) + top_up(scoped_ann_hits(new_hits)) finally: db_conn.close() diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index 8017135..e4fd4d5 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -279,14 +279,13 @@ def _token_vec(self, tok): @pytest.mark.parametrize(("question", "title"), QUESTIONS) def test_query_retrieves_the_matching_paper(built, question, title): ws, _ = built - # Per-paper cap off: see #25 for what the default cap does to a 1-paper shortlist. proc = _ok(litkit(ws, "--no-llm", "--top-papers", "1", "--per-paper-cap", "0", question)) assert set(_context_titles(proc.stdout)) == {title} @pytest.mark.parametrize(("cap", "hiv_chunks"), [("3", 3), ("2", 2), ("0", 4)]) def test_per_paper_cap_limits_chunks_per_paper(isolated_env, corpus_dir, cap, hiv_chunks): - """Every paper shortlisted, so #25 can't bite. With 300-character chunks, 2 of + """Every paper is shortlisted. With 300-character chunks, 2 of the ~140-character paragraphs fit per chunk: HIV has 6 paragraphs -> 3 body chunks + title/abstract = 4, EGFR 4 -> 2 + 1 = 3, malaria 2 -> 1 + 1 = 2. So a cap of 3 or 2 binds for HIV, and 0 means no cap.""" @@ -309,16 +308,28 @@ def test_per_paper_cap_limits_chunks_per_paper(isolated_env, corpus_dir, cap, hi assert titles.count(title) == hiv_chunks -@pytest.mark.xfail(strict=True, raises=AssertionError, reason="#25: widening leaves shortlist") def test_query_with_default_cap_stays_in_shortlist(built): ws, _ = built question, title = QUESTIONS[0] proc = _ok(litkit(ws, "--no-llm", "--top-papers", "1", question)) titles = _context_titles(proc.stdout) - _check(titles and titles[0] == title, f"shortlisted paper missing or not first: {titles}") assert set(titles) == {title} +@pytest.mark.parametrize("setting", ["flag", "environment"]) +def test_cli_can_explicitly_frontload_lexical_hits_outside_shortlist(built, monkeypatch, setting): + ws, _ = built + question, title = QUESTIONS[0] + args = ["--no-llm", "--top-papers", "1"] + if setting == "flag": + args.append("--allow-global-lexical") + else: + monkeypatch.setenv("LITKIT_ALLOW_GLOBAL_LEXICAL", "1") + proc = _ok(litkit(ws, *args, f"{question} EGFR")) + assert "global Stage-2 fallback" not in proc.stderr + assert set(_context_titles(proc.stdout)) == {title, CORPUS["egfr"]["title"]} + + def _chunk_rows(ws): with _db(ws) as conn: return conn.execute("SELECT id, paper_id, ord, text FROM chunks ORDER BY id").fetchall() diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index 0c43de6..217b6df 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -67,7 +67,7 @@ def test_query_terms_handles_edge_cases_and_unicode(): # 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. + # A Greek variant suffix preserves the underlying acronym. 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?") == [ @@ -82,7 +82,7 @@ def test_query_terms_handles_edge_cases_and_unicode(): "cells", "specifically", ] - # SQLite-supported hyphens and subscripts normalize; superscripts (no NFKC in SQL) do not. + # Hyphens and subscripts normalize. Signed exponents and charges do not become rare terms. assert query_terms("Is IL\u20116 and IC\u2085\u2080 of CO\u2082 raised?") == [ "il-6", "ic50", @@ -93,6 +93,22 @@ def test_query_terms_handles_edge_cases_and_unicode(): assert query_terms("Ca\u00b2\u207a signaling") == ["signaling"] +def test_query_terms_normalize_unicode_before_selecting_rare_terms(): + question = "Do EGFR and CD4 change fibrosis-associated Épidémie markers?" + assert query_terms(question) == [ + "egfr", + "cd4", + "change", + "fibrosis-associated", + "épidémie", + "markers", + ] + assert find_rare_terms(question, LexicalConfig()) == ["cd4", "fibrosis-associated", "egfr"] + assert find_rare_terms("Épide\u0301miologie", LexicalConfig()) == ["épidémiologie"] + assert find_rare_terms("marker²", LexicalConfig()) == ["marker2"] + assert query_terms("Michaelis\u00ad–Menten") == ["michaelis-menten"] + + def test_find_rare_terms_prefers_digits_and_hyphens(): cfg = LexicalConfig() assert find_rare_terms("Does IL-6 bind CD4 in methyltransferase pathways?", cfg) == [ @@ -210,10 +226,33 @@ def test_normalization_expected_values(): assert normalize_for_search_py("IL–6 CO₂ soft­hyphen") == "il-6 co2 softhyphen" -@pytest.mark.xfail(strict=True, raises=AssertionError, reason="#20: no NFKC/Unicode lower in SQL") -@pytest.mark.parametrize("s", ["fibrosis", "CD4", "x²", "Épidémie"]) -def test_python_and_sql_normalization_agree_beyond_ascii(s, sql_norm): - assert normalize_for_search_py(s) == sql_norm(s) +@pytest.mark.parametrize( + ("s", "expected"), + [ + ("fibrosis", "fibrosis"), + ("CD4", "cd4"), + ("x²", "x2"), + ("Épidémie", "épidémie"), + ], +) +def test_python_and_sql_normalization_agree_beyond_ascii(s, expected, sql_norm): + assert normalize_for_search_py(s) == sql_norm(s) == expected + + +def test_sql_normalization_preserves_null_and_text_affinity(sql_norm): + assert sql_norm(None) is None + assert sql_norm(42) == "42" + + +def test_register_search_normalizer_on_a_raw_connection(): + from litkit.retrieval import register_search_normalizer + + conn = sqlite3.connect(":memory:") + try: + register_search_normalizer(conn) + assert conn.execute(f"SELECT {sqlite_norm_expr('?')}", ("fibrosis",)).fetchone() == ("fibrosis",) + finally: + conn.close() @pytest.mark.parametrize( @@ -289,6 +328,37 @@ def test_lexical_search_respects_limit_and_disable(lexical_db): assert backend.search([], None, LexicalConfig()).chunk_ids == [] +def test_unicode_match_and_title_order_on_client_connection(tmp_path): + # An existing database opened by a read-only client has no LitKit SQL functions. + path = tmp_path / "unicode.db" + with init_db(path) as writer: + writer.executemany( + "INSERT INTO papers(id,title) VALUES (?,?)", + [(1, None), (2, "HIV screening"), (3, "Controls")], + ) + writer.executemany( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (?,?,0,?)", + [ + (1, 1, "HIV"), + (2, 2, "HIVs"), + (3, 3, "arcHIVed"), + (4, 3, "HIV3alpha"), + ], + ) + writer.close() + db = sqlite3.connect(f"{path.as_uri()}?mode=ro", uri=True) + try: + backend = SqliteLexicalBackend(db, load_temp_candidates) + assert backend.search(["HIV"], None, LexicalConfig()).chunk_ids == [2, 1] + cursor = db.execute("SELECT id FROM chunks ORDER BY id") + assert cursor.fetchone() == (1,) + second = SqliteLexicalBackend(db, load_temp_candidates) + assert second.search(["HIV"], {1, 3}, LexicalConfig()).chunk_ids == [1] + assert cursor.fetchall() == [(2,), (3,), (4,)] + finally: + db.close() + + 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") @@ -400,6 +470,72 @@ def encode(self, texts): assert rna_ids == [10] +# ------------------------------------------------------------- Stage 2 scope + + +@pytest.mark.parametrize( + ("shortlist", "minimum", "global_lexical", "expected", "fallback"), + [ + ([1, 2], 2.0, False, [203, 1, 201, 202], False), + ([1, 1, 2], 2.0, False, [203, 1, 201, 202], False), + ([1, 2], 2.0, True, [2, 1, 203, 201], False), + ([1, 2], 2.1, False, [2, 1, 203, 3], True), + ], + ids=["constrained", "duplicate-paper", "global-lexical-only", "sparse-fallback"], +) +def test_stage2_unicode_frontload_and_widening( + tmp_path, capsys, shortlist, minimum, global_lexical, expected, fallback +): + db_path = tmp_path / "stage2.db" + db = init_db(db_path) + with db: + db.executemany("INSERT INTO papers(id) VALUES (?)", [(1,), (2,), (9,)]) + db.executemany( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (?,?,?,?)", + [(1, 1, 0, "background"), (2, 9, -1, "fibrosis-associated")] + + [(i, 9, i, "outside shortlist") for i in range(3, 201)] + + [ + (201, 2, 0, "first passage"), + (202, 2, 1, "second passage"), + (203, 1, 1, "fibrosis-associated"), + ], + ) + db.close() + + # The first widening (ranks 101–200) sees only outsiders. The second + # reaches paper 2, including a repeated ID as can occur in older indexes. + index_ids = [*range(1, 202), 201, 202, 203] + scores = np.linspace(1.0, 0.0, len(index_ids), dtype=np.float32) + vectors = np.column_stack((scores, np.sqrt(1 - scores**2))) + index = faiss.IndexIDMap2(flat_ip_index(2)) + index.add_with_ids(vectors, np.array(index_ids, dtype=np.int64)) + index_path = tmp_path / "chunks.faiss" + with index_path.open("wb") as stream: + faiss.write_index(index, faiss.PyCallbackIOWriter(stream.write)) + + class QueryEmbedder: + def encode(self, texts): + return np.array([[1.0, 0.0]], dtype=np.float32) + + ids, _ = search_chunks_constrained( + "Is this fibrosis-associated?", + shortlist, + 4, + 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, + overshoot=1, + min_chunks_per_paper=minimum, + allow_global_lexical=global_lexical, + per_paper_cap=2, + ) + assert ids == expected + assert ("global Stage-2 fallback" in capsys.readouterr().err) == fallback + + # ------------------------------------------------------------------- merging From b7011665def4f0fff0ddb7212c988c56d4794b7e Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 13:04:50 -0700 Subject: [PATCH 02/21] Preserve mixed-script acronyms and widen past duplicate ANN windows Signed-off-by: Bill Hlavacek --- src/litkit/db/normalization.py | 8 +++---- src/litkit/retrieval/helpers.py | 27 ++++++++++++++++++----- src/litkit/retrieval/stages.py | 3 ++- tests/test_retrieval.py | 39 +++++++++++++++++++++++++-------- 4 files changed, 57 insertions(+), 20 deletions(-) diff --git a/src/litkit/db/normalization.py b/src/litkit/db/normalization.py index b9b93b9..88f35ee 100644 --- a/src/litkit/db/normalization.py +++ b/src/litkit/db/normalization.py @@ -11,11 +11,11 @@ def fold_search_dashes(text: str) -> str: return text.replace("\u00ad", "") -def normalize_for_search_py(text: str) -> str: +def normalize_for_search_py(s: str) -> str: """Normalize compatibility characters, case and dashes for lexical matching.""" - if text.isascii(): - return text.lower() - return fold_search_dashes(unicodedata.normalize("NFKC", text).lower()) + if s.isascii(): + return s.lower() + return fold_search_dashes(unicodedata.normalize("NFKC", s).lower()) def _sqlite_normalize(text: str | None) -> str | None: diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index afcae77..313a4ef 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -7,6 +7,8 @@ import re import unicodedata +from collections.abc import Iterator +from itertools import groupby from pathlib import Path from litkit.db.normalization import fold_search_dashes @@ -35,12 +37,11 @@ _PROSE_WORD_MIN_LEN = 6 _VOWELS = frozenset("AEIOU") _TOKEN_RE = re.compile(r"[^\W_]+(?:[-_][^\W_]+)*") +_ASCII_TOKEN_RE = re.compile(r"[A-Za-z0-9]+(?:[-_][A-Za-z0-9]+)*") _EN_FIGURE_DASH_BETWEEN_ALNUM_RE = re.compile(r"(?<=[^\W_])[‒–](?=[^\W_])") # A signed exponent or ionic charge must not turn into a high-priority query # term ("10⁻³", "Ca²⁺") and displace the longer descriptive words. _SUPERSCRIPTS_RE = re.compile(r"[⁰¹²³⁴⁵⁶⁷⁸⁹⁺⁻]+") -# Preserve the acronym used to search Greek variants such as TNF-α and IFNγ. -_GREEK_ACRONYM_SUFFIX = re.compile(r"([A-Z]{3,4})-?[α-ωΑ-Ω]") def _normalize_for_tokenize(s: str) -> str: @@ -85,6 +86,23 @@ def _acronym_stem(token: str) -> str | None: return None +def _non_latin_letter(ch: str) -> bool: + return not ch.isascii() and ch.isalpha() and not unicodedata.name(ch, "").startswith("LATIN ") + + +def _query_words(text: str) -> Iterator[str]: + for word in _TOKEN_RE.findall(text): + if word.isascii() or not any(_acronym_stem(t) for t in _ASCII_TOKEN_RE.findall(word)): + yield word + continue + # Keep an acronym searchable beside another script (αSMA, TNF-α, + # IFNγR, HIV感染). Accented Latin words such as ÉPIDÉMIE stay whole. + for _, chars in groupby(word, key=_non_latin_letter): + part = "".join(chars).strip("-_") + if part: + yield part + + def _extract_query_terms(s: str) -> list[tuple[str, bool]]: """Extract normalized query terms paired with an acronym flag. @@ -98,10 +116,7 @@ def _extract_query_terms(s: str) -> list[tuple[str, bool]]: allow_acronyms = not _is_all_caps_prose(normalized) out: list[tuple[str, bool]] = [] seen: set[str] = set() - for w in _TOKEN_RE.findall(normalized): - variant = _GREEK_ACRONYM_SUFFIX.fullmatch(w) - if variant: - w = variant[1] + for w in _query_words(normalized): if len(w) < 3: continue stem = _acronym_stem(w) if allow_acronyms else None diff --git a/src/litkit/retrieval/stages.py b/src/litkit/retrieval/stages.py index 582d209..a9ede31 100644 --- a/src/litkit/retrieval/stages.py +++ b/src/litkit/retrieval/stages.py @@ -246,7 +246,8 @@ def top_up(hits: list[tuple[int, float]]) -> None: for cid, dist in zip(more_ids, more_dists, strict=True) if cid not in seen_ann ] - if not new_hits: + # A full window can consist entirely of duplicate external IDs. + if not new_hits and len(more_ids) < K: break seen_ann.update(more_ids) top_up(scoped_ann_hits(new_hits)) diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index 217b6df..d487d5e 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -109,6 +109,16 @@ def test_query_terms_normalize_unicode_before_selecting_rare_terms(): assert query_terms("Michaelis\u00ad–Menten") == ["michaelis-menten"] +def test_mixed_script_names_keep_acronyms_and_accented_words(): + assert find_rare_terms("Does αSMA bind IFNγR in HIV感染?", LexicalConfig()) == [ + "sma", + "ifn", + "hiv", + ] + assert query_terms("ÉPIDÉMIE") == ["épidémie"] + assert find_rare_terms("β-catenin", LexicalConfig()) == ["β-catenin"] + + def test_find_rare_terms_prefers_digits_and_hyphens(): cfg = LexicalConfig() assert find_rare_terms("Does IL-6 bind CD4 in methyltransferase pathways?", cfg) == [ @@ -236,7 +246,7 @@ def test_normalization_expected_values(): ], ) def test_python_and_sql_normalization_agree_beyond_ascii(s, expected, sql_norm): - assert normalize_for_search_py(s) == sql_norm(s) == expected + assert normalize_for_search_py(s=s) == sql_norm(s) == expected def test_sql_normalization_preserves_null_and_text_affinity(sql_norm): @@ -250,7 +260,9 @@ def test_register_search_normalizer_on_a_raw_connection(): conn = sqlite3.connect(":memory:") try: register_search_normalizer(conn) - assert conn.execute(f"SELECT {sqlite_norm_expr('?')}", ("fibrosis",)).fetchone() == ("fibrosis",) + assert conn.execute(f"SELECT {sqlite_norm_expr('?')}", ("fibrosis",)).fetchone() == ( + "fibrosis", + ) finally: conn.close() @@ -474,17 +486,24 @@ def encode(self, texts): @pytest.mark.parametrize( - ("shortlist", "minimum", "global_lexical", "expected", "fallback"), + ("shortlist", "minimum", "global_lexical", "duplicate_window", "expected", "fallback"), [ - ([1, 2], 2.0, False, [203, 1, 201, 202], False), - ([1, 1, 2], 2.0, False, [203, 1, 201, 202], False), - ([1, 2], 2.0, True, [2, 1, 203, 201], False), - ([1, 2], 2.1, False, [2, 1, 203, 3], True), + ([1, 2], 2.0, False, False, [203, 1, 201, 202], False), + ([1, 1, 2], 2.0, False, False, [203, 1, 201, 202], False), + ([1, 2], 2.0, False, True, [203, 1, 201, 202], False), + ([1, 2], 2.0, True, False, [2, 1, 203, 201], False), + ([1, 2], 2.1, False, False, [2, 1, 203, 3], True), + ], + ids=[ + "constrained", + "duplicate-paper", + "duplicate-window", + "global-lexical-only", + "sparse-fallback", ], - ids=["constrained", "duplicate-paper", "global-lexical-only", "sparse-fallback"], ) def test_stage2_unicode_frontload_and_widening( - tmp_path, capsys, shortlist, minimum, global_lexical, expected, fallback + tmp_path, capsys, shortlist, minimum, global_lexical, duplicate_window, expected, fallback ): db_path = tmp_path / "stage2.db" db = init_db(db_path) @@ -505,6 +524,8 @@ def test_stage2_unicode_frontload_and_widening( # The first widening (ranks 101–200) sees only outsiders. The second # reaches paper 2, including a repeated ID as can occur in older indexes. index_ids = [*range(1, 202), 201, 202, 203] + if duplicate_window: + index_ids[100:100] = range(1, 101) scores = np.linspace(1.0, 0.0, len(index_ids), dtype=np.float32) vectors = np.column_stack((scores, np.sqrt(1 - scores**2))) index = faiss.IndexIDMap2(flat_ip_index(2)) From 63e8e33478866e11142614e0b9ccadee587e2747 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 13:10:22 -0700 Subject: [PATCH 03/21] Stop widening at the shortlist cap and probe SQLite functions directly Signed-off-by: Bill Hlavacek --- src/litkit/retrieval/lexical.py | 16 ++++++-- src/litkit/retrieval/stages.py | 2 + tests/test_retrieval.py | 66 ++++++++++++++++++++++----------- 3 files changed, 59 insertions(+), 25 deletions(-) diff --git a/src/litkit/retrieval/lexical.py b/src/litkit/retrieval/lexical.py index a30ab17..d55174c 100644 --- a/src/litkit/retrieval/lexical.py +++ b/src/litkit/retrieval/lexical.py @@ -59,6 +59,17 @@ def _needs_word_boundary(norm_term: str) -> bool: return norm_term.isascii() and norm_term.isalpha() and len(norm_term) <= _ACRONYM_MAX_LEN +def _has_sql_function(conn: sqlite3.Connection, call: str) -> bool: + """Check whether the connection can prepare a call with this name and arity.""" + try: + conn.execute(f"EXPLAIN SELECT {call}").close() + except sqlite3.OperationalError as exc: + if str(exc).startswith(("no such function:", "wrong number of arguments to function ")): + return False + raise + return True + + @dataclass class LexicalConfig: """Configuration for lexical front-loading behavior. @@ -191,10 +202,9 @@ def __init__( self._warn_once = False # SQLite rejects replacing a function while a caller has an active cursor. # Connections supplied by a library client may still need both functions. - functions = {(row[0], row[4]) for row in db_conn.execute("PRAGMA function_list")} - if ("litkit_normalize", 1) not in functions: + if not _has_sql_function(db_conn, "litkit_normalize(NULL)"): register_search_normalizer(db_conn) - if ("litkit_word_match", 2) not in functions: + if not _has_sql_function(db_conn, "litkit_word_match(NULL, NULL)"): db_conn.create_function("litkit_word_match", 2, _word_match, deterministic=True) def search( diff --git a/src/litkit/retrieval/stages.py b/src/litkit/retrieval/stages.py index a9ede31..80e8c04 100644 --- a/src/litkit/retrieval/stages.py +++ b/src/litkit/retrieval/stages.py @@ -239,6 +239,8 @@ def top_up(hits: list[tuple[int, float]]) -> None: for _ in range(2): if len(out) >= k or K >= 10000: break + if cand is not None and all(counts[pid] >= per_paper_cap for pid in cand): + break K = min(K * 2, 10000) more_ids, more_dists, _ = faiss_search(chunk_index_path, q, K, nprobe=nprobe) new_hits = [ diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index d487d5e..bf8589e 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -2,6 +2,7 @@ lexical search, ANN/lexical merging, the per-paper cap and nprobe selection.""" import sqlite3 +from unittest.mock import patch import faiss import numpy as np @@ -11,7 +12,7 @@ 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 import faiss_search, search_chunks_constrained from litkit.retrieval.helpers import ( escape_like, normalize_for_search_py, @@ -360,6 +361,13 @@ def test_unicode_match_and_title_order_on_client_connection(tmp_path): writer.close() db = sqlite3.connect(f"{path.as_uri()}?mode=ro", uri=True) try: + # A client may allow SELECTs and functions while denying PRAGMA introspection. + db.set_authorizer( + lambda action, *_: ( + sqlite3.SQLITE_DENY if action == sqlite3.SQLITE_PRAGMA else sqlite3.SQLITE_OK + ) + ) + db.create_function("litkit_word_match", 1, lambda text: 0) backend = SqliteLexicalBackend(db, load_temp_candidates) assert backend.search(["HIV"], None, LexicalConfig()).chunk_ids == [2, 1] cursor = db.execute("SELECT id FROM chunks ORDER BY id") @@ -485,26 +493,7 @@ def encode(self, texts): # ------------------------------------------------------------- Stage 2 scope -@pytest.mark.parametrize( - ("shortlist", "minimum", "global_lexical", "duplicate_window", "expected", "fallback"), - [ - ([1, 2], 2.0, False, False, [203, 1, 201, 202], False), - ([1, 1, 2], 2.0, False, False, [203, 1, 201, 202], False), - ([1, 2], 2.0, False, True, [203, 1, 201, 202], False), - ([1, 2], 2.0, True, False, [2, 1, 203, 201], False), - ([1, 2], 2.1, False, False, [2, 1, 203, 3], True), - ], - ids=[ - "constrained", - "duplicate-paper", - "duplicate-window", - "global-lexical-only", - "sparse-fallback", - ], -) -def test_stage2_unicode_frontload_and_widening( - tmp_path, capsys, shortlist, minimum, global_lexical, duplicate_window, expected, fallback -): +def _search_widening_index(tmp_path, shortlist, minimum, global_lexical, duplicate_window=False): db_path = tmp_path / "stage2.db" db = init_db(db_path) with db: @@ -538,7 +527,7 @@ class QueryEmbedder: def encode(self, texts): return np.array([[1.0, 0.0]], dtype=np.float32) - ids, _ = search_chunks_constrained( + return search_chunks_constrained( "Is this fibrosis-associated?", shortlist, 4, @@ -553,10 +542,43 @@ def encode(self, texts): allow_global_lexical=global_lexical, per_paper_cap=2, ) + + +@pytest.mark.parametrize( + ("shortlist", "minimum", "global_lexical", "duplicate_window", "expected", "fallback"), + [ + ([1, 2], 2.0, False, False, [203, 1, 201, 202], False), + ([1, 1, 2], 2.0, False, False, [203, 1, 201, 202], False), + ([1, 2], 2.0, False, True, [203, 1, 201, 202], False), + ([1, 2], 2.0, True, False, [2, 1, 203, 201], False), + ([1, 2], 2.1, False, False, [2, 1, 203, 3], True), + ], + ids=[ + "constrained", + "duplicate-paper", + "duplicate-window", + "global-lexical-only", + "sparse-fallback", + ], +) +def test_stage2_unicode_frontload_and_widening( + tmp_path, capsys, shortlist, minimum, global_lexical, duplicate_window, expected, fallback +): + ids, _ = _search_widening_index(tmp_path, shortlist, minimum, global_lexical, duplicate_window) assert ids == expected assert ("global Stage-2 fallback" in capsys.readouterr().err) == fallback +@pytest.mark.parametrize(("global_lexical", "expected"), [(False, [203, 1]), (True, [2, 1, 203])]) +def test_saturated_shortlist_stops_ann_widening(tmp_path, global_lexical, expected): + # The initial results already fill paper 1's two slots. A global keyword hit + # can occupy a third slot, but a larger ANN window cannot supply a fourth. + with patch("litkit.retrieval.stages.faiss_search", wraps=faiss_search) as search: + ids, _ = _search_widening_index(tmp_path, [1], 2.0, global_lexical) + assert ids == expected + search.assert_called_once() + + # ------------------------------------------------------------------- merging From 1ae61f2e90fa6adeb9a3f26b5425ca23f73d8884 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 13:17:06 -0700 Subject: [PATCH 04/21] Recover technical terms at script boundaries and honor SQLite authorizers Signed-off-by: Bill Hlavacek --- src/litkit/retrieval/helpers.py | 37 ++++++++++++++++++++++++--------- src/litkit/retrieval/lexical.py | 8 ++++++- tests/test_retrieval.py | 33 +++++++++++++++++++++++++++++ 3 files changed, 67 insertions(+), 11 deletions(-) diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index 313a4ef..88d6579 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -8,7 +8,7 @@ import re import unicodedata from collections.abc import Iterator -from itertools import groupby +from itertools import groupby, pairwise from pathlib import Path from litkit.db.normalization import fold_search_dashes @@ -37,7 +37,6 @@ _PROSE_WORD_MIN_LEN = 6 _VOWELS = frozenset("AEIOU") _TOKEN_RE = re.compile(r"[^\W_]+(?:[-_][^\W_]+)*") -_ASCII_TOKEN_RE = re.compile(r"[A-Za-z0-9]+(?:[-_][A-Za-z0-9]+)*") _EN_FIGURE_DASH_BETWEEN_ALNUM_RE = re.compile(r"(?<=[^\W_])[‒–](?=[^\W_])") # A signed exponent or ionic charge must not turn into a high-priority query # term ("10⁻³", "Ca²⁺") and displace the longer descriptive words. @@ -90,17 +89,35 @@ def _non_latin_letter(ch: str) -> bool: return not ch.isascii() and ch.isalpha() and not unicodedata.name(ch, "").startswith("LATIN ") +def _has_digit_or_joiner(term: str) -> bool: + return "-" in term or "_" in term or any(ch.isdigit() for ch in term) + + +def _split_at_script_change(left: str, right: str) -> bool: + # A Latin run can stand on its own when pasted beside another script. + # Keep an explicit join in β-catenin, but retain the acronym in TNF-α. + latin = right if _non_latin_letter(left[0]) else left + term = latin.strip("-_") + if len(term) < 3: + return False + if _acronym_stem(term) or _has_digit_or_joiner(term): + return True + return len(term) >= 5 and left[-1] not in "-_" and right[0] not in "-_" + + def _query_words(text: str) -> Iterator[str]: for word in _TOKEN_RE.findall(text): - if word.isascii() or not any(_acronym_stem(t) for t in _ASCII_TOKEN_RE.findall(word)): + if word.isascii(): yield word continue - # Keep an acronym searchable beside another script (αSMA, TNF-α, - # IFNγR, HIV感染). Accented Latin words such as ÉPIDÉMIE stay whole. - for _, chars in groupby(word, key=_non_latin_letter): - part = "".join(chars).strip("-_") - if part: - yield part + runs = ["".join(chars) for _, chars in groupby(word, key=_non_latin_letter)] + start = end = 0 + for left, right in pairwise(runs): + end += len(left) + if _split_at_script_change(left, right): + yield word[start:end].strip("-_") + start = end + yield word[start:].strip("-_") def _extract_query_terms(s: str) -> list[tuple[str, bool]]: @@ -124,7 +141,7 @@ def _extract_query_terms(s: str) -> list[tuple[str, bool]]: 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: + if len(w) >= 5 or is_acronym or _has_digit_or_joiner(w): seen.add(term) out.append((term, is_acronym)) return out diff --git a/src/litkit/retrieval/lexical.py b/src/litkit/retrieval/lexical.py index d55174c..e6bae2a 100644 --- a/src/litkit/retrieval/lexical.py +++ b/src/litkit/retrieval/lexical.py @@ -28,6 +28,7 @@ from litkit.retrieval.helpers import ( _ACRONYM_MAX_LEN, _extract_query_terms, + _has_digit_or_joiner, escape_like, normalize_for_search_py, sqlite_norm_expr, @@ -64,6 +65,11 @@ def _has_sql_function(conn: sqlite3.Connection, call: str) -> bool: try: conn.execute(f"EXPLAIN SELECT {call}").close() except sqlite3.OperationalError as exc: + # An authorizer may deny this function while allowing other searches. + # SQLite has resolved its name and arity. Let the actual query use the + # backend's usual error handling if it needs the denied function. + if str(exc).startswith("not authorized to use function:"): + return True if str(exc).startswith(("no such function:", "wrong number of arguments to function ")): return False raise @@ -160,7 +166,7 @@ def find_rare_terms(question: str, config: LexicalConfig) -> list[str]: 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 = [t for t, _ in terms if _has_digit_or_joiner(t)] primary_set = set(primary) # Priority 3: 3-4 char all-uppercase acronyms not already in priority 1 diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index bf8589e..732d516 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -118,6 +118,8 @@ def test_mixed_script_names_keep_acronyms_and_accented_words(): ] assert query_terms("ÉPIDÉMIE") == ["épidémie"] assert find_rare_terms("β-catenin", LexicalConfig()) == ["β-catenin"] + assert find_rare_terms("β-catenin研究", LexicalConfig()) == ["β-catenin"] + assert find_rare_terms("NF-κB and α2β1", LexicalConfig()) == ["nf-κb", "α2β1"] def test_find_rare_terms_prefers_digits_and_hyphens(): @@ -341,6 +343,37 @@ def test_lexical_search_respects_limit_and_disable(lexical_db): assert backend.search([], None, LexicalConfig()).chunk_ids == [] +@pytest.mark.parametrize( + ("question", "passage"), + [ + ("BRCA1突变", "Pathogenic variants of BRCA1 increase susceptibility."), + ("SARS-CoV-2感染", "A study of SARS-CoV-2 transmission."), + ("PD-L1陽性", "PD-L1 staining in tissue."), + ("p53突变", "Loss of p53 activity."), + ("研究methyltransferase", "Characterizing a methyltransferase."), + ], +) +def test_mixed_script_query_frontloads_the_latin_term(lexical_db, question, passage): + lexical_db.execute("INSERT INTO chunks(id,paper_id,ord,text) VALUES (20,1,20,?)", (passage,)) + backend = SqliteLexicalBackend(lexical_db, load_temp_candidates) + config = LexicalConfig() + terms = find_rare_terms(question, config) + assert backend.search(terms, None, config).chunk_ids == [20] + + +def test_unused_denied_sql_function_does_not_block_lexical_search(lexical_db): + def authorize(action, arg1, arg2, database, trigger): + if action == sqlite3.SQLITE_FUNCTION and arg2 == "litkit_word_match": + return sqlite3.SQLITE_DENY + return sqlite3.SQLITE_OK + + lexical_db.set_authorizer(authorize) + for _ in range(2): + backend = SqliteLexicalBackend(lexical_db, load_temp_candidates) + assert backend.search(["IL-6"], None, LexicalConfig()).chunk_ids == [12, 11, 10, 14, 15] + assert backend.search(["RNA"], None, LexicalConfig()).chunk_ids == [] + + def test_unicode_match_and_title_order_on_client_connection(tmp_path): # An existing database opened by a read-only client has no LitKit SQL functions. path = tmp_path / "unicode.db" From a25c5ed8c7c02f939f44c497353c8aa7945a9cdf Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 13:25:35 -0700 Subject: [PATCH 05/21] Preserve Greek identifiers in surrounding prose and handle busy lexical databases Signed-off-by: Bill Hlavacek --- src/litkit/retrieval/helpers.py | 32 ++++++++++++++++++++++++-------- src/litkit/retrieval/lexical.py | 26 ++++++++++++-------------- tests/test_retrieval.py | 16 ++++++++++++++++ 3 files changed, 52 insertions(+), 22 deletions(-) diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index 88d6579..3f64f5a 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -89,6 +89,21 @@ def _non_latin_letter(ch: str) -> bool: return not ch.isascii() and ch.isalpha() and not unicodedata.name(ch, "").startswith("LATIN ") +def _identifier_character(ch: str) -> bool: + return ch.isascii() or not ch.isalpha() or unicodedata.name(ch, "").startswith(("LATIN ", "GREEK ")) + + +def _identifier_spans(word: str) -> Iterator[str]: + # Latin and Greek letters can belong to the same scientific name, as in + # β-galactosidase and α2β1. Unspaced prose can occur on either side. + if not any(ch.isalpha() and _identifier_character(ch) for ch in word): + yield word + return + for _, chars in groupby(word, key=_identifier_character): + if span := "".join(chars).strip("-_"): + yield span + + def _has_digit_or_joiner(term: str) -> bool: return "-" in term or "_" in term or any(ch.isdigit() for ch in term) @@ -110,14 +125,15 @@ def _query_words(text: str) -> Iterator[str]: if word.isascii(): yield word continue - runs = ["".join(chars) for _, chars in groupby(word, key=_non_latin_letter)] - start = end = 0 - for left, right in pairwise(runs): - end += len(left) - if _split_at_script_change(left, right): - yield word[start:end].strip("-_") - start = end - yield word[start:].strip("-_") + for span in _identifier_spans(word): + runs = ["".join(chars) for _, chars in groupby(span, key=_non_latin_letter)] + start = end = 0 + for left, right in pairwise(runs): + end += len(left) + if _split_at_script_change(left, right): + yield span[start:end].strip("-_") + start = end + yield span[start:].strip("-_") def _extract_query_terms(s: str) -> list[tuple[str, bool]]: diff --git a/src/litkit/retrieval/lexical.py b/src/litkit/retrieval/lexical.py index e6bae2a..b840737 100644 --- a/src/litkit/retrieval/lexical.py +++ b/src/litkit/retrieval/lexical.py @@ -65,11 +65,6 @@ def _has_sql_function(conn: sqlite3.Connection, call: str) -> bool: try: conn.execute(f"EXPLAIN SELECT {call}").close() except sqlite3.OperationalError as exc: - # An authorizer may deny this function while allowing other searches. - # SQLite has resolved its name and arity. Let the actual query use the - # backend's usual error handling if it needs the denied function. - if str(exc).startswith("not authorized to use function:"): - return True if str(exc).startswith(("no such function:", "wrong number of arguments to function ")): return False raise @@ -206,12 +201,6 @@ def __init__( self.db_conn = db_conn self.load_temp_candidates = load_temp_candidates self._warn_once = False - # SQLite rejects replacing a function while a caller has an active cursor. - # Connections supplied by a library client may still need both functions. - if not _has_sql_function(db_conn, "litkit_normalize(NULL)"): - register_search_normalizer(db_conn) - if not _has_sql_function(db_conn, "litkit_word_match(NULL, NULL)"): - db_conn.create_function("litkit_word_match", 2, _word_match, deterministic=True) def search( self, @@ -239,8 +228,8 @@ def search( norm = sqlite_norm_expr("c.text") like_parts: list[str] = [] params: list[object] = [] - for t in terms: - nt = normalize_for_search_py(t) + normalized_terms = [normalize_for_search_py(t) for t in terms] + for nt in normalized_terms: if _needs_word_boundary(nt): like_parts.append(f"litkit_word_match({norm}, ?)") params.append(nt) @@ -250,7 +239,7 @@ def search( like_clause = " OR ".join(like_parts) # Title hint for sorting (prefer chunks from papers with matching title) - title_hint = normalize_for_search_py(terms[0] if terms else "") + title_hint = normalized_terms[0] title_norm = sqlite_norm_expr("p.title") if title_hint and _needs_word_boundary(title_hint): title_expr = f"litkit_word_match({title_norm}, ?)" @@ -263,6 +252,15 @@ def search( chunk_ids: list[int] = [] try: + # Probe only functions this query needs. Replacing an existing one + # can fail while a client cursor is active, and a locked database + # must follow the same lexical fallback as the SELECT below. + if not _has_sql_function(self.db_conn, "litkit_normalize(NULL)"): + register_search_normalizer(self.db_conn) + if any(map(_needs_word_boundary, normalized_terms)) and not _has_sql_function( + self.db_conn, "litkit_word_match(NULL, NULL)" + ): + self.db_conn.create_function("litkit_word_match", 2, _word_match, deterministic=True) if scope == "global": cur.execute( f""" diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index 732d516..b8fe70f 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -351,6 +351,9 @@ def test_lexical_search_respects_limit_and_disable(lexical_db): ("PD-L1陽性", "PD-L1 staining in tissue."), ("p53突变", "Loss of p53 activity."), ("研究methyltransferase", "Characterizing a methyltransferase."), + ("研究β-galactosidase活性", "Assay of β-galactosidase activity."), + ("研究β-lactamase", "Expression of β-lactamase."), + ("研究α2β1活性", "Binding of integrin α2β1."), ], ) def test_mixed_script_query_frontloads_the_latin_term(lexical_db, question, passage): @@ -374,6 +377,19 @@ def authorize(action, arg1, arg2, database, trigger): assert backend.search(["RNA"], None, LexicalConfig()).chunk_ids == [] +def test_locked_lexical_db_can_retry_after_unlock(lexical_db, tmp_path, caplog): + reader = connect_db(tmp_path / "lex.sqlite3", busy_timeout_ms=1) + try: + lexical_db.execute("BEGIN EXCLUSIVE") + backend = SqliteLexicalBackend(reader, load_temp_candidates) + assert backend.search(["IL-6"], None, LexicalConfig()).chunk_ids == [] + assert "database is locked" in caplog.text + lexical_db.rollback() + assert backend.search(["IL-6"], None, LexicalConfig()).chunk_ids == [12, 11, 10, 14, 15] + finally: + reader.close() + + def test_unicode_match_and_title_order_on_client_connection(tmp_path): # An existing database opened by a read-only client has no LitKit SQL functions. path = tmp_path / "unicode.db" From 94d3a63ea4f844749739f9885841cbcc3c49d157 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 13:35:39 -0700 Subject: [PATCH 06/21] Prefer the query subject over measurements and defer unused ANN lookups Signed-off-by: Bill Hlavacek --- src/litkit/retrieval/lexical.py | 13 ++++++++- src/litkit/retrieval/stages.py | 16 ++++++++++- tests/test_retrieval.py | 49 ++++++++++++++++++++++++++++++--- 3 files changed, 72 insertions(+), 6 deletions(-) diff --git a/src/litkit/retrieval/lexical.py b/src/litkit/retrieval/lexical.py index b840737..f5314c0 100644 --- a/src/litkit/retrieval/lexical.py +++ b/src/litkit/retrieval/lexical.py @@ -38,6 +38,13 @@ from sqlite3 import Connection +# Normalized quantities can be ambiguous: both micromolar (µM) and +# micrometres (µm) become μm. Use these common measurements as a last resort. +_MEASUREMENT_RE = re.compile( + r"\d+(?:-\d+)?(?:μ[^\W\d_]*|[fpnumcdhk]?(?:mol|hz|pa|gy|sv|da|m|g|l|s)|å)" +) + + @lru_cache(maxsize=256) def _word_boundary_re(term: str) -> re.Pattern[str]: # ASCII alphanumeric boundaries allow matches in 'RNA-seq', '(RNA)' and @@ -149,6 +156,7 @@ def find_rare_terms(question: str, config: LexicalConfig) -> list[str]: 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 + 4. Numeric measurements (10µM, 25mg) when there are no more specific terms Args: question: The user's question @@ -159,6 +167,9 @@ def find_rare_terms(question: str, config: LexicalConfig) -> list[str]: """ # Use shared extraction so acronym flags are preserved before lowercasing terms = _extract_query_terms(question) + measurements = [t for t, _ in terms if _MEASUREMENT_RE.fullmatch(t)] + if measurements: + terms = [(t, acronym) for t, acronym in terms if t not in measurements] # Priority 1: digits or hyphens/underscores primary = [t for t, _ in terms if _has_digit_or_joiner(t)] @@ -175,7 +186,7 @@ def find_rare_terms(question: str, config: LexicalConfig) -> list[str]: long_set = set(long_terms) rare = long_terms + [t for t in acronyms if t not in long_set] - return rare[: config.max_terms] + return (rare or measurements)[: config.max_terms] class SqliteLexicalBackend: diff --git a/src/litkit/retrieval/stages.py b/src/litkit/retrieval/stages.py index 80e8c04..fc860c0 100644 --- a/src/litkit/retrieval/stages.py +++ b/src/litkit/retrieval/stages.py @@ -170,7 +170,19 @@ def scoped_ann_hits(hits: list[tuple[int, float]]) -> list[tuple[int, float]]: if cid in paper_by_chunk and (cand is None or paper_by_chunk[cid] in cand) ] - ranked = scoped_ann_hits(list(zip(ids, dists, strict=True))) + ann_hits = list(zip(ids, dists, strict=True)) + pending_hits = [] + if cand is None and per_paper_cap and 0 < k < len(ann_hits): + # With global scope, k distinct database-backed ANN hits suffice + # for the merge. Resolve the rest only if the paper cap binds. + ranked = scoped_ann_hits(ann_hits[:k]) + pending_hits = ann_hits[k:] + if len({cid for cid, _ in ranked}) < k: + # Missing or duplicate IDs can change the initial interleaving. + ranked.extend(scoped_ann_hits(pending_hits)) + pending_hits = [] + else: + ranked = scoped_ann_hits(ann_hits) # Lexical front-loading via modular lexical module force_global = ( @@ -235,6 +247,8 @@ def top_up(hits: list[tuple[int, float]]) -> None: counts[pid] += 1 top_up(ranked) + if len(out) < k and pending_hits: + top_up(scoped_ann_hits(pending_hits)) seen_ann = set(ids) for _ in range(2): if len(out) >= k or K >= 10000: diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index b8fe70f..9fff8de 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -2,7 +2,7 @@ lexical search, ANN/lexical merging, the per-paper cap and nprobe selection.""" import sqlite3 -from unittest.mock import patch +from unittest.mock import Mock, patch import faiss import numpy as np @@ -364,6 +364,21 @@ def test_mixed_script_query_frontloads_the_latin_term(lexical_db, question, pass assert backend.search(terms, None, config).chunk_ids == [20] +def test_measurements_do_not_displace_the_query_subject(lexical_db): + lexical_db.executemany( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (?,1,?,?)", + [(20, 20, "At 10 µM, methyltransferase activity doubled."), (21, 21, "A 10μm distance.")], + ) + config = LexicalConfig() + backend = SqliteLexicalBackend(lexical_db, load_temp_candidates) + terms = find_rare_terms("How does 10µM affect methyltransferase activity?", config) + assert backend.search(terms, None, config).chunk_ids == [20] + assert find_rare_terms("25㎎ of 5-FU", config) == ["5-fu"] + assert find_rare_terms("HIV at 10µM", config) == ["hiv"] + assert find_rare_terms("0.25µA stimulation", config) == ["stimulation"] + assert find_rare_terms("10µM", config) == ["10μm"] + + def test_unused_denied_sql_function_does_not_block_lexical_search(lexical_db): def authorize(action, arg1, arg2, database, trigger): if action == sqlite3.SQLITE_FUNCTION and arg2 == "litkit_word_match": @@ -542,7 +557,16 @@ def encode(self, texts): # ------------------------------------------------------------- Stage 2 scope -def _search_widening_index(tmp_path, shortlist, minimum, global_lexical, duplicate_window=False): +def _search_widening_index( + tmp_path, + shortlist, + minimum, + global_lexical, + duplicate_window=False, + *, + chunk_mapper=chunk_ids_to_paper_ids, + index_prefix=(), +): db_path = tmp_path / "stage2.db" db = init_db(db_path) with db: @@ -561,7 +585,7 @@ def _search_widening_index(tmp_path, shortlist, minimum, global_lexical, duplica # The first widening (ranks 101–200) sees only outsiders. The second # reaches paper 2, including a repeated ID as can occur in older indexes. - index_ids = [*range(1, 202), 201, 202, 203] + index_ids = [*index_prefix, *range(1, 202), 201, 202, 203] if duplicate_window: index_ids[100:100] = range(1, 101) scores = np.linspace(1.0, 0.0, len(index_ids), dtype=np.float32) @@ -585,7 +609,7 @@ def encode(self, texts): embedder=QueryEmbedder(), connect_db=connect_db, load_temp_candidates=load_temp_candidates, - chunk_ids_to_paper_ids=chunk_ids_to_paper_ids, + chunk_ids_to_paper_ids=chunk_mapper, overshoot=1, min_chunks_per_paper=minimum, allow_global_lexical=global_lexical, @@ -628,6 +652,23 @@ def test_saturated_shortlist_stops_ann_widening(tmp_path, global_lexical, expect search.assert_called_once() +def test_global_fallback_only_maps_the_needed_ann_prefix(tmp_path): + mapper = Mock(wraps=chunk_ids_to_paper_ids) + ids, _ = _search_widening_index(tmp_path, [1, 2], 2.1, False, chunk_mapper=mapper) + assert ids == [2, 1, 203, 3] + # Four ANN results plus the front-loaded keyword hit suffice to fill k. + looked_up = {cid for call in mapper.call_args_list for cid in call.args[1]} + assert looked_up <= {1, 2, 3, 4, 203} + + +@pytest.mark.parametrize("prefix", [(2, 3, 4, 5), (999, 2, 2, 3, 4, 5)]) +def test_global_fallback_continues_past_capped_or_stale_prefix(tmp_path, prefix): + # Paper 9 fills its two slots before the ANN search reaches paper 1. + # 999 has no row, and repeated ID 2 must still occupy just one slot. + ids, _ = _search_widening_index(tmp_path, [1, 2], 2.1, False, index_prefix=prefix) + assert ids == [2, 203, 3, 1] + + # ------------------------------------------------------------------- merging From fba040a5015f9abc18ce31b23f1eb1d0b1a633bb Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 13:40:34 -0700 Subject: [PATCH 07/21] Keep numbered scientific identifiers distinct from measurement units Signed-off-by: Bill Hlavacek --- src/litkit/retrieval/helpers.py | 21 ++++++++++----------- src/litkit/retrieval/lexical.py | 27 +++++++++++++++------------ tests/test_retrieval.py | 16 ++++++++++++++++ 3 files changed, 41 insertions(+), 23 deletions(-) diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index 3f64f5a..645e26b 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -79,7 +79,10 @@ def _acronym_stem(token: str) -> str | 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 + # A mass number and element symbol (137Cs, 75As) is not a plural acronym. + stem = token + if len(token) > 3 and token.endswith("s") and not token[:-2].isdigit(): + stem = token[:-1] if 3 <= len(stem) <= _ACRONYM_MAX_LEN and stem.isascii() and stem.isupper(): return stem return None @@ -136,8 +139,8 @@ def _query_words(text: str) -> Iterator[str]: yield span[start:].strip("-_") -def _extract_query_terms(s: str) -> list[tuple[str, bool]]: - """Extract normalized query terms paired with an acronym flag. +def _extract_query_terms(s: str) -> Iterator[tuple[str, bool]]: + """Extract case-preserved query terms paired with an acronym flag. Applies Unicode and dash normalization before tokenizing alphanumeric/hyphen/underscore words of at least 3 @@ -147,20 +150,16 @@ def _extract_query_terms(s: str) -> list[tuple[str, bool]]: """ 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 _query_words(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: + term = stem or w + if term.lower() in _STOPWORDS: continue is_acronym = stem is not None if len(w) >= 5 or is_acronym or _has_digit_or_joiner(w): - seen.add(term) - out.append((term, is_acronym)) - return out + yield term, is_acronym def query_terms(s: str) -> list[str]: @@ -182,7 +181,7 @@ def query_terms(s: str) -> list[str]: Returns: List of unique query terms in original order """ - return [term for term, _ in _extract_query_terms(s)] + return list(dict.fromkeys(term.lower() for term, _ in _extract_query_terms(s))) def escape_like(s: str, esc: str = "\\") -> str: diff --git a/src/litkit/retrieval/lexical.py b/src/litkit/retrieval/lexical.py index f5314c0..bceb5c8 100644 --- a/src/litkit/retrieval/lexical.py +++ b/src/litkit/retrieval/lexical.py @@ -38,10 +38,10 @@ from sqlite3 import Connection -# Normalized quantities can be ambiguous: both micromolar (µM) and -# micrometres (µm) become μm. Use these common measurements as a last resort. +# Both micromolar (µM) and micrometres (µm) become μm in a search. Recognize +# common units before lowercasing. A bare letter is ambiguous (16S rRNA, 14C). _MEASUREMENT_RE = re.compile( - r"\d+(?:-\d+)?(?:μ[^\W\d_]*|[fpnumcdhk]?(?:mol|hz|pa|gy|sv|da|m|g|l|s)|å)" + r"\d+(?:-\d+)?(?:μ[^\W\d_]*|[fpnumk][mglLMs]|cm|[fpnumk]?(?:mol|Hz|Pa|Gy|Sv|Da)|Å)" ) @@ -165,28 +165,31 @@ def find_rare_terms(question: str, config: LexicalConfig) -> list[str]: Returns: List of rare terms, capped at config.max_terms """ - # Use shared extraction so acronym flags are preserved before lowercasing - terms = _extract_query_terms(question) - measurements = [t for t, _ in terms if _MEASUREMENT_RE.fullmatch(t)] - if measurements: - terms = [(t, acronym) for t, acronym in terms if t not in measurements] + terms: dict[str, bool] = {} + measurements: dict[str, None] = {} + for term, acronym in _extract_query_terms(question): + lowered = term.lower() + if _MEASUREMENT_RE.fullmatch(term): + measurements[lowered] = None + else: + terms[lowered] = acronym or terms.get(lowered, False) # Priority 1: digits or hyphens/underscores - primary = [t for t, _ in terms if _has_digit_or_joiner(t)] + primary = [t for t in terms if _has_digit_or_joiner(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] + acronyms = [t for t, is_acronym in terms.items() 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_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 or measurements)[: config.max_terms] + return (rare or list(measurements))[: config.max_terms] class SqliteLexicalBackend: diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index 9fff8de..5eb7012 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -379,6 +379,22 @@ def test_measurements_do_not_displace_the_query_subject(lexical_db): assert find_rare_terms("10µM", config) == ["10μm"] +def test_numbered_scientific_identifiers_keep_priority(lexical_db): + lexical_db.executemany( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (?,1,?,?)", + [(20, 20, "Comparisons of 16S rRNA amplicons."), (21, 21, "Whole-genome sequencing.")], + ) + config = LexicalConfig() + backend = SqliteLexicalBackend(lexical_db, load_temp_candidates) + for query in ("16S rRNA sequencing", "16s rRNA sequencing", "16S RRNA SEQUENCING"): + terms = find_rare_terms(query, config) + assert backend.search(terms, None, config).chunk_ids == [20] + assert find_rare_terms("2HG and mitochondrial metabolism", config) == ["2hg"] + assert find_rare_terms("137Cs accumulation", config) == ["137cs"] + assert find_rare_terms("25Mg accumulation", config) == ["25mg"] + assert find_rare_terms("25mg of 25Mg tracer, accumulation", config) == ["25mg"] + + def test_unused_denied_sql_function_does_not_block_lexical_search(lexical_db): def authorize(action, arg1, arg2, database, trigger): if action == sqlite3.SQLITE_FUNCTION and arg2 == "litkit_word_match": From dd6e956f8d77e3e411ffb72bbf4db059271e7f99 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 13:46:31 -0700 Subject: [PATCH 08/21] Recognize numeric powers before Unicode normalization flattens exponents Signed-off-by: Bill Hlavacek --- src/litkit/retrieval/helpers.py | 22 ++++++++++++++++++++-- src/litkit/retrieval/lexical.py | 8 +------- tests/test_retrieval.py | 17 +++++++++++++++++ 3 files changed, 38 insertions(+), 9 deletions(-) diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index 645e26b..7d62212 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -38,13 +38,28 @@ _VOWELS = frozenset("AEIOU") _TOKEN_RE = re.compile(r"[^\W_]+(?:[-_][^\W_]+)*") _EN_FIGURE_DASH_BETWEEN_ALNUM_RE = re.compile(r"(?<=[^\W_])[‒–](?=[^\W_])") -# A signed exponent or ionic charge must not turn into a high-priority query -# term ("10⁻³", "Ca²⁺") and displace the longer descriptive words. +# Separate numerical powers from identifiers before NFKC flattens their +# typography. A numeric exponent is not an ordinary integer (10⁶ ≠ 106). +_DECIMAL = r"\d+(?:[.,]\d+)?" +_LENGTH_UNIT = r"[fpnuµμmck]?m" +_QUANTITY_POWER_RE = re.compile( + rf"(? str: """Normalize compatibility characters while preserving acronym case and prose boundaries.""" + if s.isascii(): + return s + s = _QUANTITY_POWER_RE.sub(" ", s) if "⁺" in s or "⁻" in s: s = _SUPERSCRIPTS_RE.sub(lambda m: " " if "⁺" in m[0] or "⁻" in m[0] else m[0], s) s = unicodedata.normalize("NFKC", s).replace("\u00ad", "") @@ -129,6 +144,9 @@ def _query_words(text: str) -> Iterator[str]: yield word continue for span in _identifier_spans(word): + if span.isascii() or _MEASUREMENT_RE.fullmatch(span): + yield span + continue runs = ["".join(chars) for _, chars in groupby(span, key=_non_latin_letter)] start = end = 0 for left, right in pairwise(runs): diff --git a/src/litkit/retrieval/lexical.py b/src/litkit/retrieval/lexical.py index bceb5c8..6ec3ffe 100644 --- a/src/litkit/retrieval/lexical.py +++ b/src/litkit/retrieval/lexical.py @@ -27,6 +27,7 @@ from litkit.db.normalization import register_search_normalizer from litkit.retrieval.helpers import ( _ACRONYM_MAX_LEN, + _MEASUREMENT_RE, _extract_query_terms, _has_digit_or_joiner, escape_like, @@ -38,13 +39,6 @@ from sqlite3 import Connection -# Both micromolar (µM) and micrometres (µm) become μm in a search. Recognize -# common units before lowercasing. A bare letter is ambiguous (16S rRNA, 14C). -_MEASUREMENT_RE = re.compile( - r"\d+(?:-\d+)?(?:μ[^\W\d_]*|[fpnumk][mglLMs]|cm|[fpnumk]?(?:mol|Hz|Pa|Gy|Sv|Da)|Å)" -) - - @lru_cache(maxsize=256) def _word_boundary_re(term: str) -> re.Pattern[str]: # ASCII alphanumeric boundaries allow matches in 'RNA-seq', '(RNA)' and diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index 5eb7012..24c44d8 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -377,6 +377,23 @@ def test_measurements_do_not_displace_the_query_subject(lexical_db): assert find_rare_terms("HIV at 10µM", config) == ["hiv"] assert find_rare_terms("0.25µA stimulation", config) == ["stimulation"] assert find_rare_terms("10µM", config) == ["10μm"] + assert find_rare_terms("100µM methyltransferase activity", config) == ["methyltransferase"] + assert find_rare_terms("100µM", config) == ["100μm"] + + +@pytest.mark.parametrize( + "sample", ["10⁶ cells", "3×10⁵ cells", "1.25 × 10⁶ cells", "10⁻³ M", "10 cm²", "2µm³"] +) +def test_numeric_powers_do_not_match_unrelated_integers(lexical_db, sample): + lexical_db.executemany( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (?,1,?,?)", + [(20, 20, "Methyltransferase expression increased."), (21, 21, "105 or 106 controls.")], + ) + config = LexicalConfig() + terms = find_rare_terms(f"How does methyltransferase expression change in {sample}?", config) + assert terms == ["methyltransferase", "expression"] + backend = SqliteLexicalBackend(lexical_db, load_temp_candidates) + assert backend.search(terms, None, config).chunk_ids == [20] def test_numbered_scientific_identifiers_keep_priority(lexical_db): From 30295c3368d24202376bd124d8a4360e3247710f Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 13:54:07 -0700 Subject: [PATCH 09/21] Preserve numbered identifiers followed by superscript citations Signed-off-by: Bill Hlavacek --- src/litkit/retrieval/helpers.py | 32 ++++++++++++++++++++++---------- tests/test_retrieval.py | 27 ++++++++++++++++++++++++++- 2 files changed, 48 insertions(+), 11 deletions(-) diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index 7d62212..8dd0b15 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -38,33 +38,45 @@ _VOWELS = frozenset("AEIOU") _TOKEN_RE = re.compile(r"[^\W_]+(?:[-_][^\W_]+)*") _EN_FIGURE_DASH_BETWEEN_ALNUM_RE = re.compile(r"(?<=[^\W_])[‒–](?=[^\W_])") +_SUPERSCRIPT_DIGITS = "⁰¹²³⁴⁵⁶⁷⁸⁹" +_SUPERSCRIPTS_RE = re.compile(f"[{_SUPERSCRIPT_DIGITS}⁺⁻]+") +_NON_SUPERSCRIPT_RE = re.compile(f"[^{_SUPERSCRIPT_DIGITS}⁺⁻]+") # Separate numerical powers from identifiers before NFKC flattens their # typography. A numeric exponent is not an ordinary integer (10⁶ ≠ 106). _DECIMAL = r"\d+(?:[.,]\d+)?" _LENGTH_UNIT = r"[fpnuµμmck]?m" _QUANTITY_POWER_RE = re.compile( - rf"(? str: + if "⁺" in match[0] or "⁻" in match[0]: + return " " + # Standalone powers have been removed. After an identifier's final digit, + # a pasted citation (IL-6¹, CD4¹) must leave the identifier searchable. + if match.start() and match.string[match.start() - 1].isdecimal(): + return " " + return unicodedata.normalize("NFKC", match[0]) + + def _normalize_for_tokenize(s: str) -> str: """Normalize compatibility characters while preserving acronym case and prose boundaries.""" if s.isascii(): return s - s = _QUANTITY_POWER_RE.sub(" ", s) - if "⁺" in s or "⁻" in s: - s = _SUPERSCRIPTS_RE.sub(lambda m: " " if "⁺" in m[0] or "⁻" in m[0] else m[0], s) - s = unicodedata.normalize("NFKC", s).replace("\u00ad", "") + # Normalize the context first so e.g. IL‑6 and CD₄ are recognizable while + # the superscript itself still carries its typographic information. + s = _NON_SUPERSCRIPT_RE.sub(lambda m: unicodedata.normalize("NFKC", m[0]), s) + s = s.replace("\u00ad", "") s = _EN_FIGURE_DASH_BETWEEN_ALNUM_RE.sub("-", s) - return fold_search_dashes(s.replace("‒", " ").replace("–", " ").replace("—", " ")) + s = fold_search_dashes(s.replace("‒", " ").replace("–", " ").replace("—", " ")) + return _SUPERSCRIPTS_RE.sub(_query_superscript, _QUANTITY_POWER_RE.sub(" ", s)) def _is_prose_word(word: str) -> bool: diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index 24c44d8..a77cd36 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -382,7 +382,8 @@ def test_measurements_do_not_displace_the_query_subject(lexical_db): @pytest.mark.parametrize( - "sample", ["10⁶ cells", "3×10⁵ cells", "1.25 × 10⁶ cells", "10⁻³ M", "10 cm²", "2µm³"] + "sample", + ["10⁶ cells", "3×10⁵ cells", "1.25 × 10⁶ cells", "5–10⁶ cells", "10⁻³ M", "10 cm²", "2µm³"], ) def test_numeric_powers_do_not_match_unrelated_integers(lexical_db, sample): lexical_db.executemany( @@ -410,6 +411,30 @@ def test_numbered_scientific_identifiers_keep_priority(lexical_db): assert find_rare_terms("137Cs accumulation", config) == ["137cs"] assert find_rare_terms("25Mg accumulation", config) == ["25mg"] assert find_rare_terms("25mg of 25Mg tracer, accumulation", config) == ["25mg"] + assert find_rare_terms("What is the role of 231Pa in sedimentation?", config) == ["231pa"] + + +@pytest.mark.parametrize( + ("question", "expected"), + [ + ("How does IL-6¹ change?", "il-6"), + ("How does IL‑6¹ change?", "il-6"), + ("What about SARS-CoV-2¹?", "sars-cov-2"), + ("What about CD₄¹?", "cd4"), + ], +) +def test_superscript_reference_preserves_the_numbered_identifier(lexical_db, question, expected): + lexical_db.executemany( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (?,1,?,?)", + [(20, 20, "SARS-CoV-2 and CD4."), (21, 21, "SARS-CoV-1.")], + ) + config = LexicalConfig() + terms = find_rare_terms(question, config) + assert terms == [expected] + ids = ( + SqliteLexicalBackend(lexical_db, load_temp_candidates).search(terms, None, config).chunk_ids + ) + assert ids == ([12, 11, 10, 14, 15] if expected == "il-6" else [20]) def test_unused_denied_sql_function_does_not_block_lexical_search(lexical_db): From 70ffcb7d5c1c290ffa1d14636eadea152c020e67 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 13:59:26 -0700 Subject: [PATCH 10/21] Remove superscript citation lists before extracting lexical terms Signed-off-by: Bill Hlavacek --- src/litkit/retrieval/helpers.py | 4 ++++ tests/test_retrieval.py | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index 8dd0b15..15c36e6 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -41,6 +41,9 @@ _SUPERSCRIPT_DIGITS = "⁰¹²³⁴⁵⁶⁷⁸⁹" _SUPERSCRIPTS_RE = re.compile(f"[{_SUPERSCRIPT_DIGITS}⁺⁻]+") _NON_SUPERSCRIPT_RE = re.compile(f"[^{_SUPERSCRIPT_DIGITS}⁺⁻]+") +_CITATION_LIST_RE = re.compile( + rf"[{_SUPERSCRIPT_DIGITS}]+(?:\s*[,;‐‒–—−⁻-]\s*[{_SUPERSCRIPT_DIGITS}]+)+" +) # Separate numerical powers from identifiers before NFKC flattens their # typography. A numeric exponent is not an ordinary integer (10⁶ ≠ 106). _DECIMAL = r"\d+(?:[.,]\d+)?" @@ -74,6 +77,7 @@ def _normalize_for_tokenize(s: str) -> str: # the superscript itself still carries its typographic information. s = _NON_SUPERSCRIPT_RE.sub(lambda m: unicodedata.normalize("NFKC", m[0]), s) s = s.replace("\u00ad", "") + s = _CITATION_LIST_RE.sub(" ", s) s = _EN_FIGURE_DASH_BETWEEN_ALNUM_RE.sub("-", s) s = fold_search_dashes(s.replace("‒", " ").replace("–", " ").replace("—", " ")) return _SUPERSCRIPTS_RE.sub(_query_superscript, _QUANTITY_POWER_RE.sub(" ", s)) diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index a77cd36..23915b2 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -437,6 +437,26 @@ def test_superscript_reference_preserves_the_numbered_identifier(lexical_db, que assert ids == ([12, 11, 10, 14, 15] if expected == "il-6" else [20]) +@pytest.mark.parametrize( + ("question", "expected"), + [ + ("Does EGFR¹–³ affect tumors?", "egfr"), + ("How is methyltransferase¹,² measured?", "methyltransferase"), + ("Does EGFR [¹, ²–⁴] affect tumors?", "egfr"), + ], +) +def test_superscript_citation_lists_keep_the_cited_term(lexical_db, question, expected): + lexical_db.execute( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (20,1,20,'EGFR and methyltransferase.')" + ) + config = LexicalConfig() + terms = find_rare_terms(question, config) + assert terms == [expected] + assert SqliteLexicalBackend(lexical_db, load_temp_candidates).search( + terms, None, config + ).chunk_ids == [20] + + def test_unused_denied_sql_function_does_not_block_lexical_search(lexical_db): def authorize(action, arg1, arg2, database, trigger): if action == sqlite3.SQLITE_FUNCTION and arg2 == "litkit_word_match": From 43059f5925d6f7e423502e4b460546fb69849b57 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 14:06:16 -0700 Subject: [PATCH 11/21] Keep query subjects searchable beside ambiguous superscripts Signed-off-by: Bill Hlavacek --- src/litkit/retrieval/helpers.py | 39 ++++++++++++++++++++++----------- src/litkit/retrieval/lexical.py | 17 ++++++++++++-- tests/test_retrieval.py | 31 ++++++++++++++++++++++++++ 3 files changed, 72 insertions(+), 15 deletions(-) diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index 15c36e6..e948be5 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -59,20 +59,24 @@ ) -def _query_superscript(match: re.Match[str]) -> str: +def _query_superscript(match: re.Match[str], *, as_citation: bool = False) -> str: if "⁺" in match[0] or "⁻" in match[0]: return " " # Standalone powers have been removed. After an identifier's final digit, # a pasted citation (IL-6¹, CD4¹) must leave the identifier searchable. - if match.start() and match.string[match.start() - 1].isdecimal(): + before = match.string[match.start() - 1] if match.start() else "" + after = match.string[match.end() : match.end() + 1] + if before.isdecimal() or (not before.isalnum() and not after.isalnum()): + return " " + if as_citation and before.isalpha() and not after.isalnum(): return " " return unicodedata.normalize("NFKC", match[0]) -def _normalize_for_tokenize(s: str) -> str: - """Normalize compatibility characters while preserving acronym case and prose boundaries.""" +def _query_spellings(s: str) -> tuple[str, ...]: + """Normalize a query, retaining both readings of an ambiguous superscript suffix.""" if s.isascii(): - return s + return (s,) # Normalize the context first so e.g. IL‑6 and CD₄ are recognizable while # the superscript itself still carries its typographic information. s = _NON_SUPERSCRIPT_RE.sub(lambda m: unicodedata.normalize("NFKC", m[0]), s) @@ -80,7 +84,12 @@ def _normalize_for_tokenize(s: str) -> str: s = _CITATION_LIST_RE.sub(" ", s) s = _EN_FIGURE_DASH_BETWEEN_ALNUM_RE.sub("-", s) s = fold_search_dashes(s.replace("‒", " ").replace("–", " ").replace("—", " ")) - return _SUPERSCRIPTS_RE.sub(_query_superscript, _QUANTITY_POWER_RE.sub(" ", s)) + s = _QUANTITY_POWER_RE.sub(" ", s) + if not _SUPERSCRIPTS_RE.search(s): + return (s,) + numbered = _SUPERSCRIPTS_RE.sub(_query_superscript, s) + cited = _SUPERSCRIPTS_RE.sub(lambda m: _query_superscript(m, as_citation=True), s) + return (numbered,) if numbered == cited else (numbered, cited) def _is_prose_word(word: str) -> bool: @@ -173,16 +182,14 @@ def _query_words(text: str) -> Iterator[str]: yield span[start:].strip("-_") -def _extract_query_terms(s: str) -> Iterator[tuple[str, bool]]: - """Extract case-preserved query terms paired with an acronym flag. +def _extract_query_terms(normalized: str) -> Iterator[tuple[str, bool]]: + """Extract case-preserved query terms and acronym flags from a normalized spelling. - Applies Unicode and dash normalization before tokenizing - alphanumeric/hyphen/underscore words of at least 3 + Tokenize 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) for w in _query_words(normalized): if len(w) < 3: @@ -213,9 +220,15 @@ def query_terms(s: str) -> list[str]: s: Input string (typically a question) Returns: - List of unique query terms in original order + Unique query terms in original order, followed by alternate readings of + ambiguous superscripts """ - return list(dict.fromkeys(term.lower() for term, _ in _extract_query_terms(s))) + terms = ( + term.lower() + for spelling in _query_spellings(s) + for term, _ in _extract_query_terms(spelling) + ) + return list(dict.fromkeys(terms)) def escape_like(s: str, esc: str = "\\") -> str: diff --git a/src/litkit/retrieval/lexical.py b/src/litkit/retrieval/lexical.py index 6ec3ffe..df29f73 100644 --- a/src/litkit/retrieval/lexical.py +++ b/src/litkit/retrieval/lexical.py @@ -30,6 +30,7 @@ _MEASUREMENT_RE, _extract_query_terms, _has_digit_or_joiner, + _query_spellings, escape_like, normalize_for_search_py, sqlite_norm_expr, @@ -159,9 +160,21 @@ def find_rare_terms(question: str, config: LexicalConfig) -> list[str]: Returns: List of rare terms, capped at config.max_terms """ + # A pasted superscript can label an identifier or cite the preceding word. + # Rank each reading separately so a possible citation on “patients¹” cannot + # displace “methyltransferase” from the long-term fallback. Search once. + ranked = dict.fromkeys( + term + for spelling in reversed(_query_spellings(question)) + for term in _rank_rare_terms(spelling, config) + ) + return list(ranked)[: config.max_terms] + + +def _rank_rare_terms(spelling: str, config: LexicalConfig) -> list[str]: terms: dict[str, bool] = {} measurements: dict[str, None] = {} - for term, acronym in _extract_query_terms(question): + for term, acronym in _extract_query_terms(spelling): lowered = term.lower() if _MEASUREMENT_RE.fullmatch(term): measurements[lowered] = None @@ -183,7 +196,7 @@ def find_rare_terms(question: str, config: LexicalConfig) -> list[str]: long_set = set(long_terms) rare = long_terms + [t for t in acronyms if t not in long_set] - return (rare or list(measurements))[: config.max_terms] + return rare or list(measurements) class SqliteLexicalBackend: diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index 23915b2..13ff120 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -457,6 +457,37 @@ def test_superscript_citation_lists_keep_the_cited_term(lexical_db, question, ex ).chunk_ids == [20] +@pytest.mark.parametrize( + ("question", "ids"), + [ + ("How is methyltransferase measured [¹²³]?", [20]), + ("What is known about methyltransferase in patients¹?", [20]), + ("Does EGFR¹ affect tumors?", [22, 23]), + ("What about marker²?", [24]), + ("What about marker² and EGFR?", [22, 23, 24]), + ("What about ¹⁴C?", [25]), + ], +) +def test_single_superscripts_preserve_query_subject_and_identifier(lexical_db, question, ids): + lexical_db.executemany( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (?,1,?,?)", + [ + (20, 20, "Methyltransferase activity doubled."), + (21, 21, "The study enrolled 123 participants."), + (22, 22, "EGFR expression in tumors."), + (23, 23, "The numbered identifier EGFR1."), + (24, 24, "Expression of marker2."), + (25, 25, "We used a 14C tracer."), + ], + ) + config = LexicalConfig() + terms = find_rare_terms(question, config) + assert ( + SqliteLexicalBackend(lexical_db, load_temp_candidates).search(terms, None, config).chunk_ids + == ids + ) + + def test_unused_denied_sql_function_does_not_block_lexical_search(lexical_db): def authorize(action, arg1, arg2, database, trigger): if action == sqlite3.SQLITE_FUNCTION and arg2 == "litkit_word_match": From 59c449ca8466c334ac74a37af8aab70b3fdf4455 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 14:16:35 -0700 Subject: [PATCH 12/21] Rank technical terms across spellings and preserve alphabetic footnote boundaries Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 2 +- src/litkit/retrieval/helpers.py | 36 +++++++++---- src/litkit/retrieval/lexical.py | 92 +++++++++++++++++---------------- tests/test_retrieval.py | 47 +++++++++++++++++ 4 files changed, 121 insertions(+), 56 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 64f383f..6c4d398 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ internal versions are summarized under 0.3.33. ## [Unreleased] ### Fixed -- Keyword search now matches Unicode forms such as `fibrosis`, `CD4`, and `marker²` in existing indexes. Applications executing `sqlite_norm_expr()` on their own SQLite connections can call `litkit.retrieval.register_search_normalizer(conn)` once. LitKit connections and the lexical backend register it automatically. (#20) +- Keyword search now matches Unicode forms such as `fibrosis`, `CD4`, and `marker²` in existing indexes. Applications executing `sqlite_norm_expr()` on their own SQLite connections can call `litkit.retrieval.register_search_normalizer(conn)` once. LitKit handles registration for its own searches. (#20) - Capped Stage-2 searches keep newly fetched chunks inside the paper shortlist. Sparse-shortlist fallback and explicit global lexical searches can still return other papers. (#25) - Corpus manifests accept dotted shard names without a tar extension. The CLI reports entries it cannot resolve. (#19) - Archive scans release processed headers. Parallel parsing keeps a bounded window and continues in order after empty articles. Compressed archives can contain rootless XML members without stopping the build. (#12, #24) diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index e948be5..0661e5d 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -39,11 +39,7 @@ _TOKEN_RE = re.compile(r"[^\W_]+(?:[-_][^\W_]+)*") _EN_FIGURE_DASH_BETWEEN_ALNUM_RE = re.compile(r"(?<=[^\W_])[‒–](?=[^\W_])") _SUPERSCRIPT_DIGITS = "⁰¹²³⁴⁵⁶⁷⁸⁹" -_SUPERSCRIPTS_RE = re.compile(f"[{_SUPERSCRIPT_DIGITS}⁺⁻]+") -_NON_SUPERSCRIPT_RE = re.compile(f"[^{_SUPERSCRIPT_DIGITS}⁺⁻]+") -_CITATION_LIST_RE = re.compile( - rf"[{_SUPERSCRIPT_DIGITS}]+(?:\s*[,;‐‒–—−⁻-]\s*[{_SUPERSCRIPT_DIGITS}]+)+" -) +_NON_ASCII_RE = re.compile(r"[^\x00-\x7f]") # Separate numerical powers from identifiers before NFKC flattens their # typography. A numeric exponent is not an ordinary integer (10⁶ ≠ 106). _DECIMAL = r"\d+(?:[.,]\d+)?" @@ -59,6 +55,14 @@ ) +def _superscript_pattern(s: str) -> str | None: + """Match runs of characters present in this text with Unicode's decomposition.""" + marks = { + ch for ch in _NON_ASCII_RE.findall(s) if unicodedata.decomposition(ch).startswith("") + } + return f"[{re.escape(''.join(sorted(marks)))}]+" if marks else None + + def _query_superscript(match: re.Match[str], *, as_citation: bool = False) -> str: if "⁺" in match[0] or "⁻" in match[0]: return " " @@ -68,27 +72,37 @@ def _query_superscript(match: re.Match[str], *, as_citation: bool = False) -> st after = match.string[match.end() : match.end() + 1] if before.isdecimal() or (not before.isalnum() and not after.isalnum()): return " " - if as_citation and before.isalpha() and not after.isalnum(): + if as_citation and (not before.isalnum() or not after.isalnum()): return " " return unicodedata.normalize("NFKC", match[0]) +def _cited_reading(s: str, pattern: str) -> str: + return re.sub(pattern, lambda m: _query_superscript(m, as_citation=True), s) + + def _query_spellings(s: str) -> tuple[str, ...]: """Normalize a query, retaining both readings of an ambiguous superscript suffix.""" if s.isascii(): return (s,) # Normalize the context first so e.g. IL‑6 and CD₄ are recognizable while # the superscript itself still carries its typographic information. - s = _NON_SUPERSCRIPT_RE.sub(lambda m: unicodedata.normalize("NFKC", m[0]), s) + raised = _superscript_pattern(s) + if raised: + parts = re.split(f"({raised})", s) + parts[::2] = [unicodedata.normalize("NFKC", part) for part in parts[::2]] + s = "".join(parts) + s = re.sub(rf"{raised}(?:\s*[,;‐‒–—−⁻-]\s*{raised})+", " ", s) + else: + s = unicodedata.normalize("NFKC", s) s = s.replace("\u00ad", "") - s = _CITATION_LIST_RE.sub(" ", s) s = _EN_FIGURE_DASH_BETWEEN_ALNUM_RE.sub("-", s) s = fold_search_dashes(s.replace("‒", " ").replace("–", " ").replace("—", " ")) s = _QUANTITY_POWER_RE.sub(" ", s) - if not _SUPERSCRIPTS_RE.search(s): + if not raised: return (s,) - numbered = _SUPERSCRIPTS_RE.sub(_query_superscript, s) - cited = _SUPERSCRIPTS_RE.sub(lambda m: _query_superscript(m, as_citation=True), s) + numbered = re.sub(raised, _query_superscript, s) + cited = _cited_reading(s, raised) return (numbered,) if numbered == cited else (numbered, cited) diff --git a/src/litkit/retrieval/lexical.py b/src/litkit/retrieval/lexical.py index df29f73..22fc185 100644 --- a/src/litkit/retrieval/lexical.py +++ b/src/litkit/retrieval/lexical.py @@ -28,9 +28,11 @@ from litkit.retrieval.helpers import ( _ACRONYM_MAX_LEN, _MEASUREMENT_RE, + _cited_reading, _extract_query_terms, _has_digit_or_joiner, _query_spellings, + _superscript_pattern, escape_like, normalize_for_search_py, sqlite_norm_expr, @@ -52,10 +54,19 @@ def _word_boundary_re(term: str) -> re.Pattern[str]: def _word_match(text: object, term: object) -> int: - """Match an acronym and its accepted suffixes in normalized SQLite text.""" - if not isinstance(text, str) or not isinstance(term, str) or term not in text: + """Match a normalized acronym, including a word ending at a pasted footnote.""" + if not isinstance(text, str) or not isinstance(term, str): return 0 - return int(_word_boundary_re(term).search(text) is not None) + normalized = normalize_for_search_py(text) + if term not in normalized: + return 0 + boundary = _word_boundary_re(term) + if boundary.search(normalized): + return 1 + if not text.isascii() and (raised := _superscript_pattern(text)): + cited = normalize_for_search_py(_cited_reading(text, raised)) + return int(boundary.search(cited) is not None) + return 0 def _needs_word_boundary(norm_term: str) -> bool: @@ -160,43 +171,35 @@ def find_rare_terms(question: str, config: LexicalConfig) -> list[str]: Returns: List of rare terms, capped at config.max_terms """ - # A pasted superscript can label an identifier or cite the preceding word. - # Rank each reading separately so a possible citation on “patients¹” cannot - # displace “methyltransferase” from the long-term fallback. Search once. - ranked = dict.fromkeys( - term - for spelling in reversed(_query_spellings(question)) - for term in _rank_rare_terms(spelling, config) - ) - return list(ranked)[: config.max_terms] - - -def _rank_rare_terms(spelling: str, config: LexicalConfig) -> list[str]: - terms: dict[str, bool] = {} - measurements: dict[str, None] = {} - for term, acronym in _extract_query_terms(spelling): - lowered = term.lower() - if _MEASUREMENT_RE.fullmatch(term): - measurements[lowered] = None + primary = [] + long_terms = [] + acronyms = [] + measurements = [] + for spelling in _query_spellings(question): + # A possible citation on “patients¹” must leave the long-term fallback + # available in the citation reading of “methyltransferase in patients¹”. + technical = [] + descriptive = [] + for term, acronym in _extract_query_terms(spelling): + lowered = term.lower() + if _MEASUREMENT_RE.fullmatch(term): + measurements.append(lowered) + elif _has_digit_or_joiner(term): + technical.append(lowered) + else: + if len(lowered) >= config.min_term_length: + descriptive.append(lowered) + if acronym: + acronyms.append(lowered) + if technical: + primary.extend(technical) else: - terms[lowered] = acronym or terms.get(lowered, False) - - # Priority 1: digits or hyphens/underscores - primary = [t for t in terms if _has_digit_or_joiner(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.items() 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] + long_terms.extend(descriptive) - return rare or list(measurements) + # Apply priority and the term budget once, across all readings. A numbered + # identifier such as marker² keeps its place ahead of short acronyms. + ranked = primary + long_terms + acronyms or measurements + return list(dict.fromkeys(ranked))[: config.max_terms] class SqliteLexicalBackend: @@ -249,12 +252,15 @@ def search( norm = sqlite_norm_expr("c.text") like_parts: list[str] = [] params: list[object] = [] + uses_normalizer = uses_word_match = False normalized_terms = [normalize_for_search_py(t) for t in terms] for nt in normalized_terms: if _needs_word_boundary(nt): - like_parts.append(f"litkit_word_match({norm}, ?)") + uses_word_match = True + like_parts.append("litkit_word_match(c.text, ?)") params.append(nt) else: + uses_normalizer = True like_parts.append(f"{norm} LIKE ? ESCAPE '\\'") params.append(f"%{escape_like(nt)}%") like_clause = " OR ".join(like_parts) @@ -263,7 +269,7 @@ def search( title_hint = normalized_terms[0] title_norm = sqlite_norm_expr("p.title") if title_hint and _needs_word_boundary(title_hint): - title_expr = f"litkit_word_match({title_norm}, ?)" + title_expr = "litkit_word_match(p.title, ?)" title_params: list[object] = [title_hint] else: title_expr = f"{title_norm} LIKE ? ESCAPE '\\'" @@ -276,11 +282,9 @@ def search( # Probe only functions this query needs. Replacing an existing one # can fail while a client cursor is active, and a locked database # must follow the same lexical fallback as the SELECT below. - if not _has_sql_function(self.db_conn, "litkit_normalize(NULL)"): + if uses_normalizer and not _has_sql_function(self.db_conn, "litkit_normalize(NULL)"): register_search_normalizer(self.db_conn) - if any(map(_needs_word_boundary, normalized_terms)) and not _has_sql_function( - self.db_conn, "litkit_word_match(NULL, NULL)" - ): + if uses_word_match and not _has_sql_function(self.db_conn, "litkit_word_match(NULL, NULL)"): self.db_conn.create_function("litkit_word_match", 2, _word_match, deterministic=True) if scope == "global": cur.execute( diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index 13ff120..c9d9847 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -488,6 +488,53 @@ def test_single_superscripts_preserve_query_subject_and_identifier(lexical_db, q ) +@pytest.mark.parametrize("spelling", ["EGFRᵃ", "EGFR™", "EGFRᵇ"]) +def test_alphabetic_superscripts_are_searchable_in_questions_bodies_and_titles( + lexical_db, spelling +): + lexical_db.executemany( + "INSERT INTO papers(id,title) VALUES (?,?)", [(4, "Control"), (5, spelling)] + ) + lexical_db.executemany( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (?,?,0,?)", + [ + (20, 4, "EGFR signaling."), + (21, 5, f"We measured {spelling}."), + (22, 4, "EGFRactive is a longer word."), + ], + ) + config = LexicalConfig() + backend = SqliteLexicalBackend(lexical_db, load_temp_candidates) + for query in ("Does EGFR affect tumors?", f"Does {spelling} affect tumors?"): + terms = find_rare_terms(query, config) + assert backend.search(terms, None, config).chunk_ids == [21, 20] + assert "methyltransferase" in find_rare_terms("How is methyltransferaseᵇ measured?", config) + + +@pytest.mark.parametrize( + ("question", "limit"), + [ + ("marker² and EGFR", 1), + ("marker² and EGFR", 8), + ("marker² in TNF IFN VEGF EGFR KRAS BRAF PTEN MYC", 8), + ], +) +def test_ambiguous_superscript_respects_term_priority_across_readings(lexical_db, question, limit): + lexical_db.executemany( + "INSERT INTO papers(id,title) VALUES (?,?)", [(4, "marker2"), (5, "EGFR")] + ) + lexical_db.executemany( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (?,?,0,?)", + [(20, 4, "marker2 was expressed."), (21, 5, "EGFR was expressed.")], + ) + config = LexicalConfig(max_terms=limit) + terms = find_rare_terms(question, config) + assert terms == find_rare_terms(question.replace("²", "2"), config) + assert terms[0] == "marker2" + backend = SqliteLexicalBackend(lexical_db, load_temp_candidates) + assert backend.search(terms, None, config).chunk_ids[0] == 20 + + def test_unused_denied_sql_function_does_not_block_lexical_search(lexical_db): def authorize(action, arg1, arg2, database, trigger): if action == sqlite3.SQLITE_FUNCTION and arg2 == "litkit_word_match": From 4b5da93a26eda477c86ee89015cdfe75dd954609 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 14:25:17 -0700 Subject: [PATCH 13/21] Distinguish numeric powers from literal counts and internal identifier digits Signed-off-by: Bill Hlavacek --- src/litkit/retrieval/helpers.py | 2 +- src/litkit/retrieval/lexical.py | 70 +++++++++++++++++---------------- tests/test_retrieval.py | 37 +++++++++++++++++ 3 files changed, 75 insertions(+), 34 deletions(-) diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index 0661e5d..0f9a250 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -46,7 +46,7 @@ _LENGTH_UNIT = r"[fpnuµμmck]?m" _QUANTITY_POWER_RE = re.compile( rf"(? bool: return norm_term.isascii() and norm_term.isalpha() and len(norm_term) <= _ACRONYM_MAX_LEN +def _number_match(text: object, term: object) -> int: + """Match literal or compatibility digits without joining a base to its exponent.""" + if not isinstance(text, str) or not isinstance(term, str): + return 0 + if term in text: + return 1 + if text.isascii() or term not in normalize_for_search_py(text): + return 0 + return int(term in _query_spellings(text)[0]) + + +def _match_spec(term: str) -> tuple[str | None, str]: + if _needs_word_boundary(term): + return "litkit_word_match", term + if term.isdecimal(): + return "litkit_number_match", term + return None, f"%{escape_like(term)}%" + + +def _match_sql(field: str, function: str | None) -> str: + if function is not None: + return f"{function}({field}, ?)" + return f"{sqlite_norm_expr(field)} LIKE ? ESCAPE '\\'" + + def _has_sql_function(conn: sqlite3.Connection, call: str) -> bool: """Check whether the connection can prepare a call with this name and arity.""" try: @@ -246,34 +271,12 @@ def search( scope = "global" if candidate_papers is None else "candidates" - # 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] = [] - uses_normalizer = uses_word_match = False - normalized_terms = [normalize_for_search_py(t) for t in terms] - for nt in normalized_terms: - if _needs_word_boundary(nt): - uses_word_match = True - like_parts.append("litkit_word_match(c.text, ?)") - params.append(nt) - else: - uses_normalizer = True - like_parts.append(f"{norm} LIKE ? ESCAPE '\\'") - params.append(f"%{escape_like(nt)}%") - like_clause = " OR ".join(like_parts) - - # Title hint for sorting (prefer chunks from papers with matching title) - title_hint = normalized_terms[0] - title_norm = sqlite_norm_expr("p.title") - if title_hint and _needs_word_boundary(title_hint): - title_expr = "litkit_word_match(p.title, ?)" - title_params: list[object] = [title_hint] - else: - title_expr = f"{title_norm} LIKE ? ESCAPE '\\'" - title_params = [f"%{escape_like(title_hint)}%" if title_hint else "%"] + # Apply the same matching rule to the body and the first term's title hint. + specs = [_match_spec(normalize_for_search_py(t)) for t in terms] + like_clause = " OR ".join(_match_sql("c.text", name) for name, _ in specs) + title_expr = _match_sql("p.title", specs[0][0]) + params = [value for _, value in specs] + [specs[0][1], config.limit] + required = {name for name, _ in specs} cur = self.db_conn.cursor() chunk_ids: list[int] = [] @@ -282,10 +285,11 @@ def search( # Probe only functions this query needs. Replacing an existing one # can fail while a client cursor is active, and a locked database # must follow the same lexical fallback as the SELECT below. - if uses_normalizer and not _has_sql_function(self.db_conn, "litkit_normalize(NULL)"): + if None in required and not _has_sql_function(self.db_conn, "litkit_normalize(NULL)"): register_search_normalizer(self.db_conn) - if uses_word_match and not _has_sql_function(self.db_conn, "litkit_word_match(NULL, NULL)"): - self.db_conn.create_function("litkit_word_match", 2, _word_match, deterministic=True) + for name, matcher in (("litkit_word_match", _word_match), ("litkit_number_match", _number_match)): + if name in required and not _has_sql_function(self.db_conn, f"{name}(NULL, NULL)"): + self.db_conn.create_function(name, 2, matcher, deterministic=True) if scope == "global": cur.execute( f""" @@ -300,7 +304,7 @@ def search( c.id ASC LIMIT ? """, - params + title_params + [config.limit], + params, ) else: # Scope to candidate papers @@ -319,7 +323,7 @@ def search( c.id ASC LIMIT ? """, - params + title_params + [config.limit], + params, ) chunk_ids = [row[0] for row in cur.fetchall()] diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index c9d9847..5c5e793 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -397,6 +397,22 @@ def test_numeric_powers_do_not_match_unrelated_integers(lexical_db, sample): assert backend.search(terms, None, config).chunk_ids == [20] +@pytest.mark.parametrize( + ("formatted", "plain"), [("m⁶A", "m6A"), ("m¹A", "m1A"), ("m³C", "m3C"), ("m⁶Am", "m6Am")] +) +def test_internal_superscript_is_part_of_a_scientific_identifier(lexical_db, formatted, plain): + lexical_db.executemany( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (?,1,?,?)", + [(20, 20, f"Detection of {plain}."), (21, 21, f"Detection of {formatted}.")], + ) + config = LexicalConfig() + terms = find_rare_terms(f"What is {formatted}?", config) + assert terms == find_rare_terms(f"What is {plain}?", config) == [plain.lower()] + assert SqliteLexicalBackend(lexical_db, load_temp_candidates).search( + terms, None, config + ).chunk_ids == [20, 21] + + def test_numbered_scientific_identifiers_keep_priority(lexical_db): lexical_db.executemany( "INSERT INTO chunks(id,paper_id,ord,text) VALUES (?,1,?,?)", @@ -488,6 +504,27 @@ def test_single_superscripts_preserve_query_subject_and_identifier(lexical_db, q ) +def test_number_query_does_not_retrieve_a_flattened_power_or_citation(lexical_db): + lexical_db.executemany( + "INSERT INTO papers(id,title) VALUES (?,?)", [(4, "10⁶ cells"), (5, "106 participants")] + ) + lexical_db.executemany( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (?,?,0,?)", + [ + (20, 4, "Aliquots contained 10⁶ cells."), + (21, 4, "Findings in 106 participants."), + (22, 5, "Results for 106 subjects."), + (23, 4, "Gene expression [¹⁰⁶]."), + ], + ) + config = LexicalConfig() + terms = find_rare_terms("What are the findings in 106 participants?", config) + assert terms == ["106"] + assert SqliteLexicalBackend(lexical_db, load_temp_candidates).search( + terms, None, config + ).chunk_ids == [22, 21] + + @pytest.mark.parametrize("spelling", ["EGFRᵃ", "EGFR™", "EGFRᵇ"]) def test_alphabetic_superscripts_are_searchable_in_questions_bodies_and_titles( lexical_db, spelling From 1fd067eb1c5053825e23faba1e8f189d4ef14159 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 14:30:44 -0700 Subject: [PATCH 14/21] Preserve internal and leading isotope masses in chemical formulas Signed-off-by: Bill Hlavacek --- src/litkit/retrieval/helpers.py | 8 +++++--- tests/test_retrieval.py | 27 +++++++++++++++++++++++++-- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index 0f9a250..5b70efe 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -44,9 +44,10 @@ # typography. A numeric exponent is not an ordinary integer (10⁶ ≠ 106). _DECIMAL = r"\d+(?:[.,]\d+)?" _LENGTH_UNIT = r"[fpnuµμmck]?m" +_EXPONENT = rf"[⁺⁻]?[{_SUPERSCRIPT_DIGITS}]+" _QUANTITY_POWER_RE = re.compile( rf"(? st # a pasted citation (IL-6¹, CD4¹) must leave the identifier searchable. before = match.string[match.start() - 1] if match.start() else "" after = match.string[match.end() : match.end() + 1] - if before.isdecimal() or (not before.isalnum() and not after.isalnum()): + if not after.isalnum() and (before.isdecimal() or not before.isalnum()): return " " - if as_citation and (not before.isalnum() or not after.isalnum()): + # A leading raised number is part of an isotope label such as ¹³CH₄. + if as_citation and (not after.isalnum() or (not before.isalnum() and not match[0].isdigit())): return " " return unicodedata.normalize("NFKC", match[0]) diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index 5c5e793..aa6b0d6 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -383,7 +383,16 @@ def test_measurements_do_not_displace_the_query_subject(lexical_db): @pytest.mark.parametrize( "sample", - ["10⁶ cells", "3×10⁵ cells", "1.25 × 10⁶ cells", "5–10⁶ cells", "10⁻³ M", "10 cm²", "2µm³"], + [ + "10⁶ cells", + "10⁶cells", + "3×10⁵ cells", + "1.25 × 10⁶ cells", + "5–10⁶ cells", + "10⁻³ M", + "10 cm²", + "2µm³", + ], ) def test_numeric_powers_do_not_match_unrelated_integers(lexical_db, sample): lexical_db.executemany( @@ -398,7 +407,8 @@ def test_numeric_powers_do_not_match_unrelated_integers(lexical_db, sample): @pytest.mark.parametrize( - ("formatted", "plain"), [("m⁶A", "m6A"), ("m¹A", "m1A"), ("m³C", "m3C"), ("m⁶Am", "m6Am")] + ("formatted", "plain"), + [("m⁶A", "m6A"), ("m¹A", "m1A"), ("m³C", "m3C"), ("m⁶Am", "m6Am"), ("H₂¹⁸O", "H218O")], ) def test_internal_superscript_is_part_of_a_scientific_identifier(lexical_db, formatted, plain): lexical_db.executemany( @@ -525,6 +535,19 @@ def test_number_query_does_not_retrieve_a_flattened_power_or_citation(lexical_db ).chunk_ids == [22, 21] +def test_leading_isotope_mass_does_not_match_the_unlabelled_compound(lexical_db): + lexical_db.executemany( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (?,1,?,?)", + [(20, 20, "Concentrations of CH4."), (21, 21, "We measured the rare isotope 13CH4.")], + ) + config = LexicalConfig() + terms = find_rare_terms("How is ¹³CH₄ detected?", config) + assert terms == find_rare_terms("How is 13CH4 detected?", config) == ["13ch4"] + assert SqliteLexicalBackend(lexical_db, load_temp_candidates).search( + terms, None, config + ).chunk_ids == [21] + + @pytest.mark.parametrize("spelling", ["EGFRᵃ", "EGFR™", "EGFRᵇ"]) def test_alphabetic_superscripts_are_searchable_in_questions_bodies_and_titles( lexical_db, spelling From ff906550f029c5f93ebd73a8fcab01f37effbaac Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 14:36:33 -0700 Subject: [PATCH 15/21] Recognize leading table footnotes without broadening isotope queries Signed-off-by: Bill Hlavacek --- src/litkit/retrieval/helpers.py | 28 +++++++++++++++++++++------- tests/test_retrieval.py | 15 +++++++++++++++ 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index 5b70efe..0ed8d4a 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -40,6 +40,9 @@ _EN_FIGURE_DASH_BETWEEN_ALNUM_RE = re.compile(r"(?<=[^\W_])[‒–](?=[^\W_])") _SUPERSCRIPT_DIGITS = "⁰¹²³⁴⁵⁶⁷⁸⁹" _NON_ASCII_RE = re.compile(r"[^\x00-\x7f]") +# One-letter element symbols include D and T in isotope notation. A two-letter +# symbol uses a lowercase second letter, distinguishing a formula from EGFR. +_FORMULA_RE = re.compile(r"(?:(?:[A-Z][a-z]|[BCDFHIKNOPSTUVWY])\d*)+(?!\w)") # Separate numerical powers from identifiers before NFKC flattens their # typography. A numeric exponent is not an ordinary integer (10⁶ ≠ 106). _DECIMAL = r"\d+(?:[.,]\d+)?" @@ -64,7 +67,7 @@ def _superscript_pattern(s: str) -> str | None: return f"[{re.escape(''.join(sorted(marks)))}]+" if marks else None -def _query_superscript(match: re.Match[str], *, as_citation: bool = False) -> str: +def _query_superscript(match: re.Match[str]) -> str: if "⁺" in match[0] or "⁻" in match[0]: return " " # Standalone powers have been removed. After an identifier's final digit, @@ -73,14 +76,25 @@ def _query_superscript(match: re.Match[str], *, as_citation: bool = False) -> st after = match.string[match.end() : match.end() + 1] if not after.isalnum() and (before.isdecimal() or not before.isalnum()): return " " - # A leading raised number is part of an isotope label such as ¹³CH₄. - if as_citation and (not after.isalnum() or (not before.isalnum() and not match[0].isdigit())): - return " " return unicodedata.normalize("NFKC", match[0]) -def _cited_reading(s: str, pattern: str) -> str: - return re.sub(pattern, lambda m: _query_superscript(m, as_citation=True), s) +def _cited_reading(s: str, pattern: str, *, keep_isotope_labels: bool = False) -> str: + def replace(match: re.Match[str]) -> str: + before = s[match.start() - 1] if match.start() else "" + after = s[match.end() : match.end() + 1] + if before.isalnum() and after.isalnum(): + return _query_superscript(match) + if ( + keep_isotope_labels + and not before.isalnum() + and match[0].isdigit() + and _FORMULA_RE.match(s, match.end()) + ): + return _query_superscript(match) + return " " + + return re.sub(pattern, replace, s) def _query_spellings(s: str) -> tuple[str, ...]: @@ -104,7 +118,7 @@ def _query_spellings(s: str) -> tuple[str, ...]: if not raised: return (s,) numbered = re.sub(raised, _query_superscript, s) - cited = _cited_reading(s, raised) + cited = _cited_reading(s, raised, keep_isotope_labels=True) return (numbered,) if numbered == cited else (numbered, cited) diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index aa6b0d6..63a0676 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -548,6 +548,21 @@ def test_leading_isotope_mass_does_not_match_the_unlabelled_compound(lexical_db) ).chunk_ids == [21] +def test_leading_footnote_preserves_query_and_stored_acronym_boundaries(lexical_db): + lexical_db.executemany( + "INSERT INTO papers(id,title) VALUES (?,?)", [(4, "Control"), (5, "¹EGFR")] + ) + lexical_db.executemany( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (?,?,0,?)", + [(20, 4, "EGFR expression."), (21, 5, "¹EGFR was measured at baseline.")], + ) + config = LexicalConfig() + backend = SqliteLexicalBackend(lexical_db, load_temp_candidates) + for query in ("How was EGFR measured?", "How was ¹EGFR measured?"): + terms = find_rare_terms(query, config) + assert backend.search(terms, None, config).chunk_ids == [21, 20] + + @pytest.mark.parametrize("spelling", ["EGFRᵃ", "EGFR™", "EGFRᵇ"]) def test_alphabetic_superscripts_are_searchable_in_questions_bodies_and_titles( lexical_db, spelling From e175003a5ffa93d899d66f756d50d6ada4de8a7d Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 14:48:17 -0700 Subject: [PATCH 16/21] Preserve query subjects after leading table notes Signed-off-by: Bill Hlavacek --- src/litkit/retrieval/helpers.py | 31 +++++++++++++++++++++++------- src/litkit/retrieval/lexical.py | 19 ++++++++++++++++-- tests/test_retrieval.py | 34 +++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 9 deletions(-) diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index 0ed8d4a..57bc9c3 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -43,6 +43,9 @@ # One-letter element symbols include D and T in isotope notation. A two-letter # symbol uses a lowercase second letter, distinguishing a formula from EGFR. _FORMULA_RE = re.compile(r"(?:(?:[A-Z][a-z]|[BCDFHIKNOPSTUVWY])\d*)+(?!\w)") +# These element symbols also spell stopwords. A preceding table note such as +# “¹In this study” cannot label indium with a mass below its atomic number. +_STOPWORD_ELEMENTS = {"Be": 4, "As": 33, "In": 49, "I": 53, "At": 85} # Separate numerical powers from identifiers before NFKC flattens their # typography. A numeric exponent is not an ordinary integer (10⁶ ≠ 106). _DECIMAL = r"\d+(?:[.,]\d+)?" @@ -76,6 +79,19 @@ def _query_superscript(match: re.Match[str]) -> str: after = match.string[match.end() : match.end() + 1] if not after.isalnum() and (before.isdecimal() or not before.isalnum()): return " " + if not before.isalnum() and match[0].isdigit(): + following = _TOKEN_RE.match(match.string, match.end()) + if following and following[0].isalpha(): + word = following[0] + if word.lower() in _STOPWORDS: + atomic_number = _STOPWORD_ELEMENTS.get(word) + mass = unicodedata.normalize("NFKC", match[0]) + if atomic_number is None or len(mass) > 3 or int(mass) < atomic_number: + return " " + elif not _acronym_stem(word) and not _FORMULA_RE.fullmatch(word): + # A note before prose ("¹Methods") must not turn the first + # word into a numbered identifier and suppress the subject. + return " " return unicodedata.normalize("NFKC", match[0]) @@ -85,13 +101,14 @@ def replace(match: re.Match[str]) -> str: after = s[match.end() : match.end() + 1] if before.isalnum() and after.isalnum(): return _query_superscript(match) - if ( - keep_isotope_labels - and not before.isalnum() - and match[0].isdigit() - and _FORMULA_RE.match(s, match.end()) - ): - return _query_superscript(match) + if keep_isotope_labels and not before.isalnum() and match[0].isdigit(): + formula = _FORMULA_RE.match(s, match.end()) + if formula: + # A bare acronym such as COPD can also be parsed as a string + # of element symbols. Keep the table-note reading as well. + word = formula[0] + if not word.isalpha() or not _acronym_stem(word): + return _query_superscript(match) return " " return re.sub(pattern, replace, s) diff --git a/src/litkit/retrieval/lexical.py b/src/litkit/retrieval/lexical.py index ebf7eb6..51b513e 100644 --- a/src/litkit/retrieval/lexical.py +++ b/src/litkit/retrieval/lexical.py @@ -200,11 +200,12 @@ def find_rare_terms(question: str, config: LexicalConfig) -> list[str]: long_terms = [] acronyms = [] measurements = [] - for spelling in _query_spellings(question): + for index, spelling in enumerate(_query_spellings(question)): # A possible citation on “patients¹” must leave the long-term fallback # available in the citation reading of “methyltransferase in patients¹”. technical = [] descriptive = [] + spelling_acronyms = [] for term, acronym in _extract_query_terms(spelling): lowered = term.lower() if _MEASUREMENT_RE.fullmatch(term): @@ -215,7 +216,21 @@ def find_rare_terms(question: str, config: LexicalConfig) -> list[str]: if len(lowered) >= config.min_term_length: descriptive.append(lowered) if acronym: - acronyms.append(lowered) + spelling_acronyms.append(lowered) + if index: + # For a leading note on an acronym (¹HIV), search HIV before the + # possible numbered alias. A literal 1HIV is present in both views. + preferred = [] + for term in primary: + plain = term.lstrip("0123456789") + if plain != term and term not in technical: + if plain.endswith("s") and plain[:-1] in spelling_acronyms: + plain = plain[:-1] + if plain in spelling_acronyms: + preferred.append(plain) + preferred.append(term) + primary = preferred + acronyms.extend(spelling_acronyms) if technical: primary.extend(technical) else: diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index 63a0676..adca2a6 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -563,6 +563,40 @@ def test_leading_footnote_preserves_query_and_stored_acronym_boundaries(lexical_ assert backend.search(terms, None, config).chunk_ids == [21, 20] +@pytest.mark.parametrize( + ("question", "expected"), + [ + ("How was ¹HIV diagnosed?", 20), + ("How was ¹COPD diagnosed?", 21), + ("¹We studied methyltransferase activity.", 22), + ("¹In methyltransferase assays, what changed?", 22), + ("¹Methods to quantify methyltransferase activity.", 22), + ("How is ¹¹⁵In detected?", 23), + ], +) +@pytest.mark.parametrize("max_terms", [1, 8]) +def test_leading_notes_keep_acronyms_and_prose_subjects(lexical_db, question, expected, max_terms): + lexical_db.executemany( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (?,1,?,?)", + [ + (20, 20, "HIV diagnosis."), + (21, 21, "COPD diagnosis."), + (22, 22, "Methyltransferase activity."), + (23, 23, "A rare 115In isotope."), + (24, 24, "Unrelated specimen codes 1we, 1methods and 1in."), + ], + ) + config = LexicalConfig(max_terms=max_terms) + terms = find_rare_terms(question, config) + result = SqliteLexicalBackend(lexical_db, load_temp_candidates).search(terms, None, config) + assert result.chunk_ids == [expected] + + +def test_literal_numbered_acronym_keeps_its_priority(): + config = LexicalConfig(max_terms=1) + assert find_rare_terms("How was 1HIV diagnosed in HIV cases with marker²?", config) == ["1hiv"] + + @pytest.mark.parametrize("spelling", ["EGFRᵃ", "EGFR™", "EGFRᵇ"]) def test_alphabetic_superscripts_are_searchable_in_questions_bodies_and_titles( lexical_db, spelling From 26d3d616c1476ab2a1e34fec80e320bdf10ff1fd Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 14:53:00 -0700 Subject: [PATCH 17/21] Check isotope notation before attaching leading notes to identifiers Signed-off-by: Bill Hlavacek --- src/litkit/retrieval/helpers.py | 74 +++++++++++++++++++++------------ tests/test_retrieval.py | 19 +++++++++ 2 files changed, 66 insertions(+), 27 deletions(-) diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index 57bc9c3..2cb1d37 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -40,12 +40,22 @@ _EN_FIGURE_DASH_BETWEEN_ALNUM_RE = re.compile(r"(?<=[^\W_])[‒–](?=[^\W_])") _SUPERSCRIPT_DIGITS = "⁰¹²³⁴⁵⁶⁷⁸⁹" _NON_ASCII_RE = re.compile(r"[^\x00-\x7f]") -# One-letter element symbols include D and T in isotope notation. A two-letter -# symbol uses a lowercase second letter, distinguishing a formula from EGFR. -_FORMULA_RE = re.compile(r"(?:(?:[A-Z][a-z]|[BCDFHIKNOPSTUVWY])\d*)+(?!\w)") -# These element symbols also spell stopwords. A preceding table note such as -# “¹In this study” cannot label indium with a mass below its atomic number. -_STOPWORD_ELEMENTS = {"Be": 4, "As": 33, "In": 49, "I": 53, "At": 85} +_ELEMENT_RE = re.compile(r"[A-Z][a-z]?") +_FORMULA_RE = re.compile(r"(?:[A-Z][a-z]?\d*)+") +_ATOMIC_NUMBERS = { + symbol: number + for number, symbol in enumerate( + ( + "H He Li Be B C N O F Ne Na Mg Al Si P S Cl Ar K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn " + "Ga Ge As Se Br Kr Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe Cs Ba La Ce " + "Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At " + "Rn Fr Ra Ac Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr Rf Db Sg Bh Hs Mt Ds Rg Cn " + "Nh Fl Mc Lv Ts Og" + ).split(), + start=1, + ) +} +_ATOMIC_NUMBERS.update(D=1, T=1) # Separate numerical powers from identifiers before NFKC flattens their # typography. A numeric exponent is not an ordinary integer (10⁶ ≠ 106). _DECIMAL = r"\d+(?:[.,]\d+)?" @@ -70,6 +80,28 @@ def _superscript_pattern(s: str) -> str | None: return f"[{re.escape(''.join(sorted(marks)))}]+" if marks else None +def _keep_leading_number(match: re.Match[str], *, numbered_acronyms: bool) -> bool: + """Preserve isotope labels, and optionally the numbered reading of a bare acronym.""" + following = _TOKEN_RE.match(match.string, match.end()) + if not following: + return False + word = following[0] + if word.isalpha() and word.lower() not in _STOPWORDS and _acronym_stem(word): + return numbered_acronyms + # A mass can prefix a formula or a named tracer such as ¹⁸F-FDG. For + # ¹CD4 the mass is below carbon's atomic number, so it is a table note. + formula, _, suffix = word.partition("-") + if suffix[:1].isdigit() or not _FORMULA_RE.fullmatch(formula): + return False + elements = _ELEMENT_RE.findall(formula) + mass = unicodedata.normalize("NFKC", match[0]) + return ( + len(mass) <= 3 + and all(symbol in _ATOMIC_NUMBERS for symbol in elements) + and int(mass) >= _ATOMIC_NUMBERS[elements[0]] + ) + + def _query_superscript(match: re.Match[str]) -> str: if "⁺" in match[0] or "⁻" in match[0]: return " " @@ -79,19 +111,12 @@ def _query_superscript(match: re.Match[str]) -> str: after = match.string[match.end() : match.end() + 1] if not after.isalnum() and (before.isdecimal() or not before.isalnum()): return " " - if not before.isalnum() and match[0].isdigit(): - following = _TOKEN_RE.match(match.string, match.end()) - if following and following[0].isalpha(): - word = following[0] - if word.lower() in _STOPWORDS: - atomic_number = _STOPWORD_ELEMENTS.get(word) - mass = unicodedata.normalize("NFKC", match[0]) - if atomic_number is None or len(mass) > 3 or int(mass) < atomic_number: - return " " - elif not _acronym_stem(word) and not _FORMULA_RE.fullmatch(word): - # A note before prose ("¹Methods") must not turn the first - # word into a numbered identifier and suppress the subject. - return " " + if ( + not before.isalnum() + and match[0].isdigit() + and not _keep_leading_number(match, numbered_acronyms=True) + ): + return " " return unicodedata.normalize("NFKC", match[0]) @@ -102,20 +127,15 @@ def replace(match: re.Match[str]) -> str: if before.isalnum() and after.isalnum(): return _query_superscript(match) if keep_isotope_labels and not before.isalnum() and match[0].isdigit(): - formula = _FORMULA_RE.match(s, match.end()) - if formula: - # A bare acronym such as COPD can also be parsed as a string - # of element symbols. Keep the table-note reading as well. - word = formula[0] - if not word.isalpha() or not _acronym_stem(word): - return _query_superscript(match) + if _keep_leading_number(match, numbered_acronyms=False): + return unicodedata.normalize("NFKC", match[0]) return " " return re.sub(pattern, replace, s) def _query_spellings(s: str) -> tuple[str, ...]: - """Normalize a query, retaining both readings of an ambiguous superscript suffix.""" + """Normalize a query, retaining both readings of an ambiguous superscript.""" if s.isascii(): return (s,) # Normalize the context first so e.g. IL‑6 and CD₄ are recognizable while diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index adca2a6..d754b71 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -568,6 +568,8 @@ def test_leading_footnote_preserves_query_and_stored_acronym_boundaries(lexical_ [ ("How was ¹HIV diagnosed?", 20), ("How was ¹COPD diagnosed?", 21), + ("How were ¹CD4 counts measured?", 25), + ("What were ¹COVID-19 outcomes?", 26), ("¹We studied methyltransferase activity.", 22), ("¹In methyltransferase assays, what changed?", 22), ("¹Methods to quantify methyltransferase activity.", 22), @@ -584,6 +586,8 @@ def test_leading_notes_keep_acronyms_and_prose_subjects(lexical_db, question, ex (22, 22, "Methyltransferase activity."), (23, 23, "A rare 115In isotope."), (24, 24, "Unrelated specimen codes 1we, 1methods and 1in."), + (25, 25, "We measured CD4 counts."), + (26, 26, "Long-term outcomes after COVID-19."), ], ) config = LexicalConfig(max_terms=max_terms) @@ -597,6 +601,21 @@ def test_literal_numbered_acronym_keeps_its_priority(): assert find_rare_terms("How was 1HIV diagnosed in HIV cases with marker²?", config) == ["1hiv"] +@pytest.mark.parametrize(("formatted", "plain"), [("¹³CD₄", "13CD4"), ("¹⁸F-FDG", "18F-FDG")]) +def test_isotope_specificity_for_a_formula_or_named_tracer(lexical_db, formatted, plain): + unlabelled = plain.lstrip("0123456789") + lexical_db.executemany( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (?,1,?,?)", + [(20, 20, f"Measured {plain} uptake."), (21, 21, f"Measured {unlabelled} uptake.")], + ) + config = LexicalConfig() + terms = find_rare_terms(f"How was {formatted} detected?", config) + assert terms == [plain.lower()] + assert SqliteLexicalBackend(lexical_db, load_temp_candidates).search( + terms, None, config + ).chunk_ids == [20] + + @pytest.mark.parametrize("spelling", ["EGFRᵃ", "EGFR™", "EGFRᵇ"]) def test_alphabetic_superscripts_are_searchable_in_questions_bodies_and_titles( lexical_db, spelling From 96b3f4c1e2e4fc503d4284e277e8a7eb39b961cc Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 14:58:32 -0700 Subject: [PATCH 18/21] Retain all isotope labels when matching named compounds and tracers Signed-off-by: Bill Hlavacek --- src/litkit/retrieval/helpers.py | 36 +++++++++++++++++++++------------ tests/test_retrieval.py | 31 ++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 13 deletions(-) diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index 2cb1d37..d3a8776 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -42,6 +42,9 @@ _NON_ASCII_RE = re.compile(r"[^\x00-\x7f]") _ELEMENT_RE = re.compile(r"[A-Z][a-z]?") _FORMULA_RE = re.compile(r"(?:[A-Z][a-z]?\d*)+") +_ISOTOPE_MASS_RE = re.compile(r"([0-9]{1,3})(?:m[0-9]*)?") +# These biomedical acronyms can each be read entirely as element symbols. +_AMBIGUOUS_BIOMEDICAL_ACRONYMS = {"COPD", "HBV", "HCV", "HIV", "HPV"} _ATOMIC_NUMBERS = { symbol: number for number, symbol in enumerate( @@ -85,21 +88,28 @@ def _keep_leading_number(match: re.Match[str], *, numbered_acronyms: bool) -> bo following = _TOKEN_RE.match(match.string, match.end()) if not following: return False - word = following[0] - if word.isalpha() and word.lower() not in _STOPWORDS and _acronym_stem(word): + word = unicodedata.normalize("NFKC", following[0]) + acronym = word.isalpha() and word.lower() not in _STOPWORDS and bool(_acronym_stem(word)) + if acronym and word.removesuffix("s") in _AMBIGUOUS_BIOMEDICAL_ACRONYMS: return numbered_acronyms + mass = _ISOTOPE_MASS_RE.fullmatch(unicodedata.normalize("NFKC", match[0])) + if not mass: + return False # A mass can prefix a formula or a named tracer such as ¹⁸F-FDG. For # ¹CD4 the mass is below carbon's atomic number, so it is a table note. formula, _, suffix = word.partition("-") - if suffix[:1].isdigit() or not _FORMULA_RE.fullmatch(formula): - return False - elements = _ELEMENT_RE.findall(formula) - mass = unicodedata.normalize("NFKC", match[0]) - return ( - len(mass) <= 3 - and all(symbol in _ATOMIC_NUMBERS for symbol in elements) - and int(mass) >= _ATOMIC_NUMBERS[elements[0]] - ) + if _FORMULA_RE.fullmatch(formula) and (not suffix.isdecimal() or formula in _ATOMIC_NUMBERS): + elements = _ELEMENT_RE.findall(formula) + number = int(mass[1]) + # In bare acronyms ¹ is commonly a note (¹HIV). Keep explicit + # isotope masses in formulas such as ¹³COOH. + if ( + all(symbol in _ATOMIC_NUMBERS for symbol in elements) + and number >= _ATOMIC_NUMBERS[elements[0]] + and (not acronym or number > 1) + ): + return True + return acronym and numbered_acronyms def _query_superscript(match: re.Match[str]) -> str: @@ -113,7 +123,7 @@ def _query_superscript(match: re.Match[str]) -> str: return " " if ( not before.isalnum() - and match[0].isdigit() + and match[0][0].isdigit() and not _keep_leading_number(match, numbered_acronyms=True) ): return " " @@ -126,7 +136,7 @@ def replace(match: re.Match[str]) -> str: after = s[match.end() : match.end() + 1] if before.isalnum() and after.isalnum(): return _query_superscript(match) - if keep_isotope_labels and not before.isalnum() and match[0].isdigit(): + if keep_isotope_labels and not before.isalnum() and match[0][0].isdigit(): if _keep_leading_number(match, numbered_acronyms=False): return unicodedata.normalize("NFKC", match[0]) return " " diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index d754b71..48328db 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -568,6 +568,9 @@ def test_leading_footnote_preserves_query_and_stored_acronym_boundaries(lexical_ [ ("How was ¹HIV diagnosed?", 20), ("How was ¹COPD diagnosed?", 21), + ("How was ²HIV diagnosed?", 20), + ("How was ¹³COPD diagnosed?", 21), + ("How was ²HPV diagnosed?", 27), ("How were ¹CD4 counts measured?", 25), ("What were ¹COVID-19 outcomes?", 26), ("¹We studied methyltransferase activity.", 22), @@ -588,6 +591,7 @@ def test_leading_notes_keep_acronyms_and_prose_subjects(lexical_db, question, ex (24, 24, "Unrelated specimen codes 1we, 1methods and 1in."), (25, 25, "We measured CD4 counts."), (26, 26, "Long-term outcomes after COVID-19."), + (27, 27, "HPV diagnosis."), ], ) config = LexicalConfig(max_terms=max_terms) @@ -616,6 +620,33 @@ def test_isotope_specificity_for_a_formula_or_named_tracer(lexical_db, formatted ).chunk_ids == [20] +@pytest.mark.parametrize( + ("formatted", "plain", "other"), + [ + ("¹³C¹⁸O₂", "13C18O2", "¹²C¹⁸O₂"), + ("¹³C₆¹⁵N₂-lysine", "13C615N2-lysine", "¹²C₆¹⁵N₂-lysine"), + ( + "¹⁸F-2-fluoro-2-deoxy-D-glucose", + "18F-2-fluoro-2-deoxy-D-glucose", + "¹⁹F-2-fluoro-2-deoxy-D-glucose", + ), + ("⁹⁹ᵐTc-DTPA", "99mTc-DTPA", "99Tc-DTPA"), + ("¹³COOH", "13COOH", "COOH"), + ], +) +def test_labelled_compounds_distinguish_the_first_isotope(lexical_db, formatted, plain, other): + lexical_db.executemany( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (?,1,?,?)", + [(20, 20, f"We measured {other}."), (21, 21, f"We measured {formatted}.")], + ) + config = LexicalConfig(limit=1) + backend = SqliteLexicalBackend(lexical_db, load_temp_candidates) + for spelling in (formatted, plain): + terms = find_rare_terms(f"How was {spelling} detected?", config) + assert terms == [plain.lower()] + assert backend.search(terms, None, config).chunk_ids == [21] + + @pytest.mark.parametrize("spelling", ["EGFRᵃ", "EGFR™", "EGFRᵇ"]) def test_alphabetic_superscripts_are_searchable_in_questions_bodies_and_titles( lexical_db, spelling From ad098fe4d749abf2e459a11f18974512929ab3f2 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 15:04:41 -0700 Subject: [PATCH 19/21] Resolve ambiguous superscript acronyms within the active search scope Signed-off-by: Bill Hlavacek --- src/litkit/retrieval/helpers.py | 50 ++++++++------- src/litkit/retrieval/lexical.py | 106 +++++++++++++++++--------------- tests/test_retrieval.py | 40 +++++++++++- 3 files changed, 120 insertions(+), 76 deletions(-) diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index d3a8776..85cc0cb 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -43,8 +43,9 @@ _ELEMENT_RE = re.compile(r"[A-Z][a-z]?") _FORMULA_RE = re.compile(r"(?:[A-Z][a-z]?\d*)+") _ISOTOPE_MASS_RE = re.compile(r"([0-9]{1,3})(?:m[0-9]*)?") -# These biomedical acronyms can each be read entirely as element symbols. -_AMBIGUOUS_BIOMEDICAL_ACRONYMS = {"COPD", "HBV", "HCV", "HIV", "HPV"} +_RAISED_ACRONYM_RE = re.compile( + rf"([{_SUPERSCRIPT_DIGITS}]+)([A-Z]{{3,4}})", re.ASCII | re.IGNORECASE +) _ATOMIC_NUMBERS = { symbol: number for number, symbol in enumerate( @@ -83,33 +84,33 @@ def _superscript_pattern(s: str) -> str | None: return f"[{re.escape(''.join(sorted(marks)))}]+" if marks else None -def _keep_leading_number(match: re.Match[str], *, numbered_acronyms: bool) -> bool: - """Preserve isotope labels, and optionally the numbered reading of a bare acronym.""" +def _leading_number(match: re.Match[str], *, cited: bool) -> str: + """Interpret a leading note or mass, preserving typography for ambiguous acronyms.""" following = _TOKEN_RE.match(match.string, match.end()) if not following: - return False + return " " word = unicodedata.normalize("NFKC", following[0]) acronym = word.isalpha() and word.lower() not in _STOPWORDS and bool(_acronym_stem(word)) - if acronym and word.removesuffix("s") in _AMBIGUOUS_BIOMEDICAL_ACRONYMS: - return numbered_acronyms - mass = _ISOTOPE_MASS_RE.fullmatch(unicodedata.normalize("NFKC", match[0])) + normalized = unicodedata.normalize("NFKC", match[0]) + mass = _ISOTOPE_MASS_RE.fullmatch(normalized) if not mass: - return False + return " " # A mass can prefix a formula or a named tracer such as ¹⁸F-FDG. For # ¹CD4 the mass is below carbon's atomic number, so it is a table note. formula, _, suffix = word.partition("-") if _FORMULA_RE.fullmatch(formula) and (not suffix.isdecimal() or formula in _ATOMIC_NUMBERS): elements = _ELEMENT_RE.findall(formula) number = int(mass[1]) - # In bare acronyms ¹ is commonly a note (¹HIV). Keep explicit - # isotope masses in formulas such as ¹³COOH. - if ( - all(symbol in _ATOMIC_NUMBERS for symbol in elements) - and number >= _ATOMIC_NUMBERS[elements[0]] - and (not acronym or number > 1) + if all(symbol in _ATOMIC_NUMBERS for symbol in elements) and ( + number >= _ATOMIC_NUMBERS[elements[0]] ): - return True - return acronym and numbered_acronyms + # Keep the distinction between ²HSV and literal 2HSV until the + # lexical backend can check for the labelled form inside the scope. + if acronym and number > 1 and match[0].isdigit(): + return match[0] + if not acronym or number > 1: + return normalized + return normalized if acronym and not cited else " " def _query_superscript(match: re.Match[str]) -> str: @@ -121,12 +122,8 @@ def _query_superscript(match: re.Match[str]) -> str: after = match.string[match.end() : match.end() + 1] if not after.isalnum() and (before.isdecimal() or not before.isalnum()): return " " - if ( - not before.isalnum() - and match[0][0].isdigit() - and not _keep_leading_number(match, numbered_acronyms=True) - ): - return " " + if not before.isalnum() and match[0][0].isdigit(): + return _leading_number(match, cited=False) return unicodedata.normalize("NFKC", match[0]) @@ -137,8 +134,7 @@ def replace(match: re.Match[str]) -> str: if before.isalnum() and after.isalnum(): return _query_superscript(match) if keep_isotope_labels and not before.isalnum() and match[0][0].isdigit(): - if _keep_leading_number(match, numbered_acronyms=False): - return unicodedata.normalize("NFKC", match[0]) + return _leading_number(match, cited=True) return " " return re.sub(pattern, replace, s) @@ -271,6 +267,8 @@ def _extract_query_terms(normalized: str) -> Iterator[tuple[str, bool]]: for w in _query_words(normalized): if len(w) < 3: continue + if w.endswith("s") and not w.isascii() and _RAISED_ACRONYM_RE.fullmatch(w[:-1]): + w = w[:-1] stem = _acronym_stem(w) if allow_acronyms else None term = stem or w if term.lower() in _STOPWORDS: @@ -301,7 +299,7 @@ def query_terms(s: str) -> list[str]: ambiguous superscripts """ terms = ( - term.lower() + normalize_for_search_py(term) for spelling in _query_spellings(s) for term, _ in _extract_query_terms(spelling) ) diff --git a/src/litkit/retrieval/lexical.py b/src/litkit/retrieval/lexical.py index 51b513e..278e797 100644 --- a/src/litkit/retrieval/lexical.py +++ b/src/litkit/retrieval/lexical.py @@ -28,6 +28,7 @@ from litkit.retrieval.helpers import ( _ACRONYM_MAX_LEN, _MEASUREMENT_RE, + _RAISED_ACRONYM_RE, _cited_reading, _extract_query_terms, _has_digit_or_joiner, @@ -48,9 +49,8 @@ def _word_boundary_re(term: str) -> re.Pattern[str]: # 'TNFα' while excluding substrings in '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'. - return re.compile( - rf"(? int: @@ -81,7 +81,7 @@ def _number_match(text: object, term: object) -> int: return 1 if text.isascii() or term not in normalize_for_search_py(text): return 0 - return int(term in _query_spellings(text)[0]) + return int(term in normalize_for_search_py(_query_spellings(text)[0])) def _match_spec(term: str) -> tuple[str | None, str]: @@ -92,10 +92,10 @@ def _match_spec(term: str) -> tuple[str | None, str]: return None, f"%{escape_like(term)}%" -def _match_sql(field: str, function: str | None) -> str: +def _match_sql(field: str, function: str | None, argument: str) -> str: if function is not None: - return f"{function}({field}, ?)" - return f"{sqlite_norm_expr(field)} LIKE ? ESCAPE '\\'" + return f"{function}({field}, {argument})" + return f"{sqlite_norm_expr(field)} LIKE {argument} ESCAPE '\\'" def _has_sql_function(conn: sqlite3.Connection, call: str) -> bool: @@ -194,7 +194,8 @@ def find_rare_terms(question: str, config: LexicalConfig) -> list[str]: config: LexicalConfig with min_term_length and max_terms Returns: - List of rare terms, capped at config.max_terms + List of rare terms, capped at config.max_terms. An ambiguous leading + superscript stays attached so a backend can resolve it within the search scope. """ primary = [] long_terms = [] @@ -286,13 +287,38 @@ def search( scope = "global" if candidate_papers is None else "candidates" - # Apply the same matching rule to the body and the first term's title hint. - specs = [_match_spec(normalize_for_search_py(t)) for t in terms] - like_clause = " OR ".join(_match_sql("c.text", name) for name, _ in specs) - title_expr = _match_sql("p.title", specs[0][0]) - params = [value for _, value in specs] + [specs[0][1], config.limit] - required = {name for name, _ in specs} - + source = "FROM chunks c JOIN papers p ON p.id = c.paper_id" + scope_clause = ( + "" if candidate_papers is None else "AND c.paper_id IN (SELECT id FROM cand_papers)" + ) + params: dict[str, str | int] = {"limit": config.limit} + choices = [] + specs = [] + for i, term in enumerate(terms): + normalized = normalize_for_search_py(term) + parameter = f"term{i}" + argument = f":{parameter}" + if marked := _RAISED_ACRONYM_RE.fullmatch(term): + # A mass on a short acronym may be a table note. Resolve that + # term once in the same scope and snapshot as the ranked hits. + name, value = "litkit_word_match", normalized + exact = _match_sql("c.text", name, argument) + choices.append( + f"CASE WHEN EXISTS (SELECT 1 {source} WHERE {exact} {scope_clause}) " + f"THEN {argument} ELSE :plain{i} END AS {parameter}" + ) + params[f"plain{i}"] = marked[2].lower() + argument = f"chosen.{parameter}" + else: + name, value = _match_spec(normalized) + params[parameter] = value + specs.append((name, argument)) + with_clause = "" + if choices: + with_clause = f"WITH chosen AS (SELECT {', '.join(choices)})" + source += " CROSS JOIN chosen" + like_clause = " OR ".join(_match_sql("c.text", *spec) for spec in specs) + title_expr = _match_sql("p.title", *specs[0]) cur = self.db_conn.cursor() chunk_ids: list[int] = [] @@ -300,46 +326,28 @@ def search( # Probe only functions this query needs. Replacing an existing one # can fail while a client cursor is active, and a locked database # must follow the same lexical fallback as the SELECT below. + required = {name for name, _ in specs} if None in required and not _has_sql_function(self.db_conn, "litkit_normalize(NULL)"): register_search_normalizer(self.db_conn) for name, matcher in (("litkit_word_match", _word_match), ("litkit_number_match", _number_match)): if name in required and not _has_sql_function(self.db_conn, f"{name}(NULL, NULL)"): self.db_conn.create_function(name, 2, matcher, deterministic=True) - if scope == "global": - cur.execute( - f""" - SELECT c.id - FROM chunks c - JOIN papers p ON p.id = c.paper_id - WHERE ({like_clause}) - ORDER BY (c.ord = -1) DESC, - ({title_expr}) DESC, - (p.pmid IS NOT NULL) DESC, - (p.pmcid IS NOT NULL) DESC, - c.id ASC - LIMIT ? - """, - params, - ) - else: - # Scope to candidate papers + if candidate_papers is not None: self.load_temp_candidates(self.db_conn, list(candidate_papers)) - cur.execute( - f""" - SELECT c.id - FROM chunks c - JOIN papers p ON p.id = c.paper_id - WHERE ({like_clause}) - AND c.paper_id IN (SELECT id FROM cand_papers) - ORDER BY (c.ord = -1) DESC, - ({title_expr}) DESC, - (p.pmid IS NOT NULL) DESC, - (p.pmcid IS NOT NULL) DESC, - c.id ASC - LIMIT ? - """, - params, - ) + + cur.execute( + f""" + {with_clause} SELECT c.id {source} + WHERE ({like_clause}) {scope_clause} + ORDER BY (c.ord = -1) DESC, + ({title_expr}) DESC, + (p.pmid IS NOT NULL) DESC, + (p.pmcid IS NOT NULL) DESC, + c.id ASC + LIMIT :limit + """, + params, + ) chunk_ids = [row[0] for row in cur.fetchall()] except sqlite3.OperationalError as e: diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index 48328db..22e1720 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -605,6 +605,44 @@ def test_literal_numbered_acronym_keeps_its_priority(): assert find_rare_terms("How was 1HIV diagnosed in HIV cases with marker²?", config) == ["1hiv"] +@pytest.mark.parametrize( + ("marked", "plain"), [("²HSV", "HSV"), ("³HSP", "HSP"), ("¹⁰CNS", "CNS"), ("⁷CKD", "CKD")] +) +def test_ambiguous_mass_uses_acronym_only_if_the_scope_lacks_a_label(lexical_db, marked, plain): + lexical_db.execute( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (20,1,20,?)", (f"{plain} testing.",) + ) + config = LexicalConfig(max_terms=1, limit=1) + backend = SqliteLexicalBackend(lexical_db, load_temp_candidates) + terms = find_rare_terms(f"How was {marked} measured?", config) + assert backend.search(terms, None, config).chunk_ids == [20] + literal = normalize_for_search_py(marked) + assert backend.search([literal], None, config).chunk_ids == [] + lexical_db.execute( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (22,1,22,?)", + (f"A longer specimen identifier 1{literal}code.",), + ) + assert backend.search(terms, None, config).chunk_ids == [20] + lexical_db.execute( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (21,2,21,?)", (f"Measured {literal}.",) + ) + assert backend.search(terms, None, config).chunk_ids == [21] + assert backend.search(terms, {1}, config).chunk_ids == [20] + assert backend.search(terms, {2}, config).chunk_ids == [21] + + +def test_ambiguous_acronyms_resolve_independently_in_one_question(lexical_db): + lexical_db.executemany( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (?,1,?,?)", + [(20, 20, "The 2HSV code."), (21, 21, "CNS function."), (22, 22, "HSV testing.")], + ) + config = LexicalConfig(max_terms=2) + terms = find_rare_terms("How were ²HSV and ¹⁰CNS measured?", config) + assert SqliteLexicalBackend(lexical_db, load_temp_candidates).search( + terms, None, config + ).chunk_ids == [20, 21] + + @pytest.mark.parametrize(("formatted", "plain"), [("¹³CD₄", "13CD4"), ("¹⁸F-FDG", "18F-FDG")]) def test_isotope_specificity_for_a_formula_or_named_tracer(lexical_db, formatted, plain): unlabelled = plain.lstrip("0123456789") @@ -643,7 +681,7 @@ def test_labelled_compounds_distinguish_the_first_isotope(lexical_db, formatted, backend = SqliteLexicalBackend(lexical_db, load_temp_candidates) for spelling in (formatted, plain): terms = find_rare_terms(f"How was {spelling} detected?", config) - assert terms == [plain.lower()] + assert [normalize_for_search_py(term) for term in terms] == [plain.lower()] assert backend.search(terms, None, config).chunk_ids == [21] From 7ac28a72f02e1440b7bb73e4f7dd33b680f00cf9 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 15:10:38 -0700 Subject: [PATCH 20/21] Preserve public acronym readings and match raised masses inside molecules Signed-off-by: Bill Hlavacek --- src/litkit/retrieval/helpers.py | 33 ++++++++++++++++++++++++++++----- src/litkit/retrieval/lexical.py | 21 +++++++++++++++++++-- tests/test_retrieval.py | 30 ++++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+), 7 deletions(-) diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index 85cc0cb..a59aed8 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -39,6 +39,7 @@ _TOKEN_RE = re.compile(r"[^\W_]+(?:[-_][^\W_]+)*") _EN_FIGURE_DASH_BETWEEN_ALNUM_RE = re.compile(r"(?<=[^\W_])[‒–](?=[^\W_])") _SUPERSCRIPT_DIGITS = "⁰¹²³⁴⁵⁶⁷⁸⁹" +_RAISED_DIGITS_RE = re.compile(rf"[{_SUPERSCRIPT_DIGITS}]+") _NON_ASCII_RE = re.compile(r"[^\x00-\x7f]") _ELEMENT_RE = re.compile(r"[A-Z][a-z]?") _FORMULA_RE = re.compile(r"(?:[A-Z][a-z]?\d*)+") @@ -278,6 +279,17 @@ def _extract_query_terms(normalized: str) -> Iterator[tuple[str, bool]]: yield term, is_acronym +class _AcronymAlternative(str): + """A normalized bare acronym and the numbered forms it can stand in for.""" + + labels: tuple[str, ...] + + def __new__(cls, acronym: str, labels: tuple[str, ...] = ()): + value = super().__new__(cls, acronym) + value.labels = labels + return value + + def query_terms(s: str) -> list[str]: """Extract meaningful query terms from a string. @@ -298,12 +310,23 @@ def query_terms(s: str) -> list[str]: Unique query terms in original order, followed by alternate readings of ambiguous superscripts """ - terms = ( - normalize_for_search_py(term) - for spelling in _query_spellings(s) - for term, _ in _extract_query_terms(spelling) + terms = [] + labels_by_acronym: dict[str, list[str]] = {} + for spelling in _query_spellings(s): + for term, _ in _extract_query_terms(spelling): + normalized = normalize_for_search_py(term) + terms.append(normalized) + if marked := _RAISED_ACRONYM_RE.fullmatch(term): + labels_by_acronym.setdefault(marked[2].lower(), []).append(normalized) + unique = list(dict.fromkeys(terms)) + # Every reader gets normalized strings for both interpretations. The SQL + # backend also knows which bare acronyms were added solely as alternatives. + unique.extend( + _AcronymAlternative(acronym, tuple(labels)) + for acronym, labels in labels_by_acronym.items() + if acronym not in terms ) - return list(dict.fromkeys(terms)) + return unique def escape_like(s: str, esc: str = "\\") -> str: diff --git a/src/litkit/retrieval/lexical.py b/src/litkit/retrieval/lexical.py index 278e797..a36b699 100644 --- a/src/litkit/retrieval/lexical.py +++ b/src/litkit/retrieval/lexical.py @@ -27,8 +27,10 @@ from litkit.db.normalization import register_search_normalizer from litkit.retrieval.helpers import ( _ACRONYM_MAX_LEN, + _AcronymAlternative, _MEASUREMENT_RE, _RAISED_ACRONYM_RE, + _RAISED_DIGITS_RE, _cited_reading, _extract_query_terms, _has_digit_or_joiner, @@ -63,6 +65,12 @@ def _word_match(text: object, term: object) -> int: boundary = _word_boundary_re(term) if boundary.search(normalized): return 1 + if term[0:1].isdecimal() and not text.isascii(): + # A raised mass starts a labelled group even inside another formula, + # as in CH₃¹³COOH. A longer ASCII specimen ID has no such boundary. + labelled = _RAISED_DIGITS_RE.sub(r" \g<0>", text) + if labelled != text and boundary.search(normalize_for_search_py(labelled)): + return 1 if not text.isascii() and (raised := _superscript_pattern(text)): cited = normalize_for_search_py(_cited_reading(text, raised)) return int(boundary.search(cited) is not None) @@ -294,11 +302,20 @@ def search( params: dict[str, str | int] = {"limit": config.limit} choices = [] specs = [] + alternatives = { + label: str(term) + for term in terms if isinstance(term, _AcronymAlternative) + for label in term.labels if label in terms + } for i, term in enumerate(terms): + if isinstance(term, _AcronymAlternative) and term in alternatives.values(): + continue normalized = normalize_for_search_py(term) parameter = f"term{i}" argument = f":{parameter}" - if marked := _RAISED_ACRONYM_RE.fullmatch(term): + marked = _RAISED_ACRONYM_RE.fullmatch(term) + fallback = marked[2].lower() if marked else alternatives.get(normalized) + if fallback is not None: # A mass on a short acronym may be a table note. Resolve that # term once in the same scope and snapshot as the ranked hits. name, value = "litkit_word_match", normalized @@ -307,7 +324,7 @@ def search( f"CASE WHEN EXISTS (SELECT 1 {source} WHERE {exact} {scope_clause}) " f"THEN {argument} ELSE :plain{i} END AS {parameter}" ) - params[f"plain{i}"] = marked[2].lower() + params[f"plain{i}"] = fallback argument = f"chosen.{parameter}" else: name, value = _match_spec(normalized) diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index 22e1720..7e5ab35 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -643,6 +643,36 @@ def test_ambiguous_acronyms_resolve_independently_in_one_question(lexical_db): ).chunk_ids == [20, 21] +@pytest.mark.parametrize("limit", [1, 8]) +def test_labelled_group_inside_a_molecule_wins_over_plain_acronym(lexical_db, limit): + lexical_db.executemany( + "INSERT INTO chunks(id,paper_id,ord,text) VALUES (?,?,0,?)", + [(20, 1, "A COOH molecule."), (21, 2, "We measured CH₃¹³COOH.")], + ) + backend = SqliteLexicalBackend(lexical_db, load_temp_candidates) + config = LexicalConfig(limit=limit) + for spelling in ("¹³COOH", "13COOH"): + for terms in (find_rare_terms(spelling, config), query_terms(spelling)): + assert backend.search(terms, None, config).chunk_ids == [21] + assert backend.search(terms, {2}, config).chunk_ids == [21] + + +def test_public_query_terms_expose_normalized_acronym_readings(lexical_db): + lexical_db.execute("INSERT INTO chunks(id,paper_id,ord,text) VALUES (20,1,20,'HSV testing.')") + terms = query_terms("How was ²HSV detected?") + assert "2hsv" in terms and "hsv" in terms + assert SqliteLexicalBackend(lexical_db, load_temp_candidates).search( + list(terms), None, LexicalConfig() + ).chunk_ids == [20] + lexical_db.execute("INSERT INTO chunks(id,paper_id,ord,text) VALUES (21,2,21,'The 2HSV code.')") + backend = SqliteLexicalBackend(lexical_db, load_temp_candidates) + assert backend.search(terms, None, LexicalConfig()).chunk_ids == [21] + assert backend.search(["hsv"], None, LexicalConfig()).chunk_ids == [20] + assert backend.search( + query_terms("Compare ²HSV and HSV."), None, LexicalConfig() + ).chunk_ids == [20, 21] + + @pytest.mark.parametrize(("formatted", "plain"), [("¹³CD₄", "13CD4"), ("¹⁸F-FDG", "18F-FDG")]) def test_isotope_specificity_for_a_formula_or_named_tracer(lexical_db, formatted, plain): unlabelled = plain.lstrip("0123456789") From 80a25dbae6dfc1957d6b5a9569f351bc938651cc Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 15:14:41 -0700 Subject: [PATCH 21/21] Keep normalized query terms stable across serialization and caching Signed-off-by: Bill Hlavacek --- src/litkit/retrieval/helpers.py | 33 +++++++------------------------- src/litkit/retrieval/lexical.py | 34 +++++++++++++++++---------------- tests/test_retrieval.py | 20 ++++++++++++------- 3 files changed, 38 insertions(+), 49 deletions(-) diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index a59aed8..089b6be 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -279,17 +279,6 @@ def _extract_query_terms(normalized: str) -> Iterator[tuple[str, bool]]: yield term, is_acronym -class _AcronymAlternative(str): - """A normalized bare acronym and the numbered forms it can stand in for.""" - - labels: tuple[str, ...] - - def __new__(cls, acronym: str, labels: tuple[str, ...] = ()): - value = super().__new__(cls, acronym) - value.labels = labels - return value - - def query_terms(s: str) -> list[str]: """Extract meaningful query terms from a string. @@ -307,26 +296,18 @@ def query_terms(s: str) -> list[str]: s: Input string (typically a question) Returns: - Unique query terms in original order, followed by alternate readings of - ambiguous superscripts + Unique normalized strings in original order, followed by alternate + readings of ambiguous superscripts. Searches using this list can + match either reading. """ terms = [] - labels_by_acronym: dict[str, list[str]] = {} + alternate_acronyms = [] for spelling in _query_spellings(s): for term, _ in _extract_query_terms(spelling): - normalized = normalize_for_search_py(term) - terms.append(normalized) + terms.append(normalize_for_search_py(term)) if marked := _RAISED_ACRONYM_RE.fullmatch(term): - labels_by_acronym.setdefault(marked[2].lower(), []).append(normalized) - unique = list(dict.fromkeys(terms)) - # Every reader gets normalized strings for both interpretations. The SQL - # backend also knows which bare acronyms were added solely as alternatives. - unique.extend( - _AcronymAlternative(acronym, tuple(labels)) - for acronym, labels in labels_by_acronym.items() - if acronym not in terms - ) - return unique + alternate_acronyms.append(marked[2].lower()) + return list(dict.fromkeys(terms + alternate_acronyms)) def escape_like(s: str, esc: str = "\\") -> str: diff --git a/src/litkit/retrieval/lexical.py b/src/litkit/retrieval/lexical.py index a36b699..dc5fb22 100644 --- a/src/litkit/retrieval/lexical.py +++ b/src/litkit/retrieval/lexical.py @@ -27,7 +27,6 @@ from litkit.db.normalization import register_search_normalizer from litkit.retrieval.helpers import ( _ACRONYM_MAX_LEN, - _AcronymAlternative, _MEASUREMENT_RE, _RAISED_ACRONYM_RE, _RAISED_DIGITS_RE, @@ -45,6 +44,9 @@ from sqlite3 import Connection +_NUMBERED_ACRONYM_RE = re.compile(r"[0-9]+([a-z]{3,4})") + + @lru_cache(maxsize=256) def _word_boundary_re(term: str) -> re.Pattern[str]: # ASCII alphanumeric boundaries allow matches in 'RNA-seq', '(RNA)' and @@ -288,7 +290,8 @@ def search( 2. Title matches 3. PMID presence (indexed in PubMed) 4. PMCID presence - 5. Chunk ID (stable ordering) + 5. Matching a numbered acronym when its bare form was also requested + 6. Chunk ID (stable ordering) """ if not terms or not config.enabled: return LexicalResult(scope="global" if candidate_papers is None else "candidates") @@ -302,20 +305,12 @@ def search( params: dict[str, str | int] = {"limit": config.limit} choices = [] specs = [] - alternatives = { - label: str(term) - for term in terms if isinstance(term, _AcronymAlternative) - for label in term.labels if label in terms - } - for i, term in enumerate(terms): - if isinstance(term, _AcronymAlternative) and term in alternatives.values(): - continue - normalized = normalize_for_search_py(term) + specific_matches = [] + normalized_terms = [normalize_for_search_py(term) for term in terms] + for i, (term, normalized) in enumerate(zip(terms, normalized_terms, strict=True)): parameter = f"term{i}" argument = f":{parameter}" - marked = _RAISED_ACRONYM_RE.fullmatch(term) - fallback = marked[2].lower() if marked else alternatives.get(normalized) - if fallback is not None: + if marked := _RAISED_ACRONYM_RE.fullmatch(term): # A mass on a short acronym may be a table note. Resolve that # term once in the same scope and snapshot as the ranked hits. name, value = "litkit_word_match", normalized @@ -324,10 +319,16 @@ def search( f"CASE WHEN EXISTS (SELECT 1 {source} WHERE {exact} {scope_clause}) " f"THEN {argument} ELSE :plain{i} END AS {parameter}" ) - params[f"plain{i}"] = fallback + params[f"plain{i}"] = marked[2].lower() argument = f"chosen.{parameter}" else: name, value = _match_spec(normalized) + numbered = _NUMBERED_ACRONYM_RE.fullmatch(normalized) + if numbered and numbered[1] in normalized_terms: + # Explicit plain-string alternatives request both. Break + # otherwise equal ranks in favor of the exact numbered hit. + params[f"label{i}"] = normalized + specific_matches.append(_match_sql("c.text", "litkit_word_match", f":label{i}")) params[parameter] = value specs.append((name, argument)) with_clause = "" @@ -336,6 +337,7 @@ def search( source += " CROSS JOIN chosen" like_clause = " OR ".join(_match_sql("c.text", *spec) for spec in specs) title_expr = _match_sql("p.title", *specs[0]) + specific_order = f"({' OR '.join(specific_matches)}) DESC," if specific_matches else "" cur = self.db_conn.cursor() chunk_ids: list[int] = [] @@ -360,7 +362,7 @@ def search( ({title_expr}) DESC, (p.pmid IS NOT NULL) DESC, (p.pmcid IS NOT NULL) DESC, - c.id ASC + {specific_order} c.id ASC LIMIT :limit """, params, diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index 7e5ab35..21ce998 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -1,6 +1,7 @@ """Tests for retrieval helpers: query terms, text normalization, LIKE escaping, lexical search, ANN/lexical merging, the per-paper cap and nprobe selection.""" +import json import sqlite3 from unittest.mock import Mock, patch @@ -652,9 +653,14 @@ def test_labelled_group_inside_a_molecule_wins_over_plain_acronym(lexical_db, li backend = SqliteLexicalBackend(lexical_db, load_temp_candidates) config = LexicalConfig(limit=limit) for spelling in ("¹³COOH", "13COOH"): - for terms in (find_rare_terms(spelling, config), query_terms(spelling)): - assert backend.search(terms, None, config).chunk_ids == [21] - assert backend.search(terms, {2}, config).chunk_ids == [21] + assert backend.search(find_rare_terms(spelling, config), None, config).chunk_ids == [21] + terms = query_terms(spelling) + # The public helper exposes both normalized readings of a marked + # acronym. Asking SQLite for both readings retains both hits. + expected = [21, 20] if spelling == "¹³COOH" else [21] + for tokens in (terms, json.loads(json.dumps(terms))): + assert backend.search(tokens, None, config).chunk_ids == expected[:limit] + assert backend.search(tokens, {2}, config).chunk_ids == [21] def test_public_query_terms_expose_normalized_acronym_readings(lexical_db): @@ -666,11 +672,11 @@ def test_public_query_terms_expose_normalized_acronym_readings(lexical_db): ).chunk_ids == [20] lexical_db.execute("INSERT INTO chunks(id,paper_id,ord,text) VALUES (21,2,21,'The 2HSV code.')") backend = SqliteLexicalBackend(lexical_db, load_temp_candidates) - assert backend.search(terms, None, LexicalConfig()).chunk_ids == [21] + assert backend.search(terms, None, LexicalConfig()).chunk_ids == [21, 20] assert backend.search(["hsv"], None, LexicalConfig()).chunk_ids == [20] - assert backend.search( - query_terms("Compare ²HSV and HSV."), None, LexicalConfig() - ).chunk_ids == [20, 21] + for tokens in (query_terms("²HSV"), query_terms("²HSV and HSV"), ["2hsv", "hsv"]): + assert tokens == ["2hsv", "hsv"] + assert backend.search(tokens, None, LexicalConfig(limit=1)).chunk_ids == [21] @pytest.mark.parametrize(("formatted", "plain"), [("¹³CD₄", "13CD4"), ("¹⁸F-FDG", "18F-FDG")])