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(direct-query): better errors (#58803)

Marius Andra3489e6493da5
diff --git a/.agents/skills/using-kea-disposables/SKILL.md b/.agents/skills/using-kea-disposables/SKILL.md
index dc63ae197122..0983edababff 100644
--- a/.agents/skills/using-kea-disposables/SKILL.md
+++ b/.agents/skills/using-kea-disposables/SKILL.md
@@ -1,6 +1,6 @@
---
name: using-kea-disposables
-description: Use when adding timers (`setInterval`, `setTimeout`), event listeners (`window.addEventListener`, `document.addEventListener`, `MediaQueryList.addEventListener`), or any other resource that needs cleanup inside a kea logic. Every logic has `cache.disposables.add(setup, key?, options?)` and `cache.disposables.dispose(key)` available via the globally registered `disposablesPlugin` (`frontend/src/kea-disposables.ts`). Replaces the bare `cache.foo = setInterval(...)` + `beforeUnmount: clearInterval(cache.foo)` pattern and auto-pauses background work when the tab is hidden.
+description: 'Use when adding timers (`setInterval`, `setTimeout`), event listeners (`window.addEventListener`, `document.addEventListener`, `MediaQueryList.addEventListener`), or any other resource that needs cleanup inside a kea logic. Every logic has `cache.disposables.add(setup, key?, options?)` and `cache.disposables.dispose(key)` available via the globally registered `disposablesPlugin` (`frontend/src/kea-disposables.ts`). Replaces the bare `cache.foo = setInterval(...)` + `beforeUnmount: clearInterval(cache.foo)` pattern and auto-pauses background work when the tab is hidden.'
---
# Using kea disposables
diff --git a/frontend/src/lib/api.test.ts b/frontend/src/lib/api.test.ts
index c90021ed8efd..a617df64102c 100644
--- a/frontend/src/lib/api.test.ts
+++ b/frontend/src/lib/api.test.ts
@@ -1,6 +1,7 @@
import posthog from 'posthog-js'
import api, { ApiConfig, ApiRequest } from 'lib/api'
+import type { ApiError } from 'lib/api'
import { NodeKind } from '~/queries/schema/schema-general'
import { PropertyFilterType, PropertyOperator } from '~/types'
@@ -148,6 +149,24 @@ describe('API helper', () => {
})
})
+ it('uses response message as the ApiError message when no detail or error is present', async () => {
+ fakeFetch.mockResolvedValueOnce({
+ ok: false,
+ status: 400,
+ statusText: '',
+ headers: new Headers(),
+ json: () => Promise.resolve({ message: 'Could not fetch schemas from source.' }),
+ })
+
+ await expect(
+ api.create('/api/projects/2/external_data_sources/source-1/refresh_schemas/')
+ ).rejects.toMatchObject({
+ message: 'Could not fetch schemas from source.',
+ status: 400,
+ data: { message: 'Could not fetch schemas from source.' },
+ } satisfies Partial<ApiError>)
+ })
+
describe('organizationFeatureFlags', () => {
it('builds correct URL for organization feature flags', () => {
const apiRequest = new ApiRequest()
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 9ac2b03cadfb..cf03ebe231d2 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -7023,6 +7023,10 @@ async function handleFetch(url: string, method: string, fetcher: () => Promise<R
if (typeof data.detail === 'string') {
throw new ApiError(data.detail, response.status, response.headers, data)
}
+
+ if (typeof data.message === 'string') {
+ throw new ApiError(data.message, response.status, response.headers, data)
+ }
}
throw new ApiError(
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.py
index 05816aace925..7d4110d2069a 100644
--- a/products/data_warehouse/backend/api/external_data_source.py
+++ b/products/data_warehouse/backend/api/external_data_source.py
@@ -46,7 +46,7 @@ from posthog.models.user import User
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from posthog.rbac.user_access_control import UserAccessControlSerializerMixin
from posthog.temporal.data_imports.sources import SourceRegistry
-from posthog.temporal.data_imports.sources.common.base import ExternalWebhookInfo, FieldType, WebhookSource
+from posthog.temporal.data_imports.sources.common.base import AnySource, ExternalWebhookInfo, FieldType, WebhookSource
from posthog.temporal.data_imports.sources.common.config import Config
from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.postgres.cdc.config import PostgresCDCConfig
@@ -94,6 +94,53 @@ from products.revenue_analytics.backend.joins import ensure_person_join, remove_
logger = structlog.get_logger(__name__)
+REFRESH_SCHEMAS_FALLBACK_ERROR_MESSAGE = "Could not fetch schemas from source."
+
+REFRESH_SCHEMAS_EXPECTED_ERROR_MESSAGES = {
+ "timeout": "Connection timed out while fetching schemas from the source.",
+ "timed out": "Connection timed out while fetching schemas from the source.",
+ "connection refused": "Could not connect to the source. Check the host, port, and network access.",
+ "could not connect": "Could not connect to the source. Check the host, port, and network access.",
+ "could not translate host name": "Could not resolve the source host.",
+ "name or service not known": "Could not resolve the source host.",
+ "network is unreachable": "Could not reach the source network.",
+ "no route to host": "Could not reach the source host.",
+ "access denied": "Could not authenticate with the source. Check the connection credentials.",
+ "authentication failed": "Could not authenticate with the source. Check the connection credentials.",
+ "password authentication failed": "Could not authenticate with the source. Check the connection credentials.",
+ "unauthorized": "Could not authenticate with the source. Check the connection credentials.",
+ "forbidden": "The source credentials do not have permission to fetch schemas.",
+ "ssl/tls connection is required": "SSL/TLS is required to connect to the source.",
+ "could not establish session to ssh gateway": "Could not establish an SSH tunnel to the source.",
+}
+
+
+def _exception_text(error: Exception) -> str:
+ message = " ".join(str(arg) for arg in error.args if arg is not None) or str(error)
+ return f"{type(error).__name__}: {message}"
+
+
+def _classify_refresh_schemas_error(source: AnySource | None, error: Exception) -> tuple[str, bool]:
+ error_text = _exception_text(error)
+ normalized_error_text = error_text.lower()
+ matched_source_error = False
+
+ if source is not None:
+ for pattern, friendly_message in source.get_non_retryable_errors().items():
+ if pattern and pattern.lower() in normalized_error_text:
+ if friendly_message:
+ return friendly_message, True
+ matched_source_error = True
+
+ for pattern, friendly_message in REFRESH_SCHEMAS_EXPECTED_ERROR_MESSAGES.items():
+ if pattern in normalized_error_text:
+ return friendly_message, True
+
+ if matched_source_error:
+ return REFRESH_SCHEMAS_FALLBACK_ERROR_MESSAGE, True
+
+ return REFRESH_SCHEMAS_FALLBACK_ERROR_MESSAGE, False
+
def get_sensitive_field_names(fields: list[FieldType]) -> set[str]:
"""Extract field names that contain sensitive data from a source config's fields."""
@@ -1440,6 +1487,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
status=status.HTTP_400_BAD_REQUEST,
data={"message": "Source has no configuration."},
)
+ source: AnySource | None = None
try:
source_type = ExternalDataSourceType(instance.source_type)
source = SourceRegistry.get_source(source_type)
@@ -1466,10 +1514,29 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
schema_names=schema_names,
)
except Exception as e:
- logger.exception("Could not fetch schemas from source", exc_info=e)
+ error_message, is_expected_source_error = _classify_refresh_schemas_error(source, e)
+ logger.exception(
+ "Could not fetch schemas from source",
+ exc_info=e,
+ source_id=str(instance.id),
+ team_id=self.team_id,
+ source_type=instance.source_type,
+ error_type=type(e).__name__,
+ is_expected_source_error=is_expected_source_error,
+ )
+ if not is_expected_source_error:
+ capture_exception(
+ e,
+ {
+ "source_id": str(instance.id),
+ "source_type": instance.source_type,
+ "team_id": self.team_id,
+ "refresh_schemas": True,
+ },
+ )
return Response(
status=status.HTTP_400_BAD_REQUEST,
- data={"message": "Could not fetch schemas from source."},
+ data={"message": error_message},
)
descriptions = {s.name: s.description for s in schemas}
with transaction.atomic():
diff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.py
index 669ce6e3f8b0..90ebc3f96645 100644
--- a/products/data_warehouse/backend/api/test/test_external_data_source.py
+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py
@@ -1520,6 +1520,7 @@ class TestExternalDataSource(APIBaseTest):
@patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")
def test_refresh_schemas_returns_400_when_get_schemas_raises(self, mock_get_source):
mock_get_source.return_value.parse_config.return_value = None
+ mock_get_source.return_value.get_non_retryable_errors.return_value = {"Connection failed": None}
mock_get_source.return_value.get_schemas.side_effect = Exception("Connection failed")
source = self._create_external_data_source()
@@ -1530,6 +1531,52 @@ class TestExternalDataSource(APIBaseTest):
self.assertEqual(response.status_code, 400)
self.assertIn("Could not fetch schemas from source", response.json().get("message", ""))
+ @patch("products.data_warehouse.backend.api.external_data_source.capture_exception")
+ @patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")
+ def test_refresh_schemas_returns_specific_message_without_capture_for_expected_source_error(
+ self, mock_get_source, mock_capture_exception
+ ):
+ mock_get_source.return_value.parse_config.return_value = None
+ mock_get_source.return_value.get_non_retryable_errors.return_value = {"timeout": None}
+ mock_get_source.return_value.get_schemas.side_effect = TimeoutError("connection timed out")
+ source = self._create_external_data_source()
+
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/refresh_schemas/"
+ )
+
+ self.assertEqual(response.status_code, 400)
+ self.assertEqual(
+ response.json().get("message"),
+ "Connection timed out while fetching schemas from the source.",
+ )
+ mock_capture_exception.assert_not_called()
+
+ @patch("products.data_warehouse.backend.api.external_data_source.capture_exception")
+ @patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")
+ def test_refresh_schemas_captures_unexpected_source_error(self, mock_get_source, mock_capture_exception):
+ error = RuntimeError("schema parser exploded")
+ mock_get_source.return_value.parse_config.return_value = None
+ mock_get_source.return_value.get_non_retryable_errors.return_value = {}
+ mock_get_source.return_value.get_schemas.side_effect = error
+ source = self._create_external_data_source()
+
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/refresh_schemas/"
+ )
+
+ self.assertEqual(response.status_code, 400)
+ self.assertEqual(response.json().get("message"), "Could not fetch schemas from source.")
+ mock_capture_exception.assert_called_once_with(
+ error,
+ {
+ "source_id": str(source.id),
+ "source_type": source.source_type,
+ "team_id": self.team.pk,
+ "refresh_schemas": True,
+ },
+ )
+
@patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")
@patch("products.data_warehouse.backend.api.external_data_source.trigger_external_data_source_workflow")
def test_reload_direct_external_data_source_refreshes_schemas(self, mock_trigger, mock_get_source):