diff --git a/pyproject.toml b/pyproject.toml index 1d623b4..c30caf1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,7 +41,10 @@ dependencies = [ "httpx>=0.27.0", "PyJWT>=2.8.0", "networkx>=3.1", - "mcp>=1.0.0", + # FastMCP lives at mcp.server.fastmcp in the 1.x API used by this project. + # Keep the upper bound so an unannounced 2.x release cannot break imports + # during an otherwise unrelated CI run. + "mcp>=1.0.0,<2.0.0", # Repairs malformed LLM JSON (doubled braces, truncation, trailing commas). # Pure-Python, MIT, no mandatory transitive deps. "json-repair>=0.30.0", diff --git a/scripts/feel_the_issue.py b/scripts/feel_the_issue.py new file mode 100644 index 0000000..a5a0efa --- /dev/null +++ b/scripts/feel_the_issue.py @@ -0,0 +1,127 @@ +"""Feel-the-issue demo for #54 — show the IDF cache's real DB impact. + +Runs the SAME search workload twice against a real HebbMind + SQLiteMemoryStore: + + A) With the cache (default). + B) With the cache neutralised (TTL=0, so every call re-fetches). + +and prints the number of real ``corpus_size`` / ``keyword_doc_freqs`` DB calls +in each case. That delta is the work issue #54 removes — made visible, not +asserted. Intended for a human to read the output, so it narrates as it goes. +""" + +from __future__ import annotations + +import sys +import tempfile +from contextlib import contextmanager +from pathlib import Path +from collections.abc import Iterator + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) + +from hebb import HebbMind +from hebb.config.settings import Settings +from hebb.storage.sqlite_store import SQLiteMemoryStore + +# A realistic recall workload: 3 back-to-back queries over one corpus, +# mirroring RecallAgent.recall's queries[:3] loop. The queries share words +# ("python", "retrieval") so the cache can reuse DF across them — the exact +# case issue #54 calls out. +QUERIES = [ + "how does python handle concurrency and the gil", + "python gil and retrieval tradeoffs", + "python async retrieval patterns", +] + + +class Counter: + def __init__(self, store: SQLiteMemoryStore) -> None: + self.corpus = 0 + self.df = 0 + self._s = store + self._oc = store.corpus_size + self._od = store.keyword_doc_freqs + store.corpus_size = self._c # type: ignore[method-assign] + store.keyword_doc_freqs = self._d # type: ignore[method-assign] + + async def _c(self, partition_ids=None) -> int: + self.corpus += 1 + return await self._oc(partition_ids) + + async def _d(self, terms, partition_ids=None) -> dict[str, int]: + self.df += 1 + return await self._od(terms, partition_ids) + + +def _seed(hc: HebbMind) -> None: + hc.add("Python's GIL serializes bytecode execution in one process.", partition="mem_semantic") + hc.add("RAG retrieves documents then conditions the LLM on them.", partition="mem_semantic") + hc.add("asyncio lets Python do concurrent IO despite the GIL.", partition="mem_semantic") + hc.add("I prefer dark mode and 2-space indents.", partition="mem_preference") + + +def _run_workload(hc: HebbMind) -> tuple[int, int]: + store = hc._searcher.store # type: ignore[assignment] + c = Counter(store) + # Scenario 1: RecallAgent's 3-query pass (overlapping tokens). + for q in QUERIES: + hc.search(q) + # Scenario 2: the same query retried 4 times (UI retry / agent retry) — + # the other case issue #54 names. With the cache, only the first hits. + for _ in range(4): + hc.search("python gil retrieval") + return c.corpus, c.df + + +@contextmanager +def _temporary_home() -> Iterator[Path]: + """Provide a temporary Hebb home that is cleaned up on failure too.""" + with tempfile.TemporaryDirectory() as home: + yield Path(home) + + +def main() -> int: + print("=" * 64) + print("Issue #54 demo: does caching cut DB round-trips on recall?") + print("=" * 64) + + # ---- A) With cache (default, TTL=60s) ------------------------------- # + print("\n[A] WITH cache (TTL=60s, the fix):") + with _temporary_home() as home_a: + sa = Settings(home_dir=home_a, llm_model="openai/gpt-4o-mini", + embedding_provider="noop", embedding_dim=3) + with HebbMind(config=sa) as hc: + _seed(hc) + corpus_a, df_a = _run_workload(hc) + print(" 3 recall queries + 4 retried same-query searches") + print(f" → {corpus_a} corpus_size SQL, {df_a} DF SQL") + + # ---- B) Without cache (TTL=0 → every call re-fetches) --------------- # + print("\n[B] WITHOUT cache (TTL=0 → re-fetch every time):") + with _temporary_home() as home_b: + sb = Settings(home_dir=home_b, llm_model="openai/gpt-4o-mini", + embedding_provider="noop", embedding_dim=3) + with HebbMind(config=sb) as hc: + _seed(hc) + hc._searcher._idf_cache_ttl = 0.0 # neutralise: all entries expire instantly + corpus_b, df_b = _run_workload(hc) + print(" 3 recall queries + 4 retried same-query searches") + print(f" → {corpus_b} corpus_size SQL, {df_b} DF SQL") + + # ---- Verdict -------------------------------------------------------- # + print("\n" + "=" * 64) + print("VERDICT") + print("=" * 64) + print(f" corpus_size SQL: with cache {corpus_a} vs without {corpus_b}") + print(f" DF SQL: with cache {df_a} vs without {df_b}") + saved_c = corpus_b - corpus_a + saved_d = df_b - df_a + print(f"\n #54 saves {saved_c} corpus_size round-trip(s) and {saved_d} DF round-trip(s)") + print(" on this 3-query recall pass. That is the waste the cache removes.") + print("=" * 64) + return 0 if (saved_c >= 0 and saved_d >= 0) else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/verify_idf_cache_e2e.py b/scripts/verify_idf_cache_e2e.py new file mode 100644 index 0000000..08b58bd --- /dev/null +++ b/scripts/verify_idf_cache_e2e.py @@ -0,0 +1,142 @@ +"""End-to-end verification of the IDF cache via the real HebbMind facade (issue #54). + +Unlike ``verify_idf_cache_real_store.py`` (which drives ``SQLiteMemoryStore`` + +``MemorySearcher`` directly), this starts the actual public SDK entrypoint — +``HebbMind`` — exactly the way README's five-minute tour does: ``hc.add(...)`` +then ``hc.search(...)``. The whole stack (storage + embedder + graph + hybrid +searcher) runs in-process; only the embedding model is swapped for the noop +provider so no model download / GPU is needed. + +Asserts, against the genuine component chain: + +1. After two identical ``search()`` calls, the searcher's IDF statistic caches + are populated (corpus_size: one entry per partition scope; df: one per + (token, partition)) — i.e. the production code path actually fills the cache. +2. The second ``search()`` reuses cached stats — verified by counting real + ``SQLiteMemoryStore`` method calls (each = a real SQL round-trip). +3. Staleness is bounded, not silent: a memory written AFTER the cache is filled + is invisible to IDF within the TTL (expected by design), and reappears once + the TTL elapses. Proves the cache is honest about its trade-off. + +Runnable script (scripts/ is ruff-excluded), prints PASS/FAIL, exits non-zero +on regression. +""" + +from __future__ import annotations + +import asyncio +import sys +import tempfile +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) + +from hebb import HebbMind +from hebb.config.settings import Settings +from hebb.storage.sqlite_store import SQLiteMemoryStore + +_QUERY = "alpha beta" + + +class IDFReadCounter: + """Count real calls to the live store's IDF-read methods.""" + + def __init__(self, store: SQLiteMemoryStore) -> None: + self.corpus = 0 + self.df = 0 + self._store = store + self._orig_c = store.corpus_size + self._orig_d = store.keyword_doc_freqs + store.corpus_size = self._c # type: ignore[method-assign] + store.keyword_doc_freqs = self._d # type: ignore[method-assign] + + async def _c(self, partition_ids=None) -> int: + self.corpus += 1 + return await self._orig_c(partition_ids) + + async def _d(self, terms, partition_ids=None) -> dict[str, int]: + self.df += 1 + return await self._orig_d(terms, partition_ids) + + +def main() -> int: + failures: list[str] = [] + home = Path(tempfile.mkdtemp()) + settings = Settings( + home_dir=home, + llm_model="openai/gpt-4o-mini", + embedding_provider="noop", + embedding_dim=3, + ) + + with HebbMind(config=settings) as hc: + hc.add("alpha beta rule the early corpus", partition="mem_semantic") + hc.add("beta dominates the common terms here", partition="mem_semantic") + + searcher = hc._searcher # the live MemorySearcher the facade owns + store = searcher.store # type: ignore[assignment] + counter = IDFReadCounter(store) + + # ---- Check 1: two identical searches, second reuses the cache ------- # + hc.search(_QUERY) + first_c, first_d = counter.corpus, counter.df + hc.search(_QUERY) + second_c, second_d = counter.corpus, counter.df + d_c, d_d = second_c - first_c, second_d - first_d + + cache_populated = len(searcher._corpus_size_cache) >= 1 and len(searcher._df_cache) >= 1 + second_reused = d_c == 0 and d_d == 0 + print( + "Check 1 — real HebbMind.search() twice:\n" + f" caches populated? corpus_size={len(searcher._corpus_size_cache)}, df={len(searcher._df_cache)}\n" + f" 1st → {first_c} corpus / {first_d} df calls; 2nd → +{d_c} / +{d_d} (expect 0/0)" + ) + if not cache_populated: + failures.append("Check 1a: production path did not populate the IDF cache.") + if not second_reused: + failures.append(f"Check 1b: 2nd search added {d_c}/{d_d} IDF calls (expected 0/0).") + + # ---- Check 2: staleness within TTL, then self-heals after TTL ------- # + # Write a 3rd memory. Within the TTL the cached corpus_size is stale + # (still 2), so the IDF weighter keeps using the old N — by design. + hc.add("gamma is a rare word", partition="mem_semantic") + # Read the ACTUAL partition key the production path cached under (the + # facade's search scope may be None or a partition set — don't assume). + pk = next(iter(searcher._corpus_size_cache.keys())) + cached_n = searcher._idf_corpus_size_get(time.monotonic(), pk) + stale_within_ttl = cached_n == 2 # real is now 3 + print( + f"\nCheck 2 — staleness bounded by TTL:\n" + f" after 3rd write, cached corpus_size = {cached_n} (real 3) → stale within TTL? {stale_within_ttl}" + ) + if not stale_within_ttl: + failures.append("Check 2a: cache did not show expected bounded staleness.") + + # Backdate the cache entry so the TTL elapses, then search → must + # refetch the NEW corpus size (3). + entry = searcher._corpus_size_cache.get(pk) + if entry is not None: + searcher._corpus_size_cache[pk] = (entry[0], time.monotonic() - 1) + # Also expire the df entries so they refetch against the new corpus. + for k in list(searcher._df_cache.keys()): + v = searcher._df_cache[k] + searcher._df_cache[k] = (v[0], time.monotonic() - 1) + counter.corpus = 0 + hc.search("alpha gamma") # gamma is the newly-added token + refreshed = searcher._idf_corpus_size_get(time.monotonic(), pk) + refetched = refreshed == 3 + print(f" after forced TTL expiry + search, refetched corpus_size = {refreshed} (expect 3) → self-healed? {refetched}") + if not refetched: + failures.append("Check 2b: cache did not refetch the new corpus_size after TTL expiry.") + + print() + if failures: + print("RESULT: FAIL — " + " | ".join(failures)) + return 1 + print("RESULT: PASS — real HebbMind facade fills/reuses/heals the IDF cache end-to-end.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/scripts/verify_idf_cache_real_store.py b/scripts/verify_idf_cache_real_store.py new file mode 100644 index 0000000..c17c24e --- /dev/null +++ b/scripts/verify_idf_cache_real_store.py @@ -0,0 +1,175 @@ +"""End-to-end verification for the IDF statistic cache (issue #54). + +Runs against a REAL ``SQLiteMemoryStore`` on a temp FTS5 DB (vector extension +disabled — the IDF path only touches ``memory_fts``, not ``vec0``) and counts +calls to the store's actual IDF-read methods (``corpus_size`` / +``keyword_doc_freqs``). Each such call fires real SQL against the genuine FTS5 +index, so this is a faithful — not mocked — measure of the DB round-trips the +cache is meant to avoid: + +1. A repeated identical ``search()`` adds ZERO real ``corpus_size`` / DF store + calls within the TTL (issue "Expected Outcomes" bullet 1). +2. The ``RecallAgent.recall`` 3-query pass (``queries[:3]`` over an unchanged + corpus) calls ``corpus_size`` exactly ONCE and reuses DF for overlapping + tokens (issue "Expected Outcomes" bullet 2). + +Not a pytest case — a runnable script that prints a PASS/FAIL verdict and exits +non-zero on regression. Kept out of the test suite (scripts/ is ruff-excluded): +it touches real sqlite and duplicates the unit-store assertions, here only to +prove the cache hits against the genuine store. +""" + +from __future__ import annotations + +import asyncio +import sys +import tempfile +from pathlib import Path + +# repo src on path when run from the project root +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) + +from hebb.embedding.local import NoopEmbedder +from hebb.models.memory import MemoryCreate, MemoryQuery +from hebb.retrieval.searcher import MemorySearcher +from hebb.storage.migrations import get_connection, initialize_schema +from hebb.storage.sqlite_store import SQLiteMemoryStore + +# Memories whose content maps cleanly to the test queries' surface tokens. +_MEMOIRS = [ + ("alpha rules the early corpus", "p1"), + ("beta dominates the common terms here", "p1"), + ("gamma is a rare discriminating word", "p1"), +] +_QUERY = "alpha beta gamma" # surface tokens line up with the seeded terms + + +class IDFReadCounter: + """Count calls to the real store's ``corpus_size`` / ``keyword_doc_freqs``. + + Wraps (not replaces) the genuine ``SQLiteMemoryStore`` methods, so each + counted call is a real SQL round-trip — the exact thing the cache skips. + """ + + def __init__(self, store: SQLiteMemoryStore) -> None: + self.corpus_calls = 0 + self.df_calls = 0 + self._store = store + self._orig_corpus = store.corpus_size + self._orig_df = store.keyword_doc_freqs + store.corpus_size = self._count_corpus # type: ignore[method-assign] + store.keyword_doc_freqs = self._count_df # type: ignore[method-assign] + + async def _count_corpus(self, partition_ids: list[str] | None = None) -> int: + self.corpus_calls += 1 + return await self._orig_corpus(partition_ids) + + async def _count_df(self, terms: list[str], partition_ids: list[str] | None = None) -> dict[str, int]: + self.df_calls += 1 + return await self._orig_df(terms, partition_ids) + + def snapshot(self) -> tuple[int, int]: + return self.corpus_calls, self.df_calls + + +async def _seed(store: SQLiteMemoryStore, embedder: NoopEmbedder) -> None: + for content, partition in _MEMOIRS: + await store.create( + MemoryCreate(content=content, partition_id=partition), + embedding=await embedder.embed(content), + ) + + +async def main() -> int: + embedder = NoopEmbedder(3) + failures: list[str] = [] + + with tempfile.TemporaryDirectory() as tmp: + db_path = Path(tmp) / "verify.db" + # load_vec=False: skip sqlite-vec (unavailable in some envs); IDF only + # needs the FTS5 index, which initialise_schema always creates. + conn = await get_connection(str(db_path), load_vec=False) + await initialize_schema(conn, embedder.dimension) + store = SQLiteMemoryStore(conn) + await _seed(store, embedder) + counter = IDFReadCounter(store) + + searcher = MemorySearcher( + store=store, # type: ignore[arg-type] + embedder=embedder, + graph=None, + vector_search_enabled=False, # IDF lives on the keyword/lexical path + graph_search_enabled=False, + graph_expansion_enabled=False, + ) + + # ---- Check 1: repeated identical search adds ZERO IDF store calls --- # + await searcher.search(MemoryQuery(query=_QUERY, top_k=10)) + first_corpus, first_df = counter.snapshot() + + await searcher.search(MemoryQuery(query=_QUERY, top_k=10)) + after_corpus, after_df = counter.snapshot() + delta_corpus, delta_df = after_corpus - first_corpus, after_df - first_df + + check1_ok = delta_corpus == 0 and delta_df == 0 + print( + "Check 1 — repeated identical search within TTL:\n" + f" first search → {first_corpus} corpus_size call(s), {first_df} DF call(s)\n" + f" repeat search → +{delta_corpus} corpus_size call(s), +{delta_df} DF call(s) (expect 0, 0)" + ) + if not check1_ok: + failures.append("Check 1: repeated search did not hit the cache (expected 0 IDF calls).") + + # ---- Check 2: RecallAgent-style 3-query pass over same corpus ----- # + # Fresh searcher so the cache starts empty, then reproduce RecallAgent's + # queries[:3] loop: three back-to-back searches with overlapping tokens. + # One fresh token (delta) plus two shared (alpha/beta) makes both + # behaviours visible: corpus_size fetched once, shared DF reused, the + # fresh term the only new DF fetch. + recall_searcher = MemorySearcher( + store=store, # type: ignore[arg-type] + embedder=embedder, + graph=None, + vector_search_enabled=False, + graph_search_enabled=False, + graph_expansion_enabled=False, + ) + recall_counter = IDFReadCounter(store) + start_corpus, start_df = recall_counter.snapshot() + # Add a fresh memory so "delta" is a real DF-eligible token. + await store.create( + MemoryCreate(content="delta epsilon fresh tokens", partition_id="p1"), + embedding=await embedder.embed("delta epsilon fresh tokens"), + ) + for q in ("alpha beta delta", "beta gamma alpha", "alpha delta"): + await recall_searcher.search(MemoryQuery(query=q, top_k=10)) + three_corpus = recall_counter.corpus_calls - start_corpus + three_df = recall_counter.df_calls - start_df + # corpus_size depends only on the partition scope → fetched exactly once. + # DF is per-token; alpha/beta/gamma repeat across the 3 queries and are + # fetched only the first time they appear. The three queries should need + # exactly two batches here: alpha/beta/delta, then the new gamma. + check2_ok = three_corpus == 1 and 1 <= three_df <= 2 + print( + f"\nCheck 2 — RecallAgent 3-query pass (queries[:3], overlapping tokens):\n" + f" 3 searches → {three_corpus} corpus_size call(s), {three_df} DF call(s)\n" + f" (expect corpus_size == 1; 1 <= DF <= 2 with overlap reuse)" + ) + if not check2_ok: + failures.append( + f"Check 2: 3-query pass issued {three_corpus} corpus_size / {three_df} DF calls " + "(expected corpus_size==1 and 1 <= DF <= 2 with reuse)." + ) + + await conn.close() + + print() + if failures: + print("RESULT: FAIL — " + " | ".join(failures)) + return 1 + print("RESULT: PASS — real SQLiteMemoryStore issues zero/reused IDF round-trips within TTL.") + return 0 + + +if __name__ == "__main__": + sys.exit(asyncio.run(main())) diff --git a/src/hebb/retrieval/searcher.py b/src/hebb/retrieval/searcher.py index c4e0c71..4dd8aec 100644 --- a/src/hebb/retrieval/searcher.py +++ b/src/hebb/retrieval/searcher.py @@ -3,8 +3,10 @@ from __future__ import annotations import asyncio +import time from collections.abc import Callable from datetime import datetime, timezone +from typing import TypeVar from hebb.embedding.base import EmbeddingProvider from hebb.graph.knowledge_graph import KnowledgeGraph @@ -46,6 +48,24 @@ # sigmoid, so a 0.8 composite floor maps to a 0.5 sigmoid floor (0.8 * 0.625). _RERANK_FLOOR_RATIO = 0.625 +# IDF corpus statistics — ``corpus_size`` and the documents-frequency dict for a +# query's surface tokens — change only when memories are written, which is rare +# relative to the read-heavy search/recall workload. Re-fetching them on every +# ``search()`` repeats SQL the previous identical query already paid for; e.g. +# ``RecallAgent`` fires 3 queries back-to-back over an unchanged corpus. A short +# instance-level TTL (rather than event-driven write invalidation) bounds +# staleness cheaply: stale stats only drift IDF slightly, never corrupt results, +# and the TTL regenerates each entry shortly after any new write. See +# :meth:`MemorySearcher._build_idf`. Copied to ``self._idf_cache_ttl`` so tests +# can shorten it without sleeping through 60s. +_IDF_CACHE_TTL = 60.0 +# Bound cache growth when a long-lived searcher sees many partition scopes or +# one-off query terms. The cache is an optimisation, so eviction is preferable +# to retaining unbounded application state. +_IDF_CORPUS_CACHE_MAX_ENTRIES = 128 +_IDF_DF_CACHE_MAX_ENTRIES = 4096 +_CacheKey = TypeVar("_CacheKey") + class MemorySearcher: """Orchestrates hybrid retrieval: vector + keyword + graph, then scoring. @@ -91,6 +111,33 @@ def __init__( # its intrinsic top-1/top-k so it stands on its own (and feeds RRF a # better rank) without depending on the cross-encoder reranker. self.keyword_blend_enabled = keyword_blend_enabled + # IDF statistic caches (issue #54) — short-TTL, instance-level dicts so + # repeated ``search()`` over an unchanged corpus reuses ``corpus_size`` and + # per-query document frequencies instead of re-hitting the store. The two + # depend on different inputs, so they get independent dicts: + # * ``_corpus_size_cache``: keyed by the partition scope (corpus size + # depends only on which partitions are searched, not the query). + # * ``_df_cache``: keyed by (token, partition scope) — DF depends on both + # the token and the partition, so the token MUST be in the key to stop + # one query's "alpha" frequency overwriting another's "beta". + # Values are ``(result, expires_at)`` with ``expires_at`` a ``time.monotonic`` + # deadline. Zero corpus sizes and omitted/zero DF results are cached too; + # queries with no eligible surface tokens return before any store call. + self._idf_cache_ttl: float = _IDF_CACHE_TTL + self._corpus_size_cache: dict[tuple[str, ...] | None, tuple[int, float]] = {} + # Per-token DF cache: keyed by (token, partition-scope) so one query's + # frequency for "alpha" never overwrites another's for "beta", and the + # same token reuses its df across the back-to-back recall queries. + self._df_cache: dict[tuple[str, tuple[str, ...] | None], tuple[int, float]] = {} + # Serialise the cache miss → store round-trip → back-fill critical section + # across concurrent ``_build_idf`` calls. Without it, two coroutines that + # both miss the same key each fetch from the store and race to back-fill + # (correct result, but a wasted DB hit). The lock guards only this in/out + # dance; uncached candidates wait on a hit that the first caller produces. + # Coarse-grained on purpose: a per-key lock registry needs its own lock, + # and the section it protects is a single short DB round-trip, so holding + # one instance lock is simpler and costs no meaningful concurrency. + self._idf_cache_lock: asyncio.Lock = asyncio.Lock() async def search(self, query: MemoryQuery) -> SearchResponse: # Sanitize LLM-generated queries (XML tags, tool artifacts, etc.) @@ -471,6 +518,73 @@ async def _keyword_search( # IDF weighting for calibrated lexical relevance # ------------------------------------------------------------------ + @staticmethod + def _idf_partition_key(partition_ids: list[str] | None) -> tuple[str, ...] | None: + """Normalise a partition scope into a hashable cache key. + + ``None`` (search the whole corpus) stays ``None``; a list is de-duped and + sorted so the same partition set in any order maps to one entry. That cost + is negligible next to the store round-trip it lets us skip. + """ + return None if partition_ids is None else tuple(sorted(dict.fromkeys(partition_ids))) + + def _idf_corpus_size_get(self, now: float, partition_key: tuple[str, ...] | None) -> int | None: + """Return the cached corpus size if present and fresh, else ``None``. + + A miss — never cached, or the entry aged past its TTL deadline — yields + ``None`` so the caller re-fetches and back-fills; a cached ``0`` (empty + corpus) is a real answer we deliberately keep, distinguished from a miss + by being a non-``None`` entry. + """ + entry = self._corpus_size_cache.get(partition_key) + if entry is None: + return None + size, expires_at = entry + if now >= expires_at: + del self._corpus_size_cache[partition_key] + return None + return size + + def _idf_corpus_size_put(self, size: int, now: float, partition_key: tuple[str, ...] | None) -> None: + """Cache ``size`` for the partition scope with a TTL deadline stamp.""" + self._idf_prune_cache(self._corpus_size_cache, now, _IDF_CORPUS_CACHE_MAX_ENTRIES) + self._corpus_size_cache[partition_key] = (size, now + self._idf_cache_ttl) + + def _idf_df_get(self, token: str, partition_key: tuple[str, ...] | None, now: float) -> int | None: + """Return the cached document frequency for ``token`` if fresh, else ``None``. + + A cached ``0`` (term absent from the corpus) is kept — it is a real + answer, not a miss — so repeat lookups of an unseen term skip the store. + """ + entry = self._df_cache.get((token, partition_key)) + if entry is None: + return None + df, expires_at = entry + if now >= expires_at: + del self._df_cache[(token, partition_key)] + return None + return df + + def _idf_df_put(self, token: str, partition_key: tuple[str, ...] | None, df: int, now: float) -> None: + """Cache a document frequency for ``token`` with a TTL deadline stamp.""" + self._idf_prune_cache(self._df_cache, now, _IDF_DF_CACHE_MAX_ENTRIES) + self._df_cache[(token, partition_key)] = (df, now + self._idf_cache_ttl) + + @staticmethod + def _idf_prune_cache(cache: dict[_CacheKey, tuple[int, float]], now: float, max_entries: int) -> None: + """Remove expired entries and oldest entries before a cache insertion. + + These caches are deliberately tiny implementation details rather than a + source of truth. Evicting insertion-order entries keeps memory bounded + without adding a dependency or changing the externally visible search + behaviour: an evicted entry simply becomes a normal store miss. + """ + for key, (_, expires_at) in list(cache.items()): + if now >= expires_at: + del cache[key] + while len(cache) >= max_entries: + del cache[next(iter(cache))] + async def _build_idf(self, query: str, partition_ids: list[str] | None) -> Callable[[str], float] | None: """Build a ``token -> idf`` weighter from corpus document frequencies. @@ -480,6 +594,13 @@ async def _build_idf(self, query: str, partition_ids: list[str] | None) -> Calla calibrated relevance honours its "Σ idf·matched / Σ idf" contract. Rare, discriminating terms dominate; generic shared words barely move the score. + ``corpus_size`` and the per-token document frequencies are short-TTL + instance-level cached (``_corpus_size_cache`` / ``_df_cache``, issue #54): + a repeated ``search()`` over an unchanged corpus, or a later query whose + surface tokens overlap the first, reuses cached stats and skips the store + round-trip. Zero/omitted results are cached too. Fall through to the store + only on a cache miss or after the TTL elapses, then back-fill the cache. + Args: query: Raw user query. partition_ids: Partition scope for the DF / corpus-size counts — @@ -493,10 +614,54 @@ async def _build_idf(self, query: str, partition_ids: list[str] | None) -> Calla surface = [*query_surface_tokens(query), *cjk_surface_tokens(query)] if not surface: return None - total_docs = await self.store.corpus_size(partition_ids) - if total_docs <= 0: + partition_key = self._idf_partition_key(partition_ids) + + def cached_dfs(now: float) -> tuple[dict[str, int], list[str]]: + doc_freqs: dict[str, int] = {} + miss_tokens: list[str] = [] + for token in dict.fromkeys(surface): + df = self._idf_df_get(token, partition_key, now) + if df is None: + miss_tokens.append(token) + else: + doc_freqs[token] = df + return doc_freqs, miss_tokens + + # Complete cache hits should not wait behind an unrelated cold query. + # A second check under the lock below preserves miss de-duplication. + now = time.monotonic() + total_docs = self._idf_corpus_size_get(now, partition_key) + if total_docs is not None and total_docs > 0: + doc_freqs, miss_tokens = cached_dfs(now) + if not miss_tokens: + return make_idf(doc_freqs, total_docs) + elif total_docs == 0: return None - doc_freqs = await self.store.keyword_doc_freqs(surface, partition_ids) + + # Only the miss → store round-trip → back-fill section is locked. This + # keeps complete cache hits concurrent while still ensuring identical + # cold requests share one store fetch. + async with self._idf_cache_lock: + now = time.monotonic() + total_docs = self._idf_corpus_size_get(now, partition_key) + if total_docs is None: + total_docs = await self.store.corpus_size(partition_ids) + self._idf_corpus_size_put(total_docs, now, partition_key) + if total_docs <= 0: + return None + doc_freqs, miss_tokens = cached_dfs(now) + # Batch the misses in one store round-trip (the store's DF API accepts + # a term list), then back-fill the per-token cache so the next + # overlapping query — ``RecallAgent`` fires 3 back-to-back — reuses + # what it can. A term the store omits is recorded as df 0 (its + # "best-effort" convention): cache and surface that 0, never the + # absence-of-lookup default. + if miss_tokens: + fetched = await self.store.keyword_doc_freqs(miss_tokens, partition_ids) + for token in miss_tokens: + df = fetched.get(token, 0) + self._idf_df_put(token, partition_key, df, now) + doc_freqs[token] = df return make_idf(doc_freqs, total_docs) # ------------------------------------------------------------------ diff --git a/tests/unit/test_idf_cache.py b/tests/unit/test_idf_cache.py new file mode 100644 index 0000000..c7c7000 --- /dev/null +++ b/tests/unit/test_idf_cache.py @@ -0,0 +1,311 @@ +"""IDF statistic cache regression tests (issue #54). + +``MemorySearcher._build_idf`` reuses ``corpus_size`` and per-query document +frequencies across ``search()`` calls via two short-TTL, instance-level dicts, +so a repeated or overlapping query over an unchanged corpus skips the store +round-trip. These tests pin the four behaviours the issue calls out: + +* Cache Hit — identical re-search adds zero ``corpus_size`` / DF store calls. +* Cache Miss — a fresh token set re-hits the store. +* TTL Expiry — after the TTL elapses, a hit becomes a miss and re-fetches. +* Partition Isolation — different partition scopes get independent entries, and + a DF entry keyed by one token does not leak into another token's score. + +The store is a lightweight in-memory double that records every call, so the +assertions are about *call counts*, not clock-time latency. +""" + +from __future__ import annotations + +import asyncio + +import pytest + +from hebb.models.memory import Memory +from hebb.retrieval.searcher import MemorySearcher + +# --------------------------------------------------------------------------- +# Test doubles +# --------------------------------------------------------------------------- + + +class _FakeEmbedder: + """Constant non-empty embedding so a ``MemorySearcher`` can be constructed.""" + + @property + def dimension(self) -> int: + return 3 + + async def embed(self, text: str) -> list[float]: + return [0.1, 0.2, 0.3] + + async def embed_batch(self, texts: list[str]) -> list[list[float]]: + return [[0.1, 0.2, 0.3] for _ in texts] + + async def aclose(self) -> None: # pragma: no cover - no resources + return None + + +class _RecordingStore: + """In-memory ``MemoryStore`` stand-in that counts every IDF-related call. + + Unlike the audit lane's ``FakeStore``, this one returns *distinct* document + frequencies per term (``alpha`` is rare, ``beta`` is common) so partition + isolation and cross-token leakage can be observed through the scores, not + only the call counts. + """ + + def __init__(self, corpus_size: int, df_map: dict[str, int] | None = None) -> None: + self._corpus_size = corpus_size + self._df_map = df_map or {} + self.corpus_size_calls: int = 0 + self.doc_freq_calls: int = 0 + + # --- read paths the searcher touches via _build_idf ------------------- + + async def corpus_size(self, partition_ids: list[str] | None = None) -> int: + self.corpus_size_calls += 1 + return self._corpus_size + + async def keyword_doc_freqs(self, terms: list[str], partition_ids: list[str] | None = None) -> dict[str, int]: + self.doc_freq_calls += 1 + # Default absent terms to df 1 (the store's "best-effort" convention): + # an unseen query term is treated as rare, not zero. + return {term: self._df_map.get(term, 1) for term in terms} + + # --- out-of-path MemoryStore methods the searcher may touch on search - + + async def get(self, memory_id: str) -> Memory | None: # pragma: no cover + return None + + async def search_by_vector( # pragma: no cover + self, + query_embedding: list[float], + top_k: int = 10, + partition_ids: list[str] | None = None, + ) -> list[tuple[Memory, float]]: + return [] + + async def search_by_keyword( # pragma: no cover + self, + query: str, + top_k: int = 10, + partition_ids: list[str] | None = None, + ) -> list[tuple[Memory, float]]: + return [] + + async def update_access_batch(self, memory_ids: list[str]) -> None: # pragma: no cover + return None + + +def _make_searcher(store: _RecordingStore) -> MemorySearcher: + """A searcher with every channel off — only ``_build_idf`` is exercised.""" + return MemorySearcher( + store=store, # type: ignore[arg-type] + embedder=_FakeEmbedder(), + graph=None, + graph_search_enabled=False, + graph_expansion_enabled=False, + ) + + +def _df_map() -> dict[str, int]: + # Rare "alpha" (df 1) vs common "beta" (df 5) make IDF *and* leakage observable. + return {"alpha": 1, "beta": 5} + + +# --------------------------------------------------------------------------- +# Cache Hit / Miss +# --------------------------------------------------------------------------- + + +async def test_cache_hit_repeated_query_adds_no_store_calls() -> None: + """An identical re-search reuses cached stats — zero extra store calls.""" + store = _RecordingStore(corpus_size=100, df_map=_df_map()) + searcher = _make_searcher(store) + + await searcher._build_idf("alpha beta", ["p1"]) + first_corpus, first_df = store.corpus_size_calls, store.doc_freq_calls + + await searcher._build_idf("alpha beta", ["p1"]) + + assert store.corpus_size_calls == first_corpus # no new corpus_size hit + assert store.doc_freq_calls == first_df # no new DF hit + + +async def test_cache_miss_new_tokens_refetch_df() -> None: + """A query with tokens not yet seen re-hits the store for the misses only. + + ``corpus_size`` depends only on the partition scope, so it stays cached + (same partition → one hit). DF is per-token, so the new terms miss and + trigger exactly one more DF round-trip. + """ + store = _RecordingStore(corpus_size=100, df_map=_df_map()) + searcher = _make_searcher(store) + + await searcher._build_idf("alpha", ["p1"]) + + await searcher._build_idf("alpha gamma", ["p1"]) + + assert store.corpus_size_calls == 1 # partition scope unchanged → still 1 + assert store.doc_freq_calls == 2 # "gamma" missed → one refetch + + +# --------------------------------------------------------------------------- +# TTL Expiry +# --------------------------------------------------------------------------- + + +async def test_ttl_expiry_refetches_after_deadline() -> None: + """A cached entry that has aged past its TTL becomes a miss and re-fetches.""" + store = _RecordingStore(corpus_size=100, df_map=_df_map()) + searcher = _make_searcher(store) + # Make the TTL effectively instantaneous: any second call is past the deadline. + searcher._idf_cache_ttl = 0.0 + + await searcher._build_idf("alpha beta", ["p1"]) + assert store.corpus_size_calls == 1 + assert store.doc_freq_calls == 1 + + await searcher._build_idf("alpha beta", ["p1"]) + + # With a 0s TTL the prior entries expired, so both stats re-hit the store. + assert store.corpus_size_calls == 2 + assert store.doc_freq_calls == 2 + + +# --------------------------------------------------------------------------- +# Partition Isolation +# --------------------------------------------------------------------------- + + +async def test_partition_isolation_does_not_cross_scopes() -> None: + """Different partition scopes get independent corpus_size entries, and the + same tokens on a different scope re-fetch DF rather than reuse.""" + store = _RecordingStore(corpus_size=100, df_map=_df_map()) + searcher = _make_searcher(store) + + await searcher._build_idf("alpha beta", ["p1"]) + first_corpus, first_df = store.corpus_size_calls, store.doc_freq_calls + + # Same tokens, different partition scope → independent entries, so both + # stats miss and re-fetch; a cached p1 entry must not serve a p2 query. + await searcher._build_idf("alpha beta", ["p2"]) + + assert store.corpus_size_calls == first_corpus + 1 + assert store.doc_freq_calls == first_df + 1 + + # Order-independence: a re-scope of the same set as p1 should now hit cache. + await searcher._build_idf("alpha beta", ["p1"]) + assert store.corpus_size_calls == first_corpus + 1 # p1 still cached → no hit + assert store.doc_freq_calls == first_df + 1 + + +async def test_df_keyed_by_token_does_not_leak_across_tokens() -> None: + """DF entries are keyed by token, so one token's df never masquerades as + another's — observable through IDF: a rare term and a common term on the + same partition scope keep distinct scores even after caching.""" + store = _RecordingStore(corpus_size=100, df_map=_df_map()) + searcher = _make_searcher(store) + + idf = await searcher._build_idf("alpha beta", ["p1"]) + assert idf is not None + rare_score = idf("alpha") # df 1 → higher IDF + common_score = idf("beta") # df 5 → lower IDF + assert rare_score > common_score + + # Re-querying only the common term must not reuse the rare term's df: its + # IDF comes from its own cached entry, not alpha's. ``beta`` was already + # cached by the first query, so the second query adds *no* DF round-trip — + # and the common score is unchanged (it did not pick up alpha's rare-term df). + idf_beta_only = await searcher._build_idf("beta", ["p1"]) + assert idf_beta_only is not None + assert idf_beta_only("beta") == common_score + assert store.doc_freq_calls == 1 # beta cached from query 1 → no refetch, no leak + + +@pytest.mark.parametrize("order_a,order_b", [(["p2", "p1"], ["p1", "p2"])]) +async def test_partition_key_is_order_independent(order_a: list[str], order_b: list[str]) -> None: + """The same partition set in any order maps to one cache entry.""" + store = _RecordingStore(corpus_size=100, df_map=_df_map()) + searcher = _make_searcher(store) + + await searcher._build_idf("alpha", order_a) + corpus_after_first = store.corpus_size_calls + + await searcher._build_idf("alpha", order_b) + + assert store.corpus_size_calls == corpus_after_first # same set → hit + + +async def test_zero_statistics_are_cached() -> None: + """Zero corpus/DF values are answers, not cache misses.""" + empty_store = _RecordingStore(corpus_size=0) + empty_searcher = _make_searcher(empty_store) + + assert await empty_searcher._build_idf("alpha", ["p1"]) is None + assert await empty_searcher._build_idf("alpha", ["p1"]) is None + assert empty_store.corpus_size_calls == 1 + assert empty_store.doc_freq_calls == 0 + + zero_df_store = _RecordingStore(corpus_size=10, df_map={"alpha": 0}) + zero_df_searcher = _make_searcher(zero_df_store) + assert await zero_df_searcher._build_idf("alpha", ["p1"]) is not None + assert await zero_df_searcher._build_idf("alpha", ["p1"]) is not None + assert zero_df_store.corpus_size_calls == 1 + assert zero_df_store.doc_freq_calls == 1 + + +# --------------------------------------------------------------------------- +# Concurrent miss de-duplication (the instance lock around the miss section) +# --------------------------------------------------------------------------- + + +async def test_concurrent_miss_deduplicates_store_calls() -> None: + """Concurrent ``_build_idf`` calls that miss the same key share one fetch. + + Without the instance lock guarding the miss → fetch → back-fill section, N + coroutines entering with the same cold key would each hit the store (N + round-trips, correct result but wasteful). The leader fetches; waiters + re-check the cache under the lock and find it populated, so ``corpus_size`` + is called exactly once for the whole concurrent batch, and every caller + gets the same IDF weighter. + """ + store = _RecordingStore(corpus_size=100, df_map=_df_map()) + searcher = _make_searcher(store) + + # Fire 5 identical cold-key calls concurrently. corpus_size depends only on + # the partition scope, so the leader's single fetch warms it for all 5. + results = await asyncio.gather(*[searcher._build_idf("alpha", ["p1"]) for _ in range(5)]) + + assert store.corpus_size_calls == 1 # leader fetched, the rest hit cache + # DF is per-token; "alpha" was fetched once by the leader too. + assert store.doc_freq_calls == 1 + # Every concurrent caller built the same weighter from the shared stats. + scores = [idf("alpha") for idf in results if idf is not None] + assert len(scores) == 5 + assert len(set(scores)) == 1 + + +async def test_concurrent_distinct_keys_still_fetch_their_own() -> None: + """The lock de-duplicates *identical* misses, not unrelated ones. + + Two concurrent calls over disjoint token sets (on the same cached partition) + share the cached ``corpus_size`` but each fetches its own DF — the lock + serialises the section but does not collapse distinct keys. + """ + store = _RecordingStore(corpus_size=100, df_map=_df_map()) + searcher = _make_searcher(store) + + # Warm corpus_size for the partition so only DF is in play. + await searcher._build_idf("alpha", ["p1"]) + corpus_before = store.corpus_size_calls + df_before = store.doc_freq_calls + + await asyncio.gather( + searcher._build_idf("beta", ["p1"]), # new token → its own DF fetch + searcher._build_idf("gamma", ["p1"]), # different new token → its own + ) + + assert store.corpus_size_calls == corpus_before # partition warmed → 0 more + assert store.doc_freq_calls == df_before + 2 # beta + gamma, distinct keys diff --git a/uv.lock b/uv.lock index 74a551e..865c12c 100644 --- a/uv.lock +++ b/uv.lock @@ -1091,7 +1091,7 @@ wheels = [ [[package]] name = "hebb-mind" -version = "0.1.3" +version = "0.3.0" source = { editable = "." } dependencies = [ { name = "aiosqlite" }, @@ -1099,6 +1099,7 @@ dependencies = [ { name = "click" }, { name = "fastapi" }, { name = "httpx" }, + { name = "json-repair" }, { name = "litellm" }, { name = "mcp" }, { name = "networkx", version = "3.4.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, @@ -1141,8 +1142,9 @@ requires-dist = [ { name = "datasets", marker = "extra == 'dev'", specifier = ">=2.0.0" }, { name = "fastapi", specifier = ">=0.115.0" }, { name = "httpx", specifier = ">=0.27.0" }, + { name = "json-repair", specifier = ">=0.30.0" }, { name = "litellm", specifier = ">=1.40.0" }, - { name = "mcp", specifier = ">=1.0.0" }, + { name = "mcp", specifier = ">=1.0.0,<2.0.0" }, { name = "mypy", marker = "extra == 'dev'", specifier = ">=1.10.0" }, { name = "networkx", specifier = ">=3.1" }, { name = "numpy", specifier = ">=1.24.0" }, @@ -1456,6 +1458,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7b/91/984aca2ec129e2757d1e4e3c81c3fcda9d0f85b74670a094cc443d9ee949/joblib-1.5.3-py3-none-any.whl", hash = "sha256:5fc3c5039fc5ca8c0276333a188bbd59d6b7ab37fe6632daa76bc7f9ec18e713", size = 309071, upload-time = "2025-12-15T08:41:44.973Z" }, ] +[[package]] +name = "json-repair" +version = "0.61.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f0/a3/6001c2448ee54a80f35a2501b848f4bbd87987bd41ead8cc17367a2bfd56/json_repair-0.61.7.tar.gz", hash = "sha256:a3754543f050093efcda6c9ab00b20a236b5d082c8c622bc65b88fa74ff8d51f", size = 51573, upload-time = "2026-07-21T13:01:15.085Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/76/da/7f9e2b0a1120b107a204bbab6d0ef7ff2ae37790bddc5ee21c9c1f961f3b/json_repair-0.61.7-py3-none-any.whl", hash = "sha256:45c99b8cffef404e846b60d3dc21fc6f0fd5a4595cebad169dfab083ffb8246a", size = 50146, upload-time = "2026-07-21T13:01:13.734Z" }, +] + [[package]] name = "jsonschema" version = "4.26.0"