Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
169 changes: 153 additions & 16 deletions flow/util/uploadMetadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@

# --- 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__)), ".."))

Expand Down Expand Up @@ -45,6 +49,17 @@
"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.",
)

# --- PUBSUB args ---
parser.add_argument(
Expand Down Expand Up @@ -229,17 +244,114 @@ def build_design_record(dataFile, platform, design, variant, rules):
}


def build_pipeline_payload(design_records, args):
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")
Comment thread
migueldalberto marked this conversation as resolved.
Resolved
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 build_pipeline_payload(design_records, args, provenance=None):
"""Return the pipeline-level payload dict.

Emits schema v3 (v2 structure plus a top-level ``job_name``) when
``--jobName`` is supplied; otherwise falls back to v2. The backend
requires a non-blank ``job_name`` for v3, so an empty job name keeps
the message on v2 and the legacy BUILD_TAG classifier.
Emits schema v2 (no job name), v3 (job name) or v4 (job name plus build
provenance) — see :func:`resolve_schema_version`.
"""
job_name = args.jobName.strip() if args.jobName else None
job_name = resolve_job_name(args)
schema_version = resolve_schema_version(args, provenance)
payload = {
"payload_schema_version": 3 if job_name else 2,
"payload_schema_version": schema_version,
"jenkins_env": args.jenkinsEnv,
"build_id": args.buildID,
"branch_name": args.branchName,
Expand All @@ -251,14 +363,21 @@ def build_pipeline_payload(design_records, args):
}
if job_name:
payload["job_name"] = job_name
# 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)
return payload


def publish_pipeline_report(publisher, topic_path, message_data, design_count, args):
"""Publish a pre-encoded pipeline message (v3 when --jobName is set, else v2)."""
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
job_name = args.jobName.strip() if args.jobName else None
schema_version = "3" if job_name else "2"
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."
Expand All @@ -273,12 +392,22 @@ def publish_pipeline_report(publisher, topic_path, message_data, design_count, a
print(f"[INFO] Published pipeline report to Pub/Sub (message ID: {message_id}).")


def publish_v1_per_design(publisher, topic_path, design_records, args):
def publish_v1_per_design(publisher, topic_path, design_records, args, provenance=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.

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.
"""
futures = []
for d in design_records:
Expand All @@ -292,6 +421,8 @@ def publish_v1_per_design(publisher, topic_path, design_records, args):
"jenkins_env": args.jenkinsEnv,
"rules": d["rules"],
}
if provenance:
payload.update(provenance)
payload.update(d["metrics"])

message_data = json.dumps(payload, default=str).encode("utf-8")
Expand Down Expand Up @@ -402,20 +533,26 @@ def get_rules(dataFile):

# --- PUBSUB ---
if publisher and design_records:
payload = build_pipeline_payload(design_records, args)
provenance = load_provenance(args.provenanceFile)
payload = build_pipeline_payload(design_records, args, provenance)
message_data = json.dumps(payload, default=str).encode("utf-8")

if len(message_data) > MAX_PUBSUB_BYTES:
print(
f"[WARN] v2 payload size {len(message_data) / 1024:.1f} KB exceeds "
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)."
)
publish_v1_per_design(publisher, topic_path, design_records, args)
publish_v1_per_design(publisher, topic_path, design_records, args, provenance)
else:
try:
publish_pipeline_report(
publisher, topic_path, message_data, len(design_records), args
publisher,
topic_path,
message_data,
len(design_records),
args,
provenance,
)
except Exception as e:
print(f"[WARN] Pub/Sub publish failed for pipeline report: {e}")
Expand Down