:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import json
import uuid
from datetime import datetime
from functools import reduce
from operator import or_
from typing import Annotated, Any, Final, cast
from zoneinfo import ZoneInfo
from django.db import transaction
from django.db.models import OuterRef, Prefetch, Q, QuerySet, Subquery
from django.utils import timezone
import pydantic
import posthoganalytics
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, OpenApiTypes, extend_schema, extend_schema_view
from pydantic import (
Field as PydanticField,
RootModel,
)
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import APIException, ValidationError
from rest_framework.response import Response
from posthog.schema import (
AlertCalculationInterval,
AlertCondition,
DetectorConfig,
DetectorType,
FunnelsAlertConfig,
HogQLAlertConfig,
InsightThreshold,
MetricsAlertConfig,
NodeKind,
TrendsAlertConfig,
)
from posthog.api.documentation import extend_schema_field
from posthog.api.fields import OptionalBooleanField
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer
from posthog.email import is_email_available
from posthog.event_usage import get_request_analytics_properties
from posthog.exceptions import InsufficientScope, as_drf_validation_error
from posthog.exceptions_capture import capture_exception
from posthog.helpers.impersonation import is_impersonated
from posthog.helpers.trigram_search import (
MAX_SEARCH_LENGTH,
NAME_FIELD,
apply_trigram_search,
drop_similar_when_exact_exists,
)
from posthog.integrations import IntegrationManager
from posthog.models import User
from posthog.models.activity_logging.model_activity import get_was_impersonated
from posthog.models.tag import tagify
from posthog.models.tagged_item import TaggedItem
from posthog.permissions import get_authenticator_scopes
from posthog.query_creator_access import (
CreatorLeftOrganizationError,
assert_creator_can_run,
describe_owner_unavailable,
owner_unavailable_code,
)
from posthog.rate_limit import (
AlertLLMSimulationBurstThrottle,
AlertLLMSimulationDailyThrottle,
AlertLLMSimulationSustainedThrottle,
AlertTestDeliveryThrottle,
BurstRateThrottle,
SustainedRateThrottle,
)
from posthog.resource_limits import LimitKey, check_count_limit
from posthog.schema_migrations.upgrade_manager import upgrade_insight
from posthog.tasks.alerts.detector import MAX_DETECTOR_BREAKDOWN_VALUES
from posthog.tasks.alerts.schedule_restriction import validate_and_normalize_schedule_restriction
from posthog.tasks.alerts.utils import (
next_check_at_after_schedule_restriction_change,
send_test_alert_email,
trigger_alert_hog_functions,
)
from posthog.utils import relative_date_parse
from products.access_control.backend.facade.user_access_control import UserAccessControlError
from products.alerts.backend.evaluation.contract import AlertExtractionError
from products.alerts.backend.evaluation.detector import simulate_detector_on_insight
from products.alerts.backend.evaluation.validation import (
THRESHOLD_BOUNDS_REQUIRED_MESSAGE,
should_default_check_ongoing_interval,
validate_alert_config,
validate_alert_insight_query,
)
from products.alerts.backend.facade.api import (
LLM_DETECTOR_PAUSED_ERROR_CODE,
LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,
LLMAlertWrite,
LLMDetectorError,
LLMDetectorPausedError,
LLMDetectorUnavailableError,
admit_llm_alert_write,
assign_alert_owner,
is_llm_detector_config,
llm_detector_access_error,
)
from products.alerts.backend.facade.contracts import (
INSIGHT_ALERT_DESTINATION_EVENT_IDS,
INSIGHT_ALERT_DESTINATION_TYPES,
INSIGHT_ALERT_EVENT_IDS,
MovedAlertCheck,
PlatformCannotOwn,
)
from products.alerts.backend.facade.destinations import (
MAX_DESTINATION_IDS_PER_DELETE_REQUEST,
MAX_DESTINATIONS_PER_ALERT,
build_insight_alert_slack_config,
count_active_alert_destinations,
create_alert_destination_hog_functions,
soft_delete_alert_destinations,
validate_destination_data,
)
from products.alerts.backend.facade.evaluation import DelayedEvaluationUnavailable, validate_evaluation_delay
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_fired_checks,
moved_alert_statuses,
write_moved_alert_edit,
)
from products.alerts.backend.insight_alert_state_machine import (
apply_disable,
apply_enable,
apply_platform_state,
apply_snooze,
apply_threshold_change,
apply_unsnooze,
)
from products.alerts.backend.models.alert import (
METRICS_INSIGHT_QUERY_FILTER,
AlertCheck,
AlertConfiguration,
AlertSubscription,
Threshold,
)
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
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
def _validate_interval_entitlement(
*,
calculation_interval: str | AlertCalculationInterval | None,
organization,
) -> None:
if error := AlertConfiguration.interval_entitlement_error(
calculation_interval=calculation_interval,
organization=organization,
):
raise ValidationError({"calculation_interval": [error]})
def _reject_deleted_insight(insight: Insight) -> None:
# The insight lock holds a soft-deleted row too, and the scheduler never runs an alert on
# one, so a save that raced the deletion must not report success.
if insight.deleted:
raise ValidationError({"insight": ["This insight was deleted. Pick another insight."]})
def _require_insight_viewer_access(context: dict[str, Any], insight: Insight) -> None:
# Team scoping alone doesn't gate per-object insight access controls, so require viewer access
# explicitly — alert write/simulate access must not expose a restricted insight's results.
if not context["view"].user_access_control.check_access_level_for_object(insight, "viewer"):
raise ValidationError("Viewer access to this insight is required.")
@extend_schema_field(InsightThreshold) # type: ignore[arg-type]
class ThresholdConfigurationField(serializers.JSONField):
pass
@extend_schema_field(AlertCondition) # type: ignore[arg-type]
class AlertConditionField(serializers.JSONField):
pass
class LLMDetectorUnavailable(APIException):
# The preview makes a live model call. Without this a model outage surfaces as a bare
# 500 on the button, indistinguishable from a bug in the simulation itself.
status_code = status.HTTP_503_SERVICE_UNAVAILABLE
default_detail = "The AI detector could not reach the model. Try the preview again in a moment."
default_code = "llm_detector_unavailable"
def _insight_alert_flag_enabled(context: dict[str, Any], flag: str) -> bool:
# Scope the flag to the alert's organization (via team scope), not the user's current
# organization — otherwise a user in multiple orgs could flip their current org to a
# flag-on org and create an alert in a team where the flag is disabled. get_organization is
# always injected by TeamAndOrgViewSetMixin; access it unconditionally so the org-scoping
# invariant can't silently degrade to an unscoped check.
user = context["request"].user
org = context["get_organization"]()
return bool(
posthoganalytics.feature_enabled(
flag,
str(user.distinct_id),
groups={"organization": str(org.id)},
)
)
MAX_DETECTOR_INSTRUCTIONS_CHARS = 2000
def _as_number(value: Any) -> int | float | None:
"""The value when it is a JSON number; bool is not one."""
return value if isinstance(value, int | float) and not isinstance(value, bool) else None
def _detector_types(detector_config: Any) -> set[str]:
"""Every detector type named in a config, flattening an ensemble's sub-detectors."""
if not isinstance(detector_config, dict):
return set()
# Runs on the raw request body, so a type can be any JSON value. Only strings are
# detector names; anything else is left for schema validation to reject as a 400.
candidates = [detector_config.get("type")]
detectors = detector_config.get("detectors")
for sub in detectors if isinstance(detectors, list) else []:
if isinstance(sub, dict):
candidates.append(sub.get("type"))
return {candidate for candidate in candidates if isinstance(candidate, str) and candidate}
def _enforce_llm_detector_rules(detector_config: Any) -> None:
"""Gate and constrain the AI detector, shared by create/update and simulate.
Runs on the raw config before schema validation, so each rule can explain itself
instead of collapsing into the generic "Invalid detector configuration."
"""
if not isinstance(detector_config, dict) or DetectorType.LLM.value not in _detector_types(detector_config):
return
if detector_config.get("type") != DetectorType.LLM.value:
# Every check of an ensemble scores every sub-detector, so one AI sub-detector
# makes a model call on every check of that alert. Worth having, but not before
# there is a budget model for it.
raise ValidationError("The AI detector cannot be combined with other detectors yet.")
if detector_config.get("preprocessing"):
raise ValidationError(
"The AI detector reads the series as it is, so it cannot use preprocessing. "
"Differencing or smoothing would hide the shape it is meant to judge."
)
instructions = detector_config.get("instructions")
if instructions is not None:
if not isinstance(instructions, str):
raise ValidationError("Instructions for the AI detector must be text.")
if len(instructions) > MAX_DETECTOR_INSTRUCTIONS_CHARS:
raise ValidationError(
f"Instructions for the AI detector must be {MAX_DETECTOR_INSTRUCTIONS_CHARS} characters or fewer."
)
def _enforce_llm_feature_access(context: dict[str, Any], detector_config: Any) -> None:
"""Refuse an AI preview or takeover the person asking cannot use.
Saved alerts go through ``admit_llm_alert_write`` instead, which checks the alert's
creator. A preview has no alert, and a takeover makes the requester the creator, so
both check the requester.
"""
if DetectorType.LLM.value not in _detector_types(detector_config):
return
user = context["request"].user
try:
error = llm_detector_access_error(distinct_id=str(user.distinct_id), organization=context["get_organization"]())
except LLMDetectorUnavailableError as unavailable_error:
raise LLMDetectorUnavailable(str(unavailable_error)) from unavailable_error
if error:
raise ValidationError(error)
def _normalize_llm_detector_config(detector_config: Any) -> Any:
"""Store the author's instructions stripped, and drop them when they are only whitespace."""
if not isinstance(detector_config, dict) or detector_config.get("type") != DetectorType.LLM.value:
return detector_config
instructions = detector_config.get("instructions")
if not isinstance(instructions, str):
return detector_config
stripped = instructions.strip()
return {**detector_config, "instructions": stripped or None}
# Parameter ranges: (min, max, name)
_DETECTOR_PARAM_RANGES: dict[str, tuple[float, float, str]] = {
"threshold": (0.0, 1.0, "Sensitivity threshold"),
"window": (5, 1000, "Window size"),
"n_estimators": (10, 500, "Number of trees"),
"n_neighbors": (1, 50, "Number of neighbors"),
"n_bins": (5, 50, "Number of bins"),
"multiplier": (0.5, 10.0, "IQR multiplier"),
"training_offset_n": (1, 500, "Training offset"),
}
def _validate_detector_params(config: dict) -> None:
"""Validate detector parameter ranges match frontend constraints.
Runs on the raw config before schema validation, so the message can name the field and
its range: the schema carries the same bounds, but its rejection is the generic one. A
value of the wrong type is left for the schema.
"""
for param, (min_val, max_val, label) in _DETECTOR_PARAM_RANGES.items():
val = _as_number(config.get(param))
if val is not None and (val < min_val or val > max_val):
raise ValidationError(f"{label} must be between {min_val} and {max_val}.")
preprocessing = config.get("preprocessing")
if preprocessing and isinstance(preprocessing, dict):
smooth_n = _as_number(preprocessing.get("smooth_n"))
if smooth_n is not None and (smooth_n < 0 or smooth_n > 30):
raise ValidationError("Smoothing window must be between 0 and 30.")
lags_n = _as_number(preprocessing.get("lags_n"))
if lags_n is not None and (lags_n < 0 or lags_n > 10):
raise ValidationError("Lag features must be between 0 and 10.")
def _validate_detector_config(value: Any) -> Any:
"""The detector-config validation shared by the alert and simulate serializers.
Returns the schema-normalized config.
"""
_enforce_llm_detector_rules(value)
value = _normalize_llm_detector_config(value)
if isinstance(value, dict):
sub_detectors = value.get("detectors")
for config in [value, *(sub_detectors if isinstance(sub_detectors, list) else [])]:
if isinstance(config, dict):
_validate_detector_params(config)
try:
validated = DetectorConfig.model_validate(value)
except pydantic.ValidationError:
raise ValidationError("Invalid detector configuration.")
root = validated.root if hasattr(validated, "root") else validated
if getattr(root, "type", None) == "ensemble" and hasattr(root, "detectors") and len(root.detectors) < 2:
raise ValidationError("Ensemble detector requires at least 2 sub-detectors.")
return validated.model_dump() if hasattr(validated, "model_dump") else value
def _admit_llm_alert_write(
context: dict[str, Any],
*,
detector_config: dict[str, Any] | None,
enabled: bool,
calculation_interval: Any,
instance: AlertConfiguration | None,
) -> None:
"""Run the AI detector's write rules and translate a refusal into this endpoint's 400.
Call inside the transaction that saves, holding the row lock for an update: the
admission takes the team's cap lock when the write adds an enabled AI alert.
"""
try:
refusal = admit_llm_alert_write(
LLMAlertWrite(
team_id=context["team_id"],
organization=context["get_organization"](),
# An existing alert keeps its creator, and that is who its checks run as.
principal=instance.created_by if instance is not None else context["request"].user,
detector_config=detector_config,
enabled=enabled,
calculation_interval=calculation_interval,
existing=instance,
)
)
except LLMDetectorUnavailableError as unavailable_error:
raise LLMDetectorUnavailable(str(unavailable_error)) from unavailable_error
if refusal is None:
return
if refusal.field:
raise ValidationError({refusal.field: [refusal.message]})
raise ValidationError(refusal.message)
def _enforce_alert_feature_flags(context: dict[str, Any], insight: Insight) -> None:
# Shared by create/update (AlertSerializer) and simulate (AlertSimulateSerializer), so a
# flag-gated insight kind gets the same rejection on every alerts entry point.
kind = insight.alertable_query_kind
if kind is None:
raise ValidationError("Alerts are not supported for this insight.")
# Gated on the Metrics product flag itself: anyone who can see the product can alert on it.
if kind == NodeKind.METRICS_QUERY and not _insight_alert_flag_enabled(context, "metrics"):
raise ValidationError("Metrics insight alerts are not enabled for your account.")
def _token_lacks_metrics_scope(request) -> bool:
# Session auth (no token scopes) is exempt: those users are gated by team membership and
# insight viewer access instead.
key_scopes = get_authenticator_scopes(request.successful_authenticator)
if key_scopes is None or "*" in key_scopes:
return False
return not any(scope in key_scopes for scope in ("metrics:read", "metrics:write"))
def _require_write_scope_for_charged_simulation(request, detector_config: Any) -> None:
"""An AI simulation makes a real model call, so a read-only token must not start one.
Every other mode of this endpoint only reads: a statistical simulation is a ClickHouse
query. This one spends the organization's model budget, which is a side effect a token
scoped to read alerts and insights was never granted.
"""
if isinstance(detector_config, str):
try:
detector_config = json.loads(detector_config)
except ValueError:
return
if not is_llm_detector_config(detector_config):
return
key_scopes = get_authenticator_scopes(request.successful_authenticator)
# Session auth carries no scopes; it is gated by team membership and access control.
if key_scopes is None or "*" in key_scopes or "alert:write" in key_scopes:
return
raise InsufficientScope(
["alert:write"],
detail="Simulating the AI detector makes a model call, so it needs the 'alert:write' scope. "
"A statistical detector simulates with 'alert:read'.",
)
def _require_metrics_scope_for_programmatic_auth(context: dict[str, Any], insight: Insight) -> None:
# An alert on a metrics insight executes the query as `created_by` and delivers the computed
# value and labels in notifications, so a programmatic token must also carry the metrics data
# scope — otherwise `alert:write` alone becomes a metrics-read oracle bypassing the explicit
# product-scope gate on the query endpoints.
if insight.alertable_query_kind != NodeKind.METRICS_QUERY:
return
if _token_lacks_metrics_scope(context["request"]):
raise InsufficientScope(["metrics:read"])
class AlertConfigUnion(RootModel):
"""Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the
generated frontend types and MCP tool schemas) in sync with every kind alerts support."""
root: Annotated[
TrendsAlertConfig | HogQLAlertConfig | FunnelsAlertConfig | MetricsAlertConfig,
PydanticField(discriminator="type"),
]
@extend_schema_field(AlertConfigUnion) # type: ignore[arg-type]
class AlertConfigField(serializers.JSONField):
pass
@extend_schema_field(DetectorConfig) # type: ignore[arg-type]
class DetectorConfigField(serializers.JSONField):
pass
@extend_schema_field(
{
"oneOf": [{"type": "integer"}, {"type": "string"}],
"description": "Numeric insight ID or saved insight short ID.",
}
)
class TeamScopedInsightReferenceField(TeamScopedPrimaryKeyRelatedField):
"""Resolve an insight by its database ID or its user-facing short ID."""
def to_internal_value(self, data: object) -> Insight:
if isinstance(data, bool) or not isinstance(data, (str, int)):
self.fail("incorrect_type", data_type=type(data).__name__)
insight = resolve_insight_by_id_or_short_id(self.get_queryset(), data)
if insight is not None:
return insight
self.fail("does_not_exist", pk_value=data)
class ThresholdSerializer(serializers.ModelSerializer):
configuration = ThresholdConfigurationField(
help_text="Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage). "
"For threshold-based alerts (no detector_config), at least one of lower or upper must be set.",
)
name = serializers.CharField(
required=False,
allow_blank=True,
max_length=255,
help_text="Optional name for the threshold.",
)
class Meta:
model = Threshold
fields = [
"id",
"created_at",
"name",
"configuration",
]
read_only_fields = [
"id",
"created_at",
]
def validate(self, data):
instance = Threshold(**data)
instance.clean()
return data
def _destination_deliveries(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
# Only Slack names its own channel; the rest repeat a bare type name, so carry the hog
# function id to tell two apart — never the webhook URL, which is the credential.
labelled = []
for row in rows:
label = row.get("target") or "Destination"
target_id = row.get("target_id")
if target_id and row.get("template") != DestinationType.SLACK.value:
label = f"{label} · {target_id[-4:]}"
labelled.append({**row, "display_label": label})
return labelled
class AlertDeliverySerializer(serializers.Serializer):
channel = serializers.CharField(help_text="Delivery channel: 'email' or 'hog_function' (destinations).")
target = serializers.CharField(help_text="Email address, or destination name, that received the notification.")
target_id = serializers.CharField(
required=False, allow_null=True, help_text="Hog function ID, for destination deliveries. Null for email."
)
template = serializers.CharField(
required=False,
allow_null=True,
help_text="Destination template: 'slack', 'discord', 'webhook', or 'teams'. Null for email.",
)
status = serializers.CharField(help_text="Delivery status. Always 'accepted', for a confirmed send.")
at = serializers.DateTimeField(allow_null=True, help_text="When the delivery was recorded.")
display_label = serializers.CharField(
help_text="Ready-to-display description of the delivery, e.g. 'Email: [email protected]' or 'Slack #eng-alerts'."
)
class AlertCheckSerializer(serializers.ModelSerializer):
targets_notified = serializers.SerializerMethodField()
error = serializers.SerializerMethodField(allow_null=True)
investigation_notebook_short_id = serializers.SerializerMethodField(
help_text="Short ID of the Notebook produced by the investigation agent, when the agent ran for this check."
)
deliveries = serializers.SerializerMethodField(
allow_null=True,
help_text="Destinations that accepted this check's notification, one record per destination "
"(channel, target, status, at). Null when no delivery receipt was recorded, which covers "
"checks that notified nobody and checks predating delivery receipts.",
)
class Meta:
model = AlertCheck
fields = [
"id",
"created_at",
"calculated_value",
"state",
"error",
"targets_notified",
"anomaly_scores",
"triggered_points",
"triggered_dates",
"interval",
"triggered_metadata",
"investigation_status",
"investigation_verdict",
"investigation_summary",
"investigation_notebook_short_id",
"notification_sent_at",
"notification_suppressed_by_agent",
"deliveries",
]
read_only_fields = fields
def get_targets_notified(self, instance: AlertCheck) -> bool:
return instance.targets_notified != {}
def get_error(self, instance: AlertCheck) -> dict[str, str] | None:
if not isinstance(instance.error, dict):
return None
message = instance.error.get("message")
if not isinstance(message, str):
return None
# Only reasons written for the alert's owner pass through. Anything else may carry an
# internal detail, so the history shows a generic message instead.
code = instance.error.get("code")
if code in (
"email_unavailable",
"invalid_configuration",
LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,
LLM_DETECTOR_PAUSED_ERROR_CODE,
):
return {"code": code, "message": message}
return {"message": "This alert encountered an error. Check the alert configuration and try again."}
def get_investigation_notebook_short_id(self, instance: AlertCheck) -> str | None:
notebook = instance.investigation_notebook
return notebook.short_id if notebook is not None else None
@extend_schema_field(AlertDeliverySerializer(many=True))
def get_deliveries(self, instance: AlertCheck) -> list[dict[str, Any]] | None:
if not instance.has_delivery_receipts:
return None
notified = instance.targets_notified or {}
accepted_at = instance.notification_sent_at.isoformat() if instance.notification_sent_at else None
emails = [
{
"channel": "email",
"target": email,
"status": "accepted",
"at": accepted_at,
"display_label": f"Email: {email}",
}
for email in notified.get("users") or []
]
return emails + _destination_deliveries(notified.get("destinations") or [])
class AlertSubscriptionSerializer(serializers.ModelSerializer):
# nosemgrep: unscoped-primary-key-related-field — User model is not team-scoped; validate() checks team membership
user = serializers.PrimaryKeyRelatedField(queryset=User.objects.filter(is_active=True), required=True)
class Meta:
model = AlertSubscription
fields = ["id", "user", "alert_configuration"]
read_only_fields = ["id", "alert_configuration"]
def validate(self, data):
user: User = data["user"]
alert_configuration = data["alert_configuration"]
if not user.teams.filter(pk=alert_configuration.team_id).exists():
raise serializers.ValidationError("User does not belong to the same organization as the alert's team.")
return data
@extend_schema_field(
{
"type": "string",
"nullable": True,
"description": "Snooze the alert until this time. Pass a relative date string (e.g. '2h', '1d') or null to unsnooze.",
}
)
class RelativeDateTimeField(serializers.DateTimeField):
def to_internal_value(self, data):
return data
def _owner_unavailable_message(owner: User | None, error: Exception) -> str:
"""The refusal for an enable the owner cannot run, naming the owner and the cause."""
return f"Can't enable this alert. {describe_owner_unavailable(owner, error)}"
class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializer):
evaluation_delay_intervals = serializers.IntegerField(
min_value=0,
max_value=100,
required=False,
help_text="Skip this many completed insight intervals after excluding the ongoing interval (0-100, default 0). "
"Time-series Trends only. A positive delay requires check_ongoing_interval=false. Uses the insight interval, "
"not the check frequency. Allows late data to arrive, but also delays detection of real problems.",
)
created_by = UserBasicSerializer(read_only=True)
checks = AlertCheckSerializer(
many=True,
read_only=True,
help_text="Alert check results. By default returns the last 5. Use checks_date_from and checks_date_to (e.g. '-24h', '-7d') to get checks within a time window, checks_limit to cap how many are returned (default 5, max 500), and checks_offset to skip the newest N checks for pagination (0-based). Newest checks first. Only populated on retrieve.",
)
checks_total = serializers.SerializerMethodField(
read_only=True,
help_text="Total alert checks matching the retrieve filters (date window). Only set on alert retrieve; omitted otherwise.",
)
threshold = ThresholdSerializer(
help_text="Threshold configuration with bounds and type for evaluating the alert.",
)
condition = AlertConditionField(
required=False,
allow_null=True,
help_text="Alert condition type. Determines how the value is evaluated: absolute_value, relative_increase, or relative_decrease.",
)
config = AlertConfigField(
required=False,
allow_null=True,
help_text=(
"Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index "
"(which series to monitor) and check_ongoing_interval (whether to check the current incomplete "
"interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to "
"the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, "
"'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and "
"label_column (names the evaluated row(s) in breach messages, in every evaluation mode). "
"FunnelsAlertConfig (funnel insights): funnel_step (the step to monitor, null for the overall "
"last step), metric ('conversion_from_start' or 'conversion_from_previous'), and "
"check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). "
"Steps funnels support only absolute_value conditions; historical-trend funnels also support "
"relative_increase/relative_decrease (compared against the prior period)."
),
)
detector_config = DetectorConfigField(required=False, allow_null=True)
insight = TeamScopedPrimaryKeyRelatedField(
queryset=Insight.objects.all(),
help_text="Insight ID monitored by this alert. Note: Response returns full InsightBasicSerializer object.",
)
insight_short_id = serializers.CharField(
source="insight.short_id",
read_only=True,
help_text="Short ID of the insight monitored by this alert.",
)
insight_display_name = serializers.SerializerMethodField(
read_only=True,
help_text="Display name of the insight monitored by this alert.",
)
llm_detector_available = serializers.SerializerMethodField(
read_only=True,
allow_null=True,
help_text=(
"Whether this alert can use the AI detector, judged for the person who created it, since scheduled "
"checks run as the creator. Only computed when retrieving a single alert; null elsewhere."
),
)
name = serializers.CharField(
required=False,
allow_blank=True,
max_length=255,
help_text="Human-readable name for the alert.",
)
# nosemgrep: unscoped-primary-key-related-field — User model is not team-scoped; validate_subscribed_users() checks team membership
subscribed_users = serializers.PrimaryKeyRelatedField(
queryset=User.objects.filter(is_active=True),
many=True,
required=True,
allow_empty=True,
help_text="User IDs to subscribe to this alert. Note: Response returns full UserBasicSerializer object.",
)
enabled = serializers.BooleanField(
required=False,
help_text="Whether the alert is actively being evaluated.",
)
calculation_interval = serializers.ChoiceField(
choices=AlertConfiguration.CALCULATION_INTERVAL_CHOICES,
required=False,
help_text="How often the alert is checked: real time (Scale+), every 15 minutes (Boost+), hourly, daily, weekly, or monthly.",
)
schedule_start_time = serializers.CharField(
required=False,
allow_null=True,
help_text="Local time that starts alert checks in HH:MM format. Updating this value recalculates the next check. Set null to remove the custom start time.",
)
snoozed_until = RelativeDateTimeField(
allow_null=True,
required=False,
help_text="Snooze the alert until this time. Pass a relative date string (e.g. '2h', '1d') or null to unsnooze.",
)
skip_weekend = serializers.BooleanField(
required=False,
allow_null=True,
help_text="Skip alert evaluation on weekends (Saturday and Sunday, local to project timezone).",
)
schedule_restriction = ScheduleRestrictionField(
required=False,
allow_null=True,
help_text="Blocked local time windows (HH:MM in the project timezone). Interval is half-open [start, end): "
"start inclusive, end exclusive. Use blocked_windows array of {start, end}. Null disables.",
)
investigation_agent_enabled = serializers.BooleanField(
required=False,
help_text="When enabled, an investigation agent runs on each check where the alert fires, up to three times per firing episode, and writes findings to a Notebook linked from the alert check. An episode is the run of consecutive firing checks since the last check that did not fire. A later investigation of the same episode that reaches a different verdict sends one follow-up notification, unless investigation_inconclusive_action suppresses it. Only effective for detector-based (anomaly) alerts.",
)
investigation_gates_notifications = serializers.BooleanField(
required=False,
help_text="When enabled (and investigation_agent_enabled is on), the first fire of an episode is held until the investigation agent produces a verdict, and that notification is suppressed when the verdict is false_positive (and optionally when inconclusive). Later fires of the same episode notify without waiting. A safety-net task force-fires after a few minutes if the investigation stalls.",
)
investigation_inconclusive_action = serializers.ChoiceField(
choices=[("notify", "Notify"), ("suppress", "Suppress")],
required=False,
help_text="How to handle an 'inconclusive' verdict: whether gated notifications fire and whether the investigation surfaces in the Signals inbox. 'notify' is the safe default — an agent that can't be sure is itself useful signal. False positives never reach the inbox regardless of this setting.",
)
state = serializers.CharField(
read_only=True,
help_text="Current alert state: Firing, Not firing, Errored, or Snoozed.",
)
last_value = serializers.FloatField(
read_only=True,
allow_null=True,
help_text="The last calculated value from the most recent alert check.",
)
def get_checks_total(self, obj: AlertConfiguration) -> int | None:
return getattr(obj, "checks_total", None)
def get_insight_display_name(self, obj: AlertConfiguration) -> str:
return obj.insight.name or obj.insight.derived_name or "Untitled insight"
@extend_schema_field(serializers.BooleanField(allow_null=True))
def get_llm_detector_available(self, obj: AlertConfiguration) -> bool | None:
# One flag evaluation per alert is fine on the alert detail view, and nowhere else: not on
# a list, and not when the alert is nested inside another resource such as a dashboard.
if self.root is not self or getattr(self.context.get("view"), "action", None) != "retrieve":
return None
if obj.created_by is None:
return False
try:
return (
llm_detector_access_error(
distinct_id=str(obj.created_by.distinct_id), organization=self.context["get_organization"]()
)
is None
)
except LLMDetectorUnavailableError:
return None
class Meta:
model = AlertConfiguration
fields = [
"id",
"created_by",
"created_at",
"insight",
"insight_short_id",
"insight_display_name",
"llm_detector_available",
"name",
"subscribed_users",
"threshold",
"condition",
"state",
"enabled",
"last_notified_at",
"last_checked_at",
"schedule_start_time",
"next_check_at",
"checks",
"checks_total",
"config",
"detector_config",
"evaluation_delay_intervals",
"calculation_interval",
"snoozed_until",
"skip_weekend",
"schedule_restriction",
"last_value",
"investigation_agent_enabled",
"investigation_gates_notifications",
"investigation_inconclusive_action",
"search_match_type",
]
read_only_fields = [
"id",
"created_at",
"state",
"last_notified_at",
"last_checked_at",
"next_check_at",
]
def to_representation(self, instance):
# Deferred: the insight API serializer drags the product-analytics query-runner chain;
# keeping it out of module scope lets this module connect its delete receivers at
# AppConfig.ready() without pulling that chain onto startup.
from products.product_analytics.backend.presentation.insight import InsightBasicSerializer # noqa: PLC0415
data = super().to_representation(instance)
data["subscribed_users"] = UserBasicSerializer(instance.subscribed_users.all(), many=True, read_only=True).data
data["insight"] = InsightBasicSerializer(instance.insight).data
if data.get("checks_total") is None:
data.pop("checks_total", None)
return data
def add_threshold(self, threshold_data, validated_data):
threshold_instance = Threshold.objects.create(
**threshold_data,
team_id=self.context["team_id"],
created_by=self.context["request"].user,
insight_id=validated_data["insight"].id,
)
return threshold_instance
@transaction.atomic
def create(self, validated_data: dict) -> AlertConfiguration:
validated_data["team_id"] = self.context["team_id"]
validated_data["created_by"] = self.context["request"].user
team = self.context["get_team"]()
if DetectorType.LLM.value in _detector_types(validated_data.get("detector_config")):
insight = validated_data["insight"]
if not lock_insight_for_evaluation(team_id=team.id, insight_id=insight.id):
raise ValidationError({"insight": ["The insight no longer exists. Refresh the alert."]})
insight.refresh_from_db()
_reject_deleted_insight(insight)
validated_data = self.validate(validated_data)
current_count = AlertConfiguration.objects.filter(team_id=team.id).count()
check_count_limit(
team=team,
key=LimitKey.MAX_ALERTS_PER_TEAM,
current_count=current_count,
user=self.context["request"].user,
)
subscribed_users = validated_data.pop("subscribed_users")
threshold_data = validated_data.pop("threshold", None)
with transaction.atomic():
_admit_llm_alert_write(
self.context,
detector_config=validated_data.get("detector_config"),
enabled=validated_data.get("enabled", True) is True,
calculation_interval=validated_data.get("calculation_interval", AlertCalculationInterval.DAILY),
instance=None,
)
if threshold_data:
threshold_instance = self.add_threshold(threshold_data, validated_data)
validated_data["threshold"] = threshold_instance
instance: AlertConfiguration = super().create(validated_data)
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(
user=user, alert_configuration=instance, created_by=self.context["request"].user
)
instance.report_created(
self.context["request"].user,
analytics_props=get_request_analytics_properties(self.context["request"]),
)
# 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
)
return instance
@transaction.atomic
def update(self, instance, validated_data):
current_insight_id = AlertConfiguration.objects.get(pk=instance.pk).insight_id
target_insight = validated_data.get("insight")
insight_ids = {current_insight_id, target_insight.id if target_insight else current_insight_id}
# Use the evaluation lock order so query edits cannot pass validation during this save.
for insight_id in sorted(insight_ids):
if not lock_insight_for_evaluation(team_id=instance.team_id, insight_id=insight_id):
raise ValidationError({"insight": ["The insight no longer exists. Refresh the alert."]})
instance = AlertConfiguration.objects.select_for_update(no_key=True).get(pk=instance.pk)
if instance.insight_id != current_insight_id:
raise ValidationError({"insight": ["The alert's insight changed. Retry the update."]})
if target_insight:
target_insight.refresh_from_db()
_reject_deleted_insight(target_insight)
# Recheck the combined configuration after concurrent updates have finished.
self.instance = instance
validated_data = self.validate(validated_data)
enabled_changed = "enabled" in validated_data and validated_data["enabled"] != instance.enabled
resulting_enabled = validated_data.get("enabled", instance.enabled) is True
_admit_llm_alert_write(
self.context,
detector_config=validated_data.get("detector_config", instance.detector_config),
enabled=resulting_enabled,
calculation_interval=validated_data.get("calculation_interval", instance.calculation_interval),
instance=instance,
)
enable_now = enabled_changed and validated_data["enabled"]
if enable_now:
apply_enable(instance)
snoozed_until_param = validated_data.pop("snoozed_until", serializers.empty)
snooze_changed = snoozed_until_param is not serializers.empty
snoozed_until = None
if snooze_changed and snoozed_until_param is not None:
snoozed_until = relative_date_parse(
snoozed_until_param, ZoneInfo("UTC"), increase=True, always_truncate=True
)
conditions_or_threshold_changed = False
threshold_data = validated_data.pop("threshold", None)
if threshold_data is not None:
if threshold_data == {}:
instance.threshold = None
conditions_or_threshold_changed = True
elif instance.threshold:
previous_threshold_configuration = instance.threshold.configuration
threshold_instance = instance.threshold
for key, value in threshold_data.items():
setattr(threshold_instance, key, value)
threshold_instance.save()
if previous_threshold_configuration != threshold_instance.configuration:
conditions_or_threshold_changed = True
else:
threshold_instance = self.add_threshold(threshold_data, validated_data)
validated_data["threshold"] = threshold_instance
conditions_or_threshold_changed = True
subscribed_users = validated_data.pop("subscribed_users", None)
if subscribed_users is not None:
AlertSubscription.objects.filter(alert_configuration=instance).exclude(user__in=subscribed_users).delete()
for user in subscribed_users:
# nosemgrep: idor-lookup-without-team (user team membership validated by viewset)
AlertSubscription.objects.get_or_create(
user=user, alert_configuration=instance, defaults={"created_by": self.context["request"].user}
)
evaluation_changed = conditions_or_threshold_changed or any(
validated_data.get(field, getattr(instance, field)) != getattr(instance, field)
for field in ("condition", "config", "skip_weekend", "detector_config", "evaluation_delay_intervals")
)
calculation_interval_changed = (
"calculation_interval" in validated_data
and validated_data["calculation_interval"] != instance.calculation_interval
)
rescheduled = enable_now or evaluation_changed or calculation_interval_changed
if rescheduled:
if evaluation_changed:
apply_threshold_change(instance)
# Keep the due timestamp so the scheduler metric can measure a
# recheck that remains unhandled. Null is reserved for a brand-new
# alert that has never had a scheduling timestamp.
instance.next_check_at = timezone.now()
if snooze_changed:
instance.snoozed_until = snoozed_until
if snoozed_until_param is None:
apply_unsnooze(instance)
else:
apply_snooze(instance)
if not resulting_enabled:
apply_disable(instance)
if snooze_changed:
AlertCheck.objects.create(
alert_configuration=instance,
calculated_value=None,
condition=instance.condition,
targets_notified={},
state=instance.state,
error=None,
)
schedule_restriction_changed = False
schedule_start_time_changed = False
if "schedule_restriction" in validated_data:
new_sr = validated_data["schedule_restriction"]
if new_sr != instance.schedule_restriction:
schedule_restriction_changed = True
if "schedule_start_time" in validated_data:
schedule_start_time_changed = validated_data["schedule_start_time"] != instance.schedule_start_time
instance = super().update(instance, validated_data)
rescheduled = rescheduled or schedule_restriction_changed or schedule_start_time_changed
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,
rescheduled=rescheduled,
)
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 and not instance.platform_owned:
transaction.on_commit(
lambda: follow_insight_alert(team_id=instance.team_id, alert_id=instance.id), robust=True
)
return instance
def validate_schedule_start_time(self, value: str | None) -> str | None:
try:
return validate_and_normalize_schedule_start_time(value)
except ValueError:
raise serializers.ValidationError("Invalid schedule start time.")
def validate_detector_config(self, value):
if value is None:
return value
return _validate_detector_config(value)
def validate_snoozed_until(self, value):
if value is not None and not isinstance(value, str):
raise ValidationError("snoozed_until has to be passed in string format")
return value
def validate_insight(self, value):
if not value:
return value
_require_insight_viewer_access(self.context, value)
_enforce_alert_feature_flags(self.context, value)
return value
def validate_subscribed_users(self, value):
for user in value:
if not user.teams.filter(pk=self.context["team_id"]).exists():
raise ValidationError("User does not belong to the same organization as the alert's team.")
return value
def validate_schedule_restriction(self, value):
try:
return validate_and_normalize_schedule_restriction(value)
except ValueError:
raise serializers.ValidationError("Invalid schedule restriction.")
def validate(self, attrs):
if attrs.get("insight") and attrs["insight"].team.id != self.context["team_id"]:
raise ValidationError({"insight": ["This insight does not belong to your team."]})
condition = attrs.get("condition", self.instance.condition if self.instance else None)
config = attrs.get("config", self.instance.config if self.instance else None)
insight = attrs.get("insight") or (self.instance.insight if self.instance else None)
if insight is None:
raise ValidationError({"insight": ["Insight is required."]})
# Checks run as the owner, so an owner who cannot run them would only get the alert disabled again.
if self.instance is not None and attrs.get("enabled") is True and not self.instance.enabled:
try:
assert_creator_can_run(self.instance.created_by, self.instance.team, insight)
except (CreatorLeftOrganizationError, UserAccessControlError) as error:
raise ValidationError(
{"enabled": [_owner_unavailable_message(self.instance.created_by, error)]},
code=owner_unavailable_code(error),
)
# Enforced from the object-level validate() so it runs on every create and update — including
# a PATCH that omits `insight` (which skips the field-level validator), so an alert can't be
# repointed at a flag-gated insight kind (or a scope-gated one) in an account where the flag
# is off or the token lacks the data scope. The model stays flag-agnostic so existing alerts
# keep working when the flag is off.
_enforce_alert_feature_flags(self.context, insight)
_require_metrics_scope_for_programmatic_auth(self.context, insight)
with upgrade_insight(insight):
query = insight.query
if query is None:
raise ValidationError({"insight": ["Insight has no valid query."]})
threshold_config = None
if "threshold" in attrs and isinstance(attrs["threshold"], dict):
threshold_config = attrs["threshold"].get("configuration")
elif self.instance and self.instance.threshold:
threshold_config = self.instance.threshold.configuration
calculation_interval = attrs.get(
"calculation_interval",
self.instance.calculation_interval if self.instance else AlertCalculationInterval.DAILY,
)
if "detector_config" in attrs:
detector_config = attrs["detector_config"]
elif self.instance is not None:
detector_config = self.instance.detector_config
else:
detector_config = None
require_threshold_bounds = detector_config is None and (
self.instance is None or "threshold" in attrs or "detector_config" in attrs
)
# Mirror the UI's default for cadences finer than the insight interval. Applied before
# validate_alert_config so the validated config is the persisted config.
evaluation_delay = attrs.get(
"evaluation_delay_intervals", self.instance.evaluation_delay_intervals if self.instance else 0
)
if not evaluation_delay and isinstance(config, dict) and config.get("check_ongoing_interval") is None:
if should_default_check_ongoing_interval(
query=query,
config=config,
condition=condition,
threshold_config=threshold_config,
calculation_interval=calculation_interval,
):
config = {**config, "check_ongoing_interval": True}
attrs["config"] = config
request_user = self.context["request"].user
creating_user = request_user if isinstance(request_user, User) else None
try:
validate_evaluation_delay(query, config, evaluation_delay)
validate_alert_insight_query(
query,
team=self.context["get_team"](),
# The alert evaluates as its creator, so an update validates as that user rather
# than as whoever is editing it.
user=self.instance.created_by if self.instance is not None else creating_user,
)
validate_alert_config(
query,
condition,
config,
threshold_config,
calculation_interval,
detector_config=detector_config,
require_threshold_bounds=require_threshold_bounds,
)
except ValueError as e:
if str(e) == THRESHOLD_BOUNDS_REQUIRED_MESSAGE:
raise ValidationError({"threshold": {"configuration": [THRESHOLD_BOUNDS_REQUIRED_MESSAGE]}})
raise ValidationError(str(e))
# The AI detector's own rules (rollout, consent, cadence, cap) run in create/update
# through admit_llm_alert_write, under the locks they need.
organization = self.context["get_organization"]()
_validate_interval_entitlement(
calculation_interval=calculation_interval,
organization=organization,
)
# Investigation agent is supported for detector-based alerts (the agent
# workflow) and for metrics threshold alerts (a synchronous facade
# investigation attached to the firing check) — nothing else.
investigation_enabled = attrs.get(
"investigation_agent_enabled",
self.instance.investigation_agent_enabled if self.instance else False,
)
if investigation_enabled:
detector_config = attrs.get(
"detector_config",
self.instance.detector_config if self.instance else None,
)
if not detector_config and insight.alertable_query_kind != NodeKind.METRICS_QUERY:
raise ValidationError(
{
"investigation_agent_enabled": [
"Investigation agent is only supported for anomaly detection alerts."
]
}
)
# Notification gating only makes sense when the investigation agent is on —
# otherwise there's no verdict to wait for and the safety-net task would
# end up being the only notifier, which defeats the feature.
gates_notifications = attrs.get(
"investigation_gates_notifications",
self.instance.investigation_gates_notifications if self.instance else False,
)
if gates_notifications and not investigation_enabled:
raise ValidationError(
{
"investigation_gates_notifications": [
"Notification gating requires investigation_agent_enabled=true."
]
}
)
# Only a create adds an alert; a takeover is a POST that enables an existing one.
if self.instance is None:
if msg := AlertConfiguration.check_alert_limit(self.context["team_id"], self.context["get_organization"]()):
raise ValidationError({"alert": [msg]})
existing_enabled = self.instance.enabled if self.instance else True
if msg := AlertConfiguration.real_time_alert_validation_error(
team_id=self.context["team_id"],
organization=organization,
calculation_interval=calculation_interval,
enabled=attrs.get("enabled", existing_enabled) is True,
existing=self.instance,
):
posthoganalytics.capture(
distinct_id=str(self.context["request"].user.distinct_id),
event="real time alert limit reached",
properties={
"team_id": self.context["team_id"],
"organization_id": str(organization.id),
},
groups={"organization": str(organization.id)},
)
raise ValidationError({"calculation_interval": [msg]})
return attrs
class AlertSimulateSerializer(serializers.Serializer):
evaluation_delay_intervals = serializers.IntegerField(
min_value=0,
max_value=100,
default=0,
help_text="Skip this many completed insight intervals before simulation, matching live evaluation. "
"Time-series Trends only; a positive delay requires check_ongoing_interval=false.",
)
insight = TeamScopedInsightReferenceField(
queryset=Insight.objects.all(),
help_text="Numeric insight ID or saved insight short ID to simulate the detector on.",
)
detector_config = DetectorConfigField(
required=False,
default=lambda: {
"type": "zscore",
"threshold": 0.95,
"window": 90,
"preprocessing": {"diffs_n": 1},
},
help_text=(
"Detector configuration to simulate. Omit it to use the default daily z-score detector "
"(threshold 0.95, window 90, first-difference preprocessing)."
),
)
# TODO: fold series_index and date_from into a per-kind range on `config` once a second insight
# kind needs a range knob. They stay flat today because date_from is a preview-only range with
# no home in the persisted alert config, and trends is the only kind with a range knob — but the
# duplication (series_index already lives in TrendsAlertConfig) should be removed at that point.
series_index = serializers.IntegerField(
default=0,
help_text="Zero-based index of the series to analyze (trends insights only).",
)
date_from = serializers.CharField(
required=False,
allow_null=True,
default=None,
help_text="Relative date string for how far back to simulate (e.g. '-24h', '-30d', '-4w'). "
"If not provided, uses the detector's minimum required samples. Trends insights only — a SQL "
"query's own rows are the series.",
)
config = AlertConfigField(
required=False,
allow_null=True,
default=None,
help_text="Per-insight-kind alert config. For SQL insights, selects the evaluated column and "
"read direction (last_row/first_row) so the preview matches the alert; ignored for trends.",
)
alert = serializers.UUIDField(
required=False,
allow_null=True,
default=None,
help_text="ID of the saved alert this preview is for. The AI detector reads the points that the "
"alert's earlier AI checks fired on, the same way a live check does. Omit it for a new alert.",
)
def validate_insight(self, value):
_require_insight_viewer_access(self.context, value)
# Same feature gate as create/update: a flag-gated insight kind must get the gated
# rejection here too, not fall through to the unsupported-detector error.
_enforce_alert_feature_flags(self.context, value)
return value
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
with upgrade_insight(attrs["insight"]):
query = attrs["insight"].query
try:
validate_evaluation_delay(query, attrs.get("config"), attrs["evaluation_delay_intervals"])
except ValueError as err:
raise ValidationError({"evaluation_delay_intervals": [str(err)]}) from err
return attrs
def validate_detector_config(self, value):
# Same gate as create/update: previewing a flag-gated detector must be rejected the
# same way saving one is, or the preview becomes the way to use it.
_enforce_llm_feature_access(self.context, value)
return _validate_detector_config(value)
class BreakdownSimulationResultSerializer(serializers.Serializer):
label = serializers.CharField(help_text="Breakdown value label.") # type: ignore[assignment]
data = serializers.ListField(child=serializers.FloatField(), help_text="Data values for each point.") # type: ignore[assignment]
dates = serializers.ListField(child=serializers.CharField(), help_text="Date labels for each point.")
scores = serializers.ListField(
child=serializers.FloatField(allow_null=True),
help_text="Anomaly score for each point.",
)
triggered_indices = serializers.ListField(
child=serializers.IntegerField(), help_text="Indices of points flagged as anomalies."
)
triggered_dates = serializers.ListField(
child=serializers.CharField(), help_text="Dates of points flagged as anomalies."
)
total_points = serializers.IntegerField(help_text="Total number of data points analyzed.")
anomaly_count = serializers.IntegerField(help_text="Number of anomalies detected.")
sub_detector_scores = serializers.ListField(
child=serializers.DictField(),
required=False,
help_text="Per-sub-detector scores for ensemble detectors.",
)
class AlertSimulateResponseSerializer(serializers.Serializer):
evaluation_delay_intervals = serializers.IntegerField(required=False, help_text="Completed intervals skipped.")
evaluated_interval_start = serializers.CharField(required=False, help_text="Start of the latest eligible interval.")
evaluated_interval_end = serializers.CharField(
required=False, help_text="Exclusive end of the latest eligible interval."
)
evaluated_interval_timezone = serializers.CharField(required=False, help_text="Project timezone of the interval.")
data = serializers.ListField(child=serializers.FloatField(), help_text="Data values for each point.") # type: ignore[assignment]
dates = serializers.ListField(child=serializers.CharField(), help_text="Date labels for each point.")
scores = serializers.ListField(
child=serializers.FloatField(allow_null=True),
help_text=(
"Score for each point. Null can mean insufficient data or a valid unscored point. "
"The AI detector has no score, so every point is null in an AI preview."
),
)
triggered_indices = serializers.ListField(
child=serializers.IntegerField(), help_text="Indices of points flagged as anomalies."
)
triggered_dates = serializers.ListField(
child=serializers.CharField(), help_text="Dates of points flagged as anomalies."
)
interval = serializers.CharField(
allow_null=True, help_text="Interval of the trends query (hour, day, week, month)."
)
total_points = serializers.IntegerField(help_text="Total number of data points analyzed.")
anomaly_count = serializers.IntegerField(help_text="Number of anomalies detected.")
sub_detector_scores = serializers.ListField(
child=serializers.DictField(),
required=False,
help_text="Per-sub-detector scores for ensemble detectors. Each entry has 'type' and 'scores' fields.",
)
rationale = serializers.CharField(
required=False,
help_text="AI detector only: the model's reason for its verdict on the latest point.",
)
kind = serializers.CharField(
required=False,
allow_null=True,
help_text="AI detector only: the shape the model saw at the latest point, or 'none'.",
)
breakdown_results = BreakdownSimulationResultSerializer(
many=True,
required=False,
help_text=f"Per-breakdown-value simulation results. Present only when the insight has breakdowns (up to {MAX_DETECTOR_BREAKDOWN_VALUES} values).",
)
class AlertTestDeliveryResponseSerializer(serializers.Serializer):
destination_count = serializers.IntegerField(help_text="Number of active destinations queued for test delivery.")
email_recipient_count = serializers.IntegerField(help_text="Number of subscribed users sent a test email.")
failed_delivery_channels = serializers.ListField(
child=serializers.ChoiceField(choices=("email", "destination")),
help_text="Configured delivery channels that failed to schedule or send.",
)
class AlertCreateDestinationSerializer(serializers.Serializer):
type = serializers.ChoiceField(
choices=INSIGHT_ALERT_DESTINATION_TYPES,
default=DestinationType.SLACK,
help_text="Destination type. Slack is the only type this endpoint creates.",
)
slack_workspace_id = serializers.IntegerField(
help_text="Integration ID of the Slack workspace to post in. List them with the integrations endpoint."
)
slack_channel_id = serializers.CharField(help_text="Slack channel ID to post in, for example C0123456789.")
slack_channel_name = serializers.CharField(
required=False,
allow_blank=True,
help_text="Channel name shown on the destination, for example product-alerts.",
)
def validate(self, attrs: dict) -> dict:
data = cast(AlertDestinationData, attrs)
data["type"] = DestinationType(attrs["type"])
try:
validate_destination_data(data, allowed_destination_types=INSIGHT_ALERT_DESTINATION_TYPES)
except AlertDestinationValidationError as error:
if error.field:
raise ValidationError({error.field: error.message})
raise ValidationError(error.message)
# The runtime refuses another team's integration anyway, so without this the destination
# is created and then silently never posts.
team = self.context["get_team"]()
if not IntegrationManager.slack.oauth.get_many(team.id, [attrs["slack_workspace_id"]]):
raise ValidationError({"slack_workspace_id": "Connect this Slack workspace to PostHog first."})
return attrs
class AlertDestinationResponseSerializer(serializers.Serializer):
hog_function_ids = serializers.ListField(
child=serializers.UUIDField(),
help_text="IDs of the created destination. Pass them to destinations/delete to remove it.",
)
class AlertDeleteDestinationSerializer(serializers.Serializer):
hog_function_ids = serializers.ListField(
child=serializers.UUIDField(),
min_length=1,
max_length=MAX_DESTINATION_IDS_PER_DELETE_REQUEST,
help_text="Destination IDs to delete, as returned when the destination was created.",
)
class AlertListFiltersSerializer(serializers.Serializer):
insight_tag = serializers.CharField(required=False, max_length=255)
has_detector = OptionalBooleanField(required=False)
def _show_platform_status(alerts: list[AlertConfiguration], *, now: datetime) -> None:
"""Shows each alert the platform owns as the platform has it, in place. Its own row stops
moving once the insight stack stops checking it."""
moved = {alert.id: alert for alert in alerts if alert.platform_owned}
if not moved:
return
statuses = moved_alert_statuses(team_id=next(iter(moved.values())).team_id, alert_ids=list(moved), now=now)
for alert_id, moved_status in statuses.items():
alert = moved[alert_id]
if moved_status.runtime is not None:
apply_platform_state(alert, moved_status.runtime.state)
alert.next_check_at = moved_status.runtime.next_check_at
alert.last_notified_at = moved_status.runtime.last_notified_at
if moved_status.last_check is not None:
alert.last_checked_at = moved_status.last_check.checked_at
# Annotated from the alert's own checks, which stop once the shadow ends.
alert.last_value = moved_status.last_check.value # type: ignore[attr-defined]
# How many fired checks of one moved alert the list returns for the chart's dots. The window holds a
# check every 15 minutes for a 15-minute alert, and one alert that keeps firing must not fill the response.
MOVED_ALERT_FIRED_CHECKS_LIMIT: Final = 500
# The notebook model, reached through the check's link so this product does not import another's models.
_NOTEBOOK: Final = cast(type[Any], AlertCheck._meta.get_field("investigation_notebook").related_model)
def _as_alert_check(alert: AlertConfiguration, check: MovedAlertCheck) -> AlertCheck:
# Never saved. It carries what the check serializer shows.
return AlertCheck(
id=check.id,
alert_configuration=alert,
created_at=check.checked_at,
calculated_value=check.value,
condition=alert.condition,
state=check.state,
error=({"code": check.error_code} if check.error_code else {}) | {"message": check.error_message}
if check.error_message
else None,
targets_notified={},
anomaly_scores=list(check.anomaly_scores) or None,
triggered_points=list(check.triggered_points) or None,
triggered_dates=list(check.triggered_dates) or None,
interval=check.interval,
triggered_metadata=check.triggered_metadata,
investigation_status=check.investigation_status,
investigation_verdict=check.investigation_verdict,
investigation_summary=check.investigation_summary,
investigation_notebook=_NOTEBOOK(short_id=check.investigation_notebook_short_id)
if check.investigation_notebook_short_id
else None,
notification_suppressed_by_agent=check.notification_suppressed_by_agent,
)
@extend_schema_view(
list=extend_schema(
parameters=[
OpenApiParameter(
"search",
OpenApiTypes.STR,
location=OpenApiParameter.QUERY,
description=(
"Optional. Fuzzy match against alert `name` using Postgres trigram word similarity "
"(handles typos, transpositions, and prefix-as-you-type). Results are ordered by relevance, "
"then creation time. Capped at 200 characters; longer queries return a 400 error."
),
),
OpenApiParameter(
"created_by",
OpenApiTypes.UUID,
location=OpenApiParameter.QUERY,
description="Optional. Restrict results to alerts created by the user with this UUID.",
),
OpenApiParameter(
"insight_id",
OpenApiTypes.INT,
location=OpenApiParameter.QUERY,
description="Optional. Restrict results to alerts on this insight ID.",
),
OpenApiParameter(
"insight_tag",
OpenApiTypes.STR,
location=OpenApiParameter.QUERY,
description="Optional. Restrict results to alerts whose insight has this tag.",
),
OpenApiParameter(
"has_detector",
OpenApiTypes.BOOL,
location=OpenApiParameter.QUERY,
description="Optional. Restrict results by whether the alert uses anomaly detection.",
),
],
),
)
class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
scope_object = "alert"
queryset = (
AlertConfiguration.objects.select_related("team", "insight", "threshold", "created_by")
.prefetch_related(
"subscribed_users",
Prefetch(
"insight__tagged_items",
queryset=TaggedItem.objects.select_related("tag"),
to_attr="prefetched_tags",
),
)
.order_by("-created_at")
)
serializer_class = AlertSerializer
def check_throttles(self, request) -> None:
# DRF checks permissions first. Reject an unscoped charged request before it
# consumes the team's shared AI preview quota.
if self.action == "simulate" and isinstance(request.data, dict):
_require_write_scope_for_charged_simulation(request, request.data.get("detector_config"))
super().check_throttles(request)
def safely_get_queryset(self, queryset) -> QuerySet:
filters = self.request.query_params
list_filters = AlertListFiltersSerializer(data=filters)
list_filters.is_valid(raise_exception=True)
if "insight" in filters:
queryset = queryset.filter(insight_id=filters["insight"])
insight_id = filters.get("insight_id")
if insight_id is not None:
queryset = queryset.filter(insight_id=insight_id)
insight_tag = list_filters.validated_data.get("insight_tag")
if insight_tag:
queryset = queryset.filter(
insight__tagged_items__tag__name=tagify(insight_tag),
insight__tagged_items__tag__team_id=self.team_id,
)
has_detector = list_filters.validated_data.get("has_detector")
if has_detector is not None:
queryset = queryset.filter(detector_config__isnull=not has_detector)
created_by = filters.get("created_by")
if created_by:
try:
uuid.UUID(created_by)
except ValueError:
raise ValidationError({"created_by": ["Not a valid UUID."]}) from None
queryset = queryset.filter(created_by__uuid=created_by)
search = filters.get("search")
if search:
if len(search) > MAX_SEARCH_LENGTH:
raise serializers.ValidationError(
{"search": f"Search query must be {MAX_SEARCH_LENGTH} characters or fewer."}
)
queryset = self._apply_search(queryset, search)
# Gate on viewer access to the linked insight. Alert read/write access does not imply access
# to the insight's results (carried in AlertCheck.triggered_metadata / calculated_value), and
# "alert" isn't an access-control resource — so without this an alert leaks a restricted
# insight's data via check history, or via a PATCH that omits `insight` (skipping the
# create-time check). Filtering here covers list, retrieve, update, delete, and the embedded
# checks, since get_object() resolves detail routes from this queryset.
viewable_insights = self.user_access_control.filter_queryset_by_access_level(
Insight.objects.filter(team_id=self.team_id)
)
queryset = queryset.filter(insight_id__in=viewable_insights.values("id"))
# Read-side twin of the write-side metrics scope gate: a programmatic token without the
# metrics data scope must not read metric alert results (last_value, check history, breach
# labels) that a session user scheduled. Filtering here covers list, retrieve, update,
# delete, and the embedded checks, since get_object() resolves from this queryset.
# filter-then-exclude-by-id rather than exclude(Q) — NOT over a JSON path is three-valued,
# so a plain exclude also drops rows whose query lacks the key entirely.
if _token_lacks_metrics_scope(self.request):
queryset = queryset.exclude(id__in=queryset.filter(METRICS_INSIGHT_QUERY_FILTER).values("id"))
latest_check = AlertCheck.objects.filter(alert_configuration=OuterRef("pk")).order_by("-created_at")
queryset = queryset.annotate(last_value=Subquery(latest_check.values("calculated_value")[:1]))
return queryset
def filter_queryset(self, queryset: QuerySet) -> QuerySet:
return drop_similar_when_exact_exists(super().filter_queryset(queryset))
@staticmethod
def _apply_search(queryset: QuerySet, search: str) -> QuerySet:
return apply_trigram_search(
queryset,
search,
span_prefix="alert.search",
fields=(NAME_FIELD,),
tiebreakers=("-created_at",),
)
CHECKS_DEFAULT_LIMIT = 5
CHECKS_MAX_LIMIT = 500
@extend_schema(
parameters=[
OpenApiParameter(
name="checks_date_from",
type=str,
required=False,
description="Relative date string for the start of the check history window (e.g. '-24h', '-7d', '-14d'). Returns checks created after this time. Max retention is 14 days.",
),
OpenApiParameter(
name="checks_date_to",
type=str,
required=False,
description="Relative date string for the end of the check history window (e.g. '-1h', '-1d'). Defaults to now if not specified.",
),
OpenApiParameter(
name="checks_limit",
type=int,
required=False,
description="Maximum number of check results to return (default 5, max 500). Applied after date filtering.",
),
OpenApiParameter(
name="checks_offset",
type=int,
required=False,
description="Number of newest checks to skip (0-based). Use with checks_limit for pagination. Default 0.",
),
],
)
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
checks_qs = instance.alertcheck_set.select_related("investigation_notebook").order_by("-created_at")
checks_date_from = request.query_params.get("checks_date_from")
checks_since = relative_date_parse(checks_date_from, ZoneInfo("UTC")) if checks_date_from else None
if checks_since is not None:
checks_qs = checks_qs.filter(created_at__gte=checks_since)
checks_date_to = request.query_params.get("checks_date_to")
checks_until = relative_date_parse(checks_date_to, ZoneInfo("UTC")) if checks_date_to else None
if checks_until is not None:
checks_qs = checks_qs.filter(created_at__lte=checks_until)
has_date_filter = checks_date_from or checks_date_to
raw_limit = request.query_params.get("checks_limit")
if raw_limit is not None:
try:
limit = max(1, min(int(raw_limit), self.CHECKS_MAX_LIMIT))
except (ValueError, TypeError):
limit = self.CHECKS_DEFAULT_LIMIT
else:
limit = self.CHECKS_MAX_LIMIT if has_date_filter else self.CHECKS_DEFAULT_LIMIT
raw_offset = request.query_params.get("checks_offset")
if raw_offset is not None:
try:
offset = max(0, int(raw_offset))
except (ValueError, TypeError):
offset = 0
else:
offset = 0
_show_platform_status([instance], now=timezone.now())
platform_page = (
moved_alert_check_page(
team_id=instance.team_id,
alert_id=instance.id,
since=checks_since,
until=checks_until,
limit=limit,
offset=offset,
)
if instance.platform_owned
else None
)
if platform_page is not None:
instance.checks_total = platform_page.total
instance.checks = [_as_alert_check(instance, check) for check in platform_page.checks]
else:
checks_total = checks_qs.count()
instance.checks_total = checks_total
offset = min(offset, checks_total)
instance.checks = checks_qs[offset : offset + limit]
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())
# Paginate first, then prefetch checks only for the page
page = self.paginate_queryset(queryset)
alerts = list(page) if page is not None else list(queryset)
_show_platform_status(alerts, now=timezone.now())
# Prefetch firing checks for anomaly point display on chart.
if alerts:
alert_ids = [a.id for a in alerts]
moved_at = {alert.id: at for alert in alerts if (at := alert.platform_owned_since) is not None}
firing_checks = (
AlertCheck.objects.filter(
alert_configuration_id__in=alert_ids,
triggered_points__isnull=False,
)
.exclude(triggered_points=[])
# A moved alert's own checks after the move are the shadow's, so the platform's replace them.
.exclude(
reduce(
or_,
(Q(alert_configuration_id=alert_id, created_at__gte=at) for alert_id, at in moved_at.items()),
Q(pk__in=[]),
)
)
.select_related("investigation_notebook")
.order_by("-created_at")
)
moved_checks = moved_alert_fired_checks(
team_id=self.team_id,
moved_at=moved_at,
not_before=timezone.now() - AlertCheck.RETENTION,
limit=MOVED_ALERT_FIRED_CHECKS_LIMIT,
)
alerts_by_id = {alert.id: alert for alert in alerts}
checks_by_alert: dict[str, list] = {str(a.id): [] for a in alerts}
for alert_id, checks in moved_checks.items():
checks_by_alert[str(alert_id)] = [_as_alert_check(alerts_by_id[alert_id], check) for check in checks]
for check in firing_checks:
checks_by_alert.setdefault(str(check.alert_configuration_id), []).append(check)
for alert in alerts:
alert.checks = checks_by_alert.get(str(alert.id), [])
if page is not None:
serializer = self.get_serializer(alerts, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(alerts, many=True)
return Response(serializer.data)
@extend_schema(
request=None,
responses={200: AlertSerializer},
description=(
"Make the requesting user the owner of this alert and enable it. Checks run with the owner's "
"access, so this is how an alert continues after its owner left."
),
)
@action(detail=True, methods=["POST"], required_scopes=["alert:write"])
def take_ownership(self, request, *args, **kwargs):
alert = self.get_object()
user = cast(User, request.user)
try:
assert_creator_can_run(user, alert.team, alert.insight)
except (CreatorLeftOrganizationError, UserAccessControlError):
raise ValidationError("Can't take ownership: you don't have access to this insight.") from None
# The scheduled checks run as the owner, so an AI alert needs the requester on the rollout.
# An already enabled alert does not pass through the admission below, so it is checked here.
_enforce_llm_feature_access(self.get_serializer_context(), alert.detector_config)
# One transaction, so a refused enable leaves the owner as it was. The enable below reloads
# the row, so the owner is saved first.
with transaction.atomic():
# Same lock order as update(): insight, then alert row. The owner write below locks the row.
if not lock_insight_for_evaluation(team_id=alert.team_id, insight_id=alert.insight_id):
raise ValidationError({"insight": ["The insight no longer exists. Refresh the alert."]})
assign_alert_owner(
team_id=alert.team_id, alert_id=alert.id, user=user, was_impersonated=get_was_impersonated()
)
# The enable below saves this instance, so it must carry the new owner.
alert.refresh_from_db(fields=["created_by"])
# The enable runs the usual update path, so the insight query is validated as the new owner.
serializer = self.get_serializer(alert, data={"enabled": True}, partial=True)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(self.get_serializer(serializer.instance).data)
@extend_schema(
request=None,
responses={202: AlertTestDeliveryResponseSerializer},
description="Send a synthetic test notification to subscribed users and every active destination on this alert.",
)
# nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients
@action(
detail=True,
methods=["POST"],
url_path="test-delivery",
required_scopes=["alert:write"],
throttle_classes=[AlertTestDeliveryThrottle],
)
def test_delivery(self, request, *args, **kwargs):
alert = self.get_object()
destination_count = count_active_alert_destinations(
team_id=alert.team_id,
alert_id=str(alert.id),
allowed_event_ids=INSIGHT_ALERT_EVENT_IDS,
)
email_targets = alert.get_subscribed_users_emails()
if destination_count == 0 and not email_targets:
return Response(
{"detail": "Add an email recipient or active destination before sending a test."},
status=status.HTTP_409_CONFLICT,
)
failed_delivery_channels: list[str] = []
successful_email_count = 0
successful_destination_count = 0
email_delivery_unavailable = bool(email_targets) and not is_email_available()
if email_targets:
try:
if send_test_alert_email(alert, recipients=email_targets, idempotency_key=str(uuid.uuid4())):
successful_email_count = len(email_targets)
else:
failed_delivery_channels.append("email")
except Exception as error:
capture_exception(
error,
additional_properties={"alert_id": str(alert.id), "feature": "alerts", "channel": "email"},
)
failed_delivery_channels.append("email")
if destination_count and trigger_alert_hog_functions(
alert,
{
"breaches": "Test alert from PostHog. No action is needed.",
"is_test": True,
"alert_name": f"[TEST] {alert.name}",
},
):
successful_destination_count = destination_count
elif destination_count:
failed_delivery_channels.append("destination")
if successful_email_count == 0 and successful_destination_count == 0:
detail = (
"Email delivery is unavailable for this instance. Configure email settings before trying again."
if email_delivery_unavailable
else "Unable to start the test delivery. Check the configured channels and try again."
)
return Response(
{"detail": detail},
status=status.HTTP_503_SERVICE_UNAVAILABLE,
)
posthoganalytics.capture(
distinct_id=str(request.user.distinct_id),
event="insight alert test delivery scheduled",
properties={
**get_request_analytics_properties(request),
"alert_id": str(alert.id),
"destination_count": successful_destination_count,
"email_recipient_count": successful_email_count,
"failed_delivery_channels": failed_delivery_channels,
"team_id": alert.team_id,
},
)
return Response(
{
"destination_count": successful_destination_count,
"email_recipient_count": successful_email_count,
"failed_delivery_channels": failed_delivery_channels,
},
status=status.HTTP_202_ACCEPTED,
)
@extend_schema(
request=AlertCreateDestinationSerializer,
responses={201: AlertDestinationResponseSerializer},
description=(
"Send this alert to a Slack channel as well as by email. The workspace must already be "
"connected to the project. The returned IDs identify the destination."
),
)
@action(detail=True, methods=["POST"], url_path="destinations", required_scopes=["alert:write"])
def create_destination(self, request, *args, **kwargs):
alert = self.get_object()
serializer = AlertCreateDestinationSerializer(data=request.data, context=self.get_serializer_context())
serializer.is_valid(raise_exception=True)
data = cast(AlertDestinationData, serializer.validated_data)
existing = count_active_alert_destinations(
team_id=self.team_id, alert_id=str(alert.id), allowed_event_ids=INSIGHT_ALERT_EVENT_IDS
)
if existing >= MAX_DESTINATIONS_PER_ALERT:
raise ValidationError(
f"This alert already has {MAX_DESTINATIONS_PER_ALERT} destinations. Remove one to add another."
)
try:
hog_function_ids = create_alert_destination_hog_functions(
[build_insight_alert_slack_config(alert_id=str(alert.id), alert_name=alert.name, data=data)],
team_id=alert.team_id,
created_by_id=request.user.id,
alert_id=str(alert.id),
allowed_event_ids=INSIGHT_ALERT_EVENT_IDS,
)
except AlertDestinationValidationError as error:
raise as_drf_validation_error(error)
posthoganalytics.capture(
distinct_id=str(request.user.distinct_id),
event="insight alert destination created",
properties={
**get_request_analytics_properties(request),
"alert_id": str(alert.id),
"team_id": alert.team_id,
"type": data["type"],
},
)
response = AlertDestinationResponseSerializer({"hog_function_ids": list(hog_function_ids)})
return Response(response.data, status=status.HTTP_201_CREATED)
@extend_schema(
request=AlertDeleteDestinationSerializer,
responses={204: None},
description="Stop sending this alert to a destination. The alert keeps its email recipients.",
)
@action(detail=True, methods=["POST"], url_path="destinations/delete", required_scopes=["alert:write"])
def delete_destination(self, request, *args, **kwargs):
alert = self.get_object()
serializer = AlertDeleteDestinationSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
hog_function_ids = serializer.validated_data["hog_function_ids"]
try:
soft_delete_alert_destinations(
team_id=self.team_id,
alert_id=str(alert.id),
allowed_event_ids=INSIGHT_ALERT_DESTINATION_EVENT_IDS,
hog_function_ids=hog_function_ids,
)
except AlertDestinationValidationError as error:
raise as_drf_validation_error(error)
posthoganalytics.capture(
distinct_id=str(request.user.distinct_id),
event="insight alert destination deleted",
properties={
**get_request_analytics_properties(request),
"alert_id": str(alert.id),
"count": len(hog_function_ids),
"team_id": alert.team_id,
},
)
return Response(status=status.HTTP_204_NO_CONTENT)
@extend_schema(
request=AlertSimulateSerializer,
responses={
200: AlertSimulateResponseSerializer,
503: OpenApiResponse(description="The AI detector could not reach the model."),
},
description=(
"Simulate a detector on an insight's historical data. No AlertCheck records are created. "
"The AI detector makes a real model call, so that mode needs the 'alert:write' scope."
),
)
# Returns an insight's computed result series, so it requires insight read in addition to
# alert read — an alert-scoped token must not read insight/query data it isn't scoped for.
# (Object-level insight viewer access is enforced separately in AlertSimulateSerializer.)
# An llm detector_config needs alert:write on top of these; see check_throttles.
@action(
detail=False,
methods=["POST"],
url_path="simulate",
required_scopes=["alert:read", "insight:read"],
# Action-level throttles replace the global ones, so the defaults are restated here:
# a statistical simulation is still a ClickHouse query per call.
throttle_classes=[
BurstRateThrottle,
SustainedRateThrottle,
AlertLLMSimulationBurstThrottle,
AlertLLMSimulationSustainedThrottle,
AlertLLMSimulationDailyThrottle,
],
)
def simulate(self, request, *args, **kwargs):
serializer = AlertSimulateSerializer(data=request.data, context=self.get_serializer_context())
serializer.is_valid(raise_exception=True)
insight = serializer.validated_data["insight"]
detector_config = serializer.validated_data["detector_config"]
series_index = serializer.validated_data["series_index"]
date_from = serializer.validated_data.get("date_from")
config = serializer.validated_data.get("config")
alert_id = serializer.validated_data.get("alert")
if alert_id is not None and not AlertConfiguration.objects.filter(team_id=self.team_id, id=alert_id).exists():
raise ValidationError({"alert": ["Alert not found."]})
try:
result = simulate_detector_on_insight(
insight=insight,
team=self.team,
detector_config=detector_config,
series_index=series_index,
date_from=date_from,
user=cast(User, request.user),
config=config,
is_agent_billable=not is_impersonated(request),
evaluation_delay_intervals=serializer.validated_data["evaluation_delay_intervals"],
alert_id=alert_id,
)
except (ValueError, IndexError, AlertExtractionError, DelayedEvaluationUnavailable) as e:
raise ValidationError(str(e))
except LLMDetectorPausedError as e:
# A 503 tells the user to try again in a moment, which cannot help until access or credits return.
raise ValidationError(str(e))
except LLMDetectorError as e:
capture_exception(e)
raise LLMDetectorUnavailable()
except RuntimeError:
raise ValidationError("Simulation failed: unable to compute results for this insight.")
response_serializer = AlertSimulateResponseSerializer(result)
return Response(response_serializer.data)
class ThresholdWithAlertSerializer(ThresholdSerializer):
alerts = AlertSerializer(many=True, read_only=True, source="alertconfiguration_set")
class Meta(ThresholdSerializer.Meta):
fields = [*ThresholdSerializer.Meta.fields, "alerts"]
read_only_fields = [*ThresholdSerializer.Meta.read_only_fields, "alerts"]
class ThresholdViewSet(TeamAndOrgViewSetMixin, viewsets.ReadOnlyModelViewSet):
scope_object = "alert"
queryset = Threshold.objects.all()
serializer_class = ThresholdWithAlertSerializer
def safely_get_queryset(self, queryset) -> QuerySet:
# Thresholds embed full alerts (including check values), so they get the same read-side
# metrics scope gate as the alerts endpoints. Same null-safe filter-then-exclude shape.
if _token_lacks_metrics_scope(self.request):
queryset = queryset.exclude(id__in=queryset.filter(METRICS_INSIGHT_QUERY_FILTER).values("id"))
return queryset