: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
refactor(data-warehouse): consolidate duckgres/ducklake models 4→2 (#66011)
Benjamin Knofe-Vider44eeb73d872c
diff --git a/posthog/admin/admins/duckgres_server_admin.py b/posthog/admin/admins/duckgres_server_admin.pyindex 9e1a1b22d28d..cbee8682e900 100644--- a/posthog/admin/admins/duckgres_server_admin.py+++ b/posthog/admin/admins/duckgres_server_admin.py@@ -17,7 +17,6 @@ logger = structlog.get_logger(__name__)class DuckgresServerAdmin(admin.ModelAdmin):list_display = ("id",- "team_id","organization_id","host","port",@@ -27,12 +26,12 @@ class DuckgresServerAdmin(admin.ModelAdmin):"created_at","updated_at",)- search_fields = ("=team__id", "=organization__id", "host", "bucket")+ search_fields = ("=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")+ raw_id_fields = ("organization",)# Custom templates add the provision / enable-backfill / deprovision buttons.change_list_template = "admin/posthog/duckgres_server/change_list.html"@@ -42,7 +41,7 @@ class DuckgresServerAdmin(admin.ModelAdmin):(None,{- "fields": ("id", "team", "organization"),+ "fields": ("id", "organization"),},),(@@ -51,6 +50,12 @@ class DuckgresServerAdmin(admin.ModelAdmin):"fields": ("host", "port", "flight_port", "database", "username"),},),+ (+ "DuckLake catalog connection",+ {+ "fields": ("catalog_host", "catalog_port", "catalog_database", "catalog_username"),+ },+ ),("Storage",{@@ -72,7 +77,7 @@ class DuckgresServerAdmin(admin.ModelAdmin):(None,{- "fields": ("team", "organization"),+ "fields": ("organization",),},),(@@ -81,6 +86,12 @@ class DuckgresServerAdmin(admin.ModelAdmin):"fields": ("host", "port", "flight_port", "database", "username", "password"),},),+ (+ "DuckLake catalog connection",+ {+ "fields": ("catalog_host", "catalog_port", "catalog_database", "catalog_username", "catalog_password"),+ },+ ),("Storage",{@@ -116,9 +127,9 @@ class DuckgresServerAdmin(admin.ModelAdmin):"""Provision a brand-new managed warehouse for an org + its first team.Runs the same path as the in-product provision API: the duckgres control-plane- /provision call, then the DuckgresServer, DuckgresServerTeam, and DuckLakeBackfill- records. The org's feature flag is bypassed (require_enabled=False) so ops can- provision before the org is entitled to the in-product UI.+ /provision call, then the DuckgresServer and DuckgresServerTeam records. The org's+ feature flag is bypassed (require_enabled=False) so ops can provision before the org+ is entitled to the in-product UI."""if request.method not in {"GET", "POST"}:return HttpResponseNotAllowed(["GET", "POST"])diff --git a/posthog/admin/admins/duckgres_server_team_admin.py b/posthog/admin/admins/duckgres_server_team_admin.pyindex 724073f4825b..0908425da9f5 100644--- a/posthog/admin/admins/duckgres_server_team_admin.py+++ b/posthog/admin/admins/duckgres_server_team_admin.py@@ -1,4 +1,6 @@from django.contrib import admin+from django.db.models import QuerySet+from django.http import HttpRequestfrom posthog.models import DuckgresServerTeam@@ -9,24 +11,64 @@ class DuckgresServerTeamAdmin(admin.ModelAdmin):"id","server_id","team_id",+ "backfill_enabled",+ "table_suffix",+ "earliest_event_date",+ "created_by","created_at","updated_at",)- search_fields = ("=team__id", "=server__id")- readonly_fields = ("id", "created_at", "updated_at")- raw_id_fields = ("server", "team")+ list_filter = ("backfill_enabled",)+ search_fields = ("=team__id", "=server__id", "table_suffix")+ # `table_suffix` is write-once: it names a team's warehouse tables/schema, so changing it after+ # data is written moves the target and orphans the old tables. It's set only through the+ # validated enable flow (`enable_team_backfill`), never edited here.+ # `earliest_event_date` is the sensor's cached backfill floor — shown for visibility but+ # not hand-edited (the sensor owns it; it resolves+caches it from ClickHouse once). To+ # force re-discovery, use the "Reset earliest_event_date" action rather than a free-form edit.+ readonly_fields = ("id", "table_suffix", "earliest_event_date", "created_at", "updated_at")+ raw_id_fields = ("server", "team", "created_by")+ actions = ("make_enabled", "make_disabled", "reset_earliest_event_date")++ # Toggling `backfill_enabled` drives the duckling sensors into expensive ClickHouse->S3+ # backfills, so it goes through Django's action-confirmation flow rather than an+ # inline `list_editable` checkbox that can be flipped for the wrong team in passing.+ @admin.action(description="Enable warehouse backfills for selected teams")+ def make_enabled(self, request: HttpRequest, queryset: QuerySet[DuckgresServerTeam]) -> None:+ updated = queryset.update(backfill_enabled=True)+ self.message_user(request, f"Enabled warehouse backfills for {updated} team(s).")++ @admin.action(description="Disable warehouse backfills for selected teams")+ def make_disabled(self, request: HttpRequest, queryset: QuerySet[DuckgresServerTeam]) -> None:+ updated = queryset.update(backfill_enabled=False)+ self.message_user(request, f"Disabled warehouse backfills for {updated} team(s).")++ # The field is read-only in the form (the sensor owns it), but a team that previously had+ # no events — and so cached the no-history sentinel — needs a way to re-trigger discovery+ # after a historical import. Clearing it makes the sensor re-query ClickHouse and re-derive+ # the backfill range on its next tick.+ @admin.action(description="Reset earliest_event_date (re-discover backfill range)")+ def reset_earliest_event_date(self, request: HttpRequest, queryset: QuerySet[DuckgresServerTeam]) -> None:+ updated = queryset.update(earliest_event_date=None)+ self.message_user(request, f"Reset backfill range for {updated} team(s); the sensor will re-discover it.")fieldsets = ((None,{- "fields": ("id", "server", "team"),+ "fields": ("id", "server", "team", "backfill_enabled", "table_suffix"),+ },+ ),+ (+ "Backfill range",+ {+ "fields": ("earliest_event_date",),},),("Metadata",{- "fields": ("created_at", "updated_at"),+ "fields": ("created_by", "created_at", "updated_at"),},),)diff --git a/posthog/admin/admins/ducklake_backfill_admin.py b/posthog/admin/admins/ducklake_backfill_admin.pydeleted file mode 100644index 233fd05c35ad..000000000000--- a/posthog/admin/admins/ducklake_backfill_admin.py+++ /dev/null@@ -1,67 +0,0 @@-from django.contrib import admin-from django.db.models import QuerySet-from django.http import HttpRequest--from posthog.models import DuckLakeBackfill--[email protected](DuckLakeBackfill)-class DuckLakeBackfillAdmin(admin.ModelAdmin):- list_display = (- "id",- "team_id",- "enabled",- "table_suffix",- "earliest_event_date",- "created_by",- "created_at",- "updated_at",- )- list_filter = ("enabled",)- search_fields = ("=team__id", "table_suffix")- # `table_suffix` is write-once: it names a team's warehouse tables/schema, so changing it after- # data is written moves the target and orphans the old tables. It's set only through the- # validated enable flow (`enable_team_backfill`), never edited here.- # `earliest_event_date` is the sensor's cached backfill floor — shown for visibility but- # not hand-edited (the sensor owns it; it resolves+caches it from ClickHouse once). To- # force re-discovery, use the "Reset earliest_event_date" action rather than a free-form edit.- readonly_fields = ("id", "table_suffix", "earliest_event_date", "created_at", "updated_at")- raw_id_fields = ("team", "created_by")- actions = ("make_enabled", "make_disabled", "reset_earliest_event_date")-- # Toggling `enabled` drives the duckling sensors into expensive ClickHouse->S3- # backfills, so it goes through Django's action-confirmation flow rather than an- # inline `list_editable` checkbox that can be flipped for the wrong team in passing.- @admin.action(description="Enable warehouse backfills for selected teams")- def make_enabled(self, request: HttpRequest, queryset: QuerySet[DuckLakeBackfill]) -> None:- updated = queryset.update(enabled=True)- self.message_user(request, f"Enabled warehouse backfills for {updated} team(s).")-- @admin.action(description="Disable warehouse backfills for selected teams")- def make_disabled(self, request: HttpRequest, queryset: QuerySet[DuckLakeBackfill]) -> None:- updated = queryset.update(enabled=False)- self.message_user(request, f"Disabled warehouse backfills for {updated} team(s).")-- # The field is read-only in the form (the sensor owns it), but a team that previously had- # no events — and so cached the no-history sentinel — needs a way to re-trigger discovery- # after a historical import. Clearing it makes the sensor re-query ClickHouse and re-derive- # the backfill range on its next tick.- @admin.action(description="Reset earliest_event_date (re-discover backfill range)")- def reset_earliest_event_date(self, request: HttpRequest, queryset: QuerySet[DuckLakeBackfill]) -> None:- updated = queryset.update(earliest_event_date=None)- self.message_user(request, f"Reset backfill range for {updated} team(s); the sensor will re-discover it.")-- fieldsets = (- (- None,- {- "fields": ("id", "team", "enabled", "table_suffix"),- },- ),- (- "Metadata",- {- "fields": ("created_by", "created_at", "updated_at"),- },- ),- )diff --git a/posthog/admin/admins/ducklake_catalog_admin.py b/posthog/admin/admins/ducklake_catalog_admin.pydeleted file mode 100644index 5b0d67f3a3d7..000000000000--- a/posthog/admin/admins/ducklake_catalog_admin.py+++ /dev/null@@ -1,49 +0,0 @@-from django.contrib import admin--from posthog.models import DuckLakeCatalog--[email protected](DuckLakeCatalog)-class DuckLakeCatalogAdmin(admin.ModelAdmin):- list_display = (- "id",- "team_id",- "organization_id",- "db_host",- "db_database",- "bucket",- "bucket_region",- "created_at",- "updated_at",- )- list_filter = ("bucket_region",)- search_fields = ("=team__id", "=organization__id", "db_host", "bucket")- readonly_fields = ("id", "created_at", "updated_at")- raw_id_fields = ("team", "organization")-- fieldsets = (- (- None,- {- "fields": ("id", "team", "organization"),- },- ),- (- "Database connection",- {- "fields": ("db_host", "db_port", "db_database", "db_username", "db_password"),- },- ),- (- "S3 bucket",- {- "fields": ("bucket", "bucket_region"),- },- ),- (- "Metadata",- {- "fields": ("created_at", "updated_at"),- },- ),- )diff --git a/posthog/admin/test_duckgres_server_team_admin.py b/posthog/admin/test_duckgres_server_team_admin.pynew file mode 100644index 000000000000..a405be1b1403--- /dev/null+++ b/posthog/admin/test_duckgres_server_team_admin.py@@ -0,0 +1,26 @@+from posthog.test.base import BaseTest++from django.contrib.admin.sites import AdminSite+from django.test import RequestFactory++from posthog.admin.admins.duckgres_server_team_admin import DuckgresServerTeamAdmin+from posthog.models import DuckgresServer, DuckgresServerTeam+++class TestDuckgresServerTeamAdmin(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.admin = DuckgresServerTeamAdmin(DuckgresServerTeam, AdminSite())+ self.request = RequestFactory().get("/")+ self.request.user = self.user++ def test_table_suffix_is_readonly(self) -> None:+ # `table_suffix` is write-once — editing it in admin would move a team's warehouse+ # schema/tables and orphan the old ones. It must never be editable here.+ server = DuckgresServer.objects.create(+ organization=self.organization, host="h", port=5432, database="ducklake", username="root", password="x"+ )+ link = DuckgresServerTeam.objects.create(+ server=server, team=self.team, backfill_enabled=True, table_suffix="acme"+ )+ assert "table_suffix" in self.admin.get_readonly_fields(self.request, link)diff --git a/posthog/admin/test_ducklake_backfill_admin.py b/posthog/admin/test_ducklake_backfill_admin.pydeleted file mode 100644index 1de52cd3e014..000000000000--- a/posthog/admin/test_ducklake_backfill_admin.py+++ /dev/null@@ -1,21 +0,0 @@-from posthog.test.base import BaseTest--from django.contrib.admin.sites import AdminSite-from django.test import RequestFactory--from posthog.admin.admins.ducklake_backfill_admin import DuckLakeBackfillAdmin-from posthog.models import DuckLakeBackfill---class TestDuckLakeBackfillAdmin(BaseTest):- def setUp(self) -> None:- super().setUp()- self.admin = DuckLakeBackfillAdmin(DuckLakeBackfill, AdminSite())- self.request = RequestFactory().get("/")- self.request.user = self.user-- def test_table_suffix_is_readonly(self) -> None:- # `table_suffix` is write-once — editing it in admin would move a team's warehouse- # schema/tables and orphan the old ones. It must never be editable here.- backfill = DuckLakeBackfill.objects.create(team=self.team, enabled=True, table_suffix="acme")- assert "table_suffix" in self.admin.get_readonly_fields(self.request, backfill)diff --git a/posthog/dags/README_DUCKLINGS.md b/posthog/dags/README_DUCKLINGS.mdindex 279f1886e08e..4bde093f2884 100644--- a/posthog/dags/README_DUCKLINGS.md+++ b/posthog/dags/README_DUCKLINGS.md@@ -5,8 +5,8 @@ This document describes the Dagster jobs and sensors for backfilling ClickHouse## Architecture```text-DuckLakeCatalog (Django model)- │ lookup by team_id+DuckgresServer + DuckgresServerTeam (Django models)+ │ team_id → org's DuckgresServer (connection + bucket); DuckgresServerTeam gates enablement▼ClickHouse (events/person tables)│ export via s3() - bucket policy allows ClickHouse EC2 role@@ -108,16 +108,19 @@ class DucklingBackfillConfig:## Adding a New Duckling-1. Create a `DuckLakeCatalog` entry in Django admin:- - `team_id`: The team to backfill- - `bucket`: S3 bucket name- - `bucket_region`: AWS region- - `db_host`: RDS endpoint- - `db_name`: Database name+1. Provision (or create) the org's `DuckgresServer` (typically via the Django admin+ "Provision managed warehouse" action, which also records the team's+ `DuckgresServerTeam`). The relevant fields are:+ - `organization`: the org that owns the warehouse+ - `bucket` / `bucket_region`: S3 bucket name and AWS region+ - `catalog_host` / `catalog_database` / `catalog_username` / `catalog_password`: the+ DuckLake catalog RDS connectionEnsure the runtime IAM role can read from and write to the configured S3 bucket.-2. The discovery sensor will automatically pick up the new team on its next run+2. Enable the team's backfill by creating its `DuckgresServerTeam` row with+ `backfill_enabled=True` (the provision / enable-backfill admin actions do this). The+ discovery sensor will then pick up the team on its next run.3. To trigger immediate historical backfill, reset the full backfill sensor cursor@@ -148,7 +151,7 @@ If multiple partitions for the same team run concurrently, they may race to crea- **Job definition**: `posthog/dags/events_backfill_to_duckling.py`- **Tests**: `posthog/dags/test_events_backfill_to_duckling.py`- **Dagster registration**: `posthog/dags/locations/data_stack.py`-- **DuckLakeCatalog model**: `posthog/ducklake/models.py`+- **DuckgresServer / DuckgresServerTeam models**: `posthog/ducklake/models.py`## S3 Path Structurediff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.pyindex 1b0e360d00f5..cb2565fc9477 100644--- a/posthog/dags/events_backfill_to_duckling.py+++ b/posthog/dags/events_backfill_to_duckling.py@@ -8,8 +8,8 @@ This job targets individual customer "ducklings" - isolated DuckLake instances wown RDS catalog and S3 bucket.Architecture:- DuckgresServer (connection + S3 bucket name; older orgs read the bucket from DuckLakeCatalog)- │ team_id → organization_id → connection; bucket from the stored DuckgresServer/DuckLakeCatalog row+ DuckgresServer (duckgres connection + DuckLake catalog connection + S3 bucket name)+ │ team_id → organization_id → connection; bucket from the control plane / stored DuckgresServer row▼ClickHouse (events table)│ export via s3() - bucket policy allows ClickHouse EC2 role@@ -25,7 +25,7 @@ IAM Access:Partition Strategy:DynamicPartitionsDefinition with composite keys: {team_id}_{date}- - team_id maps to a duckling via DuckLakeBackfill (enablement) + DuckgresServer (connection)+ - team_id maps to a duckling via DuckgresServerTeam (membership + enablement) + DuckgresServer (connection)- date is the partition date (YYYY-MM-DD)"""@@ -67,13 +67,8 @@ from posthog.clickhouse.query_tagging import tags_contextfrom posthog.cloud_utils import is_cloudfrom posthog.dags.common import JobOwners, dagster_tags, settings_with_log_commentfrom posthog.ducklake.client import make_duckgres_conninfo-from posthog.ducklake.common import (- DUCKGRES_BUCKET_REGION,- _get_org_id_for_team,- get_duckgres_server_for_organization,- get_ducklake_catalog_for_organization,-)-from posthog.ducklake.models import DuckLakeBackfill+from posthog.ducklake.common import DUCKGRES_BUCKET_REGION, _get_org_id_for_team, get_duckgres_server_for_organization+from posthog.ducklake.models import DuckgresServerTeamlogger = structlog.get_logger(__name__)@@ -179,8 +174,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 resolved by _resolve_duckling_target (DuckLakeCatalog → control plane → stored- DuckgresServer fallback). The control plane is the authoritative owner of the bucket name.+ is resolved by _resolve_duckling_target (control plane → stored DuckgresServer fallback).+ The control plane is the authoritative owner of the bucket name."""team_id: int@@ -195,12 +190,12 @@ class DucklingTarget:def _resolve_table_names(team_id: int) -> tuple[str, str]:"""Resolve this team's per-environment events/persons table names.- A team's `DuckLakeBackfill.table_suffix` (when set) isolates its data into+ A team's `DuckgresServerTeam.table_suffix` (when set) isolates its data intodedicated `events_<suffix>` / `persons_<suffix>` tables so multiple teams sharing oneorg-scoped duckling don't merge into the shared `posthog.events` / `posthog.persons`.An unset suffix (legacy single-team ducklings) keeps the shared table names."""- suffix = DuckLakeBackfill.objects.filter(team_id=team_id).values_list("table_suffix", flat=True).first()+ suffix = DuckgresServerTeam.objects.filter(team_id=team_id).values_list("table_suffix", flat=True).first()if not suffix:return "events", "persons"_validate_identifier(suffix)@@ -215,14 +210,12 @@ def _resolve_duckling_target(team_id: int) -> DucklingTarget:per-environment suffix (or the shared defaults).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+ 1. The control plane — the single owner of the duckling bucket name. It is consultedBEFORE the stored DuckgresServer row on purpose: a row provisioned before thenaming fix carries a stale, locally-derived bucket that names an object storethat doesn't exist, and that stale value must not win. cp_bucket_for() alsoreconciles the row so it converges for next time.- 3. The stored DuckgresServer.bucket, only as a fallback when the control plane is+ 2. The stored DuckgresServer.bucket, only as a fallback when the control plane isunreachable/unconfigured — so a transient CP outage doesn't fail a run whosebucket is already known-good.@@ -235,18 +228,6 @@ def _resolve_duckling_target(team_id: int) -> DucklingTarget:org_id = _get_org_id_for_team(team_id)events_table, persons_table = _resolve_table_names(team_id)- catalog = get_ducklake_catalog_for_organization(org_id)- if catalog is not None and catalog.bucket:- bucket, bucket_region = catalog.bucket, catalog.bucket_region- return DucklingTarget(- team_id=team_id,- organization_id=org_id,- bucket=bucket,- bucket_region=bucket_region,- events_table=events_table,- persons_table=persons_table,- )-# Control plane first — authoritative, and rejects an org_id-mismatched status body.cp_bucket = managed_warehouse.cp_bucket_for(org_id)if cp_bucket:@@ -285,8 +266,8 @@ def _resolve_duckling_target(team_id: int) -> DucklingTarget:)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."+ f"No S3 bucket resolvable for org {org_id}: the control plane warehouse status named "+ f"none, and no stored DuckgresServer bucket to fall back to.")@@ -2327,10 +2308,10 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBadef duckling_events_daily_backfill_sensor(context: SensorEvaluationContext,) -> SensorResult:- """Discover teams with backfills enabled (DuckLakeBackfill) and create daily backfill partitions.+ """Discover teams with backfills enabled (DuckgresServerTeam) and create daily backfill partitions.This sensor runs periodically to:- 1. Find all teams with backfills enabled (DuckLakeBackfill)+ 1. Find all teams with backfills enabled (DuckgresServerTeam)2. Create partitions for yesterday's data (if not already exists)3. Trigger backfill runs for new partitions4. Retry failed partitions that already exist@@ -2343,7 +2324,7 @@ def duckling_events_daily_backfill_sensor(new_partitions: list[str] = []run_requests: list[RunRequest] = []- for backfill in DuckLakeBackfill.objects.filter(enabled=True):+ for backfill in DuckgresServerTeam.objects.filter(backfill_enabled=True):partition_key = f"{backfill.team_id}_{yesterday}"if partition_key not in existing:@@ -2442,7 +2423,7 @@ EVENTS_BACKFILL_MAX_PARTITIONS_PER_TICK = 100# Cap on per-team earliest-event ClickHouse lookups per tick. This is the only expensive# sensor op; it runs once per team ever, then the result is cached on the model row.EVENTS_BACKFILL_MAX_EARLIEST_LOOKUPS_PER_TICK = 5-# Stored in DuckLakeBackfill.earliest_event_date for a team with no events, so the sensor+# Stored in DuckgresServerTeam.earliest_event_date for a team with no events, so the sensor# caches "nothing to backfill" instead of re-querying every tick. Far enough in the future# that the generated months range is always empty._NO_HISTORY_SENTINEL = date(9999, 12, 31)@@ -2487,7 +2468,7 @@ def duckling_events_full_backfill_sensor(limit throttles to a handful of concurrent runs to protect ClickHouse):* ``earliest_event_date`` is resolved from ClickHouse ONCE per team and cached on the- ``DuckLakeBackfill`` row (bounded to EVENTS_BACKFILL_MAX_EARLIEST_LOOKUPS_PER_TICK+ ``DuckgresServerTeam`` row (bounded to EVENTS_BACKFILL_MAX_EARLIEST_LOOKUPS_PER_TICKlookups per tick), so the hot path issues no ClickHouse queries and an org's wholehistory can be enqueued in a few quick ticks instead of dripping 3 months / 10 min.* Candidate months are interleaved ROUND-ROBIN across all enabled teams (each team@@ -2503,9 +2484,9 @@ def duckling_events_full_backfill_sensor("""yesterday = (timezone.now() - timedelta(days=1)).date()- backfills = list(DuckLakeBackfill.objects.filter(enabled=True).order_by("team_id"))+ backfills = list(DuckgresServerTeam.objects.filter(backfill_enabled=True).order_by("team_id"))if not backfills:- context.log.info("No enabled DuckLakeBackfill entries found")+ context.log.info("No enabled DuckgresServerTeam entries found")return SensorResult(run_requests=[])# 1. Resolve + cache earliest_event_date for teams that don't have it yet. This is the@@ -2619,7 +2600,7 @@ duckling_events_backfill_job = define_asset_job(def duckling_persons_daily_backfill_sensor(context: SensorEvaluationContext,) -> SensorResult:- """Discover teams with backfills enabled (DuckLakeBackfill) and create daily persons partitions.+ """Discover teams with backfills enabled (DuckgresServerTeam) and create daily persons partitions.Similar to duckling_events_daily_backfill_sensor but for persons data.Uses _timestamp (Kafka ingestion time) for date filtering.@@ -2631,7 +2612,7 @@ def duckling_persons_daily_backfill_sensor(new_partitions: list[str] = []run_requests: list[RunRequest] = []- for backfill in DuckLakeBackfill.objects.filter(enabled=True):+ for backfill in DuckgresServerTeam.objects.filter(backfill_enabled=True):partition_key = f"{backfill.team_id}_{yesterday}"if partition_key not in existing:@@ -2721,9 +2702,9 @@ def duckling_persons_full_backfill_sensor(To restart from scratch, reset the cursor in Dagster UI:Sensors -> duckling_persons_full_backfill_sensor -> Reset cursor"""- backfills = list(DuckLakeBackfill.objects.filter(enabled=True).order_by("team_id"))+ backfills = list(DuckgresServerTeam.objects.filter(backfill_enabled=True).order_by("team_id"))if not backfills:- context.log.info("No enabled DuckLakeBackfill entries found")+ context.log.info("No enabled DuckgresServerTeam entries found")return SensorResult(run_requests=[])# Check existing partitionsdiff --git a/posthog/dags/test_events_backfill_to_duckling.py b/posthog/dags/test_events_backfill_to_duckling.pyindex bc2873e38b74..e13265321cc0 100644--- a/posthog/dags/test_events_backfill_to_duckling.py+++ b/posthog/dags/test_events_backfill_to_duckling.py@@ -73,10 +73,9 @@ class TestDucklingBackfillAlertRouting:class TestResolveDucklingTarget:@patch("posthog.dags.events_backfill_to_duckling._resolve_table_names", return_value=("events", "persons"))@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_resolves_bucket_from_control_plane(- self, mock_org: MagicMock, _mock_catalog: MagicMock, _mock_server: MagicMock, _mock_tables: MagicMock+ self, mock_org: MagicMock, _mock_server: MagicMock, _mock_tables: MagicMock):# The control plane is the authoritative owner of the bucket name.with patch(@@ -95,11 +94,8 @@ class TestResolveDucklingTarget:mock_cp.assert_called_once_with("org-1")@patch("posthog.dags.events_backfill_to_duckling._resolve_table_names", return_value=("events", "persons"))- @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, _mock_tables: MagicMock- ):+ def test_control_plane_wins_over_stale_stored_server_bucket(self, _mock_org: MagicMock, _mock_tables: 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")@@ -118,10 +114,9 @@ class TestResolveDucklingTarget:assert target.bucket == "posthog-duckling-org-1-mw-prod-us"@patch("posthog.dags.events_backfill_to_duckling._resolve_table_names", return_value=("events", "persons"))- @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, _mock_tables: MagicMock+ self, _mock_org: MagicMock, _mock_tables: 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")@@ -141,10 +136,9 @@ class TestResolveDucklingTarget:@patch("posthog.dags.events_backfill_to_duckling._resolve_table_names", return_value=("events", "persons"))@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, _mock_tables: MagicMock+ self, _mock_org: MagicMock, _mock_server: MagicMock, _mock_tables: MagicMock):with patch("products.data_warehouse.backend.presentation.views.managed_warehouse.cp_bucket_for",@@ -166,22 +160,22 @@ class TestResolveTableNames:return modeldef test_set_suffix_yields_dedicated_tables(self):- with patch("posthog.dags.events_backfill_to_duckling.DuckLakeBackfill", self._patch_suffix("alpha")):+ with patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam", self._patch_suffix("alpha")):assert _resolve_table_names(1) == ("events_alpha", "persons_alpha")def test_distinct_suffixes_isolate_two_teams(self):- with patch("posthog.dags.events_backfill_to_duckling.DuckLakeBackfill", self._patch_suffix("alpha")):+ with patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam", self._patch_suffix("alpha")):assert _resolve_table_names(1) == ("events_alpha", "persons_alpha")- with patch("posthog.dags.events_backfill_to_duckling.DuckLakeBackfill", self._patch_suffix("beta")):+ with patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam", self._patch_suffix("beta")):assert _resolve_table_names(2) == ("events_beta", "persons_beta")@parameterized.expand([("none", None), ("empty", "")])def test_unset_suffix_falls_back_to_shared_tables(self, _name, suffix):- with patch("posthog.dags.events_backfill_to_duckling.DuckLakeBackfill", self._patch_suffix(suffix)):+ with patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam", self._patch_suffix(suffix)):assert _resolve_table_names(1) == ("events", "persons")def test_unsafe_suffix_is_rejected(self):- with patch("posthog.dags.events_backfill_to_duckling.DuckLakeBackfill", self._patch_suffix("a-b; DROP")):+ with patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam", self._patch_suffix("a-b; DROP")):with pytest.raises(ValueError):_resolve_table_names(1)@@ -661,7 +655,7 @@ class TestFullBackfillSensorEarliestDate:])@patch("posthog.dags.events_backfill_to_duckling.get_earliest_event_date_for_team")- @patch("posthog.dags.events_backfill_to_duckling.DuckLakeBackfill")+ @patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam")@patch("posthog.dags.events_backfill_to_duckling.timezone")def test_earliest_date_clamped(self,@@ -697,7 +691,7 @@ class TestFullBackfillSensorEarliestDate:assert backfill.earliest_event_date == max(earliest_dt, datetime(2015, 1, 1)).date()@patch("posthog.dags.events_backfill_to_duckling.get_earliest_event_date_for_team")- @patch("posthog.dags.events_backfill_to_duckling.DuckLakeBackfill")+ @patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam")@patch("posthog.dags.events_backfill_to_duckling.timezone")def test_no_events_returns_empty(self, mock_tz, mock_backfill_cls, mock_get_earliest):from dagster import DagsterInstance, SensorResult, build_sensor_context@@ -738,7 +732,7 @@ class TestFullBackfillSensorEarliestDate:with (patch("posthog.dags.events_backfill_to_duckling.timezone") as mock_tz,- patch("posthog.dags.events_backfill_to_duckling.DuckLakeBackfill") as mock_cls,+ patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam") as mock_cls,patch("posthog.dags.events_backfill_to_duckling.get_earliest_event_date_for_team") as mock_ge,):mock_tz.now.return_value = now@@ -830,7 +824,7 @@ class TestFullBackfillSensorEarliestDate:with (patch("posthog.dags.events_backfill_to_duckling.timezone") as mock_tz,- patch("posthog.dags.events_backfill_to_duckling.DuckLakeBackfill") as mock_cls,+ patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam") as mock_cls,patch("posthog.dags.events_backfill_to_duckling.get_earliest_event_date_for_team"),):mock_tz.now.return_value = datetime(2020, 2, 10, 12, 0, 0)diff --git a/posthog/dags/tests/test_events_backfill_to_duckling.py b/posthog/dags/tests/test_events_backfill_to_duckling.pyindex 4e71020466a0..86775753f0c8 100644--- a/posthog/dags/tests/test_events_backfill_to_duckling.py+++ b/posthog/dags/tests/test_events_backfill_to_duckling.py@@ -16,15 +16,11 @@ class _FakeRow:class TestResolveDucklingTarget: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(- "posthog.dags.events_backfill_to_duckling.get_ducklake_catalog_for_organization", return_value=catalog- ),patch("posthog.dags.events_backfill_to_duckling.get_duckgres_server_for_organization", return_value=server),patch("products.data_warehouse.backend.presentation.views.managed_warehouse.cp_bucket_for",@@ -36,34 +32,6 @@ class TestResolveDucklingTarget:target = _resolve_duckling_target(team_id=123)return target, mock_cp- @parameterized.expand(- [- # name, catalog, server, expected_bucket, expected_region- (- "catalog_wins",- _FakeRow("catalog-bucket", "us-east-2"),- _FakeRow("server-bucket", "eu-west-1"),- "catalog-bucket",- "us-east-2",- ),- ]- )- def test_catalog_bucket_wins_without_consulting_control_plane(- self,- _name: str,- catalog: "_FakeRow | None",- server: "_FakeRow | None",- expected_bucket: str,- expected_region: str,- ) -> None:- target, mock_cp = self._resolve(catalog, server, cp_bucket="cp-bucket")-- assert target.bucket == expected_bucket- assert target.bucket_region == expected_region- assert target.organization_id == "org-1"- # 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,@@ -74,14 +42,15 @@ class TestResolveDucklingTarget:])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")+ target, mock_cp = self._resolve(server=server, cp_bucket="cp-bucket")mock_cp.assert_called_once_with("org-1")assert target.bucket == "cp-bucket"+ assert target.organization_id == "org-1"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)+ target, mock_cp = self._resolve(server=_FakeRow("server-bucket", "eu-west-1"), cp_bucket=None)mock_cp.assert_called_once_with("org-1")assert target.bucket == "server-bucket"@@ -89,15 +58,13 @@ class TestResolveDucklingTarget:@parameterized.expand([- ("no_rows", None, None),- ("server_with_null_bucket", None, _FakeRow(None, "us-east-1")),- ("both_blank", _FakeRow("", "us-east-1"), _FakeRow(None, "us-east-1")),+ ("no_rows", None),+ ("server_with_null_bucket", _FakeRow(None, "us-east-1")),+ ("server_blank", _FakeRow("", "us-east-1")),])- def test_raises_when_nothing_can_name_the_bucket(- self, _name: str, catalog: "_FakeRow | None", server: "_FakeRow | None"- ) -> None:+ def test_raises_when_nothing_can_name_the_bucket(self, _name: str, server: "_FakeRow | None") -> None:import pytestwith pytest.raises(ValueError, match="No S3 bucket resolvable"):- self._resolve(catalog, server, cp_bucket=None)+ self._resolve(server=server, cp_bucket=None)diff --git a/posthog/ducklake/common.py b/posthog/ducklake/common.pyindex 13cbb4290015..22e85f7e344d 100644--- a/posthog/ducklake/common.py+++ b/posthog/ducklake/common.py@@ -4,12 +4,13 @@ Two-tier config system:- **Dev mode** (USE_LOCAL_SETUP=True): every helper returns hardcoded localhostdefaults from the DEFAULTS / DUCKGRES_DEFAULTS dicts, optionally overriddenby environment variables. No database rows need to exist.-- **Production**: per-team config is read from the DuckLakeCatalog and- DuckgresServer models. The get_*_for_team() lookups return None only when- the row is genuinely missing; callers should treat that as an error or- provision the row via admin.+- **Production**: per-org config is read from the DuckgresServer model (which holds+ both the duckgres query-server connection and the separate DuckLake catalog+ connection). The get_*_for_organization() lookups return None only when the row is+ genuinely missing; callers should treat that as an error or provision the row via+ admin.-The `get_team_config()` and `get_duckgres_config()` entry-points encapsulate+The `get_org_config()` and `get_duckgres_config_for_org()` entry-points encapsulatethis branching so callers don't need to check the mode themselves."""@@ -26,7 +27,7 @@ import psycopgfrom psycopg import sqlif TYPE_CHECKING:- from posthog.ducklake.models import DuckgresServer, DuckLakeCatalog+ from posthog.ducklake.models import DuckgresServerfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema@@ -64,35 +65,21 @@ def get_config() -> dict[str, str]:return _get_config_from_env_strict()-def _catalog_to_config(catalog: DuckLakeCatalog) -> dict[str, str]:- config = catalog.to_public_config()- config["DUCKLAKE_RDS_PASSWORD"] = catalog.db_password+def _server_to_catalog_config(server: DuckgresServer) -> dict[str, str]:+ config = server.to_catalog_public_config()+ config["DUCKLAKE_RDS_PASSWORD"] = server.catalog_password or ""return configdef get_org_config(organization_id: str) -> dict[str, str]:- """Get DuckLake configuration for an organization from DuckLakeCatalog."""- if is_dev_mode():- return get_config()-- catalog = get_ducklake_catalog_for_organization(organization_id)- if catalog is not None:- return _catalog_to_config(catalog)- raise ValueError(f"No DuckLakeCatalog configured for organization {organization_id}")---def get_team_config(team_id: int) -> dict[str, str]:- """Get DuckLake configuration for a specific team from DuckLakeCatalog.-- Deprecated: use get_org_config() instead.- """+ """Get DuckLake catalog configuration for an organization from DuckgresServer."""if is_dev_mode():return get_config()- catalog = get_ducklake_catalog_for_team(team_id)- if catalog is not None:- return _catalog_to_config(catalog)- raise ValueError(f"No DuckLakeCatalog configured for team {team_id}")+ server = get_duckgres_server_for_organization(organization_id)+ if server is not None:+ return _server_to_catalog_config(server)+ raise ValueError(f"No DuckgresServer configured for organization {organization_id}")def is_dev_mode() -> bool:@@ -130,17 +117,6 @@ def _get_org_id_for_team(team_id: int) -> str:return str(team.organization_id)-def get_ducklake_catalog_by_team_org(team_id: int) -> DuckLakeCatalog | None:- """Look up DuckLakeCatalog via team_id → organization_id.-- Convenience wrapper for callers that have team_id but catalog is org-scoped.- """- if is_dev_mode():- return None- org_id = _get_org_id_for_team(team_id)- return get_ducklake_catalog_for_organization(org_id)--def get_duckgres_server_by_team_org(team_id: int) -> DuckgresServer | None:"""Look up DuckgresServer via team_id → organization_id.@@ -152,35 +128,6 @@ def get_duckgres_server_by_team_org(team_id: int) -> DuckgresServer | None:return get_duckgres_server_for_organization(org_id)-def get_ducklake_catalog_for_organization(organization_id: str) -> DuckLakeCatalog | None:- """Look up DuckLakeCatalog for an organization."""- if is_dev_mode():- return None-- from posthog.ducklake.models import DuckLakeCatalog-- try:- return DuckLakeCatalog.objects.get(organization_id=organization_id)- except DuckLakeCatalog.DoesNotExist:- return None---def get_ducklake_catalog_for_team(team_id: int) -> DuckLakeCatalog | None:- """Look up DuckLakeCatalog for a team.-- Deprecated: use get_ducklake_catalog_for_organization() instead.- """- if is_dev_mode():- return None-- from posthog.ducklake.models import DuckLakeCatalog-- try:- return DuckLakeCatalog.objects.get(team_id=team_id)- except DuckLakeCatalog.DoesNotExist:- return None--DUCKGRES_DEFAULTS: dict[str, str] = {"DUCKGRES_HOST": "localhost","DUCKGRES_PORT": "5432",@@ -217,20 +164,6 @@ def get_duckgres_config_for_org(organization_id: str) -> dict[str, str]:raise ValueError(f"No DuckgresServer configured for organization {organization_id}")-def get_duckgres_config(team_id: int) -> dict[str, str]:- """Get duckgres connection config for a specific team.-- Deprecated: use get_duckgres_config_for_org() instead.- """- if is_dev_mode():- return _duckgres_dev_config()-- server = get_duckgres_server_for_team(team_id)- if server is not None:- return _server_to_config(server)- raise ValueError(f"No DuckgresServer configured for team {team_id}")--def get_duckgres_server_for_organization(organization_id: str) -> DuckgresServer | None:"""Look up DuckgresServer for an organization."""if is_dev_mode():@@ -293,22 +226,6 @@ def upsert_duckgres_server_for_org(DUCKGRES_BUCKET_REGION = "us-east-1"-def get_duckgres_server_for_team(team_id: int) -> DuckgresServer | None:- """Look up DuckgresServer for a team.-- Deprecated: use get_duckgres_server_for_organization() instead.- """- if is_dev_mode():- return None-- from posthog.ducklake.models import DuckgresServer-- try:- return DuckgresServer.objects.get(team_id=team_id)- except DuckgresServer.DoesNotExist:- return None--def get_ducklake_connection_string(config: dict[str, str] | None = None) -> str:"""Build the DuckLake catalog connection string from config or environment variables."""if config is None:@@ -561,7 +478,7 @@ def validate_duckgres_identifier(identifier: str) -> None:Only alphanumeric characters and underscores are allowed. Mirrors theevents/persons duckling DAG's ``_validate_identifier`` so a user-supplied- ``DuckLakeBackfill.table_suffix`` is validated identically wherever it is+ ``DuckgresServerTeam.table_suffix`` is validated identically wherever it isinterpolated into DuckDB DDL."""if not identifier or not identifier.replace("_", "").isalnum():@@ -573,7 +490,7 @@ def duckgres_data_imports_schema(team_id: int) -> str:A DuckgresServer is org-scoped and hosts many teams, so each team needs itsown schema. Historically that was ``posthog_data_imports_team_{team_id}``.- When a team sets ``DuckLakeBackfill.table_suffix`` (the same field that+ When a team sets ``DuckgresServerTeam.table_suffix`` (the same field thatgoverns its events/persons tables), the data-import schema uses that suffixso one user-chosen identifier names all of a team's warehouse tables.@@ -584,9 +501,9 @@ def duckgres_data_imports_schema(team_id: int) -> str:that have already written a team's tables must trigger a re-prime (handledby the backfill state machine), not silently switch."""- from posthog.ducklake.models import DuckLakeBackfill+ from posthog.ducklake.models import DuckgresServerTeam- suffix = DuckLakeBackfill.objects.filter(team_id=team_id).values_list("table_suffix", flat=True).first()+ suffix = DuckgresServerTeam.objects.filter(team_id=team_id).values_list("table_suffix", flat=True).first()if not suffix:return f"posthog_data_imports_team_{team_id}"validate_duckgres_identifier(suffix)@@ -640,9 +557,9 @@ def enable_team_backfill(*, team_id: int, organization_id: str | UUID, table_nam"""Enable a team's warehouse backfill with a dedicated set of per-environment tables.The user-supplied ``table_name`` is used verbatim as the table suffix (validated, not- rewritten). Records first-class team↔duckling membership (DuckgresServerTeam) and persists- the suffix on the team's DuckLakeBackfill so the Dagster backfill writes to ``events_<suffix>``- / ``persons_<suffix>`` instead of the shared tables.+ rewritten). Records the team↔duckling membership and the backfill suffix on a single+ DuckgresServerTeam row so the Dagster backfill writes to ``events_<suffix>`` /+ ``persons_<suffix>`` instead of the shared tables.**Write-once.** The suffix is fixed when the backfill is first created and cannot be changedafterward — including switching a legacy NULL suffix (shared tables) to a real name. Changing@@ -653,9 +570,7 @@ def enable_team_backfill(*, team_id: int, organization_id: str | UUID, table_namand the suffix must be unique among the org's environments. Returns the suffix, or raisesDucklingBackfillEnableError with a user-facing message."""- from django.db import transaction-- from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam, DuckLakeBackfill+ from posthog.ducklake.models import DuckgresServer, DuckgresServerTeamerror = validate_table_suffix(table_name)if error:@@ -669,11 +584,10 @@ def enable_team_backfill(*, team_id: int, organization_id: str | UUID, table_nam"No managed warehouse is provisioned for this organization. Provision one first.")- existing = DuckLakeBackfill.objects.filter(team_id=team_id).first()+ existing = DuckgresServerTeam.objects.filter(team_id=team_id).first()if existing is not None:if existing.table_suffix == suffix:- # Same name — ensure membership is recorded, then leave the backfill untouched.- DuckgresServerTeam.objects.get_or_create(server=server, team_id=team_id)+ # Same name — already set up; idempotent no-op.return suffixcurrent = f"events_{existing.table_suffix}" if existing.table_suffix else "the shared tables"raise DucklingBackfillEnableError(@@ -682,7 +596,7 @@ def enable_team_backfill(*, team_id: int, organization_id: str | UUID, table_nam)collision = (- DuckLakeBackfill.objects.filter(team__organization_id=organization_id, table_suffix=suffix)+ DuckgresServerTeam.objects.filter(team__organization_id=organization_id, table_suffix=suffix).exclude(team_id=team_id).exists())@@ -691,9 +605,7 @@ def enable_team_backfill(*, team_id: int, organization_id: str | UUID, table_namf"The table name '{suffix}' is already used by another environment in this organization.")- with transaction.atomic():- DuckgresServerTeam.objects.get_or_create(server=server, team_id=team_id)- DuckLakeBackfill.objects.create(team_id=team_id, enabled=True, table_suffix=suffix)+ DuckgresServerTeam.objects.create(server=server, team_id=team_id, backfill_enabled=True, table_suffix=suffix)return suffix@@ -704,9 +616,9 @@ def get_team_backfill_state(team_id: int) -> dict[str, object]:safe to show) from one already backfilling (a row exists → show read-only, since the table isimmutable). ``table_suffix`` is None for legacy teams still on the shared tables."""- from posthog.ducklake.models import DuckLakeBackfill+ from posthog.ducklake.models import DuckgresServerTeam- backfill = DuckLakeBackfill.objects.filter(team_id=team_id).values("table_suffix").first()+ backfill = DuckgresServerTeam.objects.filter(team_id=team_id).values("table_suffix").first()if backfill is None:return {"has_backfill": False, "table_suffix": None}return {"has_backfill": True, "table_suffix": backfill["table_suffix"]}@@ -721,16 +633,12 @@ __all__ = ["enable_team_backfill","escape","get_config",- "get_ducklake_catalog_for_organization",- "get_ducklake_catalog_for_team","get_ducklake_connection_string","get_ducklake_data_path",- "get_duckgres_config","get_duckgres_config_for_org",+ "get_duckgres_server_by_team_org","get_duckgres_server_for_organization",- "get_duckgres_server_for_team","get_org_config",- "get_team_config","ensure_ducklake_catalog","initialize_ducklake","is_ducklake_catalog_reset_allowed",diff --git a/posthog/ducklake/models.py b/posthog/ducklake/models.pyindex a1bec1bb31c9..aca66374ae00 100644--- a/posthog/ducklake/models.py+++ b/posthog/ducklake/models.py@@ -6,81 +6,23 @@ from posthog.helpers.encrypted_fields import EncryptedTextFieldfrom posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel-class DuckLakeCatalog(CreatedMetaFields, UpdatedMetaFields, UUIDModel):- """Per-organization DuckLake catalog configuration.-- Stores database connection details and bucket configuration for orgs that need- isolated DuckLake catalogs (e.g., managed warehouse customers).-- For orgs without a DuckLakeCatalog entry, the system falls back to- environment variable configuration.- """-- # Deprecated: use organization instead. Kept nullable for backward compatibility.- team = models.OneToOneField(- "posthog.Team",- on_delete=models.CASCADE,- related_name="ducklake_catalog",- null=True,- blank=True,- )- organization = models.OneToOneField(- "posthog.Organization",- on_delete=models.CASCADE,- related_name="ducklake_catalog",- )-- # Database connection settings- db_host = models.CharField(max_length=255)- db_port = models.IntegerField(default=5432)- db_database = models.CharField(max_length=255, default="ducklake")- db_username = models.CharField(max_length=255)- db_password = EncryptedTextField(max_length=500)-- # Bucket settings (no secrets - credentials come from IRSA or storage.py)- bucket = models.CharField(max_length=255)- bucket_region = models.CharField(max_length=50, default="us-east-1")-- class Meta:- db_table = "posthog_ducklakecatalog"- verbose_name = "DuckLake catalog"- verbose_name_plural = "DuckLake catalogs"-- def to_public_config(self) -> dict[str, str]:- """Convert to a config dict without secrets (safe for logging/debugging)."""- return {- "DUCKLAKE_RDS_HOST": self.db_host,- "DUCKLAKE_RDS_PORT": str(self.db_port),- "DUCKLAKE_RDS_DATABASE": self.db_database,- "DUCKLAKE_RDS_USERNAME": self.db_username,- "DUCKLAKE_BUCKET": self.bucket,- "DUCKLAKE_BUCKET_REGION": self.bucket_region,- "DUCKLAKE_S3_ACCESS_KEY": "",- "DUCKLAKE_S3_SECRET_KEY": "",- }--class DuckgresServer(CreatedMetaFields, UpdatedMetaFields, UUIDModel):- """Per-organization duckgres query server connection details.+ """Per-organization duckgres query server + DuckLake catalog connection details.- Duckgres is a Postgres-protocol-compatible DuckDB server, separate from- the DuckLake catalog Postgres database. Each org that uses duckgres for- copy workflows needs its own connection entry.+ Duckgres is a Postgres-protocol-compatible DuckDB server. Each org that uses+ duckgres for copy workflows/backfills needs its own connection entry. The+ DuckLake catalog is a *separate* Postgres metadata store (the duckgres server's+ query connection is not the same endpoint), so its connection is recorded here+ too under the ``catalog_*`` fields."""- # Deprecated: use organization instead. Kept nullable for backward compatibility.- team = models.OneToOneField(- "posthog.Team",- on_delete=models.CASCADE,- related_name="duckgres_server",- null=True,- blank=True,- )organization = models.OneToOneField("posthog.Organization",on_delete=models.CASCADE,related_name="duckgres_server",)++ # Duckgres query-server connection.host = models.CharField(max_length=255)port = models.IntegerField(default=5432)flight_port = models.IntegerField(default=8815)@@ -88,6 +30,15 @@ class DuckgresServer(CreatedMetaFields, UpdatedMetaFields, UUIDModel):username = models.CharField(max_length=255)password = EncryptedTextField(max_length=500)+ # DuckLake catalog Postgres connection — a separate metadata store from the+ # query server above. Nullable: an org may have a provisioned server before its+ # catalog row is recorded (the dev/env-var path doesn't need these at all).+ catalog_host = models.CharField(max_length=255, null=True, blank=True)+ catalog_port = models.IntegerField(default=5432)+ catalog_database = models.CharField(max_length=255, default="ducklake")+ catalog_username = models.CharField(max_length=255, null=True, blank=True)+ catalog_password = EncryptedTextField(max_length=500, null=True, blank=True)+# S3 bucket backing the org's managed warehouse (no secrets — access is via IRSA / the# ClickHouse EC2 role). Written at provision time so the duckling backfill reads the# authoritative bucket name instead of re-deriving it. Nullable for rows provisioned@@ -102,13 +53,27 @@ class DuckgresServer(CreatedMetaFields, UpdatedMetaFields, UUIDModel):verbose_name = "Duckgres server"verbose_name_plural = "Duckgres servers"+ def to_catalog_public_config(self) -> dict[str, str]:+ """DuckLake catalog config without secrets (safe for logging/debugging)."""+ return {+ "DUCKLAKE_RDS_HOST": self.catalog_host or "",+ "DUCKLAKE_RDS_PORT": str(self.catalog_port),+ "DUCKLAKE_RDS_DATABASE": self.catalog_database,+ "DUCKLAKE_RDS_USERNAME": self.catalog_username or "",+ "DUCKLAKE_BUCKET": self.bucket or "",+ "DUCKLAKE_BUCKET_REGION": self.bucket_region or "",+ "DUCKLAKE_S3_ACCESS_KEY": "",+ "DUCKLAKE_S3_SECRET_KEY": "",+ }+class DuckgresServerTeam(CreatedMetaFields, UpdatedMetaFields, UUIDModel):- """Per-team membership of an org's Duckgres warehouse.+ """Per-team membership of an org's Duckgres warehouse + that team's backfill state.- A DuckgresServer is org-scoped and can host many teams (1->n). This model- records which teams live in a given server, and is the home for any future- team-specific server config.+ A DuckgresServer is org-scoped and can host many teams (1->n). This model records+ which teams live in a given server and carries the team-specific warehouse backfill+ configuration (whether backfills are enabled, the per-team table suffix, and the+ cached backfill floor)."""server = models.ForeignKey(@@ -121,27 +86,7 @@ class DuckgresServerTeam(CreatedMetaFields, UpdatedMetaFields, UUIDModel):on_delete=models.CASCADE,related_name="duckgres_server_team",)-- class Meta:- db_table = "posthog_duckgresserverteam"- verbose_name = "Duckgres server team"- verbose_name_plural = "Duckgres server teams"---class DuckLakeBackfill(CreatedMetaFields, UpdatedMetaFields, UUIDModel):- """Per-team enablement of DuckLake warehouse backfills.-- Controls which teams should be backfilled by the Dagster duckling sensors.- Catalog credentials are resolved from the team's organization via- DuckLakeCatalog/DuckgresServer — this model only tracks enablement.- """-- team = models.OneToOneField(- "posthog.Team",- on_delete=models.CASCADE,- related_name="ducklake_backfill",- )- enabled = models.BooleanField(+ backfill_enabled = models.BooleanField(default=True,help_text="Whether warehouse backfills are enabled for this team",)@@ -161,6 +106,6 @@ class DuckLakeBackfill(CreatedMetaFields, UpdatedMetaFields, UUIDModel):)class Meta:- db_table = "posthog_ducklakebackfill"- verbose_name = "DuckLake backfill"- verbose_name_plural = "DuckLake backfills"+ db_table = "posthog_duckgresserverteam"+ verbose_name = "Duckgres server team"+ verbose_name_plural = "Duckgres server teams"diff --git a/posthog/ducklake/test_backfill_duckgresserverteam_migration.py b/posthog/ducklake/test_backfill_duckgresserverteam_migration.pydeleted file mode 100644index ae536dafb0b8..000000000000--- a/posthog/ducklake/test_backfill_duckgresserverteam_migration.py+++ /dev/null@@ -1,55 +0,0 @@-import importlib--import pytest--from django.apps import apps as global_apps--from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam, DuckLakeBackfill-from posthog.models import Organization, Team--# The migration module name starts with a digit, so it can't be imported with a plain `import`.-_migration = importlib.import_module("posthog.migrations.1233_backfill_duckgresserverteam")-backfill_duckgres_server_teams = _migration.backfill_duckgres_server_teams---def _server(org: Organization) -> DuckgresServer:- return DuckgresServer.objects.create(- organization=org, host="h", port=5432, database="ducklake", username="root", password="x"- )---class TestBackfillDuckgresServerTeams:- def test_links_existing_backfill_teams_to_their_org_server(self):- org = Organization.objects.create(name="Org")- team = Team.objects.create(organization=org)- server = _server(org)- DuckLakeBackfill.objects.create(team=team, table_suffix=None)-- backfill_duckgres_server_teams(global_apps, None)-- link = DuckgresServerTeam.objects.get(team_id=team.id)- assert link.server_id == server.id- # Legacy rows keep writing to the shared tables — the backfill never sets a suffix.- assert DuckLakeBackfill.objects.get(team_id=team.id).table_suffix is None-- def test_skips_teams_whose_org_has_no_server(self):- org = Organization.objects.create(name="Org")- team = Team.objects.create(organization=org)- DuckLakeBackfill.objects.create(team=team)-- backfill_duckgres_server_teams(global_apps, None)-- assert not DuckgresServerTeam.objects.filter(team_id=team.id).exists()-- def test_is_idempotent_and_preserves_existing_membership(self):- org = Organization.objects.create(name="Org")- team = Team.objects.create(organization=org)- server = _server(org)- DuckLakeBackfill.objects.create(team=team)- DuckgresServerTeam.objects.create(server=server, team=team)-- backfill_duckgres_server_teams(global_apps, None)- backfill_duckgres_server_teams(global_apps, None)-- assert DuckgresServerTeam.objects.filter(team_id=team.id).count() == 1diff --git a/posthog/ducklake/test_common.py b/posthog/ducklake/test_common.pyindex 0c4e1508007f..83766b437b5f 100644--- a/posthog/ducklake/test_common.py+++ b/posthog/ducklake/test_common.py@@ -13,7 +13,7 @@ from posthog.ducklake.common import (reset_ducklake_catalog,upsert_duckgres_server_for_org,)-from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam, DuckLakeBackfill+from posthog.ducklake.models import DuckgresServer, DuckgresServerTeamfrom posthog.models import Organization, Team@@ -54,10 +54,10 @@ class TestEnableTeamBackfill:suffix = enable_team_backfill(team_id=team.id, organization_id=org.id, table_name="my_prod_env")assert suffix == "my_prod_env"- assert DuckgresServerTeam.objects.filter(server=server, team_id=team.id).exists()- backfill = DuckLakeBackfill.objects.get(team_id=team.id)- assert backfill.enabled is True- assert backfill.table_suffix == "my_prod_env"+ link = DuckgresServerTeam.objects.get(team_id=team.id)+ assert link.server_id == server.id+ assert link.backfill_enabled is True+ assert link.table_suffix == "my_prod_env"def test_rejects_an_invalid_table_name(self):org = Organization.objects.create(name="Org")@@ -71,8 +71,8 @@ class TestEnableTeamBackfill:org = Organization.objects.create(name="Org")team_a = Team.objects.create(organization=org)team_b = Team.objects.create(organization=org)- self._server(org)- DuckLakeBackfill.objects.create(team=team_a, table_suffix="shared")+ server = self._server(org)+ DuckgresServerTeam.objects.create(server=server, team=team_a, table_suffix="shared")with pytest.raises(DucklingBackfillEnableError):enable_team_backfill(team_id=team_b.id, organization_id=org.id, table_name="shared")@@ -86,7 +86,6 @@ class TestEnableTeamBackfill:suffix = enable_team_backfill(team_id=team.id, organization_id=org.id, table_name="prod")assert suffix == "prod"- assert DuckLakeBackfill.objects.filter(team_id=team.id).count() == 1assert DuckgresServerTeam.objects.filter(team_id=team.id).count() == 1def test_refuses_to_change_a_set_suffix(self):@@ -97,17 +96,17 @@ class TestEnableTeamBackfill:with pytest.raises(DucklingBackfillEnableError):enable_team_backfill(team_id=team.id, organization_id=org.id, table_name="second")- assert DuckLakeBackfill.objects.get(team_id=team.id).table_suffix == "first"+ assert DuckgresServerTeam.objects.get(team_id=team.id).table_suffix == "first"def test_refuses_to_set_a_suffix_on_a_legacy_shared_team(self):org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)- self._server(org)- DuckLakeBackfill.objects.create(team=team, enabled=True, table_suffix=None)+ server = self._server(org)+ DuckgresServerTeam.objects.create(server=server, team=team, backfill_enabled=True, table_suffix=None)with pytest.raises(DucklingBackfillEnableError):enable_team_backfill(team_id=team.id, organization_id=org.id, table_name="new_name")- assert DuckLakeBackfill.objects.get(team_id=team.id).table_suffix is None+ assert DuckgresServerTeam.objects.get(team_id=team.id).table_suffix is Nonedef test_requires_a_provisioned_server(self):org = Organization.objects.create(name="Org")@@ -119,20 +118,27 @@ class TestEnableTeamBackfill:@pytest.mark.django_dbclass TestGetTeamBackfillState:+ def _server_team(self, table_suffix: str | None) -> Team:+ org = Organization.objects.create(name="Org")+ team = Team.objects.create(organization=org)+ server = DuckgresServer.objects.create(+ organization=org, host="h", port=5432, database="ducklake", username="root", password="x"+ )+ DuckgresServerTeam.objects.create(server=server, team=team, table_suffix=table_suffix)+ return team+def test_no_backfill(self):team = Team.objects.create(organization=Organization.objects.create(name="Org"))assert get_team_backfill_state(team.id) == {"has_backfill": False, "table_suffix": None}def test_legacy_shared_backfill(self):- team = Team.objects.create(organization=Organization.objects.create(name="Org"))- DuckLakeBackfill.objects.create(team=team, table_suffix=None)+ team = self._server_team(table_suffix=None)assert get_team_backfill_state(team.id) == {"has_backfill": True, "table_suffix": None}def test_suffixed_backfill(self):- team = Team.objects.create(organization=Organization.objects.create(name="Org"))- DuckLakeBackfill.objects.create(team=team, table_suffix="prod")+ team = self._server_team(table_suffix="prod")assert get_team_backfill_state(team.id) == {"has_backfill": True, "table_suffix": "prod"}@@ -357,6 +363,17 @@ class TestDuckgresDataImportsSchema:org = Organization.objects.create(name="o")return Team.objects.create(organization=org, name="t")+ def _server_team(self, team: Team, table_suffix: str | None) -> DuckgresServerTeam:+ server = DuckgresServer.objects.create(+ organization_id=team.organization_id,+ host="h",+ port=5432,+ database="ducklake",+ username="root",+ password="x",+ )+ return DuckgresServerTeam.objects.create(server=server, team=team, table_suffix=table_suffix)+def test_falls_back_to_team_id_when_no_backfill_row(self):from posthog.ducklake.common import duckgres_data_imports_schema@@ -365,27 +382,24 @@ class TestDuckgresDataImportsSchema:def test_falls_back_to_team_id_when_suffix_null_or_empty(self):from posthog.ducklake.common import duckgres_data_imports_schema- from posthog.ducklake.models import DuckLakeBackfillteam = self._team()- DuckLakeBackfill.objects.create(team=team, table_suffix=None)+ link = self._server_team(team, table_suffix=None)assert duckgres_data_imports_schema(team.id) == f"posthog_data_imports_team_{team.id}"- DuckLakeBackfill.objects.filter(team=team).update(table_suffix="")+ DuckgresServerTeam.objects.filter(pk=link.pk).update(table_suffix="")assert duckgres_data_imports_schema(team.id) == f"posthog_data_imports_team_{team.id}"def test_uses_suffix_when_set(self):from posthog.ducklake.common import duckgres_data_imports_schema- from posthog.ducklake.models import DuckLakeBackfillteam = self._team()- DuckLakeBackfill.objects.create(team=team, table_suffix="us_prod")+ self._server_team(team, table_suffix="us_prod")assert duckgres_data_imports_schema(team.id) == "posthog_data_imports_us_prod"def test_rejects_unsafe_suffix(self):from posthog.ducklake.common import duckgres_data_imports_schema- from posthog.ducklake.models import DuckLakeBackfillteam = self._team()- DuckLakeBackfill.objects.create(team=team, table_suffix="a;drop")+ self._server_team(team, table_suffix="a;drop")with pytest.raises(ValueError):duckgres_data_imports_schema(team.id)diff --git a/posthog/migrations/1240_consolidate_duckgres_models.py b/posthog/migrations/1240_consolidate_duckgres_models.pynew file mode 100644index 000000000000..7c869f699a53--- /dev/null+++ b/posthog/migrations/1240_consolidate_duckgres_models.py@@ -0,0 +1,68 @@+from django.db import migrations, models++import posthog.helpers.encrypted_fields+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1239_migrate_approvals_models"),+ ]++ operations = [+ # Catalog connection moves onto DuckgresServer (the DuckLake catalog is a separate+ # Postgres store from the duckgres query server, so its connection is preserved).+ migrations.AddField(+ model_name="duckgresserver",+ name="catalog_host",+ field=models.CharField(blank=True, max_length=255, null=True),+ ),+ migrations.AddField(+ model_name="duckgresserver",+ name="catalog_port",+ field=models.IntegerField(default=5432),+ ),+ migrations.AddField(+ model_name="duckgresserver",+ name="catalog_database",+ field=models.CharField(default="ducklake", max_length=255),+ ),+ migrations.AddField(+ model_name="duckgresserver",+ name="catalog_username",+ field=models.CharField(blank=True, max_length=255, null=True),+ ),+ migrations.AddField(+ model_name="duckgresserver",+ name="catalog_password",+ field=posthog.helpers.encrypted_fields.EncryptedTextField(blank=True, max_length=500, null=True),+ ),+ # Backfill state moves onto DuckgresServerTeam (one row per team — the same row that+ # records the team's duckling membership).+ migrations.AddField(+ model_name="duckgresserverteam",+ name="backfill_enabled",+ field=models.BooleanField(default=True, help_text="Whether warehouse backfills are enabled for this team"),+ ),+ migrations.AddField(+ model_name="duckgresserverteam",+ name="table_suffix",+ field=models.CharField(+ blank=True,+ help_text="Suffix for this team's warehouse tables in the duckling (events_<suffix>, persons_<suffix>). "+ "User-supplied; falls back to the shared tables when unset.",+ max_length=63,+ null=True,+ ),+ ),+ migrations.AddField(+ model_name="duckgresserverteam",+ name="earliest_event_date",+ field=models.DateField(+ blank=True,+ help_text="Cached earliest event date (clamped to the backfill floor) used to size the historical "+ "backfill range. Populated lazily by the full-backfill sensor so it never re-queries ClickHouse; "+ "leave unset to have the sensor resolve and store it on its next tick.",+ null=True,+ ),+ ),+ ]diff --git a/posthog/migrations/1241_consolidate_duckgres_models_data.py b/posthog/migrations/1241_consolidate_duckgres_models_data.pynew file mode 100644index 000000000000..e2bd5151a0c1--- /dev/null+++ b/posthog/migrations/1241_consolidate_duckgres_models_data.py@@ -0,0 +1,64 @@+from django.db import migrations+++def merge_catalog_into_server(apps, schema_editor):+ """Copy each DuckLakeCatalog's connection + bucket onto its org's DuckgresServer.++ Every catalog maps 1:1 to an existing server by organization_id (verified against prod).+ The catalog's bucket wins over any value already on the server — this preserves the older+ catalog-first runtime resolution, so a team's backfill keeps reading the same bucket it+ reads today. The control plane self-heal still reconciles server.bucket on read afterward.+ """+ DuckLakeCatalog = apps.get_model("posthog", "DuckLakeCatalog")+ DuckgresServer = apps.get_model("posthog", "DuckgresServer")++ servers_by_org = {server.organization_id: server for server in DuckgresServer.objects.all()}+ for catalog in DuckLakeCatalog.objects.all().iterator():+ server = servers_by_org.get(catalog.organization_id)+ if server is None:+ # No server for this org — nothing to merge onto (none in prod).+ continue+ server.catalog_host = catalog.db_host+ server.catalog_port = catalog.db_port+ server.catalog_database = catalog.db_database+ server.catalog_username = catalog.db_username+ server.catalog_password = catalog.db_password+ update_fields = ["catalog_host", "catalog_port", "catalog_database", "catalog_username", "catalog_password"]+ if catalog.bucket:+ server.bucket = catalog.bucket+ server.bucket_region = catalog.bucket_region+ update_fields += ["bucket", "bucket_region"]+ server.save(update_fields=update_fields)+++def merge_backfill_into_server_team(apps, schema_editor):+ """Copy each DuckLakeBackfill onto the team's existing DuckgresServerTeam row.++ The backfill teams are the exact set of server-team teams (verified against prod), so every+ backfill maps 1:1 to an existing membership row. A backfill whose team has no membership row+ (none in prod) is skipped — DuckgresServerTeam.server is non-null and there is nothing to+ attach it to.+ """+ DuckLakeBackfill = apps.get_model("posthog", "DuckLakeBackfill")+ DuckgresServerTeam = apps.get_model("posthog", "DuckgresServerTeam")++ links_by_team = {link.team_id: link for link in DuckgresServerTeam.objects.all()}+ for backfill in DuckLakeBackfill.objects.all().iterator():+ link = links_by_team.get(backfill.team_id)+ if link is None:+ continue+ link.backfill_enabled = backfill.enabled+ link.table_suffix = backfill.table_suffix+ link.earliest_event_date = backfill.earliest_event_date+ link.save(update_fields=["backfill_enabled", "table_suffix", "earliest_event_date"])+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1240_consolidate_duckgres_models"),+ ]++ operations = [+ migrations.RunPython(merge_catalog_into_server, migrations.RunPython.noop),+ migrations.RunPython(merge_backfill_into_server_team, migrations.RunPython.noop),+ ]diff --git a/posthog/migrations/1242_consolidate_duckgres_models_drop.py b/posthog/migrations/1242_consolidate_duckgres_models_drop.pynew file mode 100644index 000000000000..fa866a81b3cd--- /dev/null+++ b/posthog/migrations/1242_consolidate_duckgres_models_drop.py@@ -0,0 +1,35 @@+from django.db import migrations+++class Migration(migrations.Migration):+ """Remove the folded-in models from Django state only.++ The data has already moved onto DuckgresServer / DuckgresServerTeam (1241). Here we drop+ DuckLakeCatalog, DuckLakeBackfill, and the deprecated DuckgresServer.team from Django's+ *state* but emit no SQL, so the tables/column physically remain. This keeps old code+ (still reading those tables during a rolling deploy) working; a follow-up migration drops+ the physical objects once every worker is on the new code. See+ docs/.../safe-django-migrations.md#dropping-tables.+ """++ dependencies = [+ ("posthog", "1241_consolidate_duckgres_models_data"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.RemoveField(+ model_name="duckgresserver",+ name="team",+ ),+ migrations.DeleteModel(+ name="DuckLakeCatalog",+ ),+ migrations.DeleteModel(+ name="DuckLakeBackfill",+ ),+ ],+ database_operations=[],+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 379e354ae555..0cb5724cd28f 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1239_migrate_approvals_models+1242_consolidate_duckgres_models_dropdiff --git a/posthog/models/__init__.py b/posthog/models/__init__.pyindex 07dc14d23531..4a6f1f9d5147 100644--- a/posthog/models/__init__.py+++ b/posthog/models/__init__.py@@ -15,7 +15,7 @@ from .comment import Commentfrom .core_event import CoreEventfrom .data_deletion_request import DataDeletionRequestfrom .data_color_theme import DataColorTheme-from ..ducklake.models import DuckgresServer, DuckgresServerTeam, DuckLakeBackfill, DuckLakeCatalog+from ..ducklake.models import DuckgresServer, DuckgresServerTeamfrom .element import Elementfrom .element_group import ElementGroupfrom .entity import Entity@@ -101,8 +101,6 @@ __all__ = ["DeletionType","DuckgresServer","DuckgresServerTeam",- "DuckLakeBackfill",- "DuckLakeCatalog","Element","ElementGroup","Entity",diff --git a/posthog/templates/admin/posthog/duckgres_server/deprovision_confirm.html b/posthog/templates/admin/posthog/duckgres_server/deprovision_confirm.htmlindex e83017d5464f..57f0b15a9b93 100644--- a/posthog/templates/admin/posthog/duckgres_server/deprovision_confirm.html+++ b/posthog/templates/admin/posthog/duckgres_server/deprovision_confirm.html@@ -5,7 +5,7 @@<p><strong>Deprovision the managed warehouse for organization <code>{{ server.organization_id }}</code>?</strong></p><p>This makes a real control-plane <code>/deprovision</code> call for server <code>{{ server.host }}</code>and tears down the org's managed warehouse. <strong>This cannot be undone.</strong> The-<code>DuckgresServer</code> / <code>DuckgresServerTeam</code> / <code>DuckLakeBackfill</code> rows are+<code>DuckgresServer</code> / <code>DuckgresServerTeam</code> rows areleft in place for the record — delete them separately if needed.</p><form method="post">diff --git a/posthog/templates/admin/posthog/duckgres_server/enable_backfill_form.html b/posthog/templates/admin/posthog/duckgres_server/enable_backfill_form.htmlindex d4cb4e4b7979..9f0cb9b20d85 100644--- a/posthog/templates/admin/posthog/duckgres_server/enable_backfill_form.html+++ b/posthog/templates/admin/posthog/duckgres_server/enable_backfill_form.html@@ -3,8 +3,8 @@{% block content %}<p>Add another team to this organization's existing managed warehouse. Runs the same flow as the-in-product enable-backfill API: records the team's <code>DuckgresServerTeam</code> membership and a-<code>DuckLakeBackfill</code> with its own per-environment table suffix. The organization's feature+in-product enable-backfill API: records the team's <code>DuckgresServerTeam</code> membership with its+own per-environment table suffix. The organization's featureflag is not required here.</p><p>Organization: <code>{{ server.organization_id }}</code> — server <code>{{ server.host }}</code></p>diff --git a/posthog/templates/admin/posthog/duckgres_server/provision_form.html b/posthog/templates/admin/posthog/duckgres_server/provision_form.htmlindex 57258c1313a7..80ef6c16a37e 100644--- a/posthog/templates/admin/posthog/duckgres_server/provision_form.html+++ b/posthog/templates/admin/posthog/duckgres_server/provision_form.html@@ -4,7 +4,7 @@{% block content %}<p>Provision a new managed warehouse for an organization and its first team. This runs the sameflow as the in-product provision API: the duckgres control-plane <code>/provision</code> call, then-the <code>DuckgresServer</code>, <code>DuckgresServerTeam</code>, and <code>DuckLakeBackfill</code>+the <code>DuckgresServer</code> and <code>DuckgresServerTeam</code>records for the team. The organization's <code>data-warehouse-scene</code> feature flag is<strong>not</strong> required here.</p><p><strong>This makes a real control-plane call.</strong> In environments wherediff --git a/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py b/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.pyindex 770e76092246..851fcb66df5d 100644--- a/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py+++ b/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py@@ -19,9 +19,8 @@ from posthog.ducklake.common import (duckgres_data_imports_schema,duckgres_data_imports_table_name,get_config,+ get_duckgres_server_by_team_org,get_duckgres_server_for_organization,- get_ducklake_catalog_by_team_org,- get_ducklake_catalog_for_organization,is_dev_mode,)from posthog.ducklake.storage import (@@ -305,12 +304,12 @@ def _copy_data_imports_via_duckdb(inputs: DuckLakeCopyDataImportsActivityInputs,def _copy_data_imports_via_duckgres(inputs: DuckLakeCopyDataImportsActivityInputs, logger: typing.Any) -> None:"""Stage Delta files and create the DuckLake table via duckgres."""org_id = _get_org_id_for_team(inputs.team_id)- catalog = get_ducklake_catalog_for_organization(org_id)server = get_duckgres_server_for_organization(org_id)- if catalog is None:- raise ApplicationError(f"No DuckLakeCatalog configured for team {inputs.team_id}", non_retryable=True)if server is None:raise ApplicationError(f"No DuckgresServer configured for team {inputs.team_id}", non_retryable=True)+ bucket = server.bucket+ if not bucket:+ raise ApplicationError(f"No S3 bucket configured for team {inputs.team_id}", non_retryable=True)if not inputs.model.staging_uri:raise ApplicationError(f"No staging_uri for model {inputs.model.model_label}", non_retryable=True)@@ -321,7 +320,7 @@ def _copy_data_imports_via_duckgres(inputs: DuckLakeCopyDataImportsActivityInput)stage_delta_table(source_uri=inputs.model.source_table_uri,- catalog_bucket=catalog.bucket,+ catalog_bucket=bucket,organization_id=org_id,)@@ -353,8 +352,8 @@ class DuckLakeDataImportsStagingCleanupInputs:def cleanup_data_imports_staging_activity(inputs: DuckLakeDataImportsStagingCleanupInputs) -> None:"""Clean up staged Delta files after successful verification."""bind_contextvars(team_id=inputs.team_id)- catalog = get_ducklake_catalog_by_team_org(inputs.team_id)- if catalog is None:+ server = get_duckgres_server_by_team_org(inputs.team_id)+ if server is None:returncleanup_staged_files(staging_uri=inputs.staging_uri,@@ -366,11 +365,13 @@ def _resolve_data_imports_staging_uri(source_uri: str, *, team_id: int) -> str |if is_dev_mode():return None- catalog = get_ducklake_catalog_by_team_org(team_id)- if catalog is None:- raise ApplicationError(f"No DuckLakeCatalog configured for team {team_id}", non_retryable=True)+ server = get_duckgres_server_by_team_org(team_id)+ if server is None:+ raise ApplicationError(f"No DuckgresServer configured for team {team_id}", non_retryable=True)+ if not server.bucket:+ raise ApplicationError(f"No S3 bucket configured for team {team_id}", non_retryable=True)- return compute_staging_uri(source_uri, catalog.bucket)+ return compute_staging_uri(source_uri, server.bucket)def _detect_data_imports_partition_column(table_uri: str, *, team_id: int) -> str | None:diff --git a/posthog/temporal/ducklake/ducklake_copy_data_modeling_workflow.py b/posthog/temporal/ducklake/ducklake_copy_data_modeling_workflow.pyindex e8d091bbb022..c43f408d9b85 100644--- a/posthog/temporal/ducklake/ducklake_copy_data_modeling_workflow.py+++ b/posthog/temporal/ducklake/ducklake_copy_data_modeling_workflow.py@@ -11,11 +11,11 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.ducklake.common import (_get_org_id_for_team,+ _server_to_catalog_config,attach_catalog,get_config,+ get_duckgres_server_by_team_org,get_duckgres_server_for_organization,- get_ducklake_catalog_by_team_org,- get_ducklake_catalog_for_organization,is_dev_mode,sanitize_ducklake_identifier,)@@ -160,9 +160,9 @@ async def prepare_data_modeling_ducklake_metadata_activity(staging_uri: str | None = Noneif not is_dev_mode():- catalog = await database_sync_to_async(get_ducklake_catalog_by_team_org)(inputs.team_id)- if catalog:- staging_uri = compute_staging_uri(model.table_uri, catalog.bucket)+ server = await database_sync_to_async(get_duckgres_server_by_team_org)(inputs.team_id)+ if server and server.bucket:+ staging_uri = compute_staging_uri(model.table_uri, server.bucket)model_list.append(DuckLakeCopyModelMetadata(@@ -242,13 +242,12 @@ def verify_ducklake_copy_activity(inputs: DuckLakeCopyActivityInputs) -> list[Duconfig = get_config()configure_connection(conn)else:- catalog = get_ducklake_catalog_by_team_org(inputs.team_id)- if catalog is None:+ server = get_duckgres_server_by_team_org(inputs.team_id)+ if server is None:raise ApplicationError(- f"No DuckLakeCatalog configured for team {inputs.team_id}", non_retryable=True+ f"No DuckgresServer configured for team {inputs.team_id}", non_retryable=True)- config = catalog.to_public_config()- config["DUCKLAKE_RDS_PASSWORD"] = catalog.db_password+ config = _server_to_catalog_config(server)configure_connection(conn)_attach_ducklake_catalog(conn, config, alias=alias)@@ -501,12 +500,12 @@ class DuckLakeCopyDataModelingWorkflow(PostHogWorkflow):def _copy_data_modeling_via_duckgres(inputs: DuckLakeCopyActivityInputs, logger) -> None:"""Stage Delta files and create the DuckLake table via duckgres."""org_id = _get_org_id_for_team(inputs.team_id)- catalog = get_ducklake_catalog_for_organization(org_id)server = get_duckgres_server_for_organization(org_id)- if catalog is None:- raise ApplicationError(f"No DuckLakeCatalog configured for team {inputs.team_id}", non_retryable=True)if server is None:raise ApplicationError(f"No DuckgresServer configured for team {inputs.team_id}", non_retryable=True)+ bucket = server.bucket+ if not bucket:+ raise ApplicationError(f"No S3 bucket configured for team {inputs.team_id}", non_retryable=True)if not inputs.model.staging_uri:raise ApplicationError(f"No staging_uri for model {inputs.model.model_label}", non_retryable=True)@@ -517,7 +516,7 @@ def _copy_data_modeling_via_duckgres(inputs: DuckLakeCopyActivityInputs, logger))stage_delta_table(source_uri=inputs.model.source_table_uri,- catalog_bucket=catalog.bucket,+ catalog_bucket=bucket,organization_id=org_id,)@@ -549,8 +548,8 @@ class DuckLakeDataModelingStagingCleanupInputs:def cleanup_data_modeling_staging_activity(inputs: DuckLakeDataModelingStagingCleanupInputs) -> None:"""Clean up staged Delta files after successful verification."""bind_contextvars(team_id=inputs.team_id)- catalog = get_ducklake_catalog_by_team_org(inputs.team_id)- if catalog is None:+ server = get_duckgres_server_by_team_org(inputs.team_id)+ if server is None:returncleanup_staged_files(staging_uri=inputs.staging_uri,diff --git a/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.py b/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.pyindex 5b2e78af9a13..1347e50c5d8d 100644--- a/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.py+++ b/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.py@@ -291,10 +291,10 @@ async def test_prepare_data_imports_ducklake_metadata_activity_empty_schema_ids(assert result == []-def _create_mock_catalog():- """Create a mock DuckLakeCatalog."""- mock_catalog = MagicMock()- mock_catalog.to_public_config.return_value = {+def _create_mock_server():+ """Create a mock DuckgresServer (catalog connection config + bucket)."""+ mock_server = MagicMock()+ mock_server.to_catalog_public_config.return_value = {"DUCKLAKE_RDS_HOST": "localhost","DUCKLAKE_RDS_PORT": "5432","DUCKLAKE_RDS_DATABASE": "ducklake",@@ -305,8 +305,9 @@ def _create_mock_catalog():"DUCKLAKE_S3_ACCESS_KEY": "","DUCKLAKE_S3_SECRET_KEY": "",}- mock_catalog.bucket = "test-bucket"- return mock_catalog+ mock_server.catalog_password = "password"+ mock_server.bucket = "test-bucket"+ return mock_serverdef test_resolve_data_imports_staging_uri_returns_none_in_dev(monkeypatch):@@ -316,7 +317,7 @@ def test_resolve_data_imports_staging_uri_returns_none_in_dev(monkeypatch):)mock_get_catalog = MagicMock(side_effect=AssertionError("catalog lookup should not run in dev mode"))monkeypatch.setattr(- "posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.get_ducklake_catalog_by_team_org",+ "posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.get_duckgres_server_by_team_org",mock_get_catalog,)@@ -334,25 +335,25 @@ def test_resolve_data_imports_staging_uri_raises_without_prod_catalog(monkeypatcMagicMock(return_value=False),)monkeypatch.setattr(- "posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.get_ducklake_catalog_by_team_org",+ "posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.get_duckgres_server_by_team_org",MagicMock(return_value=None),)with pytest.raises(ApplicationError) as exc_info:ducklake_module._resolve_data_imports_staging_uri("s3://source/team_1/customers", team_id=1)- assert "No DuckLakeCatalog configured for team 1" in str(exc_info.value)+ assert "No DuckgresServer configured for team 1" in str(exc_info.value)assert exc_info.value.non_retryable is Truedef test_resolve_data_imports_staging_uri_uses_prod_catalog(monkeypatch):- catalog = _create_mock_catalog()+ catalog = _create_mock_server()monkeypatch.setattr("posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.is_dev_mode",MagicMock(return_value=False),)monkeypatch.setattr(- "posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.get_ducklake_catalog_by_team_org",+ "posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.get_duckgres_server_by_team_org",MagicMock(return_value=catalog),)@@ -455,14 +456,9 @@ def test_copy_data_imports_to_ducklake_activity_via_duckgres(monkeypatch):"posthog.temporal.ducklake.ducklake_copy_data_imports_workflow._get_org_id_for_team",MagicMock(return_value="org-123"),)- monkeypatch.setattr(- "posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.get_ducklake_catalog_for_organization",- MagicMock(return_value=_create_mock_catalog()),- )- mock_server = MagicMock()monkeypatch.setattr("posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.get_duckgres_server_for_organization",- MagicMock(return_value=mock_server),+ MagicMock(return_value=_create_mock_server()),)mock_stage = MagicMock()monkeypatch.setattr(@@ -939,7 +935,7 @@ def test_copy_data_imports_to_ducklake_activity_raises_when_no_catalog(monkeypatMagicMock(return_value="org-123"),)monkeypatch.setattr(- "posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.get_ducklake_catalog_for_organization",+ "posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.get_duckgres_server_for_organization",MagicMock(return_value=None),)@@ -958,7 +954,7 @@ def test_copy_data_imports_to_ducklake_activity_raises_when_no_catalog(monkeypatwith pytest.raises(ApplicationError) as exc_info:copy_data_imports_to_ducklake_activity(inputs)- assert "No DuckLakeCatalog configured for team 1" in str(exc_info.value)+ assert "No DuckgresServer configured for team 1" in str(exc_info.value)assert exc_info.value.non_retryable is Truediff --git a/posthog/temporal/tests/ducklake/test_ducklake_copy_data_modeling_workflow.py b/posthog/temporal/tests/ducklake/test_ducklake_copy_data_modeling_workflow.pyindex 2d3d167a40d0..f96a699235af 100644--- a/posthog/temporal/tests/ducklake/test_ducklake_copy_data_modeling_workflow.py+++ b/posthog/temporal/tests/ducklake/test_ducklake_copy_data_modeling_workflow.py@@ -28,10 +28,10 @@ from posthog.temporal.ducklake.types import DataModelingDuckLakeCopyInputs, Duckfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery-def _create_mock_catalog():- """Create a mock DuckLakeCatalog."""- mock_catalog = MagicMock()- mock_catalog.to_public_config.return_value = {+def _create_mock_server():+ """Create a mock DuckgresServer (catalog connection config + bucket)."""+ mock_server = MagicMock()+ mock_server.to_catalog_public_config.return_value = {"DUCKLAKE_RDS_HOST": "localhost","DUCKLAKE_RDS_PORT": "5432","DUCKLAKE_RDS_DATABASE": "ducklake",@@ -42,8 +42,9 @@ def _create_mock_catalog():"DUCKLAKE_S3_ACCESS_KEY": "","DUCKLAKE_S3_SECRET_KEY": "",}- mock_catalog.bucket = "test-bucket"- return mock_catalog+ mock_server.catalog_password = "password"+ mock_server.bucket = "test-bucket"+ return mock_server@pytest.mark.asyncio@@ -201,14 +202,9 @@ def test_copy_data_modeling_model_to_ducklake_activity_via_duckgres(monkeypatch)"posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow._get_org_id_for_team",MagicMock(return_value="org-123"),)- monkeypatch.setattr(- "posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow.get_ducklake_catalog_for_organization",- MagicMock(return_value=_create_mock_catalog()),- )- mock_server = MagicMock()monkeypatch.setattr("posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow.get_duckgres_server_for_organization",- MagicMock(return_value=mock_server),+ MagicMock(return_value=_create_mock_server()),)mock_stage = MagicMock()monkeypatch.setattr(@@ -299,8 +295,8 @@ def test_verify_ducklake_copy_activity_runs_queries(monkeypatch):MagicMock(return_value=False),)monkeypatch.setattr(- "posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow.get_ducklake_catalog_by_team_org",- MagicMock(return_value=_create_mock_catalog()),+ "posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow.get_duckgres_server_by_team_org",+ MagicMock(return_value=_create_mock_server()),)monkeypatch.setattr("posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow.configure_connection",@@ -448,8 +444,8 @@ def test_verify_ducklake_copy_activity_reports_failures(monkeypatch):MagicMock(return_value=False),)monkeypatch.setattr(- "posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow.get_ducklake_catalog_by_team_org",- MagicMock(return_value=_create_mock_catalog()),+ "posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow.get_duckgres_server_by_team_org",+ MagicMock(return_value=_create_mock_server()),)monkeypatch.setattr("posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow.configure_connection",@@ -604,8 +600,8 @@ def test_verify_ducklake_copy_activity_respects_tolerance(monkeypatch, observed,MagicMock(return_value=False),)monkeypatch.setattr(- "posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow.get_ducklake_catalog_by_team_org",- MagicMock(return_value=_create_mock_catalog()),+ "posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow.get_duckgres_server_by_team_org",+ MagicMock(return_value=_create_mock_server()),)monkeypatch.setattr("posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow.configure_connection",@@ -685,8 +681,8 @@ def test_verify_ducklake_copy_activity_includes_additional_checks(monkeypatch):MagicMock(return_value=False),)monkeypatch.setattr(- "posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow.get_ducklake_catalog_by_team_org",- MagicMock(return_value=_create_mock_catalog()),+ "posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow.get_duckgres_server_by_team_org",+ MagicMock(return_value=_create_mock_server()),)monkeypatch.setattr("posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow.configure_connection",@@ -744,7 +740,7 @@ def test_copy_data_modeling_model_to_ducklake_activity_raises_when_no_catalog(moMagicMock(return_value="org-123"),)monkeypatch.setattr(- "posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow.get_ducklake_catalog_for_organization",+ "posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow.get_duckgres_server_for_organization",MagicMock(return_value=None),)@@ -764,12 +760,12 @@ def test_copy_data_modeling_model_to_ducklake_activity_raises_when_no_catalog(mowith pytest.raises(ApplicationError) as exc_info:copy_data_modeling_model_to_ducklake_activity(inputs)- assert "No DuckLakeCatalog configured for team 1" in str(exc_info.value)+ assert "No DuckgresServer configured for team 1" in str(exc_info.value)assert exc_info.value.non_retryable is Truedef test_verify_ducklake_copy_activity_raises_when_no_catalog(monkeypatch):- """Test that verify activity raises ApplicationError when no DuckLakeCatalog is configured."""+ """Test that verify activity raises ApplicationError when no DuckgresServer is configured."""from temporalio.exceptions import ApplicationErrormock_heartbeater = MagicMock()@@ -785,7 +781,7 @@ def test_verify_ducklake_copy_activity_raises_when_no_catalog(monkeypatch):MagicMock(return_value=False),)monkeypatch.setattr(- "posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow.get_ducklake_catalog_by_team_org",+ "posthog.temporal.ducklake.ducklake_copy_data_modeling_workflow.get_duckgres_server_by_team_org",MagicMock(return_value=None),)@@ -813,7 +809,7 @@ def test_verify_ducklake_copy_activity_raises_when_no_catalog(monkeypatch):with pytest.raises(ApplicationError) as exc_info:verify_ducklake_copy_activity(inputs)- assert "No DuckLakeCatalog configured for team 42" in str(exc_info.value)+ assert "No DuckgresServer configured for team 42" in str(exc_info.value)assert exc_info.value.non_retryable is Truediff --git a/products/data_warehouse/backend/presentation/views/managed_warehouse.py b/products/data_warehouse/backend/presentation/views/managed_warehouse.pyindex 7725dfb66cd0..2d1db132d9e3 100644--- a/products/data_warehouse/backend/presentation/views/managed_warehouse.py+++ b/products/data_warehouse/backend/presentation/views/managed_warehouse.py@@ -250,8 +250,8 @@ def _register_provisioning_team(organization_id: UUID | str, team_id: int, table"""Record the provisioning (calling) team's duckling membership and enable its backfill.A managed warehouse is org-scoped, but membership and backfills are per team, so provision- registers only the provisioning team: its `DuckgresServerTeam` link (first-class membership)- and a `DuckLakeBackfill` enabled with the per-environment table name the admin chose at+ registers only the provisioning team: a single `DuckgresServerTeam` row carrying its+ membership and a backfill enabled with the per-environment table name the admin chose atprovision — so a newly provisioned org writes to its own `events_<suffix>` tables. Other teamsjoin later via `enable_backfill`, which runs the same path.@@ -314,8 +314,8 @@ def enable_backfill() -> Response:"""Enable warehouse backfill for a team's environment with dedicated per-environment tables.- Per-team (not org-wide): persists the per-environment table suffix on the team's- DuckLakeBackfill and records team↔duckling membership. Gated on the org's feature flag so+ Per-team (not org-wide): persists the per-environment table suffix and team↔duckling+ membership on the team's DuckgresServerTeam. Gated on the org's feature flag soa team can't enable a backfill for an org that isn't entitled to the managed warehouse;backend/ops callers (the Django admin) pass `require_enabled=False` to bypass that gate."""diff --git a/products/data_warehouse/backend/tests/api/test_managed_warehouse.py b/products/data_warehouse/backend/tests/api/test_managed_warehouse.pyindex c5496b63a82c..8dc05930007b 100644--- a/products/data_warehouse/backend/tests/api/test_managed_warehouse.py+++ b/products/data_warehouse/backend/tests/api/test_managed_warehouse.py@@ -7,7 +7,7 @@ from django.test import override_settingsfrom rest_framework.response import Response-from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam, DuckLakeBackfill+from posthog.ducklake.models import DuckgresServer, DuckgresServerTeamfrom posthog.models import Organization, Teamfrom products.data_warehouse.backend.presentation.views import managed_warehouse@@ -100,15 +100,12 @@ def test_provision_enables_backfill_for_calling_team_only(mock_request: MagicMocmanaged_warehouse.provision(org.id, "my-warehouse", team.id, "prod_events")- backfill = DuckLakeBackfill.objects.get(team_id=team.id)- assert backfill.enabled is True- # New provisions set the per-environment suffix from the admin-provided table name.- assert backfill.table_suffix == "prod_events"- assert not DuckLakeBackfill.objects.filter(team_id=other_team.id).exists()-- # Provision also records first-class duckling membership for the provisioning team only.+ # Provision records first-class duckling membership + backfill for the provisioning team only.server = DuckgresServer.objects.get(organization_id=org.id)- assert DuckgresServerTeam.objects.filter(server=server, team_id=team.id).exists()+ link = DuckgresServerTeam.objects.get(server=server, team_id=team.id)+ assert link.backfill_enabled is True+ # New provisions set the per-environment suffix from the admin-provided table name.+ assert link.table_suffix == "prod_events"assert not DuckgresServerTeam.objects.filter(team_id=other_team.id).exists()@@ -144,7 +141,7 @@ 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()- assert not DuckLakeBackfill.objects.filter(team_id=team.id).exists()+ assert not DuckgresServerTeam.objects.filter(team_id=team.id).exists()@pytest.mark.django_db@@ -373,10 +370,9 @@ def test_enable_backfill_creates_backfill_and_membership(mock_enabled: MagicMockassert resp.status_code == 200assert resp.data == {"enabled": True, "table_suffix": "my_events"}- backfill = DuckLakeBackfill.objects.get(team_id=team.id)- assert backfill.enabled is True- assert backfill.table_suffix == "my_events"- assert DuckgresServerTeam.objects.filter(server=server, team_id=team.id).exists()+ link = DuckgresServerTeam.objects.get(server=server, team_id=team.id)+ assert link.backfill_enabled is True+ assert link.table_suffix == "my_events"@pytest.mark.django_db@@ -388,20 +384,20 @@ def test_enable_backfill_rejects_invalid_name(mock_enabled: MagicMock) -> None:resp = managed_warehouse.enable_backfill(org.id, team.id, bad_name)assert resp.status_code == 400, bad_name- assert not DuckLakeBackfill.objects.filter(team_id=team.id).exists()+ assert not DuckgresServerTeam.objects.filter(team_id=team.id).exists()@pytest.mark.django_db@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)def test_enable_backfill_rejects_duplicate_suffix_in_org(mock_enabled: MagicMock) -> None:- org, team_a, _ = _provisioned_org()+ org, team_a, server = _provisioned_org()team_b = Team.objects.create(organization=org, name="Env B")- DuckLakeBackfill.objects.create(team=team_a, table_suffix="shared")+ DuckgresServerTeam.objects.create(server=server, team=team_a, table_suffix="shared")resp = managed_warehouse.enable_backfill(org.id, team_b.id, "shared")assert resp.status_code == 400- assert not DuckLakeBackfill.objects.filter(team_id=team_b.id).exists()+ assert not DuckgresServerTeam.objects.filter(team_id=team_b.id).exists()@pytest.mark.django_db@@ -424,7 +420,7 @@ def test_enable_backfill_gated_on_feature_flag(mock_enabled: MagicMock) -> None:resp = managed_warehouse.enable_backfill(org.id, team.id, "events")assert resp.status_code == 403- assert not DuckLakeBackfill.objects.filter(team_id=team.id).exists()+ assert not DuckgresServerTeam.objects.filter(team_id=team.id).exists()@pytest.mark.django_db@@ -436,9 +432,8 @@ def test_enable_backfill_same_name_is_idempotent(mock_enabled: MagicMock) -> Nonresp = managed_warehouse.enable_backfill(org.id, team.id, "first")assert resp.status_code == 200- assert DuckLakeBackfill.objects.filter(team_id=team.id).count() == 1assert DuckgresServerTeam.objects.filter(team_id=team.id).count() == 1- assert DuckLakeBackfill.objects.get(team_id=team.id).table_suffix == "first"+ assert DuckgresServerTeam.objects.get(team_id=team.id).table_suffix == "first"@pytest.mark.django_db@@ -451,17 +446,17 @@ def test_enable_backfill_refuses_to_change_an_existing_suffix(mock_enabled: Magi# Changing a set suffix would split the team's data across two tables — rejected, unchanged.assert resp.status_code == 400- assert DuckLakeBackfill.objects.get(team_id=team.id).table_suffix == "first"+ assert DuckgresServerTeam.objects.get(team_id=team.id).table_suffix == "first"@pytest.mark.django_db@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)def test_enable_backfill_refuses_to_set_a_suffix_on_a_legacy_shared_team(mock_enabled: MagicMock) -> None:- org, team, _ = _provisioned_org()+ org, team, server = _provisioned_org()# A legacy team already backfilling to the shared tables (NULL suffix), e.g. backfilled by migration.- DuckLakeBackfill.objects.create(team=team, enabled=True, table_suffix=None)+ DuckgresServerTeam.objects.create(server=server, team=team, backfill_enabled=True, table_suffix=None)resp = managed_warehouse.enable_backfill(org.id, team.id, "new_name")assert resp.status_code == 400- assert DuckLakeBackfill.objects.get(team_id=team.id).table_suffix is None+ assert DuckgresServerTeam.objects.get(team_id=team.id).table_suffix is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.pyindex 535554b05ef7..eaf317028dfb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py@@ -215,7 +215,7 @@ def _process_batch(conn: psycopg.Connection[Any], batch: PendingBatch, schema: Edef _duckgres_schema_name(team_id: int) -> str:# Resolves to posthog_data_imports_<table_suffix> when the team has set one- # (DuckLakeBackfill.table_suffix — the same suffix that names its+ # (DuckgresServerTeam.table_suffix — the same suffix that names its# events/persons tables), else the legacy posthog_data_imports_team_<id>.return duckgres_data_imports_schema(team_id)