internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: getsentry/sentry

Issue:
Migrate Rule data for consistency
We have inconsistent data saved in the `conditions` and `actions` fields in `Rule`'s `data` column because in the past we sometimes added a `name` field which is a human readable string describing what the rule is doing. This is unnecessary and makes it harder to compare and do analysis on rule data, so we should write a migration to delete all that stuff now that we're not writing that to the db anymore.


Discussion:

Resolving patch:
diff --git a/src/sentry/migrations/0538_remove_name_data_from_rule.py b/src/sentry/migrations/0538_remove_name_data_from_rule.py
new file mode 100644
--- /dev/null
+++ b/src/sentry/migrations/0538_remove_name_data_from_rule.py
@@ -0,0 +1,47 @@
+# Generated by Django 3.2.20 on 2023-08-29 19:04
+
+from django.db import migrations
+
+from sentry.new_migrations.migrations import CheckedMigration
+from sentry.utils.query import RangeQuerySetWrapperWithProgressBar
+
+
+def remove_name_data(apps, schema_editor):
+    Rule = apps.get_model("sentry", "Rule")
+
+    for rule in RangeQuerySetWrapperWithProgressBar(Rule.objects.all()):
+        for action in rule.data.get("actions", []):
+            if action.get("name") or action.get("name") in [0, ""]:
+                del action["name"]
+
+        for condition in rule.data.get("conditions", []):
+            if condition.get("name") or condition.get("name") in [0, ""]:
+                del condition["name"]
+
+        rule.save(update_fields=["data"])
+
+
+class Migration(CheckedMigration):
+    # This flag is used to mark that a migration shouldn't be automatically run in production. For
+    # the most part, this should only be used for operations where it's safe to run the migration
+    # after your code has deployed. So this should not be used for most operations that alter the
+    # schema of a table.
+    # Here are some things that make sense to mark as dangerous:
+    # - Large data migrations. Typically we want these to be run manually by ops so that they can
+    #   be monitored and not block the deploy for a long period of time while they run.
+    # - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to
+    #   have ops run this and not block the deploy. Note that while adding an index is a schema
+    #   change, it's completely safe to run the operation after the code has deployed.
+    is_dangerous = True
+
+    dependencies = [
+        ("sentry", "0537_backfill_xactor_team_and_user_ids"),
+    ]
+
+    operations = [
+        migrations.RunPython(
+            remove_name_data,
+            migrations.RunPython.noop,
+            hints={"tables": ["sentry_rule"]},
+        ),
+    ]


Test patch:
Repository: getsentry/sentry

Issue:
Expose source map method on event endpoints
Problem: We'd like to determine how effective symbolication using the new debugIDs method is compared to the legacy method that uses releases. However, this information it not yet available on the FE.

Proposed solution: Expose the `resolved_with` property of the event stack trace's frames in the event endpoints.


Relates to https://github.com/getsentry/sentry/issues/54834


Discussion:

Resolving patch:
diff --git a/src/sentry/api/serializers/models/event.py b/src/sentry/api/serializers/models/event.py
--- a/src/sentry/api/serializers/models/event.py
+++ b/src/sentry/api/serializers/models/event.py
@@ -3,7 +3,7 @@
 import re
 from collections import defaultdict
 from datetime import datetime, timezone
-from typing import Any, Dict, Sequence
+from typing import Any, Dict, List, Sequence
 
 import sentry_sdk
 import sqlparse
@@ -15,6 +15,7 @@
 from sentry.models import EventAttachment, EventError, Release, User, UserReport
 from sentry.sdk_updates import SdkSetupState, get_suggested_updates
 from sentry.search.utils import convert_user_tag_to_query, map_device_class_level
+from sentry.stacktraces.processing import find_stacktraces_in_data
 from sentry.utils.json import prune_empty_keys
 from sentry.utils.safe import get_path
 
@@ -429,11 +430,26 @@ def _get_release_info(self, user, event, include_full_release_data: bool):
     def _get_sdk_updates(self, obj):
         return list(get_suggested_updates(SdkSetupState.from_event_json(obj.data)))
 
+    def _get_resolved_with(self, obj: Event) -> List[str]:
+        stacktraces = find_stacktraces_in_data(obj.data)
+
+        frame_lists = [stacktrace.get_frames() for stacktrace in stacktraces]
+        frames = [frame for frame_list in frame_lists for frame in frame_list]
+
+        unique_resolution_methods = {
+            resolved_with
+            for frame in frames
+            if (resolved_with := frame.get("resolved_with")) is not None
+        }
+
+        return list(unique_resolution_methods)
+
     def serialize(self, obj, attrs, user, include_full_release_data=False):
         result = super().serialize(obj, attrs, user)
         result["release"] = self._get_release_info(user, obj, include_full_release_data)
         result["userReport"] = self._get_user_report(user, obj)
         result["sdkUpdates"] = self._get_sdk_updates(obj)
+        result["resolvedWith"] = self._get_resolved_with(obj)
         return result
 
 


Test patch:
Repository: getsentry/sentry

Issue:
Support apdex without parameter



Discussion:

Resolving patch:
diff --git a/src/sentry/snuba/metrics/extraction.py b/src/sentry/snuba/metrics/extraction.py
--- a/src/sentry/snuba/metrics/extraction.py
+++ b/src/sentry/snuba/metrics/extraction.py
@@ -306,13 +306,13 @@ def _get_function_support(function: str) -> SupportedBy:
 
 
 def _get_args_support(function: str, args: Sequence[str]) -> SupportedBy:
+    if len(args) == 0:
+        return SupportedBy.both()
+
     # apdex can have two variations, either apdex() or apdex(value).
     if function == "apdex":
         return SupportedBy(on_demand_metrics=True, standard_metrics=False)
 
-    if len(args) == 0:
-        return SupportedBy.both()
-
     arg = args[0]
 
     standard_metrics = _is_standard_metrics_field(arg)


Test patch:
Repository: getsentry/sentry

Issue:
Expose source map method on event endpoints
Problem: We'd like to determine how effective symbolication using the new debugIDs method is compared to the legacy method that uses releases. However, this information it not yet available on the FE.

Proposed solution: Expose the `resolved_with` property of the event stack trace's frames in the event endpoints.


Relates to https://github.com/getsentry/sentry/issues/54834


Discussion:

Resolving patch:
diff --git a/src/sentry/api/serializers/models/event.py b/src/sentry/api/serializers/models/event.py
--- a/src/sentry/api/serializers/models/event.py
+++ b/src/sentry/api/serializers/models/event.py
@@ -434,12 +434,10 @@ def _get_resolved_with(self, obj: Event) -> List[str]:
         stacktraces = find_stacktraces_in_data(obj.data)
 
         frame_lists = [stacktrace.get_frames() for stacktrace in stacktraces]
-        frames = [frame for frame_list in frame_lists for frame in frame_list]
+        frame_data = [frame.get("data") for frame_list in frame_lists for frame in frame_list]
 
         unique_resolution_methods = {
-            resolved_with
-            for frame in frames
-            if (resolved_with := frame.get("resolved_with")) is not None
+            frame.get("resolved_with") for frame in frame_data if frame is not None
         }
 
         return list(unique_resolution_methods)


Test patch:
Repository: getsentry/sentry

Issue:
Fix typing for `sentry.tasks.commits`
Many files related to post-process are skipping type checks.

* Remove the file from [sentry/pyproject.toml](https://github.com/getsentry/sentry/blob/b7810a9dca4b57afd2858903a6a9ec7ab50cdead/pyproject.toml)
* Run `mypy sentry.tasks.commits` and fix the typing errors

From https://github.com/getsentry/sentry/issues/55193


Discussion:

Resolving patch:
diff --git a/src/sentry/tasks/commits.py b/src/sentry/tasks/commits.py
--- a/src/sentry/tasks/commits.py
+++ b/src/sentry/tasks/commits.py
@@ -159,7 +159,9 @@ def fetch_commits(release_id: int, user_id: int, refs, prev_release_id=None, **k
                     "start_sha": start_sha,
                 },
             )
-            span = sentry_sdk.Hub.current.scope.span
+            span = sentry_sdk.get_current_span()
+            if span is None:
+                raise TypeError("No span is currently active right now")
             span.set_status("unknown_error")
             logger.exception(e)
             if isinstance(e, InvalidIdentity) and getattr(e, "identity", None):
@@ -254,15 +256,16 @@ def is_integration_provider(provider):
 
 
 def get_emails_for_user_or_org(user: RpcUser | None, orgId: int):
-    emails = []
+    emails: list[str] = []
     if not user:
         return []
     if user.is_sentry_app:
         organization = Organization.objects.get(id=orgId)
         members = organization.get_members_with_org_roles(roles=["owner"])
         user_ids = [m.user_id for m in members if m.user_id]
-        emails = {u.email for u in user_service.get_many(filter={"user_ids": user_ids}) if u.email}
-        emails = list(emails)
+        emails = list(
+            {u.email for u in user_service.get_many(filter={"user_ids": user_ids}) if u.email}
+        )
     else:
         emails = [user.email]
 


Test patch:
Repository: getsentry/sentry

Issue:
Extend on-demand field support
We need to extend the list of fields supported by on-demand with the following:
```
device.arch
device.battery_level
device.brand
device.charging
device.locale
device.online
device.orientation
device.screen_density
device.screen_dpi
device.screen_height_pixels
device.screen_width_pixels
device.simulator
device.uuid

platform.name

os.build
os.kernel_version

sdk.name
sdk.version
```
```[tasklist]
- [ ] https://github.com/getsentry/sentry/issues/58504
- [ ] https://github.com/getsentry/sentry/issues/58505
- [ ] https://github.com/getsentry/sentry/issues/58507
- [ ] https://github.com/getsentry/relay/pull/2607
```


Discussion:
This list is missing the following fields:
 - `contexts.app.in_foreground`
 - `contexts.unreal.crash_type`

I'll be addressing this in https://github.com/getsentry/relay/pull/2607

Resolving patch:
diff --git a/src/sentry/snuba/metrics/extraction.py b/src/sentry/snuba/metrics/extraction.py
--- a/src/sentry/snuba/metrics/extraction.py
+++ b/src/sentry/snuba/metrics/extraction.py
@@ -69,14 +69,32 @@
     "geo.subdivision": "user.geo.subdivision",
     "http.method": "request.method",
     # Subset of context fields
-    "device.name": "contexts.device.name",
+    "device.arch": "contexts.device.arch",
+    "device.battery_level": "contexts.device.battery_level",
+    "device.brand": "contexts.device.brand",
+    "device.charging": "contexts.device.charging",
     "device.family": "contexts.device.family",
+    "device.locale": "contexts.device.locale",
+    "device.name": "contexts.device.name",
+    "device.online": "contexts.device.online",
+    "device.orientation": "contexts.device.orientation",
+    "device.screen_density": "contexts.device.screen_density",
+    "device.screen_dpi": "contexts.device.screen_dpi",
+    "device.screen_height_pixels": "contexts.device.screen_height_pixels",
+    "device.screen_width_pixels": "contexts.device.screen_width_pixels",
+    "device.simulator": "contexts.device.simulator",
+    "device.uuid": "contexts.device.uuid",
     "os.name": "contexts.os.name",
+    "os.build": "contexts.os.build",
+    "os.kernel_version": "contexts.os.kernel_version",
     "os.version": "contexts.os.version",
+    "platform.name": "contexts.platform.name",
     "browser.name": "contexts.browser.name",
     "transaction.op": "contexts.trace.op",
     "transaction.status": "contexts.trace.status",
     "http.status_code": "contexts.response.status_code",
+    "sdk.name": "contexts.sdk.name",
+    "sdk.version": "contexts.sdk.version",
     # Computed fields
     "transaction.duration": "duration",
     "release.build": "release.build",


Test patch:
Repository: getsentry/sentry

Issue:
Include Issue alerts under Errors in Segmented Control
**Problem**: The segmented control today shows Errors, Sessions and Performance (the 3 categories that exist also in the alert creation), however Issue alerts don't appear in any of those categories, just under "All". Most of our customers have mainly issue alerts, so this "hides" them. There is an expectation that issue alerts appear under Errors, but that is currently not the case.

**Proposed solution:** Have issue alerts appear under Errors (for now at least).


Discussion:

Resolving patch:
diff --git a/src/sentry/incidents/endpoints/organization_alert_rule_index.py b/src/sentry/incidents/endpoints/organization_alert_rule_index.py
--- a/src/sentry/incidents/endpoints/organization_alert_rule_index.py
+++ b/src/sentry/incidents/endpoints/organization_alert_rule_index.py
@@ -187,11 +187,11 @@ def get(self, request: Request, organization) -> Response:
             # Filter to only error alert rules
             alert_rules = alert_rules.filter(snuba_query__dataset=Dataset.Events.value)
         else:
-            # Filter only non-issue alert rules
             datasets = request.GET.getlist("dataset", [])
             if len(datasets) > 0:
                 alert_rules = alert_rules.filter(snuba_query__dataset__in=datasets)
-                issue_rules = Rule.objects.none()
+                if Dataset.Events.value not in datasets:
+                    issue_rules = Rule.objects.none()
 
         name = request.GET.get("name", None)
         if name:


Test patch:
diff --git a/tests/sentry/incidents/endpoints/test_organization_combined_rule_index_endpoint.py b/tests/sentry/incidents/endpoints/test_organization_combined_rule_index_endpoint.py
--- a/tests/sentry/incidents/endpoints/test_organization_combined_rule_index_endpoint.py
+++ b/tests/sentry/incidents/endpoints/test_organization_combined_rule_index_endpoint.py
@@ -905,6 +905,10 @@ def test_dataset_filter(self):
             self.assert_alert_rule_serialized(
                 transaction_rule, transactions_res.data[0], skip_dates=True
             )
+            events_res = self.get_success_response(
+                self.organization.slug, dataset=[Dataset.Events.value]
+            )
+            self.assert_alert_rule_serialized(events_rule, events_res.data[0], skip_dates=True)
 
         with self.feature("organizations:incidents"):
             # without performance-view, we should only see events rules
Repository: getsentry/sentry

Issue:
Add support for the metric type and aggregation functions to the metrics meta endpoint



Discussion:

Resolving patch:
diff --git a/src/sentry/snuba/metrics/datasource.py b/src/sentry/snuba/metrics/datasource.py
--- a/src/sentry/snuba/metrics/datasource.py
+++ b/src/sentry/snuba/metrics/datasource.py
@@ -203,11 +203,18 @@ def get_stored_mris(projects: Sequence[Project], use_case_id: UseCaseID) -> List
             EntityKey.MetricsSets,
             EntityKey.MetricsDistributions,
         }
+    elif use_case_id == UseCaseID.TRANSACTIONS:
+        entity_keys = {
+            EntityKey.GenericMetricsCounters,
+            EntityKey.GenericMetricsSets,
+            EntityKey.GenericMetricsDistributions,
+        }
     else:
         entity_keys = {
             EntityKey.GenericMetricsCounters,
             EntityKey.GenericMetricsSets,
             EntityKey.GenericMetricsDistributions,
+            EntityKey.GenericMetricsGauges,
         }
 
     stored_metrics = []
diff --git a/src/sentry/snuba/metrics/fields/base.py b/src/sentry/snuba/metrics/fields/base.py
--- a/src/sentry/snuba/metrics/fields/base.py
+++ b/src/sentry/snuba/metrics/fields/base.py
@@ -194,6 +194,7 @@ def _get_known_entity_of_metric_mri(metric_mri: str) -> Optional[EntityKey]:
                 "c": EntityKey.GenericMetricsCounters,
                 "d": EntityKey.GenericMetricsDistributions,
                 "s": EntityKey.GenericMetricsSets,
+                "g": EntityKey.GenericMetricsGauges,
             }[entity_prefix]
     except (ValueError, IndexError, KeyError):
         pass


Test patch:
Repository: getsentry/sentry

Issue:
Deprecate the ProjectCombinedRuleIndexEndpoint
[GCP API access logs](https://console.cloud.google.com/logs/query;query=resource.type%20%3D%20k8s_container%0Aresource.labels.namespace_name%20%3D%20default%0Aresource.labels.container_name%20%3D%20sentry%0Alabels.name%20%3D%20sentry.access.api%0AjsonPayload.view%3D~%22ProjectCombinedRuleIndexEndpoint%22;summaryFields=:true:32:beginning;lfeCustomFields=jsonPayload%252Fview,jsonPayload%252Forganization_id;cursorTimestamp=2023-09-06T18:29:05.855473577Z;startTime=2023-09-06T16:51:17.461Z;endTime=2023-09-06T23:51:17.461482Z?project=internal-sentry) show that it's not used by us, and only by 2 customers. It's an undocumented endpoint so we can [set the deprecation header](https://www.notion.so/sentry/Sentry-API-Deprecation-Policy-ccbdea15a34c4fdeb50985685adc3368) and get rid of it. 

Related to https://github.com/getsentry/sentry/issues/54005


Discussion:

Resolving patch:
diff --git a/src/sentry/incidents/endpoints/project_alert_rule_index.py b/src/sentry/incidents/endpoints/project_alert_rule_index.py
--- a/src/sentry/incidents/endpoints/project_alert_rule_index.py
+++ b/src/sentry/incidents/endpoints/project_alert_rule_index.py
@@ -1,5 +1,7 @@
 from __future__ import annotations
 
+from datetime import datetime
+
 from rest_framework.request import Request
 from rest_framework.response import Response
 
@@ -7,6 +9,7 @@
 from sentry.api.api_publish_status import ApiPublishStatus
 from sentry.api.base import region_silo_endpoint
 from sentry.api.bases.project import ProjectAlertRulePermission, ProjectEndpoint
+from sentry.api.helpers.deprecation import deprecated
 from sentry.api.paginator import CombinedQuerysetIntermediary, CombinedQuerysetPaginator
 from sentry.api.serializers import CombinedRuleSerializer, serialize
 from sentry.constants import ObjectStatus
@@ -18,13 +21,15 @@
 
 @region_silo_endpoint
 class ProjectCombinedRuleIndexEndpoint(ProjectEndpoint):
+    DEPRECATION_DATE = datetime.fromisoformat("2024-02-07T00:00:00+00:00:00")
     publish_status = {
         "GET": ApiPublishStatus.UNKNOWN,
     }
 
+    @deprecated(DEPRECATION_DATE, "sentry-api-0-organization-combined-rules")
     def get(self, request: Request, project) -> Response:
         """
-        Fetches alert rules and legacy rules for a project
+        Fetches alert rules and legacy rules for a project. @deprecated. Use OrganizationCombinedRuleIndexEndpoint instead.
         """
         alert_rules = AlertRule.objects.fetch_for_project(project)
         if not features.has("organizations:performance-view", project.organization):


Test patch:
Repository: getsentry/sentry

Issue:
Jira deprecation of glance panels
Notice from Atlassian Support team about glance panel deprecation. 

AC:
- Review the deprecation plan
- Build a recommendation based on how we're impacted. If minor development work is required, complete that with this ticket. If significant work is required, notify EM/PM to share impact and come up with next steps together.

Email from Atlassian:
```
Hope you are having a good day!
As part of this deprecation notice (https://developer.atlassian.com/cloud/jira/platform/changelog/#CHANGE-897), we are reaching out because we have identified that your app, “Sentry,” will be affected by the deprecation of glance panels. 
This was initially scheduled for the 6th of October, but we have delayed it until the 30th of November.
The jiraIssueGlances and jira:issueGlance modules in Forge (https://developer.atlassian.com/platform/forge/manifest-reference/modules/jira-issue-glance/) and Connect (https://developer.atlassian.com/cloud/jira/platform/modules/issue-glance/) are being deprecated and replaced with the issueContext module. 
We recommend transitioning from the glance panel to the new issue context module before the 30th of November. 
Please note, we will not be extending this deprecation date as we announced it on the 30th of March.
Let me know if you need any further assistance,
Ahmud
Product Manager-Jira Cloud
```


Discussion:

Resolving patch:
diff --git a/src/sentry/integrations/jira/endpoints/descriptor.py b/src/sentry/integrations/jira/endpoints/descriptor.py
--- a/src/sentry/integrations/jira/endpoints/descriptor.py
+++ b/src/sentry/integrations/jira/endpoints/descriptor.py
@@ -60,7 +60,7 @@ def get(self, request: Request) -> Response:
                         "name": {"value": "Configure Sentry Add-on"},
                         "key": "configure-sentry",
                     },
-                    "jiraIssueGlances": [
+                    "jiraIssueContexts": [
                         {
                             "icon": {"width": 24, "height": 24, "url": sentry_logo},
                             "content": {"type": "label", "label": {"value": "Linked Issues"}},


Test patch:
Repository: getsentry/sentry

Issue:
Create ddm-experimental feature flag



Discussion:

Resolving patch:
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -1426,6 +1426,8 @@ def custom_parameter_sort(parameter: dict) -> tuple[str, int]:
     "organizations:customer-domains": False,
     # Delightful Developer Metrics (DDM): Enable sidebar menu item and all UI (requires custom-metrics flag as well)
     "organizations:ddm-ui": False,
+    # Enables experimental WIP ddm related features
+    "organizations:ddm-experimental": False,
     # Enable the 'discover' interface.
     "organizations:discover": False,
     # Enables events endpoint rate limit
diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py
--- a/src/sentry/features/__init__.py
+++ b/src/sentry/features/__init__.py
@@ -244,6 +244,7 @@
 default_manager.add("organizations:u2f-superuser-form", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
 default_manager.add("organizations:api-auth-provider", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
 default_manager.add("organizations:ddm-ui", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
+default_manager.add("organizations:ddm-experimental", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
 default_manager.add("organizations:escalating-issues", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
 default_manager.add("organizations:escalating-issues-msteams", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
 default_manager.add("organizations:escalating-issues-v2", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)


Test patch: