Skip to content

Commit 5f45b91

Browse files
ci: publish build provenance in the metrics payload (schema v4)
The payload identified a build by its ORFS superproject commit alone. Nightly pipelines repoint tools/OpenROAD away from the pinned submodule, so that commit does not describe what was built. Add --provenanceFile, carrying the jenkins-ci shared-library version and the submodule commits captured in the build workspace. It has to be produced there and passed in: the reporting workspace is a fresh submodule-pinned checkout, so reading the SHAs here would report the pinned commit for a build that used something else. Passed as a file rather than argv so the JSON never has to survive shell quoting. Emit v4 when both a job name and provenance are present, v3 when provenance is missing or malformed, v2 when there is no job name. The backend requires every v4 key, so a run that could not capture its submodules must stay on v3 rather than emit a message that will be rejected. Mirror provenance onto the oversized-payload v1 fallback as well — all its messages resolve to the same build and the backend upserts components by path, so omitting it would make an oversized nightly look like a build with no overrides. Also resolve a relative --provenanceFile against the caller's directory: the chdir to flow/ at import time would otherwise silently reinterpret it. Signed-off-by: Miguel Dalberto Pedro <miguel.pedro@precisioninno.com>
1 parent 56496f3 commit 5f45b91

1 file changed

Lines changed: 144 additions & 16 deletions

File tree

‎flow/util/uploadMetadata.py‎

Lines changed: 144 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@
1818

1919
# --- END PUBSUB ---
2020

21+
# Remember where we were invoked from: the chdir below would otherwise silently
22+
# reinterpret any relative path passed on the command line as relative to flow/.
23+
INVOCATION_DIR = os.getcwd()
24+
2125
# make sure the working dir is flow/
2226
os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
2327

@@ -45,6 +49,17 @@
4549
"so the backend resolves the pipeline directly instead of "
4650
"classifying the BUILD_TAG.",
4751
)
52+
parser.add_argument(
53+
"--provenanceFile",
54+
type=str,
55+
default=None,
56+
help="Path to a JSON file describing what was actually built: the "
57+
"jenkins-ci shared-library version and the submodule commits present in "
58+
"the build workspace. Must be produced there, not here — nightly "
59+
"pipelines repoint tools/OpenROAD, so the reporting workspace holds the "
60+
"pinned commit rather than the built one. When supplied alongside "
61+
"--jobName the payload is emitted as schema v4.",
62+
)
4863

4964
# --- PUBSUB args ---
5065
parser.add_argument(
@@ -229,17 +244,105 @@ def build_design_record(dataFile, platform, design, variant, rules):
229244
}
230245

231246

232-
def build_pipeline_payload(design_records, args):
247+
def _submodule_defect(entry):
248+
"""Describe why ``entry`` is not a usable submodule record, or ``None``.
249+
250+
Mirrors the keys the backend requires of every element of the v4
251+
``submodules`` array. ``overridden`` is checked for presence only: ``False``
252+
is the common, valid case.
253+
"""
254+
if not isinstance(entry, dict):
255+
return "is not an object"
256+
257+
for key in ("path", "sha"):
258+
value = entry.get(key)
259+
if not isinstance(value, str) or not value.strip():
260+
return f"has no {key}"
261+
262+
if entry.get("overridden") is None:
263+
return "has no overridden"
264+
265+
return None
266+
267+
268+
def load_provenance(path):
269+
"""Return the build-provenance dict from ``path``, or ``None``.
270+
271+
A malformed or unreadable file degrades to v3 rather than failing the upload:
272+
losing the whole metrics report over missing provenance would be a worse
273+
outcome than losing the provenance.
274+
"""
275+
if not path:
276+
return None
277+
278+
# Relative paths are resolved against the caller's directory, not flow/.
279+
if not os.path.isabs(path):
280+
path = os.path.join(INVOCATION_DIR, path)
281+
282+
try:
283+
with open(path) as f:
284+
data = json.load(f)
285+
except (OSError, ValueError) as e:
286+
print(
287+
f"[WARN] Could not read provenance file '{path}': {e}. "
288+
"Falling back to v3."
289+
)
290+
return None
291+
292+
submodules = data.get("submodules")
293+
library = data.get("jenkins_library")
294+
if not isinstance(submodules, list) or not submodules:
295+
print(f"[WARN] Provenance file '{path}' has no submodules. Falling back to v3.")
296+
return None
297+
if not isinstance(library, dict) or not library.get("ref"):
298+
print(
299+
f"[WARN] Provenance file '{path}' has no jenkins_library.ref. "
300+
"Falling back to v3."
301+
)
302+
return None
303+
304+
# Every entry has to satisfy the backend's per-entry v4 keys, not just the
305+
# array as a whole: one defective entry rejects the whole message, and the
306+
# point of degrading to v3 is to not emit a message the backend will reject.
307+
for i, entry in enumerate(submodules):
308+
defect = _submodule_defect(entry)
309+
if defect:
310+
print(
311+
f"[WARN] Provenance file '{path}': submodules[{i}] {defect}. "
312+
"Falling back to v3."
313+
)
314+
return None
315+
316+
return {"jenkins_library": library, "submodules": submodules}
317+
318+
319+
def resolve_job_name(args):
320+
"""Canonical job name, or None when absent/blank."""
321+
return args.jobName.strip() if args.jobName else None
322+
323+
324+
def resolve_schema_version(args, provenance):
325+
"""The schema version this run's payload satisfies.
326+
327+
v4 needs both a job name and provenance; the backend requires every v4 key,
328+
so a run that could not capture its submodules must stay on v3 rather than
329+
emit a v4 message the backend will reject.
330+
"""
331+
if not resolve_job_name(args):
332+
return 2
333+
return 4 if provenance else 3
334+
335+
336+
def build_pipeline_payload(design_records, args, provenance=None):
233337
"""Return the pipeline-level payload dict.
234338
235-
Emits schema v3 (v2 structure plus a top-level ``job_name``) when
236-
``--jobName`` is supplied; otherwise falls back to v2. The backend
237-
requires a non-blank ``job_name`` for v3, so an empty job name keeps
238-
the message on v2 and the legacy BUILD_TAG classifier.
339+
Emits schema v2 (no job name), v3 (job name) or v4 (job name plus build
340+
provenance) — see :func:`resolve_schema_version`.
239341
"""
240-
job_name = args.jobName.strip() if args.jobName else None
342+
job_name = resolve_job_name(args)
343+
schema_version = resolve_schema_version(args, provenance)
241344
payload = {
242-
"payload_schema_version": 3 if job_name else 2,
345+
"payload_schema_version": schema_version,
243346
"jenkins_env": args.jenkinsEnv,
244347
"build_id": args.buildID,
245348
"branch_name": args.branchName,
@@ -251,14 +354,21 @@ def build_pipeline_payload(design_records, args):
251354
}
252355
if job_name:
253356
payload["job_name"] = job_name
357+
# Only a v4 payload carries provenance. Provenance without a job name cannot
358+
# be v4 (the backend requires job_name from v3 up), and attaching v4 keys to
359+
# a message labelled v2 would make payload_schema_version stop describing
360+
# the payload.
361+
if schema_version == 4:
362+
payload.update(provenance)
254363
return payload
255364

256365

257-
def publish_pipeline_report(publisher, topic_path, message_data, design_count, args):
258-
"""Publish a pre-encoded pipeline message (v3 when --jobName is set, else v2)."""
366+
def publish_pipeline_report(
367+
publisher, topic_path, message_data, design_count, args, provenance=None
368+
):
369+
"""Publish a pre-encoded pipeline message (v2, v3 or v4)."""
259370
size_kb = len(message_data) / 1024
260-
job_name = args.jobName.strip() if args.jobName else None
261-
schema_version = "3" if job_name else "2"
371+
schema_version = str(resolve_schema_version(args, provenance))
262372
print(
263373
f"[INFO] Publishing v{schema_version} pipeline report "
264374
f"({design_count} designs, {size_kb:.1f} KB) to Pub/Sub."
@@ -273,12 +383,22 @@ def publish_pipeline_report(publisher, topic_path, message_data, design_count, a
273383
print(f"[INFO] Published pipeline report to Pub/Sub (message ID: {message_id}).")
274384

275385

276-
def publish_v1_per_design(publisher, topic_path, design_records, args):
386+
def publish_v1_per_design(publisher, topic_path, design_records, args, provenance=None):
277387
"""Fallback path used when the v2 pipeline payload exceeds MAX_PUBSUB_BYTES.
278388
279389
Emits one v1-format message per design (no payload_schema_version, metrics
280390
flattened at the root), matching the legacy schema the ingestion service
281391
still supports.
392+
393+
Provenance is mirrored onto every message: all of them resolve to the same
394+
build, and the backend upserts components by path, so N copies converge on
395+
one set of rows. Omitting it here would make an oversized nightly look like
396+
a build with no overrides.
397+
398+
Unlike the pipeline payload this is not gated on the v4 job-name
399+
requirement: a v1 message declares no schema version, so there is nothing
400+
for the extra keys to contradict, and the backend reads provenance here by
401+
key presence rather than by version.
282402
"""
283403
futures = []
284404
for d in design_records:
@@ -292,6 +412,8 @@ def publish_v1_per_design(publisher, topic_path, design_records, args):
292412
"jenkins_env": args.jenkinsEnv,
293413
"rules": d["rules"],
294414
}
415+
if provenance:
416+
payload.update(provenance)
295417
payload.update(d["metrics"])
296418

297419
message_data = json.dumps(payload, default=str).encode("utf-8")
@@ -402,20 +524,26 @@ def get_rules(dataFile):
402524

403525
# --- PUBSUB ---
404526
if publisher and design_records:
405-
payload = build_pipeline_payload(design_records, args)
527+
provenance = load_provenance(args.provenanceFile)
528+
payload = build_pipeline_payload(design_records, args, provenance)
406529
message_data = json.dumps(payload, default=str).encode("utf-8")
407530

408531
if len(message_data) > MAX_PUBSUB_BYTES:
409532
print(
410-
f"[WARN] v2 payload size {len(message_data) / 1024:.1f} KB exceeds "
533+
f"[WARN] Payload size {len(message_data) / 1024:.1f} KB exceeds "
411534
f"{MAX_PUBSUB_BYTES // 1024} KB cap. Falling back to v1 per-design publish "
412535
f"({len(design_records)} messages)."
413536
)
414-
publish_v1_per_design(publisher, topic_path, design_records, args)
537+
publish_v1_per_design(publisher, topic_path, design_records, args, provenance)
415538
else:
416539
try:
417540
publish_pipeline_report(
418-
publisher, topic_path, message_data, len(design_records), args
541+
publisher,
542+
topic_path,
543+
message_data,
544+
len(design_records),
545+
args,
546+
provenance,
419547
)
420548
except Exception as e:
421549
print(f"[WARN] Pub/Sub publish failed for pipeline report: {e}")

0 commit comments

Comments
 (0)