: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): add cp read routing for duckgres team state (#72863)
Benjamin Knofe-Vider7becb1367e58
diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.pyindex 80234a36ef9f..2f0271c1ed69 100644--- a/posthog/dags/events_backfill_to_duckling.py+++ b/posthog/dags/events_backfill_to_duckling.py@@ -39,7 +39,7 @@ import dataclassesfrom collections.abc import Callablefrom contextlib import closingfrom datetime import date, datetime, timedelta-from typing import Any, Literal+from typing import Any, Literal, castfrom django.db import DatabaseErrorfrom django.utils import timezone@@ -71,6 +71,7 @@ from posthog.clickhouse.cluster import ClickhouseCluster, get_clusterfrom posthog.clickhouse.query_tagging import tags_contextfrom posthog.cloud_utils import is_cloudfrom posthog.dags.common import JobOwners, dagster_tags, settings_with_log_comment+from posthog.ducklake import team_statefrom posthog.ducklake.client import make_duckgres_conninfofrom posthog.ducklake.common import (DUCKGRES_BUCKET_REGION,@@ -215,12 +216,14 @@ def _resolve_table_names(team_id: int) -> tuple[str, str]: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."""- suffix = DuckgresServerTeam.objects.filter(team_id=team_id).values_list("table_suffix", flat=True).first()- if not suffix:- return "events", "persons"- _validate_identifier(suffix)- return f"events_{suffix}", f"persons_{suffix}"+ events_table, persons_table = team_state.resolve_events_persons_tables(team_id)+ _validate_identifier(events_table)+ _validate_identifier(persons_table)+ return events_table, persons_tabledef _resolve_duckling_target(team_id: int) -> DucklingTarget:@@ -2859,7 +2862,7 @@ def duckling_events_daily_backfill_sensor(run_requests: list[RunRequest] = []catchup_emitted = 0 # older-than-yesterday days created this tick, bounded below- for backfill in DuckgresServerTeam.objects.filter(backfill_enabled=True):+ for backfill in team_state.list_enabled_backfill_rows("events_daily_backfill_sensor"):for partition_date in current_month_dates:date_str = partition_date.strftime("%Y-%m-%d")partition_key = f"{backfill.team_id}_{date_str}"@@ -2973,24 +2976,28 @@ EVENTS_BACKFILL_STATUS_RECONCILE_LIMIT = 25_FULL_BACKFILL_RUN_TAG = {"duckling_backfill_type": "full"}-def _push_earliest_event_date_to_cp(bf: DuckgresServerTeam) -> None:+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.- Dual-write while per-team backfill state moves into the control plane: the Django row- stays 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.+ Dual-write while per-team backfill state moves into the control plane. 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."""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- managed_warehouse.push_team_earliest_event_date(bf.server.organization_id, bf.team_id, bf.earliest_event_date)+ return managed_warehouse.push_team_earliest_event_date(+ bf.server.organization_id, bf.team_id, bf.earliest_event_date+ )except Exception:logger.exception("duckling_earliest_event_date_cp_push_failed", team_id=bf.team_id)+ return False-def _reconcile_earliest_event_dates_with_cp(backfills: list[DuckgresServerTeam]) -> None:+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@@ -3140,31 +3147,39 @@ def duckling_events_full_backfill_sensor(today = timezone.now().date()last_month_end = today.replace(day=1) - timedelta(days=1)- backfills = list(- DuckgresServerTeam.objects.filter(backfill_enabled=True).select_related("server").order_by("team_id")- )+ backfills = team_state.list_enabled_backfill_rows("events_full_backfill_sensor")if not backfills:context.log.info("No enabled DuckgresServerTeam entries 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# only expensive op (one ClickHouse query/team), bounded per tick and cached forever.- lookups = 0- for bf in backfills:- if bf.earliest_event_date is not None:- continue- if lookups >= EVENTS_BACKFILL_MAX_EARLIEST_LOOKUPS_PER_TICK:- break- lookups += 1+ # 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.+ 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")- bf.save(update_fields=["earliest_event_date"])- _push_earliest_event_date_to_cp(bf)+ 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:+ context.log.warning(+ f"Control plane rejected earliest_event_date persist for team_id={bf.team_id}; retrying next tick"+ )- # Heal one-shot pushes that failed: re-mirror any resolved date the control plane- # is missing or has stale. Never fails the tick.- _reconcile_earliest_event_dates_with_cp(backfills)+ 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"))@@ -3279,7 +3294,7 @@ def duckling_persons_daily_backfill_sensor(new_partitions: list[str] = []run_requests: list[RunRequest] = []- for backfill in DuckgresServerTeam.objects.filter(backfill_enabled=True):+ for backfill in team_state.list_enabled_backfill_rows("persons_daily_backfill_sensor"):partition_key = f"{backfill.team_id}_{yesterday}"if partition_key not in existing:@@ -3369,9 +3384,7 @@ def duckling_persons_full_backfill_sensor(To restart from scratch, reset the cursor in Dagster UI:Sensors -> duckling_persons_full_backfill_sensor -> Reset cursor"""- backfills = list(- DuckgresServerTeam.objects.filter(backfill_enabled=True).select_related("server").order_by("team_id")- )+ backfills = team_state.list_enabled_backfill_rows("persons_full_backfill_sensor")if not backfills:context.log.info("No enabled DuckgresServerTeam entries found")return SensorResult(run_requests=[])diff --git a/posthog/dags/test_events_backfill_to_duckling.py b/posthog/dags/test_events_backfill_to_duckling.pyindex 1e1205daa804..06fbb27f09b6 100644--- a/posthog/dags/test_events_backfill_to_duckling.py+++ b/posthog/dags/test_events_backfill_to_duckling.py@@ -178,22 +178,22 @@ class TestResolveTableNames:return modeldef test_set_suffix_yields_dedicated_tables(self):- with patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam", self._patch_suffix("alpha")):+ 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.dags.events_backfill_to_duckling.DuckgresServerTeam", self._patch_suffix("alpha")):+ with patch("posthog.ducklake.models.DuckgresServerTeam", self._patch_suffix("alpha")):assert _resolve_table_names(1) == ("events_alpha", "persons_alpha")- with patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam", self._patch_suffix("beta")):+ 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.dags.events_backfill_to_duckling.DuckgresServerTeam", self._patch_suffix(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.dags.events_backfill_to_duckling.DuckgresServerTeam", self._patch_suffix("a-b; DROP")):+ with patch("posthog.ducklake.models.DuckgresServerTeam", self._patch_suffix("a-b; DROP")):with pytest.raises(ValueError):_resolve_table_names(1)@@ -673,7 +673,7 @@ class TestFullBackfillSensorEarliestDate:])@patch("posthog.ducklake.common.get_earliest_event_date_for_team")- @patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam")+ @patch("posthog.ducklake.team_state.list_enabled_backfill_rows")@patch("posthog.dags.events_backfill_to_duckling.timezone")@patch("posthog.dags.events_backfill_to_duckling.stale_running_partitions", new=MagicMock(return_value=[]))def test_earliest_date_clamped(@@ -682,7 +682,7 @@ class TestFullBackfillSensorEarliestDate:earliest_dt,expected_first_month,mock_tz,- mock_backfill_cls,+ mock_list_rows,mock_get_earliest,):from dagster import DagsterInstance, SensorResult, build_sensor_context@@ -693,7 +693,7 @@ class TestFullBackfillSensorEarliestDate:backfill = MagicMock()backfill.team_id = 1backfill.earliest_event_date = None # unresolved → sensor resolves + caches it- mock_backfill_cls.objects.filter.return_value.select_related.return_value.order_by.return_value = [backfill]+ mock_list_rows.return_value = [backfill]instance = DagsterInstance.ephemeral()context = build_sensor_context(instance=instance)@@ -710,10 +710,10 @@ class TestFullBackfillSensorEarliestDate:assert backfill.earliest_event_date == max(earliest_dt, datetime(2015, 1, 1)).date()@patch("posthog.ducklake.common.get_earliest_event_date_for_team")- @patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam")+ @patch("posthog.ducklake.team_state.list_enabled_backfill_rows")@patch("posthog.dags.events_backfill_to_duckling.timezone")@patch("posthog.dags.events_backfill_to_duckling.stale_running_partitions", new=MagicMock(return_value=[]))- def test_no_events_returns_empty(self, mock_tz, mock_backfill_cls, mock_get_earliest):+ def test_no_events_returns_empty(self, mock_tz, mock_list_rows, mock_get_earliest):from dagster import DagsterInstance, SensorResult, build_sensor_contextmock_tz.now.return_value = datetime(2025, 2, 10, 12, 0, 0)@@ -722,7 +722,7 @@ class TestFullBackfillSensorEarliestDate:backfill = MagicMock()backfill.team_id = 1backfill.earliest_event_date = None- mock_backfill_cls.objects.filter.return_value.select_related.return_value.order_by.return_value = [backfill]+ mock_list_rows.return_value = [backfill]instance = DagsterInstance.ephemeral()context = build_sensor_context(instance=instance)@@ -750,14 +750,14 @@ class TestFullBackfillSensorEarliestDate:with (patch("posthog.dags.events_backfill_to_duckling.timezone") as mock_tz,- patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam") as mock_cls,+ patch("posthog.ducklake.team_state.list_enabled_backfill_rows") as mock_list_rows,patch("posthog.dags.events_backfill_to_duckling.ManagedWarehouseBackfillPartition") as mock_projection,patch("posthog.dags.events_backfill_to_duckling.record_backfill_outcome"),patch("posthog.dags.events_backfill_to_duckling.stale_running_partitions", return_value=[]),patch("posthog.ducklake.common.get_earliest_event_date_for_team") as mock_ge,):mock_tz.now.return_value = now- mock_cls.objects.filter.return_value.select_related.return_value.order_by.return_value = backfills+ mock_list_rows.return_value = backfillsmock_projection.objects.unscoped.return_value.filter.return_value.values_list.return_value = []if isinstance(get_earliest, list):mock_ge.side_effect = get_earliest@@ -833,15 +833,16 @@ class TestFullBackfillSensorEarliestDate:def test_caps_earliest_lookups_per_tick(self):# 7 unresolved teams, cap is 5 → only 5 ClickHouse lookups this tick; the other two- # stay unresolved and contribute no partitions until a later tick.+ # stay unresolved and contribute no partitions until a later tick. Selection is+ # shuffled (budget fairness), so assert counts, not which teams won the budget.backfills = [self._bf(t) for t in range(1, 8)]result, mock_ge = self._run_full_sensor(backfills, now=datetime(2020, 2, 10, 12, 0, 0), get_earliest=datetime(2020, 1, 1))assert mock_ge.call_count == 5teams_emitted = {rr.partition_key.split("_")[0] for rr in result.run_requests}- assert teams_emitted == {"1", "2", "3", "4", "5"}- assert backfills[5].earliest_event_date is None and backfills[6].earliest_event_date is None+ assert len(teams_emitted) == 5+ assert sum(1 for bf in backfills if bf.earliest_event_date is None) == 2def test_top_up_only_fills_to_target_depth(self):# 98 runs already in flight against the depth-100 target → only 2 slots free this tick.@@ -869,14 +870,12 @@ class TestFullBackfillSensorEarliestDate:with (patch("posthog.dags.events_backfill_to_duckling.timezone") as mock_tz,- patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam") as mock_cls,+ patch("posthog.ducklake.team_state.list_enabled_backfill_rows") as mock_list_rows,patch("posthog.dags.events_backfill_to_duckling.stale_running_partitions", return_value=[]),patch("posthog.ducklake.common.get_earliest_event_date_for_team"),):mock_tz.now.return_value = datetime(2020, 2, 10, 12, 0, 0)- mock_cls.objects.filter.return_value.select_related.return_value.order_by.return_value = [- self._bf(1, earliest=date(2020, 1, 1))- ]+ mock_list_rows.return_value = [self._bf(1, earliest=date(2020, 1, 1))]instance = DagsterInstance.ephemeral()context = build_sensor_context(instance=instance)with patch.object(instance, "get_runs", return_value=[]) as mock_get_runs:@@ -985,6 +984,79 @@ class TestEarliestEventDateReconcile: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.++ @staticmethod+ def _cp_row(team_id: int, earliest: str | None = None) -> dict:+ return {+ "org_id": "org-a",+ "team_id": team_id,+ "schema_name": f"schema_{team_id}",+ "enabled": True,+ "backfill_enabled": True,+ "events_table_name": None,+ "persons_table_name": None,+ "schema_data_imports_name": None,+ "earliest_event_date": earliest,+ }++ def _run_cp_sensor(self, cp_rows, *, now, get_earliest=None):+ from dagster import DagsterInstance, build_sensor_context++ from posthog.ducklake import cp_teams++ 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,+ patch("posthog.dags.events_backfill_to_duckling.record_backfill_outcome"),+ patch("posthog.dags.events_backfill_to_duckling.stale_running_partitions", return_value=[]),+ patch("posthog.ducklake.common.get_earliest_event_date_for_team", return_value=get_earliest),+ 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 = now+ mock_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+ finally:+ 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(+ [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).+ 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(+ [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))+ assert result.run_requests == []+ mock_push.assert_not_called()++class TestStaleRunOutcome:# A stuck-RUNNING row may only be resolved from a run that provably ended — resolving a live# or queued run would overwrite the terminal state its own process is about to write.@@ -1032,10 +1104,10 @@ class TestDailyBackfillSensor:with (patch("posthog.dags.events_backfill_to_duckling.timezone") as mock_tz,- patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam") as mock_cls,+ patch("posthog.ducklake.team_state.list_enabled_backfill_rows") as mock_list_rows,):mock_tz.now.return_value = now- mock_cls.objects.filter.return_value = backfills+ mock_list_rows.return_value = backfillsinstance = DagsterInstance.ephemeral()if existing:diff --git a/posthog/ducklake/common.py b/posthog/ducklake/common.pyindex 477867cc2e70..e0b29e33be43 100644--- a/posthog/ducklake/common.py+++ b/posthog/ducklake/common.py@@ -535,13 +535,11 @@ def duckgres_data_imports_schema(team_id: int) -> str:that have already written a team's tables must trigger a re-prime (handledby the backfill state machine), not silently switch."""- from posthog.ducklake.models import DuckgresServerTeam+ # Deferred: team_state imports this module at the top level, so a module-level+ # import back would be circular.+ from posthog.ducklake import team_state # noqa: PLC0415- 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}"+ return team_state.data_imports_schema(team_id)def duckgres_data_imports_table_name(schema: ExternalDataSchema) -> str:@@ -708,12 +706,11 @@ def get_team_backfill_state(team_id: int) -> dict[str, object]:safe to show) from one already backfilling (a row exists → show read-only, since the table isimmutable). ``table_suffix`` is None for legacy teams still on the shared tables."""- from posthog.ducklake.models import DuckgresServerTeam+ # Deferred: team_state imports this module at the top level, so a module-level+ # import back would be circular.+ from posthog.ducklake import team_state # noqa: PLC0415- 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"]}+ return team_state.team_backfill_state(team_id)# Ignore events before this date — pre-2015 data is typically junk timestamps.diff --git a/posthog/ducklake/cp_teams.py b/posthog/ducklake/cp_teams.pynew file mode 100644index 000000000000..aa7df6392be9--- /dev/null+++ b/posthog/ducklake/cp_teams.py@@ -0,0 +1,190 @@+"""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).+This module exposes the CP rows as :class:`CPTeam` values plus a small process-local+TTL cache so hot paths (the v3 data-import sink schema resolution) don't issue one+HTTP call per batch.++Legacy-name semantics of a CP row: a non-NULL ``events_table_name`` /+``persons_table_name`` / ``schema_data_imports_name`` is a grandfathered explicit+pin; NULL means "derive from ``schema_name``". The derive rule here is the+TRANSITIONAL one — writers still produce the old suffix-derived layout, so for+every existing row it is byte-identical to the Django-side derivation:++* events: ``events_<schema_name>``+* persons: ``persons_<schema_name>``+* data-imports schema: ``posthog_data_imports_<schema_name>``++Do NOT change this to the future ``<schema_name>.events`` layout until the writers do.++Every fetcher returns ``None`` when the control plane is unreachable or answers+unusably — callers decide the failure posture (fail open, fail closed, or raise).+"""++from __future__ import annotations++import time+import logging+import threading+from collections.abc import Callable+from dataclasses import dataclass+from datetime import date++logger = logging.getLogger(__name__)++# TTL for the process-local cache below. Monkeypatchable in tests; sized so sensor+# ticks and per-batch schema resolutions coalesce onto one CP call per minute.+CACHE_TTL_SECONDS: float = 60.0+++@dataclass+class CPTeam:+ """One duckgres control-plane org-team row."""++ team_id: int+ organization_id: str+ schema_name: str+ enabled: bool+ backfill_enabled: bool+ events_table_name: str | None+ persons_table_name: str | None+ schema_data_imports_name: str | None+ earliest_event_date: date | None++ @property+ def resolved_events_table(self) -> str:+ """Events table name: the grandfathered pin, else the transitional derivation."""+ return self.events_table_name or f"events_{self.schema_name}"++ @property+ def resolved_persons_table(self) -> str:+ """Persons table name: the grandfathered pin, else the transitional derivation."""+ return self.persons_table_name or f"persons_{self.schema_name}"++ @property+ def resolved_data_imports_schema(self) -> str:+ """Data-imports schema: the grandfathered pin, else the transitional derivation."""+ return self.schema_data_imports_name or f"posthog_data_imports_{self.schema_name}"+++def _parse_earliest_event_date(raw: object) -> date | None:+ if not raw:+ return None+ if isinstance(raw, date):+ return raw+ try:+ return date.fromisoformat(str(raw))+ except ValueError:+ logger.warning("cp_teams_unparseable_earliest_event_date: %r", raw)+ return None+++def team_from_row(row: dict, *, organization_id: str | None = None) -> CPTeam | None:+ """Build a CPTeam from a raw API row, or None when the row is unusable."""+ try:+ team_id = int(row["team_id"]) # defensive: the API serializes ints, but coerce anyway+ except (KeyError, TypeError, ValueError):+ logger.warning("cp_teams_row_missing_team_id")+ return None+ schema_name = row.get("schema_name")+ if not isinstance(schema_name, str) or not schema_name:+ logger.warning("cp_teams_row_missing_schema_name (team_id=%s)", team_id)+ return None+ # Writes derive their URL from the org id, so a row without one is unusable — an+ # empty org would send updates down /orgs//teams/... and fail silently every tick.+ org = row.get("org_id") or organization_id+ if not org:+ logger.warning("cp_teams_row_missing_org_id (team_id=%s)", team_id)+ return None+ return CPTeam(+ team_id=team_id,+ organization_id=str(org),+ schema_name=schema_name,+ enabled=bool(row.get("enabled")),+ backfill_enabled=bool(row.get("backfill_enabled")),+ events_table_name=row.get("events_table_name") or None,+ persons_table_name=row.get("persons_table_name") or None,+ schema_data_imports_name=row.get("schema_data_imports_name") or None,+ earliest_event_date=_parse_earliest_event_date(row.get("earliest_event_date")),+ )+++_cache_lock = threading.Lock()+_cache: dict[tuple[str, ...], tuple[float, list[dict]]] = {}+++def clear_cache() -> None:+ """Drop every cached CP response (for tests and operational cache busts)."""+ with _cache_lock:+ _cache.clear()+++def _cached_rows(key: tuple[str, ...], fetch: Callable[[], list[dict] | None]) -> list[dict] | None:+ """Serve `key` from the TTL cache, fetching (and caching only successes) on a miss."""+ with _cache_lock:+ hit = _cache.get(key)+ if hit is not None and time.monotonic() - hit[0] < CACHE_TTL_SECONDS:+ return hit[1]+ rows = fetch()+ if rows is not None:+ with _cache_lock:+ _cache[key] = (time.monotonic(), rows)+ return rows+++def _fetch_org_rows(organization_id: str) -> list[dict] | None:+ # Deferred: keeps the DRF-importing adapter (and the products presentation stack)+ # off this module's import path.+ from products.data_warehouse.backend.presentation.views import managed_warehouse # noqa: PLC0415++ try:+ resp = managed_warehouse.list_teams(organization_id, require_enabled=False)+ return managed_warehouse._teams_from_response(resp)+ except Exception:+ logger.exception("cp_teams_list_org_teams_failed (organization_id=%s)", organization_id)+ return None+++def _fetch_all_rows() -> list[dict] | None:+ # Deferred for the same reason as _fetch_org_rows.+ from products.data_warehouse.backend.presentation.views import managed_warehouse # noqa: PLC0415++ try:+ resp = managed_warehouse.list_all_teams()+ return managed_warehouse._teams_from_response(resp)+ except Exception:+ logger.exception("cp_teams_list_all_teams_failed")+ return None+++def list_org_teams(organization_id: str) -> list[CPTeam] | None:+ """All CP team rows of an org, or None when the control plane can't answer."""+ org_id = str(organization_id)+ rows = _cached_rows(("org_teams", org_id), lambda: _fetch_org_rows(org_id))+ if rows is None:+ return None+ teams = (team_from_row(row, organization_id=org_id) for row in rows)+ return [team for team in teams if team is not None]+++def get_team(organization_id: str, team_id: int) -> CPTeam | None:+ """The CP row for one team, or None when absent OR the control plane can't answer.++ Callers that must distinguish "absent" from "unreachable" should use+ :func:`list_org_teams` directly.+ """+ teams = list_org_teams(organization_id)+ if teams is None:+ return None+ wanted = int(team_id)+ 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."""+ rows = _cached_rows(("all_teams",), _fetch_all_rows)+ if rows is None:+ return None+ teams = (team_from_row(row) for row in rows)+ return [team for team in teams if team is not None and team.backfill_enabled]diff --git a/posthog/ducklake/team_state.py b/posthog/ducklake/team_state.pynew file mode 100644index 000000000000..e19309aa350b--- /dev/null+++ b/posthog/ducklake/team_state.py@@ -0,0 +1,404 @@+"""Mode-routable 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:++* ``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.+"""++from __future__ import annotations++import time+import threading+from datetime import date+from typing import TYPE_CHECKING++import structlog++from posthog.ducklake import cp_teams+from 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 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)+++# --- 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 _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)+ if row is None:+ # Mirrors the django no-row case: legacy single-team ducklings share the base tables.+ return "events", "persons"+ events_table, persons_table = row.resolved_events_table, row.resolved_persons_table+ validate_duckgres_identifier(events_table)+ validate_duckgres_identifier(persons_table)+ 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 _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)+ if row is None:+ # Mirrors the django no-row case: the historical per-team schema.+ return f"posthog_data_imports_team_{team_id}"+ schema = row.resolved_data_imports_schema+ validate_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.++ A grandfathered legacy-shared team pins the base ``events``/``persons`` tables and+ has no suffix (None); every other row's schema name doubles as its suffix (the+ dual-write stores the same identifier in both places).+ """+ if row.events_table_name == "events" or row.persons_table_name == "persons":+ return None+ return 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_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).+ """+ 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+++# --- membership existence (team-deletion guard) -----------------------------------+++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.+ """+ 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+++# --- enabled-backfill enumeration (Dagster sensors) -------------------------------+++class CPBackfillRow:+ """Lightweight sensor row mirroring the ``DuckgresServerTeam`` attributes 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.+ """++ def __init__(self, team_id: int, organization_id: str, earliest_event_date: date | None) -> None:+ self.team_id = team_id+ self.organization_id = organization_id+ self.earliest_event_date = earliest_event_date++ @property+ def server(self) -> 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]:+ """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.+ """+ 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)diff --git a/posthog/ducklake/test_cp_teams.py b/posthog/ducklake/test_cp_teams.pynew file mode 100644index 000000000000..f99d6271e51b--- /dev/null+++ b/posthog/ducklake/test_cp_teams.py@@ -0,0 +1,149 @@+from datetime import date++from unittest.mock import patch++from parameterized import parameterized++from posthog.ducklake import cp_teams+from posthog.ducklake.cp_teams import CPTeam, team_from_row+++def _row(**overrides) -> dict:+ row = {+ "org_id": "org-1",+ "team_id": 1,+ "schema_name": "prod",+ "enabled": True,+ "is_billing_team": False,+ "backfill_enabled": True,+ "events_table_name": None,+ "persons_table_name": None,+ "schema_data_imports_name": None,+ "earliest_event_date": None,+ }+ row.update(overrides)+ return row+++class TestCPTeamResolution:+ # The transitional derive rule must stay byte-identical to the django-suffix layout;+ # a premature switch to the future `<schema>.events` derivation (or broken pin+ # precedence) would point readers/writers at tables that don't exist.+ @parameterized.expand(+ [+ (+ "null_pins_derive_from_schema",+ {"schema_name": "us_prod"},+ ("events_us_prod", "persons_us_prod", "posthog_data_imports_us_prod"),+ ),+ (+ "pins_win_over_derivation",+ {+ "schema_name": "team_7",+ "events_table_name": "events",+ "persons_table_name": "persons",+ "schema_data_imports_name": "posthog_data_imports_team_7",+ },+ ("events", "persons", "posthog_data_imports_team_7"),+ ),+ (+ "partial_pins_mix_with_derivation",+ {"schema_name": "beta", "events_table_name": "events_legacy"},+ ("events_legacy", "persons_beta", "posthog_data_imports_beta"),+ ),+ (+ "empty_string_pins_are_treated_as_unset",+ {"schema_name": "beta", "events_table_name": "", "schema_data_imports_name": ""},+ ("events_beta", "persons_beta", "posthog_data_imports_beta"),+ ),+ ]+ )+ def test_resolved_names(self, _name: str, overrides: dict, expected: tuple[str, str, str]) -> None:+ team = team_from_row(_row(**overrides))+ assert team is not None+ assert (team.resolved_events_table, team.resolved_persons_table, team.resolved_data_imports_schema) == expected+++class TestTeamFromRow:+ def test_coerces_types_defensively(self) -> None:+ # A CP that serializes team_id as a string must not break int comparisons, and the+ # date string must come back as a date so sensor math works.+ team = team_from_row(_row(team_id="42", earliest_event_date="2020-06-15", backfill_enabled=True))+ assert team == CPTeam(+ team_id=42,+ organization_id="org-1",+ schema_name="prod",+ enabled=True,+ backfill_enabled=True,+ events_table_name=None,+ persons_table_name=None,+ schema_data_imports_name=None,+ earliest_event_date=date(2020, 6, 15),+ )++ @parameterized.expand(+ [+ ("missing_team_id", {"team_id": None}),+ ("unparseable_team_id", {"team_id": "abc"}),+ ("missing_schema_name", {"schema_name": None}),+ # No org anywhere: a write would target /orgs//teams/... and fail silently.+ ("missing_org_id", {"org_id": None}),+ ]+ )+ def test_unusable_rows_are_dropped(self, _name: str, overrides: dict) -> None:+ assert team_from_row(_row(**overrides)) is None+++class TestTTLCache:+ def setup_method(self) -> None:+ cp_teams.clear_cache()++ def teardown_method(self) -> None:+ cp_teams.clear_cache()++ def test_second_call_within_ttl_hits_cache(self) -> None:+ with patch("posthog.ducklake.cp_teams._fetch_org_rows", return_value=[_row()]) as mock_fetch:+ first = cp_teams.list_org_teams("org-1")+ second = cp_teams.list_org_teams("org-1")+ assert mock_fetch.call_count == 1+ assert first == second++ def test_clear_cache_forces_a_refetch(self) -> None:+ with patch("posthog.ducklake.cp_teams._fetch_org_rows", return_value=[_row()]) as mock_fetch:+ cp_teams.list_org_teams("org-1")+ cp_teams.clear_cache()+ cp_teams.list_org_teams("org-1")+ assert mock_fetch.call_count == 2++ def test_cache_is_keyed_per_org(self) -> None:+ with patch("posthog.ducklake.cp_teams._fetch_org_rows", return_value=[_row()]) as mock_fetch:+ cp_teams.list_org_teams("org-1")+ cp_teams.list_org_teams("org-2")+ assert mock_fetch.call_count == 2++ def test_failed_fetches_are_not_cached(self) -> None:+ # An outage must not poison the cache: the next call retries immediately.+ with patch("posthog.ducklake.cp_teams._fetch_org_rows", side_effect=[None, [_row()]]) as mock_fetch:+ assert cp_teams.list_org_teams("org-1") is None+ teams = cp_teams.list_org_teams("org-1")+ assert mock_fetch.call_count == 2+ assert teams is not None and teams[0].team_id == 1++ def test_expired_entry_is_refetched(self) -> None:+ with (+ patch("posthog.ducklake.cp_teams.CACHE_TTL_SECONDS", 0.0),+ patch("posthog.ducklake.cp_teams._fetch_org_rows", return_value=[_row()]) as mock_fetch,+ ):+ cp_teams.list_org_teams("org-1")+ cp_teams.list_org_teams("org-1")+ assert mock_fetch.call_count == 2++ def test_list_enabled_backfills_filters_disabled_rows(self) -> None:+ rows = [+ _row(team_id=1, backfill_enabled=True),+ _row(team_id=2, schema_name="two", backfill_enabled=False),+ ]+ with patch("posthog.ducklake.cp_teams._fetch_all_rows", return_value=rows):+ teams = cp_teams.list_enabled_backfills()+ assert teams is not None+ assert [team.team_id for team in teams] == [1]diff --git a/posthog/ducklake/test_team_state.py b/posthog/ducklake/test_team_state.pynew file mode 100644index 000000000000..2a3593ab1818--- /dev/null+++ b/posthog/ducklake/test_team_state.py@@ -0,0 +1,309 @@+from datetime import date++import pytest+from unittest.mock import patch++from django.test import override_settings++from parameterized import parameterized++from posthog.ducklake import cp_teams, team_state+from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam+from posthog.models import Organization, Team++[email protected](autouse=True)+def _reset_cp_state():+ cp_teams.clear_cache()+ team_state.clear_parity_state()+ yield+ cp_teams.clear_cache()+ team_state.clear_parity_state()+++def _onboarded_team(table_suffix: str | None = "prod") -> 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+++def _cp_row(team: Team, schema_name: str, **overrides) -> dict:+ row = {+ "org_id": str(team.organization_id),+ "team_id": team.id,+ "schema_name": schema_name,+ "enabled": True,+ "backfill_enabled": True,+ "events_table_name": None,+ "persons_table_name": None,+ "schema_data_imports_name": None,+ "earliest_event_date": None,+ }+ row.update(overrides)+ return row+++def _patch_org_rows(rows):+ return patch("posthog.ducklake.cp_teams._fetch_org_rows", return_value=rows)+++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([]):+ 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):+ 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.+ 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)+++class TestEventsPersonsTablesRouting:+ @parameterized.expand(+ [+ # Derive rule and pin precedence as served through the accessor in cp mode.+ ("derived", {}, ("events_cp_schema", "persons_cp_schema")),+ (+ "grandfathered_shared_pins",+ {"events_table_name": "events", "persons_table_name": "persons"},+ ("events", "persons"),+ ),+ ]+ )+ 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)]),+ ):+ 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([]):+ assert team_state.resolve_events_persons_tables(team.id) == ("events", "persons")++ def test_cp_mode_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")]),+ ):+ 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")+++class TestTeamBackfillStateRouting:+ @parameterized.expand(+ [+ ("dual_write_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"},+ {"has_backfill": True, "table_suffix": None},+ ),+ ]+ )+ 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)]),+ ):+ assert team_state.team_backfill_state(team.id) == expected++ @parameterized.expand(+ [+ ("no_cp_row", []),+ # An unreachable CP must degrade to the not-onboarded shape, never 500 the status read.+ ("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):+ 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+++class TestBackfillRowExistsRouting:+ @parameterized.expand(+ [+ ("cp_row_present", "present", True),+ ("cp_row_absent", "absent", False),+ # Fail closed: an unreachable CP must block a possibly-onboarded team's deletion.+ ("cp_unreachable_fails_closed", "unreachable", True),+ ]+ )+ def test_cp_mode(self, _name: str, cp_state: str, expected: bool) -> None:+ org, team = _onboarded_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):+ 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+++class 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()+ 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),+ ):+ rows = team_state.list_enabled_backfill_rows("test")+ assert len(rows) == 1+ row = rows[0]+ assert row.team_id == team.id+ assert row.earliest_event_date == date(2020, 6, 15)+ # 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),+ ):+ 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) == 2diff --git a/posthog/settings/base_variables.py b/posthog/settings/base_variables.pyindex 148a9c1f916b..463ba782e84c 100644--- a/posthog/settings/base_variables.py+++ b/posthog/settings/base_variables.py@@ -76,6 +76,10 @@ 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/products/data_warehouse/backend/presentation/views/managed_warehouse.py b/products/data_warehouse/backend/presentation/views/managed_warehouse.pyindex 793bd4c35607..cd46ee39db89 100644--- a/products/data_warehouse/backend/presentation/views/managed_warehouse.py+++ b/products/data_warehouse/backend/presentation/views/managed_warehouse.py@@ -421,6 +421,15 @@ def list_teams(organization_id: UUID | str, require_enabled: bool = True) -> Resreturn _request("GET", organization_id, "/teams", require_enabled=require_enabled)+def list_all_teams() -> Response:+ """List every duckgres team row across orgs (global internal endpoint).++ Backend-only: feeds the cp-mode sensor enumeration in posthog.ducklake.cp_teams,+ which is why the feature-flag gate is bypassed.+ """+ return _request("GET", "", "teams", require_enabled=False)++def create_team(organization_id: UUID | str,team_id: int,@@ -776,7 +785,10 @@ def block_team_deletion(team_id: int, organization_id: UUID | str) -> str | Nonethe deletion is blocked with a retry error rather than silently orphaning the duckgres row."""# Keep ducklake.models off the core API import path.- from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam # noqa: PLC0415+ # Keep ducklake.team_state (and via it ducklake.common's duckdb dependency) off the+ # API import path.+ from posthog.ducklake import team_state # noqa: PLC0415+ from posthog.ducklake.models import DuckgresServer # noqa: PLC0415if not DuckgresServer.objects.filter(organization_id=organization_id).exists():return None@@ -790,9 +802,9 @@ def block_team_deletion(team_id: int, organization_id: UUID | str) -> str | None"Deprovision the managed warehouse in Data ops settings, or delete the organization, ""before deleting this project.")- if DuckgresServerTeam.objects.filter(team_id=team_id).exists():+ if team_state.backfill_row_exists(team_id, str(organization_id)):return "Could not remove this project from your organization's managed warehouse. Try again in a few minutes."- # Org has a warehouse but this team has no Django backfill row: almost certainly not+ # Org has a warehouse but this team has no membership row: almost certainly not# onboarded, so a control-plane hiccup must not block its deletion. If a duckgres-only# row does exist it is orphaned here, which the control plane tolerates.logger.warning(