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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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#!/usr/bin/env python3
"""Run CodeQL on the pinned public cohort and compare method-level alerts.

The caller supplies the downloaded public benchmark.jsonl files. GitHub's
CodeQL CLI and query packs are installed separately; this script does not
download or redistribute them.
"""

import argparse
import concurrent.futures
import json
import re
import shutil
import subprocess
import time
from collections import defaultdict
from functools import lru_cache
from pathlib import Path
from zipfile import ZipFile


LANGUAGES = {"python": "python", "javascript": "javascript", "typescript": "javascript",
             "c": "cpp", "c++": "cpp", "cpp": "cpp"}
PACKS = {"python": "1.8.11", "javascript": "2.4.6", "cpp": "1.9.0"}


def rows(path):
    with open(path, encoding="utf-8") as stream:
        for line in stream:
            if line.strip():
                yield json.loads(line)


def selected_pairs(args):
    cohort = None if args.all_supported else json.loads(Path(args.cohort).read_text())
    selected = {}
    for domain in ("bug", "security"):
        repos = set(cohort[domain]) if cohort else None
        selected[domain] = [
            pair for pair in rows(Path(args.data) / domain / "benchmark.jsonl")
            if (repos is None or pair["repository"] in repos)
            and pair["language"].lower() in LANGUAGES
            and all(isinstance(pair[role].get("revision"), str)
                    and re.fullmatch(r"[0-9a-f]{40}", pair[role]["revision"])
                    for role in ("before", "after"))
        ]
    return selected


def run(command, log_path, timeout=None, container_name=None):
    log_path.parent.mkdir(parents=True, exist_ok=True)
    start = time.monotonic()
    with log_path.open("w", encoding="utf-8") as log:
        try:
            result = subprocess.run(command, stdout=log, stderr=subprocess.STDOUT,
                                    timeout=timeout)
            code = result.returncode
        except subprocess.TimeoutExpired:
            if container_name:
                subprocess.run(["docker", "stop", "--time", "2", container_name],
                               stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            log.write(f"CodeQL stage exceeded {timeout} seconds.\n")
            code = 124
    return code, round(time.monotonic() - start, 2)


def prepare_rebench_patches(pairs, root, source_parquet):
    """Recreate SWE-rebench repaired snapshots from its published gold patches."""
    if not source_parquet:
        return
    instances = {}
    for pair in pairs["bug"]:
        if not pair["pair_id"].startswith("swe-rebench:"):
            continue
        if "+" in pair["after"]["revision"]:
            continue
        instance = pair["pair_id"].split(":", 2)[1]
        if not re.fullmatch(r"[A-Za-z0-9_.-]+", instance):
            raise ValueError(f"Invalid instance ID: {instance}")
        instances[instance] = pair
    if not instances:
        return
    quoted = ",".join("'" + instance + "'" for instance in sorted(instances))
    parquet = Path(source_parquet).resolve().as_posix().replace("'", "''")
    query = ("SELECT instance_id,base_commit,patch FROM read_parquet('"
             + parquet + "') WHERE instance_id IN (" + quoted + ")")
    response = subprocess.run(["duckdb", "-json", "-c", query], check=True,
                              capture_output=True, text=True)
    source_rows = {row["instance_id"]: row for row in json.loads(response.stdout)}
    errors = []
    for instance, pair in instances.items():
        source = source_rows.get(instance)
        if not source:
            errors.append({"instance_id": instance, "reason": "missing source patch"})
            continue
        if pair["before"]["revision"] != source["base_commit"]:
            errors.append({"instance_id": instance, "reason": "base commit mismatch"})
            continue
        repo = pair["repository"]
        slug = repo.replace("/", "__")
        git_dir = root / "git" / slug
        checkout = root / "checkouts" / slug / pair["after"]["revision"]
        patch_file = root / "patches" / f"{instance}.patch"
        patch_file.parent.mkdir(parents=True, exist_ok=True)
        patch_file.write_text(source["patch"], encoding="utf-8")
        try:
            if not git_dir.exists():
                git_dir.parent.mkdir(parents=True, exist_ok=True)
                subprocess.run(["git", "clone", "--filter=blob:none", "--no-checkout",
                                f"https://github.com/{repo}.git", str(git_dir)], check=True,
                               stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
            have = subprocess.run(
                ["git", "-C", str(git_dir), "cat-file", "-e",
                 f"{source['base_commit']}^{{commit}}"],
                stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
            ).returncode == 0
            if not have:
                subprocess.run(["git", "-C", str(git_dir), "fetch", "origin",
                                source["base_commit"]], check=True,
                               stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
            if not checkout.exists():
                checkout.parent.mkdir(parents=True, exist_ok=True)
                subprocess.run(["git", "-C", str(git_dir), "worktree", "add", "--detach",
                                str(checkout), source["base_commit"]], check=True,
                               stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
                subprocess.run(["git", "-C", str(checkout), "apply", "--whitespace=nowarn",
                                str(patch_file)], check=True,
                               stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
        except subprocess.CalledProcessError as error:
            errors.append({"instance_id": instance,
                           "reason": f"{error.cmd[0]} exited {error.returncode}"})
    (root / "patch-errors.json").write_text(json.dumps(errors, indent=2) + "\n")


def prepare_sources(pairs, root):
    tasks = defaultdict(set)
    for domain, group in pairs.items():
        for pair in group:
            repo = pair["repository"]
            language = LANGUAGES[pair["language"].lower()]
            for role in ("before", "after"):
                tasks[(repo, pair[role]["revision"], language)].add(domain)

    sources = {}
    errors = []
    for repo, revision, language in sorted(tasks):
        if not re.fullmatch(r"[0-9a-f]{40}", revision):
            errors.append({"repository": repo, "revision": revision,
                           "reason": "not a Git commit"})
            continue
        slug = repo.replace("/", "__")
        git_dir = root / "git" / slug
        checkout = root / "checkouts" / slug / revision
        try:
            if not git_dir.exists():
                git_dir.parent.mkdir(parents=True, exist_ok=True)
                subprocess.run(
                    ["git", "clone", "--filter=blob:none", "--no-checkout",
                     f"https://github.com/{repo}.git", str(git_dir)],
                    check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
                )
            if not checkout.exists():
                checkout.parent.mkdir(parents=True, exist_ok=True)
                have = subprocess.run(
                    ["git", "-C", str(git_dir), "cat-file", "-e", f"{revision}^{{commit}}"],
                    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                ).returncode == 0
                if not have:
                    subprocess.run(["git", "-C", str(git_dir), "fetch", "origin", revision],
                                   check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
                subprocess.run(["git", "-C", str(git_dir), "worktree", "add", "--detach",
                                str(checkout), revision], check=True,
                               stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
            sources[(repo, revision, language)] = (checkout, tasks[(repo, revision, language)])
        except subprocess.CalledProcessError as error:
            errors.append({"repository": repo, "revision": revision,
                           "reason": f"{error.cmd[0]} exited {error.returncode}"})
    (root / "source-errors.json").write_text(json.dumps(errors, indent=2) + "\n")
    return sources


def docker(args, name, *command):
    return ["docker", "run", "--rm", "--name", name,
            "-v", f"{Path(args.codeql).resolve()}:/opt/codeql:ro",
            "-v", f"{Path(args.root).resolve()}:/work", args.image,
            "/opt/codeql/codeql", *command]


def scan_one(args, task):
    (repo, revision, language), (checkout, domains) = task
    root = Path(args.root).resolve()
    slug = repo.replace("/", "__")
    stem = f"{slug}-{revision[:12]}-{language}"
    db = root / "dbs" / stem
    log_dir = root / "logs"
    result = {"repository": repo, "revision": revision, "language": language,
              "domains": sorted(domains)}
    if not (db / f"db-{language}").exists():
        if db.exists():
            shutil.rmtree(db)
        container = f"codeql-create-{stem}".lower()
        code, seconds = run(docker(args, container, "database", "create", f"/work/dbs/{stem}",
                                  f"--language={language}", "--build-mode=none",
                                  f"--source-root=/work/checkouts/{slug}/{revision}",
                                  "--threads=4", "--ram=4096"),
                            log_dir / f"{stem}-create.log", args.scan_timeout, container)
        result["create_seconds"] = seconds
        if code:
            result["error"] = f"database create exit {code}"
            return result
    for domain in sorted(domains):
        sarif = root / "sarif" / domain / f"{stem}.sarif"
        if sarif.exists():
            continue
        sarif.parent.mkdir(parents=True, exist_ok=True)
        suite = "security-extended" if domain == "security" else "security-and-quality"
        query = (f"/work/packs/codeql/{language}-queries/{PACKS[language]}/"
                 f"codeql-suites/{language}-{suite}.qls")
        container = f"codeql-{domain}-{stem}".lower()
        code, seconds = run(docker(args, container, "database", "analyze", f"/work/dbs/{stem}",
                                  query, "--format=sarif-latest",
                                  f"--output=/work/sarif/{domain}/{stem}.sarif",
                                  "--threads=4", "--ram=4096"),
                            log_dir / f"{stem}-{domain}-analyze.log", args.scan_timeout,
                            container)
        result[f"{domain}_analyze_seconds"] = seconds
        if code:
            result["error"] = f"{domain} analyze exit {code}"
            return result
    result["ok"] = True
    return result


def scan(args):
    root = Path(args.root).resolve()
    (root / "dbs").mkdir(parents=True, exist_ok=True)
    pairs = selected_pairs(args)
    prepare_rebench_patches(pairs, root, args.rebench_parquet)
    sources = prepare_sources(pairs, root)
    print(f"Fixed cohort: {len(pairs['bug'])} bug pairs, "
          f"{len(pairs['security'])} security pairs, {len(sources)} databases", flush=True)
    manifest = {domain: [p["pair_id"] for p in group] for domain, group in pairs.items()}
    (root / "cohort-pair-ids.json").write_text(json.dumps(manifest, indent=2) + "\n")
    with concurrent.futures.ThreadPoolExecutor(max_workers=args.jobs) as executor:
        for result in concurrent.futures.as_completed(
            [executor.submit(scan_one, args, task) for task in sources.items()]
        ):
            item = result.result()
            with (root / "scan-status.jsonl").open("a", encoding="utf-8") as stream:
                stream.write(json.dumps(item, sort_keys=True) + "\n")
            print(f"{'OK' if item.get('ok') else 'FAILED'} "
                  f"{item['repository']} {item['revision'][:12]} "
                  f"{','.join(item['domains'])}", flush=True)


def method_span(side):
    lines = [int(match) for match in re.findall(r"(?m)^L(\d+)\|",
                                                 side["state"]["method"]["source"])]
    return (min(lines), max(lines)) if lines else None


def source_matches(side, source_path):
    content = source_path.read_text(errors="replace").replace("\r\n", "\n")
    needle = side["source"].replace("\r\n", "\n").strip()
    start = content.find(needle)
    return start >= 0 and content.count("\n", 0, start) + 1 == method_span(side)[0]


@lru_cache(maxsize=128)
def archived_sources(archive):
    with ZipFile(archive) as zipped:
        return set(zipped.namelist())


def codeql_alert(sarif, side, domain):
    path = side["path"].lstrip("/")
    span = method_span(side)
    if not span:
        raise ValueError(f"Missing line-numbered method: {path}")
    data = json.loads(sarif.read_text())
    alerts = []
    for run_data in data["runs"]:
        rule_tags = {
            rule["id"]: set(rule.get("properties", {}).get("tags", []))
            for rule in run_data["tool"]["driver"].get("rules", [])
        }
        for finding in run_data.get("results", []):
            tags = rule_tags.get(finding["ruleId"], set())
            if domain == "security" and "security" not in tags:
                continue
            if domain == "bug" and not tags.intersection(
                ("correctness", "reliability", "security")
            ):
                continue
            for location in finding.get("locations", [])[:1]:
                physical = location.get("physicalLocation", {})
                uri = physical.get("artifactLocation", {}).get("uri", "")
                region = physical.get("region", {})
                if uri.lstrip("/") != path or "startLine" not in region:
                    continue
                start = region["startLine"]
                end = region.get("endLine", start)
                if start <= span[1] and end >= span[0]:
                    alerts.append(finding["ruleId"])
    return sorted(set(alerts))


def metrics(items):
    items = list(items)
    tp = sum(label and alert for label, alert in items)
    fp = sum(not label and alert for label, alert in items)
    fn = sum(label and not alert for label, alert in items)
    tn = sum(not label and not alert for label, alert in items)
    precision = tp / (tp + fp) if tp + fp else None
    recall = tp / (tp + fn) if tp + fn else 0.0
    fpr = fp / (fp + tn) if fp + tn else 0.0
    f1 = (2 * precision * recall / (precision + recall)
          if precision is not None and precision + recall else 0.0)
    return {"tp": tp, "fp": fp, "fn": fn, "tn": tn, "precision": precision,
            "recall": recall, "fpr": fpr, "f1": f1, "recall_minus_fpr": recall - fpr}


def score(args):
    root = Path(args.root).resolve()
    selected = selected_pairs(args)
    all_results = {}
    for domain, group in selected.items():
        jev = {(r["pair_id"], r["role"]): r for r in
               rows(Path(args.predictions) / domain / "jev.jsonl")}
        output = []
        unavailable = []
        for pair in group:
            decisions = []
            for role in ("before", "after"):
                side = pair[role]
                lang = LANGUAGES[pair["language"].lower()]
                stem = f"{pair['repository'].replace('/', '__')}-{side['revision'][:12]}-{lang}"
                sarif = root / "sarif" / domain / f"{stem}.sarif"
                source_path = (root / "checkouts" / pair["repository"].replace("/", "__")
                               / side["revision"] / side["path"])
                if not sarif.exists() or (pair["pair_id"], role) not in jev:
                    reason = ("source snapshot unavailable" if not source_path.exists()
                              else "CodeQL analysis unavailable" if not sarif.exists()
                              else "Jev prediction unavailable")
                    unavailable.append({"pair_id": pair["pair_id"], "role": role,
                                        "reason": reason})
                    decisions = []
                    break
                archive = root / "dbs" / stem / "src.zip"
                archived_name = (f"work/checkouts/{pair['repository'].replace('/', '__')}/"
                                 f"{side['revision']}/{side['path']}")
                if not source_path.exists():
                    unavailable.append({"pair_id": pair["pair_id"], "role": role,
                                        "reason": "source snapshot unavailable"})
                    decisions = []
                    break
                if (not archive.exists()
                        or archived_name not in archived_sources(archive)
                        or not source_matches(side, source_path)):
                    unavailable.append({"pair_id": pair["pair_id"], "role": role,
                                        "reason": "target source not verified in CodeQL database"})
                    decisions = []
                    break
                rules = codeql_alert(sarif, side, domain)
                label = int(side["labels"][domain])
                decisions.append({"role": role, "label": label, "codeql_alert": bool(rules),
                                  "codeql_rules": rules,
                                  "jev_alert": bool(jev[(pair["pair_id"], role)]["alert"]),
                                  "jev_score": jev[(pair["pair_id"], role)]["score"]})
            if decisions:
                output.append({"pair_id": pair["pair_id"], "repository": pair["repository"],
                               "language": pair["language"], "decisions": decisions})
        model_scores = {}
        for model in ("codeql", "jev"):
            model_scores[model] = metrics(
                (d["label"], d[f"{model}_alert"]) for row in output for d in row["decisions"]
            )
        all_results[domain] = {"pairs": len(output), "requested_pairs": len(group),
                               "missing_sides": unavailable, "models": model_scores}
        out = root / f"{domain}-codeql-comparison.jsonl"
        out.write_text("".join(json.dumps(r, sort_keys=True) + "\n" for r in output))
    (root / "codeql-comparison-results.json").write_text(
        json.dumps(all_results, indent=2, sort_keys=True) + "\n"
    )
    print(json.dumps(all_results, indent=2))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("operation", choices=("scan", "score"))
    parser.add_argument("--root", required=True)
    parser.add_argument("--data", required=True, help="directory with bug/security/benchmark.jsonl")
    parser.add_argument("--predictions", required=True, help="directory with bug/security/jev.jsonl")
    parser.add_argument("--cohort", default=str(Path(__file__).with_name("codeql-cohort.json")))
    parser.add_argument("--all-supported", action="store_true",
                        help="scan every pair in supported languages with two Git revisions")
    parser.add_argument("--codeql", help="unpacked CodeQL CLI directory")
    parser.add_argument("--rebench-parquet", help="SWE-rebench-V2 source Parquet with gold patches")
    parser.add_argument("--image", default="node:22-bookworm")
    parser.add_argument("--jobs", type=int, default=4)
    parser.add_argument("--scan-timeout", type=int, default=600,
                        help="seconds allowed per CodeQL database or analysis stage")
    args = parser.parse_args()
    if args.operation == "scan":
        if not args.codeql:
            parser.error("--codeql is required for scanning")
        scan(args)
    else:
        score(args)


if __name__ == "__main__":
    main()