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

mozilla / relman-auto-nag / #5161

12 Jul 2024 02:21PM UTC coverage: 21.766%. Remained the same
#5161

push

coveralls-python

suhaibmujahid
[component] Skip bugs that are not available for BugBug

585 of 3497 branches covered (16.73%)

0 of 2 new or added lines in 1 file covered. (0.0%)

44 existing lines in 1 file now uncovered.

1933 of 8881 relevant lines covered (21.77%)

0.22 hits per line

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

0.0
/bugbot/rules/component.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
from libmozdata.bugzilla import Bugzilla
×
6

7
from bugbot import logger
×
8
from bugbot.bugbug_utils import get_bug_ids_classification
×
9
from bugbot.bzcleaner import BzCleaner
×
10
from bugbot.utils import get_config, nice_round
×
11

12

13
class Component(BzCleaner):
×
14
    def __init__(self):
×
15
        super().__init__()
×
16
        self.autofix_component = {}
×
17
        self.frequency = "daily"
×
18
        self.general_confidence_threshold = self.get_config(
×
19
            "general_confidence_threshold"
20
        )
21
        self.component_confidence_threshold = self.get_config("confidence_threshold")
×
22
        self.fenix_confidence_threshold = self.get_config("fenix_confidence_threshold")
×
23

24
    def add_custom_arguments(self, parser):
×
25
        parser.add_argument(
×
26
            "--frequency",
27
            help="Daily (noisy) or Hourly",
28
            choices=["daily", "hourly"],
29
            default="daily",
30
        )
31

32
    def parse_custom_arguments(self, args):
×
33
        self.frequency = args.frequency
×
34

35
    def description(self):
×
36
        return f"[Using ML] Assign a component to untriaged bugs ({self.frequency})"
×
37

38
    def columns(self):
×
39
        return ["id", "summary", "component", "confidence", "autofixed"]
×
40

41
    def sort_columns(self):
×
42
        return lambda p: (-p[3], -int(p[0]))
×
43

44
    def has_product_component(self):
×
45
        # Inject product and components when calling BzCleaner.get_bugs
46
        return True
×
47

48
    def get_bz_params(self, date):
×
49
        start_date, end_date = self.get_dates(date)
×
50

51
        bot = get_config("common", "bot_bz_mail")[0]
×
52

53
        return {
×
54
            "include_fields": ["id", "groups", "summary", "product", "component"],
55
            # Ignore bugs for which we ever modified the product or the component.
56
            "n1": 1,
57
            "f1": "product",
58
            "o1": "changedby",
59
            "v1": bot,
60
            "n2": 1,
61
            "f2": "component",
62
            "o2": "changedby",
63
            "v2": bot,
64
            # Ignore closed bugs.
65
            "bug_status": "__open__",
66
            # Get recent General bugs, and all Untriaged bugs.
67
            "j3": "OR",
68
            "f3": "OP",
69
            "j4": "AND",
70
            "f4": "OP",
71
            "f5": "component",
72
            "o5": "equals",
73
            "v5": "General",
74
            "f6": "creation_ts",
75
            "o6": "greaterthan",
76
            "v6": start_date,
77
            "f7": "CP",
78
            "f8": "component",
79
            "o8": "anyexact",
80
            "v8": "Untriaged,Foxfooding",
81
            "f9": "CP",
82
        }
83

84
    def get_bugs(self, date="today", bug_ids=[]):
×
85
        def meets_threshold(bug_data):
×
86
            threshold = (
×
87
                self.general_confidence_threshold
88
                if bug_data["class"] == "Fenix" or bug_data["class"] == "General"
89
                else self.component_confidence_threshold
90
            )
91
            return bug_data["prob"][bug_data["index"]] >= threshold
×
92

93
        # Retrieve the bugs with the fields defined in get_bz_params
94
        raw_bugs = super().get_bugs(date=date, bug_ids=bug_ids, chunk_size=7000)
×
95

96
        if len(raw_bugs) == 0:
×
97
            return {}
×
98

99
        # Extract the bug ids
100
        bug_ids = list(raw_bugs.keys())
×
101

102
        # Classify those bugs
103
        bugs = get_bug_ids_classification("component", bug_ids)
×
104

105
        fenix_general_bug_ids = []
×
106
        for bug_id, bug_data in bugs.items():
×
NEW
107
            if not bug_data.get("available", True):
×
108
                # The bug was not available, it was either removed or is a
109
                # security bug.
NEW
110
                continue
×
UNCOV
111
            if meets_threshold(bug_data):
×
UNCOV
112
                if bug_data.get("class") == "Fenix":
×
UNCOV
113
                    fenix_general_bug_ids.append(bug_id)
×
114
            else:
115
                current_bug_data = raw_bugs[bug_id]
×
116
                if (
×
117
                    current_bug_data["product"] == "Fenix"
118
                    and current_bug_data["component"] == "General"
119
                ):
120
                    fenix_general_bug_ids.append(bug_id)
×
121

UNCOV
122
        if fenix_general_bug_ids:
×
UNCOV
123
            fenix_general_classification = get_bug_ids_classification(
×
124
                "fenixcomponent", fenix_general_bug_ids
125
            )
126

127
            for bug_id, data in fenix_general_classification.items():
×
UNCOV
128
                confidence = data["prob"][data["index"]]
×
129

UNCOV
130
                if confidence > self.fenix_confidence_threshold:
×
131
                    data["class"] = f"Fenix::{data['class']}"
×
132
                    bugs[bug_id] = data
×
133

134
        results = {}
×
135

136
        for bug_id in sorted(bugs.keys()):
×
UNCOV
137
            bug_data = bugs[bug_id]
×
138

UNCOV
139
            if not bug_data.get("available", True):
×
140
                # The bug was not available, it was either removed or is a
141
                # security bug
UNCOV
142
                continue
×
143

UNCOV
144
            if not {"prob", "index", "class", "extra_data"}.issubset(bug_data.keys()):
×
UNCOV
145
                raise Exception(f"Invalid bug response {bug_id}: {bug_data!r}")
×
146

UNCOV
147
            bug = raw_bugs[bug_id]
×
148
            prob = bug_data["prob"]
×
149
            index = bug_data["index"]
×
UNCOV
150
            suggestion = bug_data["class"]
×
151

152
            conflated_components_mapping = bug_data["extra_data"].get(
×
153
                "conflated_components_mapping", {}
154
            )
155

156
            # Skip product-only suggestions that are not useful.
UNCOV
157
            if "::" not in suggestion and bug["product"] == suggestion:
×
UNCOV
158
                continue
×
159

UNCOV
160
            suggestion = conflated_components_mapping.get(suggestion, suggestion)
×
161

162
            if "::" not in suggestion:
×
UNCOV
163
                logger.error(
×
164
                    f"There is something wrong with this component suggestion! {suggestion}"
165
                )
166
                continue
×
167

UNCOV
168
            i = suggestion.index("::")
×
UNCOV
169
            suggested_product = suggestion[:i]
×
170
            suggested_component = suggestion[i + 2 :]
×
171

172
            # When moving bugs out of the 'General' component, we don't want to change the product (unless it is Firefox).
173
            if bug["component"] == "General" and bug["product"] not in {
×
174
                suggested_product,
175
                "Firefox",
176
            }:
177
                continue
×
178

179
            # Don't move bugs from Firefox::General to Core::Internationalization.
UNCOV
180
            if (
×
181
                bug["product"] == "Firefox"
182
                and bug["component"] == "General"
183
                and suggested_product == "Core"
184
                and suggested_component == "Internationalization"
185
            ):
UNCOV
186
                continue
×
187

UNCOV
188
            result = {
×
189
                "id": bug_id,
190
                "summary": bug["summary"],
191
                "component": suggestion,
192
                "confidence": nice_round(prob[index]),
193
                "autofixed": False,
194
            }
195

196
            # In daily mode, we send an email with all results.
UNCOV
197
            if self.frequency == "daily":
×
UNCOV
198
                results[bug_id] = result
×
199

UNCOV
200
            confidence_threshold_conf = (
×
201
                "confidence_threshold"
202
                if bug["component"] != "General"
203
                else "general_confidence_threshold"
204
            )
205

UNCOV
206
            if prob[index] >= self.get_config(confidence_threshold_conf):
×
UNCOV
207
                self.autofix_component[bug_id] = {
×
208
                    "product": suggested_product,
209
                    "component": suggested_component,
210
                }
211

UNCOV
212
                result["autofixed"] = True
×
213

214
                # In hourly mode, we send an email with only the bugs we acted upon.
UNCOV
215
                if self.frequency == "hourly":
×
216
                    results[bug_id] = result
×
217

218
        # Don't move bugs back into components they were moved out of.
219
        # TODO: Use the component suggestion from the service with the second highest confidence instead.
220
        def history_handler(bug):
×
UNCOV
221
            bug_id = str(bug["id"])
×
222

UNCOV
223
            previous_product_components = set()
×
224

225
            current_product = raw_bugs[bug_id]["product"]
×
UNCOV
226
            current_component = raw_bugs[bug_id]["component"]
×
227

UNCOV
228
            for history in bug["history"]:
×
229
                for change in history["changes"][::-1]:
×
230
                    if change["field_name"] == "product":
×
UNCOV
231
                        current_product = change["removed"]
×
232
                    elif change["field_name"] == "component":
×
233
                        current_component = change["removed"]
×
234

235
                previous_product_components.add((current_product, current_component))
×
236

237
            suggested_product = self.autofix_component[bug_id]["product"]
×
UNCOV
238
            suggested_component = self.autofix_component[bug_id]["component"]
×
239

UNCOV
240
            if (suggested_product, suggested_component) in previous_product_components:
×
241
                results[bug_id]["autofixed"] = False
×
242
                del self.autofix_component[bug_id]
×
243

244
        bugids = list(self.autofix_component.keys())
×
245
        Bugzilla(
×
246
            bugids=bugids,
247
            historyhandler=history_handler,
248
        ).get_data().wait()
249

UNCOV
250
        return results
×
251

UNCOV
252
    def get_autofix_change(self):
×
UNCOV
253
        cc = self.get_config("cc")
×
254
        return {
×
255
            bug_id: (
256
                data.update(
257
                    {
258
                        "cc": {"add": cc},
259
                        "comment": {
260
                            "body": f"The [Bugbug](https://github.com/mozilla/bugbug/) bot thinks this bug should belong to the '{data['product']}::{data['component']}' component, and is moving the bug to that component. Please correct in case you think the bot is wrong."
261
                        },
262
                    }
263
                )
264
                or data
265
            )
266
            for bug_id, data in self.autofix_component.items()
267
        }
268

UNCOV
269
    def get_db_extra(self):
×
UNCOV
270
        return {
×
271
            bugid: "{}::{}".format(v["product"], v["component"])
272
            for bugid, v in self.get_autofix_change().items()
273
        }
274

275

UNCOV
276
if __name__ == "__main__":
×
UNCOV
277
    Component().run()
×
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