:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(alerts): seal the shared alerting facade (#98214)
Julian Bezd4b9cb9001f5
diff --git a/.agents/skills/adding-product-alerting/SKILL.md b/.agents/skills/adding-product-alerting/SKILL.mdindex dae71bc3154a..96aa6fcdadb8 100644--- a/.agents/skills/adding-product-alerting/SKILL.md+++ b/.agents/skills/adding-product-alerting/SKILL.md@@ -38,12 +38,12 @@ This skill covers two jobs:Both paths must preserve these rules:1. **Evaluation stays domain-specific.** Products decide whether their data breached. The shared lifecycle consumes normalized `CheckInput`.-2. **One lifecycle machine.** Reuse `products/alerts/backend/state_machine.py`; express real product differences through `AlertPolicy`, not forks.+2. **One lifecycle machine.** Reuse `products/alerts/backend/facade/lifecycle.py`; express real product differences through `AlertPolicy`, not forks.3. **One product mutator.** Every persisted `state` or `consecutive_failures` write goes through the product adapter's `apply_outcome`.4. **Dispatch and persistence agree.** For HogFunction notifications, do not persist a notification-dependent transition until the internal-event producer acknowledges the event. Restore the pre-check outcome when production fails. This acknowledgement does not confirm downstream destination execution.5. **Destinations are allowlisted.** Shared support does not automatically expose a destination in every product.-6. **Scheduling math is shared, eligibility is product-owned.** Reuse fixed-cadence, calendar-anchor, timezone, and schedule-restriction helpers from `products/alerts/backend/scheduling.py`. Keep model-specific due predicates and persistence with the adopter.-7. **Shared code has no product branches.** The lifecycle module stays pure Python. Reusable Django behavior belongs elsewhere in `products/alerts/backend/`.+6. **Scheduling math is shared, eligibility is product-owned.** Reuse fixed-cadence, calendar-anchor, timezone, and schedule-restriction helpers from `products/alerts/backend/facade/scheduling.py`. Keep model-specific due predicates and persistence with the adopter.+7. **Shared code has no product branches.** The lifecycle module stays pure Python. Reusable Django behavior belongs behind `products/alerts/backend/facade/`. Implementation that several facade modules share goes in `products/alerts/backend/logic/`. Consumers import the facade. The tach interface also exposes the DRF presentation surface and, until the core pipeline moves, a named legacy set (see [architecture.md](references/architecture.md)).8. **Frontend data is normalized at the product boundary.** Shared editor components render normalized definitions, destinations, advanced options, schedules, and history. Product API calls, payloads, and evaluation-specific fields stay in the product adapter.9. **Defaults remain backward compatible.** New platform options must preserve existing adopters until they explicitly opt in.10. **Configuration, routing, and delivery are one contract.** A supported destination must persist, remain visible, be selected when its alert fires, and reach its delivery worker. Do not test only one of these steps.diff --git a/.agents/skills/adding-product-alerting/references/adopting-platform-alerting.md b/.agents/skills/adding-product-alerting/references/adopting-platform-alerting.mdindex 0d67b4c1770c..62529a8b38b6 100644--- a/.agents/skills/adding-product-alerting/references/adopting-platform-alerting.md+++ b/.agents/skills/adding-product-alerting/references/adopting-platform-alerting.md@@ -29,7 +29,7 @@ Invoke `/django-migrations` for model changes.## 3. Build the lifecycle adapter-Create one product state-machine module, following `products/logs/backend/alert_state_machine.py`.+Create one product state-machine module, following `products/logs/backend/alert_state_machine.py`. It imports the shared machine from `products.alerts.backend.facade.lifecycle`.1. Select or define the product's `AlertPolicy`.2. Convert the model and recent history into the shared snapshot.@@ -48,8 +48,9 @@ Create a thin product module like `products/logs/backend/alert_destinations.py`.- Define one `EventKindSpec` per notification action.- Keep event IDs and properties stable because HogFunctions filter and render from them.- Include every template property in the internal event payload.-- Define the product's allowed `DestinationType` values explicitly.-- Validate, build, create, and delete destination HogFunctions through `products.alerts.backend.facade.api`.+- Define the product's allowed `DestinationType` values explicitly. `DestinationType` and `EventKindSpec` come from `products.alerts.backend.facade.contracts`.+- Validate, build, create, and delete destination HogFunctions through `products.alerts.backend.facade.destinations`. Create returns the new HogFunction ids, not rows.+- Catch `AlertDestinationValidationError` at the view and raise the product's own validation error with the same message.- Scope deletion with the team, alert ID, and allowed event IDs.Shared support for a destination does not opt the product into it.@@ -60,21 +61,21 @@ For HogFunction destinations:1. Evaluate alerts and retain each pre-check snapshot or outcome needed for rollback.2. Produce internal events and retain each `ProduceResult`.-3. Flush once after producing the batch.+3. Flush once after producing the batch. The three delivery helpers live in `products.alerts.backend.facade.destinations`.4. Check producer acknowledgement for each result with `alert_internal_event_delivered(...)`.5. Restore delivery-dependent outcomes for unacknowledged results before persistence.6. Persist acknowledged outcomes, check history, and product scheduling according to the product contract.Producer acknowledgement does not confirm downstream HogFunction execution or final destination delivery. Logs is the reference for reevaluating on the next cadence after an internal event is not acknowledged.-For email, call `send_alert_email(...)` through the facade. The product must choose authorized recipients, a stable campaign key, subject, template, and context. Decide explicitly whether an email failure blocks a lifecycle transition or is recorded separately.+For email, call `send_alert_email(...)` from `products.alerts.backend.facade.email`. The product must choose authorized recipients, a stable campaign key, subject, template, and context. Decide explicitly whether an email failure blocks a lifecycle transition or is recorded separately.## 6. Add scheduling and due selection-Import the product-facing scheduling contract directly from its implementation module:+Import the product-facing scheduling contract from the facade:```python-from products.alerts.backend.scheduling import (+from products.alerts.backend.facade.scheduling import (CalendarInterval,advance_next_check_at,compute_shard_offset_seconds,diff --git a/.agents/skills/adding-product-alerting/references/architecture.md b/.agents/skills/adding-product-alerting/references/architecture.mdindex 1c2dd1485b8b..28065167ecbd 100644--- a/.agents/skills/adding-product-alerting/references/architecture.md+++ b/.agents/skills/adding-product-alerting/references/architecture.md@@ -4,19 +4,33 @@ Use this reference to decide where code belongs before editing it.## Layer map-| Layer | Location | Owns |-| --------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ |-| Pure lifecycle decisions | `products/alerts/backend/state_machine.py` | State transitions, policy decisions, and notification actions |-| Shared alert infrastructure | `products/alerts/backend/` | Scheduling math, destination configuration and persistence, internal-event delivery, email transport, insight alert models/API, and insight evaluation |-| Product adapter | `products/<name>/backend/` | Domain evaluation, model snapshots, the single mutator, event payloads, allowed destinations, due queries, history, and orchestration |-| Shared alert creation UI | `frontend/src/lib/components/Alerting/AlertWizard/` | Reusable HogFunction destination, trigger, and configuration flow |-| Shared product alert UI | `products/alerts/frontend/components/` | Container-agnostic editor layout, definition primitives, advanced options, destination editor, schedule presentation, and evaluation chart |-| Product UI | `products/<name>/frontend/` or `frontend/src/scenes/<name>/` | Form logic, API calls, product fields, normalized adapters, entry points, detail tables, and wizard configuration |+| Layer | Location | Owns |+| --------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ |+| Pure lifecycle decisions | `products/alerts/backend/facade/lifecycle.py` | State transitions, policy decisions, and notification actions |+| Shared alert door | `products/alerts/backend/facade/` | Contracts, constants, scheduling math, delivery SLOs, and insight alert reads and writes. Other products call it |+| Shared alert implementation | `products/alerts/backend/logic/` | Destination configuration and persistence, internal-event delivery, and email transport. Only the facade calls it |+| Insight alert evaluation | `products/alerts/backend/evaluation/` | Insight query extraction, comparison, and breach formatting. Core still drives it directly |+| Product adapter | `products/<name>/backend/` | Domain evaluation, model snapshots, the single mutator, event payloads, allowed destinations, due queries, history, and orchestration |+| Shared alert creation UI | `frontend/src/lib/components/Alerting/AlertWizard/` | Reusable HogFunction destination, trigger, and configuration flow |+| Shared product alert UI | `products/alerts/frontend/components/` | Container-agnostic editor layout, definition primitives, advanced options, destination editor, schedule presentation, and evaluation chart |+| Product UI | `products/<name>/frontend/` or `frontend/src/scenes/<name>/` | Form logic, API calls, product fields, normalized adapters, entry points, detail tables, and wizard configuration |++`products/billing_alerts` is the reference adopter for the backend boundary shape: it holds destination ids and the facade contracts, and never an alerts model or queryset.`products/logs` is the reference adopter for fixed-cadence scheduling, HogFunction destinations, delivery rollback, product-owned Temporal orchestration, and the shared product alert editor components.Logs and insight alerts both adapt their product state to the shared lifecycle engine. Insight alerts are the reference adopter for calendar anchors, weekend skipping, and email delivery. Both products use shared schedule restrictions for quiet hours. Each product keeps its model, due query, and scheduling persistence. The evaluation package is shared across insight query kinds, but it is not a generic evaluator for unrelated products.+## Boundary++Consumers import `products.alerts.backend.facade.*`. The tach interface also exposes `presentation.views.*` and `routes.*`, which carry the DRF surface other products mount or reuse in process.++- Models, querysets and DRF objects never cross the facade in either direction.+- Facade functions take and return contracts, ids, and plain values.+- Consumers hold ids and come back to the facade for anything else.++Core still runs the insight-alert pipeline itself, so its imports of the alert models, the insight evaluation, the insight lifecycle adapter, the investigation episode reader and the Max tool stay open. Those five are named in the legacy-leaks block for `products.alerts` in `tach.toml`, and the product stays non-isolated until the block is empty.+## Frontend contractShared product alert UI lives in `products/alerts/frontend/components/`. It is presentation infrastructure, not a frontend product registry.@@ -36,7 +50,7 @@ Read [frontend-alerting.md](frontend-alerting.md) before adding or extending a p## Lifecycle contract-`products/alerts/backend/state_machine.py` is pure Python.+`products/alerts/backend/facade/lifecycle.py` is pure Python.- `CheckInput` normalizes one product evaluation.- `AlertSnapshot` contains only fields needed for lifecycle decisions.@@ -57,23 +71,32 @@ Error behavior is load-bearing:## Destination contract-Product-facing destination setup is exported from `products.alerts.backend.facade.api`:+Product-facing destination setup lives in `products.alerts.backend.facade.destinations`. Read that module for the full surface. An adopter starts from:- `validate_destination_data`- `build_alert_destination_config`- `create_alert_destination_hog_functions`- `soft_delete_alert_destinations`-- `soft_delete_all_alert_destinations`-- `send_alert_email`-`EventKindSpec` describes destination-neutral content for one event kind. The shared builder converts it into a HogFunction payload through `DESTINATION_SPECS`, the registry where each destination type owns its template ID, required fields, input building, read-back, and read redaction. Adding a destination type means adding one entry there. Products own event IDs, event properties, wording, actions, and their allowed destination list.+The module also holds the destination limits. The insight-alert event and destination-type constants live in `products.alerts.backend.facade.api`.++`send_alert_email` lives in `products.alerts.backend.facade.email`. The data types the+functions above take and return live in `products.alerts.backend.facade.contracts`.++`create_alert_destination_hog_functions` returns the ids of the hog functions it created. It+does not return model rows, so the caller keeps ids and asks for anything else through+another facade read.++`EventKindSpec` describes destination-neutral content for one event kind. The shared builder converts it into a HogFunction payload through an internal registry where each destination type owns its template ID, required fields, input building, read-back, and read redaction. Adding a destination type means adding one entry there. Products own event IDs, event properties, wording, actions, and their allowed destination list.++Validation failures raise `AlertDestinationValidationError`, a plain exception with a message and an optional field name. The adopter's view translates it into its own framework's validation error, because the facade has no HTTP layer of its own. `as_drf_validation_error` in `posthog.exceptions` does that translation for a DRF view.Deletion is fail-closed. Always scope it with `team_id`, `alert_id`, and the product's allowed event IDs.`create_alert_destination_hog_functions` refuses any destination in the call that the alert already has, so call it with the alert row locked.## Delivery contract-HogFunction notification workers use `products.alerts.backend.destinations` directly:+HogFunction notification workers use `products.alerts.backend.facade.destinations`:1. `produce_alert_internal_event(...)` returns a `ProduceResult` or `None`.2. `flush_alert_internal_events(...)` flushes the shared producer. Batch workers should flush once per produced batch.@@ -82,11 +105,13 @@ HogFunction notification workers use `products.alerts.backend.destinations` direThis acknowledgement confirms production to the internal-event transport, not downstream HogFunction execution or final Slack, Discord, webhook, or Microsoft Teams delivery. The helpers log and capture producer failures. The product owns rollback, retry timing, schedule advancement, and check-history semantics.-Email callers use `send_alert_email(...)` through the facade. The caller owns recipients, authorization, subject, template, context, error handling, and a stable `campaign_key` for the required retry and deduplication behavior.+Wrap the delivery step in `alert_delivery_slo(...)` from `products.alerts.backend.facade.delivery_slo`. Logs' Temporal activities are the reference.++Email callers use `send_alert_email(...)` from `products.alerts.backend.facade.email`. The caller owns recipients, authorization, subject, template, context, error handling, and a stable `campaign_key` for the required retry and deduplication behavior.## Scheduling contract-`products/alerts/backend/scheduling.py` is pure Python and owns reusable scheduling math:+`products/alerts/backend/facade/scheduling.py` is pure Python and owns reusable scheduling math:- `compute_shard_offset_seconds(...)` deterministically assigns a UUID-keyed alert to scheduler ticks.- `advance_next_check_at(...)` advances from the prior schedule, skips missed intervals, snaps to the midnight-anchored cadence grid, and applies the shard offset.diff --git a/.agents/skills/adding-product-alerting/references/extending-platform-alerting.md b/.agents/skills/adding-product-alerting/references/extending-platform-alerting.mdindex 573ef071c15b..55dfeeff3d05 100644--- a/.agents/skills/adding-product-alerting/references/extending-platform-alerting.md+++ b/.agents/skills/adding-product-alerting/references/extending-platform-alerting.md@@ -4,16 +4,16 @@ Use this path when adding a reusable alert capability, option, or advanced behav## 1. Classify the extension-| Capability | Primary source of truth | Also inspect |-| -------------------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |-| Lifecycle state, notification action, control-plane transition, or policy option | `products/alerts/backend/state_machine.py` | Shared decision tests, every adopter policy and adapter, semgrep rule |-| Fixed-cadence, calendar, timezone, or schedule-restriction behavior | `products/alerts/backend/scheduling.py` | Product wrappers, create/update paths, due queries, scheduler interval, DST boundaries |-| Destination type or destination-wide option | `products/alerts/backend/destination_configs.py` | HogFunction templates/sub-templates, facade exports, product allowlists, `AlertWizard` |-| HogFunction persistence or delivery semantics | `products/alerts/backend/destinations.py` | Worker batching, rollback, delivery metrics, destination tests |-| Email transport capability | `products/alerts/backend/email_notifications.py` | Facade export, campaign-key semantics, adopter templates and tests |-| Shared insight query evaluation | `products/alerts/backend/evaluation/` | Alert config schema, API validation, query-kind gates, generated API types |-| Shared alert model or API option | `products/alerts/backend/models/` and `products/alerts/backend/api/` | Migrations, OpenAPI, frontend logic, MCP schema |-| Wizard trigger, destination, or advanced creation option | `frontend/src/lib/components/Alerting/AlertWizard/` | HogFunction sub-template compatibility, adopter props, kea tests |+| Capability | Primary source of truth | Also inspect |+| -------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |+| Lifecycle state, notification action, control-plane transition, or policy option | `products/alerts/backend/facade/lifecycle.py` | Shared decision tests, every adopter policy and adapter, semgrep rule |+| Fixed-cadence, calendar, timezone, or schedule-restriction behavior | `products/alerts/backend/facade/scheduling.py` | Product wrappers, create/update paths, due queries, scheduler interval, DST boundaries |+| Destination type or destination-wide option | `products/alerts/backend/logic/destination_configs.py` | HogFunction templates/sub-templates, facade exports, product allowlists, `AlertWizard` |+| HogFunction persistence or delivery semantics | `products/alerts/backend/logic/destinations.py` | Worker batching, rollback, delivery metrics, destination tests |+| Email transport capability | `products/alerts/backend/facade/email.py` | Campaign-key semantics, adopter templates and tests |+| Shared insight query evaluation | `products/alerts/backend/evaluation/` | Alert config schema, API validation, query-kind gates, generated API types |+| Shared alert model or API option | `products/alerts/backend/models/` and `products/alerts/backend/presentation/views/` | Migrations, OpenAPI, frontend logic, MCP schema |+| Wizard trigger, destination, or advanced creation option | `frontend/src/lib/components/Alerting/AlertWizard/` | HogFunction sub-template compatibility, adopter props, kea tests |If the change crosses rows, update each row deliberately. Do not hide a cross-layer contract in one product adapter.@@ -21,7 +21,7 @@ If the change crosses rows, update each row deliberately. Do not hide a cross-la### Lifecycle-- Keep `products/alerts/backend/state_machine.py` free of Django and product-model imports.+- Keep `products/alerts/backend/facade/lifecycle.py` free of Django and product-model imports.- Add policy fields only for observed semantic differences. Give them defaults that preserve every existing adopter.- Prefer a new pure transition helper over direct model mutation.- Update the decision table for firing, resolving, snoozing, erroring, breaking, cooldown, and notification edges affected by the change.@@ -42,7 +42,7 @@ If the change crosses rows, update each row deliberately. Do not hide a cross-laA new destination type normally requires all of these:-1. Add the enum value, HogFunction template ID, and required fields in `products/alerts/backend/destination_configs.py`.+1. Add the enum value in `products/alerts/backend/facade/contracts.py`, and the HogFunction template ID and required fields in `products/alerts/backend/logic/destination_configs.py`.2. Extend validation and `build_alert_destination_config(...)` without changing existing payloads.3. Add or update the transport template under `posthog/cdp/templates/<destination>/template_<destination>.py` and its adjacent tests.4. Add alert-specific template compatibility in `frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts`.@@ -106,8 +106,8 @@ Read `frontend/src/AGENTS.md` before changing the wizard.## 3. Expose the shared contract-- Export product-facing Django helpers through `products.alerts.backend.facade.api`.-- Keep worker-only delivery primitives in `products.alerts.backend.destinations` when callers need their detailed result types.+- Export product-facing Django helpers as real functions on the matching facade module: `facade.destinations`, `facade.email`, `facade.delivery_slo`, or `facade.api`. A facade module must never be a list of names re-exported from an internal one.+- Put the types those functions take and return in `products.alerts.backend.facade.contracts`, and keep them free of Django and DRF.- Update type annotations and help text so OpenAPI and MCP schemas remain useful.- Update this skill when the ownership boundary, public helper set, or adoption workflow changes.diff --git a/.agents/skills/implementing-mcp-tools/SKILL.md b/.agents/skills/implementing-mcp-tools/SKILL.mdindex 170f8814bcfc..f3a7ff781d6c 100644--- a/.agents/skills/implementing-mcp-tools/SKILL.md+++ b/.agents/skills/implementing-mcp-tools/SKILL.md@@ -40,7 +40,7 @@ Before scaffolding YAML, verify:Missing descriptions = agents guessing at parameters.Use `ListField(child=serializers.CharField())` instead of bare `ListField()`,and `@extend_schema_field(PydanticModel)` on `JSONField` subclasses to get typed Zod output- (see `products/alerts/backend/api/alert.py` for the pattern).+ (see `products/alerts/backend/presentation/views/alert.py` for the pattern).2. **Plain `ViewSet` methods have `@extend_schema(request=...)`** —without it, drf-spectacular can't discover the request bodyand the generated tool gets `z.object({})` (zero parameters).diff --git a/.agents/skills/improving-drf-endpoints/SKILL.md b/.agents/skills/improving-drf-endpoints/SKILL.mdindex 2f0c852bfdca..7170b98430b6 100644--- a/.agents/skills/improving-drf-endpoints/SKILL.md+++ b/.agents/skills/improving-drf-endpoints/SKILL.md@@ -169,7 +169,7 @@ See [common-anti-patterns.md](references/common-anti-patterns.md) for before/aft## Canonical examples in the codebase-- **JSONField + @extend_schema_field:** `products/alerts/backend/api/alert.py`+- **JSONField + @extend_schema_field:** `products/alerts/backend/presentation/views/alert.py`- **@validated_request:** `products/tasks/backend/presentation/views/api.py`- **help_text + typed responses:** `products/ai_observability/backend/api/summarization.py`- **Facade product:** `products/visual_review/backend/presentation/views.py`diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.ymlindex e6404be8473f..79c2736c1475 100644--- a/.github/workflows/container-images-cd.yml+++ b/.github/workflows/container-images-cd.yml@@ -831,7 +831,8 @@ jobs:- bin/temporal-django-workerlogsAlerting:- 'posthog/temporal/logs_alerting/**'- - 'products/alerts/backend/state_machine.py'+ - 'products/alerts/backend/facade/**'+ - 'products/alerts/backend/logic/**'- 'products/logs/backend/**'- 'posthog/temporal/common/**'- 'posthog/management/commands/start_temporal_worker.py'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.yamlindex 0aca07e729c0..a3ae2fc40ef0 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@@ -108,14 +108,15 @@ rules:confidence: HIGHpaths:include:- - '/products/alerts/backend/api/alert.py'- - '/products/alerts/backend/facade/api.py'- - '/products/alerts/backend/max_tools.py'- - '/products/alerts/backend/models/alert.py'+ - '/products/alerts/backend/**/*.py'- '/posthog/tasks/alerts/**/*.py'- '/posthog/temporal/alerts/**/*.py'- '/.semgrep/rules/security/tests/insight-alert-state-must-go-through-state-machine.py'exclude:- - '/products/alerts/backend/api/test/**'+ - '/products/alerts/backend/insight_alert_state_machine.py'+ # Writes HogFunction.enabled (destination plumbing), not an alert.+ - '/products/alerts/backend/logic/destinations.py'+ - '/products/alerts/backend/test/**'+ - '/products/alerts/backend/tests/**'- '/products/alerts/backend/**/test_*.py'- '/posthog/tasks/alerts/test/**'diff --git a/posthog/exceptions.py b/posthog/exceptions.pyindex 4e486e00251c..7c066f7766b7 100644--- a/posthog/exceptions.py+++ b/posthog/exceptions.py@@ -1,4 +1,4 @@-from typing import Any, Optional, TypedDict+from typing import Any, Optional, Protocol, TypedDictfrom django.http.request import HttpRequestfrom django.http.response import JsonResponse@@ -137,6 +137,20 @@ class ClickHouseClusterMemoryLimitExceeded(ClickHouseQueryMemoryLimitExceeded):)+class FieldedValidationError(Protocol):+ """A framework-free validation error, as a product's internals raise it."""++ message: str+ field: str | None+++def as_drf_validation_error(error: FieldedValidationError) -> ValidationError:+ """The DRF equivalent of a framework-free validation error, keyed by field when it names one."""+ if error.field:+ return ValidationError({error.field: [error.message]})+ return ValidationError(error.message)++class ExceptionContext(TypedDict):request: HttpRequestdiff --git a/posthog/tasks/alerts/schedule_restriction.py b/posthog/tasks/alerts/schedule_restriction.pyindex 6c68a1b7cd8f..b4cd6d228566 100644--- a/posthog/tasks/alerts/schedule_restriction.py+++ b/posthog/tasks/alerts/schedule_restriction.py@@ -1,6 +1,6 @@"""Schedule restrictions (blocked local time windows) for insight alerts.-The pure minute-math and validation live in products/alerts/backend/scheduling.py; this+The pure minute-math and validation live in products/alerts/backend/facade/scheduling.py; thismodule keeps the AlertConfiguration-aware entry points plus the cap-exceededretry/logging fallback."""@@ -11,8 +11,7 @@ from datetime import UTC, datetime, timedeltaimport structlog-from products.alerts.backend.models.alert import AlertConfiguration-from products.alerts.backend.scheduling import (+from products.alerts.backend.facade.scheduling import (MAX_BLOCKED_WINDOWS,MAX_UNBLOCK_STEPS,MIN_BLOCKED_WINDOW_MINUTES,@@ -25,6 +24,7 @@ from products.alerts.backend.scheduling import (scan_next_unblocked_utc,validate_and_normalize_schedule_restriction,)+from products.alerts.backend.models.alert import AlertConfigurationlogger = 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.pyindex 6d63aa777668..46f6f31256ee 100644--- a/posthog/tasks/alerts/test/test_alert_check_helpers.py+++ b/posthog/tasks/alerts/test/test_alert_check_helpers.py@@ -7,7 +7,7 @@ from posthog.api.test.dashboards import DashboardAPIfrom posthog.tasks.alerts.test.alert_check_helpers import run_alert_checkfrom posthog.tasks.alerts.utils import AlertEvaluationResult, record_alert_delivery-from products.alerts.backend.destinations import AlertDelivery+from products.alerts.backend.facade.contracts import AlertDeliveryfrom products.alerts.backend.models import AlertCheck, AlertConfigurationdiff --git a/posthog/tasks/alerts/test/test_alert_subscriptions.py b/posthog/tasks/alerts/test/test_alert_subscriptions.pyindex 10c805897c00..1a9f932f3ab9 100644--- a/posthog/tasks/alerts/test/test_alert_subscriptions.py+++ b/posthog/tasks/alerts/test/test_alert_subscriptions.py@@ -9,7 +9,6 @@ from posthog.models import Userfrom posthog.models.instance_setting import set_instance_settingfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.tasks.alerts.utils import send_notifications_for_breaches, send_notifications_for_disabled-from posthog.tasks.test.utils_email_tests import mock_email_messagesfrom products.alerts.backend.models import AlertConfiguration, AlertSubscription@@ -65,19 +64,16 @@ class TestAlertSubscriptionOrgMembership(APIBaseTest):assert not AlertSubscription.objects.filter(alert_configuration=alert, user=self.other_user).exists()assert AlertSubscription.objects.filter(alert_configuration=alert, user=self.user).exists()- @patch("products.alerts.backend.email_notifications.EmailMessage")- def test_send_notifications_excludes_removed_members(self, MockEmailMessage: MagicMock) -> None:- mocked_email_messages = mock_email_messages(MockEmailMessage)+ @patch("posthog.tasks.alerts.utils.send_alert_email")+ def test_send_notifications_excludes_removed_members(self, mock_send_alert_email: MagicMock) -> None:alert = AlertConfiguration.objects.get(pk=self.alert["id"])OrganizationMembership.objects.filter(user=self.other_user, organization=self.organization).delete()send_notifications_for_breaches(alert, ["test breach"], idempotency_key="test-excludes-removed-members")- assert len(mocked_email_messages) == 1- email = mocked_email_messages[0]- assert len(email.to) == 1- assert email.to[0]["recipient"] == "[email protected]"+ mock_send_alert_email.assert_called_once()+ assert list(mock_send_alert_email.call_args.kwargs["recipients"]) == ["[email protected]"]@time_machine.travel("2024-06-02T08:55:00.000Z", tick=False)@@ -180,30 +176,30 @@ class TestAlertEmailNotifications(APIBaseTest):},).json()- @patch("products.alerts.backend.email_notifications.EmailMessage")- def test_send_emails(self, MockEmailMessage: MagicMock) -> None:- mocked_email_messages = mock_email_messages(MockEmailMessage)+ @patch("posthog.tasks.alerts.utils.send_alert_email")+ def test_send_emails(self, mock_send_alert_email: MagicMock) -> None:alert = AlertConfiguration.objects.get(pk=self.alert["id"])send_notifications_for_breaches(alert, ["first anomaly description", "second anomaly description"], idempotency_key="test-send-emails")- assert len(mocked_email_messages) == 1- email = mocked_email_messages[0]- assert len(email.to) == 1- assert email.to[0]["recipient"] == "[email protected]"- assert "first anomaly description" in email.html_body- assert "second anomaly description" in email.html_body-- @patch("products.alerts.backend.email_notifications.EmailMessage")- def test_send_disabled_email(self, MockEmailMessage: MagicMock) -> None:- mocked_email_messages = mock_email_messages(MockEmailMessage)+ mock_send_alert_email.assert_called_once()+ kwargs = mock_send_alert_email.call_args.kwargs+ assert list(kwargs["recipients"]) == ["[email protected]"]+ assert kwargs["template_name"] == "alert_check_firing"+ assert kwargs["template_context"]["match_descriptions"] == [+ "first anomaly description",+ "second anomaly description",+ ]++ @patch("posthog.tasks.alerts.utils.send_alert_email")+ def test_send_disabled_email(self, mock_send_alert_email: MagicMock) -> None:alert = AlertConfiguration.objects.get(pk=self.alert["id"])send_notifications_for_disabled(alert, "Insight query is invalid", [self.user.email])- assert len(mocked_email_messages) == 1- email = mocked_email_messages[0]- assert email.template_name == "alert_disabled"- assert email.to[0]["recipient"] == "[email protected]"- assert "Insight query is invalid" in email.html_body+ mock_send_alert_email.assert_called_once()+ kwargs = mock_send_alert_email.call_args.kwargs+ assert kwargs["template_name"] == "alert_disabled"+ assert list(kwargs["recipients"]) == ["[email protected]"]+ assert kwargs["template_context"]["alert_error"] == "Insight query is invalid"diff --git a/posthog/tasks/alerts/test/test_investigation_notifications.py b/posthog/tasks/alerts/test/test_investigation_notifications.pyindex aba899eeeaf5..9a8c56d0ec34 100644--- a/posthog/tasks/alerts/test/test_investigation_notifications.py+++ b/posthog/tasks/alerts/test/test_investigation_notifications.py@@ -14,7 +14,7 @@ from posthog.tasks.alerts.investigation_notifications import (run_investigation_notification_safety_net,)-from products.alerts.backend.destinations import AlertDelivery+from products.alerts.backend.facade.contracts import AlertDeliveryfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatusfrom products.product_analytics.backend.facade.models import Insightdiff --git a/posthog/tasks/alerts/test/test_trends_absolute_alerts.py b/posthog/tasks/alerts/test/test_trends_absolute_alerts.pyindex acb28a707e06..fc576ac4a76a 100644--- a/posthog/tasks/alerts/test/test_trends_absolute_alerts.py+++ b/posthog/tasks/alerts/test/test_trends_absolute_alerts.py@@ -28,7 +28,7 @@ from posthog.caching.calculate_results import calculate_for_query_based_insightfrom posthog.models.instance_setting import set_instance_settingfrom posthog.tasks.alerts.test.alert_check_helpers import run_alert_check-from products.alerts.backend.destinations import AlertDelivery+from products.alerts.backend.facade.contracts import AlertDeliveryfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration# 8:55 AMdiff --git a/posthog/tasks/alerts/test/test_trends_relative_alerts.py b/posthog/tasks/alerts/test/test_trends_relative_alerts.pyindex 4d2f36fa141b..74f4690b2a12 100644--- a/posthog/tasks/alerts/test/test_trends_relative_alerts.py+++ b/posthog/tasks/alerts/test/test_trends_relative_alerts.py@@ -29,7 +29,7 @@ from posthog.caching.calculate_results import calculate_for_query_based_insightfrom posthog.models.instance_setting import set_instance_settingfrom posthog.tasks.alerts.test.alert_check_helpers import run_alert_check-from products.alerts.backend.destinations import AlertDelivery+from products.alerts.backend.facade.contracts import AlertDeliveryfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration# Tuesdaydiff --git a/posthog/tasks/alerts/test/test_utils.py b/posthog/tasks/alerts/test/test_utils.pyindex b3de59ca8b06..8139bd23c3b9 100644--- a/posthog/tasks/alerts/test/test_utils.py+++ b/posthog/tasks/alerts/test/test_utils.py@@ -21,7 +21,7 @@ from posthog.tasks.alerts.utils import (trigger_alert_hog_functions,)-from products.alerts.backend.destinations import ActiveAlertDestination+from products.alerts.backend.facade.contracts import ActiveAlertDestinationfrom products.alerts.backend.models.alert import AlertCheck, AlertConfigurationfrom products.product_analytics.backend.facade.models import Insightdiff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.pyindex fc396a1bae2e..b7770fbe1110 100644--- a/posthog/tasks/alerts/utils.py+++ b/posthog/tasks/alerts/utils.py@@ -18,17 +18,24 @@ from posthog.slo.types import SloOperationfrom posthog.tasks.alerts.schedule_restriction import snap_candidate_utc_to_schedule_restrictionfrom products.access_control.backend.facade.user_access_control import UserAccessControl-from products.alerts.backend.delivery_slo import alert_delivery_slo-from products.alerts.backend.destinations import (+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,- AlertDelivery,alert_internal_event_delivered,flush_alert_internal_events,list_active_alert_destinations,produce_alert_internal_event,serialize_deliveries,)-from products.alerts.backend.facade.api import send_alert_email+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,@@ -36,13 +43,6 @@ 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.backend.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 exportslogger = structlog.get_logger(__name__)diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.pyindex 3ac63aab42a0..abfed2160385 100644--- a/posthog/temporal/alerts/activities.py+++ b/posthog/temporal/alerts/activities.py@@ -52,10 +52,10 @@ from posthog.temporal.alerts.types import ()from posthog.temporal.common.heartbeat import Heartbeater-from products.alerts.backend.destinations import count_active_alert_destinationsfrom products.alerts.backend.evaluation import check_alert_for_insightfrom products.alerts.backend.evaluation.contract import AlertExtractionErrorfrom products.alerts.backend.evaluation.validation import validate_alert_config+from products.alerts.backend.facade.destinations import count_active_alert_destinationsfrom products.alerts.backend.insight_alert_state_machine import apply_unsnoozefrom products.alerts.backend.models.alert import AlertCheck, AlertConfigurationfrom products.notifications.backend.facade.api import (diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.pyindex fb79371f90d6..1a105f750d56 100644--- a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py@@ -19,7 +19,7 @@ from posthog.temporal.ai.anomaly_investigation.workflow import (investigate_anomaly_activity,)-from products.alerts.backend.destinations import AlertDelivery+from products.alerts.backend.facade.contracts import AlertDeliveryfrom products.alerts.backend.models.alert import (AlertCheck,AlertConfiguration,diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.pyindex 3916b196f1e3..c8a83f524560 100644--- a/posthog/temporal/tests/test_alerts_activities.py+++ b/posthog/temporal/tests/test_alerts_activities.py@@ -54,9 +54,9 @@ from posthog.temporal.alerts.types import (SkipReason,)-from products.alerts.backend.destinations import AlertDeliveryfrom products.alerts.backend.evaluation.contract import AlertExtractionErrorfrom products.alerts.backend.evaluation.validation import THRESHOLD_BOUNDS_REQUIRED_MESSAGE+from products.alerts.backend.facade.contracts import AlertDeliveryfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, Thresholdfrom products.product_analytics.backend.facade.models import Insight@@ -634,7 +634,7 @@ class TestNotifyAlert:with (patch("posthog.slo.events.posthoganalytics"),- patch("products.alerts.backend.delivery_slo.get_instance_region", return_value="US"),+ patch("products.alerts.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,):@@ -658,7 +658,7 @@ class TestNotifyAlert:with (patch("posthog.slo.events.posthoganalytics") as mock_slo_analytics,- patch("products.alerts.backend.delivery_slo.get_instance_region", return_value="US"),+ patch("products.alerts.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]")],@@ -889,7 +889,7 @@ class TestNotifyAlert:with (patch("posthog.slo.events.posthoganalytics") as mock_slo_analytics,- patch("products.alerts.backend.delivery_slo.get_instance_region", return_value="US"),+ patch("products.alerts.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/activity_logging.py b/products/alerts/backend/activity_logging.pyindex 73d7815960c8..c708d2b80047 100644--- a/products/alerts/backend/activity_logging.py+++ b/products/alerts/backend/activity_logging.py@@ -120,7 +120,7 @@ def handle_alert_subscription_change(@receiver(pre_delete, sender=AlertConfiguration)def cleanup_alert_hog_functions(sender, instance: AlertConfiguration, **kwargs) -> None:- from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType+ from products.cdp.backend.facade.models import HogFunction, HogFunctionTypefor hog_function in HogFunction.objects.filter(team_id=instance.team_id,@@ -128,6 +128,7 @@ def cleanup_alert_hog_functions(sender, instance: AlertConfiguration, **kwargs)deleted=False,filters__contains={"properties": [{"key": "alert_id", "value": str(instance.id)}]},):+ # nosemgrep: insight-alert-state-direct-mutation (writes HogFunction.enabled, not the alert's state)hog_function.enabled = Falsehog_function.deleted = Truehog_function.save()diff --git a/products/alerts/backend/destination_backfill.py b/products/alerts/backend/destination_backfill.pyindex 22d9ec9d7e95..36f774cc797a 100644--- a/products/alerts/backend/destination_backfill.py+++ b/products/alerts/backend/destination_backfill.py@@ -24,8 +24,8 @@ from posthog.dataclasses import frozenfrom posthog.plugins.plugin_server_api import reload_hog_functions_on_workersfrom posthog.tasks.alerts.utils import INSIGHT_ALERT_FIRING_EVENT-from products.alerts.backend.insight_alert_destinations import INSIGHT_CHART_BLOCK, SLACK_TEMPLATE_ID-from products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.alerts.backend.logic.insight_alert_destinations import INSIGHT_CHART_BLOCK, SLACK_TEMPLATE_ID+from products.cdp.backend.facade.models import HogFunctionlogger = structlog.get_logger(__name__)diff --git a/products/alerts/backend/facade/api.py b/products/alerts/backend/facade/api.pyindex 1824c2bab7cd..27566fae7a97 100644--- a/products/alerts/backend/facade/api.py+++ b/products/alerts/backend/facade/api.py@@ -1,54 +1,31 @@+"""Facade for insight alerts.++Reads and writes other products need on the insight-alert model, in ids and plain values.+Destination configuration lives in `facade.destinations`, email in `facade.email`, the+lifecycle machine in `facade.lifecycle`, and scheduling math in `facade.scheduling`.+"""+import uuidfrom collections.abc import Collectionfrom datetime import datetime, timedelta-from typing import Any, Literal, cast+from typing import Final, Literalfrom zoneinfo import ZoneInfofrom django.db import transaction-from django.db.models import Prefetchfrom django.utils import timezoneimport structlog+from posthog.cdp.internal_events import LEGACY_INSIGHT_ALERT_EVENTfrom posthog.models.activity_logging.model_activity import ActingUserContextfrom posthog.models.user import Userfrom posthog.user_permissions import UserPermissionsfrom posthog.utils import relative_date_parsefrom products.access_control.backend.facade.user_access_control import UserAccessControl-from products.alerts.backend.destination_configs import (- DESTINATION_SPECS,- AlertDestinationData,- AlertDestinationValidationError,- DestinationType,- build_alert_destination_config,- validate_destination_data,-)-from products.alerts.backend.destinations import (- count_active_alert_destinations,- create_alert_destination_hog_functions,- list_alert_destination_groups,- owned_alert_destinations_qs,- redact_urls_in_name,- soft_delete_alert_destinations,- soft_delete_alert_destinations_for_alerts,- soft_delete_all_alert_destinations,-)-from products.alerts.backend.email_notifications import send_alert_email-from products.alerts.backend.insight_alert_destinations import (- INSIGHT_ALERT_DESTINATION_TYPES,- INSIGHT_ALERT_EVENT_IDS,- MAX_DESTINATION_IDS_PER_DELETE_REQUEST,- MAX_DESTINATIONS_PER_ALERT,- build_insight_alert_slack_config,-)+from products.alerts.backend.facade.contracts import DestinationTypefrom products.alerts.backend.insight_alert_state_machine import apply_snoozefrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration-from products.alerts.backend.presentation.views.alert_schedule_restriction import AlertScheduleRestriction-from products.alerts.backend.scheduling import (- validate_and_normalize_schedule_restriction,- validate_and_normalize_schedule_start_time,-)logger = structlog.get_logger(__name__)@@ -58,6 +35,15 @@ 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.@@ -85,21 +71,6 @@ def insight_ids_with_alerts(insight_ids: Collection[int]) -> set[int]:return set(AlertConfiguration.objects.filter(insight_id__in=insight_ids).values_list("insight_id", flat=True))-def insight_alerts_prefetch(to_attr: str) -> Prefetch:- """A ``Prefetch`` loading an insight's alerts in the shape ``serialize_insight_alerts`` needs.-- Callers add it to their insight queryset and read the alerts back off ``to_attr``. The- select_related/prefetch_related shape belongs here because it follows AlertSerializer:- that serializer emits threshold and subscribed_users per alert, so without them every- alert in the response costs two extra queries.- """- # Sets no team filter of its own: the prefetch is scoped by the insight queryset it is- # attached to, and an alert always belongs to its insight's team.- # nosemgrep: idor-lookup-without-team- queryset = AlertConfiguration.objects.select_related("created_by", "threshold").prefetch_related("subscribed_users")- return Prefetch("alertconfiguration_set", queryset=queryset, to_attr=to_attr)--def delete_insight_alerts(insight_ids: Collection[int]) -> None:"""Delete the alerts pointing at the given insights.@@ -114,20 +85,6 @@ def delete_insight_alerts(insight_ids: Collection[int]) -> None:alert.delete()-def serialize_insight_alerts(alerts: Collection[AlertConfiguration], context: dict[str, Any]) -> list[dict[str, Any]]:- """Render an insight's alerts for the insight API response.-- The insight API prefetches the alerts so the render costs no extra query, then hands them- back here — the alert JSON shape is this product's to define, not product_analytics'.- ``context`` is the calling serializer's DRF context.- """- # Deferred so the facade does not pull DRF onto its import path.- from products.alerts.backend.presentation.views.alert import AlertSerializer # noqa: PLC0415-- # `many=True` yields a ReturnList; the DRF stubs type `.data` as ReturnDict either way.- return cast(list[dict[str, Any]], AlertSerializer(alerts, many=True, context=context).data)--def snooze_alert_from_slack(alert_id: uuid.UUID, *, user: User, duration: str | None = None, until: datetime | None = None) -> SlackSnoozeOutcome:@@ -213,38 +170,3 @@ def snooze_alert_from_slack()return "snoozed"---__all__ = [- "DESTINATION_SPECS",- "INSIGHT_ALERT_DESTINATION_TYPES",- "INSIGHT_ALERT_EVENT_IDS",- "MAX_DESTINATIONS_PER_ALERT",- "MAX_DESTINATION_IDS_PER_DELETE_REQUEST",- "AlertDestinationData",- "AlertDestinationValidationError",- "AlertScheduleRestriction",- "DestinationType",- "SLACK_SNOOZE_MAX_DAYS",- "SlackSnoozeOutcome",- "build_alert_destination_config",- "build_insight_alert_slack_config",- "count_active_alert_destinations",- "create_alert_destination_hog_functions",- "delete_insight_alerts",- "get_alert_team_id",- "insight_alerts_prefetch",- "insight_ids_with_alerts",- "list_alert_destination_groups",- "owned_alert_destinations_qs",- "redact_urls_in_name",- "serialize_insight_alerts",- "snooze_alert_from_slack",- "soft_delete_alert_destinations",- "soft_delete_alert_destinations_for_alerts",- "soft_delete_all_alert_destinations",- "send_alert_email",- "validate_destination_data",- "validate_and_normalize_schedule_restriction",- "validate_and_normalize_schedule_start_time",-]diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.pynew file mode 100644index 000000000000..72c01e878adf--- /dev/null+++ b/products/alerts/backend/facade/contracts.py@@ -0,0 +1,127 @@+"""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 enum import StrEnum+from typing import Any, Final, NotRequired, TypedDict+from uuid import UUID++from posthog.dataclasses import frozen+++class DestinationType(StrEnum):+ SLACK = "slack"+ DISCORD = "discord"+ WEBHOOK = "webhook"+ TEAMS = "teams"++ @property+ def label(self) -> str:+ """Name for this type in a message a person reads."""+ return _DESTINATION_TYPE_LABELS[self]+++_DESTINATION_TYPE_LABELS: Final[dict[DestinationType, str]] = {+ DestinationType.SLACK: "Slack",+ DestinationType.DISCORD: "Discord",+ DestinationType.WEBHOOK: "Webhook",+ DestinationType.TEAMS: "Microsoft Teams",+}++# A type without a label would only surface as a KeyError inside a validation message a+# person reads, so a new member without one fails the import instead.+if _DESTINATION_TYPE_LABELS.keys() != set(DestinationType):+ raise RuntimeError("Every DestinationType needs an entry in _DESTINATION_TYPE_LABELS.")+++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 timestampdiff --git a/products/alerts/backend/delivery_slo.py b/products/alerts/backend/facade/delivery_slo.pysimilarity index 100%rename from products/alerts/backend/delivery_slo.pyrename to products/alerts/backend/facade/delivery_slo.pydiff --git a/products/alerts/backend/facade/destinations.py b/products/alerts/backend/facade/destinations.pynew file mode 100644index 000000000000..58bd6aaa1d10--- /dev/null+++ b/products/alerts/backend/facade/destinations.py@@ -0,0 +1,201 @@+"""Facade for alert notification destinations.++The only door other products use to configure, read, and dispatch alert destinations.+Everything here takes and returns contracts and ids; HogFunction rows, querysets and DRF+objects stay inside the product.+"""++from __future__ import annotations++from collections.abc import Collection, Sequence+from dataclasses import asdict+from datetime import datetime+from typing import Any, Final+from uuid import UUID++from posthog.kafka_client.client import ProduceResult++from ..logic import destination_configs, destinations, insight_alert_destinations+from .contracts import (+ ActiveAlertDestination,+ AlertDelivery,+ AlertDestinationConfig,+ AlertDestinationData,+ AlertDestinationGroup,+ DestinationType,+ EventKindSpec,+ OwnedAlertDestination,+)++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.+MAX_DESTINATIONS_PER_ALERT: Final = 5++# One destination is one HogFunction, so this only stops a malformed request becoming a huge query.+MAX_DESTINATION_IDS_PER_DELETE_REQUEST: Final = 100+++def destination_template_id(destination_type: DestinationType) -> str:+ """The HogFunction template one destination type is stored as."""+ return destination_configs.DESTINATION_SPECS[destination_type].template_id+++def redact_destination_data(data: AlertDestinationData) -> AlertDestinationData:+ """Drop the parts of a destination's configuration that are a credential."""+ return destination_configs.DESTINATION_SPECS[DestinationType(data["type"])].redact(data)+++def redact_urls_in_name(name: str) -> str:+ return destinations.redact_urls_in_name(name)+++def validate_destination_data(+ data: AlertDestinationData, *, allowed_destination_types: Sequence[DestinationType]+) -> None:+ """Raise `AlertDestinationValidationError` when the payload cannot become a destination."""+ destination_configs.validate_destination_data(data, allowed_destination_types=allowed_destination_types)+++def build_alert_destination_config(+ *,+ spec: EventKindSpec,+ alert_id: str,+ alert_name: str,+ data: AlertDestinationData,+ slack_context_elements: tuple[str, ...],+) -> AlertDestinationConfig:+ return destination_configs.build_alert_destination_config(+ spec=spec,+ alert_id=alert_id,+ alert_name=alert_name,+ data=data,+ slack_context_elements=slack_context_elements,+ )+++def build_insight_alert_slack_config(+ *, alert_id: str, alert_name: str | None, data: AlertDestinationData+) -> AlertDestinationConfig:+ return insight_alert_destinations.build_insight_alert_slack_config(+ alert_id=alert_id, alert_name=alert_name, data=data+ )+++def create_alert_destination_hog_functions(+ configs: list[AlertDestinationConfig],+ *,+ team_id: int,+ created_by_id: int,+ alert_id: str,+ allowed_event_ids: Collection[str],+) -> tuple[UUID, ...]:+ """Persist the configs as destinations for one alert and return the new ids."""+ return destinations.create_alert_destination_hog_functions(+ configs, team_id=team_id, created_by_id=created_by_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids+ )+++def soft_delete_alert_destinations(+ *, team_id: int, alert_id: str, allowed_event_ids: Collection[str], hog_function_ids: list[UUID]+) -> None:+ destinations.soft_delete_alert_destinations(+ team_id=team_id,+ alert_id=alert_id,+ allowed_event_ids=allowed_event_ids,+ hog_function_ids=hog_function_ids,+ )+++def soft_delete_all_alert_destinations(*, team_id: int, alert_id: str, allowed_event_ids: Collection[str]) -> int:+ return destinations.soft_delete_all_alert_destinations(+ team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids+ )+++def soft_delete_alert_destinations_for_alerts(+ *, team_id: int, alert_ids: Collection[str], allowed_event_ids: Collection[str]+) -> int:+ return destinations.soft_delete_alert_destinations_for_alerts(+ team_id=team_id, alert_ids=alert_ids, allowed_event_ids=allowed_event_ids+ )+++def list_alert_destination_groups(+ *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]+) -> list[AlertDestinationGroup]:+ """The destinations configured for one alert, one entry per destination a person added."""+ return destinations.list_alert_destination_groups(+ team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids+ )+++def list_owned_alert_destinations(+ *,+ team_id: int,+ alert_ids: Collection[str],+ allowed_event_ids: Collection[str],+ template_ids: Collection[str],+ enabled: bool,+) -> tuple[OwnedAlertDestination, ...]:+ return destinations.list_owned_alert_destinations(+ team_id=team_id,+ alert_ids=alert_ids,+ allowed_event_ids=allowed_event_ids,+ template_ids=template_ids,+ enabled=enabled,+ )+++def configured_destination_template_ids(+ *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]+) -> frozenset[str]:+ return destinations.configured_destination_template_ids(+ team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids+ )+++def count_active_alert_destinations(*, team_id: int, alert_id: str, allowed_event_ids: Collection[str]) -> int:+ return destinations.count_active_alert_destinations(+ team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids+ )+++def list_active_alert_destinations(+ *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]+) -> list[ActiveAlertDestination]:+ return destinations.list_active_alert_destinations(+ team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids+ )+++def serialize_deliveries(deliveries: Sequence[AlertDelivery]) -> list[dict[str, Any]]:+ """Delivery receipts in the shape an alert check stores them in."""+ return [asdict(delivery) for delivery in deliveries]+++def produce_alert_internal_event(+ *,+ team_id: int,+ event_name: str,+ properties: dict[str, Any],+ timestamp: datetime | None = None,+ uuid: str | None = None,+) -> ProduceResult | None:+ """Enqueue the internal event that makes the destinations for an alert fire."""+ return destinations.produce_alert_internal_event(+ team_id=team_id, event_name=event_name, properties=properties, timestamp=timestamp, uuid=uuid+ )+++def flush_alert_internal_events(timeout_seconds: float) -> None:+ destinations.flush_alert_internal_events(timeout_seconds)+++def alert_internal_event_delivered(+ produce_result: ProduceResult, *, team_id: int, alert_id: str, event_name: str+) -> bool:+ """Whether the broker acknowledged the event. This does not confirm the destination ran."""+ return destinations.alert_internal_event_delivered(+ produce_result, team_id=team_id, alert_id=alert_id, event_name=event_name+ )diff --git a/products/alerts/backend/email_notifications.py b/products/alerts/backend/facade/email.pysimilarity index 80%rename from products/alerts/backend/email_notifications.pyrename to products/alerts/backend/facade/email.pyindex fab4120f4b3a..fac5c65b3378 100644--- a/products/alerts/backend/email_notifications.py+++ b/products/alerts/backend/facade/email.py@@ -1,3 +1,7 @@+"""Facade for alert email notifications."""++from __future__ import annotations+from collections.abc import Collectionfrom posthog.email import EmailMessage@@ -11,6 +15,7 @@ def send_alert_email(template_name: str,template_context: dict[str, object],) -> None:+ """Send one alert email to every recipient."""message = EmailMessage(campaign_key=campaign_key,subject=subject,diff --git a/products/alerts/backend/state_machine.py b/products/alerts/backend/facade/lifecycle.pysimilarity index 100%rename from products/alerts/backend/state_machine.pyrename to products/alerts/backend/facade/lifecycle.pydiff --git a/products/alerts/backend/scheduling.py b/products/alerts/backend/facade/scheduling.pysimilarity index 100%rename from products/alerts/backend/scheduling.pyrename to products/alerts/backend/facade/scheduling.pydiff --git a/products/alerts/backend/insight_alert_state_machine.py b/products/alerts/backend/insight_alert_state_machine.pyindex 414dd90416cc..88112f6e3f49 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_CHECKINGfrom posthog.schema_enums import AlertState as InsightAlertState-from products.alerts.backend.state_machine import (+from products.alerts.backend.facade.lifecycle import (AlertCheckOutcome,AlertPolicy,AlertSnapshot,diff --git a/products/alerts/backend/logic/__init__.py b/products/alerts/backend/logic/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/alerts/backend/destination_configs.py b/products/alerts/backend/logic/destination_configs.pysimilarity index 87%rename from products/alerts/backend/destination_configs.pyrename to products/alerts/backend/logic/destination_configs.pyindex 883245b0f71e..ae7f4b3c369b 100644--- a/products/alerts/backend/destination_configs.py+++ b/products/alerts/backend/logic/destination_configs.py@@ -4,69 +4,23 @@ from __future__ import annotationsfrom abc import ABC, abstractmethodfrom collections.abc import Sequence-from dataclasses import dataclass-from typing import Any, ClassVar, NotRequired, TypedDict+from typing import Any, ClassVarfrom urllib.parse import urlsplit-from django.db import models---class DestinationType(models.TextChoices):- 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):- def __init__(self, message: str, *, field: str | None = None) -> None:- self.message = message- self.field = field- super().__init__(message)-+from products.alerts.backend.facade.contracts import (+ AlertDestinationAction,+ AlertDestinationConfig,+ AlertDestinationData,+ AlertDestinationValidationError,+ DestinationType,+ EventKindSpec,+)WEBHOOK_HEADERS = {"Content-Type": "application/json", "X-PostHog-Webhook-Version": "1"}_HOG_FUNCTION_NAME_MAX_LEN = 400-@dataclass(frozen=True)-class AlertDestinationConfig:- team: Any- payload: dict[str, Any]---@dataclass(frozen=True)-class AlertDestinationAction:- url: str- label: str---@dataclass(frozen=True)-class EventKindSpec:- 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}".'--def clip_hog_function_name(name: str) -> str:if len(name) <= _HOG_FUNCTION_NAME_MAX_LEN:return name@@ -338,7 +292,6 @@ def validate_destination_data(def build_alert_destination_config(*,- team: Any,spec: EventKindSpec,alert_id: str,alert_name: str,@@ -350,7 +303,6 @@ def build_alert_destination_config(destination_name = destination_spec.build_name(data)return AlertDestinationConfig(- team=team,payload={"type": "internal_destination","enabled": True,diff --git a/products/alerts/backend/destinations.py b/products/alerts/backend/logic/destinations.pysimilarity index 81%rename from products/alerts/backend/destinations.pyrename to products/alerts/backend/logic/destinations.pyindex 4038cd67c393..7a6a982e3047 100644--- a/products/alerts/backend/destinations.py+++ b/products/alerts/backend/logic/destinations.py@@ -3,8 +3,7 @@from __future__ import annotationsimport re-from collections.abc import Collection, Sequence-from dataclasses import asdict, dataclass+from collections.abc import Collectionfrom datetime import datetimefrom typing import Any, NamedTuple, castfrom urllib.parse import urlsplit@@ -16,25 +15,26 @@ from django.db.models import Q, QuerySetimport structlogimport posthoganalyticsfrom prometheus_client import Counter-from rest_framework.exceptions import ValidationErrorfrom posthog.cdp.internal_events import InternalEventEvent, flush_internal_events_producer, produce_internal_eventfrom posthog.exceptions_capture import capture_exceptionfrom posthog.kafka_client.client import ProduceResultfrom posthog.plugins.plugin_server_api import reload_hog_functions_on_workers-from products.alerts.backend.destination_configs import (- SPEC_BY_TEMPLATE_ID,+from products.alerts.backend.facade.contracts import (+ ActiveAlertDestination,AlertDestinationConfig,AlertDestinationData,+ AlertDestinationGroup,+ AlertDestinationValidationError,+ OwnedAlertDestination,)-from products.cdp.backend.api.hog_function import HogFunctionSerializer-from products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.alerts.backend.logic.destination_configs import SPEC_BY_TEMPLATE_ID+from products.cdp.backend.facade.api import create_hog_functions+from products.cdp.backend.facade.models import HogFunctionlogger = structlog.get_logger(__name__)-ALERT_NOTIFICATION_FLUSH_TIMEOUT_SECONDS = 10.0-ALERT_INTERNAL_EVENT_DELIVERY_FAILURES = Counter("posthog_alert_internal_event_delivery_failures_total","Number of alert internal events that failed delivery",@@ -42,30 +42,6 @@ ALERT_INTERNAL_EVENT_DELIVERY_FAILURES = Counter()-@dataclass(frozen=True, kw_only=True)-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---def serialize_deliveries(deliveries: Sequence[AlertDelivery]) -> list[dict[str, Any]]:- return [asdict(delivery) for delivery in deliveries]---@dataclass(frozen=True, kw_only=True)-class ActiveAlertDestination:- id: str- name: str- destination_type: str | None--class AlertDestinationGroupKey(NamedTuple):template_id: strconfig: tuple[tuple[str, Any], ...] | None@@ -81,13 +57,6 @@ class AlertDestinationRow(NamedTuple):inputs: dict[str, Any] | None-@dataclass(frozen=True, kw_only=True)-class AlertDestinationGroup:- hog_function_ids: tuple[UUID, ...]- data: AlertDestinationData- fully_enabled: bool--def alert_destination_group_key(*, template_id: str, inputs: dict[str, Any] | None) -> AlertDestinationGroupKey:spec = SPEC_BY_TEMPLATE_ID.get(template_id)if spec is None:@@ -158,6 +127,50 @@ def owned_alert_destinations_qs()+def list_owned_alert_destinations(+ *,+ team_id: int,+ alert_ids: Collection[str],+ allowed_event_ids: Collection[str],+ template_ids: Collection[str],+ enabled: bool,+) -> tuple[OwnedAlertDestination, ...]:+ """Alert-owned destination rows, without their stored inputs.++ `inputs` is several KB per row and is what a caller listing many alerts must not pay+ for, so this read stops at the columns a caller needs to tell one destination from+ another.+ """+ queryset = owned_alert_destinations_qs(+ team_id=team_id, alert_ids=alert_ids, allowed_event_ids=allowed_event_ids+ ).filter(template_id__in=list(template_ids), enabled=enabled)+ return tuple(+ OwnedAlertDestination(+ hog_function_id=hog_function_id,+ template_id=template_id,+ filters=filters if isinstance(filters, dict) else None,+ )+ for hog_function_id, template_id, filters in queryset.values_list("id", "template_id", "filters")+ )+++def configured_destination_template_ids(+ *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]+) -> frozenset[str]:+ """The distinct HogFunction templates one alert has a destination for.++ One indexed column with DISTINCT, because a list serializer runs this once per alert and+ reading whole rows would pull their stored inputs, several KB each.+ """+ template_ids = (+ owned_alert_destinations_qs(team_id=team_id, alert_ids=[alert_id], allowed_event_ids=allowed_event_ids)+ .values_list("template_id", flat=True)+ .distinct()+ )+ # The queryset filters template_id__in, so no row it returns has a null template.+ return frozenset(cast(Collection[str], template_ids))++def _active_alert_destinations_qs(*, team_id: int, alert_id: str, allowed_event_ids: Collection[str]) -> QuerySet[HogFunction]:@@ -190,41 +203,38 @@ def _raise_if_alert_already_has_these_destination_configs(alert_destination_group_key(template_id=template_id or "", inputs=inputs) in readable_keysfor template_id, inputs in stored_rows):- raise ValidationError("This destination is already configured for this alert.")+ raise AlertDestinationValidationError("This destination is already configured for this alert.")def create_alert_destination_hog_functions(- configs: list[AlertDestinationConfig], *, request: Any, alert_id: str, allowed_event_ids: Collection[str]-) -> list[HogFunction]:+ configs: list[AlertDestinationConfig],+ *,+ team_id: int,+ created_by_id: int,+ alert_id: str,+ allowed_event_ids: Collection[str],+) -> tuple[UUID, ...]:+ """Persist one HogFunction per config and return their ids.++ Every config belongs to `team_id`; the caller builds them for one alert at a time.+ """if not configs:- return []- created: list[HogFunction] = []- hog_function_ids_by_team: dict[int, list[UUID]] = {}+ return ()with transaction.atomic():_raise_if_alert_already_has_these_destination_configs(- team_id=configs[0].team.id,+ team_id=team_id,alert_id=alert_id,allowed_event_ids=allowed_event_ids,configs=configs,)- for config in configs:- team = config.team- serializer = HogFunctionSerializer(- data=config.payload,- context={- "request": request,- "get_team": lambda team=team: team,- "is_create": True,- "allow_managed_alert_destination": True,- },- )- serializer.is_valid(raise_exception=True)- hog_function = serializer.save(team=team)- created.append(hog_function)- hog_function_ids_by_team.setdefault(team.id, []).append(hog_function.id)- for team_id, hog_function_ids in hog_function_ids_by_team.items():- _reload_hog_functions_after_commit(team_id=team_id, hog_function_ids=hog_function_ids)- return created+ created_ids = create_hog_functions(+ [config.payload for config in configs],+ team_id=team_id,+ created_by_id=created_by_id,+ allow_managed_alert_destination=True,+ )+ _reload_hog_functions_after_commit(team_id=team_id, hog_function_ids=created_ids)+ return tuple(created_ids)def _report_unreadable_destination_configs(@@ -278,12 +288,9 @@ def soft_delete_alert_destinations(invalid_ids = unique_ids - owned_idsif invalid_ids:formatted_ids = ", ".join(str(hog_function_id) for hog_function_id in sorted(invalid_ids, key=str))- raise ValidationError(- {- "hog_function_ids": [- f"These HogFunctions do not belong to this alert: {formatted_ids}. Refresh the alert and try again."- ]- }+ raise AlertDestinationValidationError(+ f"These HogFunctions do not belong to this alert: {formatted_ids}. Refresh the alert and try again.",+ field="hog_function_ids",)_report_unreadable_destination_configs(team_id=team_id, alert_id=alert_id, rows=owned_rows)@@ -296,7 +303,7 @@ def soft_delete_alert_destinations(if group_key.is_config_readableelse "Some destinations of this type have settings that can no longer be read. To delete any of them, remove every destination of this type together.")- raise ValidationError({"hog_function_ids": [message]})+ raise AlertDestinationValidationError(message, field="hog_function_ids")HogFunction.objects.filter(team_id=team_id, id__in=unique_ids).update(deleted=True, enabled=False)_reload_hog_functions_after_commit(team_id=team_id, hog_function_ids=unique_ids)diff --git a/products/alerts/backend/insight_alert_destinations.py b/products/alerts/backend/logic/insight_alert_destinations.pysimilarity index 81%rename from products/alerts/backend/insight_alert_destinations.pyrename to products/alerts/backend/logic/insight_alert_destinations.pyindex ba16141c197b..236dbfa533cb 100644--- a/products/alerts/backend/insight_alert_destinations.py+++ b/products/alerts/backend/logic/insight_alert_destinations.py@@ -12,30 +12,13 @@ from typing import Any, Finalfrom posthog.cdp.internal_events import LEGACY_INSIGHT_ALERT_EVENT-from products.alerts.backend.destination_configs import (+from products.alerts.backend.facade.contracts import AlertDestinationConfig, AlertDestinationData, DestinationType+from products.alerts.backend.logic.destination_configs import (DESTINATION_SPECS,- AlertDestinationConfig,- AlertDestinationData,- DestinationType,clip_hog_function_name,destination_filter,)-# 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, which imports this one.-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,)--# Each destination is another message every time the alert fires, so a caller in a loop is capped.-MAX_DESTINATIONS_PER_ALERT: Final = 5--# One destination is one HogFunction, so this only stops a malformed request becoming a huge query.-MAX_DESTINATION_IDS_PER_DELETE_REQUEST: Final = 100-SLACK_TEMPLATE_ID: Final = DESTINATION_SPECS[DestinationType.SLACK].template_id# A hog template that is a single {…} expression resolves to the expression's raw value, so this@@ -119,11 +102,10 @@ def _slack_blocks() -> list[Any]:def build_insight_alert_slack_config(- *, team: Any, alert_id: str, alert_name: str | None, data: AlertDestinationData+ *, alert_id: str, alert_name: str | None, data: AlertDestinationData) -> AlertDestinationConfig:channel_name = data.get("slack_channel_name") or "channel"return AlertDestinationConfig(- team=team,payload={"type": "internal_destination","enabled": True,diff --git a/products/alerts/backend/presentation/views/alert.py b/products/alerts/backend/presentation/views/alert.pyindex 74ce0bce34d9..37e10496c56c 100644--- a/products/alerts/backend/presentation/views/alert.py+++ b/products/alerts/backend/presentation/views/alert.py@@ -36,6 +36,7 @@ from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializerfrom posthog.email import is_email_availablefrom posthog.event_usage import get_request_analytics_properties+from posthog.exceptions import as_drf_validation_errorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.trigram_search import (MAX_SEARCH_LENGTH,@@ -67,21 +68,22 @@ from products.alerts.backend.evaluation.validation import (should_default_check_ongoing_interval,validate_alert_config,)-from products.alerts.backend.facade.api import (- INSIGHT_ALERT_DESTINATION_TYPES,- INSIGHT_ALERT_EVENT_IDS,- MAX_DESTINATION_IDS_PER_DELETE_REQUEST,- MAX_DESTINATIONS_PER_ALERT,+from products.alerts.backend.facade.api import INSIGHT_ALERT_DESTINATION_TYPES, INSIGHT_ALERT_EVENT_IDS+from products.alerts.backend.facade.contracts import (AlertDestinationData,AlertDestinationValidationError,DestinationType,+)+from products.alerts.backend.facade.destinations import (+ MAX_DESTINATION_IDS_PER_DELETE_REQUEST,+ MAX_DESTINATIONS_PER_ALERT,build_insight_alert_slack_config,count_active_alert_destinations,create_alert_destination_hog_functions,soft_delete_alert_destinations,- validate_and_normalize_schedule_start_time,validate_destination_data,)+from products.alerts.backend.facade.scheduling import validate_and_normalize_schedule_start_timefrom products.alerts.backend.insight_alert_state_machine import (apply_disable,apply_enable,@@ -90,7 +92,7 @@ from products.alerts.backend.insight_alert_state_machine import (apply_unsnooze,)from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold-from products.alerts.backend.presentation.views.alert_schedule_restriction import AlertScheduleRestriction+from products.alerts.backend.presentation.views.schedule_restriction import AlertScheduleRestrictionfrom products.product_analytics.backend.facade.models import Insight, resolve_insight_by_id_or_short_id@@ -1465,16 +1467,16 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):f"This alert already has {MAX_DESTINATIONS_PER_ALERT} destinations. Remove one to add another.")- hog_functions = create_alert_destination_hog_functions(- [- build_insight_alert_slack_config(- team=alert.team, alert_id=str(alert.id), alert_name=alert.name, data=data- )- ],- request=self.request,- alert_id=str(alert.id),- allowed_event_ids=INSIGHT_ALERT_EVENT_IDS,- )+ try:+ hog_function_ids = create_alert_destination_hog_functions(+ [build_insight_alert_slack_config(alert_id=str(alert.id), alert_name=alert.name, data=data)],+ team_id=alert.team_id,+ created_by_id=request.user.id,+ alert_id=str(alert.id),+ allowed_event_ids=INSIGHT_ALERT_EVENT_IDS,+ )+ except AlertDestinationValidationError as error:+ raise as_drf_validation_error(error)posthoganalytics.capture(distinct_id=str(request.user.distinct_id),@@ -1486,7 +1488,7 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"type": data["type"],},)- response = AlertDestinationResponseSerializer({"hog_function_ids": [hf.id for hf in hog_functions]})+ response = AlertDestinationResponseSerializer({"hog_function_ids": list(hog_function_ids)})return Response(response.data, status=status.HTTP_201_CREATED)@extend_schema(@@ -1501,12 +1503,15 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):serializer.is_valid(raise_exception=True)hog_function_ids = serializer.validated_data["hog_function_ids"]- soft_delete_alert_destinations(- team_id=self.team_id,- alert_id=str(alert.id),- allowed_event_ids=INSIGHT_ALERT_EVENT_IDS,- hog_function_ids=hog_function_ids,- )+ try:+ soft_delete_alert_destinations(+ team_id=self.team_id,+ alert_id=str(alert.id),+ allowed_event_ids=INSIGHT_ALERT_EVENT_IDS,+ hog_function_ids=hog_function_ids,+ )+ except AlertDestinationValidationError as error:+ raise as_drf_validation_error(error)posthoganalytics.capture(distinct_id=str(request.user.distinct_id),diff --git a/products/alerts/backend/presentation/views/insight_alerts.py b/products/alerts/backend/presentation/views/insight_alerts.pynew file mode 100644index 000000000000..a6c2fe29cbb2--- /dev/null+++ b/products/alerts/backend/presentation/views/insight_alerts.py@@ -0,0 +1,40 @@+"""The alert data the insight API embeds in its own response."""++from __future__ import annotations++from collections.abc import Collection+from typing import Any, cast++from django.db.models import Prefetch++from products.alerts.backend.models.alert import AlertConfiguration+++def insight_alerts_prefetch(to_attr: str) -> Prefetch:+ """A ``Prefetch`` loading an insight's alerts in the shape ``serialize_insight_alerts`` needs.++ Callers add it to their insight queryset and read the alerts back off ``to_attr``. The+ select_related/prefetch_related shape belongs here because it follows AlertSerializer:+ that serializer emits threshold and subscribed_users per alert, so without them every+ alert in the response costs two extra queries.+ """+ # Sets no team filter of its own: the prefetch is scoped by the insight queryset it is+ # attached to, and an alert always belongs to its insight's team.+ # nosemgrep: idor-lookup-without-team+ queryset = AlertConfiguration.objects.select_related("created_by", "threshold").prefetch_related("subscribed_users")+ return Prefetch("alertconfiguration_set", queryset=queryset, to_attr=to_attr)+++def serialize_insight_alerts(alerts: Collection[AlertConfiguration], context: dict[str, Any]) -> list[dict[str, Any]]:+ """Render an insight's alerts for the insight API response.++ The insight API prefetches the alerts so the render costs no extra query, then hands them+ back here — the alert JSON shape is this product's to define, not product_analytics'.+ ``context`` is the calling serializer's DRF context.+ """+ # Deferred: the insight API imports this module and `alert` imports the insight API, so+ # the three form an import loop that only a deferred edge keeps open.+ from products.alerts.backend.presentation.views.alert import AlertSerializer # noqa: PLC0415++ # `many=True` yields a ReturnList; the DRF stubs type `.data` as ReturnDict either way.+ return cast(list[dict[str, Any]], AlertSerializer(alerts, many=True, context=context).data)diff --git a/products/alerts/backend/presentation/views/alert_schedule_restriction.py b/products/alerts/backend/presentation/views/schedule_restriction.pysimilarity index 82%rename from products/alerts/backend/presentation/views/alert_schedule_restriction.pyrename to products/alerts/backend/presentation/views/schedule_restriction.pyindex 0b4a64280c82..6634a2691872 100644--- a/products/alerts/backend/presentation/views/alert_schedule_restriction.py+++ b/products/alerts/backend/presentation/views/schedule_restriction.py@@ -1,4 +1,9 @@-"""Pydantic OpenAPI types for alert quiet hours (schedule_restriction JSONField)."""+"""Pydantic OpenAPI types for alert quiet hours (schedule_restriction JSONField).++Adopter products reuse them to describe the same JSON field on their own alert APIs.+They carry drf-spectacular meaning rather than data a consumer reads, so they sit on the+presentation surface, not in the facade.+"""from __future__ import annotationsdiff --git a/products/alerts/backend/temporal/schedule.py b/products/alerts/backend/temporal/schedule.pyindex a5cc283a904f..12f7fbd3a625 100644--- a/products/alerts/backend/temporal/schedule.py+++ b/products/alerts/backend/temporal/schedule.py@@ -33,6 +33,7 @@ async def create_alerts_product_check_due_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)schedule.state = description.schedule.stateawait a_update_schedule(client, SCHEDULE_ID, schedule)else:diff --git a/products/alerts/backend/test/test_delivery_slo.py b/products/alerts/backend/test/test_delivery_slo.pyindex 1dfc5998d3ff..1f7ce8e4275f 100644--- a/products/alerts/backend/test/test_delivery_slo.py+++ b/products/alerts/backend/test/test_delivery_slo.py@@ -2,10 +2,10 @@ from unittest.mock import MagicMock, patchfrom posthog.slo.types import SloOperation, SloOutcome-from products.alerts.backend.delivery_slo import alert_delivery_slo+from products.alerts.backend.facade.delivery_slo import alert_delivery_slo-@patch("products.alerts.backend.delivery_slo.get_instance_region", return_value="EU")+@patch("products.alerts.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_destination_backfill.py b/products/alerts/backend/test/test_destination_backfill.pyindex 18b6a013bb5f..9c5fc7e6ea08 100644--- a/products/alerts/backend/test/test_destination_backfill.py+++ b/products/alerts/backend/test/test_destination_backfill.py@@ -14,7 +14,7 @@ from products.alerts.backend.destination_backfill import (backfill_insight_alert_chart_blocks,blocks_with_chart,)-from products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.cdp.backend.facade.models import HogFunctionHEADER_BLOCK = {"type": "header", "text": {"type": "plain_text", "text": "Alert firing"}}CONTEXT_BLOCK = {"type": "context", "elements": [{"type": "mrkdwn", "text": "Project"}]}diff --git a/products/alerts/backend/test/test_destination_configs.py b/products/alerts/backend/test/test_destination_configs.pyindex 4b12d9fcfdcb..3c2e5795ba38 100644--- a/products/alerts/backend/test/test_destination_configs.py+++ b/products/alerts/backend/test/test_destination_configs.py@@ -4,12 +4,14 @@ import pytestfrom posthog.cdp.templates import HOG_FUNCTION_TEMPLATES-from products.alerts.backend.destination_configs import (- DESTINATION_SPECS,+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,@@ -25,6 +27,16 @@ DEFAULT_SPEC = EventKindSpec(webhook_body={},)+MULTI_DETAIL_SPEC = EventKindSpec(+ event_id="$insight_alert_broken",+ display_kind="broken",+ header="Insight alert broken",+ details=(("Reason", "5 consecutive check failures."), ("Last error", "Query is too expensive.")),+ primary_action_url="https://example.com/insight",+ primary_action_label="View insight",+ webhook_body={},+)+PROSE_SPEC = EventKindSpec(event_id="$insight_alert_firing",display_kind="firing",@@ -62,6 +74,23 @@ class TestSpecVocabularyRendering:assert "Pageviews is 42, breaching 30" in textassert "[View insight](https://example.com/insight) · [Manage alert](https://example.com/alert)" in text+ def test_slack_renders_one_line_per_detail(self) -> None:+ blocks = slack_blocks(MULTI_DETAIL_SPEC, context_elements=())++ section = next(b for b in blocks if b["type"] == "section")+ assert section["text"]["text"] == (+ "*Reason:* 5 consecutive check failures.\n*Last error:* Query is too expensive."+ )++ def test_teams_separates_details_with_one_blank_line(self) -> None:+ text = teams_text(MULTI_DETAIL_SPEC)++ assert "**Reason:** 5 consecutive check failures.\n\n**Last error:** Query is too expensive." in text+ # An Adaptive Card paragraph break is exactly one blank line; stacked ones render as gaps.+ assert "\n\n\n" not in text+ # Every asterisk belongs to a `**` pair. A Slack single-asterisk bold renders literally here.+ assert "*" not in text.replace("**", "")+def test_defaults_render_single_button_and_details_only(self) -> None:blocks = slack_blocks(DEFAULT_SPEC, context_elements=())actions = next(b for b in blocks if b["type"] == "actions")@@ -98,7 +127,6 @@ class TestDestinationTemplateContract:template = _TEMPLATES_BY_ID[DESTINATION_SPECS[destination_type].template_id]data = _DESTINATION_DATA[destination_type]config = build_alert_destination_config(- team=None,spec=DEFAULT_SPEC,alert_id="alert-1",alert_name="Signups",@@ -118,7 +146,6 @@ class TestDestinationTemplateContract:"slack_channel_name": "eng",}config = build_alert_destination_config(- team=None,spec=DEFAULT_SPEC,alert_id="alert-1",alert_name="Signups",diff --git a/products/alerts/backend/test/test_destinations.py b/products/alerts/backend/test/test_destinations.pyindex 4af8743e0d9a..3586fe164370 100644--- a/products/alerts/backend/test/test_destinations.py+++ b/products/alerts/backend/test/test_destinations.py@@ -5,35 +5,38 @@ import pytestfrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch+from django.test import SimpleTestCase+from parameterized import parameterized-from rest_framework.exceptions import ValidationErrorfrom posthog.models.team.team import Team-from products.alerts.backend.destination_configs import (- DESTINATION_SPECS,+from products.alerts.backend.facade.contracts import (+ AlertDelivery,AlertDestinationConfig,AlertDestinationData,+ AlertDestinationValidationError,DestinationType,EventKindSpec,- build_alert_destination_config,)-from products.alerts.backend.destinations import (+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 (SPEC_BY_TEMPLATE_ID,- AlertDelivery,AlertDestinationGroupKey,AlertDestinationRow,_raise_if_alert_already_has_these_destination_configs,alert_destination_group_key,alert_internal_event_delivered,+ flush_alert_internal_events,group_alert_destination_rows,list_active_alert_destinations,+ produce_alert_internal_event,redact_urls_in_name,- serialize_deliveries,soft_delete_alert_destinations,soft_delete_all_alert_destinations,)-from products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.cdp.backend.facade.models import HogFunctionALLOWED_EVENT_IDS = ("$logs_alert_firing",@@ -126,7 +129,6 @@ class AlertDestinationTestCase(APIBaseTest):def _config_for(destination_type: DestinationType, event_id: str) -> AlertDestinationConfig:return build_alert_destination_config(- team=None,spec=EventKindSpec(event_id=event_id,display_kind=event_id,@@ -224,7 +226,7 @@ class TestRaiseIfAlertAlreadyHasTheseDestinationConfigs(AlertDestinationTestCasealert_id=alert_id,allowed_event_ids=ALLOWED_EVENT_IDS,configs=[- AlertDestinationConfig(team=self.team, payload={"template_id": template_id, "inputs": inputs})+ AlertDestinationConfig(payload={"template_id": template_id, "inputs": inputs})for template_id, inputs in configs],)@@ -232,7 +234,7 @@ class TestRaiseIfAlertAlreadyHasTheseDestinationConfigs(AlertDestinationTestCasedef test_rejects_a_destination_whose_config_already_exists(self) -> None:self._make_group(template_id="template-webhook", alert_id="alert-1", inputs=webhook_inputs("https://a"))- with self.assertRaisesRegex(ValidationError, "already configured for this alert"):+ with self.assertRaisesRegex(AlertDestinationValidationError, "already configured for this alert"):self._raise_if_exists(configs=[("template-webhook", webhook_inputs("https://a"))])def test_allows_a_second_destination_with_a_different_config(self) -> None:@@ -257,7 +259,7 @@ class TestRaiseIfAlertAlreadyHasTheseDestinationConfigs(AlertDestinationTestCasedestinations = self._make_group(template_id="template-slack", alert_id="alert-1", inputs=slack_inputs("C-ENG"))HogFunction.objects.filter(id__in=[destination.id for destination in destinations]).update(enabled=False)- with self.assertRaisesRegex(ValidationError, "already configured for this alert"):+ with self.assertRaisesRegex(AlertDestinationValidationError, "already configured for this alert"):self._raise_if_exists(configs=[("template-slack", slack_inputs("C-ENG"))])def test_allows_a_destination_whose_config_cannot_be_read(self) -> None:@@ -268,7 +270,7 @@ class TestRaiseIfAlertAlreadyHasTheseDestinationConfigs(AlertDestinationTestCasedef test_rejects_a_duplicate_that_is_not_the_first_config_in_the_call(self) -> None:self._make_group(template_id="template-webhook", alert_id="alert-1", inputs=webhook_inputs("https://a"))- with self.assertRaisesRegex(ValidationError, "already configured for this alert"):+ with self.assertRaisesRegex(AlertDestinationValidationError, "already configured for this alert"):self._raise_if_exists(configs=[("template-slack", slack_inputs("C-NEW")),@@ -299,7 +301,7 @@ class TestSoftDeleteAlertDestinations(AlertDestinationTestCase):def test_rejects_partial_destination_group(self) -> None:destinations = self._make_group(template_id="template-slack", alert_id="alert-1")- with self.assertRaisesRegex(ValidationError, "Delete all destinations in this group"):+ with self.assertRaisesRegex(AlertDestinationValidationError, "Delete all destinations in this group"):soft_delete_alert_destinations(team_id=self.team.id,alert_id="alert-1",@@ -364,7 +366,7 @@ class TestSoftDeleteAlertDestinations(AlertDestinationTestCase):destinations = self._make_group(template_id="template-slack", alert_id="alert-1")HogFunction.objects.filter(id=destinations[0].id).update(enabled=False)- with self.assertRaisesRegex(ValidationError, "Delete all destinations in this group"):+ with self.assertRaisesRegex(AlertDestinationValidationError, "Delete all destinations in this group"):soft_delete_alert_destinations(team_id=self.team.id,alert_id="alert-1",@@ -389,7 +391,7 @@ class TestSoftDeleteAlertDestinations(AlertDestinationTestCase):first = self._make_group(template_id="template-slack", alert_id="alert-1", inputs=slack_inputs("C-ENG"))second = self._make_group(template_id="template-slack", alert_id="alert-1", inputs=slack_inputs("C-OPS"))- with self.assertRaisesRegex(ValidationError, "Delete all destinations in this group"):+ with self.assertRaisesRegex(AlertDestinationValidationError, "Delete all destinations in this group"):soft_delete_alert_destinations(team_id=self.team.id,alert_id="alert-1",@@ -420,7 +422,7 @@ class TestSoftDeleteAlertDestinations(AlertDestinationTestCase):template_id="template-webhook", alert_id="alert-1", inputs=webhook_inputs("https://x"))- with self.assertRaisesRegex(ValidationError, "Delete all destinations in this group"):+ with self.assertRaisesRegex(AlertDestinationValidationError, "Delete all destinations in this group"):soft_delete_alert_destinations(team_id=self.team.id,alert_id="alert-1",@@ -434,7 +436,7 @@ class TestSoftDeleteAlertDestinations(AlertDestinationTestCase):orphan = self._make_hog_function(template_id="template-slack", alert_id="alert-1", inputs={})destinations = self._make_group(template_id="template-slack", alert_id="alert-1")- with self.assertRaisesRegex(ValidationError, "can no longer be read"):+ with self.assertRaisesRegex(AlertDestinationValidationError, "can no longer be read"):soft_delete_alert_destinations(team_id=self.team.id,alert_id="alert-1",@@ -448,7 +450,7 @@ class TestSoftDeleteAlertDestinations(AlertDestinationTestCase):orphan = self._make_hog_function(template_id="template-slack", alert_id="alert-1", inputs={})destinations = self._make_group(template_id="template-slack", alert_id="alert-1")- with self.assertRaisesRegex(ValidationError, "can no longer be read"):+ with self.assertRaisesRegex(AlertDestinationValidationError, "can no longer be read"):soft_delete_alert_destinations(team_id=self.team.id,alert_id="alert-1",@@ -485,8 +487,8 @@ class TestSoftDeleteAlertDestinations(AlertDestinationTestCase):self._assert_deleted(webhooks)self._assert_intact([orphan])- @patch("products.alerts.backend.destinations.logger")- @patch("products.alerts.backend.destinations.posthoganalytics.capture")+ @patch("products.alerts.backend.logic.destinations.logger")+ @patch("products.alerts.backend.logic.destinations.posthoganalytics.capture")def test_unreadable_config_is_captured_and_logged(self, capture, logger) -> None:self._make_hog_function(template_id="template-slack", alert_id="alert-1", inputs={})webhooks = self._make_group(template_id="template-webhook", alert_id="alert-1")@@ -516,7 +518,7 @@ class TestSoftDeleteAlertDestinations(AlertDestinationTestCase):destinations = self._make_group(template_id="template-slack", alert_id="alert-1")other_alert = self._make_group(template_id="template-slack", alert_id="alert-2")- with self.assertRaisesRegex(ValidationError, "do not belong to this alert"):+ with self.assertRaisesRegex(AlertDestinationValidationError, "do not belong to this alert"):soft_delete_alert_destinations(team_id=self.team.id,alert_id="alert-1",@@ -530,7 +532,7 @@ class TestSoftDeleteAlertDestinations(AlertDestinationTestCase):other_team = Team.objects.create(organization=self.organization, name="Other")other_team_destinations = self._make_group(template_id="template-slack", alert_id="alert-1", team=other_team)- with self.assertRaisesRegex(ValidationError, "do not belong to this alert"):+ with self.assertRaisesRegex(AlertDestinationValidationError, "do not belong to this alert"):soft_delete_alert_destinations(team_id=self.team.id,alert_id="alert-1",@@ -557,7 +559,7 @@ class TestSoftDeleteAlertDestinations(AlertDestinationTestCase):destinations = self._make_group(template_id="template-slack", alert_id="alert-1")other = self._make_hog_function(template_id="template-webhook", alert_id="alert-1", event_id="$unrelated_event")- with self.assertRaises(ValidationError) as error:+ with self.assertRaises(AlertDestinationValidationError) as error:soft_delete_alert_destinations(team_id=self.team.id,alert_id="alert-1",@@ -565,10 +567,8 @@ class TestSoftDeleteAlertDestinations(AlertDestinationTestCase):hog_function_ids=[destinations[0].id, other.id],)- assert isinstance(error.exception.detail, dict)- hog_function_id_errors = error.exception.detail["hog_function_ids"]- assert isinstance(hog_function_id_errors, list)- assert str(hog_function_id_errors[0]) == (+ assert error.exception.field == "hog_function_ids"+ assert error.exception.message == (f"These HogFunctions do not belong to this alert: {other.id}. Refresh the alert and try again.")self._assert_intact([*destinations, other])@@ -598,7 +598,7 @@ class TestSoftDeleteAlertDestinations(AlertDestinationTestCase):self._assert_intact(destinations)- @patch("products.alerts.backend.destinations.reload_hog_functions_on_workers")+ @patch("products.alerts.backend.logic.destinations.reload_hog_functions_on_workers")def test_reload_happens_after_destination_delete_commits(self, reload_hog_functions_on_workers) -> None:destinations = self._make_group(template_id="template-slack", alert_id="alert-1")@@ -615,7 +615,9 @@ class TestSoftDeleteAlertDestinations(AlertDestinationTestCase):team_id=self.team.id, hog_function_ids=sorted(str(destination.id) for destination in destinations))- @patch("products.alerts.backend.destinations.reload_hog_functions_on_workers", side_effect=RuntimeError("boom"))+ @patch(+ "products.alerts.backend.logic.destinations.reload_hog_functions_on_workers", side_effect=RuntimeError("boom")+ )def test_reload_failure_does_not_fail_committed_delete(self, _reload_hog_functions_on_workers) -> None:destinations = self._make_group(template_id="template-slack", alert_id="alert-1")@@ -631,8 +633,8 @@ class TestSoftDeleteAlertDestinations(AlertDestinationTestCase):class TestAlertInternalEventDelivery(APIBaseTest):- @patch("products.alerts.backend.destinations.capture_exception")- @patch("products.alerts.backend.destinations.ALERT_INTERNAL_EVENT_DELIVERY_FAILURES")+ @patch("products.alerts.backend.logic.destinations.capture_exception")+ @patch("products.alerts.backend.logic.destinations.ALERT_INTERNAL_EVENT_DELIVERY_FAILURES")def test_expected_delivery_failure_records_metric_without_capturing_exception(self, delivery_failures, capture_exception) -> None:@@ -652,6 +654,37 @@ class TestAlertInternalEventDelivery(APIBaseTest):delivery_failures.labels.return_value.inc.assert_called_once_with()+class TestProduceAlertInternalEvent(SimpleTestCase):+ @patch("products.alerts.backend.logic.destinations.capture_exception")+ @patch(+ "products.alerts.backend.logic.destinations.produce_internal_event",+ side_effect=RuntimeError("broker down"),+ )+ def test_a_producer_failure_is_swallowed_so_a_batch_caller_still_saves(+ self, _produce_internal_event, capture_exception+ ) -> None:+ result = produce_alert_internal_event(+ team_id=1, event_name="$logs_alert_firing", properties={"alert_id": "alert-1"}+ )++ assert result is None+ capture_exception.assert_called_once()+++class TestFlushAlertInternalEvents(SimpleTestCase):+ @patch("products.alerts.backend.logic.destinations.capture_exception")+ @patch(+ "products.alerts.backend.logic.destinations.flush_internal_events_producer",+ side_effect=RuntimeError("broker down"),+ )+ def test_a_broker_failure_is_swallowed_so_a_batch_caller_still_saves(+ self, _flush_internal_events_producer, capture_exception+ ) -> None:+ flush_alert_internal_events(1.0)++ capture_exception.assert_called_once()++class TestListActiveAlertDestinations(AlertDestinationTestCase):def test_list_active_alert_destinations_returns_name_and_type(self) -> None:self._make_hog_function(diff --git a/products/alerts/backend/test/test_email_notifications.py b/products/alerts/backend/test/test_email_notifications.pyindex 0784e266cace..65a8c0ea9c11 100644--- a/products/alerts/backend/test/test_email_notifications.py+++ b/products/alerts/backend/test/test_email_notifications.py@@ -2,10 +2,10 @@ from unittest.mock import MagicMock, call, patchfrom django.template.loader import render_to_string-from products.alerts.backend.email_notifications import send_alert_email+from products.alerts.backend.facade.email import send_alert_email-@patch("products.alerts.backend.email_notifications.EmailMessage")+@patch("products.alerts.backend.facade.email.EmailMessage")def test_send_alert_email_delivers_to_every_recipient(MockEmailMessage: MagicMock) -> None:send_alert_email(recipients=("[email protected]", "[email protected]"),@@ -61,6 +61,23 @@ def test_alert_firing_email_labels_test_delivery_without_claiming_the_alert_is_fassert "alert is firing" not in html+def test_alert_firing_email_lists_every_breach_description() -> None:+ html = render_to_string(+ "email/alert_check_firing.html",+ {+ "match_descriptions": ["Signups dropped below 100", "Signups dropped below 50"],+ "insight_url": "/project/1/insights/example",+ "insight_name": "Example insight",+ "alert_url": "/project/1/insights/example?alert_id=1",+ "alert_name": "Example alert",+ "project_name": "Example project",+ },+ )++ assert "Signups dropped below 100" in html+ assert "Signups dropped below 50" in html++def test_alert_evaluation_failure_email_includes_the_reason_and_next_check_timing() -> None:html = render_to_string("email/alert_check_failed_to_evaluate.html",diff --git a/products/alerts/backend/test/test_grid_scheduling.py b/products/alerts/backend/test/test_grid_scheduling.pyindex cff7abf75ea0..6685cd43e5d8 100644--- a/products/alerts/backend/test/test_grid_scheduling.py+++ b/products/alerts/backend/test/test_grid_scheduling.py@@ -12,7 +12,7 @@ from hypothesis import ()from parameterized import parameterized-from products.alerts.backend.scheduling import (+from products.alerts.backend.facade.scheduling import (DEFAULT_SCHEDULE_INTERVAL_SECONDS,advance_next_check_at,compute_shard_offset_seconds,diff --git a/products/alerts/backend/test/test_insight_alert_state_machine.py b/products/alerts/backend/test/test_insight_alert_state_machine.pyindex 351dcd870ed5..715ecab5bec9 100644--- a/products/alerts/backend/test/test_insight_alert_state_machine.py+++ b/products/alerts/backend/test/test_insight_alert_state_machine.py@@ -4,6 +4,7 @@ from typing import castfrom posthog.schema_enums import AlertState as InsightAlertState+from products.alerts.backend.facade.lifecycle import AlertStatefrom products.alerts.backend.insight_alert_state_machine import (apply_disable,apply_enable,@@ -14,7 +15,6 @@ from products.alerts.backend.insight_alert_state_machine import (should_notify,)from products.alerts.backend.models.alert import AlertConfiguration-from products.alerts.backend.state_machine import AlertStateNOW = datetime(2026, 7, 27, 12, 0, tzinfo=UTC)diff --git a/products/alerts/backend/test/test_scheduling.py b/products/alerts/backend/test/test_scheduling.pyindex 0dac7510f588..7ee289059651 100644--- a/products/alerts/backend/test/test_scheduling.py+++ b/products/alerts/backend/test/test_scheduling.py@@ -5,7 +5,7 @@ import pytestfrom parameterized import parameterized-from products.alerts.backend.scheduling import (+from products.alerts.backend.facade.scheduling import (BlockedWindow,CalendarInterval,is_weekend,diff --git a/products/alerts/backend/test/test_state_machine.py b/products/alerts/backend/test/test_state_machine.pyindex a823984767b2..6c9c49b95ddc 100644--- a/products/alerts/backend/test/test_state_machine.py+++ b/products/alerts/backend/test/test_state_machine.py@@ -2,7 +2,7 @@ from datetime import UTC, datetime, timedeltafrom parameterized import parameterized-from products.alerts.backend.state_machine import (+from products.alerts.backend.facade.lifecycle import (LOGS_ALERT_POLICY,AlertCheckOutcome,AlertPolicy,diff --git a/products/alerts/backend/tests/api/test_alert.py b/products/alerts/backend/tests/api/test_alert.pyindex 8c27a3ec50cb..ac1a0ceee49f 100644--- a/products/alerts/backend/tests/api/test_alert.py+++ b/products/alerts/backend/tests/api/test_alert.py@@ -23,14 +23,12 @@ from posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team import Teamfrom posthog.models.utils import generate_random_token_personal, hash_key_value-from products.alerts.backend.destinations import AlertDelivery, count_active_alert_destinations-from products.alerts.backend.insight_alert_destinations import (- INSIGHT_ALERT_EVENT_IDS,- MAX_DESTINATIONS_PER_ALERT,- SLACK_TEMPLATE_ID,-)+from products.alerts.backend.facade.api import INSIGHT_ALERT_EVENT_IDS+from products.alerts.backend.facade.contracts import AlertDelivery+from products.alerts.backend.facade.destinations import MAX_DESTINATIONS_PER_ALERT, count_active_alert_destinations+from products.alerts.backend.logic.insight_alert_destinations import SLACK_TEMPLATE_IDfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold-from products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.cdp.backend.facade.models import HogFunctionfrom products.product_analytics.backend.facade.models import InsightTEST_DESTINATION_DELIVERY = AlertDelivery(@@ -1935,7 +1933,7 @@ class TestAlertTestDelivery(APIBaseTest):assert AlertCheck.objects.filter(alert_configuration_id=self.alert["id"]).count() == 0@mock.patch("products.alerts.backend.presentation.views.alert.trigger_alert_hog_functions")- @mock.patch("products.alerts.backend.email_notifications.EmailMessage")+ @mock.patch("products.alerts.backend.facade.email.EmailMessage")def test_sends_test_delivery_to_subscribed_users_without_a_destination(self, mock_email_message, mock_trigger) -> None:diff --git a/products/alerts/tsconfig.json b/products/alerts/tsconfig.jsonnew file mode 100644index 000000000000..fe425d6fcba8--- /dev/null+++ b/products/alerts/tsconfig.json@@ -0,0 +1,6 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "composite": true+ }+}diff --git a/products/billing_alerts/backend/alert_destinations.py b/products/billing_alerts/backend/alert_destinations.pyindex e73af9a50f4f..ef08595d076e 100644--- a/products/billing_alerts/backend/alert_destinations.py+++ b/products/billing_alerts/backend/alert_destinations.py@@ -2,15 +2,15 @@ from __future__ import annotationsfrom typing import Final, Literal-from products.alerts.backend.destination_configs import DestinationType, EventKindSpec-from products.alerts.backend.facade.api import DESTINATION_SPECS, owned_alert_destinations_qs+from products.alerts.backend.facade.contracts import DestinationType, EventKindSpec+from products.alerts.backend.facade.destinations import destination_template_id, list_owned_alert_destinationsEventKind = Literal["firing", "resolved", "errored", "broken"]BILLING_DESTINATION_TYPES = (DestinationType.SLACK, DestinationType.WEBHOOK, DestinationType.TEAMS)DESTINATION_TYPE_BY_TEMPLATE_ID = {- DESTINATION_SPECS[destination_type].template_id: destination_type for destination_type in BILLING_DESTINATION_TYPES+ destination_template_id(destination_type): destination_type for destination_type in BILLING_DESTINATION_TYPES}_PRODUCT_LABEL = "billing alert"@@ -124,23 +124,25 @@ def destination_groups_for_alerts(if not team_ids or not alert_ids:return {}- rows = [+ rows = (rowfor team_id in team_ids- for row in owned_alert_destinations_qs(- team_id=team_id, alert_ids=alert_ids, allowed_event_ids=BILLING_ALERT_EVENT_IDS+ for row in list_owned_alert_destinations(+ team_id=team_id,+ alert_ids=alert_ids,+ allowed_event_ids=BILLING_ALERT_EVENT_IDS,+ template_ids=list(DESTINATION_TYPE_BY_TEMPLATE_ID),+ enabled=True,)- .filter(enabled=True, template_id__in=list(DESTINATION_TYPE_BY_TEMPLATE_ID))- .values_list("id", "template_id", "filters")- ]+ )groups: dict[str, dict[str, dict[str, str]]] = {}- for hog_function_id, template_id, filters in rows:- destination_type = DESTINATION_TYPE_BY_TEMPLATE_ID.get(template_id) if template_id else None- if destination_type is None or not isinstance(filters, dict):+ for row in rows:+ destination_type = DESTINATION_TYPE_BY_TEMPLATE_ID.get(row.template_id) if row.template_id else None+ if destination_type is None or row.filters is None:continue- properties = filters.get("properties") or []- events = filters.get("events") or []+ properties = row.filters.get("properties") or []+ events = row.filters.get("events") or []if not isinstance(properties, list) or not isinstance(events, list):continueevent_id = next(@@ -158,6 +160,8 @@ def destination_groups_for_alerts(continuealert_id = str(property_filter.get("value"))if alert_id in alert_ids:- groups.setdefault(alert_id, {}).setdefault(destination_type.value, {})[event_id] = str(hog_function_id)+ groups.setdefault(alert_id, {}).setdefault(destination_type.value, {})[event_id] = str(+ row.hog_function_id+ )breakreturn groupsdiff --git a/products/billing_alerts/backend/facade/api.py b/products/billing_alerts/backend/facade/api.pyindex 15d31c1bb15e..2979837d0edb 100644--- a/products/billing_alerts/backend/facade/api.py+++ b/products/billing_alerts/backend/facade/api.py@@ -14,12 +14,12 @@ from rest_framework.exceptions import ValidationError as DRFValidationErrorfrom posthog.models.integration import Integrationfrom posthog.models.team.team import Team-from products.alerts.backend.facade.api import (- AlertDestinationData,- DestinationType,+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,soft_delete_alert_destinations,+ soft_delete_alert_destinations_for_alerts,soft_delete_all_alert_destinations,validate_destination_data,)@@ -157,6 +157,13 @@ def delete_alert_and_destinations(alert: BillingAlertConfiguration) -> None:alert.delete()+def soft_delete_destinations_for_alerts(*, team_id: int, alert_ids: list[str]) -> None:+ """Remove the destinations of several billing alerts at once."""+ soft_delete_alert_destinations_for_alerts(+ team_id=team_id, alert_ids=alert_ids, allowed_event_ids=BILLING_ALERT_EVENT_IDS+ )++def destinations_for_alerts(alerts: list[BillingAlertConfiguration]) -> dict[str, list[dict[str, Any]]]:alert_ids = {str(alert.id) for alert in alerts}team_ids = {alert.execution_team_id for alert in alerts if alert.team_id is not None}@@ -215,7 +222,6 @@ def create_destination(alert: BillingAlertConfiguration, *, request: Any, data:_raise_if_billing_alert_already_has_this_destination_type(locked_alert, destination_data["type"])configs = [build_alert_destination_config(- team=locked_alert.team,spec=EVENT_KIND_CONFIG[kind],alert_id=str(locked_alert.id),alert_name=locked_alert.name,@@ -224,13 +230,14 @@ def create_destination(alert: BillingAlertConfiguration, *, request: Any, data:)for kind in EVENT_KINDS]- hog_functions = create_alert_destination_hog_functions(+ hog_function_ids = create_alert_destination_hog_functions(configs,- request=request,+ team_id=locked_alert.execution_team_id,+ created_by_id=request.user.id,alert_id=str(locked_alert.id),allowed_event_ids=BILLING_ALERT_EVENT_IDS,)- return [hog_function.id for hog_function in hog_functions]+ return list(hog_function_ids)def delete_destination(alert: BillingAlertConfiguration, hog_function_ids: list[UUID]) -> None:@@ -282,6 +289,7 @@ __all__ = ["initialize_billing_alert_lifecycle","reschedule_billing_alert_configuration","slack_integration_belongs_to_team",+ "soft_delete_destinations_for_alerts","validate_threshold_configuration","visible_events_for_alert",]diff --git a/products/billing_alerts/backend/logic/notifications.py b/products/billing_alerts/backend/logic/notifications.pyindex 89597a5505bd..a3e172a656fd 100644--- a/products/billing_alerts/backend/logic/notifications.py+++ b/products/billing_alerts/backend/logic/notifications.py@@ -11,7 +11,7 @@ import structlogfrom posthog.kafka_client.client import ProduceResultfrom posthog.utils import absolute_uri-from products.alerts.backend.destinations import (+from products.alerts.backend.facade.destinations import (alert_internal_event_delivered,flush_alert_internal_events,produce_alert_internal_event,diff --git a/products/billing_alerts/backend/logic/state_machine.py b/products/billing_alerts/backend/logic/state_machine.pyindex 65253449698a..47f9993d0368 100644--- a/products/billing_alerts/backend/logic/state_machine.py+++ b/products/billing_alerts/backend/logic/state_machine.py@@ -12,8 +12,7 @@ import structlogfrom posthog.exceptions_capture import capture_exception-from products.alerts.backend.scheduling import compute_shard_offset_seconds-from products.alerts.backend.state_machine import (+from products.alerts.backend.facade.lifecycle import (BILLING_ALERT_POLICY,MAX_CONSECUTIVE_FAILURES,AlertCheckOutcome,@@ -30,6 +29,7 @@ from products.alerts.backend.state_machine 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_secondsfrom 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.pyindex d63e3b2f5aef..198fc914a3f0 100644--- a/products/billing_alerts/backend/presentation/serializers.py+++ b/products/billing_alerts/backend/presentation/serializers.py@@ -11,14 +11,15 @@ from drf_spectacular.utils import extend_schema_fieldfrom rest_framework import serializersfrom rest_framework.exceptions import ValidationError+from posthog.exceptions import as_drf_validation_errorfrom posthog.security.url_validation import is_microsoft_teams_webhook_url-from products.alerts.backend.facade.api import (+from products.alerts.backend.facade.contracts import (AlertDestinationData,AlertDestinationValidationError,DestinationType,- validate_destination_data,)+from products.alerts.backend.facade.destinations import validate_destination_datafrom products.billing_alerts.backend.facade import api as billing_alerts_apifrom products.billing_alerts.backend.facade.api import (BillingAlertConfiguration,@@ -130,9 +131,7 @@ class BillingAlertDestinationCreateDataSerializer(serializers.Serializer):try:validate_destination_data(data, allowed_destination_types=billing_alerts_api.BILLING_DESTINATION_TYPES)except AlertDestinationValidationError as error:- if error.field:- raise ValidationError({error.field: error.message})- raise ValidationError(error.message)+ raise as_drf_validation_error(error)# URL-shape checks beyond the shared required-field validation.webhook_url = attrs.get("webhook_url")@@ -364,9 +363,12 @@ class BillingAlertConfigurationSerializer(serializers.ModelSerializer):alert = super().create(validated_data)billing_alerts_api.initialize_billing_alert_lifecycle(alert)if destination_changes:- billing_alerts_api.apply_destination_changes(- alert, request=self.context["request"], changes=destination_changes- )+ try:+ billing_alerts_api.apply_destination_changes(+ alert, request=self.context["request"], changes=destination_changes+ )+ except AlertDestinationValidationError as error:+ raise as_drf_validation_error(error)return alertdef update(@@ -418,9 +420,12 @@ class BillingAlertConfigurationSerializer(serializers.ModelSerializer):configuration_changed=configuration_changed,)if destination_changes:- billing_alerts_api.apply_destination_changes(- updated, request=self.context["request"], changes=destination_changes- )+ try:+ billing_alerts_api.apply_destination_changes(+ updated, request=self.context["request"], changes=destination_changes+ )+ except AlertDestinationValidationError as error:+ raise as_drf_validation_error(error)return updateddiff --git a/products/billing_alerts/backend/presentation/views.py b/products/billing_alerts/backend/presentation/views.pyindex 6dd866078ab4..8278a03b20f0 100644--- a/products/billing_alerts/backend/presentation/views.py+++ b/products/billing_alerts/backend/presentation/views.py@@ -13,10 +13,12 @@ from rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.event_usage import report_user_action+from posthog.exceptions import as_drf_validation_errorfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.permissions import OrganizationAdminReadPermissions, PostHogFeatureFlagPermission+from products.alerts.backend.facade.contracts import AlertDestinationValidationErrorfrom products.billing_alerts.backend.facade import api as billing_alerts_apifrom products.billing_alerts.backend.facade.api import BillingAlertConfigurationfrom products.billing_alerts.backend.presentation.serializers import (@@ -159,7 +161,10 @@ class BillingAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):serializer.is_valid(raise_exception=True)data = serializer.validated_data- hog_function_ids = billing_alerts_api.create_destination(alert, request=self.request, data=data)+ try:+ hog_function_ids = billing_alerts_api.create_destination(alert, request=self.request, data=data)+ except AlertDestinationValidationError as error:+ raise as_drf_validation_error(error)report_user_action(request.user,@@ -182,7 +187,10 @@ class BillingAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):serializer.is_valid(raise_exception=True)hog_function_ids = serializer.validated_data["hog_function_ids"]- billing_alerts_api.delete_destination(alert, hog_function_ids)+ try:+ billing_alerts_api.delete_destination(alert, hog_function_ids)+ except AlertDestinationValidationError as error:+ raise as_drf_validation_error(error)report_user_action(request.user,diff --git a/products/billing_alerts/backend/team_lifecycle.py b/products/billing_alerts/backend/team_lifecycle.pyindex 826ba69a6e15..3de020a78e7a 100644--- a/products/billing_alerts/backend/team_lifecycle.py+++ b/products/billing_alerts/backend/team_lifecycle.py@@ -37,8 +37,9 @@ def rehome_billing_alerts_before_team_delete(if table_name not in connections[using].introspection.table_names():return- from products.alerts.backend.destinations import soft_delete_alert_destinations_for_alerts # noqa: PLC0415- from products.billing_alerts.backend.alert_destinations import BILLING_ALERT_EVENT_IDS # noqa: PLC0415+ # Deferred: this receiver is connected at app start, and the facade drags the alerts+ # platform onto that path.+ from products.billing_alerts.backend.facade.api import soft_delete_destinations_for_alerts # noqa: PLC0415deleting_team_ids = _deleting_team_ids(origin=origin, instance=instance, using=using)replacement_team_id = (@@ -53,11 +54,7 @@ def rehome_billing_alerts_before_team_delete(with transaction.atomic(using=using):alerts = BillingAlertConfiguration.objects.using(using).select_for_update().filter(team_id=instance.id)alert_ids = [str(alert_id) for alert_id in alerts.values_list("id", flat=True)]- soft_delete_alert_destinations_for_alerts(- team_id=instance.id,- alert_ids=alert_ids,- allowed_event_ids=BILLING_ALERT_EVENT_IDS,- )+ soft_delete_destinations_for_alerts(team_id=instance.id, alert_ids=alert_ids)# Billing alerts evaluate organization-wide data, but HogFunction destinations are team-scoped.# Re-home and disable them because team-specific integrations cannot be moved safely.diff --git a/products/billing_alerts/backend/test/test_state_machine.py b/products/billing_alerts/backend/test/test_state_machine.pyindex ef1bf1b98f59..c713b6cf3587 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, timedeltafrom decimal import Decimalfrom uuid import UUID-from products.alerts.backend.state_machine import AlertSnapshot, AlertState, NotificationAction+from products.alerts.backend.facade.lifecycle import AlertSnapshot, AlertState, NotificationActionfrom products.billing_alerts.backend.logic.evaluator import BillingAlertEvaluationfrom products.billing_alerts.backend.logic.state_machine import (apply_outcome,diff --git a/products/billing_alerts/backend/test/test_team_lifecycle.py b/products/billing_alerts/backend/test/test_team_lifecycle.pyindex 42f91da41293..fa997574f004 100644--- a/products/billing_alerts/backend/test/test_team_lifecycle.py+++ b/products/billing_alerts/backend/test/test_team_lifecycle.py@@ -5,7 +5,7 @@ from unittest.mock import patchfrom posthog.models.team.team import Team-from products.alerts.backend.destinations import (+from products.alerts.backend.facade.destinations import (soft_delete_alert_destinations_for_alerts as shared_soft_delete_destinations,)from products.billing_alerts.backend.alert_destinations import BILLING_ALERT_EVENT_IDS, EVENT_KIND_CONFIG@@ -69,7 +69,7 @@ class TestBillingAlertTeamLifecycle(BaseTest):)with patch(- "products.alerts.backend.destinations.soft_delete_alert_destinations_for_alerts",+ "products.billing_alerts.backend.facade.api.soft_delete_alert_destinations_for_alerts",wraps=shared_soft_delete_destinations,) as soft_delete_destinations:self.team.delete()diff --git a/products/cdp/backend/api/hog_function.py b/products/cdp/backend/api/hog_function.pyindex d6c918ac6265..34c50418352d 100644--- a/products/cdp/backend/api/hog_function.py+++ b/products/cdp/backend/api/hog_function.py@@ -790,8 +790,9 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):return {**draft, "inputs": inputs}def create(self, validated_data: dict, *args, **kwargs) -> HogFunction:- request = self.context["request"]- validated_data["created_by"] = request.user+ # An in-process caller has no request to take the acting user from, so it passes+ # `created_by` to `save()` instead.+ validated_data["created_by"] = validated_data.get("created_by") or self.context["request"].usertemplate_id = validated_data.get("template_id")if template_id:diff --git a/products/cdp/backend/facade/api.py b/products/cdp/backend/facade/api.pyindex ca218f1a8ef5..5574485f1423 100644--- a/products/cdp/backend/facade/api.py+++ b/products/cdp/backend/facade/api.py@@ -5,11 +5,54 @@ Re-exports the HogFunction serializer cross-product API views reuse. Lazy (PEP 5keep the DRF/serializer import chain off config-only import paths."""+from __future__ import annotations++from collections.abc import Sequence+from typing import Any+from uuid import UUID++from posthog.models.team import Team+from posthog.models.user import User+_B = "products.cdp.backend."_LAZY = {"HogFunctionSerializer": "api.hog_function"}-__all__ = sorted(_LAZY)+__all__ = [*sorted(_LAZY), "create_hog_functions"]+++def create_hog_functions(+ payloads: Sequence[dict[str, Any]],+ *,+ team_id: int,+ created_by_id: int,+ allow_managed_alert_destination: bool,+) -> list[UUID]:+ """Create one hog function per payload and return their ids in the order given.++ Callers outside this product have no DRF request to take an acting user from, so the+ acting user comes in as an id. The team and the acting user are resolved once for the+ whole batch, so a caller writing several functions still pays two point lookups.+ """+ # Same reason as _LAZY below: the serializer drags DRF, so it stays off this module's+ # import path.+ from products.cdp.backend.api.hog_function import HogFunctionSerializer # noqa: PLC0415++ team = Team.objects.get(id=team_id)+ created_by = User.objects.get(id=created_by_id)+ created_ids: list[UUID] = []+ for payload in payloads:+ serializer = HogFunctionSerializer(+ data=payload,+ context={+ "get_team": lambda: team,+ "is_create": True,+ "allow_managed_alert_destination": allow_managed_alert_destination,+ },+ )+ serializer.is_valid(raise_exception=True)+ created_ids.append(serializer.save(team=team, created_by=created_by).id)+ return created_idsdef __getattr__(name: str):diff --git a/products/logs/backend/alert_destinations.py b/products/logs/backend/alert_destinations.pyindex 139f0aae6b68..4b0210d5dcde 100644--- a/products/logs/backend/alert_destinations.py+++ b/products/logs/backend/alert_destinations.py@@ -4,7 +4,7 @@ from __future__ import annotationsfrom typing import Literal-from products.alerts.backend.destination_configs import DestinationType, EventKindSpec+from products.alerts.backend.facade.contracts import DestinationType, EventKindSpecEventKind = Literal["firing", "resolved", "broken", "errored"]LOGS_DESTINATION_TYPES = (DestinationType.SLACK, DestinationType.WEBHOOK, DestinationType.TEAMS)diff --git a/products/logs/backend/alert_state_machine.py b/products/logs/backend/alert_state_machine.pyindex b1fb389a55f5..3859e88aadff 100644--- a/products/logs/backend/alert_state_machine.py+++ b/products/logs/backend/alert_state_machine.py@@ -9,7 +9,7 @@ that mutates those two fields.The semgrep rule at `.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml`enforces this invariant in CI.-The decision logic itself lives in `products/alerts/backend/state_machine.py`+The decision logic itself lives in `products/alerts/backend/facade/lifecycle.py`(configured here with `LOGS_ALERT_POLICY`); this module owns the logs-shaped inputs(`AlertSnapshot`, `CheckResult`) and the model mutation (`apply_outcome`)."""@@ -20,7 +20,7 @@ from dataclasses import dataclassfrom datetime import datetime, timedeltafrom typing import TYPE_CHECKING-from products.alerts.backend.state_machine import (+from products.alerts.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.pyindex 7eb476569727..053cf55f0b9d 100644--- a/products/logs/backend/alert_utils.py+++ b/products/logs/backend/alert_utils.py@@ -8,7 +8,7 @@ from django.db.models import Qimport structlog-from products.alerts.backend.scheduling import (+from products.alerts.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/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.pyindex 66dfdc7afd6a..60fbbee475eb 100644--- a/products/logs/backend/presentation/views/alerts_api.py+++ b/products/logs/backend/presentation/views/alerts_api.py@@ -22,27 +22,31 @@ from posthog.schema import LogsAlertFiltersfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.event_usage import report_user_action+from posthog.exceptions import as_drf_validation_errorfrom posthog.helpers.impersonation import is_impersonatedfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.utils import relative_date_parse-from products.alerts.backend.facade.api import (- DESTINATION_SPECS,+from products.alerts.backend.facade.contracts import (AlertDestinationData,AlertDestinationValidationError,- AlertScheduleRestriction,DestinationType,+)+from products.alerts.backend.facade.destinations import (build_alert_destination_config,+ configured_destination_template_ids,create_alert_destination_hog_functions,+ destination_template_id,list_alert_destination_groups,- owned_alert_destinations_qs,+ redact_destination_data,soft_delete_alert_destinations,soft_delete_all_alert_destinations,- validate_and_normalize_schedule_restriction,validate_destination_data,)+from products.alerts.backend.facade.scheduling import validate_and_normalize_schedule_restriction+from products.alerts.backend.presentation.views.schedule_restriction import AlertScheduleRestrictionfrom products.logs.backend.alert_check_query import AlertCheckQuery, BucketedCountfrom products.logs.backend.alert_destinations import (EVENT_KIND_CONFIG,@@ -399,22 +403,16 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):@extend_schema_field(serializers.ListField(child=serializers.ChoiceField(choices=LOGS_DESTINATION_TYPES)))def get_destination_types(self, obj: LogsAlertConfiguration) -> list[str]:- # Only template_id is read. Reading the whole destination would pull its stored- # inputs, several KB per row, for every alert on the page.# N+1 is acceptable: max 20 alerts per team, each query a fast indexed lookup.- configured_template_ids = set(- owned_alert_destinations_qs(- team_id=obj.team_id,- alert_ids=[str(obj.id)],- allowed_event_ids=LOGS_ALERT_EVENT_IDS,- )- .values_list("template_id", flat=True)- .distinct()+ configured_template_ids = configured_destination_template_ids(+ team_id=obj.team_id,+ alert_id=str(obj.id),+ allowed_event_ids=LOGS_ALERT_EVENT_IDS,)return sorted(destination_type.valuefor destination_type in LOGS_DESTINATION_TYPES- if DESTINATION_SPECS[destination_type].template_id in configured_template_ids+ if destination_template_id(destination_type) in configured_template_ids)@extend_schema_field(serializers.CharField(allow_null=True))@@ -665,7 +663,7 @@ class LogsAlertConfigurationDetailSerializer(LogsAlertConfigurationSerializer):{"hog_function_ids": list(group.hog_function_ids),"enabled": group.fully_enabled,- **DESTINATION_SPECS[DestinationType(group.data["type"])].redact(group.data),+ **redact_destination_data(group.data),}for group in groups]@@ -1014,7 +1012,6 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):alert = self._get_locked_alert()configs = [build_alert_destination_config(- team=alert.team,spec=EVENT_KIND_CONFIG[kind],alert_id=str(alert.id),alert_name=alert.name,@@ -1023,12 +1020,16 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)for kind in EVENT_KINDS]- hog_functions = create_alert_destination_hog_functions(- configs,- request=self.request,- alert_id=str(alert.id),- allowed_event_ids=LOGS_ALERT_EVENT_IDS,- )+ try:+ hog_function_ids = create_alert_destination_hog_functions(+ configs,+ team_id=alert.team_id,+ created_by_id=cast(User, request.user).id,+ alert_id=str(alert.id),+ allowed_event_ids=LOGS_ALERT_EVENT_IDS,+ )+ except AlertDestinationValidationError as error:+ raise as_drf_validation_error(error)report_user_action(request.user,@@ -1036,7 +1037,7 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):{"alert_id": str(alert.id), "type": data["type"], "event_kinds": list(EVENT_KINDS)},request=request,)- response = LogsAlertDestinationResponseSerializer({"hog_function_ids": [hf.id for hf in hog_functions]})+ response = LogsAlertDestinationResponseSerializer({"hog_function_ids": list(hog_function_ids)})return Response(response.data, status=201)@extend_schema(@@ -1060,12 +1061,15 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):largest_server_group = max((len(group.hog_function_ids) for group in groups), default=0)if len(hog_function_ids) > max(MAX_DESTINATION_IDS_PER_DELETE_REQUEST, largest_server_group):raise ValidationError({"hog_function_ids": "Too many destination IDs."})- soft_delete_alert_destinations(- team_id=self.team_id,- alert_id=str(alert.id),- allowed_event_ids=LOGS_ALERT_EVENT_IDS,- hog_function_ids=hog_function_ids,- )+ try:+ soft_delete_alert_destinations(+ team_id=self.team_id,+ alert_id=str(alert.id),+ allowed_event_ids=LOGS_ALERT_EVENT_IDS,+ hog_function_ids=hog_function_ids,+ )+ except AlertDestinationValidationError as error:+ raise as_drf_validation_error(error)report_user_action(request.user,diff --git a/products/logs/backend/temporal/activities.py b/products/logs/backend/temporal/activities.pyindex 0b255f666be6..37c6690d831c 100644--- a/products/logs/backend/temporal/activities.py+++ b/products/logs/backend/temporal/activities.py@@ -27,8 +27,8 @@ from posthog.slo.context import SloHandle, SloSpec, slo_operationfrom posthog.slo.types import SloArea, SloOperationfrom posthog.sync import database_sync_to_async_pool-from products.alerts.backend.delivery_slo import alert_delivery_slo-from products.alerts.backend.destinations import (+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,diff --git a/products/logs/backend/test/test_alert_destinations.py b/products/logs/backend/test/test_alert_destinations.pyindex f329d67794ae..984a41f1f976 100644--- a/products/logs/backend/test/test_alert_destinations.py+++ b/products/logs/backend/test/test_alert_destinations.py@@ -1,18 +1,22 @@-from typing import cast+from typing import Any, castfrom django.test import SimpleTestCasefrom parameterized import parameterized-from products.alerts.backend.destination_configs import (+from products.alerts.backend.facade.contracts import (AlertDestinationData,AlertDestinationValidationError,DestinationType,- slack_body as _slack_body,- teams_text as _teams_text,- validate_destination_data,)-from products.logs.backend.alert_destinations import EVENT_KIND_CONFIG, EVENT_KINDS, LOGS_DESTINATION_TYPES, EventKind+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,+ LOGS_ALERT_SLACK_CONTEXT_ELEMENTS,+ LOGS_DESTINATION_TYPES,+ EventKind,+)class TestDestinationValidation(SimpleTestCase):@@ -57,45 +61,45 @@ class TestDestinationValidation(SimpleTestCase):)-class TestSlackBody(SimpleTestCase):+SLACK_DATA = cast(+ AlertDestinationData, {"type": DestinationType.SLACK, "slack_workspace_id": 1, "slack_channel_id": "C-ENG"}+)+TEAMS_DATA = cast(AlertDestinationData, {"type": DestinationType.TEAMS, "webhook_url": "https://example.com/hook"})+++def destination_inputs(kind: EventKind, data: AlertDestinationData) -> dict[str, Any]:+ config = build_alert_destination_config(+ spec=EVENT_KIND_CONFIG[kind],+ alert_id="alert-1",+ alert_name="Checkout errors",+ data=data,+ slack_context_elements=LOGS_ALERT_SLACK_CONTEXT_ELEMENTS,+ )+ return config.payload["inputs"]+++class TestRenderedDestinationContent(SimpleTestCase):@parameterized.expand([(kind,) for kind in EVENT_KINDS])- def test_body_is_slack_mrkdwn(self, kind: EventKind) -> None:+ def test_slack_body_puts_every_detail_on_its_own_line(self, kind: EventKind) -> None:spec = EVENT_KIND_CONFIG[kind]- body = _slack_body(spec)+ blocks = destination_inputs(kind, SLACK_DATA)["blocks"]["value"]+ body = blocks[1]["text"]["text"]+lines = body.split("\n")- assert len(lines) == len(spec.details)- for line, (label, value) in zip(lines, spec.details):- # Slack mrkdwn bold label, then the plain-text value.- assert line == f"*{label}:* {value}"- # Detail values are plain text — bold markers come only from the renderer.+ assert lines == [f"*{label}:* {value}" for label, value in spec.details]+ # Slack mrkdwn bolds with one asterisk, so a `**` pair would render as literal text.assert "**" not in body- def test_multi_detail_body_renders_one_line_per_detail(self) -> None:- body = _slack_body(EVENT_KIND_CONFIG["broken"])- assert body == (- "*Reason:* {event.properties.consecutive_failures} consecutive check failures.\n"- "*Last error:* {event.properties.last_error_message}"- )---class TestTeamsText(SimpleTestCase):@parameterized.expand([(kind,) for kind in EVENT_KINDS])- def test_text_is_adaptive_card_markdown(self, kind: EventKind) -> None:+ def test_teams_text_is_adaptive_card_markdown(self, kind: EventKind) -> None:spec = EVENT_KIND_CONFIG[kind]- text = _teams_text(spec)- # Bold header, every detail label bolded, the action rendered as an inline markdown link.+ text = destination_inputs(kind, TEAMS_DATA)["text"]["value"]+assert text.startswith(f"**{spec.header}**")for label, value in spec.details:assert f"**{label}:** {value}" in textassert f"[{spec.primary_action_label}]({spec.primary_action_url})" in text- # Every asterisk must belong to a `**` pair — no Slack-style single-asterisk bold.+ # An Adaptive Card renders a single asterisk literally, so every one must be part of a pair.assert "*" not in text.replace("**", "")-- def test_multi_detail_text_separates_paragraphs_with_blank_lines(self) -> None:- text = _teams_text(EVENT_KIND_CONFIG["broken"])- assert (- "**Reason:** {event.properties.consecutive_failures} consecutive check failures.\n\n"- "**Last error:** {event.properties.last_error_message}"- ) in text- # Adaptive Card paragraphs need exactly one blank line — never stacked blank lines.+ # Its paragraphs need exactly one blank line between them; a stacked one renders as a gap.assert "\n\n\n" not in textdiff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.pyindex 99b5c8abd7ca..19f634f74868 100644--- a/products/logs/backend/test/test_alerts_api.py+++ b/products/logs/backend/test/test_alerts_api.py@@ -876,7 +876,7 @@ class TestLogsAlertAPI(APIBaseTest):reset_calls = [c for c in mock_report.call_args_list if c.args[1] == "logs alert destination created"]assert len(reset_calls) == 1- @patch("products.alerts.backend.destinations.reload_hog_functions_on_workers")+ @patch("products.alerts.backend.logic.destinations.reload_hog_functions_on_workers")@patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers")def test_create_webhook_destination_creates_one_hog_function_per_event_kind(self, signal_reload_hog_functions, alert_reload_hog_functions@@ -900,6 +900,8 @@ class TestLogsAlertAPI(APIBaseTest):hog_functions = HogFunction.objects.filter(id__in=ids)for hf in hog_functions:assert hf.template_id == "template-webhook"+ # A destination with no creator is unattributable in the activity log.+ assert hf.created_by_id == self.user.idinputs = hf.inputs or {}assert inputs["url"]["value"] == "https://example.com/hook"body = inputs["body"]["value"]@@ -1038,7 +1040,7 @@ class TestLogsAlertAPI(APIBaseTest):)assert response.status_code == status.HTTP_404_NOT_FOUND- @patch("products.alerts.backend.destinations.reload_hog_functions_on_workers")+ @patch("products.alerts.backend.logic.destinations.reload_hog_functions_on_workers")def test_delete_destination_removes_hog_functions(self, reload_hog_functions):self._sync_destination_templates()created = self._create_via_api()@@ -2136,7 +2138,7 @@ class TestSimulateEvaluatorLifecycleParity(ClickhouseTestMixin, APIBaseTest):# A None return would read as "enqueue failed" and roll back every# notification, so the fake must return a (mock) ProduceResult.self._kafka_patcher = patch(- "products.alerts.backend.destinations.produce_internal_event",+ "products.logs.backend.temporal.activities.produce_alert_internal_event",return_value=MagicMock(),)self._kafka_patcher.start()diff --git a/products/logs/backend/test/test_logs_alerting_activities.py b/products/logs/backend/test/test_logs_alerting_activities.pyindex 22d69b15a288..4c0d6ebde678 100644--- a/products/logs/backend/test/test_logs_alerting_activities.py+++ b/products/logs/backend/test/test_logs_alerting_activities.py@@ -291,11 +291,8 @@ class TestResolveNotificationDeliveries(unittest.TestCase):("still_pending_after_flush", TimeoutError("undelivered"), True),])- @patch("products.alerts.backend.destinations.flush_internal_events_producer", return_value=0)- @patch("products.alerts.backend.destinations.capture_exception")- def test_folds_delivery_outcome_into_notification_failed(- self, _name, get_side_effect, expect_failed, _mock_capture, mock_flush- ):+ @patch("products.logs.backend.temporal.activities.flush_alert_internal_events")+ def test_folds_delivery_outcome_into_notification_failed(self, _name, get_side_effect, expect_failed, mock_flush):from products.logs.backend.temporal.activities import _resolve_notification_deliveriesresult = MagicMock()@@ -307,7 +304,7 @@ class TestResolveNotificationDeliveries(unittest.TestCase):assert resolved[0].notification_failed is expect_failedmock_flush.assert_called_once()- @patch("products.alerts.backend.destinations.flush_internal_events_producer")+ @patch("products.logs.backend.temporal.activities.flush_alert_internal_events")def test_skips_flush_when_nothing_was_produced(self, mock_flush):from products.logs.backend.temporal.activities import _resolve_notification_deliveries@@ -318,21 +315,6 @@ class TestResolveNotificationDeliveries(unittest.TestCase):assert resolved == [dispatched]mock_flush.assert_not_called()- @patch("products.alerts.backend.destinations.capture_exception")- @patch(- "products.alerts.backend.destinations.flush_internal_events_producer",- side_effect=Exception("kafka down"),- )- def test_flush_failure_does_not_raise_and_marks_pending_failed(self, mock_flush, _mock_capture):- from products.logs.backend.temporal.activities import _resolve_notification_deliveries-- result = MagicMock()- result.get.side_effect = TimeoutError("undelivered")-- resolved = _resolve_notification_deliveries([self._dispatched(result)])-- assert resolved[0].notification_failed is True-class TestRunCohortQueryFallback(unittest.TestCase):@staticmethod@@ -718,7 +700,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_threshold_breached_transitions_to_firing(self, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [50])alert = self._make_alert()@@ -732,11 +714,11 @@ class TestEvaluateSingleAlert(APIBaseTest):assert stats["checked"] == 1assert stats["fired"] == 1mock_produce.assert_called_once()- assert mock_produce.call_args.kwargs["event"].event == "$logs_alert_firing"+ assert mock_produce.call_args.kwargs["event_name"] == "$logs_alert_firing"@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_threshold_not_breached_stays_not_firing(self, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [5])alert = self._make_alert()@@ -753,7 +735,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_steady_state_writes_no_alert_event(self, _mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [5]) # below threshold → stays NOT_FIRINGalert = self._make_alert()@@ -764,7 +746,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_creates_event_row(self, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [50])alert = self._make_alert()@@ -785,7 +767,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_advances_next_check_at(self, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [5])alert = self._make_alert(next_check_at=datetime(2025, 1, 1, 0, 0, 0, tzinfo=UTC))@@ -799,7 +781,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T21:58:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_advances_next_check_at_past_quiet_hours(self, _mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [5])alert = self._make_alert(@@ -815,7 +797,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T21:58:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_uses_quiet_hours_saved_after_the_alert_loaded(self, _mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [5])alert = self._make_alert(next_check_at=datetime(2025, 1, 1, 21, 55, tzinfo=UTC))@@ -831,7 +813,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T23:00:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_suppresses_notification_when_quiet_hours_start_after_evaluation(self, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [50])alert = self._make_alert(next_check_at=datetime(2025, 1, 1, 21, 55, tzinfo=UTC))@@ -850,7 +832,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-02T06:56:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_advances_last_quiet_hours_check_to_the_window_end(self, _mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [5])alert = self._make_alert(@@ -866,7 +848,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")@patch("products.logs.backend.alert_error_classifier.classify_query_error",return_value=QueryErrorCategory.QUERY_PERFORMANCE_ERROR,@@ -893,8 +875,8 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")- def test_emit_event_uses_team_distinct_id(self, mock_produce, mock_query_cls):+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")+ def test_emit_event_uses_the_alert_team(self, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [50])alert = self._make_alert()stats = {"checked": 0, "fired": 0, "resolved": 0, "errored": 0}@@ -902,12 +884,11 @@ class TestEvaluateSingleAlert(APIBaseTest):_evaluate_and_save_one(alert, now, stats)- event = mock_produce.call_args.kwargs["event"]- assert event.distinct_id == f"team_{self.team.id}"+ assert mock_produce.call_args.kwargs["team_id"] == self.team.id@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_last_notified_at_set_after_kafka_success(self, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [50])alert = self._make_alert()@@ -921,9 +902,8 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event", side_effect=Exception("Kafka down"))- @patch("products.alerts.backend.destinations.capture_exception")- def test_last_notified_at_not_set_on_kafka_failure(self, mock_capture, mock_produce, mock_query_cls):+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event", return_value=None)+ def test_last_notified_at_not_set_on_kafka_failure(self, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [50])alert = self._make_alert()stats = {"checked": 0, "fired": 0, "resolved": 0, "errored": 0}@@ -933,7 +913,6 @@ class TestEvaluateSingleAlert(APIBaseTest):alert.refresh_from_db()assert alert.last_notified_at is None- mock_capture.assert_called_once()@parameterized.expand([@@ -945,7 +924,7 @@ class TestEvaluateSingleAlert(APIBaseTest):)@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_threshold_operators(self, _name, operator, count, should_fire, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [count])alert = self._make_alert(threshold_operator=operator, threshold_count=10)@@ -964,7 +943,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_resolution_emits_resolved_event(self, mock_produce, mock_query_cls):alert = self._make_alert(state=LogsAlertConfiguration.State.FIRING)# First check breached to create an event row for get_recent_breaches@@ -982,11 +961,11 @@ class TestEvaluateSingleAlert(APIBaseTest):assert alert.state == LogsAlertConfiguration.State.NOT_FIRINGassert stats["resolved"] == 1mock_produce.assert_called_once()- assert mock_produce.call_args.kwargs["event"].event == "$logs_alert_resolved"+ assert mock_produce.call_args.kwargs["event_name"] == "$logs_alert_resolved"@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_cooldown_suppresses_notification(self, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [50])alert = self._make_alert(@@ -1005,7 +984,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_n_of_m_requires_multiple_breaches_to_fire(self, mock_produce, mock_query_cls):# Stateless eval: a single bucketed query returns the M-bucket history.# State machine derives the N-of-M decision from those buckets directly.@@ -1035,7 +1014,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_event_properties_include_logs_url_params(self, mock_produce, mock_query_cls):alert = self._make_alert(threshold_count=5,@@ -1046,7 +1025,7 @@ class TestEvaluateSingleAlert(APIBaseTest):_evaluate_and_save_one(alert, datetime(2025, 1, 1, 0, 1, 0, tzinfo=UTC), _make_stats())assert mock_produce.called- props = mock_produce.call_args.kwargs["event"].properties+ props = mock_produce.call_args.kwargs["properties"]assert "logs_url_params" in propsassert "severityLevels" in props["logs_url_params"]assert "api-server" in props["logs_url_params"]@@ -1056,7 +1035,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_logs_url_params_includes_absolute_date_range(self, mock_produce, mock_query_cls):alert = self._make_alert(threshold_count=5,@@ -1067,7 +1046,7 @@ class TestEvaluateSingleAlert(APIBaseTest):_evaluate_and_save_one(alert, datetime(2025, 1, 1, 0, 1, 0, tzinfo=UTC), _make_stats())- props = mock_produce.call_args.kwargs["event"].properties+ props = mock_produce.call_args.kwargs["properties"]assert "dateRange" in props["logs_url_params"]# Window is 10m, check time is 00:01 — so date_from should be 23:51 (previous day)assert "2024-12-31T23%3A51%3A00" in props["logs_url_params"] or "23:51:00" in props["logs_url_params"]@@ -1075,7 +1054,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_resolution_within_cooldown_suppresses_resolved_event(self, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [0])alert = self._make_alert(@@ -1131,7 +1110,7 @@ class TestEvaluateSingleAlert(APIBaseTest):)@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_break_on_consecutive_failures(self,_name,@@ -1162,13 +1141,11 @@ class TestEvaluateSingleAlert(APIBaseTest):assert alert.state == expected_stateassert alert.consecutive_failures == expected_failuresauto_disabled_calls = [- c- for c in mock_produce.call_args_list- if c.kwargs.get("event") and c.kwargs["event"].event == "$logs_alert_auto_disabled"+ c for c in mock_produce.call_args_list if c.kwargs.get("event_name") == "$logs_alert_auto_disabled"]assert len(auto_disabled_calls) == expected_eventsif expected_events:- props = auto_disabled_calls[0].kwargs["event"].properties+ props = auto_disabled_calls[0].kwargs["properties"]assert props["consecutive_failures"] == expected_failures# Auto-disabled event surfaces the classified user message, never the raw CH exception.assert props["last_error_message"] == "Query is too expensive. Try narrower filters or a shorter window."@@ -1177,7 +1154,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.increment_state_transition")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_state_transition_counter_fires_on_state_change(self, _mock_produce, mock_query_cls, mock_transition):_mock_buckets(mock_query_cls, [50])alert = self._make_alert()@@ -1189,7 +1166,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.increment_state_transition")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_state_transition_counter_silent_when_state_unchanged(self, _mock_produce, mock_query_cls, mock_transition):_mock_buckets(mock_query_cls, [5])self._make_alert()@@ -1209,14 +1186,12 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.increment_notification_failures")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event", side_effect=Exception("Kafka down"))- @patch("products.alerts.backend.destinations.capture_exception")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event", return_value=None)def test_notification_failures_counter(self,expected_action_name,result_count,initial_state,- _mock_capture,_mock_produce,mock_query_cls,mock_notif_failures,@@ -1233,7 +1208,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.increment_notification_failures")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_notification_failures_silent_on_success(self, _mock_produce, mock_query_cls, mock_notif_failures):_mock_buckets(mock_query_cls, [50])self._make_alert()@@ -1255,7 +1230,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.increment_check_errors")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_check_errors_counter_labelled_by_classifier(self,expected_category,@@ -1280,7 +1255,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.increment_check_errors")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_check_errors_counter_silent_on_success(self, _mock_produce, mock_query_cls, mock_check_errors):_mock_buckets(mock_query_cls, [5])self._make_alert()@@ -1293,7 +1268,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_query_uses_checkpoint_as_date_to_when_in_past(self, _mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [5])alert = self._make_alert(window_minutes=5)@@ -1308,7 +1283,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_query_uses_now_when_checkpoint_is_in_future(self, _mock_produce, mock_query_cls):# Defensive case: if clocks are skewed so checkpoint > now, don't query the future._mock_buckets(mock_query_cls, [5])@@ -1324,7 +1299,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_query_uses_now_when_checkpoint_is_none(self, _mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [5])alert = self._make_alert(window_minutes=5)@@ -1338,7 +1313,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T01:00:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_query_ignores_stale_checkpoint_quiet_partition_case(self, _mock_produce, mock_query_cls):# Quiet partitions pin min(max_observed_timestamp) backwards. If that's older than# CHECKPOINT_MAX_STALENESS we must ignore the checkpoint — otherwise a spike of@@ -1364,7 +1339,7 @@ class TestEvaluateSingleAlert(APIBaseTest):)@time_machine.travel("2025-01-01T05:00:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_date_from_covers_full_rolling_check_lookback(self, _name, window_minutes, evaluation_periods, expected_range_minutes, _mock_produce, mock_query_cls):@@ -1384,7 +1359,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_errored_notification_emitted_on_first_error(self, mock_produce, mock_query_cls):mock_query_cls.return_value.execute_rolling_checks.side_effect = Exception("Code: 160. DB::Exception: Estimated query execution time is too long"@@ -1401,13 +1376,9 @@ class TestEvaluateSingleAlert(APIBaseTest):# Errors no longer move firing state; the notification and counter carry the signal.assert alert.state == LogsAlertConfiguration.State.NOT_FIRINGassert alert.consecutive_failures == 1- errored_calls = [- c- for c in mock_produce.call_args_list- if c.kwargs.get("event") and c.kwargs["event"].event == "$logs_alert_errored"- ]+ errored_calls = [c for c in mock_produce.call_args_list if c.kwargs.get("event_name") == "$logs_alert_errored"]assert len(errored_calls) == 1- assert errored_calls[0].kwargs["event"].properties["consecutive_failures"] == 1+ assert errored_calls[0].kwargs["properties"]["consecutive_failures"] == 1@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")@@ -1422,24 +1393,20 @@ class TestEvaluateSingleAlert(APIBaseTest):# failure must then roll back the failure counter, or the second check# never sees the 0 -> 1 notify edge and the notification is lost.with (- patch("products.alerts.backend.destinations.produce_internal_event") as mock_produce,+ patch("products.logs.backend.temporal.activities.produce_alert_internal_event") as mock_produce,patch("products.logs.backend.alert_error_classifier.classify_query_error",return_value=QueryErrorCategory.QUERY_PERFORMANCE_ERROR,),):- mock_produce.side_effect = Exception("Kafka down")+ mock_produce.return_value = None_evaluate_and_save_one(alert, now1, _make_stats())- mock_produce.side_effect = None+ mock_produce.return_value = MagicMock()mock_produce.reset_mock()_evaluate_and_save_one(alert, now2, _make_stats())- errored_calls = [- c- for c in mock_produce.call_args_list- if c.kwargs.get("event") and c.kwargs["event"].event == "$logs_alert_errored"- ]+ errored_calls = [c for c in mock_produce.call_args_list if c.kwargs.get("event_name") == "$logs_alert_errored"]assert len(errored_calls) == 1@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@@ -1456,34 +1423,29 @@ class TestEvaluateSingleAlert(APIBaseTest):now2 = datetime(2025, 1, 1, 0, 6, 0, tzinfo=UTC)with (- patch("products.alerts.backend.destinations.produce_internal_event") as mock_produce,+ patch("products.logs.backend.temporal.activities.produce_alert_internal_event") as mock_produce,patch("products.logs.backend.alert_error_classifier.classify_query_error",return_value=QueryErrorCategory.QUERY_PERFORMANCE_ERROR,),):- mock_produce.side_effect = Exception("Kafka down")+ mock_produce.return_value = None_evaluate_and_save_one(alert, now1, _make_stats())alert.refresh_from_db()assert alert.consecutive_failures == 0- mock_produce.side_effect = None+ mock_produce.return_value = MagicMock()mock_produce.reset_mock()mock_query_cls.return_value.execute_rolling_checks.side_effect = Exception("CH down")_evaluate_and_save_one(alert, now2, _make_stats())- errored_calls = [- c- for c in mock_produce.call_args_list- if c.kwargs.get("event") and c.kwargs["event"].event == "$logs_alert_errored"- ]+ errored_calls = [c for c in mock_produce.call_args_list if c.kwargs.get("event_name") == "$logs_alert_errored"]assert len(errored_calls) == 1@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.capture_exception")- def test_broken_notification_retried_after_kafka_failure(self, _mock_capture, mock_query_cls):+ def test_broken_notification_retried_after_kafka_failure(self, mock_query_cls):mock_query_cls.return_value.execute_rolling_checks.side_effect = Exception("Code: 160. DB::Exception: Estimated query execution time is too long")@@ -1493,23 +1455,21 @@ class TestEvaluateSingleAlert(APIBaseTest):now2 = datetime(2025, 1, 1, 0, 6, 0, tzinfo=UTC)with (- patch("products.alerts.backend.destinations.produce_internal_event") as mock_produce,+ patch("products.logs.backend.temporal.activities.produce_alert_internal_event") as mock_produce,patch("products.logs.backend.alert_error_classifier.classify_query_error",return_value=QueryErrorCategory.QUERY_PERFORMANCE_ERROR,),):- mock_produce.side_effect = Exception("Kafka down")+ mock_produce.return_value = None_evaluate_and_save_one(alert, now1, _make_stats())- mock_produce.side_effect = None+ mock_produce.return_value = MagicMock()mock_produce.reset_mock()_evaluate_and_save_one(alert, now2, _make_stats())auto_disabled_calls = [- c- for c in mock_produce.call_args_list- if c.kwargs.get("event") and c.kwargs["event"].event == "$logs_alert_auto_disabled"+ c for c in mock_produce.call_args_list if c.kwargs.get("event_name") == "$logs_alert_auto_disabled"]assert len(auto_disabled_calls) == 1@@ -1522,15 +1482,13 @@ class TestEvaluateSingleAlert(APIBaseTest):@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.increment_notification_failures")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.alerts.backend.destinations.produce_internal_event", side_effect=Exception("Kafka down"))- @patch("products.alerts.backend.destinations.capture_exception")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event", return_value=None)def test_notification_failures_counter_for_error_and_broken(self,_name,initial_state,initial_failures,expected_action,- _mock_capture,_mock_produce,mock_query_cls,mock_notif_failures,@@ -1666,7 +1624,7 @@ class TestEvaluateSingleAlertEndToEnd(ClickhouseTestMixin, APIBaseTest):"""@time_machine.travel("2025-12-16T10:33:00Z", tick=False)- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_breach_against_real_clickhouse_fires_alert(self, _mock_produce):# Five logs at 10:30 with a unique service. next_check_at=10:33,# window=5, M=1 → activity's query window is [10:28, 10:33), capturing@@ -1730,7 +1688,7 @@ class TestEvaluateSingleAlertEndToEnd(ClickhouseTestMixin, APIBaseTest):return LogsAlertConfiguration.objects.create(**defaults)@time_machine.travel("2025-12-16T10:35:00Z", tick=False)- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_n_of_m_progression_across_consecutive_evals(self, _mock_produce):# Real-CH version of the N-of-M progression test. M=3 N=2 over 5-min buckets.# Symmetric N-of-M: stays firing while breach_count >= N, resolves only@@ -1791,7 +1749,7 @@ class TestEvaluateSingleAlertEndToEnd(ClickhouseTestMixin, APIBaseTest):assert alert.state == LogsAlertConfiguration.State.NOT_FIRING@time_machine.travel("2025-12-16T10:25:00Z", tick=False)- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_cooldown_suppresses_resolve_notification_within_window(self, mock_produce):# Alert fires at next_check_at #1, resolve attempted at next_check_at #2# within cooldown_minutes → state transitions to NOT_FIRING but@@ -1824,7 +1782,7 @@ class TestEvaluateSingleAlertEndToEnd(ClickhouseTestMixin, APIBaseTest):assert mock_produce.call_count == 1 # but no second notification dispatched@time_machine.travel("2025-12-16T10:33:00Z", tick=False)- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_below_operator_fires_on_truly_silent_service(self, _mock_produce):# `execute_rolling_checks` always returns exactly `period_count` entries (zero# counts for silent services, since each period is a fixed-width@@ -1846,7 +1804,7 @@ class TestEvaluateSingleAlertEndToEnd(ClickhouseTestMixin, APIBaseTest):)@time_machine.travel("2025-12-16T10:33:00Z", tick=False)- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")def test_first_run_with_null_nca_anchors_on_now(self, _mock_produce):# Alert created with next_check_at=None (first eval after enable). The# activity falls back to `now` as the anchor; the query window is@@ -2353,11 +2311,11 @@ class TestEvaluateCohortBatchActivity(NonAtomicBaseTest):assert result.alerts_checked == 1@time_machine.travel("2025-01-01T00:01:00Z", tick=False)- @patch("products.alerts.backend.delivery_slo.get_instance_region", return_value="US")+ @patch("products.alerts.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.alerts.backend.destinations.flush_internal_events_producer", return_value=0)- @patch("products.alerts.backend.destinations.produce_internal_event")+ @patch("products.logs.backend.temporal.activities.flush_alert_internal_events")+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")@patch("products.logs.backend.temporal.activities._run_cohort_query")def test_undelivered_notification_rolls_back_state_before_save(self,diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.pyindex 40b5c88ffa10..3a8a3f4b5cc3 100644--- a/products/product_analytics/backend/presentation/insight.py+++ b/products/product_analytics/backend/presentation/insight.py@@ -128,7 +128,8 @@ from products.access_control.backend.presentation.access_control import (AccessControlViewSetMixin,UserAccessControlSerializerMixin,)-from products.alerts.backend.facade.api import delete_insight_alerts, insight_alerts_prefetch, serialize_insight_alerts+from products.alerts.backend.facade.api import delete_insight_alerts+from products.alerts.backend.presentation.views.insight_alerts import insight_alerts_prefetch, serialize_insight_alertsfrom products.dashboards.backend.facade.access import (DashboardAccessMethod,dashboard_access_method,diff --git a/products/replay_vision/backend/alert_destinations.py b/products/replay_vision/backend/alert_destinations.pyindex 836c5c4cda46..bdd196329db7 100644--- a/products/replay_vision/backend/alert_destinations.py+++ b/products/replay_vision/backend/alert_destinations.py@@ -4,7 +4,7 @@ from __future__ import annotationsfrom typing import Literal-from products.alerts.backend.destination_configs import DestinationType, EventKindSpec+from products.alerts.backend.facade.contracts import DestinationType, EventKindSpecEventKind = 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.pyindex 17b9fe017920..58884341b54f 100644--- a/products/replay_vision/backend/alert_state_machine.py+++ b/products/replay_vision/backend/alert_state_machine.py@@ -7,7 +7,7 @@ outcome via `apply_outcome`, the only function that mutates those two fields. Thrule at `.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml` enforcesthis in CI.-The decision logic lives in `products/alerts/backend/state_machine.py`, configured with+The decision logic lives in `products/alerts/backend/facade/lifecycle.py`, configured with`VISION_ALERT_POLICY`; this module owns the vision-shaped inputs and the model mutation."""@@ -18,7 +18,7 @@ from typing import TYPE_CHECKINGfrom posthog.dataclasses import frozen-from products.alerts.backend.state_machine import (+from products.alerts.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.pyindex 6d5d7262ee72..6d924e61943e 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 Qimport structlog-from products.alerts.backend.scheduling import (+from products.alerts.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.pyindex 850b28205d9b..4bf3bd725d2c 100644--- a/products/replay_vision/backend/api/vision_alerts.py+++ b/products/replay_vision/backend/api/vision_alerts.py@@ -18,21 +18,25 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.api.shared import UserBasicSerializerfrom posthog.event_usage import report_user_action+from posthog.exceptions import as_drf_validation_errorfrom posthog.models.team.team import Team+from posthog.models.user import User-from products.alerts.backend.destinations import count_active_alert_destinations-from products.alerts.backend.facade.api import (+from products.alerts.backend.facade.contracts import (AlertDestinationData,AlertDestinationValidationError,- AlertScheduleRestriction,DestinationType,+)+from products.alerts.backend.facade.destinations import (build_alert_destination_config,+ count_active_alert_destinations,create_alert_destination_hog_functions,soft_delete_alert_destinations,soft_delete_all_alert_destinations,- validate_and_normalize_schedule_restriction,validate_destination_data,)+from products.alerts.backend.facade.scheduling import validate_and_normalize_schedule_restriction+from products.alerts.backend.presentation.views.schedule_restriction import AlertScheduleRestrictionfrom products.replay_vision.backend.alert_destinations import (EVENT_KIND_CONFIG,MATCH_EVENT_KINDS,@@ -588,7 +592,6 @@ class VisionAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)configs = [build_alert_destination_config(- team=alert.team,spec=EVENT_KIND_CONFIG[kind],alert_id=str(alert.id),alert_name=alert.name,@@ -597,12 +600,16 @@ class VisionAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)for kind in event_kinds]- hog_functions = create_alert_destination_hog_functions(- configs,- request=self.request,- alert_id=str(alert.id),- allowed_event_ids=VISION_ALERT_EVENT_IDS,- )+ try:+ hog_function_ids = create_alert_destination_hog_functions(+ configs,+ team_id=alert.team_id,+ created_by_id=cast(User, request.user).id,+ alert_id=str(alert.id),+ allowed_event_ids=VISION_ALERT_EVENT_IDS,+ )+ except AlertDestinationValidationError as error:+ raise as_drf_validation_error(error)report_user_action(request.user,@@ -610,7 +617,7 @@ class VisionAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):{"alert_id": str(alert.id), "type": data["type"], "event_kinds": list(event_kinds)},request=request,)- response = VisionAlertDestinationResponseSerializer({"hog_function_ids": [hf.id for hf in hog_functions]})+ response = VisionAlertDestinationResponseSerializer({"hog_function_ids": list(hog_function_ids)})return Response(response.data, status=201)@extend_schema(@@ -626,12 +633,15 @@ class VisionAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):with transaction.atomic():alert = self._get_locked_alert()- soft_delete_alert_destinations(- team_id=self.team_id,- alert_id=str(alert.id),- allowed_event_ids=VISION_ALERT_EVENT_IDS,- hog_function_ids=hog_function_ids,- )+ try:+ soft_delete_alert_destinations(+ team_id=self.team_id,+ alert_id=str(alert.id),+ allowed_event_ids=VISION_ALERT_EVENT_IDS,+ hog_function_ids=hog_function_ids,+ )+ except AlertDestinationValidationError as error:+ raise as_drf_validation_error(error)report_user_action(request.user,diff --git a/products/replay_vision/backend/temporal/vision_alerts/activities.py b/products/replay_vision/backend/temporal/vision_alerts/activities.pyindex 011a3e59c917..ffb3ba037a3f 100644--- a/products/replay_vision/backend/temporal/vision_alerts/activities.py+++ b/products/replay_vision/backend/temporal/vision_alerts/activities.py@@ -22,15 +22,15 @@ from pydantic import BaseModelfrom posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exception+from posthog.kafka_client.client import ProduceResultfrom posthog.sync import database_sync_to_async-from products.alerts.backend.destinations import (- ProduceResult,+from products.alerts.backend.facade.destinations import (alert_internal_event_delivered,flush_alert_internal_events,produce_alert_internal_event,)-from products.alerts.backend.scheduling import is_utc_datetime_blocked, parse_blocked_windows_tuples+from products.alerts.backend.facade.scheduling import is_utc_datetime_blocked, parse_blocked_windows_tuplesfrom products.replay_vision.backend.alert_destinations import escape_slack_mrkdwnfrom products.replay_vision.backend.alert_state_machine import (AlertCheckOutcome,diff --git a/products/signals/backend/scout_harness/profile/builders.py b/products/signals/backend/scout_harness/profile/builders.pyindex 815d904f4321..87120b1cb82d 100644--- a/products/signals/backend/scout_harness/profile/builders.py+++ b/products/signals/backend/scout_harness/profile/builders.py@@ -44,7 +44,7 @@ from posthog.models.product_intent.product_intent import ProductIntentfrom posthog.models.team.team import Teamfrom products.actions.backend.models.action import Action-from products.alerts.backend.facade.api import redact_urls_in_name+from products.alerts.backend.facade.destinations import redact_urls_in_namefrom products.alerts.backend.models.alert import AlertConfigurationfrom products.business_knowledge.backend.models.constants import SourceStatusfrom products.business_knowledge.backend.models.knowledge_source import KnowledgeSourcediff --git a/pyproject.toml b/pyproject.tomlindex a973c7f5d45a..2f72dab3b0ca 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -568,6 +568,7 @@ ignore_imports = ["products.alerts.backend.presentation.views.alert -> products.alerts.backend.evaluation.validation","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.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",@@ -806,8 +807,6 @@ allow_indirect_imports = trueignore_imports = [# TODO: existing violations — move the presentation-shaped code out of the facade, or the# facade-shaped code out of presentation, and drop the line- "products.alerts.backend.facade.api -> products.alerts.backend.presentation.views.alert",- "products.alerts.backend.facade.api -> products.alerts.backend.presentation.views.alert_schedule_restriction","products.managed_warehouse.backend.facade.api -> products.managed_warehouse.backend.presentation.views","products.stamphog.backend.facade.webhooks -> products.stamphog.backend.presentation.webhooks","products.tasks.backend.facade.api -> products.tasks.backend.presentation.serializers",diff --git a/tach.toml b/tach.tomlindex 4d208694920b..c6d31badaa49 100644--- a/tach.toml+++ b/tach.toml@@ -173,6 +173,22 @@ depends_on = []layer = "modules"+# alerts — external consumers go through the facade: facade.contracts for the+# destination and delivery types, facade.destinations for destination configuration and+# dispatch, facade.email for alert mail, facade.lifecycle for the shared state machine,+# facade.scheduling for the scheduling math, facade.delivery_slo for delivery SLOs, and+# facade.api for the insight-alert reads and writes. presentation.views carries the DRF+# surface adopter products mount or reuse in process, which a facade may not hold.+[[interfaces]]+expose = [+ "backend\\.facade.*",+ "backend\\.presentation\\.views.*",+ "backend\\.routes.*",+]+from = [+ "products.alerts",+]+[[modules]]path = "products.analytics_platform"depends_on = [@@ -1287,6 +1303,35 @@ from = ["products.access_control",]+# Legacy leaks — core still runs the insight-alert pipeline itself: the alert check tasks+# under posthog/tasks/alerts/, the Temporal workflows under posthog/temporal/alerts/ and+# posthog/temporal/ai/anomaly_investigation/, and the PostHog AI product-analytics preset+# reach the alert models, the insight evaluation, the insight lifecycle adapter, the+# investigation episode reader and the Max tool directly. The exit is moving that pipeline+# into the product; the block drains as it moves, and keeps backend:contract-check off+# until it is empty.+# backend.models has a second exit of its own: pulse, dashboards, signals, the AI entity+# search and posthog/models/organization.py import it from production code outside core, so+# moving the pipeline does not by itself retire that line.+# tach interfaces have no consumer scoping, so this block opens the listed paths to every+# module, not only to the consumers named above.+[[interfaces]]+expose = [+ "backend\\.evaluation",+ "backend\\.evaluation\\.check_alert_for_insight",+ "backend\\.evaluation\\.contract.*",+ "backend\\.evaluation\\.detector.*",+ "backend\\.evaluation\\.dispatcher.*",+ "backend\\.evaluation\\.validation.*",+ "backend\\.insight_alert_state_machine.*",+ "backend\\.investigation_episode.*",+ "backend\\.max_tools.*",+ "backend\\.models.*",+]+from = [+ "products.alerts",+]+# Legacy leaks — core (posthog/ee), customer_analytics, reminders and signals still# import the Notebook ORM directly: file-system / search / reminders registries dispatch# on the model class, middleware returns a raw queryset, the read_data and notebook-contextdiff --git a/tools/hogli-commands/hogli_commands/product/ast_helpers.py b/tools/hogli-commands/hogli_commands/product/ast_helpers.pyindex 6ddc2f4b8af8..0d04125be378 100644--- a/tools/hogli-commands/hogli_commands/product/ast_helpers.py+++ b/tools/hogli-commands/hogli_commands/product/ast_helpers.py@@ -116,8 +116,36 @@ def get_model_names(backend_dir: Path) -> list[str]:return names+def _decorator_name(node: ast.expr) -> str | None:+ """The bare name of a decorator, with any call and any module prefix stripped."""+ target = node.func if isinstance(node, ast.Call) else node+ if isinstance(target, ast.Name):+ return target.id+ if isinstance(target, ast.Attribute):+ return target.attr+ return None+++def _keyword_is(node: ast.expr, name: str, value: bool) -> bool:+ if not isinstance(node, ast.Call):+ return False+ return any(+ kw.arg == name and isinstance(kw.value, ast.Constant) and kw.value.value is value for kw in node.keywords+ )+++def _is_frozen_dataclass_decorator(node: ast.expr) -> bool:+ """True for @dataclass(frozen=True) and for the house decorator, which is frozen by default."""+ name = _decorator_name(node)+ if name == "dataclass":+ return _keyword_is(node, "frozen", True)+ if name == "frozen":+ return not _keyword_is(node, "frozen", False)+ return False++def get_frozen_dataclass_names(file_path: Path) -> list[str]:- """Return names of @dataclass(frozen=True) classes in a file."""+ """Return names of frozen dataclasses in a file."""tree = ast_parse_safe(file_path)if not tree:return []@@ -125,18 +153,8 @@ def get_frozen_dataclass_names(file_path: Path) -> list[str]:for node in ast.walk(tree):if not isinstance(node, ast.ClassDef):continue- for dec in node.decorator_list:- if not isinstance(dec, ast.Call):- continue- func = dec.func- is_dc = (isinstance(func, ast.Name) and func.id == "dataclass") or (- isinstance(func, ast.Attribute) and func.attr == "dataclass"- )- if is_dc and any(- kw.arg == "frozen" and isinstance(kw.value, ast.Constant) and kw.value.value is True- for kw in dec.keywords- ):- names.append(node.name)+ if any(_is_frozen_dataclass_decorator(dec) for dec in node.decorator_list):+ names.append(node.name)return namesdiff --git a/tools/hogli-commands/hogli_commands/product/maturity.py b/tools/hogli-commands/hogli_commands/product/maturity.pyindex 2216483731e0..b54738ab7ca7 100644--- a/tools/hogli-commands/hogli_commands/product/maturity.py+++ b/tools/hogli-commands/hogli_commands/product/maturity.py@@ -274,15 +274,15 @@ def score_facade(backend_dir: Path) -> DimensionScore:parts.append("contracts (empty)")next_steps.append("backend/facade/contracts.py exists but defines no frozen dataclasses. Add "- "`@dataclass(frozen=True)` types describing every value the facade returns "- "(see products/visual_review/backend/facade/contracts.py)."+ "`@frozen` (from posthog.dataclasses) types describing every value the facade "+ "returns (see products/visual_review/backend/facade/contracts.py).")else:parts.append("no contracts")next_steps.append(- "Create backend/facade/contracts.py with frozen dataclasses that describe each "- "facade return value. No Django, no DRF — just stdlib types. This is the public "- "contract other products read against."+ "Create backend/facade/contracts.py with `@frozen` (from posthog.dataclasses) "+ "dataclasses that describe each facade return value. No Django, no DRF. This is "+ "the public contract other products read against.")# Facade — must have actual function definitions, not just re-exportsdiff --git a/tools/hogli-commands/hogli_commands/tests/test_ast_helpers.py b/tools/hogli-commands/hogli_commands/tests/test_ast_helpers.pyindex 6f5869e3a55e..16072ff51b91 100644--- a/tools/hogli-commands/hogli_commands/tests/test_ast_helpers.py+++ b/tools/hogli-commands/hogli_commands/tests/test_ast_helpers.py@@ -4,7 +4,7 @@ from pathlib import Pathimport pytest-from hogli_commands.product.ast_helpers import get_model_names+from hogli_commands.product.ast_helpers import get_frozen_dataclass_names, get_model_namesMODELS_SOURCE = """from django.db import models@@ -78,3 +78,59 @@ class TestGetModelNames:backend.mkdir()(backend / "models.py").write_text(NO_DJANGO_SOURCE)assert get_model_names(backend) == []+++FROZEN_DATACLASS_SOURCE = """+import posthog.dataclasses+from dataclasses import dataclass++from posthog.dataclasses import frozen+++@frozen+class HouseDefault:+ name: str+++@frozen(slots=True)+class HouseWithOptions:+ name: str+++@frozen(frozen=False)+class HouseOptedOut:+ name: str+++class HouseQualified:+ name: str+++@dataclass(frozen=True)+class StdlibFrozen:+ name: str+++@dataclass+class StdlibMutable:+ name: str+"""+++class TestGetFrozenDataclassNames:+ @pytest.mark.parametrize(+ "name, expected",+ [+ ("HouseDefault", True), # @frozen is frozen unless it says otherwise+ ("HouseWithOptions", True), # an unrelated keyword does not unfreeze it+ ("HouseOptedOut", False), # frozen=False is the opt-out+ ("HouseQualified", True), # module prefix stripped before matching+ ("StdlibFrozen", True),+ ("StdlibMutable", False), # stdlib is mutable unless frozen=True+ ],+ )+ def test_classification(self, tmp_path: Path, name: str, expected: bool) -> None:+ source = tmp_path / "contracts.py"+ source.write_text(FROZEN_DATACLASS_SOURCE)+ assert (name in get_frozen_dataclass_names(source)) is expected