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): show alert threshold lines on dashboards after reload (#78684)

Chris Shine0dc74fe363c1
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.py
index 809c8564affa..8b609aa1c15b 100644
--- a/posthog/api/test/dashboards/test_dashboard.py
+++ b/posthog/api/test/dashboards/test_dashboard.py
@@ -3389,6 +3389,54 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
self.assertEqual(regular_response["persisted_variables"], dashboard_variables)
self.assertEqual(sse_dashboard["persisted_variables"], dashboard_variables)
+ def test_tile_insights_carry_alerts_on_regular_and_sse_endpoints(self):
+ # Alert threshold lines on dashboards render from the tile insight's inline alerts, and
+ # InsightSerializer.get_alerts silently serializes [] when the loading path forgot the
+ # alerts prefetch — so both dashboard-loading endpoints must emit them.
+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})
+ insight_id, _ = self.dashboard_api.create_insight(
+ {
+ "dashboards": [dashboard_id],
+ "query": {
+ "kind": "InsightVizNode",
+ "source": {"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "$pageview"}]},
+ },
+ }
+ )
+ threshold = Threshold.objects.create(
+ team=self.team,
+ insight_id=insight_id,
+ created_by=self.user,
+ configuration={"type": "absolute", "bounds": {"upper": 1}},
+ )
+ alert = AlertConfiguration.objects.create(
+ team=self.team,
+ insight_id=insight_id,
+ created_by=self.user,
+ name="tile alert",
+ threshold=threshold,
+ condition={"type": "absolute_value"},
+ config={"type": "TrendsAlertConfig", "series_index": 0},
+ )
+
+ regular_response = self.dashboard_api.get_dashboard(dashboard_id)
+ assert [a["id"] for a in regular_response["tiles"][0]["insight"]["alerts"]] == [str(alert.id)]
+
+ sse_response = self.client.get(f"/api/projects/{self.team.id}/dashboards/{dashboard_id}/stream_tiles/")
+ assert sse_response.status_code == status.HTTP_200_OK
+ sse_content = b"".join(sse_response.streaming_content).decode("utf-8") # type: ignore
+ metadata_line = next(
+ (
+ line[len("data: ") :]
+ for line in sse_content.split("\n")
+ if line.startswith("data: ") and '"type":"metadata"' in line
+ ),
+ None,
+ )
+ assert metadata_line is not None, f"Could not find metadata in SSE response. Content: {repr(sse_content)}"
+ streamed_tiles = json.loads(metadata_line)["dashboard"]["tiles"]
+ assert [a["id"] for a in streamed_tiles[0]["insight"]["alerts"]] == [str(alert.id)]
+
def test_streamed_tile_error_preserves_insight_metadata_without_exception_detail(self):
dashboard = Dashboard.objects.create(
team=self.team,
diff --git a/products/alerts/frontend/logic/insightAlertsLogic.test.ts b/products/alerts/frontend/logic/insightAlertsLogic.test.ts
index 9f6ef1b65a93..084905c9ef94 100644
--- a/products/alerts/frontend/logic/insightAlertsLogic.test.ts
+++ b/products/alerts/frontend/logic/insightAlertsLogic.test.ts
@@ -63,7 +63,33 @@ describe('insightAlertsLogic', () => {
insightVizDataLogic(insightLogicProps).mount()
}
- it('does not hydrate from empty insight.alerts or fetch on mount when deferInitialAlertsLoad is true', async () => {
+ it('hydrates inline insight.alerts on a deferred mount without alerts or destination-count requests', async () => {
+ const inlineAlerts = [{ id: 'alert-a', name: 'Inline' }] as AlertType[]
+ const insightLogicProps: InsightLogicProps = {
+ dashboardItemId: Insight42,
+ dashboardId: 1,
+ cachedInsight: {
+ ...createEmptyInsight(Insight42),
+ id: 42,
+ query: API_QUERY,
+ alerts: inlineAlerts,
+ },
+ }
+ mountInsightStack(insightLogicProps)
+
+ const alertsLogic = insightAlertsLogic({
+ insightId: 42,
+ insightLogicProps,
+ deferInitialAlertsLoad: true,
+ })
+ alertsLogic.mount()
+
+ await expectLogic(alertsLogic).toFinishAllListeners().toMatchValues({ alerts: inlineAlerts })
+ expect(listSpy).not.toHaveBeenCalled()
+ expect(hogFunctionsListSpy).not.toHaveBeenCalled()
+ })
+
+ it('does not fetch on a deferred mount when the cached insight has no alerts field', async () => {
const insightLogicProps: InsightLogicProps = {
dashboardItemId: Insight42,
dashboardId: 1,
@@ -71,7 +97,6 @@ describe('insightAlertsLogic', () => {
...createEmptyInsight(Insight42),
id: 42,
query: API_QUERY,
- alerts: [],
},
}
mountInsightStack(insightLogicProps)
diff --git a/products/alerts/frontend/logic/insightAlertsLogic.ts b/products/alerts/frontend/logic/insightAlertsLogic.ts
index 218f590722c6..d39c332cba0a 100644
--- a/products/alerts/frontend/logic/insightAlertsLogic.ts
+++ b/products/alerts/frontend/logic/insightAlertsLogic.ts
@@ -26,9 +26,10 @@ export interface InsightAlertsLogicProps {
insightId: number
insightLogicProps: InsightLogicProps
/**
- * When true, skip the afterMount alerts fetch. Used for dashboard tiles where `insight.alerts` is often an
- * unprefetched `[]` and we must not N+1 on mount. Call `loadAlerts()` when surfacing the UI that needs the list
- * (e.g. before `ManageAlertsModal` opens).
+ * When true, skip the afterMount alerts API fetch and the per-alert destination-count fetch — a dashboard
+ * mounts one of these logics per tile, so those requests N+1 on load. Inline `insight.alerts` (prefetched by
+ * the dashboard endpoints) still hydrates, so saved display options like alert threshold lines can render.
+ * Call `loadAlerts()` when surfacing UI that needs fresh data (e.g. before `ManageAlertsModal` opens).
*/
deferInitialAlertsLoad?: boolean
}
@@ -189,6 +190,9 @@ export interface insightAlertsLogicActions {
removeAlert: (alertId: AlertType['id']) => {
alertId: string
}
+ setAlertsFromInsight: (alerts: AlertType[]) => {
+ alerts: AlertType[]
+ }
setShouldShowAlertDeletionWarning: (show: boolean) => {
show: boolean
}
@@ -231,6 +235,7 @@ export const insightAlertsLogic = kea<insightAlertsLogicType>([
key(({ insightId }) => `insight-${insightId}`),
actions({
setShouldShowAlertDeletionWarning: (show: boolean) => ({ show }),
+ setAlertsFromInsight: (alerts: AlertType[]) => ({ alerts }),
upsertAlert: (alert: AlertType) => ({ alert }),
removeAlert: (alertId: AlertType['id']) => ({ alertId }),
setSimulationAnomalyPoints: (points: AnomalyPoint[]) => ({ points }),
@@ -289,6 +294,7 @@ export const insightAlertsLogic = kea<insightAlertsLogicType>([
alerts: [
[] as AlertType[],
{
+ setAlertsFromInsight: (_, { alerts }) => alerts,
upsertAlert: (state, { alert }) => {
const index = state.findIndex((a) => a.id === alert.id)
if (index >= 0) {
@@ -421,15 +427,22 @@ export const insightAlertsLogic = kea<insightAlertsLogicType>([
})),
afterMount(({ actions, values, props }) => {
- if (props.deferInitialAlertsLoad) {
- return
- }
// If the insight has an alerts property (even if empty), use it - this means the backend sent us the alerts data
if (values.insight?.alerts && Array.isArray(values.insight.alerts)) {
- actions.loadAlertsSuccess(values.insight.alerts)
- } else {
- // No alerts property means we need to fetch from API (e.g., when viewing insight in isolation)
- actions.loadAlerts()
+ if (props.deferInitialAlertsLoad) {
+ // Hydrate without loadAlertsSuccess: its listener fetches destination counts per
+ // insight, which dashboards must not fan out on mount. Threshold lines only need
+ // the alerts themselves; ManageAlertsModal loads the rest when opened.
+ actions.setAlertsFromInsight(values.insight.alerts)
+ } else {
+ actions.loadAlertsSuccess(values.insight.alerts)
+ }
+ return
+ }
+ if (props.deferInitialAlertsLoad) {
+ return
}
+ // No alerts property means we need to fetch from API (e.g., when viewing insight in isolation)
+ actions.loadAlerts()
}),
])
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index d0ca50312f00..09e46a664ede 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -321,6 +321,29 @@ def _compact_tile_layouts(tiles: list[DashboardTile]) -> set[int]:
return changed
+def tile_insight_prefetches() -> list[Prefetch]:
+ """Prefetches every tile-serializing path needs on its tiles queryset. InsightSerializer reads
+ `prefetched_tags` and `_prefetched_alerts` off each insight — a path that skips the alerts
+ prefetch silently serializes `alerts: []` for every tile, hiding alert threshold lines on
+ dashboards."""
+ return [
+ Prefetch(
+ "insight__tagged_items",
+ queryset=TaggedItem.objects.select_related("tag"),
+ to_attr="prefetched_tags",
+ ),
+ Prefetch(
+ "insight__alertconfiguration_set",
+ # AlertSerializer emits threshold and subscribed_users per alert; without these,
+ # every alert on the dashboard costs two extra queries
+ queryset=AlertConfiguration.objects.select_related("created_by", "threshold").prefetch_related(
+ "subscribed_users"
+ ),
+ to_attr="_prefetched_alerts",
+ ),
+ ]
+
+
def serialize_tile_with_context(tile, order: int, context: dict) -> tuple[int, dict]:
"""
Serialize a single tile with error handling. Returns (order, tile_data) tuple.
@@ -2078,22 +2101,7 @@ class DashboardSerializer(DashboardMetadataSerializer):
serialized_tiles: list[ReturnDict] = []
- tiles = DashboardTile.dashboard_queryset(dashboard.tiles.all()).prefetch_related(
- Prefetch(
- "insight__tagged_items",
- queryset=TaggedItem.objects.select_related("tag"),
- to_attr="prefetched_tags",
- ),
- Prefetch(
- "insight__alertconfiguration_set",
- # AlertSerializer emits threshold and subscribed_users per alert; without these,
- # every alert on the dashboard costs two extra queries
- queryset=AlertConfiguration.objects.select_related("created_by", "threshold").prefetch_related(
- "subscribed_users"
- ),
- to_attr="_prefetched_alerts",
- ),
- )
+ tiles = DashboardTile.dashboard_queryset(dashboard.tiles.all()).prefetch_related(*tile_insight_prefetches())
self.user_permissions.set_preloaded_dashboard_tiles(list(tiles))
team = self.context["get_team"]()
@@ -2469,13 +2477,7 @@ class DashboardsViewSet(
)
# Get tiles with proper prefetch
- tiles = DashboardTile.dashboard_queryset(dashboard.tiles.all()).prefetch_related(
- Prefetch(
- "insight__tagged_items",
- queryset=TaggedItem.objects.select_related("tag"),
- to_attr="prefetched_tags",
- )
- )
+ tiles = DashboardTile.dashboard_queryset(dashboard.tiles.all()).prefetch_related(*tile_insight_prefetches())
layout_size = self._get_layout_size_from_request(request)