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(insights): degrade a failing insight in place instead of 400ing the response (#79974)

posthog[bot]54313bcb1da5
diff --git a/frontend/src/lib/utils/requests.test.ts b/frontend/src/lib/utils/requests.test.ts
new file mode 100644
index 000000000000..7793d836f4cf
--- /dev/null
+++ b/frontend/src/lib/utils/requests.test.ts
@@ -0,0 +1,23 @@
+import { isDeterministicClientError } from 'lib/utils/requests'
+
+describe('isDeterministicClientError', () => {
+ // A dashboard tile's failed query is retried unless this returns true, so the status boundary
+ // here is what stops a deterministic 400 from being hammered several times before it surfaces.
+ it.each([
+ [400, true],
+ [401, true],
+ [403, true],
+ [404, true],
+ [422, true],
+ // transient 4xx that can succeed on retry
+ [408, false],
+ [429, false],
+ // server / network errors are retryable
+ [500, false],
+ [503, false],
+ [504, false],
+ [undefined, false],
+ ])('status %s -> %s', (status, expected) => {
+ expect(isDeterministicClientError({ status })).toBe(expected)
+ })
+})
diff --git a/frontend/src/lib/utils/requests.ts b/frontend/src/lib/utils/requests.ts
index 65b05ff98eeb..e4fa3493128b 100644
--- a/frontend/src/lib/utils/requests.ts
+++ b/frontend/src/lib/utils/requests.ts
@@ -10,3 +10,13 @@ export function isAbortedRequest(error: any): boolean {
export function isTimedOutRequest(error: any): boolean {
return error.status === 504
}
+
+/**
+ * A 4xx (except 408 timeout and 429 rate limit) means the request is deterministically bad, so
+ * retrying it can't succeed and only delays the error reaching the user. Used to short-circuit
+ * retry loops so a broken query isn't hammered several times before failing.
+ */
+export function isDeterministicClientError(error: any): boolean {
+ const status = error?.status
+ return typeof status === 'number' && status >= 400 && status < 500 && status !== 408 && status !== 429
+}
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.ts b/frontend/src/scenes/dashboard/dashboardUtils.ts
index 454dc6af9f19..e94258db787e 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.ts
@@ -10,7 +10,7 @@ import { currentSessionId } from 'lib/internalMetrics'
import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'
import { DashboardEventSource } from 'lib/utils/eventUsageLogic'
import { objectClean } from 'lib/utils/objects'
-import { shouldCancelQuery } from 'lib/utils/requests'
+import { isDeterministicClientError, shouldCancelQuery } from 'lib/utils/requests'
import { toParams } from 'lib/utils/url'
import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'
@@ -381,10 +381,8 @@ export async function getInsightWithRetry(
throw e // Re-throw cancellation errors
}
- // A 4xx response (e.g. a query validation error) is deterministic, so retrying
- // would only replay the same failure — 429 excepted, which means "retry later"
- if (e instanceof ApiError && e.status && e.status >= 400 && e.status < 500 && e.status !== 429) {
- throw e
+ if (isDeterministicClientError(e)) {
+ throw e // A 4xx won't change on retry, so surface it immediately
}
attempt++
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.py
index ec19f85fef92..097721938c95 100644
--- a/posthog/api/test/dashboards/test_dashboard.py
+++ b/posthog/api/test/dashboards/test_dashboard.py
@@ -16,6 +16,8 @@ from rest_framework import status
from posthog.schema import DateRange, EventPropertyFilter, EventsNode, PropertyOperator, TrendsQuery
+from posthog.hogql.errors import ExposedHogQLError
+
from posthog.api.test.dashboards import DashboardAPI
from posthog.caching.insight_result import InsightResult
from posthog.constants import AvailableFeature
@@ -3545,6 +3547,28 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
streamed_tiles = json.loads(metadata_line)["dashboard"]["tiles"]
assert [a["id"] for a in streamed_tiles[0]["insight"]["alerts"]] == [str(alert.id)]
+ @patch("posthog.caching.calculate_results.calculate_for_query_based_insight")
+ def test_dashboard_refresh_serializes_broken_query_tile_in_place(self, mock_calculate: MagicMock) -> None:
+ mock_calculate.side_effect = ExposedHogQLError("Invalid HogQL syntax")
+ dashboard = Dashboard.objects.create(team=self.team, name="dashboard with broken tile", created_by=self.user)
+ insight = Insight.objects.create(
+ team=self.team,
+ query={"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "$pageview"}]},
+ )
+ DashboardTile.objects.create(dashboard=dashboard, insight=insight)
+
+ response = self.client.get(f"/api/environments/{self.team.id}/dashboards/{dashboard.id}/?refresh=blocking")
+
+ # The failure must ride on the tile insight's query_status, not trip get_tiles' generic
+ # DashboardTileError fallback, and must not fail the whole response.
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ tile = response.json()["tiles"][0]
+ self.assertIsNone(tile.get("error"))
+ query_status = tile["insight"]["query_status"]
+ self.assertTrue(query_status["error"])
+ self.assertIn("Invalid HogQL syntax", query_status["error_message"])
+ self.assertEqual(query_status["error_code"], "hogql_error")
+
def test_streamed_tile_error_preserves_insight_metadata_without_exception_detail(self):
dashboard = Dashboard.objects.create(
team=self.team,
diff --git a/posthog/hogql/errors.py b/posthog/hogql/errors.py
index c635d140bf22..f8c38dd4055c 100644
--- a/posthog/hogql/errors.py
+++ b/posthog/hogql/errors.py
@@ -35,7 +35,10 @@ class BaseHogQLError(Exception, ABC):
class ExposedHogQLError(BaseHogQLError):
"""An exception that can be exposed to the user."""
- pass
+ # Surfaced as the error code on API responses so clients can tell a deterministic query
+ # failure from a transient blip without matching on the message. Subclasses override this
+ # fallback with a more specific value.
+ code_name = "hogql_error"
class InternalHogQLError(BaseHogQLError):
@@ -50,13 +53,13 @@ class InternalHogQLError(BaseHogQLError):
class SyntaxError(ExposedHogQLError):
"""The input does not conform to HogQL syntax."""
- pass
+ code_name = "hogql_syntax_error"
class QueryError(ExposedHogQLError):
"""The query is invalid, though correct syntactically."""
- pass
+ code_name = "hogql_query_error"
class TableAccessDeniedError(QueryError):
diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.py
index 4bd096899c09..8bb2c8a5bdbd 100644
--- a/products/product_analytics/backend/api/insight.py
+++ b/products/product_analytics/backend/api/insight.py
@@ -1,7 +1,7 @@
import json
import logging
from collections.abc import Sequence
-from datetime import timedelta
+from datetime import datetime, timedelta
from functools import lru_cache
from typing import Any, Union, cast
@@ -1421,61 +1421,72 @@ class InsightSerializer(InsightBasicSerializer):
)
return insight_result
except (ExposedHogQLError, ExposedCHQueryError, HogVMException) as e:
- raise ValidationError(str(e), getattr(e, "code_name", None))
+ return self._degraded_insight_result(
+ insight,
+ dashboard,
+ error_message=str(e),
+ error_code=getattr(e, "code_name", None),
+ last_refresh=None,
+ )
except ConcurrencyLimitExceeded as e:
logger.warn(
"concurrency_limit_exceeded_api", exception=e, insight_id=insight.id, team_id=insight.team_id
)
- return InsightResult(
- result=None,
+ return self._degraded_insight_result(
+ insight,
+ dashboard,
+ error_message="concurrency_limit_exceeded",
+ error_code="concurrency_limit_exceeded",
last_refresh=now(),
- is_cached=False,
- query_status=dict(
- QueryStatus(
- # QueryStatus.id is a required str; without a client_query_id this
- # fallback used to crash pydantic validation and turn the degraded
- # error state into a 500.
- id=self.context["request"].query_params.get("client_query_id") or "",
- team_id=insight.team_id,
- insight_id=str(insight.id),
- dashboard_id=str(dashboard.id) if dashboard else None,
- error_message="concurrency_limit_exceeded",
- error=True,
- )
- ),
- cache_key=None,
- hogql=None,
- columns=None,
- has_more=None,
- timezone=self.context["get_team"]().timezone,
)
except Exception as e:
# Capture unexpected crashes so the API list doesn't fail
logger.exception("insight_calculation_error", insight_id=insight.id, team_id=insight.team_id)
- return InsightResult(
- result=None,
+ return self._degraded_insight_result(
+ insight,
+ dashboard,
+ error_message=str(e),
+ error_code=None,
last_refresh=None,
- is_cached=False,
- query_status=dict(
- QueryStatus(
- # QueryStatus.id is a required str; without a client_query_id this
- # fallback used to crash pydantic validation and turn the degraded
- # error state into a 500.
- id=self.context["request"].query_params.get("client_query_id") or "",
- team_id=insight.team_id,
- insight_id=str(insight.id),
- dashboard_id=str(dashboard.id) if dashboard else None,
- error_message=str(e),
- error=True,
- )
- ),
- cache_key=None,
- hogql=None,
- columns=None,
- has_more=None,
- timezone=self.context["get_team"]().timezone,
)
+ def _degraded_insight_result(
+ self,
+ insight: Insight,
+ dashboard: Dashboard | None,
+ *,
+ error_message: str,
+ error_code: str | None,
+ last_refresh: datetime | None,
+ ) -> InsightResult:
+ """A 200 response carrying the failure on query_status, so a failing insight degrades in
+ place rather than failing the whole request. `error_code` lets the client tell a
+ deterministic query failure from a transient one."""
+ return InsightResult(
+ result=None,
+ last_refresh=last_refresh,
+ is_cached=False,
+ query_status=dict(
+ QueryStatus(
+ # QueryStatus.id is a required str; without a client_query_id this
+ # fallback used to crash pydantic validation and turn the degraded
+ # error state into a 500.
+ id=self.context["request"].query_params.get("client_query_id") or "",
+ team_id=insight.team_id,
+ insight_id=str(insight.id),
+ dashboard_id=str(dashboard.id) if dashboard else None,
+ error_message=error_message,
+ error_code=error_code,
+ error=True,
+ )
+ ),
+ cache_key=None,
+ hogql=None,
+ columns=None,
+ has_more=None,
+ timezone=self.context["get_team"]().timezone,
+ )
+
@lru_cache(maxsize=1) # noqa: B019 - short-lived serializer, one insight/tile combo
def dashboard_tile_from_context(self, insight: Insight, dashboard: Dashboard | None) -> DashboardTile | None:
dashboard_tile: DashboardTile | None = self.context.get("dashboard_tile", None)
diff --git a/products/product_analytics/backend/api/test/test_insight.py b/products/product_analytics/backend/api/test/test_insight.py
index 04de6cbeae5a..7deab17e9293 100644
--- a/products/product_analytics/backend/api/test/test_insight.py
+++ b/products/product_analytics/backend/api/test/test_insight.py
@@ -3596,7 +3596,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
)
self.assertEqual(
response_placeholder.json(),
- self.validation_error_response("Unresolved placeholder: {team_id}"),
+ self.validation_error_response("Unresolved placeholder: {team_id}", code="hogql_query_error"),
)
@also_test_with_materialized_columns(event_properties=["int_value"], person_properties=["fish"])
@@ -5089,14 +5089,14 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
class TestInsightErrorHandling(ClickhouseTestMixin, APIBaseTest):
@parameterized.expand(
[
- ("ExposedCHQueryError", "posthog.errors.ExposedCHQueryError", "NO_COMMON_TYPE error from ClickHouse"),
- ("ExposedHogQLError", "posthog.hogql.errors.ExposedHogQLError", "Invalid HogQL syntax"),
- ("HogVMException", "common.hogvm.python.utils.HogVMException", "Global variable not found: variables"),
+ ("ExposedCHQueryError", "NO_COMMON_TYPE error from ClickHouse", None),
+ ("ExposedHogQLError", "Invalid HogQL syntax", "hogql_error"),
+ ("HogVMException", "Global variable not found: variables", None),
]
)
@patch("posthog.caching.calculate_results.calculate_for_query_based_insight")
- def test_retrieve_returns_400_for_exposed_errors(
- self, _name: str, error_class_path: str, error_message: str, mock_calculate: mock.MagicMock
+ def test_retrieve_degrades_in_place_for_exposed_errors(
+ self, _name: str, error_message: str, expected_error_code: str | None, mock_calculate: mock.MagicMock
) -> None:
from posthog.hogql.errors import ExposedHogQLError
@@ -5121,8 +5121,13 @@ class TestInsightErrorHandling(ClickhouseTestMixin, APIBaseTest):
response = self.client.get(f"/api/environments/{self.team.id}/insights/{insight.id}/?refresh=blocking")
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertIn(error_message, str(response.json()))
+ # The failure must ride on query_status so a dashboard tile renders its own error state
+ # while the response as a whole succeeds.
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ query_status = response.json()["query_status"]
+ self.assertTrue(query_status["error"])
+ self.assertIn(error_message, query_status["error_message"])
+ self.assertEqual(query_status["error_code"], expected_error_code)
@parameterized.expand(
[