|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""ITK Compatibility Metrics Processor. |
| 3 | +
|
| 4 | +Compiles test outcomes from raw JSON results, retrieves and aggregates historical |
| 5 | +runs from GitHub Release assets, and outputs the updated historical metrics log. |
| 6 | +""" |
| 7 | + |
| 8 | +import datetime |
| 9 | +import json |
| 10 | +import logging |
| 11 | +import os |
| 12 | +import pathlib |
| 13 | +import sys |
| 14 | +import urllib.error |
| 15 | +import urllib.request |
| 16 | + |
| 17 | + |
| 18 | +# --- CONSTANTS --- |
| 19 | +RESULTS_FILE = 'raw_results.json' |
| 20 | +HISTORY_OUTPUT_FILE = 'itk_python.json' |
| 21 | +HISTORY_URL = 'https://github.com/a2aproject/a2a-python/releases/download/nightly-metrics/itk_python.json' |
| 22 | +SCENARIOS_FILE = 'scenarios.json' |
| 23 | +DEFAULT_HISTORY_LIMIT = 50 |
| 24 | + |
| 25 | +HTTP_STATUS_OK = 200 |
| 26 | +HTTP_STATUS_NOT_FOUND = 404 |
| 27 | + |
| 28 | +# Configure logging to match standard ITK formatting |
| 29 | +logging.basicConfig( |
| 30 | + level=logging.INFO, |
| 31 | +) |
| 32 | +logger = logging.getLogger(__name__) |
| 33 | + |
| 34 | + |
| 35 | +def load_raw_results(filepath: str) -> dict: |
| 36 | + """Loads the raw compatibility results from raw_results.json.""" |
| 37 | + path = pathlib.Path(filepath) |
| 38 | + if not path.exists(): |
| 39 | + logger.error('Results file %s not found.', filepath) |
| 40 | + raise SystemExit(1) |
| 41 | + |
| 42 | + try: |
| 43 | + with path.open() as f: |
| 44 | + return json.load(f) |
| 45 | + except (OSError, json.JSONDecodeError): |
| 46 | + logger.exception('Error loading results JSON') |
| 47 | + raise SystemExit(1) from None |
| 48 | + |
| 49 | + |
| 50 | +def fetch_existing_history(url: str) -> list: |
| 51 | + """Fetches the existing compatibility history from the GitHub release asset. |
| 52 | +
|
| 53 | + If the asset does not exist (HTTP 404), a fresh empty history list is returned. |
| 54 | + For all other network or server errors, the script exits with a non-zero status |
| 55 | + to prevent overwriting and losing historical metrics. |
| 56 | + """ |
| 57 | + try: |
| 58 | + req = urllib.request.Request( # noqa: S310 |
| 59 | + url, headers={'User-Agent': 'Mozilla/5.0'} |
| 60 | + ) |
| 61 | + with urllib.request.urlopen(req, timeout=15) as response: # noqa: S310 |
| 62 | + if response.status == HTTP_STATUS_OK: |
| 63 | + history = json.loads(response.read().decode('utf-8')) |
| 64 | + logger.info( |
| 65 | + 'Successfully retrieved history. Current entries: %d', |
| 66 | + len(history), |
| 67 | + ) |
| 68 | + return history |
| 69 | + logger.error( |
| 70 | + 'Unexpected HTTP status when downloading existing history: %d', |
| 71 | + response.status, |
| 72 | + ) |
| 73 | + raise SystemExit(1) # noqa: TRY301 |
| 74 | + except urllib.error.HTTPError as e: |
| 75 | + if e.code == HTTP_STATUS_NOT_FOUND: |
| 76 | + logger.warning( |
| 77 | + 'No existing history found (HTTP %d). Initializing fresh history.', |
| 78 | + e.code, |
| 79 | + ) |
| 80 | + return [] |
| 81 | + logger.exception( |
| 82 | + 'HTTP error downloading existing history: %d. Aborting to preserve metrics.', |
| 83 | + e.code, |
| 84 | + ) |
| 85 | + raise SystemExit(1) from None |
| 86 | + except Exception: |
| 87 | + logger.exception( |
| 88 | + 'Failed to download existing history. Aborting to preserve metrics.' |
| 89 | + ) |
| 90 | + raise SystemExit(1) from None |
| 91 | + |
| 92 | + |
| 93 | +def load_scenarios(filepath: str) -> list: |
| 94 | + """Loads the list of tests from the scenarios.json definitions.""" |
| 95 | + path = pathlib.Path(filepath) |
| 96 | + if not path.exists(): |
| 97 | + logger.error('Scenarios file %s not found.', filepath) |
| 98 | + raise SystemExit(1) |
| 99 | + |
| 100 | + try: |
| 101 | + with path.open() as f: |
| 102 | + data = json.load(f) |
| 103 | + return data['tests'] |
| 104 | + except (OSError, json.JSONDecodeError, KeyError): |
| 105 | + logger.exception('Failed to load scenarios.json definitions') |
| 106 | + raise SystemExit(1) from None |
| 107 | + |
| 108 | + |
| 109 | +def save_history(filepath: str, history: list) -> None: |
| 110 | + """Saves the updated history back to disk as a release asset candidate.""" |
| 111 | + path = pathlib.Path(filepath) |
| 112 | + try: |
| 113 | + with path.open('w') as f: |
| 114 | + json.dump(history, f, indent=2) |
| 115 | + logger.info( |
| 116 | + 'Successfully compiled and wrote nightly history to: %s', |
| 117 | + filepath, |
| 118 | + ) |
| 119 | + except (OSError, TypeError): |
| 120 | + logger.exception('Error writing history file') |
| 121 | + sys.exit(1) |
| 122 | + |
| 123 | + |
| 124 | +def main() -> None: |
| 125 | + """Orchestrates nightly ITK metrics processing and compiles rolling history.""" |
| 126 | + # 1. Load raw compatibility results |
| 127 | + data = load_raw_results(RESULTS_FILE) |
| 128 | + all_passed = data.get('all_passed', False) |
| 129 | + results = data.get('results', {}) |
| 130 | + |
| 131 | + # 2. Fetch existing history from rolling release |
| 132 | + history = fetch_existing_history(HISTORY_URL) |
| 133 | + |
| 134 | + # 3. Load scenarios list for base metadata |
| 135 | + scenarios_file = 'scenarios_full.json' if os.environ.get('ITK_NIGHTLY_RUN') == 'True' else 'scenarios.json' |
| 136 | + base_scenarios = load_scenarios(scenarios_file) |
| 137 | + # Merge definitions with current outcomes dynamically |
| 138 | + compiled_scenarios = [] |
| 139 | + for name, details in results.items(): |
| 140 | + # Extract the parent scenario name cleanly by splitting on the subtest suffix |
| 141 | + parent_name = name.split('-sub-')[0] |
| 142 | + |
| 143 | + # Find the matching base scenario with an EXACT match! |
| 144 | + matched_base = None |
| 145 | + for base in base_scenarios: |
| 146 | + if parent_name == base['name']: |
| 147 | + matched_base = base |
| 148 | + break |
| 149 | + |
| 150 | + if not matched_base: |
| 151 | + logger.warning('No matching base scenario found for result key: %s', name) |
| 152 | + continue |
| 153 | + |
| 154 | + # Build the metadata-rich scenario record |
| 155 | + passed = False |
| 156 | + sdks = matched_base.get('sdks', []) |
| 157 | + edges = matched_base.get('edges') |
| 158 | + |
| 159 | + if isinstance(details, dict): |
| 160 | + passed = details.get('passed', False) |
| 161 | + sdks = details.get('sdks', sdks) |
| 162 | + edges = details.get('edges', edges) |
| 163 | + elif isinstance(details, bool): |
| 164 | + passed = details |
| 165 | + |
| 166 | + record = { |
| 167 | + 'name': name, |
| 168 | + 'sdks': sdks, |
| 169 | + 'edges': edges, |
| 170 | + 'protocols': matched_base.get('protocols'), |
| 171 | + 'behavior': matched_base.get('behavior'), |
| 172 | + 'traversal': matched_base.get('traversal', 'euler'), |
| 173 | + 'passed': passed, |
| 174 | + } |
| 175 | + if 'streaming' in matched_base: |
| 176 | + record['streaming'] = matched_base['streaming'] |
| 177 | + if 'build_subtests' in matched_base: |
| 178 | + record['build_subtests'] = matched_base['build_subtests'] |
| 179 | + |
| 180 | + compiled_scenarios.append(record) |
| 181 | + |
| 182 | + # 4. Compile new run metadata |
| 183 | + new_run = { |
| 184 | + 'timestamp': datetime.datetime.now(datetime.timezone.utc).isoformat(), |
| 185 | + 'commit_sha': os.environ.get('GITHUB_SHA', 'local-dev'), |
| 186 | + 'github_run_id': os.environ.get('GITHUB_RUN_ID', '0'), |
| 187 | + 'all_passed': all_passed, |
| 188 | + 'scenarios': compiled_scenarios, |
| 189 | + } |
| 190 | + |
| 191 | + # 5. Merge and Prune rolling window |
| 192 | + history.append(new_run) |
| 193 | + history_limit = int( |
| 194 | + os.environ.get('ITK_HISTORY_LIMIT', str(DEFAULT_HISTORY_LIMIT)) |
| 195 | + ) |
| 196 | + if len(history) > history_limit: |
| 197 | + history = history[-history_limit:] |
| 198 | + logger.info('Pruned history to last %d entries.', history_limit) |
| 199 | + |
| 200 | + # 6. Save candidates back to disk |
| 201 | + save_history(HISTORY_OUTPUT_FILE, history) |
| 202 | + sys.exit(0) |
| 203 | + |
| 204 | + |
| 205 | +if __name__ == '__main__': |
| 206 | + main() |
0 commit comments