:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(alerts): create logs alerts through the platform api (#120013)
Jimmy Zhu08443b8cfd3e
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.pyindex 4f1ce4088626..79c2d6f4112f 100644--- a/products/alerts_platform/backend/facade/api.py+++ b/products/alerts_platform/backend/facade/api.py@@ -171,6 +171,19 @@ def update_configuration()+def create_configuration(+ *, team_id: int, source_kind: SourceKind, edit: PlatformAlertConfigurationEdit, created_by_id: int | None+) -> PlatformAlertConfigurationView:+ """Creates an alert the platform owns, with its source's own row when the source keeps one.++ Raises `PlatformAlertNotEditable` for a kind the API cannot create, `InvalidPlatformAlertEdit` for+ settings its source kind rejects, and `PlatformAlertCreateRefused` when the source refuses.+ """+ return platform_writes.create_configuration(+ team_id=team_id, source_kind=source_kind, edit=edit, created_by_id=created_by_id+ )++def snooze_group(*,team_id: int,diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.pyindex c83206163a92..f452492b4f61 100644--- a/products/alerts_platform/backend/facade/contracts.py+++ b/products/alerts_platform/backend/facade/contracts.py@@ -899,17 +899,35 @@ class SourceEditMirror(Protocol):) -> Callable[[PlatformAlertConfigurationEdit], None] | None: ...+class PlatformAlertCreateRefused(Exception):+ """A create the source refuses as a whole, such as one past its per-team limit."""+++class SourceCreate(Protocol):+ """Creates an alert through the platform API on a source that keeps its own row for it.++ Runs in the create's transaction. It writes the source's row and the platform's copy, both owned+ by the platform, the way the source hands over an alert it created itself, and returns the id of+ the source's row. The copy carries that id as `legacy_configuration_id`. It raises+ `PlatformAlertCreateRefused` when the source refuses the create.+ """++ def __call__(self, *, team_id: int, edit: PlatformAlertConfigurationEdit, created_by_id: int | None) -> UUID: ...++@frozenclass SourceConfigSpec:"""A source kind's schema for `source_config` and its rules for a whole edit.`model` validates `source_config`. `validate` raises `InvalidPlatformAlertEdit` for a rule that- spans fields, such as one that reads `enabled`. `mirror` runs in the edit's transaction.+ spans fields, such as one that reads `enabled`. `mirror` runs in the edit's transaction. Without+ `create`, the API cannot create alerts of the kind."""model: type[BaseModel]validate: Callable[[PlatformAlertConfigurationEdit], None]mirror: SourceEditMirror | None = None+ create: SourceCreate | None = None# Where the source's incident destinations listen for a close, and the alert's page in the# source's product. A control-plane close needs both to address its resolve.incident_event_ids: Mapping[str, str] | None = Nonediff --git a/products/alerts_platform/backend/logic/platform_writes.py b/products/alerts_platform/backend/logic/platform_writes.pyindex 4424fb015421..42b757fdc2c4 100644--- a/products/alerts_platform/backend/logic/platform_writes.py+++ b/products/alerts_platform/backend/logic/platform_writes.py@@ -16,6 +16,8 @@ from django.utils import timezone as django_timezonefrom pydantic import ValidationError as PydanticValidationErrorfrom posthog.exceptions_capture import capture_exception+from posthog.models.activity_logging.model_activity import get_current_user, get_was_impersonated+from posthog.models.signals import model_activity_signalfrom products.alerts_platform.backend.facade.contracts import (MAX_EVALUATION_PERIODS,@@ -54,7 +56,7 @@ def edit_of(configuration: PlatformAlertConfiguration) -> PlatformAlertConfiguradef _validated(- source_kind: SourceKind, current: PlatformAlertConfigurationEdit, edit: PlatformAlertConfigurationEdit+ source_kind: SourceKind, current: PlatformAlertConfigurationEdit | None, edit: PlatformAlertConfigurationEdit) -> PlatformAlertConfigurationEdit:spec = source_configs.spec(source_kind)if spec is None:@@ -75,7 +77,7 @@ def _validated(raise InvalidPlatformAlertEdit("schedule_restriction", str(error)) from errorsource_config = edit.source_config# Settings the edit leaves alone may predate the schema, and must not block an unrelated change.- if source_config != current.source_config:+ if current is None or source_config != current.source_config:try:parsed = spec.model.model_validate(source_config)except PydanticValidationError as error:@@ -130,6 +132,44 @@ def update_configuration()+def create_configuration(+ *, team_id: int, source_kind: SourceKind, edit: PlatformAlertConfigurationEdit, created_by_id: int | None+) -> PlatformAlertConfigurationView:+ """Creates an alert the platform owns, through the hook its source registered.++ Raises `PlatformAlertNotEditable` for a kind the API cannot create, `InvalidPlatformAlertEdit` for+ settings its source kind rejects, and `PlatformAlertCreateRefused` when the source refuses.+ """+ spec = source_configs.spec(source_kind)+ if spec is None or spec.create is None:+ raise PlatformAlertNotEditable(f"{source_kind} alerts cannot be created through this API.")+ validated = _validated(source_kind, None, edit)+ with transaction.atomic():+ legacy_configuration_id = spec.create(team_id=team_id, edit=validated, created_by_id=created_by_id)+ configuration = _locked_owned_copy(team_id, legacy_configuration_id)+ if configuration is None:+ raise MissingPlatformCopy(f"The {source_kind} source created no platform copy of {legacy_configuration_id}")+ # The copy was written as the source's and then handed over, so no write logged its creation.+ model_activity_signal.send(+ sender=PlatformAlertConfiguration,+ scope=PlatformAlertConfiguration.__name__,+ before_update=None,+ after_update=configuration,+ activity="created",+ user=get_current_user(),+ was_impersonated=get_was_impersonated(),+ )+ # The source wrote the settings it shares with the copy. This writes the rest, such as grouping.+ _, pending = _apply(configuration, lambda _: validated, now=django_timezone.now())+ control_plane.announce_after_commit(pending)++ view = platform_reads.get_configuration(+ team_id=team_id, source_kinds=[source_kind.value], configuration_id=configuration.id+ )+ assert view is not None+ return view++# A snoozed group keeps its slot under `max_instances`, so a forgotten long snooze would hold it.MAX_GROUP_SNOOZE: Final = timedelta(days=30)diff --git a/products/alerts_platform/backend/presentation/views/platform_alert.py b/products/alerts_platform/backend/presentation/views/platform_alert.pyindex ca203930df0a..0de8b80c9f4e 100644--- a/products/alerts_platform/backend/presentation/views/platform_alert.py+++ b/products/alerts_platform/backend/presentation/views/platform_alert.py@@ -3,8 +3,10 @@ from functools import cache, cached_propertyfrom typing import Any, Literal, castfrom uuid import UUID+from django.db import transaction+from drf_spectacular.utils import OpenApiResponse, PolymorphicProxySerializer, extend_schema, extend_schema_field-from rest_framework import serializers, viewsets+from rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import NotFound, PermissionDenied, ValidationErrorfrom rest_framework.request import Request@@ -13,6 +15,7 @@ from rest_framework.response import Responsefrom posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.pagination import PrecountedLimitOffsetPaginationfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.event_usage import report_user_actionfrom posthog.exceptions import Conflictfrom posthog.models import Team, Userfrom posthog.permissions import (@@ -33,7 +36,9 @@ from products.alerts_platform.backend.facade.contracts import (GroupingMode,InvalidPlatformAlertEdit,OnOverflow,+ PlatformAlertConfigurationEdit,PlatformAlertConfigurationView,+ PlatformAlertCreateRefused,PlatformAlertNotEditable,SourceConfigSpec,SourceKind,@@ -273,6 +278,72 @@ def edit_serializers() -> dict[str, type[PlatformAlertConfigurationEditSerializereturn {source.value: _typed_edit_serializer(source, spec) for source, spec in editable_source_configs().items()}+DEFAULT_ALERT_NAME = "Untitled alert"+++# The default of each setting a create may leave out, with the help text that names it.+CREATE_DEFAULTS: dict[str, tuple[Any, str]] = {+ "name": (DEFAULT_ALERT_NAME, f"Defaults to '{DEFAULT_ALERT_NAME}'."),+ "enabled": (True, "Defaults to true."),+ "grouping": (Grouping, "Defaults to mode single."),+ "schedule_restriction": (None, "Defaults to null."),+ "evaluation_periods": (1, "Defaults to 1."),+ "datapoints_to_alarm": (1, "Defaults to 1."),+ "cooldown_minutes": (0, "Defaults to 0."),+}+++def _with_default(field: serializers.Field, default: Any, note: str) -> serializers.Field:+ # Built again from the edit field's own arguments, so a create validates every setting as an edit does.+ # DRF records every field's constructor arguments on `_args` and `_kwargs`, which its stubs leave out.+ original: dict[str, Any] = field._kwargs # type: ignore[attr-defined]+ args: tuple[Any, ...] = field._args # type: ignore[attr-defined]+ return type(field)(*args, **{**original, "default": default, "help_text": f"{original['help_text']} {note}"})+++def _typed_create_serializer(+ edit_serializer: type[PlatformAlertConfigurationEditSerializer],+) -> type[PlatformAlertConfigurationEditSerializer]:+ """The create serializer for one source kind: its edit serializer, with a default for every+ setting but `source_config`, so a create stores each default and a read returns it."""+ declared = edit_serializer._declared_fields+ return type(+ edit_serializer.__name__.replace("Edit", "Create"),+ (edit_serializer,),+ {+ "__doc__": "The settings of a new alert. Every one but source_config has a default, which is stored.",+ "source_kind": serializers.CharField(+ help_text="Product whose data the alert evaluates. It cannot change after the create.",+ ),+ **{name: _with_default(declared[name], default, note) for name, (default, note) in CREATE_DEFAULTS.items()},+ },+ )+++@cache+def create_serializers() -> dict[str, type[PlatformAlertConfigurationEditSerializer]]:+ """One create serializer per kind whose source registered a create hook."""+ creatable = {source.value for source, spec in editable_source_configs().items() if spec.create is not None}+ return {+ source_kind: _typed_create_serializer(serializer)+ for source_kind, serializer in edit_serializers().items()+ if source_kind in creatable+ }+++PLATFORM_ALERT_CONFIGURATION_CREATE = PolymorphicProxySerializer(+ component_name="PlatformAlertConfigurationCreate",+ serializers=lambda: dict[str, serializers.Serializer | type[serializers.Serializer]](create_serializers()),+ resource_type_field_name="source_kind",+)++CREATE_RESPONSES = {+ 201: PlatformAlertConfigurationSerializer,+ 400: OpenApiResponse(description="The settings are invalid, or the source refused the create."),+ 403: OpenApiResponse(description="The caller cannot write alerts of this source kind."),+ 409: OpenApiResponse(description="The URL names an environment, whose alerts are created on its own page."),+}+PLATFORM_ALERT_CONFIGURATION_EDIT = PolymorphicProxySerializer(component_name="PlatformAlertConfigurationEdit",serializers=lambda: dict[str, serializers.Serializer | type[serializers.Serializer]](edit_serializers()),@@ -407,6 +478,60 @@ class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.Genericraise NotFound()return Response(PlatformAlertConfigurationSerializer(updated).data)+ @extend_schema(request=PLATFORM_ALERT_CONFIGURATION_CREATE, responses=CREATE_RESPONSES)+ def create(self, request: Request, **kwargs) -> Response:+ # The rows live on the project, so an alert made here would count the project's data rather+ # than the environment's that the URL names.+ 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:+ raise ValidationError(+ {"source_kind": f"Must be one of: {', '.join(sorted(create_serializers()))}."}, code="invalid_choice"+ )+ # 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"):+ raise PermissionDenied(f"You cannot create {source_kind} alerts.")++ serializer = create_serializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ fields = dict(serializer.validated_data)+ fields.pop("source_kind")+ try:+ created = platform_api.create_configuration(+ team_id=self._canonical_team_id(),+ source_kind=SourceKind(source_kind),+ edit=PlatformAlertConfigurationEdit(**fields),+ created_by_id=cast(User, request.user).id,+ )+ except PlatformAlertNotEditable as error:+ raise Conflict(str(error)) from error+ except InvalidPlatformAlertEdit as error:+ raise ValidationError({error.field_name: str(error)}) from error+ except PlatformAlertCreateRefused as error:+ raise ValidationError(str(error)) from error+ # Robust, so an analytics failure, such as a malformed Referer, cannot fail a create that committed.+ transaction.on_commit(lambda: self._track("created", created), robust=True)+ return Response(PlatformAlertConfigurationSerializer(created).data, status=status.HTTP_201_CREATED)++ def _track(self, action: Literal["created", "deleted"], configuration: PlatformAlertConfigurationView) -> None:+ report_user_action(+ cast(User, self.request.user),+ f"alert {action}",+ {+ "alert_id": str(configuration.id),+ "alert_name": configuration.name,+ "config_type": "PlatformAlertConfiguration",+ "source_kind": configuration.source_kind,+ "legacy_configuration_id": str(configuration.legacy_configuration_id),+ "enabled": configuration.enabled,+ },+ team=self.team,+ request=self.request,+ )+@extend_schema(request=PLATFORM_ALERT_CONFIGURATION_EDIT, responses=EDIT_RESPONSES)def update(self, request: Request, pk: str, **kwargs) -> Response:return self._edit(request, pk, partial=False)diff --git a/products/alerts_platform/frontend/generated/api.schemas.ts b/products/alerts_platform/frontend/generated/api.schemas.tsindex e46fdd687175..ca0b7e0ca402 100644--- a/products/alerts_platform/frontend/generated/api.schemas.ts+++ b/products/alerts_platform/frontend/generated/api.schemas.ts@@ -245,12 +245,12 @@ export interface PaginatedPlatformAlertConfigurationListApi {}/**- * Product whose data the alert evaluates. It cannot change, so it must match the stored value.+ * Product whose data the alert evaluates. It cannot change after the create.*/-export type LogsPlatformAlertConfigurationEditApiSourceKind =- (typeof LogsPlatformAlertConfigurationEditApiSourceKind)[keyof typeof LogsPlatformAlertConfigurationEditApiSourceKind]+export type LogsPlatformAlertConfigurationCreateApiSourceKind =+ (typeof LogsPlatformAlertConfigurationCreateApiSourceKind)[keyof typeof LogsPlatformAlertConfigurationCreateApiSourceKind]-export const LogsPlatformAlertConfigurationEditApiSourceKind = {+export const LogsPlatformAlertConfigurationCreateApiSourceKind = {Logs: 'logs',} as const@@ -677,6 +677,57 @@ export interface LogsPlatformAlertSourceConfigApi {condition: LogsPlatformAlertConditionApi}+/**+ * The settings of a new alert. Every one but source_config has a default, which is stored.+ */+export interface LogsPlatformAlertConfigurationCreateApi {+ /** Product whose data the alert evaluates. It cannot change after the create. */+ source_kind: LogsPlatformAlertConfigurationCreateApiSourceKind+ /**+ * Human-readable name of the alert. Defaults to 'Untitled alert'.+ * @maxLength 255+ */+ name?: string+ /** Whether the alert is evaluated on schedule. Defaults to true. */+ enabled?: boolean+ /** Settings for a logs alert. The bound the alert is evaluated against is under condition. */+ source_config: LogsPlatformAlertSourceConfigApi+ /** How the alert splits its results into instances. Defaults to mode single. */+ grouping?: GroupingApi+ /** Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. Defaults to null. */+ schedule_restriction?: AlertScheduleRestrictionApi | null+ /**+ * Number of recent checks considered when deciding to fire. Defaults to 1.+ * @minimum 1+ * @maximum 10+ */+ evaluation_periods?: number+ /**+ * Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods. Defaults to 1.+ * @minimum 1+ * @maximum 10+ */+ datapoints_to_alarm?: number+ /**+ * Minimum minutes between notifications for the same alert. Defaults to 0.+ * @minimum 0+ * @maximum 2147483647+ */+ cooldown_minutes?: number+}++export type PlatformAlertConfigurationCreateApi = LogsPlatformAlertConfigurationCreateApi++/**+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.+ */+export type LogsPlatformAlertConfigurationEditApiSourceKind =+ (typeof LogsPlatformAlertConfigurationEditApiSourceKind)[keyof typeof LogsPlatformAlertConfigurationEditApiSourceKind]++export const LogsPlatformAlertConfigurationEditApiSourceKind = {+ Logs: 'logs',+} as const+/*** The settings an edit can change. Each source kind subclasses it with a typed `source_config`.*/diff --git a/products/alerts_platform/frontend/generated/api.ts b/products/alerts_platform/frontend/generated/api.tsindex 351423d93dd5..ab43f12d336c 100644--- a/products/alerts_platform/frontend/generated/api.ts+++ b/products/alerts_platform/frontend/generated/api.ts@@ -13,6 +13,7 @@ import type {PatchedPlatformAlertConfigurationEditApi,PlatformAlertApi,PlatformAlertConfigurationApi,+ PlatformAlertConfigurationCreateApi,PlatformAlertConfigurationEditApi,PlatformAlertGroupSnoozeApi,PlatformAlertsListParams,@@ -45,6 +46,23 @@ export const platformAlertsList = async (})}+export const getPlatformAlertsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/platform_alerts/`+}++export const platformAlertsCreate = async (+ projectId: string,+ platformAlertConfigurationCreateApi?: PlatformAlertConfigurationCreateApi,+ options?: RequestInit+): Promise<PlatformAlertConfigurationApi> => {+ return apiMutator<PlatformAlertConfigurationApi>(getPlatformAlertsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(platformAlertConfigurationCreateApi),+ })+}+export const getPlatformAlertsRetrieveUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/platform_alerts/${id}/`}diff --git a/products/alerts_platform/frontend/generated/api.zod.ts b/products/alerts_platform/frontend/generated/api.zod.tsindex 2ad517a85ea2..217752d6267d 100644--- a/products/alerts_platform/frontend/generated/api.zod.ts+++ b/products/alerts_platform/frontend/generated/api.zod.ts@@ -9,6 +9,173 @@*/import * as zod from 'zod'+export const platformAlertsCreateBodyOneNameDefault = `Untitled alert`+export const platformAlertsCreateBodyOneNameMax = 255++export const platformAlertsCreateBodyOneEnabledDefault = true+export const platformAlertsCreateBodyOneSourceConfigOneConditionThresholdCountMin = 0+export const platformAlertsCreateBodyOneSourceConfigOneConditionThresholdCountMax = 2147483647++export const platformAlertsCreateBodyOneGroupingOneMaxInstancesDefault = 100+export const platformAlertsCreateBodyOneGroupingOneMaxInstancesMax = 100++export const platformAlertsCreateBodyOneGroupingOneOnOverflowDefault = `degrade_visible`+export const platformAlertsCreateBodyOneEvaluationPeriodsDefault = 1+export const platformAlertsCreateBodyOneEvaluationPeriodsMax = 10++export const platformAlertsCreateBodyOneDatapointsToAlarmDefault = 1+export const platformAlertsCreateBodyOneDatapointsToAlarmMax = 10++export const platformAlertsCreateBodyOneCooldownMinutesDefault = 0+export const platformAlertsCreateBodyOneCooldownMinutesMin = 0+export const platformAlertsCreateBodyOneCooldownMinutesMax = 2147483647++export const PlatformAlertsCreateBody = /* @__PURE__ */ zod+ .object({+ source_kind: zod+ .enum(['logs'])+ .describe('Product whose data the alert evaluates. It cannot change after the create.'),+ name: zod+ .string()+ .max(platformAlertsCreateBodyOneNameMax)+ .default(platformAlertsCreateBodyOneNameDefault)+ .describe("Human-readable name of the alert. Defaults to 'Untitled alert'."),+ enabled: zod+ .boolean()+ .default(platformAlertsCreateBodyOneEnabledDefault)+ .describe('Whether the alert is evaluated on schedule. Defaults to true.'),+ source_config: zod+ .object({+ filters: zod+ .object({+ filterGroup: zod+ .union([+ zod.object({+ type: zod.enum(['AND', 'OR']),+ values: zod.array(+ zod+ .record(zod.string(), zod.unknown())+ .describe(+ 'Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)'+ )+ ),+ }),+ zod.null(),+ ])+ .optional(),+ serviceNames: zod.union([zod.array(zod.string()), zod.null()]).optional(),+ severityLevels: zod+ .union([+ zod.array(zod.enum(['trace', 'debug', 'info', 'warn', 'error', 'fatal'])),+ zod.null(),+ ])+ .optional(),+ })+ .describe(+ 'The logs the alert counts: severityLevels, serviceNames, or a filterGroup of property filters. An enabled alert needs at least one.'+ ),+ condition: zod+ .object({+ threshold_count: zod+ .number()+ .min(platformAlertsCreateBodyOneSourceConfigOneConditionThresholdCountMin)+ .max(platformAlertsCreateBodyOneSourceConfigOneConditionThresholdCountMax)+ .describe(+ 'Number of matching log entries in the window that breaches the threshold. Use 0 with the above operator to fire on any matching log.'+ ),+ threshold_operator: zod+ .enum(['above', 'below'])+ .describe('Whether the alert fires when the count is above or below the threshold.'),+ window_minutes: zod+ .union([zod.literal(5), zod.literal(10), zod.literal(15), zod.literal(30), zod.literal(60)])+ .describe('Time window in minutes over which logs are counted.'),+ })+ .describe('The bound the count is checked against.'),+ })+ .describe('Settings for a logs alert. The bound the alert is evaluated against is under condition.'),+ grouping: zod+ .object({+ mode: zod+ .enum(['single', 'by_result_labels'])+ .describe('\* `single` - Single\n\* `by_result_labels` - By result labels')+ .describe(+ 'single keeps one instance for the whole alert. by_result_labels keeps one instance per distinct value of the labels in keys, so each group fires and resolves on its own.\n\n\* `single` - Single\n\* `by_result_labels` - By result labels'+ ),+ keys: zod+ .array(zod.string())+ .optional()+ .describe(+ 'Result labels whose values make a group, such as service_name. Empty for mode single, required for by_result_labels. Changing them deletes the existing instances and closes their notification threads without a message.'+ ),+ max_instances: zod+ .number()+ .min(1)+ .max(platformAlertsCreateBodyOneGroupingOneMaxInstancesMax)+ .default(platformAlertsCreateBodyOneGroupingOneMaxInstancesDefault)+ .describe(+ 'Most instances the alert keeps at once. Groups past it are not tracked, and the last message says how many were left out.'+ ),+ on_overflow: zod+ .enum(['degrade_visible'])+ .describe('\* `degrade_visible` - Degrade visible')+ .default(platformAlertsCreateBodyOneGroupingOneOnOverflowDefault)+ .describe(+ 'What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'+ ),+ })+ .optional()+ .describe('How the alert splits its results into instances. Defaults to mode single.'),+ 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(),+ ])+ .optional()+ .describe(+ 'Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. Defaults to null.'+ ),+ evaluation_periods: zod+ .number()+ .min(1)+ .max(platformAlertsCreateBodyOneEvaluationPeriodsMax)+ .default(platformAlertsCreateBodyOneEvaluationPeriodsDefault)+ .describe('Number of recent checks considered when deciding to fire. Defaults to 1.'),+ datapoints_to_alarm: zod+ .number()+ .min(1)+ .max(platformAlertsCreateBodyOneDatapointsToAlarmMax)+ .default(platformAlertsCreateBodyOneDatapointsToAlarmDefault)+ .describe(+ 'Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods. Defaults to 1.'+ ),+ cooldown_minutes: zod+ .number()+ .min(platformAlertsCreateBodyOneCooldownMinutesMin)+ .max(platformAlertsCreateBodyOneCooldownMinutesMax)+ .default(platformAlertsCreateBodyOneCooldownMinutesDefault)+ .describe('Minimum minutes between notifications for the same alert. Defaults to 0.'),+ })+ .describe('The settings of a new alert. Every one but source_config has a default, which is stored.')+export const platformAlertsUpdateBodyOneNameMax = 255export const platformAlertsUpdateBodyOneSourceConfigOneConditionThresholdCountMin = 0diff --git a/products/logs/backend/alert_creation.py b/products/logs/backend/alert_creation.pynew file mode 100644index 000000000000..5eb4ae9a6b82--- /dev/null+++ b/products/logs/backend/alert_creation.py@@ -0,0 +1,47 @@+"""What every route that creates a logs alert shares: the per-team cap and the first check."""++import os+from datetime import UTC, datetime+from typing import Any++from django.db import connection++from posthog.models.team.team import Team++from products.logs.backend.alert_utils import next_allowed_check_at+from products.logs.backend.models import LogsAlertConfiguration++MAX_ALERTS_PER_TEAM = 20+# Comma-separated team IDs that bypass MAX_ALERTS_PER_TEAM. Configured via+# argocd for internal dogfood projects whose observability needs exceed the+# customer-facing cap; the cap's correctness assumptions (bounded N+1 in list,+# semaphore-sized fan-out in the Temporal activity) still hold for any team+# not in this set.+UNCAPPED_ALERT_TEAM_IDS: frozenset[int] = frozenset(+ int(t) for x in os.environ.get("LOGS_ALERTS_UNCAPPED_TEAM_IDS", "").split(",") if (t := x.strip()).isdigit()+)+++class AlertLimitReached(Exception):+ def __init__(self) -> None:+ super().__init__(f"Maximum number of alerts ({MAX_ALERTS_PER_TEAM}) reached for this team.")+++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}"])+ if team_id in UNCAPPED_ALERT_TEAM_IDS:+ return+ if LogsAlertConfiguration.objects.filter(team_id=team_id).count() >= MAX_ALERTS_PER_TEAM:+ raise AlertLimitReached()+++def first_check_at(team_id: int, schedule_restriction: dict[str, Any]) -> datetime:+ """When a new alert with quiet hours is first checked: now, or the end of the quiet window it is in."""+ return next_allowed_check_at(+ datetime.now(UTC),+ team_timezone=Team.objects.only("timezone").get(id=team_id).timezone,+ schedule_restriction=schedule_restriction,+ )diff --git a/products/logs/backend/facade/api.py b/products/logs/backend/facade/api.pyindex e63339dcc729..831831aea843 100644--- a/products/logs/backend/facade/api.py+++ b/products/logs/backend/facade/api.py@@ -3,6 +3,7 @@ from uuid import UUIDfrom django.db import transactionfrom products.logs.backend import alert_incidents+from products.logs.backend.alert_creation import AlertLimitReached, claim_alert_slot, first_check_atfrom products.logs.backend.alert_state_machine import FIRING_STATES, IncidentCloseReason, IncidentEdge, incident_edgefrom products.logs.backend.alert_utils import next_allowed_check_atfrom products.logs.backend.models import LogsAlertConfiguration@@ -24,13 +25,16 @@ from products.logs.backend.tasks.tasks import follow_logs_alert_task__all__ = ["ALLOWED_WINDOW_MINUTES",+ "AlertLimitReached","MAX_MERGED_EVENT_ROWS","NaturalLanguageQueryFailed","NaturalLanguageQueryUnavailable","PlatformCheckRow","PlatformCheckRows",+ "claim_alert_slot","close_incident_before_delete","close_incident_on_commit",+ "first_check_at","follow_logs_alert","has_any_filter","is_valid_date",diff --git a/products/logs/backend/platform_ownership.py b/products/logs/backend/platform_ownership.pyindex 0946489dc2c1..3acc23b3c92e 100644--- a/products/logs/backend/platform_ownership.py+++ b/products/logs/backend/platform_ownership.py@@ -20,8 +20,10 @@ from products.alerts_platform.backend.facade.contracts import (GroupingMode,InvalidPlatformAlertEdit,PlatformAlertConfigurationEdit,+ PlatformAlertCreateRefused,PlatformAlertNotEditable,)+from products.logs.backend.alert_creation import AlertLimitReached, claim_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@@ -59,6 +61,31 @@ 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, as a create through the logs API does in a team that has begun the cutover.++ The team counts as begun from then on, because the platform owns one of its logs alerts.+ """+ try:+ claim_alert_slot(team_id)+ except AlertLimitReached as error:+ raise PlatformAlertCreateRefused(str(error)) from error+ now = timezone.now()+ alert = LogsAlertConfiguration(+ team_id=team_id,+ created_by_id=created_by_id,+ enabled=edit.enabled,+ first_enabled_at=now if edit.enabled else None,+ next_check_at=first_check_at(team_id, edit.schedule_restriction) if edit.schedule_restriction else None,+ )+ _set_settings(alert, edit)+ alert.save()+ if not hand_over(alert, now, grouping=edit.grouping):+ raise RuntimeError(f"Logs alert {alert.id} was created with a platform copy already firing")+ return alert.id++def on_updated(alert: LogsAlertConfiguration, *, snooze_changed: bool, grouping: Grouping | None = None) -> None:"""Writes an edit the logs API saved onto the platform's copy, with the grouping the edit set.A `grouping` of None keeps the copy's own. An alert logs owns has no copy to write.@@ -110,17 +137,21 @@ def mirror_platform_edit(return lambda edit: _write_logs_row(alert, edit)-def _write_logs_row(alert: LogsAlertConfiguration, edit: PlatformAlertConfigurationEdit) -> None:+def _set_settings(alert: LogsAlertConfiguration, edit: PlatformAlertConfigurationEdit) -> None:# The inverse of `platform_upsert_of`, over the same field lists.condition = edit.source_config[SOURCE_CONDITION_KEY]- # The shadow evaluation still runs this row, so an on or off moves its state the way the logs API does.- enabled_fields = apply_enabled(alert, edit.enabled, now=timezone.now())alert.filters = filters_of(edit.source_config)for field in CONDITION_FIELDS:setattr(alert, field, condition[field])for field in SETTINGS_FIELDS:if field != "source_config":setattr(alert, field, getattr(edit, field))+++def _write_logs_row(alert: LogsAlertConfiguration, edit: PlatformAlertConfigurationEdit) -> None:+ # The shadow evaluation still runs this row, so an on or off moves its state the way the logs API does.+ enabled_fields = apply_enabled(alert, edit.enabled, now=timezone.now())+ _set_settings(alert, edit)alert.save(update_fields=[*enabled_fields,diff --git a/products/logs/backend/platform_source_config_schema.py b/products/logs/backend/platform_source_config_schema.pyindex 120282035ca0..0f88f5bcd1a1 100644--- a/products/logs/backend/platform_source_config_schema.py+++ b/products/logs/backend/platform_source_config_schema.py@@ -19,7 +19,7 @@ from products.alerts_platform.backend.facade.contracts import (from 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 mirror_platform_edit+from products.logs.backend.platform_ownership import create_platform_owned, mirror_platform_editfrom products.logs.backend.platform_source_config import WindowMinutes, has_any_filter, logs_alert_url@@ -68,6 +68,7 @@ LOGS_SOURCE_CONFIG = SourceConfigSpec(model=LogsPlatformAlertSourceConfig,validate=validate_logs_edit,mirror=mirror_platform_edit,+ create=create_platform_owned,incident_event_ids=EVENT_IDS_BY_INCIDENT_ACTION,alert_url=logs_alert_url,)diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.pyindex fa01b019182d..9a0e965c16e7 100644--- a/products/logs/backend/presentation/views/alerts_api.py+++ b/products/logs/backend/presentation/views/alerts_api.py@@ -1,4 +1,3 @@-import osimport datetime as dtfrom collections.abc import Callable, Sequencefrom datetime import UTC, datetime@@ -32,7 +31,6 @@ from posthog.exceptions import as_drf_validation_errorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.impersonation import is_impersonatedfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activity-from posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.utils import relative_date_parse@@ -99,8 +97,11 @@ from products.logs.backend.alert_state_machine import (from products.logs.backend.facade.api import (ALLOWED_WINDOW_MINUTES,MAX_MERGED_EVENT_ROWS,+ AlertLimitReached,PlatformCheckRow,+ claim_alert_slot,close_incident_on_commit,+ first_check_at,follow_logs_alert,has_any_filter,logs_state_of_platform,@@ -110,15 +111,6 @@ from products.logs.backend.facade.api import (from products.logs.backend.facade.platform_ownership import before_delete, on_created, on_deleted, on_updatedfrom products.logs.backend.models import MAX_EVALUATION_PERIODS, LogsAlertConfiguration, LogsAlertEvent-MAX_ALERTS_PER_TEAM = 20-# Comma-separated team IDs that bypass MAX_ALERTS_PER_TEAM. Configured via-# argocd for internal dogfood projects whose observability needs exceed the-# customer-facing cap; the cap's correctness assumptions (bounded N+1 in list,-# semaphore-sized fan-out in the Temporal activity) still hold for any team-# not in this set.-UNCAPPED_ALERT_TEAM_IDS: frozenset[int] = frozenset(- int(t) for x in os.environ.get("LOGS_ALERTS_UNCAPPED_TEAM_IDS", "").split(",") if (t := x.strip()).isdigit()-)MAX_SIMULATE_LOOKBACK_DAYS = 30MAX_SIMULATE_BUCKETS = 15_000MAX_DESTINATION_IDS_PER_DELETE_REQUEST = 100@@ -900,20 +892,12 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):grouping: Grouping | None = validated_data.pop("grouping", None)with transaction.atomic():- # select_for_update().count() doesn't acquire row locks because- # Django optimises count() to SELECT COUNT(*). Locking the team- # row instead serialises concurrent creates for this team.- team = Team.objects.select_for_update().get(id=validated_data["team_id"])- if validated_data["team_id"] not in UNCAPPED_ALERT_TEAM_IDS:- count = LogsAlertConfiguration.objects.filter(team_id=validated_data["team_id"]).count()- if count >= MAX_ALERTS_PER_TEAM:- raise ValidationError(f"Maximum number of alerts ({MAX_ALERTS_PER_TEAM}) reached for this team.")+ try:+ claim_alert_slot(validated_data["team_id"])+ except AlertLimitReached as error:+ raise ValidationError(str(error)) from errorif schedule_restriction := validated_data.get("schedule_restriction"):- validated_data["next_check_at"] = next_allowed_check_at(- datetime.now(UTC),- team_timezone=team.timezone,- schedule_restriction=schedule_restriction,- )+ validated_data["next_check_at"] = first_check_at(validated_data["team_id"], schedule_restriction)created = super().create(validated_data)# Raised inside the transaction, so a grouping the alert cannot take leaves no alert behind.if _write_platform_edit(diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.pyindex 6018f43ce32d..103ff0b6b520 100644--- a/products/logs/backend/test/test_alerts_api.py+++ b/products/logs/backend/test/test_alerts_api.py@@ -20,6 +20,7 @@ from rest_framework.test import APIClientfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.log_entries import INSERT_LOG_ENTRY_SQL+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.scoping import team_scopefrom posthog.models.team.team import Teamfrom posthog.models.user import User@@ -39,6 +40,7 @@ from products.cdp.backend.templates.fixtures import template_pagerduty, templatefrom products.cdp.backend.templates.hog_function_template import sync_template_to_dbfrom products.cdp.backend.templates.microsoft_teams.template_microsoft_teams import template as template_microsoft_teamsfrom products.logs.backend.alert_check_query import AlertCheckQuery, BucketedCount+from products.logs.backend.alert_creation import MAX_ALERTS_PER_TEAMfrom products.logs.backend.models import LogsAlertConfiguration, LogsAlertEventfrom products.logs.backend.platform_alert_backfill import (backfill_platform_alert_configurations,@@ -49,7 +51,6 @@ from products.logs.backend.platform_alert_backfill import (from products.logs.backend.platform_cutover import cut_over_team, hand_overfrom products.logs.backend.presentation.views.alerts_api import (ALLOWED_WINDOW_MINUTES,- MAX_ALERTS_PER_TEAM,MAX_DESTINATION_IDS_PER_DELETE_REQUEST,LogsAlertViewSet,)@@ -715,7 +716,7 @@ class TestLogsAlertAPI(APIBaseTest):)patched_ids = frozenset({self.team.id}) if uncapped else frozenset()- with patch("products.logs.backend.presentation.views.alerts_api.UNCAPPED_ALERT_TEAM_IDS", patched_ids):+ with patch("products.logs.backend.alert_creation.UNCAPPED_ALERT_TEAM_IDS", patched_ids):response = self.client.post(self.base_url,self._valid_payload(name="Boundary"),@@ -2451,6 +2452,122 @@ class TestLogsAlertAPI(APIBaseTest):True,)+ def _create_on_the_platform(self, body: dict, team_id: int | None = None) -> Any:+ with patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True):+ return self.client.post(f"/api/projects/{team_id or self.team.id}/platform_alerts/", body, format="json")++ def test_the_platform_api_creates_both_rows_with_every_default_stored(self) -> None:+ response = self._create_on_the_platform(+ {+ "source_kind": "logs",+ "source_config": {+ "filters": {"serviceNames": ["api"]},+ "condition": {"threshold_count": 5, "threshold_operator": "above", "window_minutes": 10},+ },+ "grouping": {"mode": "by_result_labels", "keys": ["service_name"]},+ }+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ created = response.json()+ with patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True):+ read = self.client.get(f"/api/projects/{self.team.id}/platform_alerts/{created['id']}/").json()+ assert read == created+ assert {+ key: created[key] for key in ("name", "enabled", "owner", "evaluation_periods", "cooldown_minutes")+ } == {+ "name": "Untitled alert",+ "enabled": True,+ "owner": "platform",+ "evaluation_periods": 1,+ "cooldown_minutes": 0,+ }+ assert created["grouping"] == {+ "mode": "by_result_labels",+ "keys": ["service_name"],+ "max_instances": 100,+ "on_overflow": "degrade_visible",+ }+ alert = LogsAlertConfiguration.objects.get(pk=created["legacy_configuration_id"])+ assert (alert.platform_owned, alert.filters, alert.threshold_count, alert.window_minutes, alert.created_by) == (+ True,+ {"serviceNames": ["api"]},+ 5,+ 10,+ self.user,+ )+ assert ActivityLog.objects.filter(+ scope="PlatformAlertConfiguration", item_id=created["id"], activity="created", user=self.user+ ).exists()++ @parameterized.expand(+ [+ ("logs_write_only", ["logs:write"], status.HTTP_403_FORBIDDEN),+ ("logs_read_only", ["alert:write", "logs:read"], status.HTTP_403_FORBIDDEN),+ ("alert_and_logs_write", ["alert:write", "logs:write"], status.HTTP_201_CREATED),+ ]+ )+ def test_a_platform_create_needs_write_access_to_alerts_and_logs(+ self, _name: str, key_scopes: list[str], expected: int+ ) -> None:+ self.client.logout()+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {self.create_personal_api_key_with_scopes(key_scopes)}")++ response = self._create_on_the_platform(+ {+ "source_kind": "logs",+ "source_config": {+ "filters": {"severityLevels": ["error"]},+ "condition": {"threshold_count": 1, "threshold_operator": "above", "window_minutes": 5},+ },+ }+ )++ assert response.status_code == expected, response.json()+ assert LogsAlertConfiguration.objects.filter(team=self.team).exists() == (expected == status.HTTP_201_CREATED)++ @parameterized.expand(+ [+ ("unservable_kind", {"source_kind": "insight"}, None, False, status.HTTP_400_BAD_REQUEST, "source_kind"),+ (+ "enabled_without_filters",+ {"source_config": {"filters": {}}},+ None,+ False,+ status.HTTP_400_BAD_REQUEST,+ "source_config",+ ),+ ("over_the_cap", {}, 0, False, status.HTTP_400_BAD_REQUEST, None),+ ("environment_url", {}, None, True, status.HTTP_409_CONFLICT, None),+ ]+ )+ def test_a_refused_platform_create_writes_neither_row(+ self,+ _name: str,+ overrides: dict,+ cap: int | None,+ on_an_environment: bool,+ expected: int,+ field: str | None,+ ) -> None:+ condition = {"threshold_count": 1, "threshold_operator": "above", "window_minutes": 5}+ body = {"source_kind": "logs", "source_config": {"filters": {"severityLevels": ["error"]}}, **overrides}+ body["source_config"] = {**body["source_config"], "condition": condition}+ environment = (+ Team.objects.create(organization=self.organization, parent_team=self.team, name="env")+ if on_an_environment+ else None+ )++ with patch("products.logs.backend.alert_creation.MAX_ALERTS_PER_TEAM", cap if cap is not None else 20):+ response = self._create_on_the_platform(body, team_id=environment.id if environment else None)++ assert response.status_code == expected, response.json()+ assert response.json()["attr"] == field+ assert not LogsAlertConfiguration.objects.exists()+ with team_scope(self.team.id):+ assert list_configurations(team_id=self.team.id, source_kinds=["logs"], limit=1, offset=0).total == 0+def test_a_new_alert_in_a_team_the_platform_has_begun_taking_over_starts_on_the_platform(self) -> None:self._owned_by_the_platform()diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 95b02818a8a9..13cc7c033c10 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -65405,12 +65405,12 @@ export namespace Schemas {}/**- * Product whose data the alert evaluates. It cannot change, so it must match the stored value.+ * Product whose data the alert evaluates. It cannot change after the create.*/- export type LogsPlatformAlertConfigurationEditSourceKind = typeof LogsPlatformAlertConfigurationEditSourceKind[keyof typeof LogsPlatformAlertConfigurationEditSourceKind];+ export type LogsPlatformAlertConfigurationCreateSourceKind = typeof LogsPlatformAlertConfigurationCreateSourceKind[keyof typeof LogsPlatformAlertConfigurationCreateSourceKind];- export const LogsPlatformAlertConfigurationEditSourceKind = {+ export const LogsPlatformAlertConfigurationCreateSourceKind = {Logs: 'logs',} as const;@@ -65421,6 +65421,55 @@ export namespace Schemas {condition: LogsPlatformAlertCondition;}+ /**+ * The settings of a new alert. Every one but source_config has a default, which is stored.+ */+ export interface LogsPlatformAlertConfigurationCreate {+ /** Product whose data the alert evaluates. It cannot change after the create. */+ source_kind: LogsPlatformAlertConfigurationCreateSourceKind;+ /**+ * Human-readable name of the alert. Defaults to 'Untitled alert'.+ * @maxLength 255+ */+ name?: string;+ /** Whether the alert is evaluated on schedule. Defaults to true. */+ enabled?: boolean;+ /** Settings for a logs alert. The bound the alert is evaluated against is under condition. */+ source_config: LogsPlatformAlertSourceConfig;+ /** How the alert splits its results into instances. Defaults to mode single. */+ grouping?: Grouping;+ /** Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. Defaults to null. */+ schedule_restriction?: AlertScheduleRestriction | null;+ /**+ * Number of recent checks considered when deciding to fire. Defaults to 1.+ * @minimum 1+ * @maximum 10+ */+ evaluation_periods?: number;+ /**+ * Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods. Defaults to 1.+ * @minimum 1+ * @maximum 10+ */+ datapoints_to_alarm?: number;+ /**+ * Minimum minutes between notifications for the same alert. Defaults to 0.+ * @minimum 0+ * @maximum 2147483647+ */+ cooldown_minutes?: number;+ }++ /**+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.+ */+ export type LogsPlatformAlertConfigurationEditSourceKind = typeof LogsPlatformAlertConfigurationEditSourceKind[keyof typeof LogsPlatformAlertConfigurationEditSourceKind];+++ export const LogsPlatformAlertConfigurationEditSourceKind = {+ Logs: 'logs',+ } as const;+/*** The settings an edit can change. Each source kind subclasses it with a typed `source_config`.*/@@ -89746,6 +89795,8 @@ export namespace Schemas {created_at: string | null;}+ export type PlatformAlertConfigurationCreate = LogsPlatformAlertConfigurationCreate;+export type PlatformAlertConfigurationEdit = LogsPlatformAlertConfigurationEdit;export interface PlatformAlertGroupSnooze {