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): edit a platform-owned alert through the platform api (#118291)

Jimmy Zhu462d84e14740
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.py
index 945e8f6d61d4..84009b0db9ce 100644
--- a/products/alerts_platform/backend/facade/api.py
+++ b/products/alerts_platform/backend/facade/api.py
@@ -7,13 +7,14 @@ so every write and every scheduling rule has one home.
from __future__ import annotations
-from collections.abc import Collection, Sequence
+from collections.abc import Callable, Collection, Sequence
from datetime import datetime
from uuid import UUID
from products.alerts_platform.backend.facade.contracts import (
HandbackRefusal,
PlatformAlertCheckInput,
+ PlatformAlertConfigurationEdit,
PlatformAlertConfigurationPage,
PlatformAlertConfigurationView,
PlatformAlertHistory,
@@ -24,7 +25,7 @@ from products.alerts_platform.backend.facade.contracts import (
PlatformOwnershipHandover,
SourceKind,
)
-from products.alerts_platform.backend.logic import platform_lifecycle, platform_reads
+from products.alerts_platform.backend.logic import platform_lifecycle, platform_reads, platform_writes
def due_checks(
@@ -130,3 +131,20 @@ def history_by_legacy_id(
return platform_reads.history_by_legacy_id(
team_id=team_id, legacy_configuration_ids=legacy_configuration_ids, since=since, until=until
)
+
+
+def update_configuration(
+ *,
+ team_id: int,
+ source_kinds: Sequence[str],
+ configuration_id: UUID,
+ change: Callable[[PlatformAlertConfigurationEdit], PlatformAlertConfigurationEdit],
+) -> PlatformAlertConfigurationView | None:
+ """Applies an edit to a configuration the platform owns, or None when the caller cannot read it.
+
+ Raises `PlatformAlertNotEditable` for a configuration its source owns, and
+ `InvalidPlatformAlertEdit` for an edit its source kind rejects.
+ """
+ return platform_writes.update_configuration(
+ team_id=team_id, source_kinds=source_kinds, configuration_id=configuration_id, change=change
+ )
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index 634305aba6bf..d9973b2a33fe 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -20,6 +20,8 @@ from posthog.enums import LabeledStrEnum
from products.alerts_platform.backend.facade.enums import DeliveryPath, PlatformAlertCheckStatus, PlatformAlertState
if TYPE_CHECKING:
+ from pydantic import BaseModel
+
# facade.lifecycle imports this module, so the policy type stays off the runtime import path.
from products.alerts_platform.backend.facade.lifecycle import AlertPolicy
@@ -103,20 +105,24 @@ def source_condition(source_config: dict[str, Any]) -> dict[str, Any]:
return condition if isinstance(condition, dict) else {}
-class GroupingMode(StrEnum):
- SINGLE = "single"
- BY_RESULT_LABELS = "by_result_labels"
+class GroupingMode(LabeledStrEnum):
+ SINGLE = "single", "Single"
+ BY_RESULT_LABELS = "by_result_labels", "By result labels"
-class OnOverflow(StrEnum):
+class OnOverflow(LabeledStrEnum):
# The only mode, because a cap that drops groups silently reads the same as nothing being wrong.
- DEGRADE_VISIBLE = "degrade_visible"
+ DEGRADE_VISIBLE = "degrade_visible", "Degrade visible"
DEFAULT_MAX_INSTANCES: Final = 100
# One check's outcome carries a group per instance, and it crosses Temporal whole, so
# `MAX_BATCH_PAYLOAD_BYTES` is sized to hold this many groups with their keys and labels at full length.
MAX_INSTANCES_CEILING: Final = 100
+# The largest value a Postgres `integer` column holds, which bounds every stored count and duration.
+MAX_STORED_INTEGER: Final = 2_147_483_647
+# The most recent checks an N-of-M decision can look back over.
+MAX_EVALUATION_PERIODS: Final = 10
@frozen
@@ -790,11 +796,60 @@ class PlatformAlertConfigurationView:
next_check_at: datetime | None
consecutive_failures: int
legacy_configuration_id: UUID | None
+ grouping: Grouping
+ snooze_until: datetime | None
+ check_status: str
+ owner: str
created_at: datetime
updated_at: datetime
alerts: tuple[PlatformAlertSnapshot, ...]
+@frozen
+class PlatformAlertConfigurationEdit:
+ """The settings of a configuration that its owner may change through the API.
+
+ The schedule, the source kind and every runtime field stay out, because a write that could set
+ them would read as drift on the next check.
+ """
+
+ name: str
+ enabled: bool
+ source_config: dict[str, Any]
+ grouping: Grouping
+ schedule_restriction: dict[str, Any] | None
+ evaluation_periods: int
+ datapoints_to_alarm: int
+ cooldown_minutes: int
+
+
+class InvalidPlatformAlertEdit(ValueError):
+ """An edit the configuration's source kind rejects, naming the field at fault."""
+
+ def __init__(self, field_name: str, message: str) -> None:
+ super().__init__(message)
+ self.field_name = field_name
+
+
+class PlatformAlertNotEditable(Exception):
+ """A configuration the platform does not own, so its source's own API writes it."""
+
+
+@frozen
+class SourceConfigSpec:
+ """A source kind's schema for `source_config` and its rules for a whole edit.
+
+ `model` validates `source_config` and supplies its defaults. `validate` raises
+ `InvalidPlatformAlertEdit` for a rule that spans fields, such as one that reads `enabled`.
+ """
+
+ model: type[BaseModel]
+ validate: Callable[[PlatformAlertConfigurationEdit], None]
+
+
+SourceConfigLoader = Callable[[], SourceConfigSpec]
+
+
@frozen
class PlatformAlertConfigurationPage:
"""One page of configurations, with the total the reader needs to paginate."""
diff --git a/products/alerts_platform/backend/facade/source_configs.py b/products/alerts_platform/backend/facade/source_configs.py
new file mode 100644
index 000000000000..60f76309a8b0
--- /dev/null
+++ b/products/alerts_platform/backend/facade/source_configs.py
@@ -0,0 +1,13 @@
+"""Facade for the schema each source kind gives its `source_config`."""
+
+from products.alerts_platform.backend.facade.contracts import SourceConfigLoader, SourceConfigSpec, SourceKind
+from products.alerts_platform.backend.logic import source_configs
+
+
+def register_source_config(source: SourceKind, loader: SourceConfigLoader) -> None:
+ source_configs.register(source, loader)
+
+
+def editable_source_configs() -> dict[SourceKind, SourceConfigSpec]:
+ """Every kind the API can write, with its schema. Loads each schema on first call."""
+ return source_configs.specs()
diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.py
index ebc13cc60a22..10645b791485 100644
--- a/products/alerts_platform/backend/logic/platform_lifecycle.py
+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py
@@ -24,6 +24,7 @@ from products.alerts_platform.backend.facade.contracts import (
HandbackRefusal,
InstanceCheckState,
PlatformAlertCheckInput,
+ PlatformAlertConfigurationEdit,
PlatformAlertOutcome,
PlatformAlertUpsert,
PlatformHandback,
@@ -45,7 +46,7 @@ from products.alerts_platform.backend.facade.scheduling import (
validate_and_normalize_schedule_start_time,
)
from products.alerts_platform.backend.logic.platform_alert_events import PlatformAlertEventRow, insert_events
-from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration
+from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration, PlatformAlertThread
def due_q(moment: datetime) -> Q:
@@ -632,6 +633,56 @@ def upsert_configuration(upsert: PlatformAlertUpsert, *, revive: bool = False) -
return created
+def write_edit(
+ configuration: PlatformAlertConfiguration,
+ edit: PlatformAlertConfigurationEdit,
+ *,
+ regrouped: bool,
+ now: datetime,
+) -> None:
+ """Writes an edit made through an API onto a configuration locked by the caller.
+
+ Here rather than with the edit's validation, because it writes `enabled` and the failure state,
+ which only this module changes.
+ """
+ if regrouped:
+ # The old keys never come back from a check, so each old instance would resolve and
+ # announce a recovery that did not happen. They go, threads included, without a message.
+ PlatformAlert.objects.for_team(configuration.team_id, canonical=True).filter(
+ configuration=configuration
+ ).delete()
+ PlatformAlertThread.objects.for_team(configuration.team_id, canonical=True).filter(
+ configuration=configuration
+ ).delete()
+ update_fields = [
+ "name",
+ "enabled",
+ "source_config",
+ "grouping",
+ "schedule_restriction",
+ "evaluation_periods",
+ "datapoints_to_alarm",
+ "cooldown_minutes",
+ "updated_at",
+ ]
+ # An alert turned back on starts clean, as a revived copy does. A BROKEN one would otherwise stay
+ # out of discovery for good.
+ if edit.enabled and not configuration.enabled:
+ configuration.consecutive_failures = 0
+ configuration.check_status = PlatformAlertConfiguration.CheckStatus.OK
+ configuration.next_check_at = now + _REVIVE_FENCE
+ update_fields += ["consecutive_failures", "check_status", "next_check_at"]
+ configuration.name = edit.name
+ configuration.enabled = edit.enabled
+ configuration.source_config = edit.source_config
+ configuration.grouping = edit.grouping.to_stored()
+ configuration.schedule_restriction = edit.schedule_restriction
+ configuration.evaluation_periods = edit.evaluation_periods
+ configuration.datapoints_to_alarm = edit.datapoints_to_alarm
+ configuration.cooldown_minutes = edit.cooldown_minutes
+ configuration.save(update_fields=update_fields)
+
+
def upsert_if_running(upsert: PlatformAlertUpsert, *, revive: bool = False) -> None:
"""Copies one configuration in when its team already runs that source here.
diff --git a/products/alerts_platform/backend/logic/platform_reads.py b/products/alerts_platform/backend/logic/platform_reads.py
index 931da5f5778a..8511f1871fc0 100644
--- a/products/alerts_platform/backend/logic/platform_reads.py
+++ b/products/alerts_platform/backend/logic/platform_reads.py
@@ -11,6 +11,7 @@ from uuid import UUID
from django.db.models import OuterRef, Prefetch, QuerySet, Subquery
from products.alerts_platform.backend.facade.contracts import (
+ Grouping,
InstanceCheckState,
PlatformAlertConfigurationPage,
PlatformAlertConfigurationView,
@@ -64,6 +65,10 @@ def _configuration_view(configuration: PlatformAlertConfiguration) -> PlatformAl
next_check_at=configuration.next_check_at,
consecutive_failures=configuration.consecutive_failures,
legacy_configuration_id=configuration.legacy_configuration_id,
+ grouping=Grouping.from_stored(configuration.grouping),
+ snooze_until=configuration.snooze_until,
+ check_status=configuration.check_status,
+ owner=configuration.owner,
created_at=configuration.created_at,
updated_at=configuration.updated_at,
alerts=tuple(instance_view(alert, configuration) for alert in configuration.alerts.all()),
diff --git a/products/alerts_platform/backend/logic/platform_writes.py b/products/alerts_platform/backend/logic/platform_writes.py
new file mode 100644
index 000000000000..4fc9a6896281
--- /dev/null
+++ b/products/alerts_platform/backend/logic/platform_writes.py
@@ -0,0 +1,114 @@
+"""Writes to a configuration through the API, for the configurations the platform owns.
+
+A configuration its source owns is a copy of the source's own row, which the source's API writes
+and the next check reads back. Writing the copy here would fork it, so those are refused.
+"""
+
+from collections.abc import Callable, Sequence
+from dataclasses import replace
+from uuid import UUID
+
+from django.db import transaction
+from django.utils import timezone as django_timezone
+
+from pydantic import ValidationError as PydanticValidationError
+
+from products.alerts_platform.backend.facade.contracts import (
+ MAX_EVALUATION_PERIODS,
+ MAX_STORED_INTEGER,
+ Grouping,
+ InvalidPlatformAlertEdit,
+ PlatformAlertConfigurationEdit,
+ PlatformAlertConfigurationView,
+ PlatformAlertNotEditable,
+ SourceKind,
+)
+from products.alerts_platform.backend.facade.enums import PlatformAlertOwner
+from products.alerts_platform.backend.facade.scheduling import validate_and_normalize_schedule_restriction
+from products.alerts_platform.backend.logic import platform_lifecycle, platform_reads, source_configs
+from products.alerts_platform.backend.models import PlatformAlertConfiguration
+
+
+def edit_of(configuration: PlatformAlertConfiguration) -> PlatformAlertConfigurationEdit:
+ return PlatformAlertConfigurationEdit(
+ name=configuration.name,
+ enabled=configuration.enabled,
+ source_config=configuration.source_config,
+ grouping=Grouping.from_stored(configuration.grouping),
+ schedule_restriction=configuration.schedule_restriction,
+ evaluation_periods=configuration.evaluation_periods,
+ datapoints_to_alarm=configuration.datapoints_to_alarm,
+ cooldown_minutes=configuration.cooldown_minutes,
+ )
+
+
+def _validated(
+ source_kind: SourceKind, current: PlatformAlertConfigurationEdit, edit: PlatformAlertConfigurationEdit
+) -> PlatformAlertConfigurationEdit:
+ spec = source_configs.spec(source_kind)
+ if spec is None:
+ raise PlatformAlertNotEditable(f"{source_kind} alerts cannot be edited through this API.")
+ for name, value in (
+ ("evaluation_periods", edit.evaluation_periods),
+ ("datapoints_to_alarm", edit.datapoints_to_alarm),
+ ):
+ if not 1 <= value <= MAX_EVALUATION_PERIODS:
+ raise InvalidPlatformAlertEdit(name, f"Must be between 1 and {MAX_EVALUATION_PERIODS}.")
+ if edit.datapoints_to_alarm > edit.evaluation_periods:
+ raise InvalidPlatformAlertEdit("datapoints_to_alarm", "Cannot exceed evaluation_periods.")
+ if not 0 <= edit.cooldown_minutes <= MAX_STORED_INTEGER:
+ raise InvalidPlatformAlertEdit("cooldown_minutes", f"Must be between 0 and {MAX_STORED_INTEGER}.")
+ try:
+ schedule_restriction = validate_and_normalize_schedule_restriction(edit.schedule_restriction)
+ except ValueError as error:
+ raise InvalidPlatformAlertEdit("schedule_restriction", str(error)) from error
+ source_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:
+ try:
+ parsed = spec.model.model_validate(source_config)
+ except PydanticValidationError as error:
+ first = error.errors()[0]
+ location = ".".join(str(part) for part in first["loc"])
+ raise InvalidPlatformAlertEdit("source_config", f"Invalid at `{location}`: {first['msg']}") from error
+ source_config = parsed.model_dump(mode="json", exclude_unset=True)
+ validated = replace(edit, source_config=source_config, schedule_restriction=schedule_restriction)
+ spec.validate(validated)
+ return validated
+
+
+def update_configuration(
+ *,
+ team_id: int,
+ source_kinds: Sequence[str],
+ configuration_id: UUID,
+ change: Callable[[PlatformAlertConfigurationEdit], PlatformAlertConfigurationEdit],
+) -> PlatformAlertConfigurationView | None:
+ """Applies `change` to the configuration's current settings under its row lock.
+
+ None when the configuration does not exist or its kind is not among `source_kinds`. Taking a
+ function rather than the new settings lets a partial update merge with what is stored inside
+ the lock, so two partial updates of different fields both survive.
+ """
+ with transaction.atomic():
+ configuration = (
+ PlatformAlertConfiguration.objects.for_team(team_id, canonical=True)
+ .select_for_update()
+ .filter(id=configuration_id, source_kind__in=list(source_kinds))
+ .first()
+ )
+ if configuration is None:
+ return None
+ if configuration.owner != PlatformAlertOwner.PLATFORM:
+ raise PlatformAlertNotEditable(
+ f"This alert is managed by the {configuration.source_kind} product. Edit it there."
+ )
+ current = edit_of(configuration)
+ edit = _validated(SourceKind(configuration.source_kind), current, change(current))
+
+ regrouped = (edit.grouping.mode, edit.grouping.keys) != (current.grouping.mode, current.grouping.keys)
+ platform_lifecycle.write_edit(configuration, edit, regrouped=regrouped, now=django_timezone.now())
+
+ return platform_reads.get_configuration(
+ team_id=team_id, source_kinds=source_kinds, configuration_id=configuration_id
+ )
diff --git a/products/alerts_platform/backend/logic/source_configs.py b/products/alerts_platform/backend/logic/source_configs.py
new file mode 100644
index 000000000000..e95d92911e4c
--- /dev/null
+++ b/products/alerts_platform/backend/logic/source_configs.py
@@ -0,0 +1,36 @@
+"""Each source kind's schema for `source_config`, which the source supplies.
+
+The platform imports no source, so a source registers a loader here when Django starts, the way it
+registers its describer. A loader rather than the schema, because `ready()` runs in every process
+and a schema is built on `posthog.schema`, which most processes never need.
+"""
+
+from products.alerts_platform.backend.facade.contracts import SourceConfigLoader, SourceConfigSpec, SourceKind
+
+_loaders: dict[SourceKind, SourceConfigLoader] = {}
+_specs: dict[SourceKind, SourceConfigSpec] = {}
+
+
+def register(source: SourceKind, loader: SourceConfigLoader) -> None:
+ # One owner per source. A second registrant would silently change what another product accepts.
+ registered = _loaders.get(source)
+ if registered is not None and registered is not loader:
+ raise RuntimeError(f"A different source config loader is already registered for {source} alerts.")
+ _loaders[source] = loader
+
+
+def _loaded(source: SourceKind, loader: SourceConfigLoader) -> SourceConfigSpec:
+ if source not in _specs:
+ _specs[source] = loader()
+ return _specs[source]
+
+
+def spec(source: SourceKind) -> SourceConfigSpec | None:
+ """The source's schema and rules, or None when the source registered none."""
+ loader = _loaders.get(source)
+ return None if loader is None else _loaded(source, loader)
+
+
+def specs() -> dict[SourceKind, SourceConfigSpec]:
+ """Every registered kind's schema, in a stable order so the published schema does not reorder."""
+ return {source: _loaded(source, _loaders[source]) for source in sorted(_loaders, key=lambda s: s.value)}
diff --git a/products/alerts_platform/backend/presentation/views/platform_alert.py b/products/alerts_platform/backend/presentation/views/platform_alert.py
index cb35ea51ace3..a04c156ec545 100644
--- a/products/alerts_platform/backend/presentation/views/platform_alert.py
+++ b/products/alerts_platform/backend/presentation/views/platform_alert.py
@@ -1,25 +1,47 @@
-from functools import cached_property
-from typing import cast
+from dataclasses import replace
+from functools import cache, cached_property
+from typing import Any, Literal, cast
-from drf_spectacular.utils import extend_schema
+from drf_spectacular.utils import OpenApiResponse, PolymorphicProxySerializer, extend_schema, extend_schema_field
from rest_framework import serializers, viewsets
-from rest_framework.exceptions import NotFound
+from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
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.exceptions import Conflict
from posthog.models import Team, User
-from posthog.permissions import PostHogFeatureFlagPermission, get_authenticator_scopes
+from posthog.permissions import (
+ PostHogFeatureFlagPermission,
+ get_authenticator_scoped_team_ids,
+ 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.contracts import (
+ DEFAULT_MAX_INSTANCES,
+ MAX_EVALUATION_PERIODS,
+ MAX_INSTANCES_CEILING,
+ MAX_STORED_INTEGER,
+ Grouping,
+ GroupingMode,
+ InvalidPlatformAlertEdit,
+ OnOverflow,
+ PlatformAlertNotEditable,
+ SourceConfigSpec,
+ SourceKind,
+)
from products.alerts_platform.backend.facade.enums import (
+ PlatformAlertCheckStatus,
PlatformAlertConfigurationRecurrenceUnit,
PlatformAlertConfigurationSourceKind,
+ PlatformAlertOwner,
PlatformAlertState,
)
+from products.alerts_platform.backend.facade.source_configs import editable_source_configs
from products.alerts_platform.backend.presentation.views.schedule_restriction import ScheduleRestrictionField
@@ -49,6 +71,42 @@ class PlatformAlertSerializer(serializers.Serializer):
)
+class GroupingSerializer(serializers.Serializer):
+ mode = serializers.ChoiceField(
+ choices=GroupingMode.choices,
+ help_text="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.",
+ )
+ keys = serializers.ListField(
+ child=serializers.CharField(),
+ default=list,
+ help_text="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 = serializers.IntegerField(
+ min_value=1,
+ max_value=MAX_INSTANCES_CEILING,
+ default=DEFAULT_MAX_INSTANCES,
+ help_text="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 = serializers.ChoiceField(
+ choices=OnOverflow.choices,
+ default=OnOverflow.DEGRADE_VISIBLE.value,
+ help_text="What happens to groups past max_instances. degrade_visible names how many were left out.",
+ )
+
+ def validate(self, attrs: dict[str, Any]) -> Grouping:
+ # A partial update makes every nested field optional, but a grouping is replaced whole.
+ if "mode" not in attrs:
+ raise ValidationError({"mode": "This field is required."})
+ try:
+ return Grouping.from_stored(attrs)
+ except ValueError as error:
+ raise ValidationError(str(error)) from error
+
+
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.")
@@ -109,6 +167,25 @@ class PlatformAlertConfigurationSerializer(serializers.Serializer):
help_text="ID of the legacy source configuration this row was backfilled from. "
"Null for alerts created on the platform.",
)
+ grouping = GroupingSerializer(read_only=True, help_text="How the alert splits its results into instances.")
+ snooze_until = serializers.DateTimeField(
+ read_only=True,
+ allow_null=True,
+ help_text="Time until which every instance's notifications are muted. Null when not muted. "
+ "An instance's own snooze_until mutes one group, and the later of the two holds.",
+ )
+ check_status = serializers.ChoiceField(
+ choices=PlatformAlertCheckStatus.choices,
+ read_only=True,
+ help_text="Whether the alert's checks succeed. Holds for every instance, because a failed check "
+ "names no group.",
+ )
+ owner = serializers.ChoiceField(
+ choices=PlatformAlertOwner.choices,
+ read_only=True,
+ help_text="Which stack evaluates and delivers the alert. Only an alert the platform owns can be "
+ "edited here. The source product's own API edits the rest.",
+ )
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(
@@ -130,6 +207,81 @@ SOURCE_KIND_RESOURCE: dict[str, APIScopeObject] = {
UNSERVED_SOURCE_KINDS: frozenset[str] = frozenset({PlatformAlertConfigurationSourceKind.INSIGHT.value})
+class PlatformAlertConfigurationEditSerializer(serializers.Serializer):
+ """The settings an edit can change. Each source kind subclasses it with a typed `source_config`."""
+
+ # A plain string: each subclass serves one kind, and the request schema's discriminator lists them.
+ source_kind = serializers.CharField(
+ help_text="Product whose data the alert evaluates. It cannot change, so it must match the stored value.",
+ )
+ name = serializers.CharField(max_length=255, help_text="Human-readable name of the alert.")
+ enabled = serializers.BooleanField(help_text="Whether the alert is evaluated on schedule.")
+ source_config = serializers.JSONField(help_text="Source-specific settings. The shape depends on source_kind.")
+ grouping = GroupingSerializer(help_text="How the alert splits its results into instances.")
+ schedule_restriction = ScheduleRestrictionField(
+ allow_null=True,
+ help_text="Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. "
+ "Null means no quiet hours.",
+ )
+ evaluation_periods = serializers.IntegerField(
+ min_value=1,
+ max_value=MAX_EVALUATION_PERIODS,
+ help_text="Number of recent checks considered when deciding to fire.",
+ )
+ datapoints_to_alarm = serializers.IntegerField(
+ min_value=1,
+ max_value=MAX_EVALUATION_PERIODS,
+ help_text="Number of breaching checks within evaluation_periods required to fire. "
+ "Cannot exceed evaluation_periods.",
+ )
+ cooldown_minutes = serializers.IntegerField(
+ min_value=0,
+ max_value=MAX_STORED_INTEGER,
+ help_text="Minimum minutes between notifications for the same alert.",
+ )
+
+
+def _typed_edit_serializer(
+ source: SourceKind, spec: SourceConfigSpec
+) -> type[PlatformAlertConfigurationEditSerializer]:
+ """The edit serializer for one source kind, whose `source_config` is described by the source's model."""
+ prefix = source.value.capitalize()
+ source_config_field = extend_schema_field(spec.model)( # type: ignore[arg-type]
+ type(f"{prefix}PlatformAlertSourceConfigField", (serializers.JSONField,), {})
+ )
+ return type(
+ f"{prefix}PlatformAlertConfigurationEditSerializer",
+ (PlatformAlertConfigurationEditSerializer,),
+ {
+ "source_config": source_config_field(
+ help_text=f"Settings for a {source.value} alert. The bound the alert is evaluated against "
+ "is under condition."
+ )
+ },
+ )
+
+
+@cache
+def edit_serializers() -> dict[str, type[PlatformAlertConfigurationEditSerializer]]:
+ """One edit serializer per kind a source registered. Built on first use, because each source's
+ schema loads only then."""
+ return {source.value: _typed_edit_serializer(source, spec) for source, spec in editable_source_configs().items()}
+
+
+PLATFORM_ALERT_CONFIGURATION_EDIT = PolymorphicProxySerializer(
+ component_name="PlatformAlertConfigurationEdit",
+ serializers=lambda: dict[str, serializers.Serializer | type[serializers.Serializer]](edit_serializers()),
+ resource_type_field_name="source_kind",
+)
+
+EDIT_RESPONSES = {
+ 200: PlatformAlertConfigurationSerializer,
+ 403: OpenApiResponse(description="The caller cannot write alerts of this source kind."),
+ 404: OpenApiResponse(description="No alert with this id that the caller can read."),
+ 409: OpenApiResponse(description="The source product owns this alert, so only its own API edits it."),
+}
+
+
class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
scope_object = "alert"
posthog_feature_flag = "platform-alerts"
@@ -144,6 +296,11 @@ class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.Generic
return self.team
parent_team = self.team.parent_team
assert parent_team is not None
+ # The scope check before the view ran saw only the URL's team, so a key confined to some
+ # projects must reach the parent as well.
+ scoped_teams = get_authenticator_scoped_team_ids(getattr(self.request, "successful_authenticator", None))
+ if scoped_teams is not None and parent_team.id not in scoped_teams:
+ raise PermissionDenied(f"API key does not have access to the requested project: ID {parent_team.id}.")
return parent_team
@cached_property
@@ -161,21 +318,75 @@ class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.Generic
def _canonical_team_id(self) -> int:
return self.canonical_team.id
- def _readable_source_kinds(self) -> list[str]:
+ def _source_kinds_with(
+ self, access_level: Literal["viewer", "editor"], scope_action: Literal["read", "write"]
+ ) -> 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] = []
+ permitted: list[str] = []
for source_kind, resource in SOURCE_KIND_RESOURCE.items():
- if not self.user_access_control.check_access_level_for_resource(resource, "viewer"):
+ if not self.user_access_control.check_access_level_for_resource(resource, access_level):
continue
if (
token_scopes is not None
and "*" not in token_scopes
- and scopes_not_covered(token_scopes, [f"{resource}:read"])
+ and scopes_not_covered(token_scopes, [f"{resource}:{scope_action}"])
):
continue
- readable.append(source_kind)
- return readable
+ permitted.append(source_kind)
+ return permitted
+
+ def _readable_source_kinds(self) -> list[str]:
+ return self._source_kinds_with("viewer", "read")
+
+ def _edit(self, request: Request, pk: str, *, partial: bool) -> Response:
+ configuration_id = serializers.UUIDField().run_validation(pk)
+ team_id = self._canonical_team_id()
+ current = platform_api.get_configuration(
+ team_id=team_id, source_kinds=self._readable_source_kinds(), configuration_id=configuration_id
+ )
+ if current is None:
+ raise NotFound()
+ writable = self._source_kinds_with("editor", "write")
+ if current.source_kind not in writable:
+ raise PermissionDenied(f"You cannot edit {current.source_kind} alerts.")
+ # Checked again under the row lock. Here it answers before the body is validated, so a caller
+ # never fixes a body for an alert it can never write.
+ if current.owner != PlatformAlertOwner.PLATFORM:
+ raise Conflict(f"This alert is managed by the {current.source_kind} product. Edit it there.")
+ edit_serializer = edit_serializers().get(current.source_kind)
+ if edit_serializer is None:
+ raise Conflict(f"{current.source_kind} alerts cannot be edited through this API.")
+
+ serializer = edit_serializer(data=request.data, partial=partial)
+ serializer.is_valid(raise_exception=True)
+ fields = dict(serializer.validated_data)
+ if fields.pop("source_kind", current.source_kind) != current.source_kind:
+ raise ValidationError({"source_kind": "The source kind of an alert cannot change."})
+
+ try:
+ updated = platform_api.update_configuration(
+ team_id=team_id,
+ source_kinds=writable,
+ configuration_id=configuration_id,
+ # A partial update names only the fields it changes. The rest keep what is stored.
+ change=lambda stored: replace(stored, **fields),
+ )
+ except PlatformAlertNotEditable as error:
+ raise Conflict(str(error)) from error
+ except InvalidPlatformAlertEdit as error:
+ raise ValidationError({error.field_name: str(error)}) from error
+ if updated is None:
+ raise NotFound()
+ return Response(PlatformAlertConfigurationSerializer(updated).data)
+
+ @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)
+
+ @extend_schema(request=PLATFORM_ALERT_CONFIGURATION_EDIT, responses=EDIT_RESPONSES)
+ def partial_update(self, request: Request, pk: str, **kwargs) -> Response:
+ return self._edit(request, pk, partial=True)
def list(self, request: Request, **kwargs) -> Response:
paginator = cast(PrecountedLimitOffsetPagination, self.paginator)
diff --git a/products/alerts_platform/backend/tests/api/test_platform_alert.py b/products/alerts_platform/backend/tests/api/test_platform_alert.py
index 25fb8c680518..769dea185600 100644
--- a/products/alerts_platform/backend/tests/api/test_platform_alert.py
+++ b/products/alerts_platform/backend/tests/api/test_platform_alert.py
@@ -12,11 +12,15 @@ from rest_framework import status
from posthog.constants import AvailableFeature
from posthog.models import OrganizationMembership, User
+from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.scoping import team_scope
from posthog.models.team import Team
+from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.access_control.backend.models.access_control import AccessControl
-from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration
+from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration, PlatformAlertThread
+
+CONDITION = {"threshold_count": 10, "threshold_operator": "above", "window_minutes": 5}
class TestPlatformAlertAPI(APIBaseTest):
@@ -26,15 +30,17 @@ class TestPlatformAlertAPI(APIBaseTest):
name: str,
legacy_configuration_id: UUID | None = None,
source_kind: str = PlatformAlertConfiguration.SourceKind.LOGS,
+ owner: str = PlatformAlertConfiguration.Owner.SOURCE,
) -> PlatformAlertConfiguration:
with team_scope(team.id):
return PlatformAlertConfiguration.objects.create(
team=team,
name=name,
source_kind=source_kind,
- source_config={"service": "api"},
+ source_config={"filters": {"serviceNames": ["api"]}, "condition": CONDITION},
check_interval_minutes=10,
legacy_configuration_id=legacy_configuration_id,
+ owner=owner,
)
def _set_flag(self, enabled: bool) -> None:
@@ -96,6 +102,37 @@ class TestPlatformAlertAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK, response.json()
assert response.json()["id"] == str(configuration.id)
+ @parameterized.expand(
+ [
+ ("key_for_the_environment_only", False, status.HTTP_403_FORBIDDEN),
+ ("key_for_the_environment_and_its_project", True, status.HTTP_200_OK),
+ ]
+ )
+ def test_a_project_scoped_key_reaches_a_child_environments_alerts_only_with_the_parent(
+ self, _name: str, scoped_to_parent: bool, expected: int
+ ) -> None:
+ self._set_flag(True)
+ configuration = self._create_configuration(self.team, "API errors", owner="platform")
+ child_environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="env")
+ key_value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="Environment key",
+ user=self.user,
+ secure_value=hash_key_value(key_value),
+ scopes=["alert:read", "alert:write", "logs:read", "logs:write"],
+ scoped_teams=[child_environment.id, self.team.id] if scoped_to_parent else [child_environment.id],
+ )
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {key_value}")
+ url = f"/api/projects/{child_environment.id}/platform_alerts/{configuration.id}/"
+
+ edit = self.client.patch(url, {"name": "Renamed"}, format="json")
+ read = self.client.get(url)
+
+ assert (edit.status_code, read.status_code) == (expected, expected), (edit.json(), read.json())
+ configuration.refresh_from_db()
+ assert configuration.name == ("Renamed" if expected == status.HTTP_200_OK else "API errors")
+
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")
@@ -214,3 +251,141 @@ class TestPlatformAlertAPI(APIBaseTest):
with CaptureQueriesContext(connection) as captured:
self.client.get(url)
return len(captured)
+
+ def _edit_url(self, configuration: PlatformAlertConfiguration) -> str:
+ return f"/api/projects/{self.team.id}/platform_alerts/{configuration.id}/"
+
+ def test_changing_the_grouping_keys_drops_the_old_instances_and_their_threads(self) -> None:
+ self._set_flag(True)
+ configuration = self._create_configuration(self.team, "API errors", owner="platform")
+ with team_scope(self.team.id):
+ PlatformAlert.objects.create(team=self.team, configuration=configuration, state=PlatformAlert.State.FIRING)
+ PlatformAlertThread.objects.create(
+ team=self.team,
+ configuration=configuration,
+ provider="slack",
+ channel_target="C1",
+ episode_started_at=datetime(2026, 10, 1, tzinfo=UTC),
+ )
+
+ response = self.client.patch(
+ self._edit_url(configuration),
+ {"grouping": {"mode": "by_result_labels", "keys": ["service_name"]}},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ body = response.json()
+ assert body["grouping"] == {
+ "mode": "by_result_labels",
+ "keys": ["service_name"],
+ "max_instances": 100,
+ "on_overflow": "degrade_visible",
+ }
+ assert (body["name"], body["alerts"]) == ("API errors", [])
+ with team_scope(self.team.id):
+ assert not PlatformAlertThread.objects.filter(configuration=configuration).exists()
+
+ def test_an_alert_its_source_owns_is_not_edited_here(self) -> None:
+ self._set_flag(True)
+ configuration = self._create_configuration(self.team, "API errors")
+
+ response = self.client.patch(
+ self._edit_url(configuration), {"name": "Renamed", "evaluation_periods": 0}, format="json"
+ )
+
+ assert response.status_code == status.HTTP_409_CONFLICT, response.json()
+ configuration.refresh_from_db()
+ assert configuration.name == "API errors"
+
+ @parameterized.expand(
+ [
+ (
+ "grouped_below",
+ {
+ "grouping": {"mode": "by_result_labels", "keys": ["service_name"]},
+ "source_config": {
+ "filters": {"serviceNames": ["api"]},
+ "condition": {**CONDITION, "threshold_operator": "below"},
+ },
+ },
+ "grouping",
+ ),
+ (
+ "unknown_window",
+ {
+ "source_config": {
+ "filters": {"serviceNames": ["api"]},
+ "condition": {**CONDITION, "window_minutes": 7},
+ }
+ },
+ "source_config",
+ ),
+ (
+ "more_datapoints_than_periods",
+ {"evaluation_periods": 2, "datapoints_to_alarm": 3},
+ "datapoints_to_alarm",
+ ),
+ ("source_kind_changed", {"source_kind": "insight"}, "source_kind"),
+ ("cooldown_past_the_column", {"cooldown_minutes": 2_147_483_648}, "cooldown_minutes"),
+ ("grouping_without_mode", {"grouping": {"keys": ["service_name"]}}, "grouping__mode"),
+ ("enabled_without_filters", {"source_config": {"filters": {}, "condition": CONDITION}}, "source_config"),
+ ("grouped_by_an_attribute", {"grouping": {"mode": "by_result_labels", "keys": ["http.route"]}}, "grouping"),
+ ]
+ )
+ def test_an_invalid_edit_names_the_field_and_changes_nothing(self, _name: str, body: dict, field: str) -> None:
+ self._set_flag(True)
+ configuration = self._create_configuration(self.team, "API errors", owner="platform")
+
+ response = self.client.patch(self._edit_url(configuration), body, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == field
+ configuration.refresh_from_db()
+ assert (configuration.source_config["condition"], configuration.grouping["mode"]) == (CONDITION, "single")
+
+ @parameterized.expand(
+ [
+ ("alert_scope_only", ["alert:write"], status.HTTP_404_NOT_FOUND),
+ ("logs_read_only", ["alert:write", "logs:read"], status.HTTP_403_FORBIDDEN),
+ ("alert_and_logs_write", ["alert:write", "logs:write"], status.HTTP_200_OK),
+ ]
+ )
+ def test_an_edit_needs_write_access_to_the_source_product(
+ self, _name: str, key_scopes: list[str], expected: int
+ ) -> None:
+ self._set_flag(True)
+ configuration = self._create_configuration(self.team, "API errors", owner="platform")
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {self.create_personal_api_key_with_scopes(key_scopes)}")
+
+ response = self.client.patch(self._edit_url(configuration), {"name": "Renamed"}, format="json")
+
+ assert response.status_code == expected, response.json()
+
+ def test_settings_an_edit_leaves_alone_are_not_revalidated(self) -> None:
+ self._set_flag(True)
+ configuration = self._create_configuration(self.team, "API errors", owner="platform")
+ PlatformAlertConfiguration.objects.for_team(self.team.id).filter(id=configuration.id).update(
+ source_config={"filters": {"serviceNames": ["api"], "retiredKey": True}, "condition": CONDITION}
+ )
+
+ response = self.client.patch(self._edit_url(configuration), {"name": "Renamed"}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["name"] == "Renamed"
+
+ def test_turning_a_broken_alert_back_on_schedules_a_clean_check(self) -> None:
+ self._set_flag(True)
+ configuration = self._create_configuration(self.team, "API errors", owner="platform")
+ PlatformAlertConfiguration.objects.for_team(self.team.id).filter(id=configuration.id).update(
+ enabled=False, check_status="broken", consecutive_failures=5, next_check_at=None
+ )
+
+ response = self.client.patch(self._edit_url(configuration), {"enabled": True}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ with team_scope(self.team.id):
+ configuration.refresh_from_db()
+ assert (configuration.check_status, configuration.consecutive_failures) == ("ok", 0)
+ assert configuration.next_check_at is not None
diff --git a/products/alerts_platform/frontend/PlatformAlerts.stories.tsx b/products/alerts_platform/frontend/PlatformAlerts.stories.tsx
index 7c1d26281497..679716337a56 100644
--- a/products/alerts_platform/frontend/PlatformAlerts.stories.tsx
+++ b/products/alerts_platform/frontend/PlatformAlerts.stories.tsx
@@ -27,6 +27,10 @@ const CONFIGURATION: PlatformAlertConfigurationApi = {
next_check_at: '2026-10-05T12:01:00Z',
consecutive_failures: 0,
legacy_configuration_id: '0192a5b0-0000-7000-8000-0000000000aa',
+ grouping: { mode: 'single', keys: [], max_instances: 100, on_overflow: 'degrade_visible' },
+ snooze_until: null,
+ check_status: 'ok',
+ owner: 'source',
created_at: '2026-09-20T09:00:00Z',
updated_at: '2026-10-01T09:00:00Z',
alerts: [
diff --git a/products/alerts_platform/frontend/generated/api.schemas.ts b/products/alerts_platform/frontend/generated/api.schemas.ts
index fdf9bdbd5f26..c1583306e079 100644
--- a/products/alerts_platform/frontend/generated/api.schemas.ts
+++ b/products/alerts_platform/frontend/generated/api.schemas.ts
@@ -44,6 +44,71 @@ export interface AlertScheduleRestrictionApi {
blocked_windows: AlertScheduleRestrictionWindowApi[]
}
+/**
+ * * `single` - Single
+ * * `by_result_labels` - By result labels
+ */
+export type GroupingModeEnumApi = (typeof GroupingModeEnumApi)[keyof typeof GroupingModeEnumApi]
+
+export const GroupingModeEnumApi = {
+ Single: 'single',
+ ByResultLabels: 'by_result_labels',
+} as const
+
+/**
+ * * `degrade_visible` - Degrade visible
+ */
+export type OnOverflowEnumApi = (typeof OnOverflowEnumApi)[keyof typeof OnOverflowEnumApi]
+
+export const OnOverflowEnumApi = {
+ DegradeVisible: 'degrade_visible',
+} as const
+
+export interface GroupingApi {
+ /** 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.
+ *
+ * * `single` - Single
+ * * `by_result_labels` - By result labels */
+ mode: GroupingModeEnumApi
+ /** 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. */
+ keys?: string[]
+ /**
+ * Most instances the alert keeps at once. Groups past it are not tracked, and the last message says how many were left out.
+ * @minimum 1
+ * @maximum 100
+ */
+ max_instances?: number
+ /** What happens to groups past max_instances. degrade_visible names how many were left out.
+ *
+ * * `degrade_visible` - Degrade visible */
+ on_overflow?: OnOverflowEnumApi
+}
+
+/**
+ * * `ok` - OK
+ * * `errored` - Errored
+ * * `broken` - Broken
+ */
+export type PlatformAlertCheckStatusEnumApi =
+ (typeof PlatformAlertCheckStatusEnumApi)[keyof typeof PlatformAlertCheckStatusEnumApi]
+
+export const PlatformAlertCheckStatusEnumApi = {
+ Ok: 'ok',
+ Errored: 'errored',
+ Broken: 'broken',
+} as const
+
+/**
+ * * `source` - Source
+ * * `platform` - Platform
+ */
+export type PlatformAlertOwnerEnumApi = (typeof PlatformAlertOwnerEnumApi)[keyof typeof PlatformAlertOwnerEnumApi]
+
+export const PlatformAlertOwnerEnumApi = {
+ Source: 'source',
+ Platform: 'platform',
+} as const
+
/**
* * `not_firing` - Not firing
* * `firing` - Firing
@@ -144,6 +209,24 @@ export interface PlatformAlertConfigurationApi {
* @nullable
*/
readonly legacy_configuration_id: string | null
+ /** How the alert splits its results into instances. */
+ readonly grouping: GroupingApi
+ /**
+ * Time until which every instance's notifications are muted. Null when not muted. An instance's own snooze_until mutes one group, and the later of the two holds.
+ * @nullable
+ */
+ readonly snooze_until: string | null
+ /** Whether the alert's checks succeed. Holds for every instance, because a failed check names no group.
+ *
+ * * `ok` - OK
+ * * `errored` - Errored
+ * * `broken` - Broken */
+ readonly check_status: PlatformAlertCheckStatusEnumApi
+ /** Which stack evaluates and delivers the alert. Only an alert the platform owns can be edited here. The source product's own API edits the rest.
+ *
+ * * `source` - Source
+ * * `platform` - Platform */
+ readonly owner: PlatformAlertOwnerEnumApi
/** When the configuration was created. */
readonly created_at: string
/** When the configuration was last changed. */
@@ -161,6 +244,530 @@ export interface PaginatedPlatformAlertConfigurationListApi {
results: PlatformAlertConfigurationApi[]
}
+/**
+ * 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
+
+export type FilterLogicalOperatorApi = (typeof FilterLogicalOperatorApi)[keyof typeof FilterLogicalOperatorApi]
+
+export const FilterLogicalOperatorApi = {
+ And: 'AND',
+ Or: 'OR',
+} as const
+
+export type PropertyOperatorApi = (typeof PropertyOperatorApi)[keyof typeof PropertyOperatorApi]
+
+export const PropertyOperatorApi = {
+ Exact: 'exact',
+ IsNot: 'is_not',
+ Icontains: 'icontains',
+ NotIcontains: 'not_icontains',
+ StartsWith: 'starts_with',
+ NotStartsWith: 'not_starts_with',
+ EndsWith: 'ends_with',
+ NotEndsWith: 'not_ends_with',
+ Regex: 'regex',
+ NotRegex: 'not_regex',
+ Gt: 'gt',
+ Gte: 'gte',
+ Lt: 'lt',
+ Lte: 'lte',
+ IsSet: 'is_set',
+ IsNotSet: 'is_not_set',
+ IsDateExact: 'is_date_exact',
+ IsDateBefore: 'is_date_before',
+ IsDateAfter: 'is_date_after',
+ Between: 'between',
+ NotBetween: 'not_between',
+ Min: 'min',
+ Max: 'max',
+ In: 'in',
+ NotIn: 'not_in',
+ IsCleanedPathExact: 'is_cleaned_path_exact',
+ IsCleanedPathNotExact: 'is_cleaned_path_not_exact',
+ FlagEvaluatesTo: 'flag_evaluates_to',
+ SemverEq: 'semver_eq',
+ SemverNeq: 'semver_neq',
+ SemverGt: 'semver_gt',
+ SemverGte: 'semver_gte',
+ SemverLt: 'semver_lt',
+ SemverLte: 'semver_lte',
+ SemverTilde: 'semver_tilde',
+ SemverCaret: 'semver_caret',
+ SemverWildcard: 'semver_wildcard',
+ IcontainsMulti: 'icontains_multi',
+ NotIcontainsMulti: 'not_icontains_multi',
+} as const
+
+export interface EventPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator?: PropertyOperatorApi | null
+ /** Event properties */
+ type?: 'event'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface PersonPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ /** Person properties */
+ type?: 'person'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface PersonMetadataPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ /** Top-level columns on the persons table (e.g. created_at), not properties JSON */
+ type?: 'person_metadata'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export type Key10Api = (typeof Key10Api)[keyof typeof Key10Api]
+
+export const Key10Api = {
+ TagName: 'tag_name',
+ Text: 'text',
+ Href: 'href',
+ Selector: 'selector',
+} as const
+
+export interface ElementPropertyFilterApi {
+ key: Key10Api
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'element'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface EventMetadataPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'event_metadata'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface SessionPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'session'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface CohortPropertyFilterApi {
+ cohort_name?: string | null
+ key?: 'id'
+ label?: string | null
+ operator?: PropertyOperatorApi | null
+ type?: 'cohort'
+ value: number
+}
+
+export type DurationTypeApi = (typeof DurationTypeApi)[keyof typeof DurationTypeApi]
+
+export const DurationTypeApi = {
+ Duration: 'duration',
+ ActiveSeconds: 'active_seconds',
+ InactiveSeconds: 'inactive_seconds',
+} as const
+
+export interface RecordingPropertyFilterApi {
+ key: DurationTypeApi | string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'recording'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface LogEntryPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'log_entry'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export type GroupPropertyFilterApiGroupKeyNames = { [key: string]: string } | null
+
+export interface GroupPropertyFilterApi {
+ group_key_names?: GroupPropertyFilterApiGroupKeyNames
+ group_type_index?: number | null
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'group'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface FeaturePropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ /** Event property with "$feature/" prepended */
+ type?: 'feature'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface FlagPropertyFilterApi {
+ /** The key should be the flag ID */
+ key: string
+ label?: string | null
+ /** Only flag_evaluates_to operator is allowed for flag dependencies */
+ operator?: 'flag_evaluates_to'
+ /** Feature flag dependency */
+ type?: 'flag'
+ /** The value can be true, false, or a variant name */
+ value: boolean | string
+}
+
+export interface HogQLPropertyFilterApi {
+ key: string
+ label?: string | null
+ type?: 'hogql'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export const EmptyPropertyFilterApiValue = {
+ type: 'empty',
+} as const
+export type EmptyPropertyFilterApi = typeof EmptyPropertyFilterApiValue
+
+export interface DataWarehousePropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'data_warehouse'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface DataWarehousePersonPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'data_warehouse_person_property'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface ErrorTrackingIssueFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'error_tracking_issue'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export type LogPropertyFilterTypeApi = (typeof LogPropertyFilterTypeApi)[keyof typeof LogPropertyFilterTypeApi]
+
+export const LogPropertyFilterTypeApi = {
+ Log: 'log',
+ LogAttribute: 'log_attribute',
+ LogResourceAttribute: 'log_resource_attribute',
+} as const
+
+export interface LogPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type: LogPropertyFilterTypeApi
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface MetricPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'metric_attribute'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export type SpanPropertyFilterTypeApi = (typeof SpanPropertyFilterTypeApi)[keyof typeof SpanPropertyFilterTypeApi]
+
+export const SpanPropertyFilterTypeApi = {
+ Span: 'span',
+ SpanAttribute: 'span_attribute',
+ SpanResourceAttribute: 'span_resource_attribute',
+} as const
+
+export interface SpanPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type: SpanPropertyFilterTypeApi
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface RevenueAnalyticsPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'revenue_analytics'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface AccountCustomPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ /** Customer analytics account custom property — the key is the property definition id */
+ type?: 'account_custom_property'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export interface WorkflowVariablePropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'workflow_variable'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
+
+export type BehavioralEventSourceApi = (typeof BehavioralEventSourceApi)[keyof typeof BehavioralEventSourceApi]
+
+export const BehavioralEventSourceApi = {
+ Events: 'events',
+ Actions: 'actions',
+} as const
+
+export type TimeUnitTypeApi = (typeof TimeUnitTypeApi)[keyof typeof TimeUnitTypeApi]
+
+export const TimeUnitTypeApi = {
+ Day: 'day',
+ Week: 'week',
+ Month: 'month',
+ Year: 'year',
+} as const
+
+export type InlineBehavioralTypeApi = (typeof InlineBehavioralTypeApi)[keyof typeof InlineBehavioralTypeApi]
+
+export const InlineBehavioralTypeApi = {
+ PerformedEvent: 'performed_event',
+ PerformedEventMultiple: 'performed_event_multiple',
+} as const
+
+export interface BehavioralPropertyFilterApi {
+ /** Extra property filters the matching events must satisfy. Deliberately excludes nested behavioral/cohort filters and groups */
+ event_filters?:
+ | (
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | ElementPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | HogQLPropertyFilterApi
+ )[]
+ | null
+ event_type: BehavioralEventSourceApi
+ /** Absolute or relative (e.g. -30d) lower date bound — alternative to time_value/time_interval */
+ explicit_datetime?: string | null
+ explicit_datetime_to?: string | null
+ /** Event name, or action id when event_type is 'actions' */
+ key: string
+ label?: string | null
+ /** Match persons who did NOT satisfy the criterion. Not the same as a low count — zero-occurrence persons never match count operators */
+ negation?: boolean | null
+ /** Count comparison for performed_event_multiple, defaults to exact */
+ operator?: PropertyOperatorApi | null
+ /** Count threshold for performed_event_multiple */
+ operator_value?: number | null
+ time_interval?: TimeUnitTypeApi | null
+ /** Relative time window size, paired with time_interval */
+ time_value?: number | null
+ /** Person performed (or didn't perform) an event in a time window. ClickHouse-only — not evaluable by flags or CDP */
+ type?: 'behavioral'
+ value: InlineBehavioralTypeApi
+}
+
+export interface PropertyGroupFilterValueApi {
+ type: FilterLogicalOperatorApi
+ values: (
+ | PropertyGroupFilterValueApi
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ | BehavioralPropertyFilterApi
+ )[]
+}
+
+export interface PropertyGroupFilterApi {
+ type: FilterLogicalOperatorApi
+ values: PropertyGroupFilterValueApi[]
+}
+
+export type LogSeverityLevelApi = (typeof LogSeverityLevelApi)[keyof typeof LogSeverityLevelApi]
+
+export const LogSeverityLevelApi = {
+ Trace: 'trace',
+ Debug: 'debug',
+ Info: 'info',
+ Warn: 'warn',
+ Error: 'error',
+ Fatal: 'fatal',
+} as const
+
+export interface LogsAlertFiltersApi {
+ filterGroup?: PropertyGroupFilterApi | null
+ serviceNames?: string[] | null
+ severityLevels?: LogSeverityLevelApi[] | null
+}
+
+export type ThresholdOperatorApi = (typeof ThresholdOperatorApi)[keyof typeof ThresholdOperatorApi]
+
+export const ThresholdOperatorApi = {
+ Above: 'above',
+ Below: 'below',
+} as const
+
+export type WindowMinutesEnumApi = (typeof WindowMinutesEnumApi)[keyof typeof WindowMinutesEnumApi]
+
+export const WindowMinutesEnumApi = {
+ Number5: 5,
+ Number10: 10,
+ Number15: 15,
+ Number30: 30,
+ Number60: 60,
+} as const
+
+export interface LogsPlatformAlertConditionApi {
+ /**
+ * Number of matching log entries in the window that breaches the threshold. Use 0 with the above operator to fire on any matching log.
+ * @minimum 0
+ */
+ threshold_count: number
+ /** Whether the alert fires when the count is above or below the threshold. */
+ threshold_operator: ThresholdOperatorApi
+ /** Time window in minutes over which logs are counted. */
+ window_minutes: WindowMinutesEnumApi
+}
+
+export interface LogsPlatformAlertSourceConfigApi {
+ /** The logs the alert counts: severityLevels, serviceNames, or a filterGroup of property filters. An enabled alert needs at least one. */
+ filters: LogsAlertFiltersApi
+ /** The bound the count is checked against. */
+ condition: LogsPlatformAlertConditionApi
+}
+
+/**
+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.
+ */
+export interface LogsPlatformAlertConfigurationEditApi {
+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */
+ source_kind: LogsPlatformAlertConfigurationEditApiSourceKind
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 255
+ */
+ name: string
+ /** Whether the alert is evaluated on schedule. */
+ 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. */
+ grouping: GroupingApi
+ /** Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. */
+ schedule_restriction: AlertScheduleRestrictionApi | null
+ /**
+ * Number of recent checks considered when deciding to fire.
+ * @minimum 1
+ * @maximum 10
+ */
+ evaluation_periods: number
+ /**
+ * Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.
+ * @minimum 1
+ * @maximum 10
+ */
+ datapoints_to_alarm: number
+ /**
+ * Minimum minutes between notifications for the same alert.
+ * @minimum 0
+ * @maximum 2147483647
+ */
+ cooldown_minutes: number
+}
+
+export type PlatformAlertConfigurationEditApi = LogsPlatformAlertConfigurationEditApi
+
+/**
+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.
+ */
+export type PatchedLogsPlatformAlertConfigurationEditApiSourceKind =
+ (typeof PatchedLogsPlatformAlertConfigurationEditApiSourceKind)[keyof typeof PatchedLogsPlatformAlertConfigurationEditApiSourceKind]
+
+export const PatchedLogsPlatformAlertConfigurationEditApiSourceKind = {
+ Logs: 'logs',
+} as const
+
+/**
+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.
+ */
+export interface PatchedLogsPlatformAlertConfigurationEditApi {
+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */
+ source_kind: PatchedLogsPlatformAlertConfigurationEditApiSourceKind
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 255
+ */
+ name?: string
+ /** Whether the alert is evaluated on schedule. */
+ 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. */
+ grouping?: GroupingApi
+ /** Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. */
+ schedule_restriction?: AlertScheduleRestrictionApi | null
+ /**
+ * Number of recent checks considered when deciding to fire.
+ * @minimum 1
+ * @maximum 10
+ */
+ evaluation_periods?: number
+ /**
+ * Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.
+ * @minimum 1
+ * @maximum 10
+ */
+ datapoints_to_alarm?: number
+ /**
+ * Minimum minutes between notifications for the same alert.
+ * @minimum 0
+ * @maximum 2147483647
+ */
+ cooldown_minutes?: number
+}
+
+export type PatchedPlatformAlertConfigurationEditApi = PatchedLogsPlatformAlertConfigurationEditApi
+
export type PlatformAlertsListParams = {
/**
* Number of results to return per page.
diff --git a/products/alerts_platform/frontend/generated/api.ts b/products/alerts_platform/frontend/generated/api.ts
index f2b375b8a0b0..56486b9f09a5 100644
--- a/products/alerts_platform/frontend/generated/api.ts
+++ b/products/alerts_platform/frontend/generated/api.ts
@@ -10,7 +10,9 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
*/
import type {
PaginatedPlatformAlertConfigurationListApi,
+ PatchedPlatformAlertConfigurationEditApi,
PlatformAlertConfigurationApi,
+ PlatformAlertConfigurationEditApi,
PlatformAlertsListParams,
} from './api.schemas'
@@ -55,3 +57,39 @@ export const platformAlertsRetrieve = async (
method: 'GET',
})
}
+
+export const getPlatformAlertsUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/platform_alerts/${id}/`
+}
+
+export const platformAlertsUpdate = async (
+ projectId: string,
+ id: string,
+ platformAlertConfigurationEditApi?: PlatformAlertConfigurationEditApi,
+ options?: RequestInit
+): Promise<PlatformAlertConfigurationApi> => {
+ return apiMutator<PlatformAlertConfigurationApi>(getPlatformAlertsUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(platformAlertConfigurationEditApi),
+ })
+}
+
+export const getPlatformAlertsPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/platform_alerts/${id}/`
+}
+
+export const platformAlertsPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedPlatformAlertConfigurationEditApi?: PatchedPlatformAlertConfigurationEditApi,
+ options?: RequestInit
+): Promise<PlatformAlertConfigurationApi> => {
+ return apiMutator<PlatformAlertConfigurationApi>(getPlatformAlertsPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedPlatformAlertConfigurationEditApi),
+ })
+}
diff --git a/products/alerts_platform/frontend/generated/api.zod.ts b/products/alerts_platform/frontend/generated/api.zod.ts
index e8a15d4e1b52..15da98c0a740 100644
--- a/products/alerts_platform/frontend/generated/api.zod.ts
+++ b/products/alerts_platform/frontend/generated/api.zod.ts
@@ -7,3 +7,310 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+import * as zod from 'zod'
+
+export const platformAlertsUpdateBodyOneNameMax = 255
+
+export const platformAlertsUpdateBodyOneSourceConfigOneConditionThresholdCountMin = 0
+
+export const platformAlertsUpdateBodyOneGroupingOneMaxInstancesDefault = 100
+export const platformAlertsUpdateBodyOneGroupingOneMaxInstancesMax = 100
+
+export const platformAlertsUpdateBodyOneGroupingOneOnOverflowDefault = `degrade_visible`
+export const platformAlertsUpdateBodyOneEvaluationPeriodsMax = 10
+
+export const platformAlertsUpdateBodyOneDatapointsToAlarmMax = 10
+
+export const platformAlertsUpdateBodyOneCooldownMinutesMin = 0
+export const platformAlertsUpdateBodyOneCooldownMinutesMax = 2147483647
+
+export const PlatformAlertsUpdateBody = /* @__PURE__ */ zod
+ .object({
+ source_kind: zod
+ .enum(['logs'])
+ .describe('Product whose data the alert evaluates. It cannot change, so it must match the stored value.'),
+ name: zod.string().max(platformAlertsUpdateBodyOneNameMax).describe('Human-readable name of the alert.'),
+ enabled: zod.boolean().describe('Whether the alert is evaluated on schedule.'),
+ 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(platformAlertsUpdateBodyOneSourceConfigOneConditionThresholdCountMin)
+ .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(platformAlertsUpdateBodyOneGroupingOneMaxInstancesMax)
+ .default(platformAlertsUpdateBodyOneGroupingOneMaxInstancesDefault)
+ .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(platformAlertsUpdateBodyOneGroupingOneOnOverflowDefault)
+ .describe(
+ 'What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'
+ ),
+ })
+ .describe('How the alert splits its results into instances.'),
+ 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 notify. Null means no quiet hours.'
+ ),
+ evaluation_periods: zod
+ .number()
+ .min(1)
+ .max(platformAlertsUpdateBodyOneEvaluationPeriodsMax)
+ .describe('Number of recent checks considered when deciding to fire.'),
+ datapoints_to_alarm: zod
+ .number()
+ .min(1)
+ .max(platformAlertsUpdateBodyOneDatapointsToAlarmMax)
+ .describe(
+ 'Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.'
+ ),
+ cooldown_minutes: zod
+ .number()
+ .min(platformAlertsUpdateBodyOneCooldownMinutesMin)
+ .max(platformAlertsUpdateBodyOneCooldownMinutesMax)
+ .describe('Minimum minutes between notifications for the same alert.'),
+ })
+ .describe('The settings an edit can change. Each source kind subclasses it with a typed `source_config`.')
+
+export const platformAlertsPartialUpdateBodyOneNameMax = 255
+
+export const platformAlertsPartialUpdateBodyOneSourceConfigOneConditionThresholdCountMin = 0
+
+export const platformAlertsPartialUpdateBodyOneGroupingOneMaxInstancesDefault = 100
+export const platformAlertsPartialUpdateBodyOneGroupingOneMaxInstancesMax = 100
+
+export const platformAlertsPartialUpdateBodyOneGroupingOneOnOverflowDefault = `degrade_visible`
+export const platformAlertsPartialUpdateBodyOneEvaluationPeriodsMax = 10
+
+export const platformAlertsPartialUpdateBodyOneDatapointsToAlarmMax = 10
+
+export const platformAlertsPartialUpdateBodyOneCooldownMinutesMin = 0
+export const platformAlertsPartialUpdateBodyOneCooldownMinutesMax = 2147483647
+
+export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod
+ .object({
+ source_kind: zod
+ .enum(['logs'])
+ .describe('Product whose data the alert evaluates. It cannot change, so it must match the stored value.'),
+ name: zod
+ .string()
+ .max(platformAlertsPartialUpdateBodyOneNameMax)
+ .optional()
+ .describe('Human-readable name of the alert.'),
+ enabled: zod.boolean().optional().describe('Whether the alert is evaluated on schedule.'),
+ 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(platformAlertsPartialUpdateBodyOneSourceConfigOneConditionThresholdCountMin)
+ .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.'),
+ })
+ .optional()
+ .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(platformAlertsPartialUpdateBodyOneGroupingOneMaxInstancesMax)
+ .default(platformAlertsPartialUpdateBodyOneGroupingOneMaxInstancesDefault)
+ .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(platformAlertsPartialUpdateBodyOneGroupingOneOnOverflowDefault)
+ .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.'),
+ 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.'
+ ),
+ evaluation_periods: zod
+ .number()
+ .min(1)
+ .max(platformAlertsPartialUpdateBodyOneEvaluationPeriodsMax)
+ .optional()
+ .describe('Number of recent checks considered when deciding to fire.'),
+ datapoints_to_alarm: zod
+ .number()
+ .min(1)
+ .max(platformAlertsPartialUpdateBodyOneDatapointsToAlarmMax)
+ .optional()
+ .describe(
+ 'Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.'
+ ),
+ cooldown_minutes: zod
+ .number()
+ .min(platformAlertsPartialUpdateBodyOneCooldownMinutesMin)
+ .max(platformAlertsPartialUpdateBodyOneCooldownMinutesMax)
+ .optional()
+ .describe('Minimum minutes between notifications for the same alert.'),
+ })
+ .describe('The settings an edit can change. Each source kind subclasses it with a typed `source_config`.')
diff --git a/products/alerts_platform/frontend/platformAlertFormat.test.ts b/products/alerts_platform/frontend/platformAlertFormat.test.ts
index 15f863c67f63..380c5f4a354c 100644
--- a/products/alerts_platform/frontend/platformAlertFormat.test.ts
+++ b/products/alerts_platform/frontend/platformAlertFormat.test.ts
@@ -28,6 +28,10 @@ function makeConfiguration(overrides: Partial<PlatformAlertConfigurationApi> = {
next_check_at: null,
consecutive_failures: 0,
legacy_configuration_id: null,
+ grouping: { mode: 'single', keys: [], max_instances: 100, on_overflow: 'degrade_visible' },
+ snooze_until: null,
+ check_status: 'ok',
+ owner: 'source',
created_at: '2026-10-01T00:00:00Z',
updated_at: '2026-10-01T00:00:00Z',
alerts: [],
diff --git a/products/logs/backend/alert_group_columns.py b/products/logs/backend/alert_group_columns.py
index 7864263b0434..50c42d45c1ef 100644
--- a/products/logs/backend/alert_group_columns.py
+++ b/products/logs/backend/alert_group_columns.py
@@ -3,6 +3,7 @@
Kept apart from the query layer, because the platform wording imports it from `ready()`.
"""
+from collections.abc import Sequence
from typing import Final
from posthog.dataclasses import frozen
@@ -24,3 +25,14 @@ GROUP_COLUMNS: Final[dict[str, GroupColumn]] = {
"service_name": GroupColumn(label="Service", filter_key="serviceNames", filter_group_key="service_name"),
"severity_text": GroupColumn(label="Severity", filter_key="severityLevels", filter_group_key="severity_level"),
}
+
+
+def grouping_problem(keys: Sequence[str], threshold_operator: object) -> str | None:
+ """Why a logs alert grouped by `keys` cannot be evaluated, or None when it can."""
+ if unknown := set(keys) - GROUP_COLUMNS.keys():
+ return f"A logs alert can only group by {', '.join(sorted(GROUP_COLUMNS))}, not {', '.join(sorted(unknown))}."
+ # A group with no matching log returns no row, so a service gone silent, the case a `below`
+ # alert exists for, is never seen unless it was already open.
+ if threshold_operator != "above":
+ return "A grouped logs alert can only alert above a threshold."
+ return None
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.py
index 8f5cfcfcfb4a..fb52ceee00c4 100644
--- a/products/logs/backend/alert_source_cycle.py
+++ b/products/logs/backend/alert_source_cycle.py
@@ -95,7 +95,7 @@ from products.logs.backend.alert_check_query import (
from products.logs.backend.alert_destinations import EVENT_KIND_CONFIG, EventKind
from products.logs.backend.alert_error_classifier import classify as classify_alert_error
from products.logs.backend.alert_evaluation_key import WINDOW_MARKER
-from products.logs.backend.alert_group_columns import GROUP_COLUMNS
+from products.logs.backend.alert_group_columns import grouping_problem
from products.logs.backend.alert_lookback import rolling_check_lookback_minutes
from products.logs.backend.models import LogsAlertConfiguration
from products.logs.backend.platform_alert_backfill import platform_upsert_of
@@ -756,13 +756,7 @@ def _labels_of(grouping_key: str) -> dict[str, str] | None:
def _broken_grouping(check: PlatformAlertCheckInput) -> str | None:
if check.grouping.mode == GroupingMode.SINGLE:
return None
- if set(check.grouping.keys) - GROUP_COLUMNS.keys():
- return f"A logs alert can only group by {', '.join(sorted(GROUP_COLUMNS))}"
- # A group with no matching log returns no row, so a service gone silent, the case a `below`
- # alert exists for, is never seen unless it was already open.
- if check.condition.get("threshold_operator") != LogsAlertConfiguration.ThresholdOperator.ABOVE:
- return "A grouped logs alert can only alert above a threshold"
- return None
+ return grouping_problem(check.grouping.keys, check.condition.get("threshold_operator"))
def _evaluate_grouped(
diff --git a/products/logs/backend/apps.py b/products/logs/backend/apps.py
index 30eff1249d29..6246504e20ca 100644
--- a/products/logs/backend/apps.py
+++ b/products/logs/backend/apps.py
@@ -13,21 +13,25 @@ class LogsConfig(AppConfig):
# transitively imports the whole query-runner layer, which would drag posthog.schema and
# HogQL into django.setup() for every process type.
# - The alerts platform cannot import this product, so native alert messages get the logs
- # wording, grandfathered webhooks the legacy logs body, and alerts on the HogFunction path
- # their `$logs_alert_*` events, through the functions registered below.
+ # wording, grandfathered webhooks the legacy logs body, alerts on the HogFunction path
+ # their `$logs_alert_*` events, and the platform API the logs `source_config` schema,
+ # through the functions registered below.
from products.alerts_platform.backend.facade.contracts import SourceKind # noqa: PLC0415
from products.alerts_platform.backend.facade.delivery import ( # noqa: PLC0415
register_legacy_event_emitter,
register_legacy_webhook_body,
register_source_describer,
)
+ from products.alerts_platform.backend.facade.source_configs import register_source_config # noqa: PLC0415
from products.logs.backend import activity_logging # noqa: F401, PLC0415
from products.logs.backend.platform_alert_legacy_events import emit_logs_legacy_events # noqa: PLC0415
from products.logs.backend.platform_alert_wording import ( # noqa: PLC0415
describe_logs_transition,
legacy_logs_webhook_body,
)
+ from products.logs.backend.platform_source_config import load_logs_source_config # noqa: PLC0415
register_source_describer(SourceKind.LOGS, describe_logs_transition)
register_legacy_webhook_body(SourceKind.LOGS, legacy_logs_webhook_body)
register_legacy_event_emitter(SourceKind.LOGS, emit_logs_legacy_events)
+ register_source_config(SourceKind.LOGS, load_logs_source_config)
diff --git a/products/logs/backend/facade/api.py b/products/logs/backend/facade/api.py
index 896d7990a45a..87b71221b4bd 100644
--- a/products/logs/backend/facade/api.py
+++ b/products/logs/backend/facade/api.py
@@ -13,14 +13,17 @@ from products.logs.backend.natural_language_query import (
translate_natural_language_query,
)
from products.logs.backend.platform_alert_backfill import logs_state_of_platform
+from products.logs.backend.platform_source_config import ALLOWED_WINDOW_MINUTES, has_any_filter
from products.logs.backend.tasks.tasks import follow_logs_alert_task
__all__ = [
+ "ALLOWED_WINDOW_MINUTES",
"NaturalLanguageQueryFailed",
"NaturalLanguageQueryUnavailable",
"close_incident_before_delete",
"close_incident_on_commit",
"follow_logs_alert",
+ "has_any_filter",
"is_valid_date",
"logs_state_of_platform",
"next_allowed_check_at",
diff --git a/products/logs/backend/models.py b/products/logs/backend/models.py
index da48dac6dfec..c7592fbbf29f 100644
--- a/products/logs/backend/models.py
+++ b/products/logs/backend/models.py
@@ -13,6 +13,7 @@ from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
from posthog.utils import generate_short_id
+from products.alerts_platform.backend.facade.contracts import MAX_EVALUATION_PERIODS as PLATFORM_MAX_EVALUATION_PERIODS
from products.alerts_platform.backend.facade.enums import PlatformAlertOwner
if TYPE_CHECKING:
@@ -167,7 +168,7 @@ class TeamLogsConfig(models.Model):
# cap on retained OK event rows — the N-of-M evaluator never reads more than this many
# non-errored rows per alert, so older OK rows are pruned. Mirrored in the serializer's
# max_value so the two can't drift.
-MAX_EVALUATION_PERIODS = 10
+MAX_EVALUATION_PERIODS = PLATFORM_MAX_EVALUATION_PERIODS
class LogsView(CreatedMetaFields, UpdatedMetaFields, UUIDModel):
diff --git a/products/logs/backend/platform_source_config.py b/products/logs/backend/platform_source_config.py
index d7daa9115cc5..b1ac05bbd552 100644
--- a/products/logs/backend/platform_source_config.py
+++ b/products/logs/backend/platform_source_config.py
@@ -3,11 +3,16 @@
Imported from `ready()` through the message wording, so it stays light: no models, no query layer.
"""
-from typing import Any, Final
+from typing import Any, Final, Literal, get_args
-from products.alerts_platform.backend.facade.contracts import SOURCE_CONDITION_KEY
+from products.alerts_platform.backend.facade.contracts import SOURCE_CONDITION_KEY, SourceConfigSpec
FILTERS_KEY: Final = "filters"
+# The filter fields that narrow which logs an alert counts. An alert with none of them counts all logs.
+LOGS_FILTER_KEYS: Final = ("severityLevels", "serviceNames", "filterGroup")
+
+WindowMinutes = Literal[5, 10, 15, 30, 60]
+ALLOWED_WINDOW_MINUTES: Final[frozenset[int]] = frozenset(get_args(WindowMinutes))
def logs_source_config(filters: object, condition: dict[str, Any]) -> dict[str, Any]:
@@ -26,3 +31,15 @@ def filters_of(source_config: dict[str, Any]) -> dict[str, Any]:
if FILTERS_KEY in source_config:
return source_config[FILTERS_KEY]
return {key: value for key, value in source_config.items() if key != SOURCE_CONDITION_KEY}
+
+
+def load_logs_source_config() -> SourceConfigSpec:
+ from products.logs.backend.platform_source_config_schema import ( # noqa: PLC0415 - keeps posthog.schema off the startup path
+ LOGS_SOURCE_CONFIG,
+ )
+
+ return LOGS_SOURCE_CONFIG
+
+
+def has_any_filter(filters: dict[str, Any]) -> bool:
+ return any(filters.get(key) for key in LOGS_FILTER_KEYS)
diff --git a/products/logs/backend/platform_source_config_schema.py b/products/logs/backend/platform_source_config_schema.py
new file mode 100644
index 000000000000..208bf3be2e41
--- /dev/null
+++ b/products/logs/backend/platform_source_config_schema.py
@@ -0,0 +1,62 @@
+"""The schema a logs alert's `source_config` takes in the alerts platform's API, and the rules for
+a whole edit.
+
+Loaded on first use through `load_logs_source_config`, never from `ready()`, because it is built
+on `posthog.schema`.
+"""
+
+from pydantic import BaseModel, ConfigDict, Field
+
+from posthog.schema import LogsAlertFilters
+
+from products.alerts_platform.backend.facade.contracts import (
+ GroupingMode,
+ InvalidPlatformAlertEdit,
+ PlatformAlertConfigurationEdit,
+ SourceConfigSpec,
+)
+from products.logs.backend.alert_group_columns import grouping_problem
+from products.logs.backend.models import LogsAlertConfiguration
+from products.logs.backend.platform_source_config import WindowMinutes, has_any_filter
+
+
+class LogsPlatformAlertCondition(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ threshold_count: int = Field(
+ ...,
+ ge=0,
+ description="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: LogsAlertConfiguration.ThresholdOperator = Field(
+ ..., description="Whether the alert fires when the count is above or below the threshold."
+ )
+ window_minutes: WindowMinutes = Field(..., description="Time window in minutes over which logs are counted.")
+
+
+class LogsPlatformAlertSourceConfig(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ filters: LogsAlertFilters = Field(
+ ...,
+ description="The logs the alert counts: severityLevels, serviceNames, or a filterGroup of property "
+ "filters. An enabled alert needs at least one.",
+ )
+ condition: LogsPlatformAlertCondition = Field(..., description="The bound the count is checked against.")
+
+
+def validate_logs_edit(edit: PlatformAlertConfigurationEdit) -> None:
+ filters = edit.source_config["filters"]
+ # The logs API's rule: a draft may hold no filters, but any filters it holds must narrow something.
+ if (edit.enabled or filters) and not has_any_filter(filters):
+ raise InvalidPlatformAlertEdit(
+ "source_config", "At least one filter is required (severityLevels, serviceNames, or filterGroup)."
+ )
+ if edit.grouping.mode == GroupingMode.SINGLE:
+ return
+ if problem := grouping_problem(edit.grouping.keys, edit.source_config["condition"]["threshold_operator"]):
+ raise InvalidPlatformAlertEdit("grouping", problem)
+
+
+LOGS_SOURCE_CONFIG = SourceConfigSpec(model=LogsPlatformAlertSourceConfig, validate=validate_logs_edit)
diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.py
index e4bc5b3b2939..989ca22cb7c1 100644
--- a/products/logs/backend/presentation/views/alerts_api.py
+++ b/products/logs/backend/presentation/views/alerts_api.py
@@ -85,15 +85,16 @@ from products.logs.backend.alert_state_machine import (
evaluate_alert_check,
)
from products.logs.backend.facade.api import (
+ ALLOWED_WINDOW_MINUTES,
close_incident_before_delete,
close_incident_on_commit,
follow_logs_alert,
+ has_any_filter,
logs_state_of_platform,
next_allowed_check_at,
)
from products.logs.backend.models import MAX_EVALUATION_PERIODS, LogsAlertConfiguration, LogsAlertEvent
-ALLOWED_WINDOW_MINUTES = {5, 10, 15, 30, 60}
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
@@ -873,10 +874,7 @@ def _validate_filters(filters: dict) -> None:
"""
if not isinstance(filters, dict):
raise ValidationError({"filters": "Must be a JSON object."})
- has_severity = bool(filters.get("severityLevels"))
- has_services = bool(filters.get("serviceNames"))
- has_filter_group = bool(filters.get("filterGroup"))
- if not (has_severity or has_services or has_filter_group):
+ if not has_any_filter(filters):
raise ValidationError(
{"filters": "At least one filter is required (severityLevels, serviceNames, or filterGroup)."}
)
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 7852b27e7b70..e230e6deb50b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -54965,6 +54965,48 @@ export namespace Schemas {
math_property?: string | null;
}
+ /**
+ * * `single` - Single
+ * * `by_result_labels` - By result labels
+ */
+ export type GroupingModeEnum = typeof GroupingModeEnum[keyof typeof GroupingModeEnum];
+
+
+ export const GroupingModeEnum = {
+ Single: 'single',
+ ByResultLabels: 'by_result_labels',
+ } as const;
+
+ /**
+ * * `degrade_visible` - Degrade visible
+ */
+ export type OnOverflowEnum = typeof OnOverflowEnum[keyof typeof OnOverflowEnum];
+
+
+ export const OnOverflowEnum = {
+ DegradeVisible: 'degrade_visible',
+ } as const;
+
+ export interface Grouping {
+ /** 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.
+ *
+ * * `single` - Single
+ * * `by_result_labels` - By result labels */
+ mode: GroupingModeEnum;
+ /** 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. */
+ keys?: string[];
+ /**
+ * Most instances the alert keeps at once. Groups past it are not tracked, and the last message says how many were left out.
+ * @minimum 1
+ * @maximum 100
+ */
+ max_instances?: number;
+ /** What happens to groups past max_instances. degrade_visible names how many were left out.
+ *
+ * * `degrade_visible` - Degrade visible */
+ on_overflow?: OnOverflowEnum;
+ }
+
export interface HandsFreeToken {
/** Single-use ElevenLabs Scribe realtime token, valid for 15 minutes. */
token: string;
@@ -65267,6 +65309,93 @@ export namespace Schemas {
BodyMining: 'body_mining',
} as const;
+ export type ThresholdOperator = typeof ThresholdOperator[keyof typeof ThresholdOperator];
+
+
+ export const ThresholdOperator = {
+ Above: 'above',
+ Below: 'below',
+ } as const;
+
+ export type WindowMinutesEnum = typeof WindowMinutesEnum[keyof typeof WindowMinutesEnum];
+
+
+ export const WindowMinutesEnum = {
+ Number5: 5,
+ Number10: 10,
+ Number15: 15,
+ Number30: 30,
+ Number60: 60,
+ } as const;
+
+ export interface LogsPlatformAlertCondition {
+ /**
+ * Number of matching log entries in the window that breaches the threshold. Use 0 with the above operator to fire on any matching log.
+ * @minimum 0
+ */
+ threshold_count: number;
+ /** Whether the alert fires when the count is above or below the threshold. */
+ threshold_operator: ThresholdOperator;
+ /** Time window in minutes over which logs are counted. */
+ window_minutes: WindowMinutesEnum;
+ }
+
+ /**
+ * 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;
+
+ export interface LogsPlatformAlertSourceConfig {
+ /** The logs the alert counts: severityLevels, serviceNames, or a filterGroup of property filters. An enabled alert needs at least one. */
+ filters: LogsAlertFilters;
+ /** The bound the count is checked against. */
+ condition: LogsPlatformAlertCondition;
+ }
+
+ /**
+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.
+ */
+ export interface LogsPlatformAlertConfigurationEdit {
+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */
+ source_kind: LogsPlatformAlertConfigurationEditSourceKind;
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 255
+ */
+ name: string;
+ /** Whether the alert is evaluated on schedule. */
+ 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. */
+ grouping: Grouping;
+ /** Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. */
+ schedule_restriction: AlertScheduleRestriction | null;
+ /**
+ * Number of recent checks considered when deciding to fire.
+ * @minimum 1
+ * @maximum 10
+ */
+ evaluation_periods: number;
+ /**
+ * Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.
+ * @minimum 1
+ * @maximum 10
+ */
+ datapoints_to_alarm: number;
+ /**
+ * Minimum minutes between notifications for the same alert.
+ * @minimum 0
+ * @maximum 2147483647
+ */
+ cooldown_minutes: number;
+ }
+
export interface LogsRetentionRule {
/** Unique identifier for this retention rule. */
readonly id: string;
@@ -73189,6 +73318,32 @@ export namespace Schemas {
Insight: 'insight',
} as const;
+ /**
+ * * `ok` - OK
+ * * `errored` - Errored
+ * * `broken` - Broken
+ */
+ export type PlatformAlertCheckStatusEnum = typeof PlatformAlertCheckStatusEnum[keyof typeof PlatformAlertCheckStatusEnum];
+
+
+ export const PlatformAlertCheckStatusEnum = {
+ Ok: 'ok',
+ Errored: 'errored',
+ Broken: 'broken',
+ } as const;
+
+ /**
+ * * `source` - Source
+ * * `platform` - Platform
+ */
+ export type PlatformAlertOwnerEnum = typeof PlatformAlertOwnerEnum[keyof typeof PlatformAlertOwnerEnum];
+
+
+ export const PlatformAlertOwnerEnum = {
+ Source: 'source',
+ Platform: 'platform',
+ } as const;
+
export interface PlatformAlert {
/** Unique identifier of this alert instance. */
readonly id: string;
@@ -73271,6 +73426,24 @@ export namespace Schemas {
* @nullable
*/
readonly legacy_configuration_id: string | null;
+ /** How the alert splits its results into instances. */
+ readonly grouping: Grouping;
+ /**
+ * Time until which every instance's notifications are muted. Null when not muted. An instance's own snooze_until mutes one group, and the later of the two holds.
+ * @nullable
+ */
+ readonly snooze_until: string | null;
+ /** Whether the alert's checks succeed. Holds for every instance, because a failed check names no group.
+ *
+ * * `ok` - OK
+ * * `errored` - Errored
+ * * `broken` - Broken */
+ readonly check_status: PlatformAlertCheckStatusEnum;
+ /** Which stack evaluates and delivers the alert. Only an alert the platform owns can be edited here. The source product's own API edits the rest.
+ *
+ * * `source` - Source
+ * * `platform` - Platform */
+ readonly owner: PlatformAlertOwnerEnum;
/** When the configuration was created. */
readonly created_at: string;
/** When the configuration was last changed. */
@@ -83764,6 +83937,55 @@ export namespace Schemas {
readonly updated_at?: string | null;
}
+ /**
+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.
+ */
+ export type PatchedLogsPlatformAlertConfigurationEditSourceKind = typeof PatchedLogsPlatformAlertConfigurationEditSourceKind[keyof typeof PatchedLogsPlatformAlertConfigurationEditSourceKind];
+
+
+ export const PatchedLogsPlatformAlertConfigurationEditSourceKind = {
+ Logs: 'logs',
+ } as const;
+
+ /**
+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.
+ */
+ export interface PatchedLogsPlatformAlertConfigurationEdit {
+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */
+ source_kind: PatchedLogsPlatformAlertConfigurationEditSourceKind;
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 255
+ */
+ name?: string;
+ /** Whether the alert is evaluated on schedule. */
+ 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. */
+ grouping?: Grouping;
+ /** Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. */
+ schedule_restriction?: AlertScheduleRestriction | null;
+ /**
+ * Number of recent checks considered when deciding to fire.
+ * @minimum 1
+ * @maximum 10
+ */
+ evaluation_periods?: number;
+ /**
+ * Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.
+ * @minimum 1
+ * @maximum 10
+ */
+ datapoints_to_alarm?: number;
+ /**
+ * Minimum minutes between notifications for the same alert.
+ * @minimum 0
+ * @maximum 2147483647
+ */
+ cooldown_minutes?: number;
+ }
+
export interface PatchedLogsRetentionRule {
/** Unique identifier for this retention rule. */
readonly id?: string;
@@ -84456,6 +84678,8 @@ export namespace Schemas {
homepage?: PinnedSceneTab | null;
}
+ export type PatchedPlatformAlertConfigurationEdit = PatchedLogsPlatformAlertConfigurationEdit;
+
/**
* Request body for PATCH /api/users/@me/product_intro_seen.
*/
@@ -89360,6 +89584,8 @@ export namespace Schemas {
created_at: string | null;
}
+ export type PlatformAlertConfigurationEdit = LogsPlatformAlertConfigurationEdit;
+
/**
* * `running` - Running
* * `completed` - Completed