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): serve the platform read api from the platform's own product (#109673)

Jimmy Zhua32c54612e0f
diff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.py
index c03a8a4539b0..a522eaf8de41 100644
--- a/posthog/test/repo_invariants/test_pagination_contract.py
+++ b/posthog/test/repo_invariants/test_pagination_contract.py
@@ -99,6 +99,7 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {
"products.ai_observability.backend.api.taggers.TaggerViewSet",
"products.ai_observability.backend.api.trace_reviews.TraceReviewViewSet",
"products.alerts.backend.presentation.views.alert.AlertViewSet",
+ "products.alerts_platform.backend.presentation.views.platform_alert.PlatformAlertConfigurationViewSet",
"products.autoresearch.backend.presentation.views.views.AutoresearchModelViewSet",
"products.autoresearch.backend.presentation.views.views.AutoresearchPipelineViewSet",
"products.autoresearch.backend.presentation.views.views.AutoresearchRunViewSet",
diff --git a/products/alerts/backend/presentation/views/alert.py b/products/alerts/backend/presentation/views/alert.py
index 514a1ccd0630..52f0d9106236 100644
--- a/products/alerts/backend/presentation/views/alert.py
+++ b/products/alerts/backend/presentation/views/alert.py
@@ -109,13 +109,13 @@ from products.alerts.backend.insight_alert_state_machine import (
apply_unsnooze,
)
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold
-from products.alerts.backend.presentation.views.schedule_restriction import AlertScheduleRestriction
from products.alerts_platform.backend.facade.contracts import (
AlertDestinationData,
AlertDestinationValidationError,
DestinationType,
)
from products.alerts_platform.backend.facade.scheduling import validate_and_normalize_schedule_start_time
+from products.alerts_platform.backend.presentation.views.schedule_restriction import ScheduleRestrictionField
from products.product_analytics.backend.facade.api import lock_insight_for_evaluation
from products.product_analytics.backend.facade.models import Insight, resolve_insight_by_id_or_short_id
@@ -458,11 +458,6 @@ class TeamScopedInsightReferenceField(TeamScopedPrimaryKeyRelatedField):
self.fail("does_not_exist", pk_value=data)
-@extend_schema_field(AlertScheduleRestriction) # type: ignore[arg-type]
-class ScheduleRestrictionField(serializers.JSONField):
- pass
-
-
class ThresholdSerializer(serializers.ModelSerializer):
configuration = ThresholdConfigurationField(
help_text="Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage). "
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.py
index c1a7b84fa73c..82500d9bca33 100644
--- a/products/alerts_platform/backend/facade/api.py
+++ b/products/alerts_platform/backend/facade/api.py
@@ -1,20 +1,24 @@
"""The shared alert tables, as a source adapter and this product's own API see them.
A source reads a batch of checks, reports what it decided, and can copy its own configurations
-in. It never holds one of these rows, so every write and every scheduling rule has one home.
+in. A reader asks for configurations and gets contracts. Neither ever holds one of these rows,
+so every write and every scheduling rule has one home.
"""
from __future__ import annotations
from collections.abc import Sequence
from datetime import datetime
+from uuid import UUID
from products.alerts_platform.backend.facade.contracts import (
PlatformAlertCheckInput,
+ PlatformAlertConfigurationPage,
+ PlatformAlertConfigurationView,
PlatformAlertOutcome,
PlatformAlertUpsert,
)
-from products.alerts_platform.backend.logic import platform_lifecycle
+from products.alerts_platform.backend.logic import platform_lifecycle, platform_reads
def due_checks(team_id: int, source_kind: str, slot: str, cutoff: datetime) -> tuple[PlatformAlertCheckInput, ...]:
@@ -35,3 +39,19 @@ def slot_of(next_check_at: datetime | None, cutoff: datetime) -> str:
def upsert_configuration(upsert: PlatformAlertUpsert) -> bool:
"""Copy one of a source's own configurations in. True when the row changed."""
return platform_lifecycle.upsert_configuration(upsert)
+
+
+def list_configurations(
+ *, team_id: int, source_kinds: Sequence[str], limit: int, offset: int
+) -> PlatformAlertConfigurationPage:
+ """One page of configurations a caller may read, with the total behind it."""
+ return platform_reads.list_configurations(team_id=team_id, source_kinds=source_kinds, limit=limit, offset=offset)
+
+
+def get_configuration(
+ *, team_id: int, source_kinds: Sequence[str], configuration_id: UUID
+) -> PlatformAlertConfigurationView | None:
+ """One configuration, or None when it does not exist or the caller may not read its kind."""
+ return platform_reads.get_configuration(
+ team_id=team_id, source_kinds=source_kinds, configuration_id=configuration_id
+ )
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index e0d4f12d0795..f08ca840318f 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -335,7 +335,7 @@ class PlatformConfigurationSnapshot:
@frozen
class PlatformAlertSnapshot:
- """One instance's runtime state, as a source's own test reads it back."""
+ """One instance's runtime state, for a reader outside this product."""
id: UUID
grouping_key: str
@@ -345,6 +345,43 @@ class PlatformAlertSnapshot:
snooze_until: datetime | None
+@frozen
+class PlatformAlertConfigurationView:
+ """One configuration and its instances, as a reader outside this product sees them.
+
+ The instances arrive with it because a reader asking for a configuration always wants its
+ runtime state, and fetching them separately would be one query per configuration.
+ """
+
+ id: UUID
+ name: str
+ enabled: bool
+ source_kind: str
+ source_config: dict[str, Any]
+ threshold_count: int
+ threshold_operator: str
+ window_minutes: int
+ check_interval_minutes: int
+ evaluation_periods: int
+ datapoints_to_alarm: int
+ cooldown_minutes: int
+ schedule_restriction: dict[str, Any] | None
+ next_check_at: datetime | None
+ consecutive_failures: int
+ legacy_configuration_id: UUID | None
+ created_at: datetime
+ updated_at: datetime
+ alerts: tuple[PlatformAlertSnapshot, ...]
+
+
+@frozen
+class PlatformAlertConfigurationPage:
+ """One page of configurations, with the total the reader needs to paginate."""
+
+ configurations: tuple[PlatformAlertConfigurationView, ...]
+ total: int
+
+
@frozen
class SourceOutcomeInputs:
team_id: int
diff --git a/products/alerts_platform/backend/facade/enums.py b/products/alerts_platform/backend/facade/enums.py
new file mode 100644
index 000000000000..c3a604d0947f
--- /dev/null
+++ b/products/alerts_platform/backend/facade/enums.py
@@ -0,0 +1,24 @@
+"""Choice vocabularies the models store and the API renders.
+
+They live here rather than on the models because a product's facade must not import Django, and
+both halves need the same list: the model to constrain what it stores, presentation to describe
+what it returns. One definition means neither can drift from the other.
+"""
+
+from posthog.enums import LabeledStrEnum
+
+
+class PlatformAlertConfigurationSourceKind(LabeledStrEnum):
+ """The product whose data an alert evaluates."""
+
+ LOGS = "logs", "Logs"
+
+
+class PlatformAlertState(LabeledStrEnum):
+ """Where one alert instance stands."""
+
+ NOT_FIRING = "not_firing", "Not firing"
+ FIRING = "firing", "Firing"
+ ERRORED = "errored", "Errored"
+ SNOOZED = "snoozed", "Snoozed"
+ BROKEN = "broken", "Broken"
diff --git a/products/alerts_platform/backend/facade/testing.py b/products/alerts_platform/backend/facade/testing.py
index 6efa0fd834b6..8c74462d0959 100644
--- a/products/alerts_platform/backend/facade/testing.py
+++ b/products/alerts_platform/backend/facade/testing.py
@@ -12,6 +12,7 @@ from typing import Any
from uuid import UUID
from products.alerts_platform.backend.facade.contracts import PlatformAlertSnapshot, PlatformConfigurationSnapshot
+from products.alerts_platform.backend.logic.platform_reads import instance_view
from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration
@@ -52,13 +53,4 @@ def count_still_due(configuration_ids: Iterable[UUID], *, at: datetime) -> int:
def alert_for(configuration_id: UUID, *, grouping_key: str = "") -> PlatformAlertSnapshot | None:
"""The instance row a check wrote, or None when no check has written one."""
row = PlatformAlert.objects.filter(configuration_id=configuration_id, grouping_key=grouping_key).first()
- if row is None:
- return None
- return PlatformAlertSnapshot(
- id=row.id,
- grouping_key=row.grouping_key,
- state=row.state,
- firing_started_at=row.firing_started_at,
- last_notified_at=row.last_notified_at,
- snooze_until=row.snooze_until,
- )
+ return None if row is None else instance_view(row)
diff --git a/products/alerts_platform/backend/logic/platform_reads.py b/products/alerts_platform/backend/logic/platform_reads.py
new file mode 100644
index 000000000000..994aaddaf0ab
--- /dev/null
+++ b/products/alerts_platform/backend/logic/platform_reads.py
@@ -0,0 +1,92 @@
+"""Reads of the shared alert tables, as a consumer outside this product sees them.
+
+Separate from `platform_lifecycle`, which serves the source adapters. These serve a reader
+outside the product, so they return views rather than rows and never change one.
+"""
+
+from collections.abc import Sequence
+from uuid import UUID
+
+from django.db.models import Prefetch, QuerySet
+
+from products.alerts_platform.backend.facade.contracts import (
+ PlatformAlertConfigurationPage,
+ PlatformAlertConfigurationView,
+ PlatformAlertSnapshot,
+)
+from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration
+
+
+def instance_view(alert: PlatformAlert) -> PlatformAlertSnapshot:
+ """One instance row as a contract. Shared with the test doors, so both describe one shape."""
+ return PlatformAlertSnapshot(
+ id=alert.id,
+ grouping_key=alert.grouping_key,
+ state=alert.state,
+ firing_started_at=alert.firing_started_at,
+ last_notified_at=alert.last_notified_at,
+ snooze_until=alert.snooze_until,
+ )
+
+
+def _configuration_view(configuration: PlatformAlertConfiguration) -> PlatformAlertConfigurationView:
+ return PlatformAlertConfigurationView(
+ id=configuration.id,
+ name=configuration.name,
+ enabled=configuration.enabled,
+ source_kind=configuration.source_kind,
+ source_config=configuration.source_config,
+ threshold_count=configuration.threshold_count,
+ threshold_operator=configuration.threshold_operator,
+ window_minutes=configuration.window_minutes,
+ check_interval_minutes=configuration.check_interval_minutes,
+ evaluation_periods=configuration.evaluation_periods,
+ datapoints_to_alarm=configuration.datapoints_to_alarm,
+ cooldown_minutes=configuration.cooldown_minutes,
+ schedule_restriction=configuration.schedule_restriction,
+ next_check_at=configuration.next_check_at,
+ consecutive_failures=configuration.consecutive_failures,
+ legacy_configuration_id=configuration.legacy_configuration_id,
+ created_at=configuration.created_at,
+ updated_at=configuration.updated_at,
+ alerts=tuple(instance_view(alert) for alert in configuration.alerts.all()),
+ )
+
+
+def _readable(team_id: int, source_kinds: Sequence[str]) -> QuerySet[PlatformAlertConfiguration]:
+ """Configurations of the given kinds belonging to `team_id`, instances prefetched.
+
+ The caller resolves which kinds it may read, because that depends on the caller's grants
+ rather than on anything this product knows.
+ """
+ instances = PlatformAlert.objects.for_team(team_id, canonical=True).order_by("grouping_key")
+ return (
+ PlatformAlertConfiguration.objects.for_team(team_id, canonical=True)
+ .filter(source_kind__in=list(source_kinds))
+ .prefetch_related(Prefetch("alerts", queryset=instances))
+ .order_by("-created_at", "-id")
+ )
+
+
+def list_configurations(
+ *, team_id: int, source_kinds: Sequence[str], limit: int, offset: int
+) -> PlatformAlertConfigurationPage:
+ """One page of configurations, newest first, with the total behind it.
+
+ The page is taken in the database rather than in the caller, so a team with many alerts
+ costs one page rather than all of them. Slicing keeps the prefetch, which resolves over the
+ page's rows alone.
+ """
+ readable = _readable(team_id, source_kinds)
+ return PlatformAlertConfigurationPage(
+ configurations=tuple(_configuration_view(row) for row in readable[offset : offset + limit]),
+ total=readable.count(),
+ )
+
+
+def get_configuration(
+ *, team_id: int, source_kinds: Sequence[str], configuration_id: UUID
+) -> PlatformAlertConfigurationView | None:
+ """One configuration, or None when it does not exist or the caller may not read its kind."""
+ row = _readable(team_id, source_kinds).filter(id=configuration_id).first()
+ return None if row is None else _configuration_view(row)
diff --git a/products/alerts_platform/backend/migrations/0002_platform_alert_list_index.py b/products/alerts_platform/backend/migrations/0002_platform_alert_list_index.py
new file mode 100644
index 000000000000..714b0945d033
--- /dev/null
+++ b/products/alerts_platform/backend/migrations/0002_platform_alert_list_index.py
@@ -0,0 +1,23 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ """The index behind the read API's page, built without locking writes out of the table."""
+
+ atomic = False
+
+ dependencies = [
+ ("alerts_platform", "0001_initial"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="platformalertconfiguration",
+ index=models.Index(
+ fields=["team_id", "-created_at", "-id"],
+ name="platform_alert_cfg_list_idx",
+ ),
+ ),
+ ]
diff --git a/products/alerts_platform/backend/migrations/max_migration.txt b/products/alerts_platform/backend/migrations/max_migration.txt
index cbab66dde92a..8daaff59ef9a 100644
--- a/products/alerts_platform/backend/migrations/max_migration.txt
+++ b/products/alerts_platform/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0001_initial
+0002_platform_alert_list_index
diff --git a/products/alerts_platform/backend/models/platform_alert.py b/products/alerts_platform/backend/models/platform_alert.py
index 8b35770638bf..f43c7a53c75a 100644
--- a/products/alerts_platform/backend/models/platform_alert.py
+++ b/products/alerts_platform/backend/models/platform_alert.py
@@ -13,6 +13,8 @@ from django.db import models
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.utils import UUIDModel
+from products.alerts_platform.backend.facade.enums import PlatformAlertConfigurationSourceKind, PlatformAlertState
+
class PlatformAlertConfiguration(TeamScopedRootMixin, UUIDModel):
"""What to evaluate, how often, and against what bound.
@@ -21,8 +23,10 @@ class PlatformAlertConfiguration(TeamScopedRootMixin, UUIDModel):
fails the whole evaluation rather than one group of its results.
"""
- class SourceKind(models.TextChoices):
- LOGS = "logs", "Logs"
+ # The facade owns the vocabulary, because presentation needs the same list and may not
+ # import this module. The attribute stays so `PlatformAlertConfiguration.SourceKind` reads
+ # the way every other model in the repo does.
+ SourceKind = PlatformAlertConfigurationSourceKind
# No database constraint: creating one takes a lock on `posthog_team` that queues behind
# live writes. Django still cascades in Python, which is the only path that deletes a team.
@@ -73,6 +77,13 @@ class PlatformAlertConfiguration(TeamScopedRootMixin, UUIDModel):
fields=["team_id", "enabled", "source_kind", "next_check_at"],
name="platform_alert_cfg_batch_idx",
),
+ # The read API's page. `source_kind` stays out of it: the API filters that column
+ # with IN, which cannot yield globally ordered rows, so including it would put
+ # back the sort this index exists to remove.
+ models.Index(
+ fields=["team_id", "-created_at", "-id"],
+ name="platform_alert_cfg_list_idx",
+ ),
]
@@ -83,18 +94,15 @@ class PlatformAlert(TeamScopedRootMixin, UUIDModel):
makes one row per group, so grouping needs no schema change beyond writing a real key.
"""
- class State(models.TextChoices):
- NOT_FIRING = "not_firing", "Not firing"
- FIRING = "firing", "Firing"
- ERRORED = "errored", "Errored"
- SNOOZED = "snoozed", "Snoozed"
- BROKEN = "broken", "Broken"
+ State = PlatformAlertState
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")
configuration = models.ForeignKey(PlatformAlertConfiguration, on_delete=models.CASCADE, related_name="alerts")
grouping_key = models.CharField(max_length=255, default="", db_default="")
- state = models.CharField(max_length=32, choices=State.choices, default=State.NOT_FIRING, db_default="not_firing")
+ state = models.CharField(
+ max_length=32, choices=State.choices, default=State.NOT_FIRING.value, db_default="not_firing"
+ )
last_notified_at = models.DateTimeField(null=True, blank=True)
snooze_until = models.DateTimeField(null=True, blank=True)
# Identifies one firing, from the transition into FIRING to the transition out. A timestamp
diff --git a/products/alerts_platform/backend/presentation/__init__.py b/products/alerts_platform/backend/presentation/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/alerts_platform/backend/presentation/views/__init__.py b/products/alerts_platform/backend/presentation/views/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/alerts_platform/backend/presentation/views/platform_alert.py b/products/alerts_platform/backend/presentation/views/platform_alert.py
new file mode 100644
index 000000000000..bc49df268a69
--- /dev/null
+++ b/products/alerts_platform/backend/presentation/views/platform_alert.py
@@ -0,0 +1,188 @@
+from functools import cached_property
+from typing import cast
+
+from drf_spectacular.utils import extend_schema
+from rest_framework import serializers, viewsets
+from rest_framework.exceptions import NotFound
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.pagination import PrecountedLimitOffsetPagination
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models import Team, User
+from posthog.permissions import PostHogFeatureFlagPermission, get_authenticator_scopes
+from posthog.scopes import APIScopeObject, scopes_not_covered
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.alerts_platform.backend.facade import api as platform_api
+from products.alerts_platform.backend.facade.enums import PlatformAlertConfigurationSourceKind, PlatformAlertState
+from products.alerts_platform.backend.presentation.views.schedule_restriction import ScheduleRestrictionField
+
+
+class PlatformAlertSerializer(serializers.Serializer):
+ id = serializers.UUIDField(read_only=True, help_text="Unique identifier of this alert instance.")
+ grouping_key = serializers.CharField(
+ read_only=True,
+ help_text="Key of the result group this instance tracks. Empty when the source does not group results.",
+ )
+ state = serializers.ChoiceField(
+ choices=PlatformAlertState.choices,
+ read_only=True,
+ help_text="Current state of this alert instance.",
+ )
+ firing_started_at = serializers.DateTimeField(
+ read_only=True,
+ allow_null=True,
+ help_text="When the current firing started. Null when the instance is not firing.",
+ )
+ last_notified_at = serializers.DateTimeField(
+ read_only=True, allow_null=True, help_text="When a notification was last sent for this instance."
+ )
+ snooze_until = serializers.DateTimeField(
+ read_only=True,
+ allow_null=True,
+ help_text="Time until which notifications are snoozed. Null when not snoozed.",
+ )
+
+
+class PlatformAlertConfigurationSerializer(serializers.Serializer):
+ id = serializers.UUIDField(read_only=True, help_text="Unique identifier of the alert configuration.")
+ name = serializers.CharField(read_only=True, help_text="Human-readable name of the alert.")
+ enabled = serializers.BooleanField(read_only=True, help_text="Whether the alert is evaluated on schedule.")
+ source_kind = serializers.ChoiceField(
+ choices=PlatformAlertConfigurationSourceKind.choices,
+ read_only=True,
+ help_text="Product whose data the alert evaluates.",
+ )
+ source_config = serializers.DictField(
+ child=serializers.JSONField(),
+ read_only=True,
+ help_text="Source-specific query settings. The shape depends on source_kind.",
+ )
+ threshold_count = serializers.IntegerField(
+ read_only=True, help_text="Count the evaluated value is compared against."
+ )
+ threshold_operator = serializers.CharField(
+ read_only=True, help_text="Comparison operator applied between the value and threshold_count."
+ )
+ window_minutes = serializers.IntegerField(
+ read_only=True, help_text="Length of the evaluated time window, in minutes."
+ )
+ check_interval_minutes = serializers.IntegerField(read_only=True, help_text="Minutes between scheduled checks.")
+ evaluation_periods = serializers.IntegerField(
+ read_only=True, help_text="Number of recent checks considered when deciding to fire."
+ )
+ datapoints_to_alarm = serializers.IntegerField(
+ read_only=True, help_text="Number of breaching checks within evaluation_periods required to fire."
+ )
+ cooldown_minutes = serializers.IntegerField(
+ read_only=True, help_text="Minimum minutes between notifications for the same alert."
+ )
+ schedule_restriction = ScheduleRestrictionField(
+ read_only=True,
+ allow_null=True,
+ help_text="Blocked local time windows (HH:MM in the project timezone) when the alert does not run. "
+ "Null means no quiet hours.",
+ )
+ next_check_at = serializers.DateTimeField(
+ read_only=True, allow_null=True, help_text="When the next check is due. Null when no check is scheduled."
+ )
+ consecutive_failures = serializers.IntegerField(
+ read_only=True, help_text="Number of checks in a row that failed to evaluate."
+ )
+ legacy_configuration_id = serializers.UUIDField(
+ read_only=True,
+ allow_null=True,
+ help_text="ID of the legacy source configuration this row was backfilled from. "
+ "Null for alerts created on the platform.",
+ )
+ created_at = serializers.DateTimeField(read_only=True, help_text="When the configuration was created.")
+ updated_at = serializers.DateTimeField(read_only=True, help_text="When the configuration was last changed.")
+ alerts = PlatformAlertSerializer(
+ many=True,
+ read_only=True,
+ help_text="Runtime state for each result group of this configuration.",
+ )
+
+
+# A configuration shows the source product's data (its filters and firing state), so a reader
+# also needs read access to that product. `alert:read` alone must not reveal it.
+SOURCE_KIND_RESOURCE: dict[str, APIScopeObject] = {
+ PlatformAlertConfigurationSourceKind.LOGS.value: "logs",
+}
+
+
+class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ scope_object = "alert"
+ posthog_feature_flag = "platform-alerts"
+ permission_classes = [PostHogFeatureFlagPermission]
+ serializer_class = PlatformAlertConfigurationSerializer
+ pagination_class = PrecountedLimitOffsetPagination
+
+ @cached_property
+ def canonical_team(self) -> Team:
+ # The rows live on the parent team, so a child environment reads its parent's.
+ if self.team.parent_team_id is None:
+ return self.team
+ parent_team = self.team.parent_team
+ assert parent_team is not None
+ return parent_team
+
+ @cached_property
+ def user_access_control(self) -> UserAccessControl:
+ # Anchored on the team the rows come from, not on the one the URL named. The mixin builds
+ # this from `self.team`, which filters access control rows by that team's id, so a deny
+ # written on the project would not be seen by a request naming one of its environments
+ # while the read still returned the project's rows.
+ return UserAccessControl(
+ user=cast(User, self.request.user),
+ team=self.canonical_team,
+ organization_id=self.organization_id,
+ )
+
+ def _canonical_team_id(self) -> int:
+ return self.canonical_team.id
+
+ def _readable_source_kinds(self) -> list[str]:
+ # Session auth carries no scopes, so only the access-control check applies to it.
+ token_scopes = get_authenticator_scopes(getattr(self.request, "successful_authenticator", None))
+ readable: list[str] = []
+ for source_kind, resource in SOURCE_KIND_RESOURCE.items():
+ if not self.user_access_control.check_access_level_for_resource(resource, "viewer"):
+ continue
+ if (
+ token_scopes is not None
+ and "*" not in token_scopes
+ and scopes_not_covered(token_scopes, [f"{resource}:read"])
+ ):
+ continue
+ readable.append(source_kind)
+ return readable
+
+ def list(self, request: Request, **kwargs) -> Response:
+ paginator = cast(PrecountedLimitOffsetPagination, self.paginator)
+ limit = paginator.get_limit(request)
+ assert limit is not None
+ page = platform_api.list_configurations(
+ team_id=self._canonical_team_id(),
+ source_kinds=self._readable_source_kinds(),
+ limit=limit,
+ offset=paginator.get_offset(request),
+ )
+ paginator.set_count(page.total)
+ return self.get_paginated_response(
+ PlatformAlertConfigurationSerializer(self.paginate_queryset(page.configurations), many=True).data
+ )
+
+ @extend_schema(responses=PlatformAlertConfigurationSerializer)
+ def retrieve(self, request: Request, pk: str, **kwargs) -> Response:
+ # The route accepts any non-slash value, and an unparseable one reaching the UUID filter
+ # raises rather than missing, which would answer a bad id with a 500.
+ configuration = platform_api.get_configuration(
+ team_id=self._canonical_team_id(),
+ source_kinds=self._readable_source_kinds(),
+ configuration_id=serializers.UUIDField().run_validation(pk),
+ )
+ if configuration is None:
+ raise NotFound()
+ return Response(PlatformAlertConfigurationSerializer(configuration).data)
diff --git a/products/alerts/backend/presentation/views/schedule_restriction.py b/products/alerts_platform/backend/presentation/views/schedule_restriction.py
similarity index 62%
rename from products/alerts/backend/presentation/views/schedule_restriction.py
rename to products/alerts_platform/backend/presentation/views/schedule_restriction.py
index 6634a2691872..f775cf0b5720 100644
--- a/products/alerts/backend/presentation/views/schedule_restriction.py
+++ b/products/alerts_platform/backend/presentation/views/schedule_restriction.py
@@ -1,13 +1,15 @@
"""Pydantic OpenAPI types for alert quiet hours (schedule_restriction JSONField).
-Adopter products reuse them to describe the same JSON field on their own alert APIs.
-They carry drf-spectacular meaning rather than data a consumer reads, so they sit on the
-presentation surface, not in the facade.
+The field belongs to this product's configuration, and adopter products reuse these to describe
+their own alert APIs. They carry drf-spectacular meaning rather than data a consumer reads, so
+they sit on the presentation surface, not in the facade.
"""
from __future__ import annotations
+from drf_spectacular.utils import extend_schema_field
from pydantic import BaseModel, ConfigDict, Field
+from rest_framework import serializers
class AlertScheduleRestrictionWindow(BaseModel):
@@ -39,3 +41,12 @@ class AlertScheduleRestriction(BaseModel):
"At most five windows before normalization; empty array clears quiet hours."
),
)
+
+
+@extend_schema_field(AlertScheduleRestriction) # type: ignore[arg-type]
+class ScheduleRestrictionField(serializers.JSONField):
+ """The quiet hours column, described to drf-spectacular by the model above.
+
+ Every alert product declares this field, so it lives beside the type it points at rather
+ than being redeclared once per adopter.
+ """
diff --git a/products/alerts_platform/backend/routes.py b/products/alerts_platform/backend/routes.py
new file mode 100644
index 000000000000..afc09fa8c885
--- /dev/null
+++ b/products/alerts_platform/backend/routes.py
@@ -0,0 +1,12 @@
+from posthog.api.routing import RouterRegistry
+
+import products.alerts_platform.backend.presentation.views.platform_alert as platform_alert
+
+
+def register_routes(routers: RouterRegistry) -> None:
+ routers.projects.register(
+ r"platform_alerts",
+ platform_alert.PlatformAlertConfigurationViewSet,
+ "project_platform_alerts",
+ ["team_id"],
+ )
diff --git a/products/alerts_platform/backend/tests/api/__init__.py b/products/alerts_platform/backend/tests/api/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/alerts_platform/backend/tests/api/test_platform_alert.py b/products/alerts_platform/backend/tests/api/test_platform_alert.py
new file mode 100644
index 000000000000..3d00e9e06e0c
--- /dev/null
+++ b/products/alerts_platform/backend/tests/api/test_platform_alert.py
@@ -0,0 +1,214 @@
+from datetime import UTC, datetime
+from uuid import UUID, uuid4
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.db import connection
+from django.test.utils import CaptureQueriesContext
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.constants import AvailableFeature
+from posthog.models import OrganizationMembership, User
+from posthog.models.scoping import team_scope
+from posthog.models.team import Team
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration
+
+
+class TestPlatformAlertAPI(APIBaseTest):
+ def _create_configuration(
+ self, team: Team, name: str, legacy_configuration_id: UUID | None = None
+ ) -> PlatformAlertConfiguration:
+ with team_scope(team.id):
+ return PlatformAlertConfiguration.objects.create(
+ team=team,
+ name=name,
+ source_kind=PlatformAlertConfiguration.SourceKind.LOGS,
+ source_config={"service": "api"},
+ threshold_count=10,
+ threshold_operator="above",
+ window_minutes=5,
+ check_interval_minutes=10,
+ legacy_configuration_id=legacy_configuration_id,
+ )
+
+ def _set_flag(self, enabled: bool) -> None:
+ self.enterContext(patch("posthog.permissions.posthog_feature_flag_enabled", return_value=enabled))
+
+ @parameterized.expand([("list", False), ("retrieve", True)])
+ def test_flag_off_blocks_access(self, _name: str, with_id: bool) -> None:
+ self._set_flag(False)
+ configuration = self._create_configuration(self.team, "API errors")
+ url = f"/api/projects/{self.team.id}/platform_alerts/"
+ if with_id:
+ url += f"{configuration.id}/"
+
+ response = self.client.get(url)
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+ assert response.json()["code"] == "feature_flag_required"
+
+ def test_list_returns_own_configurations_with_nested_alerts(self) -> None:
+ self._set_flag(True)
+ legacy_configuration_id = uuid4()
+ configuration = self._create_configuration(self.team, "API errors", legacy_configuration_id)
+ firing_started_at = datetime(2026, 9, 16, 10, tzinfo=UTC)
+ with team_scope(self.team.id):
+ alert = PlatformAlert.objects.create(
+ team=self.team,
+ configuration=configuration,
+ grouping_key="checkout",
+ state=PlatformAlert.State.FIRING,
+ firing_started_at=firing_started_at,
+ last_notified_at=firing_started_at,
+ )
+ list_response = self.client.get(f"/api/projects/{self.team.id}/platform_alerts/")
+
+ assert list_response.status_code == status.HTTP_200_OK, list_response.json()
+ results = list_response.json()["results"]
+ assert [r["id"] for r in results] == [str(configuration.id)]
+ assert results[0]["legacy_configuration_id"] == str(legacy_configuration_id)
+ assert results[0]["alerts"] == [
+ {
+ "id": str(alert.id),
+ "grouping_key": "checkout",
+ "state": "firing",
+ "firing_started_at": "2026-09-16T10:00:00Z",
+ "last_notified_at": "2026-09-16T10:00:00Z",
+ "snooze_until": None,
+ }
+ ]
+
+ def test_a_child_environment_reads_its_parents_configurations(self) -> None:
+ # The viewset resolves a child environment to its parent before reading, so a request
+ # against the child sees the parent's rows rather than an empty project.
+ self._set_flag(True)
+ configuration = self._create_configuration(self.team, "API errors")
+ child_environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="env")
+
+ response = self.client.get(f"/api/projects/{child_environment.id}/platform_alerts/{configuration.id}/")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["id"] == str(configuration.id)
+
+ def test_another_teams_configuration_is_not_found(self) -> None:
+ self._set_flag(True)
+ other_team = Team.objects.create(organization=self.organization, name="Other team")
+ other_configuration = self._create_configuration(other_team, "Other team errors")
+
+ response = self.client.get(f"/api/projects/{self.team.id}/platform_alerts/{other_configuration.id}/")
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ @parameterized.expand(
+ [
+ ("member_without_logs_access", None, False),
+ ("key_without_logs_scope", ["alert:read"], False),
+ ("key_with_logs_scope", ["alert:read", "logs:read"], True),
+ ]
+ )
+ def test_logs_configurations_need_logs_read_access(
+ self, _name: str, key_scopes: list[str] | None, visible: bool
+ ) -> None:
+ self._set_flag(True)
+ configuration = self._create_configuration(self.team, "API errors")
+ if key_scopes is None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ member = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ AccessControl.objects.create(
+ team=self.team,
+ resource="logs",
+ resource_id=None,
+ access_level="none",
+ organization_member=OrganizationMembership.objects.get(user=member, organization=self.organization),
+ )
+ self.client.force_login(member)
+ else:
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {self.create_personal_api_key_with_scopes(key_scopes)}")
+
+ list_response = self.client.get(f"/api/projects/{self.team.id}/platform_alerts/")
+ retrieve_response = self.client.get(f"/api/projects/{self.team.id}/platform_alerts/{configuration.id}/")
+
+ assert list_response.status_code == status.HTTP_200_OK, list_response.json()
+ assert [r["id"] for r in list_response.json()["results"]] == ([str(configuration.id)] if visible else [])
+ expected_retrieve_status = status.HTTP_200_OK if visible else status.HTTP_404_NOT_FOUND
+ assert retrieve_response.status_code == expected_retrieve_status, retrieve_response.json()
+
+ def test_a_logs_denial_on_the_parent_survives_a_child_environment_url(self) -> None:
+ # The rows are read from the parent, so the access check has to be read from the parent
+ # too. Anchored on the URL's team instead, a deny written on the project is invisible to a
+ # request that names one of its environments, and the parent's `source_config` filters are
+ # exactly what the deny was protecting.
+ self._set_flag(True)
+ configuration = self._create_configuration(self.team, "API errors")
+ child_environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="env")
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ member = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ AccessControl.objects.create(
+ team=self.team,
+ resource="logs",
+ resource_id=None,
+ access_level="none",
+ organization_member=OrganizationMembership.objects.get(user=member, organization=self.organization),
+ )
+ self.client.force_login(member)
+
+ list_response = self.client.get(f"/api/projects/{child_environment.id}/platform_alerts/")
+ retrieve_response = self.client.get(f"/api/projects/{child_environment.id}/platform_alerts/{configuration.id}/")
+
+ assert list_response.status_code == status.HTTP_200_OK, list_response.json()
+ assert [r["id"] for r in list_response.json()["results"]] == []
+ assert retrieve_response.status_code == status.HTTP_404_NOT_FOUND, retrieve_response.json()
+
+ def test_a_malformed_id_is_refused_rather_than_raising(self) -> None:
+ self._set_flag(True)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/platform_alerts/not-a-uuid/")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+
+ def test_two_pages_cover_every_row_once(self) -> None:
+ # `list` asks the facade for a slice and then hands that slice to the paginator. An offset
+ # applied by both would skip rows at the page boundary, which a single-page test cannot see.
+ self._set_flag(True)
+ created = {str(self._create_configuration(self.team, f"Alert {index}").id) for index in range(3)}
+ url = f"/api/projects/{self.team.id}/platform_alerts/"
+
+ first = self.client.get(f"{url}?limit=2").json()
+ second = self.client.get(f"{url}?limit=2&offset=2").json()
+
+ first_ids = [row["id"] for row in first["results"]]
+ second_ids = [row["id"] for row in second["results"]]
+ assert first["count"] == 3
+ assert len(first_ids) == 2
+ assert len(second_ids) == 1
+ assert set(first_ids).isdisjoint(second_ids)
+ assert set(first_ids) | set(second_ids) == created
+
+ def test_a_page_costs_the_same_queries_however_many_rows_it_holds(self) -> None:
+ # A filter added to the prefetched relation would bypass the cache and cost a query per
+ # configuration, which no assertion on the response body would notice.
+ self._set_flag(True)
+ for index in range(4):
+ self._create_configuration(self.team, f"Alert {index}")
+ url = f"/api/projects/{self.team.id}/platform_alerts/"
+
+ self.client.get(f"{url}?limit=1") # The first request of a test warms caches the rest reuse.
+
+ assert self._queries_for(f"{url}?limit=4") == self._queries_for(f"{url}?limit=1")
+
+ def _queries_for(self, url: str) -> int:
+ with CaptureQueriesContext(connection) as captured:
+ self.client.get(url)
+ return len(captured)
diff --git a/products/alerts_platform/backend/tests/test_source_kinds.py b/products/alerts_platform/backend/tests/test_source_kinds.py
new file mode 100644
index 000000000000..769a86d51d7d
--- /dev/null
+++ b/products/alerts_platform/backend/tests/test_source_kinds.py
@@ -0,0 +1,15 @@
+from products.alerts_platform.backend.facade.contracts import SourceKind
+from products.alerts_platform.backend.facade.enums import PlatformAlertConfigurationSourceKind
+from products.alerts_platform.backend.presentation.views.platform_alert import SOURCE_KIND_RESOURCE
+
+
+def test_a_storable_source_kind_is_one_the_contract_names() -> None:
+ # `demand.py` builds a `SourceKind` from every due row's stored value, so a kind the column
+ # accepts but the contract does not name raises for the whole tick rather than for one row.
+ assert {kind.value for kind in PlatformAlertConfigurationSourceKind} <= {kind.value for kind in SourceKind}
+
+
+def test_every_source_kind_names_the_resource_that_gates_reading_it() -> None:
+ # A kind absent from the map never enters `readable`, so its configurations are missing from
+ # the read API with nothing raised to say why.
+ assert {kind.value for kind in PlatformAlertConfigurationSourceKind} == set(SOURCE_KIND_RESOURCE)
diff --git a/products/alerts_platform/frontend/generated/api.schemas.ts b/products/alerts_platform/frontend/generated/api.schemas.ts
new file mode 100644
index 000000000000..18a196f997fd
--- /dev/null
+++ b/products/alerts_platform/frontend/generated/api.schemas.ts
@@ -0,0 +1,152 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+/**
+ * * `logs` - Logs
+ */
+export type PlatformAlertConfigurationSourceKindEnumApi =
+ (typeof PlatformAlertConfigurationSourceKindEnumApi)[keyof typeof PlatformAlertConfigurationSourceKindEnumApi]
+
+export const PlatformAlertConfigurationSourceKindEnumApi = {
+ Logs: 'logs',
+} as const
+
+export interface AlertScheduleRestrictionWindowApi {
+ /** Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)). */
+ start: string
+ /** End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally. */
+ end: string
+}
+
+export interface AlertScheduleRestrictionApi {
+ /** Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours. */
+ blocked_windows: AlertScheduleRestrictionWindowApi[]
+}
+
+/**
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken
+ */
+export type BillingAlertConfigurationStateEnumApi =
+ (typeof BillingAlertConfigurationStateEnumApi)[keyof typeof BillingAlertConfigurationStateEnumApi]
+
+export const BillingAlertConfigurationStateEnumApi = {
+ NotFiring: 'not_firing',
+ Firing: 'firing',
+ Errored: 'errored',
+ Snoozed: 'snoozed',
+ Broken: 'broken',
+} as const
+
+export interface PlatformAlertApi {
+ /** Unique identifier of this alert instance. */
+ readonly id: string
+ /** Key of the result group this instance tracks. Empty when the source does not group results. */
+ readonly grouping_key: string
+ /** Current state of this alert instance.
+ *
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken */
+ readonly state: BillingAlertConfigurationStateEnumApi
+ /**
+ * When the current firing started. Null when the instance is not firing.
+ * @nullable
+ */
+ readonly firing_started_at: string | null
+ /**
+ * When a notification was last sent for this instance.
+ * @nullable
+ */
+ readonly last_notified_at: string | null
+ /**
+ * Time until which notifications are snoozed. Null when not snoozed.
+ * @nullable
+ */
+ readonly snooze_until: string | null
+}
+
+/**
+ * Source-specific query settings. The shape depends on source_kind.
+ */
+export type PlatformAlertConfigurationApiSourceConfig = { [key: string]: unknown }
+
+export interface PlatformAlertConfigurationApi {
+ /** Unique identifier of the alert configuration. */
+ readonly id: string
+ /** Human-readable name of the alert. */
+ readonly name: string
+ /** Whether the alert is evaluated on schedule. */
+ readonly enabled: boolean
+ /** Product whose data the alert evaluates.
+ *
+ * * `logs` - Logs */
+ readonly source_kind: PlatformAlertConfigurationSourceKindEnumApi
+ /** Source-specific query settings. The shape depends on source_kind. */
+ readonly source_config: PlatformAlertConfigurationApiSourceConfig
+ /** Count the evaluated value is compared against. */
+ readonly threshold_count: number
+ /** Comparison operator applied between the value and threshold_count. */
+ readonly threshold_operator: string
+ /** Length of the evaluated time window, in minutes. */
+ readonly window_minutes: number
+ /** Minutes between scheduled checks. */
+ readonly check_interval_minutes: number
+ /** Number of recent checks considered when deciding to fire. */
+ readonly evaluation_periods: number
+ /** Number of breaching checks within evaluation_periods required to fire. */
+ readonly datapoints_to_alarm: number
+ /** Minimum minutes between notifications for the same alert. */
+ readonly cooldown_minutes: number
+ /** Blocked local time windows (HH:MM in the project timezone) when the alert does not run. Null means no quiet hours. */
+ readonly schedule_restriction: AlertScheduleRestrictionApi | null
+ /**
+ * When the next check is due. Null when no check is scheduled.
+ * @nullable
+ */
+ readonly next_check_at: string | null
+ /** Number of checks in a row that failed to evaluate. */
+ readonly consecutive_failures: number
+ /**
+ * ID of the legacy source configuration this row was backfilled from. Null for alerts created on the platform.
+ * @nullable
+ */
+ readonly legacy_configuration_id: string | null
+ /** When the configuration was created. */
+ readonly created_at: string
+ /** When the configuration was last changed. */
+ readonly updated_at: string
+ /** Runtime state for each result group of this configuration. */
+ readonly alerts: readonly PlatformAlertApi[]
+}
+
+export interface PaginatedPlatformAlertConfigurationListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: PlatformAlertConfigurationApi[]
+}
+
+export type PlatformAlertsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
diff --git a/products/alerts_platform/frontend/generated/api.ts b/products/alerts_platform/frontend/generated/api.ts
new file mode 100644
index 000000000000..f2b375b8a0b0
--- /dev/null
+++ b/products/alerts_platform/frontend/generated/api.ts
@@ -0,0 +1,57 @@
+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import type {
+ PaginatedPlatformAlertConfigurationListApi,
+ PlatformAlertConfigurationApi,
+ PlatformAlertsListParams,
+} from './api.schemas'
+
+export const getPlatformAlertsListUrl = (projectId: string, params?: PlatformAlertsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/platform_alerts/?${stringifiedParams}`
+ : `/api/projects/${projectId}/platform_alerts/`
+}
+
+export const platformAlertsList = async (
+ projectId: string,
+ params?: PlatformAlertsListParams,
+ options?: RequestInit
+): Promise<PaginatedPlatformAlertConfigurationListApi> => {
+ return apiMutator<PaginatedPlatformAlertConfigurationListApi>(getPlatformAlertsListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getPlatformAlertsRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/platform_alerts/${id}/`
+}
+
+export const platformAlertsRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<PlatformAlertConfigurationApi> => {
+ return apiMutator<PlatformAlertConfigurationApi>(getPlatformAlertsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
diff --git a/products/alerts_platform/frontend/generated/api.zod.schemas.ts b/products/alerts_platform/frontend/generated/api.zod.schemas.ts
new file mode 100644
index 000000000000..7f6c23bdc13a
--- /dev/null
+++ b/products/alerts_platform/frontend/generated/api.zod.schemas.ts
@@ -0,0 +1,301 @@
+/**
+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
+ * To modify these schemas, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import { z as zod } from 'zod'
+
+export const PlatformAlertConfigurationSourceKindEnumApi = zod.enum(['logs']).describe('\* `logs` - Logs')
+
+export type PlatformAlertConfigurationSourceKindEnumApi = zod.input<typeof PlatformAlertConfigurationSourceKindEnumApi>
+export type PlatformAlertConfigurationSourceKindEnumApiOutput = zod.output<
+ typeof PlatformAlertConfigurationSourceKindEnumApi
+>
+
+export const AlertScheduleRestrictionWindowApi = zod.object({
+ start: zod
+ .string()
+ .describe(
+ 'Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)).'
+ ),
+ end: zod
+ .string()
+ .describe(
+ 'End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally.'
+ ),
+})
+
+export type AlertScheduleRestrictionWindowApi = zod.input<typeof AlertScheduleRestrictionWindowApi>
+export type AlertScheduleRestrictionWindowApiOutput = zod.output<typeof AlertScheduleRestrictionWindowApi>
+
+export const AlertScheduleRestrictionApi = zod.object({
+ blocked_windows: zod
+ .array(
+ zod.object({
+ start: zod
+ .string()
+ .describe(
+ 'Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)).'
+ ),
+ end: zod
+ .string()
+ .describe(
+ 'End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally.'
+ ),
+ })
+ )
+ .describe(
+ 'Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours.'
+ ),
+})
+
+export type AlertScheduleRestrictionApi = zod.input<typeof AlertScheduleRestrictionApi>
+export type AlertScheduleRestrictionApiOutput = zod.output<typeof AlertScheduleRestrictionApi>
+
+export const BillingAlertConfigurationStateEnumApi = zod
+ .enum(['not_firing', 'firing', 'errored', 'snoozed', 'broken'])
+ .describe(
+ '\* `not_firing` - Not firing\n\* `firing` - Firing\n\* `errored` - Errored\n\* `snoozed` - Snoozed\n\* `broken` - Broken'
+ )
+
+export type BillingAlertConfigurationStateEnumApi = zod.input<typeof BillingAlertConfigurationStateEnumApi>
+export type BillingAlertConfigurationStateEnumApiOutput = zod.output<typeof BillingAlertConfigurationStateEnumApi>
+
+export const PlatformAlertApi = zod.object({
+ id: zod.uuid().describe('Unique identifier of this alert instance.'),
+ grouping_key: zod
+ .string()
+ .describe('Key of the result group this instance tracks. Empty when the source does not group results.'),
+ state: zod
+ .enum(['not_firing', 'firing', 'errored', 'snoozed', 'broken'])
+ .describe(
+ '\* `not_firing` - Not firing\n\* `firing` - Firing\n\* `errored` - Errored\n\* `snoozed` - Snoozed\n\* `broken` - Broken'
+ )
+ .describe(
+ 'Current state of this alert instance.\n\n\* `not_firing` - Not firing\n\* `firing` - Firing\n\* `errored` - Errored\n\* `snoozed` - Snoozed\n\* `broken` - Broken'
+ ),
+ firing_started_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('When the current firing started. Null when the instance is not firing.'),
+ last_notified_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('When a notification was last sent for this instance.'),
+ snooze_until: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('Time until which notifications are snoozed. Null when not snoozed.'),
+})
+
+export type PlatformAlertApi = zod.input<typeof PlatformAlertApi>
+export type PlatformAlertApiOutput = zod.output<typeof PlatformAlertApi>
+
+export const PlatformAlertConfigurationApi = zod.object({
+ id: zod.uuid().describe('Unique identifier of the alert configuration.'),
+ name: zod.string().describe('Human-readable name of the alert.'),
+ enabled: zod.boolean().describe('Whether the alert is evaluated on schedule.'),
+ source_kind: zod
+ .enum(['logs'])
+ .describe('\* `logs` - Logs')
+ .describe('Product whose data the alert evaluates.\n\n\* `logs` - Logs'),
+ source_config: zod
+ .record(zod.string(), zod.unknown())
+ .describe('Source-specific query settings. The shape depends on source_kind.'),
+ threshold_count: zod.number().describe('Count the evaluated value is compared against.'),
+ threshold_operator: zod.string().describe('Comparison operator applied between the value and threshold_count.'),
+ window_minutes: zod.number().describe('Length of the evaluated time window, in minutes.'),
+ check_interval_minutes: zod.number().describe('Minutes between scheduled checks.'),
+ evaluation_periods: zod.number().describe('Number of recent checks considered when deciding to fire.'),
+ datapoints_to_alarm: zod
+ .number()
+ .describe('Number of breaching checks within evaluation_periods required to fire.'),
+ cooldown_minutes: zod.number().describe('Minimum minutes between notifications for the same alert.'),
+ schedule_restriction: zod
+ .union([
+ zod.object({
+ blocked_windows: zod
+ .array(
+ zod.object({
+ start: zod
+ .string()
+ .describe(
+ 'Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)).'
+ ),
+ end: zod
+ .string()
+ .describe(
+ 'End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally.'
+ ),
+ })
+ )
+ .describe(
+ 'Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .describe(
+ 'Blocked local time windows (HH:MM in the project timezone) when the alert does not run. Null means no quiet hours.'
+ ),
+ next_check_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('When the next check is due. Null when no check is scheduled.'),
+ consecutive_failures: zod.number().describe('Number of checks in a row that failed to evaluate.'),
+ legacy_configuration_id: zod
+ .uuid()
+ .nullable()
+ .describe(
+ 'ID of the legacy source configuration this row was backfilled from. Null for alerts created on the platform.'
+ ),
+ created_at: zod.iso.datetime({ offset: true }).describe('When the configuration was created.'),
+ updated_at: zod.iso.datetime({ offset: true }).describe('When the configuration was last changed.'),
+ alerts: zod
+ .array(
+ zod.object({
+ id: zod.uuid().describe('Unique identifier of this alert instance.'),
+ grouping_key: zod
+ .string()
+ .describe(
+ 'Key of the result group this instance tracks. Empty when the source does not group results.'
+ ),
+ state: zod
+ .enum(['not_firing', 'firing', 'errored', 'snoozed', 'broken'])
+ .describe(
+ '\* `not_firing` - Not firing\n\* `firing` - Firing\n\* `errored` - Errored\n\* `snoozed` - Snoozed\n\* `broken` - Broken'
+ )
+ .describe(
+ 'Current state of this alert instance.\n\n\* `not_firing` - Not firing\n\* `firing` - Firing\n\* `errored` - Errored\n\* `snoozed` - Snoozed\n\* `broken` - Broken'
+ ),
+ firing_started_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('When the current firing started. Null when the instance is not firing.'),
+ last_notified_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('When a notification was last sent for this instance.'),
+ snooze_until: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('Time until which notifications are snoozed. Null when not snoozed.'),
+ })
+ )
+ .describe('Runtime state for each result group of this configuration.'),
+})
+
+export type PlatformAlertConfigurationApi = zod.input<typeof PlatformAlertConfigurationApi>
+export type PlatformAlertConfigurationApiOutput = zod.output<typeof PlatformAlertConfigurationApi>
+
+export const PaginatedPlatformAlertConfigurationListApi = zod.object({
+ count: zod.number(),
+ next: zod.url().nullish(),
+ previous: zod.url().nullish(),
+ results: zod.array(
+ zod.object({
+ id: zod.uuid().describe('Unique identifier of the alert configuration.'),
+ name: zod.string().describe('Human-readable name of the alert.'),
+ enabled: zod.boolean().describe('Whether the alert is evaluated on schedule.'),
+ source_kind: zod
+ .enum(['logs'])
+ .describe('\* `logs` - Logs')
+ .describe('Product whose data the alert evaluates.\n\n\* `logs` - Logs'),
+ source_config: zod
+ .record(zod.string(), zod.unknown())
+ .describe('Source-specific query settings. The shape depends on source_kind.'),
+ threshold_count: zod.number().describe('Count the evaluated value is compared against.'),
+ threshold_operator: zod
+ .string()
+ .describe('Comparison operator applied between the value and threshold_count.'),
+ window_minutes: zod.number().describe('Length of the evaluated time window, in minutes.'),
+ check_interval_minutes: zod.number().describe('Minutes between scheduled checks.'),
+ evaluation_periods: zod.number().describe('Number of recent checks considered when deciding to fire.'),
+ datapoints_to_alarm: zod
+ .number()
+ .describe('Number of breaching checks within evaluation_periods required to fire.'),
+ cooldown_minutes: zod.number().describe('Minimum minutes between notifications for the same alert.'),
+ schedule_restriction: zod
+ .union([
+ zod.object({
+ blocked_windows: zod
+ .array(
+ zod.object({
+ start: zod
+ .string()
+ .describe(
+ 'Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)).'
+ ),
+ end: zod
+ .string()
+ .describe(
+ 'End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally.'
+ ),
+ })
+ )
+ .describe(
+ 'Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .describe(
+ 'Blocked local time windows (HH:MM in the project timezone) when the alert does not run. Null means no quiet hours.'
+ ),
+ next_check_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('When the next check is due. Null when no check is scheduled.'),
+ consecutive_failures: zod.number().describe('Number of checks in a row that failed to evaluate.'),
+ legacy_configuration_id: zod
+ .uuid()
+ .nullable()
+ .describe(
+ 'ID of the legacy source configuration this row was backfilled from. Null for alerts created on the platform.'
+ ),
+ created_at: zod.iso.datetime({ offset: true }).describe('When the configuration was created.'),
+ updated_at: zod.iso.datetime({ offset: true }).describe('When the configuration was last changed.'),
+ alerts: zod
+ .array(
+ zod.object({
+ id: zod.uuid().describe('Unique identifier of this alert instance.'),
+ grouping_key: zod
+ .string()
+ .describe(
+ 'Key of the result group this instance tracks. Empty when the source does not group results.'
+ ),
+ state: zod
+ .enum(['not_firing', 'firing', 'errored', 'snoozed', 'broken'])
+ .describe(
+ '\* `not_firing` - Not firing\n\* `firing` - Firing\n\* `errored` - Errored\n\* `snoozed` - Snoozed\n\* `broken` - Broken'
+ )
+ .describe(
+ 'Current state of this alert instance.\n\n\* `not_firing` - Not firing\n\* `firing` - Firing\n\* `errored` - Errored\n\* `snoozed` - Snoozed\n\* `broken` - Broken'
+ ),
+ firing_started_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('When the current firing started. Null when the instance is not firing.'),
+ last_notified_at: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('When a notification was last sent for this instance.'),
+ snooze_until: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe('Time until which notifications are snoozed. Null when not snoozed.'),
+ })
+ )
+ .describe('Runtime state for each result group of this configuration.'),
+ })
+ ),
+})
+
+export type PaginatedPlatformAlertConfigurationListApi = zod.input<typeof PaginatedPlatformAlertConfigurationListApi>
+export type PaginatedPlatformAlertConfigurationListApiOutput = zod.output<
+ typeof PaginatedPlatformAlertConfigurationListApi
+>
diff --git a/products/alerts_platform/frontend/generated/api.zod.ts b/products/alerts_platform/frontend/generated/api.zod.ts
new file mode 100644
index 000000000000..e8a15d4e1b52
--- /dev/null
+++ b/products/alerts_platform/frontend/generated/api.zod.ts
@@ -0,0 +1,9 @@
+/**
+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
+ * To modify these schemas, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.py
index 19543cc16305..2c7bd3683337 100644
--- a/products/logs/backend/presentation/views/alerts_api.py
+++ b/products/logs/backend/presentation/views/alerts_api.py
@@ -40,13 +40,13 @@ from products.alerts.backend.facade.destinations import (
soft_delete_all_alert_destinations,
validate_destination_data,
)
-from products.alerts.backend.presentation.views.schedule_restriction import AlertScheduleRestriction
from products.alerts_platform.backend.facade.contracts import (
AlertDestinationData,
AlertDestinationValidationError,
DestinationType,
)
from products.alerts_platform.backend.facade.scheduling import validate_and_normalize_schedule_restriction
+from products.alerts_platform.backend.presentation.views.schedule_restriction import ScheduleRestrictionField
from products.logs.backend.alert_check_query import AlertCheckQuery, BucketedCount
from products.logs.backend.alert_destinations import (
EVENT_KIND_CONFIG,
@@ -160,11 +160,6 @@ class LogsAlertFiltersField(serializers.JSONField):
return value
-@extend_schema_field(AlertScheduleRestriction) # type: ignore[arg-type]
-class ScheduleRestrictionField(serializers.JSONField):
- pass
-
-
class LogsAlertDestinationResponseSerializer(serializers.Serializer):
hog_function_ids = serializers.ListField(child=serializers.UUIDField())
diff --git a/products/replay_vision/backend/api/vision_alerts.py b/products/replay_vision/backend/api/vision_alerts.py
index 83f8c5d59845..9f40f8891023 100644
--- a/products/replay_vision/backend/api/vision_alerts.py
+++ b/products/replay_vision/backend/api/vision_alerts.py
@@ -32,13 +32,13 @@ from products.alerts.backend.facade.destinations import (
soft_delete_all_alert_destinations,
validate_destination_data,
)
-from products.alerts.backend.presentation.views.schedule_restriction import AlertScheduleRestriction
from products.alerts_platform.backend.facade.contracts import (
AlertDestinationData,
AlertDestinationValidationError,
DestinationType,
)
from products.alerts_platform.backend.facade.scheduling import validate_and_normalize_schedule_restriction
+from products.alerts_platform.backend.presentation.views.schedule_restriction import ScheduleRestrictionField
from products.replay_vision.backend.alert_destinations import (
EVENT_KIND_CONFIG,
MATCH_EVENT_KINDS,
@@ -85,11 +85,6 @@ def _any_field_changed(instance: VisionAlertConfiguration, validated_data: dict,
return any(f in validated_data and validated_data[f] != getattr(instance, f) for f in fields)
-@extend_schema_field(AlertScheduleRestriction) # type: ignore[arg-type]
-class ScheduleRestrictionField(serializers.JSONField):
- pass
-
-
class VisionAlertSelectionSerializer(serializers.Serializer):
verdict = serializers.ListField(
child=serializers.CharField(max_length=100),
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c557ab48405c..0ea6686078da 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -68054,6 +68054,109 @@ export namespace Schemas {
results?: PersonListRecord[];
}
+ /**
+ * * `logs` - Logs
+ */
+ export type PlatformAlertConfigurationSourceKindEnum = typeof PlatformAlertConfigurationSourceKindEnum[keyof typeof PlatformAlertConfigurationSourceKindEnum];
+
+
+ export const PlatformAlertConfigurationSourceKindEnum = {
+ Logs: 'logs',
+ } as const;
+
+ export interface PlatformAlert {
+ /** Unique identifier of this alert instance. */
+ readonly id: string;
+ /** Key of the result group this instance tracks. Empty when the source does not group results. */
+ readonly grouping_key: string;
+ /** Current state of this alert instance.
+ *
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken */
+ readonly state: BillingAlertConfigurationStateEnum;
+ /**
+ * When the current firing started. Null when the instance is not firing.
+ * @nullable
+ */
+ readonly firing_started_at: string | null;
+ /**
+ * When a notification was last sent for this instance.
+ * @nullable
+ */
+ readonly last_notified_at: string | null;
+ /**
+ * Time until which notifications are snoozed. Null when not snoozed.
+ * @nullable
+ */
+ readonly snooze_until: string | null;
+ }
+
+ /**
+ * Source-specific query settings. The shape depends on source_kind.
+ */
+ export type PlatformAlertConfigurationSourceConfig = { [key: string]: unknown };
+
+ export interface PlatformAlertConfiguration {
+ /** Unique identifier of the alert configuration. */
+ readonly id: string;
+ /** Human-readable name of the alert. */
+ readonly name: string;
+ /** Whether the alert is evaluated on schedule. */
+ readonly enabled: boolean;
+ /** Product whose data the alert evaluates.
+ *
+ * * `logs` - Logs */
+ readonly source_kind: PlatformAlertConfigurationSourceKindEnum;
+ /** Source-specific query settings. The shape depends on source_kind. */
+ readonly source_config: PlatformAlertConfigurationSourceConfig;
+ /** Count the evaluated value is compared against. */
+ readonly threshold_count: number;
+ /** Comparison operator applied between the value and threshold_count. */
+ readonly threshold_operator: string;
+ /** Length of the evaluated time window, in minutes. */
+ readonly window_minutes: number;
+ /** Minutes between scheduled checks. */
+ readonly check_interval_minutes: number;
+ /** Number of recent checks considered when deciding to fire. */
+ readonly evaluation_periods: number;
+ /** Number of breaching checks within evaluation_periods required to fire. */
+ readonly datapoints_to_alarm: number;
+ /** Minimum minutes between notifications for the same alert. */
+ readonly cooldown_minutes: number;
+ /** Blocked local time windows (HH:MM in the project timezone) when the alert does not run. Null means no quiet hours. */
+ readonly schedule_restriction: AlertScheduleRestriction | null;
+ /**
+ * When the next check is due. Null when no check is scheduled.
+ * @nullable
+ */
+ readonly next_check_at: string | null;
+ /** Number of checks in a row that failed to evaluate. */
+ readonly consecutive_failures: number;
+ /**
+ * ID of the legacy source configuration this row was backfilled from. Null for alerts created on the platform.
+ * @nullable
+ */
+ readonly legacy_configuration_id: string | null;
+ /** When the configuration was created. */
+ readonly created_at: string;
+ /** When the configuration was last changed. */
+ readonly updated_at: string;
+ /** Runtime state for each result group of this configuration. */
+ readonly alerts: readonly PlatformAlert[];
+ }
+
+ export interface PaginatedPlatformAlertConfigurationList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: PlatformAlertConfiguration[];
+ }
+
/**
* * `SYSTEM` - SYSTEM
* * `PLUGIN` - PLUGIN
@@ -120921,6 +121024,17 @@ export namespace Schemas {
Json: 'json',
} as const;
+ export type PlatformAlertsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type PluginConfigsLogsListParams = {
/**
* Number of results to return per page.
diff --git a/tach.toml b/tach.toml
index 1025dafeb0fa..8cf2c8849215 100644
--- a/tach.toml
+++ b/tach.toml
@@ -1648,7 +1648,7 @@ layer = "modules"
[[modules]]
path = "products.alerts_platform"
-depends_on = ["posthog"]
+depends_on = ["posthog", "products.access_control"]
layer = "modules"
[[interfaces]]