"""Normalize one FrontierCS-2 run archive into a timeline. Output dir data/normalized///: meta.json run-level metadata nodes.json submissions (train + final) in submission order, with submit/result times and scores units.jsonl chronological transcript units {t, thread, kind, text}; t in unix ms payloads// files of node i's submitted payload (size capped) Usage: python -I scripts/extract.py [--jobs N] [--only task/model ...] """ import argparse, csv, hashlib, io, json, os, re, sys, tarfile, traceback from datetime import datetime, timezone from multiprocessing import Pool import zstandard ROOT = 'data/hf_raw/' OUT = 'data/normalized/' MAXMSG = 16000 # cap per transcript unit MAXPAYLOAD_FILE = 400_000 MAXPAYLOAD_TOTAL = 2_000_000 CROCK = '0123456789ABCDEFGHJKMNPQRSTVWXYZ' def ulid_ms(s): m = re.search(r'([0-9A-HJKMNP-TV-Z]{26})', s) if not m: return None v = 0 for ch in m.group(1)[:10]: v = v * 32 + CROCK.index(ch) return v def iso_ms(s): s = s.rstrip('Z') if '.' in s: a, b = s.split('.') s = a + '.' + b[:6] return int(datetime.fromisoformat(s).replace(tzinfo=timezone.utc).timestamp() * 1000) def cap(s, n=MAXMSG): if s is None: return '' if not isinstance(s, str): s = json.dumps(s, ensure_ascii=False) if len(s) <= n: return s h = int(n * 0.65) t = n - h return s[:h] + f'\n...[{len(s) - n} chars truncated]...\n' + s[-t:] B64 = re.compile(r'[A-Za-z0-9+/=]{2000,}') def clean(s): return B64.sub('[base64 blob removed]', s) # ---------------------------------------------------------------- message normalisation def content_text(c): """Flatten a content field (str | list of parts) into text.""" if c is None: return '' if isinstance(c, str): return c if isinstance(c, dict): c = [c] out = [] for p in c: if isinstance(p, str): out.append(p) continue if not isinstance(p, dict): continue t = p.get('type', '') if t in ('text', 'input_text', 'output_text'): out.append(p.get('text', '')) elif t in ('image', 'image_url', 'input_image'): out.append('[image]') elif t == 'thinking': if p.get('thinking'): out.append('' + p['thinking'] + '') elif t == 'redacted_thinking': pass elif t == 'tool_use' or t == 'server_tool_use': out.append(f"{json.dumps(p.get('input'), ensure_ascii=False)}") elif t == 'tool_result': out.append(f"{content_text(p.get('content'))}") elif 'text' in p: out.append(str(p['text'])) else: out.append(json.dumps(p, ensure_ascii=False)[:2000]) return '\n'.join(x for x in out if x) def norm_messages(req): """Return list of (role, text) for chat / anthropic / responses request bodies.""" msgs = [] if 'input' in req and 'messages' not in req: # OpenAI responses if req.get('instructions'): msgs.append(('system', content_text(req['instructions']))) inp = req['input'] if isinstance(inp, str): inp = [{'type': 'message', 'role': 'user', 'content': inp}] for it in inp: if not isinstance(it, dict): msgs.append(('user', str(it))) continue t = it.get('type', 'message') if t == 'message' or ('role' in it and t not in ('function_call', 'function_call_output')): msgs.append((it.get('role', 'user'), content_text(it.get('content')))) elif t in ('function_call', 'custom_tool_call', 'local_shell_call', 'tool_search_call', 'web_search_call'): args = it.get('arguments') or it.get('input') or it.get('action') or '' msgs.append(('assistant', f"{args if isinstance(args, str) else json.dumps(args, ensure_ascii=False)}")) elif t.endswith('_output'): o = it.get('output') msgs.append(('tool', f"{content_text(o) if not isinstance(o, str) else o}")) elif t == 'reasoning': summ = ' '.join(s.get('text', '') for s in (it.get('summary') or []) if isinstance(s, dict)) if summ: msgs.append(('assistant', '' + summ + '')) elif t in ('compaction', 'compaction_summary'): msgs.append(('system', '[context compacted]')) else: msgs.append(('other', json.dumps(it, ensure_ascii=False)[:2000])) return msgs if req.get('system'): msgs.append(('system', content_text(req['system']))) for m in req.get('messages', []) or []: role = m.get('role', '?') parts = [] if m.get('reasoning_content'): parts.append('' + str(m['reasoning_content']) + '') parts.append(content_text(m.get('content'))) for tc in m.get('tool_calls') or []: f = tc.get('function', {}) parts.append(f"{f.get('arguments')}") txt = '\n'.join(p for p in parts if p) if role == 'tool': txt = '' + txt + '' msgs.append((role, txt)) return msgs def parse_sse(raw): """Best-effort: assistant text + tool calls from a streamed response (chat, anthropic, responses).""" try: s = raw.decode('utf8', 'replace') except Exception: return '' text, reasoning, tools = [], [], {} final_items = None for line in s.splitlines(): line = line.strip() if not line.startswith('data:'): continue d = line[5:].strip() if d in ('[DONE]', ''): continue try: e = json.loads(d) except Exception: continue t = e.get('type', '') if 'choices' in e: # chat for ch in e.get('choices') or []: dl = ch.get('delta') or {} if dl.get('content'): text.append(dl['content']) if dl.get('reasoning_content'): reasoning.append(dl['reasoning_content']) for tc in dl.get('tool_calls') or []: k = tc.get('index', 0) f = tc.get('function') or {} cur = tools.setdefault(k, ['', '']) if f.get('name'): cur[0] = f['name'] if f.get('arguments'): cur[1] += f['arguments'] elif t == 'content_block_start': cb = e.get('content_block', {}) if cb.get('type') == 'tool_use': tools[e.get('index', 0)] = [cb.get('name', ''), ''] elif t == 'content_block_delta': dl = e.get('delta', {}) if dl.get('type') == 'text_delta': text.append(dl.get('text', '')) elif dl.get('type') == 'thinking_delta': reasoning.append(dl.get('thinking', '')) elif dl.get('type') == 'input_json_delta': tools.setdefault(e.get('index', 0), ['?', ''])[1] += dl.get('partial_json', '') elif t == 'response.completed' or t == 'response.done': final_items = (e.get('response') or {}).get('output') elif t == 'response.output_text.delta': text.append(e.get('delta', '')) elif t == 'response.output_item.done': it = e.get('item', {}) if it.get('type') in ('function_call', 'custom_tool_call'): tools[len(tools)] = [it.get('name', ''), it.get('arguments') or it.get('input') or ''] if final_items and not text and not tools: for it in final_items: if it.get('type') == 'message': text.append(content_text(it.get('content'))) elif it.get('type') in ('function_call', 'custom_tool_call'): tools[len(tools)] = [it.get('name', ''), it.get('arguments') or it.get('input') or ''] out = [] if reasoning: out.append('' + ''.join(reasoning) + '') if text: out.append(''.join(text)) for k in sorted(tools, key=lambda x: str(x)): out.append(f'{tools[k][1]}') return '\n'.join(out) class Threads: """Turns a sequence of full-context requests into incremental transcript units.""" def __init__(self): self.prev = {} # key -> list of hashes self.ids = {} self.units = [] def add(self, t_ms, req, resp_raw=None, t_end=None): msgs = norm_messages(req) if not msgs: return key_src = '\n'.join(m[1][:3000] for m in msgs[:2]) key = hashlib.sha1(key_src.encode('utf8', 'replace')).hexdigest() tid = self.ids.setdefault(key, f'T{len(self.ids)}') hs = [hashlib.sha1((r + '\x00' + x).encode('utf8', 'replace')).hexdigest() for r, x in msgs] prev = self.prev.get(key, []) k = 0 while k < min(len(prev), len(hs)) and prev[k] == hs[k]: k += 1 if prev and k < len(prev): self.units.append({'t': t_ms, 'thread': tid, 'kind': 'marker', 'text': f'[context rewritten: kept {k}/{len(prev)} earlier messages]'}) for (role, txt) in msgs[k:]: self.units.append({'t': t_ms, 'thread': tid, 'kind': role, 'text': cap(clean(txt))}) self.prev[key] = hs if resp_raw is not None: r = parse_sse(resp_raw) if r: # response is only emitted as "pending response" unit; it duplicates the next request's # assistant message, so build_tasks uses it only for the last request of a thread before a cut self.units.append({'t': t_end or t_ms, 'thread': tid, 'kind': 'response', 'text': cap(clean(r))}) def iter_tar(path): with open(path, 'rb') as f: r = zstandard.ZstdDecompressor().stream_reader(f) with tarfile.open(fileobj=r, mode='r|') as t: for m in t: if m.isfile(): yield m.name, t.extractfile(m).read() def extract_payload(blob, dest): os.makedirs(dest, exist_ok=True) total = 0 try: with tarfile.open(fileobj=io.BytesIO(blob)) as t: for m in t: if not m.isfile(): continue name = os.path.normpath(m.name).lstrip('/') if name.startswith('..'): continue data = t.extractfile(m).read() if len(data) > MAXPAYLOAD_FILE: data = data[:MAXPAYLOAD_FILE] + b'\n...[truncated]\n' total += len(data) if total > MAXPAYLOAD_TOTAL: break p = os.path.join(dest, name) os.makedirs(os.path.dirname(p), exist_ok=True) with open(p, 'wb') as fh: fh.write(data) except tarfile.TarError: with open(os.path.join(dest, 'payload.raw'), 'wb') as fh: fh.write(blob[:MAXPAYLOAD_FILE]) # ---------------------------------------------------------------- family A / B (platform evidence) def process_platform(trace, outdir, run, fam): manifest = None reqs = {} # seq -> dict(t, req, resp) verifs = {} # id -> result payloads = {} # id -> (meta, blob) cc_lines = [] # (fname, line) pending_req = {} for name, data in iter_tar(trace): if name == 'manifest.json': manifest = json.loads(data) elif name.startswith('verifications/') and name.endswith('result.json'): d = json.loads(data) verifs[d.get('verification_id') or name.split('/')[1]] = d elif name.startswith('payloads/'): pid = name.split('/')[1] e = payloads.setdefault(pid, [None, None]) if name.endswith('metadata.json'): e[0] = json.loads(data) elif name.endswith('payload.tar'): e[1] = data elif name.startswith('models/primary/traffic/') and (name.endswith('.request.bin') or name.endswith('.response.bin')): seq = int(re.search(r'(\d+)\.(request|response)\.bin$', name).group(1)) pending_req.setdefault(seq, {})['req' if 'request' in name else 'resp'] = data elif name.startswith('agent-traces/claude-code/') and '/events/' in name: cc_lines.append((name, data)) units = [] if fam == 'A': th = Threads() meta_by_seq = {m['request_seq']: m for m in (manifest or {}).get('model_requests', [])} for seq in sorted(pending_req): d = pending_req[seq] mm = meta_by_seq.get(seq) if not mm or 'req' not in d: continue try: req = json.loads(d['req']) except Exception: continue t0 = iso_ms(mm['started_at']) th.add(t0, req, d.get('resp'), t0 + (mm.get('duration_millis') or 0)) units = th.units else: # B: claude code stream-json last_t = 0 cc_lines.sort() buf = b''.join(d if d.endswith(b'\n') else d + b'\n' for _, d in cc_lines) for line in buf.splitlines(): line = line.strip() if not line: continue try: e = json.loads(line) except Exception: continue if 'timestamp' in e: try: last_t = max(last_t, iso_ms(e['timestamp'])) except Exception: pass ty = e.get('type') thread = 'sub:' + e['parent_tool_use_id'][-8:] if e.get('parent_tool_use_id') else 'main' if ty in ('assistant', 'user'): txt = content_text((e.get('message') or {}).get('content')) if txt: units.append({'t': last_t, 'thread': thread, 'kind': ty, 'text': cap(clean(txt))}) elif ty == 'system' and e.get('subtype') == 'init': units.append({'t': last_t, 'thread': thread, 'kind': 'system', 'text': f"[claude code session init: model={e.get('model')}, tools={e.get('tools')}]"}) elif ty == 'system' and e.get('subtype') in ('compact_boundary',): units.append({'t': last_t, 'thread': thread, 'kind': 'marker', 'text': '[context compacted]'}) elif ty == 'system' and e.get('subtype') == 'task_notification': units.append({'t': last_t, 'thread': thread, 'kind': 'system', 'text': f"[background task {e.get('status')}: {e.get('summary')}]"}) # first unit (init) has t=0 -> set to first real timestamp first = next((u['t'] for u in units if u['t']), 0) for u in units: if not u['t']: u['t'] = first # ---- nodes pl = sorted(((ulid_ms(pid) or 0, pid, m, b) for pid, (m, b) in payloads.items() if m), key=lambda x: x[0]) nodes = [] for vid, d in verifs.items(): mode = d.get('mode') nodes.append({'id': vid, 'mode': 'final' if mode == 'eval' else 'train', 't_submit': ulid_ms(vid), 'status': d.get('status'), 'raw_score': d.get('raw_score'), 'summary': d.get('summary'), 'metrics': d.get('metrics')}) nodes.sort(key=lambda n: n['t_submit']) # keep only first eval as the final node (others are re-judgements) finals = [n for n in nodes if n['mode'] == 'final'] nodes = [n for n in nodes if n['mode'] == 'train'] + finals[:1] nodes.sort(key=lambda n: n['t_submit']) # payload matching: latest payload (same purpose) at or before verification time used = set() for n in nodes: want = 'final' if n['mode'] == 'final' else 'train' cands = [p for p in pl if p[0] <= n['t_submit'] + 1000 and p[1] not in used and (p[2].get('purpose') == want)] if cands: p = cands[-1] used.add(p[1]) n['payload_id'] = p[1] n['_blob'] = p[3] # result-visible time: first transcript unit (non-response) mentioning the id together with a score for n in nodes: n['t_result'] = None for u in units: if u['kind'] == 'response': continue if n['id'] in u['text'] and re.search(r'raw_score|"state"\s*:\s*"(passed|failed)|score', u['text']): if u['t'] >= n['t_submit']: n['t_result'] = u['t'] break return units, nodes # ---------------------------------------------------------------- family C (pumpkin) def process_pumpkin(trace, outdir, run): files = {} items = {} log = None for name, data in iter_tar(trace): if name == 'log.jsonl': log = data elif name.startswith('model/items/'): items[name.split('/')[-1]] = data elif re.match(r'model/\d+\.(request|response)$', name): files[name] = data elif re.match(r'jobs/\d+/out/result\.json$', name): files[name] = data elif name.startswith('payloads/'): files[name] = data ev = [json.loads(l) for l in log.splitlines() if l.strip()] base = None for e in ev: if e.get('event', {}).get('kind') == 'run_started': base = int(e['event']['unix_ns']) - int(e['at_ns']) break def T(e): return (base + int(e['at_ns'])) // 1_000_000 def resolve(x): if isinstance(x, str) and x.startswith('sha256:') and len(x) == 71: b = items.get(x[7:]) if b is not None: try: return resolve(json.loads(b)) except Exception: return b.decode('utf8', 'replace') return x if isinstance(x, list): return [resolve(v) for v in x] if isinstance(x, dict): return {k: resolve(v) for k, v in x.items()} return x req_start, req_end = {}, {} jobs = {} final_job = None for e in ev: k = e.get('event', {}).get('kind') E = e.get('event', {}) if k == 'model_request_started': req_start[E['request']] = T(e) elif k == 'model_answered': req_end[E['request']] = T(e) elif k == 'call_started': jobs.setdefault(E['job'], {})['t_submit'] = T(e) elif k == 'target_put' and E.get('path', '').startswith('/pumpkin/in/payload'): jobs.setdefault(E['job'], {})['digest'] = E.get('digest') elif k == 'call_returned': jobs.setdefault(E['job'], {})['t_result'] = T(e) for a in e.get('actions') or []: if a.get('kind') == 'start_final_call': final_job = a['job'] jobs.setdefault(a['job'], {})['t_submit'] = T(e) jobs[a['job']]['digest'] = (a.get('payload') or {}).get('digest') th = Threads() for r in sorted(req_start): q = files.get(f'model/{r}.request') if q is None: continue try: req = resolve(json.loads(q)) except Exception: continue th.add(req_start[r], req, files.get(f'model/{r}.response'), req_end.get(r)) nodes = [] for j, d in jobs.items(): if 't_submit' not in d: continue res = files.get(f'jobs/{j}/out/result.json') res = json.loads(res) if res else {} n = {'id': f'job_{j}', 'mode': 'final' if j == final_job else 'train', 't_submit': d['t_submit'], 't_result': d.get('t_result') if j != final_job else None, 'status': res.get('status'), 'raw_score': res.get('raw_score'), 'summary': res.get('summary'), 'metrics': res.get('metrics')} dg = (d.get('digest') or '').replace('sha256:', '') if dg and f'payloads/{dg}' in files: n['payload_id'] = dg[:16] n['_blob'] = files[f'payloads/{dg}'] nodes.append(n) nodes.sort(key=lambda n: n['t_submit']) return th.units, nodes # ---------------------------------------------------------------- driver def process(args): run, fam = args task, model = run['task'], run['model_id'] outdir = os.path.join(OUT, task, model) if os.path.exists(os.path.join(outdir, 'nodes.json')): return task, model, 'skip' try: trace = ROOT + run['trace_path'] if fam == 'C': units, nodes = process_pumpkin(trace, outdir, run) else: units, nodes = process_platform(trace, outdir, run, fam) units.sort(key=lambda u: u['t']) # stable os.makedirs(outdir, exist_ok=True) for i, n in enumerate(nodes): n['idx'] = i b = n.pop('_blob', None) if b: extract_payload(b, os.path.join(outdir, 'payloads', str(i))) # final node: formal score is the authoritative final score for n in nodes: if n['mode'] == 'final': n['formal_score'] = run.get('score') meta = {k: run.get(k) for k in ('task', 'model_id', 'candidate_name', 'run_id', 'score', 'verdict', 'reference_score', 'n_train_submissions', 'result_source', 'final_submission_status', 'started_at', 'finished_at', 'elapsed_seconds')} meta['family'] = fam with open(os.path.join(outdir, 'units.jsonl'), 'w') as f: for u in units: f.write(json.dumps(u, ensure_ascii=False) + '\n') json.dump(nodes, open(os.path.join(outdir, 'nodes.json'), 'w'), indent=1) json.dump(meta, open(os.path.join(outdir, 'meta.json'), 'w'), indent=1) return task, model, f'ok units={len(units)} nodes={len(nodes)} ntrain_meta={run.get("n_train_submissions")}' except Exception: return task, model, 'ERR ' + traceback.format_exc()[-1500:] def main(): ap = argparse.ArgumentParser() ap.add_argument('--jobs', type=int, default=8) ap.add_argument('--only', nargs='*') a = ap.parse_args() fr = json.load(open(ROOT + 'metadata/formal-results.json')) fams = json.load(open('data/families.json')) runs = fr['runs'] if a.only: runs = [r for r in runs if f"{r['task']}/{r['model_id']}" in a.only] work = [(r, fams[f"{r['task']}/{r['model_id']}"]) for r in runs] work.sort(key=lambda x: -(x[0].get('trace_size_bytes') or 0)) with Pool(a.jobs) as p: for task, model, msg in p.imap_unordered(process, work): print(f'{task}/{model}: {msg}', flush=True) if __name__ == '__main__': main()