File size: 23,184 Bytes
27587c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
"""Normalize one FrontierCS-2 run archive into a timeline.

Output dir data/normalized/<task>/<model>/:
  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/<i>/    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('<thinking>' + p['thinking'] + '</thinking>')
        elif t == 'redacted_thinking':
            pass
        elif t == 'tool_use' or t == 'server_tool_use':
            out.append(f"<tool_call name={p.get('name')}>{json.dumps(p.get('input'), ensure_ascii=False)}</tool_call>")
        elif t == 'tool_result':
            out.append(f"<tool_result{' error' if p.get('is_error') else ''}>{content_text(p.get('content'))}</tool_result>")
        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"<tool_call name={it.get('name', t)}>{args if isinstance(args, str) else json.dumps(args, ensure_ascii=False)}</tool_call>"))
            elif t.endswith('_output'):
                o = it.get('output')
                msgs.append(('tool', f"<tool_result>{content_text(o) if not isinstance(o, str) else o}</tool_result>"))
            elif t == 'reasoning':
                summ = ' '.join(s.get('text', '') for s in (it.get('summary') or []) if isinstance(s, dict))
                if summ:
                    msgs.append(('assistant', '<reasoning_summary>' + summ + '</reasoning_summary>'))
            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('<reasoning>' + str(m['reasoning_content']) + '</reasoning>')
        parts.append(content_text(m.get('content')))
        for tc in m.get('tool_calls') or []:
            f = tc.get('function', {})
            parts.append(f"<tool_call name={f.get('name')}>{f.get('arguments')}</tool_call>")
        txt = '\n'.join(p for p in parts if p)
        if role == 'tool':
            txt = '<tool_result>' + txt + '</tool_result>'
        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('<reasoning>' + ''.join(reasoning) + '</reasoning>')
    if text:
        out.append(''.join(text))
    for k in sorted(tools, key=lambda x: str(x)):
        out.append(f'<tool_call name={tools[k][0]}>{tools[k][1]}</tool_call>')
    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()