:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(alerts): enforce insight, metrics and warehouse caps on the platform (#129739)
Jimmy Zhu18281454c55c
diff --git a/products/alerts/backend/models/alert.py b/products/alerts/backend/models/alert.pyindex af341988bb35..809bc13ff443 100644--- a/products/alerts/backend/models/alert.py+++ b/products/alerts/backend/models/alert.py@@ -343,20 +343,41 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):def check_alert_limit(cls, team_id: int, organization: Organization) -> str | None:"""Return an error message if the team has reached its alert limit, else None."""alerts_feature = organization.get_available_feature(AvailableFeature.ALERTS)- existing_count = cls.objects.filter(team_id=team_id).count()if alerts_feature:allowed = alerts_feature.get("limit")# If allowed is None then the user is allowed unlimited alerts- if allowed is not None and existing_count >= allowed:+ if allowed is not None and cls._counted(team_id) >= allowed:return f"Your team has reached the limit of {allowed} alerts on your plan."else:# If the org doesn't have alerts feature, limit to that on free tier- if existing_count >= cls.ALERTS_ALLOWED_ON_FREE_TIER:+ if cls._counted(team_id) >= cls.ALERTS_ALLOWED_ON_FREE_TIER:return f"Your plan is limited to {cls.ALERTS_ALLOWED_ON_FREE_TIER} alerts."return None+ @classmethod+ def _counted(cls, team_id: int, *, active_real_time: bool = False, exclude_id: str | None = None) -> int:+ """The team's insight alerts: each insight row, and each platform alert with no insight row."""+ # Deferred: the platform's read logic stays off django.setup(), where this model loads in every process.+ from products.alerts_platform.backend.facade.api import count_configurations # noqa: PLC0415+ from products.alerts_platform.backend.facade.contracts import SourceKind # noqa: PLC0415+ from products.alerts_platform.backend.facade.scheduling import REAL_TIME_CADENCE_MINUTES # noqa: PLC0415++ rows = cls.objects.filter(team_id=team_id)+ if active_real_time:+ rows = rows.filter(calculation_interval=AlertCalculationInterval.REAL_TIME, enabled=True)+ if exclude_id:+ rows = rows.exclude(pk=exclude_id)+ native = count_configurations(+ team_id=team_id,+ source_kind=SourceKind.INSIGHT,+ native_only=True,+ enabled_only=active_real_time,+ check_interval_minutes=REAL_TIME_CADENCE_MINUTES if active_real_time else None,+ )+ return rows.count() + native+@classmethoddef supports_high_frequency_intervals(cls, organization: Organization) -> bool:return organization.is_feature_available(AvailableFeature.HIGH_FREQUENCY_ALERTS)@@ -421,10 +442,7 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):if allowed is None:return None- qs = cls.objects.filter(team_id=team_id, calculation_interval=AlertCalculationInterval.REAL_TIME, enabled=True)- if exclude_id:- qs = qs.exclude(pk=exclude_id)- existing_count = qs.count()+ existing_count = cls._counted(team_id, active_real_time=True, exclude_id=exclude_id)if existing_count >= allowed:return f"Your team has reached the limit of {allowed} real-time alerts on your plan."return Nonediff --git a/products/alerts/backend/platform_ownership.py b/products/alerts/backend/platform_ownership.pyindex cd6892a4b425..8e789d7f8e59 100644--- a/products/alerts/backend/platform_ownership.py+++ b/products/alerts/backend/platform_ownership.py@@ -14,6 +14,8 @@ from uuid import UUIDfrom django.db import transaction+from posthog.models.team.team import Team+from products.alerts.backend.evaluation.validation import validate_alert_configfrom products.alerts.backend.facade.contracts import PlatformCannotOwnfrom products.alerts.backend.insight_alert_state_machine import apply_disable, apply_enable, apply_threshold_change@@ -26,12 +28,13 @@ from products.alerts.backend.platform_cutover import (has_begun_cutover,in_an_environment,)-from products.alerts.backend.platform_source_cycle import platform_upsert_of+from products.alerts.backend.platform_source_cycle import interval_of, platform_upsert_offrom products.alerts_platform.backend.facade.api import close_owned_firings_now, delete_copy, update_owned_copyfrom products.alerts_platform.backend.facade.contracts import (SOURCE_CONDITION_KEY,InvalidPlatformAlertEdit,PlatformAlertConfigurationEdit,+ PlatformAlertCreateRefused,PlatformAlertUpsert,)from products.alerts_platform.backend.facade.enums import PlatformAlertOwner@@ -153,7 +156,7 @@ def mirror_platform_edit("""Locks the insight row of an alert edited through the platform API, and returns its writer."""alert = (AlertConfiguration.objects.select_for_update(no_key=True, of=("self",))- .select_related("threshold", "insight", "team__organization")+ .select_related("threshold", "insight")# A copy lives on the project's team. An insight alert in one of its environments is never# handed over, so the copy of one is the insight stack's and refuses the edit..filter(team_id=team_id, id=legacy_configuration_id)@@ -175,20 +178,6 @@ def _write_insight_row(alert: AlertConfiguration, edit: PlatformAlertConfigurati"enabled","An AI detector alert can't be turned back on through this API. Turn it on in the insight's alert settings.",)- if edit.enabled and not alert.enabled:- # The insight API and the Max tool check the plan and the active real-time limit before they- # turn an alert on. Without the plan check, the next evaluation would switch it off again.- organization = alert.team.organization- if admission_error := AlertConfiguration.interval_entitlement_error(- calculation_interval=alert.calculation_interval, organization=organization- ) or AlertConfiguration.real_time_alert_validation_error(- team_id=alert.team_id,- organization=organization,- calculation_interval=alert.calculation_interval,- enabled=True,- existing=alert,- ):- raise InvalidPlatformAlertEdit("enabled", admission_error)condition = edit.source_config[SOURCE_CONDITION_KEY]if condition.get("detector") != alert.detector_config:# A detector config is checked against its insight and its access rules in the insight API only.@@ -221,6 +210,33 @@ def _write_insight_row(alert: AlertConfiguration, edit: PlatformAlertConfiguratialert.save(update_fields=list(dict.fromkeys(update_fields)))+def admit_platform_write(+ *,+ team_id: int,+ current: PlatformAlertConfigurationEdit | None,+ edit: PlatformAlertConfigurationEdit,+ check_interval_minutes: int | None,+) -> None:+ """The plan limits on an insight alert created or turned on through the platform, the same ones the+ insight API and the Max tool check. A create counts against the plan's alerts. An enabled alert+ needs the plan to include its cadence, and a real-time one counts against the active real-time+ limit. Without these, the next evaluation would switch the alert off again."""+ organization = Team.objects.select_related("organization").get(id=team_id).organization+ interval = interval_of(check_interval_minutes) if edit.enabled and check_interval_minutes else None+ error = (+ (AlertConfiguration.check_alert_limit(team_id, organization) if current is None else None)+ or AlertConfiguration.interval_entitlement_error(calculation_interval=interval, organization=organization)+ or AlertConfiguration.real_time_alert_validation_error(+ team_id=team_id, organization=organization, calculation_interval=interval, enabled=True+ )+ )+ if error is None:+ return+ if current is None:+ raise PlatformAlertCreateRefused(error)+ raise InvalidPlatformAlertEdit("enabled", error)++def _threshold_of(alert: AlertConfiguration) -> dict | None:return alert.threshold.configuration if alert.threshold else Nonediff --git a/products/alerts/backend/platform_source_config_schema.py b/products/alerts/backend/platform_source_config_schema.pyindex 3689e15e88a1..bec3d34d603f 100644--- a/products/alerts/backend/platform_source_config_schema.py+++ b/products/alerts/backend/platform_source_config_schema.py@@ -12,7 +12,7 @@ from pydantic import BaseModel, ConfigDict, Fieldfrom posthog.schema import AlertCondition, InsightThresholdfrom products.alerts.backend.facade.contracts import INSIGHT_EVENT_IDS_BY_INCIDENT_ACTION-from products.alerts.backend.platform_ownership import mirror_platform_edit+from products.alerts.backend.platform_ownership import admit_platform_write, mirror_platform_editfrom products.alerts_platform.backend.facade.contracts import (GroupingMode,InvalidPlatformAlertEdit,@@ -63,6 +63,7 @@ def validate_insight_edit(edit: PlatformAlertConfigurationEdit) -> None:INSIGHT_SOURCE_CONFIG = SourceConfigSpec(model=InsightPlatformAlertSourceConfig,validate=validate_insight_edit,+ admit=admit_platform_write,mirror=mirror_platform_edit,incident_event_ids=INSIGHT_EVENT_IDS_BY_INCIDENT_ACTION,)diff --git a/products/alerts/backend/platform_source_cycle.py b/products/alerts/backend/platform_source_cycle.pyindex 2069a90aa1b9..e3bbd9f5f6d3 100644--- a/products/alerts/backend/platform_source_cycle.py+++ b/products/alerts/backend/platform_source_cycle.py@@ -225,6 +225,11 @@ SETTINGS_FIELDS: Final = ()+def interval_of(check_interval_minutes: int) -> str | None:+ """The insight cadence a platform alert's `check_interval_minutes` stands for, or None for one insight has not."""+ return next((interval for interval, (minutes, _) in _RECURRENCE.items() if minutes == check_interval_minutes), None)++def platform_upsert_of(alert: AlertConfiguration) -> PlatformAlertUpsert | None:"""The copy of one alert, or None when the platform does not evaluate it in parallel."""recurrence = _RECURRENCE.get(alert.calculation_interval or "")diff --git a/products/alerts/backend/tests/api/test_alert.py b/products/alerts/backend/tests/api/test_alert.pyindex b23240743a85..c652c549c8e9 100644--- a/products/alerts/backend/tests/api/test_alert.py+++ b/products/alerts/backend/tests/api/test_alert.py@@ -2,6 +2,7 @@ import jsonfrom copy import deepcopyfrom datetime import UTC, datetime, timedeltafrom typing import Any+from uuid import uuid4import time_machinefrom posthog.test.base import APIBaseTest, QueryMatchingTest@@ -23,6 +24,7 @@ from posthog.errors import CHQueryErrorNoCommonTypefrom posthog.models import Userfrom posthog.models.integration import Integrationfrom posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.scoping import team_scopefrom posthog.models.team import Teamfrom posthog.models.utils import generate_random_token_personal, hash_key_value@@ -33,6 +35,7 @@ from products.alerts.backend.judge.verdict import LLMDetectionVerdictfrom products.alerts.backend.logic.insight_alert_destinations import SLACK_TEMPLATE_IDfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Thresholdfrom products.alerts.backend.presentation.views.alert import AlertSerializer+from products.alerts_platform.backend.facade import testing as platform_testingfrom products.alerts_platform.backend.facade.contracts import AlertDeliveryfrom products.alerts_platform.backend.facade.scheduling import CalendarInterval, alert_check_offsetfrom products.cdp.backend.facade.models import HogFunction@@ -784,7 +787,14 @@ class TestAlert(TrendsInsightAPITest, QueryMatchingTest):assert serialized["deliveries"] == expected_deliveriesassert serialized["targets_notified"] is expected_targets_notified- def test_alert_limit(self) -> None:+ @parameterized.expand(+ [+ ("first_alert_on_insight", "insight", "invalid_input"),+ ("first_alert_only_on_the_platform", "platform_only", "invalid_input"),+ ("copy_of_a_deleted_alert", "copy_of_a_deleted_row", None),+ ]+ )+ def test_alert_limit(self, _name: str, first: str, refused_code: str | None) -> None:with mock.patch("products.alerts.backend.presentation.views.alert.AlertConfiguration.ALERTS_ALLOWED_ON_FREE_TIER") as alert_limit:@@ -800,11 +810,23 @@ class TestAlert(TrendsInsightAPITest, QueryMatchingTest):"threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "alert name",}- self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request)+ if first == "insight":+ self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request)+ else:+ with team_scope(self.team.id):+ platform_testing.create_configuration(+ team_id=self.team.id,+ name="alert name",+ source_kind="insight",+ source_config={},+ check_interval_minutes=60,+ owner="platform" if first == "platform_only" else "source",+ legacy_configuration_id=uuid4() if first == "copy_of_a_deleted_row" else None,+ )alert_2 = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request).json()- assert alert_2["code"] == "invalid_input"+ assert alert_2.get("code") == refused_codedef test_alert_is_deleted_on_insight_update(self) -> None:another_insight = self.client.post(diff --git a/products/alerts/backend/tests/api/test_alert_platform_owned.py b/products/alerts/backend/tests/api/test_alert_platform_owned.pyindex c0694f565e24..5588cf1bc6c6 100644--- a/products/alerts/backend/tests/api/test_alert_platform_owned.py+++ b/products/alerts/backend/tests/api/test_alert_platform_owned.py@@ -41,6 +41,7 @@ from products.alerts_platform.backend.facade.contracts import (VerdictChange,)from products.alerts_platform.backend.facade.enums import HoldRelease, HoldReleasedBy+from products.alerts_platform.backend.facade.scheduling import REAL_TIME_CADENCE_MINUTESfrom products.notebooks.backend.facade.api import create_notebook@@ -384,6 +385,9 @@ class TestPlatformOwnedInsightAlertWrites(APIBaseTest):self.organization.save()self._edit_on_the_platform(lambda stored: replace(stored, enabled=False))AlertConfiguration.objects.filter(id=self.alert.id).update(**stored)+ if stored.get("calculation_interval") == AlertCalculationInterval.REAL_TIME:+ with team_scope(self.team.id):+ platform_testing.set_check_interval_minutes(self.copy_id, REAL_TIME_CADENCE_MINUTES)with (patch.object(AlertConfiguration, "check_real_time_alert_limit", return_value=real_time_limit_error),diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.pyindex 884d859188e5..6daa2c2ac07c 100644--- a/products/alerts_platform/backend/facade/contracts.py+++ b/products/alerts_platform/backend/facade/contracts.py@@ -1151,6 +1151,8 @@ class NativeAlertLifecycle:"""check_interval_minutes: int+ # The most alerts of the kind a team can have, or None for no cap.+ max_per_team: int | None = None# Removes the source's HogFunction destinations of a deleted alert. None for a kind whose# destinations are `AlertDestination` rows from the start, which go with the configuration.remove_destinations: NativeAlertRemoveDestinations | None = Nonediff --git a/products/alerts_platform/backend/facade/testing.py b/products/alerts_platform/backend/facade/testing.pyindex 04feda2f6cf7..27a54018ac6d 100644--- a/products/alerts_platform/backend/facade/testing.py+++ b/products/alerts_platform/backend/facade/testing.py@@ -193,6 +193,12 @@ def set_check_status(configuration_id: UUID, check_status: str) -> None:PlatformAlertConfiguration.objects.filter(id=configuration_id).update(check_status=check_status)+def set_check_interval_minutes(configuration_id: UUID, minutes: int) -> None:+ """Set a configuration's cadence, as an edit to its source's row leaves it. The caller holds the team scope."""+ # nosemgrep: idor-lookup-without-team — fail-closed model; the caller holds the team scope+ PlatformAlertConfiguration.objects.filter(id=configuration_id).update(check_interval_minutes=minutes)++def set_enabled(configuration_id: UUID, enabled: bool) -> None:"""Switch a configuration on or off, as a broken check the platform owns leaves it.diff --git a/products/alerts_platform/backend/logic/platform_writes.py b/products/alerts_platform/backend/logic/platform_writes.pyindex 41108326094a..282e4b781354 100644--- a/products/alerts_platform/backend/logic/platform_writes.py+++ b/products/alerts_platform/backend/logic/platform_writes.py@@ -29,6 +29,7 @@ from products.alerts_platform.backend.facade.contracts import (NativeAlertLifecycle,PlatformAlertConfigurationEdit,PlatformAlertConfigurationView,+ PlatformAlertCreateRefused,PlatformAlertNotEditable,PlatformAlertSnapshot,PlatformAlertUpsert,@@ -142,10 +143,18 @@ def _admit() -> None:"""Runs the source's admission for a write, in the caller's transaction."""spec = source_configs.spec(source_kind)- if spec is None or spec.admit is None:+ if spec is None:+ return+ cap = spec.native.max_per_team if spec.native is not None and current is None else None+ if spec.admit is None and cap is None:returnhold_cap_lock(team_id, source_kind)- spec.admit(team_id=team_id, current=current, edit=edit, check_interval_minutes=check_interval_minutes)+ if cap is not None and platform_reads.count_configurations(team_id=team_id, source_kind=source_kind.value) >= cap:+ raise PlatformAlertCreateRefused(+ f"This project has reached the limit of {cap} alerts of this type. Delete one to add another."+ )+ if spec.admit is not None:+ spec.admit(team_id=team_id, current=current, edit=edit, check_interval_minutes=check_interval_minutes)def update_configuration(diff --git a/products/alerts_platform/backend/tests/test_native_alerts.py b/products/alerts_platform/backend/tests/test_native_alerts.pyindex e8412f36efa4..6c74aa33bb8d 100644--- a/products/alerts_platform/backend/tests/test_native_alerts.py+++ b/products/alerts_platform/backend/tests/test_native_alerts.py@@ -136,10 +136,10 @@ class TestNativeAlerts(ClickhouseTestMixin, APIBaseTest):check_interval_minutes: int | None,) -> None:admitted.append((current is None, edit.enabled, check_interval_minutes))- if current is None and count_configurations(team_id=team_id, source_kind=SourceKind.LOGS) >= 1:- raise PlatformAlertCreateRefused("At the cap.")- with patch(_SOURCE_CONFIGS, return_value=replace(self.spec, admit=admit)):+ assert self.spec.native is not None+ capped = replace(self.spec, admit=admit, native=replace(self.spec.native, max_per_team=1))+ with patch(_SOURCE_CONFIGS, return_value=capped):configuration_id = self._create()with pytest.raises(PlatformAlertCreateRefused):self._create()@@ -157,7 +157,7 @@ class TestNativeAlerts(ClickhouseTestMixin, APIBaseTest):change=lambda current: replace(current, enabled=True),)- assert admitted == [(True, True, 5), (True, True, 5), (False, True, 5)]+ assert admitted == [(True, True, 5), (False, True, 5)]assert count_configurations(team_id=self.team.id, source_kind=SourceKind.LOGS) == 1def test_deleting_a_firing_native_alert_resolves_by_its_own_id_before_its_destinations_go(self) -> None:diff --git a/products/metrics/backend/alerts/source_config.py b/products/metrics/backend/alerts/source_config.pyindex 3b678f6f2040..7099dc9edb46 100644--- a/products/metrics/backend/alerts/source_config.py+++ b/products/metrics/backend/alerts/source_config.py@@ -18,6 +18,7 @@ from products.metrics.backend.alerts.wording import alert_url# A metrics alert checks the latest value of each series, so it runs as often as the platform allows.CHECK_INTERVAL_MINUTES: Final = 1+MAX_ALERTS_PER_TEAM: Final = 20MAX_QUERY_LENGTH: Final = 10_000# Words rather than symbols, because generated API clients build enum keys from the values.@@ -70,7 +71,7 @@ METRICS_ALERT_CONFIG: Final = SourceConfigSpec(model=MetricsPlatformAlertConfig,validate=_validate_edit,# No `remove_destinations`, so the alert's destinations are `AlertDestination` rows from the start.- native=NativeAlertLifecycle(check_interval_minutes=CHECK_INTERVAL_MINUTES),+ native=NativeAlertLifecycle(check_interval_minutes=CHECK_INTERVAL_MINUTES, max_per_team=MAX_ALERTS_PER_TEAM),incident_event_ids=EVENT_IDS_BY_INCIDENT_ACTION,alert_url=alert_url,rollout_flag="platform-alerts-source-metrics",diff --git a/products/warehouse_sources/backend/sync_alerts/source_config.py b/products/warehouse_sources/backend/sync_alerts/source_config.pyindex 70088265de1b..b0e0d319664d 100644--- a/products/warehouse_sources/backend/sync_alerts/source_config.py+++ b/products/warehouse_sources/backend/sync_alerts/source_config.py@@ -35,6 +35,7 @@ from products.warehouse_sources.backend.sync_alerts.wording import (# A sync status changes at most once per sync, so a few minutes of delay costs nothing a user notices.CHECK_INTERVAL_MINUTES: Final = 5+MAX_ALERTS_PER_TEAM: Final = 20MAX_SCOPED_IDS: Final = 100_EMAIL_PROJECT_MEMBERS_HELP = (@@ -133,7 +134,7 @@ def _spec(validate=validate,check_in_team=check_in_team,# No `remove_destinations`, so the platform owns the destinations from the start.- native=NativeAlertLifecycle(check_interval_minutes=CHECK_INTERVAL_MINUTES),+ native=NativeAlertLifecycle(check_interval_minutes=CHECK_INTERVAL_MINUTES, max_per_team=MAX_ALERTS_PER_TEAM),incident_event_ids=EVENT_IDS_BY_INCIDENT_ACTION[source_kind],alert_url=alert_url,access_flag=WAREHOUSE_ALERTS_FLAG,