:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): drop DuckgresServerTeam, read team state from cp (#73876)
Benjamin Knofe-Vider60294173c7a9
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.pyindex a07d3de1b6a4..b00e41bf4808 100644--- a/.github/scripts/check-idor-model-coverage.py+++ b/.github/scripts/check-idor-model-coverage.py@@ -178,7 +178,6 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st"DuckLakeBackfill","DuckLakeCatalog","DuckgresServer",- "DuckgresServerTeam","DuckgresSinkSchemaState","EvaluationConfig","RemoteConfig",diff --git a/posthog/admin/admins/duckgres_server_admin.py b/posthog/admin/admins/duckgres_server_admin.pyindex 2afd3b76c8e9..e1560e2f3d34 100644--- a/posthog/admin/admins/duckgres_server_admin.py+++ b/posthog/admin/admins/duckgres_server_admin.py@@ -127,9 +127,10 @@ 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 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.+ /provision call (which creates the first team's control-plane row), then the+ DuckgresServer connection record. 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.pydeleted file mode 100644index 0908425da9f5..000000000000--- a/posthog/admin/admins/duckgres_server_team_admin.py+++ /dev/null@@ -1,74 +0,0 @@-from django.contrib import admin-from django.db.models import QuerySet-from django.http import HttpRequest--from posthog.models import DuckgresServerTeam--[email protected](DuckgresServerTeam)-class DuckgresServerTeamAdmin(admin.ModelAdmin):- list_display = (- "id",- "server_id",- "team_id",- "backfill_enabled",- "table_suffix",- "earliest_event_date",- "created_by",- "created_at",- "updated_at",- )- 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", "backfill_enabled", "table_suffix"),- },- ),- (- "Backfill range",- {- "fields": ("earliest_event_date",),- },- ),- (- "Metadata",- {- "fields": ("created_by", "created_at", "updated_at"),- },- ),- )diff --git a/posthog/admin/test_duckgres_server_team_admin.py b/posthog/admin/test_duckgres_server_team_admin.pydeleted file mode 100644index a405be1b1403..000000000000--- a/posthog/admin/test_duckgres_server_team_admin.py+++ /dev/null@@ -1,26 +0,0 @@-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/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.pyindex 02509685a740..f2a5a30eb58b 100644--- a/posthog/dags/events_backfill_to_duckling.py+++ b/posthog/dags/events_backfill_to_duckling.py@@ -25,7 +25,8 @@ IAM Access:Partition Strategy:DynamicPartitionsDefinition with composite keys: {team_id}_{date}- - team_id maps to a duckling via DuckgresServerTeam (membership + enablement) + DuckgresServer (connection)+ - team_id maps to a duckling via its duckgres control-plane team row (membership ++ enablement) + DuckgresServer (connection)- date is the partition date (YYYY-MM-DD)"""@@ -39,7 +40,7 @@ import dataclassesfrom collections.abc import Callablefrom contextlib import closingfrom datetime import date, datetime, timedelta-from typing import Any, Literal, cast+from typing import Any, Literalfrom django.db import DatabaseErrorfrom django.utils import timezone@@ -81,7 +82,6 @@ from posthog.ducklake.common import (get_duckgres_server_for_organization,resolve_team_earliest_event_date,)-from posthog.ducklake.models import DuckgresServerTeamfrom products.data_warehouse.backend.facade.backfill_status import (BackfillOutcome,@@ -213,13 +213,10 @@ 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 `DuckgresServerTeam.table_suffix` (when set) isolates its data into- dedicated `events_<suffix>` / `persons_<suffix>` tables so multiple teams sharing one+ A team's duckgres control-plane row isolates its data into dedicated+ `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.-- Routed through the team-state accessor so the read source (Django rows vs. the- duckgres control plane) follows DUCKGRES_TEAM_STATE_SOURCE.+ A team without a row (legacy single-team ducklings) keeps the shared table names."""events_table, persons_table = team_state.resolve_events_persons_tables(team_id)_validate_identifier(events_table)@@ -1790,7 +1787,7 @@ def _fixup_partition_values_for_added_files(# table_kind is the logical kind ("events" or "persons") used to look up the# spec + path regex; table_name is the actual catalog table the files were# registered into and may carry a per-team suffix (events_<suffix> /- # persons_<suffix>) per DuckgresServerTeam.table_suffix. The dagster+ # persons_<suffix>) per the team's duckgres control-plane row. The dagster# registration path writes files for the suffixed table while keeping the# S3 prefix (backfill/events/.../) tied to the kind, not the suffix.# Raises RuntimeError on any inconsistency; see module-level block for the@@ -2858,7 +2855,7 @@ DAILY_BACKFILL_MAX_CATCHUP_PARTITIONS_PER_TICK = 1000def duckling_events_daily_backfill_sensor(context: SensorEvaluationContext,) -> SensorResult:- """Discover teams with backfills enabled (DuckgresServerTeam) and keep the current month's+ """Discover teams with backfills enabled (via the duckgres control plane) and keep the current month'sdaily backfill partitions filled.This sensor owns the CURRENT month; the full-backfill sensor owns every complete prior@@ -3012,13 +3009,13 @@ EVENTS_BACKFILL_STATUS_RECONCILE_LIMIT = 25_FULL_BACKFILL_RUN_TAG = {"duckling_backfill_type": "full"}-def _push_earliest_event_date_to_cp(bf: DuckgresServerTeam | team_state.CPBackfillRow) -> bool:- """Mirror a freshly resolved earliest_event_date onto the team's duckgres control-plane row.+def _push_earliest_event_date_to_cp(bf: team_state.CPBackfillRow) -> bool:+ """Persist a freshly resolved earliest_event_date onto the team's duckgres control-plane row.- Dual-write while per-team backfill state moves into the control plane. Best-effort —+ This push IS the persistence (the CP row is the sensor's read source). Best-effort —any failure (resolving the org, the CP call itself) is logged and swallowed so it can- never fail the sensor tick — but the outcome is returned so cp mode (where this push- IS the persistence) can surface a failed write instead of silently retrying forever.+ never fail the sensor tick — but the outcome is returned so the sensor can surface a+ failed write (the row stays unresolved and is retried on a later tick)."""try:# Deferred like the other control-plane touchpoints: keeps the DRF-importing@@ -3033,51 +3030,6 @@ def _push_earliest_event_date_to_cp(bf: DuckgresServerTeam | team_state.CPBackfireturn False-def _reconcile_earliest_event_dates_with_cp(backfills: list[DuckgresServerTeam | team_state.CPBackfillRow]) -> None:- """Re-push resolved earliest_event_dates whose control-plane mirror is missing or stale.-- The per-row pushes (the provisioning Celery task, the sensor's resolve loop) are- best-effort one-shots: a transient control-plane failure would otherwise diverge the- two stores forever, because a row with a resolved date is never revisited. One- list-teams call per org per tick keeps this bounded; only teams the control plane- already knows are pushed (a missing row is the lazy grandfather's job, not this one's).- Best-effort in every direction — nothing here may fail the sensor tick.- """- try:- # Deferred like the other control-plane touchpoints: keeps the DRF-importing- # adapter off this module's import path.- from products.data_warehouse.backend.presentation.views import managed_warehouse # noqa: PLC0415- except Exception:- logger.exception("duckling_earliest_event_date_cp_reconcile_import_failed")- return-- by_org: dict = {}- for bf in backfills:- if bf.earliest_event_date is not None:- by_org.setdefault(bf.server.organization_id, []).append(bf)-- for org_id, rows in by_org.items():- try:- teams = managed_warehouse._teams_from_response(managed_warehouse.list_teams(org_id, require_enabled=False))- if teams is None:- continue- # Coerce team ids to int: a control plane serializing them as JSON strings- # would otherwise make every team look unknown and silently skip the repair.- cp_dates = {}- for row in teams:- try:- cp_dates[int(row["team_id"])] = row.get("earliest_event_date")- except (KeyError, TypeError, ValueError):- continue- for bf in rows:- if bf.team_id not in cp_dates:- continue- if cp_dates[bf.team_id] != bf.earliest_event_date.isoformat():- _push_earliest_event_date_to_cp(bf)- except Exception:- logger.exception("duckling_earliest_event_date_cp_reconcile_failed", organization_id=str(org_id))--def _reconcile_events_backfill_statuses(context: SensorEvaluationContext, partition_keys: list[str]) -> None:"""Backfill the status projection for partitions that ran before it existed.@@ -3160,7 +3112,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- ``DuckgresServerTeam`` row (bounded to EVENTS_BACKFILL_MAX_EARLIEST_LOOKUPS_PER_TICK+ team's duckgres control-plane 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@@ -3185,38 +3137,25 @@ def duckling_events_full_backfill_sensor(backfills = team_state.list_enabled_backfill_rows("events_full_backfill_sensor")if not backfills:- context.log.info("No enabled DuckgresServerTeam entries found")+ context.log.info("No enabled duckling backfill teams found")return SensorResult(run_requests=[])- cp_is_read_source = team_state.get_team_state_source() == team_state.SOURCE_CP-- # 1. Resolve + cache earliest_event_date for teams that don't have it yet. This is the+ # 1. Resolve + persist earliest_event_date for teams that don't have it yet. This is the# only expensive op (one ClickHouse query/team), bounded per tick and cached forever.- # Shuffled so rows whose cp-mode persist keeps failing (they stay unresolved next- # tick) can't deterministically occupy the bounded budget and starve later teams.+ # Shuffled so rows whose control-plane persist keeps failing (they stay unresolved+ # next tick) can't deterministically occupy the bounded budget and starve later teams.unresolved = [bf for bf in backfills if bf.earliest_event_date is None]random.shuffle(unresolved)for bf in unresolved[:EVENTS_BACKFILL_MAX_EARLIEST_LOOKUPS_PER_TICK]:bf.earliest_event_date = resolve_team_earliest_event_date(bf.team_id)if bf.earliest_event_date == NO_HISTORY_SENTINEL:context.log.info(f"No events for team_id={bf.team_id}; caching no-history sentinel")- if not cp_is_read_source:- # In django/dual mode the enumeration yields model rows, never CPBackfillRow.- cast(DuckgresServerTeam, bf).save(update_fields=["earliest_event_date"])- # In cp mode this push IS the persistence (the CP row is the read source);- # otherwise it stays the best-effort dual-write mirror.- pushed = _push_earliest_event_date_to_cp(bf)- if cp_is_read_source and not pushed:+ # This push IS the persistence: the control-plane row is the read source.+ if not _push_earliest_event_date_to_cp(bf):context.log.warning(f"Control plane rejected earliest_event_date persist for team_id={bf.team_id}; retrying next tick")- if not cp_is_read_source:- # Heal one-shot pushes that failed: re-mirror any resolved date the control plane- # is missing or has stale. Never fails the tick. Pointless in cp mode, where the- # control plane is already the read source being enumerated.- _reconcile_earliest_event_dates_with_cp(backfills)-# 2. Per-team remaining months (oldest first), skipping already-registered partitions.existing = set(context.instance.get_dynamic_partitions("duckling_events_backfill"))per_team_remaining: list[list[str]] = []@@ -3318,7 +3257,7 @@ duckling_events_backfill_job = define_asset_job(def duckling_persons_daily_backfill_sensor(context: SensorEvaluationContext,) -> SensorResult:- """Discover teams with backfills enabled (DuckgresServerTeam) and create daily persons partitions.+ """Discover teams with backfills enabled (via the duckgres control plane) and create daily persons partitions.Similar to duckling_events_daily_backfill_sensor but for persons data.Uses _timestamp (Kafka ingestion time) for date filtering.@@ -3422,7 +3361,7 @@ def duckling_persons_full_backfill_sensor("""backfills = team_state.list_enabled_backfill_rows("persons_full_backfill_sensor")if not backfills:- context.log.info("No enabled DuckgresServerTeam entries found")+ context.log.info("No enabled duckling backfill teams 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 4b7d367bec31..8767e9884b4c 100644--- a/posthog/dags/test_events_backfill_to_duckling.py+++ b/posthog/dags/test_events_backfill_to_duckling.py@@ -168,33 +168,20 @@ class TestResolveDucklingTarget:class TestResolveTableNames:- """Resolution of per-environment table names from a team's stored table_suffix.+ """The DAG-side wrapper passes the accessor's names through fail-closed validation."""- Kept DB-free (the rest of this file is): the stored suffix is mocked at the ORM boundary.- """-- def _patch_suffix(self, suffix: str | None) -> MagicMock:- model = MagicMock()- model.objects.filter.return_value.values_list.return_value.first.return_value = suffix- return model-- def test_set_suffix_yields_dedicated_tables(self):- with patch("posthog.ducklake.models.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.ducklake.models.DuckgresServerTeam", self._patch_suffix("alpha")):+ def test_passes_through_resolved_names(self):+ with patch(+ "posthog.ducklake.team_state.resolve_events_persons_tables",+ return_value=("events_alpha", "persons_alpha"),+ ):assert _resolve_table_names(1) == ("events_alpha", "persons_alpha")- with patch("posthog.ducklake.models.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.ducklake.models.DuckgresServerTeam", self._patch_suffix(suffix)):- assert _resolve_table_names(1) == ("events", "persons")- def test_unsafe_suffix_is_rejected(self):- with patch("posthog.ducklake.models.DuckgresServerTeam", self._patch_suffix("a-b; DROP")):+ def test_unsafe_resolved_name_is_rejected(self):+ with patch(+ "posthog.ducklake.team_state.resolve_events_persons_tables",+ return_value=("events_a-b; DROP", "persons"),+ ):with pytest.raises(ValueError):_resolve_table_names(1)@@ -892,8 +879,8 @@ class TestFullBackfillSensorEarliestDate:])def test_pushes_freshly_resolved_earliest_date_to_control_plane(self, _name, earliest_dt, expected_pushed):- # Dual-write: the resolved date (or the no-history sentinel) lands on the Django row- # AND is mirrored onto the duckgres control-plane team row.+ # The resolved date (or the no-history sentinel) is persisted onto the team's+ # duckgres control-plane row — the sensors' read source.backfill = self._bf(1)with patch("products.data_warehouse.backend.presentation.views.managed_warehouse.push_team_earliest_event_date"@@ -902,8 +889,8 @@ class TestFullBackfillSensorEarliestDate:mock_push.assert_called_once_with(backfill.server.organization_id, 1, expected_pushed)def test_control_plane_push_failure_does_not_fail_tick(self):- # The CP mirror is best-effort: a push blowing up must lose neither the Django- # write nor the tick's run requests.+ # The CP push is the persistence, but it is best-effort within a tick: a push+ # blowing up must not fail the tick — the row stays unresolved and is retried.backfill = self._bf(1)with patch("products.data_warehouse.backend.presentation.views.managed_warehouse.push_team_earliest_event_date",@@ -913,82 +900,12 @@ class TestFullBackfillSensorEarliestDate:[backfill], now=datetime(2020, 8, 10, 12, 0, 0), get_earliest=datetime(2020, 6, 15))assert backfill.earliest_event_date == date(2020, 6, 15)- backfill.save.assert_called_once_with(update_fields=["earliest_event_date"])assert len(result.run_requests) > 0-class TestEarliestEventDateReconcile:- # The one-shot CP pushes are best-effort; this pass is what heals a transient failure.- @staticmethod- def _bf(team_id: int, org_id: str, earliest):- m = MagicMock()- m.team_id = team_id- m.server.organization_id = org_id- m.earliest_event_date = earliest- return m-- @parameterized.expand(- [- # CP has no date for the team -> re-push- ("cp_missing_date", {"team_id": 1, "earliest_event_date": None}, True),- # A CP serializing team_id as a string must not make the team look unknown- ("cp_string_team_id", {"team_id": "1", "earliest_event_date": None}, True),- # CP has a stale date -> re-push- ("cp_stale_date", {"team_id": 1, "earliest_event_date": "2019-01-01"}, True),- # CP already converged -> nothing to do- ("cp_in_sync", {"team_id": 1, "earliest_event_date": "2020-06-15"}, False),- # CP doesn't know the team at all -> not this pass's job (lazy grandfather owns creation)- ("cp_missing_team", {"team_id": 999, "earliest_event_date": None}, False),- ]- )- def test_repushes_only_divergent_rows(self, _name, cp_row, expect_push):- from posthog.dags.events_backfill_to_duckling import _reconcile_earliest_event_dates_with_cp-- bf = self._bf(1, "org-a", date(2020, 6, 15))- with (- patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams") as mock_list,- patch(- "products.data_warehouse.backend.presentation.views.managed_warehouse._teams_from_response",- return_value=[cp_row],- ),- patch(- "products.data_warehouse.backend.presentation.views.managed_warehouse.push_team_earliest_event_date"- ) as mock_push,- ):- _reconcile_earliest_event_dates_with_cp([bf])-- mock_list.assert_called_once_with("org-a", require_enabled=False)- if expect_push:- mock_push.assert_called_once_with("org-a", 1, date(2020, 6, 15))- else:- mock_push.assert_not_called()-- def test_unresolved_rows_and_cp_failures_are_skipped_quietly(self):- from posthog.dags.events_backfill_to_duckling import _reconcile_earliest_event_dates_with_cp-- unresolved = self._bf(1, "org-a", None)- resolved = self._bf(2, "org-b", date(2020, 6, 15))- with (- patch(- "products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams",- side_effect=Exception("cp down"),- ) as mock_list,- patch(- "products.data_warehouse.backend.presentation.views.managed_warehouse.push_team_earliest_event_date"- ) as mock_push,- ):- # Must not raise: a CP outage can never fail the sensor tick.- _reconcile_earliest_event_dates_with_cp([unresolved, resolved])-- # Unresolved rows contribute no org lookup; the failing org is logged and skipped.- mock_list.assert_called_once_with("org-b", require_enabled=False)- mock_push.assert_not_called()---class TestFullBackfillSensorCpMode:- # With DUCKGRES_TEAM_STATE_SOURCE=cp the sensor enumerates the control plane and- # persists resolved dates through it ONLY — a django save (impossible on the CP rows)- # or a reconcile pass would mean the routing regressed.+class TestFullBackfillSensorCpEnumeration:+ # End-to-end through the real team_state enumeration: the sensor reads the control+ # plane and persists resolved dates through it.@staticmethoddef _cp_row(team_id: int, earliest: str | None = None) -> dict:@@ -1012,7 +929,6 @@ class TestFullBackfillSensorCpMode:cp_teams.clear_cache()try:with (- patch("posthog.ducklake.team_state.get_team_state_source", return_value="cp"),patch("posthog.ducklake.cp_teams._fetch_all_rows", return_value=cp_rows),patch("posthog.dags.events_backfill_to_duckling.timezone") as mock_tz,patch("posthog.dags.events_backfill_to_duckling.ManagedWarehouseBackfillPartition") as mock_projection,@@ -1022,38 +938,33 @@ class TestFullBackfillSensorCpMode:patch("products.data_warehouse.backend.presentation.views.managed_warehouse.push_team_earliest_event_date") as mock_push,- patch(- "products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams"- ) as mock_list_teams,):mock_tz.now.return_value = nowmock_projection.objects.unscoped.return_value.filter.return_value.values_list.return_value = []context = build_sensor_context(instance=DagsterInstance.ephemeral())result = duckling_events_full_backfill_sensor(context)- return result, mock_push, mock_list_teams+ return result, mock_pushfinally:cp_teams.clear_cache()- def test_enumerates_cp_and_writes_resolved_date_to_cp_only(self):- result, mock_push, mock_list_teams = self._run_cp_sensor(+ def test_enumerates_cp_and_persists_resolved_date_via_cp(self):+ result, mock_push = self._run_cp_sensor([self._cp_row(1)], now=datetime(2020, 8, 10, 12, 0, 0), get_earliest=datetime(2020, 6, 15))- # The resolved date is persisted through the control plane, not a django save- # (the CP rows expose no save(); one would crash the tick).+ # The resolved date is persisted through the control plane (the CP rows expose+ # no save(); a django-style save would crash the tick).mock_push.assert_called_once_with("org-a", 1, date(2020, 6, 15))- # The django→CP reconcile pass is skipped: the CP is already the read source.- mock_list_teams.assert_not_called()assert [rr.partition_key for rr in result.run_requests] == ["1_2020-06", "1_2020-07"]def test_cached_cp_date_is_not_re_resolved(self):- result, mock_push, _ = self._run_cp_sensor(+ result, mock_push = self._run_cp_sensor([self._cp_row(1, earliest="2020-06-15")], now=datetime(2020, 8, 10, 12, 0, 0))mock_push.assert_not_called()assert [rr.partition_key for rr in result.run_requests] == ["1_2020-06", "1_2020-07"]def test_cp_down_yields_empty_tick_without_raising(self):- result, mock_push, _ = self._run_cp_sensor(None, now=datetime(2020, 8, 10, 12, 0, 0))+ result, mock_push = self._run_cp_sensor(None, now=datetime(2020, 8, 10, 12, 0, 0))assert result.run_requests == []mock_push.assert_not_called()@@ -2117,7 +2028,7 @@ class TestDucklakeFilePartitionValueFixupHelper:def test_suffixed_table_name_uses_actual_name_in_catalog_lookup(self, _label, kind, actual_table_name, mock_open_conn):- # When DuckgresServerTeam.table_suffix is set, the dagster registration+ # When the team's CP row names suffixed tables, the dagster registration# path writes to events_<suffix> / persons_<suffix>. The fix-up must# look up THAT table in the catalog, not the bare kind name. Verified# by inspecting the cur.execute call binding the table_name param.@@ -2270,7 +2181,7 @@ class TestRegisterTriggersFixup:def test_fixup_passes_suffixed_table_name(self, _label, register_fn, kind, expected_table_name, target_overrides, _mock_enabled, mock_fixup):- # When DuckgresServerTeam.table_suffix is set, target.{events,persons}_table+ # When the team's CP row names suffixed tables, target.{events,persons}_table# carries the suffixed name. The fix-up trigger must pass that actual# name through so the catalog lookup targets the right table.target = DucklingTarget(diff --git a/posthog/ducklake/common.py b/posthog/ducklake/common.pyindex e0b29e33be43..087b78d6b693 100644--- a/posthog/ducklake/common.py+++ b/posthog/ducklake/common.py@@ -512,7 +512,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- ``DuckgresServerTeam.table_suffix`` is validated identically wherever it is+ schema name / table suffix is validated identically wherever it isinterpolated into DuckDB DDL."""if not identifier or not identifier.replace("_", "").isalnum():@@ -524,14 +524,14 @@ 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 ``DuckgresServerTeam.table_suffix`` (the same field that- governs its events/persons tables), the data-import schema uses that suffix- so one user-chosen identifier names all of a team's warehouse tables.+ A team with a control-plane row uses that row's data-imports schema (derived+ from its schema name — the same identifier that governs its events/persons+ tables) so one user-chosen identifier names all of a team's warehouse tables.- Backward-compatible: a NULL/empty suffix keeps the team-id schema, so- existing teams are unaffected until a suffix is explicitly set.+ Backward-compatible: a team without a control-plane row keeps the team-id+ schema, so legacy teams are unaffected until they onboard.- NOTE: a suffix CHANGE moves the schema and orphans the old one — callers+ NOTE: a schema-name CHANGE moves the schema and orphans the old one — callersthat have already written a team's tables must trigger a re-prime (handledby the backfill state machine), not silently switch."""@@ -563,30 +563,17 @@ def duckgres_data_modeling_schema(team_id: int) -> str:TABLE_SUFFIX_MAX_LENGTH = 63-# The table name the user supplies is used verbatim as the suffix in `events_<suffix>` /-# `persons_<suffix>`, so it must already be a safe SQL identifier — lowercase letters,-# numbers, and underscores. We validate rather than silently rewrite, so what the user-# types is exactly what they get.+# A schema name doubles as the suffix in `events_<suffix>` / `persons_<suffix>`, so it must+# already be a safe SQL identifier — lowercase letters, numbers, and underscores. We validate+# rather than silently rewrite, so what the user types is exactly what they get.TABLE_SUFFIX_PATTERN = re.compile(r"^[a-z0-9_]+$")-def validate_table_suffix(name: str | None) -> str | None:- """Return a human-readable error if `name` isn't a valid table suffix, else None."""- if not name:- return "table_name is required"- if len(name) > TABLE_SUFFIX_MAX_LENGTH:- return f"Table name must be at most {TABLE_SUFFIX_MAX_LENGTH} characters"- if not TABLE_SUFFIX_PATTERN.match(name):- return "Table name must use only lowercase letters, numbers, and underscores"- return None--def validate_schema_name(name: str | None) -> str | None:"""Return a human-readable error if `name` isn't a valid duckgres schema name, else None.- A team's schema name shares the table-suffix constraints (it doubles as the- table suffix on the Django side): lowercase letters, numbers, and underscores,- at most 63 characters.+ A team's schema name doubles as its warehouse table suffix: lowercase letters,+ numbers, and underscores, at most 63 characters."""if not name:return "schema_name is required"@@ -597,108 +584,6 @@ def validate_schema_name(name: str | None) -> str | None:return None-class DucklingBackfillEnableError(Exception):- """Raised when a team's warehouse backfill cannot be enabled (no server, name collision)."""---def check_team_backfill_enable(*, team_id: int, organization_id: str | UUID, table_name: str) -> bool:- """Run every ``enable_team_backfill`` guard without writing anything.-- Returns True when the team already has a row with this exact suffix (an idempotent- no-op for the caller), False when a new row would be created. Raises- DucklingBackfillEnableError with a user-facing message otherwise. Lets dual-write- callers reject bad input before touching the duckgres control plane.- """- from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam-- error = validate_table_suffix(table_name)- if error:- raise DucklingBackfillEnableError(error)- suffix = table_name-- if not DuckgresServer.objects.filter(organization_id=organization_id).exists():- raise DucklingBackfillEnableError(- "No managed warehouse is provisioned for this organization. Provision one first."- )-- existing = DuckgresServerTeam.objects.filter(team_id=team_id).first()- if existing is not None:- if existing.table_suffix == suffix:- # Same name — already set up; idempotent no-op.- return True- current = f"events_{existing.table_suffix}" if existing.table_suffix else "the shared tables"- raise DucklingBackfillEnableError(- f"This project already writes to {current}, and its warehouse table can't be changed — "- "that would split its existing data across two tables."- )-- collision = (- DuckgresServerTeam.objects.filter(team__organization_id=organization_id, table_suffix=suffix)- .exclude(team_id=team_id)- .exists()- )- if collision:- raise DucklingBackfillEnableError(- f"The name '{suffix}' is already used by another environment in this organization."- )- return False---def enable_team_backfill(*, team_id: int, organization_id: str | UUID, table_name: str) -> str:- """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 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 changed- afterward — including switching a legacy NULL suffix (shared tables) to a real name. Changing- it would make the Dagster job write to a different table and split the team's existing data- across two tables. Re-calling with the team's current name is an idempotent no-op.-- The org must already have a provisioned DuckgresServer, the name must be a valid identifier,- and the suffix must be unique among the org's environments. Returns the suffix, or raises- DucklingBackfillEnableError with a user-facing message.- """- from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam-- already_enabled = check_team_backfill_enable(- team_id=team_id, organization_id=organization_id, table_name=table_name- )- suffix = table_name- if already_enabled:- existing = DuckgresServerTeam.objects.get(team_id=team_id)- if not existing.backfill_enabled:- existing.backfill_enabled = True- existing.save(update_fields=["backfill_enabled", "updated_at"])- _ensure_managed_warehouse_direct_source(team_id=team_id, organization_id=organization_id)- return suffix-- server = DuckgresServer.objects.get(organization_id=organization_id)- DuckgresServerTeam.objects.create(server=server, team_id=team_id, backfill_enabled=True, table_suffix=suffix)- _ensure_managed_warehouse_direct_source(team_id=team_id, organization_id=organization_id)- return suffix---def _ensure_managed_warehouse_direct_source(*, team_id: int, organization_id: str | UUID) -> None:- """Best-effort: register the org's managed warehouse as a restricted query connection.-- A managed warehouse speaks the Postgres wire protocol, so each member team gets an- ExternalDataSource pointed at the org server. Duckgres scopes its credential to the project- and enforces read-only SQL. Isolated from backfill enablement: a failure here must never block- a team from joining the warehouse.- """- try:- # Lazy import: keep the data_warehouse/warehouse_sources stack off this module's import- # path (it's loaded by the API and by Dagster, which don't need it).- from products.data_warehouse.backend.facade.api import ensure_managed_warehouse_direct_source # noqa: PLC0415-- ensure_managed_warehouse_direct_source(team_id=team_id, organization_id=organization_id)- except Exception:- logger.exception("Failed to register managed warehouse query source for team %s", team_id)--def get_team_backfill_state(team_id: int) -> dict[str, object]:"""Return the team's duckling backfill state for the warehouse-status UI.@@ -716,10 +601,9 @@ def get_team_backfill_state(team_id: int) -> dict[str, object]:# Ignore events before this date — pre-2015 data is typically junk timestamps.EARLIEST_BACKFILL_DATE = datetime(2015, 1, 1)-# Stored in DuckgresServerTeam.earliest_event_date (and mirrored to the duckgres control-# plane) for a team with no events, so callers cache "nothing to backfill" instead of-# re-querying ClickHouse. Far enough in the future that any generated backfill months-# range is always empty.+# Stored on the team's duckgres control-plane row for a team with no events, so callers+# cache "nothing to backfill" instead of re-querying ClickHouse. Far enough in the future+# that any generated backfill months range is always empty.NO_HISTORY_SENTINEL = date(9999, 12, 31)@@ -801,16 +685,13 @@ def resolve_team_earliest_event_date(team_id: int) -> date:__all__ = ["EARLIEST_BACKFILL_DATE","NO_HISTORY_SENTINEL",- "DucklingBackfillEnableError","attach_catalog",- "check_team_backfill_enable","default_bucket_region","get_earliest_event_date_for_team","resolve_team_earliest_event_date","duckgres_data_imports_schema","duckgres_data_imports_table_name","duckgres_data_modeling_schema",- "enable_team_backfill","escape","get_config","get_ducklake_connection_string",@@ -831,5 +712,4 @@ __all__ = ["sanitize_ducklake_identifier","validate_duckgres_identifier","validate_schema_name",- "validate_table_suffix",]diff --git a/posthog/ducklake/cp_teams.py b/posthog/ducklake/cp_teams.pyindex aa7df6392be9..62ac0ab273d1 100644--- a/posthog/ducklake/cp_teams.py+++ b/posthog/ducklake/cp_teams.py@@ -1,7 +1,6 @@"""Read-side client for the duckgres control-plane org-teams API.-The control plane is becoming the source of truth for per-team managed-warehouse-state (today mirrored from the Django ``DuckgresServerTeam`` rows via dual-writes).+The control plane is the source of truth for per-team managed-warehouse state.This module exposes the CP rows as :class:`CPTeam` values plus a small process-localTTL cache so hot paths (the v3 data-import sink schema resolution) don't issue oneHTTP call per batch.@@ -181,10 +180,18 @@ def get_team(organization_id: str, team_id: int) -> CPTeam | None:return next((team for team in teams if team.team_id == wanted), None)-def list_enabled_backfills() -> list[CPTeam] | None:- """Every CP team row with backfill_enabled, across all orgs, or None when unreachable."""+def list_member_teams() -> list[CPTeam] | None:+ """Every CP team row across all orgs, or None when unreachable."""rows = _cached_rows(("all_teams",), _fetch_all_rows)if rows is None:return Noneteams = (team_from_row(row) for row in rows)- return [team for team in teams if team is not None and team.backfill_enabled]+ return [team for team in teams if team is not None]+++def list_enabled_backfills() -> list[CPTeam] | None:+ """Every CP team row with backfill_enabled, across all orgs, or None when unreachable."""+ teams = list_member_teams()+ if teams is None:+ return None+ return [team for team in teams if team.backfill_enabled]diff --git a/posthog/ducklake/models.py b/posthog/ducklake/models.pyindex 516ccc6361d8..6e70f9eab0c6 100644--- a/posthog/ducklake/models.py+++ b/posthog/ducklake/models.py@@ -72,50 +72,6 @@ class DuckgresServer(CreatedMetaFields, UpdatedMetaFields, UUIDModel):}-class DuckgresServerTeam(CreatedMetaFields, UpdatedMetaFields, UUIDModel):- """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 carries the team-specific warehouse backfill- configuration (whether backfills are enabled, the per-team table suffix, and the- cached backfill floor).- """-- server = models.ForeignKey(- "posthog.DuckgresServer",- on_delete=models.CASCADE,- related_name="teams",- )- team = models.OneToOneField(- "posthog.Team",- on_delete=models.CASCADE,- related_name="duckgres_server_team",- )- backfill_enabled = models.BooleanField(- default=True,- help_text="Whether warehouse backfills are enabled for this team",- )- table_suffix = models.CharField(- max_length=63,- null=True,- 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.",- )- earliest_event_date = models.DateField(- null=True,- 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.",- )-- class Meta:- db_table = "posthog_duckgresserverteam"- verbose_name = "Duckgres server team"- verbose_name_plural = "Duckgres server teams"--class DuckgresSinkSchemaState(CreatedMetaFields, UpdatedMetaFields, UUIDModel):r"""Per-schema lifecycle of the Duckgres v3 batch sink.diff --git a/posthog/ducklake/team_state.py b/posthog/ducklake/team_state.pyindex e19309aa350b..bb3007b9f127 100644--- a/posthog/ducklake/team_state.py+++ b/posthog/ducklake/team_state.py@@ -1,143 +1,57 @@-"""Mode-routable readers for per-team managed-warehouse (duckling) state.+"""Readers for per-team managed-warehouse (duckling) state.-Per-team state lives in the Django ``DuckgresServerTeam`` rows and is dual-written-to the duckgres control-plane org-teams API. This module is the single read seam-for that state: every consumer calls an accessor here, and the accessor branches on-the ``DUCKGRES_TEAM_STATE_SOURCE`` setting:+Per-team state lives in the duckgres control-plane org-teams API (read via+:mod:`posthog.ducklake.cp_teams`). This module is the single read seam for that+state: every consumer calls an accessor here instead of talking to the control+plane directly, so the failure posture of each read stays in one place.-* ``django`` (default): the current queryset logic, unchanged.-* ``cp``: the control-plane rows (via :mod:`posthog.ducklake.cp_teams`).-* ``dual``: serve django, also read the CP, compare field-by-field, and emit- parity telemetry — the rollout gate before flipping to ``cp``.--Failure posture is per accessor (see each function); parity telemetry is-best-effort and never affects the served value.+Failure posture is per accessor (see each function): backfill-critical reads+raise :class:`CPUnavailableError`, sensor enumerations degrade to empty, status+reads degrade to not-onboarded, and the team-deletion guard fails closed."""from __future__ import annotations-import time-import threadingfrom datetime import date-from typing import TYPE_CHECKINGimport structlogfrom posthog.ducklake import cp_teamsfrom posthog.ducklake.common import _get_org_id_for_team, validate_duckgres_identifier-if TYPE_CHECKING:- from posthog.ducklake.models import DuckgresServerTeam-logger = structlog.get_logger(__name__)-SOURCE_DJANGO = "django"-SOURCE_DUAL = "dual"-SOURCE_CP = "cp"-_VALID_SOURCES = (SOURCE_DJANGO, SOURCE_DUAL, SOURCE_CP)--# statshog counters emitted by dual-mode parity checks.-PARITY_CHECKS_COUNTER = "duckgres_team_state_parity_checks_total"-PARITY_MISMATCH_COUNTER = "duckgres_team_state_parity_mismatch_total"-PARITY_CP_UNAVAILABLE_COUNTER = "duckgres_team_state_parity_cp_unavailable_total"-class CPUnavailableError(RuntimeError):"""The duckgres control plane could not answer a team-state read."""-def get_team_state_source() -> str:- """Resolve the configured read source, defaulting to django on anything unexpected."""- try:- from django.conf import settings # noqa: PLC0415 — keeps this module importable without Django configured-- source = getattr(settings, "DUCKGRES_TEAM_STATE_SOURCE", SOURCE_DJANGO)- except Exception:- return SOURCE_DJANGO- if source not in _VALID_SOURCES:- logger.warning("duckgres_team_state_source_invalid", source=source)- return SOURCE_DJANGO- return source---# --- Parity telemetry (dual mode) ---------------------------------------------------_parity_log_lock = threading.Lock()-_last_mismatch_log: dict[tuple[int, str], float] = {}+def _get_cp_row(team_id: int) -> cp_teams.CPTeam | None:+ """The team's control-plane row, or None when absent.--def clear_parity_state() -> None:- """Reset the mismatch-log rate limiter (for tests)."""- with _parity_log_lock:- _last_mismatch_log.clear()---def _incr(metric: str, call_site: str) -> None:- try:- from statshog.defaults.django import (- statsd, # noqa: PLC0415 — statsd needs Django settings; keep it off the import path- )-- statsd.incr(metric, tags={"call_site": call_site})- except Exception:- logger.exception("duckgres_team_state_parity_counter_failed", metric=metric)---def _report_mismatch(call_site: str, team_id: int, field: str, django_value: object, cp_value: object) -> None:- _incr(PARITY_MISMATCH_COUNTER, call_site)- now = time.monotonic()- key = (team_id, field)- with _parity_log_lock:- last = _last_mismatch_log.get(key)- if last is not None and now - last < cp_teams.CACHE_TTL_SECONDS:- return- _last_mismatch_log[key] = now- logger.warning(- "duckgres_team_state_parity_mismatch",- team_id=team_id,- field=field,- django_value=django_value,- cp_value=cp_value,- call_site=call_site,- )---def _report_cp_unavailable(call_site: str) -> None:- _incr(PARITY_CP_UNAVAILABLE_COUNTER, call_site)---def _compare(call_site: str, team_id: int, fields: dict[str, tuple[object, object]]) -> None:- """Count one parity check and report every differing field. Never raises."""- try:- _incr(PARITY_CHECKS_COUNTER, call_site)- for field, (django_value, cp_value) in fields.items():- if django_value != cp_value:- _report_mismatch(call_site, team_id, field, django_value, cp_value)- except Exception:- logger.exception("duckgres_team_state_parity_compare_failed", call_site=call_site)+ Raises :class:`CPUnavailableError` when the control plane can't answer and the+ cache is cold — callers pick their own degrade posture around it.+ """+ organization_id = _get_org_id_for_team(team_id)+ teams = cp_teams.list_org_teams(organization_id)+ if teams is None:+ raise CPUnavailableError(f"duckgres control plane unreachable reading team state for team {team_id}")+ return next((team for team in teams if team.team_id == team_id), None)# --- events/persons table names (Dagster duckling backfill) ------------------------def _django_events_persons_tables(team_id: int) -> tuple[str, str]:- from posthog.ducklake.models import DuckgresServerTeam # noqa: PLC0415 — keeps Django models off the import path-- suffix = DuckgresServerTeam.objects.filter(team_id=team_id).values_list("table_suffix", flat=True).first()- if not suffix:- return "events", "persons"- validate_duckgres_identifier(suffix)- return f"events_{suffix}", f"persons_{suffix}"-+def resolve_events_persons_tables(team_id: int) -> tuple[str, str]:+ """The per-team (events, persons) duckling table names the backfill writes to.-def _cp_events_persons_tables(team_id: int) -> tuple[str, str]:- organization_id = _get_org_id_for_team(team_id)- teams = cp_teams.list_org_teams(organization_id)- if teams is None:- raise CPUnavailableError(f"duckgres control plane unreachable resolving table names for team {team_id}")- row = next((team for team in teams if team.team_id == team_id), None)+ Failure posture: raises :class:`CPUnavailableError` when the control plane can't+ answer and the cache is cold — the backfill run fails and retries rather than+ writing to guessed tables.+ """+ row = _get_cp_row(team_id)if row is None:- # Mirrors the django no-row case: legacy single-team ducklings share the base tables.+ # Legacy single-team ducklings without a team row share the base tables.return "events", "persons"events_table, persons_table = row.resolved_events_table, row.resolved_persons_tablevalidate_duckgres_identifier(events_table)@@ -145,153 +59,63 @@ def _cp_events_persons_tables(team_id: int) -> tuple[str, str]:return events_table, persons_table-def resolve_events_persons_tables(team_id: int) -> tuple[str, str]:- """The per-team (events, persons) duckling table names the backfill writes to.-- cp-mode failure posture: raises :class:`CPUnavailableError` when the control plane- can't answer and the cache is cold — the backfill run fails and retries rather than- writing to guessed tables.- """- source = get_team_state_source()- if source == SOURCE_CP:- return _cp_events_persons_tables(team_id)- django_value = _django_events_persons_tables(team_id)- if source == SOURCE_DUAL:- try:- cp_value = _cp_events_persons_tables(team_id)- except CPUnavailableError:- _report_cp_unavailable("resolve_table_names")- except Exception:- logger.exception("duckgres_team_state_dual_read_failed", call_site="resolve_table_names")- else:- _compare(- "resolve_table_names",- team_id,- {- "events_table": (django_value[0], cp_value[0]),- "persons_table": (django_value[1], cp_value[1]),- },- )- return django_value--# --- data-imports schema (v3 sink hot path) ----------------------------------------def _django_data_imports_schema(team_id: int) -> str:- from posthog.ducklake.models import DuckgresServerTeam # noqa: PLC0415 — keeps Django models off the import path-- 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)- return f"posthog_data_imports_{suffix}"-+def data_imports_schema(team_id: int) -> str:+ """The duckgres schema the v3 data-import sink writes a team into.-def _cp_data_imports_schema(team_id: int) -> str:- organization_id = _get_org_id_for_team(team_id)- teams = cp_teams.list_org_teams(organization_id)- if teams is None:- raise CPUnavailableError(f"duckgres control plane unreachable resolving data-imports schema for team {team_id}")- row = next((team for team in teams if team.team_id == team_id), None)+ Hot path: reads are served from the cp_teams TTL cache. Failure posture: raises+ :class:`CPUnavailableError` when the control plane can't answer and the cache is+ cold — the batch fails and retries.+ """+ row = _get_cp_row(team_id)if row is None:- # Mirrors the django no-row case: the historical per-team schema.+ # Teams without a control-plane row keep the historical per-team schema.return f"posthog_data_imports_team_{team_id}"schema = row.resolved_data_imports_schemavalidate_duckgres_identifier(schema)return schema-def data_imports_schema(team_id: int) -> str:- """The duckgres schema the v3 data-import sink writes a team into.-- Hot path: cp/dual reads are served from the cp_teams TTL cache. cp-mode failure- posture: raises :class:`CPUnavailableError` when the control plane can't answer and- the cache is cold — the batch fails and retries.- """- source = get_team_state_source()- if source == SOURCE_CP:- return _cp_data_imports_schema(team_id)- django_value = _django_data_imports_schema(team_id)- if source == SOURCE_DUAL:- try:- cp_value = _cp_data_imports_schema(team_id)- except CPUnavailableError:- _report_cp_unavailable("data_imports_schema")- except Exception:- logger.exception("duckgres_team_state_dual_read_failed", call_site="data_imports_schema")- else:- _compare("data_imports_schema", team_id, {"data_imports_schema": (django_value, cp_value)})- return django_value--# --- backfill state (warehouse-status UI) ------------------------------------------def _django_team_backfill_state(team_id: int) -> dict[str, object]:- from posthog.ducklake.models import DuckgresServerTeam # noqa: PLC0415 — keeps Django models off the import path-- 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"]}---def _cp_table_suffix(row: cp_teams.CPTeam) -> str | None:- """Reverse-map a CP row onto the Django ``table_suffix`` semantics.+def cp_table_suffix(row: cp_teams.CPTeam) -> str | None:+ """Map a CP row onto the historical ``table_suffix`` semantics.A grandfathered legacy-shared team pins the base ``events``/``persons`` tables andhas no suffix (None); every other row's schema name doubles as its suffix (the- dual-write stores the same identifier in both places).+ onboarding write stores the same identifier in both places)."""if row.events_table_name == "events" or row.persons_table_name == "persons":return Nonereturn row.schema_name-def _cp_team_backfill_state(team_id: int) -> dict[str, object]:- organization_id = _get_org_id_for_team(team_id)- teams = cp_teams.list_org_teams(organization_id)- if teams is None:- raise CPUnavailableError(f"duckgres control plane unreachable reading backfill state for team {team_id}")- row = next((team for team in teams if team.team_id == team_id), None)- if row is None:- return {"has_backfill": False, "table_suffix": None}- return {"has_backfill": True, "table_suffix": _cp_table_suffix(row)}+def team_backfill_row(team_id: int) -> cp_teams.CPTeam | None:+ """The team's control-plane row for status reads, or None when absent.++ Failure posture: a status read must never 500 — an unreachable control plane+ degrades to None (reported as not onboarded / not configured).+ """+ try:+ return _get_cp_row(team_id)+ except CPUnavailableError:+ logger.warning("duckgres_team_state_cp_unavailable", call_site="team_backfill_row", team_id=team_id)+ return Nonedef team_backfill_state(team_id: int) -> dict[str, object]:"""The team's duckling backfill state for the warehouse-status UI.- cp-mode failure posture: a status read must never 500 — an unreachable control- plane degrades to the not-onboarded shape (mirroring the existing best-effort- control-plane reads in the status path).+ Failure posture: a status read must never 500 — an unreachable control plane+ degrades to the not-onboarded shape."""- source = get_team_state_source()- if source == SOURCE_CP:- try:- return _cp_team_backfill_state(team_id)- except CPUnavailableError:- logger.warning("duckgres_team_state_cp_unavailable", call_site="team_backfill_state", team_id=team_id)- return {"has_backfill": False, "table_suffix": None}- django_value = _django_team_backfill_state(team_id)- if source == SOURCE_DUAL:- try:- cp_value = _cp_team_backfill_state(team_id)- except CPUnavailableError:- _report_cp_unavailable("team_backfill_state")- except Exception:- logger.exception("duckgres_team_state_dual_read_failed", call_site="team_backfill_state")- else:- _compare(- "team_backfill_state",- team_id,- {- "has_backfill": (django_value["has_backfill"], cp_value["has_backfill"]),- "table_suffix": (django_value["table_suffix"], cp_value["table_suffix"]),- },- )- return django_value+ row = team_backfill_row(team_id)+ if row is None:+ return {"has_backfill": False, "table_suffix": None}+ return {"has_backfill": True, "table_suffix": cp_table_suffix(row)}# --- membership existence (team-deletion guard) -----------------------------------@@ -300,40 +124,26 @@ def team_backfill_state(team_id: int) -> dict[str, object]:def backfill_row_exists(team_id: int, organization_id: str) -> bool:"""Whether the team has a managed-warehouse membership row.- cp-mode failure posture: fail closed — an unreachable control plane reports the- row as existing, so a possibly-onboarded team's deletion is blocked with a retry- error instead of silently orphaning its duckgres state.+ Failure posture: fail closed — an unreachable control plane reports the row as+ existing, so a possibly-onboarded team's deletion is blocked with a retry error+ instead of silently orphaning its duckgres state."""- source = get_team_state_source()- if source == SOURCE_CP:- teams = cp_teams.list_org_teams(str(organization_id))- if teams is None:- logger.warning("duckgres_team_state_cp_unavailable", call_site="backfill_row_exists", team_id=team_id)- return True- return any(team.team_id == team_id for team in teams)-- from posthog.ducklake.models import DuckgresServerTeam # noqa: PLC0415 — keeps Django models off the import path-- django_value = DuckgresServerTeam.objects.filter(team_id=team_id).exists()- if source == SOURCE_DUAL:- teams = cp_teams.list_org_teams(str(organization_id))- if teams is None:- _report_cp_unavailable("backfill_row_exists")- else:- cp_value = any(team.team_id == team_id for team in teams)- _compare("backfill_row_exists", team_id, {"row_exists": (django_value, cp_value)})- return django_value+ teams = cp_teams.list_org_teams(str(organization_id))+ if teams is None:+ logger.warning("duckgres_team_state_cp_unavailable", call_site="backfill_row_exists", team_id=team_id)+ return True+ return any(team.team_id == team_id for team in teams)# --- enabled-backfill enumeration (Dagster sensors) -------------------------------class CPBackfillRow:- """Lightweight sensor row mirroring the ``DuckgresServerTeam`` attributes sensors touch.+ """Lightweight sensor row carrying the per-team attributes the duckling sensors touch.- ``server`` returns self so ``row.server.organization_id`` keeps working where the- django rows expose the org through their server FK. No ``save()`` on purpose: in cp- mode the earliest-event-date write goes through the control plane only.+ ``server`` returns self so ``row.server.organization_id`` keeps working where callers+ historically reached the org through a server FK. No ``save()`` on purpose: the+ earliest-event-date write goes through the control plane only."""def __init__(self, team_id: int, organization_id: str, earliest_event_date: date | None) -> None:@@ -346,59 +156,17 @@ class CPBackfillRow:return self-def _django_enabled_backfills() -> list[DuckgresServerTeam]:- from posthog.ducklake.models import DuckgresServerTeam # noqa: PLC0415 — keeps Django models off the import path-- return list(DuckgresServerTeam.objects.filter(backfill_enabled=True).select_related("server").order_by("team_id"))---def list_enabled_backfill_rows(call_site: str) -> list[DuckgresServerTeam | CPBackfillRow]:+def list_enabled_backfill_rows(call_site: str) -> list[CPBackfillRow]:"""Every team with warehouse backfills enabled, for sensor enumeration.- cp-mode failure posture: an unreachable control plane yields an empty enumeration- (the sensor tick becomes a no-op and the next tick retries) — it must never raise.+ Failure posture: an unreachable control plane yields an empty enumeration (the+ sensor tick becomes a no-op and the next tick retries) — it must never raise."""- source = get_team_state_source()- if source == SOURCE_CP:- cp_rows = cp_teams.list_enabled_backfills()- if cp_rows is None:- logger.warning("duckgres_team_state_cp_unavailable", call_site=call_site)- return []- return [- CPBackfillRow(row.team_id, row.organization_id, row.earliest_event_date)- for row in sorted(cp_rows, key=lambda row: row.team_id)- ]- django_rows = _django_enabled_backfills()- if source == SOURCE_DUAL:- _compare_enabled_backfills(call_site, django_rows)- return list(django_rows)---def _compare_enabled_backfills(call_site: str, django_rows: list[DuckgresServerTeam]) -> None:- """Dual-mode parity for the sensor enumeration: membership + earliest_event_date."""- try:- cp_rows = cp_teams.list_enabled_backfills()- if cp_rows is None:- _report_cp_unavailable(call_site)- return- _incr(PARITY_CHECKS_COUNTER, call_site)- cp_by_team = {row.team_id: row for row in cp_rows}- django_team_ids = set()- for django_row in django_rows:- django_team_ids.add(django_row.team_id)- cp_row = cp_by_team.get(django_row.team_id)- if cp_row is None:- _report_mismatch(call_site, django_row.team_id, "backfill_enabled", True, False)- continue- if django_row.earliest_event_date != cp_row.earliest_event_date:- _report_mismatch(- call_site,- django_row.team_id,- "earliest_event_date",- django_row.earliest_event_date,- cp_row.earliest_event_date,- )- for team_id in cp_by_team.keys() - django_team_ids:- _report_mismatch(call_site, team_id, "backfill_enabled", False, True)- except Exception:- logger.exception("duckgres_team_state_parity_compare_failed", call_site=call_site)+ cp_rows = cp_teams.list_enabled_backfills()+ if cp_rows is None:+ logger.warning("duckgres_team_state_cp_unavailable", call_site=call_site)+ return []+ return [+ CPBackfillRow(row.team_id, row.organization_id, row.earliest_event_date)+ for row in sorted(cp_rows, key=lambda row: row.team_id)+ ]diff --git a/posthog/ducklake/test_client.py b/posthog/ducklake/test_client.pyindex 9e57a45744f3..882b98663e2a 100644--- a/posthog/ducklake/test_client.py+++ b/posthog/ducklake/test_client.py@@ -5,8 +5,20 @@ from psycopg import sql as psqlfrom posthog.schema import HogQLQuery, HogQLVariable+from posthog.ducklake import cp_teamsfrom posthog.ducklake.client import _SEARCH_PATH_SCHEMAS, compile_hogql_to_ducklake_sql, execute_ducklake_query+[email protected](autouse=True)+def _cp_no_rows():+ # Compilation binds source tables via the team's control-plane row; serve the+ # no-row (legacy team-id schema) shape so these tests stay CP-independent.+ cp_teams.clear_cache()+ with mock.patch("posthog.ducklake.cp_teams._fetch_org_rows", return_value=[]):+ yield+ cp_teams.clear_cache()++pytestmark = [pytest.mark.django_db]diff --git a/posthog/ducklake/test_common.py b/posthog/ducklake/test_common.pyindex 97aac3d8c9bf..1159622802d8 100644--- a/posthog/ducklake/test_common.py+++ b/posthog/ducklake/test_common.py@@ -7,19 +7,14 @@ import duckdbfrom parameterized import parameterizedfrom posthog.ducklake.common import (- DucklingBackfillEnableError,default_bucket_region,- enable_team_backfill,- get_team_backfill_state,initialize_ducklake,is_version_mismatch,reset_ducklake_catalog,upsert_duckgres_server_for_org,)-from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam-from posthog.models import Organization, Team--from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from posthog.ducklake.models import DuckgresServer+from posthog.models import Organization@pytest.mark.django_db@@ -44,156 +39,6 @@ class TestUpsertDuckgresServerForOrg:assert updated.password == "pw2"-class TestEnableTeamBackfill:- def _server(self, org: Organization) -> DuckgresServer:- return DuckgresServer.objects.create(- organization=org, host="h", port=5432, database="ducklake", username="root", password="x"- )-- def test_creates_membership_and_suffixed_backfill(self):- org = Organization.objects.create(name="Org")- team = Team.objects.create(organization=org)- server = self._server(org)-- suffix = enable_team_backfill(team_id=team.id, organization_id=org.id, table_name="my_prod_env")-- assert 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")- team = Team.objects.create(organization=org)- self._server(org)-- with pytest.raises(DucklingBackfillEnableError):- enable_team_backfill(team_id=team.id, organization_id=org.id, table_name="Bad Name!")-- def test_rejects_duplicate_suffix_within_org(self):- org = Organization.objects.create(name="Org")- team_a = Team.objects.create(organization=org)- team_b = Team.objects.create(organization=org)- 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")-- def test_same_name_is_idempotent(self):- org = Organization.objects.create(name="Org")- team = Team.objects.create(organization=org)- self._server(org)-- enable_team_backfill(team_id=team.id, organization_id=org.id, table_name="prod")- suffix = enable_team_backfill(team_id=team.id, organization_id=org.id, table_name="prod")-- assert suffix == "prod"- assert DuckgresServerTeam.objects.filter(team_id=team.id).count() == 1-- def test_same_name_reenables_a_deprovisioned_membership(self):- org = Organization.objects.create(name="Org")- team = Team.objects.create(organization=org)- server = self._server(org)- DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="prod", backfill_enabled=False)-- suffix = enable_team_backfill(team_id=team.id, organization_id=org.id, table_name="prod")-- assert suffix == "prod"- assert DuckgresServerTeam.objects.get(team=team).backfill_enabled is True-- def test_refuses_to_change_a_set_suffix(self):- org = Organization.objects.create(name="Org")- team = Team.objects.create(organization=org)- self._server(org)- enable_team_backfill(team_id=team.id, organization_id=org.id, table_name="first")-- with pytest.raises(DucklingBackfillEnableError):- enable_team_backfill(team_id=team.id, organization_id=org.id, table_name="second")- 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)- 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 DuckgresServerTeam.objects.get(team_id=team.id).table_suffix is None-- def test_requires_a_provisioned_server(self):- org = Organization.objects.create(name="Org")- team = Team.objects.create(organization=org)-- with pytest.raises(DucklingBackfillEnableError):- enable_team_backfill(team_id=team.id, organization_id=org.id, table_name="events")-- def test_registers_a_restricted_postgres_query_connection_for_the_team(self):- org = Organization.objects.create(name="Org")- team = Team.objects.create(organization=org)- server = self._server(org)-- with patch(- "products.data_warehouse.backend.presentation.views.managed_warehouse.configure_project_reader",- side_effect=lambda **kwargs: {- "username": f"posthog_team_{kwargs['team_id']}",- "password": kwargs["password"],- },- ):- enable_team_backfill(team_id=team.id, organization_id=org.id, table_name="prod")-- source = ExternalDataSource.objects.get(- team_id=team.id, access_method=ExternalDataSource.AccessMethod.DIRECT, direct_query_enabled=True- )- assert source.source_type == "Postgres"- assert source.job_inputs["host"] == server.host-- def test_direct_connection_failure_does_not_block_enablement(self):- # The connection is a best-effort convenience; a failure must never stop a team joining.- org = Organization.objects.create(name="Org")- team = Team.objects.create(organization=org)- self._server(org)-- with patch(- "products.data_warehouse.backend.managed_warehouse_connection.ensure_managed_warehouse_direct_source",- side_effect=Exception("boom"),- ):- suffix = enable_team_backfill(team_id=team.id, organization_id=org.id, table_name="prod")-- assert suffix == "prod"- assert DuckgresServerTeam.objects.filter(team_id=team.id).count() == 1---class 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 = 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 = self._server_team(table_suffix="prod")-- assert get_team_backfill_state(team.id) == {"has_backfill": True, "table_suffix": "prod"}--class TestDefaultBucketRegion:@parameterized.expand([@@ -418,53 +263,3 @@ class TestValidateDuckgresIdentifier:with pytest.raises(ValueError):validate_duckgres_identifier(ident)---class TestDuckgresDataImportsSchema:- def _team(self):- from posthog.models import Organization, Team-- 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-- team = self._team()- assert duckgres_data_imports_schema(team.id) == f"posthog_data_imports_team_{team.id}"-- def test_falls_back_to_team_id_when_suffix_null_or_empty(self):- from posthog.ducklake.common import duckgres_data_imports_schema-- team = self._team()- link = self._server_team(team, table_suffix=None)- assert duckgres_data_imports_schema(team.id) == f"posthog_data_imports_team_{team.id}"- 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-- team = self._team()- 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-- team = self._team()- self._server_team(team, table_suffix="a;drop")- with pytest.raises(ValueError):- duckgres_data_imports_schema(team.id)diff --git a/posthog/ducklake/test_team_state.py b/posthog/ducklake/test_team_state.pyindex 2a3593ab1818..0d74f4361fbe 100644--- a/posthog/ducklake/test_team_state.py+++ b/posthog/ducklake/test_team_state.py@@ -3,31 +3,22 @@ from datetime import dateimport pytestfrom unittest.mock import patch-from django.test import override_settings-from parameterized import parameterizedfrom posthog.ducklake import cp_teams, team_state-from posthog.ducklake.models import DuckgresServer, DuckgresServerTeamfrom posthog.models import Organization, Team@pytest.fixture(autouse=True)def _reset_cp_state():cp_teams.clear_cache()- team_state.clear_parity_state()yieldcp_teams.clear_cache()- team_state.clear_parity_state()-def _onboarded_team(table_suffix: str | None = "prod") -> tuple[Organization, Team]:+def _team() -> tuple[Organization, 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 org, team@@ -52,110 +43,36 @@ def _patch_org_rows(rows):@pytest.mark.django_db-class TestDataImportsSchemaRouting:- @parameterized.expand(- [- # django (the default) must serve the django value even when the CP disagrees —- # flipping reads is opt-in, never a side effect of a CP edit.- ("django", "posthog_data_imports_prod"),- ("dual", "posthog_data_imports_prod"),- ("cp", "posthog_data_imports_cp_schema"),- ]- )- def test_mode_selects_the_read_source(self, source: str, expected: str) -> None:- org, team = _onboarded_team(table_suffix="prod")- with (- override_settings(DUCKGRES_TEAM_STATE_SOURCE=source),- _patch_org_rows([_cp_row(team, "cp_schema")]),- ):- assert team_state.data_imports_schema(team.id) == expected-- def test_cp_mode_without_cp_row_falls_back_to_team_id_schema(self) -> None:- org, team = _onboarded_team()- with override_settings(DUCKGRES_TEAM_STATE_SOURCE="cp"), _patch_org_rows([]):+class TestDataImportsSchema:+ def test_resolves_from_cp_row(self) -> None:+ org, team = _team()+ with _patch_org_rows([_cp_row(team, "cp_schema")]):+ assert team_state.data_imports_schema(team.id) == "posthog_data_imports_cp_schema"++ def test_without_cp_row_falls_back_to_team_id_schema(self) -> None:+ org, team = _team()+ with _patch_org_rows([]):assert team_state.data_imports_schema(team.id) == f"posthog_data_imports_team_{team.id}"- def test_cp_mode_raises_when_cp_unreachable_and_cache_cold(self) -> None:- org, team = _onboarded_team()- with override_settings(DUCKGRES_TEAM_STATE_SOURCE="cp"), _patch_org_rows(None):+ def test_raises_when_cp_unreachable_and_cache_cold(self) -> None:+ org, team = _team()+ with _patch_org_rows(None):with pytest.raises(team_state.CPUnavailableError):team_state.data_imports_schema(team.id)- def test_cp_mode_serves_cached_rows_during_an_outage(self) -> None:- org, team = _onboarded_team()- with override_settings(DUCKGRES_TEAM_STATE_SOURCE="cp"):- with _patch_org_rows([_cp_row(team, "cp_schema")]):- team_state.data_imports_schema(team.id)- with _patch_org_rows(None):- assert team_state.data_imports_schema(team.id) == "posthog_data_imports_cp_schema"-- def test_django_mode_never_touches_the_control_plane(self) -> None:- org, team = _onboarded_team()- with patch("posthog.ducklake.cp_teams._fetch_org_rows") as mock_fetch:- team_state.data_imports_schema(team.id)- mock_fetch.assert_not_called()---class TestDualModeParityTelemetry:- def test_mismatch_emits_counter_and_rate_limited_log(self) -> None:- org, team = _onboarded_team(table_suffix="prod")- with (- override_settings(DUCKGRES_TEAM_STATE_SOURCE="dual"),- _patch_org_rows([_cp_row(team, "other")]),- patch("statshog.defaults.django.statsd") as mock_statsd,- patch.object(team_state.logger, "warning") as mock_warning,- ):- assert team_state.data_imports_schema(team.id) == "posthog_data_imports_prod"- # Second call within the TTL window: counted again, but not logged again.+ def test_serves_cached_rows_during_an_outage(self) -> None:+ org, team = _team()+ with _patch_org_rows([_cp_row(team, "cp_schema")]):team_state.data_imports_schema(team.id)-- counters = [call.args[0] for call in mock_statsd.incr.call_args_list]- assert counters.count(team_state.PARITY_CHECKS_COUNTER) == 2- assert counters.count(team_state.PARITY_MISMATCH_COUNTER) == 2- mismatch_logs = [- call for call in mock_warning.call_args_list if call.args[0] == "duckgres_team_state_parity_mismatch"- ]- assert len(mismatch_logs) == 1- assert mismatch_logs[0].kwargs == {- "team_id": team.id,- "field": "data_imports_schema",- "django_value": "posthog_data_imports_prod",- "cp_value": "posthog_data_imports_other",- "call_site": "data_imports_schema",- }-- def test_agreement_emits_check_but_no_mismatch(self) -> None:- org, team = _onboarded_team(table_suffix="prod")- with (- override_settings(DUCKGRES_TEAM_STATE_SOURCE="dual"),- _patch_org_rows([_cp_row(team, "prod")]),- patch("statshog.defaults.django.statsd") as mock_statsd,- ):- assert team_state.data_imports_schema(team.id) == "posthog_data_imports_prod"- counters = [call.args[0] for call in mock_statsd.incr.call_args_list]- assert team_state.PARITY_CHECKS_COUNTER in counters- assert team_state.PARITY_MISMATCH_COUNTER not in counters-- def test_cp_unavailable_serves_django_and_counts_distinctly(self) -> None:- org, team = _onboarded_team(table_suffix="prod")- with (- override_settings(DUCKGRES_TEAM_STATE_SOURCE="dual"),- _patch_org_rows(None),- patch("statshog.defaults.django.statsd") as mock_statsd,- patch.object(team_state.logger, "warning") as mock_warning,- ):- assert team_state.data_imports_schema(team.id) == "posthog_data_imports_prod"- counters = [call.args[0] for call in mock_statsd.incr.call_args_list]- assert counters == [team_state.PARITY_CP_UNAVAILABLE_COUNTER]- assert not any(call.args[0] == "duckgres_team_state_parity_mismatch" for call in mock_warning.call_args_list)+ with _patch_org_rows(None):+ assert team_state.data_imports_schema(team.id) == "posthog_data_imports_cp_schema"@pytest.mark.django_db-class TestEventsPersonsTablesRouting:+class TestEventsPersonsTables:@parameterized.expand([- # Derive rule and pin precedence as served through the accessor in cp mode.+ # Derive rule and pin precedence as served through the accessor.("derived", {}, ("events_cp_schema", "persons_cp_schema")),("grandfathered_shared_pins",@@ -164,39 +81,35 @@ class TestEventsPersonsTablesRouting:),])- def test_cp_mode_resolves_from_cp_row(self, _name: str, overrides: dict, expected: tuple[str, str]) -> None:- org, team = _onboarded_team()- with (- override_settings(DUCKGRES_TEAM_STATE_SOURCE="cp"),- _patch_org_rows([_cp_row(team, "cp_schema", **overrides)]),- ):+ def test_resolves_from_cp_row(self, _name: str, overrides: dict, expected: tuple[str, str]) -> None:+ org, team = _team()+ with _patch_org_rows([_cp_row(team, "cp_schema", **overrides)]):assert team_state.resolve_events_persons_tables(team.id) == expected- def test_cp_mode_without_cp_row_falls_back_to_shared_tables(self) -> None:- org, team = _onboarded_team()- with override_settings(DUCKGRES_TEAM_STATE_SOURCE="cp"), _patch_org_rows([]):+ def test_without_cp_row_falls_back_to_shared_tables(self) -> None:+ org, team = _team()+ with _patch_org_rows([]):assert team_state.resolve_events_persons_tables(team.id) == ("events", "persons")- def test_cp_mode_rejects_an_unsafe_resolved_name(self) -> None:+ def test_raises_when_cp_unreachable_and_cache_cold(self) -> None:+ org, team = _team()+ with _patch_org_rows(None):+ with pytest.raises(team_state.CPUnavailableError):+ team_state.resolve_events_persons_tables(team.id)++ def test_rejects_an_unsafe_resolved_name(self) -> None:# Fail-closed SQL-safety: a CP row carrying a hostile identifier must never reach DDL.- org, team = _onboarded_team()- with (- override_settings(DUCKGRES_TEAM_STATE_SOURCE="cp"),- _patch_org_rows([_cp_row(team, "cp_schema", events_table_name="a;drop")]),- ):+ org, team = _team()+ with _patch_org_rows([_cp_row(team, "cp_schema", events_table_name="a;drop")]):with pytest.raises(ValueError):team_state.resolve_events_persons_tables(team.id)- def test_django_mode_uses_the_suffix(self) -> None:- org, team = _onboarded_team(table_suffix="prod")- assert team_state.resolve_events_persons_tables(team.id) == ("events_prod", "persons_prod")-@pytest.mark.django_db-class TestTeamBackfillStateRouting:+class TestTeamBackfillState:@parameterized.expand([- ("dual_write_row_schema_is_suffix", {}, {"has_backfill": True, "table_suffix": "cp_schema"}),+ ("onboarded_row_schema_is_suffix", {}, {"has_backfill": True, "table_suffix": "cp_schema"}),("grandfathered_shared_row_has_no_suffix",{"events_table_name": "events", "persons_table_name": "persons"},@@ -204,12 +117,9 @@ class TestTeamBackfillStateRouting:),])- def test_cp_mode_shapes(self, _name: str, overrides: dict, expected: dict) -> None:- org, team = _onboarded_team()- with (- override_settings(DUCKGRES_TEAM_STATE_SOURCE="cp"),- _patch_org_rows([_cp_row(team, "cp_schema", **overrides)]),- ):+ def test_shapes(self, _name: str, overrides: dict, expected: dict) -> None:+ org, team = _team()+ with _patch_org_rows([_cp_row(team, "cp_schema", **overrides)]):assert team_state.team_backfill_state(team.id) == expected@parameterized.expand(@@ -219,25 +129,14 @@ class TestTeamBackfillStateRouting:("cp_unreachable", None),])- def test_cp_mode_falls_back_to_not_onboarded(self, _name: str, rows) -> None:- org, team = _onboarded_team()- with override_settings(DUCKGRES_TEAM_STATE_SOURCE="cp"), _patch_org_rows(rows):+ def test_falls_back_to_not_onboarded(self, _name: str, rows) -> None:+ org, team = _team()+ with _patch_org_rows(rows):assert team_state.team_backfill_state(team.id) == {"has_backfill": False, "table_suffix": None}- def test_dual_mode_serves_django_and_flags_divergence(self) -> None:- org, team = _onboarded_team(table_suffix="prod")- with (- override_settings(DUCKGRES_TEAM_STATE_SOURCE="dual"),- _patch_org_rows([]),- patch("statshog.defaults.django.statsd") as mock_statsd,- ):- assert team_state.team_backfill_state(team.id) == {"has_backfill": True, "table_suffix": "prod"}- counters = [call.args[0] for call in mock_statsd.incr.call_args_list]- assert team_state.PARITY_MISMATCH_COUNTER in counters-@pytest.mark.django_db-class TestBackfillRowExistsRouting:+class TestBackfillRowExists:@parameterized.expand([("cp_row_present", "present", True),@@ -246,37 +145,19 @@ class TestBackfillRowExistsRouting:("cp_unreachable_fails_closed", "unreachable", True),])- def test_cp_mode(self, _name: str, cp_state: str, expected: bool) -> None:- org, team = _onboarded_team()+ def test_postures(self, _name: str, cp_state: str, expected: bool) -> None:+ org, team = _team()rows = {"present": [_cp_row(team, "cp_schema")], "absent": [], "unreachable": None}[cp_state]- with override_settings(DUCKGRES_TEAM_STATE_SOURCE="cp"), _patch_org_rows(rows):+ with _patch_org_rows(rows):assert team_state.backfill_row_exists(team.id, str(org.id)) is expected- def test_dual_mode_serves_django(self) -> None:- org, team = _onboarded_team()- with (- override_settings(DUCKGRES_TEAM_STATE_SOURCE="dual"),- _patch_org_rows([]),- patch("statshog.defaults.django.statsd"),- ):- assert team_state.backfill_row_exists(team.id, str(org.id)) is True-@pytest.mark.django_dbclass TestListEnabledBackfillRows:- def test_django_mode_returns_model_rows(self) -> None:- org, team = _onboarded_team()- rows = team_state.list_enabled_backfill_rows("test")- assert [row.team_id for row in rows] == [team.id]- assert isinstance(rows[0], DuckgresServerTeam)-- def test_cp_mode_returns_cp_rows_with_server_shim(self) -> None:- org, team = _onboarded_team()+ def test_returns_cp_rows_with_server_shim(self) -> None:+ org, team = _team()cp_rows = [_cp_row(team, "cp_schema", earliest_event_date="2020-06-15")]- with (- override_settings(DUCKGRES_TEAM_STATE_SOURCE="cp"),- patch("posthog.ducklake.cp_teams._fetch_all_rows", return_value=cp_rows),- ):+ with patch("posthog.ducklake.cp_teams._fetch_all_rows", return_value=cp_rows):rows = team_state.list_enabled_backfill_rows("test")assert len(rows) == 1row = rows[0]@@ -285,25 +166,12 @@ class TestListEnabledBackfillRows:# The sensors reach the org through the server FK; the CP row must mirror that shape.assert row.server.organization_id == str(org.id)- def test_cp_mode_returns_empty_without_raising_when_cp_down(self) -> None:- with (- override_settings(DUCKGRES_TEAM_STATE_SOURCE="cp"),- patch("posthog.ducklake.cp_teams._fetch_all_rows", return_value=None),- ):+ def test_excludes_rows_with_backfill_disabled(self) -> None:+ org, team = _team()+ cp_rows = [_cp_row(team, "cp_schema", backfill_enabled=False)]+ with patch("posthog.ducklake.cp_teams._fetch_all_rows", return_value=cp_rows):assert team_state.list_enabled_backfill_rows("test") == []- def test_dual_mode_flags_membership_and_date_divergence(self) -> None:- org, team = _onboarded_team()- cp_rows = [_cp_row(team, "cp_schema", earliest_event_date="2020-06-15"), _cp_row(team, "x", team_id=999_999)]- with (- override_settings(DUCKGRES_TEAM_STATE_SOURCE="dual"),- patch("posthog.ducklake.cp_teams._fetch_all_rows", return_value=cp_rows),- patch("statshog.defaults.django.statsd") as mock_statsd,- ):- rows = team_state.list_enabled_backfill_rows("test")- # Django rows are served untouched.- assert [row.team_id for row in rows] == [team.id]- assert isinstance(rows[0], DuckgresServerTeam)- # Two mismatches: the django row's earliest date differs, and the CP-only team 999999.- counters = [call.args[0] for call in mock_statsd.incr.call_args_list]- assert counters.count(team_state.PARITY_MISMATCH_COUNTER) == 2+ def test_returns_empty_without_raising_when_cp_down(self) -> None:+ with patch("posthog.ducklake.cp_teams._fetch_all_rows", return_value=None):+ assert team_state.list_enabled_backfill_rows("test") == []diff --git a/posthog/migrations/1265_delete_duckgresserverteam.py b/posthog/migrations/1265_delete_duckgresserverteam.pynew file mode 100644index 000000000000..f7a1765efb8a--- /dev/null+++ b/posthog/migrations/1265_delete_duckgresserverteam.py@@ -0,0 +1,19 @@+from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [("posthog", "1264_delete_revenue_analytics_user_product_list")]++ operations = [+ # State-only: per-team managed-warehouse state now lives in the duckgres+ # control plane, so the model goes, but the posthog_duckgresserverteam table+ # is kept for now (deploy safety: old code may still read it mid-rollout).+ # A later RunSQL migration can DROP TABLE once this has been out for a full+ # deploy cycle.+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.DeleteModel(name="DuckgresServerTeam"),+ ],+ database_operations=[],+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 872666d56a96..228eacb3aaed 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1264_delete_revenue_analytics_user_product_list+1265_delete_duckgresserverteamdiff --git a/posthog/models/__init__.py b/posthog/models/__init__.pyindex c29d02f3ed28..b0887721378d 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, DuckgresSinkSchemaState+from ..ducklake.models import DuckgresServer, DuckgresSinkSchemaStatefrom .element import Elementfrom .element_group import ElementGroupfrom .entity import Entity@@ -102,7 +102,6 @@ __all__ = ["DataColorTheme","DeletionType","DuckgresServer",- "DuckgresServerTeam","DuckgresSinkSchemaState","Element","ElementGroup",diff --git a/posthog/settings/base_variables.py b/posthog/settings/base_variables.pyindex eb998ddc5fed..1b5c996b32c8 100644--- a/posthog/settings/base_variables.py+++ b/posthog/settings/base_variables.py@@ -76,10 +76,6 @@ PERSONAL_SPEND_CROSS_REGION_SECRET: str = get_from_env("PERSONAL_SPEND_CROSS_REGDUCKGRES_API_URL: str | None = get_from_env("DUCKGRES_API_URL", optional=True)DUCKGRES_INTERNAL_SECRET: str | None = get_from_env("DUCKGRES_INTERNAL_SECRET", optional=True)DUCKGRES_PG_PORT: int = get_from_env("DUCKGRES_PG_PORT", 5432, type_cast=int)-# Read source for per-team managed-warehouse state: "django" (DuckgresServerTeam rows,-# the default), "dual" (serve django, compare against the duckgres control plane and emit-# parity telemetry), or "cp" (serve the control plane org-teams API).-DUCKGRES_TEAM_STATE_SOURCE: str = get_from_env("DUCKGRES_TEAM_STATE_SOURCE", "django")# Bulk deletion operations can be disabled during database migrationsDISABLE_BULK_DELETES: bool = get_from_env("DISABLE_BULK_DELETES", False, type_cast=str_to_bool)diff --git a/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py b/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.pyindex 560d081cfc4f..cf3b2e8504c2 100644--- a/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py+++ b/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py@@ -213,7 +213,7 @@ async def prepare_data_imports_ducklake_metadata_activity(# Per-source mutual exclusion with the Duckgres v3 batch sink. The sink owns a# registered team's v3 sources (it mirrors them live + backfills history), so# drop those here; non-v3 sources stay on the copy workflow because the sink never- # touches them. A flagged team without a DuckgresServerTeam membership remains+ # touches them. A flagged team without a duckgres control-plane team row remains# on this copy path until it completes the enable flow.# is_pipeline_v3_enabled is the same gate the v3 router uses, so "copy" and# "sink" never disagree on who owns a source (and both fail to "copy owns it").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 90acf6a4e74d..d5bc172d3645 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@@ -13,7 +13,8 @@ import temporalio.converterfrom temporalio import activity as temporal_activityfrom temporalio.testing import WorkflowEnvironment-from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam+from posthog.ducklake import cp_teams+from posthog.ducklake.models import DuckgresServerfrom posthog.ducklake.storage import compute_staging_urifrom posthog.ducklake.verification import DuckLakeCopyVerificationParameter, DuckLakeCopyVerificationQueryfrom posthog.sync import database_sync_to_async@@ -39,6 +40,18 @@ from products.warehouse_sources.backend.facade.models import ()[email protected](autouse=True)+def _cp_no_rows():+ # The data-imports schema resolves via the team's control-plane row; serve the+ # no-row (legacy team-id schema) shape so these tests stay CP-independent.+ from unittest.mock import patch++ cp_teams.clear_cache()+ with patch("posthog.ducklake.cp_teams._fetch_org_rows", return_value=[]):+ yield+ cp_teams.clear_cache()++class _FakeColumn:def __init__(self, name: str, type_code: int) -> None:self.name = name@@ -139,14 +152,20 @@ async def test_prepare_excludes_only_v3_sink_owned_schemas(ateam, monkeypatch):create_job_model, "is_pipeline_v3_enabled", lambda team_id, source_type: source_type == "Postgres")- server = await database_sync_to_async(DuckgresServer.objects.create)(+ await database_sync_to_async(DuckgresServer.objects.create)(organization_id=ateam.organization_id,host="h",username="root",password="x",bucket="bucket",)- membership = await database_sync_to_async(DuckgresServerTeam.objects.create)(server=server, team=ateam)+ # Sink membership now lives in the duckgres control plane; toggle it at the seam the+ # activity reads (membership resolution itself is covered in the enablement tests).+ member = {"value": True}+ monkeypatch.setattr(+ "posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.is_duckgres_sink_team_member",+ lambda team_id: member["value"],+ )credential = await database_sync_to_async(DataWarehouseCredential.objects.create)(team=ateam, access_key="k", access_secret="s"@@ -183,7 +202,7 @@ async def test_prepare_excludes_only_v3_sink_owned_schemas(ateam, monkeypatch):# v3 source dropped (sink owns it); non-v3 source still copied.assert [m.source_schema_id for m in result] == [str(non_v3_schema.id)]- await database_sync_to_async(membership.delete)()+ member["value"] = Falseresult_without_membership = await prepare_data_imports_ducklake_metadata_activity(inputs)assert {m.source_schema_id for m in result_without_membership} == {str(v3_schema.id), str(non_v3_schema.id)}diff --git a/products/data_warehouse/backend/logic/managed_warehouse_data_status.py b/products/data_warehouse/backend/logic/managed_warehouse_data_status.pyindex 793967fe6024..6d248aea4573 100644--- a/products/data_warehouse/backend/logic/managed_warehouse_data_status.py+++ b/products/data_warehouse/backend/logic/managed_warehouse_data_status.py@@ -5,7 +5,8 @@ from typing import Literal, TypedDictfrom django.utils import timezone-from posthog.ducklake.models import DuckgresServerTeam, DuckgresSinkSchemaState+from posthog.ducklake.cp_teams import CPTeam+from posthog.ducklake.models import DuckgresSinkSchemaStatefrom products.data_warehouse.backend.logic.backfill_status import historical_backfill_monthsfrom products.data_warehouse.backend.models import ManagedWarehouseBackfillPartition@@ -88,7 +89,7 @@ class ManagedWarehouseDataStatus(TypedDict):generated_at: datetime-def _event_historical_partition_count(backfill: DuckgresServerTeam) -> int | None:+def _event_historical_partition_count(backfill: CPTeam) -> int | None:if backfill.earliest_event_date is None:return None@@ -99,7 +100,7 @@ def _event_historical_partition_count(backfill: DuckgresServerTeam) -> int | Nondef dataset_status(*,dataset: Literal["events", "persons"],- backfill: DuckgresServerTeam | None,+ backfill: CPTeam | None,partitions: list[ManagedWarehouseBackfillPartition],) -> DatasetStatus:if backfill is None or not backfill.backfill_enabled:@@ -362,7 +363,13 @@ def _roll_up_state(states: list[ReadinessState]) -> ReadinessState:def get_managed_warehouse_data_status(team_id: int) -> ManagedWarehouseDataStatus:- backfill = DuckgresServerTeam.objects.filter(team_id=team_id).first()+ # Deferred: team_state pulls ducklake.common (and its duckdb dependency) in — keep+ # that off the API import path.+ from posthog.ducklake import team_state # noqa: PLC0415++ # Degrades to None (reported not_configured) when the control plane can't answer:+ # a status read must never 500.+ backfill = team_state.team_backfill_row(team_id)partitions = list(ManagedWarehouseBackfillPartition.objects.for_team(team_id).filter(environment_id=team_id)diff --git a/products/data_warehouse/backend/managed_warehouse_connection.py b/products/data_warehouse/backend/managed_warehouse_connection.pyindex 8b1f57bf52a1..97848792073c 100644--- a/products/data_warehouse/backend/managed_warehouse_connection.py+++ b/products/data_warehouse/backend/managed_warehouse_connection.py@@ -153,24 +153,37 @@ def _ensure_managed_source_locked()+def _membership_table_suffix(*, team_id: int, organization_id: str | UUID) -> str:+ """The team's warehouse table suffix from its duckgres control-plane row.++ Raises RuntimeError when the control plane can't answer (callers treat that like the+ reader handshake being unavailable and retry on a later sweep) and ValueError when the+ team has no backfill-enabled row or sits on the legacy shared tables — neither can be+ exposed as a per-project query connection.+ """+ from posthog.ducklake import cp_teams, team_state # noqa: PLC0415 — keeps duckdb off this module's import path++ teams = cp_teams.list_org_teams(str(organization_id))+ if teams is None:+ raise RuntimeError("The managed warehouse control plane is unreachable")+ row = next((team for team in teams if team.team_id == team_id), None)+ if row is None or not row.backfill_enabled:+ raise ValueError("The team has not joined this managed warehouse")+ table_suffix = team_state.cp_table_suffix(row)+ if not table_suffix:+ raise ValueError("Legacy shared managed warehouse tables cannot be exposed as a query connection")+ return table_suffix++def ensure_managed_warehouse_direct_source(*, team_id: int, organization_id: str | UUID) -> ExternalDataSource:"""Create or refresh the team's restricted live-query source from its membership."""- from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam # noqa: PLC0415+ from posthog.ducklake.models import DuckgresServer # noqa: PLC0415++ table_suffix = _membership_table_suffix(team_id=team_id, organization_id=organization_id)with transaction.atomic():server = DuckgresServer.objects.select_for_update().get(organization_id=organization_id)Team.objects.select_for_update().only("id").get(id=team_id, organization_id=organization_id)- membership = (- DuckgresServerTeam.objects.select_for_update()- .filter(server=server, team_id=team_id, backfill_enabled=True)- .values("table_suffix")- .first()- )- if membership is None:- raise ValueError("The team has not joined this managed warehouse")- table_suffix = membership["table_suffix"]- if not table_suffix:- raise ValueError("Legacy shared managed warehouse tables cannot be exposed as a query connection")existing = _managed_source_queryset(team_id).select_for_update().filter(deleted=False).first()existing_metadata = existing.connection_metadata if existing is not None else None@@ -217,16 +230,8 @@ def ensure_managed_warehouse_direct_source(*, team_id: int, organization_id: strraise RuntimeError("Managed warehouse reader credentials did not match the requested credentials")with transaction.atomic():- server = DuckgresServer.objects.select_for_update().get(organization_id=organization_id)+ DuckgresServer.objects.select_for_update().get(organization_id=organization_id)Team.objects.select_for_update().only("id").get(id=team_id, organization_id=organization_id)- membership_exists = DuckgresServerTeam.objects.select_for_update().filter(- server=server,- team_id=team_id,- backfill_enabled=True,- table_suffix=table_suffix,- )- if not membership_exists.exists():- raise ValueError("The team has not joined this managed warehouse")source = _managed_source_queryset(team_id).select_for_update().filter(id=source_id, deleted=False).first()if source is None or not isinstance(source.job_inputs, dict):raise RuntimeError("Managed warehouse query source changed while its reader was configured")@@ -241,7 +246,7 @@ def ensure_managed_warehouse_direct_source(*, team_id: int, organization_id: strdef reconcile_managed_warehouse_tables(*, team_id: int, organization_id: str | UUID) -> None:"""Discover and register only this team's managed-warehouse tables."""- from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam # noqa: PLC0415+ from posthog.ducklake.models import DuckgresServer # noqa: PLC0415try:ensure_managed_warehouse_direct_source(team_id=team_id, organization_id=organization_id)@@ -259,24 +264,6 @@ def reconcile_managed_warehouse_tables(*, team_id: int, organization_id: str | Uif server is None or team is None:return- membership_data = (- DuckgresServerTeam.objects.select_for_update()- .filter(- server=server,- team_id=team_id,- team__organization_id=organization_id,- backfill_enabled=True,- )- .values("table_suffix")- .first()- )- if membership_data is None:- return-- table_suffix = membership_data["table_suffix"]- if not table_suffix:- # Legacy tables are shared across teams and require a team_id predicate that direct HogQL cannot enforce.- returnsource = _managed_source_queryset(team_id).select_for_update().filter(deleted=False).first()if source is None:return@@ -314,22 +301,11 @@ def reconcile_managed_warehouse_tables(*, team_id: int, organization_id: str | Ureturnwith transaction.atomic():- # Revalidate after live introspection so deprovision or membership removal wins the race.+ # Revalidate after live introspection so deprovision wins the race.server = DuckgresServer.objects.select_for_update().filter(organization_id=organization_id).first()team = Team.objects.select_for_update().only("id").filter(id=team_id, organization_id=organization_id).first()if server is None or team is None:return- membership = (- DuckgresServerTeam.objects.select_for_update()- .filter(- server=server,- team_id=team_id,- team__organization_id=organization_id,- table_suffix=table_suffix,- backfill_enabled=True,- )- .first()- )source = (_managed_source_queryset(team_id).select_for_update()@@ -341,7 +317,7 @@ def reconcile_managed_warehouse_tables(*, team_id: int, organization_id: str | U).first())- if membership is None or source is None:+ if source is None:returnfor schema in source_schemas:@@ -380,14 +356,17 @@ def update_managed_warehouse_root_password(*, organization_id: str | UUID, passwdef soft_delete_managed_warehouse_sources(*, organization_id: str | UUID) -> None:- """Atomically tombstone the organization's managed query sources on deprovision."""- from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam # noqa: PLC0415+ """Atomically tombstone the organization's managed query sources on deprovision.++ Per-team state needs no disabling here: deprovisioning removes the org's team rows+ from the duckgres control plane, which is the read source for membership.+ """+ from posthog.ducklake.models import DuckgresServer # noqa: PLC0415now = timezone.now()with transaction.atomic():DuckgresServer.objects.select_for_update().filter(organization_id=organization_id).first()sources = list(_managed_sources_for_org(organization_id).select_for_update().order_by("team_id"))- DuckgresServerTeam.objects.filter(server__organization_id=organization_id).update(backfill_enabled=False)DataWarehouseTable.raw_objects.filter(external_data_source_id__in=[source.id for source in sources], deleted=False).update(deleted=True, deleted_at=now, updated_at=now)diff --git a/products/data_warehouse/backend/presentation/views/managed_warehouse.py b/products/data_warehouse/backend/presentation/views/managed_warehouse.pyindex 62738bfbd72d..639e9cb37494 100644--- a/products/data_warehouse/backend/presentation/views/managed_warehouse.py+++ b/products/data_warehouse/backend/presentation/views/managed_warehouse.py@@ -12,11 +12,10 @@ per organization (not per team).import refrom datetime import date-from typing import TypedDict, cast+from typing import TypedDictfrom uuid import UUIDfrom django.conf import settings-from django.db import transactionimport requests as http_requestsimport structlog@@ -350,7 +349,7 @@ def provision(# Complete the row BEFORE registering the team: registration kicks off the# SQL-editor reader handshake, whose namespace grants derive from this row._complete_provisioning_team_row(organization_id, team_id, schema_name, require_enabled=require_enabled)- _register_provisioning_team(organization_id, team_id, schema_name)+ _register_provisioning_team(organization_id, team_id)# The bucket is internal infra detail, persisted above and consumed by the# backfill via cp_bucket_for — not part of the UI-facing ProvisionWarehouseResponse# schema. Strip it so the response matches its OpenAPI contract.@@ -366,9 +365,9 @@ def _complete_provisioning_team_row(The provision body cannot carry them, and without them the team's SQL-editor reader isgranted only the derived schemas no data lands in yet (see onboard_team). Best-effort:the warehouse is already provisioned, so a transient failure must not fail the provision —- re-running onboarding (or the grandfather upsert) completes the row later.+ re-running onboarding completes the row later."""- legacy = _grandfathered_team_fields(team_id, schema_name)+ legacy = _legacy_table_fields(schema_name)resp = create_team(organization_id,team_id,@@ -409,29 +408,40 @@ def team_backfill_state(team_id: int) -> dict:return get_team_backfill_state(team_id)-def _register_provisioning_team(organization_id: UUID | str, team_id: int, schema_name: str) -> None:- """Record the provisioning (calling) team's duckling membership and enable its backfill.+def _register_provisioning_team(organization_id: UUID | str, team_id: int) -> None:+ """Finish the provisioning (calling) team's onboarding after its row exists.- A managed warehouse is org-scoped, but membership and backfills are per team, so provision- registers only the provisioning team: a single `DuckgresServerTeam` row carrying its- membership and a backfill enabled with the schema name chosen at provision (stored as the- team's table suffix, which Dagster still reads). duckgres creates its own team row from the- provision request itself. Other teams join later via `onboard_team`, which runs the same- dual-write.+ duckgres creates the provisioning team's row from the provision request itself (and+ `_complete_provisioning_team_row` pins its legacy table names), so nothing is written+ here — the team just gets its SQL-editor query connection and its earliest-event-date+ sync kicked off, the same tail `onboard_team` runs for later teams.- Best-effort, mirroring `_persist_duckgres_server`: a failure is logged, not raised, so the- one-time provision password is never lost to it.+ Best-effort, mirroring `_persist_duckgres_server`: a failure is logged, not raised, so+ the one-time provision password is never lost to it."""- # Keep ducklake.common (and its duckdb dependency) off the API import path.- from posthog.ducklake.common import enable_team_backfill # noqa: PLC0415-try:- enable_team_backfill(team_id=team_id, organization_id=organization_id, table_name=schema_name)+ _ensure_direct_source(team_id, organization_id)_schedule_earliest_event_date_sync(team_id)except Exception:logger.exception("Failed to register provisioning team after provision", team_id=team_id)+def _ensure_direct_source(team_id: int, organization_id: UUID | str) -> None:+ """Best-effort: register the org's managed warehouse as the team's restricted query connection.++ A managed warehouse speaks the Postgres wire protocol, so each member team gets an+ ExternalDataSource pointed at the org server. Duckgres scopes its credential to the+ project and enforces read-only SQL. A failure here must never block onboarding.+ """+ try:+ # Keep the data_warehouse/warehouse_sources stack off this adapter's import path.+ from products.data_warehouse.backend.facade.api import ensure_managed_warehouse_direct_source # noqa: PLC0415++ ensure_managed_warehouse_direct_source(team_id=team_id, organization_id=organization_id)+ except Exception:+ logger.exception("Failed to register managed warehouse query source", team_id=team_id)++def _persist_duckgres_server(organization_id: UUID | str, database_name: str | None, body: dict) -> None:"""Persist the org's DuckgresServer row from a successful provision response.@@ -541,13 +551,12 @@ def update_team(def push_team_earliest_event_date(organization_id: UUID | str, team_id: int, earliest: date | None) -> bool:- """Best-effort mirror of a team's cached earliest event date onto its duckgres team row.+ """Persist a team's resolved earliest event date (incl. the no-history sentinel) onto+ its duckgres team row — the read source for the backfill sensors.- Part of the dual-write moving per-team backfill state into the control plane: the- Django ``DuckgresServerTeam.earliest_event_date`` (including the no-history sentinel)- stays the read source for now, so a failure here is logged and swallowed — a later- push (the provisioning-time task or the full-backfill sensor) converges the CP row.- Returns True when the control plane accepted the value.+ A failure is logged and swallowed; returns True when the control plane accepted the+ value, so callers (the provisioning-time task, the full-backfill sensor) can leave+ the date unresolved and retry on a later tick."""if earliest is None:return False@@ -572,23 +581,19 @@ def push_team_earliest_event_date(organization_id: UUID | str, team_id: int, eardef _schedule_earliest_event_date_sync(team_id: int) -> None:- """Dispatch the earliest-event-date resolution task once the membership row commits.+ """Dispatch the earliest-event-date resolution task for a freshly onboarded team.- ``transaction.on_commit`` so the task never races a rollback of the row it reads (it- runs immediately in autocommit). Best-effort: a dispatch failure is logged, not- raised — the full-backfill sensor resolves the date lazily regardless.+ Best-effort: a dispatch failure is logged, not raised — the full-backfill sensor+ resolves the date lazily regardless."""# Keep the Celery task module (and its import graph) off the API import path; the# facade is the allowed boundary for presentation -> tasks.from products.data_warehouse.backend.facade.tasks import sync_team_earliest_event_date # noqa: PLC0415- def dispatch() -> None:- try:- sync_team_earliest_event_date.delay(team_id)- except Exception:- logger.exception("Failed to schedule earliest event date sync", team_id=team_id)-- transaction.on_commit(dispatch)+ try:+ sync_team_earliest_event_date.delay(team_id)+ except Exception:+ logger.exception("Failed to schedule earliest event date sync", team_id=team_id)def delete_team(organization_id: UUID | str, team_id: int, require_enabled: bool = True) -> Response:@@ -605,11 +610,14 @@ def onboard_team() -> Response:"""Onboard a team onto the org's existing managed warehouse with its own schema.- Dual-write: creates the duckgres team row (the control plane owns schema uniqueness and- answers 409 on a conflict) and the Django DuckgresServerTeam backfill row, which Dagster- still reads. The Django guards run first so a name the team can't use (already onboarded- with a different name, suffix collision) is rejected before anything is written to the- control plane — the duckgres upsert would otherwise overwrite an existing row's schema.+ The duckgres control plane owns per-team state: it enforces schema uniqueness across+ the org's teams (409 on a conflict, mapped to a user-facing message here) and stores+ the row the backfill sensors and the v3 sink read.++ The schema name is write-once: it names the team's warehouse tables, so changing it+ after data is written would split the team's data across two layouts. The control-plane+ POST is an upsert, so an already-onboarded team is guarded here — re-onboarding with+ the current name is an idempotent no-op, any other name is rejected.Backend/ops callers (the Django admin) pass `require_enabled=False` to bypass theorg feature-flag gate.@@ -622,72 +630,79 @@ def onboard_team(schema_error = _validate_schema_name(schema_name)if schema_error or schema_name is None:return Response({"error": schema_error or "schema_name is required"}, status=status.HTTP_400_BAD_REQUEST)-- # Keep ducklake.common (and its duckdb dependency) off the API import path.- from posthog.ducklake.common import ( # noqa: PLC0415- DucklingBackfillEnableError,- check_team_backfill_enable,- enable_team_backfill,- )-- try:- check_team_backfill_enable(team_id=team_id, organization_id=organization_id, table_name=schema_name)- except DucklingBackfillEnableError as exc:- return Response({"error": str(exc)}, status=status.HTTP_400_BAD_REQUEST)-- # Pin the legacy table names the duckling DAG writes today (posthog.events_<suffix>,- # posthog_data_imports_<suffix>): the suffix for a newly onboarded team IS its schema- # name. A row without them describes the derived layout no data lands in yet, which- # grants the project's SQL-editor reader nothing (the EU placeholder-row bug). Drop- # this once the duckling DAG writes the derived <schema_name>.events layout for real.- legacy = _grandfathered_team_fields(team_id, schema_name)- resp = create_team(- organization_id,- team_id,- schema_name,- events_table_name=legacy["events_table_name"],- persons_table_name=legacy["persons_table_name"],- schema_data_imports_name=legacy["schema_data_imports_name"],- require_enabled=require_enabled,- )- if resp.status_code == status.HTTP_409_CONFLICT:+ if not _org_has_warehouse(organization_id):return Response(- {"error": f"The schema name '{schema_name}' is already used by another project in this organization."},- status=status.HTTP_409_CONFLICT,+ {"error": "No managed warehouse is provisioned for this organization. Provision one first."},+ status=status.HTTP_400_BAD_REQUEST,)- if not status.is_success(resp.status_code):- return resptry:- suffix = enable_team_backfill(team_id=team_id, organization_id=organization_id, table_name=schema_name)- except DucklingBackfillEnableError as exc:- # Rare race: the guards above passed but the write lost to a concurrent onboard. The- # duckgres upsert is idempotent, so a retry after the user picks another name is safe.- return Response({"error": str(exc)}, status=status.HTTP_400_BAD_REQUEST)+ existing = _get_project_team_row(organization_id=organization_id, team_id=team_id)+ except RuntimeError:+ return Response(+ {"error": "Could not read the organization's managed warehouse state. Try again in a few minutes."},+ status=status.HTTP_502_BAD_GATEWAY,+ )+ if existing is not None:+ if existing.get("schema_name") != schema_name:+ events_table = existing.get("events_table_name") or f"events_{existing.get('schema_name')}"+ current = "the shared tables" if events_table == "events" else events_table+ return Response(+ {+ "error": f"This project already writes to {current}, and its warehouse table can't be changed — "+ "that would split its existing data across two tables."+ },+ status=status.HTTP_400_BAD_REQUEST,+ )+ else:+ # Pin the legacy table names the duckling DAG writes today (posthog.events_<suffix>,+ # posthog_data_imports_<suffix>): the suffix for a newly onboarded team IS its schema+ # name. A row without them describes the derived layout no data lands in yet, which+ # grants the project's SQL-editor reader nothing (the EU placeholder-row bug). Drop+ # this once the duckling DAG writes the derived <schema_name>.events layout for real.+ legacy = _legacy_table_fields(schema_name)+ resp = create_team(+ organization_id,+ team_id,+ schema_name,+ events_table_name=legacy["events_table_name"],+ persons_table_name=legacy["persons_table_name"],+ schema_data_imports_name=legacy["schema_data_imports_name"],+ require_enabled=require_enabled,+ )+ if resp.status_code == status.HTTP_409_CONFLICT:+ return Response(+ {"error": f"The schema name '{schema_name}' is already used by another project in this organization."},+ status=status.HTTP_409_CONFLICT,+ )+ if not status.is_success(resp.status_code):+ return resp+ _ensure_direct_source(team_id, organization_id)_schedule_earliest_event_date_sync(team_id)- return Response({"onboarded": True, "schema_name": suffix}, status=status.HTTP_200_OK)+ return Response({"onboarded": True, "schema_name": schema_name}, status=status.HTTP_200_OK)++def _org_has_warehouse(organization_id: UUID | str) -> bool:+ """Whether the org has a provisioned managed warehouse (its connection row exists)."""+ # Keep ducklake.models off the core API import path.+ from posthog.ducklake.models import DuckgresServer # noqa: PLC0415++ return DuckgresServer.objects.filter(organization_id=organization_id).exists()-def _grandfathered_team_fields(team_id: int, table_suffix: str | None) -> dict:- """Map an existing Django backfill row to an explicit duckgres team payload.- Grandfathered teams predate the derived `<schema_name>.events` layout, so their legacy- table names are pinned explicitly: suffixed tables when a suffix is set, the shared- `events`/`persons` tables (what the duckling DAG writes for a NULL suffix) otherwise.+def _legacy_table_fields(schema_name: str) -> dict:+ """The legacy suffix-derived table names to pin on a new duckgres team row.++ The duckling DAG and the v3 sink still write the suffix-derived layout+ (`posthog.events_<schema>`, `posthog_data_imports_<schema>`), so a new row pins those+ names explicitly instead of leaving duckgres to derive the future+ `<schema_name>.events` layout no data lands in yet."""- if table_suffix:- return {- "schema_name": table_suffix,- "events_table_name": f"events_{table_suffix}",- "persons_table_name": f"persons_{table_suffix}",- "schema_data_imports_name": f"posthog_data_imports_{table_suffix}",- }return {- "schema_name": f"team_{team_id}",- "events_table_name": "events",- "persons_table_name": "persons",- "schema_data_imports_name": f"posthog_data_imports_team_{team_id}",+ "events_table_name": f"events_{schema_name}",+ "persons_table_name": f"persons_{schema_name}",+ "schema_data_imports_name": f"posthog_data_imports_{schema_name}",}@@ -706,37 +721,14 @@ def _teams_from_response(resp: Response) -> list[dict] | None:def team_onboarding_state(organization_id: UUID | str, team_id: int) -> dict:"""Resolve the calling team's duckgres onboarding state for the warehouse-status response.- Best-effort on the control-plane side: a failed list-teams call falls back to the Django- backfill row and never fails the status read.-- Lazy grandfather backfill: a team with a Django backfill row but no duckgres team row yet- (onboarded before the control plane tracked teams) is pushed to duckgres here, with its- explicit legacy table names. The push is idempotent (the control plane upserts) and- best-effort — a failure is logged and retried on the next status read.-- Reverse heal: a duckgres team row without a Django backfill row means a dual-write lost its- second half (provision registered the team with the control plane but the Django write- failed, or `onboard_team`'s Django write raced). Recreate the Django row from the duckgres- schema here so Dagster picks the team up, instead of reporting it onboarded forever with no- backfill. Only rows without explicit legacy table names are healed — those are the ones the- dual-write created, where schema name and table suffix are the same identifier.+ Best-effort: a status read must never 500, so a failed list-teams call degrades to the+ not-onboarded shape."""- # Keep ducklake.common (and its duckdb dependency) off the API import path.- from posthog.ducklake.common import get_team_backfill_state # noqa: PLC0415-- backfill = get_team_backfill_state(team_id)- has_django_row = bool(backfill["has_backfill"])- table_suffix = cast(str | None, backfill["table_suffix"])-duckgres_team: dict | None = Nonetry:teams = _teams_from_response(list_teams(organization_id, require_enabled=False))if teams is not None:duckgres_team = next((row for row in teams if _row_team_id(row) == team_id), None)- if duckgres_team is None and has_django_row:- duckgres_team = _push_grandfathered_team(organization_id, team_id, table_suffix)- elif duckgres_team is not None and not has_django_row:- _heal_django_backfill_row(organization_id, team_id, duckgres_team)except Exception:logger.exception("Failed to resolve duckgres team onboarding state",@@ -744,91 +736,12 @@ def team_onboarding_state(organization_id: UUID | str, team_id: int) -> dict:team_id=team_id,)- schema_name: str | None = None- if duckgres_team is not None:- schema_name = duckgres_team.get("schema_name")- elif has_django_row:- # Control plane unreachable but the team is onboarded Django-side: report the schema- # its grandfather push will claim.- schema_name = _grandfathered_team_fields(team_id, table_suffix)["schema_name"]-- return {"team_onboarded": duckgres_team is not None or has_django_row, "schema_name": schema_name}---def _push_grandfathered_team(organization_id: UUID | str, team_id: int, table_suffix: str | None) -> dict | None:- """Push a Django-only warehouse team into duckgres. Returns the pushed row, or None on failure."""- fields = _grandfathered_team_fields(team_id, table_suffix)- resp = create_team(- organization_id,- team_id,- fields["schema_name"],- events_table_name=fields["events_table_name"],- persons_table_name=fields["persons_table_name"],- schema_data_imports_name=fields["schema_data_imports_name"],- require_enabled=False,- )- if not status.is_success(resp.status_code):- logger.warning(- "Failed to push grandfathered team to duckgres",- organization_id=str(organization_id),- team_id=team_id,- status_code=resp.status_code,- )- return None- logger.info(- "duckgres_grandfathered_team_pushed",- organization_id=str(organization_id),- team_id=team_id,- schema_name=fields["schema_name"],- )- return {"team_id": team_id, **fields}---def _heal_django_backfill_row(organization_id: UUID | str, team_id: int, duckgres_team: dict) -> None:- """Recreate the missing Django backfill row for a duckgres-registered team. Best-effort.-- Guarded to rows without explicit legacy table names: those came from the dual-write- (provision or onboard), where the duckgres schema name IS the Django table suffix. Rows- with legacy overrides originate from the grandfather push, which only runs off an existing- Django row — a missing one there is unexpected, so it's logged rather than guessed at.- """- # Keep ducklake.common (and its duckdb dependency) off the API import path.- from posthog.ducklake.common import enable_team_backfill # noqa: PLC0415-- schema_name = duckgres_team.get("schema_name")- has_legacy_names = any(- duckgres_team.get(key) for key in ("events_table_name", "persons_table_name", "schema_data_imports_name")- )- if not schema_name or has_legacy_names:- logger.warning(- "Duckgres team has no Django backfill row and cannot be healed",- organization_id=str(organization_id),- team_id=team_id,- has_legacy_names=has_legacy_names,- )- return- try:- enable_team_backfill(team_id=team_id, organization_id=organization_id, table_name=schema_name)- logger.info(- "duckgres_team_django_backfill_healed",- organization_id=str(organization_id),- team_id=team_id,- schema_name=schema_name,- )- except Exception:- logger.exception(- "Failed to heal Django backfill row for duckgres team",- organization_id=str(organization_id),- team_id=team_id,- )+ schema_name = duckgres_team.get("schema_name") if duckgres_team is not None else None+ return {"team_onboarded": duckgres_team is not None, "schema_name": schema_name}def check_schema_name(organization_id: UUID | str, name: str | None) -> Response:- """Check whether a schema name is free within the org's warehouse.-- Checks both the duckgres team rows and the Django backfill suffixes: a Django-only row- (not yet lazily grandfathered into duckgres) still owns its future schema name.- """+ """Check whether a schema name is free within the org's warehouse."""schema_error = _validate_schema_name(name)if schema_error:return Response({"error": schema_error}, status=status.HTTP_400_BAD_REQUEST)@@ -839,12 +752,6 @@ def check_schema_name(organization_id: UUID | str, name: str | None) -> Responsereturn resptaken = any(row.get("schema_name") == name for row in teams)- if not taken:- # Keep ducklake.models (via ducklake.common's import graph) off the API import path.- from posthog.ducklake.models import DuckgresServerTeam # noqa: PLC0415-- taken = DuckgresServerTeam.objects.filter(team__organization_id=organization_id, table_suffix=name).exists()-return Response({"name": name, "available": not taken}, status=status.HTTP_200_OK)diff --git a/products/data_warehouse/backend/tasks/tasks.py b/products/data_warehouse/backend/tasks/tasks.pyindex 7ec9862c0a75..35e28d042ef2 100644--- a/products/data_warehouse/backend/tasks/tasks.py+++ b/products/data_warehouse/backend/tasks/tasks.py@@ -4,7 +4,6 @@ import structlogfrom celery import shared_taskfrom prometheus_client import Counter-from posthog.ducklake.models import DuckgresServerTeamfrom posthog.redis import get_client, redisfrom posthog.scoping_audit import skip_team_scope_audit@@ -101,14 +100,21 @@ def schedule_soft_delete_managed_warehouse_sources(*, organization_id: str | UUI@shared_task(ignore_result=True, name="products.data_warehouse.backend.tasks.reconcile_all_managed_warehouse_tables")@skip_team_scope_auditdef reconcile_all_managed_warehouse_tables_task() -> None:- memberships = (- DuckgresServerTeam.objects.filter(backfill_enabled=True, table_suffix__isnull=False)- .exclude(table_suffix="")- .values_list("team_id", "server__organization_id")- .iterator()- )- for team_id, organization_id in memberships:- schedule_managed_warehouse_tables_reconcile(team_id=team_id, organization_id=organization_id)+ # Deferred: ducklake pulls duckdb in via common, and that must not load while Celery+ # imports task modules — keep it off this module's import path.+ from posthog.ducklake import cp_teams, team_state # noqa: PLC0415++ rows = cp_teams.list_enabled_backfills()+ if rows is None:+ # Periodic sweep: an unreachable control plane just skips this run — the next+ # scheduled sweep retries.+ logger.warning("Managed warehouse reconcile sweep skipped: control plane unreachable")+ return+ for row in rows:+ if team_state.cp_table_suffix(row) is None:+ # Legacy shared tables can't be exposed as a per-project query connection.+ continue+ schedule_managed_warehouse_tables_reconcile(team_id=row.team_id, organization_id=row.organization_id)def schedule_external_data_failure_digest(team_id: int, *, trigger: str = "inline") -> None:@@ -144,45 +150,48 @@ def send_external_data_failure_digest_task(team_id: int) -> None:@shared_task(ignore_result=True, name="products.data_warehouse.backend.tasks.sync_team_earliest_event_date")-@skip_team_scope_audit # DuckgresServerTeam is on the default Django manager+@skip_team_scope_audit # reads the duckgres control plane, not team-scoped Django modelsdef sync_team_earliest_event_date(team_id: int) -> None:- """Resolve, cache, and mirror a team's earliest event date after provision/onboard.-- Dual-write: the clamped earliest event date is stored on the Django- ``DuckgresServerTeam`` row — the full-backfill sensor's read source — and mirrored to- the team's duckgres control-plane row.- Idempotent: an already-cached date is never recomputed, and both writes are upserts.- Best-effort on the control-plane side: a failed push is logged and dropped — the- sensor's reconciliation pass re-pushes it on a later tick.-- A team with no events yet is left unresolved (NULL), NOT cached as the no-history- sentinel: this task runs seconds after provision/onboard, when a brand-new project- plausibly hasn't ingested its first events. A cached date is final (nothing+ """Resolve and persist a team's earliest event date after provision/onboard.++ The clamped earliest event date is stored on the team's duckgres control-plane row —+ the full-backfill sensor's read source. Idempotent: an already-cached date is never+ recomputed. Best-effort: a failed push (or an unreachable control plane) is logged+ and dropped — the full-backfill sensor resolves and persists the date lazily on a+ later tick regardless.++ A team with no events yet is left unresolved (nothing stored), NOT cached as the+ no-history sentinel: this task runs seconds after provision/onboard, when a brand-new+ project plausibly hasn't ingested its first events. A cached date is final (nothingre-resolves a non-NULL value), so persisting the sentinel here would permanentlyexclude the team from historical backfill. The full-backfill sensor resolves itlater, when "no events" is a meaningful answer."""- # Deferred: ducklake.common pulls duckdb in, and posthog.models must not load while- # Celery imports task modules — keep both off this module's import path.- from posthog.ducklake.common import NO_HISTORY_SENTINEL, resolve_team_earliest_event_date # noqa: PLC0415- from posthog.ducklake.models import DuckgresServerTeam # noqa: PLC0415+ # Deferred: ducklake pulls duckdb in via common, and posthog.models must not load+ # while Celery imports task modules — keep both off this module's import path.+ from posthog.ducklake import cp_teams # noqa: PLC0415+ from posthog.ducklake.common import ( # noqa: PLC0415+ NO_HISTORY_SENTINEL,+ _get_org_id_for_team,+ resolve_team_earliest_event_date,+ )from products.data_warehouse.backend.presentation.views.managed_warehouse import ( # noqa: PLC0415push_team_earliest_event_date,)- bf = DuckgresServerTeam.objects.select_related("server").filter(team_id=team_id).first()- if bf is None:- logger.info("No duckling membership row for team; skipping earliest event date sync", team_id=team_id)+ organization_id = _get_org_id_for_team(team_id)+ row = cp_teams.get_team(organization_id, team_id)+ if row is None:+ logger.info("No duckling team row for team; skipping earliest event date sync", team_id=team_id)+ return+ if row.earliest_event_date is not None:+ return+ resolved = resolve_team_earliest_event_date(team_id)+ if resolved == NO_HISTORY_SENTINEL:+ logger.info("No events for team yet; leaving earliest event date unresolved", team_id=team_id)return- if bf.earliest_event_date is None:- resolved = resolve_team_earliest_event_date(team_id)- if resolved == NO_HISTORY_SENTINEL:- logger.info("No events for team yet; leaving earliest event date unresolved", team_id=team_id)- return- bf.earliest_event_date = resolved- bf.save(update_fields=["earliest_event_date"])- push_team_earliest_event_date(bf.server.organization_id, team_id, bf.earliest_event_date)+ push_team_earliest_event_date(organization_id, team_id, resolved)@shared_task(ignore_result=True, name="products.data_warehouse.backend.tasks.send_external_data_failure_digest_catchup")diff --git a/products/data_warehouse/backend/tests/api/test_managed_warehouse.py b/products/data_warehouse/backend/tests/api/test_managed_warehouse.pyindex cbdb27fab6ef..d76db23e926f 100644--- a/products/data_warehouse/backend/tests/api/test_managed_warehouse.py+++ b/products/data_warehouse/backend/tests/api/test_managed_warehouse.py@@ -1,3 +1,4 @@+from types import SimpleNamespacefrom uuid import uuid4import pytest@@ -8,12 +9,29 @@ from django.test import override_settingsfrom parameterized import parameterizedfrom rest_framework.response import Response-from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam+from posthog.ducklake import cp_teams+from posthog.ducklake.models import DuckgresServerfrom posthog.models import Organization, Teamfrom products.data_warehouse.backend.presentation.views import managed_warehouse[email protected](autouse=True)+def _onboarding_side_effects():+ """Isolate onboarding's best-effort tail (query-connection setup + earliest-date sync).++ Both are real calls now that they run inline (no dual-write / on_commit), so patch them+ at the facade boundary to keep the control-plane request assertions exact.+ """+ cp_teams.clear_cache()+ with (+ patch("products.data_warehouse.backend.facade.tasks.sync_team_earliest_event_date") as mock_task,+ patch("products.data_warehouse.backend.facade.api.ensure_managed_warehouse_direct_source") as mock_ensure,+ ):+ yield SimpleNamespace(task=mock_task, ensure=mock_ensure)+ cp_teams.clear_cache()++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")def test_configure_project_reader_creates_a_missing_team_row_before_rotating_credentials(mock_request: MagicMock,@@ -350,10 +368,10 @@ def test_provision_persists_bucket_returned_by_control_plane(@pytest.mark.django_db@override_settings(CLOUD_DEPLOYMENT="US", DUCKGRES_PG_PORT=5432)@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")-def test_provision_enables_backfill_for_calling_team_only(mock_request: MagicMock) -> None:+def test_provision_registers_calling_team_only(mock_request: MagicMock, _onboarding_side_effects) -> None:org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)- other_team = Team.objects.create(organization=org)+ Team.objects.create(organization=org)mock_request.return_value = Response({"status": "provisioning started", "org": str(org.id), "username": "root", "password": "secret"},status=202,@@ -361,13 +379,10 @@ def test_provision_enables_backfill_for_calling_team_only(mock_request: MagicMocmanaged_warehouse.provision(org.id, "my-warehouse", team.id, "prod_events")- # Provision records first-class duckling membership + backfill for the provisioning team only.- server = DuckgresServer.objects.get(organization_id=org.id)- 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()+ # The control plane creates the provisioning team's row from the provision request itself;+ # locally only that team gets its query connection and earliest-date sync kicked off.+ _onboarding_side_effects.ensure.assert_called_once_with(team_id=team.id, organization_id=org.id)+ _onboarding_side_effects.task.delay.assert_called_once_with(team.id)@pytest.mark.django_db@@ -403,7 +418,6 @@ 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 DuckgresServerTeam.objects.filter(team_id=team.id).exists()@pytest.mark.django_db@@ -626,9 +640,14 @@ def test_cp_bucket_for_returns_none_when_cp_has_no_bucket(mock_request: MagicMoc@pytest.mark.django_db@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")-def test_onboard_team_dual_writes_duckgres_and_django(mock_request: MagicMock, _mock_enabled: MagicMock) -> None:- org, team, server = _provisioned_org()- mock_request.return_value = Response({"team_id": team.id, "schema_name": "my_events"}, status=200)+def test_onboard_team_creates_duckgres_row_with_legacy_names(+ mock_request: MagicMock, _mock_enabled: MagicMock, _onboarding_side_effects+) -> None:+ org, team, _ = _provisioned_org()+ mock_request.side_effect = [+ Response({"teams": []}, status=200),+ Response({"team_id": team.id, "schema_name": "my_events"}, status=200),+ ]resp = managed_warehouse.onboard_team(org.id, team.id, "my_events")@@ -639,36 +658,37 @@ def test_onboard_team_dual_writes_duckgres_and_django(mock_request: MagicMock, _# duckling DAG actually writes today (posthog.events_<suffix> + posthog_data_imports_<suffix>).# A row without them grants the project reader only nonexistent derived schemas — the# empty-SQL-editor-sidebar bug the EU placeholder rows hit.- method, org_id, path = mock_request.call_args_list[0].args+ assert mock_request.call_args_list[0].args == ("GET", org.id, "/teams")+ method, org_id, path = mock_request.call_args_list[1].argsassert (method, org_id, path) == ("POST", org.id, "/teams")- json_body = mock_request.call_args_list[0].kwargs["json_body"]- assert json_body == {+ assert mock_request.call_args_list[1].kwargs["json_body"] == {"team_id": team.id,"schema_name": "my_events","events_table_name": "events_my_events","persons_table_name": "persons_my_events","schema_data_imports_name": "posthog_data_imports_my_events",}-- link = DuckgresServerTeam.objects.get(server=server, team_id=team.id)- assert link.backfill_enabled is True- assert link.table_suffix == "my_events"+ # Onboarding's tail: the query connection and the earliest-date sync.+ _onboarding_side_effects.ensure.assert_called_once_with(team_id=team.id, organization_id=org.id)+ _onboarding_side_effects.task.delay.assert_called_once_with(team.id)@pytest.mark.django_db@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")def test_onboard_team_surfaces_duckgres_schema_conflict(mock_request: MagicMock, _mock_enabled: MagicMock) -> None:- # duckgres owns cross-team schema uniqueness (it also knows grandfathered schemas Django- # doesn't) — its 409 must reach the caller as a clear conflict, with no Django row written.+ # duckgres owns cross-team schema uniqueness (it also knows grandfathered schemas) —+ # its 409 must reach the caller as a clear conflict.org, team, _ = _provisioned_org()- mock_request.return_value = Response({"error": "schema already in use"}, status=409)+ mock_request.side_effect = [+ Response({"teams": []}, status=200),+ Response({"error": "schema already in use"}, status=409),+ ]resp = managed_warehouse.onboard_team(org.id, team.id, "taken")assert resp.status_code == 409assert "taken" in resp.data["error"]- assert not DuckgresServerTeam.objects.filter(team_id=team.id).exists()@pytest.mark.django_db@@ -684,26 +704,6 @@ def test_onboard_team_rejects_invalid_name_before_control_plane(assert resp.status_code == 400, bad_namemock_request.assert_not_called()- assert not DuckgresServerTeam.objects.filter(team_id=team.id).exists()---@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)-@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")-def test_onboard_team_rejects_duplicate_suffix_before_control_plane(- mock_request: MagicMock, _mock_enabled: MagicMock-) -> None:- # The Django guard must run before the duckgres upsert: the upsert overwrites an existing- # row's schema, so a rejected name must never reach the control plane.- org, team_a, server = _provisioned_org()- team_b = Team.objects.create(organization=org, name="Env B")- DuckgresServerTeam.objects.create(server=server, team=team_a, table_suffix="shared")-- resp = managed_warehouse.onboard_team(org.id, team_b.id, "shared")-- assert resp.status_code == 400- mock_request.assert_not_called()- assert not DuckgresServerTeam.objects.filter(team_id=team_b.id).exists()@pytest.mark.django_db@@ -728,57 +728,98 @@ def test_onboard_team_gated_on_feature_flag(mock_enabled: MagicMock) -> None:resp = managed_warehouse.onboard_team(org.id, team.id, "events")assert resp.status_code == 403- 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)@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")-def test_onboard_team_same_name_is_idempotent(mock_request: MagicMock, _mock_enabled: MagicMock) -> None:+def test_onboard_team_same_name_is_idempotent(+ mock_request: MagicMock, _mock_enabled: MagicMock, _onboarding_side_effects+) -> None:+ # The CP POST is an upsert, so an already-onboarded team must not re-POST (a hand-set+ # row's overrides would be clobbered) — but re-onboarding with the current name still+ # succeeds and re-runs the best-effort tail.org, team, _ = _provisioned_org()- mock_request.return_value = Response({"team_id": team.id, "schema_name": "first"}, status=200)+ mock_request.return_value = Response({"teams": [{"team_id": team.id, "schema_name": "first"}]}, status=200)- managed_warehouse.onboard_team(org.id, team.id, "first")resp = managed_warehouse.onboard_team(org.id, team.id, "first")assert resp.status_code == 200- assert DuckgresServerTeam.objects.filter(team_id=team.id).count() == 1- assert DuckgresServerTeam.objects.get(team_id=team.id).table_suffix == "first"+ assert resp.data == {"onboarded": True, "schema_name": "first"}+ assert [c.args[0] for c in mock_request.call_args_list] == ["GET"]+ _onboarding_side_effects.ensure.assert_called_once_with(team_id=team.id, organization_id=org.id)@pytest.mark.django_db@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")-def test_onboard_team_refuses_to_change_an_existing_suffix(mock_request: MagicMock, _mock_enabled: MagicMock) -> None:+def test_onboard_team_refuses_to_change_an_existing_schema(mock_request: MagicMock, _mock_enabled: MagicMock) -> None:+ # Changing a set schema would split the team's data across two tables — rejected before+ # the upsert, so the duckgres row keeps its schema.org, team, _ = _provisioned_org()- mock_request.return_value = Response({"team_id": team.id, "schema_name": "first"}, status=200)- managed_warehouse.onboard_team(org.id, team.id, "first")- mock_request.reset_mock()+ mock_request.return_value = Response(+ {"teams": [{"team_id": team.id, "schema_name": "first", "events_table_name": "events_first"}]}, status=200+ )resp = managed_warehouse.onboard_team(org.id, team.id, "second")- # Changing a set suffix would split the team's data across two tables — rejected before- # the control plane, so the duckgres row keeps its schema too.assert resp.status_code == 400- mock_request.assert_not_called()- assert DuckgresServerTeam.objects.get(team_id=team.id).table_suffix == "first"+ assert "events_first" in resp.data["error"]+ assert [c.args[0] for c in mock_request.call_args_list] == ["GET"]@pytest.mark.django_db@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")-def test_onboard_team_refuses_to_set_a_suffix_on_a_legacy_shared_team(- mock_request: MagicMock, _mock_enabled: MagicMock-) -> None:- org, team, server = _provisioned_org()- # A legacy team already backfilling to the shared tables (NULL suffix), e.g. backfilled by migration.- DuckgresServerTeam.objects.create(server=server, team=team, backfill_enabled=True, table_suffix=None)+def test_onboard_team_refuses_to_rename_a_legacy_shared_team(mock_request: MagicMock, _mock_enabled: MagicMock) -> None:+ org, team, _ = _provisioned_org()+ # A legacy team pinned to the shared tables (grandfathered row).+ mock_request.return_value = Response(+ {"teams": [{"team_id": team.id, "schema_name": f"team_{team.id}", "events_table_name": "events"}]},+ status=200,+ )resp = managed_warehouse.onboard_team(org.id, team.id, "new_name")assert resp.status_code == 400- mock_request.assert_not_called()- assert DuckgresServerTeam.objects.get(team_id=team.id).table_suffix is None+ assert "shared tables" in resp.data["error"]+ assert [c.args[0] for c in mock_request.call_args_list] == ["GET"]+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")+def test_onboard_team_fails_retryably_when_control_plane_unreachable(+ mock_request: MagicMock, _mock_enabled: MagicMock+) -> None:+ # The write-once guard needs the CP row list; without it the upsert could silently move+ # an existing schema, so the onboard fails with a retry error instead.+ org, team, _ = _provisioned_org()+ mock_request.return_value = Response({"error": "unreachable"}, status=502)++ resp = managed_warehouse.onboard_team(org.id, team.id, "my_events")++ assert resp.status_code == 502+ assert "try again" in resp.data["error"].lower()+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")+def test_onboard_team_survives_direct_source_failure(+ mock_request: MagicMock, _mock_enabled: MagicMock, _onboarding_side_effects+) -> None:+ # The query connection is a best-effort convenience; a failure must never fail onboarding.+ org, team, _ = _provisioned_org()+ mock_request.side_effect = [+ Response({"teams": []}, status=200),+ Response({"team_id": team.id, "schema_name": "my_events"}, status=200),+ ]+ _onboarding_side_effects.ensure.side_effect = Exception("boom")++ resp = managed_warehouse.onboard_team(org.id, team.id, "my_events")++ assert resp.status_code == 200@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)@@ -864,181 +905,42 @@ def test_delete_team_hits_org_team_route(mock_internal: MagicMock, _mock_enabledassert url == f"http://duckgres.invalid/api/v1/orgs/{org_id}/teams/42"-@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.create_team")@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams")-def test_team_onboarding_state_for_duckgres_team(mock_list: MagicMock, mock_create: MagicMock) -> None:- # Branch b: the duckgres row exists — onboarded, no grandfather push.- org, team, server = _provisioned_org()- DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="mine")- mock_list.return_value = Response([{"team_id": team.id, "schema_name": "mine"}], status=200)+def test_team_onboarding_state_for_duckgres_team(mock_list: MagicMock) -> None:+ mock_list.return_value = Response([{"team_id": 42, "schema_name": "mine"}], status=200)- state = managed_warehouse.team_onboarding_state(org.id, team.id)+ state = managed_warehouse.team_onboarding_state(uuid4(), 42)assert state == {"team_onboarded": True, "schema_name": "mine"}- mock_create.assert_not_called()-@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.create_team")@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams")-def test_team_onboarding_state_for_unonboarded_team(mock_list: MagicMock, mock_create: MagicMock) -> None:- # Branch c: warehouse exists but this team has no row anywhere — the onboarding screen case.- org, team, _ = _provisioned_org()- mock_list.return_value = Response([{"team_id": team.id + 1, "schema_name": "other"}], status=200)+def test_team_onboarding_state_for_unonboarded_team(mock_list: MagicMock) -> None:+ # Warehouse exists but this team has no row — the onboarding screen case.+ mock_list.return_value = Response([{"team_id": 43, "schema_name": "other"}], status=200)- state = managed_warehouse.team_onboarding_state(org.id, team.id)+ state = managed_warehouse.team_onboarding_state(uuid4(), 42)assert state == {"team_onboarded": False, "schema_name": None}- mock_create.assert_not_called()@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams")-def test_team_onboarding_state_heals_missing_django_row(mock_list: MagicMock) -> None:- # Reverse heal: a dual-write that lost its Django half (provision registered the team with- # duckgres but enable_team_backfill failed) is repaired on the next status read, so Dagster- # picks the team up instead of it reporting onboarded forever with no backfill.- org, team, _ = _provisioned_org()- mock_list.return_value = Response([{"team_id": team.id, "schema_name": "healed_env"}], status=200)-- state = managed_warehouse.team_onboarding_state(org.id, team.id)-- assert state == {"team_onboarded": True, "schema_name": "healed_env"}- row = DuckgresServerTeam.objects.get(team=team)- assert row.table_suffix == "healed_env"---@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams")-def test_team_onboarding_state_refuses_to_heal_legacy_named_row(mock_list: MagicMock) -> None:- # A duckgres row with explicit legacy table names came from the grandfather push (which only- # runs off an existing Django row) — a missing Django row there is unexpected, so the heal- # must not guess a suffix that would rename the team's tables.- org, team, _ = _provisioned_org()- mock_list.return_value = Response(- [{"team_id": team.id, "schema_name": "team_x", "events_table_name": "events"}], status=200- )-- state = managed_warehouse.team_onboarding_state(org.id, team.id)-- assert state == {"team_onboarded": True, "schema_name": "team_x"}- assert not DuckgresServerTeam.objects.filter(team=team).exists()---@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams")-def test_team_onboarding_state_survives_failed_heal(mock_list: MagicMock) -> None:- # A heal that loses to a suffix collision is logged, never failing the status read.- org, team, server = _provisioned_org()- other_team = Team.objects.create(organization=org, name="other")- DuckgresServerTeam.objects.create(server=server, team=other_team, table_suffix="taken_env")- mock_list.return_value = Response([{"team_id": team.id, "schema_name": "taken_env"}], status=200)-- state = managed_warehouse.team_onboarding_state(org.id, team.id)-- assert state == {"team_onboarded": True, "schema_name": "taken_env"}- assert not DuckgresServerTeam.objects.filter(team=team).exists()--- [- # suffix set: schema is the suffix, explicit suffixed legacy names- (- "with_suffix",- "prod_env",- {- "schema_name": "prod_env",- "events_table_name": "events_prod_env",- "persons_table_name": "persons_prod_env",- "schema_data_imports_name": "posthog_data_imports_prod_env",- },- ),- # NULL suffix: legacy shared tables and the team-id data-imports schema- (- "without_suffix",- None,- {- "schema_name": None, # filled per-team below- "events_table_name": "events",- "persons_table_name": "persons",- "schema_data_imports_name": None, # filled per-team below- },- ),- ]-)-@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams")-@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.internal_requests")-@override_settings(DUCKGRES_API_URL="http://duckgres.invalid", DUCKGRES_INTERNAL_SECRET="s")-def test_team_onboarding_state_lazily_grandfathers_django_only_team(- _name: str,- table_suffix: str | None,- expected: dict,- mock_internal: MagicMock,- mock_list: MagicMock,-) -> None:- # A team onboarded before the control plane tracked teams (Django row only) is pushed to- # duckgres during the status read, pinning its explicit legacy table names.- org, team, server = _provisioned_org()- DuckgresServerTeam.objects.create(server=server, team=team, table_suffix=table_suffix)- mock_list.return_value = Response([], status=200)- mock_internal.request.return_value = MagicMock(status_code=200, **{"json.return_value": {}})-- expected = {- **expected,- "schema_name": expected["schema_name"] or f"team_{team.id}",- "schema_data_imports_name": expected["schema_data_imports_name"] or f"posthog_data_imports_team_{team.id}",- }-- state = managed_warehouse.team_onboarding_state(org.id, team.id)-- assert state == {"team_onboarded": True, "schema_name": expected["schema_name"]}- assert mock_internal.request.call_args.kwargs["json"] == {"team_id": team.id, **expected}---@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.create_team")-@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams")-def test_team_onboarding_state_survives_control_plane_failure(mock_list: MagicMock, mock_create: MagicMock) -> None:- # The status read must never fail on the control plane: a Django-onboarded team still- # reports as onboarded (with its would-be schema) when list-teams errors.- org, team, server = _provisioned_org()- DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="mine")+def test_team_onboarding_state_degrades_when_control_plane_unreachable(mock_list: MagicMock) -> None:+ # The status read must never fail on the control plane: an unreachable CP degrades to+ # the not-onboarded shape.mock_list.return_value = Response({"error": "unreachable"}, status=502)- state = managed_warehouse.team_onboarding_state(org.id, team.id)-- assert state == {"team_onboarded": True, "schema_name": "mine"}- mock_create.assert_not_called()---@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.create_team")-@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams")-def test_team_onboarding_state_survives_failed_grandfather_push(mock_list: MagicMock, mock_create: MagicMock) -> None:- # A failed push is logged and retried on the next status read; the team still reports- # onboarded from its Django row.- org, team, server = _provisioned_org()- DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="mine")- mock_list.return_value = Response([], status=200)- mock_create.return_value = Response({"error": "boom"}, status=500)-- state = managed_warehouse.team_onboarding_state(org.id, team.id)+ state = managed_warehouse.team_onboarding_state(uuid4(), 42)- assert state == {"team_onboarded": True, "schema_name": "mine"}+ assert state == {"team_onboarded": False, "schema_name": None}@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams")def test_check_schema_name_availability(mock_list: MagicMock) -> None:- # Taken by a duckgres row, taken by a Django-only (not yet grandfathered) suffix, or free.- org, team, server = _provisioned_org()- DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="django_only")mock_list.return_value = Response([{"team_id": 999, "schema_name": "in_duckgres"}], status=200)- for name, available in (("in_duckgres", False), ("django_only", False), ("fresh_name", True)):- resp = managed_warehouse.check_schema_name(org.id, name)+ for name, available in (("in_duckgres", False), ("fresh_name", True)):+ resp = managed_warehouse.check_schema_name(uuid4(), name)assert resp.status_code == 200, nameassert resp.data == {"name": name, "available": available}@@ -1073,8 +975,7 @@ def test_block_team_deletion_skips_orgs_without_warehouse(mock_delete: MagicMockdef test_block_team_deletion_proceeds_when_duckgres_row_gone(_name: str, cp_status: int, expected: None, mock_delete: MagicMock) -> None:- org, team, server = _provisioned_org()- DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="mine")+ org, team, _ = _provisioned_org()mock_delete.return_value = Response({}, status=cp_status)assert managed_warehouse.block_team_deletion(team.id, org.id) is expected@@ -1086,8 +987,7 @@ def test_block_team_deletion_proceeds_when_duckgres_row_gone(def test_block_team_deletion_blocks_last_warehouse_team(mock_delete: MagicMock) -> None:# duckgres 409s on the org's last team: the Django deletion must be blocked with guidance# to deprovision the warehouse (or delete the organization) instead.- org, team, server = _provisioned_org()- DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="mine")+ org, team, _ = _provisioned_org()mock_delete.return_value = Response({"error": "last team"}, status=409)reason = managed_warehouse.block_team_deletion(team.id, org.id)@@ -1096,15 +996,26 @@ def test_block_team_deletion_blocks_last_warehouse_team(mock_delete: MagicMock)assert "deprovision" in reason.lower()+ [+ # CP row lists the team → onboarded, block with a retry error.+ ("onboarded", "row"),+ # CP row list unreachable → fail closed: a possibly-onboarded team must not be+ # silently orphaned in duckgres.+ ("membership_unknown", None),+ ]+)@pytest.mark.django_db@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.delete_team")-def test_block_team_deletion_blocks_onboarded_team_when_control_plane_unreachable(mock_delete: MagicMock) -> None:- # An onboarded team must not be silently orphaned in duckgres — block with a retry error.- org, team, server = _provisioned_org()- DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="mine")+def test_block_team_deletion_blocks_when_delete_fails_and_membership_possible(+ _name: str, cp_rows_kind: str | None, mock_delete: MagicMock+) -> None:+ org, team, _ = _provisioned_org()mock_delete.return_value = Response({"error": "unreachable"}, status=502)+ rows = [{"org_id": str(org.id), "team_id": team.id, "schema_name": "mine"}] if cp_rows_kind else None- reason = managed_warehouse.block_team_deletion(team.id, org.id)+ with patch("posthog.ducklake.cp_teams._fetch_org_rows", return_value=rows):+ reason = managed_warehouse.block_team_deletion(team.id, org.id)assert reason is not Noneassert "try again" in reason.lower()@@ -1113,12 +1024,13 @@ def test_block_team_deletion_blocks_onboarded_team_when_control_plane_unreachabl@pytest.mark.django_db@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.delete_team")def test_block_team_deletion_lets_unonboarded_team_through_on_control_plane_error(mock_delete: MagicMock) -> None:- # The org has a warehouse but this team is not onboarded Django-side: a control-plane+ # The org has a warehouse but this team has no membership row: a control-plane# outage must not brick its deletion.org, team, _ = _provisioned_org()mock_delete.return_value = Response({"error": "unreachable"}, status=502)- assert managed_warehouse.block_team_deletion(team.id, org.id) is None+ with patch("posthog.ducklake.cp_teams._fetch_org_rows", return_value=[]):+ assert managed_warehouse.block_team_deletion(team.id, org.id) is None@pytest.mark.django_db@@ -1222,48 +1134,3 @@ def test_update_team_puts_only_passed_fields_to_org_team_route(mock_internal: Maassert method == "PUT"assert url == f"http://duckgres.invalid/api/v1/orgs/{org_id}/teams/42"assert mock_internal.request.call_args.kwargs["json"] == {"earliest_event_date": "2020-06-15"}---@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")-@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)-@patch("products.data_warehouse.backend.facade.tasks.sync_team_earliest_event_date")-def test_onboard_team_schedules_earliest_event_date_sync_after_commit(- mock_task: MagicMock,- _mock_enabled: MagicMock,- mock_request: MagicMock,- django_capture_on_commit_callbacks,-) -> None:- # The resolve task must only fire once the DuckgresServerTeam row is committed,- # or it could run against a rolled-back membership row.- org, team, _ = _provisioned_org()- mock_request.return_value = Response({"team_id": team.id, "schema_name": "my_events"}, status=200)-- with django_capture_on_commit_callbacks(execute=True) as callbacks:- resp = managed_warehouse.onboard_team(org.id, team.id, "my_events")-- assert resp.status_code == 200- assert len(callbacks) == 1- mock_task.delay.assert_called_once_with(team.id)---@override_settings(CLOUD_DEPLOYMENT="US", DUCKGRES_PG_PORT=5432)-@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")-@patch("products.data_warehouse.backend.facade.tasks.sync_team_earliest_event_date")-def test_provision_schedules_earliest_event_date_sync_after_commit(- mock_task: MagicMock,- mock_request: MagicMock,- django_capture_on_commit_callbacks,-) -> None:- org = Organization.objects.create(name="Org")- team = Team.objects.create(organization=org)- mock_request.return_value = Response(- {"status": "provisioning started", "org": str(org.id), "username": "root", "password": "secret"},- status=202,- )-- with django_capture_on_commit_callbacks(execute=True):- managed_warehouse.provision(org.id, "my-warehouse", team.id, "prod_events")-- mock_task.delay.assert_called_once_with(team.id)diff --git a/products/data_warehouse/backend/tests/test_managed_warehouse_connection.py b/products/data_warehouse/backend/tests/test_managed_warehouse_connection.pyindex b51e825f2e84..8f76af39a135 100644--- a/products/data_warehouse/backend/tests/test_managed_warehouse_connection.py+++ b/products/data_warehouse/backend/tests/test_managed_warehouse_connection.py@@ -7,7 +7,8 @@ from posthog.hogql.direct_connection import get_direct_connection_sourcefrom posthog.hogql.errors import QueryErrorfrom posthog.hogql.query import HogQLQueryExecutor-from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam+from posthog.ducklake import cp_teams+from posthog.ducklake.models import DuckgresServerfrom posthog.models import Organization, Teamfrom products.data_warehouse.backend.direct_postgres import DIRECT_POSTGRES_URL_PATTERN@@ -68,6 +69,46 @@ def _mock_project_reader_credentials():yield mocked+# Per-test control-plane membership rows, keyed by org id. The CP is the read source for+# membership now, so tests register rows here instead of creating Django rows.+_MEMBERSHIPS: dict[str, list[dict]] = {}+++def _add_membership(+ team: Team, schema_name: str = "prod", *, legacy_shared: bool = False, backfill_enabled: bool = True+) -> None:+ org_id = str(team.organization_id)+ row = {+ "org_id": org_id,+ "team_id": team.id,+ "schema_name": f"team_{team.id}" if legacy_shared else schema_name,+ "enabled": True,+ "backfill_enabled": backfill_enabled,+ "events_table_name": "events" if legacy_shared else f"events_{schema_name}",+ "persons_table_name": "persons" if legacy_shared else f"persons_{schema_name}",+ "schema_data_imports_name": None,+ "earliest_event_date": None,+ }+ _MEMBERSHIPS.setdefault(org_id, []).append(row)+ cp_teams.clear_cache()+++def _clear_memberships() -> None:+ _MEMBERSHIPS.clear()+ cp_teams.clear_cache()++[email protected](autouse=True)+def _cp_memberships():+ _clear_memberships()+ with patch(+ "posthog.ducklake.cp_teams._fetch_org_rows",+ side_effect=lambda org_id: list(_MEMBERSHIPS.get(str(org_id), [])),+ ):+ yield+ _clear_memberships()++def _ensure(team: Team) -> ExternalDataSource:return ensure_managed_warehouse_direct_source(team_id=team.id, organization_id=team.organization_id)@@ -77,7 +118,7 @@ class TestEnsureManagedWarehouseDirectSource:def test_creates_a_restricted_postgres_query_source_from_the_server(self) -> None:org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)- server = DuckgresServer.objects.create(+ DuckgresServer.objects.create(organization=org,host=_CONNECTION["host"],port=_CONNECTION["port"],@@ -85,7 +126,7 @@ class TestEnsureManagedWarehouseDirectSource:username=_CONNECTION["username"],password=_CONNECTION["password"],)- DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="prod")+ _add_membership(team)source = _ensure(team)@@ -105,7 +146,7 @@ class TestEnsureManagedWarehouseDirectSource:# Without dedup, every status poll / re-enable would spawn a duplicate connection.org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)- server = DuckgresServer.objects.create(+ DuckgresServer.objects.create(organization=org,host=_CONNECTION["host"],port=_CONNECTION["port"],@@ -113,7 +154,7 @@ class TestEnsureManagedWarehouseDirectSource:username=_CONNECTION["username"],password=_CONNECTION["password"],)- DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="prod")+ _add_membership(team)first = _ensure(team)second = _ensure(team)@@ -124,7 +165,7 @@ class TestEnsureManagedWarehouseDirectSource:def test_concurrent_reader_setup_reuses_the_persisted_credential(self) -> None:org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)- server = DuckgresServer.objects.create(+ DuckgresServer.objects.create(organization=org,host=_CONNECTION["host"],port=_CONNECTION["port"],@@ -132,7 +173,7 @@ class TestEnsureManagedWarehouseDirectSource:username=_CONNECTION["username"],password=_CONNECTION["password"],)- DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="prod")+ _add_membership(team)requested_passwords: list[str] = []def configure_project_reader(*, team_id: int, password: str, **_kwargs: object) -> dict[str, str]:@@ -154,7 +195,7 @@ class TestEnsureManagedWarehouseDirectSource:def test_does_not_expose_legacy_shared_tables(self) -> None:org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)- server = DuckgresServer.objects.create(+ DuckgresServer.objects.create(organization=org,host=_CONNECTION["host"],port=_CONNECTION["port"],@@ -162,7 +203,7 @@ class TestEnsureManagedWarehouseDirectSource:username=_CONNECTION["username"],password=_CONNECTION["password"],)- DuckgresServerTeam.objects.create(server=server, team=team, table_suffix=None)+ _add_membership(team, legacy_shared=True)with pytest.raises(ValueError, match="shared managed warehouse tables"):_ensure(team)@@ -172,7 +213,7 @@ class TestEnsureManagedWarehouseDirectSource:def test_does_not_promote_a_user_source_with_the_reserved_prefix(self) -> None:org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)- server = DuckgresServer.objects.create(+ DuckgresServer.objects.create(organization=org,host=_CONNECTION["host"],port=_CONNECTION["port"],@@ -180,7 +221,7 @@ class TestEnsureManagedWarehouseDirectSource:username=_CONNECTION["username"],password=_CONNECTION["password"],)- DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="prod")+ _add_membership(team)user_source = ExternalDataSource.objects.create(team=team,source_id="user-source",@@ -213,7 +254,7 @@ class TestEnsureManagedWarehouseDirectSource:def test_removes_existing_schemas_when_upgrading_a_root_managed_source(self) -> None:org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)- server = DuckgresServer.objects.create(+ DuckgresServer.objects.create(organization=org,host=_CONNECTION["host"],port=_CONNECTION["port"],@@ -221,7 +262,7 @@ class TestEnsureManagedWarehouseDirectSource:username=_CONNECTION["username"],password=_CONNECTION["password"],)- DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="prod")+ _add_membership(team)source = ExternalDataSource.objects.create(team=team,source_id="managed-source",@@ -264,7 +305,7 @@ class TestReconcileManagedWarehouseTables:def _setup(self) -> tuple[Organization, Team]:org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)- server = DuckgresServer.objects.create(+ DuckgresServer.objects.create(organization=org,host=_CONNECTION["host"],port=_CONNECTION["port"],@@ -272,7 +313,7 @@ class TestReconcileManagedWarehouseTables:username=_CONNECTION["username"],password=_CONNECTION["password"],)- DuckgresServerTeam.objects.create(server=server, team=team, backfill_enabled=True, table_suffix="prod")+ _add_membership(team)return org, teamdef test_discovers_only_the_teams_tables_and_makes_them_queryable(self) -> None:@@ -455,13 +496,31 @@ class TestReconcileManagedWarehouseTables:def test_periodic_sweep_schedules_every_managed_project(self) -> None:org, team = self._setup()+ all_rows = _MEMBERSHIPS[str(org.id)] + [+ # Legacy shared-table membership: nothing to expose, must be skipped.+ {"org_id": str(org.id), "team_id": team.id + 1, "schema_name": "team_x", "events_table_name": "events"}+ ]- with patch(- "products.data_warehouse.backend.tasks.tasks.schedule_managed_warehouse_tables_reconcile"- ) as schedule:+ with (+ patch("posthog.ducklake.cp_teams._fetch_all_rows", return_value=all_rows),+ patch(+ "products.data_warehouse.backend.tasks.tasks.schedule_managed_warehouse_tables_reconcile"+ ) as schedule,+ ):reconcile_all_managed_warehouse_tables_task()- schedule.assert_called_once_with(team_id=team.id, organization_id=org.id)+ schedule.assert_called_once_with(team_id=team.id, organization_id=str(org.id))++ def test_periodic_sweep_skips_run_when_control_plane_unreachable(self) -> None:+ with (+ patch("posthog.ducklake.cp_teams._fetch_all_rows", return_value=None),+ patch(+ "products.data_warehouse.backend.tasks.tasks.schedule_managed_warehouse_tables_reconcile"+ ) as schedule,+ ):+ reconcile_all_managed_warehouse_tables_task()++ schedule.assert_not_called()def test_does_nothing_for_a_team_that_has_not_joined_the_warehouse(self) -> None:# A non-member team polling status while the warehouse is ready must not get a connection.@@ -478,7 +537,7 @@ class TestReconcileManagedWarehouseTables:def test_does_not_reconcile_legacy_shared_tables(self) -> None:org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)- server = DuckgresServer.objects.create(+ DuckgresServer.objects.create(organization=org,host=_CONNECTION["host"],port=_CONNECTION["port"],@@ -486,7 +545,7 @@ class TestReconcileManagedWarehouseTables:username=_CONNECTION["username"],password=_CONNECTION["password"],)- DuckgresServerTeam.objects.create(server=server, team=team, table_suffix=None)+ _add_membership(team, legacy_shared=True)with patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas"@@ -508,7 +567,7 @@ class TestReconcileManagedWarehouseTables:username="root",password="org-a-password",)- server_b = DuckgresServer.objects.create(+ DuckgresServer.objects.create(organization=org_b,host="b.example.com",port=5432,@@ -516,7 +575,7 @@ class TestReconcileManagedWarehouseTables:username="root",password="org-b-password",)- DuckgresServerTeam.objects.create(server=server_b, team=team_b, table_suffix="b")+ _add_membership(team_b, "b")with patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas"@@ -541,7 +600,7 @@ class TestManagedWarehouseLifecycle:username=_CONNECTION["username"],password=_CONNECTION["password"],)- DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="prod")+ _add_membership(team)source = ensure_managed_warehouse_direct_source(team_id=team.id, organization_id=org.id)return org, team, source, server@@ -568,12 +627,13 @@ class TestManagedWarehouseLifecycle:)soft_delete_managed_warehouse_sources(organization_id=org.id)+ # Deprovision removes the org's team rows from the control plane.+ _clear_memberships()source.refresh_from_db()table.refresh_from_db()assert source.deleted is Trueassert table.deleted is True- assert DuckgresServerTeam.objects.get(team=team).backfill_enabled is Falsewith patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas"@@ -590,7 +650,7 @@ class TestManagedWarehouseLifecycle:def test_soft_delete_is_atomic_across_all_organization_sources(self) -> None:org = Organization.objects.create(name="Org")- server = DuckgresServer.objects.create(+ DuckgresServer.objects.create(organization=org,host=_CONNECTION["host"],port=_CONNECTION["port"],@@ -600,8 +660,8 @@ class TestManagedWarehouseLifecycle:)team_a = Team.objects.create(organization=org)team_b = Team.objects.create(organization=org)- DuckgresServerTeam.objects.create(server=server, team=team_a, table_suffix="a")- DuckgresServerTeam.objects.create(server=server, team=team_b, table_suffix="b")+ _add_membership(team_a, "a")+ _add_membership(team_b, "b")source_a = _ensure(team_a)source_b = _ensure(team_b)original_save = ExternalDataSource.savediff --git a/products/data_warehouse/backend/tests/test_managed_warehouse_data_status.py b/products/data_warehouse/backend/tests/test_managed_warehouse_data_status.pyindex ef7098fcbbd9..0952ab0713e2 100644--- a/products/data_warehouse/backend/tests/test_managed_warehouse_data_status.py+++ b/products/data_warehouse/backend/tests/test_managed_warehouse_data_status.py@@ -7,7 +7,8 @@ from django.test import SimpleTestCase, TestCasefrom parameterized import parameterized-from posthog.ducklake.models import DuckgresServerTeam, DuckgresSinkSchemaState+from posthog.ducklake.cp_teams import CPTeam+from posthog.ducklake.models import DuckgresSinkSchemaStatefrom posthog.models import Organization, Teamfrom products.data_warehouse.backend.logic.managed_warehouse_data_status import (@@ -96,8 +97,18 @@ class TestDatasetStatus(SimpleTestCase):updated_at=datetime(2026, 7, 12, tzinfo=UTC),)- def _backfill(self, earliest_event_date: date | None = date(2026, 3, 14)) -> DuckgresServerTeam:- return DuckgresServerTeam(team_id=1, backfill_enabled=True, earliest_event_date=earliest_event_date)+ def _backfill(self, earliest_event_date: date | None = date(2026, 3, 14)) -> CPTeam:+ return CPTeam(+ team_id=1,+ organization_id="org-a",+ schema_name="prod",+ enabled=True,+ backfill_enabled=True,+ events_table_name=None,+ persons_table_name=None,+ schema_data_imports_name=None,+ earliest_event_date=earliest_event_date,+ )def test_daily_partitions_do_not_count_toward_historical_progress(self) -> None:# Daily runs land constantly once a team is live. Counting them as historical progress woulddiff --git a/products/data_warehouse/backend/tests/test_tasks.py b/products/data_warehouse/backend/tests/test_tasks.pyindex 9fb9ee7ca574..adc50018d77c 100644--- a/products/data_warehouse/backend/tests/test_tasks.py+++ b/products/data_warehouse/backend/tests/test_tasks.py@@ -6,22 +6,42 @@ from unittest.mock import MagicMock, patchfrom parameterized import parameterizedfrom rest_framework.response import Response-from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam+from posthog.ducklake import cp_teamsfrom posthog.models import Organization, Teamfrom products.data_warehouse.backend.tasks.tasks import sync_team_earliest_event_date-def _onboarded_team(earliest: date | None = None) -> tuple[Organization, Team]:[email protected](autouse=True)+def _reset_cp_cache():+ cp_teams.clear_cache()+ yield+ cp_teams.clear_cache()+++def _team() -> tuple[Organization, 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="env", earliest_event_date=earliest)return org, team+def _cp_rows(org: Organization, team: Team, earliest: date | None = None) -> list[dict]:+ return [+ {+ "org_id": str(org.id),+ "team_id": team.id,+ "schema_name": "env",+ "enabled": True,+ "backfill_enabled": True,+ "earliest_event_date": earliest.isoformat() if earliest else None,+ }+ ]+++def _patch_org_rows(rows):+ return patch("posthog.ducklake.cp_teams._fetch_org_rows", return_value=rows)++@parameterized.expand([("pre_2015_clamped", datetime(2010, 3, 1), date(2015, 1, 1)),@@ -31,25 +51,24 @@ def _onboarded_team(earliest: date | None = None) -> tuple[Organization, Team]:@pytest.mark.django_db@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.update_team")@patch("posthog.ducklake.common.get_earliest_event_date_for_team")-def test_sync_task_resolves_and_dual_writes(+def test_sync_task_resolves_and_pushes_to_control_plane(_name: str,earliest_dt: datetime | None,expected: date,mock_get_earliest: MagicMock,mock_update: MagicMock,) -> None:- # The provisioning-time task must apply the same clamp the backfill sensor uses, and- # write the result to BOTH the Django row (the sensor's read source) and the duckgres- # control-plane team row.- org, team = _onboarded_team()+ # The provisioning-time task must apply the same clamp the backfill sensor uses and+ # persist the result on the team's duckgres control-plane row (the sensor's read source).+ org, team = _team()mock_get_earliest.return_value = earliest_dtmock_update.return_value = Response({}, status=200)- sync_team_earliest_event_date(team.id)+ with _patch_org_rows(_cp_rows(org, team)):+ sync_team_earliest_event_date(team.id)- assert DuckgresServerTeam.objects.get(team=team).earliest_event_date == expectedmock_update.assert_called_once_with(- org.id, team.id, require_enabled=False, earliest_event_date=expected.isoformat()+ str(org.id), team.id, require_enabled=False, earliest_event_date=expected.isoformat())@@ -59,14 +78,14 @@ def test_sync_task_resolves_and_dual_writes(def test_sync_task_leaves_empty_team_unresolved(mock_get_earliest: MagicMock, mock_update: MagicMock) -> None:# A just-provisioned project plausibly has no events YET. A cached date is final, so# storing the no-history sentinel here would permanently exclude the team from- # historical backfill; the task must leave the row NULL for the sensor to resolve- # later, and push nothing to the control plane.- _, team = _onboarded_team()+ # historical backfill; the task must store nothing and leave the sensor to resolve+ # it later.+ org, team = _team()mock_get_earliest.return_value = None- sync_team_earliest_event_date(team.id)+ with _patch_org_rows(_cp_rows(org, team)):+ sync_team_earliest_event_date(team.id)- assert DuckgresServerTeam.objects.get(team=team).earliest_event_date is Nonemock_update.assert_not_called()@@ -76,44 +95,36 @@ def test_sync_task_leaves_empty_team_unresolved(mock_get_earliest: MagicMock, modef test_sync_task_skips_clickhouse_when_date_already_cached(mock_get_earliest: MagicMock, mock_update: MagicMock) -> None:- # Idempotent re-runs (dispatch retries, re-onboards) must not re-query ClickHouse,- # but still converge the control-plane row from the cached value.- org, team = _onboarded_team(earliest=date(2019, 5, 1))- mock_update.return_value = Response({}, status=200)+ # Idempotent re-runs (dispatch retries, re-onboards) must not re-query ClickHouse or+ # re-push a date the control plane already holds.+ org, team = _team()- sync_team_earliest_event_date(team.id)+ with _patch_org_rows(_cp_rows(org, team, earliest=date(2019, 5, 1))):+ sync_team_earliest_event_date(team.id)mock_get_earliest.assert_not_called()- mock_update.assert_called_once_with(org.id, team.id, require_enabled=False, earliest_event_date="2019-05-01")+ mock_update.assert_not_called()+ [+ # A dispatch can race a deleted membership row — skip quietly for a de-onboarded team.+ ("no_cp_row", []),+ # An unreachable control plane must not raise or query ClickHouse: the sensor+ # resolves the date lazily once the CP is back.+ ("cp_unreachable", None),+ ]+)@pytest.mark.django_db@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.update_team")@patch("posthog.ducklake.common.get_earliest_event_date_for_team")-def test_sync_task_control_plane_failure_keeps_django_write(- mock_get_earliest: MagicMock, mock_update: MagicMock+def test_sync_task_is_a_noop_without_a_readable_row(+ _name: str, rows, mock_get_earliest: MagicMock, mock_update: MagicMock) -> None:- # Best-effort CP side: a control-plane error must neither raise nor lose the Django- # write — the sensor keeps reading the Django row either way.- _, team = _onboarded_team()- mock_get_earliest.return_value = datetime(2020, 6, 15)- mock_update.return_value = Response({"error": "boom"}, status=502)-- sync_team_earliest_event_date(team.id)-- assert DuckgresServerTeam.objects.get(team=team).earliest_event_date == date(2020, 6, 15)---@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.update_team")-@patch("posthog.ducklake.common.get_earliest_event_date_for_team")-def test_sync_task_without_membership_row_is_a_noop(mock_get_earliest: MagicMock, mock_update: MagicMock) -> None:- # A dispatch can race a deleted membership row — the task must skip quietly instead- # of querying ClickHouse or pushing to the control plane for a de-onboarded team.- org = Organization.objects.create(name="Org")- team = Team.objects.create(organization=org)+ org, team = _team()- sync_team_earliest_event_date(team.id)+ with _patch_org_rows(rows):+ sync_team_earliest_event_date(team.id)mock_get_earliest.assert_not_called()mock_update.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/enablement.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/enablement.pyindex a24ed02c40ea..ddec8f161f37 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/enablement.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/enablement.py@@ -1,7 +1,7 @@"""Which teams the Duckgres batch sink is enabled for.-The sink must only claim batches for teams that (a) have a DuckgresServerTeam-membership and (b) have the rollout feature flag on. The membership is created+The sink must only claim batches for teams that (a) have a team row in their org's+duckgres control plane and (b) have the rollout feature flag on. The row is createdwhen the team completes the managed-warehouse enable flow. Claiming anythingelse can switch an unregistered team from its legacy team-id schema to a newlychosen suffix after the sink has already primed it.@@ -16,12 +16,11 @@ from __future__ import annotationsfrom dataclasses import dataclass-from django.db.models import F-import structlogimport posthoganalytics-from posthog.ducklake.common import is_dev_mode+from posthog.ducklake import cp_teams+from posthog.ducklake.common import _get_org_id_for_team, is_dev_modefrom posthog.exceptions_capture import capture_exceptionlogger = structlog.get_logger(__name__)@@ -30,17 +29,17 @@ DUCKGRES_BATCH_SINK_FLAG = "duckgres-batch-sink"def is_duckgres_sink_team_member(team_id: int) -> bool:- """Whether a team has registered its membership in its org's Duckgres server.+ """Whether a team has registered its membership in its org's Duckgres warehouse.- ``table_suffix`` is intentionally not part of this check. Legacy memberships- with a NULL/empty suffix use the stable team-id schema naming fallback.+ Membership is the team's row in the duckgres control plane; whether the row derives+ or pins its schema names is intentionally not part of this check. Raises when the+ control plane can't answer — the caller decides how to degrade."""- from posthog.ducklake.models import DuckgresServerTeam-- return DuckgresServerTeam.objects.filter(- team_id=team_id,- server__organization_id=F("team__organization_id"),- ).exists()+ organization_id = _get_org_id_for_team(team_id)+ teams = cp_teams.list_org_teams(organization_id)+ if teams is None:+ raise RuntimeError(f"duckgres control plane unreachable resolving sink membership for team {team_id}")+ return any(team.team_id == team_id for team in teams)@dataclass(frozen=True)@@ -61,9 +60,10 @@ def duckgres_sink_enablement() -> SinkEnablement | None:"""Enabled teams plus their org's sink concurrency budget, or None for"no filter, no budgets" (dev mode).- Runs sync (Django ORM + flag evaluation); call via sync_to_async from the- consumer. Raises on app-DB errors — the caller keeps its previous cached- value so a transient app-DB blip doesn't blind the sink.+ Runs sync (control-plane read + Django ORM + flag evaluation); call via+ sync_to_async from the consumer. Raises on app-DB errors or an unreachable+ control plane — the caller keeps its previous cached value so a transient+ blip doesn't blind the sink.The flag is evaluated only-locally (no per-team network round-trip) with theorg/project group properties supplied inline, matching the data-warehouse-scene@@ -73,32 +73,59 @@ def duckgres_sink_enablement() -> SinkEnablement | None:if is_dev_mode():return None- from posthog.ducklake.models import DuckgresServerTeam+ from posthog.ducklake.models import DuckgresServer+ from posthog.models.team.team import Team++ rows = cp_teams.list_member_teams()+ if rows is None:+ raise RuntimeError("duckgres control plane unreachable; keeping the previous sink enablement")++ team_info = {+ team_id: (str(team_uuid), str(org_id))+ for team_id, team_uuid, org_id in Team.objects.filter(id__in=[row.team_id for row in rows]).values_list(+ "id", "uuid", "organization_id"+ )+ }+ budgets = {+ str(org_id): sink_max_concurrency+ for org_id, sink_max_concurrency in DuckgresServer.objects.filter(+ organization_id__in={row.organization_id for row in rows}+ ).values_list("organization_id", "sink_max_concurrency")+ }enabled: list[int] = []team_org_budgets: list[tuple[int, str, int]] = []- memberships = DuckgresServerTeam.objects.filter(server__organization_id=F("team__organization_id")).values_list(- "team_id", "team__uuid", "team__organization_id", "server__sink_max_concurrency"- )- for team_id, team_uuid, org_id, sink_max_concurrency in memberships:+ for row in rows:+ info = team_info.get(row.team_id)+ if info is None:+ continue+ team_uuid, org_id = info+ if org_id.lower() != row.organization_id.lower():+ # A control-plane row whose org doesn't match the team's own org is not a+ # membership of that team's warehouse — mirror the old server-org join.+ continue+ sink_max_concurrency = budgets.get(org_id)+ if sink_max_concurrency is None:+ # No connection row means the sink can't reach the org's server anyway.+ continuetry:if posthoganalytics.feature_enabled(DUCKGRES_BATCH_SINK_FLAG,- str(team_uuid),- groups={"organization": str(org_id), "project": str(team_id)},+ team_uuid,+ groups={"organization": org_id, "project": str(row.team_id)},group_properties={- "organization": {"id": str(org_id)},- "project": {"id": str(team_id), "organization_id": str(org_id)},+ "organization": {"id": org_id},+ "project": {"id": str(row.team_id), "organization_id": org_id},},only_evaluate_locally=True,send_feature_flag_events=False,):- enabled.append(team_id)- team_org_budgets.append((team_id, str(org_id), sink_max_concurrency))+ enabled.append(row.team_id)+ team_org_budgets.append((row.team_id, org_id, sink_max_concurrency))except Exception as e:# Flag evaluation failing for one team must not blind the whole sink;# treat as disabled (safe direction: we skip, never wrongly claim).- logger.exception("duckgres_sink_flag_evaluation_failed", team_id=team_id)+ logger.exception("duckgres_sink_flag_evaluation_failed", team_id=row.team_id)capture_exception(e)return SinkEnablement(team_ids=enabled, team_org_budgets=team_org_budgets)diff --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 ebf0c1bdc22d..8fe711465398 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@@ -594,9 +594,9 @@ def _process_backfill_batch(def _duckgres_schema_name(team_id: int) -> str:- # Resolves to posthog_data_imports_<table_suffix> when the team has set one- # (DuckgresServerTeam.table_suffix — the same suffix that names its- # events/persons tables), else the legacy posthog_data_imports_team_<id>.+ # Resolves to posthog_data_imports_<schema> from the team's duckgres control-plane+ # row (the same identifier that names its events/persons tables), else the legacy+ # posthog_data_imports_team_<id>.return duckgres_data_imports_schema(team_id)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_enablement.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_enablement.pyindex 41183f208df3..eac84be3128c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_enablement.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_enablement.py@@ -1,15 +1,38 @@import pytestfrom unittest.mock import MagicMock, patch-from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam+from posthog.ducklake import cp_teams+from posthog.ducklake.models import DuckgresServerfrom posthog.models import Organization, Teamfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres import enablementfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.enablement import (duckgres_sink_team_ids,+ is_duckgres_sink_team_member,)[email protected](autouse=True)+def _reset_cp_cache():+ cp_teams.clear_cache()+ yield+ cp_teams.clear_cache()+++def _cp_row(team: Team, *, backfill_enabled: bool = True) -> dict:+ return {+ "org_id": str(team.organization_id),+ "team_id": team.id,+ "schema_name": f"team_{team.id}",+ "enabled": True,+ "backfill_enabled": backfill_enabled,+ }+++def _patch_all_rows(rows):+ return patch("posthog.ducklake.cp_teams._fetch_all_rows", return_value=rows)++@pytest.mark.django_db@patch.object(enablement, "is_dev_mode", return_value=False)@patch.object(enablement.posthoganalytics, "feature_enabled")@@ -20,11 +43,11 @@ def test_duckgres_sink_flag_evaluated_locally_with_group_properties(org+project group properties supplied inline and only-local evaluation."""org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)- server = DuckgresServer.objects.create(organization=org, host="h", username="root", password="x")- DuckgresServerTeam.objects.create(server=server, team=team)+ DuckgresServer.objects.create(organization=org, host="h", username="root", password="x")mock_feature_enabled.return_value = True- assert duckgres_sink_team_ids() == [team.id]+ with _patch_all_rows([_cp_row(team)]):+ assert duckgres_sink_team_ids() == [team.id]mock_feature_enabled.assert_called_once_with("duckgres-batch-sink",@@ -49,11 +72,11 @@ def test_duckgres_sink_skips_team_when_flag_unresolved_locally(falsy value must skip the team, never claim it."""org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)- server = DuckgresServer.objects.create(organization=org, host="h", username="root", password="x")- DuckgresServerTeam.objects.create(server=server, team=team)+ DuckgresServer.objects.create(organization=org, host="h", username="root", password="x")mock_feature_enabled.return_value = None- assert duckgres_sink_team_ids() == []+ with _patch_all_rows([_cp_row(team)]):+ assert duckgres_sink_team_ids() == []@pytest.mark.django_db@@ -69,15 +92,14 @@ def test_duckgres_sink_enablement_uses_memberships_and_carries_org_budgets(team_a = Team.objects.create(organization=org_a)team_b = Team.objects.create(organization=org_b)Team.objects.create(organization=org_a)- server_a = DuckgresServer.objects.create(organization=org_a, host="h", username="root", password="x")- server_b = DuckgresServer.objects.create(- organization=org_b, host="h", username="root", password="x", sink_max_concurrency=7- )- DuckgresServerTeam.objects.create(server=server_a, team=team_a)- DuckgresServerTeam.objects.create(server=server_b, team=team_b, backfill_enabled=False)+ DuckgresServer.objects.create(organization=org_a, host="h", username="root", password="x")+ DuckgresServer.objects.create(organization=org_b, host="h", username="root", password="x", sink_max_concurrency=7)mock_feature_enabled.return_value = True- result = enablement.duckgres_sink_enablement()+ # Disabled events backfill does not revoke sink membership; the unregistered third+ # team is never evaluated even though its org is provisioned.+ with _patch_all_rows([_cp_row(team_a), _cp_row(team_b, backfill_enabled=False)]):+ result = enablement.duckgres_sink_enablement()assert result is not Noneassert sorted(result.team_ids) == sorted([team_a.id, team_b.id])@@ -85,6 +107,35 @@ def test_duckgres_sink_enablement_uses_memberships_and_carries_org_budgets((team_a.id, str(org_a.id), 4), # model default(team_b.id, str(org_b.id), 7),}- # NULL suffix and disabled events backfill do not revoke sink membership;- # the unregistered third team is never evaluated even though its org is provisioned.assert mock_feature_enabled.call_count == 2++[email protected](enablement, "is_dev_mode", return_value=False)[email protected](enablement.posthoganalytics, "feature_enabled")+def test_duckgres_sink_enablement_raises_when_control_plane_unreachable(+ mock_feature_enabled: MagicMock, _mock_dev: MagicMock+) -> None:+ # The consumer keeps its previous cached enablement on a raise; returning an empty+ # enablement instead would silently stop the sink fleet-wide on a CP blip.+ with _patch_all_rows(None):+ with pytest.raises(RuntimeError):+ enablement.duckgres_sink_enablement()++ mock_feature_enabled.assert_not_called()+++def test_is_duckgres_sink_team_member_reads_the_control_plane() -> None:+ org = Organization.objects.create(name="Org")+ member = Team.objects.create(organization=org)+ non_member = Team.objects.create(organization=org)++ with patch("posthog.ducklake.cp_teams._fetch_org_rows", return_value=[_cp_row(member)]):+ assert is_duckgres_sink_team_member(member.id) is True+ assert is_duckgres_sink_team_member(non_member.id) is False++ cp_teams.clear_cache()+ with patch("posthog.ducklake.cp_teams._fetch_org_rows", return_value=None):+ with pytest.raises(RuntimeError):+ is_duckgres_sink_team_member(member.id)