Skip to content

: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.

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.yml
index 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.py
index 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 Insight
from products.actions.backend.models.action import Action
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.project import Project
diff --git a/ee/api/subscription.py b/ee/api/subscription.py
index 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 groups
from posthog.exceptions import QuotaLimitExceeded
from posthog.exceptions_capture import capture_exception
-from posthog.models import Insight
from posthog.models.integration import Integration
from posthog.models.subscription import Subscription, SubscriptionDelivery, unsubscribe_using_token
from posthog.permissions import PremiumFeaturePermission
@@ -43,6 +42,8 @@ from posthog.temporal.common.client import sync_connect
from posthog.temporal.subscriptions.types import ProcessSubscriptionWorkflowInputs, SubscriptionTriggerType
from posthog.utils import str_to_bool
+from products.product_analytics.backend.models.insight import Insight
+
from ee.tasks.subscriptions.auto_disable import validate_re_enable
from ee.tasks.subscriptions.subscription_utils import DEFAULT_MAX_ASSET_COUNT
diff --git a/ee/api/test/test_insight.py b/ee/api/test/test_insight.py
index 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 status
from posthog.api.test.dashboards import DashboardAPI
from posthog.constants import AvailableFeature
-from posthog.models import Insight, OrganizationMembership, User
+from posthog.models import OrganizationMembership, User
from posthog.test.db_context_capturing import capture_db_queries
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.models.insight import Insight
from ee.api.test.base import APILicensedTest
from ee.models import DashboardPrivilege
diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.py
index 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 WorkflowAlreadyStartedError
from posthog.models import Team
from posthog.models.filters.filter import Filter
-from posthog.models.insight import Insight
from posthog.models.integration import Integration
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.subscription import Subscription, SubscriptionDelivery
@@ -22,6 +21,7 @@ from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.temporal.subscriptions.types import ProcessSubscriptionWorkflowInputs, SubscriptionTriggerType
from products.dashboards.backend.models.dashboard import Dashboard
+from products.product_analytics.backend.models.insight import Insight
from ee.api.test.base import APILicensedTest
from ee.tasks.subscriptions.slack_subscriptions import get_slack_integration_for_team
diff --git a/ee/api/test/test_tagged_item.py b/ee/api/test/test_tagged_item.py
index 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 APIBaseTest
from rest_framework import status
-from posthog.models import Insight, Tag
+from posthog.models import Tag
from posthog.models.tagged_item import TaggedItem
from products.dashboards.backend.models.dashboard import Dashboard
from 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.py
index f2bcd0e75ef3..890be1dddd18 100644
--- a/ee/clickhouse/views/insights.py
+++ b/ee/clickhouse/views/insights.py
@@ -5,13 +5,13 @@ from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.documentation import extend_schema
-from posthog.api.insight import InsightViewSet, capture_legacy_api_call
from posthog.api.utils import action
from posthog.decorators import cached_by_filters
-from posthog.models import Insight
from posthog.models.filters import Filter
from 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 Insight
from ee.clickhouse.queries.funnels.funnel_correlation import FunnelCorrelation
diff --git a/ee/clickhouse/views/person.py b/ee/clickhouse/views/person.py
index d9ad4a0d29d8..03e226ae3745 100644
--- a/ee/clickhouse/views/person.py
+++ b/ee/clickhouse/views/person.py
@@ -2,7 +2,6 @@ from typing import Optional
from rest_framework import request, response
-from posthog.api.insight import capture_legacy_api_call
from posthog.api.person import PersonViewSet
from posthog.api.utils import action
from posthog.constants import FUNNEL_CORRELATION_PERSON_LIMIT, FUNNEL_CORRELATION_PERSON_OFFSET, INSIGHT_FUNNELS
@@ -10,6 +9,8 @@ from posthog.decorators import cached_by_filters
from posthog.models import Filter
from 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 FunnelCorrelationActors
diff --git a/ee/hogai/artifacts/handlers/visualization.py b/ee/hogai/artifacts/handlers/visualization.py
index 868dbef133b9..d6e9c2b91aad 100644
--- a/ee/hogai/artifacts/handlers/visualization.py
+++ b/ee/hogai/artifacts/handlers/visualization.py
@@ -7,7 +7,9 @@ from pydantic import ValidationError
from 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 Insight
from ee.hogai.artifacts.handlers.base import ArtifactHandler, EnrichmentContext, register_handler
from ee.hogai.artifacts.types import (
diff --git a/ee/hogai/artifacts/test/test_manager.py b/ee/hogai/artifacts/test/test_manager.py
index 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 Insight
from ee.hogai.artifacts.manager import ArtifactManager
from ee.hogai.artifacts.types import StoredNotebookArtifactContent
diff --git a/ee/hogai/artifacts/types.py b/ee/hogai/artifacts/types.py
index 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 Insight
class VisualizationRefBlock(BaseModel):
diff --git a/ee/hogai/chat_agent/insights/nodes.py b/ee/hogai/chat_agent/insights/nodes.py
index 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 tool
from posthog.schema import ArtifactContentType, ArtifactSource, AssistantToolCallMessage
from posthog.exceptions_capture import capture_exception
-from posthog.models import Insight
+
+from products.product_analytics.backend.models.insight import Insight
from ee.hogai.context.insight.query_executor import AssistantQueryExecutor
from ee.hogai.core.node import AssistantNode
diff --git a/ee/hogai/chat_agent/insights/test/test_nodes.py b/ee/hogai/chat_agent/insights/test/test_nodes.py
index 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, InsightViewed
from ee.hogai.artifacts.manager import ArtifactManager
from ee.hogai.chat_agent.insights.nodes import InsightDict, InsightSearchNode, NoInsightsException
diff --git a/ee/hogai/context/entity_search/context.py b/ee/hogai/context/entity_search/context.py
index 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, User
from posthog.rbac.user_access_control import UserAccessControl
from posthog.sync import database_sync_to_async
@@ -24,6 +24,7 @@ from products.dashboards.backend.models.dashboard import Dashboard
from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.notebooks.backend.models import Notebook
+from products.product_analytics.backend.models.insight import Insight
from products.surveys.backend.models import Survey
from ee.hogai.artifacts.handlers.base import get_handler_for_content_type
diff --git a/ee/hogai/context/entity_search/test/test_context.py b/ee/hogai/context/entity_search/test/test_context.py
index 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 timezone
from parameterized import parameterized
-from posthog.models import Cohort, Insight
-from posthog.models.insight import InsightViewed
+from posthog.models import Cohort
from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.product_analytics.backend.models.insight import Insight, InsightViewed
from products.surveys.backend.models import Survey
from ee.hogai.context import AssistantContextManager
diff --git a/ee/hogai/context/insight/context.py b/ee/hogai/context/insight/context.py
index 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, User
from 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_query
from ee.hogai.tool_errors import MaxToolRetryableError
from ee.hogai.utils.helpers import build_insight_url
diff --git a/ee/hogai/eval/ci/max_tools/eval_upsert_dashboard.py b/ee/hogai/eval/ci/max_tools/eval_upsert_dashboard.py
index 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 Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.models.insight import Insight
from ee.hogai.chat_agent import AssistantGraph
from ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointer
diff --git a/ee/hogai/eval/data_setup.py b/ee/hogai/eval/data_setup.py
index 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_settings
from posthog.clickhouse.client import sync_execute
from posthog.demo.matrix.manager import MatrixManager
from 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, User
from posthog.models.event.sql import COPY_EVENTS_BETWEEN_TEAMS
from posthog.models.group.sql import COPY_GROUPS_BETWEEN_TEAMS
from posthog.models.person.sql import COPY_PERSON_DISTINCT_ID2S_BETWEEN_TEAMS, COPY_PERSONS_BETWEEN_TEAMS
from posthog.tasks.demo_create_data import HedgeboxMatrix
from products.dashboards.backend.models import Dashboard, DashboardTile
+from products.product_analytics.backend.models.insight import Insight
from ee.models.assistant import CoreMemory
diff --git a/ee/hogai/eval/sandboxed/seeders/insight.py b/ee/hogai/eval/sandboxed/seeders/insight.py
index 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 worker
thread via ``asyncio.to_thread`` from ``base.py:task()``.
"""
- from posthog.models.insight import Insight
+ from products.product_analytics.backend.models.insight import Insight
team_id = context.team_id
user_id = context.user_id
diff --git a/ee/hogai/tools/execute_sql/test/test_mcp_tool.py b/ee/hogai/tools/execute_sql/test/test_mcp_tool.py
index 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, patch
from asgiref.sync import sync_to_async
-from posthog.models import Insight
+from products.product_analytics.backend.models.insight import Insight
from ee.hogai.tool_errors import MaxToolRetryableError
from ee.hogai.tools.execute_sql.mcp_tool import ExecuteSQLMCPTool, ExecuteSQLMCPToolArgs
diff --git a/ee/hogai/tools/execute_sql/test/test_tool.py b/ee/hogai/tools/execute_sql/test/test_tool.py
index 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 Insight
from ee.hogai.context.context import AssistantContextManager
from ee.hogai.tools.execute_sql.tool import ExecuteSQLTool, ExecuteSQLToolArgs
diff --git a/ee/hogai/tools/read_data/test/test_tool.py b/ee/hogai/tools/read_data/test/test_tool.py
index 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 Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from 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 Insight
from products.surveys.backend.models import Survey
from products.warehouse_sources.backend.models.credential import DataWarehouseCredential
from products.warehouse_sources.backend.models.table import DataWarehouseTable
diff --git a/ee/hogai/tools/upsert_dashboard/test/test_tool.py b/ee/hogai/tools/upsert_dashboard/test/test_tool.py
index 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 Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile, Text
+from products.product_analytics.backend.models.insight import Insight
from ee.hogai.artifacts.types import ModelArtifactResult, StateArtifactResult, VisualizationWithSourceResult
from ee.hogai.context.context import AssistantContextManager
diff --git a/ee/hogai/tools/upsert_dashboard/tool.py b/ee/hogai/tools/upsert_dashboard/tool.py
index 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, Field
from posthog.schema import DataTableNode, HogQLQuery, InsightVizNode, QuerySchemaRoot
from posthog.event_usage import EventSource, report_user_action
-from posthog.models import Insight
from posthog.sync import database_sync_to_async
from posthog.utils import pluralize
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.models.insight import Insight
from ee.hogai.artifacts.types import ModelArtifactResult, VisualizationWithSourceResult
from ee.hogai.context.dashboard.context import DashboardContext, DashboardInsightContext
diff --git a/ee/tasks/subscriptions/subscription_utils.py b/ee/tasks/subscriptions/subscription_utils.py
index 02aac42bb786..aaede6bdb360 100644
--- a/ee/tasks/subscriptions/subscription_utils.py
+++ b/ee/tasks/subscriptions/subscription_utils.py
@@ -8,12 +8,13 @@ from celery import chain
from prometheus_client import Histogram
from posthog.models.exported_asset import ExportedAsset
-from posthog.models.insight import Insight
from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.subscription import Subscription
from posthog.tasks import exporter
from 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.py
index 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 APIBaseTest
from unittest.mock import MagicMock, patch
from posthog.models.exported_asset import ExportedAsset
-from posthog.models.insight import Insight
from posthog.models.instance_setting import set_instance_setting
from posthog.models.subscription import Subscription
from posthog.tasks.test.utils_email_tests import mock_email_messages
from products.dashboards.backend.models.dashboard import Dashboard
+from products.product_analytics.backend.models.insight import Insight
from ee.tasks.subscriptions.email_subscriptions import send_email_subscription_report
from ee.tasks.test.subscriptions.subscriptions_test_factory import create_subscription
diff --git a/ee/tasks/test/subscriptions/test_slack_subscriptions.py b/ee/tasks/test/subscriptions/test_slack_subscriptions.py
index 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 SlackApiError
from slack_sdk.web.async_slack_response import AsyncSlackResponse
from posthog.models.exported_asset import ExportedAsset
-from posthog.models.insight import Insight
from posthog.models.integration import Integration
from posthog.models.subscription import Subscription
from products.dashboards.backend.models.dashboard import Dashboard
+from products.product_analytics.backend.models.insight import Insight
from 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.py
index 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 APIBaseTest
from unittest.mock import MagicMock, patch
from posthog.models.exported_asset import ExportedAsset
-from posthog.models.insight import Insight
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.models.insight import Insight
from ee.tasks.subscriptions.subscription_utils import DEFAULT_MAX_ASSET_COUNT, generate_assets
from ee.tasks.test.subscriptions.subscriptions_test_factory import create_subscription
diff --git a/ee/tasks/test/test_slack.py b/ee/tasks/test/test_slack.py
index 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, patch
from posthog import settings
from posthog.models.exported_asset import ExportedAsset
-from posthog.models.insight import Insight
from posthog.models.integration import Integration
from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.subscription import Subscription
from products.dashboards.backend.models.dashboard import Dashboard
+from products.product_analytics.backend.models.insight import Insight
from ee.tasks.slack import handle_slack_event
diff --git a/posthog/admin/admins/insight_admin.py b/posthog/admin/admins/insight_admin.py
index 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 reverse
from django.utils.html import format_html
from posthog.admin.filters import DeletedFilter
-from posthog.models import Insight
+
+from products.product_analytics.backend.models.insight import Insight
class InsightAdminForm(forms.ModelForm):
diff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.py
index 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__.py
index 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, "query
from posthog.api.cohort import CohortViewSet, LegacyCohortViewSet # noqa: E402
from posthog.api.element import ElementViewSet, LegacyElementViewSet # noqa: E402
from posthog.api.event import EventViewSet, LegacyEventViewSet # noqa: E402
-from posthog.api.insight import InsightViewSet # noqa: E402
from posthog.api.person import LegacyPersonViewSet, PersonViewSet # noqa: E402
from posthog.api.web_experiment import WebExperimentViewSet # noqa: E402
from 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.py
index 00916b5a0e28..2434f47a26c7 100644
--- a/posthog/api/annotation.py
+++ b/posthog/api/annotation.py
@@ -14,11 +14,12 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.api.shared import UserBasicSerializer
from posthog.event_usage import report_user_action
-from posthog.models import Annotation, Insight
+from posthog.models import Annotation
from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activity
from posthog.models.signals import model_activity_signal, mutable_receiver
from 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.py
index 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 CohortTypeValidationSerializer
from posthog.models.filters.filter import Filter
-from posthog.models.insight import Insight
from posthog.models.person.person import READ_DB_FOR_PERSONS, PersonDistinctId
from posthog.models.person.util import validate_person_uuids_exist
from 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.py
index 8bfa60e25763..88e8704269f2 100644
--- a/posthog/api/exports.py
+++ b/posthog/api/exports.py
@@ -19,7 +19,7 @@ from temporalio.common import RetryPolicy, SearchAttributePair, TypedSearchAttri
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
from posthog.event_usage import EventSource, get_event_source, groups
-from posthog.models import Insight, Team, User
+from posthog.models import Team, User
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from posthog.models.exported_asset import ExportedAsset, get_content_response
from 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, ExportAssetWorkflowInputs
from 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.py
index 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.py
index 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 status
from rest_framework.test import APIRequestFactory
from 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, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.cohort import Cohort
from posthog.models.file_system.file_system import FileSystem
@@ -24,6 +24,7 @@ from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.links.backend.models import Link
from products.notebooks.backend.models import Notebook
+from products.product_analytics.backend.models.insight import Insight
from products.surveys.backend.models import Survey
from ee.models.rbac.access_control import AccessControl
diff --git a/posthog/api/my_notifications.py b/posthog/api/my_notifications.py
index 0845d8d0b147..9c6b4999af4c 100644
--- a/posthog/api/my_notifications.py
+++ b/posthog/api/my_notifications.py
@@ -12,11 +12,12 @@ from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.utils import ServerTimingsGathered, action
-from posthog.models import ActivityLog, Cohort, HogFunction, Insight, NotificationViewed, User
+from posthog.models import ActivityLog, Cohort, HogFunction, NotificationViewed, User
from posthog.models.comment import Comment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.notebooks.backend.models import Notebook
+from products.product_analytics.backend.models.insight import Insight
class MyNotificationsSerializer(serializers.ModelSerializer):
diff --git a/posthog/api/person.py b/posthog/api/person.py
index 98dff774ff3f..6ca4ee71e45e 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -35,7 +35,6 @@ from posthog.hogql.constants import CSV_EXPORT_LIMIT
from posthog.api.capture import capture_internal
from posthog.api.documentation import PersonPropertiesSerializer
-from posthog.api.insight import capture_legacy_api_call
from posthog.api.property_value_metrics import PROPERTY_VALUES_DURATION
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action, format_paginated_url, get_target_entity
@@ -79,6 +78,8 @@ from posthog.settings import EE_AVAILABLE
from posthog.tasks.split_person import split_person
from 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.py
index 2d8d757b892c..a26654d97bd0 100644
--- a/posthog/api/search.py
+++ b/posthog/api/search.py
@@ -12,7 +12,7 @@ from rest_framework.response import Response
from posthog.api.documentation import _FallbackSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.helpers.full_text_search import build_rank, process_query
-from posthog.models import Cohort, EventDefinition, Insight, PropertyDefinition
+from posthog.models import Cohort, EventDefinition, PropertyDefinition
from posthog.models.hog_flow.hog_flow import HogFlow
from products.actions.backend.models.action import Action
@@ -21,6 +21,7 @@ from products.early_access_features.backend.models import EarlyAccessFeature
from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.notebooks.backend.models import Notebook
+from products.product_analytics.backend.models.insight import Insight
from products.surveys.backend.models import Survey
LIMIT = 25
diff --git a/posthog/api/sharing.py b/posthog/api/sharing.py
index f8ac03273f6c..e43b9cdc3c5d 100644
--- a/posthog/api/sharing.py
+++ b/posthog/api/sharing.py
@@ -24,8 +24,6 @@ from posthog.schema import SharingConfigurationSettings
from posthog.api.data_color_theme import DataColorTheme, DataColorThemeSerializer
from posthog.api.exports import ExportedAssetSerializer
-from posthog.api.insight import InsightSerializer
-from posthog.api.insight_variable import InsightVariable
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.services.query import process_query_dict
from posthog.api.shared import TeamPublicSerializer
@@ -35,10 +33,9 @@ from posthog.constants import AvailableFeature
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.query_runner import ExecutionMode, shared_insights_execution_mode
from posthog.jwt import PosthogJwtAudience, encode_jwt
-from posthog.models import Cohort, InsightViewed, SessionRecording, SharePassword, SharingConfiguration, Team
+from posthog.models import Cohort, SessionRecording, SharePassword, SharingConfiguration, Team
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from posthog.models.exported_asset import ExportedAsset, asset_for_token, get_content_response
-from posthog.models.insight import Insight
from posthog.models.resource_transfer.visitors.insight import InsightVisitor
from posthog.models.user import User
from posthog.rbac.user_access_control import UserAccessControl, access_level_satisfied_for_resource
@@ -53,6 +50,9 @@ from products.dashboards.backend.models.dashboard import Dashboard
from products.notebooks.backend.api.notebook import NotebookSerializer
from products.notebooks.backend.models import Notebook
from 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 InsightVariable
logger = structlog.get_logger(__name__)
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.py
index 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, PropertyO
from posthog.api.test.dashboards import DashboardAPI
from posthog.constants import AvailableFeature
from 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, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.file_system.file_system_view_log import FileSystemViewLog
from posthog.models.group_type_mapping import GROUP_TYPES_CACHE_KEY_PREFIX, GROUP_TYPES_STALE_CACHE_KEY_PREFIX
-from posthog.models.insight_variable import InsightVariable
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.project import Project
from posthog.models.quick_filter import QuickFilter
@@ -34,6 +33,8 @@ from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.dashboards.backend.api.dashboard import DashboardSerializer
from products.dashboards.backend.models.dashboard import Dashboard
from 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 InsightVariable
from ee.models.rbac.access_control import AccessControl
diff --git a/posthog/api/test/test_annotation.py b/posthog/api/test/test_annotation.py
index 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 now
from parameterized import parameterized
from rest_framework import status
-from posthog.models import Annotation, Insight, Organization, Team, User
+from posthog.models import Annotation, Organization, Team, User
from products.dashboards.backend.models.dashboard import Dashboard
+from products.product_analytics.backend.models.insight import Insight
class TestAnnotation(APIBaseTest, QueryMatchingTest):
diff --git a/posthog/api/test/test_annotation_context.py b/posthog/api/test/test_annotation_context.py
index 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, Team
from products.dashboards.backend.models.dashboard import Dashboard
+from products.product_analytics.backend.models.insight import Insight
class TestAnnotationContext(APIBaseTest):
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index 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 Insight
response = 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 Insight
response = 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 Insight
response = 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 Insight
response = 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 Insight
response = 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 Insight
response = 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.py
index 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 status
from posthog.hogql.errors import QueryError
-from posthog.api.insight import InsightSerializer
from posthog.errors import CHQueryErrorTooManySimultaneousQueries
from posthog.models.exported_asset import ExportedAsset
from posthog.models.filters.filter import Filter
-from posthog.models.insight import Insight
from posthog.models.team import Team
from posthog.models.user import User
from posthog.settings import (
@@ -39,6 +37,8 @@ from posthog.tasks.exports.image_exporter import export_image
from products.dashboards.backend.models.dashboard import Dashboard
from 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 Insight
from ee.models.rbac.access_control import AccessControl
diff --git a/posthog/api/test/test_file_system.py b/posthog/api/test/test_file_system.py
index 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 Cohort
from posthog.models.file_system.file_system import FileSystem
from posthog.models.file_system.file_system_view_log import FileSystemViewLog
from posthog.models.hog_functions.hog_function import HogFunction, HogFunctionType
-from posthog.models.insight import Insight
from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
from products.actions.backend.models.action import Action
@@ -33,6 +32,7 @@ from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.links.backend.models import Link
from products.notebooks.backend.models import Notebook
+from products.product_analytics.backend.models.insight import Insight
from products.surveys.backend.models import Survey
diff --git a/posthog/api/test/test_personal_api_keys.py b/posthog/api/test/test_personal_api_keys.py
index 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 EventsQuery
from posthog.api.personal_api_key import PersonalAPIKeySerializer
from posthog.constants import AvailableFeature
from posthog.jwt import PosthogJwtAudience, encode_jwt
-from posthog.models.insight import Insight
from posthog.models.organization import Organization
from posthog.models.personal_api_key import LEGACY_PERSONAL_API_KEY_SALT, PersonalAPIKey
from posthog.models.team.team import Team
from posthog.models.utils import SHA256_HASH_PREFIX, generate_random_token_personal, hash_key_value
from products.error_tracking.backend.models import ErrorTrackingIssue
+from products.product_analytics.backend.models.insight import Insight
class TestPersonalAPIKeysAPI(APIBaseTest):
diff --git a/posthog/api/test/test_query.py b/posthog/api/test/test_query.py
index 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 LimitContext
from posthog.api.services.query import process_query_dict, process_query_model
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.query_tagging import Product, QueryTags
-from posthog.models.insight_variable import InsightVariable
from posthog.models.utils import UUIDT
from products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType
+from products.product_analytics.backend.models.insight_variable import InsightVariable
class TestQuery(ClickhouseTestMixin, APIBaseTest):
diff --git a/posthog/api/test/test_resource_transfer.py b/posthog/api/test/test_resource_transfer.py
index 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 patch
from parameterized import parameterized
from rest_framework import status
-from posthog.models import Insight, Project, Team
+from posthog.models import Project, Team
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.cohort import Cohort
from posthog.models.organization import Organization, OrganizationMembership
@@ -15,6 +15,7 @@ from posthog.models.resource_transfer.resource_transfer import ResourceTransfer
from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.models.insight import Insight
from products.surveys.backend.models import Survey
from ee.models.rbac.access_control import AccessControl
diff --git a/posthog/api/test/test_search.py b/posthog/api/test/test_search.py
index 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 CaptureQueriesContext
from posthog.api.search import ENTITY_MAP, class_queryset, search_entities
from posthog.helpers.full_text_search import build_search_vector, process_query
-from posthog.models import Insight, Team
+from posthog.models import Team
from posthog.models.hog_flow.hog_flow import HogFlow
from products.dashboards.backend.models.dashboard import Dashboard
@@ -15,6 +15,7 @@ from products.early_access_features.backend.models import EarlyAccessFeature
from products.event_definitions.backend.models.event_definition import EventDefinition
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.notebooks.backend.models import Notebook
+from products.product_analytics.backend.models.insight import Insight
class TestSearch(APIBaseTest):
diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.py
index 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_png
from posthog.constants import AvailableFeature
from posthog.models import ActivityLog, ExportedAsset
from posthog.models.filters.filter import Filter
-from posthog.models.insight import Insight
from posthog.models.share_password import SharePassword
from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.user import User
from products.dashboards.backend.models.dashboard import Dashboard
+from products.product_analytics.backend.models.insight import Insight
def 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_template
def 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_template
def 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_template
def 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.py
index 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 settings
from django.utils import timezone
from posthog.constants import AvailableFeature
-from posthog.models.insight import Insight
from posthog.models.sharing_configuration import SharingConfiguration
from products.dashboards.backend.models.dashboard import Dashboard
+from products.product_analytics.backend.models.insight import Insight
class 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 first
variable = InsightVariable.objects.create(
diff --git a/posthog/api/test/test_tagged_item.py b/posthog/api/test/test_tagged_item.py
index 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 APIBaseTest
from parameterized import parameterized
from rest_framework import status
-from posthog.models import Insight, Organization, Tag, Team
+from posthog.models import Organization, Tag, Team
from posthog.models.tagged_item import TaggedItem
from products.dashboards.backend.models.dashboard import Dashboard
+from products.product_analytics.backend.models.insight import Insight
class TestTaggedItemSerializerMixin(APIBaseTest):
diff --git a/posthog/caching/calculate_results.py b/posthog/caching/calculate_results.py
index 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_dict
from posthog.clickhouse.query_tagging import get_team_query_tags, tag_queries
from posthog.event_usage import AnalyticsProps
from 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, User
from posthog.schema_migrations.upgrade_manager import upgrade_query
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.models.insight import Insight, generate_insight_filters_hash
if TYPE_CHECKING:
from posthog.caching.fetch_from_cache import InsightResult
diff --git a/posthog/caching/insight_cache.py b/posthog/caching/insight_cache.py
index 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_queries
from posthog.event_usage import EventSource
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.query_runner import ExecutionMode
-from posthog.models import Insight, InsightCachingState
from posthog.schema_migrations.upgrade_manager import upgrade_query
from posthog.tasks.tasks import update_cache_task
from 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 InsightCachingState
logger = structlog.get_logger(__name__)
diff --git a/posthog/caching/insight_caching_state.py b/posthog/caching/insight_caching_state.py
index 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 Counter
from posthog.caching.calculate_results import calculate_cache_key
from posthog.caching.utils import active_teams, is_team_active
from 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 InsightCachingState
from posthog.models.team import Team
from posthog.models.utils import UUIDT
from posthog.schema_migrations.upgrade_manager import upgrade_query
from 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 InsightCachingState
VERY_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.py
index 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 json
from posthog.caching.insight_cache import update_cache
from posthog.caching.insight_caching_state import upsert
from posthog.caching.test.test_insight_caching_state import create_insight, filter_dict
-from posthog.models import InsightCachingState, Team, User
+from posthog.models import Team, User
from posthog.models.signals import mute_selected_signals
from 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.py
index 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, User
from posthog.models.signals import mute_selected_signals
from products.dashboards.backend.models.dashboard import Dashboard
from 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 InsightCachingState
filter_dict = {
"events": [{"id": "$pageview"}],
diff --git a/posthog/caching/test/test_warming.py b/posthog/caching/test/test_warming.py
index 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 APIBaseTest
from unittest.mock import patch
from posthog.caching.warming import insights_to_keep_fresh, schedule_warming_for_teams_task
-from posthog.models import Insight, InsightViewed
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.models.insight import Insight, InsightViewed
class TestWarming(APIBaseTest):
diff --git a/posthog/caching/warming.py b/posthog/caching/warming.py
index ec6ef9701fa6..d482b47ac1c7 100644
--- a/posthog/caching/warming.py
+++ b/posthog/caching/warming.py
@@ -21,13 +21,14 @@ from posthog.event_usage import EventSource
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.query_cache_base import QueryCacheManagerBase
from posthog.hogql_queries.query_runner import ExecutionMode
-from posthog.models import Insight, Team
+from posthog.models import Team
from posthog.ph_client import ph_scoped_capture
from posthog.schema_migrations.upgrade_manager import upgrade_query
from posthog.scoping_audit import skip_team_scope_audit
from posthog.tasks.utils import CeleryQueue
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.models.insight import Insight
logger = structlog.get_logger(__name__)
diff --git a/posthog/demo/legacy/app_data_generator.py b/posthog/demo/legacy/app_data_generator.py
index 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 now
from dateutil.relativedelta import relativedelta
from posthog.constants import TREND_FILTER_TYPE_ACTIONS
-from posthog.models import EventDefinition, Insight, Person, PropertyDefinition
+from posthog.models import EventDefinition, Person, PropertyDefinition
from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.models.insight import Insight
from .data_generator import DataGenerator
diff --git a/posthog/demo/legacy/insight_variables_data_generator.py b/posthog/demo/legacy/insight_variables_data_generator.py
index 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 Person
from products.dashboards.backend.models.dashboard import Dashboard
from 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 InsightVariable
from .data_generator import DataGenerator
diff --git a/posthog/demo/legacy/revenue_data_generator.py b/posthog/demo/legacy/revenue_data_generator.py
index 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 now
from dateutil.relativedelta import relativedelta
from posthog.constants import TREND_FILTER_TYPE_ACTIONS
-from posthog.models import EventDefinition, Insight, Person, PropertyDefinition
+from posthog.models import EventDefinition, Person, PropertyDefinition
from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.models.insight import Insight
from .data_generator import DataGenerator
diff --git a/posthog/demo/legacy/web_data_generator.py b/posthog/demo/legacy/web_data_generator.py
index 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 now
from dateutil.relativedelta import relativedelta
from posthog.constants import TREND_FILTER_TYPE_ACTIONS
-from posthog.models import Insight, Person, PropertyDefinition
+from posthog.models import Person, PropertyDefinition
from posthog.models.filters.mixins.utils import cached_property
from posthog.models.utils import UUIDT
from posthog.utils import get_absolute_path
@@ -16,6 +16,7 @@ from posthog.utils import get_absolute_path
from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.models.insight import Insight
from .data_generator import DataGenerator
diff --git a/posthog/demo/products/hedgebox/matrix.py b/posthog/demo/products/hedgebox/matrix.py
index 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, Matrix
from posthog.demo.matrix.models import SimEvent
from posthog.demo.matrix.randomization import Industry
from posthog.exceptions_capture import capture_exception
-from posthog.models import Cohort, Insight, InsightViewed
+from posthog.models import Cohort
from posthog.models.event.util import create_event
from posthog.models.oauth import OAuthApplication
from 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, ExperimentToSavedMetric
from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.product_analytics.backend.models.insight import Insight, InsightViewed
from products.warehouse_sources.backend.models.credential import get_or_create_datawarehouse_credential
from products.warehouse_sources.backend.models.table import DataWarehouseTable
diff --git a/posthog/helpers/dashboard_templates.py b/posthog/helpers/dashboard_templates.py
index 2099772ed49f..405d94ac33d5 100644
--- a/posthog/helpers/dashboard_templates.py
+++ b/posthog/helpers/dashboard_templates.py
@@ -6,12 +6,12 @@ from django.db.models import Q
import structlog
from posthog.constants import ENRICHED_DASHBOARD_INSIGHT_IDENTIFIER
-from posthog.models.insight import Insight
from posthog.models.tag import Tag
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_templates import DashboardTemplate
from products.dashboards.backend.models.dashboard_tile import ButtonTile, DashboardTile, Text
+from products.product_analytics.backend.models.insight import Insight
DASHBOARD_COLORS: list[str] = ["white", "blue", "green", "purple", "black"]
diff --git a/posthog/hogql/autocomplete.py b/posthog/hogql/autocomplete.py
index 16d1e3c56b2d..80690d5f562f 100644
--- a/posthog/hogql/autocomplete.py
+++ b/posthog/hogql/autocomplete.py
@@ -46,11 +46,11 @@ from posthog.hogql.visitor import TraversingVisitor, clone_expr
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.query_runner import get_query_runner
-from posthog.models.insight_variable import InsightVariable
from posthog.models.team.team import Team
from posthog.models.user import User
from products.event_definitions.backend.models.property_definition import PropertyDefinition
+from products.product_analytics.backend.models.insight_variable import InsightVariable
from common.hogvm.python.stl import STL
from common.hogvm.python.stl.bytecode import BYTECODE_STL
diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.py
index 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 ScoreDefinit
from products.llm_analytics.backend.models.trace_reviews import TraceReview, TraceReviewScore
from products.logs.backend.models import LogsAlertConfiguration, LogsView
from products.notebooks.backend.models import Notebook
+from products.product_analytics.backend.models.insight import Insight
+from products.product_analytics.backend.models.insight_variable import InsightVariable
from products.surveys.backend.models import Survey
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
diff --git a/posthog/hogql/test/test_autocomplete.py b/posthog/hogql/test/test_autocomplete.py
index 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 StringDatabaseField
from posthog.hogql.database.schema.events import EventsTable
from 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 DataWarehouseSavedQuery
from products.data_warehouse.backend.types import ExternalDataSourceType
from products.event_definitions.backend.models.property_definition import PropertyDefinition
+from products.product_analytics.backend.models.insight_variable import InsightVariable
from products.warehouse_sources.backend.models.credential import DataWarehouseCredential
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import DataWarehouseTable
diff --git a/posthog/hogql/test/test_metadata.py b/posthog/hogql/test/test_metadata.py
index 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_metadata
from posthog.models import Cohort, PropertyDefinition
-from posthog.models.insight_variable import InsightVariable
from products.data_warehouse.backend.types import ExternalDataSourceType
+from products.product_analytics.backend.models.insight_variable import InsightVariable
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import DataWarehouseTable
diff --git a/posthog/hogql/test/test_query.py b/posthog/hogql/test/test_query.py
index 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 InternalCHQueryError
from posthog.models import Cohort
from posthog.models.cohort.util import recalculate_cohortpeople
from posthog.models.exchange_rate.currencies import SUPPORTED_CURRENCY_CODES
-from posthog.models.insight_variable import InsightVariable
from posthog.models.utils import UUIDT, uuid7
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
from products.data_warehouse.backend.types import ExternalDataSourceType
+from products.product_analytics.backend.models.insight_variable import InsightVariable
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
diff --git a/posthog/hogql/variables.py b/posthog/hogql/variables.py
index 5beff455139e..2ee3e17f2cf9 100644
--- a/posthog/hogql/variables.py
+++ b/posthog/hogql/variables.py
@@ -7,9 +7,10 @@ from posthog.hogql import ast
from posthog.hogql.errors import QueryError
from posthog.hogql.visitor import CloningVisitor
-from posthog.models.insight_variable import InsightVariable
from 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.py
index 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_exception
from .filter_to_query import filter_to_query
if TYPE_CHECKING:
- from posthog.models.insight import Insight
+ from products.product_analytics.backend.models.insight import Insight
@contextmanager
diff --git a/posthog/hogql_queries/test/test_hogql_query_runner.py b/posthog/hogql_queries/test/test_hogql_query_runner.py
index 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_locations
from posthog.caching.utils import ThresholdMode, staleness_threshold_map
from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner
-from posthog.models.insight_variable import InsightVariable
from posthog.models.utils import UUIDT
from products.data_warehouse.backend.types import ExternalDataSourceType
+from products.product_analytics.backend.models.insight_variable import InsightVariable
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
diff --git a/posthog/management/commands/backfill_insights_query_metadata.py b/posthog/management/commands/backfill_insights_query_metadata.py
index 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 Q
import structlog
from posthog.hogql_queries.query_metadata import InsightQueryMetadata
-from posthog.models import Insight
+
+from products.product_analytics.backend.models.insight import Insight
logger = structlog.get_logger(__name__)
diff --git a/posthog/management/commands/migrate_retention_show_mean.py b/posthog/management/commands/migrate_retention_show_mean.py
index 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 BaseCommand
from django.db import transaction
-from posthog.models import Insight
+from products.product_analytics.backend.models.insight import Insight
def migrate_show_mean_from_boolean_to_string(batch_size: int, live_run: bool = False) -> None:
diff --git a/posthog/middleware.py b/posthog/middleware.py
index 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_h
from posthog.geoip import get_geoip_properties
from posthog.helpers.impersonation import get_original_user_from_session
from posthog.helpers.user_devices import set_known_device_cookie
-from posthog.models import Cohort, Insight, Team, User
+from posthog.models import Cohort, Team, User
from 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 Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.notebooks.backend.models import Notebook
+from products.product_analytics.backend.models.insight import Insight
from .auth import PersonalAPIKeyAuthentication
diff --git a/posthog/migrations/0156_insight_short_id.py b/posthog/migrations/0156_insight_short_id.py
index 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.utils
def 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.py
new file mode 100644
index 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.py
new file mode 100644
index 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.txt
index 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_models
diff --git a/posthog/models/__init__.py b/posthog/models/__init__.py
index 354f41ec5fe6..01e9ed934e15 100644
--- a/posthog/models/__init__.py
+++ b/posthog/models/__init__.py
@@ -50,9 +50,6 @@ from .hog_flow import HogFlow
from .hog_functions import HogFunction
from .hog_function_template import HogFunctionTemplate
from .health_issue import HealthIssue
-from .insight import Insight, InsightViewed
-from .insight_caching_state import InsightCachingState
-from .insight_variable import InsightVariable
from .instance_setting import InstanceSetting
from .integration import Integration
from .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.py
index 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.py
index 67b37615b820..0c5223668b9f 100644
--- a/posthog/models/exported_asset.py
+++ b/posthog/models/exported_asset.py
@@ -68,7 +68,7 @@ class ExportedAsset(models.Model):
# Relations
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)
# Content related fields
export_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.py
index 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, User
from posthog.models.file_system.file_system import FileSystem, escape_path, join_path, split_path
from posthog.models.file_system.unfiled_file_saver import save_unfiled_files
@@ -8,6 +8,7 @@ from products.dashboards.backend.models.dashboard import Dashboard
from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.notebooks.backend.models import Notebook
+from products.product_analytics.backend.models.insight import Insight
class 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.py
index 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, User
from products.dashboards.backend.models.dashboard import Dashboard
from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.notebooks.backend.models import Notebook
+from products.product_analytics.backend.models.insight import Insight
class 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.py
index 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_time
from django.test import TestCase
-from posthog.models import FileSystem, FileSystemViewLog, Insight, Organization, Team, User
+from posthog.models import FileSystem, FileSystemViewLog, Organization, Team, User
from posthog.models.file_system.file_system_view_log import get_recent_file_system_items, log_file_system_view
from products.dashboards.backend.models.dashboard import Dashboard
+from products.product_analytics.backend.models.insight import Insight
class FileSystemWithLastViewed(Protocol):
diff --git a/posthog/models/file_system/unfiled_file_saver.py b/posthog/models/file_system/unfiled_file_saver.py
index 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 Cohort
from posthog.models.file_system.file_system import FileSystem, escape_path, split_path
from posthog.models.file_system.file_system_mixin import FileSystemSyncMixin
from posthog.models.hog_functions.hog_function import HogFunction
-from posthog.models.insight import Insight
from posthog.models.team import Team
from posthog.models.user import User
from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
@@ -20,6 +19,7 @@ from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.links.backend.models import Link
from products.notebooks.backend.models import Notebook
+from products.product_analytics.backend.models.insight import Insight
from products.surveys.backend.models import Survey
MIXIN_MODELS = {
diff --git a/posthog/models/product_intent/product_intent.py b/posthog/models/product_intent/product_intent.py
index 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, ProductKey
from posthog.exceptions_capture import capture_exception
from posthog.models.hog_flow.hog_flow import HogFlow
-from posthog.models.insight import Insight
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.models.utils import RootTeamMixin, UUIDTModel
@@ -27,6 +26,7 @@ from products.error_tracking.backend.models import ErrorTrackingIssue
from products.event_definitions.backend.models.event_definition import EventDefinition
from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.product_analytics.backend.models.insight import Insight
from products.product_tours.backend.models import ProductTour
from products.surveys.backend.models import Survey
diff --git a/posthog/models/resource_transfer/test/test_inter_project_transferer.py b/posthog/models/resource_transfer/test/test_inter_project_transferer.py
index 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 BaseTest
from parameterized import parameterized
-from posthog.models import Insight, Project, Team
+from posthog.models import Project, Team
from 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, ResourceTransfe
from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile, Text
+from products.product_analytics.backend.models.insight import Insight
from products.surveys.backend.models import Survey
diff --git a/posthog/models/resource_transfer/visitors/insight.py b/posthog/models/resource_transfer/visitors/insight.py
index 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(
):
@classmethod
def get_model(cls) -> type[models.Model]:
- from posthog.models import Insight
+ from products.product_analytics.backend.models.insight import Insight
return Insight
diff --git a/posthog/models/sharing_configuration.py b/posthog/models/sharing_configuration.py
index 43fb8627c3d8..3c0dce6e8da5 100644
--- a/posthog/models/sharing_configuration.py
+++ b/posthog/models/sharing_configuration.py
@@ -12,7 +12,8 @@ from django.utils import timezone
import structlog
from posthog.jwt import PosthogJwtAudience, encode_jwt
-from posthog.models.insight import Insight
+
+from products.product_analytics.backend.models.insight import Insight
logger = structlog.get_logger(__name__)
@@ -25,7 +26,7 @@ class SharingConfiguration(models.Model):
# Relations
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)
recording = models.ForeignKey(
"SessionRecording",
related_name="sharing_configurations",
diff --git a/posthog/models/subscription.py b/posthog/models/subscription.py
index 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.py
index 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.py
index 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 Cohort
from posthog.models.file_system.file_system_view_log import FileSystemViewLog
- from posthog.models.insight_caching_state import InsightCachingState
from products.data_modeling.backend.models import Edge, Node
from products.early_access_features.backend.models import EarlyAccessFeature
from products.error_tracking.backend.models import ErrorTrackingIssueFingerprintV2
from 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.py
index 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 ValidationError
from django.db.utils import IntegrityError
from posthog.models.exported_asset import ExportedAsset
-from posthog.models.insight import Insight
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile, Text
+from products.product_analytics.backend.models.insight import Insight
class TestDashboardTileModel(APIBaseTest):
diff --git a/posthog/models/test/test_product_intent.py b/posthog/models/test/test_product_intent.py
index 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, ProductKey
from posthog.models.file_system.user_product_list import UserProductList
from posthog.models.hog_flow.hog_flow import HogFlow
-from posthog.models.insight import Insight
from posthog.models.product_intent.product_intent import (
ProductIntent,
_fetch_product_intents,
@@ -30,6 +29,7 @@ from products.dashboards.backend.models.dashboard import Dashboard
from products.event_definitions.backend.models.event_definition import EventDefinition
from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.product_analytics.backend.models.insight import Insight
from products.surveys.backend.models import Survey
diff --git a/posthog/models/test/test_subscription_model.py b/posthog/models/test/test_subscription_model.py
index 79cbda02b1dd..38396125b9e2 100644
--- a/posthog/models/test/test_subscription_model.py
+++ b/posthog/models/test/test_subscription_model.py
@@ -14,7 +14,6 @@ import jwt
from parameterized import parameterized
from posthog.jwt import PosthogJwtAudience
-from posthog.models.insight import Insight
from 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.py
index 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 BaseTest
from django.core.exceptions import ValidationError
-from posthog.models import Insight, Tag, TaggedItem
+from posthog.models import Tag, TaggedItem
from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.models.insight import Insight
class TestTaggedItem(BaseTest):
diff --git a/posthog/rbac/test/test_user_access_control.py b/posthog/rbac/test/test_user_access_control.py
index 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(BaseUserAccessControlTes
def 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 Insight
insight = 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.py
index 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 impor
from posthog.schema_migrations.upgrade import upgrade
if TYPE_CHECKING:
- from posthog.models.insight import Insight
+ from products.product_analytics.backend.models.insight import Insight
@contextmanager
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 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.py
index 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, Trends
from posthog.api.services.query import ExecutionMode
from posthog.caching.calculate_results import calculate_for_query_based_insight
-from posthog.models import Insight
from posthog.schema_migrations.upgrade_manager import upgrade_query
from posthog.tasks.alerts.detectors import get_detector
from posthog.tasks.alerts.detectors.base import DetectionResult
@@ -22,6 +21,7 @@ from posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, AlertEvaluationResult
from posthog.utils import get_from_dict_or_attr
from products.alerts.backend.models.alert import AlertConfiguration
+from products.product_analytics.backend.models.insight import Insight
# Minimum samples required for each detector type
DETECTOR_MIN_SAMPLES: dict[DetectorType, int] = {
diff --git a/posthog/tasks/alerts/test/test_detector_breakdowns.py b/posthog/tasks/alerts/test/test_detector_breakdowns.py
index 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 Insight
from 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 Insight
def _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.py
index 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 parameterized
from posthog.schema import AlertState
-from posthog.models import Insight
from 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 Insight
NOW = datetime(2026, 5, 4, 12, 0, 0, tzinfo=UTC)
diff --git a/posthog/tasks/alerts/trends.py b/posthog/tasks/alerts/trends.py
index 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_insight
from posthog.caching.fetch_from_cache import InsightResult
from posthog.event_usage import EventSource
from posthog.hogql_queries.insights.utils.breakdowns import has_breakdown_filter
-from posthog.models import Insight
from posthog.tasks.alerts.utils import NON_TIME_SERIES_DISPLAY_TYPES, AlertEvaluationResult
from 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 instead
diff --git a/posthog/tasks/exports/image_exporter.py b/posthog/tasks/exports/image_exporter.py
index 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 ChromeType
from posthog.schema import FunnelLayout, NodeKind
-from posthog.api.insight_variable import map_stale_to_latest
from posthog.caching.calculate_results import calculate_for_query_based_insight
from posthog.event_usage import AnalyticsProps, EventSource
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.query_runner import ExecutionMode
-from posthog.models import InsightVariable
from posthog.models.exported_asset import ExportedAsset, get_public_access_token, save_content
from posthog.schema_migrations.upgrade_manager import upgrade_query
from 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_reach
from posthog.utils import absolute_uri
from 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 InsightVariable
logger = structlog.get_logger(__name__)
diff --git a/posthog/tasks/exports/test/test_image_exporter.py b/posthog/tasks/exports/test/test_image_exporter.py
index 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 resource
from botocore.client import Config
from parameterized import parameterized
-from posthog.api.insight_variable import map_stale_to_latest
from posthog.caching.fetch_from_cache import InsightResult
from posthog.hogql_queries.query_runner import ExecutionMode
-from posthog.models import ExportedAsset, Insight, InsightVariable
+from posthog.models import ExportedAsset
from posthog.settings import (
OBJECT_STORAGE_ACCESS_KEY_ID,
OBJECT_STORAGE_BUCKET,
@@ -24,6 +23,9 @@ from posthog.tasks.exports import image_exporter
from products.dashboards.backend.models.dashboard import Dashboard
from 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 InsightVariable
def make_insight_result(cache_key: str) -> InsightResult:
diff --git a/posthog/temporal/ai/anomaly_investigation/notebook.py b/posthog/temporal/ai/anomaly_investigation/notebook.py
index 282d3e4dea22..3100f7bfdfab 100644
--- a/posthog/temporal/ai/anomaly_investigation/notebook.py
+++ b/posthog/temporal/ai/anomaly_investigation/notebook.py
@@ -3,7 +3,6 @@ import uuid
from dataclasses import dataclass
from typing import Any
-from posthog.models import Insight
from posthog.temporal.ai.anomaly_investigation.report import InvestigationReport
from 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 Insight
VERDICT_LABEL = {
"true_positive": "True positive",
diff --git a/posthog/temporal/product_analytics/upgrade_queries_activities.py b/posthog/temporal/product_analytics/upgrade_queries_activities.py
index 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 connection
from structlog import get_logger
from temporalio import activity
-from posthog.models import Insight
from posthog.schema_migrations import LATEST_VERSIONS
from 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.py
index 3d19f5353784..cbedafaf4ac8 100644
--- a/posthog/temporal/subscriptions/activities.py
+++ b/posthog/temporal/subscriptions/activities.py
@@ -13,7 +13,6 @@ from temporalio.exceptions import ApplicationError
from posthog.exceptions_capture import capture_exception
from posthog.models.exported_asset import ExportedAsset
-from posthog.models.insight import Insight
from posthog.models.subscription import Subscription, SubscriptionDelivery
from posthog.sync import database_sync_to_async
from 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 Insight
from ee.tasks.subscriptions import SLACK_USER_CONFIG_ERRORS, _capture_delivery_failed_event
from ee.tasks.subscriptions.auto_disable import (
diff --git a/posthog/temporal/subscriptions/insight_snapshot.py b/posthog/temporal/subscriptions/insight_snapshot.py
index 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_python
from posthog.api.services.query import ExecutionMode
from posthog.caching.calculate_results import calculate_cache_key, calculate_for_query_based_insight
from posthog.caching.fetch_from_cache import InsightResult, NothingInCacheResult
-from posthog.models import Insight, Team, User
+from posthog.models import Team, User
from posthog.models.subscription import Subscription
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.models.insight import Insight
logger = structlog.get_logger(__name__)
diff --git a/posthog/temporal/subscriptions/llm_change_summary.py b/posthog/temporal/subscriptions/llm_change_summary.py
index 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 Counter
if TYPE_CHECKING:
from posthog.models.team.team import Team
-from posthog.api.insight_suggestions import get_query_specific_instructions
from posthog.exceptions_capture import capture_exception
from posthog.models.llm_prompt import normalize_prompt_to_string
from 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.py
index 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_logger
from posthog.api.annotation_context import build_annotations_block, resolve_snapshot_date_range
from posthog.constants import SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE_FEATURE_FLAG_KEY
-from posthog.models import Insight
from posthog.models.exported_asset import ExportedAsset
from posthog.models.subscription import Subscription, SubscriptionDelivery
from 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_summary
from posthog.temporal.subscriptions.types import SnapshotInsightsInputs, SnapshotInsightsResult
+from products.product_analytics.backend.models.insight import Insight
+
from ee.models import CoreMemory
LOGGER = get_logger(__name__)
diff --git a/posthog/temporal/subscriptions/test_snapshot_ai_consent.py b/posthog/temporal/subscriptions/test_snapshot_ai_consent.py
index 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 structlog
from asgiref.sync import sync_to_async
from temporalio.testing import ActivityEnvironment
-from posthog.models.insight import Insight
from posthog.models.subscription import Subscription, SubscriptionDelivery
from posthog.temporal.subscriptions.snapshot_activities import snapshot_subscription_insights
from posthog.temporal.subscriptions.types import SnapshotInsightsInputs
+from products.product_analytics.backend.models.insight import Insight
+
from ee.models import CoreMemory
pytestmark = [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.py
index 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 APIBaseTest
from parameterized import parameterized
from posthog.api.annotation_context import resolve_snapshot_date_range
-from posthog.models import Annotation, Insight
+from posthog.models import Annotation
from 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.py
index 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 pytest
from unittest.mock import patch
from posthog.models.exported_asset import ExportedAsset
-from posthog.models.insight import Insight
from 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_db
diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_notebook.py b/posthog/temporal/tests/ai/test_anomaly_investigation_notebook.py
index 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 Insight
from posthog.temporal.ai.anomaly_investigation.notebook import NotebookRenderContext, build_investigation_notebook
from posthog.temporal.ai.anomaly_investigation.report import InvestigationHypothesis, InvestigationReport
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
+from products.product_analytics.backend.models.insight import Insight
class TestAnomalyInvestigationNotebook(BaseTest):
diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
index 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_async
from posthog.schema import AlertState
-from posthog.models import Insight
from posthog.temporal.ai.anomaly_investigation.report import InvestigationReport
from posthog.temporal.ai.anomaly_investigation.runner import InvestigationRunResult
from 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 Insight
class 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.py
index 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, Worker
from posthog.schema import NodeKind
import posthog.schema_migrations as schema_migrations_module
-from posthog.models.insight import Insight
from posthog.schema_migrations import LATEST_VERSIONS, MIGRATIONS, SchemaMigration, _discover_migrations
from 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.py
index 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 User
from posthog.tasks.alerts.utils import AlertEvaluationResult
from posthog.temporal.alerts.activities import cleanup_alert_checks, evaluate_alert, notify_alert, prepare_alert
from 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 Insight
def _valid_trends_query() -> dict:
diff --git a/posthog/temporal/tests/test_alerts_investigation.py b/posthog/temporal/tests/test_alerts_investigation.py
index 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 parameterized
from posthog.schema import AlertState
-from posthog.models import Insight
from posthog.temporal.alerts.investigation import claim_investigation_slot, should_trigger_investigation
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus
+from products.product_analytics.backend.models.insight import Insight
class TestShouldTriggerInvestigation(BaseTest):
diff --git a/posthog/temporal/tests/test_alerts_workflows.py b/posthog/temporal/tests/test_alerts_workflows.py
index 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 User
from posthog.slo.types import SloArea, SloConfig, SloOperation, SloOutcome
from posthog.tasks.alerts.utils import AlertEvaluationResult
from posthog.temporal.alerts.activities import evaluate_alert, notify_alert, prepare_alert
@@ -32,6 +32,7 @@ from posthog.temporal.alerts.workflows import CheckAlertWorkflow
from posthog.temporal.common.slo_interceptor import SloInterceptor
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
+from products.product_analytics.backend.models.insight import Insight
CHECK_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.py
index 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 QueryError
from posthog.errors import CHQueryErrorS3Error
from posthog.models.exported_asset import ExportedAsset
-from posthog.models.insight import Insight
from posthog.models.instance_setting import set_instance_setting
from posthog.models.integration import Integration
from posthog.models.subscription import Subscription, SubscriptionDelivery
@@ -59,6 +58,7 @@ from posthog.temporal.subscriptions.workflows import (
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.models.insight import Insight
from ee.tasks.subscriptions.slack_subscriptions import SlackDeliveryResult
from ee.tasks.test.subscriptions.subscriptions_test_factory import create_subscription
diff --git a/posthog/test/activity_logging/test_annotation_activity_logging.py b/posthog/test/activity_logging/test_annotation_activity_logging.py
index 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, cast
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.annotation import Annotation
-from posthog.models.insight import Insight
from posthog.test.activity_log_utils import ActivityLogTestHelper
from products.dashboards.backend.models.dashboard import Dashboard
+from products.product_analytics.backend.models.insight import Insight
class TestAnnotationActivityLogging(ActivityLogTestHelper):
diff --git a/posthog/test/base.py b/posthog/test/base.py
index 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_cache
from posthog.helpers.two_factor_session import email_mfa_token_generator
from posthog.hogql_queries.ai.ai_table_resolver import AI_EVENT_NAMES as _AI_EVENT_TYPES
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
-from posthog.models import Insight, Organization, Team, User
+from posthog.models import Organization, Team, User
from posthog.models.ai_events.sql import TRUNCATE_AI_EVENTS_TABLE_SQL
from 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.py
index 43bdc389c9f5..64fea8a505da 100644
--- a/posthog/test/playwright_setup_functions.py
+++ b/posthog/test/playwright_setup_functions.py
@@ -13,13 +13,14 @@ from pydantic import BaseModel
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.constants import AvailableFeature
from 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, User
from posthog.models.utils import hash_key_value, mask_key_value
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from 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 InsightVariable
class PlaywrightSetupVariableType(StrEnum):
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index 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, AuthMissingParamete
from posthog.api.test.test_organization import create_organization
from posthog.api.test.test_team import create_team
from posthog.middleware import per_request_logging_context_middleware
-from posthog.models import Cohort, Insight
+from posthog.models import Cohort
from posthog.models.organization import Organization
from posthog.models.team import Team
from posthog.models.user import User
@@ -35,6 +35,7 @@ from posthog.settings import SITE_URL
from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.product_analytics.backend.models.insight import Insight
def _social_auth_backend() -> BaseAuth:
diff --git a/posthog/test/test_user_permissions.py b/posthog/test/test_user_permissions.py
index 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 BaseTest
from posthog.constants import AvailableFeature
-from posthog.models.insight import Insight
from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -9,6 +8,7 @@ from posthog.user_permissions import UserPermissions
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.models.insight import Insight
from ee.models.dashboard_privilege import DashboardPrivilege
diff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.py
index 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.py
index d7197d734e72..48ae81823f3c 100644
--- a/posthog/user_permissions.py
+++ b/posthog/user_permissions.py
@@ -3,10 +3,11 @@ from typing import Any, Optional, cast
from uuid import UUID
from posthog.constants import AvailableFeature
-from posthog.models import Insight, Organization, OrganizationMembership, Team, User
+from posthog.models import Organization, OrganizationMembership, Team, User
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.models.insight import Insight
class UserPermissions:
diff --git a/posthog/utils.py b/posthog/utils.py
index 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, User
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+ from products.product_analytics.backend.models.insight_variable import InsightVariable
DATERANGE_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_latest
from 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 None
diff --git a/products/actions/backend/api/action.py b/products/actions/backend/api/action.py
index 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 UserBasicSerializer
from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin
from posthog.constants import TREND_FILTER_TYPE_EVENTS
from posthog.event_usage import report_user_action
-from posthog.models import Cohort, Insight, Team
+from posthog.models import Cohort, Team
from posthog.models.activity_logging.activity_log import Detail, changes_between, log_activity
from posthog.models.event.event import Selector
from posthog.models.hog_functions.hog_function import HogFunction
@@ -41,6 +41,7 @@ from posthog.resource_limits import LimitKey, check_count_limit
from products.actions.backend.models.action import ACTION_STEP_MATCHING_OPTIONS, Action
from 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.py
index 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, patch
from rest_framework import status
-from posthog.models import Cohort, Insight, Tag, User
+from posthog.models import Cohort, Tag, User
from posthog.models.hog_functions.hog_function import HogFunction
from products.actions.backend.models.action import Action
+from products.product_analytics.backend.models.insight import Insight
class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.py
index 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 InsightBasicSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.api.shared import UserBasicSerializer
from posthog.event_usage import get_request_analytics_properties
-from posthog.models import Insight, User
+from posthog.models import User
from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activity
from posthog.models.signals import model_activity_signal, mutable_receiver
from posthog.resource_limits import LimitKey, check_count_limit
@@ -39,6 +38,8 @@ from posthog.utils import relative_date_parse
from products.alerts.backend.api.alert_schedule_restriction import AlertScheduleRestriction
from 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 Insight
def _validate_every_15_minutes_interval(
diff --git a/products/alerts/backend/max_tools.py b/products/alerts/backend/max_tools.py
index 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 EventSource
from posthog.exceptions_capture import capture_exception
-from posthog.models.insight import Insight
from posthog.models.team import Team
from posthog.models.user import User
from posthog.rbac.user_access_control import AccessControlLevel
from posthog.scopes import APIScopeObject
from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Threshold
+from products.product_analytics.backend.models.insight import Insight
from ee.hogai.artifacts.types import ModelArtifactResult
from ee.hogai.tool import MaxTool
diff --git a/products/alerts/backend/migrations/0002_migrate_product_analytics_models.py b/products/alerts/backend/migrations/0002_migrate_product_analytics_models.py
new file mode 100644
index 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.txt
index 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_models
diff --git a/products/alerts/backend/models/alert.py b/products/alerts/backend/models/alert.py
index 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 = 5
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)
subscribed_users = models.ManyToManyField(
diff --git a/products/alerts/backend/test_max_tools.py b/products/alerts/backend/test_max_tools.py
index 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 parameterized
from posthog.schema import AlertCalculationInterval, AlertConditionType, AlertState, InsightThresholdType
from posthog.models import Organization, Team
-from posthog.models.insight import Insight
from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Threshold
+from products.product_analytics.backend.models.insight import Insight
from .max_tools import CreateAlertAction, UpdateAlertAction, UpsertAlertTool
diff --git a/products/customer_analytics/backend/api/test_views.py b/products/customer_analytics/backend/api/test_views.py
index 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 status
from posthog.api.tagged_item import set_tags_on_object
from posthog.constants import AvailableFeature
-from posthog.models import Insight, Tag, TaggedItem
+from posthog.models import Tag, TaggedItem
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.organization import OrganizationMembership
from posthog.models.team import Team
@@ -14,6 +14,7 @@ from posthog.models.user import User
from products.customer_analytics.backend.models import Account, CustomerJourney, CustomerProfileConfig
from products.customer_analytics.backend.models.account import AccountAssignment
+from products.product_analytics.backend.models.insight import Insight
class 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.py
new file mode 100644
index 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.txt
index 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_models
diff --git a/products/customer_analytics/backend/models/customer_journey.py b/products/customer_analytics/backend/models/customer_journey.py
index 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, UUIDModel
class 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.py
index 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 ReturnDict
from posthog.schema import InsightVizNode
from posthog.api.forbid_destroy_model import ForbidDestroyModel
-from posthog.api.insight import DashboardTileBasicSerializer, InsightSerializer, InsightViewSet
-from posthog.api.insight_suggestions import summarize_insight_result
from posthog.api.monitoring import Feature, monitor
from posthog.api.openapi_parameters import make_filters_override_param, make_variables_override_param
from 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 Insight
from posthog.models.activity_logging.activity_log import Detail, changes_between, log_activity
-from posthog.models.insight_variable import InsightVariable
from posthog.models.quick_filter import QuickFilter
from posthog.models.signals import model_activity_signal, mutable_receiver
from posthog.models.tagged_item import TaggedItem
@@ -80,6 +76,14 @@ from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import ButtonTile, DashboardTile, Text
from products.llm_analytics.backend.dashboard_templates import get_llm_analytics_default_template
from 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 InsightVariable
from ee.hogai.utils.aio import async_to_sync
diff --git a/products/dashboards/backend/api/test/test_run_insights.py b/products/dashboards/backend/api/test/test_run_insights.py
index 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 status
from posthog.schema import DateRange, EventsNode, InsightVizNode, TrendsFilter, TrendsQuery
from posthog.api.test.dashboards import DashboardAPI
-from posthog.models import Insight
-from posthog.models.insight_variable import InsightVariable
from posthog.models.organization import Organization
from posthog.models.team import Team
from products.dashboards.backend.models.dashboard import Dashboard
from 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 InsightVariable
def _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.py
new file mode 100644
index 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.txt
index 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_models
diff --git a/products/dashboards/backend/models/dashboard.py b/products/dashboards/backend/models/dashboard.py
index 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.M
default=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.ManyToManyField
quick_filter_ids = models.JSONField(default=list, blank=True, null=True)
# Deprecated in favour of app-wide tagging model. See EnterpriseTaggedItem
diff --git a/products/dashboards/backend/models/dashboard_tile.py b/products/dashboards/backend/models/dashboard_tile.py
index 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):
# Relations
dashboard = 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 None
if 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_hash
self.filters_hash = generate_insight_filters_hash(self.insight, self.dashboard)
diff --git a/products/endpoints/backend/api.py b/products/endpoints/backend/api.py
index 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 InsightVariable
from posthog.schema_migrations.upgrade import upgrade
from 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 InsightVariable
from products.warehouse_sources.backend.models.external_data_schema import sync_frequency_to_sync_frequency_interval
from common.hogvm.python.utils import HogVMException
diff --git a/products/endpoints/backend/openapi.py b/products/endpoints/backend/openapi.py
index 028d63fa8a43..48dd8f898417 100644
--- a/products/endpoints/backend/openapi.py
+++ b/products/endpoints/backend/openapi.py
@@ -2,9 +2,8 @@ from django.conf import settings
from 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 InsightVariable
INSIGHT_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.py
index 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 status
from posthog.schema import EndpointLastExecutionTimesRequest
from posthog.models.activity_logging.activity_log import ActivityLog
-from posthog.models.insight_variable import InsightVariable
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team import Team
from posthog.models.user import User
@@ -20,6 +19,7 @@ from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.endpoints.backend.models import Endpoint
from products.endpoints.backend.tests.conftest import create_endpoint_with_version
+from products.product_analytics.backend.models.insight_variable import InsightVariable
class 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 InsightVariable
InsightVariable.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 None
def test_bucket_overrides_stored_on_version(self):
- from posthog.models.insight_variable import InsightVariable
+ from products.product_analytics.backend.models.insight_variable import InsightVariable
InsightVariable.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.py
index 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 Response
from posthog.schema import EventsNode, TrendsQuery
-from posthog.models.insight_variable import InsightVariable
-
from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
from products.endpoints.backend.api import EndpointViewSet
from products.endpoints.backend.tests.conftest import create_endpoint_with_version
+from products.product_analytics.backend.models.insight_variable import InsightVariable
from products.warehouse_sources.backend.models.table import DataWarehouseTable
diff --git a/products/endpoints/backend/tests/test_openapi_spec.py b/products/endpoints/backend/tests/test_openapi_spec.py
index 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 InsightVariable
variable = 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 InsightVariable
test_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.ambr
index 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.py
index 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 redis
from posthog.api.cohort import get_cohort_actors_for_feature_flag
from posthog.constants import AvailableFeature
from 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, User
from posthog.models.cohort import Cohort
from posthog.models.cohort.cohort import CohortType
from 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 Insight
from products.product_tours.backend.models import ProductTour
from products.surveys.backend.models import Survey
diff --git a/products/notebooks/backend/test/test_sharing.py b/products/notebooks/backend/test/test_sharing.py
index 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 APIBaseTest
from parameterized import parameterized
from rest_framework import status
-from posthog.models import Insight, SharingConfiguration
+from posthog.models import SharingConfiguration
from products.notebooks.backend.models import Notebook
from 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 Insight
def _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__.py
new file mode 100644
index 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.py
similarity index 99%
rename from posthog/api/insight.py
rename to products/product_analytics/backend/api/insight.py
index 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 HogQLTimings
from posthog import schema
from posthog.api.documentation import extend_schema, extend_schema_field, extend_schema_serializer
from 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_latest
from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.monitoring import Feature, monitor
from 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, User
from 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_response
from 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 InsightVariable
from posthog.models.organization import Organization
from posthog.models.team.team import Team
from posthog.models.utils import UUIDT
@@ -133,6 +127,12 @@ from posthog.utils import (
from products.alerts.backend.models.alert import AlertConfiguration
from products.dashboards.backend.models.dashboard import Dashboard
from 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 InsightVariable
from common.hogvm.python.utils import HogVMException
diff --git a/posthog/api/insight_metadata.py b/products/product_analytics/backend/api/insight_metadata.py
similarity index 100%
rename from posthog/api/insight_metadata.py
rename to products/product_analytics/backend/api/insight_metadata.py
diff --git a/posthog/api/insight_serializers.py b/products/product_analytics/backend/api/insight_serializers.py
similarity index 100%
rename from posthog/api/insight_serializers.py
rename to products/product_analytics/backend/api/insight_serializers.py
diff --git a/posthog/api/insight_suggestions.py b/products/product_analytics/backend/api/insight_suggestions.py
similarity index 100%
rename from posthog/api/insight_suggestions.py
rename to products/product_analytics/backend/api/insight_suggestions.py
diff --git a/posthog/api/insight_variable.py b/products/product_analytics/backend/api/insight_variable.py
similarity index 98%
rename from posthog/api/insight_variable.py
rename to products/product_analytics/backend/api/insight_variable.py
index 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 ProductKey
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.auth import SharingAccessTokenAuthentication, SharingPasswordProtectedAuthentication
-from posthog.models.insight_variable import InsightVariable
+
+from products.product_analytics.backend.models.insight_variable import InsightVariable
class InsightVariableSerializer(serializers.ModelSerializer):
diff --git a/products/product_analytics/backend/api/test/__init__.py b/products/product_analytics/backend/api/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/api/test/__snapshots__/test_insight.ambr b/products/product_analytics/backend/api/test/__snapshots__/test_insight.ambr
similarity index 100%
rename from posthog/api/test/__snapshots__/test_insight.ambr
rename to products/product_analytics/backend/api/test/__snapshots__/test_insight.ambr
diff --git a/posthog/api/test/__snapshots__/test_insight_funnels.ambr b/products/product_analytics/backend/api/test/__snapshots__/test_insight_funnels.ambr
similarity index 100%
rename from posthog/api/test/__snapshots__/test_insight_funnels.ambr
rename to products/product_analytics/backend/api/test/__snapshots__/test_insight_funnels.ambr
diff --git a/posthog/api/test/test_insight.py b/products/product_analytics/backend/api/test/test_insight.py
similarity index 99%
rename from posthog/api/test/test_insight.py
rename to products/product_analytics/backend/api/test/test_insight.py
index 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_query
from posthog import settings
-from posthog.api.insight import _last_refresh_for_shared_gate
from posthog.api.test.dashboards import DashboardAPI
from posthog.caching.insight_cache import update_cache
from posthog.caching.insight_caching_state import TargetCacheAge
from posthog.constants import AvailableFeature
from 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, User
from posthog.models.project import Project
from posthog.test.db_context_capturing import capture_db_queries
from products.dashboards.backend.models.dashboard import Dashboard
from 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 InsightVariable
from 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.py
similarity index 100%
rename from posthog/api/test/test_insight_funnels.py
rename to products/product_analytics/backend/api/test/test_insight_funnels.py
diff --git a/posthog/api/test/test_insight_metadata.py b/products/product_analytics/backend/api/test/test_insight_metadata.py
similarity index 99%
rename from posthog/api/test/test_insight_metadata.py
rename to products/product_analytics/backend/api/test/test_insight_metadata.py
index 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 patch
from parameterized import parameterized
from 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.py
similarity index 99%
rename from posthog/api/test/test_insight_query.py
rename to products/product_analytics/backend/api/test/test_insight_query.py
index 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 parameterized
from rest_framework import status
from posthog.api.test.dashboards import DashboardAPI
-from posthog.models.insight import Insight
+
+from products.product_analytics.backend.models.insight import Insight
from ee.api.test.base import LicensedTestMixin
diff --git a/posthog/api/test/test_insight_variable.py b/products/product_analytics/backend/api/test/test_insight_variable.py
similarity index 97%
rename from posthog/api/test/test_insight_variable.py
rename to products/product_analytics/backend/api/test/test_insight_variable.py
index 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, patch
from parameterized import parameterized
from rest_framework.exceptions import PermissionDenied
-from posthog.api.insight_variable import InsightVariableViewSet, map_stale_to_latest
from 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 InsightVariable
class 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.py
new file mode 100644
index 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__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/product_analytics/backend/migrations/max_migration.txt b/products/product_analytics/backend/migrations/max_migration.txt
new file mode 100644
index 000000000000..f8937f2a44c5
--- /dev/null
+++ b/products/product_analytics/backend/migrations/max_migration.txt
@@ -0,0 +1 @@
+0001_migrate_product_analytics_models
diff --git a/products/product_analytics/backend/models/__init__.py b/products/product_analytics/backend/models/__init__.py
new file mode 100644
index 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.py
similarity index 95%
rename from posthog/models/insight.py
rename to products/product_analytics/backend/models/insight.py
index 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_filter
from posthog.models.utils import RootTeamManager, RootTeamMixin, sane_repr
from 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 templates
is_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_query
if (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.py
similarity index 93%
rename from posthog/models/insight_caching_state.py
rename to products/product_analytics/backend/models/insight_caching_state.py
index 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 models
from django.db.models.signals import post_save
-from posthog.models.insight import Insight
from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.signals import mutable_receiver
-from posthog.models.team import Team
from posthog.models.utils import UniqueConstraintByExpression, UUIDTModel
from posthog.tasks.tasks import sync_insight_caching_state
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.models.insight import Insight
class 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.py
similarity index 85%
rename from posthog/models/insight_variable.py
rename to products/product_analytics/backend/models/insight_variable.py
index 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, UpdatedMetaF
LIST = "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, UpdatedMetaF
values = 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__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/models/test/test_insight_caching_state.py b/products/product_analytics/backend/models/test/test_insight_caching_state.py
similarity index 95%
rename from posthog/models/test/test_insight_caching_state.py
rename to products/product_analytics/backend/models/test/test_insight_caching_state.py
index 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 BaseTest
from django.utils.timezone import now
-from posthog.models import Insight, InsightCachingState, SharingConfiguration
+from posthog.models import SharingConfiguration
from posthog.models.signals import mute_selected_signals
from products.dashboards.backend.models.dashboard import Dashboard
from 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 InsightCachingState
filters = {
"events": [{"id": "$pageview"}],
diff --git a/posthog/models/test/test_insight_model.py b/products/product_analytics/backend/models/test/test_insight_model.py
similarity index 98%
rename from posthog/models/test/test_insight_model.py
rename to products/product_analytics/backend/models/test/test_insight_model.py
index 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 IntegrityError
from parameterized import parameterized
-from posthog.models import Insight, Team
-from posthog.models.insight import generate_insight_filters_hash
+from posthog.models import Team
from products.dashboards.backend.models.dashboard import Dashboard
+from products.product_analytics.backend.models.insight import Insight, generate_insight_filters_hash
class TestInsightModel(BaseTest):
diff --git a/products/product_analytics/backend/test/__init__.py b/products/product_analytics/backend/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/test/activity_logging/test_insight_activity_logging.py b/products/product_analytics/backend/test/test_insight_activity_logging.py
similarity index 98%
rename from posthog/test/activity_logging/test_insight_activity_logging.py
rename to products/product_analytics/backend/test/test_insight_activity_logging.py
index 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 BaseTest
from dateutil import parser
-from posthog.models import Insight, Tag
+from posthog.models import Tag
from posthog.models.activity_logging.activity_log import Change, changes_between
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.models.insight import Insight
class TestChangesBetweenInsights(BaseTest):
diff --git a/products/product_analytics/mcp/tools.yaml b/products/product_analytics/mcp/tools.yaml
index 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: false
insights-activity-retrieve:
operation: insights_activity_retrieve
enabled: true
diff --git a/products/ruff.toml b/products/ruff.toml
index 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.py
index 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 urlparse
import structlog
-from posthog.models import Insight
from posthog.models.integration import Integration, SlackIntegration
from posthog.rbac.user_access_control import UserAccessControl, access_level_satisfied_for_resource
from products.dashboards.backend.models.dashboard import Dashboard
+from products.product_analytics.backend.models.insight import Insight
logger = 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.py
index 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 pytest
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
-from posthog.models import Insight
from posthog.models.integration import Integration
from products.dashboards.backend.models.dashboard import Dashboard
+from products.product_analytics.backend.models.insight import Insight
from 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.py
index 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 Insight
from posthog.models.activity_logging.activity_log import Change, Detail, changes_between, load_activity, log_activity
from posthog.models.activity_logging.activity_page import activity_page_response
from 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 Insight
from products.surveys.backend.models import MAX_ITERATION_COUNT, Survey, SurveyResponseArchive, ensure_question_ids
from products.surveys.backend.summarization import fetch_responses, format_as_markdown, summarize_responses
from products.surveys.backend.translation import generate_survey_translation
diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.py
index 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 status
from posthog.api.test.test_personal_api_keys import PersonalAPIKeysBaseTest
from posthog.constants import AvailableFeature
-from posthog.models import Insight, Person, Team
+from posthog.models import Person, Team
from posthog.models.cohort.cohort import Cohort
from posthog.models.organization import Organization, OrganizationMembership
from products.actions.backend.models.action import Action
from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.product_analytics.backend.models.insight import Insight
from products.product_tours.backend.models import ProductTour
from products.surveys.backend.api.survey import nh3_clean_with_allow_list
from products.surveys.backend.models import MAX_ITERATION_COUNT, Survey, SurveyResponseArchive
diff --git a/products/surveys/backend/migrations/0005_migrate_product_analytics_models.py b/products/surveys/backend/migrations/0005_migrate_product_analytics_models.py
new file mode 100644
index 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.txt
index 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_models
diff --git a/products/surveys/backend/models.py b/products/surveys/backend/models.py
index 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.py
index 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_async
from langchain_core.runnables import RunnableConfig
from 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 Insight
from products.surveys.backend.models import Survey
from .max_tools import CreateSurveyTool, EditSurveyTool, SimpleSurveyQuestion, SurveyAnalysisTool
diff --git a/tach.toml b/tach.toml
index 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.*",