File size: 34,900 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
#!/usr/bin/env python3
"""Batch driver for the lock-step ART runner.

Runs a JSON episode list with N supervised worker processes inside ONE container (start it with
run_campaign.sh). Resumable: an episode whose episodes/<episode_id>/summary.json exists with the same config hash
is skipped; a different hash is a hard error (never overwrite).

Supervision. Each worker is its own spawned process with
its own pipe, so the supervisor always knows which episode a worker is running.
  * A worker that dies (SIGKILL, OOM kill, segfault) or exceeds the per-episode wall-clock timeout
    (--episode-timeout-base-s + --episode-timeout-factor x horizon_s) is an INFRASTRUCTURE error: the supervisor
    writes infrastructure_errors/<episode_id>_<ms>/summary.json (and moves the partial .tmp directory there),
    starts a replacement worker, and retries the identical config.
  * Every infrastructure error (returned by the worker or detected by the supervisor) is retried up to
    --max-retries times (default 2) within the invocation; an episode still failing after that is
    listed in the manifest (`infrastructure_exhausted`) and is re-attempted on the next invocation.
  * Stall watchdog: if no episode finishes for --stall-timeout-s (default max(900 s, 10 x median episode wall,
    1.5 x the largest running per-episode timeout)), the manifest status becomes 'stalled' and campaign.py exits.
  * A heartbeat file heartbeat_<run_id>.json is rewritten every 30 s (running episodes, elapsed, last progress).
  * Exit codes: 0 complete; 3 stalled; 4 infrastructure errors left after retries; 5 worker start failure or
    worker/parent environment mismatch; 130 SIGINT; 143 SIGTERM. The manifest status always says which.

Provenance and resume. Every summary.json carries `provenance`: the code digest (runner
files, physics binary, released controller code, checkpoints, waypoint files, terrain JSON, Chrono libraries,
image digest), the host fingerprint (CPU model and flags, torch CPU capability, numpy SIMD dispatch, OpenBLAS core,
MKL code path, numerics environment variables, TR_HOST_NAME), the run_id and the attempt number. An existing OUT
directory is resumed only if every manifest and summary in it has the same code digest and host fingerprint;
otherwise campaign.py refuses (use one OUT directory per code version and host). --allow-host-change
overrides only the host check and is recorded in the manifest (use it only after a bytewise cross-host reference
check).

Usage (inside the image, ROS env sourced; see run_campaign.sh):
    python3 campaign.py --episodes EPISODES.json --out OUTDIR --workers 6
"""
import argparse
import collections
import csv
import datetime as _dt
import glob
import hashlib
import json
import multiprocessing as mp
import multiprocessing.connection as mpc
import os
import platform
import re
import shutil
import signal
import statistics
import subprocess
import sys
import time
import traceback

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

from art_runner import config as cfgmod  # noqa: E402
from art_runner.released import CHECKPOINT_SHA256, RELEASED_DIR, RELEASED_SHA256, WAYPOINT_DIR, sha256_file  # noqa: E402

POOL = None
SUMMARY_FIELDS = ['episode_id', 'scenario_id', 'controller', 'latency_model', 'status', 'outcome',
                  'tube_entry_time_100hz_s', 'tube_entry_time_tick_s', 'stay_in_tube_time_100hz_s',
                  'fraction_inside_tube_after_entry', 'tube_exits_after_entry', 'max_abs_lat_100hz_m',
                  'final_e_lat_m', 'final_e_head_rad', 'completion_step', 'run_mae_lateral_m', 'run_mae_heading_rad',
                  'run_mae_samples', 'n_ticks', 'n_published', 'n_rate_limited', 'sim_s', 'failure_category',
                  'failure_t', 'wall_total_s', 'wall_init_s', 'wall_stepping_s', 'wall_controller_s', 'wall_other_s',
                  'server_spawn_to_ready_s', 'config_hash', 'worker_pid',
                  # offline diagnostics and provenance (no effect on the logs)
                  'tube_entry_time_100hz_lookahead_s', 'tube_entry_time_tick_lookahead_s', 'spin_flag',
                  'spin_first_step', 'max_abs_yaw_rate_100hz', 'first_command_apply_step', 'chassis_touchdown_step',
                  'run_id', 'attempt', 'code_digest', 'host_fingerprint',
                  # offline summary fields (no effect on the logs)
                  'horizon_mean_abs_e_lat_m', 'horizon_mean_abs_e_head_rad', 'horizon_mean_covers_horizon',
                  'divergence_flag', 'n_divergence_events', 'diverged_then_recovered', 'entered_then_diverged',
                  'first_tube_entry_after_divergence_s', 'divergence_step', 'mpc_osqp_n_solves', 'mpc_osqp_n_not_solved',
                  'mpc_osqp_iter_mean', 'mpc_osqp_iter_max', 'obs_noise_model']
NUMERICS_ENV = ('ATEN_CPU_CAPABILITY', 'MKL_CBWR', 'MKL_ENABLE_INSTRUCTIONS', 'OPENBLAS_CORETYPE',
                'NPY_DISABLE_CPU_FEATURES', 'ONEDNN_MAX_CPU_ISA', 'OMP_NUM_THREADS', 'MKL_NUM_THREADS',
                'OPENBLAS_NUM_THREADS', 'KERAS_BACKEND', 'CUDA_VISIBLE_DEVICES')
EXIT_OK, EXIT_STALLED, EXIT_INFRA, EXIT_WORKER_START, EXIT_SIGINT, EXIT_SIGTERM = 0, 3, 4, 5, 130, 143


def _now():
    return _dt.datetime.now(_dt.timezone.utc).isoformat()


def _digest(obj):
    return hashlib.sha256(json.dumps(obj, sort_keys=True, separators=(',', ':'), default=str).encode()).hexdigest()


def _write_json_atomic(path, obj):
    tmp = path + '.tmp'
    with open(tmp, 'w') as f:
        json.dump(obj, f, indent=1, sort_keys=True, default=str)
    os.replace(tmp, path)


# --------------------------------------------------------------------------- environment / provenance
def numerics_dispatch():
    """CPU dispatch paths that can change last-bit results (recorded in every manifest and summary)."""
    rec = {'env': {k: os.environ.get(k) for k in NUMERICS_ENV}}
    try:
        import torch
        rec['torch_cpu_capability'] = torch.backends.cpu.get_cpu_capability()
    except Exception as e:  # pragma: no cover
        rec['torch_cpu_capability'] = f'error: {e}'
    try:
        from numpy.core import _multiarray_umath as mu
        rec['numpy_simd_dispatch_enabled'] = [f for f in mu.__cpu_dispatch__ if mu.__cpu_features__.get(f)]
        rec['numpy_simd_baseline'] = list(mu.__cpu_baseline__)
    except Exception as e:  # pragma: no cover
        rec['numpy_simd_dispatch_enabled'] = f'error: {e}'
    rec['openblas_core'] = None
    try:
        import ctypes
        import numpy  # noqa: F401  (loads libopenblas)
        libs = sorted({l.split()[-1] for l in open('/proc/self/maps') if 'openblas' in l and l.split()[-1].startswith('/')})
        for lib in libs:
            h = ctypes.CDLL(lib)
            for sym in ('openblas_get_corename64_', 'openblas_get_corename'):
                if hasattr(h, sym):
                    fn = getattr(h, sym)
                    fn.restype = ctypes.c_char_p
                    rec['openblas_core'] = fn().decode()
                    break
            if rec['openblas_core']:
                break
    except Exception as e:  # pragma: no cover
        rec['openblas_core'] = f'error: {e}'
    return rec


def mkl_code_path():
    """MKL's own report of the instruction set it dispatches to (MKL_VERBOSE on one small sgemm, subprocess)."""
    code = 'import torch; a = torch.ones(1, 4); w = torch.ones(4, 32); (a @ w).sum().item()'
    env = dict(os.environ, MKL_VERBOSE='1')
    try:
        out = subprocess.run([sys.executable, '-c', code], env=env, capture_output=True, text=True, timeout=120).stdout
        lines = [l.strip() for l in out.splitlines() if l.startswith('MKL_VERBOSE')]
        ver = next((l for l in lines if 'processors' in l), 'no MKL_VERBOSE version line')
        ver = re.sub(r'\s*\d+(\.\d+)?GHz', '', ver)  # the reported clock varies between runs; not a code path
        fn = next((l for l in lines if 'CNR:' in l), '')
        cnr = re.search(r'CNR:\S+', fn)
        return f"{ver} | {cnr.group(0) if cnr else 'CNR:?'}"
    except Exception as e:  # pragma: no cover
        return f'error: {e}'


def host_record(with_mkl=True):
    cpu, flags = '', ''
    try:
        with open('/proc/cpuinfo') as f:
            for l in f:
                if l.startswith('model name') and not cpu:
                    cpu = l.split(':', 1)[1].strip()
                elif l.startswith('flags') and not flags:
                    flags = l.split(':', 1)[1].strip()
                if cpu and flags:
                    break
    except Exception:
        pass
    simd = sorted(f for f in flags.split() if f.startswith(('avx', 'fma', 'sse', 'f16c', 'bmi', 'amx')))
    rec = {'host_name': os.environ.get('TR_HOST_NAME', 'unset'), 'cpu_model': cpu,
           'cpu_flags_sha256': hashlib.sha256(flags.encode()).hexdigest(), 'cpu_simd_flags': simd,
           'kernel': platform.release(), 'numerics': numerics_dispatch()}
    if with_mkl:
        rec['mkl_code_path'] = mkl_code_path()
    return rec


def host_fingerprint(rec):
    keys = ('host_name', 'cpu_model', 'cpu_flags_sha256', 'numerics', 'mkl_code_path')
    return _digest({k: rec.get(k) for k in keys})


def worker_fingerprint_fields(rec):
    """Fields a worker can recompute cheaply (no MKL subprocess) to prove it inherited the parent's environment."""
    return _digest({k: rec.get(k) for k in ('host_name', 'cpu_model', 'cpu_flags_sha256', 'numerics')})


def file_hashes(paths):
    return {p: sha256_file(p) for p in paths if os.path.isfile(p)}


def runner_files():
    """The digest covers the runner defaults (default_config.json), the episode builders (default_episode.py), the
    schemas and every plug-in / controller-copy file (art_runner/**/*.py, controllers/*.py). Paths are recorded
    relative to runner/, so the digest does not depend on where the runner directory lives."""
    return (sorted(glob.glob(os.path.join(HERE, 'art_runner', '**', '*.py'), recursive=True)) +
            sorted(glob.glob(os.path.join(HERE, 'controllers', '*.py'))) + [
        os.path.join(HERE, 'campaign.py'), os.path.join(HERE, 'build', 'art_lockstep'),
        os.path.join(HERE, 'src', 'art_lockstep.cpp'), os.path.join(HERE, 'build.sh'),
        os.path.join(HERE, 'run_campaign.sh'), os.path.join(HERE, 'default_config.json'),
        os.path.join(HERE, 'default_episode.py')] + sorted(glob.glob(os.path.join(HERE, 'schemas', '*'))))


CHRONO_LIB = '/sbel/Desktop/chrono/build/lib'
CHRONO_LIBS = [os.path.join(CHRONO_LIB, n) for n in
               ('libChronoEngine.so', 'libChronoEngine_vehicle.so', 'libChronoModels_vehicle.so')]
TERRAIN_JSON = '/sbel/Desktop/chrono/build/data/vehicle/terrain/RigidPlane.json'


def code_record():
    """Everything that can change an episode's numbers given its config, plus default_config.json,
    default_episode.py and schemas/, so that every input of a batch is bound to the digest."""
    return {
        'runner': {os.path.relpath(p, HERE): sha256_file(p) for p in runner_files() if os.path.isfile(p)},
        'released_controller': {n: sha256_file(os.path.join(RELEASED_DIR, n)) for n in RELEASED_SHA256},
        'checkpoints': file_hashes(list(CHECKPOINT_SHA256)),
        'references': file_hashes(sorted(glob.glob(os.path.join(WAYPOINT_DIR, '*.csv')))),
        'terrain_json': file_hashes([TERRAIN_JSON]),
        'chrono_libraries': file_hashes(CHRONO_LIBS),
        'image_digest': os.environ.get('TR_IMAGE_DIGEST', 'unknown (set by run_campaign.sh)'),
        'image_id': os.environ.get('TR_IMAGE_ID', 'unknown (set by run_campaign.sh)'),
    }


def environment_record(host):
    import numpy, scipy, osqp, torch, keras_core, casadi
    import importlib.metadata as md
    return {
        'image_digest': os.environ.get('TR_IMAGE_DIGEST', 'unknown (set by run_campaign.sh)'),
        'image_id': os.environ.get('TR_IMAGE_ID', 'unknown (set by run_campaign.sh)'),
        'max_workers_cap_env': os.environ.get('TR_MAX_WORKERS'),
        'python': platform.python_version(), 'platform': platform.platform(), 'cpu_model': host['cpu_model'],
        'nproc': os.cpu_count(), 'host': host,
        'packages': {'numpy': numpy.__version__, 'scipy': scipy.__version__, 'osqp': md.version('osqp'),
                     'torch': torch.__version__, 'keras_core': keras_core.__version__, 'casadi': casadi.__version__},
        'chrono_libraries': file_hashes(CHRONO_LIBS),
        'chrono_commit': '9d26ff7834a1a4ac4601a9e71a4a42c69ee080a5 (image /sbel/Desktop/chrono)',
        'thread_env': {k: os.environ.get(k) for k in ('OMP_NUM_THREADS', 'MKL_NUM_THREADS', 'OPENBLAS_NUM_THREADS',
                                                      'KERAS_BACKEND', 'CUDA_VISIBLE_DEVICES')},
    }


def input_hashes(episodes_file):
    return {
        'runner': {os.path.relpath(p, HERE): h for p, h in file_hashes(runner_files()).items()},
        'runner_root': HERE,
        'released_controller': {n: sha256_file(os.path.join(RELEASED_DIR, n)) for n in RELEASED_SHA256},
        'released_controller_expected': RELEASED_SHA256,
        'checkpoints': file_hashes(list(CHECKPOINT_SHA256)),
        'references': file_hashes(sorted(glob.glob(os.path.join(WAYPOINT_DIR, '*.csv')))),
        'terrain_json': file_hashes([TERRAIN_JSON]),
        'episodes_file': {episodes_file: sha256_file(episodes_file)},
    }


# --------------------------------------------------------------------------- worker side
def force_worker_env():
    """The environment every worker runs with (also applied in the supervisor before it records the host
    fingerprint and spawns workers, so both see the same values)."""
    for k in ('OMP_NUM_THREADS', 'MKL_NUM_THREADS', 'OPENBLAS_NUM_THREADS'):
        os.environ[k] = '1'
    os.environ['KERAS_BACKEND'] = 'torch'
    os.environ['CUDA_VISIBLE_DEVICES'] = ''


def worker_init():
    # The released MPC creates OSQP problems with the default verbose=True and keras
    # may print; this text goes to the worker's stdout. Discard it at fd level (no
    # numerical effect; printing to a pipe cost ~9 ms per MPC tick).
    devnull = os.open(os.devnull, os.O_WRONLY)
    os.dup2(devnull, 1)
    force_worker_env()
    import torch
    torch.set_num_threads(1)
    from art_runner.episode import ControllerPool
    global POOL
    POOL = ControllerPool()


def worker_run(args):
    cfg, out_root = args[0], args[1]
    prov = args[2] if len(args) > 2 else None
    from art_runner.episode import run_episode_to_dir
    t0 = time.perf_counter()
    try:
        s = run_episode_to_dir(cfg, POOL, out_root, provenance=prov)
    except Exception as e:
        s = {'episode_id': cfg['episode_id'], 'scenario_id': cfg['scenario_id'], 'controller': cfg['controller'],
             'status': 'infrastructure_error', 'outcome': None, 'config_hash': cfgmod.config_hash(cfg),
             'failure': {'category': 'infrastructure', 'error': f'{type(e).__name__}: {e}',
                         'traceback': traceback.format_exc()[-6000:]},
             'wall': {'total_s': time.perf_counter() - t0}, 'provenance': prov}
    s['worker_pid'] = os.getpid()
    return s


def worker_main(conn, out_root):
    """Long-lived supervised worker: init once, then run one episode per message until None/EOF."""
    signal.signal(signal.SIGINT, signal.SIG_IGN)  # the supervisor decides when workers stop
    try:
        worker_init()
        conn.send(('ready', os.getpid(), worker_fingerprint_fields(host_record(with_mkl=False))))
    except BaseException:
        try:
            conn.send(('init_failed', os.getpid(), traceback.format_exc()[-4000:]))
        finally:
            return
    while True:
        try:
            task = conn.recv()
        except (EOFError, OSError):
            return
        if task is None:
            return
        cfg, prov = task
        conn.send(('result', worker_run((cfg, out_root, prov))))


# --------------------------------------------------------------------------- summaries
def flatten(s):
    w = s.get('wall') or {}
    f = s.get('failure') or {}
    p = s.get('provenance') or {}
    row = {k: s.get(k) for k in SUMMARY_FIELDS}
    row.update({'wall_total_s': w.get('total_s'), 'wall_init_s': w.get('init_s'), 'wall_stepping_s': w.get('stepping_s'),
                'wall_controller_s': w.get('controller_s'), 'wall_other_s': w.get('other_s'),
                'failure_category': f.get('category'), 'failure_t': f.get('t'),
                'run_id': s.get('run_id', p.get('run_id')), 'attempt': p.get('attempt'),
                'code_digest': p.get('code_digest'), 'host_fingerprint': p.get('host_fingerprint')})
    mo = s.get('mpc_osqp') or {}
    row.update({'mpc_osqp_n_solves': mo.get('n_solves'), 'mpc_osqp_n_not_solved': mo.get('n_not_solved'),
                'mpc_osqp_iter_mean': mo.get('iter_mean'), 'mpc_osqp_iter_max': mo.get('iter_max')})
    return row


def rebuild_summary_csv(out_root):
    rows = []
    for p in sorted(glob.glob(os.path.join(out_root, 'episodes', '*', 'summary.json'))):
        with open(p) as f:
            rows.append(flatten(json.load(f)))
    rows.sort(key=lambda r: r['episode_id'])
    with open(os.path.join(out_root, 'summary.csv'), 'w', newline='') as f:
        w = csv.DictWriter(f, fieldnames=SUMMARY_FIELDS)
        w.writeheader()
        for r in rows:
            w.writerow(r)
    return len(rows)


def check_resume(out, prov, allow_host_change):
    """Refuse to mix results produced by different code or on different hosts in one OUT directory."""
    code_bad, host_bad, legacy = [], [], []
    for path in sorted(glob.glob(os.path.join(out, 'manifest_*.json'))):
        with open(path) as f:
            p = (json.load(f).get('provenance') or {})
        (legacy if not p.get('code_digest') else code_bad if p['code_digest'] != prov['code_digest'] else
         host_bad if p.get('host_fingerprint') != prov['host_fingerprint'] else []).append(os.path.basename(path))
    for path in sorted(glob.glob(os.path.join(out, 'episodes', '*', 'summary.json'))):
        with open(path) as f:
            p = (json.load(f).get('provenance') or {})
        name = os.path.basename(os.path.dirname(path))
        (legacy if not p.get('code_digest') else code_bad if p['code_digest'] != prov['code_digest'] else
         host_bad if p.get('host_fingerprint') != prov['host_fingerprint'] else []).append(name)
    msgs = []
    if legacy:
        msgs.append(f'{len(legacy)} manifest/summary files without provenance (older runner version), e.g. {legacy[:3]}')
    if code_bad:
        msgs.append(f'{len(code_bad)} manifest/summary files with a different code digest, e.g. {code_bad[:3]}')
    if host_bad and not allow_host_change:
        msgs.append(f'{len(host_bad)} manifest/summary files with a different host fingerprint, e.g. {host_bad[:3]} '
                    '(--allow-host-change only after a bytewise cross-host reference check)')
    return msgs, host_bad


def move_stale_tmp(out):
    moved = []
    for d in sorted(glob.glob(os.path.join(out, 'episodes', '.tmp_*'))):
        dst = os.path.join(out, 'infrastructure_errors', 'stale_tmp',
                           f'{os.path.basename(d)}_{int(time.time() * 1e3)}')
        os.makedirs(os.path.dirname(dst), exist_ok=True)
        os.rename(d, dst)
        moved.append(os.path.relpath(dst, out))
    return moved


# --------------------------------------------------------------------------- supervisor
class _Stop(Exception):
    def __init__(self, code, status):
        super().__init__(status)
        self.code, self.status = code, status


class Worker:
    def __init__(self, ctx, out_root, idx):
        self.conn, child = ctx.Pipe(duplex=True)
        self.proc = ctx.Process(target=worker_main, args=(child, out_root), name=f'tr-c1-worker-{idx}', daemon=True)
        self.proc.start()
        child.close()
        self.pid = self.proc.pid
        self.ready = False
        self.task = None  # (cfg, attempt)
        self.t_start = None
        self.timeout = None

    def kill(self):
        try:
            if self.proc.is_alive():
                os.kill(self.pid, signal.SIGKILL)
        except ProcessLookupError:
            pass
        self.proc.join(timeout=10)
        try:
            self.conn.close()
        except Exception:
            pass


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument('--episodes', required=True)
    ap.add_argument('--out', required=True)
    ap.add_argument('--workers', type=int, default=1)
    ap.add_argument('--limit', type=int, default=None, help='run at most this many pending episodes')
    ap.add_argument('--max-retries', type=int, default=2, help='retries of an infrastructure error in this invocation')
    ap.add_argument('--episode-timeout-base-s', type=float, default=120.0)
    ap.add_argument('--episode-timeout-factor', type=float, default=6.0, help='wall seconds per simulated horizon second')
    ap.add_argument('--stall-timeout-s', type=float, default=None)
    ap.add_argument('--heartbeat-s', type=float, default=30.0)
    ap.add_argument('--allow-host-change', action='store_true',
                    help='resume an OUT written with a different host fingerprint (recorded; code digest must match)')
    a = ap.parse_args()
    # worker cap: TR_MAX_WORKERS (default 12, never more than nproc - 2).
    cap = min(int(os.environ.get('TR_MAX_WORKERS', '12')), max(1, (os.cpu_count() or 8) - 2))
    if not 1 <= a.workers <= cap:
        sys.exit(f'workers must be 1..{cap} (shared machine limit; TR_MAX_WORKERS)')
    episodes = cfgmod.load_episode_list(a.episodes)
    out = os.path.abspath(a.out)
    os.makedirs(os.path.join(out, 'episodes'), exist_ok=True)

    force_worker_env()
    host = host_record(with_mkl=True)
    code = code_record()
    run_id = _dt.datetime.now(_dt.timezone.utc).strftime('%Y%m%dT%H%M%SZ') + f'_{os.getpid()}'
    prov = {'code_digest': _digest(code), 'host_fingerprint': host_fingerprint(host), 'host_name': host['host_name'],
            'cpu_model': host['cpu_model'], 'run_id': run_id}
    problems, host_changed = check_resume(out, prov, a.allow_host_change)
    if problems:
        sys.exit('refusing to resume into ' + out + ':\n  ' + '\n  '.join(problems) +
                 '\nuse a new --out directory for this code version / host')
    stale = move_stale_tmp(out)

    todo, skipped = [], 0
    for cfg in episodes:
        sp = os.path.join(out, 'episodes', cfg['episode_id'], 'summary.json')
        if os.path.exists(sp):
            with open(sp) as f:
                old = json.load(f)
            if old.get('config_hash') != cfgmod.config_hash(cfg):
                sys.exit(f"episode {cfg['episode_id']} already exists with a different config hash; refusing")
            skipped += 1
            continue
        todo.append(cfg)
    if a.limit is not None:
        todo = todo[:a.limit]

    def ep_timeout(cfg):
        return a.episode_timeout_base_s + a.episode_timeout_factor * float(cfg['horizon_s'])

    manifest = {'run_id': run_id, 'started_utc': _now(), 'workers': a.workers, 'episodes_file': os.path.abspath(a.episodes),
                'n_episodes_in_file': len(episodes), 'n_skipped_existing': skipped, 'n_scheduled': len(todo),
                'config_hashes': {c['episode_id']: cfgmod.config_hash(c) for c in episodes},
                'schema_version': cfgmod.SCHEMA_VERSION, 'environment': environment_record(host),
                'input_sha256': input_hashes(os.path.abspath(a.episodes)), 'status': 'running',
                'provenance': prov, 'code_record': code,
                'resume': {'allow_host_change': a.allow_host_change, 'host_changed_entries': len(host_changed),
                           'stale_tmp_moved': stale},
                'supervisor': {'max_retries': a.max_retries, 'episode_timeout_base_s': a.episode_timeout_base_s,
                               'episode_timeout_factor': a.episode_timeout_factor, 'stall_timeout_s': a.stall_timeout_s,
                               'heartbeat_s': a.heartbeat_s}}
    mpath = os.path.join(out, f'manifest_{run_id}.json')
    hpath = os.path.join(out, f'heartbeat_{run_id}.json')
    _write_json_atomic(mpath, manifest)
    print(f'[campaign] run {run_id}: {len(todo)} scheduled, {skipped} already complete, {a.workers} workers; '
          f'code {prov["code_digest"][:12]} host {prov["host_fingerprint"][:12]} ({host["host_name"]})', flush=True)
    if stale:
        print(f'[campaign] moved {len(stale)} stale .tmp directories to infrastructure_errors/stale_tmp/', flush=True)

    t0 = time.perf_counter()
    counts, per_episode, infra_events, exhausted = {}, [], [], []
    walls = []
    jsonl = open(os.path.join(out, 'summary.jsonl'), 'a')
    exit_code, status = EXIT_OK, 'complete'
    queue = collections.deque((c, 0) for c in todo)
    n_final = 0  # episodes finished for good (ok, or infrastructure error with retries exhausted)
    workers = []
    expected_wfp = worker_fingerprint_fields(host)
    init_failures = 0

    def on_signal(signum, frame):
        raise _Stop(EXIT_SIGTERM if signum == signal.SIGTERM else EXIT_SIGINT,
                    'interrupted_sigterm' if signum == signal.SIGTERM else 'interrupted_sigint')

    signal.signal(signal.SIGTERM, on_signal)
    signal.signal(signal.SIGINT, on_signal)

    def emit(s):
        jsonl.write(json.dumps(flatten(s), default=str) + '\n')
        jsonl.flush()

    def handle_infra(cfg, attempt, s, kind):
        nonlocal n_final
        ev = {'utc': _now(), 'episode_id': cfg['episode_id'], 'attempt': attempt, 'kind': kind,
              'error': (s.get('failure') or {}).get('error'), 'worker_pid': s.get('worker_pid')}
        if attempt < a.max_retries:
            queue.append((cfg, attempt + 1))
            ev['action'] = f'retry {attempt + 1}/{a.max_retries}'
            key = 'infrastructure_error/retried'
        else:
            exhausted.append(cfg['episode_id'])
            ev['action'] = 'exhausted (left for the next invocation)'
            key = 'infrastructure_error/exhausted'
            n_final += 1
        counts[key] = counts.get(key, 0) + 1
        infra_events.append(ev)
        print(f"[campaign] INFRASTRUCTURE {cfg['episode_id']} attempt {attempt} ({kind}): {ev['error']} -> {ev['action']}",
              flush=True)

    def lost_episode(w, reason, kind):
        cfg, attempt = w.task
        eid = cfg['episode_id']
        errdir = os.path.join(out, 'infrastructure_errors', f'{eid}_{int(time.time() * 1e3)}_{w.pid}')
        os.makedirs(os.path.dirname(errdir), exist_ok=True)
        tmp = os.path.join(out, 'episodes', f'.tmp_{eid}_{w.pid}')
        if os.path.isdir(tmp):
            os.rename(tmp, errdir)
        else:
            os.makedirs(errdir)
        if os.path.exists(os.path.join(errdir, 'summary.json')):
            os.rename(os.path.join(errdir, 'summary.json'), os.path.join(errdir, 'summary_from_worker.json'))
        s = {'episode_id': eid, 'scenario_id': cfg['scenario_id'], 'controller': cfg['controller'],
             'status': 'infrastructure_error', 'outcome': None, 'config_hash': cfgmod.config_hash(cfg),
             'failure': {'category': 'infrastructure', 'kind': kind, 'error': reason},
             'wall': {'total_s': time.monotonic() - w.t_start}, 'worker_pid': w.pid,
             'provenance': dict(prov, attempt=attempt), 'run_id': run_id}
        _write_json_atomic(os.path.join(errdir, 'summary.json'), s)
        emit(s)
        w.task = None
        handle_infra(cfg, attempt, s, kind)

    def handle_msg(w, msg):
        nonlocal n_final, init_failures
        if msg[0] == 'ready':
            if msg[2] != expected_wfp:
                raise _Stop(EXIT_WORKER_START, 'failed_worker_environment_mismatch')
            w.ready = True
        elif msg[0] == 'init_failed':
            init_failures += 1
            infra_events.append({'utc': _now(), 'kind': 'worker_init_failed', 'worker_pid': msg[1], 'error': msg[2]})
            print(f'[campaign] worker {msg[1]} failed to start:\n{msg[2]}', flush=True)
            if init_failures >= 3:
                raise _Stop(EXIT_WORKER_START, 'failed_worker_start')
        elif msg[0] == 'result':
            s = msg[1]
            cfg, attempt = w.task
            w.task = None
            s['run_id'] = run_id
            emit(s)
            wall = (s.get('wall') or {})
            if s.get('status') == 'infrastructure_error':
                handle_infra(cfg, attempt, s, 'returned_by_worker')
            else:
                key = f"{s.get('status')}/{s.get('outcome')}"
                counts[key] = counts.get(key, 0) + 1
                n_final += 1
                if wall.get('total_s') is not None:
                    walls.append(wall['total_s'])
                print(f"[campaign] {n_final}/{len(todo)} {s['episode_id']} {key} "
                      f"wall={wall.get('total_s', float('nan')):.2f}s", flush=True)
            per_episode.append({'episode_id': s['episode_id'], 'controller': s.get('controller'), 'attempt': attempt,
                                'status': s.get('status'), 'sim_s': s.get('sim_s'), 'wall': wall,
                                'worker_pid': s.get('worker_pid')})

    def stall_limit():
        if a.stall_timeout_s is not None:
            return a.stall_timeout_s
        med = statistics.median(walls) if walls else 0.0
        running = [w.timeout for w in workers if w.task is not None] or [0.0]
        return max(900.0, 10.0 * med, 1.5 * max(running))

    def write_heartbeat(state):
        now = time.monotonic()
        _write_json_atomic(hpath, {'run_id': run_id, 'utc': _now(), 'status': state, 'n_final': n_final,
                                   'n_scheduled': len(todo), 'queue': len(queue), 'counts': counts,
                                   'seconds_since_progress': now - last_progress, 'stall_limit_s': stall_limit(),
                                   'running': [{'episode_id': w.task[0]['episode_id'], 'attempt': w.task[1],
                                                'worker_pid': w.pid, 'elapsed_s': now - w.t_start,
                                                'timeout_s': w.timeout} for w in workers if w.task]})

    last_progress = time.monotonic()
    try:
        if todo:
            ctx = mp.get_context('spawn')
            workers = [Worker(ctx, out, i) for i in range(min(a.workers, len(todo)))]
            spawned = len(workers)
            last_hb = 0.0
            while queue or any(w.task for w in workers):
                for w in workers:  # assign work to idle, initialised workers
                    if w.ready and w.task is None and queue:
                        cfg, attempt = queue.popleft()
                        w.task, w.t_start, w.timeout = (cfg, attempt), time.monotonic(), ep_timeout(cfg)
                        try:
                            w.conn.send((cfg, dict(prov, attempt=attempt)))
                        except (BrokenPipeError, OSError):
                            pass  # the worker died; the death check below records the episode and retries it
                mpc.wait([w.conn for w in workers] + [w.proc.sentinel for w in workers], timeout=2.0)
                for i, w in enumerate(list(workers)):
                    dead = False
                    try:
                        while w.conn.poll():
                            before = n_final
                            handle_msg(w, w.conn.recv())
                            if n_final != before or not w.task:
                                last_progress = time.monotonic()
                    except (EOFError, OSError):
                        dead = True
                    now = time.monotonic()
                    timed_out = w.task is not None and now - w.t_start > w.timeout
                    if timed_out:
                        w.kill()
                        lost_episode(w, f'episode wall-clock timeout after {now - w.t_start:.1f} s '
                                        f'(limit {w.timeout:.1f} s); worker {w.pid} killed', 'episode_timeout')
                        last_progress = time.monotonic()
                    elif dead or not w.proc.is_alive():
                        w.proc.join(timeout=5)
                        code_ = w.proc.exitcode
                        w.kill()
                        if w.task is not None:
                            lost_episode(w, f'worker process {w.pid} died (exitcode {code_}) while running the episode',
                                         'worker_lost')
                            last_progress = time.monotonic()
                    else:
                        continue
                    if queue or any(x.task for x in workers if x is not w):
                        workers[i] = Worker(ctx, out, spawned)
                        spawned += 1
                    else:
                        workers[i] = None
                workers = [w for w in workers if w is not None]
                if queue and not workers:
                    workers = [Worker(ctx, out, spawned)]
                    spawned += 1
                now = time.monotonic()
                if now - last_progress > stall_limit():
                    raise _Stop(EXIT_STALLED, 'stalled')
                if now - last_hb > a.heartbeat_s:
                    write_heartbeat('running')
                    last_hb = now
        if exhausted:
            exit_code, status = EXIT_INFRA, 'complete_with_infrastructure_errors'
    except _Stop as e:
        exit_code, status = e.code, e.status
        print(f'[campaign] STOP: {status}', flush=True)
    finally:
        signal.signal(signal.SIGTERM, signal.SIG_DFL)
        signal.signal(signal.SIGINT, signal.SIG_DFL)
        for w in workers:
            if w.task is None and w.proc.is_alive():
                try:
                    w.conn.send(None)
                except Exception:
                    pass
        for w in workers:
            w.proc.join(timeout=5 if w.task is None else 0)
            w.kill()
        jsonl.close()
        n_rows = rebuild_summary_csv(out)
        manifest.update({'finished_utc': _now(), 'wall_s': time.perf_counter() - t0, 'counts': counts,
                         'per_episode_wall': per_episode, 'summary_csv_rows': n_rows, 'status': status,
                         'exit_code': exit_code, 'infrastructure_events': infra_events,
                         'infrastructure_exhausted': exhausted,
                         'unfinished_at_stop': [w.task[0]['episode_id'] for w in workers if w.task] + [c['episode_id'] for c, _ in queue]})
        _write_json_atomic(mpath, manifest)
        try:
            write_heartbeat(status)
        except Exception:
            pass
    print(f'[campaign] {status} in {manifest["wall_s"]:.1f}s: {counts}', flush=True)
    sys.exit(exit_code)


if __name__ == '__main__':
    main()