: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): persist the duckling bucket name the control plane returns (#65209)
Benjamin Knofe-Vider9315c423f582
diff --git a/posthog/admin/admins/duckgres_server_admin.py b/posthog/admin/admins/duckgres_server_admin.pyindex 3914a711f3eb..56bf20be4f34 100644--- a/posthog/admin/admins/duckgres_server_admin.py+++ b/posthog/admin/admins/duckgres_server_admin.py@@ -13,11 +13,15 @@ class DuckgresServerAdmin(admin.ModelAdmin):"port","flight_port","database",+ "bucket","created_at","updated_at",)- search_fields = ("=team__id", "=organization__id", "host")- readonly_fields = ("id", "created_at", "updated_at")+ search_fields = ("=team__id", "=organization__id", "host", "bucket")+ # bucket / bucket_region are control-plane-owned: provisioning persists them+ # and status_for() self-heals them on every read, so a manual admin edit+ # would just be overwritten. Show them, but read-only.+ readonly_fields = ("id", "created_at", "updated_at", "bucket", "bucket_region")raw_id_fields = ("team", "organization")fieldsets = (@@ -33,6 +37,16 @@ class DuckgresServerAdmin(admin.ModelAdmin):"fields": ("host", "port", "flight_port", "database", "username", "password"),},),+ (+ "Storage",+ {+ # The duckling's per-org S3 bucket. Control-plane-owned and+ # read-only: provisioning persists it and status_for() self-heals+ # it from the warehouse status, so it's shown for reference but not+ # editable here.+ "fields": ("bucket", "bucket_region"),+ },+ ),("Metadata",{diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.pyindex 215c910bd409..4cf6f60d14d3 100644--- a/posthog/dags/events_backfill_to_duckling.py+++ b/posthog/dags/events_backfill_to_duckling.py@@ -69,8 +69,8 @@ from posthog.cloud_utils import is_cloudfrom posthog.dags.common import JobOwners, dagster_tags, settings_with_log_commentfrom posthog.ducklake.client import make_duckgres_conninfofrom posthog.ducklake.common import (+ DUCKGRES_BUCKET_REGION,_get_org_id_for_team,- derive_duckling_bucket,get_duckgres_server_for_organization,get_ducklake_catalog_for_organization,)@@ -180,8 +180,8 @@ class DucklingTarget:Built once per run from the team's organization id. The duckgres connection is driven bymake_duckgres_conninfo (duckgres owns catalog attachment on the connection); the S3 bucket- is read from the org's stored DuckLakeCatalog row — the provisioning source of truth — and- only falls back to deterministic derivation when no catalog row exists (e.g. dev mode).+ is resolved by _resolve_duckling_target (DuckLakeCatalog → control plane → stored+ DuckgresServer fallback). The control plane is the authoritative owner of the bucket name."""team_id: int@@ -194,11 +194,26 @@ def _resolve_duckling_target(team_id: int) -> DucklingTarget:"""Resolve the per-org duckling target for a backfill partition.The organization id (team → org) drives both the connection (make_duckgres_conninfo- resolves the duckgres server itself) and the S3 bucket. The bucket name is read from a- stored source of truth — the org's DuckLakeCatalog (hand-entered, older orgs) or its- DuckgresServer (written at provision time, newer orgs) — and only falls back to the- deterministic derivation when neither carries one (e.g. dev mode).+ resolves the duckgres server itself) and the S3 bucket.++ Bucket resolution order:+ 1. The org's DuckLakeCatalog row (hand-entered, older orgs that predate the control+ plane and have no CP-owned bucket to ask about).+ 2. The control plane — the single owner of the duckling bucket name. It is consulted+ BEFORE the stored DuckgresServer row on purpose: a row provisioned before the+ naming fix carries a stale, locally-derived bucket that names an object store+ that doesn't exist, and that stale value must not win. cp_bucket_for() also+ reconciles the row so it converges for next time.+ 3. The stored DuckgresServer.bucket, only as a fallback when the control plane is+ unreachable/unconfigured — so a transient CP outage doesn't fail a run whose+ bucket is already known-good.++ The bucket name is never re-derived locally — that derivation drifted from the+ Crossplane composition and produced buckets that don't exist. Fail loudly if nothing+ can name it rather than export to a guessed bucket."""+ from products.data_warehouse.backend.api import managed_warehouse # noqa: PLC0415+org_id = _get_org_id_for_team(team_id)catalog = get_ducklake_catalog_for_organization(org_id)@@ -206,22 +221,35 @@ def _resolve_duckling_target(team_id: int) -> DucklingTarget:bucket, bucket_region = catalog.bucket, catalog.bucket_regionreturn DucklingTarget(team_id=team_id, organization_id=org_id, bucket=bucket, bucket_region=bucket_region)+ # Control plane first — authoritative, and rejects an org_id-mismatched status body.+ cp_bucket = managed_warehouse.cp_bucket_for(org_id)+ if cp_bucket:+ logger.info(+ "duckling_bucket_resolved_from_control_plane",+ team_id=team_id,+ organization_id=org_id,+ bucket=cp_bucket,+ )+ return DucklingTarget(+ team_id=team_id, organization_id=org_id, bucket=cp_bucket, bucket_region=DUCKGRES_BUCKET_REGION+ )++ # CP couldn't answer — fall back to the stored row if it knows a bucket.server = get_duckgres_server_for_organization(org_id)if server is not None and server.bucket:- bucket, bucket_region = server.bucket, server.bucket_region+ bucket, bucket_region = server.bucket, server.bucket_region or DUCKGRES_BUCKET_REGION+ logger.warning(+ "duckling_bucket_from_stored_server_control_plane_unavailable",+ team_id=team_id,+ organization_id=org_id,+ bucket=bucket,+ )return DucklingTarget(team_id=team_id, organization_id=org_id, bucket=bucket, bucket_region=bucket_region)- # No stored bucket anywhere (dev mode, or a pre-existing row from before the bucket was- # persisted): the derived name is an unverified guess at the provisioned bucket. Log it- # so the "bucket does not exist" failure mode is observable rather than silent.- bucket, bucket_region = derive_duckling_bucket(org_id)- logger.warning(- "duckling_bucket_derived_no_stored_source",- team_id=team_id,- organization_id=org_id,- bucket=bucket,+ raise ValueError(+ f"No S3 bucket resolvable for org {org_id}: absent from DuckLakeCatalog, the control "+ f"plane warehouse status named none, and no stored DuckgresServer bucket to fall back to.")- return DucklingTarget(team_id=team_id, organization_id=org_id, bucket=bucket, bucket_region=bucket_region)@retry(@@ -1812,7 +1840,7 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBac)# Resolve the duckling target: org id (team → org) drives both the connection and the- # S3 bucket, derived deterministically (mirrors the duckgres Crossplane composition).+ # S3 bucket (the control plane is the authoritative source of the bucket name).target = _resolve_duckling_target(team_id)context.log.info(f"Backfill ready for team_id={team_id}: org={target.organization_id}, bucket={target.bucket}")@@ -1993,7 +2021,7 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa)# Resolve the duckling target: org id (team → org) drives both the connection and the- # S3 bucket, derived deterministically (mirrors the duckgres Crossplane composition).+ # S3 bucket (the control plane is the authoritative source of the bucket name).target = _resolve_duckling_target(team_id)context.log.info(f"Backfill ready for team_id={team_id}: org={target.organization_id}, bucket={target.bucket}")diff --git a/posthog/dags/test_events_backfill_to_duckling.py b/posthog/dags/test_events_backfill_to_duckling.pyindex 752e73131fe0..7b5f76b79a00 100644--- a/posthog/dags/test_events_backfill_to_duckling.py+++ b/posthog/dags/test_events_backfill_to_duckling.py@@ -69,14 +69,81 @@ class TestDucklingBackfillAlertRouting:class TestResolveDucklingTarget:- @patch("posthog.dags.events_backfill_to_duckling.derive_duckling_bucket", return_value=("bkt", "us-west-2"))+ @patch("posthog.dags.events_backfill_to_duckling.get_duckgres_server_for_organization", return_value=None)+ @patch("posthog.dags.events_backfill_to_duckling.get_ducklake_catalog_for_organization", return_value=None)@patch("posthog.dags.events_backfill_to_duckling._get_org_id_for_team", return_value="org-1")- def test_builds_target_from_org_and_derived_bucket(self, mock_org: MagicMock, mock_derive: MagicMock):- target = _resolve_duckling_target(7)-- assert target == DucklingTarget(team_id=7, organization_id="org-1", bucket="bkt", bucket_region="us-west-2")+ def test_resolves_bucket_from_control_plane(+ self, mock_org: MagicMock, _mock_catalog: MagicMock, _mock_server: MagicMock+ ):+ # The control plane is the authoritative owner of the bucket name.+ with patch(+ "products.data_warehouse.backend.api.managed_warehouse.cp_bucket_for",+ return_value="posthog-duckling-org-1-mw-prod-us",+ ) as mock_cp:+ target = _resolve_duckling_target(7)++ assert target == DucklingTarget(+ team_id=7,+ organization_id="org-1",+ bucket="posthog-duckling-org-1-mw-prod-us",+ bucket_region="us-east-1",+ )mock_org.assert_called_once_with(7)- mock_derive.assert_called_once_with("org-1")+ mock_cp.assert_called_once_with("org-1")++ @patch("posthog.dags.events_backfill_to_duckling.get_ducklake_catalog_for_organization", return_value=None)+ @patch("posthog.dags.events_backfill_to_duckling._get_org_id_for_team", return_value="org-1")+ def test_control_plane_wins_over_stale_stored_server_bucket(self, _mock_org: MagicMock, _mock_catalog: MagicMock):+ # A row provisioned before the naming fix carries a stale bucket; the CP value+ # must win so the backfill never exports to a bucket that doesn't exist.+ server = MagicMock(bucket="posthog-duckling-stale-prod-us", bucket_region="us-east-1")+ with (+ patch(+ "posthog.dags.events_backfill_to_duckling.get_duckgres_server_for_organization",+ return_value=server,+ ),+ patch(+ "products.data_warehouse.backend.api.managed_warehouse.cp_bucket_for",+ return_value="posthog-duckling-org-1-mw-prod-us",+ ),+ ):+ target = _resolve_duckling_target(7)++ assert target.bucket == "posthog-duckling-org-1-mw-prod-us"++ @patch("posthog.dags.events_backfill_to_duckling.get_ducklake_catalog_for_organization", return_value=None)+ @patch("posthog.dags.events_backfill_to_duckling._get_org_id_for_team", return_value="org-1")+ def test_falls_back_to_stored_server_when_control_plane_unavailable(+ self, _mock_org: MagicMock, _mock_catalog: MagicMock+ ):+ # CP can't answer → use the known-good stored row rather than failing the run.+ server = MagicMock(bucket="posthog-duckling-org-1-mw-prod-us", bucket_region="us-east-1")+ with (+ patch(+ "posthog.dags.events_backfill_to_duckling.get_duckgres_server_for_organization",+ return_value=server,+ ),+ patch(+ "products.data_warehouse.backend.api.managed_warehouse.cp_bucket_for",+ return_value=None,+ ),+ ):+ target = _resolve_duckling_target(7)++ assert target.bucket == "posthog-duckling-org-1-mw-prod-us"++ @patch("posthog.dags.events_backfill_to_duckling.get_duckgres_server_for_organization", return_value=None)+ @patch("posthog.dags.events_backfill_to_duckling.get_ducklake_catalog_for_organization", return_value=None)+ @patch("posthog.dags.events_backfill_to_duckling._get_org_id_for_team", return_value="org-1")+ def test_raises_when_nothing_can_name_the_bucket(+ self, _mock_org: MagicMock, _mock_catalog: MagicMock, _mock_server: MagicMock+ ):+ with patch(+ "products.data_warehouse.backend.api.managed_warehouse.cp_bucket_for",+ return_value=None,+ ):+ with pytest.raises(ValueError, match="No S3 bucket resolvable"):+ _resolve_duckling_target(7)class TestParsePartitionKey:diff --git a/posthog/dags/tests/test_events_backfill_to_duckling.py b/posthog/dags/tests/test_events_backfill_to_duckling.pyindex 4c1f433b0c28..ae1f601905c0 100644--- a/posthog/dags/tests/test_events_backfill_to_duckling.py+++ b/posthog/dags/tests/test_events_backfill_to_duckling.py@@ -14,7 +14,12 @@ class _FakeRow:class TestResolveDucklingTarget:- def _resolve(self, catalog: "_FakeRow | None", server: "_FakeRow | None"):+ def _resolve(+ self,+ catalog: "_FakeRow | None",+ server: "_FakeRow | None",+ cp_bucket: str | None = None,+ ):with (patch("posthog.dags.events_backfill_to_duckling._get_org_id_for_team", return_value="org-1"),patch(@@ -22,12 +27,12 @@ class TestResolveDucklingTarget:),patch("posthog.dags.events_backfill_to_duckling.get_duckgres_server_for_organization", return_value=server),patch(- "posthog.dags.events_backfill_to_duckling.derive_duckling_bucket",- return_value=("derived-bucket", "us-east-1"),- ) as mock_derive,+ "products.data_warehouse.backend.api.managed_warehouse.cp_bucket_for",+ return_value=cp_bucket,+ ) as mock_cp,):target = _resolve_duckling_target(team_id=123)- return target, mock_derive+ return target, mock_cp@parameterized.expand([@@ -39,17 +44,9 @@ class TestResolveDucklingTarget:"catalog-bucket","us-east-2",),- ("server_used_when_no_catalog", None, _FakeRow("server-bucket", "eu-west-1"), "server-bucket", "eu-west-1"),- (- "server_used_when_catalog_blank",- _FakeRow("", "us-east-2"),- _FakeRow("server-bucket", "eu-west-1"),- "server-bucket",- "eu-west-1",- ),])- def test_prefers_stored_bucket(+ def test_catalog_bucket_wins_without_consulting_control_plane(self,_name: str,catalog: "_FakeRow | None",@@ -57,12 +54,36 @@ class TestResolveDucklingTarget:expected_bucket: str,expected_region: str,) -> None:- target, mock_derive = self._resolve(catalog, server)+ target, mock_cp = self._resolve(catalog, server, cp_bucket="cp-bucket")assert target.bucket == expected_bucketassert target.bucket_region == expected_regionassert target.organization_id == "org-1"- mock_derive.assert_not_called()+ # An older catalog-backed org has no control-plane bucket to ask about.+ mock_cp.assert_not_called()++ @parameterized.expand(+ [+ # The control plane wins over a stored DuckgresServer bucket — a stale,+ # locally-derived stored value must never beat the authoritative name.+ ("server_present_but_stale", _FakeRow("stale-stored-bucket", "eu-west-1")),+ ("no_server", None),+ ("server_blank", _FakeRow("", "eu-west-1")),+ ]+ )+ def test_control_plane_wins_over_stored_server(self, _name: str, server: "_FakeRow | None") -> None:+ target, mock_cp = self._resolve(catalog=None, server=server, cp_bucket="cp-bucket")++ mock_cp.assert_called_once_with("org-1")+ assert target.bucket == "cp-bucket"++ def test_falls_back_to_stored_server_when_control_plane_unavailable(self) -> None:+ # CP returns nothing (unreachable/unconfigured) — use the known-good stored row.+ target, mock_cp = self._resolve(catalog=None, server=_FakeRow("server-bucket", "eu-west-1"), cp_bucket=None)++ mock_cp.assert_called_once_with("org-1")+ assert target.bucket == "server-bucket"+ assert target.bucket_region == "eu-west-1"@parameterized.expand([@@ -71,11 +92,10 @@ class TestResolveDucklingTarget:("both_blank", _FakeRow("", "us-east-1"), _FakeRow(None, "us-east-1")),])- def test_falls_back_to_derived_when_no_stored_bucket(+ def test_raises_when_nothing_can_name_the_bucket(self, _name: str, catalog: "_FakeRow | None", server: "_FakeRow | None") -> None:- target, mock_derive = self._resolve(catalog, server)+ import pytest- mock_derive.assert_called_once_with("org-1")- assert target.bucket == "derived-bucket"- assert target.bucket_region == "us-east-1"+ with pytest.raises(ValueError, match="No S3 bucket resolvable"):+ self._resolve(catalog, server, cp_bucket=None)diff --git a/posthog/ducklake/common.py b/posthog/ducklake/common.pyindex 373e58186bdf..7e404028a627 100644--- a/posthog/ducklake/common.py+++ b/posthog/ducklake/common.py@@ -277,40 +277,16 @@ def upsert_duckgres_server_for_org(return server-# Managed-warehouse S3 bucket naming. The bucket is created by the duckgres Crossplane-# composition (charts: crossplane-config) as "posthog-duckling-{organization_id}-{suffix}",-# where the suffix identifies the managed-warehouse environment. The mapping is fixed per-# deployment, so we derive it from the deployment region rather than reading it back.-DUCKGRES_BUCKET_PREFIX = "posthog-duckling"+# Managed-warehouse S3 bucket naming. The duckgres control plane is the single owner of+# the per-org bucket name: it names the bucket, pins it on the Duckling CR's+# spec.dataStore.bucketName, and returns it from the provision / warehouse-status API.+# 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"-def _duckling_env_suffix() -> str:- """Managed-warehouse environment suffix for the org's S3 bucket name.-- Mirrors the duckgres Crossplane composition, keyed off the deployment region. EU is not- enabled yet, so that path is a no-op (raises rather than fabricating a bucket name);- everything that isn't prod-US — hosted dev/staging, local dev — maps to "dev".- """- # Lazy import so this module can be loaded standalone (see bin/check_ducklake_up)- # without the full posthog package on sys.path.- from posthog.utils import get_instance_region # noqa: PLC0415-- region = (get_instance_region() or "").upper()- if region == "EU":- raise NotImplementedError("Managed warehouse is not enabled in the EU region")- return "prod-us" if region == "US" else "dev"---def derive_duckling_bucket(organization_id: str) -> tuple[str, str]:- """Derive the org's managed-warehouse S3 bucket name and region.-- Deterministic — mirrors the duckgres Crossplane composition, which names the bucket- "posthog-duckling-{organization_id}-{suffix}". Returns (bucket_name, region).- """- return f"{DUCKGRES_BUCKET_PREFIX}-{organization_id}-{_duckling_env_suffix()}", DUCKGRES_BUCKET_REGION--def get_duckgres_server_for_team(team_id: int) -> DuckgresServer | None:"""Look up DuckgresServer for a team.diff --git a/posthog/ducklake/models.py b/posthog/ducklake/models.pyindex 8a06239c1a43..deab3edbd6d5 100644--- a/posthog/ducklake/models.py+++ b/posthog/ducklake/models.py@@ -93,7 +93,9 @@ class DuckgresServer(CreatedMetaFields, UpdatedMetaFields, UUIDModel):# authoritative bucket name instead of re-deriving it. Nullable for rows provisioned# before this field existed.bucket = models.CharField(max_length=255, null=True, blank=True)- bucket_region = models.CharField(max_length=50, default="us-east-1")+ # Region travels with the bucket: set alongside it, left NULL when no bucket is+ # recorded yet (status_for()'s self-heal fills both in once the control plane reports them).+ bucket_region = models.CharField(max_length=50, null=True, blank=True, default=None)class Meta:db_table = "posthog_duckgresserver"diff --git a/posthog/ducklake/test_common.py b/posthog/ducklake/test_common.pyindex 703206328b00..2007c0809a9d 100644--- a/posthog/ducklake/test_common.py+++ b/posthog/ducklake/test_common.py@@ -5,7 +5,6 @@ import duckdbfrom parameterized import parameterizedfrom posthog.ducklake.common import (- derive_duckling_bucket,initialize_ducklake,is_version_mismatch,reset_ducklake_catalog,@@ -15,25 +14,6 @@ from posthog.ducklake.models import DuckgresServerfrom posthog.models import Organization-class TestDeriveDucklingBucket:- @parameterized.expand(- [- ("prod_us", "US", "posthog-duckling-org-abc-prod-us"),- ("hosted_dev", "DEV", "posthog-duckling-org-abc-dev"),- ("local_unset", None, "posthog-duckling-org-abc-dev"),- ]- )- def test_derives_bucket_from_region(self, _name: str, region: str | None, expected_bucket: str):- # Mirrors the duckgres Crossplane composition: posthog-duckling-{org}-{suffix}.- with patch("posthog.utils.get_instance_region", return_value=region):- assert derive_duckling_bucket("org-abc") == (expected_bucket, "us-east-1")-- def test_eu_is_not_enabled(self):- with patch("posthog.utils.get_instance_region", return_value="EU"):- with pytest.raises(NotImplementedError, match="EU"):- derive_duckling_bucket("org-1")--@pytest.mark.django_dbclass TestUpsertDuckgresServerForOrg:def test_creates_then_updates_a_single_row(self):diff --git a/posthog/migrations/1232_alter_duckgresserver_bucket_region.py b/posthog/migrations/1232_alter_duckgresserver_bucket_region.pynew file mode 100644index 000000000000..821d0d6fa8f0--- /dev/null+++ b/posthog/migrations/1232_alter_duckgresserver_bucket_region.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.14 on 2026-06-22 19:21++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1231_duckgresserverteam"),+ ]++ operations = [+ migrations.AlterField(+ model_name="duckgresserver",+ name="bucket_region",+ field=models.CharField(blank=True, default=None, max_length=50, null=True),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 910e1f1b655d..b01b0e9ab1dd 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1231_duckgresserverteam+1232_alter_duckgresserver_bucket_regiondiff --git a/products/data_warehouse/backend/api/managed_warehouse.py b/products/data_warehouse/backend/api/managed_warehouse.pyindex 0f52eba7f48d..c4ca72bbee05 100644--- a/products/data_warehouse/backend/api/managed_warehouse.py+++ b/products/data_warehouse/backend/api/managed_warehouse.py@@ -117,13 +117,20 @@ def _request(json_body: dict | None = None,params: dict | None = None,timeout: int = 30,+ require_enabled: bool = True,) -> Response:"""Proxy a request to the duckgres provisioning API, gated on the org's feature flag.Paths starting with "/" are org-scoped (`/api/v1/orgs/{org}{path}`); others are globalAPI paths (`/api/v1/{path}`).++ `require_enabled` gates on the user-facing `data-warehouse-scene` flag and is the right+ default for UI-driven calls. Backend/background callers (e.g. the Dagster duckling+ backfill) must pass `require_enabled=False`: the flag is evaluated only-locally and a+ worker without the flag definition loaded would otherwise get a spurious 403 even when+ the control plane can answer."""- if not is_enabled(organization_id):+ if require_enabled and not is_enabled(organization_id):return Response({"error": "This feature is not enabled"}, status=status.HTTP_403_FORBIDDEN)base_url = getattr(settings, "DUCKGRES_API_URL", None)@@ -197,9 +204,19 @@ def provision(organization_id: UUID | str, database_name: str | None) -> Respons)if status.is_success(resp.status_code) and isinstance(resp.data, dict):_persist_duckgres_server(organization_id, database_name, resp.data)+ # The bucket is internal infra detail, persisted above and consumed by the+ # backfill via cp_bucket_for — not part of the UI-facing ProvisionWarehouseResponse+ # schema. Strip it so the response matches its OpenAPI contract.+ _strip_bucket_fields(resp.data)return resp+def _strip_bucket_fields(body: dict) -> None:+ """Drop the internal bucket fields from a UI-facing response body, in place."""+ body.pop("bucket", None)+ body.pop("bucket_region", None)++def _persist_duckgres_server(organization_id: UUID | str, database_name: str | None, body: dict) -> None:"""Persist the org's DuckgresServer row from a successful provision response.@@ -212,18 +229,19 @@ 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 derive_duckling_bucket, upsert_duckgres_server_for_org # noqa: PLC0415-- # Best-effort bucket derivation: a region without a managed-warehouse bucket convention- # (e.g. EU, where derive_duckling_bucket raises) must not block persisting the connection- # row. upsert treats None as "leave unset", so the bucket stays NULL and the backfill- # resolver falls back to derivation if it ever needs one.- try:- bucket: str | None- bucket_region: str | None- bucket, bucket_region = derive_duckling_bucket(str(organization_id))- except NotImplementedError:- bucket, bucket_region = None, None+ from posthog.ducklake.common import 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,+ # and returns it here. Persist it verbatim; never re-derive (the old local+ # derivation drifted from the Crossplane composition and named buckets that+ # don't exist). A response without a bucket (external data store, or a CP too+ # 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 Nonetry:connection = _present_connection({"database": database_name, "username": body.get("username", "root")})@@ -247,11 +265,102 @@ def deprovision(organization_id: UUID | str) -> Response:def status_for(organization_id: UUID | str) -> Response:resp = _request("GET", organization_id, "/warehouse/status")- if resp.status_code == 200 and isinstance(resp.data, dict) and isinstance(resp.data.get("connection"), dict):- resp.data["connection"] = _present_connection(resp.data["connection"])+ if resp.status_code == 200 and isinstance(resp.data, dict):+ # Self-heal: the control plane is the authoritative source of the per-org+ # bucket name. If the stored DuckgresServer row disagrees — NULL (row+ # created before the CP returned it) or a stale locally-derived name — fix+ # it here so the value converges on every status read without a separate+ # backfill job. The UI reads status when viewing a warehouse, so a deploy+ # heals each org the first time its status is fetched.+ _reconcile_bucket_from_status(organization_id, resp.data)+ if isinstance(resp.data.get("connection"), dict):+ resp.data["connection"] = _present_connection(resp.data["connection"])+ # Internal infra detail — reconciled above, not part of the UI-facing+ # WarehouseStatusResponse schema. Backend callers use cp_bucket_for instead.+ _strip_bucket_fields(resp.data)return resp+def cp_bucket_for(organization_id: UUID | str) -> str | None:+ """Authoritative S3 bucket for the org's duckling, straight from the control plane.++ For backend/background callers (the Dagster duckling backfill), not the UI. Unlike+ `status_for` it:+ - bypasses the user-facing feature-flag gate (`require_enabled=False`), so a Dagster+ worker without the flag loaded locally doesn't get a spurious 403; and+ - returns the bucket only when the status body's own `org_id` matches the org asked+ about, so a CP bug or misrouted proxy can never hand back another tenant's bucket.++ Also reconciles the stored `DuckgresServer` row so it converges for next time. Returns+ None when the control plane is unreachable, unconfigured, or names no bucket.+ """+ resp = _request("GET", organization_id, "/warehouse/status", require_enabled=False)+ if resp.status_code != 200 or not isinstance(resp.data, dict):+ return None++ response_org = resp.data.get("org_id")+ if response_org is not None and str(response_org) != str(organization_id):+ logger.warning(+ "Refusing to use control-plane bucket: status org_id mismatch",+ requested_organization_id=str(organization_id),+ response_org_id=str(response_org),+ )+ return None++ _reconcile_bucket_from_status(organization_id, resp.data)+ return resp.data.get("bucket") or None+++def _reconcile_bucket_from_status(organization_id: UUID | str, body: dict) -> None:+ """Converge DuckgresServer.bucket/bucket_region onto the control-plane-reported values.++ Best-effort and side-effect-only: a single UPDATE touching only rows where the+ bucket OR the region differs (no fetch, no create). A DB hiccup is swallowed — it+ must never fail the status read it piggybacks on.+ """+ # Defense-in-depth: the request is per-org (the URL carries the org id), but+ # only write back when the response's own org_id agrees with the one we asked+ # about. A mismatch (CP bug, misrouted proxy) must never let one tenant's+ # status overwrite another's bucket mapping — that would redirect backfill+ # reads/writes to the wrong S3 bucket.+ response_org = body.get("org_id")+ if response_org is not None and str(response_org) != str(organization_id):+ logger.warning(+ "Refusing to reconcile DuckgresServer bucket: status org_id mismatch",+ requested_organization_id=str(organization_id),+ response_org_id=str(response_org),+ )+ return++ bucket = body.get("bucket")+ if not bucket:+ # 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"+ try:+ from posthog.ducklake.models import DuckgresServer # noqa: PLC0415++ # exclude rows where BOTH already match, so a correct bucket with a stale+ # region (or vice versa) is still repaired.+ updated = (+ DuckgresServer.objects.filter(organization_id=organization_id)+ .exclude(bucket=bucket, bucket_region=bucket_region)+ .update(bucket=bucket, bucket_region=bucket_region)+ )+ if updated:+ logger.info(+ "duckgres_server_bucket_reconciled_from_status",+ organization_id=str(organization_id),+ bucket=bucket,+ )+ except Exception:+ logger.exception(+ "Failed to reconcile DuckgresServer bucket from status",+ organization_id=str(organization_id),+ )++def reset_password(organization_id: UUID | str) -> Response:return _request("POST", organization_id, "/reset-password")diff --git a/products/data_warehouse/backend/api/test/test_managed_warehouse.py b/products/data_warehouse/backend/api/test/test_managed_warehouse.pyindex c8e4e90701ae..1e1d7ca09e30 100644--- a/products/data_warehouse/backend/api/test/test_managed_warehouse.py+++ b/products/data_warehouse/backend/api/test/test_managed_warehouse.py@@ -48,7 +48,39 @@ def test_provision_persists_duckgres_server_on_success(mock_request: MagicMock)assert server.database == "ducklake"assert server.username == "root"assert server.password == "secret"- assert server.bucket == f"posthog-duckling-{org.id}-prod-us"+ # No bucket in the provision response → column left unset. There is no local+ # derivation fallback anymore; the control plane is the only source of the name+ # and status_for() self-heals the row once the CP reports it.+ assert server.bucket is None+ assert server.bucket_region is None+++@override_settings(CLOUD_DEPLOYMENT="US", DUCKGRES_PG_PORT=5432)+@patch("products.data_warehouse.backend.api.managed_warehouse._request")+def test_provision_persists_bucket_returned_by_control_plane(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.+ org = Organization.objects.create(name="Org")+ cp_bucket = "posthog-duckling-0194d6405db400006cde48d6114c0f99-mw-prod-us"+ mock_request.return_value = Response(+ {+ "status": "provisioning started",+ "org": str(org.id),+ "username": "root",+ "password": "secret",+ "bucket": cp_bucket,+ },+ status=202,+ )++ resp = managed_warehouse.provision(org.id, "my-warehouse")++ assert resp.status_code == 202+ server = DuckgresServer.objects.get(organization_id=org.id)+ # Verbatim, not the locally-derived f"posthog-duckling-{org.id}-prod-us".+ assert server.bucket == cp_bucketassert server.bucket_region == "us-east-1"@@ -82,3 +114,196 @@ def test_provision_does_not_persist_on_failure(mock_request: MagicMock) -> None:assert resp.status_code == 500assert not DuckgresServer.objects.filter(organization_id=org.id).exists()+++@patch("products.data_warehouse.backend.api.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+ # name on the next status read — no separate backfill needed.+ org = Organization.objects.create(name="Org")+ DuckgresServer.objects.create(+ organization_id=org.id,+ host="h",+ port=5432,+ database="ducklake",+ username="root",+ password="pw",+ bucket="posthog-duckling-stale-prod-us", # wrong/drifted+ )+ cp_bucket = "posthog-duckling-0194d6405db400006cde48d6114c0f99-mw-prod-us"+ mock_request.return_value = Response({"org_id": str(org.id), "state": "ready", "bucket": cp_bucket}, status=200)++ managed_warehouse.status_for(org.id)++ server = DuckgresServer.objects.get(organization_id=org.id)+ assert server.bucket == cp_bucket+ assert server.bucket_region == "us-east-1"+++@patch("products.data_warehouse.backend.api.managed_warehouse._request")+def test_status_for_leaves_matching_bucket_untouched(mock_request: MagicMock) -> None:+ org = Organization.objects.create(name="Org")+ bucket = "posthog-duckling-org-mw-prod-us"+ DuckgresServer.objects.create(+ organization_id=org.id,+ host="h",+ port=5432,+ database="ducklake",+ username="root",+ password="pw",+ bucket=bucket,+ )+ mock_request.return_value = Response({"org_id": str(org.id), "state": "ready", "bucket": bucket}, status=200)++ managed_warehouse.status_for(org.id)++ assert DuckgresServer.objects.get(organization_id=org.id).bucket == bucket+++@patch("products.data_warehouse.backend.api.managed_warehouse._request")+def test_status_for_refuses_to_reconcile_on_org_mismatch(mock_request: MagicMock) -> None:+ # A status whose org_id disagrees with the requested org must never overwrite+ # this tenant's bucket — that would redirect backfill to another org's bucket.+ org = Organization.objects.create(name="Org")+ DuckgresServer.objects.create(+ organization_id=org.id,+ host="h",+ port=5432,+ database="ducklake",+ username="root",+ password="pw",+ bucket="posthog-duckling-mine-mw-prod-us",+ )+ mock_request.return_value = Response(+ {+ "org_id": "00000000-0000-0000-0000-000000000000",+ "state": "ready",+ "bucket": "posthog-duckling-other-mw-prod-us",+ },+ status=200,+ )++ managed_warehouse.status_for(org.id)++ assert DuckgresServer.objects.get(organization_id=org.id).bucket == "posthog-duckling-mine-mw-prod-us"+++@patch("products.data_warehouse.backend.api.managed_warehouse._request")+def test_status_for_without_bucket_leaves_row_alone(mock_request: MagicMock) -> None:+ # External data stores / pre-backfill ducklings report no bucket — don't blank it.+ org = Organization.objects.create(name="Org")+ DuckgresServer.objects.create(+ organization_id=org.id,+ host="h",+ port=5432,+ database="ducklake",+ username="root",+ password="pw",+ bucket="posthog-duckling-keep-mw-prod-us",+ )+ mock_request.return_value = Response({"org_id": str(org.id), "state": "ready"}, status=200)++ managed_warehouse.status_for(org.id)++ assert DuckgresServer.objects.get(organization_id=org.id).bucket == "posthog-duckling-keep-mw-prod-us"+++@patch("products.data_warehouse.backend.api.managed_warehouse._request")+def test_status_for_self_heals_stale_region_only(mock_request: MagicMock) -> None:+ # Bucket already correct but region drifted — the row must still be repaired.+ org = Organization.objects.create(name="Org")+ bucket = "posthog-duckling-org-mw-prod-us"+ DuckgresServer.objects.create(+ organization_id=org.id,+ host="h",+ port=5432,+ database="ducklake",+ username="root",+ password="pw",+ bucket=bucket,+ bucket_region="eu-west-1", # stale+ )+ mock_request.return_value = Response(+ {"org_id": str(org.id), "state": "ready", "bucket": bucket, "bucket_region": "us-east-1"}, status=200+ )++ managed_warehouse.status_for(org.id)++ server = DuckgresServer.objects.get(organization_id=org.id)+ assert server.bucket == bucket+ assert server.bucket_region == "us-east-1"+++@patch("products.data_warehouse.backend.api.managed_warehouse._request")+def test_status_for_strips_bucket_from_response(mock_request: MagicMock) -> None:+ # The bucket is internal infra detail — never part of the UI-facing status body.+ org = Organization.objects.create(name="Org")+ mock_request.return_value = Response(+ {"org_id": str(org.id), "state": "ready", "bucket": "posthog-duckling-x-mw-prod-us"}, status=200+ )++ resp = managed_warehouse.status_for(org.id)++ assert "bucket" not in resp.data+ assert "bucket_region" not in resp.data+++@patch("products.data_warehouse.backend.api.managed_warehouse.is_enabled", return_value=False)+@patch("products.data_warehouse.backend.api.managed_warehouse.internal_requests")+@override_settings(DUCKGRES_API_URL="http://duckgres.invalid", DUCKGRES_INTERNAL_SECRET="s")+def test_cp_bucket_for_bypasses_feature_gate_and_reconciles(mock_internal: MagicMock, _mock_enabled: MagicMock) -> None:+ # Backend path: the user-facing flag is OFF, but cp_bucket_for must still reach the+ # control plane (require_enabled=False) and return + reconcile the authoritative bucket.+ org = Organization.objects.create(name="Org")+ DuckgresServer.objects.create(+ organization_id=org.id, host="h", port=5432, database="ducklake", username="root", password="pw", bucket="stale"+ )+ cp_bucket = "posthog-duckling-0194d6405db400006cde48d6114c0f99-mw-prod-us"+ http_resp = MagicMock(status_code=200)+ http_resp.json.return_value = {"org_id": str(org.id), "state": "ready", "bucket": cp_bucket}+ mock_internal.request.return_value = http_resp++ result = managed_warehouse.cp_bucket_for(org.id)++ assert result == cp_bucket+ assert DuckgresServer.objects.get(organization_id=org.id).bucket == cp_bucket+++@patch("products.data_warehouse.backend.api.managed_warehouse.is_enabled", return_value=True)+@patch("products.data_warehouse.backend.api.managed_warehouse.internal_requests")+@override_settings(DUCKGRES_API_URL="http://duckgres.invalid", DUCKGRES_INTERNAL_SECRET="s")+def test_cp_bucket_for_rejects_org_mismatch(mock_internal: MagicMock, _mock_enabled: MagicMock) -> None:+ # A status body for a different org must yield no bucket and touch no row.+ org = Organization.objects.create(name="Org")+ DuckgresServer.objects.create(+ organization_id=org.id, host="h", port=5432, database="ducklake", username="root", password="pw", bucket="mine"+ )+ http_resp = MagicMock(status_code=200)+ http_resp.json.return_value = {+ "org_id": "00000000-0000-0000-0000-000000000000",+ "state": "ready",+ "bucket": "other",+ }+ mock_internal.request.return_value = http_resp++ result = managed_warehouse.cp_bucket_for(org.id)++ assert result is None+ assert DuckgresServer.objects.get(organization_id=org.id).bucket == "mine"+++@patch("products.data_warehouse.backend.api.managed_warehouse._request")+def test_cp_bucket_for_returns_none_when_cp_has_no_bucket(mock_request: MagicMock) -> None:+ org = Organization.objects.create(name="Org")+ mock_request.return_value = Response({"org_id": str(org.id), "state": "ready"}, status=200)++ assert managed_warehouse.cp_bucket_for(org.id) is None