: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
refactor(alerts): move lifecycle engine into alerts product (#73957)
Matt Puab167b44efca9
diff --git a/.agents/skills/adding-product-alerting/SKILL.md b/.agents/skills/adding-product-alerting/SKILL.mdindex 76ebae3b4536..942bf220c7f3 100644--- a/.agents/skills/adding-product-alerting/SKILL.md+++ b/.agents/skills/adding-product-alerting/SKILL.md@@ -36,12 +36,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 `common/alerting/state_machine.py`; express real product differences through `AlertPolicy`, not forks.+2. **One lifecycle machine.** Reuse `products/alerts/backend/state_machine.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.** `common/alerting/` stays pure Python. Reusable Django behavior belongs in `products/alerts/backend/`.+7. **Shared code has no product branches.** The lifecycle module stays pure Python. Reusable Django behavior belongs elsewhere in `products/alerts/backend/`.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.diff --git a/.agents/skills/adding-product-alerting/references/architecture.md b/.agents/skills/adding-product-alerting/references/architecture.mdindex 98b49506025a..54be8c2b6bca 100644--- a/.agents/skills/adding-product-alerting/references/architecture.md+++ b/.agents/skills/adding-product-alerting/references/architecture.md@@ -6,7 +6,7 @@ Use this reference to decide where code belongs before editing it.| Layer | Location | Owns || --------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ |-| Pure lifecycle decisions | `common/alerting/` | State transitions, policy decisions, and notification actions |+| 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 |@@ -35,7 +35,7 @@ Read [frontend-alerting.md](frontend-alerting.md) before adding or extending a p## Lifecycle contract-`common/alerting/state_machine.py` is pure Python.+`products/alerts/backend/state_machine.py` is pure Python.- `CheckInput` normalizes one product evaluation.- `AlertSnapshot` contains only fields needed for lifecycle decisions.diff --git a/.agents/skills/adding-product-alerting/references/extending-platform-alerting.md b/.agents/skills/adding-product-alerting/references/extending-platform-alerting.mdindex 8930669b57b4..29184e67ccbb 100644--- a/.agents/skills/adding-product-alerting/references/extending-platform-alerting.md+++ b/.agents/skills/adding-product-alerting/references/extending-platform-alerting.md@@ -6,7 +6,7 @@ Use this path when adding a reusable alert capability, option, or advanced behav| Capability | Primary source of truth | Also inspect || -------------------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |-| Lifecycle state, notification action, control-plane transition, or policy option | `common/alerting/state_machine.py` | Shared decision tests, every adopter policy and adapter, semgrep rule |+| 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 |@@ -21,7 +21,7 @@ If the change crosses rows, update each row deliberately. Do not hide a cross-la### Lifecycle-- Keep `common/alerting/` free of Django and product imports.+- Keep `products/alerts/backend/state_machine.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.@@ -141,7 +141,7 @@ Invoke the matching mandatory skills before editing their areas:Stop and keep the change product-owned when:- No second use case exists.-- The option leaks product model fields into `common/alerting/`.+- The option leaks product model fields into the shared state machine.- A generic helper would need product-name branches.- A destination option changes only one event kind's content.- A shared due query would require one product's state names or tenant model.diff --git a/.dockerignore b/.dockerignoreindex 8fb9cdba8b6d..a98362e6e693 100644--- a/.dockerignore+++ b/.dockerignore@@ -3,7 +3,6 @@!.devcontainer!.kearc!bin-!common/alerting!common/hogvm!common/esbuilder!common/migration_utilsdiff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.ymlindex 74bf649b2dff..3bced59d7189 100644--- a/.github/workflows/container-images-cd.yml+++ b/.github/workflows/container-images-cd.yml@@ -787,6 +787,7 @@ jobs:- bin/temporal-django-workerlogsAlerting:- 'posthog/temporal/logs_alerting/**'+ - 'products/alerts/backend/state_machine.py'- '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 9d4d1e1e20aa..0de68df81a5a 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@@ -1,7 +1,7 @@# Enforces the invariant that ALL writes to an alert configuration's `state` and# `consecutive_failures` go through the product's alert state machine module.#-# The decision logic is shared across products in common/alerting/state_machine.py;+# The decision logic is shared across products in products/alerts/backend/state_machine.py;# each product owns one module that is the single legal mutator of its alert model:# - products/logs/backend/alert_state_machine.py (apply_outcome)#@@ -9,7 +9,7 @@# (apply_user_reset, apply_enable, apply_disable, apply_snooze, apply_unsnooze,# apply_threshold_change), and the check-driven path goes through evaluate_alert_check.#-# If you need a new transition, add a helper in common/alerting/state_machine.py (or+# If you need a new transition, add a helper in products/alerts/backend/state_machine.py (or# the product's state machine module) rather than bypassing this rule — the point is# to keep the legal-transitions table readable in one place.#@@ -37,7 +37,7 @@ rules:alert.save(update_fields=update_fields)If you need a new transition type, add a helper in- common/alerting/state_machine.py (e.g. apply_<your_action>) and a+ products/alerts/backend/state_machine.py (e.g. apply_<your_action>) and aControlPlaneOutcome return — do not mutate these fields directly.languages: [python]severity: ERRORdiff --git a/Dockerfile b/Dockerfileindex 2cfe99494aa4..6c39ed6c5db7 100644--- a/Dockerfile+++ b/Dockerfile@@ -188,7 +188,6 @@ COPY manage.py manage.pyCOPY common/esbuilder common/esbuilderCOPY common/hogvm common/hogvm/COPY common/migration_utils common/migration_utils/-COPY common/alerting common/alerting/COPY posthog posthog/COPY products/ products/COPY ee ee/@@ -407,7 +406,6 @@ COPY --chown=posthog:posthog posthog posthog/COPY --chown=posthog:posthog ee ee/COPY --chown=posthog:posthog common/hogvm common/hogvm/COPY --chown=posthog:posthog common/migration_utils common/migration_utils/-COPY --chown=posthog:posthog common/alerting common/alerting/COPY --chown=posthog:posthog products products/# Stamphog ships the review engine + owners resolver from this checkout into its sandbox at# runtime (products/stamphog/backend/temporal/activities.py), so both must exist in the image.diff --git a/Dockerfile.llm-analytics b/Dockerfile.llm-analyticsindex 9526b3cabc97..fa9a261174c2 100644--- a/Dockerfile.llm-analytics+++ b/Dockerfile.llm-analytics@@ -53,7 +53,6 @@ COPY manage.py manage.pyCOPY common/esbuilder common/esbuilderCOPY common/hogvm common/hogvm/COPY common/migration_utils common/migration_utils/-COPY common/alerting common/alerting/COPY posthog posthog/COPY products/ products/COPY ee ee/diff --git a/common/alerting/__init__.py b/common/alerting/__init__.pydeleted file mode 100644index 39f10338ba34..000000000000--- a/common/alerting/__init__.py+++ /dev/null@@ -1,43 +0,0 @@-from common.alerting.state_machine import (- LOGS_ALERT_POLICY,- MAX_CONSECUTIVE_FAILURES,- AlertCheckOutcome,- AlertPolicy,- AlertSnapshot,- AlertState,- CheckInput,- ControlPlaneOutcome,- InvalidTransition,- NotificationAction,- Outcome,- apply_disable,- apply_enable,- apply_snooze,- apply_threshold_change,- apply_unsnooze,- apply_user_reset,- evaluate_alert_check,- evaluate_alert_failure,-)--__all__ = [- "LOGS_ALERT_POLICY",- "MAX_CONSECUTIVE_FAILURES",- "AlertCheckOutcome",- "AlertPolicy",- "AlertSnapshot",- "AlertState",- "CheckInput",- "ControlPlaneOutcome",- "InvalidTransition",- "NotificationAction",- "Outcome",- "apply_disable",- "apply_enable",- "apply_snooze",- "apply_threshold_change",- "apply_unsnooze",- "apply_user_reset",- "evaluate_alert_check",- "evaluate_alert_failure",-]diff --git a/common/alerting/state_machine.py b/products/alerts/backend/state_machine.pysimilarity index 99%rename from common/alerting/state_machine.pyrename to products/alerts/backend/state_machine.pyindex ab21a66704c7..25a2b4b19634 100644--- a/common/alerting/state_machine.py+++ b/products/alerts/backend/state_machine.py@@ -12,7 +12,7 @@ while an alert stays firing; billing re-notifies once per cooldown window). Thosdifferences are expressed as an `AlertPolicy` so each product is a configuration ofthe same decision table rather than a fork of it.-This module is pure Python — no Django, no product imports. Products own persistence:+This module is pure Python. It has no Django or product-model imports. Products own persistence:they build a snapshot from their model, call the machine, and apply the outcome throughtheir product-local `apply_outcome` (the single legal mutator, enforced by semgrep —see `.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml`).diff --git a/common/alerting/test/test_state_machine.py b/products/alerts/backend/test/test_state_machine.pysimilarity index 99%rename from common/alerting/test/test_state_machine.pyrename to products/alerts/backend/test/test_state_machine.pyindex e7a255b37929..94c157a5e89f 100644--- a/common/alerting/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 common.alerting.state_machine import (+from products.alerts.backend.state_machine import (LOGS_ALERT_POLICY,AlertCheckOutcome,AlertPolicy,diff --git a/products/logs/backend/alert_state_machine.py b/products/logs/backend/alert_state_machine.pyindex 694c30116781..b1fb389a55f5 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 the shared machine at `common/alerting/state_machine.py`+The decision logic itself lives in `products/alerts/backend/state_machine.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 common.alerting.state_machine import (+from products.alerts.backend.state_machine import (LOGS_ALERT_POLICY,MAX_CONSECUTIVE_FAILURES,AlertCheckOutcome,diff --git a/tach.toml b/tach.tomlindex cbbe4ba03b58..0d0c3aa793f5 100644--- a/tach.toml+++ b/tach.toml@@ -36,12 +36,6 @@ depends_on = [layer = "modules"utility = true-[[modules]]-path = "common.alerting"-depends_on = []-layer = "modules"-utility = true-[[modules]]path = "ee"depends_on = [