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): evaluate insight alerts on the platform in parallel (#111204)

Jimmy Zhue14e5116e2b1
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.md
index 0827b2abac6d..136fac4a61f0 100644
--- a/docs/internal/alerts-platform-temporal.md
+++ b/docs/internal/alerts-platform-temporal.md
@@ -10,7 +10,7 @@ The alerts platform registers three queues through `products/alerts_platform/bac
These queue names are hardcoded and stay separate even with `DEBUG=True`.
Shared orchestration registers the orchestration workflow, the source dispatcher and a synthetic demand-discovery activity.
-The evaluation queue registers the evaluation workflow (`alerts-platform-evaluate`), each bound source evaluation, and the probe activity.
+The evaluation queue registers the evaluation workflow (`alerts-platform-evaluate`), the logs and insight source evaluations, the probe activity and the record-outcomes activity.
Each schedule tick starts orchestration, which discovers demand once and then pages source dispatchers until the demand is exhausted or its dispatch budget is spent.
Each dispatcher starts one evaluation child for its source. Evaluation runs the probe and starts its independent delivery child on the delivery queue.
Start one worker for each queue:
@@ -169,7 +169,7 @@ The limit that will matter is the evaluation workflow's own history, which depen
It starts one evaluation child per key with `ParentClosePolicy.ABANDON` and one attempt.
A source with an entry in `SOURCE_BINDINGS` (`temporal/sources.py`) starts the binding's workflow on the binding's `task_queue`, under its `evaluation_timeout`.
A source with no binding starts `alerts-platform-evaluate` on the evaluation queue, under the 75-second `NOOP_EVALUATION_TIMEOUT`.
-A source with slow checks gets its own queue and its own timeout, so it neither shares the logs ceiling nor holds the logs worker's slots.
+Each source has its own timeout, so no source adopts the logs ceiling. Sources share the evaluation queue while their checks finish in seconds. A source whose checks hold a worker slot for minutes needs its own queue, so that it does not hold the slots the other sources need.
The timeout has to hold every attempt a source's activities allow, because an attempt cut off here is a batch that decided something and recorded nothing.
Evaluations are abandoned rather than awaited, so it does not have to fit inside the tick.
It waits for the child to start, never for it to finish, then returns the dispatched count and the remaining IDs.
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index dac2add4e669..d1a758c0c641 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -150,6 +150,10 @@ from posthog.temporal.weekly_digest import (
WORKFLOWS as WEEKLY_DIGEST_WORKFLOWS,
)
+from products.alerts.backend.facade.temporal import (
+ PLATFORM_EVALUATION_ACTIVITIES as INSIGHT_PLATFORM_EVALUATION_ACTIVITIES,
+ PLATFORM_EVALUATION_WORKFLOWS as INSIGHT_PLATFORM_EVALUATION_WORKFLOWS,
+)
from products.alerts_platform.backend.facade.temporal import (
DELIVERY_ACTIVITIES as ALERTS_PLATFORM_DELIVERY_ACTIVITIES,
DELIVERY_WORKFLOWS as ALERTS_PLATFORM_DELIVERY_WORKFLOWS,
@@ -599,8 +603,10 @@ _task_queue_specs = [
),
(
settings.ALERTS_PLATFORM_EVALUATION_TASK_QUEUE,
- ALERTS_PLATFORM_EVALUATION_WORKFLOWS + LOGS_SOURCE_EVALUATION_WORKFLOWS,
- ALERTS_PLATFORM_EVALUATION_ACTIVITIES + LOGS_SOURCE_EVALUATION_ACTIVITIES,
+ ALERTS_PLATFORM_EVALUATION_WORKFLOWS + LOGS_SOURCE_EVALUATION_WORKFLOWS + INSIGHT_PLATFORM_EVALUATION_WORKFLOWS,
+ ALERTS_PLATFORM_EVALUATION_ACTIVITIES
+ + LOGS_SOURCE_EVALUATION_ACTIVITIES
+ + INSIGHT_PLATFORM_EVALUATION_ACTIVITIES,
),
(
settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE,
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index 93a059ac4f47..420afd57fb33 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -323,6 +323,15 @@ ANALYTICS_PLATFORM_TASK_QUEUE = _set_temporal_task_queue("analytics-platform-tas
ALERTS_PLATFORM_SHARED_ORCHESTRATION_TASK_QUEUE = "alerts-platform-shared-orchestration-task-queue"
ALERTS_PLATFORM_EVALUATION_TASK_QUEUE = "alerts-platform-evaluation-task-queue"
ALERTS_PLATFORM_DELIVERY_TASK_QUEUE = "alerts-platform-delivery-task-queue"
+# The platform's parallel insight checks allowed to run at once, across every team. A pool of its
+# own, so the parallel run never takes a slot from `ALERTS_MAX_INFLIGHT_EVALUATIONS`.
+ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS: int = get_from_env(
+ "ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS", 10, type_cast=int
+)
+if ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS <= 0:
+ raise ImproperlyConfigured(
+ "ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS must be a positive integer, or no platform insight check starts"
+ )
# Insight alert checks allowed to run against ClickHouse at once, across every team.
ALERTS_MAX_INFLIGHT_EVALUATIONS: int = get_from_env("ALERTS_MAX_INFLIGHT_EVALUATIONS", 40, type_cast=int)
if ALERTS_MAX_INFLIGHT_EVALUATIONS <= 0:
diff --git a/products/alerts/backend/facade/temporal.py b/products/alerts/backend/facade/temporal.py
new file mode 100644
index 000000000000..907d1b214611
--- /dev/null
+++ b/products/alerts/backend/facade/temporal.py
@@ -0,0 +1,11 @@
+"""Temporal workflows and activities this product registers on the alerts platform's queues."""
+
+from products.alerts.backend.temporal.platform_evaluate import (
+ PLATFORM_EVALUATION_ACTIVITIES,
+ PLATFORM_EVALUATION_WORKFLOWS,
+)
+
+__all__ = [
+ "PLATFORM_EVALUATION_ACTIVITIES",
+ "PLATFORM_EVALUATION_WORKFLOWS",
+]
diff --git a/products/alerts/backend/insight_alert_state_machine.py b/products/alerts/backend/insight_alert_state_machine.py
index d4126d72dbbe..6ec8b59121bc 100644
--- a/products/alerts/backend/insight_alert_state_machine.py
+++ b/products/alerts/backend/insight_alert_state_machine.py
@@ -35,13 +35,31 @@ INSIGHT_ALERT_POLICY = AlertPolicy(
)
-def snapshot_from_alert(alert: AlertConfiguration) -> AlertSnapshot:
+def insight_snapshot(
+ state: AlertState,
+ *,
+ last_notified_at: datetime | None,
+ snooze_until: datetime | None = None,
+ firing_started_at: datetime | None = None,
+) -> AlertSnapshot:
+ """The machine's view of an insight alert. The model keeps no failure counter, so an ERRORED
+ state reads as one failure. The platform's parallel run builds its view here too, so both
+ stacks announce an error on the same check."""
return AlertSnapshot(
- state=AlertState[InsightAlertState(alert.state).name],
+ state=state,
cooldown=timedelta(0),
+ last_notified_at=last_notified_at,
+ snooze_until=snooze_until,
+ consecutive_failures=1 if state == AlertState.ERRORED else 0,
+ firing_started_at=firing_started_at,
+ )
+
+
+def snapshot_from_alert(alert: AlertConfiguration) -> AlertSnapshot:
+ return insight_snapshot(
+ AlertState[InsightAlertState(alert.state).name],
last_notified_at=alert.last_notified_at,
snooze_until=alert.snoozed_until,
- consecutive_failures=1 if alert.state == InsightAlertState.ERRORED else 0,
)
diff --git a/products/alerts/backend/platform_source_cycle.py b/products/alerts/backend/platform_source_cycle.py
new file mode 100644
index 000000000000..7c7a18c3b421
--- /dev/null
+++ b/products/alerts/backend/platform_source_cycle.py
@@ -0,0 +1,325 @@
+"""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.
+
+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
+query runs the way production runs it, and the verdict comes from the shared machine under
+`INSIGHT_ALERT_POLICY`, applied to the platform's own state. `add_alert_check` is the production
+writer, and nothing here calls it.
+
+A check that production skips without a query is skipped here too, so both stacks answer the
+same set of checks.
+"""
+
+import time
+from dataclasses import replace
+from datetime import UTC, datetime
+
+from django.conf import settings
+
+import structlog
+
+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
+from posthog.schema_enums import AlertCalculationInterval
+from posthog.tasks.alerts.schedule_restriction import is_utc_datetime_blocked
+from posthog.tasks.alerts.utils import skip_because_of_weekend
+from posthog.temporal.alerts.admission import admit_evaluation_slots, release_evaluation_slot
+
+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.models.alert import AlertConfiguration
+from products.alerts_platform.backend.facade.api import due_checks, slot_of
+from products.alerts_platform.backend.facade.contracts import (
+ PlatformAlertCheckInput,
+ PlatformAlertOutcome,
+ SkipReason,
+ SourceKind,
+)
+from products.alerts_platform.backend.facade.lifecycle import (
+ NOTIFICATION_EVENT_KINDS,
+ AlertSnapshot,
+ AlertState,
+ CheckInput,
+ ControlPlaneOutcome,
+ NotificationAction,
+ Outcome,
+ apply_snooze,
+ apply_unsnooze,
+ decide_firing_episode,
+ evaluate_alert_check,
+)
+from products.alerts_platform.backend.facade.platform_metrics import (
+ increment_checks,
+ increment_checks_skipped,
+ increment_state_transition,
+ record_scheduler_lag,
+ safe_record,
+)
+
+logger = structlog.get_logger(__name__)
+
+INFLIGHT_KEY = "alerts:platform:insight:evaluations:inflight"
+
+# Every query the parallel run sends starts with this, so its ClickHouse cost can be read apart from
+# production's in `query_log`. Production's other tags are kept, so workload management treats both
+# the same way.
+QUERY_ID_PREFIX = "alerts-platform-insight:"
+
+# The history row's error for a check ClickHouse refused for load. Stable, because a comparison
+# matches on it to set those checks aside.
+CAPACITY_REJECTED = "ClickHouse refused the query for capacity"
+
+# Real-time and 15-minute alerts are the most expensive cadences and the ones production holds to a
+# tighter budget, so the parallel run leaves them out until it agrees with production elsewhere.
+EVALUATED_INTERVALS = frozenset(
+ {
+ AlertCalculationInterval.HOURLY,
+ AlertCalculationInterval.DAILY,
+ AlertCalculationInterval.WEEKLY,
+ AlertCalculationInterval.MONTHLY,
+ }
+)
+
+
+def is_evaluated_on_the_platform(alert: AlertConfiguration) -> bool:
+ """Threshold alerts on an hourly 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."""
+ return not alert.detector_config and alert.calculation_interval in EVALUATED_INTERVALS
+
+
+def plan_insight_batch(team_id: int, slot: str, cutoff: datetime, *, expires_at: float) -> tuple[str, ...]:
+ """Admits the batch's checks into the pool, in id order, while it has room, and returns the
+ ids it admitted.
+
+ The checks left out keep their due time, so a later tick finds them again. `expires_at` comes
+ from the workflow rather than the clock, so a retried attempt gets back the same admitted ids.
+ """
+ checks = due_checks(team_id, SourceKind.INSIGHT.value, slot, cutoff)
+ if not checks:
+ return ()
+ admitted = admit_evaluation_slots(
+ [str(check.id) for check in checks],
+ limit=settings.ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS,
+ expires_at=expires_at,
+ key=INFLIGHT_KEY,
+ )
+ if len(admitted) < len(checks):
+ logger.info(
+ "Deferred platform insight checks over the pool limit",
+ team_id=team_id,
+ slot=slot,
+ admitted=len(admitted),
+ deferred=len(checks) - len(admitted),
+ )
+ return tuple(admitted)
+
+
+def evaluate_insight_check(
+ team_id: int,
+ slot: str,
+ cutoff: datetime,
+ configuration_id: str,
+ *,
+ held_until: float,
+ evaluation_id: str,
+) -> PlatformAlertOutcome | 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.
+ """
+ try:
+ checks = due_checks(team_id, SourceKind.INSIGHT.value, slot, cutoff, configuration_ids=[configuration_id])
+ if not checks:
+ return None
+ if checks[0].next_check_at is not None:
+ # Wall clock rather than the tick: a check can wait in the pool and the worker queue,
+ # and that wait is the lag a backlog shows up as.
+ 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)
+ finally:
+ release_evaluation_slot(configuration_id, held_until=held_until, key=INFLIGHT_KEY)
+
+
+def _legacy_alert(check: PlatformAlertCheckInput) -> AlertConfiguration | None:
+ if check.legacy_configuration_id is None:
+ return None
+ return (
+ AlertConfiguration.objects.select_related("insight", "team", "threshold", "created_by")
+ .filter(team_id=check.team_id, id=check.legacy_configuration_id)
+ .first()
+ )
+
+
+def _snapshot(check: PlatformAlertCheckInput) -> AlertSnapshot:
+ return insight_snapshot(
+ AlertState(check.state), last_notified_at=check.last_notified_at, firing_started_at=check.firing_started_at
+ )
+
+
+def _evaluation_key(check: PlatformAlertCheckInput, cutoff: datetime) -> str:
+ """The due slot. An insight check is one scheduled run, not a window, so the slot names it."""
+ return f"slot:{slot_of(check.next_check_at, cutoff)}"
+
+
+def _decide(check: PlatformAlertCheckInput, now: datetime, *, evaluation_id: str) -> PlatformAlertOutcome:
+ snapshot = _snapshot(check)
+ alert = _legacy_alert(check)
+ if alert is None:
+ # The production alert is gone, so this copy can never be compared again.
+ return _skipped(check, snapshot, now=now, disable=True)
+ if not alert.enabled or alert.insight.deleted or not is_evaluated_on_the_platform(alert):
+ return _skipped(check, snapshot, now=now)
+ if skip_because_of_weekend(alert) or is_utc_datetime_blocked(alert, now):
+ return _skipped(check, snapshot, now=now)
+
+ # Production gates evaluation on a snooze and holds the alert in SNOOZED, then clears it to
+ # NOT_FIRING on the first check after the snooze ends. The legacy row is read for the snooze,
+ # because a snooze set after the backfill copied the row lives only there.
+ if alert.snoozed_until is not None and alert.snoozed_until > now:
+ return _recorded(check, snapshot, apply_snooze(snapshot), now=now, skip=SkipReason.SOURCE_RULE)
+ if snapshot.state == AlertState.SNOOZED:
+ unsnoozed = apply_unsnooze(snapshot)
+ snapshot = replace(snapshot, state=unsnoozed.new_state, consecutive_failures=unsnoozed.consecutive_failures)
+
+ # Production's tags, so ClickHouse workload management treats the query the way it treats
+ # production's and its cost is grouped the same way in the query log. The user is the
+ # platform's own, so the parallel run never takes from production's per-user budget.
+ tag_queries(
+ ch_user=ClickHouseUser.ALERTS_PLATFORM_INSIGHT,
+ team_id=alert.team_id,
+ client_query_id=f"{QUERY_ID_PREFIX}{evaluation_id}",
+ alert_config_id=str(alert.id),
+ product=Product.PRODUCT_ANALYTICS,
+ feature=Feature.ALERTING,
+ alert_calculation_interval=alert.calculation_interval,
+ alert_config_type=(alert.config or {}).get("type"),
+ )
+ started_at = time.monotonic()
+ try:
+ result = check_alert_for_insight(alert, evaluation_id=evaluation_id)
+ except AlertExtractionError as error:
+ return _recorded(
+ check,
+ snapshot,
+ ControlPlaneOutcome(new_state=AlertState.ERRORED, consecutive_failures=0),
+ now=now,
+ notification=NotificationAction.ERROR,
+ notified=True,
+ error_message=str(error),
+ skip=SkipReason.BROKEN_CONFIG,
+ disable=True,
+ )
+ except Exception as error:
+ if classify_query_error(error) == QueryErrorCategory.RATE_LIMITED:
+ return _skipped(check, snapshot, now=now, skip=SkipReason.CAPACITY, error_message=CAPACITY_REJECTED)
+ if not isinstance(error, CH_TRANSIENT_ERRORS):
+ logger.exception("Platform insight check failed", check_id=str(check.id), error=str(error))
+ return _verdict(
+ check,
+ snapshot,
+ CheckInput(
+ threshold_breached=False,
+ error_message=str(error),
+ is_transient_error=isinstance(error, CH_TRANSIENT_ERRORS),
+ ),
+ now=now,
+ skip=SkipReason.QUERY_FAILED,
+ )
+ duration_ms = int((time.monotonic() - started_at) * 1000)
+
+ if result.skipped_reason is not None:
+ return _skipped(check, snapshot, now=now)
+ return _verdict(
+ check,
+ snapshot,
+ CheckInput(threshold_breached=bool(result.breaches)),
+ now=now,
+ value=result.value,
+ query_duration_ms=duration_ms,
+ )
+
+
+def _verdict(
+ check: PlatformAlertCheckInput,
+ snapshot: AlertSnapshot,
+ check_input: CheckInput,
+ *,
+ now: datetime,
+ value: float | None = None,
+ query_duration_ms: int | None = None,
+ skip: SkipReason | None = None,
+) -> PlatformAlertOutcome:
+ outcome = evaluate_alert_check(snapshot, check_input, now, policy=INSIGHT_ALERT_POLICY)
+ return _recorded(
+ check,
+ snapshot,
+ outcome,
+ now=now,
+ notification=outcome.notification,
+ notified=outcome.update_last_notified_at,
+ value=value,
+ error_message=outcome.error_message,
+ query_duration_ms=query_duration_ms,
+ skip=skip,
+ disable=outcome.disable,
+ )
+
+
+def _skipped(
+ check: PlatformAlertCheckInput,
+ snapshot: AlertSnapshot,
+ *,
+ now: datetime,
+ skip: SkipReason = SkipReason.SOURCE_RULE,
+ error_message: str | None = None,
+ disable: bool = False,
+) -> PlatformAlertOutcome:
+ """A check that reached no verdict. Recorded all the same, so its schedule advances."""
+ unchanged = ControlPlaneOutcome(new_state=snapshot.state, consecutive_failures=snapshot.consecutive_failures)
+ return _recorded(check, snapshot, unchanged, now=now, skip=skip, error_message=error_message, disable=disable)
+
+
+def _recorded(
+ check: PlatformAlertCheckInput,
+ snapshot: AlertSnapshot,
+ outcome: Outcome,
+ *,
+ now: datetime,
+ notification: NotificationAction = NotificationAction.NONE,
+ notified: bool = False,
+ value: float | None = None,
+ error_message: str | None = None,
+ query_duration_ms: int | None = None,
+ skip: SkipReason | None = None,
+ disable: bool = False,
+) -> PlatformAlertOutcome:
+ """The one place an outcome is built. Every path goes through the firing decision, because
+ an outcome without an episode clears the start of a firing the alert is still in."""
+ source = SourceKind.INSIGHT.value
+ safe_record(increment_checks, source, notification.value)
+ if skip is not None:
+ safe_record(increment_checks_skipped, source, skip.value)
+ if check.state != outcome.new_state.value:
+ safe_record(increment_state_transition, source, check.state, outcome.new_state.value)
+ return PlatformAlertOutcome(
+ configuration_id=check.id,
+ evaluation_key=_evaluation_key(check, now),
+ kind=NOTIFICATION_EVENT_KINDS[notification],
+ new_state=outcome.new_state.value,
+ notified=notified,
+ consecutive_failures=outcome.consecutive_failures,
+ firing_episode=decide_firing_episode(snapshot, outcome, now, policy=INSIGHT_ALERT_POLICY),
+ value=value,
+ error_message=error_message,
+ query_duration_ms=query_duration_ms,
+ disable=disable,
+ )
diff --git a/products/alerts/backend/temporal/__init__.py b/products/alerts/backend/temporal/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/alerts/backend/temporal/platform_evaluate.py b/products/alerts/backend/temporal/platform_evaluate.py
new file mode 100644
index 000000000000..6fec106fddeb
--- /dev/null
+++ b/products/alerts/backend/temporal/platform_evaluate.py
@@ -0,0 +1,157 @@
+"""Temporal wiring for the platform's parallel insight evaluation.
+
+The decisions live in `products/alerts/backend/platform_source_cycle.py`, so they stay plain
+functions a test can call without Temporal.
+
+One activity per admitted check, run side by side. A batch key is a team's alerts due in one
+minute, and daily alerts in one timezone share their minute, so evaluating a key one check after
+another would put the last check minutes behind the first.
+"""
+
+import asyncio
+import datetime as dt
+
+from temporalio import activity, workflow
+from temporalio.common import RetryPolicy
+from temporalio.exceptions import ActivityError
+
+from posthog.dataclasses import frozen
+from posthog.temporal.common.base import PostHogWorkflow
+
+with workflow.unsafe.imports_passed_through():
+ from posthog.temporal.alerts.retry_policy import alert_timeouts
+ from posthog.temporal.common.utils import close_db_connections
+
+ from products.alerts_platform.backend.facade.contracts import (
+ RECORD_OUTCOMES_ACTIVITY,
+ PlatformAlertOutcome,
+ SourceEvaluationInputs,
+ SourceKind,
+ SourceOutcomeInputs,
+ )
+ from products.alerts_platform.backend.facade.temporal import source_evaluation_timeout
+
+PLAN_START_TO_CLOSE = dt.timedelta(seconds=10)
+PLAN_SCHEDULE_TO_CLOSE = dt.timedelta(seconds=20)
+# Production's per-attempt budget for an hourly or slower check, so a query the parallel run
+# gives up on is one production would have given up on as well.
+CHECK_START_TO_CLOSE = alert_timeouts(None).evaluate_start_to_close
+# Checks wait for a worker slot here. Derived rather than set, so queue time cannot shorten a
+# check below its own budget.
+CHECK_QUEUE_TOLERANCE = dt.timedelta(minutes=1)
+CHECK_SCHEDULE_TO_CLOSE = CHECK_START_TO_CLOSE + CHECK_QUEUE_TOLERANCE
+RECORD_START_TO_CLOSE = dt.timedelta(seconds=8)
+RECORD_SCHEDULE_TO_CLOSE = dt.timedelta(seconds=12)
+# What the source needs from its binding's `evaluation_timeout`. The checks run side by side, so
+# the batch costs one check's budget, not one per check.
+EVALUATION_BUDGET = PLAN_SCHEDULE_TO_CLOSE + CHECK_SCHEDULE_TO_CLOSE + RECORD_SCHEDULE_TO_CLOSE
+
+
+@frozen
+class InsightBatchPlanInputs:
+ evaluation: SourceEvaluationInputs
+ expires_at: float
+
+
+@frozen
+class InsightCheckInputs:
+ evaluation: SourceEvaluationInputs
+ configuration_id: str
+ held_until: float
+
+
+@close_db_connections
+def plan_platform_insight_batch_activity(inputs: InsightBatchPlanInputs) -> list[str]:
+ # Imported in the body: the workflow below forces this module to evaluate inside Temporal's
+ # sandbox, which a Django model import trips.
+ from products.alerts.backend.platform_source_cycle import plan_insight_batch # noqa: PLC0415
+
+ key = inputs.evaluation.batch_key
+ return list(
+ plan_insight_batch(
+ key.team_id, key.slot, dt.datetime.fromisoformat(inputs.evaluation.cutoff), expires_at=inputs.expires_at
+ )
+ )
+
+
+@close_db_connections
+def evaluate_platform_insight_check_activity(inputs: InsightCheckInputs) -> PlatformAlertOutcome | 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
+
+ info = activity.info()
+ key = inputs.evaluation.batch_key
+ return evaluate_insight_check(
+ key.team_id,
+ key.slot,
+ dt.datetime.fromisoformat(inputs.evaluation.cutoff),
+ inputs.configuration_id,
+ held_until=inputs.held_until,
+ evaluation_id=f"{info.workflow_run_id}:{info.activity_id}:{info.attempt}",
+ )
+
+
[email protected](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."""
+
+ inputs_cls = SourceEvaluationInputs
+
+ @workflow.run
+ async def run(self, inputs: SourceEvaluationInputs) -> int:
+ # From the workflow's clock, so a retried plan reuses the expiry and gets its slots back. A
+ # check releases its slot only while the slot still carries this expiry.
+ expires_at = (workflow.now() + source_evaluation_timeout(SourceKind.INSIGHT)).timestamp()
+ admitted = await workflow.execute_activity(
+ plan_platform_insight_batch_activity,
+ InsightBatchPlanInputs(evaluation=inputs, expires_at=expires_at),
+ start_to_close_timeout=PLAN_START_TO_CLOSE,
+ schedule_to_close_timeout=PLAN_SCHEDULE_TO_CLOSE,
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ if not admitted:
+ return 0
+
+ # One attempt each. A check that does not finish leaves no outcome, so it keeps its due time
+ # and a later tick evaluates it again, the way a cohort the logs budget left out behaves.
+ settled = await asyncio.gather(
+ *(
+ workflow.execute_activity(
+ evaluate_platform_insight_check_activity,
+ InsightCheckInputs(evaluation=inputs, configuration_id=configuration_id, held_until=expires_at),
+ start_to_close_timeout=CHECK_START_TO_CLOSE,
+ schedule_to_close_timeout=CHECK_SCHEDULE_TO_CLOSE,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+ for configuration_id in admitted
+ ),
+ return_exceptions=True,
+ )
+ for result in settled:
+ # Only a check's own failure is a missing outcome. A cancellation or a bug in this
+ # 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))
+ if len(outcomes) < len(settled):
+ workflow.logger.warning(
+ "%d of %d platform insight checks reached no outcome", len(settled) - len(outcomes), len(settled)
+ )
+ if not outcomes:
+ return 0
+
+ await workflow.execute_activity(
+ RECORD_OUTCOMES_ACTIVITY,
+ SourceOutcomeInputs(team_id=inputs.batch_key.team_id, cutoff=inputs.cutoff, outcomes=outcomes),
+ start_to_close_timeout=RECORD_START_TO_CLOSE,
+ schedule_to_close_timeout=RECORD_SCHEDULE_TO_CLOSE,
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ return len(outcomes)
+
+
+PLATFORM_EVALUATION_WORKFLOWS = [InsightAlertPlatformEvaluateWorkflow]
+PLATFORM_EVALUATION_ACTIVITIES = [plan_platform_insight_batch_activity, evaluate_platform_insight_check_activity]
diff --git a/products/alerts/backend/test/test_platform_evaluate_workflow.py b/products/alerts/backend/test/test_platform_evaluate_workflow.py
new file mode 100644
index 000000000000..617ec9ba04c3
--- /dev/null
+++ b/products/alerts/backend/test/test_platform_evaluate_workflow.py
@@ -0,0 +1,85 @@
+import uuid
+from collections.abc import AsyncIterator
+
+import pytest_asyncio
+from temporalio import activity
+from temporalio.exceptions import ApplicationError
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+
+from products.alerts.backend.temporal.platform_evaluate import (
+ EVALUATION_BUDGET,
+ InsightAlertPlatformEvaluateWorkflow,
+ InsightBatchPlanInputs,
+ InsightCheckInputs,
+)
+from products.alerts_platform.backend.facade.contracts import (
+ RECORD_OUTCOMES_ACTIVITY,
+ AlertBatchKey,
+ AlertEventKind,
+ PlatformAlertOutcome,
+ SourceEvaluationInputs,
+ SourceKind,
+ SourceOutcomeInputs,
+)
+from products.alerts_platform.backend.facade.temporal import source_evaluation_timeout
+
+QUEUE = "test-platform-insight-evaluation"
+ADMITTED = ("00000000-0000-0000-0000-000000000001", "00000000-0000-0000-0000-000000000002")
+
+
+@pytest_asyncio.fixture
+async def environment() -> AsyncIterator[WorkflowEnvironment]:
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ yield env
+
+
+async def test_a_check_that_fails_does_not_stop_the_batch_recording_the_rest(environment: WorkflowEnvironment) -> None:
+ recorded: list[SourceOutcomeInputs] = []
+
+ @activity.defn(name="plan_platform_insight_batch_activity")
+ async def plan(inputs: InsightBatchPlanInputs) -> list[str]:
+ return list(ADMITTED)
+
+ @activity.defn(name="evaluate_platform_insight_check_activity")
+ async def evaluate(inputs: InsightCheckInputs) -> PlatformAlertOutcome | None:
+ if inputs.configuration_id == ADMITTED[0]:
+ raise ApplicationError("query failed", non_retryable=True)
+ return 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,
+ consecutive_failures=0,
+ )
+
+ @activity.defn(name=RECORD_OUTCOMES_ACTIVITY)
+ async def record(inputs: SourceOutcomeInputs) -> int:
+ recorded.append(inputs)
+ return len(inputs.outcomes)
+
+ async with Worker(
+ environment.client,
+ task_queue=QUEUE,
+ workflows=[InsightAlertPlatformEvaluateWorkflow],
+ activities=[plan, evaluate, record],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ result = await environment.client.execute_workflow(
+ InsightAlertPlatformEvaluateWorkflow.run,
+ SourceEvaluationInputs(
+ source=SourceKind.INSIGHT,
+ cutoff="2026-09-16T10:00:00+00:00",
+ batch_key=AlertBatchKey(team_id=1, slot="2026-09-16T10:00:00+00:00"),
+ ),
+ id=f"test-{uuid.uuid4()}",
+ task_queue=QUEUE,
+ )
+
+ assert result == 1
+ assert [[str(o.configuration_id) for o in batch.outcomes] for batch in recorded] == [[ADMITTED[1]]]
+
+
+def test_the_binding_holds_the_whole_batch() -> None:
+ assert source_evaluation_timeout(SourceKind.INSIGHT) > EVALUATION_BUDGET
diff --git a/products/alerts/backend/test/test_platform_source_cycle.py b/products/alerts/backend/test/test_platform_source_cycle.py
new file mode 100644
index 000000000000..203d7fa12ca3
--- /dev/null
+++ b/products/alerts/backend/test/test_platform_source_cycle.py
@@ -0,0 +1,184 @@
+import time
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from django.test import override_settings
+
+from parameterized import parameterized
+
+from posthog.schema import ChartDisplayType, EventsNode, IntervalType, TrendsFilter, TrendsQuery
+
+from posthog.clickhouse.client.connection import ClickHouseUser
+from posthog.clickhouse.query_tagging import get_query_tags
+from posthog.exceptions import ClickHouseAtCapacity, ClickHouseClusterMemoryLimitExceeded
+from posthog.models.scoping import team_scope
+from posthog.redis import get_client
+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.models.alert import AlertCheck, AlertConfiguration, Threshold
+from products.alerts.backend.platform_source_cycle import (
+ CAPACITY_REJECTED,
+ INFLIGHT_KEY,
+ evaluate_insight_check,
+ plan_insight_batch,
+)
+from products.alerts_platform.backend.facade import testing as platform_testing
+from products.alerts_platform.backend.facade.api import record_outcomes, slot_of
+from products.alerts_platform.backend.facade.contracts import (
+ AlertEventKind,
+ PlatformAlertOutcome,
+ PlatformConfigurationSnapshot,
+ SourceKind,
+)
+from products.product_analytics.backend.facade.models import Insight
+
+_MODULE = "products.alerts.backend.platform_source_cycle"
+# A Wednesday, so no weekend rule applies.
+CUTOFF = datetime(2026, 9, 16, 10, tzinfo=UTC)
+
+
+class TestPlatformInsightEvaluation(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ get_client().delete(INFLIGHT_KEY)
+ self.addCleanup(get_client().delete, INFLIGHT_KEY)
+
+ def _alert(self, **overrides: Any) -> AlertConfiguration:
+ insight = Insight.objects.create(
+ team=self.team,
+ name="insight",
+ query=TrendsQuery(
+ series=[EventsNode(event="$pageview")],
+ interval=IntervalType.DAY,
+ trendsFilter=TrendsFilter(display=ChartDisplayType.BOLD_NUMBER),
+ ).model_dump(),
+ )
+ threshold = Threshold.objects.create(
+ team=self.team, insight=insight, configuration={"type": "absolute", "bounds": {"upper": 100.0}}
+ )
+ fields: dict[str, Any] = {
+ "team": self.team,
+ "insight": insight,
+ "name": "alert",
+ "calculation_interval": AlertCalculationInterval.DAILY.value,
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "condition": {"type": "absolute_value"},
+ "threshold": threshold,
+ "next_check_at": CUTOFF - timedelta(minutes=1),
+ }
+ fields.update(overrides)
+ return AlertConfiguration.objects.create(**fields)
+
+ def _copy(self, alert: AlertConfiguration | None) -> PlatformConfigurationSnapshot:
+ with team_scope(self.team.id):
+ return platform_testing.create_configuration(
+ team_id=self.team.id,
+ name="alert",
+ source_kind=SourceKind.INSIGHT,
+ source_config={},
+ check_interval_minutes=60 * 24,
+ recurrence_unit="day",
+ next_check_at=CUTOFF - timedelta(minutes=1),
+ legacy_configuration_id=alert.id if alert else None,
+ )
+
+ def _evaluate(
+ self, configuration: PlatformConfigurationSnapshot, *, result: Any = None
+ ) -> tuple[PlatformAlertOutcome | None, MagicMock]:
+ slot = slot_of(configuration.next_check_at, CUTOFF)
+ expires_at = time.time() + 3600
+ assert plan_insight_batch(self.team.id, slot, CUTOFF, expires_at=expires_at) == (str(configuration.id),)
+ 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(
+ self.team.id, slot, CUTOFF, str(configuration.id), held_until=expires_at, evaluation_id="test"
+ )
+ return outcome, query
+
+ def test_a_breach_fires_on_the_platform_and_leaves_the_production_alert_alone(self) -> None:
+ alert = self._alert()
+ before = AlertConfiguration.objects.values("state", "next_check_at", "last_checked_at").get(id=alert.id)
+ configuration = self._copy(alert)
+
+ outcome, _ = self._evaluate(configuration, result=AlertEvaluationResult(value=150.0, breaches=["above 100"]))
+ assert outcome is not None
+ assert get_query_tags().ch_user == ClickHouseUser.ALERTS_PLATFORM_INSIGHT
+ record_outcomes(self.team.id, (outcome,), CUTOFF)
+
+ assert (outcome.kind, outcome.value, outcome.evaluation_key) == (
+ AlertEventKind.FIRING,
+ 150.0,
+ f"slot:{slot_of(configuration.next_check_at, CUTOFF)}",
+ )
+ with team_scope(self.team.id):
+ platform_alert = platform_testing.alert_for(configuration.id)
+ assert platform_alert is not None and platform_alert.state == "firing"
+ 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(
+ [
+ ("real_time", {"calculation_interval": AlertCalculationInterval.REAL_TIME.value}, "not_firing"),
+ ("detector", {"detector_config": {"type": "zscore"}}, "not_firing"),
+ ("disabled", {"enabled": False}, "not_firing"),
+ ("snoozed", {"snoozed_until": CUTOFF + timedelta(hours=1)}, "snoozed"),
+ ]
+ )
+ def test_a_check_production_would_not_run_is_recorded_without_a_query(
+ self, _name: str, overrides: dict[str, Any], state: str
+ ) -> None:
+ outcome, query = self._evaluate(self._copy(self._alert(**overrides)))
+
+ query.assert_not_called()
+ assert outcome is not None
+ assert (outcome.kind, outcome.new_state, outcome.disable) == (AlertEventKind.CHECK, state, False)
+
+ def test_a_copy_whose_production_alert_is_gone_is_disabled(self) -> None:
+ outcome, query = self._evaluate(self._copy(None))
+
+ query.assert_not_called()
+ assert outcome is not None and outcome.disable
+
+ @parameterized.expand(
+ [
+ ("too_many_queries", ClickHouseAtCapacity()),
+ ("cluster_memory_full", ClickHouseClusterMemoryLimitExceeded()),
+ ]
+ )
+ def test_a_check_clickhouse_refuses_for_load_leaves_the_alert_as_it_was(self, _name: str, error: Exception) -> None:
+ outcome, _ = self._evaluate(self._copy(self._alert()), result=error)
+
+ assert outcome is not None
+ assert (outcome.kind, outcome.new_state, outcome.error_message, outcome.disable) == (
+ AlertEventKind.CHECK,
+ "not_firing",
+ CAPACITY_REJECTED,
+ False,
+ )
+
+ def test_an_alert_production_cannot_evaluate_as_configured_errors_and_is_disabled(self) -> None:
+ outcome, _ = self._evaluate(self._copy(self._alert()), result=AlertExtractionError("bad query shape"))
+
+ assert outcome is not None
+ assert (outcome.kind, outcome.new_state, outcome.disable) == (AlertEventKind.ERRORED, "errored", True)
+
+ @override_settings(ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS=1)
+ def test_the_pool_defers_what_it_cannot_hold_until_a_check_frees_its_slot(self) -> None:
+ first, second = self._copy(self._alert()), self._copy(self._alert())
+ slot = slot_of(first.next_check_at, CUTOFF)
+ expires_at = time.time() + 3600
+
+ (admitted,) = plan_insight_batch(self.team.id, slot, CUTOFF, expires_at=expires_at)
+ assert plan_insight_batch(self.team.id, slot, CUTOFF, expires_at=expires_at + 60) == ()
+
+ with patch(f"{_MODULE}.check_alert_for_insight", return_value=AlertEvaluationResult(value=1.0, breaches=[])):
+ evaluate_insight_check(self.team.id, slot, CUTOFF, admitted, held_until=expires_at, evaluation_id="test")
+
+ assert len(plan_insight_batch(self.team.id, slot, CUTOFF, expires_at=expires_at + 60)) == 1
+ assert {str(first.id), str(second.id)} >= {admitted}
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.py
index 82500d9bca33..ab1fb0acabfc 100644
--- a/products/alerts_platform/backend/facade/api.py
+++ b/products/alerts_platform/backend/facade/api.py
@@ -7,7 +7,7 @@ so every write and every scheduling rule has one home.
from __future__ import annotations
-from collections.abc import Sequence
+from collections.abc import Collection, Sequence
from datetime import datetime
from uuid import UUID
@@ -21,9 +21,11 @@ from products.alerts_platform.backend.facade.contracts import (
from products.alerts_platform.backend.logic import platform_lifecycle, platform_reads
-def due_checks(team_id: int, source_kind: str, slot: str, cutoff: datetime) -> tuple[PlatformAlertCheckInput, ...]:
- """Every check one batch key owes, flattened as a source reads them."""
- return platform_lifecycle.due_checks(team_id, source_kind, slot, cutoff)
+def due_checks(
+ team_id: int, source_kind: str, slot: str, cutoff: datetime, *, configuration_ids: Collection[str] | None = None
+) -> tuple[PlatformAlertCheckInput, ...]:
+ """Every check one batch key owes, flattened as a source reads them, or only the named ones."""
+ return platform_lifecycle.due_checks(team_id, source_kind, slot, cutoff, configuration_ids=configuration_ids)
def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now: datetime) -> int:
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index 88e540ce3d7c..a35105b185bd 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -166,6 +166,12 @@ class SkipReason(StrEnum):
BROKEN_CONFIG = "broken_config"
QUERY_FAILED = "query_failed"
+ # The source's own stack runs no query for this check, so the source does not either: a
+ # snooze or a schedule restriction where that stack gates evaluation, or data not ready yet.
+ SOURCE_RULE = "source_rule"
+ # ClickHouse refused the query for load, not because of the alert. The check leaves the alert's
+ # state alone, so a comparison can set it aside instead of reading load as a disagreement.
+ CAPACITY = "capacity"
class MuteReason(StrEnum):
diff --git a/products/alerts_platform/backend/facade/lifecycle.py b/products/alerts_platform/backend/facade/lifecycle.py
index a2eb423972dd..c44ccae18d8f 100644
--- a/products/alerts_platform/backend/facade/lifecycle.py
+++ b/products/alerts_platform/backend/facade/lifecycle.py
@@ -25,7 +25,7 @@ from datetime import datetime, timedelta
from enum import Enum, StrEnum
from typing import Protocol
-from products.alerts_platform.backend.facade.contracts import FiringEpisode, IncidentAction
+from products.alerts_platform.backend.facade.contracts import AlertEventKind, FiringEpisode, IncidentAction
MAX_CONSECUTIVE_FAILURES = 5
@@ -48,6 +48,18 @@ class NotificationAction(Enum):
BROKEN = "broken"
+# What a source reports as a check's kind. A check that announced nothing is a CHECK even when it
+# moved the alert; the row's two states carry the move. `AlertEventKind`'s other four values are
+# the `EventKind` strings the logs destination config is keyed on.
+NOTIFICATION_EVENT_KINDS: dict[NotificationAction, AlertEventKind] = {
+ NotificationAction.NONE: AlertEventKind.CHECK,
+ NotificationAction.FIRE: AlertEventKind.FIRING,
+ NotificationAction.RESOLVE: AlertEventKind.RESOLVED,
+ NotificationAction.ERROR: AlertEventKind.ERRORED,
+ NotificationAction.BROKEN: AlertEventKind.BROKEN,
+}
+
+
class InvalidTransition(Exception):
"""Raised by control-plane transitions when the pre-condition isn't met."""
diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.py
index d70bd3c739ec..5d7df371556f 100644
--- a/products/alerts_platform/backend/logic/platform_lifecycle.py
+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py
@@ -4,7 +4,7 @@ A source decides whether its data breached; everything about what that means for
and every write to these rows, stays here. A source never holds one of these models.
"""
-from collections.abc import Sequence
+from collections.abc import Collection, Sequence
from datetime import datetime
from django.db import transaction
@@ -89,16 +89,24 @@ def suppressed() -> Exists:
)
-def due_checks(team_id: int, source_kind: str, slot: str, cutoff: datetime) -> tuple[PlatformAlertCheckInput, ...]:
- """Every configuration in one batch key, with its runtime state, ready to evaluate."""
- configurations = list(
+def due_checks(
+ team_id: int, source_kind: str, slot: str, cutoff: datetime, *, configuration_ids: Collection[str] | None = None
+) -> tuple[PlatformAlertCheckInput, ...]:
+ """Every configuration in one batch key, with its runtime state, ready to evaluate.
+
+ `configuration_ids` narrows the batch to those rows, for a source that evaluates one check at
+ a time and must still read nothing the batch would not.
+ """
+ due = (
PlatformAlertConfiguration.objects.for_team(team_id)
.filter(enabled=True, source_kind=source_kind)
.filter(due_q(cutoff))
.exclude(suppressed())
- # Ordered so a retried attempt keeps the same alerts under any downstream cap.
- .order_by("id")
)
+ if configuration_ids is not None:
+ due = due.filter(id__in=list(configuration_ids))
+ # Ordered so a retried attempt keeps the same alerts under any downstream cap.
+ configurations = list(due.order_by("id"))
configurations = [c for c in configurations if slot_of(c.next_check_at, cutoff) == slot]
if not configurations:
return ()
diff --git a/products/alerts_platform/backend/temporal/sources.py b/products/alerts_platform/backend/temporal/sources.py
index b7dd4c7afbad..b88ed46da570 100644
--- a/products/alerts_platform/backend/temporal/sources.py
+++ b/products/alerts_platform/backend/temporal/sources.py
@@ -20,8 +20,10 @@ from products.alerts_platform.backend.logic.demand import DISCOVERY_LIMIT_PER_SO
class SourceBinding:
workflow: str
# The evaluation workflow runs here, and so does every activity it starts without naming a
- # queue. A source with slow checks gets its own queue, so it cannot hold the worker slots that
- # another source's checks need.
+ # queue. Sources share the evaluation queue while their checks finish in seconds. A source
+ # whose checks hold a worker slot for minutes, such as one that calls a model per check,
+ # needs a queue of its own so that it cannot take the slots another source needs. That queue
+ # must also register the record-outcomes activity.
task_queue: str
# What an evaluation gets end to end: its reads, its write, and the delivery children it
# starts. It has to hold every attempt a source's activities allow, because an attempt cut
@@ -46,6 +48,14 @@ SOURCE_BINDINGS: dict[SourceKind, SourceBinding] = {
evaluation_timeout=dt.timedelta(seconds=75),
discovery_limit=DISCOVERY_LIMIT_PER_SOURCE,
),
+ SourceKind.INSIGHT: SourceBinding(
+ workflow="insight-alert-platform-evaluate",
+ task_queue=settings.ALERTS_PLATFORM_EVALUATION_TASK_QUEUE,
+ evaluation_timeout=dt.timedelta(minutes=15),
+ # A key holds at least one check and the pool admits this many, so more keys than this
+ # only start workflows that find the pool full.
+ discovery_limit=settings.ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS,
+ ),
}
diff --git a/products/alerts_platform/backend/temporal/telemetry.py b/products/alerts_platform/backend/temporal/telemetry.py
index 09ed5cda6926..b11e4d4ce415 100644
--- a/products/alerts_platform/backend/temporal/telemetry.py
+++ b/products/alerts_platform/backend/temporal/telemetry.py
@@ -9,6 +9,8 @@ from temporalio.worker import ActivityInboundInterceptor, ExecuteActivityInput,
from posthog.temporal.common.logger import get_write_only_logger
+from products.alerts_platform.backend.temporal.sources import SOURCE_BINDINGS
+
LOGGER = get_write_only_logger(__name__)
@@ -45,7 +47,17 @@ async def _log_activity_event(
class AlertsPlatformTelemetryInterceptor(Interceptor):
- task_queue = (settings.ALERTS_PLATFORM_EVALUATION_TASK_QUEUE, settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE)
+ # Every queue a source binding names, so a source on a queue of its own is covered with no
+ # second list to keep in step.
+ task_queue = tuple(
+ sorted(
+ {
+ settings.ALERTS_PLATFORM_EVALUATION_TASK_QUEUE,
+ settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE,
+ *(binding.task_queue for binding in SOURCE_BINDINGS.values()),
+ }
+ )
+ )
def intercept_activity(self, next: ActivityInboundInterceptor) -> ActivityInboundInterceptor:
return _AlertsPlatformActivityInterceptor(next)
diff --git a/products/alerts_platform/backend/tests/test_temporal_workflows.py b/products/alerts_platform/backend/tests/test_temporal_workflows.py
index 163cfef74dd0..e57b329b9dc4 100644
--- a/products/alerts_platform/backend/tests/test_temporal_workflows.py
+++ b/products/alerts_platform/backend/tests/test_temporal_workflows.py
@@ -634,8 +634,11 @@ def test_every_source_evaluation_binding_names_a_workflow_registered_on_its_queu
import temporalio.workflow # noqa: PLC0415 — read after the registry
# The registry imports every product's workflows, so it stays off this module's import path.
- from posthog.management.commands.start_temporal_worker import WORKFLOWS_DICT # noqa: PLC0415
+ from posthog.management.commands.start_temporal_worker import ACTIVITIES_DICT, WORKFLOWS_DICT # noqa: PLC0415
+ from products.alerts_platform.backend.temporal.outcomes import ( # noqa: PLC0415 — read after the registry
+ alerts_platform_record_outcomes_activity,
+ )
from products.alerts_platform.backend.temporal.sources import ( # noqa: PLC0415 — read after the registry
SOURCE_BINDINGS,
)
@@ -645,10 +648,12 @@ def test_every_source_evaluation_binding_names_a_workflow_registered_on_its_queu
return {definition.name for definition in definitions if definition is not None}
# A binding naming a workflow its queue's worker does not register leaves every dispatch for
- # that source queued until it times out.
+ # that source queued until it times out. The source's workflow records its outcomes on the
+ # same queue, so a queue without that activity evaluates every check and records none.
unregistered = {
- source: binding.workflow
+ source: binding.task_queue
for source, binding in SOURCE_BINDINGS.items()
if binding.workflow not in registered_on(binding.task_queue)
+ or alerts_platform_record_outcomes_activity not in ACTIVITIES_DICT[binding.task_queue]
}
assert unregistered == {}
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.py
index 531ef11bc3e2..a8fcb150b426 100644
--- a/products/logs/backend/alert_source_cycle.py
+++ b/products/logs/backend/alert_source_cycle.py
@@ -40,6 +40,7 @@ from products.alerts_platform.backend.facade.contracts import (
SourceKind,
)
from products.alerts_platform.backend.facade.lifecycle import (
+ NOTIFICATION_EVENT_KINDS,
PLATFORM_LOGS_ALERT_POLICY,
AlertCheckOutcome,
AlertSnapshot,
@@ -102,17 +103,6 @@ MAX_QUERY_SECONDS = 20
# Below this there is no point starting another query; the cohort keeps its due time instead.
MIN_QUERY_SECONDS = 2
-# A check that announced nothing is a CHECK even when it moved the alert; the row's two states
-# carry the move. `AlertEventKind`'s other four values are the `EventKind` strings the destination
-# config is keyed on, so this is also the only table mapping an action to a destination.
-_NOTIFICATION_OUTCOME_KINDS: dict[NotificationAction, AlertEventKind] = {
- NotificationAction.NONE: AlertEventKind.CHECK,
- NotificationAction.FIRE: AlertEventKind.FIRING,
- NotificationAction.RESOLVE: AlertEventKind.RESOLVED,
- NotificationAction.ERROR: AlertEventKind.ERRORED,
- NotificationAction.BROKEN: AlertEventKind.BROKEN,
-}
-
@frozen
class LogsAlertCondition:
@@ -352,7 +342,7 @@ def _delivery(
check,
outcome=outcome,
evaluation_key=_evaluation_key(check, window_end),
- kind=_NOTIFICATION_OUTCOME_KINDS[outcome.notification],
+ kind=NOTIFICATION_EVENT_KINDS[outcome.notification],
notified=outcome.update_last_notified_at,
now=now,
value=value,