Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add warehouse sync alerts to the alerts platform (#121354)

Tom Owers6f03d760b424
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 3ea3ee79f83e..0b5c6eebd33d 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -329,6 +329,8 @@ from products.warehouse_sources.backend.facade.temporal import (
PERSON_PROPERTY_BACKFILL_WORKFLOWS,
PERSON_PROPERTY_SYNC_ACTIVITIES,
PERSON_PROPERTY_SYNC_WORKFLOWS,
+ WAREHOUSE_ALERT_EVALUATION_ACTIVITIES,
+ WAREHOUSE_ALERT_EVALUATION_WORKFLOWS,
WORKFLOWS as DATA_SYNC_WORKFLOWS,
load_all_sources,
)
@@ -653,11 +655,13 @@ _task_queue_specs = [
ALERTS_PLATFORM_EVALUATION_WORKFLOWS
+ LOGS_SOURCE_EVALUATION_WORKFLOWS
+ INSIGHT_PLATFORM_EVALUATION_WORKFLOWS
- + BILLING_PLATFORM_EVALUATION_WORKFLOWS,
+ + BILLING_PLATFORM_EVALUATION_WORKFLOWS
+ + WAREHOUSE_ALERT_EVALUATION_WORKFLOWS,
ALERTS_PLATFORM_EVALUATION_ACTIVITIES
+ LOGS_SOURCE_EVALUATION_ACTIVITIES
+ INSIGHT_PLATFORM_EVALUATION_ACTIVITIES
- + BILLING_PLATFORM_EVALUATION_ACTIVITIES,
+ + BILLING_PLATFORM_EVALUATION_ACTIVITIES
+ + WAREHOUSE_ALERT_EVALUATION_ACTIVITIES,
),
(
settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE,
diff --git a/posthog/management/commands/test/test_start_temporal_worker.py b/posthog/management/commands/test/test_start_temporal_worker.py
index a9c4c353e211..836a77a075b2 100644
--- a/posthog/management/commands/test/test_start_temporal_worker.py
+++ b/posthog/management/commands/test/test_start_temporal_worker.py
@@ -33,6 +33,10 @@ from products.metrics.backend.facade.temporal import (
WORKFLOWS as METRICS_WORKFLOWS,
)
from products.signals.backend.temporal import InboxRankingScoringWorkflow, score_inbox_reports_activity
+from products.warehouse_sources.backend.facade.temporal import (
+ WAREHOUSE_ALERT_EVALUATION_ACTIVITIES,
+ WAREHOUSE_ALERT_EVALUATION_WORKFLOWS,
+)
from products.wizard.backend.facade.temporal import (
ACTIVITIES as WIZARD_ACTIVITIES,
WORKFLOWS as WIZARD_WORKFLOWS,
@@ -68,6 +72,11 @@ def test_aggregation_runs_on_its_own_queue_and_the_billing_queue() -> None:
SHARED_ORCHESTRATION_ACTIVITIES,
),
("alerts-platform-evaluation-task-queue", EVALUATION_WORKFLOWS, EVALUATION_ACTIVITIES),
+ (
+ "alerts-platform-evaluation-task-queue",
+ WAREHOUSE_ALERT_EVALUATION_WORKFLOWS,
+ WAREHOUSE_ALERT_EVALUATION_ACTIVITIES,
+ ),
("alerts-platform-delivery-task-queue", DELIVERY_WORKFLOWS, DELIVERY_ACTIVITIES),
(settings.SELF_DRIVING_TASK_QUEUE, [InboxRankingScoringWorkflow], [score_inbox_reports_activity]),
(settings.GENERAL_PURPOSE_TASK_QUEUE, METRICS_WORKFLOWS, METRICS_ACTIVITIES),
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 5cfaa0e7632e..ff605a97f505 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -711,6 +711,8 @@ SPECTACULAR_SETTINGS = {
"InitialPermissionModeEnum": ["default", "acceptEdits", "plan", "bypassPermissions", "auto"],
"NotificationDestinationTypeEnum": ["slack", "webhook", "teams"],
"LogsAlertDestinationTypeEnum": ["slack", "webhook", "teams", "pagerduty"],
+ "WarehouseAlertDestinationTypeEnum": ["slack", "webhook", "teams", "discord", "pagerduty"],
+ "WarehouseAlertGroupByEnum": ["schema", "source"],
"PagerDutySeverityEnum": ["critical", "error", "warning", "info"],
"PagerDutyRegionEnum": ["us", "eu"],
# growth's identity-matching tier and the signals scout suggestion confidence.
diff --git a/products/alerts_platform/backend/delivery/message.py b/products/alerts_platform/backend/delivery/message.py
index 0d82b5148fcf..a6a27d420736 100644
--- a/products/alerts_platform/backend/delivery/message.py
+++ b/products/alerts_platform/backend/delivery/message.py
@@ -43,6 +43,8 @@ _SOURCE_LABELS: Final[dict[SourceKind, str]] = {
SourceKind.LOGS: "Log",
SourceKind.INSIGHT: "Insight",
SourceKind.BILLING: "Billing",
+ SourceKind.WAREHOUSE_SOURCE: "Warehouse sync",
+ SourceKind.WAREHOUSE_DESTINATION: "Warehouse destination",
}
# What a held row says, when cooldown or mute kept its announcement and only its incident moved.
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.py
index 8fb0294007dd..8d9e6193d95b 100644
--- a/products/alerts_platform/backend/facade/api.py
+++ b/products/alerts_platform/backend/facade/api.py
@@ -158,11 +158,14 @@ def list_configurations(
def get_configuration(
- *, team_id: int, source_kinds: Sequence[str], configuration_id: UUID
+ *, team_id: int, source_kinds: Sequence[str], configuration_id: UUID, lock: bool = False
) -> PlatformAlertConfigurationView | None:
- """One configuration, or None when it does not exist or the caller may not read its kind."""
+ """One configuration, or None when it does not exist or the caller may not read its kind.
+
+ With `lock`, call it inside a transaction: the row stays locked until it ends, so a delete waits.
+ """
return platform_reads.get_configuration(
- team_id=team_id, source_kinds=source_kinds, configuration_id=configuration_id
+ team_id=team_id, source_kinds=source_kinds, configuration_id=configuration_id, lock=lock
)
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index 7d4fe5a1f890..63d4a0901d81 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -30,6 +30,8 @@ class SourceKind(StrEnum):
LOGS = "logs"
INSIGHT = "insight"
BILLING = "billing"
+ WAREHOUSE_SOURCE = "warehouse_source"
+ WAREHOUSE_DESTINATION = "warehouse_destination"
@frozen
@@ -270,6 +272,12 @@ class PlatformAlertCheckInput:
recurrence_unit: str | None = None
anchor_time: str | None = None
+ @property
+ def destination_alert_id(self) -> UUID:
+ """The id the alert's destinations are matched on: the source row's for a copy, and the
+ configuration's own for an alert whose source keeps no row."""
+ return self.legacy_configuration_id or self.id
+
def admit(self, grouping_keys: Sequence[str], *, now: datetime) -> GroupAdmission:
"""The groups a check may report, from keys in the source's priority order.
@@ -956,6 +964,12 @@ class PlatformAlertConfigurationView:
updated_at: datetime
alerts: tuple[PlatformAlertSnapshot, ...]
+ @property
+ def destination_alert_id(self) -> UUID:
+ """The id the alert's destinations are matched on: the source row's for a copy, and the
+ configuration's own for an alert whose source keeps no row."""
+ return self.legacy_configuration_id or self.id
+
@frozen
class PlatformAlertConfigurationEdit:
diff --git a/products/alerts_platform/backend/facade/enums.py b/products/alerts_platform/backend/facade/enums.py
index 0ede6bb3fd6d..273e0897a913 100644
--- a/products/alerts_platform/backend/facade/enums.py
+++ b/products/alerts_platform/backend/facade/enums.py
@@ -13,6 +13,8 @@ class PlatformAlertConfigurationSourceKind(LabeledStrEnum):
LOGS = "logs", "Logs"
INSIGHT = "insight", "Insight"
+ WAREHOUSE_SOURCE = "warehouse_source", "Warehouse source"
+ WAREHOUSE_DESTINATION = "warehouse_destination", "Warehouse destination"
class PlatformAlertOwner(LabeledStrEnum):
diff --git a/products/alerts_platform/backend/facade/lifecycle.py b/products/alerts_platform/backend/facade/lifecycle.py
index 13ba709bca63..6fcfbd418301 100644
--- a/products/alerts_platform/backend/facade/lifecycle.py
+++ b/products/alerts_platform/backend/facade/lifecycle.py
@@ -112,6 +112,16 @@ PLATFORM_DEFAULT_ALERT_POLICY = replace(LOGS_ALERT_POLICY, mute_gates_notificati
PLATFORM_LOGS_ALERT_POLICY = PLATFORM_DEFAULT_ALERT_POLICY
+# A warehouse sync alert watches a status that stays failed until a sync succeeds. So it announces
+# a failure once, keeps quiet while the status stays failed, and resolves when a sync recovers.
+# A mute holds only the message, so the state keeps tracking the status during quiet hours.
+PLATFORM_WAREHOUSE_ALERT_POLICY = replace(
+ LOGS_ALERT_POLICY,
+ renotify_while_firing=False,
+ notify_resolve=True,
+ mute_gates_notification_only=True,
+)
+
BILLING_ALERT_POLICY = AlertPolicy(
broken_is_terminal=False,
transient_errors_count_toward_broken=True,
diff --git a/products/alerts_platform/backend/logic/platform_reads.py b/products/alerts_platform/backend/logic/platform_reads.py
index 6b39487353e0..043e6d419ff2 100644
--- a/products/alerts_platform/backend/logic/platform_reads.py
+++ b/products/alerts_platform/backend/logic/platform_reads.py
@@ -122,10 +122,16 @@ def list_configurations(
def get_configuration(
- *, team_id: int, source_kinds: Sequence[str], configuration_id: UUID
+ *, team_id: int, source_kinds: Sequence[str], configuration_id: UUID, lock: bool = False
) -> PlatformAlertConfigurationView | None:
- """One configuration, or None when it does not exist or the caller may not read its kind."""
- row = _readable(team_id, source_kinds).filter(id=configuration_id).first()
+ """One configuration, or None when it does not exist or the caller may not read its kind.
+
+ With `lock`, the row stays locked until the caller's transaction ends, so a delete waits for it.
+ """
+ rows = _readable(team_id, source_kinds).filter(id=configuration_id)
+ if lock:
+ rows = rows.select_for_update(no_key=True)
+ row = rows.first()
return None if row is None else _configuration_view(row)
diff --git a/products/alerts_platform/backend/presentation/views/platform_alert.py b/products/alerts_platform/backend/presentation/views/platform_alert.py
index 38fee6982a40..de1de6fc0288 100644
--- a/products/alerts_platform/backend/presentation/views/platform_alert.py
+++ b/products/alerts_platform/backend/presentation/views/platform_alert.py
@@ -232,6 +232,8 @@ class PlatformAlertConfigurationListQuerySerializer(serializers.Serializer):
# also needs read access to that product. `alert:read` alone must not reveal it.
SOURCE_KIND_RESOURCE: dict[str, APIScopeObject] = {
PlatformAlertConfigurationSourceKind.LOGS.value: "logs",
+ PlatformAlertConfigurationSourceKind.WAREHOUSE_SOURCE.value: "external_data_source",
+ PlatformAlertConfigurationSourceKind.WAREHOUSE_DESTINATION.value: "external_data_source",
}
# Kinds the read API does not serve. An insight copy shows its insight's bound and firing state,
@@ -278,7 +280,8 @@ def _typed_edit_serializer(
source: SourceKind, spec: SourceConfigSpec
) -> type[PlatformAlertConfigurationEditSerializer]:
"""The edit serializer for one source kind, whose `source_config` is described by the source's model."""
- prefix = source.value.capitalize()
+ # Pascal case, so a kind like `warehouse_source` names its schema component `WarehouseSource...`.
+ prefix = "".join(part.capitalize() for part in source.value.split("_"))
source_config_field = extend_schema_field(spec.model)( # type: ignore[arg-type]
type(f"{prefix}PlatformAlertSourceConfigField", (serializers.JSONField,), {})
)
diff --git a/products/alerts_platform/backend/temporal/sources.py b/products/alerts_platform/backend/temporal/sources.py
index a938ab555dd0..7492ab765256 100644
--- a/products/alerts_platform/backend/temporal/sources.py
+++ b/products/alerts_platform/backend/temporal/sources.py
@@ -62,6 +62,19 @@ SOURCE_BINDINGS: dict[SourceKind, SourceBinding] = {
evaluation_timeout=dt.timedelta(minutes=2),
discovery_limit=settings.ALERTS_PLATFORM_BILLING_KEYS_PER_TICK,
),
+ # One workflow serves both warehouse kinds. Its checks read Postgres rows, so they finish in seconds.
+ SourceKind.WAREHOUSE_SOURCE: SourceBinding(
+ workflow="warehouse-alert-evaluate",
+ task_queue=settings.ALERTS_PLATFORM_EVALUATION_TASK_QUEUE,
+ evaluation_timeout=dt.timedelta(seconds=60),
+ discovery_limit=DISCOVERY_LIMIT_PER_SOURCE,
+ ),
+ SourceKind.WAREHOUSE_DESTINATION: SourceBinding(
+ workflow="warehouse-alert-evaluate",
+ task_queue=settings.ALERTS_PLATFORM_EVALUATION_TASK_QUEUE,
+ evaluation_timeout=dt.timedelta(seconds=60),
+ discovery_limit=DISCOVERY_LIMIT_PER_SOURCE,
+ ),
}
diff --git a/products/alerts_platform/backend/tests/test_source_kinds.py b/products/alerts_platform/backend/tests/test_source_kinds.py
index dd2620e01c32..798ecfc5c981 100644
--- a/products/alerts_platform/backend/tests/test_source_kinds.py
+++ b/products/alerts_platform/backend/tests/test_source_kinds.py
@@ -1,3 +1,6 @@
+import pytest
+
+from products.alerts_platform.backend.delivery.message import _SOURCE_LABELS
from products.alerts_platform.backend.facade.contracts import SourceKind
from products.alerts_platform.backend.facade.enums import PlatformAlertConfigurationSourceKind
from products.alerts_platform.backend.presentation.views.platform_alert import (
@@ -19,3 +22,9 @@ def test_every_source_kind_names_the_resource_that_gates_reading_it() -> None:
SOURCE_KIND_RESOURCE
) | UNSERVED_SOURCE_KINDS
assert not set(SOURCE_KIND_RESOURCE) & UNSERVED_SOURCE_KINDS
+
+
[email protected]("source", list(SourceKind))
+def test_every_source_kind_names_itself_in_a_message_headline(source: SourceKind) -> None:
+ # The headline reads the label by key, so a kind without one raises on every send of its alerts.
+ assert _SOURCE_LABELS[source]
diff --git a/products/alerts_platform/frontend/generated/api.schemas.ts b/products/alerts_platform/frontend/generated/api.schemas.ts
index e37549fb5365..38f128d9df5d 100644
--- a/products/alerts_platform/frontend/generated/api.schemas.ts
+++ b/products/alerts_platform/frontend/generated/api.schemas.ts
@@ -10,6 +10,8 @@
/**
* * `logs` - Logs
* * `insight` - Insight
+ * * `warehouse_source` - Warehouse source
+ * * `warehouse_destination` - Warehouse destination
*/
export type PlatformAlertConfigurationSourceKindEnumApi =
(typeof PlatformAlertConfigurationSourceKindEnumApi)[keyof typeof PlatformAlertConfigurationSourceKindEnumApi]
@@ -17,6 +19,8 @@ export type PlatformAlertConfigurationSourceKindEnumApi =
export const PlatformAlertConfigurationSourceKindEnumApi = {
Logs: 'logs',
Insight: 'insight',
+ WarehouseSource: 'warehouse_source',
+ WarehouseDestination: 'warehouse_destination',
} as const
/**
@@ -179,7 +183,9 @@ export interface PlatformAlertConfigurationApi {
/** Product whose data the alert evaluates.
*
* * `logs` - Logs
- * * `insight` - Insight */
+ * * `insight` - Insight
+ * * `warehouse_source` - Warehouse source
+ * * `warehouse_destination` - Warehouse destination */
readonly source_kind: PlatformAlertConfigurationSourceKindEnumApi
/** Source-specific settings. The shape depends on source_kind. The bound the alert is evaluated against is under the condition key. */
readonly source_config: PlatformAlertConfigurationApiSourceConfig
@@ -731,7 +737,140 @@ export interface LogsPlatformAlertConfigurationCreateApi {
cooldown_minutes?: number
}
-export type PlatformAlertConfigurationCreateApi = LogsPlatformAlertConfigurationCreateApi
+/**
+ * Product whose data the alert evaluates. It cannot change after the create.
+ */
+export type WarehouseDestinationPlatformAlertConfigurationCreateApiSourceKind =
+ (typeof WarehouseDestinationPlatformAlertConfigurationCreateApiSourceKind)[keyof typeof WarehouseDestinationPlatformAlertConfigurationCreateApiSourceKind]
+
+export const WarehouseDestinationPlatformAlertConfigurationCreateApiSourceKind = {
+ WarehouseDestination: 'warehouse_destination',
+} as const
+
+export interface WarehouseDestinationAlertConfigApi {
+ /**
+ * 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].
+ * @maxItems 100
+ */
+ destination_ids?: string[]
+ /** Whether project members who get data pipeline error emails also get an email when this alert fires or resolves. */
+ email_project_members?: boolean
+}
+
+/**
+ * The settings of a new alert. Every one but source_config has a default, which is stored.
+ */
+export interface WarehouseDestinationPlatformAlertConfigurationCreateApi {
+ /** Product whose data the alert evaluates. It cannot change after the create. */
+ source_kind: WarehouseDestinationPlatformAlertConfigurationCreateApiSourceKind
+ /**
+ * 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 warehouse_destination alert. The bound the alert is evaluated against is under condition. */
+ source_config: WarehouseDestinationAlertConfigApi
+ /** 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
+}
+
+/**
+ * Product whose data the alert evaluates. It cannot change after the create.
+ */
+export type WarehouseSourcePlatformAlertConfigurationCreateApiSourceKind =
+ (typeof WarehouseSourcePlatformAlertConfigurationCreateApiSourceKind)[keyof typeof WarehouseSourcePlatformAlertConfigurationCreateApiSourceKind]
+
+export const WarehouseSourcePlatformAlertConfigurationCreateApiSourceKind = {
+ WarehouseSource: 'warehouse_source',
+} as const
+
+export type WarehouseAlertGroupByEnumApi =
+ (typeof WarehouseAlertGroupByEnumApi)[keyof typeof WarehouseAlertGroupByEnumApi]
+
+export const WarehouseAlertGroupByEnumApi = {
+ Schema: 'schema',
+ Source: 'source',
+} as const
+
+export interface WarehouseSourceAlertConfigApi {
+ /**
+ * Warehouse sources the alert watches. Empty watches every source in the project, including sources added later.
+ * @maxItems 100
+ */
+ source_ids?: string[]
+ /** 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. */
+ group_by?: WarehouseAlertGroupByEnumApi
+ /** Whether a table that stops syncing at the project's billing limit also fires the alert. */
+ include_billing_limits?: boolean
+ /** Whether project members who get data pipeline error emails also get an email when this alert fires or resolves. */
+ email_project_members?: boolean
+}
+
+/**
+ * The settings of a new alert. Every one but source_config has a default, which is stored.
+ */
+export interface WarehouseSourcePlatformAlertConfigurationCreateApi {
+ /** Product whose data the alert evaluates. It cannot change after the create. */
+ source_kind: WarehouseSourcePlatformAlertConfigurationCreateApiSourceKind
+ /**
+ * 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 warehouse_source alert. The bound the alert is evaluated against is under condition. */
+ source_config: WarehouseSourceAlertConfigApi
+ /** How the alert splits its results into instances. Defaults to mode single. */
+ grouping?: GroupingApi
+ /** Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. Defaults to null. */
+ schedule_restriction?: AlertScheduleRestrictionApi | null
+ /**
+ * Number of recent checks considered when deciding to fire. Defaults to 1.
+ * @minimum 1
+ * @maximum 10
+ */
+ evaluation_periods?: number
+ /**
+ * Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods. Defaults to 1.
+ * @minimum 1
+ * @maximum 10
+ */
+ datapoints_to_alarm?: number
+ /**
+ * Minimum minutes between notifications for the same alert. Defaults to 0.
+ * @minimum 0
+ * @maximum 2147483647
+ */
+ cooldown_minutes?: number
+}
+
+export type PlatformAlertConfigurationCreateApi =
+ | LogsPlatformAlertConfigurationCreateApi
+ | WarehouseDestinationPlatformAlertConfigurationCreateApi
+ | WarehouseSourcePlatformAlertConfigurationCreateApi
/**
* Product whose data the alert evaluates. It cannot change, so it must match the stored value.
@@ -884,9 +1023,109 @@ export interface LogsPlatformAlertConfigurationEditApi {
cooldown_minutes: number
}
+/**
+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.
+ */
+export type WarehouseDestinationPlatformAlertConfigurationEditApiSourceKind =
+ (typeof WarehouseDestinationPlatformAlertConfigurationEditApiSourceKind)[keyof typeof WarehouseDestinationPlatformAlertConfigurationEditApiSourceKind]
+
+export const WarehouseDestinationPlatformAlertConfigurationEditApiSourceKind = {
+ WarehouseDestination: 'warehouse_destination',
+} as const
+
+/**
+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.
+ */
+export interface WarehouseDestinationPlatformAlertConfigurationEditApi {
+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */
+ source_kind: WarehouseDestinationPlatformAlertConfigurationEditApiSourceKind
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 255
+ */
+ name: string
+ /** Whether the alert is evaluated on schedule. */
+ enabled: boolean
+ /** Settings for a warehouse_destination alert. The bound the alert is evaluated against is under condition. */
+ source_config: WarehouseDestinationAlertConfigApi
+ /** How the alert splits its results into instances. */
+ grouping: GroupingApi
+ /** Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. */
+ schedule_restriction: AlertScheduleRestrictionApi | null
+ /**
+ * Number of recent checks considered when deciding to fire.
+ * @minimum 1
+ * @maximum 10
+ */
+ evaluation_periods: number
+ /**
+ * Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.
+ * @minimum 1
+ * @maximum 10
+ */
+ datapoints_to_alarm: number
+ /**
+ * Minimum minutes between notifications for the same alert.
+ * @minimum 0
+ * @maximum 2147483647
+ */
+ cooldown_minutes: number
+}
+
+/**
+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.
+ */
+export type WarehouseSourcePlatformAlertConfigurationEditApiSourceKind =
+ (typeof WarehouseSourcePlatformAlertConfigurationEditApiSourceKind)[keyof typeof WarehouseSourcePlatformAlertConfigurationEditApiSourceKind]
+
+export const WarehouseSourcePlatformAlertConfigurationEditApiSourceKind = {
+ WarehouseSource: 'warehouse_source',
+} as const
+
+/**
+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.
+ */
+export interface WarehouseSourcePlatformAlertConfigurationEditApi {
+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */
+ source_kind: WarehouseSourcePlatformAlertConfigurationEditApiSourceKind
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 255
+ */
+ name: string
+ /** Whether the alert is evaluated on schedule. */
+ enabled: boolean
+ /** Settings for a warehouse_source alert. The bound the alert is evaluated against is under condition. */
+ source_config: WarehouseSourceAlertConfigApi
+ /** How the alert splits its results into instances. */
+ grouping: GroupingApi
+ /** Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. */
+ schedule_restriction: AlertScheduleRestrictionApi | null
+ /**
+ * Number of recent checks considered when deciding to fire.
+ * @minimum 1
+ * @maximum 10
+ */
+ evaluation_periods: number
+ /**
+ * Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.
+ * @minimum 1
+ * @maximum 10
+ */
+ datapoints_to_alarm: number
+ /**
+ * Minimum minutes between notifications for the same alert.
+ * @minimum 0
+ * @maximum 2147483647
+ */
+ cooldown_minutes: number
+}
+
export type PlatformAlertConfigurationEditApi =
| InsightPlatformAlertConfigurationEditApi
| LogsPlatformAlertConfigurationEditApi
+ | WarehouseDestinationPlatformAlertConfigurationEditApi
+ | WarehouseSourcePlatformAlertConfigurationEditApi
/**
* Product whose data the alert evaluates. It cannot change, so it must match the stored value.
@@ -986,9 +1225,109 @@ export interface PatchedLogsPlatformAlertConfigurationEditApi {
cooldown_minutes?: number
}
+/**
+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.
+ */
+export type PatchedWarehouseDestinationPlatformAlertConfigurationEditApiSourceKind =
+ (typeof PatchedWarehouseDestinationPlatformAlertConfigurationEditApiSourceKind)[keyof typeof PatchedWarehouseDestinationPlatformAlertConfigurationEditApiSourceKind]
+
+export const PatchedWarehouseDestinationPlatformAlertConfigurationEditApiSourceKind = {
+ WarehouseDestination: 'warehouse_destination',
+} as const
+
+/**
+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.
+ */
+export interface PatchedWarehouseDestinationPlatformAlertConfigurationEditApi {
+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */
+ source_kind: PatchedWarehouseDestinationPlatformAlertConfigurationEditApiSourceKind
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 255
+ */
+ name?: string
+ /** Whether the alert is evaluated on schedule. */
+ enabled?: boolean
+ /** Settings for a warehouse_destination alert. The bound the alert is evaluated against is under condition. */
+ source_config?: WarehouseDestinationAlertConfigApi
+ /** How the alert splits its results into instances. */
+ grouping?: GroupingApi
+ /** Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. */
+ schedule_restriction?: AlertScheduleRestrictionApi | null
+ /**
+ * Number of recent checks considered when deciding to fire.
+ * @minimum 1
+ * @maximum 10
+ */
+ evaluation_periods?: number
+ /**
+ * Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.
+ * @minimum 1
+ * @maximum 10
+ */
+ datapoints_to_alarm?: number
+ /**
+ * Minimum minutes between notifications for the same alert.
+ * @minimum 0
+ * @maximum 2147483647
+ */
+ cooldown_minutes?: number
+}
+
+/**
+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.
+ */
+export type PatchedWarehouseSourcePlatformAlertConfigurationEditApiSourceKind =
+ (typeof PatchedWarehouseSourcePlatformAlertConfigurationEditApiSourceKind)[keyof typeof PatchedWarehouseSourcePlatformAlertConfigurationEditApiSourceKind]
+
+export const PatchedWarehouseSourcePlatformAlertConfigurationEditApiSourceKind = {
+ WarehouseSource: 'warehouse_source',
+} as const
+
+/**
+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.
+ */
+export interface PatchedWarehouseSourcePlatformAlertConfigurationEditApi {
+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */
+ source_kind: PatchedWarehouseSourcePlatformAlertConfigurationEditApiSourceKind
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 255
+ */
+ name?: string
+ /** Whether the alert is evaluated on schedule. */
+ enabled?: boolean
+ /** Settings for a warehouse_source alert. The bound the alert is evaluated against is under condition. */
+ source_config?: WarehouseSourceAlertConfigApi
+ /** How the alert splits its results into instances. */
+ grouping?: GroupingApi
+ /** Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. */
+ schedule_restriction?: AlertScheduleRestrictionApi | null
+ /**
+ * Number of recent checks considered when deciding to fire.
+ * @minimum 1
+ * @maximum 10
+ */
+ evaluation_periods?: number
+ /**
+ * Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.
+ * @minimum 1
+ * @maximum 10
+ */
+ datapoints_to_alarm?: number
+ /**
+ * Minimum minutes between notifications for the same alert.
+ * @minimum 0
+ * @maximum 2147483647
+ */
+ cooldown_minutes?: number
+}
+
export type PatchedPlatformAlertConfigurationEditApi =
| PatchedInsightPlatformAlertConfigurationEditApi
| PatchedLogsPlatformAlertConfigurationEditApi
+ | PatchedWarehouseDestinationPlatformAlertConfigurationEditApi
+ | PatchedWarehouseSourcePlatformAlertConfigurationEditApi
export interface PlatformAlertGroupSnoozeApi {
/**
diff --git a/products/alerts_platform/frontend/generated/api.zod.ts b/products/alerts_platform/frontend/generated/api.zod.ts
index 12232bd064b8..42dd19c9519a 100644
--- a/products/alerts_platform/frontend/generated/api.zod.ts
+++ b/products/alerts_platform/frontend/generated/api.zod.ts
@@ -30,182 +30,1080 @@ export const platformAlertsCreateBodyOneCooldownMinutesDefault = 0
export const platformAlertsCreateBodyOneCooldownMinutesMin = 0
export const platformAlertsCreateBodyOneCooldownMinutesMax = 2147483647
-export const PlatformAlertsCreateBody = /* @__PURE__ */ zod
- .object({
- source_kind: zod
- .enum(['logs'])
- .describe('Product whose data the alert evaluates. It cannot change after the create.'),
- name: zod
- .string()
- .max(platformAlertsCreateBodyOneNameMax)
- .default(platformAlertsCreateBodyOneNameDefault)
- .describe("Human-readable name of the alert. Defaults to 'Untitled alert'."),
- enabled: zod
- .boolean()
- .default(platformAlertsCreateBodyOneEnabledDefault)
- .describe('Whether the alert is evaluated on schedule. Defaults to true.'),
- source_config: zod
- .object({
- filters: zod
- .object({
- filterGroup: zod
- .union([
+export const platformAlertsCreateBodyTwoNameDefault = `Untitled alert`
+export const platformAlertsCreateBodyTwoNameMax = 255
+
+export const platformAlertsCreateBodyTwoEnabledDefault = true
+export const platformAlertsCreateBodyTwoSourceConfigOneDestinationIdsMax = 100
+
+export const platformAlertsCreateBodyTwoSourceConfigOneEmailProjectMembersDefault = false
+export const platformAlertsCreateBodyTwoGroupingOneMaxInstancesDefault = 100
+export const platformAlertsCreateBodyTwoGroupingOneMaxInstancesMax = 100
+
+export const platformAlertsCreateBodyTwoGroupingOneOnOverflowDefault = `degrade_visible`
+export const platformAlertsCreateBodyTwoEvaluationPeriodsDefault = 1
+export const platformAlertsCreateBodyTwoEvaluationPeriodsMax = 10
+
+export const platformAlertsCreateBodyTwoDatapointsToAlarmDefault = 1
+export const platformAlertsCreateBodyTwoDatapointsToAlarmMax = 10
+
+export const platformAlertsCreateBodyTwoCooldownMinutesDefault = 0
+export const platformAlertsCreateBodyTwoCooldownMinutesMin = 0
+export const platformAlertsCreateBodyTwoCooldownMinutesMax = 2147483647
+
+export const platformAlertsCreateBodyThreeNameDefault = `Untitled alert`
+export const platformAlertsCreateBodyThreeNameMax = 255
+
+export const platformAlertsCreateBodyThreeEnabledDefault = true
+export const platformAlertsCreateBodyThreeSourceConfigOneSourceIdsMax = 100
+
+export const platformAlertsCreateBodyThreeSourceConfigOneGroupByDefault = `source`
+export const platformAlertsCreateBodyThreeSourceConfigOneIncludeBillingLimitsDefault = false
+export const platformAlertsCreateBodyThreeSourceConfigOneEmailProjectMembersDefault = false
+export const platformAlertsCreateBodyThreeGroupingOneMaxInstancesDefault = 100
+export const platformAlertsCreateBodyThreeGroupingOneMaxInstancesMax = 100
+
+export const platformAlertsCreateBodyThreeGroupingOneOnOverflowDefault = `degrade_visible`
+export const platformAlertsCreateBodyThreeEvaluationPeriodsDefault = 1
+export const platformAlertsCreateBodyThreeEvaluationPeriodsMax = 10
+
+export const platformAlertsCreateBodyThreeDatapointsToAlarmDefault = 1
+export const platformAlertsCreateBodyThreeDatapointsToAlarmMax = 10
+
+export const platformAlertsCreateBodyThreeCooldownMinutesDefault = 0
+export const platformAlertsCreateBodyThreeCooldownMinutesMin = 0
+export const platformAlertsCreateBodyThreeCooldownMinutesMax = 2147483647
+
+export const PlatformAlertsCreateBody = /* @__PURE__ */ zod.union([
+ zod
+ .object({
+ source_kind: zod
+ .enum(['logs'])
+ .describe('Product whose data the alert evaluates. It cannot change after the create.'),
+ name: zod
+ .string()
+ .max(platformAlertsCreateBodyOneNameMax)
+ .default(platformAlertsCreateBodyOneNameDefault)
+ .describe("Human-readable name of the alert. Defaults to 'Untitled alert'."),
+ enabled: zod
+ .boolean()
+ .default(platformAlertsCreateBodyOneEnabledDefault)
+ .describe('Whether the alert is evaluated on schedule. Defaults to true.'),
+ source_config: zod
+ .object({
+ filters: zod
+ .object({
+ filterGroup: zod
+ .union([
+ zod.object({
+ type: zod.enum(['AND', 'OR']),
+ values: zod.array(
+ zod
+ .record(zod.string(), zod.unknown())
+ .describe(
+ 'Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)'
+ )
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional(),
+ serviceNames: zod.union([zod.array(zod.string()), zod.null()]).optional(),
+ severityLevels: zod
+ .union([
+ zod.array(zod.enum(['trace', 'debug', 'info', 'warn', 'error', 'fatal'])),
+ zod.null(),
+ ])
+ .optional(),
+ })
+ .describe(
+ 'The logs the alert counts: severityLevels, serviceNames, or a filterGroup of property filters. An enabled alert needs at least one.'
+ ),
+ condition: zod
+ .object({
+ threshold_count: zod
+ .number()
+ .min(platformAlertsCreateBodyOneSourceConfigOneConditionThresholdCountMin)
+ .max(platformAlertsCreateBodyOneSourceConfigOneConditionThresholdCountMax)
+ .describe(
+ 'Number of matching log entries in the window that breaches the threshold. Use 0 with the above operator to fire on any matching log.'
+ ),
+ threshold_operator: zod
+ .enum(['above', 'below'])
+ .describe('Whether the alert fires when the count is above or below the threshold.'),
+ window_minutes: zod
+ .union([
+ zod.literal(5),
+ zod.literal(10),
+ zod.literal(15),
+ zod.literal(30),
+ zod.literal(60),
+ ])
+ .describe('Time window in minutes over which logs are counted.'),
+ })
+ .describe('The bound the count is checked against.'),
+ })
+ .describe('Settings for a logs alert. The bound the alert is evaluated against is under condition.'),
+ grouping: zod
+ .object({
+ mode: zod
+ .enum(['single', 'by_result_labels'])
+ .describe('\* `single` - Single\n\* `by_result_labels` - By result labels')
+ .describe(
+ 'single keeps one instance for the whole alert. by_result_labels keeps one instance per distinct value of the labels in keys, so each group fires and resolves on its own.\n\n\* `single` - Single\n\* `by_result_labels` - By result labels'
+ ),
+ keys: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Result labels whose values make a group, such as service_name. Empty for mode single, required for by_result_labels. Changing them deletes the existing instances and closes their notification threads without a message.'
+ ),
+ max_instances: zod
+ .number()
+ .min(1)
+ .max(platformAlertsCreateBodyOneGroupingOneMaxInstancesMax)
+ .default(platformAlertsCreateBodyOneGroupingOneMaxInstancesDefault)
+ .describe(
+ 'Most instances the alert keeps at once. Groups past it are not tracked, and the last message says how many were left out.'
+ ),
+ on_overflow: zod
+ .enum(['degrade_visible'])
+ .describe('\* `degrade_visible` - Degrade visible')
+ .default(platformAlertsCreateBodyOneGroupingOneOnOverflowDefault)
+ .describe(
+ 'What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'
+ ),
+ })
+ .optional()
+ .describe('How the alert splits its results into instances. Defaults to mode single.'),
+ schedule_restriction: zod
+ .union([
+ zod.object({
+ blocked_windows: zod
+ .array(
+ zod.object({
+ start: zod
+ .string()
+ .describe(
+ 'Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)).'
+ ),
+ end: zod
+ .string()
+ .describe(
+ 'End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally.'
+ ),
+ })
+ )
+ .describe(
+ 'Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. Defaults to null.'
+ ),
+ evaluation_periods: zod
+ .number()
+ .min(1)
+ .max(platformAlertsCreateBodyOneEvaluationPeriodsMax)
+ .default(platformAlertsCreateBodyOneEvaluationPeriodsDefault)
+ .describe('Number of recent checks considered when deciding to fire. Defaults to 1.'),
+ datapoints_to_alarm: zod
+ .number()
+ .min(1)
+ .max(platformAlertsCreateBodyOneDatapointsToAlarmMax)
+ .default(platformAlertsCreateBodyOneDatapointsToAlarmDefault)
+ .describe(
+ 'Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods. Defaults to 1.'
+ ),
+ cooldown_minutes: zod
+ .number()
+ .min(platformAlertsCreateBodyOneCooldownMinutesMin)
+ .max(platformAlertsCreateBodyOneCooldownMinutesMax)
+ .default(platformAlertsCreateBodyOneCooldownMinutesDefault)
+ .describe('Minimum minutes between notifications for the same alert. Defaults to 0.'),
+ })
+ .describe('The settings of a new alert. Every one but source_config has a default, which is stored.'),
+ zod
+ .object({
+ source_kind: zod
+ .enum(['warehouse_destination'])
+ .describe('Product whose data the alert evaluates. It cannot change after the create.'),
+ name: zod
+ .string()
+ .max(platformAlertsCreateBodyTwoNameMax)
+ .default(platformAlertsCreateBodyTwoNameDefault)
+ .describe("Human-readable name of the alert. Defaults to 'Untitled alert'."),
+ enabled: zod
+ .boolean()
+ .default(platformAlertsCreateBodyTwoEnabledDefault)
+ .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)
+ .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(platformAlertsCreateBodyTwoGroupingOneMaxInstancesMax)
+ .default(platformAlertsCreateBodyTwoGroupingOneMaxInstancesDefault)
+ .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(platformAlertsCreateBodyTwoGroupingOneOnOverflowDefault)
+ .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(platformAlertsCreateBodyTwoEvaluationPeriodsMax)
+ .default(platformAlertsCreateBodyTwoEvaluationPeriodsDefault)
+ .describe('Number of recent checks considered when deciding to fire. Defaults to 1.'),
+ datapoints_to_alarm: zod
+ .number()
+ .min(1)
+ .max(platformAlertsCreateBodyTwoDatapointsToAlarmMax)
+ .default(platformAlertsCreateBodyTwoDatapointsToAlarmDefault)
+ .describe(
+ 'Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods. Defaults to 1.'
+ ),
+ cooldown_minutes: zod
+ .number()
+ .min(platformAlertsCreateBodyTwoCooldownMinutesMin)
+ .max(platformAlertsCreateBodyTwoCooldownMinutesMax)
+ .default(platformAlertsCreateBodyTwoCooldownMinutesDefault)
+ .describe('Minimum minutes between notifications for the same alert. Defaults to 0.'),
+ })
+ .describe('The settings of a new alert. Every one but source_config has a default, which is stored.'),
+ 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(platformAlertsCreateBodyThreeNameMax)
+ .default(platformAlertsCreateBodyThreeNameDefault)
+ .describe("Human-readable name of the alert. Defaults to 'Untitled alert'."),
+ enabled: zod
+ .boolean()
+ .default(platformAlertsCreateBodyThreeEnabledDefault)
+ .describe('Whether the alert is evaluated on schedule. Defaults to true.'),
+ source_config: zod
+ .object({
+ source_ids: zod
+ .array(zod.uuid())
+ .max(platformAlertsCreateBodyThreeSourceConfigOneSourceIdsMax)
+ .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)
+ .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)
+ .describe(
+ "Whether a table that stops syncing at the project's billing limit also fires the alert."
+ ),
+ 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_source 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.'),
+ })
+ .describe('The settings of a new alert. Every one but source_config has a default, which is stored.'),
+])
+
+export const platformAlertsUpdateBodyOneNameMax = 255
+
+export const platformAlertsUpdateBodyOneGroupingOneMaxInstancesDefault = 100
+export const platformAlertsUpdateBodyOneGroupingOneMaxInstancesMax = 100
+
+export const platformAlertsUpdateBodyOneGroupingOneOnOverflowDefault = `degrade_visible`
+export const platformAlertsUpdateBodyOneEvaluationPeriodsMax = 10
+
+export const platformAlertsUpdateBodyOneDatapointsToAlarmMax = 10
+
+export const platformAlertsUpdateBodyOneCooldownMinutesMin = 0
+export const platformAlertsUpdateBodyOneCooldownMinutesMax = 2147483647
+
+export const platformAlertsUpdateBodyTwoNameMax = 255
+
+export const platformAlertsUpdateBodyTwoSourceConfigOneConditionThresholdCountMin = 0
+export const platformAlertsUpdateBodyTwoSourceConfigOneConditionThresholdCountMax = 2147483647
+
+export const platformAlertsUpdateBodyTwoGroupingOneMaxInstancesDefault = 100
+export const platformAlertsUpdateBodyTwoGroupingOneMaxInstancesMax = 100
+
+export const platformAlertsUpdateBodyTwoGroupingOneOnOverflowDefault = `degrade_visible`
+export const platformAlertsUpdateBodyTwoEvaluationPeriodsMax = 10
+
+export const platformAlertsUpdateBodyTwoDatapointsToAlarmMax = 10
+
+export const platformAlertsUpdateBodyTwoCooldownMinutesMin = 0
+export const platformAlertsUpdateBodyTwoCooldownMinutesMax = 2147483647
+
+export const platformAlertsUpdateBodyThreeNameMax = 255
+
+export const platformAlertsUpdateBodyThreeSourceConfigOneDestinationIdsMax = 100
+
+export const platformAlertsUpdateBodyThreeSourceConfigOneEmailProjectMembersDefault = false
+export const platformAlertsUpdateBodyThreeGroupingOneMaxInstancesDefault = 100
+export const platformAlertsUpdateBodyThreeGroupingOneMaxInstancesMax = 100
+
+export const platformAlertsUpdateBodyThreeGroupingOneOnOverflowDefault = `degrade_visible`
+export const platformAlertsUpdateBodyThreeEvaluationPeriodsMax = 10
+
+export const platformAlertsUpdateBodyThreeDatapointsToAlarmMax = 10
+
+export const platformAlertsUpdateBodyThreeCooldownMinutesMin = 0
+export const platformAlertsUpdateBodyThreeCooldownMinutesMax = 2147483647
+
+export const platformAlertsUpdateBodyFourNameMax = 255
+
+export const platformAlertsUpdateBodyFourSourceConfigOneSourceIdsMax = 100
+
+export const platformAlertsUpdateBodyFourSourceConfigOneGroupByDefault = `source`
+export const platformAlertsUpdateBodyFourSourceConfigOneIncludeBillingLimitsDefault = false
+export const platformAlertsUpdateBodyFourSourceConfigOneEmailProjectMembersDefault = false
+export const platformAlertsUpdateBodyFourGroupingOneMaxInstancesDefault = 100
+export const platformAlertsUpdateBodyFourGroupingOneMaxInstancesMax = 100
+
+export const platformAlertsUpdateBodyFourGroupingOneOnOverflowDefault = `degrade_visible`
+export const platformAlertsUpdateBodyFourEvaluationPeriodsMax = 10
+
+export const platformAlertsUpdateBodyFourDatapointsToAlarmMax = 10
+
+export const platformAlertsUpdateBodyFourCooldownMinutesMin = 0
+export const platformAlertsUpdateBodyFourCooldownMinutesMax = 2147483647
+
+export const PlatformAlertsUpdateBody = /* @__PURE__ */ zod.union([
+ zod
+ .object({
+ source_kind: zod
+ .enum(['insight'])
+ .describe(
+ 'Product whose data the alert evaluates. It cannot change, so it must match the stored value.'
+ ),
+ name: zod.string().max(platformAlertsUpdateBodyOneNameMax).describe('Human-readable name of the alert.'),
+ enabled: zod.boolean().describe('Whether the alert is evaluated on schedule.'),
+ source_config: zod
+ .object({
+ insight_id: zod
+ .number()
+ .describe('The insight the alert checks. It cannot change through this API.'),
+ condition: zod
+ .object({
+ threshold: zod
+ .union([
+ zod.object({
+ bounds: zod
+ .union([
+ zod.object({
+ lower: zod
+ .union([zod.number(), zod.null()])
+ .optional()
+ .describe(
+ 'Alert fires when the value drops below this number.'
+ ),
+ upper: zod
+ .union([zod.number(), zod.null()])
+ .optional()
+ .describe('Alert fires when the value exceeds this number.'),
+ }),
+ zod.null(),
+ ])
+ .optional(),
+ type: zod
+ .enum(['absolute', 'percentage'])
+ .describe(
+ 'Whether bounds are compared as absolute values or as percentage change from the previous interval.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .describe(
+ "The bounds the insight's value is checked against, absolute or as a percentage change."
+ ),
+ comparison: zod
+ .object({
+ type: zod.enum(['absolute_value', 'relative_increase', 'relative_decrease']),
+ })
+ .describe(
+ 'How the value is compared: as it is, or as an increase or decrease from the previous interval.'
+ ),
+ detector: zod
+ .union([zod.record(zod.string(), zod.unknown()), zod.null()])
+ .optional()
+ .describe(
+ "The anomaly detector the alert uses in place of its threshold, or null for a threshold alert. It can't change through this API."
+ ),
+ })
+ .describe("The bound the insight's value is checked against."),
+ })
+ .describe('Settings for a insight alert. The bound the alert is evaluated against is under condition.'),
+ grouping: zod
+ .object({
+ mode: zod
+ .enum(['single', 'by_result_labels'])
+ .describe('\* `single` - Single\n\* `by_result_labels` - By result labels')
+ .describe(
+ 'single keeps one instance for the whole alert. by_result_labels keeps one instance per distinct value of the labels in keys, so each group fires and resolves on its own.\n\n\* `single` - Single\n\* `by_result_labels` - By result labels'
+ ),
+ keys: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Result labels whose values make a group, such as service_name. Empty for mode single, required for by_result_labels. Changing them deletes the existing instances and closes their notification threads without a message.'
+ ),
+ max_instances: zod
+ .number()
+ .min(1)
+ .max(platformAlertsUpdateBodyOneGroupingOneMaxInstancesMax)
+ .default(platformAlertsUpdateBodyOneGroupingOneMaxInstancesDefault)
+ .describe(
+ 'Most instances the alert keeps at once. Groups past it are not tracked, and the last message says how many were left out.'
+ ),
+ on_overflow: zod
+ .enum(['degrade_visible'])
+ .describe('\* `degrade_visible` - Degrade visible')
+ .default(platformAlertsUpdateBodyOneGroupingOneOnOverflowDefault)
+ .describe(
+ 'What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'
+ ),
+ })
+ .describe('How the alert splits its results into instances.'),
+ schedule_restriction: zod
+ .union([
+ zod.object({
+ blocked_windows: zod
+ .array(
+ zod.object({
+ start: zod
+ .string()
+ .describe(
+ 'Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)).'
+ ),
+ end: zod
+ .string()
+ .describe(
+ 'End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally.'
+ ),
+ })
+ )
+ .describe(
+ 'Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .describe(
+ 'Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours.'
+ ),
+ evaluation_periods: zod
+ .number()
+ .min(1)
+ .max(platformAlertsUpdateBodyOneEvaluationPeriodsMax)
+ .describe('Number of recent checks considered when deciding to fire.'),
+ datapoints_to_alarm: zod
+ .number()
+ .min(1)
+ .max(platformAlertsUpdateBodyOneDatapointsToAlarmMax)
+ .describe(
+ 'Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.'
+ ),
+ cooldown_minutes: zod
+ .number()
+ .min(platformAlertsUpdateBodyOneCooldownMinutesMin)
+ .max(platformAlertsUpdateBodyOneCooldownMinutesMax)
+ .describe('Minimum minutes between notifications for the same alert.'),
+ })
+ .describe('The settings an edit can change. Each source kind subclasses it with a typed `source_config`.'),
+ zod
+ .object({
+ source_kind: zod
+ .enum(['logs'])
+ .describe(
+ 'Product whose data the alert evaluates. It cannot change, so it must match the stored value.'
+ ),
+ name: zod.string().max(platformAlertsUpdateBodyTwoNameMax).describe('Human-readable name of the alert.'),
+ enabled: zod.boolean().describe('Whether the alert is evaluated on schedule.'),
+ source_config: zod
+ .object({
+ filters: zod
+ .object({
+ filterGroup: zod
+ .union([
+ zod.object({
+ type: zod.enum(['AND', 'OR']),
+ values: zod.array(
+ zod
+ .record(zod.string(), zod.unknown())
+ .describe(
+ 'Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)'
+ )
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional(),
+ serviceNames: zod.union([zod.array(zod.string()), zod.null()]).optional(),
+ severityLevels: zod
+ .union([
+ zod.array(zod.enum(['trace', 'debug', 'info', 'warn', 'error', 'fatal'])),
+ zod.null(),
+ ])
+ .optional(),
+ })
+ .describe(
+ 'The logs the alert counts: severityLevels, serviceNames, or a filterGroup of property filters. An enabled alert needs at least one.'
+ ),
+ condition: zod
+ .object({
+ threshold_count: zod
+ .number()
+ .min(platformAlertsUpdateBodyTwoSourceConfigOneConditionThresholdCountMin)
+ .max(platformAlertsUpdateBodyTwoSourceConfigOneConditionThresholdCountMax)
+ .describe(
+ 'Number of matching log entries in the window that breaches the threshold. Use 0 with the above operator to fire on any matching log.'
+ ),
+ threshold_operator: zod
+ .enum(['above', 'below'])
+ .describe('Whether the alert fires when the count is above or below the threshold.'),
+ window_minutes: zod
+ .union([
+ zod.literal(5),
+ zod.literal(10),
+ zod.literal(15),
+ zod.literal(30),
+ zod.literal(60),
+ ])
+ .describe('Time window in minutes over which logs are counted.'),
+ })
+ .describe('The bound the count is checked against.'),
+ })
+ .describe('Settings for a logs alert. The bound the alert is evaluated against is under condition.'),
+ grouping: zod
+ .object({
+ mode: zod
+ .enum(['single', 'by_result_labels'])
+ .describe('\* `single` - Single\n\* `by_result_labels` - By result labels')
+ .describe(
+ 'single keeps one instance for the whole alert. by_result_labels keeps one instance per distinct value of the labels in keys, so each group fires and resolves on its own.\n\n\* `single` - Single\n\* `by_result_labels` - By result labels'
+ ),
+ keys: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Result labels whose values make a group, such as service_name. Empty for mode single, required for by_result_labels. Changing them deletes the existing instances and closes their notification threads without a message.'
+ ),
+ max_instances: zod
+ .number()
+ .min(1)
+ .max(platformAlertsUpdateBodyTwoGroupingOneMaxInstancesMax)
+ .default(platformAlertsUpdateBodyTwoGroupingOneMaxInstancesDefault)
+ .describe(
+ 'Most instances the alert keeps at once. Groups past it are not tracked, and the last message says how many were left out.'
+ ),
+ on_overflow: zod
+ .enum(['degrade_visible'])
+ .describe('\* `degrade_visible` - Degrade visible')
+ .default(platformAlertsUpdateBodyTwoGroupingOneOnOverflowDefault)
+ .describe(
+ 'What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'
+ ),
+ })
+ .describe('How the alert splits its results into instances.'),
+ schedule_restriction: zod
+ .union([
+ zod.object({
+ blocked_windows: zod
+ .array(
zod.object({
- type: zod.enum(['AND', 'OR']),
- values: zod.array(
- zod
- .record(zod.string(), zod.unknown())
- .describe(
- 'Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)'
- )
- ),
- }),
- zod.null(),
- ])
- .optional(),
- serviceNames: zod.union([zod.array(zod.string()), zod.null()]).optional(),
- severityLevels: zod
- .union([
- zod.array(zod.enum(['trace', 'debug', 'info', 'warn', 'error', 'fatal'])),
- zod.null(),
- ])
- .optional(),
- })
- .describe(
- 'The logs the alert counts: severityLevels, serviceNames, or a filterGroup of property filters. An enabled alert needs at least one.'
- ),
- condition: zod
- .object({
- threshold_count: zod
- .number()
- .min(platformAlertsCreateBodyOneSourceConfigOneConditionThresholdCountMin)
- .max(platformAlertsCreateBodyOneSourceConfigOneConditionThresholdCountMax)
+ start: zod
+ .string()
+ .describe(
+ 'Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)).'
+ ),
+ end: zod
+ .string()
+ .describe(
+ 'End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally.'
+ ),
+ })
+ )
+ .describe(
+ 'Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .describe(
+ 'Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours.'
+ ),
+ evaluation_periods: zod
+ .number()
+ .min(1)
+ .max(platformAlertsUpdateBodyTwoEvaluationPeriodsMax)
+ .describe('Number of recent checks considered when deciding to fire.'),
+ datapoints_to_alarm: zod
+ .number()
+ .min(1)
+ .max(platformAlertsUpdateBodyTwoDatapointsToAlarmMax)
+ .describe(
+ 'Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.'
+ ),
+ cooldown_minutes: zod
+ .number()
+ .min(platformAlertsUpdateBodyTwoCooldownMinutesMin)
+ .max(platformAlertsUpdateBodyTwoCooldownMinutesMax)
+ .describe('Minimum minutes between notifications for the same alert.'),
+ })
+ .describe('The settings an edit can change. Each source kind subclasses it with a typed `source_config`.'),
+ 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(platformAlertsUpdateBodyThreeNameMax).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)
+ .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)
+ .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(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.'),
+ })
+ .describe('The settings an edit can change. Each source kind subclasses it with a typed `source_config`.'),
+ zod
+ .object({
+ source_kind: zod
+ .enum(['warehouse_source'])
+ .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({
+ source_ids: zod
+ .array(zod.uuid())
+ .max(platformAlertsUpdateBodyFourSourceConfigOneSourceIdsMax)
+ .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)
+ .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)
+ .describe(
+ "Whether a table that stops syncing at the project's billing limit also fires the alert."
+ ),
+ email_project_members: zod
+ .boolean()
+ .default(platformAlertsUpdateBodyFourSourceConfigOneEmailProjectMembersDefault)
+ .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_source 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(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(platformAlertsUpdateBodyFourGroupingOneOnOverflowDefault)
+ .describe(
+ 'What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'
+ ),
+ })
+ .describe('How the alert splits its results into instances.'),
+ schedule_restriction: zod
+ .union([
+ zod.object({
+ blocked_windows: zod
+ .array(
+ zod.object({
+ start: zod
+ .string()
+ .describe(
+ 'Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)).'
+ ),
+ end: zod
+ .string()
+ .describe(
+ 'End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally.'
+ ),
+ })
+ )
.describe(
- 'Number of matching log entries in the window that breaches the threshold. Use 0 with the above operator to fire on any matching log.'
+ 'Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours.'
),
- threshold_operator: zod
- .enum(['above', 'below'])
- .describe('Whether the alert fires when the count is above or below the threshold.'),
- window_minutes: zod
- .union([zod.literal(5), zod.literal(10), zod.literal(15), zod.literal(30), zod.literal(60)])
- .describe('Time window in minutes over which logs are counted.'),
- })
- .describe('The bound the count is checked against.'),
- })
- .describe('Settings for a logs alert. The bound the alert is evaluated against is under condition.'),
- grouping: zod
- .object({
- mode: zod
- .enum(['single', 'by_result_labels'])
- .describe('\* `single` - Single\n\* `by_result_labels` - By result labels')
- .describe(
- 'single keeps one instance for the whole alert. by_result_labels keeps one instance per distinct value of the labels in keys, so each group fires and resolves on its own.\n\n\* `single` - Single\n\* `by_result_labels` - By result labels'
- ),
- keys: zod
- .array(zod.string())
- .optional()
- .describe(
- 'Result labels whose values make a group, such as service_name. Empty for mode single, required for by_result_labels. Changing them deletes the existing instances and closes their notification threads without a message.'
- ),
- max_instances: zod
- .number()
- .min(1)
- .max(platformAlertsCreateBodyOneGroupingOneMaxInstancesMax)
- .default(platformAlertsCreateBodyOneGroupingOneMaxInstancesDefault)
- .describe(
- 'Most instances the alert keeps at once. Groups past it are not tracked, and the last message says how many were left out.'
- ),
- on_overflow: zod
- .enum(['degrade_visible'])
- .describe('\* `degrade_visible` - Degrade visible')
- .default(platformAlertsCreateBodyOneGroupingOneOnOverflowDefault)
- .describe(
- 'What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'
- ),
- })
- .optional()
- .describe('How the alert splits its results into instances. Defaults to mode single.'),
- schedule_restriction: zod
- .union([
- zod.object({
- blocked_windows: zod
- .array(
- zod.object({
- start: zod
- .string()
- .describe(
- 'Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)).'
- ),
- end: zod
- .string()
- .describe(
- 'End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally.'
- ),
- })
- )
- .describe(
- 'Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours.'
- ),
- }),
- zod.null(),
- ])
- .optional()
- .describe(
- 'Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. Defaults to null.'
- ),
- evaluation_periods: zod
- .number()
- .min(1)
- .max(platformAlertsCreateBodyOneEvaluationPeriodsMax)
- .default(platformAlertsCreateBodyOneEvaluationPeriodsDefault)
- .describe('Number of recent checks considered when deciding to fire. Defaults to 1.'),
- datapoints_to_alarm: zod
- .number()
- .min(1)
- .max(platformAlertsCreateBodyOneDatapointsToAlarmMax)
- .default(platformAlertsCreateBodyOneDatapointsToAlarmDefault)
- .describe(
- 'Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods. Defaults to 1.'
- ),
- cooldown_minutes: zod
- .number()
- .min(platformAlertsCreateBodyOneCooldownMinutesMin)
- .max(platformAlertsCreateBodyOneCooldownMinutesMax)
- .default(platformAlertsCreateBodyOneCooldownMinutesDefault)
- .describe('Minimum minutes between notifications for the same alert. Defaults to 0.'),
- })
- .describe('The settings of a new alert. Every one but source_config has a default, which is stored.')
+ }),
+ 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(platformAlertsUpdateBodyFourEvaluationPeriodsMax)
+ .describe('Number of recent checks considered when deciding to fire.'),
+ datapoints_to_alarm: zod
+ .number()
+ .min(1)
+ .max(platformAlertsUpdateBodyFourDatapointsToAlarmMax)
+ .describe(
+ 'Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.'
+ ),
+ cooldown_minutes: zod
+ .number()
+ .min(platformAlertsUpdateBodyFourCooldownMinutesMin)
+ .max(platformAlertsUpdateBodyFourCooldownMinutesMax)
+ .describe('Minimum minutes between notifications for the same alert.'),
+ })
+ .describe('The settings an edit can change. Each source kind subclasses it with a typed `source_config`.'),
+])
+
+export const platformAlertsPartialUpdateBodyOneNameMax = 255
+
+export const platformAlertsPartialUpdateBodyOneGroupingOneMaxInstancesDefault = 100
+export const platformAlertsPartialUpdateBodyOneGroupingOneMaxInstancesMax = 100
+
+export const platformAlertsPartialUpdateBodyOneGroupingOneOnOverflowDefault = `degrade_visible`
+export const platformAlertsPartialUpdateBodyOneEvaluationPeriodsMax = 10
+
+export const platformAlertsPartialUpdateBodyOneDatapointsToAlarmMax = 10
+
+export const platformAlertsPartialUpdateBodyOneCooldownMinutesMin = 0
+export const platformAlertsPartialUpdateBodyOneCooldownMinutesMax = 2147483647
+
+export const platformAlertsPartialUpdateBodyTwoNameMax = 255
+
+export const platformAlertsPartialUpdateBodyTwoSourceConfigOneConditionThresholdCountMin = 0
+export const platformAlertsPartialUpdateBodyTwoSourceConfigOneConditionThresholdCountMax = 2147483647
+
+export const platformAlertsPartialUpdateBodyTwoGroupingOneMaxInstancesDefault = 100
+export const platformAlertsPartialUpdateBodyTwoGroupingOneMaxInstancesMax = 100
+
+export const platformAlertsPartialUpdateBodyTwoGroupingOneOnOverflowDefault = `degrade_visible`
+export const platformAlertsPartialUpdateBodyTwoEvaluationPeriodsMax = 10
-export const platformAlertsUpdateBodyOneNameMax = 255
+export const platformAlertsPartialUpdateBodyTwoDatapointsToAlarmMax = 10
-export const platformAlertsUpdateBodyOneGroupingOneMaxInstancesDefault = 100
-export const platformAlertsUpdateBodyOneGroupingOneMaxInstancesMax = 100
+export const platformAlertsPartialUpdateBodyTwoCooldownMinutesMin = 0
+export const platformAlertsPartialUpdateBodyTwoCooldownMinutesMax = 2147483647
-export const platformAlertsUpdateBodyOneGroupingOneOnOverflowDefault = `degrade_visible`
-export const platformAlertsUpdateBodyOneEvaluationPeriodsMax = 10
+export const platformAlertsPartialUpdateBodyThreeNameMax = 255
-export const platformAlertsUpdateBodyOneDatapointsToAlarmMax = 10
+export const platformAlertsPartialUpdateBodyThreeSourceConfigOneDestinationIdsMax = 100
-export const platformAlertsUpdateBodyOneCooldownMinutesMin = 0
-export const platformAlertsUpdateBodyOneCooldownMinutesMax = 2147483647
+export const platformAlertsPartialUpdateBodyThreeSourceConfigOneEmailProjectMembersDefault = false
+export const platformAlertsPartialUpdateBodyThreeGroupingOneMaxInstancesDefault = 100
+export const platformAlertsPartialUpdateBodyThreeGroupingOneMaxInstancesMax = 100
-export const platformAlertsUpdateBodyTwoNameMax = 255
+export const platformAlertsPartialUpdateBodyThreeGroupingOneOnOverflowDefault = `degrade_visible`
+export const platformAlertsPartialUpdateBodyThreeEvaluationPeriodsMax = 10
-export const platformAlertsUpdateBodyTwoSourceConfigOneConditionThresholdCountMin = 0
-export const platformAlertsUpdateBodyTwoSourceConfigOneConditionThresholdCountMax = 2147483647
+export const platformAlertsPartialUpdateBodyThreeDatapointsToAlarmMax = 10
-export const platformAlertsUpdateBodyTwoGroupingOneMaxInstancesDefault = 100
-export const platformAlertsUpdateBodyTwoGroupingOneMaxInstancesMax = 100
+export const platformAlertsPartialUpdateBodyThreeCooldownMinutesMin = 0
+export const platformAlertsPartialUpdateBodyThreeCooldownMinutesMax = 2147483647
-export const platformAlertsUpdateBodyTwoGroupingOneOnOverflowDefault = `degrade_visible`
-export const platformAlertsUpdateBodyTwoEvaluationPeriodsMax = 10
+export const platformAlertsPartialUpdateBodyFourNameMax = 255
-export const platformAlertsUpdateBodyTwoDatapointsToAlarmMax = 10
+export const platformAlertsPartialUpdateBodyFourSourceConfigOneSourceIdsMax = 100
-export const platformAlertsUpdateBodyTwoCooldownMinutesMin = 0
-export const platformAlertsUpdateBodyTwoCooldownMinutesMax = 2147483647
+export const platformAlertsPartialUpdateBodyFourSourceConfigOneGroupByDefault = `source`
+export const platformAlertsPartialUpdateBodyFourSourceConfigOneIncludeBillingLimitsDefault = false
+export const platformAlertsPartialUpdateBodyFourSourceConfigOneEmailProjectMembersDefault = false
+export const platformAlertsPartialUpdateBodyFourGroupingOneMaxInstancesDefault = 100
+export const platformAlertsPartialUpdateBodyFourGroupingOneMaxInstancesMax = 100
-export const PlatformAlertsUpdateBody = /* @__PURE__ */ zod.union([
+export const platformAlertsPartialUpdateBodyFourGroupingOneOnOverflowDefault = `degrade_visible`
+export const platformAlertsPartialUpdateBodyFourEvaluationPeriodsMax = 10
+
+export const platformAlertsPartialUpdateBodyFourDatapointsToAlarmMax = 10
+
+export const platformAlertsPartialUpdateBodyFourCooldownMinutesMin = 0
+export const platformAlertsPartialUpdateBodyFourCooldownMinutesMax = 2147483647
+
+export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod.union([
zod
.object({
source_kind: zod
@@ -213,8 +1111,12 @@ 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(platformAlertsUpdateBodyOneNameMax).describe('Human-readable name of the alert.'),
- enabled: zod.boolean().describe('Whether the alert is evaluated on schedule.'),
+ name: zod
+ .string()
+ .max(platformAlertsPartialUpdateBodyOneNameMax)
+ .optional()
+ .describe('Human-readable name of the alert.'),
+ enabled: zod.boolean().optional().describe('Whether the alert is evaluated on schedule.'),
source_config: zod
.object({
insight_id: zod
@@ -269,6 +1171,7 @@ export const PlatformAlertsUpdateBody = /* @__PURE__ */ zod.union([
})
.describe("The bound the insight's value is checked against."),
})
+ .optional()
.describe('Settings for a insight alert. The bound the alert is evaluated against is under condition.'),
grouping: zod
.object({
@@ -287,19 +1190,20 @@ export const PlatformAlertsUpdateBody = /* @__PURE__ */ zod.union([
max_instances: zod
.number()
.min(1)
- .max(platformAlertsUpdateBodyOneGroupingOneMaxInstancesMax)
- .default(platformAlertsUpdateBodyOneGroupingOneMaxInstancesDefault)
+ .max(platformAlertsPartialUpdateBodyOneGroupingOneMaxInstancesMax)
+ .default(platformAlertsPartialUpdateBodyOneGroupingOneMaxInstancesDefault)
.describe(
'Most instances the alert keeps at once. Groups past it are not tracked, and the last message says how many were left out.'
),
on_overflow: zod
.enum(['degrade_visible'])
.describe('\* `degrade_visible` - Degrade visible')
- .default(platformAlertsUpdateBodyOneGroupingOneOnOverflowDefault)
+ .default(platformAlertsPartialUpdateBodyOneGroupingOneOnOverflowDefault)
.describe(
'What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'
),
})
+ .optional()
.describe('How the alert splits its results into instances.'),
schedule_restriction: zod
.union([
@@ -325,25 +1229,29 @@ export const PlatformAlertsUpdateBody = /* @__PURE__ */ zod.union([
}),
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(platformAlertsUpdateBodyOneEvaluationPeriodsMax)
+ .max(platformAlertsPartialUpdateBodyOneEvaluationPeriodsMax)
+ .optional()
.describe('Number of recent checks considered when deciding to fire.'),
datapoints_to_alarm: zod
.number()
.min(1)
- .max(platformAlertsUpdateBodyOneDatapointsToAlarmMax)
+ .max(platformAlertsPartialUpdateBodyOneDatapointsToAlarmMax)
+ .optional()
.describe(
'Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.'
),
cooldown_minutes: zod
.number()
- .min(platformAlertsUpdateBodyOneCooldownMinutesMin)
- .max(platformAlertsUpdateBodyOneCooldownMinutesMax)
+ .min(platformAlertsPartialUpdateBodyOneCooldownMinutesMin)
+ .max(platformAlertsPartialUpdateBodyOneCooldownMinutesMax)
+ .optional()
.describe('Minimum minutes between notifications for the same alert.'),
})
.describe('The settings an edit can change. Each source kind subclasses it with a typed `source_config`.'),
@@ -354,8 +1262,12 @@ 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(platformAlertsUpdateBodyTwoNameMax).describe('Human-readable name of the alert.'),
- enabled: zod.boolean().describe('Whether the alert is evaluated on schedule.'),
+ name: zod
+ .string()
+ .max(platformAlertsPartialUpdateBodyTwoNameMax)
+ .optional()
+ .describe('Human-readable name of the alert.'),
+ enabled: zod.boolean().optional().describe('Whether the alert is evaluated on schedule.'),
source_config: zod
.object({
filters: zod
@@ -390,8 +1302,8 @@ export const PlatformAlertsUpdateBody = /* @__PURE__ */ zod.union([
.object({
threshold_count: zod
.number()
- .min(platformAlertsUpdateBodyTwoSourceConfigOneConditionThresholdCountMin)
- .max(platformAlertsUpdateBodyTwoSourceConfigOneConditionThresholdCountMax)
+ .min(platformAlertsPartialUpdateBodyTwoSourceConfigOneConditionThresholdCountMin)
+ .max(platformAlertsPartialUpdateBodyTwoSourceConfigOneConditionThresholdCountMax)
.describe(
'Number of matching log entries in the window that breaches the threshold. Use 0 with the above operator to fire on any matching log.'
),
@@ -410,6 +1322,7 @@ export const PlatformAlertsUpdateBody = /* @__PURE__ */ zod.union([
})
.describe('The bound the count is checked against.'),
})
+ .optional()
.describe('Settings for a logs alert. The bound the alert is evaluated against is under condition.'),
grouping: zod
.object({
@@ -428,19 +1341,20 @@ export const PlatformAlertsUpdateBody = /* @__PURE__ */ zod.union([
max_instances: zod
.number()
.min(1)
- .max(platformAlertsUpdateBodyTwoGroupingOneMaxInstancesMax)
- .default(platformAlertsUpdateBodyTwoGroupingOneMaxInstancesDefault)
+ .max(platformAlertsPartialUpdateBodyTwoGroupingOneMaxInstancesMax)
+ .default(platformAlertsPartialUpdateBodyTwoGroupingOneMaxInstancesDefault)
.describe(
'Most instances the alert keeps at once. Groups past it are not tracked, and the last message says how many were left out.'
),
on_overflow: zod
.enum(['degrade_visible'])
.describe('\* `degrade_visible` - Degrade visible')
- .default(platformAlertsUpdateBodyTwoGroupingOneOnOverflowDefault)
+ .default(platformAlertsPartialUpdateBodyTwoGroupingOneOnOverflowDefault)
.describe(
'What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'
),
})
+ .optional()
.describe('How the alert splits its results into instances.'),
schedule_restriction: zod
.union([
@@ -466,129 +1380,65 @@ export const PlatformAlertsUpdateBody = /* @__PURE__ */ zod.union([
}),
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(platformAlertsUpdateBodyTwoEvaluationPeriodsMax)
+ .max(platformAlertsPartialUpdateBodyTwoEvaluationPeriodsMax)
+ .optional()
.describe('Number of recent checks considered when deciding to fire.'),
datapoints_to_alarm: zod
.number()
.min(1)
- .max(platformAlertsUpdateBodyTwoDatapointsToAlarmMax)
+ .max(platformAlertsPartialUpdateBodyTwoDatapointsToAlarmMax)
+ .optional()
.describe(
'Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.'
),
cooldown_minutes: zod
.number()
- .min(platformAlertsUpdateBodyTwoCooldownMinutesMin)
- .max(platformAlertsUpdateBodyTwoCooldownMinutesMax)
+ .min(platformAlertsPartialUpdateBodyTwoCooldownMinutesMin)
+ .max(platformAlertsPartialUpdateBodyTwoCooldownMinutesMax)
+ .optional()
.describe('Minimum minutes between notifications for the same alert.'),
})
.describe('The settings an edit can change. Each source kind subclasses it with a typed `source_config`.'),
-])
-
-export const platformAlertsPartialUpdateBodyOneNameMax = 255
-
-export const platformAlertsPartialUpdateBodyOneGroupingOneMaxInstancesDefault = 100
-export const platformAlertsPartialUpdateBodyOneGroupingOneMaxInstancesMax = 100
-
-export const platformAlertsPartialUpdateBodyOneGroupingOneOnOverflowDefault = `degrade_visible`
-export const platformAlertsPartialUpdateBodyOneEvaluationPeriodsMax = 10
-
-export const platformAlertsPartialUpdateBodyOneDatapointsToAlarmMax = 10
-
-export const platformAlertsPartialUpdateBodyOneCooldownMinutesMin = 0
-export const platformAlertsPartialUpdateBodyOneCooldownMinutesMax = 2147483647
-
-export const platformAlertsPartialUpdateBodyTwoNameMax = 255
-
-export const platformAlertsPartialUpdateBodyTwoSourceConfigOneConditionThresholdCountMin = 0
-export const platformAlertsPartialUpdateBodyTwoSourceConfigOneConditionThresholdCountMax = 2147483647
-
-export const platformAlertsPartialUpdateBodyTwoGroupingOneMaxInstancesDefault = 100
-export const platformAlertsPartialUpdateBodyTwoGroupingOneMaxInstancesMax = 100
-
-export const platformAlertsPartialUpdateBodyTwoGroupingOneOnOverflowDefault = `degrade_visible`
-export const platformAlertsPartialUpdateBodyTwoEvaluationPeriodsMax = 10
-
-export const platformAlertsPartialUpdateBodyTwoDatapointsToAlarmMax = 10
-
-export const platformAlertsPartialUpdateBodyTwoCooldownMinutesMin = 0
-export const platformAlertsPartialUpdateBodyTwoCooldownMinutesMax = 2147483647
-
-export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod.union([
zod
.object({
source_kind: zod
- .enum(['insight'])
+ .enum(['warehouse_destination'])
.describe(
'Product whose data the alert evaluates. It cannot change, so it must match the stored value.'
),
name: zod
.string()
- .max(platformAlertsPartialUpdateBodyOneNameMax)
+ .max(platformAlertsPartialUpdateBodyThreeNameMax)
.optional()
.describe('Human-readable name of the alert.'),
enabled: zod.boolean().optional().describe('Whether the alert is evaluated on schedule.'),
source_config: zod
.object({
- insight_id: zod
- .number()
- .describe('The insight the alert checks. It cannot change through this API.'),
- condition: zod
- .object({
- threshold: zod
- .union([
- zod.object({
- bounds: zod
- .union([
- zod.object({
- lower: zod
- .union([zod.number(), zod.null()])
- .optional()
- .describe(
- 'Alert fires when the value drops below this number.'
- ),
- upper: zod
- .union([zod.number(), zod.null()])
- .optional()
- .describe('Alert fires when the value exceeds this number.'),
- }),
- zod.null(),
- ])
- .optional(),
- type: zod
- .enum(['absolute', 'percentage'])
- .describe(
- 'Whether bounds are compared as absolute values or as percentage change from the previous interval.'
- ),
- }),
- zod.null(),
- ])
- .describe(
- "The bounds the insight's value is checked against, absolute or as a percentage change."
- ),
- comparison: zod
- .object({
- type: zod.enum(['absolute_value', 'relative_increase', 'relative_decrease']),
- })
- .describe(
- 'How the value is compared: as it is, or as an increase or decrease from the previous interval.'
- ),
- detector: zod
- .union([zod.record(zod.string(), zod.unknown()), zod.null()])
- .optional()
- .describe(
- "The anomaly detector the alert uses in place of its threshold, or null for a threshold alert. It can't change through this API."
- ),
- })
- .describe("The bound the insight's value is checked against."),
+ destination_ids: zod
+ .array(zod.uuid())
+ .max(platformAlertsPartialUpdateBodyThreeSourceConfigOneDestinationIdsMax)
+ .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)
+ .describe(
+ 'Whether project members who get data pipeline error emails also get an email when this alert fires or resolves.'
+ ),
})
.optional()
- .describe('Settings for a insight alert. The bound the alert is evaluated against is under condition.'),
+ .describe(
+ 'Settings for a warehouse_destination alert. The bound the alert is evaluated against is under condition.'
+ ),
grouping: zod
.object({
mode: zod
@@ -606,15 +1456,15 @@ export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod.union([
max_instances: zod
.number()
.min(1)
- .max(platformAlertsPartialUpdateBodyOneGroupingOneMaxInstancesMax)
- .default(platformAlertsPartialUpdateBodyOneGroupingOneMaxInstancesDefault)
+ .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(platformAlertsPartialUpdateBodyOneGroupingOneOnOverflowDefault)
+ .default(platformAlertsPartialUpdateBodyThreeGroupingOneOnOverflowDefault)
.describe(
'What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'
),
@@ -652,21 +1502,21 @@ export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod.union([
evaluation_periods: zod
.number()
.min(1)
- .max(platformAlertsPartialUpdateBodyOneEvaluationPeriodsMax)
+ .max(platformAlertsPartialUpdateBodyThreeEvaluationPeriodsMax)
.optional()
.describe('Number of recent checks considered when deciding to fire.'),
datapoints_to_alarm: zod
.number()
.min(1)
- .max(platformAlertsPartialUpdateBodyOneDatapointsToAlarmMax)
+ .max(platformAlertsPartialUpdateBodyThreeDatapointsToAlarmMax)
.optional()
.describe(
'Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.'
),
cooldown_minutes: zod
.number()
- .min(platformAlertsPartialUpdateBodyOneCooldownMinutesMin)
- .max(platformAlertsPartialUpdateBodyOneCooldownMinutesMax)
+ .min(platformAlertsPartialUpdateBodyThreeCooldownMinutesMin)
+ .max(platformAlertsPartialUpdateBodyThreeCooldownMinutesMax)
.optional()
.describe('Minimum minutes between notifications for the same alert.'),
})
@@ -674,72 +1524,48 @@ export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod.union([
zod
.object({
source_kind: zod
- .enum(['logs'])
+ .enum(['warehouse_source'])
.describe(
'Product whose data the alert evaluates. It cannot change, so it must match the stored value.'
),
name: zod
.string()
- .max(platformAlertsPartialUpdateBodyTwoNameMax)
+ .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({
- filters: zod
- .object({
- filterGroup: zod
- .union([
- zod.object({
- type: zod.enum(['AND', 'OR']),
- values: zod.array(
- zod
- .record(zod.string(), zod.unknown())
- .describe(
- 'Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)'
- )
- ),
- }),
- zod.null(),
- ])
- .optional(),
- serviceNames: zod.union([zod.array(zod.string()), zod.null()]).optional(),
- severityLevels: zod
- .union([
- zod.array(zod.enum(['trace', 'debug', 'info', 'warn', 'error', 'fatal'])),
- zod.null(),
- ])
- .optional(),
- })
+ source_ids: zod
+ .array(zod.uuid())
+ .max(platformAlertsPartialUpdateBodyFourSourceConfigOneSourceIdsMax)
+ .optional()
.describe(
- 'The logs the alert counts: severityLevels, serviceNames, or a filterGroup of property filters. An enabled alert needs at least one.'
+ 'Warehouse sources the alert watches. Empty watches every source in the project, including sources added later.'
+ ),
+ group_by: zod
+ .enum(['schema', 'source'])
+ .default(platformAlertsPartialUpdateBodyFourSourceConfigOneGroupByDefault)
+ .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)
+ .describe(
+ "Whether a table that stops syncing at the project's billing limit also fires the alert."
+ ),
+ email_project_members: zod
+ .boolean()
+ .default(platformAlertsPartialUpdateBodyFourSourceConfigOneEmailProjectMembersDefault)
+ .describe(
+ 'Whether project members who get data pipeline error emails also get an email when this alert fires or resolves.'
),
- condition: zod
- .object({
- threshold_count: zod
- .number()
- .min(platformAlertsPartialUpdateBodyTwoSourceConfigOneConditionThresholdCountMin)
- .max(platformAlertsPartialUpdateBodyTwoSourceConfigOneConditionThresholdCountMax)
- .describe(
- 'Number of matching log entries in the window that breaches the threshold. Use 0 with the above operator to fire on any matching log.'
- ),
- threshold_operator: zod
- .enum(['above', 'below'])
- .describe('Whether the alert fires when the count is above or below the threshold.'),
- window_minutes: zod
- .union([
- zod.literal(5),
- zod.literal(10),
- zod.literal(15),
- zod.literal(30),
- zod.literal(60),
- ])
- .describe('Time window in minutes over which logs are counted.'),
- })
- .describe('The bound the count is checked against.'),
})
.optional()
- .describe('Settings for a logs alert. The bound the alert is evaluated against is under condition.'),
+ .describe(
+ 'Settings for a warehouse_source alert. The bound the alert is evaluated against is under condition.'
+ ),
grouping: zod
.object({
mode: zod
@@ -757,15 +1583,15 @@ export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod.union([
max_instances: zod
.number()
.min(1)
- .max(platformAlertsPartialUpdateBodyTwoGroupingOneMaxInstancesMax)
- .default(platformAlertsPartialUpdateBodyTwoGroupingOneMaxInstancesDefault)
+ .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(platformAlertsPartialUpdateBodyTwoGroupingOneOnOverflowDefault)
+ .default(platformAlertsPartialUpdateBodyFourGroupingOneOnOverflowDefault)
.describe(
'What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'
),
@@ -803,21 +1629,21 @@ export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod.union([
evaluation_periods: zod
.number()
.min(1)
- .max(platformAlertsPartialUpdateBodyTwoEvaluationPeriodsMax)
+ .max(platformAlertsPartialUpdateBodyFourEvaluationPeriodsMax)
.optional()
.describe('Number of recent checks considered when deciding to fire.'),
datapoints_to_alarm: zod
.number()
.min(1)
- .max(platformAlertsPartialUpdateBodyTwoDatapointsToAlarmMax)
+ .max(platformAlertsPartialUpdateBodyFourDatapointsToAlarmMax)
.optional()
.describe(
'Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.'
),
cooldown_minutes: zod
.number()
- .min(platformAlertsPartialUpdateBodyTwoCooldownMinutesMin)
- .max(platformAlertsPartialUpdateBodyTwoCooldownMinutesMax)
+ .min(platformAlertsPartialUpdateBodyFourCooldownMinutesMin)
+ .max(platformAlertsPartialUpdateBodyFourCooldownMinutesMax)
.optional()
.describe('Minimum minutes between notifications for the same alert.'),
})
diff --git a/products/alerts_platform/frontend/platformAlertFormat.ts b/products/alerts_platform/frontend/platformAlertFormat.ts
index 256a61dd38fa..8728d80bbf8e 100644
--- a/products/alerts_platform/frontend/platformAlertFormat.ts
+++ b/products/alerts_platform/frontend/platformAlertFormat.ts
@@ -11,24 +11,36 @@ export type PlatformAlertConfigurationStatus = PlatformAlertStateApi | 'disabled
interface SourceKind {
label: string
- // The source product's own page for the alert, reached through the legacy configuration id.
- alertUrl?: (legacyConfigurationId: string) => string
+ // The source product's own page for the alert, or null when the configuration cannot reach it.
+ alertUrl: (configuration: PlatformAlertConfigurationApi) => string | null
+}
+
+function legacyAlertUrl(url: (legacyConfigurationId: string) => string): SourceKind['alertUrl'] {
+ return ({ legacy_configuration_id }) => (legacy_configuration_id ? url(legacy_configuration_id) : null)
}
export const SOURCE_KINDS: Record<PlatformAlertConfigurationSourceKindEnumApi, SourceKind> = {
[PlatformAlertConfigurationSourceKindEnumApi.Logs]: {
label: 'Logs',
- alertUrl: (legacyConfigurationId) => urls.logsAlertDetail(legacyConfigurationId),
+ alertUrl: legacyAlertUrl(urls.logsAlertDetail),
},
[PlatformAlertConfigurationSourceKindEnumApi.Insight]: {
label: 'Insight',
- alertUrl: (legacyConfigurationId) => urls.alert(legacyConfigurationId),
+ alertUrl: legacyAlertUrl(urls.alert),
+ },
+ // A warehouse alert has no page of its own, so it links to the page that lists what it watches.
+ [PlatformAlertConfigurationSourceKindEnumApi.WarehouseSource]: {
+ label: 'Warehouse source',
+ alertUrl: () => urls.sources(),
+ },
+ [PlatformAlertConfigurationSourceKindEnumApi.WarehouseDestination]: {
+ label: 'Warehouse destination',
+ alertUrl: () => urls.warehouseDestinations(),
},
}
export function sourceAlertUrl(configuration: PlatformAlertConfigurationApi): string | null {
- const { alertUrl } = SOURCE_KINDS[configuration.source_kind]
- return alertUrl && configuration.legacy_configuration_id ? alertUrl(configuration.legacy_configuration_id) : null
+ return SOURCE_KINDS[configuration.source_kind].alertUrl(configuration)
}
// Most urgent first, so a configuration shows the state that needs attention.
diff --git a/products/warehouse_sources/backend/apps.py b/products/warehouse_sources/backend/apps.py
index 97cdb48bc460..7f1ae3c23c44 100644
--- a/products/warehouse_sources/backend/apps.py
+++ b/products/warehouse_sources/backend/apps.py
@@ -14,3 +14,9 @@ class WarehouseSourcesConfig(AppConfig):
# would otherwise drop audit logs. They live in a light activity_logging module because both
# viewsets pull in dlt via the data-import chain.
from products.warehouse_sources.backend import activity_logging # noqa: F401, PLC0415
+
+ # The alerts platform imports no source, so warehouse alerts register their wording and
+ # their `source_config` schema with it here, in every process.
+ from products.warehouse_sources.backend.sync_alerts.registration import register # noqa: PLC0415
+
+ register()
diff --git a/products/warehouse_sources/backend/facade/sync_alerts.py b/products/warehouse_sources/backend/facade/sync_alerts.py
new file mode 100644
index 000000000000..9b4d210445c7
--- /dev/null
+++ b/products/warehouse_sources/backend/facade/sync_alerts.py
@@ -0,0 +1,9 @@
+"""Warehouse alert destination vocabulary for the warehouse presentation endpoints."""
+
+from products.warehouse_sources.backend.sync_alerts.destinations import (
+ EVENT_IDS,
+ EVENT_KIND_CONFIG,
+ WAREHOUSE_ALERT_DESTINATION_TYPES,
+)
+
+__all__ = ["EVENT_IDS", "EVENT_KIND_CONFIG", "WAREHOUSE_ALERT_DESTINATION_TYPES"]
diff --git a/products/warehouse_sources/backend/facade/temporal.py b/products/warehouse_sources/backend/facade/temporal.py
index 080cdf538c85..213bdb0ba34f 100644
--- a/products/warehouse_sources/backend/facade/temporal.py
+++ b/products/warehouse_sources/backend/facade/temporal.py
@@ -55,6 +55,10 @@ from products.warehouse_sources.backend.temporal.data_imports.table_metadata_set
WORKFLOWS as METADATA_WORKFLOWS,
)
from products.warehouse_sources.backend.temporal.data_imports.util import prepare_s3_files_for_querying
+from products.warehouse_sources.backend.temporal.sync_alert_evaluate import (
+ WAREHOUSE_ALERT_EVALUATION_ACTIVITIES,
+ WAREHOUSE_ALERT_EVALUATION_WORKFLOWS,
+)
__all__ = [
"ACTIVITIES",
@@ -64,6 +68,8 @@ __all__ = [
"PERSON_PROPERTY_BACKFILL_WORKFLOWS",
"PERSON_PROPERTY_SYNC_ACTIVITIES",
"PERSON_PROPERTY_SYNC_WORKFLOWS",
+ "WAREHOUSE_ALERT_EVALUATION_ACTIVITIES",
+ "WAREHOUSE_ALERT_EVALUATION_WORKFLOWS",
"WORKFLOWS",
"ExternalDataSchemaSyncPausedError",
"AccountPropertyRowSink",
diff --git a/products/warehouse_sources/backend/presentation/views/warehouse_alert_destinations.py b/products/warehouse_sources/backend/presentation/views/warehouse_alert_destinations.py
new file mode 100644
index 000000000000..5ee900e1cc45
--- /dev/null
+++ b/products/warehouse_sources/backend/presentation/views/warehouse_alert_destinations.py
@@ -0,0 +1,333 @@
+"""Notification destinations of a warehouse alert on the alerts platform.
+
+The alert itself is created, edited and deleted through the platform API (`platform_alerts`). Its
+destinations are HogFunctions this product owns, matched on the alert's configuration id, so they
+are managed here.
+"""
+
+from typing import Any, Literal, cast
+from uuid import UUID
+
+from django.db import models, transaction
+
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from rest_framework import serializers, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
+from rest_framework.permissions import SAFE_METHODS
+from rest_framework.request import Request
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.event_usage import report_user_action
+from posthog.exceptions import Conflict, as_drf_validation_error
+from posthog.models.user import User
+from posthog.permissions import PostHogFeatureFlagPermission
+
+from products.alerts.backend.facade.destinations import (
+ MAX_DESTINATIONS_PER_ALERT,
+ build_alert_destination_config,
+ create_alert_destination_hog_functions,
+ destination_handles_event_kind,
+ list_alert_destination_groups,
+ redact_destination_data,
+ soft_delete_alert_destinations,
+ validate_destination_data,
+)
+from products.alerts_platform.backend.facade.api import get_configuration
+from products.alerts_platform.backend.facade.contracts import (
+ AlertDestinationData,
+ AlertDestinationValidationError,
+ DestinationType,
+ PagerDutyRegion,
+ PagerDutySeverity,
+ PlatformAlertConfigurationView,
+ SourceKind,
+)
+from products.alerts_platform.backend.facade.enums import PlatformAlertOwner
+from products.warehouse_sources.backend.facade.sync_alerts import (
+ EVENT_IDS,
+ EVENT_KIND_CONFIG,
+ WAREHOUSE_ALERT_DESTINATION_TYPES,
+)
+
+MAX_DESTINATION_IDS_PER_DELETE_REQUEST = 100
+WAREHOUSE_ALERT_KINDS = (SourceKind.WAREHOUSE_SOURCE.value, SourceKind.WAREHOUSE_DESTINATION.value)
+# The warehouse data an alert names is gated by the same resource as the sources page.
+WAREHOUSE_RESOURCE: Literal["external_data_source"] = "external_data_source"
+_SLACK_CONTEXT_ELEMENTS = ("Project: <{project.url}|{project.name}>",)
+# Choices classes for the serializers below. Each label is its value, so the OpenAPI enums keep the
+# names their ENUM_NAME_OVERRIDES entries in posthog/settings/web.py give them. TextChoices supports
+# this functional API at runtime, but its type stubs only describe member construction.
+WarehouseAlertDestinationTypeChoices = cast(Any, models.TextChoices)(
+ "WarehouseAlertDestinationTypeChoices",
+ [(member.name, (member.value, member.value)) for member in WAREHOUSE_ALERT_DESTINATION_TYPES],
+)
+PagerDutySeverityChoices = cast(Any, models.TextChoices)(
+ "PagerDutySeverityChoices", [(member.name, (member.value, member.value)) for member in PagerDutySeverity]
+)
+PagerDutyRegionChoices = cast(Any, models.TextChoices)(
+ "PagerDutyRegionChoices", [(member.name, (member.value, member.value)) for member in PagerDutyRegion]
+)
+
+
+class WarehouseAlertDestinationSerializer(serializers.Serializer):
+ hog_function_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ help_text="HogFunction IDs that make up this destination, one per alert event kind it handles. "
+ "Send them all to the delete endpoint to remove the destination.",
+ )
+ type = serializers.ChoiceField(
+ choices=WarehouseAlertDestinationTypeChoices.choices, help_text="Notification destination type."
+ )
+ enabled = serializers.BooleanField(
+ help_text="Whether every HogFunction of the destination is enabled, so it notifies for every event kind."
+ )
+ slack_workspace_id = serializers.IntegerField(
+ required=False, help_text="Integration ID of the Slack workspace. Set when type=slack."
+ )
+ slack_channel_id = serializers.CharField(required=False, help_text="Slack channel ID. Set when type=slack.")
+ slack_channel_name = serializers.CharField(
+ required=False, help_text="Human-readable Slack channel name. Set when type=slack."
+ )
+ webhook_url = serializers.CharField(
+ required=False,
+ help_text="Webhook endpoint reduced to scheme and host. The path, query and userinfo carry the secret.",
+ )
+ pagerduty_routing_key = serializers.CharField(
+ required=False, help_text="PagerDuty integration key reduced to its last four characters."
+ )
+ pagerduty_severity = serializers.ChoiceField(
+ choices=PagerDutySeverityChoices.choices,
+ required=False,
+ help_text="Severity of the PagerDuty incident.",
+ )
+ pagerduty_region = serializers.ChoiceField(
+ choices=PagerDutyRegionChoices.choices,
+ required=False,
+ help_text="PagerDuty service region the events go to.",
+ )
+
+
+class WarehouseAlertCreateDestinationSerializer(serializers.Serializer):
+ type = serializers.ChoiceField(
+ choices=WarehouseAlertDestinationTypeChoices.choices, help_text="Notification destination type."
+ )
+ slack_workspace_id = serializers.IntegerField(
+ required=False, help_text="Integration ID for the Slack workspace. Required when type=slack."
+ )
+ slack_channel_id = serializers.CharField(required=False, help_text="Slack channel ID. Required when type=slack.")
+ slack_channel_name = serializers.CharField(
+ required=False, allow_blank=True, help_text="Human-readable channel name for display."
+ )
+ webhook_url = serializers.URLField(
+ required=False, help_text="HTTPS endpoint to post to. Required for webhook, teams and discord."
+ )
+ pagerduty_routing_key = serializers.CharField(
+ required=False,
+ trim_whitespace=True,
+ help_text="Integration key of a PagerDuty Events API v2 integration. Required when type=pagerduty.",
+ )
+ pagerduty_severity = serializers.ChoiceField(
+ choices=PagerDutySeverityChoices.choices,
+ required=False,
+ default=PagerDutySeverity.CRITICAL.value,
+ help_text="Severity PagerDuty records on the incident. Used when type=pagerduty.",
+ )
+ pagerduty_region = serializers.ChoiceField(
+ choices=PagerDutyRegionChoices.choices,
+ required=False,
+ default=PagerDutyRegion.US.value,
+ help_text="PagerDuty service region of the account. Used when type=pagerduty.",
+ )
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ data = cast(AlertDestinationData, attrs)
+ data["type"] = DestinationType(attrs["type"])
+ try:
+ validate_destination_data(data, allowed_destination_types=WAREHOUSE_ALERT_DESTINATION_TYPES)
+ except AlertDestinationValidationError as error:
+ raise as_drf_validation_error(error)
+ return attrs
+
+
+class WarehouseAlertDestinationCreatedSerializer(serializers.Serializer):
+ hog_function_ids = serializers.ListField(
+ child=serializers.UUIDField(), help_text="HogFunction IDs created for the destination, one per event kind."
+ )
+
+
+class WarehouseAlertDeleteDestinationSerializer(serializers.Serializer):
+ hog_function_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ min_length=1,
+ max_length=MAX_DESTINATION_IDS_PER_DELETE_REQUEST,
+ help_text="HogFunction IDs of one destination, as the list endpoint returns them. They are deleted together.",
+ )
+
+
+class WarehouseAlertDestinationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ """Destinations of a warehouse alert. The URL's ID is the alert's platform configuration ID."""
+
+ scope_object = "alert"
+ posthog_feature_flag = "platform-alerts"
+ permission_classes = [PostHogFeatureFlagPermission]
+
+ def dangerously_get_required_scopes(self, request: Request, view: APIView) -> list[str]:
+ # A destination exposes the warehouse alert it belongs to, so a key needs the warehouse scope too.
+ access = "read" if request.method in SAFE_METHODS else "write"
+ return [f"alert:{access}", f"{WAREHOUSE_RESOURCE}:{access}"]
+
+ def _alert(self, pk: str) -> PlatformAlertConfigurationView:
+ level: Literal["viewer", "editor"] = "viewer" if self.request.method in SAFE_METHODS else "editor"
+ if not self.user_access_control.check_access_level_for_resource(WAREHOUSE_RESOURCE, level):
+ raise PermissionDenied("You don't have access to warehouse sources in this project.")
+ alert = get_configuration(
+ team_id=self.team_id,
+ source_kinds=WAREHOUSE_ALERT_KINDS,
+ configuration_id=serializers.UUIDField().run_validation(pk),
+ )
+ if alert is None:
+ raise NotFound()
+ if alert.owner != PlatformAlertOwner.PLATFORM:
+ raise Conflict("This alert has no destinations to manage here.")
+ return alert
+
+ @extend_schema(
+ responses={200: WarehouseAlertDestinationSerializer(many=True)},
+ description="List the notification destinations of a warehouse alert.",
+ )
+ @action(detail=True, methods=["GET"], url_path="destinations", pagination_class=None)
+ def destinations(self, request: Request, pk: str, **kwargs: Any) -> Response:
+ alert = self._alert(pk)
+ groups = list_alert_destination_groups(
+ team_id=self.team_id,
+ alert_id=str(alert.destination_alert_id),
+ allowed_event_ids=EVENT_IDS[SourceKind(alert.source_kind)],
+ )
+ return Response(
+ WarehouseAlertDestinationSerializer(
+ [
+ {
+ "hog_function_ids": list(group.hog_function_ids),
+ "enabled": group.fully_enabled,
+ **redact_destination_data(group.data),
+ }
+ for group in groups
+ ],
+ many=True,
+ ).data
+ )
+
+ @extend_schema(
+ request=WarehouseAlertCreateDestinationSerializer,
+ responses={
+ 201: WarehouseAlertDestinationCreatedSerializer,
+ 400: OpenApiResponse(description="The destination settings are invalid."),
+ },
+ description=(
+ "Add a notification destination to a warehouse alert. One HogFunction is created per alert event kind "
+ "(firing, resolved). A PagerDuty destination gets the incident opened and incident closed kinds "
+ "instead, so each incident it opens is resolved."
+ ),
+ )
+ @destinations.mapping.post
+ def create_destination(self, request: Request, pk: str, **kwargs: Any) -> Response:
+ alert = self._alert(pk)
+ serializer = WarehouseAlertCreateDestinationSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = cast(AlertDestinationData, serializer.validated_data)
+ source_kind = SourceKind(alert.source_kind)
+ kinds = EVENT_KIND_CONFIG[source_kind]
+ event_kinds = [kind for kind, spec in kinds.items() if destination_handles_event_kind(data["type"], spec)]
+ configs = [
+ build_alert_destination_config(
+ spec=kinds[kind],
+ alert_id=str(alert.destination_alert_id),
+ alert_name=alert.name,
+ data=data,
+ slack_context_elements=_SLACK_CONTEXT_ELEMENTS,
+ )
+ for kind in event_kinds
+ ]
+ try:
+ with transaction.atomic():
+ # The alert's row stays locked until the destinations commit. A delete that got there
+ # first leaves no row, and one that comes later waits, then removes these destinations too.
+ if (
+ get_configuration(
+ team_id=self.team_id, source_kinds=WAREHOUSE_ALERT_KINDS, configuration_id=alert.id, lock=True
+ )
+ is None
+ ):
+ raise NotFound()
+ # Each destination is another message every time the alert fires, so one alert has only a few.
+ existing = list_alert_destination_groups(
+ team_id=self.team_id,
+ alert_id=str(alert.destination_alert_id),
+ allowed_event_ids=EVENT_IDS[source_kind],
+ )
+ if len(existing) >= MAX_DESTINATIONS_PER_ALERT:
+ raise ValidationError(
+ f"This alert already has {MAX_DESTINATIONS_PER_ALERT} destinations. Remove one to add another."
+ )
+ hog_function_ids = create_alert_destination_hog_functions(
+ configs,
+ team_id=self.team_id,
+ created_by_id=cast(User, request.user).id,
+ alert_id=str(alert.destination_alert_id),
+ allowed_event_ids=EVENT_IDS[source_kind],
+ )
+ except AlertDestinationValidationError as error:
+ raise as_drf_validation_error(error)
+
+ report_user_action(
+ cast(User, request.user),
+ "warehouse alert destination created",
+ {
+ "alert_id": str(alert.id),
+ "source_kind": alert.source_kind,
+ "type": data["type"],
+ "event_kinds": event_kinds,
+ },
+ team=self.team,
+ request=request,
+ )
+ return Response(
+ WarehouseAlertDestinationCreatedSerializer({"hog_function_ids": list(hog_function_ids)}).data,
+ status=status.HTTP_201_CREATED,
+ )
+
+ @extend_schema(
+ request=WarehouseAlertDeleteDestinationSerializer,
+ responses={
+ 204: OpenApiResponse(description="The destination's HogFunctions are deleted."),
+ 400: OpenApiResponse(description="An ID does not belong to this alert, or names part of a destination."),
+ },
+ description="Delete one notification destination of a warehouse alert, all its HogFunctions together.",
+ )
+ @action(detail=True, methods=["POST"], url_path="destinations/delete")
+ def delete_destination(self, request: Request, pk: str, **kwargs: Any) -> Response:
+ alert = self._alert(pk)
+ serializer = WarehouseAlertDeleteDestinationSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ hog_function_ids: list[UUID] = serializer.validated_data["hog_function_ids"]
+ try:
+ soft_delete_alert_destinations(
+ team_id=self.team_id,
+ alert_id=str(alert.destination_alert_id),
+ allowed_event_ids=EVENT_IDS[SourceKind(alert.source_kind)],
+ hog_function_ids=hog_function_ids,
+ )
+ except AlertDestinationValidationError as error:
+ raise as_drf_validation_error(error)
+
+ report_user_action(
+ cast(User, request.user),
+ "warehouse alert destination deleted",
+ {"alert_id": str(alert.id), "source_kind": alert.source_kind, "count": len(hog_function_ids)},
+ team=self.team,
+ request=request,
+ )
+ return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/products/warehouse_sources/backend/routes.py b/products/warehouse_sources/backend/routes.py
index 8991e28f526f..c32a045a7a79 100644
--- a/products/warehouse_sources/backend/routes.py
+++ b/products/warehouse_sources/backend/routes.py
@@ -4,6 +4,7 @@ from products.warehouse_sources.backend.presentation.views import (
column_statistics,
external_data_destination,
external_data_schema,
+ warehouse_alert_destinations,
)
from products.warehouse_sources.backend.presentation.views.external_data_source.viewset import ExternalDataSourceViewSet
@@ -27,6 +28,12 @@ def register_routes(routers: RouterRegistry) -> None:
"project_external_data_schemas",
["team_id"],
)
+ routers.projects.register(
+ r"warehouse_alerts",
+ warehouse_alert_destinations.WarehouseAlertDestinationViewSet,
+ "project_warehouse_alerts",
+ ["team_id"],
+ )
routers.projects.register(
r"warehouse_column_statistics",
column_statistics.WarehouseColumnStatisticsViewSet,
diff --git a/products/warehouse_sources/backend/sync_alerts/__init__.py b/products/warehouse_sources/backend/sync_alerts/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/warehouse_sources/backend/sync_alerts/destinations.py b/products/warehouse_sources/backend/sync_alerts/destinations.py
new file mode 100644
index 000000000000..3d9dbb809630
--- /dev/null
+++ b/products/warehouse_sources/backend/sync_alerts/destinations.py
@@ -0,0 +1,149 @@
+"""What each warehouse alert event says, and where its destinations may send it.
+
+A destination is a set of HogFunctions, one per event kind it handles. They are the stored form of
+the destination: native delivery reads them to find who to tell and words the message itself. Nothing
+emits their events, and the generic HogFunction API refuses to edit them, so their templates never run.
+
+The evaluation reads Postgres rows and records no failed check, so these alerts only fire and resolve.
+"""
+
+from dataclasses import replace
+from typing import Final, Literal
+
+from products.alerts_platform.backend.facade.contracts import (
+ AlertDestinationAction,
+ AlertEventKind,
+ DestinationType,
+ EventKindSpec,
+ IncidentAction,
+ SourceKind,
+)
+
+EventKind = Literal["firing", "resolved", "incident_opened", "incident_closed"]
+
+WAREHOUSE_ALERT_DESTINATION_TYPES: Final = (
+ DestinationType.SLACK,
+ DestinationType.WEBHOOK,
+ DestinationType.TEAMS,
+ DestinationType.DISCORD,
+ DestinationType.PAGERDUTY,
+)
+
+_SOURCES_URL = "{project.url}/data-management/sources"
+_DESTINATIONS_URL = "{project.url}/data-management/warehouse-destinations"
+
+
+def _event_kinds(
+ *,
+ prefix: str,
+ product_label: str,
+ headline: str,
+ details: tuple[tuple[str, str], ...],
+ url: str,
+ data: dict[str, str],
+) -> dict[EventKind, EventKindSpec]:
+ firing = EventKindSpec(
+ event_id=f"${prefix}_firing",
+ display_kind="firing",
+ header=f"🔴 {headline} '{{event.properties.alert_name}}' is firing",
+ details=details,
+ primary_action_url=url,
+ primary_action_label="View in PostHog",
+ webhook_body={
+ "id": "{event.uuid}",
+ "type": f"{prefix}.firing",
+ "timestamp": "{event.properties.triggered_at}",
+ "data": data,
+ },
+ product_label=product_label,
+ )
+ return {
+ "firing": firing,
+ "resolved": replace(
+ firing,
+ event_id=f"${prefix}_resolved",
+ display_kind="resolved",
+ header=f"🟢 {headline} '{{event.properties.alert_name}}' is resolved",
+ webhook_body={**firing.webhook_body, "type": f"{prefix}.resolved"},
+ ),
+ # 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=f"${prefix}_incident_opened",
+ display_kind="incident opened",
+ webhook_body={},
+ additional_actions=(AlertDestinationAction(url=url, label="View in PostHog"),),
+ incident_action=IncidentAction.TRIGGER,
+ ),
+ "incident_closed": replace(
+ firing,
+ event_id=f"${prefix}_incident_closed",
+ display_kind="incident closed",
+ header=f"{headline} '{{event.properties.alert_name}}' stopped firing",
+ details=(("Reason", "{event.properties.reason}"),),
+ webhook_body={},
+ incident_action=IncidentAction.RESOLVE,
+ ),
+ }
+
+
+EVENT_KIND_CONFIG: Final[dict[SourceKind, dict[EventKind, EventKindSpec]]] = {
+ SourceKind.WAREHOUSE_SOURCE: _event_kinds(
+ prefix="warehouse_source_alert",
+ product_label="warehouse sync alert",
+ headline="Warehouse sync alert",
+ details=(
+ ("Source", "{event.properties.source}"),
+ ("Tables", "{event.properties.tables}"),
+ ("Error", "{event.properties.error}"),
+ ),
+ url=_SOURCES_URL,
+ data={
+ "alert_id": "{event.properties.alert_id}",
+ "alert_name": "{event.properties.alert_name}",
+ "source_id": "{event.properties.source_id}",
+ "source": "{event.properties.source}",
+ "tables": "{event.properties.tables}",
+ "error": "{event.properties.error}",
+ },
+ ),
+ SourceKind.WAREHOUSE_DESTINATION: _event_kinds(
+ prefix="warehouse_destination_alert",
+ product_label="warehouse destination alert",
+ headline="Warehouse destination alert",
+ details=(
+ ("Destination", "{event.properties.destination}"),
+ ("Status", "{event.properties.status}"),
+ ("Error", "{event.properties.error}"),
+ ),
+ url=_DESTINATIONS_URL,
+ data={
+ "alert_id": "{event.properties.alert_id}",
+ "alert_name": "{event.properties.alert_name}",
+ "destination_id": "{event.properties.destination_id}",
+ "destination": "{event.properties.destination}",
+ "status": "{event.properties.status}",
+ "error": "{event.properties.error}",
+ },
+ ),
+}
+
+EVENT_IDS: Final[dict[SourceKind, tuple[str, ...]]] = {
+ source: tuple(spec.event_id for spec in kinds.values()) for source, kinds in EVENT_KIND_CONFIG.items()
+}
+
+# Which event id each announced kind's destinations filter on. The platform imports no source, so
+# the delivery request carries this map.
+EVENT_IDS_BY_KIND: Final[dict[SourceKind, dict[str, str]]] = {
+ source: {
+ AlertEventKind.FIRING.value: kinds["firing"].event_id,
+ AlertEventKind.RESOLVED.value: kinds["resolved"].event_id,
+ }
+ for source, kinds in EVENT_KIND_CONFIG.items()
+}
+
+EVENT_IDS_BY_INCIDENT_ACTION: Final[dict[SourceKind, dict[str, str]]] = {
+ source: {spec.incident_action.value: spec.event_id for spec in kinds.values() if spec.incident_action}
+ for source, kinds in EVENT_KIND_CONFIG.items()
+}
diff --git a/products/warehouse_sources/backend/sync_alerts/evaluation.py b/products/warehouse_sources/backend/sync_alerts/evaluation.py
new file mode 100644
index 000000000000..cd26cf1210bb
--- /dev/null
+++ b/products/warehouse_sources/backend/sync_alerts/evaluation.py
@@ -0,0 +1,503 @@
+"""Evaluation of due warehouse alerts on the shared alerts platform.
+
+A check reads sync statuses from Postgres and reports which groups fail. A table (or a source, or a
+destination) that fails is a breaching group, and an open group that stops failing resolves. The
+lifecycle decision comes from the shared machine under `PLATFORM_WAREHOUSE_ALERT_POLICY`.
+
+This reads and decides. It writes nothing, so a retried attempt reads the same due checks and makes
+the same decisions. The platform records the outcomes in its own activity.
+
+Each batch is one team's due checks, so every read here is one query for the whole batch.
+"""
+
+import time
+from collections.abc import Mapping, Sequence
+from datetime import datetime, timedelta
+from typing import Final
+from uuid import UUID
+
+from django.db.models import Q
+
+import structlog
+
+from posthog.dataclasses import frozen
+from posthog.models import Team
+
+from products.alerts.backend.facade.destinations import configured_destination_template_ids
+from products.alerts_platform.backend.facade.api import due_checks, slot_of
+from products.alerts_platform.backend.facade.contracts import (
+ AlertDeliveryRequest,
+ InstanceCheckState,
+ PlatformAlertCheckInput,
+ PlatformAlertOutcome,
+ SourceBatchEvaluation,
+ SourceKind,
+)
+from products.alerts_platform.backend.facade.grouping import (
+ GroupDecision,
+ GroupObservation,
+ decide_groups,
+ delivery_parts,
+)
+from products.alerts_platform.backend.facade.lifecycle import (
+ PLATFORM_WAREHOUSE_ALERT_POLICY,
+ AlertSnapshot,
+ AlertState,
+ NotificationAction,
+ decide_incident_action,
+)
+from products.alerts_platform.backend.facade.payload import MAX_BATCH_PAYLOAD_BYTES, payload_bytes
+from products.alerts_platform.backend.facade.platform_metrics import (
+ increment_checks,
+ increment_checks_deferred,
+ increment_state_transition,
+ record_batch_duration,
+ safe_record,
+)
+from products.alerts_platform.backend.facade.scheduling import is_utc_datetime_blocked, parse_blocked_windows_tuples
+from products.warehouse_sources.backend.models.external_data_destination import ExternalDataDestination
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.presentation.views.external_data_source.helpers import (
+ get_error_redaction_values,
+ redact_error_message,
+)
+from products.warehouse_sources.backend.sync_alerts.destinations import EVENT_IDS_BY_INCIDENT_ACTION, EVENT_IDS_BY_KIND
+from products.warehouse_sources.backend.sync_alerts.wording import (
+ DESTINATION_LABEL,
+ DESTINATION_TYPE_LABEL,
+ REASON_LABEL,
+ SCHEMA_LABEL,
+ SOURCE_ID_KEY,
+ SOURCE_LABEL,
+ STATUS_LABEL,
+ destination_alerts_url,
+ group_by_of,
+ source_alerts_url,
+)
+
+logger = structlog.get_logger(__name__)
+
+Status = ExternalDataSchema.Status
+FAILED_STATUSES: Final = frozenset({Status.FAILED.value})
+BILLING_LIMIT_STATUSES: Final = frozenset({Status.BILLING_LIMIT_REACHED.value, Status.BILLING_LIMIT_TOO_LOW.value})
+FAILING_DESTINATION_STATUSES: Final = frozenset(
+ {ExternalDataDestination.Status.FAILING.value, ExternalDataDestination.Status.PAUSED.value}
+)
+
+# Rows one batch reads. A team past it still alerts on the first rows, and an open group the read may
+# have cut is left open rather than resolved.
+MAX_FAILING_ROWS: Final = 1000
+
+_BILLING_REASONS: Final = {
+ Status.BILLING_LIMIT_REACHED.value: "Syncing stopped because the project reached its data warehouse billing limit.",
+ Status.BILLING_LIMIT_TOO_LOW.value: "Syncing stopped because the billing limit is too low to sync this table.",
+}
+_FAILED_WITHOUT_ERROR: Final = "The last sync failed."
+_DESTINATION_FAILED_WITHOUT_ERROR: Final = "The last delivery to this destination failed."
+
+Decision = tuple[PlatformAlertOutcome, AlertDeliveryRequest | None]
+
+
+@frozen
+class _Failing:
+ """One failing row, with what its group's labels need."""
+
+ group_ids: Mapping[str, str]
+ status: str
+ labels: dict[str, str]
+
+
+@frozen
+class _Reading:
+ """What one batch read: the failing rows, and the labels of open groups that no longer fail."""
+
+ failing: tuple[_Failing, ...]
+ truncated: bool
+ resolved_labels: Mapping[str, dict[str, str]]
+ # Open groups that no longer fail only because a sync is running again. They stay open until it ends.
+ retrying: frozenset[str] = frozenset()
+
+
+def evaluate_warehouse_alert_batch(
+ source: SourceKind, team_id: int, slot: str, cutoff: datetime
+) -> SourceBatchEvaluation:
+ """Evaluates one batch key of a warehouse alert kind against the tick's cutoff."""
+ started_at = time.monotonic()
+ checks = due_checks(team_id, source.value, slot, cutoff)
+ if not checks:
+ return SourceBatchEvaluation(outcomes=(), deliveries=())
+ tz_name = Team.objects.filter(id=team_id).values_list("timezone", flat=True).first()
+ if tz_name is None:
+ return SourceBatchEvaluation(outcomes=(), deliveries=())
+
+ reading = (
+ _read_sources(team_id, checks) if source == SourceKind.WAREHOUSE_SOURCE else _read_destinations(team_id, checks)
+ )
+ decided = [
+ _decide(source, check, reading, now=cutoff, muted=_in_quiet_hours(check, cutoff, tz_name)) for check in checks
+ ]
+ evaluation = _collect(source, decided, team_id=team_id, slot=slot)
+ safe_record(record_batch_duration, source.value, int((time.monotonic() - started_at) * 1000))
+ return evaluation
+
+
+def _in_quiet_hours(check: PlatformAlertCheckInput, now: datetime, tz_name: str) -> bool:
+ try:
+ return is_utc_datetime_blocked(now, tz_name, parse_blocked_windows_tuples(check.schedule_restriction))
+ except Exception:
+ # A restriction that cannot be read must not hold back a failure.
+ logger.exception("Unparseable schedule restriction on a warehouse alert", check_id=str(check.id))
+ return False
+
+
+def _observations(source: SourceKind, check: PlatformAlertCheckInput, reading: _Reading) -> list[GroupObservation]:
+ config = check.source_config
+ if source == SourceKind.WAREHOUSE_DESTINATION:
+ scope = {str(item) for item in config.get("destination_ids") or []}
+ return [
+ GroupObservation(grouping_key=row.group_ids["destination"], current_breached=True, labels=row.labels)
+ for row in reading.failing
+ if not scope or row.group_ids["destination"] in scope
+ ]
+
+ scope = {str(item) for item in config.get("source_ids") or []}
+ statuses = FAILED_STATUSES | (BILLING_LIMIT_STATUSES if config.get("include_billing_limits") else frozenset())
+ in_scope = [
+ row for row in reading.failing if row.status in statuses and (not scope or row.group_ids["source"] in scope)
+ ]
+ if group_by_of(config) == "schema":
+ return [
+ GroupObservation(grouping_key=row.group_ids["schema"], current_breached=True, labels=row.labels)
+ for row in in_scope
+ ]
+ by_source: dict[str, list[_Failing]] = {}
+ for row in in_scope:
+ by_source.setdefault(row.group_ids["source"], []).append(row)
+ return [
+ GroupObservation(
+ grouping_key=source_id,
+ current_breached=True,
+ # How many of the source's tables fail, which the message states.
+ value=float(len(rows)),
+ labels={
+ **rows[0].labels,
+ SCHEMA_LABEL: ", ".join(row.labels[SCHEMA_LABEL] for row in rows),
+ },
+ )
+ for source_id, rows in by_source.items()
+ ]
+
+
+def _decide(
+ source: SourceKind, check: PlatformAlertCheckInput, reading: _Reading, *, now: datetime, muted: bool
+) -> Decision:
+ def absent(key: str) -> GroupObservation | None:
+ # A group the read may have cut could still be failing, so it stays as it is. So does one whose
+ # sync is retrying, so a retry that fails again does not resolve and re-fire the same failure.
+ if reading.truncated or key in reading.retrying:
+ return None
+ return GroupObservation(grouping_key=key, current_breached=False, labels=reading.resolved_labels.get(key, {}))
+
+ decision = decide_groups(
+ check,
+ _observations(source, check, reading),
+ snapshot_of=lambda instance, _prior: _snapshot(check, instance),
+ policy=PLATFORM_WAREHOUSE_ALERT_POLICY,
+ now=now,
+ muted=muted,
+ absent=absent,
+ )
+ for verdict in decision.verdicts:
+ safe_record(increment_checks, source.value, verdict.outcome.notification.value)
+ if verdict.snapshot.state != verdict.outcome.new_state:
+ safe_record(
+ increment_state_transition, source.value, verdict.snapshot.state.value, verdict.outcome.new_state.value
+ )
+ recorded = decision.as_outcome(
+ configuration_id=check.id,
+ evaluation_key=f"slot:{slot_of(check.next_check_at, now)}",
+ grouping=check.grouping,
+ query_duration_ms=None,
+ results_cut=reading.truncated,
+ )
+ return recorded, _request(source, check, recorded, decision)
+
+
+def _snapshot(check: PlatformAlertCheckInput, instance: InstanceCheckState) -> AlertSnapshot:
+ return AlertSnapshot(
+ state=AlertState(instance.state),
+ cooldown=timedelta(minutes=check.cooldown_minutes),
+ last_notified_at=instance.last_notified_at,
+ snooze_until=instance.snooze_until,
+ consecutive_failures=check.consecutive_failures,
+ firing_started_at=instance.firing_started_at,
+ )
+
+
+def _request(
+ source: SourceKind, check: PlatformAlertCheckInput, recorded: PlatformAlertOutcome, decision: GroupDecision
+) -> AlertDeliveryRequest | None:
+ """The delivery for a recorded outcome, or None when it neither announces nor moves a firing.
+
+ A firing that opens or closes needs a delivery even when cooldown or mute held the message,
+ because a paging destination needs one resolve for every trigger.
+ """
+ destination_alert_id = str(check.destination_alert_id)
+ actions = {
+ verdict.group.grouping_key: action
+ for verdict in decision.verdicts
+ if (
+ action := decide_incident_action(
+ verdict.snapshot.state, verdict.outcome.new_state, policy=PLATFORM_WAREHOUSE_ALERT_POLICY
+ )
+ )
+ is not None
+ }
+ if actions and not configured_destination_template_ids(
+ team_id=check.team_id,
+ alert_id=destination_alert_id,
+ allowed_event_ids=tuple(EVENT_IDS_BY_INCIDENT_ACTION[source].values()),
+ ):
+ actions = {}
+ sends_messages = any(verdict.outcome.notification != NotificationAction.NONE for verdict in decision.verdicts)
+ if not sends_messages and not actions:
+ return None
+ alert_url = source_alerts_url if source == SourceKind.WAREHOUSE_SOURCE else destination_alerts_url
+ return AlertDeliveryRequest(
+ source=source,
+ team_id=check.team_id,
+ configuration_id=str(check.id),
+ evaluation_key=recorded.evaluation_key,
+ destination_alert_id=destination_alert_id,
+ event_ids_by_kind=EVENT_IDS_BY_KIND[source],
+ event_ids_by_incident_action=EVENT_IDS_BY_INCIDENT_ACTION[source],
+ incident_actions=actions,
+ sends_messages=sends_messages,
+ source_alert_url=alert_url(check.team_id, check.destination_alert_id),
+ owned_by_platform=check.owned_by_platform,
+ overflowed=recorded.overflowed,
+ overflow_is_lower_bound=recorded.overflow_is_lower_bound,
+ parts=delivery_parts(recorded, actions),
+ )
+
+
+def _collect(source: SourceKind, decided: Sequence[Decision], *, team_id: int, slot: str) -> SourceBatchEvaluation:
+ """The batch, held to one payload. A check that does not fit keeps its due time for a later tick."""
+ outcomes: list[PlatformAlertOutcome] = []
+ deliveries: list[AlertDeliveryRequest] = []
+ deferred = 0
+ spent = 0
+ for outcome, delivery in decided:
+ size = payload_bytes(outcome) + (payload_bytes(delivery) if delivery is not None else 0)
+ if spent + size > MAX_BATCH_PAYLOAD_BYTES:
+ deferred += 1
+ continue
+ spent += size
+ outcomes.append(outcome)
+ if delivery is not None:
+ deliveries.append(delivery)
+ if deferred:
+ logger.warning(
+ "Deferred warehouse alert checks over the batch payload budget",
+ source=source.value,
+ team_id=team_id,
+ slot=slot,
+ deferred=deferred,
+ )
+ safe_record(increment_checks_deferred, source.value, deferred)
+ return SourceBatchEvaluation(outcomes=tuple(outcomes), deliveries=tuple(deliveries), omitted=deferred)
+
+
+def _open_keys(checks: Sequence[PlatformAlertCheckInput]) -> set[str]:
+ return {key for check in checks for key in check.open_keys()}
+
+
+def _scoped_ids(checks: Sequence[PlatformAlertCheckInput], config_key: str) -> set[str] | None:
+ """Every id the batch's checks watch, or None when one of them watches them all.
+
+ The read is cut to these ids before its row limit, so a scoped check is not starved by other rows.
+ """
+ ids: set[str] = set()
+ for check in checks:
+ scope = check.source_config.get(config_key) or []
+ if not scope:
+ return None
+ ids.update(str(item) for item in scope)
+ return set(_uuids(ids))
+
+
+def _source_display(source_type: str, prefix: str | None) -> str:
+ return f"{source_type} ({prefix})" if prefix else source_type
+
+
+def _read_sources(team_id: int, checks: Sequence[PlatformAlertCheckInput]) -> _Reading:
+ statuses = FAILED_STATUSES | (
+ BILLING_LIMIT_STATUSES if any(check.source_config.get("include_billing_limits") for check in checks) else set()
+ )
+ query = (
+ ExternalDataSchema.objects.filter(team_id=team_id, status__in=statuses)
+ # `deleted` is nullable, and a NULL row is not deleted.
+ .exclude(deleted=True)
+ .exclude(source__deleted=True)
+ )
+ if (scoped := _scoped_ids(checks, "source_ids")) is not None:
+ query = query.filter(source_id__in=scoped)
+ schemas = list(
+ query
+ # A schema the user turned off keeps its last status, and is not failing. One PostHog
+ # turned off after an error it cannot retry past is.
+ .filter(Q(should_sync=True) | Q(auto_disabled_at__isnull=False))
+ .select_related("source")
+ # Decrypted only for the sources whose errors need redacting, below.
+ .defer("source__job_inputs")
+ .order_by("source_id", "name", "id")[: MAX_FAILING_ROWS + 1]
+ )
+ truncated = len(schemas) > MAX_FAILING_ROWS
+ schemas = schemas[:MAX_FAILING_ROWS]
+ secrets = _secret_values(
+ team_id, {schema.source_id for schema in schemas if schema.latest_error and schema.status in FAILED_STATUSES}
+ )
+
+ failing: list[_Failing] = []
+ for schema in schemas:
+ source_id = str(schema.source_id)
+ if schema.status in BILLING_LIMIT_STATUSES:
+ reason = _BILLING_REASONS[schema.status]
+ elif schema.latest_error:
+ # The error can quote a connection string or a request URL, and the message leaves PostHog.
+ reason = (
+ redact_error_message(schema.latest_error, secrets.get(source_id, frozenset())) or _FAILED_WITHOUT_ERROR
+ )
+ else:
+ reason = _FAILED_WITHOUT_ERROR
+ failing.append(
+ _Failing(
+ group_ids={"schema": str(schema.id), "source": source_id},
+ status=schema.status or "",
+ labels={
+ SOURCE_ID_KEY: source_id,
+ SOURCE_LABEL: _source_display(schema.source.source_type, schema.source.prefix),
+ SCHEMA_LABEL: schema.name,
+ REASON_LABEL: reason,
+ },
+ )
+ )
+
+ failing_keys = {key for row in failing for key in row.group_ids.values()}
+ open_keys = _open_keys(checks)
+ resolved = open_keys - failing_keys
+ return _Reading(
+ failing=tuple(failing),
+ truncated=truncated,
+ # A row can still be present in the batch-wide failing read while one check excludes its
+ # status (for example, a billing limit). Hydrate every open key so that check can resolve
+ # with its source and table names.
+ resolved_labels=_source_labels(team_id, open_keys),
+ retrying=_retrying_keys(team_id, resolved),
+ )
+
+
+def _secret_values(team_id: int, source_ids: set[UUID]) -> dict[str, frozenset[str]]:
+ if not source_ids:
+ return {}
+ return {
+ str(source.id): get_error_redaction_values(source)
+ for source in ExternalDataSource.objects.filter(team_id=team_id, id__in=source_ids)
+ }
+
+
+def _source_labels(team_id: int, keys: set[str]) -> dict[str, dict[str, str]]:
+ """Names for groups that stopped failing, so the resolve says what recovered. Deleted rows count too."""
+ if not keys:
+ return {}
+ labels: dict[str, dict[str, str]] = {}
+ ids = _uuids(keys)
+ for schema_id, name, source_id, source_type, prefix in ExternalDataSchema.objects.filter(
+ team_id=team_id, id__in=ids
+ ).values_list("id", "name", "source_id", "source__source_type", "source__prefix"):
+ labels[str(schema_id)] = {
+ SOURCE_ID_KEY: str(source_id),
+ SOURCE_LABEL: _source_display(source_type, prefix),
+ SCHEMA_LABEL: name,
+ }
+ for source_id, source_type, prefix in ExternalDataSource.objects.filter(team_id=team_id, id__in=ids).values_list(
+ "id", "source_type", "prefix"
+ ):
+ labels[str(source_id)] = {SOURCE_ID_KEY: str(source_id), SOURCE_LABEL: _source_display(source_type, prefix)}
+ return labels
+
+
+def _retrying_keys(team_id: int, keys: set[str]) -> frozenset[str]:
+ """The keys among `keys` with a sync running again: a table that runs, or a source with a table that runs.
+
+ A retry paints a failed table Running, so its group must not resolve until the retry ends.
+ """
+ if not keys:
+ return frozenset()
+ ids = _uuids(keys)
+ running = (
+ ExternalDataSchema.objects.filter(team_id=team_id, status=Status.RUNNING, should_sync=True)
+ .exclude(deleted=True)
+ .exclude(source__deleted=True)
+ .filter(Q(id__in=ids) | Q(source_id__in=ids))
+ .values_list("id", "source_id")
+ )
+ return frozenset(str(item) for row in running for item in row) & keys
+
+
+def _read_destinations(team_id: int, checks: Sequence[PlatformAlertCheckInput]) -> _Reading:
+ destinations = ExternalDataDestination.objects.for_team(team_id, canonical=True)
+ failing_query = destinations.filter(deleted=False, status__in=FAILING_DESTINATION_STATUSES)
+ if (scoped := _scoped_ids(checks, "destination_ids")) is not None:
+ failing_query = failing_query.filter(id__in=scoped)
+ rows = list(
+ failing_query.order_by("name", "id").values_list("id", "name", "type", "status", "latest_error")[
+ : MAX_FAILING_ROWS + 1
+ ]
+ )
+ truncated = len(rows) > MAX_FAILING_ROWS
+ failing = tuple(
+ _Failing(
+ group_ids={"destination": str(destination_id)},
+ status=status,
+ labels={
+ DESTINATION_LABEL: name,
+ DESTINATION_TYPE_LABEL: _destination_type_label(destination_type),
+ STATUS_LABEL: ExternalDataDestination.Status(status).label,
+ # Saved in words safe to show the user, without credentials.
+ REASON_LABEL: latest_error or _DESTINATION_FAILED_WITHOUT_ERROR,
+ },
+ )
+ for destination_id, name, destination_type, status, latest_error in rows[:MAX_FAILING_ROWS]
+ )
+ resolved = _open_keys(checks) - {row.group_ids["destination"] for row in failing}
+ resolved_labels: dict[str, dict[str, str]] = {}
+ if resolved:
+ for destination_id, name, destination_type in destinations.filter(id__in=_uuids(resolved)).values_list(
+ "id", "name", "type"
+ ):
+ resolved_labels[str(destination_id)] = {
+ DESTINATION_LABEL: name,
+ DESTINATION_TYPE_LABEL: _destination_type_label(destination_type),
+ }
+ return _Reading(failing=failing, truncated=truncated, resolved_labels=resolved_labels)
+
+
+def _destination_type_label(destination_type: str) -> str:
+ if destination_type in ExternalDataDestination.Type.values:
+ return str(ExternalDataDestination.Type(destination_type).label)
+ return destination_type
+
+
+def _uuids(keys: set[str]) -> list[str]:
+ # An open key is a stored id this product minted, but a malformed one must not fail the batch's query.
+ return [key for key in keys if _is_uuid(key)]
+
+
+def _is_uuid(value: str) -> bool:
+ try:
+ UUID(value)
+ except ValueError:
+ return False
+ return True
diff --git a/products/warehouse_sources/backend/sync_alerts/registration.py b/products/warehouse_sources/backend/sync_alerts/registration.py
new file mode 100644
index 000000000000..2965670425aa
--- /dev/null
+++ b/products/warehouse_sources/backend/sync_alerts/registration.py
@@ -0,0 +1,33 @@
+"""Plugs warehouse 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.warehouse_sources.backend.sync_alerts.wording import (
+ describe_destination_transition,
+ describe_source_transition,
+)
+
+
+def load_source_alert_config() -> SourceConfigSpec:
+ from products.warehouse_sources.backend.sync_alerts.source_config import ( # noqa: PLC0415 - keeps the platform API and the destinations layer off the startup path
+ WAREHOUSE_SOURCE_ALERT_CONFIG,
+ )
+
+ return WAREHOUSE_SOURCE_ALERT_CONFIG
+
+
+def load_destination_alert_config() -> SourceConfigSpec:
+ from products.warehouse_sources.backend.sync_alerts.source_config import ( # noqa: PLC0415 - keeps the platform API and the destinations layer off the startup path
+ WAREHOUSE_DESTINATION_ALERT_CONFIG,
+ )
+
+ return WAREHOUSE_DESTINATION_ALERT_CONFIG
+
+
+def register() -> None:
+ # Native delivery only, so no legacy event emitter and no legacy webhook body.
+ register_source_describer(SourceKind.WAREHOUSE_SOURCE, describe_source_transition)
+ register_source_describer(SourceKind.WAREHOUSE_DESTINATION, describe_destination_transition)
+ register_source_config(SourceKind.WAREHOUSE_SOURCE, load_source_alert_config)
+ register_source_config(SourceKind.WAREHOUSE_DESTINATION, load_destination_alert_config)
diff --git a/products/warehouse_sources/backend/sync_alerts/source_config.py b/products/warehouse_sources/backend/sync_alerts/source_config.py
new file mode 100644
index 000000000000..0e46a21dde58
--- /dev/null
+++ b/products/warehouse_sources/backend/sync_alerts/source_config.py
@@ -0,0 +1,156 @@
+"""The `source_config` of a warehouse alert on the alerts platform, and its native lifecycle.
+
+A warehouse 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 collections.abc import Callable
+from typing import Final, Literal
+from uuid import UUID
+
+from pydantic import BaseModel, ConfigDict, Field
+
+from products.alerts.backend.facade.destinations import soft_delete_all_alert_destinations
+from products.alerts_platform.backend.facade.contracts import (
+ GroupingMode,
+ InvalidPlatformAlertEdit,
+ NativeAlertLifecycle,
+ PlatformAlertConfigurationEdit,
+ SourceConfigSpec,
+ SourceKind,
+)
+from products.warehouse_sources.backend.models.external_data_destination import ExternalDataDestination
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.sync_alerts.destinations import EVENT_IDS, EVENT_IDS_BY_INCIDENT_ACTION
+from products.warehouse_sources.backend.sync_alerts.wording import (
+ DEFAULT_GROUP_BY,
+ DESTINATION_ID_KEY,
+ GROUPING_KEY_BY_GROUP_BY,
+ destination_alerts_url,
+ group_by_of,
+ source_alerts_url,
+)
+
+# A sync status changes at most once per sync, so a few minutes of delay costs nothing a user notices.
+CHECK_INTERVAL_MINUTES: Final = 5
+MAX_SCOPED_IDS: Final = 100
+
+_EMAIL_PROJECT_MEMBERS_HELP = (
+ "Whether project members who get data pipeline error emails also get an email when this alert fires or resolves."
+)
+
+
+class WarehouseSourceAlertConfig(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ source_ids: list[UUID] = Field(
+ default_factory=list,
+ max_length=MAX_SCOPED_IDS,
+ description="Warehouse sources the alert watches. Empty watches every source in the project, "
+ "including sources added later.",
+ )
+ group_by: Literal["schema", "source"] = Field(
+ default=DEFAULT_GROUP_BY,
+ description="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: bool = Field(
+ default=False,
+ description="Whether a table that stops syncing at the project's billing limit also fires the alert.",
+ )
+ email_project_members: bool = Field(default=False, description=_EMAIL_PROJECT_MEMBERS_HELP)
+
+
+class WarehouseDestinationAlertConfig(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ destination_ids: list[UUID] = Field(
+ default_factory=list,
+ max_length=MAX_SCOPED_IDS,
+ description="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: bool = Field(default=False, description=_EMAIL_PROJECT_MEMBERS_HELP)
+
+
+def _validate_common(edit: PlatformAlertConfigurationEdit, grouping_key: str) -> None:
+ if edit.grouping.mode != GroupingMode.BY_RESULT_LABELS or edit.grouping.keys != (grouping_key,):
+ raise InvalidPlatformAlertEdit(
+ "grouping", f'Set the grouping mode to by_result_labels with keys ["{grouping_key}"].'
+ )
+ # A sync status is the current state, not a series of samples, so there is nothing to count N of M over.
+ for field_name in ("evaluation_periods", "datapoints_to_alarm"):
+ if getattr(edit, field_name) != 1:
+ raise InvalidPlatformAlertEdit(field_name, "Warehouse alerts check the current sync status. Set it to 1.")
+
+
+def validate_source_edit(edit: PlatformAlertConfigurationEdit) -> None:
+ _validate_common(edit, GROUPING_KEY_BY_GROUP_BY[group_by_of(edit.source_config)])
+
+
+def validate_destination_edit(edit: PlatformAlertConfigurationEdit) -> None:
+ _validate_common(edit, DESTINATION_ID_KEY)
+
+
+def _require_ids_in_team(source_kind: SourceKind, team_id: int, edit: PlatformAlertConfigurationEdit) -> None:
+ """The edit's ids must name this project's own rows. Validation cannot check this, because it has no team."""
+ if source_kind == SourceKind.WAREHOUSE_SOURCE:
+ ids = {str(item) for item in edit.source_config.get("source_ids") or []}
+ found = {
+ str(source_id)
+ for source_id in ExternalDataSource.objects.filter(team_id=team_id, deleted=False, id__in=ids).values_list(
+ "id", flat=True
+ )
+ }
+ noun = "source"
+ else:
+ ids = {str(item) for item in edit.source_config.get("destination_ids") or []}
+ found = {
+ str(destination_id)
+ for destination_id in ExternalDataDestination.objects.for_team(team_id, canonical=True)
+ .filter(deleted=False, id__in=ids)
+ .values_list("id", flat=True)
+ }
+ noun = "destination"
+ if missing := sorted(ids - found):
+ raise InvalidPlatformAlertEdit("source_config", f"No {noun} in this project has the ID {', '.join(missing)}.")
+
+
+def _spec(
+ source_kind: SourceKind,
+ model: type[BaseModel],
+ validate: Callable[[PlatformAlertConfigurationEdit], None],
+ alert_url: Callable[[int, UUID], str],
+) -> SourceConfigSpec:
+ def check_in_team(*, team_id: int, edit: PlatformAlertConfigurationEdit) -> None:
+ _require_ids_in_team(source_kind, team_id, edit)
+
+ 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[source_kind]
+ )
+
+ return SourceConfigSpec(
+ model=model,
+ validate=validate,
+ check_in_team=check_in_team,
+ native=NativeAlertLifecycle(
+ check_interval_minutes=CHECK_INTERVAL_MINUTES, remove_destinations=remove_destinations
+ ),
+ incident_event_ids=EVENT_IDS_BY_INCIDENT_ACTION[source_kind],
+ alert_url=alert_url,
+ )
+
+
+WAREHOUSE_SOURCE_ALERT_CONFIG: Final = _spec(
+ SourceKind.WAREHOUSE_SOURCE, WarehouseSourceAlertConfig, validate_source_edit, source_alerts_url
+)
+WAREHOUSE_DESTINATION_ALERT_CONFIG: Final = _spec(
+ SourceKind.WAREHOUSE_DESTINATION, WarehouseDestinationAlertConfig, validate_destination_edit, destination_alerts_url
+)
+
+ALERT_CONFIGS: Final[dict[SourceKind, SourceConfigSpec]] = {
+ SourceKind.WAREHOUSE_SOURCE: WAREHOUSE_SOURCE_ALERT_CONFIG,
+ SourceKind.WAREHOUSE_DESTINATION: WAREHOUSE_DESTINATION_ALERT_CONFIG,
+}
diff --git a/products/warehouse_sources/backend/sync_alerts/wording.py b/products/warehouse_sources/backend/sync_alerts/wording.py
new file mode 100644
index 000000000000..e193fda4296d
--- /dev/null
+++ b/products/warehouse_sources/backend/sync_alerts/wording.py
@@ -0,0 +1,107 @@
+"""How a warehouse sync 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 evaluation puts the names and the error in the group's labels.
+
+Imported from `ready()`, so it stays light: no models, no query layer.
+"""
+
+from typing import Any, Final, Literal
+from uuid import UUID
+
+from posthog.utils import absolute_uri
+
+from products.alerts_platform.backend.facade.contracts import (
+ AnnouncedTransition,
+ MessageDetail,
+ MessageLink,
+ SourceDescription,
+)
+
+GroupBy = Literal["schema", "source"]
+GROUP_BY_KEY: Final = "group_by"
+DEFAULT_GROUP_BY: Final[GroupBy] = "source"
+
+# The result label each `group_by` keys its groups on, which the alert's grouping must name.
+SCHEMA_ID_KEY: Final = "schema_id"
+SOURCE_ID_KEY: Final = "source_id"
+DESTINATION_ID_KEY: Final = "destination_id"
+GROUPING_KEY_BY_GROUP_BY: Final[dict[GroupBy, str]] = {"schema": SCHEMA_ID_KEY, "source": SOURCE_ID_KEY}
+
+# The platform keeps at most four labels per group, so each kind uses exactly four.
+SOURCE_LABEL: Final = "source"
+SCHEMA_LABEL: Final = "schema"
+REASON_LABEL: Final = "reason"
+DESTINATION_LABEL: Final = "destination"
+DESTINATION_TYPE_LABEL: Final = "destination_type"
+STATUS_LABEL: Final = "status"
+
+
+def sources_url(team_id: int) -> str:
+ return absolute_uri(f"/project/{team_id}/data-management/sources")
+
+
+def source_url(team_id: int, source_id: str) -> str:
+ return absolute_uri(f"/project/{team_id}/data-management/sources/managed-{source_id}/syncs")
+
+
+def destinations_url(team_id: int) -> str:
+ return absolute_uri(f"/project/{team_id}/data-management/warehouse-destinations")
+
+
+def destination_url(team_id: int, destination_id: str) -> str:
+ return absolute_uri(f"/project/{team_id}/data-management/warehouse-destinations?destination={destination_id}")
+
+
+def source_alerts_url(team_id: int, _configuration_id: UUID) -> str:
+ """Where a warehouse sync alert's messages link. The alert has no page of its own yet."""
+ return sources_url(team_id)
+
+
+def destination_alerts_url(team_id: int, _configuration_id: UUID) -> str:
+ return destinations_url(team_id)
+
+
+def group_by_of(source_config: dict[str, Any]) -> GroupBy:
+ return "schema" if source_config.get(GROUP_BY_KEY) == "schema" else DEFAULT_GROUP_BY
+
+
+def describe_source_transition(*, project_id: int, transition: AnnouncedTransition) -> SourceDescription:
+ labels = transition.labels
+ per_source = group_by_of(transition.source_config) == "source"
+ details = [
+ MessageDetail(label=label, value=labels[key])
+ for label, key in (
+ ("Source", SOURCE_LABEL),
+ ("Failing tables" if per_source else "Table", SCHEMA_LABEL),
+ ("Error", REASON_LABEL),
+ )
+ if labels.get(key)
+ ]
+ source_id = labels.get(SOURCE_ID_KEY)
+ link = (
+ MessageLink(label="View source", url=source_url(project_id, source_id))
+ if source_id
+ else MessageLink(label="View sources", url=sources_url(project_id))
+ )
+ return SourceDescription(details=tuple(details), data_link=link)
+
+
+def describe_destination_transition(*, project_id: int, transition: AnnouncedTransition) -> SourceDescription:
+ labels = transition.labels
+ details = [
+ MessageDetail(label=label, value=labels[key])
+ for label, key in (
+ ("Destination", DESTINATION_LABEL),
+ ("Type", DESTINATION_TYPE_LABEL),
+ ("Status", STATUS_LABEL),
+ ("Error", REASON_LABEL),
+ )
+ if labels.get(key)
+ ]
+ link = (
+ MessageLink(label="View destination", url=destination_url(project_id, transition.grouping_key))
+ if transition.grouping_key
+ else MessageLink(label="View destinations", url=destinations_url(project_id))
+ )
+ return SourceDescription(details=tuple(details), data_link=link)
diff --git a/products/warehouse_sources/backend/temporal/sync_alert_evaluate.py b/products/warehouse_sources/backend/temporal/sync_alert_evaluate.py
new file mode 100644
index 000000000000..a59498c72a5f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/sync_alert_evaluate.py
@@ -0,0 +1,85 @@
+"""Temporal wiring for warehouse alerts on the shared alerts platform.
+
+The evaluation itself lives in `products/warehouse_sources/backend/sync_alerts/evaluation.py`, so it
+stays a plain function a test can call without Temporal. One workflow serves both warehouse kinds,
+because the dispatcher passes the kind in its inputs.
+"""
+
+import datetime as dt
+
+from temporalio import activity, workflow
+from temporalio.common import RetryPolicy
+
+from posthog.temporal.common.base import PostHogWorkflow
+
+with workflow.unsafe.imports_passed_through():
+ from posthog.temporal.common.utils import close_db_connections
+
+ from products.alerts_platform.backend.facade.contracts import (
+ RECORD_OUTCOMES_ACTIVITY,
+ SourceBatchEvaluation,
+ SourceEvaluationInputs,
+ SourceOutcomeInputs,
+ )
+ from products.alerts_platform.backend.facade.payload import outcome_chunks
+ from products.alerts_platform.backend.facade.temporal import start_deliveries
+
+WORKFLOW_NAME = "warehouse-alert-evaluate"
+
+EVALUATE_START_TO_CLOSE = dt.timedelta(seconds=20)
+EVALUATE_SCHEDULE_TO_CLOSE = dt.timedelta(seconds=30)
+RECORD_START_TO_CLOSE = dt.timedelta(seconds=8)
+RECORD_SCHEDULE_TO_CLOSE = dt.timedelta(seconds=12)
+
+
+@close_db_connections
+def evaluate_warehouse_alerts_activity(inputs: SourceEvaluationInputs) -> SourceBatchEvaluation:
+ """Sync, so the thread this blocks is a slot Temporal is accounting for."""
+ # Imported in the body, because the workflow below makes this module load inside Temporal's
+ # sandbox, which refuses a Django model import.
+ from products.warehouse_sources.backend.sync_alerts.evaluation import ( # noqa: PLC0415
+ evaluate_warehouse_alert_batch,
+ )
+
+ return evaluate_warehouse_alert_batch(
+ inputs.source, inputs.batch_key.team_id, inputs.batch_key.slot, dt.datetime.fromisoformat(inputs.cutoff)
+ )
+
+
[email protected](name=WORKFLOW_NAME)
+class WarehouseAlertEvaluateWorkflow(PostHogWorkflow):
+ """Evaluates one batch key, records what it decided, and starts the deliveries it asked for."""
+
+ inputs_cls = SourceEvaluationInputs
+
+ @workflow.run
+ async def run(self, inputs: SourceEvaluationInputs) -> int:
+ # One attempt. The evaluation writes nothing, so a lost attempt leaves the checks due and
+ # the next tick reads them again.
+ evaluation = await workflow.execute_activity(
+ evaluate_warehouse_alerts_activity,
+ inputs,
+ start_to_close_timeout=EVALUATE_START_TO_CLOSE,
+ schedule_to_close_timeout=EVALUATE_SCHEDULE_TO_CLOSE,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+ started = 0
+ for chunk in outcome_chunks(evaluation.outcomes):
+ await workflow.execute_activity(
+ RECORD_OUTCOMES_ACTIVITY,
+ SourceOutcomeInputs(team_id=inputs.batch_key.team_id, cutoff=inputs.cutoff, outcomes=chunk),
+ start_to_close_timeout=RECORD_START_TO_CLOSE,
+ schedule_to_close_timeout=RECORD_SCHEDULE_TO_CLOSE,
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ # Started only after the record, because a delivery reads the history row the record writes.
+ recorded = {str(outcome.configuration_id) for outcome in chunk}
+ started += await start_deliveries(
+ [delivery for delivery in evaluation.deliveries if delivery.configuration_id in recorded]
+ )
+ return started
+
+
+WAREHOUSE_ALERT_EVALUATION_WORKFLOWS = [WarehouseAlertEvaluateWorkflow]
+WAREHOUSE_ALERT_EVALUATION_ACTIVITIES = [evaluate_warehouse_alerts_activity]
diff --git a/products/warehouse_sources/backend/tests/test_sync_alerts.py b/products/warehouse_sources/backend/tests/test_sync_alerts.py
new file mode 100644
index 000000000000..d2a6cfb42e0e
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/test_sync_alerts.py
@@ -0,0 +1,617 @@
+from datetime import UTC, datetime, timedelta
+from typing import Any
+from uuid import UUID
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models.scoping import team_scope
+from posthog.models.team.team import Team
+
+from products.alerts.backend.facade.destinations import MAX_DESTINATIONS_PER_ALERT, list_alert_destination_groups
+from products.alerts_platform.backend.facade import testing as platform_testing
+from products.alerts_platform.backend.facade.api import (
+ create_configuration,
+ delete_configuration,
+ list_configurations,
+ record_outcomes,
+ slot_of,
+)
+from products.alerts_platform.backend.facade.contracts import (
+ AlertEventKind,
+ AnnouncedTransition,
+ Grouping,
+ GroupingMode,
+ IncidentAction,
+ PlatformAlertConfigurationEdit,
+ PlatformAlertOutcome,
+ SourceBatchEvaluation,
+ SourceKind,
+)
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.cdp.backend.templates.fixtures import template_pagerduty, template_slack
+from products.cdp.backend.templates.hog_function_template import sync_template_to_db
+from products.warehouse_sources.backend.models.external_data_destination import ExternalDataDestination
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.presentation.views import warehouse_alert_destinations as destinations_view
+from products.warehouse_sources.backend.sync_alerts.destinations import EVENT_IDS_BY_KIND
+from products.warehouse_sources.backend.sync_alerts.evaluation import evaluate_warehouse_alert_batch
+from products.warehouse_sources.backend.sync_alerts.wording import (
+ describe_destination_transition,
+ describe_source_transition,
+)
+
+Status = ExternalDataSchema.Status
+DestinationStatus = ExternalDataDestination.Status
+SECRET = "hunter2-correct-horse"
+PAGERDUTY_ROUTING_KEY = "0123456789abcdef0123456789abcdef"
+
+
+class TestWarehouseAlerts(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.cutoff = timezone.now().replace(second=0, microsecond=0) + timedelta(minutes=5)
+ self.enterContext(patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True))
+
+ def _source(self, team: Team | None = None, prefix: str | None = None, **fields: Any) -> ExternalDataSource:
+ return ExternalDataSource.objects.create(
+ team=team or self.team,
+ source_id="src",
+ connection_id="conn",
+ status="Running",
+ source_type="Postgres",
+ prefix=prefix,
+ **fields,
+ )
+
+ def _schema(self, source: ExternalDataSource, name: str, status_: str, **fields: Any) -> ExternalDataSchema:
+ return ExternalDataSchema.objects.create(
+ team=self.team, source=source, name=name, status=status_, latest_error=f"{name} broke", **fields
+ )
+
+ def _destination(self, name: str, status_: str, team: Team | None = None, **fields: Any) -> ExternalDataDestination:
+ team_id = (team or self.team).pk
+ return ExternalDataDestination.objects.for_team(team_id).create(
+ team_id=team_id, type=ExternalDataDestination.Type.SNOWFLAKE, name=name, status=status_, **fields
+ )
+
+ def _alert(
+ self,
+ kind: SourceKind,
+ source_config: dict[str, Any],
+ grouping_key: str,
+ schedule_restriction: dict[str, Any] | None = None,
+ ) -> UUID:
+ with team_scope(self.team.id):
+ view = create_configuration(
+ team_id=self.team.id,
+ source_kind=kind,
+ edit=PlatformAlertConfigurationEdit(
+ name="Sync failures",
+ enabled=True,
+ source_config=source_config,
+ grouping=Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=(grouping_key,)),
+ schedule_restriction=schedule_restriction,
+ evaluation_periods=1,
+ datapoints_to_alarm=1,
+ cooldown_minutes=0,
+ ),
+ created_by_id=self.user.id,
+ )
+ platform_testing.set_due_at(view.id, self.cutoff - timedelta(minutes=1))
+ return view.id
+
+ def _evaluate(self, kind: SourceKind) -> SourceBatchEvaluation:
+ with team_scope(self.team.id):
+ return evaluate_warehouse_alert_batch(
+ kind, self.team.id, slot_of(self.cutoff - timedelta(minutes=1), self.cutoff), self.cutoff
+ )
+
+ def _only_outcome(self, evaluation: SourceBatchEvaluation) -> PlatformAlertOutcome:
+ (outcome,) = evaluation.outcomes
+ return outcome
+
+ def _next_check(self, configuration_id: UUID, outcome: PlatformAlertOutcome) -> None:
+ with team_scope(self.team.id):
+ record_outcomes(self.team.id, [outcome], self.cutoff)
+ self.cutoff += timedelta(minutes=5)
+ platform_testing.set_due_at(configuration_id, self.cutoff - timedelta(minutes=1))
+
+ def _add_pagerduty(self, configuration_id: UUID) -> list[str]:
+ sync_template_to_db(template_pagerduty)
+ added = self.client.post(
+ f"/api/projects/{self.team.id}/warehouse_alerts/{configuration_id}/destinations/",
+ {"type": "pagerduty", "pagerduty_routing_key": PAGERDUTY_ROUTING_KEY},
+ format="json",
+ )
+ assert added.status_code == status.HTTP_201_CREATED, added.json()
+ return added.json()["hog_function_ids"]
+
+ def _create_on_the_platform(self, body: dict[str, Any]) -> Any:
+ return self.client.post(f"/api/projects/{self.team.id}/platform_alerts/", body, format="json")
+
+ @parameterized.expand(
+ [
+ ("every_source_by_table", {"group_by": "schema"}, "schema_id", {"a_failed", "a_halted", "b_failed"}),
+ (
+ "billing_limits_included",
+ {"group_by": "schema", "include_billing_limits": True},
+ "schema_id",
+ {"a_failed", "a_halted", "a_billing", "b_failed"},
+ ),
+ ("one_source_in_scope", {"group_by": "schema", "source_ids": ["a"]}, "schema_id", {"a_failed", "a_halted"}),
+ ("grouped_by_source", {"group_by": "source"}, "source_id", {"a", "b"}),
+ ]
+ )
+ def test_a_source_check_fires_for_each_failing_group_in_scope(
+ self, _name: str, source_config: dict[str, Any], grouping_key: str, expected: set[str]
+ ) -> None:
+ sources = {"a": self._source(prefix="prod"), "b": self._source()}
+ ids = {name: str(source.id) for name, source in sources.items()}
+ schemas: list[tuple[str, str, str, dict[str, Any]]] = [
+ ("a_failed", "a", Status.FAILED, {}),
+ ("a_completed", "a", Status.COMPLETED, {}),
+ ("a_billing", "a", Status.BILLING_LIMIT_REACHED, {}),
+ ("a_deleted", "a", Status.FAILED, {"deleted": True}),
+ ("a_turned_off", "a", Status.FAILED, {"should_sync": False}),
+ ("a_halted", "a", Status.FAILED, {"should_sync": False, "auto_disabled_at": timezone.now()}),
+ ("b_failed", "b", Status.FAILED, {}),
+ ]
+ for name, source_name, status_, fields in schemas:
+ ids[name] = str(self._schema(sources[source_name], name, status_, **fields).id)
+ self._source(team=Team.objects.create(organization=self.organization), prefix="other")
+ if "source_ids" in source_config:
+ source_config = {**source_config, "source_ids": [ids[name] for name in source_config["source_ids"]]}
+
+ self._alert(SourceKind.WAREHOUSE_SOURCE, source_config, grouping_key)
+ evaluation = self._evaluate(SourceKind.WAREHOUSE_SOURCE)
+
+ outcome = self._only_outcome(evaluation)
+ assert {group.grouping_key: group.kind for group in outcome.groups} == {
+ ids[name]: AlertEventKind.FIRING for name in expected
+ }
+ if grouping_key == "source_id":
+ assert {group.grouping_key: group.value for group in outcome.groups} == {ids["a"]: 2.0, ids["b"]: 1.0}
+ (delivery,) = evaluation.deliveries
+ assert (delivery.sends_messages, delivery.owned_by_platform, delivery.event_ids_by_kind) == (
+ True,
+ True,
+ {"firing": "$warehouse_source_alert_firing", "resolved": "$warehouse_source_alert_resolved"},
+ )
+
+ @parameterized.expand(
+ [
+ ("synced_again", {"status": Status.COMPLETED}),
+ ("deleted", {"deleted": True}),
+ ("turned_off", {"should_sync": False}),
+ ]
+ )
+ def test_a_table_that_stops_failing_resolves_and_the_resolve_names_it(
+ self, _name: str, change: dict[str, Any]
+ ) -> None:
+ schema = self._schema(self._source(prefix="prod"), "charges", Status.FAILED)
+ configuration_id = self._alert(SourceKind.WAREHOUSE_SOURCE, {"group_by": "schema"}, "schema_id")
+ self._next_check(configuration_id, self._only_outcome(self._evaluate(SourceKind.WAREHOUSE_SOURCE)))
+ ExternalDataSchema.objects.filter(id=schema.id).update(**change)
+
+ evaluation = self._evaluate(SourceKind.WAREHOUSE_SOURCE)
+
+ (group,) = self._only_outcome(evaluation).groups
+ assert (group.grouping_key, group.kind, group.labels["schema"], group.labels["source"]) == (
+ str(schema.id),
+ AlertEventKind.RESOLVED,
+ "charges",
+ "Postgres (prod)",
+ )
+ (delivery,) = evaluation.deliveries
+ assert delivery.sends_messages
+
+ def test_a_table_that_keeps_failing_announces_once(self) -> None:
+ self._schema(self._source(), "charges", Status.FAILED)
+ configuration_id = self._alert(SourceKind.WAREHOUSE_SOURCE, {"group_by": "schema"}, "schema_id")
+ self._next_check(configuration_id, self._only_outcome(self._evaluate(SourceKind.WAREHOUSE_SOURCE)))
+
+ evaluation = self._evaluate(SourceKind.WAREHOUSE_SOURCE)
+
+ (group,) = self._only_outcome(evaluation).groups
+ assert (group.kind, group.new_state, evaluation.deliveries) == (AlertEventKind.CHECK, "firing", ())
+
+ def test_a_billing_limit_resolution_keeps_labels_when_another_check_includes_limits(self) -> None:
+ schema = self._schema(self._source(prefix="prod"), "charges", Status.FAILED)
+ excluding_id = self._alert(SourceKind.WAREHOUSE_SOURCE, {"group_by": "schema"}, "schema_id")
+ including_id = self._alert(
+ SourceKind.WAREHOUSE_SOURCE,
+ {"group_by": "schema", "include_billing_limits": True},
+ "schema_id",
+ )
+ initial = self._evaluate(SourceKind.WAREHOUSE_SOURCE)
+ with team_scope(self.team.id):
+ record_outcomes(self.team.id, initial.outcomes, self.cutoff)
+ self.cutoff += timedelta(minutes=5)
+ for configuration_id in (excluding_id, including_id):
+ platform_testing.set_due_at(configuration_id, self.cutoff - timedelta(minutes=1))
+ ExternalDataSchema.objects.filter(id=schema.id).update(status=Status.BILLING_LIMIT_REACHED)
+
+ outcomes = {
+ outcome.configuration_id: outcome for outcome in self._evaluate(SourceKind.WAREHOUSE_SOURCE).outcomes
+ }
+
+ (resolved,) = outcomes[excluding_id].groups
+ assert (resolved.kind, resolved.labels["schema"], resolved.labels["source"]) == (
+ AlertEventKind.RESOLVED,
+ "charges",
+ "Postgres (prod)",
+ )
+ (still_firing,) = outcomes[including_id].groups
+ assert still_firing.kind == AlertEventKind.CHECK
+
+ @parameterized.expand([("by_table", "schema", "schema_id"), ("by_source", "source", "source_id")])
+ def test_a_failed_table_that_retries_stays_open_until_the_retry_ends(
+ self, _name: str, group_by: str, grouping_key: str
+ ) -> None:
+ schema = self._schema(self._source(), "charges", Status.FAILED)
+ configuration_id = self._alert(SourceKind.WAREHOUSE_SOURCE, {"group_by": group_by}, grouping_key)
+ self._next_check(configuration_id, self._only_outcome(self._evaluate(SourceKind.WAREHOUSE_SOURCE)))
+ ExternalDataSchema.objects.filter(id=schema.id).update(status=Status.RUNNING)
+
+ retrying = self._evaluate(SourceKind.WAREHOUSE_SOURCE)
+
+ assert [group.kind for group in self._only_outcome(retrying).groups] == []
+ assert retrying.deliveries == ()
+ self._next_check(configuration_id, self._only_outcome(retrying))
+ ExternalDataSchema.objects.filter(id=schema.id).update(status=Status.COMPLETED)
+
+ (group,) = self._only_outcome(self._evaluate(SourceKind.WAREHOUSE_SOURCE)).groups
+ assert group.kind == AlertEventKind.RESOLVED
+
+ def test_a_scoped_check_sees_its_source_past_the_row_limit(self) -> None:
+ crowded, watched = self._source(), self._source()
+ for name in ("a", "b", "c"):
+ self._schema(crowded, name, Status.FAILED)
+ schema = self._schema(watched, "charges", Status.FAILED)
+ self._alert(SourceKind.WAREHOUSE_SOURCE, {"group_by": "schema", "source_ids": [str(watched.id)]}, "schema_id")
+
+ with patch("products.warehouse_sources.backend.sync_alerts.evaluation.MAX_FAILING_ROWS", 1):
+ (group,) = self._only_outcome(self._evaluate(SourceKind.WAREHOUSE_SOURCE)).groups
+
+ assert (group.grouping_key, group.kind) == (str(schema.id), AlertEventKind.FIRING)
+
+ def test_the_error_a_message_quotes_hides_the_source_credentials(self) -> None:
+ source = self._source(job_inputs={"host": "db.example.com", "password": SECRET})
+ ExternalDataSchema.objects.create(
+ team=self.team,
+ source=source,
+ name="charges",
+ status=Status.FAILED,
+ latest_error=f"could not connect with password {SECRET}",
+ )
+ self._alert(SourceKind.WAREHOUSE_SOURCE, {"group_by": "schema"}, "schema_id")
+
+ (group,) = self._only_outcome(self._evaluate(SourceKind.WAREHOUSE_SOURCE)).groups
+
+ assert group.labels["reason"] == "could not connect with password ***"
+
+ @parameterized.expand(
+ [
+ ("every_destination", [], {"failing", "paused"}),
+ ("one_in_scope", ["paused"], {"paused"}),
+ ]
+ )
+ def test_a_destination_check_fires_for_each_failing_destination_in_scope(
+ self, _name: str, scope: list[str], expected: set[str]
+ ) -> None:
+ destinations = {
+ "failing": self._destination("Snowflake prod", DestinationStatus.FAILING, latest_error="Wrong password"),
+ "paused": self._destination("Snowflake dev", DestinationStatus.PAUSED),
+ "healthy": self._destination("Snowflake eu", DestinationStatus.HEALTHY),
+ "deleted": self._destination("Snowflake old", DestinationStatus.FAILING, deleted=True),
+ }
+ self._alert(
+ SourceKind.WAREHOUSE_DESTINATION,
+ {"destination_ids": [str(destinations[name].id) for name in scope]},
+ "destination_id",
+ )
+
+ outcome = self._only_outcome(self._evaluate(SourceKind.WAREHOUSE_DESTINATION))
+
+ assert {group.grouping_key: group.kind for group in outcome.groups} == {
+ str(destinations[name].id): AlertEventKind.FIRING for name in expected
+ }
+ if "failing" in expected:
+ failing = next(group for group in outcome.groups if group.grouping_key == str(destinations["failing"].id))
+ assert failing.labels == {
+ "destination": "Snowflake prod",
+ "destination_type": "Snowflake",
+ "status": "Failing",
+ "reason": "Wrong password",
+ }
+
+ @parameterized.expand(
+ [
+ (
+ "grouping_does_not_match_group_by",
+ {
+ "source_config": {"group_by": "schema"},
+ "grouping": {"mode": "by_result_labels", "keys": ["source_id"]},
+ },
+ "grouping",
+ ),
+ ("default_single_grouping", {"source_config": {"group_by": "source"}}, "grouping"),
+ (
+ "more_than_one_evaluation_period",
+ {
+ "source_config": {"group_by": "source"},
+ "grouping": {"mode": "by_result_labels", "keys": ["source_id"]},
+ "evaluation_periods": 2,
+ },
+ "evaluation_periods",
+ ),
+ (
+ "source_of_another_project",
+ {
+ "source_config": {"group_by": "source", "source_ids": ["other"]},
+ "grouping": {"mode": "by_result_labels", "keys": ["source_id"]},
+ },
+ "source_config",
+ ),
+ ]
+ )
+ def test_a_refused_create_writes_nothing(self, _name: str, body: dict[str, Any], field: str) -> None:
+ other = self._source(team=Team.objects.create(organization=self.organization))
+ if body["source_config"].get("source_ids"):
+ body = {**body, "source_config": {**body["source_config"], "source_ids": [str(other.id)]}}
+
+ response = self._create_on_the_platform({"source_kind": "warehouse_source", **body})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == field
+ with team_scope(self.team.id):
+ assert (
+ list_configurations(
+ team_id=self.team.id, source_kinds=[SourceKind.WAREHOUSE_SOURCE.value], limit=10, offset=0
+ ).total
+ == 0
+ )
+
+ def test_an_edit_naming_a_destination_of_another_project_changes_nothing(self) -> None:
+ other = self._destination(
+ "Snowflake", DestinationStatus.HEALTHY, team=Team.objects.create(organization=self.organization)
+ )
+ configuration_id = self._alert(SourceKind.WAREHOUSE_DESTINATION, {}, "destination_id")
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/platform_alerts/{configuration_id}/",
+ {"source_kind": "warehouse_destination", "source_config": {"destination_ids": [str(other.id)]}},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ read = self.client.get(f"/api/projects/{self.team.id}/platform_alerts/{configuration_id}/").json()
+ assert read["source_config"] == {}
+
+ @parameterized.expand(
+ [
+ ("alert_only", ["alert:read"], status.HTTP_403_FORBIDDEN),
+ ("warehouse_only", ["external_data_source:read"], status.HTTP_403_FORBIDDEN),
+ ("alert_and_warehouse", ["alert:read", "external_data_source:read"], status.HTTP_200_OK),
+ ]
+ )
+ def test_reading_destinations_needs_both_alert_and_warehouse_scopes(
+ self, _name: str, scopes: list[str], expected: int
+ ) -> None:
+ configuration_id = self._alert(SourceKind.WAREHOUSE_SOURCE, {}, "source_id")
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {self.create_personal_api_key_with_scopes(scopes)}")
+
+ response = self.client.get(f"/api/projects/{self.team.id}/warehouse_alerts/{configuration_id}/destinations/")
+
+ assert response.status_code == expected, response.json()
+
+ def test_an_alert_and_its_slack_destination_route_a_failure_to_that_channel(self) -> None:
+ sync_template_to_db(template_slack)
+ schema = self._schema(self._source(), "charges", Status.FAILED)
+
+ created = self._create_on_the_platform(
+ {
+ "source_kind": "warehouse_source",
+ "name": "Sync failures",
+ "source_config": {"group_by": "schema"},
+ "grouping": {"mode": "by_result_labels", "keys": ["schema_id"]},
+ }
+ )
+ assert created.status_code == status.HTTP_201_CREATED, created.json()
+ alert = created.json()
+ assert self.client.get(f"/api/projects/{self.team.id}/platform_alerts/{alert['id']}/").json() == alert
+ assert alert["owner"] == "platform"
+
+ destinations_url = f"/api/projects/{self.team.id}/warehouse_alerts/{alert['id']}/destinations/"
+ added = self.client.post(
+ destinations_url,
+ {"type": "slack", "slack_workspace_id": 42, "slack_channel_id": "C123", "slack_channel_name": "data"},
+ format="json",
+ )
+ assert added.status_code == status.HTTP_201_CREATED, added.json()
+ hog_function_ids = added.json()["hog_function_ids"]
+ (listed,) = self.client.get(destinations_url).json()
+ assert (listed["type"], listed["slack_channel_id"], sorted(listed["hog_function_ids"])) == (
+ "slack",
+ "C123",
+ sorted(hog_function_ids),
+ )
+
+ with team_scope(self.team.id):
+ platform_testing.set_due_at(UUID(alert["id"]), self.cutoff - timedelta(minutes=1))
+ evaluation = self._evaluate(SourceKind.WAREHOUSE_SOURCE)
+
+ (group,) = self._only_outcome(evaluation).groups
+ assert (group.grouping_key, group.kind) == (str(schema.id), AlertEventKind.FIRING)
+ (delivery,) = evaluation.deliveries
+ assert delivery.destination_alert_id == alert["id"]
+ firing_event_id = delivery.event_ids_by_kind[AlertEventKind.FIRING.value]
+ assert firing_event_id == EVENT_IDS_BY_KIND[SourceKind.WAREHOUSE_SOURCE]["firing"]
+ (routed,) = list_alert_destination_groups(
+ team_id=self.team.id, alert_id=delivery.destination_alert_id, allowed_event_ids=[firing_event_id]
+ )
+ assert routed.data["slack_channel_id"] == "C123"
+
+ deleted = self.client.delete(f"/api/projects/{self.team.id}/platform_alerts/{alert['id']}/")
+ assert deleted.status_code == status.HTTP_204_NO_CONTENT
+ assert not HogFunction.objects.filter(id__in=hog_function_ids, deleted=False).exists()
+
+ @parameterized.expand(
+ [
+ ("announced", None, True),
+ ("quiet_hours", {"blocked_windows": [{"start": "11:00", "end": "13:00"}]}, False),
+ ]
+ )
+ def test_a_pagerduty_incident_follows_the_failure_even_when_quiet_hours_hold_the_message(
+ self, _name: str, schedule_restriction: dict[str, Any] | None, announced: bool
+ ) -> None:
+ self.cutoff = self.cutoff.replace(hour=12, minute=0)
+ schema = self._schema(self._source(), "charges", Status.FAILED)
+ configuration_id = self._alert(
+ SourceKind.WAREHOUSE_SOURCE, {"group_by": "schema"}, "schema_id", schedule_restriction
+ )
+ self._add_pagerduty(configuration_id)
+
+ firing = self._evaluate(SourceKind.WAREHOUSE_SOURCE)
+ (fired,) = firing.deliveries
+ self._next_check(configuration_id, self._only_outcome(firing))
+ ExternalDataSchema.objects.filter(id=schema.id).update(status=Status.COMPLETED)
+ (resolved,) = self._evaluate(SourceKind.WAREHOUSE_SOURCE).deliveries
+
+ assert [(delivery.incident_actions, delivery.sends_messages) for delivery in (fired, resolved)] == [
+ ({str(schema.id): IncidentAction.TRIGGER}, announced),
+ ({str(schema.id): IncidentAction.RESOLVE}, announced),
+ ]
+
+ def test_deleting_a_firing_alert_resolves_its_incident_before_the_destination_goes(self) -> None:
+ schema = self._schema(self._source(), "charges", Status.FAILED)
+ configuration_id = self._alert(SourceKind.WAREHOUSE_SOURCE, {"group_by": "schema"}, "schema_id")
+ hog_function_ids = self._add_pagerduty(configuration_id)
+ self._next_check(configuration_id, self._only_outcome(self._evaluate(SourceKind.WAREHOUSE_SOURCE)))
+ sent: list[tuple[str, dict[str, IncidentAction], int]] = []
+
+ def deliver(request: Any) -> None:
+ live = HogFunction.objects.filter(id__in=hog_function_ids, deleted=False).count()
+ sent.append((request.destination_alert_id, request.incident_actions, live))
+
+ with patch("products.alerts_platform.backend.temporal.web_start.deliver_evaluation", side_effect=deliver):
+ deleted = self.client.delete(f"/api/projects/{self.team.id}/platform_alerts/{configuration_id}/")
+
+ assert deleted.status_code == status.HTTP_204_NO_CONTENT
+ assert sent == [(str(configuration_id), {str(schema.id): IncidentAction.RESOLVE}, len(hog_function_ids))]
+ assert not HogFunction.objects.filter(id__in=hog_function_ids, deleted=False).exists()
+
+ def test_an_alert_takes_only_a_few_destinations(self) -> None:
+ sync_template_to_db(template_slack)
+ configuration_id = self._alert(SourceKind.WAREHOUSE_SOURCE, {}, "source_id")
+ destinations_url = f"/api/projects/{self.team.id}/warehouse_alerts/{configuration_id}/destinations/"
+
+ def add(channel: str) -> Any:
+ return self.client.post(
+ destinations_url,
+ {"type": "slack", "slack_workspace_id": 42, "slack_channel_id": channel},
+ format="json",
+ )
+
+ for index in range(MAX_DESTINATIONS_PER_ALERT):
+ assert add(f"C{index}").status_code == status.HTTP_201_CREATED
+
+ refused = add("C-one-too-many")
+
+ assert refused.status_code == status.HTTP_400_BAD_REQUEST, refused.json()
+ assert len(self.client.get(destinations_url).json()) == MAX_DESTINATIONS_PER_ALERT
+
+ def test_a_destination_added_while_its_alert_is_deleted_is_refused(self) -> None:
+ sync_template_to_db(template_slack)
+ configuration_id = self._alert(SourceKind.WAREHOUSE_SOURCE, {}, "source_id")
+ real_get_configuration = destinations_view.get_configuration
+
+ def deleted_in_between(**kwargs: Any) -> Any:
+ # The alert goes after the request has read it, before its destinations are inserted.
+ if kwargs.get("lock"):
+ delete_configuration(
+ team_id=self.team.id,
+ source_kinds=[SourceKind.WAREHOUSE_SOURCE.value],
+ configuration_id=configuration_id,
+ )
+ return real_get_configuration(**kwargs)
+
+ with patch.object(destinations_view, "get_configuration", side_effect=deleted_in_between):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/warehouse_alerts/{configuration_id}/destinations/",
+ {"type": "slack", "slack_workspace_id": 42, "slack_channel_id": "C1"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND, response.json()
+ assert not HogFunction.objects.filter(team=self.team, deleted=False).exists()
+
+ @parameterized.expand(
+ [
+ (
+ "table",
+ SourceKind.WAREHOUSE_SOURCE,
+ "schema-1",
+ {"group_by": "schema"},
+ {"source_id": "source-1", "source": "Stripe", "schema": "charges", "reason": "Bad key"},
+ [("Source", "Stripe"), ("Table", "charges"), ("Error", "Bad key")],
+ "/project/7/data-management/sources/managed-source-1/syncs",
+ ),
+ (
+ "source",
+ SourceKind.WAREHOUSE_SOURCE,
+ "source-1",
+ {"group_by": "source"},
+ {"source_id": "source-1", "source": "Stripe", "schema": "charges, refunds"},
+ [("Source", "Stripe"), ("Failing tables", "charges, refunds")],
+ "/project/7/data-management/sources/managed-source-1/syncs",
+ ),
+ (
+ "destination",
+ SourceKind.WAREHOUSE_DESTINATION,
+ "destination-1",
+ {},
+ {"destination": "Snowflake prod", "destination_type": "Snowflake", "status": "Paused"},
+ [("Destination", "Snowflake prod"), ("Type", "Snowflake"), ("Status", "Paused")],
+ "/project/7/data-management/warehouse-destinations?destination=destination-1",
+ ),
+ ]
+ )
+ def test_a_message_names_the_failing_group_and_links_to_it(
+ self,
+ _name: str,
+ kind: SourceKind,
+ grouping_key: str,
+ source_config: dict[str, Any],
+ labels: dict[str, str],
+ details: list[tuple[str, str]],
+ path: str,
+ ) -> None:
+ describe = (
+ describe_source_transition if kind == SourceKind.WAREHOUSE_SOURCE else describe_destination_transition
+ )
+ transition = AnnouncedTransition(
+ grouping_key=grouping_key,
+ kind=AlertEventKind.FIRING,
+ episode_started_at=datetime(2026, 10, 1, tzinfo=UTC),
+ value=None,
+ labels=labels,
+ condition={},
+ source_config=source_config,
+ error_message=None,
+ occurred_at=datetime(2026, 10, 1, tzinfo=UTC),
+ )
+
+ description = describe(project_id=7, transition=transition)
+
+ assert [(detail.label, detail.value) for detail in description.details] == details
+ assert description.data_link is not None
+ assert description.data_link.url.endswith(path)
diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.ts
index 3cd39f1189ec..9053fe76ec72 100644
--- a/products/warehouse_sources/frontend/generated/api.schemas.ts
+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts
@@ -14676,6 +14676,134 @@ export interface SourceConfigMapResponseApi {
[key: string]: SourceConfigResponseApi
}
+/**
+ * * `slack` - slack
+ * * `webhook` - webhook
+ * * `teams` - teams
+ * * `discord` - discord
+ * * `pagerduty` - pagerduty
+ */
+export type WarehouseAlertDestinationTypeEnumApi =
+ (typeof WarehouseAlertDestinationTypeEnumApi)[keyof typeof WarehouseAlertDestinationTypeEnumApi]
+
+export const WarehouseAlertDestinationTypeEnumApi = {
+ Slack: 'slack',
+ Webhook: 'webhook',
+ Teams: 'teams',
+ Discord: 'discord',
+ Pagerduty: 'pagerduty',
+} as const
+
+/**
+ * * `critical` - critical
+ * * `error` - error
+ * * `warning` - warning
+ * * `info` - info
+ */
+export type PagerDutySeverityEnumApi = (typeof PagerDutySeverityEnumApi)[keyof typeof PagerDutySeverityEnumApi]
+
+export const PagerDutySeverityEnumApi = {
+ Critical: 'critical',
+ Error: 'error',
+ Warning: 'warning',
+ Info: 'info',
+} as const
+
+/**
+ * * `us` - us
+ * * `eu` - eu
+ */
+export type PagerDutyRegionEnumApi = (typeof PagerDutyRegionEnumApi)[keyof typeof PagerDutyRegionEnumApi]
+
+export const PagerDutyRegionEnumApi = {
+ Us: 'us',
+ Eu: 'eu',
+} as const
+
+export interface WarehouseAlertDestinationApi {
+ /** HogFunction IDs that make up this destination, one per alert event kind it handles. Send them all to the delete endpoint to remove the destination. */
+ hog_function_ids: string[]
+ /** Notification destination type.
+ *
+ * * `slack` - slack
+ * * `webhook` - webhook
+ * * `teams` - teams
+ * * `discord` - discord
+ * * `pagerduty` - pagerduty */
+ type: WarehouseAlertDestinationTypeEnumApi
+ /** Whether every HogFunction of the destination is enabled, so it notifies for every event kind. */
+ enabled: boolean
+ /** Integration ID of the Slack workspace. Set when type=slack. */
+ slack_workspace_id?: number
+ /** Slack channel ID. Set when type=slack. */
+ slack_channel_id?: string
+ /** Human-readable Slack channel name. Set when type=slack. */
+ slack_channel_name?: string
+ /** Webhook endpoint reduced to scheme and host. The path, query and userinfo carry the secret. */
+ webhook_url?: string
+ /** PagerDuty integration key reduced to its last four characters. */
+ pagerduty_routing_key?: string
+ /** Severity of the PagerDuty incident.
+ *
+ * * `critical` - critical
+ * * `error` - error
+ * * `warning` - warning
+ * * `info` - info */
+ pagerduty_severity?: PagerDutySeverityEnumApi
+ /** PagerDuty service region the events go to.
+ *
+ * * `us` - us
+ * * `eu` - eu */
+ pagerduty_region?: PagerDutyRegionEnumApi
+}
+
+export interface WarehouseAlertCreateDestinationApi {
+ /** Notification destination type.
+ *
+ * * `slack` - slack
+ * * `webhook` - webhook
+ * * `teams` - teams
+ * * `discord` - discord
+ * * `pagerduty` - pagerduty */
+ type: WarehouseAlertDestinationTypeEnumApi
+ /** Integration ID for the Slack workspace. Required when type=slack. */
+ slack_workspace_id?: number
+ /** Slack channel ID. Required when type=slack. */
+ slack_channel_id?: string
+ /** Human-readable channel name for display. */
+ slack_channel_name?: string
+ /** HTTPS endpoint to post to. Required for webhook, teams and discord. */
+ webhook_url?: string
+ /** Integration key of a PagerDuty Events API v2 integration. Required when type=pagerduty. */
+ pagerduty_routing_key?: string
+ /** Severity PagerDuty records on the incident. Used when type=pagerduty.
+ *
+ * * `critical` - critical
+ * * `error` - error
+ * * `warning` - warning
+ * * `info` - info */
+ pagerduty_severity?: PagerDutySeverityEnumApi
+ /** PagerDuty service region of the account. Used when type=pagerduty.
+ *
+ * * `us` - us
+ * * `eu` - eu */
+ pagerduty_region?: PagerDutyRegionEnumApi
+}
+
+export interface WarehouseAlertDestinationCreatedApi {
+ /** HogFunction IDs created for the destination, one per event kind. */
+ hog_function_ids: string[]
+}
+
+export interface WarehouseAlertDeleteDestinationApi {
+ /**
+ * HogFunction IDs of one destination, as the list endpoint returns them. They are deleted together.
+ * @minItems 1
+ * @maxItems 100
+ */
+ hog_function_ids: string[]
+}
+
export interface WarehouseColumnStatisticsApi {
readonly id: string
/** ID of the data warehouse table this column belongs to. */
diff --git a/products/warehouse_sources/frontend/generated/api.ts b/products/warehouse_sources/frontend/generated/api.ts
index c3e95ef5ecca..d74be9b45cf9 100644
--- a/products/warehouse_sources/frontend/generated/api.ts
+++ b/products/warehouse_sources/frontend/generated/api.ts
@@ -63,6 +63,10 @@ import type {
SourceSetupApi,
SourceSetupResponseApi,
UpdateWebhookInputsResponseApi,
+ WarehouseAlertCreateDestinationApi,
+ WarehouseAlertDeleteDestinationApi,
+ WarehouseAlertDestinationApi,
+ WarehouseAlertDestinationCreatedApi,
WarehouseColumnStatisticsApi,
WarehouseColumnStatisticsListParams,
WebhookInfoResponseApi,
@@ -1488,6 +1492,66 @@ export const externalDataSourcesWizardRetrieve = async (
})
}
+export const getWarehouseAlertsDestinationsListUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/warehouse_alerts/${id}/destinations/`
+}
+
+/**
+ * List the notification destinations of a warehouse alert.
+ */
+export const warehouseAlertsDestinationsList = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<WarehouseAlertDestinationApi[]> => {
+ return apiMutator<WarehouseAlertDestinationApi[]>(getWarehouseAlertsDestinationsListUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getWarehouseAlertsDestinationsCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/warehouse_alerts/${id}/destinations/`
+}
+
+/**
+ * Add a notification destination to a warehouse alert. One HogFunction is created per alert event kind (firing, resolved). A PagerDuty destination gets the incident opened and incident closed kinds instead, so each incident it opens is resolved.
+ */
+export const warehouseAlertsDestinationsCreate = async (
+ projectId: string,
+ id: string,
+ warehouseAlertCreateDestinationApi: WarehouseAlertCreateDestinationApi,
+ options?: RequestInit
+): Promise<WarehouseAlertDestinationCreatedApi> => {
+ return apiMutator<WarehouseAlertDestinationCreatedApi>(getWarehouseAlertsDestinationsCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(warehouseAlertCreateDestinationApi),
+ })
+}
+
+export const getWarehouseAlertsDestinationsDeleteCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/warehouse_alerts/${id}/destinations/delete/`
+}
+
+/**
+ * Delete one notification destination of a warehouse alert, all its HogFunctions together.
+ */
+export const warehouseAlertsDestinationsDeleteCreate = async (
+ projectId: string,
+ id: string,
+ warehouseAlertDeleteDestinationApi: WarehouseAlertDeleteDestinationApi,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getWarehouseAlertsDestinationsDeleteCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(warehouseAlertDeleteDestinationApi),
+ })
+}
+
export const getWarehouseColumnStatisticsListUrl = (
projectId: string,
params?: WarehouseColumnStatisticsListParams
diff --git a/products/warehouse_sources/frontend/generated/api.zod.ts b/products/warehouse_sources/frontend/generated/api.zod.ts
index 3c69d1d49c35..af4bb0a8ebaa 100644
--- a/products/warehouse_sources/frontend/generated/api.zod.ts
+++ b/products/warehouse_sources/frontend/generated/api.zod.ts
@@ -721,3 +721,56 @@ export const ExternalDataSourcesSourcePrefixCreateBody = /* @__PURE__ */ zod
export const ExternalDataSourcesStoreCredentialsCreateBody = /* @__PURE__ */ zod
.record(zod.string(), zod.unknown())
.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
+
+/**
+ * Add a notification destination to a warehouse alert. One HogFunction is created per alert event kind (firing, resolved). A PagerDuty destination gets the incident opened and incident closed kinds instead, so each incident it opens is resolved.
+ */
+export const warehouseAlertsDestinationsCreateBodyPagerdutySeverityDefault = `critical`
+export const warehouseAlertsDestinationsCreateBodyPagerdutyRegionDefault = `us`
+
+export const WarehouseAlertsDestinationsCreateBody = /* @__PURE__ */ zod.object({
+ type: zod
+ .enum(['slack', 'webhook', 'teams', 'discord', 'pagerduty'])
+ .describe(
+ '\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams\n\* `discord` - discord\n\* `pagerduty` - pagerduty'
+ )
+ .describe(
+ 'Notification destination type.\n\n\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams\n\* `discord` - discord\n\* `pagerduty` - pagerduty'
+ ),
+ slack_workspace_id: zod
+ .number()
+ .optional()
+ .describe('Integration ID for the Slack workspace. Required when type=slack.'),
+ slack_channel_id: zod.string().optional().describe('Slack channel ID. Required when type=slack.'),
+ slack_channel_name: zod.string().optional().describe('Human-readable channel name for display.'),
+ webhook_url: zod.url().optional().describe('HTTPS endpoint to post to. Required for webhook, teams and discord.'),
+ pagerduty_routing_key: zod
+ .string()
+ .optional()
+ .describe('Integration key of a PagerDuty Events API v2 integration. Required when type=pagerduty.'),
+ pagerduty_severity: zod
+ .enum(['critical', 'error', 'warning', 'info'])
+ .describe('\* `critical` - critical\n\* `error` - error\n\* `warning` - warning\n\* `info` - info')
+ .default(warehouseAlertsDestinationsCreateBodyPagerdutySeverityDefault)
+ .describe(
+ 'Severity PagerDuty records on the incident. Used when type=pagerduty.\n\n\* `critical` - critical\n\* `error` - error\n\* `warning` - warning\n\* `info` - info'
+ ),
+ pagerduty_region: zod
+ .enum(['us', 'eu'])
+ .describe('\* `us` - us\n\* `eu` - eu')
+ .default(warehouseAlertsDestinationsCreateBodyPagerdutyRegionDefault)
+ .describe('PagerDuty service region of the account. Used when type=pagerduty.\n\n\* `us` - us\n\* `eu` - eu'),
+})
+
+/**
+ * Delete one notification destination of a warehouse alert, all its HogFunctions together.
+ */
+export const warehouseAlertsDestinationsDeleteCreateBodyHogFunctionIdsMax = 100
+
+export const WarehouseAlertsDestinationsDeleteCreateBody = /* @__PURE__ */ zod.object({
+ hog_function_ids: zod
+ .array(zod.uuid())
+ .min(1)
+ .max(warehouseAlertsDestinationsDeleteCreateBodyHogFunctionIdsMax)
+ .describe('HogFunction IDs of one destination, as the list endpoint returns them. They are deleted together.'),
+})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3371cc77f521..86a105d8e393 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -77242,6 +77242,8 @@ export namespace Schemas {
/**
* * `logs` - Logs
* * `insight` - Insight
+ * * `warehouse_source` - Warehouse source
+ * * `warehouse_destination` - Warehouse destination
*/
export type PlatformAlertConfigurationSourceKindEnum = typeof PlatformAlertConfigurationSourceKindEnum[keyof typeof PlatformAlertConfigurationSourceKindEnum];
@@ -77249,6 +77251,8 @@ export namespace Schemas {
export const PlatformAlertConfigurationSourceKindEnum = {
Logs: 'logs',
Insight: 'insight',
+ WarehouseSource: 'warehouse_source',
+ WarehouseDestination: 'warehouse_destination',
} as const;
/**
@@ -77329,7 +77333,9 @@ export namespace Schemas {
/** Product whose data the alert evaluates.
*
* * `logs` - Logs
- * * `insight` - Insight */
+ * * `insight` - Insight
+ * * `warehouse_source` - Warehouse source
+ * * `warehouse_destination` - Warehouse destination */
readonly source_kind: PlatformAlertConfigurationSourceKindEnum;
/** Source-specific settings. The shape depends on source_kind. The bound the alert is evaluated against is under the condition key. */
readonly source_config: PlatformAlertConfigurationSourceConfig;
@@ -89035,7 +89041,137 @@ export namespace Schemas {
homepage?: PinnedSceneTab | null;
}
- export type PatchedPlatformAlertConfigurationEdit = PatchedInsightPlatformAlertConfigurationEdit | PatchedLogsPlatformAlertConfigurationEdit;
+ /**
+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.
+ */
+ export type PatchedWarehouseDestinationPlatformAlertConfigurationEditSourceKind = typeof PatchedWarehouseDestinationPlatformAlertConfigurationEditSourceKind[keyof typeof PatchedWarehouseDestinationPlatformAlertConfigurationEditSourceKind];
+
+
+ export const PatchedWarehouseDestinationPlatformAlertConfigurationEditSourceKind = {
+ WarehouseDestination: 'warehouse_destination',
+ } as const;
+
+ export interface WarehouseDestinationAlertConfig {
+ /**
+ * 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].
+ * @maxItems 100
+ */
+ destination_ids?: string[];
+ /** Whether project members who get data pipeline error emails also get an email when this alert fires or resolves. */
+ email_project_members?: boolean;
+ }
+
+ /**
+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.
+ */
+ export interface PatchedWarehouseDestinationPlatformAlertConfigurationEdit {
+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */
+ source_kind: PatchedWarehouseDestinationPlatformAlertConfigurationEditSourceKind;
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 255
+ */
+ name?: string;
+ /** Whether the alert is evaluated on schedule. */
+ enabled?: boolean;
+ /** Settings for a warehouse_destination alert. The bound the alert is evaluated against is under condition. */
+ source_config?: WarehouseDestinationAlertConfig;
+ /** 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;
+ }
+
+ /**
+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.
+ */
+ export type PatchedWarehouseSourcePlatformAlertConfigurationEditSourceKind = typeof PatchedWarehouseSourcePlatformAlertConfigurationEditSourceKind[keyof typeof PatchedWarehouseSourcePlatformAlertConfigurationEditSourceKind];
+
+
+ export const PatchedWarehouseSourcePlatformAlertConfigurationEditSourceKind = {
+ WarehouseSource: 'warehouse_source',
+ } as const;
+
+ export type WarehouseAlertGroupByEnum = typeof WarehouseAlertGroupByEnum[keyof typeof WarehouseAlertGroupByEnum];
+
+
+ export const WarehouseAlertGroupByEnum = {
+ Schema: 'schema',
+ Source: 'source',
+ } as const;
+
+ export interface WarehouseSourceAlertConfig {
+ /**
+ * Warehouse sources the alert watches. Empty watches every source in the project, including sources added later.
+ * @maxItems 100
+ */
+ source_ids?: string[];
+ /** 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. */
+ group_by?: WarehouseAlertGroupByEnum;
+ /** Whether a table that stops syncing at the project's billing limit also fires the alert. */
+ include_billing_limits?: boolean;
+ /** Whether project members who get data pipeline error emails also get an email when this alert fires or resolves. */
+ email_project_members?: boolean;
+ }
+
+ /**
+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.
+ */
+ export interface PatchedWarehouseSourcePlatformAlertConfigurationEdit {
+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */
+ source_kind: PatchedWarehouseSourcePlatformAlertConfigurationEditSourceKind;
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 255
+ */
+ name?: string;
+ /** Whether the alert is evaluated on schedule. */
+ enabled?: boolean;
+ /** Settings for a warehouse_source alert. The bound the alert is evaluated against is under condition. */
+ source_config?: WarehouseSourceAlertConfig;
+ /** How the alert splits its results into instances. */
+ grouping?: Grouping;
+ /** Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. */
+ schedule_restriction?: AlertScheduleRestriction | null;
+ /**
+ * Number of recent checks considered when deciding to fire.
+ * @minimum 1
+ * @maximum 10
+ */
+ evaluation_periods?: number;
+ /**
+ * Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.
+ * @minimum 1
+ * @maximum 10
+ */
+ datapoints_to_alarm?: number;
+ /**
+ * Minimum minutes between notifications for the same alert.
+ * @minimum 0
+ * @maximum 2147483647
+ */
+ cooldown_minutes?: number;
+ }
+
+ export type PatchedPlatformAlertConfigurationEdit = PatchedInsightPlatformAlertConfigurationEdit | PatchedLogsPlatformAlertConfigurationEdit | PatchedWarehouseDestinationPlatformAlertConfigurationEdit | PatchedWarehouseSourcePlatformAlertConfigurationEdit;
/**
* Request body for PATCH /api/users/@me/product_intro_seen.
@@ -94152,9 +94288,205 @@ export namespace Schemas {
created_at: string | null;
}
- export type PlatformAlertConfigurationCreate = LogsPlatformAlertConfigurationCreate;
+ /**
+ * Product whose data the alert evaluates. It cannot change after the create.
+ */
+ export type WarehouseDestinationPlatformAlertConfigurationCreateSourceKind = typeof WarehouseDestinationPlatformAlertConfigurationCreateSourceKind[keyof typeof WarehouseDestinationPlatformAlertConfigurationCreateSourceKind];
+
+
+ export const WarehouseDestinationPlatformAlertConfigurationCreateSourceKind = {
+ WarehouseDestination: 'warehouse_destination',
+ } as const;
+
+ /**
+ * The settings of a new alert. Every one but source_config has a default, which is stored.
+ */
+ export interface WarehouseDestinationPlatformAlertConfigurationCreate {
+ /** Product whose data the alert evaluates. It cannot change after the create. */
+ source_kind: WarehouseDestinationPlatformAlertConfigurationCreateSourceKind;
+ /**
+ * 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 warehouse_destination alert. The bound the alert is evaluated against is under condition. */
+ source_config: WarehouseDestinationAlertConfig;
+ /** How the alert splits its results into instances. Defaults to mode single. */
+ grouping?: Grouping;
+ /** Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. Defaults to null. */
+ schedule_restriction?: AlertScheduleRestriction | null;
+ /**
+ * Number of recent checks considered when deciding to fire. Defaults to 1.
+ * @minimum 1
+ * @maximum 10
+ */
+ evaluation_periods?: number;
+ /**
+ * Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods. Defaults to 1.
+ * @minimum 1
+ * @maximum 10
+ */
+ datapoints_to_alarm?: number;
+ /**
+ * Minimum minutes between notifications for the same alert. Defaults to 0.
+ * @minimum 0
+ * @maximum 2147483647
+ */
+ cooldown_minutes?: number;
+ }
+
+ /**
+ * Product whose data the alert evaluates. It cannot change after the create.
+ */
+ export type WarehouseSourcePlatformAlertConfigurationCreateSourceKind = typeof WarehouseSourcePlatformAlertConfigurationCreateSourceKind[keyof typeof WarehouseSourcePlatformAlertConfigurationCreateSourceKind];
+
- export type PlatformAlertConfigurationEdit = InsightPlatformAlertConfigurationEdit | LogsPlatformAlertConfigurationEdit;
+ export const WarehouseSourcePlatformAlertConfigurationCreateSourceKind = {
+ WarehouseSource: 'warehouse_source',
+ } as const;
+
+ /**
+ * The settings of a new alert. Every one but source_config has a default, which is stored.
+ */
+ export interface WarehouseSourcePlatformAlertConfigurationCreate {
+ /** Product whose data the alert evaluates. It cannot change after the create. */
+ source_kind: WarehouseSourcePlatformAlertConfigurationCreateSourceKind;
+ /**
+ * 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 warehouse_source alert. The bound the alert is evaluated against is under condition. */
+ source_config: WarehouseSourceAlertConfig;
+ /** 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;
+ }
+
+ export type PlatformAlertConfigurationCreate = LogsPlatformAlertConfigurationCreate | WarehouseDestinationPlatformAlertConfigurationCreate | WarehouseSourcePlatformAlertConfigurationCreate;
+
+ /**
+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.
+ */
+ export type WarehouseDestinationPlatformAlertConfigurationEditSourceKind = typeof WarehouseDestinationPlatformAlertConfigurationEditSourceKind[keyof typeof WarehouseDestinationPlatformAlertConfigurationEditSourceKind];
+
+
+ export const WarehouseDestinationPlatformAlertConfigurationEditSourceKind = {
+ WarehouseDestination: 'warehouse_destination',
+ } as const;
+
+ /**
+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.
+ */
+ export interface WarehouseDestinationPlatformAlertConfigurationEdit {
+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */
+ source_kind: WarehouseDestinationPlatformAlertConfigurationEditSourceKind;
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 255
+ */
+ name: string;
+ /** Whether the alert is evaluated on schedule. */
+ enabled: boolean;
+ /** Settings for a warehouse_destination alert. The bound the alert is evaluated against is under condition. */
+ source_config: WarehouseDestinationAlertConfig;
+ /** 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;
+ }
+
+ /**
+ * Product whose data the alert evaluates. It cannot change, so it must match the stored value.
+ */
+ export type WarehouseSourcePlatformAlertConfigurationEditSourceKind = typeof WarehouseSourcePlatformAlertConfigurationEditSourceKind[keyof typeof WarehouseSourcePlatformAlertConfigurationEditSourceKind];
+
+
+ export const WarehouseSourcePlatformAlertConfigurationEditSourceKind = {
+ WarehouseSource: 'warehouse_source',
+ } as const;
+
+ /**
+ * The settings an edit can change. Each source kind subclasses it with a typed `source_config`.
+ */
+ export interface WarehouseSourcePlatformAlertConfigurationEdit {
+ /** Product whose data the alert evaluates. It cannot change, so it must match the stored value. */
+ source_kind: WarehouseSourcePlatformAlertConfigurationEditSourceKind;
+ /**
+ * Human-readable name of the alert.
+ * @maxLength 255
+ */
+ name: string;
+ /** Whether the alert is evaluated on schedule. */
+ enabled: boolean;
+ /** Settings for a warehouse_source alert. The bound the alert is evaluated against is under condition. */
+ source_config: WarehouseSourceAlertConfig;
+ /** How the alert splits its results into instances. */
+ grouping: Grouping;
+ /** Blocked local time windows (HH:MM in the project timezone) when the alert does not notify. Null means no quiet hours. */
+ schedule_restriction: AlertScheduleRestriction | null;
+ /**
+ * Number of recent checks considered when deciding to fire.
+ * @minimum 1
+ * @maximum 10
+ */
+ evaluation_periods: number;
+ /**
+ * Number of breaching checks within evaluation_periods required to fire. Cannot exceed evaluation_periods.
+ * @minimum 1
+ * @maximum 10
+ */
+ datapoints_to_alarm: number;
+ /**
+ * Minimum minutes between notifications for the same alert.
+ * @minimum 0
+ * @maximum 2147483647
+ */
+ cooldown_minutes: number;
+ }
+
+ export type PlatformAlertConfigurationEdit = InsightPlatformAlertConfigurationEdit | LogsPlatformAlertConfigurationEdit | WarehouseDestinationPlatformAlertConfigurationEdit | WarehouseSourcePlatformAlertConfigurationEdit;
export interface PlatformAlertGroupSnooze {
/**
@@ -120791,6 +121123,108 @@ export namespace Schemas {
readonly days: readonly VisionSpendDay[];
}
+ /**
+ * * `slack` - slack
+ * * `webhook` - webhook
+ * * `teams` - teams
+ * * `discord` - discord
+ * * `pagerduty` - pagerduty
+ */
+ export type WarehouseAlertDestinationTypeEnum = typeof WarehouseAlertDestinationTypeEnum[keyof typeof WarehouseAlertDestinationTypeEnum];
+
+
+ export const WarehouseAlertDestinationTypeEnum = {
+ Slack: 'slack',
+ Webhook: 'webhook',
+ Teams: 'teams',
+ Discord: 'discord',
+ Pagerduty: 'pagerduty',
+ } as const;
+
+ export interface WarehouseAlertCreateDestination {
+ /** Notification destination type.
+ *
+ * * `slack` - slack
+ * * `webhook` - webhook
+ * * `teams` - teams
+ * * `discord` - discord
+ * * `pagerduty` - pagerduty */
+ type: WarehouseAlertDestinationTypeEnum;
+ /** Integration ID for the Slack workspace. Required when type=slack. */
+ slack_workspace_id?: number;
+ /** Slack channel ID. Required when type=slack. */
+ slack_channel_id?: string;
+ /** Human-readable channel name for display. */
+ slack_channel_name?: string;
+ /** HTTPS endpoint to post to. Required for webhook, teams and discord. */
+ webhook_url?: string;
+ /** Integration key of a PagerDuty Events API v2 integration. Required when type=pagerduty. */
+ pagerduty_routing_key?: string;
+ /** Severity PagerDuty records on the incident. Used when type=pagerduty.
+ *
+ * * `critical` - critical
+ * * `error` - error
+ * * `warning` - warning
+ * * `info` - info */
+ pagerduty_severity?: PagerDutySeverityEnum;
+ /** PagerDuty service region of the account. Used when type=pagerduty.
+ *
+ * * `us` - us
+ * * `eu` - eu */
+ pagerduty_region?: PagerDutyRegionEnum;
+ }
+
+ export interface WarehouseAlertDeleteDestination {
+ /**
+ * HogFunction IDs of one destination, as the list endpoint returns them. They are deleted together.
+ * @minItems 1
+ * @maxItems 100
+ */
+ hog_function_ids: string[];
+ }
+
+ export interface WarehouseAlertDestination {
+ /** HogFunction IDs that make up this destination, one per alert event kind it handles. Send them all to the delete endpoint to remove the destination. */
+ hog_function_ids: string[];
+ /** Notification destination type.
+ *
+ * * `slack` - slack
+ * * `webhook` - webhook
+ * * `teams` - teams
+ * * `discord` - discord
+ * * `pagerduty` - pagerduty */
+ type: WarehouseAlertDestinationTypeEnum;
+ /** Whether every HogFunction of the destination is enabled, so it notifies for every event kind. */
+ enabled: boolean;
+ /** Integration ID of the Slack workspace. Set when type=slack. */
+ slack_workspace_id?: number;
+ /** Slack channel ID. Set when type=slack. */
+ slack_channel_id?: string;
+ /** Human-readable Slack channel name. Set when type=slack. */
+ slack_channel_name?: string;
+ /** Webhook endpoint reduced to scheme and host. The path, query and userinfo carry the secret. */
+ webhook_url?: string;
+ /** PagerDuty integration key reduced to its last four characters. */
+ pagerduty_routing_key?: string;
+ /** Severity of the PagerDuty incident.
+ *
+ * * `critical` - critical
+ * * `error` - error
+ * * `warning` - warning
+ * * `info` - info */
+ pagerduty_severity?: PagerDutySeverityEnum;
+ /** PagerDuty service region the events go to.
+ *
+ * * `us` - us
+ * * `eu` - eu */
+ pagerduty_region?: PagerDutyRegionEnum;
+ }
+
+ export interface WarehouseAlertDestinationCreated {
+ /** HogFunction IDs created for the destination, one per event kind. */
+ hog_function_ids: string[];
+ }
+
export interface WarehouseConnection {
/** Postgres connection host. The warehouse name is the SNI subdomain, e.g. my-warehouse.dw.us.postwh.com */
host: string;
diff --git a/tach.toml b/tach.toml
index 0809bb9ca260..32f5eb6f90a9 100644
--- a/tach.toml
+++ b/tach.toml
@@ -408,6 +408,8 @@ path = "products.warehouse_sources"
depends_on = [
"ee",
"posthog",
+ "products.alerts",
+ "products.alerts_platform",
"products.batch_exports",
"products.cdp",
"products.data_modeling",