: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(logs): enforce the logs alert cap on every create route (#129738)
Jimmy Zhu39b5b0349631
diff --git a/products/logs/backend/alert_creation.py b/products/logs/backend/alert_creation.pyindex 5eb4ae9a6b82..c4413db79f66 100644--- a/products/logs/backend/alert_creation.py+++ b/products/logs/backend/alert_creation.py@@ -4,10 +4,10 @@ import osfrom datetime import UTC, datetimefrom typing import Any-from django.db import connection-from posthog.models.team.team import Team+from products.alerts_platform.backend.facade.api import count_configurations, hold_cap_lock+from products.alerts_platform.backend.facade.contracts import SourceKindfrom products.logs.backend.alert_utils import next_allowed_check_atfrom products.logs.backend.models import LogsAlertConfiguration@@ -28,13 +28,22 @@ class AlertLimitReached(Exception):def claim_alert_slot(team_id: int) -> None:- """Serializes the team's creates until the caller's transaction ends, and raises- `AlertLimitReached` when the team is at its cap."""- with connection.cursor() as cursor:- cursor.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", [f"logs_alerts:{team_id}"])+ """Serializes the team's logs alert creates on every route, the platform's included, until the+ caller's transaction ends, and raises `AlertLimitReached` when the team is at its cap."""+ hold_cap_lock(team_id=team_id, source_kind=SourceKind.LOGS)+ check_alert_slot(team_id)+++def check_alert_slot(team_id: int) -> None:+ """Raises `AlertLimitReached` when the team is at its cap. The caller holds the cap lock."""if team_id in UNCAPPED_ALERT_TEAM_IDS:return- if LogsAlertConfiguration.objects.filter(team_id=team_id).count() >= MAX_ALERTS_PER_TEAM:+ # Every logs row, and every platform alert with no logs row. A copy stands for a logs row already+ # counted here, so copies are not counted.+ alerts = LogsAlertConfiguration.objects.filter(team_id=team_id).count() + count_configurations(+ team_id=team_id, source_kind=SourceKind.LOGS, native_only=True+ )+ if alerts >= MAX_ALERTS_PER_TEAM:raise AlertLimitReached()diff --git a/products/logs/backend/platform_ownership.py b/products/logs/backend/platform_ownership.pyindex 6e72a1155007..c3c60fcaa10d 100644--- a/products/logs/backend/platform_ownership.py+++ b/products/logs/backend/platform_ownership.py@@ -23,7 +23,7 @@ from products.alerts_platform.backend.facade.contracts import (PlatformAlertCreateRefused,PlatformAlertNotEditable,)-from products.logs.backend.alert_creation import AlertLimitReached, claim_alert_slot, first_check_at+from products.logs.backend.alert_creation import AlertLimitReached, check_alert_slot, first_check_atfrom products.logs.backend.alert_group_columns import grouping_problemfrom products.logs.backend.alert_state_machine import apply_enabledfrom products.logs.backend.facade.api import close_incident_before_delete@@ -60,14 +60,27 @@ def on_created(alert: LogsAlertConfiguration, at: datetime, *, grouping: Groupinreturn False-def create_platform_owned(*, team_id: int, edit: PlatformAlertConfigurationEdit, created_by_id: int | None) -> UUID:- """Creates a logs alert through the platform API: the logs row and the platform's copy, both owned- by the platform.- """+def admit_platform_write(+ *,+ team_id: int,+ current: PlatformAlertConfigurationEdit | None,+ edit: PlatformAlertConfigurationEdit,+ check_interval_minutes: int | None,+) -> None:+ """The per-team cap on a logs alert created through the platform. The platform holds the cap lock+ the logs API's creates also take."""+ if current is not None:+ returntry:- claim_alert_slot(team_id)+ check_alert_slot(team_id)except AlertLimitReached as error:raise PlatformAlertCreateRefused(str(error)) from error+++def create_platform_owned(*, team_id: int, edit: PlatformAlertConfigurationEdit, created_by_id: int | None) -> UUID:+ """Creates a logs alert through the platform API: the logs row and the platform's copy, both owned+ by the platform. `admit_platform_write` has already checked the cap.+ """now = timezone.now()alert = LogsAlertConfiguration(team_id=team_id,diff --git a/products/logs/backend/platform_source_config_schema.py b/products/logs/backend/platform_source_config_schema.pyindex ff6e779c59e1..9040a46e69bf 100644--- a/products/logs/backend/platform_source_config_schema.py+++ b/products/logs/backend/platform_source_config_schema.py@@ -20,7 +20,7 @@ from products.logs.backend.alert_deletion import delete_platform_ownedfrom products.logs.backend.alert_group_columns import grouping_problemfrom products.logs.backend.alert_source_cycle import EVENT_IDS_BY_INCIDENT_ACTIONfrom products.logs.backend.models import LogsAlertConfiguration-from products.logs.backend.platform_ownership import create_platform_owned, mirror_platform_edit+from products.logs.backend.platform_ownership import admit_platform_write, create_platform_owned, mirror_platform_editfrom products.logs.backend.platform_source_config import WindowMinutes, has_any_filter, logs_alert_url@@ -68,6 +68,7 @@ def validate_logs_edit(edit: PlatformAlertConfigurationEdit) -> None:LOGS_SOURCE_CONFIG = SourceConfigSpec(model=LogsPlatformAlertSourceConfig,validate=validate_logs_edit,+ admit=admit_platform_write,mirror=mirror_platform_edit,create=create_platform_owned,delete=delete_platform_owned,diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.pyindex d06a0a1e9aac..ce47a85e0605 100644--- a/products/logs/backend/test/test_alerts_api.py+++ b/products/logs/backend/test/test_alerts_api.py@@ -726,19 +726,36 @@ class TestLogsAlertAPI(APIBaseTest):@parameterized.expand([- ("capped", False, status.HTTP_400_BAD_REQUEST, MAX_ALERTS_PER_TEAM),- ("uncapped", True, status.HTTP_201_CREATED, MAX_ALERTS_PER_TEAM + 1),+ ("capped", False, "logs_rows", status.HTTP_400_BAD_REQUEST, 0),+ ("uncapped", True, "logs_rows", status.HTTP_201_CREATED, 1),+ ("capped_by_alerts_only_on_the_platform", False, "platform_only", status.HTTP_400_BAD_REQUEST, 0),+ ("not_capped_by_copies_of_deleted_alerts", False, "copies_of_deleted_rows", status.HTTP_201_CREATED, 1),])- def test_per_team_limit(self, _name, uncapped, expected_status, expected_count):+ def test_per_team_limit(+ self, _name: str, uncapped: bool, existing: str, expected_status: int, created: int+ ) -> None:for i in range(MAX_ALERTS_PER_TEAM):- LogsAlertConfiguration.objects.create(- team=self.team,- name=f"Alert {i}",- threshold_count=1,- created_by=self.user,- filters={"severityLevels": ["error"]},- )+ if existing != "logs_rows":+ with team_scope(self.team.id):+ platform_testing.create_configuration(+ team_id=self.team.id,+ name=f"Alert {i}",+ source_kind="logs",+ source_config={},+ check_interval_minutes=5,+ owner="platform" if existing == "platform_only" else "source",+ legacy_configuration_id=uuid4() if existing == "copies_of_deleted_rows" else None,+ )+ else:+ LogsAlertConfiguration.objects.create(+ team=self.team,+ name=f"Alert {i}",+ threshold_count=1,+ created_by=self.user,+ filters={"severityLevels": ["error"]},+ )+ logs_rows_before = LogsAlertConfiguration.objects.filter(team=self.team).count()patched_ids = frozenset({self.team.id}) if uncapped else frozenset()with patch("products.logs.backend.alert_creation.UNCAPPED_ALERT_TEAM_IDS", patched_ids):@@ -748,7 +765,7 @@ class TestLogsAlertAPI(APIBaseTest):format="json",)assert response.status_code == expected_status- assert LogsAlertConfiguration.objects.filter(team=self.team).count() == expected_count+ assert LogsAlertConfiguration.objects.filter(team=self.team).count() == logs_rows_before + created# --- Read-only fields ---