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(insights): return warehouse sync warnings with insight results (#106148)

Daniel RC11f2c4969edc
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.py
index d8b1f7f69206..73a7d79a3837 100644
--- a/posthog/api/test/dashboards/test_dashboard.py
+++ b/posthog/api/test/dashboards/test_dashboard.py
@@ -3124,6 +3124,7 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
"resolved_date_range": ANY,
"query_status": None,
"query_scan": None,
+ "warnings": None,
"result": None,
"saved": True,
"short_id": ANY,
diff --git a/posthog/caching/calculate_results.py b/posthog/caching/calculate_results.py
index d278a53754a8..de6142ecfffd 100644
--- a/posthog/caching/calculate_results.py
+++ b/posthog/caching/calculate_results.py
@@ -173,6 +173,7 @@ def calculate_for_query_based_insight(
types=getattr(process_response, "types", None),
resolved_date_range=_model_field_as_dict(process_response, "resolved_date_range"),
query_scan=_model_field_as_dict(process_response, "query_scan"),
+ warnings=_model_list_field_as_dicts(process_response, "warnings"),
)
response = process_response
@@ -196,4 +197,5 @@ def calculate_for_query_based_insight(
types=response.get("types"),
resolved_date_range=response.get("resolved_date_range"),
query_scan=response.get("query_scan"),
+ warnings=response.get("warnings"),
)
diff --git a/posthog/caching/insight_result.py b/posthog/caching/insight_result.py
index 1cb05b0478f5..0429c121dc95 100644
--- a/posthog/caching/insight_result.py
+++ b/posthog/caching/insight_result.py
@@ -24,6 +24,7 @@ class InsightResult:
resolved_date_range: Optional[dict] = None
# A QueryScanSummary dict. The insight serializer puts the stored analysis on it.
query_scan: Optional[dict] = None
+ warnings: Optional[list] = None
@dataclass(frozen=True)
diff --git a/posthog/caching/test/test_calculate_results.py b/posthog/caching/test/test_calculate_results.py
index cca37306f029..be0d8719abcc 100644
--- a/posthog/caching/test/test_calculate_results.py
+++ b/posthog/caching/test/test_calculate_results.py
@@ -10,6 +10,7 @@ from posthog.schema import (
CachedMarketingAnalyticsTableQueryResponse,
CachedRetentionQueryResponse,
CachedTrendsQueryResponse,
+ DataWarehouseSyncWarning,
HogQueryResponse,
MarketingAnalyticsItem,
RetentionResult,
@@ -108,6 +109,29 @@ class TestCalculateForQueryBasedInsight(BaseTest):
assert insight_result.is_cached is True
assert insight_result.cache_key == "key"
+ def test_warehouse_sync_warnings_reach_the_insight_result(self):
+ warning = DataWarehouseSyncWarning(
+ message="Last sync of `costs` (from DoIt) failed.",
+ schema_name="costs",
+ source_id="source-1",
+ source_type="DoIt",
+ status="Failed",
+ table_name="doit_costs",
+ )
+ response = CachedTrendsQueryResponse(
+ results=[],
+ is_cached=True,
+ last_refresh=datetime(2026, 1, 1, tzinfo=UTC),
+ next_allowed_client_refresh=datetime(2026, 1, 1, tzinfo=UTC),
+ cache_key="key",
+ timezone="UTC",
+ warnings=[warning],
+ )
+
+ insight_result = self._calculate(response)
+
+ assert insight_result.warnings == [warning.model_dump(by_alias=True)]
+
def test_raw_cached_results_become_fragments(self):
raw = orjson.dumps([{"data": [1.0], "label": "series"}])
response = RawCachedQueryResponse(
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index 67d8c13da36f..7a11061e94c7 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -1050,7 +1050,7 @@ class DashboardTileErrorSerializer(DashboardTileSerializer):
class InsightResultSerializer(InsightSerializer):
- """InsightSerializer restricted to identifiers + result only."""
+ """InsightSerializer restricted to identifiers, the result, and the warnings about that result."""
class Meta:
model = Insight
@@ -1060,6 +1060,7 @@ class InsightResultSerializer(InsightSerializer):
"name",
"derived_name",
"result",
+ "warnings",
]
read_only_fields = fields
diff --git a/products/dashboards/backend/api/test/test_run_insights.py b/products/dashboards/backend/api/test/test_run_insights.py
index d41d2adcf246..c09cc3fe75fd 100644
--- a/products/dashboards/backend/api/test/test_run_insights.py
+++ b/products/dashboards/backend/api/test/test_run_insights.py
@@ -1,7 +1,9 @@
import json
from posthog.test.base import APIBaseTest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
+
+from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
@@ -9,6 +11,7 @@ from rest_framework import status
from posthog.schema import DateRange, EventsNode, InsightVizNode, TrendsFilter, TrendsQuery
from posthog.api.test.dashboards import DashboardAPI
+from posthog.caching.insight_result import InsightResult
from posthog.models.organization import Organization
from posthog.models.team import Team
@@ -75,7 +78,7 @@ class TestDashboardRunInsights(APIBaseTest):
insight = tile["insight"]
self.assertEqual(
set(insight.keys()),
- {"id", "short_id", "name", "derived_name", "result"},
+ {"id", "short_id", "name", "derived_name", "result", "warnings"},
)
def test_json_format_returns_raw_query_results(self) -> None:
@@ -104,6 +107,33 @@ class TestDashboardRunInsights(APIBaseTest):
if isinstance(result, str):
self.assertIn("|", result)
+ @parameterized.expand([("json",), ("optimized",)])
+ @patch("posthog.caching.calculate_results.calculate_for_query_based_insight")
+ def test_a_tile_carries_its_warehouse_sync_warnings(self, output_format: str, mock_calculate: MagicMock) -> None:
+ warning = {
+ "type": "warehouse_sync",
+ "message": "Last sync of `costs` (from DoIt) failed.",
+ "schema_name": "costs",
+ "source_id": "source-1",
+ "source_type": "DoIt",
+ "status": "Failed",
+ "table_name": "doit_costs",
+ }
+ mock_calculate.return_value = InsightResult(
+ result=[],
+ last_refresh=timezone.now(),
+ cache_key="cache-key",
+ is_cached=True,
+ timezone=self.team.timezone,
+ warnings=[warning],
+ )
+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dash"})
+ self.dashboard_api.create_insight({"name": "A", "query": _trends_query_dict(), "dashboards": [dashboard_id]})
+
+ body = self._run(dashboard_id, output_format=output_format)
+
+ self.assertEqual(body["results"][0]["insight"]["warnings"], [warning])
+
def test_tile_ids_runs_only_the_selected_tiles(self) -> None:
dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dash"})
first_id, _ = self.dashboard_api.create_insight(
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 27f5e8ee6c6b..a6d97d7fb6d6 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -9232,6 +9232,11 @@ export interface DashboardTileBasicApi {
deleted?: boolean | null
}
+/**
+ * Warnings attached to the query response that produced an insight's results.
+ */
+export type _InsightResultWarningsApi = (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[]
+
export interface DashboardFilterApi {
breakdown_filter?: BreakdownFilterApi | null
date_from?: string | null
@@ -9430,6 +9435,8 @@ export interface InsightApi {
readonly resolved_date_range: InsightApiResolvedDateRange
/** What ClickHouse read for this insight's last slow run, with the findings of its query scan. */
readonly query_scan: unknown
+ /** Warnings from the run that produced these results. A `warehouse_sync` warning means the query read a data warehouse table whose sync failed, is paused, or is overdue, so the results can be out of date. Reflects the sync state when the results were computed. Null for shared insights. */
+ readonly warnings: _InsightResultWarningsApi | null
_create_in_folder?: string
readonly alerts: readonly unknown[]
/** Resolved dashboard and tile filter layers used to explain filter precedence in the UI. */
@@ -9589,7 +9596,7 @@ export interface ReorderTilesRequestApi {
}
/**
- * InsightSerializer restricted to identifiers + result only.
+ * InsightSerializer restricted to identifiers, the result, and the warnings about that result.
*/
export interface InsightResultApi {
readonly id: number
@@ -9599,6 +9606,8 @@ export interface InsightResultApi {
/** @nullable */
readonly derived_name: string | null
readonly result: unknown
+ /** Warnings from the run that produced these results. A `warehouse_sync` warning means the query read a data warehouse table whose sync failed, is paused, or is overdue, so the results can be out of date. Reflects the sync state when the results were computed. Null for shared insights. */
+ readonly warnings: _InsightResultWarningsApi | null
}
/**
diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.py
index ef5ae50e4b80..5b882e9baa52 100644
--- a/products/product_analytics/backend/presentation/insight.py
+++ b/products/product_analytics/backend/presentation/insight.py
@@ -32,7 +32,7 @@ from rest_framework.response import Response
from rest_framework.settings import api_settings
from rest_framework_csv import renderers as csvrenderers
-from posthog.schema import ProductKey, QueryStatus
+from posthog.schema import AccessControlFilterWarning, DataWarehouseSyncWarning, ProductKey, QueryStatus
from posthog.hogql.errors import ExposedHogQLError
@@ -519,6 +519,12 @@ class InsightFilterOverrideContext(BaseModel):
)
+class _InsightResultWarnings(RootModel):
+ """Warnings attached to the query response that produced an insight's results."""
+
+ root: list[DataWarehouseSyncWarning | AccessControlFilterWarning]
+
+
@extend_schema_serializer(deprecate_fields=["dashboards"])
class InsightSerializer(InsightBasicSerializer):
result = serializers.SerializerMethodField()
@@ -577,6 +583,15 @@ class InsightSerializer(InsightBasicSerializer):
read_only=True,
help_text="What ClickHouse read for this insight's last slow run, with the findings of its query scan.",
)
+ warnings = serializers.SerializerMethodField(
+ read_only=True,
+ allow_null=True,
+ help_text=(
+ "Warnings from the run that produced these results. A `warehouse_sync` warning means the query"
+ " read a data warehouse table whose sync failed, is paused, or is overdue, so the results can be"
+ " out of date. Reflects the sync state when the results were computed. Null for shared insights."
+ ),
+ )
_create_in_folder = serializers.CharField(required=False, allow_blank=True, write_only=True)
alerts = serializers.SerializerMethodField(read_only=True)
filter_override_context = serializers.SerializerMethodField(
@@ -623,6 +638,7 @@ class InsightSerializer(InsightBasicSerializer):
"types",
"resolved_date_range",
"query_scan",
+ "warnings",
"_create_in_folder",
"alerts",
"filter_override_context",
@@ -1116,6 +1132,14 @@ class InsightSerializer(InsightBasicSerializer):
return None
return hydrate_scan_summary(self.context["get_team"](), summary, cache_key)
+ @extend_schema_field(_InsightResultWarnings) # type: ignore[arg-type]
+ def get_warnings(self, insight: Insight) -> list[dict] | None:
+ # Sync warnings name warehouse tables and sources, which a shared viewer outside the
+ # project must not see.
+ if self.context.get("is_shared"):
+ return None
+ return self.insight_result(insight).warnings
+
@extend_schema_field(serializers.ListField())
def get_alerts(self, insight: Insight):
if insight.alertable_query_kind is None:
@@ -1299,6 +1323,7 @@ class InsightSerializer(InsightBasicSerializer):
hogql=cached_response.get("hogql"),
types=cached_response.get("types"),
query_scan=cached_response.get("query_scan"),
+ warnings=cached_response.get("warnings"),
)
else:
EXPORT_QUERY_CACHE_MISS.inc()
diff --git a/products/product_analytics/backend/tests/api/test_insight.py b/products/product_analytics/backend/tests/api/test_insight.py
index beeb7a3ace83..9484b0b0657b 100644
--- a/products/product_analytics/backend/tests/api/test_insight.py
+++ b/products/product_analytics/backend/tests/api/test_insight.py
@@ -4332,6 +4332,49 @@ class TestInsightQueryScan(APIBaseTest):
self.assertNotIn("query_scan", body["query_status"])
+class TestInsightWarnings(APIBaseTest):
+ WARNING = {
+ "type": "warehouse_sync",
+ "message": "Last sync of `costs` (from DoIt) failed.",
+ "schema_name": "costs",
+ "source_id": "source-1",
+ "source_type": "DoIt",
+ "status": "Failed",
+ "table_name": "doit_costs",
+ }
+
+ @parameterized.expand([("a project member", False, [WARNING]), ("a shared link viewer", True, None)])
+ @patch("posthog.caching.calculate_results.calculate_for_query_based_insight")
+ def test_an_insight_carries_its_warehouse_sync_warnings(
+ self, _name: str, shared: bool, expected: list[dict] | None, mock_calculate: mock.MagicMock
+ ) -> None:
+ insight = Insight.objects.create(
+ team=self.team,
+ created_by=self.user,
+ query={"kind": "DataVisualizationNode", "source": {"kind": "HogQLQuery", "query": "SELECT 1"}},
+ )
+ mock_calculate.return_value = InsightResult(
+ result=[],
+ last_refresh=timezone.now(),
+ cache_key="cache-key",
+ is_cached=True,
+ timezone=self.team.timezone,
+ warnings=[self.WARNING],
+ )
+ url = f"/api/projects/{self.team.id}/insights/{insight.id}/"
+ if shared:
+ sharing_configuration = SharingConfiguration.objects.create(
+ team=self.team, insight=insight, enabled=True, access_token="xyz"
+ )
+ self.client.logout()
+ url += f"?sharing_access_token={sharing_configuration.access_token}"
+
+ response = self.client.get(url)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ self.assertEqual(response.json()["warnings"], expected)
+
+
class TestInsightBulkDelete(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
def _create_insight(self, name: str = "My insight") -> Insight:
return Insight.objects.create(team=self.team, name=name, saved=True, created_by=self.user)
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index cfa0f598c849..acfc036a43fc 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -8374,6 +8374,11 @@ export const PrivilegeLevelEnumApi = {
Number37: 37,
} as const
+/**
+ * Warnings attached to the query response that produced an insight's results.
+ */
+export type _InsightResultWarningsApi = (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[]
+
export interface DashboardFilterApi {
breakdown_filter?: BreakdownFilterApi | null
date_from?: string | null
@@ -8579,6 +8584,8 @@ export interface InsightApi {
readonly resolved_date_range: InsightApiResolvedDateRange
/** What ClickHouse read for this insight's last slow run, with the findings of its query scan. */
readonly query_scan: unknown
+ /** Warnings from the run that produced these results. A `warehouse_sync` warning means the query read a data warehouse table whose sync failed, is paused, or is overdue, so the results can be out of date. Reflects the sync state when the results were computed. Null for shared insights. */
+ readonly warnings: _InsightResultWarningsApi | null
_create_in_folder?: string
readonly alerts: readonly unknown[]
/** Resolved dashboard and tile filter layers used to explain filter precedence in the UI. */
@@ -8709,6 +8716,8 @@ export interface PatchedInsightApi {
readonly resolved_date_range?: PatchedInsightApiResolvedDateRange
/** What ClickHouse read for this insight's last slow run, with the findings of its query scan. */
readonly query_scan?: unknown
+ /** Warnings from the run that produced these results. A `warehouse_sync` warning means the query read a data warehouse table whose sync failed, is paused, or is overdue, so the results can be out of date. Reflects the sync state when the results were computed. Null for shared insights. */
+ readonly warnings?: _InsightResultWarningsApi | null
_create_in_folder?: string
readonly alerts?: readonly unknown[]
/** Resolved dashboard and tile filter layers used to explain filter precedence in the UI. */
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 87885a2cc8dd..294867303992 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -9823,6 +9823,11 @@ export namespace Schemas {
Number37: 37,
} as const;
+ /**
+ * Warnings attached to the query response that produced an insight's results.
+ */
+ export type _InsightResultWarnings = (DataWarehouseSyncWarning | AccessControlFilterWarning)[];
+
export interface TileFilters {
breakdown_filter?: BreakdownFilter | null;
date_from?: string | null;
@@ -9963,6 +9968,8 @@ export namespace Schemas {
readonly resolved_date_range: InsightResolvedDateRange;
/** What ClickHouse read for this insight's last slow run, with the findings of its query scan. */
readonly query_scan: unknown;
+ /** Warnings from the run that produced these results. A `warehouse_sync` warning means the query read a data warehouse table whose sync failed, is paused, or is overdue, so the results can be out of date. Reflects the sync state when the results were computed. Null for shared insights. */
+ readonly warnings: _InsightResultWarnings | null;
_create_in_folder?: string;
readonly alerts: readonly unknown[];
/** Resolved dashboard and tile filter layers used to explain filter precedence in the UI. */
@@ -25206,7 +25213,7 @@ export namespace Schemas {
}
/**
- * InsightSerializer restricted to identifiers + result only.
+ * InsightSerializer restricted to identifiers, the result, and the warnings about that result.
*/
export interface InsightResult {
readonly id: number;
@@ -25216,6 +25223,8 @@ export namespace Schemas {
/** @nullable */
readonly derived_name: string | null;
readonly result: unknown;
+ /** Warnings from the run that produced these results. A `warehouse_sync` warning means the query read a data warehouse table whose sync failed, is paused, or is overdue, so the results can be out of date. Reflects the sync state when the results were computed. Null for shared insights. */
+ readonly warnings: _InsightResultWarnings | null;
}
/**
@@ -74429,6 +74438,8 @@ export namespace Schemas {
readonly resolved_date_range?: PatchedInsightResolvedDateRange;
/** What ClickHouse read for this insight's last slow run, with the findings of its query scan. */
readonly query_scan?: unknown;
+ /** Warnings from the run that produced these results. A `warehouse_sync` warning means the query read a data warehouse table whose sync failed, is paused, or is overdue, so the results can be out of date. Reflects the sync state when the results were computed. Null for shared insights. */
+ readonly warnings?: _InsightResultWarnings | null;
_create_in_folder?: string;
readonly alerts?: readonly unknown[];
/** Resolved dashboard and tile filter layers used to explain filter precedence in the UI. */