umanggarg Claude Sonnet 4.6 commited on
Commit
ed5aef3
·
1 Parent(s): c970958

Fix remaining architect-flagged issues — targeting 9.5+

Browse files

RetrievalService shared QdrantClient:
- Was creating its own QdrantClient despite main.py wiring a shared QdrantStore.
- Now accepts QdrantStore param and uses store.client — single connection pool.

BM25 docstring correctness:
- Comment claimed Qdrant applies IDF to manually-supplied sparse vectors.
- Factually wrong: IDF is only applied by Qdrant's built-in FastEmbed vectorizer.
- Corrected to accurately describe TF-only behavior, explain the practical
impact on code search, and document the upgrade path to true BM25.

GenerationService hardcoded model strings:
- _groq_complete/_groq_stream had "llama-3.3-70b-versatile" as literals.
- Now uses self._model set in _init_provider, consistent with AgentService.

Security — filepath path traversal (get_file_chunk):
- LLM-supplied filepath was passed directly into GitHub API URL.
- Added validation: repo must be "owner/name", filepath must not contain
".." components or start with "/". Uses PurePosixPath for robust parsing.

Security — X-Forwarded-For leftmost vs rightmost IP:
- Was using split(",")[0] — the leftmost entry is user-controlled and
trivially bypassable to defeat per-IP rate limiting.
- Fixed to split(",")[-1] — the rightmost entry is appended by the actual
proxy and cannot be forged by the client.

Eval harness improvements:
- Added eval/test_cases/nanogpt.json: 10 cases for karpathy/nanoGPT covering
BM25-heavy queries ("where is get_batch called"), semantic queries
("how does attention work"), and config/init cases.
- Added --output FILE flag: writes JSON summary for CI integration.
Enables git diff eval_results.json to surface retrieval regressions.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

backend/main.py CHANGED
@@ -95,7 +95,7 @@ async def lifespan(app: FastAPI):
95
  _qdrant_store = QdrantStore()
96
 
97
  # Core services — all share the same store + embedder instances
98
- _retrieval_service = RetrievalService(embedder=_embedder)
99
  _ingestion_service = IngestionService(store=_qdrant_store, embedder=_embedder)
100
  _graph_service = GraphService(_qdrant_store)
101
  _generation_service = GenerationService()
@@ -188,8 +188,12 @@ def _check_rate_limit(request: Request) -> None:
188
  if limit <= 0:
189
  return # disabled
190
 
191
- ip = request.headers.get("X-Forwarded-For", "").split(",")[0].strip()
192
- ip = ip or (request.client.host if request.client else "unknown")
 
 
 
 
193
  now = time.monotonic()
194
 
195
  window = _rate_windows[ip]
 
95
  _qdrant_store = QdrantStore()
96
 
97
  # Core services — all share the same store + embedder instances
98
+ _retrieval_service = RetrievalService(embedder=_embedder, store=_qdrant_store)
99
  _ingestion_service = IngestionService(store=_qdrant_store, embedder=_embedder)
100
  _graph_service = GraphService(_qdrant_store)
101
  _generation_service = GenerationService()
 
188
  if limit <= 0:
189
  return # disabled
190
 
191
+ # Use the RIGHTMOST X-Forwarded-For entry — it's appended by the actual
192
+ # proxy (Render, Cloudflare, etc.) and cannot be forged by the client.
193
+ # The leftmost entry is user-controlled and trivially bypassable.
194
+ forwarded = request.headers.get("X-Forwarded-For", "")
195
+ ip = forwarded.split(",")[-1].strip() if forwarded else ""
196
+ ip = ip or (request.client.host if request.client else "unknown")
197
  now = time.monotonic()
198
 
199
  window = _rate_windows[ip]
backend/mcp_server.py CHANGED
@@ -226,6 +226,20 @@ def get_file_chunk(
226
  start_line: First line to fetch, 1-indexed
227
  end_line: Last line to fetch, inclusive
228
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
  owner, name = repo.split("/", 1)
230
  url = f"https://api.github.com/repos/{owner}/{name}/contents/{filepath}"
231
  headers = {"Accept": "application/vnd.github.v3.raw"}
 
226
  start_line: First line to fetch, 1-indexed
227
  end_line: Last line to fetch, inclusive
228
  """
229
+ # Validate repo format — LLM-supplied args must never be passed raw into URLs.
230
+ if "/" not in repo or repo.count("/") != 1:
231
+ return f"Invalid repo format '{repo}'. Expected 'owner/name'."
232
+
233
+ # Reject path traversal — an LLM (or prompt injection) could pass "../.env"
234
+ # which would resolve to an unintended path in the GitHub API URL.
235
+ from pathlib import PurePosixPath
236
+ try:
237
+ parts = PurePosixPath(filepath).parts
238
+ except Exception:
239
+ return "Invalid filepath."
240
+ if ".." in parts or filepath.startswith("/"):
241
+ return "Invalid filepath: path traversal not allowed."
242
+
243
  owner, name = repo.split("/", 1)
244
  url = f"https://api.github.com/repos/{owner}/{name}/contents/{filepath}"
245
  headers = {"Accept": "application/vnd.github.v3.raw"}
backend/services/generation.py CHANGED
@@ -148,12 +148,14 @@ class GenerationService:
148
  if settings.groq_api_key:
149
  from groq import Groq
150
  self._client = Groq(api_key=settings.groq_api_key)
151
- print("Generation: using Groq (llama-3.3-70b-versatile)")
 
152
  return "groq"
153
  elif settings.anthropic_api_key:
154
  import anthropic
155
  self._client = anthropic.Anthropic(api_key=settings.anthropic_api_key)
156
- print("Generation: using Anthropic (claude-haiku-4-5)")
 
157
  return "anthropic"
158
  else:
159
  raise ValueError(
@@ -207,7 +209,7 @@ class GenerationService:
207
 
208
  def _groq_complete(self, system: str, prompt: str, params: dict) -> str:
209
  response = self._client.chat.completions.create(
210
- model="llama-3.3-70b-versatile",
211
  messages=[
212
  {"role": "system", "content": system},
213
  {"role": "user", "content": prompt},
@@ -219,7 +221,7 @@ class GenerationService:
219
 
220
  def _groq_stream(self, system: str, prompt: str, params: dict) -> Iterator[str]:
221
  stream = self._client.chat.completions.create(
222
- model="llama-3.3-70b-versatile",
223
  messages=[
224
  {"role": "system", "content": system},
225
  {"role": "user", "content": prompt},
@@ -237,7 +239,7 @@ class GenerationService:
237
 
238
  def _anthropic_complete(self, system: str, prompt: str, params: dict) -> str:
239
  response = self._client.messages.create(
240
- model="claude-haiku-4-5-20251001",
241
  system=system,
242
  messages=[{"role": "user", "content": prompt}],
243
  temperature=params["temperature"],
@@ -247,7 +249,7 @@ class GenerationService:
247
 
248
  def _anthropic_stream(self, system: str, prompt: str, params: dict) -> Iterator[str]:
249
  with self._client.messages.stream(
250
- model="claude-haiku-4-5-20251001",
251
  system=system,
252
  messages=[{"role": "user", "content": prompt}],
253
  temperature=params["temperature"],
 
148
  if settings.groq_api_key:
149
  from groq import Groq
150
  self._client = Groq(api_key=settings.groq_api_key)
151
+ self._model = "llama-3.3-70b-versatile"
152
+ print(f"Generation: using Groq ({self._model})")
153
  return "groq"
154
  elif settings.anthropic_api_key:
155
  import anthropic
156
  self._client = anthropic.Anthropic(api_key=settings.anthropic_api_key)
157
+ self._model = "claude-haiku-4-5-20251001"
158
+ print(f"Generation: using Anthropic ({self._model})")
159
  return "anthropic"
160
  else:
161
  raise ValueError(
 
209
 
210
  def _groq_complete(self, system: str, prompt: str, params: dict) -> str:
211
  response = self._client.chat.completions.create(
212
+ model=self._model,
213
  messages=[
214
  {"role": "system", "content": system},
215
  {"role": "user", "content": prompt},
 
221
 
222
  def _groq_stream(self, system: str, prompt: str, params: dict) -> Iterator[str]:
223
  stream = self._client.chat.completions.create(
224
+ model=self._model,
225
  messages=[
226
  {"role": "system", "content": system},
227
  {"role": "user", "content": prompt},
 
239
 
240
  def _anthropic_complete(self, system: str, prompt: str, params: dict) -> str:
241
  response = self._client.messages.create(
242
+ model=self._model,
243
  system=system,
244
  messages=[{"role": "user", "content": prompt}],
245
  temperature=params["temperature"],
 
249
 
250
  def _anthropic_stream(self, system: str, prompt: str, params: dict) -> Iterator[str]:
251
  with self._client.messages.stream(
252
+ model=self._model,
253
  system=system,
254
  messages=[{"role": "user", "content": prompt}],
255
  temperature=params["temperature"],
eval/eval.py CHANGED
@@ -235,6 +235,11 @@ def main():
235
  "--verbose", action="store_true",
236
  help="Show per-case results including misses"
237
  )
 
 
 
 
 
238
  args = parser.parse_args()
239
 
240
  # ── Load test cases ────────────────────────────────────────────────────────
@@ -274,6 +279,25 @@ def main():
274
  all_summaries[mode] = summary
275
  print_report(mode, summary, results, args.top_k, args.verbose)
276
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
  # ── Comparison table ───────────────────────────────────────────────────────
278
  if len(args.modes) > 1:
279
  k = args.top_k
 
235
  "--verbose", action="store_true",
236
  help="Show per-case results including misses"
237
  )
238
+ parser.add_argument(
239
+ "--output", default=None, metavar="FILE",
240
+ help="Write results as JSON to FILE (e.g. eval_results.json). "
241
+ "Useful for CI: git diff eval_results.json shows regressions."
242
+ )
243
  args = parser.parse_args()
244
 
245
  # ── Load test cases ────────────────────────────────────────────────────────
 
279
  all_summaries[mode] = summary
280
  print_report(mode, summary, results, args.top_k, args.verbose)
281
 
282
+ # ── JSON output for CI ────────────────────────────────────────────────────
283
+ if args.output:
284
+ import json as _json
285
+ output = {
286
+ "repo": args.repo,
287
+ "top_k": args.top_k,
288
+ "n_cases": len(cases),
289
+ "results": {
290
+ mode: {
291
+ "hit_at_k": s[f"hit@{args.top_k}"],
292
+ "mrr": s["mrr"],
293
+ "p_at_k": s[f"p@{args.top_k}"],
294
+ }
295
+ for mode, s in all_summaries.items()
296
+ }
297
+ }
298
+ Path(args.output).write_text(_json.dumps(output, indent=2))
299
+ print(f"\nResults written to {args.output}")
300
+
301
  # ── Comparison table ───────────────────────────────────────────────────────
302
  if len(args.modes) > 1:
303
  k = args.top_k
eval/test_cases/nanogpt.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "question": "where is get_batch called",
4
+ "expected_files": ["train.py"],
5
+ "expected_names": ["get_batch"]
6
+ },
7
+ {
8
+ "question": "How is the attention mechanism implemented?",
9
+ "expected_files": ["model.py"],
10
+ "expected_names": ["CausalSelfAttention"]
11
+ },
12
+ {
13
+ "question": "What does the GPT class do?",
14
+ "expected_files": ["model.py"],
15
+ "expected_names": ["GPT"]
16
+ },
17
+ {
18
+ "question": "How is learning rate decay scheduled?",
19
+ "expected_files": ["train.py"],
20
+ "expected_names": ["get_lr"]
21
+ },
22
+ {
23
+ "question": "How does the forward pass work in the transformer block?",
24
+ "expected_files": ["model.py"],
25
+ "expected_names": ["Block", "forward"]
26
+ },
27
+ {
28
+ "question": "How is the model configured and initialised from a checkpoint?",
29
+ "expected_files": ["model.py"],
30
+ "expected_names": ["GPTConfig", "from_pretrained"]
31
+ },
32
+ {
33
+ "question": "How are tokens generated after training?",
34
+ "expected_files": ["model.py", "sample.py"],
35
+ "expected_names": ["generate"]
36
+ },
37
+ {
38
+ "question": "How is gradient clipping applied during training?",
39
+ "expected_files": ["train.py"],
40
+ "expected_names": []
41
+ },
42
+ {
43
+ "question": "What is the LayerNorm implementation used?",
44
+ "expected_files": ["model.py"],
45
+ "expected_names": ["LayerNorm"]
46
+ },
47
+ {
48
+ "question": "How does DDP distributed training work in the training loop?",
49
+ "expected_files": ["train.py"],
50
+ "expected_names": []
51
+ }
52
+ ]
ingestion/qdrant_store.py CHANGED
@@ -329,9 +329,21 @@ def _text_to_sparse(text: str) -> SparseVector:
329
  → indices = [md5("def") % 1M, md5("embed_text") % 1M, ...]
330
  values = [1.0, 1.0, 1.0, 2.0, ...]
331
 
332
- Qdrant uses these sparse vectors for BM25-style keyword matching.
333
- The actual BM25 ranking (IDF weighting, document length normalisation)
334
- is applied at query time by Qdrant.
 
 
 
 
 
 
 
 
 
 
 
 
335
 
336
  WHY NOT hash(token)?
337
  Python's built-in hash() is randomised per process (PYTHONHASHSEED).
 
329
  → indices = [md5("def") % 1M, md5("embed_text") % 1M, ...]
330
  values = [1.0, 1.0, 1.0, 2.0, ...]
331
 
332
+ IMPORTANT this is TF (term frequency) only, NOT full BM25.
333
+ True BM25 requires IDF (inverse document frequency), which weights rare
334
+ terms higher than common ones (e.g. "backward" > "def"). Qdrant can apply
335
+ IDF automatically only if you use its built-in FastEmbed sparse vectorizer
336
+ (which builds a vocabulary from your corpus). When you supply raw sparse
337
+ vectors manually (as we do here), Qdrant treats them as-is — no IDF,
338
+ no document length normalisation.
339
+
340
+ Practical effect: exact identifier lookups still work well (TF alone finds
341
+ the chunk containing "backward" 5 times better than one mentioning it once).
342
+ But stop-word-heavy queries ("how does the") may score higher than they
343
+ should. For a code search use case this is a reasonable trade-off since
344
+ identifiers are the dominant signal and they're naturally rare.
345
+
346
+ Upgrade path: switch to Qdrant's FastEmbed sparse vectorizer for true BM25.
347
 
348
  WHY NOT hash(token)?
349
  Python's built-in hash() is randomised per process (PYTHONHASHSEED).
retrieval/retrieval.py CHANGED
@@ -46,7 +46,7 @@ from qdrant_client.models import (
46
  sys.path.insert(0, str(Path(__file__).parent.parent))
47
  from backend.config import settings
48
  from ingestion.embedder import Embedder
49
- from ingestion.qdrant_store import _text_to_sparse
50
 
51
 
52
  class RetrievalService:
@@ -57,22 +57,34 @@ class RetrievalService:
57
  as the indexed chunks. Mixing embedding models breaks retrieval entirely —
58
  vectors from different models are incomparable.
59
 
60
- Why accept embedder as an argument?
61
- IngestionService and RetrievalService both need the same 600MB model.
62
- Instantiating it twice wastes ~600MB RAM. main.py creates one Embedder
63
- and passes it to both services. Shared state, one load.
 
 
64
  """
65
 
66
  DENSE_VECTOR_NAME = "code"
67
  SPARSE_VECTOR_NAME = "bm25"
68
 
69
- def __init__(self, embedder: Embedder | None = None):
70
- self.embedder = embedder or Embedder()
71
- self.client = QdrantClient(
72
- url=settings.qdrant_url,
73
- api_key=settings.qdrant_api_key or None,
74
- )
75
- self.collection = settings.qdrant_collection
 
 
 
 
 
 
 
 
 
 
76
 
77
  def search(
78
  self,
 
46
  sys.path.insert(0, str(Path(__file__).parent.parent))
47
  from backend.config import settings
48
  from ingestion.embedder import Embedder
49
+ from ingestion.qdrant_store import QdrantStore, _text_to_sparse
50
 
51
 
52
  class RetrievalService:
 
57
  as the indexed chunks. Mixing embedding models breaks retrieval entirely —
58
  vectors from different models are incomparable.
59
 
60
+ Why accept embedder and store as arguments?
61
+ - Embedder: IngestionService and RetrievalService both need the 600MB model.
62
+ Instantiating twice wastes ~600MB RAM. main.py creates one and shares it.
63
+ - QdrantStore: opening a second QdrantClient creates a second connection pool
64
+ to the same database, which wastes resources and was the "3 QdrantStore
65
+ instances" bug. By accepting the shared store we use its existing client.
66
  """
67
 
68
  DENSE_VECTOR_NAME = "code"
69
  SPARSE_VECTOR_NAME = "bm25"
70
 
71
+ def __init__(
72
+ self,
73
+ embedder: Embedder | None = None,
74
+ store: QdrantStore | None = None,
75
+ ):
76
+ self.embedder = embedder or Embedder()
77
+ # Use the shared store's client if provided; otherwise open a new connection.
78
+ # The store already validated QDRANT_URL and created payload indices.
79
+ if store is not None:
80
+ self.client = store.client
81
+ self.collection = store.collection
82
+ else:
83
+ self.client = QdrantClient(
84
+ url=settings.qdrant_url,
85
+ api_key=settings.qdrant_api_key or None,
86
+ )
87
+ self.collection = settings.qdrant_collection
88
 
89
  def search(
90
  self,