Ray5th commited on
Commit
2e7766e
·
unverified ·
2 Parent(s): c84133e1c701bb

Merge pull request #8 from ray5th/worktree-agent-a0c1e62025fb04462

Browse files
Files changed (2) hide show
  1. src/retriever.py +24 -0
  2. tests/test_retriever_fuzz.py +230 -0
src/retriever.py CHANGED
@@ -61,6 +61,11 @@ class MathLibRetriever:
61
 
62
  self._retriever = self._build_retriever(faiss_store, docs)
63
 
 
 
 
 
 
64
  def retrieve(self, query: str, k: Optional[int] = None) -> List[Document]:
65
  """
66
  Retrieve and rerank the most relevant Mathlib lemmas for a query.
@@ -71,7 +76,26 @@ class MathLibRetriever:
71
 
72
  Returns:
73
  List of Documents ranked by relevance.
 
 
 
74
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  if self._retriever is None:
76
  if not self.is_index_built():
77
  if not self._missing_index_warned:
 
61
 
62
  self._retriever = self._build_retriever(faiss_store, docs)
63
 
64
+ # Hard cap on query length passed to downstream retrievers. Long queries
65
+ # waste embedding work and can blow past tokenizer limits; truncating here
66
+ # gives callers a predictable upper bound.
67
+ _MAX_QUERY_CHARS = 2000
68
+
69
  def retrieve(self, query: str, k: Optional[int] = None) -> List[Document]:
70
  """
71
  Retrieve and rerank the most relevant Mathlib lemmas for a query.
 
76
 
77
  Returns:
78
  List of Documents ranked by relevance.
79
+
80
+ Raises:
81
+ TypeError: If `query` is not a string.
82
  """
83
+ if not isinstance(query, str):
84
+ raise TypeError(
85
+ f"query must be a str, got {type(query).__name__}"
86
+ )
87
+
88
+ # Empty/whitespace-only queries are valid input but degenerate; bail
89
+ # out early with no results rather than asking the embedding model to
90
+ # vectorise an empty string (which produces noisy nearest neighbours).
91
+ if not query.strip():
92
+ return []
93
+
94
+ # Truncate absurdly long inputs so a runaway caller can't pin the
95
+ # embedding model.
96
+ if len(query) > self._MAX_QUERY_CHARS:
97
+ query = query[: self._MAX_QUERY_CHARS]
98
+
99
  if self._retriever is None:
100
  if not self.is_index_built():
101
  if not self._missing_index_warned:
tests/test_retriever_fuzz.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Fuzz tests for `MathLibRetriever.retrieve()` and `MathLibRetriever.__init__`.
3
+
4
+ Heavy/expensive deps (HuggingFaceEmbeddings, FAISS, HuggingFaceCrossEncoder) are
5
+ mocked BEFORE `retriever` is imported so the module never touches the real
6
+ models or disk-resident indices.
7
+ """
8
+
9
+ import os
10
+ import sys
11
+ import tempfile
12
+ import unittest
13
+ from unittest import mock
14
+
15
+ # Make `src/` importable.
16
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "src")))
17
+ # Spec requires literal `sys.path.insert(0, 'src')` too.
18
+ sys.path.insert(0, "src")
19
+
20
+ # ---------------------------------------------------------------------------
21
+ # Patch heavy dependencies BEFORE importing retriever.
22
+ # ---------------------------------------------------------------------------
23
+
24
+ from langchain_core.documents import Document # safe import (lightweight)
25
+
26
+ # Fake documents the mocked retriever pipeline returns.
27
+ _FAKE_DOCS = [
28
+ Document(page_content=f"lemma_{i}", metadata={"name": f"lemma_{i}"})
29
+ for i in range(5)
30
+ ]
31
+
32
+
33
+ class _FakeEmbeddings:
34
+ def __init__(self, *a, **kw):
35
+ pass
36
+
37
+ def embed_documents(self, texts):
38
+ return [[0.0] * 8 for _ in texts]
39
+
40
+ def embed_query(self, text):
41
+ return [0.0] * 8
42
+
43
+
44
+ class _FakeDocstore:
45
+ def __init__(self, docs):
46
+ self._dict = {str(i): d for i, d in enumerate(docs)}
47
+
48
+
49
+ class _FakeFAISS:
50
+ """Mock for `langchain_community.vectorstores.FAISS`."""
51
+
52
+ def __init__(self, docs=None):
53
+ self.docstore = _FakeDocstore(docs or _FAKE_DOCS)
54
+
55
+ @classmethod
56
+ def from_documents(cls, docs, embeddings): # noqa: ARG003
57
+ return cls(docs)
58
+
59
+ @classmethod
60
+ def load_local(cls, path, embeddings, allow_dangerous_deserialization=False): # noqa: ARG003
61
+ # Mimic real FAISS: choke on garbage files.
62
+ index_path = os.path.join(path, "index.faiss")
63
+ if os.path.exists(index_path):
64
+ with open(index_path, "rb") as fh:
65
+ head = fh.read(64)
66
+ # Real FAISS index has a magic header; garbage will fail to parse.
67
+ if b"garbage" in head or len(head) < 8:
68
+ raise RuntimeError(f"FAISS index at {path} is corrupt or unreadable.")
69
+ return cls(_FAKE_DOCS)
70
+
71
+ def save_local(self, path):
72
+ os.makedirs(path, exist_ok=True)
73
+ with open(os.path.join(path, "index.faiss"), "wb") as fh:
74
+ fh.write(b"\x00" * 128)
75
+
76
+ def as_retriever(self, search_kwargs=None): # noqa: ARG002
77
+ return _FakeBaseRetriever()
78
+
79
+
80
+ class _FakeBaseRetriever:
81
+ def invoke(self, query): # noqa: ARG002
82
+ return list(_FAKE_DOCS)
83
+
84
+
85
+ class _FakeCrossEncoder:
86
+ def __init__(self, *a, **kw):
87
+ pass
88
+
89
+ def score(self, pairs):
90
+ return [0.5 for _ in pairs]
91
+
92
+
93
+ # Build the module-level mocks. These need to be patched in *both* the
94
+ # original module *and* the `retriever` module namespace, since `retriever.py`
95
+ # does `from X import Y` (binds Y locally).
96
+ _patchers = [
97
+ mock.patch("langchain_huggingface.HuggingFaceEmbeddings", _FakeEmbeddings),
98
+ mock.patch("langchain_community.vectorstores.FAISS", _FakeFAISS),
99
+ mock.patch(
100
+ "langchain_community.cross_encoders.HuggingFaceCrossEncoder",
101
+ _FakeCrossEncoder,
102
+ ),
103
+ ]
104
+ for p in _patchers:
105
+ p.start()
106
+
107
+ # Now safe to import the module under test.
108
+ import retriever # noqa: E402
109
+
110
+ # Re-bind the locally imported names inside `retriever` to our fakes, because
111
+ # `from … import …` already captured the originals at import time.
112
+ retriever.HuggingFaceEmbeddings = _FakeEmbeddings
113
+ retriever.FAISS = _FakeFAISS
114
+ retriever.HuggingFaceCrossEncoder = _FakeCrossEncoder
115
+
116
+
117
+ # ---------------------------------------------------------------------------
118
+ # Helper: build a retriever with `_retriever` pre-populated, sidestepping the
119
+ # real BM25/EnsembleRetriever/ContextualCompressionRetriever pipeline that we
120
+ # don't need for fuzzing `retrieve()`'s query handling.
121
+ # ---------------------------------------------------------------------------
122
+
123
+ def _make_retriever_with_fake_pipeline(index_dir=None):
124
+ r = retriever.MathLibRetriever(index_dir=index_dir)
125
+ r._retriever = _FakeBaseRetriever()
126
+ return r
127
+
128
+
129
+ # ---------------------------------------------------------------------------
130
+ # Tests
131
+ # ---------------------------------------------------------------------------
132
+
133
+
134
+ class RetrieveQueryFuzzTests(unittest.TestCase):
135
+ """Fuzz the `retrieve(query)` method."""
136
+
137
+ def setUp(self):
138
+ self.r = _make_retriever_with_fake_pipeline()
139
+
140
+ def test_empty_string_does_not_crash(self):
141
+ results = self.r.retrieve("")
142
+ self.assertIsInstance(results, list)
143
+
144
+ def test_whitespace_only_does_not_crash(self):
145
+ results = self.r.retrieve(" \n ")
146
+ self.assertIsInstance(results, list)
147
+
148
+ def test_long_query_does_not_crash(self):
149
+ q = "foo " * 1250 # 5000 chars
150
+ self.assertEqual(len(q), 5000)
151
+ results = self.r.retrieve(q)
152
+ self.assertIsInstance(results, list)
153
+
154
+ def test_only_special_chars_does_not_crash(self):
155
+ q = "!@#$%^&*()_+-=[]{}|;:',.<>?/`"
156
+ results = self.r.retrieve(q)
157
+ self.assertIsInstance(results, list)
158
+
159
+ def test_lean_unicode_does_not_crash(self):
160
+ q = "∀ n : ℕ, ∃ m, n + m = m + n" # ∀ n : ℕ, ∃ m, n + m = m + n
161
+ results = self.r.retrieve(q)
162
+ self.assertIsInstance(results, list)
163
+
164
+ def test_none_query_raises_typeerror(self):
165
+ """None as a query must raise TypeError, not return garbage."""
166
+ with self.assertRaises(TypeError):
167
+ self.r.retrieve(None)
168
+
169
+ def test_non_string_int_raises_typeerror(self):
170
+ with self.assertRaises(TypeError):
171
+ self.r.retrieve(12345) # type: ignore[arg-type]
172
+
173
+ def test_respects_k_argument(self):
174
+ results = self.r.retrieve("anything", k=2)
175
+ self.assertLessEqual(len(results), 2)
176
+
177
+ def test_default_k_truncates_to_rerank_top_k(self):
178
+ # _FAKE_DOCS has 5 entries, default rerank_top_k=5 so we expect all 5
179
+ results = self.r.retrieve("anything")
180
+ self.assertLessEqual(len(results), self.r.rerank_top_k)
181
+
182
+
183
+ class RetrieveLazyLoadTests(unittest.TestCase):
184
+ """`retrieve()` should lazily call `_load()` when no retriever exists."""
185
+
186
+ def test_retrieve_without_built_index_raises_runtime_error(self):
187
+ with tempfile.TemporaryDirectory() as tmp:
188
+ r = retriever.MathLibRetriever(index_dir=tmp)
189
+ with self.assertRaises(RuntimeError):
190
+ r.retrieve("query")
191
+
192
+
193
+ class InitFuzzTests(unittest.TestCase):
194
+ """Fuzz `MathLibRetriever.__init__` and related path handling."""
195
+
196
+ def test_index_dir_none_uses_default(self):
197
+ r = retriever.MathLibRetriever(index_dir=None)
198
+ # The default lives at <repo>/data/mathlib_index.
199
+ self.assertTrue(str(r.index_dir).endswith(os.path.join("data", "mathlib_index")))
200
+
201
+ def test_index_dir_nonexistent_path_is_index_built_false(self):
202
+ r = retriever.MathLibRetriever(index_dir="/nonexistent/path/definitely-not-here")
203
+ self.assertFalse(r.is_index_built())
204
+
205
+ def test_index_dir_garbage_raises_clear_error_on_load(self):
206
+ with tempfile.TemporaryDirectory() as tmp:
207
+ # Drop a "looks like an index but is garbage" file.
208
+ garbage = os.path.join(tmp, "index.faiss")
209
+ with open(garbage, "wb") as fh:
210
+ fh.write(b"garbage" * 4)
211
+
212
+ r = retriever.MathLibRetriever(index_dir=tmp)
213
+ self.assertTrue(r.is_index_built()) # file exists, so passes the cheap check
214
+ with self.assertRaises(Exception) as ctx:
215
+ r._load()
216
+ # Must surface a meaningful error, not silently succeed.
217
+ msg = str(ctx.exception).lower()
218
+ self.assertTrue(
219
+ any(k in msg for k in ("faiss", "index", "corrupt", "unread", "load")),
220
+ f"Error message should mention the index/FAISS, got: {ctx.exception!r}",
221
+ )
222
+
223
+ def test_empty_index_dir_is_index_built_false(self):
224
+ with tempfile.TemporaryDirectory() as tmp:
225
+ r = retriever.MathLibRetriever(index_dir=tmp)
226
+ self.assertFalse(r.is_index_built())
227
+
228
+
229
+ if __name__ == "__main__":
230
+ unittest.main()