: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): document adding alerting to products (#68940)
Matt Pua126446278a28
diff --git a/.agents/skills/adding-product-alerting/SKILL.md b/.agents/skills/adding-product-alerting/SKILL.mdnew file mode 100644index 000000000000..d30bb2f12d79--- /dev/null+++ b/.agents/skills/adding-product-alerting/SKILL.md@@ -0,0 +1,56 @@+---+name: adding-product-alerting+description: >+ Recommended repo-engineering guide when adding alerting to a PostHog product or+ extending the shared alerts platform. Routes lifecycle state machines,+ AlertPolicy, destinations, HogFunction dispatch, email, fixed-cadence scheduling,+ insight evaluation, and the AlertWizard. Use for product alert implementations,+ shared destination types, lifecycle or scheduling options, advanced alert settings,+ and platform alert infrastructure. Not for configuring alerts in an existing product.+---++# Adding and extending product alerting++> [!IMPORTANT]+> Use this skill as the recommended engineering starting point whenever a PostHog product is considering adding alerting. Start here before creating a product-local alert framework.++This skill covers two jobs:++1. Add platform alerting to a product by composing the shared lifecycle, destination, delivery, scheduling, email, and frontend primitives.+2. Extend the alerts platform when a reusable capability, option, or advanced behavior belongs in shared infrastructure.++## Route first++| Request | Path | Read |+| -------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------ |+| Add alerting to a product | Adopt | [adopting-platform-alerting.md](references/adopting-platform-alerting.md) |+| Add a lifecycle rule, destination type, delivery behavior, schedule primitive, email capability, wizard option, or shared evaluation feature | Extend | [extending-platform-alerting.md](references/extending-platform-alerting.md) |+| Change behavior for one existing product | Adopt first | Keep it product-owned unless the behavior is reusable and backed by a real second use case |+| Understand ownership or choose the correct layer | Architecture | [architecture.md](references/architecture.md) |+| Configure or author an existing logs or error tracking alert | Out of scope | Use `authoring-log-alerts` or `authoring-error-tracking-alerts` |+| Add real-time in-app notifications | Out of scope | Use `sending-notifications` |++## Platform invariants++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.+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 math, but keep model-specific due predicates and calendar scheduling with the adopter.+7. **Shared code has no product branches.** `common/alerting/` stays pure Python. Reusable Django behavior belongs in `products/alerts/backend/`.+8. **Defaults remain backward compatible.** New platform options must preserve existing adopters until they explicitly opt in.++## Current limits++There is no generic alert base model, product registry, push-mode `submit_check(...)`, generic Temporal harness, or shared calendar scheduler. Do not invent a parallel framework around those missing pieces. For non-insight products, keep evaluation, persistence, due queries, history, and orchestration in the product until a shared contract lands.++## Reference appendix++| Topic | Reference |+| --------------------------------------------------------- | --------------------------------------------------------------------------- |+| Layer ownership, public contracts, and reference adopters | [architecture.md](references/architecture.md) |+| Add alerting to a product | [adopting-platform-alerting.md](references/adopting-platform-alerting.md) |+| Extend shared alert infrastructure | [extending-platform-alerting.md](references/extending-platform-alerting.md) |diff --git a/.agents/skills/adding-product-alerting/references/adopting-platform-alerting.md b/.agents/skills/adding-product-alerting/references/adopting-platform-alerting.mdnew file mode 100644index 000000000000..8096c37e4173--- /dev/null+++ b/.agents/skills/adding-product-alerting/references/adopting-platform-alerting.md@@ -0,0 +1,113 @@+# Add platform alerting to a product++Use this path when a product needs alerting. Compose the existing platform before adding shared abstractions.++## 1. Define the product contract++Write down the product-specific inputs before coding:++- What data is evaluated and what constitutes breached, clear, inconclusive, transient error, and permanent error?+- Which lifecycle states and control-plane actions are user-visible?+- Is evaluation fixed-cadence or calendar-aligned?+- Which notification event kinds exist, such as firing, resolved, errored, or broken?+- Which destination types are allowed?+- Does the product need HogFunction delivery, email, or both?+- What fields belong in check history and detail pages?++Do not add a new `AlertPolicy` option merely because the product might need it. First confirm an existing policy cannot express the behavior and that the difference is intentional.++## 2. Add product persistence and isolation++The product owns its alert configuration and check-history models.++- Every tenant-data model needs `team_id` and fail-closed scoping.+- Store the fields required to construct `AlertSnapshot`, plus product evaluation and scheduling fields.+- Keep writes that must agree in a narrow `transaction.atomic()` block.+- Do not perform notification delivery inside the transaction.++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`.++1. Select or define the product's `AlertPolicy`.+2. Convert the model and recent history into the shared snapshot.+3. Convert the domain evaluation into `CheckInput`.+4. Call `evaluate_alert_check(...)` or `evaluate_alert_failure(...)`.+5. Apply every shared outcome through one product-owned `apply_outcome` function.+6. Route control-plane actions through the shared helpers and the same mutator.+7. Extend the alert-state semgrep rule to cover the product backend and exclude only its mutator and tests.++Do not mutate `state` or `consecutive_failures` elsewhere.++## 4. Define notification content and destinations++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`.+- Scope deletion with the team, alert ID, and allowed event IDs.++Shared support for a destination does not opt the product into it.++## 5. Make delivery transactional with lifecycle state++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.+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.++## 6. Add scheduling and due selection++For fixed-minute checks:++- Reuse `compute_shard_offset_seconds(...)` and `advance_next_check_at(...)`.+- Wrap the shard function if the product scheduler interval differs from the shared default.+- Keep one stable shard calculation across create, update, and evaluation paths.+- Implement and test a product-specific due predicate with team scoping, enabled state, broken state, snooze state, and `next_check_at` behavior.++For calendar scheduling, keep timezone anchors and restrictions in the product. Do not mix calendar semantics into the fixed-cadence helpers.++## 7. Add product orchestration++The product owns its evaluator, history, due query, batching, Temporal or Celery orchestration, retries, and metrics.++Avoid large Temporal payloads. Pass alert IDs and references, then load data inside activities. Keep notification dispatch out of database transactions.++## 8. Add the frontend++Use the shared `AlertWizard` when the product creates HogFunction-backed alerts.++- Configure a unique `logicKey`.+- Supply supported sub-template IDs, triggers, and destinations.+- Add product-specific configuration outside the shared wizard when it is not a reusable HogFunction input.+- Keep the traditional HogFunction editor as the advanced fallback when the product already supports it.+- Ensure every network-backed action has loading and double-submit protection.++A product may skip `AlertWizard` if it has no HogFunction destinations.++## 9. Verify the boundaries++Add the lowest-level tests that cover real regressions:++- Shared state-machine decision cases used by the product.+- Product snapshot and single-mutator behavior.+- Destination validation, generated configs, ownership-safe deletion, and event property completeness.+- Delivery success, enqueue failure, flush failure, and rollback before save.+- Due predicate and cadence/shard behavior.+- API schemas and tenant isolation.+- Wizard logic and product entry points when frontend alert creation is added.++Invoke `/writing-tests` when adding or substantially changing tests. Also invoke `/improving-drf-endpoints` for serializer or viewset changes, `/adopting-generated-api-types` when frontend API types are involved, and `/writing-kea-logics` when adding or changing alert kea logic.diff --git a/.agents/skills/adding-product-alerting/references/architecture.md b/.agents/skills/adding-product-alerting/references/architecture.mdnew file mode 100644index 000000000000..1f4f9073e157--- /dev/null+++ b/.agents/skills/adding-product-alerting/references/architecture.md@@ -0,0 +1,85 @@+# Shared alerting architecture++Use this reference to decide where code belongs before editing it.++## Layer map++| Layer | Location | Owns |+| ---------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |+| Pure lifecycle and cadence math | `common/alerting/` | State transitions, policy decisions, notification actions, fixed-minute cadence and sharding |+| Shared Django alert infrastructure | `products/alerts/backend/` | 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 |+| Product UI | `products/<name>/frontend/` or `frontend/src/scenes/<name>/` | Alert settings, product-specific fields, entry points, detail pages, and wizard configuration |++`products/logs` is the reference adopter for the shared lifecycle, fixed-cadence scheduling, HogFunction destinations, delivery rollback, and product-owned Temporal orchestration.++Insight alerts are the reference for email delivery and calendar scheduling. Their model, API, and query evaluation live in `products/alerts/backend/` and `posthog/tasks/alerts/`. The evaluation package is shared across insight query kinds, but it is not a generic evaluator for unrelated products.++## Lifecycle contract++`common/alerting/state_machine.py` is pure Python.++- `CheckInput` normalizes one product evaluation.+- `AlertSnapshot` contains only fields needed for lifecycle decisions.+- `AlertPolicy` represents deliberate differences between adopters. Its defaults are existing behavior, not a menu of speculative options.+- `evaluate_alert_check(...)` and `evaluate_alert_failure(...)` return `AlertCheckOutcome` without persistence.+- Control-plane helpers such as `apply_enable`, `apply_disable`, `apply_snooze`, and `apply_threshold_change` return `ControlPlaneOutcome`.+- `NotificationAction` tells the product which event to deliver.++The product converts its model to a snapshot and applies the outcome through one local `apply_outcome` function. Extend `.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml` when another product adopts this contract.++Error behavior is load-bearing:++- Failed checks do not clear an already firing alert.+- Inconclusive checks preserve state and failure count.+- Transient errors are silent unless the policy opts into counting them.+- Error notification normally occurs on the first failure edge.+- Delivery failure must not consume a lifecycle or failure-counter edge that should be retried.++## Destination contract++Product-facing destination setup is exported from `products.alerts.backend.facade.api`:++- `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 Slack, Discord, webhook, or Microsoft Teams HogFunction payloads. Products own event IDs, event properties, wording, actions, and their allowed destination list.++Deletion is fail-closed. Always scope it with `team_id`, `alert_id`, and the product's allowed event IDs.++## Delivery contract++HogFunction notification workers use `products.alerts.backend.destinations` directly:++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.+3. `alert_internal_event_delivered(...)` checks whether the producer acknowledged each internal event after the flush.+4. The product persists notification-dependent lifecycle changes only for acknowledged internal events.++This 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.++## Scheduling contract++`common/alerting/scheduling.py` supports fixed-minute cadences:++- `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.++Use the scheduler's real interval when computing shards. Use the same shard function when creating, updating, and advancing an alert.++Due eligibility stays product-specific because model fields, states, snooze behavior, and tenant constraints differ. Calendar behavior such as team-local anchors, schedule restrictions, and weekend skipping remains separate from fixed-grid scheduling.++## Frontend contract++`AlertWizard` is a shared HogFunction creation flow, not a lifecycle engine.++Adopters provide keyed `alertWizardLogic` props with supported sub-template IDs, `WizardTrigger[]`, `WizardDestination[]`, and optional URL/preset behavior. Compatibility comes from HogFunction sub-templates. Backend destination support alone does not make an option available in the wizard.++Keep product business logic in kea. Follow `frontend/src/AGENTS.md`, use generated API types, and guard network submissions from double clicks.diff --git a/.agents/skills/adding-product-alerting/references/extending-platform-alerting.md b/.agents/skills/adding-product-alerting/references/extending-platform-alerting.mdnew file mode 100644index 000000000000..b85349533d8c--- /dev/null+++ b/.agents/skills/adding-product-alerting/references/extending-platform-alerting.md@@ -0,0 +1,134 @@+# Extend the alerts platform++Use this path when adding a reusable alert capability, option, or advanced behavior. Keep a change product-local when only one product needs it and the shared contract would become speculative.++## 1. Classify the extension++| 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 |+| Fixed-cadence or shard behavior | `common/alerting/scheduling.py` | Product wrappers, create/update paths, due queries, scheduler interval |+| 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 |++If the change crosses rows, update each row deliberately. Do not hide a cross-layer contract in one product adapter.++## 2. Preserve extension rules++### Lifecycle++- Keep `common/alerting/` free of Django and product 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.+- Audit delivery rollback so a new notification action cannot consume an edge before delivery succeeds.++### Scheduling++- Keep fixed-grid math separate from calendar and timezone rules.+- Make scheduler interval assumptions explicit.+- Preserve deterministic UUID-based sharding and stable steady-state cadence.+- Test missed intervals, drift healing, cadence changes, and boundary times.+- Keep due eligibility with the product unless a real cross-product model contract exists.++### Destinations and advanced destination options++A 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`.+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`.+5. Decide which products explicitly allow the destination and update their destination editors or display logic.+6. Add the option to `AlertWizard` only where supported by the relevant sub-template.+7. Cover validation, generated payloads, ownership-safe deletion, CDP template behavior, product rendering, and wizard compatibility.++For an advanced option on an existing destination, decide whether it is transport-wide or product-specific. Transport-wide options belong in typed shared destination data and the shared builder. Product-only wording, event properties, and event-kind behavior remain in `EventKindSpec` and the product adapter.++### Delivery++- Treat event creation, producer flush, and producer acknowledgement as separate phases.+- Do not describe producer acknowledgement as final destination delivery. HogFunction execution and external destination delivery happen downstream.+- Keep batch flushing efficient and bounded.+- Keep helpers non-throwing only where the caller can make an explicit rollback decision from the return value.+- Add metrics and structured failure context for new dispatch phases.+- Verify that partial batch production failure rolls back only affected alerts.+++- Keep `send_alert_email(...)` a transport helper, not a product policy engine.+- Preserve caller ownership of recipients, templates, context, and campaign keys.+- Add shared options only when multiple alert types need the same transport behavior.+- Do not weaken retry or deduplication behavior by generating unstable campaign keys inside the helper.++### Shared insight evaluation++`products/alerts/backend/evaluation/` is kind-agnostic within insight alerts. Extend its contract when adding a query kind or comparison behavior:++1. Define the alert config schema and validation.+2. Add or update the extractor that produces `ExtractionResult`.+3. Keep comparison and breach formatting independent from query execution where possible.+4. Register dispatch by query kind without branching in unrelated extractors.+5. Gate unsupported or feature-flagged kinds consistently across create, update, and simulate paths.+6. Regenerate OpenAPI and frontend types after serializer/schema changes.++Do not route unrelated product evaluators through this package solely because it is named `evaluation`.++### AlertWizard++- Put business logic in keyed kea logic, not React hooks.+- Keep trigger/destination compatibility derived from HogFunction sub-templates.+- Add reusable UI options only when their backend input contract is shared.+- Keep product-only fields in the product UI and pass the resulting HogFunction inputs into the wizard contract.+- Preserve URL restoration, existing-alert detection, testing, loading, and double-submit behavior.++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.+- 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.++Do not expose internal helpers merely for convenience. A facade export is a compatibility commitment.++## 4. Prove backward compatibility++Verify both the shared layer and reference adopters:++- Pure lifecycle or scheduling unit tests.+- Destination, delivery, email, or evaluation tests for the changed contract.+- Logs tests for lifecycle, scheduling, HogFunction delivery, and rollback changes.+- Insight alert tests for model/API, evaluation, email, or calendar scheduling changes.+- `AlertWizard` logic tests and at least one adopter path for frontend changes.+- OpenAPI generation and frontend typecheck for API contract changes.+- The alert-state semgrep rule when lifecycle mutation paths change.++Invoke the matching mandatory skills before editing their areas:++| Change | Skill |+| --------------------------------------------------------- | ------------------------------- |+| Serializer or viewset | `/improving-drf-endpoints` |+| Django model or migration | `/django-migrations` |+| Frontend handwritten API usage or generated type adoption | `/adopting-generated-api-types` |+| Tests | `/writing-tests` |+| MCP tools or `tools.yaml` | `/implementing-mcp-tools` |+| AlertWizard or product kea logic | `/writing-kea-logics` |++## 5. Reject the wrong abstraction++Stop and keep the change product-owned when:++- No second use case exists.+- The option leaks product model fields into `common/alerting/`.+- 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.+- A wizard option has no shared HogFunction input contract.++The platform should grow from proven adopter needs, not from guessed future flexibility.