Debian Codegraph @

testing/skipfails.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 gzip
6 import json
7 import logging
8 import os
9 import os.path
10 import pprint
11 import re
12 import sys
13 import tempfile
14 import urllib.parse
15 from copy import deepcopy
16 from pathlib import Path
17 from statistics import median
18 from typing import Any, Dict, List, Literal, Tuple
19 from xmlrpc.client import Fault
20
21 from failedplatform import FailedPlatform
22 from mozinfo.platforminfo import PlatformInfo
23 from yaml import load
24
25 try:
26 from yaml import CLoader as Loader
27 except ImportError:
28 from yaml import Loader
29
30 import bugzilla
31 import mozci.push
32 import requests
33 from manifestparser import ManifestParser
34 from manifestparser.toml import add_skip_if, alphabetize_toml_str, sort_paths
35 from mozci.task import Optional, TestTask
36 from mozci.util.taskcluster import get_task
37
38 from taskcluster.exceptions import TaskclusterRestFailure
39
40 TASK_LOG = "live_backing.log"
41 TASK_ARTIFACT = "public/logs/" + TASK_LOG
42 ATTACHMENT_DESCRIPTION = "Compressed " + TASK_ARTIFACT + " for task "
43 ATTACHMENT_REGEX = (
44 r".*Created attachment ([0-9]+)\n.*"
45 + ATTACHMENT_DESCRIPTION
46 + "([A-Za-z0-9_-]+)\n.*"
47 )
48
49 BUGZILLA_AUTHENTICATION_HELP = "Must create a Bugzilla API key per https://github.com/mozilla/mozci-tools/blob/main/citools/test_triage_bug_filer.py"
50
51 MS_PER_MINUTE = 60 * 1000 # ms per minute
52 DEBUG_THRESHOLD = 40 * MS_PER_MINUTE # 40 minutes in ms
53 OPT_THRESHOLD = 20 * MS_PER_MINUTE # 20 minutes in ms
54
55 ANYJS = "anyjs"
56 CC = "classification"
57 DEF = "DEFAULT"
58 DIFFERENCE = "difference"
59 DURATIONS = "durations"
60 EQEQ = "=="
61 ERROR = "error"
62 FAIL = "FAIL"
63 FAILED_RUNS = "runs_failed"
64 FAILURE_RATIO = 0.4 # more than this fraction of failures will disable
65 INTERMITTENT_RATIO_REFTEST = 0.4 # reftest low frequency intermittent
66 FAILURE_RATIO_REFTEST = 0.8 # disable ratio for reftest (high freq intermittent)
67 GROUP = "group"
68 KIND = "kind"
69 LINENO = "lineno"
70 LL = "label"
71 MEDIAN_DURATION = "duration_median"
72 MINIMUM_RUNS = 3 # mininum number of runs to consider success/failure
73 MOCK_BUG_DEFAULTS = {"blocks": [], "comments": []}
74 MOCK_TASK_DEFAULTS = {"extra": {}, "failure_types": {}, "results": []}
75 MOCK_TASK_INITS = ["results"]
76 MODIFIERS = "modifiers"
77 NOTEQ = "!="
78 OPT = "opt"
79 PASS = "PASS"
80 PIXELS = "pixels"
81 PP = "path"
82 QUERY = "query"
83 RR = "result"
84 RUNS = "runs"
85 STATUS = "status"
86 SUBTEST = "subtest"
87 SUBTEST_REGEX = (
88 r"image comparison, max difference: ([0-9]+), number of differing pixels: ([0-9]+)"
89 )
90 SUM_BY_LABEL = "sum_by_label"
91 TEST = "test"
92 TEST_TYPES = [EQEQ, NOTEQ]
93 TOTAL_DURATION = "duration_total"
94 TOTAL_RUNS = "runs_total"
95 WP = "testing/web-platform/"
96 WPT0 = WP + "tests/infrastructure"
97 WPT_META0 = WP + "tests/infrastructure/metadata"
98 WPT_META0_CLASSIC = WP + "meta/infrastructure"
99 WPT1 = WP + "tests"
100 WPT_META1 = WPT1.replace("tests", "meta")
101 WPT2 = WP + "mozilla/tests"
102 WPT_META2 = WPT2.replace("tests", "meta")
103 WPT_MOZILLA = "/_mozilla"
104
105
106 class Mock:
107 def __init__(self, data, defaults={}, inits=[]):
108 self._data = data
109 self._defaults = defaults
110 for name in inits:
111 values = self._data.get(name, []) # assume type is an array
112 values = [Mock(value, defaults, inits) for value in values]
113 self._data[name] = values
114
115 def __getattr__(self, name):
116 if name in self._data:
117 return self._data[name]
118 if name in self._defaults:
119 return self._defaults[name]
120 return ""
121
122
123 class Classification:
124 "Classification of the failure (not the task result)"
125
126 DISABLE_INTERMITTENT = "disable_intermittent" # reftest [40%, 80%)
127 DISABLE_FAILURE = "disable_failure" # reftest (80%,100%] failure
128 DISABLE_MANIFEST = "disable_manifest" # crash found
129 DISABLE_RECOMMENDED = "disable_recommended" # disable first failing path
130 DISABLE_TOO_LONG = "disable_too_long" # runtime threshold exceeded
131 INTERMITTENT = "intermittent"
132 SECONDARY = "secondary" # secondary failing path
133 SUCCESS = "success" # path always succeeds
134 UNKNOWN = "unknown"
135
136
137 class Kind:
138 "Kind of manifest"
139
140 LIST = "list"
141 TOML = "toml"
142 UNKNOWN = "unknown"
143 WPT = "wpt"
144
145
146 class Skipfails:
147 "mach manifest skip-fails implementation: Update manifests to skip failing tests"
148
149 REPO = "repo"
150 REVISION = "revision"
151 TREEHERDER = "treeherder.mozilla.org"
152 BUGZILLA_SERVER_DEFAULT = "bugzilla.allizom.org"
153
154 def __init__(
155 self,
156 command_context=None,
157 try_url="",
158 verbose=True,
159 bugzilla=None,
160 dry_run=False,
161 turbo=False,
162 implicit_vars=False,
163 new_version=None,
164 ):
165 self.command_context = command_context
166 if self.command_context is not None:
167 self.topsrcdir = self.command_context.topsrcdir
168 else:
169 self.topsrcdir = Path(__file__).parent.parent
170 self.topsrcdir = os.path.normpath(self.topsrcdir)
171 if isinstance(try_url, list) and len(try_url) == 1:
172 self.try_url = try_url[0]
173 else:
174 self.try_url = try_url
175 self.dry_run = dry_run
176 self.implicit_vars = implicit_vars
177 self.new_version = new_version
178 self.verbose = verbose
179 self.turbo = turbo
180 if bugzilla is not None:
181 self.bugzilla = bugzilla
182 elif "BUGZILLA" in os.environ:
183 self.bugzilla = os.environ["BUGZILLA"]
184 else:
185 self.bugzilla = Skipfails.BUGZILLA_SERVER_DEFAULT
186 if self.bugzilla == "disable":
187 self.bugzilla = None # Bug filing disabled
188 self.component = "skip-fails"
189 self._bzapi = None
190 self._attach_rx = None
191 self.variants = {}
192 self.tasks = {}
193 self.pp = None
194 self.headers = {} # for Treeherder requests
195 self.headers["Accept"] = "application/json"
196 self.headers["User-Agent"] = "treeherder-pyclient"
197 self.jobs_url = "https://treeherder.mozilla.org/api/jobs/"
198 self.push_ids = {}
199 self.job_ids = {}
200 self.extras: Dict[str, PlatformInfo] = {}
201 self.bugs = [] # preloaded bugs, currently not an updated cache
202 self.error_summary = {}
203 self._subtest_rx = None
204 self.lmp = None
205 self.failure_types = None
206 self.failed_platforms: Dict[str, FailedPlatform] = {}
207 self.platform_permutations: Dict[
208 str, # Manifest
209 Dict[
210 str, # OS
211 Dict[
212 str, # OS Version
213 Dict[
214 str, # Processor
215 Dict[
216 str, # Build type
217 Dict[
218 str, # Test Variant
219 Dict[str, int], # {'pass': x, 'fail': y}
220 ],
221 ],
222 ],
223 ],
224 ],
225 ] = {}
226
227 def _initialize_bzapi(self):
228 """Lazily initializes the Bugzilla API (returns True on success)"""
229 if self._bzapi is None and self.bugzilla is not None:
230 self._bzapi = bugzilla.Bugzilla(self.bugzilla)
231 self._attach_rx = re.compile(ATTACHMENT_REGEX, flags=re.M)
232 return self._bzapi is not None
233
234 def pprint(self, obj):
235 if self.pp is None:
236 self.pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
237 self.pp.pprint(obj)
238 sys.stderr.flush()
239
240 def error(self, e):
241 if self.command_context is not None:
242 self.command_context.log(
243 logging.ERROR, self.component, {ERROR: str(e)}, "ERROR: {error}"
244 )
245 else:
246 print(f"ERROR: {e}", file=sys.stderr, flush=True)
247
248 def warning(self, e):
249 if self.command_context is not None:
250 self.command_context.log(
251 logging.WARNING, self.component, {ERROR: str(e)}, "WARNING: {error}"
252 )
253 else:
254 print(f"WARNING: {e}", file=sys.stderr, flush=True)
255
256 def info(self, e):
257 if self.command_context is not None:
258 self.command_context.log(
259 logging.INFO, self.component, {ERROR: str(e)}, "INFO: {error}"
260 )
261 else:
262 print(f"INFO: {e}", file=sys.stderr, flush=True)
263
264 def vinfo(self, e):
265 if self.verbose:
266 self.info(e)
267
268 def full_path(self, filename):
269 """Returns full path for the relative filename"""
270
271 return os.path.join(self.topsrcdir, os.path.normpath(filename.split(":")[-1]))
272
273 def isdir(self, filename):
274 """Returns True if filename is a directory"""
275
276 return os.path.isdir(self.full_path(filename))
277
278 def exists(self, filename):
279 """Returns True if filename exists"""
280
281 return os.path.exists(self.full_path(filename))
282
283 def run(
284 self,
285 meta_bug_id=None,
286 save_tasks=None,
287 use_tasks=None,
288 save_failures=None,
289 use_failures=None,
290 max_failures=-1,
291 ):
292 "Run skip-fails on try_url, return True on success"
293
294 try_url = self.try_url
295 revision, repo = self.get_revision(try_url)
296 if use_tasks is not None:
297 tasks = self.read_tasks(use_tasks)
298 self.vinfo(f"use tasks: {use_tasks}")
299 self.failure_types = None # do NOT cache failure_types
300 else:
301 tasks = self.get_tasks(revision, repo)
302 self.failure_types = {} # cache failure_types
303 if use_failures is not None:
304 failures = self.read_failures(use_failures)
305 self.vinfo(f"use failures: {use_failures}")
306 else:
307 failures = self.get_failures(tasks)
308 if save_failures is not None:
309 self.write_json(save_failures, failures)
310 self.vinfo(f"save failures: {save_failures}")
311 if save_tasks is not None:
312 self.write_tasks(save_tasks, tasks)
313 self.vinfo(f"save tasks: {save_tasks}")
314 num_failures = 0
315 self.vinfo(
316 f"skip-fails assumes implicit-vars for reftest: {self.implicit_vars}"
317 )
318 for manifest in failures:
319 kind = failures[manifest][KIND]
320 for label in failures[manifest][LL]:
321 for path in failures[manifest][LL][label][PP]:
322 classification = failures[manifest][LL][label][PP][path][CC]
323 if classification.startswith("disable_") or (
324 self.turbo and classification == Classification.SECONDARY
325 ):
326 anyjs = {} # anyjs alternate basename = False
327 differences = []
328 pixels = []
329 status = FAIL
330 lineno = failures[manifest][LL][label][PP][path].get(LINENO, 0)
331 runs: Dict[str, Dict[str, Any]] = failures[manifest][LL][label][
332 PP
333 ][path][RUNS]
334 # skip_failure only needs to run against one task for each path
335 first_task_id = next(iter(runs))
336 for task_id in runs:
337 if kind == Kind.TOML:
338 break
339 elif kind == Kind.LIST:
340 difference = runs[task_id].get(DIFFERENCE, 0)
341 if difference > 0:
342 differences.append(difference)
343 pixel = runs[task_id].get(PIXELS, 0)
344 if pixel > 0:
345 pixels.append(pixel)
346 status = runs[task_id].get(STATUS, FAIL)
347 elif kind == Kind.WPT:
348 filename = os.path.basename(path)
349 anyjs[filename] = False
350 if QUERY in runs[task_id]:
351 query = runs[task_id][QUERY]
352 anyjs[filename + query] = False
353 else:
354 query = None
355 if ANYJS in runs[task_id]:
356 any_filename = os.path.basename(
357 runs[task_id][ANYJS]
358 )
359 anyjs[any_filename] = False
360 if query is not None:
361 anyjs[any_filename + query] = False
362
363 self.skip_failure(
364 manifest,
365 kind,
366 path,
367 anyjs,
368 differences,
369 pixels,
370 lineno,
371 status,
372 label,
373 classification,
374 first_task_id,
375 try_url,
376 revision,
377 repo,
378 meta_bug_id,
379 )
380 num_failures += 1
381 if max_failures >= 0 and num_failures >= max_failures:
382 self.warning(
383 f"max_failures={max_failures} threshold reached: stopping."
384 )
385 return True
386 return True
387
388 def get_revision(self, url):
389 parsed = urllib.parse.urlparse(url)
390 if parsed.scheme != "https":
391 raise ValueError("try_url scheme not https")
392 if parsed.netloc != Skipfails.TREEHERDER:
393 raise ValueError(f"try_url server not {Skipfails.TREEHERDER}")
394 if len(parsed.query) == 0:
395 raise ValueError("try_url query missing")
396 query = urllib.parse.parse_qs(parsed.query)
397 if Skipfails.REVISION not in query:
398 raise ValueError("try_url query missing revision")
399 revision = query[Skipfails.REVISION][0]
400 if Skipfails.REPO in query:
401 repo = query[Skipfails.REPO][0]
402 else:
403 repo = "try"
404 self.vinfo(f"considering {repo} revision={revision}")
405 return revision, repo
406
407 def get_tasks(self, revision, repo):
408 push = mozci.push.Push(revision, repo)
409 return push.tasks
410
411 def get_kind_manifest(self, manifest: str):
412 kind = Kind.UNKNOWN
413 if manifest.endswith(".ini"):
414 self.warning(f"cannot analyze skip-fails on INI manifests: {manifest}")
415 return (None, None)
416 elif manifest.endswith(".list"):
417 kind = Kind.LIST
418 elif manifest.endswith(".toml"):
419 kind = Kind.TOML
420 else:
421 kind = Kind.WPT
422 path, wpt_manifest, _query, _anyjs = self.wpt_paths(manifest)
423 if path is None or wpt_manifest is None: # not WPT
424 self.warning(
425 f"cannot analyze skip-fails on unknown manifest type: {manifest}"
426 )
427 return (None, None)
428 manifest = wpt_manifest
429 return (kind, manifest)
430
431 def get_task_config(self, task: TestTask):
432 if task.label is None:
433 self.warning(f"Cannot find task label for task: {task.id}")
434 return None
435 # strip chunk number - this finds failures across different chunks
436 try:
437 parts = task.label.split("-")
438 int(parts[-1])
439 return "-".join(parts[:-1])
440 except ValueError:
441 return task.label
442
443 def get_failures(self, tasks: List[TestTask]):
444 """
445 find failures and create structure comprised of runs by path:
446 result:
447 * False (failed)
448 * True (passed)
449 classification: Classification
450 * unknown (default) < 3 runs
451 * intermittent (not enough failures)
452 * disable_recommended (enough repeated failures) >3 runs >= 4
453 * disable_manifest (disable DEFAULT if no other failures)
454 * secondary (not first failure in group)
455 * success
456 """
457
458 failures = {}
459 manifest_paths: Dict[str, Dict[str, List[str]]] = {}
460 manifest_ = {
461 KIND: Kind.UNKNOWN,
462 LL: {},
463 }
464 label_ = {
465 DURATIONS: {},
466 MEDIAN_DURATION: 0,
467 OPT: False,
468 PP: {},
469 SUM_BY_LABEL: {}, # All sums implicitly zero
470 TOTAL_DURATION: 0,
471 }
472 path_ = {
473 CC: Classification.UNKNOWN,
474 FAILED_RUNS: 0,
475 RUNS: {},
476 TOTAL_RUNS: 0,
477 }
478 run_ = {
479 RR: False,
480 }
481
482 for task in tasks: # add explicit failures
483 config = self.get_task_config(task)
484 if config is None:
485 continue
486
487 try:
488 if len(task.results) == 0:
489 continue # ignore aborted tasks
490 failure_types = task.failure_types # call magic property once
491 if failure_types is None:
492 continue
493 if self.failure_types is None:
494 self.failure_types = {}
495 self.failure_types[task.id] = failure_types
496 self.vinfo(f"Getting failure_types from task: {task.id}")
497 for raw_manifest in failure_types:
498 kind, manifest = self.get_kind_manifest(raw_manifest)
499 if kind is None or manifest is None:
500 continue
501
502 if kind != Kind.WPT:
503 if manifest not in failures:
504 failures[manifest] = deepcopy(manifest_)
505 failures[manifest][KIND] = kind
506 if task.label not in failures[manifest][LL]:
507 failures[manifest][LL][task.label] = deepcopy(label_)
508
509 if manifest not in manifest_paths:
510 manifest_paths[manifest] = {}
511 if config not in manifest_paths[manifest]:
512 manifest_paths[manifest][config] = []
513
514 for path_type in failure_types[raw_manifest]:
515 path, _type = path_type
516 query = None
517 anyjs = None
518 allpaths = []
519 if kind == Kind.WPT:
520 path, mmpath, query, anyjs = self.wpt_paths(path)
521 if path is None or mmpath is None:
522 self.warning(
523 f"non existant failure path: {path_type[0]}"
524 )
525 break
526 allpaths = [path]
527 manifest = os.path.dirname(mmpath)
528 if manifest not in manifest_paths:
529 # this can be a subdir, or translated path
530 manifest_paths[manifest] = {}
531 if config not in manifest_paths[manifest]:
532 manifest_paths[manifest][config] = []
533 if manifest not in failures:
534 failures[manifest] = deepcopy(manifest_)
535 failures[manifest][KIND] = kind
536 if task.label not in failures[manifest][LL]:
537 failures[manifest][LL][task.label] = deepcopy(label_)
538 elif kind == Kind.LIST:
539 words = path.split()
540 if len(words) != 3 or words[1] not in TEST_TYPES:
541 self.warning(f"reftest type not supported: {path}")
542 continue
543 allpaths = self.get_allpaths(task.id, manifest, path)
544 elif kind == Kind.TOML:
545 if path == manifest:
546 path = DEF # refers to the manifest itself
547 allpaths = [path]
548 for path in allpaths:
549 if path not in manifest_paths[manifest].get(config, []):
550 manifest_paths[manifest][config].append(path)
551 self.vinfo(
552 f"Getting failure info in manifest: {manifest}, path: {path}"
553 )
554 task_path_object = failures[manifest][LL][task.label][PP]
555 if path not in task_path_object:
556 task_path_object[path] = deepcopy(path_)
557 task_path = task_path_object[path]
558 if task.id not in task_path[RUNS]:
559 task_path[RUNS][task.id] = deepcopy(run_)
560 else:
561 continue
562 result = task.result == "passed"
563 task_path[RUNS][task.id][RR] = result
564 if query is not None:
565 task_path[RUNS][task.id][QUERY] = query
566 if anyjs is not None:
567 task_path[RUNS][task.id][ANYJS] = anyjs
568 task_path[TOTAL_RUNS] += 1
569 if not result:
570 task_path[FAILED_RUNS] += 1
571 if kind == Kind.LIST:
572 (
573 lineno,
574 difference,
575 pixels,
576 status,
577 ) = self.get_lineno_difference_pixels_status(
578 task.id, manifest, path
579 )
580 if lineno > 0:
581 task_path[LINENO] = lineno
582 else:
583 self.vinfo(f"ERROR no lineno for {path}")
584 if status != FAIL:
585 task_path[RUNS][task.id][STATUS] = status
586 if status == FAIL and difference == 0 and pixels == 0:
587 # intermittent, not error
588 task_path[RUNS][task.id][RR] = True
589 task_path[FAILED_RUNS] -= 1
590 elif difference > 0:
591 task_path[RUNS][task.id][DIFFERENCE] = difference
592 if pixels > 0:
593 task_path[RUNS][task.id][PIXELS] = pixels
594 except AttributeError:
595 pass # self.warning(f"unknown attribute in task (#1): {ae}")
596
597 for task in tasks: # add results
598 config = self.get_task_config(task)
599 if config is None:
600 continue
601
602 try:
603 if len(task.results) == 0:
604 continue # ignore aborted tasks
605 if self.failure_types is None:
606 continue
607 self.vinfo(f"Getting results from task: {task.id}")
608 for result in task.results:
609 kind, manifest = self.get_kind_manifest(result.group)
610 if kind is None or manifest is None:
611 continue
612
613 if manifest not in manifest_paths:
614 continue
615 if config not in manifest_paths[manifest]:
616 continue
617 if manifest not in failures:
618 failures[manifest] = deepcopy(manifest_)
619 task_label_object = failures[manifest][LL]
620 if task.label not in task_label_object:
621 task_label_object[task.label] = deepcopy(label_)
622 task_label = task_label_object[task.label]
623 if task.id not in task_label[DURATIONS]:
624 # duration may be None !!!
625 task_label[DURATIONS][task.id] = result.duration or 0
626 if task_label[OPT] is None:
627 task_label[OPT] = self.get_opt_for_task(task.id)
628 for path in manifest_paths[manifest][config]: # all known paths
629 # path can be one of any paths that have failed for the manifest/config
630 # ensure the path is in the specific task failure data
631 if path not in [
632 path
633 for path, type in self.failure_types.get(task.id, {}).get(
634 manifest, [("", "")]
635 )
636 ]:
637 result.ok = True
638
639 task_path_object = task_label[PP]
640 if path not in task_path_object:
641 task_path_object[path] = deepcopy(path_)
642 task_path = task_path_object[path]
643 if task.id not in task_path[RUNS]:
644 task_path[RUNS][task.id] = deepcopy(run_)
645 task_path[RUNS][task.id][RR] = result.ok
646 task_path[TOTAL_RUNS] += 1
647 if not result.ok:
648 task_path[FAILED_RUNS] += 1
649 if kind == Kind.LIST:
650 (
651 lineno,
652 difference,
653 pixels,
654 status,
655 ) = self.get_lineno_difference_pixels_status(
656 task.id, manifest, path
657 )
658 if lineno > 0:
659 task_path[LINENO] = lineno
660 else:
661 self.vinfo(f"ERROR no lineno for {path}")
662 if status != FAIL:
663 task_path[RUNS][task.id][STATUS] = status
664 if (
665 status == FAIL
666 and difference == 0
667 and pixels == 0
668 and not result.ok
669 ):
670 # intermittent, not error
671 task_path[RUNS][task.id][RR] = True
672 task_path[FAILED_RUNS] -= 1
673 if difference > 0:
674 task_path[RUNS][task.id][DIFFERENCE] = difference
675 if pixels > 0:
676 task_path[RUNS][task.id][PIXELS] = pixels
677 except AttributeError:
678 pass # self.warning(f"unknown attribute in task (#2): {ae}")
679
680 for manifest in failures: # determine classifications
681 kind = failures[manifest][KIND]
682 for label in failures[manifest][LL]:
683 task_label = failures[manifest][LL][label]
684 opt = task_label[OPT]
685 durations = [] # summarize durations
686 try:
687 first_task_id: str = next(iter(task_label.get(DURATIONS, {})))
688 except StopIteration:
689 continue
690 for task_id in task_label.get(DURATIONS, {}):
691 duration = task_label[DURATIONS][task_id]
692 durations.append(duration)
693 if len(durations) > 0:
694 total_duration = sum(durations)
695 median_duration = median(durations)
696 task_label[TOTAL_DURATION] = total_duration
697 task_label[MEDIAN_DURATION] = median_duration
698 if (opt and median_duration > OPT_THRESHOLD) or (
699 (not opt) and median_duration > DEBUG_THRESHOLD
700 ):
701 if kind == Kind.TOML:
702 paths = [DEF]
703 else:
704 paths = task_label[PP].keys()
705 for path in paths:
706 task_path_object = task_label[PP]
707 if path not in task_path_object:
708 task_path_object[path] = deepcopy(path_)
709 task_path = task_path_object[path]
710 if first_task_id not in task_path[RUNS]:
711 task_path[RUNS][first_task_id] = deepcopy(run_)
712 task_path[RUNS][first_task_id][RR] = False
713 task_path[TOTAL_RUNS] += 1
714 task_path[FAILED_RUNS] += 1
715 task_path[CC] = Classification.DISABLE_TOO_LONG
716 primary = True # we have not seen the first failure
717 for path in sort_paths(task_label[PP]):
718 task_path = task_label[PP][path]
719 classification = task_path[CC]
720 if classification == Classification.UNKNOWN:
721 failed_runs = task_path[FAILED_RUNS]
722 total_runs = task_path[TOTAL_RUNS]
723 status = FAIL # default status, only one run could be PASS
724 for first_task_id in task_path[RUNS]:
725 status = task_path[RUNS][first_task_id].get(STATUS, status)
726 if kind == Kind.LIST:
727 failure_ratio = INTERMITTENT_RATIO_REFTEST
728 else:
729 failure_ratio = FAILURE_RATIO
730 if total_runs >= MINIMUM_RUNS:
731 if failed_runs / total_runs < failure_ratio:
732 if failed_runs == 0:
733 classification = Classification.SUCCESS
734 else:
735 classification = Classification.INTERMITTENT
736 elif kind == Kind.LIST:
737 if failed_runs / total_runs < FAILURE_RATIO_REFTEST:
738 classification = Classification.DISABLE_INTERMITTENT
739 else:
740 classification = Classification.DISABLE_FAILURE
741 elif primary:
742 if path == DEF:
743 classification = Classification.DISABLE_MANIFEST
744 else:
745 classification = Classification.DISABLE_RECOMMENDED
746 primary = False
747 else:
748 classification = Classification.SECONDARY
749 task_path[CC] = classification
750 if classification not in task_label[SUM_BY_LABEL]:
751 task_label[SUM_BY_LABEL][classification] = 0
752 task_label[SUM_BY_LABEL][classification] += 1
753
754 return failures
755
756 def _get_os_version(self, os, platform):
757 """Return the os_version given the label platform string"""
758 i = platform.find(os)
759 j = i + len(os)
760 yy = platform[j : j + 2]
761 mm = platform[j + 2 : j + 4]
762 return yy + "." + mm
763
764 def get_bug_by_id(self, id):
765 """Get bug by bug id"""
766
767 bug = None
768 for b in self.bugs:
769 if b.id == id:
770 bug = b
771 break
772 if bug is None and self._initialize_bzapi():
773 bug = self._bzapi.getbug(id)
774 return bug
775
776 def get_bugs_by_summary(self, summary):
777 """Get bug by bug summary"""
778
779 bugs = []
780 for b in self.bugs:
781 if b.summary == summary:
782 bugs.append(b)
783 if len(bugs) > 0:
784 return bugs
785 if self._initialize_bzapi():
786 query = self._bzapi.build_query(short_desc=summary)
787 query["include_fields"] = [
788 "id",
789 "product",
790 "component",
791 "status",
792 "resolution",
793 "summary",
794 "blocks",
795 ]
796 try:
797 bugs = self._bzapi.query(query)
798 except requests.exceptions.HTTPError:
799 if not self.dry_run:
800 raise
801 return bugs
802
803 def create_bug(
804 self,
805 summary="Bug short description",
806 description="Bug description",
807 product="Testing",
808 component="General",
809 version="unspecified",
810 bugtype="task",
811 ):
812 """Create a bug"""
813
814 bug = None
815 if self._initialize_bzapi():
816 if not self._bzapi.logged_in:
817 self.error(
818 "Must create a Bugzilla API key per https://github.com/mozilla/mozci-tools/blob/main/citools/test_triage_bug_filer.py"
819 )
820 raise PermissionError(f"Not authenticated for Bugzilla {self.bugzilla}")
821 createinfo = self._bzapi.build_createbug(
822 product=product,
823 component=component,
824 summary=summary,
825 version=version,
826 description=description,
827 )
828 createinfo["type"] = bugtype
829 bug = self._bzapi.createbug(createinfo)
830 return bug
831
832 def add_bug_comment(self, id, comment, meta_bug_id=None):
833 """Add a comment to an existing bug"""
834
835 if self._initialize_bzapi():
836 if not self._bzapi.logged_in:
837 self.error(BUGZILLA_AUTHENTICATION_HELP)
838 raise PermissionError("Not authenticated for Bugzilla")
839 if meta_bug_id is not None:
840 blocks_add = [meta_bug_id]
841 else:
842 blocks_add = None
843 updateinfo = self._bzapi.build_update(
844 comment=comment, blocks_add=blocks_add
845 )
846 self._bzapi.update_bugs([id], updateinfo)
847
848 def generate_bugzilla_comment(
849 self,
850 manifest: str,
851 kind: str,
852 path: str,
853 anyjs: Optional[Dict[str, bool]],
854 lineno: int,
855 label: str,
856 classification: str,
857 task_id: Optional[str],
858 try_url: str,
859 revision: str,
860 repo: str,
861 skip_if: str,
862 filename: str,
863 meta_bug_id: Optional[str] = None,
864 ):
865 bug_reference = ""
866 if classification == Classification.DISABLE_MANIFEST:
867 comment = "Disabled entire manifest due to crash result"
868 elif classification == Classification.DISABLE_TOO_LONG:
869 comment = "Disabled entire manifest due to excessive run time"
870 else:
871 comment = f'Disabled test due to failures in test file: "{filename}"'
872 if classification == Classification.SECONDARY:
873 comment += " (secondary)"
874 if kind != Kind.WPT:
875 bug_reference = " (secondary)"
876 if kind != Kind.LIST:
877 self.vinfo(f"filename: {filename}")
878 if kind == Kind.WPT and anyjs is not None and len(anyjs) > 1:
879 comment += "\nAdditional WPT wildcard paths:"
880 for p in sorted(anyjs.keys()):
881 if p != filename:
882 comment += f'\n "{p}"'
883 platform, testname = self.label_to_platform_testname(label)
884 if platform is not None:
885 comment += "\nCommand line to reproduce (experimental):\n"
886 comment += f" \"mach try fuzzy -q '{platform}' {testname}\""
887 comment += f"\nTry URL = {try_url}"
888 comment += f"\nrevision = {revision}"
889 comment += f"\nrepo = {repo}"
890 comment += f"\nlabel = {label}"
891 if task_id is not None:
892 comment += f"\ntask_id = {task_id}"
893 if kind != Kind.LIST:
894 push_id = self.get_push_id(revision, repo)
895 if push_id is not None:
896 comment += f"\npush_id = {push_id}"
897 job_id = self.get_job_id(push_id, task_id)
898 if job_id is not None:
899 comment += f"\njob_id = {job_id}"
900 (
901 suggestions_url,
902 line_number,
903 line,
904 log_url,
905 ) = self.get_bug_suggestions(repo, job_id, path, anyjs)
906 if log_url is not None:
907 comment += f"\nBug suggestions: {suggestions_url}"
908 comment += f"\nSpecifically see at line {line_number} in the attached log: {log_url}"
909 comment += f'\n\n "{line}"\n'
910 bug_summary = f"MANIFEST {manifest}"
911 attachments = {}
912 bugid = "TBD"
913 if self.bugzilla is None:
914 self.vinfo("Bugzilla has been disabled: no bugs created or updated")
915 else:
916 bugs = self.get_bugs_by_summary(bug_summary)
917 if len(bugs) == 0:
918 description = (
919 f"This bug covers excluded failing tests in the MANIFEST {manifest}"
920 )
921 description += "\n(generated by `mach manifest skip-fails`)"
922 product, component = self.get_file_info(path)
923 if self.dry_run:
924 self.warning(
925 f'Dry-run NOT creating bug: {product}::{component} "{bug_summary}"'
926 )
927 else:
928 bug = self.create_bug(bug_summary, description, product, component)
929 if bug is not None:
930 bugid = bug.id
931 self.vinfo(
932 f'Created Bug {bugid} {product}::{component} : "{bug_summary}"'
933 )
934 elif len(bugs) == 1:
935 bugid = bugs[0].id
936 product = bugs[0].product
937 component = bugs[0].component
938 self.vinfo(f'Found Bug {bugid} {product}::{component} "{bug_summary}"')
939 if meta_bug_id is not None:
940 if meta_bug_id in bugs[0].blocks:
941 self.vinfo(
942 f" Bug {bugid} already blocks meta bug {meta_bug_id}"
943 )
944 meta_bug_id = None # no need to add again
945 comments = bugs[0].getcomments()
946 for i in range(len(comments)):
947 text = comments[i]["text"]
948 attach_rx = self._attach_rx
949 if attach_rx is not None:
950 m = attach_rx.findall(text)
951 if len(m) == 1:
952 a_task_id = m[0][1]
953 attachments[a_task_id] = m[0][0]
954 if a_task_id == task_id:
955 self.vinfo(
956 f" Bug {bugid} already has the compressed log attached for this task"
957 )
958 else:
959 raise Exception(f'More than one bug found for summary: "{bug_summary}"')
960 bug_reference = f"Bug {bugid}" + bug_reference
961 if kind == Kind.LIST:
962 comment += (
963 f"\nfuzzy-if condition on line {lineno}: {skip_if} # {bug_reference}"
964 )
965 else:
966 comment += f"\nskip-if condition: {skip_if} # {bug_reference}"
967 return (comment, bug_reference, bugid, attachments)
968
969 def resolve_failure_filename(self, path: str, kind: str, manifest: str) -> str:
970 filename = DEF
971 if kind == Kind.TOML:
972 filename = self.get_filename_in_manifest(manifest.split(":")[-1], path)
973 elif kind == Kind.WPT:
974 filename = os.path.basename(path)
975 elif kind == Kind.LIST:
976 filename = [
977 am
978 for am in self.error_summary.get(manifest, "")
979 if self.error_summary[manifest][am]["test"].endswith(path)
980 ]
981 if filename:
982 filename = filename[0]
983 else:
984 filename = path
985 return filename
986
987 def resolve_failure_manifest(self, path: str, kind: str, manifest: str) -> str:
988 if kind == Kind.WPT:
989 _path, resolved_manifest, _query, _anyjs = self.wpt_paths(path)
990 if resolved_manifest:
991 return resolved_manifest
992 raise Exception(f"Could not resolve WPT manifest for path {path}")
993 return manifest
994
995 def skip_failure(
996 self,
997 manifest: str,
998 kind: str,
999 path: str,
1000 anyjs: Optional[Dict[str, bool]],
1001 differences: List[int],
1002 pixels: List[int],
1003 lineno: int,
1004 status: str,
1005 label: str,
1006 classification: str,
1007 task_id: Optional[str],
1008 try_url: str,
1009 revision: str,
1010 repo: str,
1011 meta_bug_id: Optional[str] = None,
1012 ):
1013 """
1014 Skip a failure (for TOML, WPT and REFTEST manifests)
1015 For wpt anyjs is a dictionary mapping from alternate basename to
1016 a boolean (indicating if the basename has been handled in the manifest)
1017 """
1018 path = path.split(":")[-1]
1019
1020 self.vinfo(f"\n\n===== Skip failure in manifest: {manifest} =====")
1021 self.vinfo(f" path: {path}")
1022 skip_if: Optional[str]
1023 if task_id is None:
1024 skip_if = "true"
1025 else:
1026 skip_if = self.task_to_skip_if(manifest, task_id, kind, path)
1027 if skip_if is None:
1028 raise Exception(
1029 f"Unable to calculate skip-if condition from manifest={manifest} from failure label={label}"
1030 )
1031
1032 filename = self.resolve_failure_filename(path, kind, manifest)
1033 manifest = self.resolve_failure_manifest(path, kind, manifest)
1034 manifest_path = self.full_path(manifest)
1035 manifest_str = ""
1036 additional_comment = ""
1037 comment, bug_reference, bugid, attachments = self.generate_bugzilla_comment(
1038 manifest,
1039 kind,
1040 path,
1041 anyjs,
1042 lineno,
1043 label,
1044 classification,
1045 task_id,
1046 try_url,
1047 revision,
1048 repo,
1049 skip_if,
1050 filename,
1051 meta_bug_id,
1052 )
1053 if kind == Kind.WPT:
1054 if os.path.exists(manifest_path):
1055 manifest_str = open(manifest_path, encoding="utf-8").read()
1056 else:
1057 # ensure parent directories exist
1058 os.makedirs(os.path.dirname(manifest_path), exist_ok=True)
1059 manifest_str, additional_comment = self.wpt_add_skip_if(
1060 manifest_str, anyjs, skip_if, bug_reference
1061 )
1062 elif kind == Kind.TOML:
1063 mp = ManifestParser(use_toml=True, document=True)
1064 try:
1065 mp.read(manifest_path)
1066 except OSError:
1067 raise Exception(f"Unable to find path: {manifest_path}")
1068
1069 document = mp.source_documents[manifest_path]
1070 try:
1071 additional_comment = add_skip_if(
1072 document,
1073 filename,
1074 skip_if,
1075 bug_reference,
1076 )
1077 except Exception:
1078 # Note: this fails to find a comment at the desired index
1079 # Note: manifestparser len(skip_if) yields: TypeError: object of type 'bool' has no len()
1080 additional_comment = ""
1081
1082 manifest_str = alphabetize_toml_str(document)
1083 elif kind == Kind.LIST:
1084 if lineno == 0:
1085 self.error(
1086 f"cannot determine line to edit in manifest: {manifest_path}"
1087 )
1088 elif not os.path.exists(manifest_path):
1089 self.error(f"manifest does not exist: {manifest_path}")
1090 else:
1091 manifest_str = open(manifest_path, encoding="utf-8").read()
1092 if status == PASS:
1093 self.info(f"Unexpected status: {status}")
1094 if (
1095 status == PASS
1096 or classification == Classification.DISABLE_INTERMITTENT
1097 ):
1098 zero = True # refest lower ranges should include zero
1099 else:
1100 zero = False
1101 manifest_str, additional_comment = self.reftest_add_fuzzy_if(
1102 manifest_str,
1103 filename,
1104 skip_if,
1105 differences,
1106 pixels,
1107 lineno,
1108 zero,
1109 bug_reference,
1110 )
1111 if not manifest_str and additional_comment:
1112 self.warning(additional_comment)
1113 if additional_comment:
1114 comment += "\n" + additional_comment
1115 if len(manifest_str) > 0:
1116 fp = open(manifest_path, "w", encoding="utf-8", newline="\n")
1117 fp.write(manifest_str)
1118 fp.close()
1119 self.info(f'Edited ["{filename}"] in manifest: "{manifest}"')
1120 if kind != Kind.LIST:
1121 self.info(f'added skip-if condition: "{skip_if}" # {bug_reference}')
1122 if self.dry_run:
1123 self.info(f"Dry-run NOT adding comment to Bug {bugid}:\n{comment}")
1124 self.info(
1125 f'Dry-run NOT editing ["{filename}"] in manifest: "{manifest}"'
1126 )
1127 self.info(f'would add skip-if condition: "{skip_if}" # {bug_reference}')
1128 if task_id is not None and task_id not in attachments:
1129 self.info("would add compressed log for this task")
1130 return
1131 elif self.bugzilla is None:
1132 self.warning(f"NOT adding comment to Bug {bugid}:\n{comment}")
1133 else:
1134 self.add_bug_comment(bugid, comment, meta_bug_id)
1135 self.info(f"Added comment to Bug {bugid}:\n{comment}")
1136 if meta_bug_id is not None:
1137 self.info(f" Bug {bugid} blocks meta Bug: {meta_bug_id}")
1138 if task_id is not None and task_id not in attachments:
1139 self.add_attachment_log_for_task(bugid, task_id)
1140 self.info("Added compressed log for this task")
1141 else:
1142 self.error(f'Error editing ["{filename}"] in manifest: "{manifest}"')
1143
1144 def get_variants(self):
1145 """Get mozinfo for each test variants"""
1146
1147 if len(self.variants) == 0:
1148 variants_file = "taskcluster/kinds/test/variants.yml"
1149 variants_path = self.full_path(variants_file)
1150 fp = open(variants_path, encoding="utf-8")
1151 raw_variants = load(fp, Loader=Loader)
1152 fp.close()
1153 for k, v in raw_variants.items():
1154 mozinfo = k
1155 if "mozinfo" in v:
1156 mozinfo = v["mozinfo"]
1157 self.variants[k] = mozinfo
1158 return self.variants
1159
1160 def get_task_details(self, task_id):
1161 """Download details for task task_id"""
1162
1163 if task_id in self.tasks: # if cached
1164 task = self.tasks[task_id]
1165 else:
1166 self.vinfo(f"get_task_details for task: {task_id}")
1167 try:
1168 task = get_task(task_id)
1169 except TaskclusterRestFailure:
1170 self.warning(f"Task {task_id} no longer exists.")
1171 return None
1172 self.tasks[task_id] = task
1173 return task
1174
1175 def get_extra(self, task_id):
1176 """Calculate extra for task task_id"""
1177
1178 if task_id in self.extras: # if cached
1179 platform_info = self.extras[task_id]
1180 else:
1181 self.get_variants()
1182 task = self.get_task_details(task_id) or {}
1183 test_setting = task.get("extra", {}).get("test-setting", {})
1184 platform = test_setting.get("platform", {})
1185 platform_os = platform.get("os", {})
1186 if self.new_version:
1187 platform_os["version"] = self.new_version
1188 platform_info = PlatformInfo(test_setting)
1189 self.extras[task_id] = platform_info
1190 return platform_info
1191
1192 def get_opt_for_task(self, task_id):
1193 extra = self.get_extra(task_id)
1194 return extra.opt
1195
1196 def _fetch_platform_permutations(self):
1197 self.info("Fetching platform permutations...")
1198 import taskcluster
1199
1200 url: Optional[str] = None
1201 index = taskcluster.Index(
1202 {
1203 "rootUrl": "https://firefox-ci-tc.services.mozilla.com",
1204 }
1205 )
1206 route = "gecko.v2.mozilla-central.latest.source.test-info-all"
1207 queue = taskcluster.Queue(
1208 {
1209 "rootUrl": "https://firefox-ci-tc.services.mozilla.com",
1210 }
1211 )
1212
1213 # Typing from findTask is wrong, so we need to convert to Any
1214 result: Optional[Dict[str, Any]] = index.findTask(route)
1215 if result is not None:
1216 task_id: str = result["taskId"]
1217 result = queue.listLatestArtifacts(task_id)
1218 if result is not None and task_id is not None:
1219 artifact_list: List[Dict[Literal["name"], str]] = result["artifacts"]
1220 for artifact in artifact_list:
1221 artifact_name = artifact["name"]
1222 if artifact_name.endswith("test-info-testrun-matrix.json"):
1223 url = queue.buildUrl(
1224 "getLatestArtifact", task_id, artifact_name
1225 )
1226 break
1227
1228 if url is not None:
1229 response = requests.get(url, headers={"User-agent": "mach-test-info/1.0"})
1230 self.platform_permutations = response.json()
1231 else:
1232 self.info("Failed fetching platform permutations...")
1233
1234 def _get_list_skip_if(self, platform_info: PlatformInfo):
1235 aa = "&&"
1236 nn = "!"
1237
1238 os = platform_info.os
1239 build_type = platform_info.build_type
1240 runtimes = platform_info.test_variant
1241
1242 skip_if = None
1243 if os == "linux":
1244 skip_if = "gtkWidget"
1245 elif os == "win":
1246 skip_if = "winWidget"
1247 elif os == "mac":
1248 skip_if = "cocoaWidget"
1249 elif os == "android":
1250 skip_if = "Android"
1251 else:
1252 self.error(f"cannot calculate skip-if for unknown OS: '{os}'")
1253 if skip_if is not None:
1254 ccov = "ccov" in build_type
1255 asan = "asan" in build_type
1256 tsan = "tsan" in build_type
1257 optimized = (
1258 (not platform_info.debug) and (not ccov) and (not asan) and (not tsan)
1259 )
1260 skip_if += aa
1261 if optimized:
1262 skip_if += "optimized"
1263 elif platform_info.debug:
1264 skip_if += "isDebugBuild"
1265 elif ccov:
1266 skip_if += "isCoverageBuild"
1267 elif asan:
1268 skip_if += "AddressSanitizer"
1269 elif tsan:
1270 skip_if += "ThreadSanitizer"
1271 # See implicit VARIANT_DEFAULTS in
1272 # https://searchfox.org/mozilla-central/source/layout/tools/reftest/manifest.sys.mjs#30
1273 fission = "no-fission" not in runtimes
1274 snapshot = "snapshot" in runtimes
1275 swgl = "swgl" in runtimes
1276 nogpu = "nogpu" in runtimes
1277 if not self.implicit_vars and fission:
1278 skip_if += aa + "fission"
1279 elif not fission: # implicit default: fission
1280 skip_if += aa + nn + "fission"
1281 if platform_info.bits is not None:
1282 if platform_info.bits == "32":
1283 skip_if += aa + nn + "is64Bit" # override implicit is64Bit
1284 elif not self.implicit_vars and os == "winWidget":
1285 skip_if += aa + "is64Bit"
1286 if not self.implicit_vars and not swgl:
1287 skip_if += aa + nn + "swgl"
1288 elif swgl: # implicit default: !swgl
1289 skip_if += aa + "swgl"
1290
1291 if not self.implicit_vars and not nogpu:
1292 skip_if += aa + nn + "nogpu"
1293 elif nogpu: # implicit default: !swgl
1294 skip_if += aa + "nogpu"
1295
1296 if os == "gtkWidget":
1297 if not self.implicit_vars and not snapshot:
1298 skip_if += aa + nn + "useDrawSnapshot"
1299 elif snapshot: # implicit default: !useDrawSnapshot
1300 skip_if += aa + "useDrawSnapshot"
1301 return skip_if
1302
1303 def task_to_skip_if(
1304 self, manifest: str, task_id: str, kind: str, file_path: str
1305 ) -> str:
1306 """Calculate the skip-if condition for failing task task_id"""
1307
1308 if kind == Kind.WPT:
1309 qq = '"'
1310 aa = " and "
1311 else:
1312 qq = "'"
1313 aa = " && "
1314 eq = " == "
1315 extra = self.get_extra(task_id)
1316 skip_if = None
1317 os = extra.os
1318 os_version = extra.os_version
1319 if os is not None:
1320 if kind == Kind.LIST:
1321 skip_if = self._get_list_skip_if(extra)
1322 elif os_version is not None:
1323 skip_if = "os" + eq + qq + os + qq
1324 if os == "android":
1325 skip_if += aa + "android_version" + eq + qq + os_version + qq
1326 else:
1327 skip_if += aa + "os_version" + eq + qq + os_version + qq
1328
1329 processor = extra.arch
1330 if skip_if is not None and kind != Kind.LIST:
1331 # Rosetta specific hack for macos 11.20
1332 if (
1333 extra.os == "mac"
1334 and extra.os_version == "11.20"
1335 and processor == "aarch64"
1336 ):
1337 skip_if += aa + "arch" + eq + qq + processor + qq
1338 elif processor is not None:
1339 skip_if += aa + "processor" + eq + qq + processor + qq
1340
1341 failure_key = os + os_version + processor + manifest + file_path
1342 if self.failed_platforms.get(failure_key) is None:
1343 if not self.platform_permutations:
1344 self._fetch_platform_permutations()
1345 permutations = (
1346 self.platform_permutations.get(manifest, {})
1347 .get(os, {})
1348 .get(os_version, {})
1349 .get(processor, None)
1350 )
1351
1352 self.failed_platforms[failure_key] = FailedPlatform(permutations)
1353
1354 build_types = extra.build_type
1355 skip_cond = self.failed_platforms[failure_key].get_skip_string(
1356 aa, build_types, extra.test_variant
1357 )
1358 if kind == Kind.WPT:
1359 # ensure ! -> 'not', primarily fission and e10s
1360 skip_cond = skip_cond.replace("!", "not ")
1361 skip_if += skip_cond
1362 return skip_if
1363
1364 def get_file_info(self, path, product="Testing", component="General"):
1365 """
1366 Get bugzilla product and component for the path.
1367 Provide defaults (in case command_context is not defined
1368 or there isn't file info available).
1369 """
1370 if path != DEF and self.command_context is not None:
1371 reader = self.command_context.mozbuild_reader(config_mode="empty")
1372 info = reader.files_info([path])
1373 cp = info[path]["BUG_COMPONENT"]
1374 product = cp.product
1375 component = cp.component
1376 return product, component
1377
1378 def get_filename_in_manifest(self, manifest: str, path: str) -> str:
1379 """return relative filename for path in manifest"""
1380
1381 filename = os.path.basename(path)
1382 if filename == DEF:
1383 return filename
1384 manifest_dir = os.path.dirname(manifest)
1385 i = 0
1386 j = min(len(manifest_dir), len(path))
1387 while i < j and manifest_dir[i] == path[i]:
1388 i += 1
1389 if i < len(manifest_dir):
1390 for _ in range(manifest_dir.count("/", i) + 1):
1391 filename = "../" + filename
1392 elif i < len(path):
1393 filename = path[i + 1 :]
1394 return filename
1395
1396 def get_push_id(self, revision, repo):
1397 """Return the push_id for revision and repo (or None)"""
1398
1399 self.vinfo(f"Retrieving push_id for {repo} revision: {revision} ...")
1400 if revision in self.push_ids: # if cached
1401 push_id = self.push_ids[revision]
1402 else:
1403 push_id = None
1404 push_url = f"https://treeherder.mozilla.org/api/project/{repo}/push/"
1405 params = {}
1406 params["full"] = "true"
1407 params["count"] = 10
1408 params["revision"] = revision
1409 r = requests.get(push_url, headers=self.headers, params=params)
1410 if r.status_code != 200:
1411 self.warning(f"FAILED to query Treeherder = {r} for {r.url}")
1412 else:
1413 response = r.json()
1414 if "results" in response:
1415 results = response["results"]
1416 if len(results) > 0:
1417 r0 = results[0]
1418 if "id" in r0:
1419 push_id = r0["id"]
1420 self.push_ids[revision] = push_id
1421 return push_id
1422
1423 def get_job_id(self, push_id, task_id):
1424 """Return the job_id for push_id, task_id (or None)"""
1425
1426 self.vinfo(f"Retrieving job_id for push_id: {push_id}, task_id: {task_id} ...")
1427 k = f"{push_id}:{task_id}"
1428 if k in self.job_ids: # if cached
1429 job_id = self.job_ids[k]
1430 else:
1431 job_id = None
1432 params = {}
1433 params["push_id"] = push_id
1434 r = requests.get(self.jobs_url, headers=self.headers, params=params)
1435 if r.status_code != 200:
1436 self.warning(f"FAILED to query Treeherder = {r} for {r.url}")
1437 else:
1438 response = r.json()
1439 if "results" in response:
1440 results = response["results"]
1441 if len(results) > 0:
1442 for result in results:
1443 if len(result) > 14:
1444 if result[14] == task_id:
1445 job_id = result[1]
1446 break
1447 self.job_ids[k] = job_id
1448 return job_id
1449
1450 def get_bug_suggestions(self, repo, job_id, path, anyjs=None):
1451 """
1452 Return the (suggestions_url, line_number, line, log_url)
1453 for the given repo and job_id
1454 """
1455 self.vinfo(
1456 f"Retrieving bug_suggestions for {repo} job_id: {job_id}, path: {path} ..."
1457 )
1458 suggestions_url = f"https://treeherder.mozilla.org/api/project/{repo}/jobs/{job_id}/bug_suggestions/"
1459 line_number = None
1460 line = None
1461 log_url = None
1462 r = requests.get(suggestions_url, headers=self.headers)
1463 if r.status_code != 200:
1464 self.warning(f"FAILED to query Treeherder = {r} for {r.url}")
1465 else:
1466 if anyjs is not None:
1467 pathdir = os.path.dirname(path) + "/"
1468 paths = [pathdir + f for f in anyjs.keys()]
1469 else:
1470 paths = [path]
1471 response = r.json()
1472 if len(response) > 0:
1473 for sugg in response:
1474 for p in paths:
1475 path_end = sugg.get("path_end", None)
1476 # handles WPT short paths
1477 if path_end is not None and p.endswith(path_end):
1478 line_number = sugg["line_number"] + 1
1479 line = sugg["search"]
1480 log_url = f"https://treeherder.mozilla.org/logviewer?repo={repo}&job_id={job_id}&lineNumber={line_number}"
1481 break
1482 rv = (suggestions_url, line_number, line, log_url)
1483 return rv
1484
1485 def read_json(self, filename):
1486 """read data as JSON from filename"""
1487
1488 fp = open(filename, encoding="utf-8")
1489 data = json.load(fp)
1490 fp.close()
1491 return data
1492
1493 def read_tasks(self, filename):
1494 """read tasks as JSON from filename"""
1495
1496 if not os.path.exists(filename):
1497 msg = f"use-tasks JSON file does not exist: {filename}"
1498 raise OSError(2, msg, filename)
1499 tasks = self.read_json(filename)
1500 tasks = [Mock(task, MOCK_TASK_DEFAULTS, MOCK_TASK_INITS) for task in tasks]
1501 for task in tasks:
1502 if len(task.extra) > 0: # pre-warm cache for extra information
1503 platform_info = PlatformInfo()
1504 extra: Any = task.extra
1505 platform_info.from_dict(extra)
1506 self.extras[task.id] = platform_info
1507 return tasks
1508
1509 def read_failures(self, filename):
1510 """read failures as JSON from filename"""
1511
1512 if not os.path.exists(filename):
1513 msg = f"use-failures JSON file does not exist: {filename}"
1514 raise OSError(2, msg, filename)
1515 failures = self.read_json(filename)
1516 return failures
1517
1518 def read_bugs(self, filename):
1519 """read bugs as JSON from filename"""
1520
1521 if not os.path.exists(filename):
1522 msg = f"bugs JSON file does not exist: {filename}"
1523 raise OSError(2, msg, filename)
1524 bugs = self.read_json(filename)
1525 bugs = [Mock(bug, MOCK_BUG_DEFAULTS) for bug in bugs]
1526 return bugs
1527
1528 def write_json(self, filename, data):
1529 """saves data as JSON to filename"""
1530 fp = open(filename, "w", encoding="utf-8")
1531 json.dump(data, fp, indent=2, sort_keys=True)
1532 fp.close()
1533
1534 def write_tasks(self, save_tasks, tasks):
1535 """saves tasks as JSON to save_tasks"""
1536 jtasks = []
1537 for task in tasks:
1538 if not isinstance(task, TestTask):
1539 continue
1540 jtask = {}
1541 jtask["id"] = task.id
1542 jtask["label"] = task.label
1543 jtask["duration"] = task.duration
1544 jtask["result"] = task.result
1545 jtask["state"] = task.state
1546 jtask["extra"] = self.get_extra(task.id).to_dict()
1547 jtags = {}
1548 for k, v in task.tags.items():
1549 if k == "createdForUser":
1550 jtags[k] = "[email protected]"
1551 else:
1552 jtags[k] = v
1553 jtask["tags"] = jtags
1554 jtask["tier"] = task.tier
1555 jtask["results"] = [
1556 {"group": r.group, "ok": r.ok, "duration": r.duration}
1557 for r in task.results
1558 ]
1559 jtask["errors"] = None # Bug with task.errors property??
1560 jft = {}
1561 if self.failure_types is not None and task.id in self.failure_types:
1562 failure_types = self.failure_types[task.id] # use cache
1563 else:
1564 try:
1565 failure_types = task.failure_types
1566 except requests.exceptions.HTTPError:
1567 continue
1568 except TaskclusterRestFailure:
1569 continue
1570 for k in failure_types:
1571 jft[k] = [[f[0], f[1].value] for f in task.failure_types[k]]
1572 jtask["failure_types"] = jft
1573 jtasks.append(jtask)
1574 self.write_json(save_tasks, jtasks)
1575
1576 def label_to_platform_testname(self, label):
1577 """convert from label to platform, testname for mach command line"""
1578 platform = None
1579 testname = None
1580 platform_details = label.split("/")
1581 if len(platform_details) == 2:
1582 platform, details = platform_details
1583 words = details.split("-")
1584 if len(words) > 2:
1585 platform += "/" + words.pop(0) # opt or debug
1586 try:
1587 _chunk = int(words[-1])
1588 words.pop()
1589 except ValueError:
1590 pass
1591 words.pop() # remove test suffix
1592 testname = "-".join(words)
1593 else:
1594 platform = None
1595 return platform, testname
1596
1597 def add_attachment_log_for_task(self, bugid, task_id):
1598 """Adds compressed log for this task to bugid"""
1599
1600 log_url = f"https://firefox-ci-tc.services.mozilla.com/api/queue/v1/task/{task_id}/artifacts/public/logs/live_backing.log"
1601 r = requests.get(log_url, headers=self.headers)
1602 if r.status_code != 200:
1603 self.error(f"Unable to get log for task: {task_id}")
1604 return
1605 attach_fp = tempfile.NamedTemporaryFile()
1606 fp = gzip.open(attach_fp, "wb")
1607 fp.write(r.text.encode("utf-8"))
1608 fp.close()
1609 if self._initialize_bzapi():
1610 description = ATTACHMENT_DESCRIPTION + task_id
1611 file_name = TASK_LOG + ".gz"
1612 comment = "Added compressed log"
1613 content_type = "application/gzip"
1614 try:
1615 self._bzapi.attachfile(
1616 [bugid],
1617 attach_fp.name,
1618 description,
1619 file_name=file_name,
1620 comment=comment,
1621 content_type=content_type,
1622 is_private=False,
1623 )
1624 except Fault:
1625 pass # Fault expected: Failed to fetch key 9372091 from network storage: The specified key does not exist.
1626
1627 def get_wpt_path_meta(self, shortpath: str):
1628 if shortpath.startswith(WPT0):
1629 path = shortpath
1630 meta = shortpath.replace(WPT0, WPT_META0, 1)
1631 elif shortpath.startswith(WPT1):
1632 path = shortpath
1633 meta = shortpath.replace(WPT1, WPT_META1, 1)
1634 elif shortpath.startswith(WPT2):
1635 path = shortpath
1636 meta = shortpath.replace(WPT2, WPT_META2, 1)
1637 elif shortpath.startswith(WPT_MOZILLA):
1638 shortpath = shortpath[len(WPT_MOZILLA) :]
1639 path = WPT2 + shortpath
1640 meta = WPT_META2 + shortpath
1641 else:
1642 path = WPT1 + shortpath
1643 meta = WPT_META1 + shortpath
1644 return (path, meta)
1645
1646 def wpt_paths(
1647 self, shortpath: str
1648 ) -> Tuple[Optional[str], Optional[str], Optional[str], Optional[str]]:
1649 """
1650 Analyzes the WPT short path for a test and returns
1651 (path, manifest, query, anyjs) where
1652 path is the relative path to the test file
1653 manifest is the relative path to the file metadata
1654 query is the test file query paramters (or None)
1655 anyjs is the html test file as reported by mozci (or None)
1656 """
1657 query: Optional[str] = None
1658 anyjs: Optional[str] = None
1659 i = shortpath.find("?")
1660 if i > 0:
1661 query = shortpath[i:]
1662 shortpath = shortpath[0:i]
1663 path, manifest = self.get_wpt_path_meta(shortpath)
1664 failure_type = not self.isdir(path)
1665 if failure_type:
1666 i = path.find(".any.")
1667 if i > 0:
1668 anyjs = path # orig path
1669 manifest = manifest.replace(path[i:], ".any.js")
1670 path = path[0:i] + ".any.js"
1671 else:
1672 i = path.find(".window.")
1673 if i > 0:
1674 anyjs = path # orig path
1675 manifest = manifest.replace(path[i:], ".window.js")
1676 path = path[0:i] + ".window.js"
1677 else:
1678 i = path.find(".worker.")
1679 if i > 0:
1680 anyjs = path # orig path
1681 manifest = manifest.replace(path[i:], ".worker.js")
1682 path = path[0:i] + ".worker.js"
1683 manifest += ".ini"
1684 manifest_classic = ""
1685 if manifest.startswith(WPT_META0):
1686 manifest_classic = manifest.replace(WPT_META0, WPT_META0_CLASSIC, 1)
1687 if self.exists(manifest_classic):
1688 if self.exists(manifest):
1689 self.warning(
1690 f"Both classic {manifest_classic} and metadata {manifest} manifests exist"
1691 )
1692 else:
1693 self.warning(
1694 f"Using the classic {manifest_classic} manifest as the metadata manifest {manifest} does not exist"
1695 )
1696 manifest = manifest_classic
1697 if not self.exists(path):
1698 return (None, None, None, None)
1699 return (path, manifest, query, anyjs)
1700
1701 def wpt_add_skip_if(self, manifest_str, anyjs, skip_if, bug_reference):
1702 """
1703 Edits a WPT manifest string to add disabled condition
1704 anyjs is a dictionary mapping from filename and any alternate basenames to
1705 a boolean (indicating if the file has been handled in the manifest).
1706 Returns additional_comment (if any)
1707 """
1708
1709 additional_comment = ""
1710 disabled_key = False
1711 disabled = " disabled:"
1712 condition_start = " if "
1713 condition = condition_start + skip_if + ": " + bug_reference
1714 lines = manifest_str.splitlines()
1715 section = None # name of the section
1716 i = 0
1717 n = len(lines)
1718 while i < n:
1719 line = lines[i]
1720 if line.startswith("["):
1721 if section is not None and not anyjs[section]: # not yet handled
1722 if not disabled_key:
1723 lines.insert(i, disabled)
1724 i += 1
1725 lines.insert(i, condition)
1726 lines.insert(i + 1, "") # blank line after condition
1727 i += 2
1728 n += 2
1729 anyjs[section] = True
1730 section = line[1:-1]
1731 if section in anyjs and not anyjs[section]:
1732 disabled_key = False
1733 else:
1734 section = None # ignore section we are not interested in
1735 elif section is not None:
1736 if line == disabled:
1737 disabled_key = True
1738 elif line.startswith(" ["):
1739 if i > 0 and i - 1 < n and lines[i - 1] == "":
1740 del lines[i - 1]
1741 i -= 1
1742 n -= 1
1743 if not disabled_key:
1744 lines.insert(i, disabled)
1745 i += 1
1746 n += 1
1747 lines.insert(i, condition)
1748 lines.insert(i + 1, "") # blank line after condition
1749 i += 2
1750 n += 2
1751 anyjs[section] = True
1752 section = None
1753 elif line.startswith(" ") and not line.startswith(" "):
1754 if disabled_key: # insert condition above new key
1755 lines.insert(i, condition)
1756 i += 1
1757 n += 1
1758 anyjs[section] = True
1759 section = None
1760 disabled_key = False
1761 elif line.startswith(" "):
1762 if disabled_key and line == condition:
1763 anyjs[section] = True # condition already present
1764 section = None
1765 i += 1
1766 if section is not None and not anyjs[section]: # not yet handled
1767 if i > 0 and i - 1 < n and lines[i - 1] == "":
1768 del lines[i - 1]
1769 if not disabled_key:
1770 lines.append(disabled)
1771 i += 1
1772 n += 1
1773 lines.append(condition)
1774 lines.append("") # blank line after condition
1775 i += 2
1776 n += 2
1777 anyjs[section] = True
1778 for section in anyjs:
1779 if not anyjs[section]:
1780 if i > 0 and i - 1 < n and lines[i - 1] != "":
1781 lines.append("") # blank line before condition
1782 i += 1
1783 n += 1
1784 lines.append("[" + section + "]")
1785 lines.append(disabled)
1786 lines.append(condition)
1787 lines.append("") # blank line after condition
1788 i += 4
1789 n += 4
1790 manifest_str = "\n".join(lines) + "\n"
1791 return manifest_str, additional_comment
1792
1793 def reftest_add_fuzzy_if(
1794 self,
1795 manifest_str,
1796 filename,
1797 fuzzy_if,
1798 differences,
1799 pixels,
1800 lineno,
1801 zero,
1802 bug_reference,
1803 ):
1804 """
1805 Edits a reftest manifest string to add disabled condition
1806 """
1807
1808 if self.lmp is None:
1809 from parse_reftest import ListManifestParser
1810
1811 self.lmp = ListManifestParser(
1812 self.implicit_vars, self.verbose, self.error, self.warning, self.info
1813 )
1814 manifest_str, additional_comment = self.lmp.reftest_add_fuzzy_if(
1815 manifest_str,
1816 filename,
1817 fuzzy_if,
1818 differences,
1819 pixels,
1820 lineno,
1821 zero,
1822 bug_reference,
1823 )
1824 return manifest_str, additional_comment
1825
1826 def get_lineno_difference_pixels_status(self, task_id, manifest, allmods):
1827 """
1828 Returns
1829 - lineno in manifest
1830 - image comparison, max *difference*
1831 - number of differing *pixels*
1832 - status (PASS or FAIL)
1833 as cached from reftest_errorsummary.log for a task
1834 """
1835 manifest_obj = self.error_summary.get(manifest, {})
1836 # allmods_obj: manifest_test_name: {test: allmods, error: ...}
1837 allmods_obj = manifest_obj[
1838 [am for am in manifest_obj if manifest_obj[am]["test"].endswith(allmods)][0]
1839 ]
1840 lineno = allmods_obj.get(LINENO, 0)
1841 runs_obj = allmods_obj.get(RUNS, {})
1842 task_obj = runs_obj.get(task_id, {})
1843 difference = task_obj.get(DIFFERENCE, 0)
1844 pixels = task_obj.get(PIXELS, 0)
1845 status = task_obj.get(STATUS, FAIL)
1846 return lineno, difference, pixels, status
1847
1848 def reftest_find_lineno(self, manifest, modifiers, allmods):
1849 """
1850 Return the line number with modifiers in manifest (else 0)
1851 """
1852
1853 lineno = 0
1854 mods = []
1855 prefs = []
1856 for i in range(len(modifiers)):
1857 if modifiers[i].find("pref(") >= 0 or modifiers[i].find("skip-if(") >= 0:
1858 prefs.append(modifiers[i])
1859 else:
1860 mods.append(modifiers[i])
1861 m = len(mods)
1862 manifest_str = open(manifest, encoding="utf-8").read()
1863 lines = manifest_str.splitlines()
1864 defaults = []
1865 found = False
1866 alt_lineno = 0
1867 for linenum in range(len(lines)):
1868 line = lines[linenum]
1869 if len(line) > 0 and line[0] == "#":
1870 continue
1871 comment_start = line.find(" #") # MUST NOT match anchors!
1872 if comment_start > 0:
1873 line = line[0:comment_start].strip()
1874 words = line.split()
1875 n = len(words)
1876 if n > 1 and words[0] == "defaults":
1877 defaults = words[1:].copy()
1878 continue
1879 line_defaults = defaults.copy()
1880 i = 0
1881 while i < n:
1882 if words[i].find("pref(") >= 0 or words[i].find("skip-if(") >= 0:
1883 line_defaults.append(words[i])
1884 del words[i]
1885 n -= 1
1886 else:
1887 i += 1
1888 if (len(prefs) == 0 or prefs == line_defaults) and words == mods:
1889 found = True
1890 lineno = linenum + 1
1891 break
1892 elif m > 2 and n > 2:
1893 if words[-3:] == mods[-3:]:
1894 alt_lineno = linenum + 1
1895 else:
1896 bwords = [os.path.basename(f) for f in words[-2:]]
1897 bmods = [os.path.basename(f) for f in mods[-2:]]
1898 if bwords == bmods:
1899 alt_lineno = linenum + 1
1900 if not found:
1901 if alt_lineno > 0:
1902 lineno = alt_lineno
1903 self.warning(
1904 f"manifest '{manifest}' found lineno: {lineno}, but it does not contain all the prefs from modifiers,\nSEARCH: {allmods}\nFOUND : {lines[alt_lineno - 1]}"
1905 )
1906 else:
1907 lineno = 0
1908 self.error(
1909 f"manifest '{manifest}' does not contain line with modifiers: {allmods}"
1910 )
1911 return lineno
1912
1913 def get_allpaths(self, task_id, manifest, path):
1914 """
1915 Looks up the reftest_errorsummary.log for a task
1916 and caches the details in self.error_summary by
1917 task_id, manifest, allmods
1918 where allmods is the concatenation of all modifiers
1919 and the details include
1920 - image comparison, max *difference*
1921 - number of differing *pixels*
1922 - status: unexpected PASS or FAIL
1923
1924 The list iof unique modifiers (allmods) for the given path are returned
1925 """
1926
1927 allpaths = []
1928 words = path.split()
1929 if len(words) != 3 or words[1] not in TEST_TYPES:
1930 self.warning(
1931 f"reftest_errorsummary.log for task: {task_id} has unsupported test type '{path}'"
1932 )
1933 return allpaths
1934 if manifest in self.error_summary:
1935 for allmods in self.error_summary[manifest]:
1936 if self.error_summary[manifest][allmods][
1937 TEST
1938 ] == path and task_id in self.error_summary[manifest][allmods].get(
1939 RUNS, {}
1940 ):
1941 allpaths.append(path)
1942 if len(allpaths) > 0:
1943 return allpaths # cached (including self tests)
1944 error_url = f"https://firefox-ci-tc.services.mozilla.com/api/queue/v1/task/{task_id}/artifacts/public/test_info/reftest_errorsummary.log"
1945 self.vinfo(f"Requesting reftest_errorsummary.log for task: {task_id}")
1946 r = requests.get(error_url, headers=self.headers)
1947 if r.status_code != 200:
1948 self.error(f"Unable to get reftest_errorsummary.log for task: {task_id}")
1949 return allpaths
1950 for line in r.text.encode("utf-8").splitlines():
1951 summary = json.loads(line)
1952 group = summary.get(GROUP, "")
1953 if not group or not os.path.exists(group): # not error line
1954 continue
1955 test = summary.get(TEST, None)
1956 if test is None:
1957 continue
1958 if not MODIFIERS in summary:
1959 self.warning(
1960 f"reftest_errorsummary.log for task: {task_id} does not have modifiers for '{test}'"
1961 )
1962 continue
1963 words = test.split()
1964 if len(words) != 3 or words[1] not in TEST_TYPES:
1965 self.warning(
1966 f"reftest_errorsummary.log for task: {task_id} has unsupported test '{test}'"
1967 )
1968 continue
1969 status = summary.get(STATUS, "")
1970 if status not in [FAIL, PASS]:
1971 self.warning(
1972 f"reftest_errorsummary.log for task: {task_id} has unknown status: {status} for '{test}'"
1973 )
1974 continue
1975 error = summary.get(SUBTEST, "")
1976 mods = summary[MODIFIERS]
1977 allmods = " ".join(mods)
1978 if group not in self.error_summary:
1979 self.error_summary[group] = {}
1980 if allmods not in self.error_summary[group]:
1981 self.error_summary[group][allmods] = {}
1982 self.error_summary[group][allmods][TEST] = test
1983 lineno = self.error_summary[group][allmods].get(LINENO, 0)
1984 if lineno == 0:
1985 lineno = self.reftest_find_lineno(group, mods, allmods)
1986 if lineno > 0:
1987 self.error_summary[group][allmods][LINENO] = lineno
1988 if RUNS not in self.error_summary[group][allmods]:
1989 self.error_summary[group][allmods][RUNS] = {}
1990 if task_id not in self.error_summary[group][allmods][RUNS]:
1991 self.error_summary[group][allmods][RUNS][task_id] = {}
1992 self.error_summary[group][allmods][RUNS][task_id][ERROR] = error
1993 if self._subtest_rx is None:
1994 self._subtest_rx = re.compile(SUBTEST_REGEX)
1995 m = self._subtest_rx.findall(error)
1996 if len(m) == 1:
1997 difference = int(m[0][0])
1998 pixels = int(m[0][1])
1999 else:
2000 difference = 0
2001 pixels = 0
2002 if difference > 0:
2003 self.error_summary[group][allmods][RUNS][task_id][
2004 DIFFERENCE
2005 ] = difference
2006 if pixels > 0:
2007 self.error_summary[group][allmods][RUNS][task_id][PIXELS] = pixels
2008 if status != FAIL:
2009 self.error_summary[group][allmods][RUNS][task_id][STATUS] = status
2010 if test == path:
2011 allpaths.append(test)
2012 return allpaths