File size: 20,912 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
"""Validate a generated dataset: structure, design coverage, physical invariants and reproducibility.



    python scripts/validate_dataset.py                 # validates data/

    python scripts/validate_dataset.py --out data_large --resimulate 5



Checks, in order: every shard has every table; the design is balanced and the splits present;

packet conservation and metric consistency across the summary and telemetry tables; buffers,

link loads and potentials respect their physical bounds; a sample of episodes re-simulated from

``config.json`` reproduces the stored tables bit for bit; and a stored potential-field snapshot

is recovered from the graph state and queue depths with the sparse SuperLU reference solver.

Exits with status 1 if any check fails.



The step-level tables are far larger than memory at the full design (``flow_telemetry`` alone is

episodes x routers x steps x tracked_flows = 2.6e8 rows), so every check over them streams the

shards one record batch at a time and folds partial aggregates together; peak memory is a few

hundred MB regardless of dataset size.

"""
import os

for _var in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
    os.environ.setdefault(_var, "1")

import argparse
import json
import sys
from pathlib import Path
from typing import Iterator, Sequence

import numpy as np
import pyarrow as pa
import pyarrow.dataset as pads

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from src.config import SimConfig  # noqa: E402
from src.graph_generator import effective_capacity, TopologyEvent, Topology  # noqa: E402
from src.physics_engine import grounded_solve, live_graph  # noqa: E402
from src.simulation_loop import simulate_episode  # noqa: E402
from src.telemetry_logger import read_table, shard_files, table_names  # noqa: E402

BATCH_ROWS = 1 << 18   # rows per streamed record batch (~10 MB for the scalar telemetry columns)
READAHEAD = 2          # batches/fragments the scanner may buffer ahead; keeps peak memory flat
FOLD_EVERY = 8         # partial aggregates combined before they accumulate

failures = []


def check(condition: bool, message: str) -> None:
    status = "ok " if condition else "FAIL"
    print(f"  [{status}] {message}")
    if not condition:
        failures.append(message)


# --------------------------------------------------------------------------------------
# Streaming helpers.  Nothing below ever materialises a whole step-level table: the shards are
# read one record batch at a time and folded into a dense per-group accumulator whose size is
# fixed by the design (episodes x routers x tracked flows), not by the number of rows.
# --------------------------------------------------------------------------------------

def scan(data_dir: Path, table: str, columns: Sequence[str], filter=None,

         batch_rows: int = BATCH_ROWS) -> Iterator[pa.RecordBatch]:
    """Record batches of a table's shards, reading only `columns`."""
    files = [str(p) for p in shard_files(data_dir, table)]
    dataset = pads.dataset(files, format="parquet")
    yield from dataset.to_batches(columns=list(columns), filter=filter, batch_size=batch_rows,
                                  batch_readahead=READAHEAD, fragment_readahead=READAHEAD)


class Groups:
    """Dense (episode, router[, flow]) -> slot mapping shared by a telemetry and a summary table."""

    def __init__(self, episode_ids: Sequence[int], routers: Sequence[str], width: int = 1):
        ids = np.asarray(sorted(int(e) for e in episode_ids), np.int64)
        self.episode_ids = ids
        self.lookup = np.full(int(ids.max()) + 1, -1, np.int64)
        self.lookup[ids] = np.arange(len(ids))
        self.routers = list(routers)
        self.router_slot = {r: i for i, r in enumerate(self.routers)}
        self.width = int(width)
        self.size = len(ids) * len(self.routers) * self.width

    def slots(self, batch: pa.RecordBatch) -> np.ndarray:
        episode = self.lookup[batch.column("episode_id").to_numpy(zero_copy_only=False).astype(np.int64)]
        encoded = batch.column("router").dictionary_encode()
        codes = np.array([self.router_slot[v] for v in encoded.dictionary.to_pylist()], np.int64)
        router = codes[encoded.indices.to_numpy(zero_copy_only=False).astype(np.int64)]
        slot = (episode * len(self.routers) + router) * self.width
        if self.width > 1:
            slot = slot + batch.column("flow").to_numpy(zero_copy_only=False).astype(np.int64)
        return slot

    def label(self, slot: int) -> str:
        episode, rest = divmod(int(slot), len(self.routers) * self.width)
        router, flow = divmod(rest, self.width)
        name = f"episode {self.episode_ids[episode]}, router {self.routers[router]}"
        return name + (f", flow {flow}" if self.width > 1 else "")


class Sums:
    """Per-group sums of integer counters, accumulated batch by batch."""

    def __init__(self, groups: Groups, values: Sequence[str]):
        self.groups = groups
        self.values = list(values)
        self.rows = np.zeros(groups.size, np.int64)
        self.totals = {v: np.zeros(groups.size, np.int64) for v in self.values}

    def add(self, batch: pa.RecordBatch) -> None:
        slot = self.groups.slots(batch)
        self.rows += np.bincount(slot, minlength=self.groups.size)
        for name in self.values:
            column = batch.column(name).to_numpy(zero_copy_only=False).astype(np.float64)
            self.totals[name] += np.rint(np.bincount(slot, weights=column,
                                                     minlength=self.groups.size)).astype(np.int64)

    @property
    def present(self) -> np.ndarray:
        return self.rows > 0


def accumulate(data_dir: Path, table: str, groups: Groups, values: Sequence[str],

               batch_rows: int = BATCH_ROWS, on_batch=None) -> Sums:
    """Stream `table` and sum `values` per group."""
    sums = Sums(groups, values)
    columns = ["episode_id", "router"] + (["flow"] if groups.width > 1 else [])
    extra = [v for v in values if v not in columns]
    for batch in scan(data_dir, table, columns + extra, batch_rows=batch_rows):
        if on_batch is not None:
            on_batch(batch)
        sums.add(batch)
    return sums


def compare_sums(streamed: Sums, reference: Sums, columns: Sequence[str], label: str) -> None:
    """Check that per-group sums streamed from a telemetry table equal those of a summary table."""
    groups = streamed.groups
    same_groups = bool((streamed.present == reference.present).all())
    if not same_groups:
        missing = np.flatnonzero(streamed.present != reference.present)
        check(False, f"{label}: {len(missing)} group(s) on one side only, e.g. {groups.label(missing[0])}")
        return
    check(True, f"{label}: the same groups appear in both tables")
    where = streamed.present
    bad = [c for c in columns if not bool((streamed.totals[c][where] == reference.totals[c][where]).all())]
    if bad:
        c = bad[0]
        first = np.flatnonzero(where & (streamed.totals[c] != reference.totals[c]))[0]
        check(False, f"{label} (differs in {', '.join(bad)}; first at {groups.label(first)}: "
                     f"{streamed.totals[c][first]} vs {reference.totals[c][first]})")
    else:
        check(True, label)


# --------------------------------------------------------------------------------------
# Checks
# --------------------------------------------------------------------------------------

def structure(data_dir: Path, cfg: SimConfig) -> int:
    print("Structure")
    tables = table_names(cfg.routers)
    counts = {t: len(shard_files(data_dir, t)) for t in tables}
    n_shards = max(counts.values()) if counts else 0
    check(n_shards > 0, f"{n_shards} shards present")
    check(all(c == n_shards for c in counts.values()), "every table has every shard")
    check((data_dir / "manifest.json").exists(), "manifest.json present")
    return n_shards


def coverage(data_dir: Path, cfg: SimConfig) -> None:
    print("Design coverage")
    ep = read_table(data_dir, "episodes", columns=["episode_id", "cell_id", "replicate", "split"]).to_pandas()
    per_cell = ep.cell_id.value_counts()
    check(len(per_cell) == len(cfg.cells), f"all {len(cfg.cells)} design cells present")
    check(per_cell.max() - per_cell.min() <= 1, f"balanced: {per_cell.min()}-{per_cell.max()} episodes per cell")
    check(ep.episode_id.is_unique, "episode ids unique")
    check({"train", "validation", "test"} <= set(ep.split) or cfg.replicates < 5,
          f"splits present: {sorted(set(ep.split))}")


FLOW_SUMMARY_COLUMNS = ["offered", "delivered", "dropped", "in_flight", "loss_ratio", "mean_delay",
                        "min_latency", "min_hops", "mean_hops", "p50_delay", "p95_delay", "p99_delay",
                        "max_delay", "mean_queueing_delay", "mean_path_latency"]


def flow_summary_elementwise(data_dir: Path, batch_rows: int) -> None:
    """Per-row invariants of flow_summary, accumulated over streamed batches."""
    results = dict(conservation=True, loss=True, delay=True, hops=True, quantiles=True, decomposition=True)
    for batch in scan(data_dir, "flow_summary", FLOW_SUMMARY_COLUMNS, batch_rows=batch_rows):
        c = {name: batch.column(name).to_numpy(zero_copy_only=False) for name in FLOW_SUMMARY_COLUMNS}
        ok = c["delivered"] > 0
        results["conservation"] &= bool((c["offered"] == c["delivered"] + c["dropped"] + c["in_flight"]).all())
        results["loss"] &= bool(((c["loss_ratio"] >= 0) & (c["loss_ratio"] <= 1)).all())
        results["delay"] &= bool((c["mean_delay"][ok] >= c["min_latency"][ok] - 1e-3).all())
        results["hops"] &= bool((c["mean_hops"][ok] >= c["min_hops"][ok] - 1e-3).all())
        results["quantiles"] &= bool(((c["p50_delay"][ok] <= c["p95_delay"][ok] + 1e-3)
                                      & (c["p95_delay"][ok] <= c["p99_delay"][ok] + 1e-3)
                                      & (c["p99_delay"][ok] <= c["max_delay"][ok] + 1e-3)).all())
        results["decomposition"] &= bool(np.allclose(c["mean_delay"][ok],
                                                     c["mean_queueing_delay"][ok] + c["mean_path_latency"][ok],
                                                     atol=1e-2))
    check(results["conservation"], "flow conservation: offered = delivered + dropped + in-flight")
    check(results["loss"], "loss ratio within [0, 1]")
    check(results["delay"], "mean delay >= minimum path latency")
    check(results["hops"], "mean hops >= minimum hop count")
    check(results["quantiles"], "delay quantiles ordered")
    check(results["decomposition"], "delay = queueing + propagation")


def invariants(data_dir: Path, cfg: SimConfig, batch_rows: int = BATCH_ROWS) -> None:
    print("Invariants")
    flow_summary_elementwise(data_dir, batch_rows)

    episode_ids = read_table(data_dir, "episodes", columns=["episode_id"]).column("episode_id").to_pylist()
    counters = ["offered", "delivered", "dropped", "in_flight"]
    per_router = Groups(episode_ids, cfg.routers)

    router_summary = read_table(data_dir, "router_summary")
    reference = Sums(per_router, counters)
    for batch in router_summary.to_batches():
        reference.add(batch)
    check(bool((reference.rows <= 1).all()), "router_summary has one row per (episode, router)")
    compare_sums(accumulate(data_dir, "flow_summary", per_router, counters, batch_rows),
                 reference, counters, "router summary equals the sum of its flows")
    util = router_summary.column("link_utilisation").to_numpy(zero_copy_only=False)
    sat = router_summary.column("link_saturation").to_numpy(zero_copy_only=False)
    check(bool(((util >= 0) & (util <= 1) & (sat >= 0) & (sat <= 1)).all()), "utilisation within [0, 1]")

    admission = {"ok": True}

    def admitted_le_offered(batch: pa.RecordBatch) -> None:
        admission["ok"] &= bool((batch.column("admitted").to_numpy(zero_copy_only=False)
                                 <= batch.column("offered").to_numpy(zero_copy_only=False)).all())

    steps = ["offered", "delivered", "dropped"]
    compare_sums(accumulate(data_dir, "network_telemetry", per_router, steps + ["admitted"], batch_rows,
                            on_batch=admitted_le_offered),
                 reference, steps, "network telemetry sums to the router summary")

    per_flow = Groups(episode_ids, cfg.routers, width=int(cfg.tracked_flows))
    tracked = accumulate(data_dir, "flow_telemetry", per_flow, steps + ["admitted"], batch_rows,
                         on_batch=admitted_le_offered)
    flow_reference = Sums(per_flow, steps)
    for batch in scan(data_dir, "flow_summary", ["episode_id", "router", "flow"] + steps,
                      filter=pads.field("flow") < int(cfg.tracked_flows), batch_rows=batch_rows):
        flow_reference.add(batch)
    compare_sums(tracked, flow_reference, steps, "tracked-flow telemetry sums to the flow summary")
    check(admission["ok"], "admitted <= offered")


def physical_bounds(data_dir: Path, cfg: SimConfig, episode_ids) -> None:
    print("Physical bounds (sampled episodes)")
    episodes = read_table(data_dir, "episodes").to_pandas().set_index("episode_id")
    events = read_table(data_dir, "events").to_pandas()
    for eid in episode_ids:
        ep = episodes.loc[eid]
        net = read_table(data_dir, "network_telemetry", filters=[("episode_id", "=", int(eid))]).to_pandas()
        queue = np.stack(net.queue_depth)
        check(queue.min() >= 0 and queue.max() <= cfg.buffer_size, f"episode {eid}: queue depths within the buffer")
        check((np.stack(net.node_dropped).sum(1) == net.dropped).all(), f"episode {eid}: node drops sum to step drops")
        link = read_table(data_dir, "link_telemetry", filters=[("episode_id", "=", int(eid))]).to_pandas()
        topo = Topology(int(ep.n_nodes), np.stack([ep.edge_u, ep.edge_v], 1).astype(np.int16),
                        ep.capacity.astype(np.int16), ep.latency.astype(np.int16),
                        np.zeros(0, np.int16), np.zeros(0, np.int8), np.zeros((0, 2), np.float32))
        evs = [TopologyEvent(e.kind, int(e.start), int(e.end),
                             edge=int(np.flatnonzero((ep.edge_u == e.edge_u) & (ep.edge_v == e.edge_v))[0]) if e.kind == "link_failure" else -1,
                             node=int(e.node), factor=float(e.factor))
               for e in events[events.episode_id == eid].itertuples()]
        steps = sorted({0} | {e.start for e in evs} | {e.end for e in evs if e.end < ep.steps})
        cap_at = {t: effective_capacity(topo, evs, t) for t in steps}
        bounds = np.array([cap_at[steps[np.searchsorted(steps, t, side="right") - 1]] for t in link.step])
        loads = np.maximum(np.stack(link.load_uv), np.stack(link.load_vu))
        check((loads <= bounds).all(), f"episode {eid}: link loads never exceed the capacity in force")
        if "potential_field" in table_names(cfg.routers):
            pf = read_table(data_dir, "potential_field", filters=[("episode_id", "=", int(eid))]).to_pandas()
            phi = np.stack(pf.potential).reshape(len(pf), int(ep.tracked_flows), int(ep.n_nodes))
            sinks = ep.flow_sink[: int(ep.tracked_flows)]
            check(phi.min() >= 0 and np.all(phi[:, np.arange(len(sinks)), sinks] == 0),
                  f"episode {eid}: potentials non-negative and zero at the sinks")


def tables_equal(a: pa.Table, b: pa.Table) -> bool:
    """Exact equality of two tables, treating NaN as equal to NaN."""
    if a.num_rows != b.num_rows or not a.schema.equals(b.schema, check_metadata=False):
        return False
    for name in a.column_names:
        x, y = a.column(name).combine_chunks(), b.column(name).combine_chunks()
        if pa.types.is_list(x.type):
            if not x.offsets.equals(y.offsets):
                return False
            x, y = x.flatten(), y.flatten()
        if pa.types.is_floating(x.type):
            if not np.array_equal(x.to_numpy(zero_copy_only=False), y.to_numpy(zero_copy_only=False), equal_nan=True):
                return False
        elif not x.equals(y):
            return False
    return True


def reproducibility(data_dir: Path, cfg: SimConfig, episode_ids) -> None:
    print("Reproducibility (re-simulating from config.json)")
    for eid in episode_ids:
        fresh = simulate_episode(cfg, int(eid))
        same = all(tables_equal(read_table(data_dir, name, filters=[("episode_id", "=", int(eid))]), table)
                   for name, table in fresh.items())
        check(same, f"episode {eid}: every table reproduced bit for bit")


def field_reconstruction(data_dir: Path, cfg: SimConfig, eid: int) -> None:
    print("Potential-field reconstruction (sparse reference solver)")
    ep = read_table(data_dir, "episodes", filters=[("episode_id", "=", int(eid))]).to_pandas().iloc[0]
    events = read_table(data_dir, "events", filters=[("episode_id", "=", int(eid))]).to_pandas()
    pf = read_table(data_dir, "potential_field", filters=[("episode_id", "=", int(eid))]).to_pandas()
    row = pf.iloc[len(pf) // 2]
    step = int(row.step)
    net = read_table(data_dir, "network_telemetry",
                     filters=[("episode_id", "=", int(eid)), ("router", "=", "potential"), ("step", "=", step)]).to_pandas()
    queue = np.asarray(net.queue_depth.iloc[0], np.float64)
    n = int(ep.n_nodes)
    cap = ep.capacity.astype(np.float64)
    factor, failed = np.ones(n), np.zeros(len(cap), bool)
    for e in events[(events.start <= step) & (step < events.end)].itertuples():
        if e.kind == "node_degradation":
            factor[e.node] *= e.factor
        else:
            failed |= (ep.edge_u == e.edge_u) & (ep.edge_v == e.edge_v)
    cap = np.maximum(1, np.floor(cap * factor[ep.edge_u] * factor[ep.edge_v]))
    cap[failed] = 0
    g = live_graph(n, np.stack([ep.edge_u, ep.edge_v], 1), cap.astype(np.int16), ep.latency.astype(np.int16))
    stored = np.asarray(row.potential, np.float64).reshape(int(ep.tracked_flows), n)
    injection = cfg.background_injection / (n - 1) + cfg.congestion_gain * queue / cfg.buffer_size
    worst = 0.0
    for f in range(int(ep.tracked_flows)):
        b = injection.copy()
        b[ep.flow_source[f]] += cfg.source_injection
        phi = grounded_solve(g, int(ep.flow_sink[f]), b)
        worst = max(worst, np.abs(phi - stored[f]).max() / max(np.abs(phi).max(), 1e-12))
    check(worst < 1e-5, f"episode {eid}, step {step}: stored field matches the sparse solve (max rel err {worst:.1e})")


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--out", type=Path, default=ROOT / "data", help="dataset folder (default: data/)")
    parser.add_argument("--resimulate", type=int, default=3, help="episodes to re-simulate for the reproducibility check")
    parser.add_argument("--seed", type=int, default=0, help="seed for choosing the sampled episodes")
    parser.add_argument("--batch-rows", type=int, default=BATCH_ROWS,
                        help=f"rows per streamed record batch in the invariant checks (default: {BATCH_ROWS})")
    args = parser.parse_args()
    cfg = SimConfig.load(args.out / "config.json")
    n_shards = structure(args.out, cfg)
    if n_shards == 0:
        sys.exit("no shards found")
    coverage(args.out, cfg)
    invariants(args.out, cfg, max(1024, args.batch_rows))
    ids = read_table(args.out, "episodes", columns=["episode_id", "size"]).to_pandas().sort_values("size")
    rng = np.random.default_rng(args.seed)
    sample = [int(ids.episode_id.iloc[i]) for i in
              np.unique(np.linspace(0, len(ids) - 1, max(1, args.resimulate)).astype(int))]
    if len(ids) > args.resimulate:
        sample = sorted(set(sample) | {int(x) for x in rng.choice(ids.episode_id, 1, replace=False)})
    physical_bounds(args.out, cfg, sample)
    reproducibility(args.out, cfg, sample[:args.resimulate])
    if "potential_field" in table_names(cfg.routers):
        field_reconstruction(args.out, cfg, sample[0])
    manifest = json.loads((args.out / "manifest.json").read_text(encoding="utf-8"))
    print(f"\nDataset v{manifest['dataset_version']}: {manifest['design']['episodes_present']} episodes, "
          f"{sum(t['bytes'] for t in manifest['tables'].values()) / 1e9:.2f} GB")
    if failures:
        sys.exit(f"{len(failures)} check(s) failed: " + "; ".join(failures))
    print("All checks passed.")


if __name__ == "__main__":
    main()