File size: 35,931 Bytes
891c713
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
"""v2 forecasting tasks (v49, strict-audit fixes): shared library.

Fixes over v48lib:
1. B_cut / D1 / D5:
   - id_value: id and score/terminal state must be in the SAME single-submission JSON object (or non-JSON result
     line); never pair across objects; strip wrapper fields like "terminal_status":"completed"; reject any unit
     where this submission's id appears with a running/queued/pending state; accept JSON-escaped \\"job\\": N (D5).
   - poll_reply: only for an unambiguous single-submission poll (single tool result in thread, reply carries no
     other id, assistant polled only this id); parallel polls require this submission's own id in the reply.
   - value_early / value_only: removed unless this submission's own id is in the same unit (not running), not an
     observer/safety-rater sidecar prompt, and the nonzero score differs by > 0.005 from every earlier submission.
   - echo_index: visibility-only (makes no cut), requires unique nonzero score not matching any earlier submission
     within 0.005, after polling this specific id (and after call_returned for family C). window_index removed.
2. D2: pair family A/B payloads by platform submit acknowledgement (frontier.candidate-submit-result/v1) and
   verifications/<vid>/evidence.tar metrics.json payload_sha256; mark multi-candidate unpairable train nodes as
   d2_unverifiable so build.py drops tasks whose submissions/ would hold them.
3. D3 / D4: helpers is_d3, is_d4, is_incomplete_final_run, has_trace_final (D9).
4. D7: render_upto middle-truncates above 3,000,000 chars, keeping the first ~200,000 chars (system prompt + task
   statement), a one-line marker '[... N characters omitted ...]', and the tail through unit k (total <= 3,000,000).
"""
import collections, hashlib, io, json, math, os, pickle, re, sys, tarfile

import zstandard

V = os.environ.get('PROPHET_ROOT', '/scratch/gpfs/TRIDAO/ly3223/oraclebench').rstrip('/') + '/'
DATA = V + 'data'
sys.path.insert(0, V + 'scripts')
import extract as X          # noqa: E402  released extractor
import build_tasks as BT     # noqa: E402  released v1 builder (templates, true_score, fmt_dt, TRANSCRIPT_CAP)

SRC = V + 'data/hf_raw/'
MISS = V + 'data/hf_raw/'
AUDIT_NORM = V + 'data/normalized/'            # read-only: meta.json 'family'
PEER_CACHE = V + 'data/v3/no_peer_cache/'            # read-only: verified-exact cache of extract.py output
TEMPL = V + 'scripts/harbor_templates/'

HEAD_CAP = 200_000

VID_RX = re.compile(r'verification_[0-9A-HJKMNP-TV-Z]{26}')
PID_RX = re.compile(r'payload_[0-9A-HJKMNP-TV-Z]{26}')
JOB_JSON_RX = re.compile(r'\\?"job\\?"\s*:\s*(\d+)\b')

SUBMIT_ACK_RX = re.compile(
    r'\\?"payload_id\\?"\s*:\s*\\?"(payload_[0-9A-HJKMNP-TV-Z]{26})\\?"'
    r'(?:(?!verification_01)[^{}]){0,1200}?'
    r'\\?"verification_id\\?"\s*:\s*\\?"(verification_[0-9A-HJKMNP-TV-Z]{26})\\?"'
)

EXTRA_INFRA = re.compile(
    r'Verifier GPU control failed|HarnessInfrastructureFailure|Verifier GPU endpoint returned HTTP|'
    r'Trusted verification measurements are unavailable|Verifier setup exhausted its execution envelope|'
    r'Owned platform provisioning could not complete|Verifier GPU sandbox run failed',
    re.I
)


def trace_path(run):
    p = SRC + run['trace_path']
    return p if os.path.exists(p) else MISS + run['trace_path']


def is_d3(n):
    """D3: train submission with no verifier result (status is None)."""
    return n['mode'] == 'train' and n.get('status') is None


def is_d4(n):
    """D4: train submission that failed due to explicit verifier/platform infrastructure error."""
    return (n['mode'] == 'train' and n.get('status') is not None
            and n.get('status') != 'passed' and bool(EXTRA_INFRA.search(n.get('summary') or '')))


def is_incomplete_final_run(run):
    """D3/D4 final: 5 runs whose official final verification did not complete and was recorded as 0."""
    return run.get('result_source') == 'final verification did not complete; recorded as 0'


def has_trace_final(nodes):
    """D9: whether the trace has an eval/final verification node."""
    return any(n['mode'] == 'final' for n in nodes)


def payload_files(blob):
    """In-memory copy of extract.extract_payload: {relpath: bytes}, same caps."""
    out, 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) > X.MAXPAYLOAD_FILE:
                    data = data[:X.MAXPAYLOAD_FILE] + b'\n...[truncated]\n'
                total += len(data)
                if total > X.MAXPAYLOAD_TOTAL:
                    break
                out[name] = data
    except tarfile.TarError:
        out['payload.raw'] = blob[:X.MAXPAYLOAD_FILE]
    return out


def _payload_digest(pf):
    h = hashlib.sha256()
    for k in sorted(pf):
        h.update(k.encode('utf8') + b'\x00' + pf[k] + b'\x00')
    return h.hexdigest()


def _extract_acks_from_text(s, pairs):
    if 'verification_' not in s or 'payload_' not in s:
        return
    for pid, vid in SUBMIT_ACK_RX.findall(s):
        pairs[vid].add(pid)


def _pair_ab_from_data(units, nodes, payload_meta, payload_pf, evid_p_sha, raw_ack_blobs):
    """Pair Family A/B nodes with exact payloads via submit ack -> evidence.tar payload_sha256 -> single candidate."""
    acks = collections.defaultdict(set)
    for u in units:
        if u['kind'] != 'response':
            _extract_acks_from_text(u['text'], acks)

    still_missing = {n['id']: n['id'].encode() for n in nodes
                     if len(acks.get(n['id'], ())) != 1 and n['id'] not in evid_p_sha}
    if still_missing and raw_ack_blobs:
        for rb in reversed(raw_ack_blobs):
            hits = [vid for vid, vb in still_missing.items() if vb in rb]
            if not hits:
                continue
            s = rb.decode('utf8', 'replace')
            _extract_acks_from_text(s, acks)
            for vid in list(hits):
                if len(acks.get(vid, ())) == 0:
                    for m in re.finditer(re.escape(vid), s):
                        lo = max(0, m.start() - 1500)
                        hi = min(len(s), m.end() + 1500)
                        pvs = list(VID_RX.finditer(s, lo, m.start()))
                        if pvs:
                            lo = pvs[-1].end()
                        nv = VID_RX.search(s, m.end(), hi)
                        if nv:
                            hi = nv.start()
                        nl_b = s.rfind('\n', lo, m.start())
                        nl_a = s.find('\n', m.end(), hi)
                        lseg = s[nl_b + 1 if nl_b != -1 else lo: nl_a if nl_a != -1 else hi]
                        pids = set(PID_RX.findall(lseg))
                        if len(pids) == 1:
                            acks[vid].add(next(iter(pids)))
                if len(acks.get(vid, ())) == 1:
                    still_missing.pop(vid, None)
            if not still_missing:
                break

    payload_ext_dig = {pid: _payload_digest(pf) for pid, pf in payload_pf.items()}
    sha_to_pids = collections.defaultdict(list)
    for pid, (sha, purp, ums) in sorted(payload_meta.items(), key=lambda x: x[1][2]):
        if sha:
            sha_to_pids[(purp, sha)].append(pid)

    new_P = {}
    for n in nodes:
        idx = n['idx']
        vid = n['id']
        want_purp = 'final' if n['mode'] == 'final' else 'train'
        a_set = acks.get(vid, set())
        right_pid = None
        if len(a_set) == 1:
            right_pid = next(iter(a_set))
        elif vid in evid_p_sha:
            cands = sha_to_pids.get((want_purp, evid_p_sha[vid]), [])
            if cands:
                right_pid = cands[0]

        if right_pid is not None:
            if right_pid in payload_pf:
                new_P[idx] = payload_pf[right_pid]
            n['payload_id'] = right_pid
            n['d2_unverifiable'] = False
        else:
            cands_time = [pid for pid, (_, purp, ums) in sorted(payload_meta.items(), key=lambda x: x[1][2])
                          if purp == want_purp and ums <= n['t_submit'] + 1000]
            distinct_ext = {payload_ext_dig.get(pid) for pid in cands_time}
            if len(distinct_ext) <= 1:
                if cands_time and cands_time[-1] in payload_pf:
                    new_P[idx] = payload_pf[cands_time[-1]]
                    n['payload_id'] = cands_time[-1]
                n['d2_unverifiable'] = False
            else:
                n['d2_unverifiable'] = True
    return new_P


def _pair_ab_from_tar_path(path, units, nodes, existing_payloads):
    """Fast D2 check for peer_cache runs: only stream the raw tar if units lack a 1-to-1 ack match."""
    acks = collections.defaultdict(set)
    for u in units:
        if u['kind'] != 'response':
            _extract_acks_from_text(u['text'], acks)
    if all(len(acks.get(n['id'], ())) == 1 and next(iter(acks[n['id']])) == n.get('payload_id') for n in nodes):
        for n in nodes:
            n['d2_unverifiable'] = False
        return existing_payloads

    need_raw = any(len(acks.get(n['id'], ())) != 1 for n in nodes)
    payload_meta, payload_pf, evid_p_sha, raw_ack_blobs = {}, {}, {}, []
    with open(path, 'rb') as fh:
        with tarfile.open(fileobj=zstandard.ZstdDecompressor().stream_reader(fh), mode='r|') as tf:
            for m in tf:
                if not m.isfile():
                    continue
                nm = m.name
                if nm.startswith('payloads/') and nm.endswith('/metadata.json'):
                    md = json.loads(tf.extractfile(m).read())
                    pid = nm.split('/')[1]
                    payload_meta[pid] = (md.get('sha256'), md.get('purpose'), X.ulid_ms(pid) or 0)
                elif nm.startswith('payloads/') and nm.endswith('/payload.tar'):
                    pid = nm.split('/')[1]
                    payload_pf[pid] = payload_files(tf.extractfile(m).read())
                elif nm.startswith('verifications/') and nm.endswith('/evidence.tar'):
                    vid = nm.split('/')[1]
                    try:
                        with tarfile.open(fileobj=io.BytesIO(tf.extractfile(m).read())) as etf:
                            for em in etf:
                                if em.isfile() and em.name.endswith('metrics.json'):
                                    emd = json.loads(etf.extractfile(em).read())
                                    if emd.get('payload_sha256'):
                                        evid_p_sha[vid] = emd['payload_sha256']
                    except Exception:
                        pass
                elif need_raw and ((nm.startswith('agent-traces/claude-code/') and '/events/' in nm)
                                   or (nm.startswith('models/primary/traffic/')
                                       and (nm.endswith('.request.bin') or nm.endswith('.response.bin')))):
                    data = tf.extractfile(m).read()
                    if b'payload_' in data and b'verification_' in data:
                        raw_ack_blobs.append(data)
    return _pair_ab_from_data(units, nodes, payload_meta, payload_pf, evid_p_sha, raw_ack_blobs)


def refine(nodes, units):
    """refine_result_times.py, applied to one run in memory (kept unchanged for v1 rebuild check)."""
    todo = [n for n in nodes if n['mode'] == 'train' and n['t_result'] is None and isinstance(n.get('raw_score'), (int, float))]
    if not todo:
        return
    U = [u for u in units if u['kind'] not in ('response', 'assistant')]
    for n in todo:
        s = n['raw_score']
        pats = {f'{s:.4f}'[:-1], f'{s:.3f}', f'{s:.2f}'} if s not in (0, 100) else set()
        pats = [re.escape(x) for x in pats if len(x.replace('.', '').lstrip('0')) >= 3]
        hit = None
        if pats:
            rx = re.compile('|'.join(pats))
            for u in U:
                if u['t'] >= n['t_submit'] and rx.search(u['text']):
                    hit = u['t']; break
        if hit is not None:
            n['t_result'] = hit; n['t_result_src'] = 'score_digits'


def load_run(run):
    """Return (family, units, nodes, payloads, source) with D2 pairing and refine applied."""
    pc = os.path.join(PEER_CACHE, run['task'], run['model_id'] + '.pkl.zst')
    if os.path.exists(pc):
        with open(pc, 'rb') as f:
            d = pickle.loads(zstandard.ZstdDecompressor().stream_reader(f).read())
        fam, units, nodes, payloads, src = d['meta']['family'], d['units'], d['nodes'], d['payloads'], 'peer_cache'
        if fam != 'C' and nodes:
            payloads = _pair_ab_from_tar_path(trace_path(run), units, nodes, payloads)
        else:
            for n in nodes:
                n['d2_unverifiable'] = False
    else:
        path = trace_path(run)
        # Single streaming pass over raw .tar.zst: detect family, collect extract.py entries and D2 records together
        fam = 'A'
        has_log = False
        tar_entries = []
        payload_meta, payload_pf, evid_p_sha, raw_ack_blobs = {}, {}, {}, []
        with open(path, 'rb') as fh:
            with tarfile.open(fileobj=zstandard.ZstdDecompressor().stream_reader(fh), mode='r|') as tf:
                for m in tf:
                    if not m.isfile():
                        continue
                    nm = m.name
                    if nm == 'log.jsonl':
                        has_log = True
                        fam = 'C'
                        tar_entries.append((nm, tf.extractfile(m).read()))
                    elif nm.startswith('agent-traces/claude-code/'):
                        if fam != 'C':
                            fam = 'B'
                        data = tf.extractfile(m).read()
                        tar_entries.append((nm, data))
                        if '/events/' in nm and b'payload_' in data and b'verification_' in data:
                            raw_ack_blobs.append(data)
                    elif nm == 'manifest.json' or nm.startswith('model/items/') or re.match(
                            r'^(model/\d+\.(request|response)|jobs/\d+/out/result\.json)$', nm):
                        tar_entries.append((nm, tf.extractfile(m).read()))
                    elif nm.startswith('models/primary/traffic/') and (
                            nm.endswith('.request.bin') or nm.endswith('.response.bin')):
                        data = tf.extractfile(m).read()
                        tar_entries.append((nm, data))
                        if b'payload_' in data and b'verification_' in data:
                            raw_ack_blobs.append(data)
                    elif nm.startswith('verifications/') and nm.endswith('/result.json'):
                        tar_entries.append((nm, tf.extractfile(m).read()))
                    elif nm.startswith('verifications/') and nm.endswith('/evidence.tar'):
                        vid = nm.split('/')[1]
                        try:
                            with tarfile.open(fileobj=io.BytesIO(tf.extractfile(m).read())) as etf:
                                for em in etf:
                                    if em.isfile() and em.name.endswith('metrics.json'):
                                        emd = json.loads(etf.extractfile(em).read())
                                        if emd.get('payload_sha256'):
                                            evid_p_sha[vid] = emd['payload_sha256']
                        except Exception:
                            pass
                    elif nm.startswith('payloads/'):
                        data = tf.extractfile(m).read()
                        tar_entries.append((nm, data))
                        if not has_log:
                            parts = nm.split('/')
                            if len(parts) >= 3 and parts[2] == 'metadata.json':
                                md = json.loads(data)
                                payload_meta[parts[1]] = (md.get('sha256'), md.get('purpose'), X.ulid_ms(parts[1]) or 0)
                            elif len(parts) >= 3 and parts[2] == 'payload.tar':
                                payload_pf[parts[1]] = payload_files(data)

        m_norm = os.path.join(AUDIT_NORM, run['task'], run['model_id'], 'meta.json')
        if os.path.exists(m_norm):
            fam = json.load(open(m_norm))['family']

        orig_iter_tar = X.iter_tar
        X.iter_tar = lambda _p: iter(tar_entries)
        try:
            if fam == 'C':
                units, nodes = X.process_pumpkin(path, None, run)
            else:
                units, nodes = X.process_platform(path, None, run, fam)
        finally:
            X.iter_tar = orig_iter_tar
            tar_entries.clear()

        units.sort(key=lambda u: u['t'])
        payloads = {}
        for i, n in enumerate(nodes):
            n['idx'] = i
            b = n.pop('_blob', None)
            if fam == 'C' and b:
                payloads[i] = payload_files(b)
            n['d2_unverifiable'] = False
        for n in nodes:
            if n['mode'] == 'final':
                n['formal_score'] = run.get('score')
        if fam != 'C' and nodes:
            payloads = _pair_ab_from_data(units, nodes, payload_meta, payload_pf, evid_p_sha, raw_ack_blobs)
        raw_ack_blobs.clear()
        src = 'tar'
    refine(nodes, units)
    return fam, units, nodes, payloads, src


# ------------------------------------------------------------------ strict delivering unit & visibility
NUM = re.compile(r'(?<![\w.])(-?\d{1,3}(?:\.\d+)?)(?![\d.]*\d)')
LABEL = re.compile(r'(raw_score|score)["\']?\s*[:=]\s*(-?\d+(?:\.\d+)?)', re.I)
DONE = re.compile(r'\\?"(state|status)\\?"\s*:\s*\\?"(passed|failed|completed|terminated|error|errored|invalid|rejected)\\?"', re.I)
SHELL_WRAP_DONE = re.compile(r'\\?"terminal_status\\?"\s*:\s*\\?"completed\\?"', re.I)
RUNNING = re.compile(r'\\?"(state|status)\\?"\s*:\s*\\?"(running|queued|pending|in_progress|submitted|stored)\\?"', re.I)
PLAIN_RUN = re.compile(r'\bstate\s*[:=]\s*running\b|\bstate\s+running\b', re.I)
ZERO_LABEL = re.compile(r'score\W{0,5}(0|100)(\.0+)?(?![\d.])', re.I)
C_CALL = re.compile(r'sandboxctl\s+(call|status)')
C_RESULT = re.compile(r'\\?"returned\\?"|raw_score|fail_percent|beat_spec_progress')


def is_sidecar(tx):
    return ('You are a safety and security rater' in tx
            or 'You are a reminder observer' in tx
            or tx.startswith('Another language model started to solve this problem'))


def _match(tok, s):
    d = len(tok.split('.')[1]) if '.' in tok else 0
    return abs(float(tok) - s) <= 0.5 * 10 ** -d + 1e-9


def shows_value(text, s):
    """Text shows score s: a number with >= 2 decimals and >= 3 significant digits that rounds to s, or a
    'raw_score'/'score' label followed by s at any precision."""
    if s is None:
        return False
    s = float(s)
    for m in LABEL.finditer(text):
        if _match(m.group(2), s):
            return True
    if s in (0.0, 100.0):
        return False
    for m in NUM.finditer(text):
        tok = m.group(1)
        if '.' in tok and len(tok.split('.')[1]) >= 2 and len(tok.replace('.', '').replace('-', '').lstrip('0')) >= 3 \
                and _match(tok, s):
            return True
    return False


def node_values(n):
    vals = []
    for v in (n.get('raw_score'), (n.get('metrics') or {}).get('score_unbounded')):
        if isinstance(v, (int, float)) and not isinstance(v, bool) and all(abs(v - x) > 1e-12 for x in vals):
            vals.append(float(v))
    return vals


def single_id_segments(tx, fam):
    """Extract minimal single-submission JSON objects (balanced {...}, middle-truncated {...}, or truncated {...})
    and plain-text lines.

    Never pairs across separate JSON objects; unescapes nested JSON strings (e.g. Pumpkin exec output, Muse
    shell wrappers, HTML &quot;) and keeps minimal single-ID spans so outer shell wrappers do not merge inner objects.
    """
    id_rx = JOB_JSON_RX if fam == 'C' else VID_RX
    t_norm = tx.replace('&quot;', '"') if '&quot;' in tx else tx
    if not id_rx.search(t_norm):
        return []
    out = []
    variants = [t_norm]
    if '\\"' in t_norm or '\\n' in t_norm:
        variants.append(t_norm.replace('\\"', '"').replace('\\n', '\n'))
    for s in variants:
        stack = []
        closed_spans = []
        unmatched_close_spans = []
        last_top_end = 0
        for idx, ch in enumerate(s):
            if ch == '{':
                stack.append(idx)
            elif ch == '}':
                if stack:
                    start = stack.pop()
                    closed_spans.append((start, idx + 1))
                    if not stack:
                        last_top_end = idx + 1
                else:
                    tr_m = s.rfind('chars truncated]...\n', last_top_end, idx)
                    seg_st = (tr_m + len('chars truncated]...\n')) if tr_m != -1 else last_top_end
                    unmatched_close_spans.append((seg_st, idx + 1))
                    last_top_end = idx + 1
        kept_closed = []
        for st, en in closed_spans + unmatched_close_spans:
            seg = s[st:en]
            ids = set(id_rx.findall(seg))
            if len(ids) != 1:
                continue
            only_id = next(iter(ids))
            if any(kst >= st and ken <= en and (kst, ken) != (st, en) and kid == only_id
                   for kst, ken, kid in kept_closed):
                continue
            kept_closed.append((st, en, only_id))
            out.append((only_id, seg))
        for st in stack:
            end_nl = s.find('\n', st + 1)
            en = end_nl if (end_nl != -1 and end_nl - st > 40) else min(len(s), st + 4000)
            seg = s[st:en]
            ids = set(id_rx.findall(seg))
            if len(ids) == 1:
                only_id = next(iter(ids))
                if not any(kst >= st and ken <= en and kid == only_id for kst, ken, kid in kept_closed):
                    out.append((only_id, seg))
        for line in s.splitlines():
            if '{' not in line:
                ids = set(id_rx.findall(line))
                if len(ids) == 1:
                    out.append((only_id := next(iter(ids)), line))
    return out


def precompute_units(U, fam):
    """Precompute per-unit ID segments and assistant->tool sibling structure in O(|U|)."""
    id_rx = JOB_JSON_RX if fam == 'C' else VID_RX
    segs_by_u = []
    all_ids_by_u = []
    prev_asst_by_u = {}
    sib_groups = {}
    last_asst = {}
    for ui, u in enumerate(U):
        kind = u['kind']
        if kind == 'response':
            segs_by_u.append([])
            all_ids_by_u.append(set())
            continue
        th = u['thread']
        if kind == 'assistant':
            last_asst[th] = ui
            sib_groups[ui] = []
            segs_by_u.append([])
            all_ids_by_u.append(set())
        else:
            tx = u['text']
            t_norm = tx.replace('&quot;', '"') if '&quot;' in tx else tx
            segs = single_id_segments(tx, fam)
            segs_by_u.append(segs)
            all_ids_by_u.append(set(id_rx.findall(t_norm)))
            if kind in ('tool', 'user') and th in last_asst:
                aui = last_asst[th]
                sib_groups[aui].append(ui)
                prev_asst_by_u[ui] = aui
    return {
        'segs_by_u': segs_by_u,
        'all_ids_by_u': all_ids_by_u,
        'prev_asst_by_u': prev_asst_by_u,
        'sib_groups': sib_groups,
    }


def _has_earlier_same_score(n, N):
    if N is None:
        return False
    j = n.get('idx', len(N))
    s_val = n.get('raw_score')
    vals = [v for v in node_values(n) if v not in (0.0, 100.0)]
    for m in range(min(j, len(N))):
        ms = N[m].get('raw_score')
        if ms is not None and s_val is not None and abs(float(ms) - float(s_val)) < 0.005:
            return True
        for mv in node_values(N[m]):
            if any(abs(mv - v) < 0.005 for v in vals):
                return True
    return False


def deliver_index(n, units, fam, N=None, pre=None):
    """Index into `units` of the first valid unit delivering node n's result, or (None, 'not_found')."""
    if is_d3(n):
        return None, 'd3_no_result'
    if fam == 'C':
        if n['mode'] == 'final':
            return None, 'final_c'
        if n.get('t_result') is None:
            return None, 'not_found'
        nid = n['id'].replace('job_', '')
        t_lo = n['t_result']
    else:
        nid = n['id']
        t_lo = n['t_submit']

    if pre is None:
        pre = precompute_units(units, fam)
    segs_by_u = pre['segs_by_u']
    all_ids_by_u = pre['all_ids_by_u']
    prev_asst_by_u = pre['prev_asst_by_u']
    sib_groups = pre['sib_groups']

    vals = node_values(n)
    s_val = n.get('raw_score')
    zero = s_val is None or float(s_val) in (0.0, 100.0)
    earlier_same = _has_earlier_same_score(n, N)
    j = n.get('idx', -1)

    for ui, u in enumerate(units):
        if u['kind'] in ('assistant', 'response') or u['t'] < t_lo:
            continue
        tx = u['text']
        if is_sidecar(tx):
            continue
        tx_norm = tx.replace('&quot;', '"') if '&quot;' in tx else tx
        tx_clean = SHELL_WRAP_DONE.sub('', tx_norm)

        my_segs = [seg for i_s, seg in segs_by_u[ui] if i_s == nid]
        if my_segs:
            for seg in my_segs:
                sc = SHELL_WRAP_DONE.sub('', seg)
                if (not RUNNING.search(sc) and not PLAIN_RUN.search(sc)
                        and (DONE.search(sc) or any(shows_value(sc, v) for v in vals)
                             or (fam == 'C' and C_RESULT.search(sc)))):
                    return ui, 'id_value'
            # If this submission's id appears with state=running, this unit never delivers it
            if any(RUNNING.search(seg) or PLAIN_RUN.search(seg) for seg in my_segs):
                continue
            # Single-ID unit (e.g. Command: frontier-submit status <vid> \n Output: passed <score>)
            if all_ids_by_u[ui] == {nid} and not RUNNING.search(tx_clean) and not PLAIN_RUN.search(tx_clean):
                if any(shows_value(tx_clean, v) for v in vals) or DONE.search(tx_clean):
                    return ui, 'id_value'
                if not zero and not earlier_same and (u['t'] - n['t_submit']) >= 5000:
                    if any(shows_value(tx_clean, v) for v in vals):
                        return ui, 'id_unique_value'
            continue

        # Multi-ID unit where nid had no standalone segment -> do not pair across IDs
        if nid in all_ids_by_u[ui]:
            continue

        # poll_reply: unambiguous single-ID tool call & reply (no other ID in reply, no parallel sibling tool calls)
        if (u['kind'] in ('tool', 'user') and not all_ids_by_u[ui] and ui in prev_asst_by_u
                and not tx.startswith('The following is a <SYSTEM_MESSAGE>')):
            aui = prev_asst_by_u[ui]
            sibs = sib_groups[aui]
            if len(sibs) != 1:
                continue
            atx = units[aui]['text']
            if '<tool_call' not in atx:
                continue
            if RUNNING.search(tx_clean) or PLAIN_RUN.search(tx_clean):
                continue
            if fam != 'C':
                if 'frontier-submit' in atx and set(VID_RX.findall(atx)) == {nid}:
                    if any(shows_value(tx_clean, v) for v in vals) or DONE.search(tx_clean) or (zero and ZERO_LABEL.search(tx_clean)):
                        return ui, 'poll_reply'
            else:
                polled_jobs = set(re.findall(r'sandboxctl\s+status\s+(\d+)\b', atx))
                sync_call = bool(re.search(r'sandboxctl\s+call\s+train\b', atx))
                is_latest_sub = (N is None) or not any(
                    N[m]['mode'] == 'train' and N[m]['t_submit'] <= u['t'] for m in range(j + 1, len(N))
                )
                if polled_jobs == {nid} or (sync_call and not polled_jobs and is_latest_sub):
                    if (any(shows_value(tx_clean, v) for v in vals) or DONE.search(tx_clean)
                            or C_RESULT.search(tx_clean) or (zero and ZERO_LABEL.search(tx_clean))):
                        return ui, 'poll_reply'

    return None, 'not_found'


def echo_index(n, units, fam, N=None):
    """Strict audit echo rule (visibility only, makes no cut):
    First assistant unit stating node n's unique nonzero score after polling n's id (C: after call_returned).
    """
    if n['mode'] == 'final' or is_d3(n) or is_d4(n):
        return None
    vals = [v for v in node_values(n) if v not in (0.0, 100.0)]
    if not vals or _has_earlier_same_score(n, N):
        return None
    j = n.get('idx', -1)
    if fam == 'C':
        if n.get('t_result') is None:
            return None
        j_num = n['id'].replace('job_', '')
        key_explicit = re.compile(r'\\?"job\\?"\s*:\s*' + j_num + r'\b|sandboxctl\s+status\s+' + j_num + r'\b')
        sync_rx = re.compile(r'sandboxctl\s+call\s+train\b')
        t_lo = n['t_result']
    else:
        key_explicit = re.compile(re.escape(n['id']))
        sync_rx = None
        t_lo = n['t_submit']

    polled = False
    for i, u in enumerate(units):
        if u['kind'] == 'response' or u['t'] < t_lo:
            continue
        if u['kind'] == 'assistant':
            tx = u['text']
            if polled and any(shows_value(tx, v) for v in vals):
                return i
            if '<tool_call' in tx:
                if key_explicit.search(tx):
                    polled = True
                elif sync_rx is not None and sync_rx.search(tx):
                    if N is None or not any(N[m]['mode'] == 'train' and N[m]['t_submit'] <= u['t'] for m in range(j + 1, len(N))):
                        polled = True
    return None


# ------------------------------------------------------------------ rendering (D7 fix)
def fmt_hm(ms):
    s = max(0, int(ms // 1000))
    return f'+{s // 3600:d}h{(s % 3600) // 60:02d}m'


def render_upto(units, k, t0):
    """Transcript of units[0..k] (inclusive), with middle truncation above 3,000,000 chars (D7 fix):
    keeps the first ~200,000 chars (system prompt & task statement), a one-line marker
    '[... N characters omitted ...]', and the tail through unit k, total <= 3,000,000 chars.
    """
    pre = units[:k + 1]
    last_nonresp = {}
    for u in pre:
        if u['kind'] != 'response':
            last_nonresp[u['thread']] = u['t']
    out = []
    for u in pre:
        if u['kind'] == 'response' and last_nonresp.get(u['thread'], -1) >= u['t']:
            continue
        tag = 'assistant (latest streamed reply)' if u['kind'] == 'response' else u['kind']
        out.append(f"\n### [{BT.fmt_dt(u['t'] - t0)}] [{u['thread']}] {tag}\n{u['text']}\n")
    s = ''.join(out)
    cap = BT.TRANSCRIPT_CAP  # 3,000,000
    if len(s) > cap:
        nl_h = s.rfind('\n', HEAD_CAP - 5000, HEAD_CAP + 1)
        if nl_h != -1:
            h_len = nl_h + 1
            head = s[:h_len]
            prefix_nl = ''
        else:
            h_len = HEAD_CAP
            head = s[:h_len]
            prefix_nl = '\n'
        max_tail = cap - len(head) - len(prefix_nl) - 64
        nl_t = s.find('\n', len(s) - max_tail)
        if nl_t != -1 and (len(s) - (nl_t + 1)) >= max_tail - 5000:
            t_len = len(s) - (nl_t + 1)
        else:
            t_len = max_tail
        omitted = len(s) - h_len - t_len
        marker = f'{prefix_nl}[... {omitted} characters omitted ...]\n'
        while len(head) + len(marker) + t_len > cap:
            t_len -= 1
            omitted = len(s) - h_len - t_len
            marker = f'{prefix_nl}[... {omitted} characters omitted ...]\n'
        s = head + marker + s[len(s) - t_len:]
    return s


def task_id(task, model, r, letter='r'):
    return f'{task}__{model}__{letter}{r:03d}'.replace('_', '-').lower()


INSTRUCTION = """# Forecast the scores of an AI agent's later submissions

You are watching an AI coding agent work on a research-engineering task from the **FrontierCS 2**
benchmark. The agent iterates: it edits code, submits a payload to a *train* verifier (which
returns a score on train workloads), and finally submits one *final* payload that is scored on
**hidden** workloads. Scores are on a 0-100 scale (higher is better); a submission that fails
verification scores 0.

The trajectory has been cut at the moment the agent received the result of {received}.
Everything the agent saw up to that moment is in `/app/context/`:

- `run_info.json` - task, category, paper, the agent (model + harness), elapsed time at the cut.
- `transcript.md` - the agent's conversation up to the cut (model inputs/outputs, tool calls and
  tool results, in time order; long items are truncated in the middle). It ends with the tool
  result that delivered that score.
- `submissions.json` - every submission made before the cut: when it was made and, if the agent
  had already seen it, its score, status and metrics. Results the agent had not yet seen are
  marked `pending`.
- `submissions/<i>/` - the files of every submission made before the cut.
- `targets.json` - the submissions you must forecast.

## Rules

- Use only the files in `/app/context/`. No network, no web search, and do not try to find this
  run, its dataset, or the paper's results anywhere else.
- Forecast by reading and reasoning. Think as long as you need: compare the submissions, read what
  the agent tried and what it observed, and weigh the score history. Small calculations over the
  context (diffs, greps, averages, trend fits) are fine.
- Do not solve the task end to end: do not build, install or run the submitted code or the task,
  do not re-implement or improve the solution, and do not write benchmarks or simulations to
  measure a score.
- Do not modify `/app/context/`.

## Your job

Predict the score of every later submission of this run: each submission whose result the agent
had not seen at the cut, through the final submission. Each target is named by when it was
submitted, in minutes after the cut and in elapsed run time:

{targets_md}

Write `/app/prediction.json` exactly in this form (numbers on the 0-100 scale):

```json
{{"predictions": [{pred_example}], "rationale": "<a few sentences>"}}
```

You are graded on absolute error per target (reward = mean over targets of max(0, 1 - |error| / 10)).
"""


def received_phrase(idxs):
    if len(idxs) == 1:
        return f'train submission **{idxs[0]}** (0-based submission index)'
    return ('train submissions ' + ', '.join(f'**{i}**' for i in idxs[:-1]) + f' and **{idxs[-1]}**'
            + ' (0-based submission indices; these results arrived at the same moment)')


def target_line(t):
    kind = 'final, hidden workloads' if t['kind'] == 'final' else 'train'
    m = t['submitted_min_after_cut']
    if t['state_at_cut'] == 'pending':
        when = (f'already submitted, result pending (submitted {-m} min before the cut' if m < 0
                else 'already submitted, result pending (submitted less than 1 min before the cut')
        return f"- Submission {t['index']} ({kind}), {when}, {t['submitted_at_elapsed']} into the run): score?"
    when = f'submitted {m} min after the cut' if m >= 1 else 'submitted less than 1 min after the cut'
    return f"- Submission {t['index']} ({kind}), {when} ({t['submitted_at_elapsed']} into the run): score?"


def instruction(received, targets):
    tmd = '\n'.join(target_line(t) for t in targets)
    ex = ', '.join(f'{{"index": {t["index"]}, "score": <number>}}' for t in targets)
    return INSTRUCTION.format(received=received_phrase(received), targets_md=tmd, pred_example=ex)


def minutes(ms):
    """Signed whole minutes, rounded half away from zero."""
    x = ms / 60000
    return int(math.floor(x + 0.5)) if x >= 0 else -int(math.floor(-x + 0.5))