File size: 26,153 Bytes
6fbb45f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Monte Carlo episodes: MMPP traffic through a packet-level queueing network under six routers.



One episode samples a topology from its design cell, the failure/degradation timeline, F flows

between distinct ordered (source, sink) pairs whose mean rates realise the cell's offered load,

and each flow's Markov-modulated Poisson arrival stream. That identical scenario is then replayed

under every router, so any difference between routers is attributable to the routing policy

alone. The queueing model is deliberately explicit:



* every node owns one drop-tail FIFO buffer of ``buffer_size`` packets shared by all flows;

* every directed link forwards at most ``capacity`` packets per step, taking the oldest packets at

  its tail whose next hop crosses it (virtual output queueing, no head-of-line blocking);

* a packet forwarded at step t over a link of latency ℓ reaches the head node at step t + ℓ, where

  it is delivered (its flow's sink), admitted, or dropped if the buffer is full;

* routing decisions are recomputed every step (potential, potential_split, adaptive_shortest_path)

  or at every topology change (potential_static, shortest_path, ecmp).



Every step is vectorised with NumPy over the packets in flight; episodes are mapped across CPU

cores with ``multiprocessing.Pool`` and streamed to Parquet shard by shard.

"""
from __future__ import annotations

import multiprocessing as mp
import time
from dataclasses import dataclass
from functools import partial
from pathlib import Path
from typing import Dict, List

import numpy as np
import pyarrow as pa

from .config import SimConfig
from .design import RATE_SIGMA, Cell, TrafficProfile, locate
from .graph_generator import Topology, TopologyEvent, generate_timeline, generate_topology
from .physics_engine import (COST_QUANTUM, EcmpTable, LiveGraph, PotentialField, currents,
                             dijkstra_next_hops, live_graph, path_metrics, spray_next_hops,
                             steepest_next_hops)
from .telemetry_logger import SCHEMAS, completed_shards, list_column, write_shard

FIELD_ROUTER = "potential"  # the router whose potential field is stored


@dataclass(frozen=True)
class Flows:
    source: np.ndarray       # (F,) int16
    sink: np.ndarray         # (F,) int16
    mean_rate: np.ndarray    # (F,) float32 long-run packets/step
    idle_rate: np.ndarray    # (F,) float32
    burst_rate: np.ndarray   # (F,) float32
    min_hops: np.ndarray     # (F,) int16 on the base topology
    min_latency: np.ndarray  # (F,) int16 on the base topology
    total_capacity: float    # Σ over directed base links of capacity, packets/step


def sample_flows(cfg: SimConfig, cell: Cell, topo: Topology, base: LiveGraph,

                 rng: np.random.Generator) -> Flows:
    endpoints = topo.endpoints
    k = len(endpoints)
    n_flows = cfg.flows_per_endpoint * k
    pair = rng.choice(k * (k - 1), n_flows, replace=False)          # distinct ordered pairs
    si, ti = pair // (k - 1), pair % (k - 1)
    ti = ti + (ti >= si)
    source, sink = endpoints[si], endpoints[ti]
    min_hops, min_latency = path_metrics(base, source, sink)
    weight = np.exp(RATE_SIGMA * rng.standard_normal(n_flows))        # elephants and mice
    total_capacity = float(base.capacity.sum())
    mean = cell.load * total_capacity * weight / float(weight @ min_hops)
    idle, burst = cell.profile.rates(mean)
    return Flows(source, sink, mean.astype(np.float32), idle.astype(np.float32),
                 burst.astype(np.float32), min_hops, min_latency, total_capacity)


def sample_mmpp(cfg: SimConfig, profile: TrafficProfile, flows: Flows, rng: np.random.Generator):
    """Two-state MMPP per flow: (state (F, T) int8 with 1 = burst, arrivals (F, T) int32)."""
    n_flows = len(flows.source)
    state = np.zeros((n_flows, cfg.steps), np.int8)
    if profile.peak_ratio > 1.0:
        p_ib, p_bi = 1.0 / profile.mean_idle_steps, 1.0 / profile.mean_burst_steps
        state[:, 0] = rng.random(n_flows) < profile.duty  # stationary start
        u = rng.random((n_flows, cfg.steps))
        for t in range(1, cfg.steps):
            idle = state[:, t - 1] == 0
            state[:, t] = np.where(idle, u[:, t] < p_ib, u[:, t] >= p_bi)
    rate = np.where(state == 1, flows.burst_rate[:, None], flows.idle_rate[:, None])
    return state, rng.poisson(rate).astype(np.int32)


def _rank_within_groups(sorted_keys: np.ndarray) -> np.ndarray:
    """Position of every element inside its run of equal keys (keys must be sorted)."""
    n = len(sorted_keys)
    starts = np.flatnonzero(np.r_[True, sorted_keys[1:] != sorted_keys[:-1]])
    return np.arange(n) - np.repeat(starts, np.diff(np.r_[starts, n]))


@dataclass
class RouterRun:
    queue: np.ndarray            # (T, N) int16 buffer occupancy after admission, before forwarding
    node_drops: np.ndarray       # (T, N) int16 packets dropped at each node this step
    link_load: np.ndarray        # (T, 2E) int16 packets forwarded over each directed base link
    potential: np.ndarray        # (S, tracked, N) float32 field snapshots every `stride` steps, or None
    per_flow: Dict[str, np.ndarray]  # (T, F) int32: admitted, delivered, dropped, queued, in_transit, route_changes
    delay_sum: np.ndarray        # (T, F) sum of end-to-end delays of packets delivered this step
    in_flight: np.ndarray        # (F,) packets still queued or on a link when the episode ends
    delays: List[np.ndarray]     # per flow, end-to-end delay of every delivered packet
    propagation: List[np.ndarray]  # per flow, propagation part of that delay
    hops: List[np.ndarray]       # per flow, hop count of every delivered packet
    utilisation: float           # packets forwarded / directed link capacity, over all link-steps
    saturation: float            # fraction of directed link-steps forwarding at full capacity


def run_router(cfg: SimConfig, topo: Topology, flows: Flows, arrivals: np.ndarray,

               changes: list, router: str, field_stride: int) -> RouterRun:
    n, n_flows, steps, buffer = topo.n_nodes, len(flows.source), cfg.steps, cfg.buffer_size
    n_edges = len(topo.edges)
    source, sink = flows.source, flows.sink
    flow_ids = np.arange(n_flows)
    sinks, sink_index = np.unique(sink, return_inverse=True)          # per-sink tables serve every flow
    background = cfg.background_injection / (n - 1)
    tracked = min(cfg.tracked_flows, n_flows)
    field_based = router in ("potential", "potential_split", "potential_static")
    per_step = router in ("potential", "potential_split", "adaptive_shortest_path")

    # Packets in flight as a structure of arrays.
    p_flow = np.zeros(0, np.int16)
    p_birth = np.zeros(0, np.int32)
    p_node = np.zeros(0, np.int16)
    p_ready = np.zeros(0, np.int32)  # step at which the packet is (or becomes) available at p_node
    p_prop = np.zeros(0, np.int32)   # propagation delay accumulated so far
    p_hops = np.zeros(0, np.int16)
    p_id = np.zeros(0, np.int64)     # global creation order: FIFO tie-break and spraying coordinate
    next_id = 0

    queue_log = np.zeros((steps, n), np.int16)
    drop_log = np.zeros((steps, n), np.int16)
    link_log = np.zeros((steps, 2 * n_edges), np.int16)
    phi_log = (np.zeros((-(-steps // field_stride), tracked, n), np.float32)
               if router == FIELD_ROUTER else None)
    per_flow = {k: np.zeros((steps, n_flows), np.int32) for k in
                ("admitted", "delivered", "dropped", "queued", "in_transit", "route_changes")}
    delay_sum = np.zeros((steps, n_flows), np.float64)
    done_flow, done_delay, done_prop, done_hops = [], [], [], []
    util_num = util_den = 0.0
    saturated = link_steps = 0
    previous_hops = None
    change_i = 0

    for t in range(steps):
        # 1. Topology in force at this step; rebuild the routing state when links change.
        if change_i < len(changes) and changes[change_i][0] == t:
            g = live_graph(n, topo.edges, changes[change_i][1], topo.latency)
            change_i += 1
            if field_based:
                field = PotentialField(g, source, sink, cfg.source_injection)
                if router == "potential_static":
                    next_hop = steepest_next_hops(currents(field.solve(np.full(n, background)), g), g)
            elif router in ("shortest_path", "ecmp"):
                by_sink, dist = dijkstra_next_hops(g.latency.astype(np.float64), g, sinks)
                next_hop = by_sink[sink_index]
                if router == "ecmp":
                    ecmp = EcmpTable(dist, g)

        # 2. New packets appear at their sources.
        new = arrivals[:, t]
        n_new = int(new.sum())
        if n_new:
            new_flow = np.repeat(flow_ids, new).astype(np.int16)
            p_flow = np.concatenate([p_flow, new_flow])
            p_birth = np.concatenate([p_birth, np.full(n_new, t, np.int32)])
            p_node = np.concatenate([p_node, source[new_flow]])
            p_ready = np.concatenate([p_ready, np.full(n_new, t, np.int32)])
            p_prop = np.concatenate([p_prop, np.zeros(n_new, np.int32)])
            p_hops = np.concatenate([p_hops, np.zeros(n_new, np.int16)])
            p_id = np.concatenate([p_id, np.arange(next_id, next_id + n_new)])
            next_id += n_new

        # 3. Packets reaching a node this step: deliver at the sink, otherwise admit (drop-tail).
        per_flow["admitted"][t] = new
        arriving = p_ready == t
        if arriving.any():
            at_sink = arriving & (p_node == sink[p_flow])
            remove = at_sink.copy()
            if at_sink.any():
                f, d = p_flow[at_sink], (t - p_birth[at_sink]).astype(np.int32)
                np.add.at(per_flow["delivered"][t], f, 1)
                np.add.at(delay_sum[t], f, d)
                done_flow.append(f)
                done_delay.append(d)
                done_prop.append(p_prop[at_sink])
                done_hops.append(p_hops[at_sink])
            entering = np.flatnonzero(arriving & ~at_sink)
            if len(entering):
                space = buffer - np.bincount(p_node[p_ready < t], minlength=n)
                entering = entering[np.lexsort((p_id[entering], p_node[entering]))]  # per node, oldest first
                node = p_node[entering]
                lost = entering[_rank_within_groups(node) >= space[node]]
                if len(lost):
                    np.add.at(per_flow["dropped"][t], p_flow[lost], 1)
                    np.add.at(drop_log[t], p_node[lost], 1)
                    at_source = lost[p_birth[lost] == t]
                    per_flow["admitted"][t] -= np.bincount(p_flow[at_source], minlength=n_flows)
                    remove[lost] = True
            keep = ~remove
            p_flow, p_birth, p_node, p_ready = p_flow[keep], p_birth[keep], p_node[keep], p_ready[keep]
            p_prop, p_hops, p_id = p_prop[keep], p_hops[keep], p_id[keep]

        # 4. Telemetry snapshot of every buffer, then the routing decision.
        in_buffer = p_ready <= t
        queue = np.bincount(p_node[in_buffer], minlength=n)
        queue_log[t] = queue
        per_flow["queued"][t] = np.bincount(p_flow[in_buffer], minlength=n_flows)
        per_flow["in_transit"][t] = np.bincount(p_flow[~in_buffer], minlength=n_flows)
        if per_step:
            if router == "adaptive_shortest_path":
                cost = np.round((g.latency + queue[g.src] / g.capacity) / COST_QUANTUM)
                by_sink, _ = dijkstra_next_hops(cost, g, sinks)
                next_hop = by_sink[sink_index]
            else:
                phi = field.solve(background + cfg.congestion_gain * queue / buffer)
                cur = currents(phi, g)
                next_hop = steepest_next_hops(cur, g)
                if router == FIELD_ROUTER and t % field_stride == 0:
                    phi_log[t // field_stride] = phi[:tracked]
        if previous_hops is not None and next_hop is not previous_hops:
            per_flow["route_changes"][t] = (next_hop != previous_hops).sum(axis=1)
        previous_hops = next_hop

        # 5. Forwarding: each directed link takes the oldest packets routed over it, up to capacity.
        idx = np.flatnonzero(in_buffer)
        if len(idx):
            node, flow = p_node[idx], p_flow[idx]
            if router == "potential_split":
                hop = spray_next_hops(cur, g, node, flow, p_id[idx])
            elif router == "ecmp":
                hop = ecmp.hops(sink_index[flow], node, p_id[idx])
            else:
                hop = next_hop[flow, node]
            routable = hop >= 0
            idx, hop = idx[routable], hop[routable]
            link = g.dir_edge[p_node[idx], hop]
            order = np.lexsort((p_id[idx], p_ready[idx], link))
            idx, link = idx[order], link[order]
            forward = _rank_within_groups(link) < g.capacity[link]
            idx, link = idx[forward], link[forward]
            p_ready[idx] = t + g.latency[link]
            p_prop[idx] += g.latency[link]
            p_hops[idx] += 1
            p_node[idx] = g.dst[link]
            load = np.bincount(link, minlength=len(g.src))
            link_log[t] = np.bincount(g.base, weights=load, minlength=2 * n_edges).astype(np.int16)
            util_num += load.sum()
            saturated += int((load == g.capacity).sum())
        util_den += g.capacity.sum()
        link_steps += len(g.src)

    done_flow = np.concatenate(done_flow) if done_flow else np.zeros(0, np.int16)
    done_delay = np.concatenate(done_delay) if done_delay else np.zeros(0, np.int32)
    done_prop = np.concatenate(done_prop) if done_prop else np.zeros(0, np.int32)
    done_hops = np.concatenate(done_hops) if done_hops else np.zeros(0, np.int16)
    in_flight = np.bincount(p_flow, minlength=n_flows).astype(np.int32)
    conserved = per_flow["delivered"].sum(0) + per_flow["dropped"].sum(0) + in_flight
    assert np.array_equal(arrivals.sum(axis=1), conserved), "packet conservation"
    order = np.argsort(done_flow, kind="stable")
    bounds = np.searchsorted(done_flow[order], np.arange(n_flows + 1))

    def by_flow(values: np.ndarray) -> List[np.ndarray]:
        values = values[order]
        return [values[bounds[f]:bounds[f + 1]] for f in flow_ids]

    return RouterRun(queue_log, drop_log, link_log, phi_log, per_flow, delay_sum, in_flight,
                     by_flow(done_delay), by_flow(done_prop), by_flow(done_hops),
                     util_num / util_den, saturated / link_steps)


def field_stride(cfg: SimConfig, n_nodes: int, n_flows: int) -> int:
    tracked = min(cfg.tracked_flows, n_flows)
    return max(1, -(-4 * n_nodes * tracked * cfg.steps // cfg.field_budget_bytes))


def simulate_episode(cfg: SimConfig, episode_id: int) -> Dict[str, pa.Table]:
    """Sample one scenario, replay it under every configured router, return its telemetry tables."""
    cells = cfg.cells
    cell_index, replicate, split = locate(episode_id, len(cells))
    cell = cells[cell_index]
    rng = np.random.default_rng([cfg.seed, episode_id])
    topo = generate_topology(cfg, cell, rng)
    base = live_graph(topo.n_nodes, topo.edges, topo.capacity, topo.latency)
    flows = sample_flows(cfg, cell, topo, base, rng)
    mmpp_state, arrivals = sample_mmpp(cfg, cell.profile, flows, rng)
    events, changes = generate_timeline(cfg, topo, cell.dynamics, rng)
    stride = field_stride(cfg, topo.n_nodes, len(flows.source))
    runs = {r: run_router(cfg, topo, flows, arrivals, changes, r, stride) for r in cfg.routers}
    return _episode_tables(cfg, episode_id, cell, cell_index, replicate, split, topo, flows,
                           mmpp_state, arrivals, events, stride, runs)


def _stat(values: List[np.ndarray], fn, empty=np.nan, dtype=np.float32) -> np.ndarray:
    return np.array([fn(v) if len(v) else empty for v in values], dtype)


def _episode_tables(cfg: SimConfig, episode_id: int, cell: Cell, cell_index: int, replicate: int,

                    split: str, topo: Topology, flows: Flows, mmpp_state: np.ndarray,

                    arrivals: np.ndarray, events: List[TopologyEvent], stride: int,

                    runs: Dict[str, RouterRun]) -> Dict[str, pa.Table]:
    n, n_flows, steps, n_edges = topo.n_nodes, len(flows.source), cfg.steps, len(topo.edges)
    tracked = min(cfg.tracked_flows, n_flows)
    step = np.arange(steps, dtype=np.int32)
    offered = arrivals.sum(axis=1).astype(np.int32)
    profile = cell.profile

    def ep(size: int) -> np.ndarray:
        return np.full(size, episode_id, np.int32)

    def text(value: str, size: int) -> pa.Array:
        return pa.array([value] * size, pa.string())

    tables = {
        "episodes": pa.table({
            "episode_id": ep(1), "cell_id": np.array([cell_index], np.int16),
            "replicate": np.array([replicate], np.int16), "split": [split],
            "topology": [cell.topology], "size": np.array([cell.size], np.int16),
            "traffic_profile": [cell.traffic_profile], "load_level": [cell.load_level],
            "dynamics_level": [cell.dynamics_level],
            "n_nodes": np.array([n], np.int16), "n_edges": np.array([n_edges], np.int32),
            "n_flows": np.array([n_flows], np.int16), "tracked_flows": np.array([tracked], np.int16),
            "steps": np.array([steps], np.int32), "field_stride": np.array([stride], np.int16),
            "offered_load": np.array([cell.load], np.float32),
            "total_capacity": np.array([flows.total_capacity], np.float32),
            "edge_u": [topo.edges[:, 0]], "edge_v": [topo.edges[:, 1]],
            "capacity": [topo.capacity], "latency": [topo.latency],
            "node_role": [topo.node_role], "node_x": [topo.node_xy[:, 0]], "node_y": [topo.node_xy[:, 1]],
            "flow_source": [flows.source], "flow_sink": [flows.sink],
            "flow_mean_rate": [flows.mean_rate], "flow_idle_rate": [flows.idle_rate],
            "flow_burst_rate": [flows.burst_rate],
            "p_idle_to_burst": np.array([1.0 / profile.mean_idle_steps if profile.peak_ratio > 1 else 0.0], np.float32),
            "p_burst_to_idle": np.array([1.0 / profile.mean_burst_steps if profile.peak_ratio > 1 else 0.0], np.float32),
        }, schema=SCHEMAS["episodes"]),
        "events": pa.table({
            "episode_id": ep(len(events)),
            "kind": [e.kind for e in events],
            "start": np.array([e.start for e in events], np.int32),
            "end": np.array([e.end for e in events], np.int32),
            "node": np.array([e.node for e in events], np.int16),
            "edge_u": np.array([topo.edges[e.edge, 0] if e.edge >= 0 else -1 for e in events], np.int16),
            "edge_v": np.array([topo.edges[e.edge, 1] if e.edge >= 0 else -1 for e in events], np.int16),
            "factor": np.array([e.factor for e in events], np.float32),
        }, schema=SCHEMAS["events"]),
    }

    parts = {name: [] for name in ("router_summary", "flow_summary", "flow_telemetry",
                                   "network_telemetry", "link_telemetry")}
    for router, run in runs.items():
        pf = run.per_flow
        delivered, dropped = pf["delivered"].sum(0), pf["dropped"].sum(0)
        all_delays = np.concatenate(run.delays)
        with np.errstate(invalid="ignore", divide="ignore"):
            flow_mean_delay = (run.delay_sum / pf["delivered"]).astype(np.float32)
            step_mean_delay = (run.delay_sum.sum(1) / pf["delivered"].sum(1)).astype(np.float32)
        parts["router_summary"].append(pa.table({
            "episode_id": ep(1), "router": [router],
            "offered": np.array([offered.sum()], np.int32), "delivered": np.array([delivered.sum()], np.int32),
            "dropped": np.array([dropped.sum()], np.int32), "in_flight": np.array([run.in_flight.sum()], np.int32),
            "loss_ratio": np.array([dropped.sum() / max(offered.sum(), 1)], np.float32),
            "mean_delay": np.array([all_delays.mean() if len(all_delays) else np.nan], np.float32),
            "p99_delay": np.array([np.percentile(all_delays, 99) if len(all_delays) else np.nan], np.float32),
            "mean_queue": np.array([run.queue.mean()], np.float32),
            "max_queue": np.array([run.queue.max()], np.int32),
            "link_utilisation": np.array([run.utilisation], np.float32),
            "link_saturation": np.array([run.saturation], np.float32),
            "route_changes": np.array([pf["route_changes"].sum()], np.int32),
        }, schema=SCHEMAS["router_summary"]))
        quantiles = np.array([np.percentile(d, [50, 95, 99]) if len(d) else [np.nan] * 3
                              for d in run.delays], np.float32)
        parts["flow_summary"].append(pa.table({
            "episode_id": ep(n_flows), "router": text(router, n_flows),
            "flow": np.arange(n_flows, dtype=np.int16), "source": flows.source, "sink": flows.sink,
            "mean_rate": flows.mean_rate, "min_hops": flows.min_hops, "min_latency": flows.min_latency,
            "offered": offered, "delivered": delivered, "dropped": dropped, "in_flight": run.in_flight,
            "loss_ratio": (dropped / np.maximum(offered, 1)).astype(np.float32),
            "mean_delay": _stat(run.delays, np.mean), "delay_std": _stat(run.delays, np.std),
            "p50_delay": quantiles[:, 0], "p95_delay": quantiles[:, 1], "p99_delay": quantiles[:, 2],
            "max_delay": _stat(run.delays, np.max, -1, np.int32),
            "mean_queueing_delay": np.array([(d - p).mean() if len(d) else np.nan
                                             for d, p in zip(run.delays, run.propagation)], np.float32),
            "mean_path_latency": _stat(run.propagation, np.mean),
            "mean_hops": _stat(run.hops, np.mean),
            "route_changes": pf["route_changes"].sum(0).astype(np.int32),
        }, schema=SCHEMAS["flow_summary"]))
        tf = slice(0, tracked)
        parts["flow_telemetry"].append(pa.table({
            "episode_id": ep(steps * tracked), "router": text(router, steps * tracked),
            "step": np.repeat(step, tracked), "flow": np.tile(np.arange(tracked, dtype=np.int16), steps),
            "mmpp_state": mmpp_state[tf].T.ravel(), "offered": arrivals[tf].T.ravel(),
            "admitted": pf["admitted"][:, tf].ravel(), "delivered": pf["delivered"][:, tf].ravel(),
            "dropped": pf["dropped"][:, tf].ravel(), "queued": pf["queued"][:, tf].ravel(),
            "in_transit": pf["in_transit"][:, tf].ravel(), "mean_delay": flow_mean_delay[:, tf].ravel(),
            "route_changes": pf["route_changes"][:, tf].ravel(),
        }, schema=SCHEMAS["flow_telemetry"]))
        parts["network_telemetry"].append(pa.table({
            "episode_id": ep(steps), "router": text(router, steps), "step": step,
            "offered": arrivals.sum(0).astype(np.int32), "admitted": pf["admitted"].sum(1),
            "delivered": pf["delivered"].sum(1), "dropped": pf["dropped"].sum(1),
            "queued": pf["queued"].sum(1), "in_transit": pf["in_transit"].sum(1),
            "mean_delay": step_mean_delay, "route_changes": pf["route_changes"].sum(1),
            "queue_depth": list_column(run.queue, pa.int16()),
            "node_dropped": list_column(run.node_drops, pa.int16()),
        }, schema=SCHEMAS["network_telemetry"]))
        parts["link_telemetry"].append(pa.table({
            "episode_id": ep(steps), "router": text(router, steps), "step": step,
            "load_uv": list_column(run.link_load[:, :n_edges], pa.int16()),
            "load_vu": list_column(run.link_load[:, n_edges:], pa.int16()),
        }, schema=SCHEMAS["link_telemetry"]))
        if run.potential is not None:
            snapshots = run.potential.shape[0]
            tables["potential_field"] = pa.table({
                "episode_id": ep(snapshots), "step": (np.arange(snapshots) * stride).astype(np.int32),
                "potential": list_column(run.potential.reshape(snapshots, -1), pa.float32()),
            }, schema=SCHEMAS["potential_field"])
    for name, chunks in parts.items():
        tables[name] = pa.concat_tables(chunks)
    return tables


def run_sweep(cfg: SimConfig, data_dir: Path, workers: int, log=print) -> None:
    """Map every unfinished shard of episodes across `workers` processes and stream it to Parquet."""
    n_shards = -(-cfg.episodes // cfg.shard_episodes)

    def shard_ids(shard: int) -> range:
        return range(shard * cfg.shard_episodes, min((shard + 1) * cfg.shard_episodes, cfg.episodes))

    done = completed_shards(data_dir, n_shards, cfg.routers)
    todo = [s for s in range(n_shards) if s not in done]
    if done:
        log(f"Resuming: {len(done)}/{n_shards} shards already complete.")
    if not todo:
        log("Nothing to do: every shard is complete.")
        return
    episodes_todo = [e for s in todo for e in shard_ids(s)]
    log(f"Simulating {len(episodes_todo)} episodes x {len(cfg.routers)} routers "
        f"({len(cfg.cells)} design cells) on {workers} workers ...")
    start, finished = time.time(), 0
    with mp.get_context("spawn").Pool(workers) as pool:  # same start method on every platform
        results = pool.imap(partial(simulate_episode, cfg), episodes_todo, chunksize=1)
        for shard in todo:
            ids = shard_ids(shard)
            write_shard(data_dir, shard, [next(results) for _ in ids])
            finished += len(ids)
            elapsed = time.time() - start
            eta = elapsed / finished * (len(episodes_todo) - finished)
            log(f"  shard {shard + 1:>4}/{n_shards}  episodes {finished:>6}/{len(episodes_todo)}  "
                f"elapsed {elapsed / 3600:5.2f} h  eta {eta / 3600:5.2f} h")
    log(f"Done in {(time.time() - start) / 3600:.2f} h.")