: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): save a source with a warning when the API cannot reach it (#113808)
Daniel RCe4a77c3d3d48
diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 2961ff7b39ef..269144aca17e 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -6521,6 +6521,7 @@ export interface ExternalDataSource {supports_column_selection?: booleanapi_version?: string | nullapi_version_deprecation?: ExternalDataSourceApiVersionDeprecation | null+ connection_warning?: string | null}export interface ExternalDataSourceApiVersionDeprecation {diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/dataWarehouseSourceSettingsLogic.test.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/dataWarehouseSourceSettingsLogic.test.tsindex 26f0bc9786e6..9d2433cd309c 100644--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/dataWarehouseSourceSettingsLogic.test.ts+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/dataWarehouseSourceSettingsLogic.test.ts@@ -1,6 +1,7 @@import { expectLogic } from 'kea-test-utils'import api from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'@@ -286,6 +287,30 @@ describe('sourceSettingsLogic', () => {])})+ it.each([+ { case: 'a warning toast', connection_warning: 'Source saved, but the connection check failed.', warnings: 1 },+ { case: 'the success toast', connection_warning: null, warnings: 0 },+ ])(+ 'shows $case after a save, from the connection warning in the response',+ async ({ connection_warning, warnings }) => {+ const source = { ...makeSource([makeSchema()]), connection_warning }+ jest.spyOn(api.externalDataSources, 'update').mockResolvedValue(source)+ const warningToastSpy = jest.spyOn(lemonToast, 'warning')+ const successToastSpy = jest.spyOn(lemonToast, 'success')++ logic = sourceSettingsLogic({ id: 'source-1' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ await expectLogic(logic, () => {+ logic.actions.submitSourceConfig()+ }).toDispatchActions(['submitSourceConfigSuccess'])++ expect(warningToastSpy).toHaveBeenCalledTimes(warnings)+ expect(successToastSpy).toHaveBeenCalledTimes(1 - warnings)+ }+ )+it('keys the logic by source id', () => {expect(sourceSettingsLogic({ id: 'source-1' }).key).toEqual('source-1')})diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.tsindex f1b192c58664..0ab23f219207 100644--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts@@ -1146,7 +1146,12 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([})actions.loadSource()captureSaveOutcome('success')- lemonToast.success('Source updated')+ const connectionWarning = sourcesDataLogic.values.lastUpdateConnectionWarning+ if (connectionWarning) {+ lemonToast.warning(connectionWarning)+ } else {+ lemonToast.success('Source updated')+ }if (nextLookbackDays > previousLookbackDays && schemasToResync.length > 0) {LemonDialog.open({diff --git a/products/data_warehouse/frontend/shared/logics/sourcesDataLogic.ts b/products/data_warehouse/frontend/shared/logics/sourcesDataLogic.tsindex e4bb908424c8..2c07e5bc8440 100644--- a/products/data_warehouse/frontend/shared/logics/sourcesDataLogic.ts+++ b/products/data_warehouse/frontend/shared/logics/sourcesDataLogic.ts@@ -9,6 +9,7 @@ import { ExternalDataSource, ExternalDataSourceRevenueAnalyticsConfig } from '~/export interface sourcesDataLogicValues {dataWarehouseSources: PaginatedResponse<ExternalDataSource> | nulldataWarehouseSourcesLoading: boolean+ lastUpdateConnectionWarning: string | null}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -51,6 +52,9 @@ export interface sourcesDataLogicActions {value: true}}+ setLastUpdateConnectionWarning: (warning: string | null) => {+ warning: string | null+ }updateSource: (source: ExternalDataSource) => ExternalDataSourceupdateSourceFailure: (error: string,@@ -121,6 +125,7 @@ export const sourcesDataLogic = kea<sourcesDataLogicType>([actions({abortAnyRunningQuery: true,loadSources: true,+ setLastUpdateConnectionWarning: (warning: string | null) => ({ warning }),}),loaders(({ cache, values, actions }) => ({dataWarehouseSources: [@@ -173,6 +178,7 @@ export const sourcesDataLogic = kea<sourcesDataLogicType>([},updateSource: async (source: ExternalDataSource) => {const updatedSource = await api.externalDataSources.update(source.id, source)+ actions.setLastUpdateConnectionWarning(updatedSource.connection_warning ?? null)return {...values.dataWarehouseSources,results:@@ -201,6 +207,12 @@ export const sourcesDataLogic = kea<sourcesDataLogicType>([],})),reducers(({ cache }) => ({+ lastUpdateConnectionWarning: [+ null as string | null,+ {+ setLastUpdateConnectionWarning: (_, { warning }) => warning,+ },+ ],dataWarehouseSourcesLoading: [false as boolean,{diff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.pyindex 00574d30a6a6..9d7255a86692 100644--- a/products/warehouse_sources/backend/facade/source_management.py+++ b/products/warehouse_sources/backend/facade/source_management.py@@ -47,6 +47,7 @@ _LAZY = {"CredentialAccountsMixin": "sources.common.mixins","DATABASE_HOST_NOT_ALLOWED_GUIDANCE": "sources.common.mixins","HostNotAllowedError": "sources.common.mixins",+ "is_team_allowlisted_for_internal_hosts": "sources.common.mixins","OAuthMixin": "sources.common.mixins","pinned_host_kwargs": "sources.common.mixins","TemporaryHostResolutionError": "sources.common.mixins",diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py b/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.pyindex bc3122efc15b..e37b4037d84b 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py@@ -50,6 +50,11 @@ INVALID_CREDENTIALS_FALLBACK_MESSAGE = ("We couldn't validate those credentials. Check they're correct and have the required access, then try again.")+UNVERIFIED_CONNECTION_WARNING = (+ "Source saved, but the API could not reach the database. Syncs and live queries connect "+ "from other services and can still work. Details: {error}"+)+def _source_unavailable_message(source_type: str) -> str:# A source with no schema discovery is an unreleased scaffold the UI normally hides. Tell thediff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.pyindex 0606340f85e6..3658d339ddc0 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py@@ -69,6 +69,7 @@ from products.warehouse_sources.backend.facade.source_management import (fetch_docs_text,filter_dwh_columns_by_enabled_columns,get_cdc_adapter,+ is_team_allowlisted_for_internal_hosts,new_source_requires_ssl,sql_schema_metadata,validate_and_coerce_row_filters,@@ -181,6 +182,13 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer"null otherwise. Drives the in-product deprecation warning."),)+ connection_warning = serializers.SerializerMethodField(+ read_only=True,+ help_text=(+ "Set on an update response when the change was saved but the connection check from the "+ "API could not reach the database. Null otherwise."+ ),+ )class Meta:model = ExternalDataSource@@ -210,6 +218,7 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer"supports_column_selection","api_version","api_version_deprecation",+ "connection_warning",]read_only_fields = ["id",@@ -228,6 +237,7 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer"supports_column_selection","api_version","api_version_deprecation",+ "connection_warning",]def to_representation(self, instance):@@ -291,6 +301,10 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializerdef get_api_version_deprecation(self, instance: ExternalDataSource) -> dict[str, Any] | None:return api_version_deprecation_payload(instance.source_type, instance.api_version)+ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_connection_warning(self, instance: ExternalDataSource) -> str | None:+ return getattr(instance, "_connection_warning", None)+def _prefetched_schemas(self, instance: ExternalDataSource) -> list[ExternalDataSchema] | None:prefetched = getattr(instance, "_prefetched_objects_cache", {}).get("schemas")if prefetched is None:@@ -411,6 +425,7 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializersensitive_fields = helpers.get_sensitive_field_names(source.get_source_config.fields)declared_field_names = helpers.get_declared_field_names(source.get_source_config.fields)discovered_schemas: list[SourceSchema] | None = None+ connection_warning: str | None = Nonenew_job_inputs = {**existing_job_inputs, **incoming_job_inputs}@@ -642,7 +657,18 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializersource, instance.team_id, e)if not credentials_valid:- raise ValidationError(credentials_error or helpers.INVALID_CREDENTIALS_FALLBACK_MESSAGE)+ credentials_error = credentials_error or helpers.INVALID_CREDENTIALS_FALLBACK_MESSAGE+ # These teams use internal hosts that the API cannot always reach, while the+ # workers that sync and run live queries can. Only an unreachable host qualifies,+ # so rejected credentials and rejected configs still block the save. A direct+ # query source still needs the probe, because the same call discovers its schemas.+ if (+ instance.is_direct_query+ or not is_team_allowlisted_for_internal_hosts(instance.team_id)+ or not source.is_unreachable_validation_error(credentials_error)+ ):+ raise ValidationError(credentials_error)+ connection_warning = helpers.UNVERIFIED_CONNECTION_WARNING.format(error=credentials_error)if instance.is_direct_query:discovered_schemas = source.get_schemas(source_config, instance.team_id, api_version=effective_api_version@@ -673,6 +699,7 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializerold_namespaced_resources = namespaced_adapter.resources_for_job_inputs(existing_job_inputs)updated_source: ExternalDataSource = super().update(instance, validated_data)+ cast(Any, updated_source)._connection_warning = connection_warningif namespaced_adapter is not None and job_inputs_were_submitted:# Adds schema rows for added resources, retires removed ones, and reconciles theirdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.pyindex 92e6e303bd0d..9046f919a99a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py@@ -439,6 +439,14 @@ class _BaseSource(ABC, Generic[ConfigType]):a differently named field (e.g. Okta's ``okta_domain``) should list it here."""return []+ def is_unreachable_validation_error(self, error: str) -> bool:+ """Whether a ``validate_credentials`` message means only that the host could not be reached+ over the network. The update serializer may then save the change with a warning for a team+ that uses internal hosts, because the API can lack a network path that the workers have. A+ message that reports rejected credentials or a rejected config must return ``False``.+ Default: no message qualifies."""+ return False+def server_managed_job_input_fields(self, incoming_job_inputs: dict[str, Any], existing_job_inputs: dict[str, Any]) -> list[str]:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.pyindex 76a250b784fa..bde0124a2d90 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py@@ -163,6 +163,8 @@ _HOST_UNREACHABLE_VALIDATION_ERROR = ("correct, and that PostHog's IP addresses are allowed through your firewall.")+_CONNECT_TIMEOUT_VALIDATION_ERROR = "Connection timed out. Check that your database is reachable from the public internet and that PostHog's egress IP addresses are allowed through your firewall (see the docs). For a database that can't be exposed publicly, use the SSH tunnel option."+PostgresErrors = {"password authentication failed for user": _INVALID_CREDENTIALS_VALIDATION_ERROR,# A proxy/pooler in front of some providers rejects bad credentials during its own@@ -285,7 +287,7 @@ PostgresErrors = {"No route to host": _HOST_UNREACHABLE_ERROR,"Is the server running on that host and accepting TCP/IP connections": _HOST_UNREACHABLE_VALIDATION_ERROR,'database "': "The database named in your connection details doesn't exist on this server. Check the database name is correct and try again.",- "timeout expired": "Connection timed out. Check that your database is reachable from the public internet and that PostHog's egress IP addresses are allowed through your firewall (see the docs). For a database that can't be exposed publicly, use the SSH tunnel option.",+ "timeout expired": _CONNECT_TIMEOUT_VALIDATION_ERROR,"the database system is starting up": "Your database is starting up or recovering. Wait a moment and try again.","SSL/TLS connection is required": "SSL/TLS connection is required but your database does not support it. Please enable SSL/TLS on your PostgreSQL server.","server does not support SSL, but SSL was required": "SSL/TLS connection is required but your database does not support it. Please enable SSL/TLS on your PostgreSQL server.",@@ -480,6 +482,13 @@ class PostgresSource(def get_implementation(self) -> PostgresImplementation:return _POSTGRES_IMPLEMENTATION+ def is_unreachable_validation_error(self, error: str) -> bool:+ return error in (+ _CONNECT_TIMEOUT_VALIDATION_ERROR,+ _HOST_UNREACHABLE_ERROR,+ _HOST_UNREACHABLE_VALIDATION_ERROR,+ )+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.POSTGRESdiff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.pyindex b362edfd7ed8..57585b4e8797 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py@@ -110,7 +110,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.pPostgresDiscoveredSchema,SSLRequiredError,)-from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import PostgresSource+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import (+ _CONNECT_TIMEOUT_VALIDATION_ERROR,+ PostgresSource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.reddit_ads.reddit_ads import RedditAdsApiErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.stripe.constants import (BALANCE_TRANSACTION_RESOURCE_NAME as STRIPE_BALANCE_TRANSACTION_RESOURCE_NAME,@@ -3313,6 +3316,7 @@ class TestExternalDataSource(APIBaseTest):"supports_column_selection","api_version","api_version_deprecation",+ "connection_warning",],)self.assertIsNone(payload["engine"])@@ -6774,6 +6778,56 @@ class TestExternalDataSource(APIBaseTest):assert source.job_inputs["password"] == "new_password"mock_validate_credentials.assert_called_once()+ @parameterized.expand(+ [+ ("internal_host_team_saves_with_warning", True, _CONNECT_TIMEOUT_VALIDATION_ERROR, 200),+ ("other_team_is_rejected", False, _CONNECT_TIMEOUT_VALIDATION_ERROR, 400),+ ("internal_host_team_with_rejected_credentials_is_rejected", True, "Invalid password.", 400),+ ]+ )+ def test_update_with_failed_connection_probe(self, _name, allowlisted, probe_error, expected_status):+ source = ExternalDataSource.objects.create(+ team_id=self.team.pk,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ source_type="Postgres",+ created_by=self.user,+ prefix="test_failed_probe",+ job_inputs={+ "source_type": "Postgres",+ "host": "db.example.com",+ "port": "5432",+ "database": "mydb",+ "user": "dbuser",+ "password": "original_password",+ "schema": "public",+ },+ )++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.validate_credentials",+ return_value=(False, probe_error),+ ),+ patch(+ "products.warehouse_sources.backend.presentation.views.external_data_source.source_setup.is_team_allowlisted_for_internal_hosts",+ return_value=allowlisted,+ ),+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={"job_inputs": {"host": "new-host.example.com", "password": "new_password"}},+ )++ assert response.status_code == expected_status, response.json()+ source.refresh_from_db()+ if expected_status == 200:+ assert source.job_inputs["host"] == "new-host.example.com"+ assert probe_error in response.json()["connection_warning"]+ else:+ assert source.job_inputs["host"] == "db.example.com"+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.kafka.source.KafkaSource.validate_credentials",return_value=(True, None),diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.tsindex b8fd8680d2a6..7a29eac74e04 100644--- a/products/warehouse_sources/frontend/generated/api.schemas.ts+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts@@ -3542,6 +3542,11 @@ export interface ExternalDataSourceSerializersApi {readonly api_version: string | null/** Set when the vendor has deprecated the API version this source is pinned to; null otherwise. Drives the in-product deprecation warning. */readonly api_version_deprecation: ExternalDataSourceApiVersionDeprecationApi | null+ /**+ * Set on an update response when the change was saved but the connection check from the API could not reach the database. Null otherwise.+ * @nullable+ */+ readonly connection_warning: string | null}export interface PaginatedExternalDataSourceSerializersListApi {@@ -5062,6 +5067,11 @@ export interface PatchedExternalDataSourceSerializersApi {readonly api_version?: string | null/** Set when the vendor has deprecated the API version this source is pinned to; null otherwise. Drives the in-product deprecation warning. */readonly api_version_deprecation?: ExternalDataSourceApiVersionDeprecationApi | null+ /**+ * Set on an update response when the change was saved but the connection check from the API could not reach the database. Null otherwise.+ * @nullable+ */+ readonly connection_warning?: string | null}export type ExternalDataSourceBulkUpdateSchemaApiRowFiltersItem = {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e1b08aa39374..cd6ebddd8e1a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -49784,6 +49784,11 @@ export namespace Schemas {readonly api_version: string | null;/** Set when the vendor has deprecated the API version this source is pinned to; null otherwise. Drives the in-product deprecation warning. */readonly api_version_deprecation: ExternalDataSourceApiVersionDeprecation | null;+ /**+ * Set on an update response when the change was saved but the connection check from the API could not reach the database. Null otherwise.+ * @nullable+ */+ readonly connection_warning: string | null;}export type ExternalQueryErrorCode = typeof ExternalQueryErrorCode[keyof typeof ExternalQueryErrorCode];@@ -78718,6 +78723,11 @@ export namespace Schemas {readonly api_version?: string | null;/** Set when the vendor has deprecated the API version this source is pinned to; null otherwise. Drives the in-product deprecation warning. */readonly api_version_deprecation?: ExternalDataSourceApiVersionDeprecation | null;+ /**+ * Set on an update response when the change was saved but the connection check from the API could not reach the database. Null otherwise.+ * @nullable+ */+ readonly connection_warning?: string | null;}export interface PatchedFeatureFlagPartialUpdateRequestSchema {