Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(alerts): retry an insight alert check when the cluster ran out of memory (#81734)

Vasco de Krijgerb96d472eda53
diff --git a/ee/clickhouse/test/test_error.py b/ee/clickhouse/test/test_error.py
index 061779b6bc49..618c60730462 100644
--- a/ee/clickhouse/test/test_error.py
+++ b/ee/clickhouse/test/test_error.py
@@ -3,8 +3,14 @@ import pytest
from clickhouse_driver.errors import ServerException
from posthog.clickhouse.client import sync_execute
-from posthog.errors import clickhouse_error_type, wrap_clickhouse_query_error
-from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded
+from posthog.errors import (
+ CH_TRANSIENT_ERRORS,
+ QueryErrorCategory,
+ classify_query_error,
+ clickhouse_error_type,
+ wrap_clickhouse_query_error,
+)
+from posthog.exceptions import ClickHouseClusterMemoryLimitExceeded, ClickHouseQueryMemoryLimitExceeded
@pytest.mark.parametrize(
@@ -224,3 +230,30 @@ def test_per_query_memory_limit_phrasing_matches_real_clickhouse():
settings={"max_memory_usage": 1_000_000},
)
assert ctx.value.is_per_query_limit
+ assert not isinstance(ctx.value, ClickHouseClusterMemoryLimitExceeded)
+
+
+ "message,expected_per_query",
+ [
+ ("DB::Exception: Memory limit (for query) exceeded: would use 1.00 GiB, maximum: 900.00 MiB.", True),
+ ("DB::Exception: Query memory limit exceeded: would use 1.00 GiB, maximum: 900.00 MiB.", True),
+ (
+ "DB::Exception: (total) memory limit exceeded: would use 270.76 GiB, maximum: 660.53 GiB. : While executing Remote.",
+ False,
+ ),
+ ("DB::Exception: Memory limit (for user) exceeded: would use 1.00 GiB, maximum: 900.00 MiB.", False),
+ ],
+)
+def test_memory_limit_wraps_by_which_ceiling_was_hit(message, expected_per_query):
+ wrapped = wrap_clickhouse_query_error(ServerException(message, code=241))
+ assert isinstance(wrapped, ClickHouseQueryMemoryLimitExceeded)
+ assert wrapped.is_per_query_limit is expected_per_query
+
+ # A ceiling the query did not set is cluster pressure: it lands on the class every retry path
+ # keys off, and classifies as rate-limited capacity rather than a query-performance problem.
+ is_cluster = isinstance(wrapped, ClickHouseClusterMemoryLimitExceeded)
+ assert is_cluster is (not expected_per_query)
+ if is_cluster:
+ assert isinstance(wrapped, CH_TRANSIENT_ERRORS)
+ assert classify_query_error(wrapped) == QueryErrorCategory.RATE_LIMITED
diff --git a/posthog/errors.py b/posthog/errors.py
index 5ee931dad660..b3d21eeb8e59 100644
--- a/posthog/errors.py
+++ b/posthog/errors.py
@@ -10,6 +10,7 @@ from posthog.hogql.errors import ExposedHogQLError
from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
from posthog.exceptions import (
ClickHouseAtCapacity,
+ ClickHouseClusterMemoryLimitExceeded,
ClickHouseEstimatedQueryExecutionTimeTooLong,
ClickHouseQueryMemoryLimitExceeded,
ClickHouseQuerySizeExceeded,
@@ -122,12 +123,15 @@ def wrap_clickhouse_query_error(err: Exception) -> Exception:
elif name == "TIMEOUT_EXCEEDED":
return ClickHouseQueryTimeOut()
elif name == "MEMORY_LIMIT_EXCEEDED":
- memory_error = ClickHouseQueryMemoryLimitExceeded()
# Match the known per-query phrasings ("Memory limit (for query) exceeded" before
# ClickHouse 26, "Query memory limit exceeded" since). Anything else - "(total)",
- # "(for user)", or a future rewording - counts as transient cluster pressure.
- memory_error.is_per_query_limit = "(for query)" in err.message or "Query memory limit exceeded" in err.message
- return memory_error
+ # "(for user)", or a future rewording - counts as transient cluster pressure, which gets
+ # its own class so the CH_TRANSIENT_ERRORS retry paths cover it.
+ if "(for query)" in err.message or "Query memory limit exceeded" in err.message:
+ memory_error = ClickHouseQueryMemoryLimitExceeded()
+ memory_error.is_per_query_limit = True
+ return memory_error
+ return ClickHouseClusterMemoryLimitExceeded()
elif (
name == "SYNTAX_ERROR" and "query size exceeded" in err.message
): # Handle syntax error when "max query size exceeded" in the message
@@ -210,7 +214,9 @@ def classify_query_error(e: Exception) -> QueryErrorCategory:
if isinstance(e, ServerException):
return look_up_clickhouse_error_code_meta(e).get_category()
- if isinstance(e, (ClickHouseAtCapacity, ConcurrencyLimitExceeded)):
+ # Cluster-wide / per-user memory pressure is transient capacity, not a problem with this query,
+ # so it classifies with the other rate-limited capacity errors. Checked before its parent below.
+ if isinstance(e, (ClickHouseAtCapacity, ConcurrencyLimitExceeded, ClickHouseClusterMemoryLimitExceeded)):
return QueryErrorCategory.RATE_LIMITED
if isinstance(
@@ -1027,4 +1033,5 @@ CH_TRANSIENT_ERRORS = (
CHQueryErrorS3FileChangedDuringRead,
CHQueryErrorTableIsReadOnly,
ClickHouseAtCapacity,
+ ClickHouseClusterMemoryLimitExceeded,
)
diff --git a/posthog/exceptions.py b/posthog/exceptions.py
index 3f6c4ee5f1d0..c2ea6aa3c819 100644
--- a/posthog/exceptions.py
+++ b/posthog/exceptions.py
@@ -106,11 +106,22 @@ class ClickHouseQueryMemoryLimitExceeded(APIException):
# CLICKHOUSE_MEMORY_LIMIT_ERROR_CODE constant.
default_code = "clickhouse_memory_limit_exceeded"
default_detail = "This query ran out of memory before it could finish, usually because it's scanning too much data. Try a shorter date range or narrower filters, or see our docs for more ways to speed it up: https://posthog.com/docs/product-analytics/troubleshooting#how-do-i-speed-up-my-insights-and-queries"
- # True only when ClickHouse hit this query's own memory ceiling, meaning a retry will fail
- # the same way. Server-wide and per-user limits are transient cluster pressure.
is_per_query_limit = False
+class ClickHouseClusterMemoryLimitExceeded(ClickHouseQueryMemoryLimitExceeded):
+ """ClickHouse refused the query because the server-wide or per-user memory ceiling was full.
+
+ The query itself can be sized fine, so this belongs to `CH_TRANSIENT_ERRORS` and every retry
+ mechanism that references that tuple can get past it. Subclassing keeps the 513 status and the
+ machine-readable code, but the detail tells the user to wait rather than shrink a fine query.
+ """
+
+ default_detail = (
+ "We're under heavy load right now and couldn't finish this query. Please try again in a few minutes."
+ )
+
+
class ExceptionContext(TypedDict):
request: HttpRequest
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
index f11c2f816a26..13dfc476eeae 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
@@ -19,7 +19,12 @@ from parameterized import parameterized
from posthog.hogql import ast
-from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut
+from posthog.exceptions import (
+ ClickHouseAtCapacity,
+ ClickHouseClusterMemoryLimitExceeded,
+ ClickHouseQueryMemoryLimitExceeded,
+ ClickHouseQueryTimeOut,
+)
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
MAX_REPORT_SECTIONS,
Citation,
@@ -1058,7 +1063,7 @@ class TestExecuteChQueryWithRetry(SimpleTestCase):
[
("network", NetworkError()),
("socket_timeout", SocketTimeoutError()),
- ("cluster_memory_pressure", ClickHouseQueryMemoryLimitExceeded()),
+ ("cluster_memory_pressure", ClickHouseClusterMemoryLimitExceeded()),
]
)
@patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools.time.sleep")
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
index b46e62621d25..4ddef5e3a6d9 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
@@ -26,7 +26,6 @@ from posthog.hogql import ast
from posthog.dataclasses import frozen
from posthog.errors import CH_TRANSIENT_ERRORS
-from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded
from posthog.temporal.ai_observability.eval_reports.output_types import (
EvaluationReportOutcomeDefinition,
get_outcome_definition,
@@ -223,9 +222,7 @@ T = TypeVar("T")
def _is_retriable_ch_error(error: Exception) -> bool:
- return isinstance(error, RETRIABLE_CH_ERRORS) or (
- isinstance(error, ClickHouseQueryMemoryLimitExceeded) and not error.is_per_query_limit
- )
+ return isinstance(error, RETRIABLE_CH_ERRORS)
def _execute_ch_query_with_retry(
diff --git a/posthog/temporal/alerts/__init__.py b/posthog/temporal/alerts/__init__.py
index 357bf9e2c4cf..b089a2635742 100644
--- a/posthog/temporal/alerts/__init__.py
+++ b/posthog/temporal/alerts/__init__.py
@@ -3,6 +3,7 @@ from posthog.temporal.alerts.activities import (
evaluate_alert,
notify_alert,
prepare_alert,
+ record_failed_evaluation,
retrieve_due_alerts,
run_investigation_safety_net,
)
@@ -25,6 +26,7 @@ ACTIVITIES = [
prepare_alert,
evaluate_alert,
notify_alert,
+ record_failed_evaluation,
run_investigation_safety_net,
cleanup_alert_checks,
]
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index de689416c512..7c4228ec7aec 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -42,6 +42,8 @@ from posthog.temporal.alerts.types import (
PrepareAction,
PrepareAlertActivityInputs,
PrepareAlertResult,
+ RecordFailedEvaluationActivityInputs,
+ RecordFailedEvaluationResult,
SkipReason,
)
from posthog.temporal.common.heartbeat import Heartbeater
@@ -200,6 +202,15 @@ async def prepare_alert(inputs: PrepareAlertActivityInputs) -> PrepareAlertResul
return await _prepare()
+def _write_errored_alert_check(alert: AlertConfiguration, error: dict) -> tuple[AlertCheck, bool]:
+ """Write an errored AlertCheck for an already-locked alert and return it with the notify decision.
+
+ Both evaluate_alert's failure path and the retry-exhausted record_failed_evaluation activity go
+ through here, so the errored-check write stays in one place.
+ """
+ return add_alert_check(alert, None, None, error)
+
+
@temporalio.activity.defn
async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertResult:
"""Run the insight ClickHouse query, apply the state machine, persist an AlertCheck row."""
@@ -291,6 +302,23 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe
)
error = {"message": str(err), "traceback": traceback.format_exc()}
+ # A non-transient failure: write the errored check and return. Transient errors were
+ # re-raised above for the retry policy, and the investigation gating below only fires on a
+ # FIRING transition, so the errored path skips it.
+ if error is not None:
+ with transaction.atomic():
+ alert = (
+ AlertConfiguration.objects.select_for_update(of=("self",))
+ .select_related("insight", "team", "threshold")
+ .get(id=inputs.alert_id)
+ )
+ alert_check, should_notify = _write_errored_alert_check(alert, error)
+ return EvaluateAlertResult(
+ alert_check_id=str(alert_check.id),
+ should_notify=should_notify,
+ new_state=AlertState.ERRORED,
+ )
+
anomaly_scores = alert_evaluation_result.anomaly_scores if alert_evaluation_result else None
triggered_points = alert_evaluation_result.triggered_points if alert_evaluation_result else None
triggered_dates = alert_evaluation_result.triggered_dates if alert_evaluation_result else None
@@ -355,6 +383,55 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe
return await _evaluate()
+async def record_failed_evaluation(inputs: RecordFailedEvaluationActivityInputs) -> RecordFailedEvaluationResult:
+ """Persist an errored AlertCheck for an evaluation that never got to write one itself.
+
+ evaluate_alert re-raises transient ClickHouse errors so its retry policy can get past a busy
+ cluster. Nothing has written an AlertCheck by the time those attempts run out, and next_check_at
+ is still in the past, so the one-minute sweep would start the whole chain over again: an alert
+ whose query fails every time would run forever, and its owner would never be told. Recording the
+ failure here advances next_check_at to the alert's normal cadence slot, which caps a permanently
+ failing alert at one chain of attempts per cadence period.
+ """
+
+ @database_sync_to_async(thread_sensitive=False)
+ def _record() -> RecordFailedEvaluationResult:
+ try:
+ with transaction.atomic():
+ alert = (
+ AlertConfiguration.objects.select_for_update(of=("self",))
+ .select_related("insight", "team", "threshold")
+ .get(id=inputs.alert_id)
+ )
+ # Disabling an alert mid-check makes evaluate_alert raise a non-retryable "disabled
+ # between prepare and evaluate" error into this path. That is a normal user action,
+ # not an alert failure, so it must not gain an errored check or email subscribers.
+ if not alert.enabled:
+ logger.info("alerts.skip_failed_evaluation_disabled", alert_id=inputs.alert_id)
+ return RecordFailedEvaluationResult()
+ # add_alert_check advances next_check_at, so skipping once it is in the future keeps a
+ # committed-but-undelivered retry from writing a duplicate errored check. Best effort:
+ # a real-time alert lagging past its short cadence can still write one, but the state
+ # machine keeps that from sending a duplicate notification.
+ if alert.next_check_at is not None and alert.next_check_at > datetime.now(UTC):
+ return RecordFailedEvaluationResult()
+ alert_check, should_notify = _write_errored_alert_check(alert, {"message": inputs.error_message})
+ except AlertConfiguration.DoesNotExist:
+ logger.warning("Alert gone before its failure could be recorded", alert_id=inputs.alert_id)
+ return RecordFailedEvaluationResult()
+
+ logger.warning(
+ "alerts.recorded_failed_evaluation",
+ alert_id=inputs.alert_id,
+ alert_check_id=str(alert_check.id),
+ )
+ return RecordFailedEvaluationResult(alert_check_id=str(alert_check.id), should_notify=should_notify)
+
+ async with Heartbeater():
+ return await _record()
+
+
def dispatch_alert_firing_realtime_notification(alert: AlertConfiguration, breaches: list[str]) -> None:
"""Fan out one realtime in-app notification per subscribed user when an alert fires.
diff --git a/posthog/temporal/alerts/retry_policy.py b/posthog/temporal/alerts/retry_policy.py
index 60696fc7a751..2cf601f486cf 100644
--- a/posthog/temporal/alerts/retry_policy.py
+++ b/posthog/temporal/alerts/retry_policy.py
@@ -7,6 +7,11 @@ from posthog.schema_enums import AlertCalculationInterval
from products.exports.backend.tasks.failure_handler import USER_QUERY_ERROR_NAMES
+# A user's query error won't clear on retry, so evaluate_alert fails fast on it. Temporal matches
+# non-retryable types by exact name, so transient cluster memory pressure — a distinct subclass
+# name — stays retryable without being listed here. Sorted for a stable order across processes.
+_EVALUATE_NON_RETRYABLE_ERROR_NAMES = sorted(USER_QUERY_ERROR_NAMES)
+
ALERT_PREPARE_RETRY_POLICY = RetryPolicy(
initial_interval=dt.timedelta(seconds=1),
maximum_interval=dt.timedelta(seconds=10),
@@ -19,7 +24,7 @@ ALERT_EVALUATE_RETRY_POLICY = RetryPolicy(
maximum_interval=dt.timedelta(seconds=30),
backoff_coefficient=2.0,
maximum_attempts=5,
- non_retryable_error_types=list(USER_QUERY_ERROR_NAMES),
+ non_retryable_error_types=_EVALUATE_NON_RETRYABLE_ERROR_NAMES,
)
ALERT_NOTIFY_RETRY_POLICY = RetryPolicy(
@@ -54,7 +59,7 @@ _REAL_TIME_EVALUATE_RETRY_POLICY = RetryPolicy(
maximum_interval=dt.timedelta(seconds=10),
backoff_coefficient=2.0,
maximum_attempts=2,
- non_retryable_error_types=list(USER_QUERY_ERROR_NAMES),
+ non_retryable_error_types=_EVALUATE_NON_RETRYABLE_ERROR_NAMES,
)
# workflow_execution covers prepare (2 min) + evaluate at its schedule_to_close cap
diff --git a/posthog/temporal/alerts/types.py b/posthog/temporal/alerts/types.py
index 8dc6be90c7bc..eb1cb657f80b 100644
--- a/posthog/temporal/alerts/types.py
+++ b/posthog/temporal/alerts/types.py
@@ -57,6 +57,19 @@ class EvaluateAlertActivityInputs:
alert_id: str
[email protected](frozen=True)
+class RecordFailedEvaluationActivityInputs:
+ alert_id: str
+ error_message: str
+
+
[email protected](frozen=True)
+class RecordFailedEvaluationResult:
+ # None when there is no alert left to record against, e.g. it was deleted mid-workflow.
+ alert_check_id: str | None = None
+ should_notify: bool = False
+
+
@dataclasses.dataclass(frozen=True)
class EvaluateAlertResult:
# AlertCheck PK is a UUIDT; stringified here so Temporal's JSON codec can pass it through.
diff --git a/posthog/temporal/alerts/workflows.py b/posthog/temporal/alerts/workflows.py
index 899720913b67..4b76a553c44f 100644
--- a/posthog/temporal/alerts/workflows.py
+++ b/posthog/temporal/alerts/workflows.py
@@ -16,18 +16,26 @@ from posthog.temporal.alerts.activities import (
evaluate_alert,
notify_alert,
prepare_alert,
+ record_failed_evaluation,
retrieve_due_alerts,
run_investigation_safety_net,
)
-from posthog.temporal.alerts.retry_policy import ALERT_NOTIFY_RETRY_POLICY, ALERT_PREPARE_RETRY_POLICY, alert_timeouts
+from posthog.temporal.alerts.retry_policy import (
+ ALERT_NOTIFY_RETRY_POLICY,
+ ALERT_PREPARE_RETRY_POLICY,
+ AlertTimeouts,
+ alert_timeouts,
+)
from posthog.temporal.alerts.types import (
CheckAlertWorkflowInputs,
EvaluateAlertActivityInputs,
NotifyAlertActivityInputs,
PrepareAction,
PrepareAlertActivityInputs,
+ RecordFailedEvaluationActivityInputs,
)
from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.common.errors import MAX_ERROR_MESSAGE_CHARS, truncate_for_temporal_payload, unwrap_temporal_cause
with temporalio.workflow.unsafe.imports_passed_through():
from django.conf import settings
@@ -143,14 +151,32 @@ class CheckAlertWorkflow(PostHogWorkflow):
return
# Phase 2 — evaluate: CH query + state machine + persist AlertCheck
- evaluation = await temporalio.workflow.execute_activity(
- evaluate_alert,
- EvaluateAlertActivityInputs(alert_id=inputs.alert_id),
- start_to_close_timeout=timeouts.evaluate_start_to_close,
- schedule_to_close_timeout=timeouts.activity_schedule_to_close,
- heartbeat_timeout=timeouts.heartbeat_timeout,
- retry_policy=timeouts.evaluate_retry_policy,
- )
+ try:
+ evaluation = await temporalio.workflow.execute_activity(
+ evaluate_alert,
+ EvaluateAlertActivityInputs(alert_id=inputs.alert_id),
+ start_to_close_timeout=timeouts.evaluate_start_to_close,
+ schedule_to_close_timeout=timeouts.activity_schedule_to_close,
+ heartbeat_timeout=timeouts.heartbeat_timeout,
+ retry_policy=timeouts.evaluate_retry_policy,
+ )
+ except Exception as evaluation_error:
+ # Transient ClickHouse errors re-raise so the retry policy can get past a busy
+ # cluster. Once those run out no AlertCheck exists and next_check_at is still in the
+ # past, so record the failure to stop the sweep restarting the chain forever. Set
+ # the state first so the SLO completion event still attributes this as errored.
+ # (No workflow.patched guard needed: this only runs on the path that fails the
+ # workflow, so no open execution has already replayed past it.)
+ new_state = AlertState.ERRORED
+ try:
+ await self._record_failed_evaluation(inputs, timeouts, evaluation_error)
+ except Exception:
+ # A failure while recording must not replace the original evaluation error: the
+ # bare raise below still re-raises evaluation_error, not this one.
+ temporalio.workflow.logger.warning(
+ "alerts.record_failed_evaluation_failed", extra={"alert_id": inputs.alert_id}
+ )
+ raise
new_state = evaluation.new_state
# Phase 3 — notify (optional)
@@ -206,6 +232,38 @@ class CheckAlertWorkflow(PostHogWorkflow):
if caught_error:
raise caught_error
+ async def _record_failed_evaluation(
+ self,
+ inputs: CheckAlertWorkflowInputs,
+ timeouts: AlertTimeouts,
+ evaluation_error: BaseException,
+ ) -> None:
+ """Write the errored AlertCheck the failed evaluation never got to write, then notify."""
+ # Unwrap Temporal's ActivityError plumbing to the underlying reason the owner sees in the
+ # error email, and bound it so a large trace can't blow the payload limit or the DB row.
+ cause = unwrap_temporal_cause(evaluation_error)
+ message = cause.message if cause is not None else str(evaluation_error)
+ message = truncate_for_temporal_payload(message, MAX_ERROR_MESSAGE_CHARS)
+ recorded = await temporalio.workflow.execute_activity(
+ record_failed_evaluation,
+ RecordFailedEvaluationActivityInputs(alert_id=inputs.alert_id, error_message=message),
+ start_to_close_timeout=dt.timedelta(minutes=1),
+ retry_policy=ALERT_PREPARE_RETRY_POLICY,
+ )
+ if not recorded.should_notify or not recorded.alert_check_id:
+ return
+
+ await temporalio.workflow.execute_activity(
+ notify_alert,
+ NotifyAlertActivityInputs(
+ alert_id=inputs.alert_id,
+ alert_check_id=recorded.alert_check_id,
+ breaches=None,
+ ),
+ start_to_close_timeout=timeouts.notify_start_to_close,
+ retry_policy=ALERT_NOTIFY_RETRY_POLICY,
+ )
+
@temporalio.workflow.defn(name="run-investigation-safety-net")
class RunInvestigationSafetyNetWorkflow(PostHogWorkflow):
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index 5da4aee20fe4..4255b2827481 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -22,7 +22,11 @@ from posthog.schema import (
)
from posthog.constants import AvailableFeature
-from posthog.exceptions import ClickHouseAtCapacity
+from posthog.exceptions import (
+ ClickHouseAtCapacity,
+ ClickHouseClusterMemoryLimitExceeded,
+ ClickHouseQueryMemoryLimitExceeded,
+)
from posthog.models import User
from posthog.slo.types import SloOperation, SloOutcome
from posthog.tasks.alerts.utils import (
@@ -30,12 +34,20 @@ from posthog.tasks.alerts.utils import (
get_alert_error_notification_recipients,
send_notifications_for_errors,
)
-from posthog.temporal.alerts.activities import cleanup_alert_checks, evaluate_alert, notify_alert, prepare_alert
+from posthog.temporal.alerts.activities import (
+ cleanup_alert_checks,
+ evaluate_alert,
+ notify_alert,
+ prepare_alert,
+ record_failed_evaluation,
+)
+from posthog.temporal.alerts.retry_policy import alert_timeouts
from posthog.temporal.alerts.types import (
EvaluateAlertActivityInputs,
NotifyAlertActivityInputs,
PrepareAction,
PrepareAlertActivityInputs,
+ RecordFailedEvaluationActivityInputs,
SkipReason,
)
@@ -57,6 +69,12 @@ def _default_threshold_configuration() -> dict:
return {"type": "absolute", "bounds": {"upper": 100.0}}
+def _memory_limit_error() -> ClickHouseQueryMemoryLimitExceeded:
+ error = ClickHouseQueryMemoryLimitExceeded()
+ error.is_per_query_limit = True
+ return error
+
+
async def _create_alert(
ateam,
*,
@@ -444,21 +462,42 @@ class TestEvaluateAlert:
assert "2 numeric columns" in reason
assert targets # the subscribed owner's email
- async def test_evaluate_reraises_ch_transient_error(self, alert) -> None:
- # Transient CH errors bubble up so Temporal's retry policy handles them.
- # Capacity errors (codes 202/439) surface as ClickHouseAtCapacity, so that's what we simulate.
+ # Transient CH errors bubble up so Temporal's retry policy handles them.
+ # 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.
+ @pytest.mark.parametrize(
+ "error_class",
+ [ClickHouseAtCapacity, ClickHouseClusterMemoryLimitExceeded],
+ )
+ async def test_evaluate_reraises_ch_transient_error(self, alert, error_class) -> None:
with patch(
"posthog.temporal.alerts.activities.check_alert_for_insight",
- side_effect=ClickHouseAtCapacity(),
+ side_effect=error_class(),
):
env = ActivityEnvironment()
- with pytest.raises(ClickHouseAtCapacity):
+ with pytest.raises(error_class):
await env.run(evaluate_alert, EvaluateAlertActivityInputs(alert_id=str(alert.id)))
# No AlertCheck should have been written
count = await sync_to_async(AlertCheck.objects.filter(alert_configuration=alert).count)()
assert count == 0
+ async def test_evaluate_records_error_when_the_query_ran_out_of_memory(self, alert) -> None:
+ # The query hit its own memory ceiling, so retrying it fails identically. It has to stay on
+ # the recorded-error path rather than joining the transient class above.
+ with patch(
+ "posthog.temporal.alerts.activities.check_alert_for_insight",
+ side_effect=_memory_limit_error(),
+ ):
+ env = ActivityEnvironment()
+ result = await env.run(evaluate_alert, EvaluateAlertActivityInputs(alert_id=str(alert.id)))
+
+ assert result.new_state == AlertState.ERRORED
+
+ check = await sync_to_async(AlertCheck.objects.get)(pk=result.alert_check_id)
+ assert check.error is not None
+
async def test_evaluate_non_retryable_when_alert_deleted_mid_workflow(self) -> None:
env = ActivityEnvironment()
with pytest.raises(ApplicationError) as exc_info:
@@ -474,6 +513,29 @@ class TestEvaluateAlert:
assert exc_info.value.non_retryable is True
+class TestRecordFailedEvaluation:
+ async def test_skips_disabled_alert_without_recording_or_notifying(self, alert_with_user) -> None:
+ # Disabling an alert mid-check makes evaluate_alert raise into this activity. A normal
+ # disable must not become an errored check or a "could not evaluate" email to subscribers.
+ await sync_to_async(AlertConfiguration.objects.filter(pk=alert_with_user.id).update)(enabled=False)
+
+ env = ActivityEnvironment()
+ result = await env.run(
+ record_failed_evaluation,
+ RecordFailedEvaluationActivityInputs(
+ alert_id=str(alert_with_user.id),
+ error_message="Alert disabled between prepare and evaluate",
+ ),
+ )
+
+ assert result.alert_check_id is None
+ assert result.should_notify is False
+ count = await sync_to_async(AlertCheck.objects.filter(alert_configuration=alert_with_user).count)()
+ assert count == 0
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
class TestNotifyAlert:
@@ -817,6 +879,15 @@ class TestNotifyAlert:
assert refreshed.targets_notified == {"users": ["[email protected]"]}
[email protected]("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, and
+ # the cluster class subclasses one of them. Listing it there too would stop every retry, so the
+ # re-raise out of evaluate_alert would fail the workflow on the first attempt instead.
+ policy = alert_timeouts(calculation_interval).evaluate_retry_policy
+ assert ClickHouseClusterMemoryLimitExceeded.__name__ not in (policy.non_retryable_error_types or [])
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
class TestCleanupAlertChecks:
diff --git a/posthog/temporal/tests/test_alerts_workflows.py b/posthog/temporal/tests/test_alerts_workflows.py
index 6ccf31e13805..9b1dd832eac4 100644
--- a/posthog/temporal/tests/test_alerts_workflows.py
+++ b/posthog/temporal/tests/test_alerts_workflows.py
@@ -1,5 +1,7 @@
import uuid
from collections.abc import Callable
+from contextlib import nullcontext
+from datetime import UTC, datetime
from typing import Any
import pytest
@@ -9,6 +11,7 @@ from django.conf import settings
import pytest_asyncio
from asgiref.sync import sync_to_async
+from temporalio.client import WorkflowFailureError
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
@@ -22,10 +25,12 @@ from posthog.schema import (
TrendsQuery,
)
+from posthog.exceptions import ClickHouseClusterMemoryLimitExceeded
from posthog.models import User
from posthog.slo.types import SloArea, SloConfig, SloOperation, SloOutcome
from posthog.tasks.alerts.utils import AlertEvaluationResult
-from posthog.temporal.alerts.activities import evaluate_alert, notify_alert, prepare_alert
+from posthog.temporal.alerts.activities import evaluate_alert, notify_alert, prepare_alert, record_failed_evaluation
+from posthog.temporal.alerts.retry_policy import ALERT_EVALUATE_RETRY_POLICY
from posthog.temporal.alerts.schedule import create_schedule_due_alert_checks_schedule
from posthog.temporal.alerts.types import AlertInfo, CheckAlertWorkflowInputs, SkipReason
from posthog.temporal.alerts.workflows import CheckAlertWorkflow, ScheduleDueAlertChecksWorkflow
@@ -34,7 +39,12 @@ from posthog.temporal.common.slo_interceptor import SloInterceptor
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, Threshold
from products.product_analytics.backend.models.insight import Insight
-CHECK_ALERT_ACTIVITIES: list[Callable[..., Any]] = [prepare_alert, evaluate_alert, notify_alert]
+CHECK_ALERT_ACTIVITIES: list[Callable[..., Any]] = [
+ prepare_alert,
+ evaluate_alert,
+ notify_alert,
+ record_failed_evaluation,
+]
@pytest.mark.asyncio
@@ -291,25 +301,55 @@ async def test_check_alert_workflow_skip_short_circuits_before_evaluate(
assert "alert_state" not in completed_props
+class _PermanentEvaluationError(Exception):
+ pass
+
+
+ "error,expected_attempts,expect_workflow_failure,expected_outcome",
+ [
+ pytest.param(
+ ClickHouseClusterMemoryLimitExceeded(),
+ ALERT_EVALUATE_RETRY_POLICY.maximum_attempts,
+ True,
+ SloOutcome.FAILURE,
+ id="transient_retried_to_exhaustion",
+ ),
+ pytest.param(
+ _PermanentEvaluationError("insight query broken"),
+ 1,
+ False,
+ SloOutcome.SUCCESS,
+ id="non_transient_not_retried",
+ ),
+ ],
+)
@patch("posthog.slo.events.posthoganalytics")
@pytest.mark.asyncio
@pytest.mark.django_db(transaction=True)
-async def test_check_alert_workflow_records_errored_check_on_permanent_evaluation_failure(
+async def test_check_alert_workflow_records_errored_check_when_evaluation_keeps_failing(
mock_slo_analytics: MagicMock,
alert_with_subscriber: AlertConfiguration,
+ error: Exception,
+ expected_attempts: int,
+ expect_workflow_failure: bool,
+ expected_outcome: SloOutcome,
) -> None:
- class PermanentError(Exception):
- pass
-
+ # However evaluation fails, the workflow must leave an errored check, notify the owner, and push
+ # next_check_at into the future so the one-minute sweep doesn't restart the chain forever.
+ # Transient cluster pressure re-raises and exhausts the retry policy before the workflow records
+ # the failure and fails; a user's query error is recorded inline on the first attempt.
+ failure_ctx = pytest.raises(WorkflowFailureError) if expect_workflow_failure else nullcontext()
with (
patch(
"posthog.temporal.alerts.activities.check_alert_for_insight",
- side_effect=PermanentError("insight query broken"),
- ),
+ side_effect=error,
+ ) as mock_ch_query,
patch(
"posthog.tasks.alerts.utils.send_notifications_for_errors",
return_value=["[email protected]"],
) as mock_send_errors,
+ failure_ctx,
):
await _run_check_alert_workflow(
alert_id=str(alert_with_subscriber.id),
@@ -318,24 +358,23 @@ async def test_check_alert_workflow_records_errored_check_on_permanent_evaluatio
insight_id=alert_with_subscriber.insight_id,
)
+ assert mock_ch_query.call_count == expected_attempts
+
check = await sync_to_async(
lambda: AlertCheck.objects.filter(alert_configuration=alert_with_subscriber).order_by("-created_at").first()
)()
assert check is not None
assert check.state == AlertState.ERRORED
- assert check.error is not None
- assert "insight query broken" in check.error["message"]
+ mock_send_errors.assert_called_once()
- # Evaluate-time errors are transient — alert stays enabled so next run retries.
- # Only prepare-time validate_alert_config failures call disable_invalid_alert.
+ # Evaluate-time failures keep the alert enabled (only prepare-time config errors disable it).
refreshed = await sync_to_async(AlertConfiguration.objects.get)(pk=alert_with_subscriber.pk)
assert refreshed.enabled is True
-
- mock_send_errors.assert_called_once()
+ assert refreshed.next_check_at is not None
+ assert refreshed.next_check_at > datetime.now(UTC)
completed_props = _completed_slo_props(mock_slo_analytics)
- # Errored evaluation = degraded alert, not a workflow failure → SLO stays SUCCESS.
- assert completed_props["outcome"] == SloOutcome.SUCCESS
+ assert completed_props["outcome"] == expected_outcome
assert completed_props["alert_state"] == AlertState.ERRORED