: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): bound concurrent alert evaluations (#104225)
Sandy Spicer65a00e22c1fb
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex f2d780228c7a..50f337d51fa1 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -1,5 +1,7 @@import os+from django.core.exceptions import ImproperlyConfigured+from posthog.settings.access import SECRET_KEYfrom posthog.settings.base_variables import CLOUD_DEPLOYMENT, DEBUGfrom posthog.settings.utils import get_from_env, get_list, str_to_bool@@ -277,6 +279,12 @@ ANALYTICS_PLATFORM_TASK_QUEUE = _set_temporal_task_queue("analytics-platform-tasALERTS_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"+# 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:+ raise ImproperlyConfigured(+ "ALERTS_MAX_INFLIGHT_EVALUATIONS must be a positive integer, or no alert check ever starts"+ )SESSION_REPLAY_TASK_QUEUE = _set_temporal_task_queue("session-replay-task-queue")REPLAY_VISION_TASK_QUEUE = _set_temporal_task_queue("replay-vision-task-queue")# The XGBoost-based session surfacing scoring sweep runs on the session-replaydiff --git a/posthog/temporal/alerts/__init__.py b/posthog/temporal/alerts/__init__.pyindex b33fe60d85ce..bd1e14959451 100644--- a/posthog/temporal/alerts/__init__.py+++ b/posthog/temporal/alerts/__init__.py@@ -1,9 +1,11 @@from posthog.temporal.alerts.activities import (+ admit_alert_evaluations,cleanup_alert_checks,evaluate_alert,notify_alert,prepare_alert,record_failed_evaluation,+ release_alert_evaluation_slots,retrieve_due_alerts,run_investigation_safety_net,)@@ -27,6 +29,8 @@ AI_QUEUE_ACTIVITIES = [evaluate_alert]ACTIVITIES = [retrieve_due_alerts,+ admit_alert_evaluations,+ release_alert_evaluation_slots,prepare_alert,evaluate_alert,notify_alert,diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.pyindex 132b7f88ed98..38b5b4510b12 100644--- a/posthog/temporal/alerts/activities.py+++ b/posthog/temporal/alerts/activities.py@@ -1,9 +1,16 @@import json+import timeimport asyncioimport hashlib+import threadingimport traceback+import contextlib+import contextvars+from collections.abc import AsyncIterator, Awaitable, Callablefrom concurrent.futures import ThreadPoolExecutorfrom datetime import UTC, datetime+from functools import partial+from typing import ParamSpec, TypeVarfrom django.core.serializers.json import DjangoJSONEncoderfrom django.db import transaction@@ -12,16 +19,18 @@ from django.db.models.functions import Coalesce, RowNumberimport structlogimport temporalio.activity+from temporalio.common import RetryPolicyfrom temporalio.exceptions import ApplicationErrorfrom posthog.schema import AlertStatefrom posthog.hogql.errors import TableAccessDeniedError+from posthog.clickhouse.cancel import cancel_query_on_clusterfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.dataclasses import frozenfrom posthog.email import is_email_available-from posthog.errors import CH_TRANSIENT_ERRORS+from posthog.errors import CH_TRANSIENT_ERRORS, CHQueryErrorQueryWasCancelledfrom posthog.exceptions_capture import capture_exceptionfrom posthog.query_creator_access import creator_access_revoked, report_creator_access_revokedfrom posthog.schema_migrations.upgrade_manager import upgrade_insight@@ -40,9 +49,21 @@ from posthog.tasks.alerts.utils import (record_alert_delivery,skip_because_of_weekend,)+from posthog.temporal.alerts.admission import (+ admit_evaluation_slots,+ hold_evaluation_slot,+ inflight_alert_ids,+ max_inflight_evaluations,+ refresh_evaluation_slot,+ release_evaluation_slot,+ release_evaluation_slots,+)from posthog.temporal.alerts.investigation import claim_investigation_slot, decide_investigationfrom posthog.temporal.alerts.metrics import record_ai_detector_check_outcome, record_due_insight_alert_metrics+from posthog.temporal.alerts.retry_policy import ALERT_PREPARE_RETRY_POLICY, SlotLease, alert_timeoutsfrom posthog.temporal.alerts.types import (+ AdmitEvaluationsInputs,+ AdmittedEvaluations,AlertInfo,EvaluateAlertActivityInputs,EvaluateAlertResult,@@ -52,6 +73,7 @@ from posthog.temporal.alerts.types import (PrepareAlertResult,RecordFailedEvaluationActivityInputs,RecordFailedEvaluationResult,+ ReleaseEvaluationSlotsInputs,ScheduleDueAlertChecksWorkflowInputs,SkipReason,)@@ -84,6 +106,21 @@ from products.product_analytics.backend.facade.api import lock_insight_for_evalulogger = structlog.get_logger(__name__)+_T = TypeVar("_T")+_P = ParamSpec("_P")++# Slow evaluations must not occupy the threads that renew their leases or cancel their queries.+_ADMISSION_EXECUTOR = ThreadPoolExecutor(max_workers=4, thread_name_prefix="insight-alert-admission")+_CANCELLATION_EXECUTOR = ThreadPoolExecutor(max_workers=10, thread_name_prefix="insight-alert-cancel")+++async def _run_control(+ executor: ThreadPoolExecutor, function: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs+) -> _T:+ context = contextvars.copy_context()+ return await asyncio.get_running_loop().run_in_executor(executor, partial(context.run, function, *args, **kwargs))++_NOTIFICATION_DELIVERY_EXECUTOR = ThreadPoolExecutor(max_workers=10, thread_name_prefix="insight-alert-delivery")# AI-detector checks hold a thread for the model call, up to a minute each. On the shared@@ -101,6 +138,7 @@ class _RetrievedAlerts:due_count: intoldest_due_at: datetime | Nonepolled_at: datetime+ in_flight_count: int@temporalio.activity.defn@@ -128,8 +166,11 @@ async def retrieve_due_alerts(inputs: ScheduleDueAlertChecksWorkflowInputs | Non.filter(Q(snoozed_until__isnull=True) | Q(snoozed_until__lt=polled_at)).filter(insight__deleted=False))+ # A check stays due until it finishes, so admitted alerts would otherwise be handed out again.+ in_flight = inflight_alert_ids()+ selectable_query = due_alerts_query.exclude(id__in=in_flight) if in_flight else due_alerts_queryalerts_query = (- due_alerts_query.annotate(_interval_order=calculation_interval_order)+ selectable_query.annotate(_interval_order=calculation_interval_order).annotate(_team_rank=Window(expression=RowNumber(),@@ -170,6 +211,7 @@ async def retrieve_due_alerts(inputs: ScheduleDueAlertChecksWorkflowInputs | Nondue_count=due_alert_metrics["due_count"],oldest_due_at=due_alert_metrics["oldest_due_at"],polled_at=polled_at,+ in_flight_count=len(in_flight),)retrieved = await get_alerts()@@ -193,11 +235,37 @@ async def retrieve_due_alerts(inputs: ScheduleDueAlertChecksWorkflowInputs | Non"insight_alert_scheduler_alerts_selected","Due alerts selected across successful alert scheduler retrieval runs",).add(len(retrieved.alerts))+ meter.create_gauge("insight_alert_evaluations_inflight", "Alert checks holding an evaluation slot").set(+ retrieved.in_flight_count+ )except Exception:logger.exception("Failed to record alert scheduler capacity metrics")return retrieved.alerts+async def admit_alert_evaluations(inputs: AdmitEvaluationsInputs) -> AdmittedEvaluations:+ admitted = await _run_control(+ _ADMISSION_EXECUTOR,+ admit_evaluation_slots,+ inputs.alert_ids,+ limit=max_inflight_evaluations(),+ expires_at=inputs.expires_at,+ )+ try:+ get_metric_meter().create_counter(+ "insight_alert_evaluations_admitted", "Alert checks admitted to an evaluation slot"+ ).add(len(admitted))+ except Exception:+ logger.exception("Failed to record alert admission metrics")+ return AdmittedEvaluations(alert_ids=admitted)+++async def release_alert_evaluation_slots(inputs: ReleaseEvaluationSlotsInputs) -> None:+ await _run_control(_ADMISSION_EXECUTOR, release_evaluation_slots, inputs.alert_ids, held_until=inputs.held_until)++def _has_active_destinations(alert: AlertConfiguration) -> bool:return (count_active_alert_destinations(@@ -209,6 +277,204 @@ def _has_active_destinations(alert: AlertConfiguration) -> bool:)+# How often a waiting attempt looks again: for a free slot before it runs its query, or for its+# thread to exit after the query was killed.+_SLOT_POLL_SECONDS = 5.0++_SLOT_LOST_ERROR_TYPE = "EvaluationSlotLost"+++class _EvaluationStopped(Exception):+ """Raised in the evaluation thread once its attempt's cancellation began, so it records nothing."""+++async def _hold_evaluation_slot_before_running(alert_id: str, *, lease_seconds: float) -> float:+ """Hold the slot for evaluate_alert, waiting while there is no room or Redis is unreachable.++ An id that lapsed from the set is no longer admitted, and running its query anyway would put it+ over the limit, so it waits for room until its budget cancels it. Redis being unreachable waits+ too instead of failing the check, because an outage shorter than the budget then costs nothing.+ """+ waited_since: float | None = None+ while True:+ try:+ held_until = await _run_control(+ _ADMISSION_EXECUTOR,+ hold_evaluation_slot,+ alert_id,+ limit=max_inflight_evaluations(),+ lease_seconds=lease_seconds,+ )+ except Exception:+ if waited_since is None:+ logger.exception("alerts.admission.hold_failed", alert_id=alert_id)+ held_until = None+ if held_until is not None:+ if waited_since is not None:+ logger.info("alerts.admission.slot_waited", alert_id=alert_id, seconds=time.time() - waited_since)+ return held_until+ if waited_since is None:+ waited_since = time.time()+ await asyncio.sleep(_SLOT_POLL_SECONDS)+++def _attempt_will_retry(error: Exception, retry_policy: RetryPolicy) -> bool:+ if isinstance(error, ApplicationError):+ if error.non_retryable:+ return False+ error_type = error.type+ else:+ error_type = type(error).__name__+ if error_type in (retry_policy.non_retryable_error_types or ()):+ return False+ return not retry_policy.maximum_attempts or temporalio.activity.info().attempt < retry_policy.maximum_attempts+++class _SlotHolder:+ """The evaluation slot one attempt holds, identified by the expiry it last wrote."""++ def __init__(self, alert_id: str, held_until: float | None) -> None:+ self.alert_id = alert_id+ self.held_until = held_until+ self.lost = False+ self._stop = asyncio.Event()+ self._refresher: asyncio.Task[None] | None = None++ @contextlib.asynccontextmanager+ async def refreshing(self, lease: SlotLease | None, *, on_lost: Callable[[], object]) -> AsyncIterator[None]:+ """Re-hold the slot under the lease while the body runs, and call on_lost once it cannot be kept.++ The lease makes a slot lapse soon after its worker dies. The same lapse would let the+ scheduler reuse the slot of a live attempt that cannot reach Redis, so that attempt is+ stopped first, while it is still counted.+ """+ if lease is None or self.held_until is None:+ yield+ return+ self._refresher = asyncio.create_task(self._refresh_until(lease, on_lost))+ try:+ yield+ finally:+ await self._stop_refreshing()++ async def _stop_refreshing(self) -> None:+ # Wait for the refresher rather than cancel it, so a refresh in flight cannot write a new+ # expiry after a release has checked the old one.+ if self._refresher is None:+ return+ self._stop.set()+ await self._refresher+ self._refresher = None++ async def _refresh_until(self, lease: SlotLease, on_lost: Callable[[], object]) -> None:+ refresh_seconds = lease.refresh.total_seconds()+ while (held_until := self.held_until) is not None:+ try:+ await asyncio.wait_for(self._stop.wait(), timeout=refresh_seconds)+ return+ except TimeoutError:+ pass+ expires_at = time.time() + lease.lease.total_seconds()+ try:+ owned = await _run_control(+ _ADMISSION_EXECUTOR,+ refresh_evaluation_slot,+ self.alert_id,+ held_until=held_until,+ expires_at=expires_at,+ )+ except Exception:+ logger.exception("alerts.admission.refresh_failed", alert_id=self.alert_id)+ # Stop with a refresh interval to spare, so the query is dead before the slot lapses+ # and the kill that stops it has time to land.+ if time.time() + refresh_seconds < held_until - refresh_seconds:+ continue+ self.lost = True+ on_lost()+ return+ if not owned:+ # Another attempt took the slot over, or it lapsed while Redis was unreachable.+ # Either way this attempt is no longer admitted and has nothing left to release.+ self.held_until = None+ self.lost = True+ on_lost()+ return+ self.held_until = expires_at++ async def release(self) -> None:+ await self._stop_refreshing()+ if self.held_until is not None:+ await _run_control(_ADMISSION_EXECUTOR, release_evaluation_slot, self.alert_id, held_until=self.held_until)+++async def _finish(cleanup: Awaitable[_T]) -> _T:+ """Await cleanup even if this task is cancelled again while it runs.++ Once the server has timed an attempt out it may cancel the task once more for each heartbeat it+ no longer recognises, and a cleanup cut short would leave a running query nobody stops.+ """+ task = asyncio.ensure_future(cleanup)+ while not task.done():+ try:+ await asyncio.shield(task)+ except asyncio.CancelledError:+ pass+ return task.result()+++async def _run_holding_slot(+ alert_id: str,+ held_until: float | None,+ run: Callable[[], Awaitable[_T]],+ *,+ retry_policy: RetryPolicy,+ keeps_slot: Callable[[_T], bool],+ lease: SlotLease | None = None,+ stop_work: Callable[[], Awaitable[bool]] | None = None,+) -> _T:+ """Run one attempt of a check while it holds its evaluation slot.++ With a lease the slot is re-held for as long as the attempt runs, so a worker that dies frees it+ soon after. Without one it stays until the scheduler's expiry, which suits prepare_alert: its+ attempts run without a heartbeat timeout, so a slow one cannot be presumed dead.++ The slot is released when the attempt finishes for good: a result keeps_slot rejects, a failure+ Temporal will not retry, or a cancellation. A retryable failure keeps it, because releasing+ during the backoff lets the scheduler admit past the limit under the very overload that causes+ the retries; the next attempt's hold takes the slot over.++ An attempt stops early when Temporal cancels it or when the slot can no longer be held, and+ runs stop_work to completion before it gives the slot back. When Redis is unreachable it stops+ a refresh interval before the slot lapses, so its work ends while it is still counted. When a+ retried attempt takes the slot over, the old attempt learns it only on its next refresh, so the+ two overlap under one slot for up to one refresh interval. Work that stop_work could not stop+ keeps the slot, which lapses on its own once nothing refreshes it. A lost slot fails the+ attempt with a retryable error, and a retry waits for a slot of its own.+ """+ holder = _SlotHolder(alert_id, held_until)+ body = asyncio.ensure_future(run())+ async with holder.refreshing(lease, on_lost=body.cancel), Heartbeater():+ try:+ result = await body+ except asyncio.CancelledError:+ body.cancel()+ stopped = True+ if stop_work is not None:+ stopped = await _finish(stop_work())+ if stopped:+ await _finish(holder.release())+ if holder.lost and not temporalio.activity.is_cancelled():+ raise ApplicationError("The evaluation lost its admission slot", type=_SLOT_LOST_ERROR_TYPE)+ raise+ except Exception as error:+ if not _attempt_will_retry(error, retry_policy):+ await holder.release()+ raise+ if not keeps_slot(result):+ await holder.release()+ return result++@temporalio.activity.defnasync def prepare_alert(inputs: PrepareAlertActivityInputs) -> PrepareAlertResult:"""Load the alert, validate its config, and decide whether to evaluate."""@@ -313,8 +579,24 @@ async def prepare_alert(inputs: PrepareAlertActivityInputs) -> PrepareAlertResulevaluation_fingerprint=evaluation_fingerprint,)- async with Heartbeater():- return await _prepare()+ # The scheduler's reservation names no owner, and prepare_alert runs without a heartbeat timeout,+ # so a timed-out attempt that finishes late would otherwise remove the lease a retried attempt holds.+ # No room means the reservation lapsed and the set filled up; prepare runs no query, so it goes+ # on without a slot and evaluate_alert waits for one.+ try:+ held_until = await _run_control(+ _ADMISSION_EXECUTOR, hold_evaluation_slot, inputs.alert_id, limit=max_inflight_evaluations()+ )+ except Exception:+ logger.exception("alerts.admission.hold_failed", alert_id=inputs.alert_id)+ held_until = None+ return await _run_holding_slot(+ inputs.alert_id,+ held_until,+ _prepare,+ retry_policy=ALERT_PREPARE_RETRY_POLICY,+ keeps_slot=lambda result: result.action == PrepareAction.EVALUATE,+ )def _failed_evaluation_error(inputs: RecordFailedEvaluationActivityInputs) -> dict:@@ -342,14 +624,30 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe"""Run the insight ClickHouse query, apply the state machine, persist an AlertCheck row."""info = temporalio.activity.info()evaluation_id = f"{info.workflow_run_id}:{info.activity_id}"+ # Keep detector idempotency stable, but prevent cleanup from cancelling a replacement attempt.+ query_id = f"{evaluation_id}:{info.attempt}:"+ # Set once cancellation begins. A kill misses a query that has not started or that finishes+ # between two kills, and a thread abandoned after the kill budget can wake up later, so the+ # thread itself checks this before it queries and before it records. An attempt that a retry+ # replaced learns it only on its next slot refresh, so a query that finishes before then still+ # records.+ stopping = threading.Event()++ def _stop_if_cancelled() -> None:+ if stopping.is_set():+ raise _EvaluationStopped()def _evaluate(alert: AlertConfiguration) -> EvaluateAlertResult:+ _stop_if_cancelled()evaluated_alert = alertevaluated_fingerprint = _evaluation_fingerprint(alert)# CH workload management keys off these tags to isolate alert queries from other tenants.# calculation_interval / config_type also let query_log cost be grouped by alert cadence# (real_time vs every_15_minutes vs ...) and query shape (trends vs HogQL) without a join.+ # client_query_id names every query of this attempt, so a cancelled attempt can kill them.tag_queries(+ team_id=alert.team_id,+ client_query_id=query_id,alert_config_id=str(alert.id),product=Product.PRODUCT_ANALYTICS,feature=Feature.ALERTING,@@ -369,6 +667,10 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRerecord_ai_detector_check_outcome("evaluated")except CH_TRANSIENT_ERRORS:raise+ except CHQueryErrorQueryWasCancelled:+ # A cancelled attempt kills its query and decides what to record; the thread it left+ # behind must not write a check of its own.+ raiseexcept AlertDataUnavailableError as err:error = {"message": str(err)}except LLMDetectorUnavailableError:@@ -426,10 +728,12 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertReshould_start_investigation = Falseshould_gate_notification = Falseshould_run_metrics_investigation = False+ _stop_if_cancelled()with transaction.atomic():current_alert = _lock_evaluation_alert(alert_id=inputs.alert_id, team_id=evaluated_alert.team_id, insight_id=evaluated_alert.insight_id)+ _stop_if_cancelled()if current_alert is None or not _evaluation_inputs_match(evaluated_fingerprint, current_alert):# Leave the current state and due time intact. The next scheduler tick can# evaluate the edited alert; a disabled or deleted alert needs no further work.@@ -484,10 +788,15 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertReinvestigation_user_id=alert.created_by_id if should_start_investigation else None,)- async with Heartbeater():+ team_id = inputs.team_id+ thread: asyncio.Future[EvaluateAlertResult] | None = None++ async def _load_and_evaluate() -> EvaluateAlertResult:+ nonlocal team_id, thread# Route and evaluate the same snapshot. A second read after choosing the executor# could pick up an AI detector and run its model call on the shared pool.alert = await _load_alert_for_evaluation(inputs)+ team_id = alert.team_iduses_llm_detector = is_llm_detector_config(alert.detector_config)if uses_llm_detector != inputs.uses_llm_detector:# The prepare phase picked the task queue from the detector type it read, and only@@ -497,7 +806,56 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRelogger.info("alerts.skip_detector_type_changed", alert_id=inputs.alert_id)return EvaluateAlertResult(alert_check_id=None, should_notify=False, new_state=AlertState(alert.state))executor = _LLM_EVALUATE_EXECUTOR if uses_llm_detector else None- return await database_sync_to_async(_evaluate, thread_sensitive=False, executor=executor)(alert)+ # Shielded, so cancelling the attempt leaves this future to complete when the thread exits,+ # which is what _stop_work waits for.+ thread = asyncio.ensure_future(+ database_sync_to_async(_evaluate, thread_sensitive=False, executor=executor)(alert)+ )+ return await asyncio.shield(thread)++ timeouts = alert_timeouts(inputs.calculation_interval)++ def _log_thread_outcome(finished: asyncio.Future[EvaluateAlertResult]) -> None:+ # Retrieve the error the thread ended on, so asyncio does not log it as never retrieved.+ error = None if finished.cancelled() else finished.exception()+ if error is not None and not isinstance(error, (CHQueryErrorQueryWasCancelled, _EvaluationStopped)):+ logger.warning("alerts.evaluate.stopped_thread_failed", alert_id=inputs.alert_id, exc_info=error)++ async def _stop_work() -> bool:+ # Cancellation cannot reach the thread the query runs in, so the query is killed in+ # ClickHouse by the id it was tagged with. A kill only finds a query that is running at that+ # moment, and the thread may still be waiting for a connection or be between two queries, so+ # it is repeated until the thread has exited on the killed query's error. A thread that+ # outlives a whole evaluation budget after that is stuck on something no kill reaches, such+ # as a node that stopped answering, and is abandoned so the slot it kept lapses instead.+ stopping.set()+ if thread is None or team_id is None:+ return True+ thread.add_done_callback(_log_thread_outcome)+ give_up_at = time.monotonic() + timeouts.activity_schedule_to_close.total_seconds()+ while not thread.done() and time.monotonic() < give_up_at:+ try:+ await _run_control(_CANCELLATION_EXECUTOR, cancel_query_on_cluster, team_id, query_id)+ except Exception:+ logger.exception("alerts.evaluate.cancel_query_failed", alert_id=inputs.alert_id)+ await asyncio.wait({thread}, timeout=_SLOT_POLL_SECONDS)+ if not thread.done():+ logger.error("alerts.evaluate.thread_abandoned", alert_id=inputs.alert_id, evaluation_id=evaluation_id)+ return thread.done()++ async with Heartbeater():+ held_until = await _hold_evaluation_slot_before_running(+ inputs.alert_id, lease_seconds=timeouts.evaluation_slot_lease.lease.total_seconds()+ )+ return await _run_holding_slot(+ inputs.alert_id,+ held_until,+ _load_and_evaluate,+ retry_policy=timeouts.evaluate_retry_policy,+ keeps_slot=lambda _result: False,+ lease=timeouts.evaluation_slot_lease,+ stop_work=_stop_work,+ )def _lock_evaluation_alert(*, alert_id: str, team_id: int, insight_id: int) -> AlertConfiguration | None:diff --git a/posthog/temporal/alerts/admission.py b/posthog/temporal/alerts/admission.pynew file mode 100644index 000000000000..7002f3637d6b--- /dev/null+++ b/posthog/temporal/alerts/admission.py@@ -0,0 +1,152 @@+import time++from django.conf import settings++import structlog++from posthog import redis+from posthog.temporal.alerts.retry_policy import alert_timeouts++logger = structlog.get_logger(__name__)++# Admitted alert ids scored by lease expiry; a check joins when started, not when its query runs.+INFLIGHT_KEY = "alerts:evaluations:inflight"++# A check cannot outlive its workflow's execution timeout, so a lease this long can never lapse+# while the check it belongs to may still reach ClickHouse. A running evaluation re-holds its slot+# under the much shorter evaluation_slot_lease, so a worker that dies frees it soon after.+SLOT_LEASE_SECONDS = int(alert_timeouts(None).workflow_execution.total_seconds())++_BOOKKEEPING_ATTEMPTS = 3+_BOOKKEEPING_RETRY_SECONDS = 0.2++# One step, so overlapping scheduler runs cannot both fill the same room. Only ids absent from the+# set are added, under the expiry the scheduler chose, and only candidates carrying that expiry are+# returned: a retried admission whose first reply was lost gets the same ids back, and a member+# another run or a running check wrote is neither started nor touched by this one.+_ADMIT_SCRIPT = """+local key = KEYS[1]+local now = tonumber(ARGV[1])+local limit = tonumber(ARGV[2])+local expires_at = tonumber(ARGV[3])+redis.call('ZREMRANGEBYSCORE', key, '-inf', now)+local free = limit - redis.call('ZCARD', key)+local admitted = {}+for i = 4, #ARGV do+ local alert_id = ARGV[i]+ local current = redis.call('ZSCORE', key, alert_id)+ if current then+ if tonumber(current) == expires_at then+ admitted[#admitted + 1] = alert_id+ end+ elseif free > 0 then+ redis.call('ZADD', key, ARGV[3], alert_id)+ admitted[#admitted + 1] = alert_id+ free = free - 1+ end+end+return admitted+"""++# Temporal can retry an activity while the timed-out attempt is still running, and the scheduler can+# re-admit an id whose check already holds the slot, so only the writer whose expiry is still on the+# member may remove it.+_RELEASE_OWNED_SCRIPT = """+local key = KEYS[1]+local held_until = tonumber(ARGV[1])+local removed = 0+for i = 2, #ARGV do+ local current = redis.call('ZSCORE', key, ARGV[i])+ if current and tonumber(current) == held_until then+ removed = removed + redis.call('ZREM', key, ARGV[i])+ end+end+return removed+"""++_REFRESH_OWNED_SCRIPT = """+local key = KEYS[1]+local alert_id = ARGV[1]+local held_until = tonumber(ARGV[2])+local current = redis.call('ZSCORE', key, alert_id)+if current and tonumber(current) == held_until then+ redis.call('ZADD', key, ARGV[3], alert_id)+ return 1+end+return 0+"""++# A check normally holds by rewriting the expiry the scheduler or an earlier attempt wrote, which+# changes nothing about the count. An id that has lapsed from the set (a Redis outage outlasted its+# lease, or a failover lost the set) is no longer admitted, so it only gets a slot back while there+# is room, or the checks that took the room would run over the limit alongside it.+_HOLD_SCRIPT = """+local key = KEYS[1]+local now = tonumber(ARGV[1])+local limit = tonumber(ARGV[2])+local alert_id = ARGV[4]+redis.call('ZREMRANGEBYSCORE', key, '-inf', now)+if redis.call('ZSCORE', key, alert_id) or redis.call('ZCARD', key) < limit then+ redis.call('ZADD', key, ARGV[3], alert_id)+ return 1+end+return 0+"""+++def max_inflight_evaluations() -> int:+ return settings.ALERTS_MAX_INFLIGHT_EVALUATIONS+++def _decode(member: bytes | str) -> str:+ return member.decode() if isinstance(member, bytes) else member+++def admit_evaluation_slots(alert_ids: list[str], *, limit: int, expires_at: float) -> list[str]:+ """Admit candidates in order while the set has room and return the ids held under expires_at."""+ admitted = redis.get_client().eval(_ADMIT_SCRIPT, 1, INFLIGHT_KEY, time.time(), limit, expires_at, *alert_ids)+ return [_decode(member) for member in admitted]+++def hold_evaluation_slot(alert_id: str, *, limit: int, lease_seconds: float = SLOT_LEASE_SECONDS) -> float | None:+ """Take the slot for a check that is about to run and return the expiry that identifies this holder.++ Returns None when the check no longer holds a slot and the set is full.+ """+ expires_at = time.time() + lease_seconds+ held = redis.get_client().eval(_HOLD_SCRIPT, 1, INFLIGHT_KEY, time.time(), limit, expires_at, alert_id)+ return expires_at if held else None+++def refresh_evaluation_slot(alert_id: str, *, held_until: float, expires_at: float) -> bool:+ """Move the holder's expiry to expires_at and report whether the holder still owned the slot."""+ owned = redis.get_client().eval(_REFRESH_OWNED_SCRIPT, 1, INFLIGHT_KEY, alert_id, held_until, expires_at)+ return bool(owned)+++def release_evaluation_slots(alert_ids: list[str], *, held_until: float) -> None:+ """Free the slots that still carry the expiry their writer was given."""+ if alert_ids:+ redis.get_client().eval(_RELEASE_OWNED_SCRIPT, 1, INFLIGHT_KEY, held_until, *alert_ids)+++def release_evaluation_slot(alert_id: str, *, held_until: float) -> None:+ """Free a slot, but only if the holder identified by held_until still owns it.++ Best effort: the check this belongs to already ran, so a failure is logged rather than raised.+ """+ for attempt in range(_BOOKKEEPING_ATTEMPTS):+ try:+ release_evaluation_slots([alert_id], held_until=held_until)+ return+ except Exception:+ if attempt == _BOOKKEEPING_ATTEMPTS - 1:+ logger.exception("alerts.admission.release_failed", alert_id=alert_id)+ return+ time.sleep(_BOOKKEEPING_RETRY_SECONDS)+++def inflight_alert_ids() -> set[str]:+ client = redis.get_client()+ client.zremrangebyscore(INFLIGHT_KEY, "-inf", time.time())+ return {_decode(member) for member in client.zrange(INFLIGHT_KEY, 0, -1)}diff --git a/posthog/temporal/alerts/retry_policy.py b/posthog/temporal/alerts/retry_policy.pyindex 2cf601f486cf..ea50dd6a1518 100644--- a/posthog/temporal/alerts/retry_policy.py+++ b/posthog/temporal/alerts/retry_policy.py@@ -35,23 +35,68 @@ ALERT_NOTIFY_RETRY_POLICY = RetryPolicy()[email protected](frozen=True)+class SlotLease:+ """How a running evaluation keeps its admission slot: re-held every `refresh`, lapsing after `lease`."""++ lease: dt.timedelta+ refresh: dt.timedelta+++# A worker that dies stops refreshing, and Temporal retries its check heartbeat_timeout after the+# last heartbeat. The slot must still be held when that retry takes it over, or the scheduler fills+# it in between and the retry runs past the limit. The last refresh can be a whole interval before+# the death, so the grace must cover that interval plus Temporal's retry backoff and pickup delay.+_SLOT_REFRESH_INTERVAL = dt.timedelta(seconds=30)+_SLOT_TAKEOVER_GRACE = dt.timedelta(minutes=2)++@dataclasses.dataclass(frozen=True)class AlertTimeouts:+ """Every clock on a check, derived from one evaluation budget per cadence.++ Build one with for_budget. Evaluate's per-attempt timeout equals its total budget, so Temporal+ never restarts an attempt that is still heartbeating: a lost heartbeat is the only thing that+ retries a running check. The budget ends by cancelling the attempt, which stops its query.+ """+workflow_execution: dt.timedeltaactivity_schedule_to_close: dt.timedeltaevaluate_start_to_close: dt.timedeltaevaluate_retry_policy: RetryPolicyheartbeat_timeout: dt.timedelta+ prepare_start_to_close: dt.timedeltanotify_start_to_close: dt.timedelta+ evaluation_slot_lease: SlotLease++ @classmethod+ def for_budget(+ cls,+ *,+ evaluate: dt.timedelta,+ heartbeat: dt.timedelta,+ prepare: dt.timedelta,+ notify: dt.timedelta,+ evaluate_retry_policy: RetryPolicy,+ ) -> "AlertTimeouts":+ return cls(+ workflow_execution=prepare + evaluate + notify,+ activity_schedule_to_close=evaluate,+ evaluate_start_to_close=evaluate,+ evaluate_retry_policy=evaluate_retry_policy,+ heartbeat_timeout=heartbeat,+ prepare_start_to_close=prepare,+ notify_start_to_close=notify,+ evaluation_slot_lease=SlotLease(lease=heartbeat + _SLOT_TAKEOVER_GRACE, refresh=_SLOT_REFRESH_INTERVAL),+ )-_DEFAULT_TIMEOUTS = AlertTimeouts(- workflow_execution=dt.timedelta(minutes=15),- activity_schedule_to_close=dt.timedelta(minutes=12),- evaluate_start_to_close=dt.timedelta(minutes=10),+_DEFAULT_TIMEOUTS = AlertTimeouts.for_budget(+ evaluate=dt.timedelta(minutes=12),+ heartbeat=dt.timedelta(minutes=2),+ prepare=dt.timedelta(minutes=2),+ notify=dt.timedelta(minutes=5),evaluate_retry_policy=ALERT_EVALUATE_RETRY_POLICY,- heartbeat_timeout=dt.timedelta(minutes=2),- notify_start_to_close=dt.timedelta(minutes=5),)_REAL_TIME_EVALUATE_RETRY_POLICY = RetryPolicy(@@ -62,15 +107,12 @@ _REAL_TIME_EVALUATE_RETRY_POLICY = RetryPolicy(non_retryable_error_types=_EVALUATE_NON_RETRYABLE_ERROR_NAMES,)-# workflow_execution covers prepare (2 min) + evaluate at its schedule_to_close cap-# (7 min) + notify (1 min), so one activity exhausting its budget can't kill the run.-_REAL_TIME_TIMEOUTS = AlertTimeouts(- workflow_execution=dt.timedelta(minutes=10),- activity_schedule_to_close=dt.timedelta(minutes=7),- evaluate_start_to_close=dt.timedelta(minutes=3),+_REAL_TIME_TIMEOUTS = AlertTimeouts.for_budget(+ evaluate=dt.timedelta(minutes=7),+ heartbeat=dt.timedelta(seconds=90),+ prepare=dt.timedelta(minutes=2),+ notify=dt.timedelta(seconds=60),evaluate_retry_policy=_REAL_TIME_EVALUATE_RETRY_POLICY,- heartbeat_timeout=dt.timedelta(seconds=90),- notify_start_to_close=dt.timedelta(seconds=60),)diff --git a/posthog/temporal/alerts/types.py b/posthog/temporal/alerts/types.pyindex 53bc4e22eee9..fa2ea4db13c3 100644--- a/posthog/temporal/alerts/types.py+++ b/posthog/temporal/alerts/types.py@@ -40,6 +40,36 @@ class ScheduleDueAlertChecksWorkflowInputs:max_alerts_per_run: int = DEFAULT_MAX_DUE_ALERTS_PER_SCHEDULE_RUN+@frozen+class AdmitEvaluationsInputs:+ alert_ids: list[str]+ # Chosen by the workflow so every attempt of one admission writes, and later releases, the same expiry.+ expires_at: float+++@frozen+class AdmittedEvaluations:+ alert_ids: list[str]+++@frozen+class ReleaseEvaluationSlotsInputs:+ alert_ids: list[str]+ held_until: float+++@frozen+class UnstartedChecks:+ """Alerts a scheduler batch admitted without starting a new check for them."""++ failed_ids: list[str]+ already_running_ids: list[str]++ @property+ def alert_ids(self) -> list[str]:+ return self.failed_ids + self.already_running_ids++@dataclasses.dataclass(frozen=True)class CheckAlertWorkflowInputs:alert_id: str@@ -68,6 +98,7 @@ class PrepareAlertResult:@dataclasses.dataclass(frozen=True)class EvaluateAlertActivityInputs:alert_id: str+ calculation_interval: str | None = Noneuses_llm_detector: bool = False# Scopes the evaluation lookup. None on a workflow that started before this field existed.team_id: int | None = Nonediff --git a/posthog/temporal/alerts/workflows.py b/posthog/temporal/alerts/workflows.pyindex dd4ced955a4d..012e7e602f36 100644--- a/posthog/temporal/alerts/workflows.py+++ b/posthog/temporal/alerts/workflows.py@@ -11,11 +11,13 @@ from posthog.schema import AlertStatefrom posthog.slo.context import JsonValuefrom posthog.slo.types import SloArea, SloConfig, SloOperationfrom posthog.temporal.alerts.activities import (+ admit_alert_evaluations,cleanup_alert_checks,evaluate_alert,notify_alert,prepare_alert,record_failed_evaluation,+ release_alert_evaluation_slots,retrieve_due_alerts,run_investigation_safety_net,)@@ -26,14 +28,18 @@ from posthog.temporal.alerts.retry_policy import (alert_timeouts,)from posthog.temporal.alerts.types import (+ AdmitEvaluationsInputs,+ AlertInfo,CheckAlertWorkflowInputs,EvaluateAlertActivityInputs,NotifyAlertActivityInputs,PrepareAction,PrepareAlertActivityInputs,RecordFailedEvaluationActivityInputs,+ ReleaseEvaluationSlotsInputs,ScheduleDueAlertChecksWorkflowInputs,SkipReason,+ UnstartedChecks,)from posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.errors import MAX_ERROR_MESSAGE_CHARS, truncate_for_temporal_payload, unwrap_temporal_cause@@ -44,6 +50,18 @@ with temporalio.workflow.unsafe.imports_passed_through():from posthog.temporal.ai.anomaly_investigation import AnomalyInvestigationWorkflowInputs+# Runs started before the deploy replay the fan-out; drop the gate once no such run is left.+_PATCH_INFLIGHT_ADMISSION = "alerts-inflight-admission-2026-09"+_ADMISSION_POLL_INTERVAL = dt.timedelta(seconds=2)+# Under the one-minute schedule cadence, so the next run takes over what this one did not reach.+_ADMISSION_RUN_BUDGET = dt.timedelta(seconds=50)+_ADMISSION_ACTIVITY_RETRY_POLICY = temporalio.common.RetryPolicy(+ initial_interval=dt.timedelta(seconds=1),+ maximum_interval=dt.timedelta(seconds=10),+ maximum_attempts=5,+)++@temporalio.workflow.defn(name="schedule-due-alert-checks")class ScheduleDueAlertChecksWorkflow(PostHogWorkflow):@staticmethod@@ -59,7 +77,61 @@ class ScheduleDueAlertChecksWorkflow(PostHogWorkflow):if inputs is None:inputs = ScheduleDueAlertChecksWorkflowInputs()- alerts = await temporalio.workflow.execute_activity(+ if not temporalio.workflow.patched(_PATCH_INFLIGHT_ADMISSION):+ unstarted = await self._start_checks(await self._retrieve_due_alerts(inputs))+ self._raise_for_failed_starts(unstarted.failed_ids)+ return++ failed_ids: list[str] = []+ pending: list[AlertInfo] = []+ deadline = temporalio.workflow.now() + _ADMISSION_RUN_BUDGET+ while temporalio.workflow.now() < deadline:+ alerts = await self._retrieve_due_alerts(inputs)+ pending = list(alerts)+ while pending and temporalio.workflow.now() < deadline:+ expires_at = (temporalio.workflow.now() + alert_timeouts(None).workflow_execution).timestamp()+ admitted = await temporalio.workflow.execute_activity(+ admit_alert_evaluations,+ AdmitEvaluationsInputs(alert_ids=[alert.alert_id for alert in pending], expires_at=expires_at),+ start_to_close_timeout=dt.timedelta(seconds=30),+ retry_policy=_ADMISSION_ACTIVITY_RETRY_POLICY,+ )+ if admitted.alert_ids:+ admitted_ids = set(admitted.alert_ids)+ batch = [alert for alert in pending if alert.alert_id in admitted_ids]+ pending = [alert for alert in pending if alert.alert_id not in admitted_ids]+ unstarted = await self._start_checks(batch)+ failed_ids.extend(unstarted.failed_ids)+ if unstarted.alert_ids:+ await self._release_slots(unstarted.alert_ids, expires_at)+ if pending:+ await temporalio.workflow.sleep(_ADMISSION_POLL_INTERVAL)+ # A short page means nothing else is due; a full page may hide more behind it.+ if pending or not alerts or len(alerts) < inputs.max_alerts_per_run:+ break++ if pending:+ temporalio.workflow.logger.info(+ "check_alert.admission_budget_exhausted",+ extra={"remaining": len(pending)},+ )+ self._raise_for_failed_starts(failed_ids)++ async def _release_slots(self, alert_ids: list[str], expires_at: float) -> None:+ """Give back reservations no child will use: the start failed, or the check was already running.++ Admission returned only ids written under this expiry, and a running check holds its slot+ under its own, so a release keyed on it cannot take that slot away.+ """+ await temporalio.workflow.execute_activity(+ release_alert_evaluation_slots,+ ReleaseEvaluationSlotsInputs(alert_ids=alert_ids, held_until=expires_at),+ start_to_close_timeout=dt.timedelta(seconds=30),+ retry_policy=_ADMISSION_ACTIVITY_RETRY_POLICY,+ )++ async def _retrieve_due_alerts(self, inputs: ScheduleDueAlertChecksWorkflowInputs) -> list[AlertInfo]:+ return await temporalio.workflow.execute_activity(retrieve_due_alerts,inputs,start_to_close_timeout=dt.timedelta(minutes=2),@@ -70,10 +142,22 @@ class ScheduleDueAlertChecksWorkflow(PostHogWorkflow):),)- # 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.+ @staticmethod+ def _raise_for_failed_starts(failed_ids: list[str]) -> None:+ if failed_ids:+ raise ApplicationError(+ f"Alert checks failed to start for IDs: {failed_ids}",+ non_retryable=True,+ )++ async def _start_checks(self, alerts: list[AlertInfo]) -> UnstartedChecks:+ """Start one child workflow per alert and return the ids that did not get a new check.++ 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] = []+ already_running_ids: list[str] = []for alert in alerts:slo_properties: dict[str, JsonValue] = {"alert_type": "insight",@@ -104,6 +188,7 @@ class ScheduleDueAlertChecksWorkflow(PostHogWorkflow):execution_timeout=alert_timeouts(alert.calculation_interval).workflow_execution,)except WorkflowAlreadyStartedError:+ already_running_ids.append(alert.alert_id)temporalio.workflow.logger.info("check_alert.already_running",extra={"alert_id": alert.alert_id},@@ -114,12 +199,7 @@ class ScheduleDueAlertChecksWorkflow(PostHogWorkflow):"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,- )+ return UnstartedChecks(failed_ids=failed_ids, already_running_ids=already_running_ids)@temporalio.workflow.defn(name="check-alert")@@ -141,7 +221,7 @@ class CheckAlertWorkflow(PostHogWorkflow):prepare_result = await temporalio.workflow.execute_activity(prepare_alert,PrepareAlertActivityInputs(alert_id=inputs.alert_id),- start_to_close_timeout=dt.timedelta(minutes=2),+ start_to_close_timeout=timeouts.prepare_start_to_close,schedule_to_close_timeout=timeouts.activity_schedule_to_close,retry_policy=ALERT_PREPARE_RETRY_POLICY,)@@ -164,6 +244,7 @@ class CheckAlertWorkflow(PostHogWorkflow):evaluate_alert,EvaluateAlertActivityInputs(alert_id=inputs.alert_id,+ calculation_interval=inputs.calculation_interval,uses_llm_detector=prepare_result.uses_llm_detector,team_id=inputs.team_id,),diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.pyindex 4dd7c3070abe..f49e514ecc79 100644--- a/posthog/temporal/tests/test_alerts_activities.py+++ b/posthog/temporal/tests/test_alerts_activities.py@@ -1,13 +1,17 @@+import timeimport uuid+import asyncioimport threadingimport contextlib+import dataclassesfrom concurrent.futures import ThreadPoolExecutor-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltaimport pytestimport time_machine-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, call, patch+from django.core.exceptions import ValidationErrorfrom django.db import OperationalError, connection, transactionimport pytest_asyncio@@ -26,13 +30,16 @@ from posthog.schema import (TrendsQuery,)+from posthog.clickhouse.query_tagging import get_query_tagsfrom posthog.constants import AvailableFeature+from posthog.errors import CHQueryErrorQueryWasCancelledfrom posthog.exceptions import (ClickHouseAtCapacity,ClickHouseClusterMemoryLimitExceeded,ClickHouseQueryMemoryLimitExceeded,)from posthog.models import Team, User+from posthog.redis import get_clientfrom posthog.slo.types import SloOperation, SloOutcomefrom posthog.tasks.alerts.utils import (AlertEvaluationResult,@@ -42,6 +49,7 @@ from posthog.tasks.alerts.utils import (from posthog.temporal.alerts.activities import (_evaluation_inputs_match,_load_alert_for_evaluation,+ _lock_evaluation_alert,cleanup_alert_checks,evaluate_alert,notify_alert,@@ -49,7 +57,14 @@ from posthog.temporal.alerts.activities import (record_failed_evaluation,retrieve_due_alerts,)-from posthog.temporal.alerts.retry_policy import alert_timeouts+from posthog.temporal.alerts.admission import (+ INFLIGHT_KEY,+ SLOT_LEASE_SECONDS,+ admit_evaluation_slots,+ hold_evaluation_slot,+ inflight_alert_ids,+)+from posthog.temporal.alerts.retry_policy import SlotLease, alert_timeoutsfrom posthog.temporal.alerts.types import (EvaluateAlertActivityInputs,NotifyAlertActivityInputs,@@ -76,6 +91,22 @@ def _email_delivery(target: str, at: str = "2026-08-11T00:00:00+00:00") -> Alertreturn AlertDelivery(channel="email", target=target, at=at)[email protected](autouse=True)+def clear_inflight_slots():+ get_client().delete(INFLIGHT_KEY)+ yield+ get_client().delete(INFLIGHT_KEY)+++def _reserve_as_the_scheduler(alert_id: str) -> None:+ admit_evaluation_slots([alert_id], limit=1, expires_at=time.time() + SLOT_LEASE_SECONDS)+++def _hold_as_a_later_attempt(alert_id: str) -> None:+ with time_machine.travel(datetime.now(UTC) + timedelta(minutes=1), tick=False):+ hold_evaluation_slot(alert_id, limit=1)++def _valid_trends_query() -> dict:return TrendsQuery(series=[EventsNode(event="$pageview")],@@ -288,8 +319,10 @@ class TestPrepareAlert:ctx = time_machine.travel(frozen_time, tick=False) if frozen_time else contextlib.nullcontext()with ctx:a = await _create_alert(ateam, **setup_kwargs)+ _reserve_as_the_scheduler(str(a.id))env = ActivityEnvironment()result = await env.run(prepare_alert, PrepareAlertActivityInputs(alert_id=str(a.id)))+ assert inflight_alert_ids() == set()assert result.action == PrepareAction.SKIPassert result.reason == expected_reason@@ -304,6 +337,35 @@ class TestPrepareAlert:# Non-advancing skip branches must leave next_check_at untouched.assert refreshed.next_check_at == setup_kwargs.get("next_check_at")+ @pytest.mark.parametrize(+ "attempt,still_held",+ [pytest.param(1, True, id="retried"), pytest.param(3, False, id="last_attempt")],+ )+ async def test_failed_preparation_keeps_the_slot_until_the_last_attempt(+ self, attempt: int, still_held: bool+ ) -> None:+ env = ActivityEnvironment()+ env.info = dataclasses.replace(env.info, attempt=attempt)+ with pytest.raises(ValidationError):+ await env.run(prepare_alert, PrepareAlertActivityInputs(alert_id="not-a-uuid"))+ assert ("not-a-uuid" in inflight_alert_ids()) is still_held++ async def test_skip_leaves_the_slot_a_later_attempt_holds(self, ateam) -> None:+ a = await _create_alert(ateam, skip_weekend=True, schedule_start_time="08:30")++ def _hold_as_a_retried_attempt(alert: AlertConfiguration) -> bool:+ # A retried attempt takes the slot while this attempt is still deciding to skip.+ _hold_as_a_later_attempt(str(alert.id))+ return True++ with (+ time_machine.travel("2024-12-21T08:00:00Z", tick=False), # Saturday+ patch("posthog.temporal.alerts.activities.skip_because_of_weekend", side_effect=_hold_as_a_retried_attempt),+ ):+ result = await ActivityEnvironment().run(prepare_alert, PrepareAlertActivityInputs(alert_id=str(a.id)))+ assert result.reason == SkipReason.WEEKEND+ assert str(a.id) in inflight_alert_ids()+@time_machine.travel("2024-06-03T10:00:00Z", tick=False)async def test_snoozed_future_preserves_snoozed_until(self, ateam) -> None:# Separate from the parameterized set because it asserts a DB field is UNCHANGED,@@ -417,9 +479,14 @@ class TestPrepareAlert:check = await sync_to_async(AlertCheck.objects.get)(alert_configuration=refreshed)assert check.error == {"message": result.reason, "code": "email_unavailable"}- async def test_evaluate_for_valid_alert(self, alert) -> None:+ @pytest.mark.parametrize("redis_unreachable", [False, True])+ async def test_evaluate_for_valid_alert(self, alert, redis_unreachable: bool) -> None:env = ActivityEnvironment()- result = await env.run(prepare_alert, PrepareAlertActivityInputs(alert_id=str(alert.id)))+ with patch(+ "posthog.temporal.alerts.activities.hold_evaluation_slot",+ side_effect=ConnectionError("redis down") if redis_unreachable else hold_evaluation_slot,+ ):+ result = await env.run(prepare_alert, PrepareAlertActivityInputs(alert_id=str(alert.id)))assert result.action == PrepareAction.EVALUATEassert result.reason is None@@ -642,10 +709,12 @@ class TestEvaluateAlert:async def test_retry_keeps_evaluation_id_after_the_schedule_advances(self, alert) -> None:evaluation_ids: list[str] = []+ query_ids: list[str | None] = []schedules: list[datetime | None] = []def _record_evaluation(_alert, *, evaluation_id):evaluation_ids.append(evaluation_id)+ query_ids.append(get_query_tags().client_query_id)schedules.append(_alert.next_check_at)return AlertEvaluationResult(value=5.0, breaches=None)@@ -654,29 +723,285 @@ class TestEvaluateAlert:env = ActivityEnvironment()inputs = EvaluateAlertActivityInputs(alert_id=str(alert.id))await env.run(evaluate_alert, inputs)+ env.info = dataclasses.replace(env.info, attempt=10)await env.run(evaluate_alert, inputs)assert schedules[0] is Noneassert schedules[1] is not Noneassert evaluation_ids[0]assert evaluation_ids[0] == evaluation_ids[1]+ assert query_ids[0] and query_ids[1]+ assert not query_ids[1].startswith(query_ids[0])+ assert not query_ids[0].startswith(query_ids[1])async def test_evaluate_not_firing_no_breaches(self, alert) -> None:+ def _check_while_holding_the_slot(evaluated_alert, *, evaluation_id):+ assert str(evaluated_alert.id) in inflight_alert_ids()+ return AlertEvaluationResult(value=5.0, breaches=None)+with patch("posthog.temporal.alerts.activities.check_alert_for_insight",- return_value=AlertEvaluationResult(value=5.0, breaches=None),+ side_effect=_check_while_holding_the_slot,):env = ActivityEnvironment()result = await env.run(evaluate_alert, EvaluateAlertActivityInputs(alert_id=str(alert.id)))+ assert inflight_alert_ids() == set()assert result.new_state == AlertState.NOT_FIRING- assert result.should_notify is False- assert result.alert_check_id # stringified UUID, truthy- check = await sync_to_async(AlertCheck.objects.get)(pk=result.alert_check_id)- assert check.state == AlertState.NOT_FIRING- assert check.calculated_value == 5.0- assert check.targets_notified == {} # empty sentinel — notify_alert fills on success+ async def test_evaluate_leaves_the_slot_a_later_attempt_holds(self, alert) -> None:+ def _check_while_a_retried_attempt_takes_over(evaluated_alert, *, evaluation_id):+ _hold_as_a_later_attempt(str(evaluated_alert.id))+ return AlertEvaluationResult(value=5.0, breaches=None)++ with patch(+ "posthog.temporal.alerts.activities.check_alert_for_insight",+ side_effect=_check_while_a_retried_attempt_takes_over,+ ):+ await ActivityEnvironment().run(evaluate_alert, EvaluateAlertActivityInputs(alert_id=str(alert.id)))++ assert str(alert.id) in inflight_alert_ids()++ async def test_evaluate_re_holds_its_slot_while_the_query_runs(self, alert) -> None:+ short_lease = dataclasses.replace(+ alert_timeouts(None),+ evaluation_slot_lease=SlotLease(lease=timedelta(seconds=1), refresh=timedelta(seconds=0.1)),+ )++ def _query_until_the_slot_is_re_held(evaluated_alert, *, evaluation_id):+ alert_id = str(evaluated_alert.id)+ first_expiry = get_client().zscore(INFLIGHT_KEY, alert_id)+ give_up_at = time.monotonic() + 5+ while get_client().zscore(INFLIGHT_KEY, alert_id) == first_expiry:+ assert time.monotonic() < give_up_at, "the running evaluation never re-held its slot"+ time.sleep(0.05)+ return AlertEvaluationResult(value=5.0, breaches=None)++ loop = asyncio.get_running_loop()+ run_in_executor = loop.run_in_executor+ with (+ ThreadPoolExecutor(max_workers=1) as query_executor,+ patch.object(+ loop,+ "run_in_executor",+ side_effect=lambda executor, function, *args: run_in_executor(+ executor if executor is not None else query_executor, function, *args+ ),+ ),+ patch("posthog.temporal.alerts.activities.alert_timeouts", return_value=short_lease),+ patch(+ "posthog.temporal.alerts.activities.check_alert_for_insight",+ side_effect=_query_until_the_slot_is_re_held,+ ),+ ):+ result = await ActivityEnvironment().run(+ evaluate_alert, EvaluateAlertActivityInputs(alert_id=str(alert.id))+ )++ assert result.new_state == AlertState.NOT_FIRING+ assert inflight_alert_ids() == set()++ @pytest.mark.parametrize("cancel_during", ["query", "before_query", "persistence_lock"])+ async def test_cancelled_evaluate_kills_its_query_and_frees_the_slot_once_the_thread_exits(+ self, alert, cancel_during: str+ ) -> None:+ loop = asyncio.get_running_loop()+ run_in_executor = loop.run_in_executor+ attempt_running = asyncio.Event()+ query_started = threading.Event()+ query_killed = threading.Event()+ query_thread_done = threading.Event()+ query_ids: list[str | None] = []+ slot_held_at_kill: list[bool] = []+ kills_before_the_query_starts = int(cancel_during == "before_query")++ def _query_until_killed(evaluated_alert, *, evaluation_id):+ query_ids.append(get_query_tags().client_query_id)+ if cancel_during == "persistence_lock":+ return AlertEvaluationResult(value=20.0, breaches=["above threshold"])+ loop.call_soon_threadsafe(attempt_running.set)+ try:+ # The thread is still waiting for a connection when the first kill lands.+ if kills_before_the_query_starts:+ query_started.wait(timeout=5)+ query_killed.wait(timeout=5)+ raise CHQueryErrorQueryWasCancelled("killed", code=394)+ finally:+ query_thread_done.set()++ def _lock_then_wait(**kwargs):+ current = _lock_evaluation_alert(**kwargs)+ if cancel_during == "persistence_lock":+ loop.call_soon_threadsafe(attempt_running.set)+ query_killed.wait(timeout=5)+ query_thread_done.set()+ return current++ def _kill(team_id, client_query_id):+ slot_held_at_kill.append(str(alert.id) in inflight_alert_ids())+ if len(slot_held_at_kill) <= kills_before_the_query_starts:+ query_started.set() # this kill found no query; the thread reaches ClickHouse only now+ else:+ query_killed.set()++ env = ActivityEnvironment()+ with (+ ThreadPoolExecutor(max_workers=1) as query_executor,+ patch.object(+ loop,+ "run_in_executor",+ side_effect=lambda executor, function, *args: run_in_executor(+ executor if executor is not None else query_executor, function, *args+ ),+ ),+ patch("posthog.temporal.alerts.activities._SLOT_POLL_SECONDS", 0.05),+ patch("posthog.temporal.alerts.activities._lock_evaluation_alert", side_effect=_lock_then_wait),+ patch("posthog.temporal.alerts.activities.check_alert_for_insight", side_effect=_query_until_killed),+ patch("posthog.temporal.alerts.activities.cancel_query_on_cluster", side_effect=_kill) as kill,+ ):+ attempt = asyncio.ensure_future(+ env.run(evaluate_alert, EvaluateAlertActivityInputs(alert_id=str(alert.id), team_id=alert.team_id))+ )+ await asyncio.wait_for(attempt_running.wait(), timeout=5)+ assert str(alert.id) in inflight_alert_ids()+ env.cancel()+ with pytest.raises(asyncio.CancelledError):+ await attempt+ await asyncio.to_thread(query_thread_done.wait, 5)++ assert len(slot_held_at_kill) > kills_before_the_query_starts+ assert all(slot_held_at_kill)+ assert query_ids[0]+ assert all(kill_call == call(alert.team_id, query_ids[0]) for kill_call in kill.call_args_list)+ assert inflight_alert_ids() == set()+ assert await sync_to_async(AlertCheck.objects.filter(alert_configuration=alert).exists)() is False++ async def test_cancelled_evaluate_leaves_the_slot_to_lapse_when_its_thread_will_not_stop(self, alert) -> None:+ short_budget = dataclasses.replace(alert_timeouts(None), activity_schedule_to_close=timedelta(seconds=0.3))+ query_running = threading.Event()+ let_the_thread_go = threading.Event()++ def _query_that_ignores_the_kill(evaluated_alert, *, evaluation_id):+ query_running.set()+ let_the_thread_go.wait(timeout=5)+ return AlertEvaluationResult(value=5.0, breaches=None)++ env = ActivityEnvironment()+ with (+ patch("posthog.temporal.alerts.activities.alert_timeouts", return_value=short_budget),+ patch("posthog.temporal.alerts.activities._SLOT_POLL_SECONDS", 0.05),+ patch(+ "posthog.temporal.alerts.activities.check_alert_for_insight", side_effect=_query_that_ignores_the_kill+ ),+ patch("posthog.temporal.alerts.activities.cancel_query_on_cluster") as kill,+ ):+ attempt = asyncio.ensure_future(+ env.run(evaluate_alert, EvaluateAlertActivityInputs(alert_id=str(alert.id), team_id=alert.team_id))+ )+ await asyncio.to_thread(query_running.wait, 5)+ env.cancel()+ with pytest.raises(asyncio.CancelledError):+ await attempt+ # The thread is still alive, so the slot that counts it stays until its lease lapses.+ assert kill.called+ assert str(alert.id) in inflight_alert_ids()+ let_the_thread_go.set()+ # The thread's task is the only work left on the loop. Once it ends, the abandoned+ # thread has woken up with a result that its cancelled attempt must not record.+ leftover = asyncio.all_tasks() - {asyncio.current_task()}+ _done, pending = await asyncio.wait(leftover, timeout=5)+ assert not pending+ assert await sync_to_async(AlertCheck.objects.filter(alert_configuration=alert).exists)() is False++ @pytest.mark.parametrize("how_the_slot_is_lost", ["taken_over", "redis_unreachable"])+ async def test_evaluate_stops_its_query_once_it_can_no_longer_hold_its_slot(+ self, alert, how_the_slot_is_lost: str+ ) -> None:+ short_lease = dataclasses.replace(+ alert_timeouts(None),+ evaluation_slot_lease=SlotLease(lease=timedelta(seconds=1), refresh=timedelta(seconds=0.1)),+ )+ query_running = threading.Event()+ query_killed = threading.Event()+ query_thread_done = threading.Event()++ def _query_until_killed(evaluated_alert, *, evaluation_id):+ query_running.set()+ try:+ query_killed.wait(timeout=5)+ raise CHQueryErrorQueryWasCancelled("killed", code=394)+ finally:+ query_thread_done.set()++ redis_unreachable = (+ patch("posthog.temporal.alerts.activities.refresh_evaluation_slot", side_effect=ConnectionError("down"))+ if how_the_slot_is_lost == "redis_unreachable"+ else contextlib.nullcontext()+ )+ with (+ patch("posthog.temporal.alerts.activities.alert_timeouts", return_value=short_lease),+ patch("posthog.temporal.alerts.activities._SLOT_POLL_SECONDS", 0.05),+ patch("posthog.temporal.alerts.activities.check_alert_for_insight", side_effect=_query_until_killed),+ patch(+ "posthog.temporal.alerts.activities.cancel_query_on_cluster",+ side_effect=lambda team_id, client_query_id: query_killed.set(),+ ) as kill,+ redis_unreachable,+ ):+ attempt = asyncio.ensure_future(+ ActivityEnvironment().run(+ evaluate_alert, EvaluateAlertActivityInputs(alert_id=str(alert.id), team_id=alert.team_id)+ )+ )+ await asyncio.to_thread(query_running.wait, 5)+ if how_the_slot_is_lost == "taken_over":+ _hold_as_a_later_attempt(str(alert.id))+ with pytest.raises(ApplicationError) as raised:+ await attempt+ await asyncio.to_thread(query_thread_done.wait, 5)++ assert raised.value.type == "EvaluationSlotLost"+ assert raised.value.non_retryable is False+ kill.assert_called()+ assert await sync_to_async(AlertCheck.objects.filter(alert_configuration=alert).exists)() is False+ # The later attempt keeps the slot it took; a slot that could not be kept is given back.+ assert (str(alert.id) in inflight_alert_ids()) is (how_the_slot_is_lost == "taken_over")++ @pytest.mark.parametrize(+ "first_hold",+ [pytest.param(ConnectionError("redis down"), id="redis_unreachable"), pytest.param(None, id="no_room")],+ )+ async def test_evaluate_waits_for_a_slot_before_it_runs(self, alert, first_hold) -> None:+ holds: list[float | None] = []++ def _hold_after_one_refusal(*args, **kwargs):+ if holds:+ holds.append(hold_evaluation_slot(*args, **kwargs))+ return holds[-1]+ holds.append(None)+ if isinstance(first_hold, Exception):+ raise first_hold+ return None++ def _check_while_holding_the_slot(evaluated_alert, *, evaluation_id):+ assert str(evaluated_alert.id) in inflight_alert_ids()+ return AlertEvaluationResult(value=5.0, breaches=None)++ with (+ patch("posthog.temporal.alerts.activities._SLOT_POLL_SECONDS", 0.01),+ patch("posthog.temporal.alerts.activities.hold_evaluation_slot", side_effect=_hold_after_one_refusal),+ patch(+ "posthog.temporal.alerts.activities.check_alert_for_insight",+ side_effect=_check_while_holding_the_slot,+ ),+ ):+ result = await ActivityEnvironment().run(+ evaluate_alert, EvaluateAlertActivityInputs(alert_id=str(alert.id))+ )++ assert len(holds) == 2+ assert result.new_state == AlertState.NOT_FIRING+ assert inflight_alert_ids() == set()async def test_evaluate_firing_with_breaches(self, alert) -> None:with patch(@@ -847,24 +1172,29 @@ class TestEvaluateAlert:# Capacity errors (codes 202/439) surface as ClickHouseAtCapacity, so that's what we simulate.# A server-wide or per-user memory limit is the same kind of cluster pressure: recording it as# an error instead sends the alert silent until its next cadence slot, an hour for hourly ones.+ # A killed query is the cancelled attempt's own doing, and recording it would write a check+ # the attempt that killed it never asked for.@pytest.mark.parametrize(- "error_class",+ "error",[- ClickHouseAtCapacity,- ClickHouseClusterMemoryLimitExceeded,- SocketTimeoutError,- NetworkError,- LLMDetectorUnavailableError,+ ClickHouseAtCapacity(),+ ClickHouseClusterMemoryLimitExceeded(),+ SocketTimeoutError(),+ NetworkError(),+ LLMDetectorUnavailableError(),+ CHQueryErrorQueryWasCancelled("killed", code=394),],)- async def test_evaluate_reraises_ch_transient_error(self, alert, error_class) -> None:+ async def test_evaluate_reraises_ch_transient_error(self, alert, error) -> None:with patch("posthog.temporal.alerts.activities.check_alert_for_insight",- side_effect=error_class(),+ side_effect=error,):env = ActivityEnvironment()- with pytest.raises(error_class):+ with pytest.raises(type(error)):await env.run(evaluate_alert, EvaluateAlertActivityInputs(alert_id=str(alert.id)))+ # The retry keeps its slot, or the scheduler admits past the limit during the backoff.+ assert str(alert.id) in inflight_alert_ids()# No AlertCheck should have been writtencount = await sync_to_async(AlertCheck.objects.filter(alert_configuration=alert).count)()@@ -1467,6 +1797,18 @@ class TestNotifyAlert:assert refreshed.targets_notified == {"users": ["[email protected]"], "destinations": []}[email protected]("calculation_interval", [None, AlertCalculationInterval.REAL_TIME])+def test_alert_timeouts_never_restart_a_live_attempt(calculation_interval) -> None:+ timeouts = alert_timeouts(calculation_interval)+ # A per-attempt timeout under the budget restarts a slow attempt while its query still runs.+ assert timeouts.evaluate_start_to_close == timeouts.activity_schedule_to_close+ # The retried attempt must take the slot over before it lapses, or the scheduler fills it in between.+ slot = timeouts.evaluation_slot_lease+ assert slot.lease - slot.refresh > timeouts.heartbeat_timeout+ activities = timeouts.prepare_start_to_close + timeouts.activity_schedule_to_close + timeouts.notify_start_to_close+ assert timeouts.workflow_execution >= activities++@pytest.mark.parametrize("calculation_interval", [None, AlertCalculationInterval.REAL_TIME])def test_cluster_memory_limit_stays_retryable_for_the_evaluate_policy(calculation_interval) -> None:# The evaluate policy takes its non-retryable list from the exports user-error class names, anddiff --git a/posthog/temporal/tests/test_alerts_admission.py b/posthog/temporal/tests/test_alerts_admission.pynew file mode 100644index 000000000000..97335b2bbf7e--- /dev/null+++ b/posthog/temporal/tests/test_alerts_admission.py@@ -0,0 +1,102 @@+from datetime import UTC, datetime++import pytest+import time_machine++from posthog.redis import get_client+from posthog.temporal.alerts.admission import (+ INFLIGHT_KEY,+ SLOT_LEASE_SECONDS,+ admit_evaluation_slots,+ hold_evaluation_slot,+ inflight_alert_ids,+ refresh_evaluation_slot,+ release_evaluation_slot,+ release_evaluation_slots,+)++_AT_TEN = datetime(2026, 9, 22, 10, tzinfo=UTC).timestamp() # where the frozen clocks below start++[email protected](autouse=True)+def clear_inflight_slots():+ get_client().delete(INFLIGHT_KEY)+ yield+ get_client().delete(INFLIGHT_KEY)+++def _expiry(offset_seconds: float = 0) -> float:+ return _AT_TEN + offset_seconds + SLOT_LEASE_SECONDS+++def _at(offset_seconds: float) -> datetime:+ return datetime.fromtimestamp(_AT_TEN + offset_seconds, tz=UTC)+++def _hold(alert_id: str, *, limit: int, lease_seconds: float = SLOT_LEASE_SECONDS) -> float:+ held = hold_evaluation_slot(alert_id, limit=limit, lease_seconds=lease_seconds)+ assert held is not None+ return held+++def test_admission_fills_only_the_free_capacity_and_slots_outlive_any_check() -> None:+ with time_machine.travel(_at(0), tick=False):+ first_hold = _hold("running", limit=3)+ assert admit_evaluation_slots(["a", "b", "c"], limit=3, expires_at=_expiry()) == ["a", "b"]+ assert admit_evaluation_slots(["c"], limit=3, expires_at=_expiry(1)) == []+ # A check that lost its slot to a full set gets none back; one still in the set re-holds regardless.+ assert hold_evaluation_slot("c", limit=3) is None+ assert hold_evaluation_slot("a", limit=3) == _expiry()+ assert inflight_alert_ids() == {"running", "a", "b"}++ # The scheduler's lease is the workflow timeout, so every slot is still held one minute short of it.+ one_minute_short = SLOT_LEASE_SECONDS - 60+ with time_machine.travel(_at(one_minute_short), tick=False):+ second_hold = _hold("running", limit=3)+ assert admit_evaluation_slots(["c"], limit=3, expires_at=_expiry(one_minute_short)) == []+ release_evaluation_slots(["a"], held_until=_expiry())+ assert admit_evaluation_slots(["c"], limit=3, expires_at=_expiry(one_minute_short)) == ["c"]+ # The attempt that held first no longer owns the slot, so its release is a no-op.+ release_evaluation_slot("running", held_until=first_hold)+ assert "running" in inflight_alert_ids()++ # Past that, "b" lapses on its own; the slots held or admitted one minute short do not.+ with time_machine.travel(_at(SLOT_LEASE_SECONDS + 60), tick=False):+ assert inflight_alert_ids() == {"running", "c"}+ release_evaluation_slot("running", held_until=second_hold)+ assert inflight_alert_ids() == {"c"}+++def test_refresh_moves_only_the_expiry_its_holder_wrote() -> None:+ with time_machine.travel(_at(0), tick=False):+ held = _hold("running", limit=1, lease_seconds=120)+ assert refresh_evaluation_slot("running", held_until=held, expires_at=_AT_TEN + 300) is True+ # The expiry the holder first wrote no longer identifies it, and an unheld member is not created.+ assert refresh_evaluation_slot("running", held_until=held, expires_at=_AT_TEN + 900) is False+ assert refresh_evaluation_slot("absent", held_until=held, expires_at=_AT_TEN + 900) is False+ with time_machine.travel(_at(240), tick=False):+ assert inflight_alert_ids() == {"running"}+ with time_machine.travel(_at(360), tick=False):+ assert inflight_alert_ids() == set()+++def test_retried_admission_returns_its_first_result_and_another_run_gets_none_of_it() -> None:+ candidates = ["a", "b", "c", "d", "e", "f"]+ with time_machine.travel("2026-09-22T10:00:00Z", tick=False):+ first = admit_evaluation_slots(candidates, limit=4, expires_at=_expiry())+ retry = admit_evaluation_slots(candidates, limit=4, expires_at=_expiry())+ other_run = admit_evaluation_slots(candidates, limit=6, expires_at=_expiry(2))+ assert inflight_alert_ids() == set(candidates)+ assert first == ["a", "b", "c", "d"]+ assert retry == first+ assert other_run == ["e", "f"]+++def test_scheduler_release_leaves_the_slot_a_running_check_holds() -> None:+ with time_machine.travel("2026-09-22T10:00:00Z", tick=False):+ held = _hold("running", limit=3)+ assert admit_evaluation_slots(["running", "fresh"], limit=3, expires_at=_expiry(1)) == ["fresh"]+ release_evaluation_slots(["running", "fresh"], held_until=_expiry(1))+ assert inflight_alert_ids() == {"running"}+ release_evaluation_slot("running", held_until=held)+ assert inflight_alert_ids() == set()diff --git a/posthog/temporal/tests/test_alerts_retrieval.py b/posthog/temporal/tests/test_alerts_retrieval.pyindex a99c2d91b976..d04ce4eb7a25 100644--- a/posthog/temporal/tests/test_alerts_retrieval.py+++ b/posthog/temporal/tests/test_alerts_retrieval.py@@ -1,3 +1,4 @@+import timefrom datetime import UTC, datetimeimport pytest@@ -11,11 +12,20 @@ from temporalio.testing import ActivityEnvironmentfrom posthog.schema import AlertCalculationIntervalfrom posthog.models import Team+from posthog.redis import get_clientfrom posthog.temporal.alerts.activities import _RetrievedAlerts, retrieve_due_alerts+from posthog.temporal.alerts.admission import INFLIGHT_KEY, SLOT_LEASE_SECONDS, admit_evaluation_slotsfrom posthog.temporal.alerts.types import AlertInfo, ScheduleDueAlertChecksWorkflowInputsfrom posthog.temporal.tests.test_alerts_activities import _create_alert[email protected](autouse=True)+def clear_inflight_slots():+ get_client().delete(INFLIGHT_KEY)+ yield+ get_client().delete(INFLIGHT_KEY)++@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)@pytest.mark.parametrize(@@ -105,7 +115,7 @@ async def test_retrieve_due_alerts_excludes_future_checks_and_applies_the_docume@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)-async def test_retrieve_due_alerts_reselects_the_same_oldest_due_alerts_until_checks_advance(ateam: Team) -> None:+async def test_retrieve_due_alerts_reselects_the_same_oldest_due_alerts_until_they_are_admitted(ateam: Team) -> None:due_alerts = [await _create_alert(ateam,@@ -118,6 +128,9 @@ async def test_retrieve_due_alerts_reselects_the_same_oldest_due_alerts_until_chwith time_machine.travel("2026-09-10T12:00:00Z", tick=False):first_sweep = await ActivityEnvironment().run(retrieve_due_alerts, inputs)second_sweep = await ActivityEnvironment().run(retrieve_due_alerts, inputs)+ admitted = [alert.alert_id for alert in first_sweep]+ admit_evaluation_slots(admitted, limit=len(admitted), expires_at=time.time() + SLOT_LEASE_SECONDS)+ third_sweep = await ActivityEnvironment().run(retrieve_due_alerts, inputs)oldest_due_alert_ids = [str(alert.id) for alert in due_alerts[:2]]first_sweep_ids = [alert.alert_id for alert in first_sweep]@@ -126,6 +139,7 @@ async def test_retrieve_due_alerts_reselects_the_same_oldest_due_alerts_until_chassert first_sweep_ids == oldest_due_alert_ids# Retrieval does not advance next_check_at, so the next sweep sees the same oldest cohort as due.assert second_sweep_ids == first_sweep_ids+ assert [alert.alert_id for alert in third_sweep] == [str(due_alerts[2].id)]@pytest.mark.asyncio@@ -142,7 +156,9 @@ async def test_retrieve_due_alerts_records_capacity_and_selected_alert_counters(polled_at = datetime(2026, 9, 10, 12, 0, tzinfo=UTC)async def fake_get_alerts() -> _RetrievedAlerts:- return _RetrievedAlerts(alerts=[MagicMock()] * 9, due_count=42, oldest_due_at=None, polled_at=polled_at)+ return _RetrievedAlerts(+ alerts=[MagicMock()] * 9, due_count=42, oldest_due_at=None, polled_at=polled_at, in_flight_count=3+ )with (patch(@@ -166,6 +182,10 @@ async def test_retrieve_due_alerts_records_capacity_and_selected_alert_counters(assert created_counter_names == expected_counter_namesassert capacity_counter.add.call_args_list == [call(11), call(10), call(9)]assert selected_counter.add.call_args_list == [call(9), call(9), call(9)]+ assert [gauge_call.args[0] for gauge_call in meter.create_gauge.call_args_list] == [+ "insight_alert_evaluations_inflight"+ ] * 3+ assert meter.create_gauge.return_value.set.call_args_list == [call(3)] * 3meter.with_additional_attributes.assert_not_called()@@ -176,7 +196,9 @@ async def test_retrieve_due_alerts_succeeds_when_metric_recording_fails(failing_polled_at = datetime(2026, 9, 10, 12, 0, tzinfo=UTC)async def fake_get_alerts() -> _RetrievedAlerts:- return _RetrievedAlerts(alerts=expected_alerts, due_count=1, oldest_due_at=None, polled_at=polled_at)+ return _RetrievedAlerts(+ alerts=expected_alerts, due_count=1, oldest_due_at=None, polled_at=polled_at, in_flight_count=0+ )record_due_metrics = MagicMock()get_metric_meter = MagicMock(return_value=MagicMock(spec=MetricMeter))diff --git a/posthog/temporal/tests/test_alerts_workflows.py b/posthog/temporal/tests/test_alerts_workflows.pyindex 13dd37ccad27..0290fb536953 100644--- a/posthog/temporal/tests/test_alerts_workflows.py+++ b/posthog/temporal/tests/test_alerts_workflows.py@@ -1,7 +1,9 @@import uuid-from collections.abc import Callable-from contextlib import nullcontext-from datetime import UTC, datetime+import itertools+import dataclasses+from collections.abc import Callable, Iterator+from contextlib import contextmanager, nullcontext+from datetime import UTC, datetime, timedeltafrom typing import Anyimport pytest@@ -30,11 +32,20 @@ from posthog.exceptions import ClickHouseClusterMemoryLimitExceededfrom posthog.models import Userfrom posthog.slo.types import SloArea, SloConfig, SloOperation, SloOutcomefrom posthog.tasks.alerts.utils import AlertEvaluationResult-from posthog.temporal.alerts.activities import evaluate_alert, notify_alert, prepare_alert, record_failed_evaluation+from posthog.temporal.alerts.activities import (+ admit_alert_evaluations,+ evaluate_alert,+ notify_alert,+ prepare_alert,+ record_failed_evaluation,+ release_alert_evaluation_slots,+ retrieve_due_alerts,+)from posthog.temporal.alerts.retry_policy import ALERT_EVALUATE_RETRY_POLICYfrom posthog.temporal.alerts.schedule import create_schedule_due_alert_checks_schedulefrom posthog.temporal.alerts.types import (DEFAULT_MAX_DUE_ALERTS_PER_SCHEDULE_RUN,+ AdmittedEvaluations,AlertInfo,CheckAlertWorkflowInputs,EvaluateAlertResult,@@ -63,6 +74,87 @@ CHECK_ALERT_ACTIVITIES: list[Callable[..., Any]] = []+def _alerts(count: int) -> list[AlertInfo]:+ return [+ 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(count)+ ]++[email protected](frozen=True)+class _SchedulerRun:+ execute_activity: AsyncMock+ start_child: AsyncMock+ sleep: AsyncMock+ admitted: list[list[str]]+ admission_expiries: list[float]+ released: list[tuple[list[str], float]]+++@contextmanager+def _admission_scheduler(+ *,+ due_pages: list[list[AlertInfo]],+ free_capacity: list[int],+ start_child_side_effect: Any = None,+ seconds_per_clock_read: int = 0,+) -> Iterator[_SchedulerRun]:+ pages = iter(due_pages)+ capacities = iter(free_capacity)+ admitted: list[list[str]] = []+ admission_expiries: list[float] = []+ released: list[tuple[list[str], float]] = []+ clock = itertools.count(0, seconds_per_clock_read)+ started_at = datetime(2026, 9, 22, 10, 0, tzinfo=UTC)++ async def execute_activity(activity: Any, *args: Any, **kwargs: Any) -> Any:+ if activity is retrieve_due_alerts:+ return next(pages, [])+ if activity is admit_alert_evaluations:+ admitted_ids = list(args[0].alert_ids)[: next(capacities, len(args[0].alert_ids))]+ if admitted_ids:+ admitted.append(admitted_ids)+ admission_expiries.append(args[0].expires_at)+ return AdmittedEvaluations(alert_ids=admitted_ids)+ if activity is release_alert_evaluation_slots:+ released.append((list(args[0].alert_ids), args[0].held_until))+ return None+ raise AssertionError(f"unexpected activity {activity}")++ execute_activity_mock = AsyncMock(side_effect=execute_activity)+ start_child = AsyncMock(side_effect=start_child_side_effect)+ sleep = AsyncMock()+ with (+ patch("posthog.temporal.alerts.workflows.temporalio.workflow.patched", return_value=True),+ patch(+ "posthog.temporal.alerts.workflows.temporalio.workflow.now",+ side_effect=lambda: started_at + timedelta(seconds=next(clock)),+ ),+ patch("posthog.temporal.alerts.workflows.temporalio.workflow.execute_activity", new=execute_activity_mock),+ patch("posthog.temporal.alerts.workflows.temporalio.workflow.start_child_workflow", new=start_child),+ patch("posthog.temporal.alerts.workflows.temporalio.workflow.sleep", new=sleep),+ patch("posthog.temporal.alerts.workflows.temporalio.workflow.logger", new=MagicMock()),+ ):+ yield _SchedulerRun(+ execute_activity=execute_activity_mock,+ start_child=start_child,+ sleep=sleep,+ admitted=admitted,+ admission_expiries=admission_expiries,+ released=released,+ )+++def _started_alert_ids(run: _SchedulerRun) -> list[str]:+ return [call.args[1].alert_id for call in run.start_child.await_args_list]++@pytest.mark.parametrize("uses_llm_detector,expected_task_queue",[(False, None), (True, settings.MAX_AI_TASK_QUEUE)],@@ -101,17 +193,61 @@ async def test_check_alert_workflow_evaluates_ai_detectors_on_the_ai_task_queue(@pytest.mark.asyncioasync 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,- ):+ with _admission_scheduler(due_pages=[[]], free_capacity=[]) as run:+ await ScheduleDueAlertChecksWorkflow().run(inputs)++ run.execute_activity.assert_awaited_once()+ assert run.execute_activity.await_args is not None+ assert run.execute_activity.await_args.args[:2] == (retrieve_due_alerts, inputs)+++async def test_schedule_due_alert_checks_admits_only_the_free_capacity() -> None:+ alerts = _alerts(5)++ with _admission_scheduler(due_pages=[alerts], free_capacity=[2, 0, 3]) as run:+ await ScheduleDueAlertChecksWorkflow().run()++ assert _started_alert_ids(run) == [alert.alert_id for alert in alerts]+ assert run.admitted == [[alert.alert_id for alert in alerts[:2]], [alert.alert_id for alert in alerts[2:]]]+ assert run.sleep.await_count == 2+++async def test_schedule_due_alert_checks_keeps_fetching_pages_while_capacity_remains() -> None:+ alerts = _alerts(3)+ inputs = ScheduleDueAlertChecksWorkflowInputs(max_alerts_per_run=2)++ with _admission_scheduler(due_pages=[alerts[:2], alerts[2:], []], free_capacity=[10, 10, 10]) as run:await ScheduleDueAlertChecksWorkflow().run(inputs)- assert execute_activity.await_args is not None- assert execute_activity.await_args.args[1] == inputs+ assert _started_alert_ids(run) == [alert.alert_id for alert in alerts]+ retrievals = [call for call in run.execute_activity.await_args_list if call.args[0] is retrieve_due_alerts]+ assert len(retrievals) == 2+++async def test_schedule_due_alert_checks_leaves_the_rest_to_the_next_run_when_the_budget_ends() -> None:+ with _admission_scheduler(due_pages=[_alerts(2)], free_capacity=[0] * 50, seconds_per_clock_read=10) as run:+ await ScheduleDueAlertChecksWorkflow().run()++ run.start_child.assert_not_awaited()+ assert run.sleep.await_count >= 1+++async def test_schedule_due_alert_checks_replays_the_fan_out_for_runs_started_before_the_patch() -> None:+ with (+ _admission_scheduler(due_pages=[_alerts(2)], free_capacity=[]) as run,+ patch("posthog.temporal.alerts.workflows.temporalio.workflow.patched", return_value=False),+ ):+ await ScheduleDueAlertChecksWorkflow().run()++ assert run.start_child.await_count == 2+ run.execute_activity.assert_awaited_once()+ run.sleep.assert_not_awaited()@pytest.mark.asyncio@@ -147,17 +283,10 @@ async def test_schedule_due_alert_checks_starts_child_with_shared_slo_context()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()- ) as start_child,- ):+ with _admission_scheduler(due_pages=[[alert]], free_capacity=[10]) as run:await ScheduleDueAlertChecksWorkflow().run()+ start_child = run.start_childstart_child.assert_awaited_once()assert start_child.await_args is not Noneinputs = start_child.await_args.args[1]@@ -189,20 +318,16 @@ async def test_schedule_due_alert_checks_skips_already_running_children() -> Noninsight_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()),- ):+ with _admission_scheduler(+ due_pages=[[alert]],+ free_capacity=[10],+ start_child_side_effect=WorkflowAlreadyStartedError("check-alert-alert-1", "check-alert"),+ ) as run:await ScheduleDueAlertChecksWorkflow().run()- start_child.assert_awaited_once()+ run.start_child.assert_awaited_once()+ # The running child released its own slot already, so the reservation this run made goes back.+ assert run.released == [(["alert-1"], run.admission_expiries[0])]@pytest.mark.asyncio@@ -218,21 +343,16 @@ async def test_schedule_due_alert_checks_attempts_remaining_children_before_repofor 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 _admission_scheduler(+ due_pages=[alerts],+ free_capacity=[10],+ start_child_side_effect=[RuntimeError("start failed"), None],+ ) as run:with pytest.raises(ApplicationError, match="alert-0"):await ScheduleDueAlertChecksWorkflow().run()- assert start_child.await_count == 2+ assert run.start_child.await_count == 2+ assert run.released == [(["alert-0"], run.admission_expiries[0])]def test_schedule_is_registered_in_init_schedules():