File size: 29,488 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
"""R5 test pass: self-test of the J2-J9 machinery on VALIDATION data only, with scratch registries, scratch gate files
and scratch output folders (the real gate files and the real testpass folder are never touched).

mode cpu (ZEN4 job test_testpass2.sbatch):
  A  builder: fallback (no selection), selection mode from a synthetic frozen selection.json, three not-frozen variants
     (provisional, wrong sha256, generated after 12:00), and two concurrent --final builds (one list).
  B  two runner processes on one fixed task list: an eval_vlm_test.py task (PaddleOCR-VL short, CPU), a maker-code task
     (nemotron short through vlmb_eval_vlm_testpass.py, CPU), a LINEDET task through linedet_ckpt_task.sh (A2 long2x on
     60 print_real_val lines, CPU, scratch pred/logit folders, LM decoding with the checkpoint's validation alpha/beta),
     dummy command tasks for locks, pin wait, late gate, failure and retry, missing checkpoint, the 'no start from'
     rule and the process-group stop at the stop time.
  C  eval_vlm_test.py J4: a set stopped by its deadline is written only as <set>.partial.tsv.
  D  a runner started after 'no start from' claims nothing.
  E  times on a second list: a task still running at the stop time is stopped with its process group; a process that
     becomes free after 'no start from' claims nothing more.
  F  a command task whose own gate file is missing is passed over (not failed) and later tasks run.
  G  J3: worker 1 runs only when the N file says 2.
mode gpu (step in job 52335 before 12:00, gpu_smoke_testmode.sh): B with the GPU (HunyuanOCR leader, nemotron, LINEDET
  on cuda, linedet.lm_gate), plus C, without the dummy tasks.
Prints PASS/FAIL per check and a final line; writes <out>/tptest_result.json.

usage: tptest.py cpu|gpu --out DIR
"""
import csv
import hashlib
import json
import os
import shutil
import subprocess
import sys
import time
from datetime import datetime, timezone

MODE = sys.argv[1]
OUT = sys.argv[sys.argv.index("--out") + 1]
CODE = "/path/to/TURKIC_OCR_CODE"
DATA = "/path/to/TURKIC_OCR_DATA"
S = os.path.join(CODE, "scripts", "r5_vlma")
PY = [CODE + "/.venv_vlm/bin/python", "-I"]
REALCFG = os.path.join(S, "testpass_config.json")
RES = {"mode": MODE, "started_utc": None, "checks": []}


def utc(t=None):
    return datetime.fromtimestamp(time.time() if t is None else t, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def ts(s):
    return datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc).timestamp()


def check(name, ok, detail=""):
    RES["checks"].append({"check": name, "ok": bool(ok), "detail": str(detail)[:600]})
    print("%s  %s  %s" % ("PASS" if ok else "FAIL", name, str(detail)[:300]), flush=True)


def jl(p, d=None):
    try:
        return json.load(open(p, encoding="utf-8"))
    except Exception:  # noqa: BLE001
        return d


def jd(o, p):
    json.dump(o, open(p, "w", encoding="utf-8"), indent=1, ensure_ascii=False)


RES["started_utc"] = utc()
shutil.rmtree(OUT, ignore_errors=True)
os.makedirs(OUT)
REAL = jl(REALCFG)
reg = jl(DATA + "/data/processed/r5/evalsets.json")
ents = reg["sets"] if isinstance(reg, dict) else reg
V = {e["name"]: e for e in ents if e.get("name") in ("V1", "print_real_val")}
for n in V:
    assert V[n].get("locked") is not True and str(V[n].get("split")).lower() == "val", n


def head_rows(src, dst, n, blank_split=False):
    """first n data rows of a manifest, copied line by line (optionally with the split column emptied)"""
    with open(src, encoding="utf-8") as f, open(dst, "w", encoding="utf-8") as g:
        hdr = f.readline()
        g.write(hdr)
        cols = hdr.rstrip("\n").split("\t")
        k = cols.index("split") if "split" in cols else None
        for i, ln in enumerate(f):
            if i >= n:
                break
            if blank_split and k is not None:
                parts = ln.rstrip("\n").split("\t")
                parts[k] = ""
                ln = "\t".join(parts) + "\n"
            g.write(ln)


# scratch data: VALIDATION rows only, entered as locked so that the test-pass code reads them
head_rows(V["print_real_val"]["manifest"], OUT + "/pr40.tsv", 40)
head_rows(V["print_real_val"]["manifest"], OUT + "/ld60.tsv", 60, blank_split=True)   # LINEDET's test mode keeps rows of split test or blank
jd({"about": "SELF-TEST registry: validation manifests entered as locked; not test sets",
    "sets": [{"name": "LOCKEDV1", "manifest": V["V1"]["manifest"], "split": "val", "locked": True, "unit": "word"},
             {"name": "LOCKEDPR", "manifest": OUT + "/pr40.tsv", "split": "val", "locked": True, "unit": "line"},
             {"name": "LOCKEDPR2", "manifest": OUT + "/pr40.tsv", "split": "val", "locked": True, "unit": "line"},
             {"name": "OPENV1", "manifest": V["V1"]["manifest"], "split": "val", "locked": False, "unit": "word"}]}, OUT + "/registry.json")
jd({"sets": [{"name": "LDSMOKE", "manifest": OUT + "/ld60.tsv", "split": "val", "locked": True, "unit": "line"}]}, OUT + "/ld_registry.json")
os.makedirs(OUT + "/ld_preds/A2/long2x_lm")
shutil.copy(DATA + "/outputs/r5/preds/A2/long2x_lm/meta.json", OUT + "/ld_preds/A2/long2x_lm/meta.json")  # validation alpha/beta
for g in ("gate_vlm.txt", "gate_ld.txt"):
    open(os.path.join(OUT, g), "w").write("SELF-TEST gate %s (not a test-pass gate)\n" % utc())
GPU = MODE == "gpu"
DEV = "cuda" if GPU else "cpu"


def cfg(tpd, t0, no_start_s, stop_s, not_before_s=15):
    c = json.loads(json.dumps(REAL))
    c["about"] = "SELF-TEST config (tptest.py)"
    c["times_utc"].update(not_before=utc(t0 + not_before_s), no_task_starts_from=utc(t0 + no_start_s), evaluations_stop_at=utc(t0 + stop_s))
    c["paths"].update(testpass_dir=tpd, preds_root=OUT + "/preds", evalsets=OUT + "/registry.json", gate_vlm=OUT + "/gate_vlm.txt",
                      gate_linedet=OUT + "/gate_ld.txt", gate_ref=OUT + "/gate_ref.txt", selection=OUT + "/no_selection.json")
    c["cmd_env"] = {"LD_GATE": OUT + "/gate_ld.txt", "LD_EVALSETS": OUT + "/ld_registry.json", "LD_PRED_DIR": OUT + "/ld_preds",
                    "LD_LOGIT_DIR": OUT + "/ld_logits", "LINEDET_DEVICE": DEV}
    return c


DUMMY = ["bash", S + "/tptest_dummy.sh"]
LDT = ["bash", S + "/linedet_ckpt_task.sh", "A2", "A2", DATA + "/checkpoints/r5/linedet_ext", "long2x", "LDSMOKE"]


# ------------------------------------------------------------------ A builder
def build(extra, out):
    r = subprocess.run(PY + [S + "/testpass_build_tasks.py", "--config", REALCFG, "--out", out] + extra, capture_output=True, text=True)
    return r.returncode, jl(out), r.stdout + r.stderr


def triples_unique(doc):
    seen = set()
    for t in doc["tasks"]:
        for s in t.get("sets") or []:
            k = (t.get("arm"), t.get("ckpt"), s)
            if k in seen:
                return False, k
            seen.add(k)
    return True, None


ROWORDER = ["1", "2", "3", "4", "5", "6", "7", "8"]
if MODE == "cpu":
    rc, fb, log = build(["--now-utc", "2026-11-24T12:00:00Z", "--selection", OUT + "/no_selection.json"], OUT + "/b_fallback.json")
    check("A1 builder fallback mode", rc == 0 and fb and fb["mode"] == "fallback", log[-300:])
    if fb:
        first = [(t["arm"], t["ckpt"]) for t in fb["tasks"][:6]]
        check("A1 fallback rows 1/2/6 = four leader finals in J2 order", first == [("hunyuanocr", "leader"), ("hunyuanocr", "leader_seed2"),
              ("minicpm_ocr_1_0", "leader"), ("minicpm_ocr_1_0", "leader_seed2"), ("paddleocr_vl_1_6", "leader"), ("qwen3_vl_2b", "leader")], first)
        check("A1 row-1 sets", fb["tasks"][0]["sets"] == ["kohtd_test", "kohtd_test_p2", "kohtd_test_p2b", "print_real_test", "synth_clutter_test"], fb["tasks"][0]["sets"])
        rows = [t["row"] for t in fb["tasks"]]
        check("A1 rows in J2 order", rows == sorted(rows, key=ROWORDER.index), json.dumps(fb["rows_count"]))
        allsets = {s for t in fb["tasks"] for s in (t.get("sets") or [])}
        check("A1 excluded sets never scheduled", not (allsets & {"more_real_print", "synth_pages_test", "kohtd_rand_test"}), sorted(allsets))
        u, k = triples_unique(fb)
        check("A1 each (arm, checkpoint, set) once", u, k)
        r3 = [(t["arm"], t["ckpt"]) for t in fb["tasks"] if t["row"] == "3" and t["kind"] == "cmd" and t.get("owner") == "LINEDET" and t.get("ckpt")]
        check("A1 row 3 line order (A1/A2 long2x first)", r3[:2] == [("A1", "long2x"), ("A2", "long2x")] and len(r3) == 9, r3)
        ref = [t for t in fb["tasks"] if t["id"].startswith("r5:ref")]
        check("A1 REF task pinned to slot L with REF_DEVICE=gpu", len(ref) == 1 and ref[0]["slot"] == "L" and ref[0]["env"] == {"REF_DEVICE": "gpu"}, ref)
        h14 = [t["arm"] for t in fb["tasks"] if t["row"] == "7"]
        check("A1 row 7 H14 order, granite/youtu/unlimited last", h14[-3:] == ["granite_docling_258m", "youtu_parsing", "unlimited_ocr_2"] and h14[0] == "glm_ocr", h14)
        mk = [t for t in fb["tasks"] if t["kind"] == "vlmb" and t["row"] == "7"]
        check("A1 maker-code P_short on kohtd_test only (p2/p2b later)", all(t["sets"] == ["kohtd_test"] for t in mk), [t["sets"] for t in mk][:2])
        print("fallback list: %d tasks, rows %s" % (len(fb["tasks"]), fb["rows_count"]), flush=True)
    sel = {"schema": "r5eval-selection-2", "generated_utc": "2026-11-24T10:30:00Z", "provisional": False, "B1": "minicpm_ocr_1_0",
           "B2": "paddleocr_vl_1_6", "roles": {
               "B1": {"arm": "minicpm_ocr_1_0", "checkpoint": "leader", "seed2_checkpoint": "leader_seed2", "short_checkpoint": "short",
                      "short_seed2_checkpoint": "short_seed2", "seeds": 2, "at_leader_length": True},
               "B2": {"arm": "paddleocr_vl_1_6", "checkpoint": "leader", "short_checkpoint": "short", "seeds": 1, "at_leader_length": True},
               "R1": {"arm": "R1", "checkpoint": "ours"}, "R2": {"arm": "R2", "checkpoint": "ours"}, "R1_rand": {"arm": "R1", "checkpoint": "rand"},
               "R2_rand": {"arm": "R2", "checkpoint": "rand"}, "R1_iii": {"arm": "R1", "checkpoint": "mix"}, "R2_iii": {"arm": "R2", "checkpoint": "mix"}},
           "note": "SYNTHETIC selection for the self-test; not a real selection"}

    def write_sel(p, s, good_sha=True):
        jd(s, p)
        h = hashlib.sha256(open(p, "rb").read()).hexdigest() if good_sha else "0" * 64
        open(p + ".sha256", "w").write("%s  %s  %s\n" % (h, os.path.basename(p), s["generated_utc"]))
    write_sel(OUT + "/sel_ok.json", sel)
    rc, sd, log = build(["--now-utc", "2026-11-24T12:00:00Z", "--selection", OUT + "/sel_ok.json"], OUT + "/b_selection.json")
    check("A2 builder selection mode", rc == 0 and sd and sd["mode"] == "selection" and sd["B1"] == "minicpm_ocr_1_0", log[-300:])
    if sd:
        head = [(t["row"], t["arm"], t["ckpt"]) for t in sd["tasks"] if t["row"] in ("1", "2")]
        check("A2 rows 1-2 = B1 finals (two seeds), B2 final", head == [("1", "minicpm_ocr_1_0", "leader"), ("1", "minicpm_ocr_1_0", "leader_seed2"),
                                                                       ("2", "paddleocr_vl_1_6", "leader")], head)
        r4 = [(t["arm"], t["ckpt"]) for t in sd["tasks"] if t["row"] == "4" and t["kind"] != "cmd"]
        check("A2 row 4 = B1 short + short_seed2, B2 short", r4 == [("minicpm_ocr_1_0", "short"), ("minicpm_ocr_1_0", "short_seed2"), ("paddleocr_vl_1_6", "short")], r4)
        r6 = [(t["arm"], t["ckpt"]) for t in sd["tasks"] if t["row"] == "6"]
        check("A2 row 6 = other leaders: finals then P_short", r6 == [("hunyuanocr", "leader"), ("hunyuanocr", "leader_seed2"), ("qwen3_vl_2b", "leader"),
                                                                     ("hunyuanocr", "short"), ("hunyuanocr", "short_seed2"), ("qwen3_vl_2b", "short")], r6)
        u, k = triples_unique(sd)
        check("A2 each (arm, checkpoint, set) once", u, k)
        rows = [t["row"] for t in sd["tasks"]]
        check("A2 rows in J2 order", rows == sorted(rows, key=ROWORDER.index), json.dumps(sd["rows_count"]))
    for tag, s2, good in (("provisional", dict(sel, provisional=True), True), ("wrong sha256", sel, False),
                          ("generated after 12:00", dict(sel, generated_utc="2026-11-24T12:00:30Z"), True)):
        p = OUT + "/sel_%s.json" % tag.replace(" ", "_").replace(":", "")
        write_sel(p, s2, good)
        rc, d3, log = build(["--now-utc", "2026-11-24T12:01:00Z", "--selection", p], p + ".tasks.json")
        check("A3 not frozen (%s) -> fallback" % tag, rc == 0 and d3 and d3["mode"] == "fallback", (d3 or {}).get("selection", {}).get("checks"))
    c6 = cfg(OUT + "/tpd_build", time.time(), 600, 700)
    jd(c6, OUT + "/cfg_build.json")
    ps = [subprocess.Popen(PY + [S + "/testpass_build_tasks.py", "--config", OUT + "/cfg_build.json", "--final"], stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT, text=True) for _ in range(3)]
    outs = [p.communicate()[0] for p in ps]
    built = sum(1 for o in outs if o.startswith("built "))
    check("A4 three concurrent --final builds: one list written, all exit 0", built == 1 and all(p.returncode == 0 for p in ps), [o[:90] for o in outs])
    rc, d5, log = build(["--now-utc", "2026-11-24T12:00:00Z", "--selection", OUT + "/sel_ok.json", "--force-fallback"], OUT + "/b_forced.json")
    check("A5 --force-fallback with a frozen selection -> fallback", rc == 0 and d5 and d5["mode"] == "fallback", log[-200:])
    open(OUT + "/sel_corrupt.json", "w").write('{"B1": "minicpm_ocr_1_0", "roles": {')
    open(OUT + "/sel_corrupt.json.sha256", "w").write("0  sel_corrupt.json  x\n")
    rc, d6, log = build(["--now-utc", "2026-11-24T12:00:00Z", "--selection", OUT + "/sel_corrupt.json"], OUT + "/b_corrupt.json")
    check("A6 unreadable selection.json -> fallback, no crash", rc == 0 and d6 and d6["mode"] == "fallback" and "error" in d6["selection"], log[-200:])
    bad = json.loads(json.dumps(sel))
    del bad["roles"]["B1"]["arm"]
    write_sel(OUT + "/sel_badrole.json", bad)
    rc, d7, log = build(["--now-utc", "2026-11-24T12:00:00Z", "--selection", OUT + "/sel_badrole.json"], OUT + "/b_badrole.json")
    check("A7 frozen selection with a malformed role -> fallback, exception recorded", rc == 0 and d7 and d7["mode"] == "fallback"
          and any("building from selection.json failed" in n for n in d7["notes"]), log[-200:])
    lt = [t for t in (sd or {}).get("tasks", []) if t.get("owner") == "LINEDET"]
    check("A8 LINEDET locks per label; one final lm_gate, exclusive", all(t["lock"] == ("linedet_ALL" if "lm_gate" in t["id"] else "linedet_" + t["arm"]) for t in lt)
          and [t["id"] for t in lt if "lm_gate" in t["id"]] == ["r8:linedet_lm_gate"], [(t["id"], t["lock"]) for t in lt][:3])

# ------------------------------------------------------------------ B runners on one fixed task list
T0 = time.time()
NOSTART, STOP = 1500, 1560        # phase 1 ends when its list is exhausted; phase 2 tests the times
c = cfg(OUT + "/tpd", T0, NOSTART, STOP)
jd(c, OUT + "/cfg_run.json")
tasks = []
if GPU:
    tasks.append({"id": "g_vlma", "row": "1", "kind": "vlma", "short": "hunyuanocr", "arm": "tp_hunyuan", "ckpt": "leader",
                  "model_dir": DATA + "/checkpoints/r5/hunyuanocr/leader", "exists_path": DATA + "/checkpoints/r5/hunyuanocr/leader",
                  "sets": ["LOCKEDV1", "LOCKEDPR"], "limit": 64, "batch": 16, "device": "cuda"})
else:
    tasks.append({"id": "t_vlma", "row": "1", "kind": "vlma", "short": "paddleocr_vl_1_6", "arm": "tp_paddle", "ckpt": "short",
                  "model_dir": DATA + "/checkpoints/r5/paddleocr_vl_1_6/short", "exists_path": DATA + "/checkpoints/r5/paddleocr_vl_1_6/short",
                  "sets": ["LOCKEDV1", "LOCKEDPR"], "limit": 6, "batch": 3, "device": "cpu"})
    tasks += [{"id": "t_lock_a", "row": "2", "kind": "cmd", "argv": DUMMY + ["sleep", "20", "lock_a", "0"], "lock": "L1"},
              {"id": "t_lock_b", "row": "2", "kind": "cmd", "argv": DUMMY + ["sleep", "5", "lock_b", "0"], "lock": "L1"},
              {"id": "t_pin", "row": "3", "kind": "cmd", "argv": DUMMY + ["sleep", "3", "pin", "0"], "slot": "L", "pin_wait_max_seconds": 60},
              {"id": "t_gate_late", "row": "3", "kind": "cmd", "argv": DUMMY + ["sleep", "3", "gate", "0"], "gate": OUT + "/gate_ref.txt"},
              {"id": "t_fail", "row": "4", "kind": "cmd", "argv": DUMMY + ["sleep", "1", "fail", "1"]},
              {"id": "t_nockpt", "row": "4", "kind": "vlma", "short": "glm_ocr", "arm": "tp_none", "ckpt": "short", "model_dir": OUT + "/no_model",
               "exists_path": OUT + "/no_model", "sets": ["LOCKEDV1"]}]
tasks.append({"id": "t_line", "row": "5", "kind": "cmd", "owner": "LINEDET", "arm": "A2", "ckpt": "long2x", "sets": ["LDSMOKE"], "argv": LDT,
              "gate": OUT + "/gate_ld.txt", "lock": "linedet_A2", "blocked_by": ["linedet_ALL"], "exists_path": DATA + "/checkpoints/r5/linedet_ext/A2/long2x.pt"})
if not GPU:
    tasks += [{"id": "t_excl", "row": "5", "kind": "cmd", "argv": DUMMY + ["sleep", "3", "excl", "0"], "lock": "linedet_ALL", "exclusive_prefix": "linedet_"},
              {"id": "t_line_missing", "row": "5", "kind": "cmd", "owner": "LINEDET", "arm": "A2", "ckpt": "long2x", "sets": ["LDSMOKE", "NOSUCHSET"],
               "argv": LDT[:-1] + ["LDSMOKE,NOSUCHSET"], "gate": OUT + "/gate_ld.txt", "lock": "linedet_A2", "blocked_by": ["linedet_ALL"]}]
tasks.append({"id": "t_vlmb", "row": "6", "kind": "vlmb", "short": "nemotron_3_5_parse", "arm": "tp_nemotron", "ckpt": "short",
              "state": DATA + "/checkpoints/r5/nemotron_3_5_parse/short/model_bf16.pt", "exists_path": DATA + "/checkpoints/r5/nemotron_3_5_parse/short/model_bf16.pt",
              "sets": ["LOCKEDV1"], "limit": 32 if GPU else 4, "batch": 16 if GPU else 2, "device": DEV})
if GPU:
    tasks.append({"id": "g_lm_gate", "row": "7", "kind": "cmd", "owner": "LINEDET",
                  "argv": [CODE + "/.venv_kraken/bin/python", "-I", "-m", "linedet.lm_gate", "--pred_dir", OUT + "/ld_preds", "--labels", "A2"],
                  "gate": OUT + "/gate_ld.txt", "lock": "linedet_ALL", "exclusive_prefix": "linedet_"})
jd({"schema": "r5-testpass-tasks-1", "mode": "self-test", "tasks": tasks}, OUT + "/tasks_fixed.json")
GATE_REF_AT = {"t": None}


def run_phase(tag, cfgp, tlist, tpd, t0, limit_s, hooks):
    rs = [subprocess.Popen(PY + [S + "/testpass_runner.py", "--config", cfgp, "--slot", "V", "--worker", str(w), "--tasks", tlist],
                           stdout=open(OUT + "/runner_%s_w%d.log" % (tag, w), "w"), stderr=subprocess.STDOUT) for w in (0, 1)]
    while any(p.poll() is None for p in rs):
        if hooks:
            fake_alive = tpd + "/alive/L_w0_fake"
            os.makedirs(os.path.dirname(fake_alive), exist_ok=True)
            pin = jl(tpd + "/status/t_pin.json", {}) or {}
            if pin.get("status") != "done":
                open(fake_alive, "w").write(utc())   # a live slot-L runner (fake) until the pinned task has run: V must wait first
            elif os.path.exists(fake_alive):
                os.remove(fake_alive)
            if GATE_REF_AT["t"] is None and time.time() > t0 + 90:
                open(OUT + "/gate_ref.txt", "w").write("SELF-TEST late gate %s\n" % utc())
                GATE_REF_AT["t"] = time.time()
        if time.time() > t0 + limit_s:
            for p in rs:
                p.kill()
            check("%s runners ended in time" % tag, False, "killed by the test after %d s" % limit_s)
            break
        time.sleep(5)


run_phase("B", OUT + "/cfg_run.json", OUT + "/tasks_fixed.json", OUT + "/tpd", T0, 1500, not GPU)
gate_ref_at = GATE_REF_AT["t"]


def st(i, tpd="tpd"):
    return jl(OUT + "/%s/status/%s.json" % (tpd, i), {}) or {}


for t in tasks:
    s = st(t["id"])
    print("status %-12s %-22s failures %s history %d %s" % (t["id"], s.get("status"), s.get("failures"), len(s.get("history") or []),
                                                          json.dumps(s.get("complete_sets"))[:160]), flush=True)
vid = "g_vlma" if GPU else "t_vlma"
arm = "tp_hunyuan/leader" if GPU else "tp_paddle/short"
check("B eval_vlm_test task done", st(vid).get("status") == "done" and len(st(vid).get("history") or []) == 1, st(vid).get("status"))
check("B eval_vlm_test outputs (greedy + retry TSV)", all(os.path.exists(OUT + "/preds/%s%s/%s.tsv" % (arm, sfx, s)) for s in ("LOCKEDV1", "LOCKEDPR") for sfx in ("", "_retry")),
      sorted(os.listdir(OUT + "/preds/" + arm)) if os.path.isdir(OUT + "/preds/" + arm) else "none")
check("B maker-code task done", st("t_vlmb").get("status") == "done", st("t_vlmb"))
lp = OUT + "/ld_preds/A2"
check("B LINEDET task done (greedy, _lm, _lm_gated written)", st("t_line").get("status") == "done" and all(os.path.exists("%s/%s/LDSMOKE.tsv" % (lp, d)) for d in ("long2x", "long2x_lm", "long2x_lm_gated")),
      [st("t_line").get("status"), sorted(os.listdir(lp)) if os.path.isdir(lp) else None])
check("B LINEDET per-call meta copies kept", os.path.isdir(OUT + "/tpd/linedet_meta") and len(os.listdir(OUT + "/tpd/linedet_meta")) >= 2,
      os.listdir(OUT + "/tpd/linedet_meta") if os.path.isdir(OUT + "/tpd/linedet_meta") else None)
if GPU:
    check("B linedet.lm_gate task done", st("g_lm_gate").get("status") == "done", st("g_lm_gate"))
else:
    a, b = st("t_lock_a"), st("t_lock_b")
    ea, eb = (ts(x["history"][-1]["ended_utc"]) if x.get("history") else 0 for x in (a, b))
    sa, sb = (ts(x["started_utc"]) if x.get("started_utc") else 0 for x in (a, b))
    check("B lock: the two tasks of one lock did not overlap", a.get("status") == b.get("status") == "done" and (sb >= ea - 1 or sa >= eb - 1),
          [a.get("started_utc"), ea, b.get("started_utc"), eb])
    p = st("t_pin")
    check("B pin: waited for the live slot L, then ran here (recorded)", p.get("status") == "done" and p.get("pin_wait_seconds", 0) >= 55 and p.get("ran_on_slot") == "V",
          {k: p.get(k) for k in ("status", "pin_wait_seconds", "ran_on_slot")})
    g = st("t_gate_late")
    check("B own gate: started only after its gate file existed", g.get("status") == "done" and gate_ref_at and ts(g["started_utc"]) >= gate_ref_at - 1,
          [g.get("started_utc"), utc(gate_ref_at) if gate_ref_at else None])
    f = st("t_fail")
    check("B failure: retried once, then failed_final", f.get("status") == "failed_final" and len(f.get("history") or []) == 2, [f.get("status"), len(f.get("history") or [])])
    check("B missing checkpoint: not_run_no_checkpoint", st("t_nockpt").get("status") == "not_run_no_checkpoint", st("t_nockpt").get("status"))
    lm = st("t_line_missing")
    check("B LINEDET wrapper: a requested set without TSV -> exit 4, retried, failed_final", lm.get("status") == "failed_final"
          and [h.get("rc") for h in lm.get("history") or []] == [4, 4], [lm.get("status"), [h.get("rc") for h in lm.get("history") or []]])

    def spans(x):  # every attempt: (start, end) from its history entry
        return [(ts(h["ended_utc"]) - h["seconds"], ts(h["ended_utc"])) for h in x.get("history") or []]
    ex = spans(st("t_excl"))
    lines = spans(st("t_line")) + spans(lm)
    check("B exclusive lm_gate lock: never ran beside a LINEDET call", st("t_excl").get("status") == "done" and len(ex) == 1 and len(lines) == 3
          and all(ex[0][0] >= e - 1.5 or s >= ex[0][1] - 1.5 for s, e in lines), [ex, lines])
    dups = [t["id"] for t in tasks if st(t["id"]).get("status") == "done" and len(st(t["id"]).get("history") or []) != 1]
    check("B no task ran twice", dups == [], dups)
summ = [f for f in os.listdir(OUT + "/tpd") if f.startswith("summary_")]
check("B both runners wrote a summary", len(summ) == 2, summ)

# ------------------------------------------------------------------ E times (J4): no start from 'no_task_starts_from', stop by process group
if not GPU:
    T1 = time.time()
    c3 = cfg(OUT + "/tpd_times", T1, 60, 100, not_before_s=5)
    jd(c3, OUT + "/cfg_times.json")
    t3 = [{"id": "t_long", "row": "7", "kind": "cmd", "argv": DUMMY + ["tree", "901"]},
          {"id": "t_mid", "row": "7", "kind": "cmd", "argv": DUMMY + ["until", str(int(T1 + 75))]},
          {"id": "t_never", "row": "8", "kind": "cmd", "argv": DUMMY + ["sleep", "2", "never", "0"]}]
    jd({"schema": "r5-testpass-tasks-1", "mode": "self-test", "tasks": t3}, OUT + "/tasks_times.json")
    run_phase("E", OUT + "/cfg_times.json", OUT + "/tasks_times.json", OUT + "/tpd_times", T1, 400, False)
    lg = st("t_long", "tpd_times")
    check("E stop time: long task stopped (process group), status stopped_by_deadline", lg.get("status") == "stopped_by_deadline"
          and ts(lg["history"][-1]["ended_utc"]) <= T1 + 100 + 40, [lg.get("status"), (lg.get("history") or [{}])[-1].get("ended_utc"), utc(T1 + 100)])
    left = subprocess.run(["pgrep", "-f", "sleep 901"], capture_output=True, text=True).stdout.strip()
    check("E stop time: no child left in its process group", left == "", left)
    check("E no task starts from 'no_task_starts_from' (t_mid ended after it; t_never never started)",
          st("t_never", "tpd_times") == {} and st("t_mid", "tpd_times").get("status") == "done", [st("t_never", "tpd_times"), st("t_mid", "tpd_times").get("status")])
    # F own gate missing: the task is passed over (not failed), later tasks run, the runner waits for the gate until 'no start from'
    T2 = time.time()
    jd(cfg(OUT + "/tpd_gate", T2, 45, 60, not_before_s=0), OUT + "/cfg_gate.json")
    jd({"schema": "r5-testpass-tasks-1", "mode": "self-test", "tasks": [
        {"id": "t_gated", "row": "5", "kind": "cmd", "argv": DUMMY + ["sleep", "1", "gated", "0"], "gate": OUT + "/gate_never.txt"},
        {"id": "t_after", "row": "6", "kind": "cmd", "argv": DUMMY + ["sleep", "1", "after", "0"]}]}, OUT + "/tasks_gate.json")
    r = subprocess.run(PY + [S + "/testpass_runner.py", "--config", OUT + "/cfg_gate.json", "--slot", "V", "--worker", "0", "--tasks",
                             OUT + "/tasks_gate.json"], capture_output=True, text=True, timeout=300)
    check("F own gate missing: passed over (not failed), later task ran, nothing claimed after 'no start from'",
          st("t_gated", "tpd_gate") == {} and st("t_after", "tpd_gate").get("status") == "done" and "does not exist yet" in r.stdout,
          [st("t_gated", "tpd_gate"), st("t_after", "tpd_gate").get("status"), r.stdout[-160:]])
    # G J3 N file: worker 1 runs only when the N file (read when the pass opens) starts with 2
    for nval, expect in (("1\n{}\n", False), ("2\n{}\n", True)):
        tag = "g%s" % nval[0]
        T3 = time.time()
        jd(cfg(OUT + "/tpd_" + tag, T3, 120, 150, not_before_s=0), OUT + "/cfg_%s.json" % tag)
        jd({"schema": "r5-testpass-tasks-1", "mode": "self-test", "tasks": [{"id": "t_n", "row": "1", "kind": "cmd", "argv": DUMMY + ["sleep", "1", "n", "0"]}]},
           OUT + "/tasks_%s.json" % tag)
        open(OUT + "/nfile_%s.txt" % tag, "w").write(nval)
        r = subprocess.run(PY + [S + "/testpass_runner.py", "--config", OUT + "/cfg_%s.json" % tag, "--slot", "V", "--worker", "1", "--nfile",
                                 OUT + "/nfile_%s.txt" % tag, "--tasks", OUT + "/tasks_%s.json" % tag], capture_output=True, text=True, timeout=200)
        ran = st("t_n", "tpd_" + tag).get("status") == "done"
        check("G N file says %s: worker 1 %s" % (nval[0], "runs" if expect else "exits"), r.returncode == 0 and ran == expect, r.stdout[-160:])

# ------------------------------------------------------------------ C eval_vlm_test.py J4 partial set
mdl = (["--short", "hunyuanocr", "--model-dir", DATA + "/checkpoints/r5/hunyuanocr/leader"] if GPU else
       ["--short", "paddleocr_vl_1_6", "--model-dir", DATA + "/checkpoints/r5/paddleocr_vl_1_6/short"])
r = subprocess.run(PY + [S + "/eval_vlm_test.py"] + mdl + ["--arm", "tp_partial", "--ckpt", "c", "--registry", S + "/models_r5.tsv",
                   "--evalsets", OUT + "/registry.json", "--preds-root", OUT + "/preds", "--sets", "LOCKEDPR2", "--test-pass", "--gate-file",
                   OUT + "/gate_vlm.txt", "--deadline-utc", utc(time.time() - 60), "--device", DEV, "--batch", "4"], capture_output=True, text=True)
pdir = OUT + "/preds/tp_partial/c"
m = jl(pdir + "/meta.json", {}) or {}
check("C J4: set stopped by the deadline -> only <set>.partial.tsv", os.path.exists(pdir + "/LOCKEDPR2.partial.tsv") and not os.path.exists(pdir + "/LOCKEDPR2.tsv")
      and (m.get("test_pass", {}).get("sets", {}).get("LOCKEDPR2", {}).get("complete") is False), [r.returncode, os.listdir(pdir) if os.path.isdir(pdir) else None])

# ------------------------------------------------------------------ D runner after 'no start from'
if not GPU:
    c2 = cfg(OUT + "/tpd_late", time.time() - 600, -60, 60, not_before_s=0)
    jd(c2, OUT + "/cfg_late.json")
    r = subprocess.run(PY + [S + "/testpass_runner.py", "--config", OUT + "/cfg_late.json", "--slot", "V", "--worker", "0", "--tasks", OUT + "/tasks_fixed.json"],
                       capture_output=True, text=True, timeout=120)
    sd = OUT + "/tpd_late/status"
    check("D runner after 16:40-equivalent claims nothing", r.returncode == 0 and (not os.path.isdir(sd) or os.listdir(sd) == []), r.stdout[-200:])

RES["ended_utc"] = utc()
RES["all_pass"] = all(x["ok"] for x in RES["checks"])
jd(RES, OUT + "/tptest_result.json")
print("RESULT %s: %d checks, %d failed" % ("ALL PASS" if RES["all_pass"] else "FAILURES", len(RES["checks"]), sum(1 for x in RES["checks"] if not x["ok"])), flush=True)