File size: 41,718 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Tests of amendment 3.4: the leader selection (E2, selection.leaders and select_leaders.py), B1 and B2 from the final checkpoints (E4) and the line arms'
long2x checkpoint (E5). usage: python -I test_leaders.py [workdir]. Synthetic data only: no real prediction, manifest or score file is read."""
import copy
import json
import os
import shutil
import subprocess
import sys
import tempfile
import traceback

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
sys.path.insert(0, os.path.join(HERE, "..", "src"))

import synth_world as sw  # noqa: E402
from r5eval import selection, verdictgather  # noqa: E402

SCORE = os.path.join(HERE, "..", "scripts", "r5eval", "score.py")
LEADERS = os.path.join(HERE, "..", "scripts", "r5eval", "select_leaders.py")
RESULTS = []
W = {"root": sys.argv[1] if len(sys.argv) > 1 else tempfile.mkdtemp(prefix="r5leaders_")}
if os.path.exists(W["root"]):
    shutil.rmtree(W["root"])
os.makedirs(W["root"])


def test(fn):
    try:
        fn()
        RESULTS.append((fn.__name__, True))
        print("PASS", fn.__name__)
    except Exception:  # noqa: BLE001
        RESULTS.append((fn.__name__, False))
        print("FAIL", fn.__name__)
        print(traceback.format_exc())
    return fn


def score(root):
    r = subprocess.run([sys.executable, "-I", SCORE, "--registry", os.path.join(root, "reg.json"), "--preds", os.path.join(root, "preds"), "--out", os.path.join(root, "scores"),
                        "--B", "100", "--settle", "0", "--ktrain", os.path.join(root, "no_ktrain.json")], capture_output=True, text=True)
    assert r.returncode == 0, r.stderr[-1500:]


def world(name, spec):
    """spec: list of (arm, checkpoint, damage rate, meta kwargs). Writes V1 predictions and meta.json for each and scores them."""
    root = os.path.join(W["root"], name)
    os.makedirs(root)
    man = os.path.join(root, "manifests")
    v1 = sw.make_manifest(os.path.join(man, "kohtd_screen_v1.tsv"), "v1", 20, 10, seed=21)
    sw.write_registry(os.path.join(root, "reg.json"), [{"name": "V1", "manifest": os.path.join(man, "kohtd_screen_v1.tsv"), "split": "val", "locked": False}])
    W[name + "_v1"] = v1
    for i, (arm, ck, rate, meta) in enumerate(spec):
        sw.write_preds(os.path.join(root, "preds", arm, ck, "V1.tsv"), v1, rate, seed=100 + i)
        sw.write_meta(os.path.join(root, "preds", arm, ck, "meta.json"), **meta)
    score(root)
    return root


# ---------------------------------------------------------------------------------------------------------------- E2: the leaders
LEAD_SPEC = [("m_a", "short", 0.02, {}), ("m_a", "short_retry", 0.03, {}), ("m_b", "short", 0.06, {}), ("l_d", "short", 0.12, {}), ("m_e", "short", 0.20, {}),
             ("s_c", "short", 0.30, {}),
             ("short_p", "short", 0.01, {"samples_seen": 99936, "train_flag": "short of P (3.0 h training cap reached)"}),
             ("flagged", "short", 0.015, {}), ("few", "short", 0.017, {"samples_seen": 140000}), ("outside", "short", 0.005, {}),
             ("A1", "short", 0.001, {}), ("R1", "short", 0.001, {}),
             ("t_a", "short", 0.40, {}), ("t_b", "short", 0.40, {})]
INFO = {"m_a": {"unique_params_b": 1.0}, "m_b": {"unique_params_b": 0.9}, "l_d": {"unique_params_b": 2.0}, "m_e": {"unique_params_b": 1.2}, "s_c": {"unique_params_b": 0.3},
        "short_p": {"unique_params_b": 2.5}, "flagged": {"unique_params_b": 0.8, "flags": ["short of P: stopped by the 3-hour training cap at 131,456 of 150,000 samples"]},
        "few": {"unique_params_b": 0.4}, "outside": {"unique_params_b": 0.2}, "late": {"unique_params_b": 0.6}, "t_a": {"unique_params_b": 1.0}, "t_b": {"unique_params_b": 1.0}}
ALLOW = {"m_a", "m_b", "l_d", "m_e", "s_c", "short_p", "flagged", "few", "ghost", "late", "t_a", "t_b"}


def lead_world():
    if "lead" not in W:
        W["lead"] = world("lead", LEAD_SPEC)
        v1 = W["lead_v1"]                                      # an arm whose predictions arrive after the last scoring run: present but not scored
        sw.write_preds(os.path.join(W["lead"], "preds", "late", "short", "V1.tsv"), v1, 0.001, seed=555)
        sw.write_meta(os.path.join(W["lead"], "preds", "late", "short", "meta.json"))
    return W["lead"]


@test
def t_leaders_rule_a_b_c_and_eligibility():
    root = lead_world()
    res = selection.leaders(os.path.join(root, "scores"), os.path.join(root, "preds"), copy.deepcopy(INFO), ALLOW, B=200)
    assert [x["arm"] for x in res["leaders"]] == ["m_a", "m_b"]                       # lowest V1 among the eligible arms, strict order
    assert res["extra_b"]["arm"] == "l_d" and res["extra_c"]["arm"] == "m_e"          # (b) lowest outside the leaders' class (middle); (c) next lowest not chosen
    assert res["n_runs"] == 6 and [x["seeds"] for x in res["runs_to_leader_length"]] == [2, 2, 1, 1]
    for x in res["runs_to_leader_length"]:
        assert x["v1_cer"] is not None and len(x["v1_cer_ci95"]) == 2 and x["size_class"] in ("small", "middle", "large") and x["samples_seen"] == 150000
    ne = {x["arm"]: x["reasons"] for x in res["not_eligible"]}
    assert set(ne) >= {"short_p", "flagged", "few", "late"}
    assert "short of P" in ne["short_p"][0] and "short of P" in ne["flagged"][0] and "below the full P_short" in ne["few"][0]    # flag in meta, flag in arms_info, samples
    assert "short of P: short of P" not in ne["flagged"][0] and "short of P: short of P" not in ne["short_p"][0]        # the flag text is not prefixed twice
    assert any("r5_score.sbatch" in r for r in ne["late"])                              # predictions without a score: score first
    unf = res["leaders_if_the_eligibility_filter_were_not_applied"]
    by_v1 = [t["arm"] for t in sorted(res["table"], key=lambda t: (t["v1_cer"] is None, t["v1_cer"] or 0, t["arm"])) if t["v1_cer"] is not None]
    assert unf == by_v1[:2] and set(unf) <= {"short_p", "flagged", "few"} and res["eligibility_filter_changes_the_leaders"] is True    # all three ineligible arms have the lowest V1
    assert [o["arm"] for o in res["outside_allow_list"]] == ["outside"]               # not silently dropped, not considered
    names = {t["arm"] for t in res["table"]}
    assert "A1" not in names and "R1" not in names and "outside" not in names           # line and reference arms are not VLM arms
    assert res["not_started_or_not_finished"] == ["ghost"]
    assert any("ghost" in w and "late" in w for w in res["warnings"]) and any("outside" in w for w in res["warnings"])
    row = {t["arm"]: t for t in res["table"]}["m_a"]
    assert row["v1_cer_short_retry"] is not None and row["v1_cer_short_retry"] > row["v1_cer"]       # the retry's V1 is shown beside, never used
    # H14: paired intervals among the six lowest eligible arms (five eligible arms: ten pairs; t_a and t_b are the sixth and seventh by V1)
    pw = res["pairwise_top6_v1"]
    assert pw["arms_in_order_of_V1_CER"][:5] == ["m_a", "m_b", "l_d", "m_e", "s_c"] and len(pw["arms_in_order_of_V1_CER"]) == 6 and len(pw["pairs"]) == 15
    assert res["within_5_percent_of_the_lowest_eligible"][0]["arm"] == "m_a"


@test
def t_leaders_classes_and_ties():
    root = lead_world()
    sc, pr = os.path.join(root, "scores"), os.path.join(root, "preds")
    info = copy.deepcopy(INFO)
    info["m_b"]["unique_params_b"] = 0.3                                              # leaders now in the middle and the small class: (b) must come from the large class
    res = selection.leaders(sc, pr, info, ALLOW, B=100)
    assert [x["arm"] for x in res["leaders"]] == ["m_a", "m_b"] and res["extra_b"]["arm"] == "l_d" and res["extra_c"]["arm"] == "m_e"
    info = copy.deepcopy(INFO)
    info["l_d"]["unique_params_b"], info["s_c"]["unique_params_b"], info["t_a"]["unique_params_b"], info["t_b"]["unique_params_b"] = 1.1, 1.3, 1.4, 1.4   # every eligible arm is middle
    res = selection.leaders(sc, pr, info, ALLOW, B=100)
    assert res["extra_b"] is None and any("extra arm (b)" in w for w in res["warnings"])      # no class without a leader: no (b), and nothing invented
    assert res["extra_c"]["arm"] == "l_d"                                              # (c) is still the next lowest remaining
    info = copy.deepcopy(INFO)
    info["m_a"]["unique_params_b"] = None                                              # a leader without a parameter count: its class is unknown
    res = selection.leaders(sc, pr, info, ALLOW, B=100)
    assert any("no unique parameter count" in w for w in res["warnings"])
    info = copy.deepcopy(INFO)
    info["s_c"]["unique_params_b"] = None
    res = selection.leaders(sc, pr, info, {"m_a", "s_c", "t_a"}, B=100)                # an arm of unknown class can be (c), never (b)
    assert res["leaders"][0]["arm"] == "m_a" and res["extra_b"] is None
    # an exact tie is broken by the arm name; there is no speed tie-break for leaders
    res = selection.leaders(sc, pr, copy.deepcopy(INFO), {"m_a", "t_a", "t_b"}, B=100)
    assert [x["arm"] for x in res["leaders"]] == ["m_a", "t_a"] and res["extra_c"]["arm"] == "t_b"


@test
def t_select_leaders_cli_writes_its_own_file_only():
    root = lead_world()
    t1, t2 = os.path.join(root, "vlma.tsv"), os.path.join(root, "vlmb.tsv")
    with open(t1, "w") as f:
        f.write("short\tsize_class\tparams_unique_design\nm_a\tmiddle\t1000000000\nm_b\tmiddle\t900000000\nl_d\tlarge\t2000000000\nm_e\tmiddle\t1200000000\n")
    with open(t2, "w") as f:
        f.write("short\tsize_class\tparams_unique_design\ns_c\tsmall\t300000000\nshort_p\tlarge\t2500000000\nflagged\tmiddle\t800000000\nfew\tsmall\t400000000\n"
                "t_a\tmiddle\t1000000000\nt_b\tmiddle\t1000000000\n")
    json.dump({"_what": "comment", "flagged": {"flags": ["short of P: stopped by the 3-hour training cap"]}}, open(os.path.join(root, "arms_info.json"), "w"))
    out = os.path.join(root, "leaders_selection.json")
    r = subprocess.run([sys.executable, "-I", LEADERS, "--scores", os.path.join(root, "scores"), "--preds", os.path.join(root, "preds"), "--out", out,
                        "--arms-info", os.path.join(root, "arms_info.json"), "--models-tsv", t1 + "," + t2, "--B", "100"], capture_output=True, text=True)
    assert r.returncode == 0, r.stdout[-800:] + r.stderr[-1500:]
    res = json.load(open(out))
    assert [x["arm"] for x in res["leaders"]] == ["m_a", "m_b"] and res["extra_b"]["arm"] == "l_d" and res["extra_c"]["arm"] == "m_e"    # parameter counts from two tables
    assert os.path.exists(out + ".sha256") and res["inputs"]["report_code_sha256"] and res["inputs"]["n_arms_in_allow_list"] == 10
    assert not os.path.exists(os.path.join(root, "leaders.json")) and not os.path.exists(os.path.join(root, "selection.json"))     # never writes the selection files
    assert "leaders:" in r.stdout and "WARNING" in r.stdout


# ---------------------------------------------------------------------------------------------------------------- E4: B1 and B2 from the final checkpoints
FIN_SPEC = [("lead_a", "short", 0.12, {}), ("lead_a", "leader", 0.06, {"samples_seen": 300000}), ("lead_a", "leader_seed2", 0.08, {"samples_seen": 300000}),
            ("lead_b", "short", 0.14, {}), ("lead_b", "leader", 0.03, {"samples_seen": 300000}),
            ("short_only", "short", 0.02, {})]
FIN_INFO = {"lead_a": {"unique_params_b": 1.0}, "lead_b": {"unique_params_b": 2.0}, "short_only": {"unique_params_b": 0.3}}


def fin_world():
    if "fin" not in W:
        W["fin"] = world("fin", FIN_SPEC)
    return W["fin"]


@test
def t_b1_b2_from_final_checkpoints_at_leader_length():
    root = fin_world()
    sc, pr = os.path.join(root, "scores"), os.path.join(root, "preds")
    s = selection.select(sc, copy.deepcopy(FIN_INFO), preds_dir=pr, vlm_allow={"lead_a", "lead_b", "short_only"})
    assert s["B1"] == "lead_b" and s["provisional"] is False                            # lowest at leader length; short_only (0.02 at P_short) can not be B1
    assert s["B2"] == "lead_a"                                                          # a leader-length arm of another class beats the P_short arm of a third class
    r1, r2 = s["roles"]["B1"], s["roles"]["B2"]
    assert r1["seeds"] == 1 and "single seed" in r1["single_seed_note"] and r1["samples_seen"] == 300000 and r1["at_leader_length"] is True
    assert r2["seeds"] == 2 and r2["seed2_checkpoint"] == "leader_seed2" and "single_seed_note" not in r2
    row = {t["arm"]: t for t in s["table"]}
    assert abs(row["lead_a"]["v1_cer"] - sum(row["lead_a"]["v1_cer_seeds"]) / 2) < 1e-12      # the seed mean is its V1 CER
    fb = s["final_checkpoint_budgets"]
    assert fb["equal_budget_E3"] is True and [x["arm"] for x in fb["arms_left_at_P_short"]] == ["short_only"]
    assert [x["arm"] for x in fb["arms_at_leader_length"]] == ["lead_a", "lead_b"]
    assert s["pairwise_top6_v1"]["arms_in_order_of_V1_CER"] == ["lead_b", "lead_a"]      # the intervals compare final checkpoints at one budget only
    # the provisional dry run lets the P_short arm compete and says so
    p = selection.select(sc, copy.deepcopy(FIN_INFO), preds_dir=pr, vlm_allow={"lead_a", "lead_b", "short_only"}, strict_final=False)
    assert p["B1"] == "short_only" and p["provisional"] is True and any("PROVISIONAL" in w for w in p["warnings"])
    # B2 falls back to an arm left at P_short only when no arm of another size class reached leader length
    f = selection.select(sc, copy.deepcopy(FIN_INFO), preds_dir=pr, vlm_allow={"lead_b", "short_only"})
    assert f["B1"] == "lead_b" and f["B2"] == "short_only" and "no arm of another size class reached leader length" in f["B2_reason"]
    assert any("DIFFERENT BUDGETS" in w for w in f["warnings"]) and f["roles"]["B2"]["at_leader_length"] is False
    # nobody at leader length: no B1, and the reason says why
    n = selection.select(sc, copy.deepcopy(FIN_INFO), preds_dir=pr, vlm_allow={"short_only"})
    assert n["B1"] is None and "leader length" in n["B1_reason"] and n["B2"] is None
    # unequal budgets among the leader-length runs are flagged (E3)
    mp = os.path.join(pr, "lead_b", "leader", "meta.json")
    m = json.load(open(mp))
    m["samples_seen"] = 250000
    json.dump(m, open(mp, "w"))
    u = selection.select(sc, copy.deepcopy(FIN_INFO), preds_dir=pr, vlm_allow={"lead_a", "lead_b", "short_only"})
    assert u["final_checkpoint_budgets"]["equal_budget_E3"] is False and any("equal samples_seen" in w for w in u["warnings"])
    m["samples_seen"] = 300000
    json.dump(m, open(mp, "w"))


@test
def t_select_cli_strict_by_default_and_provisional_on_request():
    root = fin_world()
    json.dump({"lead_a": {"unique_params_b": 1.0}, "lead_b": {"unique_params_b": 2.0}, "short_only": {"unique_params_b": 0.3}}, open(os.path.join(root, "arms_info.json"), "w"))
    sel_py = os.path.join(HERE, "..", "scripts", "r5eval", "select_b1b2.py")
    base = [sys.executable, "-I", sel_py, "--scores", os.path.join(root, "scores"), "--preds", os.path.join(root, "preds"), "--arms-info", os.path.join(root, "arms_info.json"),
            "--vlm-arms", "lead_a,lead_b,short_only"]
    r = subprocess.run(base + ["--out", os.path.join(root, "sel_strict.json")], capture_output=True, text=True)
    assert r.returncode == 0, r.stderr[-1500:]
    assert json.load(open(os.path.join(root, "sel_strict.json")))["B1"] == "lead_b"
    r = subprocess.run(base + ["--out", os.path.join(root, "sel_prov.json"), "--allow-short-b1"], capture_output=True, text=True)
    assert r.returncode == 0, r.stderr[-1500:]
    p = json.load(open(os.path.join(root, "sel_prov.json")))
    assert p["B1"] == "short_only" and p["provisional"] is True and "NOTE: PROVISIONAL" in r.stdout


# ---------------------------------------------------------------------------------------------------------------- E5: long2x for the line arms
LINE_SPEC = [("A1", "short", 0.06, {"samples_seen": 150016}), ("A1", "long", 0.05, {"samples_seen": 1584384}), ("A1", "long2x", 0.04, {"samples_seen": 3168768}),
             ("A1", "long_seed2", 0.055, {"samples_seen": 1584384}),
             ("A2", "short", 0.07, {"samples_seen": 150016}), ("A2", "long", 0.06, {"samples_seen": 1584384}), ("A2", "long2x", 0.05, {"samples_seen": 3000000}),
             ("A2", "long_seed2", 0.065, {"samples_seen": 1584384}),
             ("A4", "short", 0.9, {"samples_seen": 150016})]                                                  # an arm with no long folder at all (the real arms_info pins it to 'short')


@test
def t_line_final_checkpoint_long2x_budget_and_seeds():
    root = world("line", LINE_SPEC)
    sc, pr = os.path.join(root, "scores"), os.path.join(root, "preds")
    s = selection.select(sc, {}, preds_dir=pr, vlm_allow={"nobody"})
    a1, a2 = s["roles"]["A1"], s["roles"]["A2"]
    # clarification J1: TWO checkpoints per line role. Section 3 reads the P_long checkpoint 'long' (two seeds); section 4 and the H10 block read the furthest one, long2x
    assert a1["checkpoint"] == "long" and "P_long" in a1["checkpoint_basis"] and a1["seed2_checkpoint"] == "long_seed2" and a1["budget"]["label"] == "samples reached: 1,584,384"
    assert a1["section4_checkpoint"] == "long2x" and "furthest" in a1["section4_checkpoint_basis"] and "section4_seed2_checkpoint" not in a1
    assert a1["section4_budget"]["label"] == "2 x P_long (3,168,768 samples)" and a1["section4_budget"]["samples_seen"] == 3168768
    assert a2["section4_budget"]["label"] == "samples reached: 3,000,000"                           # the job could not reach 2 x P_long: the samples reached are reported
    assert "long_seed2" in a1["seed_note"] and "never paired" in a1["seed_note"] and "single seed" in a1["seed_note"]      # single seed at long2x (confirmed in J1)
    assert any("A1 and A2" in n and "furthest checkpoint" in n for n in s["notes"]) and not s["decisions_needed"]
    # arms_info pins final_checkpoint 'long' for section 3 (as the run's arms_info file does): the section-4 key is separate and stays 'auto'
    p = selection.select(sc, {"A1": {"final_checkpoint": "long"}, "A2": {"final_checkpoint": "long"}}, preds_dir=pr, vlm_allow={"nobody"})
    assert p["roles"]["A1"]["checkpoint"] == "long" and p["roles"]["A1"]["section4_checkpoint"] == "long2x" and p["roles"]["A2"]["section4_checkpoint"] == "long2x"
    assert not any("long2x" in w for w in p["warnings"])                                            # the pin is right for section 3: no warning
    q = selection.select(sc, {"A1": {"section4_checkpoint": "long"}}, preds_dir=pr, vlm_allow={"nobody"})       # an explicit section4_checkpoint wins over 'auto'
    assert q["roles"]["A1"]["section4_checkpoint"] == "long" and q["roles"]["A1"]["section4_checkpoint_basis"] == "arms_info section4_checkpoint"
    assert q["roles"]["A1"]["section4_seed2_checkpoint"] == "long_seed2" and q["roles"]["A2"]["section4_checkpoint"] == "long2x"
    w = selection.select(sc, {"A1": {"final_checkpoint": "long2x"}}, preds_dir=pr, vlm_allow={"nobody"})      # a section-3 pin on long2x is warned about
    assert any("section 3" in x and "long2x" in x for x in w["warnings"])
    s_a4 = selection.select(sc, {"A4": {"final_checkpoint": "short"}}, preds_dir=pr, vlm_allow={"nobody"})            # no long2x and no long: section 4 reads the section-3 checkpoint, no invented name
    a4 = s_a4["roles"]["A4"]
    assert a4["checkpoint"] == "short" and a4["section4_checkpoint"] == "short" and "no long2x" in a4["section4_checkpoint_basis"]
    g4 = verdictgather.Gather(sc, {"roles": {"A4": a4}}, {"T1": {"evalsets": ["V1"], "P1_group": "all"}}, synthetic=True)
    assert "A4@s4" not in g4.roles and g4.s4 == {} and not any("could not be applied" in n for n in g4.notes)
    c = selection.select(sc, {}, line_checkpoint="long", preds_dir=pr, vlm_allow={"nobody"}, section4_checkpoint="long")
    assert c["roles"]["A1"]["checkpoint"] == "long" and c["roles"]["A1"]["checkpoint_basis"] == "--line-checkpoint" and c["roles"]["A1"]["section4_checkpoint"] == "long"
    assert "notes" not in c                                                                          # nothing is single-seed when both sections read 'long'
    # the verdict side: section 3 and section 4 are two roles of the same arm; long2x is never paired with long_seed2; the budgets of both are stated
    g = verdictgather.Gather(sc, s, {"T1": {"evalsets": ["V1"], "P1_group": "all"}}, synthetic=True)
    assert g.roles["A1"]["checkpoint"] == "long" and g.roles["A1"]["seed2_checkpoint"] == "long_seed2" and g.s4 == {"A1": "A1@s4", "A2": "A2@s4"}
    assert g.roles["A1@s4"]["checkpoint"] == "long2x" and "seed2_checkpoint" not in g.roles["A1@s4"]
    fb = g.final_budgets()
    assert fb["A1"]["checkpoint"] == "long" and fb["A1"]["seeds"] == 2 and fb["A1"]["budget"] == "samples reached: 1,584,384"
    assert fb["A1"]["section4_checkpoint"] == "long2x" and fb["A1"]["section4_budget"] == "2 x P_long (3,168,768 samples)" and fb["A1"]["section4_seeds"] == 1
    assert fb["A2"]["section4_budget"] == "samples reached: 3,000,000" and "single seed" in fb["A2"]["section4_note"]
    sel_bad = {"roles": {"A1": dict(s["roles"]["A1"], section4_seed2_checkpoint="long_seed2")}}      # a hand-made selection that pairs long2x with long_seed2
    gb = verdictgather.Gather(sc, sel_bad, {"T1": {"evalsets": ["V1"], "P1_group": "all"}}, synthetic=True)
    assert "seed2_checkpoint" not in gb.roles["A1@s4"] or gb.roles["A1@s4"]["seed2_checkpoint"] in ("long2x_seed2", "long2x") or any("not paired" in n for n in gb.notes)


# ---------------------------------------------------------------------------------------------------------------- the three seed-2 naming conventions
# 1. VLMA arms: <arm>/<ckpt>_seed2.  2. maker-code VLM arms run by the leader runner: the arm folder <short>_s2 with the same checkpoint names (short, leader).
# 3. line arms of LINEDET: the arm folders A1_s2 and A2_s2 (short, long).  The extra arms of E2 have one seed; their final checkpoint is 'leader'.
S2_SPEC = [("va", "short", 0.12, {}), ("va", "short_seed2", 0.13, {}), ("va", "leader", 0.08, {"samples_seen": 300000}), ("va", "leader_seed2", 0.10, {"samples_seen": 300000}),   # 1
           ("mk", "short", 0.14, {}), ("mk", "leader", 0.02, {"samples_seen": 300000}),                                                                                              # 2
           ("mk_s2", "short", 0.15, {}), ("mk_s2", "leader", 0.04, {"samples_seen": 300000}),
           ("ex", "short", 0.16, {}), ("ex", "leader", 0.06, {"samples_seen": 300000}),                                                                                              # extra arm: one seed
           ("A1", "short", 0.06, {"samples_seen": 150016}), ("A1", "long", 0.05, {"samples_seen": 1584384}),                                                                          # 3
           ("A1_s2", "short", 0.07, {"samples_seen": 150016}), ("A1_s2", "long", 0.055, {"samples_seen": 1584384}),
           ("A2", "short", 0.07, {"samples_seen": 150016}), ("A2", "long", 0.06, {"samples_seen": 1584384}), ("A2", "long2x", 0.05, {"samples_seen": 3168768}),
           ("A2_s2", "short", 0.08, {"samples_seen": 150016}), ("A2_s2", "long", 0.065, {"samples_seen": 1584384}),
           ("lit", "short", 0.3, {}), ("lit", "short_s2", 0.3, {})]
S2_INFO = {"va": {"unique_params_b": 2.0}, "mk": {"unique_params_b": 1.0}, "ex": {"unique_params_b": 0.3}, "lit": {"unique_params_b": 0.4}}


def s2_world():
    if "s2" not in W:
        W["s2"] = world("s2", S2_SPEC)
    return W["s2"]


@test
def t_seed2_convention_1_vlma_checkpoint_suffix():
    root = s2_world()
    sc, pr = os.path.join(root, "scores"), os.path.join(root, "preds")
    assert selection.find_seed2(sc, "va", "leader") == ("va", "leader_seed2") and selection.find_seed2(sc, "va", "short") == ("va", "short_seed2")
    s = selection.select(sc, copy.deepcopy(S2_INFO), preds_dir=pr, vlm_allow={"va", "ex"})
    assert s["B1"] == "ex" and s["B2"] == "va"
    r = s["roles"]["B2"]
    assert r["seeds"] == 2 and r["seed2_checkpoint"] == "leader_seed2" and "seed2_arm" not in r and r["short_seed2_checkpoint"] == "short_seed2" and "short_seed2_arm" not in r
    row = {t["arm"]: t for t in s["table"]}["va"]
    assert abs(row["v1_cer"] - sum(row["v1_cer_seeds"]) / 2) < 1e-12


@test
def t_seed2_convention_2_arm_folder_s2_of_maker_code_vlm_arms():
    root = s2_world()
    sc, pr = os.path.join(root, "scores"), os.path.join(root, "preds")
    assert selection.find_seed2(sc, "mk", "leader") == ("mk_s2", "leader") and selection.find_seed2(sc, "mk", "short") == ("mk_s2", "short")
    s = selection.select(sc, copy.deepcopy(S2_INFO), preds_dir=pr, vlm_allow={"va", "mk", "ex"})
    assert s["B1"] == "mk" and s["B2"] == "ex"                                         # the extra arm (one seed, final checkpoint 'leader') is a full candidate
    r1, r2 = s["roles"]["B1"], s["roles"]["B2"]
    assert r1["seeds"] == 2 and r1["seed2_arm"] == "mk_s2" and r1["seed2_checkpoint"] == "leader" and r1["short_seed2_arm"] == "mk_s2" and r1["short_seed2_checkpoint"] == "short"
    assert r2["seeds"] == 1 and r2["checkpoint"] == "leader" and "seed2_checkpoint" not in r2 and "single seed" in r2["single_seed_note"]
    names = {t["arm"] for t in s["table"]}
    assert "mk_s2" not in names and "A1_s2" not in names                                   # a seed-2 folder is no arm of its own: not ranked, not listed as excluded
    row = {t["arm"]: t for t in s["table"]}["mk"]
    assert row["seeds"] == 2 and abs(row["v1_cer"] - sum(row["v1_cer_seeds"]) / 2) < 1e-12 and row["v1_cer_seeds"][0] != row["v1_cer_seeds"][1]
    assert "mk_s2" not in {x["arm"] for x in s["arms_not_ranked_at_this_pick"]}
    # the leader tool does not list the seed-2 folder either, as an arm or as an arm outside the allow-list
    res = selection.leaders(sc, pr, copy.deepcopy(S2_INFO), {"va", "mk", "ex"}, B=100)
    assert "mk_s2" not in {t["arm"] for t in res["table"]} and "mk_s2" not in {o["arm"] for o in res["outside_allow_list"]} and "A1_s2" not in {o["arm"] for o in res["outside_allow_list"]}
    # the verdict side reads seed 2 from the folder named in the role
    g = verdictgather.Gather(sc, s, {"T1": {"evalsets": ["V1"], "P1_group": "all"}}, synthetic=True)
    assert g.seeds_with("B1") == [1, 2] and g.score("B1", "T1", 2)[0]["arm"] == "mk_s2" and g.score("B1", "T1", 2)[0]["checkpoint"] == "leader"
    assert g.score("B1", "T1", 1)[0]["arm"] == "mk" and g.seeds_with("B2") == [1]
    fb = g.final_budgets()
    assert fb["B1"]["seeds"] == 2 and fb["B1"]["seed2_checkpoint"] == "leader" and fb["B2"]["seeds"] == 1 and fb["B2"]["checkpoint"] == "leader"
    # the P_short pseudo-role of the same-data comparison (H13) uses the folder as well
    assert g.val_score("B1", "V1", 2)["arm"] == "mk_s2"


@test
def t_seed2_convention_3_line_arm_folders_a1_s2_and_a2_s2():
    root = s2_world()
    sc, pr = os.path.join(root, "scores"), os.path.join(root, "preds")
    s = selection.select(sc, {}, preds_dir=pr, vlm_allow={"nobody"})
    a1, a2 = s["roles"]["A1"], s["roles"]["A2"]
    assert a1["checkpoint"] == "long" and a1["seed2_arm"] == "A1_s2" and a1["seed2_checkpoint"] == "long" and a1["short_seed2_arm"] == "A1_s2" and a1["short_seed2_checkpoint"] == "short"
    assert a2["checkpoint"] == "long" and a2["seed2_arm"] == "A2_s2" and a2["seed2_checkpoint"] == "long"        # section 3 (J1): P_long with the second seed from the folder A2_s2
    assert a2["section4_checkpoint"] == "long2x" and "section4_seed2_checkpoint" not in a2 and "A2_s2/long" in a2["seed_note"] and "never paired" in a2["seed_note"]    # long2x: seed 1 only
    assert a1["section4_checkpoint"] == "long" and a1["section4_seed2_arm"] == "A1_s2" and a1["section4_seed2_checkpoint"] == "long"      # no long2x for A1 here: section 4 = section 3
    assert "A1_s2" not in s["roles"] and "A2_s2" not in s["roles"]
    g = verdictgather.Gather(sc, s, {"T1": {"evalsets": ["V1"], "P1_group": "all"}}, synthetic=True)
    assert g.seeds_with("A1") == [1, 2] and g.score("A1", "T1", 2)[0]["arm"] == "A1_s2" and g.seeds_with("A2") == [1, 2] and g.seeds_with("A2@s4") == [1]
    assert g.s4 == {"A2": "A2@s4"}                                                                          # an alias role only where the section-4 checkpoint is another one
    fb = g.final_budgets()
    assert fb["A1"]["seeds"] == 2 and fb["A2"]["seeds"] == 2 and fb["A2"]["checkpoint"] == "long" and fb["A2"]["section4_checkpoint"] == "long2x" and fb["A2"]["section4_seeds"] == 1
    # a seed-2 run that does reach long2x in the folder A2_s2 is paired with it at section 4 (same budget)
    sw.write_preds(os.path.join(root, "preds", "A2_s2", "long2x", "V1.tsv"), W["s2_v1"], 0.055, seed=777)
    sw.write_meta(os.path.join(root, "preds", "A2_s2", "long2x", "meta.json"), samples_seen=3168768)
    score(root)
    s2 = selection.select(sc, {}, preds_dir=pr, vlm_allow={"nobody"})
    assert s2["roles"]["A2"]["section4_seed2_arm"] == "A2_s2" and s2["roles"]["A2"]["section4_seed2_checkpoint"] == "long2x"
    g2 = verdictgather.Gather(sc, s2, {"T1": {"evalsets": ["V1"], "P1_group": "all"}}, synthetic=True)
    assert g2.roles["A2@s4"]["seed2_checkpoint"] == "long2x" and "not paired" not in " ".join(g2.notes) and g2.final_budgets()["A2"]["section4_seeds"] == 2
    assert not any("A2" in n and "single seed" in n for n in s2.get("notes", []))


@test
def t_seed2_checkpoint_folder_inside_the_arm_and_the_cards_fold():
    from r5eval import cards
    root = s2_world()
    sc = os.path.join(root, "scores")
    assert selection.find_seed2(sc, "lit", "short") == ("lit", "short_s2")             # a checkpoint folder <ckpt>_s2 inside the arm is accepted as well
    assert selection.seed2_folders(sc, os.path.join(root, "preds")) == {"A1_s2": "A1", "A2_s2": "A2", "mk_s2": "mk"}
    assert selection.seed2_base("x_s2", {"y"}) is None and selection.seed2_base("_s2", {""}) is None     # no base arm: an arm whose own name ends in _s2 is not folded
    by = {("mk", "short"): {"V1": "a"}, ("mk", "leader"): {"V1": "b"}, ("mk_s2", "short"): {"V1": "c"}, ("mk_s2", "leader"): {"V1": "d"}, ("mk_s2", "short_lm_gated"): {"V1": "e"},
          ("mk_s2", "curve_37504"): {"V1": "f"}, ("solo_s2", "short"): {"V1": "g"}, ("A1", "long_seed2"): {"V1": "own"}, ("A1_s2", "long"): {"V1": "folded"}}
    out, folded = cards.fold_seed2_arms(by)
    assert folded == ["A1_s2", "mk_s2"] and ("solo_s2", "short") in out and ("mk_s2", "short") not in out
    assert out[("mk", "short_seed2")]["V1"] == "c" and out[("mk", "leader_seed2")]["V1"] == "d" and out[("mk", "short_seed2_lm_gated")]["V1"] == "e"      # variant tail kept after the seed tag
    assert out[("mk", "curve_37504_seed2")]["V1"] == "f" and out[("A1", "long_seed2")]["V1"] == "own"                                           # a set present in both keeps the base arm's own
    assert cards.variant_kind("short_seed2_lm_gated")[0] == "gated character LM (H9)" and cards.variant_kind("leader_seed2")[0] == "second seed"
    # the cards CLI: no card for a seed-2 folder; it shows up as a second-seed row of its base arm, with its folder named
    cdir = os.path.join(root, "cards")
    r = subprocess.run([sys.executable, "-I", os.path.join(HERE, "..", "scripts", "r5eval", "report_cards.py"), "--scores", sc, "--preds", os.path.join(root, "preds"), "--out", cdir],
                       capture_output=True, text=True)
    assert r.returncode == 0, r.stdout[-600:] + r.stderr[-1500:]
    assert not os.path.exists(os.path.join(cdir, "mk_s2.json")) and not os.path.exists(os.path.join(cdir, "A1_s2.json")) and os.path.exists(os.path.join(cdir, "mk.json"))
    card = json.load(open(os.path.join(cdir, "mk.json")))
    assert card["seed2_arm_folder"] == "mk_s2" and {r_["checkpoint"]: r_["kind"] for r_ in card["variant_rows"]} == {"short_seed2": "second seed", "leader_seed2": "second seed"}
    idx = json.load(open(os.path.join(cdir, "status_index.json")))
    assert idx["seed2_arm_folders_folded_into_their_base_arm"] == ["A1_s2", "A2_s2", "mk_s2"] and "mk_s2" not in idx["arms"]
    # summary.tsv (written by the scorer run): seed-2 rows are marked in two trailing columns, not hidden and not mistaken for arms
    lines = open(os.path.join(sc, "summary.tsv"), encoding="utf-8").read().strip().split("\n")
    hdr = lines[0].split("\t")
    assert hdr[-3:-1] == ["seed", "seed_of_arm"] and hdr[-1] == "samples_this_call"                  # columns are only ever appended: positions of the older ones do not move
    tab = {(r_[hdr.index("arm")], r_[hdr.index("checkpoint")]): (r_[hdr.index("seed")], r_[hdr.index("seed_of_arm")]) for r_ in (l.split("\t") for l in lines[1:])}
    assert tab[("mk_s2", "leader")] == ("2", "mk") and tab[("A1_s2", "long")] == ("2", "A1") and tab[("va", "leader_seed2")] == ("2", "va") and tab[("lit", "short_s2")] == ("2", "lit")
    assert tab[("mk", "leader")] == ("1", "") and tab[("A1", "long")] == ("1", "") and tab[("va", "leader")] == ("1", "")
    lit = json.load(open(os.path.join(cdir, "lit.json")))
    assert {r_["checkpoint"]: r_["kind"] for r_ in lit["variant_rows"]} == {"short_s2": "second seed"}                 # the literal checkpoint-folder form is a second-seed row too
    a1 = json.load(open(os.path.join(cdir, "A1.json")))
    assert a1["seed2_arm_folder"] == "A1_s2" and any(r_["checkpoint"] == "long_seed2" for r_ in a1["variant_rows"])


# ---------------------------------------------------------------------------------------------------------------- samples of a continued run (leader checkpoint)
# The real row (22 Nov): minicpm_ocr_1_0 / leader: meta samples_seen 1,160,592 = the leader call only, samples_total 1,310,592 = P_lead, train_flag complete.
LEAD_META = {"samples_seen": 1160592, "samples_total": 1310592, "train_flag": "complete"}
TOT_SPEC = [("minicpm_ocr_1_0", "short", 0.07, {"samples_seen": 150000, "samples_total": 150000, "train_flag": "complete"}),
            ("minicpm_ocr_1_0", "leader", 0.03, dict(LEAD_META)), ("minicpm_ocr_1_0", "leader_seed2", 0.035, dict(LEAD_META)),
            ("hunyuanocr", "short", 0.08, {"samples_seen": 150000, "samples_total": 150000, "train_flag": "complete"}), ("hunyuanocr", "leader", 0.02, dict(LEAD_META)),
            ("capped", "short", 0.09, {"samples_seen": 150000, "samples_total": 150000, "train_flag": "complete"}),
            ("capped", "leader", 0.04, {"samples_seen": 600000, "samples_total": 1310592, "train_flag": "short of P_lead (3-hour cap)"})]
TOT_INFO = {"minicpm_ocr_1_0": {"unique_params_b": 1.3}, "hunyuanocr": {"unique_params_b": 2.0}, "capped": {"unique_params_b": 0.3}}


@test
def t_samples_of_a_complete_leader_run_are_the_total_not_the_call_and_not_short_of_p():
    from r5eval import summary
    ts = summary.total_samples
    assert ts(LEAD_META) == 1310592 and ts({"samples_seen": 150000, "samples_total": 150000, "train_flag": "complete"}) == 150000      # the exact row, and a short run
    assert ts({"samples_seen": 2309088}) == 2309088 and ts({"samples_total": 99}) == 99 and ts({}) is None and ts(None) is None      # line arms write the cumulative figure in samples_seen
    assert ts({"samples_seen": 100, "samples_total": 50}) == 100                                                                     # a total below the call is not believed
    assert ts({"samples_seen": 600000, "samples_total": 1310592, "train_flag": "short of P_lead (cap)"}) == 600000               # a capped run keeps what it reached (samples_total may be the plan)
    assert ts({"samples_seen": 1, "samples_total": True}) == 1
    root = world("tot", TOT_SPEC)
    sc, pr = os.path.join(root, "scores"), os.path.join(root, "preds")
    lines = open(os.path.join(sc, "summary.tsv"), encoding="utf-8").read().strip().split("\n")        # summary.tsv as the scorer wrote it
    hdr = lines[0].split("\t")
    row = {(r_[hdr.index("arm")], r_[hdr.index("checkpoint")]): r_ for r_ in (l.split("\t") for l in lines[1:])}
    r_lead = row[("minicpm_ocr_1_0", "leader")]
    assert r_lead[hdr.index("samples_seen")] == "1310592" and r_lead[hdr.index("samples_this_call")] == "1160592" and r_lead[hdr.index("train_flag")] == "complete"
    assert row[("minicpm_ocr_1_0", "short")][hdr.index("samples_seen")] == "150000" and row[("capped", "leader")][hdr.index("samples_seen")] == "600000"
    assert row[("minicpm_ocr_1_0", "leader_seed2")][hdr.index("samples_seen")] == "1310592"
    cols = json.load(open(os.path.join(sc, "summary_columns.json")))
    assert any(c["column"] == "samples_seen" and "samples_total" in c["meaning"] for c in cols) and cols[-1]["column"] == "samples_this_call"
    # selection: the complete leader runs are at leader length, at equal budgets (E3), and not 'short of P'
    s = selection.select(sc, copy.deepcopy(TOT_INFO), preds_dir=pr, vlm_allow={"minicpm_ocr_1_0", "hunyuanocr"})
    fb = s["final_checkpoint_budgets"]
    assert fb["equal_budget_E3"] is True and fb["arms_left_at_P_short"] == [] and not any("equal samples_seen" in w or "short of P" in w for w in s["warnings"])
    assert {x["arm"]: x["samples_seen"] for x in fb["arms_at_leader_length"]} == {"minicpm_ocr_1_0": 1310592, "hunyuanocr": 1310592}
    assert s["B1"] == "hunyuanocr" and s["roles"]["B1"]["samples_seen"] == 1310592 and s["roles"]["B1"]["at_leader_length"] is True
    assert s["roles"]["B2"]["arm"] is not None or s["B2"] is None
    # a capped leader run (flagged short of P_lead) IS reported as short: it keeps the samples it reached and the E3 check flags it
    s2 = selection.select(sc, copy.deepcopy(TOT_INFO), preds_dir=pr, vlm_allow={"minicpm_ocr_1_0", "hunyuanocr", "capped"})
    assert s2["final_checkpoint_budgets"]["equal_budget_E3"] is False and any("equal samples_seen" in w for w in s2["warnings"])
    # the leader tool reads the short checkpoints: a complete arm is eligible, whatever its leader checkpoint writes
    res = selection.leaders(sc, pr, copy.deepcopy(TOT_INFO), {"minicpm_ocr_1_0", "hunyuanocr", "capped"}, B=100)
    assert {r_["arm"] for r_ in res["table"] if r_["eligible"]} == {"minicpm_ocr_1_0", "hunyuanocr", "capped"}
    assert selection.short_of_p_reason({}, LEAD_META, ts(LEAD_META)) is None                      # a complete leader run is not short of anything
    b = selection.budget_of(sc, pr, "minicpm_ocr_1_0", "leader")
    assert b == {"samples_seen": 1310592, "label": "samples reached: 1,310,592"}


# ---------------------------------------------------------------------------------------------------------------- gap G2: reference roles in selection.json
REF_SPEC = [("R1", "ours", 0.20, {"samples_seen": 2963680, "parameters": 843582}), ("R1", "rand", 0.04, {"samples_seen": 2724896, "parameters": 842554}),
            ("R1", "mix", 0.15, {"samples_seen": 150016, "parameters": 861572}), ("R1", "ours_paperdec", 0.01, {"samples_seen": 2963680, "parameters": 843582}),
            ("R2", "ours", 0.25, {"samples_seen": 1158784, "parameters": 13878426, "parameters_ctc_branch_used_at_test_time": 2232812}),
            ("R2", "mix", 0.10, {"samples_seen": 150016, "parameters": 14026406, "parameters_ctc_branch_used_at_test_time": 2237362}),
            ("vlm_x", "short", 0.05, {})]


@test
def t_select_writes_the_six_reference_roles_and_lists_a_missing_one():
    root = world("refs", REF_SPEC)                                  # no R2/rand folder yet
    sc, pr = os.path.join(root, "scores"), os.path.join(root, "preds")
    s = selection.select(sc, {"vlm_x": {"unique_params_b": 1.0}}, preds_dir=pr, vlm_allow={"vlm_x"}, strict_final=False)
    assert s["reference_roles"] == ["R1", "R1_iii", "R1_rand", "R2", "R2_iii"] and "R2_rand" not in s["roles"]
    assert any("R2_rand" in w and "R2/rand" in w for w in s["warnings"])                             # listed, never invented
    r = s["roles"]
    assert (r["R1"]["arm"], r["R1"]["checkpoint"]) == ("R1", "ours") and (r["R1_rand"]["arm"], r["R1_rand"]["checkpoint"]) == ("R1", "rand")
    assert (r["R1_iii"]["arm"], r["R1_iii"]["checkpoint"]) == ("R1", "mix") and (r["R2"]["arm"], r["R2"]["checkpoint"]) == ("R2", "ours") and r["R2_iii"]["checkpoint"] == "mix"
    assert r["R1"]["unique_params_b"] == 843582 / 1e9 and r["R2"]["unique_params_b"] == 2232812 / 1e9 and r["R2"]["reference_variant"] == "i" and r["R1_iii"]["samples_seen"] == 150016
    assert all(not v["checkpoint"].endswith("paperdec") for k, v in r.items() if k.startswith("R"))
    assert "R1" not in {t["arm"] for t in s["table"]} and s["B1"] == "vlm_x"                         # the reference arms are still not VLM candidates
    os.makedirs(os.path.join(pr, "R2", "rand"))                                                       # the folder appears: the role follows
    s2 = selection.select(sc, {"vlm_x": {"unique_params_b": 1.0}}, preds_dir=pr, vlm_allow={"vlm_x"}, strict_final=False)
    assert s2["reference_roles"] == ["R1", "R1_iii", "R1_rand", "R2", "R2_iii", "R2_rand"] and s2["roles"]["R2_rand"] == {
        "arm": "R2", "checkpoint": "rand", "reference_variant": "ii", "unique_params_b": None, "samples_seen": None, "unique_params_basis": None}
    sel_py = os.path.join(HERE, "..", "scripts", "r5eval", "select_b1b2.py")                          # the script writes them into the file that is hashed
    out = os.path.join(root, "selection_cli.json")
    rr = subprocess.run([sys.executable, "-I", sel_py, "--scores", sc, "--preds", pr, "--out", out, "--vlm-arms", "vlm_x", "--allow-short-b1"], capture_output=True, text=True)
    assert rr.returncode == 0, rr.stderr[-1500:]
    assert set(json.load(open(out))["roles"]) >= {"R1", "R2", "R1_rand", "R2_rand", "R1_iii", "R2_iii", "B1"} and os.path.exists(out + ".sha256")


fails = [n for n, ok in RESULTS if not ok]
print("tests: %d passed, %d failed" % (len(RESULTS) - len(fails), len(fails)))
sys.exit(1 if fails else 0)