|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# |
| 3 | +# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 4 | +# or more contributor license agreements. Licensed under the Elastic License |
| 5 | +# 2.0 and the following additional limitation. Functionality enabled by the |
| 6 | +# files subject to the Elastic License 2.0 may only be used in production when |
| 7 | +# invoked by an Elasticsearch process with a license key installed that permits |
| 8 | +# use of machine learning features. You may not use this file except in |
| 9 | +# compliance with the Elastic License 2.0 and the foregoing additional |
| 10 | +# limitation. |
| 11 | + |
| 12 | +""" |
| 13 | +Analyse build+test timings for the current snapshot build and compare |
| 14 | +against recent history. Produces a Buildkite annotation with a summary |
| 15 | +table and flags any regressions. |
| 16 | +""" |
| 17 | + |
| 18 | +import json |
| 19 | +import math |
| 20 | +import os |
| 21 | +import subprocess |
| 22 | +import sys |
| 23 | +import urllib.request |
| 24 | +import urllib.error |
| 25 | + |
| 26 | +PIPELINE_SLUG = "ml-cpp-snapshot-builds" |
| 27 | +ORG_SLUG = "elastic" |
| 28 | +API_BASE = f"https://api.buildkite.com/v2/organizations/{ORG_SLUG}/pipelines/{PIPELINE_SLUG}" |
| 29 | +HISTORY_COUNT = 14 |
| 30 | + |
| 31 | +PLATFORM_MAP = { |
| 32 | + "Windows": "windows_x86_64", |
| 33 | + "MacOS": "macos_aarch64", |
| 34 | + "linux-x86_64": "linux_x86_64", |
| 35 | + "linux-aarch64": "linux_aarch64", |
| 36 | +} |
| 37 | + |
| 38 | + |
| 39 | +def api_get(path, token): |
| 40 | + url = f"{API_BASE}{path}" |
| 41 | + req = urllib.request.Request(url, headers={"Authorization": f"Bearer {token}"}) |
| 42 | + try: |
| 43 | + with urllib.request.urlopen(req, timeout=30) as resp: |
| 44 | + return json.loads(resp.read()) |
| 45 | + except urllib.error.HTTPError as e: |
| 46 | + print(f"API error {e.code} for {url}: {e.read().decode()}", file=sys.stderr) |
| 47 | + sys.exit(1) |
| 48 | + |
| 49 | + |
| 50 | +def extract_timings(build_data): |
| 51 | + """Extract per-platform build+test timings from a build's jobs.""" |
| 52 | + timings = {} |
| 53 | + for job in build_data.get("jobs", []): |
| 54 | + name = job.get("name") or "" |
| 55 | + if "Build & test" not in name: |
| 56 | + continue |
| 57 | + if "debug" in name.lower(): |
| 58 | + continue |
| 59 | + started = job.get("started_at") |
| 60 | + finished = job.get("finished_at") |
| 61 | + if not started or not finished: |
| 62 | + continue |
| 63 | + |
| 64 | + for pattern, key in PLATFORM_MAP.items(): |
| 65 | + if pattern in name: |
| 66 | + from datetime import datetime, timezone |
| 67 | + fmt = "%Y-%m-%dT%H:%M:%S.%fZ" |
| 68 | + t_start = datetime.strptime(started, fmt).replace(tzinfo=timezone.utc) |
| 69 | + t_end = datetime.strptime(finished, fmt).replace(tzinfo=timezone.utc) |
| 70 | + mins = (t_end - t_start).total_seconds() / 60.0 |
| 71 | + timings[key] = round(mins, 1) |
| 72 | + break |
| 73 | + return timings |
| 74 | + |
| 75 | + |
| 76 | +def mean_stddev(values): |
| 77 | + if not values: |
| 78 | + return 0.0, 0.0 |
| 79 | + n = len(values) |
| 80 | + m = sum(values) / n |
| 81 | + if n < 2: |
| 82 | + return m, 0.0 |
| 83 | + variance = sum((x - m) ** 2 for x in values) / (n - 1) |
| 84 | + return m, math.sqrt(variance) |
| 85 | + |
| 86 | + |
| 87 | +def annotate(markdown, style="info"): |
| 88 | + """Create a Buildkite annotation.""" |
| 89 | + cmd = ["buildkite-agent", "annotate", "--style", style, "--context", "build-timings"] |
| 90 | + proc = subprocess.run(cmd, input=markdown.encode(), capture_output=True) |
| 91 | + if proc.returncode != 0: |
| 92 | + print(f"buildkite-agent annotate failed: {proc.stderr.decode()}", file=sys.stderr) |
| 93 | + |
| 94 | + |
| 95 | +def main(): |
| 96 | + token = os.environ.get("BUILDKITE_API_READ_TOKEN", "") |
| 97 | + if not token: |
| 98 | + print("BUILDKITE_API_READ_TOKEN not set, skipping timing analysis", file=sys.stderr) |
| 99 | + sys.exit(0) |
| 100 | + |
| 101 | + build_number = os.environ.get("BUILDKITE_BUILD_NUMBER", "") |
| 102 | + branch = os.environ.get("BUILDKITE_BRANCH", "main") |
| 103 | + |
| 104 | + # Fetch current build |
| 105 | + current = api_get(f"/builds/{build_number}", token) |
| 106 | + current_timings = extract_timings(current) |
| 107 | + current_date = current.get("created_at", "")[:10] |
| 108 | + |
| 109 | + if not current_timings: |
| 110 | + print("No build+test timings found for current build") |
| 111 | + sys.exit(0) |
| 112 | + |
| 113 | + # Fetch historical builds for the same branch |
| 114 | + history_data = api_get( |
| 115 | + f"/builds?branch={branch}&state=passed&per_page={HISTORY_COUNT + 1}", token |
| 116 | + ) |
| 117 | + |
| 118 | + # Exclude the current build from history |
| 119 | + history_builds = [ |
| 120 | + b for b in history_data if str(b.get("number")) != str(build_number) |
| 121 | + ][:HISTORY_COUNT] |
| 122 | + |
| 123 | + # Collect historical timings per platform |
| 124 | + history = {key: [] for key in PLATFORM_MAP.values()} |
| 125 | + for build in history_builds: |
| 126 | + full_build = api_get(f"/builds/{build['number']}", token) |
| 127 | + timings = extract_timings(full_build) |
| 128 | + for key, val in timings.items(): |
| 129 | + history[key].append(val) |
| 130 | + |
| 131 | + # Build the summary table |
| 132 | + platforms = ["linux_x86_64", "linux_aarch64", "macos_aarch64", "windows_x86_64"] |
| 133 | + platform_labels = { |
| 134 | + "linux_x86_64": "Linux x86_64", |
| 135 | + "linux_aarch64": "Linux aarch64", |
| 136 | + "macos_aarch64": "macOS aarch64", |
| 137 | + "windows_x86_64": "Windows x86_64", |
| 138 | + } |
| 139 | + |
| 140 | + lines = [] |
| 141 | + lines.append(f"### Build Timing Analysis — {current_date} (build #{build_number})") |
| 142 | + lines.append("") |
| 143 | + lines.append("| Platform | Current (min) | Avg (min) | Std Dev | Delta | Status |") |
| 144 | + lines.append("|----------|:------------:|:---------:|:-------:|:-----:|:------:|") |
| 145 | + |
| 146 | + has_regression = False |
| 147 | + for plat in platforms: |
| 148 | + cur = current_timings.get(plat) |
| 149 | + hist = history.get(plat, []) |
| 150 | + avg, sd = mean_stddev(hist) |
| 151 | + |
| 152 | + if cur is None: |
| 153 | + lines.append(f"| {platform_labels[plat]} | — | {avg:.1f} | {sd:.1f} | — | — |") |
| 154 | + continue |
| 155 | + |
| 156 | + delta = cur - avg |
| 157 | + delta_pct = (delta / avg * 100) if avg > 0 else 0 |
| 158 | + sign = "+" if delta >= 0 else "" |
| 159 | + |
| 160 | + if avg > 0 and sd > 0 and cur > avg + 2 * sd: |
| 161 | + status = ":rotating_light: Regression" |
| 162 | + has_regression = True |
| 163 | + elif avg > 0 and cur < avg - sd: |
| 164 | + status = ":rocket: Faster" |
| 165 | + else: |
| 166 | + status = ":white_check_mark: Normal" |
| 167 | + |
| 168 | + lines.append( |
| 169 | + f"| {platform_labels[plat]} | **{cur:.1f}** | {avg:.1f} | {sd:.1f} " |
| 170 | + f"| {sign}{delta:.1f} ({sign}{delta_pct:.0f}%) | {status} |" |
| 171 | + ) |
| 172 | + |
| 173 | + n_hist = len(history_builds) |
| 174 | + lines.append("") |
| 175 | + lines.append(f"_Compared against {n_hist} recent `{branch}` builds._") |
| 176 | + |
| 177 | + markdown = "\n".join(lines) |
| 178 | + print(markdown) |
| 179 | + |
| 180 | + style = "warning" if has_regression else "info" |
| 181 | + annotate(markdown, style) |
| 182 | + |
| 183 | + |
| 184 | +if __name__ == "__main__": |
| 185 | + main() |
0 commit comments