File size: 33,130 Bytes
3e56913
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import argparse
from datetime import datetime, timezone
import json
import os
import signal
import socket
import subprocess
import sys
import time
from pathlib import Path


RETRYABLE_ROUTE_STATUSES = {
    "Started",
    "Failed - Simulation crashed",
    "Failed - Agent crashed",
}
FATAL_ROUTE_STATUS_FRAGMENTS = (
    "Agent couldn't be set up",
    "Agent's sensors were invalid",
)
FATAL_ENTRY_STATUSES = {"Invalid", "Rejected"}


def parse_args():
    parser = argparse.ArgumentParser(description="Run the local DriveVLA agent on Bench2Drive routes.")
    parser.add_argument("--checkpoint", required=True, help="Model checkpoint file or DeepSpeed checkpoint directory.")
    parser.add_argument("--config", default=None, help="Optional resolved Hydra config.yaml. Inferred from outputs/<run>/.hydra when omitted.")
    parser.add_argument("--routes", default="leaderboard/data/bench2drive_split/bench2drive_00.xml", help="Route XML file or directory of XML files.")
    parser.add_argument("--routes-subset", default="", help="Comma/range subset passed to Bench2Drive for a multi-route XML.")
    parser.add_argument("--result-dir", default="eval_results/Bench2Drive/drivevla", help="Directory for result JSON files.")
    parser.add_argument("--result-file", default=None, help="Explicit result JSON path. Only valid when --routes resolves to one XML file.")
    parser.add_argument("--agent-config-file", default=None, help="Explicit agent config JSON path.")
    parser.add_argument("--retry-state-file", default=None, help="Persistent per-worker route retry state JSON.")
    parser.add_argument("--debug-checkpoint-file", default=None, help="Per-worker live statistics text file.")
    parser.add_argument("--carla-root", default=os.environ.get("CARLA_ROOT"), help="CARLA 0.9.15 root directory.")
    parser.add_argument("--port", type=int, default=2000, help="CARLA world port.")
    parser.add_argument("--traffic-manager-port", type=int, default=8000, help="CARLA traffic manager port.")
    parser.add_argument("--traffic-manager-seed", type=int, default=1, help="Traffic manager seed.")
    parser.add_argument("--timeout", type=int, default=600, help="Leaderboard evaluator timeout.")
    parser.add_argument("--repetitions", type=int, default=1)
    parser.add_argument(
        "--gpu-rank",
        type=int,
        default=0,
        help="Logical CARLA GPU rank. 0 omits -graphicsadapter; N>0 maps to -graphicsadapter=N+1.",
    )
    parser.add_argument("--agent-file", default="team_code/agent_drivevla.py")
    parser.add_argument(
        "--visualize-trajectories",
        action="store_true",
        help="Save per-frame closed-loop visualizations with spatial and temporal predicted trajectories.",
    )
    parser.add_argument(
        "--trajectory-viz-dir",
        default=None,
        help="Output directory for trajectory visualization frames. Defaults to <result-dir>/trajectory_viz.",
    )
    parser.add_argument(
        "--trajectory-viz-frequency",
        type=int,
        default=1,
        help="Save one visualization every N agent frames when --visualize-trajectories is enabled.",
    )
    parser.add_argument(
        "--record-dir",
        default=None,
        help="Directory for CARLA recorder logs (one <route>_rep<N>.log per route). Disabled when omitted.",
    )
    parser.add_argument(
        "--trajectory-viz-no-bev-camera",
        action="store_true",
        help="Do not add the extra top-down RGB camera used for BEV visualization.",
    )
    parser.add_argument(
        "--consequence-gating",
        action="store_true",
        help="Gate the executed speed profile with the trained consequence head "
        "(requires a ConsDrive checkpoint).",
    )
    parser.add_argument(
        "--gating-algorithm",
        choices=("v2", "v3"),
        default="v2",
        help="Consequence gating controller: 'v2' (one-step hysteresis, default) "
        "or 'v3' (jump-to-safe).",
    )
    parser.add_argument(
        "--gating-speed-scales",
        default="1.0,0.85,0.7,0.5",
        help="Comma-separated speed-trajectory scale candidates for consequence gating.",
    )
    parser.add_argument(
        "--gating-risk-threshold",
        type=float,
        default=0.5,
        help="Highest acceptable aggregated collision probability for a speed candidate.",
    )
    parser.add_argument(
        "--gating-aggregate",
        choices=("max", "mean"),
        default="max",
        help="How per-waypoint risk probabilities are aggregated per candidate.",
    )
    parser.add_argument(
        "--gating-hysteresis-down-steps",
        type=int,
        default=3,
        help="Consecutive above-threshold steps before gating downgrades speed one tier.",
    )
    parser.add_argument(
        "--gating-hysteresis-up-steps",
        type=int,
        default=5,
        help="Consecutive safe steps before gating upgrades speed one tier.",
    )
    parser.add_argument(
        "--gating-min-speed",
        type=float,
        default=1.5,
        help="Skip consequence gating when ego speed is below this value (m/s).",
    )
    parser.add_argument(
        "--risk-shadow-log",
        action="store_true",
        help="Score the executed plan with the consequence head every step and "
        "dump per-route risk distributions to <result-dir>/risk_shadow. Used on "
        "no-gating runs to pick the gating threshold for a new checkpoint.",
    )
    parser.add_argument(
        "--resume",
        action="store_true",
        default=True,
        help="Resume from the Bench2Drive result checkpoint. Enabled by default.",
    )
    parser.add_argument(
        "--overwrite",
        action="store_true",
        help="Disable resume and overwrite the Bench2Drive result checkpoint from the beginning.",
    )
    parser.add_argument("--dry-run", action="store_true", help="Print commands without running them.")
    parser.add_argument(
        "--max-route-retries",
        "--max-retries",
        dest="max_route_retries",
        type=int,
        default=3,
        help="Extra attempts allowed for each route after a CARLA/agent runtime crash.",
    )
    parser.add_argument(
        "--retry-wait",
        type=int,
        default=15,
        help="Seconds to wait after cleaning up crashed CARLA processes before restarting.",
    )
    parser.add_argument(
        "--carla-death-grace",
        type=int,
        default=90,
        help=(
            "Seconds the evaluator may keep running after its CARLA instance died "
            "before the supervisor kills it to trigger a retry. 0 disables the watchdog."
        ),
    )
    return parser.parse_args()


def atomic_write_json(path, data):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    temp_path = path.with_name(f".{path.name}.{os.getpid()}.tmp")
    try:
        with open(temp_path, "w", encoding="utf-8") as file_handle:
            json.dump(data, file_handle, indent=2)
            file_handle.flush()
            os.fsync(file_handle.fileno())
        os.replace(temp_path, path)
    finally:
        temp_path.unlink(missing_ok=True)


def load_json(path, *, allow_missing=False):
    path = Path(path)
    if allow_missing and not path.exists():
        return None
    try:
        with open(path, encoding="utf-8") as file_handle:
            data = json.load(file_handle)
    except FileNotFoundError:
        raise RuntimeError(f"Required JSON file does not exist: {path}") from None
    except json.JSONDecodeError as exc:
        raise RuntimeError(f"Refusing to modify malformed JSON file {path}: {exc}") from exc
    if not isinstance(data, dict):
        raise RuntimeError(f"Expected a JSON object in {path}")
    return data


def _carla_process_groups(port, gpu_rank=None):
    """Return CARLA process groups bound to this worker's RPC port.

    Matching is port-only. Do not fall back to graphicsadapter: multiple workers
    can share the same adapter and that would cause false positives in the
    watchdog and could kill another worker's CARLA during cleanup.
    """
    del gpu_rank  # kept for call-site compatibility
    port_marker = f"-carla-rpc-port={port}"
    groups = set()
    current_group = os.getpgrp()
    for proc_dir in Path("/proc").iterdir():
        if not proc_dir.name.isdigit():
            continue
        try:
            command = (proc_dir / "cmdline").read_bytes().replace(b"\0", b" ").decode(errors="replace")
            if "CarlaUE4" not in command or port_marker not in command:
                continue
            process_group = os.getpgid(int(proc_dir.name))
            if process_group != current_group:
                groups.add(process_group)
        except (FileNotFoundError, ProcessLookupError, PermissionError):
            continue
    return groups


def _port_is_available(port):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        try:
            sock.bind(("127.0.0.1", port))
        except OSError:
            return False
    return True


def cleanup_carla(port, gpu_rank=None, grace_seconds=5, max_wait_seconds=120):
    """Stop CARLA for this worker and wait until its RPC ports are free."""
    reserved_ports = (port, port + 1)
    deadline = time.monotonic() + max_wait_seconds
    attempt = 0

    while time.monotonic() < deadline:
        attempt += 1
        groups = _carla_process_groups(port, gpu_rank)
        for process_group in groups:
            try:
                os.killpg(process_group, signal.SIGTERM)
            except ProcessLookupError:
                pass

        term_deadline = time.monotonic() + grace_seconds
        while groups and time.monotonic() < term_deadline:
            groups = _carla_process_groups(port, gpu_rank)
            if groups:
                time.sleep(0.2)

        for process_group in groups:
            try:
                os.killpg(process_group, signal.SIGKILL)
            except ProcessLookupError:
                pass

        if _carla_process_groups(port, gpu_rank):
            print(f"[eval_bench2drive] force-killed CARLA on rpc port {port}", flush=True)

        port_deadline = time.monotonic() + grace_seconds
        while time.monotonic() < port_deadline:
            if all(_port_is_available(reserved_port) for reserved_port in reserved_ports):
                if attempt > 1:
                    print(
                        f"[eval_bench2drive] CARLA cleanup succeeded on port {port} "
                        f"after {attempt} attempts",
                        flush=True,
                    )
                return
            time.sleep(0.2)

        occupied = [
            reserved_port
            for reserved_port in reserved_ports
            if not _port_is_available(reserved_port)
        ]
        remaining_time = deadline - time.monotonic()
        if remaining_time <= 0:
            break
        print(
            f"[eval_bench2drive] ports {occupied} still occupied after cleanup "
            f"attempt {attempt}; retrying in {grace_seconds}s "
            f"({remaining_time:.0f}s left)",
            flush=True,
        )
        time.sleep(min(grace_seconds, remaining_time))

    occupied = [
        reserved_port
        for reserved_port in reserved_ports
        if not _port_is_available(reserved_port)
    ]
    raise RuntimeError(f"CARLA worker ports are still occupied after cleanup: {occupied}")


def empty_route_infractions(template=None):
    if isinstance(template, dict):
        return {name: [] for name in template}
    return {
        "collisions_layout": [],
        "collisions_pedestrian": [],
        "collisions_vehicle": [],
        "red_light": [],
        "stop_infraction": [],
        "outside_route_lanes": [],
        "min_speed_infractions": [],
        "yield_emergency_vehicle_infractions": [],
        "scenario_timeouts": [],
        "route_dev": [],
        "vehicle_blocked": [],
        "route_timeout": [],
    }


def resolve_worker_route_id(routes_subset, record_index, repetitions=1):
    if not routes_subset:
        return None
    route_ids = [part.strip() for part in routes_subset.replace(" ", "").split(",") if part.strip()]
    if record_index < 0 or record_index >= len(route_ids) * repetitions:
        return None
    xml_id = route_ids[record_index // repetitions]
    rep_index = record_index % repetitions
    return f"RouteScenario_{xml_id}_rep{rep_index}"


def _is_superseded_route_record(index, records):
    """Return True when a later route already finished after this record.

    Resume can leave an early fatal record in the checkpoint even after the
    worker continued with later routes (for example after a manual restart).
    Those stale records must not block watchdog retries for the current route.
    """
    for later_index in range(index + 1, len(records)):
        later_record = records[later_index]
        if isinstance(later_record, dict) and later_record.get("status") == "Completed":
            return True
    return False


def inspect_failure(result_file, routes_subset="", repetitions=1):
    """Classify the evaluator failure using its durable route checkpoint."""
    data = load_json(result_file, allow_missing=True)
    if data is None:
        return {
            "classification": "startup",
            "route_key": f"startup:{Path(result_file).name}",
            "route_id": None,
            "record_index": None,
            "status": "No result checkpoint",
            "entry_status": None,
        }

    entry_status = data.get("entry_status")
    if entry_status in FATAL_ENTRY_STATUSES:
        return {
            "classification": "fatal",
            "route_key": f"fatal:{Path(result_file).name}",
            "route_id": None,
            "record_index": None,
            "status": f"entry_status={entry_status}",
            "entry_status": entry_status,
        }

    checkpoint = data.get("_checkpoint")
    if not isinstance(checkpoint, dict):
        raise RuntimeError(f"Malformed result checkpoint in {result_file}: missing _checkpoint")
    progress = checkpoint.get("progress")
    records = checkpoint.get("records")
    if not isinstance(progress, list) or len(progress) != 2 or not isinstance(records, list):
        raise RuntimeError(f"Malformed result checkpoint in {result_file}: invalid progress/records")

    completed, total = progress
    if not isinstance(completed, int) or not isinstance(total, int) or completed < 0 or total < completed:
        raise RuntimeError(f"Malformed result checkpoint in {result_file}: invalid progress {progress}")
    if entry_status == "Finished" and completed == total and len(records) == total:
        return {"classification": "complete", "status": "Finished"}

    # Scan from the newest record backward so stale early failures do not mask
    # the route that actually crashed or is currently in progress.
    for index in range(len(records) - 1, -1, -1):
        record = records[index]
        if not isinstance(record, dict):
            raise RuntimeError(f"Malformed route record {index} in {result_file}")
        if _is_superseded_route_record(index, records):
            continue
        status = record.get("status")
        if any(fragment in str(status) for fragment in FATAL_ROUTE_STATUS_FRAGMENTS):
            return {
                "classification": "fatal",
                "route_key": f"fatal:{record.get('route_id', index)}",
                "route_id": record.get("route_id"),
                "record_index": index,
                "status": status,
                "entry_status": entry_status,
            }
        if status in RETRYABLE_ROUTE_STATUSES:
            route_id = record.get("route_id")
            if not route_id:
                raise RuntimeError(f"Retryable route record {index} has no route_id in {result_file}")
            return {
                "classification": "route",
                "route_key": route_id,
                "route_id": route_id,
                "record_index": index,
                "status": status,
                "entry_status": entry_status,
            }

    if completed < total:
        route_id = resolve_worker_route_id(routes_subset, completed, repetitions)
        if route_id:
            status = "Started"
            if completed < len(records):
                status = records[completed].get("status", status)
            return {
                "classification": "route",
                "route_key": route_id,
                "route_id": route_id,
                "record_index": completed,
                "status": status,
                "entry_status": entry_status,
            }

    return {
        "classification": "startup",
        "route_key": f"process:{Path(result_file).name}:{completed}",
        "route_id": None,
        "record_index": None,
        "status": f"Evaluator exited without a retryable route (entry_status={entry_status}, progress={progress})",
        "entry_status": entry_status,
    }


def register_retry_event(state_file, failure, returncode, max_route_retries):
    state = load_json(state_file, allow_missing=True) or {"version": 1, "routes": {}}
    routes = state.get("routes")
    if not isinstance(routes, dict):
        raise RuntimeError(f"Malformed retry state in {state_file}: routes must be an object")

    route_state = routes.setdefault(
        failure["route_key"],
        {"route_id": failure.get("route_id"), "retries": 0, "history": []},
    )
    retries = int(route_state.get("retries", 0))
    can_retry = retries < max_route_retries
    skippable = failure["classification"] == "route" or failure.get("record_index") is not None
    action = "retry" if can_retry else ("skip" if skippable else "fatal")
    if can_retry:
        retries += 1
        route_state["retries"] = retries

    event = {
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "status": failure["status"],
        "entry_status": failure.get("entry_status"),
        "returncode": returncode,
        "action": action,
        "retry": retries,
    }
    route_state.setdefault("history", []).append(event)
    route_state["last_status"] = failure["status"]
    route_state["last_action"] = action
    route_state["updated_at"] = event["timestamp"]
    if action == "skip":
        route_state["exhausted"] = True
    atomic_write_json(state_file, state)
    return action, retries


def mark_route_zero(result_file, failure, routes_subset="", repetitions=1):
    """Finalize a repeatedly crashing route as a schema-valid zero-score failure."""
    data = load_json(result_file)
    checkpoint = data.get("_checkpoint")
    if not isinstance(checkpoint, dict):
        raise RuntimeError(f"Malformed result checkpoint in {result_file}")
    records = checkpoint.get("records")
    progress = checkpoint.get("progress")
    index = failure.get("record_index")
    if not isinstance(records, list) or not isinstance(progress, list) or not isinstance(index, int):
        raise RuntimeError(f"Cannot mark route zero in malformed checkpoint {result_file}")
    if index < 0:
        raise RuntimeError(f"Route index {index} is out of range in {result_file}")

    route_id = failure.get("route_id") or resolve_worker_route_id(routes_subset, index, repetitions)
    if not route_id:
        raise RuntimeError(f"Cannot resolve route id for index {index} in {result_file}")

    if index >= len(records):
        template = records[-1].get("infractions") if records else None
        record = {
            "index": index,
            "route_id": route_id,
            "scenario_name": "",
            "weather_id": "",
            "save_name": "",
            "status": "Started",
            "num_infractions": 0,
            "infractions": empty_route_infractions(template),
            "scores": {
                "score_route": 0.0,
                "score_penalty": 1.0,
                "score_composed": 0.0,
            },
            "meta": {
                "route_length": 0,
                "duration_game": 0,
                "duration_system": 0,
            },
            "town_name": "",
        }
        records.append(record)
    else:
        record = records[index]
        if record.get("route_id") and record.get("route_id") != route_id:
            raise RuntimeError(
                f"Route mismatch while marking zero: expected {route_id}, found {record.get('route_id')}"
            )
        record["route_id"] = route_id
        if record.get("status") not in RETRYABLE_ROUTE_STATUSES:
            raise RuntimeError(
                f"Refusing to overwrite non-retryable route {route_id} with status {record.get('status')}"
            )

    record["status"] = "Failed - Retry limit exceeded"
    record["scores"] = {
        "score_route": 0.0,
        "score_penalty": 1.0,
        "score_composed": 0.0,
    }
    infractions = record.get("infractions")
    if isinstance(infractions, dict):
        record["infractions"] = {name: [] for name in infractions}
    record["num_infractions"] = 0
    progress[0] = max(progress[0], index + 1)
    checkpoint["global_record"] = {}
    data["entry_status"] = "Started"
    data["eligible"] = False
    data["values"] = []
    data["labels"] = []
    atomic_write_json(result_file, data)


def run_evaluator_with_watchdog(cmd, cwd, env, port, gpu_rank, death_grace, poll_seconds=5):
    """Run the evaluator, killing it if CARLA dies and it fails to exit on its own.

    Without this, a mid-route CARLA segfault leaves the evaluator blocked on
    600s RPC timeouts and the retry loop cannot engage for many minutes.
    """
    proc = subprocess.Popen(cmd, cwd=cwd, env=env)
    carla_seen = False
    carla_dead_since = None
    watchdog_fired = False
    try:
        while True:
            try:
                returncode = proc.wait(timeout=poll_seconds)
                break
            except subprocess.TimeoutExpired:
                pass

            if death_grace <= 0:
                continue
            if _carla_process_groups(port, gpu_rank):
                carla_seen = True
                carla_dead_since = None
                continue
            if not carla_seen:
                # CARLA has not started yet (evaluator launches it itself).
                continue
            now = time.monotonic()
            if carla_dead_since is None:
                carla_dead_since = now
                continue
            if now - carla_dead_since < death_grace:
                continue

            print(
                f"[eval_bench2drive] watchdog: CARLA on port {port} has been dead for "
                f"{death_grace}s but the evaluator (pid {proc.pid}) is still running; "
                "killing it to trigger a retry.",
                flush=True,
            )
            watchdog_fired = True
            proc.terminate()
            try:
                returncode = proc.wait(timeout=30)
            except subprocess.TimeoutExpired:
                proc.kill()
                returncode = proc.wait()
            break
    except KeyboardInterrupt:
        proc.terminate()
        try:
            proc.wait(timeout=10)
        except subprocess.TimeoutExpired:
            proc.kill()
            proc.wait()
        raise
    return returncode, watchdog_fired


def route_files(route_arg):
    path = Path(route_arg)
    if path.is_dir():
        return sorted(path.glob("*.xml"))
    return [path]


def build_env(repo_root, carla_root):
    env = os.environ.copy()
    python_paths = [
        str(repo_root),
        str(repo_root / "Bench2Drive" / "leaderboard"),
        str(repo_root / "Bench2Drive" / "scenario_runner"),
    ]
    if carla_root:
        carla_root = Path(carla_root).expanduser()
        python_paths.extend(
            [
                str(carla_root / "PythonAPI" / "carla"),
            ]
        )
        env["CARLA_ROOT"] = str(carla_root)
    env["PYTHONPATH"] = os.pathsep.join(python_paths + ([env["PYTHONPATH"]] if env.get("PYTHONPATH") else []))
    env["SCENARIO_RUNNER_ROOT"] = str(repo_root / "Bench2Drive" / "scenario_runner")
    env.setdefault("SAVE_PATH", str(repo_root / "eval_results" / "viz"))
    return env


def main():
    args = parse_args()
    if args.max_route_retries < 0:
        raise ValueError("--max-route-retries must be non-negative")
    repo_root = Path(__file__).resolve().parent
    result_dir = (repo_root / args.result_dir).resolve()
    result_dir.mkdir(parents=True, exist_ok=True)

    agent_config = {
        "checkpoint": str(Path(args.checkpoint).expanduser().resolve()),
    }
    if args.config is not None:
        config_path = Path(args.config).expanduser().resolve()
        if not config_path.is_file():
            raise FileNotFoundError(f"--config does not exist: {config_path}")
        agent_config["config"] = str(config_path)
    if args.visualize_trajectories:
        viz_dir = Path(args.trajectory_viz_dir).expanduser() if args.trajectory_viz_dir else result_dir / "trajectory_viz"
        if not viz_dir.is_absolute():
            viz_dir = repo_root / viz_dir
        agent_config["trajectory_viz"] = {
            "enabled": True,
            "output_dir": str(viz_dir.resolve()),
            "frequency": max(int(args.trajectory_viz_frequency), 1),
            "bev_sensor": not args.trajectory_viz_no_bev_camera,
        }
    if args.consequence_gating:
        agent_config["consequence_gating"] = {
            "enabled": True,
            "algorithm": args.gating_algorithm,
            "speed_scales": [float(s) for s in args.gating_speed_scales.split(",") if s.strip()],
            "risk_threshold": args.gating_risk_threshold,
            "aggregate": args.gating_aggregate,
            "hysteresis_down_steps": int(args.gating_hysteresis_down_steps),
            "hysteresis_up_steps": int(args.gating_hysteresis_up_steps),
            "min_speed": float(args.gating_min_speed),
        }
    if args.risk_shadow_log:
        agent_config["risk_shadow_log"] = {
            "enabled": True,
            "output_dir": str(result_dir / "risk_shadow"),
        }

    agent_config_path = Path(args.agent_config_file).expanduser() if args.agent_config_file else result_dir / "agent_config.json"
    if not agent_config_path.is_absolute():
        agent_config_path = repo_root / agent_config_path
    agent_config_path.parent.mkdir(parents=True, exist_ok=True)
    atomic_write_json(agent_config_path, agent_config)

    env = build_env(repo_root, args.carla_root)
    evaluator = repo_root / "Bench2Drive" / "leaderboard" / "leaderboard" / "leaderboard_evaluator.py"
    agent_file = (repo_root / args.agent_file).resolve()

    routes = route_files(args.routes)
    if args.result_file and len(routes) != 1:
        raise ValueError("--result-file can only be used when --routes resolves to one XML file")

    for route in routes:
        route = route.resolve()
        if args.result_file:
            result_file = Path(args.result_file).expanduser()
            if not result_file.is_absolute():
                result_file = repo_root / result_file
            result_file.parent.mkdir(parents=True, exist_ok=True)
        else:
            result_file = result_dir / f"{route.stem}_res.json"

        retry_state_file = (
            Path(args.retry_state_file).expanduser()
            if args.retry_state_file
            else result_file.with_suffix(".retry_state.json")
        )
        if not retry_state_file.is_absolute():
            retry_state_file = repo_root / retry_state_file
        debug_checkpoint_file = (
            Path(args.debug_checkpoint_file).expanduser()
            if args.debug_checkpoint_file
            else result_file.with_suffix(".live.txt")
        )
        if not debug_checkpoint_file.is_absolute():
            debug_checkpoint_file = repo_root / debug_checkpoint_file
        retry_state_file.parent.mkdir(parents=True, exist_ok=True)
        debug_checkpoint_file.parent.mkdir(parents=True, exist_ok=True)
        if args.overwrite:
            retry_state_file.unlink(missing_ok=True)

        env["ROUTES"] = str(route)
        cmd = [
            sys.executable,
            "-u",
            str(evaluator),
            f"--routes={route}",
            f"--repetitions={args.repetitions}",
            "--track=SENSORS",
            f"--checkpoint={result_file}",
            f"--debug-checkpoint={debug_checkpoint_file}",
            f"--timeout={args.timeout}",
            f"--agent={agent_file}",
            f"--agent-config={agent_config_path}",
            f"--traffic-manager-seed={args.traffic_manager_seed}",
            f"--port={args.port}",
            f"--traffic-manager-port={args.traffic_manager_port}",
            f"--gpu-rank={args.gpu_rank}",
        ]
        if args.routes_subset:
            cmd.append(f"--routes-subset={args.routes_subset}")
        if args.record_dir:
            record_dir = Path(args.record_dir).expanduser()
            if not record_dir.is_absolute():
                record_dir = repo_root / record_dir
            record_dir.mkdir(parents=True, exist_ok=True)
            # The CARLA server writes the recording and may run as a different user.
            record_dir.chmod(0o777)
            cmd.append(f"--record={record_dir.resolve()}")
        if args.resume and not args.overwrite:
            cmd.append("--resume=True")
        print(" ".join(cmd), flush=True)
        if args.dry_run:
            continue

        # Retries always resume from the result checkpoint, even when the first
        # attempt was started with --overwrite.
        resume_cmd = cmd if "--resume=True" in cmd else cmd + ["--resume=True"]

        first_attempt = True
        while True:
            # Clear only this worker's CARLA instance before (re)starting.
            cleanup_carla(args.port, args.gpu_rank)

            run_cmd = cmd if first_attempt else resume_cmd
            first_attempt = False
            try:
                returncode, watchdog_fired = run_evaluator_with_watchdog(
                    run_cmd,
                    cwd=repo_root,
                    env=env,
                    port=args.port,
                    gpu_rank=args.gpu_rank,
                    death_grace=args.carla_death_grace,
                )
            except KeyboardInterrupt:
                cleanup_carla(args.port, args.gpu_rank)
                raise
            if watchdog_fired and returncode == 0:
                # A zero exit after a forced kill cannot be trusted as success.
                returncode = -signal.SIGTERM
            if returncode == 0:
                break

            failure = inspect_failure(
                result_file,
                routes_subset=args.routes_subset,
                repetitions=args.repetitions,
            )
            if failure["classification"] == "complete":
                print(
                    f"[eval_bench2drive] evaluator exited {returncode}, but checkpoint is complete; "
                    "treating the worker as finished.",
                    flush=True,
                )
                break
            if failure["classification"] == "fatal":
                cleanup_carla(args.port, args.gpu_rank)
                raise RuntimeError(
                    f"Fatal Bench2Drive failure: route={failure.get('route_id')} "
                    f"status={failure['status']} exit={returncode}"
                )

            action, retry_number = register_retry_event(
                retry_state_file,
                failure,
                returncode,
                args.max_route_retries,
            )
            if action == "skip":
                mark_route_zero(
                    result_file,
                    failure,
                    routes_subset=args.routes_subset,
                    repetitions=args.repetitions,
                )
                print(
                    f"[eval_bench2drive] route={failure['route_id']} "
                    f"class={failure['classification']} status={failure['status']} "
                    f"action=skip retries={retry_number}; "
                    "recorded score_composed=0 and continuing with the next route.",
                    flush=True,
                )
                time.sleep(args.retry_wait)
                continue
            if action == "fatal":
                cleanup_carla(args.port, args.gpu_rank)
                raise RuntimeError(
                    f"Evaluator failed before a route could be identified after "
                    f"{args.max_route_retries} retries: {failure['status']}"
                )

            print(
                f"[eval_bench2drive] route={failure.get('route_id') or 'startup'} "
                f"class={failure['classification']} status={failure['status']} action=retry "
                f"retry={retry_number}/{args.max_route_retries} exit={returncode}; "
                f"restarting in {args.retry_wait}s.",
                flush=True,
            )
            time.sleep(args.retry_wait)


if __name__ == "__main__":
    main()