: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
feat(data-warehouse): implement neon import source (#72737)
Daniel RC09f143d2ca63
diff --git a/products/data_warehouse/backend/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.pyindex 5bb202010d46..2dbe0a3c45a8 100644--- a/products/data_warehouse/backend/presentation/views/external_data_source.py+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py@@ -3549,13 +3549,20 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiand by the self-managed setup popup to verify user-created publications."""source_type = request.data.get("source_type")- if not source_type_supports_cdc(source_type):+ if not isinstance(source_type, str) or not source_type_supports_cdc(source_type):return Response(status=status.HTTP_400_BAD_REQUEST,data={"message": "CDC prerequisite checks are only supported for CDC enabled sources."},)- source_impl: PostgresSource = PostgresSource()+ # Dispatch to the actual source class so subclasses (Supabase, Neon) can run+ # their own pre-connection checks, e.g. rejecting pooled hosts for CDC.+ source_impl = SourceRegistry.get_source(ExternalDataSourceType(source_type))+ if not isinstance(source_impl, PostgresSource):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"CDC prerequisite checks are not supported for source type: {source_type}"},+ )is_valid, errors = source_impl.validate_config(request.data)if not is_valid:return Response(diff --git a/products/data_warehouse/frontend/shared/cdc.ts b/products/data_warehouse/frontend/shared/cdc.tsindex a660cdcf221b..c136596c003e 100644--- a/products/data_warehouse/frontend/shared/cdc.ts+++ b/products/data_warehouse/frontend/shared/cdc.ts@@ -1,4 +1,4 @@-// Source types that support change data capture (logical replication). Supabase is-// Postgres on the wire and reuses the same CDC path. Keep in sync with the backend+// Source types that support change data capture (logical replication). Supabase and Neon+// are Postgres on the wire and reuse the same CDC path. Keep in sync with the backend// adapter registry in products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py.-export const CDC_SOURCE_TYPES: string[] = ['Postgres', 'Supabase']+export const CDC_SOURCE_TYPES: string[] = ['Postgres', 'Supabase', 'Neon']diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.pyindex 21e8dcb0cb08..2744e8bf4774 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py@@ -142,11 +142,12 @@ class CDCSourceAdapter(Protocol[CDCConfigT_co]):def _cdc_adapters() -> dict[ExternalDataSourceType, CDCSourceAdapter[CDCConfig]]:"""Registry of CDC adapters keyed by source type. Adding a new CDC-capable sourceis a single entry here — everything else derives from this map."""- # Supabase is Postgres on the wire, so it reuses the Postgres adapter verbatim.+ # Supabase and Neon are Postgres on the wire, so they reuse the Postgres adapter verbatim.postgres_adapter = PostgresCDCAdapter()return {ExternalDataSourceType.POSTGRES: postgres_adapter,ExternalDataSourceType.SUPABASE: postgres_adapter,+ ExternalDataSourceType.NEON: postgres_adapter,}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex e05ca40807bf..7fe27035e342 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -374,6 +374,7 @@ the row lists both.| mysql | DB protocol | pymysql | ➖ || n8n | HTTP | requests | ✅ || nebius_ai | HTTP | requests | ✅ |+| neon | DB protocol | psycopg (delegates to PostgresSource) | ➖ || netlify | HTTP | requests | ✅ || new_relic | HTTP (GraphQL/NerdGraph) | requests | ✅ || new_york_times | HTTP | requests | ✅ |@@ -1103,7 +1104,6 @@ doesn't conflict with concurrent PRs.- nager_date- nasa- navan-- neon- neon_crm- netsuite- news_apidiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/neon.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/neon.pyindex 8e032f1f4928..bbde6290afa1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/neon.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/neon.py@@ -1,9 +1,17 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from products.warehouse_sources.backend.models.ssh_tunnel import SSHTunnelConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.common import config@config.configclass NeonSourceConfig(config.Config):- pass+ host: str+ database: str+ user: str+ password: str+ port: int = config.value(converter=int)+ connection_string: str | None = None+ schema: str | None = None+ ssh_tunnel: SSHTunnelConfig | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/neon/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/neon/source.pyindex 6017c201d5f4..ccf71768da87 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/neon/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/neon/source.py@@ -1,31 +1,121 @@-from typing import cast-from posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldFileUploadConfig,+ SourceFieldInputConfig,+ SourceFieldOauthAccountSelectConfig,+ SourceFieldOauthConfig,+ SourceFieldSelectConfig,+ SourceFieldSSHTunnelConfig,+ SourceFieldSwitchGroupConfig,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry-from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.neon import NeonSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.postgres import (+ PostgresSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import PostgresSourcefrom products.warehouse_sources.backend.types import ExternalDataSourceType+_SourceField = (+ SourceFieldInputConfig+ | SourceFieldSwitchGroupConfig+ | SourceFieldSelectConfig+ | SourceFieldOauthConfig+ | SourceFieldOauthAccountSelectConfig+ | SourceFieldFileUploadConfig+ | SourceFieldSSHTunnelConfig+)++_NEON_POOLED_HOST_CDC_ERROR = (+ "This is Neon's pooled endpoint, which doesn't support logical replication. For CDC, use the "+ "direct host instead — remove the '-pooler' suffix (e.g. "+ "ep-cool-darkness-123456.us-east-2.aws.neon.tech) — and make sure logical replication is "+ "enabled in your Neon project settings."+)+++def _is_neon_pooled_host(host: str) -> bool:+ bare = (host or "").strip().lower()+ return bare.endswith(".neon.tech") and bare.split(".", 1)[0].endswith("-pooler")+++_NEON_HOST_CAPTION = (+ "In the Neon Console, open your project and click **Connect** to see your connection "+ "details. Use the direct host, e.g. `ep-cool-darkness-123456.us-east-2.aws.neon.tech` — "+ "not the pooled host (the one with `-pooler`). Pooled connections work for standard "+ "syncs, but **change data capture (CDC)** requires the direct host, and you must enable "+ "**logical replication** in your Neon project settings first. Neon requires SSL, which "+ "PostHog uses by default."+)+@SourceRegistry.register-class NeonSource(SimpleSource[NeonSourceConfig]):+class NeonSource(PostgresSource):+ def __init__(self):+ super().__init__(source_name="Neon")+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.NEON+ @staticmethod+ def _adjust_field(field: _SourceField) -> _SourceField:+ if isinstance(field, SourceFieldInputConfig):+ if field.name == "connection_string":+ return field.model_copy(+ update={+ "placeholder": "postgresql://neondb_owner:[email protected]/neondb?sslmode=require"+ }+ )+ if field.name == "host":+ return field.model_copy(+ update={+ "placeholder": "ep-cool-darkness-123456.us-east-2.aws.neon.tech",+ "caption": _NEON_HOST_CAPTION,+ }+ )+ if field.name == "database":+ return field.model_copy(update={"placeholder": "neondb"})+ if field.name == "user":+ return field.model_copy(update={"placeholder": "neondb_owner"})+ return field+@propertydef get_source_config(self) -> SourceConfig:+ fields = [self._adjust_field(field) for field in super().get_source_config.fields]+return SourceConfig(name=SchemaExternalDataSourceType.NEON,category=DataWarehouseSourceCategory.DATABASES,keywords=["serverless postgres", "postgresql"],- label="Neon",iconPath="/static/services/neon.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ caption="Enter your Neon credentials to automatically pull your data into the PostHog Data warehouse",+ docsUrl="https://posthog.com/docs/cdp/sources/neon",+ fields=fields,+ releaseStatus=ReleaseStatus.ALPHA,+ )++ def check_cdc_prerequisites(+ self,+ config: PostgresSourceConfig,+ management_mode: str,+ tables: list[str],+ slot_name: str | None = None,+ publication_name: str | None = None,+ require_ssl: bool = True,+ ) -> list[str]:+ # The pooled endpoint accepts normal connections, so the generic checks would pass —+ # but logical replication doesn't work through it. Fail fast without connecting.+ if _is_neon_pooled_host(config.host or ""):+ return [_NEON_POOLED_HOST_CDC_ERROR]+ return super().check_cdc_prerequisites(+ config,+ management_mode=management_mode,+ tables=tables,+ slot_name=slot_name,+ publication_name=publication_name,+ require_ssl=require_ssl,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/neon/test_neon_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/neon/test_neon_source.pynew file mode 100644index 000000000000..36346f58d012--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/neon/test_neon_source.py@@ -0,0 +1,121 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.neon.source import NeonSource+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import PostgresSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _field(name: str) -> SourceFieldInputConfig:+ return next(+ field+ for field in NeonSource().get_source_config.fields+ if isinstance(field, SourceFieldInputConfig) and field.name == name+ )+++def test_neon_supports_cdc():+ from products.warehouse_sources.backend.temporal.data_imports.cdc.adapters import source_type_supports_cdc++ assert source_type_supports_cdc(ExternalDataSourceType.NEON)+++def test_neon_source_type_and_name():+ source = NeonSource()++ assert source.source_type == ExternalDataSourceType.NEON+ # source_name feeds the connection error messages ("Could not connect to Neon...").+ assert source.source_name == "Neon"+++def test_neon_schema_field_is_optional():+ # Multi-schema is supported (same as Postgres), so the schema field must not be required.+ schema_field = _field("schema")++ assert schema_field.required is False+ assert schema_field.label == "Schema"+++def test_neon_is_visible_and_alpha():+ config = NeonSource().get_source_config++ # A finished source must not be hidden behind unreleasedSource or a gating flag.+ assert not config.unreleasedSource+ assert config.featureFlag is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+++def test_neon_host_field_guides_to_the_direct_host():+ host_field = _field("host")++ assert "neon.tech" in host_field.placeholder+ assert host_field.caption is not None+ assert "-pooler" in host_field.caption+ assert "logical replication" in host_field.caption.lower()+++def test_neon_placeholders_match_neon_defaults():+ assert _field("database").placeholder == "neondb"+ assert _field("user").placeholder == "neondb_owner"+ assert "neon.tech" in _field("connection_string").placeholder+++def test_successful_connection_delegates_to_postgres():+ config = mock.MagicMock(host="ep-cool-darkness-123456.us-east-2.aws.neon.tech")++ with mock.patch.object(PostgresSource, "validate_credentials", return_value=(True, None)) as super_validate:+ success, error = NeonSource().validate_credentials(config, team_id=1)++ assert success is True+ assert error is None+ super_validate.assert_called_once()+++def test_connection_failure_uses_postgres_error():+ config = mock.MagicMock(host="ep-cool-darkness-123456.us-east-2.aws.neon.tech")++ with mock.patch.object(PostgresSource, "validate_credentials", return_value=(False, "postgres error")):+ success, error = NeonSource().validate_credentials(config, team_id=1)++ assert success is False+ assert error == "postgres error"+++ "host",+ [+ "ep-cool-darkness-123456-pooler.us-east-2.aws.neon.tech",+ " EP-COOL-DARKNESS-123456-POOLER.US-EAST-2.AWS.NEON.TECH ",+ ],+)+def test_cdc_prerequisites_reject_pooled_host_without_connecting(host):+ # The pooled endpoint accepts normal connections so the generic checks would pass,+ # but logical replication doesn't work through it — fail fast, no connection attempt.+ config = mock.MagicMock(host=host)++ with mock.patch.object(PostgresSource, "check_cdc_prerequisites") as super_check:+ errors = NeonSource().check_cdc_prerequisites(config, management_mode="posthog", tables=["users"])++ super_check.assert_not_called()+ assert len(errors) == 1+ assert "-pooler" in errors[0]+ assert "logical replication" in errors[0].lower()+++ "host",+ [+ "ep-cool-darkness-123456.us-east-2.aws.neon.tech",+ "my-pooler.example.com", # non-Neon host: '-pooler' label must not trigger the guard+ ],+)+def test_cdc_prerequisites_delegate_for_direct_hosts(host):+ config = mock.MagicMock(host=host)++ with mock.patch.object(PostgresSource, "check_cdc_prerequisites", return_value=[]) as super_check:+ errors = NeonSource().check_cdc_prerequisites(config, management_mode="posthog", tables=["users"])++ super_check.assert_called_once()+ assert errors == []