Skip to content

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

feat(alerts): investigate every firing check, up to 3 per episode (#94162)

posthog[bot]42317cefa0c5
diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.py
index 9b01254da488..04b2875fdb0b 100644
--- a/posthog/tasks/alerts/utils.py
+++ b/posthog/tasks/alerts/utils.py
@@ -337,6 +337,7 @@ def dispatch_alert_notification(
alert_check: AlertCheck,
breaches: list[str] | None,
extra_properties: dict[str, str] | None = None,
+ idempotency_key: str | None = None,
) -> list[AlertDelivery] | None:
"""Route an AlertCheck to the correct notification sender.
@@ -345,10 +346,15 @@ def dispatch_alert_notification(
receipts to record_alert_delivery so the `targets_notified` sentinel reflects reality,
never claiming delivery for a state that didn't actually send.
+ `idempotency_key` defaults to the check id, which gives at-most-once email delivery per
+ check. A caller that deliberately sends a second message about the same check must pass
+ its own key, or MessagingRecord drops that email as a duplicate of the first.
+
Raises:
ValueError: state is FIRING but breaches is None/empty.
AssertionError: unknown state — surfaces a missing AlertState branch loudly.
"""
+ key = idempotency_key or str(alert_check.id)
with ExitStack() as stack:
if alert_check.state == AlertState.FIRING:
stack.enter_context(
@@ -379,7 +385,7 @@ def dispatch_alert_notification(
alert_check_id=alert_check.id,
)
return None
- return send_notifications_for_errors(alert, alert_check.error, idempotency_key=str(alert_check.id))
+ return send_notifications_for_errors(alert, alert_check.error, idempotency_key=key)
case AlertState.FIRING:
if not breaches:
raise ValueError(
@@ -391,9 +397,9 @@ def dispatch_alert_notification(
# keeping the common threshold-alert call unchanged.
if extra_properties:
return send_notifications_for_breaches(
- alert, breaches, idempotency_key=str(alert_check.id), extra_properties=extra_properties
+ alert, breaches, idempotency_key=key, extra_properties=extra_properties
)
- return send_notifications_for_breaches(alert, breaches, idempotency_key=str(alert_check.id))
+ return send_notifications_for_breaches(alert, breaches, idempotency_key=key)
case _:
raise AssertionError(f"dispatch_alert_notification: unhandled alert state: {alert_check.state}")
diff --git a/posthog/temporal/ai/anomaly_investigation/workflow.py b/posthog/temporal/ai/anomaly_investigation/workflow.py
index 6119e2ec1136..e37694be520c 100644
--- a/posthog/temporal/ai/anomaly_investigation/workflow.py
+++ b/posthog/temporal/ai/anomaly_investigation/workflow.py
@@ -1,7 +1,7 @@
"""Temporal workflow that kicks off the anomaly investigation agent and persists
its findings as a Notebook linked to the AlertCheck.
-Triggered from posthog/temporal/alerts/workflows.py when an alert transitions to FIRING.
+Triggered from posthog/temporal/alerts/workflows.py for a firing check the budget allows.
"""
from __future__ import annotations
@@ -35,6 +35,7 @@ from posthog.temporal.common.heartbeat import Heartbeater
from posthog.utils import absolute_uri
from products.alerts.backend.destinations import list_active_alert_destinations
+from products.alerts.backend.investigation_episode import EpisodeInvestigations, episode_investigations
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus
from products.exports.backend.facade import api as exports
from products.notebooks.backend.facade import api as notebooks
@@ -64,6 +65,15 @@ ANOMALY_INVESTIGATION_ACTIVITY_MAX_ATTEMPTS = 2
MAX_SUMMARY_CHARS = 500
+_VERDICT_LABELS = {
+ "true_positive": "True positive",
+ "false_positive": "False positive",
+ "inconclusive": "Inconclusive",
+}
+
+# Marker on the check's delivery receipts: the follow-up for a changed verdict is sent once.
+_VERDICT_CHANGE_FOLLOWUP_KEY = "investigation_verdict_change"
+
# Cap for the embedded signal description. Kept well under the signals facade's ~8000-token limit
# (a conservative margin even for token-dense text) so a long agent report can't get the signal
# rejected and silently dropped.
@@ -209,6 +219,10 @@ async def investigate_anomaly_activity(inputs: AnomalyInvestigationWorkflowInput
verdict=result.report.verdict,
)
+ # Read the episode before this check's own verdict lands, so `previous_verdict` is the
+ # last verdict of an earlier check in the same firing episode.
+ episode = await sync_to_async(episode_investigations, thread_sensitive=False)(alert, alert_check)
+
summary_for_list = _truncate_summary(result.report.summary)
await sync_to_async(AlertCheck.objects.filter(id=alert_check.id).update, thread_sensitive=False)(
investigation_notebook_id=notebook.id,
@@ -226,10 +240,11 @@ async def investigate_anomaly_activity(inputs: AnomalyInvestigationWorkflowInput
# after the check was held back but before the workflow completes — in
# that case the current flag would say "don't dispatch" even though the
# notification was never sent.
- await sync_to_async(_dispatch_gated_notification, thread_sensitive=False)(
+ await sync_to_async(_deliver_investigation_outcome, thread_sensitive=False)(
alert=alert,
alert_check=alert_check,
verdict=result.report.verdict,
+ previous_verdict=episode.previous_verdict,
summary=summary_for_list or "",
notebook_short_id=notebook.short_id,
insight_chart_url=insight_chart_url,
@@ -240,7 +255,9 @@ async def investigate_anomaly_activity(inputs: AnomalyInvestigationWorkflowInput
# AlertCheck and in the notebook). Best-effort: the investigation itself has already
# succeeded and been persisted, so a failure to emit must not fail the activity
# (and trigger a re-run of the whole agent).
- if not should_emit_investigation_signal(result.report.verdict, alert.investigation_inconclusive_action):
+ if not should_emit_episode_signal(
+ result.report.verdict, episode.previous_verdict, alert.investigation_inconclusive_action
+ ):
logger.info(
"anomaly_investigation.signal_skipped",
alert_id=str(alert.id),
@@ -254,6 +271,7 @@ async def investigate_anomaly_activity(inputs: AnomalyInvestigationWorkflowInput
team=team,
alert=alert,
alert_check=alert_check,
+ episode=episode,
insight=insight,
detector_type=detector_type,
report=result.report,
@@ -281,6 +299,20 @@ def should_emit_investigation_signal(verdict: str | None, inconclusive_action: s
return False
+def should_emit_episode_signal(
+ verdict: str | None, previous_verdict: str | None, inconclusive_action: str | None
+) -> bool:
+ """Whether this investigation should reach the Signals inbox.
+
+ A re-investigation only emits when its verdict differs from the last one on the same
+ episode. That bounds an incident to one emission per verdict it reaches, so a long
+ incident cannot file a report for every check of it.
+ """
+ if verdict == previous_verdict:
+ return False
+ return should_emit_investigation_signal(verdict, inconclusive_action)
+
+
def _build_investigation_signal_extra(
*,
alert: AlertConfiguration,
@@ -320,23 +352,31 @@ async def _emit_investigation_signal(
team: Team,
alert: AlertConfiguration,
alert_check: AlertCheck,
+ episode: EpisodeInvestigations,
insight: Insight,
detector_type: str,
report: InvestigationReport,
notebook_short_id: str | None,
) -> None:
- """Emit an `alerts/anomaly_investigation` signal carrying the agent's verdict and findings."""
+ """Emit an `alerts/anomaly_investigation` signal carrying the agent's verdict and findings.
+
+ The source id is the episode's first check, not this one, so every investigation of one
+ incident carries the same identity. Grouping matches a signal on its description and on
+ semantically near signals, not on the source id, so one report per episode is a strong
+ default and not a guarantee: a re-emit can still open a report of its own.
+ """
await signals.emit_signal(
team=team,
source_product=SIGNAL_SOURCE_PRODUCT,
source_type=SIGNAL_SOURCE_TYPE,
- source_id=str(alert_check.id),
+ source_id=episode.first_check_id,
description=_build_signal_description(
alert_name=alert.name or "Unnamed alert",
insight_name=insight.name or None,
insight_id=str(insight.id),
insight_short_id=getattr(insight, "short_id", None),
report=report,
+ previous_verdict=episode.previous_verdict,
),
weight=1,
extra=_build_investigation_signal_extra(
@@ -357,14 +397,24 @@ def _build_signal_description(
insight_id: str,
insight_short_id: str | None,
report: InvestigationReport,
+ previous_verdict: str | None = None,
) -> str:
"""Human-readable description embedded for grouping. Leads with the verdict, names the insight
- (with its id, handy for lookups), then the agent's summary, hypotheses, and recommendations."""
+ (with its id, handy for lookups), then the agent's summary, hypotheses, and recommendations.
+
+ A re-investigation of the same episode leads with the verdict change instead, because that
+ change is why the agent ran again."""
verdict_label = report.verdict.replace("_", " ")
metric = f" on {insight_name}" if insight_name else ""
insight_ref = f"{insight_short_id} / id {insight_id}" if insight_short_id else f"id {insight_id}"
+ headline = f"Anomaly investigation for alert '{alert_name}'{metric} (verdict: {verdict_label})."
+ if previous_verdict and previous_verdict != report.verdict:
+ headline = (
+ f"Verdict changed from {previous_verdict.replace('_', ' ')} to {verdict_label} "
+ f"for alert '{alert_name}'{metric}, which is still firing."
+ )
lines: list[str] = [
- f"Anomaly investigation for alert '{alert_name}'{metric} (verdict: {verdict_label}).",
+ headline,
f"Insight: {insight_ref}.",
report.summary,
]
@@ -386,12 +436,15 @@ def _build_signal_description(
return description
+def _inconclusive_is_suppressed(verdict: str | None, inconclusive_action: str | None) -> bool:
+ """Whether an inconclusive verdict is held back by the alert's configured policy."""
+ return verdict == "inconclusive" and (inconclusive_action or "notify") == "suppress"
+
+
def _should_suppress_notification(verdict: str | None, inconclusive_action: str | None) -> bool:
"""Whether the verdict holds the notification back: false positives always suppress,
inconclusive follows the alert's configured policy."""
- return verdict == "false_positive" or (
- verdict == "inconclusive" and (inconclusive_action or "notify") == "suppress"
- )
+ return verdict == "false_positive" or _inconclusive_is_suppressed(verdict, inconclusive_action)
def _prepare_insight_chart_url(
@@ -447,24 +500,33 @@ def _prepare_insight_chart_url(
return None
-def _dispatch_gated_notification(
+def _deliver_investigation_outcome(
*,
alert,
alert_check,
verdict: str | None,
+ previous_verdict: str | None,
summary: str,
notebook_short_id: str | None,
insight_chart_url: str | None = None,
) -> None:
- """Decide whether to fire the notification now that we have the verdict.
+ """Decide what the user gets now that we have the verdict.
+
+ For a check whose notification was held back (the episode's first fire):
- true_positive → notify (enriched body with verdict + summary + notebook link)
- false_positive → suppress, mark the check so the UI can surface why
- inconclusive → fall back to the alert's configured policy
- unknown / null verdict → notify (safest default)
+ A later investigation of the same episode is not gated, so its notification already
+ went out. It gets a follow-up only when the verdict changed, because the change is
+ the news; an unchanged verdict would repeat what the user already read. A change to
+ a false positive is a correction of a message the user already has, so it is sent
+ rather than suppressed.
+
Idempotent: if another codepath (retry, safety-net task) already dispatched,
- this is a no-op.
+ the first delivery is a no-op, and the follow-up is written once per check.
"""
suppress = _should_suppress_notification(verdict, alert.investigation_inconclusive_action)
@@ -472,6 +534,14 @@ def _dispatch_gated_notification(
# Re-fetch under a row lock so concurrent dispatchers can't double-notify.
check = AlertCheck.objects.select_for_update().get(id=alert_check.id)
if check.notification_sent_at is not None or check.notification_suppressed_by_agent:
+ _dispatch_verdict_change_followup(
+ alert=alert,
+ check=check,
+ verdict=verdict,
+ previous_verdict=previous_verdict,
+ summary=summary,
+ notebook_short_id=notebook_short_id,
+ )
return
if suppress:
@@ -486,7 +556,11 @@ def _dispatch_gated_notification(
return
breaches = _build_breach_descriptions(
- alert_check=check, verdict=verdict, summary=summary, notebook_short_id=notebook_short_id
+ alert_check=check,
+ verdict=verdict,
+ previous_verdict=previous_verdict,
+ summary=summary,
+ notebook_short_id=notebook_short_id,
)
# Event properties beyond the breach text, for HogFunction destinations. The notebook
# URL backs the Slack "View Investigation" button (falls back to "View Alert" when
@@ -510,10 +584,103 @@ def _dispatch_gated_notification(
raise
+def _dispatch_verdict_change_followup(
+ *,
+ alert,
+ check,
+ verdict: str | None,
+ previous_verdict: str | None,
+ summary: str,
+ notebook_short_id: str | None,
+) -> None:
+ """Send one follow-up for a check whose notification already went out and whose verdict
+ changed since the previous investigation of the same episode.
+
+ A false positive does not hold this back the way it holds back a first notification.
+ The user was already told the anomaly was real, so the correction is the whole point of
+ the message. An inconclusive verdict still follows the alert's configured policy: a user
+ who asked not to hear about unsure verdicts did not ask to hear about them here.
+
+ Caller holds the row lock. The marker on `targets_notified` is the idempotency guard, so
+ an activity retry past a successful send cannot notify twice. It is written only once a
+ destination accepts the send, so a failed enqueue leaves the follow-up retryable.
+
+ Never raises into the activity: a correction that cannot be sent is not worth a second
+ agent run.
+ """
+ if not previous_verdict or verdict == previous_verdict:
+ return
+ if _inconclusive_is_suppressed(verdict, alert.investigation_inconclusive_action):
+ return
+ receipts = check.targets_notified or {}
+ if receipts.get(_VERDICT_CHANGE_FOLLOWUP_KEY):
+ return
+
+ breaches = _build_breach_descriptions(
+ alert_check=check,
+ verdict=verdict,
+ previous_verdict=previous_verdict,
+ summary=summary,
+ notebook_short_id=notebook_short_id,
+ )
+ extra_properties = (
+ {"investigation_notebook_url": absolute_uri(f"/notebooks/{notebook_short_id}")} if notebook_short_id else None
+ )
+ try:
+ # The savepoint keeps a database failure inside the dispatch from poisoning the
+ # caller's transaction once the handler below swallows it.
+ with transaction.atomic():
+ # A key of its own: the check id already carries a delivery record per recipient
+ # from the notification sent at fire time, and the email sender drops a second
+ # send under the same campaign. Stable across retries, so at-most-once per
+ # recipient still holds.
+ deliveries = dispatch_alert_notification(
+ alert,
+ check,
+ breaches,
+ extra_properties=extra_properties,
+ idempotency_key=f"{check.id}:investigation-verdict-change",
+ )
+ except Exception:
+ # Best-effort, like the signal emit: the verdict is persisted and the user already
+ # has the fire notification, so raising would rerun the whole agent for one
+ # correction message. The safety net cannot recover this check either — it only
+ # picks up checks that were never notified.
+ logger.exception(
+ "anomaly_investigation.verdict_change_followup_failed",
+ alert_id=str(alert.id),
+ alert_check_id=str(check.id),
+ )
+ return
+ if not deliveries:
+ # A failed enqueue and an alert with no destinations look the same from here, so
+ # leave the marker unset. A later attempt can then send again, and an alert with no
+ # destination has nothing to re-send. Marking it would lose the follow-up for good:
+ # no sweep picks up a check whose notification already went out.
+ logger.warning(
+ "anomaly_investigation.verdict_change_followup_not_delivered",
+ alert_id=str(alert.id),
+ alert_check_id=str(check.id),
+ verdict=verdict,
+ previous_verdict=previous_verdict,
+ )
+ return
+ check.targets_notified = {**receipts, _VERDICT_CHANGE_FOLLOWUP_KEY: True}
+ check.save(update_fields=["targets_notified"])
+ logger.info(
+ "anomaly_investigation.verdict_change_followup_sent",
+ alert_id=str(alert.id),
+ alert_check_id=str(check.id),
+ verdict=verdict,
+ previous_verdict=previous_verdict,
+ )
+
+
def _build_breach_descriptions(
*,
alert_check,
verdict: str | None,
+ previous_verdict: str | None,
summary: str,
notebook_short_id: str | None,
) -> list[str]:
@@ -522,6 +689,11 @@ def _build_breach_descriptions(
giving gated notifications richer body content.
"""
lines: list[str] = []
+ if previous_verdict and verdict and verdict != previous_verdict:
+ lines.append(
+ f"Investigation verdict changed from {_VERDICT_LABELS.get(previous_verdict, previous_verdict)} "
+ f"to {_VERDICT_LABELS.get(verdict, verdict)} while this alert keeps firing."
+ )
triggered_dates = alert_check.triggered_dates or []
if triggered_dates:
if len(triggered_dates) == 1:
@@ -533,7 +705,7 @@ def _build_breach_descriptions(
else:
lines.append("Anomaly detected.")
- verdict_label = {"true_positive": "True positive", "inconclusive": "Inconclusive"}.get(verdict or "", "")
+ verdict_label = _VERDICT_LABELS.get(verdict or "", "")
if verdict_label:
lines.append(f"Investigation verdict: {verdict_label}.")
if summary:
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index 69a4c1bfe3d4..bd98b992ab10 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -34,7 +34,7 @@ from posthog.tasks.alerts.utils import (
record_alert_delivery,
skip_because_of_weekend,
)
-from posthog.temporal.alerts.investigation import claim_investigation_slot, should_trigger_investigation
+from posthog.temporal.alerts.investigation import claim_investigation_slot, decide_investigation
from posthog.temporal.alerts.types import (
AlertInfo,
EvaluateAlertActivityInputs,
@@ -321,7 +321,7 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe
# 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.
+ # FIRING check, so the errored path skips it.
if error is not None:
with transaction.atomic():
alert = (
@@ -348,14 +348,12 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe
previous_state = alert.state
alert_check, should_notify = add_alert_check(alert, alert_evaluation_result, error)
- if should_trigger_investigation(
- alert,
- previous_state=previous_state,
- new_state=alert_check.state,
- ):
- if claim_investigation_slot(alert, alert_check):
- should_start_investigation = True
- should_gate_notification = bool(alert.investigation_gates_notifications)
+ investigation = decide_investigation(alert, alert_check)
+ if investigation.should_investigate and claim_investigation_slot(alert, alert_check):
+ should_start_investigation = True
+ should_gate_notification = investigation.is_first_of_episode and bool(
+ alert.investigation_gates_notifications
+ )
# Claim the cooldown slot inside the transaction so a flapping or
# concurrently-retried alert can't pile up investigations.
diff --git a/posthog/temporal/alerts/investigation.py b/posthog/temporal/alerts/investigation.py
index 55daa2a2e606..a9a4e0cf30b6 100644
--- a/posthog/temporal/alerts/investigation.py
+++ b/posthog/temporal/alerts/investigation.py
@@ -10,54 +10,108 @@ from __future__ import annotations
from datetime import UTC, datetime, timedelta
-from posthog.schema import AlertState
+from django.db.models import Q
+from posthog.schema import AlertCalculationInterval, AlertState
+
+from posthog.dataclasses import frozen
+from posthog.tasks.alerts.investigation_notifications import INVESTIGATION_RUNNING_GRACE_MINUTES
+
+from products.alerts.backend.investigation_episode import episode_investigations
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus
-INVESTIGATION_COOLDOWN = timedelta(hours=1)
+# A firing episode is the run of consecutive FIRING checks since the last check that was
+# not FIRING. Every check in the episode is eligible, up to this many investigations, so
+# a verdict that flips halfway through an incident still gets found. The budget is the
+# only cap: dismissals and confirmations spend it alike.
+MAX_INVESTIGATIONS_PER_EPISODE = 3
+
+# The cooldown only stops an alert that flaps inside one of its own intervals. It must
+# stay below the interval, or scheduler jitter decides whether the next scheduled check
+# investigates. Long intervals keep the historical one-hour ceiling.
+INVESTIGATION_COOLDOWN_MARGIN = timedelta(minutes=5)
+MAX_INVESTIGATION_COOLDOWN = timedelta(hours=1)
+MIN_INVESTIGATION_COOLDOWN = timedelta(minutes=5)
+
+# An investigation that is still in flight blocks a new one however long it has run. The
+# cooldown is shorter than the alert's interval by design, so on a fast cadence the previous
+# check falls outside the cooldown window while its agent still works, and a purely
+# time-scoped guard would let two agents investigate the same anomaly at once. Past this
+# horizon the row is presumed dead, which is the same point at which the notification safety
+# net stops waiting for a non-terminal investigation.
+IN_FLIGHT_INVESTIGATION_HORIZON = timedelta(minutes=INVESTIGATION_RUNNING_GRACE_MINUTES)
+
+_CALCULATION_INTERVAL_DURATIONS: dict[str, timedelta] = {
+ AlertCalculationInterval.REAL_TIME: timedelta(minutes=1),
+ AlertCalculationInterval.EVERY_15_MINUTES: timedelta(minutes=15),
+ AlertCalculationInterval.HOURLY: timedelta(hours=1),
+ AlertCalculationInterval.DAILY: timedelta(days=1),
+ AlertCalculationInterval.WEEKLY: timedelta(weeks=1),
+ AlertCalculationInterval.MONTHLY: timedelta(days=30),
+}
+
+
+@frozen
+class InvestigationDecision:
+ should_investigate: bool = False
+ is_first_of_episode: bool = False
+
+def investigation_cooldown(alert: AlertConfiguration) -> timedelta:
+ """The minimum gap between two investigations of the same alert."""
+ interval = _CALCULATION_INTERVAL_DURATIONS.get(alert.calculation_interval or "", MAX_INVESTIGATION_COOLDOWN)
+ return min(max(interval - INVESTIGATION_COOLDOWN_MARGIN, MIN_INVESTIGATION_COOLDOWN), MAX_INVESTIGATION_COOLDOWN)
-def should_trigger_investigation(
- alert: AlertConfiguration,
- *,
- previous_state: str | None,
- new_state: str,
-) -> bool:
- """True when this fire is eligible for an investigation, ignoring cooldown.
+
+def decide_investigation(alert: AlertConfiguration, alert_check: AlertCheck) -> InvestigationDecision:
+ """Whether this firing check gets an investigation, and whether it opened the episode.
+
+ Only the episode's first fire may gate the notification, because it is the fire the
+ user has not heard about yet. A later check runs while its notification goes out on the
+ normal path, because holding a reminder of an incident the user already knows about
+ costs more than the verdict is worth. A skipped investigation on an earlier check does
+ not move the gate forward: that check notified all the same.
Cooldown is enforced by `claim_investigation_slot`, which does the read-then-write
inside the caller's transaction.
"""
if not alert.investigation_agent_enabled:
- return False
+ return InvestigationDecision()
if not alert.detector_config:
- return False
- if previous_state == AlertState.FIRING:
- return False
- if new_state != AlertState.FIRING:
- return False
- return True
+ return InvestigationDecision()
+ if alert_check.state != AlertState.FIRING:
+ return InvestigationDecision()
+
+ episode = episode_investigations(alert, alert_check)
+ if episode.started >= MAX_INVESTIGATIONS_PER_EPISODE:
+ return InvestigationDecision()
+ return InvestigationDecision(should_investigate=True, is_first_of_episode=episode.is_first_fire)
def claim_investigation_slot(alert: AlertConfiguration, alert_check: AlertCheck) -> bool:
- """Try to claim the cooldown slot for `alert` and return True on success.
+ """Try to claim the investigation slot for `alert` and return True on success.
- On success, marks `alert_check.investigation_status = PENDING`. On failure
- (a recent investigation is RUNNING/DONE/PENDING within the cooldown window),
- marks it SKIPPED and returns False so flappy alerts don't pile up.
+ Two things fail the claim: an investigation of the same alert that is still in flight
+ (PENDING or RUNNING), whatever its age, and one that finished (DONE) inside the
+ cooldown window. On success, marks `alert_check.investigation_status = PENDING`; on
+ failure, marks it SKIPPED and returns False so flappy alerts don't pile up.
Caller must run this inside a transaction so the read-then-write is atomic.
"""
- cooldown_since = datetime.now(UTC) - INVESTIGATION_COOLDOWN
- recent = AlertCheck.objects.filter(
- alert_configuration=alert,
- created_at__gte=cooldown_since,
- investigation_status__in=[
- InvestigationStatus.RUNNING,
- InvestigationStatus.DONE,
- InvestigationStatus.PENDING,
- ],
- ).exclude(id=alert_check.id)
+ now = datetime.now(UTC)
+ in_flight = Q(
+ investigation_status__in=[InvestigationStatus.PENDING, InvestigationStatus.RUNNING],
+ created_at__gte=now - IN_FLIGHT_INVESTIGATION_HORIZON,
+ )
+ within_cooldown = Q(
+ investigation_status=InvestigationStatus.DONE,
+ created_at__gte=now - investigation_cooldown(alert),
+ )
+ recent = (
+ AlertCheck.objects.filter(alert_configuration=alert)
+ .exclude(id=alert_check.id)
+ .filter(in_flight | within_cooldown)
+ )
if recent.exists():
AlertCheck.objects.filter(id=alert_check.id).update(investigation_status=InvestigationStatus.SKIPPED)
return False
diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_signal.py b/posthog/temporal/tests/ai/test_anomaly_investigation_signal.py
index 36164a9c02bb..6a78ab56e3e5 100644
--- a/posthog/temporal/tests/ai/test_anomaly_investigation_signal.py
+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_signal.py
@@ -4,6 +4,7 @@ from posthog.temporal.ai.anomaly_investigation.report import InvestigationReport
from posthog.temporal.ai.anomaly_investigation.workflow import (
_MAX_DESCRIPTION_CHARS,
_build_signal_description,
+ should_emit_episode_signal,
should_emit_investigation_signal,
)
@@ -66,3 +67,40 @@ class TestShouldEmitInvestigationSignal:
)
def test_gating_by_verdict_and_policy(self, verdict: str, inconclusive_action: str | None, expected: bool) -> None:
assert should_emit_investigation_signal(verdict, inconclusive_action) is expected
+
+
+class TestReInvestigationOfAnEpisode:
+ def test_description_leads_with_the_verdict_change(self) -> None:
+ # The change is why the agent ran again, and it is what groups the update onto
+ # the episode's existing report.
+ report = InvestigationReport(
+ verdict="true_positive",
+ summary="The drop is real, the checkout API is erroring.",
+ hypotheses=[],
+ recommendations=[],
+ )
+
+ description = _build_signal_description(
+ alert_name="Signups dropped",
+ insight_name="Daily signups",
+ insight_id="42",
+ insight_short_id="abc123",
+ report=report,
+ previous_verdict="false_positive",
+ )
+
+ assert description.startswith("Verdict changed from false positive to true positive")
+
+ @parameterized.expand(
+ [
+ ("first_investigation", "true_positive", None, True),
+ ("verdict_held", "true_positive", "true_positive", False),
+ ("verdict_flipped", "true_positive", "false_positive", True),
+ ("still_dismissed", "false_positive", "false_positive", False),
+ ("flipped_to_dismissed", "false_positive", "true_positive", False),
+ ]
+ )
+ def test_only_a_changed_verdict_reaches_the_inbox_again(
+ self, _name: str, verdict: str, previous_verdict: str | None, expected: bool
+ ) -> None:
+ assert should_emit_episode_signal(verdict, previous_verdict, "notify") is expected
diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
index 3766ca59c632..60039136b89d 100644
--- a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
@@ -1,10 +1,13 @@
"""Verifies that the workflow activity persists the agent's verdict onto the AlertCheck."""
+from datetime import UTC, datetime
+
import pytest
from posthog.test.base import NonAtomicBaseTest
from unittest.mock import patch
from asgiref.sync import sync_to_async
+from parameterized import parameterized
from posthog.schema import AlertState
@@ -12,12 +15,15 @@ from posthog.temporal.ai.anomaly_investigation.report import InvestigationReport
from posthog.temporal.ai.anomaly_investigation.runner import InvestigationRunResult
from posthog.temporal.ai.anomaly_investigation.workflow import (
AnomalyInvestigationWorkflowInputs,
+ _deliver_investigation_outcome,
investigate_anomaly_activity,
)
+from products.alerts.backend.destinations import AlertDelivery
from products.alerts.backend.models.alert import (
AlertCheck,
AlertConfiguration,
+ AlertSubscription,
InvestigationStatus,
InvestigationVerdict,
)
@@ -211,3 +217,120 @@ class TestInvestigationVerdictPersistence(NonAtomicBaseTest):
extra_properties = mock_dispatch.call_args.kwargs["extra_properties"]
assert "/exporter/" in extra_properties["insight_chart_url"]
assert "token=" in extra_properties["insight_chart_url"]
+
+
+class TestVerdictChangeFollowup(NonAtomicBaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.insight = Insight.objects.create(team=self.team, name="test insight")
+ self.alert = AlertConfiguration.objects.create(
+ team=self.team,
+ insight=self.insight,
+ name="anomaly alert",
+ detector_config={"type": "zscore", "threshold": 0.95, "window": 30},
+ investigation_agent_enabled=True,
+ investigation_gates_notifications=True,
+ state=AlertState.FIRING,
+ created_by=self.user,
+ )
+ # A later check of a firing episode: it was never gated, so its notification is
+ # already out and a changed verdict is the only thing left to tell the user.
+ self.alert_check = AlertCheck.objects.create(
+ alert_configuration=self.alert,
+ state=AlertState.FIRING,
+ calculated_value=42.0,
+ notification_sent_at=datetime.now(UTC),
+ )
+
+ @parameterized.expand(
+ [
+ ("reversed_to_false_positive", "false_positive", "notify", True),
+ ("turned_inconclusive_and_policy_notifies", "inconclusive", "notify", True),
+ ("turned_inconclusive_and_policy_suppresses", "inconclusive", "suppress", False),
+ ("verdict_held", "true_positive", "notify", False),
+ ]
+ )
+ @patch(
+ "posthog.temporal.ai.anomaly_investigation.workflow.dispatch_alert_notification",
+ return_value=[AlertDelivery(channel="hog_function", target="Slack #alerts", at="2026-04-30T06:00:00+00:00")],
+ )
+ def test_follow_up_after_a_true_positive(
+ self,
+ _name: str,
+ verdict: str,
+ inconclusive_action: str,
+ expect_follow_up: bool,
+ mock_dispatch,
+ ) -> None:
+ self.alert.investigation_inconclusive_action = inconclusive_action
+ self.alert.save()
+
+ _deliver_investigation_outcome(
+ alert=self.alert,
+ alert_check=self.alert_check,
+ verdict=verdict,
+ previous_verdict="true_positive",
+ summary="The spike is a bot crawl.",
+ notebook_short_id=None,
+ )
+
+ self.alert_check.refresh_from_db()
+ if not expect_follow_up:
+ mock_dispatch.assert_not_called()
+ assert self.alert_check.targets_notified == {}
+ return
+
+ mock_dispatch.assert_called_once()
+ breaches = mock_dispatch.call_args.args[2]
+ assert breaches[0].startswith("Investigation verdict changed from True positive to")
+ assert self.alert_check.targets_notified == {"investigation_verdict_change": True}
+
+ @patch("posthog.tasks.alerts.utils.send_alert_email")
+ def test_follow_up_email_uses_a_campaign_of_its_own(self, mock_send_email) -> None:
+ AlertSubscription.objects.create(user=self.user, alert_configuration=self.alert, created_by=self.user)
+
+ _deliver_investigation_outcome(
+ alert=self.alert,
+ alert_check=self.alert_check,
+ verdict="false_positive",
+ previous_verdict="true_positive",
+ summary="The spike is a bot crawl.",
+ notebook_short_id=None,
+ )
+
+ campaign_key = mock_send_email.call_args.kwargs["campaign_key"]
+ assert campaign_key != f"alert-firing-notification-{self.alert_check.id}"
+ assert str(self.alert_check.id) in campaign_key
+
+ @patch("posthog.temporal.ai.anomaly_investigation.workflow.dispatch_alert_notification", return_value=[])
+ def test_follow_up_stays_unmarked_when_no_destination_accepts(self, _mock_dispatch) -> None:
+ _deliver_investigation_outcome(
+ alert=self.alert,
+ alert_check=self.alert_check,
+ verdict="false_positive",
+ previous_verdict="true_positive",
+ summary="The spike is a bot crawl.",
+ notebook_short_id=None,
+ )
+
+ self.alert_check.refresh_from_db()
+ assert self.alert_check.targets_notified == {}
+
+ @patch(
+ "posthog.temporal.ai.anomaly_investigation.workflow.dispatch_alert_notification",
+ side_effect=RuntimeError("destination lookup failed"),
+ )
+ def test_follow_up_failure_does_not_fail_the_activity(self, _mock_dispatch) -> None:
+ _deliver_investigation_outcome(
+ alert=self.alert,
+ alert_check=self.alert_check,
+ verdict="false_positive",
+ previous_verdict="true_positive",
+ summary="The spike is a bot crawl.",
+ notebook_short_id=None,
+ )
+
+ self.alert_check.refresh_from_db()
+ assert self.alert_check.targets_notified == {}
diff --git a/posthog/temporal/tests/test_alerts_investigation.py b/posthog/temporal/tests/test_alerts_investigation.py
index c3c8f678c481..72f7b4939772 100644
--- a/posthog/temporal/tests/test_alerts_investigation.py
+++ b/posthog/temporal/tests/test_alerts_investigation.py
@@ -12,15 +12,24 @@ from posthog.test.base import BaseTest
from parameterized import parameterized
-from posthog.schema import AlertState
+from posthog.schema import AlertCalculationInterval, AlertState
-from posthog.temporal.alerts.investigation import claim_investigation_slot, should_trigger_investigation
+from posthog.temporal.alerts.investigation import (
+ IN_FLIGHT_INVESTIGATION_HORIZON,
+ MAX_INVESTIGATIONS_PER_EPISODE,
+ claim_investigation_slot,
+ decide_investigation,
+ investigation_cooldown,
+)
+from products.alerts.backend.investigation_episode import episode_investigations
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus
from products.product_analytics.backend.facade.models import Insight
+_EPISODE_START = datetime(2026, 4, 30, 6, 0, tzinfo=UTC)
-class TestShouldTriggerInvestigation(BaseTest):
+
+class InvestigationTestCase(BaseTest):
def setUp(self) -> None:
super().setUp()
self.insight = Insight.objects.create(team=self.team, name="test insight")
@@ -30,77 +39,206 @@ class TestShouldTriggerInvestigation(BaseTest):
name="anomaly alert",
detector_config={"type": "zscore", "threshold": 0.95, "window": 30},
investigation_agent_enabled=True,
+ calculation_interval=AlertCalculationInterval.HOURLY,
)
- def test_triggers_on_transition_to_firing(self) -> None:
- assert should_trigger_investigation(
- self.alert,
- previous_state=AlertState.NOT_FIRING,
- new_state=AlertState.FIRING,
+ def _make_check(
+ self,
+ *,
+ at: datetime,
+ state: str = AlertState.FIRING,
+ investigation_status: str | None = None,
+ investigation_verdict: str | None = None,
+ ) -> AlertCheck:
+ with freeze_time(at):
+ return AlertCheck.objects.create(
+ alert_configuration=self.alert,
+ state=state,
+ calculated_value=42.0,
+ investigation_status=investigation_status,
+ investigation_verdict=investigation_verdict,
+ )
+
+ def _firing_episode(self, *, investigated: int) -> AlertCheck:
+ """Write a NOT_FIRING check, then `investigated` investigated firing checks,
+ then the current firing check, one hour apart."""
+ self._make_check(at=_EPISODE_START, state=AlertState.NOT_FIRING)
+ for index in range(investigated):
+ self._make_check(
+ at=_EPISODE_START + timedelta(hours=index + 1),
+ investigation_status=InvestigationStatus.DONE,
+ investigation_verdict="true_positive",
+ )
+ return self._make_check(at=_EPISODE_START + timedelta(hours=investigated + 1))
+
+
+class TestDecideInvestigation(InvestigationTestCase):
+ @parameterized.expand([("first", 0), ("second", 1), ("third", MAX_INVESTIGATIONS_PER_EPISODE - 1)])
+ def test_investigates_every_firing_check_inside_the_budget(self, _name: str, already_investigated: int) -> None:
+ check = self._firing_episode(investigated=already_investigated)
+
+ decision = decide_investigation(self.alert, check)
+
+ assert decision.should_investigate
+ assert decision.is_first_of_episode is (already_investigated == 0)
+
+ def test_stops_once_the_budget_is_spent(self) -> None:
+ check = self._firing_episode(investigated=MAX_INVESTIGATIONS_PER_EPISODE)
+
+ assert not decide_investigation(self.alert, check).should_investigate
+
+ def test_investigates_a_check_whose_predecessor_was_dismissed(self) -> None:
+ # The suppressed-false-positive case needs no rule of its own: the next check is
+ # simply the episode's second, and the budget lets it through.
+ self._make_check(at=_EPISODE_START, state=AlertState.NOT_FIRING)
+ self._make_check(
+ at=_EPISODE_START + timedelta(hours=1),
+ investigation_status=InvestigationStatus.DONE,
+ investigation_verdict="false_positive",
)
+ check = self._make_check(at=_EPISODE_START + timedelta(hours=2))
- @parameterized.expand(
- [
- ("already_firing", AlertState.FIRING, AlertState.FIRING),
- ("still_not_firing", AlertState.NOT_FIRING, AlertState.NOT_FIRING),
- ("transition_to_errored", AlertState.NOT_FIRING, AlertState.ERRORED),
- ]
- )
- def test_does_not_trigger_on_other_transitions(self, _name: str, previous: str, new: str) -> None:
- assert not should_trigger_investigation(self.alert, previous_state=previous, new_state=new)
+ decision = decide_investigation(self.alert, check)
+
+ assert decision.should_investigate
+ assert not decision.is_first_of_episode
+
+ def test_budget_resets_after_the_alert_stops_firing(self) -> None:
+ self._firing_episode(investigated=MAX_INVESTIGATIONS_PER_EPISODE)
+ self._make_check(at=_EPISODE_START + timedelta(hours=12), state=AlertState.NOT_FIRING)
+ check = self._make_check(at=_EPISODE_START + timedelta(hours=13))
+
+ decision = decide_investigation(self.alert, check)
+
+ assert decision.should_investigate
+ assert decision.is_first_of_episode
+
+ def test_a_skipped_check_does_not_spend_budget(self) -> None:
+ # SKIPPED means the cooldown refused the slot, so no agent ever ran.
+ self._make_check(at=_EPISODE_START, state=AlertState.NOT_FIRING)
+ for index in range(MAX_INVESTIGATIONS_PER_EPISODE):
+ self._make_check(
+ at=_EPISODE_START + timedelta(hours=index + 1),
+ investigation_status=InvestigationStatus.SKIPPED,
+ )
+ check = self._make_check(at=_EPISODE_START + timedelta(hours=MAX_INVESTIGATIONS_PER_EPISODE + 1))
+
+ assert decide_investigation(self.alert, check).should_investigate
+
+ def test_does_not_gate_a_reminder_after_a_skipped_first_fire(self) -> None:
+ # The cooldown refused the episode's opening fire, so its notification already went
+ # out. The next check must not hold a reminder of an incident the user knows about.
+ self._make_check(at=_EPISODE_START, state=AlertState.NOT_FIRING)
+ self._make_check(
+ at=_EPISODE_START + timedelta(hours=1),
+ investigation_status=InvestigationStatus.SKIPPED,
+ )
+ check = self._make_check(at=_EPISODE_START + timedelta(hours=2))
+
+ decision = decide_investigation(self.alert, check)
+
+ assert decision.should_investigate
+ assert not decision.is_first_of_episode
+
+ @parameterized.expand([("not_firing", AlertState.NOT_FIRING), ("errored", AlertState.ERRORED)])
+ def test_does_not_trigger_on_a_check_that_is_not_firing(self, _name: str, state: str) -> None:
+ check = self._make_check(at=_EPISODE_START + timedelta(hours=1), state=state)
+
+ assert not decide_investigation(self.alert, check).should_investigate
def test_does_not_trigger_when_not_opted_in(self) -> None:
self.alert.investigation_agent_enabled = False
self.alert.save()
- assert not should_trigger_investigation(
- self.alert,
- previous_state=AlertState.NOT_FIRING,
- new_state=AlertState.FIRING,
- )
+ check = self._make_check(at=_EPISODE_START + timedelta(hours=1))
+
+ assert not decide_investigation(self.alert, check).should_investigate
def test_does_not_trigger_for_threshold_only_alerts(self) -> None:
self.alert.detector_config = None
self.alert.save()
- assert not should_trigger_investigation(
- self.alert,
- previous_state=AlertState.NOT_FIRING,
- new_state=AlertState.FIRING,
- )
+ check = self._make_check(at=_EPISODE_START + timedelta(hours=1))
+ assert not decide_investigation(self.alert, check).should_investigate
-class TestClaimInvestigationSlot(BaseTest):
- def setUp(self) -> None:
- super().setUp()
- self.insight = Insight.objects.create(team=self.team, name="test insight")
- self.alert = AlertConfiguration.objects.create(
- team=self.team,
- insight=self.insight,
- name="anomaly alert",
- detector_config={"type": "zscore", "threshold": 0.95, "window": 30},
- investigation_agent_enabled=True,
+
+class TestEpisodeInvestigations(InvestigationTestCase):
+ def test_reports_the_previous_verdict_and_the_episode_key(self) -> None:
+ self._make_check(at=_EPISODE_START, state=AlertState.NOT_FIRING)
+ first = self._make_check(
+ at=_EPISODE_START + timedelta(hours=1),
+ investigation_status=InvestigationStatus.DONE,
+ investigation_verdict="false_positive",
+ )
+ second = self._make_check(
+ at=_EPISODE_START + timedelta(hours=2),
+ investigation_status=InvestigationStatus.DONE,
+ investigation_verdict="true_positive",
)
- def _make_check(self, *, investigation_status: str | None = None) -> AlertCheck:
- return AlertCheck.objects.create(
- alert_configuration=self.alert,
- state=AlertState.FIRING,
- calculated_value=42.0,
- investigation_status=investigation_status,
+ episode = episode_investigations(self.alert, second)
+
+ assert episode.previous_verdict == "false_positive"
+ # Every investigation of one incident emits under the same signal source id.
+ assert episode.first_check_id == str(first.id)
+ assert episode.is_first_fire is False
+
+ def test_a_verdict_from_the_previous_episode_is_not_carried_over(self) -> None:
+ self._make_check(
+ at=_EPISODE_START,
+ investigation_status=InvestigationStatus.DONE,
+ investigation_verdict="true_positive",
)
+ self._make_check(at=_EPISODE_START + timedelta(hours=1), state=AlertState.NOT_FIRING)
+ check = self._make_check(at=_EPISODE_START + timedelta(hours=2))
+
+ episode = episode_investigations(self.alert, check)
+ assert episode.previous_verdict is None
+ assert episode.first_check_id == str(check.id)
+ assert episode.is_first_fire
+
+
+class TestInvestigationCooldown(InvestigationTestCase):
+ @parameterized.expand(
+ [
+ ("real_time", AlertCalculationInterval.REAL_TIME, timedelta(minutes=5)),
+ ("every_15_minutes", AlertCalculationInterval.EVERY_15_MINUTES, timedelta(minutes=10)),
+ # An hourly alert's next check must clear the cooldown, or scheduler jitter
+ # decides whether the episode's second investigation runs.
+ ("hourly", AlertCalculationInterval.HOURLY, timedelta(minutes=55)),
+ ("daily", AlertCalculationInterval.DAILY, timedelta(hours=1)),
+ ]
+ )
+ def test_cooldown_follows_the_calculation_interval(self, _name: str, interval: str, expected: timedelta) -> None:
+ self.alert.calculation_interval = interval
+ self.alert.save()
+
+ assert investigation_cooldown(self.alert) == expected
+
+ def test_hourly_alert_can_investigate_its_next_check(self) -> None:
+ self._make_check(at=_EPISODE_START, investigation_status=InvestigationStatus.DONE)
+ check = self._make_check(at=_EPISODE_START + timedelta(hours=1))
+
+ with freeze_time(_EPISODE_START + timedelta(hours=1)):
+ assert claim_investigation_slot(self.alert, check)
+
+
+class TestClaimInvestigationSlot(InvestigationTestCase):
def test_claims_when_no_recent_investigation(self) -> None:
- check = self._make_check()
- assert claim_investigation_slot(self.alert, check)
+ check = self._make_check(at=_EPISODE_START)
+
+ with freeze_time(_EPISODE_START):
+ assert claim_investigation_slot(self.alert, check)
+
check.refresh_from_db()
assert check.investigation_status == InvestigationStatus.PENDING
def test_skips_when_recent_investigation_exists(self) -> None:
now = datetime(2026, 4, 30, 10, 0, tzinfo=UTC)
- with freeze_time(now - timedelta(minutes=10)):
- self._make_check(investigation_status=InvestigationStatus.DONE)
+ self._make_check(at=now - timedelta(minutes=10), investigation_status=InvestigationStatus.DONE)
+ new_check = self._make_check(at=now)
with freeze_time(now):
- new_check = self._make_check()
assert not claim_investigation_slot(self.alert, new_check)
new_check.refresh_from_db()
@@ -108,11 +246,10 @@ class TestClaimInvestigationSlot(BaseTest):
def test_claims_after_cooldown_expires(self) -> None:
now = datetime(2026, 4, 30, 10, 0, tzinfo=UTC)
- with freeze_time(now - timedelta(hours=2)):
- self._make_check(investigation_status=InvestigationStatus.DONE)
+ self._make_check(at=now - timedelta(hours=2), investigation_status=InvestigationStatus.DONE)
+ new_check = self._make_check(at=now)
with freeze_time(now):
- new_check = self._make_check()
assert claim_investigation_slot(self.alert, new_check)
new_check.refresh_from_db()
@@ -127,11 +264,10 @@ class TestClaimInvestigationSlot(BaseTest):
)
def test_cooldown_blocks_for_active_statuses(self, _name: str, blocking_status: str) -> None:
now = datetime(2026, 4, 30, 10, 0, tzinfo=UTC)
- with freeze_time(now - timedelta(minutes=10)):
- self._make_check(investigation_status=blocking_status)
+ self._make_check(at=now - timedelta(minutes=10), investigation_status=blocking_status)
+ new_check = self._make_check(at=now)
with freeze_time(now):
- new_check = self._make_check()
assert not claim_investigation_slot(self.alert, new_check)
@parameterized.expand(
@@ -142,9 +278,48 @@ class TestClaimInvestigationSlot(BaseTest):
)
def test_cooldown_ignores_terminal_failure_statuses(self, _name: str, terminal_status: str) -> None:
now = datetime(2026, 4, 30, 10, 0, tzinfo=UTC)
- with freeze_time(now - timedelta(minutes=10)):
- self._make_check(investigation_status=terminal_status)
+ self._make_check(at=now - timedelta(minutes=10), investigation_status=terminal_status)
+ new_check = self._make_check(at=now)
+
+ with freeze_time(now):
+ assert claim_investigation_slot(self.alert, new_check)
+
+ @parameterized.expand(
+ [
+ ("pending", InvestigationStatus.PENDING),
+ ("running", InvestigationStatus.RUNNING),
+ ]
+ )
+ def test_in_flight_investigation_blocks_past_the_cooldown(self, _name: str, in_flight_status: str) -> None:
+ self.alert.calculation_interval = AlertCalculationInterval.REAL_TIME
+ self.alert.save()
+ now = datetime(2026, 4, 30, 10, 0, tzinfo=UTC)
+ # Half an hour is an ordinary agent run and far past a real-time alert's five-minute
+ # cooldown, so a time-scoped guard would start a second agent on the same anomaly.
+ self._make_check(at=now - timedelta(minutes=30), investigation_status=in_flight_status)
+ new_check = self._make_check(at=now)
+
+ with freeze_time(now):
+ assert not claim_investigation_slot(self.alert, new_check)
+
+ new_check.refresh_from_db()
+ assert new_check.investigation_status == InvestigationStatus.SKIPPED
+
+ @parameterized.expand(
+ [
+ ("pending", InvestigationStatus.PENDING),
+ ("running", InvestigationStatus.RUNNING),
+ ]
+ )
+ def test_stalled_investigation_stops_blocking_past_the_horizon(self, _name: str, in_flight_status: str) -> None:
+ self.alert.calculation_interval = AlertCalculationInterval.REAL_TIME
+ self.alert.save()
+ now = datetime(2026, 4, 30, 10, 0, tzinfo=UTC)
+ self._make_check(
+ at=now - IN_FLIGHT_INVESTIGATION_HORIZON - timedelta(minutes=1),
+ investigation_status=in_flight_status,
+ )
+ new_check = self._make_check(at=now)
with freeze_time(now):
- new_check = self._make_check()
assert claim_investigation_slot(self.alert, new_check)
diff --git a/products/alerts/backend/investigation_episode.py b/products/alerts/backend/investigation_episode.py
new file mode 100644
index 000000000000..cf19c657d6e1
--- /dev/null
+++ b/products/alerts/backend/investigation_episode.py
@@ -0,0 +1,68 @@
+"""Reads the firing episode an AlertCheck belongs to.
+
+An episode is the run of consecutive FIRING checks since the last check that was not
+FIRING. The investigation agent budgets its work per episode, and it groups everything
+it publishes about one incident under the episode's first check.
+"""
+
+from __future__ import annotations
+
+from posthog.schema import AlertState
+
+from posthog.dataclasses import frozen
+
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus
+
+# Statuses of a check whose investigation was started. SKIPPED never ran, so it costs no
+# budget; FAILED did run and costs one, which keeps a broken agent from retrying forever.
+_STARTED_INVESTIGATION_STATUSES = [
+ InvestigationStatus.PENDING,
+ InvestigationStatus.RUNNING,
+ InvestigationStatus.DONE,
+ InvestigationStatus.FAILED,
+]
+
+
+@frozen
+class EpisodeInvestigations:
+ """What the current firing episode already spent, seen from one check in it."""
+
+ started: int
+ first_check_id: str
+ previous_verdict: str | None
+ # True when no earlier check of this episode fired, so this is the fire the user has not
+ # been told about yet. The count of started investigations cannot answer that: a check
+ # whose investigation the cooldown refused still sent its notification.
+ is_first_fire: bool
+
+
+def episode_investigations(alert: AlertConfiguration, alert_check: AlertCheck) -> EpisodeInvestigations:
+ """Read the firing episode that `alert_check` belongs to.
+
+ The episode starts after the most recent check that was not FIRING, so a check that
+ does not fire resets the budget for the next episode.
+ """
+ earlier = AlertCheck.objects.filter(
+ alert_configuration=alert,
+ created_at__lte=alert_check.created_at,
+ ).exclude(id=alert_check.id)
+
+ episode_start = (
+ earlier.exclude(state=AlertState.FIRING).order_by("-created_at").values_list("created_at", flat=True).first()
+ )
+ if episode_start is not None:
+ earlier = earlier.filter(created_at__gt=episode_start)
+
+ first_check_id = earlier.order_by("created_at").values_list("id", flat=True).first()
+ previous_verdict = (
+ earlier.filter(investigation_verdict__isnull=False)
+ .order_by("-created_at")
+ .values_list("investigation_verdict", flat=True)
+ .first()
+ )
+ return EpisodeInvestigations(
+ started=earlier.filter(investigation_status__in=_STARTED_INVESTIGATION_STATUSES).count(),
+ first_check_id=str(first_check_id or alert_check.id),
+ previous_verdict=previous_verdict,
+ is_first_fire=first_check_id is None,
+ )
diff --git a/products/alerts/backend/models/alert.py b/products/alerts/backend/models/alert.py
index d1d51fc41abe..9b5c36cf966f 100644
--- a/products/alerts/backend/models/alert.py
+++ b/products/alerts/backend/models/alert.py
@@ -163,16 +163,18 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
schedule_restriction = models.JSONField(null=True, blank=True, default=None)
- # When enabled and the alert transitions to FIRING, an investigation agent runs
- # and writes its findings to a linked Notebook. Only effective for detector-based
- # (anomaly) alerts. See posthog/temporal/alerts/workflows.py for the trigger logic.
+ # When enabled, an investigation agent runs on each firing check, up to three per
+ # firing episode, and writes its findings to a linked Notebook. Only effective for
+ # detector-based (anomaly) alerts. See posthog/temporal/alerts/investigation.py for
+ # the trigger logic.
investigation_agent_enabled = models.BooleanField(default=False)
- # When enabled (and investigation_agent_enabled is on), notification dispatch is
- # held until the investigation agent produces a verdict — and suppressed if the
- # verdict is false_positive. A safety-net Temporal workflow force-notifies after a
- # grace period if the investigation stalls, so users can never silently miss a
- # real fire. See posthog/temporal/alerts/workflows.py (RunInvestigationSafetyNetWorkflow).
+ # When enabled (and investigation_agent_enabled is on), the episode's first fire is
+ # held until the investigation agent produces a verdict, and suppressed if the
+ # verdict is false_positive. Later fires of the episode notify without waiting. A
+ # safety-net Temporal workflow force-notifies after a grace period if the
+ # investigation stalls, so users can never silently miss a real fire.
+ # See posthog/temporal/alerts/workflows.py (RunInvestigationSafetyNetWorkflow).
investigation_gates_notifications = models.BooleanField(default=False)
# What to do with an "inconclusive" verdict when notifications are gated.
diff --git a/products/alerts/backend/presentation/views/alert.py b/products/alerts/backend/presentation/views/alert.py
index 604794caa199..5033eb7ee705 100644
--- a/products/alerts/backend/presentation/views/alert.py
+++ b/products/alerts/backend/presentation/views/alert.py
@@ -465,11 +465,11 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
)
investigation_agent_enabled = serializers.BooleanField(
required=False,
- help_text="When enabled, an investigation agent runs on the state transition to firing and writes findings to a Notebook linked from the alert check. Only effective for detector-based (anomaly) alerts.",
+ help_text="When enabled, an investigation agent runs on each check where the alert fires, up to three times per firing episode, and writes findings to a Notebook linked from the alert check. An episode is the run of consecutive firing checks since the last check that did not fire. A later investigation of the same episode that reaches a different verdict sends one follow-up notification, unless investigation_inconclusive_action suppresses it. Only effective for detector-based (anomaly) alerts.",
)
investigation_gates_notifications = serializers.BooleanField(
required=False,
- help_text="When enabled (and investigation_agent_enabled is on), notification dispatch is held until the investigation agent produces a verdict. Notifications are suppressed when the verdict is false_positive (and optionally when inconclusive). A safety-net task force-fires after a few minutes if the investigation stalls.",
+ help_text="When enabled (and investigation_agent_enabled is on), the first fire of an episode is held until the investigation agent produces a verdict, and that notification is suppressed when the verdict is false_positive (and optionally when inconclusive). Later fires of the same episode notify without waiting. A safety-net task force-fires after a few minutes if the investigation stalls.",
)
investigation_inconclusive_action = serializers.ChoiceField(
choices=[("notify", "Notify"), ("suppress", "Suppress")],
diff --git a/products/alerts/frontend/components/InvestigationAgentSettings.tsx b/products/alerts/frontend/components/InvestigationAgentSettings.tsx
index c95c1889679f..c6b9f7171029 100644
--- a/products/alerts/frontend/components/InvestigationAgentSettings.tsx
+++ b/products/alerts/frontend/components/InvestigationAgentSettings.tsx
@@ -33,7 +33,7 @@ export function InvestigationAgentSettings({
<span className="flex items-center gap-1">
Run investigation agent when this alert fires
<Tooltip
- title="On the transition to firing, an agent validates the anomaly with read-only queries, writes a notebook with its findings, and links it from the alert check history. Runs once per transition."
+ title="On each check where this alert fires, an agent validates the anomaly with read-only queries, writes a notebook with its findings, and links it from the alert check history. It runs up to 3 times per firing episode, then stops until the alert stops firing."
placement="right"
delayMs={0}
>
@@ -53,7 +53,7 @@ export function InvestigationAgentSettings({
<span className="flex items-center gap-1">
Wait for the verdict before notifying
<Tooltip
- title="Notifications are delayed ~30–90s while the agent investigates. False-positive verdicts are suppressed. A safety-net task force-fires after a few minutes if the investigation stalls, so real fires can't be silently missed."
+ title="Only the first fire of an episode waits, by about 30 to 90 seconds, while the agent investigates. False-positive verdicts are suppressed. A safety-net task force-fires after a few minutes if the investigation stalls, so real fires can't be silently missed. Later fires notify right away, and a changed verdict arrives as a follow-up."
placement="right"
delayMs={0}
>
diff --git a/products/alerts/frontend/generated/api.schemas.ts b/products/alerts/frontend/generated/api.schemas.ts
index 758330db5ceb..c996321ad1af 100644
--- a/products/alerts/frontend/generated/api.schemas.ts
+++ b/products/alerts/frontend/generated/api.schemas.ts
@@ -695,9 +695,9 @@ export interface AlertApi {
* @nullable
*/
readonly last_value: number | null
- /** When enabled, an investigation agent runs on the state transition to firing and writes findings to a Notebook linked from the alert check. Only effective for detector-based (anomaly) alerts. */
+ /** When enabled, an investigation agent runs on each check where the alert fires, up to three times per firing episode, and writes findings to a Notebook linked from the alert check. An episode is the run of consecutive firing checks since the last check that did not fire. A later investigation of the same episode that reaches a different verdict sends one follow-up notification, unless investigation_inconclusive_action suppresses it. Only effective for detector-based (anomaly) alerts. */
investigation_agent_enabled?: boolean
- /** When enabled (and investigation_agent_enabled is on), notification dispatch is held until the investigation agent produces a verdict. Notifications are suppressed when the verdict is false_positive (and optionally when inconclusive). A safety-net task force-fires after a few minutes if the investigation stalls. */
+ /** When enabled (and investigation_agent_enabled is on), the first fire of an episode is held until the investigation agent produces a verdict, and that notification is suppressed when the verdict is false_positive (and optionally when inconclusive). Later fires of the same episode notify without waiting. A safety-net task force-fires after a few minutes if the investigation stalls. */
investigation_gates_notifications?: boolean
/** How to handle an 'inconclusive' verdict: whether gated notifications fire and whether the investigation surfaces in the Signals inbox. 'notify' is the safe default — an agent that can't be sure is itself useful signal. False positives never reach the inbox regardless of this setting.
*
@@ -784,9 +784,9 @@ export interface PatchedAlertApi {
* @nullable
*/
readonly last_value?: number | null
- /** When enabled, an investigation agent runs on the state transition to firing and writes findings to a Notebook linked from the alert check. Only effective for detector-based (anomaly) alerts. */
+ /** When enabled, an investigation agent runs on each check where the alert fires, up to three times per firing episode, and writes findings to a Notebook linked from the alert check. An episode is the run of consecutive firing checks since the last check that did not fire. A later investigation of the same episode that reaches a different verdict sends one follow-up notification, unless investigation_inconclusive_action suppresses it. Only effective for detector-based (anomaly) alerts. */
investigation_agent_enabled?: boolean
- /** When enabled (and investigation_agent_enabled is on), notification dispatch is held until the investigation agent produces a verdict. Notifications are suppressed when the verdict is false_positive (and optionally when inconclusive). A safety-net task force-fires after a few minutes if the investigation stalls. */
+ /** When enabled (and investigation_agent_enabled is on), the first fire of an episode is held until the investigation agent produces a verdict, and that notification is suppressed when the verdict is false_positive (and optionally when inconclusive). Later fires of the same episode notify without waiting. A safety-net task force-fires after a few minutes if the investigation stalls. */
investigation_gates_notifications?: boolean
/** How to handle an 'inconclusive' verdict: whether gated notifications fire and whether the investigation surfaces in the Signals inbox. 'notify' is the safe default — an agent that can't be sure is itself useful signal. False positives never reach the inbox regardless of this setting.
*
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3d0f04210942..f7adb46900e4 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -10054,9 +10054,9 @@ export namespace Schemas {
* @nullable
*/
readonly last_value: number | null;
- /** When enabled, an investigation agent runs on the state transition to firing and writes findings to a Notebook linked from the alert check. Only effective for detector-based (anomaly) alerts. */
+ /** When enabled, an investigation agent runs on each check where the alert fires, up to three times per firing episode, and writes findings to a Notebook linked from the alert check. An episode is the run of consecutive firing checks since the last check that did not fire. A later investigation of the same episode that reaches a different verdict sends one follow-up notification, unless investigation_inconclusive_action suppresses it. Only effective for detector-based (anomaly) alerts. */
investigation_agent_enabled?: boolean;
- /** When enabled (and investigation_agent_enabled is on), notification dispatch is held until the investigation agent produces a verdict. Notifications are suppressed when the verdict is false_positive (and optionally when inconclusive). A safety-net task force-fires after a few minutes if the investigation stalls. */
+ /** When enabled (and investigation_agent_enabled is on), the first fire of an episode is held until the investigation agent produces a verdict, and that notification is suppressed when the verdict is false_positive (and optionally when inconclusive). Later fires of the same episode notify without waiting. A safety-net task force-fires after a few minutes if the investigation stalls. */
investigation_gates_notifications?: boolean;
/** How to handle an 'inconclusive' verdict: whether gated notifications fire and whether the investigation surfaces in the Signals inbox. 'notify' is the safe default — an agent that can't be sure is itself useful signal. False positives never reach the inbox regardless of this setting.
*
@@ -60240,9 +60240,9 @@ export namespace Schemas {
* @nullable
*/
readonly last_value?: number | null;
- /** When enabled, an investigation agent runs on the state transition to firing and writes findings to a Notebook linked from the alert check. Only effective for detector-based (anomaly) alerts. */
+ /** When enabled, an investigation agent runs on each check where the alert fires, up to three times per firing episode, and writes findings to a Notebook linked from the alert check. An episode is the run of consecutive firing checks since the last check that did not fire. A later investigation of the same episode that reaches a different verdict sends one follow-up notification, unless investigation_inconclusive_action suppresses it. Only effective for detector-based (anomaly) alerts. */
investigation_agent_enabled?: boolean;
- /** When enabled (and investigation_agent_enabled is on), notification dispatch is held until the investigation agent produces a verdict. Notifications are suppressed when the verdict is false_positive (and optionally when inconclusive). A safety-net task force-fires after a few minutes if the investigation stalls. */
+ /** When enabled (and investigation_agent_enabled is on), the first fire of an episode is held until the investigation agent produces a verdict, and that notification is suppressed when the verdict is false_positive (and optionally when inconclusive). Later fires of the same episode notify without waiting. A safety-net task force-fires after a few minutes if the investigation stalls. */
investigation_gates_notifications?: boolean;
/** How to handle an 'inconclusive' verdict: whether gated notifications fire and whether the investigation surfaces in the Signals inbox. 'notify' is the safe default — an agent that can't be sure is itself useful signal. False positives never reach the inbox regardless of this setting.
*
diff --git a/services/mcp/src/generated/alerts/api.ts b/services/mcp/src/generated/alerts/api.ts
index e28c848f49fb..7e0e9c6ebaff 100644
--- a/services/mcp/src/generated/alerts/api.ts
+++ b/services/mcp/src/generated/alerts/api.ts
@@ -1291,13 +1291,13 @@ export const AlertsCreateBody = () => zod.object({
.boolean()
.optional()
.describe(
- 'When enabled, an investigation agent runs on the state transition to firing and writes findings to a Notebook linked from the alert check. Only effective for detector-based (anomaly) alerts.'
+ 'When enabled, an investigation agent runs on each check where the alert fires, up to three times per firing episode, and writes findings to a Notebook linked from the alert check. An episode is the run of consecutive firing checks since the last check that did not fire. A later investigation of the same episode that reaches a different verdict sends one follow-up notification, unless investigation_inconclusive_action suppresses it. Only effective for detector-based (anomaly) alerts.'
),
investigation_gates_notifications: zod
.boolean()
.optional()
.describe(
- 'When enabled (and investigation_agent_enabled is on), notification dispatch is held until the investigation agent produces a verdict. Notifications are suppressed when the verdict is false_positive (and optionally when inconclusive). A safety-net task force-fires after a few minutes if the investigation stalls.'
+ 'When enabled (and investigation_agent_enabled is on), the first fire of an episode is held until the investigation agent produces a verdict, and that notification is suppressed when the verdict is false_positive (and optionally when inconclusive). Later fires of the same episode notify without waiting. A safety-net task force-fires after a few minutes if the investigation stalls.'
),
investigation_inconclusive_action: zod
.enum(['notify', 'suppress'])
@@ -2620,13 +2620,13 @@ export const AlertsPartialUpdateBody = () => zod.object({
.boolean()
.optional()
.describe(
- 'When enabled, an investigation agent runs on the state transition to firing and writes findings to a Notebook linked from the alert check. Only effective for detector-based (anomaly) alerts.'
+ 'When enabled, an investigation agent runs on each check where the alert fires, up to three times per firing episode, and writes findings to a Notebook linked from the alert check. An episode is the run of consecutive firing checks since the last check that did not fire. A later investigation of the same episode that reaches a different verdict sends one follow-up notification, unless investigation_inconclusive_action suppresses it. Only effective for detector-based (anomaly) alerts.'
),
investigation_gates_notifications: zod
.boolean()
.optional()
.describe(
- 'When enabled (and investigation_agent_enabled is on), notification dispatch is held until the investigation agent produces a verdict. Notifications are suppressed when the verdict is false_positive (and optionally when inconclusive). A safety-net task force-fires after a few minutes if the investigation stalls.'
+ 'When enabled (and investigation_agent_enabled is on), the first fire of an episode is held until the investigation agent produces a verdict, and that notification is suppressed when the verdict is false_positive (and optionally when inconclusive). Later fires of the same episode notify without waiting. A safety-net task force-fires after a few minutes if the investigation stalls.'
),
investigation_inconclusive_action: zod
.enum(['notify', 'suppress'])
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json
index 97cacfe55201..55200701f710 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json
@@ -2232,11 +2232,11 @@
"type": "number"
},
"investigation_agent_enabled": {
- "description": "When enabled, an investigation agent runs on the state transition to firing and writes findings to a Notebook linked from the alert check. Only effective for detector-based (anomaly) alerts.",
+ "description": "When enabled, an investigation agent runs on each check where the alert fires, up to three times per firing episode, and writes findings to a Notebook linked from the alert check. An episode is the run of consecutive firing checks since the last check that did not fire. A later investigation of the same episode that reaches a different verdict sends one follow-up notification, unless investigation_inconclusive_action suppresses it. Only effective for detector-based (anomaly) alerts.",
"type": "boolean"
},
"investigation_gates_notifications": {
- "description": "When enabled (and investigation_agent_enabled is on), notification dispatch is held until the investigation agent produces a verdict. Notifications are suppressed when the verdict is false_positive (and optionally when inconclusive). A safety-net task force-fires after a few minutes if the investigation stalls.",
+ "description": "When enabled (and investigation_agent_enabled is on), the first fire of an episode is held until the investigation agent produces a verdict, and that notification is suppressed when the verdict is false_positive (and optionally when inconclusive). Later fires of the same episode notify without waiting. A safety-net task force-fires after a few minutes if the investigation stalls.",
"type": "boolean"
},
"investigation_inconclusive_action": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json
index bee2683eafc6..f1a9435eb606 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json
@@ -2236,11 +2236,11 @@
"type": "number"
},
"investigation_agent_enabled": {
- "description": "When enabled, an investigation agent runs on the state transition to firing and writes findings to a Notebook linked from the alert check. Only effective for detector-based (anomaly) alerts.",
+ "description": "When enabled, an investigation agent runs on each check where the alert fires, up to three times per firing episode, and writes findings to a Notebook linked from the alert check. An episode is the run of consecutive firing checks since the last check that did not fire. A later investigation of the same episode that reaches a different verdict sends one follow-up notification, unless investigation_inconclusive_action suppresses it. Only effective for detector-based (anomaly) alerts.",
"type": "boolean"
},
"investigation_gates_notifications": {
- "description": "When enabled (and investigation_agent_enabled is on), notification dispatch is held until the investigation agent produces a verdict. Notifications are suppressed when the verdict is false_positive (and optionally when inconclusive). A safety-net task force-fires after a few minutes if the investigation stalls.",
+ "description": "When enabled (and investigation_agent_enabled is on), the first fire of an episode is held until the investigation agent produces a verdict, and that notification is suppressed when the verdict is false_positive (and optionally when inconclusive). Later fires of the same episode notify without waiting. A safety-net task force-fires after a few minutes if the investigation stalls.",
"type": "boolean"
},
"investigation_inconclusive_action": {