Skip to content

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

fix(alerts): accept short IDs in detector simulations (#91809)

Vasco de Krijger654d712ebf03
diff --git a/products/alerts/backend/max_tools.py b/products/alerts/backend/max_tools.py
index 4cf30a2700c0..72c7a908a3aa 100644
--- a/products/alerts/backend/max_tools.py
+++ b/products/alerts/backend/max_tools.py
@@ -26,7 +26,7 @@ from products.access_control.backend.facade.user_access_control import AccessCon
from products.alerts.backend.evaluation.validation import THRESHOLD_BOUNDS_REQUIRED_MESSAGE
from products.alerts.backend.insight_alert_state_machine import apply_disable, apply_enable, apply_threshold_change
from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Threshold
-from products.product_analytics.backend.facade.models import Insight
+from products.product_analytics.backend.facade.models import Insight, resolve_insight_by_id_or_short_id
from ee.hogai.artifacts.types import ModelArtifactResult
from ee.hogai.tool import MaxTool
@@ -492,19 +492,12 @@ class UpsertAlertTool(MaxTool):
qs = Insight.objects.filter(team=self._team, deleted=False)
- # 1. Try numeric DB ID
- try:
- return await sync_to_async(qs.get)(id=int(effective_id)), False
- except (ValueError, Insight.DoesNotExist):
- pass
-
- # 2. Try short_id
- try:
- return await sync_to_async(qs.get)(short_id=effective_id), False
- except Insight.DoesNotExist:
- pass
+ # 1. Try numeric DB ID, then short_id (including legacy numeric-only short IDs).
+ insight = await sync_to_async(resolve_insight_by_id_or_short_id)(qs, effective_id)
+ if insight is not None:
+ return insight, False
- # 3. Try conversation artifact — auto-save as a new insight
+ # 2. Try conversation artifact — auto-save as a new insight
result = await self._context_manager.artifacts.aget_visualization(self._state.messages, effective_id)
if result is None:
raise Insight.DoesNotExist(f"Insight or visualization '{effective_id}' not found.")
diff --git a/products/alerts/backend/presentation/views/alert.py b/products/alerts/backend/presentation/views/alert.py
index 23b66dab7b53..604794caa199 100644
--- a/products/alerts/backend/presentation/views/alert.py
+++ b/products/alerts/backend/presentation/views/alert.py
@@ -76,7 +76,7 @@ from products.alerts.backend.insight_alert_state_machine import (
)
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold
from products.alerts.backend.presentation.views.alert_schedule_restriction import AlertScheduleRestriction
-from products.product_analytics.backend.facade.models import Insight
+from products.product_analytics.backend.facade.models import Insight, resolve_insight_by_id_or_short_id
INSIGHT_ALERT_FIRING_EVENT = "$insight_alert_firing"
@@ -183,6 +183,26 @@ class DetectorConfigField(serializers.JSONField):
pass
+@extend_schema_field(
+ {
+ "oneOf": [{"type": "integer"}, {"type": "string"}],
+ "description": "Numeric insight ID or saved insight short ID.",
+ }
+)
+class TeamScopedInsightReferenceField(TeamScopedPrimaryKeyRelatedField):
+ """Resolve an insight by its database ID or its user-facing short ID."""
+
+ def to_internal_value(self, data: object) -> Insight:
+ if isinstance(data, bool) or not isinstance(data, (str, int)):
+ self.fail("incorrect_type", data_type=type(data).__name__)
+
+ insight = resolve_insight_by_id_or_short_id(self.get_queryset(), data)
+ if insight is not None:
+ return insight
+
+ self.fail("does_not_exist", pk_value=data)
+
+
@extend_schema_field(AlertScheduleRestriction) # type: ignore[arg-type]
class ScheduleRestrictionField(serializers.JSONField):
pass
@@ -875,12 +895,22 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
class AlertSimulateSerializer(serializers.Serializer):
- insight = TeamScopedPrimaryKeyRelatedField(
+ insight = TeamScopedInsightReferenceField(
queryset=Insight.objects.all(),
- help_text="Insight ID to simulate the detector on.",
+ help_text="Numeric insight ID or saved insight short ID to simulate the detector on.",
)
detector_config = DetectorConfigField(
- help_text="Detector configuration to simulate.",
+ required=False,
+ default=lambda: {
+ "type": "zscore",
+ "threshold": 0.95,
+ "window": 90,
+ "preprocessing": {"diffs_n": 1},
+ },
+ help_text=(
+ "Detector configuration to simulate. Omit it to use the default daily z-score detector "
+ "(threshold 0.95, window 90, first-difference preprocessing)."
+ ),
)
# TODO: fold series_index and date_from into a per-kind range on `config` once a second insight
# kind needs a range knob. They stay flat today because date_from is a preview-only range with
@@ -914,9 +944,6 @@ class AlertSimulateSerializer(serializers.Serializer):
return value
def validate_detector_config(self, value):
- if value is None:
- raise ValidationError("detector_config is required.")
-
import pydantic
try:
diff --git a/products/alerts/backend/tests/api/test_alert.py b/products/alerts/backend/tests/api/test_alert.py
index e2ab77a00dd9..0c91459f0ac6 100644
--- a/products/alerts/backend/tests/api/test_alert.py
+++ b/products/alerts/backend/tests/api/test_alert.py
@@ -1562,7 +1562,19 @@ class TestAlertSimulate(APIBaseTest):
assert isinstance(data["scores"], list)
assert len(data["scores"]) == 34
- def test_simulate_missing_detector_config_returns_400(self) -> None:
+ @mock.patch("products.alerts.backend.presentation.views.alert.simulate_detector_on_insight")
+ def test_simulate_uses_default_detector_config(self, mock_simulate) -> None:
+ mock_simulate.return_value = {
+ "data": [],
+ "dates": [],
+ "scores": [],
+ "triggered_indices": [],
+ "triggered_dates": [],
+ "interval": "day",
+ "total_points": 0,
+ "anomaly_count": 0,
+ }
+
response = self.client.post(
f"/api/projects/{self.team.id}/alerts/simulate",
{
@@ -1570,7 +1582,59 @@ class TestAlertSimulate(APIBaseTest):
"series_index": 0,
},
)
+ assert response.status_code == status.HTTP_200_OK, response.content
+ detector_config = mock_simulate.call_args.kwargs["detector_config"]
+ assert detector_config["type"] == "zscore"
+ assert detector_config["threshold"] == 0.95
+ assert detector_config["window"] == 90
+ assert detector_config["preprocessing"]["diffs_n"] == 1
+
+ def test_simulate_null_detector_config_returns_400(self) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/alerts/simulate",
+ {
+ "insight": self.insight["id"],
+ "detector_config": None,
+ },
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_simulate_unknown_insight_short_id_returns_not_found_error(self) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/alerts/simulate",
+ {
+ "insight": "not-a-real-short-id",
+ "detector_config": {"type": "zscore"},
+ },
+ )
+
assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["code"] == "does_not_exist"
+
+ @mock.patch("products.alerts.backend.presentation.views.alert.simulate_detector_on_insight")
+ def test_simulate_accepts_insight_short_id(self, mock_simulate) -> None:
+ mock_simulate.return_value = {
+ "data": [],
+ "dates": [],
+ "scores": [],
+ "triggered_indices": [],
+ "triggered_dates": [],
+ "interval": "day",
+ "total_points": 0,
+ "anomaly_count": 0,
+ }
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/alerts/simulate",
+ {
+ "insight": self.insight["short_id"],
+ "detector_config": {"type": "zscore"},
+ },
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert mock_simulate.call_args.kwargs["insight"].id == self.insight["id"]
def test_simulate_invalid_detector_config_returns_400(self) -> None:
response = self.client.post(
diff --git a/products/alerts/frontend/generated/api.schemas.ts b/products/alerts/frontend/generated/api.schemas.ts
index ae7512ba5a81..758330db5ceb 100644
--- a/products/alerts/frontend/generated/api.schemas.ts
+++ b/products/alerts/frontend/generated/api.schemas.ts
@@ -819,10 +819,10 @@ export interface AlertTestDeliveryResponseApi {
}
export interface AlertSimulateApi {
- /** Insight ID to simulate the detector on. */
- insight: number
- /** Detector configuration to simulate. */
- detector_config: DetectorConfigApi
+ /** Numeric insight ID or saved insight short ID to simulate the detector on. */
+ insight: number | string
+ /** Detector configuration to simulate. Omit it to use the default daily z-score detector (threshold 0.95, window 90, first-difference preprocessing). */
+ detector_config?: DetectorConfigApi
/** Zero-based index of the series to analyze (trends insights only). */
series_index?: number
/**
diff --git a/products/alerts/frontend/generated/api.zod.ts b/products/alerts/frontend/generated/api.zod.ts
index d756a85aee42..0677a931c6b3 100644
--- a/products/alerts/frontend/generated/api.zod.ts
+++ b/products/alerts/frontend/generated/api.zod.ts
@@ -56,7 +56,9 @@ export const alertsSimulateCreateBodyConfigOneThreeTypeDefault = `FunnelsAlertCo
export const alertsSimulateCreateBodyConfigOneFourTypeDefault = `MetricsAlertConfig`
export const AlertsSimulateCreateBody = /* @__PURE__ */ zod.object({
- insight: zod.number().describe('Insight ID to simulate the detector on.'),
+ insight: zod
+ .union([zod.number(), zod.string()])
+ .describe('Numeric insight ID or saved insight short ID to simulate the detector on.'),
detector_config: zod
.union([
zod.object({
@@ -1060,7 +1062,10 @@ export const AlertsSimulateCreateBody = /* @__PURE__ */ zod.object({
}),
])
.describe('Detector configuration types')
- .describe('Detector configuration to simulate.'),
+ .optional()
+ .describe(
+ 'Detector configuration to simulate. Omit it to use the default daily z-score detector (threshold 0.95, window 90, first-difference preprocessing).'
+ ),
series_index: zod
.number()
.default(alertsSimulateCreateBodySeriesIndexDefault)
diff --git a/products/alerts/mcp/tools.yaml b/products/alerts/mcp/tools.yaml
index dcfad76d9515..bf73f99a41fc 100644
--- a/products/alerts/mcp/tools.yaml
+++ b/products/alerts/mcp/tools.yaml
@@ -101,11 +101,13 @@ tools:
title: Simulate detector on insight
description: >
Run an anomaly detector on an insight's historical data without creating any alert or check records. Use
- this to preview how a detector configuration would perform before saving it as an alert. Requires an insight
- ID and a detector_config object with a type (zscore, mad, iqr, copod, ecod, hbos, isolation_forest, knn,
- lof, ocsvm, pca, or ensemble). Optionally specify date_from (e.g. '-48h', '-30d') to control how far back to
- simulate, and series_index to pick which series to analyze. Returns data values, anomaly scores per point,
- triggered indices and dates, and for ensemble detectors, per-sub-detector score breakdowns.
+ this to preview how a detector configuration would perform before saving it as an alert. Pass either the
+ numeric insight ID or its saved short ID. Omit detector_config to use the default daily z-score detector
+ (threshold 0.95, window 90, first-difference preprocessing). To choose another detector, pass
+ detector_config with a type (zscore, mad, iqr, copod, ecod, hbos, isolation_forest, knn, lof, ocsvm, pca, or
+ ensemble). Optionally specify date_from (e.g. '-48h', '-30d') to control how far back to simulate, and
+ series_index to pick which series to analyze. Returns data values, anomaly scores per point, triggered
+ indices and dates, and for ensemble detectors, per-sub-detector score breakdowns.
alert-update:
operation: alerts_partial_update
enabled: true
diff --git a/products/product_analytics/backend/facade/models.py b/products/product_analytics/backend/facade/models.py
index 8875f99350b7..5fd5d53387b5 100644
--- a/products/product_analytics/backend/facade/models.py
+++ b/products/product_analytics/backend/facade/models.py
@@ -2,17 +2,29 @@
Model-class wiring for product_analytics.
Re-exports the ``Insight`` and ``InsightVariable`` model classes for consumers under the
-watched-models allowance (MODEL_CROSSINGS), together with the model-module helper
-``generate_insight_filters_hash``, which takes model instances. Consumers are moving behind
-facade functions; see products/architecture.md § Wiring couplings for what a consumer may do
-with a crossing class while they do. ``InsightVariable`` has no consumer left outside the
-product, but the SQL-variables ``ModelViewSet`` in ``presentation/`` still needs the class, and
-presentation may only reach internals through the facade. The whole model surface
-(``backend/models/`` and ``backend/migrations/``) stays in the contract-check inputs, so a change
-to these classes still runs the full suite.
+watched-models allowance (MODEL_CROSSINGS), together with helpers that take model instances or
+querysets. Consumers are moving behind facade functions; see products/architecture.md § Wiring
+couplings for what a consumer may do with a crossing class while they do. ``InsightVariable`` has
+no consumer left outside the product, but the SQL-variables ``ModelViewSet`` in ``presentation/``
+still needs the class, and presentation may only reach internals through the facade. The whole
+model surface (``backend/models/`` and ``backend/migrations/``) stays in the contract-check
+inputs, so a change to these classes still runs the full suite.
"""
+from django.db.models import QuerySet
+
from products.product_analytics.backend.models.insight import Insight, generate_insight_filters_hash
from products.product_analytics.backend.models.insight_variable import InsightVariable
-__all__ = ["Insight", "InsightVariable", "generate_insight_filters_hash"]
+
+def resolve_insight_by_id_or_short_id(queryset: QuerySet[Insight], reference: str | int) -> Insight | None:
+ """Resolve an insight reference, preferring its numeric primary key when ambiguous."""
+ lookup_value = str(reference).strip()
+ if lookup_value.isdigit():
+ insight = queryset.filter(pk=int(lookup_value)).first()
+ if insight is not None:
+ return insight
+ return queryset.filter(short_id=lookup_value).first()
+
+
+__all__ = ["Insight", "InsightVariable", "generate_insight_filters_hash", "resolve_insight_by_id_or_short_id"]
diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.py
index 83a0a06771b0..8e431e68884d 100644
--- a/products/product_analytics/backend/presentation/insight.py
+++ b/products/product_analytics/backend/presentation/insight.py
@@ -179,7 +179,7 @@ from products.product_analytics.backend.facade.api import (
record_insight_views,
with_last_viewed_at,
)
-from products.product_analytics.backend.facade.models import Insight
+from products.product_analytics.backend.facade.models import Insight, resolve_insight_by_id_or_short_id
from products.product_analytics.backend.presentation.insight_metadata import (
InsightMetadataTimeoutError,
generate_insight_metadata,
@@ -1924,15 +1924,7 @@ class InsightViewSet(
return self.order_queryset(queryset)
def safely_get_object(self, queryset: QuerySet) -> Insight | None:
- lookup_value = self.kwargs[self.lookup_field]
- if isinstance(lookup_value, str) and lookup_value.isdigit():
- # A numeric lookup is ambiguous: usually it's a primary key, but a small number of
- # legacy rows have numeric-only short_ids. Try pk first (preserving existing behavior)
- # and fall back to short_id so those legacy insights stay retrievable.
- pk_match = queryset.filter(pk=int(lookup_value)).first()
- if pk_match is not None:
- return pk_match
- return queryset.filter(short_id=lookup_value).first()
+ return resolve_insight_by_id_or_short_id(queryset, self.kwargs[self.lookup_field])
def filter_queryset(self, queryset: QuerySet) -> QuerySet:
return drop_similar_when_exact_exists(super().filter_queryset(queryset))
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 48bd69b4c59f..8eb7edab090f 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -457,7 +457,7 @@
}
},
"alert-simulate": {
- "description": "Run an anomaly detector on an insight's historical data without creating any alert or check records. Use this to preview how a detector configuration would perform before saving it as an alert. Requires an insight ID and a detector_config object with a type (zscore, mad, iqr, copod, ecod, hbos, isolation_forest, knn, lof, ocsvm, pca, or ensemble). Optionally specify date_from (e.g. '-48h', '-30d') to control how far back to simulate, and series_index to pick which series to analyze. Returns data values, anomaly scores per point, triggered indices and dates, and for ensemble detectors, per-sub-detector score breakdowns.",
+ "description": "Run an anomaly detector on an insight's historical data without creating any alert or check records. Use this to preview how a detector configuration would perform before saving it as an alert. Pass either the numeric insight ID or its saved short ID. Omit detector_config to use the default daily z-score detector (threshold 0.95, window 90, first-difference preprocessing). To choose another detector, pass detector_config with a type (zscore, mad, iqr, copod, ecod, hbos, isolation_forest, knn, lof, ocsvm, pca, or ensemble). Optionally specify date_from (e.g. '-48h', '-30d') to control how far back to simulate, and series_index to pick which series to analyze. Returns data values, anomaly scores per point, triggered indices and dates, and for ensemble detectors, per-sub-detector score breakdowns.",
"category": "Alerts",
"feature": "alerts",
"summary": "Simulate detector on insight",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 6685a6874730..0b5e8b4824b4 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -472,7 +472,7 @@
}
},
"alert-simulate": {
- "description": "Run an anomaly detector on an insight's historical data without creating any alert or check records. Use this to preview how a detector configuration would perform before saving it as an alert. Requires an insight ID and a detector_config object with a type (zscore, mad, iqr, copod, ecod, hbos, isolation_forest, knn, lof, ocsvm, pca, or ensemble). Optionally specify date_from (e.g. '-48h', '-30d') to control how far back to simulate, and series_index to pick which series to analyze. Returns data values, anomaly scores per point, triggered indices and dates, and for ensemble detectors, per-sub-detector score breakdowns.",
+ "description": "Run an anomaly detector on an insight's historical data without creating any alert or check records. Use this to preview how a detector configuration would perform before saving it as an alert. Pass either the numeric insight ID or its saved short ID. Omit detector_config to use the default daily z-score detector (threshold 0.95, window 90, first-difference preprocessing). To choose another detector, pass detector_config with a type (zscore, mad, iqr, copod, ecod, hbos, isolation_forest, knn, lof, ocsvm, pca, or ensemble). Optionally specify date_from (e.g. '-48h', '-30d') to control how far back to simulate, and series_index to pick which series to analyze. Returns data values, anomaly scores per point, triggered indices and dates, and for ensemble detectors, per-sub-detector score breakdowns.",
"category": "Alerts",
"feature": "alerts",
"summary": "Simulate detector on insight",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6d2889527a1a..53a0edebd857 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -10128,10 +10128,10 @@ export namespace Schemas {
}
export interface AlertSimulate {
- /** Insight ID to simulate the detector on. */
- insight: number;
- /** Detector configuration to simulate. */
- detector_config: DetectorConfig;
+ /** Numeric insight ID or saved insight short ID to simulate the detector on. */
+ insight: number | string;
+ /** Detector configuration to simulate. Omit it to use the default daily z-score detector (threshold 0.95, window 90, first-difference preprocessing). */
+ detector_config?: DetectorConfig;
/** Zero-based index of the series to analyze (trends insights only). */
series_index?: number;
/**
diff --git a/services/mcp/src/generated/alerts/api.ts b/services/mcp/src/generated/alerts/api.ts
index 1e31f93fb5de..34622eb0e7c8 100644
--- a/services/mcp/src/generated/alerts/api.ts
+++ b/services/mcp/src/generated/alerts/api.ts
@@ -2689,7 +2689,9 @@ export const alertsSimulateCreateBodyConfigOneThreeTypeDefault = `FunnelsAlertCo
export const alertsSimulateCreateBodyConfigOneFourTypeDefault = `MetricsAlertConfig`
export const AlertsSimulateCreateBody = /* @__PURE__ */ zod.object({
- insight: zod.number().describe('Insight ID to simulate the detector on.'),
+ insight: zod
+ .union([zod.number(), zod.string()])
+ .describe('Numeric insight ID or saved insight short ID to simulate the detector on.'),
detector_config: zod
.union([
zod.object({
@@ -3693,7 +3695,10 @@ export const AlertsSimulateCreateBody = /* @__PURE__ */ zod.object({
}),
])
.describe('Detector configuration types')
- .describe('Detector configuration to simulate.'),
+ .optional()
+ .describe(
+ 'Detector configuration to simulate. Omit it to use the default daily z-score detector (threshold 0.95, window 90, first-difference preprocessing).'
+ ),
series_index: zod
.number()
.default(alertsSimulateCreateBodySeriesIndexDefault)
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json
index 1b9944586535..8689327ce2ee 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json
@@ -2202,11 +2202,18 @@
"type": "object"
}
],
- "description": "Detector configuration to simulate."
+ "description": "Detector configuration to simulate. Omit it to use the default daily z-score detector (threshold 0.95, window 90, first-difference preprocessing)."
},
"insight": {
- "description": "Insight ID to simulate the detector on.",
- "type": "number"
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "string"
+ }
+ ],
+ "description": "Numeric insight ID or saved insight short ID to simulate the detector on."
},
"series_index": {
"default": 0,
@@ -2214,6 +2221,6 @@
"type": "number"
}
},
- "required": ["insight", "detector_config"],
+ "required": ["insight"],
"type": "object"
}