Download codeql_compare.py from perchscan/benchmark-results: direct link, hf CLI and curl.
- Browser
- Download file 19.8 kB
-
https://huggingface.co/datasets/perchscan/benchmark-results/resolve/refs%2Fpr%2F41/codeql_compare.py
- Command line
-
hf download hf://datasets/perchscan/benchmark-results@refs/pr/41/codeql_compare.py
-
curl -L -o codeql_compare.py https://huggingface.co/datasets/perchscan/benchmark-results/resolve/refs%2Fpr%2F41/codeql_compare.py
19.8 kB
| #!/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] | |
| 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() | |