File size: 59,788 Bytes
8ca7ffa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
"""Benchmark round N: score the v2 chain (calib_refined_v2.json + calib/mount_params.json + per-episode
URDFs + cy+1 renderer) on the fixed SAM3 benchmark (out/diag/gtmask: 36 episodes x 3 cams x 10 frames,
out/diag/sample.json) against the OLD pipeline numbers in out/diag/residual/metrics.csv.

Per frame (1280x720 unless the MP4 differs): IoU, r2g (rendered-silhouette-edge -> nearest GT-edge mean
distance, px), g2r, sym, centroid offset, area ratio, gripper-ROI / arm metrics, GT far fraction; the old
pipeline render (out/diag/gtmask/.../<step>_rend.png) is re-scored with the same code (iou_old / r2g_old)
and merged with the csv (iou_old_csv / r2g_old_csv) as a cross-check.  Attribution probes on the new
render: a +-20/40 ms time probe (exterior; wrist is time-invariant) and the best integer image shift of
the render (FFT, half resolution) -> how much a pure time change / a pure rigid shift would recover.

Held-out logic: every frame carries in_fit (step is in the v2 fit step list of that camera, from
calib_refined_v2.json quality[serial].extra.steps), in_fit_pm1 (+-1 step), in_gt (step is in out/gt/<uuid>/steps.json,
the SAM3-at-scale step pool that refine_v2 / session_prior / fit_mount_global draw from) and in_gt_pm1; a frame is
held out iff not in_fit and not in_gt.  refine_v2 / gt_masks_scale exclude the benchmark frames +-1 by construction,
so all four are expected to be False; if any is True the summary reports both with and without those frames.
Diagnostic metric r2g_near = r2g restricted to render-edge pixels within 60 px of any GT pixel (drops rendered parts
the GT omits, e.g. the robot base occluded by a table); the target metric stays the plain r2g.
--exclude-frames <json list of {uuid, serial, step, reason}> marks benchmark frames judged GT failures (robot out of view, hallucinated
SAM3 mask); they stay in every target row and are only dropped in one extra DIAG row (column excluded_gt_failure in metrics.csv).
--prev-csv <metrics.csv of an earlier run> adds prev_iou / prev_r2g per frame + paired deltas (e.g. to measure the
effect of re-fitting with new session deltas); --prev-v2-dir <dir of <uuid>.json> reports the per-camera pose and
time-offset change between the superseded and the current calib_refined_v2.json.  The global mount
parameters (calib/mount_params.json) WERE fitted on these benchmark frames (out/mount_fit_final); that is
reported, not corrected.

Outputs (--out, default out/bench/round1; round 2 used out/bench/round2): metrics.csv (per frame), per_episode.csv, summary.json,
summary.md (+ the --notes markdown appended), worst12_ext.jpg, worst12_wrist.jpg (GT contour green, new render contour red, old render
contour blue), before_after_grid.jpg (8 diverse episodes: ext + wrist, old vs new), masks/<uuid>/<serial>/
<step>.png (new render masks).

Usage (run on a compute node; ~1080 frames x (1 + 4 time probes) renders):
  sbatch -p c6-128-main -c 8 --mem=16G --time=01:00:00 -o out/slurm/bench_r1_%j.log \
      --wrap "python scripts/benchmark_align.py --workers 8"
  python scripts/benchmark_align.py --episodes <uuid> --max-frames 2 --workers 1 --no-images   # smoke test
"""
import argparse
import csv
import json
import os
import sys
import time
from pathlib import Path

import cv2
import numpy as np

HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
if str(HERE) not in sys.path:
    sys.path.insert(0, str(HERE))

cv2.setNumThreads(1)

SAMPLE = ROOT / "out/diag/sample.json"
BENCH_ROOT = ROOT / "out/diag/gtmask"
OLD_CSV = ROOT / "out/diag/residual/metrics.csv"
USABLE = ("ok", "single", "low_conf")                                   # metrics.csv 'usable' definition
USABLE_EXT = USABLE + ("render_far_off", "render_missing_robot")
MIN_GT_PX = 3000
TIME_PROBES_MS = (-40.0, -20.0, 20.0, 40.0)
SHIFT_MAX_HALF = 75                                                    # +-150 px at full res
K3 = np.ones((3, 3), np.uint8)
TARGETS = {  # p10/p50/p90 at 1280x720 (DIAGNOSIS sec 5 / task FACTS)
    "ext": dict(iou=(0.65, 0.85, 0.93), r2g=(2.6, 4.6, 15.0)),
    "wrist": dict(iou=(0.74, 0.88, 0.93), r2g=(5.3, 11.4, 35.0)),
}
NOISE_FLOOR = {"ext": dict(iou_p50=0.871, r2g_p50=3.8), "wrist": dict(iou_p50=0.894, r2g_p50=9.4)}
GRID_LABS = ["AUTOLab", "RAIL", "REAL", "TRI", "CLVR", "IPRL", "GuptaLab", "ILIAD"]


def log(msg):
    print(f"[bench {time.strftime('%H:%M:%S')}] {msg}", flush=True)


def _f(v, nd=4):
    try:
        v = float(v)
    except (TypeError, ValueError):
        return None
    return None if not np.isfinite(v) else round(v, nd)


def pct(a, q=(10, 50, 90)):
    a = np.asarray([x for x in a if x is not None and np.isfinite(x)], dtype=float)
    if a.size == 0:
        return [None] * len(q), 0
    return [float(np.percentile(a, p)) for p in q], int(a.size)


# ----------------------------------------------------------------------------- metrics (== scripts/diag/residual_analysis.py)

def edge(m):
    return cv2.morphologyEx(m.astype(np.uint8), cv2.MORPH_GRADIENT, K3) > 0


def dt_to(e):
    return cv2.distanceTransform((~e).astype(np.uint8), cv2.DIST_L2, 5)


def centroid(m):
    ys, xs = np.nonzero(m)
    return (float(xs.mean()), float(ys.mean())) if len(xs) else (float("nan"), float("nan"))


def iou_of(a, b):
    u = int((a | b).sum())
    return float((a & b).sum() / u) if u > 0 else float("nan")


def mask_metrics(rend, gt, grip=None, arm=None, gt_cache=None, prefix=""):
    nan = float("nan")
    o = dict(area_rend=int(rend.sum()), area_gt=int(gt.sum()), iou=iou_of(rend, gt))
    o["area_ratio"] = o["area_rend"] / o["area_gt"] if o["area_gt"] > 0 else nan
    for k in ("r2g", "r2g_p90", "r2g_near", "r2g_near_frac", "g2r", "sym", "dx", "dy", "gt_far_frac", "grip_px", "grip_iou_roi",
              "grip_prec", "grip_r2g", "arm_px", "arm_prec", "arm_r2g"):
        o[k] = nan
    if o["area_rend"] == 0 or o["area_gt"] == 0:
        return {prefix + k: v for k, v in o.items()}
    e_r = edge(rend)
    if gt_cache is None:
        e_g = edge(gt)
        dt_g = dt_to(e_g)
        dt_gm = dt_to(gt)
    else:
        e_g, dt_g, dt_gm = gt_cache
    dt_r = dt_to(e_r)
    d_rg, d_gr = dt_g[e_r], dt_r[e_g]
    o["r2g"], o["r2g_p90"] = float(d_rg.mean()), float(np.percentile(d_rg, 90))
    near = dt_gm[e_r] <= 60.0          # render-edge px within 60 px of ANY GT px (occlusion-robust variant)
    o["r2g_near_frac"] = float(near.mean())
    if near.any():
        o["r2g_near"] = float(d_rg[near].mean())
    o["g2r"] = float(d_gr.mean())
    o["sym"] = 0.5 * (o["r2g"] + o["g2r"])
    cr, cg = centroid(rend), centroid(gt)
    o["dx"], o["dy"] = cr[0] - cg[0], cr[1] - cg[1]
    dt_rend = dt_to(rend)
    o["gt_far_frac"] = float((dt_rend[gt] > 60).mean())
    if grip is not None and grip.sum() >= 200:
        roi = cv2.dilate(grip.astype(np.uint8), np.ones((41, 41), np.uint8)) > 0
        o["grip_px"] = int(grip.sum())
        o["grip_iou_roi"] = iou_of(rend & roi, gt & roi)
        o["grip_prec"] = float((grip & gt).sum() / grip.sum())
        eg_r = e_r & (cv2.dilate(grip.astype(np.uint8), np.ones((5, 5), np.uint8)) > 0)
        if eg_r.sum() > 20:
            o["grip_r2g"] = float(dt_g[eg_r].mean())
        if arm is not None and arm.sum() >= 200:
            roi_a = (cv2.dilate(arm.astype(np.uint8), np.ones((41, 41), np.uint8)) > 0) & ~roi
            o["arm_px"] = int(arm.sum())
            if roi_a.sum() > 500:
                o["arm_prec"] = float((arm & gt).sum() / arm.sum())
                ea_r = e_r & roi_a
                if ea_r.sum() > 20:
                    o["arm_r2g"] = float(dt_g[ea_r].mean())
    elif arm is not None and arm.sum() >= 200:
        o["arm_px"] = int(arm.sum())
        o["arm_prec"] = float((arm & gt).sum() / arm.sum())
    return {prefix + k: v for k, v in o.items()}


def best_shift(rend, gt, max_shift=SHIFT_MAX_HALF):
    """Best integer translation of the render (half resolution) -> (iou_best, dx_full, dy_full, iou_at_zero)."""
    from scipy.signal import fftconvolve
    h, w = gt.shape
    r = cv2.resize(rend.astype(np.uint8) * 255, (w // 2, h // 2), interpolation=cv2.INTER_AREA) >= 128
    g = cv2.resize(gt.astype(np.uint8) * 255, (w // 2, h // 2), interpolation=cv2.INTER_AREA) >= 128
    if r.sum() == 0 or g.sum() == 0:
        return float("nan"), float("nan"), float("nan"), float("nan")
    rf, gf = r.astype(np.float32), g.astype(np.float32)
    inter = fftconvolve(gf, rf[::-1, ::-1], mode="full")
    inter = np.clip(np.rint(inter), 0, None)
    union = rf.sum() + gf.sum() - inter
    m = np.where(union > 0, inter / np.maximum(union, 1), 0.0)
    cy, cx = r.shape[0] - 1, r.shape[1] - 1
    win = m[cy - max_shift:cy + max_shift + 1, cx - max_shift:cx + max_shift + 1]
    k = int(np.argmax(win))
    dy, dx = divmod(k, win.shape[1])
    return float(win[dy, dx]), float(2 * (dx - max_shift)), float(2 * (dy - max_shift)), float(m[cy, cx])


# ----------------------------------------------------------------------------- worker

def body_masks(rr, seg):
    valid = seg >= 0
    body = np.where(valid, seg & ((1 << 24) - 1), -1)
    return valid, body == rr.gripper, body == rr.arm


def load_gt_steps(uuid):
    """{serial: set(steps)} of out/gt/<uuid>/steps.json = the SAM3-at-scale step pool every v2-chain fit draws from."""
    p = ROOT / "out/gt" / uuid / "steps.json"
    if not p.exists():
        return {}
    try:
        d = json.load(open(p))
    except (OSError, ValueError):
        return {}
    return {str(s): set(int(x["step"]) for x in lst if isinstance(x, dict) and "step" in x) for s, lst in d.items() if isinstance(lst, list)}


def held(r):
    """Held-out frame: not used by the v2 fit of that camera and not in the out/gt step pool."""
    return (not r.get("in_fit")) and (not r.get("in_gt"))


def v2_fit_steps(calib):
    out = {}
    for s, q in ((calib or {}).get("quality") or {}).items():
        st = ((q or {}).get("extra") or {}).get("steps") or []
        out[str(s)] = set(int(x) for x in st)
    return out


def score_episode(task):
    """One episode: all benchmark frames of all 3 cameras -> (rows, episode_info)."""
    ep, args = task
    os.environ.setdefault("OMP_NUM_THREADS", "1")
    cv2.setNumThreads(1)
    import render_episode as RE
    RE.VERBOSE = False
    uuid = ep["uuid"]
    ep_dir = ROOT / "data" / uuid
    gdir = Path(args["bench_root"]) / uuid
    out_masks = Path(args["out"]) / "masks" / uuid
    t0 = time.time()
    info = dict(uuid=uuid, lab=ep["lab"], robot=ep["robot_kind"], error=None)
    try:
        try:
            sess = RE.EpisodeSession(str(ep_dir), wrist=True)
        except KeyError as e:
            info["wrist_error"] = repr(e)
            sess = RE.EpisodeSession(str(ep_dir), wrist=False)
    except Exception as e:  # noqa: BLE001
        info["error"] = f"EpisodeSession: {e!r}"
        return [], info
    calib = sess.calib if sess.calib_version == 2 else None
    fit_steps = v2_fit_steps(calib)
    gt_steps = load_gt_steps(uuid)
    q_all = calib.get("quality", {}) if calib else {}
    info.update(calib_version=sess.calib_version, time_offset_ms=float(sess.dt_ms), arm=sess.arm_type,
                time_quality=sess.time_quality if calib else None, wrist_flipped=bool(getattr(sess, "wrist_flipped", False)),
                gt_masks_used=bool(getattr(sess, "gt_masks_used", False)), calib_mount_md5_ok=sess.calib_mount_md5_ok,
                calib_problems=list(getattr(sess, "calib_problems", []) or []),
                ext_base_source=dict(sess.ext_base_source), wrist_serial=sess.wrist_serial,
                quality={s: dict(status=q.get("status"), metric_before=q.get("metric_before"), metric_after=q.get("metric_after"),
                                 metric_name=q.get("metric_name"), n_steps=q.get("n_steps"), notes=q.get("notes"),
                                 delta_t_mm=(q.get("extra") or {}).get("delta_t_mm"), delta_rot_deg=(q.get("extra") or {}).get("delta_rot_deg"),
                                 iou_after_fit=(q.get("extra") or {}).get("iou_after"), r2g_after_fit=(q.get("extra") or {}).get("r2g_after"),
                                 mode=(q.get("extra") or {}).get("mode"), chosen_source=(q.get("extra") or {}).get("chosen_source"))
                         for s, q in q_all.items()},
                fit_steps={s: sorted(v) for s, v in fit_steps.items()}, n_gt_steps={s: len(v) for s, v in gt_steps.items()})
    rows = []
    serials = list(ep["serials"]["ext"]) + [ep["serials"]["wrist"]]
    frames = [int(f) for f in ep["frames"]][: args["max_frames"] or None]
    for serial in serials:
        serial = str(serial)
        is_wrist = serial == sess.wrist_serial
        cam = "wrist" if is_wrist else "ext"
        if serial not in sess.cap_ts or serial not in sess.K_mp4:
            info.setdefault("skipped", []).append(f"{serial}: no cap_ts / K")
            continue
        if is_wrist and not hasattr(sess, "X_handeye"):
            info.setdefault("skipped", []).append(f"{serial}: no wrist hand-eye")
            continue
        wh = tuple(sess.mp4_wh.get(serial, tuple(sess.wh[serial])))
        K = sess.K_mp4[serial]
        for step in frames:
            gp = gdir / serial / f"{step:04d}_gt.png"
            if not gp.exists() or step >= sess.n - 1:
                continue
            status = None
            pj = gdir / serial / f"{step:04d}_prompt.json"
            if pj.exists():
                try:
                    status = json.load(open(pj)).get("status")
                except (OSError, ValueError):
                    status = None
            gt = cv2.imread(str(gp), cv2.IMREAD_GRAYSCALE)
            if gt is None:
                continue
            gt = gt > 128
            if (gt.shape[1], gt.shape[0]) != wh:
                gt = cv2.resize(gt.astype(np.uint8) * 255, wh, interpolation=cv2.INTER_NEAREST) > 128
            gt_cache = None
            if gt.any():
                e_g = edge(gt)
                gt_cache = (e_g, dt_to(e_g), dt_to(gt))
            row = dict(uuid=uuid, lab=ep["lab"], robot=ep["robot_kind"], serial=serial, cam=cam, step=step, status=status,
                       gt_px=int(gt.sum()), res=f"{wh[0]}x{wh[1]}",
                       in_fit=bool(step in fit_steps.get(serial, set())),
                       in_fit_pm1=bool(any((step + k) in fit_steps.get(serial, set()) for k in (-1, 0, 1))),
                       in_gt=bool(step in gt_steps.get(serial, set())),
                       in_gt_pm1=bool(any((step + k) in gt_steps.get(serial, set()) for k in (-1, 0, 1))),
                       usable=bool(status in USABLE and gt.sum() >= MIN_GT_PX),
                       usable_ext=bool(status in USABLE_EXT and gt.sum() >= MIN_GT_PX),
                       g=float(sess.gs[step]), dt_ms=float(sess.dt_ms), fast=bool(step in set(ep.get("fast_frames", []))),
                       ee_speed=float(ep["frame_speed_mps"][ep["frames"].index(step)]) if step in ep["frames"] else float("nan"),
                       v2_status=(q_all.get(serial) or {}).get("status"), wrist_flipped=bool(is_wrist and info["wrist_flipped"]))
            # ---- new render
            T = sess.set_step(serial, step, interp=True)
            _, _, seg = sess.rr.render_raw(T, K, wh)
            mask, grip, arm = body_masks(sess.rr, seg)
            row.update(mask_metrics(mask, gt, grip, arm, gt_cache, prefix="new_"))
            row["new_touch_border"] = bool(mask[0].any() or mask[-1].any() or mask[:, 0].any() or mask[:, -1].any())
            row["gt_touch_border"] = bool(gt[0].any() or gt[-1].any() or gt[:, 0].any() or gt[:, -1].any())
            # ---- old render (benchmark-time pipeline render), re-scored with the same code
            op = gdir / serial / f"{step:04d}_rend.png"
            old = cv2.imread(str(op), cv2.IMREAD_GRAYSCALE) if op.exists() else None
            if old is not None:
                old = old > 128
                if old.shape != gt.shape:
                    old = cv2.resize(old.astype(np.uint8) * 255, wh, interpolation=cv2.INTER_NEAREST) > 128
                row.update(mask_metrics(old, gt, None, None, gt_cache, prefix="old_"))
            # ---- probes
            if not args["no_probe"] and gt.any() and mask.any():
                ib, dxb, dyb, i0 = best_shift(mask, gt)
                row.update(shift_iou_best=ib, shift_dx=dxb, shift_dy=dyb, shift_iou0=i0, shift_gain=ib - i0 if np.isfinite(ib) else float("nan"))
                if not is_wrist:
                    best, best_d = row["new_iou"], 0.0
                    for d in TIME_PROBES_MS:
                        q, g = sess.state_at(float(sess.cap_ts[serial][step]) + float(sess.dt_ms) + d)
                        sess.rr.set_state(q, g)
                        _, _, seg_d = sess.rr.render_raw(sess.T_ext[serial], K, wh)
                        v = iou_of(seg_d >= 0, gt)
                        row[f"time_iou_{int(d):+d}"] = v
                        if np.isfinite(v) and v > best:
                            best, best_d = v, d
                    row.update(time_iou_best=best, time_d_best=best_d, time_gain=best - row["new_iou"])
            if args["save_masks"]:
                (out_masks / serial).mkdir(parents=True, exist_ok=True)
                cv2.imwrite(str(out_masks / serial / f"{step:04d}.png"), mask.astype(np.uint8) * 255)
            rows.append(row)
    info["secs"] = round(time.time() - t0, 1)
    info["n_rows"] = len(rows)
    try:
        sess.rr.close()
    except Exception:  # noqa: BLE001
        pass
    return rows, info


# ----------------------------------------------------------------------------- aggregation

def load_old_csv(path):
    out = {}
    if not Path(path).exists():
        return out
    with open(path) as f:
        for r in csv.DictReader(f):
            key = (r["uuid"], str(r["serial"]), int(r["step"]))
            out[key] = r
    return out


def fnum(v):
    try:
        x = float(v)
        return x if np.isfinite(x) else None
    except (TypeError, ValueError):
        return None


def summarize(rows, key_iou, key_r2g):
    (i10, i50, i90), n = pct([r.get(key_iou) for r in rows])
    (r10, r50, r90), _ = pct([r.get(key_r2g) for r in rows])
    return dict(n=n, iou_p10_p50_p90=[_f(i10), _f(i50), _f(i90)], r2g_p10_p50_p90=[_f(r10, 2), _f(r50, 2), _f(r90, 2)])


def targets_met(cam, summ):
    t = TARGETS[cam]
    iou, r2g = summ["iou_p10_p50_p90"], summ["r2g_p10_p50_p90"]
    if any(v is None for v in iou + r2g):
        return None, {}
    det = {f"iou_p{p}": (iou[i] >= t["iou"][i]) for i, p in enumerate((10, 50, 90))}
    det.update({f"r2g_p{p}": (r2g[i] <= t["r2g"][i]) for i, p in enumerate((10, 50, 90))})
    return all(det.values()), det


def attribute(row, cam_shift_med, ep_info):
    """Suspected dominant cause of a bad frame (heuristic, from the probes + v2 quality)."""
    cam = row["cam"]
    q = (ep_info.get("quality") or {}).get(row["serial"]) or {}
    st = q.get("status")
    tg = fnum(row.get("time_gain")) or 0.0
    sg = fnum(row.get("shift_gain")) or 0.0
    loss = 1.0 - (fnum(row.get("new_iou")) or 0.0)
    far = fnum(row.get("new_gt_far_frac")) or 0.0
    ar = fnum(row.get("new_area_ratio"))
    gr, arr = fnum(row.get("new_grip_r2g")), fnum(row.get("new_arm_r2g"))
    gt_noise = far > 0.08 or (ar is not None and (ar < 0.6 or ar > 1.5)) or (row.get("status") in ("low_conf", "single") and far > 0.04)
    med = cam_shift_med.get((row["uuid"], row["serial"]))
    consistent = False
    if med is not None and fnum(row.get("shift_dx")) is not None:
        consistent = (abs(row["shift_dx"] - med[0]) <= 6 and abs(row["shift_dy"] - med[1]) <= 6 and np.hypot(*med) >= 4)
    tags = []
    iou_new = fnum(row.get("new_iou")) or 0.0
    r2g_new = fnum(row.get("new_r2g")) or 0.0
    gt_px = fnum(row.get("gt_px")) or 0.0
    if iou_new >= 0.8 and r2g_new > 15:
        tags.append("occluded robot part rendered but absent from GT (metric artifact: r2g not robust to GT omissions)")
    if far > 0.3 or (gt_px < 20000 and (row.get("gt_touch_border") or row.get("new_touch_border")) and iou_new < 0.5):
        tags.append("GT failure / robot barely in view (SAM3 hallucination or cables)")
    if cam == "wrist":
        if st == "failed":
            tags.append("wrist stage FAILED (identity wrist_delta)")
        elif st == "degraded":
            tags.append("wrist stage degraded")
        if row.get("wrist_flipped"):
            tags.append("flipped wrist")
        if gt_noise:
            tags.append("GT noise (far px / area ratio)")
        if sg >= 0.05 and sg >= 0.4 * loss:
            tags.append("wrist hand-eye rigid residual (shift recovers %.0f%%)" % (100 * sg / max(loss, 1e-6)))
        if gr is not None and gr > 12 and (row.get("g") or 0) > 0.5:
            tags.append("closed gripper pads (mimic/mount/compliance)")
        if not tags:
            tags.append("residual (mesh/GT floor, non-rigid)")
        return "; ".join(tags)
    if st == "failed":
        tags.append("ext stage FAILED (official pose + identity)")
    elif st == "degraded":
        tags.append("ext stage degraded")
    if gt_noise:
        tags.append("GT noise (far px / area ratio)")
    if tg >= 0.03 and tg >= 0.5 * sg:
        tags.append("time (%+.0f ms recovers %.0f%%)" % (fnum(row.get("time_d_best")) or 0, 100 * tg / max(loss, 1e-6)))
    if sg >= 0.05 and sg >= 0.4 * loss:
        tags.append(("ext rigid residual (camera-consistent shift %.0f/%.0f px)" % tuple(med)) if consistent
                    else "per-frame pose/time (shift recovers %.0f%%, not camera-consistent)" % (100 * sg / max(loss, 1e-6)))
    if gr is not None and gr > max(8.0, 2.0 * (arr or 0.0)):
        tags.append("gripper/mount (grip edge %.1f px vs arm %s)" % (gr, f"{arr:.1f}" if arr is not None else "?"))
    if not tags:
        tags.append("residual (mesh/GT floor, non-rigid)")
    return "; ".join(tags)


def md_table(header, rows):
    out = ["| " + " | ".join(header) + " |", "|" + "---|" * len(header)]
    for r in rows:
        out.append("| " + " | ".join("" if v is None else str(v) for v in r) + " |")
    return "\n".join(out)


def fmt3(v, nd=3):
    if v is None:
        return "-"
    return "/".join("-" if x is None else f"{x:.{nd}f}" for x in v)


# ----------------------------------------------------------------------------- images

def load_real(gdir, serial, step, wh):
    p = gdir / serial / f"{step:04d}_real.png"
    im = cv2.imread(str(p), cv2.IMREAD_COLOR)
    if im is None:
        return np.zeros((wh[1], wh[0], 3), np.uint8)
    if (im.shape[1], im.shape[0]) != wh:
        im = cv2.resize(im, wh, interpolation=cv2.INTER_AREA)
    return im


def draw_contours(img, mask, color, thick=1):
    if mask is None or not mask.any():
        return img
    cs, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
    cv2.drawContours(img, cs, -1, color, thick)
    return img


def tile(real, gt, new, old, text, size=(640, 360), draw_old=True):
    im = cv2.resize(real, size, interpolation=cv2.INTER_AREA)
    rs = lambda m: None if m is None else (cv2.resize(m.astype(np.uint8) * 255, size, interpolation=cv2.INTER_AREA) >= 128)  # noqa: E731
    if draw_old and old is not None:
        draw_contours(im, rs(old), (255, 128, 0), 1)       # old render: blue (BGR)
    draw_contours(im, rs(gt), (0, 220, 0), 1)              # GT: green
    draw_contours(im, rs(new), (0, 0, 255), 1)             # new render: red
    y = 16
    for line in text:
        cv2.putText(im, line, (6, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 0), 3, cv2.LINE_AA)
        cv2.putText(im, line, (6, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255, 255, 255), 1, cv2.LINE_AA)
        y += 17
    return im


def read_mask(p):
    m = cv2.imread(str(p), cv2.IMREAD_GRAYSCALE)
    return None if m is None else m > 128


def make_worst_sheet(rows, out_path, bench_root, mask_root, title):
    tiles = []
    for r in rows:
        gdir = Path(bench_root) / r["uuid"]
        w, h = [int(x) for x in r["res"].split("x")]
        real = load_real(gdir, r["serial"], r["step"], (w, h))
        gt = read_mask(gdir / r["serial"] / f"{r['step']:04d}_gt.png")
        old = read_mask(gdir / r["serial"] / f"{r['step']:04d}_rend.png")
        new = read_mask(Path(mask_root) / r["uuid"] / r["serial"] / f"{r['step']:04d}.png")
        txt = [f"{r['uuid'][:40]} {r['serial']} step {r['step']} [{r['status']}] g={r['g']:.2f} v={r['ee_speed']:.2f}",
               f"IoU old {fnum(r.get('old_iou_csv')) or float('nan'):.3f} -> new {r['new_iou']:.3f}   r2g {fnum(r.get('old_r2g_csv')) or float('nan'):.1f} -> {r['new_r2g']:.1f} px",
               f"probe: shift {r.get('shift_dx', float('nan')):+.0f},{r.get('shift_dy', float('nan')):+.0f} px gain {fnum(r.get('shift_gain')) or 0:.3f}; time {fnum(r.get('time_d_best')) or 0:+.0f} ms gain {fnum(r.get('time_gain')) or 0:.3f}",
               f"v2 {r['serial']}: {r.get('v2_status')}; cause: {r.get('cause', '')[:70]}"]
        tiles.append(tile(real, gt, new, old, txt))
    if not tiles:
        return
    cols = 3
    while len(tiles) % cols:
        tiles.append(np.zeros_like(tiles[0]))
    grid = np.vstack([np.hstack(tiles[i:i + cols]) for i in range(0, len(tiles), cols)])
    head = np.full((28, grid.shape[1], 3), 30, np.uint8)
    cv2.putText(head, title, (8, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 1, cv2.LINE_AA)
    cv2.imwrite(str(out_path), np.vstack([head, grid]), [cv2.IMWRITE_JPEG_QUALITY, 88])


def make_before_after_grid(rows, infos, out_path, bench_root, mask_root, sample_eps):
    by_lab = {}
    for ep in sample_eps:
        by_lab.setdefault(ep["lab"], []).append(ep)
    chosen = []
    for lab in GRID_LABS:
        eps = by_lab.get(lab) or []
        if lab == "TRI":
            eps = [e for e in eps if e["robot_kind"] == "fr3"] or eps
        if eps:
            chosen.append(eps[0])
    for ep in sample_eps:  # top up to 8
        if len(chosen) >= 8:
            break
        if ep not in chosen:
            chosen.append(ep)
    strips = []
    for ep in chosen[:8]:
        u = ep["uuid"]
        info = infos.get(u, {})
        ext_serial = str(ep["serials"]["ext"][0])
        wr_serial = str(ep["serials"]["wrist"])
        row_tiles = []
        for serial in (ext_serial, wr_serial):
            cand = [r for r in rows if r["uuid"] == u and r["serial"] == serial and r["usable"] and fnum(r.get("new_iou")) is not None]
            if not cand:
                row_tiles += [np.zeros((360, 640, 3), np.uint8)] * 2
                continue
            cand.sort(key=lambda r: r["new_iou"])
            r = cand[len(cand) // 2]  # median new-IoU frame
            gdir = Path(bench_root) / u
            w, h = [int(x) for x in r["res"].split("x")]
            real = load_real(gdir, serial, r["step"], (w, h))
            gt = read_mask(gdir / serial / f"{r['step']:04d}_gt.png")
            old = read_mask(gdir / serial / f"{r['step']:04d}_rend.png")
            new = read_mask(Path(mask_root) / u / serial / f"{r['step']:04d}.png")
            q = (info.get("quality") or {}).get(serial) or {}
            t_old = [f"OLD {u[:34]} {serial} step {r['step']}", f"IoU {fnum(r.get('old_iou_csv')) or float('nan'):.3f} r2g {fnum(r.get('old_r2g_csv')) or float('nan'):.1f} px (old calib, old geometry)"]
            t_new = [f"NEW v2 {serial} dt {info.get('time_offset_ms', float('nan')):+.1f} ms [{(info.get('time_quality') or {}).get('sweep_class', '?')}] arm {info.get('arm')}",
                     f"IoU {r['new_iou']:.3f} r2g {r['new_r2g']:.1f} px; v2 {q.get('status')} {q.get('metric_before')} -> {q.get('metric_after')}"]
            row_tiles.append(tile(real, gt, old, None, t_old, draw_old=False))
            row_tiles.append(tile(real, gt, new, None, t_new, draw_old=False))
        strips.append(np.hstack(row_tiles))
    if not strips:
        return
    head = np.full((28, strips[0].shape[1], 3), 30, np.uint8)
    cv2.putText(head, "before (old pipeline render, red) vs after (v2 chain render, red); GT green. cols: ext old | ext new | wrist old | wrist new",
                (8, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 1, cv2.LINE_AA)
    cv2.imwrite(str(out_path), np.vstack([head] + strips), [cv2.IMWRITE_JPEG_QUALITY, 88])


# ----------------------------------------------------------------------------- main

def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--out", default=str(ROOT / "out/bench/round1"))
    ap.add_argument("--sample", default=str(SAMPLE))
    ap.add_argument("--bench-root", default=str(BENCH_ROOT))
    ap.add_argument("--old-csv", default=str(OLD_CSV))
    ap.add_argument("--workers", type=int, default=int(os.environ.get("SLURM_CPUS_PER_TASK", 4)))
    ap.add_argument("--episodes", nargs="*", default=None, help="subset of uuids")
    ap.add_argument("--max-frames", type=int, default=0, help="per camera (smoke test)")
    ap.add_argument("--no-probe", action="store_true", help="skip the time / shift probes")
    ap.add_argument("--no-images", action="store_true")
    ap.add_argument("--no-save-masks", action="store_true")
    ap.add_argument("--round-name", default="round 1")
    ap.add_argument("--notes", default=None, help="markdown file appended to summary.md (analyst notes)")
    ap.add_argument("--prev-csv", default=None, help="metrics.csv of an earlier run of this script -> prev_iou / prev_r2g + paired deltas")
    ap.add_argument("--prev-v2-dir", default=None, help="directory of <uuid>.json = superseded calib_refined_v2.json -> per-camera pose / time change")
    ap.add_argument("--exclude-frames", default=None,
                    help="json list of {uuid, serial, step[, reason]} = benchmark frames judged GT failures (robot out of view / hallucinated mask); "
                         "reported as an extra DIAG variant only, the target rows keep every usable frame")
    args = ap.parse_args(argv)
    excl = {}
    if args.exclude_frames and Path(args.exclude_frames).exists():
        for e in json.load(open(args.exclude_frames)):
            excl[(e["uuid"], str(e["serial"]), int(e["step"]))] = e.get("reason", "")
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    sample = json.load(open(args.sample))
    eps = sample["episodes"]
    if args.episodes:
        eps = [e for e in eps if e["uuid"] in set(args.episodes)]
    wargs = dict(bench_root=args.bench_root, out=str(out), max_frames=int(args.max_frames), no_probe=bool(args.no_probe),
                 save_masks=not args.no_save_masks)
    tasks = [(e, wargs) for e in eps]
    t0 = time.time()
    log(f"{len(tasks)} episodes, {args.workers} workers -> {out}")
    results = []
    if args.workers <= 1:
        for t in tasks:
            results.append(score_episode(t))
            log(f"  {t[0]['uuid']}: {results[-1][1].get('n_rows')} rows {results[-1][1].get('secs')} s {results[-1][1].get('error') or ''}")
    else:
        import multiprocessing as mp
        ctx = mp.get_context("spawn")
        with ctx.Pool(args.workers) as pool:
            for rows_i, info_i in pool.imap_unordered(score_episode, tasks):
                results.append((rows_i, info_i))
                log(f"  {info_i['uuid']}: {info_i.get('n_rows')} rows {info_i.get('secs')} s calib v{info_i.get('calib_version')} {info_i.get('error') or ''}")
    rows = [r for rs, _ in results for r in rs]
    infos = {i["uuid"]: i for _, i in results}
    log(f"scored {len(rows)} frames in {time.time() - t0:.0f} s")

    for r in rows:
        r["excluded_gt_failure"] = (r["uuid"], r["serial"], r["step"]) in excl
        r["exclude_reason"] = excl.get((r["uuid"], r["serial"], r["step"]), "")

    # ---- merge the old csv
    old = load_old_csv(args.old_csv)
    n_status_mismatch = 0
    for r in rows:
        o = old.get((r["uuid"], r["serial"], r["step"]))
        if o:
            r["old_iou_csv"], r["old_r2g_csv"] = fnum(o.get("iou")), fnum(o.get("ch_r2g_mean"))
            r["old_dt_ms"] = fnum(o.get("dt_ms"))
            r["h1_iou"], r["h7_iou"], r["h7_r2g"] = fnum(o.get("h1_iou")), fnum(o.get("h7_iou")), fnum(o.get("h7_ch_r2g_mean"))
            r["old_status_csv"] = o.get("status")
            if o.get("status") != r["status"]:
                n_status_mismatch += 1
        else:
            r["old_iou_csv"] = r["old_r2g_csv"] = r["old_dt_ms"] = r["h1_iou"] = r["h7_iou"] = r["h7_r2g"] = None
            r["old_status_csv"] = None

    # ---- merge a previous run of this script (paired comparison of two v2 fits)
    prev = load_old_csv(args.prev_csv) if args.prev_csv else {}
    for r in rows:
        p = prev.get((r["uuid"], r["serial"], r["step"]))
        r["prev_iou"] = fnum(p.get("new_iou")) if p else None
        r["prev_r2g"] = fnum(p.get("new_r2g")) if p else None
        r["d_iou_vs_prev"] = (r["new_iou"] - r["prev_iou"]) if (r["prev_iou"] is not None and fnum(r.get("new_iou")) is not None) else None

    # ---- previous (superseded) v2 files: pose / time change per camera
    prev_v2 = {}
    if args.prev_v2_dir:
        from dutils import pose6_to_mat
        from scipy.spatial.transform import Rotation as Rot
        for u in infos:
            pp = Path(args.prev_v2_dir) / f"{u}.json"
            cur = ROOT / "data" / u / "calib_refined_v2.json"
            if not pp.exists() or not cur.exists():
                continue
            try:
                a, b = json.load(open(pp)), json.load(open(cur))
            except (OSError, ValueError):
                continue
            rec = dict(prev_time_offset_ms=a.get("time_offset_ms"), d_time_ms=(b.get("time_offset_ms") or 0) - (a.get("time_offset_ms") or 0),
                       prev_written=(a.get("fit_meta") or {}).get("written"), cams={})
            for serial in set(list((b.get("ext_delta") or {}).keys()) + list((b.get("wrist_delta") or {}).keys())):
                try:
                    if serial in (b.get("ext_delta") or {}):
                        Tb = pose6_to_mat(b["ext_delta"][serial]) @ np.linalg.inv(pose6_to_mat(b["ext_base_pose6"][serial]))
                        Ta = pose6_to_mat(a["ext_delta"][serial]) @ np.linalg.inv(pose6_to_mat(a["ext_base_pose6"][serial]))
                    else:
                        Tb, Ta = pose6_to_mat(b["wrist_delta"][serial]), pose6_to_mat(a["wrist_delta"][serial])
                    D = Tb @ np.linalg.inv(Ta)
                    rec["cams"][serial] = dict(dt_mm=float(np.linalg.norm(D[:3, 3]) * 1000.0), drot_deg=float(np.degrees(Rot.from_matrix(D[:3, :3]).magnitude())),
                                               prev_status=((a.get("quality") or {}).get(serial) or {}).get("status"),
                                               prev_metric_after=((a.get("quality") or {}).get(serial) or {}).get("metric_after"),
                                               prev_source=(a.get("ext_base_source") or {}).get(serial), source=(b.get("ext_base_source") or {}).get(serial))
                except (KeyError, TypeError, ValueError, np.linalg.LinAlgError) as e:  # noqa: PERF203
                    rec["cams"][serial] = dict(error=repr(e))
            prev_v2[u] = rec

    # ---- per-camera median best shift (for the attribution)
    cam_shift_med = {}
    for key in {(r["uuid"], r["serial"]) for r in rows}:
        sub = [r for r in rows if (r["uuid"], r["serial"]) == key and r["usable"] and fnum(r.get("shift_dx")) is not None]
        if len(sub) >= 3:
            cam_shift_med[key] = (float(np.median([r["shift_dx"] for r in sub])), float(np.median([r["shift_dy"] for r in sub])))
    for r in rows:
        bad = False
        if r["usable"] and fnum(r.get("new_iou")) is not None:
            t = TARGETS[r["cam"]]
            bad = r["new_iou"] < t["iou"][1] or (fnum(r.get("new_r2g")) or 0) > t["r2g"][1]
        r["bad"] = bad
        r["cause"] = attribute(r, cam_shift_med, infos.get(r["uuid"], {})) if bad else ""

    # ---- summaries
    def subset(cam, pred=lambda r: True, held_out=True):
        return [r for r in rows if r["cam"] == cam and r["usable"] and pred(r) and (not held_out or held(r))]

    summary = dict(round=args.round_name, n_rows=len(rows), n_episodes=len(infos), old_csv_rows_matched=sum(1 for r in rows if r.get("old_iou_csv") is not None),
                   status_mismatch_vs_csv=n_status_mismatch, n_in_fit=sum(1 for r in rows if r["in_fit"]), n_in_fit_pm1=sum(1 for r in rows if r["in_fit_pm1"]),
                   n_in_gt=sum(1 for r in rows if r["in_gt"]), n_in_gt_pm1=sum(1 for r in rows if r["in_gt_pm1"]), n_not_held_out=sum(1 for r in rows if not held(r)),
                   prev_csv=args.prev_csv, prev_v2_dir=args.prev_v2_dir,
                   mount_fit_note="calib/mount_params.json (6 mount params + gripper_max_angle) was fitted on these benchmark frames (out/mount_fit_final); "
                                  "per-episode time/ext/wrist (refine_v2) and session priors use out/gt steps, which exclude the benchmark frames +-1.",
                   targets=TARGETS, noise_floor=NOISE_FLOOR, overall={}, per_lab={}, per_robot={}, splits={}, episodes={})
    for cam in ("ext", "wrist"):
        sub = subset(cam)
        sub_all = subset(cam, held_out=False)
        sub_ext = [r for r in rows if r["cam"] == cam and r["usable_ext"] and held(r)]
        occ = lambda r: (fnum(r.get("new_iou")) or 0) >= 0.8 and (fnum(r.get("new_r2g")) or 0) > 15  # noqa: E731
        o = dict(old_csv=summarize(sub, "old_iou_csv", "old_r2g_csv"), old_rescored=summarize(sub, "old_iou", "old_r2g"),
                 new_status_ok_only=summarize([r for r in sub if r["status"] == "ok"], "new_iou", "new_r2g"),
                 new_excl_occlusion_type=summarize([r for r in sub if not occ(r)], "new_iou", "new_r2g"),
                 new_v2_ok_cams_only=summarize([r for r in sub if r.get("v2_status") == "ok"], "new_iou", "new_r2g"),
                 new=summarize(sub, "new_iou", "new_r2g"), new_incl_fit_frames=summarize(sub_all, "new_iou", "new_r2g"),
                 new_usable_ext_statuses=summarize(sub_ext, "new_iou", "new_r2g"),
                 new_r2g_near=summarize(sub, "new_iou", "new_r2g_near"),
                 new_excl_listed_gt_failures=summarize([r for r in sub if not r["excluded_gt_failure"]], "new_iou", "new_r2g"),
                 n_listed_gt_failures=int(sum(1 for r in sub if r["excluded_gt_failure"])),
                 prev_run=summarize(sub, "prev_iou", "prev_r2g") if prev else None,
                 h7_free_pose_bound_old_geometry=summarize(sub, "h7_iou", "h7_r2g"),
                 h1_rigid_bound_old_geometry=summarize(sub, "h1_iou", "h1_iou"))
        o["h1_rigid_bound_old_geometry"].pop("r2g_p10_p50_p90", None)
        met, det = targets_met(cam, o["new"])
        o["targets_met"], o["targets_detail"] = met, det
        o["targets_met_excl_listed_gt_failures"], o["targets_detail_excl_listed_gt_failures"] = targets_met(cam, o["new_excl_listed_gt_failures"])
        o["frac_bad_new"] = _f(np.mean([r["bad"] for r in sub])) if sub else None
        o["frac_r2g_gt10_old"] = _f(np.mean([(r.get("old_r2g_csv") or 0) > 10 for r in sub if r.get("old_r2g_csv") is not None])) if sub else None
        o["frac_r2g_gt10_new"] = _f(np.mean([(r.get("new_r2g") or 0) > 10 for r in sub])) if sub else None
        o["delta_iou_median_paired"] = _f(np.median([r["new_iou"] - r["old_iou_csv"] for r in sub if r.get("old_iou_csv") is not None and fnum(r.get("new_iou")) is not None])) if sub else None
        o["frac_frames_improved_iou"] = _f(np.mean([r["new_iou"] > r["old_iou_csv"] for r in sub if r.get("old_iou_csv") is not None and fnum(r.get("new_iou")) is not None])) if sub else None
        if prev:
            pair = [r for r in sub if r.get("prev_iou") is not None and fnum(r.get("new_iou")) is not None]
            o["vs_prev"] = dict(n=len(pair), d_iou_p10_p50_p90=[_f(v) for v in pct([r["new_iou"] - r["prev_iou"] for r in pair])[0]],
                                d_r2g_p10_p50_p90=[_f(v, 2) for v in pct([r["new_r2g"] - r["prev_r2g"] for r in pair if r.get("prev_r2g") is not None and fnum(r.get("new_r2g")) is not None])[0]],
                                frac_iou_up=_f(np.mean([r["new_iou"] > r["prev_iou"] + 1e-6 for r in pair])) if pair else None,
                                frac_iou_down=_f(np.mean([r["new_iou"] < r["prev_iou"] - 1e-6 for r in pair])) if pair else None,
                                frac_abs_d_iou_gt_0p02=_f(np.mean([abs(r["new_iou"] - r["prev_iou"]) > 0.02 for r in pair])) if pair else None)
        if not args.no_probe:
            o["probe_time_gain_p50_p90"] = [_f(v) for v in pct([r.get("time_gain") for r in sub], (50, 90))[0]] if cam == "ext" else None
            o["probe_shift_gain_p50_p90"] = [_f(v) for v in pct([r.get("shift_gain") for r in sub], (50, 90))[0]]
            o["probe_shift_px_p50_p90"] = [_f(v, 1) for v in pct([np.hypot(r["shift_dx"], r["shift_dy"]) for r in sub if fnum(r.get("shift_dx")) is not None], (50, 90))[0]]
        summary["overall"][cam] = o
        for lab in sorted({r["lab"] for r in rows}):
            s = subset(cam, lambda r, lab=lab: r["lab"] == lab)
            lab_new = summarize(s, "new_iou", "new_r2g")
            lab_met, lab_det = targets_met(cam, lab_new)
            summary["per_lab"].setdefault(lab, {})[cam] = dict(old_csv=summarize(s, "old_iou_csv", "old_r2g_csv"), new=lab_new,
                                                                 prev_run=summarize(s, "prev_iou", "prev_r2g") if prev else None,
                                                                 n_bad_new=int(sum(r["bad"] for r in s)), targets_met=lab_met,
                                                                 n_targets_met=(sum(lab_det.values()) if lab_det else None))
        for rb in ("fr3", "panda"):
            s = subset(cam, lambda r, rb=rb: r["robot"] == rb)
            summary["per_robot"].setdefault(rb, {})[cam] = dict(old_csv=summarize(s, "old_iou_csv", "old_r2g_csv"), new=summarize(s, "new_iou", "new_r2g"))
        splits = {}
        if cam == "ext":
            splits["fast(EE>=0.15)"] = subset(cam, lambda r: (r.get("ee_speed") or 0) >= 0.15)
            splits["slow"] = subset(cam, lambda r: (r.get("ee_speed") or 0) < 0.15)
        splits["gripper_closed(g>0.5)"] = subset(cam, lambda r: r["g"] > 0.5)
        splits["gripper_open(g<0.1)"] = subset(cam, lambda r: r["g"] < 0.1)
        splits["status_ok"] = subset(cam, lambda r: r["status"] == "ok")
        splits["status_single"] = subset(cam, lambda r: r["status"] == "single")
        splits["status_low_conf"] = subset(cam, lambda r: r["status"] == "low_conf")
        splits["v2_cam_ok"] = subset(cam, lambda r: r.get("v2_status") == "ok")
        splits["v2_cam_not_ok"] = subset(cam, lambda r: r.get("v2_status") != "ok")
        summary["splits"][cam] = {k: dict(old_csv=summarize(v, "old_iou_csv", "old_r2g_csv"), new=summarize(v, "new_iou", "new_r2g")) for k, v in splits.items()}

    # ---- per episode / per camera
    per_ep_rows = []
    for ep in eps:
        u = ep["uuid"]
        info = infos.get(u, {})
        rec = dict(uuid=u, lab=ep["lab"], robot=ep["robot_kind"], calib_version=info.get("calib_version"), arm=info.get("arm"),
                   time_offset_ms=_f(info.get("time_offset_ms"), 2), old_time_offset_ms=ep.get("time_offset_ms"),
                   sweep_class=(info.get("time_quality") or {}).get("sweep_class"), prior_used=(info.get("time_quality") or {}).get("prior_used"),
                   wrist_flipped=info.get("wrist_flipped"), gt_masks_used=info.get("gt_masks_used"), mount_md5_ok=info.get("calib_mount_md5_ok"),
                   calib_problems=";".join(info.get("calib_problems") or []), error=info.get("error"), cams={},
                   prev_time_offset_ms=(prev_v2.get(u) or {}).get("prev_time_offset_ms"), d_time_ms_vs_prev=_f((prev_v2.get(u) or {}).get("d_time_ms"), 2))
        for serial in [str(s) for s in ep["serials"]["ext"]] + [str(ep["serials"]["wrist"])]:
            s = [r for r in rows if r["uuid"] == u and r["serial"] == serial and r["usable"] and held(r)]
            q = (info.get("quality") or {}).get(serial) or {}
            (oi,), _ = pct([r.get("old_iou_csv") for r in s], (50,))
            (ni,), _ = pct([r.get("new_iou") for r in s], (50,))
            (orr,), _ = pct([r.get("old_r2g_csv") for r in s], (50,))
            (nr,), _ = pct([r.get("new_r2g") for r in s], (50,))
            (nmin,), _ = pct([r.get("new_iou") for r in s], (0,))
            (nrmax,), _ = pct([r.get("new_r2g") for r in s], (100,))
            med = cam_shift_med.get((u, serial))
            rec["cams"][serial] = dict(cam="wrist" if serial == str(ep["serials"]["wrist"]) else "ext", n=len(s), v2_status=q.get("status"),
                                       v2_metric=f"{q.get('metric_before')}->{q.get('metric_after')}", v2_source=(info.get("ext_base_source") or {}).get(serial),
                                       v2_delta=f"{q.get('delta_t_mm')} mm/{q.get('delta_rot_deg')} deg", v2_notes=(q.get("notes") or "")[:160],
                                       iou_p50_old=_f(oi, 3), iou_p50_new=_f(ni, 3), r2g_p50_old=_f(orr, 2), r2g_p50_new=_f(nr, 2),
                                       iou_min_new=_f(nmin, 3), r2g_max_new=_f(nrmax, 2), n_bad=int(sum(r["bad"] for r in s)),
                                       shift_med_px=None if med is None else [round(med[0], 1), round(med[1], 1)],
                                       causes=sorted({r["cause"].split(";")[0] for r in s if r["bad"]}))
            pv = ((prev_v2.get(u) or {}).get("cams") or {}).get(serial)
            if pv:
                (pi,), _ = pct([r.get("prev_iou") for r in s], (50,))
                (pr,), _ = pct([r.get("prev_r2g") for r in s], (50,))
                rec["cams"][serial].update(pose_change_vs_prev=(f"{pv['dt_mm']:.1f} mm/{pv['drot_deg']:.2f} deg" if "dt_mm" in pv else pv.get("error")),
                                           prev_v2_status=pv.get("prev_status"), prev_v2_source=pv.get("prev_source"), prev_v2_metric_after=pv.get("prev_metric_after"),
                                           iou_p50_prev=_f(pi, 3), r2g_p50_prev=_f(pr, 2))
        per_ep_rows.append(rec)
        summary["episodes"][u] = rec

    # ---- worst frames / cause histogram
    usable_rows = [r for r in rows if r["usable"] and held(r) and fnum(r.get("new_iou")) is not None]
    worst = {cam: sorted([r for r in usable_rows if r["cam"] == cam], key=lambda r: (r["new_iou"], -(r.get("new_r2g") or 0)))[:12] for cam in ("ext", "wrist")}
    summary["worst12"] = {cam: [dict(uuid=r["uuid"], serial=r["serial"], step=r["step"], status=r["status"], iou_old=_f(r.get("old_iou_csv"), 3), iou_new=_f(r["new_iou"], 3),
                                     r2g_old=_f(r.get("old_r2g_csv"), 1), r2g_new=_f(r.get("new_r2g"), 1), g=_f(r["g"], 2), speed=_f(r.get("ee_speed"), 2),
                                     shift=[_f(r.get("shift_dx"), 0), _f(r.get("shift_dy"), 0)], shift_gain=_f(r.get("shift_gain"), 3),
                                     time_d_best=_f(r.get("time_d_best"), 0), time_gain=_f(r.get("time_gain"), 3), v2_status=r.get("v2_status"), cause=r["cause"])
                                for r in worst[cam]] for cam in worst}
    causes = {}
    for cam in ("ext", "wrist"):
        c = {}
        for r in usable_rows:
            if r["cam"] == cam and r["bad"]:
                k = r["cause"].split(";")[0].split(" (")[0]
                c[k] = c.get(k, 0) + 1
        causes[cam] = dict(sorted(c.items(), key=lambda kv: -kv[1]))
    summary["bad_frame_causes"] = causes
    summary["targets_met_all"] = bool(all((summary["overall"][c].get("targets_met") is True) for c in ("ext", "wrist")))
    summary["elapsed_s"] = round(time.time() - t0, 1)

    # ---- write csv / json
    keys = []
    for r in rows:
        for k in r:
            if k not in keys:
                keys.append(k)
    with open(out / "metrics.csv", "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=keys)
        w.writeheader()
        for r in rows:
            w.writerow({k: ("" if (v is None or (isinstance(v, float) and not np.isfinite(v))) else v) for k, v in r.items()})
    with open(out / "per_episode.csv", "w", newline="") as f:
        cols = ["uuid", "lab", "robot", "serial", "cam", "n", "v2_status", "v2_source", "v2_metric", "v2_delta", "iou_p50_old", "iou_p50_new",
                "r2g_p50_old", "r2g_p50_new", "iou_min_new", "r2g_max_new", "n_bad", "shift_med_px", "time_offset_ms", "old_time_offset_ms", "sweep_class",
                "wrist_flipped", "causes", "v2_notes", "iou_p50_prev", "r2g_p50_prev", "pose_change_vs_prev", "prev_v2_status", "prev_v2_source",
                "prev_v2_metric_after", "prev_time_offset_ms", "d_time_ms_vs_prev"]
        w = csv.DictWriter(f, fieldnames=cols)
        w.writeheader()
        for rec in per_ep_rows:
            for serial, c in rec["cams"].items():
                w.writerow(dict(uuid=rec["uuid"], lab=rec["lab"], robot=rec["robot"], serial=serial, time_offset_ms=rec["time_offset_ms"],
                                old_time_offset_ms=rec["old_time_offset_ms"], sweep_class=rec["sweep_class"], wrist_flipped=rec["wrist_flipped"],
                                prev_time_offset_ms=rec.get("prev_time_offset_ms"), d_time_ms_vs_prev=rec.get("d_time_ms_vs_prev"),
                                **{k: (";".join(c[k]) if isinstance(c[k], list) and k == "causes" else c[k]) for k in cols if k in c}))
    summary["prev_v2_change"] = prev_v2
    json.dump(summary, open(out / "summary.json", "w"), indent=1, default=lambda o: o.tolist() if hasattr(o, "tolist") else str(o))

    # ---- images
    if not args.no_images and not args.no_save_masks:
        mask_root = out / "masks"
        for cam in ("ext", "wrist"):
            make_worst_sheet(worst[cam], out / f"worst12_{cam}.jpg", args.bench_root, mask_root,
                             f"worst 12 {cam} frames by new IoU ({args.round_name}); green = SAM3 GT, red = v2 render, blue = old render")
        make_before_after_grid(rows, infos, out / "before_after_grid.jpg", args.bench_root, mask_root, eps)

    # ---- summary.md
    L = [f"# Benchmark {args.round_name}: v2 chain vs old pipeline on the SAM3 benchmark", "",
         f"Frames scored: {len(rows)} ({len(infos)} episodes); usable (status ok/single/low_conf, GT >= {MIN_GT_PX} px): "
         f"ext {len(subset('ext', held_out=False))}, wrist {len(subset('wrist', held_out=False))}; in_fit (benchmark step used by the v2 fit): "
         f"{summary['n_in_fit']} (+-1: {summary['n_in_fit_pm1']}); in out/gt steps.json pool: {summary['n_in_gt']} (+-1: {summary['n_in_gt_pm1']}); "
         f"not held out: {summary['n_not_held_out']}; old csv rows matched: {summary['old_csv_rows_matched']} (status mismatches {n_status_mismatch}).", "",
         f"Held-out = not in the v2 fit step list AND not in out/gt/<uuid>/steps.json. 'new incl. fit frames' = all usable frames (identical when nothing overlaps)."
         + (f" prev run = {args.prev_csv}." if args.prev_csv else ""), "",
         f"NOTE: {summary['mount_fit_note']}", "",
         "## Overall (held-out frames = not in the v2 fit step list; p10 / p50 / p90 at 1280x720)", ""]
    tab = []
    for cam in ("ext", "wrist"):
        o = summary["overall"][cam]
        t = TARGETS[cam]
        tab.append([cam, "old (metrics.csv)", o["old_csv"]["n"], fmt3(o["old_csv"]["iou_p10_p50_p90"]), fmt3(o["old_csv"]["r2g_p10_p50_p90"], 1), "", ""])
        tab.append([cam, "old re-scored (_rend.png)", o["old_rescored"]["n"], fmt3(o["old_rescored"]["iou_p10_p50_p90"]), fmt3(o["old_rescored"]["r2g_p10_p50_p90"], 1), "", ""])
        tab.append([cam, "**new v2**", o["new"]["n"], fmt3(o["new"]["iou_p10_p50_p90"]), fmt3(o["new"]["r2g_p10_p50_p90"], 1),
                    f">= {fmt3(t['iou'], 2)} / <= {fmt3(t['r2g'], 1)}", "MET" if o["targets_met"] else f"NOT MET {[k for k, v in o['targets_detail'].items() if not v]}"])
        tab.append([cam, "new incl. fit frames", o["new_incl_fit_frames"]["n"], fmt3(o["new_incl_fit_frames"]["iou_p10_p50_p90"]), fmt3(o["new_incl_fit_frames"]["r2g_p10_p50_p90"], 1), "", ""])
        if o.get("prev_run"):
            pm, pd = targets_met(cam, o["prev_run"])
            tab.append([cam, "prev run of the v2 chain (--prev-csv)", o["prev_run"]["n"], fmt3(o["prev_run"]["iou_p10_p50_p90"]), fmt3(o["prev_run"]["r2g_p10_p50_p90"], 1), "",
                        "MET" if pm else f"NOT MET {[k for k, v in pd.items() if not v]}"])
        tab.append([cam, "DIAG new, r2g_near (render edge within 60 px of GT)", o["new_r2g_near"]["n"], fmt3(o["new_r2g_near"]["iou_p10_p50_p90"]), fmt3(o["new_r2g_near"]["r2g_p10_p50_p90"], 1), "", ""])
        tab.append([cam, "DIAG new, GT status ok only", o["new_status_ok_only"]["n"], fmt3(o["new_status_ok_only"]["iou_p10_p50_p90"]), fmt3(o["new_status_ok_only"]["r2g_p10_p50_p90"], 1), "", ""])
        if excl:
            em, ed = o["targets_met_excl_listed_gt_failures"], o["targets_detail_excl_listed_gt_failures"]
            tab.append([cam, f"DIAG new, excl. {o['n_listed_gt_failures']} listed GT-failure frames (--exclude-frames)", o["new_excl_listed_gt_failures"]["n"],
                        fmt3(o["new_excl_listed_gt_failures"]["iou_p10_p50_p90"]), fmt3(o["new_excl_listed_gt_failures"]["r2g_p10_p50_p90"], 1), "",
                        "" if em is None else ("MET" if em else f"NOT MET {[k for k, v in ed.items() if not v]}")])
        tab.append([cam, "DIAG new, excl. occlusion-type frames (IoU>=0.8 & r2g>15)", o["new_excl_occlusion_type"]["n"], fmt3(o["new_excl_occlusion_type"]["iou_p10_p50_p90"]), fmt3(o["new_excl_occlusion_type"]["r2g_p10_p50_p90"], 1), "", ""])
        tab.append([cam, "DIAG new, v2 cam status ok only", o["new_v2_ok_cams_only"]["n"], fmt3(o["new_v2_ok_cams_only"]["iou_p10_p50_p90"]), fmt3(o["new_v2_ok_cams_only"]["r2g_p10_p50_p90"], 1), "", ""])
        tab.append([cam, "new, + render_far_off/missing statuses", o["new_usable_ext_statuses"]["n"], fmt3(o["new_usable_ext_statuses"]["iou_p10_p50_p90"]), fmt3(o["new_usable_ext_statuses"]["r2g_p10_p50_p90"], 1), "", ""])
        tab.append([cam, "H7 free per-frame pose (old geometry)", o["h7_free_pose_bound_old_geometry"]["n"], fmt3(o["h7_free_pose_bound_old_geometry"]["iou_p10_p50_p90"]),
                    fmt3(o["h7_free_pose_bound_old_geometry"]["r2g_p10_p50_p90"], 1), f"noise floor p50 {NOISE_FLOOR[cam]}", ""])
    L.append(md_table(["cam", "variant", "n", "IoU p10/p50/p90", "r2g p10/p50/p90 px", "target", "met"], tab))
    L.append("")
    for cam in ("ext", "wrist"):
        o = summary["overall"][cam]
        L.append(f"- {cam}: frac r2g > 10 px old {o['frac_r2g_gt10_old']} -> new {o['frac_r2g_gt10_new']}; frac frames with IoU improved {o['frac_frames_improved_iou']}; "
                 f"paired median dIoU {o['delta_iou_median_paired']}; frac 'bad' (IoU < p50 target or r2g > p50 target) {o['frac_bad_new']}"
                 + (f"; probes: shift gain p50/p90 {o.get('probe_shift_gain_p50_p90')} (|shift| px {o.get('probe_shift_px_p50_p90')}), time gain p50/p90 {o.get('probe_time_gain_p50_p90')}" if not args.no_probe else "")
                 + (f"; vs prev run: {o['vs_prev']}" if o.get("vs_prev") else ""))
    L += ["", "## Per lab (held-out usable frames; old csv -> new)", ""]
    tab = []
    for lab, d in sorted(summary["per_lab"].items()):
        for cam in ("ext", "wrist"):
            if cam in d:
                tab.append([lab, cam, d[cam]["new"]["n"], fmt3(d[cam]["old_csv"]["iou_p10_p50_p90"]), fmt3(d[cam]["new"]["iou_p10_p50_p90"]),
                            fmt3(d[cam]["old_csv"]["r2g_p10_p50_p90"], 1), fmt3(d[cam]["new"]["r2g_p10_p50_p90"], 1), d[cam]["n_bad_new"],
                            "-" if d[cam].get("n_targets_met") is None else f"{d[cam]['n_targets_met']}/6",
                            fmt3((d[cam].get("prev_run") or {}).get("iou_p10_p50_p90")) + " / " + fmt3((d[cam].get("prev_run") or {}).get("r2g_p10_p50_p90"), 1) if d[cam].get("prev_run") else ""])
    L.append(md_table(["lab", "cam", "n", "IoU old", "IoU new", "r2g old", "r2g new", "n bad", "targets met", "prev run IoU / r2g"], tab))
    L += ["", "## Per robot type / splits", ""]
    tab = []
    for rb, d in summary["per_robot"].items():
        for cam in ("ext", "wrist"):
            tab.append([rb, cam, d[cam]["new"]["n"], fmt3(d[cam]["old_csv"]["iou_p10_p50_p90"]), fmt3(d[cam]["new"]["iou_p10_p50_p90"]),
                        fmt3(d[cam]["old_csv"]["r2g_p10_p50_p90"], 1), fmt3(d[cam]["new"]["r2g_p10_p50_p90"], 1)])
    for cam in ("ext", "wrist"):
        for k, d in summary["splits"][cam].items():
            tab.append([k, cam, d["new"]["n"], fmt3(d["old_csv"]["iou_p10_p50_p90"]), fmt3(d["new"]["iou_p10_p50_p90"]),
                        fmt3(d["old_csv"]["r2g_p10_p50_p90"], 1), fmt3(d["new"]["r2g_p10_p50_p90"], 1)])
    L.append(md_table(["split", "cam", "n", "IoU old", "IoU new", "r2g old", "r2g new"], tab))
    L += ["", "## Per episode / camera (held-out usable frames; p50 old -> new)", ""]
    tab = []
    for rec in per_ep_rows:
        for serial, c in rec["cams"].items():
            tab.append([rec["uuid"], rec["robot"], f"{rec['time_offset_ms']} [{rec['sweep_class']}]" if rec["calib_version"] == 2 else f"NO V2 (v{rec['calib_version']})",
                        serial, c["cam"], c["n"], c["v2_status"], c["v2_source"], c["v2_metric"], c["v2_delta"],
                        f"{c['iou_p50_old']} -> {c['iou_p50_new']}", f"{c['r2g_p50_old']} -> {c['r2g_p50_new']}", c["iou_min_new"], c["r2g_max_new"], c["n_bad"],
                        c["shift_med_px"], "; ".join(c["causes"])[:120],
                        (f"{c.get('iou_p50_prev')} / {c.get('r2g_p50_prev')}; moved {c.get('pose_change_vs_prev')}; was {c.get('prev_v2_status')} {c.get('prev_v2_metric_after')}; dt {rec.get('d_time_ms_vs_prev'):+} ms"
                         if c.get("pose_change_vs_prev") else "")])
    L.append(md_table(["uuid", "robot", "dt ms [class]", "serial", "cam", "n", "v2", "base", "metric b->a", "delta", "IoU p50", "r2g p50", "IoU min", "r2g max", "bad", "shift med px", "causes", "prev run (IoU/r2g p50; pose change; status; dt change)"], tab))
    L += ["", "## Worst 12 frames (new IoU) per camera type", ""]
    for cam in ("ext", "wrist"):
        tab = [[w["uuid"], w["serial"], w["step"], w["status"], f"{w['iou_old']} -> {w['iou_new']}", f"{w['r2g_old']} -> {w['r2g_new']}", w["g"], w["speed"],
                f"{w['shift']} gain {w['shift_gain']}", f"{w['time_d_best']} ms gain {w['time_gain']}", w["v2_status"], w["cause"]] for w in summary["worst12"][cam]]
        L.append(f"### {cam} (worst12_{cam}.jpg)")
        L.append(md_table(["uuid", "serial", "step", "status", "IoU old->new", "r2g old->new", "g", "speed", "best shift", "best time", "v2", "suspected cause"], tab))
        L.append("")
    L += ["## Bad-frame cause histogram (first tag)", "", "```", json.dumps(causes, indent=1), "```", "",
          f"targets_met_all: {summary['targets_met_all']}", ""]
    if args.notes and Path(args.notes).exists():
        L += ["", Path(args.notes).read_text()]
    (out / "summary.md").write_text("\n".join(L))
    log(f"wrote {out / 'metrics.csv'}, per_episode.csv, summary.json, summary.md" + ("" if args.no_images else ", worst12_*.jpg, before_after_grid.jpg"))
    for cam in ("ext", "wrist"):
        o = summary["overall"][cam]
        log(f"{cam}: old {fmt3(o['old_csv']['iou_p10_p50_p90'])} / {fmt3(o['old_csv']['r2g_p10_p50_p90'], 1)} -> new {fmt3(o['new']['iou_p10_p50_p90'])} / "
            f"{fmt3(o['new']['r2g_p10_p50_p90'], 1)} (n {o['new']['n']}) targets_met {o['targets_met']} {o['targets_detail']}")
    return 0


if __name__ == "__main__":
    sys.exit(main())