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(data-warehouse): warn when querying stale or failed warehouse syncs (#59436)

George Munyorod7d7c50c800a
diff --git a/ee/hogai/context/insight/format/__init__.py b/ee/hogai/context/insight/format/__init__.py
index 3fb7e2413df4..ca68ca039bee 100644
--- a/ee/hogai/context/insight/format/__init__.py
+++ b/ee/hogai/context/insight/format/__init__.py
@@ -58,6 +58,23 @@ def get_boxplot_results(response: dict[str, Any]) -> list[Any]:
return results if results else response.get("boxplot_data", [])
+def format_warehouse_sync_warnings(response: dict[str, Any]) -> str:
+ """Render data warehouse sync warnings as a leading block for LLM-facing output.
+
+ Returns empty string when the response has no warnings.
+ """
+ warnings = response.get("warnings") or []
+ if not warnings:
+ return ""
+ lines = ["[Data warehouse sync warnings — results may not reflect current source data]"]
+ for warning in warnings:
+ message = warning.get("message") if isinstance(warning, dict) else getattr(warning, "message", None)
+ if message:
+ lines.append(f"- {message}")
+ lines.append("")
+ return "\n".join(lines)
+
+
def format_query_results_for_llm(
query: BaseModel,
response: dict[str, Any],
@@ -79,32 +96,37 @@ def format_query_results_for_llm(
if isinstance(query, InsightVizNode | DataVisualizationNode | DataTableNode):
query = query.source
+ formatted: str | None = None
if isinstance(query, AssistantTrendsQuery | TrendsQuery):
if is_boxplot_query(query):
- return BoxPlotResultsFormatter(get_boxplot_results(response)).format()
- return TrendsResultsFormatter(query, response["results"]).format()
+ formatted = BoxPlotResultsFormatter(get_boxplot_results(response)).format()
+ else:
+ formatted = TrendsResultsFormatter(query, response["results"]).format()
elif isinstance(query, AssistantFunnelsQuery | FunnelsQuery):
- return FunnelResultsFormatter(query, response["results"], team, utc_now).format()
+ formatted = FunnelResultsFormatter(query, response["results"], team, utc_now).format()
elif isinstance(query, AssistantLifecycleQuery | LifecycleQuery):
- return LifecycleResultsFormatter(query, response["results"]).format()
+ formatted = LifecycleResultsFormatter(query, response["results"]).format()
elif isinstance(query, AssistantPathsQuery | PathsQuery):
- return PathsResultsFormatter(response["results"]).format()
+ formatted = PathsResultsFormatter(response["results"]).format()
elif isinstance(query, AssistantStickinessQuery | StickinessQuery):
- return StickinessResultsFormatter(query, response["results"]).format()
+ formatted = StickinessResultsFormatter(query, response["results"]).format()
elif isinstance(query, AssistantRetentionQuery | RetentionQuery):
- return RetentionResultsFormatter(query, response["results"]).format()
+ formatted = RetentionResultsFormatter(query, response["results"]).format()
elif isinstance(query, AssistantHogQLQuery | HogQLQuery):
- return SQLResultsFormatter(query, response["results"], response["columns"]).format()
+ formatted = SQLResultsFormatter(query, response["results"], response["columns"]).format()
elif isinstance(query, RevenueAnalyticsGrossRevenueQuery):
- return RevenueAnalyticsGrossRevenueResultsFormatter(query, response["results"]).format()
+ formatted = RevenueAnalyticsGrossRevenueResultsFormatter(query, response["results"]).format()
elif isinstance(query, RevenueAnalyticsMetricsQuery):
- return RevenueAnalyticsMetricsResultsFormatter(query, response["results"]).format()
+ formatted = RevenueAnalyticsMetricsResultsFormatter(query, response["results"]).format()
elif isinstance(query, RevenueAnalyticsMRRQuery):
- return RevenueAnalyticsMRRResultsFormatter(query, response["results"]).format()
+ formatted = RevenueAnalyticsMRRResultsFormatter(query, response["results"]).format()
elif isinstance(query, RevenueAnalyticsTopCustomersQuery):
- return RevenueAnalyticsTopCustomersResultsFormatter(query, response["results"]).format()
+ formatted = RevenueAnalyticsTopCustomersResultsFormatter(query, response["results"]).format()
- return None
+ if formatted is None:
+ return None
+ warning_prefix = format_warehouse_sync_warnings(response)
+ return warning_prefix + formatted if warning_prefix else formatted
__all__ = [
@@ -122,4 +144,5 @@ __all__ = [
"RevenueAnalyticsTopCustomersResultsFormatter",
"TRUNCATED_MARKER",
"format_query_results_for_llm",
+ "format_warehouse_sync_warnings",
]
diff --git a/ee/hogai/context/insight/query_executor.py b/ee/hogai/context/insight/query_executor.py
index c7a198bf7594..df3c0a091128 100644
--- a/ee/hogai/context/insight/query_executor.py
+++ b/ee/hogai/context/insight/query_executor.py
@@ -68,6 +68,7 @@ from ee.hogai.context.insight.format import (
SQLResultsFormatter,
StickinessResultsFormatter,
TrendsResultsFormatter,
+ format_warehouse_sync_warnings,
get_boxplot_results,
is_boxplot_query,
)
@@ -540,6 +541,10 @@ class AssistantQueryExecutor:
logger.warning(
f"{TIMING_LOG_PREFIX} {formatter_name}.format() completed in {elapsed:.3f}s for {query_type}"
)
+
+ warning_prefix = format_warehouse_sync_warnings(response)
+ if warning_prefix:
+ result = warning_prefix + result
return result
except Exception:
elapsed = time.time() - start_time
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index a2c00359cf3d..9a23b7bf7e76 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -6506,6 +6506,13 @@
"description": "Types of returned columns",
"items": {},
"type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ "type": "array"
}
},
"required": [
@@ -11856,6 +11863,13 @@
"description": "Types of returned columns",
"items": {},
"type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ "type": "array"
}
},
"required": ["results"],
@@ -13511,6 +13525,33 @@
"enum": ["data_warehouse", "endpoint", "managed_viewset"],
"type": "string"
},
+ "DataWarehouseSyncWarning": {
+ "additionalProperties": false,
+ "properties": {
+ "message": {
+ "description": "Human-readable warning shown to the user",
+ "type": "string"
+ },
+ "schema_name": {
+ "description": "Name of the ExternalDataSchema responsible for syncing the table",
+ "type": "string"
+ },
+ "source_type": {
+ "description": "Source type, e.g. \"Stripe\", \"Hubspot\"",
+ "type": "string"
+ },
+ "status": {
+ "description": "Sync status that triggered the warning, e.g. \"Failed\", \"Paused\", \"BillingLimitReached\"",
+ "type": "string"
+ },
+ "table_name": {
+ "description": "Name of the warehouse table the warning refers to",
+ "type": "string"
+ }
+ },
+ "required": ["table_name", "schema_name", "source_type", "status", "message"],
+ "type": "object"
+ },
"DataWarehouseViewLink": {
"additionalProperties": false,
"properties": {
@@ -21175,6 +21216,13 @@
"description": "Types of returned columns",
"items": {},
"type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ "type": "array"
}
},
"required": ["results"],
@@ -28433,6 +28481,13 @@
"description": "Types of returned columns",
"items": {},
"type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ "type": "array"
}
},
"required": ["results"],
@@ -30237,6 +30292,13 @@
"description": "Types of returned columns",
"items": {},
"type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ "type": "array"
}
},
"required": ["results"],
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 57857f5ddcdc..9772f0edf64c 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -468,6 +468,19 @@ export interface DataWarehouseEventsModifier {
id_field: string
}
+export interface DataWarehouseSyncWarning {
+ /** Name of the warehouse table the warning refers to */
+ table_name: string
+ /** Name of the ExternalDataSchema responsible for syncing the table */
+ schema_name: string
+ /** Source type, e.g. "Stripe", "Hubspot" */
+ source_type: string
+ /** Sync status that triggered the warning, e.g. "Failed", "Paused", "BillingLimitReached" */
+ status: string
+ /** Human-readable warning shown to the user */
+ message: string
+}
+
export interface HogQLQueryResponse<T = any[]> extends AnalyticsQueryResponseBase {
results: T
/** Input query string */
@@ -482,6 +495,11 @@ export interface HogQLQueryResponse<T = any[]> extends AnalyticsQueryResponseBas
explain?: string[]
/** Query metadata output */
metadata?: HogQLMetadataResponse
+ /**
+ * Warnings about data warehouse sources referenced by the query whose latest sync failed,
+ * is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data.
+ */
+ warnings?: DataWarehouseSyncWarning[]
hasMore?: boolean
limit?: integer
offset?: integer
diff --git a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
index 7c82de55fd71..ea1bf0bbe8db 100644
--- a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
@@ -19,7 +19,7 @@ import {
IconShare,
IconScreen,
} from '@posthog/icons'
-import { LemonButton, LemonDivider, LemonMenu, LemonModal, LemonTable, Tooltip } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonDivider, LemonMenu, LemonModal, LemonTable, Tooltip } from '@posthog/lemon-ui'
import { ExportButton } from 'lib/components/ExportButton/ExportButton'
import { JSONViewer } from 'lib/components/JSONViewer'
@@ -946,6 +946,24 @@ function InternalDataTableVisualization(
)
}
+const SyncWarningsBanner = ({ warnings }: { warnings?: HogQLQueryResponse['warnings'] }): JSX.Element | null => {
+ if (!warnings || warnings.length === 0) {
+ return null
+ }
+ return (
+ <LemonBanner type="warning" className="m-2" data-attr="sql-editor-output-pane-sync-warnings">
+ <div className="font-semibold mb-1">
+ Some warehouse sources used by this query are out of date — results may not reflect current data
+ </div>
+ <ul className="list-disc pl-5 space-y-1">
+ {warnings.map((warning, index) => (
+ <li key={`${warning.table_name}-${warning.schema_name}-${index}`}>{warning.message}</li>
+ ))}
+ </ul>
+ </LemonBanner>
+ )
+}
+
const ErrorState = ({ responseError, sourceQuery, queryCancelled, response }: any): JSX.Element | null => {
const error = queryCancelled
? 'The query was cancelled'
@@ -1055,7 +1073,8 @@ const Content = ({
}
return (
- <div className="flex-1 absolute inset-0 hide-scrollbar border-t">
+ <div className="flex-1 absolute inset-0 hide-scrollbar border-t overflow-auto">
+ <SyncWarningsBanner warnings={response?.warnings} />
<InternalDataTableVisualization
uniqueKey={vizKey}
query={sourceQuery}
@@ -1110,6 +1129,7 @@ const Content = ({
if (activeTab === OutputTab.Results) {
return (
<TabScroller data-attr="sql-editor-output-pane-results">
+ <SyncWarningsBanner warnings={response?.warnings} />
<DataGrid
className={clsx(isDarkModeOn ? 'rdg-dark h-full' : 'rdg-light h-full', 'ph-no-capture')}
columns={columns}
diff --git a/posthog/hogql/context.py b/posthog/hogql/context.py
index 0f6aae3191ab..29fc51e4329a 100644
--- a/posthog/hogql/context.py
+++ b/posthog/hogql/context.py
@@ -2,7 +2,7 @@ from dataclasses import dataclass, field
from functools import cached_property
from typing import TYPE_CHECKING, Any, Literal, Optional
-from posthog.schema import HogQLNotice, HogQLQueryModifiers
+from posthog.schema import DataWarehouseSyncWarning, HogQLNotice, HogQLQueryModifiers
from posthog.hogql.constants import LimitContext
from posthog.hogql.timings import HogQLTimings
@@ -65,6 +65,10 @@ class HogQLContext:
# Errors returned with the metadata query
errors: list["HogQLNotice"] = field(default_factory=list)
+ # Data warehouse sync warnings collected while resolving warehouse tables referenced by the query.
+ # Keyed by (table_id, schema_name) to dedupe when a table is referenced multiple times.
+ data_warehouse_sync_warnings: dict[tuple[str, str], "DataWarehouseSyncWarning"] = field(default_factory=dict)
+
# Timings in seconds for different parts of the HogQL query
timings: HogQLTimings = field(default_factory=HogQLTimings)
# Modifications requested by the HogQL client
@@ -124,6 +128,9 @@ class HogQLContext:
if not any(n.start == start and n.end == end and n.message == message and n.fix == fix for n in self.errors):
self.errors.append(HogQLNotice(start=start, end=end, message=message, fix=fix))
+ def add_data_warehouse_sync_warning(self, table_id: str, warning: "DataWarehouseSyncWarning") -> None:
+ self.data_warehouse_sync_warnings[(table_id, warning.schema_name)] = warning
+
@cached_property
def project_id(self) -> int:
from posthog.models import Team
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 12daacc4325d..ccdda4328195 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -1,6 +1,7 @@
import dataclasses
from collections import defaultdict
from collections.abc import Callable, Sequence
+from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any, Literal, Optional, Union, cast
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
@@ -151,6 +152,7 @@ from posthog.exceptions_capture import capture_exception
from posthog.models.group_type_mapping import get_group_types_for_project
from posthog.models.team.team import WeekStartDay
+from products.data_warehouse.backend.sync_status import get_warehouse_sync_warnings
from products.revenue_analytics.backend.views import RevenueAnalyticsBaseView
from products.revenue_analytics.backend.views.orchestrator import build_all_revenue_analytics_views
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
@@ -159,6 +161,8 @@ from products.warehouse_sources.backend.models.external_data_source import Exter
from products.warehouse_sources.backend.models.table import DataWarehouseTable, DataWarehouseTableColumns
if TYPE_CHECKING:
+ from posthog.schema import DataWarehouseSyncWarning
+
from posthog.models import Team, User
from posthog.rbac.user_access_control import UserAccessControl
@@ -340,6 +344,9 @@ class Database(BaseModel):
_connection_id: str | None = None
_direct_connection_metadata: dict[str, Any] | None = None
_direct_access_warehouse_table_names: set[str] = set()
+ # Warnings about data warehouse tables (failed/paused/billing-limited/stale syncs),
+ # keyed by HogQL DataWarehouseTable.table_id (str(Django table UUID)).
+ _data_warehouse_sync_warnings: dict[str, list["DataWarehouseSyncWarning"]] = {}
_timezone: str | None
_week_start_day: WeekStartDay | None
@@ -364,6 +371,7 @@ class Database(BaseModel):
self._connection_id = None
self._direct_connection_metadata = None
self._direct_access_warehouse_table_names = set()
+ self._data_warehouse_sync_warnings = {}
self._serialization_errors: dict[str, str] = {} # table_key -> error_message
self.user_access_control: Optional[UserAccessControl] = None
@@ -1173,6 +1181,7 @@ class Database(BaseModel):
connection_id=cast(str, database._connection_id),
)
]
+ sync_warnings_now = datetime.now(UTC)
for table in tables:
if (
not database._is_direct_query()
@@ -1183,6 +1192,10 @@ class Database(BaseModel):
with timings.measure(f"table_{table.name}"):
s3_table = table.hogql_definition(modifiers)
+
+ sync_warnings = get_warehouse_sync_warnings(table, now=sync_warnings_now)
+ if sync_warnings:
+ database._data_warehouse_sync_warnings[str(table.id)] = sync_warnings
primary_table = s3_table
# If the warehouse table has no _properties_ field, then set it as a virtual table
@@ -1682,7 +1695,9 @@ def _preload_active_external_data_schemas(warehouse_tables: Sequence[DataWarehou
return
schemas_by_table_id: dict[str, list[ExternalDataSchema]] = defaultdict(list)
- for schema in ExternalDataSchema.objects.filter(NOT_DELETED_Q, table_id__in=table_ids):
+ # select_related("source"): warning rendering reads schema.source.source_type, so avoid a
+ # per-schema lazy fetch when any of these tables turns out to be unhealthy.
+ for schema in ExternalDataSchema.objects.filter(NOT_DELETED_Q, table_id__in=table_ids).select_related("source"):
schemas_by_table_id[str(schema.table_id)].append(schema)
for warehouse_table in warehouse_tables:
diff --git a/posthog/hogql/query.py b/posthog/hogql/query.py
index 27b5a81fdc34..7d5f5b1c4753 100644
--- a/posthog/hogql/query.py
+++ b/posthog/hogql/query.py
@@ -389,6 +389,11 @@ class HogQLQueryExecutor:
connection_id=self.connection_id,
)
+ # Reset between executions: the resolver appends per query, and dataclasses.replace below
+ # shares this dict by reference. Without reset, callers reusing a HogQLContext across
+ # executors would see warnings from prior runs.
+ self.context.data_warehouse_sync_warnings.clear()
+
self.hogql_context = dataclasses.replace(
self.context,
team_id=self.team.pk,
@@ -880,6 +885,7 @@ class HogQLQueryExecutor:
elif self.clickhouse_sql is not None:
self._execute_clickhouse_query()
+ warnings = list(self.context.data_warehouse_sync_warnings.values()) if self.context else []
return HogQLQueryResponse(
query=self.query,
hogql=self.hogql,
@@ -892,6 +898,7 @@ class HogQLQueryExecutor:
modifiers=self.query_modifiers,
explain=self.explain,
metadata=self.metadata,
+ warnings=warnings or None,
hasMore=self.has_more,
limit=self.limit,
offset=self.offset,
diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.py
index 477c85952afc..bf4cd7a1f779 100644
--- a/posthog/hogql/resolver.py
+++ b/posthog/hogql/resolver.py
@@ -13,7 +13,10 @@ from posthog.hogql.constants import HogQLDialect
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
from posthog.hogql.database.models import FunctionCallTable, LazyTable, SavedQuery, StringJSONDatabaseField
-from posthog.hogql.database.s3_table import S3Table
+from posthog.hogql.database.s3_table import (
+ DataWarehouseTable as HogQLDataWarehouseTable,
+ S3Table,
+)
from posthog.hogql.database.schema.duckdb_table_functions import build_opaque_function_call_table
from posthog.hogql.database.schema.events import EventsTable
from posthog.hogql.database.schema.persons import PersonsTable
@@ -1092,6 +1095,9 @@ class Resolver(CloningVisitor):
assert isinstance(database_table, ast.Table)
node_table_type = ast.TableType(table=database_table)
+ if isinstance(database_table, HogQLDataWarehouseTable) and database_table.table_id is not None:
+ self._record_warehouse_sync_warnings(database_table.table_id)
+
# Always add an alias for function call tables. This way `select table.* from table` is replaced with
# `select table.* from something() as table`, and not with `select something().* from something()`.
if node.column_aliases:
@@ -2069,6 +2075,15 @@ class Resolver(CloningVisitor):
return False
+ def _record_warehouse_sync_warnings(self, table_id: str) -> None:
+ if self.database is None:
+ return
+ warnings = getattr(self.database, "_data_warehouse_sync_warnings", {}).get(table_id)
+ if not warnings:
+ return
+ for warning in warnings:
+ self.context.add_data_warehouse_sync_warning(table_id, warning)
+
def _build_opaque_table_function(
self, table_name_chain: list[str], node: ast.JoinExpr
) -> Optional[FunctionCallTable]:
diff --git a/posthog/schema.py b/posthog/schema.py
index 810838452d86..320dc27fbbe9 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -1360,6 +1360,23 @@ class DataWarehouseSavedQueryOrigin(StrEnum):
MANAGED_VIEWSET = "managed_viewset"
+class DataWarehouseSyncWarning(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ message: str = Field(..., description="Human-readable warning shown to the user")
+ schema_name: str = Field(
+ ...,
+ description="Name of the ExternalDataSchema responsible for syncing the table",
+ )
+ source_type: str = Field(..., description='Source type, e.g. "Stripe", "Hubspot"')
+ status: str = Field(
+ ...,
+ description=('Sync status that triggered the warning, e.g. "Failed", "Paused", "BillingLimitReached"'),
+ )
+ table_name: str = Field(..., description="Name of the warehouse table the warning refers to")
+
+
class DatabaseSchemaManagedViewTableKind(StrEnum):
REVENUE_ANALYTICS_CHARGE = "revenue_analytics_charge"
REVENUE_ANALYTICS_CUSTOMER = "revenue_analytics_customer"
@@ -15259,6 +15276,14 @@ class HogQLQueryResponse(BaseModel):
description=("Measured timings for different parts of the query generation process"),
)
types: list | None = Field(default=None, description="Types of returned columns")
+ warnings: list[DataWarehouseSyncWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose latest"
+ " sync failed, is paused, hit a billing limit, or is otherwise stale."
+ " Results may not reflect current source data."
+ ),
+ )
class IQRDetectorConfig(BaseModel):
@@ -16124,6 +16149,14 @@ class QueryResponseAlternative8(BaseModel):
description=("Measured timings for different parts of the query generation process"),
)
types: list | None = Field(default=None, description="Types of returned columns")
+ warnings: list[DataWarehouseSyncWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose latest"
+ " sync failed, is paused, hit a billing limit, or is otherwise stale."
+ " Results may not reflect current source data."
+ ),
+ )
class QueryResponseAlternative11(BaseModel):
@@ -16845,6 +16878,14 @@ class QueryResponseAlternative42(BaseModel):
description=("Measured timings for different parts of the query generation process"),
)
types: list | None = Field(default=None, description="Types of returned columns")
+ warnings: list[DataWarehouseSyncWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose latest"
+ " sync failed, is paused, hit a billing limit, or is otherwise stale."
+ " Results may not reflect current source data."
+ ),
+ )
class QueryResponseAlternative43(BaseModel):
@@ -19430,6 +19471,14 @@ class CachedHogQLQueryResponse(BaseModel):
description=("Measured timings for different parts of the query generation process"),
)
types: list | None = Field(default=None, description="Types of returned columns")
+ warnings: list[DataWarehouseSyncWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose latest"
+ " sync failed, is paused, hit a billing limit, or is otherwise stale."
+ " Results may not reflect current source data."
+ ),
+ )
class CachedInsightActorsQueryOptionsResponse(BaseModel):
@@ -19639,6 +19688,14 @@ class Response3(BaseModel):
description=("Measured timings for different parts of the query generation process"),
)
types: list | None = Field(default=None, description="Types of returned columns")
+ warnings: list[DataWarehouseSyncWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose latest"
+ " sync failed, is paused, hit a billing limit, or is otherwise stale."
+ " Results may not reflect current source data."
+ ),
+ )
class Response21(BaseModel):
diff --git a/products/data_warehouse/backend/sync_status.py b/products/data_warehouse/backend/sync_status.py
new file mode 100644
index 000000000000..71c4ac52b3eb
--- /dev/null
+++ b/products/data_warehouse/backend/sync_status.py
@@ -0,0 +1,136 @@
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from typing import TYPE_CHECKING, cast
+
+from django.db.models import Q
+
+import humanize
+
+from posthog.schema import DataWarehouseSyncWarning
+
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.models.table import DataWarehouseTable
+
+
+# When a schema is still in RUNNING state but its last successful sync is older than
+# (sync_frequency_interval * STALE_RUNNING_MULTIPLIER), we consider the data stale.
+STALE_RUNNING_MULTIPLIER = 2
+
+# Mirrors database._get_active_external_data_schemas / NOT_DELETED_Q. Kept local to avoid a
+# circular import between sync_status.py and posthog.hogql.database.database.
+_NOT_DELETED = Q(deleted=False) | Q(deleted__isnull=True)
+
+
+def _ensure_utc(dt: datetime) -> datetime:
+ return dt if dt.tzinfo is not None else dt.replace(tzinfo=UTC)
+
+
+def _active_external_data_schemas(warehouse_table: DataWarehouseTable) -> list[ExternalDataSchema]:
+ preloaded = cast(
+ list[ExternalDataSchema] | None,
+ getattr(warehouse_table, "_active_external_data_schemas", None),
+ )
+ if preloaded is not None:
+ return preloaded
+ if warehouse_table.external_data_source_id is None:
+ return []
+ # select_related("source"): _build_warning_for_schema reads schema.source.source_type.
+ return list(ExternalDataSchema.objects.filter(_NOT_DELETED, table_id=warehouse_table.id).select_related("source"))
+
+
+def _build_warning_for_schema(
+ *,
+ table_name: str,
+ schema: ExternalDataSchema,
+ now: datetime,
+) -> DataWarehouseSyncWarning | None:
+ schema_status = schema.status
+ source_type = schema.source.source_type if schema.source_id else "unknown"
+
+ def build(*, status: str, message: str) -> DataWarehouseSyncWarning:
+ return DataWarehouseSyncWarning(
+ table_name=table_name,
+ schema_name=schema.name,
+ source_type=source_type,
+ status=status,
+ message=message,
+ )
+
+ if schema_status == ExternalDataSchema.Status.FAILED:
+ message = f"Last sync of `{table_name}` (from {source_type}) failed."
+ if schema.last_synced_at:
+ message += f" Results reflect data from {humanize.naturaltime(now - _ensure_utc(schema.last_synced_at))}."
+ else:
+ message += " No successful sync has completed yet — the table may be empty or incomplete."
+ # Deliberately omit schema.latest_error: it holds raw exception text (DB hostnames,
+ # credentials, stack traces) and this message reaches LLM contexts via MCP/Max. The full
+ # error stays in the data warehouse source screen, which is access-scoped.
+ message += " Check the data warehouse source for details."
+ return build(status=ExternalDataSchema.Status.FAILED, message=message)
+
+ if schema_status == ExternalDataSchema.Status.BILLING_LIMIT_REACHED:
+ return build(
+ status=ExternalDataSchema.Status.BILLING_LIMIT_REACHED,
+ message=(
+ f"Sync of `{table_name}` (from {source_type}) is paused because the data warehouse "
+ "billing limit has been reached. Results may be out of date."
+ ),
+ )
+
+ if schema_status == ExternalDataSchema.Status.BILLING_LIMIT_TOO_LOW:
+ return build(
+ status=ExternalDataSchema.Status.BILLING_LIMIT_TOO_LOW,
+ message=(
+ f"Sync of `{table_name}` (from {source_type}) is paused because the configured "
+ "billing limit is too low. Results may be out of date."
+ ),
+ )
+
+ if schema_status == ExternalDataSchema.Status.PAUSED or not schema.should_sync:
+ return build(
+ status=ExternalDataSchema.Status.PAUSED,
+ message=f"Sync of `{table_name}` (from {source_type}) is paused. Results reflect the last successful sync.",
+ )
+
+ if schema_status == ExternalDataSchema.Status.RUNNING:
+ interval = schema.sync_frequency_interval
+ if interval is None or schema.last_synced_at is None:
+ return None
+ last_synced = _ensure_utc(schema.last_synced_at)
+ if (now - last_synced) <= interval * STALE_RUNNING_MULTIPLIER:
+ return None
+ return build(
+ status=ExternalDataSchema.Status.RUNNING,
+ message=(
+ f"`{table_name}` (from {source_type}) last completed syncing "
+ f"{humanize.naturaltime(now - last_synced)}, more than twice its configured sync interval. "
+ "A new sync is in progress but results may be out of date."
+ ),
+ )
+
+ return None
+
+
+def get_warehouse_sync_warnings(
+ warehouse_table: DataWarehouseTable,
+ *,
+ now: datetime,
+) -> list[DataWarehouseSyncWarning]:
+ """Return sync warnings for a single data warehouse table.
+
+ Uses the table's preloaded `_active_external_data_schemas` when available; falls back to a query.
+ Skips self-managed tables (no external data source). Caller must pass `now` so a single timestamp
+ is shared across all tables in a build.
+ """
+ if warehouse_table.external_data_source_id is None:
+ return []
+
+ warnings: list[DataWarehouseSyncWarning] = []
+ for schema in _active_external_data_schemas(warehouse_table):
+ warning = _build_warning_for_schema(table_name=warehouse_table.name, schema=schema, now=now)
+ if warning is not None:
+ warnings.append(warning)
+ return warnings
diff --git a/products/data_warehouse/backend/test/test_sync_status.py b/products/data_warehouse/backend/test/test_sync_status.py
new file mode 100644
index 000000000000..67fea5035a1c
--- /dev/null
+++ b/products/data_warehouse/backend/test/test_sync_status.py
@@ -0,0 +1,180 @@
+from datetime import UTC, datetime, timedelta
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from products.data_warehouse.backend.sync_status import get_warehouse_sync_warnings
+from products.data_warehouse.backend.types import ExternalDataSourceType
+from products.warehouse_sources.backend.models.credential import DataWarehouseCredential
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.models.table import DataWarehouseTable
+
+
+class TestWarehouseSyncWarnings(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_id="source_id",
+ connection_id="connection_id",
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type=ExternalDataSourceType.STRIPE,
+ )
+ self.credential = DataWarehouseCredential.objects.create(
+ team=self.team,
+ access_key="key",
+ access_secret="secret",
+ )
+ self.table = DataWarehouseTable.objects.create(
+ name="stripe_charge",
+ format=DataWarehouseTable.TableFormat.Parquet,
+ team=self.team,
+ external_data_source=self.source,
+ credential=self.credential,
+ url_pattern="http://host.docker.internal:19000/test/*.parquet",
+ columns={"id": "String"},
+ )
+ self.now = datetime(2026, 1, 1, 12, 0, 0, tzinfo=UTC)
+
+ def _make_schema(
+ self,
+ *,
+ status: str | None,
+ last_synced_at: datetime | None = None,
+ sync_frequency_interval: timedelta | None = timedelta(hours=6),
+ latest_error: str | None = None,
+ should_sync: bool = True,
+ ) -> ExternalDataSchema:
+ return ExternalDataSchema.objects.create(
+ name="Charge",
+ team=self.team,
+ source=self.source,
+ table=self.table,
+ status=status,
+ last_synced_at=last_synced_at,
+ sync_frequency_interval=sync_frequency_interval,
+ latest_error=latest_error,
+ should_sync=should_sync,
+ )
+
+ def test_no_warnings_for_self_managed_table(self) -> None:
+ self.table.external_data_source = None
+ self.table.save()
+ warnings = get_warehouse_sync_warnings(self.table, now=self.now)
+ assert warnings == []
+
+ def test_no_warnings_when_completed(self) -> None:
+ self._make_schema(
+ status=ExternalDataSchema.Status.COMPLETED,
+ last_synced_at=self.now - timedelta(hours=1),
+ )
+ warnings = get_warehouse_sync_warnings(self.table, now=self.now)
+ assert warnings == []
+
+ def test_no_warning_when_running_within_interval(self) -> None:
+ self._make_schema(
+ status=ExternalDataSchema.Status.RUNNING,
+ last_synced_at=self.now - timedelta(hours=6),
+ sync_frequency_interval=timedelta(hours=6),
+ )
+ warnings = get_warehouse_sync_warnings(self.table, now=self.now)
+ assert warnings == []
+
+ @parameterized.expand(
+ [
+ (ExternalDataSchema.Status.FAILED,),
+ (ExternalDataSchema.Status.BILLING_LIMIT_REACHED,),
+ (ExternalDataSchema.Status.BILLING_LIMIT_TOO_LOW,),
+ (ExternalDataSchema.Status.PAUSED,),
+ ]
+ )
+ def test_warning_for_problem_statuses(self, status: str) -> None:
+ self._make_schema(
+ status=status,
+ last_synced_at=self.now - timedelta(hours=2),
+ latest_error="boom" if status == ExternalDataSchema.Status.FAILED else None,
+ )
+ warnings = get_warehouse_sync_warnings(self.table, now=self.now)
+ assert len(warnings) == 1
+ warning = warnings[0]
+ assert warning.table_name == "stripe_charge"
+ assert warning.schema_name == "Charge"
+ assert warning.source_type == ExternalDataSourceType.STRIPE
+ assert warning.status == str(status)
+ assert "stripe_charge" in warning.message
+
+ def test_failed_does_not_leak_raw_error(self) -> None:
+ self._make_schema(
+ status=ExternalDataSchema.Status.FAILED,
+ last_synced_at=self.now - timedelta(hours=2),
+ latest_error="connection to db-prod-1.internal:5432 failed: password authentication failed",
+ )
+ warnings = get_warehouse_sync_warnings(self.table, now=self.now)
+ assert len(warnings) == 1
+ # Raw error text (hostnames, credentials) must not reach the warning message.
+ assert "db-prod-1.internal" not in warnings[0].message
+ assert "password" not in warnings[0].message
+ assert "data warehouse source" in warnings[0].message.lower()
+
+ def test_warning_when_running_but_stale(self) -> None:
+ self._make_schema(
+ status=ExternalDataSchema.Status.RUNNING,
+ sync_frequency_interval=timedelta(hours=6),
+ last_synced_at=self.now - timedelta(hours=13),
+ )
+ warnings = get_warehouse_sync_warnings(self.table, now=self.now)
+ assert len(warnings) == 1
+ assert warnings[0].status == str(ExternalDataSchema.Status.RUNNING)
+ assert "more than twice" in warnings[0].message
+
+ def test_no_warning_when_running_at_exact_threshold(self) -> None:
+ self._make_schema(
+ status=ExternalDataSchema.Status.RUNNING,
+ sync_frequency_interval=timedelta(hours=6),
+ last_synced_at=self.now - timedelta(hours=12),
+ )
+ warnings = get_warehouse_sync_warnings(self.table, now=self.now)
+ assert warnings == []
+
+ def test_no_warning_when_running_without_interval(self) -> None:
+ self._make_schema(
+ status=ExternalDataSchema.Status.RUNNING,
+ sync_frequency_interval=None,
+ last_synced_at=self.now - timedelta(days=5),
+ )
+ warnings = get_warehouse_sync_warnings(self.table, now=self.now)
+ assert warnings == []
+
+ def test_should_not_sync_treated_as_paused(self) -> None:
+ self._make_schema(
+ status=ExternalDataSchema.Status.COMPLETED,
+ should_sync=False,
+ last_synced_at=self.now - timedelta(hours=1),
+ )
+ warnings = get_warehouse_sync_warnings(self.table, now=self.now)
+ assert len(warnings) == 1
+ assert "paused" in warnings[0].message.lower()
+ # status must be consistent with the "paused" message, not the raw schema status (Completed).
+ assert warnings[0].status == ExternalDataSchema.Status.PAUSED
+
+ def test_uses_preloaded_schemas_when_available(self) -> None:
+ """If `_active_external_data_schemas` is set on the table, it's used directly without a DB query."""
+ fake_schema = MagicMock(spec=ExternalDataSchema)
+ fake_schema.name = "PreloadedSchema"
+ fake_schema.status = ExternalDataSchema.Status.FAILED
+ fake_schema.last_synced_at = self.now - timedelta(hours=3)
+ fake_schema.sync_frequency_interval = timedelta(hours=6)
+ fake_schema.latest_error = "preloaded error"
+ fake_schema.should_sync = True
+ fake_schema.source_id = self.source.id
+ fake_schema.source = self.source
+
+ self.table.__dict__["_active_external_data_schemas"] = [fake_schema]
+
+ warnings = get_warehouse_sync_warnings(self.table, now=self.now)
+ assert len(warnings) == 1
+ assert warnings[0].schema_name == "PreloadedSchema"
+ assert warnings[0].status == ExternalDataSchema.Status.FAILED
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index fa4bfdc0d2d6..3aefbbe08a70 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -3042,6 +3042,19 @@ export interface HogQLMetadataResponseApi {
warnings: HogQLNoticeApi[]
}
+export interface DataWarehouseSyncWarningApi {
+ /** Human-readable warning shown to the user */
+ message: string
+ /** Name of the ExternalDataSchema responsible for syncing the table */
+ schema_name: string
+ /** Source type, e.g. "Stripe", "Hubspot" */
+ source_type: string
+ /** Sync status that triggered the warning, e.g. "Failed", "Paused", "BillingLimitReached" */
+ status: string
+ /** Name of the warehouse table the warning refers to */
+ table_name: string
+}
+
export interface Response3Api {
/** Executed ClickHouse query */
clickhouse?: string | null
@@ -3071,6 +3084,8 @@ export interface Response3Api {
timings?: QueryTimingApi[] | null
/** Types of returned columns */
types?: unknown[] | null
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. */
+ warnings?: DataWarehouseSyncWarningApi[] | null
}
export interface Response4Api {
@@ -4731,6 +4746,8 @@ export interface HogQLQueryResponseApi {
timings?: QueryTimingApi[] | null
/** Types of returned columns */
types?: unknown[] | null
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. */
+ warnings?: DataWarehouseSyncWarningApi[] | null
}
export interface HogQLVariableApi {
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index a098de32af6e..827244b9d4c2 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -69,6 +69,23 @@ export interface SearchResponse {
export type Result<T, E = Error> = { success: true; data: T } | { success: false; error: E }
+export interface DataWarehouseSyncWarning {
+ table_name: string
+ schema_name: string
+ source_type: string
+ status: string
+ message: string
+}
+
+export interface QueryEndpointResponse {
+ results: unknown
+ columns?: unknown
+ formatted_results?: string
+ // null (not just absent) when the query response carries no warnings — the backend
+ // serializes the field explicitly rather than omitting it.
+ warnings?: DataWarehouseSyncWarning[] | null
+}
+
export interface ApiConfig {
apiToken: string
baseUrl: string
@@ -982,14 +999,10 @@ export class ApiClient {
}
},
- query: async ({
- query,
- }: {
- query: Record<string, any>
- }): Promise<Result<{ results: unknown; columns?: unknown; formatted_results?: string }>> => {
+ query: async ({ query }: { query: Record<string, any> }): Promise<Result<QueryEndpointResponse>> => {
const url = `${this.baseUrl}/api/environments/${projectId}/query/`
- return this.fetchJson<{ results: unknown; columns?: unknown; formatted_results?: string }>(url, {
+ return this.fetchJson<QueryEndpointResponse>(url, {
method: 'POST',
body: JSON.stringify({ query }),
})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e729396e862f..16e97b5d1b74 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -3567,6 +3567,19 @@ export namespace Schemas {
warnings: HogQLNotice[];
}
+ export interface DataWarehouseSyncWarning {
+ /** Human-readable warning shown to the user */
+ message: string;
+ /** Name of the ExternalDataSchema responsible for syncing the table */
+ schema_name: string;
+ /** Source type, e.g. "Stripe", "Hubspot" */
+ source_type: string;
+ /** Sync status that triggered the warning, e.g. "Failed", "Paused", "BillingLimitReached" */
+ status: string;
+ /** Name of the warehouse table the warning refers to */
+ table_name: string;
+ }
+
export interface HogQLQueryResponse {
/** Executed ClickHouse query */
clickhouse?: string | null;
@@ -3596,6 +3609,8 @@ export namespace Schemas {
timings?: QueryTiming[] | null;
/** Types of returned columns */
types?: unknown[] | null;
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. */
+ warnings?: DataWarehouseSyncWarning[] | null;
}
export interface HogQLVariable {
@@ -9248,6 +9263,8 @@ export namespace Schemas {
timings?: QueryTiming[] | null;
/** Types of returned columns */
types?: unknown[] | null;
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. */
+ warnings?: DataWarehouseSyncWarning[] | null;
}
export interface Response4 {
@@ -33529,6 +33546,8 @@ export namespace Schemas {
timings?: QueryTiming[] | null;
/** Types of returned columns */
types?: unknown[] | null;
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. */
+ warnings?: DataWarehouseSyncWarning[] | null;
}
export interface QueryResponseAlternative9 {
@@ -34145,6 +34164,8 @@ export namespace Schemas {
timings?: QueryTiming[] | null;
/** Types of returned columns */
types?: unknown[] | null;
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. */
+ warnings?: DataWarehouseSyncWarning[] | null;
}
export interface QueryResponseAlternative43 {
diff --git a/services/mcp/src/tools/query/run.ts b/services/mcp/src/tools/query/run.ts
index 48b186ee22b0..13245470b613 100644
--- a/services/mcp/src/tools/query/run.ts
+++ b/services/mcp/src/tools/query/run.ts
@@ -1,5 +1,6 @@
import type { z } from 'zod'
+import type { DataWarehouseSyncWarning } from '@/api/client'
import { withUiApp } from '@/resources/ui-apps'
import { QueryRunInputSchema } from '@/schema/tool-inputs'
import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
@@ -12,7 +13,7 @@ const schema = QueryRunInputSchema
type Params = z.infer<typeof schema>
-type Result = WithPostHogUrl<{ query: unknown; results: unknown }>
+type Result = WithPostHogUrl<{ query: unknown; results: unknown; warnings?: DataWarehouseSyncWarning[] }>
export const queryRunHandler: ToolBase<typeof schema, Result>['handler'] = async (context: Context, params: Params) => {
const { query } = params
@@ -39,6 +40,8 @@ export const queryRunHandler: ToolBase<typeof schema, Result>['handler'] = async
// TrendsQuery, FunnelsQuery, and PathsQuery return results directly as an array
// HogQLQuery returns { results: [...], columns: [...] }
// The UI app infers the visualization type from the data structure
+ const warningsField = queryResult.data.warnings?.length ? { warnings: queryResult.data.warnings } : {}
+
if (
queryInfo.visualization === 'trends' ||
queryInfo.visualization === 'funnel' ||
@@ -49,6 +52,7 @@ export const queryRunHandler: ToolBase<typeof schema, Result>['handler'] = async
{
query: queryInfo.innerQuery || query,
results: queryResult.data.results,
+ ...warningsField,
},
path
)
@@ -63,6 +67,7 @@ export const queryRunHandler: ToolBase<typeof schema, Result>['handler'] = async
columns: queryResult.data.columns || [],
results: queryResult.data.results || [],
},
+ ...warningsField,
},
path
)