File size: 5,182 Bytes
2a0b0fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Phase 0, measurement A — DECIDABILITY (D).
Frontier oracle (codex gpt-5.6-sol ultra) sees BOTH twins of a PrimeVul pair (so it knows
the ground-truth security fix = the diff) and classifies whether the vulnerability is
judgeable from the VULNERABLE FUNCTION ALONE (intra-procedural) or requires context
OUTSIDE the function (inter-procedural). D = intra fraction = hard ceiling of any
local single-function method. Compare against cppcheck's 2% directional to locate the lever."""
import json, os, re, subprocess, threading, time
from concurrent.futures import ThreadPoolExecutor, as_completed
from huggingface_hub import hf_hub_download
import pyarrow.parquet as pq

N_PAIRS=100; WORKERS=8
CK=os.path.expanduser("~/.cache/phase0_decide_ckpt.jsonl")
TMPDIR="/private/tmp/claude-501/-Users-bert/98b949c0-1b8d-4b6f-a742-3c071ad4b3f3/scratchpad/codex_dec"
os.makedirs(TMPDIR,exist_ok=True)

PROMPT="""You are auditing a security patch. Below are TWO versions of the same function: the VULNERABLE version and the PATCHED (fixed) version. The difference between them is the security fix.

Classify where the deciding signal lives, from the perspective of a detector that sees ONLY the vulnerable function in isolation (no callers, no other files, no repo):

- INTRA = the vulnerability is determinable from the vulnerable function's own text: the unsafe operation and the missing/insufficient guard are both visible inside this function (e.g. a missing bounds/null check before a local buffer op, an unchecked cast, a format-string, integer arithmetic overflow, a use-after-free within the function's own control flow). An expert reading ONLY the vulnerable function could flag it.

- INTER = correctly judging it REQUIRES information outside this function: whether a caller already validated/bounded an argument, the concrete size/type of a parameter defined elsewhere, global/config state, or cross-function aliasing. Reading only the vulnerable function, an expert could NOT reliably decide, because the deciding fact is external.

Think briefly, then output EXACTLY two final lines:
#class: <INTRA or INTER>
#why: <max 15 words naming the exact deciding operation or the exact external fact needed>

VULNERABLE version:
```
{VULN}
```

PATCHED version:
```
{PATCH}
```
"""

CLS=re.compile(r"#class:\s*(INTRA|INTER)",re.I)

def call(vuln, patch, tmpf):
    prompt=PROMPT.format(VULN=vuln[:9000], PATCH=patch[:9000])
    try:
        subprocess.run(["codex","exec","-m","gpt-5.6-sol","-c","model_reasoning_effort=ultra",
                        "--ignore-user-config","--skip-git-repo-check","--output-last-message",tmpf,prompt],
                       stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=300)
        return open(tmpf).read() if os.path.exists(tmpf) else ""
    except Exception:
        return ""

def main():
    p=hf_hub_download("ASSERT-KTH/PrimeVul","data/test_paired-00000-of-00001.parquet",repo_type="dataset")
    t=pq.read_table(p); func=t.column("func").to_pylist(); lab=t.column("is_vulnerable").to_pylist()
    done=set()
    if os.path.exists(CK):
        for l in open(CK):
            try: done.add(json.loads(l)["k"])
            except: pass
    todo=[k for k in range(N_PAIRS) if k not in done]
    print(f"decidability todo {len(todo)}",flush=True)
    lock=threading.Lock(); ck=open(CK,"a"); t0=time.time(); cnt=[0]
    def work(k):
        i0,i1=2*k,2*k+1
        vi=i0 if lab[i0] else i1; pi=i1 if vi==i0 else i0
        out=call(func[vi],func[pi],os.path.join(TMPDIR,f"d{k}.txt"))
        m=None
        for m in CLS.finditer(out): pass
        cls=m.group(1).upper() if m else None
        why=""
        wm=re.search(r"#why:\s*(.+)",out)
        if wm: why=wm.group(1).strip()[:120]
        with lock:
            ck.write(json.dumps({"k":k,"cls":cls,"why":why})+"\n"); ck.flush(); cnt[0]+=1
            if cnt[0]%10==0 or cnt[0]==len(todo):
                print(f"  {cnt[0]}/{len(todo)} ({cnt[0]/(time.time()-t0)*60:.1f}/min)",flush=True)
    with ThreadPoolExecutor(max_workers=WORKERS) as ex:
        for _ in as_completed([ex.submit(work,k) for k in todo]): pass
    ck.close()
    recs={json.loads(l)["k"]:json.loads(l) for l in open(CK)}
    recs=[recs[k] for k in sorted(recs) if k<N_PAIRS]
    intra=sum(1 for r in recs if r["cls"]=="INTRA")
    inter=sum(1 for r in recs if r["cls"]=="INTER")
    unp=sum(1 for r in recs if r["cls"] is None)
    scored=intra+inter or 1
    print(f"\n===== PHASE 0 (A): DECIDABILITY D on {intra+inter} scored pairs ({unp} unparsed) =====")
    print(f"INTRA (judgeable from function alone): {intra}/{scored} = {intra/scored*100:.1f}%   <- D, the ceiling")
    print(f"INTER (needs caller/external context): {inter}/{scored} = {inter/scored*100:.1f}%")
    print("\nsample INTER reasons (why the signal is outside the function):")
    for r in recs:
        if r["cls"]=="INTER" and r["why"]:
            print(f"  - {r['why']}")
    print("\nsample INTRA reasons:")
    n=0
    for r in recs:
        if r["cls"]=="INTRA" and r["why"]:
            print(f"  - {r['why']}"); n+=1
            if n>=8: break

if __name__=="__main__": main()