: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
chore(product-analytics): move insight models to product app (#60001)
Julian Bez3fbcbbddde18
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex a0960e8745fd..f7f31b4df865 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -1709,7 +1709,7 @@ jobs:&& env.CLICKHOUSE_COMPAT_PYTEST_TARGETS|| (matrix.person-on-events- && './posthog/clickhouse/ ./posthog/queries/ ./posthog/api/test/test_insight* ./posthog/api/test/dashboards/test_dashboard.py'+ && './posthog/clickhouse/ ./posthog/queries/ ./products/product_analytics/backend/api/test/ ./posthog/api/test/dashboards/test_dashboard.py'|| 'posthog')}} ${{ matrix.compat && '' || (matrix.person-on-events && 'ee/clickhouse/' || 'ee/') }} -m "not async_migrations" \diff --git a/.semgrep/rules/idor-team-scoped-models.py b/.semgrep/rules/idor-team-scoped-models.pyindex 8594f7bc99b6..3156b66092c9 100644--- a/.semgrep/rules/idor-team-scoped-models.py+++ b/.semgrep/rules/idor-team-scoped-models.py@@ -1,5 +1,6 @@from django.shortcuts import get_object_or_404-from posthog.models import ChangeRequest, Cohort, Insight, Notebook+from posthog.models import ChangeRequest, Cohort, Notebook+from products.product_analytics.backend.models.insight import Insightfrom products.actions.backend.models.action import Actionfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.project import Projectdiff --git a/ee/api/subscription.py b/ee/api/subscription.pyindex fe166555c839..bff98b24506d 100644--- a/ee/api/subscription.py+++ b/ee/api/subscription.py@@ -30,7 +30,6 @@ from posthog.constants import SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE_FEATURE_FLAG_from posthog.event_usage import groupsfrom posthog.exceptions import QuotaLimitExceededfrom posthog.exceptions_capture import capture_exception-from posthog.models import Insightfrom posthog.models.integration import Integrationfrom posthog.models.subscription import Subscription, SubscriptionDelivery, unsubscribe_using_tokenfrom posthog.permissions import PremiumFeaturePermission@@ -43,6 +42,8 @@ from posthog.temporal.common.client import sync_connectfrom posthog.temporal.subscriptions.types import ProcessSubscriptionWorkflowInputs, SubscriptionTriggerTypefrom posthog.utils import str_to_bool+from products.product_analytics.backend.models.insight import Insight+from ee.tasks.subscriptions.auto_disable import validate_re_enablefrom ee.tasks.subscriptions.subscription_utils import DEFAULT_MAX_ASSET_COUNTdiff --git a/ee/api/test/test_insight.py b/ee/api/test/test_insight.pyindex 3a2cdbc53106..9442ce1a94ba 100644--- a/ee/api/test/test_insight.py+++ b/ee/api/test/test_insight.py@@ -11,11 +11,12 @@ from rest_framework import statusfrom posthog.api.test.dashboards import DashboardAPIfrom posthog.constants import AvailableFeature-from posthog.models import Insight, OrganizationMembership, User+from posthog.models import OrganizationMembership, Userfrom posthog.test.db_context_capturing import capture_db_queriesfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insightfrom ee.api.test.base import APILicensedTestfrom ee.models import DashboardPrivilegediff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.pyindex e62c27ac2ead..5f9988fe20ac 100644--- a/ee/api/test/test_subscription.py+++ b/ee/api/test/test_subscription.py@@ -14,7 +14,6 @@ from temporalio.exceptions import WorkflowAlreadyStartedErrorfrom posthog.models import Teamfrom posthog.models.filters.filter import Filter-from posthog.models.insight import Insightfrom posthog.models.integration import Integrationfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.subscription import Subscription, SubscriptionDelivery@@ -22,6 +21,7 @@ from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.temporal.subscriptions.types import ProcessSubscriptionWorkflowInputs, SubscriptionTriggerTypefrom products.dashboards.backend.models.dashboard import Dashboard+from products.product_analytics.backend.models.insight import Insightfrom ee.api.test.base import APILicensedTestfrom ee.tasks.subscriptions.slack_subscriptions import get_slack_integration_for_teamdiff --git a/ee/api/test/test_tagged_item.py b/ee/api/test/test_tagged_item.pyindex d7fe6b5ea71a..56904bb2b163 100644--- a/ee/api/test/test_tagged_item.py+++ b/ee/api/test/test_tagged_item.py@@ -6,11 +6,12 @@ from posthog.test.base import APIBaseTestfrom rest_framework import status-from posthog.models import Insight, Tag+from posthog.models import Tagfrom posthog.models.tagged_item import TaggedItemfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.product_analytics.backend.models.insight import Insight# This serializer only tests the business logic of getting and setting of ee descriptions. It uses the dashboard model# as an example, since model specific functionality is already tested in their models' respective serializer tests.diff --git a/ee/clickhouse/views/insights.py b/ee/clickhouse/views/insights.pyindex f2bcd0e75ef3..890be1dddd18 100644--- a/ee/clickhouse/views/insights.py+++ b/ee/clickhouse/views/insights.py@@ -5,13 +5,13 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.api.documentation import extend_schema-from posthog.api.insight import InsightViewSet, capture_legacy_api_callfrom posthog.api.utils import actionfrom posthog.decorators import cached_by_filters-from posthog.models import Insightfrom posthog.models.filters import Filterfrom products.dashboards.backend.models.dashboard import Dashboard+from products.product_analytics.backend.api.insight import InsightViewSet, capture_legacy_api_call+from products.product_analytics.backend.models.insight import Insightfrom ee.clickhouse.queries.funnels.funnel_correlation import FunnelCorrelationdiff --git a/ee/clickhouse/views/person.py b/ee/clickhouse/views/person.pyindex d9ad4a0d29d8..03e226ae3745 100644--- a/ee/clickhouse/views/person.py+++ b/ee/clickhouse/views/person.py@@ -2,7 +2,6 @@ from typing import Optionalfrom rest_framework import request, response-from posthog.api.insight import capture_legacy_api_callfrom posthog.api.person import PersonViewSetfrom posthog.api.utils import actionfrom posthog.constants import FUNNEL_CORRELATION_PERSON_LIMIT, FUNNEL_CORRELATION_PERSON_OFFSET, INSIGHT_FUNNELS@@ -10,6 +9,8 @@ from posthog.decorators import cached_by_filtersfrom posthog.models import Filterfrom posthog.utils import format_query_params_absolute_url+from products.product_analytics.backend.api.insight import capture_legacy_api_call+from ee.clickhouse.queries.funnels.funnel_correlation_persons import FunnelCorrelationActorsdiff --git a/ee/hogai/artifacts/handlers/visualization.py b/ee/hogai/artifacts/handlers/visualization.pyindex 868dbef133b9..d6e9c2b91aad 100644--- a/ee/hogai/artifacts/handlers/visualization.py+++ b/ee/hogai/artifacts/handlers/visualization.py@@ -7,7 +7,9 @@ from pydantic import ValidationErrorfrom posthog.schema import ArtifactContentType, ArtifactSource, VisualizationArtifactContent, VisualizationMessage-from posthog.models import Insight, Team+from posthog.models import Team++from products.product_analytics.backend.models.insight import Insightfrom ee.hogai.artifacts.handlers.base import ArtifactHandler, EnrichmentContext, register_handlerfrom ee.hogai.artifacts.types import (diff --git a/ee/hogai/artifacts/test/test_manager.py b/ee/hogai/artifacts/test/test_manager.pyindex c5ecedb687a4..d868c8200511 100644--- a/ee/hogai/artifacts/test/test_manager.py+++ b/ee/hogai/artifacts/test/test_manager.py@@ -26,7 +26,7 @@ from posthog.schema import (VisualizationMessage,)-from posthog.models import Insight+from products.product_analytics.backend.models.insight import Insightfrom ee.hogai.artifacts.manager import ArtifactManagerfrom ee.hogai.artifacts.types import StoredNotebookArtifactContentdiff --git a/ee/hogai/artifacts/types.py b/ee/hogai/artifacts/types.pyindex 784bbfc695a1..0496fa21ee65 100644--- a/ee/hogai/artifacts/types.py+++ b/ee/hogai/artifacts/types.py@@ -15,7 +15,7 @@ from posthog.schema import (VisualizationBlock,)-from posthog.models import Insight+from products.product_analytics.backend.models.insight import Insightclass VisualizationRefBlock(BaseModel):diff --git a/ee/hogai/chat_agent/insights/nodes.py b/ee/hogai/chat_agent/insights/nodes.pyindex 190ff26ddfdc..5c6dc200494e 100644--- a/ee/hogai/chat_agent/insights/nodes.py+++ b/ee/hogai/chat_agent/insights/nodes.py@@ -18,7 +18,8 @@ from langchain_core.tools import toolfrom posthog.schema import ArtifactContentType, ArtifactSource, AssistantToolCallMessagefrom posthog.exceptions_capture import capture_exception-from posthog.models import Insight++from products.product_analytics.backend.models.insight import Insightfrom ee.hogai.context.insight.query_executor import AssistantQueryExecutorfrom ee.hogai.core.node import AssistantNodediff --git a/ee/hogai/chat_agent/insights/test/test_nodes.py b/ee/hogai/chat_agent/insights/test/test_nodes.pyindex ad3c7a8b3d56..06df4cdfa4c5 100644--- a/ee/hogai/chat_agent/insights/test/test_nodes.py+++ b/ee/hogai/chat_agent/insights/test/test_nodes.py@@ -20,7 +20,7 @@ from posthog.schema import (VisualizationArtifactContent,)-from posthog.models import Insight, InsightViewed+from products.product_analytics.backend.models.insight import Insight, InsightViewedfrom ee.hogai.artifacts.manager import ArtifactManagerfrom ee.hogai.chat_agent.insights.nodes import InsightDict, InsightSearchNode, NoInsightsExceptiondiff --git a/ee/hogai/context/entity_search/context.py b/ee/hogai/context/entity_search/context.pyindex fa5139e4c6a5..faf10e57b628 100644--- a/ee/hogai/context/entity_search/context.py+++ b/ee/hogai/context/entity_search/context.py@@ -14,7 +14,7 @@ from posthog.api.search import (EntityConfig,search_entities as search_entities_fts,)-from posthog.models import Cohort, Insight, Team, User+from posthog.models import Cohort, Team, Userfrom posthog.rbac.user_access_control import UserAccessControlfrom posthog.sync import database_sync_to_async@@ -24,6 +24,7 @@ from products.dashboards.backend.models.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebook+from products.product_analytics.backend.models.insight import Insightfrom products.surveys.backend.models import Surveyfrom ee.hogai.artifacts.handlers.base import get_handler_for_content_typediff --git a/ee/hogai/context/entity_search/test/test_context.py b/ee/hogai/context/entity_search/test/test_context.pyindex f2e3fc0ba8ba..844c790fc370 100644--- a/ee/hogai/context/entity_search/test/test_context.py+++ b/ee/hogai/context/entity_search/test/test_context.py@@ -7,13 +7,13 @@ from django.utils import timezonefrom parameterized import parameterized-from posthog.models import Cohort, Insight-from posthog.models.insight import InsightViewed+from posthog.models import Cohortfrom products.actions.backend.models.action import Actionfrom 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.models.insight import Insight, InsightViewedfrom products.surveys.backend.models import Surveyfrom ee.hogai.context import AssistantContextManagerdiff --git a/ee/hogai/context/insight/context.py b/ee/hogai/context/insight/context.pyindex 831f16a6ac53..ab44edcf2d8d 100644--- a/ee/hogai/context/insight/context.py+++ b/ee/hogai/context/insight/context.py@@ -2,9 +2,11 @@ from posthog.hogql_queries.apply_dashboard_filters import (apply_dashboard_filters_to_dict,apply_dashboard_variables_to_dict,)-from posthog.models import Insight, Team, User+from posthog.models import Team, Userfrom posthog.sync import database_sync_to_async+from products.product_analytics.backend.models.insight import Insight+from ee.hogai.context.insight.query_executor import execute_and_format_queryfrom ee.hogai.tool_errors import MaxToolRetryableErrorfrom ee.hogai.utils.helpers import build_insight_urldiff --git a/ee/hogai/eval/ci/max_tools/eval_upsert_dashboard.py b/ee/hogai/eval/ci/max_tools/eval_upsert_dashboard.pyindex 8f4af025532d..bfcc4ec3b9dc 100644--- a/ee/hogai/eval/ci/max_tools/eval_upsert_dashboard.py+++ b/ee/hogai/eval/ci/max_tools/eval_upsert_dashboard.py@@ -17,10 +17,9 @@ from posthog.schema import (TrendsQuery,)-from posthog.models import Insight-from products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insightfrom ee.hogai.chat_agent import AssistantGraphfrom ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointerdiff --git a/ee/hogai/eval/data_setup.py b/ee/hogai/eval/data_setup.pyindex 75c0cb8e55c6..cb1861543a9e 100644--- a/ee/hogai/eval/data_setup.py+++ b/ee/hogai/eval/data_setup.py@@ -16,13 +16,14 @@ from django.test import override_settingsfrom posthog.clickhouse.client import sync_executefrom posthog.demo.matrix.manager import MatrixManagerfrom posthog.demo.matrix.taxonomy_inference import infer_taxonomy_for_team-from posthog.models import GroupTypeMapping, Insight, Organization, OrganizationMembership, Team, User+from posthog.models import GroupTypeMapping, Organization, OrganizationMembership, Team, Userfrom posthog.models.event.sql import COPY_EVENTS_BETWEEN_TEAMSfrom posthog.models.group.sql import COPY_GROUPS_BETWEEN_TEAMSfrom posthog.models.person.sql import COPY_PERSON_DISTINCT_ID2S_BETWEEN_TEAMS, COPY_PERSONS_BETWEEN_TEAMSfrom posthog.tasks.demo_create_data import HedgeboxMatrixfrom products.dashboards.backend.models import Dashboard, DashboardTile+from products.product_analytics.backend.models.insight import Insightfrom ee.models.assistant import CoreMemorydiff --git a/ee/hogai/eval/sandboxed/seeders/insight.py b/ee/hogai/eval/sandboxed/seeders/insight.pyindex 36426b1f0d14..85351718014a 100644--- a/ee/hogai/eval/sandboxed/seeders/insight.py+++ b/ee/hogai/eval/sandboxed/seeders/insight.py@@ -118,7 +118,7 @@ def seed_insight_noise(context: CustomPromptSandboxContext) -> dict[str, Any]:whether the agent found the right one. Synchronous — runs in a workerthread via ``asyncio.to_thread`` from ``base.py:task()``."""- from posthog.models.insight import Insight+ from products.product_analytics.backend.models.insight import Insightteam_id = context.team_iduser_id = context.user_iddiff --git a/ee/hogai/tools/execute_sql/test/test_mcp_tool.py b/ee/hogai/tools/execute_sql/test/test_mcp_tool.pyindex 067f3303b87e..686649b3fb66 100644--- a/ee/hogai/tools/execute_sql/test/test_mcp_tool.py+++ b/ee/hogai/tools/execute_sql/test/test_mcp_tool.py@@ -3,7 +3,7 @@ from unittest.mock import Mock, patchfrom asgiref.sync import sync_to_async-from posthog.models import Insight+from products.product_analytics.backend.models.insight import Insightfrom ee.hogai.tool_errors import MaxToolRetryableErrorfrom ee.hogai.tools.execute_sql.mcp_tool import ExecuteSQLMCPTool, ExecuteSQLMCPToolArgsdiff --git a/ee/hogai/tools/execute_sql/test/test_tool.py b/ee/hogai/tools/execute_sql/test/test_tool.pyindex 0e965a1da9d1..04e106ca8050 100644--- a/ee/hogai/tools/execute_sql/test/test_tool.py+++ b/ee/hogai/tools/execute_sql/test/test_tool.py@@ -14,7 +14,7 @@ from posthog.schema import (VisualizationArtifactContent,)-from posthog.models import Insight+from products.product_analytics.backend.models.insight import Insightfrom ee.hogai.context.context import AssistantContextManagerfrom ee.hogai.tools.execute_sql.tool import ExecuteSQLTool, ExecuteSQLToolArgsdiff --git a/ee/hogai/tools/read_data/test/test_tool.py b/ee/hogai/tools/read_data/test/test_tool.pyindex 9e8756335a06..84f851f9a053 100644--- a/ee/hogai/tools/read_data/test/test_tool.py+++ b/ee/hogai/tools/read_data/test/test_tool.py@@ -17,8 +17,6 @@ from posthog.schema import (VisualizationArtifactContent,)-from posthog.models import Insight-from products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery@@ -29,6 +27,7 @@ from products.llm_analytics.backend.summarization.llm.schema import (SummarizationResponse,SummaryBullet,)+from products.product_analytics.backend.models.insight import Insightfrom products.surveys.backend.models import Surveyfrom products.warehouse_sources.backend.models.credential import DataWarehouseCredentialfrom products.warehouse_sources.backend.models.table import DataWarehouseTablediff --git a/ee/hogai/tools/upsert_dashboard/test/test_tool.py b/ee/hogai/tools/upsert_dashboard/test/test_tool.pyindex d922060a55a2..1aa0c1b00ba8 100644--- a/ee/hogai/tools/upsert_dashboard/test/test_tool.py+++ b/ee/hogai/tools/upsert_dashboard/test/test_tool.py@@ -22,10 +22,9 @@ from posthog.schema import (VisualizationMessage,)-from posthog.models import Insight-from products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile, Text+from products.product_analytics.backend.models.insight import Insightfrom ee.hogai.artifacts.types import ModelArtifactResult, StateArtifactResult, VisualizationWithSourceResultfrom ee.hogai.context.context import AssistantContextManagerdiff --git a/ee/hogai/tools/upsert_dashboard/tool.py b/ee/hogai/tools/upsert_dashboard/tool.pyindex b843e4a25382..4d2e447d0edd 100644--- a/ee/hogai/tools/upsert_dashboard/tool.py+++ b/ee/hogai/tools/upsert_dashboard/tool.py@@ -8,12 +8,12 @@ from pydantic import BaseModel, Fieldfrom posthog.schema import DataTableNode, HogQLQuery, InsightVizNode, QuerySchemaRootfrom posthog.event_usage import EventSource, report_user_action-from posthog.models import Insightfrom posthog.sync import database_sync_to_asyncfrom posthog.utils import pluralizefrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insightfrom ee.hogai.artifacts.types import ModelArtifactResult, VisualizationWithSourceResultfrom ee.hogai.context.dashboard.context import DashboardContext, DashboardInsightContextdiff --git a/ee/tasks/subscriptions/subscription_utils.py b/ee/tasks/subscriptions/subscription_utils.pyindex 02aac42bb786..aaede6bdb360 100644--- a/ee/tasks/subscriptions/subscription_utils.py+++ b/ee/tasks/subscriptions/subscription_utils.py@@ -8,12 +8,13 @@ from celery import chainfrom prometheus_client import Histogramfrom posthog.models.exported_asset import ExportedAsset-from posthog.models.insight import Insightfrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.subscription import Subscriptionfrom posthog.tasks import exporterfrom posthog.utils import wait_for_parallel_celery_group+from products.product_analytics.backend.models.insight import Insight+logger = structlog.get_logger(__name__)UTM_TAGS_BASE = "utm_source=posthog&utm_campaign=subscription_report"diff --git a/ee/tasks/test/subscriptions/test_email_subscriptions.py b/ee/tasks/test/subscriptions/test_email_subscriptions.pyindex 728b2a6a3aa6..4c96bc7ea25c 100644--- a/ee/tasks/test/subscriptions/test_email_subscriptions.py+++ b/ee/tasks/test/subscriptions/test_email_subscriptions.py@@ -3,12 +3,12 @@ from posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patchfrom posthog.models.exported_asset import ExportedAsset-from posthog.models.insight import Insightfrom posthog.models.instance_setting import set_instance_settingfrom posthog.models.subscription import Subscriptionfrom posthog.tasks.test.utils_email_tests import mock_email_messagesfrom products.dashboards.backend.models.dashboard import Dashboard+from products.product_analytics.backend.models.insight import Insightfrom ee.tasks.subscriptions.email_subscriptions import send_email_subscription_reportfrom ee.tasks.test.subscriptions.subscriptions_test_factory import create_subscriptiondiff --git a/ee/tasks/test/subscriptions/test_slack_subscriptions.py b/ee/tasks/test/subscriptions/test_slack_subscriptions.pyindex 4cc8aa3337c7..bf6addd8c7fb 100644--- a/ee/tasks/test/subscriptions/test_slack_subscriptions.py+++ b/ee/tasks/test/subscriptions/test_slack_subscriptions.py@@ -10,11 +10,11 @@ from slack_sdk.errors import SlackApiErrorfrom slack_sdk.web.async_slack_response import AsyncSlackResponsefrom posthog.models.exported_asset import ExportedAsset-from posthog.models.insight import Insightfrom posthog.models.integration import Integrationfrom posthog.models.subscription import Subscriptionfrom products.dashboards.backend.models.dashboard import Dashboard+from products.product_analytics.backend.models.insight import Insightfrom ee.tasks.subscriptions.slack_subscriptions import (_block_for_asset,diff --git a/ee/tasks/test/subscriptions/test_subscriptions_utils.py b/ee/tasks/test/subscriptions/test_subscriptions_utils.pyindex 2d37311b5d21..92ddf02b9d69 100644--- a/ee/tasks/test/subscriptions/test_subscriptions_utils.py+++ b/ee/tasks/test/subscriptions/test_subscriptions_utils.py@@ -3,10 +3,10 @@ from posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patchfrom posthog.models.exported_asset import ExportedAsset-from posthog.models.insight import Insightfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insightfrom ee.tasks.subscriptions.subscription_utils import DEFAULT_MAX_ASSET_COUNT, generate_assetsfrom ee.tasks.test.subscriptions.subscriptions_test_factory import create_subscriptiondiff --git a/ee/tasks/test/test_slack.py b/ee/tasks/test/test_slack.pyindex cbd079d2c5e5..17f0134eae2c 100644--- a/ee/tasks/test/test_slack.py+++ b/ee/tasks/test/test_slack.py@@ -4,12 +4,12 @@ from unittest.mock import MagicMock, patchfrom posthog import settingsfrom posthog.models.exported_asset import ExportedAsset-from posthog.models.insight import Insightfrom posthog.models.integration import Integrationfrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.subscription import Subscriptionfrom products.dashboards.backend.models.dashboard import Dashboard+from products.product_analytics.backend.models.insight import Insightfrom ee.tasks.slack import handle_slack_eventdiff --git a/posthog/admin/admins/insight_admin.py b/posthog/admin/admins/insight_admin.pyindex e1e3ae7e1f3e..22cf4215164e 100644--- a/posthog/admin/admins/insight_admin.py+++ b/posthog/admin/admins/insight_admin.py@@ -4,7 +4,8 @@ from django.urls import reversefrom django.utils.html import format_htmlfrom posthog.admin.filters import DeletedFilter-from posthog.models import Insight++from products.product_analytics.backend.models.insight import Insightclass InsightAdminForm(forms.ModelForm):diff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.pyindex a8010a4fe79c..11740921d2a6 100644--- a/posthog/admin/admins/organization_admin.py+++ b/posthog/admin/admins/organization_admin.py@@ -44,7 +44,11 @@ BULK_DELETE_MODEL_REGISTRY: tuple[tuple[str, str, str], ...] = (("posthog.models.group.group.Group", "team_id", "Groups"),("posthog.models.group_type_mapping.GroupTypeMapping", "team_id", "Group Type Mappings"),("posthog.models.person.Person", "team_id", "Persons"),- ("posthog.models.insight_caching_state.InsightCachingState", "team_id", "Insight Caching States"),+ (+ "products.product_analytics.backend.models.insight_caching_state.InsightCachingState",+ "team_id",+ "Insight Caching States",+ ),)diff --git a/posthog/api/__init__.py b/posthog/api/__init__.pyindex 5b3e8f28a1cb..8667f5916ac9 100644--- a/posthog/api/__init__.py+++ b/posthog/api/__init__.py@@ -167,7 +167,6 @@ from . import (hog_function,hog_function_template,ingestion_warnings,- insight_variable,instance_settings,instance_status,integration,@@ -837,11 +836,12 @@ router.register(r"query_performance_proxy", QueryPerformanceProxyViewSet, "queryfrom posthog.api.cohort import CohortViewSet, LegacyCohortViewSet # noqa: E402from posthog.api.element import ElementViewSet, LegacyElementViewSet # noqa: E402from posthog.api.event import EventViewSet, LegacyEventViewSet # noqa: E402-from posthog.api.insight import InsightViewSet # noqa: E402from posthog.api.person import LegacyPersonViewSet, PersonViewSet # noqa: E402from posthog.api.web_experiment import WebExperimentViewSet # noqa: E402from products.actions.backend.api.action import ActionViewSet # noqa: E402+from products.product_analytics.backend.api.insight import InsightViewSet # noqa: E402+from products.product_analytics.backend.api.insight_variable import InsightVariableViewSet # noqa: E402# Legacy endpoints CH (to be removed eventually)router.register(r"cohort", LegacyCohortViewSet, basename="cohort")@@ -1278,7 +1278,7 @@ register_grandfathered_environment_nested_viewset(register_grandfathered_environment_nested_viewset(r"insight_variables",- insight_variable.InsightVariableViewSet,+ InsightVariableViewSet,"environment_insight_variables",["team_id"],)diff --git a/posthog/api/annotation.py b/posthog/api/annotation.pyindex 00916b5a0e28..2434f47a26c7 100644--- a/posthog/api/annotation.py+++ b/posthog/api/annotation.py@@ -14,11 +14,12 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.api.shared import UserBasicSerializerfrom posthog.event_usage import report_user_action-from posthog.models import Annotation, Insight+from posthog.models import Annotationfrom posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activityfrom posthog.models.signals import model_activity_signal, mutable_receiverfrom products.dashboards.backend.models.dashboard import Dashboard+from products.product_analytics.backend.models.insight import Insight@dataclasses.dataclass(frozen=True)diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex 4bb458cfb053..b083b39893cb 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -64,7 +64,6 @@ from posthog.models.cohort.util import ()from posthog.models.cohort.validation import CohortTypeValidationSerializerfrom posthog.models.filters.filter import Filter-from posthog.models.insight import Insightfrom posthog.models.person.person import READ_DB_FOR_PERSONS, PersonDistinctIdfrom posthog.models.person.util import validate_person_uuids_existfrom posthog.models.property.property import Property, PropertyGroup@@ -83,6 +82,7 @@ from products.feature_flags.backend.flag_matching import (get_feature_flag_hash_key_overrides,)from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.product_analytics.backend.models.insight import Insight# Mirrors SerializedPerson in posthog/queries/actor_base_query.py.diff --git a/posthog/api/exports.py b/posthog/api/exports.pyindex 8bfa60e25763..88e8704269f2 100644--- a/posthog/api/exports.py+++ b/posthog/api/exports.py@@ -19,7 +19,7 @@ from temporalio.common import RetryPolicy, SearchAttributePair, TypedSearchAttrifrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import actionfrom posthog.event_usage import EventSource, get_event_source, groups-from posthog.models import Insight, Team, User+from posthog.models import Team, Userfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.exported_asset import ExportedAsset, get_content_responsefrom posthog.models.organization import Organization@@ -32,6 +32,8 @@ from posthog.temporal.common.search_attributes import POSTHOG_SESSION_RECORDING_from posthog.temporal.exports.workflows import ExportAssetWorkflow, ExportAssetWorkflowInputsfrom posthog.temporal.session_replay.rasterize_recording.types import RasterizeRecordingInputs+from products.product_analytics.backend.models.insight import Insight+# Full video exports per team per calendar month, tiered by plan.FULL_VIDEO_EXPORTS_LIMIT_BY_TIER: dict[Literal["free", "paid", "enterprise"], int] = {"free": 10,diff --git a/posthog/api/file_system/registrations.py b/posthog/api/file_system/registrations.pyindex 0eb0a6b61cd8..afdf7a7aa954 100644--- a/posthog/api/file_system/registrations.py+++ b/posthog/api/file_system/registrations.py@@ -377,7 +377,7 @@ def register_core_file_system_types() -> None:register_file_system_type("insight",- "posthog",+ "product_analytics","Insight",lookup_field="short_id",undo_message="Send PATCH /api/projects/@current/insights/{id} with deleted=false.",diff --git a/posthog/api/file_system/test/test_file_system.py b/posthog/api/file_system/test/test_file_system.pyindex 94f1e5debd1e..698c93fe3449 100644--- a/posthog/api/file_system/test/test_file_system.py+++ b/posthog/api/file_system/test/test_file_system.py@@ -11,7 +11,7 @@ from rest_framework import statusfrom rest_framework.test import APIRequestFactoryfrom posthog.api.file_system.file_system import DELETE_PREVIEW_ENTRY_LIMIT-from posthog.models import Insight, Project, Team, User+from posthog.models import Project, Team, Userfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.cohort import Cohortfrom posthog.models.file_system.file_system import FileSystem@@ -24,6 +24,7 @@ from products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.links.backend.models import Linkfrom products.notebooks.backend.models import Notebook+from products.product_analytics.backend.models.insight import Insightfrom products.surveys.backend.models import Surveyfrom ee.models.rbac.access_control import AccessControldiff --git a/posthog/api/my_notifications.py b/posthog/api/my_notifications.pyindex 0845d8d0b147..9c6b4999af4c 100644--- a/posthog/api/my_notifications.py+++ b/posthog/api/my_notifications.py@@ -12,11 +12,12 @@ from rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import ServerTimingsGathered, action-from posthog.models import ActivityLog, Cohort, HogFunction, Insight, NotificationViewed, User+from posthog.models import ActivityLog, Cohort, HogFunction, NotificationViewed, Userfrom posthog.models.comment import Commentfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebook+from products.product_analytics.backend.models.insight import Insightclass MyNotificationsSerializer(serializers.ModelSerializer):diff --git a/posthog/api/person.py b/posthog/api/person.pyindex 98dff774ff3f..6ca4ee71e45e 100644--- a/posthog/api/person.py+++ b/posthog/api/person.py@@ -35,7 +35,6 @@ from posthog.hogql.constants import CSV_EXPORT_LIMITfrom posthog.api.capture import capture_internalfrom posthog.api.documentation import PersonPropertiesSerializer-from posthog.api.insight import capture_legacy_api_callfrom posthog.api.property_value_metrics import PROPERTY_VALUES_DURATIONfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import action, format_paginated_url, get_target_entity@@ -79,6 +78,8 @@ from posthog.settings import EE_AVAILABLEfrom posthog.tasks.split_person import split_personfrom posthog.utils import format_query_params_absolute_url, is_anonymous_id, refresh_requested_by_client+from products.product_analytics.backend.api.insight import capture_legacy_api_call+logger = structlog.get_logger(__name__)tracer = trace.get_tracer(__name__)diff --git a/posthog/api/search.py b/posthog/api/search.pyindex 2d8d757b892c..a26654d97bd0 100644--- a/posthog/api/search.py+++ b/posthog/api/search.py@@ -12,7 +12,7 @@ from rest_framework.response import Responsefrom posthog.api.documentation import _FallbackSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.helpers.full_text_search import build_rank, process_query-from posthog.models import Cohort, EventDefinition, Insight, PropertyDefinition+from posthog.models import Cohort, EventDefinition, PropertyDefinitionfrom posthog.models.hog_flow.hog_flow import HogFlowfrom products.actions.backend.models.action import Action@@ -21,6 +21,7 @@ from products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebook+from products.product_analytics.backend.models.insight import Insightfrom products.surveys.backend.models import SurveyLIMIT = 25diff --git a/posthog/api/sharing.py b/posthog/api/sharing.pyindex f8ac03273f6c..e43b9cdc3c5d 100644--- a/posthog/api/sharing.py+++ b/posthog/api/sharing.py@@ -24,8 +24,6 @@ from posthog.schema import SharingConfigurationSettingsfrom posthog.api.data_color_theme import DataColorTheme, DataColorThemeSerializerfrom posthog.api.exports import ExportedAssetSerializer-from posthog.api.insight import InsightSerializer-from posthog.api.insight_variable import InsightVariablefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.services.query import process_query_dictfrom posthog.api.shared import TeamPublicSerializer@@ -35,10 +33,9 @@ from posthog.constants import AvailableFeaturefrom posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.query_runner import ExecutionMode, shared_insights_execution_modefrom posthog.jwt import PosthogJwtAudience, encode_jwt-from posthog.models import Cohort, InsightViewed, SessionRecording, SharePassword, SharingConfiguration, Team+from posthog.models import Cohort, SessionRecording, SharePassword, SharingConfiguration, Teamfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.exported_asset import ExportedAsset, asset_for_token, get_content_response-from posthog.models.insight import Insightfrom posthog.models.resource_transfer.visitors.insight import InsightVisitorfrom posthog.models.user import Userfrom posthog.rbac.user_access_control import UserAccessControl, access_level_satisfied_for_resource@@ -53,6 +50,9 @@ from products.dashboards.backend.models.dashboard import Dashboardfrom products.notebooks.backend.api.notebook import NotebookSerializerfrom products.notebooks.backend.models import Notebookfrom products.notebooks.backend.util import extract_inline_query_nodes, filter_notebook_content_for_sharing+from products.product_analytics.backend.api.insight import InsightSerializer+from products.product_analytics.backend.models.insight import Insight, InsightViewed+from products.product_analytics.backend.models.insight_variable import InsightVariablelogger = structlog.get_logger(__name__)diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.pyindex efc7b39d5879..b97abaf8ca90 100644--- a/posthog/api/test/dashboards/test_dashboard.py+++ b/posthog/api/test/dashboards/test_dashboard.py@@ -19,11 +19,10 @@ from posthog.schema import DateRange, EventPropertyFilter, EventsNode, PropertyOfrom posthog.api.test.dashboards import DashboardAPIfrom posthog.constants import AvailableFeaturefrom posthog.helpers.dashboard_templates import create_group_type_mapping_detail_dashboard-from posthog.models import Filter, Insight, Team, User+from posthog.models import Filter, Team, Userfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.file_system.file_system_view_log import FileSystemViewLogfrom posthog.models.group_type_mapping import GROUP_TYPES_CACHE_KEY_PREFIX, GROUP_TYPES_STALE_CACHE_KEY_PREFIX-from posthog.models.insight_variable import InsightVariablefrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.project import Projectfrom posthog.models.quick_filter import QuickFilter@@ -34,6 +33,8 @@ from posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.dashboards.backend.api.dashboard import DashboardSerializerfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import ButtonTile, DashboardTile, Text+from products.product_analytics.backend.models.insight import Insight+from products.product_analytics.backend.models.insight_variable import InsightVariablefrom ee.models.rbac.access_control import AccessControldiff --git a/posthog/api/test/test_annotation.py b/posthog/api/test/test_annotation.pyindex d2e96cdd1db7..c5217fe2e598 100644--- a/posthog/api/test/test_annotation.py+++ b/posthog/api/test/test_annotation.py@@ -11,9 +11,10 @@ from django.utils.timezone import nowfrom parameterized import parameterizedfrom rest_framework import status-from posthog.models import Annotation, Insight, Organization, Team, User+from posthog.models import Annotation, Organization, Team, Userfrom products.dashboards.backend.models.dashboard import Dashboard+from products.product_analytics.backend.models.insight import Insightclass TestAnnotation(APIBaseTest, QueryMatchingTest):diff --git a/posthog/api/test/test_annotation_context.py b/posthog/api/test/test_annotation_context.pyindex 1af3ead21552..aefe272ed032 100644--- a/posthog/api/test/test_annotation_context.py+++ b/posthog/api/test/test_annotation_context.py@@ -11,9 +11,10 @@ from posthog.api.annotation_context import (resolve_dashboard_date_range,resolve_query_date_range,)-from posthog.models import Annotation, Insight, Organization, Team+from posthog.models import Annotation, Organization, Teamfrom products.dashboards.backend.models.dashboard import Dashboard+from products.product_analytics.backend.models.insight import Insightclass TestAnnotationContext(APIBaseTest):diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex 953a575cf4a4..a62489a13ce1 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -4574,7 +4574,7 @@ [email protected],@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")def test_cannot_delete_cohort_used_in_insight(self, patch_calculate_cohort, patch_capture):- from posthog.models.insight import Insight+ from products.product_analytics.backend.models.insight import Insightresponse = self.client.post(f"/api/projects/{self.team.id}/cohorts",@@ -4603,7 +4603,7 @@ [email protected],@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")def test_cannot_delete_cohort_used_in_multiple_insights(self, patch_calculate_cohort, patch_capture):- from posthog.models.insight import Insight+ from products.product_analytics.backend.models.insight import Insightresponse = self.client.post(f"/api/projects/{self.team.id}/cohorts",@@ -4637,7 +4637,7 @@ [email protected],@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")def test_cannot_delete_cohort_used_in_more_than_five_insights(self, patch_calculate_cohort, patch_capture):- from posthog.models.insight import Insight+ from products.product_analytics.backend.models.insight import Insightresponse = self.client.post(f"/api/projects/{self.team.id}/cohorts",@@ -4683,7 +4683,7 @@ [email protected],@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")def test_can_delete_cohort_not_used_in_insights(self, patch_calculate_cohort, patch_capture):- from posthog.models.insight import Insight+ from products.product_analytics.backend.models.insight import Insightresponse = self.client.post(f"/api/projects/{self.team.id}/cohorts",@@ -4713,7 +4713,7 @@ [email protected],@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")def test_cannot_delete_cohort_used_in_breakdown_filter(self, patch_calculate_cohort, patch_capture):- from posthog.models.insight import Insight+ from products.product_analytics.backend.models.insight import Insightresponse = self.client.post(f"/api/projects/{self.team.id}/cohorts",@@ -4749,7 +4749,7 @@ [email protected],@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")def test_cannot_delete_cohort_used_in_deeply_nested_properties(self, patch_calculate_cohort, patch_capture):- from posthog.models.insight import Insight+ from products.product_analytics.backend.models.insight import Insightresponse = self.client.post(f"/api/projects/{self.team.id}/cohorts",diff --git a/posthog/api/test/test_exports.py b/posthog/api/test/test_exports.pyindex 05b0013972e9..0b3d03b5a30e 100644--- a/posthog/api/test/test_exports.py+++ b/posthog/api/test/test_exports.py@@ -19,11 +19,9 @@ from rest_framework import statusfrom posthog.hogql.errors import QueryError-from posthog.api.insight import InsightSerializerfrom posthog.errors import CHQueryErrorTooManySimultaneousQueriesfrom posthog.models.exported_asset import ExportedAssetfrom posthog.models.filters.filter import Filter-from posthog.models.insight import Insightfrom posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.settings import (@@ -39,6 +37,8 @@ from posthog.tasks.exports.image_exporter import export_imagefrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.api.insight import InsightSerializer+from products.product_analytics.backend.models.insight import Insightfrom ee.models.rbac.access_control import AccessControldiff --git a/posthog/api/test/test_file_system.py b/posthog/api/test/test_file_system.pyindex d88c3f70f807..d40ef12fede3 100644--- a/posthog/api/test/test_file_system.py+++ b/posthog/api/test/test_file_system.py@@ -23,7 +23,6 @@ from posthog.models.cohort.cohort import Cohortfrom posthog.models.file_system.file_system import FileSystemfrom posthog.models.file_system.file_system_view_log import FileSystemViewLogfrom posthog.models.hog_functions.hog_function import HogFunction, HogFunctionType-from posthog.models.insight import Insightfrom posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylistfrom products.actions.backend.models.action import Action@@ -33,6 +32,7 @@ from products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.links.backend.models import Linkfrom products.notebooks.backend.models import Notebook+from products.product_analytics.backend.models.insight import Insightfrom products.surveys.backend.models import Surveydiff --git a/posthog/api/test/test_personal_api_keys.py b/posthog/api/test/test_personal_api_keys.pyindex 13d21723e274..5e38e5f4964a 100644--- a/posthog/api/test/test_personal_api_keys.py+++ b/posthog/api/test/test_personal_api_keys.py@@ -14,13 +14,13 @@ from posthog.schema import EventsQueryfrom posthog.api.personal_api_key import PersonalAPIKeySerializerfrom posthog.constants import AvailableFeaturefrom posthog.jwt import PosthogJwtAudience, encode_jwt-from posthog.models.insight import Insightfrom posthog.models.organization import Organizationfrom posthog.models.personal_api_key import LEGACY_PERSONAL_API_KEY_SALT, PersonalAPIKeyfrom posthog.models.team.team import Teamfrom posthog.models.utils import SHA256_HASH_PREFIX, generate_random_token_personal, hash_key_valuefrom products.error_tracking.backend.models import ErrorTrackingIssue+from products.product_analytics.backend.models.insight import Insightclass TestPersonalAPIKeysAPI(APIBaseTest):diff --git a/posthog/api/test/test_query.py b/posthog/api/test/test_query.pyindex e6ed26d84c2c..ff221b0abb88 100644--- a/posthog/api/test/test_query.py+++ b/posthog/api/test/test_query.py@@ -36,10 +36,10 @@ from posthog.hogql.constants import LimitContextfrom posthog.api.services.query import process_query_dict, process_query_modelfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.query_tagging import Product, QueryTags-from posthog.models.insight_variable import InsightVariablefrom posthog.models.utils import UUIDTfrom products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType+from products.product_analytics.backend.models.insight_variable import InsightVariableclass TestQuery(ClickhouseTestMixin, APIBaseTest):diff --git a/posthog/api/test/test_resource_transfer.py b/posthog/api/test/test_resource_transfer.pyindex b96286a67294..fe1ce8e5c8e0 100644--- a/posthog/api/test/test_resource_transfer.py+++ b/posthog/api/test/test_resource_transfer.py@@ -6,7 +6,7 @@ from unittest.mock import patchfrom parameterized import parameterizedfrom rest_framework import status-from posthog.models import Insight, Project, Team+from posthog.models import Project, Teamfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.cohort import Cohortfrom posthog.models.organization import Organization, OrganizationMembership@@ -15,6 +15,7 @@ from posthog.models.resource_transfer.resource_transfer import ResourceTransferfrom products.actions.backend.models.action import Actionfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insightfrom products.surveys.backend.models import Surveyfrom ee.models.rbac.access_control import AccessControldiff --git a/posthog/api/test/test_search.py b/posthog/api/test/test_search.pyindex 9b621cc4bda8..d9c81bdd7dd9 100644--- a/posthog/api/test/test_search.py+++ b/posthog/api/test/test_search.py@@ -7,7 +7,7 @@ from django.test.utils import CaptureQueriesContextfrom posthog.api.search import ENTITY_MAP, class_queryset, search_entitiesfrom posthog.helpers.full_text_search import build_search_vector, process_query-from posthog.models import Insight, Team+from posthog.models import Teamfrom posthog.models.hog_flow.hog_flow import HogFlowfrom products.dashboards.backend.models.dashboard import Dashboard@@ -15,6 +15,7 @@ from products.early_access_features.backend.models import EarlyAccessFeaturefrom products.event_definitions.backend.models.event_definition import EventDefinitionfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebook+from products.product_analytics.backend.models.insight import Insightclass TestSearch(APIBaseTest):diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.pyindex 44cdd0fe50df..602dace4999f 100644--- a/posthog/api/test/test_sharing.py+++ b/posthog/api/test/test_sharing.py@@ -17,12 +17,12 @@ from posthog.api.sharing import _log_share_password_attempt, shared_url_as_pngfrom posthog.constants import AvailableFeaturefrom posthog.models import ActivityLog, ExportedAssetfrom posthog.models.filters.filter import Filter-from posthog.models.insight import Insightfrom posthog.models.share_password import SharePasswordfrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.user import Userfrom products.dashboards.backend.models.dashboard import Dashboard+from products.product_analytics.backend.models.insight import Insightdef mock_exporter_template(test_func):@@ -1241,7 +1241,7 @@ class TestExportCacheKeyFlow(APIBaseTest):)@patch("posthog.caching.calculate_results.calculate_for_query_based_insight")- @patch("posthog.api.insight.fetch_cached_response_by_key")+ @patch("products.product_analytics.backend.api.insight.fetch_cached_response_by_key")@mock_exporter_templatedef test_cache_keys_parameter_triggers_direct_cache_lookup(self, mock_fetch_cached, mock_calculate):"""Test that cache_keys param causes InsightSerializer to use direct cache lookup and skip calculation."""@@ -1263,7 +1263,7 @@ class TestExportCacheKeyFlow(APIBaseTest):mock_calculate.assert_not_called()@patch("posthog.caching.calculate_results.calculate_for_query_based_insight")- @patch("posthog.api.insight.fetch_cached_response_by_key")+ @patch("products.product_analytics.backend.api.insight.fetch_cached_response_by_key")@mock_exporter_templatedef test_cache_miss_falls_back_to_normal_calculation(self, mock_fetch_cached, mock_calculate):"""Test that cache miss on expected key falls back to normal calculation."""@@ -1288,7 +1288,7 @@ class TestExportCacheKeyFlow(APIBaseTest):mock_calculate.assert_called_once()@patch("posthog.caching.calculate_results.calculate_for_query_based_insight")- @patch("posthog.api.insight.fetch_cached_response_by_key")+ @patch("products.product_analytics.backend.api.insight.fetch_cached_response_by_key")@mock_exporter_templatedef test_invalid_cache_keys_param_continues_without_it(self, mock_fetch_cached, mock_calculate):"""Test that invalid cache_keys parameter is ignored and normal flow continues."""diff --git a/posthog/api/test/test_sharing_access_token_security.py b/posthog/api/test/test_sharing_access_token_security.pyindex 973aa19419d4..fe836c98eea8 100644--- a/posthog/api/test/test_sharing_access_token_security.py+++ b/posthog/api/test/test_sharing_access_token_security.py@@ -13,10 +13,10 @@ from django.conf import settingsfrom django.utils import timezonefrom posthog.constants import AvailableFeature-from posthog.models.insight import Insightfrom posthog.models.sharing_configuration import SharingConfigurationfrom products.dashboards.backend.models.dashboard import Dashboard+from products.product_analytics.backend.models.insight import Insightclass SharingAccessTokenSecurityTest(APIBaseTest):@@ -248,7 +248,7 @@ class SharingAccessTokenSecurityTest(APIBaseTest):Test that variables_override parameter is ignored when using sharing access tokens.Variables only work in HogQL queries, not TrendsQuery."""- from posthog.models.insight_variable import InsightVariable+ from products.product_analytics.backend.models.insight_variable import InsightVariable# Create an insight variable firstvariable = InsightVariable.objects.create(diff --git a/posthog/api/test/test_tagged_item.py b/posthog/api/test/test_tagged_item.pyindex ead88c897831..3284efb11f5b 100644--- a/posthog/api/test/test_tagged_item.py+++ b/posthog/api/test/test_tagged_item.py@@ -3,10 +3,11 @@ from posthog.test.base import APIBaseTestfrom parameterized import parameterizedfrom rest_framework import status-from posthog.models import Insight, Organization, Tag, Team+from posthog.models import Organization, Tag, Teamfrom posthog.models.tagged_item import TaggedItemfrom products.dashboards.backend.models.dashboard import Dashboard+from products.product_analytics.backend.models.insight import Insightclass TestTaggedItemSerializerMixin(APIBaseTest):diff --git a/posthog/caching/calculate_results.py b/posthog/caching/calculate_results.pyindex c11abef66005..1564925a25b2 100644--- a/posthog/caching/calculate_results.py+++ b/posthog/caching/calculate_results.py@@ -12,12 +12,12 @@ from posthog.api.services.query import ExecutionMode, process_query_dictfrom posthog.clickhouse.query_tagging import get_team_query_tags, tag_queriesfrom posthog.event_usage import AnalyticsPropsfrom posthog.hogql_queries.query_runner import get_query_runner_or_none-from posthog.models import Insight, Team, User-from posthog.models.insight import generate_insight_filters_hash+from posthog.models import Team, Userfrom posthog.schema_migrations.upgrade_manager import upgrade_queryfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insight, generate_insight_filters_hashif TYPE_CHECKING:from posthog.caching.fetch_from_cache import InsightResultdiff --git a/posthog/caching/insight_cache.py b/posthog/caching/insight_cache.pyindex 85d59b2d98c7..b7080eeb4f80 100644--- a/posthog/caching/insight_cache.py+++ b/posthog/caching/insight_cache.py@@ -13,11 +13,12 @@ from posthog.clickhouse.query_tagging import get_team_query_tags, tag_queriesfrom posthog.event_usage import EventSourcefrom posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.query_runner import ExecutionMode-from posthog.models import Insight, InsightCachingStatefrom posthog.schema_migrations.upgrade_manager import upgrade_queryfrom posthog.tasks.tasks import update_cache_taskfrom products.dashboards.backend.models.dashboard import Dashboard+from products.product_analytics.backend.models.insight import Insight+from products.product_analytics.backend.models.insight_caching_state import InsightCachingStatelogger = structlog.get_logger(__name__)diff --git a/posthog/caching/insight_caching_state.py b/posthog/caching/insight_caching_state.pyindex 8b071d69e778..a519186eee8a 100644--- a/posthog/caching/insight_caching_state.py+++ b/posthog/caching/insight_caching_state.py@@ -12,13 +12,13 @@ from prometheus_client import Counterfrom posthog.caching.calculate_results import calculate_cache_keyfrom posthog.caching.utils import active_teams, is_team_activefrom posthog.hogql_queries.query_runner import get_query_runner_or_none-from posthog.models.insight import Insight, InsightViewed-from posthog.models.insight_caching_state import InsightCachingStatefrom posthog.models.team import Teamfrom posthog.models.utils import UUIDTfrom posthog.schema_migrations.upgrade_manager import upgrade_queryfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insight, InsightViewed+from products.product_analytics.backend.models.insight_caching_state import InsightCachingStateVERY_RECENTLY_VIEWED_THRESHOLD = timedelta(hours=48)GENERALLY_VIEWED_THRESHOLD = timedelta(weeks=2)diff --git a/posthog/caching/test/test_insight_cache.py b/posthog/caching/test/test_insight_cache.pyindex 8fb5c29543da..3ac262718085 100644--- a/posthog/caching/test/test_insight_cache.py+++ b/posthog/caching/test/test_insight_cache.py@@ -12,10 +12,12 @@ import orjson as jsonfrom posthog.caching.insight_cache import update_cachefrom posthog.caching.insight_caching_state import upsertfrom posthog.caching.test.test_insight_caching_state import create_insight, filter_dict-from posthog.models import InsightCachingState, Team, User+from posthog.models import Team, Userfrom posthog.models.signals import mute_selected_signalsfrom posthog.utils import get_safe_cache+from products.product_analytics.backend.models.insight_caching_state import InsightCachingState+def create_insight_caching_state(team: Team,diff --git a/posthog/caching/test/test_insight_caching_state.py b/posthog/caching/test/test_insight_caching_state.pyindex 9a0903d3a44f..6606f98a6136 100644--- a/posthog/caching/test/test_insight_caching_state.py+++ b/posthog/caching/test/test_insight_caching_state.py@@ -15,11 +15,13 @@ from posthog.caching.insight_caching_state import (sync_insight_cache_states,upsert,)-from posthog.models import Insight, InsightCachingState, InsightViewed, SharingConfiguration, Team, User+from posthog.models import SharingConfiguration, Team, Userfrom posthog.models.signals import mute_selected_signalsfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile, Text+from products.product_analytics.backend.models.insight import Insight, InsightViewed+from products.product_analytics.backend.models.insight_caching_state import InsightCachingStatefilter_dict = {"events": [{"id": "$pageview"}],diff --git a/posthog/caching/test/test_warming.py b/posthog/caching/test/test_warming.pyindex 8627a3ff780a..d3c0a2a530b1 100644--- a/posthog/caching/test/test_warming.py+++ b/posthog/caching/test/test_warming.py@@ -4,10 +4,10 @@ from posthog.test.base import APIBaseTestfrom unittest.mock import patchfrom posthog.caching.warming import insights_to_keep_fresh, schedule_warming_for_teams_task-from posthog.models import Insight, InsightViewedfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insight, InsightViewedclass TestWarming(APIBaseTest):diff --git a/posthog/caching/warming.py b/posthog/caching/warming.pyindex ec6ef9701fa6..d482b47ac1c7 100644--- a/posthog/caching/warming.py+++ b/posthog/caching/warming.py@@ -21,13 +21,14 @@ from posthog.event_usage import EventSourcefrom posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.query_cache_base import QueryCacheManagerBasefrom posthog.hogql_queries.query_runner import ExecutionMode-from posthog.models import Insight, Team+from posthog.models import Teamfrom posthog.ph_client import ph_scoped_capturefrom posthog.schema_migrations.upgrade_manager import upgrade_queryfrom posthog.scoping_audit import skip_team_scope_auditfrom posthog.tasks.utils import CeleryQueuefrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insightlogger = structlog.get_logger(__name__)diff --git a/posthog/demo/legacy/app_data_generator.py b/posthog/demo/legacy/app_data_generator.pyindex 1b72784f4984..baedc57973b5 100644--- a/posthog/demo/legacy/app_data_generator.py+++ b/posthog/demo/legacy/app_data_generator.py@@ -5,11 +5,12 @@ from django.utils.timezone import nowfrom dateutil.relativedelta import relativedeltafrom posthog.constants import TREND_FILTER_TYPE_ACTIONS-from posthog.models import EventDefinition, Insight, Person, PropertyDefinition+from posthog.models import EventDefinition, Person, PropertyDefinitionfrom products.actions.backend.models.action import Actionfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insightfrom .data_generator import DataGeneratordiff --git a/posthog/demo/legacy/insight_variables_data_generator.py b/posthog/demo/legacy/insight_variables_data_generator.pyindex 629735683ccc..6dd2737a6c61 100644--- a/posthog/demo/legacy/insight_variables_data_generator.py+++ b/posthog/demo/legacy/insight_variables_data_generator.py@@ -1,7 +1,9 @@-from posthog.models import Insight, InsightVariable, Person+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.models.insight import Insight+from products.product_analytics.backend.models.insight_variable import InsightVariablefrom .data_generator import DataGeneratordiff --git a/posthog/demo/legacy/revenue_data_generator.py b/posthog/demo/legacy/revenue_data_generator.pyindex d1f7bcb0353a..2ee0c7f786da 100644--- a/posthog/demo/legacy/revenue_data_generator.py+++ b/posthog/demo/legacy/revenue_data_generator.py@@ -5,11 +5,12 @@ from django.utils.timezone import nowfrom dateutil.relativedelta import relativedeltafrom posthog.constants import TREND_FILTER_TYPE_ACTIONS-from posthog.models import EventDefinition, Insight, Person, PropertyDefinition+from posthog.models import EventDefinition, Person, PropertyDefinitionfrom products.actions.backend.models.action import Actionfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insightfrom .data_generator import DataGeneratordiff --git a/posthog/demo/legacy/web_data_generator.py b/posthog/demo/legacy/web_data_generator.pyindex 2b390067c958..0069318fc47a 100644--- a/posthog/demo/legacy/web_data_generator.py+++ b/posthog/demo/legacy/web_data_generator.py@@ -8,7 +8,7 @@ from django.utils.timezone import nowfrom dateutil.relativedelta import relativedeltafrom posthog.constants import TREND_FILTER_TYPE_ACTIONS-from posthog.models import Insight, Person, PropertyDefinition+from posthog.models import Person, PropertyDefinitionfrom posthog.models.filters.mixins.utils import cached_propertyfrom posthog.models.utils import UUIDTfrom posthog.utils import get_absolute_path@@ -16,6 +16,7 @@ from posthog.utils import get_absolute_pathfrom products.actions.backend.models.action import Actionfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insightfrom .data_generator import DataGeneratordiff --git a/posthog/demo/products/hedgebox/matrix.py b/posthog/demo/products/hedgebox/matrix.pyindex 7c49c7f0139b..0fb5d2022bbf 100644--- a/posthog/demo/products/hedgebox/matrix.py+++ b/posthog/demo/products/hedgebox/matrix.py@@ -50,7 +50,7 @@ from posthog.demo.matrix.matrix import Cluster, Matrixfrom posthog.demo.matrix.models import SimEventfrom posthog.demo.matrix.randomization import Industryfrom posthog.exceptions_capture import capture_exception-from posthog.models import Cohort, Insight, InsightViewed+from posthog.models import Cohortfrom posthog.models.event.util import create_eventfrom posthog.models.oauth import OAuthApplicationfrom posthog.storage import object_storage@@ -75,6 +75,7 @@ from products.event_definitions.backend.models.schema import ()from products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetricfrom products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.product_analytics.backend.models.insight import Insight, InsightViewedfrom products.warehouse_sources.backend.models.credential import get_or_create_datawarehouse_credentialfrom products.warehouse_sources.backend.models.table import DataWarehouseTablediff --git a/posthog/helpers/dashboard_templates.py b/posthog/helpers/dashboard_templates.pyindex 2099772ed49f..405d94ac33d5 100644--- a/posthog/helpers/dashboard_templates.py+++ b/posthog/helpers/dashboard_templates.py@@ -6,12 +6,12 @@ from django.db.models import Qimport structlogfrom posthog.constants import ENRICHED_DASHBOARD_INSIGHT_IDENTIFIER-from posthog.models.insight import Insightfrom posthog.models.tag import Tagfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_templates import DashboardTemplatefrom products.dashboards.backend.models.dashboard_tile import ButtonTile, DashboardTile, Text+from products.product_analytics.backend.models.insight import InsightDASHBOARD_COLORS: list[str] = ["white", "blue", "green", "purple", "black"]diff --git a/posthog/hogql/autocomplete.py b/posthog/hogql/autocomplete.pyindex 16d1e3c56b2d..80690d5f562f 100644--- a/posthog/hogql/autocomplete.py+++ b/posthog/hogql/autocomplete.py@@ -46,11 +46,11 @@ from posthog.hogql.visitor import TraversingVisitor, clone_exprfrom posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.query_runner import get_query_runner-from posthog.models.insight_variable import InsightVariablefrom 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.models.insight_variable import InsightVariablefrom common.hogvm.python.stl import STLfrom common.hogvm.python.stl.bytecode import BYTECODE_STLdiff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.pyindex 17f1d21cc7c0..afc6b4a596f7 100644--- a/posthog/hogql/database/schema/test/test_system_tables.py+++ b/posthog/hogql/database/schema/test/test_system_tables.py@@ -17,8 +17,6 @@ from posthog.models import (Group,GroupTypeMapping,GroupUsageMetric,- Insight,- InsightVariable,Organization,Team,)@@ -46,6 +44,8 @@ from products.llm_analytics.backend.models.score_definitions import ScoreDefinitfrom products.llm_analytics.backend.models.trace_reviews import TraceReview, TraceReviewScorefrom products.logs.backend.models import LogsAlertConfiguration, LogsViewfrom products.notebooks.backend.models import Notebook+from products.product_analytics.backend.models.insight import Insight+from products.product_analytics.backend.models.insight_variable import InsightVariablefrom products.surveys.backend.models import Surveyfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemadiff --git a/posthog/hogql/test/test_autocomplete.py b/posthog/hogql/test/test_autocomplete.pyindex 907b122c72e6..36ee34fd0fed 100644--- a/posthog/hogql/test/test_autocomplete.py+++ b/posthog/hogql/test/test_autocomplete.py@@ -17,11 +17,10 @@ from posthog.hogql.database.models import StringDatabaseFieldfrom posthog.hogql.database.schema.events import EventsTablefrom posthog.hogql.database.schema.persons import PERSONS_FIELDS-from posthog.models.insight_variable import InsightVariable-from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.data_warehouse.backend.types import ExternalDataSourceTypefrom products.event_definitions.backend.models.property_definition import PropertyDefinition+from products.product_analytics.backend.models.insight_variable import InsightVariablefrom products.warehouse_sources.backend.models.credential import DataWarehouseCredentialfrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTablediff --git a/posthog/hogql/test/test_metadata.py b/posthog/hogql/test/test_metadata.pyindex 72c434713f20..7ebe5adb78b2 100644--- a/posthog/hogql/test/test_metadata.py+++ b/posthog/hogql/test/test_metadata.py@@ -17,9 +17,9 @@ from posthog.schema import (from posthog.hogql.metadata import get_hogql_metadatafrom posthog.models import Cohort, PropertyDefinition-from posthog.models.insight_variable import InsightVariablefrom products.data_warehouse.backend.types import ExternalDataSourceType+from products.product_analytics.backend.models.insight_variable import InsightVariablefrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTablediff --git a/posthog/hogql/test/test_query.py b/posthog/hogql/test/test_query.pyindex 6bb467822671..5a3f8fd383d9 100644--- a/posthog/hogql/test/test_query.py+++ b/posthog/hogql/test/test_query.py@@ -37,12 +37,12 @@ from posthog.errors import InternalCHQueryErrorfrom posthog.models import Cohortfrom posthog.models.cohort.util import recalculate_cohortpeoplefrom posthog.models.exchange_rate.currencies import SUPPORTED_CURRENCY_CODES-from posthog.models.insight_variable import InsightVariablefrom posthog.models.utils import UUIDT, uuid7from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIMEfrom products.data_warehouse.backend.types import ExternalDataSourceType+from products.product_analytics.backend.models.insight_variable import InsightVariablefrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcediff --git a/posthog/hogql/variables.py b/posthog/hogql/variables.pyindex 5beff455139e..2ee3e17f2cf9 100644--- a/posthog/hogql/variables.py+++ b/posthog/hogql/variables.py@@ -7,9 +7,10 @@ from posthog.hogql import astfrom posthog.hogql.errors import QueryErrorfrom posthog.hogql.visitor import CloningVisitor-from posthog.models.insight_variable import InsightVariablefrom posthog.models.team.team import Team+from products.product_analytics.backend.models.insight_variable import InsightVariable+T = TypeVar("T", bound=ast.Expr)diff --git a/posthog/hogql_queries/legacy_compatibility/flagged_conversion_manager.py b/posthog/hogql_queries/legacy_compatibility/flagged_conversion_manager.pyindex bb455cafa53f..2ba9b4bf5421 100644--- a/posthog/hogql_queries/legacy_compatibility/flagged_conversion_manager.py+++ b/posthog/hogql_queries/legacy_compatibility/flagged_conversion_manager.py@@ -7,7 +7,7 @@ from posthog.exceptions_capture import capture_exceptionfrom .filter_to_query import filter_to_queryif TYPE_CHECKING:- from posthog.models.insight import Insight+ from products.product_analytics.backend.models.insight import Insight@contextmanagerdiff --git a/posthog/hogql_queries/test/test_hogql_query_runner.py b/posthog/hogql_queries/test/test_hogql_query_runner.pyindex 24a5f37647f3..c8fec606662c 100644--- a/posthog/hogql_queries/test/test_hogql_query_runner.py+++ b/posthog/hogql_queries/test/test_hogql_query_runner.py@@ -22,10 +22,10 @@ from posthog.hogql.visitor import clear_locationsfrom posthog.caching.utils import ThresholdMode, staleness_threshold_mapfrom posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner-from posthog.models.insight_variable import InsightVariablefrom posthog.models.utils import UUIDTfrom products.data_warehouse.backend.types import ExternalDataSourceType+from products.product_analytics.backend.models.insight_variable import InsightVariablefrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcediff --git a/posthog/management/commands/backfill_insights_query_metadata.py b/posthog/management/commands/backfill_insights_query_metadata.pyindex 79ab04290373..fe11c10ee2bf 100644--- a/posthog/management/commands/backfill_insights_query_metadata.py+++ b/posthog/management/commands/backfill_insights_query_metadata.py@@ -11,7 +11,8 @@ from django.db.models import Qimport structlogfrom posthog.hogql_queries.query_metadata import InsightQueryMetadata-from posthog.models import Insight++from products.product_analytics.backend.models.insight import Insightlogger = structlog.get_logger(__name__)diff --git a/posthog/management/commands/migrate_retention_show_mean.py b/posthog/management/commands/migrate_retention_show_mean.pyindex b22ce3eb6c62..0bfc1709f63b 100644--- a/posthog/management/commands/migrate_retention_show_mean.py+++ b/posthog/management/commands/migrate_retention_show_mean.py@@ -1,7 +1,7 @@from django.core.management.base import BaseCommandfrom django.db import transaction-from posthog.models import Insight+from products.product_analytics.backend.models.insight import Insightdef migrate_show_mean_from_boolean_to_string(batch_size: int, live_run: bool = False) -> None:diff --git a/posthog/middleware.py b/posthog/middleware.pyindex 9254378b9992..d637068d1e13 100644--- a/posthog/middleware.py+++ b/posthog/middleware.py@@ -40,7 +40,7 @@ from posthog.event_usage import get_event_source, get_mcp_properties, sanitize_hfrom posthog.geoip import get_geoip_propertiesfrom posthog.helpers.impersonation import get_original_user_from_sessionfrom posthog.helpers.user_devices import set_known_device_cookie-from posthog.models import Cohort, Insight, Team, User+from posthog.models import Cohort, Team, Userfrom posthog.models.activity_logging.utils import (ACTIVITY_LOG_CLIENT_HEADER,ACTIVITY_LOG_CLIENT_MAX_LENGTH,@@ -56,6 +56,7 @@ from products.actions.backend.models.action import Actionfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebook+from products.product_analytics.backend.models.insight import Insightfrom .auth import PersonalAPIKeyAuthenticationdiff --git a/posthog/migrations/0156_insight_short_id.py b/posthog/migrations/0156_insight_short_id.pyindex ccbcbf14308a..f8edcfc73e33 100644--- a/posthog/migrations/0156_insight_short_id.py+++ b/posthog/migrations/0156_insight_short_id.py@@ -2,7 +2,7 @@from django.db import migrations, models-import posthog.models.insight+import posthog.utilsdef create_short_ids(apps, schema_editor):diff --git a/posthog/migrations/1183_migrate_product_analytics_models_state.py b/posthog/migrations/1183_migrate_product_analytics_models_state.pynew file mode 100644index 000000000000..82faddf5fa5e--- /dev/null+++ b/posthog/migrations/1183_migrate_product_analytics_models_state.py@@ -0,0 +1,41 @@+# Generated by Django 5.2.14 on 2026-05-22 11:19++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1182_migrate_feature_flags_models"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AlterUniqueTogether(+ name="insight",+ unique_together=None,+ ),+ migrations.RemoveField(+ model_name="insight",+ name="created_by",+ ),+ migrations.RemoveField(+ model_name="insight",+ name="dashboard",+ ),+ migrations.RemoveField(+ model_name="insight",+ name="dive_dashboard",+ ),+ migrations.RemoveField(+ model_name="insight",+ name="last_modified_by",+ ),+ migrations.RemoveField(+ model_name="insight",+ name="team",+ ),+ ],+ database_operations=[],+ ),+ ]diff --git a/posthog/migrations/1184_migrate_product_analytics_models.py b/posthog/migrations/1184_migrate_product_analytics_models.pynew file mode 100644index 000000000000..183e750c4d24--- /dev/null+++ b/posthog/migrations/1184_migrate_product_analytics_models.py@@ -0,0 +1,160 @@+# Generated by Django 5.2.14 on 2026-05-22 11:19++import django.db.models.deletion+from django.db import migrations, models++MODELS_TO_MOVE = ("insight", "insightcachingstate", "insightvariable", "insightviewed")+++def _move_content_types(apps, schema_editor, from_label, to_label):+ """Move ContentTypes between apps, handling duplicates idempotently.++ If the target (app_label, model) already exists (e.g., Django auto-created+ it before migration ran, or a prior failed attempt), merges permissions+ onto the target and deletes the source to avoid unique constraint violations.++ Uses schema_editor.connection.alias for multi-DB safety.+ """+ db_alias = schema_editor.connection.alias+ ContentType = apps.get_model("contenttypes", "ContentType")+ Permission = apps.get_model("auth", "Permission")++ for model_name in MODELS_TO_MOVE:+ source = ContentType.objects.using(db_alias).filter(app_label=from_label, model=model_name).first()+ target = ContentType.objects.using(db_alias).filter(app_label=to_label, model=model_name).first()++ if source and target:+ Permission.objects.using(db_alias).filter(content_type=source).update(content_type=target)+ source.delete(using=db_alias)+ elif source:+ source.app_label = to_label+ source.save(using=db_alias)+++def update_content_types(apps, schema_editor):+ _move_content_types(apps, schema_editor, "posthog", "product_analytics")+++def reverse_content_types(apps, schema_editor):+ _move_content_types(apps, schema_editor, "product_analytics", "posthog")+++class Migration(migrations.Migration):+ dependencies = [+ ("alerts", "0002_migrate_product_analytics_models"),+ ("customer_analytics", "0006_migrate_product_analytics_models"),+ ("dashboards", "0006_migrate_product_analytics_models"),+ ("posthog", "1183_migrate_product_analytics_models_state"),+ ("product_analytics", "0001_migrate_product_analytics_models"),+ ("surveys", "0005_migrate_product_analytics_models"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AlterField(+ model_name="sharingconfiguration",+ name="insight",+ field=models.ForeignKey(+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ to="product_analytics.insight",+ ),+ ),+ migrations.RemoveField(+ model_name="insightcachingstate",+ name="insight",+ ),+ migrations.RemoveField(+ model_name="insightviewed",+ name="insight",+ ),+ migrations.AlterField(+ model_name="subscription",+ name="insight",+ field=models.ForeignKey(+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ to="product_analytics.insight",+ ),+ ),+ migrations.AlterField(+ model_name="annotation",+ name="dashboard_item",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to="product_analytics.insight",+ ),+ ),+ migrations.AlterField(+ model_name="taggeditem",+ name="insight",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="tagged_items",+ to="product_analytics.insight",+ ),+ ),+ migrations.AlterField(+ model_name="exportedasset",+ name="insight",+ field=models.ForeignKey(+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ to="product_analytics.insight",+ ),+ ),+ migrations.RemoveField(+ model_name="insightcachingstate",+ name="dashboard_tile",+ ),+ migrations.RemoveField(+ model_name="insightcachingstate",+ name="team",+ ),+ migrations.RemoveField(+ model_name="insightvariable",+ name="created_by",+ ),+ migrations.RemoveField(+ model_name="insightvariable",+ name="team",+ ),+ migrations.RemoveField(+ model_name="insightviewed",+ name="team",+ ),+ migrations.RemoveField(+ model_name="insightviewed",+ name="user",+ ),+ migrations.AlterField(+ model_name="subscription",+ name="dashboard_export_insights",+ field=models.ManyToManyField(+ blank=True,+ related_name="subscriptions_dashboard_export",+ to="product_analytics.insight",+ ),+ ),+ migrations.DeleteModel(+ name="Insight",+ ),+ migrations.DeleteModel(+ name="InsightCachingState",+ ),+ migrations.DeleteModel(+ name="InsightVariable",+ ),+ migrations.DeleteModel(+ name="InsightViewed",+ ),+ ],+ database_operations=[],+ ),+ migrations.RunPython(update_content_types, reverse_content_types),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex d4a743cad995..4282e86c14b1 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1182_migrate_feature_flags_models+1184_migrate_product_analytics_modelsdiff --git a/posthog/models/__init__.py b/posthog/models/__init__.pyindex 354f41ec5fe6..01e9ed934e15 100644--- a/posthog/models/__init__.py+++ b/posthog/models/__init__.py@@ -50,9 +50,6 @@ from .hog_flow import HogFlowfrom .hog_functions import HogFunctionfrom .hog_function_template import HogFunctionTemplatefrom .health_issue import HealthIssue-from .insight import Insight, InsightViewed-from .insight_caching_state import InsightCachingState-from .insight_variable import InsightVariablefrom .instance_setting import InstanceSettingfrom .integration import Integrationfrom .integration_repository_cache import IntegrationRepositoryCacheEntry@@ -157,10 +154,6 @@ __all__ = ["HogFunctionTemplate","LLMPrompt","HostDefinition",- "Insight",- "InsightCachingState",- "InsightVariable",- "InsightViewed","InstanceSetting","Integration","IntegrationRepositoryCacheEntry",diff --git a/posthog/models/annotation.py b/posthog/models/annotation.pyindex ddd3e603836d..e5c9456c8d92 100644--- a/posthog/models/annotation.py+++ b/posthog/models/annotation.py@@ -23,7 +23,7 @@ class Annotation(ModelActivityMixin, models.Model):content = models.CharField(max_length=8192, null=True, blank=True)created_at = models.DateTimeField(default=timezone.now, null=True)updated_at = models.DateTimeField(auto_now=True)- dashboard_item = models.ForeignKey("posthog.Insight", on_delete=models.SET_NULL, null=True, blank=True)+ dashboard_item = models.ForeignKey("product_analytics.Insight", on_delete=models.SET_NULL, null=True, blank=True)dashboard = models.ForeignKey("dashboards.Dashboard", on_delete=models.SET_NULL, null=True, blank=True)team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)organization = models.ForeignKey("posthog.Organization", on_delete=models.CASCADE, null=True)diff --git a/posthog/models/exported_asset.py b/posthog/models/exported_asset.pyindex 67b37615b820..0c5223668b9f 100644--- a/posthog/models/exported_asset.py+++ b/posthog/models/exported_asset.py@@ -68,7 +68,7 @@ class ExportedAsset(models.Model):# Relationsteam = models.ForeignKey("Team", on_delete=models.CASCADE)dashboard = models.ForeignKey("dashboards.Dashboard", on_delete=models.CASCADE, null=True)- insight = models.ForeignKey("posthog.Insight", on_delete=models.CASCADE, null=True)+ insight = models.ForeignKey("product_analytics.Insight", on_delete=models.CASCADE, null=True)# Content related fieldsexport_format = models.CharField(max_length=100, choices=ExportFormat)diff --git a/posthog/models/file_system/test/test_file_system.py b/posthog/models/file_system/test/test_file_system.pyindex c3383285ffe7..1d3baa477ba5 100644--- a/posthog/models/file_system/test/test_file_system.py+++ b/posthog/models/file_system/test/test_file_system.py@@ -1,6 +1,6 @@from django.test import TestCase-from posthog.models import Insight, Organization, Team, User+from posthog.models import Organization, Team, Userfrom posthog.models.file_system.file_system import FileSystem, escape_path, join_path, split_pathfrom posthog.models.file_system.unfiled_file_saver import save_unfiled_files@@ -8,6 +8,7 @@ from products.dashboards.backend.models.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebook+from products.product_analytics.backend.models.insight import Insightclass TestFileSystemModel(TestCase):diff --git a/posthog/models/file_system/test/test_file_system_mixin.py b/posthog/models/file_system/test/test_file_system_mixin.pyindex 91ab599d52a7..33aae873e78d 100644--- a/posthog/models/file_system/test/test_file_system_mixin.py+++ b/posthog/models/file_system/test/test_file_system_mixin.py@@ -1,11 +1,12 @@from django.test import TestCase-from posthog.models import FileSystem, Insight, Organization, Team, User+from posthog.models import FileSystem, Organization, Team, Userfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebook+from products.product_analytics.backend.models.insight import Insightclass TestFileSystemSyncMixin(TestCase):diff --git a/posthog/models/file_system/test/test_file_system_view_log.py b/posthog/models/file_system/test/test_file_system_view_log.pyindex d17b501e33f5..cfeccbd773bc 100644--- a/posthog/models/file_system/test/test_file_system_view_log.py+++ b/posthog/models/file_system/test/test_file_system_view_log.py@@ -5,10 +5,11 @@ from freezegun import freeze_timefrom django.test import TestCase-from posthog.models import FileSystem, FileSystemViewLog, Insight, Organization, Team, User+from posthog.models import FileSystem, FileSystemViewLog, Organization, Team, Userfrom posthog.models.file_system.file_system_view_log import get_recent_file_system_items, log_file_system_viewfrom products.dashboards.backend.models.dashboard import Dashboard+from products.product_analytics.backend.models.insight import Insightclass FileSystemWithLastViewed(Protocol):diff --git a/posthog/models/file_system/unfiled_file_saver.py b/posthog/models/file_system/unfiled_file_saver.pyindex cb6b4ce6e5fc..845386d28ec8 100644--- a/posthog/models/file_system/unfiled_file_saver.py+++ b/posthog/models/file_system/unfiled_file_saver.py@@ -8,7 +8,6 @@ from posthog.models.cohort import Cohortfrom posthog.models.file_system.file_system import FileSystem, escape_path, split_pathfrom posthog.models.file_system.file_system_mixin import FileSystemSyncMixinfrom posthog.models.hog_functions.hog_function import HogFunction-from posthog.models.insight import Insightfrom posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist@@ -20,6 +19,7 @@ from products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.links.backend.models import Linkfrom products.notebooks.backend.models import Notebook+from products.product_analytics.backend.models.insight import Insightfrom products.surveys.backend.models import SurveyMIXIN_MODELS = {diff --git a/posthog/models/product_intent/product_intent.py b/posthog/models/product_intent/product_intent.pyindex df1cc067dad2..acab275e93e8 100644--- a/posthog/models/product_intent/product_intent.py+++ b/posthog/models/product_intent/product_intent.py@@ -14,7 +14,6 @@ from posthog.schema import ProductIntentContext, ProductKeyfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.hog_flow.hog_flow import HogFlow-from posthog.models.insight import Insightfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.models.utils import RootTeamMixin, UUIDTModel@@ -27,6 +26,7 @@ from products.error_tracking.backend.models import ErrorTrackingIssuefrom products.event_definitions.backend.models.event_definition import EventDefinitionfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.product_analytics.backend.models.insight import Insightfrom products.product_tours.backend.models import ProductTourfrom products.surveys.backend.models import Surveydiff --git a/posthog/models/resource_transfer/test/test_inter_project_transferer.py b/posthog/models/resource_transfer/test/test_inter_project_transferer.pyindex d2d2a0e193a8..ee9aeadf7688 100644--- a/posthog/models/resource_transfer/test/test_inter_project_transferer.py+++ b/posthog/models/resource_transfer/test/test_inter_project_transferer.py@@ -4,7 +4,7 @@ from posthog.test.base import BaseTestfrom parameterized import parameterized-from posthog.models import Insight, Project, Team+from posthog.models import Project, Teamfrom posthog.models.resource_transfer.inter_project_transferer import (_get_mapped_substitutions,build_resource_duplication_graph,@@ -18,6 +18,7 @@ from posthog.models.resource_transfer.types import ResourceKind, ResourceTransfefrom products.actions.backend.models.action import Actionfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile, Text+from products.product_analytics.backend.models.insight import Insightfrom products.surveys.backend.models import Surveydiff --git a/posthog/models/resource_transfer/visitors/insight.py b/posthog/models/resource_transfer/visitors/insight.pyindex 350c6e1509bf..a9b85b3451e2 100644--- a/posthog/models/resource_transfer/visitors/insight.py+++ b/posthog/models/resource_transfer/visitors/insight.py@@ -31,7 +31,7 @@ class InsightVisitor():@classmethoddef get_model(cls) -> type[models.Model]:- from posthog.models import Insight+ from products.product_analytics.backend.models.insight import Insightreturn Insightdiff --git a/posthog/models/sharing_configuration.py b/posthog/models/sharing_configuration.pyindex 43fb8627c3d8..3c0dce6e8da5 100644--- a/posthog/models/sharing_configuration.py+++ b/posthog/models/sharing_configuration.py@@ -12,7 +12,8 @@ from django.utils import timezoneimport structlogfrom posthog.jwt import PosthogJwtAudience, encode_jwt-from posthog.models.insight import Insight++from products.product_analytics.backend.models.insight import Insightlogger = structlog.get_logger(__name__)@@ -25,7 +26,7 @@ class SharingConfiguration(models.Model):# Relationsteam = models.ForeignKey("Team", on_delete=models.CASCADE)dashboard = models.ForeignKey("dashboards.Dashboard", on_delete=models.CASCADE, null=True)- insight = models.ForeignKey("posthog.Insight", on_delete=models.CASCADE, null=True)+ insight = models.ForeignKey("product_analytics.Insight", on_delete=models.CASCADE, null=True)recording = models.ForeignKey("SessionRecording",related_name="sharing_configurations",diff --git a/posthog/models/subscription.py b/posthog/models/subscription.pyindex e744f24ad20c..26ed2d74511a 100644--- a/posthog/models/subscription.py+++ b/posthog/models/subscription.py@@ -77,9 +77,9 @@ class Subscription(models.Model):# Relations - i.e. WHAT are we exporting?team = models.ForeignKey("Team", on_delete=models.CASCADE)dashboard = models.ForeignKey("dashboards.Dashboard", on_delete=models.CASCADE, null=True)- insight = models.ForeignKey("posthog.Insight", on_delete=models.CASCADE, null=True)+ insight = models.ForeignKey("product_analytics.Insight", on_delete=models.CASCADE, null=True)dashboard_export_insights = models.ManyToManyField(- "posthog.Insight",+ "product_analytics.Insight",blank=True,related_name="subscriptions_dashboard_export",)diff --git a/posthog/models/tagged_item.py b/posthog/models/tagged_item.pyindex 4ad1fc113466..1e3865380b3a 100644--- a/posthog/models/tagged_item.py+++ b/posthog/models/tagged_item.py@@ -45,7 +45,7 @@ class TaggedItem(ModelActivityMixin, UUIDTModel):related_name="tagged_items",)insight = models.ForeignKey(- "Insight",+ "product_analytics.Insight",on_delete=models.CASCADE,null=True,blank=True,diff --git a/posthog/models/team/util.py b/posthog/models/team/util.pyindex 79a495a211d4..0c93f7d7aa4e 100644--- a/posthog/models/team/util.py+++ b/posthog/models/team/util.py@@ -28,12 +28,12 @@ def delete_bulky_postgres_data(team_ids: list[int]):from posthog.models.cohort import Cohortfrom posthog.models.file_system.file_system_view_log import FileSystemViewLog- from posthog.models.insight_caching_state import InsightCachingStatefrom products.data_modeling.backend.models import Edge, Nodefrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.error_tracking.backend.models import ErrorTrackingIssueFingerprintV2from products.feature_flags.backend.models.feature_flag import FeatureFlagHashKeyOverride+ from products.product_analytics.backend.models.insight_caching_state import InsightCachingState# Delete data modeling nodes and edges first to not block Team deletion.# Team cascades to DataWarehouseSavedQuery, but it has PROTECT on delete.diff --git a/posthog/models/test/test_dashboard_tile_model.py b/posthog/models/test/test_dashboard_tile_model.pyindex 70f6c6134adc..41777d612258 100644--- a/posthog/models/test/test_dashboard_tile_model.py+++ b/posthog/models/test/test_dashboard_tile_model.py@@ -6,10 +6,10 @@ from django.core.exceptions import ValidationErrorfrom django.db.utils import IntegrityErrorfrom posthog.models.exported_asset import ExportedAsset-from posthog.models.insight import Insightfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile, Text+from products.product_analytics.backend.models.insight import Insightclass TestDashboardTileModel(APIBaseTest):diff --git a/posthog/models/test/test_product_intent.py b/posthog/models/test/test_product_intent.pyindex a8030e2d82d9..37046b59d022 100644--- a/posthog/models/test/test_product_intent.py+++ b/posthog/models/test/test_product_intent.py@@ -13,7 +13,6 @@ from posthog.schema import ProductIntentContext, ProductKeyfrom posthog.models.file_system.user_product_list import UserProductListfrom posthog.models.hog_flow.hog_flow import HogFlow-from posthog.models.insight import Insightfrom posthog.models.product_intent.product_intent import (ProductIntent,_fetch_product_intents,@@ -30,6 +29,7 @@ from products.dashboards.backend.models.dashboard import Dashboardfrom products.event_definitions.backend.models.event_definition import EventDefinitionfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.product_analytics.backend.models.insight import Insightfrom products.surveys.backend.models import Surveydiff --git a/posthog/models/test/test_subscription_model.py b/posthog/models/test/test_subscription_model.pyindex 79cbda02b1dd..38396125b9e2 100644--- a/posthog/models/test/test_subscription_model.py+++ b/posthog/models/test/test_subscription_model.py@@ -14,7 +14,6 @@ import jwtfrom parameterized import parameterizedfrom posthog.jwt import PosthogJwtAudience-from posthog.models.insight import Insightfrom posthog.models.subscription import (UNSUBSCRIBE_TOKEN_EXP_DAYS,Subscription,@@ -23,6 +22,8 @@ from posthog.models.subscription import (unsubscribe_using_token,)+from products.product_analytics.backend.models.insight import Insight+@patch.object(settings, "SECRET_KEY", "not-so-secret")@freeze_time("2022-01-01")diff --git a/posthog/models/test/test_tagged_item_model.py b/posthog/models/test/test_tagged_item_model.pyindex 92eaaf36d44e..f3763098838a 100644--- a/posthog/models/test/test_tagged_item_model.py+++ b/posthog/models/test/test_tagged_item_model.py@@ -2,11 +2,12 @@ from posthog.test.base import BaseTestfrom django.core.exceptions import ValidationError-from posthog.models import Insight, Tag, TaggedItem+from posthog.models import Tag, TaggedItemfrom products.actions.backend.models.action import Actionfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insightclass TestTaggedItem(BaseTest):diff --git a/posthog/rbac/test/test_user_access_control.py b/posthog/rbac/test/test_user_access_control.pyindex 6ae294d564c2..1ade2fa59701 100644--- a/posthog/rbac/test/test_user_access_control.py+++ b/posthog/rbac/test/test_user_access_control.py@@ -1052,7 +1052,7 @@ class TestUserAccessControlSpecificAccessLevelForObject(BaseUserAccessControlTesdef test_insight_specific_access_control(self):"""Test insight-specific access controls"""- from posthog.models.insight import Insight+ from products.product_analytics.backend.models.insight import Insightinsight = Insight.objects.create(team=self.team, created_by=self.other_user)diff --git a/posthog/schema_migrations/upgrade_manager.py b/posthog/schema_migrations/upgrade_manager.pyindex 8672a3208a29..ba7d0153b01d 100644--- a/posthog/schema_migrations/upgrade_manager.py+++ b/posthog/schema_migrations/upgrade_manager.py@@ -6,7 +6,7 @@ from posthog.hogql_queries.legacy_compatibility.flagged_conversion_manager imporfrom posthog.schema_migrations.upgrade import upgradeif TYPE_CHECKING:- from posthog.models.insight import Insight+ from products.product_analytics.backend.models.insight import Insight@contextmanagerdiff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex a4484790e1c6..afe9edadf6f3 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -80,6 +80,7 @@ PRODUCTS_APPS = ["products.data_tools.backend.apps.DataToolsConfig","products.alerts.backend.apps.AlertsConfig","products.actions.backend.apps.ActionsConfig",+ "products.product_analytics.backend.apps.ProductAnalyticsConfig","products.wizard.backend.apps.WizardConfig",]diff --git a/posthog/tasks/alerts/detector.py b/posthog/tasks/alerts/detector.pyindex 84097212b901..4da72ce8802c 100644--- a/posthog/tasks/alerts/detector.py+++ b/posthog/tasks/alerts/detector.py@@ -7,7 +7,6 @@ from posthog.schema import DetectorType, IntervalType, TrendsAlertConfig, Trendsfrom posthog.api.services.query import ExecutionModefrom posthog.caching.calculate_results import calculate_for_query_based_insight-from posthog.models import Insightfrom posthog.schema_migrations.upgrade_manager import upgrade_queryfrom posthog.tasks.alerts.detectors import get_detectorfrom posthog.tasks.alerts.detectors.base import DetectionResult@@ -22,6 +21,7 @@ from posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, AlertEvaluationResultfrom posthog.utils import get_from_dict_or_attrfrom products.alerts.backend.models.alert import AlertConfiguration+from products.product_analytics.backend.models.insight import Insight# Minimum samples required for each detector typeDETECTOR_MIN_SAMPLES: dict[DetectorType, int] = {diff --git a/posthog/tasks/alerts/test/test_detector_breakdowns.py b/posthog/tasks/alerts/test/test_detector_breakdowns.pyindex 16053b28a617..2bfd8102f488 100644--- a/posthog/tasks/alerts/test/test_detector_breakdowns.py+++ b/posthog/tasks/alerts/test/test_detector_breakdowns.py@@ -15,7 +15,6 @@ from posthog.schema import ()from posthog.caching.fetch_from_cache import InsightResult-from posthog.models import Insightfrom posthog.tasks.alerts.detector import (MAX_DETECTOR_BREAKDOWN_VALUES,check_trends_alert_with_detector,@@ -23,6 +22,7 @@ from posthog.tasks.alerts.detector import ()from products.alerts.backend.models.alert import AlertConfiguration+from products.product_analytics.backend.models.insight import Insightdef _make_trend_result(label: str, data: list[float], breakdown_value: str = "") -> dict[str, Any]:diff --git a/posthog/tasks/alerts/test/test_investigation_notifications.py b/posthog/tasks/alerts/test/test_investigation_notifications.pyindex e340b21e7287..0f762b5eedee 100644--- a/posthog/tasks/alerts/test/test_investigation_notifications.py+++ b/posthog/tasks/alerts/test/test_investigation_notifications.py@@ -8,7 +8,6 @@ from parameterized import parameterizedfrom posthog.schema import AlertState-from posthog.models import Insightfrom posthog.tasks.alerts.investigation_notifications import (INVESTIGATION_NOTIFY_GRACE_MINUTES,INVESTIGATION_RUNNING_GRACE_MINUTES,@@ -16,6 +15,7 @@ from posthog.tasks.alerts.investigation_notifications import ()from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus+from products.product_analytics.backend.models.insight import InsightNOW = datetime(2026, 5, 4, 12, 0, 0, tzinfo=UTC)diff --git a/posthog/tasks/alerts/trends.py b/posthog/tasks/alerts/trends.pyindex 9f2ab65eab38..cc758ffacc5d 100644--- a/posthog/tasks/alerts/trends.py+++ b/posthog/tasks/alerts/trends.py@@ -18,10 +18,10 @@ from posthog.caching.calculate_results import calculate_for_query_based_insightfrom posthog.caching.fetch_from_cache import InsightResultfrom posthog.event_usage import EventSourcefrom posthog.hogql_queries.insights.utils.breakdowns import has_breakdown_filter-from posthog.models import Insightfrom posthog.tasks.alerts.utils import NON_TIME_SERIES_DISPLAY_TYPES, AlertEvaluationResultfrom products.alerts.backend.models.alert import AlertConfiguration+from products.product_analytics.backend.models.insight import Insight# TODO: move the TrendResult UI type to schema.ts and use that insteaddiff --git a/posthog/tasks/exports/image_exporter.py b/posthog/tasks/exports/image_exporter.pyindex d21fcf85a715..cbf3d9222cbb 100644--- a/posthog/tasks/exports/image_exporter.py+++ b/posthog/tasks/exports/image_exporter.py@@ -22,12 +22,10 @@ from webdriver_manager.core.os_manager import ChromeTypefrom posthog.schema import FunnelLayout, NodeKind-from posthog.api.insight_variable import map_stale_to_latestfrom posthog.caching.calculate_results import calculate_for_query_based_insightfrom posthog.event_usage import AnalyticsProps, EventSourcefrom posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.query_runner import ExecutionMode-from posthog.models import InsightVariablefrom posthog.models.exported_asset import ExportedAsset, get_public_access_token, save_contentfrom posthog.schema_migrations.upgrade_manager import upgrade_queryfrom posthog.security.url_validation import is_url_allowed@@ -36,6 +34,8 @@ from posthog.tasks.exports.exporter_utils import log_error_if_site_url_not_reachfrom posthog.utils import absolute_urifrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.api.insight_variable import map_stale_to_latest+from products.product_analytics.backend.models.insight_variable import InsightVariablelogger = structlog.get_logger(__name__)diff --git a/posthog/tasks/exports/test/test_image_exporter.py b/posthog/tasks/exports/test/test_image_exporter.pyindex c13ac8df0d26..ffa819ffc387 100644--- a/posthog/tasks/exports/test/test_image_exporter.py+++ b/posthog/tasks/exports/test/test_image_exporter.py@@ -8,10 +8,9 @@ from boto3 import resourcefrom botocore.client import Configfrom parameterized import parameterized-from posthog.api.insight_variable import map_stale_to_latestfrom posthog.caching.fetch_from_cache import InsightResultfrom posthog.hogql_queries.query_runner import ExecutionMode-from posthog.models import ExportedAsset, Insight, InsightVariable+from posthog.models import ExportedAssetfrom posthog.settings import (OBJECT_STORAGE_ACCESS_KEY_ID,OBJECT_STORAGE_BUCKET,@@ -24,6 +23,9 @@ from posthog.tasks.exports import image_exporterfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.api.insight_variable import map_stale_to_latest+from products.product_analytics.backend.models.insight import Insight+from products.product_analytics.backend.models.insight_variable import InsightVariabledef make_insight_result(cache_key: str) -> InsightResult:diff --git a/posthog/temporal/ai/anomaly_investigation/notebook.py b/posthog/temporal/ai/anomaly_investigation/notebook.pyindex 282d3e4dea22..3100f7bfdfab 100644--- a/posthog/temporal/ai/anomaly_investigation/notebook.py+++ b/posthog/temporal/ai/anomaly_investigation/notebook.py@@ -3,7 +3,6 @@ import uuidfrom dataclasses import dataclassfrom typing import Any-from posthog.models import Insightfrom posthog.temporal.ai.anomaly_investigation.report import InvestigationReportfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration@@ -15,6 +14,7 @@ from products.notebooks.backend.util import (create_heading_with_text,create_paragraph_with_text,)+from products.product_analytics.backend.models.insight import InsightVERDICT_LABEL = {"true_positive": "True positive",diff --git a/posthog/temporal/product_analytics/upgrade_queries_activities.py b/posthog/temporal/product_analytics/upgrade_queries_activities.pyindex 1e8369c6a749..1c62c4a7655c 100644--- a/posthog/temporal/product_analytics/upgrade_queries_activities.py+++ b/posthog/temporal/product_analytics/upgrade_queries_activities.py@@ -7,10 +7,11 @@ from django.db import connectionfrom structlog import get_loggerfrom temporalio import activity-from posthog.models import Insightfrom posthog.schema_migrations import LATEST_VERSIONSfrom posthog.schema_migrations.upgrade import upgrade+from products.product_analytics.backend.models.insight import Insight+LOGGER = get_logger(__name__)diff --git a/posthog/temporal/subscriptions/activities.py b/posthog/temporal/subscriptions/activities.pyindex 3d19f5353784..cbedafaf4ac8 100644--- a/posthog/temporal/subscriptions/activities.py+++ b/posthog/temporal/subscriptions/activities.py@@ -13,7 +13,6 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.exported_asset import ExportedAsset-from posthog.models.insight import Insightfrom posthog.models.subscription import Subscription, SubscriptionDeliveryfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.subscriptions.insight_snapshot import (@@ -34,6 +33,7 @@ from posthog.temporal.subscriptions.types import ()from products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insightfrom ee.tasks.subscriptions import SLACK_USER_CONFIG_ERRORS, _capture_delivery_failed_eventfrom ee.tasks.subscriptions.auto_disable import (diff --git a/posthog/temporal/subscriptions/insight_snapshot.py b/posthog/temporal/subscriptions/insight_snapshot.pyindex 6d5073d76678..f7079a8d6ded 100644--- a/posthog/temporal/subscriptions/insight_snapshot.py+++ b/posthog/temporal/subscriptions/insight_snapshot.py@@ -23,11 +23,12 @@ from pydantic_core import to_jsonable_pythonfrom posthog.api.services.query import ExecutionModefrom posthog.caching.calculate_results import calculate_cache_key, calculate_for_query_based_insightfrom posthog.caching.fetch_from_cache import InsightResult, NothingInCacheResult-from posthog.models import Insight, Team, User+from posthog.models import Team, Userfrom posthog.models.subscription import Subscriptionfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insightlogger = structlog.get_logger(__name__)diff --git a/posthog/temporal/subscriptions/llm_change_summary.py b/posthog/temporal/subscriptions/llm_change_summary.pyindex 6ad95ab12775..e364f3a914b2 100644--- a/posthog/temporal/subscriptions/llm_change_summary.py+++ b/posthog/temporal/subscriptions/llm_change_summary.py@@ -16,7 +16,6 @@ from prometheus_client import Counterif TYPE_CHECKING:from posthog.models.team.team import Team-from posthog.api.insight_suggestions import get_query_specific_instructionsfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.llm_prompt import normalize_prompt_to_stringfrom posthog.temporal.subscriptions.prompt_sanitization import (@@ -28,6 +27,8 @@ from posthog.temporal.subscriptions.prompt_sanitization import ()from posthog.utils import get_instance_region+from products.product_analytics.backend.api.insight_suggestions import get_query_specific_instructions+logger = structlog.get_logger(__name__)SUBSCRIPTION_PROMPT_SOURCE = Counter(diff --git a/posthog/temporal/subscriptions/snapshot_activities.py b/posthog/temporal/subscriptions/snapshot_activities.pyindex 2050d951511e..0e8c81af8fc8 100644--- a/posthog/temporal/subscriptions/snapshot_activities.py+++ b/posthog/temporal/subscriptions/snapshot_activities.py@@ -8,7 +8,6 @@ from structlog import get_loggerfrom posthog.api.annotation_context import build_annotations_block, resolve_snapshot_date_rangefrom posthog.constants import SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE_FEATURE_FLAG_KEY-from posthog.models import Insightfrom posthog.models.exported_asset import ExportedAssetfrom posthog.models.subscription import Subscription, SubscriptionDeliveryfrom posthog.ph_client import ph_scoped_capture@@ -19,6 +18,8 @@ from posthog.temporal.subscriptions.prompt_sanitization import PROMPT_GUIDE_MAX_from posthog.temporal.subscriptions.results_summarizer import build_results_summaryfrom posthog.temporal.subscriptions.types import SnapshotInsightsInputs, SnapshotInsightsResult+from products.product_analytics.backend.models.insight import Insight+from ee.models import CoreMemoryLOGGER = get_logger(__name__)diff --git a/posthog/temporal/subscriptions/test_snapshot_ai_consent.py b/posthog/temporal/subscriptions/test_snapshot_ai_consent.pyindex e7f59b4ecfc7..26a77decbc42 100644--- a/posthog/temporal/subscriptions/test_snapshot_ai_consent.py+++ b/posthog/temporal/subscriptions/test_snapshot_ai_consent.py@@ -8,11 +8,12 @@ import structlogfrom asgiref.sync import sync_to_asyncfrom temporalio.testing import ActivityEnvironment-from posthog.models.insight import Insightfrom posthog.models.subscription import Subscription, SubscriptionDeliveryfrom posthog.temporal.subscriptions.snapshot_activities import snapshot_subscription_insightsfrom posthog.temporal.subscriptions.types import SnapshotInsightsInputs+from products.product_analytics.backend.models.insight import Insight+from ee.models import CoreMemorypytestmark = [pytest.mark.asyncio, pytest.mark.django_db(transaction=True)]diff --git a/posthog/temporal/subscriptions/test_snapshot_annotations.py b/posthog/temporal/subscriptions/test_snapshot_annotations.pyindex caec07b24ce6..d83bc4004a82 100644--- a/posthog/temporal/subscriptions/test_snapshot_annotations.py+++ b/posthog/temporal/subscriptions/test_snapshot_annotations.py@@ -9,9 +9,11 @@ from posthog.test.base import APIBaseTestfrom parameterized import parameterizedfrom posthog.api.annotation_context import resolve_snapshot_date_range-from posthog.models import Annotation, Insight+from posthog.models import Annotationfrom posthog.temporal.subscriptions.snapshot_activities import _load_annotations_section+from products.product_analytics.backend.models.insight import Insight+def _snap_with_range(date_from: str | None, date_to: str | None) -> dict:qr: dict = {}diff --git a/posthog/temporal/subscriptions/test_snapshot_image_loading.py b/posthog/temporal/subscriptions/test_snapshot_image_loading.pyindex d1b8fea8ec83..787db5a29ea6 100644--- a/posthog/temporal/subscriptions/test_snapshot_image_loading.py+++ b/posthog/temporal/subscriptions/test_snapshot_image_loading.py@@ -4,13 +4,14 @@ import pytestfrom unittest.mock import patchfrom posthog.models.exported_asset import ExportedAsset-from posthog.models.insight import Insightfrom posthog.temporal.subscriptions.snapshot_activities import (MAX_SUMMARY_IMAGES,SUBSCRIPTION_SUMMARY_IMAGE_SKIPPED,_load_insight_images,)+from products.product_analytics.backend.models.insight import Insight+pytestmark = pytest.mark.django_dbdiff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_notebook.py b/posthog/temporal/tests/ai/test_anomaly_investigation_notebook.pyindex 2949c3fca511..e15decb2a109 100644--- a/posthog/temporal/tests/ai/test_anomaly_investigation_notebook.py+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_notebook.py@@ -1,10 +1,10 @@from posthog.test.base import BaseTest-from posthog.models import Insightfrom posthog.temporal.ai.anomaly_investigation.notebook import NotebookRenderContext, build_investigation_notebookfrom posthog.temporal.ai.anomaly_investigation.report import InvestigationHypothesis, InvestigationReportfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration+from products.product_analytics.backend.models.insight import Insightclass TestAnomalyInvestigationNotebook(BaseTest):diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.pyindex 1793a316d782..284d7fc0b1b7 100644--- a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py@@ -8,7 +8,6 @@ from asgiref.sync import sync_to_asyncfrom posthog.schema import AlertState-from posthog.models import Insightfrom posthog.temporal.ai.anomaly_investigation.report import InvestigationReportfrom posthog.temporal.ai.anomaly_investigation.runner import InvestigationRunResultfrom posthog.temporal.ai.anomaly_investigation.workflow import (@@ -22,6 +21,7 @@ from products.alerts.backend.models.alert import (InvestigationStatus,InvestigationVerdict,)+from products.product_analytics.backend.models.insight import Insightclass TestInvestigationVerdictPersistence(NonAtomicBaseTest):diff --git a/posthog/temporal/tests/product_analytics/test_upgrade_queries_workflow.py b/posthog/temporal/tests/product_analytics/test_upgrade_queries_workflow.pyindex dc2668ab0f09..1d59a4b2c0a9 100644--- a/posthog/temporal/tests/product_analytics/test_upgrade_queries_workflow.py+++ b/posthog/temporal/tests/product_analytics/test_upgrade_queries_workflow.py@@ -13,7 +13,6 @@ from temporalio.worker import UnsandboxedWorkflowRunner, Workerfrom posthog.schema import NodeKindimport posthog.schema_migrations as schema_migrations_module-from posthog.models.insight import Insightfrom posthog.schema_migrations import LATEST_VERSIONS, MIGRATIONS, SchemaMigration, _discover_migrationsfrom posthog.temporal.product_analytics.upgrade_queries_activities import (GetInsightsToMigrateActivityInputs,@@ -26,6 +25,8 @@ from posthog.temporal.product_analytics.upgrade_queries_workflow import (UpgradeQueriesWorkflowInputs,)+from products.product_analytics.backend.models.insight import Insight+class InsightVizMigration1(SchemaMigration):targets = {NodeKind.INSIGHT_VIZ_NODE: 1}diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.pyindex 967fe36a2ed0..4cc62d4d5cdf 100644--- a/posthog/temporal/tests/test_alerts_activities.py+++ b/posthog/temporal/tests/test_alerts_activities.py@@ -22,7 +22,7 @@ from posthog.schema import ()from posthog.errors import CHQueryErrorTooManySimultaneousQueries-from posthog.models import Insight, User+from posthog.models import Userfrom posthog.tasks.alerts.utils import AlertEvaluationResultfrom posthog.temporal.alerts.activities import cleanup_alert_checks, evaluate_alert, notify_alert, prepare_alertfrom posthog.temporal.alerts.types import (@@ -34,6 +34,7 @@ from posthog.temporal.alerts.types import ()from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration+from products.product_analytics.backend.models.insight import Insightdef _valid_trends_query() -> dict:diff --git a/posthog/temporal/tests/test_alerts_investigation.py b/posthog/temporal/tests/test_alerts_investigation.pyindex b37b734e998f..a4baa387e528 100644--- a/posthog/temporal/tests/test_alerts_investigation.py+++ b/posthog/temporal/tests/test_alerts_investigation.py@@ -14,10 +14,10 @@ from parameterized import parameterizedfrom posthog.schema import AlertState-from posthog.models import Insightfrom posthog.temporal.alerts.investigation import claim_investigation_slot, should_trigger_investigationfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus+from products.product_analytics.backend.models.insight import Insightclass TestShouldTriggerInvestigation(BaseTest):diff --git a/posthog/temporal/tests/test_alerts_workflows.py b/posthog/temporal/tests/test_alerts_workflows.pyindex ce089a00b736..8ee869c1f110 100644--- a/posthog/temporal/tests/test_alerts_workflows.py+++ b/posthog/temporal/tests/test_alerts_workflows.py@@ -22,7 +22,7 @@ from posthog.schema import (TrendsQuery,)-from posthog.models import Insight, User+from posthog.models import Userfrom posthog.slo.types import SloArea, SloConfig, SloOperation, SloOutcomefrom posthog.tasks.alerts.utils import AlertEvaluationResultfrom posthog.temporal.alerts.activities import evaluate_alert, notify_alert, prepare_alert@@ -32,6 +32,7 @@ from posthog.temporal.alerts.workflows import CheckAlertWorkflowfrom posthog.temporal.common.slo_interceptor import SloInterceptorfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration+from products.product_analytics.backend.models.insight import InsightCHECK_ALERT_ACTIVITIES: list[Callable[..., Any]] = [prepare_alert, evaluate_alert, notify_alert]diff --git a/posthog/temporal/tests/test_subscriptions_workflows.py b/posthog/temporal/tests/test_subscriptions_workflows.pyindex 401695a0721c..1dfa54f787d0 100644--- a/posthog/temporal/tests/test_subscriptions_workflows.py+++ b/posthog/temporal/tests/test_subscriptions_workflows.py@@ -22,7 +22,6 @@ from posthog.hogql.errors import QueryErrorfrom posthog.errors import CHQueryErrorS3Errorfrom posthog.models.exported_asset import ExportedAsset-from posthog.models.insight import Insightfrom posthog.models.instance_setting import set_instance_settingfrom posthog.models.integration import Integrationfrom posthog.models.subscription import Subscription, SubscriptionDelivery@@ -59,6 +58,7 @@ from posthog.temporal.subscriptions.workflows import (from products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insightfrom ee.tasks.subscriptions.slack_subscriptions import SlackDeliveryResultfrom ee.tasks.test.subscriptions.subscriptions_test_factory import create_subscriptiondiff --git a/posthog/test/activity_logging/test_annotation_activity_logging.py b/posthog/test/activity_logging/test_annotation_activity_logging.pyindex fddb1ab2482c..b02c95ad2789 100644--- a/posthog/test/activity_logging/test_annotation_activity_logging.py+++ b/posthog/test/activity_logging/test_annotation_activity_logging.py@@ -2,10 +2,10 @@ from typing import Any, castfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.annotation import Annotation-from posthog.models.insight import Insightfrom posthog.test.activity_log_utils import ActivityLogTestHelperfrom products.dashboards.backend.models.dashboard import Dashboard+from products.product_analytics.backend.models.insight import Insightclass TestAnnotationActivityLogging(ActivityLogTestHelper):diff --git a/posthog/test/base.py b/posthog/test/base.pyindex d5ec454dcf24..ed98947e2657 100644--- a/posthog/test/base.py+++ b/posthog/test/base.py@@ -77,7 +77,7 @@ from posthog.cloud_utils import TEST_clear_instance_license_cachefrom posthog.helpers.two_factor_session import email_mfa_token_generatorfrom posthog.hogql_queries.ai.ai_table_resolver import AI_EVENT_NAMES as _AI_EVENT_TYPESfrom posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator-from posthog.models import Insight, Organization, Team, User+from posthog.models import Organization, Team, Userfrom posthog.models.ai_events.sql import TRUNCATE_AI_EVENTS_TABLE_SQLfrom posthog.models.channel_type.sql import (CHANNEL_DEFINITION_DATA_SQL,@@ -204,6 +204,7 @@ from products.event_definitions.backend.models.property_definition import (DROP_PROPERTY_DEFINITIONS_TABLE_SQL,PROPERTY_DEFINITIONS_TABLE_SQL,)+from products.product_analytics.backend.models.insight import Insight# Make sure freezegun ignores our utils class that times functions, and heavy optional# deps (e.g. transformers) that can break when freezegun walks sys.modules.diff --git a/posthog/test/playwright_setup_functions.py b/posthog/test/playwright_setup_functions.pyindex 43bdc389c9f5..64fea8a505da 100644--- a/posthog/test/playwright_setup_functions.py+++ b/posthog/test/playwright_setup_functions.py@@ -13,13 +13,14 @@ from pydantic import BaseModelfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.constants import AvailableFeaturefrom posthog.management.commands.generate_demo_data import Command as GenerateDemoDataCommand-from posthog.models import Insight, PersonalAPIKey, Team, User-from posthog.models.insight_variable import InsightVariable+from posthog.models import PersonalAPIKey, Team, Userfrom posthog.models.utils import hash_key_value, mask_key_valuefrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.experiments.backend.models.experiment import Experiment+from products.product_analytics.backend.models.insight import Insight+from products.product_analytics.backend.models.insight_variable import InsightVariableclass PlaywrightSetupVariableType(StrEnum):diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.pyindex 0f8161637b4b..7914f0f1d72c 100644--- a/posthog/test/test_middleware.py+++ b/posthog/test/test_middleware.py@@ -26,7 +26,7 @@ from social_core.exceptions import AuthCanceled, AuthFailed, AuthMissingParametefrom posthog.api.test.test_organization import create_organizationfrom posthog.api.test.test_team import create_teamfrom posthog.middleware import per_request_logging_context_middleware-from posthog.models import Cohort, Insight+from posthog.models import Cohortfrom posthog.models.organization import Organizationfrom posthog.models.team import Teamfrom posthog.models.user import User@@ -35,6 +35,7 @@ from posthog.settings import SITE_URLfrom products.actions.backend.models.action import Actionfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.product_analytics.backend.models.insight import Insightdef _social_auth_backend() -> BaseAuth:diff --git a/posthog/test/test_user_permissions.py b/posthog/test/test_user_permissions.pyindex d9ee777298b7..919cbc4b1470 100644--- a/posthog/test/test_user_permissions.py+++ b/posthog/test/test_user_permissions.py@@ -1,7 +1,6 @@from posthog.test.base import BaseTestfrom posthog.constants import AvailableFeature-from posthog.models.insight import Insightfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team.team import Teamfrom posthog.models.user import User@@ -9,6 +8,7 @@ from posthog.user_permissions import UserPermissionsfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insightfrom ee.models.dashboard_privilege import DashboardPrivilegediff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.pyindex ddc44ac24af8..1f6018e5efbd 100644--- a/posthog/test/test_utils.py+++ b/posthog/test/test_utils.py@@ -940,7 +940,10 @@ class TestSharingOverrideProtection(TestCase):("password_protected_auth",),])- @patch("posthog.api.insight_variable.map_stale_to_latest", side_effect=lambda variables, _: variables)+ @patch(+ "products.product_analytics.backend.api.insight_variable.map_stale_to_latest",+ side_effect=lambda variables, _: variables,+ )def test_variables_override_blocked_for_sharing_authenticators(self, auth_type, _mock):from posthog.auth import SharingAccessTokenAuthentication, SharingPasswordProtectedAuthentication@@ -958,7 +961,10 @@ class TestSharingOverrideProtection(TestCase):assert result == {"var1": {"value": "safe"}}- @patch("posthog.api.insight_variable.map_stale_to_latest", side_effect=lambda variables, _: variables)+ @patch(+ "products.product_analytics.backend.api.insight_variable.map_stale_to_latest",+ side_effect=lambda variables, _: variables,+ )def test_variables_override_allowed_for_normal_auth(self, _mock):request = self._make_request(None, query_params={"variables_override": json.dumps({"var1": {"value": "custom"}})}diff --git a/posthog/user_permissions.py b/posthog/user_permissions.pyindex d7197d734e72..48ae81823f3c 100644--- a/posthog/user_permissions.py+++ b/posthog/user_permissions.py@@ -3,10 +3,11 @@ from typing import Any, Optional, castfrom uuid import UUIDfrom posthog.constants import AvailableFeature-from posthog.models import Insight, Organization, OrganizationMembership, Team, User+from posthog.models import Organization, OrganizationMembership, Team, Userfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insightclass UserPermissions:diff --git a/posthog/utils.py b/posthog/utils.pyindex 176212e5771d..a2a56381cde5 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -75,10 +75,11 @@ TEMPLATE_CONTEXT_DURATION_HISTOGRAM = Histogram(if TYPE_CHECKING:from django.contrib.auth.models import AbstractBaseUser, AnonymousUser- from posthog.models import InsightVariable, Team, User+ from posthog.models import Team, Userfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+ from products.product_analytics.backend.models.insight_variable import InsightVariableDATERANGE_MAP = {"second": datetime.timedelta(seconds=1),@@ -1441,9 +1442,10 @@ def filters_override_requested_by_client(request: Request, dashboard: Optional["def variables_override_requested_by_client(request: Optional[Request], dashboard: Optional["Dashboard"], variables: list["InsightVariable"]) -> Optional[dict[str, dict]]:- from posthog.api.insight_variable import map_stale_to_latestfrom posthog.auth import SharingAccessTokenAuthentication, SharingPasswordProtectedAuthentication+ from products.product_analytics.backend.api.insight_variable import map_stale_to_latest+dashboard_variables = (dashboard and dashboard.variables) or {}raw_override = request.query_params.get("variables_override") if request else Nonediff --git a/products/actions/backend/api/action.py b/products/actions/backend/api/action.pyindex 6964a23ddeca..cb62efeeec2d 100644--- a/products/actions/backend/api/action.py+++ b/products/actions/backend/api/action.py@@ -29,7 +29,7 @@ from posthog.api.shared import UserBasicSerializerfrom posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixinfrom posthog.constants import TREND_FILTER_TYPE_EVENTSfrom posthog.event_usage import report_user_action-from posthog.models import Cohort, Insight, Team+from posthog.models import Cohort, Teamfrom posthog.models.activity_logging.activity_log import Detail, changes_between, log_activityfrom posthog.models.event.event import Selectorfrom posthog.models.hog_functions.hog_function import HogFunction@@ -41,6 +41,7 @@ from posthog.resource_limits import LimitKey, check_count_limitfrom products.actions.backend.models.action import ACTION_STEP_MATCHING_OPTIONS, Actionfrom products.experiments.backend.models.experiment import Experiment+from products.product_analytics.backend.models.insight import Insight_PropertyFilterUnion = PolymorphicProxySerializer(component_name="ActionStepPropertyFilter",diff --git a/products/actions/backend/api/test/test_action.py b/products/actions/backend/api/test/test_action.pyindex e04e55bf1ddc..39ba23748ed4 100644--- a/products/actions/backend/api/test/test_action.py+++ b/products/actions/backend/api/test/test_action.py@@ -10,10 +10,11 @@ from unittest.mock import ANY, patchfrom rest_framework import status-from posthog.models import Cohort, Insight, Tag, User+from posthog.models import Cohort, Tag, Userfrom posthog.models.hog_functions.hog_function import HogFunctionfrom products.actions.backend.models.action import Action+from products.product_analytics.backend.models.insight import Insightclass TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.pyindex c42a06fc7b50..0a4ae0aee86e 100644--- a/products/alerts/backend/api/alert.py+++ b/products/alerts/backend/api/alert.py@@ -22,12 +22,11 @@ from posthog.schema import ()from posthog.api.documentation import extend_schema_field-from posthog.api.insight import InsightBasicSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.api.shared import UserBasicSerializerfrom posthog.event_usage import get_request_analytics_properties-from posthog.models import Insight, User+from posthog.models import Userfrom posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activityfrom posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.resource_limits import LimitKey, check_count_limit@@ -39,6 +38,8 @@ from posthog.utils import relative_date_parsefrom products.alerts.backend.api.alert_schedule_restriction import AlertScheduleRestrictionfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold+from products.product_analytics.backend.api.insight import InsightBasicSerializer+from products.product_analytics.backend.models.insight import Insightdef _validate_every_15_minutes_interval(diff --git a/products/alerts/backend/max_tools.py b/products/alerts/backend/max_tools.pyindex bcabe3909a1d..7529e6750080 100644--- a/products/alerts/backend/max_tools.py+++ b/products/alerts/backend/max_tools.py@@ -17,13 +17,13 @@ from posthog.schema import (from posthog.event_usage import EventSourcefrom posthog.exceptions_capture import capture_exception-from posthog.models.insight import Insightfrom posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.rbac.user_access_control import AccessControlLevelfrom posthog.scopes import APIScopeObjectfrom products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Threshold+from products.product_analytics.backend.models.insight import Insightfrom ee.hogai.artifacts.types import ModelArtifactResultfrom ee.hogai.tool import MaxTooldiff --git a/products/alerts/backend/migrations/0002_migrate_product_analytics_models.py b/products/alerts/backend/migrations/0002_migrate_product_analytics_models.pynew file mode 100644index 000000000000..f491db0cec54--- /dev/null+++ b/products/alerts/backend/migrations/0002_migrate_product_analytics_models.py@@ -0,0 +1,38 @@+# Generated by Django 5.2.14 on 2026-05-22 11:19++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("alerts", "0001_migrate_models"),+ ("product_analytics", "0001_migrate_product_analytics_models"),+ ]++ operations = [+ migrations.AlterField(+ model_name="alert",+ name="insight",+ field=models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ to="product_analytics.insight",+ ),+ ),+ migrations.AlterField(+ model_name="alertconfiguration",+ name="insight",+ field=models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ to="product_analytics.insight",+ ),+ ),+ migrations.AlterField(+ model_name="threshold",+ name="insight",+ field=models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ to="product_analytics.insight",+ ),+ ),+ ]diff --git a/products/alerts/backend/migrations/max_migration.txt b/products/alerts/backend/migrations/max_migration.txtindex 09da3a27f2cf..44181c85e953 100644--- a/products/alerts/backend/migrations/max_migration.txt+++ b/products/alerts/backend/migrations/max_migration.txt@@ -1 +1 @@-0001_migrate_models+0002_migrate_product_analytics_modelsdiff --git a/products/alerts/backend/models/alert.py b/products/alerts/backend/models/alert.pyindex 624928da211a..63c6b2611570 100644--- a/products/alerts/backend/models/alert.py+++ b/products/alerts/backend/models/alert.py@@ -68,7 +68,7 @@ def derive_detector_event_fields(detector_config: dict | None) -> dict:# @deprecated("AlertConfiguration should be used instead.")class Alert(models.Model):team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)- insight = models.ForeignKey("posthog.Insight", on_delete=models.CASCADE)+ insight = models.ForeignKey("product_analytics.Insight", on_delete=models.CASCADE)name = models.CharField(max_length=100)target_value = models.TextField()@@ -85,7 +85,7 @@ class Threshold(ModelActivityMixin, CreatedMetaFields, UUIDTModel):"""team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)- insight = models.ForeignKey("posthog.Insight", on_delete=models.CASCADE)+ insight = models.ForeignKey("product_analytics.Insight", on_delete=models.CASCADE)name = models.CharField(max_length=255, blank=True)configuration = models.JSONField(default=dict)@@ -110,7 +110,7 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):ALERTS_ALLOWED_ON_FREE_TIER = 5team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)- insight = models.ForeignKey("posthog.Insight", on_delete=models.CASCADE)+ insight = models.ForeignKey("product_analytics.Insight", on_delete=models.CASCADE)name = models.CharField(max_length=255, blank=True)subscribed_users = models.ManyToManyField(diff --git a/products/alerts/backend/test_max_tools.py b/products/alerts/backend/test_max_tools.pyindex f8a74bfd3e88..7d88fc15213c 100644--- a/products/alerts/backend/test_max_tools.py+++ b/products/alerts/backend/test_max_tools.py@@ -10,9 +10,9 @@ from parameterized import parameterizedfrom posthog.schema import AlertCalculationInterval, AlertConditionType, AlertState, InsightThresholdTypefrom posthog.models import Organization, Team-from posthog.models.insight import Insightfrom products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Threshold+from products.product_analytics.backend.models.insight import Insightfrom .max_tools import CreateAlertAction, UpdateAlertAction, UpsertAlertTooldiff --git a/products/customer_analytics/backend/api/test_views.py b/products/customer_analytics/backend/api/test_views.pyindex ceb9f9d0c26a..bfb08cd5f11b 100644--- a/products/customer_analytics/backend/api/test_views.py+++ b/products/customer_analytics/backend/api/test_views.py@@ -6,7 +6,7 @@ from rest_framework import statusfrom posthog.api.tagged_item import set_tags_on_objectfrom posthog.constants import AvailableFeature-from posthog.models import Insight, Tag, TaggedItem+from posthog.models import Tag, TaggedItemfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team import Team@@ -14,6 +14,7 @@ from posthog.models.user import Userfrom products.customer_analytics.backend.models import Account, CustomerJourney, CustomerProfileConfigfrom products.customer_analytics.backend.models.account import AccountAssignment+from products.product_analytics.backend.models.insight import Insightclass TestCustomerProfileConfigViewSet(APIBaseTest):diff --git a/products/customer_analytics/backend/migrations/0006_migrate_product_analytics_models.py b/products/customer_analytics/backend/migrations/0006_migrate_product_analytics_models.pynew file mode 100644index 000000000000..56e498aa7cc4--- /dev/null+++ b/products/customer_analytics/backend/migrations/0006_migrate_product_analytics_models.py@@ -0,0 +1,22 @@+# Generated by Django 5.2.14 on 2026-05-22 11:19++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("customer_analytics", "0005_account"),+ ("product_analytics", "0001_migrate_product_analytics_models"),+ ]++ operations = [+ migrations.AlterField(+ model_name="customerjourney",+ name="insight",+ field=models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ to="product_analytics.insight",+ ),+ ),+ ]diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txtindex a0db376f0946..02613e949737 100644--- a/products/customer_analytics/backend/migrations/max_migration.txt+++ b/products/customer_analytics/backend/migrations/max_migration.txt@@ -1 +1 @@-0005_account+0006_migrate_product_analytics_modelsdiff --git a/products/customer_analytics/backend/models/customer_journey.py b/products/customer_analytics/backend/models/customer_journey.pyindex ebc7f9ec98b6..2b409fc1da14 100644--- a/products/customer_analytics/backend/models/customer_journey.py+++ b/products/customer_analytics/backend/models/customer_journey.py@@ -5,7 +5,7 @@ from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModelclass CustomerJourney(UUIDModel, CreatedMetaFields, UpdatedMetaFields):team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)- insight = models.ForeignKey("posthog.Insight", on_delete=models.CASCADE)+ insight = models.ForeignKey("product_analytics.Insight", on_delete=models.CASCADE)name = models.CharField(max_length=400)description = models.TextField(null=True, blank=True)diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 5d5f08c1652c..ffc620fb1b7f 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -35,8 +35,6 @@ from rest_framework.utils.serializer_helpers import ReturnDictfrom posthog.schema import InsightVizNodefrom posthog.api.forbid_destroy_model import ForbidDestroyModel-from posthog.api.insight import DashboardTileBasicSerializer, InsightSerializer, InsightViewSet-from posthog.api.insight_suggestions import summarize_insight_resultfrom posthog.api.monitoring import Feature, monitorfrom posthog.api.openapi_parameters import make_filters_override_param, make_variables_override_paramfrom posthog.api.routing import TeamAndOrgViewSetMixin@@ -57,9 +55,7 @@ from posthog.helpers.trigram_search import (normalize_search_term,)from posthog.hogql_queries.query_runner import ExecutionMode-from posthog.models import Insightfrom posthog.models.activity_logging.activity_log import Detail, changes_between, log_activity-from posthog.models.insight_variable import InsightVariablefrom posthog.models.quick_filter import QuickFilterfrom posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.models.tagged_item import TaggedItem@@ -80,6 +76,14 @@ from products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import ButtonTile, DashboardTile, Textfrom products.llm_analytics.backend.dashboard_templates import get_llm_analytics_default_templatefrom products.mcp_analytics.backend.dashboard_templates import get_mcp_analytics_default_template+from products.product_analytics.backend.api.insight import (+ DashboardTileBasicSerializer,+ InsightSerializer,+ InsightViewSet,+)+from products.product_analytics.backend.api.insight_suggestions import summarize_insight_result+from products.product_analytics.backend.models.insight import Insight+from products.product_analytics.backend.models.insight_variable import InsightVariablefrom ee.hogai.utils.aio import async_to_syncdiff --git a/products/dashboards/backend/api/test/test_run_insights.py b/products/dashboards/backend/api/test/test_run_insights.pyindex 498016aa123a..d2e33b6c8da1 100644--- a/products/dashboards/backend/api/test/test_run_insights.py+++ b/products/dashboards/backend/api/test/test_run_insights.py@@ -7,13 +7,13 @@ from rest_framework import statusfrom posthog.schema import DateRange, EventsNode, InsightVizNode, TrendsFilter, TrendsQueryfrom posthog.api.test.dashboards import DashboardAPI-from posthog.models import Insight-from posthog.models.insight_variable import InsightVariablefrom posthog.models.organization import Organizationfrom posthog.models.team import Teamfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile, Text+from products.product_analytics.backend.models.insight import Insight+from products.product_analytics.backend.models.insight_variable import InsightVariabledef _trends_query_dict(event: str = "$pageview") -> dict:diff --git a/products/dashboards/backend/migrations/0006_migrate_product_analytics_models.py b/products/dashboards/backend/migrations/0006_migrate_product_analytics_models.pynew file mode 100644index 000000000000..3c7c74054d82--- /dev/null+++ b/products/dashboards/backend/migrations/0006_migrate_product_analytics_models.py@@ -0,0 +1,34 @@+# Generated by Django 5.2.14 on 2026-05-22 11:19++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("dashboards", "0005_enforce_dashboardtile_team_id_not_null"),+ ("product_analytics", "0001_migrate_product_analytics_models"),+ ]++ operations = [+ migrations.AlterField(+ model_name="dashboard",+ name="insights",+ field=models.ManyToManyField(+ blank=True,+ related_name="dashboards",+ through="dashboards.DashboardTile",+ to="product_analytics.insight",+ ),+ ),+ migrations.AlterField(+ model_name="dashboardtile",+ name="insight",+ field=models.ForeignKey(+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="dashboard_tiles",+ to="product_analytics.insight",+ ),+ ),+ ]diff --git a/products/dashboards/backend/migrations/max_migration.txt b/products/dashboards/backend/migrations/max_migration.txtindex 2d070391bceb..02613e949737 100644--- a/products/dashboards/backend/migrations/max_migration.txt+++ b/products/dashboards/backend/migrations/max_migration.txt@@ -1 +1 @@-0005_enforce_dashboardtile_team_id_not_null+0006_migrate_product_analytics_modelsdiff --git a/products/dashboards/backend/models/dashboard.py b/products/dashboards/backend/models/dashboard.pyindex b18284e34632..0000669093aa 100644--- a/products/dashboards/backend/models/dashboard.py+++ b/products/dashboards/backend/models/dashboard.py@@ -73,7 +73,9 @@ class Dashboard(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.Mdefault=RestrictionLevel.EVERYONE_IN_PROJECT_CAN_EDIT,choices=RestrictionLevel,)- insights = models.ManyToManyField("posthog.Insight", related_name="dashboards", through="DashboardTile", blank=True) # type: models.ManyToManyField+ insights = models.ManyToManyField(+ "product_analytics.Insight", related_name="dashboards", through="DashboardTile", blank=True+ ) # type: models.ManyToManyFieldquick_filter_ids = models.JSONField(default=list, blank=True, null=True)# Deprecated in favour of app-wide tagging model. See EnterpriseTaggedItemdiff --git a/products/dashboards/backend/models/dashboard_tile.py b/products/dashboards/backend/models/dashboard_tile.pyindex 0c76fcc82b07..d010bf59f1fe 100644--- a/products/dashboards/backend/models/dashboard_tile.py+++ b/products/dashboards/backend/models/dashboard_tile.py@@ -60,7 +60,7 @@ class DashboardTile(models.Model):# Relationsdashboard = models.ForeignKey("dashboards.Dashboard", on_delete=models.CASCADE, related_name="tiles")insight = models.ForeignKey(- "posthog.Insight",+ "product_analytics.Insight",on_delete=models.CASCADE,related_name="dashboard_tiles",null=True,@@ -148,7 +148,7 @@ class DashboardTile(models.Model):if self.insight is not None:has_no_filters_hash = self.filters_hash is Noneif has_no_filters_hash and self.insight.filters != {}:- from posthog.models.insight import generate_insight_filters_hash+ from products.product_analytics.backend.models.insight import generate_insight_filters_hashself.filters_hash = generate_insight_filters_hash(self.insight, self.dashboard)diff --git a/products/endpoints/backend/api.py b/products/endpoints/backend/api.pyindex 7a1c90cb9055..fc2cf6c952ef 100644--- a/products/endpoints/backend/api.py+++ b/products/endpoints/backend/api.py@@ -76,7 +76,6 @@ from posthog.models.activity_logging.activity_log import (changes_between,log_activity,)-from posthog.models.insight_variable import InsightVariablefrom posthog.schema_migrations.upgrade import upgradefrom posthog.types import InsightQueryNode@@ -126,6 +125,7 @@ from products.endpoints.backend.serializers import (EndpointRunResponseSerializer,EndpointVersionResponseSerializer,)+from products.product_analytics.backend.models.insight_variable import InsightVariablefrom products.warehouse_sources.backend.models.external_data_schema import sync_frequency_to_sync_frequency_intervalfrom common.hogvm.python.utils import HogVMExceptiondiff --git a/products/endpoints/backend/openapi.py b/products/endpoints/backend/openapi.pyindex 028d63fa8a43..48dd8f898417 100644--- a/products/endpoints/backend/openapi.py+++ b/products/endpoints/backend/openapi.py@@ -2,9 +2,8 @@ from django.conf import settingsfrom rest_framework.request import Request-from posthog.models.insight_variable import InsightVariable-from products.endpoints.backend.models import Endpoint, EndpointVersion+from products.product_analytics.backend.models.insight_variable import InsightVariableINSIGHT_VARIABLE_TYPE_TO_OPENAPI: dict[str, dict] = {InsightVariable.Type.STRING: {"type": "string"},diff --git a/products/endpoints/backend/tests/test_endpoint.py b/products/endpoints/backend/tests/test_endpoint.pyindex 5b60407309da..458aa6b2f1cb 100644--- a/products/endpoints/backend/tests/test_endpoint.py+++ b/products/endpoints/backend/tests/test_endpoint.py@@ -12,7 +12,6 @@ from rest_framework import statusfrom posthog.schema import EndpointLastExecutionTimesRequestfrom posthog.models.activity_logging.activity_log import ActivityLog-from posthog.models.insight_variable import InsightVariablefrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team import Teamfrom posthog.models.user import User@@ -20,6 +19,7 @@ from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom products.endpoints.backend.models import Endpointfrom products.endpoints.backend.tests.conftest import create_endpoint_with_version+from products.product_analytics.backend.models.insight_variable import InsightVariableclass TestEndpoint(ClickhouseTestMixin, APIBaseTest):@@ -1172,7 +1172,7 @@ class TestMaterializationPreview(ClickhouseTestMixin, APIBaseTest):}def _create_endpoint_with_variables(self, name="range-endpoint"):- from posthog.models.insight_variable import InsightVariable+ from products.product_analytics.backend.models.insight_variable import InsightVariableInsightVariable.objects.create(team=self.team, id="00000000-0000-0000-0000-000000000001", code_name="start_ts", type="String"@@ -1252,7 +1252,7 @@ class TestMaterializationPreview(ClickhouseTestMixin, APIBaseTest):assert endpoint_data.get("materialization", {}).get("status") is Nonedef test_bucket_overrides_stored_on_version(self):- from posthog.models.insight_variable import InsightVariable+ from products.product_analytics.backend.models.insight_variable import InsightVariableInsightVariable.objects.create(team=self.team, id="00000000-0000-0000-0000-000000000001", code_name="start_ts", type="String"diff --git a/products/endpoints/backend/tests/test_endpoint_execution.py b/products/endpoints/backend/tests/test_endpoint_execution.pyindex 0f50ba2872b9..4e99b9888bef 100644--- a/products/endpoints/backend/tests/test_endpoint_execution.py+++ b/products/endpoints/backend/tests/test_endpoint_execution.py@@ -9,11 +9,10 @@ from rest_framework.response import Responsefrom posthog.schema import EventsNode, TrendsQuery-from posthog.models.insight_variable import InsightVariable-from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.endpoints.backend.api import EndpointViewSetfrom products.endpoints.backend.tests.conftest import create_endpoint_with_version+from products.product_analytics.backend.models.insight_variable import InsightVariablefrom products.warehouse_sources.backend.models.table import DataWarehouseTablediff --git a/products/endpoints/backend/tests/test_openapi_spec.py b/products/endpoints/backend/tests/test_openapi_spec.pyindex d179a1c5bc42..1aa784872102 100644--- a/products/endpoints/backend/tests/test_openapi_spec.py+++ b/products/endpoints/backend/tests/test_openapi_spec.py@@ -53,7 +53,7 @@ class TestEndpointOpenAPISpec(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response_schema["properties"]["results"]["type"], "array")def test_openapi_spec_with_variables(self):- from posthog.models.insight_variable import InsightVariable+ from products.product_analytics.backend.models.insight_variable import InsightVariablevariable = InsightVariable.objects.create(team=self.team,@@ -92,7 +92,7 @@ class TestEndpointOpenAPISpec(ClickhouseTestMixin, APIBaseTest):self.assertEqual(variables_schema["properties"]["country"]["type"], "string")def test_openapi_spec_variable_types(self):- from posthog.models.insight_variable import InsightVariable+ from products.product_analytics.backend.models.insight_variable import InsightVariabletest_cases = [(InsightVariable.Type.NUMBER, "number", None),diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambrindex 41a89cc7fc86..1dcb927414dd 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr@@ -857,78 +857,6 @@'''# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.32- '''- SELECT "posthog_dashboarditem"."id",- "posthog_dashboarditem"."name",- "posthog_dashboarditem"."derived_name",- "posthog_dashboarditem"."description",- "posthog_dashboarditem"."team_id",- "posthog_dashboarditem"."filters",- "posthog_dashboarditem"."filters_hash",- "posthog_dashboarditem"."query",- "posthog_dashboarditem"."query_metadata",- "posthog_dashboarditem"."order",- "posthog_dashboarditem"."deleted",- "posthog_dashboarditem"."saved",- "posthog_dashboarditem"."created_at",- "posthog_dashboarditem"."refreshing",- "posthog_dashboarditem"."created_by_id",- "posthog_dashboarditem"."is_sample",- "posthog_dashboarditem"."short_id",- "posthog_dashboarditem"."favorited",- "posthog_dashboarditem"."refresh_attempt",- "posthog_dashboarditem"."last_modified_at",- "posthog_dashboarditem"."last_modified_by_id",- "posthog_dashboarditem"."dashboard_id",- "posthog_dashboarditem"."last_refresh",- "posthog_dashboarditem"."layouts",- "posthog_dashboarditem"."color",- "posthog_dashboarditem"."dive_dashboard_id",- "posthog_dashboarditem"."updated_at",- "posthog_dashboarditem"."deprecated_tags",- "posthog_dashboarditem"."tags"- FROM "posthog_dashboarditem"- WHERE (NOT ("posthog_dashboarditem"."deleted")- AND "posthog_dashboarditem"."dashboard_id" = 99999)- '''-# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.33- '''- SELECT "posthog_dashboarditem"."id",- "posthog_dashboarditem"."name",- "posthog_dashboarditem"."derived_name",- "posthog_dashboarditem"."description",- "posthog_dashboarditem"."team_id",- "posthog_dashboarditem"."filters",- "posthog_dashboarditem"."filters_hash",- "posthog_dashboarditem"."query",- "posthog_dashboarditem"."query_metadata",- "posthog_dashboarditem"."order",- "posthog_dashboarditem"."deleted",- "posthog_dashboarditem"."saved",- "posthog_dashboarditem"."created_at",- "posthog_dashboarditem"."refreshing",- "posthog_dashboarditem"."created_by_id",- "posthog_dashboarditem"."is_sample",- "posthog_dashboarditem"."short_id",- "posthog_dashboarditem"."favorited",- "posthog_dashboarditem"."refresh_attempt",- "posthog_dashboarditem"."last_modified_at",- "posthog_dashboarditem"."last_modified_by_id",- "posthog_dashboarditem"."dashboard_id",- "posthog_dashboarditem"."last_refresh",- "posthog_dashboarditem"."layouts",- "posthog_dashboarditem"."color",- "posthog_dashboarditem"."dive_dashboard_id",- "posthog_dashboarditem"."updated_at",- "posthog_dashboarditem"."deprecated_tags",- "posthog_dashboarditem"."tags"- FROM "posthog_dashboarditem"- WHERE (NOT ("posthog_dashboarditem"."deleted")- AND "posthog_dashboarditem"."dashboard_id" = 99999)- '''-# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.34'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -1024,7 +952,7 @@WHERE "posthog_team"."primary_dashboard_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.35+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.33'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -1120,7 +1048,7 @@WHERE "posthog_team"."primary_dashboard_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.36+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.34'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",@@ -1138,7 +1066,7 @@WHERE "posthog_taggeditem"."dashboard_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.37+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.35'''SELECT "posthog_tag"."id","posthog_tag"."name",@@ -1148,7 +1076,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.38+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.36'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",@@ -1166,7 +1094,7 @@WHERE "posthog_taggeditem"."dashboard_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.39+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.37'''SELECT "posthog_tag"."id","posthog_tag"."name",@@ -1176,40 +1104,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.4- '''- SELECT "posthog_featureflag"."id",- "posthog_featureflag"."key",- "posthog_featureflag"."name",- "posthog_featureflag"."filters",- "posthog_featureflag"."team_id",- "posthog_featureflag"."created_by_id",- "posthog_featureflag"."created_at",- "posthog_featureflag"."updated_at",- "posthog_featureflag"."deleted",- "posthog_featureflag"."active",- "posthog_featureflag"."version",- "posthog_featureflag"."last_modified_by_id",- "posthog_featureflag"."rollback_conditions",- "posthog_featureflag"."performed_rollback",- "posthog_featureflag"."ensure_experience_continuity",- "posthog_featureflag"."usage_dashboard_id",- "posthog_featureflag"."has_enriched_analytics",- "posthog_featureflag"."is_remote_configuration",- "posthog_featureflag"."has_encrypted_payloads",- "posthog_featureflag"."evaluation_runtime",- "posthog_featureflag"."bucketing_identifier",- "posthog_featureflag"."last_called_at"- FROM "posthog_featureflag"- INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")- WHERE (NOT ("posthog_featureflag"."deleted")- AND "posthog_featureflag"."key" = 'copied-flag-key'- AND "posthog_team"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid- AND "posthog_team"."project_id" = 99999)- LIMIT 21- '''-# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.40+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.38'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -1235,7 +1130,7 @@AND "posthog_dashboardtile"."dashboard_id" = 99999)'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.41+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.39'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -1261,6 +1156,111 @@AND "posthog_dashboardtile"."dashboard_id" = 99999)'''# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.4+ '''+ SELECT "posthog_featureflag"."id",+ "posthog_featureflag"."key",+ "posthog_featureflag"."name",+ "posthog_featureflag"."filters",+ "posthog_featureflag"."team_id",+ "posthog_featureflag"."created_by_id",+ "posthog_featureflag"."created_at",+ "posthog_featureflag"."updated_at",+ "posthog_featureflag"."deleted",+ "posthog_featureflag"."active",+ "posthog_featureflag"."version",+ "posthog_featureflag"."last_modified_by_id",+ "posthog_featureflag"."rollback_conditions",+ "posthog_featureflag"."performed_rollback",+ "posthog_featureflag"."ensure_experience_continuity",+ "posthog_featureflag"."usage_dashboard_id",+ "posthog_featureflag"."has_enriched_analytics",+ "posthog_featureflag"."is_remote_configuration",+ "posthog_featureflag"."has_encrypted_payloads",+ "posthog_featureflag"."evaluation_runtime",+ "posthog_featureflag"."bucketing_identifier",+ "posthog_featureflag"."last_called_at"+ FROM "posthog_featureflag"+ INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")+ WHERE (NOT ("posthog_featureflag"."deleted")+ AND "posthog_featureflag"."key" = 'copied-flag-key'+ AND "posthog_team"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid+ AND "posthog_team"."project_id" = 99999)+ LIMIT 21+ '''+# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.40+ '''+ SELECT "posthog_dashboarditem"."id",+ "posthog_dashboarditem"."name",+ "posthog_dashboarditem"."derived_name",+ "posthog_dashboarditem"."description",+ "posthog_dashboarditem"."team_id",+ "posthog_dashboarditem"."filters",+ "posthog_dashboarditem"."filters_hash",+ "posthog_dashboarditem"."query",+ "posthog_dashboarditem"."query_metadata",+ "posthog_dashboarditem"."order",+ "posthog_dashboarditem"."deleted",+ "posthog_dashboarditem"."saved",+ "posthog_dashboarditem"."created_at",+ "posthog_dashboarditem"."refreshing",+ "posthog_dashboarditem"."created_by_id",+ "posthog_dashboarditem"."is_sample",+ "posthog_dashboarditem"."short_id",+ "posthog_dashboarditem"."favorited",+ "posthog_dashboarditem"."refresh_attempt",+ "posthog_dashboarditem"."last_modified_at",+ "posthog_dashboarditem"."last_modified_by_id",+ "posthog_dashboarditem"."dashboard_id",+ "posthog_dashboarditem"."last_refresh",+ "posthog_dashboarditem"."layouts",+ "posthog_dashboarditem"."color",+ "posthog_dashboarditem"."dive_dashboard_id",+ "posthog_dashboarditem"."updated_at",+ "posthog_dashboarditem"."deprecated_tags",+ "posthog_dashboarditem"."tags"+ FROM "posthog_dashboarditem"+ WHERE (NOT ("posthog_dashboarditem"."deleted")+ AND "posthog_dashboarditem"."dashboard_id" = 99999)+ '''+# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.41+ '''+ SELECT "posthog_dashboarditem"."id",+ "posthog_dashboarditem"."name",+ "posthog_dashboarditem"."derived_name",+ "posthog_dashboarditem"."description",+ "posthog_dashboarditem"."team_id",+ "posthog_dashboarditem"."filters",+ "posthog_dashboarditem"."filters_hash",+ "posthog_dashboarditem"."query",+ "posthog_dashboarditem"."query_metadata",+ "posthog_dashboarditem"."order",+ "posthog_dashboarditem"."deleted",+ "posthog_dashboarditem"."saved",+ "posthog_dashboarditem"."created_at",+ "posthog_dashboarditem"."refreshing",+ "posthog_dashboarditem"."created_by_id",+ "posthog_dashboarditem"."is_sample",+ "posthog_dashboarditem"."short_id",+ "posthog_dashboarditem"."favorited",+ "posthog_dashboarditem"."refresh_attempt",+ "posthog_dashboarditem"."last_modified_at",+ "posthog_dashboarditem"."last_modified_by_id",+ "posthog_dashboarditem"."dashboard_id",+ "posthog_dashboarditem"."last_refresh",+ "posthog_dashboarditem"."layouts",+ "posthog_dashboarditem"."color",+ "posthog_dashboarditem"."dive_dashboard_id",+ "posthog_dashboarditem"."updated_at",+ "posthog_dashboarditem"."deprecated_tags",+ "posthog_dashboarditem"."tags"+ FROM "posthog_dashboarditem"+ WHERE (NOT ("posthog_dashboarditem"."deleted")+ AND "posthog_dashboarditem"."dashboard_id" = 99999)+ '''+# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.42'''SELECT "posthog_dashboarditem"."id",diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex e76604645b40..2e59e59bfb26 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -27,7 +27,7 @@ from posthog import redisfrom posthog.api.cohort import get_cohort_actors_for_feature_flagfrom posthog.constants import AvailableFeaturefrom posthog.helpers.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUE, get_decrypted_flag_payload-from posthog.models import GroupTypeMapping, Insight, TaggedItem, User+from posthog.models import GroupTypeMapping, TaggedItem, Userfrom posthog.models.cohort import Cohortfrom posthog.models.cohort.cohort import CohortTypefrom posthog.models.group.group import Group@@ -51,6 +51,7 @@ from products.feature_flags.backend.models.feature_flag import (FeatureFlagHashKeyOverride,get_feature_flags_for_team_in_cache,)+from products.product_analytics.backend.models.insight import Insightfrom products.product_tours.backend.models import ProductTourfrom products.surveys.backend.models import Surveydiff --git a/products/notebooks/backend/test/test_sharing.py b/products/notebooks/backend/test/test_sharing.pyindex 9342c9d002a8..f469d9a6aad4 100644--- a/products/notebooks/backend/test/test_sharing.py+++ b/products/notebooks/backend/test/test_sharing.py@@ -5,7 +5,7 @@ from posthog.test.base import APIBaseTestfrom parameterized import parameterizedfrom rest_framework import status-from posthog.models import Insight, SharingConfiguration+from posthog.models import SharingConfigurationfrom products.notebooks.backend.models import Notebookfrom products.notebooks.backend.util import (@@ -14,6 +14,7 @@ from products.notebooks.backend.util import (filter_notebook_content_for_sharing,iter_prosemirror_nodes,)+from products.product_analytics.backend.models.insight import Insightdef _saved_insight_query_node(short_id: str) -> dict[str, Any]:diff --git a/products/product_analytics/backend/api/__init__.py b/products/product_analytics/backend/api/__init__.pynew file mode 100644index 000000000000..ef556a5d355f--- /dev/null+++ b/products/product_analytics/backend/api/__init__.py@@ -0,0 +1,8 @@+from .insight import InsightViewSet, LegacyInsightViewSet+from .insight_variable import InsightVariableViewSet++__all__ = [+ "InsightVariableViewSet",+ "InsightViewSet",+ "LegacyInsightViewSet",+]diff --git a/posthog/api/insight.py b/products/product_analytics/backend/api/insight.pysimilarity index 99%rename from posthog/api/insight.pyrename to products/product_analytics/backend/api/insight.pyindex 1bc2eabaa27b..d4cc0c7c5f6f 100644--- a/posthog/api/insight.py+++ b/products/product_analytics/backend/api/insight.py@@ -46,9 +46,6 @@ from posthog.hogql.timings import HogQLTimingsfrom posthog import schemafrom posthog.api.documentation import extend_schema, extend_schema_field, extend_schema_serializerfrom posthog.api.forbid_destroy_model import ForbidDestroyModel-from posthog.api.insight_metadata import generate_insight_metadata-from posthog.api.insight_suggestions import get_insight_analysis, get_insight_suggestions-from posthog.api.insight_variable import map_stale_to_latestfrom posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.monitoring import Feature, monitorfrom posthog.api.openapi_parameters import make_filters_override_param, make_variables_override_param@@ -90,7 +87,7 @@ from posthog.hogql_queries.query_runner import (shared_insights_execution_mode,)from posthog.kafka_client.topics import KAFKA_METRICS_TIME_TO_SEE_DATA-from posthog.models import Cohort, Filter, Insight, User+from posthog.models import Cohort, Filter, Userfrom posthog.models.activity_logging.activity_log import (Change,Detail,@@ -101,9 +98,6 @@ from posthog.models.activity_logging.activity_log import ()from posthog.models.activity_logging.activity_page import ActivityLogPaginatedResponseSerializer, activity_page_responsefrom posthog.models.filters.utils import get_filter-from posthog.models.insight import InsightViewed-from posthog.models.insight_caching_state import InsightCachingState-from posthog.models.insight_variable import InsightVariablefrom posthog.models.organization import Organizationfrom posthog.models.team.team import Teamfrom posthog.models.utils import UUIDT@@ -133,6 +127,12 @@ from posthog.utils import (from products.alerts.backend.models.alert import AlertConfigurationfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.api.insight_metadata import generate_insight_metadata+from products.product_analytics.backend.api.insight_suggestions import get_insight_analysis, get_insight_suggestions+from products.product_analytics.backend.api.insight_variable import map_stale_to_latest+from products.product_analytics.backend.models.insight import Insight, InsightViewed+from products.product_analytics.backend.models.insight_caching_state import InsightCachingState+from products.product_analytics.backend.models.insight_variable import InsightVariablefrom common.hogvm.python.utils import HogVMExceptiondiff --git a/posthog/api/insight_metadata.py b/products/product_analytics/backend/api/insight_metadata.pysimilarity index 100%rename from posthog/api/insight_metadata.pyrename to products/product_analytics/backend/api/insight_metadata.pydiff --git a/posthog/api/insight_serializers.py b/products/product_analytics/backend/api/insight_serializers.pysimilarity index 100%rename from posthog/api/insight_serializers.pyrename to products/product_analytics/backend/api/insight_serializers.pydiff --git a/posthog/api/insight_suggestions.py b/products/product_analytics/backend/api/insight_suggestions.pysimilarity index 100%rename from posthog/api/insight_suggestions.pyrename to products/product_analytics/backend/api/insight_suggestions.pydiff --git a/posthog/api/insight_variable.py b/products/product_analytics/backend/api/insight_variable.pysimilarity index 98%rename from posthog/api/insight_variable.pyrename to products/product_analytics/backend/api/insight_variable.pyindex 8c58c04d42e1..34d8713fab7b 100644--- a/posthog/api/insight_variable.py+++ b/products/product_analytics/backend/api/insight_variable.py@@ -7,7 +7,8 @@ from posthog.schema import ProductKeyfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.auth import SharingAccessTokenAuthentication, SharingPasswordProtectedAuthentication-from posthog.models.insight_variable import InsightVariable++from products.product_analytics.backend.models.insight_variable import InsightVariableclass InsightVariableSerializer(serializers.ModelSerializer):diff --git a/products/product_analytics/backend/api/test/__init__.py b/products/product_analytics/backend/api/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/api/test/__snapshots__/test_insight.ambr b/products/product_analytics/backend/api/test/__snapshots__/test_insight.ambrsimilarity index 100%rename from posthog/api/test/__snapshots__/test_insight.ambrrename to products/product_analytics/backend/api/test/__snapshots__/test_insight.ambrdiff --git a/posthog/api/test/__snapshots__/test_insight_funnels.ambr b/products/product_analytics/backend/api/test/__snapshots__/test_insight_funnels.ambrsimilarity index 100%rename from posthog/api/test/__snapshots__/test_insight_funnels.ambrrename to products/product_analytics/backend/api/test/__snapshots__/test_insight_funnels.ambrdiff --git a/posthog/api/test/test_insight.py b/products/product_analytics/backend/api/test/test_insight.pysimilarity index 99%rename from posthog/api/test/test_insight.pyrename to products/product_analytics/backend/api/test/test_insight.pyindex 10f0f59ba8b3..7e13a91c93c6 100644--- a/posthog/api/test/test_insight.py+++ b/products/product_analytics/backend/api/test/test_insight.py@@ -46,30 +46,21 @@ from posthog.schema import (from posthog.hogql.query import execute_hogql_queryfrom posthog import settings-from posthog.api.insight import _last_refresh_for_shared_gatefrom posthog.api.test.dashboards import DashboardAPIfrom posthog.caching.insight_cache import update_cachefrom posthog.caching.insight_caching_state import TargetCacheAgefrom posthog.constants import AvailableFeaturefrom posthog.hogql_queries.query_runner import ExecutionMode-from posthog.models import (- Cohort,- Filter,- Insight,- InsightViewed,- OrganizationMembership,- Person,- SharingConfiguration,- Team,- User,-)-from posthog.models.insight_caching_state import InsightCachingState-from posthog.models.insight_variable import InsightVariable+from posthog.models import Cohort, Filter, OrganizationMembership, Person, SharingConfiguration, Team, Userfrom posthog.models.project import Projectfrom posthog.test.db_context_capturing import capture_db_queriesfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile, Text+from products.product_analytics.backend.api.insight import _last_refresh_for_shared_gate+from products.product_analytics.backend.models.insight import Insight, InsightViewed+from products.product_analytics.backend.models.insight_caching_state import InsightCachingState+from products.product_analytics.backend.models.insight_variable import InsightVariablefrom ee.models.rbac.access_control import AccessControl@@ -88,7 +79,9 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):])def test_legacy_insight_endpoints_blocked_with_feature_flag(self, _name: str, path: str) -> None:- with patch("posthog.api.insight.posthoganalytics.feature_enabled", return_value=True) as mock_feature_enabled:+ with patch(+ "products.product_analytics.backend.api.insight.posthoganalytics.feature_enabled", return_value=True+ ) as mock_feature_enabled:response = self.client.get(path.format(team_id=self.team.id))self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)@@ -99,7 +92,9 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertEqual(len(legacy_calls), 1)def test_creating_legacy_filter_insight_blocked_with_feature_flag(self) -> None:- with patch("posthog.api.insight.posthoganalytics.feature_enabled", return_value=True) as mock_feature_enabled:+ with patch(+ "products.product_analytics.backend.api.insight.posthoganalytics.feature_enabled", return_value=True+ ) as mock_feature_enabled:response = self.client.post(f"/api/projects/{self.team.id}/insights/",{"name": "Legacy filter insight", "filters": {"insight": "TRENDS", "events": [{"id": "$pageview"}]}},@@ -116,7 +111,9 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertEqual(len(legacy_filter_calls), 1)def test_creating_query_insight_not_blocked_by_legacy_filter_flag(self) -> None:- with patch("posthog.api.insight.posthoganalytics.feature_enabled", return_value=True) as mock_feature_enabled:+ with patch(+ "products.product_analytics.backend.api.insight.posthoganalytics.feature_enabled", return_value=True+ ) as mock_feature_enabled:response = self.client.post(f"/api/projects/{self.team.id}/insights/",{@@ -1393,7 +1390,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):),])- @patch("posthog.api.insight.report_user_action")+ @patch("products.product_analytics.backend.api.insight.report_user_action")def test_creating_insight_with_dashboard_fires_tile_added_event(self,_name: str,@@ -1420,7 +1417,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):request=ANY,)- @patch("posthog.api.insight.report_user_action")+ @patch("products.product_analytics.backend.api.insight.report_user_action")def test_adding_insight_to_dashboard_fires_tile_added_event(self, mock_report_user_action: mock.Mock) -> None:dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "test"})insight_id, _ = self.dashboard_api.create_insight({"filters": {"insight": "STICKINESS"}})@@ -4764,7 +4761,7 @@ class TestInsightErrorHandling(ClickhouseTestMixin, APIBaseTest):("HogVMException", "Global variable not found: variables"),])- @patch("posthog.api.insight.process_query_dict")+ @patch("products.product_analytics.backend.api.insight.process_query_dict")def test_trend_returns_400_for_exposed_errors(self, error_type: str, error_message: str, mock_process: mock.MagicMock) -> None:@@ -4796,7 +4793,7 @@ class TestInsightErrorHandling(ClickhouseTestMixin, APIBaseTest):("HogVMException", "Global variable not found: variables"),])- @patch("posthog.api.insight.process_query_dict")+ @patch("products.product_analytics.backend.api.insight.process_query_dict")def test_funnel_returns_400_for_exposed_errors(self, error_type: str, error_message: str, mock_process: mock.MagicMock) -> None:diff --git a/posthog/api/test/test_insight_funnels.py b/products/product_analytics/backend/api/test/test_insight_funnels.pysimilarity index 100%rename from posthog/api/test/test_insight_funnels.pyrename to products/product_analytics/backend/api/test/test_insight_funnels.pydiff --git a/posthog/api/test/test_insight_metadata.py b/products/product_analytics/backend/api/test/test_insight_metadata.pysimilarity index 99%rename from posthog/api/test/test_insight_metadata.pyrename to products/product_analytics/backend/api/test/test_insight_metadata.pyindex 62a729a780fc..684a734c31a0 100644--- a/posthog/api/test/test_insight_metadata.py+++ b/products/product_analytics/backend/api/test/test_insight_metadata.py@@ -4,7 +4,7 @@ from unittest.mock import patchfrom parameterized import parameterizedfrom rest_framework import status-MOCK_PATH = "posthog.api.insight_metadata.hit_openai"+MOCK_PATH = "products.product_analytics.backend.api.insight_metadata.hit_openai"def _make_query(source: dict) -> dict:diff --git a/posthog/api/test/test_insight_query.py b/products/product_analytics/backend/api/test/test_insight_query.pysimilarity index 99%rename from posthog/api/test/test_insight_query.pyrename to products/product_analytics/backend/api/test/test_insight_query.pyindex 7d887133b0db..58dbc0f198f7 100644--- a/posthog/api/test/test_insight_query.py+++ b/products/product_analytics/backend/api/test/test_insight_query.py@@ -4,7 +4,8 @@ from parameterized import parameterizedfrom rest_framework import statusfrom posthog.api.test.dashboards import DashboardAPI-from posthog.models.insight import Insight++from products.product_analytics.backend.models.insight import Insightfrom ee.api.test.base import LicensedTestMixindiff --git a/posthog/api/test/test_insight_variable.py b/products/product_analytics/backend/api/test/test_insight_variable.pysimilarity index 97%rename from posthog/api/test/test_insight_variable.pyrename to products/product_analytics/backend/api/test/test_insight_variable.pyindex 961ead816a9b..165ba9922299 100644--- a/posthog/api/test/test_insight_variable.py+++ b/products/product_analytics/backend/api/test/test_insight_variable.py@@ -7,9 +7,10 @@ from unittest.mock import MagicMock, patchfrom parameterized import parameterizedfrom rest_framework.exceptions import PermissionDenied-from posthog.api.insight_variable import InsightVariableViewSet, map_stale_to_latestfrom posthog.auth import SharingAccessTokenAuthentication-from posthog.models.insight_variable import InsightVariable++from products.product_analytics.backend.api.insight_variable import InsightVariableViewSet, map_stale_to_latest+from products.product_analytics.backend.models.insight_variable import InsightVariableclass TestInsightVariable(APIBaseTest):diff --git a/products/product_analytics/backend/migrations/0001_migrate_product_analytics_models.py b/products/product_analytics/backend/migrations/0001_migrate_product_analytics_models.pynew file mode 100644index 000000000000..e734bc8f6dfa--- /dev/null+++ b/products/product_analytics/backend/migrations/0001_migrate_product_analytics_models.py@@ -0,0 +1,342 @@+# Generated by Django 5.2.14 on 2026-05-22 11:19++import django.utils.timezone+import django.db.models.deletion+import django.contrib.postgres.fields+import django.contrib.postgres.indexes+from django.conf import settings+from django.db import migrations, models++import posthog.utils+import posthog.models.utils+++class Migration(migrations.Migration):+ initial = True++ dependencies = [+ ("dashboards", "0003_backfill_dashboardtile_team_id"),+ ("posthog", "1183_migrate_product_analytics_models_state"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.CreateModel(+ name="Insight",+ fields=[+ (+ "id",+ models.BigAutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("name", models.CharField(blank=True, max_length=400, null=True)),+ (+ "derived_name",+ models.CharField(blank=True, max_length=400, null=True),+ ),+ (+ "description",+ models.CharField(blank=True, max_length=400, null=True),+ ),+ ("filters", models.JSONField(default=dict)),+ (+ "filters_hash",+ models.CharField(blank=True, max_length=400, null=True),+ ),+ ("query", models.JSONField(blank=True, null=True)),+ ("query_metadata", models.JSONField(blank=True, null=True)),+ ("order", models.IntegerField(blank=True, null=True)),+ ("deleted", models.BooleanField(default=False)),+ ("saved", models.BooleanField(default=True)),+ ("created_at", models.DateTimeField(auto_now_add=True, null=True)),+ ("refreshing", models.BooleanField(default=False)),+ ("is_sample", models.BooleanField(default=False)),+ (+ "short_id",+ models.CharField(+ blank=True,+ default=posthog.utils.generate_short_id,+ max_length=12,+ ),+ ),+ ("favorited", models.BooleanField(default=False)),+ ("refresh_attempt", models.IntegerField(blank=True, null=True)),+ (+ "last_modified_at",+ models.DateTimeField(default=django.utils.timezone.now),+ ),+ ("last_refresh", models.DateTimeField(blank=True, null=True)),+ ("layouts", models.JSONField(default=dict)),+ ("color", models.CharField(blank=True, max_length=400, null=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ ("type", models.CharField(blank=True, max_length=400, null=True)),+ ("funnel", models.IntegerField(blank=True, null=True)),+ (+ "deprecated_tags",+ django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=32),+ blank=True,+ default=list,+ null=True,+ size=None,+ ),+ ),+ (+ "deprecated_tags_v2",+ django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=32),+ blank=True,+ db_column="tags",+ default=None,+ null=True,+ size=None,+ ),+ ),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "dashboard",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="items",+ to="dashboards.dashboard",+ ),+ ),+ (+ "dive_dashboard",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to="dashboards.dashboard",+ ),+ ),+ (+ "last_modified_by",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="modified_insights",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ ],+ options={+ "db_table": "posthog_dashboarditem",+ },+ ),+ migrations.CreateModel(+ name="InsightCachingState",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.UUIDT,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("cache_key", models.CharField(max_length=400)),+ ("target_cache_age_seconds", models.IntegerField(null=True)),+ ("last_refresh", models.DateTimeField(blank=True, null=True)),+ ("last_refresh_queued_at", models.DateTimeField(blank=True, null=True)),+ ("refresh_attempt", models.IntegerField(default=0)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "dashboard_tile",+ models.ForeignKey(+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="caching_states",+ to="dashboards.dashboardtile",+ ),+ ),+ (+ "insight",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="caching_states",+ to="product_analytics.insight",+ ),+ ),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ ],+ options={+ "db_table": "posthog_insightcachingstate",+ },+ ),+ migrations.CreateModel(+ name="InsightVariable",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.UUIDT,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("name", models.CharField(max_length=400)),+ ("code_name", models.CharField(blank=True, max_length=400, null=True)),+ (+ "type",+ models.CharField(+ choices=[+ ("String", "String"),+ ("Number", "Number"),+ ("Boolean", "Boolean"),+ ("List", "List"),+ ("Date", "Date"),+ ],+ max_length=128,+ ),+ ),+ ("default_value", models.JSONField(blank=True, null=True)),+ ("values", models.JSONField(blank=True, null=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ ],+ options={+ "db_table": "posthog_insightvariable",+ },+ ),+ migrations.CreateModel(+ name="InsightViewed",+ fields=[+ (+ "id",+ models.BigAutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("last_viewed_at", models.DateTimeField()),+ (+ "insight",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ to="product_analytics.insight",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ (+ "user",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ ],+ options={+ "db_table": "posthog_insightviewed",+ },+ ),+ migrations.AddIndex(+ model_name="insight",+ index=django.contrib.postgres.indexes.GinIndex(+ fields=["query_metadata"],+ name="dashboarditem_query_metadata",+ opclasses=["jsonb_ops"],+ ),+ ),+ migrations.AddIndex(+ model_name="insight",+ index=models.Index(+ condition=models.Q(("deleted", False)),+ fields=["team_id", "-last_modified_at"],+ name="dashboarditem_team_lmod_idx",+ ),+ ),+ migrations.AlterUniqueTogether(+ name="insight",+ unique_together={("team", "short_id")},+ ),+ migrations.AddIndex(+ model_name="insightcachingstate",+ index=models.Index(fields=["cache_key"], name="filter_by_cache_key_idx"),+ ),+ migrations.AddConstraint(+ model_name="insightcachingstate",+ constraint=posthog.models.utils.UniqueConstraintByExpression(+ concurrently=True,+ expression="(insight_id, coalesce(dashboard_tile_id, -1))",+ name="unique_insight_tile_idx",+ ),+ ),+ migrations.AddIndex(+ model_name="insightviewed",+ index=models.Index(+ fields=["team_id", "user_id", "-last_viewed_at"],+ name="posthog_ins_team_id_339ee0_idx",+ ),+ ),+ migrations.AddIndex(+ model_name="insightviewed",+ index=models.Index(+ fields=["insight_id", "-last_viewed_at"],+ name="insightviewed_insight_lva_idx",+ ),+ ),+ migrations.AddConstraint(+ model_name="insightviewed",+ constraint=models.UniqueConstraint(+ fields=("team", "user", "insight"), name="posthog_unique_insightviewed"+ ),+ ),+ ],+ database_operations=[+ # No database operations - table already exists with this name+ ],+ ),+ ]diff --git a/products/product_analytics/backend/migrations/__init__.py b/products/product_analytics/backend/migrations/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/product_analytics/backend/migrations/max_migration.txt b/products/product_analytics/backend/migrations/max_migration.txtnew file mode 100644index 000000000000..f8937f2a44c5--- /dev/null+++ b/products/product_analytics/backend/migrations/max_migration.txt@@ -0,0 +1 @@+0001_migrate_product_analytics_modelsdiff --git a/products/product_analytics/backend/models/__init__.py b/products/product_analytics/backend/models/__init__.pynew file mode 100644index 000000000000..fa2373e3e73c--- /dev/null+++ b/products/product_analytics/backend/models/__init__.py@@ -0,0 +1,10 @@+from .insight import Insight, InsightViewed+from .insight_caching_state import InsightCachingState+from .insight_variable import InsightVariable++__all__ = [+ "Insight",+ "InsightCachingState",+ "InsightVariable",+ "InsightViewed",+]diff --git a/posthog/models/insight.py b/products/product_analytics/backend/models/insight.pysimilarity index 95%rename from posthog/models/insight.pyrename to products/product_analytics/backend/models/insight.pyindex dc4fe3d393dd..7abc4094b755 100644--- a/posthog/models/insight.py+++ b/products/product_analytics/backend/models/insight.py@@ -19,14 +19,14 @@ from posthog.models.filters.utils import get_filterfrom posthog.models.utils import RootTeamManager, RootTeamMixin, sane_reprfrom posthog.utils import absolute_uri, generate_cache_key, generate_short_id-from products.dashboards.backend.models.dashboard import Dashboard-logger = structlog.get_logger(__name__)if TYPE_CHECKING:from posthog.models.team import Team+ from products.dashboards.backend.models.dashboard import Dashboard+class InsightManager(RootTeamManager):def get_queryset(self):@@ -42,7 +42,7 @@ class Insight(RootTeamMixin, FileSystemSyncMixin, models.Model):name = models.CharField(max_length=400, null=True, blank=True)derived_name = models.CharField(max_length=400, null=True, blank=True)description = models.CharField(max_length=400, null=True, blank=True)- team = models.ForeignKey("Team", on_delete=models.CASCADE)+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)filters = models.JSONField(default=dict)filters_hash = models.CharField(max_length=400, null=True, blank=True)query = models.JSONField(null=True, blank=True)@@ -53,7 +53,7 @@ class Insight(RootTeamMixin, FileSystemSyncMixin, models.Model):saved = models.BooleanField(default=True)created_at = models.DateTimeField(null=True, blank=True, auto_now_add=True)refreshing = models.BooleanField(default=False)- created_by = models.ForeignKey("User", on_delete=models.SET_NULL, null=True, blank=True)+ created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True)# Indicates if it's a sample graph generated by dashboard templatesis_sample = models.BooleanField(default=False)# Unique ID per team for easy sharing and short links@@ -62,7 +62,7 @@ class Insight(RootTeamMixin, FileSystemSyncMixin, models.Model):refresh_attempt = models.IntegerField(null=True, blank=True)last_modified_at = models.DateTimeField(default=timezone.now)last_modified_by = models.ForeignKey(- "User",+ "posthog.User",on_delete=models.SET_NULL,null=True,blank=True,@@ -200,7 +200,7 @@ class Insight(RootTeamMixin, FileSystemSyncMixin, models.Model):capture_exception(e)def dashboard_filters(- self, dashboard: Optional[Dashboard] = None, dashboard_filters_override: Optional[dict] = None+ self, dashboard: Optional["Dashboard"] = None, dashboard_filters_override: Optional[dict] = None):# query date range is set in a different function, see dashboard_queryif (dashboard is not None or dashboard_filters_override is not None) and not self.query:@@ -265,7 +265,7 @@ class Insight(RootTeamMixin, FileSystemSyncMixin, models.Model):def get_effective_query(self,*,- dashboard: Optional[Dashboard],+ dashboard: Optional["Dashboard"],dashboard_filters_override: Optional[dict] = None,dashboard_variables_override: Optional[dict[str, dict]] = None,) -> Optional[dict]:@@ -342,8 +342,8 @@ class Insight(RootTeamMixin, FileSystemSyncMixin, models.Model):class InsightViewed(models.Model):# To track views from shared insights, team and user can be null- team = models.ForeignKey("Team", on_delete=models.CASCADE, null=True, blank=True)- user = models.ForeignKey("User", on_delete=models.CASCADE, null=True, blank=True)+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, null=True, blank=True)+ user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, null=True, blank=True)insight: models.ForeignKey = models.ForeignKey(Insight, on_delete=models.CASCADE)last_viewed_at: models.DateTimeField = models.DateTimeField()@@ -354,10 +354,11 @@ class InsightViewed(models.Model):models.Index(fields=["team_id", "user_id", "-last_viewed_at"]),models.Index(fields=["insight_id", "-last_viewed_at"], name="insightviewed_insight_lva_idx"),]+ db_table = "posthog_insightviewed"@timed("generate_insight_cache_key")-def generate_insight_filters_hash(insight: Insight, dashboard: Optional[Dashboard]) -> str:+def generate_insight_filters_hash(insight: Insight, dashboard: Optional["Dashboard"]) -> str:try:dashboard_insight_filter = get_filter(data=insight.dashboard_filters(dashboard=dashboard), team=insight.team)candidate_filters_hash = generate_cache_key(diff --git a/posthog/models/insight_caching_state.py b/products/product_analytics/backend/models/insight_caching_state.pysimilarity index 93%rename from posthog/models/insight_caching_state.pyrename to products/product_analytics/backend/models/insight_caching_state.pyindex 8bbd51ba676d..43f280a70d73 100644--- a/posthog/models/insight_caching_state.py+++ b/products/product_analytics/backend/models/insight_caching_state.py@@ -1,15 +1,14 @@from django.db import modelsfrom django.db.models.signals import post_save-from posthog.models.insight import Insightfrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.signals import mutable_receiver-from posthog.models.team import Teamfrom posthog.models.utils import UniqueConstraintByExpression, UUIDTModelfrom posthog.tasks.tasks import sync_insight_caching_statefrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insightclass InsightCachingState(UUIDTModel):@@ -21,11 +20,12 @@ class InsightCachingState(UUIDTModel):expression="(insight_id, coalesce(dashboard_tile_id, -1))",)]+ db_table = "posthog_insightcachingstate"- team = models.ForeignKey(Team, on_delete=models.CASCADE)+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)insight = models.ForeignKey(- "posthog.Insight",+ "product_analytics.Insight",on_delete=models.CASCADE,related_name="caching_states",null=False,diff --git a/posthog/models/insight_variable.py b/products/product_analytics/backend/models/insight_variable.pysimilarity index 85%rename from posthog/models/insight_variable.pyrename to products/product_analytics/backend/models/insight_variable.pyindex b32040d6731a..bc75b9828c4e 100644--- a/posthog/models/insight_variable.py+++ b/products/product_analytics/backend/models/insight_variable.py@@ -11,7 +11,7 @@ class InsightVariable(UUIDTModel, RootTeamMixin, CreatedMetaFields, UpdatedMetaFLIST = "List", "List"DATE = "Date", "Date"- team = models.ForeignKey("Team", on_delete=models.CASCADE)+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)name = models.CharField(max_length=400)code_name = models.CharField(max_length=400, null=True, blank=True)type = models.CharField(max_length=128, choices=Type)@@ -19,3 +19,6 @@ class InsightVariable(UUIDTModel, RootTeamMixin, CreatedMetaFields, UpdatedMetaFvalues = models.JSONField(null=True, blank=True)__repr__ = sane_repr("id")++ class Meta:+ db_table = "posthog_insightvariable"diff --git a/products/product_analytics/backend/models/test/__init__.py b/products/product_analytics/backend/models/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/models/test/test_insight_caching_state.py b/products/product_analytics/backend/models/test/test_insight_caching_state.pysimilarity index 95%rename from posthog/models/test/test_insight_caching_state.pyrename to products/product_analytics/backend/models/test/test_insight_caching_state.pyindex 05a9ebb6e680..19621e3c5ec7 100644--- a/posthog/models/test/test_insight_caching_state.py+++ b/products/product_analytics/backend/models/test/test_insight_caching_state.py@@ -4,11 +4,13 @@ from posthog.test.base import BaseTestfrom django.utils.timezone import now-from posthog.models import Insight, InsightCachingState, SharingConfiguration+from posthog.models import SharingConfigurationfrom posthog.models.signals import mute_selected_signalsfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insight+from products.product_analytics.backend.models.insight_caching_state import InsightCachingStatefilters = {"events": [{"id": "$pageview"}],diff --git a/posthog/models/test/test_insight_model.py b/products/product_analytics/backend/models/test/test_insight_model.pysimilarity index 98%rename from posthog/models/test/test_insight_model.pyrename to products/product_analytics/backend/models/test/test_insight_model.pyindex 0ae3e8cbacf4..e5efb027f119 100644--- a/posthog/models/test/test_insight_model.py+++ b/products/product_analytics/backend/models/test/test_insight_model.py@@ -4,10 +4,10 @@ from django.db.utils import IntegrityErrorfrom parameterized import parameterized-from posthog.models import Insight, Team-from posthog.models.insight import generate_insight_filters_hash+from posthog.models import Teamfrom products.dashboards.backend.models.dashboard import Dashboard+from products.product_analytics.backend.models.insight import Insight, generate_insight_filters_hashclass TestInsightModel(BaseTest):diff --git a/products/product_analytics/backend/test/__init__.py b/products/product_analytics/backend/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/test/activity_logging/test_insight_activity_logging.py b/products/product_analytics/backend/test/test_insight_activity_logging.pysimilarity index 98%rename from posthog/test/activity_logging/test_insight_activity_logging.pyrename to products/product_analytics/backend/test/test_insight_activity_logging.pyindex 55ae7abe6501..627761c37264 100644--- a/posthog/test/activity_logging/test_insight_activity_logging.py+++ b/products/product_analytics/backend/test/test_insight_activity_logging.py@@ -5,11 +5,12 @@ from posthog.test.base import BaseTestfrom dateutil import parser-from posthog.models import Insight, Tag+from posthog.models import Tagfrom posthog.models.activity_logging.activity_log import Change, changes_betweenfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.models.insight import Insightclass TestChangesBetweenInsights(BaseTest):diff --git a/products/product_analytics/mcp/tools.yaml b/products/product_analytics/mcp/tools.yamlindex d9f34cd3a531..a32c1a642cea 100644--- a/products/product_analytics/mcp/tools.yaml+++ b/products/product_analytics/mcp/tools.yaml@@ -176,6 +176,12 @@ tools:- query_status- hogql- types+ insight-variables-create:+ operation: insight_variables_create+ enabled: false+ insight-variables-list:+ operation: insight_variables_list+ enabled: falseinsights-activity-retrieve:operation: insights_activity_retrieveenabled: truediff --git a/products/ruff.toml b/products/ruff.tomlindex d41a23e02998..ed413ce2f5b4 100644--- a/products/ruff.toml+++ b/products/ruff.toml@@ -37,6 +37,7 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]"marketing_analytics/backend/**" = ["ANN"]"messaging/backend/**" = ["ANN"]"notebooks/backend/**" = ["ANN"]+"product_analytics/backend/**" = ["ANN"]"product_tours/backend/**" = ["ANN"]"revenue_analytics/backend/**" = ["ANN"]"signals/backend/**" = ["ANN"]diff --git a/products/slack_app/backend/slack_link_unfurl.py b/products/slack_app/backend/slack_link_unfurl.pyindex 3dcd4ff6a2ed..5b6b8923ec18 100644--- a/products/slack_app/backend/slack_link_unfurl.py+++ b/products/slack_app/backend/slack_link_unfurl.py@@ -7,11 +7,11 @@ from urllib.parse import urlparseimport structlog-from posthog.models import Insightfrom posthog.models.integration import Integration, SlackIntegrationfrom posthog.rbac.user_access_control import UserAccessControl, access_level_satisfied_for_resourcefrom products.dashboards.backend.models.dashboard import Dashboard+from products.product_analytics.backend.models.insight import Insightlogger = structlog.get_logger(__name__)diff --git a/products/slack_app/backend/tests/test_link_unfurl.py b/products/slack_app/backend/tests/test_link_unfurl.pyindex 093b4db9f599..d5c211cf141b 100644--- a/products/slack_app/backend/tests/test_link_unfurl.py+++ b/products/slack_app/backend/tests/test_link_unfurl.py@@ -2,10 +2,10 @@ import pytestfrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch-from posthog.models import Insightfrom posthog.models.integration import Integrationfrom products.dashboards.backend.models.dashboard import Dashboard+from products.product_analytics.backend.models.insight import Insightfrom products.slack_app.backend.slack_link_unfurl import (_insight_resource_label,handle_posthog_link_unfurl,diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.pyindex a29c3bc6a017..c6c4eb0347eb 100644--- a/products/surveys/backend/api/survey.py+++ b/products/surveys/backend/api/survey.py@@ -57,7 +57,6 @@ from posthog.helpers.trigram_search import (MIN_NAME_TRIGRAM_SIMILARITY,normalize_search_term,)-from posthog.models import Insightfrom posthog.models.activity_logging.activity_log import Change, Detail, changes_between, load_activity, log_activityfrom posthog.models.activity_logging.activity_page import activity_page_responsefrom posthog.models.team.team import Team@@ -76,6 +75,7 @@ from products.feature_flags.backend.api.feature_flag import (warn_if_missing_feature_flag_write_scope,)from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.product_analytics.backend.models.insight import Insightfrom products.surveys.backend.models import MAX_ITERATION_COUNT, Survey, SurveyResponseArchive, ensure_question_idsfrom products.surveys.backend.summarization import fetch_responses, format_as_markdown, summarize_responsesfrom products.surveys.backend.translation import generate_survey_translationdiff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.pyindex 6461e9e5b3c1..7760997231e8 100644--- a/products/surveys/backend/api/test/test_survey.py+++ b/products/surveys/backend/api/test/test_survey.py@@ -24,12 +24,13 @@ from rest_framework import statusfrom posthog.api.test.test_personal_api_keys import PersonalAPIKeysBaseTestfrom posthog.constants import AvailableFeature-from posthog.models import Insight, Person, Team+from posthog.models import Person, Teamfrom posthog.models.cohort.cohort import Cohortfrom posthog.models.organization import Organization, OrganizationMembershipfrom products.actions.backend.models.action import Actionfrom products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.product_analytics.backend.models.insight import Insightfrom products.product_tours.backend.models import ProductTourfrom products.surveys.backend.api.survey import nh3_clean_with_allow_listfrom products.surveys.backend.models import MAX_ITERATION_COUNT, Survey, SurveyResponseArchivediff --git a/products/surveys/backend/migrations/0005_migrate_product_analytics_models.py b/products/surveys/backend/migrations/0005_migrate_product_analytics_models.pynew file mode 100644index 000000000000..c766d961a0dc--- /dev/null+++ b/products/surveys/backend/migrations/0005_migrate_product_analytics_models.py@@ -0,0 +1,26 @@+# Generated by Django 5.2.14 on 2026-05-22 11:19++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("product_analytics", "0001_migrate_product_analytics_models"),+ ("surveys", "0004_migrate_feature_flags_models"),+ ]++ operations = [+ migrations.AlterField(+ model_name="survey",+ name="linked_insight",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="surveys_linked_insight",+ related_query_name="survey_linked_insight",+ to="product_analytics.insight",+ ),+ ),+ ]diff --git a/products/surveys/backend/migrations/max_migration.txt b/products/surveys/backend/migrations/max_migration.txtindex 9b337fbc2f53..5eb66bf5118e 100644--- a/products/surveys/backend/migrations/max_migration.txt+++ b/products/surveys/backend/migrations/max_migration.txt@@ -1 +1 @@-0004_migrate_feature_flags_models+0005_migrate_product_analytics_modelsdiff --git a/products/surveys/backend/models.py b/products/surveys/backend/models.pyindex b2871cbf122c..f55636da68a7 100644--- a/products/surveys/backend/models.py+++ b/products/surveys/backend/models.py@@ -74,7 +74,7 @@ class Survey(FileSystemSyncMixin, RootTeamMixin, UUIDTModel):related_query_name="survey_targeting_flag",)linked_insight = models.ForeignKey(- "posthog.Insight",+ "product_analytics.Insight",null=True,blank=True,on_delete=models.SET_NULL,diff --git a/products/surveys/backend/test_max_tools.py b/products/surveys/backend/test_max_tools.pyindex 8193f464549d..bc6caf6d01f4 100644--- a/products/surveys/backend/test_max_tools.py+++ b/products/surveys/backend/test_max_tools.py@@ -11,9 +11,8 @@ from asgiref.sync import sync_to_asyncfrom langchain_core.runnables import RunnableConfigfrom parameterized import parameterized-from posthog.models import Insight-from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.product_analytics.backend.models.insight import Insightfrom products.surveys.backend.models import Surveyfrom .max_tools import CreateSurveyTool, EditSurveyTool, SimpleSurveyQuestion, SurveyAnalysisTooldiff --git a/tach.toml b/tach.tomlindex 0c1cf3423bbd..db7c5d22167c 100644--- a/tach.toml+++ b/tach.toml@@ -47,6 +47,7 @@ depends_on = ["products.mcp_store","products.notebooks","products.posthog_ai",+ "products.product_analytics","products.replay","products.revenue_analytics","products.surveys",@@ -116,6 +117,7 @@ depends_on = ["posthog","products.experiments","products.feature_flags",+ "products.product_analytics",]layer = "modules"@@ -124,6 +126,7 @@ path = "products.alerts"depends_on = ["ee","posthog",+ "products.product_analytics",]layer = "modules"@@ -159,16 +162,6 @@ depends_on = []layer = "modules"-[[modules]]-path = "products.customer_analytics"-depends_on = [- "ee",- "posthog",- "products.data_warehouse",- "products.notebooks",-]-layer = "modules"-[[modules]]path = "products.dashboards"depends_on = [@@ -177,6 +170,7 @@ depends_on = ["products.alerts","products.llm_analytics","products.mcp_analytics",+ "products.product_analytics",]layer = "modules"@@ -240,7 +234,8 @@ layer = "modules"[[modules]]path = "products.early_access_features"depends_on = [- "posthog", "products.feature_flags",+ "posthog",+ "products.feature_flags",]layer = "modules"@@ -250,6 +245,7 @@ depends_on = ["posthog","products.data_modeling","products.data_warehouse",+ "products.product_analytics","products.signals", "products.warehouse_sources",]layer = "modules"@@ -277,9 +273,10 @@ depends_on = ["posthog","products.actions","products.event_definitions",+ "products.feature_flags","products.notifications","products.product_tours",- "products.surveys", "products.feature_flags",+ "products.surveys",]layer = "modules"@@ -287,7 +284,13 @@ layer = "modules"path = "products.feature_flags"depends_on = ["ee",- "posthog", "products.surveys", "products.dashboards", "products.early_access_features", "products.product_tours", "products.experiments",+ "posthog",+ "products.dashboards",+ "products.early_access_features",+ "products.experiments",+ "products.product_analytics",+ "products.product_tours",+ "products.surveys",]layer = "modules"@@ -335,17 +338,6 @@ path = "products.managed_migrations"depends_on = []layer = "modules"-[[modules]]-path = "products.marketing_analytics"-depends_on = [- "posthog",- "products.access_control",- "products.actions",- "products.analytics_platform",- "products.data_warehouse", "products.warehouse_sources",-]-layer = "modules"-[[modules]]path = "products.mcp_analytics"depends_on = [@@ -380,6 +372,7 @@ path = "products.notebooks"depends_on = ["ee","posthog",+ "products.product_analytics","products.tasks",]layer = "modules"@@ -422,8 +415,11 @@ layer = "modules"[[modules]]path = "products.product_analytics"depends_on = [+ "ee","posthog","products.actions",+ "products.alerts",+ "products.dashboards","products.data_warehouse","products.event_definitions",]@@ -433,7 +429,8 @@ layer = "modules"path = "products.product_tours"depends_on = ["posthog",- "products.surveys", "products.feature_flags",+ "products.feature_flags",+ "products.surveys",]layer = "modules"@@ -482,6 +479,7 @@ path = "products.slack_app"depends_on = ["posthog","products.dashboards",+ "products.product_analytics",]layer = "modules"@@ -491,7 +489,31 @@ depends_on = ["ee","posthog","products.actions",- "products.product_tours", "products.feature_flags",+ "products.feature_flags",+ "products.product_analytics",+ "products.product_tours",+]+layer = "modules"++[[modules]]+path = "products.customer_analytics"+depends_on = [+ "ee",+ "posthog",+ "products.data_warehouse",+ "products.notebooks",+ "products.product_analytics",+]+layer = "modules"++[[modules]]+path = "products.marketing_analytics"+depends_on = [+ "posthog",+ "products.access_control",+ "products.actions",+ "products.analytics_platform",+ "products.data_warehouse", "products.warehouse_sources",]layer = "modules"@@ -502,11 +524,12 @@ depends_on = ["posthog","products.error_tracking","products.event_definitions",+ "products.feature_flags","products.llm_analytics","products.mcp_store","products.posthog_ai","products.signals",- "products.slack_app", "products.feature_flags",+ "products.slack_app",]layer = "modules"@@ -558,6 +581,7 @@ depends_on = [layer = "modules"# Facade + views: the canonical public surface for all isolated products.+[[interfaces]]expose = ["backend\\.facade.*",@@ -569,6 +593,7 @@ from = [# TODO: Experiments-specific temporary interface# Remove this block once all ViewSets are migrated to products/experiments/backend/presentation/views.py+[[interfaces]]expose = ["backend\\.presentation\\.experiments.*",@@ -579,6 +604,7 @@ from = []# user_interviews exposes Vapi webhook handlers that are routed directly from posthog/urls.py.+[[interfaces]]expose = ["backend\\.presentation\\.webhooks.*",@@ -629,6 +655,7 @@ from = [# integration import models / dashboard_templates directly. Move those into# the product (and through the facade) so this interface can shrink back to# the isolated default.+[[interfaces]]expose = ["backend\\.dashboard_templates.*",@@ -664,6 +691,7 @@ from = []# Legacy leaks — core (posthog/ee) still imports these internals directly.+[[interfaces]]expose = ["backend\\.models.*",