dis-bench / analysis /build_data.py
meddyrat's picture
Update from corrected local artifact
1911aea verified
Raw History Blame Contribute Delete
23.4 kB
#!/usr/bin/env python3
"""
Single source of truth for every number, table and figure in the DIS-Bench paper.
Reads the per-attempt evaluation results (experiments/results/ in the released
artifact) and the analysis inputs, and writes into the output directory:
tasks.csv one row per DIS-Bench-Lite task (555)
outcomes.jsonl one row per (config, task): recorded attempts
results.json every aggregate used by the paper
RESULTS.md human-readable version of results.json
Metrics: every configuration has a nominal number of samples per task N (RAG 5,
coding agents 3, GPT-5.4 agents 1, context-ablation runs 1). Per task, pass@k is
the unbiased estimator 1 - C(n-c,k)/C(n,k) over the n recorded attempts (first
record per try_id, try_id < N). Overall scores average over the tasks with at
least one recorded attempt within each program and then weight the 37 programs
equally; category / target-type scores divide by the number of tasks in the group
(a task without recorded attempts counts as unsolved).
Usage: python3 build_data.py
"""
import collections
import csv
import glob
import json
import os
import random
import re
from math import comb
OUT = os.path.dirname(os.path.abspath(__file__))
_ART = os.path.dirname(OUT)
DATASET = os.path.join(_ART, 'dataset.jsonl')
RESULTS = os.path.join(_ART, 'experiments', 'results')
DATA = os.path.join(OUT, 'data')
TYPES_CSV = os.path.join(DATA, 'target_types.csv')
AFLGO_JSON = os.path.join(DATA, 'aflgo_75_targets.json')
TRACE_JSON = os.path.join(DATA, 'reach_trace.json')
FAIL_STATS = os.path.join(DATA, 'failure_mode_stats.json')
OUT = os.path.join(OUT, 'output')
os.makedirs(OUT, exist_ok=True)
# ---------------------------------------------------------------- metadata
CAT = {
'nm-new': 'Binaries', 'objdump': 'Binaries', 'readelf': 'Binaries', 'size': 'Binaries',
'strip-new': 'Binaries', 'bloaty_fuzz_target': 'Binaries',
'exiv2': 'Image', 'imginfo': 'Image', 'jhead': 'Image', 'libjpeg_turbo_fuzzer': 'Image',
'libpng_read_fuzzer': 'Image', 'tiff2ps': 'Image', 'tiffsplit': 'Image', 'stb_stbi_read_fuzzer': 'Image',
'ffmpeg': 'Video/Audio', 'sndfile_fuzzer': 'Video/Audio', 'openh264_decoder_fuzzer': 'Video/Audio',
'vorbis_decode_fuzzer': 'Video/Audio',
'freetype2_ftfuzzer': 'Fonts', 'harfbuzz_hb-shape-fuzzer': 'Fonts', 'woff2_convert_woff2ttf_fuzzer': 'Fonts',
'jq': 'Data Formats', 'sqlite3_ossfuzz': 'Data Formats', 'libpcap_fuzz_both': 'Data Formats',
'lcms_cms_transform_fuzzer': 'Others', 'infotocap': 'Others', 'proj4_proj_crs_to_crs_fuzzer': 'Others',
're2_fuzzer': 'Others',
'mbedtls_fuzz_dtlsclient': 'Network', 'openthread_ot-ip6-send-fuzzer': 'Network', 'tcpdump': 'Network',
'libxml2_xml': 'Documents', 'pdftotext': 'Documents',
'lua': 'Compilers/Interpreters', 'mruby_fuzzer': 'Compilers/Interpreters', 'mujs': 'Compilers/Interpreters',
'php_php-fuzz-parser': 'Compilers/Interpreters',
}
CATS = ['Image', 'Video/Audio', 'Documents', 'Fonts', 'Data Formats', 'Compilers/Interpreters',
'Binaries', 'Network', 'Others']
TYPES = ['semantic_feature', 'input_validation_error', 'boundary_safety', 'algorithmic_state',
'resource_lifecycle', 'metadata_diagnostic_output']
OPEN = ['qwen-3.5-27b', 'qwen-3.5-122b-a10b', 'gemma-4-31b', 'glm-4.7-flash',
'gpt-oss-20b', 'gpt-oss-120b', 'minimax-m2.5']
FRONTIER = ['seed-2.0', 'gpt-5.4']
DISPLAY = {
'qwen-3.5-27b': 'Qwen3.5-27B', 'qwen-3.5-122b-a10b': 'Qwen3.5-122B-A10B', 'gemma-4-31b': 'Gemma4-31B',
'glm-4.7-flash': 'GLM-4.7-Flash', 'gpt-oss-20b': 'GPT-OSS-20B', 'gpt-oss-120b': 'GPT-OSS-120B',
'minimax-m2.5': 'MiniMax-M2.5', 'seed-2.0': 'Seed-2.0', 'gpt-5.4': 'GPT-5.4',
}
METHODS = { # method key -> (method, thinking, nominal N, display)
'rag-nothink': ('rag', 'nothinking', 5, 'RAG-NoThink'),
'rag-think': ('rag', 'thinking', 5, 'RAG-Think'),
'miniswe': ('miniswe', 'nothinking', 3, 'Mini-SWE-Agent'),
'openhands': ('openhands', 'nothinking', 3, 'OpenHands'),
'claude': ('claude', 'nothinking', 3, 'Claude-Code'),
}
AGENTS = ['miniswe', 'openhands', 'claude']
# Context-ablation runs reported in the paper: label -> {model: (method, thinking)}
_LC = 'rag_lc'
ABL = {
'RAG-fo': {'qwen-3.5-27b': ('rag_fo', 'thinking'), 'minimax-m2.5': ('rag_fo', 'thinking')},
'RAG-lc': {'qwen-3.5-27b': (_LC, 'thinking'), 'minimax-m2.5': (_LC, 'thinking')},
'RAG-dense': {'qwen-3.5-27b': ('rag_dense', 'nothinking'), 'minimax-m2.5': ('rag_dense', 'thinking')},
}
def configs():
"""Configurations reported in the paper (proprietary models: coding agents only;
GPT-5.4: one sample per task)."""
out = []
for m in OPEN:
for mk in METHODS:
out.append((m, mk))
for m in FRONTIER:
for mk in AGENTS:
out.append((m, mk))
return out
def nominal(model, mk):
return 1 if (model == 'gpt-5.4' and mk in AGENTS) else METHODS[mk][2]
def cfg_id(model, mk):
return f'{mk}|{model}'
# ---------------------------------------------------------------- loading
def load_tasks():
tasks = [json.loads(l) for l in open(DATASET)]
assert len(tasks) == 555
ty = {}
with open(TYPES_CSV) as f:
for r in csv.DictReader(f):
ty[(r['prog'], int(r['src_site_id']), int(r['to_take']))] = r['category']
for i, t in enumerate(tasks):
t['tid'] = i
t['category'] = CAT[t['prog']]
t['type'] = ty[(t['prog'], t['src_site_id'], t['to_take'])]
return tasks
def load_raw(method, model, thinking):
"""-> {(prog, site, to_take): [record, ...]} (all recorded attempts, file order)"""
P = collections.defaultdict(list)
files = glob.glob(os.path.join(RESULTS, f'{method}_{model}_{thinking}_*.json'))
assert len(files) == 37, (method, model, thinking, len(files))
for fp in sorted(files):
for r in json.load(open(fp))['results']:
P[(r['prog'], r['src_site_id'], r['to_take'])].append(r)
return P
def pass_at_k(n, c, k):
if n == 0:
return 0.0
if n < k:
return 1.0 if c > 0 else 0.0
if n - c < k:
return 1.0
return 1.0 - comb(n - c, k) / comb(n, k)
ANAT = ['Pass', 'Exec success (cov-miss)', 'Code error', 'Missing/invalid output',
'Timeout', 'Resource exceeded', 'No output']
def anat_class(r):
s = r['exec_status']
if s == 'success':
return 'Pass' if r['pass'] else 'Exec success (cov-miss)'
if s in ('syntax_error', 'name_error', 'import_error', 'runtime_error', 'type_error', 'value_error'):
return 'Code error'
if s in ('missing_function', 'no_result'):
return 'Missing/invalid output'
if s == 'timeout':
return 'Timeout'
if s == 'memory_exceeded':
return 'Resource exceeded'
if s == 'missing_generator':
return 'No output'
raise ValueError(s)
FUNNEL = ['pass', 'reach \\ pass', 'sfunc \\ reach', 'miss function', 'no output']
def funnel_class(r):
if r['pass']:
return 'pass'
if r['reach']:
return 'reach \\ pass'
if r['sfunc']:
return 'sfunc \\ reach'
if r['exec_status'] == 'missing_generator':
return 'no output'
return 'miss function'
# ---------------------------------------------------------------- core
class Cfg:
def __init__(self, model, mk, tasks, method=None, thinking=None, N=None):
self.model, self.mk = model, mk
method = method or METHODS[mk][0]
thinking = thinking or METHODS[mk][1]
self.N = N or nominal(model, mk)
raw = load_raw(method, model, thinking)
self.progs = [t['prog'] for t in tasks]
self.att = [] # per task: recorded attempts
self.nextra = self.ndup = 0
for t in tasks:
recs = raw.get((t['prog'], t['src_site_id'], t['to_take']), [])
first = {}
for r in recs:
if r['try_id'] in first:
self.ndup += 1
else:
first[r['try_id']] = r
self.nextra += sum(1 for i in first if i >= self.N)
self.att.append([first[i] for i in sorted(first) if i < self.N])
self.recorded = sum(len(a) for a in self.att)
self.missing_tasks = sum(1 for a in self.att if not a)
def task_score(self, i, k, field='pass'):
a = self.att[i]
return pass_at_k(len(a), sum(bool(r[field]) for r in a), k)
def score(self, k, field='pass', idx=None):
"""overall score if idx is None, otherwise the score of the task group idx"""
if idx is None:
byp = collections.defaultdict(list)
for i, a in enumerate(self.att):
if a:
byp[self.progs[i]].append(self.task_score(i, k, field))
return 100.0 * sum(sum(v) / len(v) for v in byp.values()) / len(byp)
idx = range(len(self.att)) if idx is None else idx
idx = list(idx)
return 100.0 * sum(self.task_score(i, k, field) for i in idx) / len(idx)
def solved(self):
return {i for i, a in enumerate(self.att) if any(r['pass'] for r in a)}
def dist(self, classify, labels):
"""expected per-attempt class shares, aggregated like the overall score
(so the 'pass' share equals pass@1)"""
byp = collections.defaultdict(list)
for i, a in enumerate(self.att):
if not a:
continue
d = collections.Counter()
for r in a:
d[classify(r)] += 1.0 / len(a)
byp[self.progs[i]].append(d)
return {l: 100.0 * sum(sum(d[l] for d in v) / len(v) for v in byp.values()) / len(byp)
for l in labels}
def bootstrap_ci(cfg, tasks, k=1, B=2000, seed=0):
"""95% CI of pass@k, resampling tasks within each program (stratified)."""
rng = random.Random(seed)
byp = collections.defaultdict(list)
for t in tasks:
byp[t['prog']].append(t['tid'])
per = [cfg.task_score(i, k) for i in range(len(tasks))]
vals = []
for _ in range(B):
s = 0.0
for ids in byp.values():
for _ in ids:
s += per[rng.choice(ids)]
vals.append(100.0 * s / len(tasks))
vals.sort()
return vals[int(0.025 * B)], vals[int(0.975 * B) - 1]
def main():
tasks = load_tasks()
R = {'n_tasks': len(tasks)}
# ---- main configurations
C = {}
for model, mk in configs():
C[cfg_id(model, mk)] = Cfg(model, mk, tasks)
by_cat = {c: [t['tid'] for t in tasks if t['category'] == c] for c in CATS}
by_type = {c: [t['tid'] for t in tasks if t['type'] == c] for c in TYPES}
progs = sorted(CAT)
by_prog = {p: [t['tid'] for t in tasks if t['prog'] == p] for p in progs}
R['configs'] = {}
with open(os.path.join(OUT, 'outcomes.jsonl'), 'w') as fo:
for cid, c in C.items():
d = {
'model': c.model, 'method': c.mk, 'display': f'{DISPLAY[c.model]} + {METHODS[c.mk][3]}',
'frontier': c.model in FRONTIER, 'N': c.N,
'recorded_attempts': c.recorded, 'expected_attempts': c.N * len(tasks),
'tasks_without_attempts': c.missing_tasks, 'duplicates_dropped': c.ndup,
'extra_attempts_dropped': c.nextra,
}
for f in ('pass', 'reach', 'sfunc'):
d[f] = {k: c.score(k, f) for k in range(1, c.N + 1)}
d['pass_ci95_k1'] = bootstrap_ci(c, tasks, 1)
for f in ('pass', 'reach', 'sfunc'):
d[f'per_category_{f}'] = {cat: {k: c.score(k, f, ids) for k in range(1, c.N + 1)}
for cat, ids in by_cat.items()}
d['per_type_pass1'] = {ty: c.score(1, 'pass', ids) for ty, ids in by_type.items()}
d['per_program_pass1'] = {p: c.score(1, 'pass', ids) for p, ids in by_prog.items()}
d['funnel'] = c.dist(funnel_class, FUNNEL)
d['anatomy'] = c.dist(anat_class, ANAT)
d['solved'] = sorted(c.solved())
R['configs'][cid] = d
for t, a in zip(tasks, c.att):
fo.write(json.dumps({'config': cid, 'tid': t['tid'], 'N': c.N,
'attempts': [{'try_id': r['try_id'], 'pass': bool(r['pass']),
'reach': bool(r['reach']), 'sfunc': bool(r['sfunc']),
'exec_status': r['exec_status']} for r in a]}) + '\n')
# ---- solved-set analyses
S = {cid: set(d['solved']) for cid, d in R['configs'].items()}
all_t = set(range(len(tasks)))
O = set().union(*[S[cfg_id(m, mk)] for m in OPEN for mk in METHODS])
F = set().union(*[S[cfg_id(m, mk)] for m in FRONTIER for mk in AGENTS])
best_front = max((cfg_id(m, mk) for m in FRONTIER for mk in AGENTS),
key=lambda x: R['configs'][x]['pass'][1])
bf = S[best_front]
R['solved_sets'] = {
'O_open_union': len(O), 'F_minus_O': len(F - O), 'unsolved_all': len(all_t - O - F),
'F_union': len(F), 'best_frontier_config': best_front, 'best_frontier_solved': len(bf),
'best_frontier_in_O': len(bf & O), 'best_frontier_not_in_O': len(bf - O),
}
# method-level UpSet (paper Fig: RAG-Think, MSA, OH, CC), open-only and with frontier
def method_sets(models_rag, models_agent):
# RAG = union of both thinking modes (single convention across the paper)
ms = {'rag': set().union(*[S[cfg_id(m, mk)] for m in models_rag for mk in ('rag-think', 'rag-nothink')])}
for mk in AGENTS:
ms[mk] = set().union(*[S[cfg_id(m, mk)] for m in models_agent])
return ms
def upset(ms):
keys = list(ms)
inter = collections.Counter()
for t in all_t:
sig = tuple(k for k in keys if t in ms[k])
inter[sig] += 1
return {'|'.join(k) if k else '(none)': v for k, v in sorted(inter.items(), key=lambda x: -x[1])}
R['upset_open'] = upset(method_sets(OPEN, OPEN))
R['upset_all'] = upset(method_sets(OPEN, OPEN + FRONTIER))
# final paper figure: RAG = both thinking modes (open-weight), agents = all 9 models,
# so its empty intersection equals R['solved_sets']['unsolved_all'].
ms_final = {'rag': set().union(*[S[cfg_id(m, mk)] for m in OPEN for mk in ('rag-think', 'rag-nothink')])}
for mk in AGENTS:
ms_final[mk] = set().union(*[S[cfg_id(m, mk)] for m in OPEN + FRONTIER])
R['upset_final'] = upset(ms_final)
R['upset_final_hardcore_by_category'] = dict(collections.Counter(
tasks[t]['category'] for t in all_t - set().union(*ms_final.values())))
assert R['upset_final'].get('(none)', 0) == R['solved_sets']['unsolved_all']
for name, agents_models in (('upset_open', OPEN), ('upset_all', OPEN + FRONTIER)):
ms = method_sets(OPEN, agents_models)
solved_any = set().union(*ms.values())
R[name + '_hardcore_by_category'] = dict(collections.Counter(
tasks[t]['category'] for t in all_t - solved_any))
# pairwise Jaccard
ids = list(S)
R['jaccard'] = {a: {b: (len(S[a] & S[b]) / len(S[a] | S[b]) if S[a] | S[b] else 0.0) for b in ids} for a in ids}
# ---- RAG context variants used by the paper's context ablation (1 sample per task)
R['rag_variants'] = {}
for lab, mm in ABL.items():
for model, (v, th) in mm.items():
c = Cfg(model, 'rag-think', tasks, method=v, thinking=th, N=1)
R['rag_variants'][f'{v}|{th}|{model}'] = {'pass1': c.score(1), 'solved': sorted(c.solved()),
'recorded': c.recorded}
# ---- context ablation / dense retrieval exactly as reported in the paper
R['context_ablation_paper'] = {}
for lab, mm in ABL.items():
for model, (v, th) in mm.items():
R['context_ablation_paper'][f'{lab}|{model}'] = {
'run': f'{v}|{th}', 'pass1': R['rag_variants'][f'{v}|{th}|{model}']['pass1'], 'samples': 1}
for model in ('qwen-3.5-27b', 'minimax-m2.5'):
R['context_ablation_paper'][f'RAG|{model}'] = {
'run': 'rag|thinking', 'pass1': R['configs'][cfg_id(model, 'rag-think')]['pass'][1], 'samples': 5}
R['context_ablation_paper'][f'Claude-Code|{model}'] = {
'run': 'claude|nothinking', 'pass1': R['configs'][cfg_id(model, 'claude')]['pass'][1], 'samples': 3}
# ---- AFLGo
A = json.load(open(AFLGO_JSON))
key = {(t['prog'], t['src_site_id']): t['tid'] for t in tasks}
AFLGO_BUDGET = 6 * 3600 # a target counts as reached if AFLGo covers it within 6 hours
aflgo = []
for a in A:
aflgo.append({'tid': key[(a['prog'], a['site_id'])], 'prog': a['prog'],
'reached': a['reached'] and a['elapsed_seconds'] <= AFLGO_BUDGET,
'elapsed': a['elapsed_seconds'], 'seed_mode': a['seed_mode']})
bins = collections.Counter()
for a in aflgo:
if not a['reached']:
bins['>6h (not reached)'] += 1
elif a['elapsed'] < 60: # reached within budget
bins['<1min'] += 1
elif a['elapsed'] < 1800:
bins['1-30min'] += 1
else:
bins['30min-6h'] += 1
pairing = {}
for cid in R['configs']:
s = S[cid]
cnt = collections.Counter()
for a in aflgo:
l, g = a['tid'] in s, a['reached']
cnt['both' if l and g else 'LLM only' if l else 'AFLGo only' if g else 'neither'] += 1
pairing[cid] = dict(cnt)
R['aflgo'] = {'budget_s': AFLGO_BUDGET, 'n_reached': sum(a['reached'] for a in aflgo),
'n': len(aflgo), 'n_programs': len({a['prog'] for a in aflgo}),
'seed_modes': dict(collections.Counter(a['seed_mode'] for a in aflgo)),
'max_elapsed_reached': max(a['elapsed'] for a in aflgo if a['reached']),
'bins': dict(bins), 'pairing': pairing}
# ---- trace statistics (reach_trace.json)
tr = json.load(open(TRACE_JSON))
nb = collections.Counter()
for t in tr:
n = len({l.rsplit(':', 2)[0] for l in t['visited_source_locations']})
nb['<3' if n < 3 else '3-29' if n < 30 else '>=30'] += 1
R['trace'] = {'n_tasks': len(tr), 'n_programs': len({t['prog'] for t in tr}),
'bins_pct': {k: 100.0 * v / len(tr) for k, v in nb.items()}, 'bins': dict(nb)}
# ---- failure-mode audit
st = json.load(open(FAIL_STATS))
R['failure_audit'] = {'sample_size': st['sample_size'], 'label_counts': st['label_counts'],
'failed_attempt_population': st['failed_attempt_population']}
# ---- task table
with open(os.path.join(OUT, 'tasks.csv'), 'w', newline='') as f:
w = csv.writer(f)
w.writerow(['tid', 'prog', 'category', 'type', 'src_site_id', 'to_take', 'source_location',
'aflgo_reached', 'aflgo_elapsed_s'])
am = {a['tid']: a for a in aflgo}
for t in tasks:
a = am.get(t['tid'])
w.writerow([t['tid'], t['prog'], t['category'], t['type'], t['src_site_id'], t['to_take'],
t['source_location'], '' if a is None else a['reached'], '' if a is None else a['elapsed']])
R['type_counts'] = dict(collections.Counter(t['type'] for t in tasks))
R['category_counts'] = dict(collections.Counter(t['category'] for t in tasks))
json.dump(R, open(os.path.join(OUT, 'results.json'), 'w'), indent=1)
write_md(R)
print('-> results.json, RESULTS.md, tasks.csv, outcomes.jsonl in', OUT)
def f1(x):
return f'{x:.1f}'
def write_md(R):
L = ['# DIS-Bench-Lite results', '',
'Generated by `build_data.py`; do not edit by hand.', '']
cf = R['configs']
L += ['## 1. Headline (pass@1 / pass@k_max, reach@1, sfunc@1, 95% CI of pass@1)', '',
'| Config | N | pass@1 | pass@kmax | reach@1 | sfunc@1 | CI95 pass@1 | recorded/expected attempts | tasks w/o attempts |',
'|---|---|---|---|---|---|---|---|---|']
for cid, d in cf.items():
L.append(f"| {d['display']} | {d['N']} | {f1(d['pass'][1])} | {f1(d['pass'][d['N']])} | "
f"{f1(d['reach'][1])} | {f1(d['sfunc'][1])} | {f1(d['pass_ci95_k1'][0])}–{f1(d['pass_ci95_k1'][1])} | "
f"{d['recorded_attempts']}/{d['expected_attempts']} | {d['tasks_without_attempts']} |")
L += ['', '## 2. Solved-set decomposition', '', '```', json.dumps(R['solved_sets'], indent=1), '```', '',
'## 3. Method-level UpSet (union over models)', '', '### open-weight only', '```',
json.dumps(R['upset_open'], indent=1), '```',
'hard core by category: ' + json.dumps(R['upset_open_hardcore_by_category']), '',
'### including frontier models in agent sets', '```', json.dumps(R['upset_all'], indent=1), '```',
'hard core by category: ' + json.dumps(R['upset_all_hardcore_by_category']), '',
'### final figure (RAG = both modes, open-weight; agents = all 9 models)', '```',
json.dumps(R['upset_final'], indent=1), '```',
'hard core by category: ' + json.dumps(R['upset_final_hardcore_by_category']), '']
L += ['## 4. pass@1 per format category', '', '| Config | ' + ' | '.join(CATS) + ' |',
'|---|' + '---|' * len(CATS)]
for cid, d in cf.items():
L.append(f"| {d['display']} | " + ' | '.join(f1(d['per_category_pass'][c][1]) for c in CATS) + ' |')
L += ['', '## 5. pass@1 per target type', '',
'| Config | ' + ' | '.join(f'{t} ({R["type_counts"][t]})' for t in TYPES) + ' |', '|---|' + '---|' * len(TYPES)]
for cid, d in cf.items():
L.append(f"| {d['display']} | " + ' | '.join(f1(d['per_type_pass1'][t]) for t in TYPES) + ' |')
L += ['', '## 6. RAG context variants (pass@1, 1 sample)', '', '| variant | thinking | model | pass@1 |', '|---|---|---|---|']
for k, v in R['rag_variants'].items():
a, b, c = k.split('|')
L.append(f'| {a} | {b} | {c} | {f1(v["pass1"])} |')
L += ['', '### Context ablation as reported in the paper', '', '| label | model | run (method, thinking) | samples | pass@1 |', '|---|---|---|---|---|']
for k, v in R['context_ablation_paper'].items():
a, b = k.split('|')
L.append(f"| {a} | {b} | {v['run']} | {v['samples']} | {f1(v['pass1'])} |")
ag = R['aflgo']
L += ['', '## 7. AFLGo', '', f"n={ag['n']} targets from {ag['n_programs']} programs; budget {ag['budget_s']/3600:.0f} h; reached {ag['n_reached']}; seed modes {ag['seed_modes']}; bins {ag['bins']}", '',
'| Config | both | LLM only | AFLGo only | neither |', '|---|---|---|---|---|']
for cid, p in ag['pairing'].items():
L.append(f"| {cf[cid]['display']} | {p.get('both', 0)} | {p.get('LLM only', 0)} | {p.get('AFLGo only', 0)} | {p.get('neither', 0)} |")
L += ['', '## 8. Trace statistics', '', json.dumps(R['trace']), '', '## 9. Failure-mode audit', '',
json.dumps(R['failure_audit']), '', '## 10. Funnel (expected per-sample shares, %)', '',
'| Config | ' + ' | '.join(FUNNEL) + ' |', '|---|' + '---|' * len(FUNNEL)]
for cid, d in cf.items():
L.append(f"| {d['display']} | " + ' | '.join(f1(d['funnel'][x]) for x in FUNNEL) + ' |')
open(os.path.join(OUT, 'RESULTS.md'), 'w').write('\n'.join(L) + '\n')
if __name__ == '__main__':
main()