File size: 29,057 Bytes
0c1f445
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Batch-run pic_evaluator on every design under a directory tree.

Walks ``<root>/<design>/<variant>/`` where the ``<design>`` folder
holds the netlist (``*_netlist.json``) and each ``<variant>``
subfolder holds the placement + routing JSON for one router run.

For every match we:

  * load the design (PDK + design-rules picked up from the same place
    every other CLI invocation uses);
  * run all registered metrics;
  * write the JSON report next to the placement file (default
    pic_evaluator behaviour);
  * (optionally) render SVG plots in the same directory;
  * collect a one-row summary into a CSV so designs / variants can
    be compared at a glance.

A single design failing is logged and skipped — the batch continues.

Example::

    python batch_eval.py \\
        --root D:/pic_router/data_collection/dual_route \\
        --pdk  ./batch_tests/PDK_&_Constrain/pdk_v2_mzi80.json \\
        --summary-csv out/summary.csv

Use ``--filter`` to narrow to a subset (substring match on design
name) and ``--no-plots`` to skip SVG rendering for speed.
"""
from __future__ import annotations

import argparse
import csv
import json
import logging
import multiprocessing as mp
import sys
import time
import traceback
from collections import namedtuple
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Tuple

from pic_evaluator.config import EvalConfig
from pic_evaluator.model.design import Design
from pic_evaluator.runner import run
from pic_evaluator.report import write_json


logger = logging.getLogger("batch_eval")

Job = Tuple[str, str, Path, Path, Path]   # (design, variant, nl, pl, rt)

# A foreground job that exceeded the per-job timeout but was demoted to
# the background pool instead of being killed. `idx` is the 0-based
# position of this job in the original job list — used to slot the row
# into the right place in the summary CSV when the bg job eventually
# finishes.
_BgJob = namedtuple(
    "_BgJob",
    "idx design variant proc queue report_path prefix t0",
)


def find_jobs(root: Path) -> Iterable[Job]:
    """Yield every (design, variant, netlist, placement, routing) tuple
    under *root*. A variant is any subdirectory of a design directory
    that contains both a ``*_placement.json`` and ``*_routing.json``.
    """
    for design_dir in sorted(p for p in root.iterdir() if p.is_dir()):
        netlists = list(design_dir.glob("*_netlist.json"))
        if not netlists:
            continue
        netlist_p = netlists[0]
        for variant_dir in sorted(p for p in design_dir.iterdir() if p.is_dir()):
            placements = list(variant_dir.glob("*_placement.json"))
            routings = list(variant_dir.glob("*_routing.json"))
            if not placements or not routings:
                continue
            yield (design_dir.name, variant_dir.name,
                   netlist_p, placements[0], routings[0])


# ── subprocess worker (used when --per-job-timeout is active) ───────

def _job_worker(nl: str, pl: str, rt: str, pdk: str,
                design_rules: Optional[str],
                no_plots: bool, no_labels: bool,
                report_path: str,
                queue) -> None:
    """Run one evaluation in a child process.

    Writes the JSON report to *report_path* on success, then puts
    ``("ok", None)`` on the queue. On failure, puts
    ``("fail", "<msg>")``. The parent reloads the report from disk
    so we don't need to pickle the (possibly large / non-picklable)
    results dict across the process boundary.
    """
    try:
        from pic_evaluator.config import EvalConfig as _EvalConfig
        from pic_evaluator.model.design import Design as _Design
        from pic_evaluator.runner import run as _run
        from pic_evaluator.report import write_json as _write_json

        d = _Design.from_paths(Path(nl), Path(pl), Path(rt), Path(pdk),
                               design_rules_p=Path(design_rules) if design_rules else None)
        cfg = _EvalConfig()
        results = _run(d, cfg, tiers=("1", "2", "3"))
        _write_json(results, report_path)

        if not no_plots:
            from pic_evaluator.plotting import generate_plots as _gen_plots
            _gen_plots(d, cfg, results, str(Path(pl).parent),
                       show_labels=not no_labels)

        queue.put(("ok", None))
    except Exception as e:
        queue.put(("fail", f"{type(e).__name__}: {e}\n{traceback.format_exc()}"))


# ── per-job summary extraction ───────────────────────────────────────

def _safe(d, *keys, default=None):
    cur = d
    for k in keys:
        if not isinstance(cur, dict):
            return default
        cur = cur.get(k)
        if cur is None:
            return default
    return cur


def summarise(results: Dict[str, Any]) -> Dict[str, Any]:
    """Pull a flat row of headline numbers out of a full results dict."""
    t1 = results.get("tiers", {}).get("1", {}) or {}
    t2 = results.get("tiers", {}).get("2", {}) or {}
    t3 = results.get("tiers", {}).get("3", {}) or {}
    return {
        # status
        "lvs_ok":          _safe(t1, "lvs", "ok"),
        "drc_ok":          _safe(t2, "drc", "ok"),
        "consistency_ok":  _safe(t3, "consistency", "ok"),
        # IL
        "n_paths":         _safe(t1, "insertion_loss", "n_paths"),
        "il_min_db":       _safe(t1, "insertion_loss", "min_db"),
        "il_max_db":       _safe(t1, "insertion_loss", "max_db"),
        "il_mean_db":      _safe(t1, "insertion_loss", "mean_db"),
        "il_spread_db":    _safe(t1, "loss_uniformity", "spread_db"),
        # path length / delay
        "group_delay_min_ps":  _safe(t2, "group_delay", "min_delay_ps"),
        "group_delay_max_ps":  _safe(t2, "group_delay", "max_delay_ps"),
        "lane_skew_ps":        _safe(t2, "lane_skew", "skew_ps"),
        "phase_match_max_um":  _safe(t3, "phase_matching", "max_mismatch_by_input_um"),
        # area / wirelength
        "bbox_mm2":            _safe(t1, "area", "bbox_area_mm2"),
        "tight_hull_mm2":      _safe(t1, "area", "tight_hull_area_mm2"),
        "cell_sum_mm2":        _safe(t1, "area", "cell_sum_mm2"),
        "utilization":         _safe(t1, "area", "utilization_cell_over_bbox"),
        "wirelength_mm":       _safe(t1, "wirelength", "total_length_mm"),
        "longest_net_um":      _safe(t1, "wirelength", "max_length_um"),
        # devices
        "n_devices":           _safe(t1, "device_count", "n_instances_total"),
        "n_crossings":         _safe(t1, "device_count", "n_crossings"),
        # crosstalk
        "xt_worst_db":         _safe(t2, "crosstalk_budget", "worst_floor_db"),
        "xt_matrix_worst_db":  _safe(t3, "crosstalk_matrix", "worst_xt_db"),
        # routing
        "detour_mean":         _safe(t3, "detour_ratio", "mean_detour"),
        "detour_max":          _safe(t3, "detour_ratio", "max_detour"),
        # error tally
        "n_errors": len(results.get("errors", {}) or {}) // 2,  # error + __traceback per failure
    }


def _resolve_design_rules(pdk_p: Path,
                          override: Optional[Path]) -> Optional[Path]:
    if override is not None:
        return override
    for cand in pdk_p.parent.glob("design_rules*.json"):
        return cand
    return None


# ── cache (mtime-based) + CSV merge helpers ──────────────────────────

def _load_existing_csv(p: Path) -> Dict[Tuple[str, str], Dict[str, Any]]:
    """Load an existing summary CSV into a dict keyed by (design, variant).

    Returns {} if the file is absent or unparseable. Used to merge
    partial-run results into the prior snapshot rather than overwriting it.
    """
    if not p.is_file():
        return {}
    try:
        with p.open("r", newline="", encoding="utf-8") as fh:
            return {(r["design"], r["variant"]): dict(r)
                    for r in csv.DictReader(fh)
                    if r.get("design") and r.get("variant")}
    except Exception as e:
        logger.warning("could not parse existing CSV %s: %s; treating as empty",
                       p, e)
        return {}


def _input_mtimes(*paths: Optional[Path]) -> List[float]:
    """mtimes (float) for the inputs that should invalidate the cache.
    Missing files map to +inf so the cache check fails closed."""
    out: List[float] = []
    for p in paths:
        if p is None:
            continue
        try:
            out.append(p.stat().st_mtime)
        except OSError:
            out.append(float("inf"))
    return out


def _is_cache_fresh(report_p: Path, input_mtimes: List[float]) -> bool:
    """True iff `report_p` exists and is at least as new as every input."""
    if not report_p.is_file():
        return False
    try:
        report_mtime = report_p.stat().st_mtime
    except OSError:
        return False
    return all(report_mtime >= t for t in input_mtimes)


def _load_cached_results(report_p: Path) -> Optional[Dict[str, Any]]:
    try:
        with report_p.open("r", encoding="utf-8") as fh:
            return json.load(fh)
    except Exception as e:
        logger.warning("cache read failed for %s: %s; will rerun", report_p, e)
        return None


# ── row builders / printers ──────────────────────────────────────────

def _build_row(design: str, variant: str,
               results: Optional[Dict[str, Any]],
               err_msg: Optional[str],
               runtime_s: float) -> Tuple[bool, Dict[str, Any]]:
    """Return (ok, row). On failure, row carries error_message; on
    success, row carries the flattened summary numbers."""
    if err_msg is not None:
        return False, {"design": design, "variant": variant,
                       "n_errors": 1, "error_message": err_msg,
                       "runtime_s": runtime_s}
    row = {"design": design, "variant": variant}
    row.update(summarise(results or {}))
    row["runtime_s"] = runtime_s
    return True, row


def _print_outcome(prefix: str, runtime_s: float, ok: bool,
                   row: Dict[str, Any], tag_prefix: str = "",
                   cached: bool = False) -> None:
    if not ok:
        msg = (row.get("error_message") or "").splitlines()
        first = msg[0] if msg else ""
        print(f"  {tag_prefix}{prefix}  {runtime_s:>6.2f}s  FAILED  {first}")
        return
    extras = []
    if row.get("lvs_ok") is False: extras.append("LVS!")
    if row.get("drc_ok") is False: extras.append("DRC!")
    if row.get("n_errors"):        extras.append(f"err={row['n_errors']}")
    tag = " ".join(extras) or ("CACHED" if cached else "OK")
    print(f"  {tag_prefix}{prefix}  {runtime_s:>6.2f}s  {tag}  "
          f"IL={row.get('il_max_db','-')} dB  "
          f"WL={row.get('wirelength_mm','-')} mm  "
          f"area={row.get('bbox_mm2','-')} mm2")


# ── background-pool helpers ──────────────────────────────────────────

def _finalize_bg(bg: _BgJob,
                 rows: List[Optional[Dict[str, Any]]],
                 tag_prefix: str) -> bool:
    """A bg job has exited. Drain its queue, read its report, populate
    rows[bg.idx], print, and return True iff the job succeeded."""
    runtime_s = round(time.time() - bg.t0, 2)
    err_msg: Optional[str] = None
    results: Optional[Dict[str, Any]] = None
    try:
        status, payload = bg.queue.get(timeout=2.0)
    except Exception:
        if bg.proc.exitcode == 0:
            status, payload = "ok", None
        else:
            status, payload = "fail", (
                f"child exited with code {bg.proc.exitcode}, no status message")
    if status == "ok":
        try:
            with bg.report_path.open("r", encoding="utf-8") as fh:
                results = json.load(fh)
        except Exception as e:
            err_msg = f"could not read report {bg.report_path}: {e}"
    else:
        err_msg = str(payload)

    ok, row = _build_row(bg.design, bg.variant, results, err_msg, runtime_s)
    rows[bg.idx] = row
    _print_outcome(bg.prefix, runtime_s, ok, row, tag_prefix=tag_prefix)
    return ok


def _reap_done_bg(bg_jobs: List[_BgJob],
                  rows: List[Optional[Dict[str, Any]]],
                  counters: Dict[str, int]) -> List[_BgJob]:
    """Non-blocking sweep: finalize any bg jobs whose process has
    exited; return the still-running ones."""
    still: List[_BgJob] = []
    for bg in bg_jobs:
        if bg.proc.is_alive():
            still.append(bg)
            continue
        ok = _finalize_bg(bg, rows, tag_prefix="[bg done] ")
        counters["bg_ok" if ok else "bg_fail"] += 1
    return still


def _wait_one_bg(bg_jobs: List[_BgJob],
                 rows: List[Optional[Dict[str, Any]]],
                 counters: Dict[str, int]) -> List[_BgJob]:
    """Block until at least one bg job exits, finalize it, return the
    remaining ones. Polls every 0.5s so we don't busy-spin."""
    while True:
        for i, bg in enumerate(bg_jobs):
            if not bg.proc.is_alive():
                ok = _finalize_bg(bg, rows, tag_prefix="[bg done] ")
                counters["bg_ok" if ok else "bg_fail"] += 1
                return bg_jobs[:i] + bg_jobs[i + 1:]
        time.sleep(0.5)


# ── main ──────────────────────────────────────────────────────────────

def main(argv=None) -> int:
    p = argparse.ArgumentParser(
        prog="batch_eval",
        description=__doc__.split("\n\n", 1)[0],
        formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--root", type=Path, required=True,
                   help="Directory holding <design>/<variant>/ subdirs.")
    p.add_argument("--pdk", type=Path, required=True,
                   help="PDK JSON (design_rules*.json picked up from the same dir).")
    p.add_argument("--design-rules", type=Path, default=None,
                   help="Override the auto-detected design-rules file.")
    p.add_argument("--summary-csv", type=Path, default=None,
                   help="Where to write the headline-numbers CSV. "
                        "Default: <root>/_batch_summary.csv")
    p.add_argument("--no-plots", action="store_true",
                   help="Skip SVG rendering (faster).")
    p.add_argument("--per-job-timeout", type=float, default=60.0,
                   help="Per-job wall-clock limit in seconds before the "
                        "main loop stops waiting on this job. The job "
                        "runs in a child process. By default (see "
                        "--max-bg-jobs) jobs that overrun are demoted to "
                        "a background pool instead of being killed. "
                        "Pass 0 to disable (run in-process, no timeout).")
    p.add_argument("--max-bg-jobs", type=int, default=5,
                   help="When a job exceeds --per-job-timeout, leave it "
                        "running in the background and move on to the "
                        "next job. At most N bg jobs run concurrently — "
                        "if the pool is full, the main loop blocks on "
                        "the next overrun until a slot frees. Pass 0 to "
                        "use the legacy behavior (kill on timeout).")
    p.add_argument("--no-labels", action="store_true", default=True,
                   help="Pass --no-labels to plotting.")
    p.add_argument("--filter", default=None,
                   help="Only run designs whose name contains this substring.")
    p.add_argument("--variant-filter", default=None,
                   help="Only run variants whose name contains this substring.")
    p.add_argument("--no-cache", action="store_true",
                   help="Disable cache reuse: rerun every job even if "
                        "the existing report.json is newer than its inputs.")
    p.add_argument("--force", action="store_true",
                   help="Alias for --no-cache. Forces a rerun of every "
                        "selected job, overwriting any existing report.json.")
    p.add_argument("-v", "--verbose", action="count", default=0)
    args = p.parse_args(argv)

    level = (logging.WARNING if args.verbose == 0
             else logging.INFO if args.verbose == 1
             else logging.DEBUG)
    logging.basicConfig(level=level, format="%(levelname)s %(name)s: %(message)s")

    if not args.root.is_dir():
        print(f"--root is not a directory: {args.root}", file=sys.stderr)
        return 2
    if not args.pdk.is_file():
        print(f"--pdk file not found: {args.pdk}", file=sys.stderr)
        return 2
    args.design_rules = _resolve_design_rules(args.pdk, args.design_rules)

    if args.summary_csv is None:
        args.summary_csv = args.root / "_batch_summary.csv"

    jobs = list(find_jobs(args.root))
    if args.filter:
        jobs = [j for j in jobs if args.filter in j[0]]
    if args.variant_filter:
        jobs = [j for j in jobs if args.variant_filter in j[1]]

    if not jobs:
        print("no jobs found.", file=sys.stderr)
        return 1

    # Pre-allocated by index so demoted-to-bg jobs can slot their rows
    # back into original job order when they eventually finish.
    rows: List[Optional[Dict[str, Any]]] = [None] * len(jobs)
    counters: Dict[str, int] = {
        "fg_ok": 0, "fg_fail": 0,
        "bg_ok": 0, "bg_fail": 0,
        "fg_killed_timeout": 0,
        "demoted_to_bg": 0,
        "cached": 0,
    }
    t_start = time.time()
    cache_disabled = bool(args.no_cache or args.force)
    existing_csv_rows = _load_existing_csv(args.summary_csv)

    timeout_s = float(args.per_job_timeout or 0)
    timeout_mode = timeout_s > 0
    mp_ctx = mp.get_context("spawn") if timeout_mode else None
    bg_max = max(0, int(args.max_bg_jobs or 0))
    bg_enabled = timeout_mode and bg_max > 0
    bg_jobs: List[_BgJob] = []

    print(f"running {len(jobs)} jobs from {args.root}")
    print(f"  pdk:           {args.pdk}")
    print(f"  design-rules:  {args.design_rules}")
    print(f"  plots:         {'no' if args.no_plots else 'yes (svg)'}")
    print(f"  per-job limit: {f'{timeout_s:g}s (subprocess)' if timeout_mode else 'none (in-process)'}")
    print(f"  bg pool:       "
          f"{f'up to {bg_max} concurrent overruns' if bg_enabled else 'off (kill on timeout)'}")
    print(f"  cache:         "
          f"{'disabled (--force/--no-cache)' if cache_disabled else 'on (skip when report.json is newer than all inputs)'}")
    print(f"  csv:           {args.summary_csv}"
          f"{f' (merging into {len(existing_csv_rows)} existing rows)' if existing_csv_rows else ' (new file)'}")
    print()

    for i, (design, variant, nl, pl, rt) in enumerate(jobs, 1):
        # Drain finished bg jobs (non-blocking) so the slot count is
        # accurate before we possibly need to demote this iteration's job.
        if bg_enabled and bg_jobs:
            bg_jobs = _reap_done_bg(bg_jobs, rows, counters)

        t0 = time.time()
        prefix = f"[{i:>3}/{len(jobs)}] {design}/{variant}"
        placement_dir = pl.parent
        stem = pl.stem.removesuffix("_placement") if hasattr(str, "removesuffix") else pl.stem.replace("_placement", "")
        report_path = placement_dir / f"{stem}_report.json"

        # ── cache fast-path ────────────────────────────────────────────
        # Reuse the existing report.json iff its mtime is at least as new
        # as every input (netlist / placement / routing / pdk / design-rules).
        # Failed/timeout runs never wrote a report, so they naturally miss.
        if not cache_disabled:
            input_mtimes = _input_mtimes(nl, pl, rt, args.pdk, args.design_rules)
            if _is_cache_fresh(report_path, input_mtimes):
                cached_results = _load_cached_results(report_path)
                if cached_results is not None:
                    runtime_s = round(time.time() - t0, 2)
                    ok, row = _build_row(design, variant, cached_results,
                                         None, runtime_s)
                    rows[i - 1] = row
                    counters["cached"] += 1
                    _print_outcome(prefix, runtime_s, ok, row, cached=True)
                    continue

        # Outcome variables filled by one of the branches below.
        results: Optional[Dict[str, Any]] = None
        err_msg: Optional[str] = None
        timed_out = False
        demoted = False

        if timeout_mode:
            q = mp_ctx.Queue()
            proc = mp_ctx.Process(
                target=_job_worker,
                args=(str(nl), str(pl), str(rt), str(args.pdk),
                      str(args.design_rules) if args.design_rules else None,
                      bool(args.no_plots), bool(args.no_labels),
                      str(report_path), q),
            )
            proc.start()
            proc.join(timeout_s)
            if proc.is_alive():
                if bg_enabled:
                    # Demote to bg pool. If the pool is full, block here
                    # until at least one slot frees up.
                    if len(bg_jobs) >= bg_max:
                        print(f"  {prefix}  >{timeout_s:g}s, bg pool full "
                              f"({len(bg_jobs)}/{bg_max}); waiting for a slot…")
                        bg_jobs = _wait_one_bg(bg_jobs, rows, counters)
                    bg_jobs.append(_BgJob(
                        idx=i - 1, design=design, variant=variant,
                        proc=proc, queue=q, report_path=report_path,
                        prefix=prefix, t0=t0))
                    counters["demoted_to_bg"] += 1
                    demoted = True
                    elapsed_so_far = round(time.time() - t0, 2)
                    print(f"  {prefix}  {elapsed_so_far:>5.2f}s  →BG  "
                          f"({len(bg_jobs)}/{bg_max} running)")
                else:
                    proc.terminate()
                    proc.join(5)
                    if proc.is_alive():
                        proc.kill()
                        proc.join(2)
                    timed_out = True
            else:
                try:
                    status, payload = q.get_nowait()
                except Exception:
                    status, payload = "fail", "child exited without reporting status"
                if status == "ok":
                    try:
                        with report_path.open("r", encoding="utf-8") as fh:
                            results = json.load(fh)
                    except Exception as e:
                        err_msg = f"could not read report {report_path}: {e}"
                else:
                    err_msg = str(payload)
        else:
            try:
                d = Design.from_paths(nl, pl, rt, args.pdk,
                                      design_rules_p=args.design_rules)
                cfg = EvalConfig()
                results = run(d, cfg, tiers=("1", "2", "3"))
                write_json(results, str(report_path))
                if not args.no_plots:
                    from pic_evaluator.plotting import generate_plots
                    generate_plots(d, cfg, results, str(placement_dir),
                                   show_labels=not args.no_labels)
            except Exception as e:
                err_msg = f"{type(e).__name__}: {e}"
                logger.exception("job failed: %s/%s", design, variant)

        if demoted:
            # Row will be filled when the bg job finishes; keep going.
            continue

        runtime_s = round(time.time() - t0, 2)

        if timed_out:
            counters["fg_killed_timeout"] += 1
            counters["fg_fail"] += 1
            rows[i - 1] = {"design": design, "variant": variant,
                           "n_errors": 1,
                           "error_message": f"TIMEOUT (>{timeout_s:g}s)",
                           "runtime_s": runtime_s}
            print(f"  {prefix}  {runtime_s:>5.2f}s  TIMEOUT (>{timeout_s:g}s) — killed")
        else:
            ok, row = _build_row(design, variant, results, err_msg, runtime_s)
            rows[i - 1] = row
            counters["fg_ok" if ok else "fg_fail"] += 1
            _print_outcome(prefix, runtime_s, ok, row)

    # ── drain remaining background jobs ──────────────────────────────
    if bg_jobs:
        print()
        print(f"== draining {len(bg_jobs)} background job(s) ==")
        while bg_jobs:
            bg_jobs = _wait_one_bg(bg_jobs, rows, counters)

    # ── merge this run's rows into the existing CSV snapshot ─────────
    # `existing_csv_rows` was loaded at startup. Rows we touched this run
    # overwrite their (design, variant) entries; rows we did not touch
    # (e.g. designs filtered out via --filter) are preserved as-is.
    fresh_rows = [r for r in rows if r is not None]
    n_overwrote = 0
    n_added = 0
    for r in fresh_rows:
        key = (r.get("design", ""), r.get("variant", ""))
        if key in existing_csv_rows:
            n_overwrote += 1
        else:
            n_added += 1
        existing_csv_rows[key] = r
    n_preserved = len(existing_csv_rows) - n_overwrote - n_added

    if existing_csv_rows:
        # Stable column order: stable seed + first-seen rest.
        fieldnames: List[str] = ["design", "variant"]
        for r in existing_csv_rows.values():
            for k in r:
                if k not in fieldnames:
                    fieldnames.append(k)
        args.summary_csv.parent.mkdir(parents=True, exist_ok=True)
        with args.summary_csv.open("w", newline="", encoding="utf-8") as fh:
            w = csv.DictWriter(fh, fieldnames=fieldnames, extrasaction="ignore")
            w.writeheader()
            for key in sorted(existing_csv_rows.keys()):
                w.writerow(existing_csv_rows[key])

    n_cached = counters["cached"]
    n_ran_ok = counters["fg_ok"] + counters["bg_ok"]
    n_ok = n_cached + n_ran_ok
    n_fail = counters["fg_fail"] + counters["bg_fail"]
    elapsed = time.time() - t_start
    print()
    print(f"== summary: {n_ok} ok ({n_cached} cached, {n_ran_ok} ran), "
          f"{n_fail} failed in {elapsed:.1f}s ==")
    if bg_enabled:
        print(f"   bg pool: {counters['demoted_to_bg']} jobs ran past "
              f"{timeout_s:g}s in background "
              f"({counters['bg_ok']} ok, {counters['bg_fail']} fail)")
    elif timeout_mode and counters["fg_killed_timeout"]:
        print(f"   ({counters['fg_killed_timeout']} timed out and were killed)")
    print(f"   csv: {args.summary_csv}  "
          f"({n_preserved} preserved, {n_overwrote} overwritten, {n_added} added)")

    # ── dataset-level rollup over the current --root tree ─────────────
    # Walks every (design × variant) currently on disk (not just this run's
    # filtered subset) and totals up device instances + routes. Sums are
    # over all jobs without deduplicating designs across variants — i.e.,
    # one variant of a 100-device netlist contributes 100 devices, all four
    # variants together contribute 400.
    n_jobs_disk = 0
    unique_designs: set = set()
    total_devices = 0.0
    n_dev_rows = 0
    total_routes = 0
    n_route_files = 0
    for design, variant, _nl, _pl, rt in find_jobs(args.root):
        n_jobs_disk += 1
        unique_designs.add(design)

        csv_row = existing_csv_rows.get((design, variant))
        if csv_row:
            try:
                v = float(csv_row.get("n_devices", ""))
                if v == v:                 # not NaN
                    total_devices += v
                    n_dev_rows += 1
            except (TypeError, ValueError):
                pass

        try:
            with rt.open("r", encoding="utf-8") as fh:
                rd = json.load(fh)
            r_list = rd.get("routes")
            if isinstance(r_list, list):
                total_routes += len(r_list)
                n_route_files += 1
        except Exception as e:
            logger.warning("could not read routes from %s: %s", rt, e)

    print()
    print("== dataset stats (over the current --root tree) ==")
    print(f"   {n_jobs_disk} routing files on disk "
          f"across {len(unique_designs)} unique designs")
    print(f"   {int(total_devices):,} total device instances  "
          f"(sum of n_devices over {n_dev_rows}/{n_jobs_disk} CSV rows)")
    print(f"   {total_routes:,} total routes  "
          f"(sum of len(routes) over {n_route_files}/{n_jobs_disk} routing.json files)")
    return 0 if n_fail == 0 else 1


if __name__ == "__main__":
    raise SystemExit(main())