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/
2226os .chdir (os .path .join (os .path .dirname (os .path .abspath (__file__ )), ".." ))
2327
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 ---
5065parser .add_argument (
@@ -229,17 +244,114 @@ 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+ # json.load accepts any top-level JSON value: a file holding a list or a
293+ # bare scalar parses fine, then .get() below raises AttributeError.
294+ if not isinstance (data , dict ):
295+ print (
296+ f"[WARN] Provenance file '{ path } ' does not contain a JSON object. "
297+ "Falling back to v3."
298+ )
299+ return None
300+
301+ submodules = data .get ("submodules" )
302+ library = data .get ("jenkins_library" )
303+ if not isinstance (submodules , list ) or not submodules :
304+ print (f"[WARN] Provenance file '{ path } ' has no submodules. Falling back to v3." )
305+ return None
306+ if not isinstance (library , dict ) or not library .get ("ref" ):
307+ print (
308+ f"[WARN] Provenance file '{ path } ' has no jenkins_library.ref. "
309+ "Falling back to v3."
310+ )
311+ return None
312+
313+ # Every entry has to satisfy the backend's per-entry v4 keys, not just the
314+ # array as a whole: one defective entry rejects the whole message, and the
315+ # point of degrading to v3 is to not emit a message the backend will reject.
316+ for i , entry in enumerate (submodules ):
317+ defect = _submodule_defect (entry )
318+ if defect :
319+ print (
320+ f"[WARN] Provenance file '{ path } ': submodules[{ i } ] { defect } . "
321+ "Falling back to v3."
322+ )
323+ return None
324+
325+ return {"jenkins_library" : library , "submodules" : submodules }
326+
327+
328+ def resolve_job_name (args ):
329+ """Canonical job name, or None when absent/blank."""
330+ return args .jobName .strip () if args .jobName else None
331+
332+
333+ def resolve_schema_version (args , provenance ):
334+ """The schema version this run's payload satisfies.
335+
336+ v4 needs both a job name and provenance; the backend requires every v4 key,
337+ so a run that could not capture its submodules must stay on v3 rather than
338+ emit a v4 message the backend will reject.
339+ """
340+ if not resolve_job_name (args ):
341+ return 2
342+ return 4 if provenance else 3
343+
344+
345+ def build_pipeline_payload (design_records , args , provenance = None ):
233346 """Return the pipeline-level payload dict.
234347
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.
348+ Emits schema v2 (no job name), v3 (job name) or v4 (job name plus build
349+ provenance) — see :func:`resolve_schema_version`.
239350 """
240- job_name = args .jobName .strip () if args .jobName else None
351+ job_name = resolve_job_name (args )
352+ schema_version = resolve_schema_version (args , provenance )
241353 payload = {
242- "payload_schema_version" : 3 if job_name else 2 ,
354+ "payload_schema_version" : schema_version ,
243355 "jenkins_env" : args .jenkinsEnv ,
244356 "build_id" : args .buildID ,
245357 "branch_name" : args .branchName ,
@@ -251,14 +363,21 @@ def build_pipeline_payload(design_records, args):
251363 }
252364 if job_name :
253365 payload ["job_name" ] = job_name
366+ # Only a v4 payload carries provenance. Provenance without a job name cannot
367+ # be v4 (the backend requires job_name from v3 up), and attaching v4 keys to
368+ # a message labelled v2 would make payload_schema_version stop describing
369+ # the payload.
370+ if schema_version == 4 :
371+ payload .update (provenance )
254372 return payload
255373
256374
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)."""
375+ def publish_pipeline_report (
376+ publisher , topic_path , message_data , design_count , args , provenance = None
377+ ):
378+ """Publish a pre-encoded pipeline message (v2, v3 or v4)."""
259379 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"
380+ schema_version = str (resolve_schema_version (args , provenance ))
262381 print (
263382 f"[INFO] Publishing v{ schema_version } pipeline report "
264383 f"({ design_count } designs, { size_kb :.1f} KB) to Pub/Sub."
@@ -273,12 +392,22 @@ def publish_pipeline_report(publisher, topic_path, message_data, design_count, a
273392 print (f"[INFO] Published pipeline report to Pub/Sub (message ID: { message_id } )." )
274393
275394
276- def publish_v1_per_design (publisher , topic_path , design_records , args ):
395+ def publish_v1_per_design (publisher , topic_path , design_records , args , provenance = None ):
277396 """Fallback path used when the v2 pipeline payload exceeds MAX_PUBSUB_BYTES.
278397
279398 Emits one v1-format message per design (no payload_schema_version, metrics
280399 flattened at the root), matching the legacy schema the ingestion service
281400 still supports.
401+
402+ Provenance is mirrored onto every message: all of them resolve to the same
403+ build, and the backend upserts components by path, so N copies converge on
404+ one set of rows. Omitting it here would make an oversized nightly look like
405+ a build with no overrides.
406+
407+ Unlike the pipeline payload this is not gated on the v4 job-name
408+ requirement: a v1 message declares no schema version, so there is nothing
409+ for the extra keys to contradict, and the backend reads provenance here by
410+ key presence rather than by version.
282411 """
283412 futures = []
284413 for d in design_records :
@@ -292,6 +421,8 @@ def publish_v1_per_design(publisher, topic_path, design_records, args):
292421 "jenkins_env" : args .jenkinsEnv ,
293422 "rules" : d ["rules" ],
294423 }
424+ if provenance :
425+ payload .update (provenance )
295426 payload .update (d ["metrics" ])
296427
297428 message_data = json .dumps (payload , default = str ).encode ("utf-8" )
@@ -402,20 +533,26 @@ def get_rules(dataFile):
402533
403534# --- PUBSUB ---
404535if publisher and design_records :
405- payload = build_pipeline_payload (design_records , args )
536+ provenance = load_provenance (args .provenanceFile )
537+ payload = build_pipeline_payload (design_records , args , provenance )
406538 message_data = json .dumps (payload , default = str ).encode ("utf-8" )
407539
408540 if len (message_data ) > MAX_PUBSUB_BYTES :
409541 print (
410- f"[WARN] v2 payload size { len (message_data ) / 1024 :.1f} KB exceeds "
542+ f"[WARN] Payload size { len (message_data ) / 1024 :.1f} KB exceeds "
411543 f"{ MAX_PUBSUB_BYTES // 1024 } KB cap. Falling back to v1 per-design publish "
412544 f"({ len (design_records )} messages)."
413545 )
414- publish_v1_per_design (publisher , topic_path , design_records , args )
546+ publish_v1_per_design (publisher , topic_path , design_records , args , provenance )
415547 else :
416548 try :
417549 publish_pipeline_report (
418- publisher , topic_path , message_data , len (design_records ), args
550+ publisher ,
551+ topic_path ,
552+ message_data ,
553+ len (design_records ),
554+ args ,
555+ provenance ,
419556 )
420557 except Exception as e :
421558 print (f"[WARN] Pub/Sub publish failed for pipeline report: { e } " )
0 commit comments