Spaces:
Sleeping

Divb30 commited on
Commit
4d67f4e
·
1 Parent(s): feca47e

evaluation harness and benchmarks

Browse files

mrr, recall@k and ndcg for retrieval, precision/recall for the analyzer. baselines.json is the floor the eval has to stay above

eval/baselines.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_comment": "Pinned quality gates. CI fails if measured metrics drop below these floors. Set conservatively below observed values to avoid flakiness while still catching real regressions. Regenerate context with: python eval/run_benchmarks.py",
3
+ "retrieval_hybrid": {
4
+ "mrr_at_5": 0.85,
5
+ "recall_at_3": 0.92,
6
+ "ndcg_at_5": 0.88
7
+ },
8
+ "retrieval_reranked": {
9
+ "mrr_at_5": 0.95,
10
+ "recall_at_1": 0.92
11
+ },
12
+ "analyzer": {
13
+ "f1": 0.90,
14
+ "max_false_positives_on_clean": 0
15
+ }
16
+ }
eval/results/benchmark_results.json ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "search_mode": {
3
+ "dense_only": {
4
+ "mrr_at_5": 0.8833,
5
+ "recall_at_1": 0.8,
6
+ "recall_at_3": 0.96,
7
+ "recall_at_5": 1.0,
8
+ "ndcg_at_5": 0.9129,
9
+ "n_answerable": 25,
10
+ "negative_rejection_rate": 0.6,
11
+ "n_negative": 5
12
+ },
13
+ "hybrid": {
14
+ "mrr_at_5": 0.9067,
15
+ "recall_at_1": 0.84,
16
+ "recall_at_3": 1.0,
17
+ "recall_at_5": 1.0,
18
+ "ndcg_at_5": 0.9305,
19
+ "n_answerable": 25,
20
+ "negative_rejection_rate": 0.6,
21
+ "n_negative": 5
22
+ }
23
+ },
24
+ "reranking": {
25
+ "no_rerank": {
26
+ "mrr_at_5": 0.9067,
27
+ "recall_at_1": 0.84,
28
+ "recall_at_3": 1.0,
29
+ "recall_at_5": 1.0,
30
+ "ndcg_at_5": 0.9305,
31
+ "n_answerable": 25,
32
+ "negative_rejection_rate": 0.6,
33
+ "n_negative": 5
34
+ },
35
+ "with_rerank": {
36
+ "mrr_at_5": 1.0,
37
+ "recall_at_1": 1.0,
38
+ "recall_at_3": 1.0,
39
+ "recall_at_5": 1.0,
40
+ "ndcg_at_5": 1.0,
41
+ "n_answerable": 25,
42
+ "negative_rejection_rate": 0.6,
43
+ "n_negative": 5
44
+ }
45
+ },
46
+ "chunk_size": {
47
+ "128": {
48
+ "mrr_at_5": 0.8633,
49
+ "recall_at_1": 0.76,
50
+ "recall_at_3": 0.96,
51
+ "recall_at_5": 1.0,
52
+ "ndcg_at_5": 0.8982,
53
+ "n_answerable": 25,
54
+ "negative_rejection_rate": 0.6,
55
+ "n_negative": 5
56
+ },
57
+ "256": {
58
+ "mrr_at_5": 0.9067,
59
+ "recall_at_1": 0.84,
60
+ "recall_at_3": 1.0,
61
+ "recall_at_5": 1.0,
62
+ "ndcg_at_5": 0.9305,
63
+ "n_answerable": 25,
64
+ "negative_rejection_rate": 0.6,
65
+ "n_negative": 5
66
+ },
67
+ "512": {
68
+ "mrr_at_5": 0.93,
69
+ "recall_at_1": 0.88,
70
+ "recall_at_3": 0.96,
71
+ "recall_at_5": 1.0,
72
+ "ndcg_at_5": 0.9477,
73
+ "n_answerable": 25,
74
+ "negative_rejection_rate": 0.6,
75
+ "n_negative": 5
76
+ }
77
+ },
78
+ "chunking_method": {
79
+ "word_split": {
80
+ "mrr_at_5": 0.8933,
81
+ "recall_at_1": 0.8,
82
+ "recall_at_3": 1.0,
83
+ "recall_at_5": 1.0,
84
+ "ndcg_at_5": 0.9209,
85
+ "n_answerable": 25,
86
+ "negative_rejection_rate": 0.6,
87
+ "n_negative": 5
88
+ },
89
+ "sentence_aware": {
90
+ "mrr_at_5": 0.9067,
91
+ "recall_at_1": 0.84,
92
+ "recall_at_3": 1.0,
93
+ "recall_at_5": 1.0,
94
+ "ndcg_at_5": 0.9305,
95
+ "n_answerable": 25,
96
+ "negative_rejection_rate": 0.6,
97
+ "n_negative": 5
98
+ }
99
+ }
100
+ }
eval/results/benchmark_tables.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### Experiment 1 - Search mode (chunk=256, no rerank)
2
+
3
+ | Configuration | mrr_at_5 | recall_at_1 | recall_at_3 | ndcg_at_5 |
4
+ |---|---|---|---|---|
5
+ | Dense only | 0.883 | 0.800 | 0.960 | 0.913 |
6
+ | Hybrid (dense + BM25) | 0.907 | 0.840 | 1.000 | 0.930 |
7
+
8
+ ### Experiment 2 - Cross-encoder reranking (hybrid, chunk=256)
9
+
10
+ | Configuration | mrr_at_5 | recall_at_1 | recall_at_3 | ndcg_at_5 |
11
+ |---|---|---|---|---|
12
+ | Hybrid, no rerank | 0.907 | 0.840 | 1.000 | 0.930 |
13
+ | Hybrid + rerank | 1.000 | 1.000 | 1.000 | 1.000 |
14
+
15
+ ### Experiment 3 - Chunk size (hybrid, no rerank)
16
+
17
+ | Configuration | mrr_at_5 | recall_at_1 | recall_at_3 | ndcg_at_5 |
18
+ |---|---|---|---|---|
19
+ | 128 tokens | 0.863 | 0.760 | 0.960 | 0.898 |
20
+ | 256 tokens | 0.907 | 0.840 | 1.000 | 0.930 |
21
+ | 512 tokens | 0.930 | 0.880 | 0.960 | 0.948 |
22
+
23
+ ### Experiment 4 - Chunking method at matched size (hybrid, no rerank)
24
+
25
+ | Configuration | mrr_at_5 | recall_at_1 | recall_at_3 | ndcg_at_5 |
26
+ |---|---|---|---|---|
27
+ | Word-split (~256 tok) | 0.893 | 0.800 | 1.000 | 0.921 |
28
+ | Sentence-aware (256 tok) | 0.907 | 0.840 | 1.000 | 0.930 |
eval/run_benchmarks.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Comparative retrieval benchmarks for IntelliCode.
2
+
3
+ Runs four controlled experiments over the labeled evaluation set and prints
4
+ Markdown tables (also written to ``eval/results/``). Each experiment changes
5
+ exactly one variable so the effect is attributable.
6
+
7
+ Runs on CPU with embeddings + FAISS only. The reranking experiment downloads
8
+ a small cross-encoder (~90 MB) on first use.
9
+
10
+ Usage:
11
+ python eval/run_benchmarks.py
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import logging
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from intellicode.config import Settings
22
+ from intellicode.evaluation import evaluate_retrieval, load_corpus, load_dataset
23
+ from intellicode.rag import RAGPipeline
24
+
25
+ logging.disable(logging.CRITICAL) # keep benchmark output clean
26
+
27
+ ROOT = Path(__file__).resolve().parent.parent
28
+ DATASET = ROOT / "tests" / "eval" / "datasets" / "retrieval_eval.json"
29
+ CORPUS = ROOT / "tests" / "fixtures" / "documents"
30
+ RESULTS_DIR = ROOT / "eval" / "results"
31
+
32
+
33
+ def _run(settings: Settings, queries, docs, names, *, use_reranker: bool) -> dict[str, Any]:
34
+ """Build an index with *settings* and return its metrics dict."""
35
+ pipeline = RAGPipeline(settings)
36
+ pipeline.build_index(docs, names)
37
+ metrics = evaluate_retrieval(pipeline, queries, use_reranker=use_reranker)
38
+ return metrics.to_dict()
39
+
40
+
41
+ def _table(title: str, rows: list[tuple[str, dict[str, Any]]], columns: list[str]) -> str:
42
+ """Render a Markdown metrics table."""
43
+ header = "| Configuration | " + " | ".join(columns) + " |"
44
+ sep = "|" + "---|" * (len(columns) + 1)
45
+ lines = [f"### {title}", "", header, sep]
46
+ for label, metrics in rows:
47
+ cells = " | ".join(f"{metrics[c]:.3f}" if isinstance(metrics[c], float) else str(metrics[c]) for c in columns)
48
+ lines.append(f"| {label} | {cells} |")
49
+ return "\n".join(lines) + "\n"
50
+
51
+
52
+ def main() -> None:
53
+ """Run all benchmark experiments and write results."""
54
+ queries = load_dataset(DATASET)
55
+ docs, names = load_corpus(CORPUS)
56
+ print(f"Loaded {len(queries)} queries over {len(docs)} documents "
57
+ f"({sum(1 for q in queries if not q.expect_no_answer)} answerable).\n")
58
+
59
+ metric_cols = ["mrr_at_5", "recall_at_1", "recall_at_3", "ndcg_at_5"]
60
+ all_results: dict[str, Any] = {}
61
+
62
+ # ── Experiment 1: search mode ────────────────────────────────────────
63
+ dense = _run(Settings(use_reranker=False, use_hybrid_search=False), queries, docs, names, use_reranker=False)
64
+ hybrid = _run(Settings(use_reranker=False, use_hybrid_search=True), queries, docs, names, use_reranker=False)
65
+ exp1 = _table("Experiment 1 - Search mode (chunk=256, no rerank)",
66
+ [("Dense only", dense), ("Hybrid (dense + BM25)", hybrid)], metric_cols)
67
+ all_results["search_mode"] = {"dense_only": dense, "hybrid": hybrid}
68
+ print(exp1)
69
+
70
+ # ── Experiment 2: reranking ──────────────────────────────────────────
71
+ no_rerank = hybrid # reuse
72
+ with_rerank = _run(Settings(use_reranker=True, use_hybrid_search=True), queries, docs, names, use_reranker=True)
73
+ exp2 = _table("Experiment 2 - Cross-encoder reranking (hybrid, chunk=256)",
74
+ [("Hybrid, no rerank", no_rerank), ("Hybrid + rerank", with_rerank)], metric_cols)
75
+ all_results["reranking"] = {"no_rerank": no_rerank, "with_rerank": with_rerank}
76
+ print(exp2)
77
+
78
+ # ── Experiment 3: chunk size ─────────────────────────────────────────
79
+ chunk_rows = []
80
+ all_results["chunk_size"] = {}
81
+ for size in (128, 256, 512):
82
+ overlap = size // 4
83
+ m = _run(
84
+ Settings(use_reranker=False, use_hybrid_search=True, chunk_size=size, chunk_overlap=overlap),
85
+ queries, docs, names, use_reranker=False,
86
+ )
87
+ chunk_rows.append((f"{size} tokens", m))
88
+ all_results["chunk_size"][str(size)] = m
89
+ exp3 = _table("Experiment 3 - Chunk size (hybrid, no rerank)", chunk_rows, metric_cols)
90
+ print(exp3)
91
+
92
+ # ── Experiment 4: chunking method (matched ~256-token size) ──────────
93
+ # Hold chunk size roughly constant so the comparison isolates *method*,
94
+ # not size: ~190 words ≈ 256 tokens.
95
+ word = _run(
96
+ Settings(use_reranker=False, use_hybrid_search=True, chunking_strategy="word", chunk_size=190, chunk_overlap=48),
97
+ queries, docs, names, use_reranker=False,
98
+ )
99
+ sentence = hybrid # sentence-aware @256 from experiment 1
100
+ exp4 = _table("Experiment 4 - Chunking method at matched size (hybrid, no rerank)",
101
+ [("Word-split (~256 tok)", word), ("Sentence-aware (256 tok)", sentence)], metric_cols)
102
+ all_results["chunking_method"] = {"word_split": word, "sentence_aware": sentence}
103
+ print(exp4)
104
+
105
+ # ── Persist ──────────────────────────────────────────────────────────
106
+ RESULTS_DIR.mkdir(parents=True, exist_ok=True)
107
+ (RESULTS_DIR / "benchmark_results.json").write_text(
108
+ json.dumps(all_results, indent=2), encoding="utf-8"
109
+ )
110
+ (RESULTS_DIR / "benchmark_tables.md").write_text(
111
+ "\n".join([exp1, exp2, exp3, exp4]), encoding="utf-8"
112
+ )
113
+ print(f"Results written to {RESULTS_DIR}")
114
+
115
+
116
+ if __name__ == "__main__":
117
+ main()
src/intellicode/evaluation.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Retrieval evaluation metrics and harness.
2
+
3
+ Relevance is defined by *answer spans*: a retrieved chunk is relevant if its
4
+ text contains at least one of a query's gold answer spans (case-insensitive
5
+ substring match). This keeps the labels robust to changes in chunking — no
6
+ brittle chunk-ID bookkeeping — while still measuring whether the answer-bearing
7
+ passage was retrieved and ranked highly.
8
+
9
+ All metrics run on embeddings + FAISS only: no GPU, no API keys.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import math
16
+ import re
17
+ from dataclasses import dataclass, field
18
+ from pathlib import Path
19
+ from typing import TYPE_CHECKING, Any
20
+
21
+ if TYPE_CHECKING:
22
+ from intellicode.analysis.code_analyzer import CodeAnalyzer
23
+ from intellicode.rag.pipeline import RAGPipeline
24
+ from intellicode.rag.retriever import RetrievalResult
25
+
26
+
27
+ # ── Relevance predicate ──────────────────────────────────────────────────────
28
+
29
+
30
+ def is_relevant(chunk_text: str, answer_spans: list[str]) -> bool:
31
+ """Return True if *chunk_text* contains any of *answer_spans* (case-insensitive)."""
32
+ haystack = chunk_text.lower()
33
+ return any(span.lower() in haystack for span in answer_spans)
34
+
35
+
36
+ # ── Ranking metrics ──────────────────────────────────────────────────────────
37
+
38
+
39
+ def reciprocal_rank(results: list[RetrievalResult], answer_spans: list[str]) -> float:
40
+ """Reciprocal rank of the first relevant result (0 if none)."""
41
+ for rank, r in enumerate(results, start=1):
42
+ if is_relevant(r.text, answer_spans):
43
+ return 1.0 / rank
44
+ return 0.0
45
+
46
+
47
+ def recall_at_k(results: list[RetrievalResult], answer_spans: list[str], k: int) -> float:
48
+ """1.0 if a relevant chunk appears in the top *k*, else 0.0."""
49
+ return 1.0 if any(is_relevant(r.text, answer_spans) for r in results[:k]) else 0.0
50
+
51
+
52
+ def ndcg_at_k(results: list[RetrievalResult], answer_spans: list[str], k: int) -> float:
53
+ """Binary NDCG@k with a single ideal relevant document.
54
+
55
+ With binary relevance and one ideal hit, the ideal DCG is 1, so NDCG@k
56
+ reduces to ``1 / log2(rank + 1)`` for the first relevant result within *k*.
57
+ """
58
+ for rank, r in enumerate(results[:k], start=1):
59
+ if is_relevant(r.text, answer_spans):
60
+ return 1.0 / math.log2(rank + 1)
61
+ return 0.0
62
+
63
+
64
+ # ── Dataset loading ──────────────────────────────────────────────────────────
65
+
66
+
67
+ @dataclass
68
+ class EvalQuery:
69
+ """A single labeled evaluation query."""
70
+
71
+ id: str
72
+ category: str
73
+ query: str
74
+ answer_spans: list[str]
75
+ expect_no_answer: bool = False
76
+
77
+
78
+ def load_dataset(path: str | Path) -> list[EvalQuery]:
79
+ """Load the retrieval evaluation dataset from a JSON file."""
80
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
81
+ return [
82
+ EvalQuery(
83
+ id=q["id"],
84
+ category=q["category"],
85
+ query=q["query"],
86
+ answer_spans=q.get("answer_spans", []),
87
+ expect_no_answer=q.get("expect_no_answer", False),
88
+ )
89
+ for q in data["queries"]
90
+ ]
91
+
92
+
93
+ def load_corpus(corpus_dir: str | Path) -> tuple[list[str], list[str]]:
94
+ """Load all ``.txt`` documents in *corpus_dir*.
95
+
96
+ Returns:
97
+ A ``(documents, filenames)`` tuple.
98
+ """
99
+ docs: list[str] = []
100
+ names: list[str] = []
101
+ for fp in sorted(Path(corpus_dir).glob("*.txt")):
102
+ docs.append(fp.read_text(encoding="utf-8"))
103
+ names.append(fp.name)
104
+ return docs, names
105
+
106
+
107
+ # ── Evaluation harness ───────────────────────────────────────────────────────
108
+
109
+
110
+ @dataclass
111
+ class RetrievalMetrics:
112
+ """Aggregate retrieval metrics over an evaluation set."""
113
+
114
+ mrr_at_5: float
115
+ recall_at_1: float
116
+ recall_at_3: float
117
+ recall_at_5: float
118
+ ndcg_at_5: float
119
+ n_answerable: int
120
+ negative_rejection_rate: float = 0.0
121
+ n_negative: int = 0
122
+
123
+ def to_dict(self) -> dict[str, Any]:
124
+ return {
125
+ "mrr_at_5": round(self.mrr_at_5, 4),
126
+ "recall_at_1": round(self.recall_at_1, 4),
127
+ "recall_at_3": round(self.recall_at_3, 4),
128
+ "recall_at_5": round(self.recall_at_5, 4),
129
+ "ndcg_at_5": round(self.ndcg_at_5, 4),
130
+ "n_answerable": self.n_answerable,
131
+ "negative_rejection_rate": round(self.negative_rejection_rate, 4),
132
+ "n_negative": self.n_negative,
133
+ }
134
+
135
+
136
+ def evaluate_retrieval(
137
+ pipeline: RAGPipeline,
138
+ queries: list[EvalQuery],
139
+ *,
140
+ top_k: int = 5,
141
+ use_reranker: bool | None = None,
142
+ negative_threshold: float = 0.35,
143
+ ) -> RetrievalMetrics:
144
+ """Evaluate a built *pipeline* against labeled *queries*.
145
+
146
+ Answerable queries contribute to MRR / Recall / NDCG. Negative queries
147
+ contribute to the *negative rejection rate*: the fraction whose top raw
148
+ dense similarity falls below *negative_threshold* (i.e. correctly treated
149
+ as "no confident answer").
150
+
151
+ Args:
152
+ pipeline: A :class:`RAGPipeline` with an index already built.
153
+ queries: Labeled evaluation queries.
154
+ top_k: Cutoff for the @k metrics.
155
+ use_reranker: Force reranking on/off (defaults to pipeline config).
156
+ negative_threshold: Dense-similarity cutoff for negative rejection.
157
+
158
+ Returns:
159
+ Aggregated :class:`RetrievalMetrics`.
160
+ """
161
+ answerable = [q for q in queries if not q.expect_no_answer]
162
+ negatives = [q for q in queries if q.expect_no_answer]
163
+
164
+ rr = r1 = r3 = r5 = ndcg = 0.0
165
+ for q in answerable:
166
+ results = pipeline.query(q.query, top_k=top_k, use_reranker=use_reranker)
167
+ rr += reciprocal_rank(results, q.answer_spans)
168
+ r1 += recall_at_k(results, q.answer_spans, 1)
169
+ r3 += recall_at_k(results, q.answer_spans, 3)
170
+ r5 += recall_at_k(results, q.answer_spans, 5)
171
+ ndcg += ndcg_at_k(results, q.answer_spans, 5)
172
+
173
+ n = max(1, len(answerable))
174
+
175
+ # Negative rejection: use raw dense similarity (comparable across queries).
176
+ rejected = 0
177
+ for q in negatives:
178
+ dense = pipeline.retriever.retrieve(q.query, top_k=1, use_hybrid=False)
179
+ top_score = dense[0].score if dense else 0.0
180
+ if top_score < negative_threshold:
181
+ rejected += 1
182
+ neg_rate = rejected / len(negatives) if negatives else 0.0
183
+
184
+ return RetrievalMetrics(
185
+ mrr_at_5=rr / n,
186
+ recall_at_1=r1 / n,
187
+ recall_at_3=r3 / n,
188
+ recall_at_5=r5 / n,
189
+ ndcg_at_5=ndcg / n,
190
+ n_answerable=len(answerable),
191
+ negative_rejection_rate=neg_rate,
192
+ n_negative=len(negatives),
193
+ )
194
+
195
+
196
+ # ── Analyzer accuracy evaluation ─────────────────────────────────────────────
197
+
198
+ # Anti-pattern classes scored by the analyzer benchmark. The stylistic
199
+ # "Missing return type hint" check is excluded — it fires on every un-hinted
200
+ # function and would dominate the counts without signalling detection quality.
201
+ ANALYZER_TARGET_CLASSES: frozenset[str] = frozenset(
202
+ {
203
+ "Mutable default argument",
204
+ "Bare except clause",
205
+ "Broad exception handler",
206
+ "Unused variable",
207
+ "Deep nesting",
208
+ "High cyclomatic complexity",
209
+ "Global statement",
210
+ "Assert in production code",
211
+ "Long function",
212
+ }
213
+ )
214
+
215
+ _EXPECT_RE = re.compile(r"#\s*EXPECT:\s*(.+?)\s*$")
216
+
217
+
218
+ def parse_expect_markers(path: str | Path) -> set[tuple[int, str]]:
219
+ """Extract ``(line, issue_type)`` ground-truth pairs from ``# EXPECT:`` markers."""
220
+ ground_truth: set[tuple[int, str]] = set()
221
+ for lineno, line in enumerate(Path(path).read_text(encoding="utf-8").splitlines(), start=1):
222
+ match = _EXPECT_RE.search(line)
223
+ if match:
224
+ ground_truth.add((lineno, match.group(1).strip()))
225
+ return ground_truth
226
+
227
+
228
+ def analyzer_detections(
229
+ analyzer: CodeAnalyzer,
230
+ path: str | Path,
231
+ target_classes: frozenset[str],
232
+ ) -> set[tuple[int, str]]:
233
+ """Run *analyzer* on *path* and return ``(line, type)`` pairs for target classes."""
234
+ result = analyzer.analyze_file(str(path))
235
+ return {
236
+ (issue.line, issue.type)
237
+ for issue in result.issues
238
+ if issue.type in target_classes
239
+ }
240
+
241
+
242
+ @dataclass
243
+ class AnalyzerMetrics:
244
+ """Precision/recall/F1 for the analyzer, with per-class breakdown."""
245
+
246
+ precision: float
247
+ recall: float
248
+ f1: float
249
+ true_positives: int
250
+ false_positives: int
251
+ false_negatives: int
252
+ false_positives_on_clean: int
253
+ per_class: dict[str, dict[str, int]] = field(default_factory=dict)
254
+
255
+ def to_dict(self) -> dict[str, Any]:
256
+ return {
257
+ "precision": round(self.precision, 4),
258
+ "recall": round(self.recall, 4),
259
+ "f1": round(self.f1, 4),
260
+ "true_positives": self.true_positives,
261
+ "false_positives": self.false_positives,
262
+ "false_negatives": self.false_negatives,
263
+ "false_positives_on_clean": self.false_positives_on_clean,
264
+ "per_class": self.per_class,
265
+ }
266
+
267
+
268
+ def evaluate_analyzer(
269
+ analyzer: CodeAnalyzer,
270
+ buggy_path: str | Path,
271
+ clean_path: str | Path | None = None,
272
+ *,
273
+ target_classes: frozenset[str] = ANALYZER_TARGET_CLASSES,
274
+ ) -> AnalyzerMetrics:
275
+ """Measure analyzer precision/recall against ``# EXPECT`` markers.
276
+
277
+ Recall and precision are computed on *buggy_path* by matching detected
278
+ ``(line, type)`` pairs against the file's markers. If *clean_path* is
279
+ given, any target-class detection there is counted as a false positive
280
+ (a well-written file should produce none).
281
+
282
+ Args:
283
+ analyzer: The analyzer under test.
284
+ buggy_path: Fixture annotated with ``# EXPECT:`` markers.
285
+ clean_path: Optional clean fixture expected to yield zero findings.
286
+ target_classes: Issue types included in scoring.
287
+
288
+ Returns:
289
+ Aggregated :class:`AnalyzerMetrics`.
290
+ """
291
+ ground_truth = {(ln, t) for ln, t in parse_expect_markers(buggy_path) if t in target_classes}
292
+ detected = analyzer_detections(analyzer, buggy_path, target_classes)
293
+
294
+ tp = len(ground_truth & detected)
295
+ fn = len(ground_truth - detected)
296
+ fp = len(detected - ground_truth)
297
+
298
+ fp_clean = 0
299
+ if clean_path is not None:
300
+ fp_clean = len(analyzer_detections(analyzer, clean_path, target_classes))
301
+
302
+ total_fp = fp + fp_clean
303
+ precision = tp / (tp + total_fp) if (tp + total_fp) else 1.0
304
+ recall = tp / (tp + fn) if (tp + fn) else 1.0
305
+ f1 = 2 * precision * recall / (precision + recall) if (precision + recall) else 0.0
306
+
307
+ # Per-class recall breakdown
308
+ per_class: dict[str, dict[str, int]] = {}
309
+ for cls in sorted(target_classes):
310
+ gt_cls = {p for p in ground_truth if p[1] == cls}
311
+ det_cls = {p for p in detected if p[1] == cls}
312
+ if gt_cls or det_cls:
313
+ per_class[cls] = {
314
+ "expected": len(gt_cls),
315
+ "detected": len(gt_cls & det_cls),
316
+ "false_positive": len(det_cls - gt_cls),
317
+ }
318
+
319
+ return AnalyzerMetrics(
320
+ precision=precision,
321
+ recall=recall,
322
+ f1=f1,
323
+ true_positives=tp,
324
+ false_positives=fp,
325
+ false_negatives=fn,
326
+ false_positives_on_clean=fp_clean,
327
+ per_class=per_class,
328
+ )
tests/fixtures/documents/api_reference.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ TechCorp Platform API Reference
2
+
3
+ The TechCorp Platform API is a RESTful interface for programmatic access to CloudSync Pro and the AI Assistant Platform. All endpoints are served over HTTPS from the base URL api.techcorp.example slash v2.
4
+
5
+ Authentication
6
+ The API uses bearer token authentication. Every request must include an Authorization header containing a valid API key in the form "Bearer YOUR_API_KEY". API keys are issued from the developer dashboard and can be scoped to specific permissions. Keys can be rotated at any time, and a revoked key stops working immediately.
7
+
8
+ Rate Limits
9
+ The API enforces a rate limit of 1000 requests per minute for standard accounts and 5000 requests per minute for enterprise accounts. When a client exceeds the limit, the API responds with HTTP status code 429 and a Retry-After header indicating how many seconds to wait. Clients are expected to implement exponential backoff.
10
+
11
+ Core Endpoints
12
+ The GET slash files endpoint lists files in a CloudSync workspace. The POST slash files endpoint uploads a new file. The GET slash files slash id endpoint retrieves metadata for a specific file. The DELETE slash files slash id endpoint moves a file to the recovery bin. The POST slash assistant slash query endpoint sends a prompt to the AI Assistant Platform and returns a generated response.
13
+
14
+ Pagination
15
+ List endpoints return at most 100 items per page. Responses include a next_cursor field. To retrieve the next page, pass the cursor value in the cursor query parameter. When next_cursor is null, there are no more results.
16
+
17
+ Error Handling
18
+ The API returns standard HTTP status codes. A 400 indicates a malformed request, a 401 indicates an invalid or missing API key, a 403 indicates insufficient permissions, and a 404 indicates a missing resource. Error responses include a JSON body with an error code and a human-readable message.
19
+
20
+ Webhooks
21
+ The API can deliver webhooks for events such as file uploads and completed assistant jobs. Webhook payloads are signed with an HMAC-SHA256 signature in the X-TechCorp-Signature header, which clients should verify before trusting the payload.
22
+
23
+ Versioning
24
+ The current API version is v2. The previous version, v1, is deprecated and will reach end of life in December 2025. Breaking changes are only introduced in new major versions, and TechCorp provides at least twelve months of notice before retiring a version.
tests/fixtures/documents/cloudsync_product.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CloudSync Pro — Product Documentation
2
+
3
+ CloudSync Pro is TechCorp's enterprise file storage and synchronization platform. It provides secure, cross-device file access with automatic conflict resolution and versioning.
4
+
5
+ Storage Tiers
6
+ CloudSync Pro is offered in three tiers. The Starter tier includes 1 terabyte of storage and supports up to 10 users. The Business tier includes 10 terabytes and supports up to 250 users. The Enterprise tier offers unlimited storage with custom user provisioning and a dedicated account manager.
7
+
8
+ Encryption and Security
9
+ All files stored in CloudSync Pro are encrypted at rest using AES-256 encryption. Data in transit is protected with TLS 1.3. CloudSync Pro supports client-side encryption, meaning files can be encrypted on the user's device before upload, so that TechCorp never has access to the plaintext contents. Encryption keys can be managed by the customer through the bring-your-own-key feature.
10
+
11
+ Versioning and Recovery
12
+ CloudSync Pro retains up to 100 previous versions of every file. Deleted files are kept in a recovery bin for 30 days before permanent removal. Administrators can configure legal hold policies that prevent deletion of specific files or folders for compliance purposes.
13
+
14
+ Synchronization
15
+ The synchronization engine uses a block-level delta algorithm, meaning only the changed portions of a file are uploaded rather than the entire file. This makes CloudSync Pro efficient for large files that change frequently, such as design assets and virtual machine images. Selective sync allows users to choose which folders are downloaded to each device.
16
+
17
+ Integrations
18
+ CloudSync Pro integrates with Microsoft 365, Google Workspace, and Slack. A REST API is available for custom integrations. Single sign-on is supported through SAML 2.0 and OpenID Connect.
19
+
20
+ Pricing
21
+ The Starter tier costs 12 dollars per user per month. The Business tier costs 22 dollars per user per month. Enterprise pricing is custom and negotiated per contract. A 14-day free trial is available for the Starter and Business tiers.
tests/fixtures/documents/company_overview.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ TechCorp Solutions — Company Overview
2
+
3
+ TechCorp Solutions is a leading enterprise software company founded in 2010 by Elena Marlowe and Raj Patel. The company is headquartered in San Francisco, California, with additional engineering offices in New York and London. TechCorp specializes in artificial intelligence, cloud infrastructure, and enterprise data platforms.
4
+
5
+ Products
6
+ TechCorp offers three flagship products. CloudSync Pro is an enterprise cloud storage and synchronization solution with end-to-end encryption. The AI Assistant Platform is a customizable framework for building domain-specific chatbots and virtual agents. DataViz Suite is a business intelligence toolkit for real-time analytics and dashboard creation.
7
+
8
+ Team and Culture
9
+ As of 2024, TechCorp employs more than 320 people worldwide, of whom roughly 180 are engineers. The company operates on a hybrid work model, with employees expected in the office three days per week. TechCorp is known for its strong engineering culture and its internal "Ship Weekly" philosophy, which encourages small, frequent releases over large quarterly launches.
10
+
11
+ Funding and Financials
12
+ TechCorp raised a Series C round of 85 million dollars in 2022, led by Horizon Ventures. Annual recurring revenue crossed 120 million dollars in fiscal year 2023. The company has been profitable since the fourth quarter of 2023.
13
+
14
+ Awards and Recognition
15
+ TechCorp was named Best AI Solution Provider in 2023 by the Enterprise Software Awards. It received the Top Cloud Services Company award in 2022 and an Innovation Award in Enterprise Software in 2021. The DataViz Suite was recognized as Product of the Year by Analytics Weekly in 2023.
16
+
17
+ Contact
18
+ General inquiries can be directed to info@techcorp.example. The support hotline operates Monday through Friday, 9 AM to 6 PM Pacific Time. TechCorp's registered office is located at 500 Market Street, San Francisco, California.
tests/fixtures/documents/engineering_handbook.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ TechCorp Engineering Handbook
2
+
3
+ This handbook describes the engineering practices, technology choices, and operational standards used across TechCorp's engineering organization.
4
+
5
+ Technology Stack
6
+ TechCorp's backend services are written primarily in Python and Go. Python is used for data processing, machine learning pipelines, and internal tooling, while Go is used for high-throughput network services. The primary database is PostgreSQL, with Redis used for caching and ephemeral state. Message queues are built on Apache Kafka.
7
+
8
+ Deployment and Infrastructure
9
+ All services run on Kubernetes clusters hosted on Amazon Web Services. Infrastructure is managed with Terraform, and configuration follows an infrastructure-as-code discipline. Deployments use a blue-green strategy to minimize downtime. Every production deployment must pass an automated test suite and a staged canary rollout before reaching all users.
10
+
11
+ Code Review Policy
12
+ Every change to production code requires review and approval from at least one other engineer. Changes to security-sensitive systems require two approvals, one of which must come from a member of the security team. Pull requests are expected to remain under 400 lines of changed code to keep reviews tractable.
13
+
14
+ Testing Standards
15
+ TechCorp requires a minimum of 80 percent test coverage for all backend services. Engineers write unit tests, integration tests, and end-to-end tests. Continuous integration runs the full test suite on every pull request, and a failing test blocks the merge. Load testing is performed before any major release.
16
+
17
+ On-Call and Incident Response
18
+ Engineering teams operate a follow-the-sun on-call rotation. When an incident occurs, the on-call engineer becomes the incident commander until the issue is resolved. Every incident is followed by a blameless postmortem within five business days. The postmortem focuses on systemic causes rather than individual blame.
19
+
20
+ Observability
21
+ All services emit structured logs in JSON format and export metrics to Prometheus. Distributed tracing is implemented with OpenTelemetry. Dashboards are built in Grafana, and alerts route through PagerDuty. The engineering standard is that any user-facing error rate above one percent triggers an automatic alert.
tests/fixtures/documents/security_policy.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ TechCorp Security and Compliance Policy
2
+
3
+ This document describes TechCorp's security practices, compliance certifications, and data handling commitments.
4
+
5
+ Compliance Certifications
6
+ TechCorp maintains SOC 2 Type II certification, which is audited annually by an independent third party. The company is also compliant with the General Data Protection Regulation for European customers and the California Consumer Privacy Act. CloudSync Pro has achieved ISO 27001 certification for information security management.
7
+
8
+ Data Residency
9
+ Customers can choose where their data is stored. TechCorp operates data centers in the United States, the European Union, and Australia. Enterprise customers can request that all their data remain within a specific region to satisfy data residency requirements. Data is never transferred outside the selected region without explicit customer consent.
10
+
11
+ Password and Authentication Policy
12
+ User passwords must be at least twelve characters long and are hashed using the bcrypt algorithm with a work factor of twelve. Multi-factor authentication is required for all administrative accounts and is strongly recommended for all users. TechCorp supports hardware security keys based on the FIDO2 standard.
13
+
14
+ Vulnerability Management
15
+ TechCorp runs automated vulnerability scans on all production systems weekly. A dedicated security team performs manual penetration testing quarterly. The company operates a bug bounty program through which external researchers can report vulnerabilities in exchange for monetary rewards. Critical vulnerabilities are patched within 24 hours of confirmation.
16
+
17
+ Incident Notification
18
+ In the event of a data breach affecting customer data, TechCorp commits to notifying affected customers within 72 hours of confirming the breach. Notifications include the nature of the breach, the data involved, and the remediation steps taken.
19
+
20
+ Employee Access
21
+ Employee access to customer data follows the principle of least privilege. Access to production systems requires multi-factor authentication and is logged and audited. All employees complete mandatory security training annually, and access rights are reviewed every quarter.
22
+
23
+ Backups and Disaster Recovery
24
+ Customer data is backed up continuously, with point-in-time recovery available for the previous 35 days. TechCorp maintains a recovery time objective of four hours and a recovery point objective of fifteen minutes for its core services. Disaster recovery drills are conducted twice per year.
tests/fixtures/sample_buggy_code.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ground-truth fixture for the AST analyzer accuracy benchmark.
2
+
3
+ Each anti-pattern is annotated with an ``# EXPECT: <Issue.type>`` marker on the
4
+ exact line the analyzer reports it (the ``def``/statement line). The analyzer
5
+ accuracy eval parses these markers to build ground truth, so this file's
6
+ markers and the analyzer's output must stay in agreement.
7
+
8
+ This module is intentionally NOT imported or executed — it only exists to be
9
+ parsed. Do not "fix" the anti-patterns below.
10
+ """
11
+
12
+ import hashlib # noqa: F401 — used by an intentional weak-crypto example elsewhere
13
+
14
+
15
+ def append_item(item, bucket=[]): # EXPECT: Mutable default argument
16
+ """Mutable default argument shared across calls."""
17
+ bucket.append(item)
18
+ return bucket
19
+
20
+
21
+ def swallow_everything():
22
+ """Bare except that hides all errors."""
23
+ try:
24
+ risky = 1 / 0
25
+ return risky
26
+ except: # EXPECT: Bare except clause
27
+ pass
28
+
29
+
30
+ def over_broad_handler():
31
+ """Catches Exception, which is too broad."""
32
+ try:
33
+ return compute()
34
+ except Exception: # EXPECT: Broad exception handler
35
+ return None
36
+
37
+
38
+ def has_unused_variable():
39
+ """Assigns a variable that is never read."""
40
+ leftover = compute_total() # EXPECT: Unused variable
41
+ return 42
42
+
43
+
44
+ def deeply_nested(data): # EXPECT: Deep nesting
45
+ """Four levels of control-flow nesting."""
46
+ out = []
47
+ for item in data:
48
+ if item > 0:
49
+ if item < 100:
50
+ if item % 2 == 0:
51
+ out.append(item)
52
+ return out
53
+
54
+
55
+ def tangled_logic(a, b, c, d, e): # EXPECT: High cyclomatic complexity
56
+ """Many branches → high cyclomatic complexity."""
57
+ total = 0
58
+ if a > 0:
59
+ total += 1
60
+ if b > 0:
61
+ total += 1
62
+ if c > 0 and d > 0:
63
+ total += 1
64
+ if e > 0 or a > b:
65
+ total += 1
66
+ for i in range(a):
67
+ if i % 2 == 0:
68
+ total += i
69
+ elif i % 3 == 0:
70
+ total -= i
71
+ while total > 100:
72
+ total -= 10
73
+ return total
74
+
75
+
76
+ def uses_global():
77
+ """Mutates module-level state via global."""
78
+ global _counter # EXPECT: Global statement
79
+ _counter += 1
80
+
81
+
82
+ def uses_assert(value):
83
+ """Relies on assert for validation (stripped under -O)."""
84
+ assert value > 0 # EXPECT: Assert in production code
85
+ return value * 2
86
+
87
+
88
+ def long_function(x): # EXPECT: Long function
89
+ """A function padded past the long-function threshold (>50 lines)."""
90
+ s = x
91
+ s = s + 1
92
+ s = s + 2
93
+ s = s + 3
94
+ s = s + 4
95
+ s = s + 5
96
+ s = s + 6
97
+ s = s + 7
98
+ s = s + 8
99
+ s = s + 9
100
+ s = s + 10
101
+ s = s + 11
102
+ s = s + 12
103
+ s = s + 13
104
+ s = s + 14
105
+ s = s + 15
106
+ s = s + 16
107
+ s = s + 17
108
+ s = s + 18
109
+ s = s + 19
110
+ s = s + 20
111
+ s = s + 21
112
+ s = s + 22
113
+ s = s + 23
114
+ s = s + 24
115
+ s = s + 25
116
+ s = s + 26
117
+ s = s + 27
118
+ s = s + 28
119
+ s = s + 29
120
+ s = s + 30
121
+ s = s + 31
122
+ s = s + 32
123
+ s = s + 33
124
+ s = s + 34
125
+ s = s + 35
126
+ s = s + 36
127
+ s = s + 37
128
+ s = s + 38
129
+ s = s + 39
130
+ s = s + 40
131
+ s = s + 41
132
+ s = s + 42
133
+ s = s + 43
134
+ s = s + 44
135
+ s = s + 45
136
+ s = s + 46
137
+ s = s + 47
138
+ s = s + 48
139
+ s = s + 49
140
+ s = s + 50
141
+ s = s + 51
142
+ s = s + 52
143
+ s = s + 53
144
+ s = s + 54
145
+ s = s + 55
146
+ return s
147
+
148
+
149
+ async def async_mutable(items={}): # EXPECT: Mutable default argument
150
+ """Async function with a mutable default — exercises AsyncFunctionDef support."""
151
+ items["seen"] = True
152
+ return items
153
+
154
+
155
+ def compute():
156
+ """Helper referenced above; return-hinted to avoid incidental findings."""
157
+ return 1
158
+
159
+
160
+ def compute_total():
161
+ """Helper referenced above."""
162
+ return 0
163
+
164
+
165
+ _counter = 0
tests/fixtures/sample_clean_code.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Clean-code fixture for the analyzer false-positive-rate benchmark.
2
+
3
+ This module is intentionally well-written: fully type-hinted public functions,
4
+ no mutable defaults, specific exception handling, no globals, no bare asserts,
5
+ and shallow nesting. The analyzer should report zero target-class issues here.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+
11
+ def add(a: int, b: int) -> int:
12
+ """Return the sum of two integers."""
13
+ return a + b
14
+
15
+
16
+ def safe_divide(numerator: float, denominator: float) -> float | None:
17
+ """Divide two numbers, returning None on division by zero."""
18
+ try:
19
+ return numerator / denominator
20
+ except ZeroDivisionError:
21
+ return None
22
+
23
+
24
+ def accumulate(items: list[int] | None = None) -> list[int]:
25
+ """Append to a fresh list, avoiding the mutable-default pitfall."""
26
+ if items is None:
27
+ items = []
28
+ items.append(0)
29
+ return items
30
+
31
+
32
+ def categorize(value: int) -> str:
33
+ """Classify a value using flat guard clauses instead of deep nesting."""
34
+ if value < 0:
35
+ return "negative"
36
+ if value == 0:
37
+ return "zero"
38
+ return "positive"
39
+
40
+
41
+ def validate_positive(value: int) -> int:
42
+ """Validate input by raising an explicit exception (not assert)."""
43
+ if value <= 0:
44
+ raise ValueError("value must be positive")
45
+ return value
46
+
47
+
48
+ class Counter:
49
+ """A small stateful helper that avoids global state."""
50
+
51
+ def __init__(self) -> None:
52
+ self._count = 0
53
+
54
+ def increment(self) -> int:
55
+ """Increment the counter and return the new value."""
56
+ self._count += 1
57
+ return self._count