Spaces:
Running
Fix remaining architect-flagged issues — targeting 9.5+
Browse filesRetrievalService 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 +7 -3
- backend/mcp_server.py +14 -0
- backend/services/generation.py +8 -6
- eval/eval.py +24 -0
- eval/test_cases/nanogpt.json +52 -0
- ingestion/qdrant_store.py +15 -3
- retrieval/retrieval.py +24 -12
|
@@ -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 |
-
|
| 192 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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]
|
|
@@ -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"}
|
|
@@ -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 |
-
|
|
|
|
| 152 |
return "groq"
|
| 153 |
elif settings.anthropic_api_key:
|
| 154 |
import anthropic
|
| 155 |
self._client = anthropic.Anthropic(api_key=settings.anthropic_api_key)
|
| 156 |
-
|
|
|
|
| 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=
|
| 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=
|
| 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=
|
| 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=
|
| 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"],
|
|
@@ -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
|
|
@@ -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 |
+
]
|
|
@@ -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 |
-
|
| 333 |
-
|
| 334 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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).
|
|
@@ -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
|
| 61 |
-
IngestionService and RetrievalService both need the
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
| 64 |
"""
|
| 65 |
|
| 66 |
DENSE_VECTOR_NAME = "code"
|
| 67 |
SPARSE_VECTOR_NAME = "bm25"
|
| 68 |
|
| 69 |
-
def __init__(
|
| 70 |
-
self
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
)
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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,
|