The user wants me to build a "Code Search Quality Evaluator".
This tool needs to incorporate three main components:
- Relevancy Tests: Assessing if the search results are actually relevant to the query.
- Click Logs: Analyzing user interaction (what they click on) to infer relevance.
- Improvement Loops: Using the data from (1) and (2) to refine the search algorithm (ranking, indexing, etc.).
This is a software engineering task. I should provide a conceptual framework, a system architecture, and code examples to implement the core logic. Python is the best choice for this due to its rich ecosystem in data processing, ML, and backend dev.
1. High-Level Architecture:
- Input: Search Queries + Code Snippets/Repository.
- Search Engine: The system being evaluated (e.g., ElasticSearch, specialized code search like Sourcegraph, or a custom vector DB).
- Evaluator Module:
- Offline: Benchmarking against labeled datasets (Relevancy Tests).
- Online: Tracking clicks, dwell time (Click Logs).
- Feedback Loop: Mechanism to update weights or re-train models.
2. Component Breakdown & Implementation Details:
-
Component A: Relevancy Tests (Offline Evaluation)
- Need a dataset: Query + [List of Code Files] + [Relevance Score (0-3)].
- Metric: NDCG (Normalized Discounted Cumulative Gain), Precision@K, MRR (Mean Reciprocal Rank). NDCG is best for graded relevance.
- Code: A Python class that takes search results and ground truth to calculate NDCG.
-
Component B: Click Logs (Online Evaluation)
- Need a way to simulate/capture events.
- Data structure:
{query_id, result_rank, clicked (bool), dwell_time}.
- Metric: Click-Through Rate (CTR), Dwell Time (Time spent on result).
- Code: A log parser/analyzer that calculates "Implicit Feedback".
-
Component C: Improvement Loops (The "Active Learning" aspect)
- How to use the data?
- Hard Negatives Mining: If users search "sort list" and click result #3 but not #1, maybe #1 is bad.
- Re-ranking: Use a Learning-to-Rank (LTR) model.
- Code: A simple optimization step that identifies "bad" results and adjusts a hypothetical score.
3. Structuring the Code Solution:
I'll create a Python project structure.
evaluator.py: The main logic.
metrics.py: Math for NDCG, MRR.
simulator.py: To demonstrate the loop working (generating fake queries/clicks).
4. Drafting the Code (Mental or scratchpad):
5. Putting it together into the final output:
- Introduction: Define the goal (improving code retrieval).
- Step 1: The Metrics (The Math): Show the NDCG implementation.
- Step 2: Click Log Analysis: Explain how to interpret clicks (propensity, position bias). I should implement a simple "Click Model" (e.g., Position-Based Model or just simple CTR correction).
- Step 3: The Evaluator System: A class that ties it all together.
- Step 4: The Loop: A script showing the cycle: Search -> Evaluate -> Log Clicks -> Update Model -> Repeat.
Self-Correction/Refinement during thought process:
- Critique: Just showing NDCG code is boring.
- Fix: Make it specific to Code Search. Use examples like "react hook useEffect" or "python read file".
- Critique: "Improvement Loop" is vague.
- Fix: Implement a simple Learning to Rank (LTR) simulation. I will create a mock search engine that scores documents. I will then show how to adjust the scoring weights based on user feedback.
Final Plan:
- Conceptual Overview: Explain NDCG, MRR, and Implicit Feedback.
- Python Implementation:
CodeSearchEvaluator class.
Metrics module.
ClickModel module.
Optimizer module.
- Usage Example: A simulation loop.
Let's write the code.
- NDCG Implementation:
DCG=∑i=1p
Let's build the system.
This is a comprehensive system design and Python implementation for a Code Search Quality Evaluator.
In the context of code search (e.g., searching a repository for a specific function), evaluation relies on two distinct data sources:
- Relevancy Tests (Explicit): Human-annotated datasets mapping queries to correct code files.
- Click Logs (Implicit): User behavior (clicks, dwell time) indicating utility.
The Improvement Loop ties these together to refine ranking algorithms (e.g., boosting specific features like document path or code complexity).
System Architecture
- Evaluation Layer: Calculates NDCG (Normalized Discounted Cumulative Gain) and MRR (Mean Reciprocal Rank).
- Analytics Layer: Parses click logs to calculate Click-Through Rate (CTR) and "Abandonment" rates.
- Feedback Loop: Identifies "Disagreements" (Low human score, High clicks) and optimizes the ranking scorer.
Python Implementation
We will build a simulation that demonstrates these components interacting.
1. Setup and Metrics
First, we need standard search evaluation metrics. We will use NDCG@K (ranking quality) and CTR (click-through rate).
import json
import math
import random
from collections import defaultdict
from dataclasses import dataclass, field
from typing import List, Dict, Tuple
# --- Data Structures ---
@dataclass
class CodeDocument:
id: str
file_path: str
code_snippet: str
# Features for ranking
bm25_score: float = 0.0
click_boost: float = 0.0
@dataclass
class SearchResult:
query: str
results: List[CodeDocument]
# "Gold Standard" relevance scores (0-3) provided by humans
relevance_grades: Dict[str, int] = field(default_factory=dict)
# --- Metrics Engine ---
class SearchMetrics:
@staticmethod
def dcg_score(relevance_scores: List[int], k: int) -> float:
"""Calculates DCG@K."""
score = 0.0
for i, rel in enumerate(relevance_scores[:k]):
# Using log2(i+2) because position is 1-based for log
score += (2**rel - 1) / math.log2(i + 2)
return score
@staticmethod
def calculate_ndcg(search_result: SearchResult, k: int = 10) -> float:
"""Calculates Normalized DCG@K."""
# Get actual relevance of retrieved docs
actual_rels = [search_result.relevance_grades.get(doc.id, 0)
for doc in search_result.results]
# Get ideal relevance (sorted all known relevant docs)
ideal_rels = sorted(search_result.relevance_grades.values(), reverse=True)
dcg = SearchMetrics.dcg_score(actual_rels, k)
idcg = SearchMetrics.dcg_score(ideal_rels, k)
return dcg / idcg if idcg > 0 else 0.0
@staticmethod
def calculate_ctr(click_logs: List[dict], position: int) -> float:
"""Calculates Click-Through Rate for a specific position."""
impressions = 0
clicks = 0
for log in click_logs:
if log['position'] == position:
impressions += 1
if log['clicked']:
clicks += 1
return clicks / impressions if impressions > 0 else 0.0
2. The Code Search Engine (Mock)
We simulate a search engine that can rank documents based on text matching (BM25) and an adjustable "Quality Weight" (derived from our feedback loop).
class CodeSearchEngine:
def __init__(self, index: List[CodeDocument]):
self.index = index
# Weight for text similarity vs behavioral signals
self.behavioral_weight = 0.3
def search(self, query: str) -> SearchResult:
"""Finds documents and ranks them."""
# 1. Retrieve (Mock BM25: check if query words in path/code)
candidates = []
for doc in self.index:
if query.lower() in doc.file_path.lower() or query.lower() in doc.code_snippet.lower():
# Simulate a raw text score
doc.bm25_score = random.uniform(0.5, 1.0)
candidates.append(doc)
# 2. Rank (Hybrid Score)
# Score = TextScore + (Weight * ClickBoost)
ranked = sorted(candidates, key=lambda d: d.bm25_score + (self.behavioral_weight * d.click_boost), reverse=True)
return SearchResult(query=query, results=ranked)
def update_boosts(self, doc_boosts: Dict[str, float]):
"""Apies feedback loop updates to the index."""
for doc in self.index:
if doc.id in doc_boosts:
doc.click_boost += doc_boosts[doc.id]
3. The Evaluation & Feedback System
This is the core logic. It compares Explicit tests (Human ratings) vs Implicit signals (Clicks) and decides how to update the system.
class SearchQualityEvaluator:
def __init__(self, engine: CodeSearchEngine):
self.engine = engine
self.click_logs = []
def run_relevancy_test(self, query: str, ground_truth: Dict[str, int]) -> Tuple[SearchResult, float]:
"""
Phase 1: Offline Evaluation.
Compares engine results against human annotated 'Gold Set'.
"""
result = self.engine.search(query)
# Attach ground truth to result object for metric calculation
result.relevance_grades = ground_truth
ndcg = SearchMetrics.calculate_ndcg(result, k=5)
return result, ndcg
def ingest_click_logs(self, logs: List[dict]):
"""
Phase 2: Online Evaluation.
Ingests user interaction data.
"""
self.click_logs.extend(logs)
def improvement_loop(self, search_result: SearchResult, ndcg_score: float):
"""
Phase 3: Analysis & Optimization.
Detects 'Relevance Drift' or 'Unpopular Good Results'.
"""
print(f"--- Running Improvement Loop (NDCG: {ndcg_score:.2f}) ---")
# Calculate CTR for the results we just got
performance_data = []
for i, doc in enumerate(search_result.results):
# Filter logs for this specific query and doc
doc_logs = [l for l in self.click_logs if l['doc_id'] == doc.id]
ctr = sum(1 for l in doc_logs if l['clicked']) / len(doc_logs) if doc_logs else 0
# Heuristic: If NDCG is low, but a specific doc has high CTR,
# the ranking might be wrong, but the content is good.
# OR: If a doc is highly relevant (Grade 3) but has low CTR,
# perhaps the title/snippet preview is bad.
is_relevant = search_result.relevance_grades.get(doc.id, 0) >= 2
if is_relevant and ctr < 0.1:
print(f"Alert: Doc {doc.id} is relevant but getting no clicks. Issue with Snippet Display?")
if not is_relevant and ctr > 0.5:
print(f"Alert: Doc {doc.id} is spam/irrelevant but getting clicks. Potential Clickbait or Query Mismatch.")
# Return a boost map: Reward clicked docs that are actually relevant
if is_relevant and ctr > 0.2:
performance_data.append((doc.id, 0.1)) # Boost score
# Apply updates to engine
updates = {doc_id: boost for doc_id, boost in performance_data}
self.engine.update_boosts(updates)
4. Running the Simulation
Here is the main execution flow demonstrating the system.
# --- Setup Data ---
docs = [
CodeDocument("1", "auth/login.py", "def handle_login(user, password): ..."),
CodeDocument("2", "utils/logger.py", "def log_error(message): ..."),
CodeDocument("3", "auth/oauth.py", "class OAuthManager: ..."),
CodeDocument("4", "tests/auth_test.py", "test_login_flow(): ..."),
]
# "Gold Standard": Humans say doc 1 and 3 are best for "login"
human_ground_truth = {
"1": 3, # Perfect match
"3": 2, # Related
"4": 1, # Tangential
"2": 0 # Irrelevant
}
# Initialize
engine = CodeSearchEngine(docs)
evaluator = SearchQualityEvaluator(engine)
# --- CYCLE 1: Initial Baseline ---
print("\n[CYCLE 1: Baseline]")
result, score = evaluator.run_relevancy_test("login", human_ground_truth)
print(f"Search Result Order: {[d.id for d in result.results]}")
print(f"Quality Score (NDCG): {score:.3f}")
# --- Simulate User Interaction (Click Logs) ---
# Scenario: Users ignore the top result (maybe it was ranked low due to random BM25)
# and click the second one (Doc 1) which is actually the best.
fake_logs = [
{'query': 'login', 'doc_id': '3', 'position': 1, 'clicked': False}, # User skipped this
{'query': 'login', 'doc_id': '1', 'position': 2, 'clicked': True}, # User clicked this
{'query': 'login', 'doc_id': '1', 'position': 2, 'clicked': True},
]
evaluator.ingest_click_logs(fake_logs)
# --- CYCLE 2: Improvement Loop ---
print("\n[CYCLE 2: Applying Feedback]")
# The evaluator analyzes logs and updates the engine weights
evaluator.improvement_loop(result, score)
# Re-run search to see if ranking improved
result_v2, score_v2 = evaluator.run_relevancy_test("login", human_ground_truth)
print(f"New Result Order: {[d.id for d in result_v2.results]}")
print(f"New Quality Score (NDCG): {score_v2:.3f}")
Key Concepts in this System
1. The Metrics
- NDCG (Normalized Discounted Cumulative Gain): The standard metric for search. It rewards finding relevant documents at the top of the list. It requires a "Gold Set" (Human judgment).
- Click Logs: We calculate CTR (Click Through Rate).
- High NDCG + High Clicks: The system is healthy.
- High NDCG + Low Clicks: The search results look bad to users (bad snippet/title formatting), even if they are technically correct.
- Low NDCG + High Clicks: Users are engaging with bad code (Security risk/Technical debt accumulation).
2. The Improvement Loop Logic
The improvement_loop function demonstrates Learning to Rank (LTR).
- We identified that Document 1 was highly relevant (Human score 3) and users clicked it often.
- We applied a
click_boost to Document 1 in the index.
- In Cycle 2, the search engine uses the formula:
Score = BM25 + (Weight * ClickBoost).
- This causes Document 1 to rank higher, increasing the NDCG score.
3. Real-World Considerations
To move this to production, you would add:
- Position Bias Correction: Users click the top result more often just because it's at the top. You need statistical models (like IPW - Inverse Propensity Weighting) to correct for this in the click log analysis.
- A/B Testing: Never deploy an improvement loop directly to 100% of traffic. Deploy the "Optimized" ranker to 10% of users and compare NDCG/Clicks against the Control group.
- Snippet Optimization: If NDCG is high but CTR is low, the problem isn't the ranking algorithm, it's how the code is displayed (e.g., highlighting the wrong lines).