: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
fix(alerts): increase due alert schedule cap (#97455)
Vasco de Krijger779cdc85f838
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.pyindex 85c280460770..a785acb4c03d 100644--- a/posthog/temporal/alerts/activities.py+++ b/posthog/temporal/alerts/activities.py@@ -46,6 +46,7 @@ from posthog.temporal.alerts.types import (PrepareAlertResult,RecordFailedEvaluationActivityInputs,RecordFailedEvaluationResult,+ ScheduleDueAlertChecksWorkflowInputs,SkipReason,)from posthog.temporal.common.heartbeat import Heartbeater@@ -68,11 +69,13 @@ 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-async def retrieve_due_alerts() -> list[AlertInfo]:+async def retrieve_due_alerts(inputs: ScheduleDueAlertChecksWorkflowInputs | None = None) -> list[AlertInfo]:+ if inputs is None:+ inputs = ScheduleDueAlertChecksWorkflowInputs()+@database_sync_to_async(thread_sensitive=False)def get_alerts() -> list[AlertInfo]:now = datetime.now(UTC)@@ -111,7 +114,7 @@ async def retrieve_due_alerts() -> list[AlertInfo]:"team_id","id",)- .only("id", "team_id", "calculation_interval", "insight_id")[:MAX_DUE_ALERTS_PER_SCHEDULE_RUN]+ .only("id", "team_id", "calculation_interval", "insight_id")[: inputs.max_alerts_per_run])return [diff --git a/posthog/temporal/alerts/schedule.py b/posthog/temporal/alerts/schedule.pyindex 3c48ed94e0a5..28b2b331398d 100644--- a/posthog/temporal/alerts/schedule.py+++ b/posthog/temporal/alerts/schedule.py@@ -11,6 +11,7 @@ from temporalio.client import (ScheduleSpec,)+from posthog.temporal.alerts.types import ScheduleDueAlertChecksWorkflowInputsfrom posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_scheduleSCHEDULE_ID = "schedule-due-alert-checks-schedule"@@ -22,6 +23,7 @@ async def create_schedule_due_alert_checks_schedule(client: Client) -> None:schedule = Schedule(action=ScheduleActionStartWorkflow("schedule-due-alert-checks",+ ScheduleDueAlertChecksWorkflowInputs(),id=SCHEDULE_ID,task_queue=settings.ANALYTICS_PLATFORM_TASK_QUEUE,execution_timeout=dt.timedelta(minutes=10),diff --git a/posthog/temporal/alerts/types.py b/posthog/temporal/alerts/types.pyindex eb1cb657f80b..d454da4f795f 100644--- a/posthog/temporal/alerts/types.py+++ b/posthog/temporal/alerts/types.py@@ -3,8 +3,11 @@ from enum import StrEnumfrom posthog.schema import AlertState+from posthog.dataclasses import frozenfrom posthog.slo.types import SloConfig+DEFAULT_MAX_DUE_ALERTS_PER_SCHEDULE_RUN = 300+class PrepareAction(StrEnum):EVALUATE = "evaluate"@@ -31,6 +34,11 @@ class AlertInfo:insight_id: int+@frozen+class ScheduleDueAlertChecksWorkflowInputs:+ max_alerts_per_run: int = DEFAULT_MAX_DUE_ALERTS_PER_SCHEDULE_RUN++@dataclasses.dataclass(frozen=True)class CheckAlertWorkflowInputs:alert_id: strdiff --git a/posthog/temporal/alerts/workflows.py b/posthog/temporal/alerts/workflows.pyindex 28b56090c9d8..a04856dad23f 100644--- a/posthog/temporal/alerts/workflows.py+++ b/posthog/temporal/alerts/workflows.py@@ -32,6 +32,7 @@ from posthog.temporal.alerts.types import (PrepareAction,PrepareAlertActivityInputs,RecordFailedEvaluationActivityInputs,+ ScheduleDueAlertChecksWorkflowInputs,)from posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.errors import MAX_ERROR_MESSAGE_CHARS, truncate_for_temporal_payload, unwrap_temporal_cause@@ -45,13 +46,21 @@ with temporalio.workflow.unsafe.imports_passed_through():@temporalio.workflow.defn(name="schedule-due-alert-checks")class ScheduleDueAlertChecksWorkflow(PostHogWorkflow):@staticmethod- def parse_inputs(inputs: list[str]) -> None:- return None+ def parse_inputs(inputs: list[str]) -> ScheduleDueAlertChecksWorkflowInputs:+ if not inputs:+ return ScheduleDueAlertChecksWorkflowInputs()++ loaded = json.loads(inputs[0])+ return ScheduleDueAlertChecksWorkflowInputs(**loaded)@temporalio.workflow.run- async def run(self) -> None:+ async def run(self, inputs: ScheduleDueAlertChecksWorkflowInputs | None = None) -> None:+ if inputs is None:+ inputs = ScheduleDueAlertChecksWorkflowInputs()+alerts = await temporalio.workflow.execute_activity(retrieve_due_alerts,+ inputs,start_to_close_timeout=dt.timedelta(minutes=2),retry_policy=temporalio.common.RetryPolicy(initial_interval=dt.timedelta(seconds=5),diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.pyindex 5093db68bd50..ce414d5a1307 100644--- a/posthog/temporal/tests/test_alerts_activities.py+++ b/posthog/temporal/tests/test_alerts_activities.py@@ -50,6 +50,7 @@ from posthog.temporal.alerts.types import (PrepareAction,PrepareAlertActivityInputs,RecordFailedEvaluationActivityInputs,+ ScheduleDueAlertChecksWorkflowInputs,SkipReason,)@@ -133,10 +134,11 @@ async def _create_alert(@pytest.mark.asyncio@pytest.mark.django_db-async def test_retrieve_due_alerts_limits_each_schedule_run_to_fifty_without_starving_other_teams(+async def test_retrieve_due_alerts_limits_each_schedule_run_without_starving_other_teams(ateam: Team,) -> None:- for _ in range(50):+ max_alerts_per_run = 2+ for _ in range(max_alerts_per_run):await _create_alert(ateam, calculation_interval=AlertCalculationInterval.REAL_TIME.value)other_team = await sync_to_async(Team.objects.create)(@@ -146,9 +148,12 @@ async def test_retrieve_due_alerts_limits_each_schedule_run_to_fifty_without_sta)other_alert = await _create_alert(other_team)- alerts = await ActivityEnvironment().run(retrieve_due_alerts)+ alerts = await ActivityEnvironment().run(+ retrieve_due_alerts,+ ScheduleDueAlertChecksWorkflowInputs(max_alerts_per_run=max_alerts_per_run),+ )- assert len(alerts) == 50+ assert len(alerts) == max_alerts_per_runassert str(other_alert.id) in {alert.alert_id for alert in alerts}diff --git a/posthog/temporal/tests/test_alerts_workflows.py b/posthog/temporal/tests/test_alerts_workflows.pyindex 776a33eab67d..5f3718d29125 100644--- a/posthog/temporal/tests/test_alerts_workflows.py+++ b/posthog/temporal/tests/test_alerts_workflows.py@@ -33,7 +33,12 @@ from posthog.tasks.alerts.utils import AlertEvaluationResultfrom posthog.temporal.alerts.activities import evaluate_alert, notify_alert, prepare_alert, record_failed_evaluationfrom posthog.temporal.alerts.retry_policy import ALERT_EVALUATE_RETRY_POLICYfrom posthog.temporal.alerts.schedule import create_schedule_due_alert_checks_schedule-from posthog.temporal.alerts.types import AlertInfo, CheckAlertWorkflowInputs, SkipReason+from posthog.temporal.alerts.types import (+ AlertInfo,+ CheckAlertWorkflowInputs,+ ScheduleDueAlertChecksWorkflowInputs,+ SkipReason,+)from posthog.temporal.alerts.workflows import CheckAlertWorkflow, ScheduleDueAlertChecksWorkflowfrom posthog.temporal.common.slo_interceptor import SloInterceptorfrom posthog.temporal.tests.test_alerts_activities import _email_delivery@@ -49,6 +54,42 @@ CHECK_ALERT_ACTIVITIES: list[Callable[..., Any]] = []+async def test_schedule_due_alert_checks_passes_configured_limit_to_retrieval() -> None:+ execute_activity = AsyncMock(return_value=[])+ inputs = ScheduleDueAlertChecksWorkflowInputs(max_alerts_per_run=17)++ with patch(+ "posthog.temporal.alerts.workflows.temporalio.workflow.execute_activity",+ new=execute_activity,+ ):+ await ScheduleDueAlertChecksWorkflow().run(inputs)++ assert execute_activity.await_args is not None+ assert execute_activity.await_args.args[1] == inputs+++async def test_schedule_due_alert_checks_defaults_to_three_hundred_alerts() -> None:+ create_schedule = AsyncMock()++ with (+ patch(+ "posthog.temporal.alerts.schedule.a_schedule_exists",+ new=AsyncMock(return_value=False),+ ),+ patch(+ "posthog.temporal.alerts.schedule.a_create_schedule",+ new=create_schedule,+ ),+ ):+ await create_schedule_due_alert_checks_schedule(MagicMock())++ assert create_schedule.await_args is not None+ schedule = create_schedule.await_args.args[2]+ assert schedule.action.args == [ScheduleDueAlertChecksWorkflowInputs(max_alerts_per_run=300)]++@pytest.mark.asyncioasync def test_schedule_due_alert_checks_starts_child_with_shared_slo_context() -> None:alert = AlertInfo(