Skip to content

: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.

feat(alerts): open warehouse alerts in the platform API on their own flag (#128659)

Jimmy Zhu73b6e452632f
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index aa38de114349..d1664598ff68 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -459,6 +459,7 @@ export const FEATURE_FLAGS = {
PI_ACP: 'pi-acp', // owner: #team-agent-infrastructure, Pi runs write ACP and show on the web run surface
PIPELINE_STATUS_PAGE: 'pipeline-status-page', // owner: @clr182 #team-support
PLATFORM_ALERTS: 'platform-alerts', // owner: #team-apm, gates the shared alerts platform read API and UI
+ PLATFORM_ALERTS_SOURCE_WAREHOUSE: 'platform-alerts-source-warehouse', // owner: #team-warehouse-sources, opens warehouse sync alerts in the platform API without platform-alerts
POSTHOG_AI_BILLING_DISPLAY: 'posthog-ai-billing-display', // owner: #team-posthog-ai
POSTHOG_AI_CHANGELOG: 'posthog-ai-changelog', // owner: #team-posthog-ai
POSTHOG_AI_CONVERSATION_FEEDBACK_CONFIG: 'posthog-ai-conversation-feedback-config', // owner: #team-posthog-ai
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index 44d4288f06b3..a62df745fbcf 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -1164,6 +1164,10 @@ class SourceConfigSpec:
# A new kind names its own flag, so it opens on its own schedule while the others stay generally
# available.
rollout_flag: str | None = None
+ # A PostHog feature flag that opens every API action on this kind in place of `platform-alerts`.
+ # The source product can then release its alerts on its own flag, while `platform-alerts` keeps
+ # the other kinds and the platform's own pages closed.
+ access_flag: str | None = None
def __post_init__(self) -> None:
# The source-row hooks write a row a native kind does not have.
diff --git a/products/alerts_platform/backend/presentation/views/platform_alert.py b/products/alerts_platform/backend/presentation/views/platform_alert.py
index dc557d3a3c90..506b22501e1c 100644
--- a/products/alerts_platform/backend/presentation/views/platform_alert.py
+++ b/products/alerts_platform/backend/presentation/views/platform_alert.py
@@ -1,6 +1,6 @@
from dataclasses import replace
from functools import cache, cached_property
-from typing import Any, Literal, cast
+from typing import Any, Final, Literal, cast
from uuid import UUID
from django.db import transaction
@@ -9,9 +9,12 @@ from drf_spectacular.utils import OpenApiResponse, PolymorphicProxySerializer, e
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
+from rest_framework.permissions import BasePermission
from rest_framework.request import Request
from rest_framework.response import Response
+from rest_framework.views import APIView
+from posthog import permissions
from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.pagination import PrecountedLimitOffsetPagination
from posthog.api.routing import TeamAndOrgViewSetMixin
@@ -20,11 +23,9 @@ from posthog.exceptions import Conflict
from posthog.models import Team, User
from posthog.permissions import (
FEATURE_FLAG_REQUIRED_ERROR_CODE,
- PostHogFeatureFlagPermission,
get_authenticator_client,
get_authenticator_scoped_team_ids,
get_authenticator_scopes,
- posthog_feature_flag_enabled,
)
from posthog.scopes import APIScopeObject, scopes_not_covered
@@ -57,6 +58,8 @@ from products.alerts_platform.backend.facade.enums import (
from products.alerts_platform.backend.facade.source_configs import editable_source_configs
from products.alerts_platform.backend.presentation.views.schedule_restriction import ScheduleRestrictionField
+PLATFORM_ALERTS_FLAG: Final = "platform-alerts"
+
RULE_LABELS_HELP = (
'Labels that say who owns the alert and how urgent it is, such as {"team": "checkout", "severity": "critical"}. '
"Names use letters, digits and underscores. alertname and names that start with posthog_ are reserved. "
@@ -433,13 +436,53 @@ EDIT_RESPONSES = {
}
+class PlatformAlertsFlagPermission(BasePermission):
+ """Lets a caller in when the flag of at least one source kind is on. Each action then serves only
+ the kinds whose flag is on."""
+
+ message = f"This action requires feature flag {PLATFORM_ALERTS_FLAG!r} to be enabled for your organization."
+ code = FEATURE_FLAG_REQUIRED_ERROR_CODE
+
+ def has_permission(self, request: Request, view: APIView) -> bool:
+ assert isinstance(view, PlatformAlertConfigurationViewSet)
+ return bool(view.open_source_kinds)
+
+
class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
scope_object = "alert"
- posthog_feature_flag = "platform-alerts"
- permission_classes = [PostHogFeatureFlagPermission]
+ permission_classes = [PlatformAlertsFlagPermission]
serializer_class = PlatformAlertConfigurationSerializer
pagination_class = PrecountedLimitOffsetPagination
+ @cached_property
+ def open_source_kinds(self) -> frozenset[str]:
+ """The kinds whose flag is on for the caller: a kind's `access_flag` when it has one, and
+ `platform-alerts` otherwise."""
+ specs = editable_source_configs()
+ flag_of_kind: dict[str, str] = {}
+ for source_kind in SOURCE_KIND_RESOURCE:
+ spec = specs.get(SourceKind(source_kind))
+ flag_of_kind[source_kind] = (
+ spec.access_flag if spec is not None and spec.access_flag else PLATFORM_ALERTS_FLAG
+ )
+ enabled = {flag: self._flag_enabled(flag) for flag in set(flag_of_kind.values())}
+ return frozenset(kind for kind, flag in flag_of_kind.items() if enabled[flag])
+
+ def _flag_required(self, source_kind: str) -> PermissionDenied:
+ label = PlatformAlertConfigurationSourceKind(source_kind).label
+ return PermissionDenied(
+ f"{label} alerts are not available for this project yet.", code=FEATURE_FLAG_REQUIRED_ERROR_CODE
+ )
+
+ def _flag_enabled(self, flag: str) -> bool:
+ return permissions.posthog_feature_flag_enabled(
+ flag,
+ str(cast(User, self.request.user).distinct_id),
+ organization_id=self.team.organization_id,
+ team_id=self.team.id,
+ caller_properties=get_authenticator_client(getattr(self.request, "successful_authenticator", None)),
+ )
+
@cached_property
def canonical_team(self) -> Team:
# The rows live on the parent team, so a child environment reads its parent's.
@@ -476,6 +519,8 @@ class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.Generic
token_scopes = get_authenticator_scopes(getattr(self.request, "successful_authenticator", None))
permitted: list[str] = []
for source_kind, resource in SOURCE_KIND_RESOURCE.items():
+ if source_kind not in self.open_source_kinds:
+ continue
if not self.user_access_control.check_access_level_for_resource(resource, access_level):
continue
if (
@@ -547,11 +592,12 @@ class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.Generic
if self.team.parent_team_id is not None:
raise Conflict("This URL names an environment. Create its alerts on that environment's logs alerts page.")
source_kind = request.data.get("source_kind") if isinstance(request.data, dict) else None
- create_serializer = create_serializers().get(source_kind) if isinstance(source_kind, str) else None
- if create_serializer is None:
+ if not isinstance(source_kind, str) or (create_serializer := create_serializers().get(source_kind)) is None:
raise ValidationError(
{"source_kind": f"Must be one of: {', '.join(sorted(create_serializers()))}."}, code="invalid_choice"
)
+ if source_kind not in self.open_source_kinds:
+ raise self._flag_required(source_kind)
# The kind comes from the body, so the source product's scope and access are checked here
# rather than through `required_scopes`.
if source_kind not in self._source_kinds_with("editor", "write"):
@@ -583,17 +629,8 @@ class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.Generic
spec = editable_source_configs().get(source_kind)
if spec is None or spec.rollout_flag is None:
return
- if not posthog_feature_flag_enabled(
- spec.rollout_flag,
- str(cast(User, self.request.user).distinct_id),
- organization_id=self.team.organization_id,
- team_id=self.team.id,
- caller_properties=get_authenticator_client(getattr(self.request, "successful_authenticator", None)),
- ):
- raise PermissionDenied(
- f"{source_kind.value.capitalize()} alerts are not available for this project yet.",
- code=FEATURE_FLAG_REQUIRED_ERROR_CODE,
- )
+ if not self._flag_enabled(spec.rollout_flag):
+ raise self._flag_required(source_kind.value)
def _track(self, action: Literal["created", "deleted"], configuration: PlatformAlertConfigurationView) -> None:
report_user_action(
diff --git a/products/alerts_platform/backend/tests/api/test_platform_alert.py b/products/alerts_platform/backend/tests/api/test_platform_alert.py
index 6cca7a1c3dc9..80a74c95da05 100644
--- a/products/alerts_platform/backend/tests/api/test_platform_alert.py
+++ b/products/alerts_platform/backend/tests/api/test_platform_alert.py
@@ -62,6 +62,49 @@ class TestPlatformAlertAPI(APIBaseTest):
assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
assert response.json()["code"] == "feature_flag_required"
+ @parameterized.expand(
+ [
+ ("platform_alerts_only", {"platform-alerts"}, ["logs"], status.HTTP_403_FORBIDDEN),
+ (
+ "warehouse_flag_only",
+ {"platform-alerts-source-warehouse"},
+ ["warehouse_source"],
+ status.HTTP_400_BAD_REQUEST,
+ ),
+ (
+ "both",
+ {"platform-alerts", "platform-alerts-source-warehouse"},
+ ["logs", "warehouse_source"],
+ status.HTTP_400_BAD_REQUEST,
+ ),
+ ]
+ )
+ def test_each_kind_opens_on_its_own_flag(
+ self, _name: str, flags_on: set[str], visible_kinds: list[str], warehouse_create_status: int
+ ) -> None:
+ self.enterContext(
+ patch(
+ "posthog.permissions.posthog_feature_flag_enabled",
+ side_effect=lambda flag, *_args, **_kwargs: flag in flags_on,
+ )
+ )
+ self._create_configuration(self.team, "API errors")
+ self._create_configuration(
+ self.team, "Stripe failing", source_kind=PlatformAlertConfiguration.SourceKind.WAREHOUSE_SOURCE
+ )
+
+ listed = self.client.get(f"/api/projects/{self.team.id}/platform_alerts/")
+ # An empty body passes the flag check and fails validation, so 400 means the kind is open.
+ create = self.client.post(
+ f"/api/projects/{self.team.id}/platform_alerts/", {"source_kind": "warehouse_source"}, format="json"
+ )
+
+ assert listed.status_code == status.HTTP_200_OK, listed.json()
+ assert sorted(row["source_kind"] for row in listed.json()["results"]) == visible_kinds
+ assert create.status_code == warehouse_create_status, create.json()
+ if warehouse_create_status == status.HTTP_403_FORBIDDEN:
+ assert create.json()["code"] == "feature_flag_required"
+
def test_list_returns_own_configurations_with_nested_alerts(self) -> None:
self._set_flag(True)
legacy_configuration_id = uuid4()
diff --git a/products/warehouse_sources/backend/facade/sync_alerts.py b/products/warehouse_sources/backend/facade/sync_alerts.py
index 20664eed7f4e..8dcbf0739c8f 100644
--- a/products/warehouse_sources/backend/facade/sync_alerts.py
+++ b/products/warehouse_sources/backend/facade/sync_alerts.py
@@ -2,7 +2,8 @@
from products.warehouse_sources.backend.sync_alerts.destinations import (
WAREHOUSE_ALERT_DESTINATION_TYPES,
+ WAREHOUSE_ALERTS_FLAG,
WAREHOUSE_DESTINATION_EVENT_KINDS,
)
-__all__ = ["WAREHOUSE_DESTINATION_EVENT_KINDS", "WAREHOUSE_ALERT_DESTINATION_TYPES"]
+__all__ = ["WAREHOUSE_ALERTS_FLAG", "WAREHOUSE_DESTINATION_EVENT_KINDS", "WAREHOUSE_ALERT_DESTINATION_TYPES"]
diff --git a/products/warehouse_sources/backend/presentation/views/warehouse_alert_destinations.py b/products/warehouse_sources/backend/presentation/views/warehouse_alert_destinations.py
index 3b17a4d2b390..959bd765d0db 100644
--- a/products/warehouse_sources/backend/presentation/views/warehouse_alert_destinations.py
+++ b/products/warehouse_sources/backend/presentation/views/warehouse_alert_destinations.py
@@ -51,6 +51,7 @@ from products.alerts_platform.backend.facade.contracts import (
from products.alerts_platform.backend.facade.enums import PlatformAlertOwner
from products.warehouse_sources.backend.facade.sync_alerts import (
WAREHOUSE_ALERT_DESTINATION_TYPES,
+ WAREHOUSE_ALERTS_FLAG,
WAREHOUSE_DESTINATION_EVENT_KINDS,
)
@@ -207,7 +208,7 @@ class WarehouseAlertDestinationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericV
"""Destinations of a warehouse alert. The URL's ID is the alert's platform configuration ID."""
scope_object = "alert"
- posthog_feature_flag = "platform-alerts"
+ posthog_feature_flag = WAREHOUSE_ALERTS_FLAG
permission_classes = [PostHogFeatureFlagPermission]
def dangerously_get_required_scopes(self, request: Request, view: APIView) -> list[str]:
diff --git a/products/warehouse_sources/backend/sync_alerts/destinations.py b/products/warehouse_sources/backend/sync_alerts/destinations.py
index 1d6525d5801a..aba62506b549 100644
--- a/products/warehouse_sources/backend/sync_alerts/destinations.py
+++ b/products/warehouse_sources/backend/sync_alerts/destinations.py
@@ -15,6 +15,8 @@ from products.alerts_platform.backend.facade.contracts import (
SourceKind,
)
+WAREHOUSE_ALERTS_FLAG: Final = "platform-alerts-source-warehouse"
+
WAREHOUSE_ALERT_DESTINATION_TYPES: Final = (
DestinationType.SLACK,
DestinationType.WEBHOOK,
diff --git a/products/warehouse_sources/backend/sync_alerts/source_config.py b/products/warehouse_sources/backend/sync_alerts/source_config.py
index 68348113892a..70088265de1b 100644
--- a/products/warehouse_sources/backend/sync_alerts/source_config.py
+++ b/products/warehouse_sources/backend/sync_alerts/source_config.py
@@ -20,7 +20,10 @@ from products.alerts_platform.backend.facade.contracts import (
)
from products.warehouse_sources.backend.models.external_data_destination import ExternalDataDestination
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
-from products.warehouse_sources.backend.sync_alerts.destinations import EVENT_IDS_BY_INCIDENT_ACTION
+from products.warehouse_sources.backend.sync_alerts.destinations import (
+ EVENT_IDS_BY_INCIDENT_ACTION,
+ WAREHOUSE_ALERTS_FLAG,
+)
from products.warehouse_sources.backend.sync_alerts.wording import (
DEFAULT_GROUP_BY,
DESTINATION_ID_KEY,
@@ -133,6 +136,7 @@ def _spec(
native=NativeAlertLifecycle(check_interval_minutes=CHECK_INTERVAL_MINUTES),
incident_event_ids=EVENT_IDS_BY_INCIDENT_ACTION[source_kind],
alert_url=alert_url,
+ access_flag=WAREHOUSE_ALERTS_FLAG,
)
diff --git a/products/warehouse_sources/backend/tests/test_sync_alerts.py b/products/warehouse_sources/backend/tests/test_sync_alerts.py
index 137374a016dc..40eb0ec97dcb 100644
--- a/products/warehouse_sources/backend/tests/test_sync_alerts.py
+++ b/products/warehouse_sources/backend/tests/test_sync_alerts.py
@@ -415,6 +415,25 @@ class TestWarehouseAlerts(APIBaseTest):
assert response.status_code == expected, response.json()
+ @parameterized.expand(
+ [
+ ("platform_alerts_only", "platform-alerts", status.HTTP_403_FORBIDDEN),
+ ("warehouse_flag_only", "platform-alerts-source-warehouse", status.HTTP_200_OK),
+ ]
+ )
+ def test_destinations_open_on_the_warehouse_flag(self, _name: str, flag_on: str, expected: int) -> None:
+ configuration_id = self._alert(SourceKind.WAREHOUSE_SOURCE, {}, "source_id")
+ self.enterContext(
+ patch(
+ "posthog.permissions.posthog_feature_flag_enabled",
+ side_effect=lambda flag, *_args, **_kwargs: flag == flag_on,
+ )
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/warehouse_alerts/{configuration_id}/destinations/")
+
+ assert response.status_code == expected, response.json()
+
def test_an_alert_and_its_slack_destination_route_a_failure_to_that_channel(self) -> None:
schema = self._schema(self._source(), "charges", Status.FAILED)