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

mozilla / relman-auto-nag / #5020

21 May 2024 08:01PM CUT coverage: 21.835% (-0.02%) from 21.85%
#5020

push

coveralls-python

benjaminmah
Keep old classification if the new classification does not meet threshold but old classification does.

716 of 3602 branches covered (19.88%)

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

1930 of 8839 relevant lines covered (21.84%)

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

19
    def add_custom_arguments(self, parser):
×
20
        parser.add_argument(
×
21
            "--frequency",
22
            help="Daily (noisy) or Hourly",
23
            choices=["daily", "hourly"],
24
            default="daily",
25
        )
26

27
    def parse_custom_arguments(self, args):
×
28
        self.frequency = args.frequency
×
29

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

33
    def columns(self):
×
34
        return ["id", "summary", "component", "confidence", "autofixed"]
×
35

36
    def sort_columns(self):
×
37
        return lambda p: (-p[3], -int(p[0]))
×
38

39
    def has_product_component(self):
×
40
        # Inject product and components when calling BzCleaner.get_bugs
41
        return True
×
42

43
    def get_bz_params(self, date):
×
44
        start_date, end_date = self.get_dates(date)
×
45

46
        bot = get_config("common", "bot_bz_mail")[0]
×
47

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

79
    def get_bugs(self, date="today", bug_ids=[]):
×
80
        # Retrieve the bugs with the fields defined in get_bz_params
81
        raw_bugs = super().get_bugs(date=date, bug_ids=bug_ids, chunk_size=7000)
×
82

83
        if len(raw_bugs) == 0:
×
84
            return {}
×
85

86
        # Extract the bug ids
87
        bug_ids = list(raw_bugs.keys())
×
88

89
        # Classify those bugs
90
        bugs = get_bug_ids_classification("component", bug_ids)
×
91

92
        # Collect bugs classified as Fenix::General
93
        fenix_general_bug_ids = [
×
94
            bug_id
95
            for bug_id, bug_data in bugs.items()
96
            if bug_data.get("class") == "Fenix::General"
97
        ]
98

99
        # Reclassify the Fenix::General bugs using the fenixcomponent model
100
        if fenix_general_bug_ids:
×
101
            fenix_general_classification = get_bug_ids_classification(
×
102
                "fenixcomponent", fenix_general_bug_ids
103
            )
104

NEW
105
            confidence_threshold = self.get_config("confidence_threshold")
×
NEW
106
            general_confidence_threshold = self.get_config(
×
107
                "general_confidence_threshold"
108
            )
109

110
            for bug_id, data in fenix_general_classification.items():
×
NEW
111
                original_data = bugs[bug_id]
×
NEW
112
                original_confidence = original_data["prob"][original_data["index"]]
×
NEW
113
                new_confidence = data["prob"][data["index"]]
×
114

115
                # If the original confidence for Fenix::General met the threshold and the new classification does not, keep the old classification.
NEW
116
                if not (
×
117
                    new_confidence < confidence_threshold
118
                    and original_confidence > general_confidence_threshold
119
                ):
NEW
120
                    bugs[bug_id] = data
×
121

122
        results = {}
×
123

124
        for bug_id in sorted(bugs.keys()):
×
125
            bug_data = bugs[bug_id]
×
126

127
            if not bug_data.get("available", True):
×
128
                # The bug was not available, it was either removed or is a
129
                # security bug
130
                continue
×
131

132
            if not {"prob", "index", "class", "extra_data"}.issubset(bug_data.keys()):
×
133
                raise Exception(f"Invalid bug response {bug_id}: {bug_data!r}")
×
134

135
            bug = raw_bugs[bug_id]
×
136
            prob = bug_data["prob"]
×
137
            index = bug_data["index"]
×
138
            suggestion = bug_data["class"]
×
139
            conflated_components_mapping = bug_data["extra_data"][
×
140
                "conflated_components_mapping"
141
            ]
142

143
            # Skip product-only suggestions that are not useful.
144
            if "::" not in suggestion and bug["product"] == suggestion:
×
145
                continue
×
146

147
            suggestion = conflated_components_mapping.get(suggestion, suggestion)
×
148

149
            if "::" not in suggestion:
×
150
                logger.error(
×
151
                    f"There is something wrong with this component suggestion! {suggestion}"
152
                )
153
                continue
×
154

155
            i = suggestion.index("::")
×
156
            suggested_product = suggestion[:i]
×
157
            suggested_component = suggestion[i + 2 :]
×
158

159
            # When moving bugs out of the 'General' component, we don't want to change the product (unless it is Firefox).
160
            if bug["component"] == "General" and bug["product"] not in {
×
161
                suggested_product,
162
                "Firefox",
163
            }:
164
                continue
×
165

166
            # Don't move bugs from Firefox::General to Core::Internationalization.
167
            if (
×
168
                bug["product"] == "Firefox"
169
                and bug["component"] == "General"
170
                and suggested_product == "Core"
171
                and suggested_component == "Internationalization"
172
            ):
173
                continue
×
174

175
            result = {
×
176
                "id": bug_id,
177
                "summary": bug["summary"],
178
                "component": suggestion,
179
                "confidence": nice_round(prob[index]),
180
                "autofixed": False,
181
            }
182

183
            # In daily mode, we send an email with all results.
184
            if self.frequency == "daily":
×
185
                results[bug_id] = result
×
186

187
            confidence_threshold_conf = (
×
188
                "confidence_threshold"
189
                if bug["component"] != "General"
190
                else "general_confidence_threshold"
191
            )
192

193
            if prob[index] >= self.get_config(confidence_threshold_conf):
×
194
                self.autofix_component[bug_id] = {
×
195
                    "product": suggested_product,
196
                    "component": suggested_component,
197
                }
198

199
                result["autofixed"] = True
×
200

201
                # In hourly mode, we send an email with only the bugs we acted upon.
202
                if self.frequency == "hourly":
×
203
                    results[bug_id] = result
×
204

205
        # Don't move bugs back into components they were moved out of.
206
        # TODO: Use the component suggestion from the service with the second highest confidence instead.
207
        def history_handler(bug):
×
208
            bug_id = str(bug["id"])
×
209

210
            previous_product_components = set()
×
211

212
            current_product = raw_bugs[bug_id]["product"]
×
213
            current_component = raw_bugs[bug_id]["component"]
×
214

215
            for history in bug["history"]:
×
216
                for change in history["changes"][::-1]:
×
217
                    if change["field_name"] == "product":
×
218
                        current_product = change["removed"]
×
219
                    elif change["field_name"] == "component":
×
220
                        current_component = change["removed"]
×
221

222
                previous_product_components.add((current_product, current_component))
×
223

224
            suggested_product = self.autofix_component[bug_id]["product"]
×
225
            suggested_component = self.autofix_component[bug_id]["component"]
×
226

227
            if (suggested_product, suggested_component) in previous_product_components:
×
228
                results[bug_id]["autofixed"] = False
×
229
                del self.autofix_component[bug_id]
×
230

231
        bugids = list(self.autofix_component.keys())
×
232
        Bugzilla(
×
233
            bugids=bugids,
234
            historyhandler=history_handler,
235
        ).get_data().wait()
236

237
        return results
×
238

239
    def get_autofix_change(self):
×
240
        cc = self.get_config("cc")
×
241
        return {
×
242
            bug_id: (
243
                data.update(
244
                    {
245
                        "cc": {"add": cc},
246
                        "comment": {
247
                            "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."
248
                        },
249
                    }
250
                )
251
                or data
252
            )
253
            for bug_id, data in self.autofix_component.items()
254
        }
255

256
    def get_db_extra(self):
×
257
        return {
×
258
            bugid: "{}::{}".format(v["product"], v["component"])
259
            for bugid, v in self.get_autofix_change().items()
260
        }
261

262

263
if __name__ == "__main__":
×
264
    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