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): add SLO tracking to insight and logs checks (#71117)

Matt Puaffc991872220
diff --git a/posthog/temporal/alerts/workflows.py b/posthog/temporal/alerts/workflows.py
index 8719a650d99f..899720913b67 100644
--- a/posthog/temporal/alerts/workflows.py
+++ b/posthog/temporal/alerts/workflows.py
@@ -9,6 +9,7 @@ from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedError
from posthog.schema import AlertState
+from posthog.slo.context import JsonValue
from posthog.slo.types import SloArea, SloConfig, SloOperation
from posthog.temporal.alerts.activities import (
cleanup_alert_checks,
@@ -58,6 +59,11 @@ class ScheduleDueAlertChecksWorkflow(PostHogWorkflow):
# rejects the duplicate start.
tasks = []
for alert in alerts:
+ slo_properties: dict[str, JsonValue] = {
+ "alert_type": "insight",
+ "calculation_interval": alert.calculation_interval,
+ "insight_id": alert.insight_id,
+ }
task = temporalio.workflow.execute_child_workflow(
CheckAlertWorkflow.run,
CheckAlertWorkflowInputs(
@@ -72,14 +78,8 @@ class ScheduleDueAlertChecksWorkflow(PostHogWorkflow):
team_id=alert.team_id,
resource_id=alert.alert_id,
distinct_id=alert.distinct_id,
- start_properties={
- "calculation_interval": alert.calculation_interval,
- "insight_id": alert.insight_id,
- },
- completion_properties={
- "calculation_interval": alert.calculation_interval,
- "insight_id": alert.insight_id,
- },
+ start_properties=slo_properties.copy(),
+ completion_properties=slo_properties.copy(),
),
),
id=f"check-alert-{alert.alert_id}",
diff --git a/posthog/temporal/tests/test_alerts_workflows.py b/posthog/temporal/tests/test_alerts_workflows.py
index c73c6d0cd440..5203471e6f30 100644
--- a/posthog/temporal/tests/test_alerts_workflows.py
+++ b/posthog/temporal/tests/test_alerts_workflows.py
@@ -3,7 +3,7 @@ from collections.abc import Callable
from typing import Any
import pytest
-from unittest.mock import MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
from django.conf import settings
@@ -27,8 +27,8 @@ from posthog.slo.types import SloArea, SloConfig, SloOperation, SloOutcome
from posthog.tasks.alerts.utils import AlertEvaluationResult
from posthog.temporal.alerts.activities import evaluate_alert, notify_alert, prepare_alert
from posthog.temporal.alerts.schedule import create_schedule_due_alert_checks_schedule
-from posthog.temporal.alerts.types import CheckAlertWorkflowInputs, SkipReason
-from posthog.temporal.alerts.workflows import CheckAlertWorkflow
+from posthog.temporal.alerts.types import AlertInfo, CheckAlertWorkflowInputs, SkipReason
+from posthog.temporal.alerts.workflows import CheckAlertWorkflow, ScheduleDueAlertChecksWorkflow
from posthog.temporal.common.slo_interceptor import SloInterceptor
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, Threshold
@@ -37,6 +37,46 @@ from products.product_analytics.backend.models.insight import Insight
CHECK_ALERT_ACTIVITIES: list[Callable[..., Any]] = [prepare_alert, evaluate_alert, notify_alert]
+async def test_schedule_due_alert_checks_adds_shared_slo_context() -> None:
+ alert = AlertInfo(
+ alert_id="alert-1",
+ team_id=42,
+ distinct_id="user-1",
+ calculation_interval=AlertCalculationInterval.DAILY.value,
+ insight_id=123,
+ )
+
+ with (
+ patch(
+ "posthog.temporal.alerts.workflows.temporalio.workflow.execute_activity",
+ new=AsyncMock(return_value=[alert]),
+ ),
+ patch(
+ "posthog.temporal.alerts.workflows.temporalio.workflow.execute_child_workflow", new=AsyncMock()
+ ) as execute_child,
+ ):
+ await ScheduleDueAlertChecksWorkflow().run()
+
+ inputs = execute_child.call_args.args[1]
+ assert isinstance(inputs, CheckAlertWorkflowInputs)
+ assert inputs.slo is not None
+ assert inputs.slo.operation == SloOperation.ALERT_CHECK
+ assert inputs.slo.area == SloArea.ANALYTIC_PLATFORM
+ assert inputs.slo.team_id == 42
+ assert inputs.slo.resource_id == "alert-1"
+ assert inputs.slo.distinct_id == "user-1"
+ assert inputs.slo.start_properties == {
+ "alert_type": "insight",
+ "calculation_interval": AlertCalculationInterval.DAILY.value,
+ "insight_id": 123,
+ }
+ assert inputs.slo.completion_properties == inputs.slo.start_properties
+
+ inputs.slo.completion_properties["alert_state"] = AlertState.FIRING
+ assert "alert_state" not in inputs.slo.start_properties
+
+
def test_schedule_is_registered_in_init_schedules():
from posthog.temporal.schedule import schedules
diff --git a/products/logs/backend/temporal/activities.py b/products/logs/backend/temporal/activities.py
index 5e4a9e059aa8..f21b019dfd2e 100644
--- a/products/logs/backend/temporal/activities.py
+++ b/products/logs/backend/temporal/activities.py
@@ -22,6 +22,8 @@ from posthog.schema import PropertyGroupFilter
from posthog.exceptions_capture import capture_exception
from posthog.kafka_client.client import ProduceResult
from posthog.models import Team
+from posthog.slo.context import SloHandle, SloSpec, slo_operation
+from posthog.slo.types import SloArea, SloOperation
from posthog.sync import database_sync_to_async_pool
from products.alerts.backend.destinations import (
@@ -586,86 +588,130 @@ async def evaluate_cohort_batch_activity(input: EvaluateCohortBatchInput) -> Eva
_safe_record("cohort_size histogram", record_cohort_size, len(cohort.alerts))
- try:
- query_result = await cohort_query_async(cohort)
- except Exception:
- logger.exception(
- "Cohort CH query failed unrecoverably",
- team_id=cohort.team_id,
- cohort_size=len(cohort.alerts),
- )
- local_stats["errored"] += len(cohort.alerts)
- return local_stats, local_notified
-
- evaluations: list[_AlertEvaluation] = []
- eval_starts: list[float] = []
- for alert in cohort.alerts:
- eval_start = time.perf_counter()
- try:
- evaluations.append(
- _evaluate_single_alert(
- alert,
- now,
- checkpoint=None,
- prefetched=query_result.for_alert(alert),
+ with contextlib.ExitStack() as slo_stack:
+ slo_handles: dict[str, SloHandle] = {
+ str(alert.id): slo_stack.enter_context(
+ slo_operation(
+ spec=SloSpec(
+ distinct_id=str(alert.id),
+ area=SloArea.ANALYTIC_PLATFORM,
+ operation=SloOperation.ALERT_CHECK,
+ team_id=alert.team_id,
+ resource_id=str(alert.id),
+ ),
+ properties={
+ "alert_type": "logs",
+ "check_interval_minutes": alert.check_interval_minutes,
+ "window_minutes": alert.window_minutes,
+ },
)
)
- eval_starts.append(eval_start)
+ for alert in cohort.alerts
+ }
+
+ try:
+ query_result = await cohort_query_async(cohort)
except Exception:
logger.exception(
- "Unexpected error evaluating alert",
- alert_id=str(alert.id),
- team_id=alert.team_id,
+ "Cohort CH query failed unrecoverably",
+ team_id=cohort.team_id,
+ cohort_size=len(cohort.alerts),
)
- local_stats["errored"] += 1
+ for slo_handle in slo_handles.values():
+ slo_handle.fail(failure_phase="cohort_query")
+ local_stats["errored"] += len(cohort.alerts)
+ return local_stats, local_notified
+
+ evaluations: list[_AlertEvaluation] = []
+ eval_starts: list[float] = []
+ for alert in cohort.alerts:
+ alert_id = str(alert.id)
+ eval_start = time.perf_counter()
+ try:
+ evaluations.append(
+ _evaluate_single_alert(
+ alert,
+ now,
+ checkpoint=None,
+ prefetched=query_result.for_alert(alert),
+ )
+ )
+ eval_starts.append(eval_start)
+ except Exception:
+ logger.exception(
+ "Unexpected error evaluating alert",
+ alert_id=alert_id,
+ team_id=alert.team_id,
+ )
+ slo_handles[alert_id].fail(failure_phase="evaluation")
+ local_stats["errored"] += 1
- dispatched_or_errors = await asyncio.gather(
- *(dispatch_async(ev, now) for ev in evaluations),
- return_exceptions=True,
- )
- phase_2_end = time.perf_counter()
- dispatched: list[_DispatchedAlert] = []
- elapsed_ms_per_alert: list[int] = []
- for ev, result, eval_start in zip(evaluations, dispatched_or_errors, eval_starts):
- if isinstance(result, BaseException):
- logger.exception(
- "Unexpected error dispatching alert",
- alert_id=str(ev.alert.id),
- team_id=ev.alert.team_id,
- exc_info=result,
- )
+ dispatched_or_errors = await asyncio.gather(
+ *(dispatch_async(ev, now) for ev in evaluations),
+ return_exceptions=True,
+ )
+ phase_2_end = time.perf_counter()
+ dispatched: list[_DispatchedAlert] = []
+ elapsed_ms_per_alert: list[int] = []
+ for ev, result, eval_start in zip(evaluations, dispatched_or_errors, eval_starts):
+ alert_id = str(ev.alert.id)
+ if isinstance(result, BaseException):
+ logger.exception(
+ "Unexpected error dispatching alert",
+ alert_id=alert_id,
+ team_id=ev.alert.team_id,
+ exc_info=result,
+ )
+ slo_handles[alert_id].fail(failure_phase="dispatch")
+ local_stats["errored"] += 1
+ else:
+ dispatched.append(result)
+ elapsed_ms_per_alert.append(int((phase_2_end - eval_start) * 1000))
+
+ # Delivery barrier: block until Kafka acks (or the flush deadline
+ # passes) BEFORE the save, so undelivered notifications roll state
+ # back and get retried next cycle. flush() blocks, so run it off
+ # the event loop, and only when something was actually produced,
+ # sparing quiet cohorts the thread hop.
+ if any(d.produce_result is not None for d in dispatched):
+ dispatched = await asyncio.to_thread(_resolve_notification_deliveries, dispatched)
+
+ try:
+ saved, failed = (await save_cohort_async(dispatched, now)) if dispatched else ([], [])
+ except Exception as e:
+ logger.exception("Cohort bulk save failed (non-recoverable)", team_id=cohort.team_id)
+ capture_exception(e, {"team_id": cohort.team_id, "phase": "bulk_save"})
+ for dispatched_alert in dispatched:
+ slo_handles[str(dispatched_alert.evaluation.alert.id)].fail(failure_phase="save")
+ local_stats["errored"] += len(dispatched)
+ local_stats["checked"] += len(dispatched)
+ return local_stats, local_notified
+
+ elapsed_by_id = {str(d.evaluation.alert.id): ms for d, ms in zip(dispatched, elapsed_ms_per_alert)}
+ for dispatched_alert in saved:
+ alert_id = str(dispatched_alert.evaluation.alert.id)
+ _finalize_alert(dispatched_alert, elapsed_by_id[alert_id], local_stats)
+ committed_state = dispatched_alert.committed_outcome.new_state.value
+ notification_action = dispatched_alert.evaluation.outcome.notification.value
+ if dispatched_alert.notification_failed:
+ slo_handles[alert_id].fail(
+ alert_state=committed_state,
+ notification_action=notification_action,
+ failure_phase="notification_delivery",
+ )
+ else:
+ slo_handles[alert_id].succeed(
+ alert_state=committed_state,
+ notification_action=notification_action,
+ )
+ for dispatched_alert in failed:
+ slo_handles[str(dispatched_alert.evaluation.alert.id)].fail(failure_phase="save")
+ local_stats["checked"] += 1
local_stats["errored"] += 1
- else:
- dispatched.append(result)
- elapsed_ms_per_alert.append(int((phase_2_end - eval_start) * 1000))
-
- # Delivery barrier: block until Kafka acks (or the flush deadline
- # passes) BEFORE the save, so undelivered notifications roll state
- # back and get retried next cycle. flush() blocks, so run it off
- # the event loop — and only when something was actually produced,
- # sparing quiet cohorts the thread hop.
- if any(d.produce_result is not None for d in dispatched):
- dispatched = await asyncio.to_thread(_resolve_notification_deliveries, dispatched)
- try:
- saved, failed = (await save_cohort_async(dispatched, now)) if dispatched else ([], [])
- except Exception as e:
- logger.exception("Cohort bulk save failed (non-recoverable)", team_id=cohort.team_id)
- capture_exception(e, {"team_id": cohort.team_id, "phase": "bulk_save"})
- local_stats["errored"] += len(dispatched)
- local_stats["checked"] += len(dispatched)
+ local_notified.extend(_build_notified_from_saved(saved))
return local_stats, local_notified
- elapsed_by_id = {str(d.evaluation.alert.id): ms for d, ms in zip(dispatched, elapsed_ms_per_alert)}
- for d in saved:
- _finalize_alert(d, elapsed_by_id[str(d.evaluation.alert.id)], local_stats)
- for _ in failed:
- local_stats["checked"] += 1
- local_stats["errored"] += 1
-
- local_notified.extend(_build_notified_from_saved(saved))
- return local_stats, local_notified
-
cohort_results = await asyncio.gather(
*(_run_one_cohort(m) for m in input.manifests),
return_exceptions=False, # _run_one_cohort never raises; it captures failures into local_stats
diff --git a/products/logs/backend/test/test_logs_alerting_activities.py b/products/logs/backend/test/test_logs_alerting_activities.py
index d4f3932bf4bb..505d078e2370 100644
--- a/products/logs/backend/test/test_logs_alerting_activities.py
+++ b/products/logs/backend/test/test_logs_alerting_activities.py
@@ -20,6 +20,7 @@ from parameterized import parameterized
from posthog.clickhouse.client import sync_execute
from posthog.errors import QueryErrorCategory
+from posthog.slo.types import SloOperation, SloOutcome
from products.logs.backend.alert_check_query import AlertCheckQuery, BatchedBucketedResult, BucketedCount
from products.logs.backend.alert_signal_emitter import NotifiedAlert
@@ -2028,8 +2029,12 @@ class TestEvaluateCohortBatchActivity(NonAtomicBaseTest):
CLASS_DATA_LEVEL_SETUP = False
@freeze_time("2026-05-05T10:05:00Z")
+ @patch("posthog.slo.context.emit_slo_completed")
+ @patch("posthog.slo.context.emit_slo_started")
@patch("products.logs.backend.temporal.activities._run_cohort_query")
- def test_loads_alerts_by_id_and_processes_each_cohort(self, mock_run_cohort_query):
+ def test_loads_alerts_by_id_and_processes_each_cohort(
+ self, mock_run_cohort_query, mock_emit_slo_started, mock_emit_slo_completed
+ ):
from products.logs.backend.temporal.activities import (
CohortManifest,
EvaluateCohortBatchInput,
@@ -2073,6 +2078,17 @@ class TestEvaluateCohortBatchActivity(NonAtomicBaseTest):
assert result.alerts_checked == 2
# _run_cohort_query was invoked exactly once (one cohort in this batch).
assert mock_run_cohort_query.call_count == 1
+ assert mock_emit_slo_started.call_count == 2
+ assert mock_emit_slo_completed.call_count == 2
+
+ started_alert_ids = {call.kwargs["properties"].resource_id for call in mock_emit_slo_started.call_args_list}
+ assert started_alert_ids == {str(alert.id) for alert in alerts}
+ for call in mock_emit_slo_started.call_args_list:
+ assert call.kwargs["properties"].operation == SloOperation.ALERT_CHECK
+ assert call.kwargs["extra_properties"]["alert_type"] == "logs"
+ for call in mock_emit_slo_completed.call_args_list:
+ assert call.kwargs["properties"].outcome == SloOutcome.SUCCESS
+ assert call.kwargs["extra_properties"]["alert_state"] == AlertState.NOT_FIRING
@freeze_time("2026-05-05T10:05:00Z")
@patch("products.logs.backend.temporal.activities._run_cohort_query")
@@ -2138,11 +2154,18 @@ class TestEvaluateCohortBatchActivity(NonAtomicBaseTest):
assert result.alerts_checked == 1
@freeze_time("2025-01-01T00:01:00Z")
+ @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._run_cohort_query")
def test_undelivered_notification_rolls_back_state_before_save(
- self, mock_run_cohort_query, mock_produce, _mock_flush
+ self,
+ mock_run_cohort_query,
+ mock_produce,
+ _mock_flush,
+ mock_emit_slo_started,
+ mock_emit_slo_completed,
):
from products.logs.backend.temporal.activities import (
CohortManifest,
@@ -2194,3 +2217,15 @@ class TestEvaluateCohortBatchActivity(NonAtomicBaseTest):
assert result.notified == []
# The cycle still advances so the next cycle re-evaluates and retries the notification.
assert alert.next_check_at is not None
+ mock_emit_slo_started.assert_called_once()
+ mock_emit_slo_completed.assert_called_once()
+ assert mock_emit_slo_completed.call_args.kwargs["properties"].outcome == SloOutcome.FAILURE
+ assert mock_emit_slo_completed.call_args.kwargs["extra_properties"] == {
+ "alert_type": "logs",
+ "check_interval_minutes": alert.check_interval_minutes,
+ "window_minutes": alert.window_minutes,
+ "correlation_id": mock_emit_slo_started.call_args.kwargs["extra_properties"]["correlation_id"],
+ "alert_state": AlertState.NOT_FIRING,
+ "notification_action": NotificationAction.FIRE.value,
+ "failure_phase": "notification_delivery",
+ }