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.

refactor(alerts): move the alerts platform into its own product (#109499)

Jimmy Zhu808a15dc9211
diff --git a/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml b/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml
index 97326e4ec11e..dd9800ea0cf3 100644
--- a/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml
+++ b/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml
@@ -114,8 +114,6 @@ rules:
- '/.semgrep/rules/security/tests/insight-alert-state-must-go-through-state-machine.py'
exclude:
- '/products/alerts/backend/insight_alert_state_machine.py'
- # Shared skeleton state, covered by platform-alert-state-direct-mutation below.
- - '/products/alerts/backend/logic/platform_lifecycle.py'
# Writes HogFunction.enabled (destination plumbing), not an alert.
- '/products/alerts/backend/logic/destinations.py'
- '/products/alerts/backend/test/**'
@@ -136,7 +134,7 @@ rules:
Direct mutation of shared alert lifecycle fields bypasses the shared mutator.
A source decides whether its data breached; the shared lifecycle decides what
that means. Route the change through
- products.alerts.backend.facade.platform_alerts.apply_outcome.
+ products.alerts_platform.backend.facade.api.record_outcomes.
languages: [python]
severity: ERROR
metadata:
@@ -145,9 +143,12 @@ rules:
confidence: HIGH
paths:
include:
+ - '/products/alerts_platform/backend/**/*.py'
- '/products/logs/backend/alert_source_cycle.py'
- '/products/logs/backend/platform_alert_backfill.py'
exclude:
+ # The sanctioned mutator: every other path reaches the rows through it.
+ - '/products/alerts_platform/backend/logic/platform_lifecycle.py'
- '/products/**/test/**'
- '/products/**/tests/**'
- '/products/**/test_*.py'
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.md
index 734421fec33a..21bb4457b87a 100644
--- a/docs/internal/alerts-platform-temporal.md
+++ b/docs/internal/alerts-platform-temporal.md
@@ -1,6 +1,6 @@
# Alerts noop workers
-The Alerts product registers three queues through `products/alerts/backend/facade/temporal.py` and the shared `start_temporal_worker` command:
+The alerts platform registers three queues through `products/alerts_platform/backend/facade/temporal.py` and the shared `start_temporal_worker` command:
| Setting in `posthog/settings/temporal.py` | Queue | Workflow |
| ------------------------------------------------- | ------------------------------------------------- | ----------------------------- |
@@ -228,7 +228,7 @@ than within one.
## Source evaluation bindings
-`products/alerts/backend/temporal/sources.py` maps a `SourceKind` to the workflow name that evaluates it.
+`products/alerts_platform/backend/temporal/sources.py` maps a `SourceKind` to the workflow name that evaluates it.
A source in that map gets its own workflow started by name, carrying one batch key and the tick cutoff.
A source absent from it keeps the noop `alerts-platform-evaluate` path, which receives no key.
The alerts product imports nothing from a source: the binding holds a name, and `test_every_source_evaluation_binding_names_a_registered_workflow` fails if that name is not registered on the evaluation queue.
@@ -246,7 +246,7 @@ so a write to those rows, a `LogsAlertEvent` row or a Kafka message here would t
State transitions land on `PlatformAlert` and schedule advancement on `PlatformAlertConfiguration`, which the logs fleet never reads.
Delivery stops at `alerts-platform-deliver-preview`, which records what would have been sent and contacts no destination.
-The lifecycle decision comes from `products/alerts/backend/facade/lifecycle.py` configured with `LOGS_ALERT_POLICY`,
+The lifecycle decision comes from `products/alerts_platform/backend/facade/lifecycle.py` configured with `LOGS_ALERT_POLICY`,
which is the shared machine the logs product's own state machine is a thin adapter over.
Going to the shared machine directly keeps the platform's lifecycle out of a source product's import path.
@@ -399,7 +399,7 @@ Logs does not group yet; the list is the shape that lets fan-out change the eval
### Metrics
The path emits through Temporal's own meter, so every series carries the worker, queue and activity attributes
-the runtime attaches. `products/alerts/backend/temporal/metrics.py` holds them and a source reaches them through
+the runtime attaches. `products/alerts_platform/backend/temporal/metrics.py` holds them and a source reaches them through
`facade/platform_metrics.py`.
| Metric | What it answers |
diff --git a/frontend/package.json b/frontend/package.json
index 54a4df20d319..f7c611b6979b 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -88,6 +88,7 @@
"@posthog/products-ai-observability": "workspace:*",
"@posthog/products-ai-training": "workspace:*",
"@posthog/products-alerts": "workspace:*",
+ "@posthog/products-alerts-platform": "workspace:*",
"@posthog/products-analytics-platform": "workspace:*",
"@posthog/products-annotations": "workspace:*",
"@posthog/products-apm": "workspace:*",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a28514972bc2..94c276113c24 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -665,6 +665,9 @@ importers:
'@posthog/products-alerts':
specifier: workspace:*
version: link:../products/alerts
+ '@posthog/products-alerts-platform':
+ specifier: workspace:*
+ version: link:../products/alerts_platform
'@posthog/products-analytics-platform':
specifier: workspace:*
version: link:../products/analytics_platform
@@ -2574,6 +2577,8 @@ importers:
specifier: 'catalog:'
version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
+ products/alerts_platform: {}
+
products/analytics_platform:
dependencies:
'@posthog/icons':
@@ -5527,7 +5532,7 @@ importers:
version: 6.0.3
vite-tsconfig-paths:
specifier: ^5.1.4
vitest:
specifier: ^3.2.4
@@ -5573,7 +5578,7 @@ importers:
version: 6.0.3
vite-tsconfig-paths:
specifier: ^5.1.4
vitest:
specifier: ^3.2.4
diff --git a/posthog/api/test/test_alert_15_minute_interval.py b/posthog/api/test/test_alert_15_minute_interval.py
index 9e917a9b9ae7..63e9b2a0ddb6 100644
--- a/posthog/api/test/test_alert_15_minute_interval.py
+++ b/posthog/api/test/test_alert_15_minute_interval.py
@@ -14,8 +14,8 @@ from posthog.schema import AlertCalculationInterval, AlertConditionType, Insight
from posthog.constants import AvailableFeature
from posthog.tasks.alerts.utils import calculation_interval_to_order, next_check_time
-from products.alerts.backend.facade.scheduling import CalendarInterval, alert_check_offset
from products.alerts.backend.models.alert import AlertConfiguration
+from products.alerts_platform.backend.facade.scheduling import CalendarInterval, alert_check_offset
class TestAlert15MinuteInterval(APIBaseTest):
diff --git a/posthog/clickhouse/migrations/0339_platform_alert_events.py b/posthog/clickhouse/migrations/0339_platform_alert_events.py
index 37b69b48621f..0a26a9f4816a 100644
--- a/posthog/clickhouse/migrations/0339_platform_alert_events.py
+++ b/posthog/clickhouse/migrations/0339_platform_alert_events.py
@@ -9,7 +9,7 @@ is `posthog` on the aux role, and a test or local ClickHouse runs under a differ
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
-from products.alerts.backend.models.platform_alert_events_sql import (
+from products.alerts_platform.backend.facade.clickhouse import (
DISTRIBUTED_PLATFORM_ALERT_EVENTS_TABLE_SQL,
SHARDED_PLATFORM_ALERT_EVENTS_TABLE_SQL,
)
diff --git a/posthog/clickhouse/migrations/0346_platform_alert_events_source_kind.py b/posthog/clickhouse/migrations/0346_platform_alert_events_source_kind.py
index d6094aa6b625..dbeee5a1fcc1 100644
--- a/posthog/clickhouse/migrations/0346_platform_alert_events_source_kind.py
+++ b/posthog/clickhouse/migrations/0346_platform_alert_events_source_kind.py
@@ -6,7 +6,7 @@ The column lands before anything writes the table, so every row it ever holds ca
from posthog.clickhouse.client.connection import NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
-from products.alerts.backend.models.platform_alert_events_sql import (
+from products.alerts_platform.backend.facade.clickhouse import (
PLATFORM_ALERT_EVENTS_TABLE,
SHARDED_PLATFORM_ALERT_EVENTS_TABLE,
)
diff --git a/posthog/clickhouse/schema.py b/posthog/clickhouse/schema.py
index 89a54c593b3b..9a68fcc74b75 100644
--- a/posthog/clickhouse/schema.py
+++ b/posthog/clickhouse/schema.py
@@ -389,7 +389,7 @@ from posthog.session_recordings.sql.session_replay_feature_sql import (
WRITABLE_SESSION_REPLAY_FEATURES_TABLE_SQL,
)
-from products.alerts.backend.models.platform_alert_events_sql import (
+from products.alerts_platform.backend.facade.clickhouse import (
DISTRIBUTED_PLATFORM_ALERT_EVENTS_TABLE_SQL,
SHARDED_PLATFORM_ALERT_EVENTS_TABLE_SQL,
)
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index fe65c8ed3125..968e3409c834 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -153,7 +153,7 @@ from posthog.temporal.weekly_digest import (
WORKFLOWS as WEEKLY_DIGEST_WORKFLOWS,
)
-from products.alerts.backend.facade.temporal import (
+from products.alerts_platform.backend.facade.temporal import (
DELIVERY_ACTIVITIES as ALERTS_PLATFORM_DELIVERY_ACTIVITIES,
DELIVERY_WORKFLOWS as ALERTS_PLATFORM_DELIVERY_WORKFLOWS,
EVALUATION_ACTIVITIES as ALERTS_PLATFORM_EVALUATION_ACTIVITIES,
diff --git a/posthog/management/commands/test/test_start_temporal_worker.py b/posthog/management/commands/test/test_start_temporal_worker.py
index 175098b4abc6..236ca1deff8f 100644
--- a/posthog/management/commands/test/test_start_temporal_worker.py
+++ b/posthog/management/commands/test/test_start_temporal_worker.py
@@ -17,7 +17,7 @@ from posthog.management.commands.start_temporal_worker import (
workflows_include_data_import_syncs,
)
-from products.alerts.backend.facade.temporal import (
+from products.alerts_platform.backend.facade.temporal import (
DELIVERY_ACTIVITIES,
DELIVERY_WORKFLOWS,
EVALUATION_ACTIVITIES,
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index f38fc8450b6a..9d9d61b84d0d 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -105,6 +105,7 @@ PRODUCTS_APPS = [
"products.warehouse_sources.backend.apps.WarehouseSourcesConfig",
"products.data_tools.backend.apps.DataToolsConfig",
"products.alerts.backend.apps.AlertsConfig",
+ "products.alerts_platform.backend.apps.AlertsPlatformConfig",
"products.actions.backend.apps.ActionsConfig",
"products.autoresearch.backend.apps.AutoresearchConfig",
"products.product_analytics.backend.apps.ProductAnalyticsConfig",
diff --git a/posthog/tasks/alerts/schedule_restriction.py b/posthog/tasks/alerts/schedule_restriction.py
index 42321d2dadf7..9e728b3f67d8 100644
--- a/posthog/tasks/alerts/schedule_restriction.py
+++ b/posthog/tasks/alerts/schedule_restriction.py
@@ -11,7 +11,8 @@ from datetime import UTC, datetime, timedelta
import structlog
-from products.alerts.backend.facade.scheduling import (
+from products.alerts.backend.models.alert import AlertConfiguration
+from products.alerts_platform.backend.facade.scheduling import (
MAX_BLOCKED_WINDOWS,
MAX_UNBLOCK_STEPS,
MIN_BLOCKED_WINDOW_MINUTES,
@@ -26,7 +27,6 @@ from products.alerts.backend.facade.scheduling import (
to_calendar_interval,
validate_and_normalize_schedule_restriction,
)
-from products.alerts.backend.models.alert import AlertConfiguration
logger = structlog.get_logger(__name__)
diff --git a/posthog/tasks/alerts/test/test_alert_check_helpers.py b/posthog/tasks/alerts/test/test_alert_check_helpers.py
index 6aef632c03dc..ebbf5399ebbb 100644
--- a/posthog/tasks/alerts/test/test_alert_check_helpers.py
+++ b/posthog/tasks/alerts/test/test_alert_check_helpers.py
@@ -7,8 +7,8 @@ from posthog.api.test.dashboards import DashboardAPI
from posthog.tasks.alerts.test.alert_check_helpers import run_alert_check
from posthog.tasks.alerts.utils import AlertEvaluationResult, add_alert_check, record_alert_delivery
-from products.alerts.backend.facade.contracts import AlertDelivery
from products.alerts.backend.models import AlertCheck, AlertConfiguration
+from products.alerts_platform.backend.facade.contracts import AlertDelivery
class TestRunAlertCheck(APIBaseTest):
diff --git a/posthog/tasks/alerts/test/test_investigation_notifications.py b/posthog/tasks/alerts/test/test_investigation_notifications.py
index d2e979eb4ff8..471c94901b56 100644
--- a/posthog/tasks/alerts/test/test_investigation_notifications.py
+++ b/posthog/tasks/alerts/test/test_investigation_notifications.py
@@ -14,8 +14,8 @@ from posthog.tasks.alerts.investigation_notifications import (
run_investigation_notification_safety_net,
)
-from products.alerts.backend.facade.contracts import AlertDelivery
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus
+from products.alerts_platform.backend.facade.contracts import AlertDelivery
from products.product_analytics.backend.facade.models import Insight
NOW = datetime(2026, 5, 4, 12, 0, 0, tzinfo=UTC)
diff --git a/posthog/tasks/alerts/test/test_schedule_restriction.py b/posthog/tasks/alerts/test/test_schedule_restriction.py
index 69ab3d4129a8..b69f3bdc7395 100644
--- a/posthog/tasks/alerts/test/test_schedule_restriction.py
+++ b/posthog/tasks/alerts/test/test_schedule_restriction.py
@@ -12,8 +12,8 @@ from posthog.tasks.alerts import schedule_restriction as schedule_restriction_mo
from posthog.tasks.alerts.schedule_restriction import is_utc_datetime_blocked, next_unblocked_utc
from posthog.tasks.alerts.utils import next_check_at_after_schedule_restriction_change
-from products.alerts.backend.facade.scheduling import CalendarInterval, alert_check_offset
from products.alerts.backend.models.alert import AlertConfiguration
+from products.alerts_platform.backend.facade.scheduling import CalendarInterval, alert_check_offset
ALERT_ID = UUID("0193f3c6-2a4b-7d2e-8f00-3c1b5d7e9a10")
HOURLY_OFFSET = alert_check_offset(CalendarInterval.HOURLY, ALERT_ID)
diff --git a/posthog/tasks/alerts/test/test_trends_absolute_alerts.py b/posthog/tasks/alerts/test/test_trends_absolute_alerts.py
index fc576ac4a76a..27a4348be2c6 100644
--- a/posthog/tasks/alerts/test/test_trends_absolute_alerts.py
+++ b/posthog/tasks/alerts/test/test_trends_absolute_alerts.py
@@ -28,8 +28,8 @@ from posthog.caching.calculate_results import calculate_for_query_based_insight
from posthog.models.instance_setting import set_instance_setting
from posthog.tasks.alerts.test.alert_check_helpers import run_alert_check
-from products.alerts.backend.facade.contracts import AlertDelivery
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
+from products.alerts_platform.backend.facade.contracts import AlertDelivery
# 8:55 AM
FROZEN_TIME = dateutil.parser.parse("2024-06-02T08:55:00.000Z")
diff --git a/posthog/tasks/alerts/test/test_trends_relative_alerts.py b/posthog/tasks/alerts/test/test_trends_relative_alerts.py
index 74f4690b2a12..5f1f527ccbd9 100644
--- a/posthog/tasks/alerts/test/test_trends_relative_alerts.py
+++ b/posthog/tasks/alerts/test/test_trends_relative_alerts.py
@@ -29,8 +29,8 @@ from posthog.caching.calculate_results import calculate_for_query_based_insight
from posthog.models.instance_setting import set_instance_setting
from posthog.tasks.alerts.test.alert_check_helpers import run_alert_check
-from products.alerts.backend.facade.contracts import AlertDelivery
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
+from products.alerts_platform.backend.facade.contracts import AlertDelivery
# Tuesday
FROZEN_TIME = dateutil.parser.parse("2024-06-04T08:55:00.000Z")
diff --git a/posthog/tasks/alerts/test/test_utils.py b/posthog/tasks/alerts/test/test_utils.py
index d7bea88407dc..baad00ef2d86 100644
--- a/posthog/tasks/alerts/test/test_utils.py
+++ b/posthog/tasks/alerts/test/test_utils.py
@@ -22,8 +22,8 @@ from posthog.tasks.alerts.utils import (
trigger_alert_hog_functions,
)
-from products.alerts.backend.facade.contracts import ActiveAlertDestination
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
+from products.alerts_platform.backend.facade.contracts import ActiveAlertDestination
from products.product_analytics.backend.facade.models import Insight
diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.py
index 094a3c99a36e..1b4790242f3f 100644
--- a/posthog/tasks/alerts/utils.py
+++ b/posthog/tasks/alerts/utils.py
@@ -19,8 +19,6 @@ from posthog.tasks.alerts.schedule_restriction import snap_candidate_utc_to_sche
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.alerts.backend.facade.api import LLM_DETECTOR_UNAVAILABLE_ERROR_CODE
-from products.alerts.backend.facade.contracts import AlertDelivery
-from products.alerts.backend.facade.delivery_slo import alert_delivery_slo
from products.alerts.backend.facade.destinations import (
ALERT_NOTIFICATION_FLUSH_TIMEOUT_SECONDS,
alert_internal_event_delivered,
@@ -30,13 +28,6 @@ from products.alerts.backend.facade.destinations import (
serialize_deliveries,
)
from products.alerts.backend.facade.email import send_alert_email
-from products.alerts.backend.facade.scheduling import (
- EVERY_15_MINUTES_CADENCE_MINUTES as EVERY_15_MINUTES_CADENCE_MINUTES,
- REAL_TIME_CADENCE_MINUTES as REAL_TIME_CADENCE_MINUTES,
- is_weekend,
- next_calendar_check_time,
- to_calendar_interval,
-)
from products.alerts.backend.insight_alert_state_machine import (
apply_invalid_configuration,
apply_outcome,
@@ -44,6 +35,15 @@ from products.alerts.backend.insight_alert_state_machine import (
should_notify,
)
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, derive_detector_event_fields
+from products.alerts_platform.backend.facade.contracts import AlertDelivery
+from products.alerts_platform.backend.facade.delivery_slo import alert_delivery_slo
+from products.alerts_platform.backend.facade.scheduling import (
+ EVERY_15_MINUTES_CADENCE_MINUTES as EVERY_15_MINUTES_CADENCE_MINUTES,
+ REAL_TIME_CADENCE_MINUTES as REAL_TIME_CADENCE_MINUTES,
+ is_weekend,
+ next_calendar_check_time,
+ to_calendar_interval,
+)
from products.exports.backend.facade import api as exports
logger = structlog.get_logger(__name__)
diff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.py
index 931f94bd86a1..ef116bcd11b4 100644
--- a/posthog/temporal/common/worker.py
+++ b/posthog/temporal/common/worker.py
@@ -58,7 +58,7 @@ from posthog.temporal.usage_report.metrics import (
USAGE_REPORTS_LATENCY_HISTOGRAM_METRICS,
)
-from products.alerts.backend.facade.temporal import (
+from products.alerts_platform.backend.facade.temporal import (
ALERTS_PLATFORM_LATENCY_HISTOGRAM_BUCKETS,
ALERTS_PLATFORM_LATENCY_HISTOGRAM_METRICS,
AlertsPlatformTelemetryInterceptor,
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index c95349976d0c..76d766f4fe5e 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -79,7 +79,7 @@ from posthog.temporal.warehouse_sources_queue_partition_management.schedule impo
)
from posthog.temporal.weekly_digest.types import WeeklyDigestInput
-from products.alerts.backend.facade.temporal import create_alerts_platform_tick_schedule
+from products.alerts_platform.backend.facade.temporal import create_alerts_platform_tick_schedule
from products.autoresearch.backend.facade.temporal import create_autoresearch_daily_schedule
from products.billing_alerts.backend.temporal.schedule import create_schedule_due_billing_alert_checks_schedule
from products.business_knowledge.backend.temporal.schedule import (
diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
index 1a105f750d56..71e3d7400d71 100644
--- a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
@@ -19,7 +19,6 @@ from posthog.temporal.ai.anomaly_investigation.workflow import (
investigate_anomaly_activity,
)
-from products.alerts.backend.facade.contracts import AlertDelivery
from products.alerts.backend.models.alert import (
AlertCheck,
AlertConfiguration,
@@ -27,6 +26,7 @@ from products.alerts.backend.models.alert import (
InvestigationStatus,
InvestigationVerdict,
)
+from products.alerts_platform.backend.facade.contracts import AlertDelivery
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.exports.backend.models.exported_asset import ExportedAsset
from products.notebooks.backend.facade.content import is_markdown_notebook_content
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index bcc62e91aca0..3df23dd626ec 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -83,8 +83,8 @@ from products.alerts.backend.facade.api import (
LLMDetectorMisconfiguredError,
LLMDetectorUnavailableError,
)
-from products.alerts.backend.facade.contracts import AlertDelivery
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus, Threshold
+from products.alerts_platform.backend.facade.contracts import AlertDelivery
from products.product_analytics.backend.facade.models import Insight
@@ -1463,7 +1463,7 @@ class TestNotifyAlert:
with (
patch("posthog.slo.events.posthoganalytics"),
- patch("products.alerts.backend.facade.delivery_slo.get_instance_region", return_value="US"),
+ patch("products.alerts_platform.backend.facade.delivery_slo.get_instance_region", return_value="US"),
patch("posthog.tasks.alerts.utils.send_notifications_for_breaches", return_value=[]),
patch("posthog.tasks.alerts.utils.send_notifications_for_errors") as mock_errors,
):
@@ -1487,7 +1487,7 @@ class TestNotifyAlert:
with (
patch("posthog.slo.events.posthoganalytics") as mock_slo_analytics,
- patch("products.alerts.backend.facade.delivery_slo.get_instance_region", return_value="US"),
+ patch("products.alerts_platform.backend.facade.delivery_slo.get_instance_region", return_value="US"),
patch(
"posthog.tasks.alerts.utils.send_notifications_for_breaches",
return_value=[_email_delivery("[email protected]")],
@@ -1793,7 +1793,7 @@ class TestNotifyAlert:
with (
patch("posthog.slo.events.posthoganalytics") as mock_slo_analytics,
- patch("products.alerts.backend.facade.delivery_slo.get_instance_region", return_value="US"),
+ patch("products.alerts_platform.backend.facade.delivery_slo.get_instance_region", return_value="US"),
patch(
"posthog.tasks.alerts.utils.send_notifications_for_breaches",
side_effect=RuntimeError("SMTP unavailable"),
diff --git a/products/alerts/backend/apps.py b/products/alerts/backend/apps.py
index 0aaa887a84b4..96ec9f7bb15f 100644
--- a/products/alerts/backend/apps.py
+++ b/products/alerts/backend/apps.py
@@ -13,3 +13,9 @@ class AlertsConfig(AppConfig):
# own module because the API module imports the alert detector stack (numpy) at module
# scope — see activity_logging's docstring.
from products.alerts.backend import activity_logging # noqa: F401, PLC0415
+
+ # The platform cannot import this product, so it reaches this product's destinations here.
+ from products.alerts.backend.facade.destinations import list_alert_destination_groups # noqa: PLC0415
+ from products.alerts_platform.backend.facade.delivery import register_destination_resolver # noqa: PLC0415
+
+ register_destination_resolver(list_alert_destination_groups)
diff --git a/products/alerts/backend/facade/api.py b/products/alerts/backend/facade/api.py
index 90ee81119103..4cdd189a9fbe 100644
--- a/products/alerts/backend/facade/api.py
+++ b/products/alerts/backend/facade/api.py
@@ -8,7 +8,7 @@ lifecycle machine in `facade.lifecycle`, and scheduling math in `facade.scheduli
import uuid
from collections.abc import Collection
from datetime import datetime, timedelta
-from typing import Final, Literal
+from typing import Literal
from zoneinfo import ZoneInfo
from django.db import transaction
@@ -16,14 +16,12 @@ from django.utils import timezone
import structlog
-from posthog.cdp.internal_events import LEGACY_INSIGHT_ALERT_EVENT
from posthog.models.activity_logging.model_activity import ActingUserContext
from posthog.models.user import User
from posthog.user_permissions import UserPermissions
from posthog.utils import relative_date_parse
from products.access_control.backend.facade.user_access_control import UserAccessControl
-from products.alerts.backend.facade.contracts import DestinationType
from products.alerts.backend.insight_alert_state_machine import apply_snooze
from products.alerts.backend.judge.contract import (
LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,
@@ -51,15 +49,6 @@ SlackSnoozeOutcome = Literal["snoozed", "no_access", "disabled", "not_found", "i
# its own, so the cap has to live here.
SLACK_SNOOZE_MAX_DAYS = 31
-# The event an insight alert check emits, named legacy where it is defined because it predates the
-# managed-alert event boundary. Do not take it from `posthog.tasks.alerts.utils` instead, because
-# that module imports this product's facade.
-INSIGHT_ALERT_EVENT_IDS: Final[tuple[str, ...]] = (LEGACY_INSIGHT_ALERT_EVENT,)
-
-# Slack only, because `alert:write` is grantable to a sandboxed agent. A connected workspace is a
-# destination an admin chose, while every other transport takes a URL the caller supplies.
-INSIGHT_ALERT_DESTINATION_TYPES: Final[tuple[DestinationType, ...]] = (DestinationType.SLACK,)
-
def get_alert_team_id(alert_id: uuid.UUID) -> int | None:
"""The team an alert belongs to, or None if no such alert exists.
diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.py
index 5de39d382619..f3f08681e241 100644
--- a/products/alerts/backend/facade/contracts.py
+++ b/products/alerts/backend/facade/contracts.py
@@ -1,459 +1,22 @@
-"""Contract types for alerts.
+"""Contract types for insight alerts.
-Framework-free types that describe what this product hands to its consumers and
-accepts back. No Django, no DRF: other products read against these, and the Turbo
-contract check watches this file to decide whether they must retest.
+Framework-free values this product hands to its consumers. The alerting vocabulary every source
+shares lives in `products.alerts_platform.backend.facade.contracts`; what stays here is what only
+an insight alert means.
"""
from __future__ import annotations
-from dataclasses import field
-from datetime import datetime
-from enum import StrEnum
-from typing import Any, Final, NotRequired, TypedDict
-from uuid import UUID
+from typing import Final
-from posthog.dataclasses import frozen
-from posthog.enums import LabeledStrEnum
+from posthog.cdp.internal_events import LEGACY_INSIGHT_ALERT_EVENT
+from products.alerts_platform.backend.facade.contracts import DestinationType
-class SourceKind(StrEnum):
- LOGS = "logs"
- INSIGHT = "insight"
+# The internal event an insight alert's destinations fire on. Do not take it from
+# `posthog.tasks.alerts.utils` instead, because that module imports this product's facade.
+INSIGHT_ALERT_EVENT_IDS: Final[tuple[str, ...]] = (LEGACY_INSIGHT_ALERT_EVENT,)
-
-@frozen
-class DemandDiscoveryInputs:
- cutoff: str
-
-
-@frozen
-class AlertBatchKey:
- """Names a chunk of due work by what it holds rather than by where it was cut.
-
- `slot` is `next_check_at` floored to the minute, so a chunk keeps its identity across ticks:
- a slow evaluation of a key is still the same key when the next tick rediscovers it.
- """
-
- team_id: int
- slot: str
-
-
-@frozen
-class AlertDemand:
- """Due batch keys per source, bounded so the payload stays small. A key costs a fixed amount and
- does not grow with a team's alert count. `omitted_by_source` counts keys discovery left out;
- that work is due again next tick."""
-
- batch_keys_by_source: dict[SourceKind, list[AlertBatchKey]]
- omitted_by_source: dict[SourceKind, int] = field(default_factory=dict)
-
-
-@frozen
-class SourceDispatchInputs:
- """Everything the tick knows about one source. The dispatcher decides how much of it to take."""
-
- tick_id: str
- source: SourceKind
- page: int
- batch_keys: list[AlertBatchKey]
- cutoff: str
-
-
-@frozen
-class SourceDispatchReport:
- source: SourceKind
- page: int
- dispatched: int
- remaining_keys: list[AlertBatchKey]
- evaluation_workflow_ids: list[str]
- # Not remaining: the run that already holds the key is still working it.
- already_running: int = 0
-
-
-@frozen
-class SourceEvaluationInputs:
- """What a source's own evaluation workflow receives from its dispatcher.
-
- The key, not a list of ids. The evaluation loads full configurations anyway, so shipping ids
- through the orchestrator would be transit cost, and re-reading gives it the fresher set.
- """
-
- source: SourceKind
- cutoff: str
- batch_key: AlertBatchKey
-
-
-@frozen
-class PlatformAlertCheckInput:
- """One configuration and its runtime state, as a source adapter reads it.
-
- Flat rather than nested, because a source never holds the rows and has nothing to do with
- the split between what belongs to the configuration and what belongs to the instance.
- """
-
- id: UUID
- team_id: int
- name: str
- source_config: dict[str, Any]
- threshold_count: int
- threshold_operator: str
- window_minutes: int
- check_interval_minutes: int
- evaluation_periods: int
- datapoints_to_alarm: int
- cooldown_minutes: int
- schedule_restriction: dict[str, Any] | None
- next_check_at: datetime | None
- consecutive_failures: int
- legacy_configuration_id: UUID | None
- state: str
- last_notified_at: datetime | None
- snooze_until: datetime | None
- firing_started_at: datetime | None = None
-
- @property
- def filters(self) -> dict[str, Any]:
- """Satisfies the logs query layer, which names this field `filters`."""
- return self.source_config
-
-
-@frozen
-class PlatformAlertUpsert:
- """One configuration a source wants copied into the shared tables."""
-
- legacy_configuration_id: UUID
- team_id: int
- name: str
- enabled: bool
- source_kind: SourceKind
- source_config: dict[str, Any]
- threshold_count: int
- threshold_operator: str
- window_minutes: int
- check_interval_minutes: int
- evaluation_periods: int
- datapoints_to_alarm: int
- cooldown_minutes: int
- schedule_restriction: dict[str, Any] | None
- next_check_at: datetime | None
- snooze_until: datetime | None
-
-
-class SkipReason(StrEnum):
- """Why a check reached an outcome without a query answering it.
-
- A label on the platform's own counters. It never reaches an alert's state or schedule. A check
- that was evaluated has no skip reason, which is `None` rather than a member here.
- """
-
- BROKEN_CONFIG = "broken_config"
- QUERY_FAILED = "query_failed"
-
-
-class MuteReason(StrEnum):
- """Why an announcement was held. A muted check is evaluated like any other, so this labels the
- held announcement rather than a skip."""
-
- SNOOZE = "snooze"
- QUIET_HOURS = "quiet_hours"
-
-
-class AlertEventKind(StrEnum):
- """What one evaluation announced about an alert.
-
- `CHECK` is an evaluation that announced nothing, which includes one that moved the alert while
- a cooldown or a mute held the notification back. Read the history row's `previous_state` and
- `state` to find the moves, because counting `RESOLVED` rows misses every recovery that was
- suppressed.
-
- A source reports the kind rather than the platform deriving it: the machine already decided
- what to announce, and deriving it again from the states would be a second implementation of
- that decision.
- """
-
- CHECK = "check"
- FIRING = "firing"
- RESOLVED = "resolved"
- ERRORED = "errored"
- BROKEN = "broken"
-
-
-@frozen
-class FiringEpisode:
- """The firing a check concerns, and whether that check is the one that ended it.
-
- Two readers want different things from it. An alert's current state wants the firing it is in
- now, which is nothing once a check ends one. A history row and a delivery want the firing the
- check was about, which on a resolve is the firing that just ended. Both come from here, so
- neither has to work the difference out from the states.
-
- `started_at` is None for a firing that began before the platform recorded starts.
- """
-
- started_at: datetime | None
- ended: bool
-
-
-@frozen
-class PlatformAlertOutcome:
- """What one check decided. The platform turns this into rows.
-
- Every check produces one, including a check a source skipped. A skip that records nothing
- leaves its due time where it was, so discovery finds the same work every tick.
- """
-
- configuration_id: UUID
- evaluation_key: str
- kind: AlertEventKind
- new_state: str
- notified: bool
- consecutive_failures: int
- firing_episode: FiringEpisode | None = None
- value: float | None = None
- labels: dict[str, str] = field(default_factory=dict)
- error_message: str | None = None
- query_duration_ms: int | None = None
- # What a mute held back, so history separates a muted fire from a check that said nothing.
- muted_notification: str = ""
- # Recording an outcome without it leaves a configuration discovery keeps handing back to an
- # evaluation that cannot succeed.
- disable: bool = False
-
-
-@frozen
-class GroupTransition:
- """One transition a delivery carries: `kind` picks the headline, `value` is the number it
- quotes.
-
- `grouping_key` is empty until a source groups, so delivery reads a list of one today and a
- list of N when fan-out ships.
-
- The condition and the source config a message also needs stay on the history row the
- delivery addresses, because `source_config` is an unbounded filter tree and one per
- transition would blow the payload bound `MAX_PREVIEWS_PER_CYCLE` was sized against.
- """
-
- grouping_key: str
- kind: AlertEventKind
- value: float | None = None
-
-
-@frozen
-class AnnouncedTransition:
- """One group's transition as delivery reads it back, projected from a history row.
-
- The sibling of `GroupTransition`, and deliberately not the same type. A `GroupTransition`
- crosses Temporal on the delivery payload, so it stays small. This never does: delivery holds
- an address, reads the row, and builds one of these in the process that sends the message. So
- it carries what a message states, including the two snapshots the row already keeps.
-
- Every field here is a column on `platform_alert_events`, which is what makes a message state
- what its own check decided however long after the check it is rendered.
- """
-
- grouping_key: str
- kind: AlertEventKind
- # The firing this transition concerns, which on a resolve is the firing that just ended.
- # None when no firing is involved, which is a failed or a turned-off check.
- episode_started_at: datetime | None
- value: float | None
- labels: dict[str, str]
- condition: dict[str, Any]
- source_config: dict[str, Any]
- error_message: str | None
-
-
-@frozen
-class EvaluationAnnouncement:
- """What one evaluation left for a destination to say.
-
- One transition is one message. A level between this and the transitions would be the place a
- fan-in policy lived, and fan-in was deprioritized on 2026-09-28, so there is nothing for it
- to hold. It arrives with fan-in rather than waiting here empty.
- """
-
- alert_name: str
- # Evaluation-level, so it sits here rather than on a transition: a failed check fails the
- # whole evaluation, and every group in one announcement saw the same count.
- consecutive_failures: int
- transitions: tuple[AnnouncedTransition, ...]
-
-
-@frozen
-class AlertDeliveryRequest:
- """Where to find what one evaluation decided, rather than a copy of it.
-
- A delivery addresses its history rows by `configuration_id` and `evaluation_key`, and reads
- the facts back from there. So a retry announces what was recorded rather than what one
- attempt happened to carry, and a batch's payload does not grow with what its alerts say.
-
- The two destination fields are supplied by the source because only the source knows them.
- `destination_alert_id` is the id its destinations are matched on, which is the legacy
- configuration while the platform runs beside a source's own stack. `event_ids_by_kind` maps
- each kind the source can announce onto the event id its destinations filter on. The platform
- imports no source, so it cannot derive either.
- """
-
- source: SourceKind
- team_id: int
- configuration_id: str
- evaluation_key: str
- destination_alert_id: str
- event_ids_by_kind: dict[str, str]
-
-
-@frozen
-class SourceBatchEvaluation:
- """What one batch decided, before any of it is written.
-
- Evaluation returns this and the write runs as its own activity, so Temporal has the
- deliveries in history before anything can advance a schedule past them.
- """
-
- outcomes: tuple[PlatformAlertOutcome, ...]
- deliveries: tuple[AlertDeliveryRequest, ...]
- # Pairs the payload bound left out. They keep their due time and a later tick re-evaluates
- # them, the way a truncated cohort already behaves.
- omitted: int = 0
-
-
-# The platform's write, which a source's evaluation workflow starts by name. One definition,
-# because a rename that misses a source breaks it at runtime and nothing else would catch it.
-RECORD_OUTCOMES_ACTIVITY: Final[str] = "alerts_platform_record_outcomes"
-
-
-@frozen
-class SourceOutcomeInputs:
- team_id: int
- cutoff: str
- outcomes: tuple[PlatformAlertOutcome, ...]
-
-
-@frozen
-class TickPage:
- page: int
- run_id: str
- dispatched: int
- remaining: int
- # Sources whose dispatcher failed on this page, and the keys they never took. Those keys keep
- # their due time, so a later tick rediscovers them; the page reports them rather than ending
- # the tick.
- failed_sources: int = 0
- undispatched: int = 0
-
-
-@frozen
-class OrchestrateInputs:
- """Empty on the first run. A continued run carries the tick's cutoff, deadlines, demand and pages."""
-
- cutoff: str | None = None
- deadline: str | None = None # stop starting pages after this
- hard_deadline: str | None = None # the execution timeout lands here; no page may run past it
- page: int = 0
- demand: dict[SourceKind, list[AlertBatchKey]] | None = None
- pages: list[TickPage] | None = None
- omitted: int = 0 # due work discovery left out of the bounded manifest; counted as remaining
-
-
-@frozen
-class OrchestrateResult:
- pages: list[TickPage]
- remaining: int
- deadline_reached: bool
-
-
-class DestinationType(LabeledStrEnum):
- # The label names the type in a message a person reads.
- SLACK = "slack", "Slack"
- DISCORD = "discord", "Discord"
- WEBHOOK = "webhook", "Webhook"
- TEAMS = "teams", "Microsoft Teams"
-
-
-class AlertDestinationData(TypedDict):
- type: DestinationType
- slack_workspace_id: NotRequired[int]
- slack_channel_id: NotRequired[str]
- slack_channel_name: NotRequired[str]
- webhook_url: NotRequired[str]
-
-
-class AlertDestinationValidationError(Exception):
- """A destination payload the platform refuses. Callers at an HTTP boundary translate
- this into their own framework's validation error."""
-
- def __init__(self, message: str, *, field: str | None = None) -> None:
- self.message = message
- self.field = field
- super().__init__(message)
-
-
-@frozen
-class AlertDestinationAction:
- url: str
- label: str
-
-
-@frozen
-class EventKindSpec:
- """Everything one alert event kind (firing, resolved, ...) says in a notification."""
-
- event_id: str
- display_kind: str
- header: str
- details: tuple[tuple[str, str], ...]
- primary_action_url: str
- primary_action_label: str
- webhook_body: dict[str, Any]
- product_label: str = "alert"
- intro_lines: tuple[str, ...] = ()
- additional_actions: tuple[AlertDestinationAction, ...] = ()
-
- def destination_description(self, alert_name: str) -> str:
- return f'Sends {self.display_kind} notifications for {self.product_label} "{alert_name}".'
-
-
-@frozen
-class AlertDestinationConfig:
- """One destination, built and ready to persist as a HogFunction."""
-
- payload: dict[str, Any]
-
-
-@frozen
-class AlertDestinationGroup:
- """The HogFunctions that together make up one destination a person configured."""
-
- hog_function_ids: tuple[UUID, ...]
- data: AlertDestinationData
- fully_enabled: bool
-
-
-@frozen
-class OwnedAlertDestination:
- """One alert-owned HogFunction row, as much of it as a consumer may read."""
-
- hog_function_id: UUID
- template_id: str | None
- filters: dict[str, Any] | None
-
-
-@frozen
-class ActiveAlertDestination:
- id: str
- name: str
- destination_type: str | None
-
-
-@frozen
-class AlertDelivery:
- """Receipt for one destination that accepted a send. `status` is an open set, so a
- future transport can report an outcome other than "accepted"."""
-
- channel: str # "email" | "hog_function"
- target: str # email address or destination name
- target_id: str | None = None # hog function id
- template: str | None = None # "slack" | "discord" | "webhook" | "teams"
- status: str = "accepted"
- at: str # ISO-8601 timestamp
+# Slack only, because `alert:write` is grantable to a sandboxed agent. A connected workspace is a
+# destination an admin chose, while every other transport takes a URL the caller supplies.
+INSIGHT_ALERT_DESTINATION_TYPES: Final[tuple[DestinationType, ...]] = (DestinationType.SLACK,)
diff --git a/products/alerts/backend/facade/destinations.py b/products/alerts/backend/facade/destinations.py
index 58bd6aaa1d10..2c43144409fa 100644
--- a/products/alerts/backend/facade/destinations.py
+++ b/products/alerts/backend/facade/destinations.py
@@ -15,8 +15,7 @@ from uuid import UUID
from posthog.kafka_client.client import ProduceResult
-from ..logic import destination_configs, destinations, insight_alert_destinations
-from .contracts import (
+from products.alerts_platform.backend.facade.contracts import (
ActiveAlertDestination,
AlertDelivery,
AlertDestinationConfig,
@@ -27,6 +26,8 @@ from .contracts import (
OwnedAlertDestination,
)
+from ..logic import destination_configs, destinations, insight_alert_destinations
+
ALERT_NOTIFICATION_FLUSH_TIMEOUT_SECONDS: Final = 10.0
# Each destination is another message every time the alert fires, so a caller in a loop is capped.
diff --git a/products/alerts/backend/facade/platform_alerts.py b/products/alerts/backend/facade/platform_alerts.py
deleted file mode 100644
index 77c59d7c2165..000000000000
--- a/products/alerts/backend/facade/platform_alerts.py
+++ /dev/null
@@ -1,14 +0,0 @@
-"""The skeleton shared alert tables, as a source adapter sees them.
-
-A source reads a batch of checks, reports what it decided, and can copy its own configurations
-in. It never holds one of these rows, so every write and every scheduling rule has one home.
-"""
-
-from products.alerts.backend.logic.platform_lifecycle import due_checks, record_outcomes, slot_of, upsert_configuration
-
-__all__ = [
- "due_checks",
- "record_outcomes",
- "slot_of",
- "upsert_configuration",
-]
diff --git a/products/alerts/backend/insight_alert_state_machine.py b/products/alerts/backend/insight_alert_state_machine.py
index 88112f6e3f49..d4126d72dbbe 100644
--- a/products/alerts/backend/insight_alert_state_machine.py
+++ b/products/alerts/backend/insight_alert_state_machine.py
@@ -5,7 +5,7 @@ from typing import TYPE_CHECKING
from posthog.schema_enums import AlertState as InsightAlertState
-from products.alerts.backend.facade.lifecycle import (
+from products.alerts_platform.backend.facade.lifecycle import (
AlertCheckOutcome,
AlertPolicy,
AlertSnapshot,
diff --git a/products/alerts/backend/logic/destination_configs.py b/products/alerts/backend/logic/destination_configs.py
index fcf3da842082..db9c52141265 100644
--- a/products/alerts/backend/logic/destination_configs.py
+++ b/products/alerts/backend/logic/destination_configs.py
@@ -7,7 +7,7 @@ from collections.abc import Sequence
from typing import Any, ClassVar
from urllib.parse import urlsplit
-from products.alerts.backend.facade.contracts import (
+from products.alerts_platform.backend.facade.contracts import (
AlertDestinationAction,
AlertDestinationConfig,
AlertDestinationData,
diff --git a/products/alerts/backend/logic/destinations.py b/products/alerts/backend/logic/destinations.py
index ca2cca775054..acbf246672db 100644
--- a/products/alerts/backend/logic/destinations.py
+++ b/products/alerts/backend/logic/destinations.py
@@ -20,7 +20,8 @@ from posthog.exceptions_capture import capture_exception
from posthog.kafka_client.client import ProduceResult
from posthog.plugins.plugin_server_api import reload_hog_functions_on_workers
-from products.alerts.backend.facade.contracts import (
+from products.alerts.backend.logic.destination_configs import SPEC_BY_TEMPLATE_ID, url_hostname
+from products.alerts_platform.backend.facade.contracts import (
ActiveAlertDestination,
AlertDestinationConfig,
AlertDestinationData,
@@ -28,7 +29,6 @@ from products.alerts.backend.facade.contracts import (
AlertDestinationValidationError,
OwnedAlertDestination,
)
-from products.alerts.backend.logic.destination_configs import SPEC_BY_TEMPLATE_ID, url_hostname
from products.cdp.backend.facade.api import create_hog_functions
from products.cdp.backend.facade.models import HogFunction
diff --git a/products/alerts/backend/logic/insight_alert_destinations.py b/products/alerts/backend/logic/insight_alert_destinations.py
index 236dbfa533cb..ad16fa52a570 100644
--- a/products/alerts/backend/logic/insight_alert_destinations.py
+++ b/products/alerts/backend/logic/insight_alert_destinations.py
@@ -12,12 +12,16 @@ from typing import Any, Final
from posthog.cdp.internal_events import LEGACY_INSIGHT_ALERT_EVENT
-from products.alerts.backend.facade.contracts import AlertDestinationConfig, AlertDestinationData, DestinationType
from products.alerts.backend.logic.destination_configs import (
DESTINATION_SPECS,
clip_hog_function_name,
destination_filter,
)
+from products.alerts_platform.backend.facade.contracts import (
+ AlertDestinationConfig,
+ AlertDestinationData,
+ DestinationType,
+)
SLACK_TEMPLATE_ID: Final = DESTINATION_SPECS[DestinationType.SLACK].template_id
diff --git a/products/alerts/backend/migrations/0012_move_platform_models_to_alerts_platform.py b/products/alerts/backend/migrations/0012_move_platform_models_to_alerts_platform.py
new file mode 100644
index 000000000000..7dcb96ed66d6
--- /dev/null
+++ b/products/alerts/backend/migrations/0012_move_platform_models_to_alerts_platform.py
@@ -0,0 +1,26 @@
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ """The platform's models leave this app's state. The tables stay where they are.
+
+ `alerts_platform.0001_initial` recreates them in the new app's state under the same
+ `db_table`, so no table is created, dropped or renamed by either migration.
+ """
+
+ dependencies = [
+ ("alerts", "0011_platformalertthread"),
+ ("alerts_platform", "0001_initial"),
+ ]
+
+ database_operations: list = []
+
+ state_operations = [
+ migrations.DeleteModel("PlatformAlertThread"),
+ migrations.DeleteModel("PlatformAlert"),
+ migrations.DeleteModel("PlatformAlertConfiguration"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(database_operations=database_operations, state_operations=state_operations)
+ ]
diff --git a/products/alerts/backend/migrations/max_migration.txt b/products/alerts/backend/migrations/max_migration.txt
index c57484510afe..3c74d15f3f74 100644
--- a/products/alerts/backend/migrations/max_migration.txt
+++ b/products/alerts/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0011_platformalertthread
+0012_move_platform_models_to_alerts_platform
diff --git a/products/alerts/backend/models/__init__.py b/products/alerts/backend/models/__init__.py
index 9f06e91b7c63..883ad1df8074 100644
--- a/products/alerts/backend/models/__init__.py
+++ b/products/alerts/backend/models/__init__.py
@@ -1,13 +1,9 @@
from .alert import Alert, AlertCheck, AlertConfiguration, AlertSubscription, Threshold
-from .platform_alert import PlatformAlert, PlatformAlertConfiguration, PlatformAlertThread
__all__ = [
"Alert",
"AlertCheck",
"AlertConfiguration",
"AlertSubscription",
- "PlatformAlert",
- "PlatformAlertConfiguration",
- "PlatformAlertThread",
"Threshold",
]
diff --git a/products/alerts/backend/presentation/views/alert.py b/products/alerts/backend/presentation/views/alert.py
index a80e80a2cc6a..514a1ccd0630 100644
--- a/products/alerts/backend/presentation/views/alert.py
+++ b/products/alerts/backend/presentation/views/alert.py
@@ -81,8 +81,6 @@ from products.alerts.backend.evaluation.validation import (
validate_alert_insight_query,
)
from products.alerts.backend.facade.api import (
- INSIGHT_ALERT_DESTINATION_TYPES,
- INSIGHT_ALERT_EVENT_IDS,
LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,
MAX_PROMPT_POINTS,
LLMAlertWrite,
@@ -92,11 +90,7 @@ from products.alerts.backend.facade.api import (
is_llm_detector_config,
llm_detector_access_error,
)
-from products.alerts.backend.facade.contracts import (
- AlertDestinationData,
- AlertDestinationValidationError,
- DestinationType,
-)
+from products.alerts.backend.facade.contracts import INSIGHT_ALERT_DESTINATION_TYPES, INSIGHT_ALERT_EVENT_IDS
from products.alerts.backend.facade.destinations import (
MAX_DESTINATION_IDS_PER_DELETE_REQUEST,
MAX_DESTINATIONS_PER_ALERT,
@@ -107,7 +101,6 @@ from products.alerts.backend.facade.destinations import (
validate_destination_data,
)
from products.alerts.backend.facade.evaluation import DelayedEvaluationUnavailable, validate_evaluation_delay
-from products.alerts.backend.facade.scheduling import validate_and_normalize_schedule_start_time
from products.alerts.backend.insight_alert_state_machine import (
apply_disable,
apply_enable,
@@ -117,6 +110,12 @@ from products.alerts.backend.insight_alert_state_machine import (
)
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold
from products.alerts.backend.presentation.views.schedule_restriction import AlertScheduleRestriction
+from products.alerts_platform.backend.facade.contracts import (
+ AlertDestinationData,
+ AlertDestinationValidationError,
+ DestinationType,
+)
+from products.alerts_platform.backend.facade.scheduling import validate_and_normalize_schedule_start_time
from products.product_analytics.backend.facade.api import lock_insight_for_evaluation
from products.product_analytics.backend.facade.models import Insight, resolve_insight_by_id_or_short_id
diff --git a/products/alerts/backend/presentation/views/platform_alert.py b/products/alerts/backend/presentation/views/platform_alert.py
deleted file mode 100644
index 2a004e30d95f..000000000000
--- a/products/alerts/backend/presentation/views/platform_alert.py
+++ /dev/null
@@ -1,144 +0,0 @@
-from django.db.models import Prefetch, QuerySet
-
-from rest_framework import serializers, viewsets
-
-from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.permissions import PostHogFeatureFlagPermission, get_authenticator_scopes
-from posthog.scopes import APIScopeObject, scopes_not_covered
-
-from products.alerts.backend.models.platform_alert import PlatformAlert, PlatformAlertConfiguration
-from products.alerts.backend.presentation.views.alert import ScheduleRestrictionField
-
-
-class PlatformAlertSerializer(serializers.ModelSerializer):
- class Meta:
- model = PlatformAlert
- fields = ["id", "grouping_key", "state", "firing_started_at", "last_notified_at", "snooze_until"]
- read_only_fields = fields
- extra_kwargs = {
- "id": {"help_text": "Unique identifier of this alert instance."},
- "grouping_key": {
- "help_text": "Key of the result group this instance tracks. Empty when the source does not group results."
- },
- "state": {"help_text": "Current state of this alert instance."},
- "firing_started_at": {
- "help_text": "When the current firing started. Null when the instance is not firing."
- },
- "last_notified_at": {"help_text": "When a notification was last sent for this instance."},
- "snooze_until": {"help_text": "Time until which notifications are snoozed. Null when not snoozed."},
- }
-
-
-class PlatformAlertConfigurationSerializer(serializers.ModelSerializer):
- source_config = serializers.DictField(
- child=serializers.JSONField(),
- read_only=True,
- help_text="Source-specific query settings. The shape depends on source_kind.",
- )
- schedule_restriction = ScheduleRestrictionField(
- read_only=True,
- allow_null=True,
- help_text="Blocked local time windows (HH:MM in the project timezone) when the alert does not run. "
- "Null means no quiet hours.",
- )
- alerts = PlatformAlertSerializer(
- many=True,
- read_only=True,
- help_text="Runtime state for each result group of this configuration.",
- )
-
- class Meta:
- model = PlatformAlertConfiguration
- fields = [
- "id",
- "name",
- "enabled",
- "source_kind",
- "source_config",
- "threshold_count",
- "threshold_operator",
- "window_minutes",
- "check_interval_minutes",
- "evaluation_periods",
- "datapoints_to_alarm",
- "cooldown_minutes",
- "schedule_restriction",
- "next_check_at",
- "consecutive_failures",
- "legacy_configuration_id",
- "created_at",
- "updated_at",
- "alerts",
- ]
- read_only_fields = fields
- extra_kwargs = {
- "id": {"help_text": "Unique identifier of the alert configuration."},
- "name": {"help_text": "Human-readable name of the alert."},
- "enabled": {"help_text": "Whether the alert is evaluated on schedule."},
- "source_kind": {"help_text": "Product whose data the alert evaluates."},
- "threshold_count": {"help_text": "Count the evaluated value is compared against."},
- "threshold_operator": {"help_text": "Comparison operator applied between the value and threshold_count."},
- "window_minutes": {"help_text": "Length of the evaluated time window, in minutes."},
- "check_interval_minutes": {"help_text": "Minutes between scheduled checks."},
- "evaluation_periods": {"help_text": "Number of recent checks considered when deciding to fire."},
- "datapoints_to_alarm": {
- "help_text": "Number of breaching checks within evaluation_periods required to fire."
- },
- "cooldown_minutes": {"help_text": "Minimum minutes between notifications for the same alert."},
- "next_check_at": {"help_text": "When the next check is due. Null when no check is scheduled."},
- "consecutive_failures": {"help_text": "Number of checks in a row that failed to evaluate."},
- "legacy_configuration_id": {
- "help_text": "ID of the legacy source configuration this row was backfilled from. "
- "Null for alerts created on the platform."
- },
- "created_at": {"help_text": "When the configuration was created."},
- "updated_at": {"help_text": "When the configuration was last changed."},
- }
-
-
-# A configuration shows the source product's data (its filters and firing state), so a reader
-# also needs read access to that product. `alert:read` alone must not reveal it.
-SOURCE_KIND_RESOURCE: dict[str, APIScopeObject] = {
- PlatformAlertConfiguration.SourceKind.LOGS: "logs",
-}
-
-
-class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.ReadOnlyModelViewSet):
- scope_object = "alert"
- serializer_class = PlatformAlertConfigurationSerializer
- posthog_feature_flag = "platform-alerts"
- permission_classes = [PostHogFeatureFlagPermission]
- # The fail-closed manager raises if `.all()` runs at import, so scoping happens in
- # safely_get_queryset.
- queryset = PlatformAlertConfiguration.objects.unscoped()
-
- def _should_skip_parents_filter(self) -> bool:
- # safely_get_queryset scopes a child environment to its parent team, where the rows live. The
- # default parent-lookup filter would AND the raw URL team id back in and hide them.
- return True
-
- def _readable_source_kinds(self) -> list[str]:
- # Session auth carries no scopes, so only the access-control check applies to it.
- token_scopes = get_authenticator_scopes(getattr(self.request, "successful_authenticator", None))
- readable: list[str] = []
- for source_kind, resource in SOURCE_KIND_RESOURCE.items():
- if not self.user_access_control.check_access_level_for_resource(resource, "viewer"):
- continue
- if (
- token_scopes is not None
- and "*" not in token_scopes
- and scopes_not_covered(token_scopes, [f"{resource}:read"])
- ):
- continue
- readable.append(source_kind)
- return readable
-
- def safely_get_queryset(self, queryset: QuerySet) -> QuerySet[PlatformAlertConfiguration]:
- canonical_team_id = self.team.parent_team_id or self.team.id
- alerts = PlatformAlert.objects.for_team(canonical_team_id, canonical=True).order_by("grouping_key")
- return (
- PlatformAlertConfiguration.objects.for_team(canonical_team_id, canonical=True)
- .filter(source_kind__in=self._readable_source_kinds())
- .prefetch_related(Prefetch("alerts", queryset=alerts))
- .order_by("-created_at", "-id")
- )
diff --git a/products/alerts/backend/routes.py b/products/alerts/backend/routes.py
index 1a70be7d5e6a..ed84bd386fa1 100644
--- a/products/alerts/backend/routes.py
+++ b/products/alerts/backend/routes.py
@@ -1,7 +1,6 @@
from posthog.api.routing import RouterRegistry
import products.alerts.backend.presentation.views.alert as alert
-import products.alerts.backend.presentation.views.platform_alert as platform_alert
def register_routes(routers: RouterRegistry) -> None:
@@ -11,11 +10,5 @@ def register_routes(routers: RouterRegistry) -> None:
"project_alerts",
["team_id"],
)
- routers.projects.register(
- r"platform_alerts",
- platform_alert.PlatformAlertConfigurationViewSet,
- "project_platform_alerts",
- ["team_id"],
- )
# ThresholdViewSet is registered as a sub-route under insights/<id>/thresholds
# by products.product_analytics.backend.routes — it imports alert.ThresholdViewSet.
diff --git a/products/alerts/backend/test/test_destination_configs.py b/products/alerts/backend/test/test_destination_configs.py
index ee47ec5b5ddc..dd7121a12043 100644
--- a/products/alerts/backend/test/test_destination_configs.py
+++ b/products/alerts/backend/test/test_destination_configs.py
@@ -4,18 +4,18 @@ import pytest
from posthog.cdp.templates import HOG_FUNCTION_TEMPLATES
-from products.alerts.backend.facade.contracts import (
- AlertDestinationAction,
- AlertDestinationData,
- DestinationType,
- EventKindSpec,
-)
from products.alerts.backend.logic.destination_configs import (
DESTINATION_SPECS,
build_alert_destination_config,
slack_blocks,
teams_text,
)
+from products.alerts_platform.backend.facade.contracts import (
+ AlertDestinationAction,
+ AlertDestinationData,
+ DestinationType,
+ EventKindSpec,
+)
DEFAULT_SPEC = EventKindSpec(
event_id="$insight_alert_firing",
diff --git a/products/alerts/backend/test/test_destinations.py b/products/alerts/backend/test/test_destinations.py
index b3d12b7f0cd5..9a4a8d901887 100644
--- a/products/alerts/backend/test/test_destinations.py
+++ b/products/alerts/backend/test/test_destinations.py
@@ -11,14 +11,6 @@ from parameterized import parameterized
from posthog.models.team.team import Team
-from products.alerts.backend.facade.contracts import (
- AlertDelivery,
- AlertDestinationConfig,
- AlertDestinationData,
- AlertDestinationValidationError,
- DestinationType,
- EventKindSpec,
-)
from products.alerts.backend.facade.destinations import serialize_deliveries
from products.alerts.backend.logic.destination_configs import DESTINATION_SPECS, build_alert_destination_config
from products.alerts.backend.logic.destinations import (
@@ -36,6 +28,14 @@ from products.alerts.backend.logic.destinations import (
soft_delete_alert_destinations,
soft_delete_all_alert_destinations,
)
+from products.alerts_platform.backend.facade.contracts import (
+ AlertDelivery,
+ AlertDestinationConfig,
+ AlertDestinationData,
+ AlertDestinationValidationError,
+ DestinationType,
+ EventKindSpec,
+)
from products.cdp.backend.facade.models import HogFunction
ALLOWED_EVENT_IDS = (
diff --git a/products/alerts/backend/test/test_insight_alert_state_machine.py b/products/alerts/backend/test/test_insight_alert_state_machine.py
index 715ecab5bec9..042eba729cd4 100644
--- a/products/alerts/backend/test/test_insight_alert_state_machine.py
+++ b/products/alerts/backend/test/test_insight_alert_state_machine.py
@@ -4,7 +4,6 @@ from typing import cast
from posthog.schema_enums import AlertState as InsightAlertState
-from products.alerts.backend.facade.lifecycle import AlertState
from products.alerts.backend.insight_alert_state_machine import (
apply_disable,
apply_enable,
@@ -15,6 +14,7 @@ from products.alerts.backend.insight_alert_state_machine import (
should_notify,
)
from products.alerts.backend.models.alert import AlertConfiguration
+from products.alerts_platform.backend.facade.lifecycle import AlertState
NOW = datetime(2026, 7, 27, 12, 0, tzinfo=UTC)
diff --git a/products/alerts/backend/tests/api/test_alert.py b/products/alerts/backend/tests/api/test_alert.py
index e3d16fd860d8..53c1e10c2aa0 100644
--- a/products/alerts/backend/tests/api/test_alert.py
+++ b/products/alerts/backend/tests/api/test_alert.py
@@ -24,14 +24,15 @@ from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team import Team
from posthog.models.utils import generate_random_token_personal, hash_key_value
-from products.alerts.backend.facade.api import INSIGHT_ALERT_EVENT_IDS, LLMDetectorUnavailableError
-from products.alerts.backend.facade.contracts import AlertDelivery
+from products.alerts.backend.facade.api import LLMDetectorUnavailableError
+from products.alerts.backend.facade.contracts import INSIGHT_ALERT_EVENT_IDS
from products.alerts.backend.facade.destinations import MAX_DESTINATIONS_PER_ALERT, count_active_alert_destinations
-from products.alerts.backend.facade.scheduling import CalendarInterval, alert_check_offset
from products.alerts.backend.judge.verdict import LLMDetectionVerdict
from products.alerts.backend.logic.insight_alert_destinations import SLACK_TEMPLATE_ID
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold
from products.alerts.backend.presentation.views.alert import AlertSerializer
+from products.alerts_platform.backend.facade.contracts import AlertDelivery
+from products.alerts_platform.backend.facade.scheduling import CalendarInterval, alert_check_offset
from products.cdp.backend.facade.models import HogFunction
from products.product_analytics.backend.facade.models import Insight
diff --git a/products/alerts/backend/tests/api/test_platform_alert.py b/products/alerts/backend/tests/api/test_platform_alert.py
deleted file mode 100644
index 4dbb1b0aa4c7..000000000000
--- a/products/alerts/backend/tests/api/test_platform_alert.py
+++ /dev/null
@@ -1,132 +0,0 @@
-from datetime import UTC, datetime
-from uuid import UUID, uuid4
-
-from posthog.test.base import APIBaseTest
-from unittest.mock import patch
-
-from parameterized import parameterized
-from rest_framework import status
-
-from posthog.constants import AvailableFeature
-from posthog.models import OrganizationMembership, User
-from posthog.models.scoping import team_scope
-from posthog.models.team import Team
-
-from products.access_control.backend.models.access_control import AccessControl
-from products.alerts.backend.models import PlatformAlert, PlatformAlertConfiguration
-
-
-class TestPlatformAlertAPI(APIBaseTest):
- def _create_configuration(
- self, team: Team, name: str, legacy_configuration_id: UUID | None = None
- ) -> PlatformAlertConfiguration:
- with team_scope(team.id):
- return PlatformAlertConfiguration.objects.create(
- team=team,
- name=name,
- source_kind=PlatformAlertConfiguration.SourceKind.LOGS,
- source_config={"service": "api"},
- threshold_count=10,
- threshold_operator="above",
- window_minutes=5,
- check_interval_minutes=10,
- legacy_configuration_id=legacy_configuration_id,
- )
-
- def _set_flag(self, enabled: bool) -> None:
- self.enterContext(patch("posthog.permissions.posthog_feature_flag_enabled", return_value=enabled))
-
- @parameterized.expand([("list", False), ("retrieve", True)])
- def test_flag_off_blocks_access(self, _name: str, with_id: bool) -> None:
- self._set_flag(False)
- configuration = self._create_configuration(self.team, "API errors")
- url = f"/api/projects/{self.team.id}/platform_alerts/"
- if with_id:
- url += f"{configuration.id}/"
-
- response = self.client.get(url)
-
- assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
- assert response.json()["code"] == "feature_flag_required"
-
- def test_list_returns_own_configurations_with_nested_alerts(self) -> None:
- self._set_flag(True)
- legacy_configuration_id = uuid4()
- configuration = self._create_configuration(self.team, "API errors", legacy_configuration_id)
- firing_started_at = datetime(2026, 9, 16, 10, tzinfo=UTC)
- with team_scope(self.team.id):
- alert = PlatformAlert.objects.create(
- team=self.team,
- configuration=configuration,
- grouping_key="checkout",
- state=PlatformAlert.State.FIRING,
- firing_started_at=firing_started_at,
- last_notified_at=firing_started_at,
- )
- other_team = Team.objects.create(organization=self.organization, name="Other team")
- other_configuration = self._create_configuration(other_team, "Other team errors")
- child_environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="env")
-
- list_response = self.client.get(f"/api/projects/{self.team.id}/platform_alerts/")
- child_retrieve_response = self.client.get(
- f"/api/projects/{child_environment.id}/platform_alerts/{configuration.id}/"
- )
- other_retrieve_response = self.client.get(
- f"/api/projects/{self.team.id}/platform_alerts/{other_configuration.id}/"
- )
-
- assert list_response.status_code == status.HTTP_200_OK, list_response.json()
- results = list_response.json()["results"]
- assert [r["id"] for r in results] == [str(configuration.id)]
- assert results[0]["legacy_configuration_id"] == str(legacy_configuration_id)
- assert results[0]["alerts"] == [
- {
- "id": str(alert.id),
- "grouping_key": "checkout",
- "state": "firing",
- "firing_started_at": "2026-09-16T10:00:00Z",
- "last_notified_at": "2026-09-16T10:00:00Z",
- "snooze_until": None,
- }
- ]
- assert child_retrieve_response.status_code == status.HTTP_200_OK, child_retrieve_response.json()
- assert child_retrieve_response.json() == results[0]
- assert other_retrieve_response.status_code == status.HTTP_404_NOT_FOUND
-
- @parameterized.expand(
- [
- ("member_without_logs_access", None, False),
- ("key_without_logs_scope", ["alert:read"], False),
- ("key_with_logs_scope", ["alert:read", "logs:read"], True),
- ]
- )
- def test_logs_configurations_need_logs_read_access(
- self, _name: str, key_scopes: list[str] | None, visible: bool
- ) -> None:
- self._set_flag(True)
- configuration = self._create_configuration(self.team, "API errors")
- if key_scopes is None:
- self.organization.available_product_features = [
- {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
- ]
- self.organization.save()
- member = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
- AccessControl.objects.create(
- team=self.team,
- resource="logs",
- resource_id=None,
- access_level="none",
- organization_member=OrganizationMembership.objects.get(user=member, organization=self.organization),
- )
- self.client.force_login(member)
- else:
- self.client.logout()
- self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {self.create_personal_api_key_with_scopes(key_scopes)}")
-
- list_response = self.client.get(f"/api/projects/{self.team.id}/platform_alerts/")
- retrieve_response = self.client.get(f"/api/projects/{self.team.id}/platform_alerts/{configuration.id}/")
-
- assert list_response.status_code == status.HTTP_200_OK, list_response.json()
- assert [r["id"] for r in list_response.json()["results"]] == ([str(configuration.id)] if visible else [])
- expected_retrieve_status = status.HTTP_200_OK if visible else status.HTTP_404_NOT_FOUND
- assert retrieve_response.status_code == expected_retrieve_status, retrieve_response.json()
diff --git a/products/alerts/frontend/generated/api.schemas.ts b/products/alerts/frontend/generated/api.schemas.ts
index 970f5c683b35..49456a5f91fc 100644
--- a/products/alerts/frontend/generated/api.schemas.ts
+++ b/products/alerts/frontend/generated/api.schemas.ts
@@ -1006,127 +1006,6 @@ export interface PaginatedThresholdWithAlertListApi {
results: ThresholdWithAlertApi[]
}
-/**
- * * `logs` - Logs
- */
-export type PlatformAlertConfigurationSourceKindEnumApi =
- (typeof PlatformAlertConfigurationSourceKindEnumApi)[keyof typeof PlatformAlertConfigurationSourceKindEnumApi]
-
-export const PlatformAlertConfigurationSourceKindEnumApi = {
- Logs: 'logs',
-} as const
-
-/**
- * * `not_firing` - Not firing
- * * `firing` - Firing
- * * `errored` - Errored
- * * `snoozed` - Snoozed
- * * `broken` - Broken
- */
-export type BillingAlertConfigurationStateEnumApi =
- (typeof BillingAlertConfigurationStateEnumApi)[keyof typeof BillingAlertConfigurationStateEnumApi]
-
-export const BillingAlertConfigurationStateEnumApi = {
- NotFiring: 'not_firing',
- Firing: 'firing',
- Errored: 'errored',
- Snoozed: 'snoozed',
- Broken: 'broken',
-} as const
-
-export interface PlatformAlertApi {
- /** Unique identifier of this alert instance. */
- readonly id: string
- /** Key of the result group this instance tracks. Empty when the source does not group results. */
- readonly grouping_key: string
- /** Current state of this alert instance.
- *
- * * `not_firing` - Not firing
- * * `firing` - Firing
- * * `errored` - Errored
- * * `snoozed` - Snoozed
- * * `broken` - Broken */
- readonly state: BillingAlertConfigurationStateEnumApi
- /**
- * When the current firing started. Null when the instance is not firing.
- * @nullable
- */
- readonly firing_started_at: string | null
- /**
- * When a notification was last sent for this instance.
- * @nullable
- */
- readonly last_notified_at: string | null
- /**
- * Time until which notifications are snoozed. Null when not snoozed.
- * @nullable
- */
- readonly snooze_until: string | null
-}
-
-/**
- * Source-specific query settings. The shape depends on source_kind.
- */
-export type PlatformAlertConfigurationApiSourceConfig = { [key: string]: unknown }
-
-export interface PlatformAlertConfigurationApi {
- /** Unique identifier of the alert configuration. */
- readonly id: string
- /** Human-readable name of the alert. */
- readonly name: string
- /** Whether the alert is evaluated on schedule. */
- readonly enabled: boolean
- /** Product whose data the alert evaluates.
- *
- * * `logs` - Logs */
- readonly source_kind: PlatformAlertConfigurationSourceKindEnumApi
- /** Source-specific query settings. The shape depends on source_kind. */
- readonly source_config: PlatformAlertConfigurationApiSourceConfig
- /** Count the evaluated value is compared against. */
- readonly threshold_count: number
- /** Comparison operator applied between the value and threshold_count. */
- readonly threshold_operator: string
- /** Length of the evaluated time window, in minutes. */
- readonly window_minutes: number
- /** Minutes between scheduled checks. */
- readonly check_interval_minutes: number
- /** Number of recent checks considered when deciding to fire. */
- readonly evaluation_periods: number
- /** Number of breaching checks within evaluation_periods required to fire. */
- readonly datapoints_to_alarm: number
- /** Minimum minutes between notifications for the same alert. */
- readonly cooldown_minutes: number
- /** Blocked local time windows (HH:MM in the project timezone) when the alert does not run. Null means no quiet hours. */
- readonly schedule_restriction: AlertScheduleRestrictionApi | null
- /**
- * When the next check is due. Null when no check is scheduled.
- * @nullable
- */
- readonly next_check_at: string | null
- /** Number of checks in a row that failed to evaluate. */
- readonly consecutive_failures: number
- /**
- * ID of the legacy source configuration this row was backfilled from. Null for alerts created on the platform.
- * @nullable
- */
- readonly legacy_configuration_id: string | null
- /** When the configuration was created. */
- readonly created_at: string
- /** When the configuration was last changed. */
- readonly updated_at: string
- /** Runtime state for each result group of this configuration. */
- readonly alerts: readonly PlatformAlertApi[]
-}
-
-export interface PaginatedPlatformAlertConfigurationListApi {
- count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
- results: PlatformAlertConfigurationApi[]
-}
-
export type AlertsListParams = {
/**
* Optional. Restrict results to alerts created by the user with this UUID.
@@ -1187,14 +1066,3 @@ export type InsightsThresholdsListParams = {
*/
offset?: number
}
-
-export type PlatformAlertsListParams = {
- /**
- * Number of results to return per page.
- */
- limit?: number
- /**
- * The initial index from which to return the results.
- */
- offset?: number
-}
diff --git a/products/alerts/frontend/generated/api.ts b/products/alerts/frontend/generated/api.ts
index c07950454434..0e6ee1dc7ea4 100644
--- a/products/alerts/frontend/generated/api.ts
+++ b/products/alerts/frontend/generated/api.ts
@@ -20,11 +20,8 @@ import type {
AlertsRetrieveParams,
InsightsThresholdsListParams,
PaginatedAlertListApi,
- PaginatedPlatformAlertConfigurationListApi,
PaginatedThresholdWithAlertListApi,
PatchedAlertApi,
- PlatformAlertConfigurationApi,
- PlatformAlertsListParams,
ThresholdWithAlertApi,
} from './api.schemas'
@@ -291,45 +288,3 @@ export const insightsThresholdsRetrieve = async (
method: 'GET',
})
}
-
-export const getPlatformAlertsListUrl = (projectId: string, params?: PlatformAlertsListParams) => {
- const normalizedParams = new URLSearchParams()
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : String(value))
- }
- })
-
- const stringifiedParams = normalizedParams.toString()
-
- return stringifiedParams.length > 0
- ? `/api/projects/${projectId}/platform_alerts/?${stringifiedParams}`
- : `/api/projects/${projectId}/platform_alerts/`
-}
-
-export const platformAlertsList = async (
- projectId: string,
- params?: PlatformAlertsListParams,
- options?: RequestInit
-): Promise<PaginatedPlatformAlertConfigurationListApi> => {
- return apiMutator<PaginatedPlatformAlertConfigurationListApi>(getPlatformAlertsListUrl(projectId, params), {
- ...options,
- method: 'GET',
- })
-}
-
-export const getPlatformAlertsRetrieveUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/platform_alerts/${id}/`
-}
-
-export const platformAlertsRetrieve = async (
- projectId: string,
- id: string,
- options?: RequestInit
-): Promise<PlatformAlertConfigurationApi> => {
- return apiMutator<PlatformAlertConfigurationApi>(getPlatformAlertsRetrieveUrl(projectId, id), {
- ...options,
- method: 'GET',
- })
-}
diff --git a/products/alerts/mcp/tools.yaml b/products/alerts/mcp/tools.yaml
index 9527e4e73649..37866dc5ebc5 100644
--- a/products/alerts/mcp/tools.yaml
+++ b/products/alerts/mcp/tools.yaml
@@ -234,9 +234,3 @@ tools:
insights-thresholds-retrieve:
operation: insights_thresholds_retrieve
enabled: false
- platform-alerts-list:
- operation: platform_alerts_list
- enabled: false
- platform-alerts-retrieve:
- operation: platform_alerts_retrieve
- enabled: false
diff --git a/products/alerts/backend/delivery/__init__.py b/products/alerts_platform/__init__.py
similarity index 100%
rename from products/alerts/backend/delivery/__init__.py
rename to products/alerts_platform/__init__.py
diff --git a/products/alerts_platform/backend/__init__.py b/products/alerts_platform/backend/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/alerts_platform/backend/apps.py b/products/alerts_platform/backend/apps.py
new file mode 100644
index 000000000000..b9f08a725137
--- /dev/null
+++ b/products/alerts_platform/backend/apps.py
@@ -0,0 +1,8 @@
+"""Django app configuration for alerts_platform."""
+
+from django.apps import AppConfig
+
+
+class AlertsPlatformConfig(AppConfig):
+ name = "products.alerts_platform.backend"
+ label = "alerts_platform"
diff --git a/products/alerts_platform/backend/delivery/__init__.py b/products/alerts_platform/backend/delivery/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/alerts_platform/backend/delivery/destinations.py b/products/alerts_platform/backend/delivery/destinations.py
new file mode 100644
index 000000000000..228a9ce44b52
--- /dev/null
+++ b/products/alerts_platform/backend/delivery/destinations.py
@@ -0,0 +1,30 @@
+"""Who a delivery sends to.
+
+Destinations are HogFunction rows, and `products.alerts` owns them. The platform imports no other
+product, so that product registers its lookup here when Django starts, and delivery asks this
+module rather than the owner. This module goes away when destinations move into the platform.
+"""
+
+from collections.abc import Collection
+
+from products.alerts_platform.backend.facade.contracts import AlertDestinationGroup, DestinationResolver
+
+_resolver: DestinationResolver | None = None
+
+
+def register(resolver: DestinationResolver) -> None:
+ global _resolver
+ # One owner. A second registrant would silently take every alert's destinations.
+ if _resolver is not None and _resolver is not resolver:
+ raise RuntimeError("A different destination resolver is already registered.")
+ _resolver = resolver
+
+
+def list_alert_destination_groups(
+ *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]
+) -> list[AlertDestinationGroup]:
+ # Raise rather than answer "no destinations". An empty answer would make a missing
+ # registration look like an alert that nobody subscribed to, and nothing would report it.
+ if _resolver is None:
+ raise RuntimeError("No destination resolver is registered. products.alerts registers one in its ready().")
+ return _resolver(team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids)
diff --git a/products/alerts/backend/delivery/dispatch.py b/products/alerts_platform/backend/delivery/dispatch.py
similarity index 87%
rename from products/alerts/backend/delivery/dispatch.py
rename to products/alerts_platform/backend/delivery/dispatch.py
index d1182fb6caa6..e870e044f6f5 100644
--- a/products/alerts/backend/delivery/dispatch.py
+++ b/products/alerts_platform/backend/delivery/dispatch.py
@@ -5,11 +5,15 @@ it. Which destinations an alert has is resolved before this, so a change to that
reaches no transport.
"""
-from products.alerts.backend.delivery.message import AlertMessage, build_message
-from products.alerts.backend.delivery.telemetry import record_delivery
-from products.alerts.backend.delivery.thread_store import ThreadBusy, ThreadKey, ThreadStore
-from products.alerts.backend.delivery.transport import DeliveryTransport, MessageHandle
-from products.alerts.backend.facade.contracts import AlertDestinationData, AnnouncedTransition, EvaluationAnnouncement
+from products.alerts_platform.backend.delivery.message import AlertMessage, build_message
+from products.alerts_platform.backend.delivery.telemetry import record_delivery
+from products.alerts_platform.backend.delivery.thread_store import ThreadBusy, ThreadKey, ThreadStore
+from products.alerts_platform.backend.delivery.transport import DeliveryTransport, MessageHandle
+from products.alerts_platform.backend.facade.contracts import (
+ AlertDestinationData,
+ AnnouncedTransition,
+ EvaluationAnnouncement,
+)
def deliver(
diff --git a/products/alerts/backend/delivery/evaluation.py b/products/alerts_platform/backend/delivery/evaluation.py
similarity index 85%
rename from products/alerts/backend/delivery/evaluation.py
rename to products/alerts_platform/backend/delivery/evaluation.py
index 82be8ac3050b..9cb3a3433926 100644
--- a/products/alerts/backend/delivery/evaluation.py
+++ b/products/alerts_platform/backend/delivery/evaluation.py
@@ -13,19 +13,19 @@ import posthoganalytics
from posthog.dataclasses import frozen
from posthog.models import Team
-from products.alerts.backend.delivery.dispatch import deliver
-from products.alerts.backend.delivery.slack import SlackTransport
-from products.alerts.backend.delivery.thread_store import DatabaseThreadStore
-from products.alerts.backend.delivery.transport import DeliveryTransport
-from products.alerts.backend.facade.contracts import (
+from products.alerts_platform.backend.delivery.destinations import list_alert_destination_groups
+from products.alerts_platform.backend.delivery.dispatch import deliver
+from products.alerts_platform.backend.delivery.slack import SlackTransport
+from products.alerts_platform.backend.delivery.thread_store import DatabaseThreadStore
+from products.alerts_platform.backend.delivery.transport import DeliveryTransport
+from products.alerts_platform.backend.facade.contracts import (
AlertDeliveryRequest,
AlertDestinationData,
AnnouncedTransition,
DestinationType,
EvaluationAnnouncement,
)
-from products.alerts.backend.facade.destinations import list_alert_destination_groups
-from products.alerts.backend.logic.platform_alert_events import announcement
+from products.alerts_platform.backend.logic.platform_alert_events import announcement
logger = structlog.get_logger(__name__)
@@ -35,10 +35,10 @@ logger = structlog.get_logger(__name__)
# and it is not this.
LIVE_DELIVERY_FLAG: Final = "alert-platform-live-delivery"
-# A destination type with no entry here has no native transport. An alert that uses one is not
-# eligible for native delivery at all, which is checked before a team is made live rather than
-# branched on per destination: one alert delivering natively to Slack and through a HogFunction
-# to Discord would send two differently worded messages for one event.
+# A destination type with no entry here has no native transport, and delivery skips it. Make a
+# team live only when its alerts use no such type. Nothing checks this in code, and one alert
+# delivering natively to Slack and through a HogFunction to Discord would send two differently
+# worded messages for one event.
_TRANSPORTS: Final[dict[DestinationType, type[DeliveryTransport]]] = {DestinationType.SLACK: SlackTransport}
diff --git a/products/alerts/backend/delivery/message.py b/products/alerts_platform/backend/delivery/message.py
similarity index 96%
rename from products/alerts/backend/delivery/message.py
rename to products/alerts_platform/backend/delivery/message.py
index a3761e625a36..fe52e14d2e09 100644
--- a/products/alerts/backend/delivery/message.py
+++ b/products/alerts_platform/backend/delivery/message.py
@@ -10,7 +10,11 @@ from typing import Any, Final
from posthog.dataclasses import frozen
from posthog.utils import pluralize
-from products.alerts.backend.facade.contracts import AlertEventKind, AnnouncedTransition, EvaluationAnnouncement
+from products.alerts_platform.backend.facade.contracts import (
+ AlertEventKind,
+ AnnouncedTransition,
+ EvaluationAnnouncement,
+)
_HEADLINES: Final[dict[AlertEventKind, str]] = {
AlertEventKind.FIRING: "{name} is firing",
diff --git a/products/alerts/backend/delivery/slack.py b/products/alerts_platform/backend/delivery/slack.py
similarity index 93%
rename from products/alerts/backend/delivery/slack.py
rename to products/alerts_platform/backend/delivery/slack.py
index fb8291d28e14..bb986529653a 100644
--- a/products/alerts/backend/delivery/slack.py
+++ b/products/alerts_platform/backend/delivery/slack.py
@@ -13,9 +13,9 @@ from posthog.models.integration import SLACK_INTEGRATION_KINDS, Integration, Sla
from posthog.slack.channels import MAX_SECTION_CHARS, clip_text, header_block, post_message, section_block
from posthog.slack.formatting import escape_slack_mrkdwn
-from products.alerts.backend.delivery.message import AlertMessage, MessageDetail
-from products.alerts.backend.delivery.transport import DeliveryError, MessageHandle
-from products.alerts.backend.facade.contracts import AlertDestinationData
+from products.alerts_platform.backend.delivery.message import AlertMessage, MessageDetail
+from products.alerts_platform.backend.delivery.transport import DeliveryError, MessageHandle
+from products.alerts_platform.backend.facade.contracts import AlertDestinationData
PROVIDER: Final = "slack"
diff --git a/products/alerts/backend/delivery/telemetry.py b/products/alerts_platform/backend/delivery/telemetry.py
similarity index 100%
rename from products/alerts/backend/delivery/telemetry.py
rename to products/alerts_platform/backend/delivery/telemetry.py
diff --git a/products/alerts/backend/delivery/thread_store.py b/products/alerts_platform/backend/delivery/thread_store.py
similarity index 97%
rename from products/alerts/backend/delivery/thread_store.py
rename to products/alerts_platform/backend/delivery/thread_store.py
index 9aa87c4758e9..2b6c8ef2df8e 100644
--- a/products/alerts/backend/delivery/thread_store.py
+++ b/products/alerts_platform/backend/delivery/thread_store.py
@@ -22,8 +22,8 @@ from django.utils import timezone
from posthog.dataclasses import frozen
-from products.alerts.backend.delivery.transport import MessageHandle
-from products.alerts.backend.models import PlatformAlertThread
+from products.alerts_platform.backend.delivery.transport import MessageHandle
+from products.alerts_platform.backend.models import PlatformAlertThread
# How long a send may hold a conversation before another attempt may take it. Long enough to
# cover a provider's own timeout, so a retry that starts while the first attempt is still
diff --git a/products/alerts/backend/delivery/transport.py b/products/alerts_platform/backend/delivery/transport.py
similarity index 92%
rename from products/alerts/backend/delivery/transport.py
rename to products/alerts_platform/backend/delivery/transport.py
index 3d0fa06ed05d..807f84630189 100644
--- a/products/alerts/backend/delivery/transport.py
+++ b/products/alerts_platform/backend/delivery/transport.py
@@ -9,8 +9,8 @@ from typing import Protocol
from posthog.dataclasses import frozen
-from products.alerts.backend.delivery.message import AlertMessage
-from products.alerts.backend.facade.contracts import AlertDestinationData
+from products.alerts_platform.backend.delivery.message import AlertMessage
+from products.alerts_platform.backend.facade.contracts import AlertDestinationData
@frozen
diff --git a/products/alerts_platform/backend/facade/__init__.py b/products/alerts_platform/backend/facade/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.py
new file mode 100644
index 000000000000..c1a7b84fa73c
--- /dev/null
+++ b/products/alerts_platform/backend/facade/api.py
@@ -0,0 +1,37 @@
+"""The shared alert tables, as a source adapter and this product's own API see them.
+
+A source reads a batch of checks, reports what it decided, and can copy its own configurations
+in. It never holds one of these rows, so every write and every scheduling rule has one home.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+from datetime import datetime
+
+from products.alerts_platform.backend.facade.contracts import (
+ PlatformAlertCheckInput,
+ PlatformAlertOutcome,
+ PlatformAlertUpsert,
+)
+from products.alerts_platform.backend.logic import platform_lifecycle
+
+
+def due_checks(team_id: int, source_kind: str, slot: str, cutoff: datetime) -> tuple[PlatformAlertCheckInput, ...]:
+ """Every check one batch key owes, flattened as a source reads them."""
+ return platform_lifecycle.due_checks(team_id, source_kind, slot, cutoff)
+
+
+def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now: datetime) -> int:
+ """The platform's only write of state and schedule. Returns how many rows it wrote."""
+ return platform_lifecycle.record_outcomes(team_id, outcomes, now)
+
+
+def slot_of(next_check_at: datetime | None, cutoff: datetime) -> str:
+ """The minute a configuration is due for."""
+ return platform_lifecycle.slot_of(next_check_at, cutoff)
+
+
+def upsert_configuration(upsert: PlatformAlertUpsert) -> bool:
+ """Copy one of a source's own configurations in. True when the row changed."""
+ return platform_lifecycle.upsert_configuration(upsert)
diff --git a/products/alerts_platform/backend/facade/clickhouse.py b/products/alerts_platform/backend/facade/clickhouse.py
new file mode 100644
index 000000000000..5b3da2b91011
--- /dev/null
+++ b/products/alerts_platform/backend/facade/clickhouse.py
@@ -0,0 +1,12 @@
+"""The ClickHouse tables core creates and migrates for this product.
+
+Wiring, not data: `posthog/clickhouse/schema.py` builds these in a local or test ClickHouse, and
+the migration that created them applies the same definitions to a cluster.
+"""
+
+from products.alerts_platform.backend.models.platform_alert_events_sql import (
+ DISTRIBUTED_PLATFORM_ALERT_EVENTS_TABLE_SQL as DISTRIBUTED_PLATFORM_ALERT_EVENTS_TABLE_SQL,
+ PLATFORM_ALERT_EVENTS_TABLE as PLATFORM_ALERT_EVENTS_TABLE,
+ SHARDED_PLATFORM_ALERT_EVENTS_TABLE as SHARDED_PLATFORM_ALERT_EVENTS_TABLE,
+ SHARDED_PLATFORM_ALERT_EVENTS_TABLE_SQL as SHARDED_PLATFORM_ALERT_EVENTS_TABLE_SQL,
+)
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
new file mode 100644
index 000000000000..e0d4f12d0795
--- /dev/null
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -0,0 +1,489 @@
+"""Contract types for alerts.
+
+Framework-free types that describe what this product hands to its consumers and
+accepts back. No Django, no DRF: other products read against these, and the Turbo
+contract check watches this file to decide whether they must retest.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Collection
+from dataclasses import field
+from datetime import datetime
+from enum import StrEnum
+from typing import Any, Final, NotRequired, Protocol, TypedDict
+from uuid import UUID
+
+from posthog.dataclasses import frozen
+from posthog.enums import LabeledStrEnum
+
+
+class SourceKind(StrEnum):
+ LOGS = "logs"
+ INSIGHT = "insight"
+
+
+@frozen
+class DemandDiscoveryInputs:
+ cutoff: str
+
+
+@frozen
+class AlertBatchKey:
+ """Names a chunk of due work by what it holds rather than by where it was cut.
+
+ `slot` is `next_check_at` floored to the minute, so a chunk keeps its identity across ticks:
+ a slow evaluation of a key is still the same key when the next tick rediscovers it.
+ """
+
+ team_id: int
+ slot: str
+
+
+@frozen
+class AlertDemand:
+ """Due batch keys per source, bounded so the payload stays small. A key costs a fixed amount and
+ does not grow with a team's alert count. `omitted_by_source` counts keys discovery left out;
+ that work is due again next tick."""
+
+ batch_keys_by_source: dict[SourceKind, list[AlertBatchKey]]
+ omitted_by_source: dict[SourceKind, int] = field(default_factory=dict)
+
+
+@frozen
+class SourceDispatchInputs:
+ """Everything the tick knows about one source. The dispatcher decides how much of it to take."""
+
+ tick_id: str
+ source: SourceKind
+ page: int
+ batch_keys: list[AlertBatchKey]
+ cutoff: str
+
+
+@frozen
+class SourceDispatchReport:
+ source: SourceKind
+ page: int
+ dispatched: int
+ remaining_keys: list[AlertBatchKey]
+ evaluation_workflow_ids: list[str]
+ # Not remaining: the run that already holds the key is still working it.
+ already_running: int = 0
+
+
+@frozen
+class SourceEvaluationInputs:
+ """What a source's own evaluation workflow receives from its dispatcher.
+
+ The key, not a list of ids. The evaluation loads full configurations anyway, so shipping ids
+ through the orchestrator would be transit cost, and re-reading gives it the fresher set.
+ """
+
+ source: SourceKind
+ cutoff: str
+ batch_key: AlertBatchKey
+
+
+@frozen
+class PlatformAlertCheckInput:
+ """One configuration and its runtime state, as a source adapter reads it.
+
+ Flat rather than nested, because a source never holds the rows and has nothing to do with
+ the split between what belongs to the configuration and what belongs to the instance.
+ """
+
+ id: UUID
+ team_id: int
+ name: str
+ source_config: dict[str, Any]
+ threshold_count: int
+ threshold_operator: str
+ window_minutes: int
+ check_interval_minutes: int
+ evaluation_periods: int
+ datapoints_to_alarm: int
+ cooldown_minutes: int
+ schedule_restriction: dict[str, Any] | None
+ next_check_at: datetime | None
+ consecutive_failures: int
+ legacy_configuration_id: UUID | None
+ state: str
+ last_notified_at: datetime | None
+ snooze_until: datetime | None
+ firing_started_at: datetime | None = None
+
+ @property
+ def filters(self) -> dict[str, Any]:
+ """Satisfies the logs query layer, which names this field `filters`."""
+ return self.source_config
+
+
+@frozen
+class PlatformAlertUpsert:
+ """One configuration a source wants copied into the shared tables."""
+
+ legacy_configuration_id: UUID
+ team_id: int
+ name: str
+ enabled: bool
+ source_kind: SourceKind
+ source_config: dict[str, Any]
+ threshold_count: int
+ threshold_operator: str
+ window_minutes: int
+ check_interval_minutes: int
+ evaluation_periods: int
+ datapoints_to_alarm: int
+ cooldown_minutes: int
+ schedule_restriction: dict[str, Any] | None
+ next_check_at: datetime | None
+ snooze_until: datetime | None
+
+
+class SkipReason(StrEnum):
+ """Why a check reached an outcome without a query answering it.
+
+ A label on the platform's own counters. It never reaches an alert's state or schedule. A check
+ that was evaluated has no skip reason, which is `None` rather than a member here.
+ """
+
+ BROKEN_CONFIG = "broken_config"
+ QUERY_FAILED = "query_failed"
+
+
+class MuteReason(StrEnum):
+ """Why an announcement was held. A muted check is evaluated like any other, so this labels the
+ held announcement rather than a skip."""
+
+ SNOOZE = "snooze"
+ QUIET_HOURS = "quiet_hours"
+
+
+class AlertEventKind(StrEnum):
+ """What one evaluation announced about an alert.
+
+ `CHECK` is an evaluation that announced nothing, which includes one that moved the alert while
+ a cooldown or a mute held the notification back. Read the history row's `previous_state` and
+ `state` to find the moves, because counting `RESOLVED` rows misses every recovery that was
+ suppressed.
+
+ A source reports the kind rather than the platform deriving it: the machine already decided
+ what to announce, and deriving it again from the states would be a second implementation of
+ that decision.
+ """
+
+ CHECK = "check"
+ FIRING = "firing"
+ RESOLVED = "resolved"
+ ERRORED = "errored"
+ BROKEN = "broken"
+
+
+@frozen
+class FiringEpisode:
+ """The firing a check concerns, and whether that check is the one that ended it.
+
+ Two readers want different things from it. An alert's current state wants the firing it is in
+ now, which is nothing once a check ends one. A history row and a delivery want the firing the
+ check was about, which on a resolve is the firing that just ended. Both come from here, so
+ neither has to work the difference out from the states.
+
+ `started_at` is None for a firing that began before the platform recorded starts.
+ """
+
+ started_at: datetime | None
+ ended: bool
+
+
+@frozen
+class PlatformAlertOutcome:
+ """What one check decided. The platform turns this into rows.
+
+ Every check produces one, including a check a source skipped. A skip that records nothing
+ leaves its due time where it was, so discovery finds the same work every tick.
+ """
+
+ configuration_id: UUID
+ evaluation_key: str
+ kind: AlertEventKind
+ new_state: str
+ notified: bool
+ consecutive_failures: int
+ firing_episode: FiringEpisode | None = None
+ value: float | None = None
+ labels: dict[str, str] = field(default_factory=dict)
+ error_message: str | None = None
+ query_duration_ms: int | None = None
+ # What a mute held back, so history separates a muted fire from a check that said nothing.
+ muted_notification: str = ""
+ # Recording an outcome without it leaves a configuration discovery keeps handing back to an
+ # evaluation that cannot succeed.
+ disable: bool = False
+
+
+@frozen
+class GroupTransition:
+ """One transition a delivery carries: `kind` picks the headline, `value` is the number it
+ quotes.
+
+ `grouping_key` is empty until a source groups, so delivery reads a list of one today and a
+ list of N when fan-out ships.
+
+ The condition and the source config a message also needs stay on the history row the
+ delivery addresses, because `source_config` is an unbounded filter tree and one per
+ transition would blow the payload bound `MAX_PREVIEWS_PER_CYCLE` was sized against.
+ """
+
+ grouping_key: str
+ kind: AlertEventKind
+ value: float | None = None
+
+
+@frozen
+class AnnouncedTransition:
+ """One group's transition as delivery reads it back, projected from a history row.
+
+ The sibling of `GroupTransition`, and deliberately not the same type. A `GroupTransition`
+ crosses Temporal on the delivery payload, so it stays small. This never does: delivery holds
+ an address, reads the row, and builds one of these in the process that sends the message. So
+ it carries what a message states, including the two snapshots the row already keeps.
+
+ Every field here is a column on `platform_alert_events`, which is what makes a message state
+ what its own check decided however long after the check it is rendered.
+ """
+
+ grouping_key: str
+ kind: AlertEventKind
+ # The firing this transition concerns, which on a resolve is the firing that just ended.
+ # None when no firing is involved, which is a failed or a turned-off check.
+ episode_started_at: datetime | None
+ value: float | None
+ labels: dict[str, str]
+ condition: dict[str, Any]
+ source_config: dict[str, Any]
+ error_message: str | None
+
+
+@frozen
+class EvaluationAnnouncement:
+ """What one evaluation left for a destination to say.
+
+ One transition is one message. A level between this and the transitions would be the place a
+ fan-in policy lived, and fan-in was deprioritized on 2026-09-28, so there is nothing for it
+ to hold. It arrives with fan-in rather than waiting here empty.
+ """
+
+ alert_name: str
+ # Evaluation-level, so it sits here rather than on a transition: a failed check fails the
+ # whole evaluation, and every group in one announcement saw the same count.
+ consecutive_failures: int
+ transitions: tuple[AnnouncedTransition, ...]
+
+
+@frozen
+class AlertDeliveryRequest:
+ """Where to find what one evaluation decided, rather than a copy of it.
+
+ A delivery addresses its history rows by `configuration_id` and `evaluation_key`, and reads
+ the facts back from there. So a retry announces what was recorded rather than what one
+ attempt happened to carry, and a batch's payload does not grow with what its alerts say.
+
+ The two destination fields are supplied by the source because only the source knows them.
+ `destination_alert_id` is the id its destinations are matched on, which is the legacy
+ configuration while the platform runs beside a source's own stack. `event_ids_by_kind` maps
+ each kind the source can announce onto the event id its destinations filter on. The platform
+ imports no source, so it cannot derive either.
+ """
+
+ source: SourceKind
+ team_id: int
+ configuration_id: str
+ evaluation_key: str
+ destination_alert_id: str
+ event_ids_by_kind: dict[str, str]
+
+
+@frozen
+class SourceBatchEvaluation:
+ """What one batch decided, before any of it is written.
+
+ Evaluation returns this and the write runs as its own activity, so Temporal has the
+ deliveries in history before anything can advance a schedule past them.
+ """
+
+ outcomes: tuple[PlatformAlertOutcome, ...]
+ deliveries: tuple[AlertDeliveryRequest, ...]
+ # Pairs the payload bound left out. They keep their due time and a later tick re-evaluates
+ # them, the way a truncated cohort already behaves.
+ omitted: int = 0
+
+
+# The platform's write, which a source's evaluation workflow starts by name. One definition,
+# because a rename that misses a source breaks it at runtime and nothing else would catch it.
+RECORD_OUTCOMES_ACTIVITY: Final[str] = "alerts_platform_record_outcomes"
+
+
+@frozen
+class PlatformConfigurationSnapshot:
+ """A configuration as a source's own test reads it back, without holding the row."""
+
+ id: UUID
+ next_check_at: datetime | None
+ consecutive_failures: int
+
+
+@frozen
+class PlatformAlertSnapshot:
+ """One instance's runtime state, as a source's own test reads it back."""
+
+ id: UUID
+ grouping_key: str
+ state: str
+ firing_started_at: datetime | None
+ last_notified_at: datetime | None
+ snooze_until: datetime | None
+
+
+@frozen
+class SourceOutcomeInputs:
+ team_id: int
+ cutoff: str
+ outcomes: tuple[PlatformAlertOutcome, ...]
+
+
+@frozen
+class TickPage:
+ page: int
+ run_id: str
+ dispatched: int
+ remaining: int
+ # Sources whose dispatcher failed on this page, and the keys they never took. Those keys keep
+ # their due time, so a later tick rediscovers them; the page reports them rather than ending
+ # the tick.
+ failed_sources: int = 0
+ undispatched: int = 0
+
+
+@frozen
+class OrchestrateInputs:
+ """Empty on the first run. A continued run carries the tick's cutoff, deadlines, demand and pages."""
+
+ cutoff: str | None = None
+ deadline: str | None = None # stop starting pages after this
+ hard_deadline: str | None = None # the execution timeout lands here; no page may run past it
+ page: int = 0
+ demand: dict[SourceKind, list[AlertBatchKey]] | None = None
+ pages: list[TickPage] | None = None
+ omitted: int = 0 # due work discovery left out of the bounded manifest; counted as remaining
+
+
+@frozen
+class OrchestrateResult:
+ pages: list[TickPage]
+ remaining: int
+ deadline_reached: bool
+
+
+class DestinationType(LabeledStrEnum):
+ # The label names the type in a message a person reads.
+ SLACK = "slack", "Slack"
+ DISCORD = "discord", "Discord"
+ WEBHOOK = "webhook", "Webhook"
+ TEAMS = "teams", "Microsoft Teams"
+
+
+class AlertDestinationData(TypedDict):
+ type: DestinationType
+ slack_workspace_id: NotRequired[int]
+ slack_channel_id: NotRequired[str]
+ slack_channel_name: NotRequired[str]
+ webhook_url: NotRequired[str]
+
+
+class AlertDestinationValidationError(Exception):
+ """A destination payload the platform refuses. Callers at an HTTP boundary translate
+ this into their own framework's validation error."""
+
+ def __init__(self, message: str, *, field: str | None = None) -> None:
+ self.message = message
+ self.field = field
+ super().__init__(message)
+
+
+@frozen
+class AlertDestinationAction:
+ url: str
+ label: str
+
+
+@frozen
+class EventKindSpec:
+ """Everything one alert event kind (firing, resolved, ...) says in a notification."""
+
+ event_id: str
+ display_kind: str
+ header: str
+ details: tuple[tuple[str, str], ...]
+ primary_action_url: str
+ primary_action_label: str
+ webhook_body: dict[str, Any]
+ product_label: str = "alert"
+ intro_lines: tuple[str, ...] = ()
+ additional_actions: tuple[AlertDestinationAction, ...] = ()
+
+ def destination_description(self, alert_name: str) -> str:
+ return f'Sends {self.display_kind} notifications for {self.product_label} "{alert_name}".'
+
+
+@frozen
+class AlertDestinationConfig:
+ """One destination, built and ready to persist as a HogFunction."""
+
+ payload: dict[str, Any]
+
+
+@frozen
+class AlertDestinationGroup:
+ """The HogFunctions that together make up one destination a person configured."""
+
+ hog_function_ids: tuple[UUID, ...]
+ data: AlertDestinationData
+ fully_enabled: bool
+
+
+@frozen
+class OwnedAlertDestination:
+ """One alert-owned HogFunction row, as much of it as a consumer may read."""
+
+ hog_function_id: UUID
+ template_id: str | None
+ filters: dict[str, Any] | None
+
+
+@frozen
+class ActiveAlertDestination:
+ id: str
+ name: str
+ destination_type: str | None
+
+
+@frozen
+class AlertDelivery:
+ """Receipt for one destination that accepted a send. `status` is an open set, so a
+ future transport can report an outcome other than "accepted"."""
+
+ channel: str # "email" | "hog_function"
+ target: str # email address or destination name
+ target_id: str | None = None # hog function id
+ template: str | None = None # "slack" | "discord" | "webhook" | "teams"
+ status: str = "accepted"
+ at: str # ISO-8601 timestamp
+
+
+class DestinationResolver(Protocol):
+ """The lookup the product that owns destinations registers for native delivery."""
+
+ def __call__(
+ self, *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]
+ ) -> list[AlertDestinationGroup]: ...
diff --git a/products/alerts_platform/backend/facade/delivery.py b/products/alerts_platform/backend/facade/delivery.py
new file mode 100644
index 000000000000..ecb8169c331d
--- /dev/null
+++ b/products/alerts_platform/backend/facade/delivery.py
@@ -0,0 +1,8 @@
+"""Facade for native delivery: how the product that owns destinations plugs them in."""
+
+from products.alerts_platform.backend.delivery import destinations
+from products.alerts_platform.backend.facade.contracts import DestinationResolver
+
+
+def register_destination_resolver(resolver: DestinationResolver) -> None:
+ destinations.register(resolver)
diff --git a/products/alerts/backend/facade/delivery_slo.py b/products/alerts_platform/backend/facade/delivery_slo.py
similarity index 100%
rename from products/alerts/backend/facade/delivery_slo.py
rename to products/alerts_platform/backend/facade/delivery_slo.py
diff --git a/products/alerts/backend/facade/lifecycle.py b/products/alerts_platform/backend/facade/lifecycle.py
similarity index 99%
rename from products/alerts/backend/facade/lifecycle.py
rename to products/alerts_platform/backend/facade/lifecycle.py
index fb54212416de..b740bbfdd5d5 100644
--- a/products/alerts/backend/facade/lifecycle.py
+++ b/products/alerts_platform/backend/facade/lifecycle.py
@@ -25,7 +25,7 @@ from datetime import datetime, timedelta
from enum import Enum, StrEnum
from typing import Protocol
-from products.alerts.backend.facade.contracts import FiringEpisode
+from products.alerts_platform.backend.facade.contracts import FiringEpisode
MAX_CONSECUTIVE_FAILURES = 5
diff --git a/products/alerts/backend/facade/platform_metrics.py b/products/alerts_platform/backend/facade/platform_metrics.py
similarity index 93%
rename from products/alerts/backend/facade/platform_metrics.py
rename to products/alerts_platform/backend/facade/platform_metrics.py
index 9950453ffc43..569fe71e9cc9 100644
--- a/products/alerts/backend/facade/platform_metrics.py
+++ b/products/alerts_platform/backend/facade/platform_metrics.py
@@ -5,7 +5,7 @@ rows, so what a check cost and what it decided are the platform's numbers to nam
from `facade/temporal.py`, which pulls in the workflow module.
"""
-from products.alerts.backend.temporal.metrics import (
+from products.alerts_platform.backend.temporal.metrics import (
increment_checks,
increment_checks_skipped,
increment_deliveries_deferred,
diff --git a/products/alerts/backend/facade/scheduling.py b/products/alerts_platform/backend/facade/scheduling.py
similarity index 100%
rename from products/alerts/backend/facade/scheduling.py
rename to products/alerts_platform/backend/facade/scheduling.py
diff --git a/products/alerts/backend/facade/temporal.py b/products/alerts_platform/backend/facade/temporal.py
similarity index 68%
rename from products/alerts/backend/facade/temporal.py
rename to products/alerts_platform/backend/facade/temporal.py
index 42cf5045f5ee..c2728d1f4698 100644
--- a/products/alerts/backend/facade/temporal.py
+++ b/products/alerts_platform/backend/facade/temporal.py
@@ -1,10 +1,10 @@
-from products.alerts.backend.temporal.metrics import (
+from products.alerts_platform.backend.temporal.metrics import (
ALERTS_PLATFORM_LATENCY_HISTOGRAM_BUCKETS,
ALERTS_PLATFORM_LATENCY_HISTOGRAM_METRICS,
)
-from products.alerts.backend.temporal.schedule import create_alerts_platform_tick_schedule
-from products.alerts.backend.temporal.telemetry import AlertsPlatformTelemetryInterceptor
-from products.alerts.backend.temporal.workflows import (
+from products.alerts_platform.backend.temporal.schedule import create_alerts_platform_tick_schedule
+from products.alerts_platform.backend.temporal.telemetry import AlertsPlatformTelemetryInterceptor
+from products.alerts_platform.backend.temporal.workflows import (
DELIVERY_ACTIVITIES,
DELIVERY_WORKFLOWS,
EVALUATION_ACTIVITIES,
diff --git a/products/alerts_platform/backend/facade/testing.py b/products/alerts_platform/backend/facade/testing.py
new file mode 100644
index 000000000000..6efa0fd834b6
--- /dev/null
+++ b/products/alerts_platform/backend/facade/testing.py
@@ -0,0 +1,64 @@
+"""Test doors onto the platform's rows, for a source's own tests.
+
+A source's tests set a configuration up and read back what a check decided. Both are rows this
+product owns, so they cross as snapshots and ids rather than as model instances.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from datetime import datetime
+from typing import Any
+from uuid import UUID
+
+from products.alerts_platform.backend.facade.contracts import PlatformAlertSnapshot, PlatformConfigurationSnapshot
+from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration
+
+
+def _configuration_snapshot(row: PlatformAlertConfiguration) -> PlatformConfigurationSnapshot:
+ return PlatformConfigurationSnapshot(
+ id=row.id, next_check_at=row.next_check_at, consecutive_failures=row.consecutive_failures
+ )
+
+
+def create_configuration(**fields: Any) -> PlatformConfigurationSnapshot:
+ """One configuration, as a source's test wants it. Team scoping is the caller's to hold."""
+ configuration = PlatformAlertConfiguration.objects.create(**fields)
+ return _configuration_snapshot(configuration)
+
+
+def configuration(configuration_id: UUID) -> PlatformConfigurationSnapshot:
+ """The configuration as it stands now, so a test can see a schedule the platform advanced.
+
+ Raises rather than returning None: a test that re-reads a configuration it created is
+ asserting about that row, so a missing one is a broken test rather than an outcome.
+ """
+ # nosemgrep: idor-lookup-without-team — fail-closed model; the caller holds the team scope
+ return _configuration_snapshot(PlatformAlertConfiguration.objects.get(id=configuration_id))
+
+
+def set_due_at(configuration_id: UUID, due_at: datetime) -> None:
+ """Move a configuration's due time, so a test can run two checks against one schedule."""
+ # nosemgrep: idor-lookup-without-team — fail-closed model; the caller holds the team scope
+ PlatformAlertConfiguration.objects.filter(id=configuration_id).update(next_check_at=due_at)
+
+
+def count_still_due(configuration_ids: Iterable[UUID], *, at: datetime) -> int:
+ """How many of these configurations a tick would still pick up at `at`."""
+ # nosemgrep: idor-lookup-without-team — fail-closed model; the caller holds the team scope
+ return PlatformAlertConfiguration.objects.filter(id__in=list(configuration_ids), next_check_at__lte=at).count()
+
+
+def alert_for(configuration_id: UUID, *, grouping_key: str = "") -> PlatformAlertSnapshot | None:
+ """The instance row a check wrote, or None when no check has written one."""
+ row = PlatformAlert.objects.filter(configuration_id=configuration_id, grouping_key=grouping_key).first()
+ if row is None:
+ return None
+ return PlatformAlertSnapshot(
+ id=row.id,
+ grouping_key=row.grouping_key,
+ state=row.state,
+ firing_started_at=row.firing_started_at,
+ last_notified_at=row.last_notified_at,
+ snooze_until=row.snooze_until,
+ )
diff --git a/products/alerts_platform/backend/logic/__init__.py b/products/alerts_platform/backend/logic/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/alerts/backend/logic/demand.py b/products/alerts_platform/backend/logic/demand.py
similarity index 88%
rename from products/alerts/backend/logic/demand.py
rename to products/alerts_platform/backend/logic/demand.py
index abf8f94f7714..0c7c51b29b5c 100644
--- a/products/alerts/backend/logic/demand.py
+++ b/products/alerts_platform/backend/logic/demand.py
@@ -1,8 +1,8 @@
import datetime as dt
-from products.alerts.backend.facade.contracts import AlertBatchKey, AlertDemand, SourceKind
-from products.alerts.backend.logic.platform_lifecycle import due_q, slot_of, suppressed
-from products.alerts.backend.models import PlatformAlertConfiguration
+from products.alerts_platform.backend.facade.contracts import AlertBatchKey, AlertDemand, SourceKind
+from products.alerts_platform.backend.logic.platform_lifecycle import due_q, slot_of, suppressed
+from products.alerts_platform.backend.models import PlatformAlertConfiguration
# Keys per source in one manifest. A key is a team id and a minute, so unlike an id list it does not
# grow with a team's alert count, and this bound is about how many distinct chunks one tick starts.
diff --git a/products/alerts/backend/logic/platform_alert_events.py b/products/alerts_platform/backend/logic/platform_alert_events.py
similarity index 97%
rename from products/alerts/backend/logic/platform_alert_events.py
rename to products/alerts_platform/backend/logic/platform_alert_events.py
index de762a4db287..59b1a6ddb436 100644
--- a/products/alerts/backend/logic/platform_alert_events.py
+++ b/products/alerts_platform/backend/logic/platform_alert_events.py
@@ -25,8 +25,12 @@ from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.dataclasses import frozen
-from products.alerts.backend.facade.contracts import AlertEventKind, AnnouncedTransition, EvaluationAnnouncement
-from products.alerts.backend.models.platform_alert_events_sql import PLATFORM_ALERT_EVENTS_TABLE
+from products.alerts_platform.backend.facade.contracts import (
+ AlertEventKind,
+ AnnouncedTransition,
+ EvaluationAnnouncement,
+)
+from products.alerts_platform.backend.models.platform_alert_events_sql import PLATFORM_ALERT_EVENTS_TABLE
logger = structlog.get_logger(__name__)
diff --git a/products/alerts/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.py
similarity index 95%
rename from products/alerts/backend/logic/platform_lifecycle.py
rename to products/alerts_platform/backend/logic/platform_lifecycle.py
index 69a6305ac63b..0d19aa980294 100644
--- a/products/alerts/backend/logic/platform_lifecycle.py
+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py
@@ -10,11 +10,15 @@ from datetime import datetime
from django.db import transaction
from django.db.models import Exists, OuterRef, Q
-from products.alerts.backend.facade.contracts import PlatformAlertCheckInput, PlatformAlertOutcome, PlatformAlertUpsert
-from products.alerts.backend.facade.platform_metrics import increment_history_rows_dropped, safe_record
-from products.alerts.backend.facade.scheduling import advance_next_check_at, compute_shard_offset_seconds
-from products.alerts.backend.logic.platform_alert_events import PlatformAlertEventRow, insert_events
-from products.alerts.backend.models import PlatformAlert, PlatformAlertConfiguration
+from products.alerts_platform.backend.facade.contracts import (
+ PlatformAlertCheckInput,
+ PlatformAlertOutcome,
+ PlatformAlertUpsert,
+)
+from products.alerts_platform.backend.facade.platform_metrics import increment_history_rows_dropped, safe_record
+from products.alerts_platform.backend.facade.scheduling import advance_next_check_at, compute_shard_offset_seconds
+from products.alerts_platform.backend.logic.platform_alert_events import PlatformAlertEventRow, insert_events
+from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration
def due_q(moment: datetime) -> Q:
diff --git a/products/alerts_platform/backend/migrations/0001_initial.py b/products/alerts_platform/backend/migrations/0001_initial.py
new file mode 100644
index 000000000000..502a88384084
--- /dev/null
+++ b/products/alerts_platform/backend/migrations/0001_initial.py
@@ -0,0 +1,237 @@
+# Generated by Django 5.2.17 on 2026-09-30 19:50
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ """The platform's tables move from the `alerts` app to this one. State only.
+
+ The rows and the tables do not move, so `database_operations` stays empty here and in the
+ `alerts` migration that drops these models from that app's state. `db_table` on each model
+ keeps the name the `alerts` app gave it.
+
+ This depends on `alerts.0008` rather than on `alerts.0011_platformalertthread`, which creates
+ the thread table. Nothing here touches the database, so the order does not matter for the
+ table, and a dependency on 0011 would make every rollback of `alerts` below it unapply this
+ app's later migrations, including a concurrent index that cannot run in a transaction.
+ """
+
+ initial = True
+
+ dependencies = [
+ ("posthog", "1390_rename_desktop_canvas_comment_scope"),
+ ("alerts", "0008_platformalert_firing_started_at_and_uuid7_pk"),
+ ]
+
+ database_operations: list = []
+
+ state_operations = [
+ migrations.CreateModel(
+ name="PlatformAlertConfiguration",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ("name", models.CharField(max_length=255)),
+ ("enabled", models.BooleanField(db_default=True, default=True)),
+ (
+ "source_kind",
+ models.CharField(choices=[("logs", "Logs")], max_length=32),
+ ),
+ ("source_config", models.JSONField(default=dict)),
+ ("threshold_count", models.PositiveIntegerField()),
+ ("threshold_operator", models.CharField(max_length=16)),
+ ("window_minutes", models.PositiveIntegerField()),
+ ("check_interval_minutes", models.PositiveIntegerField()),
+ (
+ "evaluation_periods",
+ models.PositiveIntegerField(db_default=1, default=1),
+ ),
+ (
+ "datapoints_to_alarm",
+ models.PositiveIntegerField(db_default=1, default=1),
+ ),
+ (
+ "cooldown_minutes",
+ models.PositiveIntegerField(db_default=0, default=0),
+ ),
+ ("schedule_restriction", models.JSONField(blank=True, null=True)),
+ ("next_check_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "consecutive_failures",
+ models.PositiveIntegerField(db_default=0, default=0),
+ ),
+ (
+ "legacy_configuration_id",
+ models.UUIDField(blank=True, null=True, unique=True),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "alerts_platformalertconfiguration",
+ },
+ ),
+ migrations.CreateModel(
+ name="PlatformAlert",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "grouping_key",
+ models.CharField(db_default="", default="", max_length=255),
+ ),
+ (
+ "state",
+ models.CharField(
+ choices=[
+ ("not_firing", "Not firing"),
+ ("firing", "Firing"),
+ ("errored", "Errored"),
+ ("snoozed", "Snoozed"),
+ ("broken", "Broken"),
+ ],
+ db_default="not_firing",
+ default="not_firing",
+ max_length=32,
+ ),
+ ),
+ ("last_notified_at", models.DateTimeField(blank=True, null=True)),
+ ("snooze_until", models.DateTimeField(blank=True, null=True)),
+ ("firing_started_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ (
+ "configuration",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="alerts",
+ to="alerts_platform.platformalertconfiguration",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "alerts_platformalert",
+ },
+ ),
+ migrations.AddIndex(
+ model_name="platformalertconfiguration",
+ index=models.Index(
+ condition=models.Q(("enabled", True)),
+ fields=["next_check_at", "id"],
+ name="platform_alert_cfg_due_idx",
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="platformalertconfiguration",
+ index=models.Index(
+ fields=["team_id", "enabled", "source_kind", "next_check_at"],
+ name="platform_alert_cfg_batch_idx",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="platformalert",
+ constraint=models.UniqueConstraint(
+ fields=("configuration", "grouping_key"),
+ name="platform_alert_one_per_group",
+ ),
+ ),
+ migrations.CreateModel(
+ name="PlatformAlertThread",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "grouping_key",
+ models.CharField(db_default="", default="", max_length=255),
+ ),
+ ("provider", models.CharField(max_length=32)),
+ ("channel_target", models.CharField(max_length=255)),
+ ("episode_started_at", models.DateTimeField()),
+ ("external_ref", models.JSONField(default=dict)),
+ ("delivered_evaluation_keys", models.JSONField(default=list)),
+ (
+ "pending_evaluation_key",
+ models.CharField(blank=True, max_length=255, null=True),
+ ),
+ ("pending_claimed_at", models.DateTimeField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "configuration",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="threads",
+ to="alerts_platform.platformalertconfiguration",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "alerts_platformalertthread",
+ "constraints": [
+ models.UniqueConstraint(
+ fields=(
+ "configuration",
+ "grouping_key",
+ "provider",
+ "channel_target",
+ "episode_started_at",
+ ),
+ name="platform_alert_thread_one_per_conversation",
+ )
+ ],
+ },
+ ),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(database_operations=database_operations, state_operations=state_operations)
+ ]
diff --git a/products/alerts_platform/backend/migrations/__init__.py b/products/alerts_platform/backend/migrations/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/alerts_platform/backend/migrations/max_migration.txt b/products/alerts_platform/backend/migrations/max_migration.txt
new file mode 100644
index 000000000000..cbab66dde92a
--- /dev/null
+++ b/products/alerts_platform/backend/migrations/max_migration.txt
@@ -0,0 +1 @@
+0001_initial
diff --git a/products/alerts_platform/backend/models/__init__.py b/products/alerts_platform/backend/models/__init__.py
new file mode 100644
index 000000000000..dcd4a997509b
--- /dev/null
+++ b/products/alerts_platform/backend/models/__init__.py
@@ -0,0 +1,7 @@
+from .platform_alert import PlatformAlert, PlatformAlertConfiguration, PlatformAlertThread
+
+__all__ = [
+ "PlatformAlert",
+ "PlatformAlertConfiguration",
+ "PlatformAlertThread",
+]
diff --git a/products/alerts/backend/models/platform_alert.py b/products/alerts_platform/backend/models/platform_alert.py
similarity index 97%
rename from products/alerts/backend/models/platform_alert.py
rename to products/alerts_platform/backend/models/platform_alert.py
index fc9ffd8b4249..8b35770638bf 100644
--- a/products/alerts/backend/models/platform_alert.py
+++ b/products/alerts_platform/backend/models/platform_alert.py
@@ -57,6 +57,8 @@ class PlatformAlertConfiguration(TeamScopedRootMixin, UUIDModel):
legacy_configuration_id = models.UUIDField(null=True, blank=True, unique=True)
class Meta:
+ # Pinned: the name predates this app, and removing this renames a live table.
+ db_table = "alerts_platformalertconfiguration"
indexes = [
# Discovery: enabled rows ordered by due time. Partial, because a disabled
# configuration is never discovered and does not belong in the index.
@@ -101,6 +103,7 @@ class PlatformAlert(TeamScopedRootMixin, UUIDModel):
firing_started_at = models.DateTimeField(null=True, blank=True)
class Meta:
+ db_table = "alerts_platformalert"
constraints = [
models.UniqueConstraint(fields=["configuration", "grouping_key"], name="platform_alert_one_per_group")
]
@@ -145,6 +148,7 @@ class PlatformAlertThread(TeamScopedRootMixin, UUIDModel):
updated_at = models.DateTimeField(auto_now=True)
class Meta:
+ db_table = "alerts_platformalertthread"
constraints = [
models.UniqueConstraint(
fields=["configuration", "grouping_key", "provider", "channel_target", "episode_started_at"],
diff --git a/products/alerts/backend/models/platform_alert_events_sql.py b/products/alerts_platform/backend/models/platform_alert_events_sql.py
similarity index 100%
rename from products/alerts/backend/models/platform_alert_events_sql.py
rename to products/alerts_platform/backend/models/platform_alert_events_sql.py
diff --git a/products/alerts/backend/temporal/metrics.py b/products/alerts_platform/backend/temporal/metrics.py
similarity index 97%
rename from products/alerts/backend/temporal/metrics.py
rename to products/alerts_platform/backend/temporal/metrics.py
index 6505c0fb9690..cc1f81afb1d7 100644
--- a/products/alerts/backend/temporal/metrics.py
+++ b/products/alerts_platform/backend/temporal/metrics.py
@@ -6,6 +6,7 @@ below. Every call site wraps these in `safe_record`: a metric must never fail a
"""
import datetime as dt
+from collections.abc import Callable
from posthog.temporal.common.logger import get_write_only_logger
from posthog.temporal.common.metrics import get_metric_meter
@@ -33,7 +34,7 @@ ALERTS_PLATFORM_LATENCY_HISTOGRAM_BUCKETS = [
]
-def safe_record(fn, *args, **kwargs) -> None:
+def safe_record(fn: Callable[..., object], *args: object, **kwargs: object) -> None:
"""Best-effort metric recording. A batch that decided correctly must not fail on telemetry."""
try:
fn(*args, **kwargs)
diff --git a/products/alerts/backend/temporal/outcomes.py b/products/alerts_platform/backend/temporal/outcomes.py
similarity index 75%
rename from products/alerts/backend/temporal/outcomes.py
rename to products/alerts_platform/backend/temporal/outcomes.py
index 68921cd6847d..bb4fb8ab44c2 100644
--- a/products/alerts/backend/temporal/outcomes.py
+++ b/products/alerts_platform/backend/temporal/outcomes.py
@@ -13,8 +13,8 @@ import datetime as dt
from temporalio import activity
-from products.alerts.backend.facade.contracts import RECORD_OUTCOMES_ACTIVITY, SourceOutcomeInputs
-from products.alerts.backend.temporal.metrics import increment_outcomes_recorded, safe_record
+from products.alerts_platform.backend.facade.contracts import RECORD_OUTCOMES_ACTIVITY, SourceOutcomeInputs
+from products.alerts_platform.backend.temporal.metrics import increment_outcomes_recorded, safe_record
@activity.defn(name=RECORD_OUTCOMES_ACTIVITY)
@@ -22,9 +22,9 @@ async def alerts_platform_record_outcomes_activity(inputs: SourceOutcomeInputs)
"""Records one batch's decisions. Returns how many reached the tables."""
# Imported in the activity body, not at module scope: a Django model import trips Temporal's
# workflow sandbox, and the worker registration that reaches this module runs through one.
- from posthog.sync import database_sync_to_async_pool
+ from posthog.sync import database_sync_to_async_pool # noqa: PLC0415 — the sandbox, see above
- from products.alerts.backend.facade.platform_alerts import record_outcomes
+ from products.alerts_platform.backend.facade.api import record_outcomes # noqa: PLC0415 — same
if not inputs.outcomes:
return 0
diff --git a/products/alerts/backend/temporal/postgres.py b/products/alerts_platform/backend/temporal/postgres.py
similarity index 100%
rename from products/alerts/backend/temporal/postgres.py
rename to products/alerts_platform/backend/temporal/postgres.py
diff --git a/products/alerts/backend/temporal/schedule.py b/products/alerts_platform/backend/temporal/schedule.py
similarity index 91%
rename from products/alerts/backend/temporal/schedule.py
rename to products/alerts_platform/backend/temporal/schedule.py
index edd8a6018753..0c4b6ec3e1a6 100644
--- a/products/alerts/backend/temporal/schedule.py
+++ b/products/alerts_platform/backend/temporal/schedule.py
@@ -30,7 +30,7 @@ async def create_alerts_platform_tick_schedule(client: "Client") -> None:
if await a_schedule_exists(client, SCHEDULE_ID):
description = await client.get_schedule_handle(SCHEDULE_ID).describe()
- # nosemgrep: insight-alert-state-direct-mutation (Temporal schedule state, not an alert)
+ # nosemgrep: insight-alert-state-direct-mutation,platform-alert-state-direct-mutation (Temporal schedule state, not an alert)
schedule.state = description.schedule.state
await a_update_schedule(client, SCHEDULE_ID, schedule)
else:
diff --git a/products/alerts/backend/temporal/sources.py b/products/alerts_platform/backend/temporal/sources.py
similarity index 84%
rename from products/alerts/backend/temporal/sources.py
rename to products/alerts_platform/backend/temporal/sources.py
index 7c22d753aabe..4d4f20aa2e63 100644
--- a/products/alerts/backend/temporal/sources.py
+++ b/products/alerts_platform/backend/temporal/sources.py
@@ -6,7 +6,7 @@ rather than by class. The alerts product imports nothing from a source.
A source absent from this map keeps the noop evaluation path.
"""
-from products.alerts.backend.facade.contracts import SourceKind
+from products.alerts_platform.backend.facade.contracts import SourceKind
SOURCE_EVALUATION_WORKFLOWS: dict[SourceKind, str] = {
SourceKind.LOGS: "logs-alert-evaluate",
diff --git a/products/alerts/backend/temporal/telemetry.py b/products/alerts_platform/backend/temporal/telemetry.py
similarity index 100%
rename from products/alerts/backend/temporal/telemetry.py
rename to products/alerts_platform/backend/temporal/telemetry.py
diff --git a/products/alerts/backend/temporal/workflows.py b/products/alerts_platform/backend/temporal/workflows.py
similarity index 96%
rename from products/alerts/backend/temporal/workflows.py
rename to products/alerts_platform/backend/temporal/workflows.py
index d13808c1692f..1945af859fee 100644
--- a/products/alerts/backend/temporal/workflows.py
+++ b/products/alerts_platform/backend/temporal/workflows.py
@@ -18,9 +18,9 @@ from posthog.dataclasses import frozen
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.logger import get_write_only_logger
-from products.alerts.backend.temporal.metrics import increment_deliveries_previewed, safe_record
-from products.alerts.backend.temporal.outcomes import alerts_platform_record_outcomes_activity
-from products.alerts.backend.temporal.sources import SOURCE_EVALUATION_WORKFLOWS
+from products.alerts_platform.backend.temporal.metrics import increment_deliveries_previewed, safe_record
+from products.alerts_platform.backend.temporal.outcomes import alerts_platform_record_outcomes_activity
+from products.alerts_platform.backend.temporal.sources import SOURCE_EVALUATION_WORKFLOWS
LOGGER = get_write_only_logger(__name__)
@@ -32,8 +32,8 @@ with workflow.unsafe.imports_passed_through():
from posthog.sync import database_sync_to_async_pool
- from products.alerts.backend.delivery.evaluation import deliver_evaluation
- from products.alerts.backend.facade.contracts import (
+ from products.alerts_platform.backend.delivery.evaluation import deliver_evaluation
+ from products.alerts_platform.backend.facade.contracts import (
AlertDeliveryRequest,
AlertDemand,
DemandDiscoveryInputs,
@@ -44,8 +44,8 @@ with workflow.unsafe.imports_passed_through():
SourceEvaluationInputs,
TickPage,
)
- from products.alerts.backend.logic.demand import discover_demand
- from products.alerts.backend.temporal.postgres import check_postgres_connection
+ from products.alerts_platform.backend.logic.demand import discover_demand
+ from products.alerts_platform.backend.temporal.postgres import check_postgres_connection
POSTGRES_PROBE_FAILURE = "AlertsPlatformPostgresProbeFailure"
diff --git a/products/alerts_platform/backend/tests/__init__.py b/products/alerts_platform/backend/tests/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/alerts/backend/tests/conftest.py b/products/alerts_platform/backend/tests/conftest.py
similarity index 100%
rename from products/alerts/backend/tests/conftest.py
rename to products/alerts_platform/backend/tests/conftest.py
diff --git a/products/alerts/backend/test/test_delivery_dispatch.py b/products/alerts_platform/backend/tests/test_delivery_dispatch.py
similarity index 88%
rename from products/alerts/backend/test/test_delivery_dispatch.py
rename to products/alerts_platform/backend/tests/test_delivery_dispatch.py
index 6ea74f53dc49..2e4d4c98840c 100644
--- a/products/alerts/backend/test/test_delivery_dispatch.py
+++ b/products/alerts_platform/backend/tests/test_delivery_dispatch.py
@@ -7,12 +7,12 @@ from unittest.mock import patch
from django.test import SimpleTestCase
from django.utils import timezone
-from products.alerts.backend.delivery.dispatch import deliver
-from products.alerts.backend.delivery.message import AlertMessage
-from products.alerts.backend.delivery.telemetry import record_delivery
-from products.alerts.backend.delivery.thread_store import NullThreadStore, ThreadClaim, ThreadKey
-from products.alerts.backend.delivery.transport import DeliveryError, MessageHandle
-from products.alerts.backend.facade.contracts import (
+from products.alerts_platform.backend.delivery.dispatch import deliver
+from products.alerts_platform.backend.delivery.message import AlertMessage
+from products.alerts_platform.backend.delivery.telemetry import record_delivery
+from products.alerts_platform.backend.delivery.thread_store import NullThreadStore, ThreadClaim, ThreadKey
+from products.alerts_platform.backend.delivery.transport import DeliveryError, MessageHandle
+from products.alerts_platform.backend.facade.contracts import (
AlertDestinationData,
AlertEventKind,
AnnouncedTransition,
@@ -106,7 +106,7 @@ class TestDeliveryDispatch(SimpleTestCase):
def _deliver(
self, transport: FakeTransport, store: Any, announcement: Any = None, evaluation_key: str = "eval-1"
) -> Any:
- with patch("products.alerts.backend.delivery.dispatch.record_delivery") as recorded:
+ with patch("products.alerts_platform.backend.delivery.dispatch.record_delivery") as recorded:
deliver(
transport=transport,
thread_store=store,
@@ -129,7 +129,7 @@ class TestDeliveryDispatch(SimpleTestCase):
def test_a_refused_send_is_counted_rather_than_passed_over(self) -> None:
transport = FakeTransport(error=DeliveryError("nope"))
- with patch("products.alerts.backend.delivery.dispatch.record_delivery") as recorded:
+ with patch("products.alerts_platform.backend.delivery.dispatch.record_delivery") as recorded:
with pytest.raises(DeliveryError):
deliver(
transport=transport,
@@ -191,7 +191,7 @@ class TestDeliveryDispatch(SimpleTestCase):
def test_a_provider_outage_is_counted_as_a_failed_delivery(self) -> None:
transport = FakeTransport(error=ConnectionError("slack unreachable"))
- with patch("products.alerts.backend.delivery.dispatch.record_delivery") as recorded:
+ with patch("products.alerts_platform.backend.delivery.dispatch.record_delivery") as recorded:
with pytest.raises(ConnectionError):
deliver(
transport=transport,
@@ -215,7 +215,7 @@ class TestDeliveryDispatch(SimpleTestCase):
class TestDeliveryTelemetry(SimpleTestCase):
def test_an_outcome_is_keyed_to_alerts_rather_than_to_hog_functions(self) -> None:
- with patch("products.alerts.backend.delivery.telemetry.get_producer") as producer:
+ with patch("products.alerts_platform.backend.delivery.telemetry.get_producer") as producer:
record_delivery(team_id=2, configuration_id="cfg-1", provider="slack", succeeded=True)
payload = producer.return_value.produce.call_args.kwargs["data"]
@@ -224,5 +224,7 @@ class TestDeliveryTelemetry(SimpleTestCase):
assert (payload["metric_kind"], payload["metric_name"]) == ("success", "succeeded")
def test_a_broken_producer_does_not_fail_a_send_that_already_happened(self) -> None:
- with patch("products.alerts.backend.delivery.telemetry.get_producer", side_effect=RuntimeError("down")):
+ with patch(
+ "products.alerts_platform.backend.delivery.telemetry.get_producer", side_effect=RuntimeError("down")
+ ):
record_delivery(team_id=2, configuration_id="cfg-1", provider="slack", succeeded=True)
diff --git a/products/alerts/backend/test/test_delivery_evaluation.py b/products/alerts_platform/backend/tests/test_delivery_evaluation.py
similarity index 89%
rename from products/alerts/backend/test/test_delivery_evaluation.py
rename to products/alerts_platform/backend/tests/test_delivery_evaluation.py
index 1317eac06a95..156b61dfefbe 100644
--- a/products/alerts/backend/test/test_delivery_evaluation.py
+++ b/products/alerts_platform/backend/tests/test_delivery_evaluation.py
@@ -4,10 +4,11 @@ from typing import Any, cast
from posthog.test.base import APIBaseTest
from unittest.mock import patch
-from products.alerts.backend.delivery.evaluation import LIVE_DELIVERY_FLAG, deliver_evaluation
-from products.alerts.backend.delivery.message import AlertMessage
-from products.alerts.backend.delivery.transport import MessageHandle
-from products.alerts.backend.facade.contracts import (
+from products.alerts_platform.backend.delivery.destinations import list_alert_destination_groups
+from products.alerts_platform.backend.delivery.evaluation import LIVE_DELIVERY_FLAG, deliver_evaluation
+from products.alerts_platform.backend.delivery.message import AlertMessage
+from products.alerts_platform.backend.delivery.transport import MessageHandle
+from products.alerts_platform.backend.facade.contracts import (
AlertDeliveryRequest,
AlertDestinationData,
AlertDestinationGroup,
@@ -18,7 +19,7 @@ from products.alerts.backend.facade.contracts import (
SourceKind,
)
-_MODULE = "products.alerts.backend.delivery.evaluation"
+_MODULE = "products.alerts_platform.backend.delivery.evaluation"
FIRING = datetime(2026, 9, 30, 9, tzinfo=UTC)
FIRING_EVENT = "$logs_alert_firing"
@@ -174,3 +175,10 @@ class TestDeliverEvaluation(APIBaseTest):
assert RecordingTransport.sends == []
assert outcome.live is False
+
+ def test_the_destination_owner_registers_its_lookup_at_startup(self) -> None:
+ # Every other case here patches the lookup, so none of them notices a missing registration.
+ assert (
+ list_alert_destination_groups(team_id=self.team.id, alert_id="unknown", allowed_event_ids=[FIRING_EVENT])
+ == []
+ )
diff --git a/products/alerts/backend/test/test_delivery_message.py b/products/alerts_platform/backend/tests/test_delivery_message.py
similarity index 92%
rename from products/alerts/backend/test/test_delivery_message.py
rename to products/alerts_platform/backend/tests/test_delivery_message.py
index 4caeb43c373a..12be6660afdf 100644
--- a/products/alerts/backend/test/test_delivery_message.py
+++ b/products/alerts_platform/backend/tests/test_delivery_message.py
@@ -2,8 +2,12 @@ from typing import Any
import pytest
-from products.alerts.backend.delivery.message import MessageDetail, build_message
-from products.alerts.backend.facade.contracts import AlertEventKind, AnnouncedTransition, EvaluationAnnouncement
+from products.alerts_platform.backend.delivery.message import MessageDetail, build_message
+from products.alerts_platform.backend.facade.contracts import (
+ AlertEventKind,
+ AnnouncedTransition,
+ EvaluationAnnouncement,
+)
CONDITION = {"threshold_count": 100, "threshold_operator": "above", "window_minutes": 5}
diff --git a/products/alerts/backend/test/test_delivery_slack.py b/products/alerts_platform/backend/tests/test_delivery_slack.py
similarity index 88%
rename from products/alerts/backend/test/test_delivery_slack.py
rename to products/alerts_platform/backend/tests/test_delivery_slack.py
index 52e8b076406c..dc79d6d8ee43 100644
--- a/products/alerts/backend/test/test_delivery_slack.py
+++ b/products/alerts_platform/backend/tests/test_delivery_slack.py
@@ -11,10 +11,10 @@ from slack_sdk.errors import SlackApiError
from posthog.models.integration import Integration
from posthog.slack.channels import MAX_HEADER_CHARS, MAX_SECTION_CHARS
-from products.alerts.backend.delivery.message import AlertMessage, MessageDetail
-from products.alerts.backend.delivery.slack import SlackTransport, blocks_for
-from products.alerts.backend.delivery.transport import DeliveryError, MessageHandle
-from products.alerts.backend.facade.contracts import AlertDestinationData
+from products.alerts_platform.backend.delivery.message import AlertMessage, MessageDetail
+from products.alerts_platform.backend.delivery.slack import SlackTransport, blocks_for
+from products.alerts_platform.backend.delivery.transport import DeliveryError, MessageHandle
+from products.alerts_platform.backend.facade.contracts import AlertDestinationData
MESSAGE = AlertMessage(
headline="API errors is firing",
@@ -77,7 +77,7 @@ class TestSlackTransport(APIBaseTest):
)
def _send(self, **overrides: Any) -> Any:
- with patch("products.alerts.backend.delivery.slack.SlackIntegration") as slack_integration:
+ with patch("products.alerts_platform.backend.delivery.slack.SlackIntegration") as slack_integration:
slack_integration.return_value.client.chat_postMessage.return_value = {"ts": "1700000000.1"}
handle = SlackTransport().deliver(
team_id=overrides.pop("team_id", self.team.id),
@@ -104,7 +104,7 @@ class TestSlackTransport(APIBaseTest):
self._send(team_id=self.team.id + 1)
def test_a_refusal_from_slack_becomes_a_delivery_error(self) -> None:
- with patch("products.alerts.backend.delivery.slack.SlackIntegration") as slack_integration:
+ with patch("products.alerts_platform.backend.delivery.slack.SlackIntegration") as slack_integration:
slack_integration.return_value.client.chat_postMessage.side_effect = SlackApiError(
"channel_not_found", {"error": "channel_not_found"}
)
diff --git a/products/alerts/backend/test/test_delivery_slo.py b/products/alerts_platform/backend/tests/test_delivery_slo.py
similarity index 86%
rename from products/alerts/backend/test/test_delivery_slo.py
rename to products/alerts_platform/backend/tests/test_delivery_slo.py
index 1f7ce8e4275f..9c402064a7b9 100644
--- a/products/alerts/backend/test/test_delivery_slo.py
+++ b/products/alerts_platform/backend/tests/test_delivery_slo.py
@@ -2,10 +2,10 @@ from unittest.mock import MagicMock, patch
from posthog.slo.types import SloOperation, SloOutcome
-from products.alerts.backend.facade.delivery_slo import alert_delivery_slo
+from products.alerts_platform.backend.facade.delivery_slo import alert_delivery_slo
-@patch("products.alerts.backend.facade.delivery_slo.get_instance_region", return_value="EU")
+@patch("products.alerts_platform.backend.facade.delivery_slo.get_instance_region", return_value="EU")
@patch("posthog.slo.context.emit_slo_completed")
@patch("posthog.slo.context.emit_slo_started")
def test_alert_delivery_slo_emits_shared_dimensions(
diff --git a/products/alerts/backend/test/test_delivery_thread_store.py b/products/alerts_platform/backend/tests/test_delivery_thread_store.py
similarity index 92%
rename from products/alerts/backend/test/test_delivery_thread_store.py
rename to products/alerts_platform/backend/tests/test_delivery_thread_store.py
index 47dd25a67a43..6d9f68a3a709 100644
--- a/products/alerts/backend/test/test_delivery_thread_store.py
+++ b/products/alerts_platform/backend/tests/test_delivery_thread_store.py
@@ -9,9 +9,14 @@ from parameterized import parameterized
from posthog.models.scoping import team_scope
-from products.alerts.backend.delivery.thread_store import PENDING_CLAIM_TTL, DatabaseThreadStore, ThreadBusy, ThreadKey
-from products.alerts.backend.delivery.transport import MessageHandle
-from products.alerts.backend.models import PlatformAlertConfiguration, PlatformAlertThread
+from products.alerts_platform.backend.delivery.thread_store import (
+ PENDING_CLAIM_TTL,
+ DatabaseThreadStore,
+ ThreadBusy,
+ ThreadKey,
+)
+from products.alerts_platform.backend.delivery.transport import MessageHandle
+from products.alerts_platform.backend.models import PlatformAlertConfiguration, PlatformAlertThread
FIRING = datetime(2026, 9, 30, 9, tzinfo=UTC)
diff --git a/products/alerts/backend/test/test_grid_scheduling.py b/products/alerts_platform/backend/tests/test_grid_scheduling.py
similarity index 99%
rename from products/alerts/backend/test/test_grid_scheduling.py
rename to products/alerts_platform/backend/tests/test_grid_scheduling.py
index 6685cd43e5d8..d9e74486db82 100644
--- a/products/alerts/backend/test/test_grid_scheduling.py
+++ b/products/alerts_platform/backend/tests/test_grid_scheduling.py
@@ -12,7 +12,7 @@ from hypothesis import (
)
from parameterized import parameterized
-from products.alerts.backend.facade.scheduling import (
+from products.alerts_platform.backend.facade.scheduling import (
DEFAULT_SCHEDULE_INTERVAL_SECONDS,
advance_next_check_at,
compute_shard_offset_seconds,
diff --git a/products/alerts/backend/test/test_platform_alert_events.py b/products/alerts_platform/backend/tests/test_platform_alert_events.py
similarity index 93%
rename from products/alerts/backend/test/test_platform_alert_events.py
rename to products/alerts_platform/backend/tests/test_platform_alert_events.py
index 9d57c6082384..6d25bbbe187b 100644
--- a/products/alerts/backend/test/test_platform_alert_events.py
+++ b/products/alerts_platform/backend/tests/test_platform_alert_events.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime
from uuid import uuid4
-from products.alerts.backend.logic.platform_alert_events import PlatformAlertEventRow, _deduplication_token
+from products.alerts_platform.backend.logic.platform_alert_events import PlatformAlertEventRow, _deduplication_token
CONFIGURATION_ID = uuid4()
EVALUATION_KEY = "slot:2026-09-16T10:00:00+00:00|window:2026-09-16T09:59:00+00:00"
diff --git a/products/alerts/backend/test/test_platform_announcement.py b/products/alerts_platform/backend/tests/test_platform_announcement.py
similarity index 95%
rename from products/alerts/backend/test/test_platform_announcement.py
rename to products/alerts_platform/backend/tests/test_platform_announcement.py
index fd140e779872..72908a9fb531 100644
--- a/products/alerts/backend/test/test_platform_announcement.py
+++ b/products/alerts_platform/backend/tests/test_platform_announcement.py
@@ -6,14 +6,14 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from posthog.clickhouse.client import sync_execute
from posthog.models.scoping import team_scope
-from products.alerts.backend.facade.contracts import AlertEventKind
-from products.alerts.backend.logic.platform_alert_events import (
+from products.alerts_platform.backend.facade.contracts import AlertEventKind
+from products.alerts_platform.backend.logic.platform_alert_events import (
_INSERT_SQL,
PlatformAlertEventRow,
announcement,
insert_events,
)
-from products.alerts.backend.models import PlatformAlertConfiguration
+from products.alerts_platform.backend.models import PlatformAlertConfiguration
OCCURRED = datetime(2026, 9, 30, 10, tzinfo=UTC)
FIRING = datetime(2026, 9, 30, 9, tzinfo=UTC)
diff --git a/products/alerts/backend/test/test_platform_lifecycle.py b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
similarity index 95%
rename from products/alerts/backend/test/test_platform_lifecycle.py
rename to products/alerts_platform/backend/tests/test_platform_lifecycle.py
index bc5a41c21819..f8568156da11 100644
--- a/products/alerts/backend/test/test_platform_lifecycle.py
+++ b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
@@ -7,16 +7,16 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from posthog.clickhouse.client import sync_execute
from posthog.models.scoping import team_scope
-from products.alerts.backend.facade.contracts import (
+from products.alerts_platform.backend.facade.api import due_checks, record_outcomes, upsert_configuration
+from products.alerts_platform.backend.facade.contracts import (
AlertEventKind,
FiringEpisode,
PlatformAlertOutcome,
PlatformAlertUpsert,
SourceKind,
)
-from products.alerts.backend.facade.platform_alerts import due_checks, record_outcomes, upsert_configuration
-from products.alerts.backend.models import PlatformAlert, PlatformAlertConfiguration
-from products.alerts.backend.models.platform_alert_events_sql import SHARDED_PLATFORM_ALERT_EVENTS_TABLE
+from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration
+from products.alerts_platform.backend.models.platform_alert_events_sql import SHARDED_PLATFORM_ALERT_EVENTS_TABLE
class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
diff --git a/products/alerts/backend/test/test_scheduling.py b/products/alerts_platform/backend/tests/test_scheduling.py
similarity index 99%
rename from products/alerts/backend/test/test_scheduling.py
rename to products/alerts_platform/backend/tests/test_scheduling.py
index d01c675ebfbd..91d29f9376e4 100644
--- a/products/alerts/backend/test/test_scheduling.py
+++ b/products/alerts_platform/backend/tests/test_scheduling.py
@@ -6,7 +6,7 @@ import pytest
from parameterized import parameterized
-from products.alerts.backend.facade.scheduling import (
+from products.alerts_platform.backend.facade.scheduling import (
BlockedWindow,
CalendarInterval,
alert_check_offset,
diff --git a/products/alerts/backend/test/test_state_machine.py b/products/alerts_platform/backend/tests/test_state_machine.py
similarity index 99%
rename from products/alerts/backend/test/test_state_machine.py
rename to products/alerts_platform/backend/tests/test_state_machine.py
index 01539bd2a789..a489f7ba382d 100644
--- a/products/alerts/backend/test/test_state_machine.py
+++ b/products/alerts_platform/backend/tests/test_state_machine.py
@@ -2,7 +2,7 @@ from datetime import UTC, datetime, timedelta
from parameterized import parameterized
-from products.alerts.backend.facade.lifecycle import (
+from products.alerts_platform.backend.facade.lifecycle import (
LOGS_ALERT_POLICY,
PLATFORM_LOGS_ALERT_POLICY,
AlertCheckOutcome,
diff --git a/products/alerts/backend/tests/test_temporal_dispatch.py b/products/alerts_platform/backend/tests/test_temporal_dispatch.py
similarity index 98%
rename from products/alerts/backend/tests/test_temporal_dispatch.py
rename to products/alerts_platform/backend/tests/test_temporal_dispatch.py
index da136559c12f..1a26e3498c4d 100644
--- a/products/alerts/backend/tests/test_temporal_dispatch.py
+++ b/products/alerts_platform/backend/tests/test_temporal_dispatch.py
@@ -30,7 +30,7 @@ from temporalio.exceptions import ApplicationError
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Replayer, UnsandboxedWorkflowRunner, Worker
-from products.alerts.backend.facade.contracts import (
+from products.alerts_platform.backend.facade.contracts import (
AlertBatchKey,
AlertDemand,
DemandDiscoveryInputs,
@@ -40,14 +40,14 @@ from products.alerts.backend.facade.contracts import (
SourceDispatchReport,
SourceKind,
)
-from products.alerts.backend.facade.temporal import (
+from products.alerts_platform.backend.facade.temporal import (
EVALUATION_ACTIVITIES,
EVALUATION_WORKFLOWS,
SHARED_ORCHESTRATION_WORKFLOWS,
)
-from products.alerts.backend.temporal import postgres, workflows
-from products.alerts.backend.temporal.sources import SOURCE_EVALUATION_WORKFLOWS
-from products.alerts.backend.temporal.workflows import (
+from products.alerts_platform.backend.temporal import postgres, workflows
+from products.alerts_platform.backend.temporal.sources import SOURCE_EVALUATION_WORKFLOWS
+from products.alerts_platform.backend.temporal.workflows import (
AlertsPlatformEvaluateWorkflow,
AlertsPlatformInputs,
AlertsPlatformOrchestrateWorkflow,
diff --git a/products/alerts/backend/tests/test_temporal_postgres.py b/products/alerts_platform/backend/tests/test_temporal_postgres.py
similarity index 97%
rename from products/alerts/backend/tests/test_temporal_postgres.py
rename to products/alerts_platform/backend/tests/test_temporal_postgres.py
index fa821892782e..5f4f14c86577 100644
--- a/products/alerts/backend/tests/test_temporal_postgres.py
+++ b/products/alerts_platform/backend/tests/test_temporal_postgres.py
@@ -17,8 +17,11 @@ from temporalio.converter import DefaultFailureConverter, DefaultPayloadConverte
from temporalio.exceptions import ApplicationError, CancelledError
from temporalio.testing import ActivityEnvironment
-from products.alerts.backend.temporal import postgres
-from products.alerts.backend.temporal.workflows import POSTGRES_PROBE_FAILURE, alerts_platform_probe_postgres_activity
+from products.alerts_platform.backend.temporal import postgres
+from products.alerts_platform.backend.temporal.workflows import (
+ POSTGRES_PROBE_FAILURE,
+ alerts_platform_probe_postgres_activity,
+)
if TYPE_CHECKING:
from pytest_django.fixtures import Settings
diff --git a/products/alerts/backend/tests/test_temporal_schedule.py b/products/alerts_platform/backend/tests/test_temporal_schedule.py
similarity index 93%
rename from products/alerts/backend/tests/test_temporal_schedule.py
rename to products/alerts_platform/backend/tests/test_temporal_schedule.py
index 6f978ace5c14..103461ea16bc 100644
--- a/products/alerts/backend/tests/test_temporal_schedule.py
+++ b/products/alerts_platform/backend/tests/test_temporal_schedule.py
@@ -7,9 +7,9 @@ from django.test import override_settings
from temporalio.client import Client, ScheduleActionStartWorkflow, ScheduleOverlapPolicy, ScheduleState
-from products.alerts.backend.temporal.schedule import SCHEDULE_ID, create_alerts_platform_tick_schedule
+from products.alerts_platform.backend.temporal.schedule import SCHEDULE_ID, create_alerts_platform_tick_schedule
-MODULE = "products.alerts.backend.temporal.schedule"
+MODULE = "products.alerts_platform.backend.temporal.schedule"
@pytest.mark.asyncio
diff --git a/products/alerts/backend/tests/test_temporal_telemetry.py b/products/alerts_platform/backend/tests/test_temporal_telemetry.py
similarity index 98%
rename from products/alerts/backend/tests/test_temporal_telemetry.py
rename to products/alerts_platform/backend/tests/test_temporal_telemetry.py
index b8e8f75294cb..1d56e25ec085 100644
--- a/products/alerts/backend/tests/test_temporal_telemetry.py
+++ b/products/alerts_platform/backend/tests/test_temporal_telemetry.py
@@ -19,8 +19,8 @@ from temporalio.worker import ActivityInboundInterceptor, ExecuteActivityInput
from posthog.temporal.common.interceptor import is_task_queue_supported
from posthog.temporal.common.worker import ALL_INTERCEPTOR_CLASSES
-from products.alerts.backend.facade.temporal import AlertsPlatformTelemetryInterceptor
-from products.alerts.backend.temporal import telemetry
+from products.alerts_platform.backend.facade.temporal import AlertsPlatformTelemetryInterceptor
+from products.alerts_platform.backend.temporal import telemetry
@pytest.mark.parametrize(
diff --git a/products/alerts/backend/tests/test_temporal_workflows.py b/products/alerts_platform/backend/tests/test_temporal_workflows.py
similarity index 95%
rename from products/alerts/backend/tests/test_temporal_workflows.py
rename to products/alerts_platform/backend/tests/test_temporal_workflows.py
index f03b8635686b..75344fdc70d0 100644
--- a/products/alerts/backend/tests/test_temporal_workflows.py
+++ b/products/alerts_platform/backend/tests/test_temporal_workflows.py
@@ -35,7 +35,7 @@ from temporalio.worker import Replayer, UnsandboxedWorkflowRunner, Worker
from posthog.models.scoping import team_scope
-from products.alerts.backend.facade.contracts import (
+from products.alerts_platform.backend.facade.contracts import (
AlertBatchKey,
AlertDemand,
DemandDiscoveryInputs,
@@ -43,7 +43,7 @@ from products.alerts.backend.facade.contracts import (
OrchestrateResult,
SourceKind,
)
-from products.alerts.backend.facade.temporal import (
+from products.alerts_platform.backend.facade.temporal import (
DELIVERY_ACTIVITIES,
DELIVERY_WORKFLOWS,
EVALUATION_ACTIVITIES,
@@ -52,10 +52,10 @@ from products.alerts.backend.facade.temporal import (
SHARED_ORCHESTRATION_WORKFLOWS,
AlertsPlatformTelemetryInterceptor,
)
-from products.alerts.backend.logic import demand
-from products.alerts.backend.models import PlatformAlert, PlatformAlertConfiguration
-from products.alerts.backend.temporal import postgres
-from products.alerts.backend.temporal.workflows import (
+from products.alerts_platform.backend.logic import demand
+from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration
+from products.alerts_platform.backend.temporal import postgres
+from products.alerts_platform.backend.temporal.workflows import (
AlertsPlatformEvaluateWorkflow,
AlertsPlatformInputs,
AlertsPlatformOrchestrateWorkflow,
@@ -563,9 +563,12 @@ async def test_discovery_uses_scheduled_cutoff_or_manual_start(scheduled: bool)
def test_the_dispatcher_is_registered_on_the_fleet_the_tick_starts_it_on() -> None:
- from posthog.management.commands.start_temporal_worker import WORKFLOWS_DICT
+ # The registry imports every product's workflows, so it stays off this module's import path.
+ from posthog.management.commands.start_temporal_worker import WORKFLOWS_DICT # noqa: PLC0415
- from products.alerts.backend.temporal.workflows import AlertsPlatformSourceDispatchWorkflow
+ from products.alerts_platform.backend.temporal.workflows import ( # noqa: PLC0415 — read after the registry
+ AlertsPlatformSourceDispatchWorkflow,
+ )
# The tick awaits its dispatchers. One registered on a fleet the tick does not dispatch to
# leaves every page queued until it times out, and fails the tick with it.
@@ -574,11 +577,14 @@ def test_the_dispatcher_is_registered_on_the_fleet_the_tick_starts_it_on() -> No
def test_every_source_evaluation_binding_names_a_registered_workflow() -> None:
- import temporalio.workflow
+ import temporalio.workflow # noqa: PLC0415 — read after the registry
- from posthog.management.commands.start_temporal_worker import WORKFLOWS_DICT
+ # The registry imports every product's workflows, so it stays off this module's import path.
+ from posthog.management.commands.start_temporal_worker import WORKFLOWS_DICT # noqa: PLC0415
- from products.alerts.backend.temporal.sources import SOURCE_EVALUATION_WORKFLOWS
+ from products.alerts_platform.backend.temporal.sources import ( # noqa: PLC0415 — read after the registry
+ SOURCE_EVALUATION_WORKFLOWS,
+ )
definitions = (
temporalio.workflow._Definition.from_class(registered_workflow)
diff --git a/products/alerts_platform/manifest.tsx b/products/alerts_platform/manifest.tsx
new file mode 100644
index 000000000000..8181765f8d48
--- /dev/null
+++ b/products/alerts_platform/manifest.tsx
@@ -0,0 +1,12 @@
+import { ProductManifest } from '../../frontend/src/types'
+
+export const manifest: ProductManifest = {
+ name: 'AlertsPlatform',
+ scenes: {},
+ routes: {},
+ redirects: {},
+ urls: {},
+ fileSystemTypes: {},
+ treeItemsNew: [],
+ treeItemsProducts: [],
+}
diff --git a/products/alerts_platform/package.json b/products/alerts_platform/package.json
new file mode 100644
index 000000000000..5944d8f689ed
--- /dev/null
+++ b/products/alerts_platform/package.json
@@ -0,0 +1,7 @@
+{
+ "name": "@posthog/products-alerts-platform",
+ "scripts": {
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",
+ "backend:contract-check": "echo 'Contract files unchanged'"
+ }
+}
diff --git a/products/alerts_platform/product.yaml b/products/alerts_platform/product.yaml
new file mode 100644
index 000000000000..f28f9fceb033
--- /dev/null
+++ b/products/alerts_platform/product.yaml
@@ -0,0 +1,3 @@
+name: Alerts platform
+owners:
+ - team-apm
diff --git a/products/alerts_platform/tsconfig.json b/products/alerts_platform/tsconfig.json
new file mode 100644
index 000000000000..fe425d6fcba8
--- /dev/null
+++ b/products/alerts_platform/tsconfig.json
@@ -0,0 +1,6 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "composite": true
+ }
+}
diff --git a/products/alerts_platform/turbo.json b/products/alerts_platform/turbo.json
new file mode 100644
index 000000000000..2ed03ebce7eb
--- /dev/null
+++ b/products/alerts_platform/turbo.json
@@ -0,0 +1,17 @@
+{
+ "extends": ["//"],
+ "tasks": {
+ "backend:contract-check": {
+ "inputs": [
+ "backend/facade/**",
+ "backend/presentation/**",
+ "backend/routes.py",
+ "backend/models/**",
+ "backend/temporal/**",
+ "backend/migrations/**"
+ ],
+ "outputs": [],
+ "cache": true
+ }
+ }
+}
diff --git a/products/billing_alerts/backend/alert_destinations.py b/products/billing_alerts/backend/alert_destinations.py
index ef08595d076e..cf86c5f32928 100644
--- a/products/billing_alerts/backend/alert_destinations.py
+++ b/products/billing_alerts/backend/alert_destinations.py
@@ -2,8 +2,8 @@ from __future__ import annotations
from typing import Final, Literal
-from products.alerts.backend.facade.contracts import DestinationType, EventKindSpec
from products.alerts.backend.facade.destinations import destination_template_id, list_owned_alert_destinations
+from products.alerts_platform.backend.facade.contracts import DestinationType, EventKindSpec
EventKind = Literal["firing", "resolved", "errored", "broken"]
diff --git a/products/billing_alerts/backend/facade/api.py b/products/billing_alerts/backend/facade/api.py
index 2979837d0edb..7e7415b55c90 100644
--- a/products/billing_alerts/backend/facade/api.py
+++ b/products/billing_alerts/backend/facade/api.py
@@ -14,7 +14,6 @@ from rest_framework.exceptions import ValidationError as DRFValidationError
from posthog.models.integration import Integration
from posthog.models.team.team import Team
-from products.alerts.backend.facade.contracts import AlertDestinationData, DestinationType
from products.alerts.backend.facade.destinations import (
build_alert_destination_config,
create_alert_destination_hog_functions,
@@ -23,6 +22,7 @@ from products.alerts.backend.facade.destinations import (
soft_delete_all_alert_destinations,
validate_destination_data,
)
+from products.alerts_platform.backend.facade.contracts import AlertDestinationData, DestinationType
from ..alert_destinations import (
BILLING_ALERT_EVENT_IDS,
diff --git a/products/billing_alerts/backend/logic/state_machine.py b/products/billing_alerts/backend/logic/state_machine.py
index 47f9993d0368..ebfbccedef91 100644
--- a/products/billing_alerts/backend/logic/state_machine.py
+++ b/products/billing_alerts/backend/logic/state_machine.py
@@ -12,7 +12,7 @@ import structlog
from posthog.exceptions_capture import capture_exception
-from products.alerts.backend.facade.lifecycle import (
+from products.alerts_platform.backend.facade.lifecycle import (
BILLING_ALERT_POLICY,
MAX_CONSECUTIVE_FAILURES,
AlertCheckOutcome,
@@ -29,7 +29,7 @@ from products.alerts.backend.facade.lifecycle import (
evaluate_alert_check as shared_evaluate_alert_check,
evaluate_alert_failure as shared_evaluate_alert_failure,
)
-from products.alerts.backend.facade.scheduling import compute_shard_offset_seconds
+from products.alerts_platform.backend.facade.scheduling import compute_shard_offset_seconds
from products.billing_alerts.backend.logic.evaluator import (
BillingAlertEvaluation,
evaluate_billing_alert,
diff --git a/products/billing_alerts/backend/presentation/serializers.py b/products/billing_alerts/backend/presentation/serializers.py
index 198fc914a3f0..94197380268f 100644
--- a/products/billing_alerts/backend/presentation/serializers.py
+++ b/products/billing_alerts/backend/presentation/serializers.py
@@ -14,12 +14,12 @@ from rest_framework.exceptions import ValidationError
from posthog.exceptions import as_drf_validation_error
from posthog.security.url_validation import is_microsoft_teams_webhook_url
-from products.alerts.backend.facade.contracts import (
+from products.alerts.backend.facade.destinations import validate_destination_data
+from products.alerts_platform.backend.facade.contracts import (
AlertDestinationData,
AlertDestinationValidationError,
DestinationType,
)
-from products.alerts.backend.facade.destinations import validate_destination_data
from products.billing_alerts.backend.facade import api as billing_alerts_api
from products.billing_alerts.backend.facade.api import (
BillingAlertConfiguration,
diff --git a/products/billing_alerts/backend/presentation/views.py b/products/billing_alerts/backend/presentation/views.py
index 8278a03b20f0..483fa2414670 100644
--- a/products/billing_alerts/backend/presentation/views.py
+++ b/products/billing_alerts/backend/presentation/views.py
@@ -18,7 +18,7 @@ from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.permissions import OrganizationAdminReadPermissions, PostHogFeatureFlagPermission
-from products.alerts.backend.facade.contracts import AlertDestinationValidationError
+from products.alerts_platform.backend.facade.contracts import AlertDestinationValidationError
from products.billing_alerts.backend.facade import api as billing_alerts_api
from products.billing_alerts.backend.facade.api import BillingAlertConfiguration
from products.billing_alerts.backend.presentation.serializers import (
diff --git a/products/billing_alerts/backend/test/test_state_machine.py b/products/billing_alerts/backend/test/test_state_machine.py
index c713b6cf3587..2b8a7641bb8f 100644
--- a/products/billing_alerts/backend/test/test_state_machine.py
+++ b/products/billing_alerts/backend/test/test_state_machine.py
@@ -2,7 +2,7 @@ from datetime import UTC, date, datetime, timedelta
from decimal import Decimal
from uuid import UUID
-from products.alerts.backend.facade.lifecycle import AlertSnapshot, AlertState, NotificationAction
+from products.alerts_platform.backend.facade.lifecycle import AlertSnapshot, AlertState, NotificationAction
from products.billing_alerts.backend.logic.evaluator import BillingAlertEvaluation
from products.billing_alerts.backend.logic.state_machine import (
apply_outcome,
diff --git a/products/logs/backend/alert_destinations.py b/products/logs/backend/alert_destinations.py
index 4b0210d5dcde..43ea3231f695 100644
--- a/products/logs/backend/alert_destinations.py
+++ b/products/logs/backend/alert_destinations.py
@@ -4,7 +4,7 @@ from __future__ import annotations
from typing import Literal
-from products.alerts.backend.facade.contracts import DestinationType, EventKindSpec
+from products.alerts_platform.backend.facade.contracts import DestinationType, EventKindSpec
EventKind = Literal["firing", "resolved", "broken", "errored"]
LOGS_DESTINATION_TYPES = (DestinationType.SLACK, DestinationType.WEBHOOK, DestinationType.TEAMS)
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.py
index 93b1defdee37..726eae5e06fc 100644
--- a/products/logs/backend/alert_source_cycle.py
+++ b/products/logs/backend/alert_source_cycle.py
@@ -26,7 +26,8 @@ import structlog
from posthog.dataclasses import frozen
from posthog.models import Team
-from products.alerts.backend.facade.contracts import (
+from products.alerts_platform.backend.facade.api import due_checks, slot_of
+from products.alerts_platform.backend.facade.contracts import (
AlertDeliveryRequest,
AlertEventKind,
MuteReason,
@@ -36,7 +37,7 @@ from products.alerts.backend.facade.contracts import (
SourceBatchEvaluation,
SourceKind,
)
-from products.alerts.backend.facade.lifecycle import (
+from products.alerts_platform.backend.facade.lifecycle import (
PLATFORM_LOGS_ALERT_POLICY,
AlertCheckOutcome,
AlertSnapshot,
@@ -49,8 +50,7 @@ from products.alerts.backend.facade.lifecycle import (
decide_firing_episode,
evaluate_alert_check,
)
-from products.alerts.backend.facade.platform_alerts import due_checks, slot_of
-from products.alerts.backend.facade.platform_metrics import (
+from products.alerts_platform.backend.facade.platform_metrics import (
increment_checks,
increment_checks_skipped,
increment_deliveries_deferred,
@@ -60,7 +60,7 @@ from products.alerts.backend.facade.platform_metrics import (
record_scheduler_lag,
safe_record,
)
-from products.alerts.backend.facade.scheduling import is_utc_datetime_blocked, parse_blocked_windows_tuples
+from products.alerts_platform.backend.facade.scheduling import is_utc_datetime_blocked, parse_blocked_windows_tuples
from products.logs.backend.alert_check_query import (
BatchedAlertCheckQuery,
BucketedCount,
diff --git a/products/logs/backend/alert_state_machine.py b/products/logs/backend/alert_state_machine.py
index 3859e88aadff..178224a8cbc6 100644
--- a/products/logs/backend/alert_state_machine.py
+++ b/products/logs/backend/alert_state_machine.py
@@ -20,7 +20,7 @@ from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import TYPE_CHECKING
-from products.alerts.backend.facade.lifecycle import (
+from products.alerts_platform.backend.facade.lifecycle import (
LOGS_ALERT_POLICY,
MAX_CONSECUTIVE_FAILURES,
AlertCheckOutcome,
diff --git a/products/logs/backend/alert_utils.py b/products/logs/backend/alert_utils.py
index 2feb70a2c1c9..d92bc1b41018 100644
--- a/products/logs/backend/alert_utils.py
+++ b/products/logs/backend/alert_utils.py
@@ -8,7 +8,7 @@ from django.db.models import Q
import structlog
-from products.alerts.backend.facade.scheduling import (
+from products.alerts_platform.backend.facade.scheduling import (
advance_next_check_at,
compute_shard_offset_seconds as shared_compute_shard_offset_seconds,
parse_blocked_windows_tuples,
diff --git a/products/logs/backend/platform_alert_backfill.py b/products/logs/backend/platform_alert_backfill.py
index a2e0fcbea136..06c2afad3a50 100644
--- a/products/logs/backend/platform_alert_backfill.py
+++ b/products/logs/backend/platform_alert_backfill.py
@@ -11,8 +11,8 @@ import structlog
from posthog.dataclasses import frozen
-from products.alerts.backend.facade.contracts import PlatformAlertUpsert, SourceKind
-from products.alerts.backend.facade.platform_alerts import upsert_configuration
+from products.alerts_platform.backend.facade.api import upsert_configuration
+from products.alerts_platform.backend.facade.contracts import PlatformAlertUpsert, SourceKind
from products.logs.backend.models import LogsAlertConfiguration
logger = structlog.get_logger(__name__)
diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.py
index 60fbbee475eb..19543cc16305 100644
--- a/products/logs/backend/presentation/views/alerts_api.py
+++ b/products/logs/backend/presentation/views/alerts_api.py
@@ -29,11 +29,6 @@ from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.utils import relative_date_parse
-from products.alerts.backend.facade.contracts import (
- AlertDestinationData,
- AlertDestinationValidationError,
- DestinationType,
-)
from products.alerts.backend.facade.destinations import (
build_alert_destination_config,
configured_destination_template_ids,
@@ -45,8 +40,13 @@ from products.alerts.backend.facade.destinations import (
soft_delete_all_alert_destinations,
validate_destination_data,
)
-from products.alerts.backend.facade.scheduling import validate_and_normalize_schedule_restriction
from products.alerts.backend.presentation.views.schedule_restriction import AlertScheduleRestriction
+from products.alerts_platform.backend.facade.contracts import (
+ AlertDestinationData,
+ AlertDestinationValidationError,
+ DestinationType,
+)
+from products.alerts_platform.backend.facade.scheduling import validate_and_normalize_schedule_restriction
from products.logs.backend.alert_check_query import AlertCheckQuery, BucketedCount
from products.logs.backend.alert_destinations import (
EVENT_KIND_CONFIG,
diff --git a/products/logs/backend/temporal/activities.py b/products/logs/backend/temporal/activities.py
index c71fd66ae7dc..e0571d964329 100644
--- a/products/logs/backend/temporal/activities.py
+++ b/products/logs/backend/temporal/activities.py
@@ -27,12 +27,12 @@ from posthog.slo.context import SloHandle, SloSpec, slo_operation
from posthog.slo.types import SloArea, SloOperation
from posthog.sync import database_sync_to_async_pool
-from products.alerts.backend.facade.delivery_slo import alert_delivery_slo
from products.alerts.backend.facade.destinations import (
alert_internal_event_delivered,
flush_alert_internal_events,
produce_alert_internal_event,
)
+from products.alerts_platform.backend.facade.delivery_slo import alert_delivery_slo
from products.logs.backend.alert_check_query import (
AlertCheckQuery,
BatchedAlertCheckQuery,
diff --git a/products/logs/backend/temporal/alert_evaluate.py b/products/logs/backend/temporal/alert_evaluate.py
index 907ae05e6ae0..c8e8af257b8f 100644
--- a/products/logs/backend/temporal/alert_evaluate.py
+++ b/products/logs/backend/temporal/alert_evaluate.py
@@ -18,7 +18,7 @@ with workflow.unsafe.imports_passed_through():
from posthog.temporal.common.utils import close_db_connections
- from products.alerts.backend.facade.contracts import (
+ from products.alerts_platform.backend.facade.contracts import (
RECORD_OUTCOMES_ACTIVITY,
SourceBatchEvaluation,
SourceEvaluationInputs,
diff --git a/products/logs/backend/test/test_alert_destinations.py b/products/logs/backend/test/test_alert_destinations.py
index 984a41f1f976..17e4df450d77 100644
--- a/products/logs/backend/test/test_alert_destinations.py
+++ b/products/logs/backend/test/test_alert_destinations.py
@@ -4,12 +4,12 @@ from django.test import SimpleTestCase
from parameterized import parameterized
-from products.alerts.backend.facade.contracts import (
+from products.alerts.backend.facade.destinations import build_alert_destination_config, validate_destination_data
+from products.alerts_platform.backend.facade.contracts import (
AlertDestinationData,
AlertDestinationValidationError,
DestinationType,
)
-from products.alerts.backend.facade.destinations import build_alert_destination_config, validate_destination_data
from products.logs.backend.alert_destinations import (
EVENT_KIND_CONFIG,
EVENT_KINDS,
diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.py
index ccc3d860da99..2fbc6909e044 100644
--- a/products/logs/backend/test/test_alert_evaluate.py
+++ b/products/logs/backend/test/test_alert_evaluate.py
@@ -1,8 +1,9 @@
from datetime import UTC, datetime, timedelta
+from typing import Any
import pytest
from posthog.test.base import APIBaseTest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase
@@ -12,10 +13,16 @@ from posthog.hogql.errors import ExposedHogQLError
from posthog.models.scoping import team_scope
-from products.alerts.backend.facade.contracts import AlertEventKind, SourceBatchEvaluation, SourceKind
-from products.alerts.backend.facade.platform_alerts import due_checks, record_outcomes, slot_of
-from products.alerts.backend.facade.temporal import SOURCE_EVALUATION_TIMEOUT
-from products.alerts.backend.models import PlatformAlert, PlatformAlertConfiguration
+from products.alerts_platform.backend.facade import testing as platform_testing
+from products.alerts_platform.backend.facade.api import due_checks, record_outcomes, slot_of
+from products.alerts_platform.backend.facade.contracts import (
+ AlertEventKind,
+ PlatformConfigurationSnapshot,
+ SourceBatchEvaluation,
+ SourceKind,
+)
+from products.alerts_platform.backend.facade.lifecycle import AlertState
+from products.alerts_platform.backend.facade.temporal import SOURCE_EVALUATION_TIMEOUT
from products.logs.backend.alert_check_query import BatchedBucketedResult, BucketedCount
from products.logs.backend.alert_source_cycle import BATCH_QUERY_BUDGET_SECONDS, MAX_QUERY_SECONDS, evaluate_logs_batch
from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent
@@ -34,11 +41,11 @@ class TestLogsAlertEvaluation(APIBaseTest):
super().setUp()
self.cutoff = datetime(2026, 9, 16, 10, tzinfo=UTC)
- def _configuration(self, **overrides) -> PlatformAlertConfiguration:
- defaults = {
- "team": self.team,
+ def _configuration(self, **overrides: Any) -> PlatformConfigurationSnapshot:
+ defaults: dict[str, Any] = {
+ "team_id": self.team.id,
"name": "API errors",
- "source_kind": PlatformAlertConfiguration.SourceKind.LOGS,
+ "source_kind": SourceKind.LOGS,
"source_config": {},
"threshold_count": 10,
"threshold_operator": "above",
@@ -48,14 +55,14 @@ class TestLogsAlertEvaluation(APIBaseTest):
}
defaults.update(overrides)
with team_scope(self.team.id):
- return PlatformAlertConfiguration.objects.create(**defaults)
+ return platform_testing.create_configuration(**defaults)
def _run(
self,
- *configurations: PlatformAlertConfiguration,
+ *configurations: PlatformConfigurationSnapshot,
query_error: Exception | None = None,
now: datetime | None = None,
- ):
+ ) -> tuple[SourceBatchEvaluation, MagicMock]:
now = now or self.cutoff
breaching = {str(c.id): [BucketedCount(timestamp=now, count=500)] for c in configurations}
with (
@@ -90,9 +97,10 @@ class TestLogsAlertEvaluation(APIBaseTest):
assert [(o.kind, o.value) for o in evaluation.outcomes] == [(AlertEventKind.FIRING, 500.0)]
with team_scope(self.team.id):
- alert = PlatformAlert.objects.get(configuration=configuration, grouping_key="")
- configuration.refresh_from_db()
- assert alert.state == PlatformAlert.State.FIRING
+ alert = platform_testing.alert_for(configuration.id)
+ assert alert is not None
+ configuration = platform_testing.configuration(configuration.id)
+ assert alert.state == AlertState.FIRING
assert alert.last_notified_at is not None
# The schedule advanced, so the next tick does not rediscover this configuration.
assert configuration.next_check_at is not None
@@ -112,8 +120,8 @@ class TestLogsAlertEvaluation(APIBaseTest):
assert evaluation.deliveries
with team_scope(self.team.id):
- configuration.refresh_from_db()
- assert not PlatformAlert.objects.filter(configuration=configuration).exists()
+ configuration = platform_testing.configuration(configuration.id)
+ assert platform_testing.alert_for(configuration.id) is None
assert configuration.next_check_at == self.cutoff - timedelta(minutes=1)
def test_a_delivery_the_batch_cannot_carry_leaves_its_alert_due(self) -> None:
@@ -128,9 +136,7 @@ class TestLogsAlertEvaluation(APIBaseTest):
assert len(evaluation.deliveries) == 1
assert evaluation.omitted == 1
with team_scope(self.team.id):
- still_due = PlatformAlertConfiguration.objects.filter(
- id__in=[c.id for c in configurations], next_check_at__lte=self.cutoff
- ).count()
+ still_due = platform_testing.count_still_due([c.id for c in configurations], at=self.cutoff)
assert still_due == 1
def test_two_scheduled_checks_clamped_to_one_window_keep_distinct_keys(self) -> None:
@@ -145,7 +151,7 @@ class TestLogsAlertEvaluation(APIBaseTest):
def run_at(next_check_at: datetime) -> str:
with team_scope(self.team.id):
- PlatformAlertConfiguration.objects.filter(id=configuration.id).update(next_check_at=next_check_at)
+ platform_testing.set_due_at(configuration.id, next_check_at)
with (
patch(f"{_MODULE}.fetch_live_logs_checkpoint", return_value=frozen_checkpoint),
patch(f"{_MODULE}.BatchedAlertCheckQuery") as query,
@@ -174,10 +180,11 @@ class TestLogsAlertEvaluation(APIBaseTest):
query.assert_called_once()
assert evaluation.deliveries == ()
with team_scope(self.team.id):
- alert = PlatformAlert.objects.get(configuration=configuration, grouping_key="")
- configuration.refresh_from_db()
+ alert = platform_testing.alert_for(configuration.id)
+ assert alert is not None
+ configuration = platform_testing.configuration(configuration.id)
# An incident wholly inside the window must still leave a trace, and must not move the cooldown.
- assert alert.state == PlatformAlert.State.FIRING
+ assert alert.state == AlertState.FIRING
assert alert.last_notified_at is None
assert alert.firing_started_at == self.cutoff
# Parked at the end of the window would leave the alert unevaluated until noon.
@@ -198,8 +205,9 @@ class TestLogsAlertEvaluation(APIBaseTest):
query.assert_not_called()
with team_scope(self.team.id):
- alert = PlatformAlert.objects.get(configuration=configuration, grouping_key="")
- assert alert.state == PlatformAlert.State.BROKEN
+ alert = platform_testing.alert_for(configuration.id)
+ assert alert is not None
+ assert alert.state == AlertState.BROKEN
assert due_checks(self.team.id, SourceKind.LOGS.value, self._slot(), self.cutoff + timedelta(hours=1)) == ()
@parameterized.expand(
@@ -218,8 +226,9 @@ class TestLogsAlertEvaluation(APIBaseTest):
assert [o.consecutive_failures for o in evaluation.outcomes] == [expected_failures]
with team_scope(self.team.id):
- alert = PlatformAlert.objects.get(configuration=configuration, grouping_key="")
- configuration.refresh_from_db()
+ alert = platform_testing.alert_for(configuration.id)
+ assert alert is not None
+ configuration = platform_testing.configuration(configuration.id)
assert alert.state == expected_state
assert configuration.next_check_at is not None
assert configuration.next_check_at > self.cutoff
@@ -232,8 +241,8 @@ class TestLogsAlertEvaluation(APIBaseTest):
self._run(configuration, query_error=ExposedHogQLError("unknown field"))
with team_scope(self.team.id):
- configuration.refresh_from_db()
- assert not PlatformAlert.objects.filter(configuration=configuration).exists()
+ configuration = platform_testing.configuration(configuration.id)
+ assert platform_testing.alert_for(configuration.id) is None
assert configuration.next_check_at == self.cutoff - timedelta(minutes=1)
def test_the_logs_product_rows_are_never_written(self) -> None:
diff --git a/products/logs/backend/test/test_logs_alerting_activities.py b/products/logs/backend/test/test_logs_alerting_activities.py
index 5a36b24b50c8..a2134b3b88f6 100644
--- a/products/logs/backend/test/test_logs_alerting_activities.py
+++ b/products/logs/backend/test/test_logs_alerting_activities.py
@@ -2317,7 +2317,7 @@ class TestEvaluateCohortBatchActivity(NonAtomicBaseTest):
assert result.alerts_checked == 1
@time_machine.travel("2025-01-01T00:01:00Z", tick=False)
- @patch("products.alerts.backend.facade.delivery_slo.get_instance_region", return_value="US")
+ @patch("products.alerts_platform.backend.facade.delivery_slo.get_instance_region", return_value="US")
@patch("posthog.slo.context.emit_slo_completed")
@patch("posthog.slo.context.emit_slo_started")
@patch("products.logs.backend.temporal.activities.flush_alert_internal_events")
diff --git a/products/replay_vision/backend/alert_destinations.py b/products/replay_vision/backend/alert_destinations.py
index 0d15ba62096a..6d3b178d9fa8 100644
--- a/products/replay_vision/backend/alert_destinations.py
+++ b/products/replay_vision/backend/alert_destinations.py
@@ -4,7 +4,7 @@ from __future__ import annotations
from typing import Literal
-from products.alerts.backend.facade.contracts import DestinationType, EventKindSpec
+from products.alerts_platform.backend.facade.contracts import DestinationType, EventKindSpec
EventKind = Literal["firing", "resolved", "broken", "errored", "match"]
VISION_DESTINATION_TYPES = (DestinationType.SLACK, DestinationType.WEBHOOK)
diff --git a/products/replay_vision/backend/alert_state_machine.py b/products/replay_vision/backend/alert_state_machine.py
index 58884341b54f..05d0fa86859a 100644
--- a/products/replay_vision/backend/alert_state_machine.py
+++ b/products/replay_vision/backend/alert_state_machine.py
@@ -18,7 +18,7 @@ from typing import TYPE_CHECKING
from posthog.dataclasses import frozen
-from products.alerts.backend.facade.lifecycle import (
+from products.alerts_platform.backend.facade.lifecycle import (
MAX_CONSECUTIVE_FAILURES,
AlertCheckOutcome,
AlertPolicy,
diff --git a/products/replay_vision/backend/alert_utils.py b/products/replay_vision/backend/alert_utils.py
index 6d924e61943e..67a3b991dcca 100644
--- a/products/replay_vision/backend/alert_utils.py
+++ b/products/replay_vision/backend/alert_utils.py
@@ -7,7 +7,7 @@ from django.db.models import Q
import structlog
-from products.alerts.backend.facade.scheduling import (
+from products.alerts_platform.backend.facade.scheduling import (
advance_next_check_at,
compute_shard_offset_seconds as shared_compute_shard_offset_seconds,
parse_blocked_windows_tuples,
diff --git a/products/replay_vision/backend/api/vision_alerts.py b/products/replay_vision/backend/api/vision_alerts.py
index af4835eec4ac..83f8c5d59845 100644
--- a/products/replay_vision/backend/api/vision_alerts.py
+++ b/products/replay_vision/backend/api/vision_alerts.py
@@ -22,11 +22,6 @@ from posthog.exceptions import as_drf_validation_error
from posthog.models.team.team import Team
from posthog.models.user import User
-from products.alerts.backend.facade.contracts import (
- AlertDestinationData,
- AlertDestinationValidationError,
- DestinationType,
-)
from products.alerts.backend.facade.destinations import (
build_alert_destination_config,
count_active_alert_destinations,
@@ -37,8 +32,13 @@ from products.alerts.backend.facade.destinations import (
soft_delete_all_alert_destinations,
validate_destination_data,
)
-from products.alerts.backend.facade.scheduling import validate_and_normalize_schedule_restriction
from products.alerts.backend.presentation.views.schedule_restriction import AlertScheduleRestriction
+from products.alerts_platform.backend.facade.contracts import (
+ AlertDestinationData,
+ AlertDestinationValidationError,
+ DestinationType,
+)
+from products.alerts_platform.backend.facade.scheduling import validate_and_normalize_schedule_restriction
from products.replay_vision.backend.alert_destinations import (
EVENT_KIND_CONFIG,
MATCH_EVENT_KINDS,
diff --git a/products/replay_vision/backend/temporal/vision_alerts/activities.py b/products/replay_vision/backend/temporal/vision_alerts/activities.py
index b102129de84b..aa8be2ae2e2a 100644
--- a/products/replay_vision/backend/temporal/vision_alerts/activities.py
+++ b/products/replay_vision/backend/temporal/vision_alerts/activities.py
@@ -31,7 +31,7 @@ from products.alerts.backend.facade.destinations import (
flush_alert_internal_events,
produce_alert_internal_event,
)
-from products.alerts.backend.facade.scheduling import is_utc_datetime_blocked, parse_blocked_windows_tuples
+from products.alerts_platform.backend.facade.scheduling import is_utc_datetime_blocked, parse_blocked_windows_tuples
from products.replay_vision.backend.alert_state_machine import (
AlertCheckOutcome,
AlertState,
diff --git a/pyproject.toml b/pyproject.toml
index 74eb5bfa94b6..3c088214a963 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -596,7 +596,6 @@ ignore_imports = [
"products.alerts.backend.presentation.views.alert -> products.alerts.backend.insight_alert_state_machine",
"products.alerts.backend.presentation.views.alert -> products.alerts.backend.models.alert",
"products.alerts.backend.presentation.views.insight_alerts -> products.alerts.backend.models.alert",
- "products.alerts.backend.presentation.views.platform_alert -> products.alerts.backend.models.platform_alert",
"products.mcp_analytics.backend.presentation.views -> products.mcp_analytics.backend.logic",
"products.mcp_analytics.backend.presentation.views -> products.mcp_analytics.backend.models",
"products.mcp_analytics.backend.presentation.serializers -> products.mcp_analytics.backend.models",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0ea6686078da..c557ab48405c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -68054,109 +68054,6 @@ export namespace Schemas {
results?: PersonListRecord[];
}
- /**
- * * `logs` - Logs
- */
- export type PlatformAlertConfigurationSourceKindEnum = typeof PlatformAlertConfigurationSourceKindEnum[keyof typeof PlatformAlertConfigurationSourceKindEnum];
-
-
- export const PlatformAlertConfigurationSourceKindEnum = {
- Logs: 'logs',
- } as const;
-
- export interface PlatformAlert {
- /** Unique identifier of this alert instance. */
- readonly id: string;
- /** Key of the result group this instance tracks. Empty when the source does not group results. */
- readonly grouping_key: string;
- /** Current state of this alert instance.
- *
- * * `not_firing` - Not firing
- * * `firing` - Firing
- * * `errored` - Errored
- * * `snoozed` - Snoozed
- * * `broken` - Broken */
- readonly state: BillingAlertConfigurationStateEnum;
- /**
- * When the current firing started. Null when the instance is not firing.
- * @nullable
- */
- readonly firing_started_at: string | null;
- /**
- * When a notification was last sent for this instance.
- * @nullable
- */
- readonly last_notified_at: string | null;
- /**
- * Time until which notifications are snoozed. Null when not snoozed.
- * @nullable
- */
- readonly snooze_until: string | null;
- }
-
- /**
- * Source-specific query settings. The shape depends on source_kind.
- */
- export type PlatformAlertConfigurationSourceConfig = { [key: string]: unknown };
-
- export interface PlatformAlertConfiguration {
- /** Unique identifier of the alert configuration. */
- readonly id: string;
- /** Human-readable name of the alert. */
- readonly name: string;
- /** Whether the alert is evaluated on schedule. */
- readonly enabled: boolean;
- /** Product whose data the alert evaluates.
- *
- * * `logs` - Logs */
- readonly source_kind: PlatformAlertConfigurationSourceKindEnum;
- /** Source-specific query settings. The shape depends on source_kind. */
- readonly source_config: PlatformAlertConfigurationSourceConfig;
- /** Count the evaluated value is compared against. */
- readonly threshold_count: number;
- /** Comparison operator applied between the value and threshold_count. */
- readonly threshold_operator: string;
- /** Length of the evaluated time window, in minutes. */
- readonly window_minutes: number;
- /** Minutes between scheduled checks. */
- readonly check_interval_minutes: number;
- /** Number of recent checks considered when deciding to fire. */
- readonly evaluation_periods: number;
- /** Number of breaching checks within evaluation_periods required to fire. */
- readonly datapoints_to_alarm: number;
- /** Minimum minutes between notifications for the same alert. */
- readonly cooldown_minutes: number;
- /** Blocked local time windows (HH:MM in the project timezone) when the alert does not run. Null means no quiet hours. */
- readonly schedule_restriction: AlertScheduleRestriction | null;
- /**
- * When the next check is due. Null when no check is scheduled.
- * @nullable
- */
- readonly next_check_at: string | null;
- /** Number of checks in a row that failed to evaluate. */
- readonly consecutive_failures: number;
- /**
- * ID of the legacy source configuration this row was backfilled from. Null for alerts created on the platform.
- * @nullable
- */
- readonly legacy_configuration_id: string | null;
- /** When the configuration was created. */
- readonly created_at: string;
- /** When the configuration was last changed. */
- readonly updated_at: string;
- /** Runtime state for each result group of this configuration. */
- readonly alerts: readonly PlatformAlert[];
- }
-
- export interface PaginatedPlatformAlertConfigurationList {
- count: number;
- /** @nullable */
- next?: string | null;
- /** @nullable */
- previous?: string | null;
- results: PlatformAlertConfiguration[];
- }
-
/**
* * `SYSTEM` - SYSTEM
* * `PLUGIN` - PLUGIN
@@ -121024,17 +120921,6 @@ export namespace Schemas {
Json: 'json',
} as const;
- export type PlatformAlertsListParams = {
- /**
- * Number of results to return per page.
- */
- limit?: number;
- /**
- * The initial index from which to return the results.
- */
- offset?: number;
- };
-
export type PluginConfigsLogsListParams = {
/**
* Number of results to return per page.
diff --git a/tach.toml b/tach.toml
index 814cea3f3f90..1025dafeb0fa 100644
--- a/tach.toml
+++ b/tach.toml
@@ -83,6 +83,7 @@ layer = "modules"
[[modules]]
path = "posthog"
depends_on = [
+ "products.alerts_platform",
"products.ai_training",
"products.autoresearch",
"products.cohorts",
@@ -188,6 +189,7 @@ layer = "modules"
[[modules]]
path = "products.alerts"
depends_on = [
+ "products.alerts_platform",
"ee",
"posthog",
"products.cdp",
@@ -554,6 +556,7 @@ layer = "modules"
[[modules]]
path = "products.logs"
depends_on = [
+ "products.alerts_platform",
"posthog",
"products.alerts",
"products.apm",
@@ -566,6 +569,7 @@ layer = "modules"
[[modules]]
path = "products.billing_alerts"
depends_on = [
+ "products.alerts_platform",
"ee",
"posthog",
"products.alerts",
@@ -791,6 +795,7 @@ layer = "modules"
[[modules]]
path = "products.replay_vision"
depends_on = [
+ "products.alerts_platform",
"ee",
"posthog",
"products.actions",
@@ -1641,12 +1646,18 @@ depends_on = [
]
layer = "modules"
+[[modules]]
+path = "products.alerts_platform"
+depends_on = ["posthog"]
+layer = "modules"
+
[[interfaces]]
expose = [
"backend\\.facade.*",
"backend\\.presentation\\.views.*",
]
from = [
+ "products.alerts_platform",
"products.today",
]
diff --git a/tools/hogli-commands/hogli_commands/tests/test_crossings.py b/tools/hogli-commands/hogli_commands/tests/test_crossings.py
index dda66a766edd..332f3c6fa197 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_crossings.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_crossings.py
@@ -158,7 +158,7 @@ class TestBindingPaths:
def test_unrelated_class_of_the_same_name_is_not_bound(self) -> None:
candidate = _candidate(
- "from products.alerts.backend.facade.contracts import AlertConfiguration\nqs = AlertConfiguration(id=1)"
+ "from products.alerts_platform.backend.facade.contracts import AlertConfiguration\nqs = AlertConfiguration(id=1)"
)
origins = crossings._origins([candidate], [ALERT])
assert crossings._bound_names(candidate, origins) == {}