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): expose insight alert scheduler backlog metrics (#97499)

Matt Pua131aadf93a38
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index a785acb4c03d..3ac63aab42a0 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -3,8 +3,8 @@ from concurrent.futures import ThreadPoolExecutor
from datetime import UTC, datetime
from django.db import transaction
-from django.db.models import Case, F, IntegerField, Q, Value, When, Window
-from django.db.models.functions import RowNumber
+from django.db.models import Case, Count, F, IntegerField, Min, Q, Value, When, Window
+from django.db.models.functions import Coalesce, RowNumber
import structlog
import temporalio.activity
@@ -36,6 +36,7 @@ from posthog.tasks.alerts.utils import (
skip_because_of_weekend,
)
from posthog.temporal.alerts.investigation import claim_investigation_slot, decide_investigation
+from posthog.temporal.alerts.metrics import record_due_insight_alert_metrics
from posthog.temporal.alerts.types import (
AlertInfo,
EvaluateAlertActivityInputs,
@@ -78,7 +79,7 @@ async def retrieve_due_alerts(inputs: ScheduleDueAlertChecksWorkflowInputs | Non
@database_sync_to_async(thread_sensitive=False)
def get_alerts() -> list[AlertInfo]:
- now = datetime.now(UTC)
+ polled_at = datetime.now(UTC)
calculation_interval_order = Case(
*(
@@ -89,13 +90,15 @@ async def retrieve_due_alerts(inputs: ScheduleDueAlertChecksWorkflowInputs | Non
output_field=IntegerField(),
)
- alerts = (
+ due_alerts_query = (
AlertConfiguration.objects.filter(
- Q(enabled=True, next_check_at__lte=now) | Q(enabled=True, next_check_at__isnull=True)
+ Q(enabled=True, next_check_at__lte=polled_at) | Q(enabled=True, next_check_at__isnull=True)
)
- .filter(Q(snoozed_until__isnull=True) | Q(snoozed_until__lt=now))
+ .filter(Q(snoozed_until__isnull=True) | Q(snoozed_until__lt=polled_at))
.filter(insight__deleted=False)
- .annotate(_interval_order=calculation_interval_order)
+ )
+ alerts_query = (
+ due_alerts_query.annotate(_interval_order=calculation_interval_order)
.annotate(
_team_rank=Window(
expression=RowNumber(),
@@ -117,7 +120,7 @@ async def retrieve_due_alerts(inputs: ScheduleDueAlertChecksWorkflowInputs | Non
.only("id", "team_id", "calculation_interval", "insight_id")[: inputs.max_alerts_per_run]
)
- return [
+ alerts = [
AlertInfo(
alert_id=str(a.id),
team_id=a.team_id,
@@ -125,9 +128,15 @@ async def retrieve_due_alerts(inputs: ScheduleDueAlertChecksWorkflowInputs | Non
calculation_interval=a.calculation_interval,
insight_id=a.insight_id,
)
- for a in alerts
+ for a in alerts_query
]
+ due_alert_metrics = due_alerts_query.aggregate(
+ due_count=Count("id"), oldest_due_at=Min(Coalesce("next_check_at", "created_at"))
+ )
+ record_due_insight_alert_metrics(due_alert_metrics["due_count"], due_alert_metrics["oldest_due_at"], polled_at)
+ return alerts
+
async with Heartbeater():
return await get_alerts()
diff --git a/posthog/temporal/alerts/metrics.py b/posthog/temporal/alerts/metrics.py
new file mode 100644
index 000000000000..ccbfebc7a959
--- /dev/null
+++ b/posthog/temporal/alerts/metrics.py
@@ -0,0 +1,29 @@
+from datetime import datetime
+
+from prometheus_client import Gauge
+
+from posthog.metrics import pushed_metrics_registry
+
+
+def record_due_insight_alert_metrics(due_count: int, oldest_due_at: datetime | None, polled_at: datetime) -> None:
+
+ oldest_due_age_seconds: float = 0.0
+ if oldest_due_at is not None:
+ oldest_due_age_seconds = max((polled_at - oldest_due_at).total_seconds(), 0)
+
+ with pushed_metrics_registry("temporal_insight_alerts") as registry:
+ Gauge(
+ "posthog_insight_alerts_due_count",
+ "Number of enabled insight alerts due for evaluation",
+ registry=registry,
+ ).set(due_count)
+ Gauge(
+ "posthog_insight_alerts_oldest_due_age_seconds",
+ "Age in seconds of the oldest due insight alert",
+ registry=registry,
+ ).set(oldest_due_age_seconds)
+ Gauge(
+ "posthog_insight_alerts_scheduler_last_poll_timestamp_seconds",
+ "Unix timestamp of the last successful insight alert scheduler poll",
+ registry=registry,
+ ).set(polled_at.timestamp())
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index 2553184d99dd..3916b196f1e3 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -220,6 +220,25 @@ async def _create_alert_check(
return await _create()
[email protected]_db(transaction=True)
+class TestRetrieveDueAlerts:
+ @time_machine.travel("2026-09-09T12:00:00Z", tick=False)
+ async def test_records_metrics_for_due_alerts(self, ateam) -> None:
+ due_alert = await _create_alert(ateam, next_check_at=datetime(2026, 9, 9, 11, 0, tzinfo=UTC))
+ await _create_alert(ateam, next_check_at=datetime(2026, 9, 9, 13, 0, tzinfo=UTC))
+
+ with patch("posthog.temporal.alerts.activities.record_due_insight_alert_metrics") as record_metrics:
+ result = await ActivityEnvironment().run(retrieve_due_alerts)
+
+ assert [item.alert_id for item in result] == [str(due_alert.id)]
+ record_metrics.assert_called_once()
+ due_count, oldest_due_at, polled_at = record_metrics.call_args.args
+ assert due_count == 1
+ assert oldest_due_at == datetime(2026, 9, 9, 11, 0, tzinfo=UTC)
+ assert polled_at == datetime(2026, 9, 9, 12, 0, tzinfo=UTC)
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
class TestPrepareAlert:
diff --git a/posthog/temporal/tests/test_alerts_metrics.py b/posthog/temporal/tests/test_alerts_metrics.py
new file mode 100644
index 000000000000..a6e28301e015
--- /dev/null
+++ b/posthog/temporal/tests/test_alerts_metrics.py
@@ -0,0 +1,48 @@
+from collections.abc import Generator
+from contextlib import contextmanager, nullcontext
+from datetime import UTC, datetime, timedelta
+
+from unittest.mock import MagicMock, patch
+
+from prometheus_client import CollectorRegistry
+
+from posthog.temporal.alerts.metrics import record_due_insight_alert_metrics
+
+
+def test_record_due_insight_alert_metrics_records_due_count_oldest_age_and_poll_time() -> None:
+ polled_at = datetime(2026, 9, 9, 12, 0, tzinfo=UTC)
+
+ with _metrics_registry() as (pushed_registry, registry):
+ record_due_insight_alert_metrics(2, polled_at - timedelta(hours=2), polled_at)
+
+ pushed_registry.assert_called_once_with("temporal_insight_alerts")
+ assert registry.get_sample_value("posthog_insight_alerts_due_count") == 2
+ assert registry.get_sample_value("posthog_insight_alerts_oldest_due_age_seconds") == 7200
+ assert (
+ registry.get_sample_value("posthog_insight_alerts_scheduler_last_poll_timestamp_seconds")
+ == polled_at.timestamp()
+ )
+
+
+def test_record_due_insight_alert_metrics_resets_backlog_values_when_no_alerts_are_due() -> None:
+ polled_at = datetime(2026, 9, 9, 12, 0, tzinfo=UTC)
+
+ with _metrics_registry() as (_, registry):
+ record_due_insight_alert_metrics(0, None, polled_at)
+
+ assert registry.get_sample_value("posthog_insight_alerts_due_count") == 0
+ assert registry.get_sample_value("posthog_insight_alerts_oldest_due_age_seconds") == 0
+ assert (
+ registry.get_sample_value("posthog_insight_alerts_scheduler_last_poll_timestamp_seconds")
+ == polled_at.timestamp()
+ )
+
+
+@contextmanager
+def _metrics_registry() -> Generator[tuple[MagicMock, CollectorRegistry]]:
+ registry = CollectorRegistry()
+
+ with patch(
+ "posthog.temporal.alerts.metrics.pushed_metrics_registry", return_value=nullcontext(registry)
+ ) as pushed_registry:
+ yield pushed_registry, registry
diff --git a/products/alerts/backend/max_tools.py b/products/alerts/backend/max_tools.py
index 72c7a908a3aa..0fa8ab4748fb 100644
--- a/products/alerts/backend/max_tools.py
+++ b/products/alerts/backend/max_tools.py
@@ -3,6 +3,7 @@ from typing import Any, Literal, Union, cast
from django.core.exceptions import ValidationError
from django.db import transaction
+from django.utils import timezone
from asgiref.sync import sync_to_async
from pydantic import BaseModel, Field
@@ -344,6 +345,7 @@ class UpsertAlertTool(MaxTool):
update_fields: list[str] = []
conditions_or_threshold_changed = False
+ schedule_reset_required = False
if action.name is not None:
alert.name = action.name[:255]
@@ -353,25 +355,31 @@ class UpsertAlertTool(MaxTool):
alert.condition = {"type": action.condition_type}
update_fields.append("condition")
conditions_or_threshold_changed = True
+ schedule_reset_required = True
if action.calculation_interval is not None:
- alert.calculation_interval = action.calculation_interval
- update_fields.append("calculation_interval")
+ if action.calculation_interval != alert.calculation_interval:
+ schedule_reset_required = True
+ alert.calculation_interval = action.calculation_interval
+ update_fields.append("calculation_interval")
if action.series_index is not None:
alert.config = {**(alert.config or {}), "series_index": action.series_index}
update_fields.append("config")
+ schedule_reset_required = True
enabled_changed = action.enabled is not None and action.enabled != alert.enabled
if action.enabled is not None:
if enabled_changed and action.enabled:
update_fields.extend(apply_enable(alert))
+ schedule_reset_required = True
elif enabled_changed:
update_fields.extend(apply_disable(alert))
else:
update_fields.append("enabled")
if action.skip_weekend is not None:
+ schedule_reset_required = schedule_reset_required or action.skip_weekend != alert.skip_weekend
alert.skip_weekend = action.skip_weekend
update_fields.append("skip_weekend")
@@ -386,14 +394,18 @@ class UpsertAlertTool(MaxTool):
except ValidationError as e:
return str(e), {"error": "validation_failed"}
conditions_or_threshold_changed = True
+ schedule_reset_required = True
if not update_fields and not has_threshold_changes:
return "No changes provided. Specify at least one field to update.", {"error": "no_changes"}
if conditions_or_threshold_changed:
update_fields.extend(apply_threshold_change(alert))
- alert.next_check_at = None
- update_fields.append("next_check_at")
+ if schedule_reset_required:
+ # Keep the due timestamp so the scheduler metric can measure
+ # a recheck that remains unhandled after an edit or re-enable.
+ alert.next_check_at = timezone.now()
+ update_fields.append("next_check_at")
await sync_to_async(alert.save)(update_fields=update_fields)
await sync_to_async(alert.report_updated)(self._user, {"source": EventSource.POSTHOG_AI})
diff --git a/products/alerts/backend/models/alert.py b/products/alerts/backend/models/alert.py
index 73f36d3f0510..d9d222446820 100644
--- a/products/alerts/backend/models/alert.py
+++ b/products/alerts/backend/models/alert.py
@@ -154,7 +154,8 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
last_notified_at = models.DateTimeField(null=True, blank=True)
last_checked_at = models.DateTimeField(null=True, blank=True)
- # UTC time for when next alert check is due
+ # UTC time for when next alert check is due. Null only before the first
+ # check, when created_at is the scheduler's due-age lower bound.
next_check_at = models.DateTimeField(null=True, blank=True)
# UTC time until when we shouldn't check alert/notify user
snoozed_until = models.DateTimeField(null=True, blank=True)
diff --git a/products/alerts/backend/presentation/views/alert.py b/products/alerts/backend/presentation/views/alert.py
index ec000459c3fc..74ce0bce34d9 100644
--- a/products/alerts/backend/presentation/views/alert.py
+++ b/products/alerts/backend/presentation/views/alert.py
@@ -4,6 +4,7 @@ from zoneinfo import ZoneInfo
from django.db import transaction
from django.db.models import OuterRef, Prefetch, Q, QuerySet, Subquery
+from django.utils import timezone
import posthoganalytics
from drf_spectacular.utils import OpenApiParameter, OpenApiTypes, extend_schema, extend_schema_view
@@ -613,7 +614,8 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
instance = AlertConfiguration.objects.select_for_update().get(pk=instance.pk)
enabled_changed = "enabled" in validated_data and validated_data["enabled"] != instance.enabled
resulting_enabled = validated_data.get("enabled", instance.enabled)
- if enabled_changed and validated_data["enabled"]:
+ enable_now = enabled_changed and validated_data["enabled"]
+ if enable_now:
apply_enable(instance)
snoozed_until_param = validated_data.pop("snoozed_until", serializers.empty)
@@ -653,14 +655,21 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
user=user, alert_configuration=instance, defaults={"created_by": self.context["request"].user}
)
+ evaluation_changed = conditions_or_threshold_changed or any(
+ validated_data.get(field, getattr(instance, field)) != getattr(instance, field)
+ for field in ("condition", "config", "skip_weekend")
+ )
calculation_interval_changed = (
"calculation_interval" in validated_data
and validated_data["calculation_interval"] != instance.calculation_interval
)
- if conditions_or_threshold_changed or calculation_interval_changed:
- if conditions_or_threshold_changed:
+ if enable_now or evaluation_changed or calculation_interval_changed:
+ if evaluation_changed:
apply_threshold_change(instance)
- instance.next_check_at = None
+ # Keep the due timestamp so the scheduler metric can measure a
+ # recheck that remains unhandled. Null is reserved for a brand-new
+ # alert that has never had a scheduling timestamp.
+ instance.next_check_at = timezone.now()
if snooze_changed:
instance.snoozed_until = snoozed_until
diff --git a/products/alerts/backend/test_max_tools.py b/products/alerts/backend/test_max_tools.py
index 5f030a96807c..df9cc1ecd16a 100644
--- a/products/alerts/backend/test_max_tools.py
+++ b/products/alerts/backend/test_max_tools.py
@@ -484,19 +484,19 @@ class TestUpsertAlertTool(BaseTest):
"threshold_change_resets_state",
{"lower_threshold": 100.0},
{"upper_threshold": 200.0},
- lambda a, t: a.state == AlertState.NOT_FIRING and a.next_check_at is None,
+ lambda a, t: a.state == AlertState.NOT_FIRING and a.next_check_at is not None,
),
(
"condition_change_resets_state",
{"condition_type": AlertConditionType.ABSOLUTE_VALUE},
{"condition_type": AlertConditionType.RELATIVE_INCREASE},
- lambda a, t: a.state == AlertState.NOT_FIRING and a.next_check_at is None,
+ lambda a, t: a.state == AlertState.NOT_FIRING and a.next_check_at is not None,
),
(
- "interval_change_clears_next_check_only",
+ "interval_change_marks_alert_due_now",
{"calculation_interval": AlertCalculationInterval.DAILY},
{"calculation_interval": AlertCalculationInterval.WEEKLY},
- lambda a, t: a.state == AlertState.FIRING and a.next_check_at is None,
+ lambda a, t: a.state == AlertState.FIRING and a.next_check_at is not None,
),
]
)
@@ -517,7 +517,7 @@ class TestUpsertAlertTool(BaseTest):
await sync_to_async(alert.refresh_from_db)()
threshold = await sync_to_async(lambda: alert.threshold)()
assert check(alert, threshold), f"Check failed for {_name}"
- assert alert.next_check_at is None
+ assert alert.next_check_at is not None
@pytest.mark.django_db
@pytest.mark.asyncio
diff --git a/products/alerts/backend/tests/api/test_alert.py b/products/alerts/backend/tests/api/test_alert.py
index 314eb45318d9..8c27a3ec50cb 100644
--- a/products/alerts/backend/tests/api/test_alert.py
+++ b/products/alerts/backend/tests/api/test_alert.py
@@ -1151,6 +1151,41 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
"alert name",
True,
),
+ (
+ "unchanged_interval_preserves_schedule",
+ {"calculation_interval": "weekly"},
+ status.HTTP_200_OK,
+ "weekly",
+ "alert name",
+ False,
+ ),
+ (
+ "condition_change_resets_schedule",
+ {
+ "condition": {"type": AlertConditionType.RELATIVE_INCREASE},
+ "threshold": {"configuration": {"type": InsightThresholdType.PERCENTAGE, "bounds": {"upper": 100}}},
+ },
+ status.HTTP_200_OK,
+ "weekly",
+ "alert name",
+ True,
+ ),
+ (
+ "config_change_resets_schedule",
+ {"config": {"type": "TrendsAlertConfig", "series_index": 0, "check_ongoing_interval": True}},
+ status.HTTP_200_OK,
+ "weekly",
+ "alert name",
+ True,
+ ),
+ (
+ "skip_weekend_change_resets_schedule",
+ {"skip_weekend": True},
+ status.HTTP_200_OK,
+ "weekly",
+ "alert name",
+ True,
+ ),
]
)
def test_patch_calculation_interval(
@@ -1171,6 +1206,12 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
"name": "alert name",
"calculation_interval": "weekly",
}
+ if "condition" in patch_payload:
+ time_series_insight_data = deepcopy(self.default_insight_data)
+ time_series_insight_data["query"]["trendsFilter"] = {"display": "ActionsLineGraph"}
+ creation_request["insight"] = self.client.post(
+ f"/api/projects/{self.team.id}/insights", data=time_series_insight_data
+ ).json()["id"]
alert = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request).json()
assert alert["calculation_interval"] == "weekly"
scheduled_check = datetime(2027, 1, 1, tzinfo=UTC)
@@ -1187,7 +1228,11 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
assert response.json()["name"] == expected_name
persisted_alert = AlertConfiguration.objects.get(id=alert["id"])
- assert persisted_alert.next_check_at == (None if clears_next_check else scheduled_check)
+ if clears_next_check:
+ assert persisted_alert.next_check_at is not None
+ assert persisted_alert.next_check_at <= datetime.now(UTC)
+ else:
+ assert persisted_alert.next_check_at == scheduled_check
@parameterized.expand(
[