Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/sentry/incidents/metric_detector_quota.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from sentry import features, quotas
from sentry.auth.principal import RequestPrincipal
from sentry.constants import ObjectStatus
from sentry.models.organization import Organization
from sentry.workflow_engine.endpoints.validators.base import DetectorQuota
from sentry.workflow_engine.models import Detector
from sentry.workflow_engine.types import DetectorType

UNLIMITED = -1


def get_metric_detector_quota(
organization: Organization, actor: RequestPrincipal | None = None
) -> DetectorQuota:
limit = quotas.backend.get_metric_detector_limit(organization.id)
if limit == UNLIMITED or not features.has(
"organizations:workflow-engine-metric-detector-limit", organization, actor=actor
):
return DetectorQuota(has_exceeded=False, limit=UNLIMITED, count=UNLIMITED)

count = Detector.objects.filter(
project__organization=organization,
type=DetectorType.METRIC_ISSUE,
status=ObjectStatus.ACTIVE,
enabled=True,
).count()
return DetectorQuota(has_exceeded=count >= limit, limit=limit, count=count)


def can_enable_metric_detectors(quota: DetectorQuota, count: int) -> bool:
return quota.limit == UNLIMITED or quota.count + count <= quota.limit


def metric_detector_quota_message(quota: DetectorQuota) -> str:
return f"Used {quota.count}/{quota.limit} of allowed {DetectorType.METRIC_ISSUE} monitors."
44 changes: 23 additions & 21 deletions src/sentry/incidents/metric_issue_detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,18 @@
from rest_framework import serializers
from urllib3.exceptions import MaxRetryError, TimeoutError

from sentry import features, quotas
from sentry.constants import ObjectStatus
from sentry import features
from sentry.auth.principal import has_user
from sentry.incidents.logic import (
DEFAULT_CMP_ALERT_RULE_RESOLUTION_MULTIPLIER,
enable_disable_subscriptions,
get_alert_resolution,
)
from sentry.incidents.metric_detector_quota import (
can_enable_metric_detectors,
get_metric_detector_quota,
metric_detector_quota_message,
)
from sentry.incidents.models.alert_rule import AlertRuleDetectionType
from sentry.incidents.utils.subscription_limits import is_metric_subscription_allowed
from sentry.incidents.utils.types import DATA_SOURCE_SNUBA_QUERY_SUBSCRIPTION
Expand Down Expand Up @@ -42,6 +47,7 @@
from sentry.workflow_engine.endpoints.validators.base.data_condition import (
BaseDataConditionValidator,
)
from sentry.workflow_engine.endpoints.validators.utils import log_alerting_quota_hit
from sentry.workflow_engine.models import DataCondition, DataSource, Detector
from sentry.workflow_engine.models.data_condition import Condition
from sentry.workflow_engine.registry import detector_settings_registry
Expand Down Expand Up @@ -359,26 +365,19 @@ def get_quota(self) -> DetectorQuota:
request = self.context.get("request")
if organization is None or request is None:
raise serializers.ValidationError("Missing organization/request context")
return get_metric_detector_quota(organization, actor=request.user)

detector_limit = quotas.backend.get_metric_detector_limit(organization.id)
if (
not features.has(
"organizations:workflow-engine-metric-detector-limit",
organization,
actor=request.user,
)
or detector_limit == -1
):
return DetectorQuota(has_exceeded=False, limit=-1, count=-1)

detector_count = Detector.objects.filter(
project__organization=organization,
type="metric_issue", # Avoided circular import. TODO: move magic strings to constant file
status=ObjectStatus.ACTIVE,
).count()
has_exceeded = detector_count >= detector_limit

return DetectorQuota(has_exceeded=has_exceeded, limit=detector_limit, count=detector_count)
def _enforce_enable_quota(self) -> None:
quota = self.get_quota()
if can_enable_metric_detectors(quota, 1):
return
request = self.context["request"]
log_alerting_quota_hit(
object_type=f"detector:{DetectorType.METRIC_ISSUE}",
organization=self.context["organization"],
actor=request.user if has_user(request.user) else None,
)
raise serializers.ValidationError(metric_detector_quota_message(quota))

def is_editing_transaction_dataset(
self, snuba_query: SnubaQuery, data_source: SnubaQueryDataSourceType
Expand Down Expand Up @@ -528,6 +527,9 @@ def update_anomaly_detection(self, instance: Detector, validated_data: dict[str,
return seer_updated

def update(self, instance: Detector, validated_data: dict[str, Any]) -> Detector:
if validated_data.get("enabled") is True and not instance.enabled:
self._enforce_enable_quota()

if "config" in validated_data:
self._clean_config(validated_data["config"])

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@
from sentry.constants import ObjectStatus
from sentry.deletions.models.scheduleddeletion import CellScheduledDeletion
from sentry.exceptions import InvalidSearchQuery
from sentry.incidents.metric_detector_quota import (
can_enable_metric_detectors,
get_metric_detector_quota,
metric_detector_quota_message,
)
from sentry.issues.issue_search import convert_actor_or_none_value
from sentry.models.group import GroupStatus
from sentry.models.organization import Organization
Expand Down Expand Up @@ -301,7 +306,7 @@

return queryset

@extend_schema(

Check warning on line 309 in src/sentry/workflow_engine/endpoints/organization_detector_index.py

View workflow job for this annotation

GitHub Actions / backend test (5)

S037 undocumented response

GET /organizations/{organization_id_or_slug}/detectors/ 200 body doesn't match the schema at 0/dataSources/0/queryObj: {'id': '7b6b0331-1813-4df7-8fad-71d5b6723f0c', 'status': 'active', 'isMuted': False, 'isUpserting': False, 'name': 'Cron Detector', 'slug': 'cron-detector', 'config': {'schedule': '* * * * *', 'max_runtime': None, 'schedule_type': 'crontab', 'checkin_margin': None}, 'dateCreated': '2026-11-21T00:38: (first seen in tests/sentry/workflow_engine/endpoints/test_organization_detector_index.py::OrganizationDetectorIndexGetTest::test_query_by_type_alias)

Check warning on line 309 in src/sentry/workflow_engine/endpoints/organization_detector_index.py

View workflow job for this annotation

GitHub Actions / backend test (9)

S037 undocumented response

GET /organizations/{organization_id_or_slug}/detectors/ 200 body doesn't match the schema at 3/dataSources/0/queryObj: {'id': '6e36f0fa-92d9-4fb4-ba7d-04053f2af84b', 'status': 'active', 'isMuted': False, 'isUpserting': False, 'name': 'Cron', 'slug': 'cron', 'config': {'schedule': '* * * * *', 'max_runtime': None, 'schedule_type': 'crontab', 'checkin_margin': None}, 'dateCreated': '2026-11-21T00:38:13.503891Z', 'proj (first seen in tests/sentry/workflow_engine/endpoints/test_organization_detector_index.py::OrganizationDetectorIndexGetTest::test_hides_cron_and_uptime_detectors_without_data_source)
operation_id="listOrganizationDetectors",
summary="Fetch an Organization's Monitors",
parameters=[
Expand Down Expand Up @@ -398,7 +403,7 @@
count_hits=True,
)

@extend_schema(

Check warning on line 406 in src/sentry/workflow_engine/endpoints/organization_detector_index.py

View workflow job for this annotation

GitHub Actions / backend test (8)

S037 undocumented response

PUT /organizations/{organization_id_or_slug}/detectors/ 200 body doesn't match the schema at 0/dataSources/0/queryObj: {'id': 'fcab457f-aeb2-4bf3-bdec-bb15e4d2d1a6', 'status': 'disabled', 'isMuted': False, 'isUpserting': False, 'name': '', 'slug': '154392a5d861', 'config': {'schedule': '* * * * *', 'max_runtime': None, 'schedule_type': 'crontab', 'checkin_margin': None}, 'dateCreated': '2026-11-21T00:38:06.035200Z', (first seen in tests/sentry/workflow_engine/endpoints/test_organization_detector_index.py::OrganizationDetectorIndexPutTest::test_put_exclusion_skips_type_in_query_selection)

Check warning on line 406 in src/sentry/workflow_engine/endpoints/organization_detector_index.py

View workflow job for this annotation

GitHub Actions / backend test (4)

S037 undocumented response

PUT /organizations/{organization_id_or_slug}/detectors/ 200 body doesn't match the schema at 0/dataSources/0/queryObj: {'id': '8c30fea5-825f-4898-b525-15996847e6bb', 'status': 'disabled', 'isMuted': False, 'isUpserting': False, 'name': '', 'slug': 'bfa3f7f253b6', 'config': {'schedule': '* * * * *', 'max_runtime': None, 'schedule_type': 'crontab', 'checkin_margin': None}, 'dateCreated': '2026-11-21T00:38:05.435093Z', (first seen in tests/sentry/workflow_engine/endpoints/test_organization_detector_index.py::OrganizationDetectorIndexPutTest::test_update_detectors_disable_cron)

Check warning on line 406 in src/sentry/workflow_engine/endpoints/organization_detector_index.py

View workflow job for this annotation

GitHub Actions / backend test (9)

S037 undocumented response

PUT /organizations/{organization_id_or_slug}/detectors/ 200 body doesn't match the schema at 0/dataSources/0/queryObj: {'id': '4d3f1825-ae3b-4580-8e8a-66bb26f257be', 'status': 'active', 'isMuted': False, 'isUpserting': False, 'name': '', 'slug': '50dd2c8a3e0c', 'config': {'schedule': '* * * * *', 'max_runtime': None, 'schedule_type': 'crontab', 'checkin_margin': None}, 'dateCreated': '2026-11-21T00:38:16.041412Z', ' (first seen in tests/sentry/workflow_engine/endpoints/test_organization_detector_index.py::OrganizationDetectorIndexPutTest::test_update_detectors_enable_cron)
operation_id="updateOrganizationDetectors",
summary="Mutate an Organization's Monitors",
parameters=[
Expand Down Expand Up @@ -473,6 +478,20 @@
if not can_edit_detectors(queryset, request):
raise PermissionDenied

if enabled:
metric_detectors_to_enable = sum(
1
for detector in queryset
if detector.type == DetectorType.METRIC_ISSUE and not detector.enabled
)
if metric_detectors_to_enable:
quota = get_metric_detector_quota(organization, actor=request.user)
if not can_enable_metric_detectors(quota, metric_detectors_to_enable):
return Response(
{"detail": metric_detector_quota_message(quota)},
status=status.HTTP_400_BAD_REQUEST,
)

seat_detectors = [
detector
for detector in queryset
Expand Down
59 changes: 59 additions & 0 deletions tests/sentry/incidents/endpoints/validators/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,13 @@ def test_enforce_quota_within_limit(self, mock_get_limit: mock.MagicMock) -> Non
type=MetricIssue.slug,
status=status,
)
self.create_detector(
project_id=self.project.id,
name="Disabled Detector",
type=MetricIssue.slug,
status=ObjectStatus.ACTIVE,
enabled=False,
)

validator = MetricIssueDetectorValidator(data=self.valid_data, context=self.context)
assert validator.is_valid()
Expand Down Expand Up @@ -1103,6 +1110,58 @@ def test_update_enabled_ignores_subscription_outside_detector_project(self) -> N
other_subscription.refresh_from_db()
assert other_subscription.status == original_status

@mock.patch("sentry.quotas.backend.get_metric_detector_limit", return_value=2)
@with_feature("organizations:workflow-engine-metric-detector-limit")
def test_enable_rejected_at_limit(self, mock_get_limit: mock.MagicMock) -> None:
self.create_static_detector()
disabled = self.create_static_detector()
disabled.update(enabled=False)
mock_get_limit.return_value = 1

validator = MetricIssueDetectorValidator(
instance=disabled, data={"enabled": True}, context=self.context, partial=True
)
assert validator.is_valid(), validator.errors
with self.assertRaisesMessage(
ValidationError, expected_message="Used 1/1 of allowed metric_issue monitors."
):
validator.save()

disabled.refresh_from_db()
assert disabled.enabled is False

@mock.patch("sentry.quotas.backend.get_metric_detector_limit", return_value=2)
@with_feature("organizations:workflow-engine-metric-detector-limit")
def test_enable_allowed_under_limit(self, mock_get_limit: mock.MagicMock) -> None:
self.create_static_detector()
disabled = self.create_static_detector()
disabled.update(enabled=False)

validator = MetricIssueDetectorValidator(
instance=disabled, data={"enabled": True}, context=self.context, partial=True
)
assert validator.is_valid(), validator.errors
assert validator.save().enabled is True

@mock.patch("sentry.quotas.backend.get_metric_detector_limit", return_value=2)
@with_feature("organizations:workflow-engine-metric-detector-limit")
def test_disable_and_edit_allowed_over_limit(self, mock_get_limit: mock.MagicMock) -> None:
first = self.create_static_detector()
second = self.create_static_detector()
mock_get_limit.return_value = 1

disable = MetricIssueDetectorValidator(
instance=first, data={"enabled": False}, context=self.context, partial=True
)
assert disable.is_valid(), disable.errors
assert disable.save().enabled is False

rename = MetricIssueDetectorValidator(
instance=second, data={"name": "Renamed"}, context=self.context, partial=True
)
assert rename.is_valid(), rename.errors
assert rename.save().name == "Renamed"

def test_update_data_source_ignores_subscription_outside_detector_project(self) -> None:
detector = self.create_static_detector()
other_project = self.create_project(organization=self.create_organization())
Expand Down
68 changes: 68 additions & 0 deletions tests/sentry/incidents/test_metric_detector_quota.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
from typing import Any
from unittest import mock

from sentry.constants import ObjectStatus
from sentry.grouping.grouptype import ErrorGroupType
from sentry.incidents.grouptype import MetricIssue
from sentry.incidents.metric_detector_quota import (
can_enable_metric_detectors,
get_metric_detector_quota,
)
from sentry.testutils.cases import TestCase
from sentry.testutils.helpers.features import with_feature
from sentry.workflow_engine.models import Detector


@with_feature("organizations:workflow-engine-metric-detector-limit")
@mock.patch("sentry.quotas.backend.get_metric_detector_limit", return_value=2)
class MetricDetectorQuotaTest(TestCase):
def _metric_detector(self, **kwargs: Any) -> Detector:
return self.create_detector(project=self.project, type=MetricIssue.slug, **kwargs)

def test_counts_only_enabled_active_metric_detectors(self, _limit: mock.MagicMock) -> None:
self._metric_detector(enabled=True)
self._metric_detector(enabled=False)
self._metric_detector(enabled=True, status=ObjectStatus.PENDING_DELETION)
self.create_detector(project=self.project, type=ErrorGroupType.slug, enabled=True)

quota = get_metric_detector_quota(self.organization)

assert quota.count == 1
assert quota.limit == 2
assert not quota.has_exceeded

def test_disabled_detectors_leave_room(self, _limit: mock.MagicMock) -> None:
self._metric_detector(enabled=True)
self._metric_detector(enabled=False)
self._metric_detector(enabled=False)

assert not get_metric_detector_quota(self.organization).has_exceeded

def test_exceeded_at_limit(self, _limit: mock.MagicMock) -> None:
self._metric_detector(enabled=True)
self._metric_detector(enabled=True)

assert get_metric_detector_quota(self.organization).has_exceeded

def test_can_enable_up_to_limit(self, _limit: mock.MagicMock) -> None:
self._metric_detector(enabled=True)

quota = get_metric_detector_quota(self.organization)
assert can_enable_metric_detectors(quota, 1)
assert not can_enable_metric_detectors(quota, 2)

def test_unlimited_plan(self, limit: mock.MagicMock) -> None:
limit.return_value = -1
self._metric_detector(enabled=True)

quota = get_metric_detector_quota(self.organization)
assert not quota.has_exceeded
assert can_enable_metric_detectors(quota, 100)


@mock.patch("sentry.quotas.backend.get_metric_detector_limit", return_value=0)
class MetricDetectorQuotaFlagOffTest(TestCase):
def test_flag_off_is_unlimited(self, _limit: mock.MagicMock) -> None:
quota = get_metric_detector_quota(self.organization)
assert not quota.has_exceeded
assert can_enable_metric_detectors(quota, 5)
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from sentry.testutils.cases import APITestCase
from sentry.testutils.factories import Factories
from sentry.testutils.helpers.datetime import before_now
from sentry.testutils.helpers.features import with_feature
from sentry.testutils.outbox import outbox_runner
from sentry.testutils.pytest.fixtures import django_db_all
from sentry.testutils.silo import cell_silo_test
Expand Down Expand Up @@ -1325,6 +1326,55 @@ def test_update_detectors_enable_success(self) -> None:
assert response.data[0]["id"] == str(self.detector_three.id)
assert response.data[0]["enabled"] is True

@patch("sentry.quotas.backend.get_metric_detector_limit", return_value=3)
@with_feature("organizations:workflow-engine-metric-detector-limit")
def test_update_detectors_enable_rejected_over_metric_limit(
self, mock_get_limit: MagicMock
) -> None:
self.detector_two.update(enabled=False)
self.detector_three.update(enabled=False)

response = self.get_error_response(
self.organization.slug,
qs_params={"id": [str(self.detector_two.id), str(self.detector_three.id)]},
enabled=True,
status_code=400,
)

assert response.data["detail"] == "Used 2/3 of allowed metric_issue monitors."
self.detector_two.refresh_from_db()
self.detector_three.refresh_from_db()
assert self.detector_two.enabled is False
assert self.detector_three.enabled is False

@patch("sentry.quotas.backend.get_metric_detector_limit", return_value=3)
@with_feature("organizations:workflow-engine-metric-detector-limit")
def test_update_detectors_enable_within_metric_limit(self, mock_get_limit: MagicMock) -> None:
self.detector_two.update(enabled=False)
self.detector_three.update(enabled=False)

self.get_success_response(
self.organization.slug,
qs_params={"id": str(self.detector_three.id)},
enabled=True,
status_code=200,
)

self.detector_three.refresh_from_db()
assert self.detector_three.enabled is True

@patch("sentry.quotas.backend.get_metric_detector_limit", return_value=1)
@with_feature("organizations:workflow-engine-metric-detector-limit")
def test_update_detectors_enable_already_enabled_not_counted(
self, mock_get_limit: MagicMock
) -> None:
self.get_success_response(
self.organization.slug,
qs_params={"id": str(self.detector.id)},
enabled=True,
status_code=200,
)

def test_update_detectors_no_parameters_error(self) -> None:
response = self.get_error_response(
self.organization.slug,
Expand Down
Loading