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.

fix(alerts): finish scheduled runs after child start (#97378)

Vasco de Krijgere185cf8e12de
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index 7dfad7f8b715..85c280460770 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -3,7 +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
+from django.db.models import Case, F, IntegerField, Q, Value, When, Window
+from django.db.models.functions import RowNumber
import structlog
import temporalio.activity
@@ -67,6 +68,7 @@ from products.notifications.backend.facade.api import (
logger = structlog.get_logger(__name__)
_NOTIFICATION_DELIVERY_EXECUTOR = ThreadPoolExecutor(max_workers=10, thread_name_prefix="insight-alert-delivery")
+MAX_DUE_ALERTS_PER_SCHEDULE_RUN = 50
@temporalio.activity.defn
@@ -91,8 +93,25 @@ async def retrieve_due_alerts() -> list[AlertInfo]:
.filter(Q(snoozed_until__isnull=True) | Q(snoozed_until__lt=now))
.filter(insight__deleted=False)
.annotate(_interval_order=calculation_interval_order)
- .order_by("_interval_order", F("next_check_at").asc(nulls_first=True))
- .only("id", "team_id", "calculation_interval", "insight_id")
+ .annotate(
+ _team_rank=Window(
+ expression=RowNumber(),
+ partition_by=[F("team_id")],
+ order_by=[
+ F("_interval_order").asc(),
+ F("next_check_at").asc(nulls_first=True),
+ F("id").asc(),
+ ],
+ ),
+ )
+ .order_by(
+ "_team_rank",
+ "_interval_order",
+ F("next_check_at").asc(nulls_first=True),
+ "team_id",
+ "id",
+ )
+ .only("id", "team_id", "calculation_interval", "insight_id")[:MAX_DUE_ALERTS_PER_SCHEDULE_RUN]
)
return [
diff --git a/posthog/temporal/alerts/workflows.py b/posthog/temporal/alerts/workflows.py
index 4b76a553c44f..28b56090c9d8 100644
--- a/posthog/temporal/alerts/workflows.py
+++ b/posthog/temporal/alerts/workflows.py
@@ -1,5 +1,4 @@
import json
-import asyncio
import datetime as dt
from uuid import UUID
@@ -61,65 +60,56 @@ class ScheduleDueAlertChecksWorkflow(PostHogWorkflow):
),
)
- # Fan-out child workflows — one per alert. Deterministic ID prevents
- # duplicate checks when schedule runs overlap; Temporal guarantees no
- # two open workflows can share the same ID, so a still-running child
- # rejects the duplicate start.
- tasks = []
+ # Fan-out child workflows — one per alert. Deterministic IDs prevent
+ # duplicate checks from retries or concurrent manual triggers. Wait
+ # only for Temporal to accept the start; the children run independently.
+ failed_ids: list[str] = []
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(
- alert_id=alert.alert_id,
- team_id=alert.team_id,
- distinct_id=alert.distinct_id,
- calculation_interval=alert.calculation_interval,
- insight_id=alert.insight_id,
- slo=SloConfig(
- operation=SloOperation.ALERT_CHECK,
- area=SloArea.ANALYTIC_PLATFORM,
+ try:
+ await temporalio.workflow.start_child_workflow(
+ CheckAlertWorkflow.run,
+ CheckAlertWorkflowInputs(
+ alert_id=alert.alert_id,
team_id=alert.team_id,
- resource_id=alert.alert_id,
distinct_id=alert.distinct_id,
- start_properties=slo_properties.copy(),
- completion_properties=slo_properties.copy(),
+ calculation_interval=alert.calculation_interval,
+ insight_id=alert.insight_id,
+ slo=SloConfig(
+ operation=SloOperation.ALERT_CHECK,
+ area=SloArea.ANALYTIC_PLATFORM,
+ team_id=alert.team_id,
+ resource_id=alert.alert_id,
+ distinct_id=alert.distinct_id,
+ start_properties=slo_properties.copy(),
+ completion_properties=slo_properties.copy(),
+ ),
),
- ),
- id=f"check-alert-{alert.alert_id}",
- parent_close_policy=temporalio.workflow.ParentClosePolicy.ABANDON,
- execution_timeout=alert_timeouts(alert.calculation_interval).workflow_execution,
- )
- tasks.append(task)
-
- if tasks:
- results = await asyncio.gather(*tasks, return_exceptions=True)
- failed_ids = []
- for alert, result in zip(alerts, results):
- if isinstance(result, BaseException):
- if isinstance(result, WorkflowAlreadyStartedError):
- # Previous schedule run's child still processing this
- # alert — not a failure, just skip it.
- temporalio.workflow.logger.info(
- "check_alert.already_running",
- extra={"alert_id": alert.alert_id},
- )
- else:
- failed_ids.append(alert.alert_id)
- temporalio.workflow.logger.warning(
- "check_alert.child_workflow_error",
- extra={"alert_id": alert.alert_id, "error": str(result)},
- )
-
- if failed_ids:
- raise ApplicationError(
- f"Alert checks failed for IDs: {failed_ids}",
- non_retryable=True,
+ id=f"check-alert-{alert.alert_id}",
+ parent_close_policy=temporalio.workflow.ParentClosePolicy.ABANDON,
+ execution_timeout=alert_timeouts(alert.calculation_interval).workflow_execution,
)
+ except WorkflowAlreadyStartedError:
+ temporalio.workflow.logger.info(
+ "check_alert.already_running",
+ extra={"alert_id": alert.alert_id},
+ )
+ except Exception as error:
+ failed_ids.append(alert.alert_id)
+ temporalio.workflow.logger.warning(
+ "check_alert.start_failed",
+ extra={"alert_id": alert.alert_id, "error": str(error)},
+ )
+
+ if failed_ids:
+ raise ApplicationError(
+ f"Alert checks failed to start for IDs: {failed_ids}",
+ non_retryable=True,
+ )
@temporalio.workflow.defn(name="check-alert")
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index 35acaf6a794b..5093db68bd50 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -28,7 +28,7 @@ from posthog.exceptions import (
ClickHouseClusterMemoryLimitExceeded,
ClickHouseQueryMemoryLimitExceeded,
)
-from posthog.models import User
+from posthog.models import Team, User
from posthog.slo.types import SloOperation, SloOutcome
from posthog.tasks.alerts.utils import (
AlertEvaluationResult,
@@ -41,6 +41,7 @@ from posthog.temporal.alerts.activities import (
notify_alert,
prepare_alert,
record_failed_evaluation,
+ retrieve_due_alerts,
)
from posthog.temporal.alerts.retry_policy import alert_timeouts
from posthog.temporal.alerts.types import (
@@ -82,7 +83,7 @@ def _memory_limit_error() -> ClickHouseQueryMemoryLimitExceeded:
async def _create_alert(
- ateam,
+ ateam: Team,
*,
query: dict | None = None,
enabled: bool = True,
@@ -130,6 +131,27 @@ async def _create_alert(
return await _create()
+async def test_retrieve_due_alerts_limits_each_schedule_run_to_fifty_without_starving_other_teams(
+ ateam: Team,
+) -> None:
+ for _ in range(50):
+ await _create_alert(ateam, calculation_interval=AlertCalculationInterval.REAL_TIME.value)
+
+ other_team = await sync_to_async(Team.objects.create)(
+ organization_id=ateam.organization_id,
+ project_id=ateam.project_id,
+ name="Other team",
+ )
+ other_alert = await _create_alert(other_team)
+
+ alerts = await ActivityEnvironment().run(retrieve_due_alerts)
+
+ assert len(alerts) == 50
+ assert str(other_alert.id) in {alert.alert_id for alert in alerts}
+
+
@pytest_asyncio.fixture
async def alert(ateam):
return await _create_alert(ateam)
diff --git a/posthog/temporal/tests/test_alerts_workflows.py b/posthog/temporal/tests/test_alerts_workflows.py
index 6eef8a8b5bf8..776a33eab67d 100644
--- a/posthog/temporal/tests/test_alerts_workflows.py
+++ b/posthog/temporal/tests/test_alerts_workflows.py
@@ -12,6 +12,7 @@ from django.conf import settings
import pytest_asyncio
from asgiref.sync import sync_to_async
from temporalio.client import WorkflowFailureError
+from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedError
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
@@ -49,7 +50,7 @@ CHECK_ALERT_ACTIVITIES: list[Callable[..., Any]] = [
@pytest.mark.asyncio
-async def test_schedule_due_alert_checks_adds_shared_slo_context() -> None:
+async def test_schedule_due_alert_checks_starts_child_with_shared_slo_context() -> None:
alert = AlertInfo(
alert_id="alert-1",
team_id=42,
@@ -64,12 +65,14 @@ async def test_schedule_due_alert_checks_adds_shared_slo_context() -> None:
new=AsyncMock(return_value=[alert]),
),
patch(
- "posthog.temporal.alerts.workflows.temporalio.workflow.execute_child_workflow", new=AsyncMock()
- ) as execute_child,
+ "posthog.temporal.alerts.workflows.temporalio.workflow.start_child_workflow", new=AsyncMock()
+ ) as start_child,
):
await ScheduleDueAlertChecksWorkflow().run()
- inputs = execute_child.call_args.args[1]
+ start_child.assert_awaited_once()
+ assert start_child.await_args is not None
+ inputs = start_child.await_args.args[1]
assert isinstance(inputs, CheckAlertWorkflowInputs)
assert inputs.slo is not None
assert inputs.slo.operation == SloOperation.ALERT_CHECK
@@ -88,6 +91,62 @@ async def test_schedule_due_alert_checks_adds_shared_slo_context() -> None:
assert "alert_state" not in inputs.slo.start_properties
+async def test_schedule_due_alert_checks_skips_already_running_children() -> 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.start_child_workflow",
+ new=AsyncMock(side_effect=WorkflowAlreadyStartedError("check-alert-alert-1", "check-alert")),
+ ) as start_child,
+ patch("posthog.temporal.alerts.workflows.temporalio.workflow.logger", new=MagicMock()),
+ ):
+ await ScheduleDueAlertChecksWorkflow().run()
+
+ start_child.assert_awaited_once()
+
+
+async def test_schedule_due_alert_checks_attempts_remaining_children_before_reporting_start_failures() -> None:
+ alerts = [
+ AlertInfo(
+ alert_id=f"alert-{index}",
+ team_id=42,
+ distinct_id=f"user-{index}",
+ calculation_interval=AlertCalculationInterval.DAILY.value,
+ insight_id=123,
+ )
+ for index in range(2)
+ ]
+
+ with (
+ patch(
+ "posthog.temporal.alerts.workflows.temporalio.workflow.execute_activity",
+ new=AsyncMock(return_value=alerts),
+ ),
+ patch(
+ "posthog.temporal.alerts.workflows.temporalio.workflow.start_child_workflow",
+ new=AsyncMock(side_effect=[RuntimeError("start failed"), None]),
+ ) as start_child,
+ patch("posthog.temporal.alerts.workflows.temporalio.workflow.logger", new=MagicMock()),
+ ):
+ with pytest.raises(ApplicationError, match="alert-0"):
+ await ScheduleDueAlertChecksWorkflow().run()
+
+ assert start_child.await_count == 2
+
+
def test_schedule_is_registered_in_init_schedules():
from posthog.temporal.schedule import schedules