: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(managed-warehouse): deployment-aware bucket region + sslmode for EU (6/6) (#68790)
James Greenhill318811e50678
diff --git a/posthog/ducklake/common.py b/posthog/ducklake/common.pyindex 22e85f7e344d..2fa74b0ac3ca 100644--- a/posthog/ducklake/common.py+++ b/posthog/ducklake/common.py@@ -39,6 +39,30 @@ DATA_MODELING_DUCKGRES_SHADOW_SCHEMA_PREFIX = "shadow"logger = logging.getLogger(__name__)+# Managed-warehouse buckets live in the deployment's home region: us-east-1 for+# PostHog Cloud US, eu-central-1 for PostHog Cloud EU.+_BUCKET_REGION_BY_CLOUD_DEPLOYMENT: dict[str, str] = {+ "US": "us-east-1",+ "EU": "eu-central-1",+}+++def default_bucket_region() -> str:+ """Deployment-default S3 region for managed-warehouse buckets.++ Prefers the CLOUD_DEPLOYMENT Django setting, falling back to the same-named+ environment variable so CLI tools work without Django configured. us-east-1+ remains the default for US, dev, and self-hosted setups.+ """+ try:+ from django.conf import settings++ deployment = getattr(settings, "CLOUD_DEPLOYMENT", None)+ except Exception:+ deployment = os.environ.get("CLOUD_DEPLOYMENT")+ return _BUCKET_REGION_BY_CLOUD_DEPLOYMENT.get((deployment or "").upper(), "us-east-1")++DEFAULTS: dict[str, str] = {"DUCKLAKE_RDS_HOST": "localhost","DUCKLAKE_RDS_PORT": "5432",@@ -46,7 +70,9 @@ DEFAULTS: dict[str, str] = {"DUCKLAKE_RDS_USERNAME": "posthog","DUCKLAKE_RDS_PASSWORD": "posthog","DUCKLAKE_BUCKET": "ducklake-dev",- "DUCKLAKE_BUCKET_REGION": "us-east-1",+ # Frozen at import time: depends on the CLOUD_DEPLOYMENT env var being set before+ # process start (override_settings cannot affect it).+ "DUCKLAKE_BUCKET_REGION": default_bucket_region(),# Optional: S3 credentials for local dev (production uses IRSA)"DUCKLAKE_S3_ACCESS_KEY": "","DUCKLAKE_S3_SECRET_KEY": "",@@ -222,8 +248,11 @@ def upsert_duckgres_server_for_org(# Production code reads it from there (persisted on DuckgresServer.bucket, self-healed from# warehouse status) — it is never re-derived, because a local re-derivation drifted from the# Crossplane composition (UUID hyphen-compaction + the mw- env suffix) and named buckets-# that don't exist. The region is fixed for the single managed-warehouse deployment.-DUCKGRES_BUCKET_REGION = "us-east-1"+# that don't exist. The region follows the cloud deployment: each managed warehouse+# lives in its deployment's home region (see default_bucket_region).+# Frozen at import time: depends on the CLOUD_DEPLOYMENT env var being set before+# process start (override_settings cannot affect it).+DUCKGRES_BUCKET_REGION = default_bucket_region()def get_ducklake_connection_string(config: dict[str, str] | None = None) -> str:@@ -627,6 +656,7 @@ def get_team_backfill_state(team_id: int) -> dict[str, object]:__all__ = ["DucklingBackfillEnableError","attach_catalog",+ "default_bucket_region","duckgres_data_imports_schema","duckgres_data_imports_table_name","duckgres_data_modeling_schema",diff --git a/posthog/ducklake/storage.py b/posthog/ducklake/storage.pyindex 613b223ef764..7f2f8a4fe762 100644--- a/posthog/ducklake/storage.py+++ b/posthog/ducklake/storage.py@@ -27,6 +27,7 @@ import psycopgfrom posthog.ducklake.common import (_get_org_id_for_team,+ default_bucket_region,escape as ducklake_escape,get_config,get_org_config,@@ -186,7 +187,7 @@ class DuckLakeStorageConfig:access_key = config.get("DUCKLAKE_S3_ACCESS_KEY", "")secret_key = config.get("DUCKLAKE_S3_SECRET_KEY", "")- region = config.get("DUCKLAKE_BUCKET_REGION", "us-east-1")+ region = config.get("DUCKLAKE_BUCKET_REGION") or default_bucket_region()raw_endpoint = getattr(settings, "OBJECT_STORAGE_ENDPOINT", "") if settings else ""diff --git a/posthog/ducklake/test_common.py b/posthog/ducklake/test_common.pyindex 83766b437b5f..ee66098e3094 100644--- a/posthog/ducklake/test_common.py+++ b/posthog/ducklake/test_common.py@@ -1,11 +1,14 @@import pytestfrom unittest.mock import MagicMock, patch+from django.test import override_settings+import duckdbfrom parameterized import parameterizedfrom posthog.ducklake.common import (DucklingBackfillEnableError,+ default_bucket_region,enable_team_backfill,get_team_backfill_state,initialize_ducklake,@@ -143,6 +146,20 @@ class TestGetTeamBackfillState:assert get_team_backfill_state(team.id) == {"has_backfill": True, "table_suffix": "prod"}+class TestDefaultBucketRegion:+ @parameterized.expand(+ [+ ("unset", None, "us-east-1"),+ ("us", "US", "us-east-1"),+ ("eu", "EU", "eu-central-1"),+ ("dev", "DEV", "us-east-1"),+ ]+ )+ def test_region_follows_cloud_deployment(self, _name, deployment, expected):+ with override_settings(CLOUD_DEPLOYMENT=deployment):+ assert default_bucket_region() == expected++TEST_CONFIG = {"DUCKLAKE_RDS_HOST": "localhost","DUCKLAKE_RDS_PORT": "5432",diff --git a/posthog/ducklake/test_storage.py b/posthog/ducklake/test_storage.pyindex f33f41487a08..061de6c478ee 100644--- a/posthog/ducklake/test_storage.py+++ b/posthog/ducklake/test_storage.py@@ -1,5 +1,7 @@from unittest.mock import MagicMock, patch+from django.test import override_settings+from parameterized import parameterizedfrom posthog.ducklake.storage import (@@ -226,6 +228,30 @@ class TestDuckLakeStorageConfigProduction:assert "aws_secret_access_key" not in optionsassert "endpoint_url" not in options+ @parameterized.expand(+ [+ ("us_default", None, "us-east-1"),+ ("eu_deployment", "EU", "eu-central-1"),+ ]+ )+ def test_from_runtime_org_config_empty_region_falls_back_to_deployment_default(+ self, _name, cloud_deployment, expected_region+ ):+ # Mirrors DuckgresServer.to_catalog_public_config() when bucket_region is NULL+ org_config = {+ "DUCKLAKE_BUCKET_REGION": "",+ "DUCKLAKE_S3_ACCESS_KEY": "",+ "DUCKLAKE_S3_SECRET_KEY": "",+ }+ with (+ patch("posthog.ducklake.storage.get_org_config", return_value=org_config) as mock_get_org_config,+ override_settings(CLOUD_DEPLOYMENT=cloud_deployment),+ ):+ config = DuckLakeStorageConfig.from_runtime(use_local_setup=False, organization_id="org-123")++ mock_get_org_config.assert_called_once_with("org-123")+ assert config.region == expected_region+class TestDuckLakeStorageConfigEdgeCases:def test_empty_values_filtered_from_deltalake_options(self, monkeypatch):diff --git a/posthog/hogql/direct_sql/postgres_adapter.py b/posthog/hogql/direct_sql/postgres_adapter.pyindex 76ccac6d7214..8a81d7f94680 100644--- a/posthog/hogql/direct_sql/postgres_adapter.py+++ b/posthog/hogql/direct_sql/postgres_adapter.py@@ -97,6 +97,14 @@ def postgres_error_to_message(error: Exception) -> str:return message.splitlines()[0]+def is_postwh_host(host: str | None) -> bool:+ # Hostnames are case-insensitive and may carry a trailing root-zone dot, so+ # normalize before matching to keep the sslmode enforcement bypass-proof.+ if host is None:+ return False+ return host.lower().rstrip(".").endswith(".postwh.com")++def direct_postgres_session_setup_sql(schema: str | None,connection_metadata: dict[str, object] | None = None,@@ -106,7 +114,7 @@ def direct_postgres_session_setup_sql(database = connection_metadata.get("database") if isinstance(connection_metadata, dict) else Nonenormalized_schema = schema.strip() if isinstance(schema, str) and schema.strip() else None- if engine == "duckdb" or (host is not None and host.endswith(".postwh.com")):+ if engine == "duckdb" or is_postwh_host(host):if normalized_schema:quoted_schema = escape_postgres_identifier(normalized_schema)return f"USE {quoted_schema}"@@ -257,8 +265,9 @@ class PostgresAdapter:"sslkey": "/tmp/no.txt","sslrootcert": "/tmp/no.txt",}- if host.endswith(".us.postwh.com"):- # DuckLake hosts require SSL but do not use certificate-based auth.+ if is_postwh_host(host):+ # DuckLake hosts (any region: .us/.eu/.dev.postwh.com) require SSL+ # but do not use certificate-based auth.connection_kwargs["sslmode"] = "require"with psycopg.connect(**connection_kwargs) as connection:diff --git a/posthog/hogql/test/test_direct_postgres_query.py b/posthog/hogql/test/test_direct_postgres_query.pyindex ad9567eb9557..66bca16336cb 100644--- a/posthog/hogql/test/test_direct_postgres_query.py+++ b/posthog/hogql/test/test_direct_postgres_query.py@@ -84,9 +84,15 @@ class TestDirectPostgresQuery(APIBaseTest):"USE system",)- def test_direct_postgres_session_setup_sql_treats_postwh_hosts_as_duckdb(self):+ @parameterized.expand(+ [+ ("lowercase", "db.eu.postwh.com"),+ ("uppercase_trailing_dot", "DB.EU.POSTWH.COM."),+ ]+ )+ def test_direct_postgres_session_setup_sql_treats_postwh_hosts_as_duckdb(self, _name, host):self.assertEqual(- direct_postgres_session_setup_sql("posthog", host="db.eu.postwh.com"),+ direct_postgres_session_setup_sql("posthog", host=host),"USE posthog",)@@ -1679,9 +1685,16 @@ class TestDirectPostgresQuery(APIBaseTest):self.assertEqual(mock_connect.call_args.kwargs["sslmode"], "prefer")+ @parameterized.expand(+ [+ ("us", "db.us.postwh.com"),+ ("eu", "db.eu.postwh.com"),+ ("eu_uppercase_trailing_dot", "DB.EU.POSTWH.COM."),+ ]+ )@override_settings(DEBUG=False, TEST=False)@patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")- def test_execute_direct_postgres_query_adds_ssl_cert_paths_for_postwh_hosts(self, mock_connect):+ def test_execute_direct_postgres_query_adds_ssl_cert_paths_for_postwh_hosts(self, _name, host, mock_connect):source = ExternalDataSource.objects.create(team=self.team,source_id="source_id",@@ -1691,7 +1704,7 @@ class TestDirectPostgresQuery(APIBaseTest):access_method=ExternalDataSource.AccessMethod.DIRECT,prefix="ph3",job_inputs={- "host": "db.us.postwh.com",+ "host": host,"port": 5432,"database": "postgres","user": "postgres",diff --git a/products/data_warehouse/backend/presentation/views/managed_warehouse.py b/products/data_warehouse/backend/presentation/views/managed_warehouse.pyindex 3f134e300d48..5cb1ed30fe0c 100644--- a/products/data_warehouse/backend/presentation/views/managed_warehouse.py+++ b/products/data_warehouse/backend/presentation/views/managed_warehouse.py@@ -288,7 +288,7 @@ def _persist_duckgres_server(organization_id: UUID | str, database_name: str | Nthe row can be reconciled later from the warehouse status."""# Keep ducklake.common (and its duckdb dependency) off the API import path.- from posthog.ducklake.common import upsert_duckgres_server_for_org # noqa: PLC0415+ from posthog.ducklake.common import default_bucket_region, upsert_duckgres_server_for_org # noqa: PLC0415# The control plane is the single owner of the bucket name — it provisions# the bucket, pins the name on the Duckling CR's spec.dataStore.bucketName,@@ -298,9 +298,10 @@ def _persist_duckgres_server(organization_id: UUID | str, database_name: str | N# old to return it) leaves the column unset — upsert treats None as "leave# unset" — and status_for()'s self-heal fills it in on the next status read.bucket: str | None = body.get("bucket")- # Region from the response too when present, so a future CP outside us-east-1- # isn't silently mis-recorded; None when there's no bucket to region.- bucket_region: str | None = (body.get("bucket_region") or "us-east-1") if bucket else None+ # Region from the response too when present, so a CP outside this deployment's+ # home region isn't silently mis-recorded; the fallback is the deployment's own+ # managed-warehouse region. None when there's no bucket to region.+ bucket_region: str | None = (body.get("bucket_region") or default_bucket_region()) if bucket else Nonetry:connection = _present_connection({"database": database_name, "username": body.get("username", "root")})@@ -438,7 +439,10 @@ def _reconcile_bucket_from_status(organization_id: UUID | str, body: dict) -> No# External data stores / not-yet-backfilled ducklings report no bucket —# nothing authoritative to copy.return- bucket_region = body.get("bucket_region") or "us-east-1"+ # Keep ducklake.common (and its duckdb dependency) off the API import path.+ from posthog.ducklake.common import default_bucket_region # noqa: PLC0415++ bucket_region = body.get("bucket_region") or default_bucket_region()try:from posthog.ducklake.models import DuckgresServer # noqa: PLC0415diff --git a/products/data_warehouse/backend/tests/api/test_managed_warehouse.py b/products/data_warehouse/backend/tests/api/test_managed_warehouse.pyindex 2da5169ed0bd..80e5f22f3b7a 100644--- a/products/data_warehouse/backend/tests/api/test_managed_warehouse.py+++ b/products/data_warehouse/backend/tests/api/test_managed_warehouse.py@@ -5,6 +5,7 @@ from unittest.mock import MagicMock, patchfrom django.test import override_settings+from parameterized import parameterizedfrom rest_framework.response import Responsefrom posthog.ducklake.models import DuckgresServer, DuckgresServerTeam@@ -75,16 +76,23 @@ def test_provision_sends_default_team_id_to_control_plane(mock_request: MagicMocassert json_body["default_team_id"] == team.id+ [+ ("US", "posthog-duckling-0194d6405db400006cde48d6114c0f99-mw-prod-us", "us-east-1"),+ ("EU", "posthog-duckling-0194d6405db400006cde48d6114c0f99-mw-prod-eu", "eu-central-1"),+ ]+)@pytest.mark.django_db-@override_settings(CLOUD_DEPLOYMENT="US", DUCKGRES_PG_PORT=5432)@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")-def test_provision_persists_bucket_returned_by_control_plane(mock_request: MagicMock) -> None:+def test_provision_persists_bucket_returned_by_control_plane(+ deployment: str, cp_bucket: str, expected_region: str, mock_request: MagicMock+) -> None:# When the control plane returns the authoritative bucket name, persist it# verbatim instead of re-deriving — the CP owns the naming rule (it pins the# same name on the Duckling CR), and the local derivation has drifted from it.+ # A CP response without a region falls back to the deployment's home region.org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)- cp_bucket = "posthog-duckling-0194d6405db400006cde48d6114c0f99-mw-prod-us"mock_request.return_value = Response({"status": "provisioning started",@@ -96,13 +104,14 @@ def test_provision_persists_bucket_returned_by_control_plane(mock_request: Magicstatus=202,)- resp = managed_warehouse.provision(org.id, "my-warehouse", team.id, "events")+ with override_settings(CLOUD_DEPLOYMENT=deployment, DUCKGRES_PG_PORT=5432):+ resp = managed_warehouse.provision(org.id, "my-warehouse", team.id, "events")assert resp.status_code == 202server = DuckgresServer.objects.get(organization_id=org.id)# Verbatim, not the locally-derived f"posthog-duckling-{org.id}-prod-us".assert server.bucket == cp_bucket- assert server.bucket_region == "us-east-1"+ assert server.bucket_region == expected_region@pytest.mark.django_db@@ -131,9 +140,9 @@ def test_provision_enables_backfill_for_calling_team_only(mock_request: MagicMoc@pytest.mark.django_db@override_settings(CLOUD_DEPLOYMENT="EU", DUCKGRES_PG_PORT=5432)@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")-def test_provision_persists_server_without_bucket_when_region_unsupported(mock_request: MagicMock) -> None:- # EU has no managed-warehouse bucket convention, so bucket derivation raises. The- # connection row (with the one-time password) must still be persisted.+def test_provision_on_eu_deployment_persists_eu_host(mock_request: MagicMock) -> None:+ # An EU deployment must present the eu.postwh.com zone in the persisted connection.+ # A CP response without a bucket leaves the column unset here too.org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)mock_request.return_value = Response(@@ -145,6 +154,7 @@ def test_provision_persists_server_without_bucket_when_region_unsupported(mock_rassert resp.status_code == 202server = DuckgresServer.objects.get(organization_id=org.id)+ assert server.host == "my-warehouse.dw.eu.postwh.com"assert server.password == "secret"assert server.bucket is None@@ -164,6 +174,7 @@ def test_provision_does_not_persist_on_failure(mock_request: MagicMock) -> None:@pytest.mark.django_db+@override_settings(CLOUD_DEPLOYMENT="US")@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")def test_status_for_self_heals_stale_bucket(mock_request: MagicMock) -> None:# A row with a stale (locally-derived) bucket converges to the CP-reported