Debian Codegraph @

testing/web-platform/interop.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5 import argparse
6 import csv
7 import math
8 import os
9 import re
10 import shutil
11 import sys
12 import tempfile
13 from datetime import datetime
14 from typing import Callable, Iterable, List, Mapping, Optional, Set, Tuple
15
16 repos = ["autoland", "mozilla-central", "try", "mozilla-central", "mozilla-beta", "wpt"]
17
18 default_fetch_task_filters = ["-web-platform-tests-|-spidermonkey-"]
19 default_interop_task_filters = {
20 "wpt": ["-firefox-"],
21 None: [
22 "web-platform-tests",
23 "linux.*-64",
24 "/opt",
25 "!-nofis|-headless|-asan|-tsan|-ccov|wayland",
26 ],
27 }
28
29
30 def get_parser_fetch_logs() -> argparse.Namespace:
31 parser = argparse.ArgumentParser()
32 parser.add_argument(
33 "--log-dir", action="store", help="Directory into which to download logs"
34 )
35 parser.add_argument(
36 "--task-filter",
37 dest="task_filters",
38 action="append",
39 help="Regex filter applied to task names. Filters starting ! must not match. Filters starting ^ (after any !) match the entire task name, otherwise any substring can match. Multiple filters must all match",
40 )
41 parser.add_argument(
42 "--check-complete",
43 action="store_true",
44 help="Only download logs if the task is complete",
45 )
46 parser.add_argument(
47 "commits",
48 nargs="+",
49 help="repo:commit e.g. mozilla-central:fae24810aef1 for the runs to include",
50 )
51 return parser
52
53
54 def get_default_year() -> int:
55 # Simple guess at current Interop year, based on switchover in Feburary
56 now = datetime.now()
57 year = now.year
58 if now.month < 2:
59 year -= 1
60 return year
61
62
63 def get_parser_interop_score() -> argparse.Namespace:
64 parser = get_parser_fetch_logs()
65 parser.add_argument(
66 "--year",
67 action="store",
68 default=get_default_year(),
69 type=int,
70 help="Interop year to score against",
71 )
72 parser.add_argument(
73 "--category-filter",
74 action="append",
75 dest="category_filters",
76 help="Regex filter applied to category names. Filters starting ! must not match. Filters starting ^ (after any !) match the entire task name, otherwise any substring can match. Multiple filters must all match",
77 )
78 parser.add_argument(
79 "--expected-failures",
80 help="Path to a file containing a list of tests which are not expected to pass",
81 )
82 return parser
83
84
85 def print_scores(
86 runs: Iterable[Tuple[str, str]],
87 results_by_category: Mapping[str, List[int]],
88 expected_failures_by_category: Optional[Mapping[str, List[Tuple[int, int]]]],
89 include_total: bool,
90 ):
91 include_expected_failures = expected_failures_by_category is not None
92
93 writer = csv.writer(sys.stdout, delimiter="\t")
94
95 headers = ["Category"]
96 for repo, commit in runs:
97 prefix = f"{repo}:{commit}"
98 headers.append(f"{prefix}-score")
99 if include_expected_failures:
100 headers.append(f"{prefix}-expected-failures")
101 headers.append(f"{prefix}-adjusted-score")
102
103 writer.writerow(headers)
104
105 totals = {"score": [0.0] * len(runs)}
106 if include_expected_failures:
107 totals["expected_failures"] = [0.0] * len(runs)
108 totals["adjusted_score"] = [0.0] * len(runs)
109
110 for category, category_results in results_by_category.items():
111 category_row = []
112 category_row.append(category)
113 for category_index, result in enumerate(category_results):
114 for run_index, run_score in enumerate(category_results):
115 category_row.append(f"{run_score / 10:.1f}")
116 totals["score"][run_index] += run_score
117 if include_expected_failures:
118 expected_failures, adjusted_score = expected_failures_by_category[
119 category
120 ][run_index]
121 category_row.append(f"{expected_failures / 10:.1f}")
122 category_row.append(f"{adjusted_score / 10:.1f}")
123 totals["expected_failures"][run_index] += expected_failures
124 totals["adjusted_score"][run_index] += adjusted_score
125 writer.writerow(category_row)
126
127 if include_total:
128
129 def get_total(score, floor=True):
130 total = float(score) / (len(results_by_category))
131 if floor:
132 total = math.floor(total)
133 total /= 10.0
134 return total
135
136 totals_row = ["Total"]
137 for i in range(len(runs)):
138 totals_row.append(f"{get_total(totals['score'][i]):.1f}")
139 if include_expected_failures:
140 totals_row.append(
141 f"{get_total(totals['expected_failures'][i], floor=False):.1f}"
142 )
143 totals_row.append(f"{get_total(totals['adjusted_score'][i]):.1f}")
144 writer.writerow(totals_row)
145
146
147 def get_wptreports(
148 repo: str, commit: str, task_filters: List[str], log_dir: str, check_complete: bool
149 ) -> List[str]:
150 import tcfetch
151
152 return tcfetch.download_artifacts(
153 repo,
154 commit,
155 task_filters=task_filters,
156 check_complete=check_complete,
157 out_dir=log_dir,
158 )
159
160
161 def get_runs(commits: List[str]) -> List[Tuple[str, str]]:
162 runs = []
163 for item in commits:
164 if ":" not in item:
165 raise ValueError(f"Expected commits of the form repo:commit, got {item}")
166 repo, commit = item.split(":", 1)
167 if repo not in repos:
168 raise ValueError(f"Unsupported repo {repo}")
169 runs.append((repo, commit))
170 return runs
171
172
173 def get_category_filter(
174 category_filters: Optional[List[str]],
175 ) -> Optional[Callable[[str], bool]]:
176 if category_filters is None:
177 return None
178
179 filters = []
180 for item in category_filters:
181 if not item:
182 continue
183 invert = item[0] == "!"
184 if invert:
185 item = item[1:]
186 if item[0] == "^":
187 regex = re.compile(item)
188 else:
189 regex = re.compile(f"^(.*)(?:{item})")
190 filters.append((regex, invert))
191
192 def match_filters(category):
193 for regex, invert in filters:
194 matches = regex.match(category) is not None
195 if invert:
196 matches = not matches
197 if not matches:
198 return False
199 return True
200
201 return match_filters
202
203
204 def fetch_logs(
205 commits: List[str],
206 task_filters: List[str],
207 log_dir: Optional[str],
208 check_complete: bool,
209 **kwargs,
210 ):
211 runs = get_runs(commits)
212
213 if not task_filters:
214 task_filters = default_fetch_task_filters
215
216 if log_dir is None:
217 log_dir = os.path.abspath(os.curdir)
218
219 for repo, commit in runs:
220 get_wptreports(repo, commit, task_filters, log_dir, check_complete)
221
222
223 def get_expected_failures(path: str) -> Mapping[str, Set[Optional[str]]]:
224 expected_failures = {}
225 with open(path) as f:
226 for i, entry in enumerate(csv.reader(f)):
227 entry = [item.strip() for item in entry]
228 if not any(item for item in entry) or entry[0][0] == "#":
229 continue
230 if len(entry) > 2:
231 raise ValueError(
232 f"{path}:{i+1} expected at most two columns, got {len(entry)}"
233 )
234 if entry[0][0] != "/":
235 raise ValueError(
236 f'{path}:{i+1} "{entry[0]}" is not a valid test id (must start with "/")'
237 )
238 test_id = entry[0]
239 if test_id not in expected_failures:
240 expected_failures[test_id] = set()
241 if len(entry) == 2:
242 subtest_id = entry[1]
243 if subtest_id == "":
244 print(
245 f"Warning: {path}:{i+1} got empty string subtest id, remove the trailing comma to make this apply to the full test"
246 )
247 expected_failures[test_id].add(subtest_id)
248 else:
249 expected_failures[test_id].add(None)
250 return expected_failures
251
252
253 def score_runs(
254 commits: List[str],
255 task_filters: List[str],
256 log_dir: Optional[str],
257 year: int,
258 check_complete: bool,
259 category_filters: Optional[List[str]],
260 expected_failures: Optional[str],
261 **kwargs,
262 ):
263 from wpt_interop import score
264
265 runs = get_runs(commits)
266
267 temp_dir = None
268 if log_dir is None:
269 temp_dir = tempfile.mkdtemp()
270 log_dir = temp_dir
271
272 try:
273 if expected_failures is not None:
274 expected_failures_data = get_expected_failures(expected_failures)
275 else:
276 expected_failures_data = None
277
278 run_logs = []
279 for repo, commit in runs:
280 if not task_filters:
281 if repo in default_interop_task_filters:
282 filters = default_interop_task_filters[repo]
283 else:
284 filters = default_interop_task_filters[None]
285 else:
286 filters = task_filters
287
288 log_paths = get_wptreports(repo, commit, filters, log_dir, check_complete)
289 if not log_paths:
290 print(f"Failed to get any logs for {repo}:{commit}", file=sys.stderr)
291 else:
292 run_logs.append(log_paths)
293
294 if not run_logs:
295 print("No logs to process", file=sys.stderr)
296
297 include_total = category_filters is None
298
299 category_filter = (
300 get_category_filter(category_filters) if category_filters else None
301 )
302
303 scores, expected_failure_scores = score.score_wptreports(
304 run_logs,
305 year=year,
306 category_filter=category_filter,
307 expected_failures=expected_failures_data,
308 )
309 print_scores(runs, scores, expected_failure_scores, include_total)
310 finally:
311 if temp_dir is not None:
312 shutil.rmtree(temp_dir, True)