Skip to content

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

feat(alerts): deliver allowlisted insight alerts natively on the platform (#114220)

Jimmy Zhu0d892228384f
diff --git a/products/alerts/backend/platform_source_cycle.py b/products/alerts/backend/platform_source_cycle.py
index 5958981c573a..34fc4e8e8849 100644
--- a/products/alerts/backend/platform_source_cycle.py
+++ b/products/alerts/backend/platform_source_cycle.py
@@ -1,8 +1,9 @@
"""Evaluation of due insight alerts on the shared alerts platform.
A parallel run. The production insight fleet evaluates the same alerts against
-`AlertConfiguration` and is the only stack that notifies anyone. This decides what the platform
-would have said and delivers nothing.
+`AlertConfiguration` and notifies their destinations. This decides what the platform would have
+said, and asks for a delivery only for the alerts in `LIVE_DELIVERY_INSIGHT_ALERT_IDS`. The
+platform still sends only to projects on its live delivery flag.
Each platform row resolves to its production alert through `legacy_configuration_id`, because
`check_alert_for_insight` reads the insight, the threshold and the condition off that model. The
@@ -17,11 +18,13 @@ same set of checks.
import time
from dataclasses import replace
from datetime import UTC, datetime
+from typing import Final
from django.conf import settings
import structlog
+from posthog.cdp.internal_events import LEGACY_INSIGHT_ALERT_EVENT
from posthog.clickhouse.client.connection import ClickHouseUser
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.errors import CH_TRANSIENT_ERRORS, QueryErrorCategory, classify_query_error
@@ -33,12 +36,16 @@ from posthog.temporal.alerts.admission import admit_evaluation_slots, release_ev
from products.alerts.backend.evaluation import check_alert_for_insight
from products.alerts.backend.evaluation.contract import AlertExtractionError
from products.alerts.backend.insight_alert_state_machine import INSIGHT_ALERT_POLICY, insight_snapshot
+from products.alerts.backend.logic.alert_email import INSIGHT_ALERT_ERRORED_EVENT_ID
from products.alerts.backend.models.alert import AlertConfiguration
from products.alerts_platform.backend.facade.api import due_checks, slot_of
from products.alerts_platform.backend.facade.contracts import (
+ AlertDeliveryRequest,
+ AlertEventKind,
PlatformAlertCheckInput,
PlatformAlertOutcome,
SkipReason,
+ SourceBatchEvaluation,
SourceKind,
)
from products.alerts_platform.backend.facade.lifecycle import (
@@ -88,6 +95,20 @@ EVALUATED_INTERVALS = frozenset(
)
+# The production insight alerts whose platform evaluations ask for a native delivery, as a test. The
+# platform's live delivery flag still has to be on for the project, and every other insight alert
+# keeps production as its only deliverer. Widening the test means adding an id here.
+LIVE_DELIVERY_INSIGHT_ALERT_IDS: Final = frozenset({"01a11d6f-598e-0000-8529-4bcb65526f6d"})
+
+# Which event each announced kind's destinations listen on. A resolve is left out, because
+# production never announces one and the analytics platform team has not agreed to start. A kind
+# with no event id reaches no destination.
+_EVENT_IDS_BY_KIND: Final[dict[str, str]] = {
+ AlertEventKind.FIRING.value: LEGACY_INSIGHT_ALERT_EVENT,
+ AlertEventKind.ERRORED.value: INSIGHT_ALERT_ERRORED_EVENT_ID,
+}
+
+
def is_evaluated_on_the_platform(alert: AlertConfiguration) -> bool:
"""Threshold alerts on a 15-minute or slower cadence. A detector alert makes its own decision,
and the LLM detector makes a charged model call, so evaluating either in parallel costs twice."""
@@ -129,11 +150,12 @@ def evaluate_insight_check(
*,
held_until: float,
evaluation_id: str,
-) -> PlatformAlertOutcome | None:
+) -> SourceBatchEvaluation | None:
"""Decides one admitted check, then frees its slot.
- Returns None when the configuration is no longer due, because an earlier attempt already
- recorded it or it was edited out of the batch. Writes nothing.
+ Returns the outcome with its delivery, if it asks for one. Returns None when the configuration
+ is no longer due, because an earlier attempt already recorded it or it was edited out of the
+ batch. Writes nothing.
"""
try:
checks = due_checks(team_id, SourceKind.INSIGHT.value, slot, cutoff, configuration_ids=[configuration_id])
@@ -145,11 +167,30 @@ def evaluate_insight_check(
lag_ms = int((datetime.now(UTC) - checks[0].next_check_at).total_seconds() * 1000)
if lag_ms > 0:
safe_record(record_scheduler_lag, SourceKind.INSIGHT.value, lag_ms)
- return _decide(checks[0], cutoff, evaluation_id=evaluation_id)
+ outcome = _decide(checks[0], cutoff, evaluation_id=evaluation_id)
+ delivery = _delivery(checks[0], outcome)
+ return SourceBatchEvaluation(outcomes=(outcome,), deliveries=(delivery,) if delivery is not None else ())
finally:
release_evaluation_slot(configuration_id, held_until=held_until, key=INFLIGHT_KEY)
+def _delivery(check: PlatformAlertCheckInput, outcome: PlatformAlertOutcome) -> AlertDeliveryRequest | None:
+ if outcome.kind.value not in _EVENT_IDS_BY_KIND:
+ return None
+ legacy_id = str(check.legacy_configuration_id) if check.legacy_configuration_id is not None else None
+ if legacy_id not in LIVE_DELIVERY_INSIGHT_ALERT_IDS:
+ return None
+ return AlertDeliveryRequest(
+ source=SourceKind.INSIGHT,
+ team_id=check.team_id,
+ configuration_id=str(check.id),
+ # The recorded key unchanged, so the delivery addresses the row this check wrote.
+ evaluation_key=outcome.evaluation_key,
+ destination_alert_id=legacy_id,
+ event_ids_by_kind=_EVENT_IDS_BY_KIND,
+ )
+
+
def _legacy_alert(check: PlatformAlertCheckInput) -> AlertConfiguration | None:
if check.legacy_configuration_id is None:
return None
diff --git a/products/alerts/backend/temporal/platform_evaluate.py b/products/alerts/backend/temporal/platform_evaluate.py
index 6fec106fddeb..31819f07da75 100644
--- a/products/alerts/backend/temporal/platform_evaluate.py
+++ b/products/alerts/backend/temporal/platform_evaluate.py
@@ -24,12 +24,14 @@ with workflow.unsafe.imports_passed_through():
from products.alerts_platform.backend.facade.contracts import (
RECORD_OUTCOMES_ACTIVITY,
+ AlertDeliveryRequest,
PlatformAlertOutcome,
+ SourceBatchEvaluation,
SourceEvaluationInputs,
SourceKind,
SourceOutcomeInputs,
)
- from products.alerts_platform.backend.facade.temporal import source_evaluation_timeout
+ from products.alerts_platform.backend.facade.temporal import source_evaluation_timeout, start_deliveries
PLAN_START_TO_CLOSE = dt.timedelta(seconds=10)
PLAN_SCHEDULE_TO_CLOSE = dt.timedelta(seconds=20)
@@ -77,7 +79,7 @@ def plan_platform_insight_batch_activity(inputs: InsightBatchPlanInputs) -> list
@activity.defn
@close_db_connections
-def evaluate_platform_insight_check_activity(inputs: InsightCheckInputs) -> PlatformAlertOutcome | None:
+def evaluate_platform_insight_check_activity(inputs: InsightCheckInputs) -> SourceBatchEvaluation | None:
"""Sync, so the thread this blocks is a slot Temporal is accounting for."""
from products.alerts.backend.platform_source_cycle import evaluate_insight_check # noqa: PLC0415
@@ -95,8 +97,8 @@ def evaluate_platform_insight_check_activity(inputs: InsightCheckInputs) -> Plat
@workflow.defn(name="insight-alert-platform-evaluate")
class InsightAlertPlatformEvaluateWorkflow(PostHogWorkflow):
- """Evaluates one batch key and records what it decided. Starts no deliveries: the production
- insight fleet is the only stack that notifies anyone."""
+ """Evaluates one batch key, records what it decided, and starts the deliveries its checks asked
+ for. Only the alerts the insight source allowlists ask for one."""
inputs_cls = SourceEvaluationInputs
@@ -135,7 +137,9 @@ class InsightAlertPlatformEvaluateWorkflow(PostHogWorkflow):
# workflow would otherwise be recorded as a partial batch.
if isinstance(result, BaseException) and not isinstance(result, ActivityError):
raise result
- outcomes = tuple(outcome for outcome in settled if isinstance(outcome, PlatformAlertOutcome))
+ evaluations = [result for result in settled if isinstance(result, SourceBatchEvaluation)]
+ outcomes: tuple[PlatformAlertOutcome, ...] = tuple(o for e in evaluations for o in e.outcomes)
+ deliveries: tuple[AlertDeliveryRequest, ...] = tuple(d for e in evaluations for d in e.deliveries)
if len(outcomes) < len(settled):
workflow.logger.warning(
"%d of %d platform insight checks reached no outcome", len(settled) - len(outcomes), len(settled)
@@ -150,6 +154,9 @@ class InsightAlertPlatformEvaluateWorkflow(PostHogWorkflow):
schedule_to_close_timeout=RECORD_SCHEDULE_TO_CLOSE,
retry_policy=RetryPolicy(maximum_attempts=3),
)
+
+ # Started only after the record, because a delivery reads the history row the record writes.
+ await start_deliveries(deliveries)
return len(outcomes)
diff --git a/products/alerts/backend/test/test_platform_evaluate_workflow.py b/products/alerts/backend/test/test_platform_evaluate_workflow.py
index 617ec9ba04c3..bff1e29d553b 100644
--- a/products/alerts/backend/test/test_platform_evaluate_workflow.py
+++ b/products/alerts/backend/test/test_platform_evaluate_workflow.py
@@ -1,8 +1,11 @@
import uuid
from collections.abc import AsyncIterator
+from django.conf import settings
+
import pytest_asyncio
from temporalio import activity
+from temporalio.api.enums.v1 import EventType
from temporalio.exceptions import ApplicationError
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
@@ -16,8 +19,10 @@ from products.alerts.backend.temporal.platform_evaluate import (
from products.alerts_platform.backend.facade.contracts import (
RECORD_OUTCOMES_ACTIVITY,
AlertBatchKey,
+ AlertDeliveryRequest,
AlertEventKind,
PlatformAlertOutcome,
+ SourceBatchEvaluation,
SourceEvaluationInputs,
SourceKind,
SourceOutcomeInputs,
@@ -42,17 +47,26 @@ async def test_a_check_that_fails_does_not_stop_the_batch_recording_the_rest(env
return list(ADMITTED)
@activity.defn(name="evaluate_platform_insight_check_activity")
- async def evaluate(inputs: InsightCheckInputs) -> PlatformAlertOutcome | None:
+ async def evaluate(inputs: InsightCheckInputs) -> SourceBatchEvaluation | None:
if inputs.configuration_id == ADMITTED[0]:
raise ApplicationError("query failed", non_retryable=True)
- return PlatformAlertOutcome(
+ outcome = PlatformAlertOutcome(
configuration_id=uuid.UUID(inputs.configuration_id),
evaluation_key="slot:2026-09-16T10:00:00+00:00",
- kind=AlertEventKind.CHECK,
- new_state="not_firing",
- notified=False,
+ kind=AlertEventKind.FIRING,
+ new_state="firing",
+ notified=True,
consecutive_failures=0,
)
+ delivery = AlertDeliveryRequest(
+ source=SourceKind.INSIGHT,
+ team_id=1,
+ configuration_id=inputs.configuration_id,
+ evaluation_key=outcome.evaluation_key,
+ destination_alert_id="legacy-alert",
+ event_ids_by_kind={"firing": "$insight_alert_firing"},
+ )
+ return SourceBatchEvaluation(outcomes=(outcome,), deliveries=(delivery,))
@activity.defn(name=RECORD_OUTCOMES_ACTIVITY)
async def record(inputs: SourceOutcomeInputs) -> int:
@@ -66,7 +80,7 @@ async def test_a_check_that_fails_does_not_stop_the_batch_recording_the_rest(env
activities=[plan, evaluate, record],
workflow_runner=UnsandboxedWorkflowRunner(),
):
- result = await environment.client.execute_workflow(
+ handle = await environment.client.start_workflow(
InsightAlertPlatformEvaluateWorkflow.run,
SourceEvaluationInputs(
source=SourceKind.INSIGHT,
@@ -77,8 +91,21 @@ async def test_a_check_that_fails_does_not_stop_the_batch_recording_the_rest(env
task_queue=QUEUE,
)
+ result = await handle.result()
+ history = await handle.fetch_history()
+
assert result == 1
assert [[str(o.configuration_id) for o in batch.outcomes] for batch in recorded] == [[ADMITTED[1]]]
+ children = [
+ event.child_workflow_execution_started_event_attributes
+ for event in history.events
+ if event.event_type == EventType.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_STARTED
+ ]
+ assert [child.workflow_execution.workflow_id for child in children] == [
+ f"alerts-deliver-preview-{ADMITTED[1]}:slot:2026-09-16T10:00:00+00:00"
+ ]
+ child = await environment.client.get_workflow_handle(children[0].workflow_execution.workflow_id).describe()
+ assert child.task_queue == settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE
def test_the_binding_holds_the_whole_batch() -> None:
diff --git a/products/alerts/backend/test/test_platform_source_cycle.py b/products/alerts/backend/test/test_platform_source_cycle.py
index a25d9f2063ae..edcba6e7a733 100644
--- a/products/alerts/backend/test/test_platform_source_cycle.py
+++ b/products/alerts/backend/test/test_platform_source_cycle.py
@@ -18,6 +18,7 @@ from posthog.schema_enums import AlertCalculationInterval
from posthog.tasks.alerts.utils import AlertEvaluationResult
from products.alerts.backend.evaluation.contract import AlertExtractionError
+from products.alerts.backend.logic.alert_email import INSIGHT_ALERT_ERRORED_EVENT_ID
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
from products.alerts.backend.platform_source_cycle import (
CAPACITY_REJECTED,
@@ -71,10 +72,11 @@ class TestPlatformInsightEvaluation(APIBaseTest):
side_effect = result if isinstance(result, Exception) else None
returned = result if isinstance(result, AlertEvaluationResult) else None
with patch(f"{_MODULE}.check_alert_for_insight", side_effect=side_effect, return_value=returned) as query:
- outcome = evaluate_insight_check(
+ evaluation = evaluate_insight_check(
self.team.id, slot, CUTOFF, str(configuration.id), held_until=expires_at, evaluation_id="test"
)
- return outcome, query
+ self.deliveries = evaluation.deliveries if evaluation is not None else ()
+ return (evaluation.outcomes[0] if evaluation is not None else None), query
def test_a_breach_fires_on_the_platform_and_leaves_the_production_alert_alone(self) -> None:
alert = self._alert()
@@ -97,6 +99,27 @@ class TestPlatformInsightEvaluation(APIBaseTest):
assert AlertConfiguration.objects.values("state", "next_check_at", "last_checked_at").get(id=alert.id) == before
assert not AlertCheck.objects.filter(alert_configuration=alert).exists()
+ @parameterized.expand([("allowlisted", True), ("not_allowlisted", False)])
+ def test_only_an_allowlisted_alert_asks_for_a_delivery(self, _name: str, allowlisted: bool) -> None:
+ alert = self._alert()
+ configuration = self._copy(alert)
+ allowlist = frozenset({str(alert.id)}) if allowlisted else frozenset()
+
+ with patch(f"{_MODULE}.LIVE_DELIVERY_INSIGHT_ALERT_IDS", allowlist):
+ self._evaluate(configuration, result=AlertEvaluationResult(value=150.0, breaches=["above 100"]))
+
+ expected = [
+ (
+ str(configuration.id),
+ str(alert.id),
+ {"firing": "$insight_alert_firing", "errored": INSIGHT_ALERT_ERRORED_EVENT_ID},
+ )
+ ]
+ assert [
+ (delivery.configuration_id, delivery.destination_alert_id, delivery.event_ids_by_kind)
+ for delivery in self.deliveries
+ ] == (expected if allowlisted else [])
+
@parameterized.expand(
[
("real_time", {"calculation_interval": AlertCalculationInterval.REAL_TIME.value}, "not_firing"),
diff --git a/products/alerts_platform/backend/facade/temporal.py b/products/alerts_platform/backend/facade/temporal.py
index 72098cf62345..ed10cc6530af 100644
--- a/products/alerts_platform/backend/facade/temporal.py
+++ b/products/alerts_platform/backend/facade/temporal.py
@@ -13,6 +13,7 @@ from products.alerts_platform.backend.temporal.workflows import (
EVALUATION_WORKFLOWS,
SHARED_ORCHESTRATION_ACTIVITIES,
SHARED_ORCHESTRATION_WORKFLOWS,
+ start_deliveries,
)
__all__ = [
@@ -28,4 +29,5 @@ __all__ = [
"AlertsPlatformTelemetryInterceptor",
"create_alerts_platform_tick_schedule",
"source_evaluation_timeout",
+ "start_deliveries",
]
diff --git a/products/alerts_platform/backend/temporal/workflows.py b/products/alerts_platform/backend/temporal/workflows.py
index 538927f9ec0e..ced760e3a57f 100644
--- a/products/alerts_platform/backend/temporal/workflows.py
+++ b/products/alerts_platform/backend/temporal/workflows.py
@@ -1,6 +1,6 @@
import asyncio
import datetime as dt
-from collections.abc import Callable
+from collections.abc import Callable, Sequence
from dataclasses import replace
from temporalio import activity, workflow
@@ -178,6 +178,38 @@ class AlertsPlatformDeliverPreviewWorkflow(PostHogWorkflow):
await workflow.sleep(BUSY_RETRY_DELAY)
+async def start_deliveries(deliveries: Sequence[AlertDeliveryRequest]) -> int:
+ """Starts one delivery workflow per request, from inside a source's evaluation workflow.
+
+ Returns how many started. The id names the configuration and the evaluation key, because the
+ key names a window or a slot but not the alert, so two alerts in one slot do not collide. A
+ re-run of the same occasion reuses the ids, and a reused id raises, so one delivery already
+ started does not stop the rest.
+ """
+ results = await asyncio.gather(
+ *(
+ workflow.start_child_workflow(
+ AlertsPlatformDeliverPreviewWorkflow.run,
+ delivery,
+ id=f"alerts-deliver-preview-{delivery.configuration_id}:{delivery.evaluation_key}",
+ task_queue=settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE,
+ parent_close_policy=workflow.ParentClosePolicy.ABANDON,
+ execution_timeout=DELIVERY_EXECUTION_TIMEOUT,
+ )
+ for delivery in deliveries
+ ),
+ return_exceptions=True,
+ )
+ started = 0
+ for result in results:
+ if isinstance(result, WorkflowAlreadyStartedError):
+ continue
+ if isinstance(result, BaseException):
+ raise result
+ started += 1
+ return started
+
+
@workflow.defn(name="alerts-platform-deliver")
class AlertsPlatformDeliverWorkflow(PostHogWorkflow):
inputs_cls = AlertsPlatformInputs
diff --git a/products/logs/backend/temporal/alert_evaluate.py b/products/logs/backend/temporal/alert_evaluate.py
index ba96b84356f1..963e6ceb610e 100644
--- a/products/logs/backend/temporal/alert_evaluate.py
+++ b/products/logs/backend/temporal/alert_evaluate.py
@@ -4,18 +4,14 @@ The evaluation itself lives in `products/logs/backend/alert_source_cycle.py`, so
plain function a test can call without Temporal.
"""
-import asyncio
import datetime as dt
from temporalio import activity, workflow
from temporalio.common import RetryPolicy
-from temporalio.exceptions import WorkflowAlreadyStartedError
from posthog.temporal.common.base import PostHogWorkflow
with workflow.unsafe.imports_passed_through():
- from django.conf import settings
-
from posthog.temporal.common.utils import close_db_connections
from products.alerts_platform.backend.facade.contracts import (
@@ -24,7 +20,7 @@ with workflow.unsafe.imports_passed_through():
SourceEvaluationInputs,
SourceOutcomeInputs,
)
- from products.alerts_platform.backend.facade.temporal import DELIVERY_EXECUTION_TIMEOUT
+ from products.alerts_platform.backend.facade.temporal import start_deliveries
WORKFLOW_NAME = "logs-alert-evaluate"
@@ -96,32 +92,7 @@ class LogsAlertEvaluateWorkflow(PostHogWorkflow):
retry_policy=RetryPolicy(maximum_attempts=3),
)
- # The evaluation key names the window and the slot but not the alert, because a delivery
- # addresses the history row with it. The id joins the two, so two alerts in one slot do
- # not collide. A re-run of the same occasion reuses these ids, and a reused id raises, so
- # one already-started preview must not stop the rest.
- results = await asyncio.gather(
- *(
- workflow.start_child_workflow(
- "alerts-platform-deliver-preview",
- delivery,
- id=f"alerts-deliver-preview-{delivery.configuration_id}:{delivery.evaluation_key}",
- task_queue=settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE,
- parent_close_policy=workflow.ParentClosePolicy.ABANDON,
- execution_timeout=DELIVERY_EXECUTION_TIMEOUT,
- )
- for delivery in evaluation.deliveries
- ),
- return_exceptions=True,
- )
- started = 0
- for result in results:
- if isinstance(result, WorkflowAlreadyStartedError):
- continue
- if isinstance(result, BaseException):
- raise result
- started += 1
- return started
+ return await start_deliveries(evaluation.deliveries)
SOURCE_EVALUATION_WORKFLOWS = [LogsAlertEvaluateWorkflow]