File size: 38,385 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
"""Lock-step episode loop, schedules, logging and outcome classification (NEW CODE).

Timing semantics (all in integer 1 ms physics steps; "boundary n" = after n
physics iterations, sim time n*1e-3 s):

ideal
    controller tick j at boundary S_j = c0 + j*P (P = 100);
    observation = true chassis state at boundary S_j;
    command applied with driver->Set* at boundary S_j + d (d = extra actuation
    delay, default 0), i.e. it drives iterations S_j+d, S_j+d+1, ...

ros_emulated  (ChROSManager / ChROSHandler semantics of the image)
    ChROSHandler::Update accumulator (ChROSHandler.cpp:28-40) replicated with the
    same double arithmetic for the 25 Hz ChROSBodyHandler and the 10 Hz
    ChROSDriverInputsHandler. A handler tick in iteration k happens after the
    physics step of iteration k (demo_ROS_dART.cpp:332-348), i.e. at boundary
    k+1, with the post-step state.
    state publication (25 Hz)  -> visible to the controller from boundary k+1+sd;
    controller tick j at boundary S_j = c0 + phase + j*P uses the latest
    visible publication (state_callback/vel_callback of the released node);
    its DriverInputs message arrives at boundary b_j = S_j + cd + d (compute
    delay cd, extra delay d) and overwrites the handler's stored inputs
    (ChROSDriverInputsHandler::Callback, keep-last);
    driver tick (10 Hz) in iteration k applies the stored inputs (messages with
    b <= k) via driver->SetSteering/SetThrottle/SetBraking
    (ChROSDriverInputsHandler::Tick); the vehicle uses them from iteration k+1
    (GetInputs at the top of the loop, demo_ROS_dART.cpp:332).
    Within one boundary the order is: driver tick, state publication, 100 Hz
    log, controller tick (ideal: then delayed application).
"""
import gzip
import io
import json
import math
import os
import shutil
import time
import traceback

import numpy as np

from . import config as cfgmod
from .metrics import (SPIN_CRITERION, ProgressTracker, audit_errors, divergence_events, error_state_vec,
                      first_tube_entry, nearest_index, spin_events)
from .physics import DEFAULT_BINARY, PhysicsError, PhysicsServer
from .references import build_reference
from .released import (OSQP_INFO_FIELDS, ReleasedController, classify_controller_exception, load_released_module,
                       make_messages, osqp_diag_take, set_osqp_adaptive_rho_interval, sha256_file)

DT = cfgmod.DT
COG_OFFSET_XY = (-0.1336, -0.0014)  # ARTcar chassis COM in the chassis reference frame (state at step 0)
TERRAIN_DEFAULT = '/sbel/Desktop/chrono/build/data/vehicle/terrain/RigidPlane.json'
TERRAIN_DEFAULT_FRICTION = 0.9  # RigidPlane.json "Coefficient of Friction"

TICK_COLUMNS = ['tick', 'step', 't', 't_ctrl', 'status', 'obs_pub_step', 'obs_age_steps',
                'x', 'y', 'z', 'yaw', 'yaw_unwrapped', 'speed', 'vx', 'vy', 'yaw_rate',
                'obs_x', 'obs_y', 'obs_theta', 'obs_v',
                'e0', 'e1', 'e2', 'e3', 'et0', 'et1', 'et2', 'et3',
                'idx_lookahead', 'idx_track', 'arc_s_track',
                'raw_throttle', 'raw_steering', 'rl_steering', 'rate_limited',
                'published', 'pub_steering', 'pub_throttle', 'pub_braking',
                'apply_step', 'applied_steering', 'applied_throttle', 'applied_braking',
                'drv_steering', 'drv_throttle', 'drv_braking', 'compute_wall_s']
STATE_COLUMNS = ['step', 't', 'x', 'y', 'z', 'yaw', 'yaw_unwrapped', 'speed', 'vx', 'vy', 'yaw_rate',
                 'in_steering', 'in_throttle', 'in_braking',
                 'e_long', 'e_lat', 'e_head', 'e_speed', 'nearest_idx', 'arc_s', 'progress_idx', 'dist_min']
WALL_COLUMNS = {'compute_wall_s'}  # excluded from determinism comparisons
# Side files, written only when they have rows:
#  mpc_diag.csv.gz  one row per osqp.OSQP.solve() made during a controller tick (released MPC and
#                   MPC-based plug-ins); read-only copy of res.info. Wall-clock columns: MPC_DIAG_WALL_COLUMNS.
#  obs_noise.csv.gz one row per controller tick that observed a state under observation noise.
MPC_DIAG_COLUMNS = (['tick', 'step', 'solve_index'] + list(OSQP_INFO_FIELDS) +
                    ['adaptive_rho_interval_requested', 'setup_max_iter', 'setup_warm_start', 'qp_n', 'qp_m',
                     'diag_error'])
MPC_DIAG_WALL_COLUMNS = {'setup_time', 'solve_time', 'update_time', 'polish_time', 'run_time'}
OBS_NOISE_COLUMNS = ['tick', 'step', 'obs_pub_step', 'z_x', 'z_y', 'z_yaw', 'noise_x', 'noise_y', 'noise_yaw']
SUMMARY_H_WINDOWS_S = (15.0, 25.0, 40.0)  # H = 15 / 25 / 40 s scored offline from one 40 s log

# Observation noise (channel conditions D3/D5). The noise of the state PUBLICATION at physics boundary k (ros_emulated:
# a 25 Hz ChROSBodyHandler publication; ideal: the observation boundary = the tick boundary) is
#     z = numpy.random.default_rng(numpy.random.SeedSequence([7301, seed, k])).standard_normal(3)
#     (noise_x, noise_y, noise_yaw) = (std_x z[0], std_y z[1], std_yaw z[2])   (exactly 0.0 where std = 0)
# All three components are always drawn, so (i) conditions that differ only in the std values see the same z
# (common random numbers across noise levels), (ii) every controller of a scenario sees the same noise on the same
# publication, and (iii) a publication observed by more than one tick carries the same noise. 7301 is a fixed
# domain tag that separates this stream from every campaign scenario seed sequence ([20261019, ...]).
OBS_NOISE_DOMAIN = 7301
OBS_NOISE_MODEL = 'per_publication_v2: SeedSequence([7301, obs_noise.seed, obs_pub_step]) -> standard_normal(3) x std'


def obs_noise_standard_normals(seed, pub_step):
    return np.random.default_rng(np.random.SeedSequence([OBS_NOISE_DOMAIN, int(seed), int(pub_step)])).standard_normal(3)


# ---------------------------------------------------------------------------
def handler_tick_iterations(rate_hz, n_iters, step=DT):
    """Iterations k (0-based) in which ChROSHandler::Update calls Tick()."""
    frame_time = 0 if rate_hz == 0 else 1 / rate_hz
    acc = 0.0
    out = []
    for k in range(n_iters):
        acc += step
        if acc < frame_time:
            continue
        acc -= frame_time
        out.append(k)
    return out


def yaw_released(e0, e1, e2, e3):
    """path_follower.py:123-127 with the ChROSBodyHandler field mapping."""
    return np.arctan2(2 * (e0 * e3 + e1 * e2), e0 ** 2 + e1 ** 2 - e2 ** 2 - e3 ** 2)


def yaw_rate_global(st):
    e0, e1, e2, e3 = st['q_e0'], st['q_e1'], st['q_e2'], st['q_e3']
    r20 = 2 * (e1 * e3 - e0 * e2)
    r21 = 2 * (e2 * e3 + e0 * e1)
    r22 = e0 * e0 - e1 * e1 - e2 * e2 + e3 * e3
    return r20 * st['wloc_x'] + r21 * st['wloc_y'] + r22 * st['wloc_z']


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)):
        return repr(float(v))
    return str(v)


def write_csv_gz(path, columns, rows):
    buf = io.StringIO()
    buf.write(','.join(columns) + '\n')
    for r in rows:
        buf.write(','.join(_fmt(r.get(c)) for c in columns) + '\n')
    with open(path, 'wb') as raw:
        with gzip.GzipFile(fileobj=raw, mode='wb', mtime=0, compresslevel=6) as gz:
            gz.write(buf.getvalue().encode())


def friction_terrain_json(mu, workdir):
    with open(TERRAIN_DEFAULT) as f:
        spec = json.load(f)
    spec['Patches'][0]['Contact Material']['Coefficient of Friction'] = float(mu)
    path = os.path.join(workdir, f'RigidPlane_mu_{float(mu)!r}.json')
    with open(path, 'w') as f:
        json.dump(spec, f, indent=2)
    return path


# ---------------------------------------------------------------------------
class ControllerPool:
    """Per-worker cache: released module and models loaded once; a FRESH
    ControlNode / plug-in state is constructed for every episode."""

    def __init__(self):
        self.module = None
        self.released = {}

    def get(self, name, params):
        if self.module is None:
            self.module = load_released_module()
        if name in cfgmod.RELEASED:
            if name not in self.released:
                self.released[name] = ReleasedController(name, self.module)
            return self.released[name]
        from .plugins import PluginController, make_plugin
        return PluginController(make_plugin(name.split(':', 1)[1], params, self.module), self.module)


def initial_chassis_pose(pose):
    x, y, yaw = pose['x'], pose['y'], pose['yaw']
    if pose['frame'] == 'cog':
        c, s = math.cos(yaw), math.sin(yaw)
        ox, oy = COG_OFFSET_XY
        x, y = x - (c * ox - s * oy), y - (s * ox + c * oy)
    return x, y, yaw


def run_episode(cfg, pool, workdir, binary=None, server_timeout_s=120.0):
    """Run one normalized episode config; write logs into workdir. Returns summary dict."""
    t_wall0 = time.perf_counter()
    lat = cfg['latency']
    pert = cfg['perturbation']
    term = cfg['termination']
    N = cfgmod.to_steps(cfg['horizon_s'], 'horizon_s')
    c0 = cfgmod.to_steps(cfg['control_start_s'], 'control_start_s')
    P = cfgmod.to_steps(lat['controller_period_s'], 'controller_period_s')
    d_act = cfgmod.to_steps(pert['actuation_delay_s'], 'actuation_delay_s')
    ros = lat['model'] == 'ros_emulated'
    if ros:
        phase = cfgmod.to_steps(lat['controller_phase_s'], 'controller_phase_s')
        cd = cfgmod.to_steps(lat['compute_delay_s'], 'compute_delay_s')
        sd = cfgmod.to_steps(lat['state_delay_s'], 'state_delay_s')
    else:
        phase = cd = sd = 0
    tick_steps = list(range(c0 + phase, N, P))
    tick_set = {s: j for j, s in enumerate(tick_steps)}
    log_set = set(range(0, N + 1, 10))
    pub_set = {k + 1 for k in handler_tick_iterations(lat['state_rate_hz'], N)} if ros else set()
    drv_set = {k + 1 for k in handler_tick_iterations(lat['driver_rate_hz'], N)} if ros else set()
    apply_set = {s + d_act: j for j, s in enumerate(tick_steps)} if (not ros and d_act > 0) else {}
    events = sorted(log_set | set(tick_set) | pub_set | drv_set | {s for s in apply_set if s <= N})

    ref = build_reference(cfg['reference'])
    R = ref.array
    noise = pert['obs_noise']
    noisy = any(noise[k] > 0 for k in ('std_x', 'std_y', 'std_yaw'))
    bias = pert['steering_bias']

    summary = {'episode_id': cfg['episode_id'], 'scenario_id': cfg['scenario_id'], 'controller': cfg['controller'],
               'config_hash': cfgmod.config_hash(cfg), 'latency_model': lat['model'],
               'reference_sha256': ref.sha256, 'reference_length_m': ref.length}
    tick_rows, state_rows = [], []
    diag_rows, noise_rows = [], []
    walls = {'init_s': 0.0, 'stepping_s': 0.0, 'controller_s': 0.0}
    server = None
    status, outcome, failure = 'ok', None, None
    t_init0 = time.perf_counter()
    try:
        controller = pool.get(cfg['controller'], cfg['controller_params'])
        set_osqp_adaptive_rho_interval(cfg['mpc_osqp_adaptive_rho_interval'])
        summary['mpc_osqp_adaptive_rho_interval'] = cfg['mpc_osqp_adaptive_rho_interval']
        controller.reset(ref)
        if getattr(controller, 'kind', None) == 'plugin':
            summary['controller_params_effective'] = getattr(controller.plugin, 'p', None)
        terrain = None
        if pert['friction'] is not None:
            terrain = friction_terrain_json(pert['friction'], workdir)
        x0, y0, yaw0 = initial_chassis_pose(cfg['initial_pose'])
        boxes = None
        if cfg['replicate_waypoint_boxes']:
            if cfg['reference']['type'] != 'released_csv':
                raise cfgmod.ConfigError('replicate_waypoint_boxes requires a released_csv reference')
            boxes = list(ref.source_files)[0]
        server = PhysicsServer(x0, y0, yaw0, binary=binary or DEFAULT_BINARY, terrain_json=terrain,
                               waypoint_boxes=boxes, replicate_vis=cfg['replicate_visual_setters'],
                               timeout_s=server_timeout_s, stderr_path=os.path.join(workdir, 'server_stderr.txt'))
        walls['init_s'] = time.perf_counter() - t_init0
        summary['server_spawn_to_ready_s'] = server.spawn_to_ready_s
        summary['server_internal_init_s'] = server.server_init_s
        summary['server_ready_line'] = server.ready_line

        st = server.state
        n = 0
        tracker = ProgressTracker(R) if term['type'] == 'path_completion' else None
        pubs = []  # (avail_step, pub_step, state); avail_step is non-decreasing
        n_visible = 0
        m_inputs = (0.0, 0.0, 0.0)  # ChROSDriverInputsHandler m_inputs {0,0,0,0}
        pending = []  # ros: list of [b, (s,t,b), tick]
        ideal_cmd = {}
        controller_dead = False
        diverged_since = None
        completion_step = None
        stop_step = None
        hold_steps = cfgmod.to_steps(term['divergence_hold_s'], 'divergence_hold_s')
        margin_steps = cfgmod.to_steps(term['completion_margin_s'], 'completion_margin_s')
        yaw_prev, yaw_unwrapped = None, None
        tick_yaw_prev, tick_yaw_unw = None, None

        def apply(steer, thr, brk, at_step, tick_index):
            s_app, t_app, b_app = server.set_inputs(steer + bias, thr, brk)
            if tick_index is not None:
                r = tick_rows[tick_index]
                if r.get('apply_step') in (None, -1):
                    r.update({'apply_step': at_step, 'applied_steering': s_app, 'applied_throttle': t_app,
                              'applied_braking': b_app})
            return s_app, t_app, b_app

        for m in events:
            if stop_step is not None and m > stop_step:
                break
            if m > n:
                ts = time.perf_counter()
                st = server.step(m - n)
                walls['stepping_s'] += time.perf_counter() - ts
                n = m
            # 1) ros driver tick (iteration m-1)
            if m in drv_set:
                still = []
                for item in pending:
                    if item[0] <= m - 1:
                        m_inputs = item[1]
                        last_tick = item[2]
                    else:
                        still.append(item)
                delivered = len(still) != len(pending)
                pending = still
                # the tick re-applies the stored inputs every 100 ms (Tick() always calls Set*)
                cur_tick = last_tick if delivered else None
                apply(m_inputs[0], m_inputs[1], m_inputs[2], m, cur_tick)
            # 2) ros state publication (iteration m-1, post-step state)
            if m in pub_set:
                pubs.append((m + sd, m, st))
            # 3) 100 Hz state log + termination rules
            if m in log_set:
                q = (st['q_e0'], st['q_e1'], st['q_e2'], st['q_e3'])
                yaw = float(yaw_released(*q))
                yaw_unwrapped = yaw if yaw_prev is None else yaw_unwrapped + float(np.arctan2(np.sin(yaw - yaw_prev), np.cos(yaw - yaw_prev)))
                yaw_prev = yaw
                row = {'step': m, 't': st['time'], 'x': st['cog_x'], 'y': st['cog_y'], 'z': st['cog_z'], 'yaw': yaw,
                       'yaw_unwrapped': yaw_unwrapped, 'speed': math.sqrt(st['vel_x'] ** 2 + st['vel_y'] ** 2),
                       'vx': st['vel_x'], 'vy': st['vel_y'], 'yaw_rate': yaw_rate_global(st),
                       'in_steering': st['applied_steer'], 'in_throttle': st['applied_thr'],
                       'in_braking': st['applied_brake']}
                dmin = float(np.sqrt(((R[:, :2] - (st['cog_x'], st['cog_y'])) ** 2).sum(1).min()))
                row['dist_min'] = dmin
                if tracker is not None:
                    pidx, _, just = tracker.update(st['cog_x'], st['cog_y'])
                    row['progress_idx'] = pidx
                    if just:
                        completion_step = m
                        stop_step = min(N, m + margin_steps)
                state_rows.append(row)
                if dmin > term['divergence_dist_m']:
                    diverged_since = m if diverged_since is None else diverged_since
                    if m - diverged_since >= hold_steps and outcome is None:
                        outcome = 'diverged'
                        summary['divergence_step'] = diverged_since
                        if term['stop_on_divergence']:
                            stop_step = m
                else:
                    diverged_since = None
            # 4) controller tick
            if m in tick_set:
                j = tick_set[m]
                yaw = float(yaw_released(st['q_e0'], st['q_e1'], st['q_e2'], st['q_e3']))
                tick_yaw_unw = yaw if tick_yaw_prev is None else tick_yaw_unw + float(np.arctan2(np.sin(yaw - tick_yaw_prev), np.cos(yaw - tick_yaw_prev)))
                tick_yaw_prev = yaw
                row = {'tick': j, 'step': m, 't': st['time'], 't_ctrl': (m - c0) * DT,
                       'x': st['cog_x'], 'y': st['cog_y'], 'z': st['cog_z'], 'yaw': yaw, 'yaw_unwrapped': tick_yaw_unw,
                       'speed': math.sqrt(st['vel_x'] ** 2 + st['vel_y'] ** 2), 'vx': st['vel_x'], 'vy': st['vel_y'],
                       'yaw_rate': yaw_rate_global(st), 'published': False, 'apply_step': -1,
                       'drv_steering': st['drv_steer'], 'drv_throttle': st['drv_thr'], 'drv_braking': st['drv_brake']}
                tick_rows.append(row)
                if controller_dead:
                    row['status'] = 'controller_dead'
                    continue
                if ros:
                    while n_visible < len(pubs) and pubs[n_visible][0] <= m:
                        n_visible += 1
                    obs_state = pubs[n_visible - 1][2] if n_visible else None
                    row['obs_pub_step'] = pubs[n_visible - 1][1] if n_visible else None
                else:
                    obs_state = st
                    row['obs_pub_step'] = m
                if obs_state is not None:
                    row['obs_age_steps'] = m - row['obs_pub_step']
                    if noisy:  # noise indexed by the observed publication (see OBS_NOISE_MODEL)
                        z = obs_noise_standard_normals(noise['seed'], row['obs_pub_step'])
                        nz = tuple(float(noise[k] * z[i]) if noise[k] > 0 else 0.0
                                   for i, k in enumerate(('std_x', 'std_y', 'std_yaw')))
                        noise_rows.append({'tick': j, 'step': m, 'obs_pub_step': row['obs_pub_step'],
                                           'z_x': float(z[0]), 'z_y': float(z[1]), 'z_yaw': float(z[2]),
                                           'noise_x': nz[0], 'noise_y': nz[1], 'noise_yaw': nz[2]})
                    else:
                        nz = (0.0, 0.0, 0.0)
                    pose_msg, twist_msg = make_messages(obs_state, nz)
                    controller.observe(pose_msg, twist_msg)
                osqp_diag_take()  # discard any record not made by this tick (read-only diagnostics)
                res = controller.tick()
                for si, rec in enumerate(osqp_diag_take()):
                    diag_rows.append(dict(rec, tick=j, step=m, solve_index=si))
                walls['controller_s'] += res['compute_wall_s']
                row['compute_wall_s'] = res['compute_wall_s']
                for k in ('obs_x', 'obs_y', 'obs_theta', 'obs_v', 'raw_throttle', 'raw_steering', 'rate_limited'):
                    row[k] = res.get(k)
                row['rl_steering'] = res.get('ratelimited_steering')
                if res['e'] is not None:
                    for i in range(4):
                        row[f'e{i}'] = res['e'][i]
                        row[f'et{i}'] = res['e_track'][i]
                    th = row['obs_theta']
                    row['idx_lookahead'] = int(nearest_index(row['obs_x'], row['obs_y'], th, R, 1.0)[0])
                    row['idx_track'] = int(nearest_index(row['obs_x'], row['obs_y'], th, R, 0.0)[0])
                    row['arc_s_track'] = float(ref.arc[row['idx_track']])
                if res['exception'] is not None:
                    category, text = classify_controller_exception(res['exception'])
                    if category == 'infrastructure':
                        raise RuntimeError('bridge exception in controller tick:\n' + text)
                    row['status'] = category
                    failure = {'category': category, 'tick': j, 'step': m, 't': st['time'], 'traceback': text}
                    if outcome is None:
                        outcome = category
                    controller_dead = True  # released ROS node would crash here (exception escapes the timer callback)
                    if cfg['on_controller_failure'] == 'terminate':
                        stop_step = m
                    continue
                if not res['published']:
                    row['status'] = 'no_state'  # released pub_callback returns before the first pose
                    continue
                row['status'] = 'ok'
                row['published'] = True
                cmd = (res['pub_steering'], res['pub_throttle'], res['pub_braking'])
                row['pub_steering'], row['pub_throttle'], row['pub_braking'] = cmd
                if not all(math.isfinite(v) for v in cmd):
                    row['status'] = 'controller_nonfinite_output'
                    failure = {'category': 'controller_nonfinite_output', 'tick': j, 'step': m, 't': st['time']}
                    outcome = outcome or 'controller_nonfinite_output'
                    controller_dead = True
                    if cfg['on_controller_failure'] == 'terminate':
                        stop_step = m
                    continue
                if ros:
                    pending.append([m + cd + d_act, cmd, len(tick_rows) - 1])
                elif d_act == 0:
                    apply(cmd[0], cmd[1], cmd[2], m, len(tick_rows) - 1)
                else:
                    ideal_cmd[j] = (cmd, len(tick_rows) - 1)
            # 5) ideal delayed application
            if m in apply_set and apply_set[m] in ideal_cmd:
                cmd, ti = ideal_cmd.pop(apply_set[m])
                apply(cmd[0], cmd[1], cmd[2], m, ti)
        final_step = n
        summary['final_step'] = final_step
        summary['completion_step'] = completion_step
        if term['type'] == 'path_completion' and outcome is None:
            outcome = 'completed' if completion_step is not None else 'timeout'
        if outcome is None:
            outcome = 'horizon_reached'
    except Exception as e:  # anything raised by runner/bridge/physics client = INFRASTRUCTURE
        status = 'infrastructure_error'
        failure = {'category': 'infrastructure', 'error': f'{type(e).__name__}: {e}',
                   'traceback': traceback.format_exc()[-6000:]}
    finally:
        if server is not None:
            summary['server_returncode'] = server.close()
            summary['server_extra_output'] = server.extra_output[-50:]
            summary['physics_pure_step_wall_s'] = server.state.get('step_wall_s') if server.state else None
            summary['server_step_calls'] = server.step_calls

    # ---- post-processing: tracking errors at 100 Hz (released definitions, zero lookahead) ----
    if state_rows:
        S = np.array([[r['x'], r['y'], r['yaw'], r['speed']] for r in state_rows])
        E, idx = error_state_vec(S[:, 0], S[:, 1], S[:, 2], S[:, 3], R, 0.0)
        for r, e, i in zip(state_rows, E, idx):
            r['e_long'], r['e_lat'], r['e_head'], r['e_speed'] = (float(v) for v in e)
            r['nearest_idx'] = int(i)
            r['arc_s'] = float(ref.arc[i])
    c0_t = c0 * DT
    tl, th = term['tube_lat_m'], term['tube_head_rad']
    if state_rows:
        t = np.array([r['step'] for r in state_rows]) * DT - c0_t
        lat_e = np.array([r['e_lat'] for r in state_rows])
        head_e = np.array([r['e_head'] for r in state_rows])
        after = t >= 0
        te, k = first_tube_entry(t[after], lat_e[after], head_e[after], tl, th)
        summary['tube_entry_time_100hz_s'] = te
        if te is not None:
            ta, la, ha = t[after], lat_e[after], head_e[after]
            inside = (np.abs(la) < tl) & (np.abs(ha) < th)
            summary['fraction_inside_tube_after_entry'] = float(inside[k:].mean())
            summary['tube_exits_after_entry'] = int(np.sum(np.diff(inside[k:].astype(int)) == -1))
            outside = np.flatnonzero(~inside)
            # time after which the vehicle stays inside the tube until the end of the log (None if it ends outside)
            summary['stay_in_tube_time_100hz_s'] = (None if not inside[-1] else
                                                    float(ta[outside[-1] + 1]) if len(outside) else float(ta[0]))
        summary['max_abs_lat_100hz_m'] = float(np.abs(lat_e).max())
        summary['final_e_lat_m'] = float(lat_e[-1])
        summary['final_e_head_rad'] = float(head_e[-1])
        # ---- OFFLINE diagnostics, summary only (the logs and outcomes are unchanged) ----
        # metric variant: the same tube on the controller's 1 m LOOKAHEAD error (released
        # error_state(1.0), the only error the 2024-02-27 node 763603c computed) of the true 100 Hz COG state.
        EL, _ = error_state_vec(S[:, 0], S[:, 1], S[:, 2], S[:, 3], R, 1.0)
        te_la, _ = first_tube_entry(t[after], EL[after, 1], EL[after, 2], tl, th)
        summary['tube_entry_time_100hz_lookahead_s'] = te_la
        # spin / sliding diagnostic (criterion in metrics.SPIN_CRITERION)
        yr = np.array([r['yaw_rate'] for r in state_rows])
        k0, nflag, yrmax = spin_events(yr, S[:, 3], **{'yaw_rate_min': SPIN_CRITERION['yaw_rate_min_rad_s'],
                                                       'factor': SPIN_CRITERION['kinematic_factor'],
                                                       'r_min': SPIN_CRITERION['r_min_m'],
                                                       'n_consecutive': SPIN_CRITERION['min_consecutive_samples']})
        summary['spin_flag'] = k0 is not None
        summary['spin_first_step'] = None if k0 is None else int(state_rows[k0]['step'])
        summary['spin'] = {'flag': k0 is not None, 'first_step': summary['spin_first_step'], 'n_flagged_samples': nflag,
                           'max_abs_yaw_rate': yrmax, 'criterion': SPIN_CRITERION}
        summary['max_abs_yaw_rate_100hz'] = yrmax
        # start transient: step of the lowest COG z in the first 0.5 s (touchdown after the drop from z = 0.25 m)
        early = [r for r in state_rows if r['step'] <= 500]
        if early:
            summary['chassis_touchdown_step'] = int(min(early, key=lambda r: r['z'])['step'])
        # ---- recovery summary fields, OFFLINE (logs/outcomes unchanged) ----
        summary.update(recovery_summary_fields(state_rows, c0, tl, th, term, N, summary.get('divergence_step')))
    applied = [r for r in tick_rows if r.get('apply_step') not in (None, -1)]
    if applied:
        first = min(applied, key=lambda r: r['apply_step'])
        summary['first_command_apply_step'] = int(first['apply_step'])
        prior = [r for r in state_rows if r['step'] <= first['apply_step']]
        summary['cog_z_at_first_command_apply'] = float(prior[-1]['z']) if prior else None
    pub_rows = [r for r in tick_rows if r.get('published')]
    if pub_rows:
        tt = np.array([r['t_ctrl'] for r in pub_rows])
        te, _ = first_tube_entry(tt, np.array([r['et1'] for r in pub_rows]), np.array([r['et2'] for r in pub_rows]), tl, th)
        summary['tube_entry_time_tick_s'] = te
        # metric variant on the 10 Hz ticks: the controller's own lookahead error e[1], e[2]
        te_la, _ = first_tube_entry(tt, np.array([r['e1'] for r in pub_rows]), np.array([r['e2'] for r in pub_rows]), tl, th)
        summary['tube_entry_time_tick_lookahead_s'] = te_la
        # run MAE on the released-logger quantities (observed pose at published ticks), same definitions as the physical runs
        end_step = summary.get('completion_step') or (tick_rows[-1]['step'] if tick_rows else 0)
        rows = [r for r in pub_rows if r['step'] <= end_step]
        if rows:
            A, _ = audit_errors([r['obs_x'] for r in rows], [r['obs_y'] for r in rows], [r['obs_theta'] for r in rows], R)
            summary['run_mae_lateral_m'] = float(np.abs(A[:, 0]).mean())
            summary['run_mae_heading_rad'] = float(np.abs(A[:, 1]).mean())
            summary['run_mae_samples'] = len(rows)
    summary['n_ticks'] = len(tick_rows)
    summary['n_published'] = len(pub_rows)
    summary['n_rate_limited'] = int(sum(1 for r in pub_rows if r.get('rate_limited')))
    summary['n_state_rows'] = len(state_rows)
    summary['status'] = status
    summary['outcome'] = outcome if status == 'ok' else None
    summary['failure'] = failure
    walls['total_s'] = time.perf_counter() - t_wall0
    walls['other_s'] = walls['total_s'] - walls['init_s'] - walls['stepping_s'] - walls['controller_s']
    summary['obs_noise_model'] = OBS_NOISE_MODEL if noisy else None
    if diag_rows:
        summary['mpc_osqp'] = mpc_osqp_summary(diag_rows)
        walls['osqp_run_s'] = float(sum(r.get('run_time') or 0.0 for r in diag_rows))
    summary['wall'] = walls
    summary['sim_s'] = (summary.get('final_step') or 0) * DT
    write_csv_gz(os.path.join(workdir, 'ticks.csv.gz'), TICK_COLUMNS, tick_rows)
    write_csv_gz(os.path.join(workdir, 'state100.csv.gz'), STATE_COLUMNS, state_rows)
    names = ['ticks.csv.gz', 'state100.csv.gz']
    if diag_rows:
        write_csv_gz(os.path.join(workdir, 'mpc_diag.csv.gz'), MPC_DIAG_COLUMNS, diag_rows)
        names.append('mpc_diag.csv.gz')
    if noise_rows:
        write_csv_gz(os.path.join(workdir, 'obs_noise.csv.gz'), OBS_NOISE_COLUMNS, noise_rows)
        names.append('obs_noise.csv.gz')
    summary['files'] = {name: sha256_file(os.path.join(workdir, name)) for name in names}
    return summary


def mpc_osqp_summary(rows):
    """Deterministic aggregate of the per-solve OSQP records (no wall-clock field; those stay in mpc_diag.csv.gz and
    summary.wall.osqp_run_s)."""
    status = {}
    for r in rows:
        status[str(r.get('status'))] = status.get(str(r.get('status')), 0) + 1
    its = [int(r['iter']) for r in rows if r.get('iter') is not None]
    rhou = [int(r['rho_updates']) for r in rows if r.get('rho_updates') is not None]
    rhoe = [float(r['rho_estimate']) for r in rows if r.get('rho_estimate') is not None]
    return {'n_solves': len(rows), 'status_counts': status,
            'n_not_solved': sum(v for k, v in status.items() if k != 'solved'),
            'iter_total': int(sum(its)), 'iter_mean': float(np.mean(its)) if its else None,
            'iter_max': max(its) if its else None,
            'rho_updates_total': int(sum(rhou)), 'n_solves_with_rho_update': int(sum(1 for v in rhou if v > 0)),
            'rho_estimate_min': min(rhoe) if rhoe else None, 'rho_estimate_max': max(rhoe) if rhoe else None,
            'adaptive_rho_interval_requested': sorted({str(r.get('adaptive_rho_interval_requested')) for r in rows}),
            'qp_dims': sorted({f"{r.get('qp_n')}x{r.get('qp_m')}" for r in rows}),
            'n_diag_errors': int(sum(1 for r in rows if r.get('diag_error')))}


def recovery_summary_fields(state_rows, c0, tube_lat, tube_head, term, n_steps, online_divergence_step):
    """All from the 100 Hz true-state log (released
    error_state(0.0) e_lat / e_head; t relative to control start c0). Keys:
      horizon_mean_abs_e_lat_m / _head_rad   mean |e| over every 100 Hz sample from control start (t = 0) to the
                                             end of the log (the full simulated horizon); n = horizon_mean_n_samples
      horizon_mean_from_sim0_abs_e_lat_m / _head_rad   same over every sample from sim time 0 (differs only if c0 > 0)
      horizon_mean_covers_horizon            True if the log reaches the configured horizon (no early stop)
      by_H[H]                                for H in 15 / 25 / 40 s (if H <= horizon - c0): mean |e_lat|, |e_head|
                                             over 0 <= t <= H, first tube entry within [0, H], exits after entry
                                             within [0, H], covered (log reaches c0 + H)
      divergence_events                      offline replay of the ONLINE rule (dist_min > divergence_dist_m for
                                             >= divergence_hold_s on consecutive 100 Hz samples): start_step,
                                             fire_step, end_step (last sample beyond the distance; None if the run
                                             lasts to the end of the log); n_divergence_events; divergence_flag
      diverged_then_recovered                fired, and a tube entry occurs after the first fire step
      first_tube_entry_after_divergence_s    t of that entry (None otherwise)
      entered_then_diverged                  first tube entry happened before the first divergence run started
      returned_within_divergence_dist        the first divergence run ended before the end of the log
      divergence_offline_matches_online      online divergence_step == first offline start_step (None if no online)
    The post-entry exit count over the whole log is tube_exits_after_entry (unchanged)."""
    steps = np.array([r['step'] for r in state_rows], dtype=np.int64)
    lat = np.abs(np.array([r['e_lat'] for r in state_rows], dtype=float))
    head = np.abs(np.array([r['e_head'] for r in state_rows], dtype=float))
    dist = np.array([r['dist_min'] for r in state_rows], dtype=float)
    rel = steps - c0
    after = rel >= 0
    out = {}
    out['horizon_mean_abs_e_lat_m'] = float(lat[after].mean()) if after.any() else None
    out['horizon_mean_abs_e_head_rad'] = float(head[after].mean()) if after.any() else None
    out['horizon_mean_n_samples'] = int(after.sum())
    out['horizon_mean_from_sim0_abs_e_lat_m'] = float(lat.mean())
    out['horizon_mean_from_sim0_abs_e_head_rad'] = float(head.mean())
    out['horizon_mean_covers_horizon'] = bool(steps[-1] >= n_steps)
    inside = (lat < tube_lat) & (head < tube_head)
    by_h = {}
    for H in SUMMARY_H_WINDOWS_S:
        hs = int(round(H / DT))
        if c0 + hs > n_steps:
            continue
        w = after & (rel <= hs)
        if not w.any():
            continue
        ins = inside[w]
        k = np.flatnonzero(ins)
        by_h[f'{H:g}'] = {'abs_e_lat_m': float(lat[w].mean()), 'abs_e_head_rad': float(head[w].mean()),
                          'n_samples': int(w.sum()), 'covered': bool(steps[-1] >= c0 + hs),
                          'tube_entry_s': float(rel[w][k[0]] * DT) if len(k) else None,
                          'tube_exits_after_entry': (int(np.sum(np.diff(ins[k[0]:].astype(int)) == -1))
                                                     if len(k) else None)}
    out['by_H'] = by_h
    ev = divergence_events(steps, dist, term['divergence_dist_m'], int(round(term['divergence_hold_s'] / DT)))
    out['divergence_events'] = ev[:20]
    out['n_divergence_events'] = len(ev)
    out['divergence_flag'] = bool(ev)
    k_in = np.flatnonzero(after & inside)
    first_entry_step = int(steps[k_in[0]]) if len(k_in) else None
    if ev:
        fire = ev[0]['fire_step']
        later = np.flatnonzero(after & inside & (steps > fire))
        out['diverged_then_recovered'] = bool(len(later))
        out['first_tube_entry_after_divergence_s'] = float(rel[later[0]] * DT) if len(later) else None
        out['entered_then_diverged'] = bool(first_entry_step is not None and first_entry_step < ev[0]['start_step'])
        out['returned_within_divergence_dist'] = ev[0]['end_step'] is not None
    else:
        out['diverged_then_recovered'] = False
        out['first_tube_entry_after_divergence_s'] = None
        out['entered_then_diverged'] = False
        out['returned_within_divergence_dist'] = None
    out['divergence_offline_matches_online'] = (None if online_divergence_step is None else
                                                bool(ev and ev[0]['start_step'] == online_divergence_step))
    return out


def run_episode_to_dir(cfg, pool, out_root, binary=None, server_timeout_s=120.0, provenance=None):
    """Atomic, never-overwriting wrapper: episodes/<episode_id>/ appears only when complete.
    `provenance`: code digest, host fingerprint, run_id and attempt, written into
    summary.json; an existing summary with a different code digest or host fingerprint is never reused."""
    final = os.path.join(out_root, 'episodes', cfg['episode_id'])
    if os.path.exists(os.path.join(final, 'summary.json')):
        with open(os.path.join(final, 'summary.json')) as f:
            old = json.load(f)
        if old.get('config_hash') != cfgmod.config_hash(cfg):
            raise RuntimeError(f"episode {cfg['episode_id']} exists with a different config hash; refusing to overwrite")
        if provenance is not None:
            op = old.get('provenance') or {}
            for k in ('code_digest', 'host_fingerprint'):
                if op.get(k) != provenance.get(k):
                    raise RuntimeError(f"episode {cfg['episode_id']} exists with a different {k}; refusing to reuse it")
        old['_skipped_existing'] = True
        return old
    tmp = os.path.join(out_root, 'episodes', f".tmp_{cfg['episode_id']}_{os.getpid()}")
    if os.path.exists(tmp):
        shutil.rmtree(tmp)
    os.makedirs(tmp)
    with open(os.path.join(tmp, 'episode_config.json'), 'w') as f:
        json.dump(cfg, f, indent=1, sort_keys=True)
    summary = run_episode(cfg, pool, tmp, binary=binary, server_timeout_s=server_timeout_s)
    if provenance is not None:
        summary['provenance'] = dict(provenance)
        summary['run_id'] = provenance.get('run_id')
    with open(os.path.join(tmp, 'summary.json'), 'w') as f:
        json.dump(summary, f, indent=1, sort_keys=True, default=str)
    if summary['status'] != 'ok':
        # infrastructure errors are kept apart and can be retried; never mixed with outcomes
        errdir = os.path.join(out_root, 'infrastructure_errors', f"{cfg['episode_id']}_{int(time.time() * 1e3)}_{os.getpid()}")
        os.makedirs(os.path.dirname(errdir), exist_ok=True)
        os.rename(tmp, errdir)
        return summary
    os.rename(tmp, final)
    return summary