:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(metrics): add the metrics alert source config to the alerts platform (#125046)
Jimmy Zhu60660f9c126e
diff --git a/.agents/skills/adding-product-alerting/references/adopting-platform-alerting.md b/.agents/skills/adding-product-alerting/references/adopting-platform-alerting.mdindex 62529a8b38b6..b4edf62cefc7 100644--- a/.agents/skills/adding-product-alerting/references/adopting-platform-alerting.md+++ b/.agents/skills/adding-product-alerting/references/adopting-platform-alerting.md@@ -16,6 +16,13 @@ Write down the product-specific inputs before coding:Do not add a new `AlertPolicy` option merely because the product might need it. First confirm an existing policy cannot express the behavior and that the difference is intentional.+A new source kind on the alerts platform opens behind its own feature flag.+Set `rollout_flag` on its `SourceConfigSpec`, and create a boolean PostHog feature flag with that key, such as `platform-alerts-source-metrics`.+Target the `project` group by its `id` property, starting with project 2.+Creating an alert of the kind then needs both `platform-alerts` and that flag, so the kind opens on its own schedule while the other kinds stay available to every project with `platform-alerts`.+The flag gates only creation: alerts that already exist keep evaluating.+Once the kind is generally available, remove `rollout_flag` from the spec and delete the flag.+## 2. Add product persistence and isolationThe product owns its alert configuration and check-history models.diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.pyindex ecc1a020b0df..ce0b92c35e4d 100644--- a/products/alerts_platform/backend/facade/contracts.py+++ b/products/alerts_platform/backend/facade/contracts.py@@ -1107,6 +1107,10 @@ class SourceConfigSpec:incident_event_ids: Mapping[str, str] | None = Nonealert_url: Callable[[int, UUID], str] | None = Nonenative: NativeAlertLifecycle | None = None+ # A PostHog feature flag a project needs, beside `platform-alerts`, to create alerts of this kind.+ # A new kind names its own flag, so it opens on its own schedule while the others stay generally+ # available.+ rollout_flag: str | None = Nonedef __post_init__(self) -> None:# The source-row hooks write a row a native kind does not have.diff --git a/products/alerts_platform/backend/presentation/views/platform_alert.py b/products/alerts_platform/backend/presentation/views/platform_alert.pyindex a980a00d7ac2..dc557d3a3c90 100644--- a/products/alerts_platform/backend/presentation/views/platform_alert.py+++ b/products/alerts_platform/backend/presentation/views/platform_alert.py@@ -19,9 +19,12 @@ from posthog.event_usage import report_user_actionfrom posthog.exceptions import Conflictfrom posthog.models import Team, Userfrom posthog.permissions import (+ FEATURE_FLAG_REQUIRED_ERROR_CODE,PostHogFeatureFlagPermission,+ get_authenticator_client,get_authenticator_scoped_team_ids,get_authenticator_scopes,+ posthog_feature_flag_enabled,)from posthog.scopes import APIScopeObject, scopes_not_covered@@ -553,6 +556,7 @@ class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.Generic# rather than through `required_scopes`.if source_kind not in self._source_kinds_with("editor", "write"):raise PermissionDenied(f"You cannot create {source_kind} alerts.")+ self._check_rollout_flag(SourceKind(source_kind))serializer = create_serializer(data=request.data)serializer.is_valid(raise_exception=True)@@ -575,6 +579,22 @@ class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.Generictransaction.on_commit(lambda: self._track("created", created), robust=True)return Response(PlatformAlertConfigurationSerializer(created).data, status=status.HTTP_201_CREATED)+ def _check_rollout_flag(self, source_kind: SourceKind) -> None:+ spec = editable_source_configs().get(source_kind)+ if spec is None or spec.rollout_flag is None:+ return+ if not posthog_feature_flag_enabled(+ spec.rollout_flag,+ str(cast(User, self.request.user).distinct_id),+ organization_id=self.team.organization_id,+ team_id=self.team.id,+ caller_properties=get_authenticator_client(getattr(self.request, "successful_authenticator", None)),+ ):+ raise PermissionDenied(+ f"{source_kind.value.capitalize()} alerts are not available for this project yet.",+ code=FEATURE_FLAG_REQUIRED_ERROR_CODE,+ )+def _track(self, action: Literal["created", "deleted"], configuration: PlatformAlertConfigurationView) -> None:report_user_action(cast(User, self.request.user),diff --git a/products/alerts_platform/frontend/generated/api.schemas.ts b/products/alerts_platform/frontend/generated/api.schemas.tsindex 5c17386c975d..768f5dff8999 100644--- a/products/alerts_platform/frontend/generated/api.schemas.ts+++ b/products/alerts_platform/frontend/generated/api.schemas.ts@@ -768,6 +768,113 @@ export interface LogsPlatformAlertConfigurationCreateApi {annotations?: LogsPlatformAlertConfigurationCreateApiAnnotations}+/**+ * Product whose data the alert evaluates. It cannot change after the create.+ */+export type MetricsPlatformAlertConfigurationCreateApiSourceKind =+ (typeof MetricsPlatformAlertConfigurationCreateApiSourceKind)[keyof typeof MetricsPlatformAlertConfigurationCreateApiSourceKind]++export const MetricsPlatformAlertConfigurationCreateApiSourceKind = {+ Metrics: 'metrics',+} as const++export type MetricsPlatformAlertConditionKindEnumApi =+ (typeof MetricsPlatformAlertConditionKindEnumApi)[keyof typeof MetricsPlatformAlertConditionKindEnumApi]++export const MetricsPlatformAlertConditionKindEnumApi = {+ Threshold: 'threshold',+ Present: 'present',+} as const++/**+ * How a series' value compares with `threshold`. Required for a threshold.+ */+export type MetricsPlatformAlertConditionApiOperator =+ | (typeof MetricsPlatformAlertConditionApiOperator)[keyof typeof MetricsPlatformAlertConditionApiOperator]+ | null++export const MetricsPlatformAlertConditionApiOperator = {+ Gt: 'gt',+ Gte: 'gte',+ Lt: 'lt',+ Lte: 'lte',+ Eq: 'eq',+ Ne: 'ne',+} as const++export interface MetricsPlatformAlertConditionApi {+ /** threshold compares each series' latest value with `threshold`. present fires for every series the query returns, for a query that already filters to the series in breach. */+ kind?: MetricsPlatformAlertConditionKindEnumApi+ /** How a series' value compares with `threshold`. Required for a threshold. */+ operator?: MetricsPlatformAlertConditionApiOperator+ /** The value a series is compared with. Required for a threshold. */+ threshold?: number | null+}++export interface MetricsPlatformAlertConfigApi {+ /**+ * A PromQL expression over this project's metrics. Each series it returns is one group. For a threshold condition, leave the comparison out of the expression.+ * @minLength 1+ * @maxLength 10000+ */+ query: string+ /** When a series is in breach. */+ condition: MetricsPlatformAlertConditionApi+}++/**+ * Labels that say who owns the alert and how urgent it is, such as {"team": "checkout", "severity": "critical"}. Names use letters, digits and underscores. alertname and names that start with posthog_ are reserved. Values cannot use templates.+ */+export type MetricsPlatformAlertConfigurationCreateApiLabels = { [key: string]: string }++/**+ * Context for whoever responds, such as {"runbook_url": "https://..."}. Values can use {{ $labels.<name> }} for a grouping key or label of the alert, and {{ $value }}. An annotation whose name ends in _url must start with https://.+ */+export type MetricsPlatformAlertConfigurationCreateApiAnnotations = { [key: string]: string }++/**+ * The settings of a new alert. Every one but source_config has a default, which is stored.+ */+export interface MetricsPlatformAlertConfigurationCreateApi {+ /** Product whose data the alert evaluates. It cannot change after the create. */+ source_kind: MetricsPlatformAlertConfigurationCreateApiSourceKind+ /**+ * Human-readable name of the alert. Defaults to 'Untitled alert'.+ * @maxLength 255+ */+ name?: string+ /** Whether the alert is evaluated on schedule. Defaults to true. */+ enabled?: boolean+ /** Settings for a metrics alert. The bound the alert is evaluated against is under condition. */+ source_config: MetricsPlatformAlertConfigApi+ /** How the alert splits its results into instances. Defaults to mode single. */+ grouping?: GroupingApi+ /** Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. Defaults to null. */+ schedule_restriction?: AlertScheduleRestrictionApi | null+ /**+ * Number of recent checks considered when deciding to fire. Defaults to 1.+ * @minimum 1+ * @maximum 10+ */+ evaluation_periods?: number+ /**+ * Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods. Defaults to 1.+ * @minimum 1+ * @maximum 10+ */+ datapoints_to_alarm?: number+ /**+ * Minimum minutes between notifications for the same alert. Defaults to 0.+ * @minimum 0+ * @maximum 2147483647+ */+ cooldown_minutes?: number+ /** Labels that say who owns the alert and how urgent it is, such as {"team": "checkout", "severity": "critical"}. Names use letters, digits and underscores. alertname and names that start with posthog_ are reserved. Values cannot use templates. */+ labels?: MetricsPlatformAlertConfigurationCreateApiLabels+ /** Context for whoever responds, such as {"runbook_url": "https://..."}. Values can use {{ $labels.<name> }} for a grouping key or label of the alert, and {{ $value }}. An annotation whose name ends in _url must start with https://. */+ annotations?: MetricsPlatformAlertConfigurationCreateApiAnnotations+}+/*** Product whose data the alert evaluates. It cannot change after the create.*/@@ -928,6 +1035,7 @@ export interface WarehouseSourcePlatformAlertConfigurationCreateApi {export type PlatformAlertConfigurationCreateApi =| LogsPlatformAlertConfigurationCreateApi+ | MetricsPlatformAlertConfigurationCreateApi| WarehouseDestinationPlatformAlertConfigurationCreateApi| WarehouseSourcePlatformAlertConfigurationCreateApi@@ -1110,6 +1218,69 @@ export interface LogsPlatformAlertConfigurationEditApi {annotations?: LogsPlatformAlertConfigurationEditApiAnnotations}+/**+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.+ */+export type MetricsPlatformAlertConfigurationEditApiSourceKind =+ (typeof MetricsPlatformAlertConfigurationEditApiSourceKind)[keyof typeof MetricsPlatformAlertConfigurationEditApiSourceKind]++export const MetricsPlatformAlertConfigurationEditApiSourceKind = {+ Metrics: 'metrics',+} as const++/**+ * Labels that say who owns the alert and how urgent it is, such as {"team": "checkout", "severity": "critical"}. Names use letters, digits and underscores. alertname and names that start with posthog_ are reserved. Values cannot use templates.+ */+export type MetricsPlatformAlertConfigurationEditApiLabels = { [key: string]: string }++/**+ * Context for whoever responds, such as {"runbook_url": "https://..."}. Values can use {{ $labels.<name> }} for a grouping key or label of the alert, and {{ $value }}. An annotation whose name ends in _url must start with https://.+ */+export type MetricsPlatformAlertConfigurationEditApiAnnotations = { [key: string]: string }++/**+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.+ */+export interface MetricsPlatformAlertConfigurationEditApi {+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */+ source_kind: MetricsPlatformAlertConfigurationEditApiSourceKind+ /**+ * Human-readable name of the alert.+ * @maxLength 255+ */+ name: string+ /** Whether the alert is evaluated on schedule. */+ enabled: boolean+ /** Settings for a metrics alert. The bound the alert is evaluated against is under condition. */+ source_config: MetricsPlatformAlertConfigApi+ /** 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+ /** Labels that say who owns the alert and how urgent it is, such as {"team": "checkout", "severity": "critical"}. Names use letters, digits and underscores. alertname and names that start with posthog_ are reserved. Values cannot use templates. */+ labels?: MetricsPlatformAlertConfigurationEditApiLabels+ /** Context for whoever responds, such as {"runbook_url": "https://..."}. Values can use {{ $labels.<name> }} for a grouping key or label of the alert, and {{ $value }}. An annotation whose name ends in _url must start with https://. */+ annotations?: MetricsPlatformAlertConfigurationEditApiAnnotations+}+/*** Product whose data the alert evaluates. It cannot change, so it must match the stored value.*/@@ -1239,6 +1410,7 @@ export interface WarehouseSourcePlatformAlertConfigurationEditApi {export type PlatformAlertConfigurationEditApi =| InsightPlatformAlertConfigurationEditApi| LogsPlatformAlertConfigurationEditApi+ | MetricsPlatformAlertConfigurationEditApi| WarehouseDestinationPlatformAlertConfigurationEditApi| WarehouseSourcePlatformAlertConfigurationEditApi@@ -1368,6 +1540,69 @@ export interface PatchedLogsPlatformAlertConfigurationEditApi {annotations?: PatchedLogsPlatformAlertConfigurationEditApiAnnotations}+/**+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.+ */+export type PatchedMetricsPlatformAlertConfigurationEditApiSourceKind =+ (typeof PatchedMetricsPlatformAlertConfigurationEditApiSourceKind)[keyof typeof PatchedMetricsPlatformAlertConfigurationEditApiSourceKind]++export const PatchedMetricsPlatformAlertConfigurationEditApiSourceKind = {+ Metrics: 'metrics',+} as const++/**+ * Labels that say who owns the alert and how urgent it is, such as {"team": "checkout", "severity": "critical"}. Names use letters, digits and underscores. alertname and names that start with posthog_ are reserved. Values cannot use templates.+ */+export type PatchedMetricsPlatformAlertConfigurationEditApiLabels = { [key: string]: string }++/**+ * Context for whoever responds, such as {"runbook_url": "https://..."}. Values can use {{ $labels.<name> }} for a grouping key or label of the alert, and {{ $value }}. An annotation whose name ends in _url must start with https://.+ */+export type PatchedMetricsPlatformAlertConfigurationEditApiAnnotations = { [key: string]: string }++/**+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.+ */+export interface PatchedMetricsPlatformAlertConfigurationEditApi {+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */+ source_kind: PatchedMetricsPlatformAlertConfigurationEditApiSourceKind+ /**+ * Human-readable name of the alert.+ * @maxLength 255+ */+ name?: string+ /** Whether the alert is evaluated on schedule. */+ enabled?: boolean+ /** Settings for a metrics alert. The bound the alert is evaluated against is under condition. */+ source_config?: MetricsPlatformAlertConfigApi+ /** 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+ /** Labels that say who owns the alert and how urgent it is, such as {"team": "checkout", "severity": "critical"}. Names use letters, digits and underscores. alertname and names that start with posthog_ are reserved. Values cannot use templates. */+ labels?: PatchedMetricsPlatformAlertConfigurationEditApiLabels+ /** Context for whoever responds, such as {"runbook_url": "https://..."}. Values can use {{ $labels.<name> }} for a grouping key or label of the alert, and {{ $value }}. An annotation whose name ends in _url must start with https://. */+ annotations?: PatchedMetricsPlatformAlertConfigurationEditApiAnnotations+}+/*** Product whose data the alert evaluates. It cannot change, so it must match the stored value.*/@@ -1497,6 +1732,7 @@ export interface PatchedWarehouseSourcePlatformAlertConfigurationEditApi {export type PatchedPlatformAlertConfigurationEditApi =| PatchedInsightPlatformAlertConfigurationEditApi| PatchedLogsPlatformAlertConfigurationEditApi+ | PatchedMetricsPlatformAlertConfigurationEditApi| PatchedWarehouseDestinationPlatformAlertConfigurationEditApi| PatchedWarehouseSourcePlatformAlertConfigurationEditApidiff --git a/products/alerts_platform/frontend/generated/api.zod.ts b/products/alerts_platform/frontend/generated/api.zod.tsindex ce0d27a6e898..18f11179a9e9 100644--- a/products/alerts_platform/frontend/generated/api.zod.ts+++ b/products/alerts_platform/frontend/generated/api.zod.ts@@ -34,9 +34,9 @@ export const platformAlertsCreateBodyTwoNameDefault = `Untitled alert`export const platformAlertsCreateBodyTwoNameMax = 255export const platformAlertsCreateBodyTwoEnabledDefault = true-export const platformAlertsCreateBodyTwoSourceConfigOneDestinationIdsMax = 100+export const platformAlertsCreateBodyTwoSourceConfigOneQueryMax = 10000-export const platformAlertsCreateBodyTwoSourceConfigOneEmailProjectMembersDefault = false+export const platformAlertsCreateBodyTwoSourceConfigOneConditionKindDefault = `threshold`export const platformAlertsCreateBodyTwoGroupingOneMaxInstancesDefault = 100export const platformAlertsCreateBodyTwoGroupingOneMaxInstancesMax = 100@@ -55,10 +55,8 @@ export const platformAlertsCreateBodyThreeNameDefault = `Untitled alert`export const platformAlertsCreateBodyThreeNameMax = 255export const platformAlertsCreateBodyThreeEnabledDefault = true-export const platformAlertsCreateBodyThreeSourceConfigOneSourceIdsMax = 100+export const platformAlertsCreateBodyThreeSourceConfigOneDestinationIdsMax = 100-export const platformAlertsCreateBodyThreeSourceConfigOneGroupByDefault = `source`-export const platformAlertsCreateBodyThreeSourceConfigOneIncludeBillingLimitsDefault = falseexport const platformAlertsCreateBodyThreeSourceConfigOneEmailProjectMembersDefault = falseexport const platformAlertsCreateBodyThreeGroupingOneMaxInstancesDefault = 100export const platformAlertsCreateBodyThreeGroupingOneMaxInstancesMax = 100@@ -74,6 +72,29 @@ export const platformAlertsCreateBodyThreeCooldownMinutesDefault = 0export const platformAlertsCreateBodyThreeCooldownMinutesMin = 0export const platformAlertsCreateBodyThreeCooldownMinutesMax = 2147483647+export const platformAlertsCreateBodyFourNameDefault = `Untitled alert`+export const platformAlertsCreateBodyFourNameMax = 255++export const platformAlertsCreateBodyFourEnabledDefault = true+export const platformAlertsCreateBodyFourSourceConfigOneSourceIdsMax = 100++export const platformAlertsCreateBodyFourSourceConfigOneGroupByDefault = `source`+export const platformAlertsCreateBodyFourSourceConfigOneIncludeBillingLimitsDefault = false+export const platformAlertsCreateBodyFourSourceConfigOneEmailProjectMembersDefault = false+export const platformAlertsCreateBodyFourGroupingOneMaxInstancesDefault = 100+export const platformAlertsCreateBodyFourGroupingOneMaxInstancesMax = 100++export const platformAlertsCreateBodyFourGroupingOneOnOverflowDefault = `degrade_visible`+export const platformAlertsCreateBodyFourEvaluationPeriodsDefault = 1+export const platformAlertsCreateBodyFourEvaluationPeriodsMax = 10++export const platformAlertsCreateBodyFourDatapointsToAlarmDefault = 1+export const platformAlertsCreateBodyFourDatapointsToAlarmMax = 10++export const platformAlertsCreateBodyFourCooldownMinutesDefault = 0+export const platformAlertsCreateBodyFourCooldownMinutesMin = 0+export const platformAlertsCreateBodyFourCooldownMinutesMax = 2147483647+export const PlatformAlertsCreateBody = /* @__PURE__ */ zod.union([zod.object({@@ -241,7 +262,7 @@ export const PlatformAlertsCreateBody = /* @__PURE__ */ zod.union([zod.object({source_kind: zod- .enum(['warehouse_destination'])+ .enum(['metrics']).describe('Product whose data the alert evaluates. It cannot change after the create.'),name: zod.string()@@ -254,23 +275,33 @@ export const PlatformAlertsCreateBody = /* @__PURE__ */ zod.union([.describe('Whether the alert is evaluated on schedule. Defaults to true.'),source_config: zod.object({- destination_ids: zod- .array(zod.uuid())- .max(platformAlertsCreateBodyTwoSourceConfigOneDestinationIdsMax)- .optional()- .describe(- 'Warehouse destinations the alert watches. Empty watches every destination in the project, including destinations added later. The grouping must be by_result_labels with keys [destination_id].'- ),- email_project_members: zod- .boolean()- .default(platformAlertsCreateBodyTwoSourceConfigOneEmailProjectMembersDefault)+ query: zod+ .string()+ .min(1)+ .max(platformAlertsCreateBodyTwoSourceConfigOneQueryMax).describe(- 'Whether project members who get data pipeline error emails also get an email when this alert fires or resolves.'+ "A PromQL expression over this project's metrics. Each series it returns is one group. For a threshold condition, leave the comparison out of the expression."),+ condition: zod+ .object({+ kind: zod+ .enum(['threshold', 'present'])+ .default(platformAlertsCreateBodyTwoSourceConfigOneConditionKindDefault)+ .describe(+ "threshold compares each series' latest value with `threshold`. present fires for every series the query returns, for a query that already filters to the series in breach."+ ),+ operator: zod+ .union([zod.enum(['gt', 'gte', 'lt', 'lte', 'eq', 'ne']), zod.null()])+ .optional()+ .describe("How a series' value compares with `threshold`. Required for a threshold."),+ threshold: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe('The value a series is compared with. Required for a threshold.'),+ })+ .describe('When a series is in breach.'),})- .describe(- 'Settings for a warehouse_destination alert. The bound the alert is evaluated against is under condition.'- ),+ .describe('Settings for a metrics alert. The bound the alert is evaluated against is under condition.'),grouping: zod.object({mode: zod@@ -368,7 +399,7 @@ export const PlatformAlertsCreateBody = /* @__PURE__ */ zod.union([zod.object({source_kind: zod- .enum(['warehouse_source'])+ .enum(['warehouse_destination']).describe('Product whose data the alert evaluates. It cannot change after the create.'),name: zod.string()@@ -379,30 +410,157 @@ export const PlatformAlertsCreateBody = /* @__PURE__ */ zod.union([.boolean().default(platformAlertsCreateBodyThreeEnabledDefault).describe('Whether the alert is evaluated on schedule. Defaults to true.'),+ source_config: zod+ .object({+ destination_ids: zod+ .array(zod.uuid())+ .max(platformAlertsCreateBodyThreeSourceConfigOneDestinationIdsMax)+ .optional()+ .describe(+ 'Warehouse destinations the alert watches. Empty watches every destination in the project, including destinations added later. The grouping must be by_result_labels with keys [destination_id].'+ ),+ email_project_members: zod+ .boolean()+ .default(platformAlertsCreateBodyThreeSourceConfigOneEmailProjectMembersDefault)+ .describe(+ 'Whether project members who get data pipeline error emails also get an email when this alert fires or resolves.'+ ),+ })+ .describe(+ 'Settings for a warehouse_destination 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(platformAlertsCreateBodyThreeGroupingOneMaxInstancesMax)+ .default(platformAlertsCreateBodyThreeGroupingOneMaxInstancesDefault)+ .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(platformAlertsCreateBodyThreeGroupingOneOnOverflowDefault)+ .describe(+ 'What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'+ ),+ })+ .optional()+ .describe('How the alert splits its results into instances. Defaults to mode single.'),+ schedule_restriction: zod+ .union([+ zod.object({+ blocked_windows: zod+ .array(+ zod.object({+ start: zod+ .string()+ .describe(+ 'Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)).'+ ),+ end: zod+ .string()+ .describe(+ 'End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally.'+ ),+ })+ )+ .describe(+ 'Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours.'+ ),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. Defaults to null.'+ ),+ evaluation_periods: zod+ .number()+ .min(1)+ .max(platformAlertsCreateBodyThreeEvaluationPeriodsMax)+ .default(platformAlertsCreateBodyThreeEvaluationPeriodsDefault)+ .describe('Number of recent checks considered when deciding to fire. Defaults to 1.'),+ datapoints_to_alarm: zod+ .number()+ .min(1)+ .max(platformAlertsCreateBodyThreeDatapointsToAlarmMax)+ .default(platformAlertsCreateBodyThreeDatapointsToAlarmDefault)+ .describe(+ 'Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods. Defaults to 1.'+ ),+ cooldown_minutes: zod+ .number()+ .min(platformAlertsCreateBodyThreeCooldownMinutesMin)+ .max(platformAlertsCreateBodyThreeCooldownMinutesMax)+ .default(platformAlertsCreateBodyThreeCooldownMinutesDefault)+ .describe('Minimum minutes between notifications for the same alert. Defaults to 0.'),+ labels: zod+ .record(zod.string(), zod.string())+ .optional()+ .describe(+ 'Labels that say who owns the alert and how urgent it is, such as {\"team\": \"checkout\", \"severity\": \"critical\"}. Names use letters, digits and underscores. alertname and names that start with posthog_ are reserved. Values cannot use templates.'+ ),+ annotations: zod+ .record(zod.string(), zod.string())+ .optional()+ .describe(+ 'Context for whoever responds, such as {\"runbook_url\": \"https:\/\/...\"}. Values can use {{ $labels.<name> }} for a grouping key or label of the alert, and {{ $value }}. An annotation whose name ends in _url must start with https:\/\/.'+ ),+ })+ .describe('The settings of a new alert. Every one but source_config has a default, which is stored.'),+ zod+ .object({+ source_kind: zod+ .enum(['warehouse_source'])+ .describe('Product whose data the alert evaluates. It cannot change after the create.'),+ name: zod+ .string()+ .max(platformAlertsCreateBodyFourNameMax)+ .default(platformAlertsCreateBodyFourNameDefault)+ .describe("Human-readable name of the alert. Defaults to 'Untitled alert'."),+ enabled: zod+ .boolean()+ .default(platformAlertsCreateBodyFourEnabledDefault)+ .describe('Whether the alert is evaluated on schedule. Defaults to true.'),source_config: zod.object({source_ids: zod.array(zod.uuid())- .max(platformAlertsCreateBodyThreeSourceConfigOneSourceIdsMax)+ .max(platformAlertsCreateBodyFourSourceConfigOneSourceIdsMax).optional().describe('Warehouse sources the alert watches. Empty watches every source in the project, including sources added later.'),group_by: zod.enum(['schema', 'source'])- .default(platformAlertsCreateBodyThreeSourceConfigOneGroupByDefault)+ .default(platformAlertsCreateBodyFourSourceConfigOneGroupByDefault).describe('schema keeps one alert instance, and sends one message, per failing table. source keeps one per source, whatever number of its tables fail. The grouping must be by_result_labels with keys [schema_id] or [source_id] to match.'),include_billing_limits: zod.boolean()- .default(platformAlertsCreateBodyThreeSourceConfigOneIncludeBillingLimitsDefault)+ .default(platformAlertsCreateBodyFourSourceConfigOneIncludeBillingLimitsDefault).describe("Whether a table that stops syncing at the project's billing limit also fires the alert."),email_project_members: zod.boolean()- .default(platformAlertsCreateBodyThreeSourceConfigOneEmailProjectMembersDefault)+ .default(platformAlertsCreateBodyFourSourceConfigOneEmailProjectMembersDefault).describe('Whether project members who get data pipeline error emails also get an email when this alert fires or resolves.'),@@ -427,15 +585,15 @@ export const PlatformAlertsCreateBody = /* @__PURE__ */ zod.union([max_instances: zod.number().min(1)- .max(platformAlertsCreateBodyThreeGroupingOneMaxInstancesMax)- .default(platformAlertsCreateBodyThreeGroupingOneMaxInstancesDefault)+ .max(platformAlertsCreateBodyFourGroupingOneMaxInstancesMax)+ .default(platformAlertsCreateBodyFourGroupingOneMaxInstancesDefault).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(platformAlertsCreateBodyThreeGroupingOneOnOverflowDefault)+ .default(platformAlertsCreateBodyFourGroupingOneOnOverflowDefault).describe('What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'),@@ -473,22 +631,22 @@ export const PlatformAlertsCreateBody = /* @__PURE__ */ zod.union([evaluation_periods: zod.number().min(1)- .max(platformAlertsCreateBodyThreeEvaluationPeriodsMax)- .default(platformAlertsCreateBodyThreeEvaluationPeriodsDefault)+ .max(platformAlertsCreateBodyFourEvaluationPeriodsMax)+ .default(platformAlertsCreateBodyFourEvaluationPeriodsDefault).describe('Number of recent checks considered when deciding to fire. Defaults to 1.'),datapoints_to_alarm: zod.number().min(1)- .max(platformAlertsCreateBodyThreeDatapointsToAlarmMax)- .default(platformAlertsCreateBodyThreeDatapointsToAlarmDefault)+ .max(platformAlertsCreateBodyFourDatapointsToAlarmMax)+ .default(platformAlertsCreateBodyFourDatapointsToAlarmDefault).describe('Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods. Defaults to 1.'),cooldown_minutes: zod.number()- .min(platformAlertsCreateBodyThreeCooldownMinutesMin)- .max(platformAlertsCreateBodyThreeCooldownMinutesMax)- .default(platformAlertsCreateBodyThreeCooldownMinutesDefault)+ .min(platformAlertsCreateBodyFourCooldownMinutesMin)+ .max(platformAlertsCreateBodyFourCooldownMinutesMax)+ .default(platformAlertsCreateBodyFourCooldownMinutesDefault).describe('Minimum minutes between notifications for the same alert. Defaults to 0.'),labels: zod.record(zod.string(), zod.string())@@ -537,9 +695,9 @@ export const platformAlertsUpdateBodyTwoCooldownMinutesMax = 2147483647export const platformAlertsUpdateBodyThreeNameMax = 255-export const platformAlertsUpdateBodyThreeSourceConfigOneDestinationIdsMax = 100+export const platformAlertsUpdateBodyThreeSourceConfigOneQueryMax = 10000-export const platformAlertsUpdateBodyThreeSourceConfigOneEmailProjectMembersDefault = false+export const platformAlertsUpdateBodyThreeSourceConfigOneConditionKindDefault = `threshold`export const platformAlertsUpdateBodyThreeGroupingOneMaxInstancesDefault = 100export const platformAlertsUpdateBodyThreeGroupingOneMaxInstancesMax = 100@@ -553,10 +711,8 @@ export const platformAlertsUpdateBodyThreeCooldownMinutesMax = 2147483647export const platformAlertsUpdateBodyFourNameMax = 255-export const platformAlertsUpdateBodyFourSourceConfigOneSourceIdsMax = 100+export const platformAlertsUpdateBodyFourSourceConfigOneDestinationIdsMax = 100-export const platformAlertsUpdateBodyFourSourceConfigOneGroupByDefault = `source`-export const platformAlertsUpdateBodyFourSourceConfigOneIncludeBillingLimitsDefault = falseexport const platformAlertsUpdateBodyFourSourceConfigOneEmailProjectMembersDefault = falseexport const platformAlertsUpdateBodyFourGroupingOneMaxInstancesDefault = 100export const platformAlertsUpdateBodyFourGroupingOneMaxInstancesMax = 100@@ -569,6 +725,24 @@ export const platformAlertsUpdateBodyFourDatapointsToAlarmMax = 10export const platformAlertsUpdateBodyFourCooldownMinutesMin = 0export const platformAlertsUpdateBodyFourCooldownMinutesMax = 2147483647+export const platformAlertsUpdateBodyFiveNameMax = 255++export const platformAlertsUpdateBodyFiveSourceConfigOneSourceIdsMax = 100++export const platformAlertsUpdateBodyFiveSourceConfigOneGroupByDefault = `source`+export const platformAlertsUpdateBodyFiveSourceConfigOneIncludeBillingLimitsDefault = false+export const platformAlertsUpdateBodyFiveSourceConfigOneEmailProjectMembersDefault = false+export const platformAlertsUpdateBodyFiveGroupingOneMaxInstancesDefault = 100+export const platformAlertsUpdateBodyFiveGroupingOneMaxInstancesMax = 100++export const platformAlertsUpdateBodyFiveGroupingOneOnOverflowDefault = `degrade_visible`+export const platformAlertsUpdateBodyFiveEvaluationPeriodsMax = 10++export const platformAlertsUpdateBodyFiveDatapointsToAlarmMax = 10++export const platformAlertsUpdateBodyFiveCooldownMinutesMin = 0+export const platformAlertsUpdateBodyFiveCooldownMinutesMax = 2147483647+export const PlatformAlertsUpdateBody = /* @__PURE__ */ zod.union([zod.object({@@ -879,24 +1053,151 @@ export const PlatformAlertsUpdateBody = /* @__PURE__ */ zod.union([zod.object({source_kind: zod- .enum(['warehouse_destination'])+ .enum(['metrics']).describe('Product whose data the alert evaluates. It cannot change, so it must match the stored value.'),name: zod.string().max(platformAlertsUpdateBodyThreeNameMax).describe('Human-readable name of the alert.'),enabled: zod.boolean().describe('Whether the alert is evaluated on schedule.'),+ source_config: zod+ .object({+ query: zod+ .string()+ .min(1)+ .max(platformAlertsUpdateBodyThreeSourceConfigOneQueryMax)+ .describe(+ "A PromQL expression over this project's metrics. Each series it returns is one group. For a threshold condition, leave the comparison out of the expression."+ ),+ condition: zod+ .object({+ kind: zod+ .enum(['threshold', 'present'])+ .default(platformAlertsUpdateBodyThreeSourceConfigOneConditionKindDefault)+ .describe(+ "threshold compares each series' latest value with `threshold`. present fires for every series the query returns, for a query that already filters to the series in breach."+ ),+ operator: zod+ .union([zod.enum(['gt', 'gte', 'lt', 'lte', 'eq', 'ne']), zod.null()])+ .optional()+ .describe("How a series' value compares with `threshold`. Required for a threshold."),+ threshold: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe('The value a series is compared with. Required for a threshold.'),+ })+ .describe('When a series is in breach.'),+ })+ .describe('Settings for a metrics 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(platformAlertsUpdateBodyThreeGroupingOneMaxInstancesMax)+ .default(platformAlertsUpdateBodyThreeGroupingOneMaxInstancesDefault)+ .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(platformAlertsUpdateBodyThreeGroupingOneOnOverflowDefault)+ .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(platformAlertsUpdateBodyThreeEvaluationPeriodsMax)+ .describe('Number of recent checks considered when deciding to fire.'),+ datapoints_to_alarm: zod+ .number()+ .min(1)+ .max(platformAlertsUpdateBodyThreeDatapointsToAlarmMax)+ .describe(+ 'Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.'+ ),+ cooldown_minutes: zod+ .number()+ .min(platformAlertsUpdateBodyThreeCooldownMinutesMin)+ .max(platformAlertsUpdateBodyThreeCooldownMinutesMax)+ .describe('Minimum minutes between notifications for the same alert.'),+ labels: zod+ .record(zod.string(), zod.string())+ .optional()+ .describe(+ 'Labels that say who owns the alert and how urgent it is, such as {\"team\": \"checkout\", \"severity\": \"critical\"}. Names use letters, digits and underscores. alertname and names that start with posthog_ are reserved. Values cannot use templates.'+ ),+ annotations: zod+ .record(zod.string(), zod.string())+ .optional()+ .describe(+ 'Context for whoever responds, such as {\"runbook_url\": \"https:\/\/...\"}. Values can use {{ $labels.<name> }} for a grouping key or label of the alert, and {{ $value }}. An annotation whose name ends in _url must start with https:\/\/.'+ ),+ })+ .describe('The settings an edit can change. Each source kind subclasses it with a typed `source_config`.'),+ zod+ .object({+ source_kind: zod+ .enum(['warehouse_destination'])+ .describe(+ 'Product whose data the alert evaluates. It cannot change, so it must match the stored value.'+ ),+ name: zod.string().max(platformAlertsUpdateBodyFourNameMax).describe('Human-readable name of the alert.'),+ enabled: zod.boolean().describe('Whether the alert is evaluated on schedule.'),source_config: zod.object({destination_ids: zod.array(zod.uuid())- .max(platformAlertsUpdateBodyThreeSourceConfigOneDestinationIdsMax)+ .max(platformAlertsUpdateBodyFourSourceConfigOneDestinationIdsMax).optional().describe('Warehouse destinations the alert watches. Empty watches every destination in the project, including destinations added later. The grouping must be by_result_labels with keys [destination_id].'),email_project_members: zod.boolean()- .default(platformAlertsUpdateBodyThreeSourceConfigOneEmailProjectMembersDefault)+ .default(platformAlertsUpdateBodyFourSourceConfigOneEmailProjectMembersDefault).describe('Whether project members who get data pipeline error emails also get an email when this alert fires or resolves.'),@@ -921,15 +1222,15 @@ export const PlatformAlertsUpdateBody = /* @__PURE__ */ zod.union([max_instances: zod.number().min(1)- .max(platformAlertsUpdateBodyThreeGroupingOneMaxInstancesMax)- .default(platformAlertsUpdateBodyThreeGroupingOneMaxInstancesDefault)+ .max(platformAlertsUpdateBodyFourGroupingOneMaxInstancesMax)+ .default(platformAlertsUpdateBodyFourGroupingOneMaxInstancesDefault).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(platformAlertsUpdateBodyThreeGroupingOneOnOverflowDefault)+ .default(platformAlertsUpdateBodyFourGroupingOneOnOverflowDefault).describe('What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'),@@ -965,19 +1266,19 @@ export const PlatformAlertsUpdateBody = /* @__PURE__ */ zod.union([evaluation_periods: zod.number().min(1)- .max(platformAlertsUpdateBodyThreeEvaluationPeriodsMax)+ .max(platformAlertsUpdateBodyFourEvaluationPeriodsMax).describe('Number of recent checks considered when deciding to fire.'),datapoints_to_alarm: zod.number().min(1)- .max(platformAlertsUpdateBodyThreeDatapointsToAlarmMax)+ .max(platformAlertsUpdateBodyFourDatapointsToAlarmMax).describe('Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.'),cooldown_minutes: zod.number()- .min(platformAlertsUpdateBodyThreeCooldownMinutesMin)- .max(platformAlertsUpdateBodyThreeCooldownMinutesMax)+ .min(platformAlertsUpdateBodyFourCooldownMinutesMin)+ .max(platformAlertsUpdateBodyFourCooldownMinutesMax).describe('Minimum minutes between notifications for the same alert.'),labels: zod.record(zod.string(), zod.string())@@ -1000,32 +1301,32 @@ export const PlatformAlertsUpdateBody = /* @__PURE__ */ zod.union([.describe('Product whose data the alert evaluates. It cannot change, so it must match the stored value.'),- name: zod.string().max(platformAlertsUpdateBodyFourNameMax).describe('Human-readable name of the alert.'),+ name: zod.string().max(platformAlertsUpdateBodyFiveNameMax).describe('Human-readable name of the alert.'),enabled: zod.boolean().describe('Whether the alert is evaluated on schedule.'),source_config: zod.object({source_ids: zod.array(zod.uuid())- .max(platformAlertsUpdateBodyFourSourceConfigOneSourceIdsMax)+ .max(platformAlertsUpdateBodyFiveSourceConfigOneSourceIdsMax).optional().describe('Warehouse sources the alert watches. Empty watches every source in the project, including sources added later.'),group_by: zod.enum(['schema', 'source'])- .default(platformAlertsUpdateBodyFourSourceConfigOneGroupByDefault)+ .default(platformAlertsUpdateBodyFiveSourceConfigOneGroupByDefault).describe('schema keeps one alert instance, and sends one message, per failing table. source keeps one per source, whatever number of its tables fail. The grouping must be by_result_labels with keys [schema_id] or [source_id] to match.'),include_billing_limits: zod.boolean()- .default(platformAlertsUpdateBodyFourSourceConfigOneIncludeBillingLimitsDefault)+ .default(platformAlertsUpdateBodyFiveSourceConfigOneIncludeBillingLimitsDefault).describe("Whether a table that stops syncing at the project's billing limit also fires the alert."),email_project_members: zod.boolean()- .default(platformAlertsUpdateBodyFourSourceConfigOneEmailProjectMembersDefault)+ .default(platformAlertsUpdateBodyFiveSourceConfigOneEmailProjectMembersDefault).describe('Whether project members who get data pipeline error emails also get an email when this alert fires or resolves.'),@@ -1050,15 +1351,15 @@ export const PlatformAlertsUpdateBody = /* @__PURE__ */ zod.union([max_instances: zod.number().min(1)- .max(platformAlertsUpdateBodyFourGroupingOneMaxInstancesMax)- .default(platformAlertsUpdateBodyFourGroupingOneMaxInstancesDefault)+ .max(platformAlertsUpdateBodyFiveGroupingOneMaxInstancesMax)+ .default(platformAlertsUpdateBodyFiveGroupingOneMaxInstancesDefault).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(platformAlertsUpdateBodyFourGroupingOneOnOverflowDefault)+ .default(platformAlertsUpdateBodyFiveGroupingOneOnOverflowDefault).describe('What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'),@@ -1094,19 +1395,19 @@ export const PlatformAlertsUpdateBody = /* @__PURE__ */ zod.union([evaluation_periods: zod.number().min(1)- .max(platformAlertsUpdateBodyFourEvaluationPeriodsMax)+ .max(platformAlertsUpdateBodyFiveEvaluationPeriodsMax).describe('Number of recent checks considered when deciding to fire.'),datapoints_to_alarm: zod.number().min(1)- .max(platformAlertsUpdateBodyFourDatapointsToAlarmMax)+ .max(platformAlertsUpdateBodyFiveDatapointsToAlarmMax).describe('Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.'),cooldown_minutes: zod.number()- .min(platformAlertsUpdateBodyFourCooldownMinutesMin)- .max(platformAlertsUpdateBodyFourCooldownMinutesMax)+ .min(platformAlertsUpdateBodyFiveCooldownMinutesMin)+ .max(platformAlertsUpdateBodyFiveCooldownMinutesMax).describe('Minimum minutes between notifications for the same alert.'),labels: zod.record(zod.string(), zod.string())@@ -1155,9 +1456,9 @@ export const platformAlertsPartialUpdateBodyTwoCooldownMinutesMax = 2147483647export const platformAlertsPartialUpdateBodyThreeNameMax = 255-export const platformAlertsPartialUpdateBodyThreeSourceConfigOneDestinationIdsMax = 100+export const platformAlertsPartialUpdateBodyThreeSourceConfigOneQueryMax = 10000-export const platformAlertsPartialUpdateBodyThreeSourceConfigOneEmailProjectMembersDefault = false+export const platformAlertsPartialUpdateBodyThreeSourceConfigOneConditionKindDefault = `threshold`export const platformAlertsPartialUpdateBodyThreeGroupingOneMaxInstancesDefault = 100export const platformAlertsPartialUpdateBodyThreeGroupingOneMaxInstancesMax = 100@@ -1171,10 +1472,8 @@ export const platformAlertsPartialUpdateBodyThreeCooldownMinutesMax = 2147483647export const platformAlertsPartialUpdateBodyFourNameMax = 255-export const platformAlertsPartialUpdateBodyFourSourceConfigOneSourceIdsMax = 100+export const platformAlertsPartialUpdateBodyFourSourceConfigOneDestinationIdsMax = 100-export const platformAlertsPartialUpdateBodyFourSourceConfigOneGroupByDefault = `source`-export const platformAlertsPartialUpdateBodyFourSourceConfigOneIncludeBillingLimitsDefault = falseexport const platformAlertsPartialUpdateBodyFourSourceConfigOneEmailProjectMembersDefault = falseexport const platformAlertsPartialUpdateBodyFourGroupingOneMaxInstancesDefault = 100export const platformAlertsPartialUpdateBodyFourGroupingOneMaxInstancesMax = 100@@ -1187,6 +1486,24 @@ export const platformAlertsPartialUpdateBodyFourDatapointsToAlarmMax = 10export const platformAlertsPartialUpdateBodyFourCooldownMinutesMin = 0export const platformAlertsPartialUpdateBodyFourCooldownMinutesMax = 2147483647+export const platformAlertsPartialUpdateBodyFiveNameMax = 255++export const platformAlertsPartialUpdateBodyFiveSourceConfigOneSourceIdsMax = 100++export const platformAlertsPartialUpdateBodyFiveSourceConfigOneGroupByDefault = `source`+export const platformAlertsPartialUpdateBodyFiveSourceConfigOneIncludeBillingLimitsDefault = false+export const platformAlertsPartialUpdateBodyFiveSourceConfigOneEmailProjectMembersDefault = false+export const platformAlertsPartialUpdateBodyFiveGroupingOneMaxInstancesDefault = 100+export const platformAlertsPartialUpdateBodyFiveGroupingOneMaxInstancesMax = 100++export const platformAlertsPartialUpdateBodyFiveGroupingOneOnOverflowDefault = `degrade_visible`+export const platformAlertsPartialUpdateBodyFiveEvaluationPeriodsMax = 10++export const platformAlertsPartialUpdateBodyFiveDatapointsToAlarmMax = 10++export const platformAlertsPartialUpdateBodyFiveCooldownMinutesMin = 0+export const platformAlertsPartialUpdateBodyFiveCooldownMinutesMax = 2147483647+export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod.union([zod.object({@@ -1517,7 +1834,7 @@ export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod.union([zod.object({source_kind: zod- .enum(['warehouse_destination'])+ .enum(['metrics']).describe('Product whose data the alert evaluates. It cannot change, so it must match the stored value.'),@@ -1527,18 +1844,155 @@ export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod.union([.optional().describe('Human-readable name of the alert.'),enabled: zod.boolean().optional().describe('Whether the alert is evaluated on schedule.'),+ source_config: zod+ .object({+ query: zod+ .string()+ .min(1)+ .max(platformAlertsPartialUpdateBodyThreeSourceConfigOneQueryMax)+ .describe(+ "A PromQL expression over this project's metrics. Each series it returns is one group. For a threshold condition, leave the comparison out of the expression."+ ),+ condition: zod+ .object({+ kind: zod+ .enum(['threshold', 'present'])+ .default(platformAlertsPartialUpdateBodyThreeSourceConfigOneConditionKindDefault)+ .describe(+ "threshold compares each series' latest value with `threshold`. present fires for every series the query returns, for a query that already filters to the series in breach."+ ),+ operator: zod+ .union([zod.enum(['gt', 'gte', 'lt', 'lte', 'eq', 'ne']), zod.null()])+ .optional()+ .describe("How a series' value compares with `threshold`. Required for a threshold."),+ threshold: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe('The value a series is compared with. Required for a threshold.'),+ })+ .describe('When a series is in breach.'),+ })+ .optional()+ .describe('Settings for a metrics 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(platformAlertsPartialUpdateBodyThreeGroupingOneMaxInstancesMax)+ .default(platformAlertsPartialUpdateBodyThreeGroupingOneMaxInstancesDefault)+ .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(platformAlertsPartialUpdateBodyThreeGroupingOneOnOverflowDefault)+ .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(platformAlertsPartialUpdateBodyThreeEvaluationPeriodsMax)+ .optional()+ .describe('Number of recent checks considered when deciding to fire.'),+ datapoints_to_alarm: zod+ .number()+ .min(1)+ .max(platformAlertsPartialUpdateBodyThreeDatapointsToAlarmMax)+ .optional()+ .describe(+ 'Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.'+ ),+ cooldown_minutes: zod+ .number()+ .min(platformAlertsPartialUpdateBodyThreeCooldownMinutesMin)+ .max(platformAlertsPartialUpdateBodyThreeCooldownMinutesMax)+ .optional()+ .describe('Minimum minutes between notifications for the same alert.'),+ labels: zod+ .record(zod.string(), zod.string())+ .optional()+ .describe(+ 'Labels that say who owns the alert and how urgent it is, such as {\"team\": \"checkout\", \"severity\": \"critical\"}. Names use letters, digits and underscores. alertname and names that start with posthog_ are reserved. Values cannot use templates.'+ ),+ annotations: zod+ .record(zod.string(), zod.string())+ .optional()+ .describe(+ 'Context for whoever responds, such as {\"runbook_url\": \"https:\/\/...\"}. Values can use {{ $labels.<name> }} for a grouping key or label of the alert, and {{ $value }}. An annotation whose name ends in _url must start with https:\/\/.'+ ),+ })+ .describe('The settings an edit can change. Each source kind subclasses it with a typed `source_config`.'),+ zod+ .object({+ source_kind: zod+ .enum(['warehouse_destination'])+ .describe(+ 'Product whose data the alert evaluates. It cannot change, so it must match the stored value.'+ ),+ name: zod+ .string()+ .max(platformAlertsPartialUpdateBodyFourNameMax)+ .optional()+ .describe('Human-readable name of the alert.'),+ enabled: zod.boolean().optional().describe('Whether the alert is evaluated on schedule.'),source_config: zod.object({destination_ids: zod.array(zod.uuid())- .max(platformAlertsPartialUpdateBodyThreeSourceConfigOneDestinationIdsMax)+ .max(platformAlertsPartialUpdateBodyFourSourceConfigOneDestinationIdsMax).optional().describe('Warehouse destinations the alert watches. Empty watches every destination in the project, including destinations added later. The grouping must be by_result_labels with keys [destination_id].'),email_project_members: zod.boolean()- .default(platformAlertsPartialUpdateBodyThreeSourceConfigOneEmailProjectMembersDefault)+ .default(platformAlertsPartialUpdateBodyFourSourceConfigOneEmailProjectMembersDefault).describe('Whether project members who get data pipeline error emails also get an email when this alert fires or resolves.'),@@ -1564,15 +2018,15 @@ export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod.union([max_instances: zod.number().min(1)- .max(platformAlertsPartialUpdateBodyThreeGroupingOneMaxInstancesMax)- .default(platformAlertsPartialUpdateBodyThreeGroupingOneMaxInstancesDefault)+ .max(platformAlertsPartialUpdateBodyFourGroupingOneMaxInstancesMax)+ .default(platformAlertsPartialUpdateBodyFourGroupingOneMaxInstancesDefault).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(platformAlertsPartialUpdateBodyThreeGroupingOneOnOverflowDefault)+ .default(platformAlertsPartialUpdateBodyFourGroupingOneOnOverflowDefault).describe('What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'),@@ -1610,21 +2064,21 @@ export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod.union([evaluation_periods: zod.number().min(1)- .max(platformAlertsPartialUpdateBodyThreeEvaluationPeriodsMax)+ .max(platformAlertsPartialUpdateBodyFourEvaluationPeriodsMax).optional().describe('Number of recent checks considered when deciding to fire.'),datapoints_to_alarm: zod.number().min(1)- .max(platformAlertsPartialUpdateBodyThreeDatapointsToAlarmMax)+ .max(platformAlertsPartialUpdateBodyFourDatapointsToAlarmMax).optional().describe('Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.'),cooldown_minutes: zod.number()- .min(platformAlertsPartialUpdateBodyThreeCooldownMinutesMin)- .max(platformAlertsPartialUpdateBodyThreeCooldownMinutesMax)+ .min(platformAlertsPartialUpdateBodyFourCooldownMinutesMin)+ .max(platformAlertsPartialUpdateBodyFourCooldownMinutesMax).optional().describe('Minimum minutes between notifications for the same alert.'),labels: zod@@ -1650,7 +2104,7 @@ export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod.union([),name: zod.string()- .max(platformAlertsPartialUpdateBodyFourNameMax)+ .max(platformAlertsPartialUpdateBodyFiveNameMax).optional().describe('Human-readable name of the alert.'),enabled: zod.boolean().optional().describe('Whether the alert is evaluated on schedule.'),@@ -1658,26 +2112,26 @@ export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod.union([.object({source_ids: zod.array(zod.uuid())- .max(platformAlertsPartialUpdateBodyFourSourceConfigOneSourceIdsMax)+ .max(platformAlertsPartialUpdateBodyFiveSourceConfigOneSourceIdsMax).optional().describe('Warehouse sources the alert watches. Empty watches every source in the project, including sources added later.'),group_by: zod.enum(['schema', 'source'])- .default(platformAlertsPartialUpdateBodyFourSourceConfigOneGroupByDefault)+ .default(platformAlertsPartialUpdateBodyFiveSourceConfigOneGroupByDefault).describe('schema keeps one alert instance, and sends one message, per failing table. source keeps one per source, whatever number of its tables fail. The grouping must be by_result_labels with keys [schema_id] or [source_id] to match.'),include_billing_limits: zod.boolean()- .default(platformAlertsPartialUpdateBodyFourSourceConfigOneIncludeBillingLimitsDefault)+ .default(platformAlertsPartialUpdateBodyFiveSourceConfigOneIncludeBillingLimitsDefault).describe("Whether a table that stops syncing at the project's billing limit also fires the alert."),email_project_members: zod.boolean()- .default(platformAlertsPartialUpdateBodyFourSourceConfigOneEmailProjectMembersDefault)+ .default(platformAlertsPartialUpdateBodyFiveSourceConfigOneEmailProjectMembersDefault).describe('Whether project members who get data pipeline error emails also get an email when this alert fires or resolves.'),@@ -1703,15 +2157,15 @@ export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod.union([max_instances: zod.number().min(1)- .max(platformAlertsPartialUpdateBodyFourGroupingOneMaxInstancesMax)- .default(platformAlertsPartialUpdateBodyFourGroupingOneMaxInstancesDefault)+ .max(platformAlertsPartialUpdateBodyFiveGroupingOneMaxInstancesMax)+ .default(platformAlertsPartialUpdateBodyFiveGroupingOneMaxInstancesDefault).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(platformAlertsPartialUpdateBodyFourGroupingOneOnOverflowDefault)+ .default(platformAlertsPartialUpdateBodyFiveGroupingOneOnOverflowDefault).describe('What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'),@@ -1749,21 +2203,21 @@ export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod.union([evaluation_periods: zod.number().min(1)- .max(platformAlertsPartialUpdateBodyFourEvaluationPeriodsMax)+ .max(platformAlertsPartialUpdateBodyFiveEvaluationPeriodsMax).optional().describe('Number of recent checks considered when deciding to fire.'),datapoints_to_alarm: zod.number().min(1)- .max(platformAlertsPartialUpdateBodyFourDatapointsToAlarmMax)+ .max(platformAlertsPartialUpdateBodyFiveDatapointsToAlarmMax).optional().describe('Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.'),cooldown_minutes: zod.number()- .min(platformAlertsPartialUpdateBodyFourCooldownMinutesMin)- .max(platformAlertsPartialUpdateBodyFourCooldownMinutesMax)+ .min(platformAlertsPartialUpdateBodyFiveCooldownMinutesMin)+ .max(platformAlertsPartialUpdateBodyFiveCooldownMinutesMax).optional().describe('Minimum minutes between notifications for the same alert.'),labels: zoddiff --git a/products/metrics/backend/alerts/__init__.py b/products/metrics/backend/alerts/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/metrics/backend/alerts/destinations.py b/products/metrics/backend/alerts/destinations.pynew file mode 100644index 000000000000..32c5845caea0--- /dev/null+++ b/products/metrics/backend/alerts/destinations.py@@ -0,0 +1,89 @@+"""What each metrics alert event says, and where its destinations may send it.++A destination is a set of HogFunctions, one per event kind it handles. Native delivery reads them to+find who to tell and words the message itself, so their templates never run.+"""++from dataclasses import replace+from typing import Final, Literal++from products.alerts_platform.backend.facade.contracts import AlertDestinationAction, EventKindSpec, IncidentAction++EventKind = Literal["firing", "resolved", "errored", "broken", "incident_opened", "incident_closed"]++_PRODUCT_LABEL = "metric alert"+_METRICS_URL = "{project.url}/metrics"+_DATA: Final[dict[str, str]] = {+ "alert_id": "{event.properties.alert_id}",+ "alert_name": "{event.properties.alert_name}",+ "query": "{event.properties.query}",+ "value": "{event.properties.value}",+}++_FIRING = EventKindSpec(+ event_id="$metrics_alert_firing",+ display_kind="firing",+ header="🔴 Metric alert '{event.properties.alert_name}' is firing",+ details=(("Query", "{event.properties.query}"), ("Value", "{event.properties.value}")),+ primary_action_url=_METRICS_URL,+ primary_action_label="View in PostHog",+ webhook_body={+ "id": "{event.uuid}",+ "type": "metrics_alert.firing",+ "timestamp": "{event.properties.triggered_at}",+ "data": _DATA,+ },+ product_label=_PRODUCT_LABEL,+)++EVENT_KIND_CONFIG: Final[dict[EventKind, EventKindSpec]] = {+ "firing": _FIRING,+ "resolved": replace(+ _FIRING,+ event_id="$metrics_alert_resolved",+ display_kind="resolved",+ header="🟢 Metric alert '{event.properties.alert_name}' is resolved",+ webhook_body={**_FIRING.webhook_body, "type": "metrics_alert.resolved"},+ ),+ "errored": replace(+ _FIRING,+ event_id="$metrics_alert_errored",+ display_kind="errored",+ header="🟡 Metric alert '{event.properties.alert_name}' could not be checked",+ details=(("Reason", "{event.properties.error_message}"),),+ webhook_body={**_FIRING.webhook_body, "type": "metrics_alert.errored"},+ ),+ "broken": replace(+ _FIRING,+ event_id="$metrics_alert_broken",+ display_kind="turned off",+ header="⚠️ Metric alert '{event.properties.alert_name}' is turned off",+ details=(("Reason", "{event.properties.error_message}"),),+ webhook_body={**_FIRING.webhook_body, "type": "metrics_alert.broken"},+ ),+ # The edge kinds follow every move into and out of FIRING, whatever cooldown decided. An+ # incident manager needs a resolve for every trigger, or the incident it opened stays open.+ "incident_opened": replace(+ _FIRING,+ event_id="$metrics_alert_incident_opened",+ display_kind="incident opened",+ webhook_body={},+ additional_actions=(AlertDestinationAction(url=_METRICS_URL, label="View in PostHog"),),+ incident_action=IncidentAction.TRIGGER,+ ),+ "incident_closed": replace(+ _FIRING,+ event_id="$metrics_alert_incident_closed",+ display_kind="incident closed",+ header="Metric alert '{event.properties.alert_name}' stopped firing",+ details=(("Reason", "{event.properties.reason}"),),+ webhook_body={},+ incident_action=IncidentAction.RESOLVE,+ ),+}++EVENT_IDS: Final[tuple[str, ...]] = tuple(spec.event_id for spec in EVENT_KIND_CONFIG.values())++EVENT_IDS_BY_INCIDENT_ACTION: Final[dict[str, str]] = {+ spec.incident_action.value: spec.event_id for spec in EVENT_KIND_CONFIG.values() if spec.incident_action+}diff --git a/products/metrics/backend/alerts/registration.py b/products/metrics/backend/alerts/registration.pynew file mode 100644index 000000000000..901ef8297158--- /dev/null+++ b/products/metrics/backend/alerts/registration.py@@ -0,0 +1,20 @@+"""Plugs metrics alerts into the alerts platform, which imports no source. Called from `ready()`."""++from products.alerts_platform.backend.facade.contracts import SourceConfigSpec, SourceKind+from products.alerts_platform.backend.facade.delivery import register_source_describer+from products.alerts_platform.backend.facade.source_configs import register_source_config+from products.metrics.backend.alerts.wording import describe_transition+++def load_alert_config() -> SourceConfigSpec:+ from products.metrics.backend.alerts.source_config import ( # noqa: PLC0415 - keeps the platform API and the destinations layer off the startup path+ METRICS_ALERT_CONFIG,+ )++ return METRICS_ALERT_CONFIG+++def register() -> None:+ # Native delivery only, so no legacy event emitter and no legacy webhook body.+ register_source_describer(SourceKind.METRICS, describe_transition)+ register_source_config(SourceKind.METRICS, load_alert_config)diff --git a/products/metrics/backend/alerts/source_config.py b/products/metrics/backend/alerts/source_config.pynew file mode 100644index 000000000000..3ca751c67bd3--- /dev/null+++ b/products/metrics/backend/alerts/source_config.py@@ -0,0 +1,84 @@+"""The `source_config` of a metrics alert on the alerts platform, and its native lifecycle.++A metrics alert has no row of its own in this product. The platform creates and deletes it, and its+configuration id is the id its destinations match on.+"""++from typing import Final, Literal, Self+from uuid import UUID++from pydantic import BaseModel, ConfigDict, Field, model_validator++from products.alerts.backend.facade.destinations import soft_delete_all_alert_destinations+from products.alerts_platform.backend.facade.contracts import (+ NativeAlertLifecycle,+ PlatformAlertConfigurationEdit,+ SourceConfigSpec,+)+from products.metrics.backend.alerts.destinations import EVENT_IDS, EVENT_IDS_BY_INCIDENT_ACTION+from products.metrics.backend.alerts.wording import alert_url++# A metrics alert checks the latest value of each series, so it runs as often as the platform allows.+CHECK_INTERVAL_MINUTES: Final = 1+MAX_QUERY_LENGTH: Final = 10_000++# Words rather than symbols, because generated API clients build enum keys from the values.+Operator = Literal["gt", "gte", "lt", "lte", "eq", "ne"]+++class MetricsPlatformAlertCondition(BaseModel):+ # A NaN threshold compares false with every value, so a saved alert could never fire.+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)++ kind: Literal["threshold", "present"] = Field(+ default="threshold",+ description="threshold compares each series' latest value with `threshold`. present fires for every "+ "series the query returns, for a query that already filters to the series in breach.",+ )+ operator: Operator | None = Field(+ default=None, description="How a series' value compares with `threshold`. Required for a threshold."+ )+ threshold: float | None = Field(+ default=None, description="The value a series is compared with. Required for a threshold."+ )++ @model_validator(mode="after")+ def _check_kind(self) -> Self:+ if self.kind == "threshold" and (self.operator is None or self.threshold is None):+ raise ValueError("A threshold condition needs an operator and a threshold.")+ if self.kind == "present" and (self.operator is not None or self.threshold is not None):+ raise ValueError("A present condition takes no operator or threshold.")+ return self+++class MetricsPlatformAlertConfig(BaseModel):+ model_config = ConfigDict(extra="forbid")++ query: str = Field(+ min_length=1,+ max_length=MAX_QUERY_LENGTH,+ description="A PromQL expression over this project's metrics. Each series it returns is one group. "+ "For a threshold condition, leave the comparison out of the expression.",+ )+ condition: MetricsPlatformAlertCondition = Field(description="When a series is in breach.")+++def _validate_edit(edit: PlatformAlertConfigurationEdit) -> None:+ # The model holds every rule, so an edit adds none.+ return None+++def _remove_destinations(*, team_id: int, configuration_id: UUID) -> None:+ soft_delete_all_alert_destinations(team_id=team_id, alert_id=str(configuration_id), allowed_event_ids=EVENT_IDS)+++METRICS_ALERT_CONFIG: Final = SourceConfigSpec(+ model=MetricsPlatformAlertConfig,+ validate=_validate_edit,+ native=NativeAlertLifecycle(+ check_interval_minutes=CHECK_INTERVAL_MINUTES, remove_destinations=_remove_destinations+ ),+ incident_event_ids=EVENT_IDS_BY_INCIDENT_ACTION,+ alert_url=alert_url,+ rollout_flag="platform-alerts-source-metrics",+)diff --git a/products/metrics/backend/alerts/wording.py b/products/metrics/backend/alerts/wording.pynew file mode 100644index 000000000000..d2771d20974d--- /dev/null+++ b/products/metrics/backend/alerts/wording.py@@ -0,0 +1,52 @@+"""How a metrics alert reads in a platform notification.++A describer runs on the send path and does no I/O, so everything a message names travels on the+transition: the series labels are the group's labels.++Imported from `ready()`, so it stays light: no models, no query layer.+"""++from typing import Final+from uuid import UUID++from posthog.utils import absolute_uri++from products.alerts_platform.backend.facade.contracts import (+ AnnouncedTransition,+ MessageDetail,+ MessageLink,+ SourceDescription,+)++OPERATOR_SYMBOLS: Final[dict[str, str]] = {"gt": ">", "gte": ">=", "lt": "<", "lte": "<=", "eq": "==", "ne": "!="}+++def metrics_url(team_id: int) -> str:+ return absolute_uri(f"/project/{team_id}/metrics")+++def alert_url(team_id: int, _configuration_id: UUID) -> str:+ """Where a metrics alert's messages link. The alert has no page of its own yet."""+ return metrics_url(team_id)+++def describe_transition(*, project_id: int, transition: AnnouncedTransition) -> SourceDescription:+ details = [MessageDetail(label="Query", value=str(transition.source_config.get("query", "")))]+ if transition.value is not None:+ details.append(MessageDetail(label="Value", value=f"{transition.value:g}"))+ condition = transition.condition+ if condition.get("kind", "threshold") == "threshold" and "threshold" in condition:+ details.append(+ MessageDetail(+ label="Threshold",+ value=f"{OPERATOR_SYMBOLS.get(str(condition.get('operator')), condition.get('operator'))} {condition['threshold']:g}",+ )+ )+ context = (+ (", ".join(f"{key}={value}" for key, value in sorted(transition.labels.items())),) if transition.labels else ()+ )+ return SourceDescription(+ details=tuple(details),+ context=context,+ data_link=MessageLink(label="View metrics", url=metrics_url(project_id)),+ )diff --git a/products/metrics/backend/apps.py b/products/metrics/backend/apps.pyindex c7920f7b383b..276f8aa58256 100644--- a/products/metrics/backend/apps.py+++ b/products/metrics/backend/apps.py@@ -12,3 +12,9 @@ class MetricsConfig(AppConfig):from products.metrics.backend.dashboard_import import receivers # noqa: PLC0415 — needs the app registryreceivers.connect()++ # The alerts platform imports no source, so metrics alerts register their wording and their+ # `source_config` schema with it here, in every process.+ from products.metrics.backend.alerts.registration import register # noqa: PLC0415++ register()diff --git a/products/metrics/backend/tests/test_alerts.py b/products/metrics/backend/tests/test_alerts.pynew file mode 100644index 000000000000..84ae58e88f37--- /dev/null+++ b/products/metrics/backend/tests/test_alerts.py@@ -0,0 +1,63 @@+from typing import Any++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.test import SimpleTestCase++from parameterized import parameterized+from pydantic import ValidationError+from rest_framework import status++from products.metrics.backend.alerts.source_config import MetricsPlatformAlertConfig++_QUERY = 'sum(kafka_consumer_group_lag{group="example"})'+++class TestMetricsAlertConfig(SimpleTestCase):+ @parameterized.expand(+ [+ ("threshold_without_operator", {"query": _QUERY, "condition": {"threshold": 10}}),+ ("threshold_without_value", {"query": _QUERY, "condition": {"operator": "gt"}}),+ ("present_with_threshold", {"query": _QUERY, "condition": {"kind": "present", "threshold": 1}}),+ ("empty_query", {"query": "", "condition": {"kind": "present"}}),+ ("unknown_operator", {"query": _QUERY, "condition": {"operator": ">", "threshold": 1}}),+ ("nan_threshold", {"query": _QUERY, "condition": {"operator": "gt", "threshold": float("nan")}}),+ ]+ )+ def test_a_config_that_cannot_be_evaluated_is_refused(self, _name: str, config: dict[str, object]) -> None:+ with self.assertRaises(ValidationError):+ MetricsPlatformAlertConfig.model_validate(config)+++class TestMetricsAlertCreate(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.enterContext(patch("posthoganalytics.feature_enabled", return_value=True))++ def _create(self, source_config: dict[str, object]) -> Any:+ return self.client.post(+ f"/api/projects/{self.team.id}/platform_alerts/",+ {"source_kind": "metrics", "name": "Consumer lag", "enabled": True, "source_config": source_config},+ format="json",+ )++ def test_a_metrics_alert_is_created_through_the_platform_api(self) -> None:+ response = self._create({"query": _QUERY, "condition": {"operator": "gt", "threshold": 1000}})++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ assert response.json()["source_kind"] == "metrics"+ assert response.json()["check_interval_minutes"] == 1++ def test_a_project_without_the_metrics_rollout_flag_cannot_create_one(self) -> None:+ self.enterContext(+ patch(+ "posthoganalytics.feature_enabled",+ side_effect=lambda key, *_args, **_kwargs: key != "platform-alerts-source-metrics",+ )+ )++ response = self._create({"query": _QUERY, "condition": {"operator": "gt", "threshold": 1000}})++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()+ assert response.json()["code"] == "feature_flag_required"diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 298d480786fb..61c73adc11d2 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -73050,6 +73050,175 @@ export namespace Schemas {reviewed_at: string | null;}+ /**+ * How a series' value compares with `threshold`. Required for a threshold.+ */+ export type MetricsPlatformAlertConditionOperator = typeof MetricsPlatformAlertConditionOperator[keyof typeof MetricsPlatformAlertConditionOperator] | null;+++ export const MetricsPlatformAlertConditionOperator = {+ Gt: 'gt',+ Gte: 'gte',+ Lt: 'lt',+ Lte: 'lte',+ Eq: 'eq',+ Ne: 'ne',+ } as const;++ export type MetricsPlatformAlertConditionKindEnum = typeof MetricsPlatformAlertConditionKindEnum[keyof typeof MetricsPlatformAlertConditionKindEnum];+++ export const MetricsPlatformAlertConditionKindEnum = {+ Threshold: 'threshold',+ Present: 'present',+ } as const;++ export interface MetricsPlatformAlertCondition {+ /** threshold compares each series' latest value with `threshold`. present fires for every series the query returns, for a query that already filters to the series in breach. */+ kind?: MetricsPlatformAlertConditionKindEnum;+ /** How a series' value compares with `threshold`. Required for a threshold. */+ operator?: MetricsPlatformAlertConditionOperator;+ /** The value a series is compared with. Required for a threshold. */+ threshold?: number | null;+ }++ export interface MetricsPlatformAlertConfig {+ /**+ * A PromQL expression over this project's metrics. Each series it returns is one group. For a threshold condition, leave the comparison out of the expression.+ * @minLength 1+ * @maxLength 10000+ */+ query: string;+ /** When a series is in breach. */+ condition: MetricsPlatformAlertCondition;+ }++ /**+ * Product whose data the alert evaluates. It cannot change after the create.+ */+ export type MetricsPlatformAlertConfigurationCreateSourceKind = typeof MetricsPlatformAlertConfigurationCreateSourceKind[keyof typeof MetricsPlatformAlertConfigurationCreateSourceKind];+++ export const MetricsPlatformAlertConfigurationCreateSourceKind = {+ Metrics: 'metrics',+ } as const;++ /**+ * Labels that say who owns the alert and how urgent it is, such as {"team": "checkout", "severity": "critical"}. Names use letters, digits and underscores. alertname and names that start with posthog_ are reserved. Values cannot use templates.+ */+ export type MetricsPlatformAlertConfigurationCreateLabels = {[key: string]: string};++ /**+ * Context for whoever responds, such as {"runbook_url": "https://..."}. Values can use {{ $labels.<name> }} for a grouping key or label of the alert, and {{ $value }}. An annotation whose name ends in _url must start with https://.+ */+ export type MetricsPlatformAlertConfigurationCreateAnnotations = {[key: string]: string};++ /**+ * The settings of a new alert. Every one but source_config has a default, which is stored.+ */+ export interface MetricsPlatformAlertConfigurationCreate {+ /** Product whose data the alert evaluates. It cannot change after the create. */+ source_kind: MetricsPlatformAlertConfigurationCreateSourceKind;+ /**+ * Human-readable name of the alert. Defaults to 'Untitled alert'.+ * @maxLength 255+ */+ name?: string;+ /** Whether the alert is evaluated on schedule. Defaults to true. */+ enabled?: boolean;+ /** Settings for a metrics alert. The bound the alert is evaluated against is under condition. */+ source_config: MetricsPlatformAlertConfig;+ /** How the alert splits its results into instances. Defaults to mode single. */+ grouping?: Grouping;+ /** Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. Defaults to null. */+ schedule_restriction?: AlertScheduleRestriction | null;+ /**+ * Number of recent checks considered when deciding to fire. Defaults to 1.+ * @minimum 1+ * @maximum 10+ */+ evaluation_periods?: number;+ /**+ * Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods. Defaults to 1.+ * @minimum 1+ * @maximum 10+ */+ datapoints_to_alarm?: number;+ /**+ * Minimum minutes between notifications for the same alert. Defaults to 0.+ * @minimum 0+ * @maximum 2147483647+ */+ cooldown_minutes?: number;+ /** Labels that say who owns the alert and how urgent it is, such as {"team": "checkout", "severity": "critical"}. Names use letters, digits and underscores. alertname and names that start with posthog_ are reserved. Values cannot use templates. */+ labels?: MetricsPlatformAlertConfigurationCreateLabels;+ /** Context for whoever responds, such as {"runbook_url": "https://..."}. Values can use {{ $labels.<name> }} for a grouping key or label of the alert, and {{ $value }}. An annotation whose name ends in _url must start with https://. */+ annotations?: MetricsPlatformAlertConfigurationCreateAnnotations;+ }++ /**+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.+ */+ export type MetricsPlatformAlertConfigurationEditSourceKind = typeof MetricsPlatformAlertConfigurationEditSourceKind[keyof typeof MetricsPlatformAlertConfigurationEditSourceKind];+++ export const MetricsPlatformAlertConfigurationEditSourceKind = {+ Metrics: 'metrics',+ } as const;++ /**+ * Labels that say who owns the alert and how urgent it is, such as {"team": "checkout", "severity": "critical"}. Names use letters, digits and underscores. alertname and names that start with posthog_ are reserved. Values cannot use templates.+ */+ export type MetricsPlatformAlertConfigurationEditLabels = {[key: string]: string};++ /**+ * Context for whoever responds, such as {"runbook_url": "https://..."}. Values can use {{ $labels.<name> }} for a grouping key or label of the alert, and {{ $value }}. An annotation whose name ends in _url must start with https://.+ */+ export type MetricsPlatformAlertConfigurationEditAnnotations = {[key: string]: string};++ /**+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.+ */+ export interface MetricsPlatformAlertConfigurationEdit {+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */+ source_kind: MetricsPlatformAlertConfigurationEditSourceKind;+ /**+ * Human-readable name of the alert.+ * @maxLength 255+ */+ name: string;+ /** Whether the alert is evaluated on schedule. */+ enabled: boolean;+ /** Settings for a metrics alert. The bound the alert is evaluated against is under condition. */+ source_config: MetricsPlatformAlertConfig;+ /** 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;+ /** Labels that say who owns the alert and how urgent it is, such as {"team": "checkout", "severity": "critical"}. Names use letters, digits and underscores. alertname and names that start with posthog_ are reserved. Values cannot use templates. */+ labels?: MetricsPlatformAlertConfigurationEditLabels;+ /** Context for whoever responds, such as {"runbook_url": "https://..."}. Values can use {{ $labels.<name> }} for a grouping key or label of the alert, and {{ $value }}. An annotation whose name ends in _url must start with https://. */+ annotations?: MetricsPlatformAlertConfigurationEditAnnotations;+ }+export interface MetricsSuggestedDashboard {/** Suggestion id. */id: string;@@ -89970,6 +90139,69 @@ export namespace Schemas {draft_content?: MessageTemplateContent | null;}+ /**+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.+ */+ export type PatchedMetricsPlatformAlertConfigurationEditSourceKind = typeof PatchedMetricsPlatformAlertConfigurationEditSourceKind[keyof typeof PatchedMetricsPlatformAlertConfigurationEditSourceKind];+++ export const PatchedMetricsPlatformAlertConfigurationEditSourceKind = {+ Metrics: 'metrics',+ } as const;++ /**+ * Labels that say who owns the alert and how urgent it is, such as {"team": "checkout", "severity": "critical"}. Names use letters, digits and underscores. alertname and names that start with posthog_ are reserved. Values cannot use templates.+ */+ export type PatchedMetricsPlatformAlertConfigurationEditLabels = {[key: string]: string};++ /**+ * Context for whoever responds, such as {"runbook_url": "https://..."}. Values can use {{ $labels.<name> }} for a grouping key or label of the alert, and {{ $value }}. An annotation whose name ends in _url must start with https://.+ */+ export type PatchedMetricsPlatformAlertConfigurationEditAnnotations = {[key: string]: string};++ /**+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.+ */+ export interface PatchedMetricsPlatformAlertConfigurationEdit {+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */+ source_kind: PatchedMetricsPlatformAlertConfigurationEditSourceKind;+ /**+ * Human-readable name of the alert.+ * @maxLength 255+ */+ name?: string;+ /** Whether the alert is evaluated on schedule. */+ enabled?: boolean;+ /** Settings for a metrics alert. The bound the alert is evaluated against is under condition. */+ source_config?: MetricsPlatformAlertConfig;+ /** 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;+ /** Labels that say who owns the alert and how urgent it is, such as {"team": "checkout", "severity": "critical"}. Names use letters, digits and underscores. alertname and names that start with posthog_ are reserved. Values cannot use templates. */+ labels?: PatchedMetricsPlatformAlertConfigurationEditLabels;+ /** Context for whoever responds, such as {"runbook_url": "https://..."}. Values can use {{ $labels.<name> }} for a grouping key or label of the alert, and {{ $value }}. An annotation whose name ends in _url must start with https://. */+ annotations?: PatchedMetricsPlatformAlertConfigurationEditAnnotations;+ }+export interface PatchedMoveTileRequest {/** Destination dashboard ID. */to_dashboard?: number;@@ -90582,7 +90814,7 @@ export namespace Schemas {annotations?: PatchedWarehouseSourcePlatformAlertConfigurationEditAnnotations;}- export type PatchedPlatformAlertConfigurationEdit = PatchedInsightPlatformAlertConfigurationEdit | PatchedLogsPlatformAlertConfigurationEdit | PatchedWarehouseDestinationPlatformAlertConfigurationEdit | PatchedWarehouseSourcePlatformAlertConfigurationEdit;+ export type PatchedPlatformAlertConfigurationEdit = PatchedInsightPlatformAlertConfigurationEdit | PatchedLogsPlatformAlertConfigurationEdit | PatchedMetricsPlatformAlertConfigurationEdit | PatchedWarehouseDestinationPlatformAlertConfigurationEdit | PatchedWarehouseSourcePlatformAlertConfigurationEdit;/*** Request body for PATCH /api/users/@me/product_intro_seen.@@ -95867,7 +96099,7 @@ export namespace Schemas {annotations?: WarehouseSourcePlatformAlertConfigurationCreateAnnotations;}- export type PlatformAlertConfigurationCreate = LogsPlatformAlertConfigurationCreate | WarehouseDestinationPlatformAlertConfigurationCreate | WarehouseSourcePlatformAlertConfigurationCreate;+ export type PlatformAlertConfigurationCreate = LogsPlatformAlertConfigurationCreate | MetricsPlatformAlertConfigurationCreate | WarehouseDestinationPlatformAlertConfigurationCreate | WarehouseSourcePlatformAlertConfigurationCreate;/*** Product whose data the alert evaluates. It cannot change, so it must match the stored value.@@ -95995,7 +96227,7 @@ export namespace Schemas {annotations?: WarehouseSourcePlatformAlertConfigurationEditAnnotations;}- export type PlatformAlertConfigurationEdit = InsightPlatformAlertConfigurationEdit | LogsPlatformAlertConfigurationEdit | WarehouseDestinationPlatformAlertConfigurationEdit | WarehouseSourcePlatformAlertConfigurationEdit;+ export type PlatformAlertConfigurationEdit = InsightPlatformAlertConfigurationEdit | LogsPlatformAlertConfigurationEdit | MetricsPlatformAlertConfigurationEdit | WarehouseDestinationPlatformAlertConfigurationEdit | WarehouseSourcePlatformAlertConfigurationEdit;export interface PlatformAlertGroupSnooze {/**diff --git a/tach.toml b/tach.tomlindex c487de8ed1f9..3554fa53f2a7 100644--- a/tach.toml+++ b/tach.toml@@ -706,6 +706,8 @@ depends_on = ["ee","posthog","products.access_control",+ "products.alerts",+ "products.alerts_platform","products.dashboards","products.error_tracking","products.exports",