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 firing metrics alerts synchronously (#70904)

Daniel Visca681fc07aa568
diff --git a/posthog/tasks/alerts/metrics_investigation.py b/posthog/tasks/alerts/metrics_investigation.py
new file mode 100644
index 000000000000..80adf83b1785
--- /dev/null
+++ b/posthog/tasks/alerts/metrics_investigation.py
@@ -0,0 +1,200 @@
+"""Synchronous investigation for firing metrics alerts.
+
+When a threshold alert on a metrics insight transitions into FIRING and the
+alert has the investigation agent enabled, the metrics facade investigates the
+window around the fire and the outcome lands on the AlertCheck's existing
+investigation fields — so the alert page carries the why, not just the that.
+Distinct from the detector alerts' agent workflow: this is a bounded set of
+metric queries, run in-line with the check, no agent or notebook involved.
+
+Frequency is bounded by the same per-alert cooldown the detector path uses
+(`claim_investigation_slot`), which the caller claims inside the check's
+transaction; the run itself happens outside that transaction because it issues
+ClickHouse queries and must never hold the row lock or affect the check outcome.
+"""
+
+import math
+from typing import TYPE_CHECKING, Any, NamedTuple
+
+import structlog
+
+from posthog.schema import AlertState, NodeKind
+
+from posthog.utils import get_from_dict_or_attr
+
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus
+
+if TYPE_CHECKING:
+ from products.metrics.backend.facade.contracts import InvestigationResult
+
+logger = structlog.get_logger(__name__)
+
+# Each target costs a handful of synchronous ClickHouse queries in the
+# alert-evaluation path, so multi-clause investigations stay bounded.
+MAX_INVESTIGATED_CLAUSES = 3
+# Mover keys and labels come from ingested telemetry, so the persisted summary
+# is capped rather than trusting label sizes.
+MAX_SUMMARY_LENGTH = 4000
+
+_SERVICE_FILTER_KEYS = ("service.name", "service_name")
+
+
+class _InvestigationTarget(NamedTuple):
+ metric_name: str
+ service_name: str | None
+ # The op of a service filter no single service could be derived from
+ # (anything but eq) — surfaced as a caveat on the summary.
+ unscoped_service_op: str | None
+
+
+def should_investigate_metrics_alert(
+ alert: AlertConfiguration,
+ *,
+ previous_state: str | None,
+ new_state: str,
+) -> bool:
+ """True when this check is eligible for a synchronous metrics investigation:
+ a threshold (non-detector) alert on a metrics insight, opted in via the
+ investigation flag, on a transition into FIRING (not on every re-fire).
+
+ Cooldown is enforced separately by `claim_investigation_slot`, mirroring the
+ detector path. Never raises — an unexpected error reading the insight kind
+ must not break the alert-evaluation path, so it degrades to "don't
+ investigate".
+ """
+ if not alert.investigation_agent_enabled or alert.detector_config:
+ return False
+ if previous_state == AlertState.FIRING or new_state != AlertState.FIRING:
+ return False
+ try:
+ return alert.insight.alertable_query_kind == NodeKind.METRICS_QUERY
+ except Exception:
+ logger.exception("metrics_alert_investigation_gate_failed", alert_id=str(alert.id))
+ return False
+
+
+def run_metrics_alert_investigation(alert: AlertConfiguration, alert_check: AlertCheck) -> None:
+ """Investigate the fired metric and persist the outcome on the check.
+
+ Never raises: an investigation failure is recorded on the check and must
+ not affect the alert's state or its notifications. Run OUTSIDE the check's
+ persistence transaction — this issues ClickHouse queries.
+ """
+ try:
+ summary = _run_investigation(alert, alert_check)
+ alert_check.investigation_status = InvestigationStatus.DONE
+ alert_check.investigation_summary = summary
+ alert_check.save(update_fields=["investigation_status", "investigation_summary"])
+ except Exception as error:
+ logger.exception("metrics_alert_investigation_failed", alert_id=str(alert.id), error=str(error))
+ alert_check.investigation_status = InvestigationStatus.FAILED
+ alert_check.investigation_error = {"message": str(error)[:1000]}
+ alert_check.save(update_fields=["investigation_status", "investigation_error"])
+
+
+def _run_investigation(alert: AlertConfiguration, alert_check: AlertCheck) -> str:
+ # Deferred: the facade pulls in HogQL machinery that must stay off the
+ # alerts import path (matching how core defers facade.queries).
+ from products.metrics.backend.facade.api import investigate_incident # noqa: PLC0415
+ from products.metrics.backend.facade.contracts import IncidentContext # noqa: PLC0415
+
+ summaries: list[str] = []
+ for target in _investigation_targets(alert):
+ result = investigate_incident(
+ team=alert.team,
+ context=IncidentContext(
+ metric_name=target.metric_name,
+ fired_at=alert_check.created_at,
+ service_name=target.service_name,
+ ),
+ )
+ summary = _summarize(result)
+ if target.unscoped_service_op:
+ summary += (
+ f" (The alert filters service.name with '{target.unscoped_service_op}', which does not pin "
+ "down a single service, so this investigation ran across all services.)"
+ )
+ summaries.append(summary)
+ return " ".join(summaries)[:MAX_SUMMARY_LENGTH]
+
+
+def _investigation_targets(alert: AlertConfiguration) -> list[_InvestigationTarget]:
+ """The (metric, service) pairs to investigate for this alert.
+
+ The check records a single fired value with no pointer to the clause that
+ breached (a formula query doesn't even evaluate clauses separately), so
+ every distinct clause target is investigated — bounded by
+ MAX_INVESTIGATED_CLAUSES — rather than assuming the first clause is the
+ one that moved.
+ """
+ query = alert.insight.query or {}
+ clauses = get_from_dict_or_attr(query, "clauses") or []
+ if not clauses:
+ raise ValueError("Metrics insight has no clauses to investigate")
+ targets: list[_InvestigationTarget] = []
+ seen: set[tuple[str, str | None]] = set()
+ for clause in clauses:
+ metric_name = get_from_dict_or_attr(clause, "metricName")
+ if not metric_name:
+ continue
+ service_name, unscoped_service_op = _service_scope(clause)
+ if (metric_name, service_name) in seen:
+ continue
+ seen.add((metric_name, service_name))
+ targets.append(_InvestigationTarget(metric_name, service_name, unscoped_service_op))
+ if len(targets) == MAX_INVESTIGATED_CLAUSES:
+ break
+ if not targets:
+ raise ValueError("Metrics insight clauses have no metric name to investigate")
+ return targets
+
+
+def _service_scope(clause: Any) -> tuple[str | None, str | None]:
+ """The clause's service scope: (service to investigate, underivable op).
+
+ The metrics filter ops are eq/neq/regex/not_regex over a single value, so
+ only an eq filter pins down the one service to scope the investigation to.
+ Any other service filter can't be applied (IncidentContext scopes by exact
+ service), so its op is reported back for a summary caveat instead of
+ silently investigating globally.
+ """
+ unscoped_op: str | None = None
+ for filter_ in get_from_dict_or_attr(clause, "filters") or []:
+ if get_from_dict_or_attr(filter_, "key") not in _SERVICE_FILTER_KEYS:
+ continue
+ op = get_from_dict_or_attr(filter_, "op") or "eq"
+ value = get_from_dict_or_attr(filter_, "value")
+ if op == "eq" and value:
+ return value, None
+ unscoped_op = unscoped_op or op
+ return None, unscoped_op
+
+
+def _summarize(result: "InvestigationResult") -> str:
+ """A compact human summary of the InvestigationResult for the check record.
+
+ Kept plain-text and short: it renders in the alert page's investigation
+ section and in notification surfaces that only carry a sentence or two.
+ """
+ symptom = result.symptom
+ no_movement = symptom.direction == "flat" or (symptom.baseline_mean == 0 and symptom.anomaly_mean == 0)
+ if no_movement:
+ headline = f"{result.metric_name} showed no significant movement in the window"
+ else:
+ if symptom.baseline_mean and math.isfinite(symptom.change_ratio):
+ change = f"{symptom.change_ratio:.1f}x"
+ else:
+ change = "from a near-zero baseline"
+ headline = (
+ f"{result.metric_name} moved {symptom.direction} to {symptom.anomaly_mean:.2f} "
+ f"(baseline {symptom.baseline_mean:.2f}, {change})"
+ + (f", starting around {symptom.onset_time}" if symptom.onset_time else "")
+ )
+ lines = [f"{headline}. Blast radius: {result.blast_radius}; confidence: {result.confidence}."]
+ movers = ", ".join(f"{mover.key}={mover.label}" for mover in symptom.top_movers[:3])
+ if movers:
+ lines.append(f"Top movers: {movers}.")
+ companions = ", ".join(f"{companion.metric_name} {companion.direction}" for companion in result.companions[:3])
+ if companions:
+ lines.append(f"Companions: {companions}.")
+ return " ".join(lines)
diff --git a/posthog/tasks/alerts/test/alert_check_helpers.py b/posthog/tasks/alerts/test/alert_check_helpers.py
index 94b949a76c27..bc4b3ad0e97d 100644
--- a/posthog/tasks/alerts/test/alert_check_helpers.py
+++ b/posthog/tasks/alerts/test/alert_check_helpers.py
@@ -3,6 +3,8 @@ import traceback
from django.db import transaction
from posthog.tasks.alerts import utils as alert_utils
+from posthog.tasks.alerts.metrics_investigation import run_metrics_alert_investigation, should_investigate_metrics_alert
+from posthog.temporal.alerts.investigation import claim_investigation_slot
from products.alerts.backend.evaluation import check_alert_for_insight
from products.alerts.backend.models import AlertConfiguration
@@ -14,11 +16,13 @@ def run_alert_check(alert_id: str) -> None:
error = None
result = None
+ previous_state = alert.state
try:
result = check_alert_for_insight(alert)
except Exception as e:
error = {"message": str(e), "traceback": traceback.format_exc()}
+ should_run_metrics_investigation = False
with transaction.atomic():
alert_check, notify = alert_utils.add_alert_check(
alert,
@@ -32,6 +36,18 @@ def run_alert_check(alert_id: str) -> None:
triggered_metadata=result.triggered_metadata if result else None,
)
+ # Claim the cooldown slot inside the transaction (read-then-write stays
+ # consistent with the check insert), mirroring the detector path.
+ if should_investigate_metrics_alert(
+ alert, previous_state=previous_state, new_state=alert_check.state
+ ) and claim_investigation_slot(alert, alert_check):
+ should_run_metrics_investigation = True
+
+ # Outside the persistence transaction: the investigation issues ClickHouse
+ # queries and must never hold the row lock or affect the check outcome.
+ if should_run_metrics_investigation:
+ run_metrics_alert_investigation(alert, alert_check)
+
if not notify:
return
diff --git a/posthog/tasks/alerts/test/test_metrics_alerts.py b/posthog/tasks/alerts/test/test_metrics_alerts.py
index 7695c2fa85b3..1c1c1aed115f 100644
--- a/posthog/tasks/alerts/test/test_metrics_alerts.py
+++ b/posthog/tasks/alerts/test/test_metrics_alerts.py
@@ -14,9 +14,17 @@ from posthog.api.test.dashboards import DashboardAPI
from posthog.models.instance_setting import set_instance_setting
from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
from posthog.models.utils import generate_random_token_personal
+from posthog.tasks.alerts.metrics_investigation import MAX_SUMMARY_LENGTH
from posthog.tasks.alerts.test.alert_check_helpers import run_alert_check
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
+from products.metrics.backend.facade.contracts import (
+ InvestigationEvidence,
+ InvestigationResult,
+ MetricAnomalyDimension,
+ MetricAnomalyReport,
+ MetricSeries,
+)
from products.metrics.backend.facade.testing import seed_metric
# 08:55 — the 08:00 hourly bucket is still accumulating; 07:00 is the last complete one.
@@ -27,6 +35,41 @@ def _metrics_flag_only(flag: str, *args: Any, **kwargs: Any) -> bool:
return flag == "metrics"
+def _stub_investigation_result(metric_name: str, mover_label: str = "pod-1") -> InvestigationResult:
+ symptom = MetricAnomalyReport(
+ metric_name=metric_name,
+ aggregation="avg",
+ interval="1 minute",
+ baseline_from="2026-07-01T05:00:00+00:00",
+ baseline_to="2026-07-01T06:00:00+00:00",
+ anomaly_from="2026-07-01T06:00:00+00:00",
+ anomaly_to="2026-07-01T07:00:00+00:00",
+ baseline_mean=5.0,
+ baseline_stddev=0.5,
+ anomaly_mean=50.0,
+ anomaly_peak=60.0,
+ change_ratio=10.0,
+ direction="up",
+ onset_time=None,
+ top_movers=(
+ MetricAnomalyDimension(
+ key="pod", label=mover_label, baseline_value=5.0, anomaly_value=50.0, change_ratio=10.0
+ ),
+ ),
+ series=MetricSeries(labels={}, points=()),
+ )
+ return InvestigationResult(
+ metric_name=metric_name,
+ symptom=symptom,
+ blast_radius="localized",
+ companions=(),
+ chart_specs=(),
+ evidence=InvestigationEvidence(service_name=None),
+ confidence="high",
+ narrative="",
+ )
+
+
@freeze_time(FROZEN_TIME)
@patch("products.alerts.backend.api.alert.posthoganalytics.feature_enabled", side_effect=_metrics_flag_only)
@patch("posthog.tasks.alerts.utils.send_notifications_for_errors")
@@ -40,11 +83,15 @@ class TestMetricsAlerts(APIBaseTest, ClickhouseTestMixin):
# metrics1 is not truncated between tests, so a per-test metric name keeps tests isolated.
self.metric_name = f"queue.depth.{self._testMethodName}"
- def create_metrics_insight(self, group_by: Optional[list[str]] = None) -> dict:
- clause: dict[str, Any] = {"name": "a", "metricName": self.metric_name, "aggregation": "avg"}
- if group_by:
- clause["groupBy"] = [{"key": key} for key in group_by]
- query_dict = {"kind": "MetricsQuery", "clauses": [clause]}
+ def create_metrics_insight(
+ self, group_by: Optional[list[str]] = None, clauses: Optional[list[dict[str, Any]]] = None
+ ) -> dict:
+ if clauses is None:
+ clause: dict[str, Any] = {"name": "a", "metricName": self.metric_name, "aggregation": "avg"}
+ if group_by:
+ clause["groupBy"] = [{"key": key} for key in group_by]
+ clauses = [clause]
+ query_dict = {"kind": "MetricsQuery", "clauses": clauses}
return self.dashboard_api.create_insight(data={"name": "metrics insight", "query": query_dict})[1]
def create_alert(
@@ -340,3 +387,171 @@ class TestMetricsAlerts(APIBaseTest, ClickhouseTestMixin):
insight = self.create_metrics_insight()
response = self.create_alert(insight, lower=1.0, config=config, expected_status=400, **alert_overrides)
assert expected_fragment in str(response).lower(), response
+
+ def test_firing_metrics_alert_runs_investigation_and_persists_summary(
+ self, mock_send_breaches: MagicMock, mock_send_errors: MagicMock, mock_feature_enabled: MagicMock
+ ) -> None:
+ # The roadmap loop: a firing metrics alert attaches an investigation to its
+ # check, so the alert page carries the why, not just the that.
+ self.seed_gauge(dict.fromkeys(range(0, 6), 5.0) | {6: 50.0, 7: 50.0})
+ insight = self.create_metrics_insight()
+ alert = self.create_alert(insight, upper=20.0, investigation_agent_enabled=True)
+
+ run_alert_check(alert["id"])
+
+ alert_check = AlertCheck.objects.filter(alert_configuration=alert["id"]).latest("created_at")
+ assert AlertConfiguration.objects.get(pk=alert["id"]).state == AlertState.FIRING
+ assert alert_check.investigation_status == "done"
+ assert alert_check.investigation_summary
+ assert self.metric_name in alert_check.investigation_summary
+
+ def test_investigation_only_runs_when_enabled(
+ self, mock_send_breaches: MagicMock, mock_send_errors: MagicMock, mock_feature_enabled: MagicMock
+ ) -> None:
+ self.seed_gauge({6: 50.0, 7: 50.0})
+ insight = self.create_metrics_insight()
+ alert = self.create_alert(insight, upper=20.0)
+
+ run_alert_check(alert["id"])
+
+ alert_check = AlertCheck.objects.filter(alert_configuration=alert["id"]).latest("created_at")
+ assert alert_check.investigation_status is None
+ assert alert_check.investigation_summary is None
+
+ def test_investigation_failure_is_recorded_without_breaking_the_alert(
+ self, mock_send_breaches: MagicMock, mock_send_errors: MagicMock, mock_feature_enabled: MagicMock
+ ) -> None:
+ self.seed_gauge({6: 50.0, 7: 50.0})
+ insight = self.create_metrics_insight()
+ alert = self.create_alert(insight, upper=20.0, investigation_agent_enabled=True)
+
+ with patch(
+ "posthog.tasks.alerts.metrics_investigation._run_investigation",
+ side_effect=RuntimeError("boom"),
+ ):
+ run_alert_check(alert["id"])
+
+ alert_check = AlertCheck.objects.filter(alert_configuration=alert["id"]).latest("created_at")
+ assert AlertConfiguration.objects.get(pk=alert["id"]).state == AlertState.FIRING
+ assert alert_check.investigation_status == "failed"
+ mock_send_breaches.assert_called_once() # the alert still notifies
+
+ def test_multi_clause_alert_investigates_each_distinct_clause(
+ self, mock_send_breaches: MagicMock, mock_send_errors: MagicMock, mock_feature_enabled: MagicMock
+ ) -> None:
+ # The check records one fired value with no pointer to the breaching
+ # clause, so an investigation pinned to clauses[0] could summarize the
+ # wrong metric; duplicate targets are investigated only once.
+ self.seed_gauge({6: 50.0, 7: 50.0})
+ insight = self.create_metrics_insight(
+ clauses=[
+ {"name": "a", "metricName": self.metric_name, "aggregation": "avg"},
+ {"name": "b", "metricName": "companion.metric", "aggregation": "avg"},
+ {"name": "c", "metricName": self.metric_name, "aggregation": "sum"},
+ ]
+ )
+ alert = self.create_alert(insight, upper=20.0, investigation_agent_enabled=True)
+
+ with patch(
+ "products.metrics.backend.facade.api.investigate_incident",
+ side_effect=lambda *, team, context: _stub_investigation_result(context.metric_name),
+ ) as mock_investigate:
+ run_alert_check(alert["id"])
+
+ investigated = [call.kwargs["context"].metric_name for call in mock_investigate.call_args_list]
+ assert investigated == [self.metric_name, "companion.metric"]
+ alert_check = AlertCheck.objects.filter(alert_configuration=alert["id"]).latest("created_at")
+ assert alert_check.investigation_status == "done"
+ assert alert_check.investigation_summary is not None
+ assert self.metric_name in alert_check.investigation_summary
+ assert "companion.metric" in alert_check.investigation_summary
+
+ @parameterized.expand(
+ [
+ # (name, service filter, service the investigation is scoped to, caveat expected)
+ ("eq_scopes_to_the_service", {"key": "service.name", "op": "eq", "value": "billing"}, "billing", False),
+ ("neq_cannot_derive_a_service", {"key": "service.name", "op": "neq", "value": "billing"}, None, True),
+ ("regex_cannot_derive_a_service", {"key": "service.name", "op": "regex", "value": "bill.*"}, None, True),
+ ]
+ )
+ def test_investigation_service_scope_from_clause_filters(
+ self,
+ mock_send_breaches: MagicMock,
+ mock_send_errors: MagicMock,
+ mock_feature_enabled: MagicMock,
+ _name: str,
+ service_filter: dict[str, str],
+ expected_service: Optional[str],
+ expects_caveat: bool,
+ ) -> None:
+ # The seeded first clause fires the alert; the second clause carries the
+ # service filter under test. A non-eq filter can't pin down one service,
+ # so the summary must say the investigation ran unscoped.
+ self.seed_gauge({6: 50.0, 7: 50.0})
+ insight = self.create_metrics_insight(
+ clauses=[
+ {"name": "a", "metricName": self.metric_name, "aggregation": "avg"},
+ {"name": "b", "metricName": "scoped.metric", "aggregation": "avg", "filters": [service_filter]},
+ ]
+ )
+ alert = self.create_alert(insight, upper=20.0, investigation_agent_enabled=True)
+
+ with patch(
+ "products.metrics.backend.facade.api.investigate_incident",
+ side_effect=lambda *, team, context: _stub_investigation_result(context.metric_name),
+ ) as mock_investigate:
+ run_alert_check(alert["id"])
+
+ scoped_call = mock_investigate.call_args_list[1]
+ assert scoped_call.kwargs["context"].service_name == expected_service
+ alert_check = AlertCheck.objects.filter(alert_configuration=alert["id"]).latest("created_at")
+ assert alert_check.investigation_summary is not None
+ assert ("ran across all services" in alert_check.investigation_summary) == expects_caveat
+
+ def test_investigation_summary_is_capped(
+ self, mock_send_breaches: MagicMock, mock_send_errors: MagicMock, mock_feature_enabled: MagicMock
+ ) -> None:
+ # Mover labels come from ingested telemetry, so an oversized label must
+ # not persist an unbounded summary on the check.
+ self.seed_gauge({6: 50.0, 7: 50.0})
+ insight = self.create_metrics_insight()
+ alert = self.create_alert(insight, upper=20.0, investigation_agent_enabled=True)
+
+ with patch(
+ "products.metrics.backend.facade.api.investigate_incident",
+ side_effect=lambda *, team, context: _stub_investigation_result(
+ context.metric_name, mover_label="x" * 10_000
+ ),
+ ):
+ run_alert_check(alert["id"])
+
+ alert_check = AlertCheck.objects.filter(alert_configuration=alert["id"]).latest("created_at")
+ assert alert_check.investigation_status == "done"
+ assert alert_check.investigation_summary is not None
+ assert len(alert_check.investigation_summary) == MAX_SUMMARY_LENGTH
+
+ def test_investigation_flag_still_rejected_for_trends_threshold_alerts(
+ self, mock_send_breaches: MagicMock, mock_send_errors: MagicMock, mock_feature_enabled: MagicMock
+ ) -> None:
+ # Loosening the metrics gate must not loosen it for other kinds: a trends
+ # threshold alert without a detector still can't enable the agent.
+ trends_query = {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview", "math": "total"}],
+ }
+ trends_insight = self.dashboard_api.create_insight(data={"name": "t", "query": trends_query})[1]
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/alerts",
+ data={
+ "name": "trends alert",
+ "insight": trends_insight["id"],
+ "subscribed_users": [self.user.id],
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "condition": {"type": "absolute_value"},
+ "calculation_interval": AlertCalculationInterval.DAILY,
+ "threshold": {"configuration": {"type": "absolute", "bounds": {"upper": 1.0}}},
+ "investigation_agent_enabled": True,
+ },
+ )
+ assert response.status_code == 400
+ assert "anomaly detection" in str(response.json()).lower()
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index bd2cf3ff5b7d..8be35120928f 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -20,6 +20,7 @@ from posthog.query_creator_access import creator_access_revoked, report_creator_
from posthog.schema_migrations.upgrade_manager import upgrade_query
from posthog.sync import database_sync_to_async
from posthog.tasks.alerts.investigation_notifications import run_investigation_notification_safety_net
+from posthog.tasks.alerts.metrics_investigation import run_metrics_alert_investigation, should_investigate_metrics_alert
from posthog.tasks.alerts.schedule_restriction import is_utc_datetime_blocked, next_unblocked_utc
from posthog.tasks.alerts.utils import (
CALCULATION_INTERVAL_ORDER,
@@ -300,6 +301,7 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe
should_start_investigation = False
should_gate_notification = False
+ should_run_metrics_investigation = False
with transaction.atomic():
alert_check, should_notify = add_alert_check(
alert,
@@ -322,6 +324,19 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe
should_start_investigation = True
should_gate_notification = bool(alert.investigation_gates_notifications)
+ # Claim the cooldown slot inside the transaction so a flapping or
+ # concurrently-retried alert can't pile up investigations.
+ if should_investigate_metrics_alert(
+ alert, previous_state=previous_state, new_state=alert_check.state
+ ) and claim_investigation_slot(alert, alert_check):
+ should_run_metrics_investigation = True
+
+ # Outside the persistence transaction: the metrics investigation issues
+ # ClickHouse queries and must never hold the row lock; a failure is
+ # recorded on the check and can't affect the alert outcome.
+ if should_run_metrics_investigation:
+ run_metrics_alert_investigation(alert, alert_check)
+
return EvaluateAlertResult(
alert_check_id=str(alert_check.id),
should_notify=should_notify,
diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.py
index 25e76c983f37..80af275b41d0 100644
--- a/products/alerts/backend/api/alert.py
+++ b/products/alerts/backend/api/alert.py
@@ -724,7 +724,9 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
organization=organization,
)
- # Investigation agent is only supported for detector-based alerts.
+ # Investigation agent is supported for detector-based alerts (the agent
+ # workflow) and for metrics threshold alerts (a synchronous facade
+ # investigation attached to the firing check) — nothing else.
investigation_enabled = attrs.get(
"investigation_agent_enabled",
self.instance.investigation_agent_enabled if self.instance else False,
@@ -734,7 +736,7 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
"detector_config",
self.instance.detector_config if self.instance else None,
)
- if not detector_config:
+ if not detector_config and insight.alertable_query_kind != NodeKind.METRICS_QUERY:
raise ValidationError(
{
"investigation_agent_enabled": [