File size: 12,349 Bytes
286f2b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
#!/usr/bin/env python3
"""Run Span-01 on one public Perch benchmark and score the saved predictions.

Requires RESPAN_API_KEY for new calls. The key is only read from the process
environment; it is never saved in predictions or reports. This script uses the
same method/context layout and behavior definitions as the recorded run.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import os
from pathlib import Path
import sys
import time
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen

import benchmark as core


API = 'https://api.respan.ai/api/v1/scores'
LINT_URL = 'https://huggingface.co/datasets/perchscan/perch-lint-bench-public/resolve/main/benchmark.jsonl'
MODEL = 'span-01-pro'
REVISION = 'span-01-pro (API revision not published)'
PROTOCOL = 'respan-span01-pro-perch-pack-v1'


def load_data(domain: str, path: Path | None):
    if domain != 'lint':
        return core.load_pairs(domain, path)
    raw = path.read_bytes() if path else urlopen(LINT_URL, timeout=120).read()
    pairs = [json.loads(line) for line in raw.splitlines() if line]
    if not pairs or len({pair['pair_id'] for pair in pairs}) != len(pairs):
        raise ValueError('Empty or duplicate lint pairs')
    return pairs, hashlib.sha256(raw).hexdigest()


def questions_for(pack: dict, domain: str, language: str) -> list[dict]:
    return core.detection_questions(core.scan_questions(pack, domain, language), domain)


def issue_definition(q: dict) -> str:
    criteria = q['question']['criteria']
    issue_on = q['issue'].get('on', True)
    present = ' '.join(criteria['true' if issue_on else 'false'].split())
    absent = ' '.join(criteria['false' if issue_on else 'true'].split())
    if issue_on:
        question = ' '.join(q['question']['instructions'].split())
        return (f'The target method has this issue: {question} '
                f'Present when: {present} Absent when: {absent}')
    return (f'The target method violates its stated behavior. '
            f'Present when: {present} Absent when: {absent}')


def method_parts(pair: dict, side: dict) -> tuple[str, str]:
    state = side['state']
    method = state.get('method') or {}
    language = pair.get('language') or 'unknown'
    context = [f'LANGUAGE: {language}']
    for name, title in (('imports', 'IMPORTS'), ('module_scope', 'MODULE SCOPE'),
                        ('call_graph', 'CALL GRAPH EDGES'), ('called_by', 'CALLERS'),
                        ('calls', 'CALLEES')):
        value = state.get(name)
        if not value:
            continue
        if isinstance(value, list):
            rendered = '\n'.join(
                item if isinstance(item, str) else
                f"{item.get('name', '')} ({item.get('path', '')})\n{item.get('source', '')}"
                for item in value)
        else:
            rendered = str(value)
        context.append(f'{title}:\n{rendered}')
    target = (f"PATH: {method.get('path') or side.get('path') or ''}\n"
              f"METHOD: {method.get('name') or side.get('method_name') or ''}\n"
              f"{method.get('source') or side.get('source') or ''}")
    return '\n\n'.join(context), target


def behaviors_for(pair: dict, domain: str, pack: dict):
    if domain == 'lint':
        ensure = ' '.join(pair['rule']['ensure'].split())
        return [{'id': 'rule_satisfied',
                 'definition': 'The target method satisfies this requirement: ' + ensure}], []
    questions = questions_for(pack, domain, pair['language'])
    if not questions:
        raise ValueError(f'No questions for {domain}:{pair["language"]}')
    return [{'id': q['name'], 'definition': issue_definition(q)} for q in questions], questions


def call_api(pair: dict, role: str, behaviors: list[dict], key: str):
    context, target = method_parts(pair, pair[role])
    payload = {'model': MODEL,
               'span': {'input': [{'role': 'user', 'content': context}],
                        'output': {'role': 'assistant', 'content': target}},
               'behaviors': behaviors}
    raw = json.dumps(payload, ensure_ascii=False).encode()
    for attempt in range(9):
        request = Request(API, data=raw, method='POST',
                          headers={'Authorization': f'Bearer {key}',
                                   'Content-Type': 'application/json'})
        try:
            with urlopen(request, timeout=120) as response:
                result = json.load(response)
            break
        except HTTPError as exc:
            if exc.code not in (429, 500, 502, 503, 504) or attempt == 8:
                raise RuntimeError(f'Span-01 HTTP {exc.code} for {pair["pair_id"]}:{role}') from None
            try:
                seconds = float(json.loads(exc.read()).get('retry_after', 0))
            except (ValueError, TypeError, AttributeError):
                seconds = 0
            time.sleep(max(seconds, min(60, 2 ** attempt)))
        except URLError:
            if attempt == 8:
                raise RuntimeError(f'Span-01 network failure for {pair["pair_id"]}:{role}') from None
            time.sleep(min(60, 2 ** attempt))
    if result.get('model') != MODEL:
        raise ValueError(f'Unexpected model: {result.get("model")}')
    by_id = {item['id']: item for item in result['results']}
    if by_id.keys() != {b['id'] for b in behaviors}:
        raise ValueError('Missing or duplicate behavior result')
    for item in by_id.values():
        values = [item[k] for k in ('p_present', 'p_absent', 'p_not_observable')]
        if not all(isinstance(p, (float, int)) and math.isfinite(p) and 0 <= p <= 1
                   for p in values) or abs(sum(values) - 1) > .01:
            raise ValueError('Invalid behavior probabilities')
    return by_id, result.get('usage') or {}


def predicted_row(pair: dict, role: str, domain: str, pack: dict, key: str):
    behaviors, questions = behaviors_for(pair, domain, pack)
    answers, usage = call_api(pair, role, behaviors, key)
    if domain == 'lint':
        scores = {'rule_violation': answers['rule_satisfied']['p_absent']}
        unknown = {'rule_violation': answers['rule_satisfied']['p_not_observable']}
        alert = scores['rule_violation'] > .7
    else:
        scores = {name: item['p_present'] for name, item in answers.items()}
        unknown = {name: item['p_not_observable'] for name, item in answers.items()}
        alert = any(scores[q['name']] > max(.5, (q.get('min') or 0) / 100)
                    for q in questions)
    return {'domain': domain, 'pair_id': pair['pair_id'], 'role': role,
            'score': max(scores.values()), 'question_scores': scores,
            'not_observable': unknown, 'alert': alert, 'usage': usage,
            'model_revision': REVISION, 'protocol_id': PROTOCOL,
            'pack_sha256': pack['pack_sha256'] if domain != 'lint' else None}


def score_report(pairs: list[dict], predictions: dict, domain: str, pack: dict, digest: str):
    if domain != 'lint':
        report = core.report(pairs, predictions, domain, digest, REVISION,
                             pack['protocol_id'], .5, pack)
        report['protocol_id'] = PROTOCOL
    else:
        items = []
        for pair in pairs:
            for role in ('before', 'after'):
                row = predictions[pair['pair_id'], role]
                label = pair[role]['labels'][pair['domain']]
                items.append((label, row['score'], row['score'] > .7))
        tp = sum(y and a for y, _, a in items)
        fp = sum(not y and a for y, _, a in items)
        fn = sum(y and not a for y, _, a in items)
        tn = sum(not y and not a for y, _, a in items)
        eligible = correct = ties = 0
        for pair in pairs:
            if pair['before']['labels'][pair['domain']] and not pair['after']['labels'][pair['domain']]:
                eligible += 1
                a = predictions[pair['pair_id'], 'before']['score']
                b = predictions[pair['pair_id'], 'after']['score']
                correct += a > b
                ties += a == b
        precision = tp / (tp + fp) if tp + fp else 0.0
        recall = tp / (tp + fn) if tp + fn else 0.0
        report = {'domain': 'lint', 'model_revision': REVISION, 'protocol_id': PROTOCOL,
                  'threshold': .7, 'alert_rule': 'rule violation score > 0.7',
                  'benchmark_sha256': digest, 'benchmark_pairs': len(pairs),
                  'benchmark_methods': len(items),
                  'average_precision': core.average_precision([(y, s) for y, s, _ in items]),
                  'precision': precision, 'recall': recall,
                  'f1': 2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else 0.0,
                  'confusion': {'tp': tp, 'fp': fp, 'tn': tn, 'fn': fn},
                  'vulnerable_or_buggy_before_above_fixed_after':
                  {'correct': correct, 'ties': ties, 'eligible': eligible}}
    tokens = sum((row.get('usage') or {}).get('input_tokens', 0) for row in predictions.values())
    report['input_tokens'] = tokens
    report['inference_cost_usd'] = tokens * .02 / 1_000_000
    report['methods_max_not_observable_over_50pct'] = sum(
        max(row['not_observable'].values()) > .5 for row in predictions.values())
    return report


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--domain', choices=('bug', 'security', 'lint'), required=True)
    parser.add_argument('--dataset', type=Path, help='Local benchmark.jsonl; defaults to public HF pairs')
    parser.add_argument('--question-pack', type=Path, default=Path(__file__).with_name('question-pack.json'))
    parser.add_argument('--predictions', type=Path, required=True)
    parser.add_argument('--report', type=Path, required=True)
    parser.add_argument('--limit', type=int, default=0, help='New method sides to score this run; 0 means all')
    parser.add_argument('--score-saved', action='store_true', help='Only score complete saved predictions')
    args = parser.parse_args()
    if args.limit < 0:
        parser.error('--limit must be nonnegative')
    pack = core.load_pack(args.question_pack)
    pairs, digest = load_data(args.domain, args.dataset)
    expected = {(pair['pair_id'], role) for pair in pairs for role in ('before', 'after')}
    predictions = {}
    if args.predictions.exists():
        for line in args.predictions.read_text().splitlines():
            if not line:
                continue
            row = json.loads(line)
            identity = row['pair_id'], row['role']
            if (identity not in expected or identity in predictions or row['domain'] != args.domain
                    or row.get('protocol_id') != PROTOCOL):
                raise ValueError(f'Unknown, duplicate, or wrong-protocol prediction: {identity}')
            predictions[identity] = row
    pending = [(pair, role) for pair in pairs for role in ('before', 'after')
               if (pair['pair_id'], role) not in predictions]
    if args.score_saved and pending:
        raise ValueError(f'Incomplete: {len(pending)} method sides missing')
    if args.limit:
        pending = pending[:args.limit]
    if pending:
        key = os.getenv('RESPAN_API_KEY')
        if not key:
            raise RuntimeError('Set RESPAN_API_KEY to run Span-01')
        args.predictions.parent.mkdir(parents=True, exist_ok=True)
        with args.predictions.open('a') as output:
            for index, (pair, role) in enumerate(pending, 1):
                row = predicted_row(pair, role, args.domain, pack, key)
                predictions[pair['pair_id'], role] = row
                output.write(json.dumps(row, sort_keys=True) + '\n')
                output.flush()
                if index % 100 == 0 or index == len(pending):
                    print(f'Scored {len(predictions)}/{len(expected)} method sides', file=sys.stderr)
    if predictions.keys() != expected:
        print(f'Incomplete: {len(predictions)}/{len(expected)}; rerun to resume', file=sys.stderr)
        return
    result = score_report(pairs, predictions, args.domain, pack, digest)
    args.report.parent.mkdir(parents=True, exist_ok=True)
    args.report.write_text(json.dumps(result, indent=2, sort_keys=True) + '\n')
    print(json.dumps(result, sort_keys=True))


if __name__ == '__main__':
    main()