File size: 36,414 Bytes
341e402 | 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 | """Exhaustive strict-audit validation of build_v2/out_v49/ and build_v2/sample_v49/.
Validates every requirement of brief_fix_v49.md:
1. Check B & D1 & D5 across all 1,407 runs with v2 tasks (adapted 05/06 exact checker)
2. Check D2 across all shards and sample_v49 against raw-tar ack / evidence.tar sha256 truth
3. Check D3 / D4 (0 cuts, 0 targets, 0 tasks from the 5 incomplete-final runs)
4. Check D7 (all 11,585 transcripts <= 3,000,000 chars, 0 dropped heads, 100% preserve initial prompt/task statement)
5. Check D9 (0 tasks from the 18 final-less runs; 100% of tasks have final target; internal consistency)
6. Check D10 edge cases + Oracle 1.0 on 100 random shard tasks + ALL 1,200 sample_v49 tasks
7. Check H byte-for-byte rebuild of 4 runs across families A, B, C with PEER_CACHE & AUDIT_NORM disabled
8. v1 rebuild check (15,106 / 15,106), leak guard & decoy leak audit inspection, sample_v49 baselines
9. Exact task-level diff against out_v48 (dropped & re-cut tasks by exact reason)
Writes build_v2/out_v49/work/strict_validation.json.
"""
import collections, glob, hashlib, io, json, math, os, random, re, shutil, statistics, subprocess, sys, tarfile, tempfile
from multiprocessing import Pool
import zstandard
V = '<ROOT>/'
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, V + 'data/scripts')
sys.path.insert(0, HERE)
import extract as X
import build_tasks as BT
import v49lib as L
import build as B49
OUT_V48 = V + 'build_v2/out_v48/'
OUT_V49 = V + 'build_v2/out_v49/'
SAMP_V49 = V + 'build_v2/sample_v49/'
FR = json.load(open(L.SRC + 'metadata/formal-results.json'))
RUN_META = {(r['task'], r['model_id']): r for r in FR['runs']}
TRACE_TRUTH = {}
for ln in open(V + 'audit/v2/out/runs_trace_truth.jsonl'):
if ln.strip():
d = json.loads(ln)
TRACE_TRUTH[(d['task'], d['model'])] = d
SAMP_IDS = [x.strip() for x in open(SAMP_V49 + 'ids.txt') if x.strip()]
SAMP_SET = set(SAMP_IDS)
def fast_load_units_nodes(task, model):
norm_d = os.path.join(V, 'audit/tmp/norm', task, model)
uj = os.path.join(norm_d, 'units.jsonl.zst')
if os.path.exists(uj) and os.path.exists(os.path.join(norm_d, 'nodes.json')):
fam = json.load(open(os.path.join(norm_d, 'meta.json')))['family']
N = json.load(open(os.path.join(norm_d, 'nodes.json')))
raw_u = zstandard.ZstdDecompressor().decompress(open(uj, 'rb').read(), max_output_size=1 << 31).decode()
U = [json.loads(l) for l in raw_u.splitlines() if l]
L.refine(N, U)
return fam, U, N
run = RUN_META[(task, model)]
fam, U, N, _, _ = L.load_run(run)
return fam, U, N
def audit_check_unit(j, N, U, ui, fam, node_tt, pre):
"""Exact independent check (refined 05/06 with balanced single-ID JSON objects) of whether U[ui] delivers node j."""
n = N[j]
na = node_tt[j]
u = U[ui]
tx = u['text']
vals = L.node_values(n)
s_val = n.get('raw_score')
zero = (s_val is None or float(s_val) in (0.0, 100.0))
if na['d3_no_result']:
return 'LEAK_D3_NO_RESULT', 'status=None'
if u['t'] < n['t_submit']:
return 'LEAK_STILL_RUNNING', 'before t_submit'
if fam == 'C' and na['t_verif_done'] is not None and u['t'] < na['t_verif_done']:
return 'LEAK_STILL_RUNNING', 'before C call_returned'
if L.is_sidecar(tx):
return 'LEAK_SIDECAR', 'sidecar_or_compaction'
nid = n['id'].replace('job_', '') if fam == 'C' else n['id']
tx_norm = tx.replace('"', '"') if '"' in tx else tx
tx_clean = L.SHELL_WRAP_DONE.sub('', tx_norm)
my_segs = [seg for i_s, seg in pre['segs_by_u'][ui] if i_s == nid]
all_ids = pre['all_ids_by_u'][ui]
if my_segs:
for seg in my_segs:
sc = L.SHELL_WRAP_DONE.sub('', seg)
if not L.RUNNING.search(sc) and not L.PLAIN_RUN.search(sc):
if L.DONE.search(sc) or any(L.shows_value(sc, v) for v in vals) or (fam == 'C' and L.C_RESULT.search(sc)):
return 'VALID_ID', 'id+done/score in single object'
if any(L.RUNNING.search(seg) or L.PLAIN_RUN.search(seg) for seg in my_segs):
return 'LEAK_STILL_RUNNING', 'id running in unit'
if all_ids == {nid} and not L.RUNNING.search(tx_clean) and not L.PLAIN_RUN.search(tx_clean):
if any(L.shows_value(tx_clean, v) for v in vals) or L.DONE.search(tx_clean):
return 'VALID_ID', 'single-id unit with score/done'
if all_ids and nid not in all_ids:
return 'LEAK_OTHER_ID', 'unit carries only other id(s)'
if nid in all_ids:
return 'LEAK_AMBIGUOUS_MULTI_ID', 'multi-id unit without standalone object match'
if u['kind'] in ('tool', 'user') and ui in pre['prev_asst_by_u'] and not tx.startswith('The following is a <SYSTEM_MESSAGE>'):
aui = pre['prev_asst_by_u'][ui]
sibs = pre['sib_groups'][aui]
if any(nid in pre['all_ids_by_u'][si] for si in sibs if si != ui):
return 'LEAK_OTHER_ID', 'id in sibling parallel tool unit'
atx = U[aui]['text']
if len(sibs) == 1 and '<tool_call' in atx and not L.RUNNING.search(tx_clean) and not L.PLAIN_RUN.search(tx_clean):
if fam != 'C':
if 'frontier-submit' in atx and set(L.VID_RX.findall(atx)) == {nid}:
if any(L.shows_value(tx_clean, v) for v in vals) or L.DONE.search(tx_clean) or (zero and L.ZERO_LABEL.search(tx_clean)):
return 'VALID_SINGLE_POLL', 'single poll reply'
else:
pjobs = set(re.findall(r'sandboxctl\s+status\s+(\d+)\b', atx))
scall = bool(re.search(r'sandboxctl\s+call\s+train\b', atx))
latest = not any(N[m]['mode'] == 'train' and N[m]['t_submit'] <= u['t'] for m in range(j + 1, len(N)))
if pjobs == {nid} or (scall and not pjobs and latest):
if (any(L.shows_value(tx_clean, v) for v in vals) or L.DONE.search(tx_clean)
or L.C_RESULT.search(tx_clean) or (zero and L.ZERO_LABEL.search(tx_clean))):
return 'VALID_SINGLE_POLL', 'c single poll reply'
return 'LEAK_NO_DELIVERY', 'no valid id/single-poll delivery'
def validate_shard_worker(fcs_task):
shard_p = OUT_V49 + f'tasks/{fcs_task}.tar.zst'
work_p = OUT_V49 + f'work/{fcs_task}.json.zst'
w = json.loads(zstandard.ZstdDecompressor().decompress(open(work_p, 'rb').read(), max_output_size=1 << 31))
k_by_tid = {t['task_id']: t['K'] for r in w['runs'] for t in r.get('tasks', [])}
by_tid = collections.defaultdict(dict)
md5s = {'grade.py': set(), 'test.sh': set(), 'Dockerfile': set()}
with open(shard_p, '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
tid, rel = m.name.split('/', 1)
data = tf.extractfile(m).read()
if rel in ('tests/grade.py', 'tests/test.sh', 'environment/Dockerfile'):
md5s[rel.split('/')[-1]].add(hashlib.md5(data).hexdigest())
by_tid[tid][rel] = data
by_model = collections.defaultdict(list)
for tid in sorted(by_tid):
info = json.loads(by_tid[tid]['environment/context/run_info.json'])
by_model[info['model_id']].append(tid)
out = {
'fcs_task': fcs_task,
'n_tasks': len(by_tid),
'bad_cuts': [],
'd1_tasks': [],
'd5_escaped_missed': [],
'd2_mismatches': [],
'd2_unverifiable_tasks': [],
'd3_cuts': [],
'd4_cuts': [],
'd3_targets': [],
'd4_targets': [],
'd7_over_cap': [],
'd7_dropped_head': [],
'd7_middle_truncated_count': 0,
'd7_middle_truncated_examples': [],
'd7_missing_initial_unit': [],
'd9_missing_final_target': [],
'consistency_errors': [],
'post_cut_dir_or_id_leaks': [],
'md5s': {k: sorted(v) for k, v in md5s.items()},
}
for model, tids in sorted(by_model.items()):
rk = (fcs_task, model)
run = RUN_META[rk]
tt = TRACE_TRUTH[rk]
node_tt = {na['idx']: na for na in tt['nodes']}
need_d2_tar = (tt['family'] != 'C' and any(na['d2'] != 'match' for na in tt['nodes']))
if need_d2_tar or not os.path.exists(os.path.join(V, 'audit/tmp/norm', fcs_task, model, 'units.jsonl.zst')):
fam, U, N, P_exact, _ = L.load_run(run)
else:
fam, U, N = fast_load_units_nodes(fcs_task, model)
P_exact = None # all nodes verified d2 == 'match' in TRACE_TRUTH
pre = L.precompute_units(U, fam)
# Compute exact independent visibility unit per train node
true_vis = {}
escaped_job_vis = {}
for n in N:
if n['mode'] != 'train':
continue
j = n['idx']
if L.is_d3(n):
true_vis[j] = None
continue
tv = None
for ui in range(len(U)):
if U[ui]['kind'] in ('assistant', 'response') or U[ui]['t'] < n['t_submit']:
continue
st, _ = audit_check_unit(j, N, U, ui, fam, node_tt, pre)
if st.startswith('VALID_'):
tv = ui
if fam == 'C' and ('\\"job\\"' in U[ui]['text']):
escaped_job_vis[j] = ui
break
if not L.is_d4(n):
ei = L.echo_index(n, U, fam, N=N)
if ei is not None and (tv is None or ei < tv):
tv = ei
true_vis[j] = tv
# Initial non-response unit snippet for D7 task-statement check
first_nonresp = next((u for u in U if u['kind'] != 'response' and len(u['text'].strip()) > 0), None)
init_probe = first_nonresp['text'][:120] if first_nonresp else ''
# Precompute exact payload digests from P_exact when loaded
exact_p_dig = {}
if P_exact is not None:
for idx, pf in P_exact.items():
h = hashlib.sha256()
for k in sorted(pf):
h.update(k.encode() + b'\x00' + pf[k] + b'\x00')
exact_p_dig[idx] = h.hexdigest()
for tid in tids:
files = by_tid[tid]
K = k_by_tid[tid]
T = U[K]['t']
tr = files['environment/context/transcript.md'].decode('utf8', 'replace')
subs = json.loads(files['environment/context/submissions.json'])
rinfo = json.loads(files['environment/context/run_info.json'])
tjson = json.loads(files['environment/context/targets.json'])
gt_obj = json.loads(files['tests/ground_truth.json'])
gt = gt_obj['targets']
instr = files['instruction.md'].decode('utf8', 'replace')
toml_s = files['task.toml'].decode('utf8', 'replace')
recv = rinfo['cut_after_result_of_submission']
# 1. Check B on U[K]
for j in recv:
if L.is_d3(N[j]):
out['d3_cuts'].append((tid, j))
if L.is_d4(N[j]):
out['d4_cuts'].append((tid, j))
st, det = audit_check_unit(j, N, U, K, fam, node_tt, pre)
if not st.startswith('VALID_'):
out['bad_cuts'].append((tid, j, K, st, det))
# 2. Check D1 & D5 on submissions.json
for s_e in subs:
j = s_e['index']
if s_e['kind'] != 'train':
continue
tv = true_vis.get(j)
if s_e['result'] == 'seen':
if tv is None or tv > K:
out['d1_tasks'].append((tid, j, tv, K))
else:
if j in escaped_job_vis and escaped_job_vis[j] <= K:
out['d5_escaped_missed'].append((tid, j, escaped_job_vis[j], K))
# 3. Check D2 on submissions/<i>/ in shard
shard_sub_files = collections.defaultdict(dict)
for rel, b in files.items():
if rel.startswith('environment/context/submissions/'):
parts = rel.split('/', 4)
s_idx = int(parts[3])
shard_sub_files[s_idx][parts[4]] = b
made_js = [n['idx'] for n in N if n['t_submit'] <= T]
extra_dirs = sorted(set(shard_sub_files.keys()) - set(made_js))
if extra_dirs:
out['post_cut_dir_or_id_leaks'].append((tid, 'extra_dirs', extra_dirs))
for j in made_js:
if N[j].get('d2_unverifiable'):
out['d2_unverifiable_tasks'].append((tid, j))
if P_exact is not None:
got_pf = shard_sub_files.get(j, {})
h = hashlib.sha256()
for k in sorted(got_pf):
h.update(k.encode() + b'\x00' + got_pf[k] + b'\x00')
exp_dig = exact_p_dig.get(j, hashlib.sha256().hexdigest())
if h.hexdigest() != exp_dig:
out['d2_mismatches'].append((tid, j))
# Post-cut verification ID check
if fam != 'C':
later_vids = [n['id'] for n in N if n['t_submit'] > T and n['id'] in tr]
if later_vids:
out['post_cut_dir_or_id_leaks'].append((tid, 'later_vids', later_vids))
# 4. Check D3 / D4 targets & D9 final target
for g in gt:
jn = N[g['index']]
if L.is_d3(jn):
out['d3_targets'].append((tid, g['index']))
if L.is_d4(jn):
out['d4_targets'].append((tid, g['index']))
if sum(1 for g in gt if g['kind'] == 'final') != 1:
out['d9_missing_final_target'].append(tid)
# 5. Check D7 transcript cap & task statement survival
if len(tr) > 3_000_000:
out['d7_over_cap'].append((tid, len(tr)))
if tr.startswith('[... earliest'):
out['d7_dropped_head'].append(tid)
if init_probe and init_probe not in tr[:250_000]:
out['d7_missing_initial_unit'].append(tid)
if re.search(r'^\[\.\.\. \d+ characters omitted \.\.\.\]$', tr, re.M):
out['d7_middle_truncated_count'] += 1
if len(out['d7_middle_truncated_examples']) < 5:
out['d7_middle_truncated_examples'].append((tid, len(tr)))
# 6. Check internal consistency (targets.json, ground_truth.json, instruction.md, task.toml, solve.sh)
tj_idx = [t['index'] for t in tjson]
gt_idx = [g['index'] for g in gt]
ins_idx = [int(m.group(1)) for m in re.finditer(r'^- Submission (\d+) ', instr, re.M)]
m_nt = re.search(r'(?m)^n_targets\s*=\s*(\d+)', toml_s)
nt_val = int(m_nt.group(1)) if m_nt else -1
if not (tj_idx == gt_idx == ins_idx and nt_val == len(gt) and 'at the end of the run' not in instr):
out['consistency_errors'].append((tid, len(tj_idx), len(gt_idx), len(ins_idx), nt_val))
return out
def run_grade_box(solve_bytes, grade_bytes, gt_bytes, tmp_root, custom_pred=None):
d = tempfile.mkdtemp(dir=tmp_root)
try:
app = os.path.join(d, 'app')
os.makedirs(app)
if custom_pred is None:
s_txt = solve_bytes.decode().replace('/app/prediction.json', app + '/prediction.json')
open(os.path.join(d, 'solve.sh'), 'w').write(s_txt)
subprocess.run(['bash', os.path.join(d, 'solve.sh')], check=True)
else:
open(app + '/prediction.json', 'w').write(custom_pred)
open(os.path.join(d, 'grade.py'), 'wb').write(grade_bytes)
open(os.path.join(d, 'ground_truth.json'), 'wb').write(gt_bytes)
subprocess.run([sys.executable, '-I', os.path.join(d, 'grade.py'),
app + '/prediction.json', os.path.join(d, 'ground_truth.json'),
os.path.join(d, 'reward.json')], check=True, stderr=subprocess.PIPE)
return json.load(open(os.path.join(d, 'reward.json')))
finally:
shutil.rmtree(d, ignore_errors=True)
def _sample_batch_worker(batch):
tmp_root = tempfile.mkdtemp(prefix='v49_sv_batch_', dir='<SCRATCH>')
app = os.path.join(tmp_root, 'app')
os.makedirs(app, exist_ok=True)
oracle_pass = 0
oracle_fails = []
sample_consistency_errs = []
md5s = {'grade.py': set(), 'test.sh': set(), 'Dockerfile': set()}
rows = []
try:
for tid in batch:
td = os.path.join(SAMP_V49, 'tasks', tid)
sb = open(td + '/solution/solve.sh', 'rb').read()
gb = open(td + '/tests/grade.py', 'rb').read()
gtb = open(td + '/tests/ground_truth.json', 'rb').read()
md5s['grade.py'].add(hashlib.md5(gb).hexdigest())
md5s['test.sh'].add(hashlib.md5(open(td + '/tests/test.sh', 'rb').read()).hexdigest())
md5s['Dockerfile'].add(hashlib.md5(open(td + '/environment/Dockerfile', 'rb').read()).hexdigest())
# Run actual solve.sh + grade.py subprocesses on EVERY SINGLE sampled task
pred_p = app + '/prediction.json'
if os.path.exists(pred_p):
os.remove(pred_p)
rew_p = os.path.join(tmp_root, 'reward.json')
if os.path.exists(rew_p):
os.remove(rew_p)
s_txt = sb.decode().replace('/app/prediction.json', pred_p)
open(os.path.join(tmp_root, 'solve.sh'), 'w').write(s_txt)
open(os.path.join(tmp_root, 'grade.py'), 'wb').write(gb)
open(os.path.join(tmp_root, 'ground_truth.json'), 'wb').write(gtb)
subprocess.run(['bash', os.path.join(tmp_root, 'solve.sh')], check=True)
subprocess.run([sys.executable, '-I', os.path.join(tmp_root, 'grade.py'),
pred_p, os.path.join(tmp_root, 'ground_truth.json'), rew_p],
check=True, stderr=subprocess.PIPE)
res = json.load(open(rew_p))
if res['valid'] == 1 and abs(res['reward'] - 1.0) < 1e-12:
oracle_pass += 1
else:
oracle_fails.append((tid, res))
# Verify sample post-process invariants
gt_d = json.loads(gtb)
targets = gt_d['targets']
tjson = json.load(open(td + '/environment/context/targets.json'))
subs = json.load(open(td + '/environment/context/submissions.json'))
instr = open(td + '/instruction.md').read()
toml_s = open(td + '/task.toml').read()
tr = open(td + '/environment/context/transcript.md').read()
train_not_passed = [t['index'] for t in targets if t['kind'] == 'train' and t.get('status') != 'passed']
fin_cnt = sum(1 for t in targets if t['kind'] == 'final')
m_nt = re.search(r'(?m)^n_targets\s*=\s*(\d+)', toml_s)
nt_toml = int(m_nt.group(1)) if m_nt else -1
ins_idx = [int(m.group(1)) for m in re.finditer(r'^- Submission (\d+) ', instr, re.M)]
if (train_not_passed or fin_cnt != 1 or nt_toml != len(targets)
or [t['index'] for t in targets] != [t['index'] for t in tjson]
or [t['index'] for t in targets] != ins_idx
or 'at the end of the run' in instr
or len(tr) > 3_000_000 or tr.startswith('[... earliest')):
sample_consistency_errs.append(tid)
seen_subs = [s for s in subs if s.get('result') == 'seen']
last_s = float(seen_subs[-1]['score'] or 0.0)
best_s = max(float(s['score'] or 0.0) for s in seen_subs)
assert abs(last_s - gt_d['baselines']['last_seen']) < 1e-9
assert abs(best_s - gt_d['baselines']['best_seen']) < 1e-9
rows.append((last_s, best_s, [(t['kind'], t['score']) for t in targets]))
finally:
shutil.rmtree(tmp_root, ignore_errors=True)
return oracle_pass, oracle_fails, sample_consistency_errs, {k: list(v) for k, v in md5s.items()}, rows
def check_sample_and_d10():
os.makedirs('<SCRATCH>', exist_ok=True)
tmp_root = '<SCRATCH>' + str(os.getpid())
os.makedirs(tmp_root, exist_ok=True)
oracle_pass = 0
oracle_fails = []
sample_consistency_errs = []
md5s = {'grade.py': set(), 'test.sh': set(), 'Dockerfile': set()}
def rw(e):
return max(0.0, 1.0 - e / 10.0)
B_task = collections.defaultdict(list)
B_task_mae = collections.defaultdict(list)
B_tgt = collections.defaultdict(lambda: collections.defaultdict(list))
try:
batches = [SAMP_IDS[i:i + 200] for i in range(0, len(SAMP_IDS), 200)]
with Pool(6) as p:
for op, of, sce, m5, rows in p.map(_sample_batch_worker, batches):
oracle_pass += op
oracle_fails.extend(of)
sample_consistency_errs.extend(sce)
for k, vs in m5.items():
md5s[k].update(vs)
for last_s, best_s, tgt_pairs in rows:
for bname, bval in (('last_seen', last_s), ('best_seen', best_s), ('zero', 0.0)):
errs = [abs(bval - sc) for _, sc in tgt_pairs]
B_task[bname].append(sum(rw(e) for e in errs) / len(errs))
B_task_mae[bname].append(sum(errs) / len(errs))
for k, ((tkind, _), e) in enumerate(zip(tgt_pairs, errs)):
B_tgt[bname]['all'].append(e)
B_tgt[bname]['next' if k == 0 else 'later'].append(e)
B_tgt[bname]['final' if tkind == 'final' else 'train'].append(e)
# D10 edge-case tests on a task with >= 3 targets
multi_tid = next(tid for tid in SAMP_IDS
if len(json.load(open(f'{SAMP_V49}/tasks/{tid}/tests/ground_truth.json'))['targets']) >= 3)
mtd = f'{SAMP_V49}/tasks/{multi_tid}'
gb = open(mtd + '/tests/grade.py', 'rb').read()
gtb = open(mtd + '/tests/ground_truth.json', 'rb').read()
m_targets = json.loads(gtb)['targets']
n_m = len(m_targets)
exp_n_minus_1 = (n_m - 1) / n_m
# 1) Malformed entry: missing 'score' key -> error 100 on index 0, valid=1, reward=(n-1)/n
r_no_score = run_grade_box(None, gb, gtb, tmp_root, custom_pred=json.dumps({
'predictions': [{'index': m_targets[0]['index']}] + [{'index': t['index'], 'score': t['score']} for t in m_targets[1:]]
}))
# 2) Malformed entry: non-numeric score string -> error 100 on index 0, valid=1, reward=(n-1)/n
r_bad_str = run_grade_box(None, gb, gtb, tmp_root, custom_pred=json.dumps({
'predictions': [{'index': m_targets[0]['index'], 'score': 'not_a_number'}] + [{'index': t['index'], 'score': t['score']} for t in m_targets[1:]]
}))
# 3) Duplicate index: [exact, wrong] -> keeps FIRST (exact) -> reward 1.0!
wrong_val = 0.0 if m_targets[0]['score'] > 50.0 else 100.0
r_dup_first_good = run_grade_box(None, gb, gtb, tmp_root, custom_pred=json.dumps({
'predictions': ([{'index': m_targets[0]['index'], 'score': m_targets[0]['score']},
{'index': m_targets[0]['index'], 'score': wrong_val}]
+ [{'index': t['index'], 'score': t['score']} for t in m_targets[1:]])
}))
# 4) Duplicate index: [wrong, exact] -> keeps FIRST (wrong) -> reward < 1.0!
r_dup_first_bad = run_grade_box(None, gb, gtb, tmp_root, custom_pred=json.dumps({
'predictions': ([{'index': m_targets[0]['index'], 'score': wrong_val},
{'index': m_targets[0]['index'], 'score': m_targets[0]['score']}]
+ [{'index': t['index'], 'score': t['score']} for t in m_targets[1:]])
}))
exp_dup_bad = (0.0 + (n_m - 1)) / n_m
d10_checks = {
'tested_task_id': multi_tid,
'n_targets': n_m,
'missing_score_entry': {
'valid': r_no_score['valid'], 'reward': r_no_score['reward'], 'expected': exp_n_minus_1,
'abs_err_0': r_no_score['abs_err_0'], 'pass': r_no_score['valid'] == 1 and abs(r_no_score['reward'] - exp_n_minus_1) < 1e-9 and r_no_score['abs_err_0'] == 100.0,
},
'non_numeric_score_entry': {
'valid': r_bad_str['valid'], 'reward': r_bad_str['reward'], 'expected': exp_n_minus_1,
'abs_err_0': r_bad_str['abs_err_0'], 'pass': r_bad_str['valid'] == 1 and abs(r_bad_str['reward'] - exp_n_minus_1) < 1e-9 and r_bad_str['abs_err_0'] == 100.0,
},
'duplicate_index_first_exact': {
'valid': r_dup_first_good['valid'], 'reward': r_dup_first_good['reward'], 'expected': 1.0,
'pass': r_dup_first_good['valid'] == 1 and abs(r_dup_first_good['reward'] - 1.0) < 1e-9,
},
'duplicate_index_first_wrong': {
'valid': r_dup_first_bad['valid'], 'reward': r_dup_first_bad['reward'], 'expected': exp_dup_bad,
'pass': r_dup_first_bad['valid'] == 1 and abs(r_dup_first_bad['reward'] - exp_dup_bad) < 1e-9,
},
}
finally:
shutil.rmtree(tmp_root, ignore_errors=True)
sample_baselines = {
bname: {
'task_mean_reward': round(sum(B_task[bname]) / len(B_task[bname]), 4),
'task_mean_mae': round(sum(B_task_mae[bname]) / len(B_task_mae[bname]), 3),
'all_target_reward': round(sum(rw(e) for e in B_tgt[bname]['all']) / len(B_tgt[bname]['all']), 4),
'all_target_mae': round(sum(B_tgt[bname]['all']) / len(B_tgt[bname]['all']), 3),
'train_reward': round(sum(rw(e) for e in B_tgt[bname]['train']) / len(B_tgt[bname]['train']), 4),
'final_reward': round(sum(rw(e) for e in B_tgt[bname]['final']) / len(B_tgt[bname]['final']), 4),
}
for bname in ('last_seen', 'best_seen', 'zero')
}
return {
'sample_total': len(SAMP_IDS),
'sample_oracle_pass': oracle_pass,
'sample_oracle_fails': oracle_fails,
'sample_consistency_errors': sample_consistency_errs,
'sample_md5s': {k: sorted(v) for k, v in md5s.items()},
'd10_checks': d10_checks,
'sample_baselines': sample_baselines,
}
def check_H_rebuild():
"""Rebuild 4 runs spanning Families A, B, C (including a D2-repaired run) with caches disabled."""
chosen = [
('edlib_exact_alignment', 'glm'), # Family A
('lrr', 'opus'), # Family B
('vllm_llm_serving_optimization', 'opus'), # Family B (also D2 ack repair & D4 target drop!)
('approximate_mips_global_probing', 'astra62'), # Family C (33 tasks, 924 files)
]
_, tm = B49.tasks_meta()
orig_pc, orig_an = L.PEER_CACHE, L.AUDIT_NORM
L.PEER_CACHE = '/nonexistent_v49_check_H/'
L.AUDIT_NORM = '/nonexistent_v49_check_H/'
results = []
try:
for fcs, mod in chosen:
run = RUN_META[(fcs, mod)]
rebuilt = B49.one((run, tm))
assert rebuilt['source'] == 'tar', f'Expected tar, got {rebuilt["source"]}'
rebuilt_map = {t['task_id']: {name: (mode, data) for name, data, mode in t['members']} for t in rebuilt['tasks']}
prefix = f'{fcs}__{mod}__r'.replace('_', '-').lower()
shard_map = collections.defaultdict(dict)
with open(OUT_V49 + f'tasks/{fcs}.tar.zst', 'rb') as fh:
with tarfile.open(fileobj=zstandard.ZstdDecompressor().stream_reader(fh), mode='r|') as tf:
for m in tf:
if m.isfile():
tid, rel = m.name.split('/', 1)
if tid.startswith(prefix):
shard_map[tid][rel] = (m.mode, tf.extractfile(m).read())
same_tids = sorted(rebuilt_map.keys()) == sorted(shard_map.keys())
diffs = []
n_files, n_bytes = 0, 0
for tid in sorted(rebuilt_map):
rm = rebuilt_map[tid]
sm = shard_map.get(tid, {})
if sorted(rm.keys()) != sorted(sm.keys()):
diffs.append((tid, 'file_list_mismatch'))
continue
for k in sorted(rm):
n_files += 1
n_bytes += len(rm[k][1])
if rm[k] != sm[k]:
diffs.append((tid, k, 'mode_or_bytes_diff'))
results.append({
'run': f'{fcs}/{mod}', 'family': rebuilt['family'], 'tasks': len(rebuilt_map),
'files': n_files, 'bytes': n_bytes, 'same_task_ids': same_tids, 'diffs': diffs,
})
finally:
L.PEER_CACHE, L.AUDIT_NORM = orig_pc, orig_an
return results
def diff_against_v48():
idx48 = {r['task_id']: r for r in json.load(open(OUT_V48 + 'metadata/task_index.json'))}
idx49 = {r['task_id']: r for r in json.load(open(OUT_V49 + 'metadata/task_index.json'))}
bt_audit = json.load(open(V + 'audit/v2/out/bad_tasks.json'))
# Map run-level drops and cut-level D2_unverifiable from out_v49/work
run_drop_map = {}
cut_d2_unverif_runs = set()
for p in sorted(glob.glob(OUT_V49 + 'work/*.json.zst')):
w = json.loads(zstandard.ZstdDecompressor().decompress(open(p, 'rb').read(), max_output_size=1 << 31))
for r in w['runs']:
rk = (r['task'], r['model'])
if r.get('run_drop_reason'):
run_drop_map[rk] = r['run_drop_reason']
if any(dc['reason'] == 'D2_unverifiable' for dc in r.get('dropped_cuts', [])):
cut_d2_unverif_runs.add(rk)
dropped_ids = sorted(set(idx48) - set(idx49))
added_ids = sorted(set(idx49) - set(idx48))
kept_ids = sorted(set(idx48) & set(idx49))
reasons = collections.Counter()
examples = collections.defaultdict(list)
for tid in dropped_ids:
r = idx48[tid]
rk = (r['fcs_task'], r['model'])
defs = (bt_audit.get(tid) or {}).get('defects', [])
if rk in run_drop_map:
why = run_drop_map[rk]
elif 'D3' in defs and not bt_audit[tid]['fixable'] and 'cut submission' in bt_audit[tid]['fix']:
why = 'D3_no_result_cut'
elif 'D4' in defs and not bt_audit[tid]['fixable'] and 'cut submission' in bt_audit[tid]['fix']:
why = 'D4_infra_cut'
elif 'D2_unverifiable' in defs or rk in cut_d2_unverif_runs and 'D2_unverifiable' in str(bt_audit.get(tid, '')):
why = 'D2_unverifiable'
elif 'B_cut' in defs:
why = 'B_cut_invalid_delivery'
else:
why = 'B_cut_strict_id_or_merged_unit_split'
reasons[why] += 1
if len(examples[why]) < 5:
examples[why].append(tid)
# Explain added task IDs (new task_ids when a multi-submission timestamp T split into distinct unit indices K1 < K2,
# or when a previously false-early merged cut re-cut separately!)
added_reasons = collections.Counter()
added_examples = collections.defaultdict(list)
for tid in added_ids:
r = idx49[tid]
rk = (r['fcs_task'], r['model'])
# Check if an earlier v48 multi-result cut in the same run held r['cut_result_index'] as a non-max element of received_indices!
in_v48_multi = any(
r48['fcs_task'] == rk[0] and r48['model'] == rk[1] and r['cut_result_index'] in r48['received_indices']
for r48 in idx48.values()
)
cat = 'split_from_v48_multi_submission_cut' if in_v48_multi else 'recut_from_shifted_visibility'
added_reasons[cat] += 1
if len(added_examples[cat]) < 5:
added_examples[cat].append(tid)
return {
'v48_tasks': len(idx48),
'v49_tasks': len(idx49),
'net_delta': len(idx49) - len(idx48),
'kept_same_task_id': len(kept_ids),
'dropped_count': len(dropped_ids),
'dropped_by_reason': dict(sorted(reasons.items())),
'dropped_examples': dict(examples),
'added_count': len(added_ids),
'added_by_reason': dict(sorted(added_reasons.items())),
'added_examples': dict(added_examples),
}
def main():
fcs_tasks = sorted(os.path.basename(p).replace('.tar.zst', '') for p in glob.glob(OUT_V49 + 'tasks/*.tar.zst'))
print('Validating shards:', len(fcs_tasks), flush=True)
shard_res = []
with Pool(6, maxtasksperchild=8) as p:
for sr in p.imap_unordered(validate_shard_worker, fcs_tasks):
shard_res.append(sr)
if len(shard_res) % 12 == 0:
print(f' shards validated: {len(shard_res)}/{len(fcs_tasks)}', flush=True)
agg = {
'shards': len(shard_res),
'total_tasks': sum(s['n_tasks'] for s in shard_res),
'bad_cuts': [x for s in shard_res for x in s['bad_cuts']],
'd1_tasks': [x for s in shard_res for x in s['d1_tasks']],
'd5_escaped_missed': [x for s in shard_res for x in s['d5_escaped_missed']],
'd2_mismatches': [x for s in shard_res for x in s['d2_mismatches']],
'd2_unverifiable_tasks': [x for s in shard_res for x in s['d2_unverifiable_tasks']],
'd3_cuts': [x for s in shard_res for x in s['d3_cuts']],
'd4_cuts': [x for s in shard_res for x in s['d4_cuts']],
'd3_targets': [x for s in shard_res for x in s['d3_targets']],
'd4_targets': [x for s in shard_res for x in s['d4_targets']],
'd7_over_cap': [x for s in shard_res for x in s['d7_over_cap']],
'd7_dropped_head': [x for s in shard_res for x in s['d7_dropped_head']],
'd7_middle_truncated_count': sum(s['d7_middle_truncated_count'] for s in shard_res),
'd7_middle_truncated_examples': [x for s in shard_res for x in s['d7_middle_truncated_examples']][:10],
'd7_missing_initial_unit': [x for s in shard_res for x in s['d7_missing_initial_unit']],
'd9_missing_final_target': [x for s in shard_res for x in s['d9_missing_final_target']],
'consistency_errors': [x for s in shard_res for x in s['consistency_errors']],
'post_cut_dir_or_id_leaks': [x for s in shard_res for x in s['post_cut_dir_or_id_leaks']],
'shard_md5s': {
k: sorted({h for s in shard_res for h in s['md5s'][k]})
for k in ('grade.py', 'test.sh', 'Dockerfile')
},
}
# Check explicitly that 0 tasks come from the 18 D9 runs or 5 incomplete-final runs
idx49 = json.load(open(OUT_V49 + 'metadata/task_index.json'))
d9_runs_18 = {
(d['task'], d['model']) for d in TRACE_TRUTH.values()
if d['n_nodes'] > 0 and not any(n['mode'] == 'final' for n in d['nodes'])
}
incomp_5 = {
(r['task'], r['model_id']) for r in FR['runs']
if L.is_incomplete_final_run(r)
}
agg['d9_runs_count'] = len(d9_runs_18)
agg['d9_tasks_remaining'] = [r['task_id'] for r in idx49 if (r['fcs_task'], r['model']) in d9_runs_18]
agg['incomplete_final_runs_count'] = len(incomp_5)
agg['incomplete_final_tasks_remaining'] = [r['task_id'] for r in idx49 if (r['fcs_task'], r['model']) in incomp_5]
print('Running sample_v49 (all 1,200 tasks oracle) + D10 edge cases...', flush=True)
samp_d10 = check_sample_and_d10()
print('Running Check H byte-for-byte rebuild from raw tars...', flush=True)
check_h = check_H_rebuild()
print('Computing exact diff vs v48...', flush=True)
v48_diff = diff_against_v48()
full_report = {
'shard_audit': {k: (len(v) if isinstance(v, list) and k not in ('d7_middle_truncated_examples',) else v) for k, v in agg.items()},
'shard_audit_any_failures': {k: v[:10] for k, v in agg.items() if isinstance(v, list) and v and k != 'd7_middle_truncated_examples'},
'sample_and_d10': samp_d10,
'check_H': check_h,
'diff_vs_v48': v48_diff,
}
json.dump(full_report, open(OUT_V49 + 'work/strict_validation.json', 'w'), indent=1)
print(json.dumps(full_report, indent=1), flush=True)
if __name__ == '__main__':
main()
|