File size: 12,605 Bytes
22ab540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
"""Build mini-BAC-Bench: a 10-case subset of BAC-Bench chosen offline from existing results.

No new runs. Inputs:
  authz_instances.jsonl  BAC-Bench records: data/authz_instances.jsonl of
                         github.com/avduarte333/Absentia at commit 80e30361 (not redistributed
                         here; pass its path with --records)
  frame_haiku.json       Frame hunt, Claude Haiku 5.5, all 30 cases (runs h4 + h5), scored by
                         the deterministic matcher (benchmarks/bacbench/score.py)
  runs.json              per-case scorer outcome of every Frame run in lambdasec/frame-agent-traces

Selection (simulated annealing, fixed seed) minimises the gap between the subset and the full
benchmark on: language mix, framework family mix, CWE mix, the Haiku outcome mix
(paired / detected-only / miss) and where the misses happened (never mapped / judged safe), with
at most one case per application, a scan-cost budget, and a penalty for cases known to flip
between repeated runs. The DeepSeek run is NOT used for selection: it is the held-out check.

Usage: python build.py --records PATH/TO/authz_instances.jsonl   (writes data/, analysis/)
"""

from __future__ import annotations

import csv
import itertools
import json
import math
import random
import statistics
from collections import Counter
from pathlib import Path

HERE = Path(__file__).resolve().parent
SEED = 20261201
K = 10
COST_BUDGET = 0.25          # share of the full benchmark's scan time
RANDOM_SUBSETS = 2000

# Left out, with the reason recorded in the output.
EXCLUDED = {
    "pretix-ghsa-pmjj-h5jm-vxh4": "cost: 159 min of scan time (the engine pre-scan of a large Django app)",
    "mlflow-ghsa-46r5-x6jq-v8g6": "cost: 100 min of scan time",
    "askbot-devel-ghsa-r2jv-fwfr-4j8c": "scorer-limited: the hunt names the mechanism but the matcher's regions cannot credit it",
    "git-proxy-ghsa-39p2-8hq9-fwj6": "scorer-limited: the matcher credits a different flaw in the same code",
}
# Outcomes known to change between repeated runs of the same system on the same case.
# Frame: runs h1-h3 (Haiku, same harness). ABSENTIA: Table 3 of arXiv:2610.00977 (k=5).
UNSTABLE = {
    "actualbudget-actual-qmjj-p7m9-wjrv": "Frame Haiku h1-h4: paired, detected, detected, paired",
    "frangoteam-FUXA-ghsa-8ghr-w65f-j3qr": "Frame Haiku h1-h4: detected, paired, detected, detected",
    "aegra-aegra-ghsa-m98r-6667-4wq7": "ABSENTIA pass@1 0.80 over 5 runs",
    "rallly-ghsa-4j32-25f9-qgfm": "ABSENTIA pass@1 0.60 over 5 runs",
}
ABSENTIA_TABLE3 = {  # pass@1 over 5 runs, the only per-case results the paper gives
    "payload-puck-ghsa-65w6-pf7x-5g85": 1.0, "git-proxy-ghsa-39p2-8hq9-fwj6": 0.0,
    "aegra-aegra-ghsa-m98r-6667-4wq7": 0.8, "actualbudget-actual-qmjj-p7m9-wjrv": 1.0,
    "frangoteam-FUXA-ghsa-8ghr-w65f-j3qr": 1.0, "parse-server-ghsa-5f92-jrq3-28rc": 0.0,
    "rallly-ghsa-4j32-25f9-qgfm": 0.6, "khoj-ghsa-6whj-7qmg-86qj": 1.0,
}
FRAMEWORK_FAMILY = {
    "django": "django", "django-rest-framework": "django", "fastapi": "fastapi", "flask": "flask",
    "express": "express", "koa": "koa", "nextjs-trpc": "other-js", "astro": "other-js",
    "payload": "other-js",
}


def load(records):
    recs = {r["id"]: r for r in map(json.loads, open(records))}
    haiku = json.load(open(HERE / "frame_haiku.json"))["cases"]
    runs = json.load(open(HERE / "runs.json"))
    cases = []
    for cid, r in sorted(recs.items()):
        h = haiku[cid]
        ds = runs["outcome"].get(f"v11|{cid}")
        if ds in (None, "hunt-error"):
            ds = runs["outcome"].get(f"v11b|{cid}")
        if ds == "hunt-error":
            ds = None
        if h["status"] != "miss":
            stage = "found"
        elif not h["in_map"]:
            stage = "never-mapped"
        else:
            stage = "judged-safe"
        cwe = r["expected_cwes"][0] if r["expected_cwes"] else "none"
        cases.append({
            "id": cid,
            "app": r["repo"].rstrip("/").split("/")[-1].lower(),
            "repo": r["repo"],
            "language": r["language"],
            "framework": r["framework"],
            "family": FRAMEWORK_FAMILY.get(r["framework"], r["framework"]),
            "cwe": cwe,
            "n_affected_routes": len(r["affected_routes"]),
            "vulnerable_commit": r["vulnerable_commit"],
            "fixed_commit": r["fixed_commit"],
            "advisory_url": r["advisory_url"],
            "haiku": h["status"],
            "haiku_stage": stage,
            "deepseek": ds,
            "scan_s": h["wall_clock_s"],
            "unstable": UNSTABLE.get(cid, ""),
            "absentia_pass1": ABSENTIA_TABLE3.get(cid),
            "excluded": EXCLUDED.get(cid, ""),
        })
    for c in cases:
        found = [c[s] in ("paired", "detected") for s in ("haiku", "deepseek") if c[s] is not None]
        c["band"] = ("unknown" if len(found) < 2 else
                     {0: "neither", 1: "one", 2: "both"}[sum(found)])
    return cases


def mix(rows, key):
    c = Counter(r[key] for r in rows)
    n = len(rows)
    return {k: v / n for k, v in c.items()}


def tv(a, b):
    """Total-variation distance between two category shares."""
    keys = set(a) | set(b)
    return 0.5 * sum(abs(a.get(k, 0) - b.get(k, 0)) for k in keys)


def known_mix(rows, key):
    rows = [r for r in rows if r[key] is not None]
    return mix(rows, key) if rows else {}


def objective(sub, full, total_cost, systems=("haiku", "deepseek")):
    d = (tv(mix(sub, "language"), mix(full, "language"))
         + tv(mix(sub, "family"), mix(full, "family"))
         + tv(mix(sub, "cwe"), mix(full, "cwe")))
    for system in systems:
        d += 2 * tv(known_mix(sub, system), known_mix(full, system))
    if "haiku" in systems:
        d += tv(mix(sub, "haiku_stage"), mix(full, "haiku_stage"))
    if len(systems) == 2:
        d += 2 * tv(mix([r for r in sub if r["band"] != "unknown"], "band"),
                    mix([r for r in full if r["band"] != "unknown"], "band"))
        d += 0.1 * sum(1 for r in sub if r["deepseek"] is None)
    cost = sum(r["scan_s"] for r in sub) / total_cost
    d += 4 * max(0.0, cost - COST_BUDGET)
    d += 0.05 * sum(1 for r in sub if r["unstable"])
    apps = Counter(r["app"] for r in sub)
    d += 10 * sum(v - 1 for v in apps.values() if v > 1)
    return d


def anneal(pool, full, total_cost, rng, systems=("haiku", "deepseek")):
    cur = rng.sample(pool, K)
    best, best_d = list(cur), objective(cur, full, total_cost, systems)
    cur_d = best_d
    temp = 1.0
    for _ in range(60000):
        i = rng.randrange(K)
        cand = rng.choice([p for p in pool if p not in cur])
        nxt = cur[:i] + [cand] + cur[i + 1:]
        nd = objective(nxt, full, total_cost, systems)
        if nd < cur_d or rng.random() < math.exp((cur_d - nd) / max(temp, 1e-6)):
            cur, cur_d = nxt, nd
            if nd < best_d:
                best, best_d = list(nxt), nd
        temp *= 0.9998
    return sorted(best, key=lambda r: r["id"]), best_d


def rate(rows, system, what):
    vals = [r[system] for r in rows if r[system] is not None]
    if not vals:
        return None
    ok = ("paired",) if what == "paired" else ("paired", "detected")
    return sum(v in ok for v in vals) / len(vals)


def main():
    import argparse
    ap = argparse.ArgumentParser()
    ap.add_argument("--records", default=str(HERE / "authz_instances.jsonl"))
    cases = load(ap.parse_args().records)
    full = cases
    total_cost = sum(r["scan_s"] for r in full)
    pool = [r for r in cases if not r["excluded"]]
    rng = random.Random(SEED)
    chosen, d = anneal(pool, full, total_cost, rng)
    ids = {r["id"] for r in chosen}

    # Fidelity: subset rate vs full rate, against random subsets of the same pool and size.
    fid = {"objective": round(d, 4), "k": K, "pool": len(pool), "systems": {}}
    rng2 = random.Random(SEED + 1)
    curve = []
    for system in ("haiku", "deepseek"):
        for what in ("detected", "paired"):
            f = rate(full, system, what)
            m = rate(chosen, system, what)
            errs = []
            for _ in range(RANDOM_SUBSETS):
                s = rng2.sample(pool, K)
                r_ = rate(s, system, what)
                if r_ is not None:
                    errs.append(abs(r_ - f))
            mini_err = abs(m - f)
            fid["systems"][f"{system}_{what}"] = {
                "full": round(f, 3), "mini": round(m, 3), "abs_error": round(mini_err, 3),
                "random_k_median_error": round(statistics.median(errs), 3),
                "random_k_p90_error": round(sorted(errs)[int(0.9 * len(errs))], 3),
                "share_of_random_subsets_at_least_as_close": round(
                    sum(e <= mini_err + 1e-9 for e in errs) / len(errs), 3),
                "cases_with_result": sum(1 for r in chosen if r[system] is not None),
                "used_in_selection": True,
            }
    # How much does fitting to the systems we have flatter the subset? Select on one system,
    # measure on the other.
    fid["leave_one_system_out"] = {}
    for fit, test in (("haiku", "deepseek"), ("deepseek", "haiku")):
        sub, _ = anneal(pool, full, total_cost, random.Random(SEED), systems=(fit,))
        fid["leave_one_system_out"][f"fit_{fit}_test_{test}"] = {
            what: {"full": round(rate(full, test, what), 3), "mini": round(rate(sub, test, what), 3),
                   "abs_error": round(abs(rate(sub, test, what) - rate(full, test, what)), 3)}
            for what in ("detected", "paired")}
        fid["leave_one_system_out"][f"fit_{fit}_test_{test}"]["cases"] = [r["id"] for r in sub]
    for k in (5, 8, 10, 12, 15, 20):
        row = {"k": k}
        for system in ("haiku", "deepseek"):
            f = rate(full, system, "detected")
            errs = [abs(rate(s, system, "detected") - f)
                    for s in (rng2.sample(pool, k) for _ in range(RANDOM_SUBSETS))
                    if rate(s, system, "detected") is not None]
            row[f"{system}_detected_median_abs_error"] = round(statistics.median(errs), 3)
        curve.append(row)
    fid["cost"] = {"mini_scan_s": sum(r["scan_s"] for r in chosen), "full_scan_s": total_cost,
                   "share": round(sum(r["scan_s"] for r in chosen) / total_cost, 3)}
    fid["mix"] = {key: {"mini": dict(sorted(mix(chosen, key).items())),
                        "full": dict(sorted(mix(full, key).items()))}
                  for key in ("language", "family", "cwe", "haiku", "haiku_stage", "band")}
    fid["one_case_worth"] = 1 / K

    (HERE / "data").mkdir(exist_ok=True)
    (HERE / "analysis").mkdir(exist_ok=True)
    task_fields = ["id", "repo", "language", "framework", "cwe", "n_affected_routes",
                   "vulnerable_commit", "fixed_commit", "advisory_url", "haiku", "haiku_stage",
                   "deepseek", "band", "scan_s", "unstable", "absentia_pass1"]
    rename = {"cwe": "expected_cwe", "haiku": "frame_haiku_5_5", "haiku_stage": "frame_haiku_stage",
              "deepseek": "frame_deepseek_v4_1_flash", "scan_s": "frame_scan_seconds",
              "unstable": "known_run_to_run_flip", "absentia_pass1": "absentia_pass_at_1",
              "band": "found_by_frame_models"}
    with open(HERE / "data" / "tasks.jsonl", "w") as fh:
        for r in chosen:
            fh.write(json.dumps({rename.get(k, k): r[k] for k in task_fields}) + "\n")
    with open(HERE / "analysis" / "cases.csv", "w", newline="") as fh:
        cols = ["id", "language", "framework", "cwe", "n_affected_routes", "haiku", "haiku_stage",
                "deepseek", "band", "scan_s", "unstable", "absentia_pass1", "excluded"]
        w = csv.writer(fh)
        w.writerow(["in_mini"] + [rename.get(c, c) for c in cols])
        for r in cases:
            w.writerow([r["id"] in ids] + [r[c] if r[c] is not None else "" for c in cols])
    with open(HERE / "analysis" / "size_curve.csv", "w", newline="") as fh:
        w = csv.DictWriter(fh, fieldnames=list(curve[0]))
        w.writeheader()
        w.writerows(curve)
    json.dump(fid, open(HERE / "analysis" / "fidelity.json", "w"), indent=1)

    print("chosen:")
    for r in chosen:
        print(f"  {r['id']:40} {r['language'][:3]} {r['framework']:22} {r['cwe']:8} "
              f"haiku={r['haiku']:8} {r['haiku_stage']:12} ds={r['deepseek']} {r['band']} {r['scan_s']}s "
              f"{'UNSTABLE' if r['unstable'] else ''}")
    print(json.dumps({k: v for k, v in fid.items() if k != "mix"}, indent=1))
    print(json.dumps(fid["mix"], indent=1))


if __name__ == "__main__":
    main()