File size: 26,812 Bytes
34292e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
#!/usr/bin/env python3

import json
import argparse
import os
import re
import sys
from datetime import datetime, timezone

# --- PUBSUB ---
from google.cloud import pubsub_v1
from google.oauth2 import service_account

# --- END PUBSUB ---

# Remember where we were invoked from: the chdir below would otherwise silently
# reinterpret any relative path passed on the command line as relative to flow/.
INVOCATION_DIR = os.getcwd()

# make sure the working dir is flow/
os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))

BUILD_TIME_FORMAT = "%Y-%m-%d %H:%M"
# The backend drops a longer no_metrics_reason without an error.
MAX_NO_METRICS_REASON = 100


def _build_time(val):
    """Validate --buildTime against BUILD_TIME_FORMAT; blank means unset."""
    val = val.strip()
    if not val:
        return None
    try:
        parsed = datetime.strptime(val, BUILD_TIME_FORMAT)
    except ValueError:
        raise argparse.ArgumentTypeError(
            f"'{val}' does not match the expected format 'YYYY-MM-DD HH:MM'"
        )
    # strptime accepts unpadded fields such as "2026-1-5 1:3".
    return parsed.strftime(BUILD_TIME_FORMAT)


def _non_negative_int(val):
    try:
        number = int(val)
    except ValueError:
        raise argparse.ArgumentTypeError(f"'{val}' is not an integer")
    if number < 0:
        raise argparse.ArgumentTypeError(f"'{val}' is negative")
    return number


# Create the argument parser
parser = argparse.ArgumentParser(description="Process some integers.")

# Add the named arguments
parser.add_argument("--buildID", type=str, help="Build ID from jenkins")
parser.add_argument("--branchName", type=str, help="Current Branch Name")
parser.add_argument("--pipelineID", type=str, help="Jenkins pipeline ID")
parser.add_argument("--commitSHA", type=str, help="Current commit sha")
parser.add_argument("--jenkinsURL", type=str, help="Jenkins Report URL")
parser.add_argument(
    "--changeBranch", type=str, help="Branch corresponding to change request"
)
parser.add_argument("--variant", type=str, default="base")
parser.add_argument(
    "--jobName",
    type=str,
    default=None,
    help="Canonical Jenkins job-folder name (JOB_NAME with the trailing "
    "/<branch> segment stripped, folder slashes kept). When set, the "
    "Pub/Sub payload is emitted as schema v3 with a top-level job_name "
    "so the backend resolves the pipeline directly instead of "
    "classifying the BUILD_TAG.",
)
parser.add_argument(
    "--provenanceFile",
    type=str,
    default=None,
    help="Path to a JSON file describing what was actually built: the "
    "jenkins-ci shared-library version and the submodule commits present in "
    "the build workspace. Must be produced there, not here — nightly "
    "pipelines repoint tools/OpenROAD, so the reporting workspace holds the "
    "pinned commit rather than the built one. When supplied alongside "
    "--jobName the payload is emitted as schema v4.",
)
parser.add_argument(
    "--buildTime",
    type=_build_time,
    default=None,
    help="When the build ran, emitted as build_time on the pipeline payload. "
    "Defaults to now in UTC, in the format genMetrics.py uses for "
    "run__flow__generate_date (%%Y-%%m-%%d %%H:%%M). The backend reads it "
    "as UTC.",
)
parser.add_argument(
    "--expectedDesigns",
    type=_non_negative_int,
    default=None,
    help="Number of designs the pipeline set out to build. When positive, "
    "emitted as design_count on the pipeline payload so the backend can tell "
    "a build that produced fewer (or no) metrics from one that built fewer "
    "designs. 0 is accepted but not sent, since the backend ignores it. Not "
    "sent on the per-design fallback for oversized payloads.",
)
parser.add_argument(
    "--noMetricsReason",
    type=str,
    default=None,
    help="Why no design produced metrics, as a short code such as "
    "no_reports_found (at most 100 characters; a longer value is dropped with "
    "a warning). Emitted as no_metrics_reason only on a payload with no "
    "designs.",
)
parser.add_argument(
    "--buildUserEmail",
    type=str,
    default=None,
    help="Email of the Jenkins user who started the build by hand "
    "(BUILD_USER_EMAIL). Omitted for SCM, timer and branch-scan triggers. "
    "The dashboard attributes the build to this user. Defaults to "
    "$UPLOAD_BUILD_USER_EMAIL, which keeps the address out of a traced "
    "(sh -x) command line.",
)
parser.add_argument(
    "--changeAuthorEmail",
    type=str,
    default=None,
    help="Email of the pull request's author on a PR build "
    "(CHANGE_AUTHOR_EMAIL). Empty when the author's GitHub email is private. "
    "Defaults to $UPLOAD_CHANGE_AUTHOR_EMAIL.",
)

# --- PUBSUB args ---
parser.add_argument(
    "--jenkinsEnv",
    type=str,
    default="unknown",
    choices=["public", "secure", "unknown"],
    help="Jenkins environment (public or secure)",
)
parser.add_argument("--pubsubProjectID", type=str, help="GCP project ID for Pub/Sub")
parser.add_argument(
    "--pubsubTopicID",
    type=str,
    default="ci-metrics-reports-topics",
    help="Pub/Sub topic ID",
)
parser.add_argument(
    "--pubsubCred", type=str, help="Service account credentials file for Pub/Sub"
)
# --- END PUBSUB args ---

# Parse the arguments
args = parser.parse_args()


# --- PUBSUB ---
# Pub/Sub hard cap is 10 MB. Stay under with safety margin to leave room for
# attribute overhead and future payload growth.
MAX_PUBSUB_BYTES = 8 * 1024 * 1024


def build_design_record(dataFile, platform, design, variant, outcome=None):
    """Return a dict for one design to be included in the pipeline-level payload.

    ``dataFile`` is the design's metadata.json, or ``None`` for a run that ended
    before writing one; such a record carries only its ``outcome``.
    """
    record = {"platform": platform, "design": design, "variant": variant}
    if dataFile:
        with open(dataFile) as f:
            data = json.load(f)
        record["metrics"] = {k.replace(":", "__"): v for k, v in data.items()}
    if outcome:
        record["outcome"] = outcome
    return record


# How a flow run ended, as the CI job records it next to the design's reports:
# {"exit_code": int, "timed_out": bool, "elapsed_minutes": float,
#  "limit_minutes": int}. Every key is optional.
STATUS_FILENAME = "flow-status.json"
MAX_OUTCOME_MESSAGE = 1024
# Stage log names start with the step number: 1_2_yosys.log, 5_1_grt.log.
STAGE_LOG = re.compile(r"^(\d+)_(?:(\d+)_)?.*\.log$")
# The first matching line of a failing stage's log is the error reported. The
# OpenROAD form carries the tool's message ID; Yosys prints "ERROR: ".
ERROR_LINE = re.compile(
    r"\[(?:ERROR|CRITICAL|FATAL) [A-Z][A-Z0-9]*-\d+\].*|^ERROR: .*|^Error: .*"
)
# What a tool that died on a signal leaves in its log, as opposed to an error it
# reported itself.
CRASH_LINE = re.compile(r"Signal \d+ received|Segmentation fault|core dumped")


def _stage_name(log_name):
    """The flow stage a stage log belongs to, e.g. 5_1_grt.log -> "grt"."""
    match = STAGE_LOG.match(log_name)
    if not match:
        return None
    step, sub = match.group(1), match.group(2)
    if step == "5":
        return "grt" if sub == "1" else "route"
    return {
        "1": "synth",
        "2": "floorplan",
        "3": "place",
        "4": "cts",
        "6": "finish",
    }.get(step)


def _stage_logs(log_dir):
    """The design's stage logs, last step first."""
    try:
        names = os.listdir(log_dir)
    except OSError:
        return []

    def key(name):
        match = STAGE_LOG.match(name)
        return (int(match.group(1)), int(match.group(2) or 0), name)

    return sorted((n for n in names if STAGE_LOG.match(n)), key=key, reverse=True)


def _scan_log(path):
    """The first error line of a log and whether it shows a crash."""
    error_line = None
    crashed = False
    try:
        with open(path, errors="replace") as f:
            for line in f:
                if error_line is None:
                    match = ERROR_LINE.search(line)
                    if match:
                        error_line = match.group(0).strip()
                if not crashed and CRASH_LINE.search(line):
                    crashed = True
                if error_line is not None and crashed:
                    break
    except OSError:
        pass
    return error_line, crashed


def read_flow_outcome(report_dir, log_dir):
    """The design's outcome from its flow-status.json and stage logs, or ``None``.

    ``status`` is ``timeout`` when the time limit stopped the run, ``passed`` on
    exit code 0, ``crash`` when the last stage log shows the tool died on a
    signal, and ``error`` otherwise. A failed run also names the stage it ended
    in and the first error line found in its logs, last stage first.
    """
    path = os.path.join(report_dir, STATUS_FILENAME)
    if not os.path.exists(path):
        return None
    try:
        with open(path) as f:
            status = json.load(f)
    except (OSError, ValueError) as e:
        print(f"[WARN] Could not read {path}: {e}. Reporting no outcome.")
        return None
    if not isinstance(status, dict):
        print(f"[WARN] {path} does not hold a JSON object. Reporting no outcome.")
        return None

    exit_code = status.get("exit_code")
    timed_out = status.get("timed_out") is True
    if not timed_out and not isinstance(exit_code, int):
        print(f"[WARN] {path} has no exit_code. Reporting no outcome.")
        return None

    outcome = {}
    for key in ("elapsed_minutes", "limit_minutes"):
        value = status.get(key)
        if (
            isinstance(value, (int, float))
            and not isinstance(value, bool)
            and value >= 0
        ):
            outcome[key] = value

    if not timed_out and exit_code == 0:
        outcome["status"] = "passed"
        return outcome

    logs = _stage_logs(log_dir)
    if logs:
        stage = _stage_name(logs[0])
        if stage:
            outcome["stage"] = stage

    message = None
    crashed = False
    for i, name in enumerate(logs):
        error_line, log_crashed = _scan_log(os.path.join(log_dir, name))
        if i == 0:
            crashed = log_crashed
        if error_line:
            message = error_line
            break
    if message:
        outcome["message"] = message[:MAX_OUTCOME_MESSAGE]

    if timed_out:
        outcome["status"] = "timeout"
    else:
        outcome["status"] = "crash" if crashed else "error"
    return outcome


def _submodule_defect(entry):
    """Describe why ``entry`` is not a usable submodule record, or ``None``.

    Mirrors the keys the backend requires of every element of the v4
    ``submodules`` array. ``overridden`` is checked for presence only: ``False``
    is the common, valid case.
    """
    if not isinstance(entry, dict):
        return "is not an object"

    for key in ("path", "sha"):
        value = entry.get(key)
        if not isinstance(value, str) or not value.strip():
            return f"has no {key}"

    if entry.get("overridden") is None:
        return "has no overridden"

    return None


def load_provenance(path):
    """Return the build-provenance dict from ``path``, or ``None``.

    A malformed or unreadable file degrades to v3 rather than failing the upload:
    losing the whole metrics report over missing provenance would be a worse
    outcome than losing the provenance.
    """
    if not path:
        return None

    # Relative paths are resolved against the caller's directory, not flow/.
    if not os.path.isabs(path):
        path = os.path.join(INVOCATION_DIR, path)

    try:
        with open(path) as f:
            data = json.load(f)
    except (OSError, ValueError) as e:
        print(
            f"[WARN] Could not read provenance file '{path}': {e}. "
            "Falling back to v3."
        )
        return None

    # json.load accepts any top-level JSON value: a file holding a list or a
    # bare scalar parses fine, then .get() below raises AttributeError.
    if not isinstance(data, dict):
        print(
            f"[WARN] Provenance file '{path}' does not contain a JSON object. "
            "Falling back to v3."
        )
        return None

    submodules = data.get("submodules")
    library = data.get("jenkins_library")
    if not isinstance(submodules, list) or not submodules:
        print(f"[WARN] Provenance file '{path}' has no submodules. Falling back to v3.")
        return None
    if not isinstance(library, dict) or not library.get("ref"):
        print(
            f"[WARN] Provenance file '{path}' has no jenkins_library.ref. "
            "Falling back to v3."
        )
        return None

    # Every entry has to satisfy the backend's per-entry v4 keys, not just the
    # array as a whole: one defective entry rejects the whole message, and the
    # point of degrading to v3 is to not emit a message the backend will reject.
    for i, entry in enumerate(submodules):
        defect = _submodule_defect(entry)
        if defect:
            print(
                f"[WARN] Provenance file '{path}': submodules[{i}] {defect}. "
                "Falling back to v3."
            )
            return None

    return {"jenkins_library": library, "submodules": submodules}


def resolve_job_name(args):
    """Canonical job name, or None when absent/blank."""
    return args.jobName.strip() if args.jobName else None


def resolve_schema_version(args, provenance):
    """The schema version this run's payload satisfies.

    v4 needs both a job name and provenance; the backend requires every v4 key,
    so a run that could not capture its submodules must stay on v3 rather than
    emit a v4 message the backend will reject.
    """
    if not resolve_job_name(args):
        return 2
    return 4 if provenance else 3


def resolve_requester(args):
    """Who asked for the build, as the payload keys the backend reads.

    Each value comes from its flag or, when the flag is absent, from its
    environment variable. An empty flag counts as given, so it suppresses the
    variable. Blank values are left out rather than sent empty, and a value
    without an "@" is dropped with a warning: an unset Groovy variable
    interpolates as the string "null", which must not be stored as an email.
    The keys ride on every schema version: the backend reads them by presence,
    and they describe the build rather than the payload's shape, so they do
    not bump the version.
    """
    requester = {}
    for key, flag, value, env_var in (
        (
            "build_user_email",
            "--buildUserEmail",
            args.buildUserEmail,
            "UPLOAD_BUILD_USER_EMAIL",
        ),
        (
            "change_author_email",
            "--changeAuthorEmail",
            args.changeAuthorEmail,
            "UPLOAD_CHANGE_AUTHOR_EMAIL",
        ),
    ):
        if value is None:
            value = os.environ.get(env_var, "")
        value = value.strip()
        if not value:
            continue
        if "@" not in value:
            print(f"[WARN] Not sending {flag}: '{value}' is not an email address.")
            continue
        requester[key] = value
    return requester


def resolve_build_time(args):
    """The build time to report, defaulting to now in genMetrics.py's format.

    The default is UTC because the backend reads the value as UTC; local time
    would shift the build by the agent's offset wherever that is not UTC.
    """
    if args.buildTime:
        return args.buildTime
    return datetime.now(timezone.utc).strftime(BUILD_TIME_FORMAT)


def resolve_no_metrics_reason(args, design_records):
    """The no_metrics_reason to send, and why a given reason is not sent.

    Returns ``(reason, problem)``: ``reason`` is ``None`` unless it goes on the
    payload, and ``problem`` describes a non-blank reason that was dropped.
    """
    reason = args.noMetricsReason.strip() if args.noMetricsReason else ""
    if not reason:
        return None, None
    # A reason only describes a build that produced nothing; on a payload with
    # designs it would contradict the metrics it carries.
    if design_records:
        return None, "design records were collected"
    if len(reason) > MAX_NO_METRICS_REASON:
        return None, f"it is longer than {MAX_NO_METRICS_REASON} characters"
    return reason, None


def build_pipeline_payload(
    design_records, args, provenance=None, no_metrics_reason=None, requester=None
):
    """Return the pipeline-level payload dict.

    Emits schema v2 (no job name), v3 (job name) or v4 (job name plus build
    provenance) — see :func:`resolve_schema_version`.
    """
    job_name = resolve_job_name(args)
    schema_version = resolve_schema_version(args, provenance)
    payload = {
        "payload_schema_version": schema_version,
        "jenkins_env": args.jenkinsEnv,
        "build_id": args.buildID,
        "branch_name": args.branchName,
        "pipeline_id": args.pipelineID,
        "change_branch": args.changeBranch,
        "commit_sha": args.commitSHA,
        "jenkins_url": args.jenkinsURL,
        "build_time": resolve_build_time(args),
        "designs": design_records,
    }
    if job_name:
        payload["job_name"] = job_name
    if args.expectedDesigns:
        payload["design_count"] = args.expectedDesigns
    if no_metrics_reason:
        payload["no_metrics_reason"] = no_metrics_reason
    # Only a v4 payload carries provenance. Provenance without a job name cannot
    # be v4 (the backend requires job_name from v3 up), and attaching v4 keys to
    # a message labelled v2 would make payload_schema_version stop describing
    # the payload.
    if schema_version == 4:
        payload.update(provenance)
    if requester:
        payload.update(requester)
    return payload


def publish_pipeline_report(
    publisher, topic_path, message_data, design_count, args, provenance=None
):
    """Publish a pre-encoded pipeline message (v2, v3 or v4)."""
    size_kb = len(message_data) / 1024
    schema_version = str(resolve_schema_version(args, provenance))
    print(
        f"[INFO] Publishing v{schema_version} pipeline report "
        f"({design_count} designs, {size_kb:.1f} KB) to Pub/Sub."
    )
    future = publisher.publish(
        topic_path,
        data=message_data,
        payload_schema_version=schema_version,
        jenkins_env=args.jenkinsEnv,
    )
    message_id = future.result()
    print(f"[INFO] Published pipeline report to Pub/Sub (message ID: {message_id}).")


def publish_v1_per_design(
    publisher, topic_path, design_records, args, provenance=None, requester=None
):
    """Fallback path used when the v2 pipeline payload exceeds MAX_PUBSUB_BYTES.

    Emits one v1-format message per design (no payload_schema_version, metrics
    flattened at the root), matching the legacy schema the ingestion service
    still supports. Returns the number of designs that failed to publish.

    Provenance is mirrored onto every message: all of them resolve to the same
    build, and the backend upserts components by path, so N copies converge on
    one set of rows. Omitting it here would make an oversized nightly look like
    a build with no overrides.

    Unlike the pipeline payload this is not gated on the v4 job-name
    requirement: a v1 message declares no schema version, so there is nothing
    for the extra keys to contradict, and the backend reads provenance here by
    key presence rather than by version.

    design_count is left off: the backend reads every v1 root key it does not
    list as metadata as a metric, and design_count is not on that list, so it
    would surface as a bogus metric. build_time and no_metrics_reason are
    metadata there but not needed: each design's metrics carry
    run__flow__generate_date, which the backend prefers, and a reason only
    applies to an empty build, whose payload is far below the size cap.

    The requester keys go on after the metrics, so a metric that happened to
    share their name could not replace who asked for the build.

    A design's outcome rides at the root as ``outcome``. A design that has only
    an outcome carries no metrics to name it, so its message names the design
    with the same run__flow__ keys metadata.json would hold, dated by the build.
    """
    futures = []
    failed = 0
    for d in design_records:
        payload = {
            "build_id": args.buildID,
            "branch_name": args.branchName,
            "pipeline_id": args.pipelineID,
            "change_branch": args.changeBranch,
            "commit_sha": args.commitSHA,
            "jenkins_url": args.jenkinsURL,
            "jenkins_env": args.jenkinsEnv,
        }
        if provenance:
            payload.update(provenance)
        if "metrics" in d:
            payload.update(d["metrics"])
        else:
            payload.update(
                {
                    "run__flow__platform": d["platform"],
                    "run__flow__design": d["design"],
                    "run__flow__variant": d["variant"],
                    "run__flow__generate_date": resolve_build_time(args),
                }
            )
        if "outcome" in d:
            payload["outcome"] = d["outcome"]
        if requester:
            payload.update(requester)

        message_data = json.dumps(payload, default=str).encode("utf-8")
        try:
            future = publisher.publish(
                topic_path,
                data=message_data,
                jenkins_env=args.jenkinsEnv,
            )
            futures.append((d, future))
        except Exception as e:
            failed += 1
            print(
                f"[ERROR] Pub/Sub v1 fallback publish failed for "
                f"{d['platform']} {d['design']} {d['variant']}: {e}"
            )

    for d, future in futures:
        try:
            message_id = future.result()
            print(
                f"[INFO] Published v1 fallback message (ID: {message_id}) for "
                f"{d['platform']} {d['design']} {d['variant']}."
            )
        except Exception as e:
            failed += 1
            print(
                f"[ERROR] Pub/Sub v1 fallback publish failed for "
                f"{d['platform']} {d['design']} {d['variant']}: {e}"
            )
    return failed


# --- END PUBSUB ---


# --- PUBSUB init ---
publisher = None
topic_path = None
if args.pubsubCred and args.pubsubProjectID:
    pubsub_credentials = service_account.Credentials.from_service_account_file(
        args.pubsubCred
    )
    publisher = pubsub_v1.PublisherClient(credentials=pubsub_credentials)
    topic_path = publisher.topic_path(args.pubsubProjectID, args.pubsubTopicID)
    print(f"[INFO] Pub/Sub publisher initialized for topic: {topic_path}")
elif args.pubsubProjectID:
    # No credentials file — use default credentials (e.g., emulator or ADC)
    publisher = pubsub_v1.PublisherClient()
    topic_path = publisher.topic_path(args.pubsubProjectID, args.pubsubTopicID)
    print(
        f"[INFO] Pub/Sub publisher initialized (default creds) for topic: {topic_path}"
    )
# --- END PUBSUB init ---

RUN_FILENAME = "metadata.json"

# --- PUBSUB ---
design_records = []
# --- END PUBSUB ---

for reportDir, dirs, files in sorted(os.walk("reports", topdown=False)):
    dirList = reportDir.split(os.sep)
    if len(dirList) != 4:
        continue

    # basic info about test design
    platform = dirList[1]
    design = dirList[2]
    variant = dirList[3]
    if platform == "sky130hd_fakestack" or platform == "src":
        print(f"[WARN] Skiping upload {platform} {design} {variant}.")
        continue
    dataFile = os.path.join(reportDir, RUN_FILENAME)
    if not os.path.exists(dataFile):
        dataFile = None
    outcome = read_flow_outcome(
        reportDir, os.path.join("logs", platform, design, variant)
    )
    if dataFile is None and outcome is None:
        print(f"[WARN] No data file for {platform} {design} {variant}.")
        continue
    if dataFile is None:
        print(
            f"[INFO] No data file for {platform} {design} {variant}; "
            f"reporting its {outcome['status']} outcome only."
        )
    # --- PUBSUB ---
    if publisher:
        design_records.append(
            build_design_record(dataFile, platform, design, variant, outcome)
        )
    # --- END PUBSUB ---

# --- PUBSUB ---
# A failed publish exits non-zero. A warning alone let CI builds pass while the
# QoR dashboard stopped receiving results, which froze the baseline that later
# builds are compared against.
#
# A build where no design produced metrics still publishes, with an empty
# designs list, so the dashboard lists it as a build without metrics instead of
# leaving it out.
if publisher:
    if not design_records:
        print(
            "[WARN] No design records were collected. Publishing an empty "
            "(no-metrics) pipeline report."
        )
    no_metrics_reason, reason_problem = resolve_no_metrics_reason(args, design_records)
    if reason_problem:
        print(f"[WARN] Ignoring --noMetricsReason because {reason_problem}.")
    provenance = load_provenance(args.provenanceFile)
    requester = resolve_requester(args)
    payload = build_pipeline_payload(
        design_records, args, provenance, no_metrics_reason, requester
    )
    message_data = json.dumps(payload, default=str).encode("utf-8")

    if len(message_data) > MAX_PUBSUB_BYTES:
        print(
            f"[WARN] Payload size {len(message_data) / 1024:.1f} KB exceeds "
            f"{MAX_PUBSUB_BYTES // 1024} KB cap. Falling back to v1 per-design publish "
            f"({len(design_records)} messages)."
        )
        if args.expectedDesigns:
            print(
                "[WARN] --expectedDesigns is not sent on the v1 fallback; the "
                "backend will report this build's completeness as unknown."
            )
        failed = publish_v1_per_design(
            publisher, topic_path, design_records, args, provenance, requester
        )
        if failed:
            print(
                f"[ERROR] {failed} of {len(design_records)} designs were not published."
            )
            sys.exit(1)
    else:
        try:
            publish_pipeline_report(
                publisher,
                topic_path,
                message_data,
                len(design_records),
                args,
                provenance,
            )
        except Exception as e:
            print(f"[ERROR] Pub/Sub publish failed for pipeline report: {e}")
            sys.exit(1)
        if not design_records:
            print("[INFO] Published an empty (no-metrics) pipeline report.")
# --- END PUBSUB ---