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): write both rows of an insight alert the platform owns (#120721)

Jimmy Zhueaaf6d23648b
diff --git a/products/alerts/backend/apps.py b/products/alerts/backend/apps.py
index e87a14555465..f5cbe49e9347 100644
--- a/products/alerts/backend/apps.py
+++ b/products/alerts/backend/apps.py
@@ -14,18 +14,23 @@ class AlertsConfig(AppConfig):
# scope — see activity_logging's docstring.
from products.alerts.backend import activity_logging # noqa: F401, PLC0415
- # The platform cannot import this product, so it reaches this product's destinations here.
+ # The platform cannot import this product, so it reaches this product's destinations, and the
+ # schema an edit to an insight alert's copy is checked against, here.
from products.alerts.backend.facade.destinations import ( # noqa: PLC0415
choose_delivery_path,
emit_alert_transition_events,
list_delivery_destination_groups,
)
+ from products.alerts.backend.platform_source_config import load_insight_source_config # noqa: PLC0415
+ from products.alerts_platform.backend.facade.contracts import SourceKind # noqa: PLC0415
from products.alerts_platform.backend.facade.delivery import ( # noqa: PLC0415
register_delivery_path_chooser,
register_destination_resolver,
register_transition_event_producer,
)
+ from products.alerts_platform.backend.facade.source_configs import register_source_config # noqa: PLC0415
register_destination_resolver(list_delivery_destination_groups)
register_delivery_path_chooser(choose_delivery_path)
+ register_source_config(SourceKind.INSIGHT, load_insight_source_config)
register_transition_event_producer(emit_alert_transition_events)
diff --git a/products/alerts/backend/facade/api.py b/products/alerts/backend/facade/api.py
index 16e622f385c4..1a6cdf7fa595 100644
--- a/products/alerts/backend/facade/api.py
+++ b/products/alerts/backend/facade/api.py
@@ -18,6 +18,7 @@ from django.utils import timezone
import structlog
+from posthog.exceptions_capture import capture_exception
from posthog.models.activity_logging.model_activity import ActingUserContext
from posthog.models.team import Team
from posthog.models.user import User
@@ -46,10 +47,11 @@ from products.alerts.backend.llm_detector_limits import (
llm_detector_access_error,
)
from products.alerts.backend.models.alert import METRICS_INSIGHT_QUERY_FILTER, AlertCheck, AlertConfiguration
+from products.alerts_platform.backend.facade.contracts import InvalidPlatformAlertEdit
logger = structlog.get_logger(__name__)
-SlackSnoozeOutcome = Literal["snoozed", "no_access", "disabled", "not_found", "invalid_until"]
+SlackSnoozeOutcome = Literal["snoozed", "no_access", "disabled", "not_found", "invalid_until", "not_snoozable"]
# Mirrors the in-app SnoozeButton's DateFilter max — Slack's datetimepicker has no bounds of
# its own, so the cap has to live here.
@@ -171,6 +173,19 @@ def snooze_alert_from_slack(
state_fields = apply_snooze(locked_alert)
locked_alert.snoozed_until = snoozed_until
locked_alert.save(update_fields=[*state_fields, "snoozed_until"])
+ if locked_alert.platform_owned:
+ # The platform's copy mutes delivery, so it takes the snooze under the same lock.
+ from products.alerts.backend.platform_ownership import ( # noqa: PLC0415 - platform_ownership reaches this module back
+ on_updated,
+ )
+
+ try:
+ on_updated(locked_alert, snooze_changed=True)
+ except (contracts.PlatformCannotOwn, InvalidPlatformAlertEdit) as error:
+ # Neither row takes the snooze, so the alert does not mute on one stack only.
+ capture_exception(error, {"alert_id": str(alert_id)})
+ transaction.set_rollback(True)
+ return "not_snoozable"
AlertCheck.objects.create(
alert_configuration=locked_alert,
calculated_value=None,
diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.py
index 8facb47d32c8..8e0ad562694c 100644
--- a/products/alerts/backend/facade/contracts.py
+++ b/products/alerts/backend/facade/contracts.py
@@ -181,3 +181,7 @@ class MovedAlertCheckPage:
# How many checks the requested window holds, past this page too.
total: int
checks: tuple[MovedAlertCheck, ...]
+
+
+class PlatformCannotOwn(ValueError):
+ """An edit that would leave an alert the platform owns in a shape the platform cannot evaluate."""
diff --git a/products/alerts/backend/facade/platform.py b/products/alerts/backend/facade/platform.py
index 7eda1452b028..fcb580ebc293 100644
--- a/products/alerts/backend/facade/platform.py
+++ b/products/alerts/backend/facade/platform.py
@@ -9,6 +9,12 @@ import uuid
from products.alerts.backend.models.alert import AlertConfiguration
from products.alerts.backend.platform_alert_backfill import follow_insight_alert as follow_alert
from products.alerts.backend.platform_alert_reads import moved_alert_check_page, moved_alert_statuses
+from products.alerts.backend.platform_ownership import (
+ close_moved_alert_firings,
+ delete_moved_alert_copy,
+ hand_over_new_alert,
+ write_moved_alert_edit,
+)
def follow_insight_alert(*, team_id: int, alert_id: uuid.UUID) -> None:
@@ -19,4 +25,12 @@ def follow_insight_alert(*, team_id: int, alert_id: uuid.UUID) -> None:
follow_alert(alert)
-__all__ = ["follow_insight_alert", "moved_alert_check_page", "moved_alert_statuses"]
+__all__ = [
+ "close_moved_alert_firings",
+ "delete_moved_alert_copy",
+ "follow_insight_alert",
+ "hand_over_new_alert",
+ "moved_alert_check_page",
+ "moved_alert_statuses",
+ "write_moved_alert_edit",
+]
diff --git a/products/alerts/backend/max_tools.py b/products/alerts/backend/max_tools.py
index 4892104fadcf..401007deacd1 100644
--- a/products/alerts/backend/max_tools.py
+++ b/products/alerts/backend/max_tools.py
@@ -28,8 +28,10 @@ from posthog.scopes import APIScopeObject
from products.access_control.backend.facade.user_access_control import AccessControlLevel
from products.alerts.backend.evaluation.validation import THRESHOLD_BOUNDS_REQUIRED_MESSAGE, validate_alert_config
from products.alerts.backend.facade.api import LLMAlertWrite, admit_llm_alert_write, is_llm_detector_config
+from products.alerts.backend.facade.contracts import PlatformCannotOwn
from products.alerts.backend.insight_alert_state_machine import apply_disable, apply_enable, apply_threshold_change
from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Threshold
+from products.alerts_platform.backend.facade.contracts import InvalidPlatformAlertEdit
from products.product_analytics.backend.facade.api import lock_insight_for_evaluation
from products.product_analytics.backend.facade.models import Insight, resolve_insight_by_id_or_short_id
@@ -470,7 +472,17 @@ class UpsertAlertTool(MaxTool):
alert.next_check_at = timezone.now()
update_fields.append("next_check_at")
alert.save(update_fields=update_fields)
- if enabled_changed and action.enabled:
+ if alert.platform_owned:
+ # Deferred for the same cycle as `_follow_on_commit`.
+ from products.alerts.backend.platform_ownership import on_updated # noqa: PLC0415
+
+ try:
+ on_updated(alert, snooze_changed=False)
+ except (PlatformCannotOwn, InvalidPlatformAlertEdit) as error:
+ # Rolls back the insight row, so neither row takes an edit the platform rejects.
+ transaction.set_rollback(True)
+ return _SaveRefusal(message=str(error), error_code="validation_failed")
+ elif enabled_changed and action.enabled:
_follow_on_commit(alert)
return None
@@ -663,7 +675,12 @@ class UpsertAlertTool(MaxTool):
alert_configuration=alert,
created_by=user,
)
- if alert.enabled:
+ # Deferred for the same cycle as `_follow_on_commit`.
+ from products.alerts.backend.platform_ownership import on_created # noqa: PLC0415
+
+ # A draft is handed over too, so turning it on later needs no second cutover run.
+ handed_over = on_created(alert, timezone.now())
+ if alert.enabled and not handed_over:
_follow_on_commit(alert)
return alert
diff --git a/products/alerts/backend/platform_cutover.py b/products/alerts/backend/platform_cutover.py
index 68b87bd0925e..acf8b936b38a 100644
--- a/products/alerts/backend/platform_cutover.py
+++ b/products/alerts/backend/platform_cutover.py
@@ -67,6 +67,8 @@ class CutoverSkip(StrEnum):
"""Why an alert stays with the insight stack for now."""
ALREADY_MOVED = "already_moved"
+ # Platform rows live on the project's root team, so an alert in a child environment stays.
+ ENVIRONMENT = "environment"
# The platform does not evaluate it in parallel, such as a detector or a real-time alert.
NOT_ON_PLATFORM = "not_on_platform"
# The investigation agent reads and writes the insight stack's checks, which the platform does not keep.
@@ -133,53 +135,85 @@ def delivers_as_it_does_today(alert: AlertConfiguration) -> bool:
def _cut_over_alert(team_id: int, alert_id: UUID, now: datetime | None) -> CutoverSkip | None:
with transaction.atomic():
- # `of` keeps the lock off the nullable threshold join, which PostgreSQL refuses to lock.
+ # Only the alert's own row is locked: PostgreSQL refuses to lock the nullable threshold join,
+ # and locking the team row would make a hot parent a mutex.
alert = (
AlertConfiguration.objects.select_for_update(no_key=True, of=("self",))
- .select_related("threshold")
+ .select_related("team", "threshold")
.get(team_id=team_id, id=alert_id)
)
# Read after the lock, so a check that became due while earlier alerts moved is seen as due.
at = now or timezone.now()
if alert.platform_owned:
return CutoverSkip.ALREADY_MOVED
- upsert = platform_upsert_of(alert)
- if upsert is None or not _is_threshold_alert(alert):
- return CutoverSkip.NOT_ON_PLATFORM
- if alert.investigation_agent_enabled:
- return CutoverSkip.INVESTIGATION
+ if in_an_environment(alert):
+ return CutoverSkip.ENVIRONMENT
+ if not can_move(alert):
+ return CutoverSkip.INVESTIGATION if alert.investigation_agent_enabled else CutoverSkip.NOT_ON_PLATFORM
if not delivers_as_it_does_today(alert):
return CutoverSkip.NO_HOG_FUNCTION_PATH
if alert.state == AlertState.FIRING:
return CutoverSkip.FIRING
if _insight_check_owed(team_id, alert.id, at):
return CutoverSkip.CHECK_DUE
-
- savepoint = transaction.savepoint()
- upsert_configuration(upsert)
- taken = take_ownership(
- PlatformOwnershipHandover(
- legacy_configuration_id=alert.id,
- team_id=alert.team_id,
- state=PLATFORM_HANDOVER_STATE[alert.state],
- last_notified_at=alert.last_notified_at,
- consecutive_failures=0,
- next_check_at=alert.next_check_at or at,
- at=at,
- )
- )
- if not taken:
- # The copy stays as live delivery left it. A copy disabled here would drop out of
- # discovery and never resolve the firing it is inside.
- transaction.savepoint_rollback(savepoint)
+ if not hand_over(alert, at):
return CutoverSkip.PLATFORM_FIRING
- transaction.savepoint_commit(savepoint)
- AlertConfiguration.objects.filter(team_id=alert.team_id, id=alert.id).update(
- owner=PlatformAlertOwner.PLATFORM, owner_changed_at=at
- )
return None
+def in_an_environment(alert: AlertConfiguration) -> bool:
+ """Whether the alert belongs to a child environment, whose copy would live on its project."""
+ return alert.team.parent_team_id is not None
+
+
+def can_move(alert: AlertConfiguration) -> bool:
+ """Whether the platform can own the alert: a threshold alert it evaluates, which no investigation agent reads."""
+ return (
+ platform_upsert_of(alert) is not None and _is_threshold_alert(alert) and not alert.investigation_agent_enabled
+ )
+
+
+def has_begun_cutover(team_id: int) -> bool:
+ """Whether the platform owns any of the team's insight alerts, which makes it the owner of new ones."""
+ return AlertConfiguration.objects.filter(team_id=team_id, owner=PlatformAlertOwner.PLATFORM).exists()
+
+
+def hand_over(alert: AlertConfiguration, at: datetime) -> bool:
+ """Copies an insight alert locked by the caller onto the platform and makes the platform its owner,
+ on both rows. False, changing nothing, when the platform copy is inside a firing of its own.
+
+ The caller checks `can_move` first.
+ """
+ upsert = platform_upsert_of(alert)
+ assert upsert is not None
+ savepoint = transaction.savepoint()
+ upsert_configuration(upsert)
+ taken = take_ownership(
+ PlatformOwnershipHandover(
+ legacy_configuration_id=alert.id,
+ team_id=alert.team_id,
+ state=PLATFORM_HANDOVER_STATE[alert.state],
+ last_notified_at=alert.last_notified_at,
+ consecutive_failures=0,
+ next_check_at=alert.next_check_at or at,
+ at=at,
+ )
+ )
+ if not taken:
+ # The copy stays as live delivery left it. A copy disabled here would drop out of
+ # discovery and never resolve the firing it is inside.
+ transaction.savepoint_rollback(savepoint)
+ return False
+ transaction.savepoint_commit(savepoint)
+ # `update()` rather than `save()`: a handover is not a user's edit, and `save()` would log one.
+ AlertConfiguration.objects.filter(team_id=alert.team_id, id=alert.id).update(
+ owner=PlatformAlertOwner.PLATFORM, owner_changed_at=at
+ )
+ alert.owner = PlatformAlertOwner.PLATFORM
+ alert.owner_changed_at = at
+ return True
+
+
class RollbackSkip(StrEnum):
"""Why an alert stays with the platform for now."""
diff --git a/products/alerts/backend/platform_ownership.py b/products/alerts/backend/platform_ownership.py
new file mode 100644
index 000000000000..6d8c6c76a33a
--- /dev/null
+++ b/products/alerts/backend/platform_ownership.py
@@ -0,0 +1,192 @@
+"""Keeps both rows of an insight alert the platform owns in step.
+
+An insight alert the platform owns keeps its insight row: the insight alert pages read it, the shadow
+evaluation runs it, and a rollback hands it back. So every write to either row reaches the other in
+the same transaction, and every writer locks the insight row before the platform's copy.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from dataclasses import replace
+from datetime import datetime
+from uuid import UUID
+
+from products.alerts.backend.evaluation.validation import validate_alert_config
+from products.alerts.backend.facade.contracts import PlatformCannotOwn
+from products.alerts.backend.insight_alert_state_machine import apply_disable, apply_enable, apply_threshold_change
+from products.alerts.backend.models.alert import AlertConfiguration, Threshold
+from products.alerts.backend.platform_cutover import (
+ can_move,
+ delivers_as_it_does_today,
+ hand_over,
+ has_begun_cutover,
+ in_an_environment,
+)
+from products.alerts.backend.platform_source_cycle import platform_upsert_of
+from products.alerts_platform.backend.facade.api import close_owned_firings_now, delete_owned_copy, update_owned_copy
+from products.alerts_platform.backend.facade.contracts import (
+ SOURCE_CONDITION_KEY,
+ InvalidPlatformAlertEdit,
+ PlatformAlertConfigurationEdit,
+)
+from products.alerts_platform.backend.facade.enums import PlatformAlertOwner
+
+# What an edit through either API can change on both rows. The cadence is a schedule, which the
+# platform's edit leaves out, so the check carries it onto the copy instead.
+_EDITED_FIELDS = ("name", "source_config", "schedule_restriction")
+
+
+def on_created(alert: AlertConfiguration, at: datetime) -> bool:
+ """Hands a new alert, locked by the caller, to the platform when its team has begun the cutover,
+ so the team never has to be cut over again for it. False when the alert stays with insight."""
+ return (
+ not in_an_environment(alert)
+ and can_move(alert)
+ and has_begun_cutover(alert.team_id)
+ and delivers_as_it_does_today(alert)
+ and hand_over(alert, at)
+ )
+
+
+def on_updated(alert: AlertConfiguration, *, snooze_changed: bool) -> None:
+ """Writes an edit the insight API saved onto the platform's copy.
+
+ Raises `PlatformCannotOwn` for an edit the platform cannot evaluate, such as a detector, and
+ `InvalidPlatformAlertEdit` for one the platform's schema rejects.
+ """
+ if not can_move(alert):
+ raise PlatformCannotOwn(
+ "The alerts platform runs this alert, and it cannot run detectors, real-time checks or the "
+ "investigation agent yet."
+ )
+ update_owned_copy(
+ team_id=alert.team_id,
+ legacy_configuration_id=alert.id,
+ change=_platform_change_of(alert),
+ snooze_until=alert.snoozed_until,
+ snooze_changed=snooze_changed,
+ )
+
+
+def hand_over_new_alert(*, team_id: int, alert_id: UUID, at: datetime) -> bool:
+ """Hands an alert created in the caller's transaction to the platform when its team has begun
+ the cutover. False when the alert stays with insight."""
+ alert = _locked(team_id, alert_id)
+ return alert is not None and on_created(alert, at)
+
+
+def write_moved_alert_edit(*, team_id: int, alert_id: UUID, snooze_changed: bool) -> None:
+ """Writes an edit the insight API saved in the caller's transaction onto the platform's copy.
+
+ Raises like `on_updated`.
+ """
+ alert = _locked(team_id, alert_id)
+ if alert is not None and alert.platform_owned:
+ on_updated(alert, snooze_changed=snooze_changed)
+
+
+def close_moved_alert_firings(*, team_id: int, alert_id: UUID) -> None:
+ """Ends a moved alert's firings while its destinations still exist.
+
+ Call it outside the delete's transaction, because the resolve it sends reads the history this
+ commits.
+ """
+ if AlertConfiguration.objects.filter(team_id=team_id, id=alert_id, owner=PlatformAlertOwner.PLATFORM).exists():
+ close_owned_firings_now(team_id=team_id, legacy_configuration_id=alert_id)
+
+
+def delete_moved_alert_copy(*, team_id: int, alert_id: UUID) -> None:
+ """Deletes a moved alert's copy, inside the transaction that deletes the alert.
+
+ A copy whose alert is deleted another way, such as with its insight, switches itself off at its
+ next check.
+ """
+ alert = _locked(team_id, alert_id)
+ if alert is not None and alert.platform_owned:
+ delete_owned_copy(team_id=team_id, legacy_configuration_id=alert_id)
+
+
+def _locked(team_id: int, alert_id: UUID) -> AlertConfiguration | None:
+ # Only the alert's own row is locked. Locking the team row would make a hot parent a mutex.
+ return (
+ AlertConfiguration.objects.select_for_update(no_key=True, of=("self",))
+ .select_related("team", "threshold")
+ .filter(team_id=team_id, id=alert_id)
+ .first()
+ )
+
+
+def _platform_change_of(
+ alert: AlertConfiguration,
+) -> Callable[[PlatformAlertConfigurationEdit], PlatformAlertConfigurationEdit]:
+ # Only the settings an insight alert has. The platform's own, such as grouping, keep what the
+ # copy stores, so an edit through the insight API never resets them.
+ upsert = platform_upsert_of(alert)
+ assert upsert is not None
+ shared = {field: getattr(upsert, field) for field in _EDITED_FIELDS}
+ return lambda stored: replace(stored, enabled=upsert.enabled, **shared)
+
+
+def mirror_platform_edit(
+ *, team_id: int, legacy_configuration_id: UUID
+) -> Callable[[PlatformAlertConfigurationEdit], None] | None:
+ """Locks the insight row of an alert edited through the platform API, and returns its writer."""
+ alert = (
+ AlertConfiguration.objects.select_for_update(no_key=True, of=("self",))
+ .select_related("threshold", "insight")
+ # A copy lives on the project's team. An insight alert in one of its environments is never
+ # handed over, so the copy of one is the insight stack's and refuses the edit.
+ .filter(team_id=team_id, id=legacy_configuration_id)
+ .first()
+ )
+ if alert is None:
+ return None
+ return lambda edit: _write_insight_row(alert, edit)
+
+
+def _write_insight_row(alert: AlertConfiguration, edit: PlatformAlertConfigurationEdit) -> None:
+ # The inverse of `platform_upsert_of`.
+ if edit.source_config["insight_id"] != alert.insight_id:
+ raise InvalidPlatformAlertEdit("source_config", "An insight alert cannot move to another insight.")
+ condition = edit.source_config[SOURCE_CONDITION_KEY]
+ try:
+ # The rules the insight API applies, so the insight stack never holds a pair it cannot check.
+ validate_alert_config(
+ alert.insight.query or {},
+ condition["comparison"],
+ alert.config,
+ condition["threshold"],
+ alert.calculation_interval,
+ detector_config=alert.detector_config,
+ )
+ except ValueError as error:
+ raise InvalidPlatformAlertEdit("source_config", str(error)) from error
+ update_fields = ["name", "condition", "schedule_restriction"]
+ if edit.enabled != alert.enabled:
+ # The shadow evaluation still runs this row, so an on or off moves its state the way the insight API does.
+ update_fields.extend(apply_enable(alert) if edit.enabled else apply_disable(alert))
+ if condition["comparison"] != alert.condition or condition["threshold"] != _threshold_of(alert):
+ update_fields.extend(apply_threshold_change(alert))
+ _write_threshold(alert, condition["threshold"])
+ update_fields.append("threshold")
+ alert.name = edit.name
+ alert.condition = condition["comparison"]
+ alert.schedule_restriction = edit.schedule_restriction
+ alert.save(update_fields=list(dict.fromkeys(update_fields)))
+
+
+def _threshold_of(alert: AlertConfiguration) -> dict | None:
+ return alert.threshold.configuration if alert.threshold else None
+
+
+def _write_threshold(alert: AlertConfiguration, configuration: dict | None) -> None:
+ if configuration is None:
+ alert.threshold = None
+ elif alert.threshold is not None:
+ alert.threshold.configuration = configuration
+ alert.threshold.save(update_fields=["configuration"])
+ else:
+ alert.threshold = Threshold.objects.create(
+ team_id=alert.team_id, insight_id=alert.insight_id, configuration=configuration
+ )
diff --git a/products/alerts/backend/platform_source_config.py b/products/alerts/backend/platform_source_config.py
new file mode 100644
index 000000000000..3df035e0701f
--- /dev/null
+++ b/products/alerts/backend/platform_source_config.py
@@ -0,0 +1,14 @@
+"""Where the alerts platform finds the schema of an insight alert's `source_config`.
+
+Registered from `ready()`, so it stays light: the schema loads on first use.
+"""
+
+from products.alerts_platform.backend.facade.contracts import SourceConfigSpec
+
+
+def load_insight_source_config() -> SourceConfigSpec:
+ from products.alerts.backend.platform_source_config_schema import ( # noqa: PLC0415 - keeps posthog.schema off the startup path
+ INSIGHT_SOURCE_CONFIG,
+ )
+
+ return INSIGHT_SOURCE_CONFIG
diff --git a/products/alerts/backend/platform_source_config_schema.py b/products/alerts/backend/platform_source_config_schema.py
new file mode 100644
index 000000000000..9ee564e45054
--- /dev/null
+++ b/products/alerts/backend/platform_source_config_schema.py
@@ -0,0 +1,62 @@
+"""The schema an insight alert's `source_config` takes in the alerts platform's API, and the rules for
+a whole edit.
+
+Loaded on first use through `load_insight_source_config`, never from `ready()`, because it is built
+on `posthog.schema`.
+"""
+
+from pydantic import BaseModel, ConfigDict, Field
+
+from posthog.schema import AlertCondition, InsightThreshold
+
+from products.alerts.backend.platform_ownership import mirror_platform_edit
+from products.alerts_platform.backend.facade.contracts import (
+ GroupingMode,
+ InvalidPlatformAlertEdit,
+ PlatformAlertConfigurationEdit,
+ SourceConfigSpec,
+)
+
+
+class InsightPlatformAlertCondition(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ threshold: InsightThreshold | None = Field(
+ ..., description="The bounds the insight's value is checked against, absolute or as a percentage change."
+ )
+ comparison: AlertCondition = Field(
+ ...,
+ description="How the value is compared: as it is, or as an increase or decrease from the previous interval.",
+ )
+ detector: None = Field(
+ default=None, description="Always null. The platform owns threshold alerts only, so no detector applies."
+ )
+
+
+class InsightPlatformAlertSourceConfig(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ insight_id: int = Field(..., description="The insight the alert checks. It cannot change through this API.")
+ condition: InsightPlatformAlertCondition = Field(
+ ..., description="The bound the insight's value is checked against."
+ )
+
+
+def validate_insight_edit(edit: PlatformAlertConfigurationEdit) -> None:
+ # The insight row has no place for these, and a value it cannot store would be lost on handback.
+ if edit.grouping.mode != GroupingMode.SINGLE:
+ raise InvalidPlatformAlertEdit("grouping", "An insight alert cannot be grouped through this API yet.")
+ for name, value, stored in (
+ ("evaluation_periods", edit.evaluation_periods, 1),
+ ("datapoints_to_alarm", edit.datapoints_to_alarm, 1),
+ ("cooldown_minutes", edit.cooldown_minutes, 0),
+ ):
+ if value != stored:
+ raise InvalidPlatformAlertEdit(name, f"An insight alert keeps this at {stored}.")
+
+
+INSIGHT_SOURCE_CONFIG = SourceConfigSpec(
+ model=InsightPlatformAlertSourceConfig,
+ validate=validate_insight_edit,
+ mirror=mirror_platform_edit,
+)
diff --git a/products/alerts/backend/presentation/views/alert.py b/products/alerts/backend/presentation/views/alert.py
index b699edfa04c9..5e0f7a1a84ab 100644
--- a/products/alerts/backend/presentation/views/alert.py
+++ b/products/alerts/backend/presentation/views/alert.py
@@ -95,6 +95,7 @@ from products.alerts.backend.facade.contracts import (
INSIGHT_ALERT_DESTINATION_TYPES,
INSIGHT_ALERT_EVENT_IDS,
MovedAlertCheck,
+ PlatformCannotOwn,
)
from products.alerts.backend.facade.destinations import (
MAX_DESTINATION_IDS_PER_DELETE_REQUEST,
@@ -106,7 +107,15 @@ from products.alerts.backend.facade.destinations import (
validate_destination_data,
)
from products.alerts.backend.facade.evaluation import DelayedEvaluationUnavailable, validate_evaluation_delay
-from products.alerts.backend.facade.platform import follow_insight_alert, moved_alert_check_page, moved_alert_statuses
+from products.alerts.backend.facade.platform import (
+ close_moved_alert_firings,
+ delete_moved_alert_copy,
+ follow_insight_alert,
+ hand_over_new_alert,
+ moved_alert_check_page,
+ moved_alert_statuses,
+ write_moved_alert_edit,
+)
from products.alerts.backend.insight_alert_state_machine import (
apply_disable,
apply_enable,
@@ -126,6 +135,7 @@ from products.alerts_platform.backend.facade.contracts import (
AlertDestinationData,
AlertDestinationValidationError,
DestinationType,
+ InvalidPlatformAlertEdit,
)
from products.alerts_platform.backend.facade.scheduling import validate_and_normalize_schedule_start_time
from products.alerts_platform.backend.presentation.views.schedule_restriction import ScheduleRestrictionField
@@ -896,6 +906,8 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
if instance.schedule_start_time is not None:
instance.next_check_at = next_check_at_after_schedule_restriction_change(instance)
instance.save(update_fields=["next_check_at"])
+ if hand_over_new_alert(team_id=instance.team_id, alert_id=instance.id, at=timezone.now()):
+ instance.refresh_from_db(fields=["owner", "owner_changed_at"])
for user in subscribed_users:
AlertSubscription.objects.create(
@@ -906,7 +918,8 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
self.context["request"].user,
analytics_props=get_request_analytics_properties(self.context["request"]),
)
- if instance.enabled:
+ # A handed-over copy is the platform's now, and a revived copy would lose its state.
+ if instance.enabled and not instance.platform_owned:
transaction.on_commit(
lambda: follow_insight_alert(team_id=instance.team_id, alert_id=instance.id), robust=True
)
@@ -1029,12 +1042,23 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
if schedule_restriction_changed or schedule_start_time_changed:
instance.next_check_at = next_check_at_after_schedule_restriction_change(instance)
instance.save(update_fields=["next_check_at"])
+ if instance.platform_owned:
+ try:
+ write_moved_alert_edit(
+ team_id=instance.team_id,
+ alert_id=instance.id,
+ snooze_changed=snoozed_until_param is not serializers.empty,
+ )
+ except PlatformCannotOwn as error:
+ raise ValidationError(str(error)) from error
+ except InvalidPlatformAlertEdit as error:
+ raise ValidationError({error.field_name: str(error)}) from error
instance.report_updated(
self.context["request"].user,
analytics_props=get_request_analytics_properties(self.context["request"]),
)
- if enable_now:
+ if enable_now and not instance.platform_owned:
transaction.on_commit(
lambda: follow_insight_alert(team_id=instance.team_id, alert_id=instance.id), robust=True
)
@@ -1692,6 +1716,16 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
serializer = self.get_serializer(instance)
return Response(serializer.data)
+ def perform_destroy(self, instance: AlertConfiguration) -> None:
+ # Before the delete, while the destinations a firing's resolve goes to still exist.
+ if instance.platform_owned:
+ close_moved_alert_firings(team_id=instance.team_id, alert_id=instance.id)
+ # The copy and the alert go together, so a failed delete leaves no moved alert without its copy.
+ with transaction.atomic():
+ if instance.platform_owned:
+ delete_moved_alert_copy(team_id=instance.team_id, alert_id=instance.id)
+ super().perform_destroy(instance)
+
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
diff --git a/products/alerts/backend/test/test_platform_cutover.py b/products/alerts/backend/test/test_platform_cutover.py
index b265bd209e68..7456cbcafdb5 100644
--- a/products/alerts/backend/test/test_platform_cutover.py
+++ b/products/alerts/backend/test/test_platform_cutover.py
@@ -6,6 +6,7 @@ from unittest.mock import patch
from parameterized import parameterized
+from posthog.models import Team
from posthog.models.scoping import team_scope
from posthog.schema_enums import AlertCalculationInterval, AlertState
@@ -83,6 +84,16 @@ class TestInsightPlatformCutover(APIBaseTest):
alert.refresh_from_db()
assert alert.owner == "source"
+ def test_an_alert_in_a_child_environment_stays_with_insight(self) -> None:
+ environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="env")
+ alert = create_insight_alert(environment, next_check_at=NOW + timedelta(minutes=3))
+
+ (result,) = cut_over_team(environment.id, now=NOW)
+
+ assert result.skipped == CutoverSkip.ENVIRONMENT
+ alert.refresh_from_db()
+ assert alert.owner == "source"
+
@parameterized.expand([("events_emitted", True, None), ("nothing_emits", False, CutoverSkip.NO_HOG_FUNCTION_PATH)])
def test_an_alert_on_the_hog_function_path_moves_only_while_its_events_are_emitted(
self, _name: str, emitter: bool, reason: CutoverSkip | None
diff --git a/products/alerts/backend/tests/api/test_alert_platform_owned.py b/products/alerts/backend/tests/api/test_alert_platform_owned.py
index 2afbae949a06..7334a5245cd5 100644
--- a/products/alerts/backend/tests/api/test_alert_platform_owned.py
+++ b/products/alerts/backend/tests/api/test_alert_platform_owned.py
@@ -1,18 +1,31 @@
+from collections.abc import Callable
+from dataclasses import replace
from datetime import UTC, datetime, timedelta
from typing import Any
+import pytest
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import patch
from parameterized import parameterized
from rest_framework import status
+from posthog.constants import AvailableFeature
from posthog.models.scoping import team_scope
+from posthog.schema_enums import AlertCalculationInterval
-from products.alerts.backend.models.alert import AlertCheck
+from products.alerts.backend.facade.api import snooze_alert_from_slack
+from products.alerts.backend.facade.contracts import PlatformCannotOwn
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
from products.alerts.backend.platform_cutover import cut_over_team
from products.alerts.backend.test.insight_alerts import create_insight_alert
from products.alerts_platform.backend.facade import testing as platform_testing
+from products.alerts_platform.backend.facade.api import get_configuration, update_configuration
+from products.alerts_platform.backend.facade.contracts import (
+ InvalidPlatformAlertEdit,
+ PlatformAlertConfigurationEdit,
+ SourceKind,
+)
def _iso(moment: datetime) -> str:
@@ -105,3 +118,143 @@ class TestPlatformOwnedInsightAlert(ClickhouseTestMixin, APIBaseTest):
row = self._row("retrieve")
assert [(check["state"], check["calculated_value"]) for check in row["checks"]] == [("Not firing", 1.0)]
+
+
+class TestPlatformOwnedInsightAlertWrites(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.now = datetime.now(UTC)
+ self.alert = create_insight_alert(self.team, next_check_at=self.now + timedelta(minutes=3))
+ [cutover] = cut_over_team(self.team.id, now=self.now)
+ assert cutover.skipped is None
+ with team_scope(self.team.id):
+ self.copy_id = platform_testing.copy_of(self.alert.id).id
+ self.url = f"/api/projects/{self.team.id}/alerts"
+
+ def _copy(self) -> Any:
+ with team_scope(self.team.id):
+ view = get_configuration(
+ team_id=self.team.id, source_kinds=[SourceKind.INSIGHT.value], configuration_id=self.copy_id
+ )
+ assert view is not None
+ return view
+
+ def _edit_on_the_platform(
+ self, change: Callable[[PlatformAlertConfigurationEdit], PlatformAlertConfigurationEdit]
+ ) -> None:
+ # The platform API does not serve insight copies yet, so this calls the edit it would make.
+ with team_scope(self.team.id):
+ update_configuration(
+ team_id=self.team.id,
+ source_kinds=[SourceKind.INSIGHT.value],
+ configuration_id=self.copy_id,
+ change=change,
+ )
+
+ def test_each_api_writes_both_rows_of_an_alert_the_platform_owns(self) -> None:
+ self._edit_on_the_platform(lambda stored: replace(stored, name="Edited on the platform"))
+ insight_edit = self.client.patch(
+ f"{self.url}/{self.alert.id}/",
+ {"threshold": {"configuration": {"type": "absolute", "bounds": {"upper": 200}}}},
+ format="json",
+ )
+
+ assert insight_edit.status_code == status.HTTP_200_OK, insight_edit.json()
+ assert insight_edit.json()["name"] == "Edited on the platform"
+ copy = self._copy()
+ assert (copy.name, copy.source_config["condition"]["threshold"]["bounds"]) == (
+ "Edited on the platform",
+ {"upper": 200},
+ )
+
+ def test_a_platform_edit_the_insight_stack_cannot_check_is_refused_on_both_rows(self) -> None:
+ def percentage_bound(stored: PlatformAlertConfigurationEdit) -> PlatformAlertConfigurationEdit:
+ threshold = {"type": "percentage", "bounds": {"upper": 0.5}}
+ condition = {**stored.source_config["condition"], "threshold": threshold}
+ return replace(stored, source_config={**stored.source_config, "condition": condition})
+
+ with pytest.raises(InvalidPlatformAlertEdit):
+ self._edit_on_the_platform(percentage_bound)
+
+ self.alert.refresh_from_db()
+ assert self.alert.threshold is not None
+ assert (
+ self.alert.threshold.configuration["type"],
+ self._copy().source_config["condition"]["threshold"]["type"],
+ ) == (
+ "absolute",
+ "absolute",
+ )
+
+ def test_a_snooze_from_slack_mutes_the_platform_copy(self) -> None:
+ outcome = snooze_alert_from_slack(self.alert.id, user=self.user, duration="1d")
+
+ assert outcome == "snoozed"
+ self.alert.refresh_from_db()
+ assert self.alert.snoozed_until is not None
+ assert self._copy().snooze_until == self.alert.snoozed_until
+
+ def test_a_snooze_the_platform_refuses_leaves_both_rows_unsnoozed(self) -> None:
+ with patch(
+ "products.alerts.backend.platform_ownership.on_updated",
+ side_effect=PlatformCannotOwn("The alerts platform cannot run this alert."),
+ ):
+ outcome = snooze_alert_from_slack(self.alert.id, user=self.user, duration="1d")
+
+ assert outcome == "not_snoozable"
+ self.alert.refresh_from_db()
+ assert (self.alert.snoozed_until, self._copy().snooze_until) == (None, None)
+
+ def test_an_edit_the_platform_cannot_run_is_refused_on_both_rows(self) -> None:
+ # Real-time passes the insight API's own checks on this insight, so only the platform refuses it.
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.REAL_TIME_ALERTS, "name": "Real-time alerts"}
+ ]
+ self.organization.save()
+
+ response = self.client.patch(
+ f"{self.url}/{self.alert.id}/",
+ {"calculation_interval": AlertCalculationInterval.REAL_TIME.value},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert "alerts platform" in str(response.json())
+ self.alert.refresh_from_db()
+ assert self.alert.calculation_interval == AlertCalculationInterval.DAILY.value
+
+ @parameterized.expand([("a_team_on_the_platform", True), ("a_team_off_the_platform", False)])
+ def test_a_new_alert_is_handed_over_only_in_a_team_on_the_platform(self, _name: str, begun: bool) -> None:
+ if not begun:
+ AlertConfiguration.objects.filter(id=self.alert.id).update(owner="source")
+ insight = create_insight_alert(self.team).insight
+
+ response = self.client.post(
+ f"{self.url}",
+ {
+ "insight": insight.id,
+ "subscribed_users": [self.user.id],
+ "condition": {"type": "absolute_value"},
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "name": "A new alert",
+ "threshold": {"configuration": {"type": "absolute", "bounds": {"upper": 100}}},
+ "calculation_interval": "daily",
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ created = AlertConfiguration.objects.get(id=response.json()["id"])
+ assert created.owner == ("platform" if begun else "source")
+
+ def test_deleting_a_moved_alert_deletes_its_copy(self) -> None:
+ response = self.client.delete(f"{self.url}/{self.alert.id}/")
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ with team_scope(self.team.id):
+ assert (
+ get_configuration(
+ team_id=self.team.id, source_kinds=[SourceKind.INSIGHT.value], configuration_id=self.copy_id
+ )
+ is None
+ )
diff --git a/products/alerts_platform/frontend/generated/api.schemas.ts b/products/alerts_platform/frontend/generated/api.schemas.ts
index 8e3bf886158f..c7031029f8ac 100644
--- a/products/alerts_platform/frontend/generated/api.schemas.ts
+++ b/products/alerts_platform/frontend/generated/api.schemas.ts
@@ -718,6 +718,106 @@ export interface LogsPlatformAlertConfigurationCreateApi {
export type PlatformAlertConfigurationCreateApi = LogsPlatformAlertConfigurationCreateApi
+/**
+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.
+ */
+export type InsightPlatformAlertConfigurationEditApiSourceKind =
+ (typeof InsightPlatformAlertConfigurationEditApiSourceKind)[keyof typeof InsightPlatformAlertConfigurationEditApiSourceKind]
+
+export const InsightPlatformAlertConfigurationEditApiSourceKind = {
+ Insight: 'insight',
+} as const
+
+export interface InsightsThresholdBoundsApi {
+ /** Alert fires when the value drops below this number. */
+ lower?: number | null
+ /** Alert fires when the value exceeds this number. */
+ upper?: number | null
+}
+
+export type InsightThresholdTypeApi = (typeof InsightThresholdTypeApi)[keyof typeof InsightThresholdTypeApi]
+
+export const InsightThresholdTypeApi = {
+ Absolute: 'absolute',
+ Percentage: 'percentage',
+} as const
+
+export interface InsightThresholdApi {
+ bounds?: InsightsThresholdBoundsApi | null
+ /** Whether bounds are compared as absolute values or as percentage change from the previous interval. */
+ type: InsightThresholdTypeApi
+}
+
+export type AlertConditionTypeApi = (typeof AlertConditionTypeApi)[keyof typeof AlertConditionTypeApi]
+
+export const AlertConditionTypeApi = {
+ AbsoluteValue: 'absolute_value',
+ RelativeIncrease: 'relative_increase',
+ RelativeDecrease: 'relative_decrease',
+} as const
+
+export interface AlertConditionApi {
+ type: AlertConditionTypeApi
+}
+
+export interface InsightPlatformAlertConditionApi {
+ /** The bounds the insight's value is checked against, absolute or as a percentage change. */
+ threshold: InsightThresholdApi | null
+ /** How the value is compared: as it is, or as an increase or decrease from the previous interval. */
+ comparison: AlertConditionApi
+ /**
+ * Always null. The platform owns threshold alerts only, so no detector applies.
+ * @nullable
+ */
+ detector?: null
+}
+
+export interface InsightPlatformAlertSourceConfigApi {
+ /** The insight the alert checks. It cannot change through this API. */
+ insight_id: number
+ /** The bound the insight's value is checked against. */
+ condition: InsightPlatformAlertConditionApi
+}
+
+/**
+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.
+ */
+export interface InsightPlatformAlertConfigurationEditApi {
+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */
+ source_kind: InsightPlatformAlertConfigurationEditApiSourceKind
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 255
+ */
+ name: string
+ /** Whether the alert is evaluated on schedule. */
+ enabled: boolean
+ /** Settings for a insight alert. The bound the alert is evaluated against is under condition. */
+ source_config: InsightPlatformAlertSourceConfigApi
+ /** 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
+}
+
/**
* Product whose data the alert evaluates. It cannot change, so it must match the stored value.
*/
@@ -767,7 +867,58 @@ export interface LogsPlatformAlertConfigurationEditApi {
cooldown_minutes: number
}
-export type PlatformAlertConfigurationEditApi = LogsPlatformAlertConfigurationEditApi
+export type PlatformAlertConfigurationEditApi =
+ | InsightPlatformAlertConfigurationEditApi
+ | LogsPlatformAlertConfigurationEditApi
+
+/**
+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.
+ */
+export type PatchedInsightPlatformAlertConfigurationEditApiSourceKind =
+ (typeof PatchedInsightPlatformAlertConfigurationEditApiSourceKind)[keyof typeof PatchedInsightPlatformAlertConfigurationEditApiSourceKind]
+
+export const PatchedInsightPlatformAlertConfigurationEditApiSourceKind = {
+ Insight: 'insight',
+} as const
+
+/**
+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.
+ */
+export interface PatchedInsightPlatformAlertConfigurationEditApi {
+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */
+ source_kind: PatchedInsightPlatformAlertConfigurationEditApiSourceKind
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 255
+ */
+ name?: string
+ /** Whether the alert is evaluated on schedule. */
+ enabled?: boolean
+ /** Settings for a insight alert. The bound the alert is evaluated against is under condition. */
+ source_config?: InsightPlatformAlertSourceConfigApi
+ /** 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
+}
/**
* Product whose data the alert evaluates. It cannot change, so it must match the stored value.
@@ -818,7 +969,9 @@ export interface PatchedLogsPlatformAlertConfigurationEditApi {
cooldown_minutes?: number
}
-export type PatchedPlatformAlertConfigurationEditApi = PatchedLogsPlatformAlertConfigurationEditApi
+export type PatchedPlatformAlertConfigurationEditApi =
+ | PatchedInsightPlatformAlertConfigurationEditApi
+ | PatchedLogsPlatformAlertConfigurationEditApi
export interface PlatformAlertGroupSnoozeApi {
/**
diff --git a/products/alerts_platform/frontend/generated/api.zod.ts b/products/alerts_platform/frontend/generated/api.zod.ts
index 217752d6267d..e1c621b18915 100644
--- a/products/alerts_platform/frontend/generated/api.zod.ts
+++ b/products/alerts_platform/frontend/generated/api.zod.ts
@@ -178,9 +178,6 @@ export const PlatformAlertsCreateBody = /* @__PURE__ */ zod
export const platformAlertsUpdateBodyOneNameMax = 255
-export const platformAlertsUpdateBodyOneSourceConfigOneConditionThresholdCountMin = 0
-export const platformAlertsUpdateBodyOneSourceConfigOneConditionThresholdCountMax = 2147483647
-
export const platformAlertsUpdateBodyOneGroupingOneMaxInstancesDefault = 100
export const platformAlertsUpdateBodyOneGroupingOneMaxInstancesMax = 100
@@ -192,145 +189,309 @@ 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())
+export const platformAlertsUpdateBodyTwoNameMax = 255
+
+export const platformAlertsUpdateBodyTwoSourceConfigOneConditionThresholdCountMin = 0
+export const platformAlertsUpdateBodyTwoSourceConfigOneConditionThresholdCountMax = 2147483647
+
+export const platformAlertsUpdateBodyTwoGroupingOneMaxInstancesDefault = 100
+export const platformAlertsUpdateBodyTwoGroupingOneMaxInstancesMax = 100
+
+export const platformAlertsUpdateBodyTwoGroupingOneOnOverflowDefault = `degrade_visible`
+export const platformAlertsUpdateBodyTwoEvaluationPeriodsMax = 10
+
+export const platformAlertsUpdateBodyTwoDatapointsToAlarmMax = 10
+
+export const platformAlertsUpdateBodyTwoCooldownMinutesMin = 0
+export const platformAlertsUpdateBodyTwoCooldownMinutesMax = 2147483647
+
+export const PlatformAlertsUpdateBody = /* @__PURE__ */ zod.union([
+ zod
+ .object({
+ source_kind: zod
+ .enum(['insight'])
+ .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({
+ insight_id: zod
+ .number()
+ .describe('The insight the alert checks. It cannot change through this API.'),
+ condition: zod
+ .object({
+ threshold: zod
+ .union([
+ zod.object({
+ bounds: zod
+ .union([
+ zod.object({
+ lower: zod
+ .union([zod.number(), zod.null()])
+ .optional()
+ .describe(
+ 'Alert fires when the value drops below this number.'
+ ),
+ upper: zod
+ .union([zod.number(), zod.null()])
+ .optional()
+ .describe('Alert fires when the value exceeds this number.'),
+ }),
+ zod.null(),
+ ])
+ .optional(),
+ type: zod
+ .enum(['absolute', 'percentage'])
.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)
- .max(platformAlertsUpdateBodyOneSourceConfigOneConditionThresholdCountMax)
+ 'Whether bounds are compared as absolute values or as percentage change from the previous interval.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .describe(
+ "The bounds the insight's value is checked against, absolute or as a percentage change."
+ ),
+ comparison: zod
+ .object({
+ type: zod.enum(['absolute_value', 'relative_increase', 'relative_decrease']),
+ })
+ .describe(
+ 'How the value is compared: as it is, or as an increase or decrease from the previous interval.'
+ ),
+ detector: zod
+ .null()
+ .optional()
+ .describe(
+ 'Always null. The platform owns threshold alerts only, so no detector applies.'
+ ),
+ })
+ .describe("The bound the insight's value is checked against."),
+ })
+ .describe('Settings for a insight 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(
- 'Number of matching log entries in the window that breaches the threshold. Use 0 with the above operator to fire on any matching log.'
+ '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.'
),
- 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.'
- ),
- })
- )
+ }),
+ 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`.'),
+ 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(platformAlertsUpdateBodyTwoNameMax).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(
- '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.'
+ 'The logs the alert counts: severityLevels, serviceNames, or a filterGroup of property filters. An enabled alert needs at least one.'
),
- }),
- 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`.')
+ condition: zod
+ .object({
+ threshold_count: zod
+ .number()
+ .min(platformAlertsUpdateBodyTwoSourceConfigOneConditionThresholdCountMin)
+ .max(platformAlertsUpdateBodyTwoSourceConfigOneConditionThresholdCountMax)
+ .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(platformAlertsUpdateBodyTwoGroupingOneMaxInstancesMax)
+ .default(platformAlertsUpdateBodyTwoGroupingOneMaxInstancesDefault)
+ .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(platformAlertsUpdateBodyTwoGroupingOneOnOverflowDefault)
+ .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(platformAlertsUpdateBodyTwoEvaluationPeriodsMax)
+ .describe('Number of recent checks considered when deciding to fire.'),
+ datapoints_to_alarm: zod
+ .number()
+ .min(1)
+ .max(platformAlertsUpdateBodyTwoDatapointsToAlarmMax)
+ .describe(
+ 'Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.'
+ ),
+ cooldown_minutes: zod
+ .number()
+ .min(platformAlertsUpdateBodyTwoCooldownMinutesMin)
+ .max(platformAlertsUpdateBodyTwoCooldownMinutesMax)
+ .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 platformAlertsPartialUpdateBodyOneSourceConfigOneConditionThresholdCountMax = 2147483647
-
export const platformAlertsPartialUpdateBodyOneGroupingOneMaxInstancesDefault = 100
export const platformAlertsPartialUpdateBodyOneGroupingOneMaxInstancesMax = 100
@@ -342,149 +503,326 @@ 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())
+export const platformAlertsPartialUpdateBodyTwoNameMax = 255
+
+export const platformAlertsPartialUpdateBodyTwoSourceConfigOneConditionThresholdCountMin = 0
+export const platformAlertsPartialUpdateBodyTwoSourceConfigOneConditionThresholdCountMax = 2147483647
+
+export const platformAlertsPartialUpdateBodyTwoGroupingOneMaxInstancesDefault = 100
+export const platformAlertsPartialUpdateBodyTwoGroupingOneMaxInstancesMax = 100
+
+export const platformAlertsPartialUpdateBodyTwoGroupingOneOnOverflowDefault = `degrade_visible`
+export const platformAlertsPartialUpdateBodyTwoEvaluationPeriodsMax = 10
+
+export const platformAlertsPartialUpdateBodyTwoDatapointsToAlarmMax = 10
+
+export const platformAlertsPartialUpdateBodyTwoCooldownMinutesMin = 0
+export const platformAlertsPartialUpdateBodyTwoCooldownMinutesMax = 2147483647
+
+export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod.union([
+ zod
+ .object({
+ source_kind: zod
+ .enum(['insight'])
+ .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({
+ insight_id: zod
+ .number()
+ .describe('The insight the alert checks. It cannot change through this API.'),
+ condition: zod
+ .object({
+ threshold: zod
+ .union([
+ zod.object({
+ bounds: zod
+ .union([
+ zod.object({
+ lower: zod
+ .union([zod.number(), zod.null()])
+ .optional()
+ .describe(
+ 'Alert fires when the value drops below this number.'
+ ),
+ upper: zod
+ .union([zod.number(), zod.null()])
+ .optional()
+ .describe('Alert fires when the value exceeds this number.'),
+ }),
+ zod.null(),
+ ])
+ .optional(),
+ type: zod
+ .enum(['absolute', 'percentage'])
.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)
- .max(platformAlertsPartialUpdateBodyOneSourceConfigOneConditionThresholdCountMax)
+ 'Whether bounds are compared as absolute values or as percentage change from the previous interval.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .describe(
+ "The bounds the insight's value is checked against, absolute or as a percentage change."
+ ),
+ comparison: zod
+ .object({
+ type: zod.enum(['absolute_value', 'relative_increase', 'relative_decrease']),
+ })
+ .describe(
+ 'How the value is compared: as it is, or as an increase or decrease from the previous interval.'
+ ),
+ detector: zod
+ .null()
+ .optional()
+ .describe(
+ 'Always null. The platform owns threshold alerts only, so no detector applies.'
+ ),
+ })
+ .describe("The bound the insight's value is checked against."),
+ })
+ .optional()
+ .describe('Settings for a insight 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(
- 'Number of matching log entries in the window that breaches the threshold. Use 0 with the above operator to fire on any matching log.'
+ '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.'
),
- 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.'
- ),
- })
- )
+ }),
+ 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`.'),
+ 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(platformAlertsPartialUpdateBodyTwoNameMax)
+ .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(
- '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.'
+ 'The logs the alert counts: severityLevels, serviceNames, or a filterGroup of property filters. An enabled alert needs at least one.'
),
- }),
- 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`.')
+ condition: zod
+ .object({
+ threshold_count: zod
+ .number()
+ .min(platformAlertsPartialUpdateBodyTwoSourceConfigOneConditionThresholdCountMin)
+ .max(platformAlertsPartialUpdateBodyTwoSourceConfigOneConditionThresholdCountMax)
+ .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(platformAlertsPartialUpdateBodyTwoGroupingOneMaxInstancesMax)
+ .default(platformAlertsPartialUpdateBodyTwoGroupingOneMaxInstancesDefault)
+ .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(platformAlertsPartialUpdateBodyTwoGroupingOneOnOverflowDefault)
+ .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(platformAlertsPartialUpdateBodyTwoEvaluationPeriodsMax)
+ .optional()
+ .describe('Number of recent checks considered when deciding to fire.'),
+ datapoints_to_alarm: zod
+ .number()
+ .min(1)
+ .max(platformAlertsPartialUpdateBodyTwoDatapointsToAlarmMax)
+ .optional()
+ .describe(
+ 'Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.'
+ ),
+ cooldown_minutes: zod
+ .number()
+ .min(platformAlertsPartialUpdateBodyTwoCooldownMinutesMin)
+ .max(platformAlertsPartialUpdateBodyTwoCooldownMinutesMax)
+ .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`.'),
+])
/**
* @summary Snooze one group of a grouped alert
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 038af90598d1..e3dd516d62db 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -183,6 +183,9 @@ SLACK_PLACEHOLDER_USER_ID = "U00"
# person forgot how it works.
ONBOARDING_DEDUPE_TTL_SECONDS = 60 * 10
+# Shown when the alerts platform owns an insight alert and refuses a snooze from Slack.
+NOT_SNOOZABLE_FROM_SLACK = "This alert couldn't be snoozed from Slack. Snooze it in PostHog instead."
+
EDITED_MENTION_WINDOW_SECONDS = 60 * 60
# Outlives the window, because an expired marker would let an edit start a second run.
MESSAGE_HANDLED_MARKER_TTL_SECONDS = 2 * EDITED_MENTION_WINDOW_SECONDS
@@ -5782,6 +5785,15 @@ def _handle_insight_alert_snooze(payload: dict) -> HttpResponse:
logger.info("insight_alert_snooze_alert_disabled", alert_id=str(alert_uuid))
_replace_message_stripping_actions(payload, "This alert is disabled, so there is nothing to snooze.")
return HttpResponse(status=200)
+ if outcome == "not_snoozable":
+ logger.warning("insight_alert_snooze_refused_by_platform", alert_id=str(alert_uuid))
+ response_url = payload.get("response_url")
+ if response_url:
+ inbox_interactivity.post_response_url(
+ response_url,
+ {"response_type": "ephemeral", "replace_original": False, "text": NOT_SNOOZABLE_FROM_SLACK},
+ )
+ return HttpResponse(status=200)
if outcome == "invalid_until":
logger.info("insight_alert_snooze_invalid_until", alert_id=str(alert_uuid))
response_url = payload.get("response_url")
@@ -5907,6 +5919,8 @@ def _handle_insight_alert_snooze_modal_submit(payload: dict) -> HttpResponse:
outcome = snooze_alert_from_slack(alert_uuid, until=until, user=org_member)
if outcome == "invalid_until":
return _snooze_modal_error(f"Pick a time in the next {SLACK_SNOOZE_MAX_DAYS} days.")
+ if outcome == "not_snoozable":
+ return _snooze_modal_error(NOT_SNOOZABLE_FROM_SLACK)
if outcome in ("no_access", "not_found", "disabled"):
logger.info("insight_alert_snooze_modal_submit_rejected", alert_id=str(alert_uuid), outcome=outcome)
return HttpResponse(status=200)
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 13bc0ec4e9d8..1284e06af69b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -61756,6 +61756,74 @@ export namespace Schemas {
client_query_id?: string;
}
+ export interface InsightPlatformAlertCondition {
+ /** The bounds the insight's value is checked against, absolute or as a percentage change. */
+ threshold: InsightThreshold | null;
+ /** How the value is compared: as it is, or as an increase or decrease from the previous interval. */
+ comparison: AlertCondition;
+ /**
+ * Always null. The platform owns threshold alerts only, so no detector applies.
+ * @nullable
+ */
+ detector?: null;
+ }
+
+ /**
+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.
+ */
+ export type InsightPlatformAlertConfigurationEditSourceKind = typeof InsightPlatformAlertConfigurationEditSourceKind[keyof typeof InsightPlatformAlertConfigurationEditSourceKind];
+
+
+ export const InsightPlatformAlertConfigurationEditSourceKind = {
+ Insight: 'insight',
+ } as const;
+
+ export interface InsightPlatformAlertSourceConfig {
+ /** The insight the alert checks. It cannot change through this API. */
+ insight_id: number;
+ /** The bound the insight's value is checked against. */
+ condition: InsightPlatformAlertCondition;
+ }
+
+ /**
+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.
+ */
+ export interface InsightPlatformAlertConfigurationEdit {
+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */
+ source_kind: InsightPlatformAlertConfigurationEditSourceKind;
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 255
+ */
+ name: string;
+ /** Whether the alert is evaluated on schedule. */
+ enabled: boolean;
+ /** Settings for a insight alert. The bound the alert is evaluated against is under condition. */
+ source_config: InsightPlatformAlertSourceConfig;
+ /** 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;
+ }
+
/**
* * `trends` - trends
* * `funnel` - funnel
@@ -84079,6 +84147,55 @@ export namespace Schemas {
readonly search_match_type?: SearchMatchTypeEnum | null;
}
+ /**
+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.
+ */
+ export type PatchedInsightPlatformAlertConfigurationEditSourceKind = typeof PatchedInsightPlatformAlertConfigurationEditSourceKind[keyof typeof PatchedInsightPlatformAlertConfigurationEditSourceKind];
+
+
+ export const PatchedInsightPlatformAlertConfigurationEditSourceKind = {
+ Insight: 'insight',
+ } as const;
+
+ /**
+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.
+ */
+ export interface PatchedInsightPlatformAlertConfigurationEdit {
+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */
+ source_kind: PatchedInsightPlatformAlertConfigurationEditSourceKind;
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 255
+ */
+ name?: string;
+ /** Whether the alert is evaluated on schedule. */
+ enabled?: boolean;
+ /** Settings for a insight alert. The bound the alert is evaluated against is under condition. */
+ source_config?: InsightPlatformAlertSourceConfig;
+ /** 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 PatchedInsightVariable {
/** UUID of the SQL variable. */
readonly id?: string;
@@ -85185,7 +85302,7 @@ export namespace Schemas {
homepage?: PinnedSceneTab | null;
}
- export type PatchedPlatformAlertConfigurationEdit = PatchedLogsPlatformAlertConfigurationEdit;
+ export type PatchedPlatformAlertConfigurationEdit = PatchedInsightPlatformAlertConfigurationEdit | PatchedLogsPlatformAlertConfigurationEdit;
/**
* Request body for PATCH /api/users/@me/product_intro_seen.
@@ -90215,7 +90332,7 @@ export namespace Schemas {
export type PlatformAlertConfigurationCreate = LogsPlatformAlertConfigurationCreate;
- export type PlatformAlertConfigurationEdit = LogsPlatformAlertConfigurationEdit;
+ export type PlatformAlertConfigurationEdit = InsightPlatformAlertConfigurationEdit | LogsPlatformAlertConfigurationEdit;
export interface PlatformAlertGroupSnooze {
/**