:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(devex): move warehouse enums and insight views behind the facades (#87061)
Julian Bez9081abf9ea52
diff --git a/ee/hogai/chat_agent/insights/test/test_nodes.py b/ee/hogai/chat_agent/insights/test/test_nodes.pyindex b8efb684ddd8..df7f13621760 100644--- a/ee/hogai/chat_agent/insights/test/test_nodes.py+++ b/ee/hogai/chat_agent/insights/test/test_nodes.py@@ -6,6 +6,8 @@ from unittest.mock import AsyncMock, MagicMock, patchfrom django.utils import timezone+from asgiref.sync import sync_to_async+from posthog.schema import (AssistantFunnelsQuery,AssistantHogQLQuery,@@ -21,7 +23,8 @@ from posthog.schema import ()from products.posthog_ai.backend.models.assistant import Conversation-from products.product_analytics.backend.facade.models import Insight, InsightViewed+from products.product_analytics.backend.facade.api import record_insight_views+from products.product_analytics.backend.facade.models import Insightfrom ee.hogai.artifacts.manager import ArtifactManagerfrom ee.hogai.chat_agent.insights.nodes import InsightDict, InsightSearchNode, NoInsightsException@@ -93,19 +96,10 @@ class TestInsightSearchNode(BaseTest):saved=True,)- # Create InsightViewed records- InsightViewed.objects.create(- team=self.team,- user=self.user,- insight=self.insight1,- last_viewed_at=timezone.now(),- )-- InsightViewed.objects.create(- team=self.team,- user=self.user,- insight=self.insight2,- last_viewed_at=timezone.now(),+ record_insight_views(+ team_id=self.team.id,+ user_id=self.user.id,+ last_viewed_at_by_insight_id={self.insight1.id: timezone.now(), self.insight2.id: timezone.now()},)def _insight_to_dict(self, insight: Insight) -> InsightDict:@@ -138,12 +132,10 @@ class TestInsightSearchNode(BaseTest):async def test_load_insights_page_unique_only(self):"""Test that load_insights_page returns unique insights only."""- # Update existing insight view to simulate multiple views- await InsightViewed.objects.filter(- team=self.team,- user=self.user,- insight=self.insight1,- ).aupdate(last_viewed_at=timezone.now())+ # Record the same insight again to simulate multiple views+ await sync_to_async(record_insight_views)(+ team_id=self.team.id, user_id=self.user.id, last_viewed_at_by_insight_id={self.insight1.id: timezone.now()}+ )first_page = await self.node._load_insights_page(0)@@ -460,8 +452,7 @@ class TestInsightSearchNode(BaseTest):def test_run_with_no_insights(self):"""Test arun method when no insights exist - should raise NoInsightsException."""- # Clear all insights (done outside async context)- InsightViewed.objects.all().delete()+ # Clear all insights (done outside async context); their view rows cascadeInsight.objects.all().delete()conversation = Conversation.objects.create(team=self.team, user=self.user)@@ -496,11 +487,8 @@ class TestInsightSearchNode(BaseTest):},created_by=self.user,)- await InsightViewed.objects.acreate(- team=other_team,- user=self.user,- insight=other_insight,- last_viewed_at=timezone.now(),+ await sync_to_async(record_insight_views)(+ team_id=other_team.id, user_id=self.user.id, last_viewed_at_by_insight_id={other_insight.id: timezone.now()})# Load first page to test team filtering@@ -850,11 +838,10 @@ class TestInsightSearchNode(BaseTest):created_by=self.user,saved=True,)- await InsightViewed.objects.acreate(- team=self.team,- user=self.user,- insight=insight,- last_viewed_at=timezone.now() - timedelta(days=1),+ await sync_to_async(record_insight_views)(+ team_id=self.team.id,+ user_id=self.user.id,+ last_viewed_at_by_insight_id={insight.id: timezone.now() - timedelta(days=1)},)await self.node._load_insights_page(0)@@ -888,11 +875,8 @@ class TestInsightSearchNode(BaseTest):created_by=self.user,saved=True,)- await InsightViewed.objects.acreate(- team=self.team,- user=self.user,- insight=insight,- last_viewed_at=timezone.now(),+ await sync_to_async(record_insight_views)(+ team_id=self.team.id, user_id=self.user.id, last_viewed_at_by_insight_id={insight.id: timezone.now()})await self.node._load_insights_page(0)diff --git a/ee/hogai/chat_agent/sql/mixins.py b/ee/hogai/chat_agent/sql/mixins.pyindex 345639f09c91..27f2d23279ba 100644--- a/ee/hogai/chat_agent/sql/mixins.py+++ b/ee/hogai/chat_agent/sql/mixins.py@@ -36,7 +36,7 @@ from posthog.models import Teamfrom posthog.models.user import Userfrom posthog.sync import database_sync_to_async-from products.product_analytics.backend.facade.models import InsightVariable+from products.product_analytics.backend.facade.api import insight_variables_by_code_namesfrom ee.hogai.chat_agent.schema_generator.utils import SchemaGeneratorOutputfrom ee.hogai.core.mixins import AssistantContextMixin@@ -142,7 +142,7 @@ class HogQLOutputParserMixin(HogQLDatabaseMixin):code_names = {str(chain[1]) for chain in placeholder_fields if len(chain) >= 2 and chain[0] == "variables"}if not code_names:return []- insight_variables = InsightVariable.objects.filter(team_id=self._team.pk, code_name__in=code_names)+ insight_variables = insight_variables_by_code_names(self._team.pk, code_names)return [HogQLVariable(variableId=str(variable.id), code_name=variable.code_name)for variable in insight_variablesdiff --git a/ee/hogai/context/entity_search/test/test_context.py b/ee/hogai/context/entity_search/test/test_context.pyindex bd9b6fac204d..6e631ceab870 100644--- a/ee/hogai/context/entity_search/test/test_context.py+++ b/ee/hogai/context/entity_search/test/test_context.py@@ -21,7 +21,8 @@ from products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlag-from products.product_analytics.backend.facade.models import Insight, InsightViewed+from products.product_analytics.backend.facade.api import record_insight_views+from products.product_analytics.backend.facade.models import Insightfrom products.surveys.backend.models import Surveyfrom ee.hogai.context import AssistantContextManager@@ -330,11 +331,10 @@ class TestEntitySearchContext(NonAtomicBaseTest):team=self.team, name="List Insight 2", deleted=False, saved=True, created_by=self.user)# list_entities for insights filters by recent views- await InsightViewed.objects.acreate(- team=self.team, user=self.user, insight=insight1, last_viewed_at=timezone.now()- )- await InsightViewed.objects.acreate(- team=self.team, user=self.user, insight=insight2, last_viewed_at=timezone.now()+ await sync_to_async(record_insight_views)(+ team_id=self.team.id,+ user_id=self.user.id,+ last_viewed_at_by_insight_id={insight1.id: timezone.now(), insight2.id: timezone.now()},)entities, total = await self.context.list_entities("insight", limit=10, offset=0)@@ -352,11 +352,10 @@ class TestEntitySearchContext(NonAtomicBaseTest):insight2 = await Insight.objects.acreate(team=self.team, name="Restricted Insight", deleted=False, saved=True, created_by=self.user)- await InsightViewed.objects.acreate(- team=self.team, user=self.user, insight=insight1, last_viewed_at=timezone.now()- )- await InsightViewed.objects.acreate(- team=self.team, user=self.user, insight=insight2, last_viewed_at=timezone.now()+ await sync_to_async(record_insight_views)(+ team_id=self.team.id,+ user_id=self.user.id,+ last_viewed_at_by_insight_id={insight1.id: timezone.now(), insight2.id: timezone.now()},)# Mock filter_queryset_by_access_level to filter out insight2@@ -597,8 +596,8 @@ class TestEntitySearchContext(NonAtomicBaseTest):team=self.team, name=f"Paginated Insight {i}", deleted=False, saved=True, created_by=self.user)# list_entities for insights filters by recent views- await InsightViewed.objects.acreate(- team=self.team, user=self.user, insight=insight, last_viewed_at=timezone.now()+ await sync_to_async(record_insight_views)(+ team_id=self.team.id, user_id=self.user.id, last_viewed_at_by_insight_id={insight.id: timezone.now()})entities_page1, total = await self.context.list_entities("insight", limit=2, offset=0)diff --git a/ee/hogai/tools/execute_sql/direct_connection_suggestions.py b/ee/hogai/tools/execute_sql/direct_connection_suggestions.pyindex 918dcca360e4..ec53359c22e7 100644--- a/ee/hogai/tools/execute_sql/direct_connection_suggestions.py+++ b/ee/hogai/tools/execute_sql/direct_connection_suggestions.py@@ -19,7 +19,7 @@ from posthog.ph_client import feature_enabled_or_falsefrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource-from products.warehouse_sources.backend.facade.types import DIRECT_ENGINE_BY_SOURCE_TYPE+from products.warehouse_sources.backend.facade.types import DIRECT_ENGINE_BY_SOURCE_TYPE, ExternalDataSourceAccessMethodif TYPE_CHECKING:from posthog.models import Team, User@@ -132,7 +132,7 @@ def _matching_table_names(pure_direct_ids = {source_idfor source_id, source in sources_by_id.items()- if source.access_method == ExternalDataSource.AccessMethod.DIRECT+ if source.access_method == ExternalDataSourceAccessMethod.DIRECT}dual_mode_ids = set(sources_by_id) - pure_direct_idsdiff --git a/posthog/api/sharing.py b/posthog/api/sharing.pyindex 50e08c2b54aa..af57dadc12d1 100644--- a/posthog/api/sharing.py+++ b/posthog/api/sharing.py@@ -8,6 +8,7 @@ from django.core.exceptions import ImproperlyConfiguredfrom django.core.serializers.json import DjangoJSONEncoderfrom django.db.models import Model, Qfrom django.shortcuts import render+from django.utils.functional import SimpleLazyObjectfrom django.utils.timezone import nowfrom django.views.decorators.clickjacking import xframe_options_exempt@@ -82,7 +83,8 @@ from products.feature_flags.backend.persisted_flags import get_dynamic_persistedfrom products.notebooks.backend.facade.content import extract_inline_query_nodes, filter_notebook_content_for_sharingfrom products.notebooks.backend.models import Notebookfrom products.notebooks.backend.presentation.views.notebook import NotebookSerializer-from products.product_analytics.backend.facade.models import Insight, InsightVariable, InsightViewed+from products.product_analytics.backend.facade.api import insight_variables_for_team, record_insight_view+from products.product_analytics.backend.facade.models import Insightfrom products.product_analytics.backend.presentation.insight import InsightSerializerlogger = structlog.get_logger(__name__)@@ -445,7 +447,9 @@ class SharingConfigurationViewSet(except Notebook.DoesNotExist:raise NotFound("Notebook not found.")- context["insight_variables"] = InsightVariable.objects.filter(team=self.team)+ # Deferred: every insight and dashboard response carries this, but only payloads that+ # hold variables read it, so resolving it eagerly costs a query on every list request.+ context["insight_variables"] = SimpleLazyObject(lambda: insight_variables_for_team(self.team.pk))return context@@ -1023,13 +1027,13 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSecast("User | None", SharedLinkUser(resource)) if isinstance(resource, SharingConfiguration) else None)- context = {+ context: dict[str, Any] = {"view": self,"request": request,"user_permissions": UserPermissions(cast(User, request.user), resource.team),"is_shared": True,"get_team": lambda: resource.team,- "insight_variables": InsightVariable.objects.filter(team=resource.team).all(),+ "insight_variables": SimpleLazyObject(lambda: insight_variables_for_team(resource.team.pk)),"export_cache_keys": export_cache_keys,"shared_link_user": shared_link_user,# exported_data is embedded into the page with stdlib json.dumps, which cannot@@ -1146,9 +1150,7 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSecontext["dashboard"] = resource.dashboardasset_title = resource.insight.name or resource.insight.derived_nameasset_description = resource.insight.description or ""- InsightViewed.objects.update_or_create(- insight=resource.insight, team=None, user=None, defaults={"last_viewed_at": now()}- )+ record_insight_view(insight_id=resource.insight.pk)# Add hideExtraDetails to context so that PII related information is not returned to the clientinsight_context = {**context, "hide_extra_details": state.get("hideExtraDetails", False)}@@ -1413,9 +1415,7 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSeinsights_by_short_id = {item["short_id"]: item for item in serialized_insights if item.get("short_id")}# Track the view exactly like the dashboard / single-insight branches do.for insight in referenced_insights:- InsightViewed.objects.update_or_create(- insight=insight, team=None, user=None, defaults={"last_viewed_at": now()}- )+ record_insight_view(insight_id=insight.pk)exported_data.update({"insights": insights_by_short_id})# Pre-compute every inline (non-saved-insight) `ph-query` node so the shared viewer# can seed `cachedResults` on them too — same reason as above (no `/query/` POST).diff --git a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambrindex 6ac4e7b2ca1c..65c00a119c22 100644--- a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr+++ b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr@@ -264,6 +264,22 @@'''# ---# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.14+ '''+ SELECT "posthog_insightviewed"."id",+ "posthog_insightviewed"."team_id",+ "posthog_insightviewed"."user_id",+ "posthog_insightviewed"."insight_id",+ "posthog_insightviewed"."last_viewed_at"+ FROM "posthog_insightviewed"+ WHERE ("posthog_insightviewed"."insight_id" = 99999+ AND "posthog_insightviewed"."team_id" = 99999+ AND "posthog_insightviewed"."user_id" = 99999)+ LIMIT 21+ FOR+ UPDATE+ '''+# ---+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.15'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -290,7 +306,7 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.15+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.16'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -317,26 +333,27 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.16+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.17'''- SELECT "posthog_insightvariable"."created_by_id",- "posthog_insightvariable"."created_at",- "posthog_insightvariable"."updated_at",- "posthog_insightvariable"."id",- "posthog_insightvariable"."team_id",+ SELECT "posthog_insightvariable"."id","posthog_insightvariable"."name","posthog_insightvariable"."code_name","posthog_insightvariable"."type","posthog_insightvariable"."default_value",- "posthog_insightvariable"."values",- "posthog_insightvariable"."is_multi",- "posthog_insightvariable"."values_query",- "posthog_insightvariable"."values_query_connection_id"+ "posthog_insightvariable"."is_multi"FROM "posthog_insightvariable"- WHERE "posthog_insightvariable"."team_id" = 99999+ INNER JOIN "posthog_team" ON ("posthog_insightvariable"."team_id" = "posthog_team"."id")+ WHERE ("posthog_insightvariable"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_insightvariable"."team_id" = 99999))+ ORDER BY "posthog_insightvariable"."name" ASC'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.17+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.18'''SELECT "posthog_dashboardtile"."dashboard_id" AS "dashboard_id"FROM "posthog_dashboardtile"@@ -347,7 +364,7 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.18+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.19'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -380,14 +397,6 @@5 /* ... */))'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.19- '''- SELECT "posthog_tag"."name" AS "tag__name"- FROM "posthog_taggeditem"- INNER JOIN "posthog_tag" ON ("posthog_taggeditem"."tag_id" = "posthog_tag"."id")- WHERE "posthog_taggeditem"."insight_id" = 99999- '''-# ---# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.2'''SELECT "posthog_team"."id",@@ -530,6 +539,14 @@'''# ---# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.20+ '''+ SELECT "posthog_tag"."name" AS "tag__name"+ FROM "posthog_taggeditem"+ INNER JOIN "posthog_tag" ON ("posthog_taggeditem"."tag_id" = "posthog_tag"."id")+ WHERE "posthog_taggeditem"."insight_id" = 99999+ '''+# ---+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.21'''SELECT "posthog_user"."id","posthog_user"."password",@@ -575,7 +592,7 @@AND "posthog_user"."id" = 99999)'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.21+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.22'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -620,7 +637,7 @@LIMIT 21'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.22+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.23'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -761,7 +778,7 @@LIMIT 21'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.23+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.24'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -815,7 +832,7 @@LIMIT 21'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.24+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.25'''SELECT "ee_accesscontrol"."id","ee_accesscontrol"."team_id",@@ -840,7 +857,7 @@AND "ee_accesscontrol"."team_id" = 99999))'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.25+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.26'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -892,7 +909,7 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.26+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.27'''SELECT "ee_accesscontrol"."team_id" AS "team_id","ee_accesscontrol"."resource_id" AS "resource_id",@@ -905,7 +922,7 @@AND "posthog_team"."organization_id" IN ('00000000-0000-0000-0000-000000000000'::uuid))'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.27+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.28'''SELECT "ee_role"."organization_id" AS "role__organization_id","ee_rolemembership"."role_id" AS "role_id"@@ -914,7 +931,7 @@WHERE "ee_rolemembership"."user_id" = 99999'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.28+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.29'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -1017,29 +1034,6 @@LIMIT 21'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.29- '''- SELECT "posthog_sharingconfiguration"."id",- "posthog_sharingconfiguration"."team_id",- "posthog_sharingconfiguration"."dashboard_id",- "posthog_sharingconfiguration"."insight_id",- "posthog_sharingconfiguration"."recording_id",- "posthog_sharingconfiguration"."notebook_id",- "posthog_sharingconfiguration"."interviewee_context_id",- "posthog_sharingconfiguration"."created_at",- "posthog_sharingconfiguration"."enabled",- "posthog_sharingconfiguration"."access_token",- "posthog_sharingconfiguration"."expires_at",- "posthog_sharingconfiguration"."settings",- "posthog_sharingconfiguration"."password_required"- FROM "posthog_sharingconfiguration"- WHERE "posthog_sharingconfiguration"."dashboard_id" IN (1,- 2,- 3,- 4,- 5 /* ... */)- '''-# ---# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.3'''SELECT "posthog_organizationmembership"."id",@@ -1095,6 +1089,29 @@'''# ---# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.30+ '''+ SELECT "posthog_sharingconfiguration"."id",+ "posthog_sharingconfiguration"."team_id",+ "posthog_sharingconfiguration"."dashboard_id",+ "posthog_sharingconfiguration"."insight_id",+ "posthog_sharingconfiguration"."recording_id",+ "posthog_sharingconfiguration"."notebook_id",+ "posthog_sharingconfiguration"."interviewee_context_id",+ "posthog_sharingconfiguration"."created_at",+ "posthog_sharingconfiguration"."enabled",+ "posthog_sharingconfiguration"."access_token",+ "posthog_sharingconfiguration"."expires_at",+ "posthog_sharingconfiguration"."settings",+ "posthog_sharingconfiguration"."password_required"+ FROM "posthog_sharingconfiguration"+ WHERE "posthog_sharingconfiguration"."dashboard_id" IN (1,+ 2,+ 3,+ 4,+ 5 /* ... */)+ '''+# ---+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.31'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -1457,7 +1474,7 @@ORDER BY "posthog_dashboarditem"."order" ASC'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.31+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.32'''SELECT ("posthog_dashboardtile"."insight_id") AS "_prefetch_related_val_insight_id","posthog_dashboard"."id",@@ -1499,7 +1516,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.32+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.33'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -1530,7 +1547,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.33+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.34'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -1559,7 +1576,7 @@2)/* ... */)'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.34+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.35'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",@@ -1586,7 +1603,7 @@5 /* ... */)'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.35+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.36'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -1688,7 +1705,7 @@LIMIT 21'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.36+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.37'''SELECT "posthog_filesystem"."team_id","posthog_filesystem"."id",@@ -1713,7 +1730,7 @@AND "posthog_filesystem"."shortcut" IS NOT NULL))'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.37+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.38'''SELECT "posthog_filesystemshortcut"."id","posthog_filesystemshortcut"."team_id",@@ -1736,26 +1753,52 @@AND "posthog_filesystemshortcut"."href" IS NOT NULL))'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.38+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.39'''- SELECT "posthog_insightvariable"."created_by_id",- "posthog_insightvariable"."created_at",- "posthog_insightvariable"."updated_at",- "posthog_insightvariable"."id",- "posthog_insightvariable"."team_id",+ SELECT "posthog_insightvariable"."id","posthog_insightvariable"."name","posthog_insightvariable"."code_name","posthog_insightvariable"."type","posthog_insightvariable"."default_value",- "posthog_insightvariable"."values",- "posthog_insightvariable"."is_multi",- "posthog_insightvariable"."values_query",- "posthog_insightvariable"."values_query_connection_id"+ "posthog_insightvariable"."is_multi"FROM "posthog_insightvariable"- WHERE "posthog_insightvariable"."team_id" = 99999+ INNER JOIN "posthog_team" ON ("posthog_insightvariable"."team_id" = "posthog_team"."id")+ WHERE ("posthog_insightvariable"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_insightvariable"."team_id" = 99999))+ ORDER BY "posthog_insightvariable"."name" ASC'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.39+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.4+ '''+ SELECT "ee_accesscontrol"."id",+ "ee_accesscontrol"."team_id",+ "ee_accesscontrol"."access_level",+ "ee_accesscontrol"."resource",+ "ee_accesscontrol"."resource_id",+ "ee_accesscontrol"."organization_member_id",+ "ee_accesscontrol"."role_id",+ "ee_accesscontrol"."created_by_id",+ "ee_accesscontrol"."created_at",+ "ee_accesscontrol"."updated_at",+ "posthog_team"."organization_id" AS "_team_organization_id"+ FROM "ee_accesscontrol"+ INNER JOIN "posthog_team" ON ("ee_accesscontrol"."team_id" = "posthog_team"."id")+ LEFT OUTER JOIN "posthog_organizationmembership" ON ("ee_accesscontrol"."organization_member_id" = "posthog_organizationmembership"."id")+ WHERE (("ee_accesscontrol"."organization_member_id" IS NULL+ AND "ee_accesscontrol"."role_id" IS NULL+ AND "ee_accesscontrol"."team_id" = 99999)+ OR ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid+ AND "posthog_organizationmembership"."user_id" = 99999+ AND "ee_accesscontrol"."role_id" IS NULL+ AND "ee_accesscontrol"."team_id" = 99999))+ '''+# ---+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.40'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -2119,32 +2162,7 @@ORDER BY "posthog_dashboarditem"."order" ASC'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.4- '''- SELECT "ee_accesscontrol"."id",- "ee_accesscontrol"."team_id",- "ee_accesscontrol"."access_level",- "ee_accesscontrol"."resource",- "ee_accesscontrol"."resource_id",- "ee_accesscontrol"."organization_member_id",- "ee_accesscontrol"."role_id",- "ee_accesscontrol"."created_by_id",- "ee_accesscontrol"."created_at",- "ee_accesscontrol"."updated_at",- "posthog_team"."organization_id" AS "_team_organization_id"- FROM "ee_accesscontrol"- INNER JOIN "posthog_team" ON ("ee_accesscontrol"."team_id" = "posthog_team"."id")- LEFT OUTER JOIN "posthog_organizationmembership" ON ("ee_accesscontrol"."organization_member_id" = "posthog_organizationmembership"."id")- WHERE (("ee_accesscontrol"."organization_member_id" IS NULL- AND "ee_accesscontrol"."role_id" IS NULL- AND "ee_accesscontrol"."team_id" = 99999)- OR ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid- AND "posthog_organizationmembership"."user_id" = 99999- AND "ee_accesscontrol"."role_id" IS NULL- AND "ee_accesscontrol"."team_id" = 99999))- '''-# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.40+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.41'''SELECT ("posthog_dashboardtile"."insight_id") AS "_prefetch_related_val_insight_id","posthog_dashboard"."id",@@ -2186,7 +2204,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.41+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.42'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -2217,7 +2235,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.42+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.43'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -2246,7 +2264,7 @@2)/* ... */)'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.43+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.44'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",@@ -2273,7 +2291,7 @@5 /* ... */)'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.44+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.45'''SELECT "posthog_alertconfiguration"."created_by_id","posthog_alertconfiguration"."created_at",@@ -2354,7 +2372,7 @@5 /* ... */)'''# ----# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.45+# name: TestDashboard.test_adding_insights_is_not_nplus1_for_gets.46'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -2713,6 +2731,22 @@'''# ---# name: TestDashboard.test_listing_dashboards_is_not_nplus1.12+ '''+ SELECT "posthog_insightviewed"."id",+ "posthog_insightviewed"."team_id",+ "posthog_insightviewed"."user_id",+ "posthog_insightviewed"."insight_id",+ "posthog_insightviewed"."last_viewed_at"+ FROM "posthog_insightviewed"+ WHERE ("posthog_insightviewed"."insight_id" = 99999+ AND "posthog_insightviewed"."team_id" = 99999+ AND "posthog_insightviewed"."user_id" = 99999)+ LIMIT 21+ FOR+ UPDATE+ '''+# ---+# name: TestDashboard.test_listing_dashboards_is_not_nplus1.13'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -2757,7 +2791,7 @@LIMIT 21'''# ----# name: TestDashboard.test_listing_dashboards_is_not_nplus1.13+# name: TestDashboard.test_listing_dashboards_is_not_nplus1.14'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -2859,7 +2893,7 @@LIMIT 21'''# ----# name: TestDashboard.test_listing_dashboards_is_not_nplus1.14+# name: TestDashboard.test_listing_dashboards_is_not_nplus1.15'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -2886,7 +2920,7 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestDashboard.test_listing_dashboards_is_not_nplus1.15+# name: TestDashboard.test_listing_dashboards_is_not_nplus1.16'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -2913,26 +2947,27 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestDashboard.test_listing_dashboards_is_not_nplus1.16+# name: TestDashboard.test_listing_dashboards_is_not_nplus1.17'''- SELECT "posthog_insightvariable"."created_by_id",- "posthog_insightvariable"."created_at",- "posthog_insightvariable"."updated_at",- "posthog_insightvariable"."id",- "posthog_insightvariable"."team_id",+ SELECT "posthog_insightvariable"."id","posthog_insightvariable"."name","posthog_insightvariable"."code_name","posthog_insightvariable"."type","posthog_insightvariable"."default_value",- "posthog_insightvariable"."values",- "posthog_insightvariable"."is_multi",- "posthog_insightvariable"."values_query",- "posthog_insightvariable"."values_query_connection_id"+ "posthog_insightvariable"."is_multi"FROM "posthog_insightvariable"- WHERE "posthog_insightvariable"."team_id" = 99999+ INNER JOIN "posthog_team" ON ("posthog_insightvariable"."team_id" = "posthog_team"."id")+ WHERE ("posthog_insightvariable"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_insightvariable"."team_id" = 99999))+ ORDER BY "posthog_insightvariable"."name" ASC'''# ----# name: TestDashboard.test_listing_dashboards_is_not_nplus1.17+# name: TestDashboard.test_listing_dashboards_is_not_nplus1.18'''SELECT "posthog_dashboardtile"."dashboard_id" AS "dashboard_id"FROM "posthog_dashboardtile"@@ -2943,7 +2978,7 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestDashboard.test_listing_dashboards_is_not_nplus1.18+# name: TestDashboard.test_listing_dashboards_is_not_nplus1.19'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -2976,14 +3011,6 @@5 /* ... */))'''# ----# name: TestDashboard.test_listing_dashboards_is_not_nplus1.19- '''- SELECT "posthog_tag"."name" AS "tag__name"- FROM "posthog_taggeditem"- INNER JOIN "posthog_tag" ON ("posthog_taggeditem"."tag_id" = "posthog_tag"."id")- WHERE "posthog_taggeditem"."insight_id" = 99999- '''-# ---# name: TestDashboard.test_listing_dashboards_is_not_nplus1.2'''SELECT "posthog_team"."id",@@ -3126,6 +3153,14 @@'''# ---# name: TestDashboard.test_listing_dashboards_is_not_nplus1.20+ '''+ SELECT "posthog_tag"."name" AS "tag__name"+ FROM "posthog_taggeditem"+ INNER JOIN "posthog_tag" ON ("posthog_taggeditem"."tag_id" = "posthog_tag"."id")+ WHERE "posthog_taggeditem"."insight_id" = 99999+ '''+# ---+# name: TestDashboard.test_listing_dashboards_is_not_nplus1.21'''SELECT "posthog_user"."id","posthog_user"."password",@@ -3171,7 +3206,7 @@AND "posthog_user"."id" = 99999)'''# ----# name: TestDashboard.test_listing_dashboards_is_not_nplus1.21+# name: TestDashboard.test_listing_dashboards_is_not_nplus1.22'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -3216,7 +3251,7 @@LIMIT 21'''# ----# name: TestDashboard.test_listing_dashboards_is_not_nplus1.22+# name: TestDashboard.test_listing_dashboards_is_not_nplus1.23'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -3357,7 +3392,7 @@LIMIT 21'''# ----# name: TestDashboard.test_listing_dashboards_is_not_nplus1.23+# name: TestDashboard.test_listing_dashboards_is_not_nplus1.24'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -3411,7 +3446,7 @@LIMIT 21'''# ----# name: TestDashboard.test_listing_dashboards_is_not_nplus1.24+# name: TestDashboard.test_listing_dashboards_is_not_nplus1.25'''SELECT "ee_accesscontrol"."id","ee_accesscontrol"."team_id",@@ -3436,7 +3471,7 @@AND "ee_accesscontrol"."team_id" = 99999))'''# ----# name: TestDashboard.test_listing_dashboards_is_not_nplus1.25+# name: TestDashboard.test_listing_dashboards_is_not_nplus1.26'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -3488,7 +3523,7 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestDashboard.test_listing_dashboards_is_not_nplus1.26+# name: TestDashboard.test_listing_dashboards_is_not_nplus1.27'''SELECT COUNT(*) AS "__count"FROM "posthog_dashboard"@@ -3502,7 +3537,7 @@AND NOT ("posthog_dashboard"."creation_mode" = 'unlisted'))'''# ----# name: TestDashboard.test_listing_dashboards_is_not_nplus1.27+# name: TestDashboard.test_listing_dashboards_is_not_nplus1.28'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -3607,7 +3642,7 @@LIMIT 300'''# ----# name: TestDashboard.test_listing_dashboards_is_not_nplus1.28+# name: TestDashboard.test_listing_dashboards_is_not_nplus1.29'''SELECT "posthog_sharingconfiguration"."id","posthog_sharingconfiguration"."team_id",@@ -3630,33 +3665,6 @@5 /* ... */)'''# ----# name: TestDashboard.test_listing_dashboards_is_not_nplus1.29- '''- SELECT "posthog_taggeditem"."id",- "posthog_taggeditem"."tag_id",- "posthog_taggeditem"."dashboard_id",- "posthog_taggeditem"."insight_id",- "posthog_taggeditem"."event_definition_id",- "posthog_taggeditem"."property_definition_id",- "posthog_taggeditem"."action_id",- "posthog_taggeditem"."feature_flag_id",- "posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id",- "posthog_taggeditem"."account_id",- "posthog_taggeditem"."endpoint_id",- "posthog_taggeditem"."replay_scanner_id",- "posthog_tag"."id",- "posthog_tag"."name",- "posthog_tag"."team_id"- FROM "posthog_taggeditem"- INNER JOIN "posthog_tag" ON ("posthog_taggeditem"."tag_id" = "posthog_tag"."id")- WHERE "posthog_taggeditem"."dashboard_id" IN (1,- 2,- 3,- 4,- 5 /* ... */)- '''-# ---# name: TestDashboard.test_listing_dashboards_is_not_nplus1.3'''SELECT "posthog_organizationmembership"."id",@@ -3711,17 +3719,44 @@LIMIT 21'''# ----# name: TestDashboard.test_listing_dashboards_is_not_nplus1.4+# name: TestDashboard.test_listing_dashboards_is_not_nplus1.30'''- SELECT "ee_accesscontrol"."id",- "ee_accesscontrol"."team_id",- "ee_accesscontrol"."access_level",- "ee_accesscontrol"."resource",- "ee_accesscontrol"."resource_id",- "ee_accesscontrol"."organization_member_id",- "ee_accesscontrol"."role_id",- "ee_accesscontrol"."created_by_id",- "ee_accesscontrol"."created_at",+ SELECT "posthog_taggeditem"."id",+ "posthog_taggeditem"."tag_id",+ "posthog_taggeditem"."dashboard_id",+ "posthog_taggeditem"."insight_id",+ "posthog_taggeditem"."event_definition_id",+ "posthog_taggeditem"."property_definition_id",+ "posthog_taggeditem"."action_id",+ "posthog_taggeditem"."feature_flag_id",+ "posthog_taggeditem"."experiment_saved_metric_id",+ "posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id",+ "posthog_taggeditem"."endpoint_id",+ "posthog_taggeditem"."replay_scanner_id",+ "posthog_tag"."id",+ "posthog_tag"."name",+ "posthog_tag"."team_id"+ FROM "posthog_taggeditem"+ INNER JOIN "posthog_tag" ON ("posthog_taggeditem"."tag_id" = "posthog_tag"."id")+ WHERE "posthog_taggeditem"."dashboard_id" IN (1,+ 2,+ 3,+ 4,+ 5 /* ... */)+ '''+# ---+# name: TestDashboard.test_listing_dashboards_is_not_nplus1.4+ '''+ SELECT "ee_accesscontrol"."id",+ "ee_accesscontrol"."team_id",+ "ee_accesscontrol"."access_level",+ "ee_accesscontrol"."resource",+ "ee_accesscontrol"."resource_id",+ "ee_accesscontrol"."organization_member_id",+ "ee_accesscontrol"."role_id",+ "ee_accesscontrol"."created_by_id",+ "ee_accesscontrol"."created_at","ee_accesscontrol"."updated_at","posthog_team"."organization_id" AS "_team_organization_id"FROM "ee_accesscontrol"@@ -3984,6 +4019,141 @@'''# ---# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.100+ '''+ SELECT "posthog_dashboard"."id",+ "posthog_dashboard"."name",+ "posthog_dashboard"."description",+ "posthog_dashboard"."team_id",+ "posthog_dashboard"."pinned",+ "posthog_dashboard"."created_at",+ "posthog_dashboard"."created_by_id",+ "posthog_dashboard"."deleted",+ "posthog_dashboard"."last_accessed_at",+ "posthog_dashboard"."last_refresh",+ "posthog_dashboard"."filters",+ "posthog_dashboard"."variables",+ "posthog_dashboard"."breakdown_colors",+ "posthog_dashboard"."data_color_theme_id",+ "posthog_dashboard"."creation_mode",+ "posthog_dashboard"."restriction_level",+ "posthog_dashboard"."quick_filter_ids",+ "posthog_dashboard"."customization",+ "posthog_dashboard"."deprecated_tags",+ "posthog_dashboard"."tags",+ "posthog_dashboard"."share_token",+ "posthog_dashboard"."is_shared"+ FROM "posthog_dashboard"+ WHERE (NOT ("posthog_dashboard"."deleted")+ AND "posthog_dashboard"."id" IN (1,+ 2,+ 3,+ 4,+ 5 /* ... */))+ '''+# ---+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.101+ '''+ SELECT "posthog_team"."id",+ "posthog_team"."uuid",+ "posthog_team"."organization_id",+ "posthog_team"."parent_team_id",+ "posthog_team"."project_id",+ "posthog_team"."api_token",+ "posthog_team"."app_urls",+ "posthog_team"."name",+ "posthog_team"."slack_incoming_webhook",+ "posthog_team"."created_at",+ "posthog_team"."updated_at",+ "posthog_team"."anonymize_ips",+ "posthog_team"."completed_snippet_onboarding",+ "posthog_team"."has_completed_onboarding_for",+ "posthog_team"."onboarding_tasks",+ "posthog_team"."ingested_event",+ "posthog_team"."ingested_production_event",+ "posthog_team"."ingested_production_event_last_checked_at",+ "posthog_team"."person_processing_opt_out",+ "posthog_team"."secret_api_token",+ "posthog_team"."secret_api_token_backup",+ "posthog_team"."session_recording_opt_in",+ "posthog_team"."session_recording_sample_rate",+ "posthog_team"."session_recording_minimum_duration_milliseconds",+ "posthog_team"."session_recording_linked_flag",+ "posthog_team"."session_recording_network_payload_capture_config",+ "posthog_team"."session_recording_masking_config",+ "posthog_team"."session_recording_url_trigger_config",+ "posthog_team"."session_recording_url_blocklist_config",+ "posthog_team"."session_recording_event_trigger_config",+ "posthog_team"."session_recording_trigger_match_type_config",+ "posthog_team"."session_recording_trigger_groups",+ "posthog_team"."session_replay_config",+ "posthog_team"."session_recording_retention_period",+ "posthog_team"."event_retention_months",+ "posthog_team"."conversations_enabled",+ "posthog_team"."conversations_settings",+ "posthog_team"."proactive_tasks_enabled",+ "posthog_team"."survey_config",+ "posthog_team"."surveys_opt_in",+ "posthog_team"."product_tours_opt_in",+ "posthog_team"."capture_console_log_opt_in",+ "posthog_team"."capture_performance_opt_in",+ "posthog_team"."capture_dead_clicks",+ "posthog_team"."autocapture_opt_out",+ "posthog_team"."autocapture_web_vitals_opt_in",+ "posthog_team"."autocapture_web_vitals_allowed_metrics",+ "posthog_team"."autocapture_exceptions_opt_in",+ "posthog_team"."autocapture_exceptions_errors_to_ignore",+ "posthog_team"."logs_settings",+ "posthog_team"."llm_gateway_enabled_at",+ "posthog_team"."llm_gateway_revoked_at",+ "posthog_team"."llm_gateway_overspend_allowance_usd",+ "posthog_team"."heatmaps_opt_in",+ "posthog_team"."receive_org_level_activity_logs",+ "posthog_team"."web_analytics_pre_aggregated_tables_enabled",+ "posthog_team"."web_analytics_pre_aggregated_tables_version",+ "posthog_team"."flags_persistence_default",+ "posthog_team"."feature_flag_confirmation_enabled",+ "posthog_team"."feature_flag_confirmation_message",+ "posthog_team"."default_evaluation_environments_enabled",+ "posthog_team"."require_evaluation_environment_tags",+ "posthog_team"."default_evaluation_contexts_enabled",+ "posthog_team"."require_evaluation_contexts",+ "posthog_team"."session_recording_version",+ "posthog_team"."signup_token",+ "posthog_team"."is_demo",+ "posthog_team"."access_control",+ "posthog_team"."week_start_day",+ "posthog_team"."inject_web_apps",+ "posthog_team"."test_account_filters",+ "posthog_team"."test_account_filters_default_checked",+ "posthog_team"."path_cleaning_filters",+ "posthog_team"."timezone",+ "posthog_team"."data_attributes",+ "posthog_team"."person_display_name_properties",+ "posthog_team"."live_events_columns",+ "posthog_team"."recording_domains",+ "posthog_team"."human_friendly_comparison_periods",+ "posthog_team"."cookieless_server_hash_mode",+ "posthog_team"."primary_dashboard_id",+ "posthog_team"."default_data_theme",+ "posthog_team"."extra_settings",+ "posthog_team"."modifiers",+ "posthog_team"."correlation_config",+ "posthog_team"."session_recording_retention_period_days",+ "posthog_team"."external_data_workspace_id",+ "posthog_team"."external_data_workspace_last_synced_at",+ "posthog_team"."api_query_rate_limit",+ "posthog_team"."drop_events_older_than",+ "posthog_team"."base_currency",+ "posthog_team"."experiment_recalculation_time",+ "posthog_team"."default_experiment_confidence_level",+ "posthog_team"."default_experiment_stats_method",+ "posthog_team"."business_model"+ FROM "posthog_team"+ WHERE "posthog_team"."id" = 99999+ LIMIT 21+ '''+# ---+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.102'''SELECT "posthog_filesystem"."team_id","posthog_filesystem"."id",@@ -4008,7 +4178,23 @@AND "posthog_filesystem"."shortcut" IS NOT NULL))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.101+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.103+ '''+ SELECT "posthog_insightviewed"."id",+ "posthog_insightviewed"."team_id",+ "posthog_insightviewed"."user_id",+ "posthog_insightviewed"."insight_id",+ "posthog_insightviewed"."last_viewed_at"+ FROM "posthog_insightviewed"+ WHERE ("posthog_insightviewed"."insight_id" = 99999+ AND "posthog_insightviewed"."team_id" = 99999+ AND "posthog_insightviewed"."user_id" = 99999)+ LIMIT 21+ FOR+ UPDATE+ '''+# ---+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.104'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -4053,7 +4239,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.102+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.105'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -4155,7 +4341,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.103+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.106'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -4182,7 +4368,7 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.104+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.107'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -4209,26 +4395,27 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.105+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.108'''- SELECT "posthog_insightvariable"."created_by_id",- "posthog_insightvariable"."created_at",- "posthog_insightvariable"."updated_at",- "posthog_insightvariable"."id",- "posthog_insightvariable"."team_id",+ SELECT "posthog_insightvariable"."id","posthog_insightvariable"."name","posthog_insightvariable"."code_name","posthog_insightvariable"."type","posthog_insightvariable"."default_value",- "posthog_insightvariable"."values",- "posthog_insightvariable"."is_multi",- "posthog_insightvariable"."values_query",- "posthog_insightvariable"."values_query_connection_id"+ "posthog_insightvariable"."is_multi"FROM "posthog_insightvariable"- WHERE "posthog_insightvariable"."team_id" = 99999+ INNER JOIN "posthog_team" ON ("posthog_insightvariable"."team_id" = "posthog_team"."id")+ WHERE ("posthog_insightvariable"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_insightvariable"."team_id" = 99999))+ ORDER BY "posthog_insightvariable"."name" ASC'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.106+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.109'''SELECT "posthog_dashboardtile"."dashboard_id" AS "dashboard_id"FROM "posthog_dashboardtile"@@ -4239,7 +4426,19 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.107+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.11+ '''+ SELECT COUNT(*) AS "__count"+ FROM "posthog_dashboardtile"+ INNER JOIN "posthog_dashboard" ON ("posthog_dashboardtile"."dashboard_id" = "posthog_dashboard"."id")+ WHERE (NOT ("posthog_dashboardtile"."deleted"+ AND "posthog_dashboardtile"."deleted" IS NOT NULL)+ AND NOT ("posthog_dashboard"."deleted")+ AND "posthog_dashboardtile"."dashboard_id" = 99999+ AND NOT ("posthog_dashboardtile"."insight_id" IS NULL))+ '''+# ---+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.110'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -4272,7 +4471,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.108+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.111'''SELECT "posthog_tag"."name" AS "tag__name"FROM "posthog_taggeditem"@@ -4280,7 +4479,7 @@WHERE "posthog_taggeditem"."insight_id" = 99999'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.109+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.112'''SELECT "posthog_user"."id","posthog_user"."password",@@ -4326,19 +4525,7 @@AND "posthog_user"."id" = 99999)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.11- '''- SELECT COUNT(*) AS "__count"- FROM "posthog_dashboardtile"- INNER JOIN "posthog_dashboard" ON ("posthog_dashboardtile"."dashboard_id" = "posthog_dashboard"."id")- WHERE (NOT ("posthog_dashboardtile"."deleted"- AND "posthog_dashboardtile"."deleted" IS NOT NULL)- AND NOT ("posthog_dashboard"."deleted")- AND "posthog_dashboardtile"."dashboard_id" = 99999- AND NOT ("posthog_dashboardtile"."insight_id" IS NULL))- '''-# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.110+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.113'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -4383,7 +4570,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.111+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.114'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -4524,7 +4711,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.112+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.115'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -4578,7 +4765,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.113+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.116'''SELECT "ee_accesscontrol"."id","ee_accesscontrol"."team_id",@@ -4603,7 +4790,7 @@AND "ee_accesscontrol"."team_id" = 99999))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.114+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.117'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -4655,7 +4842,7 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.115+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.118'''SELECT "ee_accesscontrol"."team_id" AS "team_id","ee_accesscontrol"."resource_id" AS "resource_id",@@ -4668,7 +4855,7 @@AND "posthog_team"."organization_id" IN ('00000000-0000-0000-0000-000000000000'::uuid))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.116+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.119'''SELECT "ee_role"."organization_id" AS "role__organization_id","ee_rolemembership"."role_id" AS "role_id"@@ -4677,7 +4864,26 @@WHERE "ee_rolemembership"."user_id" = 99999'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.117+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.12+ '''+ SELECT "posthog_sharingconfiguration"."id",+ "posthog_sharingconfiguration"."team_id",+ "posthog_sharingconfiguration"."dashboard_id",+ "posthog_sharingconfiguration"."insight_id",+ "posthog_sharingconfiguration"."recording_id",+ "posthog_sharingconfiguration"."notebook_id",+ "posthog_sharingconfiguration"."interviewee_context_id",+ "posthog_sharingconfiguration"."created_at",+ "posthog_sharingconfiguration"."enabled",+ "posthog_sharingconfiguration"."access_token",+ "posthog_sharingconfiguration"."expires_at",+ "posthog_sharingconfiguration"."settings",+ "posthog_sharingconfiguration"."password_required"+ FROM "posthog_sharingconfiguration"+ WHERE "posthog_sharingconfiguration"."dashboard_id" = 99999+ '''+# ---+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.120'''SELECT "posthog_dashboard"."id" AS "id"FROM "posthog_dashboard"@@ -4697,7 +4903,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.118+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.121'''SELECT "posthog_dashboard"."id" AS "id","posthog_dashboard"."name" AS "name"@@ -4710,7 +4916,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.119+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.122'''SELECT COUNT(*) AS "__count"FROM "posthog_dashboardtile"@@ -4723,26 +4929,7 @@AND "posthog_dashboardtile"."deleted" IS NOT NULL))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.12- '''- SELECT "posthog_sharingconfiguration"."id",- "posthog_sharingconfiguration"."team_id",- "posthog_sharingconfiguration"."dashboard_id",- "posthog_sharingconfiguration"."insight_id",- "posthog_sharingconfiguration"."recording_id",- "posthog_sharingconfiguration"."notebook_id",- "posthog_sharingconfiguration"."interviewee_context_id",- "posthog_sharingconfiguration"."created_at",- "posthog_sharingconfiguration"."enabled",- "posthog_sharingconfiguration"."access_token",- "posthog_sharingconfiguration"."expires_at",- "posthog_sharingconfiguration"."settings",- "posthog_sharingconfiguration"."password_required"- FROM "posthog_sharingconfiguration"- WHERE "posthog_sharingconfiguration"."dashboard_id" = 99999- '''-# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.120+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.123'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -4775,7 +4962,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.121+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.124'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -4877,7 +5064,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.122+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.125'''SELECT "posthog_filesystem"."team_id","posthog_filesystem"."id",@@ -4902,7 +5089,23 @@AND "posthog_filesystem"."shortcut" IS NOT NULL))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.123+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.126+ '''+ SELECT "posthog_insightviewed"."id",+ "posthog_insightviewed"."team_id",+ "posthog_insightviewed"."user_id",+ "posthog_insightviewed"."insight_id",+ "posthog_insightviewed"."last_viewed_at"+ FROM "posthog_insightviewed"+ WHERE ("posthog_insightviewed"."insight_id" = 99999+ AND "posthog_insightviewed"."team_id" = 99999+ AND "posthog_insightviewed"."user_id" = 99999)+ LIMIT 21+ FOR+ UPDATE+ '''+# ---+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.127'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -4947,7 +5150,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.124+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.128'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -5049,7 +5252,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.125+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.129'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -5076,7 +5279,14 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.126+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.13+ '''+ SELECT COUNT(*) AS "__count"+ FROM "posthog_taggeditem"+ WHERE "posthog_taggeditem"."dashboard_id" = 99999+ '''+# ---+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.130'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -5103,26 +5313,27 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.127+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.131'''- SELECT "posthog_insightvariable"."created_by_id",- "posthog_insightvariable"."created_at",- "posthog_insightvariable"."updated_at",- "posthog_insightvariable"."id",- "posthog_insightvariable"."team_id",+ SELECT "posthog_insightvariable"."id","posthog_insightvariable"."name","posthog_insightvariable"."code_name","posthog_insightvariable"."type","posthog_insightvariable"."default_value",- "posthog_insightvariable"."values",- "posthog_insightvariable"."is_multi",- "posthog_insightvariable"."values_query",- "posthog_insightvariable"."values_query_connection_id"+ "posthog_insightvariable"."is_multi"FROM "posthog_insightvariable"- WHERE "posthog_insightvariable"."team_id" = 99999+ INNER JOIN "posthog_team" ON ("posthog_insightvariable"."team_id" = "posthog_team"."id")+ WHERE ("posthog_insightvariable"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_insightvariable"."team_id" = 99999))+ ORDER BY "posthog_insightvariable"."name" ASC'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.128+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.132'''SELECT "posthog_dashboardtile"."dashboard_id" AS "dashboard_id"FROM "posthog_dashboardtile"@@ -5133,7 +5344,7 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.129+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.133'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -5166,14 +5377,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.13- '''- SELECT COUNT(*) AS "__count"- FROM "posthog_taggeditem"- WHERE "posthog_taggeditem"."dashboard_id" = 99999- '''-# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.130+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.134'''SELECT "posthog_tag"."name" AS "tag__name"FROM "posthog_taggeditem"@@ -5181,7 +5385,7 @@WHERE "posthog_taggeditem"."insight_id" = 99999'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.131+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.135'''SELECT "posthog_user"."id","posthog_user"."password",@@ -5227,7 +5431,7 @@AND "posthog_user"."id" = 99999)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.132+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.136'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -5272,7 +5476,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.133+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.137'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -5413,7 +5617,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.134+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.138'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -5467,7 +5671,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.135+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.139'''SELECT "ee_accesscontrol"."id","ee_accesscontrol"."team_id",@@ -5492,7 +5696,23 @@AND "ee_accesscontrol"."team_id" = 99999))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.136+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.14+ '''+ SELECT "posthog_filesystem"."id" AS "id",+ "posthog_filesystem"."path" AS "path"+ FROM "posthog_filesystem"+ WHERE (("posthog_filesystem"."surface" IS NULL+ OR "posthog_filesystem"."surface" = 'web')+ AND "posthog_filesystem"."ref" = '0001'+ AND "posthog_filesystem"."team_id" = 99999+ AND "posthog_filesystem"."type" = 'dashboard'+ AND NOT ("posthog_filesystem"."shortcut"+ AND "posthog_filesystem"."shortcut" IS NOT NULL))+ ORDER BY 1 ASC+ LIMIT 1+ '''+# ---+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.140'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -5544,7 +5764,7 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.137+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.141'''SELECT "ee_accesscontrol"."team_id" AS "team_id","ee_accesscontrol"."resource_id" AS "resource_id",@@ -5557,7 +5777,7 @@AND "posthog_team"."organization_id" IN ('00000000-0000-0000-0000-000000000000'::uuid))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.138+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.142'''SELECT "ee_role"."organization_id" AS "role__organization_id","ee_rolemembership"."role_id" AS "role_id"@@ -5566,7 +5786,7 @@WHERE "ee_rolemembership"."user_id" = 99999'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.139+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.143'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -5669,23 +5889,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.14- '''- SELECT "posthog_filesystem"."id" AS "id",- "posthog_filesystem"."path" AS "path"- FROM "posthog_filesystem"- WHERE (("posthog_filesystem"."surface" IS NULL- OR "posthog_filesystem"."surface" = 'web')- AND "posthog_filesystem"."ref" = '0001'- AND "posthog_filesystem"."team_id" = 99999- AND "posthog_filesystem"."type" = 'dashboard'- AND NOT ("posthog_filesystem"."shortcut"- AND "posthog_filesystem"."shortcut" IS NOT NULL))- ORDER BY 1 ASC- LIMIT 1- '''-# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.140+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.144'''SELECT "posthog_sharingconfiguration"."id","posthog_sharingconfiguration"."team_id",@@ -5708,7 +5912,7 @@5 /* ... */)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.141+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.145'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -6071,7 +6275,7 @@ORDER BY "posthog_dashboarditem"."order" ASC'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.142+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.146'''SELECT ("posthog_dashboardtile"."insight_id") AS "_prefetch_related_val_insight_id","posthog_dashboard"."id",@@ -6113,7 +6317,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.143+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.147'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -6144,7 +6348,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.144+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.148'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -6173,7 +6377,7 @@2)/* ... */)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.145+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.149'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",@@ -6200,7 +6404,23 @@5 /* ... */)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.146+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.15+ '''+ SELECT "posthog_filesystem"."id" AS "id",+ "posthog_filesystem"."path" AS "path"+ FROM "posthog_filesystem"+ WHERE (("posthog_filesystem"."surface" IS NULL+ OR "posthog_filesystem"."surface" = 'web')+ AND "posthog_filesystem"."ref" = '0001'+ AND "posthog_filesystem"."team_id" = 99999+ AND "posthog_filesystem"."type" = 'dashboard'+ AND NOT ("posthog_filesystem"."shortcut"+ AND "posthog_filesystem"."shortcut" IS NOT NULL))+ ORDER BY 1 ASC+ LIMIT 1+ '''+# ---+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.150'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -6302,7 +6522,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.147+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.151'''SELECT "posthog_filesystem"."team_id","posthog_filesystem"."id",@@ -6327,7 +6547,7 @@AND "posthog_filesystem"."shortcut" IS NOT NULL))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.148+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.152'''SELECT "posthog_filesystemshortcut"."id","posthog_filesystemshortcut"."team_id",@@ -6350,42 +6570,27 @@AND "posthog_filesystemshortcut"."href" IS NOT NULL))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.149+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.153'''- SELECT "posthog_insightvariable"."created_by_id",- "posthog_insightvariable"."created_at",- "posthog_insightvariable"."updated_at",- "posthog_insightvariable"."id",- "posthog_insightvariable"."team_id",+ SELECT "posthog_insightvariable"."id","posthog_insightvariable"."name","posthog_insightvariable"."code_name","posthog_insightvariable"."type","posthog_insightvariable"."default_value",- "posthog_insightvariable"."values",- "posthog_insightvariable"."is_multi",- "posthog_insightvariable"."values_query",- "posthog_insightvariable"."values_query_connection_id"+ "posthog_insightvariable"."is_multi"FROM "posthog_insightvariable"- WHERE "posthog_insightvariable"."team_id" = 99999- '''-# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.15- '''- SELECT "posthog_filesystem"."id" AS "id",- "posthog_filesystem"."path" AS "path"- FROM "posthog_filesystem"- WHERE (("posthog_filesystem"."surface" IS NULL- OR "posthog_filesystem"."surface" = 'web')- AND "posthog_filesystem"."ref" = '0001'- AND "posthog_filesystem"."team_id" = 99999- AND "posthog_filesystem"."type" = 'dashboard'- AND NOT ("posthog_filesystem"."shortcut"- AND "posthog_filesystem"."shortcut" IS NOT NULL))- ORDER BY 1 ASC- LIMIT 1+ INNER JOIN "posthog_team" ON ("posthog_insightvariable"."team_id" = "posthog_team"."id")+ WHERE ("posthog_insightvariable"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_insightvariable"."team_id" = 99999))+ ORDER BY "posthog_insightvariable"."name" ASC'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.150+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.154'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -6749,7 +6954,7 @@ORDER BY "posthog_dashboarditem"."order" ASC'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.151+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.155'''SELECT ("posthog_dashboardtile"."insight_id") AS "_prefetch_related_val_insight_id","posthog_dashboard"."id",@@ -6791,7 +6996,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.152+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.156'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -6822,7 +7027,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.153+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.157'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -6851,7 +7056,7 @@2)/* ... */)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.154+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.158'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",@@ -6878,7 +7083,7 @@5 /* ... */)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.155+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.159'''SELECT "posthog_alertconfiguration"."created_by_id","posthog_alertconfiguration"."created_at",@@ -6959,7 +7164,23 @@5 /* ... */)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.156+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.16+ '''+ SELECT "posthog_filesystem"."id" AS "id",+ "posthog_filesystem"."path" AS "path"+ FROM "posthog_filesystem"+ WHERE (("posthog_filesystem"."surface" IS NULL+ OR "posthog_filesystem"."surface" = 'web')+ AND "posthog_filesystem"."ref" = '0001'+ AND "posthog_filesystem"."team_id" = 99999+ AND "posthog_filesystem"."type" = 'dashboard'+ AND NOT ("posthog_filesystem"."shortcut"+ AND "posthog_filesystem"."shortcut" IS NOT NULL))+ ORDER BY 1 ASC+ LIMIT 1+ '''+# ---+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.160'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -6992,22 +7213,6 @@5 /* ... */))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.16- '''- SELECT "posthog_filesystem"."id" AS "id",- "posthog_filesystem"."path" AS "path"- FROM "posthog_filesystem"- WHERE (("posthog_filesystem"."surface" IS NULL- OR "posthog_filesystem"."surface" = 'web')- AND "posthog_filesystem"."ref" = '0001'- AND "posthog_filesystem"."team_id" = 99999- AND "posthog_filesystem"."type" = 'dashboard'- AND NOT ("posthog_filesystem"."shortcut"- AND "posthog_filesystem"."shortcut" IS NOT NULL))- ORDER BY 1 ASC- LIMIT 1- '''-# ---# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.17'''SELECT "posthog_sharingconfiguration"."id",@@ -7029,21 +7234,22 @@# ---# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.18'''- SELECT "posthog_insightvariable"."created_by_id",- "posthog_insightvariable"."created_at",- "posthog_insightvariable"."updated_at",- "posthog_insightvariable"."id",- "posthog_insightvariable"."team_id",+ SELECT "posthog_insightvariable"."id","posthog_insightvariable"."name","posthog_insightvariable"."code_name","posthog_insightvariable"."type","posthog_insightvariable"."default_value",- "posthog_insightvariable"."values",- "posthog_insightvariable"."is_multi",- "posthog_insightvariable"."values_query",- "posthog_insightvariable"."values_query_connection_id"+ "posthog_insightvariable"."is_multi"FROM "posthog_insightvariable"- WHERE "posthog_insightvariable"."team_id" = 99999+ INNER JOIN "posthog_team" ON ("posthog_insightvariable"."team_id" = "posthog_team"."id")+ WHERE ("posthog_insightvariable"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_insightvariable"."team_id" = 99999))+ ORDER BY "posthog_insightvariable"."name" ASC'''# ---# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.19@@ -8242,21 +8448,22 @@# ---# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.39'''- SELECT "posthog_insightvariable"."created_by_id",- "posthog_insightvariable"."created_at",- "posthog_insightvariable"."updated_at",- "posthog_insightvariable"."id",- "posthog_insightvariable"."team_id",+ SELECT "posthog_insightvariable"."id","posthog_insightvariable"."name","posthog_insightvariable"."code_name","posthog_insightvariable"."type","posthog_insightvariable"."default_value",- "posthog_insightvariable"."values",- "posthog_insightvariable"."is_multi",- "posthog_insightvariable"."values_query",- "posthog_insightvariable"."values_query_connection_id"+ "posthog_insightvariable"."is_multi"FROM "posthog_insightvariable"- WHERE "posthog_insightvariable"."team_id" = 99999+ INNER JOIN "posthog_team" ON ("posthog_insightvariable"."team_id" = "posthog_team"."id")+ WHERE ("posthog_insightvariable"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_insightvariable"."team_id" = 99999))+ ORDER BY "posthog_insightvariable"."name" ASC'''# ---# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.4@@ -9307,6 +9514,22 @@'''# ---# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.57+ '''+ SELECT "posthog_insightviewed"."id",+ "posthog_insightviewed"."team_id",+ "posthog_insightviewed"."user_id",+ "posthog_insightviewed"."insight_id",+ "posthog_insightviewed"."last_viewed_at"+ FROM "posthog_insightviewed"+ WHERE ("posthog_insightviewed"."insight_id" = 99999+ AND "posthog_insightviewed"."team_id" = 99999+ AND "posthog_insightviewed"."user_id" = 99999)+ LIMIT 21+ FOR+ UPDATE+ '''+# ---+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.58'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -9351,7 +9574,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.58+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.59'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -9453,7 +9676,20 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.59+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.6+ '''+ SELECT "ee_accesscontrol"."team_id" AS "team_id",+ "ee_accesscontrol"."resource_id" AS "resource_id",+ "ee_accesscontrol"."organization_member_id" AS "organization_member_id",+ "ee_accesscontrol"."role_id" AS "role_id",+ "ee_accesscontrol"."access_level" AS "access_level"+ FROM "ee_accesscontrol"+ INNER JOIN "posthog_team" ON ("ee_accesscontrol"."team_id" = "posthog_team"."id")+ WHERE ("ee_accesscontrol"."resource" = 'project'+ AND "posthog_team"."organization_id" IN ('00000000-0000-0000-0000-000000000000'::uuid))+ '''+# ---+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.60'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -9480,20 +9716,7 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.6- '''- SELECT "ee_accesscontrol"."team_id" AS "team_id",- "ee_accesscontrol"."resource_id" AS "resource_id",- "ee_accesscontrol"."organization_member_id" AS "organization_member_id",- "ee_accesscontrol"."role_id" AS "role_id",- "ee_accesscontrol"."access_level" AS "access_level"- FROM "ee_accesscontrol"- INNER JOIN "posthog_team" ON ("ee_accesscontrol"."team_id" = "posthog_team"."id")- WHERE ("ee_accesscontrol"."resource" = 'project'- AND "posthog_team"."organization_id" IN ('00000000-0000-0000-0000-000000000000'::uuid))- '''-# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.60+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.61'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -9520,26 +9743,27 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.61+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.62'''- SELECT "posthog_insightvariable"."created_by_id",- "posthog_insightvariable"."created_at",- "posthog_insightvariable"."updated_at",- "posthog_insightvariable"."id",- "posthog_insightvariable"."team_id",+ SELECT "posthog_insightvariable"."id","posthog_insightvariable"."name","posthog_insightvariable"."code_name","posthog_insightvariable"."type","posthog_insightvariable"."default_value",- "posthog_insightvariable"."values",- "posthog_insightvariable"."is_multi",- "posthog_insightvariable"."values_query",- "posthog_insightvariable"."values_query_connection_id"+ "posthog_insightvariable"."is_multi"FROM "posthog_insightvariable"- WHERE "posthog_insightvariable"."team_id" = 99999+ INNER JOIN "posthog_team" ON ("posthog_insightvariable"."team_id" = "posthog_team"."id")+ WHERE ("posthog_insightvariable"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_insightvariable"."team_id" = 99999))+ ORDER BY "posthog_insightvariable"."name" ASC'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.62+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.63'''SELECT "posthog_dashboardtile"."dashboard_id" AS "dashboard_id"FROM "posthog_dashboardtile"@@ -9550,7 +9774,7 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.63+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.64'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -9583,7 +9807,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.64+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.65'''SELECT "posthog_tag"."name" AS "tag__name"FROM "posthog_taggeditem"@@ -9591,7 +9815,7 @@WHERE "posthog_taggeditem"."insight_id" = 99999'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.65+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.66'''SELECT "posthog_user"."id","posthog_user"."password",@@ -9637,7 +9861,7 @@AND "posthog_user"."id" = 99999)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.66+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.67'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -9682,7 +9906,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.67+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.68'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -9823,7 +10047,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.68+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.69'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -9877,7 +10101,16 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.69+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.7+ '''+ SELECT "ee_role"."organization_id" AS "role__organization_id",+ "ee_rolemembership"."role_id" AS "role_id"+ FROM "ee_rolemembership"+ INNER JOIN "ee_role" ON ("ee_rolemembership"."role_id" = "ee_role"."id")+ WHERE "ee_rolemembership"."user_id" = 99999+ '''+# ---+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.70'''SELECT "ee_accesscontrol"."id","ee_accesscontrol"."team_id",@@ -9902,16 +10135,7 @@AND "ee_accesscontrol"."team_id" = 99999))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.7- '''- SELECT "ee_role"."organization_id" AS "role__organization_id",- "ee_rolemembership"."role_id" AS "role_id"- FROM "ee_rolemembership"- INNER JOIN "ee_role" ON ("ee_rolemembership"."role_id" = "ee_role"."id")- WHERE "ee_rolemembership"."user_id" = 99999- '''-# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.70+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.71'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -9963,7 +10187,7 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.71+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.72'''SELECT "ee_accesscontrol"."team_id" AS "team_id","ee_accesscontrol"."resource_id" AS "resource_id",@@ -9976,7 +10200,7 @@AND "posthog_team"."organization_id" IN ('00000000-0000-0000-0000-000000000000'::uuid))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.72+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.73'''SELECT "ee_role"."organization_id" AS "role__organization_id","ee_rolemembership"."role_id" AS "role_id"@@ -9985,7 +10209,7 @@WHERE "ee_rolemembership"."user_id" = 99999'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.73+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.74'''SELECT "posthog_dashboard"."id" AS "id"FROM "posthog_dashboard"@@ -10005,7 +10229,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.74+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.75'''SELECT "posthog_dashboard"."id" AS "id","posthog_dashboard"."name" AS "name"@@ -10018,7 +10242,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.75+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.76'''SELECT COUNT(*) AS "__count"FROM "posthog_dashboardtile"@@ -10031,7 +10255,7 @@AND "posthog_dashboardtile"."deleted" IS NOT NULL))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.76+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.77'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -10064,7 +10288,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.77+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.78'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -10166,7 +10390,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.78+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.79'''SELECT "posthog_filesystem"."team_id","posthog_filesystem"."id",@@ -10191,7 +10415,39 @@AND "posthog_filesystem"."shortcut" IS NOT NULL))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.79+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.8+ '''+ SELECT COUNT(*) AS "__count"+ FROM "posthog_dashboard"+ INNER JOIN "posthog_team" ON ("posthog_dashboard"."team_id" = "posthog_team"."id")+ WHERE (NOT ("posthog_dashboard"."deleted")+ AND ("posthog_dashboard"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_dashboard"."team_id" = 99999))+ AND NOT "posthog_dashboard"."deleted")+ '''+# ---+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.80+ '''+ SELECT "posthog_insightviewed"."id",+ "posthog_insightviewed"."team_id",+ "posthog_insightviewed"."user_id",+ "posthog_insightviewed"."insight_id",+ "posthog_insightviewed"."last_viewed_at"+ FROM "posthog_insightviewed"+ WHERE ("posthog_insightviewed"."insight_id" = 99999+ AND "posthog_insightviewed"."team_id" = 99999+ AND "posthog_insightviewed"."user_id" = 99999)+ LIMIT 21+ FOR+ UPDATE+ '''+# ---+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.81'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -10236,23 +10492,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.8- '''- SELECT COUNT(*) AS "__count"- FROM "posthog_dashboard"- INNER JOIN "posthog_team" ON ("posthog_dashboard"."team_id" = "posthog_team"."id")- WHERE (NOT ("posthog_dashboard"."deleted")- AND ("posthog_dashboard"."team_id" =- (SELECT U0."parent_team_id" AS "parent_team_id"- FROM "posthog_team" U0- WHERE U0."id" = 99999- LIMIT 1)- OR ("posthog_team"."parent_team_id" IS NULL- AND "posthog_dashboard"."team_id" = 99999))- AND NOT "posthog_dashboard"."deleted")- '''-# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.80+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.82'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -10354,7 +10594,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.81+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.83'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -10381,7 +10621,7 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.82+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.84'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -10408,26 +10648,27 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.83+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.85'''- SELECT "posthog_insightvariable"."created_by_id",- "posthog_insightvariable"."created_at",- "posthog_insightvariable"."updated_at",- "posthog_insightvariable"."id",- "posthog_insightvariable"."team_id",+ SELECT "posthog_insightvariable"."id","posthog_insightvariable"."name","posthog_insightvariable"."code_name","posthog_insightvariable"."type","posthog_insightvariable"."default_value",- "posthog_insightvariable"."values",- "posthog_insightvariable"."is_multi",- "posthog_insightvariable"."values_query",- "posthog_insightvariable"."values_query_connection_id"+ "posthog_insightvariable"."is_multi"FROM "posthog_insightvariable"- WHERE "posthog_insightvariable"."team_id" = 99999+ INNER JOIN "posthog_team" ON ("posthog_insightvariable"."team_id" = "posthog_team"."id")+ WHERE ("posthog_insightvariable"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_insightvariable"."team_id" = 99999))+ ORDER BY "posthog_insightvariable"."name" ASC'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.84+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.86'''SELECT "posthog_dashboardtile"."dashboard_id" AS "dashboard_id"FROM "posthog_dashboardtile"@@ -10438,7 +10679,7 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.85+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.87'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -10471,7 +10712,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.86+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.88'''SELECT "posthog_tag"."name" AS "tag__name"FROM "posthog_taggeditem"@@ -10479,7 +10720,7 @@WHERE "posthog_taggeditem"."insight_id" = 99999'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.87+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.89'''SELECT "posthog_user"."id","posthog_user"."password",@@ -10525,52 +10766,7 @@AND "posthog_user"."id" = 99999)'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.88- '''- SELECT "posthog_organization"."id",- "posthog_organization"."name",- "posthog_organization"."slug",- "posthog_organization"."logo_media_id",- "posthog_organization"."created_at",- "posthog_organization"."updated_at",- "posthog_organization"."is_active",- "posthog_organization"."is_not_active_reason",- "posthog_organization"."session_cookie_age",- "posthog_organization"."is_member_join_email_enabled",- "posthog_organization"."is_ai_data_processing_approved",- "posthog_organization"."is_ai_training_opted_in",- "posthog_organization"."is_ai_training_locked",- "posthog_organization"."is_ai_training_cta_shown",- "posthog_organization"."enforce_2fa",- "posthog_organization"."enforce_verified_domains",- "posthog_organization"."members_can_invite",- "posthog_organization"."members_can_create_projects",- "posthog_organization"."members_can_use_personal_api_keys",- "posthog_organization"."members_can_see_org_members",- "posthog_organization"."allow_publicly_shared_resources",- "posthog_organization"."default_role_id",- "posthog_organization"."plugins_access_level",- "posthog_organization"."for_internal_metrics",- "posthog_organization"."default_experiment_stats_method",- "posthog_organization"."default_anonymize_ips",- "posthog_organization"."is_hipaa",- "posthog_organization"."is_pending_deletion",- "posthog_organization"."customer_id",- "posthog_organization"."available_product_features",- "posthog_organization"."usage",- "posthog_organization"."never_drop_data",- "posthog_organization"."customer_trust_scores",- "posthog_organization"."has_active_subscription",- "posthog_organization"."setup_section_2_completed",- "posthog_organization"."personalization",- "posthog_organization"."domain_whitelist",- "posthog_organization"."is_platform"- FROM "posthog_organization"- WHERE "posthog_organization"."id" = '00000000-0000-0000-0000-000000000000'::uuid- LIMIT 21- '''-# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.89+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.9'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -10666,8 +10862,15 @@"posthog_team"."experiment_recalculation_time","posthog_team"."default_experiment_confidence_level","posthog_team"."default_experiment_stats_method",- "posthog_team"."business_model",- "posthog_organization"."id",+ "posthog_team"."business_model"+ FROM "posthog_team"+ WHERE "posthog_team"."id" = 99999+ LIMIT 21+ '''+# ---+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.90+ '''+ SELECT "posthog_organization"."id","posthog_organization"."name","posthog_organization"."slug","posthog_organization"."logo_media_id",@@ -10705,13 +10908,12 @@"posthog_organization"."personalization","posthog_organization"."domain_whitelist","posthog_organization"."is_platform"- FROM "posthog_team"- INNER JOIN "posthog_organization" ON ("posthog_team"."organization_id" = "posthog_organization"."id")- WHERE "posthog_team"."id" = 99999+ FROM "posthog_organization"+ WHERE "posthog_organization"."id" = '00000000-0000-0000-0000-000000000000'::uuidLIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.9+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.91'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -10807,13 +11009,52 @@"posthog_team"."experiment_recalculation_time","posthog_team"."default_experiment_confidence_level","posthog_team"."default_experiment_stats_method",- "posthog_team"."business_model"+ "posthog_team"."business_model",+ "posthog_organization"."id",+ "posthog_organization"."name",+ "posthog_organization"."slug",+ "posthog_organization"."logo_media_id",+ "posthog_organization"."created_at",+ "posthog_organization"."updated_at",+ "posthog_organization"."is_active",+ "posthog_organization"."is_not_active_reason",+ "posthog_organization"."session_cookie_age",+ "posthog_organization"."is_member_join_email_enabled",+ "posthog_organization"."is_ai_data_processing_approved",+ "posthog_organization"."is_ai_training_opted_in",+ "posthog_organization"."is_ai_training_locked",+ "posthog_organization"."is_ai_training_cta_shown",+ "posthog_organization"."enforce_2fa",+ "posthog_organization"."enforce_verified_domains",+ "posthog_organization"."members_can_invite",+ "posthog_organization"."members_can_create_projects",+ "posthog_organization"."members_can_use_personal_api_keys",+ "posthog_organization"."members_can_see_org_members",+ "posthog_organization"."allow_publicly_shared_resources",+ "posthog_organization"."default_role_id",+ "posthog_organization"."plugins_access_level",+ "posthog_organization"."for_internal_metrics",+ "posthog_organization"."default_experiment_stats_method",+ "posthog_organization"."default_anonymize_ips",+ "posthog_organization"."is_hipaa",+ "posthog_organization"."is_pending_deletion",+ "posthog_organization"."customer_id",+ "posthog_organization"."available_product_features",+ "posthog_organization"."usage",+ "posthog_organization"."never_drop_data",+ "posthog_organization"."customer_trust_scores",+ "posthog_organization"."has_active_subscription",+ "posthog_organization"."setup_section_2_completed",+ "posthog_organization"."personalization",+ "posthog_organization"."domain_whitelist",+ "posthog_organization"."is_platform"FROM "posthog_team"+ INNER JOIN "posthog_organization" ON ("posthog_team"."organization_id" = "posthog_organization"."id")WHERE "posthog_team"."id" = 99999LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.90+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.92'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -10867,7 +11108,7 @@LIMIT 21'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.91+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.93'''SELECT "ee_accesscontrol"."id","ee_accesscontrol"."team_id",@@ -10892,7 +11133,7 @@AND "ee_accesscontrol"."team_id" = 99999))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.92+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.94'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -10944,7 +11185,7 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.93+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.95'''SELECT "ee_accesscontrol"."team_id" AS "team_id","ee_accesscontrol"."resource_id" AS "resource_id",@@ -10957,7 +11198,7 @@AND "posthog_team"."organization_id" IN ('00000000-0000-0000-0000-000000000000'::uuid))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.94+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.96'''SELECT "ee_role"."organization_id" AS "role__organization_id","ee_rolemembership"."role_id" AS "role_id"@@ -10966,7 +11207,7 @@WHERE "ee_rolemembership"."user_id" = 99999'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.95+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.97'''SELECT "posthog_dashboard"."id" AS "id"FROM "posthog_dashboard"@@ -10986,7 +11227,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.96+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.98'''SELECT "posthog_dashboard"."id" AS "id","posthog_dashboard"."name" AS "name"@@ -10999,7 +11240,7 @@5 /* ... */))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.97+# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.99'''SELECT COUNT(*) AS "__count"FROM "posthog_dashboardtile"@@ -11012,141 +11253,6 @@AND "posthog_dashboardtile"."deleted" IS NOT NULL))'''# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.98- '''- SELECT "posthog_dashboard"."id",- "posthog_dashboard"."name",- "posthog_dashboard"."description",- "posthog_dashboard"."team_id",- "posthog_dashboard"."pinned",- "posthog_dashboard"."created_at",- "posthog_dashboard"."created_by_id",- "posthog_dashboard"."deleted",- "posthog_dashboard"."last_accessed_at",- "posthog_dashboard"."last_refresh",- "posthog_dashboard"."filters",- "posthog_dashboard"."variables",- "posthog_dashboard"."breakdown_colors",- "posthog_dashboard"."data_color_theme_id",- "posthog_dashboard"."creation_mode",- "posthog_dashboard"."restriction_level",- "posthog_dashboard"."quick_filter_ids",- "posthog_dashboard"."customization",- "posthog_dashboard"."deprecated_tags",- "posthog_dashboard"."tags",- "posthog_dashboard"."share_token",- "posthog_dashboard"."is_shared"- FROM "posthog_dashboard"- WHERE (NOT ("posthog_dashboard"."deleted")- AND "posthog_dashboard"."id" IN (1,- 2,- 3,- 4,- 5 /* ... */))- '''-# ----# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.99- '''- SELECT "posthog_team"."id",- "posthog_team"."uuid",- "posthog_team"."organization_id",- "posthog_team"."parent_team_id",- "posthog_team"."project_id",- "posthog_team"."api_token",- "posthog_team"."app_urls",- "posthog_team"."name",- "posthog_team"."slack_incoming_webhook",- "posthog_team"."created_at",- "posthog_team"."updated_at",- "posthog_team"."anonymize_ips",- "posthog_team"."completed_snippet_onboarding",- "posthog_team"."has_completed_onboarding_for",- "posthog_team"."onboarding_tasks",- "posthog_team"."ingested_event",- "posthog_team"."ingested_production_event",- "posthog_team"."ingested_production_event_last_checked_at",- "posthog_team"."person_processing_opt_out",- "posthog_team"."secret_api_token",- "posthog_team"."secret_api_token_backup",- "posthog_team"."session_recording_opt_in",- "posthog_team"."session_recording_sample_rate",- "posthog_team"."session_recording_minimum_duration_milliseconds",- "posthog_team"."session_recording_linked_flag",- "posthog_team"."session_recording_network_payload_capture_config",- "posthog_team"."session_recording_masking_config",- "posthog_team"."session_recording_url_trigger_config",- "posthog_team"."session_recording_url_blocklist_config",- "posthog_team"."session_recording_event_trigger_config",- "posthog_team"."session_recording_trigger_match_type_config",- "posthog_team"."session_recording_trigger_groups",- "posthog_team"."session_replay_config",- "posthog_team"."session_recording_retention_period",- "posthog_team"."event_retention_months",- "posthog_team"."conversations_enabled",- "posthog_team"."conversations_settings",- "posthog_team"."proactive_tasks_enabled",- "posthog_team"."survey_config",- "posthog_team"."surveys_opt_in",- "posthog_team"."product_tours_opt_in",- "posthog_team"."capture_console_log_opt_in",- "posthog_team"."capture_performance_opt_in",- "posthog_team"."capture_dead_clicks",- "posthog_team"."autocapture_opt_out",- "posthog_team"."autocapture_web_vitals_opt_in",- "posthog_team"."autocapture_web_vitals_allowed_metrics",- "posthog_team"."autocapture_exceptions_opt_in",- "posthog_team"."autocapture_exceptions_errors_to_ignore",- "posthog_team"."logs_settings",- "posthog_team"."llm_gateway_enabled_at",- "posthog_team"."llm_gateway_revoked_at",- "posthog_team"."llm_gateway_overspend_allowance_usd",- "posthog_team"."heatmaps_opt_in",- "posthog_team"."receive_org_level_activity_logs",- "posthog_team"."web_analytics_pre_aggregated_tables_enabled",- "posthog_team"."web_analytics_pre_aggregated_tables_version",- "posthog_team"."flags_persistence_default",- "posthog_team"."feature_flag_confirmation_enabled",- "posthog_team"."feature_flag_confirmation_message",- "posthog_team"."default_evaluation_environments_enabled",- "posthog_team"."require_evaluation_environment_tags",- "posthog_team"."default_evaluation_contexts_enabled",- "posthog_team"."require_evaluation_contexts",- "posthog_team"."session_recording_version",- "posthog_team"."signup_token",- "posthog_team"."is_demo",- "posthog_team"."access_control",- "posthog_team"."week_start_day",- "posthog_team"."inject_web_apps",- "posthog_team"."test_account_filters",- "posthog_team"."test_account_filters_default_checked",- "posthog_team"."path_cleaning_filters",- "posthog_team"."timezone",- "posthog_team"."data_attributes",- "posthog_team"."person_display_name_properties",- "posthog_team"."live_events_columns",- "posthog_team"."recording_domains",- "posthog_team"."human_friendly_comparison_periods",- "posthog_team"."cookieless_server_hash_mode",- "posthog_team"."primary_dashboard_id",- "posthog_team"."default_data_theme",- "posthog_team"."extra_settings",- "posthog_team"."modifiers",- "posthog_team"."correlation_config",- "posthog_team"."session_recording_retention_period_days",- "posthog_team"."external_data_workspace_id",- "posthog_team"."external_data_workspace_last_synced_at",- "posthog_team"."api_query_rate_limit",- "posthog_team"."drop_events_older_than",- "posthog_team"."base_currency",- "posthog_team"."experiment_recalculation_time",- "posthog_team"."default_experiment_confidence_level",- "posthog_team"."default_experiment_stats_method",- "posthog_team"."business_model"- FROM "posthog_team"- WHERE "posthog_team"."id" = 99999- LIMIT 21- '''-# ---# name: TestDashboard.test_retrieve_dashboard'''SELECT "posthog_filesystem"."team_id",@@ -11783,21 +11889,22 @@# ---# name: TestDashboard.test_retrieve_dashboard.16'''- SELECT "posthog_insightvariable"."created_by_id",- "posthog_insightvariable"."created_at",- "posthog_insightvariable"."updated_at",- "posthog_insightvariable"."id",- "posthog_insightvariable"."team_id",+ SELECT "posthog_insightvariable"."id","posthog_insightvariable"."name","posthog_insightvariable"."code_name","posthog_insightvariable"."type","posthog_insightvariable"."default_value",- "posthog_insightvariable"."values",- "posthog_insightvariable"."is_multi",- "posthog_insightvariable"."values_query",- "posthog_insightvariable"."values_query_connection_id"+ "posthog_insightvariable"."is_multi"FROM "posthog_insightvariable"- WHERE "posthog_insightvariable"."team_id" = 99999+ INNER JOIN "posthog_team" ON ("posthog_insightvariable"."team_id" = "posthog_team"."id")+ WHERE ("posthog_insightvariable"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_insightvariable"."team_id" = 99999))+ ORDER BY "posthog_insightvariable"."name" ASC'''# ---# name: TestDashboard.test_retrieve_dashboard.17@@ -12829,21 +12936,22 @@# ---# name: TestDashboard.test_retrieve_dashboard_list.18'''- SELECT "posthog_insightvariable"."created_by_id",- "posthog_insightvariable"."created_at",- "posthog_insightvariable"."updated_at",- "posthog_insightvariable"."id",- "posthog_insightvariable"."team_id",+ SELECT "posthog_insightvariable"."id","posthog_insightvariable"."name","posthog_insightvariable"."code_name","posthog_insightvariable"."type","posthog_insightvariable"."default_value",- "posthog_insightvariable"."values",- "posthog_insightvariable"."is_multi",- "posthog_insightvariable"."values_query",- "posthog_insightvariable"."values_query_connection_id"+ "posthog_insightvariable"."is_multi"FROM "posthog_insightvariable"- WHERE "posthog_insightvariable"."team_id" = 99999+ INNER JOIN "posthog_team" ON ("posthog_insightvariable"."team_id" = "posthog_team"."id")+ WHERE ("posthog_insightvariable"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_insightvariable"."team_id" = 99999))+ ORDER BY "posthog_insightvariable"."name" ASC'''# ---# name: TestDashboard.test_retrieve_dashboard_list.19@@ -14042,21 +14150,22 @@# ---# name: TestDashboard.test_retrieve_dashboard_list.39'''- SELECT "posthog_insightvariable"."created_by_id",- "posthog_insightvariable"."created_at",- "posthog_insightvariable"."updated_at",- "posthog_insightvariable"."id",- "posthog_insightvariable"."team_id",+ SELECT "posthog_insightvariable"."id","posthog_insightvariable"."name","posthog_insightvariable"."code_name","posthog_insightvariable"."type","posthog_insightvariable"."default_value",- "posthog_insightvariable"."values",- "posthog_insightvariable"."is_multi",- "posthog_insightvariable"."values_query",- "posthog_insightvariable"."values_query_connection_id"+ "posthog_insightvariable"."is_multi"FROM "posthog_insightvariable"- WHERE "posthog_insightvariable"."team_id" = 99999+ INNER JOIN "posthog_team" ON ("posthog_insightvariable"."team_id" = "posthog_team"."id")+ WHERE ("posthog_insightvariable"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_insightvariable"."team_id" = 99999))+ ORDER BY "posthog_insightvariable"."name" ASC'''# ---# name: TestDashboard.test_retrieve_dashboard_list.4diff --git a/posthog/caching/test/test_warming.py b/posthog/caching/test/test_warming.pyindex ade88e0e3ef5..2336b2d5ec33 100644--- a/posthog/caching/test/test_warming.py+++ b/posthog/caching/test/test_warming.py@@ -8,7 +8,8 @@ from posthog.exceptions import ClickHouseAtCapacityfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile-from products.product_analytics.backend.facade.models import Insight, InsightViewed+from products.product_analytics.backend.facade.api import record_insight_views+from products.product_analytics.backend.facade.models import Insightclass TestWarming(APIBaseTest):@@ -38,15 +39,14 @@ class TestWarming(APIBaseTest):self.dashboard_tile2 = DashboardTile.objects.create(insight=self.insight3, dashboard=self.dashboard2)self.dashboard_tile3 = DashboardTile.objects.create(insight=self.insight5, dashboard=self.dashboard3)- # Create test InsightViewed records- InsightViewed.objects.create(- team=self.team, user=self.user, insight=self.insight2, last_viewed_at=datetime.now(UTC) - timedelta(days=2)- )- InsightViewed.objects.create(- team=self.team, user=self.user, insight=self.insight4, last_viewed_at=datetime.now(UTC) - timedelta(days=35)- )- InsightViewed.objects.create(- team=self.team, user=self.user, insight=self.insight5, last_viewed_at=datetime.now(UTC) - timedelta(days=1)+ record_insight_views(+ team_id=self.team.id,+ user_id=self.user.id,+ last_viewed_at_by_insight_id={+ self.insight2.id: datetime.now(UTC) - timedelta(days=2),+ self.insight4.id: datetime.now(UTC) - timedelta(days=35),+ self.insight5.id: datetime.now(UTC) - timedelta(days=1),+ },)@patch("posthog.caching.warming.get_stale_insights")diff --git a/posthog/hogql/autocomplete.py b/posthog/hogql/autocomplete.pyindex 919a68633976..d6989fe43ae1 100644--- a/posthog/hogql/autocomplete.py+++ b/posthog/hogql/autocomplete.py@@ -59,7 +59,7 @@ from posthog.models.team.team import Teamfrom posthog.models.user import Userfrom products.event_definitions.backend.models.property_definition import PropertyDefinition-from products.product_analytics.backend.facade.models import InsightVariable+from products.product_analytics.backend.facade.api import insight_variables_for_teamfrom common.hogvm.python.stl import STLfrom common.hogvm.python.stl.bytecode import BYTECODE_STL@@ -896,9 +896,7 @@ def get_hogql_autocomplete(if node.chain[0] == MATCH_ANY_CHARACTER or ("variables".startswith(str(node.chain[0])) and len(node.chain) == 1):- insight_variables = InsightVariable.objects.filter(- team_id=team.pk,- ).order_by("name")+ insight_variables = insight_variables_for_team(team.pk)code_names = [f"variables.{n.code_name}" for n in insight_variables if n.code_name]extend_responses(keys=code_names,@@ -907,9 +905,7 @@ def get_hogql_autocomplete(details=["Variable"] * len(code_names),)elif len(node.chain) > 1 and node.chain[0] == "variables":- insight_variables = InsightVariable.objects.filter(- team_id=team.pk,- ).order_by("name")+ insight_variables = insight_variables_for_team(team.pk)code_names = [n.code_name for n in insight_variables if n.code_name]extend_responses(keys=code_names,diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex 632944d3a840..94b255778119 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -163,6 +163,8 @@ from posthog.scopes import APIScopeObjectfrom posthog.synthetic_user import SyntheticUserfrom posthog.week_start_day import WeekStartDay+from products.warehouse_sources.backend.facade.types import ExternalDataSourceAccessMethod+# The Django ORM / products models below are imported lazily inside the functions that build a# Database (Database._fetch_sources / _build_from_sources / serialize and their helpers) so this# module — and the HogQL resolver/printer that import it — load without django.setup(). The@@ -1239,7 +1241,7 @@ class Database(BaseModel):)if (dual_source is not None- and dual_source.access_method != ExternalDataSource.AccessMethod.DIRECT+ and dual_source.access_method != ExternalDataSourceAccessMethod.DIRECTand is_direct_capable(dual_source)):latest_completed_job = (@@ -1489,7 +1491,7 @@ class Database(BaseModel):.first())if direct_source is not None and (- direct_source.access_method == ExternalDataSource.AccessMethod.DIRECT+ direct_source.access_method == ExternalDataSourceAccessMethod.DIRECTor is_direct_capable(direct_source)):if direct_source.has_managed_warehouse_prefix:@@ -1501,7 +1503,7 @@ class Database(BaseModel):is_managed_warehouse_connection = managed_warehouse_sql_mode == ManagedWarehouseSQLMode.BUILT_INdirect_connection_metadata = direct_source.connection_metadata# A capable non-DIRECT (synced) source drives the dual-mode virtual-table path.- if direct_source.access_method != ExternalDataSource.AccessMethod.DIRECT:+ if direct_source.access_method != ExternalDataSourceAccessMethod.DIRECT:virtual_source = direct_source# Dual-mode live queries run under warehouse table-level access control. The# introspected `available_functions` (scalar passthrough, e.g. query_to_xml) and@@ -1641,7 +1643,7 @@ class Database(BaseModel):tables_query = tables_query.filter(external_data_source_id=connection_id)else:tables_query = tables_query.exclude(- external_data_source__access_method=ExternalDataSource.AccessMethod.DIRECT+ external_data_source__access_method=ExternalDataSourceAccessMethod.DIRECT)warehouse_tables = list(tables_query)@@ -1755,10 +1757,7 @@ class Database(BaseModel):# Lazy imports keep the Django ORM / products models off this module's import path.from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery # noqa: PLC0415from products.data_warehouse.backend.facade.hogql import get_warehouse_sync_warnings # noqa: PLC0415- from products.warehouse_sources.backend.facade.models import ( # noqa: PLC0415- DataWarehouseTable,- ExternalDataSource,- )+ from products.warehouse_sources.backend.facade.models import DataWarehouseTable # noqa: PLC0415from products.warehouse_sources.backend.facade.types import ExternalDataSourceType # noqa: PLC0415team = sources.team@@ -1974,7 +1973,7 @@ class Database(BaseModel):if (not database._is_direct_query()and table.external_data_source- and table.external_data_source.access_method == ExternalDataSource.AccessMethod.DIRECT+ and table.external_data_source.access_method == ExternalDataSourceAccessMethod.DIRECT):continue@@ -2016,7 +2015,7 @@ class Database(BaseModel):if database._is_direct_query()and table.external_data_sourceand table.external_data_source.access_method- == ExternalDataSource.AccessMethod.DIRECT+ == ExternalDataSourceAccessMethod.DIRECTelse "ignore")@@ -2038,7 +2037,7 @@ class Database(BaseModel):joined_table_chain = ".".join(table_chain)table_for_key.name = joined_table_chainwarehouse_tables_dot_notation_mapping[joined_table_chain] = table.name- if table.external_data_source.access_method == ExternalDataSource.AccessMethod.DIRECT:+ if table.external_data_source.access_method == ExternalDataSourceAccessMethod.DIRECT:database._direct_access_warehouse_table_names.add(joined_table_chain)if index == 0:primary_table = table_for_key@@ -2407,12 +2406,11 @@ class Database(BaseModel):def get_data_warehouse_table_name(source: ExternalDataSource | None, table_name: str):- from products.warehouse_sources.backend.facade.models import ExternalDataSource # noqa: PLC0415if source is None:return table_name- if source.access_method == ExternalDataSource.AccessMethod.DIRECT:+ if source.access_method == ExternalDataSourceAccessMethod.DIRECT:return table_namesource_type = source.source_type.lower()@@ -2773,10 +2771,9 @@ def _strip_external_source_prefix(source: ExternalDataSource, table_name: str) -def _get_warehouse_table_keys(warehouse_table: DataWarehouseTable, *, direct_query: bool) -> list[str]:- from products.warehouse_sources.backend.facade.models import ExternalDataSource # noqa: PLC0415source = warehouse_table.external_data_source- if source is not None and source.access_method == ExternalDataSource.AccessMethod.DIRECT and direct_query:+ if source is not None and source.access_method == ExternalDataSourceAccessMethod.DIRECT and direct_query:return [warehouse_table.name]return [get_data_warehouse_table_name(source, warehouse_table.name)]@@ -2787,10 +2784,9 @@ def _should_include_connection_table(*,connection_id: str,) -> bool:- from products.warehouse_sources.backend.facade.models import ExternalDataSource # noqa: PLC0415source = warehouse_table.external_data_source- if source is None or source.access_method != ExternalDataSource.AccessMethod.DIRECT:+ if source is None or source.access_method != ExternalDataSourceAccessMethod.DIRECT:return Falseif str(warehouse_table.external_data_source_id) != connection_id:diff --git a/posthog/hogql/database/postgres_utils.py b/posthog/hogql/database/postgres_utils.pyindex b774420ebc69..c785bbffc477 100644--- a/posthog/hogql/database/postgres_utils.py+++ b/posthog/hogql/database/postgres_utils.py@@ -11,6 +11,8 @@ from posthog.hogql.database.utils import get_join_field_chainfrom posthog.exceptions_capture import capture_exception+from products.warehouse_sources.backend.facade.types import ExternalDataSourceAccessMethod+if TYPE_CHECKING:from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema@@ -245,10 +247,9 @@ def _is_same_external_scope(return False# noqa keeps the warehouse ORM off this module's import path — only needed when a Database is built.- from products.warehouse_sources.backend.facade.models import ExternalDataSource # noqa: PLC0415source = warehouse_table.external_data_source- if source is not None and source.access_method == ExternalDataSource.AccessMethod.DIRECT:+ if source is not None and source.access_method == ExternalDataSourceAccessMethod.DIRECT:return isinstance(target_hogql_table, DirectSQLTable) and target_hogql_table.external_data_source_id == str(source.id)diff --git a/posthog/hogql/direct_connection.py b/posthog/hogql/direct_connection.pyindex ec9a53a29416..1de4ab87c13f 100644--- a/posthog/hogql/direct_connection.py+++ b/posthog/hogql/direct_connection.py@@ -15,7 +15,7 @@ from posthog.synthetic_user import SyntheticUserfrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource-from products.warehouse_sources.backend.facade.types import ManagedWarehouseSQLMode+from products.warehouse_sources.backend.facade.types import ExternalDataSourceAccessMethod, ManagedWarehouseSQLModeif TYPE_CHECKING:from posthog.models import Team, User@@ -116,7 +116,7 @@ def get_direct_connection_source(# boundary and reads any upstream table, so raw queries are pure-direct only. Pure-direct# sources have no restricted catalog to bypass; the whole external database is the intended# surface.- if require_pure_direct and source.access_method != ExternalDataSource.AccessMethod.DIRECT:+ if require_pure_direct and source.access_method != ExternalDataSourceAccessMethod.DIRECT:return Noneif (diff --git a/posthog/hogql/direct_sql/capability.py b/posthog/hogql/direct_sql/capability.pyindex 1c28931c833d..425093818dfd 100644--- a/posthog/hogql/direct_sql/capability.py+++ b/posthog/hogql/direct_sql/capability.py@@ -1,5 +1,5 @@from products.warehouse_sources.backend.facade.models import ExternalDataSource-from products.warehouse_sources.backend.facade.types import DIRECT_ENGINE_BY_SOURCE_TYPE+from products.warehouse_sources.backend.facade.types import DIRECT_ENGINE_BY_SOURCE_TYPE, ExternalDataSourceAccessMethoddef direct_capable_source_types() -> frozenset[str]:@@ -15,7 +15,7 @@ def is_direct_capable(source: ExternalDataSource) -> bool:"""if source.direct_engine is None:return False- if source.access_method == ExternalDataSource.AccessMethod.DIRECT:+ if source.access_method == ExternalDataSourceAccessMethod.DIRECT:return Truereturn source.direct_query_enableddiff --git a/posthog/hogql/variables.py b/posthog/hogql/variables.pyindex 46cab7c1e060..fb3f53020114 100644--- a/posthog/hogql/variables.py+++ b/posthog/hogql/variables.py@@ -11,7 +11,9 @@ from posthog.hogql.visitor import CloningVisitorfrom posthog.models.team.team import Teamfrom posthog.utils import relative_date_parse-from products.product_analytics.backend.facade.models import InsightVariable+from products.product_analytics.backend.facade.api import insight_variables_by_ids+from products.product_analytics.backend.facade.contracts import InsightVariableDefinition+from products.product_analytics.backend.facade.enums import InsightVariableTypeT = TypeVar("T", bound=ast.Expr)@@ -21,14 +23,12 @@ def replace_variables(node: T, variables: list[HogQLVariable], team: Team) -> T:class ReplaceVariables(CloningVisitor):- insight_variables: list[InsightVariable]+ insight_variables: list[InsightVariableDefinition]def __init__(self, variables: list[HogQLVariable], team: Team):super().__init__()- insight_vars = InsightVariable.objects.filter(team_id=team.pk, id__in=[v.variableId for v in variables]).all()-- self.insight_variables = list(insight_vars)+ self.insight_variables = insight_variables_by_ids(team.pk, [v.variableId for v in variables])self.variables = variablesself.team = team@@ -52,7 +52,7 @@ class ReplaceVariables(CloningVisitor):variable_definition = matching_insight_variable[0]if matching_variable.isNull:- if variable_definition.type == InsightVariable.Type.LIST and variable_definition.is_multi:+ if variable_definition.type == InsightVariableType.LIST and variable_definition.is_multi:return ast.Array(exprs=[])return ast.Constant(value=None)@@ -62,7 +62,7 @@ class ReplaceVariables(CloningVisitor):else matching_insight_variable[0].default_value)- if variable_definition.type == InsightVariable.Type.LIST:+ if variable_definition.type == InsightVariableType.LIST:if variable_definition.is_multi:# Saved insights keep the scalar value from before a variable was# toggled to multi — wrap it so {variables.x} is always an array.@@ -72,7 +72,7 @@ class ReplaceVariables(CloningVisitor):value = value[0] if value else Noneif (- variable_definition.type == InsightVariable.Type.DATE+ variable_definition.type == InsightVariableType.DATEand isinstance(value, str)and is_relative_date_value(value)):diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.pyindex f697882662a2..582ee446f527 100644--- a/posthog/tasks/usage_report.py+++ b/posthog/tasks/usage_report.py@@ -74,6 +74,7 @@ from products.tasks.backend.facade.billing import (get_task_sandbox_usage_by_team,)from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataJob, ExternalDataSchema+from products.warehouse_sources.backend.facade.types import ExternalDataJobStatus, ExternalDataSchemaStatuslogger = structlog.get_logger(__name__)logging.getLogger(__name__).setLevel(logging.INFO)@@ -2047,7 +2048,7 @@ def get_teams_with_rows_synced_in_period(begin: datetime, end: datetime) -> listfinished_at__gte=begin,finished_at__lte=end,billable=True,- status=ExternalDataJob.Status.COMPLETED,+ status=ExternalDataJobStatus.COMPLETED,).values("team_id").annotate(total=Sum("rows_synced"))@@ -2058,7 +2059,7 @@ def get_teams_with_rows_synced_in_period(begin: datetime, end: datetime) -> listfinished_at__gte=begin,finished_at__lte=end,billable=True,- status=ExternalDataJob.Status.COMPLETED,+ status=ExternalDataJobStatus.COMPLETED,).values("team_id").annotate(total=Sum("rows_synced"))@@ -2075,7 +2076,7 @@ def get_teams_with_free_historical_rows_synced_in_period(begin: datetime, end: dfinished_at__gte=begin,finished_at__lte=end,billable=True,- status=ExternalDataJob.Status.COMPLETED,+ status=ExternalDataJobStatus.COMPLETED,).values("team_id").annotate(total=Sum("rows_synced"))@@ -2086,7 +2087,7 @@ def get_teams_with_free_historical_rows_synced_in_period(begin: datetime, end: dfinished_at__gte=begin,finished_at__lte=end,billable=True,- status=ExternalDataJob.Status.COMPLETED,+ status=ExternalDataJobStatus.COMPLETED,pipeline__created_at__gte=end - timedelta(days=7),).values("team_id")@@ -2128,8 +2129,8 @@ def get_teams_with_active_external_data_schemas_in_period() -> list:return list(ExternalDataSchema.objects.filter(status__in=[- ExternalDataSchema.Status.RUNNING,- ExternalDataSchema.Status.COMPLETED,+ ExternalDataSchemaStatus.RUNNING,+ ExternalDataSchemaStatus.COMPLETED,]).values("team_id")diff --git a/posthog/utils.py b/posthog/utils.pyindex f7770ef03032..24e2377dbb0e 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -82,7 +82,7 @@ if TYPE_CHECKING:from products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.feature_flags.backend.sdk_cache_provider import HyperCacheFlagProvider- from products.product_analytics.backend.facade.models import InsightVariable+ from products.product_analytics.backend.facade.contracts import InsightVariableDefinitionDATERANGE_MAP = {"second": datetime.timedelta(seconds=1),@@ -1843,7 +1843,7 @@ def filters_override_requested_by_client(def variables_override_requested_by_client(request: Optional[Request],dashboard: Optional["Dashboard"],- variables: list["InsightVariable"],+ variables: list["InsightVariableDefinition"],is_shared: bool = False,) -> Optional[dict[str, dict]]:from posthog.auth import SharingAccessTokenAuthentication, SharingPasswordProtectedAuthenticationdiff --git a/products/architecture.md b/products/architecture.mdindex 0e1c5e722e0b..f0b863d09d89 100644--- a/products/architecture.md+++ b/products/architecture.md@@ -112,9 +112,9 @@ There the class crosses for registration only, core drives only the registry's m**The watched-models allowance** is the one further, deliberately temporary exception, for products whose models are load-bearing substrate that core and sibling products consume and cannot yet stop consuming.Two products hold entries.`warehouse_sources`: core HogQL reads its warehouse table/schema/source models to build queryable tables.-`product_analytics`: `Insight`, `InsightVariable` and `InsightViewed`.+`product_analytics`: `Insight` and `InsightVariable`.Core and seven products (alerts, dashboards, surveys, annotations, exports, customer_analytics, pulse) hold ForeignKeys or M2Ms into `Insight` — dashboard tiles, subscriptions and exported assets, sharing configurations, tagged items — and rely on cascade deletes, relation traversal, reverse relations, and queryset-typed access-control filtering that a frozen contract cannot express.-`InsightViewed` crosses for the view-tracking upsert (`update_or_create`) that shared-insight rendering and the demo generator perform.+`InsightVariable` has no consumer left outside the product; its entry survives only because the SQL-variables `ModelViewSet` in `presentation/` needs the class and presentation may reach internals only through the facade, so retiring the entry means converting that viewset off `ModelSerializer` first.The dashboards→product_analytics `DashboardTile.insight` FK and `Dashboard.insights` M2M-through cross into the product against §8's direction rule; that coupling is accepted under this entry until dashboards pursues its own isolation.An allowance product's facade may hand out model classes defined under `backend/models/`.diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 0f239ecda37c..11c212551183 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -32,6 +32,7 @@ from django.db.models import (from django.db.models.functions import Castfrom django.http.response import HttpResponseBasefrom django.shortcuts import get_object_or_404+from django.utils.functional import SimpleLazyObjectfrom django.utils.timezone import nowimport structlog@@ -159,7 +160,8 @@ from products.notifications.backend.facade.api import (create_notification,has_been_dispatched,)-from products.product_analytics.backend.facade.models import Insight, InsightVariable+from products.product_analytics.backend.facade.api import insight_variables_for_team+from products.product_analytics.backend.facade.models import Insightfrom products.product_analytics.backend.presentation.insight import (INCLUDE_DASHBOARDS_PARAMETER,InsightBasicSerializer,@@ -2449,7 +2451,9 @@ class DashboardsViewSet(@tracer.start_as_current_span("DashboardViewSet.get_serializer_context")def get_serializer_context(self) -> dict[str, Any]:context = super().get_serializer_context()- context["insight_variables"] = InsightVariable.objects.filter(team=self.team).all()+ # Deferred: every insight and dashboard response carries this, but only payloads that+ # hold variables read it, so resolving it eagerly costs a query on every list request.+ context["insight_variables"] = SimpleLazyObject(lambda: insight_variables_for_team(self.team.pk))context["compute_surface"] = (ComputeSurface.DASHBOARD_MUTATEif self.action in {"create", "update", "partial_update"}diff --git a/products/data_catalog/evals/seeders.py b/products/data_catalog/evals/seeders.pyindex c26c31e9a7f3..96eaca06951a 100644--- a/products/data_catalog/evals/seeders.py+++ b/products/data_catalog/evals/seeders.py@@ -73,6 +73,7 @@ from products.data_catalog.evals.constants import (from products.data_tools.backend.facade.models import DataWarehouseJoinfrom products.product_analytics.backend.facade.models import Insightfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable+from products.warehouse_sources.backend.facade.types import DataWarehouseTableFormatif TYPE_CHECKING:from products.tasks.backend.facade.agents import CustomPromptSandboxContext@@ -319,7 +320,7 @@ def _warehouse_table(team: Team, name: str, columns: tuple[str, ...]) -> DataWarreturn DataWarehouseTable.objects.create(team=team,name=name,- format=DataWarehouseTable.TableFormat.CSVWithNames,+ format=DataWarehouseTableFormat.CSVWithNames,url_pattern="",credential=None,columns=dict.fromkeys(columns, _STRING_COLUMN),diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query_column_annotation.py b/products/data_modeling/backend/models/datawarehouse_saved_query_column_annotation.pyindex 041f0e42b3c3..dbae56fd4ab2 100644--- a/products/data_modeling/backend/models/datawarehouse_saved_query_column_annotation.py+++ b/products/data_modeling/backend/models/datawarehouse_saved_query_column_annotation.py@@ -3,7 +3,7 @@ from django.db import modelsfrom posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDTModel, sane_repr-from products.warehouse_sources.backend.facade.models import WarehouseColumnAnnotation+from products.warehouse_sources.backend.facade.types import WarehouseColumnAnnotationDescriptionSourceclass DataWarehouseSavedQueryColumnAnnotation(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFields, UUIDTModel):@@ -15,7 +15,7 @@ class DataWarehouseSavedQueryColumnAnnotation(TeamScopedRootMixin, CreatedMetaFi"""# Reuse the physical-table annotation's provenance enum so the two annotation models never drift.- DescriptionSource = WarehouseColumnAnnotation.DescriptionSource+ DescriptionSource = WarehouseColumnAnnotationDescriptionSource# db_constraint=False on the FKs to hot tables (posthog_team, posthog_user): creating a real FK# constraint takes a SHARE ROW EXCLUSIVE lock on the parent, which stalls under write traffic. Teamdiff --git a/products/data_warehouse/backend/direct_clickhouse.py b/products/data_warehouse/backend/direct_clickhouse.pyindex 5ad59800a3a4..978d818a12b3 100644--- a/products/data_warehouse/backend/direct_clickhouse.py+++ b/products/data_warehouse/backend/direct_clickhouse.py@@ -8,6 +8,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Anyfrom products.warehouse_sources.backend.facade.models import ExternalDataSource+from products.warehouse_sources.backend.facade.types import DataWarehouseTableCreatedVia, DataWarehouseTableFormatif TYPE_CHECKING:from products.warehouse_sources.backend.models.table import DataWarehouseTable@@ -45,13 +46,13 @@ def upsert_direct_clickhouse_table(if existing_table is None:return DataWarehouseTable.objects.create(name=schema_name,- format=DataWarehouseTable.TableFormat.Parquet,+ format=DataWarehouseTableFormat.Parquet,team_id=source.team_id,url_pattern=DIRECT_CLICKHOUSE_URL_PATTERN,external_data_source=source,columns=columns,options=options,- created_via=DataWarehouseTable.CreatedVia.SOURCE,+ created_via=DataWarehouseTableCreatedVia.SOURCE,)existing_table.name = schema_namediff --git a/products/data_warehouse/backend/direct_motherduck.py b/products/data_warehouse/backend/direct_motherduck.pyindex 56d0ea6f4f44..624cdb2d96f0 100644--- a/products/data_warehouse/backend/direct_motherduck.py+++ b/products/data_warehouse/backend/direct_motherduck.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Anyfrom products.warehouse_sources.backend.facade.models import ExternalDataSource+from products.warehouse_sources.backend.facade.types import DataWarehouseTableCreatedVia, DataWarehouseTableFormatif TYPE_CHECKING:from products.warehouse_sources.backend.models.table import DataWarehouseTable@@ -52,13 +53,13 @@ def upsert_direct_motherduck_table(if existing_table is None:return DataWarehouseTable.objects.create(name=schema_name,- format=DataWarehouseTable.TableFormat.Parquet,+ format=DataWarehouseTableFormat.Parquet,team_id=source.team_id,url_pattern=DIRECT_MOTHERDUCK_URL_PATTERN,external_data_source=source,columns=columns,options=options,- created_via=DataWarehouseTable.CreatedVia.SOURCE,+ created_via=DataWarehouseTableCreatedVia.SOURCE,)existing_table.name = schema_namediff --git a/products/data_warehouse/backend/direct_mysql.py b/products/data_warehouse/backend/direct_mysql.pyindex 6063c7148a3c..85a492ecaef6 100644--- a/products/data_warehouse/backend/direct_mysql.py+++ b/products/data_warehouse/backend/direct_mysql.py@@ -7,6 +7,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Anyfrom products.warehouse_sources.backend.facade.models import ExternalDataSource+from products.warehouse_sources.backend.facade.types import DataWarehouseTableCreatedVia, DataWarehouseTableFormatif TYPE_CHECKING:from products.warehouse_sources.backend.models.table import DataWarehouseTable@@ -47,13 +48,13 @@ def upsert_direct_mysql_table(if existing_table is None:return DataWarehouseTable.objects.create(name=schema_name,- format=DataWarehouseTable.TableFormat.Parquet,+ format=DataWarehouseTableFormat.Parquet,team_id=source.team_id,url_pattern=DIRECT_MYSQL_URL_PATTERN,external_data_source=source,columns=columns,options=options,- created_via=DataWarehouseTable.CreatedVia.SOURCE,+ created_via=DataWarehouseTableCreatedVia.SOURCE,)existing_table.name = schema_namediff --git a/products/data_warehouse/backend/direct_postgres.py b/products/data_warehouse/backend/direct_postgres.pyindex 8525001a797f..922f5b28729e 100644--- a/products/data_warehouse/backend/direct_postgres.py+++ b/products/data_warehouse/backend/direct_postgres.py@@ -7,6 +7,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Anyfrom products.warehouse_sources.backend.facade.models import ExternalDataSource+from products.warehouse_sources.backend.facade.types import DataWarehouseTableCreatedVia, DataWarehouseTableFormatif TYPE_CHECKING:from products.warehouse_sources.backend.models.table import DataWarehouseTable@@ -55,13 +56,13 @@ def upsert_direct_postgres_table(if existing_table is None:return DataWarehouseTable.objects.create(name=schema_name,- format=DataWarehouseTable.TableFormat.Parquet,+ format=DataWarehouseTableFormat.Parquet,team_id=source.team_id,url_pattern=DIRECT_POSTGRES_URL_PATTERN,external_data_source=source,columns=columns,options=options,- created_via=DataWarehouseTable.CreatedVia.SOURCE,+ created_via=DataWarehouseTableCreatedVia.SOURCE,)existing_table.name = schema_namediff --git a/products/data_warehouse/backend/direct_redshift.py b/products/data_warehouse/backend/direct_redshift.pyindex 3cb65e339451..3cfe56bf8419 100644--- a/products/data_warehouse/backend/direct_redshift.py+++ b/products/data_warehouse/backend/direct_redshift.py@@ -8,6 +8,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Anyfrom products.warehouse_sources.backend.facade.models import ExternalDataSource+from products.warehouse_sources.backend.facade.types import DataWarehouseTableCreatedVia, DataWarehouseTableFormatif TYPE_CHECKING:from products.warehouse_sources.backend.models.table import DataWarehouseTable@@ -56,13 +57,13 @@ def upsert_direct_redshift_table(if existing_table is None:return DataWarehouseTable.objects.create(name=schema_name,- format=DataWarehouseTable.TableFormat.Parquet,+ format=DataWarehouseTableFormat.Parquet,team_id=source.team_id,url_pattern=DIRECT_REDSHIFT_URL_PATTERN,external_data_source=source,columns=columns,options=options,- created_via=DataWarehouseTable.CreatedVia.SOURCE,+ created_via=DataWarehouseTableCreatedVia.SOURCE,)existing_table.name = schema_namediff --git a/products/data_warehouse/backend/direct_snowflake.py b/products/data_warehouse/backend/direct_snowflake.pyindex e98e2df19ca8..adaab65d502e 100644--- a/products/data_warehouse/backend/direct_snowflake.py+++ b/products/data_warehouse/backend/direct_snowflake.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Anyfrom products.warehouse_sources.backend.facade.models import ExternalDataSource+from products.warehouse_sources.backend.facade.types import DataWarehouseTableCreatedVia, DataWarehouseTableFormatif TYPE_CHECKING:from products.warehouse_sources.backend.models.table import DataWarehouseTable@@ -52,13 +53,13 @@ def upsert_direct_snowflake_table(if existing_table is None:return DataWarehouseTable.objects.create(name=schema_name,- format=DataWarehouseTable.TableFormat.Parquet,+ format=DataWarehouseTableFormat.Parquet,team_id=source.team_id,url_pattern=DIRECT_SNOWFLAKE_URL_PATTERN,external_data_source=source,columns=columns,options=options,- created_via=DataWarehouseTable.CreatedVia.SOURCE,+ created_via=DataWarehouseTableCreatedVia.SOURCE,)existing_table.name = schema_namediff --git a/products/data_warehouse/backend/logic/data_load/create_table.py b/products/data_warehouse/backend/logic/data_load/create_table.pyindex 9ae3eee5d43b..744d247b8e4b 100644--- a/products/data_warehouse/backend/logic/data_load/create_table.py+++ b/products/data_warehouse/backend/logic/data_load/create_table.py@@ -19,6 +19,7 @@ from products.data_modeling.backend.facade.models import ()from products.data_warehouse.backend.s3 import get_size_of_folderfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable, asave_datawarehousetable+from products.warehouse_sources.backend.facade.types import DataWarehouseTableCreatedVia, DataWarehouseTableFormatLOGGER = get_logger(__name__)@@ -54,7 +55,7 @@ def _get_or_create_table_for_saved_query(url_pattern=url_pattern,team_id=team_id,queryable_folder=queryable_folder,- created_via=DataWarehouseTable.CreatedVia.MATERIALIZED_VIEW,+ created_via=DataWarehouseTableCreatedVia.MATERIALIZED_VIEW,)saved_query.table = tablesaved_query.save(update_fields=["table", "updated_at"])@@ -100,7 +101,7 @@ async def create_table_from_saved_query(try:table_name = f"{saved_query.name}"url_pattern = saved_query.url_pattern- table_format = DataWarehouseTable.TableFormat.DeltaS3Wrapper+ table_format = DataWarehouseTableFormat.DeltaS3Wrappertable_created = await _get_or_create_table_for_saved_query(saved_query_id=saved_query_id_converted,diff --git a/products/data_warehouse/backend/logic/data_load/service.py b/products/data_warehouse/backend/logic/data_load/service.pyindex a50a8a55b5b5..10770192d83b 100644--- a/products/data_warehouse/backend/logic/data_load/service.py+++ b/products/data_warehouse/backend/logic/data_load/service.py@@ -45,6 +45,8 @@ from posthog.temporal.common.schedule import ()from posthog.temporal.utils import ExternalDataWorkflowInputs+from products.warehouse_sources.backend.facade.types import ExternalDataSchemaStatus, ExternalDataSchemaSyncType+if TYPE_CHECKING:from posthog.models import Team@@ -415,7 +417,7 @@ def is_any_external_data_schema_paused(team_id: int) -> bool:return (ExternalDataSchema.objects.exclude(deleted=True)- .filter(team_id=team_id, status=ExternalDataSchema.Status.PAUSED)+ .filter(team_id=team_id, status=ExternalDataSchemaStatus.PAUSED).exists())@@ -517,7 +519,7 @@ def sync_cdc_extraction_schedule(source: ExternalDataSource, create: bool = Falscdc_schemas = list(ExternalDataSchema.objects.filter(source=source,- sync_type=ExternalDataSchema.SyncType.CDC,+ sync_type=ExternalDataSchemaSyncType.CDC,should_sync=True,).exclude(deleted=True)diff --git a/products/data_warehouse/backend/logic/data_load/source_templates.py b/products/data_warehouse/backend/logic/data_load/source_templates.pyindex f8821f04b53f..bf07059f020e 100644--- a/products/data_warehouse/backend/logic/data_load/source_templates.py+++ b/products/data_warehouse/backend/logic/data_load/source_templates.py@@ -5,7 +5,7 @@ from posthog.temporal.common.logger import get_loggerfrom products.data_tools.backend.models.join import DataWarehouseJoinfrom products.revenue_analytics.backend.joins import ensure_person_joinfrom products.warehouse_sources.backend.facade.models import ExternalDataJob-from products.warehouse_sources.backend.facade.types import ExternalDataSourceType+from products.warehouse_sources.backend.facade.types import ExternalDataJobStatus, ExternalDataSourceTypeLOGGER = get_logger(__name__)@@ -42,7 +42,7 @@ def create_warehouse_templates_for_source(team_id: int, run_id: str) -> None:job: ExternalDataJob = ExternalDataJob.objects.get(pk=run_id)last_successful_job: ExternalDataJob | None = (ExternalDataJob.objects.filter(- team_id=job.team_id, pipeline_id=job.pipeline_id, status=ExternalDataJob.Status.COMPLETED+ team_id=job.team_id, pipeline_id=job.pipeline_id, status=ExternalDataJobStatus.COMPLETED).prefetch_related("pipeline").order_by("-created_at")diff --git a/products/data_warehouse/backend/logic/external_data_source/jobs.py b/products/data_warehouse/backend/logic/external_data_source/jobs.pyindex 2b9ab03f4eb6..b39265714739 100644--- a/products/data_warehouse/backend/logic/external_data_source/jobs.py+++ b/products/data_warehouse/backend/logic/external_data_source/jobs.py@@ -16,6 +16,11 @@ from products.warehouse_sources.backend.facade.pipelines import (TERMINAL_JOB_STATUSES,emit_data_import_app_metrics,)+from products.warehouse_sources.backend.facade.types import (+ ExternalDataJobPipelineVersion,+ ExternalDataJobStatus,+ ExternalDataSchemaStatus,+)JOB_STATUS_TRANSITION_REJECTED = Counter("dwh_job_status_transition_rejected",@@ -34,7 +39,7 @@ FINALIZE_QUEUE_SWEEP_ERRORS = Counter(def update_external_job_status(- job_id: str, team_id: int, status: ExternalDataJob.Status, logger: FilteringBoundLogger, latest_error: str | None+ job_id: str, team_id: int, status: ExternalDataJobStatus, logger: FilteringBoundLogger, latest_error: str | None) -> ExternalDataJob:is_first_terminal_transition = Falsewith transaction.atomic():@@ -46,8 +51,8 @@ def update_external_job_status(# The loader may finish a run after lock takeover force-failed its job; only the# exact takeover sentinel unseals Failed -> Completed — genuine failures stay absorbing.is_takeover_recovery = (- model.status == ExternalDataJob.Status.FAILED- and status == ExternalDataJob.Status.COMPLETED+ model.status == ExternalDataJobStatus.FAILED+ and status == ExternalDataJobStatus.COMPLETEDand model.latest_error == LOCK_TAKEOVER_LATEST_ERROR)@@ -93,8 +98,8 @@ def update_external_job_status(# Scoped save so concurrent F-updates to rows_synced aren't clobbered.model.save(update_fields=update_fields)- if status == ExternalDataJob.Status.FAILED:- schema_status: ExternalDataSchema.Status = ExternalDataSchema.Status.FAILED+ if status == ExternalDataJobStatus.FAILED:+ schema_status: ExternalDataSchemaStatus = ExternalDataSchemaStatus.FAILEDelse:schema_status = status # type: ignore@@ -125,9 +130,9 @@ def update_external_job_status(# has drained the queue by construction, so the common completion path stays queue-free.# on_commit: the queue is a separate Postgres; never call it holding these row locks.should_sweep_queue = (- model.pipeline_version == ExternalDataJob.PipelineVersion.V3+ model.pipeline_version == ExternalDataJobPipelineVersion.V3and status in TERMINAL_JOB_STATUSES- and (status != ExternalDataJob.Status.COMPLETED or is_takeover_recovery)+ and (status != ExternalDataJobStatus.COMPLETED or is_takeover_recovery))if should_sweep_queue:transaction.on_commit(@@ -140,7 +145,7 @@ def update_external_job_status(logger.debug("Emitting app metrics")emit_data_import_app_metrics(model)- if status == ExternalDataJob.Status.FAILED:+ if status == ExternalDataJobStatus.FAILED:try:schedule_external_data_failure_digest(team_id)except Exception:@@ -160,7 +165,7 @@ def _is_cancellation(error: BaseException) -> bool:def _sweep_v3_queue_batches_swallowing_errors(- *, job_id: str, status: ExternalDataJob.Status, logger: FilteringBoundLogger+ *, job_id: str, status: ExternalDataJobStatus, logger: FilteringBoundLogger) -> None:# A queue-DB error must never surface into the caller that just committed the status write.# The stale-stranded reconcile sweep on the loader retries what this misses.@@ -176,7 +181,7 @@ def _sweep_v3_queue_batches_swallowing_errors(capture_exception(e)-def _sweep_v3_queue_batches(*, job_id: str, status: ExternalDataJob.Status, logger: FilteringBoundLogger) -> None:+def _sweep_v3_queue_batches(*, job_id: str, status: ExternalDataJobStatus, logger: FilteringBoundLogger) -> None:"""Fail any still-non-terminal queue batches of a v3 job that just went terminal."""# Deferred: the queue package imports back through this module (see postgres_queue.consumer),# so a top-level import would cycle.diff --git a/products/data_warehouse/backend/logic/external_data_source/notifications.py b/products/data_warehouse/backend/logic/external_data_source/notifications.pyindex 7446974032a5..074f36b2add5 100644--- a/products/data_warehouse/backend/logic/external_data_source/notifications.py+++ b/products/data_warehouse/backend/logic/external_data_source/notifications.py@@ -10,6 +10,7 @@ import structlogfrom posthog.tasks.email import send_external_data_failure_digestfrom products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema+from products.warehouse_sources.backend.facade.types import ExternalDataJobStatus, ExternalDataSchemaStatuslogger = structlog.get_logger(__name__)@@ -54,13 +55,13 @@ def get_team_ids_with_recent_sync_failures(# Schemas are one row each, and their jobs are reachable via the schema_id FK index.unnotified_failed_job = ExternalDataJob.objects.filter(schema_id=OuterRef("id"),- status=ExternalDataJob.Status.FAILED,+ status=ExternalDataJobStatus.FAILED,finished_at__gte=cutoff,).filter(Q(schema__last_error_notified_at__isnull=True) | Q(finished_at__gt=OuterRef("last_error_notified_at")))return list(ExternalDataSchema.objects.exclude(deleted=True).exclude(source__deleted=True)- .filter(status=ExternalDataSchema.Status.FAILED)+ .filter(status=ExternalDataSchemaStatus.FAILED).filter(Exists(unnotified_failed_job) | Q(last_error_notified_at__lt=renotify_cutoff)).values_list("team_id", flat=True).distinct()@@ -85,13 +86,13 @@ def notify_external_data_sync_failures(renotify_cutoff = dt.datetime.now(dt.UTC) - renotify_afternewer_failed_job = ExternalDataJob.objects.filter(schema_id=OuterRef("id"),- status=ExternalDataJob.Status.FAILED,+ status=ExternalDataJobStatus.FAILED,finished_at__gt=OuterRef("last_error_notified_at"),)failing_schemas = list(ExternalDataSchema.objects.exclude(deleted=True).exclude(source__deleted=True)- .filter(team_id=team_id, status=ExternalDataSchema.Status.FAILED)+ .filter(team_id=team_id, status=ExternalDataSchemaStatus.FAILED).filter(Q(last_error_notified_at__isnull=True)| Q(last_error_notified_at__lt=renotify_cutoff)diff --git a/products/data_warehouse/backend/logic/external_data_source/test/test_jobs.py b/products/data_warehouse/backend/logic/external_data_source/test/test_jobs.pyindex 8ad02fd4c7dd..5c517d6aebfb 100644--- a/products/data_warehouse/backend/logic/external_data_source/test/test_jobs.py+++ b/products/data_warehouse/backend/logic/external_data_source/test/test_jobs.py@@ -10,6 +10,11 @@ from posthog.models import Organization, Teamfrom products.data_warehouse.backend.logic.external_data_source.jobs import update_external_job_statusfrom products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema, ExternalDataSourcefrom products.warehouse_sources.backend.facade.pipelines import LOCK_TAKEOVER_LATEST_ERROR+from products.warehouse_sources.backend.facade.types import (+ ExternalDataJobPipelineVersion,+ ExternalDataJobStatus,+ ExternalDataSchemaStatus,+)pytestmark = [pytest.mark.django_db,@@ -17,7 +22,7 @@ pytestmark = [def _create_org_team_source_schema_job(- pipeline_version: ExternalDataJob.PipelineVersion | None = None,+ pipeline_version: ExternalDataJobPipelineVersion | None = None,) -> tuple[Team, ExternalDataSource, ExternalDataSchema, ExternalDataJob]:org = Organization.objects.create(name="Test Org")team = Team.objects.create(organization=org, name="Test Team")@@ -34,7 +39,7 @@ def _create_org_team_source_schema_job(team=team,pipeline=source,schema=schema,- status=ExternalDataJob.Status.RUNNING,+ status=ExternalDataJobStatus.RUNNING,rows_synced=100,pipeline_version=pipeline_version,)@@ -51,17 +56,17 @@ class TestUpdateExternalJobStatus:updated = update_external_job_status(job_id=str(job.id),team_id=team.pk,- status=ExternalDataJob.Status.COMPLETED,+ status=ExternalDataJobStatus.COMPLETED,logger=MagicMock(),latest_error=None,)- assert updated.status == ExternalDataJob.Status.COMPLETED+ assert updated.status == ExternalDataJobStatus.COMPLETEDassert updated.finished_at is not Nonemock_emit.assert_called_once()emitted_job = mock_emit.call_args.args[0]assert emitted_job.id == job.id- assert emitted_job.status == ExternalDataJob.Status.COMPLETED+ assert emitted_job.status == ExternalDataJobStatus.COMPLETEDdef test_retried_terminal_transition_is_idempotent(self):"""A redelivered Kafka message or retried Temporal activity must not@@ -74,7 +79,7 @@ class TestUpdateExternalJobStatus:update_external_job_status(job_id=str(job.id),team_id=team.pk,- status=ExternalDataJob.Status.COMPLETED,+ status=ExternalDataJobStatus.COMPLETED,logger=MagicMock(),latest_error=None,)@@ -83,7 +88,7 @@ class TestUpdateExternalJobStatus:update_external_job_status(job_id=str(job.id),team_id=team.pk,- status=ExternalDataJob.Status.COMPLETED,+ status=ExternalDataJobStatus.COMPLETED,logger=MagicMock(),latest_error=None,)@@ -101,7 +106,7 @@ class TestUpdateExternalJobStatus:updated = update_external_job_status(job_id=str(job.id),team_id=team.pk,- status=ExternalDataJob.Status.RUNNING,+ status=ExternalDataJobStatus.RUNNING,logger=MagicMock(),latest_error=None,)@@ -134,7 +139,7 @@ class TestUpdateExternalJobStatus:update_external_job_status(job_id=str(job.id),team_id=team.pk,- status=ExternalDataJob.Status.COMPLETED,+ status=ExternalDataJobStatus.COMPLETED,logger=MagicMock(),latest_error=None,)@@ -153,12 +158,12 @@ class TestUpdateExternalJobStatus:updated = update_external_job_status(job_id=str(job.id),team_id=team.pk,- status=ExternalDataJob.Status.FAILED,+ status=ExternalDataJobStatus.FAILED,logger=MagicMock(),latest_error="boom",)- assert updated.status == ExternalDataJob.Status.FAILED+ assert updated.status == ExternalDataJobStatus.FAILEDassert updated.finished_at is not Noneassert updated.latest_error == "boom"mock_emit.assert_called_once()@@ -166,11 +171,11 @@ class TestUpdateExternalJobStatus:@pytest.mark.parametrize("status,expect_notify",[- (ExternalDataJob.Status.FAILED, True),- (ExternalDataJob.Status.COMPLETED, False),- (ExternalDataJob.Status.BILLING_LIMIT_REACHED, False),- (ExternalDataJob.Status.BILLING_LIMIT_TOO_LOW, False),- (ExternalDataJob.Status.RUNNING, False),+ (ExternalDataJobStatus.FAILED, True),+ (ExternalDataJobStatus.COMPLETED, False),+ (ExternalDataJobStatus.BILLING_LIMIT_REACHED, False),+ (ExternalDataJobStatus.BILLING_LIMIT_TOO_LOW, False),+ (ExternalDataJobStatus.RUNNING, False),],)def test_failure_notification_only_fires_on_failed_status(self, status, expect_notify):@@ -187,7 +192,7 @@ class TestUpdateExternalJobStatus:team_id=team.pk,status=status,logger=MagicMock(),- latest_error="boom" if status == ExternalDataJob.Status.FAILED else None,+ latest_error="boom" if status == ExternalDataJobStatus.FAILED else None,)if expect_notify:@@ -208,7 +213,7 @@ class TestUpdateExternalJobStatus:update_external_job_status(job_id=str(job.id),team_id=team.pk,- status=ExternalDataJob.Status.FAILED,+ status=ExternalDataJobStatus.FAILED,logger=MagicMock(),latest_error="boom",)@@ -228,19 +233,19 @@ class TestUpdateExternalJobStatus:updated = update_external_job_status(job_id=str(job.id),team_id=team.pk,- status=ExternalDataJob.Status.FAILED,+ status=ExternalDataJobStatus.FAILED,logger=MagicMock(),latest_error="boom",)- assert updated.status == ExternalDataJob.Status.FAILED+ assert updated.status == ExternalDataJobStatus.FAILEDassert updated.finished_at is not None@pytest.mark.parametrize("first_status,rejected_status",[- (ExternalDataJob.Status.COMPLETED, ExternalDataJob.Status.FAILED),- (ExternalDataJob.Status.FAILED, ExternalDataJob.Status.COMPLETED),+ (ExternalDataJobStatus.COMPLETED, ExternalDataJobStatus.FAILED),+ (ExternalDataJobStatus.FAILED, ExternalDataJobStatus.COMPLETED),],)def test_terminal_to_different_terminal_is_rejected(self, first_status, rejected_status):@@ -252,7 +257,7 @@ class TestUpdateExternalJobStatus:team_id=team.pk,status=first_status,logger=MagicMock(),- latest_error="first error" if first_status == ExternalDataJob.Status.FAILED else None,+ latest_error="first error" if first_status == ExternalDataJobStatus.FAILED else None,)result = update_external_job_status(@@ -266,7 +271,7 @@ class TestUpdateExternalJobStatus:assert result.status == first_statusdb_job = ExternalDataJob.objects.get(id=job.id)assert db_job.status == first_status- expected_error = "first error" if first_status == ExternalDataJob.Status.FAILED else None+ expected_error = "first error" if first_status == ExternalDataJobStatus.FAILED else Noneassert db_job.latest_error == expected_errordef test_terminal_error_not_clobbered_by_later_cancelled_finalization(self):@@ -279,7 +284,7 @@ class TestUpdateExternalJobStatus:update_external_job_status(job_id=str(job.id),team_id=team.pk,- status=ExternalDataJob.Status.FAILED,+ status=ExternalDataJobStatus.FAILED,logger=MagicMock(),latest_error="Tenant or user not found",)@@ -287,7 +292,7 @@ class TestUpdateExternalJobStatus:updated = update_external_job_status(job_id=str(job.id),team_id=team.pk,- status=ExternalDataJob.Status.FAILED,+ status=ExternalDataJobStatus.FAILED,logger=MagicMock(),latest_error="Cancelled",)@@ -309,7 +314,7 @@ class TestUpdateExternalJobStatus:update_external_job_status(job_id=str(job.id),team_id=team.pk,- status=ExternalDataJob.Status.FAILED,+ status=ExternalDataJobStatus.FAILED,logger=MagicMock(),latest_error=LOCK_TAKEOVER_LATEST_ERROR,)@@ -317,19 +322,19 @@ class TestUpdateExternalJobStatus:updated = update_external_job_status(job_id=str(job.id),team_id=team.pk,- status=ExternalDataJob.Status.COMPLETED,+ status=ExternalDataJobStatus.COMPLETED,logger=MagicMock(),latest_error=None,)- assert updated.status == ExternalDataJob.Status.COMPLETED+ assert updated.status == ExternalDataJobStatus.COMPLETEDassert updated.latest_error is Noneassert updated.finished_at is not None# Success metrics must be emitted even though the takeover already stamped finished_at.assert mock_emit.call_count == 2- assert mock_emit.call_args.args[0].status == ExternalDataJob.Status.COMPLETED+ assert mock_emit.call_args.args[0].status == ExternalDataJobStatus.COMPLETEDschema.refresh_from_db()- assert schema.status == ExternalDataSchema.Status.COMPLETED+ assert schema.status == ExternalDataSchemaStatus.COMPLETEDassert schema.latest_error is None@pytest.mark.parametrize(@@ -345,7 +350,7 @@ class TestUpdateExternalJobStatus:# the job completes, the schema stays FAILED until the marker is cleared.team, _source, schema, job = _create_org_team_source_schema_job()schema.sync_type_config = halting_marker- schema.status = ExternalDataSchema.Status.FAILED+ schema.status = ExternalDataSchemaStatus.FAILEDschema.latest_error = "The replication slot no longer exists on the source database."schema.save()@@ -353,14 +358,14 @@ class TestUpdateExternalJobStatus:updated = update_external_job_status(job_id=str(job.id),team_id=team.pk,- status=ExternalDataJob.Status.COMPLETED,+ status=ExternalDataJobStatus.COMPLETED,logger=MagicMock(),latest_error=None,)- assert updated.status == ExternalDataJob.Status.COMPLETED+ assert updated.status == ExternalDataJobStatus.COMPLETEDschema.refresh_from_db()- assert schema.status == ExternalDataSchema.Status.FAILED+ assert schema.status == ExternalDataSchemaStatus.FAILEDassert schema.latest_error == "The replication slot no longer exists on the source database."def test_rejected_transition_does_not_overwrite_schema_status(self):@@ -370,24 +375,24 @@ class TestUpdateExternalJobStatus:update_external_job_status(job_id=str(job.id),team_id=team.pk,- status=ExternalDataJob.Status.COMPLETED,+ status=ExternalDataJobStatus.COMPLETED,logger=MagicMock(),latest_error=None,)schema.refresh_from_db()- assert schema.status == ExternalDataSchema.Status.COMPLETED+ assert schema.status == ExternalDataSchemaStatus.COMPLETEDupdate_external_job_status(job_id=str(job.id),team_id=team.pk,- status=ExternalDataJob.Status.FAILED,+ status=ExternalDataJobStatus.FAILED,logger=MagicMock(),latest_error="late failure",)schema.refresh_from_db()- assert schema.status == ExternalDataSchema.Status.COMPLETED+ assert schema.status == ExternalDataSchemaStatus.COMPLETEDassert schema.latest_error is None@@ -395,16 +400,16 @@ class TestFinalizeQueueSweep:@pytest.mark.parametrize("status",[- ExternalDataJob.Status.FAILED,- ExternalDataJob.Status.BILLING_LIMIT_REACHED,- ExternalDataJob.Status.BILLING_LIMIT_TOO_LOW,+ ExternalDataJobStatus.FAILED,+ ExternalDataJobStatus.BILLING_LIMIT_REACHED,+ ExternalDataJobStatus.BILLING_LIMIT_TOO_LOW,],)def test_v3_risky_terminal_sweeps_queue_batches(self, status, django_capture_on_commit_callbacks):# Any non-Completed terminal can leave enqueued batches behind; the sweep must fire# after commit or the batches stay claimable until the retention prune.team, _source, _schema, job = _create_org_team_source_schema_job(- pipeline_version=ExternalDataJob.PipelineVersion.V3+ pipeline_version=ExternalDataJobPipelineVersion.V3)with (@@ -433,11 +438,11 @@ class TestFinalizeQueueSweep:[# A normally-completed v3 run has drained its queue by construction; the fleet's# hottest status write must not gain a cross-DB call.- (ExternalDataJob.PipelineVersion.V3, ExternalDataJob.Status.COMPLETED),+ (ExternalDataJobPipelineVersion.V3, ExternalDataJobStatus.COMPLETED),# v1/v2 have no batch queue at all.- (ExternalDataJob.PipelineVersion.V2, ExternalDataJob.Status.FAILED),- (ExternalDataJob.PipelineVersion.V1, ExternalDataJob.Status.FAILED),- (None, ExternalDataJob.Status.FAILED),+ (ExternalDataJobPipelineVersion.V2, ExternalDataJobStatus.FAILED),+ (ExternalDataJobPipelineVersion.V1, ExternalDataJobStatus.FAILED),+ (None, ExternalDataJobStatus.FAILED),],)def test_no_queue_sweep_for_normal_completion_or_non_v3(@@ -460,7 +465,7 @@ class TestFinalizeQueueSweep:team_id=team.pk,status=status,logger=MagicMock(),- latest_error="boom" if status == ExternalDataJob.Status.FAILED else None,+ latest_error="boom" if status == ExternalDataJobStatus.FAILED else None,)mock_sweep.assert_not_called()@@ -469,7 +474,7 @@ class TestFinalizeQueueSweep:# Failed -> Completed after lock takeover is the one Completed write that can leave# batches behind: a producer may have enqueued after the takeover's own sweep.team, _source, _schema, job = _create_org_team_source_schema_job(- pipeline_version=ExternalDataJob.PipelineVersion.V3+ pipeline_version=ExternalDataJobPipelineVersion.V3)with (@@ -485,7 +490,7 @@ class TestFinalizeQueueSweep:update_external_job_status(job_id=str(job.id),team_id=team.pk,- status=ExternalDataJob.Status.FAILED,+ status=ExternalDataJobStatus.FAILED,logger=MagicMock(),latest_error=LOCK_TAKEOVER_LATEST_ERROR,)@@ -495,19 +500,19 @@ class TestFinalizeQueueSweep:update_external_job_status(job_id=str(job.id),team_id=team.pk,- status=ExternalDataJob.Status.COMPLETED,+ status=ExternalDataJobStatus.COMPLETED,logger=MagicMock(),latest_error=None,)mock_sweep.assert_called_once()- assert mock_sweep.call_args.kwargs["status"] == ExternalDataJob.Status.COMPLETED+ assert mock_sweep.call_args.kwargs["status"] == ExternalDataJobStatus.COMPLETEDdef test_queue_sweep_error_does_not_fail_status_update(self, django_capture_on_commit_callbacks):# The queue is a separate physical Postgres; an outage there must never fail or roll# back the status write the sweep rides on.team, _source, _schema, job = _create_org_team_source_schema_job(- pipeline_version=ExternalDataJob.PipelineVersion.V3+ pipeline_version=ExternalDataJobPipelineVersion.V3)with (@@ -524,14 +529,14 @@ class TestFinalizeQueueSweep:update_external_job_status(job_id=str(job.id),team_id=team.pk,- status=ExternalDataJob.Status.FAILED,+ status=ExternalDataJobStatus.FAILED,logger=MagicMock(),latest_error="boom",)mock_sweep.assert_called_once()db_job = ExternalDataJob.objects.get(id=job.id)- assert db_job.status == ExternalDataJob.Status.FAILED+ assert db_job.status == ExternalDataJobStatus.FAILEDassert db_job.finished_at is not Nonedef test_queue_sweep_cancellation_propagates_instead_of_being_reported(self, django_capture_on_commit_callbacks):@@ -539,7 +544,7 @@ class TestFinalizeQueueSweep:# triggered this status write is itself cancelled mid-sweep. That must propagate so the# caller's own cancellation handling runs, not get swallowed and reported as a sweep bug.team, _source, _schema, job = _create_org_team_source_schema_job(- pipeline_version=ExternalDataJob.PipelineVersion.V3+ pipeline_version=ExternalDataJobPipelineVersion.V3)with (@@ -558,7 +563,7 @@ class TestFinalizeQueueSweep:update_external_job_status(job_id=str(job.id),team_id=team.pk,- status=ExternalDataJob.Status.FAILED,+ status=ExternalDataJobStatus.FAILED,logger=MagicMock(),latest_error="boom",)diff --git a/products/data_warehouse/backend/logic/managed_warehouse_data_status.py b/products/data_warehouse/backend/logic/managed_warehouse_data_status.pyindex cbf362574f63..7bf17235b051 100644--- a/products/data_warehouse/backend/logic/managed_warehouse_data_status.py+++ b/products/data_warehouse/backend/logic/managed_warehouse_data_status.py@@ -16,6 +16,7 @@ from products.managed_warehouse.backend.facade.contracts import ()from products.managed_warehouse.backend.facade.team_state import team_backfill_membershipfrom products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource+from products.warehouse_sources.backend.facade.types import ExternalDataSourceAccessMethodif TYPE_CHECKING:from products.access_control.backend.facade.user_access_control import UserAccessControl@@ -212,7 +213,7 @@ def _schema_table_statuses(source_filter: dict[str, object] = {"team_id": team_id,"deleted": False,- "access_method": ExternalDataSource.AccessMethod.WAREHOUSE,+ "access_method": ExternalDataSourceAccessMethod.WAREHOUSE,}if source_id is not None:source_filter["id"] = source_iddiff --git a/products/data_warehouse/backend/management/commands/backfill_cdc_extraction_schedules.py b/products/data_warehouse/backend/management/commands/backfill_cdc_extraction_schedules.pyindex e37cfe9c82ef..3b0a5366fc78 100644--- a/products/data_warehouse/backend/management/commands/backfill_cdc_extraction_schedules.py+++ b/products/data_warehouse/backend/management/commands/backfill_cdc_extraction_schedules.py@@ -36,6 +36,7 @@ import structlogfrom products.data_warehouse.backend.logic.data_load.service import bulk_sync_cdc_extraction_schedules, cdc_min_intervalfrom products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource+from products.warehouse_sources.backend.facade.types import ExternalDataSchemaSyncType, ExternalDataSourceAccessMethodlogger = structlog.get_logger(__name__)@@ -73,12 +74,12 @@ class Command(BaseCommand):# otherwise resurrect the schedule for a deleted source. Mirrors `sync_cdc_extraction_schedule`.schema_qs = (ExternalDataSchema.objects.filter(- sync_type=ExternalDataSchema.SyncType.CDC,+ sync_type=ExternalDataSchemaSyncType.CDC,should_sync=True,).exclude(deleted=True).exclude(source__deleted=True)- .exclude(source__access_method=ExternalDataSource.AccessMethod.DIRECT)+ .exclude(source__access_method=ExternalDataSourceAccessMethod.DIRECT).select_related("source"))if source_type_filter is not None:diff --git a/products/data_warehouse/backend/management/commands/backfill_discovery_schedules.py b/products/data_warehouse/backend/management/commands/backfill_discovery_schedules.pyindex e7b72e2cdf8a..f34b65ada027 100644--- a/products/data_warehouse/backend/management/commands/backfill_discovery_schedules.py+++ b/products/data_warehouse/backend/management/commands/backfill_discovery_schedules.py@@ -35,7 +35,7 @@ import structlogfrom products.data_warehouse.backend.logic.data_load.service import bulk_sync_discover_schemas_schedulesfrom products.warehouse_sources.backend.facade.models import ExternalDataSourcefrom products.warehouse_sources.backend.facade.source_management import SourceRegistry-from products.warehouse_sources.backend.facade.types import ExternalDataSourceType+from products.warehouse_sources.backend.facade.types import ExternalDataSourceAccessMethod, ExternalDataSourceTypelogger = structlog.get_logger(__name__)@@ -70,7 +70,7 @@ class Command(BaseCommand):# Direct-query sources resolve schemas at query time and opt out of all# background sync — they should not get a discovery schedule.queryset = ExternalDataSource.objects.exclude(deleted=True).exclude(- access_method=ExternalDataSource.AccessMethod.DIRECT+ access_method=ExternalDataSourceAccessMethod.DIRECT)if source_type_filter is not None:queryset = queryset.filter(source_type=source_type_filter)diff --git a/products/data_warehouse/backend/management/commands/migrate_sub_5min_sync_frequencies.py b/products/data_warehouse/backend/management/commands/migrate_sub_5min_sync_frequencies.pyindex 2214c13fdbb0..e29c5183e41a 100644--- a/products/data_warehouse/backend/management/commands/migrate_sub_5min_sync_frequencies.py+++ b/products/data_warehouse/backend/management/commands/migrate_sub_5min_sync_frequencies.py@@ -12,6 +12,7 @@ from products.data_warehouse.backend.logic.data_load.service import (sync_cdc_extraction_schedule,)from products.warehouse_sources.backend.facade.models import ExternalDataSchema+from products.warehouse_sources.backend.facade.types import ExternalDataSchemaSyncTypelogger = structlog.get_logger(__name__)@@ -50,7 +51,7 @@ class Command(BaseCommand):cdc_sources = {schema.source.id: schema.sourcefor schema in live_schemas- if schema.sync_type == ExternalDataSchema.SyncType.CDC+ if schema.sync_type == ExternalDataSchemaSyncType.CDC}for schema in schemas:diff --git a/products/data_warehouse/backend/presentation/views/column_annotation_base.py b/products/data_warehouse/backend/presentation/views/column_annotation_base.pyindex 45c2e85869e5..4838677201b2 100644--- a/products/data_warehouse/backend/presentation/views/column_annotation_base.py+++ b/products/data_warehouse/backend/presentation/views/column_annotation_base.py@@ -7,10 +7,10 @@ from rest_framework.exceptions import PermissionDeniedfrom posthog.api.routing import TeamAndOrgViewSetMixin-from products.warehouse_sources.backend.facade.models import WarehouseColumnAnnotation+from products.warehouse_sources.backend.facade.types import WarehouseColumnAnnotationDescriptionSource# Both annotation models reuse this provenance enum, so the two surfaces never drift.-DescriptionSource = WarehouseColumnAnnotation.DescriptionSource+DescriptionSource = WarehouseColumnAnnotationDescriptionSource# Untrusted-content warning surfaced to MCP clients via the generated tool schema — the description is# user- or source-supplied and must never be treated as instructions.diff --git a/products/data_warehouse/backend/presentation/views/data_warehouse.py b/products/data_warehouse/backend/presentation/views/data_warehouse.pyindex 560c19fd6805..6189ac187ba0 100644--- a/products/data_warehouse/backend/presentation/views/data_warehouse.py+++ b/products/data_warehouse/backend/presentation/views/data_warehouse.py@@ -54,6 +54,11 @@ from products.data_warehouse.backend.presentation.managed_warehouse_monitoring ifrom products.managed_warehouse.backend.presentation import views as managed_warehousefrom products.warehouse_sources.backend.facade.hogql import get_view_or_table_by_namefrom products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema, ExternalDataSource+from products.warehouse_sources.backend.facade.types import (+ ExternalDataJobStatus,+ ExternalDataSchemaStatus,+ ExternalDataSourceStatus,+)from ee.billing.billing_manager import BillingManager@@ -501,14 +506,14 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):external_stats = external_jobs.aggregate(total=Count("id"),- successful=Count("id", filter=Q(status=ExternalDataJob.Status.COMPLETED)),+ successful=Count("id", filter=Q(status=ExternalDataJobStatus.COMPLETED)),failed=Count("id",filter=Q(status__in=[- ExternalDataJob.Status.FAILED,- ExternalDataJob.Status.BILLING_LIMIT_REACHED,- ExternalDataJob.Status.BILLING_LIMIT_REACHED,+ ExternalDataJobStatus.FAILED,+ ExternalDataJobStatus.BILLING_LIMIT_REACHED,+ ExternalDataJobStatus.BILLING_LIMIT_REACHED,]),),@@ -532,14 +537,14 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):external_jobs.annotate(hour=TruncHour("created_at", tzinfo=project_tz)).values("hour").annotate(- successful=Count("id", filter=Q(status=ExternalDataJob.Status.COMPLETED)),+ successful=Count("id", filter=Q(status=ExternalDataJobStatus.COMPLETED)),failed=Count("id",filter=Q(status__in=[- ExternalDataJob.Status.FAILED,- ExternalDataJob.Status.BILLING_LIMIT_REACHED,- ExternalDataJob.Status.BILLING_LIMIT_REACHED,+ ExternalDataJobStatus.FAILED,+ ExternalDataJobStatus.BILLING_LIMIT_REACHED,+ ExternalDataJobStatus.BILLING_LIMIT_REACHED,]),),@@ -572,14 +577,14 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):external_jobs.annotate(day=TruncDate("created_at", tzinfo=project_tz)).values("day").annotate(- successful=Count("id", filter=Q(status=ExternalDataJob.Status.COMPLETED)),+ successful=Count("id", filter=Q(status=ExternalDataJobStatus.COMPLETED)),failed=Count("id",filter=Q(status__in=[- ExternalDataJob.Status.FAILED,- ExternalDataJob.Status.BILLING_LIMIT_REACHED,- ExternalDataJob.Status.BILLING_LIMIT_REACHED,+ ExternalDataJobStatus.FAILED,+ ExternalDataJobStatus.BILLING_LIMIT_REACHED,+ ExternalDataJobStatus.BILLING_LIMIT_REACHED,]),),@@ -609,7 +614,7 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):}running_external_data_jobs = ExternalDataJob.objects.filter(- team_id=self.team_id, status=ExternalDataJob.Status.RUNNING, billable=True, created_at__gte=cutoff_time+ team_id=self.team_id, status=ExternalDataJobStatus.RUNNING, billable=True, created_at__gte=cutoff_time).count()running_modeling_jobs = DataModelingJob.objects.filter(team_id=self.team_id, status=DataModelingJob.Status.RUNNING, created_at__gte=cutoff_time@@ -685,15 +690,14 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):should_sync=True,).filter(- Q(status=ExternalDataSchema.Status.FAILED)- | Q(status=ExternalDataSchema.Status.BILLING_LIMIT_REACHED)+ Q(status=ExternalDataSchemaStatus.FAILED) | Q(status=ExternalDataSchemaStatus.BILLING_LIMIT_REACHED)).select_related("source"))for schema in problem_syncs:sync_status = "failed"- if schema.status == ExternalDataSchema.Status.BILLING_LIMIT_REACHED:+ if schema.status == ExternalDataSchemaStatus.BILLING_LIMIT_REACHED:sync_status = "billing_limit"results.append(@@ -713,7 +717,7 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):error_sources = ExternalDataSource.objects.filter(team_id=self.team_id,deleted=False,- status=ExternalDataSource.Status.ERROR,+ status=ExternalDataSourceStatus.ERROR,)for source in error_sources:diff --git a/products/data_warehouse/backend/presentation/views/table.py b/products/data_warehouse/backend/presentation/views/table.pyindex 9eb94a17803e..90c85287ccde 100644--- a/products/data_warehouse/backend/presentation/views/table.py+++ b/products/data_warehouse/backend/presentation/views/table.py@@ -44,10 +44,14 @@ from products.warehouse_sources.backend.facade.hogql import (from products.warehouse_sources.backend.facade.models import (DataWarehouseCredential,DataWarehouseTable,- ExternalDataSource,validate_warehouse_table_url_pattern,)from products.warehouse_sources.backend.facade.tasks import validate_data_warehouse_table_columns+from products.warehouse_sources.backend.facade.types import (+ DataWarehouseTableCreatedVia,+ DataWarehouseTableFormat,+ ExternalDataSourceAccessMethod,+)from products.warehouse_sources.backend.presentation.views.external_data_source import (SimpleExternalDataSourceSerializers,)@@ -64,15 +68,15 @@ MAX_UPLOAD_REQUEST_BODY_BYTES = MAX_FILE_UPLOAD_SIZE_BYTES + 1024 * 1024# wrap MCP but aren't separately tracked (the CLI, Slack, Max) land on `mcp` alongside plain MCP# clients, and anything without a surface of its own is a plain API caller._EVENT_SOURCE_TO_CREATED_VIA = {- EventSource.WEB: DataWarehouseTable.CreatedVia.WEB,- EventSource.WIZARD: DataWarehouseTable.CreatedVia.WIZARD,- EventSource.POSTHOG_CODE: DataWarehouseTable.CreatedVia.SELF_DRIVING,- EventSource.DESKTOP: DataWarehouseTable.CreatedVia.SELF_DRIVING,- EventSource.MOBILE: DataWarehouseTable.CreatedVia.SELF_DRIVING,- EventSource.MCP: DataWarehouseTable.CreatedVia.MCP,- EventSource.SLACK: DataWarehouseTable.CreatedVia.MCP,- EventSource.CLI: DataWarehouseTable.CreatedVia.MCP,- EventSource.POSTHOG_AI: DataWarehouseTable.CreatedVia.MCP,+ EventSource.WEB: DataWarehouseTableCreatedVia.WEB,+ EventSource.WIZARD: DataWarehouseTableCreatedVia.WIZARD,+ EventSource.POSTHOG_CODE: DataWarehouseTableCreatedVia.SELF_DRIVING,+ EventSource.DESKTOP: DataWarehouseTableCreatedVia.SELF_DRIVING,+ EventSource.MOBILE: DataWarehouseTableCreatedVia.SELF_DRIVING,+ EventSource.MCP: DataWarehouseTableCreatedVia.MCP,+ EventSource.SLACK: DataWarehouseTableCreatedVia.MCP,+ EventSource.CLI: DataWarehouseTableCreatedVia.MCP,+ EventSource.POSTHOG_AI: DataWarehouseTableCreatedVia.MCP,}@@ -81,16 +85,16 @@ def resolve_created_via(request: request.Request) -> str:Read entirely from the transport (auth method, user-agent, MCP headers) rather than from therequest body, so no caller can label its own tables as wizard- or web-created. The values line- up with `ExternalDataSource.CreatedVia`, which reaches the same answer from the other direction:+ up with `ExternalDataSourceCreatedVia`, which reaches the same answer from the other direction:a source takes `created_via` from the body because the MCP server injects it there, thenupgrades that value using this same transport signal."""event_source = get_event_source(request)- created_via = _EVENT_SOURCE_TO_CREATED_VIA.get(event_source, DataWarehouseTable.CreatedVia.API)+ created_via = _EVENT_SOURCE_TO_CREATED_VIA.get(event_source, DataWarehouseTableCreatedVia.API)# Every wizard program shares the `posthog/wizard` user-agent, so a self-driving run is only# distinguishable by the marker it adds to that UA.- if created_via == DataWarehouseTable.CreatedVia.WIZARD and is_wizard_self_driving_program(request):- return DataWarehouseTable.CreatedVia.SELF_DRIVING+ if created_via == DataWarehouseTableCreatedVia.WIZARD and is_wizard_self_driving_program(request):+ return DataWarehouseTableCreatedVia.SELF_DRIVINGreturn created_via@@ -164,7 +168,7 @@ class TableSerializer(UserAccessControlSerializerMixin, serializers.ModelSeriali"(boolean), for CSV files that quote fields with doubled quotes.",)created_via = serializers.ChoiceField(- choices=DataWarehouseTable.CreatedVia.choices,+ choices=DataWarehouseTableCreatedVia.choices,read_only=True,allow_null=True,help_text=(@@ -465,7 +469,7 @@ class TableViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mreturn (queryset.filter(team_id=self.team_id).exclude(deleted=True)- .exclude(external_data_source__access_method=ExternalDataSource.AccessMethod.DIRECT)+ .exclude(external_data_source__access_method=ExternalDataSourceAccessMethod.DIRECT).prefetch_related("created_by", "externaldataschema_set").order_by(self.ordering))@@ -830,7 +834,7 @@ class TableViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mfile_format = request.data.get("format", "CSVWithNames")# Validate format against allowed choices- valid_formats = {c[0] for c in DataWarehouseTable.TableFormat.choices}+ valid_formats = {c[0] for c in DataWarehouseTableFormat.choices}if file_format not in valid_formats:return response.Response(status=status.HTTP_400_BAD_REQUEST,diff --git a/products/data_warehouse/backend/sync_status.py b/products/data_warehouse/backend/sync_status.pyindex 9efa1eea5558..8343702d0ee4 100644--- a/products/data_warehouse/backend/sync_status.py+++ b/products/data_warehouse/backend/sync_status.py@@ -8,6 +8,7 @@ from django.db.models import Qimport humanizefrom products.warehouse_sources.backend.facade.models import ExternalDataSchema+from products.warehouse_sources.backend.facade.types import ExternalDataSchemaStatusif TYPE_CHECKING:from posthog.schema import DataWarehouseSyncWarning@@ -73,7 +74,7 @@ def _build_warning_for_schema(message=message,)- if schema_status == ExternalDataSchema.Status.FAILED:+ if schema_status == ExternalDataSchemaStatus.FAILED:message = f"Last sync of `{table_name}` (from {source_type}) failed."if schema.last_synced_at:message += f" Results reflect data from {humanize.naturaltime(now - _ensure_utc(schema.last_synced_at))}."@@ -83,27 +84,27 @@ def _build_warning_for_schema(# credentials, stack traces) and this message reaches LLM contexts via MCP/Max. The full# error stays in the data warehouse source screen, which is access-scoped.message += " Check the data warehouse source for details."- return build(status=ExternalDataSchema.Status.FAILED, message=message)+ return build(status=ExternalDataSchemaStatus.FAILED, message=message)- if schema_status == ExternalDataSchema.Status.BILLING_LIMIT_REACHED:+ if schema_status == ExternalDataSchemaStatus.BILLING_LIMIT_REACHED:return build(- status=ExternalDataSchema.Status.BILLING_LIMIT_REACHED,+ status=ExternalDataSchemaStatus.BILLING_LIMIT_REACHED,message=(f"Sync of `{table_name}` (from {source_type}) is paused because the data warehouse ""billing limit has been reached. Results may be out of date."),)- if schema_status == ExternalDataSchema.Status.BILLING_LIMIT_TOO_LOW:+ if schema_status == ExternalDataSchemaStatus.BILLING_LIMIT_TOO_LOW:return build(- status=ExternalDataSchema.Status.BILLING_LIMIT_TOO_LOW,+ status=ExternalDataSchemaStatus.BILLING_LIMIT_TOO_LOW,message=(f"Sync of `{table_name}` (from {source_type}) is paused because the configured ""billing limit is too low. Results may be out of date."),)- if schema_status == ExternalDataSchema.Status.PAUSED or not schema.should_sync:+ if schema_status == ExternalDataSchemaStatus.PAUSED or not schema.should_sync:if schema.last_synced_at is None:message = (f"Sync of `{table_name}` (from {source_type}) is paused and hasn't completed a sync yet "@@ -121,7 +122,7 @@ def _build_warning_for_schema(f"Sync of `{table_name}` (from {source_type}) is paused — results are current as of "f"{ago}, but won't update until syncing is re-enabled.")- return build(status=ExternalDataSchema.Status.PAUSED, message=message)+ return build(status=ExternalDataSchemaStatus.PAUSED, message=message)# Enabled and healthy: warn only once data is actually stale (covers RUNNING and idle COMPLETED).last_synced = schema.last_synced_at@@ -129,7 +130,7 @@ def _build_warning_for_schema(return Noneago = humanize.naturaltime(now - _ensure_utc(last_synced))- if schema_status == ExternalDataSchema.Status.RUNNING:+ if schema_status == ExternalDataSchemaStatus.RUNNING:message = (f"`{table_name}` (from {source_type}) last completed syncing {ago}, more than twice its ""configured sync interval. A new sync is in progress but results may be out of date."@@ -139,7 +140,7 @@ def _build_warning_for_schema(f"`{table_name}` (from {source_type}) last synced {ago}, more than twice its configured ""sync interval. Results may be out of date.")- return build(status=schema_status or ExternalDataSchema.Status.RUNNING, message=message)+ return build(status=schema_status or ExternalDataSchemaStatus.RUNNING, message=message)def get_warehouse_sync_warnings(diff --git a/products/data_warehouse/backend/temporal/health_checks/external_data_failure.py b/products/data_warehouse/backend/temporal/health_checks/external_data_failure.pyindex 2797228c4173..5447b6c3a12e 100644--- a/products/data_warehouse/backend/temporal/health_checks/external_data_failure.py+++ b/products/data_warehouse/backend/temporal/health_checks/external_data_failure.py@@ -10,6 +10,7 @@ from posthog.temporal.health_checks.framework import AlertContent, HealthCheck,from posthog.temporal.health_checks.models import HealthCheckResultfrom products.warehouse_sources.backend.facade.models import ExternalDataSchema+from products.warehouse_sources.backend.facade.types import ExternalDataSchemaStatus# A schema carrying a fresh column_type_widened marker is scheduled to reset and re-sync itself on# the next scheduled run (see auto_widen_resync), so its failure is about to clear on its own and@@ -82,9 +83,9 @@ class ExternalDataFailureCheck(HealthCheck):deleted=False,).filter(- Q(status=ExternalDataSchema.Status.FAILED)- | Q(status=ExternalDataSchema.Status.BILLING_LIMIT_REACHED)- | Q(status=ExternalDataSchema.Status.BILLING_LIMIT_TOO_LOW)+ Q(status=ExternalDataSchemaStatus.FAILED)+ | Q(status=ExternalDataSchemaStatus.BILLING_LIMIT_REACHED)+ | Q(status=ExternalDataSchemaStatus.BILLING_LIMIT_TOO_LOW)| Q(should_sync=False, latest_error__isnull=False)).select_related("source")diff --git a/products/demo/backend/logic/legacy/insight_variables_data_generator.py b/products/demo/backend/logic/legacy/insight_variables_data_generator.pyindex 3bed1326927c..07e7255af150 100644--- a/products/demo/backend/logic/legacy/insight_variables_data_generator.py+++ b/products/demo/backend/logic/legacy/insight_variables_data_generator.py@@ -2,7 +2,8 @@ from posthog.models import Personfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile-from products.product_analytics.backend.facade.models import Insight, InsightVariable+from products.product_analytics.backend.facade.api import create_insight_variable+from products.product_analytics.backend.facade.models import Insightfrom .data_generator import DataGenerator@@ -15,17 +16,17 @@ class InsightVariablesDataGenerator(DataGenerator):passdef create_actions_dashboards(self):- var1 = InsightVariable.objects.create(- team=self.team, name="Variable 1", code_name="variable_1", default_value=10, type="Number"+ var1 = create_insight_variable(+ team_id=self.team.pk, name="Variable 1", code_name="variable_1", default_value=10, type="Number")- var2 = InsightVariable.objects.create(- team=self.team, name="Variable 2", code_name="variable_2", default_value=10, type="Number"+ var2 = create_insight_variable(+ team_id=self.team.pk, name="Variable 2", code_name="variable_2", default_value=10, type="Number")- var3 = InsightVariable.objects.create(- team=self.team, name="Variable 3", code_name="variable_3", default_value=10, type="Number"+ var3 = create_insight_variable(+ team_id=self.team.pk, name="Variable 3", code_name="variable_3", default_value=10, type="Number")- var4 = InsightVariable.objects.create(- team=self.team, name="Variable 4", code_name="variable_4", default_value=10, type="Number"+ var4 = create_insight_variable(+ team_id=self.team.pk, name="Variable 4", code_name="variable_4", default_value=10, type="Number")dashboard = Dashboard.objects.create(diff --git a/products/demo/backend/logic/products/hedgebox/matrix.py b/products/demo/backend/logic/products/hedgebox/matrix.pyindex 3611a1af8f3f..67c1bfb9ee4a 100644--- a/products/demo/backend/logic/products/hedgebox/matrix.py+++ b/products/demo/backend/logic/products/hedgebox/matrix.py@@ -81,8 +81,10 @@ from products.experiments.backend.models.experiment import (ExperimentToSavedMetric,)from products.feature_flags.backend.models.feature_flag import FeatureFlag-from products.product_analytics.backend.facade.models import Insight, InsightViewed+from products.product_analytics.backend.facade.api import record_insight_views+from products.product_analytics.backend.facade.models import Insightfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable, get_or_create_datawarehouse_credential+from products.warehouse_sources.backend.facade.types import DataWarehouseTableCreatedVia, DataWarehouseTableFormatfrom .models import HedgeboxAccount, HedgeboxPersonfrom .taxonomy import (@@ -909,27 +911,21 @@ class HedgeboxMatrix(Matrix):last_modified_by=user,)- # InsightViewed- try:- InsightViewed.objects.bulk_create(- (- InsightViewed(- team=team,- user=user,- insight=insight,- last_viewed_at=(- self.now- - dt.timedelta(- days=self.random.randint(0, 3),- minutes=self.random.randint(5, 60),- )- ),+ # Insight views+ record_insight_views(+ team_id=team.pk,+ user_id=user.pk,+ last_viewed_at_by_insight_id={+ insight.pk: (+ self.now+ - dt.timedelta(+ days=self.random.randint(0, 3),+ minutes=self.random.randint(5, 60),)- for insight in Insight.objects.filter(team__project_id=team.project_id)- ),- )- except IntegrityError:- pass # This can happen if demo data generation is re-run for the same project+ )+ for insight in Insight.objects.filter(team__project_id=team.project_id)+ },+ )# Feature flagsdef create_experiment_flag(@@ -2424,7 +2420,7 @@ class HedgeboxMatrix(Matrix):if existing_table:if existing_table.external_data_source is not None:return- existing_table.format = DataWarehouseTable.TableFormat.CSVWithNames+ existing_table.format = DataWarehouseTableFormat.CSVWithNamesexisting_table.url_pattern = url_patternexisting_table.credential = credentialexisting_table.columns = columns@@ -2443,13 +2439,13 @@ class HedgeboxMatrix(Matrix):DataWarehouseTable.objects.create(team=team,name=table_name,- format=DataWarehouseTable.TableFormat.CSVWithNames,+ format=DataWarehouseTableFormat.CSVWithNames,url_pattern=url_pattern,credential=credential,columns=columns,options={"csv_allow_double_quotes": True},created_by=user,- created_via=DataWarehouseTable.CreatedVia.DEMO,+ created_via=DataWarehouseTableCreatedVia.DEMO,)@classmethoddiff --git a/products/endpoints/backend/logic/validation.py b/products/endpoints/backend/logic/validation.pyindex bb70ac36b642..e88dfb1cc972 100644--- a/products/endpoints/backend/logic/validation.py+++ b/products/endpoints/backend/logic/validation.py@@ -39,7 +39,7 @@ from products.endpoints.backend.models import (_breakdown_property_names,can_materialize_query,)-from products.product_analytics.backend.facade.models import InsightVariable+from products.product_analytics.backend.facade.api import insight_variables_by_code_names, insight_variables_by_idsdef validate_data_freshness(data_freshness_seconds: int | None) -> None:@@ -150,7 +150,7 @@ def sync_hogql_query_variables(query: HogQLQuery, team: Team) -> None:continueexisting_variable_ids.append(variable.variableId)- team_variables = InsightVariable.objects.filter(team=team, id__in=existing_variable_ids)+ team_variables = insight_variables_by_ids(team.pk, existing_variable_ids)team_variables_by_id = {str(variable.id): variable for variable in team_variables}synced_variables: dict[str, HogQLVariable] = {}@@ -168,16 +168,16 @@ def sync_hogql_query_variables(query: HogQLQuery, team: Team) -> None:missing_code_names = placeholder_names - existing_code_namesif missing_code_names:- missing_variables = InsightVariable.objects.filter(team=team, code_name__in=missing_code_names)+ missing_variables = insight_variables_by_code_names(team.pk, missing_code_names)- for variable in missing_variables:- if not variable.code_name:+ for definition in missing_variables:+ if not definition.code_name:continue- synced_variables[str(variable.id)] = HogQLVariable(- variableId=str(variable.id),- code_name=variable.code_name,- value=variable.default_value,- isNull=variable.default_value is None,+ synced_variables[str(definition.id)] = HogQLVariable(+ variableId=str(definition.id),+ code_name=definition.code_name,+ value=definition.default_value,+ isNull=definition.default_value is None,)query.variables = synced_variables or None@@ -223,10 +223,7 @@ def validate_variable_placeholders(node: ast.AST, variables: Optional[dict[str,raise ValidationError({"query": f"Variable ID(s) not valid UUIDs: {', '.join(sorted(invalid_uuids))}. "})if valid_uuids:- existing_ids = {- str(id)- for id in InsightVariable.objects.filter(team=team, id__in=valid_uuids).values_list("id", flat=True)- }+ existing_ids = {str(variable.id) for variable in insight_variables_by_ids(team.pk, valid_uuids)}invalid_ids = valid_uuids - existing_idsif invalid_ids:diff --git a/products/endpoints/backend/openapi.py b/products/endpoints/backend/openapi.pyindex b15b5d30dca1..69f605ba6db6 100644--- a/products/endpoints/backend/openapi.py+++ b/products/endpoints/backend/openapi.py@@ -4,14 +4,15 @@ from rest_framework.request import Requestfrom products.endpoints.backend.logic.strategies import InsightEndpointStrategyfrom products.endpoints.backend.models import Endpoint, EndpointVersion, _breakdown_property_names-from products.product_analytics.backend.facade.models import InsightVariable+from products.product_analytics.backend.facade.api import insight_variables_by_ids+from products.product_analytics.backend.facade.enums import InsightVariableTypeINSIGHT_VARIABLE_TYPE_TO_OPENAPI: dict[str, dict] = {- InsightVariable.Type.STRING: {"type": "string"},- InsightVariable.Type.NUMBER: {"type": "number"},- InsightVariable.Type.BOOLEAN: {"type": "boolean"},- InsightVariable.Type.LIST: {"type": "array", "items": {"type": "string"}},- InsightVariable.Type.DATE: {"type": "string", "format": "date"},+ InsightVariableType.STRING: {"type": "string"},+ InsightVariableType.NUMBER: {"type": "number"},+ InsightVariableType.BOOLEAN: {"type": "boolean"},+ InsightVariableType.LIST: {"type": "array", "items": {"type": "string"}},+ InsightVariableType.DATE: {"type": "string", "format": "date"},}@@ -296,10 +297,7 @@ def _build_variables_schema(if variables:variable_ids = list(variables.keys())variable_types = {- str(uid): vtype- for uid, vtype in InsightVariable.objects.filter(team_id=team_id, id__in=variable_ids).values_list(- "id", "type"- )+ str(variable.id): variable.type for variable in insight_variables_by_ids(team_id, variable_ids)}for var_id, var_data in variables.items():diff --git a/products/engineering_analytics/backend/logic/ci_signals_config.py b/products/engineering_analytics/backend/logic/ci_signals_config.pyindex 63dca9e95f98..6a5719d4210a 100644--- a/products/engineering_analytics/backend/logic/ci_signals_config.py+++ b/products/engineering_analytics/backend/logic/ci_signals_config.py@@ -22,6 +22,7 @@ from products.signals.backend.facade.api import set_signal_source_types_enabled,from products.signals.backend.models import SignalSourceConfigfrom products.warehouse_sources.backend.facade.models import ExternalDataSchemafrom products.warehouse_sources.backend.facade.sources import github_schema_repo_endpoint+from products.warehouse_sources.backend.facade.types import ExternalDataSchemaStatusCI_SIGNAL_SOURCE_TYPES = (SOURCE_TYPE_FLAKY_CHECK,@@ -159,9 +160,9 @@ def _sync_status(team: Team, user_access_control: UserAccessControl | None) -> C)required = set(CI_SIGNAL_REQUIRED_SCHEMAS)failure_statuses = {- ExternalDataSchema.Status.FAILED,- ExternalDataSchema.Status.BILLING_LIMIT_REACHED,- ExternalDataSchema.Status.BILLING_LIMIT_TOO_LOW,+ ExternalDataSchemaStatus.FAILED,+ ExternalDataSchemaStatus.BILLING_LIMIT_REACHED,+ ExternalDataSchemaStatus.BILLING_LIMIT_TOO_LOW,}syncing_by_group: dict[tuple[UUID, str], set[str]] = {}completed_by_group: dict[tuple[UUID, str], set[str]] = {}@@ -174,7 +175,7 @@ def _sync_status(team: Team, user_access_control: UserAccessControl | None) -> Creturn CISignalsSyncStatus.FAILEDgroup = (source_id, (repository or "").lower())syncing_by_group.setdefault(group, set()).add(endpoint)- if status == ExternalDataSchema.Status.COMPLETED:+ if status == ExternalDataSchemaStatus.COMPLETED:completed_by_group.setdefault(group, set()).add(endpoint)if not syncing_by_group:return CISignalsSyncStatus.RUNNINGdiff --git a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.pyindex 7741d2e20279..a7e797ecd035 100644--- a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py+++ b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py@@ -70,7 +70,11 @@ from products.warehouse_sources.backend.facade.models import (ExternalDataSource,get_or_create_datawarehouse_credential,)-from products.warehouse_sources.backend.facade.types import ExternalDataSourceType+from products.warehouse_sources.backend.facade.types import (+ DataWarehouseTableFormat,+ ExternalDataSourceStatus,+ ExternalDataSourceType,+)FIXTURE_DIR = Path(__file__).parents[3] / "fixtures"@@ -1091,7 +1095,7 @@ class Command(BaseCommand):team=team,source_id=SEED_SOURCE_ID,connection_id=SEED_SOURCE_ID,- status=ExternalDataSource.Status.COMPLETED,+ status=ExternalDataSourceStatus.COMPLETED,source_type=ExternalDataSourceType.GITHUB,prefix=prefix,job_inputs={"repository": SEED_REPOSITORY},@@ -1137,7 +1141,7 @@ class Command(BaseCommand):"Use a different --prefix (or another team) to seed fixture data.")if existing is not None:- existing.format = DataWarehouseTable.TableFormat.CSVWithNames+ existing.format = DataWarehouseTableFormat.CSVWithNamesexisting.url_pattern = url_patternexisting.credential = credentialexisting.external_data_source = source@@ -1155,7 +1159,7 @@ class Command(BaseCommand):table = DataWarehouseTable.objects.create(team=team,name=table_name,- format=DataWarehouseTable.TableFormat.CSVWithNames,+ format=DataWarehouseTableFormat.CSVWithNames,url_pattern=url_pattern,credential=credential,external_data_source=source,diff --git a/products/engineering_analytics/backend/tests/test_ci_signals.py b/products/engineering_analytics/backend/tests/test_ci_signals.pyindex 4ca607033408..b4c3da390fcf 100644--- a/products/engineering_analytics/backend/tests/test_ci_signals.py+++ b/products/engineering_analytics/backend/tests/test_ci_signals.py@@ -71,7 +71,11 @@ from products.warehouse_sources.backend.facade.models import (ExternalDataSchema,ExternalDataSource,)-from products.warehouse_sources.backend.facade.types import ExternalDataSourceType+from products.warehouse_sources.backend.facade.types import (+ ExternalDataSchemaStatus,+ ExternalDataSourceStatus,+ ExternalDataSourceType,+)from products.warehouse_sources.backend.test.utils import create_data_warehouse_table_from_csv_BY_DESIGN_JOB_NAMES = [entry.split("/", 2)[2] for entry in BY_DESIGN_FAILURES]@@ -288,7 +292,7 @@ class TestDetectForSourceMultiRepo(BaseTest):team=self.team,source_id="gh-multi-snap",connection_id="gh-multi-snap",- status=ExternalDataSource.Status.COMPLETED,+ status=ExternalDataSourceStatus.COMPLETED,source_type=ExternalDataSourceType.GITHUB,prefix="multisnap_",job_inputs={"repositories": ["Acme/one", "Acme/two"]},@@ -309,7 +313,7 @@ class TestDetectForSourceMultiRepo(BaseTest):team=self.team,source_id="gh-multi",connection_id="gh-multi",- status=ExternalDataSource.Status.COMPLETED,+ status=ExternalDataSourceStatus.COMPLETED,source_type=ExternalDataSourceType.GITHUB,prefix="multi_",job_inputs={"repositories": ["Acme/one", "Acme/two", "Acme/three"]},@@ -355,7 +359,7 @@ class TestDetectForSourceMultiRepo(BaseTest):team=self.team,source_id="gh-sib",connection_id="gh-sib",- status=ExternalDataSource.Status.COMPLETED,+ status=ExternalDataSourceStatus.COMPLETED,source_type=ExternalDataSourceType.GITHUB,prefix="sib_",job_inputs={"repositories": ["Acme/one", "Acme/two"]},@@ -562,13 +566,13 @@ class TestCISignalEmissionLedger(BaseTest):class TestSyncStatus(BaseTest):def _github_source_with_schemas(- self, *, source_id: str, repo: str, statuses: dict[str, ExternalDataSchema.Status]+ self, *, source_id: str, repo: str, statuses: dict[str, ExternalDataSchemaStatus]) -> None:source = ExternalDataSource.objects.create(team=self.team,source_id=source_id,connection_id=source_id,- status=ExternalDataSource.Status.COMPLETED,+ status=ExternalDataSourceStatus.COMPLETED,source_type=ExternalDataSourceType.GITHUB,prefix=f"{source_id.replace('-', '')}_",job_inputs={"repositories": [repo]},@@ -586,16 +590,16 @@ class TestSyncStatus(BaseTest):@parameterized.expand([("all_completed", {}, CISignalsSyncStatus.COMPLETED),- ("one_failed", {"workflow_runs": ExternalDataSchema.Status.FAILED}, CISignalsSyncStatus.FAILED),- ("one_running", {"workflow_jobs": ExternalDataSchema.Status.RUNNING}, CISignalsSyncStatus.RUNNING),+ ("one_failed", {"workflow_runs": ExternalDataSchemaStatus.FAILED}, CISignalsSyncStatus.FAILED),+ ("one_running", {"workflow_jobs": ExternalDataSchemaStatus.RUNNING}, CISignalsSyncStatus.RUNNING),])def test_sync_status_resolves_repo_qualified_schema_names(- self, _name: str, overrides: dict[str, ExternalDataSchema.Status], expected: CISignalsSyncStatus+ self, _name: str, overrides: dict[str, ExternalDataSchemaStatus], expected: CISignalsSyncStatus) -> None:# Multi-repo sources qualify schema names; a bare-name match would pin the status at# RUNNING forever and never surface FAILED.- statuses = dict.fromkeys(CI_SIGNAL_REQUIRED_SCHEMAS, ExternalDataSchema.Status.COMPLETED)+ statuses = dict.fromkeys(CI_SIGNAL_REQUIRED_SCHEMAS, ExternalDataSchemaStatus.COMPLETED)statuses.update(overrides)self._github_source_with_schemas(source_id="gh-sync", repo="acme/one", statuses=statuses)assert _sync_status(self.team, None) == expected@@ -604,11 +608,11 @@ class TestSyncStatus(BaseTest):self._github_source_with_schemas(source_id="gh-ci",repo="acme/one",- statuses=dict.fromkeys(CI_SIGNAL_REQUIRED_SCHEMAS, ExternalDataSchema.Status.COMPLETED),+ statuses=dict.fromkeys(CI_SIGNAL_REQUIRED_SCHEMAS, ExternalDataSchemaStatus.COMPLETED),)# An issues-only GitHub source (no CI tables syncing) must not pin the status at RUNNING.self._github_source_with_schemas(- source_id="gh-issues", repo="acme/two", statuses={"issues": ExternalDataSchema.Status.RUNNING}+ source_id="gh-issues", repo="acme/two", statuses={"issues": ExternalDataSchemaStatus.RUNNING})assert _sync_status(self.team, None) == CISignalsSyncStatus.COMPLETEDdiff --git a/products/exports/backend/tasks/image_exporter.py b/products/exports/backend/tasks/image_exporter.pyindex cb577ad9b379..576dc7f075bb 100644--- a/products/exports/backend/tasks/image_exporter.py+++ b/products/exports/backend/tasks/image_exporter.py@@ -42,8 +42,7 @@ from products.exports.backend.tasks.failure_handler import (InvalidExportContext,classify_failure_type,)-from products.product_analytics.backend.facade.api import map_stale_to_latest-from products.product_analytics.backend.facade.models import InsightVariable+from products.product_analytics.backend.facade.api import insight_variables_for_team, map_stale_to_latestlogger = structlog.get_logger(__name__)@@ -548,7 +547,7 @@ def export_image(tile_filters_override = Noneif exported_asset.dashboard:if exported_asset.dashboard.variables:- variables = list(InsightVariable.objects.filter(team=exported_asset.team).all())+ variables = insight_variables_for_team(exported_asset.team_id)dashboard_variables = map_stale_to_latest(exported_asset.dashboard.variables, variables)tile = DashboardTile.objects.filter(dashboard=exported_asset.dashboard,@@ -600,7 +599,7 @@ def export_image(export_context = exported_asset.export_context or {}dashboard_variables = export_context.get("variables_override")if not dashboard_variables and exported_asset.dashboard.variables:- variables = list(InsightVariable.objects.filter(team=exported_asset.team).all())+ variables = insight_variables_for_team(exported_asset.team_id)dashboard_variables = map_stale_to_latest(exported_asset.dashboard.variables, variables)tiles = (diff --git a/products/managed_warehouse/backend/logic/connection.py b/products/managed_warehouse/backend/logic/connection.pyindex aaca1a75dd0c..313013c3bdde 100644--- a/products/managed_warehouse/backend/logic/connection.py+++ b/products/managed_warehouse/backend/logic/connection.py@@ -50,7 +50,13 @@ from products.warehouse_sources.backend.facade.models import (ExternalDataSource,)from products.warehouse_sources.backend.facade.source_management import SourceRegistry-from products.warehouse_sources.backend.facade.types import ExternalDataSourceType, ManagedWarehouseSQLMode+from products.warehouse_sources.backend.facade.types import (+ ExternalDataSourceAccessMethod,+ ExternalDataSourceCreatedVia,+ ExternalDataSourceStatus,+ ExternalDataSourceType,+ ManagedWarehouseSQLMode,+)logger = structlog.get_logger(__name__)@@ -152,7 +158,7 @@ def _dynamic_source_metadata(*, lifecycle_generation: int) -> dict[str, object]:def _set_dynamic_source_auth(source: ExternalDataSource, *, lifecycle_generation: int) -> ExternalDataSource:- source.access_method = ExternalDataSource.AccessMethod.DIRECT+ source.access_method = ExternalDataSourceAccessMethod.DIRECTsource.direct_query_enabled = Truesource.connection_metadata = _dynamic_source_metadata(lifecycle_generation=lifecycle_generation)source.job_inputs = {}@@ -262,13 +268,13 @@ def _ensure_managed_source_locked(connection_id=str(uuid4()),destination_id=str(uuid4()),team_id=team_id,- status=ExternalDataSource.Status.RUNNING,+ status=ExternalDataSourceStatus.RUNNING,source_type=ExternalDataSourceType.POSTGRES,job_inputs={},prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,description=MANAGED_WAREHOUSE_SOURCE_DESCRIPTION,- access_method=ExternalDataSource.AccessMethod.DIRECT,- created_via=ExternalDataSource.CreatedVia.WEB,+ access_method=ExternalDataSourceAccessMethod.DIRECT,+ created_via=ExternalDataSourceCreatedVia.WEB,direct_query_enabled=True,connection_metadata=_dynamic_source_metadata(lifecycle_generation=lifecycle_generation),)@@ -425,7 +431,7 @@ def _reconcile_managed_warehouse_source(*, team_id: int, organization_id: str |.filter(id=source_id,deleted=False,- access_method=ExternalDataSource.AccessMethod.DIRECT,+ access_method=ExternalDataSourceAccessMethod.DIRECT,direct_query_enabled=True,).first()diff --git a/products/managed_warehouse/backend/table_binding.py b/products/managed_warehouse/backend/table_binding.pyindex 18b951d24715..dba0d55e1d30 100644--- a/products/managed_warehouse/backend/table_binding.py+++ b/products/managed_warehouse/backend/table_binding.py@@ -8,6 +8,7 @@ from products.managed_warehouse.backend.common import (duckgres_data_imports_table_name,duckgres_data_modeling_schema,)+from products.warehouse_sources.backend.facade.types import ExternalDataSourceAccessMethodlogger = logging.getLogger(__name__)@@ -69,13 +70,13 @@ def _bind_source_tables(database: Any, team_id: int) -> None:from posthog.hogql.database.direct_postgres_table import DirectPostgresTablefrom posthog.hogql.errors import ResolutionError- from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource+ from products.warehouse_sources.backend.facade.models import DataWarehouseTableschema_name = duckgres_data_imports_schema(team_id)tables = (DataWarehouseTable.objects.queryable().filter(team_id=team_id, external_data_source__isnull=False)- .exclude(external_data_source__access_method=ExternalDataSource.AccessMethod.DIRECT)+ .exclude(external_data_source__access_method=ExternalDataSourceAccessMethod.DIRECT).prefetch_related("externaldataschema_set__source"))for table in tables:diff --git a/products/marketing_analytics/backend/demo/health.py b/products/marketing_analytics/backend/demo/health.pyindex e5120edfd4a2..896ab58b029b 100644--- a/products/marketing_analytics/backend/demo/health.py+++ b/products/marketing_analytics/backend/demo/health.py@@ -18,6 +18,11 @@ from products.warehouse_sources.backend.facade.models import (ExternalDataSchema,ExternalDataSource,)+from products.warehouse_sources.backend.facade.types import (+ ExternalDataJobStatus,+ ExternalDataSchemaStatus,+ ExternalDataSourceStatus,+)# platform -> (schema names, staged state). Only data-preserving states are used# (ok / stale / error / tables_disabled) so every platform still shows cost data@@ -92,7 +97,7 @@ def create_sources(team: Team, *, unconnected: frozenset[str] = UNCONNECTED_PLATteam=team,source_id=f"marketing-demo-{platform.lower()}",connection_id=f"marketing-demo-{platform.lower()}",- status=ExternalDataSource.Status.COMPLETED,+ status=ExternalDataSourceStatus.COMPLETED,source_type=platform,prefix="",)@@ -110,10 +115,10 @@ def stage_schemas_and_jobs(if source is None: # deliberately unconnectedcontinuefor schema_name in schema_names:- schema_status: str | None = ExternalDataSchema.Status.COMPLETED+ schema_status: str | None = ExternalDataSchemaStatus.COMPLETEDshould_sync = Trueif state == "tables_failed" and schema_name == schema_names[-1]:- schema_status = ExternalDataSchema.Status.FAILED+ schema_status = ExternalDataSchemaStatus.FAILEDif state == "tables_disabled" and schema_name == schema_names[-1]:should_sync = Falseif state == "never":@@ -128,17 +133,17 @@ def stage_schemas_and_jobs(last_synced_at=None if state == "never" else now - dt.timedelta(hours=1),)if state == "ok":- _create_job(source, status=ExternalDataJob.Status.COMPLETED, age=dt.timedelta(hours=1), rows_synced=5000)+ _create_job(source, status=ExternalDataJobStatus.COMPLETED, age=dt.timedelta(hours=1), rows_synced=5000)elif state == "stale":- _create_job(source, status=ExternalDataJob.Status.COMPLETED, age=dt.timedelta(hours=30), rows_synced=4200)+ _create_job(source, status=ExternalDataJobStatus.COMPLETED, age=dt.timedelta(hours=30), rows_synced=4200)elif state == "error":- _create_job(source, status=ExternalDataJob.Status.COMPLETED, age=dt.timedelta(days=3), rows_synced=3100)+ _create_job(source, status=ExternalDataJobStatus.COMPLETED, age=dt.timedelta(days=3), rows_synced=3100)_create_job(source,- status=ExternalDataJob.Status.FAILED,+ status=ExternalDataJobStatus.FAILED,age=dt.timedelta(hours=1),latest_error="Authentication failed: refresh token expired",)elif state in ("tables_missing", "tables_failed", "tables_disabled"):- _create_job(source, status=ExternalDataJob.Status.COMPLETED, age=dt.timedelta(hours=2), rows_synced=900)+ _create_job(source, status=ExternalDataJobStatus.COMPLETED, age=dt.timedelta(hours=2), rows_synced=900)# "never": no jobs at alldiff --git a/products/marketing_analytics/backend/management/commands/generate_marketing_demo_data.py b/products/marketing_analytics/backend/management/commands/generate_marketing_demo_data.pyindex 250a88d2c7b5..a6b05ebd4ee2 100644--- a/products/marketing_analytics/backend/management/commands/generate_marketing_demo_data.py+++ b/products/marketing_analytics/backend/management/commands/generate_marketing_demo_data.py@@ -47,6 +47,7 @@ from products.warehouse_sources.backend.facade.models import (ExternalDataSource,get_or_create_datawarehouse_credential,)+from products.warehouse_sources.backend.facade.types import ExternalDataSourceStatusclass Command(BaseCommand):@@ -149,7 +150,7 @@ class Command(BaseCommand):team=team,source_id="marketing-demo-bigquery",connection_id="marketing-demo-bigquery",- status=ExternalDataSource.Status.COMPLETED,+ status=ExternalDataSourceStatus.COMPLETED,source_type="BigQuery",prefix="",)diff --git a/products/marketing_analytics/backend/services/data_source_health.py b/products/marketing_analytics/backend/services/data_source_health.pyindex 34d26154af28..45bbb245c4e5 100644--- a/products/marketing_analytics/backend/services/data_source_health.py+++ b/products/marketing_analytics/backend/services/data_source_health.py@@ -9,6 +9,7 @@ import structlogfrom posthog.schema import NativeMarketingSource+from posthog.dataclasses import frozenfrom posthog.models.team.team import Teamfrom posthog.sync import database_sync_to_async@@ -21,6 +22,7 @@ from products.marketing_analytics.backend.services.native_integrations import (EXTERNAL_SOURCE_TYPE_TO_NATIVE,)from products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema, ExternalDataSource+from products.warehouse_sources.backend.facade.types import ExternalDataJobStatuslogger = structlog.get_logger(__name__)@@ -56,12 +58,12 @@ def _source_schemas_url(source_id: str | None) -> str | None:return f"/data-management/sources/managed-{source_id}/schemas"-@dataclass+@frozenclass RequiredTableStatus:table_name: strpresent: boolshould_sync: bool- status: str | None # ExternalDataSchema.Status value (Completed/Running/Failed/Paused/Cancelled) or None+ status: str | None # ExternalDataSchemaStatus value (Completed/Running/Failed/Paused/Cancelled) or Nonelast_synced_at: datetime | None@@ -297,13 +299,13 @@ def _get_last_job_state(source: ExternalDataSource) -> tuple[datetime | None, stthe failure has been resolved by a subsequent successful sync."""last_completed = (- ExternalDataJob.objects.filter(pipeline=source, status=ExternalDataJob.Status.COMPLETED)+ ExternalDataJob.objects.filter(pipeline=source, status=ExternalDataJobStatus.COMPLETED).order_by("-finished_at").values_list("finished_at", flat=True).first())last_failed = (- ExternalDataJob.objects.filter(pipeline=source, status=ExternalDataJob.Status.FAILED)+ ExternalDataJob.objects.filter(pipeline=source, status=ExternalDataJobStatus.FAILED).exclude(latest_error__isnull=True).order_by("-created_at").values("created_at", "latest_error")@@ -324,7 +326,7 @@ def _get_rows_synced(source: ExternalDataSource) -> tuple[int, int]:in_24h = (ExternalDataJob.objects.filter(pipeline=source,- status=ExternalDataJob.Status.COMPLETED,+ status=ExternalDataJobStatus.COMPLETED,finished_at__gte=now - timedelta(hours=24),).aggregate(total=Sum("rows_synced"))["total"]or 0@@ -332,7 +334,7 @@ def _get_rows_synced(source: ExternalDataSource) -> tuple[int, int]:in_7d = (ExternalDataJob.objects.filter(pipeline=source,- status=ExternalDataJob.Status.COMPLETED,+ status=ExternalDataJobStatus.COMPLETED,finished_at__gte=now - timedelta(days=7),).aggregate(total=Sum("rows_synced"))["total"]or 0diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txtindex e5e62e7fa5b8..5360f2edabeb 100644--- a/products/model_crossing_uses_baseline.txt+++ b/products/model_crossing_uses_baseline.txt@@ -92,18 +92,6 @@ product_analytics.Insight products.pulse.backend.sources.resource_health instancproduct_analytics.Insight products.reminders.backend.constants in-collection 1product_analytics.Insight products.slack_app.backend.slack_link_unfurl instance-single 1product_analytics.Insight products.surveys.backend.api.survey instance-single 1-product_analytics.InsightVariable ee.hogai.chat_agent.sql.mixins instance-many(filter) 1-product_analytics.InsightVariable posthog.api.sharing instance-many(all) 1-product_analytics.InsightVariable posthog.api.sharing instance-many(filter) 1-product_analytics.InsightVariable posthog.hogql.autocomplete instance-many(order_by) 2-product_analytics.InsightVariable posthog.hogql.variables instance-many(all) 1-product_analytics.InsightVariable products.dashboards.backend.api.dashboard instance-many(all) 1-product_analytics.InsightVariable products.demo.backend.logic.legacy.insight_variables_data_generator write(create) 4-product_analytics.InsightVariable products.endpoints.backend.logic.validation instance-many(filter) 2-product_analytics.InsightVariable products.exports.backend.tasks.image_exporter instance-many(all) 2-product_analytics.InsightViewed posthog.api.sharing write(update_or_create) 2-product_analytics.InsightViewed products.demo.backend.logic.products.hedgebox.matrix construct 1-product_analytics.InsightViewed products.demo.backend.logic.products.hedgebox.matrix write(bulk_create) 1surveys.Survey products.early_access_features.backend.management.commands.migrate_enrollments_to_waitlist_surveys get_model 1tasks.CodeInvite products.posthog_ai.eval_harness.harness.demo_data get_model 1tasks.CodeInviteRedemption products.posthog_ai.eval_harness.harness.demo_data get_model 1diff --git a/products/posthog_ai/evals/data_warehouse/seeder.py b/products/posthog_ai/evals/data_warehouse/seeder.pyindex 0bcef0e7e7cf..c24265267da9 100644--- a/products/posthog_ai/evals/data_warehouse/seeder.py+++ b/products/posthog_ai/evals/data_warehouse/seeder.py@@ -39,6 +39,11 @@ from products.posthog_ai.evals.data_warehouse.synthesizer import (SynthTable,WarehouseSchemaSynthesizer,)+from products.warehouse_sources.backend.facade.types import (+ DataWarehouseTableFormat,+ ExternalDataSourceStatus,+ WarehouseColumnAnnotationDescriptionSource,+)if TYPE_CHECKING:from posthog.models.team import Team@@ -71,7 +76,7 @@ def seed_warehouse_schema(context: CustomPromptSandboxContext) -> dict[str, Any]t.name: DataWarehouseTable(team=team,name=t.name,- format=DataWarehouseTable.TableFormat.CSVWithNames,+ format=DataWarehouseTableFormat.CSVWithNames,url_pattern="",columns=t.columns_json(),row_count=t.row_count,@@ -84,7 +89,7 @@ def seed_warehouse_schema(context: CustomPromptSandboxContext) -> dict[str, Any]# 2. Annotations — table-level (column_name="") and column-level — under team_scope.# UUIDTModel ids are generated client-side, so the in-memory models carry valid pks.annotations: list[WarehouseColumnAnnotation] = []- source = WarehouseColumnAnnotation.DescriptionSource.CANONICAL+ source = WarehouseColumnAnnotationDescriptionSource.CANONICALfor t in metadata_tables:model = table_models[t.name]if t.description:@@ -222,7 +227,7 @@ def _create_queryable_needle(team: Team, table: SynthTable) -> dict[str, Any]:team=team,source_id="eval_source",connection_id="eval_connection",- status=ExternalDataSource.Status.COMPLETED,+ status=ExternalDataSourceStatus.COMPLETED,source_type=ExternalDataSourceType.STRIPE,prefix=RETRIEVAL_NEEDLE_PREFIX,)@@ -233,7 +238,7 @@ def _create_queryable_needle(team: Team, table: SynthTable) -> dict[str, Any]:)created = DataWarehouseTable.objects.create(name=name,- format=DataWarehouseTable.TableFormat.CSVWithNames,+ format=DataWarehouseTableFormat.CSVWithNames,team=team,external_data_source=source,credential=credential,diff --git a/products/product_analytics/backend/facade/account_filters.py b/products/product_analytics/backend/facade/account_filters.pynew file mode 100644index 000000000000..10332772d7af--- /dev/null+++ b/products/product_analytics/backend/facade/account_filters.py@@ -0,0 +1,18 @@+"""+Test account filter planning for product_analytics.++Split out of ``facade.api`` because the implementation reaches the HogQL query-runner chain,+which imports ``posthog.hogql.query``. Anything on that chain that reads insight variables would+otherwise import a facade module that is still initializing, so the light data capabilities stay+in ``facade.api`` and this one carries the heavy import.+"""++from typing import Any++from products.product_analytics.backend import insight_test_account_filters+from products.product_analytics.backend.insight_test_account_filters import TestAccountFilterUpdate+++def plan_test_account_filter_update(query: Any, *, enabled: bool) -> TestAccountFilterUpdate:+ """Work out how to set the test account filter on an insight, without touching the stored query."""+ return insight_test_account_filters.plan_test_account_filter_update(query, enabled=enabled)diff --git a/products/product_analytics/backend/facade/api.py b/products/product_analytics/backend/facade/api.pyindex 80b64d6971d0..4ba51c3fb3a6 100644--- a/products/product_analytics/backend/facade/api.py+++ b/products/product_analytics/backend/facade/api.py@@ -4,23 +4,125 @@ Facade for product_analytics.The public entry point core and other products import product-analyticsfunctionality from; ``facade.models`` carries the sanctioned model-classcrossings. Functions here stay thin and delegate to ``backend.logic``.++Saved query variables and insight-view tracking cross as data: callers pass a team id and get+``InsightVariableDefinition`` contracts back, so no caller has to hold ``InsightVariable`` or+``InsightViewed``. Variable reads scope by ``team_id=``, which ``RootTeamMixin`` widens to the+project's root team, because that is the team ``RootTeamMixin.save()`` writes the rows against."""-from typing import Any+from collections.abc import Collection, Mapping+from datetime import datetime+from typing import TYPE_CHECKING, Any+from uuid import UUID++from django.db.models import QuerySet-from products.product_analytics.backend import insight_test_account_filters, logic-from products.product_analytics.backend.insight_test_account_filters import TestAccountFilterUpdate+from products.product_analytics.backend import logic+from products.product_analytics.backend.facade.contracts import InsightVariableDefinition+from products.product_analytics.backend.models.insight import Insightfrom products.product_analytics.backend.models.insight_variable import InsightVariable+if TYPE_CHECKING:+ from posthog.models.user import User+++def _to_variable_definition(variable: InsightVariable) -> InsightVariableDefinition:+ return InsightVariableDefinition(+ id=variable.id,+ name=variable.name,+ code_name=variable.code_name,+ type=variable.type,+ default_value=variable.default_value,+ is_multi=variable.is_multi,+ )+++def insight_variables_for_team(team_id: int) -> list[InsightVariableDefinition]:+ """Every saved query variable on the team's project, ordered by name."""+ return [_to_variable_definition(variable) for variable in logic.insight_variables_for_team(team_id)]+++def insight_variables_by_ids(team_id: int, ids: Collection[str | UUID]) -> list[InsightVariableDefinition]:+ """The team's saved query variables with these ids.++ Ids reach the query as given: a value that is not a UUID raises, rather than being dropped,+ so a caller that accepts unvalidated ids keeps whatever error it raises today.+ """+ return [_to_variable_definition(variable) for variable in logic.insight_variables_by_ids(team_id, ids)]+++def insight_variables_by_code_names(team_id: int, code_names: Collection[str]) -> list[InsightVariableDefinition]:+ """The team's saved query variables with these code names."""+ return [+ _to_variable_definition(variable) for variable in logic.insight_variables_by_code_names(team_id, code_names)+ ]+++def create_insight_variable(+ *,+ team_id: int,+ name: str,+ type: str,+ code_name: str | None = None,+ default_value: Any = None,+ is_multi: bool = False,+) -> InsightVariableDefinition:+ """Add a saved query variable to the team. Runs in the caller's transaction."""+ variable = logic.create_insight_variable(+ team_id=team_id, name=name, type=type, code_name=code_name, default_value=default_value, is_multi=is_multi+ )+ return _to_variable_definition(variable)-def map_stale_to_latest(stale_variables: dict, latest_variables: list[InsightVariable]) -> dict:- """Refresh an insight's stored variables against the team's latest ``InsightVariable`` rows."""- return logic.map_stale_to_latest(stale_variables, latest_variables)+def record_insight_view(*, insight_id: int, team_id: int | None = None, user_id: int | None = None) -> None:+ """Mark an insight as viewed now, moving the timestamp if this viewer already has a row.-def plan_test_account_filter_update(query: Any, *, enabled: bool) -> TestAccountFilterUpdate:- """Work out how to set the test account filter on an insight, without touching the stored query."""- return insight_test_account_filters.plan_test_account_filter_update(query, enabled=enabled)+ Shared and embedded renders have no viewer, so ``team_id`` and ``user_id`` are both optional:+ left out, the view is recorded against the anonymous row for the insight.+ """+ logic.record_insight_view(insight_id=insight_id, team_id=team_id, user_id=user_id)+++def record_insight_views(*, team_id: int, user_id: int, last_viewed_at_by_insight_id: Mapping[int, datetime]) -> None:+ """Record this viewer's view of each insight at the given time, in a single statement.++ A viewer who already has a row for one of the insights keeps it and gets the timestamp moved.+ Runs in the caller's transaction.+ """+ logic.record_insight_views(+ team_id=team_id, user_id=user_id, last_viewed_at_by_insight_id=last_viewed_at_by_insight_id+ )+++def with_last_viewed_at(insights: QuerySet) -> QuerySet:+ """Annotate an insight queryset with ``last_viewed_at``, the most recent view by anyone."""+ return logic.with_last_viewed_at(insights)+++def recently_viewed_insights(*, team_id: int, user_id: int, limit: int) -> list[Insight]:+ """The insights this viewer looked at most recently, newest first, deleted ones left out.++ Each one carries the viewer's own ``last_viewed_at`` rather than the team-wide latest.+ """+ return logic.recently_viewed_insights(team_id=team_id, user_id=user_id, limit=limit)+++def recent_viewers_by_insight(+ *, team_id: int, insight_ids: Collection[int], since: datetime, max_per_insight: int+) -> dict[int, list["User"]]:+ """The people who most recently looked at each of these insights, newest first.++ One query for the whole batch, so a caller rendering a list of insights does not go per-row.+ """+ return logic.recent_viewers_by_insight(+ team_id=team_id, insight_ids=insight_ids, since=since, max_per_insight=max_per_insight+ )+++def map_stale_to_latest(stale_variables: dict, latest_variables: list[InsightVariableDefinition]) -> dict:+ """Refresh an insight's stored variables against the team's latest variable definitions."""+ return logic.map_stale_to_latest(stale_variables, latest_variables)def get_query_specific_instructions(kind: str) -> str:diff --git a/products/product_analytics/backend/facade/contracts.py b/products/product_analytics/backend/facade/contracts.pyindex cdf099420e34..9f69f2330277 100644--- a/products/product_analytics/backend/facade/contracts.py+++ b/products/product_analytics/backend/facade/contracts.py@@ -1,8 +1,35 @@"""Cross-product contracts for product_analytics.-Empty for now: today's crossings are the watched-models allowance classes-(``facade.models``) and the QueryRunner wiring (``facade.queries``). As those-convert to frozen dataclasses per products/architecture.md, the contracts-land here.+Stable, framework-free frozen dataclasses that define what this product hands to the rest of the+codebase. No Django imports.++These use ``pydantic.dataclasses.dataclass`` rather than the stdlib variant — same syntax, same+``is_dataclass()`` compatibility, but with runtime validation on construction, so a mapper that+loses a field surfaces at the facade boundary instead of further down the caller's stack.++``Insight``, ``InsightVariable`` and the QueryRunner wiring still cross as classes+(``facade.models``, ``facade.queries``); as they convert, their contracts land here too."""++from typing import Any+from uuid import UUID++from pydantic.dataclasses import dataclass+++@dataclass(frozen=True)+class InsightVariableDefinition:+ """A saved query variable, as callers outside product analytics read it.++ ``type`` carries an ``InsightVariableType`` value; the field stays a plain ``str`` because+ that enum is a Django ``TextChoices`` and contracts hold no Django imports. Comparing it to+ ``InsightVariableType.LIST`` works either way.+ """++ id: UUID+ name: str+ code_name: str | None+ type: str+ default_value: Any = None+ is_multi: bool = Falsediff --git a/products/product_analytics/backend/facade/enums.py b/products/product_analytics/backend/facade/enums.pynew file mode 100644index 000000000000..021b01392644--- /dev/null+++ b/products/product_analytics/backend/facade/enums.py@@ -0,0 +1,17 @@+"""Enumerations the product_analytics models use.++Consumers that only need a variable type read it from here and do not need the model class. The+model keeps it as a class attribute (``InsightVariable.Type``) so ``choices=`` and existing call+sites are unchanged. In an annotation the class attribute is not a valid type, so annotate with+``InsightVariableType`` directly.+"""++from django.db import models+++class InsightVariableType(models.TextChoices):+ STRING = "String", "String"+ NUMBER = "Number", "Number"+ BOOLEAN = "Boolean", "Boolean"+ LIST = "List", "List"+ DATE = "Date", "Date"diff --git a/products/product_analytics/backend/facade/models.py b/products/product_analytics/backend/facade/models.pyindex 5b6a86143d86..8875f99350b7 100644--- a/products/product_analytics/backend/facade/models.py+++ b/products/product_analytics/backend/facade/models.py@@ -1,19 +1,18 @@"""Model-class wiring for product_analytics.-Re-exports the ``Insight``, ``InsightVariable`` and ``InsightViewed`` model-classes for cross-product consumers under the watched-models allowance-(MODEL_CROSSINGS): dashboards, alerts, exports, sharing and other areas hold-ForeignKeys or M2Ms into ``Insight`` and need ORM semantics (relation-traversal, cascade deletes, queryset-typed access-control filtering, the-view-tracking ``update_or_create``) that a frozen contract cannot express.-Also carries the model-module helper ``generate_insight_filters_hash``, which-takes model instances. The whole model surface (``backend/models/`` and-``backend/migrations/``) stays in the contract-check inputs, so a change to-these classes still runs the full suite.+Re-exports the ``Insight`` and ``InsightVariable`` model classes for consumers under the+watched-models allowance (MODEL_CROSSINGS), together with the model-module helper+``generate_insight_filters_hash``, which takes model instances. Consumers are moving behind+facade functions; see products/architecture.md § Wiring couplings for what a consumer may do+with a crossing class while they do. ``InsightVariable`` has no consumer left outside the+product, but the SQL-variables ``ModelViewSet`` in ``presentation/`` still needs the class, and+presentation may only reach internals through the facade. The whole model surface+(``backend/models/`` and ``backend/migrations/``) stays in the contract-check inputs, so a change+to these classes still runs the full suite."""-from products.product_analytics.backend.models.insight import Insight, InsightViewed, generate_insight_filters_hash+from products.product_analytics.backend.models.insight import Insight, generate_insight_filters_hashfrom products.product_analytics.backend.models.insight_variable import InsightVariable-__all__ = ["Insight", "InsightVariable", "InsightViewed", "generate_insight_filters_hash"]+__all__ = ["Insight", "InsightVariable", "generate_insight_filters_hash"]diff --git a/products/product_analytics/backend/logic.py b/products/product_analytics/backend/logic.pyindex 9376f8407f8a..62cdeecf97e8 100644--- a/products/product_analytics/backend/logic.py+++ b/products/product_analytics/backend/logic.py@@ -1,7 +1,109 @@+from collections.abc import Collection, Mapping+from datetime import datetime+from typing import TYPE_CHECKING, Any+from uuid import UUID++from django.db.models import OuterRef, QuerySet, Subquery+from django.utils.timezone import now++from products.product_analytics.backend.facade.contracts import InsightVariableDefinition+from products.product_analytics.backend.models.insight import Insight, InsightViewedfrom products.product_analytics.backend.models.insight_variable import InsightVariable+if TYPE_CHECKING:+ from posthog.models.user import User++# The columns `InsightVariableDefinition` carries; `values` and `values_query` stay on the row.+VARIABLE_DEFINITION_FIELDS = ("id", "name", "code_name", "type", "default_value", "is_multi")+++def insight_variables_for_team(team_id: int) -> QuerySet[InsightVariable]:+ return InsightVariable.objects.filter(team_id=team_id).only(*VARIABLE_DEFINITION_FIELDS).order_by("name")+++def insight_variables_by_ids(team_id: int, ids: Collection[str | UUID]) -> QuerySet[InsightVariable]:+ return InsightVariable.objects.filter(team_id=team_id, id__in=ids).only(*VARIABLE_DEFINITION_FIELDS)+++def insight_variables_by_code_names(team_id: int, code_names: Collection[str]) -> QuerySet[InsightVariable]:+ return InsightVariable.objects.filter(team_id=team_id, code_name__in=code_names).only(*VARIABLE_DEFINITION_FIELDS)+++def create_insight_variable(+ *, team_id: int, name: str, type: str, code_name: str | None, default_value: Any, is_multi: bool+) -> InsightVariable:+ return InsightVariable.objects.create(+ team_id=team_id, name=name, type=type, code_name=code_name, default_value=default_value, is_multi=is_multi+ )+++def record_insight_view(*, insight_id: int, team_id: int | None, user_id: int | None) -> None:+ InsightViewed.objects.update_or_create(+ insight_id=insight_id, team_id=team_id, user_id=user_id, defaults={"last_viewed_at": now()}+ )+++def record_insight_views(*, team_id: int, user_id: int, last_viewed_at_by_insight_id: Mapping[int, datetime]) -> None:+ InsightViewed.objects.bulk_create(+ [+ InsightViewed(team_id=team_id, user_id=user_id, insight_id=insight_id, last_viewed_at=last_viewed_at)+ for insight_id, last_viewed_at in last_viewed_at_by_insight_id.items()+ ],+ update_conflicts=True,+ unique_fields=["team", "user", "insight"],+ update_fields=["last_viewed_at"],+ )+++def with_last_viewed_at(insights: QuerySet) -> QuerySet:+ last_viewed_at = (+ InsightViewed.objects.filter(insight=OuterRef("pk")).order_by("-last_viewed_at").values("last_viewed_at")[:1]+ )+ return insights.annotate(last_viewed_at=Subquery(last_viewed_at))+++def recently_viewed_insights(*, team_id: int, user_id: int, limit: int) -> list[Insight]:+ views = (+ InsightViewed.objects.filter(team_id=team_id, user_id=user_id)+ .select_related("insight")+ .exclude(insight__deleted=True)+ .only("insight", "last_viewed_at")+ .order_by("-last_viewed_at")[:limit]+ )++ recently_viewed = []+ for view in views:+ insight = view.insight+ insight.last_viewed_at = view.last_viewed_at+ recently_viewed.append(insight)+ return recently_viewed+++def recent_viewers_by_insight(+ *, team_id: int, insight_ids: Collection[int], since: datetime, max_per_insight: int+) -> dict[int, list["User"]]:+ views = (+ InsightViewed.objects.filter(+ team_id=team_id,+ insight_id__in=insight_ids,+ last_viewed_at__gte=since,+ user__isnull=False,+ )+ .select_related("user")+ .order_by("insight_id", "-last_viewed_at")+ )++ viewers_by_insight: dict[int, list[User]] = {}+ for view in views:+ if view.user is None:+ continue+ bucket = viewers_by_insight.setdefault(view.insight_id, [])+ if len(bucket) < max_per_insight:+ bucket.append(view.user)+ return viewers_by_insight+-def map_stale_to_latest(stale_variables: dict, latest_variables: list[InsightVariable]) -> dict:+def map_stale_to_latest(stale_variables: dict, latest_variables: list[InsightVariableDefinition]) -> dict:# Keep the variables in an insight up to date based on variable code names that existcurrent_variables = stale_variablesinsight_variables = latest_variablesdiff --git a/products/product_analytics/backend/models/insight_variable.py b/products/product_analytics/backend/models/insight_variable.pyindex 925998a699d6..847437d8c731 100644--- a/products/product_analytics/backend/models/insight_variable.py+++ b/products/product_analytics/backend/models/insight_variable.py@@ -2,14 +2,11 @@ from django.db import modelsfrom posthog.models.utils import CreatedMetaFields, RootTeamMixin, UpdatedMetaFields, UUIDTModel, sane_repr+from products.product_analytics.backend.facade import enums+class InsightVariable(UUIDTModel, RootTeamMixin, CreatedMetaFields, UpdatedMetaFields):- class Type(models.TextChoices):- STRING = "String", "String"- NUMBER = "Number", "Number"- BOOLEAN = "Boolean", "Boolean"- LIST = "List", "List"- DATE = "Date", "Date"+ Type = enums.InsightVariableTypeteam = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)name = models.CharField(max_length=400)diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.pyindex 8089704ae032..7754e702f8d6 100644--- a/products/product_analytics/backend/presentation/insight.py+++ b/products/product_analytics/backend/presentation/insight.py@@ -8,9 +8,10 @@ from typing import Any, Union, castfrom django.conf import settingsfrom django.core.exceptions import ObjectDoesNotExistfrom django.db import transaction-from django.db.models import Count, F, Max, OuterRef, QuerySet, Subquery+from django.db.models import Count, F, Max, QuerySetfrom django.db.models.query_utils import Qfrom django.http import HttpResponse+from django.utils.functional import SimpleLazyObjectfrom django.utils.text import slugifyfrom django.utils.timezone import now@@ -168,8 +169,17 @@ from products.dashboards.backend.facade.api import (update_insight_dashboard_membership,)from products.dashboards.backend.facade.enums import PrivilegeLevel, RestrictionLevel-from products.product_analytics.backend.facade.api import map_stale_to_latest, plan_test_account_filter_update-from products.product_analytics.backend.facade.models import Insight, InsightVariable, InsightViewed+from products.product_analytics.backend.facade.account_filters import plan_test_account_filter_update+from products.product_analytics.backend.facade.api import (+ insight_variables_for_team,+ map_stale_to_latest,+ recent_viewers_by_insight,+ recently_viewed_insights,+ record_insight_view,+ record_insight_views,+ with_last_viewed_at,+)+from products.product_analytics.backend.facade.models import Insightfrom products.product_analytics.backend.presentation.insight_metadata import (InsightMetadataTimeoutError,generate_insight_metadata,@@ -827,7 +837,7 @@ class InsightSerializer(InsightBasicSerializer):**validated_data,)- InsightViewed.objects.create(team_id=team_id, user=request.user, insight=insight, last_viewed_at=now())+ record_insight_view(insight_id=insight.pk, team_id=team_id, user_id=request.user.pk)if placement is not None:for dashboard in placement.create_tiles(insight):@@ -1833,7 +1843,9 @@ class InsightViewSet(# Sharing-token API refreshes authenticate as the shared-link viewer; expose it under# the same context key the /shared/ page render uses (SharingViewerPageViewSet).context["shared_link_user"] = self.request.user- context["insight_variables"] = InsightVariable.objects.filter(team=self.team).all()+ # Deferred: every insight and dashboard response carries this, but only payloads that+ # hold variables read it, so resolving it eagerly costs a query on every list request.+ context["insight_variables"] = SimpleLazyObject(lambda: insight_variables_for_team(self.team.pk))context["compute_surface"] = (ComputeSurface.INSIGHT_LIST if self.action == "list" else ComputeSurface.INSIGHT_DETAIL)@@ -1886,12 +1898,7 @@ class InsightViewSet(if self.action == "list":queryset = queryset.prefetch_related("tagged_items__tag")- last_viewed_at = (- InsightViewed.objects.filter(insight=OuterRef("pk"))- .order_by("-last_viewed_at")- .values("last_viewed_at")[:1]- )- queryset = queryset.annotate(last_viewed_at=Subquery(last_viewed_at))+ queryset = with_last_viewed_at(queryset)queryset = self._filter_request(self.request, queryset)return self.order_queryset(queryset)@@ -1930,18 +1937,7 @@ class InsightViewSet("""Returns basic details about the last 5 insights viewed by this user. Most recently viewed first."""- insight_queryset = (- InsightViewed.objects.filter(team=self.team, user=cast(User, request.user))- .select_related("insight")- .exclude(insight__deleted=True)- .only("insight", "last_viewed_at")- )-- recently_viewed = []- for rv in insight_queryset.order_by("-last_viewed_at")[:5]:- insight = rv.insight- insight.last_viewed_at = rv.last_viewed_at- recently_viewed.append(insight)+ recently_viewed = recently_viewed_insights(team_id=self.team.pk, user_id=cast(User, request.user).pk, limit=5)response = InsightBasicSerializer(recently_viewed, many=True)return Response(data=response.data, status=status.HTTP_200_OK)@@ -2005,24 +2001,13 @@ class InsightViewSet(insights = list(queryset)# Batch fetch viewers once to avoid N+1 queries- all_viewers = (- InsightViewed.objects.filter(- team=self.team,- insight_id__in=[insight.pk for insight in insights],- last_viewed_at__gte=cutoff_date,- user__isnull=False,- )- .select_related("user")- .order_by("insight_id", "-last_viewed_at")+ viewers_by_insight = recent_viewers_by_insight(+ team_id=self.team.pk,+ insight_ids=[insight.pk for insight in insights],+ since=cutoff_date,+ max_per_insight=3,)- viewers_by_insight: dict[int, list] = {}- for viewer in all_viewers:- iid = viewer.insight_id- bucket = viewers_by_insight.setdefault(iid, [])- if len(bucket) < 3:- bucket.append(viewer.user)-for insight in insights:insight.viewers = viewers_by_insight.get(insight.pk, [])@@ -2557,23 +2542,11 @@ When set, the specified dashboard's filters and date range override will be appl).values_list("id", flat=True))- if visible_insight_ids:- viewed_at = now()- user = cast(User, request.user)- InsightViewed.objects.bulk_create(- [- InsightViewed(- team=self.team,- user=user,- insight_id=insight_id,- last_viewed_at=viewed_at,- )- for insight_id in visible_insight_ids- ],- update_conflicts=True,- unique_fields=["team", "user", "insight"],- update_fields=["last_viewed_at"],- )+ record_insight_views(+ team_id=self.team.pk,+ user_id=cast(User, request.user).pk,+ last_viewed_at_by_insight_id=dict.fromkeys(visible_insight_ids, now()),+ )return Response(status=status.HTTP_201_CREATED)diff --git a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambrindex 56e4d75f5945..40cae6b2ee7b 100644--- a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr+++ b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr@@ -628,6 +628,22 @@'''# ---# name: TestInsight.test_listing_insights_does_not_nplus1.12+ '''+ SELECT "posthog_insightviewed"."id",+ "posthog_insightviewed"."team_id",+ "posthog_insightviewed"."user_id",+ "posthog_insightviewed"."insight_id",+ "posthog_insightviewed"."last_viewed_at"+ FROM "posthog_insightviewed"+ WHERE ("posthog_insightviewed"."insight_id" = 99999+ AND "posthog_insightviewed"."team_id" = 99999+ AND "posthog_insightviewed"."user_id" = 99999)+ LIMIT 21+ FOR+ UPDATE+ '''+# ---+# name: TestInsight.test_listing_insights_does_not_nplus1.13'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -654,7 +670,7 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestInsight.test_listing_insights_does_not_nplus1.13+# name: TestInsight.test_listing_insights_does_not_nplus1.14'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -681,26 +697,27 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestInsight.test_listing_insights_does_not_nplus1.14+# name: TestInsight.test_listing_insights_does_not_nplus1.15'''- SELECT "posthog_insightvariable"."created_by_id",- "posthog_insightvariable"."created_at",- "posthog_insightvariable"."updated_at",- "posthog_insightvariable"."id",- "posthog_insightvariable"."team_id",+ SELECT "posthog_insightvariable"."id","posthog_insightvariable"."name","posthog_insightvariable"."code_name","posthog_insightvariable"."type","posthog_insightvariable"."default_value",- "posthog_insightvariable"."values",- "posthog_insightvariable"."is_multi",- "posthog_insightvariable"."values_query",- "posthog_insightvariable"."values_query_connection_id"+ "posthog_insightvariable"."is_multi"FROM "posthog_insightvariable"- WHERE "posthog_insightvariable"."team_id" = 99999+ INNER JOIN "posthog_team" ON ("posthog_insightvariable"."team_id" = "posthog_team"."id")+ WHERE ("posthog_insightvariable"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_insightvariable"."team_id" = 99999))+ ORDER BY "posthog_insightvariable"."name" ASC'''# ----# name: TestInsight.test_listing_insights_does_not_nplus1.15+# name: TestInsight.test_listing_insights_does_not_nplus1.16'''SELECT "posthog_dashboardtile"."dashboard_id" AS "dashboard_id"FROM "posthog_dashboardtile"@@ -711,7 +728,7 @@AND "posthog_dashboardtile"."insight_id" = 99999)'''# ----# name: TestInsight.test_listing_insights_does_not_nplus1.16+# name: TestInsight.test_listing_insights_does_not_nplus1.17'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -744,7 +761,7 @@5 /* ... */))'''# ----# name: TestInsight.test_listing_insights_does_not_nplus1.17+# name: TestInsight.test_listing_insights_does_not_nplus1.18'''SELECT "posthog_tag"."name" AS "tag__name"FROM "posthog_taggeditem"@@ -752,59 +769,13 @@WHERE "posthog_taggeditem"."insight_id" = 99999'''# ----# name: TestInsight.test_listing_insights_does_not_nplus1.18+# name: TestInsight.test_listing_insights_does_not_nplus1.19'''SELECT COUNT(*) AS "__count"FROM "posthog_dashboarditem"WHERE NOT ("posthog_dashboarditem"."deleted")'''# ----# name: TestInsight.test_listing_insights_does_not_nplus1.19- '''- SELECT "posthog_user"."id",- "posthog_user"."password",- "posthog_user"."last_login",- "posthog_user"."first_name",- "posthog_user"."last_name",- "posthog_user"."is_staff",- "posthog_user"."date_joined",- "posthog_user"."uuid",- "posthog_user"."current_organization_id",- "posthog_user"."current_team_id",- "posthog_user"."email",- "posthog_user"."pending_email",- "posthog_user"."distinct_id",- "posthog_user"."is_email_verified",- "posthog_user"."credentials_reviewed_at",- "posthog_user"."requested_2fa_reset_at",- "posthog_user"."has_seen_product_intro_for",- "posthog_user"."strapi_id",- "posthog_user"."is_active",- "posthog_user"."role_at_organization",- "posthog_user"."theme_mode",- "posthog_user"."partial_notification_settings",- "posthog_user"."anonymize_data",- "posthog_user"."allow_impersonation",- "posthog_user"."toolbar_mode",- "posthog_user"."hedgehog_config",- "posthog_user"."allow_sidebar_suggestions",- "posthog_user"."shortcut_position",- "posthog_user"."passkeys_enabled_for_2fa",- "posthog_user"."hide_mcp_hints",- "posthog_user"."ui_configuration",- "posthog_user"."onboarding_skipped_at",- "posthog_user"."onboarding_skipped_reason",- "posthog_user"."onboarding_skipped_organization_id",- "posthog_user"."onboarding_delegated_to_invite_id",- "posthog_user"."onboarding_delegated_to_organization_id",- "posthog_user"."onboarding_delegation_accepted_at",- "posthog_user"."events_column_config",- "posthog_user"."email_opt_in"- FROM "posthog_user"- WHERE ("posthog_user"."is_active"- AND "posthog_user"."id" = 99999)- '''-# ---# name: TestInsight.test_listing_insights_does_not_nplus1.2'''SELECT "posthog_team"."id",@@ -947,6 +918,52 @@'''# ---# name: TestInsight.test_listing_insights_does_not_nplus1.20+ '''+ SELECT "posthog_user"."id",+ "posthog_user"."password",+ "posthog_user"."last_login",+ "posthog_user"."first_name",+ "posthog_user"."last_name",+ "posthog_user"."is_staff",+ "posthog_user"."date_joined",+ "posthog_user"."uuid",+ "posthog_user"."current_organization_id",+ "posthog_user"."current_team_id",+ "posthog_user"."email",+ "posthog_user"."pending_email",+ "posthog_user"."distinct_id",+ "posthog_user"."is_email_verified",+ "posthog_user"."credentials_reviewed_at",+ "posthog_user"."requested_2fa_reset_at",+ "posthog_user"."has_seen_product_intro_for",+ "posthog_user"."strapi_id",+ "posthog_user"."is_active",+ "posthog_user"."role_at_organization",+ "posthog_user"."theme_mode",+ "posthog_user"."partial_notification_settings",+ "posthog_user"."anonymize_data",+ "posthog_user"."allow_impersonation",+ "posthog_user"."toolbar_mode",+ "posthog_user"."hedgehog_config",+ "posthog_user"."allow_sidebar_suggestions",+ "posthog_user"."shortcut_position",+ "posthog_user"."passkeys_enabled_for_2fa",+ "posthog_user"."hide_mcp_hints",+ "posthog_user"."ui_configuration",+ "posthog_user"."onboarding_skipped_at",+ "posthog_user"."onboarding_skipped_reason",+ "posthog_user"."onboarding_skipped_organization_id",+ "posthog_user"."onboarding_delegated_to_invite_id",+ "posthog_user"."onboarding_delegated_to_organization_id",+ "posthog_user"."onboarding_delegation_accepted_at",+ "posthog_user"."events_column_config",+ "posthog_user"."email_opt_in"+ FROM "posthog_user"+ WHERE ("posthog_user"."is_active"+ AND "posthog_user"."id" = 99999)+ '''+# ---+# name: TestInsight.test_listing_insights_does_not_nplus1.21'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -991,7 +1008,7 @@LIMIT 21'''# ----# name: TestInsight.test_listing_insights_does_not_nplus1.21+# name: TestInsight.test_listing_insights_does_not_nplus1.22'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -1132,7 +1149,7 @@LIMIT 21'''# ----# name: TestInsight.test_listing_insights_does_not_nplus1.22+# name: TestInsight.test_listing_insights_does_not_nplus1.23'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -1186,7 +1203,7 @@LIMIT 21'''# ----# name: TestInsight.test_listing_insights_does_not_nplus1.23+# name: TestInsight.test_listing_insights_does_not_nplus1.24'''SELECT "ee_accesscontrol"."id","ee_accesscontrol"."team_id",@@ -1211,7 +1228,7 @@AND "ee_accesscontrol"."team_id" = 99999))'''# ----# name: TestInsight.test_listing_insights_does_not_nplus1.24+# name: TestInsight.test_listing_insights_does_not_nplus1.25'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -1263,7 +1280,7 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestInsight.test_listing_insights_does_not_nplus1.25+# name: TestInsight.test_listing_insights_does_not_nplus1.26'''SELECT COUNT(*) AS "__count"FROM "posthog_dashboarditem"@@ -1272,7 +1289,7 @@AND NOT ("posthog_dashboarditem"."deleted"))'''# ----# name: TestInsight.test_listing_insights_does_not_nplus1.26+# name: TestInsight.test_listing_insights_does_not_nplus1.27'''SELECT "posthog_dashboarditem"."id","posthog_dashboarditem"."name",@@ -1461,7 +1478,7 @@LIMIT 100'''# ----# name: TestInsight.test_listing_insights_does_not_nplus1.27+# name: TestInsight.test_listing_insights_does_not_nplus1.28'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -1479,29 +1496,6 @@5 /* ... */))'''# ----# name: TestInsight.test_listing_insights_does_not_nplus1.28- '''- SELECT "posthog_taggeditem"."id",- "posthog_taggeditem"."tag_id",- "posthog_taggeditem"."dashboard_id",- "posthog_taggeditem"."insight_id",- "posthog_taggeditem"."event_definition_id",- "posthog_taggeditem"."property_definition_id",- "posthog_taggeditem"."action_id",- "posthog_taggeditem"."feature_flag_id",- "posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id",- "posthog_taggeditem"."account_id",- "posthog_taggeditem"."endpoint_id",- "posthog_taggeditem"."replay_scanner_id"- FROM "posthog_taggeditem"- WHERE "posthog_taggeditem"."insight_id" IN (1,- 2,- 3,- 4,- 5 /* ... */)- '''-# ---# name: TestInsight.test_listing_insights_does_not_nplus1.29'''SELECT "posthog_taggeditem"."id",@@ -1516,12 +1510,8 @@"posthog_taggeditem"."ticket_id","posthog_taggeditem"."account_id","posthog_taggeditem"."endpoint_id",- "posthog_taggeditem"."replay_scanner_id",- "posthog_tag"."id",- "posthog_tag"."name",- "posthog_tag"."team_id"+ "posthog_taggeditem"."replay_scanner_id"FROM "posthog_taggeditem"- INNER JOIN "posthog_tag" ON ("posthog_taggeditem"."tag_id" = "posthog_tag"."id")WHERE "posthog_taggeditem"."insight_id" IN (1,2,3,@@ -1583,6 +1573,33 @@LIMIT 21'''# ---+# name: TestInsight.test_listing_insights_does_not_nplus1.30+ '''+ SELECT "posthog_taggeditem"."id",+ "posthog_taggeditem"."tag_id",+ "posthog_taggeditem"."dashboard_id",+ "posthog_taggeditem"."insight_id",+ "posthog_taggeditem"."event_definition_id",+ "posthog_taggeditem"."property_definition_id",+ "posthog_taggeditem"."action_id",+ "posthog_taggeditem"."feature_flag_id",+ "posthog_taggeditem"."experiment_saved_metric_id",+ "posthog_taggeditem"."ticket_id",+ "posthog_taggeditem"."account_id",+ "posthog_taggeditem"."endpoint_id",+ "posthog_taggeditem"."replay_scanner_id",+ "posthog_tag"."id",+ "posthog_tag"."name",+ "posthog_tag"."team_id"+ FROM "posthog_taggeditem"+ INNER JOIN "posthog_tag" ON ("posthog_taggeditem"."tag_id" = "posthog_tag"."id")+ WHERE "posthog_taggeditem"."insight_id" IN (1,+ 2,+ 3,+ 4,+ 5 /* ... */)+ '''+# ---# name: TestInsight.test_listing_insights_does_not_nplus1.4'''SELECT "ee_accesscontrol"."id",diff --git a/products/product_analytics/backend/tests/api/test_insight.py b/products/product_analytics/backend/tests/api/test_insight.pyindex 76e4e18e7fba..95457449e325 100644--- a/products/product_analytics/backend/tests/api/test_insight.py+++ b/products/product_analytics/backend/tests/api/test_insight.py@@ -61,7 +61,8 @@ from products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.facade.access import DashboardAccessMethodfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile, Text-from products.product_analytics.backend.facade.models import Insight, InsightVariable, InsightViewed+from products.product_analytics.backend.facade.models import Insight, InsightVariable+from products.product_analytics.backend.models.insight import InsightViewedclass TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):diff --git a/products/product_analytics/backend/tests/api/test_insight_variable.py b/products/product_analytics/backend/tests/api/test_insight_variable.pyindex a463e519c531..6a2f751236b9 100644--- a/products/product_analytics/backend/tests/api/test_insight_variable.py+++ b/products/product_analytics/backend/tests/api/test_insight_variable.py@@ -10,6 +10,7 @@ from rest_framework.exceptions import PermissionDeniedfrom posthog.auth import SharingAccessTokenAuthenticationfrom products.product_analytics.backend.facade.api import map_stale_to_latest+from products.product_analytics.backend.facade.contracts import InsightVariableDefinitionfrom products.product_analytics.backend.facade.models import InsightVariablefrom products.product_analytics.backend.presentation.insight_variable import (InsightVariableSerializer,@@ -337,11 +338,8 @@ class TestInsightVariableSerializer(TestCase):class TestMapStaleToLatest(TestCase):- def _make_variable(self, code_name: str) -> InsightVariable:- var = MagicMock(spec=InsightVariable)- var.id = uuid4()- var.code_name = code_name- return var+ def _make_variable(self, code_name: str) -> InsightVariableDefinition:+ return InsightVariableDefinition(id=uuid4(), name=code_name, code_name=code_name, type="String")@parameterized.expand([diff --git a/products/product_analytics/backend/tests/test_facade.py b/products/product_analytics/backend/tests/test_facade.pynew file mode 100644index 000000000000..75aa36d66d48--- /dev/null+++ b/products/product_analytics/backend/tests/test_facade.py@@ -0,0 +1,56 @@+from posthog.test.base import BaseTest++from django.utils.timezone import now++from parameterized import parameterized++from posthog.models.team import Team++from products.product_analytics.backend.facade.api import insight_variables_for_team, record_insight_view+from products.product_analytics.backend.models.insight import Insight, InsightViewed+from products.product_analytics.backend.models.insight_variable import InsightVariable+++class TestInsightVariableReads(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.variable = InsightVariable.objects.create(+ team=self.team, name="Country", code_name="country", type="String"+ )++ @parameterized.expand([("root_team",), ("environment_team",)])+ def test_variables_are_visible_from_the_whole_project(self, which_team: str) -> None:+ team = self.team+ if which_team == "environment_team":+ team = Team.objects.create(organization=self.organization, project=self.project, parent_team=self.team)++ assert [variable.code_name for variable in insight_variables_for_team(team.pk)] == ["country"]++ def test_a_team_in_another_project_sees_none_of_them(self) -> None:+ other_team = Team.objects.create(organization=self.organization)++ assert insight_variables_for_team(other_team.pk) == []+++class TestRecordInsightView(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.insight = Insight.objects.create(team=self.team, name="Signups")++ @parameterized.expand([("anonymous", False), ("identified", True)])+ def test_viewing_twice_moves_the_timestamp_instead_of_adding_a_row(self, _name: str, identified: bool) -> None:+ viewer = {"team_id": self.team.pk, "user_id": self.user.pk} if identified else {}++ record_insight_view(insight_id=self.insight.pk, **viewer)+ first = InsightViewed.objects.get(insight_id=self.insight.pk)+ record_insight_view(insight_id=self.insight.pk, **viewer)++ assert InsightViewed.objects.filter(insight_id=self.insight.pk).count() == 1+ assert InsightViewed.objects.get(insight_id=self.insight.pk).last_viewed_at >= first.last_viewed_at++ def test_an_anonymous_view_does_not_replace_a_users_view(self) -> None:+ InsightViewed.objects.create(team=self.team, user=self.user, insight=self.insight, last_viewed_at=now())++ record_insight_view(insight_id=self.insight.pk)++ assert InsightViewed.objects.filter(insight_id=self.insight.pk).count() == 2diff --git a/products/signals/backend/management/commands/reset_signals_self_driving.py b/products/signals/backend/management/commands/reset_signals_self_driving.pyindex 3ceb3248ae4d..ce8a8c57fb98 100644--- a/products/signals/backend/management/commands/reset_signals_self_driving.py+++ b/products/signals/backend/management/commands/reset_signals_self_driving.py@@ -20,6 +20,7 @@ from products.signals.backend.models import ()from products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIXfrom products.skills.backend.models.skills import LLMSkill, LLMSkillOwner+from products.warehouse_sources.backend.facade.types import ExternalDataSourceCreatedVia# Seed tag stamped on canonical scouts + the `authoring-scouts` companion; this DEBUG# reset preserves tagged rows. Not a perfect canonical marker (`_scout_origin` also checks the@@ -263,7 +264,7 @@ class Command(BaseCommand):ExternalDataSource.objects.filter(team=team,source_type__in=dwh_source_types,- created_via=ExternalDataSource.CreatedVia.MCP,+ created_via=ExternalDataSourceCreatedVia.MCP,deleted=False,))diff --git a/products/signals/backend/scout_harness/profile/builders.py b/products/signals/backend/scout_harness/profile/builders.pyindex fcf19a897f6b..65ae5f5cad5a 100644--- a/products/signals/backend/scout_harness/profile/builders.py+++ b/products/signals/backend/scout_harness/profile/builders.py@@ -64,7 +64,8 @@ from products.signals.backend.scout_harness.config_registry import live_scout_skfrom products.signals.backend.scout_harness.profile.schema import Inventoryfrom products.signals.backend.scout_harness.team_limits import withheld_skills_for_teamfrom products.surveys.backend.models import Survey-from products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema, ExternalDataSource+from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource+from products.warehouse_sources.backend.facade.types import ExternalDataJobStatusfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlowlogger = logging.getLogger(__name__)@@ -246,7 +247,7 @@ def _external_data_sources(team: Team) -> list[dict[str, Any]]:rows = (ExternalDataSource.objects.filter(team=team, deleted=False).annotate(- last_run_at=Max("jobs__created_at", filter=Q(jobs__status=ExternalDataJob.Status.COMPLETED)),+ last_run_at=Max("jobs__created_at", filter=Q(jobs__status=ExternalDataJobStatus.COMPLETED)),latest_error=latest_error,).order_by("source_type", "id")diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex 745ab0b51468..cd7523b475e8 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -14,6 +14,7 @@ from products.signals.backend import contractsfrom products.signals.backend.billing import REFUND_INELIGIBILITY_REASONS, refund_ineligibility_reasonfrom products.signals.backend.contracts import DEFAULT_NOT_ACTIONABLE_KEY, STEERING_KEY, STEERING_MAX_LENGTHfrom products.signals.backend.enums import SignalSourceProduct, SignalSourceType+from products.warehouse_sources.backend.facade.types import ExternalDataSchemaStatusfrom .artefact_schemas import NON_WRITABLE_ARTEFACT_TYPESfrom .daily_limit import reports_generated_today, team_day_start@@ -105,16 +106,16 @@ class SignalSourceConfigSerializer(serializers.ModelSerializer):.exclude(source__deleted=True).values_list("status", flat=True))- if ExternalDataSchema.Status.RUNNING in statuses:+ if ExternalDataSchemaStatus.RUNNING in statuses:return "running"# One failing repo outranks its siblings' success, so a broken repo is never hidden.if statuses & {- ExternalDataSchema.Status.FAILED,- ExternalDataSchema.Status.BILLING_LIMIT_REACHED,- ExternalDataSchema.Status.BILLING_LIMIT_TOO_LOW,+ ExternalDataSchemaStatus.FAILED,+ ExternalDataSchemaStatus.BILLING_LIMIT_REACHED,+ ExternalDataSchemaStatus.BILLING_LIMIT_TOO_LOW,}:return "failed"- if ExternalDataSchema.Status.COMPLETED in statuses:+ if ExternalDataSchemaStatus.COMPLETED in statuses:return "completed"return Nonediff --git a/products/warehouse_sources/backend/facade/types.py b/products/warehouse_sources/backend/facade/types.pyindex 66a66edfcd68..e90b2569d2d6 100644--- a/products/warehouse_sources/backend/facade/types.py+++ b/products/warehouse_sources/backend/facade/types.py@@ -17,11 +17,22 @@ from django.utils.functional import Promise__all__ = ["DIRECT_ENGINE_BY_SOURCE_TYPE","DataWarehouseManagedViewSetKind",+ "DataWarehouseTableCreatedVia",+ "DataWarehouseTableFormat",+ "ExternalDataJobPipelineVersion",+ "ExternalDataJobStatus",+ "ExternalDataSchemaStatus",+ "ExternalDataSchemaSyncFrequency",+ "ExternalDataSchemaSyncType",+ "ExternalDataSourceAccessMethod",+ "ExternalDataSourceCreatedVia",+ "ExternalDataSourceStatus","ExternalDataSourceType","IncrementalField","IncrementalFieldType","ManagedWarehouseSQLMode","PartitionSettings",+ "WarehouseColumnAnnotationDescriptionSource",]@@ -1410,3 +1421,93 @@ class ManagedWarehouseSQLMode(StrEnum):class DataWarehouseManagedViewSetKind(models.TextChoices):REVENUE_ANALYTICS = "revenue_analytics", "Revenue Analytics"ENGINEERING_ANALYTICS = "engineering_analytics", "Engineering Analytics"+++class DataWarehouseTableFormat(models.TextChoices):+ CSV = "CSV", "CSV"+ CSVWithNames = "CSVWithNames", "CSVWithNames"+ Parquet = "Parquet", "Parquet"+ JSON = "JSONEachRow", "JSON"+ Delta = "Delta", "Delta"+ DeltaS3Wrapper = "DeltaS3Wrapper", "DeltaS3Wrapper"+++class DataWarehouseTableCreatedVia(models.TextChoices):+ # The first five mirror `ExternalDataSource.CreatedVia` value-for-value, so table and source+ # attribution can be counted together. The last three have no source equivalent — they cover+ # the tables PostHog creates itself, which a request surface would otherwise misattribute to+ # whoever happened to trigger the run.+ WEB = "web", "web"+ API = "api", "api"+ MCP = "mcp", "mcp"+ WIZARD = "wizard", "wizard"+ SELF_DRIVING = "self_driving", "self_driving"+ SOURCE = "source", "source"+ MATERIALIZED_VIEW = "materialized_view", "materialized_view"+ DEMO = "demo", "demo"+++class ExternalDataJobStatus(models.TextChoices):+ RUNNING = "Running", "Running"+ FAILED = "Failed", "Failed"+ COMPLETED = "Completed", "Completed"+ BILLING_LIMIT_REACHED = "BillingLimitReached", "BillingLimitReached"+ BILLING_LIMIT_TOO_LOW = "BillingLimitTooLow", "BillingLimitTooLow"+++class ExternalDataJobPipelineVersion(models.TextChoices):+ V1 = "v1-dlt-sync", "v1-dlt-sync"+ V2 = "v2-non-dlt", "v2-non-dlt"+ V3 = "v3-kafka-s3", "v3-kafka-s3"+++class ExternalDataSourceAccessMethod(models.TextChoices):+ WAREHOUSE = "warehouse", "warehouse"+ DIRECT = "direct", "direct"+++class ExternalDataSourceCreatedVia(models.TextChoices):+ WEB = "web", "web"+ API = "api", "api"+ MCP = "mcp", "mcp"+ WIZARD = "wizard", "wizard"+ SELF_DRIVING = "self_driving", "self_driving"+++class ExternalDataSourceStatus(models.TextChoices):+ RUNNING = "Running", "Running"+ PAUSED = "Paused", "Paused"+ ERROR = "Error", "Error"+ COMPLETED = "Completed", "Completed"+ CANCELLED = "Cancelled", "Cancelled"+++class ExternalDataSchemaStatus(models.TextChoices):+ RUNNING = "Running", "Running"+ PAUSED = "Paused", "Paused"+ FAILED = "Failed", "Failed"+ COMPLETED = "Completed", "Completed"+ BILLING_LIMIT_REACHED = "BillingLimitReached", "BillingLimitReached"+ BILLING_LIMIT_TOO_LOW = "BillingLimitTooLow", "BillingLimitTooLow"+++class ExternalDataSchemaSyncType(models.TextChoices):+ FULL_REFRESH = "full_refresh", "full_refresh"+ INCREMENTAL = "incremental", "incremental"+ APPEND = "append", "append"+ WEBHOOK = "webhook", "webhook"+ CDC = "cdc", "cdc"+ XMIN = "xmin", "xmin"+++class ExternalDataSchemaSyncFrequency(models.TextChoices):+ DAILY = "day", "Daily"+ WEEKLY = "week", "Weekly"+ MONTHLY = "month", "Monthly"+ # TODO provide flexible schedule definition+++class WarehouseColumnAnnotationDescriptionSource(models.TextChoices):+ CANONICAL = "canonical", "Canonical"+ AI_GENERATED = "ai_generated", "AI generated"+ USER_EDITED = "user_edited", "User edited"diff --git a/products/warehouse_sources/backend/models/column_annotation.py b/products/warehouse_sources/backend/models/column_annotation.pyindex a48c9a4acce1..a78e6d9cd412 100644--- a/products/warehouse_sources/backend/models/column_annotation.py+++ b/products/warehouse_sources/backend/models/column_annotation.py@@ -3,6 +3,8 @@ from django.db import modelsfrom posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDTModel, sane_repr+from products.warehouse_sources.backend.types import WarehouseColumnAnnotationDescriptionSource+class WarehouseColumnAnnotation(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFields, UUIDTModel):"""Semantic description of a data warehouse table or column, surfaced to the AI agent.@@ -14,10 +16,8 @@ class WarehouseColumnAnnotation(TeamScopedRootMixin, CreatedMetaFields, UpdatedMmarked `is_user_edited` is never overwritten by automatic enrichment."""- class DescriptionSource(models.TextChoices):- CANONICAL = "canonical", "Canonical"- AI_GENERATED = "ai_generated", "AI generated"- USER_EDITED = "user_edited", "User edited"+ # Kept on the model so the nested names and the `choices=` below stay unchanged.+ DescriptionSource = WarehouseColumnAnnotationDescriptionSourceteam = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)table = models.ForeignKey(diff --git a/products/warehouse_sources/backend/models/external_data_job.py b/products/warehouse_sources/backend/models/external_data_job.pyindex 0fd4051ec420..d7cb03920289 100644--- a/products/warehouse_sources/backend/models/external_data_job.py+++ b/products/warehouse_sources/backend/models/external_data_job.py@@ -7,19 +7,13 @@ from django.db.models import Prefetchfrom posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDTModel, sane_reprfrom posthog.sync import database_sync_to_async+from products.warehouse_sources.backend.types import ExternalDataJobPipelineVersion, ExternalDataJobStatus+class ExternalDataJob(CreatedMetaFields, UpdatedMetaFields, UUIDTModel):- class Status(models.TextChoices):- RUNNING = "Running", "Running"- FAILED = "Failed", "Failed"- COMPLETED = "Completed", "Completed"- BILLING_LIMIT_REACHED = "BillingLimitReached", "BillingLimitReached"- BILLING_LIMIT_TOO_LOW = "BillingLimitTooLow", "BillingLimitTooLow"-- class PipelineVersion(models.TextChoices):- V1 = "v1-dlt-sync", "v1-dlt-sync"- V2 = "v2-non-dlt", "v2-non-dlt"- V3 = "v3-kafka-s3", "v3-kafka-s3"+ # Kept on the model so the nested names and the `choices=` below stay unchanged.+ Status = ExternalDataJobStatus+ PipelineVersion = ExternalDataJobPipelineVersionteam = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)pipeline = models.ForeignKey("warehouse_sources.ExternalDataSource", related_name="jobs", on_delete=models.CASCADE)diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex d6eba41fb96f..353112f7e110 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -27,7 +27,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typPartitionFormat,PartitionMode,)-from products.warehouse_sources.backend.types import IncrementalFieldType+from products.warehouse_sources.backend.types import (+ ExternalDataSchemaStatus,+ ExternalDataSchemaSyncFrequency,+ ExternalDataSchemaSyncType,+ IncrementalFieldType,+)if TYPE_CHECKING:from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource@@ -151,26 +156,10 @@ class ExternalDataSchemaQuerySet(models.QuerySet["ExternalDataSchema"]):class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields, UUIDTModel, DeletedMetaFields):- class Status(models.TextChoices):- RUNNING = "Running", "Running"- PAUSED = "Paused", "Paused"- FAILED = "Failed", "Failed"- COMPLETED = "Completed", "Completed"- BILLING_LIMIT_REACHED = "BillingLimitReached", "BillingLimitReached"- BILLING_LIMIT_TOO_LOW = "BillingLimitTooLow", "BillingLimitTooLow"-- class SyncType(models.TextChoices):- FULL_REFRESH = "full_refresh", "full_refresh"- INCREMENTAL = "incremental", "incremental"- APPEND = "append", "append"- WEBHOOK = "webhook", "webhook"- CDC = "cdc", "cdc"- XMIN = "xmin", "xmin"-- class SyncFrequency(models.TextChoices):- DAILY = "day", "Daily"- WEEKLY = "week", "Weekly"- MONTHLY = "month", "Monthly"+ # Kept on the model so the nested names and the `choices=` below stay unchanged.+ Status = ExternalDataSchemaStatus+ SyncType = ExternalDataSchemaSyncType+ SyncFrequency = ExternalDataSchemaSyncFrequencyname = models.CharField(max_length=400)label = models.CharField(max_length=400, null=True, blank=True)diff --git a/products/warehouse_sources/backend/models/external_data_source.py b/products/warehouse_sources/backend/models/external_data_source.pyindex 0b4b869b56e2..a1dba2fc463d 100644--- a/products/warehouse_sources/backend/models/external_data_source.py+++ b/products/warehouse_sources/backend/models/external_data_source.py@@ -12,6 +12,10 @@ from posthog.sync import database_sync_to_asyncfrom products.warehouse_sources.backend.types import (DIRECT_ENGINE_BY_SOURCE_TYPE,+ ExternalDataSchemaSyncFrequency,+ ExternalDataSourceAccessMethod,+ ExternalDataSourceCreatedVia,+ ExternalDataSourceStatus,ExternalDataSourceType,ManagedWarehouseSQLMode,external_data_source_type_choices,@@ -32,30 +36,13 @@ class ExternalDataSourceManager(models.Manager):class ExternalDataSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields, UUIDTModel, DeletedMetaFields):- class AccessMethod(models.TextChoices):- WAREHOUSE = "warehouse", "warehouse"- DIRECT = "direct", "direct"-- class CreatedVia(models.TextChoices):- WEB = "web", "web"- API = "api", "api"- MCP = "mcp", "mcp"- WIZARD = "wizard", "wizard"- SELF_DRIVING = "self_driving", "self_driving"-- class Status(models.TextChoices):- RUNNING = "Running", "Running"- PAUSED = "Paused", "Paused"- ERROR = "Error", "Error"- COMPLETED = "Completed", "Completed"- CANCELLED = "Cancelled", "Cancelled"+ # Kept on the model so the nested names and the `choices=` below stay unchanged.+ AccessMethod = ExternalDataSourceAccessMethod+ CreatedVia = ExternalDataSourceCreatedVia+ Status = ExternalDataSourceStatus# Deprecated, use `ExternalDataSchema.SyncFrequency`- class SyncFrequency(models.TextChoices):- DAILY = "day", "Daily"- WEEKLY = "week", "Weekly"- MONTHLY = "month", "Monthly"- # TODO provide flexible schedule definition+ SyncFrequency = ExternalDataSchemaSyncFrequencysource_id = models.CharField(max_length=400)connection_id = models.CharField(max_length=400)diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.pyindex 5be80f88938c..eeeb455e4abd 100644--- a/products/warehouse_sources/backend/models/table.py+++ b/products/warehouse_sources/backend/models/table.py@@ -55,6 +55,7 @@ from products.warehouse_sources.backend.models.util import (remove_named_tuples,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY+from products.warehouse_sources.backend.types import DataWarehouseTableCreatedVia, DataWarehouseTableFormatfrom .credential import DataWarehouseCredentialfrom .external_table_definitions import external_tables, get_hogql_column_name_mapping@@ -283,27 +284,9 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet# Use if it's certain externaldataschemas aren't neededraw_objects = DataWarehouseTableQuerySet.as_manager()- class TableFormat(models.TextChoices):- CSV = "CSV", "CSV"- CSVWithNames = "CSVWithNames", "CSVWithNames"- Parquet = "Parquet", "Parquet"- JSON = "JSONEachRow", "JSON"- Delta = "Delta", "Delta"- DeltaS3Wrapper = "DeltaS3Wrapper", "DeltaS3Wrapper"-- class CreatedVia(models.TextChoices):- # The first five mirror `ExternalDataSource.CreatedVia` value-for-value, so table and source- # attribution can be counted together. The last three have no source equivalent — they cover- # the tables PostHog creates itself, which a request surface would otherwise misattribute to- # whoever happened to trigger the run.- WEB = "web", "web"- API = "api", "api"- MCP = "mcp", "mcp"- WIZARD = "wizard", "wizard"- SELF_DRIVING = "self_driving", "self_driving"- SOURCE = "source", "source"- MATERIALIZED_VIEW = "materialized_view", "materialized_view"- DEMO = "demo", "demo"+ # Kept on the model so the nested names and the `choices=` below stay unchanged.+ TableFormat = DataWarehouseTableFormat+ CreatedVia = DataWarehouseTableCreatedVianame = models.CharField(max_length=128)format = models.CharField(max_length=128, choices=TableFormat)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.pyindex 6f7331dd2db1..299d53b30d70 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py@@ -40,7 +40,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpersfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import (filter_dwh_columns_by_enabled_columns,)-from products.warehouse_sources.backend.types import ExternalDataSourceType+from products.warehouse_sources.backend.types import (+ DataWarehouseTableCreatedVia,+ DataWarehouseTableFormat,+ ExternalDataSourceType,+)LOGGER = get_logger(__name__)@@ -171,7 +175,7 @@ async def validate_schema_and_update_table(team_id: int,schema_id: uuid.UUID,row_count: int,- table_format: DataWarehouseTable.TableFormat,+ table_format: DataWarehouseTableFormat,queryable_folder: str,table_schema_dict: Optional[dict[str, str]] = None,primary_keys: Optional[list[str]] = None,@@ -273,7 +277,7 @@ async def validate_schema_and_update_table(logger.debug(f"Creating table for schema: {str(schema_id)}")table_created = DataWarehouseTable.objects.create(external_data_source_id=job.pipeline.id,- created_via=DataWarehouseTable.CreatedVia.SOURCE,+ created_via=DataWarehouseTableCreatedVia.SOURCE,**table_params,)@@ -357,7 +361,7 @@ async def register_cdc_companion_table(schema_id: uuid.UUID,resource_name: str,row_count: int,- table_format: DataWarehouseTable.TableFormat,+ table_format: DataWarehouseTableFormat,queryable_folder: str,table_schema_dict: Optional[dict[str, str]] = None,set_as_schema_table: bool = False,@@ -429,7 +433,7 @@ async def register_cdc_companion_table(logger.debug(f"Creating CDC companion table: {companion_table_name}")companion_table = DataWarehouseTable.objects.create(external_data_source_id=job.pipeline.id,- created_via=DataWarehouseTable.CreatedVia.SOURCE,+ created_via=DataWarehouseTableCreatedVia.SOURCE,**table_params,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.pyindex 429224a3b41d..e86985b16494 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py@@ -25,6 +25,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineupdate_last_synced_at,validate_schema_and_update_table,)+from products.warehouse_sources.backend.types import (+ DataWarehouseTableCreatedVia,+ DataWarehouseTableFormat,+ ExternalDataJobStatus,+)_PIPELINE_SYNC_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync"_DB_RETRY_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry"@@ -123,7 +128,7 @@ def _register_companion_sync(schema_id: uuid.UUID,resource_name: str,row_count: int,- table_format: DataWarehouseTable.TableFormat,+ table_format: DataWarehouseTableFormat,queryable_folder: str,table_schema_dict: dict[str, str] | None = None,set_as_schema_table: bool = False,@@ -198,7 +203,7 @@ class TestRegisterCDCCompanionTable(BaseTest):team_id=self.team.pk,pipeline=source,schema=schema,- status=ExternalDataJob.Status.RUNNING,+ status=ExternalDataJobStatus.RUNNING,rows_synced=0,)return source, job, schema@@ -214,7 +219,7 @@ class TestRegisterCDCCompanionTable(BaseTest):schema_id=schema.id,resource_name="orders_cdc",row_count=100,- table_format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,+ table_format=DataWarehouseTableFormat.DeltaS3Wrapper,queryable_folder="s3://bucket/cdc_folder",table_schema_dict={"id": "Int64", "name": "String"},)@@ -242,7 +247,7 @@ class TestRegisterCDCCompanionTable(BaseTest):schema_id=schema.id,resource_name="orders_cdc",row_count=100,- table_format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,+ table_format=DataWarehouseTableFormat.DeltaS3Wrapper,queryable_folder="s3://bucket/cdc_folder_v1",)@@ -252,7 +257,7 @@ class TestRegisterCDCCompanionTable(BaseTest):schema_id=schema.id,resource_name="orders_cdc",row_count=200,- table_format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,+ table_format=DataWarehouseTableFormat.DeltaS3Wrapper,queryable_folder="s3://bucket/cdc_folder_v2",)@@ -279,7 +284,7 @@ class TestRegisterCDCCompanionTable(BaseTest):schema_id=schema.id,resource_name="orders_cdc",row_count=50,- table_format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,+ table_format=DataWarehouseTableFormat.DeltaS3Wrapper,queryable_folder="s3://bucket/cdc_folder",set_as_schema_table=True,)@@ -298,7 +303,7 @@ class TestRegisterCDCCompanionTable(BaseTest):schema_id=schema.id,resource_name="orders_cdc",row_count=0,- table_format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,+ table_format=DataWarehouseTableFormat.DeltaS3Wrapper,queryable_folder="s3://bucket/cdc_folder",)@@ -320,7 +325,7 @@ class TestValidateSchemaAndUpdateTable:)schema = ExternalDataSchema.objects.create(name="orders", team=team, source=source)job = ExternalDataJob.objects.create(- team=team, pipeline=source, schema=schema, status=ExternalDataJob.Status.RUNNING, rows_synced=10+ team=team, pipeline=source, schema=schema, status=ExternalDataJobStatus.RUNNING, rows_synced=10)return schema, job@@ -346,7 +351,7 @@ class TestValidateSchemaAndUpdateTable:team_id=team.pk,schema_id=schema.id,row_count=10,- table_format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,+ table_format=DataWarehouseTableFormat.DeltaS3Wrapper,queryable_folder="s3://bucket/orders",)@@ -356,7 +361,7 @@ class TestValidateSchemaAndUpdateTable:assert schema.table is Nonetable = DataWarehouseTable.objects.get(external_data_source=schema.source, deleted=False)assert not table.columns- assert table.created_via == DataWarehouseTable.CreatedVia.SOURCE+ assert table.created_via == DataWarehouseTableCreatedVia.SOURCEclass TestUpdateLastSyncedAt:diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.pyindex 7d182c920a7b..53f42bc4bfd7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py@@ -125,6 +125,11 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitieSyncNewSchemasActivityInputs,sync_new_schemas_activity,)+from products.warehouse_sources.backend.types import (+ ExternalDataJobStatus,+ ExternalDataSchemaStatus,+ ExternalDataSchemaSyncType,+)BUCKET_NAME = "test-pipeline"SESSION = aioboto3.Session()@@ -383,7 +388,7 @@ async def _run(source_type: str,job_inputs: dict[str, str | dict[str, str]],mock_data_response: Any,- sync_type: Optional[ExternalDataSchema.SyncType] = None,+ sync_type: Optional[ExternalDataSchemaSyncType] = None,sync_type_config: Optional[dict] = None,billable: Optional[bool] = None,ignore_assertions: Optional[bool] = False,@@ -442,14 +447,14 @@ async def _run(if not ignore_assertions:run = await get_latest_run_if_exists(team_id=team.pk, pipeline_id=source.pk)assert run is not None- assert run.status == ExternalDataJob.Status.COMPLETED+ assert run.status == ExternalDataJobStatus.COMPLETEDassert run.finished_at is not Noneassert run.storage_delta_mib is not Noneassert run.storage_delta_mib != 0mock_compact_table.assert_called()mock_get_data_import_finished_metric.assert_called_with(- source_type=source_type, status=ExternalDataJob.Status.COMPLETED.lower()+ source_type=source_type, status=ExternalDataJobStatus.COMPLETED.lower())# Assert that app_metrics2 rows were emitted for the successful job — both@@ -530,7 +535,7 @@ async def _replay_v3_consumer(team_id: int, schema_id, job_id: str | None = None# If the workflow already marked the job as COMPLETED (e.g. worker shutdown scenario),# the consumer should not replay — the workflow managed the job status itself and# S3 files may have been cleaned up.- if job.status == ExternalDataJob.Status.COMPLETED:+ if job.status == ExternalDataJobStatus.COMPLETED:_pg_queue_replay.clear()return@@ -1127,7 +1132,7 @@ async def test_postgres_schema_evolution(team, postgres_config, postgres_connect"ssh_tunnel_enabled": "False",},mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},)@@ -1190,7 +1195,7 @@ async def test_sql_database_missing_incremental_values(team, postgres_config, po"ssh_tunnel_enabled": "False",},mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},)@@ -1232,7 +1237,7 @@ async def test_sql_database_incremental_initial_value(team, postgres_config, pos"ssh_tunnel_enabled": "False",},mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},)@@ -1268,7 +1273,7 @@ async def test_billing_limits(team, stripe_customer, mock_stripe_client):name="Customer",team_id=team.pk,source_id=source.pk,- sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,+ sync_type=ExternalDataSchemaSyncType.FULL_REFRESH,sync_type_config={},)@@ -1288,7 +1293,7 @@ async def test_billing_limits(team, stripe_customer, mock_stripe_client):job: ExternalDataJob = await sync_to_async(ExternalDataJob.objects.get)(team_id=team.id, schema_id=schema.pk)- assert job.status == ExternalDataJob.Status.BILLING_LIMIT_REACHED+ assert job.status == ExternalDataJobStatus.BILLING_LIMIT_REACHEDwith pytest.raises(Exception):await sync_to_async(execute_hogql_query)("SELECT * FROM stripe_customer", team)@@ -1315,7 +1320,7 @@ async def test_create_external_job_failure(team, stripe_customer, mock_stripe_clname="Customer",team_id=team.pk,source_id=source.pk,- sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,+ sync_type=ExternalDataSchemaSyncType.FULL_REFRESH,sync_type_config={},)@@ -1336,7 +1341,7 @@ async def test_create_external_job_failure(team, stripe_customer, mock_stripe_cljob: ExternalDataJob = await sync_to_async(ExternalDataJob.objects.get)(team_id=team.id, schema_id=schema.pk)- assert job.status == ExternalDataJob.Status.FAILED+ assert job.status == ExternalDataJobStatus.FAILEDwith pytest.raises(Exception):await sync_to_async(execute_hogql_query)("SELECT * FROM stripe_customer", team)@@ -1362,7 +1367,7 @@ async def test_create_external_job_failure_no_job_model(team, stripe_customer, mname="Customer",team_id=team.pk,source_id=source.pk,- sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,+ sync_type=ExternalDataSchemaSyncType.FULL_REFRESH,sync_type_config={},)@@ -1418,7 +1423,7 @@ async def test_non_retryable_error(team, zendesk_brands):name="Brands",team_id=team.pk,source_id=source.pk,- sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,+ sync_type=ExternalDataSchemaSyncType.FULL_REFRESH,sync_type_config={},)@@ -1445,7 +1450,7 @@ async def test_non_retryable_error(team, zendesk_brands):job: ExternalDataJob = await sync_to_async(ExternalDataJob.objects.get)(team_id=team.id, schema_id=schema.pk)await sync_to_async(schema.refresh_from_db)()- assert job.status == ExternalDataJob.Status.FAILED+ assert job.status == ExternalDataJobStatus.FAILEDassert schema.should_sync is Falsewith pytest.raises(Exception):@@ -1473,7 +1478,7 @@ async def test_non_retryable_error_with_special_characters(team, stripe_customername="Customer",team_id=team.pk,source_id=source.pk,- sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,+ sync_type=ExternalDataSchemaSyncType.FULL_REFRESH,sync_type_config={},)@@ -1502,7 +1507,7 @@ async def test_non_retryable_error_with_special_characters(team, stripe_customerjob: ExternalDataJob = await sync_to_async(ExternalDataJob.objects.get)(team_id=team.id, schema_id=schema.pk)await sync_to_async(schema.refresh_from_db)()- assert job.status == ExternalDataJob.Status.FAILED+ assert job.status == ExternalDataJobStatus.FAILEDassert schema.should_sync is Falsewith pytest.raises(Exception):@@ -1530,7 +1535,7 @@ async def test_inconsistent_types_in_data(team):name="organizations",team_id=team.pk,source_id=source.pk,- sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,+ sync_type=ExternalDataSchemaSyncType.FULL_REFRESH,sync_type_config={},)@@ -1838,7 +1843,7 @@ async def test_delta_no_merging_on_first_sync(team, postgres_config, postgres_co"ssh_tunnel_enabled": "False",},mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},ignore_assertions=True,)@@ -1939,7 +1944,7 @@ async def test_delta_no_merging_on_first_sync_uncapped_chunk_size("ssh_tunnel_enabled": "False",},mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},ignore_assertions=True,)@@ -1992,7 +1997,7 @@ async def test_delta_no_merging_on_first_sync_after_reset(team, postgres_config,"ssh_tunnel_enabled": "False",},mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},ignore_assertions=True,)@@ -2121,7 +2126,7 @@ async def test_partition_folders_with_int_id(team, postgres_config, postgres_con"ssh_tunnel_enabled": "False",},mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},ignore_assertions=True,)@@ -2187,7 +2192,7 @@ async def test_partition_folders_with_uuid_id_and_created_at(team, postgres_conf"ssh_tunnel_enabled": "False",},mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "created_at", "incremental_field_type": "timestamp"},ignore_assertions=True,)@@ -2256,7 +2261,7 @@ async def test_in_place_repartition_to_finer_datetime_format(team, postgres_confsource_type="Postgres",job_inputs=job_inputs,mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "created_at", "incremental_field_type": "timestamp"},ignore_assertions=True,)@@ -2408,7 +2413,7 @@ async def test_in_place_coarsening_merges_weekly_partitions_into_months(source_type="Postgres",job_inputs=_postgres_job_inputs(postgres_config),mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "created_at", "incremental_field_type": "timestamp"},ignore_assertions=True,)@@ -2464,7 +2469,7 @@ async def test_oom_history_does_not_split_a_table_with_tiny_partitions(source_type="Postgres",job_inputs=_postgres_job_inputs(postgres_config),mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "created_at", "incremental_field_type": "timestamp"},ignore_assertions=True,)@@ -2501,7 +2506,7 @@ async def test_operator_nomination_coarsens_a_table_the_automatic_path_refuses(source_type="Postgres",job_inputs=_postgres_job_inputs(postgres_config),mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "created_at", "incremental_field_type": "timestamp"},ignore_assertions=True,)@@ -2544,7 +2549,7 @@ async def test_in_place_coarsening_merges_hourly_partitions_up(source_type="Postgres",job_inputs=_postgres_job_inputs(postgres_config),mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "created_at", "incremental_field_type": "timestamp"},ignore_assertions=True,)@@ -2633,7 +2638,7 @@ async def test_in_place_coarsening_for_hashed_and_numerical_modes(source_type="Postgres",job_inputs=_postgres_job_inputs(postgres_config),mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},ignore_assertions=True,)@@ -2718,7 +2723,7 @@ async def test_partition_folders_with_uuid_id_and_created_at_with_parametrized_f"ssh_tunnel_enabled": "False",},mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "created_at", "incremental_field_type": "timestamp"},ignore_assertions=True,)@@ -2823,7 +2828,7 @@ async def test_partition_folders_with_existing_table(team, postgres_config, post"ssh_tunnel_enabled": "False",},mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},ignore_assertions=True,)@@ -2923,7 +2928,7 @@ async def test_partition_folders_with_existing_table_and_pipeline_reset("ssh_tunnel_enabled": "False",},mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},ignore_assertions=True,)@@ -3018,7 +3023,7 @@ async def test_partition_folders_delta_merge_called_with_partition_predicate("ssh_tunnel_enabled": "False",},mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "created_at", "incremental_field_type": "timestamp"},ignore_assertions=True,)@@ -3180,7 +3185,7 @@ async def test_postgres_duplicate_primary_key(team, postgres_config, postgres_co"ssh_tunnel_enabled": "False",},mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},)@@ -3188,7 +3193,7 @@ async def test_postgres_duplicate_primary_key(team, postgres_config, postgres_coteam_id=team.id, schema__name="duplicate_primary_key")- assert job.status == ExternalDataJob.Status.FAILED+ assert job.status == ExternalDataJobStatus.FAILEDassert job.latest_error is not Noneassert ("The primary key set for this table isn't unique, so incremental syncing can't reliably match rows to update"@@ -3221,7 +3226,7 @@ async def test_stripe_earliest_incremental_value(team, stripe_balance_transactio"stripe_account_id": "acct_id",},mock_data_response=stripe_balance_transaction["data"],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "created", "incremental_field_type": "integer"},)@@ -3242,7 +3247,7 @@ async def test_append_only_table(team, mock_stripe_client):"stripe_account_id": "acct_id",},mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.APPEND,+ sync_type=ExternalDataSchemaSyncType.APPEND,sync_type_config={"incremental_field": "created", "incremental_field_type": "integer"},)@@ -3305,7 +3310,7 @@ async def test_worker_shutdown_desc_sort_order(team):"region": {"selection": "EU", "subdomain": ""},},mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "conversation_updated_at", "incremental_field_type": "datetime"},ignore_assertions=True,)@@ -3318,7 +3323,7 @@ async def test_worker_shutdown_desc_sort_order(team):)assert run is not None- assert run.status == ExternalDataJob.Status.COMPLETED+ assert run.status == ExternalDataJobStatus.COMPLETED@pytest.mark.django_db(transaction=True)@@ -3347,7 +3352,7 @@ async def test_worker_shutdown_triggers_schedule_buffer_one(team, zendesk_brands"email_address": "[email protected]",},mock_data_response=zendesk_brands["brands"],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "created_at", "incremental_field_type": "datetime"},ignore_assertions=True,)@@ -3360,7 +3365,7 @@ async def test_worker_shutdown_triggers_schedule_buffer_one(team, zendesk_brands)assert run is not None- assert run.status == ExternalDataJob.Status.COMPLETED+ assert run.status == ExternalDataJobStatus.COMPLETED@pytest.mark.django_db(transaction=True)@@ -3418,7 +3423,7 @@ async def test_billing_limits_too_many_rows(team, postgres_config, postgres_conn"ssh_tunnel_enabled": "False",},mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},ignore_assertions=True,)@@ -3427,7 +3432,7 @@ async def test_billing_limits_too_many_rows(team, postgres_config, postgres_connteam_id=team.id, schema__name="billing_limits")- assert job.status == ExternalDataJob.Status.BILLING_LIMIT_TOO_LOW+ assert job.status == ExternalDataJobStatus.BILLING_LIMIT_TOO_LOWwith pytest.raises(Exception):await sync_to_async(execute_hogql_query)(f"SELECT * FROM postgres_billing_limits", team)@@ -3464,7 +3469,7 @@ async def test_billing_limits_too_many_rows_previously(team, postgres_config, popipeline=source,finished_at=datetime.now(),billable=True,- status=ExternalDataJob.Status.COMPLETED,+ status=ExternalDataJobStatus.COMPLETED,)await sync_to_async(License.objects.create)(@@ -3501,7 +3506,7 @@ async def test_billing_limits_too_many_rows_previously(team, postgres_config, po"ssh_tunnel_enabled": "False",},mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},ignore_assertions=True,)@@ -3510,7 +3515,7 @@ async def test_billing_limits_too_many_rows_previously(team, postgres_config, poteam_id=team.id, schema__name="billing_limits")- assert job.status == ExternalDataJob.Status.BILLING_LIMIT_TOO_LOW+ assert job.status == ExternalDataJobStatus.BILLING_LIMIT_TOO_LOWwith pytest.raises(Exception):await sync_to_async(execute_hogql_query)(f"SELECT * FROM postgres_billing_limits", team)@@ -3695,7 +3700,7 @@ async def test_postgres_deleting_schemas_with_pre_synced_data(team, postgres_con# The schema with the deleted upstream table should now have "should_sync" updated to False and status set to completedsynced_schema = await ExternalDataSchema.objects.aget(id=inputs.external_data_schema_id)assert synced_schema.should_sync is False- assert synced_schema.status == ExternalDataSchema.Status.COMPLETED+ assert synced_schema.status == ExternalDataSchemaStatus.COMPLETED@pytest.mark.django_db(transaction=True)@@ -4193,7 +4198,7 @@ async def test_stripe_webhook_s3_charges(team, stripe_charge, mock_stripe_client"stripe_account_id": "acct_id",},mock_data_response=stripe_charge["data"],- sync_type=ExternalDataSchema.SyncType.WEBHOOK,+ sync_type=ExternalDataSchemaSyncType.WEBHOOK,)res = await sync_to_async(execute_hogql_query)("SELECT * FROM stripe_charge", team)@@ -4335,7 +4340,7 @@ async def test_stripe_webhook_s3_charges(team, stripe_charge, mock_stripe_client# Verify job completedrun = await get_latest_run_if_exists(team_id=team.pk, pipeline_id=inputs.external_data_source_id)assert run is not None- assert run.status == ExternalDataJob.Status.COMPLETED+ assert run.status == ExternalDataJobStatus.COMPLETED# Verify webhook data was ingested alongside the original chargeres = await sync_to_async(execute_hogql_query)("SELECT * FROM stripe_charge", team)@@ -4360,7 +4365,7 @@ async def test_stripe_webhook_consumer_e2e(team, stripe_charge, mock_stripe_clie"stripe_account_id": "acct_id",},mock_data_response=stripe_charge["data"],- sync_type=ExternalDataSchema.SyncType.WEBHOOK,+ sync_type=ExternalDataSchemaSyncType.WEBHOOK,)res = await sync_to_async(execute_hogql_query)("SELECT * FROM stripe_charge", team)@@ -4526,7 +4531,7 @@ async def test_stripe_webhook_consumer_e2e(team, stripe_charge, mock_stripe_clie# 7. Verify job completedrun = await get_latest_run_if_exists(team_id=team.pk, pipeline_id=inputs.external_data_source_id)assert run is not None- assert run.status == ExternalDataJob.Status.COMPLETED+ assert run.status == ExternalDataJobStatus.COMPLETED# 8. Verify webhook data was ingested alongside the original chargeres = await sync_to_async(execute_hogql_query)("SELECT * FROM stripe_charge", team)@@ -4624,7 +4629,7 @@ async def test_mysql_incremental_integer_cursor(team, mysql_config, mysql_connecsource_type="MySQL",job_inputs=_mysql_job_inputs(mysql_config),mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},)@@ -4703,7 +4708,7 @@ async def test_mysql_schema_evolution(team, mysql_config, mysql_connection):source_type="MySQL",job_inputs=_mysql_job_inputs(mysql_config),mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},)@@ -4809,7 +4814,7 @@ async def test_postgres_xmin_sync(team, postgres_config, postgres_connection):source_type="Postgres",job_inputs=_postgres_job_inputs(postgres_config),mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.XMIN,+ sync_type=ExternalDataSchemaSyncType.XMIN,sync_type_config={},)@@ -4890,7 +4895,7 @@ async def test_postgres_xmin_wraparound_or_range(team, postgres_config, postgressource_type="Postgres",job_inputs=_postgres_job_inputs(postgres_config),mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.XMIN,+ sync_type=ExternalDataSchemaSyncType.XMIN,sync_type_config={},)@@ -4922,7 +4927,7 @@ async def test_postgres_switch_to_xmin_rebuilds_table(team, postgres_config, possource_type="Postgres",job_inputs=_postgres_job_inputs(postgres_config),mock_data_response=[],- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,sync_type_config={"incremental_field": "id", "incremental_field_type": "integer"},)@@ -4931,7 +4936,7 @@ async def test_postgres_switch_to_xmin_rebuilds_table(team, postgres_config, pos# Switch to xmin with reset_pipeline — what the serializer sets when crossing the xmin boundary.schema = await ExternalDataSchema.objects.aget(id=inputs.external_data_schema_id)- schema.sync_type = ExternalDataSchema.SyncType.XMIN+ schema.sync_type = ExternalDataSchemaSyncType.XMINschema.sync_type_config = {"primary_key_columns": ["id"], "reset_pipeline": True}await sync_to_async(schema.save)()diff --git a/products/warehouse_sources/backend/types.py b/products/warehouse_sources/backend/types.pyindex f7c4057e45d3..59e157d0f72c 100644--- a/products/warehouse_sources/backend/types.py+++ b/products/warehouse_sources/backend/types.py@@ -4,10 +4,21 @@from products.warehouse_sources.backend.facade.types import (DIRECT_ENGINE_BY_SOURCE_TYPE as DIRECT_ENGINE_BY_SOURCE_TYPE,DataWarehouseManagedViewSetKind as DataWarehouseManagedViewSetKind,+ DataWarehouseTableCreatedVia as DataWarehouseTableCreatedVia,+ DataWarehouseTableFormat as DataWarehouseTableFormat,+ ExternalDataJobPipelineVersion as ExternalDataJobPipelineVersion,+ ExternalDataJobStatus as ExternalDataJobStatus,+ ExternalDataSchemaStatus as ExternalDataSchemaStatus,+ ExternalDataSchemaSyncFrequency as ExternalDataSchemaSyncFrequency,+ ExternalDataSchemaSyncType as ExternalDataSchemaSyncType,+ ExternalDataSourceAccessMethod as ExternalDataSourceAccessMethod,+ ExternalDataSourceCreatedVia as ExternalDataSourceCreatedVia,+ ExternalDataSourceStatus as ExternalDataSourceStatus,ExternalDataSourceType as ExternalDataSourceType,IncrementalField as IncrementalField,IncrementalFieldType as IncrementalFieldType,ManagedWarehouseSQLMode as ManagedWarehouseSQLMode,PartitionSettings as PartitionSettings,+ WarehouseColumnAnnotationDescriptionSource as WarehouseColumnAnnotationDescriptionSource,external_data_source_type_choices as external_data_source_type_choices,)diff --git a/tools/hogli-commands/hogli_commands/product/isolation.py b/tools/hogli-commands/hogli_commands/product/isolation.pyindex f0f22e25ce4a..c9f5d1d08c38 100644--- a/tools/hogli-commands/hogli_commands/product/isolation.py+++ b/tools/hogli-commands/hogli_commands/product/isolation.py@@ -512,7 +512,6 @@ MODEL_CROSSINGS: frozenset[tuple[str, str]] = frozenset({("product_analytics", "Insight"),("product_analytics", "InsightVariable"),- ("product_analytics", "InsightViewed"),("warehouse_sources", "DataWarehouseCredential"),("warehouse_sources", "DataWarehouseTable"),("warehouse_sources", "ExternalDataJob"),