File size: 32,879 Bytes
6faa02d
f666d3c
6faa02d
 
 
 
 
 
 
 
 
 
 
 
f666d3c
 
 
 
 
 
6faa02d
 
 
 
 
f666d3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4649fba
 
 
 
 
 
f666d3c
9868cc3
f666d3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4649fba
 
065f3c1
4649fba
 
 
 
065f3c1
 
 
 
4649fba
 
 
065f3c1
 
 
 
4649fba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f666d3c
 
4649fba
 
 
f666d3c
4649fba
f666d3c
 
4649fba
 
 
 
f666d3c
4649fba
f666d3c
 
 
 
9868cc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4649fba
 
9868cc3
4649fba
f666d3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4649fba
f666d3c
 
 
 
 
 
9868cc3
 
 
 
 
 
 
 
f666d3c
 
 
 
a4a97cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f666d3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4a97cd
 
f666d3c
 
 
9868cc3
a4a97cd
 
 
 
4649fba
 
 
f666d3c
39a8df6
f666d3c
 
 
9868cc3
 
f666d3c
 
 
a4a97cd
 
4649fba
 
f666d3c
 
4649fba
065f3c1
f666d3c
 
 
a4a97cd
 
 
 
 
 
f666d3c
 
 
a4a97cd
f666d3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6faa02d
f666d3c
 
a4a97cd
 
4649fba
 
9868cc3
 
f666d3c
a4a97cd
 
f666d3c
 
 
 
 
a4a97cd
 
 
f666d3c
 
 
 
 
 
6faa02d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f666d3c
6faa02d
 
 
 
f666d3c
 
6faa02d
 
 
 
f666d3c
4649fba
 
 
 
f666d3c
 
4649fba
 
a4a97cd
 
39a8df6
a4a97cd
 
 
 
 
 
9868cc3
 
 
 
f666d3c
 
9868cc3
6faa02d
 
 
 
9868cc3
a4a97cd
 
4649fba
a4a97cd
 
 
6faa02d
 
 
 
 
 
9868cc3
 
f666d3c
 
 
 
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
"""Select validated tasks from any FWeindel/validated-tasks release with a results.parquet.

A task is kept when every required rule-based check passed. Warnings and
not-applicable checks are fine; failed, errored, blocked or missing checks
remove the task. Optional judge and pass@4 filters apply only to releases that
have those columns (currently CalibForge v1.1).

Examples:
  python filter_tasks.py --dataset tmax11_v1.1 --out tmax-validated
  python filter_tasks.py --dataset tmax11_v1.1 --out tmax-validated --images tmax-images --wrap
  python filter_tasks.py --dataset calibforge_v1.1 --judge qwen --out calib-clean --images calib-images
  python filter_tasks.py --tasks tasks.parquet --results results.parquet --out validated

Needs pyarrow; --dataset and --images also need huggingface_hub; --wrap needs Apptainer and unsquashfs 4.4+.
"""
import argparse
from collections import Counter
import hashlib
import io
import json
import os
import re
import subprocess
import sys
import tempfile
from pathlib import Path
import tarfile


# Recorded default-training checks through deterministic validation and leakage.
# Upstream-only conventions and AI detection (user policy) are intentionally absent.
REQUIRED_CHECKS = (
    'agent_editable_test', 'artifact_efficiency', 'build', 'compose-host-binds',
    'declared_internet_access', 'declared_workdir', 'do_not_modify',
    'dockerfile-platform', 'dockerfile-references', 'dockerfile-sanity',
    'instruction-suffix', 'no-cheat-dir', 'no_behavioural_tests', 'nop',
    'nop_determinism', 'nproc', 'pip-pinning', 'python_missing_imports',
    'reference', 'reference_determinism', 'reference_leaks', 'repository_history',
    'repository_timestamps', 'resource-sizes', 'script_execution_coverage',
    'task-absolute-path', 'task-timeout', 'task-toml-schema',
    'test-file-references', 'verifier_paths', 'verifier_tamper',
)
JUDGE_CRITERIA = (
    'ANSWER-LEAK', 'INSTR-AMBIGUOUS', 'INSTR-ENV-MISMATCH',
    'INSTR-VERIFIER-CONTRADICTION', 'INSTR-VERIFIER-UNSTATED-REQUIREMENT',
    'TASK-TRIVIAL', 'VERIFIER-ACCEPTS-INCOMPLETE', 'VERIFIER-ACCEPTS-SHORTCUTS',
)
RIVER_CRITERIA = (
    'VERIFIER-TOO-WEAK', 'INSTR-VERIFIER-MISMATCH', 'INSTR-ENV-MISMATCH',
    'ANSWER-LEAK', 'INSTR-AMBIGUOUS', 'TASK-TRIVIAL', 'OTHER',
)
RUBRICS = {'ot_next_rubric': JUDGE_CRITERIA, 'river': RIVER_CRITERIA}
VOTES = ('first', 'majority')
JUDGES = {'qwen': 'Qwen/Qwen3.8-27B', 'glm': 'zai-org/GLM-5.3-Flash'}
PASSK_MODELS = {'qwen': 'passk_target', 'glm': 'passk_teacher'}
ACCEPTED = {'pass', 'warning', 'not_applicable'}
EXPERIMENT = {
    'clean': set(),
    'clean-plus-incomplete': {'VERIFIER-ACCEPTS-INCOMPLETE'},
    'clean-plus-shortcuts': {'VERIFIER-ACCEPTS-SHORTCUTS'},
}


def status(value):
    return value.get('status') if isinstance(value, dict) else value


def baseline_issues(row, checks=REQUIRED_CHECKS):
    return {key: status(row.get(key)) or 'missing' for key in checks
            if status(row.get(key)) not in ACCEPTED}


def judge_records(cell):
    """Read model records, retaining attempt order and provenance."""
    if isinstance(cell, str):
        try:
            cell = json.loads(cell)
        except ValueError:
            return {}
    if not isinstance(cell, dict):
        return {}
    old = cell.get('verdicts', cell.get('status'))
    if isinstance(old, (dict, list)):
        return {model: {'reviews': [{'status': s} for s in values]}
                for model, values in dict(old).items()}
    return {model: value
            for model, value in cell.items()
            if isinstance(value, dict) and 'status' in value}


def judge_statuses(cell):
    return {model: [r.get('status') for r in value.get('reviews', [value])]
            for model, value in judge_records(cell).items()}


def criterion_column(criterion, rubric='ot_next_rubric'):
    return 'river__' + criterion if rubric == 'river' else criterion


def judge_options(criteria, rubric, vote):
    if rubric not in RUBRICS:
        raise ValueError('Unknown rubric: ' + str(rubric))
    if vote not in VOTES:
        raise ValueError('Unknown vote: ' + str(vote))
    criteria = RUBRICS[rubric] if criteria is None else tuple(criteria)
    if not criteria or set(criteria) - set(RUBRICS[rubric]):
        raise ValueError('Criteria must belong to the selected rubric: ' + rubric)
    return criteria


def review_outcome(value, vote):
    reviews = value.get('reviews', [value])
    if not isinstance(reviews, list) or not reviews or any(not isinstance(r, dict) for r in reviews):
        return None
    # Explicit attempt numbers prevent a missing first attempt from becoming attempt 2.
    if any('attempt' in r for r in reviews):
        numbers = [r.get('attempt') for r in reviews]
        if any(type(n) is not int or n < 1 for n in numbers) or len(set(numbers)) != len(numbers):
            return None
        reviews = sorted(reviews, key=lambda r: r['attempt'])
        if vote == 'first':
            reviews = [r for r in reviews if r['attempt'] == 1]
        elif [r['attempt'] for r in reviews] != list(range(1, len(reviews) + 1)):
            return None
    elif vote == 'first':
        reviews = reviews[:1]
    if not reviews:
        return None
    if vote == 'majority':
        expected = value.get('expected_attempts', len(reviews))
        if type(expected) is not int or expected < 1 or len(reviews) != expected:
            return None
    if any(r.get('applicable_to_release') is False for r in reviews):
        return None
    statuses = [r.get('status') for r in reviews]
    if any(not isinstance(s, str) or s not in ACCEPTED | {'fail'} for s in statuses):
        return None
    failures = statuses.count('fail')
    if failures * 2 == len(statuses):
        return None  # A tie is unresolved, including when a failure is allowed.
    return 'fail' if failures * 2 > len(statuses) else 'pass'


def judge_failures(row, judge, criteria=None, *, rubric='ot_next_rubric', vote='first'):
    """Return failed criteria, or None when any required review is unresolved.

    First uses attempt 1 only. Majority requires every expected attempt to be
    resolved and a strict majority per criterion. Ties exclude the task.
    Other models and rubrics never vote.
    """
    criteria = judge_options(criteria, rubric, vote)
    failed = set()
    for criterion in criteria:
        cell = row.get(criterion_column(criterion, rubric)) or {}
        value = judge_records(cell).get(JUDGES.get(judge, judge), {})
        outcome = review_outcome(value, vote)
        if outcome is None:
            return None
        if outcome == 'fail':
            failed.add(criterion)
    return failed


def passk_successes(row, model):
    """Successful attempts in the selected complete four-attempt batch only."""
    cell = row.get(PASSK_MODELS[model])
    if not isinstance(cell, dict) or cell.get('status') not in ('pass', 'fail'):
        return None
    details = cell.get('details')
    if isinstance(details, str):
        try:
            details = json.loads(details)
        except ValueError:
            return None
    if not isinstance(details, dict) or details.get('k') != 4:
        return None
    batch = details.get('selected_batch')
    if not isinstance(batch, dict):
        return None
    successes = batch.get('successes')
    if type(batch.get('valid_attempts')) is not int or batch['valid_attempts'] != 4 or type(successes) is not int or not 0 <= successes <= 4:
        return None
    return successes


def validate_passk_filter(model, successes):
    if model is None and successes is None:
        return
    if model not in PASSK_MODELS or not successes:
        raise ValueError('--passk-model qwen|glm and --successes must be supplied together')
    if any(type(n) is not int or not 0 <= n <= 4 for n in successes):
        raise ValueError('--successes must contain integers from 0 to 4')


def select(rows, judge=None, allow_fail=(), criteria=None,
           passk_model=None, successes=None, *, rubric='ot_next_rubric', vote='first'):
    validate_passk_filter(passk_model, successes)
    criteria = judge_options(criteria, rubric, vote)
    allowed = set(allow_fail)
    if allowed - set(criteria):
        raise ValueError('Allowed failure must be one of the selected judge criteria')
    selected, reasons = {}, Counter()
    seen = set()
    for row in rows:
        name = row['task_id']
        if name in seen:
            raise ValueError(f'Duplicate result task ID: {name}')
        seen.add(name)
        issues = baseline_issues(row)
        if issues:
            reasons['validation_failed' if 'fail' in issues.values() else 'validation_incomplete'] += 1
            continue
        if judge:
            failures = judge_failures(row, judge, criteria, rubric=rubric, vote=vote)
            if failures is None:
                reasons['judge_incomplete'] += 1
                continue
            if failures - allowed:
                reasons['judge_failed_other_criteria'] += 1
                continue
        if passk_model:
            wins = passk_successes(row, passk_model)
            if wins is None:
                reasons['passk_incomplete'] += 1
                continue
            if wins not in successes:
                reasons['passk_successes_not_selected'] += 1
                continue
        selected[name] = row
    return selected, dict(reasons)


def environment_experiment(rows, judge, vote='first', clean_count=150, seed=42):
    """Experiment 2: a shared clean sample plus River-only environment defects."""
    if not judge:
        raise ValueError('--experiment-2 requires --judge')
    if type(clean_count) is not int or clean_count < 1:
        raise ValueError('--clean-count must be positive')
    judge_options(None, 'ot_next_rubric', vote)
    eligible, excluded = select(rows)
    clean, additions = {}, {}
    reasons = Counter(excluded)
    for name, row in eligible.items():
        ot = judge_failures(row, judge, rubric='ot_next_rubric', vote=vote)
        river = judge_failures(row, judge, rubric='river', vote=vote)
        if ot is None or river is None:
            reasons['judge_incomplete'] += 1
        elif not ot and not river:
            clean[name] = row
        elif not ot and river == {'INSTR-ENV-MISMATCH'}:
            additions[name] = row
        else:
            reasons['other_judge_failures'] += 1
    if len(clean) < clean_count:
        raise ValueError(f'Experiment 2 needs {clean_count} jointly clean tasks; only {len(clean)} available')
    # Hash ranking is reproducible across row order and Python versions.
    order = sorted(clean, key=lambda name: (hashlib.sha256(f'{seed}\0{name}'.encode()).hexdigest(), name))
    baseline = {name: clean[name] for name in order[:clean_count]}
    metadata = {'id': 2, 'clean_count': clean_count, 'selection_seed': seed,
                'sampling': 'lowest SHA256(seed + NUL + task_id), task_id tie-break',
                'eligible_clean_pool': len(clean), 'unused_clean_tasks': len(clean) - clean_count,
                'added_tasks': sorted(additions), 'added_count': len(additions),
                'candidate_repairability': 'Not independently verified by this filter',
                'excluded_from_both_pools': dict(reasons)}
    groups = {'clean': (baseline, dict(reasons)),
              'clean-plus-river-env-only': ({**baseline, **additions}, dict(reasons))}
    return groups, metadata


def payload_hash(binary):
    files = {}
    with tarfile.open(fileobj=io.BytesIO(binary), mode='r:*') as archive:
        for member in archive:
            name = Path(member.name).as_posix()
            if Path(name).is_absolute() or '..' in Path(name).parts:
                raise ValueError('Unsafe task archive path')
            if member.isfile():
                if name in files:
                    raise ValueError('Duplicate task archive path')
                files[name] = archive.extractfile(member).read()
            elif not member.isdir():
                raise ValueError('Unsupported task archive member')
    digest = hashlib.sha256()
    for name, data in sorted(files.items()):
        name = name.encode()
        digest.update(len(name).to_bytes(8, 'big') + name)
        digest.update(len(data).to_bytes(8, 'big') + data)
    return digest.hexdigest()


def subset_metadata(metadata, ids):
    metadata = dict(metadata or {})
    if b'ot.images.v1' in metadata:
        manifest = json.loads(metadata[b'ot.images.v1'])
        manifest['tasks'] = {k: v for k, v in manifest['tasks'].items() if k in ids}
        bundles = {e['bundle'] for t in manifest['tasks'].values() for e in t['environments']}
        manifest['bundles'] = {k: v for k, v in manifest['bundles'].items() if k in bundles}
        manifest['missing'] = [r for r in manifest.get('missing', []) if r.get('task') in ids]
        metadata[b'ot.images.v1'] = json.dumps(manifest, separators=(',', ':')).encode()
    return metadata


def export(tasks, results, out, judge=None, allow_fail=(), experiment2=False,
           criteria=None, passk_model=None, successes=None, *, rubric='ot_next_rubric', vote='first',
           river_env_experiment=False, clean_count=150, selection_seed=42):
    import pyarrow as pa
    import pyarrow.parquet as pq
    tasks, results, out = Path(tasks), Path(results), Path(out)
    validate_passk_filter(passk_model, successes)
    if river_env_experiment and (experiment2 or not judge or allow_fail or criteria is not None
                                 or passk_model or rubric != 'ot_next_rubric'):
        raise ValueError('--experiment-2 requires --judge and both complete rubrics; '
                         'cannot combine with --experiment-1, --rubric river, --criteria, --allow-fail or pass@4 filters')
    criteria = judge_options(criteria, rubric, vote)
    if experiment2 and rubric != 'ot_next_rubric':
        raise ValueError('--experiment-1 requires --rubric ot_next_rubric (the split verifier criteria)')
    if experiment2 and (not judge or allow_fail):
        raise ValueError('--experiment-1 requires --judge and cannot use --allow-fail')
    if allow_fail and not judge:
        raise ValueError('--allow-fail requires --judge')
    table = pq.read_table(results)
    if passk_model and PASSK_MODELS[passk_model] not in table.column_names:
        raise ValueError('Missing pass@4 column: ' + PASSK_MODELS[passk_model])
    absent = set(REQUIRED_CHECKS) - set(table.column_names)
    if absent:
        raise ValueError('Missing required validation columns: ' + ', '.join(sorted(absent)))
    columns = ([criterion_column(c, r) for r, cs in RUBRICS.items() for c in cs]
               if river_env_experiment else [criterion_column(c, rubric) for c in criteria])
    if judge and set(columns) - set(table.column_names):
        raise ValueError('Missing judge columns for ' + rubric + ': ' + ', '.join(sorted(set(columns) - set(table.column_names))))
    rows = table.to_pylist()
    if judge:
        available = {model for row in rows for criterion in columns
                     for model in judge_statuses(row.get(criterion))}
        if JUDGES.get(judge, judge) not in available:
            raise ValueError('No verdicts for judge ' + judge + '; available: ' + ', '.join(sorted(available)))
    variants = EXPERIMENT if experiment2 else {'selected': set(allow_fail)}
    experiment_metadata = None
    if river_env_experiment:
        groups, experiment_metadata = environment_experiment(rows, judge, vote, clean_count, selection_seed)
    else:
        groups = {name: select(rows, judge, allowed, criteria, passk_model, successes, rubric=rubric, vote=vote)
                  for name, allowed in variants.items()}
    source = pq.ParquetFile(tasks)
    schemas, writers, paths = {}, {}, {}
    for name, (selected, _) in groups.items():
        folder = out / name if experiment2 or river_env_experiment else out
        if (folder / 'tasks.parquet').exists() or (folder / 'results.parquet').exists():
            raise FileExistsError(f'Output already exists: {folder}')
        folder.mkdir(parents=True, exist_ok=True)
        paths[name] = folder
        schemas[name] = source.schema_arrow.with_metadata(subset_metadata(source.schema_arrow.metadata, set(selected)))
        writers[name] = pq.ParquetWriter(folder / 'tasks.parquet.partial', schemas[name])
    seen, written = set(), {name: set() for name in groups}
    try:
        for batch in source.iter_batches(batch_size=16):
            outputs = {name: [] for name in groups}
            for row in batch.to_pylist():
                task = row['path']
                if task in seen:
                    raise ValueError(f'Duplicate task payload: {task}')
                seen.add(task)
                matches = [name for name, (selected, _) in groups.items() if task in selected]
                if not matches:
                    continue
                digest = payload_hash(row['task_binary'])
                if row.get('content_sha256') and row['content_sha256'] != digest:
                    raise ValueError(f'Task content hash mismatch: {task}')
                for name in matches:
                    if groups[name][0][task].get('content_sha256') != digest:
                        raise ValueError(f'Results describe another task version: {task}')
                    outputs[name].append(row)
                    written[name].add(task)
            for name, output in outputs.items():
                if output:
                    writers[name].write_table(pa.Table.from_pylist(output, schema=schemas[name]))
        for name, (selected, _) in groups.items():
            if set(selected) - written[name]:
                raise ValueError(f'{name}: selected results have no task payload')
    finally:
        for writer in writers.values():
            writer.close()
    def file_identity(path):
        with path.open('rb') as stream:
            return {'path': str(path), 'sha256': sha256_file(path)}
    summary = {'inputs': {'tasks': file_identity(tasks), 'results': file_identity(results)},
               'judge': JUDGES.get(judge, judge), 'validation_checks': list(REQUIRED_CHECKS),
               'judge_criteria': {r: list(cs) for r, cs in RUBRICS.items()} if river_env_experiment else list(criteria) if judge else [],
               'judge_rubric': 'both' if river_env_experiment else rubric if judge else None,
               'judge_vote': vote if judge else None,
               'judge_tie_policy': 'exclude' if judge and vote == 'majority' else None,
               'passk_filter': {'model': passk_model, 'column': PASSK_MODELS[passk_model],
                                'k': 4, 'successes': sorted(set(successes))} if passk_model else None,
               'warnings_retained': True, 'incomplete_excluded': True, 'groups': {}}
    if experiment_metadata:
        summary['experiment'] = experiment_metadata
    for name, (selected, excluded) in groups.items():
        folder = paths[name]
        pq.write_table(pa.Table.from_pylist([selected[n] for n in sorted(written[name])], schema=table.schema),
                       folder / 'results.parquet')
        (folder / 'tasks.parquet.partial').rename(folder / 'tasks.parquet')
        allowed = ({'ot_next_rubric': [], 'river': ['INSTR-ENV-MISMATCH'] if name != 'clean' else []}
                   if river_env_experiment else sorted(variants[name]))
        summary['groups'][name] = {'tasks': len(written[name]), 'allowed_failures': allowed,
                                  'excluded': excluded, 'selection': sorted(written[name])}
    out.mkdir(parents=True, exist_ok=True)
    (out / 'selection.json').write_text(json.dumps(summary, indent=2) + '\n')
    return summary


REPO = 'FWeindel/validated-tasks'


def fetch_release(dataset, revision, cache):
    """Download one release's tasks.parquet and results.parquet."""
    from huggingface_hub import hf_hub_download
    return tuple(Path(hf_hub_download(REPO, f'{dataset}/{name}', repo_type='dataset',
                                      revision=revision, cache_dir=cache))
                 for name in ('tasks.parquet', 'results.parquet'))


def sha256_file(path):
    digest = hashlib.sha256()
    with open(path, 'rb') as stream:
        for block in iter(lambda: stream.read(8 << 20), b''):
            digest.update(block)
    return digest.hexdigest()


def optional_download(repo, path, revision, cache):
    from huggingface_hub import hf_hub_download
    from huggingface_hub.utils import EntryNotFoundError
    try:
        return Path(hf_hub_download(repo, path, repo_type='dataset', revision=revision, cache_dir=cache))
    except EntryNotFoundError:
        return None


def place(source, target, sha256):
    """Copy a downloaded file into the image folder and check its hash."""
    import shutil
    if target.exists():
        if sha256 and sha256_file(target) != sha256:
            raise ValueError(f'{target} exists with a different hash; remove it first')
        return
    partial = target.with_name(target.name + '.partial')
    shutil.copyfile(source, partial)
    if sha256 and sha256_file(partial) != sha256:
        partial.unlink()
        raise ValueError(f'Hash mismatch for {target.name}')
    partial.rename(target)


def cached_bundle_images(manifest, ids, dataset, revision, out, cache):
    """Releases with cached_images/: copy each selected task's recorded SIFs."""
    from huggingface_hub import hf_hub_download
    from huggingface_hub.utils import EntryNotFoundError
    repo = manifest.get('repo_id') or REPO
    revision = manifest.get('revision') or revision
    missing = {r['task']: r.get('reason') for r in manifest.get('missing', [])}
    report = {}
    for task in sorted(ids):
        entry = manifest.get('tasks', {}).get(task)
        if not entry:
            report[task] = {'status': 'missing', 'reason': missing.get(task, 'not in image manifest')}
            continue
        files = []
        for environment in entry['environments']:
            bundle = environment['bundle']
            for name, info in manifest['bundles'][bundle]['files'].items():
                base = f'{dataset}/cached_images/bundles-v1/{bundle}/{name}'
                for path in (f'{base}/{name}', base):  # uploads nest each file in a folder of its name
                    try:
                        local = hf_hub_download(repo, path, repo_type='dataset', revision=revision, cache_dir=cache)
                        break
                    except EntryNotFoundError:
                        local = None
                if local is None:
                    raise ValueError(f'{task}: bundle file {name} is listed but not uploaded')
                place(local, out / name, info.get('sha256'))
                files.append(name)
        report[task] = {'status': 'ok', 'files': files}
    return report


def squashfs_offset(sif):
    out = subprocess.run(['apptainer', 'sif', 'list', str(sif)], check=True, capture_output=True, text=True).stdout
    rows = [l for l in out.splitlines() if 'FS (Squashfs' in l]
    if len(rows) != 1:
        raise ValueError(f'{sif}: expected one squashfs partition')
    return int(re.search(r'\|(\d+)-(\d+)\s*\|', rows[0]).group(1))

def contents_sha256(sif, scratch=None):
    """Hash an image's files (paths, modes, owners, sizes, contents) without build timestamps.

    Rebuilding the same image changes the SIF header, file times and the build-date
    label, so file hashes of two identical builds differ. This hash does not.
    Needs unsquashfs 4.4 or newer.
    """
    off = str(squashfs_offset(sif))
    listing = subprocess.run(['unsquashfs', '-o', off, '-lln', '-no-progress', str(sif)],
                             check=True, capture_output=True, text=True).stdout
    entries = []
    for line in listing.splitlines():
        m = re.match(r'^(\S+) (\S+) +(\d+|\d+, *\d+) \d{4}-\d\d-\d\d \d\d:\d\d (squashfs-root.*)$', line)
        if m:
            entries.append(m.groups())
    with tempfile.TemporaryDirectory(dir=scratch, prefix='tree-') as tmp:
        root = Path(tmp) / 'root'
        subprocess.run(['unsquashfs', '-o', off, '-d', str(root), '-no-progress', '-no-xattrs',
                        '-ignore-errors', '-quiet', str(sif)], capture_output=True)
        digest = hashlib.sha256()
        for perms, owner, size, name in sorted(entries, key=lambda e: e[3]):
            content = ''
            if name == 'squashfs-root/.singularity.d/labels.json':
                labels = json.loads((root / '.singularity.d/labels.json').read_text())
                labels.pop('org.label-schema.build-date', None)  # the only per-build value
                content, size = hashlib.sha256(json.dumps(labels, sort_keys=True).encode()).hexdigest(), ''
            elif perms.startswith('-'):
                h = hashlib.sha256()
                with open(root / name[len('squashfs-root'):].lstrip('/'), 'rb') as f:
                    for block in iter(lambda: f.read(8 << 20), b''):
                        h.update(block)
                content = h.hexdigest()
            digest.update(f'{name}\0{perms}\0{owner}\0{size}\0{content}\n'.encode())
    return digest.hexdigest()


def upstream_images(manifest, ids, out, wrap, cache):
    """Releases with images.json: fetch the pinned upstream SIF and optionally rebuild our wrapper."""
    from huggingface_hub import hf_hub_download
    report, built, checked = {}, {}, {}
    for task in sorted(ids):
        blob = manifest['tasks'].get(task)
        if not blob:
            report[task] = {'status': 'missing', 'reason': 'not in images.json'}
            continue
        entry = manifest['images'][blob]
        source = Path(hf_hub_download(manifest['upstream_repository'], entry.get('upstream_path', blob),
                                      repo_type='dataset', revision=manifest['upstream_revision'],
                                      cache_dir=cache))
        if not wrap:
            report[task] = {'status': 'base_only', 'base_image': str(source),
                            'note': 'run again with --wrap to build the validated image'}
            continue
        target = out / manifest['cache_filenames'][task]
        if not target.exists():
            if blob in built:
                os.link(built[blob], target)
            else:
                with tempfile.TemporaryDirectory(prefix='wrap-') as temp:
                    definition = Path(temp) / 'image.def'
                    definition.write_text(f'Bootstrap: localimage\nFrom: {source}\n\n%post\n' +
                                          ''.join(f'    {c}\n' for c in entry['wrapper_commands']))
                    partial = target.with_name(target.name + '.partial')
                    subprocess.run(['apptainer', 'build', '--force', str(partial), str(definition)], check=True)
                    partial.rename(target)
        built.setdefault(blob, target)
        expected = entry.get('wrapped_contents_sha256')
        if blob not in checked:
            checked[blob] = contents_sha256(target, out)
        report[task] = {'status': 'ok', 'files': [target.name], 'contents_sha256': checked[blob],
                        'matches_validated_image': None if expected is None else checked[blob] == expected}
        if expected is not None and checked[blob] != expected:
            report[task]['status'] = 'mismatch'
            print(f'warning: {target.name} differs from the validated image', file=sys.stderr)
    return report


def fetch_images(dataset, revision, tasks_file, ids, out, wrap, cache):
    import pyarrow.parquet as pq
    out.mkdir(parents=True, exist_ok=True)
    metadata = pq.ParquetFile(tasks_file).schema_arrow.metadata or {}
    if b'ot.images.v1' in metadata:
        manifest = json.loads(metadata[b'ot.images.v1'])
    else:
        path = dataset and optional_download(REPO, f'{dataset}/cached_images/manifest.json', revision, cache)
        manifest = json.loads(path.read_text()) if path else None
    if manifest and manifest.get('tasks'):
        report = cached_bundle_images(manifest, ids, dataset, revision, out, cache)
    else:
        path = dataset and optional_download(REPO, f'{dataset}/images.json', revision, cache)
        if not path:
            raise ValueError('This release has no usable image manifest yet' +
                             (f' (cached_images status: {manifest.get("status")})' if manifest else ''))
        report = upstream_images(json.loads(path.read_text()), ids, out, wrap, cache)
    (out / 'images-report.json').write_text(json.dumps(report, indent=2) + '\n')
    return Counter(r['status'] for r in report.values())


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('--dataset', help='Release folder on the Hub, e.g. tmax11_v1.1; downloads its Parquets')
    parser.add_argument('--revision', default='main', help='Hub revision for --dataset (default: main)')
    parser.add_argument('--cache-dir', type=Path, help='Hugging Face download cache (default: HF_HOME)')
    parser.add_argument('--tasks', type=Path, default=Path('tasks.parquet'))
    parser.add_argument('--results', type=Path, default=Path('results.parquet'))
    parser.add_argument('--images', type=Path, metavar='DIR',
                        help='Also download the images of the selected tasks into DIR')
    parser.add_argument('--wrap', action='store_true',
                        help='For releases that point to upstream images: build the validated wrapper (needs Apptainer)')
    parser.add_argument('--judge', help='qwen, glm, or exact model ID; omitted = validation only')
    parser.add_argument('--rubric', choices=RUBRICS, default='ot_next_rubric',
                        help='Judge rubric (default: ot_next_rubric)')
    parser.add_argument('--vote', choices=VOTES, default='first',
                        help='Use first attempt or strict majority across attempts; ties excluded (default: first)')
    parser.add_argument('--allow-fail', action='append', default=[], metavar='CRITERION',
                        help='Allow this judge criterion to fail; all others must pass (repeatable)')
    parser.add_argument('--criteria', nargs='+',
                        help='Judge criteria to enforce; default = every criterion in the selected rubric')
    experiments = parser.add_mutually_exclusive_group()
    experiments.add_argument('--experiment-1', action='store_true',
                        help='Export all three Experiment 1 groups')
    experiments.add_argument('--experiment-2', action='store_true',
                        help='Export the shared clean baseline and baseline plus River-only environment defects')
    parser.add_argument('--clean-count', type=int, default=150,
                        help='Experiment 2 clean baseline size (default: 150)')
    parser.add_argument('--selection-seed', type=int, default=42,
                        help='Experiment 2 deterministic clean-sample seed (default: 42)')
    parser.add_argument('--passk-model', choices=PASSK_MODELS,
                        help='Filter completed pass@4 results for Qwen3.5-35B-A3B or GLM-5.3-Flash')
    parser.add_argument('--successes', type=int, nargs='+', choices=range(5),
                        help='Keep these numbers of successful attempts out of four, requires --passk-model')
    parser.add_argument('--out', type=Path, required=True)
    args = parser.parse_args()
    try:
        if args.wrap and not args.images:
            raise ValueError('--wrap requires --images')
        if args.dataset:
            args.tasks, args.results = fetch_release(args.dataset, args.revision, args.cache_dir)
        validate_passk_filter(args.passk_model, args.successes)
        if not args.experiment_2 and (args.clean_count != 150 or args.selection_seed != 42):
            raise ValueError('--clean-count and --selection-seed apply only to --experiment-2')
        summary = export(args.tasks, args.results, args.out, args.judge, args.allow_fail,
                         args.experiment_1, args.criteria, args.passk_model, args.successes,
                         rubric=args.rubric, vote=args.vote, river_env_experiment=args.experiment_2,
                         clean_count=args.clean_count, selection_seed=args.selection_seed)
        print(json.dumps({k: v['tasks'] for k, v in summary['groups'].items()}, indent=2))
        if args.images:
            ids = {t for group in summary['groups'].values() for t in group['selection']}
            counts = fetch_images(args.dataset, args.revision, args.tasks, ids, args.images,
                                  args.wrap, args.cache_dir)
            print('images:', json.dumps(dict(counts)))
    except ValueError as exc:
        parser.error(str(exc))


if __name__ == '__main__':
    main()