• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mozilla / relman-auto-nag / #4617

pending completion
#4617

push

coveralls-python

suhaibmujahid
Highlight crash address commonalities

646 of 3428 branches covered (18.84%)

40 of 40 new or added lines in 1 file covered. (100.0%)

1828 of 8530 relevant lines covered (21.43%)

0.21 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/bugbot/crash/analyzer.py
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 file,
3
# You can obtain one at http://mozilla.org/MPL/2.0/.
4

5
import itertools
×
6
import re
×
7
from collections import defaultdict
×
8
from datetime import date, timedelta
×
9
from functools import cached_property
×
10
from typing import Iterable, Iterator
×
11

12
from libmozdata import bugzilla, clouseau, connection, socorro
×
13
from libmozdata import utils as lmdutils
×
14
from libmozdata.bugzilla import Bugzilla
×
15
from libmozdata.connection import Connection
×
16

17
from bugbot import logger, utils
×
18
from bugbot.components import ComponentName
×
19
from bugbot.crash import socorro_util
×
20

21
# Allocator poison value addresses.
22
ALLOCATOR_ADDRESSES_64_BIT = (
×
23
    0xE5E5E5E5E5E5E5E5,
24
    0x4B4B4B4B4B4B4B4B,
25
)
26
ALLOCATOR_ADDRESSES_32_BIT = (
×
27
    0xE5E5E5E5,
28
    0x4B4B4B4B,
29
)
30
# The max offset from a memory address to be considered "near".
31
OFFSET_64_BIT = 0x1000
×
32
OFFSET_32_BIT = 0x100
×
33
# Ranges where addresses are considered near allocator poison values.
34
ALLOCATOR_RANGES_64_BIT = (
×
35
    (addr - OFFSET_64_BIT, addr + OFFSET_64_BIT) for addr in ALLOCATOR_ADDRESSES_64_BIT
36
)
37
ALLOCATOR_RANGES_32_BIT = (
×
38
    (addr - OFFSET_32_BIT, addr + OFFSET_32_BIT) for addr in ALLOCATOR_ADDRESSES_32_BIT
39
)
40

41

42
def is_near_null_address(str_address) -> bool:
×
43
    """Check if the address is near the null address.
44

45
    Args:
46
        str_address: The memory address to check.
47

48
    Returns:
49
        True if the address is near the null address, False otherwise.
50
    """
51
    address = int(str_address, 0)
×
52
    is_64_bit = len(str_address) >= 18
×
53

54
    if is_64_bit:
×
55
        return -OFFSET_64_BIT <= address <= OFFSET_64_BIT
×
56

57
    return -OFFSET_32_BIT <= address <= OFFSET_32_BIT
×
58

59

60
def is_near_allocator_address(str_address) -> bool:
×
61
    """Check if the address is near the allocator address.
62

63
    Args:
64
        str_address: The memory address to check.
65

66
    Returns:
67
        True if the address is near the allocator address, False otherwise.
68
    """
69
    address = int(str_address, 0)
×
70
    is_64_bit = len(str_address) >= 18
×
71

72
    return any(
×
73
        low <= address <= high
74
        for low, high in (
75
            ALLOCATOR_RANGES_64_BIT if is_64_bit else ALLOCATOR_RANGES_32_BIT
76
        )
77
    )
78

79

80
# TODO: Move this to libmozdata
81
def generate_signature_page_url(params: dict, tab: str) -> str:
×
82
    """Generate a URL to the signature page on Socorro
83

84
    Args:
85
        params: the parameters for the search query.
86
        tab: the page tab that should be selected.
87

88
    Returns:
89
        The URL of the signature page on Socorro
90
    """
91
    web_url = socorro.Socorro.CRASH_STATS_URL
×
92
    query = lmdutils.get_params_for_url(params)
×
93
    return f"{web_url}/signature/{query}#{tab}"
×
94

95

96
# NOTE: At this point, we will file bugs on bugzilla-dev. Once we are confident
97
# that the bug filing is working as expected, we can switch to filing bugs in
98
# the production instance of Bugzilla.
99
class DevBugzilla(Bugzilla):
×
100
    URL = "https://bugzilla-dev.allizom.org"
×
101
    API_URL = URL + "/rest/bug"
×
102
    ATTACHMENT_API_URL = API_URL + "/attachment"
×
103
    TOKEN = utils.get_login_info()["bz_api_key_dev"]
×
104

105

106
class NoCrashReportFoundError(Exception):
×
107
    """There are no crash reports that meet the required criteria."""
108

109

110
class ClouseauDataAnalyzer:
×
111
    """Analyze the data returned by Crash Clouseau"""
112

113
    MINIMUM_CLOUSEAU_SCORE_THRESHOLD: int = 8
×
114
    DEFAULT_CRASH_COMPONENT = ComponentName("Core", "General")
×
115

116
    def __init__(self, reports: Iterable[dict]):
×
117
        self._clouseau_reports = reports
×
118

119
    @cached_property
×
120
    def max_clouseau_score(self):
×
121
        """The maximum Clouseau score in the crash reports."""
122
        if not self._clouseau_reports:
×
123
            return 0
×
124
        return max(report["max_score"] for report in self._clouseau_reports)
×
125

126
    @cached_property
×
127
    def regressed_by_potential_bug_ids(self) -> set[int]:
×
128
        """The IDs for the bugs that their patches could have caused the crash."""
129
        minimum_accepted_score = max(
×
130
            self.MINIMUM_CLOUSEAU_SCORE_THRESHOLD, self.max_clouseau_score
131
        )
132
        return {
×
133
            changeset["bug_id"]
134
            for report in self._clouseau_reports
135
            if report["max_score"] >= minimum_accepted_score
136
            for changeset in report["changesets"]
137
            if changeset["max_score"] >= minimum_accepted_score
138
            and not changeset["is_merge"]
139
            and not changeset["is_backedout"]
140
        }
141

142
    @cached_property
×
143
    def regressed_by_patch(self) -> str | None:
×
144
        """The hash of the patch that could have caused the crash."""
145
        minimum_accepted_score = max(
×
146
            self.MINIMUM_CLOUSEAU_SCORE_THRESHOLD, self.max_clouseau_score
147
        )
148
        potential_patches = {
×
149
            changeset["changeset"]
150
            for report in self._clouseau_reports
151
            if report["max_score"] >= minimum_accepted_score
152
            for changeset in report["changesets"]
153
            if changeset["max_score"] >= minimum_accepted_score
154
            and not changeset["is_merge"]
155
            and not changeset["is_backedout"]
156
        }
157
        if len(potential_patches) == 1:
×
158
            return next(iter(potential_patches))
×
159
        return None
×
160

161
    @cached_property
×
162
    def regressed_by(self) -> int | None:
×
163
        """The ID of the bug that one of its patches could have caused
164
        the crash.
165

166
        If there are multiple bugs, the value will be `None`.
167
        """
168
        bug_ids = self.regressed_by_potential_bug_ids
×
169
        if len(bug_ids) == 1:
×
170
            return next(iter(bug_ids))
×
171
        return None
×
172

173
    @cached_property
×
174
    def regressed_by_potential_bugs(self) -> list[dict]:
×
175
        """The bugs whose patches could have caused the crash."""
176

177
        def handler(bug: dict, data: list):
×
178
            data.append(bug)
×
179

180
        bugs: list[dict] = []
×
181
        Bugzilla(
×
182
            bugids=self.regressed_by_potential_bug_ids,
183
            include_fields=[
184
                "id",
185
                "assigned_to",
186
                "product",
187
                "component",
188
            ],
189
            bughandler=handler,
190
            bugdata=bugs,
191
        ).wait()
192

193
        return bugs
×
194

195
    @cached_property
×
196
    def regressed_by_author(self) -> dict | None:
×
197
        """The author of the patch that could have caused the crash.
198

199
        If there are multiple regressors, the value will be `None`.
200

201
        The regressor bug assignee is considered as the author, even if the
202
        assignee is not the patch author.
203
        """
204

205
        if not self.regressed_by:
×
206
            return None
×
207

208
        bug = self.regressed_by_potential_bugs[0]
×
209
        assert bug["id"] == self.regressed_by
×
210
        return bug["assigned_to_detail"]
×
211

212
    @cached_property
×
213
    def crash_component(self) -> ComponentName:
×
214
        """The component that the crash belongs to.
215

216
        If there are multiple components, the value will be the default one.
217
        """
218
        potential_components = {
×
219
            ComponentName(bug["product"], bug["component"])
220
            for bug in self.regressed_by_potential_bugs
221
        }
222
        if len(potential_components) == 1:
×
223
            return next(iter(potential_components))
×
224
        return self.DEFAULT_CRASH_COMPONENT
×
225

226

227
class SocorroDataAnalyzer(socorro_util.SignatureStats):
×
228
    """Analyze the data returned by Socorro."""
229

230
    _bugzilla_os_legal_values = None
×
231
    _bugzilla_cpu_legal_values_map = None
×
232
    _platforms = [
×
233
        {"short_name": "win", "name": "Windows"},
234
        {"short_name": "mac", "name": "Mac OS X"},
235
        {"short_name": "lin", "name": "Linux"},
236
        {"short_name": "and", "name": "Android"},
237
        {"short_name": "unknown", "name": "Unknown"},
238
    ]
239

240
    def __init__(
×
241
        self,
242
        signature: dict,
243
        num_total_crashes: int,
244
    ):
245
        super().__init__(signature, num_total_crashes, platforms=self._platforms)
×
246

247
    @classmethod
×
248
    def to_bugzilla_op_sys(cls, op_sys: str) -> str:
×
249
        """Return the corresponding OS name in Bugzilla for the provided OS name
250
        from Socorro.
251

252
        If the OS name is not recognized, return "Other".
253
        """
254
        if cls._bugzilla_os_legal_values is None:
×
255
            cls._bugzilla_os_legal_values = set(
×
256
                bugzilla.BugFields.fetch_field_values("op_sys")
257
            )
258

259
        if op_sys in cls._bugzilla_os_legal_values:
×
260
            return op_sys
×
261

262
        if op_sys.startswith("OS X ") or op_sys.startswith("macOS "):
×
263
            op_sys = "macOS"
×
264
        elif op_sys.startswith("Windows"):
×
265
            op_sys = "Windows"
×
266
        elif "Linux" in op_sys or op_sys.startswith("Ubuntu"):
×
267
            op_sys = "Linux"
×
268
        else:
269
            op_sys = "Other"
×
270

271
        return op_sys
×
272

273
    @property
×
274
    def bugzilla_op_sys(self) -> str:
×
275
        """The name of the OS where the crash happens.
276

277
        The value is one of the legal values for Bugzilla's `op_sys` field.
278

279
        - If no OS name is found, the value will be "Unspecified".
280
        - If the OS name is not recognized, the value will be "Other".
281
        - If multiple OS names are found, the value will be "All". Unless the OS
282
          names can be resolved to a common name without a version. For example,
283
          "Windows 10" and "Windows 7" will become "Windows".
284
        """
285
        all_op_sys = {
×
286
            self.to_bugzilla_op_sys(op_sys["term"])
287
            for op_sys in self.signature["facets"]["platform_pretty_version"]
288
        }
289

290
        if len(all_op_sys) > 1:
×
291
            # Resolve to root OS name by removing the version number.
292
            all_op_sys = {op_sys.split(" ")[0] for op_sys in all_op_sys}
×
293

294
        if len(all_op_sys) == 2 and "Other" in all_op_sys:
×
295
            # TODO: explain this workaround.
296
            all_op_sys.remove("Other")
×
297

298
        if len(all_op_sys) == 1:
×
299
            return next(iter(all_op_sys))
×
300

301
        if len(all_op_sys) == 0:
×
302
            return "Unspecified"
×
303

304
        return "All"
×
305

306
    @classmethod
×
307
    def to_bugzilla_cpu(cls, cpu: str) -> str:
×
308
        """Return the corresponding CPU name in Bugzilla for the provided name
309
        from Socorro.
310

311
        If the CPU is not recognized, return "Other".
312
        """
313
        if cls._bugzilla_cpu_legal_values_map is None:
×
314
            cls._bugzilla_cpu_legal_values_map = {
×
315
                value.lower(): value
316
                for value in bugzilla.BugFields.fetch_field_values("rep_platform")
317
            }
318

319
        return cls._bugzilla_cpu_legal_values_map.get(cpu, "Other")
×
320

321
    @property
×
322
    def bugzilla_cpu_arch(self) -> str:
×
323
        """The CPU architecture of the devices where the crash happens.
324

325
        The value is one of the legal values for Bugzilla's `rep_platform` field.
326

327
        - If no CPU architecture is found, the value will be "Unspecified".
328
        - If the CPU architecture is not recognized, the value will be "Other".
329
        - If multiple CPU architectures are found, the value will "All".
330
        """
331
        all_cpu_arch = {
×
332
            self.to_bugzilla_cpu(cpu["term"])
333
            for cpu in self.signature["facets"]["cpu_arch"]
334
        }
335

336
        if len(all_cpu_arch) == 2 and "Other" in all_cpu_arch:
×
337
            all_cpu_arch.remove("Other")
×
338

339
        if len(all_cpu_arch) == 1:
×
340
            return next(iter(all_cpu_arch))
×
341

342
        if len(all_cpu_arch) == 0:
×
343
            return "Unspecified"
×
344

345
        return "All"
×
346

347
    @property
×
348
    def user_comments_page_url(self) -> str:
×
349
        """The URL to the Signature page on Socorro where the Comments tab is
350
        selected.
351
        """
352
        start_date = date.today() - timedelta(weeks=26)
×
353
        params = {
×
354
            "signature": self.signature_term,
355
            "date": socorro.SuperSearch.get_search_date(start_date),
356
        }
357
        return generate_signature_page_url(params, "comments")
×
358

359
    @property
×
360
    def num_user_comments(self) -> int:
×
361
        """The number of crash reports with user comments."""
362
        # TODO: count useful/interesting user comments (e.g., exclude one word comments)
363
        return self.signature["facets"]["cardinality_user_comments"]["value"]
×
364

365
    @property
×
366
    def has_user_comments(self) -> bool:
×
367
        """Whether the crash signature has any reports with a user comment."""
368
        return self.num_user_comments > 0
×
369

370
    @property
×
371
    def top_proto_signature(self) -> str:
×
372
        """The proto signature that occurs the most."""
373
        return self.signature["facets"]["proto_signature"][0]["term"]
×
374

375
    @property
×
376
    def num_top_proto_signature_crashes(self) -> int:
×
377
        """The number of crashes for the most occurring proto signature."""
378
        return self.signature["facets"]["proto_signature"][0]["count"]
×
379

380
    def _build_ids(self) -> Iterator[int]:
×
381
        """Yields the build IDs where the crash occurred."""
382
        for build_id in self.signature["facets"]["build_id"]:
×
383
            yield build_id["term"]
×
384

385
    @property
×
386
    def top_build_id(self) -> int:
×
387
        """The build ID where most crashes occurred."""
388
        return self.signature["facets"]["build_id"][0]["term"]
×
389

390
    @cached_property
×
391
    def num_near_null_crashes(self) -> int:
×
392
        """The number of crashes that occurred near the null address."""
393
        return sum(
×
394
            address["count"]
395
            for address in self.signature["facets"]["address"]
396
            if is_near_null_address(address["term"])
397
        )
398

399
    @property
×
400
    def is_near_null_crash(self) -> bool:
×
401
        """Whether all crashes occurred near the null address."""
402
        return self.num_near_null_crashes == self.num_crashes
×
403

404
    @property
×
405
    def is_potential_near_null_crash(self) -> bool:
×
406
        """Whether the signature is a potential near null crash.
407

408
        The value will be True if some but not all crashes occurred near the
409
        null address.
410
        """
411
        return not self.is_near_null_crash and self.num_near_null_crashes > 0
×
412

413
    @property
×
414
    def is_near_null_related_crash(self) -> bool:
×
415
        """Whether the signature is related to near null crashes.
416

417
        The value will be True if any of the crashes occurred near the null
418
        address.
419
        """
420
        return self.is_near_null_crash or self.is_potential_near_null_crash
×
421

422
    @cached_property
×
423
    def num_near_allocator_crashes(self) -> int:
×
424
        """The number of crashes that occurred near an allocator address."""
425
        return sum(
×
426
            address["count"]
427
            for address in self.signature["facets"]["address"]
428
            if is_near_allocator_address(address["term"])
429
        )
430

431
    @property
×
432
    def is_near_allocator_crash(self) -> bool:
×
433
        """Whether all crashes occurred near an allocator address."""
434
        return self.num_near_allocator_crashes == self.num_crashes
×
435

436
    @property
×
437
    def is_potential_near_allocator_crash(self) -> bool:
×
438
        """Whether the signature is a potential near allocator crash.
439

440
        The value will be True if some but not all crashes occurred near an
441
        allocator address.
442
        """
443
        return not self.is_near_allocator_crash and self.num_near_allocator_crashes > 0
×
444

445
    @property
×
446
    def is_near_allocator_related_crash(self) -> bool:
×
447
        """Whether the signature is related to near allocator crashes.
448

449
        The value will be True if any of the crashes occurred near an allocator
450
        address.
451
        """
452
        return self.is_near_allocator_crash or self.is_potential_near_allocator_crash
×
453

454

455
class SignatureAnalyzer(SocorroDataAnalyzer, ClouseauDataAnalyzer):
×
456
    """Analyze the data related to a signature.
457

458
    This includes data from Socorro and Clouseau.
459
    """
460

461
    def __init__(
×
462
        self,
463
        socorro_signature: dict,
464
        num_total_crashes: int,
465
        clouseau_reports: list[dict],
466
    ):
467
        SocorroDataAnalyzer.__init__(self, socorro_signature, num_total_crashes)
×
468
        ClouseauDataAnalyzer.__init__(self, clouseau_reports)
×
469

470
    def _fetch_crash_reports(
×
471
        self,
472
        proto_signature: str,
473
        build_id: int | Iterable[int],
474
        limit: int = 1,
475
    ) -> Iterator[dict]:
476
        params = {
×
477
            "proto_signature": "=" + proto_signature,
478
            "build_id": build_id,
479
            "_columns": [
480
                "uuid",
481
            ],
482
            "_results_number": limit,
483
        }
484

485
        def handler(res: dict, data: dict):
×
486
            data.update(res)
×
487

488
        data: dict = {}
×
489
        socorro.SuperSearch(params=params, handler=handler, handlerdata=data).wait()
×
490

491
        yield from data["hits"]
×
492

493
    def fetch_representative_processed_crash(self) -> dict:
×
494
        """Fetch a processed crash to represent the signature.
495

496
        This could fetch multiple processed crashes and return the one that is
497
        most likely to be useful.
498
        """
499
        limit_to_top_proto_signature = (
×
500
            self.num_top_proto_signature_crashes / self.num_crashes > 0.6
501
        )
502

503
        reports = itertools.chain(
×
504
            # Reports with a higher score from clouseau are more likely to be
505
            # useful.
506
            sorted(
507
                self._clouseau_reports,
508
                key=lambda report: report["max_score"],
509
                reverse=True,
510
            ),
511
            # Next we try find reports from the top crashing build because they
512
            # are likely to be representative.
513
            self._fetch_crash_reports(self.top_proto_signature, self.top_build_id),
514
            self._fetch_crash_reports(self.top_proto_signature, self._build_ids()),
515
        )
516
        for report in reports:
×
517
            uuid = report["uuid"]
×
518
            processed_crash = socorro.ProcessedCrash.get_processed(uuid)[uuid]
×
519
            if (
×
520
                not limit_to_top_proto_signature
521
                or processed_crash["proto_signature"] == self.top_proto_signature
522
            ):
523
                # TODO(investigate): maybe we should check if the stack is
524
                # corrupted (ask gsvelto or willkg about how to detect that)
525
                return processed_crash
×
526

527
        raise NoCrashReportFoundError(
×
528
            f"No crash report found with the most frequent proto signature for {self.signature_term}."
529
        )
530

531

532
class SignaturesDataFetcher:
×
533
    """Fetch the data related to the given signatures."""
534

535
    MEMORY_ACCESS_ERROR_REASONS = (
×
536
        # On Windows:
537
        "EXCEPTION_ACCESS_VIOLATION_READ",
538
        "EXCEPTION_ACCESS_VIOLATION_WRITE",
539
        "EXCEPTION_ACCESS_VIOLATION_EXEC"
540
        # On Linux:
541
        "SIGSEGV / SEGV_MAPERR",
542
        "SIGSEGV / SEGV_ACCERR",
543
    )
544

545
    EXCLUDED_MOZ_REASON_STRINGS = (
×
546
        "MOZ_CRASH(OOM)",
547
        "MOZ_CRASH(Out of memory)",
548
        "out of memory",
549
        "Shutdown hanging",
550
        # TODO(investigate): do we need to exclude signatures that their reason
551
        # contains `[unhandlable oom]`?
552
        # Example: arena_t::InitChunk | arena_t::AllocRun | arena_t::MallocLarge | arena_t::Malloc | BaseAllocator::malloc | Allocator::malloc | PageMalloc
553
        # "[unhandlable oom]",
554
    )
555

556
    # If any of the crash reason starts with any of the following, then it is
557
    # Network or I/O error.
558
    EXCLUDED_IO_ERROR_REASON_PREFIXES = (
×
559
        "EXCEPTION_IN_PAGE_ERROR_READ",
560
        "EXCEPTION_IN_PAGE_ERROR_WRITE",
561
        "EXCEPTION_IN_PAGE_ERROR_EXEC",
562
    )
563

564
    # TODO(investigate): do we need to exclude all these signatures prefixes?
565
    EXCLUDED_SIGNATURE_PREFIXES = (
×
566
        "OOM | ",
567
        "bad hardware | ",
568
        "shutdownhang | ",
569
    )
570

571
    def __init__(
×
572
        self,
573
        signatures: Iterable[str],
574
        product: str = "Firefox",
575
        channel: str = "nightly",
576
    ):
577
        self._signatures = set(signatures)
×
578
        self._product = product
×
579
        self._channel = channel
×
580

581
    @classmethod
×
582
    def find_new_actionable_crashes(
×
583
        cls,
584
        product: str,
585
        channel: str,
586
        days_to_check: int = 7,
587
        days_without_crashes: int = 7,
588
    ) -> "SignaturesDataFetcher":
589
        """Find new actionable crashes.
590

591
        Args:
592
            product: The product to check.
593
            channel: The release channel to check.
594
            days_to_check: The number of days to check for crashes.
595
            days_without_crashes: The number of days without crashes before the
596
                `days_to_check` to consider the signature new.
597

598
        Returns:
599
            A list of actionable signatures.
600
        """
601
        duration = days_to_check + days_without_crashes
×
602
        end_date = lmdutils.get_date_ymd("today")
×
603
        start_date = end_date - timedelta(duration)
×
604
        earliest_allowed_date = lmdutils.get_date_str(
×
605
            end_date - timedelta(days_to_check)
606
        )
607
        date_range = socorro.SuperSearch.get_search_date(start_date, end_date)
×
608

609
        params = {
×
610
            "product": product,
611
            "release_channel": channel,
612
            "date": date_range,
613
            # TODO(investigate): should we do a local filter instead of the
614
            # following (should we exclude the signature if one of the crashes
615
            # is a shutdown hang?):
616
            # If the `ipc_shutdown_state` or `shutdown_progress` field are
617
            # non-empty then it's a shutdown hang.
618
            "ipc_shutdown_state": "__null__",
619
            "shutdown_progress": "__null__",
620
            # TODO(investigate): should we use the following instead of the
621
            # local filter.
622
            # "oom_allocation_size": "!__null__",
623
            "_aggs.signature": [
624
                "moz_crash_reason",
625
                "reason",
626
                "_histogram.date",
627
                "_cardinality.install_time",
628
                "_cardinality.oom_allocation_size",
629
            ],
630
            "_results_number": 0,
631
            "_facets_size": 10000,
632
        }
633

634
        def handler(search_resp: dict, data: list):
×
635
            logger.debug(
×
636
                "Total of %d signatures received from Socorro",
637
                len(search_resp["facets"]["signature"]),
638
            )
639

640
            for crash in search_resp["facets"]["signature"]:
×
641
                signature = crash["term"]
×
642
                if any(
×
643
                    signature.startswith(excluded_prefix)
644
                    for excluded_prefix in cls.EXCLUDED_SIGNATURE_PREFIXES
645
                ):
646
                    # Ignore signatures that start with any of the excluded prefixes.
647
                    continue
×
648

649
                facets = crash["facets"]
×
650
                installations = facets["cardinality_install_time"]["value"]
×
651
                if installations <= 1:
×
652
                    # Ignore crashes that only happen on one installation.
653
                    continue
×
654

655
                first_date = facets["histogram_date"][0]["term"]
×
656
                if first_date < earliest_allowed_date:
×
657
                    # The crash is not new, skip it.
658
                    continue
×
659

660
                if any(
×
661
                    reason["term"].startswith(io_error_prefix)
662
                    for reason in facets["reason"]
663
                    for io_error_prefix in cls.EXCLUDED_IO_ERROR_REASON_PREFIXES
664
                ):
665
                    # Ignore Network or I/O error crashes.
666
                    continue
×
667

668
                if crash["count"] < 20:
×
669
                    # For signatures with low volume, having multiple types of
670
                    # memory errors indicates potential bad hardware crashes.
671
                    num_memory_error_types = sum(
×
672
                        reason["term"] in cls.MEMORY_ACCESS_ERROR_REASONS
673
                        for reason in facets["reason"]
674
                    )
675
                    if num_memory_error_types > 1:
×
676
                        # Potential bad hardware crash, skip it.
677
                        continue
×
678

679
                # TODO: Add a filter using the `possible_bit_flips_max_confidence`
680
                # field to exclude bad hardware crashes. The filed is not available yet.
681
                # See: https://bugzilla.mozilla.org/show_bug.cgi?id=1816669#c3
682

683
                # TODO(investigate): is this needed since we are already
684
                # filtering signatures that start with "OOM | "
685
                if facets["cardinality_oom_allocation_size"]["value"]:
×
686
                    # If one of the crashes is an OOM crash, skip it.
687
                    continue
×
688

689
                # TODO(investigate): do we need to check for the `moz_crash_reason`
690
                moz_crash_reasons = facets["moz_crash_reason"]
×
691
                if moz_crash_reasons and any(
×
692
                    excluded_reason in reason["term"]
693
                    for reason in moz_crash_reasons
694
                    for excluded_reason in cls.EXCLUDED_MOZ_REASON_STRINGS
695
                ):
696
                    continue
×
697

698
                data.append(signature)
×
699

700
        signatures: list = []
×
701
        socorro.SuperSearch(
×
702
            params=params,
703
            handler=handler,
704
            handlerdata=signatures,
705
        ).wait()
706

707
        logger.debug(
×
708
            "Total of %d signatures left after applying the filtering criteria",
709
            len(signatures),
710
        )
711

712
        return cls(signatures, product, channel)
×
713

714
    def fetch_clouseau_crash_reports(self) -> dict[str, list]:
×
715
        """Fetch the crash reports data from Crash Clouseau."""
716
        signature_reports = clouseau.Reports.get_by_signatures(
×
717
            self._signatures,
718
            product=self._product,
719
            channel=self._channel,
720
        )
721

722
        logger.debug(
×
723
            "Total of %d signatures received from Clouseau", len(signature_reports)
724
        )
725

726
        return signature_reports
×
727

728
    def fetch_socorro_info(self) -> tuple[list[dict], int]:
×
729
        """Fetch the signature data from Socorro."""
730
        # TODO(investigate): should we increase the duration to 6 months?
731
        duration = timedelta(weeks=1)
×
732
        end_date = lmdutils.get_date_ymd("today")
×
733
        start_date = end_date - duration
×
734
        date_range = socorro.SuperSearch.get_search_date(start_date, end_date)
×
735

736
        params = {
×
737
            "product": self._product,
738
            # TODO(investigate): should we included all release channels?
739
            "release_channel": self._channel,
740
            # TODO(investigate): should we limit based on the build date as well?
741
            "date": date_range,
742
            # TODO: split signatures into chunks to avoid very long query URLs
743
            "signature": ["=" + signature for signature in self._signatures],
744
            "_aggs.signature": [
745
                "address",
746
                "build_id",
747
                "cpu_arch",
748
                "proto_signature",
749
                "_cardinality.user_comments",
750
                "cpu_arch",
751
                "platform_pretty_version",
752
                # The following are needed for SignatureStats:
753
                "platform",
754
                "is_garbage_collecting",
755
                "_cardinality.install_time",
756
                "startup_crash",
757
                "_histogram.uptime",
758
                "process_type",
759
            ],
760
            "_results_number": 0,
761
            "_facets_size": 10000,
762
        }
763

764
        def handler(search_results: dict, data: dict):
×
765
            data["num_total_crashes"] = search_results["total"]
×
766
            data["signatures"] = search_results["facets"]["signature"]
×
767

768
        data: dict = {}
×
769
        socorro.SuperSearchUnredacted(
×
770
            params=params,
771
            handler=handler,
772
            handlerdata=data,
773
        ).wait()
774

775
        logger.debug(
×
776
            "Fetch info from Socorro for %d signatures", len(data["signatures"])
777
        )
778

779
        return data["signatures"], data["num_total_crashes"]
×
780

781
    def fetch_bugs(self, include_fields: list[str] = None) -> dict[str, list[dict]]:
×
782
        """Fetch bugs that are filed against the given signatures."""
783

784
        params_base: dict = {
×
785
            "include_fields": [
786
                "cf_crash_signature",
787
            ],
788
        }
789

790
        if include_fields:
×
791
            params_base["include_fields"].extend(include_fields)
×
792

793
        params_list = []
×
794
        for signatures_chunk in Connection.chunks(list(self._signatures), 30):
×
795
            params = params_base.copy()
×
796
            n = int(utils.get_last_field_num(params))
×
797
            params[f"f{n}"] = "OP"
×
798
            params[f"j{n}"] = "OR"
×
799
            for signature in signatures_chunk:
×
800
                n += 1
×
801
                params[f"f{n}"] = "cf_crash_signature"
×
802
                params[f"o{n}"] = "regexp"
×
803
                params[f"v{n}"] = rf"\[(@ |@){re.escape(signature)}( \]|\])"
×
804
            params[f"f{n+1}"] = "CP"
×
805
            params_list.append(params)
×
806

807
        signatures_bugs: dict = defaultdict(list)
×
808

809
        def handler(res, data):
×
810
            for bug in res["bugs"]:
×
811
                for signature in utils.get_signatures(bug["cf_crash_signature"]):
×
812
                    if signature in self._signatures:
×
813
                        data[signature].append(bug)
×
814

815
        Bugzilla(
×
816
            queries=[
817
                connection.Query(Bugzilla.API_URL, params, handler, signatures_bugs)
818
                for params in params_list
819
            ],
820
        ).wait()
821

822
        # TODO: remove the call to DevBugzilla after moving to production
823
        DevBugzilla(
×
824
            queries=[
825
                connection.Query(DevBugzilla.API_URL, params, handler, signatures_bugs)
826
                for params in params_list
827
            ],
828
        ).wait()
829

830
        logger.debug(
×
831
            "Total of %d signatures already have bugs filed", len(signatures_bugs)
832
        )
833

834
        return signatures_bugs
×
835

836
    def analyze(self) -> list[SignatureAnalyzer]:
×
837
        """Analyze the data related to the signatures."""
838
        bugs = self.fetch_bugs()
×
839
        # TODO(investigate): For now, we are ignoring signatures that have bugs
840
        # filed even if they are closed long time ago. We should investigate
841
        # whether we should include the ones with closed bugs. For example, if
842
        # the bug was closed as Fixed years ago.
843
        self._signatures.difference_update(bugs.keys())
×
844

845
        clouseau_reports = self.fetch_clouseau_crash_reports()
×
846
        # TODO(investigate): For now, we are ignoring signatures that are not
847
        # analyzed by clouseau. We should investigate why they are not analyzed
848
        # and whether we should include them.
849
        self._signatures.intersection_update(clouseau_reports.keys())
×
850

851
        signatures, num_total_crashes = self.fetch_socorro_info()
×
852
        logger.debug("Total of %d signatures will be analyzed", len(signatures))
×
853

854
        return [
×
855
            SignatureAnalyzer(
856
                signature,
857
                num_total_crashes,
858
                clouseau_reports[signature["term"]],
859
            )
860
            for signature in signatures
861
        ]
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc