"""Execute Checks F, G, and H: F. Oracle (solve.sh + grade.py) and perturbed-prediction grading on 50 random shard tasks + 50 random sample tasks + all 1,172 sample tasks check + template md5 identity across all tasks. G. Sample audit: verify 14-category selection under all 3 run definitions, verify 3-cuts-per-run rule (catching n=4 banker's rounding collision), report size, targets per task (min/median/mean/max), and copy-last & best-seen baselines on both sample (1,172 tasks, 6,517 targets) and full build. H. Determinism: rebuild 3 runs (1 each of families A, B, C) from raw trace tars with PEER_CACHE and AUDIT_NORM disabled, and diff every member byte-for-byte against out_v48/tasks/.tar.zst. Saves results to audit/v49/out/checks_FGH.json. """ import collections, glob, hashlib, io, json, math, os, random, shutil, statistics, subprocess, sys, tarfile, tempfile import zstandard V = '/' sys.path.insert(0, V + 'data/scripts') sys.path.insert(0, V + 'build_v2/scripts/v48') import v48lib as L import build as B48 SRC = '/release-20261202/' OUT_V48 = V + 'build_v2/out_v49/' SAMPLE_DIR = V + 'build_v2/sample_v49/' TMP_BASE = '' + str(os.getpid()) def run_grade(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 check_F(index): rng = random.Random(2026120399) pick50 = rng.sample(index, 50) by_fcs = collections.defaultdict(set) for r in pick50: by_fcs[r['fcs_task']].add(r['task_id']) os.makedirs(TMP_BASE, exist_ok=True) oracle_50 = [] perturb_checks = [] md5_templates = {'grade.py': set(), 'test.sh': set(), 'Dockerfile': set()} task_toml_net_ok = 0 total_tasks_scanned = 0 try: # Scan all 48 shards for template md5s + run oracle & perturbation tests on the 50 random tasks for fcs_path in sorted(glob.glob(OUT_V48 + 'tasks/*.tar.zst')): fcs = os.path.basename(fcs_path).replace('.tar.zst', '') want = by_fcs.get(fcs, set()) got = collections.defaultdict(dict) with open(fcs_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 tid, rel = m.name.split('/', 1) if rel == 'tests/grade.py': b = tf.extractfile(m).read() md5_templates['grade.py'].add(hashlib.md5(b).hexdigest()) if tid in want: got[tid][rel] = b elif rel == 'tests/test.sh': b = tf.extractfile(m).read() md5_templates['test.sh'].add(hashlib.md5(b).hexdigest()) elif rel == 'environment/Dockerfile': b = tf.extractfile(m).read() md5_templates['Dockerfile'].add(hashlib.md5(b).hexdigest()) elif rel == 'task.toml': b = tf.extractfile(m).read().decode() total_tasks_scanned += 1 if 'network_mode = "allowlist"' in b and 'allowed_hosts = ["api.anthropic.com"]' in b: task_toml_net_ok += 1 elif tid in want and rel in ('solution/solve.sh', 'tests/ground_truth.json'): got[tid][rel] = tf.extractfile(m).read() for tid in sorted(want): g = got[tid] res = run_grade(g['solution/solve.sh'], g['tests/grade.py'], g['tests/ground_truth.json'], TMP_BASE) oracle_50.append({'task_id': tid, 'reward': res['reward'], 'mae': res.get('mae'), 'valid': res['valid'], 'n_targets': res['n_targets']}) # Perturbed predictions test on ALL 50 random tasks: gt_obj = json.loads(g['tests/ground_truth.json'])['targets'] for delta in (2.5, 5.0, -4.0, 15.0): preds = [] exp_errs = [] for t in gt_obj: raw_p = t['score'] + delta clipped_p = max(0.0, min(100.0, raw_p)) exp_errs.append(abs(clipped_p - t['score'])) preds.append({'index': t['index'], 'score': raw_p}) exp_rew = sum(max(0.0, 1.0 - e / 10.0) for e in exp_errs) / len(exp_errs) exp_mae = sum(exp_errs) / len(exp_errs) pres = run_grade(None, g['tests/grade.py'], g['tests/ground_truth.json'], TMP_BASE, custom_pred=json.dumps({'predictions': preds, 'rationale': 'perturbed'})) ok = (pres['valid'] == 1 and abs(pres['reward'] - exp_rew) < 1e-9 and abs(pres['mae'] - exp_mae) < 1e-9) perturb_checks.append({'task_id': tid, 'delta': delta, 'ok': ok, 'got_reward': pres['reward'], 'exp_reward': exp_rew}) # Edge-case tests on grade.py (missing target, NaN, out-of-range clip, duplicate index, missing score key) sample_tid0 = sorted(by_fcs.values())[0] # Use first sample task for edge cases s_ids = [x.strip() for x in open(SAMPLE_DIR + 'ids.txt') if x.strip()] rng_s = random.Random(2026120377) pick50_sample = rng_s.sample(s_ids, 50) sample_oracle_50 = [] sample_oracle_all_fails = [] for tid in s_ids: td = os.path.join(SAMPLE_DIR, '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() md5_templates['grade.py'].add(hashlib.md5(gb).hexdigest()) md5_templates['test.sh'].add(hashlib.md5(open(td + '/tests/test.sh', 'rb').read()).hexdigest()) md5_templates['Dockerfile'].add(hashlib.md5(open(td + '/environment/Dockerfile', 'rb').read()).hexdigest()) if tid in pick50_sample: r50 = run_grade(sb, gb, gtb, TMP_BASE) sample_oracle_50.append({'task_id': tid, 'reward': r50['reward'], 'mae': r50.get('mae'), 'n_targets': r50['n_targets']}) # Fast check on all 1,172 sample tasks: run actual grade.py if solve.sh differs from gt gt_t = json.loads(gtb)['targets'] sol_p = {int(x['index']): float(x['score']) for x in json.loads(sb.decode().split("<<'EOF'\n")[1].split("\nEOF")[0])['predictions']} if any(int(t['index']) not in sol_p or abs(sol_p[int(t['index'])] - t['score']) > 1e-9 for t in gt_t): rf = run_grade(sb, gb, gtb, TMP_BASE) sample_oracle_all_fails.append({'task_id': tid, 'reward': rf['reward'], 'mae': rf.get('mae'), 'n_targets': rf['n_targets'], 'missing_indices': [t['index'] for t in gt_t if int(t['index']) not in sol_p]}) # Explicit edge cases on multi-target task multi_tid = next(tid for tid in s_ids if len(json.loads(open(f'{SAMPLE_DIR}/tasks/{tid}/tests/ground_truth.json').read())['targets']) >= 3) mtd = f'{SAMPLE_DIR}/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'] # Missing 1st target -> e_0 = 100, others 0 -> reward = (n-1)/n p_miss = json.dumps({'predictions': [{'index': t['index'], 'score': t['score']} for t in m_targets[1:]]}) r_miss = run_grade(None, gb, gtb, TMP_BASE, custom_pred=p_miss) # NaN on 1st target p_nan = '{"predictions": [{"index": ' + str(m_targets[0]['index']) + ', "score": NaN}, ' + ', '.join( json.dumps({'index': t['index'], 'score': t['score']}) for t in m_targets[1:]) + ']}' r_nan = run_grade(None, gb, gtb, TMP_BASE, custom_pred=p_nan) # Malformed entry without 'score' -> zeroes whole task (D10) p_mal = json.dumps({'predictions': [{'index': m_targets[0]['index']}] + [{'index': t['index'], 'score': t['score']} for t in m_targets[1:]]}) r_mal = run_grade(None, gb, gtb, TMP_BASE, custom_pred=p_mal) edge_cases = { 'multi_tid': multi_tid, 'n': len(m_targets), 'missing_one': {'got': r_miss['reward'], 'exp': (len(m_targets) - 1) / len(m_targets)}, 'nan_one': {'got': r_nan['reward'], 'exp': (len(m_targets) - 1) / len(m_targets)}, 'malformed_entry_d10': {'got_reward': r_mal['reward'], 'got_valid': r_mal['valid']}, } finally: shutil.rmtree(TMP_BASE, ignore_errors=True) return { 'shard_oracle_50_pass': sum(x['reward'] == 1.0 and x['valid'] == 1 for x in oracle_50), 'shard_oracle_50_total': len(oracle_50), 'shard_oracle_50_targets': sum(x['n_targets'] for x in oracle_50), 'perturb_all_ok': sum(x['ok'] for x in perturb_checks), 'perturb_total': len(perturb_checks), 'sample_oracle_50_pass': sum(x['reward'] == 1.0 for x in sample_oracle_50), 'sample_oracle_all_1172_fails': sample_oracle_all_fails, 'template_md5_counts': {k: sorted(v) for k, v in md5_templates.items()}, 'task_toml_allowlist_ok': f'{task_toml_net_ok}/{total_tasks_scanned}', 'edge_cases': edge_cases, } def check_G(index, fr): # 1. Verify category picks under all 3 definitions of "runs" tm = {} for t in fr['tasks']: tid = (t.get('task_id') or t.get('id')).replace('frontier-cs-2.0-', '').replace('-', '_') tm[tid] = t['category'] runs_all_1535 = collections.defaultdict(set) runs_scored_1471 = collections.defaultdict(set) for r in fr['runs']: runs_all_1535[r['task']].add(r['model_id']) if (r.get('n_train_submissions') or 0) > 0 or r.get('final_submission_status') == 'available' or (r.get('score') or 0) > 0: pass # Exact 1,471 runs with >=1 node from runs_trace_truth.jsonl runs_nodes_1471 = collections.defaultdict(set) for ln in open(V + 'audit/v2/out/runs_trace_truth.jsonl'): if ln.strip(): d = json.loads(ln) if d['n_nodes'] > 0: runs_nodes_1471[d['task']].add(d['model']) runs_v2_1428 = collections.defaultdict(set) for r in index: runs_v2_1428[r['fcs_task']].add(r['model']) def pick_by(run_counts): rng = random.Random(0) out = {} for c in sorted(set(tm.values())): ts = sorted(t for t, cat in tm.items() if cat == c) best = max(len(run_counts[t]) for t in ts) top = [t for t in ts if len(run_counts[t]) == best] chosen = rng.choice(top) if len(top) > 1 else top[0] out[c] = {'chosen': chosen, 'n_runs': best, 'tied': top} return out picks_v2 = pick_by(runs_v2_1428) picks_1471 = pick_by(runs_nodes_1471) picks_1535 = pick_by(runs_all_1535) s_json = json.load(open(SAMPLE_DIR + 'sample.json')) actual_picks = s_json['picks'] cat_comparison = {} for c in sorted(actual_picks): cat_comparison[c] = { 'sample_json': actual_picks[c], 'by_v2_runs_1428': picks_v2[c], 'by_node_runs_1471': picks_1471[c], 'by_all_runs_1535': picks_1535[c], 'diff_vs_1471': actual_picks[c] != picks_1471[c]['chosen'], 'diff_vs_1535': actual_picks[c] != picks_1535[c]['chosen'], } # 2. Check cuts per run on the 14 picked tasks picked_set = set(actual_picks.values()) by_run = collections.defaultdict(list) for r in index: if r['fcs_task'] in picked_set: by_run[(r['fcs_task'], r['model'])].append(r) s_ids = [x.strip() for x in open(SAMPLE_DIR + 'ids.txt') if x.strip()] s_set = set(s_ids) n4_collision_runs = [] cut_counts_dist = collections.Counter() for (ft, mod), rows in sorted(by_run.items()): rows_s = sorted(rows, key=lambda x: x['cut_result_index']) n = len(rows_s) in_samp = [r['task_id'] for r in rows_s if r['task_id'] in s_set] cut_counts_dist[(min(n, 5), len(in_samp))] += 1 if n >= 3 and len(in_samp) != 3: # Compute what round-half-up int(math.floor(q*(n-1) + 0.5)) would pick: pos_half_up = sorted({int(math.floor(q * (n - 1) + 0.5)) for q in (1/6, 1/2, 5/6)}) n4_collision_runs.append({ 'run': f'{ft}/{mod}', 'n_v2_tasks': n, 'drawn_count': len(in_samp), 'drawn_ids': in_samp, 'half_up_ids': [rows_s[p]['task_id'] for p in pos_half_up], }) # Also check how many runs of the 14 picked tasks exist in formal-results.json vs have nodes vs have v2 tasks fr_runs_in_14 = [r for r in fr['runs'] if r['task'] in picked_set] node_runs_in_14 = [k for k in runs_nodes_1471 if k in picked_set] # 3. Baselines on build_v2/sample_v49/ (1,172 tasks, 6,517 targets) def rw(e): return max(0.0, 1.0 - e / 10.0) B_tgt = collections.defaultdict(lambda: collections.defaultdict(list)) B_task = collections.defaultdict(list) B_task_mae = collections.defaultdict(list) by_cat_last = collections.defaultdict(list) nt_list = [] zero_targets = 0 within_05_last = 0 for tid in s_ids: td = os.path.join(SAMPLE_DIR, 'tasks', tid) gt_d = json.load(open(td + '/tests/ground_truth.json')) rinfo = json.load(open(td + '/environment/context/run_info.json')) subs = json.load(open(td + '/environment/context/submissions.json')) targets = gt_d['targets'] nt_list.append(len(targets)) # Recompute baselines directly from seen submissions in submissions.json (do not trust gt_d['baselines']!) 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 for name, val in (('last_seen', last_s), ('best_seen', best_s), ('zero', 0.0)): errs = [abs(val - t['score']) for t in targets] B_task[name].append(sum(rw(e) for e in errs) / len(errs)) B_task_mae[name].append(sum(errs) / len(errs)) if name == 'last_seen': by_cat_last[rinfo['category']].append(sum(rw(e) for e in errs) / len(errs)) for k, (t, e) in enumerate(zip(targets, errs)): B_tgt[name]['all'].append(e) B_tgt[name]['next' if k == 0 else 'later'].append(e) B_tgt[name]['final' if t['kind'] == 'final' else 'train'].append(e) B_tgt[name][t['state_at_cut']].append(e) for t in targets: if t['score'] == 0.0: zero_targets += 1 if abs(last_s - t['score']) <= 0.5: within_05_last += 1 sample_baselines = {} for name in ('last_seen', 'best_seen', 'zero'): sample_baselines[name] = { 'task_mean_reward': round(sum(B_task[name]) / len(B_task[name]), 4), 'task_mean_mae': round(sum(B_task_mae[name]) / len(B_task_mae[name]), 3), 'by_slice': { sl: { 'n': len(es), 'reward': round(sum(rw(e) for e in es) / len(es), 4), 'mae': round(sum(es) / len(es), 3), } for sl, es in B_tgt[name].items() } } return { 'n_categories': len(actual_picks), 'cat_comparison': cat_comparison, 'fr_runs_in_14_picked': len(fr_runs_in_14), 'runs_with_nodes_in_14_picked': sum(len(runs_nodes_1471[t]) for t in picked_set), 'runs_with_v2_tasks_in_14_picked': len(by_run), 'sample_tasks': len(s_ids), 'sample_targets': sum(nt_list), 'targets_per_task': { 'min': min(nt_list), 'median': statistics.median(nt_list), 'mean': round(sum(nt_list) / len(nt_list), 2), 'max': max(nt_list), }, 'zero_targets_in_sample': zero_targets, 'within_05_of_last_seen_share': round(within_05_last / sum(nt_list), 4), 'cut_counts_dist': {str(k): v for k, v in sorted(cut_counts_dist.items())}, 'n4_banker_rounding_collision_runs': len(n4_collision_runs), 'n4_collision_examples': n4_collision_runs[:10], 'n4_collision_all': n4_collision_runs, 'sample_baselines': sample_baselines, 'by_category_last_seen_task_reward': {c: round(sum(v)/len(v), 4) for c, v in sorted(by_cat_last.items())}, } def check_H(fr): # Pick 3 runs (1 Family A, 1 Family B, 1 Family C) with multiple tasks & payloads, disable PEER_CACHE & AUDIT_NORM! chosen_runs = [ ('edlib_exact_alignment', 'glm'), # Family A ('lrr', 'opus'), # Family B ('sparse_video_attention_policy', 'sol62') # Family C ] _, tm = B48.tasks_meta() run_lookup = {(r['task'], r['model_id']): r for r in fr['runs']} orig_pc, orig_an = L.PEER_CACHE, L.AUDIT_NORM L.PEER_CACHE = '/nonexistent_audit_check_H/' L.AUDIT_NORM = '/nonexistent_audit_check_H/' out_H = [] try: for fcs, mod in chosen_runs: run = run_lookup[(fcs, mod)] rebuilt = B48.one((run, tm)) assert rebuilt['source'] == 'tar', f'Expected tar source, got {rebuilt["source"]}' rebuilt_map = {} for t in rebuilt['tasks']: tid = t['task_id'] rebuilt_map[tid] = {name: (mode, data) for name, data, mode in t['members']} # Read from out_v48 shard shard_map = collections.defaultdict(dict) prefix_tids = set(rebuilt_map.keys()) # Also capture any task in shard belonging to this model! idx_tids = {r['task_id'] for r in json.load(open(OUT_V48 + 'metadata/task_index.json')) if r['fcs_task'] == fcs and r['model'] == mod} all_want = prefix_tids | idx_tids with open(OUT_V48 + 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 not m.isfile(): continue tid, rel = m.name.split('/', 1) if tid in all_want: shard_map[tid][rel] = (m.mode, tf.extractfile(m).read()) same_task_set = (set(rebuilt_map.keys()) == set(shard_map.keys())) diffs = [] n_files = 0 n_bytes = 0 for tid in sorted(all_want): rm = rebuilt_map.get(tid, {}) sm = shard_map.get(tid, {}) if set(rm.keys()) != set(sm.keys()): diffs.append((tid, 'member_set_diff', sorted(set(rm) ^ set(sm)))) continue for k in sorted(rm): n_files += 1 n_bytes += len(rm[k][1]) if rm[k][0] != sm[k][0]: diffs.append((tid, k, 'mode_diff', rm[k][0], sm[k][0])) if rm[k][1] != sm[k][1]: diffs.append((tid, k, 'bytes_diff', len(rm[k][1]), len(sm[k][1]))) out_H.append({ 'run': f'{fcs}/{mod}', 'family': rebuilt['family'], 'source_used': rebuilt['source'], 'n_tasks': len(rebuilt_map), 'n_files_compared': n_files, 'n_bytes_compared': n_bytes, 'same_task_set': same_task_set, 'diffs': diffs, }) finally: L.PEER_CACHE, L.AUDIT_NORM = orig_pc, orig_an return out_H def main(): index = json.load(open(OUT_V48 + 'metadata/task_index.json')) fr = json.load(open(SRC + 'metadata/formal-results.json')) print('Running Check F...', flush=True) res_F = check_F(index) print('F summary:', {k: v for k, v in res_F.items() if k != 'sample_oracle_all_1172_fails'}, 'sample_fails:', len(res_F['sample_oracle_all_1172_fails']), flush=True) print('Running Check G...', flush=True) res_G = check_G(index, fr) print('G summary: sample_tasks=', res_G['sample_tasks'], 'targets=', res_G['sample_targets'], 'n4_collisions=', res_G['n4_banker_rounding_collision_runs'], 'baselines=', res_G['sample_baselines']['last_seen']['task_mean_reward'], flush=True) print('Running Check H...', flush=True) res_H = check_H(fr) print('H summary:', res_H, flush=True) out_path = V + 'audit/v49/out/checks_FGH.json' json.dump({'F': res_F, 'G': res_G, 'H': res_H}, open(out_path, 'w'), indent=1) print('Saved', out_path, flush=True) if __name__ == '__main__': main()