Show recall against false positive rate

#30
README.md CHANGED
@@ -29,21 +29,21 @@ Pairs come from open-source projects in Rust, JavaScript, TypeScript, Python, Go
29
 
30
  ## Reading the results
31
 
32
- Each line shows recall minus the false-positive rate as the score cutoff changes. Higher is better; farther left means fewer clean methods flagged. The dashed zero line means issues and clean methods are flagged at equal rates.
33
 
34
- The tables use each run's recorded alert settings. A value of 20% under ‘Clean methods wrongly flagged’ means one in five clean methods received an alert. Models are ranked by recall minus that percentage. Bold marks the best full-set value in each column; cost compares priced runs captured here.
35
 
36
- Failed requests count as incorrect decisions: a failed issue is a miss; a failed clean method is a false positive. Failed cases receive no model score and remain incorrect across the plotted cutoffs.
37
 
38
  ## Bugs
39
 
40
  [Public pairs](https://huggingface.co/datasets/perchscan/bug-pairs-public)
41
 
42
- ![Bugs: recall minus false-positive rate across cutoffs](assets/bug-tradeoff.svg)
43
 
44
  ### Public — 2,220 pairs
45
 
46
- | Model | Recall | Clean methods wrongly flagged | Recall − false-positive rate | Failed requests | Inference cost |
47
  | --- | ---: | ---: | ---: | ---: | ---: |
48
  | [GPT-6 Luna Decisions](https://developers.openai.com/api/docs/guides/decisions) | 48.7% | 38.7% | **10.0%** | **0** | $1.102 |
49
  | [DiffusionGemma Jev](https://github.com/razorback16/openjev) | 33.4% | 27.1% | 6.3% | **0** | $0.239 |
@@ -60,7 +60,7 @@ Failed requests count as incorrect decisions: a failed issue is a miss; a failed
60
 
61
  ### Private — 498 pairs
62
 
63
- | Model | Recall | Clean methods wrongly flagged | Recall − false-positive rate | Failed requests | Inference cost |
64
  | --- | ---: | ---: | ---: | ---: | ---: |
65
  | [GPT-6 Luna Decisions](https://developers.openai.com/api/docs/guides/decisions) | 52.4% | 41.3% | **11.1%** | **0** | $0.247 |
66
  | [DiffusionGemma Jev](https://github.com/razorback16/openjev) | 35.8% | 27.3% | 8.6% | **0** | $0.054 |
@@ -76,11 +76,11 @@ Failed requests count as incorrect decisions: a failed issue is a miss; a failed
76
 
77
  [Public pairs](https://huggingface.co/datasets/perchscan/security-pairs-public)
78
 
79
- ![Security: recall minus false-positive rate across cutoffs](assets/security-tradeoff.svg)
80
 
81
  ### Public — 1,311 pairs
82
 
83
- | Model | Recall | Clean methods wrongly flagged | Recall − false-positive rate | Failed requests | Inference cost |
84
  | --- | ---: | ---: | ---: | ---: | ---: |
85
  | [Jev](https://typesafe.ai/blog/introducing-system-one-models-and-jev) | 34.6% | 23.6% | **11.0%** | **0** | $0.507 |
86
  | [TypeLLM](https://typellm.ai/docs) | 27.8% | 17.4% | 10.5% | **0** | $0.566 |
@@ -97,7 +97,7 @@ Failed requests count as incorrect decisions: a failed issue is a miss; a failed
97
 
98
  ### Private — 439 pairs
99
 
100
- | Model | Recall | Clean methods wrongly flagged | Recall − false-positive rate | Failed requests | Inference cost |
101
  | --- | ---: | ---: | ---: | ---: | ---: |
102
  | [GPT-6 Luna Decisions](https://developers.openai.com/api/docs/guides/decisions) | 40.5% | 31.5% | **9.0%** | **0** | $0.530 |
103
  | [Liquid d1](https://docs.liquid.ai/lfm/models/decision-models) | 34.2% | 29.0% | 5.2% | **0** | Free tier |
@@ -113,11 +113,11 @@ Failed requests count as incorrect decisions: a failed issue is a miss; a failed
113
 
114
  [Public pairs](https://huggingface.co/datasets/perchscan/perch-lint-bench-public)
115
 
116
- ![Perch Lint Bench: recall minus false-positive rate across cutoffs](assets/lint-tradeoff.svg)
117
 
118
  ### Public — 214 pairs
119
 
120
- | Model | Recall | Clean methods wrongly flagged | Recall − false-positive rate | Failed requests | Inference cost |
121
  | --- | ---: | ---: | ---: | ---: | ---: |
122
  | [GPT-6 Luna Decisions](https://developers.openai.com/api/docs/guides/decisions) | **76.6%** | 4.7% | **72.0%** | **0** | $0.093 |
123
  | [TypeLLM](https://typellm.ai/docs) | 61.7% | 2.8% | 58.9% | **0** | $0.050 |
@@ -131,7 +131,7 @@ Failed requests count as incorrect decisions: a failed issue is a miss; a failed
131
 
132
  ### Private — 71 pairs
133
 
134
- | Model | Recall | Clean methods wrongly flagged | Recall − false-positive rate | Failed requests | Inference cost |
135
  | --- | ---: | ---: | ---: | ---: | ---: |
136
  | [GPT-6 Luna Decisions](https://developers.openai.com/api/docs/guides/decisions) | **84.5%** | 7.0% | **77.5%** | **0** | $0.030 |
137
  | [TypeLLM](https://typellm.ai/docs) | 59.2% | 5.6% | 53.5% | **0** | $0.016 |
 
29
 
30
  ## Reading the results
31
 
32
+ Each point shows a model at the same cutoff used in its table. X is the false-positive rate: the percentage of clean methods wrongly flagged. Y is recall: the percentage of labelled issues found. Higher and farther left is better.
33
 
34
+ The tables use each run's recorded alert settings. A value of 20% under ‘False-positive rate’ means one in five clean methods received an alert. Models are ranked by recall minus that percentage. Bold marks the best full-set value in each column; cost compares priced runs captured here.
35
 
36
+ Failed requests count as incorrect decisions: a failed issue is a miss; a failed clean method is a false positive. Failed cases receive no model score and are included in both the table counts and plotted points.
37
 
38
  ## Bugs
39
 
40
  [Public pairs](https://huggingface.co/datasets/perchscan/bug-pairs-public)
41
 
42
+ ![Bugs: recall versus false-positive rate at table cutoffs](assets/bug-tradeoff.svg)
43
 
44
  ### Public — 2,220 pairs
45
 
46
+ | Model | Recall | False-positive rate | Recall − false-positive rate | Failed requests | Inference cost |
47
  | --- | ---: | ---: | ---: | ---: | ---: |
48
  | [GPT-6 Luna Decisions](https://developers.openai.com/api/docs/guides/decisions) | 48.7% | 38.7% | **10.0%** | **0** | $1.102 |
49
  | [DiffusionGemma Jev](https://github.com/razorback16/openjev) | 33.4% | 27.1% | 6.3% | **0** | $0.239 |
 
60
 
61
  ### Private — 498 pairs
62
 
63
+ | Model | Recall | False-positive rate | Recall − false-positive rate | Failed requests | Inference cost |
64
  | --- | ---: | ---: | ---: | ---: | ---: |
65
  | [GPT-6 Luna Decisions](https://developers.openai.com/api/docs/guides/decisions) | 52.4% | 41.3% | **11.1%** | **0** | $0.247 |
66
  | [DiffusionGemma Jev](https://github.com/razorback16/openjev) | 35.8% | 27.3% | 8.6% | **0** | $0.054 |
 
76
 
77
  [Public pairs](https://huggingface.co/datasets/perchscan/security-pairs-public)
78
 
79
+ ![Security: recall versus false-positive rate at table cutoffs](assets/security-tradeoff.svg)
80
 
81
  ### Public — 1,311 pairs
82
 
83
+ | Model | Recall | False-positive rate | Recall − false-positive rate | Failed requests | Inference cost |
84
  | --- | ---: | ---: | ---: | ---: | ---: |
85
  | [Jev](https://typesafe.ai/blog/introducing-system-one-models-and-jev) | 34.6% | 23.6% | **11.0%** | **0** | $0.507 |
86
  | [TypeLLM](https://typellm.ai/docs) | 27.8% | 17.4% | 10.5% | **0** | $0.566 |
 
97
 
98
  ### Private — 439 pairs
99
 
100
+ | Model | Recall | False-positive rate | Recall − false-positive rate | Failed requests | Inference cost |
101
  | --- | ---: | ---: | ---: | ---: | ---: |
102
  | [GPT-6 Luna Decisions](https://developers.openai.com/api/docs/guides/decisions) | 40.5% | 31.5% | **9.0%** | **0** | $0.530 |
103
  | [Liquid d1](https://docs.liquid.ai/lfm/models/decision-models) | 34.2% | 29.0% | 5.2% | **0** | Free tier |
 
113
 
114
  [Public pairs](https://huggingface.co/datasets/perchscan/perch-lint-bench-public)
115
 
116
+ ![Perch Lint Bench: recall versus false-positive rate at table cutoffs](assets/lint-tradeoff.svg)
117
 
118
  ### Public — 214 pairs
119
 
120
+ | Model | Recall | False-positive rate | Recall − false-positive rate | Failed requests | Inference cost |
121
  | --- | ---: | ---: | ---: | ---: | ---: |
122
  | [GPT-6 Luna Decisions](https://developers.openai.com/api/docs/guides/decisions) | **76.6%** | 4.7% | **72.0%** | **0** | $0.093 |
123
  | [TypeLLM](https://typellm.ai/docs) | 61.7% | 2.8% | 58.9% | **0** | $0.050 |
 
131
 
132
  ### Private — 71 pairs
133
 
134
+ | Model | Recall | False-positive rate | Recall − false-positive rate | Failed requests | Inference cost |
135
  | --- | ---: | ---: | ---: | ---: | ---: |
136
  | [GPT-6 Luna Decisions](https://developers.openai.com/api/docs/guides/decisions) | **84.5%** | 7.0% | **77.5%** | **0** | $0.030 |
137
  | [TypeLLM](https://typellm.ai/docs) | 59.2% | 5.6% | 53.5% | **0** | $0.016 |
assets/bug-tradeoff.svg CHANGED
assets/lint-tradeoff.svg CHANGED
assets/security-tradeoff.svg CHANGED
test_tradeoff.py CHANGED
@@ -7,35 +7,86 @@ import tradeoff
7
 
8
 
9
  class GraphTests(unittest.TestCase):
10
- def test_equal_alert_rates_have_zero_margin_at_both_ends(self):
11
- # Unequal class sizes prevent subtracting raw counts by mistake.
12
- curves = {model: ([(0, 0), (2, 7), (20, 10)], 10, 20) for model in tradeoff.ORDER}
13
  with tempfile.TemporaryDirectory() as temp:
14
  output = Path(temp) / 'graph.svg'
15
- tradeoff.svg('bug', curves, output)
16
- root = ET.fromstring(output.read_text())
17
- paths = root.findall('{http://www.w3.org/2000/svg}polyline')
18
- self.assertEqual(len(paths), len(tradeoff.ORDER))
19
- points = [tuple(map(float, point.split(','))) for point in paths[0].attrib['points'].split()]
20
- self.assertEqual(points[0][1], points[2][1])
21
- self.assertLess(points[1][1], points[0][1])
22
- self.assertGreater(points[2][0], points[1][0])
 
 
 
 
23
  labels = [e.text for e in root.findall('{http://www.w3.org/2000/svg}text')]
24
- self.assertIn('100%', labels)
25
- self.assertIn('Zero means issues and clean methods are flagged at equal rates.',
26
- root.find('{http://www.w3.org/2000/svg}desc').text)
27
- self.assertIn('Recall − false-positive rate (percentage points)', labels)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
- def test_negative_margins_remain_visible(self):
30
- curves = {model: ([(0, 0), (10, 2), (20, 10)], 10, 20) for model in tradeoff.ORDER}
 
 
 
 
 
 
 
 
 
 
 
31
  with tempfile.TemporaryDirectory() as temp:
32
- output = Path(temp) / 'graph.svg'
33
- tradeoff.svg('security', curves, output)
34
- root = ET.fromstring(output.read_text())
35
- path = root.find('{http://www.w3.org/2000/svg}polyline')
36
- points = [tuple(map(float, point.split(','))) for point in path.attrib['points'].split()]
37
- self.assertGreater(points[1][1], points[0][1])
38
- self.assertLessEqual(points[1][1], 498)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
 
41
  if __name__ == '__main__':
 
7
 
8
 
9
  class GraphTests(unittest.TestCase):
10
+ def render(self, current):
 
 
11
  with tempfile.TemporaryDirectory() as temp:
12
  output = Path(temp) / 'graph.svg'
13
+ tradeoff.svg('bug', current, output)
14
+ return ET.fromstring(output.read_text())
15
+
16
+ def test_points_use_recall_and_false_positive_rate_from_table(self):
17
+ current = {model: {'confusion': {'tp': 7, 'fn': 3, 'fp': 2, 'tn': 18}}
18
+ for model in tradeoff.ORDER}
19
+ root = self.render(current)
20
+ dots = [e for e in root.findall('{http://www.w3.org/2000/svg}circle') if 'data-model' in e.attrib]
21
+ self.assertEqual(len(dots), len(tradeoff.ORDER))
22
+ self.assertAlmostEqual((float(dots[0].attrib['cx']) - 90) / 990, .1)
23
+ self.assertAlmostEqual((498 - float(dots[0].attrib['cy'])) / 350, .7)
24
+ self.assertFalse(root.findall('{http://www.w3.org/2000/svg}polyline'))
25
  labels = [e.text for e in root.findall('{http://www.w3.org/2000/svg}text')]
26
+ self.assertIn('False positive rate', labels)
27
+ self.assertIn('Recall', labels)
28
+
29
+ def test_false_positives_do_not_change_vertical_recall_coordinate(self):
30
+ current = {model: {'confusion': {'tp': 7, 'fn': 3, 'fp': 2, 'tn': 18}}
31
+ for model in tradeoff.ORDER}
32
+ current['typellm'] = {'confusion': {'tp': 7, 'fn': 3, 'fp': 10, 'tn': 10}}
33
+ root = self.render(current)
34
+ dots = {e.attrib['data-model']: e for e in root.findall('{http://www.w3.org/2000/svg}circle')
35
+ if 'data-model' in e.attrib}
36
+ self.assertEqual(dots['jev'].attrib['cy'], dots['typellm'].attrib['cy'])
37
+ self.assertLess(float(dots['jev'].attrib['cx']), float(dots['typellm'].attrib['cx']))
38
+
39
+
40
+ class AlertCurveTests(unittest.TestCase):
41
+ def setUp(self):
42
+ self.pack = {'pack_sha256': 'current', 'domains': {'bug': [
43
+ {'name': 'first', 'min': 60, 'issue': {'type': 'defect'}},
44
+ {'name': 'second', 'min': 70, 'issue': {'type': 'defect'}}]}}
45
+ self.result = {'domain': 'bug', 'question_pack_sha256': 'current', 'threshold': .5,
46
+ 'confusion': {'tp': 1, 'fp': 1, 'fn': 1, 'tn': 0}}
47
 
48
+ def write_predictions(self, path, rows):
49
+ import json
50
+ path.write_text(''.join(json.dumps(row) + '\n' for row in rows))
51
+
52
+ def test_question_floors_remove_ineligible_alerts_at_every_cutoff(self):
53
+ labels = {('low', 'before'): 1, ('high', 'before'): 1, ('clean', 'after'): 0}
54
+ rows = [
55
+ {'pair_id': 'low', 'role': 'before', 'score': .68, 'alert': False,
56
+ 'question_scores': {'first': .6, 'second': .68}},
57
+ {'pair_id': 'high', 'role': 'before', 'score': .9, 'alert': True,
58
+ 'question_scores': {'first': .1, 'second': .9}},
59
+ {'pair_id': 'clean', 'role': 'after', 'score': .8, 'alert': True,
60
+ 'question_scores': {'first': .8, 'second': .1}}]
61
  with tempfile.TemporaryDirectory() as temp:
62
+ path = Path(temp) / 'scores.jsonl'
63
+ self.write_predictions(path, rows)
64
+ points, positives, negatives = tradeoff.curve(labels, path, self.result, self.pack)
65
+ self.assertEqual((positives, negatives), (2, 1))
66
+ self.assertEqual(points, [(0, 0), (0, 1), (1, 1)])
67
+ self.assertIn((self.result['confusion']['fp'], self.result['confusion']['tp']), points)
68
+ # A strict threshold at .8 must exclude the clean method's .8 score.
69
+ stricter = {**self.result, 'threshold': .8, 'confusion': {'tp': 1, 'fp': 0, 'fn': 1, 'tn': 1}}
70
+ rows[2]['alert'] = False
71
+ self.write_predictions(path, rows)
72
+ strict_points, _, _ = tradeoff.curve(labels, path, stricter, self.pack)
73
+ self.assertEqual(strict_points, points)
74
+
75
+ def test_failure_penalty_and_table_mismatch_are_preserved(self):
76
+ labels = {('positive', 'before'): 1, ('negative', 'after'): 0}
77
+ rows = [
78
+ {'pair_id': 'positive', 'role': 'before', 'score': .9, 'alert': True,
79
+ 'question_scores': {'first': .9, 'second': .1}},
80
+ {'pair_id': 'negative', 'role': 'after', 'status': 'failed'}]
81
+ result = {**self.result, 'confusion': {'tp': 1, 'fp': 1, 'fn': 0, 'tn': 0}}
82
+ with tempfile.TemporaryDirectory() as temp:
83
+ path = Path(temp) / 'scores.jsonl'
84
+ self.write_predictions(path, rows)
85
+ points, _, _ = tradeoff.curve(labels, path, result, self.pack)
86
+ self.assertEqual(points, [(1, 0), (1, 1)])
87
+ result['confusion']['fp'] = 0
88
+ with self.assertRaises(ValueError):
89
+ tradeoff.curve(labels, path, result, self.pack)
90
 
91
 
92
  if __name__ == '__main__':
tradeoff.py CHANGED
@@ -1,8 +1,8 @@
1
  #!/usr/bin/env python3
2
- """Rebuild public recall/false-alert curves and benchmark result tables.
3
 
4
- The public curves sweep saved method scores. Tables use recorded scan alerts;
5
- private tables use only aggregates in results-current.jsonl.
6
  """
7
 
8
  from __future__ import annotations
@@ -11,7 +11,7 @@ import argparse
11
  from collections import defaultdict
12
  import html
13
  import json
14
- from math import ceil, floor, isfinite
15
  from pathlib import Path
16
  from tempfile import TemporaryDirectory
17
  from urllib.request import urlopen
@@ -42,6 +42,8 @@ COLORS = {
42
  "gliner25-decide": "#9b7a39",
43
  }
44
  ORDER = tuple(NAMES)
 
 
45
 
46
 
47
  def lines(path: Path) -> list[dict]:
@@ -72,9 +74,24 @@ def labels_for(domain: str, pairs: list[dict]) -> dict[tuple[str, str], int]:
72
  return labels
73
 
74
 
75
- def curve(labels: dict[tuple[str, str], int], prediction_path: Path) -> tuple[list[tuple[int, int]], int, int]:
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  predictions = lines(prediction_path)
77
  scores, failed = {}, set()
 
 
78
  for row in predictions:
79
  key = row["pair_id"], row["role"]
80
  if row.get("status") == "failed":
@@ -83,13 +100,38 @@ def curve(labels: dict[tuple[str, str], int], prediction_path: Path) -> tuple[li
83
  failed.add(key)
84
  continue
85
  value = row["score"]
 
 
 
 
 
 
 
 
 
86
  if key in scores or key in failed or not isinstance(value, (int, float)) or not isfinite(value) or not 0 <= value <= 1:
87
  raise ValueError(f"Invalid prediction in {prediction_path}: {key}")
88
  scores[key] = float(value)
 
 
 
 
 
 
 
 
89
  if scores.keys() | failed != labels.keys():
90
  raise ValueError(f"Incomplete outcomes in {prediction_path}: {len(scores) + len(failed)} of {len(labels)}")
 
 
 
 
91
  groups = defaultdict(lambda: [0, 0])
92
  for key, score in scores.items():
 
 
 
 
93
  groups[score][1 - labels[key]] += 1 # index 0 is positive; 1 is negative
94
  # Failures count as wrong at every cutoff. They never receive invented scores.
95
  tp, fp = 0, sum(labels[key] == 0 for key in failed)
@@ -99,6 +141,8 @@ def curve(labels: dict[tuple[str, str], int], prediction_path: Path) -> tuple[li
99
  tp += positive
100
  fp += negative
101
  points.append((fp, tp))
 
 
102
  return points, sum(labels.values()), len(labels) - sum(labels.values())
103
 
104
 
@@ -145,7 +189,7 @@ def results_table(rows: list[dict]) -> str:
145
  def mark(value: str, winner: bool) -> str:
146
  return f"**{value}**" if winner else value
147
 
148
- table = ["| Model | Recall | Clean methods wrongly flagged | Recall − false-positive rate | Failed requests | Inference cost |",
149
  "| --- | ---: | ---: | ---: | ---: | ---: |"]
150
  for row in ordered:
151
  recall, false_positive_rate, j = metrics[row["model_id"]]
@@ -165,71 +209,53 @@ def results_table(rows: list[dict]) -> str:
165
  return "\n".join(table)
166
 
167
 
168
- def svg(domain: str, curves: dict[str, tuple[list[tuple[int, int]], int, int]], output: Path) -> None:
169
  width, height = 1120, 580
170
  left, right, top, bottom = 90, 40, 148, 82
171
  plot_w, plot_h = width - left - right, height - top - bottom
172
- # Subtract the diagonal so small ranking differences remain visible.
173
- # Keep every cutoff and adapt only the vertical display range.
174
- x_max = 100
175
- step = 10 if domain == "lint" else 5
176
- margins = [100 * (tp / positives - fp / negatives)
177
- for points, positives, negatives in curves.values() for fp, tp in points]
178
- y_min = min(-step, floor(min(margins) / step) * step)
179
- y_max = max(step, ceil(max(margins) / step) * step)
180
-
181
- def x(fp: int, negatives: int) -> float:
182
- return left + (fp / negatives * 100) / x_max * plot_w
183
-
184
- def y(margin: float) -> float:
185
- return top + (y_max - margin) / (y_max - y_min) * plot_h
186
-
187
  title = {"bug": "Bug detection", "security": "Security detection", "lint": "Perch Lint Bench"}[domain]
188
  out = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}" role="img" aria-labelledby="title desc">',
189
- f'<title id="title">{title}: recall minus false-positive rate</title>',
190
- '<desc id="desc">Public model curves across score cutoffs. The vertical axis subtracts the false-positive rate from recall. Zero means issues and clean methods are flagged at equal rates. Higher is better.</desc>',
191
  f'<rect width="{width}" height="{height}" rx="16" fill="#101318"/>',
192
- f'<defs><clipPath id="plot"><rect x="{left}" y="{top}" width="{plot_w}" height="{plot_h}"/></clipPath></defs>',
193
  f'<text x="{left}" y="43" fill="#f2f5fa" font-family="Arial,sans-serif" font-weight="700" font-size="28">{html.escape(title)}</text>',
194
- f'<text x="{left}" y="70" fill="#aeb9c7" font-family="Arial,sans-serif" font-size="16">Public methods · recall minus false-positive rate · higher is better</text>']
195
- for i, model in enumerate(ORDER):
196
- col = i % 4
197
- row = i // 4
198
- lx = left + col * 245
199
- ly = 91 + row * 22
200
- out += [f'<line x1="{lx}" y1="{ly}" x2="{lx + 24}" y2="{ly}" stroke="{COLORS[model]}" stroke-width="4"/>',
201
- f'<text x="{lx + 32}" y="{ly + 5}" fill="#e1e7ef" font-family="Arial,sans-serif" font-size="15">{html.escape(NAMES[model][0])}</text>']
202
- x_step = 20
203
- for value in range(0, x_max + 1, x_step):
204
- px = left + value / x_max * plot_w
205
  out += [f'<line x1="{px:.1f}" y1="{top}" x2="{px:.1f}" y2="{top + plot_h}" stroke="#29303a"/>',
206
- f'<text x="{px:.1f}" y="{top + plot_h + 25}" text-anchor="middle" fill="#aeb9c7" font-family="Arial,sans-serif" font-size="14">{value}%</text>']
207
- for value in range(y_min, y_max + 1, step):
208
- py = y(value)
209
- out += [f'<line x1="{left}" y1="{py:.1f}" x2="{left + plot_w}" y2="{py:.1f}" stroke="#29303a"/>',
210
- f'<text x="{left - 12}" y="{py + 5:.1f}" text-anchor="end" fill="#aeb9c7" font-family="Arial,sans-serif" font-size="14">{value}</text>']
211
- zero_y = y(0)
212
- out.append(f'<line x1="{left}" y1="{zero_y:.1f}" x2="{left + plot_w}" y2="{zero_y:.1f}" stroke="#aeb9c7" stroke-width="1.5" stroke-dasharray="5 5"/>')
213
- for model in ORDER:
214
- points, positives, negatives = curves[model]
215
- visible = [(fp, tp) for fp, tp in points if fp / negatives * 100 <= x_max]
216
- if len(visible) > 1:
217
- positions = " ".join(f"{x(fp, negatives):.2f},{y(100 * (tp / positives - fp / negatives)):.2f}" for fp, tp in visible)
218
- out.append(f'<polyline points="{positions}" fill="none" stroke="{COLORS[model]}" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round" clip-path="url(#plot)"/>')
219
- out += [f'<text x="{left + plot_w / 2:.1f}" y="{height - 23}" text-anchor="middle" fill="#e1e7ef" font-family="Arial,sans-serif" font-size="17">Clean methods wrongly flagged →</text>',
220
- f'<text transform="translate(23 {top + plot_h / 2:.1f}) rotate(-90)" text-anchor="middle" fill="#e1e7ef" font-family="Arial,sans-serif" font-size="14">Recall − false-positive rate (percentage points)</text>',
221
  '</svg>']
222
  output.parent.mkdir(parents=True, exist_ok=True)
223
  output.write_text("\n".join(out) + "\n")
224
 
225
 
226
- def render_sections(results: list[dict], curves_by_domain: dict[str, dict], output_dir: Path,
227
  codeql_results: dict) -> str:
228
  sections = ["## Reading the results", "",
229
- "Each line shows recall minus the false-positive rate as the score cutoff changes. Higher is better; farther left means fewer clean methods flagged. The dashed zero line means issues and clean methods are flagged at equal rates.", "",
230
- "The tables use each run's recorded alert settings. A value of 20% under ‘Clean methods wrongly flagged’ means one in five clean methods received an alert. Models are ranked by recall minus that percentage. Bold marks the best full-set value in each column; cost compares priced runs captured here.", ""]
231
  if any(r.get("failed_methods") for r in results):
232
- sections += ["Failed requests count as incorrect decisions: a failed issue is a miss; a failed clean method is a false positive. Failed cases receive no model score and remain incorrect across the plotted cutoffs.", ""]
233
  for domain in ("bug", "security", "lint"):
234
  title = {"bug": "Bugs", "security": "Security", "lint": "Perch Lint Bench"}[domain]
235
  link = {"bug": "bug-pairs-public", "security": "security-pairs-public", "lint": "perch-lint-bench-public"}[domain]
@@ -247,9 +273,9 @@ def render_sections(results: list[dict], curves_by_domain: dict[str, dict], outp
247
  public.append({"model_id": "codeql", "benchmark_pairs": comparison["pairs"],
248
  "confusion": counts})
249
  image = output_dir / f"{domain}-tradeoff.svg"
250
- svg(domain, curves_by_domain[domain], image)
251
  sections += [f"## {title}", "", f"[Public pairs](https://huggingface.co/datasets/perchscan/{link})", "",
252
- f"![{title}: recall minus false-positive rate across cutoffs](assets/{domain}-tradeoff.svg)", "",
253
  f"### Public — {public[0]['benchmark_pairs']:,} pairs", "",
254
  results_table(public), ""]
255
  if domain in ("bug", "security"):
@@ -268,18 +294,16 @@ def main() -> None:
268
  parser.add_argument("--check", action="store_true", help="Check generated card and SVGs without writing")
269
  args = parser.parse_args()
270
  results = lines(ROOT / "results-current.jsonl")
 
271
  codeql_results = json.loads((ROOT / "codeql-comparison" / "results.json").read_text())
272
- curves_by_domain = {}
273
  for domain in ("bug", "security", "lint"):
274
  labels = labels_for(domain, dataset(domain, args.dataset_root))
275
- curves_by_domain[domain] = {}
276
  for model in ORDER:
277
  result = next(r for r in results if r["domain"] == domain and r["track"] == "public" and r["model_id"] == model)
278
- points, positives, negatives = curve(labels, ROOT / "predictions" / "current" / domain / f"{model}.jsonl")
279
  counts = result["confusion"]
280
  if (positives, negatives) != (counts["tp"] + counts["fn"], counts["tn"] + counts["fp"]):
281
  raise ValueError(f"Label counts differ from recorded result: {domain}/{model}")
282
- curves_by_domain[domain][model] = points, positives, negatives
283
  card = ROOT / "README.md"
284
  original = card.read_text()
285
  start_marker, end_marker = "<!-- BEGIN TRADEOFF_RESULTS -->", "<!-- END TRADEOFF_RESULTS -->"
@@ -292,13 +316,13 @@ def main() -> None:
292
  end += len(end_marker)
293
  if args.check:
294
  with TemporaryDirectory() as temporary:
295
- content = render_sections(results, curves_by_domain, Path(temporary), codeql_results)
296
  for domain in DATASET_URLS:
297
  name = f"{domain}-tradeoff.svg"
298
  if (Path(temporary) / name).read_bytes() != (ROOT / "assets" / name).read_bytes():
299
  raise SystemExit(f"assets/{name} is not up to date; run python3 tradeoff.py")
300
  else:
301
- content = render_sections(results, curves_by_domain, ROOT / "assets", codeql_results)
302
  updated = (original[:start].rstrip("\n") + "\n\n" + start_marker + "\n\n" + content
303
  + "\n" + end_marker + "\n\n" + original[end:].lstrip("\n"))
304
  if args.check and original != updated:
 
1
  #!/usr/bin/env python3
2
+ """Rebuild public recall/false-positive-rate charts and benchmark result tables.
3
 
4
+ Recorded alert counts are validated against each run's question floors and failure policy.
5
+ Private tables use only aggregates in results-current.jsonl.
6
  """
7
 
8
  from __future__ import annotations
 
11
  from collections import defaultdict
12
  import html
13
  import json
14
+ from math import isfinite
15
  from pathlib import Path
16
  from tempfile import TemporaryDirectory
17
  from urllib.request import urlopen
 
42
  "gliner25-decide": "#9b7a39",
43
  }
44
  ORDER = tuple(NAMES)
45
+ OLD_PACK_SHA = "bb53c8a6ca30920140e2bf33b2905d159e7b1709b29d1ea896637905dbf9047d"
46
+ OLD_BUG_FLOORS = {"has_bug": 0.6, "does_what_it_claims": 0.7}
47
 
48
 
49
  def lines(path: Path) -> list[dict]:
 
74
  return labels
75
 
76
 
77
+ def question_floors(domain: str, result: dict, pack: dict) -> dict[str, float]:
78
+ if domain == "lint":
79
+ return {}
80
+ revision = result["question_pack_sha256"]
81
+ if revision not in (OLD_PACK_SHA, pack["pack_sha256"]):
82
+ raise ValueError(f"Unknown question pack: {revision}")
83
+ if domain == "bug" and revision == OLD_PACK_SHA:
84
+ return OLD_BUG_FLOORS
85
+ return {q["name"]: (q.get("min") or 0) / 100
86
+ for q in pack["domains"][domain] if q.get("issue")}
87
+
88
+
89
+ def curve(labels: dict[tuple[str, str], int], prediction_path: Path, result: dict,
90
+ pack: dict) -> tuple[list[tuple[int, int]], int, int]:
91
  predictions = lines(prediction_path)
92
  scores, failed = {}, set()
93
+ floors = question_floors(result["domain"], result, pack)
94
+ operating_tp = operating_fp = 0
95
  for row in predictions:
96
  key = row["pair_id"], row["role"]
97
  if row.get("status") == "failed":
 
100
  failed.add(key)
101
  continue
102
  value = row["score"]
103
+ if floors:
104
+ question_scores = row["question_scores"]
105
+ if not question_scores or not set(question_scores) <= set(floors):
106
+ raise ValueError(f"Question scores differ from recorded pack: {prediction_path}: {key}")
107
+ for score in question_scores.values():
108
+ if not isinstance(score, (int, float)) or isinstance(score, bool) or not isfinite(score) or not 0 <= score <= 1:
109
+ raise ValueError(f"Invalid question score in {prediction_path}: {key}")
110
+ value = max((score for name, score in question_scores.items()
111
+ if score > floors[name]), default=0.0)
112
  if key in scores or key in failed or not isinstance(value, (int, float)) or not isfinite(value) or not 0 <= value <= 1:
113
  raise ValueError(f"Invalid prediction in {prediction_path}: {key}")
114
  scores[key] = float(value)
115
+ alerted = value > result["threshold"]
116
+ if "alert" in row and row["alert"] != alerted:
117
+ raise ValueError(f"Saved alert differs from score rule: {prediction_path}: {key}")
118
+ if alerted:
119
+ if labels[key]:
120
+ operating_tp += 1
121
+ else:
122
+ operating_fp += 1
123
  if scores.keys() | failed != labels.keys():
124
  raise ValueError(f"Incomplete outcomes in {prediction_path}: {len(scores) + len(failed)} of {len(labels)}")
125
+ operating_fp += sum(labels[key] == 0 for key in failed)
126
+ counts = result["confusion"]
127
+ if (operating_tp, operating_fp) != (counts["tp"], counts["fp"]):
128
+ raise ValueError(f"Table counts differ from plotted score rule: {prediction_path}")
129
  groups = defaultdict(lambda: [0, 0])
130
  for key, score in scores.items():
131
+ # At a strict cutoff >= 0, a zero score never alerts. Methods whose
132
+ # questions all fail their floors must remain unalerted at every cutoff.
133
+ if score == 0:
134
+ continue
135
  groups[score][1 - labels[key]] += 1 # index 0 is positive; 1 is negative
136
  # Failures count as wrong at every cutoff. They never receive invented scores.
137
  tp, fp = 0, sum(labels[key] == 0 for key in failed)
 
141
  tp += positive
142
  fp += negative
143
  points.append((fp, tp))
144
+ if (counts["fp"], counts["tp"]) not in points:
145
+ raise ValueError(f"Table operating point is not on curve: {prediction_path}")
146
  return points, sum(labels.values()), len(labels) - sum(labels.values())
147
 
148
 
 
189
  def mark(value: str, winner: bool) -> str:
190
  return f"**{value}**" if winner else value
191
 
192
+ table = ["| Model | Recall | False-positive rate | Recall − false-positive rate | Failed requests | Inference cost |",
193
  "| --- | ---: | ---: | ---: | ---: | ---: |"]
194
  for row in ordered:
195
  recall, false_positive_rate, j = metrics[row["model_id"]]
 
209
  return "\n".join(table)
210
 
211
 
212
+ def svg(domain: str, current: dict[str, dict], output: Path) -> None:
213
  width, height = 1120, 580
214
  left, right, top, bottom = 90, 40, 148, 82
215
  plot_w, plot_h = width - left - right, height - top - bottom
216
+ models = [*ORDER, *(["codeql"] if "codeql" in current else [])]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
  title = {"bug": "Bug detection", "security": "Security detection", "lint": "Perch Lint Bench"}[domain]
218
  out = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}" role="img" aria-labelledby="title desc">',
219
+ f'<title id="title">{title}: recall versus false positive rate</title>',
220
+ '<desc id="desc">Each point is a model at its recorded table cutoff. X is the percentage of clean methods falsely flagged. Y is the percentage of issue-bearing methods found. Higher and farther left is better. CodeQL, where present, uses the subset documented below the table.</desc>',
221
  f'<rect width="{width}" height="{height}" rx="16" fill="#101318"/>',
 
222
  f'<text x="{left}" y="43" fill="#f2f5fa" font-family="Arial,sans-serif" font-weight="700" font-size="28">{html.escape(title)}</text>',
223
+ f'<text x="{left}" y="70" fill="#aeb9c7" font-family="Arial,sans-serif" font-size="16">Public methods · one point per model · upper left is better</text>']
224
+ for i, model in enumerate(models):
225
+ col, row = i % 4, i // 4
226
+ lx, ly = left + col * 245, 91 + row * 22
227
+ color = COLORS.get(model, "#cfd5df")
228
+ name = "CodeQL*" if model == "codeql" else NAMES[model][0]
229
+ out += [f'<circle cx="{lx + 12}" cy="{ly}" r="5" fill="{color}"/>',
230
+ f'<text x="{lx + 32}" y="{ly + 5}" fill="#e1e7ef" font-family="Arial,sans-serif" font-size="15">{html.escape(name)}</text>']
231
+ for value in range(0, 101, 20):
232
+ px = left + value / 100 * plot_w
233
+ py = top + (1 - value / 100) * plot_h
234
  out += [f'<line x1="{px:.1f}" y1="{top}" x2="{px:.1f}" y2="{top + plot_h}" stroke="#29303a"/>',
235
+ f'<text x="{px:.1f}" y="{top + plot_h + 25}" text-anchor="middle" fill="#aeb9c7" font-family="Arial,sans-serif" font-size="14">{value}%</text>',
236
+ f'<line x1="{left}" y1="{py:.1f}" x2="{left + plot_w}" y2="{py:.1f}" stroke="#29303a"/>',
237
+ f'<text x="{left - 12}" y="{py + 5:.1f}" text-anchor="end" fill="#aeb9c7" font-family="Arial,sans-serif" font-size="14">{value}%</text>']
238
+ for model in models:
239
+ recall, fpr, _ = operating_metrics(current[model])
240
+ px, py = left + fpr * plot_w, top + (1 - recall) * plot_h
241
+ color = COLORS.get(model, "#cfd5df")
242
+ name = "CodeQL*" if model == "codeql" else NAMES[model][0]
243
+ tooltip = html.escape(f"{name}: recall {recall:.1%}; false positive rate {fpr:.1%}")
244
+ out.append(f'<circle data-model="{model}" cx="{px:.2f}" cy="{py:.2f}" r="6" fill="{color}" stroke="#fff" stroke-width="1.5"><title>{tooltip}</title></circle>')
245
+ out += [f'<text x="{left + plot_w / 2:.1f}" y="{height - 23}" text-anchor="middle" fill="#e1e7ef" font-family="Arial,sans-serif" font-size="17">False positive rate</text>',
246
+ f'<text transform="translate(23 {top + plot_h / 2:.1f}) rotate(-90)" text-anchor="middle" fill="#e1e7ef" font-family="Arial,sans-serif" font-size="17">Recall</text>',
 
 
 
247
  '</svg>']
248
  output.parent.mkdir(parents=True, exist_ok=True)
249
  output.write_text("\n".join(out) + "\n")
250
 
251
 
252
+ def render_sections(results: list[dict], output_dir: Path,
253
  codeql_results: dict) -> str:
254
  sections = ["## Reading the results", "",
255
+ "Each point shows a model at the same cutoff used in its table. X is the false-positive rate: the percentage of clean methods wrongly flagged. Y is recall: the percentage of labelled issues found. Higher and farther left is better.", "",
256
+ "The tables use each run's recorded alert settings. A value of 20% under ‘False-positive rate’ means one in five clean methods received an alert. Models are ranked by recall minus that percentage. Bold marks the best full-set value in each column; cost compares priced runs captured here.", ""]
257
  if any(r.get("failed_methods") for r in results):
258
+ sections += ["Failed requests count as incorrect decisions: a failed issue is a miss; a failed clean method is a false positive. Failed cases receive no model score and are included in both the table counts and plotted points.", ""]
259
  for domain in ("bug", "security", "lint"):
260
  title = {"bug": "Bugs", "security": "Security", "lint": "Perch Lint Bench"}[domain]
261
  link = {"bug": "bug-pairs-public", "security": "security-pairs-public", "lint": "perch-lint-bench-public"}[domain]
 
273
  public.append({"model_id": "codeql", "benchmark_pairs": comparison["pairs"],
274
  "confusion": counts})
275
  image = output_dir / f"{domain}-tradeoff.svg"
276
+ svg(domain, {r["model_id"]: r for r in public}, image)
277
  sections += [f"## {title}", "", f"[Public pairs](https://huggingface.co/datasets/perchscan/{link})", "",
278
+ f"![{title}: recall versus false-positive rate at table cutoffs](assets/{domain}-tradeoff.svg)", "",
279
  f"### Public — {public[0]['benchmark_pairs']:,} pairs", "",
280
  results_table(public), ""]
281
  if domain in ("bug", "security"):
 
294
  parser.add_argument("--check", action="store_true", help="Check generated card and SVGs without writing")
295
  args = parser.parse_args()
296
  results = lines(ROOT / "results-current.jsonl")
297
+ pack = json.loads((ROOT / "question-pack.json").read_text())
298
  codeql_results = json.loads((ROOT / "codeql-comparison" / "results.json").read_text())
 
299
  for domain in ("bug", "security", "lint"):
300
  labels = labels_for(domain, dataset(domain, args.dataset_root))
 
301
  for model in ORDER:
302
  result = next(r for r in results if r["domain"] == domain and r["track"] == "public" and r["model_id"] == model)
303
+ points, positives, negatives = curve(labels, ROOT / "predictions" / "current" / domain / f"{model}.jsonl", result, pack)
304
  counts = result["confusion"]
305
  if (positives, negatives) != (counts["tp"] + counts["fn"], counts["tn"] + counts["fp"]):
306
  raise ValueError(f"Label counts differ from recorded result: {domain}/{model}")
 
307
  card = ROOT / "README.md"
308
  original = card.read_text()
309
  start_marker, end_marker = "<!-- BEGIN TRADEOFF_RESULTS -->", "<!-- END TRADEOFF_RESULTS -->"
 
316
  end += len(end_marker)
317
  if args.check:
318
  with TemporaryDirectory() as temporary:
319
+ content = render_sections(results, Path(temporary), codeql_results)
320
  for domain in DATASET_URLS:
321
  name = f"{domain}-tradeoff.svg"
322
  if (Path(temporary) / name).read_bytes() != (ROOT / "assets" / name).read_bytes():
323
  raise SystemExit(f"assets/{name} is not up to date; run python3 tradeoff.py")
324
  else:
325
+ content = render_sections(results, ROOT / "assets", codeql_results)
326
  updated = (original[:start].rstrip("\n") + "\n\n" + start_marker + "\n\n" + content
327
  + "\n" + end_marker + "\n\n" + original[end:].lstrip("\n"))
328
  if args.check and original != updated: