File size: 62,127 Bytes
0c3dd1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
#!/usr/bin/env python3
"""Per-episode metric extractor for the Case 1 (ART) simulation logs.

Reads every episode directory RUN_DIR/episodes/<episode_id>/ written by the lock-step runner (episode_config.json,
summary.json, ticks.csv.gz, state100.csv.gz; column definitions in runner/schemas/log_schema.md) and writes ONE
compact row per episode:

    OUTDIR/<batch>/recovery_part<k>.csv.gz   fixed_horizon (recovery / TR) episodes
    OUTDIR/<batch>/fullpath_part<k>.csv.gz   path_completion (full-path) episodes
    OUTDIR/<batch>/errors_part<k>.jsonl      episodes that could not be extracted
    OUTDIR/<batch>/MANIFEST.json             inputs, counts, shard SHA256, extractor SHA256

Python >= 3.8 with numpy only. Nothing here reads physical data.

Streaming / multiprocess / resumable: episodes are processed by a worker pool and written in shards of at most
--shard-size rows; each shard appears atomically (tmp + rename). On a rerun the episode ids already present in
complete shards are skipped; if such an episode's summary.json changed (different SHA256), the run is refused
(outputs of different runner outputs are never mixed). Shards are never rewritten.

Metric definitions. All times are measured from control start c0 (runner semantics, t = step * 1e-3 - c0):
  * Primary error: released error_state(0.0) lateral e[1] and heading e[2] of the TRUE COG state on the 100 Hz log
    (state100 e_lat, e_head; recomputed here and checked). Tube cell (L, Hd): |e_lat| < L and |e_head| < Hd.
    Grid L in {0.05, 0.10, 0.20} m x Hd in {0.05, 0.10, 0.20} rad; primary cell 0.10 / 0.10.
  * first entry = t of the first 100 Hz sample with t >= 0 inside the cell.
  * sustained residence D in {0.5, 1.0} s = t of the first sample k such that every sample in [t_k, t_k + D]
    is inside (closed interval: 51 / 101 consecutive 100 Hz samples); the residence must be observed in the log.
  * started_inside = the first sample with t >= 0 is inside.
  * exits after first entry within H = number of inside->outside transitions among samples t_entry <= t <= H.
  * recovery distance to first entry: along-track progress (projection of the COG displacement on the straight
    reference direction) and odometer (sum of 100 Hz COG step lengths), both from the first sample with t >= 0.
  * bounded score at H in {15, 25, 40} s: T = entry if entry (+ D for residence variants) <= H and no controller
    failure (solver failure, exception, non-finite output) happened at or before entry; T = H otherwise if the log
    covers H or ended early by a terminal rule (divergence stop or terminate-on-failure); else censored (empty).
  * Variants: the same cells on the 10 Hz published ticks with the tracking error et1, et2 ("trk10") and
    the controller's 1 m lookahead error e1, e2 ("la10"); released error_state(1.0) of the true 100 Hz COG
    ("la100"); geometric perpendicular distance to the straight line and wrapped yaw error ("geo100", primary
    cell only).
  * Full paths: run MAE with the same definitions as the physical runs (physical/physical_runs.py: nearest
    waypoint, zero lookahead, signed body-frame lateral, wrapped heading) on the pose the controller used at each
    published 10 Hz tick (obs_x, obs_y, obs_theta), window from the first published tick to the completion index
    of the extended-lap forward tracker (track(window 30) + completion_index, one extra lap for closed paths,
    including the Path-3 loop-closure rule and a 100 Hz completion fallback). Evaluation outcome:
    completed / end_departure (no offline completion, max tracked index >= N - 10; window to the first sample at
    the maximum index) / failed (window = all samples); post_completion_departure = offline completed but the
    online runner outcome is not `completed`.

Usage:
    python3 extract_metrics.py --out OUTDIR --batch NAME [--workers N] [--shard-size 2000]
                               [--waypoints-dir DIR ...] [--run-label-root DIR] RUN_DIR [RUN_DIR ...]
    python3 extract_metrics.py --selftest            (synthetic checks of the metric kernels)
"""
import argparse
import glob
import gzip
import hashlib
import io
import json
import math
import multiprocessing as mp
import os
import platform
import sys
import time

import numpy as np

EXTRACTOR_VERSION = 'tr-c1-extract/1'
DT = 1e-3
LAT_GRID = (0.05, 0.10, 0.20)
HEAD_GRID = (0.05, 0.10, 0.20)
PRIMARY_CELL = (0.10, 0.10)
RESIDENCE_S = (0.5, 1.0)
HORIZONS = (15.0, 25.0, 40.0)
DIAG_H = 25.0                      # horizon for behaviour diagnostics and horizon means (primary H)
STEER_REVERSAL_BAND = 0.05         # deadband for steering reversals (command units)
SAT_EPS = 1e-12
EPS_T = 1e-9
CTRL_FAIL = ('controller_solver_failure', 'controller_exception', 'controller_nonfinite_output')
CLOSED_PATHS = {'path_iros_1': True, 'path_iros_2': False, 'lot17_sinsquare': True, 'circ_r2_ccw': True,
                'circ_r2_cw': True, 'circ_r5_ccw': True, 'circ_r5_cw': True, 'straight_line': False}
PATH_KEY = {'path_iros_1': 'P1', 'path_iros_2': 'P2', 'lot17_sinsquare': 'P3'}
SPIN = {'yaw_rate_min': 1.5, 'factor': 2.0, 'r_min': 1.02, 'n_consecutive': 3}   # runner metrics.SPIN_CRITERION
DEFAULT_WAYPOINT_DIRS = ['/sbel/Desktop/waypoints_paths',
                         os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'data', 'waypoints')]


def cell_name(L, H):
    return f'L{int(round(L * 100)):03d}H{int(round(H * 100)):03d}'


CELLS = [(L, H) for L in LAT_GRID for H in HEAD_GRID]
PCELL = cell_name(*PRIMARY_CELL)


def res_name(D):
    return f'sus{int(round(D * 100)):03d}'


# ----------------------------------------------------------------------------------------------- column lists
# episode tags written by runner/batches/generate_lists.py; each becomes a 'tag_<key>' column (any other tag
# stays available in tags_json)
TAG_KEYS = ['batch', 'family', 'condition', 'row', 'rep', 'rf_arm', 'path', 'phase_ms', 'nominal_role',
            'sensitivity', 'repeat', 'placement_index', 'crn_source', 'tuning_family', 'tuning_config_index',
            'reference_name']
ID_COLUMNS = [
    'batch', 'run_dir', 'episode_id', 'scenario_id', 'kind', 'controller', 'ctrl_label', 'base_controller',
    'steering_scale', 'nnhd_gain', 'controller_params_json', 'ref_type', 'ref_name', 'path_key',
    'latency_model', 'controller_period_s', 'controller_phase_s', 'compute_delay_s', 'state_delay_s',
    'control_start_s', 'horizon_s', 'init_x', 'init_y', 'init_yaw', 'init_frame',
    'placement_heading', 'placement_x0', 'placement_y0', 'e_m', 'phi_rad', 'e_geom_m', 'phi_geom_rad',
    'steering_bias', 'actuation_delay_s', 'friction', 'noise_std_x', 'noise_std_y', 'noise_std_yaw', 'noise_seed',
    'tube_lat_m', 'tube_head_rad', 'divergence_dist_m', 'divergence_hold_s', 'stop_on_divergence',
    'on_controller_failure', 'osqp_rho_interval',
] + ['tag_' + k for k in TAG_KEYS] + [
    'tags_json', 'default_config_sha256',
    'config_hash', 'config_hash_ok', 'code_digest', 'host_fingerprint', 'run_id', 'attempt',
    'summary_sha256', 'ticks_sha256', 'state_sha256', 'files_hash_ok', 'reference_sha256', 'ref_sha_ok',
    'status', 'outcome', 'failure_category', 'failure_step', 'failure_t_ctrl', 'final_step', 'sim_s',
    'log_end_t', 'terminal_stop', 'completion_step', 'summary_divergence_step',
    'n_ticks', 'n_published', 'n_rate_limited', 'n_state_rows',
    'n_tick_ok', 'n_tick_no_state', 'n_tick_controller_dead', 'n_tick_solver_failure', 'n_tick_exception',
    'n_tick_nonfinite',
    'wall_total_s', 'wall_init_s', 'wall_stepping_s', 'wall_controller_s', 'wall_other_s',
    'server_spawn_to_ready_s', 'physics_pure_step_wall_s',
    'chassis_touchdown_step', 'first_command_apply_step', 'cog_z_at_first_command_apply', 'first_cmd_airborne',
]

DIAG_COLUMNS = [
    'diag_H', 'e_lat0', 'e_head0', 'first_zero_cross_t', 'overshoot_m', 'overshoot_t', 'n_lat_zero_cross',
    'n_lat_sign_changes_after_entry', 'p2p_lat_last5s', 'max_abs_lat_after_entry', 'max_abs_head_after_entry',
    'lat_at_H', 'head_at_H', 'max_abs_lat_H', 'max_abs_head_H',
    'frac_steer_sat', 'frac_rate_limited', 'n_steer_reversals', 'n_steer_sign_changes_raw',
    'thr_mean', 'thr_sd', 'frac_thr_one', 'frac_thr_zero', 'raw_thr_mean', 'raw_thr_max', 'thr_mean_to_entry',
    'speed_mean_H', 'speed_max_H', 't_speed_09', 'speed_mean_to_entry', 'max_abs_yaw_rate_H',
    'spin_flag', 'spin_first_step', 'spin_n_flagged', 'max_abs_yaw_rate_all',
    'div_flag', 'div_onset_step', 'div_onset_t', 'div_recovered_tube', 'time_beyond_div_dist_s', 'max_dist_min',
]


def recovery_columns():
    cols = []
    for (L, H) in CELLS:
        c = cell_name(L, H)
        cols += [f'trk100_{c}_first', f'trk100_{c}_{res_name(0.5)}', f'trk100_{c}_{res_name(1.0)}',
                 f'trk100_{c}_inside0', f'trk100_{c}_exits_H25', f'trk100_{c}_fracin_H25',
                 f'trk100_{c}_dprog', f'trk100_{c}_dodo',
                 f'trk10_{c}_first', f'la10_{c}_first', f'la100_{c}_first']
        for Hh in HORIZONS:
            cols += [f'T{int(Hh)}_trk100_{c}_first']
    for Hh in HORIZONS:
        for D in RESIDENCE_S:
            cols.append(f'T{int(Hh)}_trk100_{PCELL}_{res_name(D)}')
        cols += [f'T{int(Hh)}_trk10_{PCELL}_first', f'T{int(Hh)}_la10_{PCELL}_first',
                 f'T{int(Hh)}_la100_{PCELL}_first', f'T{int(Hh)}_geo100_{PCELL}_first',
                 f'reason{int(Hh)}_trk100_{PCELL}_first',
                 f'exits_{PCELL}_H{int(Hh)}', f'fracin_{PCELL}_H{int(Hh)}',
                 f'hmean_abs_lat_H{int(Hh)}', f'hmean_abs_head_H{int(Hh)}', f'hmean_complete_H{int(Hh)}']
    cols += [f'geo100_{PCELL}_first', f'geo100_{PCELL}_inside0', f'trk100_{PCELL}_final_stay_t',
             'max_abs_lat_all', 'final_e_lat', 'final_e_head']
    cols += DIAG_COLUMNS
    cols += ['chk_tube_first', 'chk_tube_tick', 'chk_tube_tick_la', 'chk_tube_100hz_la', 'chk_fracin_all',
             'chk_exits_all', 'chk_final_stay', 'chk_max_abs_lat', 'chk_final_e', 'chk_spin', 'chk_divergence',
             'chk_err_recompute_maxdiff', 'ref_index_at_end'] + [f'ref_index_at_end_H{int(Hh)}' for Hh in HORIZONS] + ['chk_all']
    return cols


FULLPATH_COLUMNS_EXTRA = [
    'n_waypoints', 'closed_path', 'ref_length_m', 'eval_outcome', 'online_outcome', 'post_completion_departure',
    'completion_from_100hz_fallback', 'completion_index', 'completion_time_s', 'max_tracked_index',
    'eval_end_index', 'eval_samples', 'mae_lat_m', 'mae_head_rad', 'mae_lat_true_m', 'mae_head_true_rad',
    'max_abs_lat_window_m', 'max_abs_lat_100hz_to_end_m', 'sim_s_to_offline_completion',
    'common_window_end_index', 'mae_lat_common_m', 'mae_head_common_rad',
    'online_mae_lat_m', 'online_mae_head_rad', 'online_mae_samples',
    'fp_frac_steer_sat', 'fp_frac_rate_limited', 'fp_n_steer_reversals', 'fp_thr_mean', 'fp_frac_thr_one',
    'fp_frac_thr_zero', 'fp_raw_thr_mean', 'fp_speed_mean', 'fp_speed_max', 'fp_max_abs_yaw_rate',
    'fp_spin_flag', 'fp_max_dist_min',
    'chk_online_mae', 'chk_spin', 'chk_all',
]


def fullpath_columns():
    return list(FULLPATH_COLUMNS_EXTRA)


# ----------------------------------------------------------------------------------------------- small helpers
def sha256_bytes(b):
    return hashlib.sha256(b).hexdigest()


def sha256_file(p):
    h = hashlib.sha256()
    with open(p, 'rb') as f:
        for blk in iter(lambda: f.read(1 << 20), b''):
            h.update(blk)
    return h.hexdigest()


def read_csv_gz_bytes(raw):
    """Parse a runner CSV (gzip bytes) into {column: numpy array of str}. Empty field = ''."""
    text = gzip.decompress(raw).decode()
    lines = text.split('\n')
    head = lines[0].split(',')
    rows = [l.split(',') for l in lines[1:] if l]
    if rows and any(len(r) != len(head) for r in rows):
        raise ValueError('ragged CSV')
    if not rows:
        return {k: np.array([], dtype=str) for k in head}, 0
    arr = np.array(rows, dtype=object)
    return {k: arr[:, i].astype(str) for i, k in enumerate(head)}, len(rows)


def fcol(d, k):
    a = d[k]
    if a.size == 0:
        return np.zeros(0)
    a = np.where(a == '', 'nan', a)
    return a.astype(float)


def icol(d, k):
    return np.array([int(v) if v != '' else -999999 for v in d[k]], dtype=np.int64)


def wrap(a):
    return np.arctan2(np.sin(a), np.cos(a))


def fnone(v):
    return None if v is None else float(v)


def same_opt(a, b, tol=1e-9):
    """True if both None or |a - b| <= tol."""
    if a is None or b is None:
        return a is None and b is None
    return abs(float(a) - float(b)) <= tol


# ----------------------------------------------------------------- released error state (copy of runner metrics.py)
def wrap_released(theta):
    th = np.array(theta, dtype=float, copy=True)
    for _ in range(64):
        lo = th < -np.pi
        hi = th > np.pi
        if not (lo.any() or hi.any()):
            break
        th[lo] = th[lo] + 2 * np.pi
        th[hi] = th[hi] - 2 * np.pi
    return th


def heading_error_released(ref, act):
    ref = np.asarray(ref, dtype=float)
    act = np.asarray(act, dtype=float)
    out = np.empty(np.broadcast(ref, act).shape)
    same = ((ref > 0) & (act > 0)) | ((ref <= 0) & (act <= 0))
    c2 = (~same) & (ref <= 0) & (act > 0)
    c3 = (~same) & ~c2
    out[same] = (ref - act)[same]
    a2 = np.abs(ref - act) < np.abs(2 * np.pi + ref - act)
    out[c2 & a2] = (-np.abs(act - ref))[c2 & a2]
    out[c2 & ~a2] = np.abs(2 * np.pi + ref - act)[c2 & ~a2]
    a3 = np.abs(ref - act) < np.abs(2 * np.pi - ref + act)
    out[c3 & a3] = np.abs(act - ref)[c3 & a3]
    out[c3 & ~a3] = (-np.abs(2 * np.pi - ref + act))[c3 & ~a3]
    return out


def nearest_index(x, y, theta, ref, lookahead, chunk=2048):
    x = np.atleast_1d(np.asarray(x, dtype=float))
    y = np.atleast_1d(np.asarray(y, dtype=float))
    th = wrap_released(np.atleast_1d(np.asarray(theta, dtype=float)))
    px = x + np.cos(th) * lookahead
    py = y + np.sin(th) * lookahead
    idx = np.empty(len(x), dtype=np.int64)
    for i in range(0, len(x), chunk):
        d = (px[i:i + chunk, None] - ref[None, :, 0]) ** 2 + (py[i:i + chunk, None] - ref[None, :, 1]) ** 2
        idx[i:i + chunk] = d.argmin(axis=1)
    return idx


def error_state_vec(x, y, theta, v, ref, lookahead):
    x = np.atleast_1d(np.asarray(x, dtype=float))
    y = np.atleast_1d(np.asarray(y, dtype=float))
    v = np.atleast_1d(np.asarray(v, dtype=float))
    th = wrap_released(np.atleast_1d(np.asarray(theta, dtype=float)))
    idx = nearest_index(x, y, th, ref, lookahead)
    r = ref[idx]
    err_theta = heading_error_released(r[:, 2], th)
    c, s = np.cos(-th), np.sin(-th)
    dx, dy = r[:, 0] - x, r[:, 1] - y
    e0 = c * dx + (-s) * dy
    e1 = s * dx + c * dy
    return np.column_stack((e0, e1, err_theta, r[:, 3] - v)), idx


def audit_errors(x, y, yaw, ref, chunk=4096):
    """errors() of physical/physical_runs.py with zero lookahead (identical formula), chunked."""
    x, y, yaw = (np.asarray(a, dtype=float) for a in (x, y, yaw))
    idx = np.empty(len(x), dtype=np.int64)
    for i in range(0, len(x), chunk):
        idx[i:i + chunk] = ((x[i:i + chunk, None] - ref[None, :, 0]) ** 2 +
                            (y[i:i + chunk, None] - ref[None, :, 1]) ** 2).argmin(axis=1)
    dx, dy = ref[idx, 0] - x, ref[idx, 1] - y
    lat = -np.sin(yaw) * dx + np.cos(yaw) * dy
    head = wrap(ref[idx, 2] - yaw)
    return lat, head


# --------------------------------------------- full-path window helpers (forward tracker and completion rule)
def track(xy, ref, closed, window=30):
    R = np.vstack([ref[:, :2], ref[:, :2]]) if closed else ref[:, :2]
    idx, out = 0, np.zeros(len(xy), int)
    for k, p in enumerate(xy):
        hi = min(len(R), idx + window + 1)
        idx += int(np.argmin(((R[idx:hi] - p) ** 2).sum(1)))
        out[k] = idx
    return out


def completion_index(xy, tracked, ref):
    n = len(ref)
    d = ref[-1, :2] - ref[-2, :2]
    d = d / np.linalg.norm(d)
    ok = (tracked >= n) | ((tracked >= n - 1) & (((xy - ref[-1, :2]) @ d) >= 0))
    return int(np.argmax(ok)) if ok.any() else None


def ref_progress(xy, tracked, ref, closed):
    R = np.vstack([ref[:, :2], ref[:, :2]]) if closed else ref[:, :2]
    S = np.concatenate([[0], np.cumsum(np.linalg.norm(np.diff(R, axis=0), axis=1))])
    out = np.zeros(len(xy))
    for k, (p, i) in enumerate(zip(xy, tracked)):
        best = (np.inf, S[i])
        for j in (i - 1, i):
            if j < 0 or j + 1 >= len(R):
                continue
            a, b = R[j], R[j + 1]
            L = np.linalg.norm(b - a)
            t = np.clip((p - a) @ (b - a) / L ** 2, 0, 1)
            dd = np.linalg.norm(a + t * (b - a) - p)
            if dd < best[0]:
                best = (dd, S[j] + t * L)
        out[k] = best[1]
    return np.maximum.accumulate(out)


# ----------------------------------------------------------------------------------------------- references
def find_waypoint_file(name, dirs):
    for d in dirs:
        p = os.path.join(d, name + '.csv')
        if os.path.exists(p):
            return p
    raise FileNotFoundError(f'waypoint file {name}.csv not found in {dirs}')


def build_reference(spec, wp_dirs):
    """Copy of runner art_runner/references.build_reference (array part); returns (array, sha256 of array bytes)."""
    kind = spec['type']
    if kind in ('released_csv', 'csv_transformed'):
        with open(find_waypoint_file(spec['name'], wp_dirs)) as f:
            arr = np.loadtxt(f, delimiter=',')
        if kind == 'csv_transformed':
            rot = float(spec.get('rotate', 0.0))
            c, s = np.cos(rot), np.sin(rot)
            out = arr.copy()
            out[:, 0] = c * arr[:, 0] - s * arr[:, 1] + float(spec.get('dx', 0.0))
            out[:, 1] = s * arr[:, 0] + c * arr[:, 1] + float(spec.get('dy', 0.0))
            if rot != 0.0:
                out[:, 2] = wrap(arr[:, 2] + rot)
            arr = out
    elif kind == 'straight':
        x0, y0 = float(spec.get('x0', 0.0)), float(spec.get('y0', 0.0))
        h = float(spec.get('heading', 0.0))
        spacing = float(spec.get('spacing', 0.1))
        s0, s1 = float(spec.get('s_start', -10.0)), float(spec.get('s_end', 60.0))
        n = int(round((s1 - s0) / spacing)) + 1
        s = s0 + spacing * np.arange(n)
        arr = np.column_stack((x0 + s * np.cos(h), y0 + s * np.sin(h),
                               np.full(n, float(wrap(h))), np.full(n, float(spec.get('v_ref', 1.0)))))
    elif kind == 'array':
        arr = np.asarray(spec['points'], dtype=float)
    else:
        raise ValueError(f'unknown reference type {kind}')
    arr = np.asarray(arr, dtype=float)
    return arr, sha256_bytes(np.ascontiguousarray(arr).tobytes())


# ----------------------------------------------------------------------------------------------- metric kernels
def first_index(mask):
    k = np.flatnonzero(mask)
    return int(k[0]) if len(k) else None


def first_sustained_index(inside, n_req):
    """First k with inside[k:k+n_req] all True (n_req consecutive samples), else None."""
    if n_req <= 1:
        return first_index(inside)
    if len(inside) < n_req:
        return None
    c = np.convolve(inside.astype(np.int64), np.ones(n_req, dtype=np.int64), 'valid')
    return first_index(c >= n_req)


def residence_samples(D, dt_log=0.01):
    """Closed-interval residence [t_k, t_k + D] at the 100 Hz log: D / dt + 1 samples."""
    return int(round(D / dt_log)) + 1


def bounded_score(entry, H, fail_t, log_end_t, terminal, dur=0.0):
    """Bounded settling-time score. Returns (value or None if censored, reason).
    A controller failure at or before entry (and before H) scores H: after a failure the runner holds the last
    command (released ChROSDriverInputsHandler behaviour), so a later entry is not credited to the controller.
    Divergence alone does not score H ('diverged, then recovered' scores the first entry before H)."""
    if fail_t is not None and fail_t <= H + EPS_T and (entry is None or fail_t <= entry + EPS_T):
        return float(H), 'controller_failure_before_entry'
    if entry is not None and entry + dur <= H + EPS_T:
        return float(entry), 'success'
    if log_end_t + EPS_T >= H:
        return float(H), 'no_entry'
    if terminal:
        return float(H), 'terminal_stop'
    return None, 'censored'


def spin_events(yaw_rate, speed, yaw_rate_min=1.5, factor=2.0, r_min=1.02, n_consecutive=3):
    """Copy of runner metrics.spin_events."""
    yr = np.abs(np.asarray(yaw_rate, dtype=float))
    sp = np.asarray(speed, dtype=float)
    if len(yr) == 0:
        return None, 0, None
    flag = (yr > yaw_rate_min) & (yr > factor * sp / r_min)
    k0 = None
    if len(flag) >= n_consecutive:
        run = np.convolve(flag.astype(int), np.ones(n_consecutive, dtype=int), 'valid') >= n_consecutive
        k = np.flatnonzero(run)
        k0 = int(k[0]) if len(k) else None
    return k0, int(flag.sum()), float(yr.max())


def divergence(steps, dist_min, dist_m, hold_s):
    """Runner rule (episode.py): dist_min > dist_m continuously for >= hold_s (100 Hz log). Returns onset step of
    the first qualifying excursion (None), total time beyond dist_m (s), max dist_min."""
    hold = int(round(hold_s / DT))
    out = dist_min > dist_m
    onset, since = None, None
    for s, o in zip(steps, out):
        if o:
            since = s if since is None else since
            if s - since >= hold and onset is None:
                onset = since
        else:
            since = None
    return onset, float(out.sum() * 0.01), float(dist_min.max()) if len(dist_min) else None


def sign_changes(x, band=0.0):
    """Number of sign changes of x, ignoring samples with |x| <= band (deadband) and exact zeros."""
    x = np.asarray(x, dtype=float)
    s = np.sign(x[np.abs(x) > band])
    if len(s) < 2:
        return 0
    return int(np.sum(s[1:] != s[:-1]))


# ----------------------------------------------------------------------------------------------- per-episode
def label_from_controller(controller, params):
    if controller in ('mpc', 'nnmpc', 'pid', 'nnhd'):
        return controller
    if controller == 'plugin:wrapped_released':
        b = params.get('base')
        k = params.get('steering_scale', 1.0)
        lab = b if k == 1.0 else f'{b}x{int(round(float(k) * 100)):03d}'
        if params.get('shared_speed'):
            lab += '_shspd'
        return lab
    return controller.replace('plugin:', '')


def episode_identity(cfg, summ, batch, run_dir):
    tags = cfg.get('tags') or {}
    params = cfg.get('controller_params') or {}
    lat = cfg['latency']
    pert = cfg.get('perturbation') or {}
    noise = pert.get('obs_noise') or {}
    term = cfg['termination']
    ref = cfg['reference']
    pl = tags.get('placement') or {}
    controller = cfg['controller']
    base = params.get('base') if controller == 'plugin:wrapped_released' else controller
    scale = float(params.get('steering_scale', 1.0)) if controller == 'plugin:wrapped_released' else 1.0
    nnhd_gain = scale if base == 'nnhd' else None
    prov = summ.get('provenance') or {}
    fail = summ.get('failure') or {}
    c0 = float(cfg.get('control_start_s', 0.0))
    c0_steps = int(round(c0 * 1000))
    # geometric (e, phi) of the chassis start in the reference frame (straight references)
    e_geom = phi_geom = None
    if ref['type'] == 'straight':
        h = float(ref.get('heading', 0.0))
        dx = cfg['initial_pose']['x'] - float(ref.get('x0', 0.0))
        dy = cfg['initial_pose']['y'] - float(ref.get('y0', 0.0))
        e_geom = -math.sin(h) * dx + math.cos(h) * dy
        phi_geom = float(wrap(np.array(cfg['initial_pose']['yaw'] - h)))
    fail_step = fail.get('step') if fail.get('category') in CTRL_FAIL else None
    row = {
        'batch': batch, 'run_dir': run_dir, 'episode_id': cfg['episode_id'], 'scenario_id': cfg.get('scenario_id'),
        'kind': 'recovery' if term['type'] == 'fixed_horizon' else 'fullpath',
        'controller': controller, 'ctrl_label': tags.get('ctrl_label') or label_from_controller(controller, params),
        'base_controller': base, 'steering_scale': scale, 'nnhd_gain': nnhd_gain,
        'controller_params_json': json.dumps(params, sort_keys=True, separators=(',', ':')),
        'ref_type': ref['type'], 'ref_name': ref.get('name', ref['type']),
        'path_key': PATH_KEY.get(ref.get('name'), ref.get('name', ref['type'])),
        'latency_model': lat['model'], 'controller_period_s': lat.get('controller_period_s'),
        'controller_phase_s': lat.get('controller_phase_s'), 'compute_delay_s': lat.get('compute_delay_s'),
        'state_delay_s': lat.get('state_delay_s'), 'control_start_s': c0, 'horizon_s': cfg['horizon_s'],
        'init_x': cfg['initial_pose']['x'], 'init_y': cfg['initial_pose']['y'], 'init_yaw': cfg['initial_pose']['yaw'],
        'init_frame': cfg['initial_pose'].get('frame'),
        'placement_heading': pl.get('heading'), 'placement_x0': pl.get('x0'), 'placement_y0': pl.get('y0'),
        'e_m': tags.get('e_m'), 'phi_rad': tags.get('phi_rad'), 'e_geom_m': e_geom, 'phi_geom_rad': phi_geom,
        'steering_bias': pert.get('steering_bias'), 'actuation_delay_s': pert.get('actuation_delay_s'),
        'friction': pert.get('friction'), 'noise_std_x': noise.get('std_x'), 'noise_std_y': noise.get('std_y'),
        'noise_std_yaw': noise.get('std_yaw'), 'noise_seed': noise.get('seed'),
        'tube_lat_m': term.get('tube_lat_m'), 'tube_head_rad': term.get('tube_head_rad'),
        'divergence_dist_m': term.get('divergence_dist_m'), 'divergence_hold_s': term.get('divergence_hold_s'),
        'stop_on_divergence': term.get('stop_on_divergence'), 'on_controller_failure': cfg.get('on_controller_failure'),
        'osqp_rho_interval': cfg.get('mpc_osqp_adaptive_rho_interval'),
        'tags_json': json.dumps(tags, sort_keys=True, separators=(',', ':')),
        'default_config_sha256': tags.get('default_config_sha256'),
        'config_hash': summ.get('config_hash'),
        'code_digest': prov.get('code_digest'), 'host_fingerprint': prov.get('host_fingerprint'),
        'run_id': prov.get('run_id', summ.get('run_id')),
        'attempt': prov.get('attempt'), 'reference_sha256': summ.get('reference_sha256'),
        'status': summ.get('status'), 'outcome': summ.get('outcome'),
        'failure_category': fail.get('category'), 'failure_step': fail_step,
        'failure_t_ctrl': None if fail_step is None else fail_step * DT - c0_steps * DT,
        'final_step': summ.get('final_step'), 'sim_s': summ.get('sim_s'),
        'completion_step': summ.get('completion_step'), 'summary_divergence_step': summ.get('divergence_step'),
        'n_ticks': summ.get('n_ticks'), 'n_published': summ.get('n_published'),
        'n_rate_limited': summ.get('n_rate_limited'), 'n_state_rows': summ.get('n_state_rows'),
        'server_spawn_to_ready_s': summ.get('server_spawn_to_ready_s'),
        'physics_pure_step_wall_s': summ.get('physics_pure_step_wall_s'),
        'chassis_touchdown_step': summ.get('chassis_touchdown_step'),
        'first_command_apply_step': summ.get('first_command_apply_step'),
        'cog_z_at_first_command_apply': summ.get('cog_z_at_first_command_apply'),
    }
    for k in TAG_KEYS:
        v = tags.get(k)
        row['tag_' + k] = json.dumps(v, sort_keys=True) if isinstance(v, (dict, list)) else v
    w = summ.get('wall') or {}
    for k in ('total_s', 'init_s', 'stepping_s', 'controller_s', 'other_s'):
        row['wall_' + k] = w.get(k)
    if row['chassis_touchdown_step'] is not None and row['first_command_apply_step'] is not None:
        row['first_cmd_airborne'] = int(row['first_command_apply_step'] < row['chassis_touchdown_step'])
    # canonical config hash (runner config.config_hash)
    blob = json.dumps(cfg, sort_keys=True, separators=(',', ':'), allow_nan=False)
    row['config_hash_ok'] = int(hashlib.sha256(blob.encode()).hexdigest() == summ.get('config_hash'))
    return row, c0_steps


def tick_status_counts(tk):
    st = tk['status'] if 'status' in tk else np.array([], dtype=str)
    return {'n_tick_ok': int(np.sum(st == 'ok')), 'n_tick_no_state': int(np.sum(st == 'no_state')),
            'n_tick_controller_dead': int(np.sum(st == 'controller_dead')),
            'n_tick_solver_failure': int(np.sum(st == 'controller_solver_failure')),
            'n_tick_exception': int(np.sum(st == 'controller_exception')),
            'n_tick_nonfinite': int(np.sum(st == 'controller_nonfinite_output'))}


def recovery_metrics(cfg, summ, row, c0_steps, st, tk, ref):
    out = {}
    steps = icol(st, 'step')
    t_all = steps * DT - c0_steps * DT           # identical arithmetic to episode.py (t = step*DT - c0*DT)
    after = t_all >= 0
    t = t_all[after]
    x, y, yaw, speed = (fcol(st, k) for k in ('x', 'y', 'yaw', 'speed'))
    yaw_rate = fcol(st, 'yaw_rate')
    lat_all, head_all = fcol(st, 'e_lat'), fcol(st, 'e_head')
    lat, head = lat_all[after], head_all[after]
    log_end_t = float(t[-1]) if len(t) else 0.0
    out['log_end_t'] = log_end_t
    N_h = int(round(float(cfg['horizon_s']) * 1000))
    final_step = summ.get('final_step') or (int(steps[-1]) if len(steps) else 0)
    stopped_early = final_step < N_h
    terminal = bool(stopped_early and (summ.get('outcome') == 'diverged' or
                                       (summ.get('outcome') in CTRL_FAIL and cfg.get('on_controller_failure') == 'terminate')))
    out['terminal_stop'] = int(terminal)
    fail_t = row['failure_t_ctrl']
    # recompute the zero-lookahead error from the logged true state (check of state100 e_lat / e_head)
    E0, _ = error_state_vec(x, y, yaw, speed, ref, 0.0)
    out['chk_err_recompute_maxdiff'] = float(max(np.max(np.abs(E0[:, 1] - lat_all)), np.max(np.abs(E0[:, 2] - head_all)))) if len(x) else 0.0
    EL, _ = error_state_vec(x[after], y[after], yaw[after], speed[after], ref, 1.0)
    la_lat, la_head = EL[:, 1], EL[:, 2]
    # geometric variant on the straight line
    rs = cfg['reference']
    h = float(rs.get('heading', 0.0)) if rs['type'] == 'straight' else None
    if h is not None:
        ux, uy = math.cos(h), math.sin(h)
        px, py = x[after] - float(rs.get('x0', 0.0)), y[after] - float(rs.get('y0', 0.0))
        g_lat = -uy * px + ux * py
        g_head = wrap(yaw[after] - h)
        s_along = ux * px + uy * py
    else:
        g_lat = g_head = None
        s_along = fcol(st, 'arc_s')[after]
    xa, ya = x[after], y[after]
    odo = np.concatenate([[0.0], np.cumsum(np.hypot(np.diff(xa), np.diff(ya)))]) if len(xa) else np.zeros(0)
    # ticks (published)
    pubm = tk['published'] == '1' if len(tk.get('published', [])) else np.zeros(0, bool)
    tt = fcol(tk, 't_ctrl')[pubm] if pubm.any() else np.zeros(0)
    et1 = fcol(tk, 'et1')[pubm] if pubm.any() else np.zeros(0)
    et2 = fcol(tk, 'et2')[pubm] if pubm.any() else np.zeros(0)
    e1 = fcol(tk, 'e1')[pubm] if pubm.any() else np.zeros(0)
    e2 = fcol(tk, 'e2')[pubm] if pubm.any() else np.zeros(0)

    def entry_t(tv, a, b, L, Hd):
        k = first_index((np.abs(a) < L) & (np.abs(b) < Hd))
        return (float(tv[k]), k) if k is not None else (None, None)

    within = {Hh: t <= Hh + EPS_T for Hh in HORIZONS}
    prim = {}
    for (L, Hd) in CELLS:
        c = cell_name(L, Hd)
        inside = (np.abs(lat) < L) & (np.abs(head) < Hd)
        k = first_index(inside)
        te = float(t[k]) if k is not None else None
        out[f'trk100_{c}_first'] = te
        out[f'trk100_{c}_inside0'] = int(bool(inside[0])) if len(inside) else None
        for D in RESIDENCE_S:
            ks = first_sustained_index(inside, residence_samples(D))
            out[f'trk100_{c}_{res_name(D)}'] = float(t[ks]) if ks is not None else None
        if k is not None:
            w = within[25.0]
            seg = inside[k:][w[k:]]
            out[f'trk100_{c}_exits_H25'] = int(np.sum(np.diff(seg.astype(int)) == -1)) if len(seg) else None
            out[f'trk100_{c}_fracin_H25'] = float(seg.mean()) if len(seg) else None
            out[f'trk100_{c}_dprog'] = float(s_along[k] - s_along[0])
            out[f'trk100_{c}_dodo'] = float(odo[k])
        else:
            for kk in ('exits_H25', 'fracin_H25', 'dprog', 'dodo'):
                out[f'trk100_{c}_{kk}'] = None
        out[f'trk10_{c}_first'] = entry_t(tt, et1, et2, L, Hd)[0]
        out[f'la10_{c}_first'] = entry_t(tt, e1, e2, L, Hd)[0]
        out[f'la100_{c}_first'] = entry_t(t, la_lat, la_head, L, Hd)[0]
        for Hh in HORIZONS:
            out[f'T{int(Hh)}_trk100_{c}_first'] = bounded_score(te, Hh, fail_t, log_end_t, terminal)[0]
        if (L, Hd) == PRIMARY_CELL:
            prim = {'inside': inside, 'k': k, 'te': te}
    pc = PCELL
    Lp, Hp = PRIMARY_CELL
    if g_lat is not None:
        gin = (np.abs(g_lat) < Lp) & (np.abs(g_head) < Hp)
        kg = first_index(gin)
        out[f'geo100_{pc}_first'] = float(t[kg]) if kg is not None else None
        out[f'geo100_{pc}_inside0'] = int(bool(gin[0])) if len(gin) else None
    else:
        out[f'geo100_{pc}_first'] = out[f'geo100_{pc}_inside0'] = None
    for Hh in HORIZONS:
        hh = int(Hh)
        for D in RESIDENCE_S:
            out[f'T{hh}_trk100_{pc}_{res_name(D)}'] = bounded_score(out[f'trk100_{pc}_{res_name(D)}'], Hh, fail_t,
                                                                    log_end_t, terminal, dur=D)[0]
        for dfn in ('trk10', 'la10', 'la100', 'geo100'):
            out[f'T{hh}_{dfn}_{pc}_first'] = bounded_score(out[f'{dfn}_{pc}_first'], Hh, fail_t, log_end_t, terminal)[0]
        out[f'reason{hh}_trk100_{pc}_first'] = bounded_score(prim['te'], Hh, fail_t, log_end_t, terminal)[1]
        w = within[Hh]
        k = prim['k']
        if k is not None:
            seg = prim['inside'][k:][w[k:]]
            out[f'exits_{pc}_H{hh}'] = int(np.sum(np.diff(seg.astype(int)) == -1)) if len(seg) else None
            out[f'fracin_{pc}_H{hh}'] = float(seg.mean()) if len(seg) else None
        else:
            out[f'exits_{pc}_H{hh}'] = out[f'fracin_{pc}_H{hh}'] = None
        out[f'hmean_abs_lat_H{hh}'] = float(np.abs(lat[w]).mean()) if w.any() else None
        out[f'hmean_abs_head_H{hh}'] = float(np.abs(head[w]).mean()) if w.any() else None
        out[f'hmean_complete_H{hh}'] = int(log_end_t + EPS_T >= Hh)
    # final stay (summary stay_in_tube_time_100hz_s, full log)
    ins = prim['inside']
    if prim['k'] is not None and ins[-1]:
        outside = np.flatnonzero(~ins)
        out[f'trk100_{pc}_final_stay_t'] = float(t[outside[-1] + 1]) if len(outside) else float(t[0])
    else:
        out[f'trk100_{pc}_final_stay_t'] = None
    out['max_abs_lat_all'] = float(np.abs(lat_all).max()) if len(lat_all) else None
    out['final_e_lat'] = float(lat_all[-1]) if len(lat_all) else None
    out['final_e_head'] = float(head_all[-1]) if len(head_all) else None

    # ------------------------------------------------------------- behaviour diagnostics, within DIAG_H
    wH = within[DIAG_H]
    out['diag_H'] = DIAG_H
    latH, headH, tH = lat[wH], head[wH], t[wH]
    out['e_lat0'] = float(lat[0]) if len(lat) else None
    out['e_head0'] = float(head[0]) if len(head) else None
    s0 = np.sign(lat[0]) if len(lat) else 0.0
    kz = first_index(latH * s0 <= 0) if s0 != 0 else None
    if kz is not None:
        seg = -s0 * latH[kz:]
        kk = int(np.argmax(seg))
        out['first_zero_cross_t'], out['overshoot_m'], out['overshoot_t'] = float(tH[kz]), float(max(seg[kk], 0.0)), float(tH[kz + kk])
    else:
        out['first_zero_cross_t'], out['overshoot_m'], out['overshoot_t'] = None, 0.0, None
    out['n_lat_zero_cross'] = sign_changes(latH)
    kp = prim['k']
    if kp is not None and kp < len(latH):
        out['n_lat_sign_changes_after_entry'] = sign_changes(latH[kp:])
        out['max_abs_lat_after_entry'] = float(np.abs(latH[kp:]).max())
        out['max_abs_head_after_entry'] = float(np.abs(headH[kp:]).max())
    else:
        out['n_lat_sign_changes_after_entry'] = out['max_abs_lat_after_entry'] = out['max_abs_head_after_entry'] = None
    last5 = tH >= DIAG_H - 5.0 - EPS_T
    out['p2p_lat_last5s'] = float(latH[last5].max() - latH[last5].min()) if last5.any() and log_end_t + EPS_T >= DIAG_H else None
    out['lat_at_H'] = float(latH[-1]) if len(latH) else None
    out['head_at_H'] = float(headH[-1]) if len(headH) else None
    out['max_abs_lat_H'] = float(np.abs(latH).max()) if len(latH) else None
    out['max_abs_head_H'] = float(np.abs(headH).max()) if len(headH) else None
    # commands on published ticks within DIAG_H
    if pubm.any():
        wt = tt <= DIAG_H + EPS_T
        ps = fcol(tk, 'pub_steering')[pubm][wt]
        pt = fcol(tk, 'pub_throttle')[pubm][wt]
        rt = fcol(tk, 'raw_throttle')[pubm][wt]
        rl = fcol(tk, 'rate_limited')[pubm][wt]
        out['frac_steer_sat'] = float(np.mean(np.abs(ps) >= 1 - SAT_EPS)) if len(ps) else None
        out['frac_rate_limited'] = float(np.mean(rl == 1)) if len(rl) else None
        out['n_steer_reversals'] = sign_changes(ps, STEER_REVERSAL_BAND)
        out['n_steer_sign_changes_raw'] = sign_changes(ps)
        out['thr_mean'] = float(pt.mean()) if len(pt) else None
        out['thr_sd'] = float(pt.std()) if len(pt) else None
        out['frac_thr_one'] = float(np.mean(pt >= 1 - SAT_EPS)) if len(pt) else None
        out['frac_thr_zero'] = float(np.mean(pt <= SAT_EPS)) if len(pt) else None
        out['raw_thr_mean'] = float(np.nanmean(rt)) if len(rt) else None
        out['raw_thr_max'] = float(np.nanmax(rt)) if len(rt) else None
        te = prim['te']
        pre = tt[wt] <= (te if te is not None else DIAG_H) + EPS_T
        out['thr_mean_to_entry'] = float(pt[pre].mean()) if pre.any() else None
    spH = speed[after][wH]
    out['speed_mean_H'] = float(spH.mean()) if len(spH) else None
    out['speed_max_H'] = float(spH.max()) if len(spH) else None
    k9 = first_index(speed[after] >= 0.9)
    out['t_speed_09'] = float(t[k9]) if k9 is not None else None
    if prim['k'] is not None:
        out['speed_mean_to_entry'] = float(speed[after][:prim['k'] + 1].mean())
    out['max_abs_yaw_rate_H'] = float(np.abs(yaw_rate[after][wH]).max()) if wH.any() else None
    k0, nflag, yrmax = spin_events(yaw_rate, speed, **SPIN)
    out['spin_flag'] = int(k0 is not None)
    out['spin_first_step'] = int(steps[k0]) if k0 is not None else None
    out['spin_n_flagged'] = nflag
    out['max_abs_yaw_rate_all'] = yrmax
    term = cfg['termination']
    dmin = fcol(st, 'dist_min')
    onset, beyond, dmax = divergence(steps, dmin, term['divergence_dist_m'], term['divergence_hold_s'])
    out['div_flag'] = int(onset is not None)
    out['div_onset_step'] = onset
    out['div_onset_t'] = None if onset is None else onset * DT - c0_steps * DT
    out['div_recovered_tube'] = (int(prim['te'] is not None and prim['te'] > out['div_onset_t'])
                                 if onset is not None else None)
    out['time_beyond_div_dist_s'] = beyond
    out['max_dist_min'] = dmax

    # ------------------------------------------------------------- checks against the runner summary
    chk = {}
    chk['chk_tube_first'] = same_opt(out[f'trk100_{cell_name(term["tube_lat_m"], term["tube_head_rad"])}_first'],
                                     summ.get('tube_entry_time_100hz_s'), 0.0) if (term['tube_lat_m'], term['tube_head_rad']) in CELLS else True
    chk['chk_tube_tick'] = same_opt(out[f'trk10_{pc}_first'], summ.get('tube_entry_time_tick_s'), 0.0)
    if 'tube_entry_time_tick_lookahead_s' in summ:
        chk['chk_tube_tick_la'] = same_opt(out[f'la10_{pc}_first'], summ.get('tube_entry_time_tick_lookahead_s'), 0.0)
        chk['chk_tube_100hz_la'] = same_opt(out[f'la100_{pc}_first'], summ.get('tube_entry_time_100hz_lookahead_s'), 0.0)
    if prim['k'] is not None and 'fraction_inside_tube_after_entry' in summ:
        ins = prim['inside']
        chk['chk_fracin_all'] = abs(float(ins[prim['k']:].mean()) - summ['fraction_inside_tube_after_entry']) <= 1e-12
        chk['chk_exits_all'] = int(np.sum(np.diff(ins[prim['k']:].astype(int)) == -1)) == summ['tube_exits_after_entry']
        chk['chk_final_stay'] = same_opt(out[f'trk100_{pc}_final_stay_t'], summ.get('stay_in_tube_time_100hz_s'), 0.0)
    chk['chk_max_abs_lat'] = same_opt(out['max_abs_lat_all'], summ.get('max_abs_lat_100hz_m'), 0.0)
    chk['chk_final_e'] = same_opt(out['final_e_lat'], summ.get('final_e_lat_m'), 0.0) and \
        same_opt(out['final_e_head'], summ.get('final_e_head_rad'), 0.0)
    if 'spin_flag' in summ:
        chk['chk_spin'] = (bool(out['spin_flag']) == bool(summ['spin_flag']) and
                           out['spin_first_step'] == summ.get('spin_first_step') and
                           same_opt(out['max_abs_yaw_rate_all'], summ.get('max_abs_yaw_rate_100hz'), 0.0))
    if summ.get('divergence_step') is not None:
        chk['chk_divergence'] = out['div_onset_step'] == summ['divergence_step']
    chk['chk_err_recompute'] = out['chk_err_recompute_maxdiff'] <= 1e-9
    # guard: a nearest-waypoint index at either end of the straight reference is a design error
    nref = len(ref)
    ends = [icol(st, 'nearest_idx')] if 'nearest_idx' in st else []
    if pubm.any():
        ends += [icol(tk, k)[pubm] for k in ('idx_lookahead', 'idx_track') if k in tk]
    out['ref_index_at_end'] = int(any(np.any((v == 0) | (v == nref - 1)) for v in ends if len(v)))
    # the same guard evaluated on [0, c0 + H] of the episode (t_ctrl <= H) for every analysed horizon H, so a
    # truncation after c0 + H cannot remove a scenario from the H analysis. The whole-log flag above is kept.
    t_ends = ([t_all] if 'nearest_idx' in st else []) + \
        ([tt for k in ('idx_lookahead', 'idx_track') if k in tk] if pubm.any() else [])
    for Hh in HORIZONS:
        out[f'ref_index_at_end_H{int(Hh)}'] = int(any(np.any(((v == 0) | (v == nref - 1)) & (tv <= Hh + EPS_T))
                                                      for v, tv in zip(ends, t_ends) if len(v)))
    for k, v in chk.items():
        if k != 'chk_err_recompute':
            out[k] = int(bool(v))
    out['chk_all'] = int(all(bool(v) for v in chk.values()))
    return out


def fullpath_metrics(cfg, summ, row, c0_steps, st, tk, ref):
    out = {}
    name = cfg['reference'].get('name')
    closed = CLOSED_PATHS.get(name, False)
    n = len(ref)
    out['n_waypoints'], out['closed_path'] = n, int(closed)
    out['ref_length_m'] = float(np.linalg.norm(np.diff(ref[:, :2], axis=0), axis=1).sum())
    out['online_outcome'] = summ.get('outcome')
    pubm = tk['published'] == '1'
    x, y, yaw = fcol(tk, 'obs_x')[pubm], fcol(tk, 'obs_y')[pubm], fcol(tk, 'obs_theta')[pubm]
    xt, yt, yawt = fcol(tk, 'x')[pubm], fcol(tk, 'y')[pubm], fcol(tk, 'yaw')[pubm]
    tstep = icol(tk, 'step')[pubm]
    t = tstep * 1e-3
    steps100 = icol(st, 'step')
    out['log_end_t'] = float(steps100[-1] * DT - c0_steps * DT) if len(steps100) else 0.0
    out['terminal_stop'] = 0
    if len(x) == 0:
        out['eval_outcome'] = 'failed'
        out['chk_all'] = 0
        return out
    xy = np.column_stack([x, y])
    tr = track(xy, ref, closed)
    ci = completion_index(xy, tr, ref)
    lat, head = audit_errors(x, y, yaw, ref)
    latT, headT = audit_errors(xt, yt, yawt, ref)
    out['max_tracked_index'] = int(tr.max())
    fallback = False
    if ci is not None:
        end, outcome = ci + 1, 'completed'
        out['completion_time_s'] = float(t[ci] - t[0])
        out['sim_s_to_offline_completion'] = float(t[ci])
    elif summ.get('outcome') == 'completed' and summ.get('completion_step') is not None:
        # compare_calibration.py: the runner stops at its 100 Hz completion step (margin 0), so the last tick can lie
        # just before the final waypoint; the window is then all published ticks.
        end, outcome, fallback = len(x), 'completed', True
        out['completion_time_s'] = float(summ['completion_step'] * 1e-3 - t[0])
        out['sim_s_to_offline_completion'] = float(summ['completion_step'] * 1e-3)
    elif tr.max() >= n - 10:
        end, outcome = int(np.flatnonzero(tr == tr.max())[0]) + 1, 'end_departure'
    else:
        end, outcome = len(x), 'failed'
    out['eval_outcome'] = outcome
    out['completion_from_100hz_fallback'] = int(fallback)
    out['completion_index'] = ci
    out['post_completion_departure'] = int(outcome == 'completed' and not fallback and summ.get('outcome') != 'completed')
    out['eval_end_index'], out['eval_samples'] = end, end
    out['mae_lat_m'] = float(np.abs(lat[:end]).mean())
    out['mae_head_rad'] = float(np.abs(head[:end]).mean())
    out['mae_lat_true_m'] = float(np.abs(latT[:end]).mean())
    out['mae_head_true_rad'] = float(np.abs(headT[:end]).mean())
    out['max_abs_lat_window_m'] = float(np.abs(lat[:end]).max())
    end_step = int(tstep[end - 1])
    e100 = fcol(st, 'e_lat')
    out['max_abs_lat_100hz_to_end_m'] = float(np.abs(e100[steps100 <= end_step]).max()) if len(e100) else None
    # common window [0, L - 2 m] of reference arc length (sensitivity)
    s = ref_progress(xy[:end], tr[:end], ref, closed)
    kc = first_index(s >= out['ref_length_m'] - 2.0)
    endc = kc if kc is not None else end
    endc = max(endc, 1)
    out['common_window_end_index'] = endc
    out['mae_lat_common_m'] = float(np.abs(lat[:endc]).mean())
    out['mae_head_common_rad'] = float(np.abs(head[:endc]).mean())
    # online window (runner summary.run_mae_*): published ticks with step <= completion_step (or the last tick)
    tk_steps = icol(tk, 'step')
    end_online = summ.get('completion_step') or (int(tk_steps[-1]) if len(tk_steps) else 0)
    on = tstep <= end_online
    if on.any():
        out['online_mae_lat_m'] = float(np.abs(lat[on]).mean())
        out['online_mae_head_rad'] = float(np.abs(head[on]).mean())
        out['online_mae_samples'] = int(on.sum())
    # behaviour diagnostics on the evaluation window
    ps = fcol(tk, 'pub_steering')[pubm][:end]
    pt = fcol(tk, 'pub_throttle')[pubm][:end]
    rt = fcol(tk, 'raw_throttle')[pubm][:end]
    rl = fcol(tk, 'rate_limited')[pubm][:end]
    sp = fcol(tk, 'speed')[pubm][:end]
    out['fp_frac_steer_sat'] = float(np.mean(np.abs(ps) >= 1 - SAT_EPS))
    out['fp_frac_rate_limited'] = float(np.mean(rl == 1))
    out['fp_n_steer_reversals'] = sign_changes(ps, STEER_REVERSAL_BAND)
    out['fp_thr_mean'] = float(pt.mean())
    out['fp_frac_thr_one'] = float(np.mean(pt >= 1 - SAT_EPS))
    out['fp_frac_thr_zero'] = float(np.mean(pt <= SAT_EPS))
    out['fp_raw_thr_mean'] = float(np.nanmean(rt))
    out['fp_speed_mean'] = float(sp.mean())
    out['fp_speed_max'] = float(sp.max())
    w100 = steps100 <= end_step
    yr = fcol(st, 'yaw_rate')
    sp100 = fcol(st, 'speed')
    out['fp_max_abs_yaw_rate'] = float(np.abs(yr[w100]).max()) if w100.any() else None
    k0, _, yrmax = spin_events(yr, sp100, **SPIN)
    out['fp_spin_flag'] = int(k0 is not None)
    dmin = fcol(st, 'dist_min')
    out['fp_max_dist_min'] = float(dmin.max()) if len(dmin) else None
    chk = {'chk_online_mae': same_opt(out.get('online_mae_lat_m'), summ.get('run_mae_lateral_m'), 1e-15) and
           same_opt(out.get('online_mae_head_rad'), summ.get('run_mae_heading_rad'), 1e-15)}
    if 'spin_flag' in summ:
        chk['chk_spin'] = bool(out['fp_spin_flag']) == bool(summ['spin_flag']) and \
            same_opt(yrmax, summ.get('max_abs_yaw_rate_100hz'), 0.0)
    for k, v in chk.items():
        out[k] = int(bool(v))
    out['chk_all'] = int(all(chk.values()))
    return out


def extract_episode(task):
    """task = (episode_dir, batch, run_dir_label, wp_dirs). Returns (kind, row) or ('error', {...})."""
    ep_dir, batch, run_label, wp_dirs = task
    try:
        with open(os.path.join(ep_dir, 'summary.json'), 'rb') as f:
            sraw = f.read()
        summ = json.loads(sraw)
        with open(os.path.join(ep_dir, 'episode_config.json')) as f:
            cfg = json.load(f)
        if summ.get('status') != 'ok':
            return 'error', {'episode_dir': ep_dir, 'error': f"status {summ.get('status')} in episodes/"}
        row, c0_steps = episode_identity(cfg, summ, batch, run_label)
        row['summary_sha256'] = sha256_bytes(sraw)
        with open(os.path.join(ep_dir, 'ticks.csv.gz'), 'rb') as f:
            traw = f.read()
        with open(os.path.join(ep_dir, 'state100.csv.gz'), 'rb') as f:
            sraw100 = f.read()
        row['ticks_sha256'], row['state_sha256'] = sha256_bytes(traw), sha256_bytes(sraw100)
        files = summ.get('files') or {}
        row['files_hash_ok'] = int(files.get('ticks.csv.gz') == row['ticks_sha256'] and
                                   files.get('state100.csv.gz') == row['state_sha256'])
        tk, _ = read_csv_gz_bytes(traw)
        st, _ = read_csv_gz_bytes(sraw100)
        ref, ref_sha = build_reference(cfg['reference'], wp_dirs)
        row['ref_sha_ok'] = int(ref_sha == summ.get('reference_sha256'))
        row.update(tick_status_counts(tk))
        if row['kind'] == 'recovery':
            row.update(recovery_metrics(cfg, summ, row, c0_steps, st, tk, ref))
        else:
            row.update(fullpath_metrics(cfg, summ, row, c0_steps, st, tk, ref))
        row['chk_all'] = int(bool(row.get('chk_all', 0)) and row['files_hash_ok'] == 1 and row['ref_sha_ok'] == 1
                             and row['config_hash_ok'] == 1)
        return row['kind'], row
    except Exception as e:  # noqa: BLE001 - recorded, never silently dropped
        import traceback
        return 'error', {'episode_dir': ep_dir, 'error': f'{type(e).__name__}: {e}', 'traceback': traceback.format_exc()[-3000:]}


# ----------------------------------------------------------------------------------------------- writing
def fmt(v):
    if v is None:
        return ''
    if isinstance(v, (bool, np.bool_)):
        return '1' if v else '0'
    if isinstance(v, (int, np.integer)):
        return str(int(v))
    if isinstance(v, (float, np.floating)):
        v = float(v)
        if math.isnan(v):
            return ''
        return repr(v)
    s = str(v)
    if any(ch in s for ch in ',"\n'):
        s = '"' + s.replace('"', '""') + '"'
    return s


def write_shard(path, columns, rows):
    unknown = sorted({k for r in rows for k in r} - set(columns))
    if unknown:
        raise RuntimeError(f'extractor bug: keys not in the column list: {unknown[:10]}')
    buf = io.StringIO()
    buf.write(','.join(columns) + '\n')
    for r in rows:
        buf.write(','.join(fmt(r.get(c)) for c in columns) + '\n')
    tmp = path + f'.tmp{os.getpid()}'
    data = buf.getvalue().encode()
    with open(tmp, 'wb') as raw:
        with gzip.GzipFile(fileobj=raw, mode='wb', mtime=0, compresslevel=6) as gz:
            gz.write(data)
    os.replace(tmp, path)
    return sha256_file(path), sha256_bytes(data)


def write_errors(path, rows):
    tmp = path + f'.tmp{os.getpid()}'
    with open(tmp, 'w') as f:
        for r in rows:
            f.write(json.dumps(r, sort_keys=True) + '\n')
    os.replace(tmp, path)
    return sha256_file(path)


def split_csv_line(line):
    """Minimal CSV split supporting the quoted fields written by fmt()."""
    out, cur, q, i = [], [], False, 0
    while i < len(line):
        ch = line[i]
        if q:
            if ch == '"':
                if i + 1 < len(line) and line[i + 1] == '"':
                    cur.append('"')
                    i += 1
                else:
                    q = False
            else:
                cur.append(ch)
        elif ch == '"':
            q = True
        elif ch == ',':
            out.append(''.join(cur))
            cur = []
        else:
            cur.append(ch)
        i += 1
    out.append(''.join(cur))
    return out


def existing_ids(batch_dir):
    """episode key -> summary_sha256 from complete shards (resume)."""
    done = {}
    for p in sorted(glob.glob(os.path.join(batch_dir, '*_part*.csv.gz'))):
        with gzip.open(p, 'rt') as f:
            head = split_csv_line(f.readline().rstrip('\n'))
            i_run, i_ep, i_sha = head.index('run_dir'), head.index('episode_id'), head.index('summary_sha256')
            for line in f:
                v = split_csv_line(line.rstrip('\n'))
                done[(v[i_run], v[i_ep])] = v[i_sha]
    return done


def next_part(batch_dir):
    ks = [int(os.path.basename(p).split('_part')[1].split('.')[0])
          for p in glob.glob(os.path.join(batch_dir, '*_part*.*')) if '_part' in p and '.tmp' not in p]
    return max(ks) + 1 if ks else 0


def run_level_info(run_dir):
    info = {'run_dir': run_dir, 'manifests': [], 'host_timing': None,
            'n_infrastructure_error_dirs': 0, 'infrastructure_error_dirs': []}
    for m in sorted(glob.glob(os.path.join(run_dir, 'manifest_*.json'))):
        try:
            d = json.load(open(m))
        except Exception as e:  # noqa: BLE001
            info['manifests'].append({'file': m, 'error': str(e)})
            continue
        info['manifests'].append({'file': os.path.basename(m), 'sha256': sha256_file(m), 'run_id': d.get('run_id'),
                                  'status': d.get('status'), 'exit_code': d.get('exit_code'),
                                  'workers': d.get('workers'), 'wall_s': d.get('wall_s'),
                                  'n_scheduled': d.get('n_scheduled'), 'n_skipped_existing': d.get('n_skipped_existing'),
                                  'counts': d.get('counts'), 'started_utc': d.get('started_utc'),
                                  'finished_utc': d.get('finished_utc'),
                                  'infrastructure_exhausted': d.get('infrastructure_exhausted'),
                                  'n_infrastructure_events': len(d.get('infrastructure_events') or []),
                                  'code_digest': (d.get('provenance') or {}).get('code_digest'),
                                  'host_fingerprint': (d.get('provenance') or {}).get('host_fingerprint'),
                                  'per_episode_wall_total_s_sum': float(sum((e.get('wall') or {}).get('total_s', 0.0) or 0.0
                                                                            for e in d.get('per_episode_wall') or []))})
    ht = os.path.join(run_dir, 'host_timing.json')
    if os.path.exists(ht):
        info['host_timing'] = json.load(open(ht))
        info['host_timing_sha256'] = sha256_file(ht)
    errs = sorted(glob.glob(os.path.join(run_dir, 'infrastructure_errors', '*')))
    info['n_infrastructure_error_dirs'] = len(errs)
    info['infrastructure_error_dirs'] = [os.path.basename(e) for e in errs]
    return info


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument('--out', help='output root')
    ap.add_argument('--batch', help='batch name (sub-directory of --out)')
    ap.add_argument('--workers', type=int, default=max(1, min(8, (os.cpu_count() or 2) - 2)))
    ap.add_argument('--shard-size', type=int, default=2000)
    ap.add_argument('--waypoints-dir', action='append', default=[])
    ap.add_argument('--run-label-root', default=None,
                    help='run_dir values are written relative to this directory (default: absolute paths)')
    ap.add_argument('--limit', type=int, default=None, help='extract at most K new episodes (testing)')
    ap.add_argument('--selftest', action='store_true')
    ap.add_argument('run_dirs', nargs='*')
    a = ap.parse_args(argv)
    if a.selftest:
        return selftest()
    if not (a.out and a.batch and a.run_dirs):
        ap.error('--out, --batch and at least one RUN_DIR are required')
    wp_dirs = a.waypoints_dir + DEFAULT_WAYPOINT_DIRS
    bdir = os.path.join(a.out, a.batch)
    os.makedirs(bdir, exist_ok=True)
    done = existing_ids(bdir)
    tasks, refused = [], []
    for rd in a.run_dirs:
        rd = os.path.abspath(rd)
        label = os.path.relpath(rd, a.run_label_root) if a.run_label_root else rd
        for sp in sorted(glob.glob(os.path.join(rd, 'episodes', '*', 'summary.json'))):
            ep = os.path.dirname(sp)
            eid = os.path.basename(ep)
            if eid.startswith('.tmp_'):
                continue
            key = (label, eid)
            if key in done:
                if sha256_file(sp) != done[key]:
                    refused.append(ep)
                continue
            tasks.append((ep, a.batch, label, wp_dirs))
    if refused:
        print(f'REFUSED: {len(refused)} already extracted episodes have a changed summary.json (e.g. {refused[0]}); '
              'use a new batch directory', file=sys.stderr)
        return 2
    if a.limit is not None:
        tasks = tasks[:a.limit]
    t0 = time.time()
    part = next_part(bdir)
    buffers = {'recovery': [], 'fullpath': [], 'error': []}
    cols = {'recovery': ID_COLUMNS + recovery_columns(), 'fullpath': ID_COLUMNS + fullpath_columns()}
    written = []

    def flush(kind, force=False):
        nonlocal part
        rows = buffers[kind]
        if not rows or (len(rows) < a.shard_size and not force):
            return
        if kind == 'error':
            p = os.path.join(bdir, f'errors_part{part:04d}.jsonl')
            h, hc = write_errors(p, rows), None
        else:
            p = os.path.join(bdir, f'{kind}_part{part:04d}.csv.gz')
            h, hc = write_shard(p, cols[kind], sorted(rows, key=lambda r: (r['run_dir'], r['episode_id'])))
        written.append({'file': os.path.basename(p), 'sha256': h, 'content_sha256': hc, 'rows': len(rows)})
        part += 1
        buffers[kind] = []

    n_done = 0
    if tasks:
        ctx = mp.get_context('fork') if hasattr(os, 'fork') else mp.get_context()
        with ctx.Pool(a.workers) as pool:
            for kind, row in pool.imap_unordered(extract_episode, tasks, chunksize=4):
                buffers[kind].append(row)
                n_done += 1
                flush(kind)
                if n_done % 500 == 0:
                    print(f'{n_done}/{len(tasks)} episodes, {time.time() - t0:.0f} s', flush=True)
    for k in ('recovery', 'fullpath', 'error'):
        flush(k, force=True)
    # manifest (rewritten; lists every shard present)
    shards = []
    for p in sorted(glob.glob(os.path.join(bdir, '*_part*.*'))):
        if '.tmp' in p:
            continue
        rec_ = {'file': os.path.basename(p), 'sha256': sha256_file(p)}
        if p.endswith('.csv.gz'):
            with gzip.open(p, 'rb') as fh:
                rec_['content_sha256'] = sha256_bytes(fh.read())   # gzip bytes depend on the zlib build; content does not
        shards.append(rec_)
    man_path = os.path.join(bdir, 'MANIFEST.json')
    old = json.load(open(man_path)) if os.path.exists(man_path) else {}
    invocations = old.get('invocations', [])
    invocations.append({'utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), 'argv': sys.argv,
                        'n_new_episodes': n_done, 'written': written, 'wall_s': time.time() - t0,
                        'workers': a.workers})
    n_err = sum(1 for s in shards if s['file'].startswith('errors_'))
    manifest = {
        'extractor': EXTRACTOR_VERSION, 'extractor_sha256': sha256_file(os.path.abspath(__file__)),
        'python': sys.version, 'numpy': np.__version__, 'platform': platform.platform(),
        'batch': a.batch, 'run_dirs': [os.path.abspath(r) for r in a.run_dirs],
        'run_level': [run_level_info(os.path.abspath(r)) for r in a.run_dirs],
        'waypoint_dirs': wp_dirs, 'shards': shards, 'n_error_shards': n_err, 'invocations': invocations,
        'definitions': {'lat_grid_m': LAT_GRID, 'head_grid_rad': HEAD_GRID, 'primary_cell': PRIMARY_CELL,
                        'residence_s': RESIDENCE_S, 'residence_rule': 'closed interval [t_k, t_k + D], D/0.01 + 1 samples',
                        'horizons_s': HORIZONS, 'diag_H_s': DIAG_H, 'steer_reversal_band': STEER_REVERSAL_BAND,
                        'spin': SPIN},
    }
    with open(man_path + '.tmp', 'w') as f:
        json.dump(manifest, f, indent=1, sort_keys=True, default=str)
    os.replace(man_path + '.tmp', man_path)
    print(json.dumps({'batch': a.batch, 'new_episodes': n_done, 'written': written, 'wall_s': round(time.time() - t0, 1)}))
    return 0 if not any(w['file'].startswith('errors_') for w in written) else 1


# ----------------------------------------------------------------------------------------------- self test
def selftest():
    ok = True
    ins = np.array([0, 1, 1, 0, 1, 1, 1, 1, 0], bool)
    ok &= first_sustained_index(ins, 3) == 4 and first_sustained_index(ins, 5) is None and first_index(ins) == 1
    ok &= residence_samples(0.5) == 51 and residence_samples(1.0) == 101
    ok &= bounded_score(5.0, 25, None, 25.0, False) == (5.0, 'success')
    ok &= bounded_score(None, 25, None, 25.0, False) == (25.0, 'no_entry')
    ok &= bounded_score(None, 40, None, 25.0, False) == (None, 'censored')
    ok &= bounded_score(10.0, 40, None, 25.0, False) == (10.0, 'success')
    ok &= bounded_score(None, 25, None, 6.5, True) == (25.0, 'terminal_stop')
    ok &= bounded_score(5.0, 25, 3.0, 25.0, False) == (25.0, 'controller_failure_before_entry')
    ok &= bounded_score(5.0, 25, 7.0, 25.0, False) == (5.0, 'success')
    ok &= bounded_score(24.8, 25, None, 25.0, False, dur=0.5) == (25.0, 'no_entry')
    ok &= sign_changes([0.3, 0.01, -0.02, -0.3, 0.2], 0.05) == 2 and sign_changes([1, -1, 1]) == 2
    steps = np.arange(0, 6000, 10)
    d = np.zeros(len(steps)); d[100:400] = 6.0
    on, beyond, mx = divergence(steps, d, 5.0, 2.0)
    ok &= on == 1000 and abs(beyond - 3.0) < 1e-9
    d2 = np.zeros(len(steps)); d2[100:250] = 6.0
    ok &= divergence(steps, d2, 5.0, 2.0)[0] is None
    # error state on a straight +x line: vehicle at y = -1 heading 0 -> lateral +1 (reference to the left)
    ref = build_reference({'type': 'straight', 's_start': -30, 's_end': 60, 'spacing': 0.1}, [])[0]
    E, _ = error_state_vec([0.0], [-1.0], [0.0], [0.0], ref, 0.0)
    ok &= abs(E[0, 1] - 1.0) < 1e-12 and abs(E[0, 2]) < 1e-12
    print('selftest', 'PASS' if ok else 'FAIL')
    return 0 if ok else 1


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