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): send the alert firing signal after notify (#129365)

posthog[bot]532506403c8b
diff --git a/posthog/temporal/alerts/__init__.py b/posthog/temporal/alerts/__init__.py
index bd1e14959451..e748db2ed850 100644
--- a/posthog/temporal/alerts/__init__.py
+++ b/posthog/temporal/alerts/__init__.py
@@ -1,6 +1,7 @@
from posthog.temporal.alerts.activities import (
admit_alert_evaluations,
cleanup_alert_checks,
+ emit_alert_firing_signal,
evaluate_alert,
notify_alert,
prepare_alert,
@@ -34,6 +35,7 @@ ACTIVITIES = [
prepare_alert,
evaluate_alert,
notify_alert,
+ emit_alert_firing_signal,
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 929e7c969b49..6c3d834eff65 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -62,6 +62,7 @@ from posthog.temporal.alerts.admission import (
)
from posthog.temporal.alerts.alert_firing_signal import (
AlertFiringSignal,
+ alert_firing_skip_reason,
dispatch_alert_firing_signal,
prepare_alert_firing_signal,
)
@@ -76,6 +77,7 @@ from posthog.temporal.alerts.types import (
AdmitEvaluationsInputs,
AdmittedEvaluations,
AlertInfo,
+ EmitAlertFiringSignalActivityInputs,
EvaluateAlertActivityInputs,
EvaluateAlertResult,
NotifyAlertActivityInputs,
@@ -647,15 +649,12 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe
# replaced learns it only on its next slot refresh, so a query that finishes before then still
# records.
stopping = threading.Event()
- # Set by the evaluation thread, and dispatched once that thread returns.
- firing_signal: AlertFiringSignal | None = None
def _stop_if_cancelled() -> None:
if stopping.is_set():
raise _EvaluationStopped()
def _evaluate(alert: AlertConfiguration) -> EvaluateAlertResult:
- nonlocal firing_signal
_stop_if_cancelled()
evaluated_alert = alert
evaluated_fingerprint = _evaluation_fingerprint(alert)
@@ -791,8 +790,8 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe
# recorded on the check and can't affect the alert outcome.
if should_run_metrics_investigation:
run_metrics_alert_investigation(alert, alert_check)
- firing_signal = prepare_alert_firing_signal(
- alert, alert_check, previous_state=previous_state, breaches=breaches
+ signal_candidate = (
+ alert_firing_skip_reason(alert, previous_state=previous_state, new_state=alert_check.state) is None
)
return EvaluateAlertResult(
@@ -803,6 +802,8 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe
should_start_investigation=should_start_investigation,
should_gate_notification=should_gate_notification,
investigation_user_id=alert.created_by_id if should_start_investigation else None,
+ signal_candidate=signal_candidate,
+ previous_state=AlertState(previous_state),
)
team_id = inputs.team_id
@@ -828,11 +829,7 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe
thread = asyncio.ensure_future(
database_sync_to_async(_evaluate, thread_sensitive=False, executor=executor)(alert)
)
- result = await asyncio.shield(thread)
- if firing_signal is not None:
- # Here, not in the thread: emit_signal needs the default executor that the thread runs on.
- await dispatch_alert_firing_signal(firing_signal)
- return result
+ return await asyncio.shield(thread)
timeouts = alert_timeouts(inputs.calculation_interval)
@@ -879,6 +876,41 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe
)
+def _prepare_firing_signal(inputs: EmitAlertFiringSignalActivityInputs) -> AlertFiringSignal | None:
+ alert_check = (
+ AlertCheck.objects.select_related("alert_configuration__insight", "alert_configuration__team")
+ .filter(
+ id=inputs.alert_check_id,
+ alert_configuration_id=inputs.alert_id,
+ alert_configuration__team_id=inputs.team_id,
+ )
+ .first()
+ )
+ if alert_check is None:
+ return None
+ alert = alert_check.alert_configuration
+ # The evaluation ruled out a platform-owned alert. This covers an owner change since then.
+ if not alert.enabled or alert.platform_owned:
+ return None
+ return prepare_alert_firing_signal(
+ alert, alert_check, previous_state=inputs.previous_state, breaches=inputs.breaches
+ )
+
+
+async def emit_alert_firing_signal(inputs: EmitAlertFiringSignalActivityInputs) -> None:
+ """Send the inbox signal for a check that started a firing episode.
+
+ The workflow runs it after the notification, so a slow or stuck send never delays the
+ notification. It skips a deleted or disabled alert, and runs the gates again against the
+ current alert, so an edit since the evaluation can still stop the signal.
+ """
+ signal = await database_sync_to_async(_prepare_firing_signal, thread_sensitive=False)(inputs)
+ if signal is not None:
+ # On the event loop, not in the thread: emit_signal needs the default executor.
+ await dispatch_alert_firing_signal(signal)
+
+
def _lock_evaluation_alert(*, alert_id: str, team_id: int, insight_id: int) -> AlertConfiguration | None:
# Call inside transaction.atomic(). Insight deletion takes the same lock order.
if not lock_insight_for_evaluation(insight_id=insight_id, team_id=team_id):
diff --git a/posthog/temporal/alerts/alert_firing_signal.py b/posthog/temporal/alerts/alert_firing_signal.py
index db2258596627..6673927de402 100644
--- a/posthog/temporal/alerts/alert_firing_signal.py
+++ b/posthog/temporal/alerts/alert_firing_signal.py
@@ -37,6 +37,9 @@ _ALL_FIRING_ALERTS = "all_firing_alerts"
# run, and a team with many noisy alerts must not flood its inbox or our spend.
CAP_BUDGET = Budget(burst=20, per_hour=1)
+# `emit_signal` has no time limit of its own, and its guidance check can take about 20 seconds.
+EMISSION_TIMEOUT_SECONDS = 30
+
# Same margin under the facade's description token limit as the investigation signal.
_MAX_DESCRIPTION_CHARS = 3000
_MAX_BREACHES = 20
@@ -88,7 +91,7 @@ def prepare_alert_firing_signal(
) -> AlertFiringSignal | None:
"""Run the gates and build the signal, or return None to skip it. Never raises.
- Call it in the evaluation thread, after the check is committed and outside the alert row lock.
+ Call it from a thread, after the check is committed and outside the alert row lock.
It charges the cap, and `dispatch_alert_firing_signal` refunds the charge when nothing is sent.
"""
try:
@@ -106,23 +109,29 @@ def prepare_alert_firing_signal(
async def dispatch_alert_firing_signal(signal: AlertFiringSignal) -> bool:
"""Send a prepared signal. Returns whether it was dispatched. Never raises.
- Await it from the activity's event loop after the evaluation thread returns. `emit_signal` runs
- sync work on the default executor, so a call that blocks an evaluation thread on it can deadlock
- once every executor thread waits the same way. A failure never changes the committed check.
+ Await it from the activity's event loop, not from a thread. `emit_signal` runs sync work on the
+ default executor, so a call that blocks an executor thread on it can deadlock once every executor
+ thread waits the same way. A failure never changes the committed check.
"""
source_id = f"{signal.alert_id}:{signal.alert_check_id}"
try:
- dispatched = await emit_signal(
- team=signal.team,
- source_product=SIGNAL_SOURCE_PRODUCT,
- source_type=SIGNAL_SOURCE_TYPE,
- source_id=source_id,
- # Same key on a retried evaluation, so one episode starts at most one emission.
- idempotency_key=source_id,
- description=signal.description,
- weight=1,
- extra=signal.extra,
- )
+ async with asyncio.timeout(EMISSION_TIMEOUT_SECONDS):
+ dispatched = await emit_signal(
+ team=signal.team,
+ source_product=SIGNAL_SOURCE_PRODUCT,
+ source_type=SIGNAL_SOURCE_TYPE,
+ source_id=source_id,
+ # Same key on a retried attempt, so one episode starts at most one emission.
+ idempotency_key=source_id,
+ description=signal.description,
+ weight=1,
+ extra=signal.extra,
+ )
+ except asyncio.CancelledError:
+ # A cancelled attempt sends nothing, so it gives back its token. The shield lets the refund
+ # finish if a second cancel arrives while it runs.
+ await asyncio.shield(asyncio.to_thread(refund, cap_key(signal.team.id), CAP_BUDGET))
+ raise
except Exception:
logger.exception(
"alert_firing.signal_emission_failed", alert_id=signal.alert_id, alert_check_id=signal.alert_check_id
diff --git a/posthog/temporal/alerts/retry_policy.py b/posthog/temporal/alerts/retry_policy.py
index ea50dd6a1518..7ab8cb14a3a6 100644
--- a/posthog/temporal/alerts/retry_policy.py
+++ b/posthog/temporal/alerts/retry_policy.py
@@ -34,6 +34,17 @@ ALERT_NOTIFY_RETRY_POLICY = RetryPolicy(
maximum_attempts=5,
)
+# The inbox signal is best effort. Few attempts and short clocks keep a stuck send from holding the
+# check open; the attempt clock leaves room for the send's own time limit and the cap refund.
+ALERT_SIGNAL_RETRY_POLICY = RetryPolicy(
+ initial_interval=dt.timedelta(seconds=2),
+ maximum_interval=dt.timedelta(seconds=10),
+ backoff_coefficient=2.0,
+ maximum_attempts=2,
+)
+ALERT_SIGNAL_START_TO_CLOSE = dt.timedelta(seconds=45)
+ALERT_SIGNAL_SCHEDULE_TO_CLOSE = dt.timedelta(minutes=2)
+
@dataclasses.dataclass(frozen=True)
class SlotLease:
@@ -80,7 +91,7 @@ class AlertTimeouts:
evaluate_retry_policy: RetryPolicy,
) -> "AlertTimeouts":
return cls(
- workflow_execution=prepare + evaluate + notify,
+ workflow_execution=prepare + evaluate + notify + ALERT_SIGNAL_SCHEDULE_TO_CLOSE,
activity_schedule_to_close=evaluate,
evaluate_start_to_close=evaluate,
evaluate_retry_policy=evaluate_retry_policy,
diff --git a/posthog/temporal/alerts/types.py b/posthog/temporal/alerts/types.py
index fa2ea4db13c3..714af63d23a9 100644
--- a/posthog/temporal/alerts/types.py
+++ b/posthog/temporal/alerts/types.py
@@ -141,6 +141,21 @@ class EvaluateAlertResult:
# Persisted alert.created_by — the investigation workflow uses this to attribute
# the resulting Notebook. Optional because legacy alerts may not have it.
investigation_user_id: int | None = None
+ # The check starts a firing episode the agent does not investigate. The workflow sends its inbox
+ # signal last, so the send never delays the notification.
+ signal_candidate: bool = False
+ # The alert state before this check. The signal phase reads it to tell a new episode from one
+ # that an errored check interrupted.
+ previous_state: AlertState | None = None
+
+
[email protected](frozen=True)
+class EmitAlertFiringSignalActivityInputs:
+ alert_id: str
+ alert_check_id: str
+ team_id: int
+ previous_state: AlertState
+ breaches: list[str] | None = None
@dataclasses.dataclass(frozen=True)
diff --git a/posthog/temporal/alerts/workflows.py b/posthog/temporal/alerts/workflows.py
index 0d68c43856e0..09f681fd241e 100644
--- a/posthog/temporal/alerts/workflows.py
+++ b/posthog/temporal/alerts/workflows.py
@@ -13,6 +13,7 @@ from posthog.slo.types import SloArea, SloConfig, SloOperation
from posthog.temporal.alerts.activities import (
admit_alert_evaluations,
cleanup_alert_checks,
+ emit_alert_firing_signal,
evaluate_alert,
notify_alert,
prepare_alert,
@@ -24,6 +25,9 @@ from posthog.temporal.alerts.activities import (
from posthog.temporal.alerts.retry_policy import (
ALERT_NOTIFY_RETRY_POLICY,
ALERT_PREPARE_RETRY_POLICY,
+ ALERT_SIGNAL_RETRY_POLICY,
+ ALERT_SIGNAL_SCHEDULE_TO_CLOSE,
+ ALERT_SIGNAL_START_TO_CLOSE,
AlertTimeouts,
alert_timeouts,
)
@@ -31,6 +35,7 @@ from posthog.temporal.alerts.types import (
AdmitEvaluationsInputs,
AlertInfo,
CheckAlertWorkflowInputs,
+ EmitAlertFiringSignalActivityInputs,
EvaluateAlertActivityInputs,
NotifyAlertActivityInputs,
PrepareAction,
@@ -52,6 +57,8 @@ with temporalio.workflow.unsafe.imports_passed_through():
# 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"
+# Runs started before the deploy sent the inbox signal from the evaluate activity.
+_PATCH_FIRING_SIGNAL_PHASE = "alerts-firing-signal-phase-2026-11"
_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)
@@ -313,6 +320,24 @@ class CheckAlertWorkflow(PostHogWorkflow):
parent_close_policy=temporalio.workflow.ParentClosePolicy.ABANDON,
)
+ # Phase 5 — inbox signal for a new firing episode. Last, so the send never delays the
+ # notification, and a failed notification stops it. The patch comes first, so a run
+ # started before the deploy keeps its old commands.
+ if (
+ temporalio.workflow.patched(_PATCH_FIRING_SIGNAL_PHASE)
+ and evaluation.signal_candidate
+ and evaluation.previous_state is not None
+ ):
+ await self._emit_firing_signal(
+ EmitAlertFiringSignalActivityInputs(
+ alert_id=inputs.alert_id,
+ alert_check_id=evaluation.alert_check_id,
+ team_id=inputs.team_id,
+ previous_state=evaluation.previous_state,
+ breaches=evaluation.breaches,
+ )
+ )
+
except Exception as e:
caught_error = e
@@ -331,6 +356,21 @@ class CheckAlertWorkflow(PostHogWorkflow):
if caught_error:
raise caught_error
+ async def _emit_firing_signal(self, signal_inputs: EmitAlertFiringSignalActivityInputs) -> None:
+ try:
+ await temporalio.workflow.execute_activity(
+ emit_alert_firing_signal,
+ signal_inputs,
+ start_to_close_timeout=ALERT_SIGNAL_START_TO_CLOSE,
+ schedule_to_close_timeout=ALERT_SIGNAL_SCHEDULE_TO_CLOSE,
+ retry_policy=ALERT_SIGNAL_RETRY_POLICY,
+ )
+ except Exception:
+ # The signal is best effort. Its failure must not fail a check that already notified.
+ temporalio.workflow.logger.warning(
+ "alerts.firing_signal_failed", extra={"alert_id": signal_inputs.alert_id}
+ )
+
async def _record_failed_evaluation(
self,
inputs: CheckAlertWorkflowInputs,
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index d1eccc148b27..c80652396b05 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -53,6 +53,7 @@ from posthog.temporal.alerts.activities import (
_load_alert_for_evaluation,
_lock_evaluation_alert,
cleanup_alert_checks,
+ emit_alert_firing_signal,
evaluate_alert,
notify_alert,
prepare_alert,
@@ -67,8 +68,9 @@ from posthog.temporal.alerts.admission import (
inflight_alert_ids,
)
from posthog.temporal.alerts.investigation import MAX_INVESTIGATIONS_PER_EPISODE
-from posthog.temporal.alerts.retry_policy import SlotLease, alert_timeouts
+from posthog.temporal.alerts.retry_policy import ALERT_SIGNAL_SCHEDULE_TO_CLOSE, SlotLease, alert_timeouts
from posthog.temporal.alerts.types import (
+ EmitAlertFiringSignalActivityInputs,
EvaluateAlertActivityInputs,
NotifyAlertActivityInputs,
PrepareAction,
@@ -1022,15 +1024,53 @@ class TestEvaluateAlert:
assert result.new_state == AlertState.NOT_FIRING
assert inflight_alert_ids() == set()
- @pytest.mark.parametrize("signal_error", [None, RuntimeError("signals unavailable")])
- async def test_evaluate_firing_with_breaches(self, alert, signal_error: Exception | None) -> None:
- # The inbox signal is best effort: a failure must not change the check or its notification.
+ async def test_evaluate_firing_with_breaches(self, alert) -> None:
+ emit = AsyncMock(return_value=True)
+ with (
+ patch(
+ "posthog.temporal.alerts.activities.check_alert_for_insight",
+ return_value=AlertEvaluationResult(value=100.0, breaches=["value above threshold"]),
+ ),
+ patch("posthog.temporal.alerts.alert_firing_signal.emit_signal", emit),
+ ):
+ result = await ActivityEnvironment().run(
+ evaluate_alert, EvaluateAlertActivityInputs(alert_id=str(alert.id))
+ )
+
+ # The signal goes out in a later workflow phase, so a slow send cannot delay the notification.
+ emit.assert_not_awaited()
+ assert result.signal_candidate is True
+ assert result.previous_state == AlertState.NOT_FIRING
+ assert result.new_state == AlertState.FIRING
+ assert result.should_notify is True
+
+ check = await sync_to_async(AlertCheck.objects.get)(pk=result.alert_check_id)
+ assert check.state == AlertState.FIRING
+ assert check.targets_notified == {}
+
+ @pytest.mark.parametrize(
+ "alert_change,signal_error,expect_emit",
+ [
+ (None, None, True),
+ (None, RuntimeError("signals unavailable"), True),
+ ("deleted", None, False),
+ ("disabled", None, False),
+ ],
+ )
+ async def test_emit_alert_firing_signal(
+ self, alert, alert_change: str | None, signal_error: Exception | None, expect_emit: bool
+ ) -> None:
+ check = await _create_alert_check(alert, state=AlertState.FIRING)
+ if alert_change == "deleted":
+ await sync_to_async(AlertConfiguration.objects.filter(id=alert.id).delete)()
+ elif alert_change == "disabled":
+ await sync_to_async(AlertConfiguration.objects.filter(id=alert.id).update)(enabled=False)
reached_default_executor = False
async def _emit(**_kwargs) -> bool:
nonlocal reached_default_executor
- # emit_signal runs sync work on the default executor. An evaluation thread that waits for
- # the emission holds the only worker, so this would time out.
+ # emit_signal runs sync work on the default executor. A thread that waits for the
+ # emission holds the only worker, so this would time out.
await asyncio.wait_for(sync_to_async(lambda: None, thread_sensitive=False)(), timeout=5)
reached_default_executor = True
if signal_error is not None:
@@ -1042,10 +1082,6 @@ class TestEvaluateAlert:
loop.set_default_executor(ThreadPoolExecutor(max_workers=1))
try:
with (
- patch(
- "posthog.temporal.alerts.activities.check_alert_for_insight",
- return_value=AlertEvaluationResult(value=100.0, breaches=["value above threshold"]),
- ),
patch("posthog.temporal.alerts.alert_firing_signal.emit_signal", emit),
patch(
"posthog.temporal.alerts.alert_firing_signal.get_source_config",
@@ -1056,21 +1092,26 @@ class TestEvaluateAlert:
return_value="all_firing_alerts",
),
):
- env = ActivityEnvironment()
- result = await env.run(evaluate_alert, EvaluateAlertActivityInputs(alert_id=str(alert.id)))
+ await ActivityEnvironment().run(
+ emit_alert_firing_signal,
+ EmitAlertFiringSignalActivityInputs(
+ alert_id=str(alert.id),
+ alert_check_id=str(check.id),
+ team_id=alert.team_id,
+ previous_state=AlertState.NOT_FIRING,
+ breaches=["value above threshold"],
+ ),
+ )
finally:
loop.set_default_executor(ThreadPoolExecutor())
- assert reached_default_executor
- emit.assert_awaited_once()
- assert emit.await_args is not None
- assert emit.await_args.kwargs["source_id"] == f"{alert.id}:{result.alert_check_id}"
- assert result.new_state == AlertState.FIRING
- assert result.should_notify is True
-
- check = await sync_to_async(AlertCheck.objects.get)(pk=result.alert_check_id)
- assert check.state == AlertState.FIRING
- assert check.targets_notified == {}
+ assert reached_default_executor is expect_emit
+ if expect_emit:
+ emit.assert_awaited_once()
+ assert emit.await_args is not None
+ assert emit.await_args.kwargs["source_id"] == f"{alert.id}:{check.id}"
+ else:
+ emit.assert_not_awaited()
@pytest.mark.parametrize(
"investigated,previous_verdict,owner,expect_investigation,expect_notify,expect_held",
@@ -2074,7 +2115,12 @@ def test_alert_timeouts_never_restart_a_live_attempt(calculation_interval) -> No
# 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
+ activities = (
+ timeouts.prepare_start_to_close
+ + timeouts.activity_schedule_to_close
+ + timeouts.notify_start_to_close
+ + ALERT_SIGNAL_SCHEDULE_TO_CLOSE
+ )
assert timeouts.workflow_execution >= activities
diff --git a/posthog/temporal/tests/test_alerts_alert_firing_signal.py b/posthog/temporal/tests/test_alerts_alert_firing_signal.py
index 65be9e5ccd04..2ac6e36f9c5a 100644
--- a/posthog/temporal/tests/test_alerts_alert_firing_signal.py
+++ b/posthog/temporal/tests/test_alerts_alert_firing_signal.py
@@ -1,3 +1,6 @@
+import asyncio
+import contextlib
+
from posthog.test.base import BaseTest
from unittest.mock import AsyncMock, patch
@@ -35,6 +38,11 @@ async def _validated_emit(**kwargs) -> bool:
return True
+async def _hang(**_kwargs) -> bool:
+ await asyncio.Event().wait()
+ return True
+
+
class TestEmitAlertFiringSignal(BaseTest):
def setUp(self) -> None:
super().setUp()
@@ -140,14 +148,20 @@ class TestEmitAlertFiringSignal(BaseTest):
("dispatched_spends_the_cap", {"return_value": True}, False),
("not_dispatched_refunds_it", {"return_value": False}, True),
("emission_error_is_swallowed_and_refunds_it", {"side_effect": RuntimeError("temporal down")}, True),
+ ("hung_emission_times_out_and_refunds_it", {"side_effect": _hang}, True),
+ ("cancelled_attempt_refunds_it", {"side_effect": asyncio.CancelledError()}, True),
]
)
def test_cap_counts_only_dispatched_signals(self, _name: str, first_emit: dict, second_expected: bool) -> None:
first = self._alert_and_check()
second = self._alert_and_check()
- with patch(f"{_MODULE}.CAP_BUDGET", Budget(burst=1, per_hour=1)):
- self._emit(*first, emit=AsyncMock(**first_emit))
+ with (
+ patch(f"{_MODULE}.CAP_BUDGET", Budget(burst=1, per_hour=1)),
+ patch(f"{_MODULE}.EMISSION_TIMEOUT_SECONDS", 0.05),
+ ):
+ with contextlib.suppress(asyncio.CancelledError):
+ self._emit(*first, emit=AsyncMock(**first_emit))
emitted, _ = self._emit(*second)
assert emitted is second_expected
diff --git a/posthog/temporal/tests/test_alerts_workflows.py b/posthog/temporal/tests/test_alerts_workflows.py
index 0290fb536953..62063fa15f7e 100644
--- a/posthog/temporal/tests/test_alerts_workflows.py
+++ b/posthog/temporal/tests/test_alerts_workflows.py
@@ -34,6 +34,7 @@ from posthog.slo.types import SloArea, SloConfig, SloOperation, SloOutcome
from posthog.tasks.alerts.utils import AlertEvaluationResult
from posthog.temporal.alerts.activities import (
admit_alert_evaluations,
+ emit_alert_firing_signal,
evaluate_alert,
notify_alert,
prepare_alert,
@@ -191,6 +192,65 @@ async def test_check_alert_workflow_evaluates_ai_detectors_on_the_ai_task_queue(
assert evaluate_call.kwargs["task_queue"] == expected_task_queue
+ "patched,notify_error,signal_error,expected_activities,expect_raise",
+ [
+ pytest.param(True, None, None, [notify_alert, emit_alert_firing_signal], False, id="signal_after_notify"),
+ pytest.param(False, None, None, [notify_alert], False, id="run_started_before_the_patch"),
+ pytest.param(True, RuntimeError("smtp down"), None, [notify_alert], True, id="no_signal_after_failed_notify"),
+ pytest.param(
+ True,
+ None,
+ RuntimeError("signals down"),
+ [notify_alert, emit_alert_firing_signal],
+ False,
+ id="signal_failure_keeps_the_check",
+ ),
+ ],
+)
+async def test_check_alert_workflow_sends_the_firing_signal_last(
+ patched: bool,
+ notify_error: Exception | None,
+ signal_error: Exception | None,
+ expected_activities: list[Callable[..., Any]],
+ expect_raise: bool,
+) -> None:
+ evaluation = EvaluateAlertResult(
+ alert_check_id=str(uuid.uuid4()),
+ should_notify=True,
+ new_state=AlertState.FIRING,
+ breaches=["value above threshold"],
+ signal_candidate=True,
+ previous_state=AlertState.NOT_FIRING,
+ )
+ execute_activity = AsyncMock(
+ side_effect=[PrepareAlertResult(action=PrepareAction.EVALUATE), evaluation, notify_error, signal_error]
+ )
+
+ with (
+ patch("posthog.temporal.alerts.workflows.temporalio.workflow.execute_activity", new=execute_activity),
+ patch("posthog.temporal.alerts.workflows.temporalio.workflow.patched", return_value=patched),
+ patch("posthog.temporal.alerts.workflows.temporalio.workflow.logger"),
+ pytest.raises(RuntimeError) if expect_raise else nullcontext(),
+ ):
+ await CheckAlertWorkflow().run(
+ CheckAlertWorkflowInputs(
+ alert_id=str(uuid.uuid4()),
+ team_id=1,
+ distinct_id="alerts-signal-test",
+ calculation_interval=AlertCalculationInterval.DAILY.value,
+ insight_id=1,
+ )
+ )
+
+ assert [c.args[0] for c in execute_activity.await_args_list[2:]] == expected_activities
+ if emit_alert_firing_signal in expected_activities:
+ signal_inputs = execute_activity.await_args_list[3].args[1]
+ assert signal_inputs.alert_check_id == evaluation.alert_check_id
+ assert signal_inputs.previous_state == AlertState.NOT_FIRING
+
+
@pytest.mark.asyncio
async def test_schedule_due_alert_checks_passes_configured_limit_to_retrieval() -> None:
inputs = ScheduleDueAlertChecksWorkflowInputs(max_alerts_per_run=17)