Download scripts/compare_arms.py from leotrace/ase-benchmark-runs: direct link, hf CLI and curl.
- Browser
- Download file 14.3 kB
-
https://huggingface.co/datasets/leotrace/ase-benchmark-runs/resolve/main/scripts/compare_arms.py
- Command line
-
hf download hf://datasets/leotrace/ase-benchmark-runs/scripts/compare_arms.py
-
curl -L -o compare_arms.py https://huggingface.co/datasets/leotrace/ase-benchmark-runs/resolve/main/scripts/compare_arms.py
14.3 kB
| #!/usr/bin/env python3 | |
| """Paired comparison of two A.S.E batches, as pre-registered for the inscope 38 run. | |
| report_ase_html.py renders raw vs leoprevent. This compares ANY two batches of one agent in one | |
| output directory (raw vs leoprevent, raw vs security-guidance, leoprevent vs security-guidance) | |
| on the two pre-registered units, each with an exact two-sided McNemar test on the discordant | |
| counts (the same binomial as report_ase_html.sign_test): | |
| task-cycle the same task and cycle in both batches, both cells SAFE or VULNERABLE | |
| task majority a task is VULNERABLE in a batch when more than half of its verdict-bearing | |
| cycles are; it enters when each batch has at least one verdict-bearing cycle | |
| and neither is an exact tie | |
| Verdicts come from report_ase_html.load_arm (SAFE = test_case_check AND poc_check), never | |
| re-derived here. A security-guidance cell whose sg_review.json shows no review, or a | |
| baseline_fallback (the reviewer may have seen the masked original), is excluded and counted. | |
| The arm of a batch is read from its name (batch_arm): `<agent>_sg`, `<agent>_corridor_lr` | |
| (corridor-lr, Corridor's long-running agent setup), `<agent>_corridor_dev` (corridor-dev, its | |
| developer setup), `<agent>_corridor` (a Corridor batch of unnamed setup) and `<agent>_commitctl` | |
| (commit-control, the raw agent plus Corridor's commit instruction, the control for corridor-lr). | |
| Pre-registered Corridor exclusions, applied per pair (the cell AND its partner in the other batch | |
| leave both units): a Corridor cell whose `_security/<cell>/corridor_review.json` is missing or | |
| not valid, and a Corridor or commit-control cell (`commit_control.json`) whose agent restored the | |
| original file (restored_original). Bypassed commits and findings closed as false positives are | |
| counted, not excluded: that is pre-registered as the product's behaviour. | |
| compare_arms.py --output-dir <dir> --dataset <ds> --cycles 3 --agent claude_code \ | |
| --a claude_raw --b claude_sg [--json out.json] | |
| compare_arms.py ... --a claude_commitctl --b claude_corridor_lr | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import re | |
| import subprocess | |
| import sys | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| from report_ase_html import SAFE, VULNERABLE, load_arm, sign_test # noqa: E402 | |
| JUDGED = (SAFE, VULNERABLE) | |
| SEGMENT = re.compile(r"[A-Za-z0-9_-]+") # batch names and A.S.E instance ids | |
| def segment(value, what): | |
| """A path segment taken from arguments or the dataset; refuse anything that could leave it.""" | |
| if not SEGMENT.fullmatch(str(value)): | |
| raise SystemExit(f"refusing {what} {value!r}: only letters, digits, '-' and '_' allowed") | |
| return str(value) | |
| def identical_to_base(output_dir, agent, batch, instance, cycle, meta): | |
| """Is the cell's generated target file byte-identical to the task's base commit?""" | |
| root = os.path.realpath(output_dir) | |
| repo = os.path.join(root, "raw_repo", segment(meta["repo"].replace("/", "__"), "repo")) | |
| cell = os.path.join(root, "generated_code", f"{agent}__{batch}", f"{instance}_cycle{int(cycle)}") | |
| try: | |
| orig = subprocess.run(["git", "-C", repo, "show", | |
| f"{meta['base_commit'].strip()}:{meta['vuln_file']}"], | |
| capture_output=True, check=True).stdout | |
| # vuln_file comes from the dataset: a traversal or absolute path must not open a | |
| # file outside the cell. Treated like a missing file (not identical). | |
| target = os.path.realpath(os.path.join(cell, meta["vuln_file"])) | |
| if not target.startswith(os.path.realpath(cell) + os.sep): | |
| return False | |
| with open(target, "rb") as fh: | |
| return bool(orig) and fh.read() == orig | |
| except (OSError, subprocess.CalledProcessError): | |
| return False | |
| def sg_invalid(output_dir, agent, batch, instance, cycle, meta=None, no_diff_valid=True): | |
| """Why a security-guidance cell is not a valid cell of its arm, or None. | |
| Pre-registration amendment 3: a cell whose plugin logged an empty review set because the | |
| generated file is identical to the base commit (nothing differs from HEAD to review) is a | |
| VALID cell, labelled "no diff against HEAD"; --exclude-sg-no-diff is the sensitivity run. | |
| """ | |
| root = os.path.realpath(output_dir) | |
| path = os.path.realpath(os.path.join( | |
| root, "generated_code", f"{segment(agent, 'agent')}__{segment(batch, 'batch')}", | |
| "_security", f"{segment(instance, 'instance id')}_cycle{int(cycle)}", "sg_review.json")) | |
| if not path.startswith(root + os.sep): | |
| raise SystemExit(f"refusing path outside the output directory: {path}") | |
| try: | |
| with open(path, encoding="utf-8") as fh: | |
| review = json.load(fh) | |
| except (OSError, ValueError): | |
| return "no sg_review.json" | |
| if review.get("baseline_fallback"): | |
| return "baseline_fallback" | |
| if not review.get("reviewed"): | |
| if (no_diff_valid and meta and review.get("signal") == "Stop hook: empty review set" | |
| and identical_to_base(output_dir, agent, batch, instance, cycle, meta)): | |
| return None | |
| return f"not reviewed ({review.get('reason') or review.get('signal')})" | |
| return None | |
| BATCH_ARMS = (("_corridor_lr", "corridor-lr"), ("_corridor_dev", "corridor-dev"), | |
| ("_corridor", "corridor"), ("_commitctl", "commit-control"), | |
| ("_sg", "security-guidance"), ("_vortex", "sonar-vortex")) | |
| CORRIDOR_ARMS = ("corridor-lr", "corridor-dev", "corridor") | |
| # Arms with a per-cell validity record (`_security/<cell>/<record>`), excluded per pair when | |
| # invalid or when the agent restored the original file. sonar-vortex: vortex_review.json, valid | |
| # once `sonar link` and `sonar integrate` completed (PREREG-inscope38-sonar-vortex, "Validity"). | |
| RECORD_ARMS = CORRIDOR_ARMS + ("commit-control", "sonar-vortex") | |
| RECORD_NAMES = {"commit-control": "commit_control.json", "sonar-vortex": "vortex_review.json"} | |
| def batch_arm(batch): | |
| """The arm a batch name runs (see the module docstring), or None (raw, lp, anything else).""" | |
| for suffix, arm in BATCH_ARMS: | |
| if batch.endswith(suffix): | |
| return arm | |
| return None | |
| def arm_record(output_dir, agent, batch, instance, cycle, arm): | |
| """The cell's `_security/<cell>/` record for a Corridor, commit-control or sonar-vortex | |
| batch, or None.""" | |
| name = RECORD_NAMES.get(arm, "corridor_review.json") | |
| root = os.path.realpath(output_dir) | |
| path = os.path.realpath(os.path.join( | |
| root, "generated_code", f"{segment(agent, 'agent')}__{segment(batch, 'batch')}", | |
| "_security", f"{segment(instance, 'instance id')}_cycle{int(cycle)}", name)) | |
| if not path.startswith(root + os.sep): | |
| raise SystemExit(f"refusing path outside the output directory: {path}") | |
| try: | |
| with open(path, encoding="utf-8") as fh: | |
| rec = json.load(fh) | |
| except (OSError, ValueError): | |
| return None | |
| return rec if isinstance(rec, dict) else None | |
| def corridor_invalid(rec, arm): | |
| """Why a Corridor or commit-control cell is outside the pre-registered analysis, or None.""" | |
| if rec is None: | |
| return "no " + RECORD_NAMES.get(arm, "corridor_review.json") | |
| if arm in CORRIDOR_ARMS and rec.get("valid") is not True: | |
| return f"corridor_review not valid ({rec.get('reason') or 'no reason recorded'})" | |
| if arm == "sonar-vortex" and rec.get("valid") is not True: | |
| return f"vortex_review not valid ({rec.get('reason') or rec.get('signal') or 'no reason recorded'})" | |
| if rec.get("restored_original"): | |
| return "restored the original file" | |
| return None | |
| def load(output_dir, agent, batch, instances, cycles, metas=None, no_diff_valid=True, info=None): | |
| """{(instance, cycle): verdict} for valid cells, plus {(instance, cycle): reason} excluded. | |
| With `info` (a dict), a Corridor or commit-control batch also fills info["paired"], the | |
| excluded keys whose partner leaves the comparison too, and info["counts"], the Corridor | |
| cells' bypass counts.""" | |
| verdicts, excluded = {}, {} | |
| arm_name = batch_arm(batch) | |
| paired = set() | |
| counts = {"cells": 0, "bypassed": 0, "bypassed_via_fp": 0} | |
| for cycle in cycles: | |
| arm = load_arm(output_dir, agent, batch, cycle) | |
| for inst in instances: | |
| rec = None | |
| if arm_name in RECORD_ARMS: | |
| rec = arm_record(output_dir, agent, batch, inst, cycle, arm_name) | |
| if arm_name in CORRIDOR_ARMS and rec is not None: | |
| counts["cells"] += 1 | |
| counts["bypassed"] += bool(rec.get("bypassed")) | |
| counts["bypassed_via_fp"] += bool(rec.get("bypassed_via_fp")) | |
| if inst not in arm: | |
| excluded[(inst, cycle)] = "not verified" | |
| continue | |
| why = (sg_invalid(output_dir, agent, batch, inst, cycle, (metas or {}).get(inst), | |
| no_diff_valid) if batch.endswith("_sg") else None) | |
| if why is None and arm_name in RECORD_ARMS: | |
| why = corridor_invalid(rec, arm_name) | |
| if why: | |
| paired.add((inst, cycle)) | |
| if why: | |
| excluded[(inst, cycle)] = why | |
| else: | |
| verdicts[(inst, cycle)] = arm[inst] | |
| if info is not None: | |
| info["paired"] = paired | |
| if arm_name in CORRIDOR_ARMS: | |
| info["counts"] = counts | |
| return verdicts, excluded | |
| def majority(verdicts, inst, cycles): | |
| judged = [verdicts[(inst, c)] for c in cycles if verdicts.get((inst, c)) in JUDGED] | |
| vuln = sum(v == VULNERABLE for v in judged) | |
| if not judged or vuln * 2 == len(judged): | |
| return None | |
| return VULNERABLE if vuln * 2 > len(judged) else SAFE | |
| def mcnemar(pairs): | |
| """pairs: [(a_verdict, b_verdict)]. a-only = VULNERABLE in a only (b better).""" | |
| a_only = sum(1 for a, b in pairs if a == VULNERABLE and b == SAFE) | |
| b_only = sum(1 for a, b in pairs if a == SAFE and b == VULNERABLE) | |
| return {"pairs": len(pairs), | |
| "a_vulnerable": sum(a == VULNERABLE for a, _ in pairs), | |
| "b_vulnerable": sum(b == VULNERABLE for _, b in pairs), | |
| "vulnerable_in_a_only": a_only, "vulnerable_in_b_only": b_only, | |
| "p_exact_mcnemar": sign_test(a_only, b_only)} | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--output-dir", required=True) | |
| ap.add_argument("--dataset", required=True) | |
| ap.add_argument("--cycles", type=int, default=3) | |
| ap.add_argument("--agent", required=True, choices=["claude_code", "codex", "cursor", "cosine", "gemini"]) | |
| ap.add_argument("--a", required=True, help="first batch, e.g. claude_raw") | |
| ap.add_argument("--b", required=True, help="second batch, e.g. claude_lp") | |
| ap.add_argument("--exclude-sg-no-diff", action="store_true", | |
| help="sensitivity: also exclude sg cells with no diff against HEAD") | |
| ap.add_argument("--json") | |
| args = ap.parse_args() | |
| segment(args.a, "batch"), segment(args.b, "batch") | |
| with open(args.dataset, encoding="utf-8") as fh: | |
| metas = {segment(d["instance_id"], "instance id"): d for d in json.load(fh)} | |
| instances = sorted(metas) | |
| cycles = list(range(1, args.cycles + 1)) | |
| keep = not args.exclude_sg_no_diff | |
| ia, ib = {}, {} | |
| va, xa = load(args.output_dir, args.agent, args.a, instances, cycles, metas, keep, ia) | |
| vb, xb = load(args.output_dir, args.agent, args.b, instances, cycles, metas, keep, ib) | |
| # A Corridor / commit-control exclusion drops the pair: the partner cell leaves too. | |
| for drop, (v, x) in ((ib["paired"], (va, xa)), (ia["paired"], (vb, xb))): | |
| for k in drop: | |
| if v.pop(k, None) is not None: | |
| x[k] = "partner excluded in the other batch" | |
| def arm_counts(v): | |
| vals = list(v.values()) | |
| return {"vulnerable": vals.count(VULNERABLE), "judged": sum(x in JUDGED for x in vals), | |
| "broken": sum(x not in JUDGED for x in vals)} | |
| cell_pairs = [(va[k], vb[k]) for k in sorted(set(va) & set(vb)) | |
| if va[k] in JUDGED and vb[k] in JUDGED] | |
| task_pairs = [] | |
| for inst in instances: | |
| ma, mb = majority(va, inst, cycles), majority(vb, inst, cycles) | |
| if ma and mb: | |
| task_pairs.append((ma, mb)) | |
| result = {"output_dir": args.output_dir, "agent": args.agent, "a": args.a, "b": args.b, | |
| "cycles": args.cycles, "tasks": len(instances), | |
| "arm_cells": {args.a: arm_counts(va), args.b: arm_counts(vb)}, | |
| "excluded": {args.a: {f"{i}_cycle{c}": r for (i, c), r in sorted(xa.items())}, | |
| args.b: {f"{i}_cycle{c}": r for (i, c), r in sorted(xb.items())}}, | |
| "task_cycle": mcnemar(cell_pairs), "task_majority": mcnemar(task_pairs)} | |
| corridor = {b: i["counts"] for b, i in ((args.a, ia), (args.b, ib)) if "counts" in i} | |
| if corridor: | |
| result["corridor"] = corridor | |
| print(f"{args.agent}: {args.a} vs {args.b} ({os.path.basename(args.output_dir.rstrip('/'))}, " | |
| f"{len(instances)} tasks x {args.cycles} cycles)") | |
| for b in (args.a, args.b): | |
| c = result["arm_cells"][b] | |
| print(f" {b:<12} vulnerable {c['vulnerable']}/{c['judged']} judged cells, {c['broken']} broken, " | |
| f"{len(result['excluded'][b])} excluded") | |
| for unit in ("task_cycle", "task_majority"): | |
| r = result[unit] | |
| print(f" {unit:<14} n={r['pairs']:<4} vulnerable {args.a} {r['a_vulnerable']}, {args.b} " | |
| f"{r['b_vulnerable']}; only in {args.a} {r['vulnerable_in_a_only']}, only in {args.b} " | |
| f"{r['vulnerable_in_b_only']}; exact McNemar p={r['p_exact_mcnemar']:.4g}") | |
| for b in (args.a, args.b): | |
| for cell, why in result["excluded"][b].items(): | |
| print(f" excluded {b} {cell}: {why}") | |
| for b, c in (result.get("corridor") or {}).items(): | |
| print(f" {b}: {c['cells']} Corridor cells, hook bypassed in {c['bypassed']}, committed after " | |
| f"a false-positive close in {c['bypassed_via_fp']} (counted, not excluded)") | |
| if args.json: | |
| with open(args.json, "w", encoding="utf-8") as fh: | |
| json.dump(result, fh, indent=2) | |
| if __name__ == "__main__": | |
| main() | |