envqc-traces / shared /scripts /extract_full.py
vibrant-ani's picture
Add run scripts
3e68beb verified
Raw History Blame Contribute Delete
6.79 kB
"""Pull the full evidence for every task from the raw run folders into one JSON file per task."""
import glob
import json
from pathlib import Path
import pyarrow.parquet as pq
H = Path.home()
R = H / 'ws/runs'
OUT = H / 'review-full'
OUT.mkdir(exist_ok=True)
STEP_CAP, FILE_CAP, TEXT_EXT = 24000, 160000, {'.py', '.sh', '.md', '.toml', '.txt', '.json', '.yaml', '.yml', '.c', '.cpp', '.h', '.rs', '.js', '.ts', '.r', '.R', ''}
def clip(s, n):
s = s or ''
if len(s) <= n:
return s
return s[:n // 2] + f'\n[... {len(s) - n} characters left out ...]\n' + s[-n // 2:]
def read(p, n=FILE_CAP):
try:
return clip(Path(p).read_text(errors='replace'), n)
except Exception:
return None
def one(pattern):
found = sorted(glob.glob(str(R / pattern)))
return json.load(open(found[0])) if found else None
def task_files(d):
out = {}
for rel in ('instruction.md', 'task.toml'):
if (d / rel).exists():
out[rel] = read(d / rel)
for sub in ('tests', 'solution', 'setup_files'):
for f in sorted((d / sub).rglob('*')) if (d / sub).exists() else []:
if f.is_file() and f.suffix in TEXT_EXT and f.stat().st_size < 400000:
out[str(f.relative_to(d))] = read(f)
if (d / 'environment/Dockerfile').exists():
out['environment/Dockerfile'] = read(d / 'environment/Dockerfile')
return out
def steps(trial):
f = trial / 'agent/trajectory.json'
if not f.exists():
return []
rows = []
for s in json.load(open(f)).get('steps', []):
if s.get('source') != 'agent':
continue
keys = '\n'.join((tc.get('arguments') or {}).get('keystrokes', '') for tc in s.get('tool_calls') or [])
obs = ''.join((r.get('content') or '') for r in (s.get('observation') or {}).get('results') or [])
rows.append({'m': clip(s.get('message') or '', 8000), 'k': clip(keys, 8000), 'o': clip(obs, STEP_CAP)})
return rows
def test_list(trial):
try:
ts = json.load(open(trial / 'verifier/ctrf.json'))['results']['tests']
except Exception:
return None
return [{'n': t.get('name', '').split('::')[-1], 's': t.get('status'), 't': clip(t.get('trace') or '', 3000) if t.get('status') != 'passed' else ''} for t in ts]
def checks(verdicts):
out = {}
for v in verdicts or []:
for name, c in (v.get('checks') or {}).items():
out[name] = {'o': c.get('outcome'), 'e': c.get('explanation')}
return out
def trial_row(ao):
d = Path(ao['trial'])
return d.parent.parent.name, {
'steps': steps(d), 'tests': test_list(d),
'stdout': clip(read(d / 'verifier/test-stdout.txt') or '', 12000),
'exception': clip(read(d / 'exception.txt') or '', 4000),
}
def reviews(patterns):
out = {}
for pat in patterns:
for f in glob.glob(str(R / pat)):
for it in json.load(open(f))['items']:
if not it.get('source_trial'):
continue
name = Path(it['source_trial']).parent.parent.name
summ = ''
for a in sorted(glob.glob(it.get('output', '') + '/**/artifacts/analysis.json', recursive=True), key=lambda x: Path(x).stat().st_mtime):
try:
summ = json.load(open(a)).get('summary') or summ
except Exception:
pass
out[name] = {'checks': checks(it.get('verdicts')), 'sum': summ}
return out
def rule_detail(row, fails, task):
try:
det = json.loads(row.get('details') or '{}') if isinstance(row.get('details'), str) else (row.get('details') or {})
except Exception:
det = {}
out = {}
for rule in fails:
d = det.get(rule) or {}
text = {k: v for k, v in d.items() if k not in ('log', 'duration_seconds', 'check', 'task')}
log = d.get('log')
lines = []
if log and Path(log).exists():
body = Path(log).read_text(errors='replace')
parts = body.splitlines()
slug = rule.replace('_', '-')
for i, x in enumerate(parts):
if x.startswith(f'=== {task} /') and (slug in x or rule in x):
for y in parts[i:i + 60]:
lines.append(y)
if y.startswith('=== result'):
break
out[rule] = {'detail': text, 'log': clip('\n'.join(lines), 6000)}
return out
def stage_rows(path):
return {r['task_id']: r for r in pq.read_table(R / path).to_pylist() if r.get('latest') is not False}
def build(run, tasks_dir, s04_path, s6, s62, review_patterns, s5):
rv = reviews(review_patterns)
rows = stage_rows(s04_path)
trials = {}
for pat in (s6, s62):
s = one(pat)
for it in (s or {}).get('items', []):
name = Path(it['task']).name
for ao in it.get('attempt_outcomes') or []:
t, row = trial_row(ao)
row['rev'] = rv.get(t)
trials.setdefault(name, {})[t] = row
for d in sorted(Path(tasks_dir).iterdir()):
if not d.is_dir():
continue
name = d.name
r = rows.get(name, {})
fails = [k for k, v in r.items() if v == 'fail']
data = {'run': run, 'id': name, 'files': task_files(d), 'rules': rule_detail(r, fails, name), 'stage5': s5.get(name, {}), 'tries': trials.get(name, {})}
(OUT / f'{name}.json').write_text(json.dumps(data, ensure_ascii=False, separators=(',', ':')))
s5a = {}
s = one('cf10-s5/stage_5_*/*/summary.json')
for it in s['items']:
s5a[Path(it['task']).name] = {'checks': {k: v for k, v in checks(it.get('verdicts')).items() if v['o'] != 'not_applicable'}}
tasks1 = next((R / 'cf10-s0-4/path-normalization').glob('*/tasks'))
build(1, H / 'ws/samples/cf10-tasks', 'cf10-s0-4/results.parquet', 'cf10-s6/stage_6_*/*/summary.json', 'cf6-s62/stage_6_*/*/summary.json', ['cf10-s8/stage_8_*/*/summary.json'], s5a)
s5b = {}
for j in ('qwen', 'glm', 'deepseek'):
s = one(f'gt40-s5-{j}/stage_5_*/*/summary.json')
for it in (s or {}).get('items', []):
v = {}
for f in sorted(glob.glob(it.get('output', '') + '/**/artifacts/verdicts.json', recursive=True), key=lambda x: Path(x).stat().st_mtime):
try:
v = json.load(open(f))
except Exception:
pass
s5b.setdefault(Path(it['task']).name, {})[j] = {'cat': v.get('category'), 'e': v.get('explanation')}
build(2, H / 'ws/samples/gt40-tasks', 'gt40-s0-4/results.parquet', 'gt40-s6/stage_6_*/*/summary.json', 'gt40-s62/stage_6_*/*/summary.json', ['gt40-s8*-g*/stage_8_*/*/summary.json'], s5b)
print('written', len(list(OUT.glob('*.json'))))