:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(devex): move exports, annotations, batch_exports models to product apps (#60228)
Julian Bezb2634c199f7a
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.ymlindex b7a4afec10f5..ac6973fc9ef2 100644--- a/.github/workflows/container-images-cd.yml+++ b/.github/workflows/container-images-cd.yml@@ -245,7 +245,7 @@ jobs:- name: Check for changes that affect batch exports temporal workerid: check_changes_batch_exports_temporal_workerrun: |- if git diff --name-only HEAD^ HEAD | grep -qE '^posthog/temporal/common|^products/batch_exports/backend/temporal|^posthog/batch_exports/|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; then+ if git diff --name-only HEAD^ HEAD | grep -qE '^posthog/temporal/common|^products/batch_exports/backend/|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; thenecho "changed=true" >> $GITHUB_OUTPUTelseecho "changed=false" >> $GITHUB_OUTPUT@@ -356,7 +356,7 @@ jobs:- name: Check for changes that affect general purpose temporal workerid: check_changes_general_purpose_temporal_workerrun: |- if git diff --name-only HEAD^ HEAD | grep -qE '^posthog/temporal/subscriptions|^posthog/temporal/common|^posthog/temporal/session_recordings|^posthog/temporal/proxy_service|^posthog/temporal/(ai_observability|llm_analytics)|^posthog/temporal/product_analytics|^posthog/temporal/delete_persons|^posthog/temporal/ingestion_acceptance_test|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; then+ if git diff --name-only HEAD^ HEAD | grep -qE '^products/exports/backend/temporal/subscriptions|^posthog/temporal/common|^posthog/temporal/session_recordings|^posthog/temporal/proxy_service|^posthog/temporal/llm_analytics|^posthog/temporal/product_analytics|^posthog/temporal/delete_persons|^posthog/temporal/ingestion_acceptance_test|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; thenecho "changed=true" >> $GITHUB_OUTPUTelseecho "changed=false" >> $GITHUB_OUTPUT@@ -435,7 +435,7 @@ jobs:id: check_python_changes_analytics_platform_temporal_workerrun: |CHANGED_FILES=$(git diff --name-only HEAD^ HEAD | tr '\n' ' ')- SUBS_RESULT=$(uv run bin/find_python_dependencies.py posthog.temporal.subscriptions --check-changes "$CHANGED_FILES" | jq -r '.affected') || SUBS_RESULT="true"+ SUBS_RESULT=$(uv run bin/find_python_dependencies.py products.exports.backend.temporal.subscriptions --check-changes "$CHANGED_FILES" | jq -r '.affected') || SUBS_RESULT="true"ALERTS_RESULT=$(uv run bin/find_python_dependencies.py posthog.temporal.alerts --check-changes "$CHANGED_FILES" | jq -r '.affected') || ALERTS_RESULT="true"EXPORTS_RESULT=$(uv run bin/find_python_dependencies.py posthog.temporal.exports --check-changes "$CHANGED_FILES" | jq -r '.affected') || EXPORTS_RESULT="true"if [ "$SUBS_RESULT" = "true" ] || [ "$ALERTS_RESULT" = "true" ] || [ "$EXPORTS_RESULT" = "true" ]; thendiff --git a/bin/find_python_dependencies.py b/bin/find_python_dependencies.pyindex aebba23d38b5..739d24ccd3cf 100644--- a/bin/find_python_dependencies.py+++ b/bin/find_python_dependencies.py@@ -13,11 +13,11 @@ dependencies (modules that the entrypoint imports, directly or transitively).This is useful for determining which files need to trigger a rebuild of a worker.Usage:- python bin/find_python_dependencies.py posthog.temporal.subscriptions+ python bin/find_python_dependencies.py products.exports.backend.temporal.subscriptions# Output: {"dependencies": ["posthog/utils.py", ...]}# Check if any changed files affect a worker- python bin/find_python_dependencies.py posthog.temporal.subscriptions --check-changes "posthog/utils.py posthog/unrelated_file.py"+ python bin/find_python_dependencies.py products.exports.backend.temporal.subscriptions --check-changes "posthog/utils.py posthog/unrelated_file.py"# Output: {"affected": true, "matching_files": ["posthog/utils.py"]}"""@@ -99,7 +99,7 @@ def main():)parser.add_argument("entrypoint",- help="Module path to analyze (e.g., posthog.temporal.subscriptions)",+ help="Module path to analyze (e.g., products.exports.backend.temporal.subscriptions)",)parser.add_argument("--check-changes",@@ -112,7 +112,7 @@ def main():# Validate entrypoint formatif "/" in args.entrypoint or args.entrypoint.endswith(".py"):sys.stderr.write(- f"Error: Entrypoint should be a module path (e.g., 'posthog.temporal.subscriptions'), "+ f"Error: Entrypoint should be a module path (e.g., 'products.exports.backend.temporal.subscriptions'), "f"not a file path ('{args.entrypoint}')\n")sys.exit(1)diff --git a/bin/test/test_find_python_dependencies.py b/bin/test/test_find_python_dependencies.pyindex 74039c9b2b57..f4afa96d0a6a 100644--- a/bin/test/test_find_python_dependencies.py+++ b/bin/test/test_find_python_dependencies.py@@ -27,7 +27,11 @@ class TestFindPythonDependencies(unittest.TestCase):@parameterized.expand([("simple_module", "posthog.utils", "posthog/utils.py"),- ("package_module", "posthog.temporal.subscriptions", "posthog/temporal/subscriptions/__init__.py"),+ (+ "package_module",+ "products.exports.backend.temporal.subscriptions",+ "products/exports/backend/temporal/subscriptions/__init__.py",+ ),("nested_module", "posthog.hogql_queries.query_runner", "posthog/hogql_queries/query_runner.py"),("nonexistent_module", "posthog.nonexistent.module", None),("ee_module", "ee.tasks.subscriptions.subscription_utils", "ee/tasks/subscriptions/subscription_utils.py"),@@ -37,7 +41,7 @@ class TestFindPythonDependencies(unittest.TestCase):self.assertEqual(module_to_file(module), expected_file)def test_returns_only_python_file_paths(self):- files = find_all_dependency_files(self.graph, "posthog.temporal.subscriptions")+ files = find_all_dependency_files(self.graph, "products.exports.backend.temporal.subscriptions")self.assertIsInstance(files, set)for f in files:self.assertTrue(f.endswith(".py"), f"Expected .py file, got {f}")@@ -54,7 +58,7 @@ class TestFindPythonDependencies(unittest.TestCase):])def test_file_inclusion(self, _name, file_path, should_be_included):- files = find_all_dependency_files(self.graph, "posthog.temporal.subscriptions")+ files = find_all_dependency_files(self.graph, "products.exports.backend.temporal.subscriptions")if should_be_included:self.assertIn(file_path, files)else:@@ -63,15 +67,15 @@ class TestFindPythonDependencies(unittest.TestCase):@parameterized.expand([# Direct dependencies - should trigger rebuild- ("entrypoint_init", "posthog/temporal/subscriptions/__init__.py", True),- ("entrypoint_activities", "posthog/temporal/subscriptions/activities.py", True),- ("entrypoint_workflows", "posthog/temporal/subscriptions/workflows.py", True),+ ("entrypoint_init", "products/exports/backend/temporal/subscriptions/__init__.py", True),+ ("entrypoint_activities", "products/exports/backend/temporal/subscriptions/activities.py", True),+ ("entrypoint_workflows", "products/exports/backend/temporal/subscriptions/workflows.py", True),# Transitive dependencies (the bug that caused issue https://github.com/PostHog/posthog/pull/42307) - should trigger rebuild("transitive_utils", "posthog/utils.py", True),("transitive_query_runner", "posthog/hogql_queries/query_runner.py", True),# Export-related files - should trigger rebuild("exporter", "posthog/tasks/exporter.py", True),- ("image_exporter", "posthog/tasks/exports/image_exporter.py", True),+ ("image_exporter", "products/exports/backend/tasks/image_exporter.py", True),("subscription_utils", "ee/tasks/subscriptions/subscription_utils.py", True),# Files that should NOT affect the worker("api_endpoint", "ee/api/subscription.py", False),@@ -84,7 +88,7 @@ class TestFindPythonDependencies(unittest.TestCase):def test_change_detection(self, _name, changed_file, should_be_affected):affected, _matching = check_if_changes_affect_entrypoint(self.graph,- "posthog.temporal.subscriptions",+ "products.exports.backend.temporal.subscriptions",[changed_file],)self.assertEqual(@@ -97,7 +101,7 @@ class TestFindPythonDependencies(unittest.TestCase):def test_multiple_changes_one_affects(self):affected, matching = check_if_changes_affect_entrypoint(self.graph,- "posthog.temporal.subscriptions",+ "products.exports.backend.temporal.subscriptions",["frontend/test.tsx", "posthog/utils.py", "README.md"],)self.assertTrue(affected)@@ -106,7 +110,7 @@ class TestFindPythonDependencies(unittest.TestCase):def test_multiple_changes_none_affect(self):affected, matching = check_if_changes_affect_entrypoint(self.graph,- "posthog.temporal.subscriptions",+ "products.exports.backend.temporal.subscriptions",["frontend/test.tsx", "README.md", "rust/main.rs"],)self.assertFalse(affected)@@ -115,7 +119,7 @@ class TestFindPythonDependencies(unittest.TestCase):def test_returns_sorted_matching_files(self):_affected, matching = check_if_changes_affect_entrypoint(self.graph,- "posthog.temporal.subscriptions",+ "products.exports.backend.temporal.subscriptions",["posthog/utils.py", "posthog/hogql_queries/query_runner.py", "ee/models/license.py"],)self.assertGreater(len(matching), 1, "Need multiple matches to verify sorting")@@ -124,17 +128,17 @@ class TestFindPythonDependencies(unittest.TestCase):@parameterized.expand([# Entrypoint - should trigger rebuild- ("entrypoint_init", "posthog/temporal/subscriptions/__init__.py", True),- ("entrypoint_activities", "posthog/temporal/subscriptions/activities.py", True),- ("entrypoint_workflows", "posthog/temporal/subscriptions/workflows.py", True),+ ("entrypoint_init", "products/exports/backend/temporal/subscriptions/__init__.py", True),+ ("entrypoint_activities", "products/exports/backend/temporal/subscriptions/activities.py", True),+ ("entrypoint_workflows", "products/exports/backend/temporal/subscriptions/workflows.py", True),# posthog/temporal/common - should trigger rebuild("temporal_common_base", "posthog/temporal/common/base.py", True),("temporal_common_client", "posthog/temporal/common/client.py", True),# posthog/tasks/exporter.py - should trigger rebuild("exporter", "posthog/tasks/exporter.py", True),- # posthog/tasks/exports/ - should trigger rebuild- ("image_exporter", "posthog/tasks/exports/image_exporter.py", True),- ("csv_exporter", "posthog/tasks/exports/csv_exporter.py", True),+ # products/exports/backend/tasks/ - should trigger rebuild+ ("image_exporter", "products/exports/backend/tasks/image_exporter.py", True),+ ("csv_exporter", "products/exports/backend/tasks/csv_exporter.py", True),# ee/tasks/subscriptions/ - should trigger rebuild("subscription_utils", "ee/tasks/subscriptions/subscription_utils.py", True),("email_subscriptions", "ee/tasks/subscriptions/email_subscriptions.py", True),@@ -151,7 +155,7 @@ class TestFindPythonDependencies(unittest.TestCase):def test_analytics_platform_worker_file_triggers_rebuild(self, _name, changed_file, should_trigger):affected, _ = check_if_changes_affect_entrypoint(self.graph,- "posthog.temporal.subscriptions",+ "products.exports.backend.temporal.subscriptions",[changed_file],)if should_trigger:diff --git a/ee/api/subscription.py b/ee/api/subscription.pyindex 00574465bcb8..d3e377bba93d 100644--- a/ee/api/subscription.py+++ b/ee/api/subscription.py@@ -31,16 +31,19 @@ from posthog.event_usage import groupsfrom posthog.exceptions import QuotaLimitExceededfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.integration import Integration-from posthog.models.subscription import Subscription, SubscriptionDelivery, unsubscribe_using_tokenfrom posthog.rate_limit import SubscriptionTestDeliveryThrottlefrom posthog.resource_limits import LimitKey, check_count_limit, get_organization_limitfrom posthog.security.url_validation import is_url_allowedfrom posthog.slo.context import SloSpec, slo_operationfrom posthog.slo.types import SloArea, SloOperationfrom posthog.temporal.common.client import sync_connect-from posthog.temporal.subscriptions.types import ProcessSubscriptionWorkflowInputs, SubscriptionTriggerTypefrom posthog.utils import str_to_bool+from products.exports.backend.models.subscription import Subscription, SubscriptionDelivery, unsubscribe_using_token+from products.exports.backend.temporal.subscriptions.types import (+ ProcessSubscriptionWorkflowInputs,+ SubscriptionTriggerType,+)from products.product_analytics.backend.models.insight import Insightfrom ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limiteddiff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.pyindex 637f602b5d34..b4a9df3516bb 100644--- a/ee/api/test/test_subscription.py+++ b/ee/api/test/test_subscription.py@@ -16,11 +16,18 @@ from posthog.models import Teamfrom posthog.models.filters.filter import Filterfrom posthog.models.integration import Integrationfrom posthog.models.personal_api_key import PersonalAPIKey-from posthog.models.subscription import SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER, Subscription, SubscriptionDeliveryfrom posthog.models.utils import generate_random_token_personal, hash_key_value-from posthog.temporal.subscriptions.types import ProcessSubscriptionWorkflowInputs, SubscriptionTriggerTypefrom products.dashboards.backend.models.dashboard import Dashboard+from products.exports.backend.models.subscription import (+ SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER,+ Subscription,+ SubscriptionDelivery,+)+from products.exports.backend.temporal.subscriptions.types import (+ ProcessSubscriptionWorkflowInputs,+ SubscriptionTriggerType,+)from products.product_analytics.backend.models.insight import Insightfrom ee.api.test.base import APILicensedTestdiff --git a/ee/hogai/videos/session_moments.py b/ee/hogai/videos/session_moments.pyindex da0faae9aa87..7dfaef6b9396 100644--- a/ee/hogai/videos/session_moments.py+++ b/ee/hogai/videos/session_moments.py@@ -13,7 +13,6 @@ from google.genai.errors import APIErrorfrom google.genai.types import Blob, Content, Part, VideoMetadatafrom temporalio.common import RetryPolicy, SearchAttributePair, TypedSearchAttributes, WorkflowIDReusePolicy-from posthog.models.exported_asset import ExportedAssetfrom posthog.models.user import Userfrom posthog.settings.temporal import TEMPORAL_WORKFLOW_MAX_ATTEMPTSfrom posthog.storage import object_storage@@ -22,6 +21,8 @@ from posthog.temporal.common.client import async_connectfrom posthog.temporal.common.search_attributes import POSTHOG_SESSION_RECORDING_ID_KEY, POSTHOG_TEAM_ID_KEYfrom posthog.temporal.session_replay.rasterize_recording.types import RasterizeRecordingInputs+from products.exports.backend.models.exported_asset import ExportedAsset+from ee.hogai.session_summaries.constants import (DEFAULT_VIDEO_UNDERSTANDING_MODEL,MOMENT_VIDEO_EXPORT_FORMAT,diff --git a/ee/tasks/slack.py b/ee/tasks/slack.pyindex 04219f27683f..bebc565d0315 100644--- a/ee/tasks/slack.py+++ b/ee/tasks/slack.py@@ -6,10 +6,11 @@ from django.conf import settingsimport structlog-from posthog.models.exported_asset import ExportedAssetfrom posthog.models.integration import Integration, SlackIntegrationfrom posthog.models.sharing_configuration import SharingConfiguration+from products.exports.backend.models.exported_asset import ExportedAsset+from ee.tasks.subscriptions.subscription_utils import generate_assetslogger = structlog.get_logger(__name__)diff --git a/ee/tasks/subscriptions/__init__.py b/ee/tasks/subscriptions/__init__.pyindex 83f2d5937f62..9dfa3c82fcca 100644--- a/ee/tasks/subscriptions/__init__.py+++ b/ee/tasks/subscriptions/__init__.py@@ -3,7 +3,7 @@ import posthoganalyticsfrom temporalio import activity, workflowfrom temporalio.common import MetricCounter, MetricMeter-from posthog.models.subscription import Subscription+from products.exports.backend.models.subscription import Subscriptionlogger = structlog.get_logger(__name__)diff --git a/ee/tasks/subscriptions/auto_disable.py b/ee/tasks/subscriptions/auto_disable.pyindex 237a9cb0ae20..de1a6473c2ea 100644--- a/ee/tasks/subscriptions/auto_disable.py+++ b/ee/tasks/subscriptions/auto_disable.py@@ -5,7 +5,8 @@ import structlogfrom posthog.email import EmailMessagefrom posthog.exceptions_capture import capture_exception-from posthog.models.subscription import Subscription++from products.exports.backend.models.subscription import Subscriptionfrom ee.tasks.subscriptions import SUPPORTED_TARGET_TYPESdiff --git a/ee/tasks/subscriptions/email_subscriptions.py b/ee/tasks/subscriptions/email_subscriptions.pyindex d35b06bdb354..e6919e1847cc 100644--- a/ee/tasks/subscriptions/email_subscriptions.py+++ b/ee/tasks/subscriptions/email_subscriptions.py@@ -4,10 +4,11 @@ from typing import Optionalimport structlogfrom posthog.email import EmailMessage-from posthog.models.exported_asset import ExportedAsset-from posthog.models.subscription import Subscription, get_unsubscribe_tokenfrom posthog.utils import absolute_uri+from products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.models.subscription import Subscription, get_unsubscribe_token+from ee.tasks.subscriptions.subscription_utils import ASSET_GENERATION_FAILED_MESSAGE, UTM_TAGS_BASE, _has_asset_failedlogger = structlog.get_logger(__name__)diff --git a/ee/tasks/subscriptions/slack_subscriptions.py b/ee/tasks/subscriptions/slack_subscriptions.pyindex de94ae0235f3..f331b837b101 100644--- a/ee/tasks/subscriptions/slack_subscriptions.py+++ b/ee/tasks/subscriptions/slack_subscriptions.py@@ -8,11 +8,12 @@ import aiohttpimport structlogfrom slack_sdk.errors import SlackApiError-from posthog.models.exported_asset import ExportedAssetfrom posthog.models.integration import Integration, SlackIntegration-from posthog.models.subscription import Subscriptionfrom posthog.utils import absolute_uri+from products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.models.subscription import Subscription+from ee.tasks.subscriptions.subscription_utils import ASSET_GENERATION_FAILED_MESSAGE, UTM_TAGS_BASE, _has_asset_failedlogger = structlog.get_logger(__name__)diff --git a/ee/tasks/subscriptions/subscription_utils.py b/ee/tasks/subscriptions/subscription_utils.pyindex aaede6bdb360..c264640a9713 100644--- a/ee/tasks/subscriptions/subscription_utils.py+++ b/ee/tasks/subscriptions/subscription_utils.py@@ -7,12 +7,12 @@ import structlogfrom celery import chainfrom prometheus_client import Histogram-from posthog.models.exported_asset import ExportedAssetfrom posthog.models.sharing_configuration import SharingConfiguration-from posthog.models.subscription import Subscriptionfrom posthog.tasks import exporterfrom posthog.utils import wait_for_parallel_celery_group+from products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.models.subscription import Subscriptionfrom products.product_analytics.backend.models.insight import Insightlogger = structlog.get_logger(__name__)diff --git a/ee/tasks/subscriptions/test_auto_disable.py b/ee/tasks/subscriptions/test_auto_disable.pyindex fb30e59ed24f..70681967872d 100644--- a/ee/tasks/subscriptions/test_auto_disable.py+++ b/ee/tasks/subscriptions/test_auto_disable.py@@ -5,7 +5,7 @@ from django.utils import timezonefrom parameterized import parameterized-from posthog.models.subscription import Subscription+from products.exports.backend.models.subscription import Subscriptionfrom ee.tasks.subscriptions.auto_disable import (SLACK_DISCONNECTED_DISABLE_REASON,diff --git a/ee/tasks/test/subscriptions/subscriptions_test_factory.py b/ee/tasks/test/subscriptions/subscriptions_test_factory.pyindex 35be52aec307..8d1a4b46a78e 100644--- a/ee/tasks/test/subscriptions/subscriptions_test_factory.py+++ b/ee/tasks/test/subscriptions/subscriptions_test_factory.py@@ -2,7 +2,7 @@ from datetime import datetimefrom typing import Anyfrom zoneinfo import ZoneInfo-from posthog.models.subscription import Subscription+from products.exports.backend.models.subscription import Subscriptiondef create_subscription(**kwargs: Any) -> Subscription:diff --git a/ee/tasks/test/subscriptions/test_email_subscriptions.py b/ee/tasks/test/subscriptions/test_email_subscriptions.pyindex 6401c032c324..af08bca6fc73 100644--- a/ee/tasks/test/subscriptions/test_email_subscriptions.py+++ b/ee/tasks/test/subscriptions/test_email_subscriptions.py@@ -2,12 +2,12 @@ from freezegun import freeze_timefrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch-from posthog.models.exported_asset import ExportedAssetfrom posthog.models.instance_setting import set_instance_setting-from posthog.models.subscription import Subscriptionfrom posthog.tasks.test.utils_email_tests import mock_email_messagesfrom products.dashboards.backend.models.dashboard import Dashboard+from products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.models.subscription import Subscriptionfrom products.product_analytics.backend.models.insight import Insightfrom ee.tasks.subscriptions.email_subscriptions import send_email_subscription_reportdiff --git a/ee/tasks/test/subscriptions/test_slack_subscriptions.py b/ee/tasks/test/subscriptions/test_slack_subscriptions.pyindex d1bf5238eb28..59ad43657e54 100644--- a/ee/tasks/test/subscriptions/test_slack_subscriptions.py+++ b/ee/tasks/test/subscriptions/test_slack_subscriptions.py@@ -9,11 +9,11 @@ from parameterized import parameterizedfrom slack_sdk.errors import SlackApiErrorfrom slack_sdk.web.async_slack_response import AsyncSlackResponse-from posthog.models.exported_asset import ExportedAssetfrom posthog.models.integration import Integration-from posthog.models.subscription import Subscriptionfrom products.dashboards.backend.models.dashboard import Dashboard+from products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.models.subscription import Subscriptionfrom products.product_analytics.backend.models.insight import Insightfrom ee.tasks.subscriptions.slack_subscriptions import (diff --git a/ee/tasks/test/subscriptions/test_subscriptions_utils.py b/ee/tasks/test/subscriptions/test_subscriptions_utils.pyindex 92ddf02b9d69..6a55a4d6d131 100644--- a/ee/tasks/test/subscriptions/test_subscriptions_utils.py+++ b/ee/tasks/test/subscriptions/test_subscriptions_utils.py@@ -2,10 +2,9 @@ import pytestfrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch-from posthog.models.exported_asset import ExportedAsset-from products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.exports.backend.models.exported_asset import ExportedAssetfrom products.product_analytics.backend.models.insight import Insightfrom ee.tasks.subscriptions.subscription_utils import DEFAULT_MAX_ASSET_COUNT, generate_assetsdiff --git a/ee/tasks/test/test_slack.py b/ee/tasks/test/test_slack.pyindex 17f0134eae2c..9bf1849e6c27 100644--- a/ee/tasks/test/test_slack.py+++ b/ee/tasks/test/test_slack.py@@ -3,12 +3,12 @@ from posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patchfrom posthog import settings-from posthog.models.exported_asset import ExportedAssetfrom posthog.models.integration import Integrationfrom posthog.models.sharing_configuration import SharingConfiguration-from posthog.models.subscription import Subscriptionfrom products.dashboards.backend.models.dashboard import Dashboard+from products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.models.subscription import Subscriptionfrom products.product_analytics.backend.models.insight import Insightfrom ee.tasks.slack import handle_slack_eventdiff --git a/frontend/package.json b/frontend/package.jsonindex c20770c5b5c1..11e522605846 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -75,6 +75,8 @@"@posthog/products-actions": "workspace:*","@posthog/products-ai-observability": "workspace:*","@posthog/products-alerts": "workspace:*",+ "@posthog/products-annotations": "workspace:*",+ "@posthog/products-batch-exports": "workspace:*","@posthog/products-business-knowledge": "workspace:*","@posthog/products-cohorts": "workspace:*","@posthog/products-conversations": "workspace:*",@@ -88,6 +90,7 @@"@posthog/products-engineering-analytics": "workspace:*","@posthog/products-error-tracking": "workspace:*","@posthog/products-experiments": "workspace:*",+ "@posthog/products-exports": "workspace:*","@posthog/products-feature-flags": "workspace:*","@posthog/products-games": "workspace:*","@posthog/products-groups": "workspace:*",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1c6b2a325b8a..8afe6a949da0 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -603,6 +603,12 @@ importers:'@posthog/products-alerts':specifier: workspace:*version: link:../products/alerts+ '@posthog/products-annotations':+ specifier: workspace:*+ version: link:../products/annotations+ '@posthog/products-batch-exports':+ specifier: workspace:*+ version: link:../products/batch_exports'@posthog/products-business-knowledge':specifier: workspace:*version: link:../products/business_knowledge@@ -642,6 +648,9 @@ importers:'@posthog/products-experiments':specifier: workspace:*version: link:../products/experiments+ '@posthog/products-exports':+ specifier: workspace:*+ version: link:../products/exports'@posthog/products-feature-flags':specifier: workspace:*version: link:../products/feature_flags@@ -2194,6 +2203,8 @@ importers:products/analytics_platform: {}+ products/annotations: {}+products/batch_exports: {}products/business_knowledge:@@ -2701,6 +2712,8 @@ importers:specifier: 'catalog:'version: 8.6.18(@storybook/[email protected]([email protected]([email protected])))([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])+ products/exports: {}+products/feature_flags:dependencies:'@posthog/icons':diff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.pyindex 11740921d2a6..9f77db5e1f5d 100644--- a/posthog/admin/admins/organization_admin.py+++ b/posthog/admin/admins/organization_admin.py@@ -112,7 +112,7 @@ def get_model_counts_for_organization(organization: Organization) -> list[dict]:# BatchExport requires deleted=False filter to match delete_batch_exports() behaviortry:- from posthog.batch_exports.models import BatchExport+ from products.batch_exports.backend.models.batch_export import BatchExportbatch_export_count = BatchExport.objects.filter(team_id__in=team_ids, deleted=False).count()results.append(@@ -127,7 +127,7 @@ def get_model_counts_for_organization(organization: Organization) -> list[dict]:{"name": "Batch Exports","count": f"Error: {e}",- "model": "posthog.batch_exports.models.BatchExport",+ "model": "products.batch_exports.backend.models.batch_export.BatchExport",})diff --git a/posthog/api/__init__.py b/posthog/api/__init__.pyindex f16b1319f035..930adaf23858 100644--- a/posthog/api/__init__.py+++ b/posthog/api/__init__.py@@ -4,7 +4,6 @@ from rest_framework_extensions.routers import NestedRegistryItem# Preload to work around circular imports in `ee.hogai.{core.agent_modes,chat_agent,tools}`.import posthog.temporal.ai # noqa: F401from posthog.api import data_color_theme, metalytics, my_notifications, project, user_integration, user_push_token-from posthog.api.batch_imports import BatchImportViewSetfrom posthog.api.csp_reporting import CSPReportingViewSetfrom posthog.api.js_snippet import JsSnippetViewSetfrom posthog.api.query_performance_proxy import QueryPerformanceProxyViewSet@@ -12,8 +11,6 @@ from posthog.api.routing import DefaultRouterPlusPlusfrom posthog.api.sdk_doctor import SdkDoctorViewSetfrom posthog.api.wizard import http as wizardfrom posthog.approvals import api as approval_api-from posthog.batch_exports import http as batch_exports-from posthog.batch_exports.api import file_downloadfrom posthog.settings import CLOUD_DEPLOYMENT, DEBUG, EE_AVAILABLE, TESTimport products.logs.backend.api as logs@@ -65,6 +62,12 @@ from products.ai_observability.backend.api import (TraceReviewViewSet,)from products.ai_observability.backend.api.skills import LLMSkillViewSet+from products.annotations.backend.api import annotation+from products.batch_exports.backend.api import (+ batch_export as batch_exports,+ file_download,+)+from products.batch_exports.backend.api.batch_imports import BatchImportViewSetfrom products.cdp.backend.api import hog_function, hog_function_template, plugin, plugin_log_entryfrom products.dashboards.backend.api import dashboard, dashboard_templatesfrom products.data_modeling.backend.api import DAGViewSet, EdgeViewSet, NodeViewSet@@ -100,6 +103,7 @@ from products.error_tracking.backend.api import (ErrorTrackingSymbolSetViewSet,GitProviderFileLinksViewSet,)+from products.exports.backend.api import exportsfrom products.feature_flags.backend.api import feature_flag, flag_value, organization_feature_flag, scheduled_changefrom products.messaging.backend.api.message_categories import MessageCategoryViewSetfrom products.messaging.backend.api.message_preferences import MessagePreferencesViewSet@@ -146,7 +150,6 @@ from ..session_recordings.session_recording_playlist_api import SessionRecordingfrom ..taxonomy import property_definition_apifrom . import (advanced_activity_logs,- annotation,async_migration,authentication,cimd_verification_token,@@ -156,7 +159,6 @@ from . import (debug_ch_queries,event_definition,event_schema,- exports,health_issue,hog,ingestion_warnings,diff --git a/posthog/api/advanced_activity_logs/viewset.py b/posthog/api/advanced_activity_logs/viewset.pyindex f9a56113299d..c6e074472fb1 100644--- a/posthog/api/advanced_activity_logs/viewset.py+++ b/posthog/api/advanced_activity_logs/viewset.py@@ -26,12 +26,13 @@ from posthog.models.activity_logging.activity_log import (ActivityScope,apply_activity_visibility_restrictions,)-from posthog.models.exported_asset import ExportedAssetfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.user import Userfrom posthog.permissions import PremiumFeaturePermissionfrom posthog.tasks import exporter+from products.exports.backend.models.exported_asset import ExportedAsset+from .field_discovery import AdvancedActivityLogFieldDiscoveryfrom .filters import AdvancedActivityLogFilterManagerfrom .utils import get_activity_log_lookback_restrictiondiff --git a/posthog/api/object_media_preview.py b/posthog/api/object_media_preview.pyindex 983f809be781..95264db2c0e6 100644--- a/posthog/api/object_media_preview.py+++ b/posthog/api/object_media_preview.py@@ -63,7 +63,7 @@ class ObjectMediaPreviewSerializer(serializers.ModelSerializer):raise ValidationError("Uploaded media not found or does not belong to this team")if exported_asset_id:- from posthog.models.exported_asset import ExportedAsset+ from products.exports.backend.models.exported_asset import ExportedAssettry:exported_asset = ExportedAsset.objects.get(id=exported_asset_id, team=team)diff --git a/posthog/api/sharing.py b/posthog/api/sharing.pyindex 0ea694b90d9a..7d744428cd1c 100644--- a/posthog/api/sharing.py+++ b/posthog/api/sharing.py@@ -24,7 +24,6 @@ from rest_framework.request import Requestfrom posthog.schema import SharingConfigurationSettingsfrom posthog.api.data_color_theme import DataColorTheme, DataColorThemeSerializer-from posthog.api.exports import ExportedAssetSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.services.query import process_query_dictfrom posthog.api.shared import TeamPublicSerializer@@ -36,13 +35,6 @@ from posthog.hogql_queries.query_runner import ExecutionMode, shared_insights_exfrom posthog.jwt import PosthogJwtAudience, encode_jwtfrom posthog.models import Cohort, SessionRecording, SharePassword, SharingConfiguration, Teamfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activity-from posthog.models.exported_asset import (- EXPORTED_ASSET_PURPOSE_RENDER,- EXPORTED_ASSET_PURPOSE_SUBSCRIPTION_DELIVERY,- ExportedAsset,- asset_for_token,- get_content_response,-)from posthog.models.resource_transfer.visitors.insight import InsightVisitorfrom posthog.models.user import Userfrom posthog.rbac.user_access_control import UserAccessControl, access_level_satisfied_for_resource@@ -54,6 +46,14 @@ from posthog.views import preflight_checkfrom products.dashboards.backend.api.dashboard import DashboardSerializerfrom products.dashboards.backend.models.dashboard import Dashboard+from products.exports.backend.api.exports import ExportedAssetSerializer+from products.exports.backend.models.exported_asset import (+ EXPORTED_ASSET_PURPOSE_RENDER,+ EXPORTED_ASSET_PURPOSE_SUBSCRIPTION_DELIVERY,+ ExportedAsset,+ asset_for_token,+ get_content_response,+)from products.notebooks.backend.api.notebook import NotebookSerializerfrom products.notebooks.backend.models import Notebookfrom products.notebooks.backend.util import extract_inline_query_nodes, filter_notebook_content_for_sharingdiff --git a/posthog/api/test/batch_exports/backfills/test_cancel.py b/posthog/api/test/batch_exports/backfills/test_cancel.pyindex d1732623ddd9..c322997f8869 100644--- a/posthog/api/test/batch_exports/backfills/test_cancel.py+++ b/posthog/api/test/batch_exports/backfills/test_cancel.py@@ -15,7 +15,8 @@ from posthog.api.test.batch_exports.operations import (get_batch_export_backfill_ok,list_batch_export_backfills_ok,)-from posthog.batch_exports.models import BatchExportRun++from products.batch_exports.backend.models.batch_export import BatchExportRunpytestmark = [pytest.mark.usefixtures("temporal_worker", "cleanup"),diff --git a/posthog/api/test/batch_exports/backfills/test_create.py b/posthog/api/test/batch_exports/backfills/test_create.pyindex 729a52c28d22..8d14b973c7c5 100644--- a/posthog/api/test/batch_exports/backfills/test_create.py+++ b/posthog/api/test/batch_exports/backfills/test_create.py@@ -13,10 +13,11 @@ from posthog.api.test.batch_exports.fixtures import create_organizationfrom posthog.api.test.batch_exports.operations import backfill_batch_export, create_batch_export_okfrom posthog.api.test.test_team import create_teamfrom posthog.api.test.test_user import create_user-from posthog.models import BatchExport, BatchExportBackfillfrom posthog.models.person.util import create_personfrom posthog.models.team import Team+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportBackfill+pytestmark = [pytest.mark.django_db,pytest.mark.usefixtures("temporal_worker", "cleanup"),@@ -398,7 +399,7 @@ def test_batch_export_earliest_backfill_rejected_without_feature_flag(batch_export = _create_batch_export_ok(client, team, "persons")batch_export_id = batch_export["id"]- with patch("posthog.batch_exports.http.posthoganalytics.feature_enabled", return_value=False):+ with patch("products.batch_exports.backend.api.batch_export.posthoganalytics.feature_enabled", return_value=False):response = backfill_batch_export(client,team.pk,@@ -528,7 +529,7 @@ def test_batch_export_earliest_backfill_allowed_with_feature_flag(batch_export = _create_batch_export_ok(client, team, "persons")batch_export_id = batch_export["id"]- with patch("posthog.batch_exports.http.posthoganalytics.feature_enabled", return_value=True):+ with patch("products.batch_exports.backend.api.batch_export.posthoganalytics.feature_enabled", return_value=True):response = backfill_batch_export(client,team.pk,diff --git a/posthog/api/test/batch_exports/backfills/test_get.py b/posthog/api/test/batch_exports/backfills/test_get.pyindex fcc310b37eda..323b908ba5a3 100644--- a/posthog/api/test/batch_exports/backfills/test_get.py+++ b/posthog/api/test/batch_exports/backfills/test_get.py@@ -8,7 +8,8 @@ from rest_framework import statusfrom posthog.api.test.batch_exports.fixtures import create_backfill, create_batch_export, create_destination, create_runfrom posthog.api.test.batch_exports.operations import get_batch_export_backfill_ok-from posthog.batch_exports.models import BatchExportBackfill, BatchExportRun++from products.batch_exports.backend.models.batch_export import BatchExportBackfill, BatchExportRunpytestmark = [pytest.mark.django_db,diff --git a/posthog/api/test/batch_exports/backfills/test_list.py b/posthog/api/test/batch_exports/backfills/test_list.pyindex 3e4c7ad8bcc7..972ed71ba3c2 100644--- a/posthog/api/test/batch_exports/backfills/test_list.py+++ b/posthog/api/test/batch_exports/backfills/test_list.py@@ -6,7 +6,8 @@ from django.test.client import Client as HttpClientfrom posthog.api.test.batch_exports.fixtures import create_backfill, create_batch_export, create_destinationfrom posthog.api.test.batch_exports.operations import list_batch_export_backfills_ok-from posthog.batch_exports.models import BatchExportBackfill++from products.batch_exports.backend.models.batch_export import BatchExportBackfillpytestmark = [pytest.mark.django_db]diff --git a/posthog/api/test/batch_exports/backfills/test_read_only.py b/posthog/api/test/batch_exports/backfills/test_read_only.pyindex 58c83c9637ee..a64826859e1e 100644--- a/posthog/api/test/batch_exports/backfills/test_read_only.py+++ b/posthog/api/test/batch_exports/backfills/test_read_only.py@@ -7,7 +7,8 @@ from django.test.client import Client as TestClientfrom rest_framework import statusfrom posthog.api.test.batch_exports.fixtures import create_backfill, create_batch_export, create_destination-from posthog.batch_exports.models import BatchExportBackfill++from products.batch_exports.backend.models.batch_export import BatchExportBackfillpytestmark = [pytest.mark.django_db]diff --git a/posthog/api/test/batch_exports/conftest.py b/posthog/api/test/batch_exports/conftest.pyindex 933a3219e856..a0adf019b181 100644--- a/posthog/api/test/batch_exports/conftest.py+++ b/posthog/api/test/batch_exports/conftest.py@@ -12,9 +12,10 @@ from temporalio.service import RPCErrorfrom posthog.api.test.batch_exports.fixtures import create_organization, create_team, create_userfrom posthog.api.test.batch_exports.operations import start_test_worker-from posthog.batch_exports.models import BATCH_EXPORT_INTERVAL_TO_START_JITTER, BatchExportfrom posthog.temporal.common.client import sync_connect+from products.batch_exports.backend.models.batch_export import BATCH_EXPORT_INTERVAL_TO_START_JITTER, BatchExport+@async_to_syncasync def delete_temporal_schedule(temporal: TemporalClient, schedule_id: str):diff --git a/posthog/api/test/batch_exports/fixtures.py b/posthog/api/test/batch_exports/fixtures.pyindex a0051ea7a87c..d651caa28877 100644--- a/posthog/api/test/batch_exports/fixtures.py+++ b/posthog/api/test/batch_exports/fixtures.py@@ -1,12 +1,11 @@from posthog.api.test.test_organization import create_organization as create_organization_base-from posthog.models import (+from posthog.models import Organization, Team, User++from products.batch_exports.backend.models.batch_export import (BatchExport,BatchExportBackfill,BatchExportDestination,BatchExportRun,- Organization,- Team,- User,)diff --git a/posthog/api/test/batch_exports/test_create.py b/posthog/api/test/batch_exports/test_create.pyindex 47ae95a7d79b..eff971f290a6 100644--- a/posthog/api/test/batch_exports/test_create.py+++ b/posthog/api/test/batch_exports/test_create.py@@ -22,9 +22,10 @@ from posthog.api.test.batch_exports.fixtures import create_organizationfrom posthog.api.test.batch_exports.operations import create_batch_exportfrom posthog.api.test.test_team import create_teamfrom posthog.api.test.test_user import create_user-from posthog.batch_exports.models import BatchExportfrom posthog.temporal.common.codec import EncryptionCodec+from products.batch_exports.backend.models.batch_export import BatchExport+pytestmark = [pytest.mark.django_db,pytest.mark.usefixtures("temporal_worker", "cleanup"),@@ -209,7 +210,7 @@ def test_create_batch_export_with_different_intervals_timezones_and_interval_off# ensure high-frequency-batch-exports feature flag is enabledwith mock.patch(- "posthog.batch_exports.http.posthoganalytics.feature_enabled",+ "products.batch_exports.backend.api.batch_export.posthoganalytics.feature_enabled",return_value=True,):response = create_batch_export(@@ -379,7 +380,7 @@ def test_cannot_create_a_batch_export_with_higher_frequencies_if_not_enabled(client.force_login(user)with mock.patch(- "posthog.batch_exports.http.posthoganalytics.feature_enabled",+ "products.batch_exports.backend.api.batch_export.posthoganalytics.feature_enabled",return_value=False,) as feature_enabled:response = create_batch_export(diff --git a/posthog/api/test/batch_exports/test_create_s3.py b/posthog/api/test/batch_exports/test_create_s3.pyindex f75b272e5f80..ef62fa07da5d 100644--- a/posthog/api/test/batch_exports/test_create_s3.py+++ b/posthog/api/test/batch_exports/test_create_s3.py@@ -8,7 +8,8 @@ from django.test.client import Client as HttpClientfrom rest_framework import statusfrom posthog.api.test.batch_exports.operations import create_batch_export-from posthog.batch_exports.models import S3_FAMILY_TYPES++from products.batch_exports.backend.models.batch_export import S3_FAMILY_TYPESpytestmark = [pytest.mark.django_db,diff --git a/posthog/api/test/batch_exports/test_create_workflows.py b/posthog/api/test/batch_exports/test_create_workflows.pyindex 955611101666..b29fc3338c40 100644--- a/posthog/api/test/batch_exports/test_create_workflows.py+++ b/posthog/api/test/batch_exports/test_create_workflows.py@@ -17,7 +17,7 @@ pytestmark = [@pytest.fixturedef enable_backfilling_workflows(team):with mock.patch(- "posthog.batch_exports.http.posthoganalytics.feature_enabled", return_value=True+ "products.batch_exports.backend.api.batch_export.posthoganalytics.feature_enabled", return_value=True) as feature_enabled:yielddiff --git a/posthog/api/test/batch_exports/test_list.py b/posthog/api/test/batch_exports/test_list.pyindex 0b9b92828269..2e2dd1e7e359 100644--- a/posthog/api/test/batch_exports/test_list.py+++ b/posthog/api/test/batch_exports/test_list.py@@ -134,7 +134,7 @@ def test_list_is_partitioned_by_team(client: HttpClient, organization, team, use@pytest.fixturedef enable_backfilling_workflows(team):with mock.patch(- "posthog.batch_exports.http.posthoganalytics.feature_enabled", return_value=True+ "products.batch_exports.backend.api.batch_export.posthoganalytics.feature_enabled", return_value=True) as feature_enabled:yielddiff --git a/posthog/api/test/batch_exports/test_serializers.py b/posthog/api/test/batch_exports/test_serializers.pyindex de297b238a91..c3052fd3f1f2 100644--- a/posthog/api/test/batch_exports/test_serializers.py+++ b/posthog/api/test/batch_exports/test_serializers.py@@ -12,10 +12,11 @@ from posthog.hogql.parser import parse_selectfrom posthog.hogql.printer import prepare_ast_for_printingfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField-from posthog.batch_exports.http import BatchExportDestinationSerializer, BatchExportSerializerfrom posthog.models import Organization, Teamfrom posthog.models.integration import Integration+from products.batch_exports.backend.api.batch_export import BatchExportDestinationSerializer, BatchExportSerializer+def prepare_query(query: str, team_id: int) -> ast.SelectQuery:"""Parse and resolve a HogQL query string into a prepared AST."""diff --git a/posthog/api/test/batch_exports/test_test.py b/posthog/api/test/batch_exports/test_test.pyindex 9a7b808df271..ddf3fdfe489d 100644--- a/posthog/api/test/batch_exports/test_test.py+++ b/posthog/api/test/batch_exports/test_test.py@@ -13,7 +13,7 @@ import pytest_asynciofrom rest_framework import statusfrom posthog.api.test.batch_exports.operations import create_batch_export_ok-from posthog.models import BatchExportDestination, Integration+from posthog.models import Integrationfrom products.batch_exports.backend.api.destination_tests.base import DestinationTestStepResult, Statusfrom products.batch_exports.backend.api.destination_tests.bigquery import BigQueryProjectTestStep@@ -22,6 +22,7 @@ from products.batch_exports.backend.api.destination_tests.databricks import (DatabricksEstablishConnectionTestStep,)from products.batch_exports.backend.api.destination_tests.snowflake import SnowflakeEstablishConnectionTestStep+from products.batch_exports.backend.models.batch_export import BatchExportDestinationpytestmark = [pytest.mark.django_db,@@ -211,7 +212,9 @@ def test_run_test_step_rejects_destination_type_change(client: HttpClient, tempo"interval": "hour",}- with unittest.mock.patch("posthog.batch_exports.http.get_destination_test") as mock_get_destination_test:+ with unittest.mock.patch(+ "products.batch_exports.backend.api.batch_export.get_destination_test"+ ) as mock_get_destination_test:response = client.post(f"/api/projects/{team.pk}/batch_exports/{batch_export['id']}/run_test_step",{**{"step": 0}, **malicious_data},@@ -499,7 +502,9 @@ def test_can_run_databricks_test_step_for_new_destination(client.force_login(user)- with unittest.mock.patch("posthog.batch_exports.http.get_destination_test") as mock_get_destination_test:+ with unittest.mock.patch(+ "products.batch_exports.backend.api.batch_export.get_destination_test"+ ) as mock_get_destination_test:test_step = DatabricksEstablishConnectionTestStep()test_step.result = DestinationTestStepResult(status=Status.PASSED, message=None)mock_databricks_destination_test = unittest.mock.Mock(spec=DatabricksDestinationTest)diff --git a/posthog/api/test/batch_exports/test_update.py b/posthog/api/test/batch_exports/test_update.pyindex 75f590ee2590..8495c1053b0a 100644--- a/posthog/api/test/batch_exports/test_update.py+++ b/posthog/api/test/batch_exports/test_update.py@@ -21,10 +21,10 @@ from posthog.api.test.batch_exports.operations import (patch_batch_export,put_batch_export,)-from posthog.models import BatchExport, BatchExportDestinationfrom posthog.models.integration import Integrationfrom posthog.temporal.common.codec import EncryptionCodec+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestinationfrom products.batch_exports.backend.service import sync_batch_exportpytestmark = [diff --git a/posthog/api/test/batch_exports/test_update_s3.py b/posthog/api/test/batch_exports/test_update_s3.pyindex 819fd442e3ac..675df821992b 100644--- a/posthog/api/test/batch_exports/test_update_s3.py+++ b/posthog/api/test/batch_exports/test_update_s3.py@@ -5,7 +5,8 @@ from django.test.client import Client as HttpClientfrom rest_framework import statusfrom posthog.api.test.batch_exports.operations import create_batch_export_ok, patch_batch_export-from posthog.batch_exports.models import S3_FAMILY_TYPES++from products.batch_exports.backend.models.batch_export import S3_FAMILY_TYPESpytestmark = [pytest.mark.django_db,diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex 7040e21d65c1..811dce661645 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -23,7 +23,6 @@ from rest_framework import statusfrom posthog.schema import PersonsOnEventsMode, PropertyOperator-from posthog.api.test.test_exports import TestExportMixinfrom posthog.clickhouse.client.execute import sync_executefrom posthog.models import Person, Userfrom posthog.models.activity_logging.activity_log import ActivityLog@@ -42,6 +41,7 @@ from posthog.tasks.calculate_cohort import ()from products.actions.backend.models.action import Action+from products.exports.backend.api.test.test_exports import TestExportMixinfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.clickhouse.materialized_columns.analyze import materializediff --git a/posthog/api/test/test_routing.py b/posthog/api/test/test_routing.pyindex adaf1eba83ad..01e44909838a 100644--- a/posthog/api/test/test_routing.py+++ b/posthog/api/test/test_routing.py@@ -12,16 +12,17 @@ from rest_framework import viewsetsfrom rest_framework.decorators import actionfrom rest_framework.response import Response-from posthog.api.annotation import AnnotationSerializerfrom posthog.api.oauth.test_dcr import generate_rsa_keyfrom posthog.api.routing import DefaultRouterPlusPlus, TeamAndOrgViewSetMixin-from posthog.models.annotation import Annotationfrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.organization import Organizationfrom posthog.models.project import Projectfrom posthog.models.scoping import get_current_team_idfrom posthog.models.team.team import Team+from products.annotations.backend.api.annotation import AnnotationSerializer+from products.annotations.backend.models.annotation import Annotation+class FooViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):scope_object = "INTERNAL"diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.pyindex 6e00798ec826..7cdb357b51ca 100644--- a/posthog/api/test/test_sharing.py+++ b/posthog/api/test/test_sharing.py@@ -16,14 +16,14 @@ from rest_framework import statusfrom posthog.api.sharing import _log_share_password_attempt, shared_url_as_pngfrom posthog.constants import AvailableFeature-from posthog.models import ActivityLog, ExportedAsset-from posthog.models.exported_asset import get_render_access_token+from posthog.models import ActivityLogfrom posthog.models.filters.filter import Filterfrom posthog.models.share_password import SharePasswordfrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.user import Userfrom products.dashboards.backend.models.dashboard import Dashboard+from products.exports.backend.models.exported_asset import ExportedAsset, get_render_access_tokenfrom products.product_analytics.backend.models.insight import Insight@@ -122,7 +122,7 @@ class TestSharing(APIBaseTest):)@freeze_time("2022-01-01")- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_gets_sharing_config(self, patched_exporter_task: Mock):assert SharingConfiguration.objects.count() == 0@@ -141,7 +141,7 @@ class TestSharing(APIBaseTest):}@freeze_time("2022-01-01")- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_does_not_change_token_when_toggling_enabled_state(self, patched_exporter_task: Mock):assert SharingConfiguration.objects.count() == 0response = self.client.patch(@@ -173,7 +173,7 @@ class TestSharing(APIBaseTest):"share_passwords": [],}- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_can_edit_enabled_state(self, patched_exporter_task: Mock):response = self.client.patch(f"/api/projects/{self.team.id}/dashboards/{self.dashboard.id}/sharing",@@ -201,7 +201,7 @@ class TestSharing(APIBaseTest):("sharing disabled", self.user.id),]- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_can_edit_enabled_state_for_insight(self, patched_exporter_task: Mock):assert ActivityLog.objects.filter(scope="SharingConfiguration").count() == 0@@ -228,7 +228,7 @@ class TestSharing(APIBaseTest):"sharing disabled",]- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_exports_image_when_sharing(self, patched_exporter_task: Mock):assert ExportedAsset.objects.count() == 0@@ -242,7 +242,7 @@ class TestSharing(APIBaseTest):assert asset is not Noneassert asset.export_format == "image/png"- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_should_update_to_match_existing_dashboard_sharing_token(self, patched_exporter_task: Mock):dashboard = Dashboard.objects.create(team=self.team, name="example dashboard", created_by=self.user)response = self.client.get(f"/api/projects/{self.team.id}/dashboards/{dashboard.id}/sharing")@@ -268,7 +268,7 @@ class TestSharing(APIBaseTest):assert data["access_token"] == "my_test_token"assert data["enabled"]- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_should_not_be_affected_by_collaboration_rules(self, _patched_exporter_task: Mock):other_user = User.objects.create_and_join(self.organization, "[email protected]", None)dashboard = Dashboard.objects.create(@@ -285,7 +285,7 @@ class TestSharing(APIBaseTest):assert response.status_code == 200- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_should_not_get_deleted_item(self, _patched_exporter_task: Mock):dashboard = Dashboard.objects.create(team=self.team,@@ -311,8 +311,8 @@ class TestSharing(APIBaseTest):"/shared_dashboard/something.png?token=my_test_token",])- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")- @patch("posthog.models.exported_asset.object_storage.get_presigned_url")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.models.exported_asset.object_storage.get_presigned_url")@patch("posthog.api.sharing.asset_for_token")def test_can_get_shared_dashboard_asset_with_no_content_but_content_location(self,@@ -342,8 +342,8 @@ class TestSharing(APIBaseTest):)@parameterized.expand(["insights", "dashboards"])- @patch("posthog.models.exported_asset.object_storage.get_presigned_url")- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.models.exported_asset.object_storage.get_presigned_url")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_shared_thing_can_generate_open_graph_image(self, type: str, patched_exporter_task: Mock, patched_get_presigned_url: Mock) -> None:@@ -368,8 +368,8 @@ class TestSharing(APIBaseTest):assert item_opengraph_image["Location"] == "https://s3.example.com/presigned-url"@parameterized.expand(["insights", "dashboards"])- @patch("posthog.models.exported_asset.object_storage.get_presigned_url")- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.models.exported_asset.object_storage.get_presigned_url")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_shared_thing_can_reuse_existing_generated_open_graph_image(self, type: str, patched_exporter_task: Mock, patched_get_presigned_url: Mock) -> None:@@ -408,8 +408,8 @@ class TestSharing(APIBaseTest):patched_exporter_task.side_effect = add_content_location_on_task_run@parameterized.expand(["insights", "dashboards"])- @patch("posthog.models.exported_asset.object_storage.get_presigned_url")- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.models.exported_asset.object_storage.get_presigned_url")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_shared_insight_can_regenerate_stale_existing_generated_open_graph_image(self, type: str, patched_exporter_task: Mock, patched_get_presigned_url: Mock) -> None:@@ -444,7 +444,7 @@ class TestSharing(APIBaseTest):assert original_asset is not Noneassert final_asset.id != original_asset.id- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_can_refresh_sharing_access_token_for_dashboard(self, patched_exporter_task: Mock):# Enable sharingresponse = self.client.patch(@@ -475,7 +475,7 @@ class TestSharing(APIBaseTest):assert first is not Noneassert first.item_id == str(self.dashboard.id)- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_can_refresh_sharing_access_token_for_insight(self, patched_exporter_task: Mock):# First enable sharingresponse = self.client.patch(@@ -503,7 +503,7 @@ class TestSharing(APIBaseTest):assert first.item_id == str(self.insight.id)@freeze_time("2025-01-01 00:00:00")- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_refresh_token_grace_period(self, patched_exporter_task: Mock):# Enable sharingresponse = self.client.patch(@@ -596,7 +596,7 @@ class TestSharing(APIBaseTest):assert original_config.expires_at is not Noneassert original_config.expires_at > timezone.now() # Should be in the future- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_sharing_configuration_settings_field_defaults(self, patched_exporter_task: Mock):"""Test that settings field defaults to empty dict"""response = self.client.patch(@@ -608,7 +608,7 @@ class TestSharing(APIBaseTest):assert "settings" in dataassert data["settings"] is None- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_can_update_settings_field(self, patched_exporter_task: Mock):"""Test that settings field can be updated"""# First enable sharing@@ -636,7 +636,7 @@ class TestSharing(APIBaseTest):"whitelabel": True,}- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_settings_preserved_on_token_rotation(self, patched_exporter_task: Mock):"""Test that settings are preserved when rotating access tokens"""# Enable sharing with comprehensive settings@@ -791,7 +791,7 @@ class TestSharing(APIBaseTest):# assert '\\"detailed\\": true' not in content@parameterized.expand(["insights", "dashboards"])- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_settings_field_works_for_both_insights_and_dashboards(self, type: str, patched_exporter_task: Mock):"""Test that settings field works for both insights and dashboards"""target = self.insight if type == "insights" else self.dashboard@@ -871,7 +871,7 @@ class TestSharingConfigurationSerializerValidation(APIBaseTest):super().setUpTestData()cls.dashboard = Dashboard.objects.create(team=cls.team, name="test dashboard", created_by=cls.user)- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_valid_settings_are_accepted(self, patched_exporter_task: Mock):"""Test that valid settings are accepted and validated"""valid_settings = {@@ -892,7 +892,7 @@ class TestSharingConfigurationSerializerValidation(APIBaseTest):data = response.json()assert data["settings"] == valid_settings- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_partial_settings_are_filled_with_defaults(self, patched_exporter_task: Mock):"""Test that partial settings are filled with defaults during validation"""partial_settings = {"whitelabel": True, "legend": True, "theme": "light"}@@ -913,7 +913,7 @@ class TestSharingConfigurationSerializerValidation(APIBaseTest):}assert data["settings"] == expected_settings- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_unknown_settings_are_filtered_out(self, patched_exporter_task: Mock):"""Test that unknown settings fields are filtered out during validation"""settings_with_unknown = {@@ -938,7 +938,7 @@ class TestSharingConfigurationSerializerValidation(APIBaseTest):}assert data["settings"] == expected_settings- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_null_settings_are_accepted(self, patched_exporter_task: Mock):"""Test that null settings are accepted"""response = self.client.patch(@@ -950,7 +950,7 @@ class TestSharingConfigurationSerializerValidation(APIBaseTest):data = response.json()assert data["settings"] is None- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_empty_settings_get_defaults(self, patched_exporter_task: Mock):"""Test that empty settings dictionary gets filled with defaults"""response = self.client.patch(@@ -986,7 +986,7 @@ class TestSharingConfigurationSerializerValidation(APIBaseTest):valid_settings = {"whitelabel": True, "detailed": True}- with patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow"):+ with patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow"):response = self.client.patch(f"/api/projects/{self.team.id}/insights/{insight.id}/sharing",{"enabled": True, "settings": valid_settings},@@ -1001,7 +1001,7 @@ class TestSharingConfigurationSerializerValidation(APIBaseTest):}assert data["settings"] == expected_settings- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")@mock_exporter_templatedef test_shared_resource_blocked_when_organization_disallows_public_sharing(self, _patched_exporter_task: Mock):"""Test that shared resources return 404 when organization.allow_publicly_shared_resources is False and feature is enabled"""@@ -1044,7 +1044,7 @@ class TestSharingConfigurationSerializerValidation(APIBaseTest):("sharing_on_subscription_on_file", True, "subscription", "file", 200),])- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")@patch("posthog.api.sharing.render_template")def test_exported_asset_token_access_matrix(self,@@ -1093,8 +1093,8 @@ class TestSharingConfigurationSerializerValidation(APIBaseTest):response = self.client.get(f"{path}?token={token}")assert response.status_code == expected_status- @patch("posthog.models.exported_asset.object_storage.get_presigned_url")- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.models.exported_asset.object_storage.get_presigned_url")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_exported_asset_public_url_blocked_when_organization_disallows_public_sharing(self, _patched_exporter_task: Mock, patched_get_presigned_url: Mock):@@ -1137,8 +1137,8 @@ class TestSharingConfigurationSerializerValidation(APIBaseTest):response = self.client.get(exporter_url)assert response.status_code == 404- @patch("posthog.models.exported_asset.object_storage.get_presigned_url")- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.models.exported_asset.object_storage.get_presigned_url")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_exported_asset_public_url_blocked_for_password_protected_share_when_disallowed(self, _patched_exporter_task: Mock, patched_get_presigned_url: Mock):diff --git a/posthog/api/unsubscribe.py b/posthog/api/unsubscribe.pyindex 98bf51868915..82adad63b13e 100644--- a/posthog/api/unsubscribe.py+++ b/posthog/api/unsubscribe.py@@ -2,7 +2,7 @@ from django.http import HttpRequest, JsonResponseimport jwt-from posthog.models.subscription import unsubscribe_using_token+from products.exports.backend.models.subscription import unsubscribe_using_tokendef unsubscribe(request: HttpRequest):diff --git a/posthog/clickhouse/migrations/0064_create_person_batch_export_view.py b/posthog/clickhouse/migrations/0064_create_person_batch_export_view.pyindex dd48dc355ec7..94a8d185432c 100644--- a/posthog/clickhouse/migrations/0064_create_person_batch_export_view.py+++ b/posthog/clickhouse/migrations/0064_create_person_batch_export_view.py@@ -1,10 +1,11 @@-from posthog.batch_exports.sql import (+from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions++from products.batch_exports.backend.sql import (CREATE_EVENTS_BATCH_EXPORT_VIEW,CREATE_EVENTS_BATCH_EXPORT_VIEW_BACKFILL,CREATE_EVENTS_BATCH_EXPORT_VIEW_UNBOUNDED,CREATE_PERSONS_BATCH_EXPORT_VIEW,)-from posthog.clickhouse.client.migration_tools import run_sql_with_exceptionsoperations = map(run_sql_with_exceptions,diff --git a/posthog/clickhouse/migrations/0065_update_batch_exports_views.py b/posthog/clickhouse/migrations/0065_update_batch_exports_views.pyindex dd48dc355ec7..94a8d185432c 100644--- a/posthog/clickhouse/migrations/0065_update_batch_exports_views.py+++ b/posthog/clickhouse/migrations/0065_update_batch_exports_views.py@@ -1,10 +1,11 @@-from posthog.batch_exports.sql import (+from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions++from products.batch_exports.backend.sql import (CREATE_EVENTS_BATCH_EXPORT_VIEW,CREATE_EVENTS_BATCH_EXPORT_VIEW_BACKFILL,CREATE_EVENTS_BATCH_EXPORT_VIEW_UNBOUNDED,CREATE_PERSONS_BATCH_EXPORT_VIEW,)-from posthog.clickhouse.client.migration_tools import run_sql_with_exceptionsoperations = map(run_sql_with_exceptions,diff --git a/posthog/clickhouse/migrations/0070_update_persons_batch_export.py b/posthog/clickhouse/migrations/0070_update_persons_batch_export.pyindex 4afa5807cf71..3ad0659fd3b2 100644--- a/posthog/clickhouse/migrations/0070_update_persons_batch_export.py+++ b/posthog/clickhouse/migrations/0070_update_persons_batch_export.py@@ -1,6 +1,7 @@-from posthog.batch_exports.sql import CREATE_PERSONS_BATCH_EXPORT_VIEWfrom posthog.clickhouse.client.migration_tools import run_sql_with_exceptions+from products.batch_exports.backend.sql import CREATE_PERSONS_BATCH_EXPORT_VIEW+operations = map(run_sql_with_exceptions,[diff --git a/posthog/clickhouse/migrations/0073_update_person_batch_exports_query_for_memory.py b/posthog/clickhouse/migrations/0073_update_person_batch_exports_query_for_memory.pyindex 4afa5807cf71..3ad0659fd3b2 100644--- a/posthog/clickhouse/migrations/0073_update_person_batch_exports_query_for_memory.py+++ b/posthog/clickhouse/migrations/0073_update_person_batch_exports_query_for_memory.py@@ -1,6 +1,7 @@-from posthog.batch_exports.sql import CREATE_PERSONS_BATCH_EXPORT_VIEWfrom posthog.clickhouse.client.migration_tools import run_sql_with_exceptions+from products.batch_exports.backend.sql import CREATE_PERSONS_BATCH_EXPORT_VIEW+operations = map(run_sql_with_exceptions,[diff --git a/posthog/clickhouse/migrations/0080_recreate_events_backfill.py b/posthog/clickhouse/migrations/0080_recreate_events_backfill.pyindex c42c5d2a802b..7421d9621040 100644--- a/posthog/clickhouse/migrations/0080_recreate_events_backfill.py+++ b/posthog/clickhouse/migrations/0080_recreate_events_backfill.py@@ -1,6 +1,7 @@-from posthog.batch_exports.sql import CREATE_EVENTS_BATCH_EXPORT_VIEW_BACKFILLfrom posthog.clickhouse.client.migration_tools import run_sql_with_exceptions+from products.batch_exports.backend.sql import CREATE_EVENTS_BATCH_EXPORT_VIEW_BACKFILL+operations = map(run_sql_with_exceptions,[diff --git a/posthog/clickhouse/migrations/0081_persons_batch_export_backfill.py b/posthog/clickhouse/migrations/0081_persons_batch_export_backfill.pyindex 8b68f0188320..83af52820b89 100644--- a/posthog/clickhouse/migrations/0081_persons_batch_export_backfill.py+++ b/posthog/clickhouse/migrations/0081_persons_batch_export_backfill.py@@ -1,6 +1,7 @@-from posthog.batch_exports.sql import CREATE_PERSONS_BATCH_EXPORT_VIEW_BACKFILLfrom posthog.clickhouse.client.migration_tools import run_sql_with_exceptions+from products.batch_exports.backend.sql import CREATE_PERSONS_BATCH_EXPORT_VIEW_BACKFILL+operations = map(run_sql_with_exceptions,[diff --git a/posthog/clickhouse/migrations/0084_persons_batch_export_update.py b/posthog/clickhouse/migrations/0084_persons_batch_export_update.pyindex ce1820c560d8..27ea6a7ea53b 100644--- a/posthog/clickhouse/migrations/0084_persons_batch_export_update.py+++ b/posthog/clickhouse/migrations/0084_persons_batch_export_update.py@@ -1,6 +1,10 @@-from posthog.batch_exports.sql import CREATE_PERSONS_BATCH_EXPORT_VIEW, CREATE_PERSONS_BATCH_EXPORT_VIEW_BACKFILLfrom posthog.clickhouse.client.migration_tools import run_sql_with_exceptions+from products.batch_exports.backend.sql import (+ CREATE_PERSONS_BATCH_EXPORT_VIEW,+ CREATE_PERSONS_BATCH_EXPORT_VIEW_BACKFILL,+)+operations = map(run_sql_with_exceptions,[diff --git a/posthog/clickhouse/migrations/0085_update_person_batch_exports_query_for_performance.py b/posthog/clickhouse/migrations/0085_update_person_batch_exports_query_for_performance.pyindex 4afa5807cf71..3ad0659fd3b2 100644--- a/posthog/clickhouse/migrations/0085_update_person_batch_exports_query_for_performance.py+++ b/posthog/clickhouse/migrations/0085_update_person_batch_exports_query_for_performance.py@@ -1,6 +1,7 @@-from posthog.batch_exports.sql import CREATE_PERSONS_BATCH_EXPORT_VIEWfrom posthog.clickhouse.client.migration_tools import run_sql_with_exceptions+from products.batch_exports.backend.sql import CREATE_PERSONS_BATCH_EXPORT_VIEW+operations = map(run_sql_with_exceptions,[diff --git a/posthog/clickhouse/migrations/0092_create_batch_exports_recent_event_view.py b/posthog/clickhouse/migrations/0092_create_batch_exports_recent_event_view.pyindex 9a63d286eb55..e48dcc4aa4c1 100644--- a/posthog/clickhouse/migrations/0092_create_batch_exports_recent_event_view.py+++ b/posthog/clickhouse/migrations/0092_create_batch_exports_recent_event_view.py@@ -1,6 +1,7 @@-from posthog.batch_exports.sql import CREATE_EVENTS_BATCH_EXPORT_VIEW_RECENTfrom posthog.clickhouse.client.migration_tools import run_sql_with_exceptions+from products.batch_exports.backend.sql import CREATE_EVENTS_BATCH_EXPORT_VIEW_RECENT+operations = map(run_sql_with_exceptions,[diff --git a/posthog/clickhouse/migrations/0093_persons_batch_export_add_created_at.py b/posthog/clickhouse/migrations/0093_persons_batch_export_add_created_at.pyindex ce1820c560d8..27ea6a7ea53b 100644--- a/posthog/clickhouse/migrations/0093_persons_batch_export_add_created_at.py+++ b/posthog/clickhouse/migrations/0093_persons_batch_export_add_created_at.py@@ -1,6 +1,10 @@-from posthog.batch_exports.sql import CREATE_PERSONS_BATCH_EXPORT_VIEW, CREATE_PERSONS_BATCH_EXPORT_VIEW_BACKFILLfrom posthog.clickhouse.client.migration_tools import run_sql_with_exceptions+from products.batch_exports.backend.sql import (+ CREATE_PERSONS_BATCH_EXPORT_VIEW,+ CREATE_PERSONS_BATCH_EXPORT_VIEW_BACKFILL,+)+operations = map(run_sql_with_exceptions,[diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.pyindex 855b8dfb1fab..4c022ba8d368 100644--- a/posthog/hogql/database/schema/test/test_system_tables.py+++ b/posthog/hogql/database/schema/test/test_system_tables.py@@ -12,17 +12,7 @@ from posthog.hogql.parser import parse_selectfrom posthog.hogql.printer import prepare_and_print_astfrom posthog.hogql.query import execute_hogql_query-from posthog.models import (- Annotation,- Cohort,- ExportedAsset,- Group,- GroupTypeMapping,- GroupUsageMetric,- Organization,- Tag,- Team,-)+from posthog.models import Cohort, Group, GroupTypeMapping, GroupUsageMetric, Organization, Tag, Teamfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.cohort.calculation_history import CohortCalculationHistoryfrom posthog.models.project import Project@@ -33,6 +23,7 @@ from products.ai_observability.backend.models.review_queues import ReviewQueue,from products.ai_observability.backend.models.score_definitions import ScoreDefinitionfrom products.ai_observability.backend.models.trace_reviews import TraceReview, TraceReviewScorefrom products.alerts.backend.models.alert import AlertConfiguration+from products.annotations.backend.models.annotation import Annotationfrom products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, KnowledgeSourcefrom products.business_knowledge.backend.models.constants import SourceStatus, SourceTypefrom products.cdp.backend.models.hog_functions.hog_function import HogFunction@@ -46,6 +37,7 @@ from products.early_access_features.backend.models import EarlyAccessFeaturefrom products.endpoints.backend.models import Endpoint, EndpointVersionfrom products.error_tracking.backend.models import ErrorTrackingIssue, ErrorTrackingSymbolSetfrom products.experiments.backend.models.experiment import Experiment+from products.exports.backend.models.exported_asset import ExportedAssetfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.logs.backend.models import LogsAlertConfiguration, LogsViewfrom products.notebooks.backend.models import Notebook, ResourceNotebook@@ -117,14 +109,18 @@ class TestSystemTablesTeamScoping(BaseTest):def _create_batch_export(team: Team, label: str):- from posthog.batch_exports.models import BatchExport, BatchExportDestination+ from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestinationdestination = BatchExportDestination.objects.create(type="S3", config={})return BatchExport.objects.create(team=team, name=f"export_{label}", destination=destination, interval="hour")def _create_batch_export_backfill(team: Team, label: str):- from posthog.batch_exports.models import BatchExport, BatchExportBackfill, BatchExportDestination+ from products.batch_exports.backend.models.batch_export import (+ BatchExport,+ BatchExportBackfill,+ BatchExportDestination,+ )destination = BatchExportDestination.objects.create(type="S3", config={})batch_export = BatchExport.objects.create(diff --git a/posthog/management/commands/backfill_batch_export_runs.py b/posthog/management/commands/backfill_batch_export_runs.pyindex cad2db222621..91435b12feb6 100644--- a/posthog/management/commands/backfill_batch_export_runs.py+++ b/posthog/management/commands/backfill_batch_export_runs.py@@ -7,9 +7,9 @@ from django.utils import timezoneimport temporalio.client-from posthog.batch_exports.models import BatchExport, BatchExportRunfrom posthog.temporal.common.client import connect+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportRunfrom products.batch_exports.backend.service import align_timestamp_to_interval# Statuses that count as "covered" — the run either succeeded or is still in progressdiff --git a/posthog/management/commands/migrate_team.py b/posthog/management/commands/migrate_team.pyindex a9b654410d24..ec01a61146a9 100644--- a/posthog/management/commands/migrate_team.py+++ b/posthog/management/commands/migrate_team.py@@ -4,10 +4,16 @@ import datetime as dtfrom django.core.management.base import BaseCommand, CommandErrorfrom django.db import transaction-from posthog.batch_exports.models import BATCH_EXPORT_INTERVALS-from posthog.models import BatchExport, BatchExportBackfill, BatchExportDestination, BatchExportRun, Team+from posthog.models import Teamfrom posthog.temporal.common.client import sync_connect+from products.batch_exports.backend.models.batch_export import (+ BATCH_EXPORT_INTERVALS,+ BatchExport,+ BatchExportBackfill,+ BatchExportDestination,+ BatchExportRun,+)from products.batch_exports.backend.service import backfill_export, delete_batch_export, sync_batch_exportlogger = logging.getLogger(__name__)diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex a95566df2b6d..5b517cdeedb7 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -138,10 +138,6 @@ from posthog.temporal.session_replay.summarization_sweep import (SUMMARIZATION_SWEEP_ACTIVITIES,SUMMARIZATION_SWEEP_WORKFLOWS,)-from posthog.temporal.subscriptions import (- ACTIVITIES as SUBSCRIPTION_ACTIVITIES,- WORKFLOWS as SUBSCRIPTION_WORKFLOWS,-)from posthog.temporal.sync_person_distinct_ids import (ACTIVITIES as SYNC_PERSON_DISTINCT_IDS_ACTIVITIES,WORKFLOWS as SYNC_PERSON_DISTINCT_IDS_WORKFLOWS,@@ -167,6 +163,10 @@ from products.batch_exports.backend.temporal import (ACTIVITIES as BATCH_EXPORTS_ACTIVITIES,WORKFLOWS as BATCH_EXPORTS_WORKFLOWS,)+from products.exports.backend.temporal.subscriptions import (+ ACTIVITIES as SUBSCRIPTION_ACTIVITIES,+ WORKFLOWS as SUBSCRIPTION_WORKFLOWS,+)from products.logs.backend.temporal import (ACTIVITIES as LOGS_ALERTING_ACTIVITIES,WORKFLOWS as LOGS_ALERTING_WORKFLOWS,diff --git a/posthog/management/commands/test/test_backfill_batch_export_runs.py b/posthog/management/commands/test/test_backfill_batch_export_runs.pyindex de6416972547..c3292b9ff253 100644--- a/posthog/management/commands/test/test_backfill_batch_export_runs.py+++ b/posthog/management/commands/test/test_backfill_batch_export_runs.py@@ -14,12 +14,12 @@ from asgiref.sync import async_to_syncfrom temporalio.service import RPCErrorfrom posthog.api.test.batch_exports.operations import start_test_worker-from posthog.batch_exports.models import BatchExport, BatchExportDestination, BatchExportRunfrom posthog.management.commands.backfill_batch_export_runs import find_missing_intervals, get_batch_exportsfrom posthog.models import Organization, Teamfrom posthog.temporal.common.client import sync_connectfrom posthog.temporal.tests.utils.models import create_batch_export+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRunfrom products.batch_exports.backend.tests.temporal.backfills.conftest import wait_for_workflowsdiff --git a/posthog/management/commands/test/test_update_batch_export_schedules.py b/posthog/management/commands/test/test_update_batch_export_schedules.pyindex 03e879d687e5..689db2c56fb8 100644--- a/posthog/management/commands/test/test_update_batch_export_schedules.py+++ b/posthog/management/commands/test/test_update_batch_export_schedules.py@@ -13,10 +13,10 @@ from temporalio.service import RPCErrorfrom posthog.api.test.test_organization import create_organizationfrom posthog.api.test.test_team import create_team-from posthog.models import BatchExport, BatchExportDestinationfrom posthog.temporal.common.client import sync_connectfrom posthog.temporal.common.schedule import describe_schedule, update_schedule+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestinationfrom products.batch_exports.backend.service import pause_batch_export, sync_batch_exportpytestmark = [diff --git a/posthog/management/commands/update_batch_export_schedules.py b/posthog/management/commands/update_batch_export_schedules.pyindex 83b4b7020192..fc97dc3dcf83 100644--- a/posthog/management/commands/update_batch_export_schedules.py+++ b/posthog/management/commands/update_batch_export_schedules.py@@ -5,8 +5,7 @@ from django.core.management.base import BaseCommand, CommandErrorimport structlog-from posthog.models import BatchExport-+from products.batch_exports.backend.models.batch_export import BatchExportfrom products.batch_exports.backend.service import sync_batch_exportlogger = structlog.get_logger(__name__)diff --git a/posthog/migrations/0001_initial_squashed_0284_improved_caching_state_idx.py b/posthog/migrations/0001_initial_squashed_0284_improved_caching_state_idx.pyindex e7e32699bde0..f680c470b278 100644--- a/posthog/migrations/0001_initial_squashed_0284_improved_caching_state_idx.py+++ b/posthog/migrations/0001_initial_squashed_0284_improved_caching_state_idx.py@@ -18,11 +18,12 @@ import posthog.utilsimport posthog.models.userimport posthog.models.utilsimport posthog.models.team.team-import posthog.models.exported_assetimport posthog.models.organization_domainimport posthog.models.sharing_configurationimport posthog.models.activity_logging.activity_log+import products.exports.backend.models.exported_asset+class Migration(migrations.Migration):replaces = [@@ -964,7 +965,7 @@ class Migration(migrations.Migration):"access_token",models.CharField(blank=True,- default=posthog.models.exported_asset.get_default_access_token,+ default=products.exports.backend.models.exported_asset.get_default_access_token,max_length=400,null=True,),diff --git a/posthog/migrations/0238_exportedasset.py b/posthog/migrations/0238_exportedasset.pyindex f1ace9731313..25db6d6be27d 100644--- a/posthog/migrations/0238_exportedasset.py+++ b/posthog/migrations/0238_exportedasset.py@@ -3,7 +3,7 @@import django.db.models.deletionfrom django.db import migrations, models-import posthog.models.exported_asset+import products.exports.backend.models.exported_assetclass Migration(migrations.Migration):@@ -41,7 +41,7 @@ class Migration(migrations.Migration):"access_token",models.CharField(blank=True,- default=posthog.models.exported_asset.get_default_access_token,+ default=products.exports.backend.models.exported_asset.get_default_access_token,max_length=400,null=True,),diff --git a/posthog/migrations/1041_backfill_subscription_integration.py b/posthog/migrations/1041_backfill_subscription_integration.pyindex 3eb2a3d2ee46..3349b035c512 100644--- a/posthog/migrations/1041_backfill_subscription_integration.py+++ b/posthog/migrations/1041_backfill_subscription_integration.py@@ -7,7 +7,10 @@ def backfill_subscription_integration(apps, schema_editor):Uses the integration with the lowest id per team, matching theexisting get_slack_integration_for_team .first() behavior."""- Subscription = apps.get_model("posthog", "Subscription")+ try:+ Subscription = apps.get_model("posthog", "Subscription")+ except LookupError:+ Subscription = apps.get_model("exports", "Subscription")Integration = apps.get_model("posthog", "Integration")slack_subs = list(diff --git a/posthog/migrations/1202_migrate_exports_models.py b/posthog/migrations/1202_migrate_exports_models.pynew file mode 100644index 000000000000..37161caa8372--- /dev/null+++ b/posthog/migrations/1202_migrate_exports_models.py@@ -0,0 +1,100 @@+# Generated by Django 5.2.14 on 2026-05-27 10:06++import django.db.models.deletion+from django.db import migrations, models++MODELS_TO_MOVE = ("exportedasset", "subscription", "subscriptiondelivery")+++def _move_content_types(apps, schema_editor, from_label, to_label):+ """Move ContentTypes between apps, handling duplicates idempotently."""+ 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", "exports")+++def reverse_content_types(apps, schema_editor):+ _move_content_types(apps, schema_editor, "exports", "posthog")+++class Migration(migrations.Migration):+ dependencies = [+ ("exports", "0001_migrate_exports_models"),+ ("posthog", "1201_persistedfolder_drop_old_unique"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AlterField(+ model_name="objectmediapreview",+ name="exported_asset",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="object_previews",+ to="exports.exportedasset",+ ),+ ),+ migrations.RemoveField(+ model_name="subscription",+ name="created_by",+ ),+ migrations.RemoveField(+ model_name="subscription",+ name="dashboard",+ ),+ migrations.RemoveField(+ model_name="subscription",+ name="dashboard_export_insights",+ ),+ migrations.RemoveField(+ model_name="subscription",+ name="insight",+ ),+ migrations.RemoveField(+ model_name="subscription",+ name="integration",+ ),+ migrations.RemoveField(+ model_name="subscription",+ name="team",+ ),+ migrations.RemoveField(+ model_name="subscriptiondelivery",+ name="subscription",+ ),+ migrations.RemoveField(+ model_name="subscriptiondelivery",+ name="team",+ ),+ migrations.DeleteModel(+ name="ExportedAsset",+ ),+ migrations.DeleteModel(+ name="Subscription",+ ),+ migrations.DeleteModel(+ name="SubscriptionDelivery",+ ),+ ],+ database_operations=[],+ ),+ migrations.RunPython(update_content_types, reverse_content_types),+ ]diff --git a/posthog/migrations/1203_migrate_annotations_models.py b/posthog/migrations/1203_migrate_annotations_models.pynew file mode 100644index 000000000000..61350d8295a9--- /dev/null+++ b/posthog/migrations/1203_migrate_annotations_models.py@@ -0,0 +1,50 @@+# Generated by Django 5.2.14 on 2026-05-27 10:13++from django.db import migrations++MODELS_TO_MOVE = ("annotation",)+++def _move_content_types(apps, schema_editor, from_label, to_label):+ """Move ContentTypes between apps, handling duplicates idempotently."""+ 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", "annotations")+++def reverse_content_types(apps, schema_editor):+ _move_content_types(apps, schema_editor, "annotations", "posthog")+++class Migration(migrations.Migration):+ dependencies = [+ ("annotations", "0001_migrate_annotations_models"),+ ("posthog", "1202_migrate_exports_models"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.DeleteModel(+ name="Annotation",+ ),+ ],+ database_operations=[],+ ),+ migrations.RunPython(update_content_types, reverse_content_types),+ ]diff --git a/posthog/migrations/1204_migrate_batch_exports_models.py b/posthog/migrations/1204_migrate_batch_exports_models.pynew file mode 100644index 000000000000..17d1a9535afc--- /dev/null+++ b/posthog/migrations/1204_migrate_batch_exports_models.py@@ -0,0 +1,50 @@+# Generated by Django 5.2.14 on 2026-05-27 10:20++from django.db import migrations++MODELS_TO_MOVE = ("batchimport",)+++def _move_content_types(apps, schema_editor, from_label, to_label):+ """Move ContentTypes between apps, handling duplicates idempotently."""+ 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", "batch_exports")+++def reverse_content_types(apps, schema_editor):+ _move_content_types(apps, schema_editor, "batch_exports", "posthog")+++class Migration(migrations.Migration):+ dependencies = [+ ("batch_exports", "0001_migrate_batch_exports_models"),+ ("posthog", "1203_migrate_annotations_models"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.DeleteModel(+ name="BatchImport",+ ),+ ],+ database_operations=[],+ ),+ migrations.RunPython(update_content_types, reverse_content_types),+ ]diff --git a/posthog/migrations/1205_delete_batch_export_models.py b/posthog/migrations/1205_delete_batch_export_models.pynew file mode 100644index 000000000000..824673020ef0--- /dev/null+++ b/posthog/migrations/1205_delete_batch_export_models.py@@ -0,0 +1,113 @@+# Generated by Django 5.2.14 on 2026-05-27 10:56++from django.db import migrations++MODELS_TO_MOVE = (+ "batchexport",+ "batchexportbackfill",+ "batchexportdestination",+ "batchexportfiledownload",+ "batchexportondemand",+ "batchexportrun",+)+++def _move_content_types(apps, schema_editor, from_label, to_label):+ """Move ContentTypes between apps, handling duplicates idempotently."""+ 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", "batch_exports")+++def reverse_content_types(apps, schema_editor):+ _move_content_types(apps, schema_editor, "batch_exports", "posthog")+++class Migration(migrations.Migration):+ dependencies = [+ ("batch_exports", "0002_batchexport_batchexportbackfill_and_more"),+ ("cdp", "0002_alter_hogfunction_batch_export"),+ ("posthog", "1204_migrate_batch_exports_models"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.RemoveField(+ model_name="batchexportbackfill",+ name="batch_export",+ ),+ migrations.RemoveField(+ model_name="batchexportrun",+ name="batch_export",+ ),+ migrations.RemoveField(+ model_name="batchexportbackfill",+ name="team",+ ),+ migrations.RemoveField(+ model_name="batchexportrun",+ name="backfill",+ ),+ migrations.RemoveField(+ model_name="batchexportdestination",+ name="integration",+ ),+ migrations.RemoveField(+ model_name="batchexportondemand",+ name="destination",+ ),+ migrations.RemoveField(+ model_name="batchexportfiledownload",+ name="batch_export_run",+ ),+ migrations.RemoveField(+ model_name="batchexportfiledownload",+ name="team",+ ),+ migrations.RemoveField(+ model_name="batchexportondemand",+ name="team",+ ),+ migrations.RemoveField(+ model_name="batchexportrun",+ name="batch_export_on_demand",+ ),+ migrations.DeleteModel(+ name="BatchExport",+ ),+ migrations.DeleteModel(+ name="BatchExportBackfill",+ ),+ migrations.DeleteModel(+ name="BatchExportDestination",+ ),+ migrations.DeleteModel(+ name="BatchExportFileDownload",+ ),+ migrations.DeleteModel(+ name="BatchExportOnDemand",+ ),+ migrations.DeleteModel(+ name="BatchExportRun",+ ),+ ],+ database_operations=[],+ ),+ migrations.RunPython(update_content_types, reverse_content_types),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 9e8e55114d13..7a92acd4d468 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1201_persistedfolder_drop_old_unique+1205_delete_batch_export_modelsdiff --git a/posthog/models/__init__.py b/posthog/models/__init__.pyindex 68e07e615b69..99224ea5de9e 100644--- a/posthog/models/__init__.py+++ b/posthog/models/__init__.py@@ -1,24 +1,14 @@# Need to skip autoimporting because this file is severely prone to circular imports errors# You should try and make them alphabetically sorted manually if possible# isort: skip_file-from ..batch_exports.models import (- BatchExport,- BatchExportBackfill,- BatchExportFileDownload,- BatchExportDestination,- BatchExportRun,- BatchExportOnDemand,-)from ..session_recordings.models.session_recording import SessionRecordingfrom ..session_recordings.models.session_recording_playlist import SessionRecordingPlaylistfrom ..session_recordings.models.session_recording_playlist_item import SessionRecordingPlaylistItemfrom ._deprecated_prompts import Prompt, PromptSequence, UserPromptStatefrom .activity_logging.activity_log import ActivityLogfrom .activity_logging.notification_viewed import NotificationViewed-from .annotation import Annotationfrom .async_deletion import AsyncDeletion, DeletionTypefrom .async_migration import AsyncMigration, AsyncMigrationError, MigrationStatus-from .batch_imports import BatchImportfrom .cohort import Cohort, CohortPeople, CohortCalculationHistoryfrom .column_configuration import ColumnConfigurationfrom .comment import Comment@@ -37,7 +27,6 @@ from .event_filter_config import EventFilterConfig # noqa: F401from products.event_definitions.backend.models import EventDefinitionfrom products.event_definitions.backend.models import EventPropertyfrom .role_external_reference import RoleExternalReference-from .exported_asset import ExportedAssetfrom .exported_recording import ExportedRecordingfrom .file_system.file_system import FileSystemfrom .file_system.file_system_view_log import FileSystemViewLog@@ -72,7 +61,6 @@ from .resource_transfer.resource_transfer import ResourceTransferfrom products.event_definitions.backend.models import EventSchema, SchemaPropertyGroup, SchemaPropertyGroupPropertyfrom .share_password import SharePasswordfrom .sharing_configuration import SharingConfiguration-from .subscription import Subscriptionfrom .tag import Tagfrom .tagged_item import TaggedItemfrom .team import Team, TeamRevenueAnalyticsConfig, TeamMarketingAnalyticsConfig@@ -102,17 +90,9 @@ __all__ = ["ApprovalPolicy","ChangeRequest","ActivityLog",- "Annotation","AsyncDeletion","AsyncMigration","AsyncMigrationError",- "BatchExport",- "BatchExportBackfill",- "BatchExportDestination",- "BatchExportFileDownload",- "BatchExportRun",- "BatchExportOnDemand",- "BatchImport","CIMDVerificationToken","Cohort","CohortPeople",@@ -136,7 +116,6 @@ __all__ = ["EventDefinition","EventProperty","RoleExternalReference",- "ExportedAsset","ExportedRecording","FileSystem","FileSystemViewLog",@@ -191,7 +170,6 @@ __all__ = ["SessionRecordingPlaylistItem","SharePassword","SharingConfiguration",- "Subscription","Tag","TaggedItem","Team",diff --git a/posthog/models/object_media_preview.py b/posthog/models/object_media_preview.pyindex d8fa057ad77a..e87de73c8930 100644--- a/posthog/models/object_media_preview.py+++ b/posthog/models/object_media_preview.py@@ -21,7 +21,7 @@ class ObjectMediaPreview(UUIDModel, CreatedMetaFields, UpdatedMetaFields):related_name="object_previews",)exported_asset = models.ForeignKey(- "ExportedAsset",+ "exports.ExportedAsset",on_delete=models.CASCADE,null=True,blank=True,diff --git a/posthog/models/resource_transfer/test/test_inter_project_transferer.py b/posthog/models/resource_transfer/test/test_inter_project_transferer.pyindex bf126e39a65d..1e8d3143a36c 100644--- a/posthog/models/resource_transfer/test/test_inter_project_transferer.py+++ b/posthog/models/resource_transfer/test/test_inter_project_transferer.py@@ -130,7 +130,7 @@ class TestBuildResourceDuplicationGraph(BaseTest):assert len(graph) == 0def test_raises_for_unvisitable_model(self) -> None:- from posthog.models import Annotation+ from products.annotations.backend.models.annotation import Annotationannotation = Annotation.objects.create(team=self.team, content="My annotation")with self.assertRaises(TypeError):diff --git a/posthog/models/team/util.py b/posthog/models/team/util.pyindex 0c93f7d7aa4e..759167cb4b02 100644--- a/posthog/models/team/util.py+++ b/posthog/models/team/util.py@@ -287,7 +287,7 @@ def delete_batch_exports(team_ids: list[int]):Using normal CASCADE doesn't trigger a delete from Temporal."""- from posthog.batch_exports.models import BatchExport+ from products.batch_exports.backend.models.batch_export import BatchExporttemporal = sync_connect()diff --git a/posthog/models/test/test_dashboard_tile_model.py b/posthog/models/test/test_dashboard_tile_model.pyindex 41777d612258..67a0eebce1bc 100644--- a/posthog/models/test/test_dashboard_tile_model.py+++ b/posthog/models/test/test_dashboard_tile_model.py@@ -5,10 +5,9 @@ from posthog.test.base import APIBaseTestfrom django.core.exceptions import ValidationErrorfrom django.db.utils import IntegrityError-from posthog.models.exported_asset import ExportedAsset-from products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile, Text+from products.exports.backend.models.exported_asset import ExportedAssetfrom products.product_analytics.backend.models.insight import Insightdiff --git a/posthog/models/test/test_subscription_model.py b/posthog/models/test/test_subscription_model.pyindex bbfe9794cdd3..ce5e9d397f6c 100644--- a/posthog/models/test/test_subscription_model.py+++ b/posthog/models/test/test_subscription_model.py@@ -15,7 +15,8 @@ from parameterized import parameterizedfrom posthog.constants import AvailableFeaturefrom posthog.jwt import PosthogJwtAudience-from posthog.models.subscription import (++from products.exports.backend.models.subscription import (SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER,UNSUBSCRIBE_TOKEN_EXP_DAYS,Subscription,@@ -23,7 +24,6 @@ from posthog.models.subscription import (get_unsubscribe_token,unsubscribe_using_token,)-from products.product_analytics.backend.models.insight import Insight@@ -473,7 +473,7 @@ class TestSubscriptionLimit(BaseTest):self.organization.available_product_features = []self.organization.save()self._create_subscriptions(2)- with patch("posthog.models.subscription.SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER", 2):+ with patch("products.exports.backend.models.subscription.SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER", 2):result = Subscription.check_subscription_limit(self.team.id, self.organization)assert result is not Noneassert "2" in resultdiff --git a/posthog/security/spreadsheet_safety.py b/posthog/security/spreadsheet_safety.pynew file mode 100644index 000000000000..748d06003c7d--- /dev/null+++ b/posthog/security/spreadsheet_safety.py@@ -0,0 +1,20 @@+"""Defensive helpers for content destined for spreadsheet apps."""++from typing import Any++# Characters that can trigger formula execution in spreadsheet applications+_FORMULA_TRIGGER_CHARS = ("=", "+", "-", "@", "\t", "\r")+++def sanitize_formula_injection(value: Any) -> Any:+ """Prefix dangerous cell values with a single quote to prevent formula injection.++ Spreadsheet applications like Excel and Google Sheets interpret cells+ starting with =, +, -, @, tab, or carriage return as formulas. Prefixing+ with a single quote forces them to be treated as plain text.+ """+ if not isinstance(value, str):+ return value+ if value and value[0] in _FORMULA_TRIGGER_CHARS:+ return f"'{value}"+ return valuediff --git a/posthog/session_recordings/synthetic_playlists.py b/posthog/session_recordings/synthetic_playlists.pyindex a03c3d4ac643..ad5274cdd51a 100644--- a/posthog/session_recordings/synthetic_playlists.py+++ b/posthog/session_recordings/synthetic_playlists.py@@ -20,11 +20,12 @@ from posthog.schema import RecordingOrder, RecordingsQueryfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.models import Comment, Team, User-from posthog.models.exported_asset import ExportedAssetfrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.session_recordings.models.session_recording_event import SessionRecordingViewedfrom posthog.session_recordings.session_recording_api import list_recordings_from_query+from products.exports.backend.models.exported_asset import ExportedAsset+try:from ee.models.session_summaries import SingleSessionSummarydiff --git a/posthog/session_recordings/test/test_synthetic_playlists.py b/posthog/session_recordings/test/test_synthetic_playlists.pyindex 824b92b72fb4..4619d15ac2a0 100644--- a/posthog/session_recordings/test/test_synthetic_playlists.py+++ b/posthog/session_recordings/test/test_synthetic_playlists.py@@ -10,7 +10,6 @@ from parameterized import parameterizedfrom rest_framework import statusfrom posthog.models import Comment, SessionRecordingPlaylist-from posthog.models.exported_asset import ExportedAssetfrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.utils import uuid7from posthog.session_recordings.models.session_recording_event import SessionRecordingViewed@@ -19,6 +18,8 @@ from posthog.session_recordings.synthetic_playlists import (NewUrlsSyntheticPlaylistSource,)+from products.exports.backend.models.exported_asset import ExportedAsset+try:from ee.models.session_summaries import SingleSessionSummarydiff --git a/posthog/settings/logs.py b/posthog/settings/logs.pyindex 4b215057436e..0ec9261d5f59 100644--- a/posthog/settings/logs.py+++ b/posthog/settings/logs.py@@ -95,7 +95,7 @@ LOGGING = {"posthog.tasks.alerts": {"level": "INFO", "handlers": ["console"], "propagate": False},"posthog.tasks.split_person": {"level": "INFO", "handlers": ["console"], "propagate": False},"posthog.tasks.email": {"level": "INFO", "handlers": ["console"], "propagate": False},- "posthog.tasks.exports": {"level": "INFO", "handlers": ["console"], "propagate": False},+ "products.exports.backend.tasks": {"level": "INFO", "handlers": ["console"], "propagate": False},"posthog.tasks.ai_observability_usage_report": {"level": "INFO", "handlers": ["console"], "propagate": False},"posthog.tasks.hypercache_verification": {"level": "INFO", "handlers": ["console"], "propagate": False},"posthog.storage.hypercache_verifier": {"level": "INFO", "handlers": ["console"], "propagate": False},diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 7b8a8a946eb5..2aa10d690359 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -82,6 +82,9 @@ PRODUCTS_APPS = ["products.actions.backend.apps.ActionsConfig","products.product_analytics.backend.apps.ProductAnalyticsConfig","products.wizard.backend.apps.WizardConfig",+ "products.exports.backend.apps.ExportsConfig",+ "products.annotations.backend.apps.AnnotationsConfig",+ "products.batch_exports.backend.apps.BatchExportsConfig","products.engineering_analytics.backend.apps.EngineeringAnalyticsConfig",]@@ -464,7 +467,7 @@ SPECTACULAR_SETTINGS = {"MCPAuthTypeEnum": "products.mcp_store.backend.models.AUTH_TYPE_CHOICES","TaskRunStatusEnum": "products.tasks.backend.models.TaskRun.Status","TaskRunEnvironmentEnum": "products.tasks.backend.models.TaskRun.Environment",- "ModelEnum": "posthog.batch_exports.models.BatchExport.Model",+ "ModelEnum": "products.batch_exports.backend.models.batch_export.BatchExport.Model","ScannerModelEnum": "products.replay_vision.backend.models.replay_scanner.ScannerModel","ScannerTypeEnum": "products.replay_vision.backend.models.replay_scanner.ScannerType","ScannerProviderEnum": "products.replay_vision.backend.models.replay_scanner.ScannerProvider",@@ -472,7 +475,7 @@ SPECTACULAR_SETTINGS = {"ObservationTriggerEnum": "products.replay_vision.backend.models.replay_observation.ObservationTrigger","AutonomyPriorityEnum": "products.signals.backend.models.AutonomyPriority","UserInterviewSearchDocumentTypeEnum": "products.user_interviews.backend.facade.enums.SEARCH_DOCUMENT_TYPES",- "BatchExportRunStatusEnum": "posthog.batch_exports.models.BatchExportRun.Status",+ "BatchExportRunStatusEnum": "products.batch_exports.backend.models.batch_export.BatchExportRun.Status",# --- Inline value lists (type-hint enums, no x-spec-enum-id) ---"PropertyGroupOperator": ["AND", "OR"],"PropertyFilterTypeEnum": [diff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 8377ba1f47f4..b3edc009445e 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -14,7 +14,6 @@ from celery import shared_taskfrom posthoganalytics import new_context, tagfrom posthog.api.two_factor_reset import TWO_FACTOR_RESET_TOKEN_TIMEOUT_HOURS-from posthog.batch_exports.models import BatchExport, BatchExportRunfrom posthog.caching.login_device_cache import check_and_cache_login_devicefrom posthog.cloud_utils import is_cloudfrom posthog.constants import AUTH_BACKEND_DISPLAY_NAMES, INVITE_DAYS_VALIDITY@@ -32,6 +31,7 @@ from posthog.ph_client import get_clientfrom posthog.scoping_audit import skip_team_scope_auditfrom posthog.user_permissions import UserPermissions+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportRunfrom products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.cdp.backend.models.plugin import Plugin, PluginConfigfrom products.conversations.backend.models import Ticketdiff --git a/posthog/tasks/exporter.py b/posthog/tasks/exporter.pyindex 2b8e9f19fadd..6b1e8597c8c9 100644--- a/posthog/tasks/exporter.py+++ b/posthog/tasks/exporter.py@@ -7,11 +7,12 @@ from celery import current_task, shared_taskfrom prometheus_client import Counter, Histogramfrom posthog.event_usage import EventSource, groups-from posthog.models import ExportedAssetfrom posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME-from posthog.tasks.exports.failure_handler import USER_QUERY_ERRORS, classify_failure_typefrom posthog.tasks.utils import CeleryQueue+from products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.tasks.failure_handler import USER_QUERY_ERRORS, classify_failure_type+logger = structlog.get_logger(__name__)@@ -81,7 +82,7 @@ def export_asset_direct(max_height_pixels: Optional[int] = None, # For images: max screenshot height in pixelssource: Optional[EventSource] = None, # EventSource value to tag queries with (e.g. "subscription")) -> None:- from posthog.tasks.exports import csv_exporter, image_exporter+ from products.exports.backend.tasks import csv_exporter, image_exporterstart_time = perf_counter()team = exported_asset.teamdiff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.pyindex e1ff1fad604e..43197d3b7542 100644--- a/posthog/tasks/tasks.py+++ b/posthog/tasks/tasks.py@@ -67,7 +67,7 @@ STALE_QUEUED_TASK_RUN_ERRORS_COUNTER = Counter(@shared_task(ignore_result=True)def delete_expired_exported_assets() -> None:- from posthog.models import ExportedAsset+ from products.exports.backend.models.exported_asset import ExportedAssetExportedAsset.delete_expired_assets()diff --git a/posthog/tasks/test/test_email.py b/posthog/tasks/test/test_email.pyindex dbdba80c10f1..d58fbe7a2dd0 100644--- a/posthog/tasks/test/test_email.py+++ b/posthog/tasks/test/test_email.py@@ -12,7 +12,6 @@ from parameterized import parameterizedfrom posthog.api.authentication import password_reset_token_generatorfrom posthog.api.email_verification import email_verification_token_generator-from posthog.batch_exports.models import BatchExport, BatchExportDestination, BatchExportRunfrom posthog.models import Organization, Team, Userfrom posthog.models.app_metrics2.sql import TRUNCATE_APP_METRICS2_TABLE_SQLfrom posthog.models.instance_setting import set_instance_setting@@ -42,6 +41,7 @@ from posthog.tasks.email import ()from posthog.tasks.test.utils_email_tests import mock_email_messages+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRunfrom products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.cdp.backend.models.plugin import Plugin, PluginConfigdiff --git a/posthog/tasks/test/test_exporter.py b/posthog/tasks/test/test_exporter.pyindex 30967e146dd7..80cdae3d6a64 100644--- a/posthog/tasks/test/test_exporter.py+++ b/posthog/tasks/test/test_exporter.py@@ -11,12 +11,16 @@ from parameterized import parameterizedfrom posthog.hogql.errors import QueryErrorfrom posthog.errors import CHQueryErrorTooManySimultaneousQueries-from posthog.models.exported_asset import ExportedAssetfrom posthog.tasks import exporter-from posthog.tasks.exports.failure_handler import FAILURE_TYPE_SYSTEM, FAILURE_TYPE_USER, is_user_query_error_type-from posthog.tasks.exports.image_exporter import get_driverfrom products.dashboards.backend.models.dashboard import Dashboard+from products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.tasks.failure_handler import (+ FAILURE_TYPE_SYSTEM,+ FAILURE_TYPE_USER,+ is_user_query_error_type,+)+from products.exports.backend.tasks.image_exporter import get_driverclass TestIsUserQueryErrorType(TestCase):@@ -56,7 +60,7 @@ class MockWebDriver(MagicMock):return None # Never return anything for Spinner-@patch("posthog.tasks.exports.image_exporter.uuid")+@patch("products.exports.backend.tasks.image_exporter.uuid")class TestExporterTask(APIBaseTest):exported_asset: ExportedAsset = None # type: ignore@@ -73,7 +77,7 @@ class TestExporterTask(APIBaseTest):with open("/tmp/posthog_test_exporter.png", "wb") as fh:fh.write(base64.decodebytes(example_png))- @patch("posthog.tasks.exports.image_exporter.get_driver")+ @patch("products.exports.backend.tasks.image_exporter.get_driver")def test_exporter_runs(self, mock_get_driver: MagicMock, mock_uuid: MagicMock) -> None:mock_uuid.uuid4.return_value = "posthog_test_exporter"mock_get_driver.return_value = MockWebDriver()@@ -98,7 +102,7 @@ class TestExporterTask(APIBaseTest):if driver:driver.close()- @patch("posthog.tasks.exports.image_exporter.export_image")+ @patch("products.exports.backend.tasks.image_exporter.export_image")def test_export_stores_exception_type_on_failure(self, mock_export: MagicMock, mock_uuid: MagicMock) -> None:mock_export.side_effect = QueryError("Unknown table 'foo'")@@ -112,7 +116,7 @@ class TestExporterTask(APIBaseTest):class TestExportAssetFailureRecording(APIBaseTest):- @patch("posthog.tasks.exports.image_exporter.export_image")+ @patch("products.exports.backend.tasks.image_exporter.export_image")def test_non_retriable_error_records_failure_and_does_not_raise(self, mock_export_direct: MagicMock) -> None:mock_export_direct.side_effect = QueryError("Invalid query syntax")@@ -128,7 +132,7 @@ class TestExportAssetFailureRecording(APIBaseTest):assert asset.exception_type == "QueryError"assert asset.failure_type == "user"- @patch("posthog.tasks.exports.image_exporter.export_image")+ @patch("products.exports.backend.tasks.image_exporter.export_image")def test_transient_error_records_failure_without_retry(self, mock_export_direct: MagicMock) -> None:mock_export_direct.side_effect = CHQueryErrorTooManySimultaneousQueries("Too many queries")diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.pyindex 1ed37cc95f2a..c31220001c6b 100644--- a/posthog/tasks/test/test_usage_report.py+++ b/posthog/tasks/test/test_usage_report.py@@ -33,7 +33,6 @@ from posthog.schema import EventsQueryfrom posthog.hogql.query import execute_hogql_query-from posthog.batch_exports.models import BatchExport, BatchExportDestination, BatchExportRunfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.client.connection import ClickHouseUserfrom posthog.clickhouse.logs.logs32 import TABLE_NAME as LOGS_LOCAL_TABLE@@ -63,6 +62,7 @@ from posthog.test.fixtures import create_app_metric2from posthog.test.test_utils import create_group_type_mapping_without_created_atfrom posthog.utils import get_previous_day+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRunfrom products.cdp.backend.models.plugin import Plugin, PluginConfigfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuerydiff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.pyindex a1450c953795..7af6e82a0eb2 100644--- a/posthog/tasks/usage_report.py+++ b/posthog/tasks/usage_report.py@@ -25,7 +25,6 @@ from retry import retryfrom posthog.schema import AIEventTypefrom posthog import version_requirement-from posthog.batch_exports.models import BatchExportDestination, BatchExportRunfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.client.connection import ClickHouseUser, Workloadfrom posthog.clickhouse.query_tagging import Feature, Product, tags_context@@ -33,7 +32,7 @@ from posthog.cloud_utils import get_cached_instance_licensefrom posthog.constants import FlagRequestTypefrom posthog.exceptions_capture import capture_exceptionfrom posthog.logging.timing import timed_log-from posthog.models import BatchExport, GroupTypeMapping, OrganizationMembership, User+from posthog.models import GroupTypeMapping, OrganizationMembership, Userfrom posthog.models.organization import Organizationfrom posthog.models.property.util import get_property_string_exprfrom posthog.models.team.team import Team@@ -44,6 +43,7 @@ from posthog.tasks.report_utils import capture_eventfrom posthog.tasks.utils import CeleryQueuefrom posthog.utils import get_helm_info_env, get_instance_realm, get_instance_region, get_previous_day+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRunfrom products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionTypefrom products.cdp.backend.models.plugin import PluginConfigfrom products.dashboards.backend.models.dashboard import Dashboarddiff --git a/posthog/temporal/alerts/retry_policy.py b/posthog/temporal/alerts/retry_policy.pyindex b9ca4799d216..5106130a7ea7 100644--- a/posthog/temporal/alerts/retry_policy.py+++ b/posthog/temporal/alerts/retry_policy.py@@ -2,7 +2,7 @@ import datetime as dtfrom temporalio.common import RetryPolicy-from posthog.tasks.exports.failure_handler import USER_QUERY_ERROR_NAMES+from products.exports.backend.tasks.failure_handler import USER_QUERY_ERROR_NAMESALERT_PREPARE_RETRY_POLICY = RetryPolicy(initial_interval=dt.timedelta(seconds=1),diff --git a/posthog/temporal/event_screenshots/activities.py b/posthog/temporal/event_screenshots/activities.pyindex a8e2c1b41a18..e4b14b95c314 100644--- a/posthog/temporal/event_screenshots/activities.py+++ b/posthog/temporal/event_screenshots/activities.py@@ -4,7 +4,7 @@ from django.db import connectionfrom temporalio import activity-from posthog.models import ExportedAsset, ObjectMediaPreview+from posthog.models import ObjectMediaPreviewfrom posthog.sync import database_sync_to_asyncfrom posthog.tasks.exporter import export_asset_directfrom posthog.temporal.common.clickhouse import get_client as get_ch_client@@ -18,6 +18,8 @@ from posthog.temporal.event_screenshots.types import (TakeEventScreenshotResult,)+from products.exports.backend.models.exported_asset import ExportedAsset+LOGGER = get_write_only_logger()diff --git a/posthog/temporal/exports/activities.py b/posthog/temporal/exports/activities.pyindex 99d39f8404de..a17453da2dda 100644--- a/posthog/temporal/exports/activities.py+++ b/posthog/temporal/exports/activities.py@@ -5,14 +5,15 @@ import temporalio.activityfrom temporalio.exceptions import ApplicationErrorfrom posthog.event_usage import EventSource-from posthog.models.exported_asset import ExportedAssetfrom posthog.sync import database_sync_to_asyncfrom posthog.tasks import exporter-from posthog.tasks.exports.failure_handler import SYSTEM_ERROR_NAMESfrom posthog.temporal.common.errors import MAX_ERROR_MESSAGE_CHARS, MAX_ERROR_TRACE_CHARS, truncate_for_temporal_payloadfrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.exports.types import ExportAssetActivityInputs, ExportAssetResult+from products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.tasks.failure_handler import SYSTEM_ERROR_NAMES+logger = structlog.get_logger(__name__)diff --git a/posthog/temporal/exports/retry_policy.py b/posthog/temporal/exports/retry_policy.pyindex 39d7f13f7cb4..793d12fa48b8 100644--- a/posthog/temporal/exports/retry_policy.py+++ b/posthog/temporal/exports/retry_policy.py@@ -2,7 +2,7 @@ from datetime import timedeltafrom temporalio.common import RetryPolicy-from posthog.tasks.exports.failure_handler import USER_QUERY_ERROR_NAMES+from products.exports.backend.tasks.failure_handler import USER_QUERY_ERROR_NAMESEXPORT_RETRY_POLICY = RetryPolicy(initial_interval=timedelta(seconds=30),diff --git a/posthog/temporal/exports/workflows.py b/posthog/temporal/exports/workflows.pyindex 835f02af89bd..089b8aa415f5 100644--- a/posthog/temporal/exports/workflows.py+++ b/posthog/temporal/exports/workflows.py@@ -6,13 +6,14 @@ import temporalio.workflow as wffrom posthog.event_usage import EventSourcefrom posthog.slo.types import SloConfig, SloOutcome-from posthog.tasks.exports.failure_handler import is_user_query_error_typefrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.errors import resolve_exception_classfrom posthog.temporal.exports.activities import export_asset_activityfrom posthog.temporal.exports.retry_policy import EXPORT_RETRY_POLICYfrom posthog.temporal.exports.types import ExportAssetActivityInputs+from products.exports.backend.tasks.failure_handler import is_user_query_error_type+@dataclasses.dataclassclass ExportAssetWorkflowInputs:diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex 564f3d091c9c..c71f1bfe998b 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -70,13 +70,13 @@ from posthog.temporal.session_replay.replay_count_metrics.types import ReplayCoufrom posthog.temporal.session_replay.summarization_sweep.reconciler import (create_summarization_sweep_reconciler_schedule,)-from posthog.temporal.subscriptions.types import ScheduleAllSubscriptionsWorkflowInputsfrom posthog.temporal.usage_report.types import RunUsageReportsInputsfrom posthog.temporal.warehouse_sources_queue_partition_management.schedule import (create_warehouse_sources_queue_partition_management_schedule,)from posthog.temporal.weekly_digest.types import WeeklyDigestInput+from products.exports.backend.temporal.subscriptions.types import ScheduleAllSubscriptionsWorkflowInputsfrom products.replay_vision.backend.temporal.reconciler import create_replay_vision_reconciler_schedulefrom products.signals.backend.temporal.agentic.schedule import create_signals_scout_coordinator_schedulefrom products.web_analytics.backend.temporal.weekly_digest.types import WAWeeklyDigestInputdiff --git a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.pyindex 1269b2f590b8..2b085ccbca32 100644--- a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py+++ b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py@@ -4,9 +4,10 @@ from django.db import close_old_connections, transactionimport structlogfrom temporalio import activity-from posthog.models.exported_asset import ExportedAssetfrom posthog.storage import object_storage+from products.exports.backend.models.exported_asset import ExportedAsset+from ..types import (BuildRasterizationResult,FinalizeRasterizationInput,diff --git a/posthog/temporal/session_replay/session_summary/activities/video_based/a1_prep_session_video_asset.py b/posthog/temporal/session_replay/session_summary/activities/video_based/a1_prep_session_video_asset.pyindex 122e44e0707d..9d317777690e 100644--- a/posthog/temporal/session_replay/session_summary/activities/video_based/a1_prep_session_video_asset.py+++ b/posthog/temporal/session_replay/session_summary/activities/video_based/a1_prep_session_video_asset.py@@ -7,7 +7,6 @@ import structlogimport temporaliofrom posthog.models import Team-from posthog.models.exported_asset import ExportedAssetfrom posthog.session_recordings.queries.session_replay_events import SessionReplayEventsfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.session_replay.session_summary.types.video import (@@ -15,6 +14,8 @@ from posthog.temporal.session_replay.session_summary.types.video import (VideoSummarySingleSessionInputs,)+from products.exports.backend.models.exported_asset import ExportedAsset+from ee.hogai.session_summaries.constants import (EXPIRES_AFTER_DAYS,FULL_VIDEO_EXPORT_FORMAT,diff --git a/posthog/temporal/session_replay/session_summary/activities/video_based/a2_upload_video_to_gemini.py b/posthog/temporal/session_replay/session_summary/activities/video_based/a2_upload_video_to_gemini.pyindex 772228ca3f1b..6465b77d658b 100644--- a/posthog/temporal/session_replay/session_summary/activities/video_based/a2_upload_video_to_gemini.py+++ b/posthog/temporal/session_replay/session_summary/activities/video_based/a2_upload_video_to_gemini.py@@ -15,7 +15,6 @@ from google.genai import (from posthog.schema import ReplayInactivityPeriod-from posthog.models.exported_asset import ExportedAssetfrom posthog.storage import object_storagefrom posthog.temporal.session_replay.gemini_cleanup_sweep.tracking import track_uploaded_filefrom posthog.temporal.session_replay.session_summary.types.video import (@@ -24,6 +23,8 @@ from posthog.temporal.session_replay.session_summary.types.video import (VideoSummarySingleSessionInputs,)+from products.exports.backend.models.exported_asset import ExportedAsset+from ee.hogai.session_summaries.constants import MOMENT_VIDEO_EXPORT_FORMATfrom ee.hogai.videos.utils import get_video_duration_sdiff --git a/posthog/temporal/tests/test_export_activities.py b/posthog/temporal/tests/test_export_activities.pyindex 6109af78a344..8f3e360c9a58 100644--- a/posthog/temporal/tests/test_export_activities.py+++ b/posthog/temporal/tests/test_export_activities.py@@ -15,13 +15,14 @@ from temporalio.exceptions import ActivityErrorfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker-from posthog.models.exported_asset import ExportedAsset-from posthog.tasks.exports.failure_handler import ExcelColumnLimitExceededfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.exports.activities import export_asset_activityfrom posthog.temporal.exports.retry_policy import EXPORT_RETRY_POLICYfrom posthog.temporal.exports.types import ExportAssetActivityInputs, ExportAssetResult+from products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.tasks.failure_handler import ExcelColumnLimitExceeded+pytestmark = [pytest.mark.asyncio, pytest.mark.django_db(transaction=True)]diff --git a/posthog/temporal/tests/test_export_workflow.py b/posthog/temporal/tests/test_export_workflow.pyindex 0bb4bb3c853a..555ae0ad3cef 100644--- a/posthog/temporal/tests/test_export_workflow.py+++ b/posthog/temporal/tests/test_export_workflow.py@@ -12,12 +12,13 @@ from temporalio.worker import UnsandboxedWorkflowRunner, Workerfrom posthog.hogql.errors import QueryErrorfrom posthog.errors import CHQueryErrorS3Error-from posthog.models.exported_asset import ExportedAssetfrom posthog.slo.types import SloArea, SloConfig, SloOperation, SloOutcomefrom posthog.temporal.common.slo_interceptor import SloInterceptorfrom posthog.temporal.exports.activities import export_asset_activityfrom posthog.temporal.exports.workflows import ExportAssetWorkflow, ExportAssetWorkflowInputs+from products.exports.backend.models.exported_asset import ExportedAsset+pytestmark = [pytest.mark.asyncio, pytest.mark.django_db(transaction=True)]EXPORT_FORMAT = ExportedAsset.ExportFormat.PNGdiff --git a/posthog/temporal/tests/test_subscriptions_workflows.py b/posthog/temporal/tests/test_subscriptions_workflows.pyindex 1dfa54f787d0..6d1c4445ab45 100644--- a/posthog/temporal/tests/test_subscriptions_workflows.py+++ b/posthog/temporal/tests/test_subscriptions_workflows.py@@ -21,15 +21,18 @@ from temporalio.worker import UnsandboxedWorkflowRunner, Workerfrom posthog.hogql.errors import QueryErrorfrom posthog.errors import CHQueryErrorS3Error-from posthog.models.exported_asset import ExportedAssetfrom posthog.models.instance_setting import set_instance_settingfrom posthog.models.integration import Integration-from posthog.models.subscription import Subscription, SubscriptionDeliveryfrom posthog.slo.types import SloArea, SloConfig, SloOperation, SloOutcome-from posthog.tasks.exports.failure_handler import ExcelColumnLimitExceededfrom posthog.temporal.common.slo_interceptor import SloInterceptorfrom posthog.temporal.exports.activities import export_asset_activity-from posthog.temporal.subscriptions.activities import (++from products.dashboards.backend.models.dashboard import Dashboard+from products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.models.subscription import Subscription, SubscriptionDelivery+from products.exports.backend.tasks.failure_handler import ExcelColumnLimitExceeded+from products.exports.backend.temporal.subscriptions.activities import (advance_next_delivery_date,create_delivery_record,create_export_assets,@@ -38,7 +41,7 @@ from posthog.temporal.subscriptions.activities import (update_delivery_record,validate_subscription_for_delivery,)-from posthog.temporal.subscriptions.types import (+from products.exports.backend.temporal.subscriptions.types import (CreateDeliveryRecordInputs,CreateExportAssetsInputs,DeliverSubscriptionInputs,@@ -50,14 +53,11 @@ from posthog.temporal.subscriptions.types import (TrackedSubscriptionInputs,UpdateDeliveryRecordInputs,)-from posthog.temporal.subscriptions.workflows import (+from products.exports.backend.temporal.subscriptions.workflows import (HandleSubscriptionValueChangeWorkflow,ProcessSubscriptionWorkflow,ScheduleAllSubscriptionsWorkflow,)--from products.dashboards.backend.models.dashboard import Dashboard-from products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.product_analytics.backend.models.insight import Insightfrom ee.tasks.subscriptions.slack_subscriptions import SlackDeliveryResult@@ -115,7 +115,7 @@ async def subscriptions_worker(temporal_client: Client):@patch("posthog.temporal.exports.activities.exporter")@patch("posthog.slo.events.posthoganalytics")@patch("ee.tasks.subscriptions.get_metric_meter")-@patch("posthog.temporal.subscriptions.activities.send_email_subscription_report")+@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")@freeze_time("2022-02-02T08:55:00.000Z")@pytest.mark.asyncioasync def test_subscription_delivery_scheduling(@@ -191,8 +191,8 @@ async def test_subscription_delivery_scheduling(@patch("posthog.temporal.exports.activities.exporter")@patch("posthog.slo.events.posthoganalytics")@patch("ee.tasks.subscriptions.get_metric_meter")-@patch("posthog.temporal.subscriptions.activities.get_slack_integration_for_team", return_value=None)-@patch("posthog.temporal.subscriptions.activities.send_email_subscription_report")+@patch("products.exports.backend.temporal.subscriptions.activities.get_slack_integration_for_team", return_value=None)+@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")@freeze_time("2022-02-02T08:55:00.000Z")@pytest.mark.asyncioasync def test_does_not_schedule_subscription_if_item_is_deleted(@@ -255,7 +255,7 @@ async def test_does_not_schedule_subscription_if_item_is_deleted(@patch("posthog.temporal.exports.activities.exporter")@patch("posthog.slo.events.posthoganalytics")@patch("ee.tasks.subscriptions.get_metric_meter")-@patch("posthog.temporal.subscriptions.activities.send_email_subscription_report")+@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")@pytest.mark.asyncioasync def test_handle_subscription_value_change_email(mock_send_email: MagicMock,@@ -329,8 +329,11 @@ async def test_handle_subscription_value_change_email(assert completed_calls[0].kwargs["properties"]["outcome"] == SloOutcome.SUCCESS-@patch("posthog.temporal.subscriptions.activities.send_slack_message_with_integration_async", new_callable=AsyncMock)-@patch("posthog.temporal.subscriptions.activities.get_slack_integration_for_team")+@patch(+ "products.exports.backend.temporal.subscriptions.activities.send_slack_message_with_integration_async",+ new_callable=AsyncMock,+)+@patch("products.exports.backend.temporal.subscriptions.activities.get_slack_integration_for_team")@patch("posthog.temporal.exports.activities.exporter")@patch("posthog.slo.events.posthoganalytics")@patch("ee.tasks.subscriptions.get_metric_meter")@@ -403,8 +406,8 @@ async def test_deliver_subscription_report_slack(@patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription")-@patch("posthog.temporal.subscriptions.activities.build_insight_delivery_snapshot")-@patch("posthog.temporal.subscriptions.activities.get_slack_integration_for_team", return_value=None)+@patch("products.exports.backend.temporal.subscriptions.activities.build_insight_delivery_snapshot")+@patch("products.exports.backend.temporal.subscriptions.activities.get_slack_integration_for_team", return_value=None)@freeze_time("2022-02-02T08:55:00.000Z")@pytest.mark.asyncioasync def test_process_subscription_records_missing_slack_integration_failure(@@ -534,10 +537,12 @@ async def test_deliver_subscription_auto_disables_invalid_subscriptions(patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription") as send_mock,# Always patched — only consulted on the slack branch, harmless otherwise.patch(- "posthog.temporal.subscriptions.activities.get_slack_integration_for_team",+ "products.exports.backend.temporal.subscriptions.activities.get_slack_integration_for_team",return_value=None,),- patch("posthog.temporal.subscriptions.activities._capture_delivery_failed_event") as capture_mock,+ patch(+ "products.exports.backend.temporal.subscriptions.activities._capture_delivery_failed_event"+ ) as capture_mock,):result = await env.run(deliver_subscription,@@ -580,7 +585,9 @@ async def test_no_assets_does_not_auto_disable(team, user):with (patch("ee.tasks.subscriptions.auto_disable.disable_invalid_subscription") as disable_mock,- patch("posthog.temporal.subscriptions.activities._capture_delivery_failed_event") as capture_mock,+ patch(+ "products.exports.backend.temporal.subscriptions.activities._capture_delivery_failed_event"+ ) as capture_mock,):# Bogus id ensures `assets` resolves empty.result = await env.run(@@ -635,7 +642,9 @@ async def test_deliver_subscription_retry_idempotent_after_auto_disable(team, us# First call: unsupported_target triggers auto-disable + per-recipient failure.with (patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription") as send_mock,- patch("posthog.temporal.subscriptions.activities._capture_delivery_failed_event") as capture_mock,+ patch(+ "products.exports.backend.temporal.subscriptions.activities._capture_delivery_failed_event"+ ) as capture_mock,):first_result = await env.run(deliver_subscription, inputs)@@ -653,7 +662,9 @@ async def test_deliver_subscription_retry_idempotent_after_auto_disable(team, us# so the disable email and analytics event do NOT fire again.with (patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription") as send_mock,- patch("posthog.temporal.subscriptions.activities._capture_delivery_failed_event") as capture_mock,+ patch(+ "products.exports.backend.temporal.subscriptions.activities._capture_delivery_failed_event"+ ) as capture_mock,):second_result = await env.run(deliver_subscription, inputs)@@ -695,7 +706,9 @@ async def test_validate_subscription_for_delivery(env = ActivityEnvironment()with (patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription") as send_mock,- patch("posthog.temporal.subscriptions.activities._capture_delivery_failed_event") as capture_mock,+ patch(+ "products.exports.backend.temporal.subscriptions.activities._capture_delivery_failed_event"+ ) as capture_mock,):abort_info = await env.run(validate_subscription_for_delivery, subscription.id)@@ -739,7 +752,9 @@ async def test_deliver_subscription_short_circuits_when_already_disabled(team, uenv = ActivityEnvironment()- with patch("posthog.temporal.subscriptions.activities.disable_invalid_subscription") as disable_mock:+ with patch(+ "products.exports.backend.temporal.subscriptions.activities.disable_invalid_subscription"+ ) as disable_mock:result = await env.run(deliver_subscription,DeliverSubscriptionInputs(@@ -808,15 +823,17 @@ async def test_deliver_subscription_handles_slack_api_errors(team, user, slack_ewith (patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription") as send_mock,patch(- "posthog.temporal.subscriptions.activities.get_slack_integration_for_team",+ "products.exports.backend.temporal.subscriptions.activities.get_slack_integration_for_team",return_value=mock_integration,),patch(- "posthog.temporal.subscriptions.activities.send_slack_message_with_integration_async",+ "products.exports.backend.temporal.subscriptions.activities.send_slack_message_with_integration_async",new_callable=AsyncMock,side_effect=slack_error,),- patch("posthog.temporal.subscriptions.activities._capture_delivery_failed_event") as capture_mock,+ patch(+ "products.exports.backend.temporal.subscriptions.activities._capture_delivery_failed_event"+ ) as capture_mock,):if expect_auto_disable:result = await ActivityEnvironment().run(deliver_subscription, inputs)@@ -883,7 +900,7 @@ async def test_create_export_assets_creates_exported_assets()-@patch("posthog.temporal.subscriptions.activities.build_insight_delivery_snapshot")+@patch("products.exports.backend.temporal.subscriptions.activities.build_insight_delivery_snapshot")@patch("posthog.slo.events.posthoganalytics")@freeze_time("2022-02-02T08:55:00.000Z")@pytest.mark.asyncio@@ -1225,7 +1242,7 @@ async def test_create_export_assets_empty_dashboard(team, user):@patch("ee.tasks.subscriptions.get_metric_meter")-@patch("posthog.temporal.subscriptions.activities.send_email_subscription_report")+@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")@freeze_time("2022-02-02T08:55:00.000Z")@pytest.mark.asyncioasync def test_deliver_subscription_sends_email(@@ -1261,7 +1278,7 @@ async def test_deliver_subscription_sends_email(@patch("posthog.temporal.exports.activities.exporter")@patch("posthog.slo.events.posthoganalytics")@patch("ee.tasks.subscriptions.get_metric_meter")-@patch("posthog.temporal.subscriptions.activities.send_email_subscription_report")+@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")@freeze_time("2022-02-02T08:55:00.000Z")@pytest.mark.asyncioasync def test_deliver_subscription_workflow_end_to_end(@@ -1336,7 +1353,7 @@ async def test_deliver_subscription_workflow_end_to_end(@patch("posthog.temporal.exports.activities.exporter")@patch("posthog.slo.events.posthoganalytics")@patch("ee.tasks.subscriptions.get_metric_meter")-@patch("posthog.temporal.subscriptions.activities.send_email_subscription_report")+@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")@pytest.mark.asyncioasync def test_new_subscription_sends_invite_email(mock_send_email: MagicMock,@@ -1400,7 +1417,7 @@ async def test_new_subscription_sends_invite_email(@patch("posthog.temporal.exports.activities.exporter")@patch("posthog.slo.events.posthoganalytics")@patch("ee.tasks.subscriptions.get_metric_meter")-@patch("posthog.temporal.subscriptions.activities.send_email_subscription_report")+@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")@pytest.mark.asyncioasync def test_manual_send_uses_regular_template_not_invite(mock_send_email: MagicMock,@@ -1460,7 +1477,7 @@ async def test_manual_send_uses_regular_template_not_invite(@patch("posthog.temporal.exports.activities.exporter")@patch("posthog.slo.events.posthoganalytics")@patch("ee.tasks.subscriptions.get_metric_meter")-@patch("posthog.temporal.subscriptions.activities.send_email_subscription_report")+@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")@freeze_time("2022-02-02T08:55:00.000Z")@pytest.mark.asyncioasync def test_scheduled_delivery_updates_next_delivery_date(@@ -1548,7 +1565,7 @@ def _make_export_counter(fail_count: int, error_factory):@patch("posthog.temporal.exports.activities.exporter")@patch("posthog.slo.events.posthoganalytics")@patch("ee.tasks.subscriptions.get_metric_meter")-@patch("posthog.temporal.subscriptions.activities.send_email_subscription_report")+@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")@freeze_time("2022-02-02T08:55:00.000Z")@pytest.mark.asyncioasync def test_export_error_slo_outcome(@@ -1633,7 +1650,7 @@ async def test_export_error_slo_outcome(@patch("posthog.temporal.exports.activities.exporter")@patch("posthog.slo.events.posthoganalytics")@patch("ee.tasks.subscriptions.get_metric_meter")-@patch("posthog.temporal.subscriptions.activities.send_email_subscription_report")+@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")@freeze_time("2022-02-02T08:55:00.000Z")@pytest.mark.asyncioasync def test_partial_export_failure_delivers_successful_assets(@@ -1730,8 +1747,8 @@ async def test_partial_export_failure_delivers_successful_assets(@patch("posthog.temporal.exports.activities.exporter")@patch("posthog.slo.events.posthoganalytics")@patch("ee.tasks.subscriptions.get_metric_meter")-@patch("posthog.temporal.subscriptions.activities.send_email_subscription_report")-@patch("posthog.temporal.subscriptions.activities.build_insight_delivery_snapshot")+@patch("products.exports.backend.temporal.subscriptions.activities.send_email_subscription_report")+@patch("products.exports.backend.temporal.subscriptions.activities.build_insight_delivery_snapshot")@pytest.mark.asyncioasync def test_workflow_survives_large_insight_snapshot(mock_build_snapshot: MagicMock,@@ -1864,8 +1881,8 @@ async def test_fetch_due_subscriptions_excludes_disabled(team, user):@patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription")-@patch("posthog.temporal.subscriptions.activities.build_insight_delivery_snapshot")-@patch("posthog.temporal.subscriptions.activities.get_slack_integration_for_team", return_value=None)+@patch("products.exports.backend.temporal.subscriptions.activities.build_insight_delivery_snapshot")+@patch("products.exports.backend.temporal.subscriptions.activities.get_slack_integration_for_team", return_value=None)@patch("posthog.temporal.exports.activities.exporter")@patch("posthog.slo.events.posthoganalytics")@freeze_time("2022-02-02T08:55:00.000Z")diff --git a/posthog/temporal/tests/utils/models.py b/posthog/temporal/tests/utils/models.pyindex 02e846c02cec..e3b442e79de0 100644--- a/posthog/temporal/tests/utils/models.py+++ b/posthog/temporal/tests/utils/models.py@@ -5,8 +5,12 @@ import uuidimport temporalio.clientfrom asgiref.sync import sync_to_async-from posthog.batch_exports.models import BatchExport, BatchExportBackfill, BatchExportDestination, BatchExportRun-+from products.batch_exports.backend.models.batch_export import (+ BatchExport,+ BatchExportBackfill,+ BatchExportDestination,+ BatchExportRun,+)from products.batch_exports.backend.service import sync_batch_exportdiff --git a/posthog/test/activity_log_utils.py b/posthog/test/activity_log_utils.pyindex 0d774b9d1a29..5741c6bd9a02 100644--- a/posthog/test/activity_log_utils.py+++ b/posthog/test/activity_log_utils.py@@ -493,7 +493,7 @@ class ActivityLogTestHelper(APILicensedTest):# BatchExportdef create_batch_export(self, name: str = "Test Export", **kwargs) -> dict[str, Any]:"""Create a batch export via direct model creation (like the original tests)."""- from posthog.batch_exports.models import BatchExport, BatchExportDestination+ from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination# Create destination first (like the original tests do)destination = BatchExportDestination.objects.create(@@ -518,7 +518,7 @@ class ActivityLogTestHelper(APILicensedTest):def update_batch_export(self, export_id: str, updates: dict[str, Any]) -> dict[str, Any]:"""Update a batch export via direct model access (like the original tests)."""- from posthog.batch_exports.models import BatchExport+ from products.batch_exports.backend.models.batch_export import BatchExportbatch_export = BatchExport.objects.get(id=export_id)for field, value in updates.items():diff --git a/posthog/test/activity_logging/test_batch_export_activity_logging.py b/posthog/test/activity_logging/test_batch_export_activity_logging.pyindex 6ce1c854119c..7a841af546f7 100644--- a/posthog/test/activity_logging/test_batch_export_activity_logging.py+++ b/posthog/test/activity_logging/test_batch_export_activity_logging.py@@ -1,6 +1,7 @@-from posthog.batch_exports.models import BatchExport, BatchExportDestinationfrom posthog.test.activity_log_utils import ActivityLogTestHelper+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination+class TestBatchExportActivityLogging(ActivityLogTestHelper):def create_test_destination(self):diff --git a/posthog/test/activity_logging/test_batch_import_activity_logging.py b/posthog/test/activity_logging/test_batch_import_activity_logging.pyindex 52bb8a14757c..f87b37ca3549 100644--- a/posthog/test/activity_logging/test_batch_import_activity_logging.py+++ b/posthog/test/activity_logging/test_batch_import_activity_logging.py@@ -1,6 +1,7 @@-from posthog.models.batch_imports import BatchImportfrom posthog.test.activity_log_utils import ActivityLogTestHelper+from products.batch_exports.backend.models.batch_imports import BatchImport+class TestBatchImportActivityLogging(ActivityLogTestHelper):def test_batch_import_model_has_activity_mixin(self):diff --git a/posthog/batch_exports/debug/__init__.py b/products/annotations/__init__.pysimilarity index 100%rename from posthog/batch_exports/debug/__init__.pyrename to products/annotations/__init__.pydiff --git a/posthog/tasks/exports/__init__.py b/products/annotations/backend/api/__init__.pysimilarity index 100%rename from posthog/tasks/exports/__init__.pyrename to products/annotations/backend/api/__init__.pydiff --git a/posthog/api/annotation.py b/products/annotations/backend/api/annotation.pysimilarity index 99%rename from posthog/api/annotation.pyrename to products/annotations/backend/api/annotation.pyindex a0951a7d020e..02a13a5644de 100644--- a/posthog/api/annotation.py+++ b/products/annotations/backend/api/annotation.py@@ -13,10 +13,10 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.api.shared import UserBasicSerializerfrom posthog.event_usage import report_user_action-from posthog.models import Annotationfrom posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activityfrom posthog.models.signals import model_activity_signal, mutable_receiver+from products.annotations.backend.models.annotation import Annotationfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.product_analytics.backend.models.insight import Insightdiff --git a/posthog/api/annotation_context.py b/products/annotations/backend/api/annotation_context.pysimilarity index 99%rename from posthog/api/annotation_context.pyrename to products/annotations/backend/api/annotation_context.pyindex 647ce02949b0..737fc302733e 100644--- a/posthog/api/annotation_context.py+++ b/products/annotations/backend/api/annotation_context.py@@ -6,9 +6,10 @@ from django.db.models import Qimport structlogfrom posthog.models import Team-from posthog.models.annotation import Annotationfrom posthog.utils import relative_date_parse+from products.annotations.backend.models.annotation import Annotation+logger = structlog.get_logger(__name__)MAX_ANNOTATIONS_FOR_AI_CONTEXT = 50diff --git a/products/annotations/backend/api/test/__init__.py b/products/annotations/backend/api/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/api/test/__snapshots__/test_annotation.ambr b/products/annotations/backend/api/test/__snapshots__/test_annotation.ambrsimilarity index 100%rename from posthog/api/test/__snapshots__/test_annotation.ambrrename to products/annotations/backend/api/test/__snapshots__/test_annotation.ambrdiff --git a/posthog/api/test/test_annotation.py b/products/annotations/backend/api/test/test_annotation.pysimilarity index 97%rename from posthog/api/test/test_annotation.pyrename to products/annotations/backend/api/test/test_annotation.pyindex c5217fe2e598..1ffcdd2a412e 100644--- a/posthog/api/test/test_annotation.py+++ b/products/annotations/backend/api/test/test_annotation.py@@ -11,14 +11,15 @@ from django.utils.timezone import nowfrom parameterized import parameterizedfrom rest_framework import status-from posthog.models import Annotation, Organization, Team, User+from posthog.models import Organization, Team, User+from products.annotations.backend.models.annotation import Annotationfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.product_analytics.backend.models.insight import Insightclass TestAnnotation(APIBaseTest, QueryMatchingTest):- @patch("posthog.api.annotation.report_user_action")+ @patch("products.annotations.backend.api.annotation.report_user_action")def test_retrieving_annotation(self, mock_capture: MagicMock) -> None:Annotation.objects.create(organization=self.organization,@@ -34,7 +35,7 @@ class TestAnnotation(APIBaseTest, QueryMatchingTest):assert len(response["results"]) == 1assert response["results"][0]["content"] == "hello world!"- @patch("posthog.api.annotation.report_user_action")+ @patch("products.annotations.backend.api.annotation.report_user_action")def test_retrieving_annotation_is_not_n_plus_1(self, _mock_capture: MagicMock) -> None:with self.assertNumQueries(FuzzyInt(9, 10)), snapshot_postgres_queries_context(self):response = self.client.get(f"/api/projects/{self.team.id}/annotations/").json()@@ -104,7 +105,7 @@ class TestAnnotation(APIBaseTest, QueryMatchingTest):assert response_2.status_code == 200assert response_2.json()["results"] == []- @patch("posthog.api.annotation.report_user_action")+ @patch("products.annotations.backend.api.annotation.report_user_action")def test_creating_annotation(self, mock_capture: MagicMock) -> None:team2 = Organization.objects.bootstrap(None)[2]@@ -135,7 +136,7 @@ class TestAnnotation(APIBaseTest, QueryMatchingTest):{"scope": "organization", "date_marker": date_marker},)- @patch("posthog.api.annotation.report_user_action")+ @patch("products.annotations.backend.api.annotation.report_user_action")def test_can_create_annotations_as_a_bot(self, mock_capture: MagicMock) -> None:response = self.client.post(f"/api/projects/{self.team.id}/annotations/",@@ -155,7 +156,7 @@ class TestAnnotation(APIBaseTest, QueryMatchingTest):get_created_response = self.client.get(f"/api/projects/{self.team.id}/annotations/{instance.id}/")assert get_created_response.json()["creation_type"] == "GIT"- @patch("posthog.api.annotation.report_user_action")+ @patch("products.annotations.backend.api.annotation.report_user_action")def test_downgrading_scope_from_org_to_project_uses_team_id_from_api(self, mock_capture: MagicMock) -> None:second_team = Team.objects.create(organization=self.organization, name="Second team")test_annotation = Annotation.objects.create(diff --git a/posthog/test/activity_logging/test_annotation_activity_logging.py b/products/annotations/backend/api/test/test_annotation_activity_logging.pysimilarity index 98%rename from posthog/test/activity_logging/test_annotation_activity_logging.pyrename to products/annotations/backend/api/test/test_annotation_activity_logging.pyindex b02c95ad2789..d791b3530dae 100644--- a/posthog/test/activity_logging/test_annotation_activity_logging.py+++ b/products/annotations/backend/api/test/test_annotation_activity_logging.py@@ -1,9 +1,9 @@from typing import Any, castfrom posthog.models.activity_logging.activity_log import ActivityLog-from posthog.models.annotation import Annotationfrom posthog.test.activity_log_utils import ActivityLogTestHelper+from products.annotations.backend.models.annotation import Annotationfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.product_analytics.backend.models.insight import Insightdiff --git a/posthog/api/test/test_annotation_context.py b/products/annotations/backend/api/test/test_annotation_context.pysimilarity index 97%rename from posthog/api/test/test_annotation_context.pyrename to products/annotations/backend/api/test/test_annotation_context.pyindex aefe272ed032..a0ef44efebe6 100644--- a/posthog/api/test/test_annotation_context.py+++ b/products/annotations/backend/api/test/test_annotation_context.py@@ -5,14 +5,15 @@ from posthog.test.base import APIBaseTestfrom parameterized import parameterized-from posthog.api.annotation_context import (+from posthog.models import Organization, Team++from products.annotations.backend.api.annotation_context import (format_annotations_for_prompt,get_annotations_for_ai_context,resolve_dashboard_date_range,resolve_query_date_range,)-from posthog.models import Annotation, Organization, Team-+from products.annotations.backend.models.annotation import Annotationfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.product_analytics.backend.models.insight import Insight@@ -135,7 +136,7 @@ class TestAnnotationContext(APIBaseTest):def test_returns_most_recent_when_window_exceeds_cap(self) -> None:# When the window contains more annotations than the cap, we want the most# recent ones — they're the ones a "what changed?" summary should care about.- from posthog.api.annotation_context import MAX_ANNOTATIONS_FOR_AI_CONTEXT+ from products.annotations.backend.api.annotation_context import MAX_ANNOTATIONS_FOR_AI_CONTEXTtotal = MAX_ANNOTATIONS_FOR_AI_CONTEXT + 5base = datetime(2026, 1, 1, tzinfo=ZoneInfo("UTC"))@@ -278,7 +279,7 @@ class TestAnnotationContext(APIBaseTest):assert "‹core_memory›" in blockdef test_format_annotations_truncates_long_content_and_strips_newlines(self) -> None:- from posthog.api.annotation_context import MAX_ANNOTATION_CONTENT_CHARS+ from products.annotations.backend.api.annotation_context import MAX_ANNOTATION_CONTENT_CHARSblock = format_annotations_for_prompt([diff --git a/products/annotations/backend/apps.py b/products/annotations/backend/apps.pynew file mode 100644index 000000000000..a86b4e5a2ea3--- /dev/null+++ b/products/annotations/backend/apps.py@@ -0,0 +1,8 @@+"""Django app configuration for annotations."""++from django.apps import AppConfig+++class AnnotationsConfig(AppConfig):+ name = "products.annotations.backend"+ label = "annotations"diff --git a/products/annotations/backend/migrations/0001_migrate_annotations_models.py b/products/annotations/backend/migrations/0001_migrate_annotations_models.pynew file mode 100644index 000000000000..56f67c2a1262--- /dev/null+++ b/products/annotations/backend/migrations/0001_migrate_annotations_models.py@@ -0,0 +1,116 @@+# Generated by Django 5.2.14 on 2026-05-27 10:13++import django.utils.timezone+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models+++class Migration(migrations.Migration):+ initial = True++ dependencies = [+ ("dashboards", "0006_migrate_product_analytics_models"),+ ("posthog", "1202_migrate_exports_models"),+ ("product_analytics", "0001_migrate_product_analytics_models"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.CreateModel(+ name="Annotation",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("content", models.CharField(blank=True, max_length=8192, null=True)),+ (+ "created_at",+ models.DateTimeField(default=django.utils.timezone.now, null=True),+ ),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "scope",+ models.CharField(+ choices=[+ ("dashboard_item", "insight"),+ ("dashboard", "dashboard"),+ ("project", "project"),+ ("organization", "organization"),+ ("recording", "recording"),+ ],+ default="dashboard_item",+ max_length=24,+ ),+ ),+ (+ "creation_type",+ models.CharField(+ choices=[("USR", "user"), ("GIT", "GitHub")],+ default="USR",+ max_length=3,+ ),+ ),+ ("date_marker", models.DateTimeField(blank=True, null=True)),+ ("deleted", models.BooleanField(default=False)),+ ("apply_all", models.BooleanField(null=True)),+ ("recording_id", models.UUIDField(blank=True, null=True)),+ ("is_emoji", models.BooleanField(blank=True, default=False, null=True)),+ (+ "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.SET_NULL,+ to="dashboards.dashboard",+ ),+ ),+ (+ "dashboard_item",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to="product_analytics.insight",+ ),+ ),+ (+ "organization",+ models.ForeignKey(+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.organization",+ ),+ ),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ ],+ options={+ "db_table": "posthog_annotation",+ },+ ),+ ],+ database_operations=[+ # No database operations - table already exists with this name+ ],+ ),+ ]diff --git a/products/annotations/backend/migrations/__init__.py b/products/annotations/backend/migrations/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/annotations/backend/migrations/max_migration.txt b/products/annotations/backend/migrations/max_migration.txtnew file mode 100644index 000000000000..b832d4bc9f4b--- /dev/null+++ b/products/annotations/backend/migrations/max_migration.txt@@ -0,0 +1 @@+0001_migrate_annotations_modelsdiff --git a/products/annotations/backend/models/__init__.py b/products/annotations/backend/models/__init__.pynew file mode 100644index 000000000000..b6d7aba4bb8f--- /dev/null+++ b/products/annotations/backend/models/__init__.py@@ -0,0 +1,3 @@+from .annotation import Annotation++__all__ = ["Annotation"]diff --git a/posthog/models/annotation.py b/products/annotations/backend/models/annotation.pysimilarity index 94%rename from posthog/models/annotation.pyrename to products/annotations/backend/models/annotation.pyindex e5c9456c8d92..37a3c7ee2863 100644--- a/posthog/models/annotation.py+++ b/products/annotations/backend/models/annotation.py@@ -27,7 +27,7 @@ class Annotation(ModelActivityMixin, models.Model):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)- 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)scope = models.CharField(max_length=24, choices=Scope, default=Scope.INSIGHT)creation_type = models.CharField(max_length=3, choices=CreationType, default=CreationType.USER)date_marker = models.DateTimeField(null=True, blank=True)@@ -40,6 +40,9 @@ class Annotation(ModelActivityMixin, models.Model):# DEPRECATED: moved to the comment modelis_emoji = deprecate_field(models.BooleanField(default=False, null=True, blank=True))+ class Meta:+ db_table = "posthog_annotation"+@propertydef insight_short_id(self) -> Optional[str]:return self.dashboard_item.short_id if self.dashboard_item is not None else Nonediff --git a/products/annotations/manifest.tsx b/products/annotations/manifest.tsxnew file mode 100644index 000000000000..05d1447a1865--- /dev/null+++ b/products/annotations/manifest.tsx@@ -0,0 +1,23 @@+/**+ * Product manifest for annotations.+ *+ * Defines scenes, routes, URLs, and navigation for this product.+ */+import { ProductManifest } from '../../frontend/src/types'++export const manifest: ProductManifest = {+ name: 'Annotations',+ scenes: {+ // Define scenes here+ },+ routes: {+ // Define routes here+ },+ redirects: {},+ urls: {+ // Define URL helpers here+ },+ fileSystemTypes: {},+ treeItemsNew: [],+ treeItemsProducts: [],+}diff --git a/products/annotations/package.json b/products/annotations/package.jsonnew file mode 100644index 000000000000..3b99880c0344--- /dev/null+++ b/products/annotations/package.json@@ -0,0 +1,6 @@+{+ "name": "@posthog/products-annotations",+ "scripts": {+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"+ }+}diff --git a/products/annotations/product.yaml b/products/annotations/product.yamlnew file mode 100644index 000000000000..4d318d151408--- /dev/null+++ b/products/annotations/product.yaml@@ -0,0 +1,3 @@+name: Annotations+owners:+ - team-product-analyticsdiff --git a/products/annotations/tsconfig.json b/products/annotations/tsconfig.jsonnew file mode 100644index 000000000000..fe425d6fcba8--- /dev/null+++ b/products/annotations/tsconfig.json@@ -0,0 +1,6 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "composite": true+ }+}diff --git a/products/batch_exports/backend/admin/__init__.py b/products/batch_exports/backend/admin/__init__.pynew file mode 100644index 000000000000..08a3ba88fb30--- /dev/null+++ b/products/batch_exports/backend/admin/__init__.py@@ -0,0 +1 @@+from . import batch_imports # noqa: F401diff --git a/posthog/admin/admins/batch_imports.py b/products/batch_exports/backend/admin/batch_imports.pysimilarity index 97%rename from posthog/admin/admins/batch_imports.pyrename to products/batch_exports/backend/admin/batch_imports.pyindex bdf67c3f8b25..9c403cb2e251 100644--- a/posthog/admin/admins/batch_imports.py+++ b/products/batch_exports/backend/admin/batch_imports.py@@ -1,7 +1,7 @@from django import formsfrom django.contrib import admin-from posthog.models.batch_imports import BatchImport+from products.batch_exports.backend.models.batch_imports import BatchImportclass BatchImportAdminForm(forms.ModelForm):diff --git a/posthog/batch_exports/http.py b/products/batch_exports/backend/api/batch_export.pysimilarity index 99%rename from posthog/batch_exports/http.pyrename to products/batch_exports/backend/api/batch_export.pyindex 0ece941a6f95..0116d4151879 100644--- a/posthog/batch_exports/http.py+++ b/products/batch_exports/backend/api/batch_export.py@@ -35,9 +35,8 @@ from posthog.api.log_entries import LogEntryMixinfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.api.utils import action-from posthog.batch_exports.models import BATCH_EXPORT_INTERVALS, S3_FAMILY_TYPES, TIMEZONESfrom posthog.event_usage import groups-from posthog.models import BatchExport, BatchExportBackfill, BatchExportDestination, BatchExportRun, Team, User+from posthog.models import Team, Userfrom posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activityfrom posthog.models.integration import (AzureBlobIntegration,@@ -51,6 +50,15 @@ from posthog.temporal.common.client import sync_connectfrom posthog.utils import relative_date_parse, str_to_boolfrom products.batch_exports.backend.api.destination_tests import get_destination_test+from products.batch_exports.backend.models.batch_export import (+ BATCH_EXPORT_INTERVALS,+ S3_FAMILY_TYPES,+ TIMEZONES,+ BatchExport,+ BatchExportBackfill,+ BatchExportDestination,+ BatchExportRun,+)from products.batch_exports.backend.service import (DESTINATION_WORKFLOWS,BaseBatchExportInputs,diff --git a/posthog/api/batch_imports.py b/products/batch_exports/backend/api/batch_imports.pysimilarity index 99%rename from posthog/api/batch_imports.pyrename to products/batch_exports/backend/api/batch_imports.pyindex 3c2df6db4d7c..444fa6ec132e 100644--- a/posthog/api/batch_imports.py+++ b/products/batch_exports/backend/api/batch_imports.py@@ -16,7 +16,6 @@ from rest_framework.response import Responsefrom posthog.api.documentation import _FallbackSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializer-from posthog.batch_exports.http import resolve_and_validate_urlfrom posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activityfrom posthog.models.activity_logging.batch_import_utils import (extract_batch_import_info,@@ -24,10 +23,12 @@ from posthog.models.activity_logging.batch_import_utils import (get_batch_import_detail_name,)from posthog.models.activity_logging.model_activity import get_current_user, get_was_impersonated-from posthog.models.batch_imports import BatchImport, ContentType, DateRangeExportSourcefrom posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.models.user import User+from products.batch_exports.backend.api.batch_export import resolve_and_validate_url+from products.batch_exports.backend.models.batch_imports import BatchImport, ContentType, DateRangeExportSource+class BatchImportSerializer(serializers.ModelSerializer):"""Serializer for BatchImport model"""diff --git a/products/batch_exports/backend/api/destination_tests/__init__.py b/products/batch_exports/backend/api/destination_tests/__init__.pyindex a512d2df9aa1..c04496166337 100644--- a/products/batch_exports/backend/api/destination_tests/__init__.py+++ b/products/batch_exports/backend/api/destination_tests/__init__.py@@ -1,6 +1,5 @@-from posthog.batch_exports.models import S3_FAMILY_TYPES-from products.batch_exports.backend.api.destination_tests.base import DestinationTest+from products.batch_exports.backend.models.batch_export import S3_FAMILY_TYPESdef get_destination_test(diff --git a/posthog/batch_exports/api/file_download.py b/products/batch_exports/backend/api/file_download.pysimilarity index 99%rename from posthog/batch_exports/api/file_download.pyrename to products/batch_exports/backend/api/file_download.pyindex 78ecc3af7197..f01b73ade849 100644--- a/posthog/batch_exports/api/file_download.py+++ b/products/batch_exports/backend/api/file_download.py@@ -20,9 +20,14 @@ from rest_framework.exceptions import APIException, NotFound, ValidationErrorfrom posthog.api.log_entries import LogEntryMixinfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import action-from posthog.models import BatchExportDestination, BatchExportFileDownload, BatchExportOnDemand, BatchExportRunfrom posthog.temporal.common.client import sync_connect+from products.batch_exports.backend.models.batch_export import (+ BatchExportDestination,+ BatchExportFileDownload,+ BatchExportOnDemand,+ BatchExportRun,+)from products.batch_exports.backend.service import cancel_running_batch_export_run, start_file_download_batch_exportSESSION = boto3.Session()diff --git a/products/batch_exports/backend/api/test/__init__.py b/products/batch_exports/backend/api/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/api/test/test_batch_imports.py b/products/batch_exports/backend/api/test/test_batch_imports.pysimilarity index 99%rename from posthog/api/test/test_batch_imports.pyrename to products/batch_exports/backend/api/test/test_batch_imports.pyindex a19686b8485e..61f2a2da7e73 100644--- a/posthog/api/test/test_batch_imports.py+++ b/products/batch_exports/backend/api/test/test_batch_imports.py@@ -4,7 +4,7 @@ from posthog.test.base import APIBaseTest, BaseTestfrom parameterized import parameterized-from posthog.models.batch_imports import BatchImport, BatchImportConfigBuilder, ContentType+from products.batch_exports.backend.models.batch_imports import BatchImport, BatchImportConfigBuilder, ContentTypeclass TestBatchImportModel(BaseTest):diff --git a/products/batch_exports/backend/apps.py b/products/batch_exports/backend/apps.pynew file mode 100644index 000000000000..da202cca7ded--- /dev/null+++ b/products/batch_exports/backend/apps.py@@ -0,0 +1,8 @@+"""Django app configuration for batch_exports."""++from django.apps import AppConfig+++class BatchExportsConfig(AppConfig):+ name = "products.batch_exports.backend"+ label = "batch_exports"diff --git a/products/batch_exports/backend/debug/__init__.py b/products/batch_exports/backend/debug/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/batch_exports/debug/debugger.py b/products/batch_exports/backend/debug/debugger.pysimilarity index 99%rename from posthog/batch_exports/debug/debugger.pyrename to products/batch_exports/backend/debug/debugger.pyindex 072804cebd96..0530a9709520 100644--- a/posthog/batch_exports/debug/debugger.py+++ b/products/batch_exports/backend/debug/debugger.py@@ -16,10 +16,10 @@ import pyarrow.fs as fsimport pyarrow.ipc as ipcfrom rich.console import Console-from posthog.models import BatchExport, BatchExportDestination, BatchExportRunfrom posthog.models.integration import DatabricksIntegrationfrom posthog.temporal.common.clickhouse import ClickHouseClient+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRunfrom products.batch_exports.backend.service import (DESTINATION_WORKFLOWS,BaseBatchExportInputs,diff --git a/posthog/batch_exports/debug/start_session.py b/products/batch_exports/backend/debug/start_session.pysimilarity index 90%rename from posthog/batch_exports/debug/start_session.pyrename to products/batch_exports/backend/debug/start_session.pyindex d55139200735..7caebbd8e92a 100644--- a/posthog/batch_exports/debug/start_session.py+++ b/products/batch_exports/backend/debug/start_session.py@@ -38,8 +38,8 @@ def make_parser():def start_session(team_id: int, batch_export_id: str | None = None):"""Start a debugging session with a debugger in an IPython shell."""- from posthog.batch_exports.debug.debugger import BatchExportsDebugger- from posthog.models import BatchExport+ from products.batch_exports.backend.debug.debugger import BatchExportsDebugger+ from products.batch_exports.backend.models.batch_export import BatchExportinitial_batch_export: BatchExport | None = Noneif batch_export_id:diff --git a/products/batch_exports/backend/migrations/0001_migrate_batch_exports_models.py b/products/batch_exports/backend/migrations/0001_migrate_batch_exports_models.pynew file mode 100644index 000000000000..b9968251b2ac--- /dev/null+++ b/products/batch_exports/backend/migrations/0001_migrate_batch_exports_models.py@@ -0,0 +1,73 @@+# Generated by Django 5.2.14 on 2026-05-27 10:20++import django.db.models.deletion+from django.db import migrations, models++import posthog.models.utils+import posthog.helpers.encrypted_fields+++class Migration(migrations.Migration):+ initial = True++ dependencies = [+ ("posthog", "1203_migrate_annotations_models"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.CreateModel(+ name="BatchImport",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.UUIDT,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("created_by_id", models.IntegerField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ ("lease_id", models.TextField(blank=True, null=True)),+ ("leased_until", models.DateTimeField(blank=True, null=True)),+ (+ "status",+ models.TextField(+ choices=[+ ("completed", "Completed"),+ ("failed", "Failed"),+ ("paused", "Paused"),+ ("running", "Running"),+ ],+ default="running",+ ),+ ),+ ("status_message", models.TextField(blank=True, null=True)),+ ("display_status_message", models.TextField(blank=True, null=True)),+ ("state", models.JSONField(blank=True, null=True)),+ ("import_config", models.JSONField()),+ (+ "secrets",+ posthog.helpers.encrypted_fields.EncryptedJSONStringField(),+ ),+ ("backoff_attempt", models.IntegerField(default=0)),+ ("backoff_until", models.DateTimeField(blank=True, null=True)),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ ],+ options={+ "db_table": "posthog_batchimport",+ },+ ),+ ],+ database_operations=[+ # No database operations - table already exists with this name+ ],+ ),+ ]diff --git a/products/batch_exports/backend/migrations/0002_batchexport_batchexportbackfill_and_more.py b/products/batch_exports/backend/migrations/0002_batchexport_batchexportbackfill_and_more.pynew file mode 100644index 000000000000..4b3abd895fb2--- /dev/null+++ b/products/batch_exports/backend/migrations/0002_batchexport_batchexportbackfill_and_more.py@@ -0,0 +1,1256 @@+# Generated by Django 5.2.14 on 2026-05-27 10:56++import django.db.models.deletion+from django.db import migrations, models++import posthog.models.utils+import posthog.helpers.encrypted_fields+++class Migration(migrations.Migration):+ dependencies = [+ ("batch_exports", "0001_migrate_batch_exports_models"),+ ("posthog", "1204_migrate_batch_exports_models"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.CreateModel(+ name="BatchExport",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.UUIDT,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "name",+ models.TextField(help_text="A human-readable name for this BatchExport."),+ ),+ (+ "interval",+ models.CharField(+ choices=[+ ("hour", "hour"),+ ("day", "day"),+ ("week", "week"),+ ("every 5 minutes", "every 5 minutes"),+ ("every 15 minutes", "every 15 minutes"),+ ],+ default="hour",+ help_text="The interval at which to export data.",+ max_length=64,+ ),+ ),+ (+ "paused",+ models.BooleanField(+ default=False,+ help_text="Whether this BatchExport is paused or not.",+ ),+ ),+ (+ "deleted",+ models.BooleanField(+ default=False,+ help_text="Whether this BatchExport is deleted or not.",+ ),+ ),+ (+ "created_at",+ models.DateTimeField(+ auto_now_add=True,+ help_text="The timestamp at which this BatchExport was created.",+ ),+ ),+ (+ "last_updated_at",+ models.DateTimeField(+ auto_now=True,+ help_text="The timestamp at which this BatchExport was last updated.",+ ),+ ),+ (+ "last_paused_at",+ models.DateTimeField(+ default=None,+ help_text="The timestamp at which this BatchExport was last paused.",+ null=True,+ ),+ ),+ (+ "start_at",+ models.DateTimeField(+ default=None,+ help_text="Time before which any Batch Export runs won't be triggered.",+ null=True,+ ),+ ),+ (+ "end_at",+ models.DateTimeField(+ default=None,+ help_text="Time after which any Batch Export runs won't be triggered.",+ null=True,+ ),+ ),+ (+ "schema",+ models.JSONField(+ default=None,+ help_text="A schema of custom fields to select when exporting data.",+ null=True,+ ),+ ),+ (+ "model",+ models.CharField(+ blank=True,+ choices=[+ ("events", "Events"),+ ("persons", "Persons"),+ ("sessions", "Sessions"),+ ],+ default="events",+ help_text="Which model this BatchExport is exporting.",+ max_length=64,+ null=True,+ ),+ ),+ ("filters", models.JSONField(blank=True, null=True)),+ (+ "timezone",+ models.CharField(+ choices=[+ ("Africa/Abidjan", "Africa/Abidjan"),+ ("Africa/Accra", "Africa/Accra"),+ ("Africa/Addis_Ababa", "Africa/Addis_Ababa"),+ ("Africa/Algiers", "Africa/Algiers"),+ ("Africa/Asmara", "Africa/Asmara"),+ ("Africa/Asmera", "Africa/Asmera"),+ ("Africa/Bamako", "Africa/Bamako"),+ ("Africa/Bangui", "Africa/Bangui"),+ ("Africa/Banjul", "Africa/Banjul"),+ ("Africa/Bissau", "Africa/Bissau"),+ ("Africa/Blantyre", "Africa/Blantyre"),+ ("Africa/Brazzaville", "Africa/Brazzaville"),+ ("Africa/Bujumbura", "Africa/Bujumbura"),+ ("Africa/Cairo", "Africa/Cairo"),+ ("Africa/Casablanca", "Africa/Casablanca"),+ ("Africa/Ceuta", "Africa/Ceuta"),+ ("Africa/Conakry", "Africa/Conakry"),+ ("Africa/Dakar", "Africa/Dakar"),+ ("Africa/Dar_es_Salaam", "Africa/Dar_es_Salaam"),+ ("Africa/Djibouti", "Africa/Djibouti"),+ ("Africa/Douala", "Africa/Douala"),+ ("Africa/El_Aaiun", "Africa/El_Aaiun"),+ ("Africa/Freetown", "Africa/Freetown"),+ ("Africa/Gaborone", "Africa/Gaborone"),+ ("Africa/Harare", "Africa/Harare"),+ ("Africa/Johannesburg", "Africa/Johannesburg"),+ ("Africa/Juba", "Africa/Juba"),+ ("Africa/Kampala", "Africa/Kampala"),+ ("Africa/Khartoum", "Africa/Khartoum"),+ ("Africa/Kigali", "Africa/Kigali"),+ ("Africa/Kinshasa", "Africa/Kinshasa"),+ ("Africa/Lagos", "Africa/Lagos"),+ ("Africa/Libreville", "Africa/Libreville"),+ ("Africa/Lome", "Africa/Lome"),+ ("Africa/Luanda", "Africa/Luanda"),+ ("Africa/Lubumbashi", "Africa/Lubumbashi"),+ ("Africa/Lusaka", "Africa/Lusaka"),+ ("Africa/Malabo", "Africa/Malabo"),+ ("Africa/Maputo", "Africa/Maputo"),+ ("Africa/Maseru", "Africa/Maseru"),+ ("Africa/Mbabane", "Africa/Mbabane"),+ ("Africa/Mogadishu", "Africa/Mogadishu"),+ ("Africa/Monrovia", "Africa/Monrovia"),+ ("Africa/Nairobi", "Africa/Nairobi"),+ ("Africa/Ndjamena", "Africa/Ndjamena"),+ ("Africa/Niamey", "Africa/Niamey"),+ ("Africa/Nouakchott", "Africa/Nouakchott"),+ ("Africa/Ouagadougou", "Africa/Ouagadougou"),+ ("Africa/Porto-Novo", "Africa/Porto-Novo"),+ ("Africa/Sao_Tome", "Africa/Sao_Tome"),+ ("Africa/Timbuktu", "Africa/Timbuktu"),+ ("Africa/Tripoli", "Africa/Tripoli"),+ ("Africa/Tunis", "Africa/Tunis"),+ ("Africa/Windhoek", "Africa/Windhoek"),+ ("America/Adak", "America/Adak"),+ ("America/Anchorage", "America/Anchorage"),+ ("America/Anguilla", "America/Anguilla"),+ ("America/Antigua", "America/Antigua"),+ ("America/Araguaina", "America/Araguaina"),+ (+ "America/Argentina/Buenos_Aires",+ "America/Argentina/Buenos_Aires",+ ),+ (+ "America/Argentina/Catamarca",+ "America/Argentina/Catamarca",+ ),+ (+ "America/Argentina/ComodRivadavia",+ "America/Argentina/ComodRivadavia",+ ),+ ("America/Argentina/Cordoba", "America/Argentina/Cordoba"),+ ("America/Argentina/Jujuy", "America/Argentina/Jujuy"),+ (+ "America/Argentina/La_Rioja",+ "America/Argentina/La_Rioja",+ ),+ ("America/Argentina/Mendoza", "America/Argentina/Mendoza"),+ (+ "America/Argentina/Rio_Gallegos",+ "America/Argentina/Rio_Gallegos",+ ),+ ("America/Argentina/Salta", "America/Argentina/Salta"),+ (+ "America/Argentina/San_Juan",+ "America/Argentina/San_Juan",+ ),+ (+ "America/Argentina/San_Luis",+ "America/Argentina/San_Luis",+ ),+ ("America/Argentina/Tucuman", "America/Argentina/Tucuman"),+ ("America/Argentina/Ushuaia", "America/Argentina/Ushuaia"),+ ("America/Aruba", "America/Aruba"),+ ("America/Asuncion", "America/Asuncion"),+ ("America/Atikokan", "America/Atikokan"),+ ("America/Atka", "America/Atka"),+ ("America/Bahia", "America/Bahia"),+ ("America/Bahia_Banderas", "America/Bahia_Banderas"),+ ("America/Barbados", "America/Barbados"),+ ("America/Belem", "America/Belem"),+ ("America/Belize", "America/Belize"),+ ("America/Blanc-Sablon", "America/Blanc-Sablon"),+ ("America/Boa_Vista", "America/Boa_Vista"),+ ("America/Bogota", "America/Bogota"),+ ("America/Boise", "America/Boise"),+ ("America/Buenos_Aires", "America/Buenos_Aires"),+ ("America/Cambridge_Bay", "America/Cambridge_Bay"),+ ("America/Campo_Grande", "America/Campo_Grande"),+ ("America/Cancun", "America/Cancun"),+ ("America/Caracas", "America/Caracas"),+ ("America/Catamarca", "America/Catamarca"),+ ("America/Cayenne", "America/Cayenne"),+ ("America/Cayman", "America/Cayman"),+ ("America/Chicago", "America/Chicago"),+ ("America/Chihuahua", "America/Chihuahua"),+ ("America/Ciudad_Juarez", "America/Ciudad_Juarez"),+ ("America/Coral_Harbour", "America/Coral_Harbour"),+ ("America/Cordoba", "America/Cordoba"),+ ("America/Costa_Rica", "America/Costa_Rica"),+ ("America/Creston", "America/Creston"),+ ("America/Cuiaba", "America/Cuiaba"),+ ("America/Curacao", "America/Curacao"),+ ("America/Danmarkshavn", "America/Danmarkshavn"),+ ("America/Dawson", "America/Dawson"),+ ("America/Dawson_Creek", "America/Dawson_Creek"),+ ("America/Denver", "America/Denver"),+ ("America/Detroit", "America/Detroit"),+ ("America/Dominica", "America/Dominica"),+ ("America/Edmonton", "America/Edmonton"),+ ("America/Eirunepe", "America/Eirunepe"),+ ("America/El_Salvador", "America/El_Salvador"),+ ("America/Ensenada", "America/Ensenada"),+ ("America/Fort_Nelson", "America/Fort_Nelson"),+ ("America/Fort_Wayne", "America/Fort_Wayne"),+ ("America/Fortaleza", "America/Fortaleza"),+ ("America/Glace_Bay", "America/Glace_Bay"),+ ("America/Godthab", "America/Godthab"),+ ("America/Goose_Bay", "America/Goose_Bay"),+ ("America/Grand_Turk", "America/Grand_Turk"),+ ("America/Grenada", "America/Grenada"),+ ("America/Guadeloupe", "America/Guadeloupe"),+ ("America/Guatemala", "America/Guatemala"),+ ("America/Guayaquil", "America/Guayaquil"),+ ("America/Guyana", "America/Guyana"),+ ("America/Halifax", "America/Halifax"),+ ("America/Havana", "America/Havana"),+ ("America/Hermosillo", "America/Hermosillo"),+ (+ "America/Indiana/Indianapolis",+ "America/Indiana/Indianapolis",+ ),+ ("America/Indiana/Knox", "America/Indiana/Knox"),+ ("America/Indiana/Marengo", "America/Indiana/Marengo"),+ (+ "America/Indiana/Petersburg",+ "America/Indiana/Petersburg",+ ),+ ("America/Indiana/Tell_City", "America/Indiana/Tell_City"),+ ("America/Indiana/Vevay", "America/Indiana/Vevay"),+ ("America/Indiana/Vincennes", "America/Indiana/Vincennes"),+ ("America/Indiana/Winamac", "America/Indiana/Winamac"),+ ("America/Indianapolis", "America/Indianapolis"),+ ("America/Inuvik", "America/Inuvik"),+ ("America/Iqaluit", "America/Iqaluit"),+ ("America/Jamaica", "America/Jamaica"),+ ("America/Jujuy", "America/Jujuy"),+ ("America/Juneau", "America/Juneau"),+ (+ "America/Kentucky/Louisville",+ "America/Kentucky/Louisville",+ ),+ (+ "America/Kentucky/Monticello",+ "America/Kentucky/Monticello",+ ),+ ("America/Knox_IN", "America/Knox_IN"),+ ("America/Kralendijk", "America/Kralendijk"),+ ("America/La_Paz", "America/La_Paz"),+ ("America/Lima", "America/Lima"),+ ("America/Los_Angeles", "America/Los_Angeles"),+ ("America/Louisville", "America/Louisville"),+ ("America/Lower_Princes", "America/Lower_Princes"),+ ("America/Maceio", "America/Maceio"),+ ("America/Managua", "America/Managua"),+ ("America/Manaus", "America/Manaus"),+ ("America/Marigot", "America/Marigot"),+ ("America/Martinique", "America/Martinique"),+ ("America/Matamoros", "America/Matamoros"),+ ("America/Mazatlan", "America/Mazatlan"),+ ("America/Mendoza", "America/Mendoza"),+ ("America/Menominee", "America/Menominee"),+ ("America/Merida", "America/Merida"),+ ("America/Metlakatla", "America/Metlakatla"),+ ("America/Mexico_City", "America/Mexico_City"),+ ("America/Miquelon", "America/Miquelon"),+ ("America/Moncton", "America/Moncton"),+ ("America/Monterrey", "America/Monterrey"),+ ("America/Montevideo", "America/Montevideo"),+ ("America/Montreal", "America/Montreal"),+ ("America/Montserrat", "America/Montserrat"),+ ("America/Nassau", "America/Nassau"),+ ("America/New_York", "America/New_York"),+ ("America/Nipigon", "America/Nipigon"),+ ("America/Nome", "America/Nome"),+ ("America/Noronha", "America/Noronha"),+ (+ "America/North_Dakota/Beulah",+ "America/North_Dakota/Beulah",+ ),+ (+ "America/North_Dakota/Center",+ "America/North_Dakota/Center",+ ),+ (+ "America/North_Dakota/New_Salem",+ "America/North_Dakota/New_Salem",+ ),+ ("America/Nuuk", "America/Nuuk"),+ ("America/Ojinaga", "America/Ojinaga"),+ ("America/Panama", "America/Panama"),+ ("America/Pangnirtung", "America/Pangnirtung"),+ ("America/Paramaribo", "America/Paramaribo"),+ ("America/Phoenix", "America/Phoenix"),+ ("America/Port-au-Prince", "America/Port-au-Prince"),+ ("America/Port_of_Spain", "America/Port_of_Spain"),+ ("America/Porto_Acre", "America/Porto_Acre"),+ ("America/Porto_Velho", "America/Porto_Velho"),+ ("America/Puerto_Rico", "America/Puerto_Rico"),+ ("America/Punta_Arenas", "America/Punta_Arenas"),+ ("America/Rainy_River", "America/Rainy_River"),+ ("America/Rankin_Inlet", "America/Rankin_Inlet"),+ ("America/Recife", "America/Recife"),+ ("America/Regina", "America/Regina"),+ ("America/Resolute", "America/Resolute"),+ ("America/Rio_Branco", "America/Rio_Branco"),+ ("America/Rosario", "America/Rosario"),+ ("America/Santa_Isabel", "America/Santa_Isabel"),+ ("America/Santarem", "America/Santarem"),+ ("America/Santiago", "America/Santiago"),+ ("America/Santo_Domingo", "America/Santo_Domingo"),+ ("America/Sao_Paulo", "America/Sao_Paulo"),+ ("America/Scoresbysund", "America/Scoresbysund"),+ ("America/Shiprock", "America/Shiprock"),+ ("America/Sitka", "America/Sitka"),+ ("America/St_Barthelemy", "America/St_Barthelemy"),+ ("America/St_Johns", "America/St_Johns"),+ ("America/St_Kitts", "America/St_Kitts"),+ ("America/St_Lucia", "America/St_Lucia"),+ ("America/St_Thomas", "America/St_Thomas"),+ ("America/St_Vincent", "America/St_Vincent"),+ ("America/Swift_Current", "America/Swift_Current"),+ ("America/Tegucigalpa", "America/Tegucigalpa"),+ ("America/Thule", "America/Thule"),+ ("America/Thunder_Bay", "America/Thunder_Bay"),+ ("America/Tijuana", "America/Tijuana"),+ ("America/Toronto", "America/Toronto"),+ ("America/Tortola", "America/Tortola"),+ ("America/Vancouver", "America/Vancouver"),+ ("America/Virgin", "America/Virgin"),+ ("America/Whitehorse", "America/Whitehorse"),+ ("America/Winnipeg", "America/Winnipeg"),+ ("America/Yakutat", "America/Yakutat"),+ ("America/Yellowknife", "America/Yellowknife"),+ ("Antarctica/Casey", "Antarctica/Casey"),+ ("Antarctica/Davis", "Antarctica/Davis"),+ ("Antarctica/DumontDUrville", "Antarctica/DumontDUrville"),+ ("Antarctica/Macquarie", "Antarctica/Macquarie"),+ ("Antarctica/Mawson", "Antarctica/Mawson"),+ ("Antarctica/McMurdo", "Antarctica/McMurdo"),+ ("Antarctica/Palmer", "Antarctica/Palmer"),+ ("Antarctica/Rothera", "Antarctica/Rothera"),+ ("Antarctica/South_Pole", "Antarctica/South_Pole"),+ ("Antarctica/Syowa", "Antarctica/Syowa"),+ ("Antarctica/Troll", "Antarctica/Troll"),+ ("Antarctica/Vostok", "Antarctica/Vostok"),+ ("Arctic/Longyearbyen", "Arctic/Longyearbyen"),+ ("Asia/Aden", "Asia/Aden"),+ ("Asia/Almaty", "Asia/Almaty"),+ ("Asia/Amman", "Asia/Amman"),+ ("Asia/Anadyr", "Asia/Anadyr"),+ ("Asia/Aqtau", "Asia/Aqtau"),+ ("Asia/Aqtobe", "Asia/Aqtobe"),+ ("Asia/Ashgabat", "Asia/Ashgabat"),+ ("Asia/Ashkhabad", "Asia/Ashkhabad"),+ ("Asia/Atyrau", "Asia/Atyrau"),+ ("Asia/Baghdad", "Asia/Baghdad"),+ ("Asia/Bahrain", "Asia/Bahrain"),+ ("Asia/Baku", "Asia/Baku"),+ ("Asia/Bangkok", "Asia/Bangkok"),+ ("Asia/Barnaul", "Asia/Barnaul"),+ ("Asia/Beirut", "Asia/Beirut"),+ ("Asia/Bishkek", "Asia/Bishkek"),+ ("Asia/Brunei", "Asia/Brunei"),+ ("Asia/Calcutta", "Asia/Calcutta"),+ ("Asia/Chita", "Asia/Chita"),+ ("Asia/Choibalsan", "Asia/Choibalsan"),+ ("Asia/Chongqing", "Asia/Chongqing"),+ ("Asia/Chungking", "Asia/Chungking"),+ ("Asia/Colombo", "Asia/Colombo"),+ ("Asia/Dacca", "Asia/Dacca"),+ ("Asia/Damascus", "Asia/Damascus"),+ ("Asia/Dhaka", "Asia/Dhaka"),+ ("Asia/Dili", "Asia/Dili"),+ ("Asia/Dubai", "Asia/Dubai"),+ ("Asia/Dushanbe", "Asia/Dushanbe"),+ ("Asia/Famagusta", "Asia/Famagusta"),+ ("Asia/Gaza", "Asia/Gaza"),+ ("Asia/Harbin", "Asia/Harbin"),+ ("Asia/Hebron", "Asia/Hebron"),+ ("Asia/Ho_Chi_Minh", "Asia/Ho_Chi_Minh"),+ ("Asia/Hong_Kong", "Asia/Hong_Kong"),+ ("Asia/Hovd", "Asia/Hovd"),+ ("Asia/Irkutsk", "Asia/Irkutsk"),+ ("Asia/Istanbul", "Asia/Istanbul"),+ ("Asia/Jakarta", "Asia/Jakarta"),+ ("Asia/Jayapura", "Asia/Jayapura"),+ ("Asia/Jerusalem", "Asia/Jerusalem"),+ ("Asia/Kabul", "Asia/Kabul"),+ ("Asia/Kamchatka", "Asia/Kamchatka"),+ ("Asia/Karachi", "Asia/Karachi"),+ ("Asia/Kashgar", "Asia/Kashgar"),+ ("Asia/Kathmandu", "Asia/Kathmandu"),+ ("Asia/Katmandu", "Asia/Katmandu"),+ ("Asia/Khandyga", "Asia/Khandyga"),+ ("Asia/Kolkata", "Asia/Kolkata"),+ ("Asia/Krasnoyarsk", "Asia/Krasnoyarsk"),+ ("Asia/Kuala_Lumpur", "Asia/Kuala_Lumpur"),+ ("Asia/Kuching", "Asia/Kuching"),+ ("Asia/Kuwait", "Asia/Kuwait"),+ ("Asia/Macao", "Asia/Macao"),+ ("Asia/Macau", "Asia/Macau"),+ ("Asia/Magadan", "Asia/Magadan"),+ ("Asia/Makassar", "Asia/Makassar"),+ ("Asia/Manila", "Asia/Manila"),+ ("Asia/Muscat", "Asia/Muscat"),+ ("Asia/Nicosia", "Asia/Nicosia"),+ ("Asia/Novokuznetsk", "Asia/Novokuznetsk"),+ ("Asia/Novosibirsk", "Asia/Novosibirsk"),+ ("Asia/Omsk", "Asia/Omsk"),+ ("Asia/Oral", "Asia/Oral"),+ ("Asia/Phnom_Penh", "Asia/Phnom_Penh"),+ ("Asia/Pontianak", "Asia/Pontianak"),+ ("Asia/Pyongyang", "Asia/Pyongyang"),+ ("Asia/Qatar", "Asia/Qatar"),+ ("Asia/Qostanay", "Asia/Qostanay"),+ ("Asia/Qyzylorda", "Asia/Qyzylorda"),+ ("Asia/Rangoon", "Asia/Rangoon"),+ ("Asia/Riyadh", "Asia/Riyadh"),+ ("Asia/Saigon", "Asia/Saigon"),+ ("Asia/Sakhalin", "Asia/Sakhalin"),+ ("Asia/Samarkand", "Asia/Samarkand"),+ ("Asia/Seoul", "Asia/Seoul"),+ ("Asia/Shanghai", "Asia/Shanghai"),+ ("Asia/Singapore", "Asia/Singapore"),+ ("Asia/Srednekolymsk", "Asia/Srednekolymsk"),+ ("Asia/Taipei", "Asia/Taipei"),+ ("Asia/Tashkent", "Asia/Tashkent"),+ ("Asia/Tbilisi", "Asia/Tbilisi"),+ ("Asia/Tehran", "Asia/Tehran"),+ ("Asia/Tel_Aviv", "Asia/Tel_Aviv"),+ ("Asia/Thimbu", "Asia/Thimbu"),+ ("Asia/Thimphu", "Asia/Thimphu"),+ ("Asia/Tokyo", "Asia/Tokyo"),+ ("Asia/Tomsk", "Asia/Tomsk"),+ ("Asia/Ujung_Pandang", "Asia/Ujung_Pandang"),+ ("Asia/Ulaanbaatar", "Asia/Ulaanbaatar"),+ ("Asia/Ulan_Bator", "Asia/Ulan_Bator"),+ ("Asia/Urumqi", "Asia/Urumqi"),+ ("Asia/Ust-Nera", "Asia/Ust-Nera"),+ ("Asia/Vientiane", "Asia/Vientiane"),+ ("Asia/Vladivostok", "Asia/Vladivostok"),+ ("Asia/Yakutsk", "Asia/Yakutsk"),+ ("Asia/Yangon", "Asia/Yangon"),+ ("Asia/Yekaterinburg", "Asia/Yekaterinburg"),+ ("Asia/Yerevan", "Asia/Yerevan"),+ ("Atlantic/Azores", "Atlantic/Azores"),+ ("Atlantic/Bermuda", "Atlantic/Bermuda"),+ ("Atlantic/Canary", "Atlantic/Canary"),+ ("Atlantic/Cape_Verde", "Atlantic/Cape_Verde"),+ ("Atlantic/Faeroe", "Atlantic/Faeroe"),+ ("Atlantic/Faroe", "Atlantic/Faroe"),+ ("Atlantic/Jan_Mayen", "Atlantic/Jan_Mayen"),+ ("Atlantic/Madeira", "Atlantic/Madeira"),+ ("Atlantic/Reykjavik", "Atlantic/Reykjavik"),+ ("Atlantic/South_Georgia", "Atlantic/South_Georgia"),+ ("Atlantic/St_Helena", "Atlantic/St_Helena"),+ ("Atlantic/Stanley", "Atlantic/Stanley"),+ ("Australia/ACT", "Australia/ACT"),+ ("Australia/Adelaide", "Australia/Adelaide"),+ ("Australia/Brisbane", "Australia/Brisbane"),+ ("Australia/Broken_Hill", "Australia/Broken_Hill"),+ ("Australia/Canberra", "Australia/Canberra"),+ ("Australia/Currie", "Australia/Currie"),+ ("Australia/Darwin", "Australia/Darwin"),+ ("Australia/Eucla", "Australia/Eucla"),+ ("Australia/Hobart", "Australia/Hobart"),+ ("Australia/LHI", "Australia/LHI"),+ ("Australia/Lindeman", "Australia/Lindeman"),+ ("Australia/Lord_Howe", "Australia/Lord_Howe"),+ ("Australia/Melbourne", "Australia/Melbourne"),+ ("Australia/NSW", "Australia/NSW"),+ ("Australia/North", "Australia/North"),+ ("Australia/Perth", "Australia/Perth"),+ ("Australia/Queensland", "Australia/Queensland"),+ ("Australia/South", "Australia/South"),+ ("Australia/Sydney", "Australia/Sydney"),+ ("Australia/Tasmania", "Australia/Tasmania"),+ ("Australia/Victoria", "Australia/Victoria"),+ ("Australia/West", "Australia/West"),+ ("Australia/Yancowinna", "Australia/Yancowinna"),+ ("Brazil/Acre", "Brazil/Acre"),+ ("Brazil/DeNoronha", "Brazil/DeNoronha"),+ ("Brazil/East", "Brazil/East"),+ ("Brazil/West", "Brazil/West"),+ ("CET", "CET"),+ ("CST6CDT", "CST6CDT"),+ ("Canada/Atlantic", "Canada/Atlantic"),+ ("Canada/Central", "Canada/Central"),+ ("Canada/Eastern", "Canada/Eastern"),+ ("Canada/Mountain", "Canada/Mountain"),+ ("Canada/Newfoundland", "Canada/Newfoundland"),+ ("Canada/Pacific", "Canada/Pacific"),+ ("Canada/Saskatchewan", "Canada/Saskatchewan"),+ ("Canada/Yukon", "Canada/Yukon"),+ ("Chile/Continental", "Chile/Continental"),+ ("Chile/EasterIsland", "Chile/EasterIsland"),+ ("Cuba", "Cuba"),+ ("EET", "EET"),+ ("EST", "EST"),+ ("EST5EDT", "EST5EDT"),+ ("Egypt", "Egypt"),+ ("Eire", "Eire"),+ ("Etc/GMT", "Etc/GMT"),+ ("Etc/GMT+0", "Etc/GMT+0"),+ ("Etc/GMT+1", "Etc/GMT+1"),+ ("Etc/GMT+10", "Etc/GMT+10"),+ ("Etc/GMT+11", "Etc/GMT+11"),+ ("Etc/GMT+12", "Etc/GMT+12"),+ ("Etc/GMT+2", "Etc/GMT+2"),+ ("Etc/GMT+3", "Etc/GMT+3"),+ ("Etc/GMT+4", "Etc/GMT+4"),+ ("Etc/GMT+5", "Etc/GMT+5"),+ ("Etc/GMT+6", "Etc/GMT+6"),+ ("Etc/GMT+7", "Etc/GMT+7"),+ ("Etc/GMT+8", "Etc/GMT+8"),+ ("Etc/GMT+9", "Etc/GMT+9"),+ ("Etc/GMT-0", "Etc/GMT-0"),+ ("Etc/GMT-1", "Etc/GMT-1"),+ ("Etc/GMT-10", "Etc/GMT-10"),+ ("Etc/GMT-11", "Etc/GMT-11"),+ ("Etc/GMT-12", "Etc/GMT-12"),+ ("Etc/GMT-13", "Etc/GMT-13"),+ ("Etc/GMT-14", "Etc/GMT-14"),+ ("Etc/GMT-2", "Etc/GMT-2"),+ ("Etc/GMT-3", "Etc/GMT-3"),+ ("Etc/GMT-4", "Etc/GMT-4"),+ ("Etc/GMT-5", "Etc/GMT-5"),+ ("Etc/GMT-6", "Etc/GMT-6"),+ ("Etc/GMT-7", "Etc/GMT-7"),+ ("Etc/GMT-8", "Etc/GMT-8"),+ ("Etc/GMT-9", "Etc/GMT-9"),+ ("Etc/GMT0", "Etc/GMT0"),+ ("Etc/Greenwich", "Etc/Greenwich"),+ ("Etc/UCT", "Etc/UCT"),+ ("Etc/UTC", "Etc/UTC"),+ ("Etc/Universal", "Etc/Universal"),+ ("Etc/Zulu", "Etc/Zulu"),+ ("Europe/Amsterdam", "Europe/Amsterdam"),+ ("Europe/Andorra", "Europe/Andorra"),+ ("Europe/Astrakhan", "Europe/Astrakhan"),+ ("Europe/Athens", "Europe/Athens"),+ ("Europe/Belfast", "Europe/Belfast"),+ ("Europe/Belgrade", "Europe/Belgrade"),+ ("Europe/Berlin", "Europe/Berlin"),+ ("Europe/Bratislava", "Europe/Bratislava"),+ ("Europe/Brussels", "Europe/Brussels"),+ ("Europe/Bucharest", "Europe/Bucharest"),+ ("Europe/Budapest", "Europe/Budapest"),+ ("Europe/Busingen", "Europe/Busingen"),+ ("Europe/Chisinau", "Europe/Chisinau"),+ ("Europe/Copenhagen", "Europe/Copenhagen"),+ ("Europe/Dublin", "Europe/Dublin"),+ ("Europe/Gibraltar", "Europe/Gibraltar"),+ ("Europe/Guernsey", "Europe/Guernsey"),+ ("Europe/Helsinki", "Europe/Helsinki"),+ ("Europe/Isle_of_Man", "Europe/Isle_of_Man"),+ ("Europe/Istanbul", "Europe/Istanbul"),+ ("Europe/Jersey", "Europe/Jersey"),+ ("Europe/Kaliningrad", "Europe/Kaliningrad"),+ ("Europe/Kiev", "Europe/Kiev"),+ ("Europe/Kirov", "Europe/Kirov"),+ ("Europe/Kyiv", "Europe/Kyiv"),+ ("Europe/Lisbon", "Europe/Lisbon"),+ ("Europe/Ljubljana", "Europe/Ljubljana"),+ ("Europe/London", "Europe/London"),+ ("Europe/Luxembourg", "Europe/Luxembourg"),+ ("Europe/Madrid", "Europe/Madrid"),+ ("Europe/Malta", "Europe/Malta"),+ ("Europe/Mariehamn", "Europe/Mariehamn"),+ ("Europe/Minsk", "Europe/Minsk"),+ ("Europe/Monaco", "Europe/Monaco"),+ ("Europe/Moscow", "Europe/Moscow"),+ ("Europe/Nicosia", "Europe/Nicosia"),+ ("Europe/Oslo", "Europe/Oslo"),+ ("Europe/Paris", "Europe/Paris"),+ ("Europe/Podgorica", "Europe/Podgorica"),+ ("Europe/Prague", "Europe/Prague"),+ ("Europe/Riga", "Europe/Riga"),+ ("Europe/Rome", "Europe/Rome"),+ ("Europe/Samara", "Europe/Samara"),+ ("Europe/San_Marino", "Europe/San_Marino"),+ ("Europe/Sarajevo", "Europe/Sarajevo"),+ ("Europe/Saratov", "Europe/Saratov"),+ ("Europe/Simferopol", "Europe/Simferopol"),+ ("Europe/Skopje", "Europe/Skopje"),+ ("Europe/Sofia", "Europe/Sofia"),+ ("Europe/Stockholm", "Europe/Stockholm"),+ ("Europe/Tallinn", "Europe/Tallinn"),+ ("Europe/Tirane", "Europe/Tirane"),+ ("Europe/Tiraspol", "Europe/Tiraspol"),+ ("Europe/Ulyanovsk", "Europe/Ulyanovsk"),+ ("Europe/Uzhgorod", "Europe/Uzhgorod"),+ ("Europe/Vaduz", "Europe/Vaduz"),+ ("Europe/Vatican", "Europe/Vatican"),+ ("Europe/Vienna", "Europe/Vienna"),+ ("Europe/Vilnius", "Europe/Vilnius"),+ ("Europe/Volgograd", "Europe/Volgograd"),+ ("Europe/Warsaw", "Europe/Warsaw"),+ ("Europe/Zagreb", "Europe/Zagreb"),+ ("Europe/Zaporozhye", "Europe/Zaporozhye"),+ ("Europe/Zurich", "Europe/Zurich"),+ ("GB", "GB"),+ ("GB-Eire", "GB-Eire"),+ ("GMT", "GMT"),+ ("GMT+0", "GMT+0"),+ ("GMT-0", "GMT-0"),+ ("GMT0", "GMT0"),+ ("Greenwich", "Greenwich"),+ ("HST", "HST"),+ ("Hongkong", "Hongkong"),+ ("Iceland", "Iceland"),+ ("Indian/Antananarivo", "Indian/Antananarivo"),+ ("Indian/Chagos", "Indian/Chagos"),+ ("Indian/Christmas", "Indian/Christmas"),+ ("Indian/Cocos", "Indian/Cocos"),+ ("Indian/Comoro", "Indian/Comoro"),+ ("Indian/Kerguelen", "Indian/Kerguelen"),+ ("Indian/Mahe", "Indian/Mahe"),+ ("Indian/Maldives", "Indian/Maldives"),+ ("Indian/Mauritius", "Indian/Mauritius"),+ ("Indian/Mayotte", "Indian/Mayotte"),+ ("Indian/Reunion", "Indian/Reunion"),+ ("Iran", "Iran"),+ ("Israel", "Israel"),+ ("Jamaica", "Jamaica"),+ ("Japan", "Japan"),+ ("Kwajalein", "Kwajalein"),+ ("Libya", "Libya"),+ ("MET", "MET"),+ ("MST", "MST"),+ ("MST7MDT", "MST7MDT"),+ ("Mexico/BajaNorte", "Mexico/BajaNorte"),+ ("Mexico/BajaSur", "Mexico/BajaSur"),+ ("Mexico/General", "Mexico/General"),+ ("NZ", "NZ"),+ ("NZ-CHAT", "NZ-CHAT"),+ ("Navajo", "Navajo"),+ ("PRC", "PRC"),+ ("PST8PDT", "PST8PDT"),+ ("Pacific/Apia", "Pacific/Apia"),+ ("Pacific/Auckland", "Pacific/Auckland"),+ ("Pacific/Bougainville", "Pacific/Bougainville"),+ ("Pacific/Chatham", "Pacific/Chatham"),+ ("Pacific/Chuuk", "Pacific/Chuuk"),+ ("Pacific/Easter", "Pacific/Easter"),+ ("Pacific/Efate", "Pacific/Efate"),+ ("Pacific/Enderbury", "Pacific/Enderbury"),+ ("Pacific/Fakaofo", "Pacific/Fakaofo"),+ ("Pacific/Fiji", "Pacific/Fiji"),+ ("Pacific/Funafuti", "Pacific/Funafuti"),+ ("Pacific/Galapagos", "Pacific/Galapagos"),+ ("Pacific/Gambier", "Pacific/Gambier"),+ ("Pacific/Guadalcanal", "Pacific/Guadalcanal"),+ ("Pacific/Guam", "Pacific/Guam"),+ ("Pacific/Honolulu", "Pacific/Honolulu"),+ ("Pacific/Johnston", "Pacific/Johnston"),+ ("Pacific/Kanton", "Pacific/Kanton"),+ ("Pacific/Kiritimati", "Pacific/Kiritimati"),+ ("Pacific/Kosrae", "Pacific/Kosrae"),+ ("Pacific/Kwajalein", "Pacific/Kwajalein"),+ ("Pacific/Majuro", "Pacific/Majuro"),+ ("Pacific/Marquesas", "Pacific/Marquesas"),+ ("Pacific/Midway", "Pacific/Midway"),+ ("Pacific/Nauru", "Pacific/Nauru"),+ ("Pacific/Niue", "Pacific/Niue"),+ ("Pacific/Norfolk", "Pacific/Norfolk"),+ ("Pacific/Noumea", "Pacific/Noumea"),+ ("Pacific/Pago_Pago", "Pacific/Pago_Pago"),+ ("Pacific/Palau", "Pacific/Palau"),+ ("Pacific/Pitcairn", "Pacific/Pitcairn"),+ ("Pacific/Pohnpei", "Pacific/Pohnpei"),+ ("Pacific/Ponape", "Pacific/Ponape"),+ ("Pacific/Port_Moresby", "Pacific/Port_Moresby"),+ ("Pacific/Rarotonga", "Pacific/Rarotonga"),+ ("Pacific/Saipan", "Pacific/Saipan"),+ ("Pacific/Samoa", "Pacific/Samoa"),+ ("Pacific/Tahiti", "Pacific/Tahiti"),+ ("Pacific/Tarawa", "Pacific/Tarawa"),+ ("Pacific/Tongatapu", "Pacific/Tongatapu"),+ ("Pacific/Truk", "Pacific/Truk"),+ ("Pacific/Wake", "Pacific/Wake"),+ ("Pacific/Wallis", "Pacific/Wallis"),+ ("Pacific/Yap", "Pacific/Yap"),+ ("Poland", "Poland"),+ ("Portugal", "Portugal"),+ ("ROC", "ROC"),+ ("ROK", "ROK"),+ ("Singapore", "Singapore"),+ ("Turkey", "Turkey"),+ ("UCT", "UCT"),+ ("US/Alaska", "US/Alaska"),+ ("US/Aleutian", "US/Aleutian"),+ ("US/Arizona", "US/Arizona"),+ ("US/Central", "US/Central"),+ ("US/East-Indiana", "US/East-Indiana"),+ ("US/Eastern", "US/Eastern"),+ ("US/Hawaii", "US/Hawaii"),+ ("US/Indiana-Starke", "US/Indiana-Starke"),+ ("US/Michigan", "US/Michigan"),+ ("US/Mountain", "US/Mountain"),+ ("US/Pacific", "US/Pacific"),+ ("US/Samoa", "US/Samoa"),+ ("UTC", "UTC"),+ ("Universal", "Universal"),+ ("W-SU", "W-SU"),+ ("WET", "WET"),+ ("Zulu", "Zulu"),+ ],+ default="UTC",+ max_length=240,+ ),+ ),+ (+ "interval_offset",+ models.IntegerField(+ blank=True,+ help_text="The offset in seconds from the start of the default interval that this batch export should run at.",+ null=True,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ help_text="The team this belongs to.",+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "posthog_batchexport",+ "abstract": False,+ },+ ),+ migrations.CreateModel(+ name="BatchExportBackfill",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.UUIDT,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "start_at",+ models.DateTimeField(help_text="The start of the data interval.", null=True),+ ),+ (+ "end_at",+ models.DateTimeField(help_text="The end of the data interval.", null=True),+ ),+ (+ "status",+ models.CharField(+ choices=[+ ("Cancelled", "Cancelled"),+ ("Completed", "Completed"),+ ("ContinuedAsNew", "Continued As New"),+ ("Failed", "Failed"),+ ("FailedRetryable", "Failed Retryable"),+ ("Terminated", "Terminated"),+ ("TimedOut", "Timedout"),+ ("Running", "Running"),+ ("Starting", "Starting"),+ ],+ help_text="The status of this backfill.",+ max_length=64,+ ),+ ),+ (+ "created_at",+ models.DateTimeField(+ auto_now_add=True,+ help_text="The timestamp at which this BatchExportBackfill was created.",+ ),+ ),+ (+ "finished_at",+ models.DateTimeField(+ help_text="The timestamp at which this BatchExportBackfill finished, successfully or not.",+ null=True,+ ),+ ),+ (+ "last_updated_at",+ models.DateTimeField(+ auto_now=True,+ help_text="The timestamp at which this BatchExportBackfill was last updated.",+ ),+ ),+ (+ "total_records_count",+ models.BigIntegerField(+ blank=True,+ help_text="The total number of records to export. Initially estimated, updated with actual count after completion.",+ null=True,+ ),+ ),+ (+ "adjusted_start_at",+ models.DateTimeField(+ blank=True,+ help_text="The actual start time after adjustment for earliest available data. May differ from start_at if user requested a date before data exists.",+ null=True,+ ),+ ),+ (+ "batch_export",+ models.ForeignKey(+ help_text="The BatchExport this backfill belongs to.",+ on_delete=django.db.models.deletion.CASCADE,+ to="batch_exports.batchexport",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ help_text="The team this belongs to.",+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "posthog_batchexportbackfill",+ "abstract": False,+ },+ ),+ migrations.CreateModel(+ name="BatchExportDestination",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.UUIDT,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "type",+ models.CharField(+ choices=[+ ("S3", "S3"),+ ("Snowflake", "Snowflake"),+ ("Postgres", "Postgres"),+ ("Redshift", "Redshift"),+ ("BigQuery", "Bigquery"),+ ("Databricks", "Databricks"),+ ("AzureBlob", "Azure Blob"),+ ("Workflows", "Workflows"),+ ("HTTP", "Http"),+ ("NoOp", "Noop"),+ ("FileDownload", "File Download"),+ ],+ help_text="A choice of supported BatchExportDestination types.",+ max_length=64,+ ),+ ),+ (+ "config",+ posthog.helpers.encrypted_fields.EncryptedJSONField(+ blank=True,+ default=dict,+ help_text="A JSON field to store all configuration parameters required to access a BatchExportDestination.",+ ),+ ),+ (+ "created_at",+ models.DateTimeField(+ auto_now_add=True,+ help_text="The timestamp at which this BatchExportDestination was created.",+ ),+ ),+ (+ "last_updated_at",+ models.DateTimeField(+ auto_now=True,+ help_text="The timestamp at which this BatchExportDestination was last updated.",+ ),+ ),+ (+ "integration",+ models.ForeignKey(+ blank=True,+ help_text="The integration for this destination.",+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to="posthog.integration",+ ),+ ),+ ],+ options={+ "db_table": "posthog_batchexportdestination",+ "abstract": False,+ },+ ),+ migrations.AddField(+ model_name="batchexport",+ name="destination",+ field=models.ForeignKey(+ help_text="The destination to export data to.",+ on_delete=django.db.models.deletion.CASCADE,+ to="batch_exports.batchexportdestination",+ ),+ ),+ migrations.CreateModel(+ name="BatchExportOnDemand",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.UUIDT,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "deleted",+ models.BooleanField(default=False, help_text="Whether this is deleted or not."),+ ),+ (+ "created_at",+ models.DateTimeField(+ auto_now_add=True,+ help_text="The timestamp at which this was created.",+ ),+ ),+ (+ "last_updated_at",+ models.DateTimeField(+ auto_now=True,+ help_text="The timestamp at which this was last updated.",+ ),+ ),+ (+ "model",+ models.CharField(+ blank=True,+ choices=[+ ("events", "Events"),+ ("persons", "Persons"),+ ("sessions", "Sessions"),+ ],+ default="events",+ help_text="Which model this batch export is exporting.",+ max_length=64,+ null=True,+ ),+ ),+ ("filters", models.JSONField(blank=True, null=True)),+ (+ "destination",+ models.ForeignKey(+ help_text="The destination to export data to.",+ on_delete=django.db.models.deletion.CASCADE,+ to="batch_exports.batchexportdestination",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ help_text="The team this belongs to.",+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "posthog_batchexportondemand",+ "abstract": False,+ },+ ),+ migrations.CreateModel(+ name="BatchExportRun",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.UUIDT,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "status",+ models.CharField(+ choices=[+ ("Cancelled", "Cancelled"),+ ("Completed", "Completed"),+ ("ContinuedAsNew", "Continued As New"),+ ("Failed", "Failed"),+ ("FailedRetryable", "Failed Retryable"),+ ("FailedBilling", "Failed Billing"),+ ("Terminated", "Terminated"),+ ("TimedOut", "Timedout"),+ ("Running", "Running"),+ ("Starting", "Starting"),+ ],+ help_text="The status of this run.",+ max_length=64,+ ),+ ),+ (+ "records_completed",+ models.IntegerField(+ help_text="The number of records that have been exported.",+ null=True,+ ),+ ),+ (+ "records_failed",+ models.IntegerField(+ help_text="The number of records that failed downstream processing (e.g. hog function execution errors).",+ null=True,+ ),+ ),+ (+ "latest_error",+ models.TextField(+ help_text="The latest error that occurred during this run.",+ null=True,+ ),+ ),+ (+ "data_interval_start",+ models.DateTimeField(help_text="The start of the data interval.", null=True),+ ),+ (+ "data_interval_end",+ models.DateTimeField(help_text="The end of the data interval."),+ ),+ (+ "cursor",+ models.TextField(+ help_text="An opaque cursor that may be used to resume.",+ null=True,+ ),+ ),+ (+ "created_at",+ models.DateTimeField(+ auto_now_add=True,+ help_text="The timestamp at which this BatchExportRun was created.",+ ),+ ),+ (+ "finished_at",+ models.DateTimeField(+ help_text="The timestamp at which this BatchExportRun finished, successfully or not.",+ null=True,+ ),+ ),+ (+ "last_updated_at",+ models.DateTimeField(+ auto_now=True,+ help_text="The timestamp at which this BatchExportRun was last updated.",+ ),+ ),+ (+ "records_total_count",+ models.IntegerField(+ help_text="The total count of records that should be exported in this BatchExportRun.",+ null=True,+ ),+ ),+ (+ "bytes_exported",+ models.BigIntegerField(+ blank=True,+ help_text="The number of bytes that have been exported in this BatchExportRun.",+ null=True,+ ),+ ),+ (+ "backfill",+ models.ForeignKey(+ blank=True,+ help_text="The backfill this run belongs to.",+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="runs",+ related_query_name="run",+ to="batch_exports.batchexportbackfill",+ ),+ ),+ (+ "batch_export",+ models.ForeignKey(+ help_text="The `BatchExport` this run belongs to.",+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ to="batch_exports.batchexport",+ ),+ ),+ (+ "batch_export_on_demand",+ models.ForeignKey(+ help_text="The `BatchExportOnDemand` this run belongs to.",+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ to="batch_exports.batchexportondemand",+ ),+ ),+ ],+ options={+ "db_table": "posthog_batchexportrun",+ },+ ),+ migrations.CreateModel(+ name="BatchExportFileDownload",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.UUIDT,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "key",+ models.TextField(help_text="The S3 key containing the file to download."),+ ),+ (+ "expires_at",+ models.DateTimeField(help_text="When will this key expire, if available.", null=True),+ ),+ (+ "created_at",+ models.DateTimeField(+ auto_now_add=True,+ help_text="The timestamp at which this was created.",+ ),+ ),+ (+ "last_updated_at",+ models.DateTimeField(+ auto_now=True,+ help_text="The timestamp at which this was last updated.",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ help_text="The team this belongs to.",+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ (+ "batch_export_run",+ models.ForeignKey(+ help_text="The batch export run that generated this file downloads.",+ on_delete=django.db.models.deletion.CASCADE,+ to="batch_exports.batchexportrun",+ ),+ ),+ ],+ options={+ "db_table": "posthog_batchexportfiledownload",+ },+ ),+ migrations.AddConstraint(+ model_name="batchexportrun",+ constraint=models.CheckConstraint(+ condition=models.Q(+ models.Q(+ ("batch_export__isnull", False),+ ("batch_export_on_demand__isnull", True),+ ),+ models.Q(+ ("batch_export__isnull", True),+ ("batch_export_on_demand__isnull", False),+ ),+ _connector="OR",+ ),+ name="run_has_exactly_one_parent_batch_export_or_batch_export_on_demand",+ ),+ ),+ migrations.AddIndex(+ model_name="batchexportfiledownload",+ index=models.Index(fields=["team", "key"], name="team_key_idx"),+ ),+ ],+ database_operations=[],+ ),+ ]diff --git a/products/batch_exports/backend/migrations/0003_alter_batchexportdestination_type.py b/products/batch_exports/backend/migrations/0003_alter_batchexportdestination_type.pynew file mode 100644index 000000000000..f91b44338ed8--- /dev/null+++ b/products/batch_exports/backend/migrations/0003_alter_batchexportdestination_type.py@@ -0,0 +1,35 @@+# Generated by Django 5.2.14 on 2026-06-03 06:38++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("batch_exports", "0002_batchexport_batchexportbackfill_and_more"),+ ]++ operations = [+ migrations.AlterField(+ model_name="batchexportdestination",+ name="type",+ field=models.CharField(+ choices=[+ ("S3", "S3"),+ ("AwsS3", "Aws S3"),+ ("S3Compatible", "S3 Compatible"),+ ("Snowflake", "Snowflake"),+ ("Postgres", "Postgres"),+ ("Redshift", "Redshift"),+ ("BigQuery", "Bigquery"),+ ("Databricks", "Databricks"),+ ("AzureBlob", "Azure Blob"),+ ("Workflows", "Workflows"),+ ("HTTP", "Http"),+ ("NoOp", "Noop"),+ ("FileDownload", "File Download"),+ ],+ help_text="A choice of supported BatchExportDestination types.",+ max_length=64,+ ),+ ),+ ]diff --git a/products/batch_exports/backend/migrations/__init__.py b/products/batch_exports/backend/migrations/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/batch_exports/backend/migrations/max_migration.txt b/products/batch_exports/backend/migrations/max_migration.txtnew file mode 100644index 000000000000..9619a5d6c573--- /dev/null+++ b/products/batch_exports/backend/migrations/max_migration.txt@@ -0,0 +1 @@+0003_alter_batchexportdestination_typediff --git a/products/batch_exports/backend/models/__init__.py b/products/batch_exports/backend/models/__init__.pynew file mode 100644index 000000000000..16d2752fa5c6--- /dev/null+++ b/products/batch_exports/backend/models/__init__.py@@ -0,0 +1,23 @@+from .batch_export import (+ BatchExport,+ BatchExportBackfill,+ BatchExportDestination,+ BatchExportFileDownload,+ BatchExportOnDemand,+ BatchExportRun,+ DayOfWeek,+)+from .batch_imports import BatchImport, ContentType, DateRangeExportSource++__all__ = [+ "BatchExport",+ "BatchExportBackfill",+ "BatchExportDestination",+ "BatchExportFileDownload",+ "BatchExportOnDemand",+ "BatchExportRun",+ "BatchImport",+ "ContentType",+ "DateRangeExportSource",+ "DayOfWeek",+]diff --git a/posthog/batch_exports/models.py b/products/batch_exports/backend/models/batch_export.pysimilarity index 96%rename from posthog/batch_exports/models.pyrename to products/batch_exports/backend/models/batch_export.pyindex 6a9cb9c5e5ec..ba512e634ffc 100644--- a/posthog/batch_exports/models.py+++ b/products/batch_exports/backend/models/batch_export.py@@ -60,6 +60,9 @@ class BatchExportDestination(UUIDTModel):will have different configuration parameters."""+ class Meta:+ db_table = "posthog_batchexportdestination"+class Destination(models.TextChoices):"""Enumeration of supported destinations for PostHog BatchExports."""@@ -113,7 +116,7 @@ class BatchExportDestination(UUIDTModel):help_text="The timestamp at which this BatchExportDestination was last updated.",)integration = models.ForeignKey(- "Integration",+ "posthog.Integration",on_delete=models.SET_NULL,help_text="The integration for this destination.",null=True,@@ -129,6 +132,7 @@ class BatchExportRun(UUIDTModel):"""class Meta:+ db_table = "posthog_batchexportrun"constraints = [models.CheckConstraint(check=(@@ -263,6 +267,9 @@ class BatchExport(ModelActivityMixin, UUIDTModel):`BatchExportBackfill` model."""+ class Meta:+ db_table = "posthog_batchexport"+class Model(models.TextChoices):"""Possible data models that this BatchExport can export."""@@ -270,7 +277,7 @@ class BatchExport(ModelActivityMixin, UUIDTModel):PERSONS = "persons"SESSIONS = "sessions"- team = models.ForeignKey("Team", on_delete=models.CASCADE, help_text="The team this belongs to.")+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, help_text="The team this belongs to.")name = models.TextField(help_text="A human-readable name for this BatchExport.")destination = models.ForeignKey("BatchExportDestination",@@ -432,6 +439,9 @@ class BatchExport(ModelActivityMixin, UUIDTModel):class BatchExportBackfill(UUIDTModel):+ class Meta:+ db_table = "posthog_batchexportbackfill"+class Status(models.TextChoices):"""Possible states of the BatchExportBackfill."""@@ -445,7 +455,7 @@ class BatchExportBackfill(UUIDTModel):RUNNING = "Running"STARTING = "Starting"- team = models.ForeignKey("Team", on_delete=models.CASCADE, help_text="The team this belongs to.")+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, help_text="The team this belongs to.")batch_export = models.ForeignKey("BatchExport",on_delete=models.CASCADE,@@ -540,11 +550,12 @@ class BatchExportFileDownload(ModelActivityMixin, UUIDTModel):"""class Meta:+ db_table = "posthog_batchexportfiledownload"indexes = [models.Index(fields=["team", "key"], name="team_key_idx"),]- team = models.ForeignKey("Team", on_delete=models.CASCADE, help_text="The team this belongs to.")+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, help_text="The team this belongs to.")batch_export_run = models.ForeignKey("BatchExportRun",on_delete=models.CASCADE,@@ -594,6 +605,9 @@ class BatchExportOnDemand(TeamScopedRootMixin, ModelActivityMixin, UUIDTModel):an on demand batch export does not run on a schedule."""+ class Meta:+ db_table = "posthog_batchexportondemand"+class Model(models.TextChoices):"""Possible data models that this BatchExport can export."""@@ -601,7 +615,7 @@ class BatchExportOnDemand(TeamScopedRootMixin, ModelActivityMixin, UUIDTModel):PERSONS = "persons"SESSIONS = "sessions"- team = models.ForeignKey("Team", on_delete=models.CASCADE, help_text="The team this belongs to.")+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, help_text="The team this belongs to.")destination = models.ForeignKey("BatchExportDestination",on_delete=models.CASCADE,diff --git a/posthog/models/batch_imports.py b/products/batch_exports/backend/models/batch_imports.pysimilarity index 98%rename from posthog/models/batch_imports.pyrename to products/batch_exports/backend/models/batch_imports.pyindex 48f1aeb0ecdc..92d3e634568b 100644--- a/posthog/models/batch_imports.py+++ b/products/batch_exports/backend/models/batch_imports.py@@ -5,7 +5,6 @@ from django.db import modelsfrom posthog.helpers.encrypted_fields import EncryptedJSONStringFieldfrom posthog.models.activity_logging.model_activity import ModelActivityMixin-from posthog.models.team import Teamfrom posthog.models.utils import UUIDTModel@@ -30,7 +29,7 @@ class BatchImport(ModelActivityMixin, UUIDTModel):PAUSED = "paused", "Paused"RUNNING = "running", "Running"- team = models.ForeignKey(Team, on_delete=models.CASCADE)+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)created_by_id = models.IntegerField(null=True, blank=True)created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)@@ -49,6 +48,9 @@ class BatchImport(ModelActivityMixin, UUIDTModel):backoff_attempt = models.IntegerField(default=0)backoff_until = models.DateTimeField(null=True, blank=True)+ class Meta:+ db_table = "posthog_batchimport"+def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)self._config_builder = BatchImportConfigBuilder(self, initialize_empty=not self.import_config)diff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.pyindex 64390b3a1ea1..e35146b4e565 100644--- a/products/batch_exports/backend/service.py+++ b/products/batch_exports/backend/service.py@@ -28,13 +28,6 @@ from temporalio.client import (from posthog.hogql.database.database import Databasefrom posthog.hogql.hogql import HogQLContext-from posthog.batch_exports.models import (- BatchExport,- BatchExportBackfill,- BatchExportDestination,- BatchExportOnDemand,- BatchExportRun,-)from posthog.temporal.common.client import sync_connectfrom posthog.temporal.common.schedule import (a_pause_schedule,@@ -45,6 +38,14 @@ from posthog.temporal.common.schedule import (update_schedule,)+from products.batch_exports.backend.models.batch_export import (+ BatchExport,+ BatchExportBackfill,+ BatchExportDestination,+ BatchExportOnDemand,+ BatchExportRun,+)+logger = structlog.get_logger(__name__)diff --git a/posthog/batch_exports/sql.py b/products/batch_exports/backend/sql.pysimilarity index 100%rename from posthog/batch_exports/sql.pyrename to products/batch_exports/backend/sql.pydiff --git a/products/batch_exports/backend/temporal/backfill_batch_export.py b/products/batch_exports/backend/temporal/backfill_batch_export.pyindex a4a67602d910..e1d73be516eb 100644--- a/products/batch_exports/backend/temporal/backfill_batch_export.py+++ b/products/batch_exports/backend/temporal/backfill_batch_export.py@@ -19,7 +19,6 @@ import temporalio.exceptionsfrom asgiref.sync import sync_to_asyncfrom structlog.contextvars import bind_contextvars-from posthog.batch_exports.models import BatchExport, BatchExportBackfill, BatchExportRunfrom posthog.clickhouse import query_taggingfrom posthog.clickhouse.query_tagging import Productfrom posthog.sync import database_sync_to_async@@ -34,6 +33,7 @@ from posthog.temporal.common.client import connectfrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.logger import get_write_only_logger+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportBackfill, BatchExportRunfrom products.batch_exports.backend.service import (BackfillBatchExportInputs,BackfillDetails,diff --git a/products/batch_exports/backend/temporal/batch_exports.py b/products/batch_exports/backend/temporal/batch_exports.pyindex a86b652c6ba9..d547e25fc54d 100644--- a/products/batch_exports/backend/temporal/batch_exports.py+++ b/products/batch_exports/backend/temporal/batch_exports.py@@ -14,7 +14,6 @@ from structlog.contextvars import bind_contextvarsfrom temporalio import activity, exceptions, workflowfrom temporalio.common import RetryPolicy-from posthog.batch_exports.models import BatchExport, BatchExportRunfrom posthog.kafka_client.routing import async_producer_scopefrom posthog.kafka_client.topics import KAFKA_APP_METRICS2from posthog.models.team.team import Team@@ -26,6 +25,7 @@ from posthog.temporal.common.clickhouse import ClickHouseClientfrom posthog.temporal.common.client import connectfrom posthog.temporal.common.logger import get_logger, get_write_only_logger+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportRunfrom products.batch_exports.backend.service import (BackfillDetails,BatchExportField,diff --git a/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py b/products/batch_exports/backend/temporal/destinations/file_download_batch_export.pyindex 5a4d568f8c30..48dd4de39ceb 100644--- a/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/file_download_batch_export.py@@ -13,11 +13,11 @@ from botocore.exceptions import ClientErrorfrom temporalio import activity, workflowfrom temporalio.common import RetryPolicy-from posthog.batch_exports.models import BatchExportFileDownloadfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.logger import get_logger, get_write_only_logger+from products.batch_exports.backend.models.batch_export import BatchExportFileDownloadfrom products.batch_exports.backend.service import BatchExportInsertInputs, FileDownloadBatchExportInputsfrom products.batch_exports.backend.temporal.batch_exports import (OverBillingLimitError,diff --git a/products/batch_exports/backend/temporal/destinations/http_batch_export.py b/products/batch_exports/backend/temporal/destinations/http_batch_export.pyindex 2ed49ebce7ed..820ec75eb7fd 100644--- a/products/batch_exports/backend/temporal/destinations/http_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/http_batch_export.py@@ -11,12 +11,12 @@ from structlog.contextvars import bind_contextvarsfrom temporalio import activity, workflowfrom temporalio.common import RetryPolicy-from posthog.models import BatchExportRunfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.clickhouse import get_clientfrom posthog.temporal.common.logger import get_logger+from products.batch_exports.backend.models.batch_export import BatchExportRunfrom products.batch_exports.backend.service import BatchExportField, BatchExportInsertInputs, HttpBatchExportInputsfrom products.batch_exports.backend.temporal.batch_exports import (FinishBatchExportRunInputs,diff --git a/products/batch_exports/backend/temporal/monitoring.py b/products/batch_exports/backend/temporal/monitoring.pyindex 83880259e109..c5da8ffbc021 100644--- a/products/batch_exports/backend/temporal/monitoring.py+++ b/products/batch_exports/backend/temporal/monitoring.py@@ -7,12 +7,12 @@ from structlog.contextvars import bind_contextvarsfrom temporalio import activity, workflowfrom temporalio.common import RetryPolicy-from posthog.batch_exports.models import BatchExport, BatchExportRunfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.clickhouse import get_clientfrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.logger import get_logger+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportRunfrom products.batch_exports.backend.service import afetch_batch_export_runs_in_range, aupdate_records_total_countfrom products.batch_exports.backend.temporal.sql import EVENT_COUNT_BY_INTERVALdiff --git a/products/batch_exports/backend/temporal/pipeline/entrypoint.py b/products/batch_exports/backend/temporal/pipeline/entrypoint.pyindex fcffb3d02005..19b58bc64552 100644--- a/products/batch_exports/backend/temporal/pipeline/entrypoint.py+++ b/products/batch_exports/backend/temporal/pipeline/entrypoint.py@@ -7,10 +7,10 @@ from django.conf import settingsfrom temporalio import exceptions, workflowfrom temporalio.common import RetryPolicy-from posthog.batch_exports.models import BatchExportRunfrom posthog.settings.base_variables import TESTfrom posthog.temporal.common.logger import get_write_only_logger+from products.batch_exports.backend.models.batch_export import BatchExportRunfrom products.batch_exports.backend.service import (BackfillDetails,BatchExportField,diff --git a/products/batch_exports/backend/temporal/utils.py b/products/batch_exports/backend/temporal/utils.pyindex d3b25de92249..889d8caa676f 100644--- a/products/batch_exports/backend/temporal/utils.py+++ b/products/batch_exports/backend/temporal/utils.py@@ -10,9 +10,9 @@ import collections.abcimport orjsonimport pyarrow as pa-from posthog.batch_exports.models import BatchExportRunfrom posthog.temporal.common.logger import get_write_only_logger+from products.batch_exports.backend.models.batch_export import BatchExportRunfrom products.batch_exports.backend.service import aupdate_batch_export_runfrom products.batch_exports.backend.temporal.pipeline.types import BatchExportResultdiff --git a/posthog/batch_exports/tests/conftest.py b/products/batch_exports/backend/tests/conftest_legacy.pysimilarity index 100%rename from posthog/batch_exports/tests/conftest.pyrename to products/batch_exports/backend/tests/conftest_legacy.pydiff --git a/products/batch_exports/backend/tests/temporal/backfills/test_backfill_workflow.py b/products/batch_exports/backend/tests/temporal/backfills/test_backfill_workflow.pyindex c8cc3a09580a..05da387aebc3 100644--- a/products/batch_exports/backend/tests/temporal/backfills/test_backfill_workflow.py+++ b/products/batch_exports/backend/tests/temporal/backfills/test_backfill_workflow.py@@ -13,7 +13,6 @@ import temporalio.commonimport temporalio.exceptionsfrom asgiref.sync import sync_to_async-from posthog.batch_exports.models import BatchExportBackfillfrom posthog.temporal.tests.utils.models import (acreate_batch_export,adelete_batch_export,@@ -21,6 +20,7 @@ from posthog.temporal.tests.utils.models import (afetch_batch_export_backfills,)+from products.batch_exports.backend.models.batch_export import BatchExportBackfillfrom products.batch_exports.backend.temporal.backfill_batch_export import (BackfillBatchExportInputs,BackfillBatchExportWorkflow,diff --git a/products/batch_exports/backend/tests/temporal/backfills/test_get_backfill_info.py b/products/batch_exports/backend/tests/temporal/backfills/test_get_backfill_info.pyindex 2cbceb2b6d07..7b6e30a3017b 100644--- a/products/batch_exports/backend/tests/temporal/backfills/test_get_backfill_info.py+++ b/products/batch_exports/backend/tests/temporal/backfills/test_get_backfill_info.py@@ -7,11 +7,11 @@ from unittest.mock import AsyncMock, patchfrom temporalio.testing import ActivityEnvironment-from posthog.batch_exports.models import BatchExport, BatchExportDestinationfrom posthog.models.utils import uuid7from posthog.temporal.common.clickhouse import ClickHouseQueryTimeoutErrorfrom posthog.temporal.tests.utils.events import generate_test_events_in_clickhouse, insert_sessions_in_clickhouse+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestinationfrom products.batch_exports.backend.temporal.backfill_batch_export import (BACKFILL_INFO_QUERY_TIMEOUT_SECONDS,GetBackfillInfoInputs,diff --git a/products/batch_exports/backend/tests/temporal/destinations/azure_blob/conftest.py b/products/batch_exports/backend/tests/temporal/destinations/azure_blob/conftest.pyindex d70165801b00..4a05f07698fc 100644--- a/products/batch_exports/backend/tests/temporal/destinations/azure_blob/conftest.py+++ b/products/batch_exports/backend/tests/temporal/destinations/azure_blob/conftest.py@@ -7,9 +7,10 @@ import pytest_asynciofrom asgiref.sync import sync_to_asyncfrom azure.storage.blob.aio import BlobServiceClient-from posthog.batch_exports.models import BatchExport, BatchExportDestinationfrom posthog.models.integration import Integration+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination+pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]# Azurite emulator default storage account credentials.diff --git a/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_workflow_with_azure_account.py b/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_workflow_with_azure_account.pyindex 922f9e6190f7..37e338f86dc1 100644--- a/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_workflow_with_azure_account.py+++ b/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_workflow_with_azure_account.py@@ -20,9 +20,9 @@ import pytest_asynciofrom asgiref.sync import sync_to_asyncfrom azure.storage.blob.aio import BlobServiceClient-from posthog.batch_exports.models import BatchExport, BatchExportDestinationfrom posthog.models.integration import Integration+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestinationfrom products.batch_exports.backend.service import BatchExportModel, BatchExportSchemafrom products.batch_exports.backend.temporal.destinations.azure_blob_batch_export import SUPPORTED_COMPRESSIONSfrom products.batch_exports.backend.tests.temporal.destinations.azure_blob.utils import (diff --git a/products/batch_exports/backend/tests/temporal/destinations/base_destination_tests.py b/products/batch_exports/backend/tests/temporal/destinations/base_destination_tests.pyindex c32f6112729c..d7cdc84ae86c 100644--- a/products/batch_exports/backend/tests/temporal/destinations/base_destination_tests.py+++ b/products/batch_exports/backend/tests/temporal/destinations/base_destination_tests.py@@ -21,13 +21,13 @@ from temporalio.common import RetryPolicyfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker-from posthog.batch_exports.models import BatchExportfrom posthog.models.integration import Integrationfrom posthog.models.team import Teamfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.logger import BATCH_EXPORT_WORKFLOW_TYPES as LOGGER_BATCH_EXPORT_WORKFLOW_TYPESfrom posthog.temporal.tests.utils.models import acreate_batch_export, adelete_batch_export, afetch_batch_export_runs+from products.batch_exports.backend.models.batch_export import BatchExportfrom products.batch_exports.backend.service import (BackfillDetails,BaseBatchExportInputs,diff --git a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_activity.py b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_activity.pyindex 7a8cf07fd19a..b44c0377b217 100644--- a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_activity.py+++ b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_activity.py@@ -6,9 +6,9 @@ from django.test import override_settingsfrom temporalio.testing._activity import ActivityEnvironment-from posthog.batch_exports.models import BatchExportFileDownload, BatchExportRunfrom posthog.temporal.tests.utils.models import acreate_batch_export, adelete_batch_export+from products.batch_exports.backend.models.batch_export import BatchExportFileDownload, BatchExportRunfrom products.batch_exports.backend.service import BatchExportInsertInputs, BatchExportModel, BatchExportSchemafrom products.batch_exports.backend.temporal.destinations.file_download_batch_export import (ExportInputs,diff --git a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.pyindex 0ea2011eb70d..3fcc6447c2f8 100644--- a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py+++ b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_api.py@@ -18,14 +18,19 @@ from asgiref.sync import sync_to_asyncfrom rest_framework import statusfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker-from posthog.batch_exports.api.file_download import (+from posthog.models.scoping import team_scope++from products.batch_exports.backend.api.file_download import (_calculate_expiration_for_file_download,_generate_s3_pre_signed_url,_get_file_download_for_run,)-from posthog.models import BatchExportDestination, BatchExportFileDownload, BatchExportOnDemand, BatchExportRun-from posthog.models.scoping import team_scope-+from products.batch_exports.backend.models.batch_export import (+ BatchExportDestination,+ BatchExportFileDownload,+ BatchExportOnDemand,+ BatchExportRun,+)from products.batch_exports.backend.temporal import ACTIVITIES, WORKFLOWSpytestmark = [@@ -339,7 +344,9 @@ async def test_file_download_create_rejects_when_concurrency_limit_reached(await async_client.aforce_login(user)- with unittest.mock.patch("posthog.batch_exports.api.file_download.start_file_download_batch_export") as mock_start:+ with unittest.mock.patch(+ "products.batch_exports.backend.api.file_download.start_file_download_batch_export"+ ) as mock_start:response = await async_client.post(f"/api/projects/{team.pk}/file_download_batch_exports",{@@ -369,7 +376,9 @@ async def test_file_download_create_rejects_future_data_interval_end(await async_client.aforce_login(user)- with unittest.mock.patch("posthog.batch_exports.api.file_download.start_file_download_batch_export") as mock_start:+ with unittest.mock.patch(+ "products.batch_exports.backend.api.file_download.start_file_download_batch_export"+ ) as mock_start:data_interval_end_iso = (now + dt.timedelta(hours=1)).isoformat()response = await async_client.post(f"/api/projects/{team.pk}/file_download_batch_exports",@@ -542,7 +551,7 @@ async def test_file_download_cancel_mocked(mocked_handle = unittest.mock.AsyncMock()mocked_client.get_workflow_handle.return_value = mocked_handle- with unittest.mock.patch("posthog.batch_exports.api.file_download.sync_connect") as mocked_connect:+ with unittest.mock.patch("products.batch_exports.backend.api.file_download.sync_connect") as mocked_connect:mocked_connect.return_value = mocked_clientstatus_response = await async_client.post(f"/api/projects/{team.pk}/file_download_batch_exports/{run.id}/cancel",diff --git a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_workflow.py b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_workflow.pyindex 05e693e15ca9..c66b11efb156 100644--- a/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_workflow.py+++ b/products/batch_exports/backend/tests/temporal/destinations/file_download/test_file_download_workflow.py@@ -11,9 +11,9 @@ from temporalio.common import RetryPolicyfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker-from posthog.batch_exports.models import BatchExportFileDownloadfrom posthog.temporal.tests.utils.models import acreate_batch_export, adelete_batch_export, afetch_batch_export_runs+from products.batch_exports.backend.models.batch_export import BatchExportFileDownloadfrom products.batch_exports.backend.service import BatchExportModel, FileDownloadBatchExportInputsfrom products.batch_exports.backend.temporal.batch_exports import finish_batch_export_run, start_batch_export_runfrom products.batch_exports.backend.temporal.destinations.file_download_batch_export import (diff --git a/products/batch_exports/backend/tests/temporal/destinations/redshift/test_workflow.py b/products/batch_exports/backend/tests/temporal/destinations/redshift/test_workflow.pyindex 50e0b7753695..5243ac42063a 100644--- a/products/batch_exports/backend/tests/temporal/destinations/redshift/test_workflow.py+++ b/products/batch_exports/backend/tests/temporal/destinations/redshift/test_workflow.py@@ -15,9 +15,9 @@ from temporalio.common import RetryPolicyfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker-from posthog.batch_exports.models import BatchExportfrom posthog.temporal.tests.utils.models import acreate_batch_export, adelete_batch_export, afetch_batch_export_runs+from products.batch_exports.backend.models.batch_export import BatchExportfrom products.batch_exports.backend.service import BatchExportModel, BatchExportSchema, RedshiftCopyInputsfrom products.batch_exports.backend.temporal.batch_exports import finish_batch_export_run, start_batch_export_runfrom products.batch_exports.backend.temporal.destinations.redshift_batch_export import (diff --git a/products/batch_exports/backend/tests/temporal/destinations/snowflake/conftest.py b/products/batch_exports/backend/tests/temporal/destinations/snowflake/conftest.pyindex 2edbdfd84d0b..bb75c06121ad 100644--- a/products/batch_exports/backend/tests/temporal/destinations/snowflake/conftest.py+++ b/products/batch_exports/backend/tests/temporal/destinations/snowflake/conftest.py@@ -8,9 +8,9 @@ import pytestimport pytest_asyncioimport snowflake.connector-from posthog.batch_exports.models import BatchExportfrom posthog.temporal.tests.utils.models import acreate_batch_export, adelete_batch_export+from products.batch_exports.backend.models.batch_export import BatchExportfrom products.batch_exports.backend.temporal.destinations.snowflake_batch_export import load_private_keydiff --git a/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_workflow.py b/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_workflow.pyindex 7775ab4ac08a..d9736fabd0da 100644--- a/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_workflow.py+++ b/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_workflow.py@@ -21,10 +21,10 @@ from temporalio.exceptions import ActivityError, ApplicationErrorfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker-from posthog.batch_exports.models import BatchExport, BatchExportRunfrom posthog.temporal.tests.utils.events import generate_test_events_in_clickhousefrom posthog.temporal.tests.utils.models import afetch_batch_export_runs+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportRunfrom products.batch_exports.backend.temporal.batch_exports import finish_batch_export_run, start_batch_export_runfrom products.batch_exports.backend.temporal.destinations.snowflake_batch_export import (SnowflakeBatchExportInputs,diff --git a/products/batch_exports/backend/tests/temporal/pipeline/test_entrypoint.py b/products/batch_exports/backend/tests/temporal/pipeline/test_entrypoint.pyindex d28e1639e751..c9c014d2ae40 100644--- a/products/batch_exports/backend/tests/temporal/pipeline/test_entrypoint.py+++ b/products/batch_exports/backend/tests/temporal/pipeline/test_entrypoint.py@@ -14,10 +14,10 @@ from temporalio.common import RetryPolicyfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker-from posthog.models import BatchExport, BatchExportDestinationfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.tests.utils.models import afetch_batch_export_runs+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestinationfrom products.batch_exports.backend.service import BaseBatchExportInputs, BatchExportInsertInputs, BatchExportModelfrom products.batch_exports.backend.temporal.batch_exports import (StartBatchExportRunInputs,diff --git a/products/batch_exports/backend/tests/temporal/test_batch_export_utils.py b/products/batch_exports/backend/tests/temporal/test_batch_export_utils.pyindex 160c9d606d98..7294a26a7a34 100644--- a/products/batch_exports/backend/tests/temporal/test_batch_export_utils.py+++ b/products/batch_exports/backend/tests/temporal/test_batch_export_utils.py@@ -6,9 +6,9 @@ import pytestimport pyarrow as paimport pytest_asyncio-from posthog.batch_exports.models import BatchExportRunfrom posthog.temporal.tests.utils.models import acreate_batch_export, adelete_batch_export+from products.batch_exports.backend.models.batch_export import BatchExportRunfrom products.batch_exports.backend.temporal.utils import (JsonType,make_retryable_with_exponential_backoff,diff --git a/products/batch_exports/backend/tests/temporal/test_monitoring.py b/products/batch_exports/backend/tests/temporal/test_monitoring.pyindex 03d91a8f89eb..d45a66f030f0 100644--- a/products/batch_exports/backend/tests/temporal/test_monitoring.py+++ b/products/batch_exports/backend/tests/temporal/test_monitoring.py@@ -12,9 +12,9 @@ from temporalio.common import RetryPolicyfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker-from posthog.batch_exports.models import BatchExportRunfrom posthog.temporal.tests.utils.models import acreate_batch_export, adelete_batch_export, afetch_batch_export_runs+from products.batch_exports.backend.models.batch_export import BatchExportRunfrom products.batch_exports.backend.service import afetch_batch_export_runs_in_rangefrom products.batch_exports.backend.temporal.monitoring import (BatchExportMonitoringInputs,diff --git a/products/batch_exports/backend/tests/temporal/test_realtime_failure_dispatch.py b/products/batch_exports/backend/tests/temporal/test_realtime_failure_dispatch.pyindex d9a489e53620..e19d3376c60a 100644--- a/products/batch_exports/backend/tests/temporal/test_realtime_failure_dispatch.py+++ b/products/batch_exports/backend/tests/temporal/test_realtime_failure_dispatch.py@@ -3,9 +3,9 @@ import datetime as dtfrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch-from posthog.batch_exports.models import BatchExport, BatchExportDestination, BatchExportRunfrom posthog.models.utils import UUIDT+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRunfrom products.batch_exports.backend.temporal.batch_exports import _dispatch_batch_export_failure_realtimediff --git a/products/batch_exports/backend/tests/temporal/test_run_updates.py b/products/batch_exports/backend/tests/temporal/test_run_updates.pyindex e8464e33db69..9363cb7e1a23 100644--- a/products/batch_exports/backend/tests/temporal/test_run_updates.py+++ b/products/batch_exports/backend/tests/temporal/test_run_updates.py@@ -8,8 +8,9 @@ from django.test import override_settingsfrom asgiref.sync import sync_to_async-from posthog.models import BatchExport, BatchExportDestination, BatchExportRun, Organization, Team+from posthog.models import Organization, Team+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRunfrom products.batch_exports.backend.service import delete_batch_export, sync_batch_exportfrom products.batch_exports.backend.temporal.batch_exports import (FinishBatchExportRunInputs,diff --git a/products/batch_exports/backend/tests/temporal/utils/clickhouse.py b/products/batch_exports/backend/tests/temporal/utils/clickhouse.pyindex eee70e2f1a51..7a47a3c1159d 100644--- a/products/batch_exports/backend/tests/temporal/utils/clickhouse.py+++ b/products/batch_exports/backend/tests/temporal/utils/clickhouse.py@@ -25,7 +25,9 @@ async def execute_query(clickhouse_client: ClickHouseClient, query: str, *data):async def create_clickhouse_tables_and_views(clickhouse_client):- from posthog.batch_exports.sql import (+ from posthog.clickhouse.schema import CREATE_KAFKA_TABLE_QUERIES, build_query++ from products.batch_exports.backend.sql import (CREATE_EVENTS_BATCH_EXPORT_VIEW,CREATE_EVENTS_BATCH_EXPORT_VIEW_BACKFILL,CREATE_EVENTS_BATCH_EXPORT_VIEW_RECENT,@@ -33,7 +35,6 @@ async def create_clickhouse_tables_and_views(clickhouse_client):CREATE_PERSONS_BATCH_EXPORT_VIEW,CREATE_PERSONS_BATCH_EXPORT_VIEW_BACKFILL,)- from posthog.clickhouse.schema import CREATE_KAFKA_TABLE_QUERIES, build_querycreate_view_queries = (CREATE_EVENTS_BATCH_EXPORT_VIEW,diff --git a/products/batch_exports/backend/tests/temporal/utils/workflow.py b/products/batch_exports/backend/tests/temporal/utils/workflow.pyindex c510a2d17333..dff6dc7957af 100644--- a/products/batch_exports/backend/tests/temporal/utils/workflow.py+++ b/products/batch_exports/backend/tests/temporal/utils/workflow.py@@ -8,8 +8,7 @@ from temporalio import activityfrom temporalio.client import WorkflowFailureErrorfrom temporalio.exceptions import ActivityError, ApplicationError-from posthog.batch_exports.models import BatchExportRun-+from products.batch_exports.backend.models.batch_export import BatchExportRunfrom products.batch_exports.backend.service import create_batch_export_runfrom products.batch_exports.backend.temporal.batch_exports import StartBatchExportRunInputsdiff --git a/posthog/batch_exports/tests/debug/test_debugger.py b/products/batch_exports/backend/tests/test_debugger.pysimilarity index 97%rename from posthog/batch_exports/tests/debug/test_debugger.pyrename to products/batch_exports/backend/tests/test_debugger.pyindex 97690c7d4e1f..40fd5ab93fdd 100644--- a/posthog/batch_exports/tests/debug/test_debugger.py+++ b/products/batch_exports/backend/tests/test_debugger.py@@ -6,8 +6,8 @@ import pytestimport pyarrow as pa-from posthog.batch_exports.debug.debugger import BatchExportsDebugger, ColumnDebugStatistics-from posthog.batch_exports.models import BatchExport, BatchExportDestination, BatchExportRun+from products.batch_exports.backend.debug.debugger import BatchExportsDebugger, ColumnDebugStatistics+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRunpytestmark = [pytest.mark.django_db,diff --git a/products/batch_exports/backend/tests/test_service.py b/products/batch_exports/backend/tests/test_service.pyindex b7d609f9cead..c29fffc24053 100644--- a/products/batch_exports/backend/tests/test_service.py+++ b/products/batch_exports/backend/tests/test_service.py@@ -3,8 +3,12 @@ import datetime as dtimport pytest-from posthog.batch_exports.models import BatchExport, BatchExportBackfill, BatchExportDestination, BatchExportRun-+from products.batch_exports.backend.models.batch_export import (+ BatchExport,+ BatchExportBackfill,+ BatchExportDestination,+ BatchExportRun,+)from products.batch_exports.backend.service import (AzureBlobBatchExportInputs,BigQueryBatchExportInputs,diff --git a/products/batch_exports/frontend/generated/api.schemas.ts b/products/batch_exports/frontend/generated/api.schemas.tsindex 1e5008c45dd8..b02cffef8e58 100644--- a/products/batch_exports/frontend/generated/api.schemas.ts+++ b/products/batch_exports/frontend/generated/api.schemas.ts@@ -1502,6 +1502,74 @@ export interface FileDownloadBatchExportOnDemandApi {data_interval_end: string}+/**+ * * `completed` - Completed+ * `failed` - Failed+ * `paused` - Paused+ * `running` - Running+ */+export type BatchImportStatusEnumApi = (typeof BatchImportStatusEnumApi)[keyof typeof BatchImportStatusEnumApi]++export const BatchImportStatusEnumApi = {+ Completed: 'completed',+ Failed: 'failed',+ Paused: 'paused',+ Running: 'running',+} as const++/**+ * @nullable+ */+export type BatchImportApiCreatedBy = { [key: string]: unknown } | null++/**+ * Serializer for BatchImport model+ */+export interface BatchImportApi {+ readonly id: string+ readonly team_id: number+ readonly created_at: string+ readonly updated_at: string+ readonly state: unknown+ /** @nullable */+ readonly created_by: BatchImportApiCreatedBy+ readonly status: BatchImportStatusEnumApi+ /** @nullable */+ readonly display_status_message: string | null+ readonly import_config: unknown+}++export interface PaginatedBatchImportListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: BatchImportApi[]+}++/**+ * @nullable+ */+export type PatchedBatchImportApiCreatedBy = { [key: string]: unknown } | null++/**+ * Serializer for BatchImport model+ */+export interface PatchedBatchImportApi {+ readonly id?: string+ readonly team_id?: number+ readonly created_at?: string+ readonly updated_at?: string+ readonly state?: unknown+ /** @nullable */+ readonly created_by?: PatchedBatchImportApiCreatedBy+ readonly status?: BatchImportStatusEnumApi+ /** @nullable */+ readonly display_status_message?: string | null+ readonly import_config?: unknown+}+/*** * `events` - events*/@@ -1743,3 +1811,38 @@ export type FileDownloadBatchExportsLogsRetrieveParams = {*/search?: string}++export type ManagedMigrationsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+ /**+ * Which field to use when ordering the results.+ */+ ordering?: string+ /**+ * A search term.+ */+ search?: string+ /**+ * * `completed` - Completed+ * `failed` - Failed+ * `paused` - Paused+ * `running` - Running+ */+ status?: ManagedMigrationsListStatus+}++export type ManagedMigrationsListStatus = (typeof ManagedMigrationsListStatus)[keyof typeof ManagedMigrationsListStatus]++export const ManagedMigrationsListStatus = {+ Completed: 'completed',+ Failed: 'failed',+ Paused: 'paused',+ Running: 'running',+} as constdiff --git a/products/batch_exports/frontend/generated/api.ts b/products/batch_exports/frontend/generated/api.tsindex 1786b484fc03..e9ee25a70834 100644--- a/products/batch_exports/frontend/generated/api.ts+++ b/products/batch_exports/frontend/generated/api.ts@@ -18,16 +18,20 @@ import type {BatchExportsLogsRetrieveParams,BatchExportsRunsListParams,BatchExportsRunsLogsRetrieveParams,+ BatchImportApi,CreateFileDownloadRequestApi,CreateOutputApi,FileDownloadBatchExportOnDemandApi,FileDownloadBatchExportsListParams,FileDownloadBatchExportsLogsRetrieveParams,+ ManagedMigrationsListParams,PaginatedBatchExportBackfillListApi,PaginatedBatchExportListApi,PaginatedBatchExportRunListApi,+ PaginatedBatchImportListApi,PaginatedListOutputListApi,PatchedBatchExportRequestApi,+ PatchedBatchImportApi,RetrieveFileDownloadResponseApi,} from './api.schemas'@@ -654,3 +658,169 @@ export const fileDownloadBatchExportsLogsRetrieve = async (method: 'GET',})}++export const getManagedMigrationsListUrl = (projectId: string, params?: ManagedMigrationsListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/managed_migrations/?${stringifiedParams}`+ : `/api/projects/${projectId}/managed_migrations/`+}++/**+ * List managed migrations using the response serializer+ */+export const managedMigrationsList = async (+ projectId: string,+ params?: ManagedMigrationsListParams,+ options?: RequestInit+): Promise<PaginatedBatchImportListApi> => {+ return apiMutator<PaginatedBatchImportListApi>(getManagedMigrationsListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getManagedMigrationsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/managed_migrations/`+}++/**+ * Create a new managed migration/batch import.+ */+export const managedMigrationsCreate = async (+ projectId: string,+ batchImportApi?: NonReadonly<BatchImportApi>,+ options?: RequestInit+): Promise<BatchImportApi> => {+ return apiMutator<BatchImportApi>(getManagedMigrationsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(batchImportApi),+ })+}++export const getManagedMigrationsRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/managed_migrations/${id}/`+}++/**+ * Viewset for BatchImport model+ */+export const managedMigrationsRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<BatchImportApi> => {+ return apiMutator<BatchImportApi>(getManagedMigrationsRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getManagedMigrationsUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/managed_migrations/${id}/`+}++/**+ * Viewset for BatchImport model+ */+export const managedMigrationsUpdate = async (+ projectId: string,+ id: string,+ batchImportApi?: NonReadonly<BatchImportApi>,+ options?: RequestInit+): Promise<BatchImportApi> => {+ return apiMutator<BatchImportApi>(getManagedMigrationsUpdateUrl(projectId, id), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(batchImportApi),+ })+}++export const getManagedMigrationsPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/managed_migrations/${id}/`+}++/**+ * Viewset for BatchImport model+ */+export const managedMigrationsPartialUpdate = async (+ projectId: string,+ id: string,+ patchedBatchImportApi?: NonReadonly<PatchedBatchImportApi>,+ options?: RequestInit+): Promise<BatchImportApi> => {+ return apiMutator<BatchImportApi>(getManagedMigrationsPartialUpdateUrl(projectId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedBatchImportApi),+ })+}++export const getManagedMigrationsDestroyUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/managed_migrations/${id}/`+}++/**+ * Viewset for BatchImport model+ */+export const managedMigrationsDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getManagedMigrationsDestroyUrl(projectId, id), {+ ...options,+ method: 'DELETE',+ })+}++export const getManagedMigrationsPauseCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/managed_migrations/${id}/pause/`+}++/**+ * Pause a running batch import.+ */+export const managedMigrationsPauseCreate = async (+ projectId: string,+ id: string,+ batchImportApi?: NonReadonly<BatchImportApi>,+ options?: RequestInit+): Promise<BatchImportApi> => {+ return apiMutator<BatchImportApi>(getManagedMigrationsPauseCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(batchImportApi),+ })+}++export const getManagedMigrationsResumeCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/managed_migrations/${id}/resume/`+}++/**+ * Resume a paused batch import.+ */+export const managedMigrationsResumeCreate = async (+ projectId: string,+ id: string,+ batchImportApi?: NonReadonly<BatchImportApi>,+ options?: RequestInit+): Promise<BatchImportApi> => {+ return apiMutator<BatchImportApi>(getManagedMigrationsResumeCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(batchImportApi),+ })+}diff --git a/products/batch_exports/frontend/generated/api.zod.ts b/products/batch_exports/frontend/generated/api.zod.tsindex d22822f92cb5..0d58e908052e 100644--- a/products/batch_exports/frontend/generated/api.zod.ts+++ b/products/batch_exports/frontend/generated/api.zod.ts@@ -1761,3 +1761,38 @@ export const FileDownloadBatchExportsCancelCreateBody = /* @__PURE__ */ zoddata_interval_end: zod.iso.datetime({ offset: true }),}).describe('Request shape for a FileDownload batch export on demand.')++/**+ * Create a new managed migration/batch import.+ */+export const ManagedMigrationsCreateBody = /* @__PURE__ */ zod+ .looseObject({})+ .describe('Serializer for BatchImport model')++/**+ * Viewset for BatchImport model+ */+export const ManagedMigrationsUpdateBody = /* @__PURE__ */ zod+ .looseObject({})+ .describe('Serializer for BatchImport model')++/**+ * Viewset for BatchImport model+ */+export const ManagedMigrationsPartialUpdateBody = /* @__PURE__ */ zod+ .looseObject({})+ .describe('Serializer for BatchImport model')++/**+ * Pause a running batch import.+ */+export const ManagedMigrationsPauseCreateBody = /* @__PURE__ */ zod+ .looseObject({})+ .describe('Serializer for BatchImport model')++/**+ * Resume a paused batch import.+ */+export const ManagedMigrationsResumeCreateBody = /* @__PURE__ */ zod+ .looseObject({})+ .describe('Serializer for BatchImport model')diff --git a/products/batch_exports/manifest.tsx b/products/batch_exports/manifest.tsxnew file mode 100644index 000000000000..a909e91f084f--- /dev/null+++ b/products/batch_exports/manifest.tsx@@ -0,0 +1,23 @@+/**+ * Product manifest for batch_exports.+ *+ * Defines scenes, routes, URLs, and navigation for this product.+ */+import { ProductManifest } from '../../frontend/src/types'++export const manifest: ProductManifest = {+ name: 'BatchExports',+ scenes: {+ // Define scenes here+ },+ routes: {+ // Define routes here+ },+ redirects: {},+ urls: {+ // Define URL helpers here+ },+ fileSystemTypes: {},+ treeItemsNew: [],+ treeItemsProducts: [],+}diff --git a/products/batch_exports/mcp/tools.yaml b/products/batch_exports/mcp/tools.yamlindex 0227162d6be1..e345b9d7d079 100644--- a/products/batch_exports/mcp/tools.yaml+++ b/products/batch_exports/mcp/tools.yaml@@ -230,3 +230,27 @@ tools:status is Completed, use the downloading-batch-export-files skill to download each file through the existingREST download endpoint; the generated MCP download operation is intentionally not enabled because it is aredirect to the file body.+ managed-migrations-create:+ operation: managed_migrations_create+ enabled: false+ managed-migrations-destroy:+ operation: managed_migrations_destroy+ enabled: false+ managed-migrations-list:+ operation: managed_migrations_list+ enabled: false+ managed-migrations-partial-update:+ operation: managed_migrations_partial_update+ enabled: false+ managed-migrations-pause-create:+ operation: managed_migrations_pause_create+ enabled: false+ managed-migrations-resume-create:+ operation: managed_migrations_resume_create+ enabled: false+ managed-migrations-retrieve:+ operation: managed_migrations_retrieve+ enabled: false+ managed-migrations-update:+ operation: managed_migrations_update+ enabled: falsediff --git a/products/batch_exports/package.json b/products/batch_exports/package.jsonindex 198c5d424ca9..e001cb294024 100644--- a/products/batch_exports/package.json+++ b/products/batch_exports/package.json@@ -1,6 +1,6 @@{"name": "@posthog/products-batch-exports","scripts": {- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests --ignore=backend/tests/temporal -v --tb=short"+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests backend/api/test --ignore=backend/tests/temporal -v --tb=short"}}diff --git a/products/batch_exports/tsconfig.json b/products/batch_exports/tsconfig.jsonnew file mode 100644index 000000000000..fe425d6fcba8--- /dev/null+++ b/products/batch_exports/tsconfig.json@@ -0,0 +1,6 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "composite": true+ }+}diff --git a/products/cdp/backend/api/hog_function.py b/products/cdp/backend/api/hog_function.pyindex 349965869217..b42320475aec 100644--- a/products/cdp/backend/api/hog_function.py+++ b/products/cdp/backend/api/hog_function.py@@ -743,7 +743,7 @@ class HogFunctionViewSet(@action(detail=True, methods=["POST"])def enable_backfills(self, request: Request, *args, **kwargs):- from posthog.batch_exports.http import BatchExportSerializer+ from products.batch_exports.backend.api.batch_export import BatchExportSerializerhog_function = self.get_object()diff --git a/products/cdp/backend/migrations/0002_alter_hogfunction_batch_export.py b/products/cdp/backend/migrations/0002_alter_hogfunction_batch_export.pynew file mode 100644index 000000000000..b658144398bf--- /dev/null+++ b/products/cdp/backend/migrations/0002_alter_hogfunction_batch_export.py@@ -0,0 +1,27 @@+import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("batch_exports", "0002_batchexport_batchexportbackfill_and_more"),+ ("cdp", "0001_migrate_cdp_models"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AlterField(+ model_name="hogfunction",+ name="batch_export",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to="batch_exports.batchexport",+ ),+ ),+ ],+ database_operations=[],+ ),+ ]diff --git a/products/cdp/backend/migrations/max_migration.txt b/products/cdp/backend/migrations/max_migration.txtindex 43312cdbb304..494f158ad14b 100644--- a/products/cdp/backend/migrations/max_migration.txt+++ b/products/cdp/backend/migrations/max_migration.txt@@ -1 +1 @@-0001_migrate_cdp_models+0002_alter_hogfunction_batch_exportdiff --git a/products/cdp/backend/models/hog_functions/hog_function.py b/products/cdp/backend/models/hog_functions/hog_function.pyindex 78ee85d95cf8..f51e8d614178 100644--- a/products/cdp/backend/models/hog_functions/hog_function.py+++ b/products/cdp/backend/models/hog_functions/hog_function.py@@ -120,7 +120,7 @@ class HogFunction(FileSystemSyncMixin, UUIDTModel):execution_order = models.PositiveSmallIntegerField(null=True, blank=True)batch_export = models.ForeignKey(- "posthog.BatchExport",+ "batch_exports.BatchExport",on_delete=models.SET_NULL,null=True,blank=True,diff --git a/products/dashboards/backend/api/dashboard_ai.py b/products/dashboards/backend/api/dashboard_ai.pyindex 5010e68f7147..2da04e47d99c 100644--- a/products/dashboards/backend/api/dashboard_ai.py+++ b/products/dashboards/backend/api/dashboard_ai.py@@ -5,8 +5,7 @@ import structlogfrom posthog.hogql.ai import hit_openai-from posthog.api.annotation_context import build_annotations_block, resolve_dashboard_date_range-+from products.annotations.backend.api.annotation_context import build_annotations_block, resolve_dashboard_date_rangefrom products.dashboards.backend.models.dashboard import Dashboardlogger = structlog.get_logger(__name__)diff --git a/products/data_warehouse/backend/api/data_warehouse.py b/products/data_warehouse/backend/api/data_warehouse.pyindex 0c577cad9037..405b4cc9ff7e 100644--- a/products/data_warehouse/backend/api/data_warehouse.py+++ b/products/data_warehouse/backend/api/data_warehouse.py@@ -24,7 +24,6 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.api.documentation import _FallbackSerializerfrom posthog.api.property_value_metrics import PROPERTY_VALUES_DURATIONfrom posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.batch_exports.models import BatchExportRunfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.cloud_utils import get_cached_instance_licensefrom posthog.helpers.dashboard_templates import create_data_ops_dashboard@@ -32,6 +31,7 @@ from posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.security.outbound_proxy import internal_requests as _internal_requestsfrom posthog.utils import convert_property_value, flatten+from products.batch_exports.backend.models.batch_export import BatchExportRunfrom products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionState, HogFunctionTypefrom products.data_modeling.backend.models.data_modeling_job import DataModelingJobfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuerydiff --git a/products/exports/__init__.py b/products/exports/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/exports/backend/__init__.py b/products/exports/backend/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/exports/backend/admin/__init__.py b/products/exports/backend/admin/__init__.pynew file mode 100644index 000000000000..18a965d49bb5--- /dev/null+++ b/products/exports/backend/admin/__init__.py@@ -0,0 +1 @@+from . import exported_asset_admin, subscription_admin # noqa: F401diff --git a/posthog/admin/admins/exported_asset_admin.py b/products/exports/backend/admin/exported_asset_admin.pysimilarity index 97%rename from posthog/admin/admins/exported_asset_admin.pyrename to products/exports/backend/admin/exported_asset_admin.pyindex 55cc2829bb1f..adba3f568f48 100644--- a/posthog/admin/admins/exported_asset_admin.py+++ b/products/exports/backend/admin/exported_asset_admin.py@@ -5,7 +5,7 @@ from django.contrib import adminfrom django.urls import reversefrom django.utils.html import format_html-from posthog.models import ExportedAsset+from products.exports.backend.models.exported_asset import ExportedAsset@admin.register(ExportedAsset)diff --git a/posthog/admin/admins/subscription_admin.py b/products/exports/backend/admin/subscription_admin.pysimilarity index 95%rename from posthog/admin/admins/subscription_admin.pyrename to products/exports/backend/admin/subscription_admin.pyindex 917f741ef90b..d075ee3dd811 100644--- a/posthog/admin/admins/subscription_admin.py+++ b/products/exports/backend/admin/subscription_admin.py@@ -3,7 +3,8 @@ from django.urls import reversefrom django.utils.html import format_htmlfrom posthog.admin.paginators.no_count_paginator import NoCountPaginator-from posthog.models import Subscription++from products.exports.backend.models.subscription import Subscription@admin.register(Subscription)diff --git a/products/exports/backend/api/__init__.py b/products/exports/backend/api/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/api/exports.py b/products/exports/backend/api/exports.pysimilarity index 99%rename from posthog/api/exports.pyrename to products/exports/backend/api/exports.pyindex 9b5c6f66dfd8..626aa137f3f0 100644--- a/posthog/api/exports.py+++ b/products/exports/backend/api/exports.py@@ -21,7 +21,6 @@ from posthog.api.utils import actionfrom posthog.event_usage import EventSource, get_event_source, groupsfrom posthog.models import Team, Userfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activity-from posthog.models.exported_asset import ExportedAsset, get_content_responsefrom posthog.models.organization import Organizationfrom posthog.security.url_validation import is_url_allowedfrom posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME@@ -32,6 +31,7 @@ from posthog.temporal.common.search_attributes import POSTHOG_SESSION_RECORDING_from posthog.temporal.exports.workflows import ExportAssetWorkflow, ExportAssetWorkflowInputsfrom posthog.temporal.session_replay.rasterize_recording.types import RasterizeRecordingInputs+from products.exports.backend.models.exported_asset import ExportedAsset, get_content_responsefrom products.product_analytics.backend.models.insight import Insight# Full video exports per team per calendar month, tiered by plan.diff --git a/products/exports/backend/api/test/__init__.py b/products/exports/backend/api/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/api/test/test_exports.py b/products/exports/backend/api/test/test_exports.pysimilarity index 95%rename from posthog/api/test/test_exports.pyrename to products/exports/backend/api/test/test_exports.pyindex 0b3d03b5a30e..1f219579d282 100644--- a/posthog/api/test/test_exports.py+++ b/products/exports/backend/api/test/test_exports.py@@ -20,7 +20,6 @@ from rest_framework import statusfrom posthog.hogql.errors import QueryErrorfrom posthog.errors import CHQueryErrorTooManySimultaneousQueries-from posthog.models.exported_asset import ExportedAssetfrom posthog.models.filters.filter import Filterfrom posthog.models.team import Teamfrom posthog.models.user import User@@ -32,11 +31,12 @@ from posthog.settings import (OBJECT_STORAGE_SECRET_ACCESS_KEY,)from posthog.tasks import exporter-from posthog.tasks.exports.failure_handler import FAILURE_TYPE_SYSTEM, FAILURE_TYPE_USER-from posthog.tasks.exports.image_exporter import export_imagefrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.tasks.failure_handler import FAILURE_TYPE_SYSTEM, FAILURE_TYPE_USER+from products.exports.backend.tasks.image_exporter import export_imagefrom products.product_analytics.backend.api.insight import InsightSerializerfrom products.product_analytics.backend.models.insight import Insight@@ -94,7 +94,7 @@ class TestExports(APIBaseTest):team=cls.team, dashboard_id=cls.dashboard.id, export_format="image/png", created_by=cls.user)- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_can_create_new_valid_export_dashboard(self, mock_exporter_task) -> None:# add filter to dashboardself.dashboard.filters = {"properties": [{"key": "$browser_version", "value": "1.0"}]}@@ -127,7 +127,7 @@ class TestExports(APIBaseTest):mock_exporter_task.assert_called_once()assert mock_exporter_task.call_args[0][0].id == data["id"]- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_can_create_export_with_ttl(self, mock_exporter_task) -> None:one_week_from_now = datetime.now() + timedelta(weeks=1)response = self.client.post(@@ -166,7 +166,7 @@ class TestExports(APIBaseTest):mock_exporter_task.assert_called_once()assert mock_exporter_task.call_args[0][0].id == data["id"]- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_swallow_missing_schema_and_allow_front_end_to_poll(self, mock_exporter_task) -> None:# regression test see https://github.com/PostHog/posthog/issues/11204@@ -188,8 +188,8 @@ class TestExports(APIBaseTest):mock_exporter_task.assert_called_once()assert mock_exporter_task.call_args[0][0].id == data["id"]- @patch("posthog.tasks.exports.image_exporter._export_to_png")- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.tasks.image_exporter._export_to_png")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")@freeze_time("2021-08-25T22:09:14.252Z")def test_can_create_new_valid_export_insight(self, mock_exporter_task, mock_export_to_png) -> None:response = self.client.post(@@ -255,7 +255,7 @@ class TestExports(APIBaseTest):# look at the page the screenshot will be taken ofexported_asset = ExportedAsset.objects.get(pk=data["id"])- with patch("posthog.tasks.exports.image_exporter.calculate_for_query_based_insight") as mock_calculate:+ with patch("products.exports.backend.tasks.image_exporter.calculate_for_query_based_insight") as mock_calculate:# Request does not calculate the result and cache is not warmed upcontext = {"is_shared": True}InsightSerializer(self.insight, many=False, context=context)@@ -294,7 +294,7 @@ class TestExports(APIBaseTest):},)- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_will_error_if_export_unsupported(self, mock_exporter_task) -> None:response = self.client.post(f"/api/projects/{self.team.id}/exports",@@ -393,8 +393,8 @@ class TestExports(APIBaseTest):},)- @patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow")- @patch("posthog.tasks.exports.csv_exporter.requests.request")+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")+ @patch("products.exports.backend.tasks.csv_exporter.requests.request")def test_can_download_a_csv(self, patched_request, _mock_workflow) -> None:with self.settings(SITE_URL="http://testserver", OBJECT_STORAGE_ENABLED=False):_create_event(@@ -929,8 +929,8 @@ class TestExports(APIBaseTest):("application/pdf", timedelta(days=180)),])- @patch("posthog.api.exports.async_to_sync")- @patch("posthog.api.exports.async_connect")+ @patch("products.exports.backend.api.exports.async_to_sync")+ @patch("products.exports.backend.api.exports.async_connect")def test_export_expiry_varies_by_format(self, export_format, expected_delta, mock_async_connect, mock_async_to_sync) -> None:@@ -961,8 +961,8 @@ class TestExports(APIBaseTest):self.assertEqual(data["expires_after"], expected_expiry)- @patch("posthog.api.exports.async_to_sync")- @patch("posthog.api.exports.async_connect")+ @patch("products.exports.backend.api.exports.async_to_sync")+ @patch("products.exports.backend.api.exports.async_connect")def test_video_export_monthly_limit(self, mock_async_connect, mock_async_to_sync) -> None:"""Test that video exports are limited to 10 per calendar month"""# Create 9 video exports this month (we're at the limit - 1)@@ -1002,8 +1002,8 @@ class TestExports(APIBaseTest):self.assertEqual(error_data["attr"], "export_limit_exceeded")self.assertIn("reached the limit of 10 full video exports this month", error_data["detail"])- @patch("posthog.api.exports.async_to_sync")- @patch("posthog.api.exports.async_connect")+ @patch("products.exports.backend.api.exports.async_to_sync")+ @patch("products.exports.backend.api.exports.async_connect")def test_video_export_limit_applies_to_all_video_formats(self, mock_async_connect, mock_async_to_sync) -> None:"""Test that the limit applies to both MP4 and WebM session recording exports"""# Create 5 MP4 and 5 WebM exports this month (at the limit)@@ -1045,8 +1045,8 @@ class TestExports(APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- @patch("posthog.api.exports.async_to_sync")- @patch("posthog.api.exports.async_connect")+ @patch("products.exports.backend.api.exports.async_to_sync")+ @patch("products.exports.backend.api.exports.async_connect")@freeze_time("2024-01-15T12:00:00Z")def test_video_export_limit_resets_monthly(self, mock_async_connect, mock_async_to_sync) -> None:"""Test that the video export limit resets at the beginning of each month"""@@ -1118,8 +1118,8 @@ class TestExports(APIBaseTest):),])- @patch("posthog.api.exports.async_to_sync")- @patch("posthog.api.exports.async_connect")+ @patch("products.exports.backend.api.exports.async_to_sync")+ @patch("products.exports.backend.api.exports.async_connect")def test_video_export_limit_varies_by_plan_tier(self,_name: str,@@ -1179,8 +1179,8 @@ class TestExports(APIBaseTest):("free_override_above_tier_wins", [], 30, 30),])- @patch("posthog.api.exports.async_to_sync")- @patch("posthog.api.exports.async_connect")+ @patch("products.exports.backend.api.exports.async_to_sync")+ @patch("products.exports.backend.api.exports.async_connect")def test_video_export_extra_settings_override_acts_as_floor_above_plan_tier(self,_name: str,@@ -1229,8 +1229,8 @@ class TestExports(APIBaseTest):("user_assets_count", False, False),])- @patch("posthog.api.exports.async_to_sync")- @patch("posthog.api.exports.async_connect")+ @patch("products.exports.backend.api.exports.async_to_sync")+ @patch("products.exports.backend.api.exports.async_connect")def test_video_export_limit_excludes_system_assets(self,_name: str,@@ -1262,7 +1262,7 @@ class TestExports(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(response.json()["attr"], "export_limit_exceeded")- @patch("posthog.tasks.exports.image_exporter.export_image")+ @patch("products.exports.backend.tasks.image_exporter.export_image")def test_export_records_failure_on_query_error(self, mock_export_direct) -> None:"""Test that export_asset records failure info on the asset when a QueryError occurs.@@ -1287,7 +1287,7 @@ class TestExports(APIBaseTest):self.assertEqual(asset.exception_type, "QueryError")self.assertEqual(asset.failure_type, "user")- @patch("posthog.api.exports.async_connect")+ @patch("products.exports.backend.api.exports.async_connect")def test_workflow_failure_returns_201_with_failed_asset(self, mock_async_connect) -> None:mock_client = AsyncMock()mock_client.execute_workflow.side_effect = Exception("workflow failed")@@ -1342,7 +1342,7 @@ class TestExportHeatmapSSRFValidation(APIBaseTest):with (patch("posthog.security.url_validation.resolve_host_ips") as mock_resolve,- patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow"),+ patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow"),):mock_resolve.return_value = {ipaddress.ip_address("93.184.216.34")}response = self.client.post(@@ -1362,8 +1362,8 @@ class TestExportMixin(APIBaseTest):"""with self.settings(SITE_URL="http://testserver", OBJECT_STORAGE_ENABLED=False):with (- patch("posthog.tasks.exports.csv_exporter.requests.request") as patched_request,- patch("posthog.api.exports.ExportedAssetSerializer._start_export_workflow"),+ patch("products.exports.backend.tasks.csv_exporter.requests.request") as patched_request,+ patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow"),):def requests_side_effect(*args, **kwargs):@@ -1433,7 +1433,7 @@ class TestExportAssetCounters(APIBaseTest):exception_context = pytest.raises(type(error)) if expects_exception and error else nullcontext()with (- patch("posthog.tasks.exports.image_exporter.export_image", side_effect=error),+ patch("products.exports.backend.tasks.image_exporter.export_image", side_effect=error),patch.object(exporter, "EXPORT_SUCCEEDED_COUNTER", self.success_counter),patch.object(exporter, "EXPORT_FAILED_COUNTER", self.failed_counter),patch("time.sleep"), # Avoid real tenacity backoff waitsdiff --git a/products/exports/backend/apps.py b/products/exports/backend/apps.pynew file mode 100644index 000000000000..cf9a8e188f02--- /dev/null+++ b/products/exports/backend/apps.py@@ -0,0 +1,8 @@+"""Django app configuration for exports."""++from django.apps import AppConfig+++class ExportsConfig(AppConfig):+ name = "products.exports.backend"+ label = "exports"diff --git a/products/exports/backend/migrations/0001_migrate_exports_models.py b/products/exports/backend/migrations/0001_migrate_exports_models.pynew file mode 100644index 000000000000..033979eb2187--- /dev/null+++ b/products/exports/backend/migrations/0001_migrate_exports_models.py@@ -0,0 +1,321 @@+# Generated by Django 5.2.14 on 2026-05-27 10:06++import django.db.models.deletion+import django.contrib.postgres.fields+from django.conf import settings+from django.db import migrations, models++import posthog.models.utils++import products.exports.backend.models.exported_asset+++class Migration(migrations.Migration):+ initial = True++ dependencies = [+ ("dashboards", "0006_migrate_product_analytics_models"),+ ("posthog", "1185_fix_non_list_test_account_filters"),+ ("product_analytics", "0001_migrate_product_analytics_models"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.CreateModel(+ name="ExportedAsset",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ (+ "export_format",+ models.CharField(+ choices=[+ ("image/png", "image/png"),+ ("application/pdf", "application/pdf"),+ ("text/csv", "text/csv"),+ (+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ ),+ ("video/webm", "video/webm"),+ ("video/mp4", "video/mp4"),+ ("image/gif", "image/gif"),+ ("application/json", "application/json"),+ ],+ max_length=100,+ ),+ ),+ ("content", models.BinaryField(null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("expires_after", models.DateTimeField(blank=True, null=True)),+ ("export_context", models.JSONField(blank=True, null=True)),+ (+ "content_location",+ models.TextField(blank=True, max_length=1000, null=True),+ ),+ ("exception", models.TextField(blank=True, null=True)),+ (+ "exception_type",+ models.CharField(blank=True, max_length=255, null=True),+ ),+ (+ "failure_type",+ models.CharField(blank=True, max_length=255, null=True),+ ),+ ("is_system", models.BooleanField(default=False, null=True)),+ (+ "access_token",+ models.CharField(+ blank=True,+ default=products.exports.backend.models.exported_asset.get_default_access_token,+ max_length=400,+ null=True,+ ),+ ),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "dashboard",+ models.ForeignKey(+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ to="dashboards.dashboard",+ ),+ ),+ (+ "insight",+ models.ForeignKey(+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ to="product_analytics.insight",+ ),+ ),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ ],+ options={+ "db_table": "posthog_exportedasset",+ },+ ),+ migrations.CreateModel(+ name="Subscription",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("title", models.CharField(blank=True, max_length=100, null=True)),+ (+ "target_type",+ models.CharField(+ choices=[+ ("email", "Email"),+ ("slack", "Slack"),+ ("webhook", "Webhook"),+ ],+ max_length=10,+ ),+ ),+ ("target_value", models.TextField()),+ (+ "frequency",+ models.CharField(+ choices=[+ ("daily", "Daily"),+ ("weekly", "Weekly"),+ ("monthly", "Monthly"),+ ("yearly", "Yearly"),+ ],+ max_length=10,+ ),+ ),+ ("interval", models.IntegerField(default=1)),+ ("count", models.IntegerField(null=True)),+ (+ "byweekday",+ django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(+ choices=[+ ("monday", "Monday"),+ ("tuesday", "Tuesday"),+ ("wednesday", "Wednesday"),+ ("thursday", "Thursday"),+ ("friday", "Friday"),+ ("saturday", "Saturday"),+ ("sunday", "Sunday"),+ ],+ max_length=10,+ ),+ blank=True,+ default=None,+ null=True,+ size=None,+ ),+ ),+ ("bysetpos", models.IntegerField(null=True)),+ ("start_date", models.DateTimeField()),+ ("until_date", models.DateTimeField(blank=True, null=True)),+ ("next_delivery_date", models.DateTimeField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("deleted", models.BooleanField(default=False)),+ ("enabled", models.BooleanField(default=True)),+ ("summary_enabled", models.BooleanField(default=False)),+ (+ "summary_prompt_guide",+ models.CharField(blank=True, default="", max_length=500),+ ),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "dashboard",+ models.ForeignKey(+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ to="dashboards.dashboard",+ ),+ ),+ (+ "dashboard_export_insights",+ models.ManyToManyField(+ blank=True,+ related_name="subscriptions_dashboard_export",+ to="product_analytics.insight",+ ),+ ),+ (+ "insight",+ models.ForeignKey(+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ to="product_analytics.insight",+ ),+ ),+ (+ "integration",+ models.ForeignKey(+ blank=True,+ db_index=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to="posthog.integration",+ ),+ ),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ ],+ options={+ "db_table": "posthog_subscription",+ },+ ),+ migrations.CreateModel(+ name="SubscriptionDelivery",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("temporal_workflow_id", models.CharField(max_length=255)),+ ("idempotency_key", models.CharField(max_length=255, unique=True)),+ ("trigger_type", models.CharField(max_length=20)),+ ("scheduled_at", models.DateTimeField(null=True)),+ ("target_type", models.CharField(max_length=10)),+ ("target_value", models.TextField()),+ (+ "exported_asset_ids",+ django.contrib.postgres.fields.ArrayField(+ base_field=models.IntegerField(), default=list, size=None+ ),+ ),+ ("content_snapshot", models.JSONField(default=dict)),+ ("change_summary", models.TextField(blank=True, null=True)),+ ("recipient_results", models.JSONField(default=list)),+ (+ "status",+ models.CharField(+ choices=[+ ("starting", "Starting"),+ ("completed", "Completed"),+ ("failed", "Failed"),+ ("skipped", "Skipped"),+ ],+ default="starting",+ max_length=24,+ ),+ ),+ ("error", models.JSONField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("last_updated_at", models.DateTimeField(auto_now=True)),+ ("finished_at", models.DateTimeField(blank=True, null=True)),+ (+ "subscription",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="deliveries",+ to="exports.subscription",+ ),+ ),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ ],+ options={+ "db_table": "posthog_subscription_delivery",+ "ordering": ["-created_at"],+ },+ ),+ migrations.AddIndex(+ model_name="subscription",+ index=models.Index(fields=["integration"], name="posthog_sub_integration_idx"),+ ),+ migrations.AddIndex(+ model_name="subscriptiondelivery",+ index=models.Index(fields=["subscription", "-created_at"], name="posthog_subdel_sub_crtd"),+ ),+ migrations.AddIndex(+ model_name="subscriptiondelivery",+ index=models.Index(fields=["team", "-created_at"], name="posthog_subdel_team_crtd"),+ ),+ ],+ database_operations=[+ # No database operations - table already exists with this name+ ],+ ),+ ]diff --git a/products/exports/backend/migrations/__init__.py b/products/exports/backend/migrations/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/exports/backend/migrations/max_migration.txt b/products/exports/backend/migrations/max_migration.txtnew file mode 100644index 000000000000..b9a56d7d71bf--- /dev/null+++ b/products/exports/backend/migrations/max_migration.txt@@ -0,0 +1 @@+0001_migrate_exports_modelsdiff --git a/products/exports/backend/models/__init__.py b/products/exports/backend/models/__init__.pynew file mode 100644index 000000000000..d2467a688e0f--- /dev/null+++ b/products/exports/backend/models/__init__.py@@ -0,0 +1,8 @@+from .exported_asset import ExportedAsset+from .subscription import Subscription, SubscriptionDelivery++__all__ = [+ "ExportedAsset",+ "Subscription",+ "SubscriptionDelivery",+]diff --git a/posthog/models/exported_asset.py b/products/exports/backend/models/exported_asset.pysimilarity index 98%rename from posthog/models/exported_asset.pyrename to products/exports/backend/models/exported_asset.pyindex 0faa32dd10f9..2e47f921bff4 100644--- a/posthog/models/exported_asset.py+++ b/products/exports/backend/models/exported_asset.py@@ -68,7 +68,7 @@ class ExportedAsset(models.Model):]# Relations- team = models.ForeignKey("Team", on_delete=models.CASCADE)+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)dashboard = models.ForeignKey("dashboards.Dashboard", on_delete=models.CASCADE, null=True)insight = models.ForeignKey("product_analytics.Insight", on_delete=models.CASCADE, null=True)@@ -81,7 +81,7 @@ class ExportedAsset(models.Model):# the object manager has been altered to exclude these assets# to allow for lazy deletesexpires_after = models.DateTimeField(null=True, blank=True)- 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)# for example holds filters for CSV exportsexport_context = models.JSONField(null=True, blank=True)# path in object storage or some other location identifier for the asset@@ -104,6 +104,9 @@ class ExportedAsset(models.Model):objects = ExportedAssetManager()objects_including_ttl_deleted: models.Manager["ExportedAsset"] = models.Manager()+ class Meta:+ db_table = "posthog_exportedasset"+def save(self, *args, **kwargs):if not self.expires_after:self.expires_after = self.compute_expires_after(self.export_format)diff --git a/posthog/models/subscription.py b/products/exports/backend/models/subscription.pysimilarity index 98%rename from posthog/models/subscription.pyrename to products/exports/backend/models/subscription.pyindex 408203c4ab1d..82c0d8dd544b 100644--- a/posthog/models/subscription.py+++ b/products/exports/backend/models/subscription.py@@ -84,7 +84,7 @@ class Subscription(models.Model):}# Relations - i.e. WHAT are we exporting?- team = models.ForeignKey("Team", on_delete=models.CASCADE)+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)dashboard = models.ForeignKey("dashboards.Dashboard", on_delete=models.CASCADE, null=True)insight = models.ForeignKey("product_analytics.Insight", on_delete=models.CASCADE, null=True)dashboard_export_insights = models.ManyToManyField(@@ -124,7 +124,7 @@ class Subscription(models.Model):# Metacreated_at = models.DateTimeField(auto_now_add=True, blank=True)- 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)deleted = models.BooleanField(default=False)# False when paused or auto-disabled because the delivery prerequisite is@@ -138,6 +138,7 @@ class Subscription(models.Model):indexes = [models.Index(fields=["integration"], name="posthog_sub_integration_idx"),]+ db_table = "posthog_subscription"def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)@@ -325,7 +326,7 @@ class SubscriptionDelivery(UUIDModel):SKIPPED = "skipped"subscription = models.ForeignKey("Subscription", on_delete=models.CASCADE, related_name="deliveries")- team = models.ForeignKey("Team", on_delete=models.CASCADE)+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)# Temporal correlation — workflow_id for debugging, idempotency_key for dedup.# idempotency_key is generated via temporalio.workflow.uuid4() which is deterministicdiff --git a/products/exports/backend/tasks/__init__.py b/products/exports/backend/tasks/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/tasks/exports/csv_exporter.py b/products/exports/backend/tasks/csv_exporter.pysimilarity index 94%rename from posthog/tasks/exports/csv_exporter.pyrename to products/exports/backend/tasks/csv_exporter.pyindex f1b965894a2a..f5a30b0ca6ad 100644--- a/posthog/tasks/exports/csv_exporter.py+++ b/products/exports/backend/tasks/csv_exporter.py@@ -22,25 +22,28 @@ from rest_framework_csv.renderers import CSVRendererfrom posthog.schema import QuerySchemaRoot+from posthog.hogql.constants import CSV_EXPORT_BREAKDOWN_LIMIT_INITIAL, CSV_EXPORT_BREAKDOWN_LIMIT_LOW, CSV_EXPORT_LIMIT+from posthog.hogql.query import LimitContext+from posthog.api.services.query import process_query_dictfrom posthog.event_usage import AnalyticsProps, EventSource+from posthog.exceptions import ClickHouseQuerySizeExceededfrom posthog.exceptions_capture import capture_exception-from posthog.hogql_queries.query_runner import ExecutionMode-from posthog.jwt import PosthogJwtAudience, encode_jwt-from posthog.models.exported_asset import ExportedAsset, save_content_from_file-from posthog.utils import absolute_uri--from ...exceptions import ClickHouseQuerySizeExceeded-from ...hogql.constants import CSV_EXPORT_BREAKDOWN_LIMIT_INITIAL, CSV_EXPORT_BREAKDOWN_LIMIT_LOW, CSV_EXPORT_LIMIT-from ...hogql.query import LimitContext-from ...hogql_queries.insights.utils.breakdowns import (+from posthog.hogql_queries.insights.utils.breakdowns import (BREAKDOWN_NULL_DISPLAY,BREAKDOWN_NULL_STRING_LABEL,BREAKDOWN_OTHER_DISPLAY,BREAKDOWN_OTHER_STRING_LABEL,)-from ..exporter import EXPORT_TIMER-from ..exports.failure_handler import ExcelColumnLimitExceeded+from posthog.hogql_queries.query_runner import ExecutionMode+from posthog.jwt import PosthogJwtAudience, encode_jwt+from posthog.security.spreadsheet_safety import sanitize_formula_injection+from posthog.tasks.exporter import EXPORT_TIMER+from posthog.utils import absolute_uri++from products.exports.backend.models.exported_asset import ExportedAsset, save_content_from_file++from .failure_handler import ExcelColumnLimitExceededlogger = structlog.get_logger(__name__)@@ -48,23 +51,6 @@ RESULT_LIMIT_KEYS = ("distinct_ids",)RESULT_LIMIT_LENGTH = 10QUERY_PAGE_SIZE = 10000-# Characters that can trigger formula execution in spreadsheet applications-_FORMULA_TRIGGER_CHARS = ("=", "+", "-", "@", "\t", "\r")---def _sanitize_formula_injection(value: Any) -> Any:- """Prefix dangerous cell values with a single quote to prevent formula injection.-- Spreadsheet applications like Excel and Google Sheets interpret cells- starting with =, +, -, @, tab, or carriage return as formulas. Prefixing- with a single quote forces them to be treated as plain text.- """- if not isinstance(value, str):- return value- if value and value[0] in _FORMULA_TRIGGER_CHARS:- return f"'{value}"- return value-def sanitize_value_for_excel(value: Any) -> Any:if not isinstance(value, str):@@ -86,11 +72,11 @@ class CsvWriter(TabularWriter):def write_header(self, columns: list[str]) -> None:self._writer = csv.DictWriter(self._tmp, fieldnames=columns, extrasaction="ignore")# Write sanitized header manually — fieldnames must stay raw for dict key lookup- self._writer.writer.writerow([_sanitize_formula_injection(c) for c in columns])+ self._writer.writer.writerow([sanitize_formula_injection(c) for c in columns])def write_row(self, row: dict) -> None:assert self._writer is not None- self._writer.writerow({k: _sanitize_formula_injection(v) for k, v in row.items()})+ self._writer.writerow({k: sanitize_formula_injection(v) for k, v in row.items()})def finish(self) -> str:self._tmp.close()@@ -109,7 +95,7 @@ class ExcelWriter(TabularWriter):def write_header(self, columns: list[str]) -> None:self._columns = columnstry:- self._worksheet.append([_sanitize_formula_injection(c) for c in columns])+ self._worksheet.append([sanitize_formula_injection(c) for c in columns])except ValueError as e:if "Invalid column index" in str(e):raise ExcelColumnLimitExceeded() from e@@ -123,7 +109,7 @@ class ExcelWriter(TabularWriter):value = str(value)# Strip illegal Excel chars first so formula check sees the final stringvalue = sanitize_value_for_excel(value)- value = _sanitize_formula_injection(value)+ value = sanitize_formula_injection(value)values.append(value)try:self._worksheet.append(values)diff --git a/posthog/tasks/exports/exporter_utils.py b/products/exports/backend/tasks/exporter_utils.pysimilarity index 100%rename from posthog/tasks/exports/exporter_utils.pyrename to products/exports/backend/tasks/exporter_utils.pydiff --git a/posthog/tasks/exports/failure_handler.py b/products/exports/backend/tasks/failure_handler.pysimilarity index 100%rename from posthog/tasks/exports/failure_handler.pyrename to products/exports/backend/tasks/failure_handler.pydiff --git a/posthog/tasks/exports/image_exporter.py b/products/exports/backend/tasks/image_exporter.pysimilarity index 99%rename from posthog/tasks/exports/image_exporter.pyrename to products/exports/backend/tasks/image_exporter.pyindex 9d5f34f44936..72ba0fac904b 100644--- a/posthog/tasks/exports/image_exporter.py+++ b/products/exports/backend/tasks/image_exporter.py@@ -33,15 +33,15 @@ from posthog.caching.calculate_results import calculate_for_query_based_insightfrom posthog.event_usage import AnalyticsProps, EventSourcefrom posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.query_runner import ExecutionMode-from posthog.models.exported_asset import ExportedAsset, get_render_access_token, save_contentfrom posthog.schema_migrations.upgrade_manager import upgrade_queryfrom posthog.security.url_validation import is_url_allowedfrom posthog.tasks.exporter import EXPORT_TIMER-from posthog.tasks.exports.exporter_utils import log_error_if_site_url_not_reachable-from posthog.tasks.exports.failure_handler import BrowserlessUnavailable, classify_failure_typefrom posthog.utils import absolute_urifrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.exports.backend.models.exported_asset import ExportedAsset, get_render_access_token, save_content+from products.exports.backend.tasks.exporter_utils import log_error_if_site_url_not_reachable+from products.exports.backend.tasks.failure_handler import BrowserlessUnavailable, classify_failure_typefrom products.product_analytics.backend.api.insight_variable import map_stale_to_latestfrom products.product_analytics.backend.models.insight_variable import InsightVariablediff --git a/posthog/tasks/exports/test/csv_renders/actors.json b/products/exports/backend/tasks/test/csv_renders/actors.jsonsimilarity index 100%rename from posthog/tasks/exports/test/csv_renders/actors.jsonrename to products/exports/backend/tasks/test/csv_renders/actors.jsondiff --git a/posthog/tasks/exports/test/csv_renders/events_query.json b/products/exports/backend/tasks/test/csv_renders/events_query.jsonsimilarity index 100%rename from posthog/tasks/exports/test/csv_renders/events_query.jsonrename to products/exports/backend/tasks/test/csv_renders/events_query.jsondiff --git a/posthog/tasks/exports/test/csv_renders/funnels.json b/products/exports/backend/tasks/test/csv_renders/funnels.jsonsimilarity index 100%rename from posthog/tasks/exports/test/csv_renders/funnels.jsonrename to products/exports/backend/tasks/test/csv_renders/funnels.jsondiff --git a/posthog/tasks/exports/test/csv_renders/funnels_breakdown.json b/products/exports/backend/tasks/test/csv_renders/funnels_breakdown.jsonsimilarity index 100%rename from posthog/tasks/exports/test/csv_renders/funnels_breakdown.jsonrename to products/exports/backend/tasks/test/csv_renders/funnels_breakdown.jsondiff --git a/posthog/tasks/exports/test/csv_renders/funnels_historic_trends.json b/products/exports/backend/tasks/test/csv_renders/funnels_historic_trends.jsonsimilarity index 100%rename from posthog/tasks/exports/test/csv_renders/funnels_historic_trends.jsonrename to products/exports/backend/tasks/test/csv_renders/funnels_historic_trends.jsondiff --git a/posthog/tasks/exports/test/csv_renders/hogql_empty.json b/products/exports/backend/tasks/test/csv_renders/hogql_empty.jsonsimilarity index 100%rename from posthog/tasks/exports/test/csv_renders/hogql_empty.jsonrename to products/exports/backend/tasks/test/csv_renders/hogql_empty.jsondiff --git a/posthog/tasks/exports/test/csv_renders/hogql_no_result.json b/products/exports/backend/tasks/test/csv_renders/hogql_no_result.jsonsimilarity index 100%rename from posthog/tasks/exports/test/csv_renders/hogql_no_result.jsonrename to products/exports/backend/tasks/test/csv_renders/hogql_no_result.jsondiff --git a/posthog/tasks/exports/test/csv_renders/people.json b/products/exports/backend/tasks/test/csv_renders/people.jsonsimilarity index 100%rename from posthog/tasks/exports/test/csv_renders/people.jsonrename to products/exports/backend/tasks/test/csv_renders/people.jsondiff --git a/posthog/tasks/exports/test/csv_renders/persons_modal.json b/products/exports/backend/tasks/test/csv_renders/persons_modal.jsonsimilarity index 100%rename from posthog/tasks/exports/test/csv_renders/persons_modal.jsonrename to products/exports/backend/tasks/test/csv_renders/persons_modal.jsondiff --git a/posthog/tasks/exports/test/csv_renders/persons_modal_retention.json b/products/exports/backend/tasks/test/csv_renders/persons_modal_retention.jsonsimilarity index 100%rename from posthog/tasks/exports/test/csv_renders/persons_modal_retention.jsonrename to products/exports/backend/tasks/test/csv_renders/persons_modal_retention.jsondiff --git a/posthog/tasks/exports/test/csv_renders/retention.json b/products/exports/backend/tasks/test/csv_renders/retention.jsonsimilarity index 100%rename from posthog/tasks/exports/test/csv_renders/retention.jsonrename to products/exports/backend/tasks/test/csv_renders/retention.jsondiff --git a/posthog/tasks/exports/test/csv_renders/trends.json b/products/exports/backend/tasks/test/csv_renders/trends.jsonsimilarity index 100%rename from posthog/tasks/exports/test/csv_renders/trends.jsonrename to products/exports/backend/tasks/test/csv_renders/trends.jsondiff --git a/posthog/tasks/exports/test/csv_renders/trends_formula.json b/products/exports/backend/tasks/test/csv_renders/trends_formula.jsonsimilarity index 100%rename from posthog/tasks/exports/test/csv_renders/trends_formula.jsonrename to products/exports/backend/tasks/test/csv_renders/trends_formula.jsondiff --git a/posthog/tasks/exports/test/test_csv_exporter.py b/products/exports/backend/tasks/test/test_csv_exporter.pysimilarity index 93%rename from posthog/tasks/exports/test/test_csv_exporter.pyrename to products/exports/backend/tasks/test/test_csv_exporter.pyindex 08de7a0dea63..89558ee3b704 100644--- a/posthog/tasks/exports/test/test_csv_exporter.py+++ b/products/exports/backend/tasks/test/test_csv_exporter.py@@ -21,8 +21,8 @@ from requests.exceptions import HTTPErrorfrom posthog.hogql.constants import CSV_EXPORT_BREAKDOWN_LIMIT_INITIAL-from posthog.models import ExportedAssetfrom posthog.models.utils import UUIDT+from posthog.security.spreadsheet_safety import sanitize_formula_injectionfrom posthog.settings import (OBJECT_STORAGE_ACCESS_KEY_ID,OBJECT_STORAGE_BUCKET,@@ -31,22 +31,22 @@ from posthog.settings import ()from posthog.storage import object_storagefrom posthog.storage.object_storage import ObjectStorageError-from posthog.tasks.exports import csv_exporter-from posthog.tasks.exports.csv_exporter import (+from posthog.test.test_journeys import journeys_for+from posthog.utils import absolute_uri++from products.actions.backend.models.action import Action+from products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.tasks import csv_exporter+from products.exports.backend.tasks.csv_exporter import (CsvWriter,ExcelWriter,UnexpectedEmptyJsonResponse,_convert_response_to_csv_data,_format_breakdown_value,- _sanitize_formula_injection,add_query_params,sanitize_value_for_excel,)-from posthog.tasks.exports.failure_handler import ExcelColumnLimitExceeded-from posthog.test.test_journeys import journeys_for-from posthog.utils import absolute_uri--from products.actions.backend.models.action import Action+from products.exports.backend.tasks.failure_handler import ExcelColumnLimitExceededTEST_PREFIX = "Test-Exports"@@ -58,7 +58,7 @@ regression_11204 = "api/projects/6642/insights/trend/?events=%5B%7B%22id%22%3A%2class TestCSVExporter(APIBaseTest):@pytest.fixture(autouse=True)def patched_request(self) -> Generator[Any, None, None]:- with patch("posthog.tasks.exports.csv_exporter.requests.request") as patched_request:+ with patch("products.exports.backend.tasks.csv_exporter.requests.request") as patched_request:mock_response = Mock()mock_response.status_code = 200# API responses copied from https://github.com/PostHog/posthog/runs/7221634689?check_suite_focus=true@@ -152,7 +152,7 @@ class TestCSVExporter(APIBaseTest):)assert exported_asset.content_location is None- @patch("posthog.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.UUIDT")def test_csv_exporter_writes_to_object_storage_when_object_storage_is_enabled(self, mocked_uuidt: Any) -> None:exported_asset = self._create_asset()mocked_uuidt.return_value = "a-guid"@@ -174,8 +174,8 @@ class TestCSVExporter(APIBaseTest):assert exported_asset.content is None- @patch("posthog.models.exported_asset.UUIDT")- @patch("posthog.models.exported_asset.object_storage.write_from_file")+ @patch("products.exports.backend.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.object_storage.write_from_file")def test_csv_exporter_writes_to_asset_when_object_storage_write_fails(self, mocked_object_storage_write_from_file: Any, mocked_uuidt: Any) -> None:@@ -193,8 +193,8 @@ class TestCSVExporter(APIBaseTest):== b"id,distinct_id,properties.$browser,event,timestamp,person,elements_chain\r\ne9ca132e-400f-4854-a83c-16c151b2f145,2,Safari,event_name,2022-07-06T19:37:43.095295+00:00,,\r\n1624228e-a4f1-48cd-aabc-6baa3ddb22e4,2,Safari,event_name,2022-07-06T19:37:43.095279+00:00,,\r\n66d45914-bdf5-4980-a54a-7dc699bdcce9,2,Safari,event_name,2022-07-06T19:37:43.095262+00:00,,\r\n")- @patch("posthog.models.exported_asset.UUIDT")- @patch("posthog.models.exported_asset.object_storage.write_from_file")+ @patch("products.exports.backend.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.object_storage.write_from_file")def test_csv_exporter_does_not_filter_columns_on_empty_param(self, mocked_object_storage_write_from_file: Any, mocked_uuidt: Any) -> None:@@ -212,8 +212,8 @@ class TestCSVExporter(APIBaseTest):== b"id,distinct_id,properties.$browser,event,timestamp,person,elements_chain\r\ne9ca132e-400f-4854-a83c-16c151b2f145,2,Safari,event_name,2022-07-06T19:37:43.095295+00:00,,\r\n1624228e-a4f1-48cd-aabc-6baa3ddb22e4,2,Safari,event_name,2022-07-06T19:37:43.095279+00:00,,\r\n66d45914-bdf5-4980-a54a-7dc699bdcce9,2,Safari,event_name,2022-07-06T19:37:43.095262+00:00,,\r\n")- @patch("posthog.models.exported_asset.UUIDT")- @patch("posthog.models.exported_asset.object_storage.write_from_file")+ @patch("products.exports.backend.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.object_storage.write_from_file")def test_csv_exporter_does_filter_columns(self, mocked_object_storage_write_from_file: Any, mocked_uuidt: Any) -> None:@@ -232,8 +232,8 @@ class TestCSVExporter(APIBaseTest):== b"distinct_id,properties.$browser,event\r\n2,Safari,event_name\r\n2,Safari,event_name\r\n2,Safari,event_name\r\n")- @patch("posthog.models.exported_asset.UUIDT")- @patch("posthog.models.exported_asset.object_storage.write_from_file")+ @patch("products.exports.backend.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.object_storage.write_from_file")def test_csv_exporter_includes_whole_dict(self, mocked_object_storage_write_from_file: Any, mocked_uuidt: Any) -> None:@@ -248,8 +248,8 @@ class TestCSVExporter(APIBaseTest):assert exported_asset.content == b"distinct_id,properties.$browser\r\n2,Safari\r\n2,Safari\r\n2,Safari\r\n"- @patch("posthog.models.exported_asset.UUIDT")- @patch("posthog.models.exported_asset.object_storage.write_from_file")+ @patch("products.exports.backend.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.object_storage.write_from_file")def test_csv_exporter_includes_whole_dict_alternative_order(self, mocked_object_storage_write_from_file: Any, mocked_uuidt: Any) -> None:@@ -264,8 +264,8 @@ class TestCSVExporter(APIBaseTest):assert exported_asset.content == b"properties.$browser,distinct_id\r\nSafari,2\r\nSafari,2\r\nSafari,2\r\n"- @patch("posthog.models.exported_asset.UUIDT")- @patch("posthog.models.exported_asset.object_storage.write_from_file")+ @patch("products.exports.backend.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.object_storage.write_from_file")def test_csv_exporter_does_filter_columns_and_can_handle_unexpected_columns(self, mocked_object_storage_write_from_file: Any, mocked_uuidt: Any) -> None:@@ -284,8 +284,8 @@ class TestCSVExporter(APIBaseTest):== b"distinct_id,properties.$browser,event,tomato\r\n2,Safari,event_name,\r\n2,Safari,event_name,\r\n2,Safari,event_name,\r\n")- @patch("posthog.models.exported_asset.UUIDT")- @patch("posthog.models.exported_asset.object_storage.write_from_file")+ @patch("products.exports.backend.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.object_storage.write_from_file")def test_csv_exporter_excel(self, mocked_object_storage_write_from_file: Any, mocked_uuidt: Any) -> None:exported_asset = self._create_asset({"columns": ["distinct_id", "properties.$browser", "event", "tomato"]})exported_asset.export_format = ExportedAsset.ExportFormat.XLSX@@ -310,9 +310,9 @@ class TestCSVExporter(APIBaseTest):("2", "Safari", "event_name", None),]- @patch("posthog.models.exported_asset.UUIDT")- @patch("posthog.models.exported_asset.object_storage.write")- @patch("posthog.tasks.exports.csv_exporter.requests.request")+ @patch("products.exports.backend.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.object_storage.write")+ @patch("products.exports.backend.tasks.csv_exporter.requests.request")def test_csv_exporter_limits_breakdown_insights_correctly(self, mocked_request: Any, mocked_object_storage_write: Any, mocked_uuidt: Any) -> None:@@ -333,9 +333,9 @@ class TestCSVExporter(APIBaseTest):headers=ANY,)- @patch("posthog.tasks.exports.csv_exporter.logger")+ @patch("products.exports.backend.tasks.csv_exporter.logger")def test_failing_export_api_is_reported(self, _mock_logger: MagicMock) -> None:- with patch("posthog.tasks.exports.csv_exporter.requests.request") as patched_request:+ with patch("products.exports.backend.tasks.csv_exporter.requests.request") as patched_request:exported_asset = self._create_asset()mock_response = MagicMock()mock_response.status_code = 403@@ -346,9 +346,9 @@ class TestCSVExporter(APIBaseTest):with pytest.raises(Exception, match="HTTP 403 Forbidden"):csv_exporter.export_tabular(exported_asset)- @patch("posthog.tasks.exports.csv_exporter.logger")+ @patch("products.exports.backend.tasks.csv_exporter.logger")def test_failing_export_api_is_reported_query_size_exceeded(self, _mock_logger: MagicMock) -> None:- with patch("posthog.tasks.exports.csv_exporter.make_api_call") as patched_make_api_call:+ with patch("products.exports.backend.tasks.csv_exporter.make_api_call") as patched_make_api_call:exported_asset = self._create_asset()mock_error = HTTPError("Query size exceeded") # type: ignore[call-arg]mock_error.response = Mock()@@ -381,7 +381,7 @@ class TestCSVExporter(APIBaseTest):}assert expected_bits == actual_bits- @patch("posthog.tasks.exports.csv_exporter.make_api_call")+ @patch("products.exports.backend.tasks.csv_exporter.make_api_call")def test_raises_expected_error_when_json_is_none(self, patched_api_call: Any) -> None:mock_response = Mock()mock_response.json.return_value = None@@ -394,7 +394,7 @@ class TestCSVExporter(APIBaseTest):@patch("posthog.hogql.constants.CSV_EXPORT_LIMIT", 10)@patch("posthog.hogql.constants.DEFAULT_RETURNED_ROWS", 5)- @patch("posthog.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.UUIDT")def test_csv_exporter_hogql_query(self, mocked_uuidt: Any, DEFAULT_RETURNED_ROWS: int = 5, CSV_EXPORT_LIMIT: int = 10) -> None:@@ -440,7 +440,7 @@ class TestCSVExporter(APIBaseTest):assert exported_asset.content is None@patch("posthog.hogql.constants.CSV_EXPORT_LIMIT", 10)- @patch("posthog.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.UUIDT")def test_csv_exporter_events_query(self, mocked_uuidt: Any, CSV_EXPORT_LIMIT: int = 10) -> None:random_uuid = f"RANDOM_TEST_ID::{UUIDT()}"for i in range(15):@@ -484,7 +484,7 @@ class TestCSVExporter(APIBaseTest):self.assertEqual(first_row[5], str(self.team.pk))@patch("posthog.hogql.constants.CSV_EXPORT_LIMIT", 10)- @patch("posthog.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.UUIDT")def test_csv_exporter_events_query_with_columns(self, mocked_uuidt: Any, CSV_EXPORT_LIMIT: int = 10) -> None:random_uuid = f"RANDOM_TEST_ID::{UUIDT()}"for i in range(15):@@ -528,7 +528,7 @@ class TestCSVExporter(APIBaseTest):self.assertEqual(first_row[4], str(self.team.pk))@patch("posthog.hogql.constants.MAX_SELECT_RETURNED_ROWS", 10)- @patch("posthog.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.UUIDT")def test_csv_exporter_funnels_query(self, mocked_uuidt: Any, MAX_SELECT_RETURNED_ROWS: int = 10) -> None:_create_person(distinct_ids=[f"user_1"],@@ -586,9 +586,9 @@ class TestCSVExporter(APIBaseTest):],)- @patch("posthog.models.exported_asset.object_storage.write_from_file")- @patch("posthog.tasks.exports.csv_exporter.process_query_dict")- @patch("posthog.tasks.exports.csv_exporter._query_supports_limit")+ @patch("products.exports.backend.models.exported_asset.object_storage.write_from_file")+ @patch("products.exports.backend.tasks.csv_exporter.process_query_dict")+ @patch("products.exports.backend.tasks.csv_exporter._query_supports_limit")def test_skips_limit_when_query_does_not_support_it(self, mock_supports_limit: MagicMock, mock_process_query: MagicMock, mock_write: MagicMock) -> None:@@ -621,14 +621,14 @@ class TestCSVExporter(APIBaseTest):lines = (bytes(content) if content else b"").decode("utf-8").strip().split("\r\n")self.assertEqual(lines, ["col", "value1", "value2"])- @patch("posthog.models.exported_asset.object_storage.write_from_file")- @patch("posthog.tasks.exports.csv_exporter.process_query_dict")- @patch("posthog.tasks.exports.csv_exporter._query_supports_limit")+ @patch("products.exports.backend.models.exported_asset.object_storage.write_from_file")+ @patch("products.exports.backend.tasks.csv_exporter.process_query_dict")+ @patch("products.exports.backend.tasks.csv_exporter._query_supports_limit")def test_adds_limit_when_query_supports_it(self, mock_supports_limit: MagicMock, mock_process_query: MagicMock, mock_write: MagicMock) -> None:"""Verify that when schema validation shows limit is supported, we add it."""- from posthog.tasks.exports.csv_exporter import QUERY_PAGE_SIZE+ from products.exports.backend.tasks.csv_exporter import QUERY_PAGE_SIZEmock_supports_limit.return_value = Truemock_process_query.return_value = {@@ -694,7 +694,7 @@ class TestCSVExporter(APIBaseTest):assert bin[0] == csv["bin"]assert bin[1] == csv["value"]- @patch("posthog.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.UUIDT")def test_csv_exporter_empty_result(self, mocked_uuidt: Any) -> None:exported_asset = ExportedAsset(team=self.team,@@ -716,7 +716,7 @@ class TestCSVExporter(APIBaseTest):exported_asset.save()mocked_uuidt.return_value = "a-guid"- with patch("posthog.tasks.exports.csv_exporter.get_from_query") as mocked_get_from_query:+ with patch("products.exports.backend.tasks.csv_exporter.get_from_query") as mocked_get_from_query:mocked_get_from_query.return_value = iter([])with self.settings(OBJECT_STORAGE_ENABLED=True, OBJECT_STORAGE_EXPORTS_FOLDER="Test-Exports"):@@ -728,7 +728,7 @@ class TestCSVExporter(APIBaseTest):self.assertEqual(lines[1], "No data available or unable to format for export.")@patch("posthog.hogql.constants.MAX_SELECT_RETURNED_ROWS", 10)- @patch("posthog.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.UUIDT")def test_csv_exporter_trends_query_with_none_action(self, mocked_uuidt: Any, MAX_SELECT_RETURNED_ROWS: int = 10) -> None:@@ -914,7 +914,7 @@ class TestCSVExporter(APIBaseTest):self,) -> None:with freeze_time("2022-06-01T12:00:00.000Z"):- _create_person(distinct_ids=[f"user_1"], team=self.team, uuid="4beb316f-23aa-2584-66d3-4a1b8ab458f2")+ _create_person(distinct_ids=[f"user_1"], team=self.team, uuid="725f10a7-26dd-fa38-f973-757866a10ad4")events_by_person = {"user_1": [@@ -973,12 +973,12 @@ class TestCSVExporter(APIBaseTest):lines,["actor.id,actor.is_identified,actor.created_at,actor.last_seen_at,actor.distinct_ids.0,actor.is_unresolved,event_count,event_distinct_ids.0",- "4beb316f-23aa-2584-66d3-4a1b8ab458f2,False,2022-06-01 12:00:00+00:00,,user_1,,2,user_1",+ "725f10a7-26dd-fa38-f973-757866a10ad4,False,2022-06-01 12:00:00+00:00,,user_1,,2,user_1","d0780d6b-ccd0-44fa-a227-47efe4f3f30d,,,,user_2,True,1,user_2",],)- @patch("posthog.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.UUIDT")def test_csv_exporter_trends_query_with_formula(self, mocked_uuidt: Any, MAX_SELECT_RETURNED_ROWS: int = 10) -> None:@@ -1035,7 +1035,7 @@ class TestCSVExporter(APIBaseTest):],)- @patch("posthog.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.UUIDT")def test_csv_exporter_trends_query_with_formula_and_single_breakdown(self, mocked_uuidt: Any, MAX_SELECT_RETURNED_ROWS: int = 10) -> None:@@ -1113,7 +1113,7 @@ class TestCSVExporter(APIBaseTest):],)- @patch("posthog.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.UUIDT")def test_csv_exporter_trends_query_with_formula_and_multiple_breakdowns(self, mocked_uuidt: Any, MAX_SELECT_RETURNED_ROWS: int = 10) -> None:@@ -1206,7 +1206,7 @@ class TestCSVExporter(APIBaseTest):],)- @patch("posthog.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.UUIDT")def test_csv_exporter_trends_with_breakdown(self, mocked_uuidt: Any) -> None:with freeze_time("2025-05-22T12:00:00.000Z"):_create_person(distinct_ids=["user_1"], team=self.team)@@ -1276,7 +1276,7 @@ class TestCSVExporter(APIBaseTest):],)- @patch("posthog.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.UUIDT")def test_csv_exporter_trends_with_breakdown_and_action(self, mocked_uuidt: Any) -> None:with freeze_time("2025-05-22T12:00:00.000Z"):_create_person(distinct_ids=["user_1"], team=self.team)@@ -1353,7 +1353,7 @@ class TestCSVExporter(APIBaseTest):)@patch("posthog.hogql.constants.CSV_EXPORT_LIMIT", 10)- @patch("posthog.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.UUIDT")def test_excel_streaming_saves_to_object_storage(self, mocked_uuidt: Any) -> None:"""Test that Excel streaming export saves to object storage and handles complex types."""random_uuid = f"RANDOM_TEST_ID::{UUIDT()}"@@ -1404,7 +1404,7 @@ class TestCSVExporter(APIBaseTest):assert all(row[2] is not None and "tag1" in str(row[2]) for row in rows[1:])@patch("posthog.hogql.constants.CSV_EXPORT_LIMIT", 10)- @patch("posthog.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.UUIDT")def test_csv_streaming_saves_to_object_storage(self, mocked_uuidt: Any, csv_export_limit: int = 10) -> None:"""Test that CSV streaming export saves to object storage and handles complex types."""random_uuid = f"RANDOM_TEST_ID::{UUIDT()}"@@ -1479,7 +1479,7 @@ class TestCSVExporter(APIBaseTest):)exported_asset.save()- with patch("posthog.tasks.exports.csv_exporter.tempfile.NamedTemporaryFile", tracking_temp_file):+ with patch("products.exports.backend.tasks.csv_exporter.tempfile.NamedTemporaryFile", tracking_temp_file):csv_exporter.export_tabular(exported_asset)# Two temp files: jsonl (phase 1) + csv (phase 2)@@ -1523,7 +1523,7 @@ class TestCSVExporter(APIBaseTest):)exported_asset.save()- with patch("posthog.tasks.exports.csv_exporter.tempfile.NamedTemporaryFile", tracking_temp_file):+ with patch("products.exports.backend.tasks.csv_exporter.tempfile.NamedTemporaryFile", tracking_temp_file):csv_exporter.export_tabular(exported_asset)# Two temp files: jsonl (phase 1) + xlsx (phase 2)@@ -1552,13 +1552,13 @@ class TestCSVExporter(APIBaseTest):for input_value, expected in test_cases:assert sanitize_value_for_excel(input_value) == expected, f"Failed for input: {repr(input_value)}"- @patch("posthog.models.exported_asset.UUIDT")- @patch("posthog.models.exported_asset.object_storage.write_from_file")+ @patch("products.exports.backend.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.object_storage.write_from_file")def test_excel_export_with_illegal_characters(self, mocked_object_storage_write_from_file: Any, mocked_uuidt: Any) -> None:"""Test that Excel export handles data with illegal XML characters without crashing."""- with patch("posthog.tasks.exports.csv_exporter.requests.request") as patched_request:+ with patch("products.exports.backend.tasks.csv_exporter.requests.request") as patched_request:mock_response = Mock()mock_response.status_code = 200# Data containing control characters that would normally crash openpyxl@@ -1646,9 +1646,9 @@ class TestNestedColumnExport(APIBaseTest):Test CSV export handles mixed null/nested data correctly."""- @patch("posthog.models.exported_asset.UUIDT")- @patch("posthog.models.exported_asset.object_storage.write_from_file")- @patch("posthog.tasks.exports.csv_exporter.get_from_query")+ @patch("products.exports.backend.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.object_storage.write_from_file")+ @patch("products.exports.backend.tasks.csv_exporter.get_from_query")def test_nested_columns_included_when_some_rows_are_null(self,mocked_get_from_query: Any,@@ -1693,9 +1693,9 @@ class TestNestedColumnExport(APIBaseTest):assert b"Hello world" in exported_asset.content, f"Nested input content missing"assert b"Hi there!" in exported_asset.content, f"Nested output content missing"- @patch("posthog.models.exported_asset.UUIDT")- @patch("posthog.models.exported_asset.object_storage.write_from_file")- @patch("posthog.tasks.exports.csv_exporter.get_from_query")+ @patch("products.exports.backend.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.object_storage.write_from_file")+ @patch("products.exports.backend.tasks.csv_exporter.get_from_query")def test_null_rows_first_still_includes_nested_columns(self,mocked_get_from_query: Any,@@ -1731,9 +1731,9 @@ class TestNestedColumnExport(APIBaseTest):assert exported_asset.content is not Noneassert b"Test message" in exported_asset.content, f"Nested content missing when null row came first"- @patch("posthog.models.exported_asset.UUIDT")- @patch("posthog.models.exported_asset.object_storage.write_from_file")- @patch("posthog.tasks.exports.csv_exporter.get_from_query")+ @patch("products.exports.backend.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.object_storage.write_from_file")+ @patch("products.exports.backend.tasks.csv_exporter.get_from_query")def test_all_null_rows_still_includes_requested_column(self,mocked_get_from_query: Any,@@ -1770,9 +1770,9 @@ class TestNestedColumnExport(APIBaseTest):assert b"trace-1" in exported_asset.contentassert b"trace-2" in exported_asset.content- @patch("posthog.models.exported_asset.UUIDT")- @patch("posthog.models.exported_asset.object_storage.write_from_file")- @patch("posthog.tasks.exports.csv_exporter.get_from_query")+ @patch("products.exports.backend.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.object_storage.write_from_file")+ @patch("products.exports.backend.tasks.csv_exporter.get_from_query")def test_deeply_nested_objects_are_flattened(self,mocked_get_from_query: Any,@@ -1833,7 +1833,7 @@ class TestSanitizeFormulaInjection:],)def test_prefixes_dangerous_strings(self, input_value: str, expected: str) -> None:- assert _sanitize_formula_injection(input_value) == expected+ assert sanitize_formula_injection(input_value) == expected@pytest.mark.parametrize("input_value",@@ -1852,7 +1852,7 @@ class TestSanitizeFormulaInjection:],)def test_passes_through_safe_values(self, input_value: Any) -> None:- assert _sanitize_formula_injection(input_value) == input_value+ assert sanitize_formula_injection(input_value) == input_valuedef test_csv_writer_sanitizes_values(self) -> None:writer = CsvWriter()diff --git a/posthog/tasks/exports/test/test_csv_exporter_renders.py b/products/exports/backend/tasks/test/test_csv_exporter_renders.pysimilarity index 88%rename from posthog/tasks/exports/test/test_csv_exporter_renders.pyrename to products/exports/backend/tasks/test/test_csv_exporter_renders.pyindex 7233d5d6374e..618e2bea5f32 100644--- a/posthog/tasks/exports/test/test_csv_exporter_renders.py+++ b/products/exports/backend/tasks/test/test_csv_exporter_renders.py@@ -5,10 +5,11 @@ from typing import Any, castimport pytestfrom unittest.mock import Mock, patch-from posthog.models import ExportedAssetfrom posthog.models.organization import Organizationfrom posthog.models.team.team import Team-from posthog.tasks.exports import csv_exporter++from products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.tasks import csv_exporterTEST_BUCKET = "Test-Exports"@@ -24,9 +25,9 @@ for file in os.listdir(directory):@pytest.mark.parametrize("filename", fixtures)@pytest.mark.parametrize("mode", ("legacy", "hogql"))@pytest.mark.django_db-@patch("posthog.tasks.exports.csv_exporter.requests.request")-@patch("posthog.tasks.exports.csv_exporter.process_query_dict")-@patch("posthog.models.exported_asset.settings")+@patch("products.exports.backend.tasks.csv_exporter.requests.request")+@patch("products.exports.backend.tasks.csv_exporter.process_query_dict")+@patch("products.exports.backend.models.exported_asset.settings")def test_csv_rendering(mock_settings: Any, mock_process_query_dict: Any, mock_request: Any, filename: str, mode: str) -> None:diff --git a/posthog/tasks/exports/test/test_csv_exporter_url_sanitising.py b/products/exports/backend/tasks/test/test_csv_exporter_url_sanitising.pysimilarity index 100%rename from posthog/tasks/exports/test/test_csv_exporter_url_sanitising.pyrename to products/exports/backend/tasks/test/test_csv_exporter_url_sanitising.pydiff --git a/posthog/tasks/exports/test/test_export_utils.py b/products/exports/backend/tasks/test/test_export_utils.pysimilarity index 82%rename from posthog/tasks/exports/test/test_export_utils.pyrename to products/exports/backend/tasks/test/test_export_utils.pyindex d40b0eee9aa8..b4573b82a28f 100644--- a/posthog/tasks/exports/test/test_export_utils.py+++ b/products/exports/backend/tasks/test/test_export_utils.py@@ -6,13 +6,13 @@ from unittest.mock import patchfrom requests import RequestException-from posthog.tasks.exports import exporter_utils+from products.exports.backend.tasks import exporter_utilsTEST_PREFIX = "Test-Exports"class TestSiteURLReachability(APIBaseTest):- @patch("posthog.tasks.exports.exporter_utils.logger")+ @patch("products.exports.backend.tasks.exporter_utils.logger")def test_url_not_reachable_exception(self, logger_mock: Any) -> None:test_url = "http://some-bad-url.test"with self.settings(SITE_URL=test_url):@@ -26,11 +26,11 @@ class TestSiteURLReachability(APIBaseTest):assert logger_mock.error.call_args[1]["site_url"] == test_urlassert isinstance(logger_mock.error.call_args[1]["exception"], RequestException)- @patch("posthog.tasks.exports.exporter_utils.logger")+ @patch("products.exports.backend.tasks.exporter_utils.logger")def test_url_not_reachable_error_status(self, logger_mock: Any) -> None:test_url = "http://some-status-bad-url.test"with self.settings(SITE_URL=test_url):- with patch("posthog.tasks.exports.exporter_utils.requests.get") as mock_request:+ with patch("products.exports.backend.tasks.exporter_utils.requests.get") as mock_request:mock_request.return_value.status_code = 500try:exporter_utils.log_error_if_site_url_not_reachable()@@ -42,11 +42,11 @@ class TestSiteURLReachability(APIBaseTest):assert logger_mock.error.call_args[1]["site_url"] == test_urlassert str(logger_mock.error.call_args[1]["exception"]) == "HTTP status code: 500"- @patch("posthog.tasks.exports.exporter_utils.logger")+ @patch("products.exports.backend.tasks.exporter_utils.logger")def test_url_reachable_success(self, logger_mock: Any) -> None:test_url = "http://some-good-url.test"with self.settings(SITE_URL=test_url):- with patch("posthog.tasks.exports.exporter_utils.requests.get") as mock_request:+ with patch("products.exports.backend.tasks.exporter_utils.requests.get") as mock_request:mock_request.return_value.status_code = 200try:exporter_utils.log_error_if_site_url_not_reachable()diff --git a/posthog/tasks/exports/test/test_failure_handler.py b/products/exports/backend/tasks/test/test_failure_handler.pysimilarity index 98%rename from posthog/tasks/exports/test/test_failure_handler.pyrename to products/exports/backend/tasks/test/test_failure_handler.pyindex bb70a145e8ae..0753bc03745b 100644--- a/posthog/tasks/exports/test/test_failure_handler.py+++ b/products/exports/backend/tasks/test/test_failure_handler.py@@ -2,7 +2,7 @@ from unittest import TestCasefrom parameterized import parameterized-from posthog.tasks.exports.failure_handler import (+from products.exports.backend.tasks.failure_handler import (FAILURE_TYPE_SYSTEM,FAILURE_TYPE_TIMEOUT_GENERATION,FAILURE_TYPE_UNKNOWN,diff --git a/posthog/tasks/exports/test/test_image_exporter.py b/products/exports/backend/tasks/test/test_image_exporter.pysimilarity index 91%rename from posthog/tasks/exports/test/test_image_exporter.pyrename to products/exports/backend/tasks/test/test_image_exporter.pyindex 3284ca5d047c..51e514b7a79b 100644--- a/posthog/tasks/exports/test/test_image_exporter.py+++ b/products/exports/backend/tasks/test/test_image_exporter.py@@ -23,7 +23,6 @@ from posthog.hogql.errors import QueryErrorfrom posthog.caching.fetch_from_cache import InsightResultfrom posthog.hogql_queries.query_runner import ExecutionMode-from posthog.models import ExportedAssetfrom posthog.settings import (OBJECT_STORAGE_ACCESS_KEY_ID,OBJECT_STORAGE_BUCKET,@@ -32,11 +31,12 @@ from posthog.settings import ()from posthog.storage import object_storagefrom posthog.storage.object_storage import ObjectStorageError-from posthog.tasks.exports import image_exporter-from posthog.tasks.exports.failure_handler import BrowserlessUnavailablefrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.tasks import image_exporter+from products.exports.backend.tasks.failure_handler import BrowserlessUnavailablefrom products.product_analytics.backend.api.insight_variable import map_stale_to_latestfrom products.product_analytics.backend.models.insight import Insightfrom products.product_analytics.backend.models.insight_variable import InsightVariable@@ -56,9 +56,9 @@ def make_insight_result(cache_key: str) -> InsightResult:TEST_PREFIX = "Test-Exports"-@patch("posthog.tasks.exports.image_exporter._screenshot_asset")+@patch("products.exports.backend.tasks.image_exporter._screenshot_asset")@patch(- "posthog.tasks.exports.image_exporter.open",+ "products.exports.backend.tasks.image_exporter.open",new_callable=mock_open,read_data=b"image_data",)@@ -100,7 +100,7 @@ class TestImageExporter(APIBaseTest):assert self.exported_asset.content == b"image_data"assert self.exported_asset.content_location is None- @patch("posthog.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.UUIDT")def test_image_exporter_writes_to_object_storage_when_object_storage_is_enabled(self, mocked_uuidt: Any, *args: Any) -> None:@@ -118,8 +118,8 @@ class TestImageExporter(APIBaseTest):assert self.exported_asset.content is None- @patch("posthog.models.exported_asset.UUIDT")- @patch("posthog.models.exported_asset.object_storage.write")+ @patch("products.exports.backend.models.exported_asset.UUIDT")+ @patch("products.exports.backend.models.exported_asset.object_storage.write")def test_image_exporter_writes_to_object_storage_when_object_storage_write_fails(self, mocked_object_storage_write: Any, mocked_uuidt: Any, *args: Any) -> None:@@ -133,7 +133,7 @@ class TestImageExporter(APIBaseTest):assert self.exported_asset.content == b"image_data"- @patch("posthog.tasks.exports.image_exporter.calculate_for_query_based_insight")+ @patch("products.exports.backend.tasks.image_exporter.calculate_for_query_based_insight")def test_dashboard_export_calculates_all_insights(self, mock_calculate: Any, *args: Any) -> None:mock_calculate.return_value = make_insight_result("test_cache_key")@@ -182,7 +182,7 @@ class TestImageExporter(APIBaseTest):f"Call {i + 1} has unexpected insight {called_insight.id}")- @patch("posthog.tasks.exports.image_exporter.calculate_for_query_based_insight")+ @patch("products.exports.backend.tasks.image_exporter.calculate_for_query_based_insight")def test_export_captures_cache_keys_and_passes_to_url(self,mock_calculate: Any,@@ -215,7 +215,7 @@ class TestImageExporter(APIBaseTest):assert "cache_keys=" in url_to_render, f"URL should contain cache_keys parameter: {url_to_render}"assert "test_cache_key_123" in url_to_render, f"URL should contain the cache key: {url_to_render}"- @patch("posthog.tasks.exports.image_exporter.calculate_for_query_based_insight")+ @patch("products.exports.backend.tasks.image_exporter.calculate_for_query_based_insight")def test_dashboard_export_captures_all_cache_keys(self,mock_calculate: Any,@@ -260,8 +260,8 @@ class TestImageExporter(APIBaseTest):f"URL should contain cache key for insight {insight.id}")- @patch("posthog.tasks.exports.image_exporter._screenshot_asset")- @patch("posthog.tasks.exports.image_exporter.open", new_callable=mock_open, read_data=b"image_data")+ @patch("products.exports.backend.tasks.image_exporter._screenshot_asset")+ @patch("products.exports.backend.tasks.image_exporter.open", new_callable=mock_open, read_data=b"image_data")@patch("os.remove")def test_export_includes_dashboard_variables(self, *args: Any) -> None:dashboard = Dashboard.objects.create(@@ -286,7 +286,7 @@ class TestImageExporter(APIBaseTest):insight=insight,)- with patch("posthog.tasks.exports.image_exporter.calculate_for_query_based_insight") as mock_calculate:+ with patch("products.exports.backend.tasks.image_exporter.calculate_for_query_based_insight") as mock_calculate:mock_calculate.return_value = make_insight_result("test_key")with self.settings(OBJECT_STORAGE_ENABLED=False):@@ -306,8 +306,8 @@ class TestImageExporter(APIBaseTest):"variables_override should match the transformed dashboard variables")- @patch("posthog.tasks.exports.image_exporter._screenshot_asset")- @patch("posthog.tasks.exports.image_exporter.open", new_callable=mock_open, read_data=b"image_data")+ @patch("products.exports.backend.tasks.image_exporter._screenshot_asset")+ @patch("products.exports.backend.tasks.image_exporter.open", new_callable=mock_open, read_data=b"image_data")@patch("os.remove")def test_export_includes_tile_filter_overrides(self, *args: Any) -> None:dashboard = Dashboard.objects.create(team=self.team, name="Dashboard with Tile Filters")@@ -326,7 +326,7 @@ class TestImageExporter(APIBaseTest):insight=insight,)- with patch("posthog.tasks.exports.image_exporter.calculate_for_query_based_insight") as mock_calculate:+ with patch("products.exports.backend.tasks.image_exporter.calculate_for_query_based_insight") as mock_calculate:mock_calculate.return_value = make_insight_result("test_key")with self.settings(OBJECT_STORAGE_ENABLED=False):@@ -378,7 +378,7 @@ class TestImageExporter(APIBaseTest):),])- @patch("posthog.tasks.exports.image_exporter.calculate_for_query_based_insight")+ @patch("products.exports.backend.tasks.image_exporter.calculate_for_query_based_insight")def test_insight_export_query_override_routing(self,_name: str,@@ -460,7 +460,7 @@ class TestImageExporter(APIBaseTest):),])- @patch("posthog.tasks.exports.image_exporter.calculate_for_query_based_insight")+ @patch("products.exports.backend.tasks.image_exporter.calculate_for_query_based_insight")def test_dashboard_export_variables_routing(self,_name: str,@@ -509,8 +509,8 @@ class TestImageExporter(APIBaseTest):}-@patch("posthog.tasks.exports.image_exporter._screenshot_asset")-@patch("posthog.tasks.exports.image_exporter.open", new_callable=mock_open, read_data=b"image_data")+@patch("products.exports.backend.tasks.image_exporter._screenshot_asset")+@patch("products.exports.backend.tasks.image_exporter.open", new_callable=mock_open, read_data=b"image_data")@patch("os.remove")class TestHeatmapExportURLEncoding(APIBaseTest):def test_heatmap_urls_with_query_params_are_encoded_in_exporter_url(@@ -566,8 +566,8 @@ class TestHeatmapExportURLEncoding(APIBaseTest):assert params["dataURL"] != [data_url]-@patch("posthog.tasks.exports.image_exporter._screenshot_asset")-@patch("posthog.tasks.exports.image_exporter.open", new_callable=mock_open, read_data=b"image_data")+@patch("products.exports.backend.tasks.image_exporter._screenshot_asset")+@patch("products.exports.backend.tasks.image_exporter.open", new_callable=mock_open, read_data=b"image_data")@patch("os.remove")class TestImageExporterQueryOverrideE2E(ClickhouseTestMixin, APIBaseTest):def test_query_override_produces_different_results_than_saved_query(@@ -699,7 +699,7 @@ class TestShouldUseBrowserless(SimpleTestCase):def test_returns_false_when_cdp_url_empty(self) -> None:asset = self._make_asset(created_by=SimpleNamespace(distinct_id="user-1"))with patch.object(settings, "BROWSERLESS_CDP_URL", ""):- with patch("posthog.tasks.exports.image_exporter.posthoganalytics.feature_enabled") as mock_flag:+ with patch("products.exports.backend.tasks.image_exporter.posthoganalytics.feature_enabled") as mock_flag:assert image_exporter._should_use_browserless(asset) is Falsemock_flag.assert_not_called()@@ -711,7 +711,7 @@ class TestShouldUseBrowserless(SimpleTestCase):with (patch.object(settings, "BROWSERLESS_CDP_URL", "wss://chrome.browserless.io"),patch(- "posthog.tasks.exports.image_exporter.posthoganalytics.feature_enabled",+ "products.exports.backend.tasks.image_exporter.posthoganalytics.feature_enabled",return_value=flag_value,) as mock_flag,):@@ -730,7 +730,7 @@ class TestShouldUseBrowserless(SimpleTestCase):with (patch.object(settings, "BROWSERLESS_CDP_URL", "wss://chrome.browserless.io"),patch(- "posthog.tasks.exports.image_exporter.posthoganalytics.feature_enabled",+ "products.exports.backend.tasks.image_exporter.posthoganalytics.feature_enabled",return_value=True,) as mock_flag,):@@ -741,16 +741,16 @@ class TestShouldUseBrowserless(SimpleTestCase):class TestScreenshotAssetDispatcher(SimpleTestCase):- @patch("posthog.tasks.exports.image_exporter._screenshot_asset_browserless")- @patch("posthog.tasks.exports.image_exporter._screenshot_asset_selenium")+ @patch("products.exports.backend.tasks.image_exporter._screenshot_asset_browserless")+ @patch("products.exports.backend.tasks.image_exporter._screenshot_asset_selenium")def test_routes_to_browserless_when_flag_on(self, mock_selenium: Any, mock_browserless: Any) -> None:image_exporter._screenshot_asset("p", "u", 800, ".ExportedInsight", use_browserless=True)mock_browserless.assert_called_once()mock_selenium.assert_not_called()- @patch("posthog.tasks.exports.image_exporter._screenshot_asset_browserless")- @patch("posthog.tasks.exports.image_exporter._screenshot_asset_selenium")+ @patch("products.exports.backend.tasks.image_exporter._screenshot_asset_browserless")+ @patch("products.exports.backend.tasks.image_exporter._screenshot_asset_selenium")def test_routes_to_selenium_by_default(self, mock_selenium: Any, mock_browserless: Any) -> None:image_exporter._screenshot_asset("p", "u", 800, ".ExportedInsight", use_browserless=False)@@ -769,7 +769,7 @@ class TestScreenshotAssetBrowserless(SimpleTestCase):sync_playwright_cm.__enter__.return_value = playwright_objwith patch(- "posthog.tasks.exports.image_exporter.sync_playwright",+ "products.exports.backend.tasks.image_exporter.sync_playwright",return_value=sync_playwright_cm,):with patch.object(settings, "BROWSERLESS_CDP_URL", "wss://chrome.browserless.io"):@@ -787,7 +787,7 @@ class TestScreenshotAssetBrowserless(SimpleTestCase):sync_playwright_cm.__enter__.return_value = playwright_objwith (- patch("posthog.tasks.exports.image_exporter.sync_playwright", return_value=sync_playwright_cm),+ patch("products.exports.backend.tasks.image_exporter.sync_playwright", return_value=sync_playwright_cm),patch.object(settings, "BROWSERLESS_CDP_URL", "wss://chrome.browserless.io"),patch.object(settings, "BROWSERLESS_TOKEN", token),):@@ -816,11 +816,11 @@ class TestScreenshotAssetBrowserless(SimpleTestCase):with (patch(- "posthog.tasks.exports.image_exporter.sync_playwright",+ "products.exports.backend.tasks.image_exporter.sync_playwright",return_value=sync_playwright_cm,),patch.object(settings, "BROWSERLESS_CDP_URL", "wss://chrome.browserless.io"),- patch("posthog.tasks.exports.image_exporter.capture_exception") as mock_capture,+ patch("products.exports.backend.tasks.image_exporter.capture_exception") as mock_capture,):with self.assertRaises(PlaywrightTimeoutError) as ctx:image_exporter._screenshot_asset_browserless("p", "u", 800, ".ExportedInsight")@@ -915,9 +915,9 @@ class TestImageExportRenderMetrics(APIBaseTest):# REGISTRY is global; treat a not-yet-emitted series (None) as 0 so assertions are deltas.return REGISTRY.get_sample_value(name, labels) or 0.0- @patch("posthog.tasks.exports.image_exporter.open", new_callable=mock_open, read_data=b"image_data")+ @patch("products.exports.backend.tasks.image_exporter.open", new_callable=mock_open, read_data=b"image_data")@patch("os.remove")- @patch("posthog.tasks.exports.image_exporter._screenshot_asset")+ @patch("products.exports.backend.tasks.image_exporter._screenshot_asset")def test_render_duration_success_counter_increments_for_selenium(self, mock_screenshot_asset: Any, *args: Any) -> None:@@ -932,9 +932,9 @@ class TestImageExportRenderMetrics(APIBaseTest):assert after - before == 1assert mock_screenshot_asset.called- @patch("posthog.tasks.exports.image_exporter.open", new_callable=mock_open, read_data=b"image_data")+ @patch("products.exports.backend.tasks.image_exporter.open", new_callable=mock_open, read_data=b"image_data")@patch("os.remove")- @patch("posthog.tasks.exports.image_exporter._screenshot_asset")+ @patch("products.exports.backend.tasks.image_exporter._screenshot_asset")def test_render_failure_counters_increment_for_selenium(self, mock_screenshot_asset: Any, *args: Any) -> None:# QueryError classifies as "user" via classify_failure_type.mock_screenshot_asset.side_effect = QueryError("bad query")diff --git a/products/exports/backend/temporal/__init__.py b/products/exports/backend/temporal/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/temporal/subscriptions/__init__.py b/products/exports/backend/temporal/subscriptions/__init__.pysimilarity index 73%rename from posthog/temporal/subscriptions/__init__.pyrename to products/exports/backend/temporal/subscriptions/__init__.pyindex 4e6fa30bc1ec..39643ec1cf1d 100644--- a/posthog/temporal/subscriptions/__init__.py+++ b/products/exports/backend/temporal/subscriptions/__init__.py@@ -1,4 +1,4 @@-from posthog.temporal.subscriptions.activities import (+from products.exports.backend.temporal.subscriptions.activities import (advance_next_delivery_date,create_delivery_record,create_export_assets,@@ -7,8 +7,8 @@ from posthog.temporal.subscriptions.activities import (update_delivery_record,validate_subscription_for_delivery,)-from posthog.temporal.subscriptions.snapshot_activities import snapshot_subscription_insights-from posthog.temporal.subscriptions.workflows import (+from products.exports.backend.temporal.subscriptions.snapshot_activities import snapshot_subscription_insights+from products.exports.backend.temporal.subscriptions.workflows import (HandleSubscriptionValueChangeWorkflow,ProcessSubscriptionWorkflow,ScheduleAllSubscriptionsWorkflow,diff --git a/posthog/temporal/subscriptions/activities.py b/products/exports/backend/temporal/subscriptions/activities.pysimilarity index 98%rename from posthog/temporal/subscriptions/activities.pyrename to products/exports/backend/temporal/subscriptions/activities.pyindex a87b0db43e16..d1cda9a87ea9 100644--- a/posthog/temporal/subscriptions/activities.py+++ b/products/exports/backend/temporal/subscriptions/activities.py@@ -12,14 +12,16 @@ from structlog import get_loggerfrom temporalio.exceptions import ApplicationErrorfrom posthog.exceptions_capture import capture_exception-from posthog.models.exported_asset import ExportedAsset-from posthog.models.subscription import Subscription, SubscriptionDeliveryfrom posthog.sync import database_sync_to_async-from posthog.temporal.subscriptions.insight_snapshot import (++from products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.models.subscription import Subscription, SubscriptionDelivery+from products.exports.backend.temporal.subscriptions.insight_snapshot import (build_initial_content_snapshot,build_insight_delivery_snapshot,)-from posthog.temporal.subscriptions.types import (+from products.exports.backend.temporal.subscriptions.types import (CreateDeliveryRecordInputs,CreateExportAssetsInputs,CreateExportAssetsResult,@@ -31,8 +33,6 @@ from posthog.temporal.subscriptions.types import (SubscriptionInfo,UpdateDeliveryRecordInputs,)--from products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.product_analytics.backend.models.insight import Insightfrom ee.tasks.subscriptions import SLACK_USER_CONFIG_ERRORS, _capture_delivery_failed_eventdiff --git a/posthog/temporal/subscriptions/insight_snapshot.py b/products/exports/backend/temporal/subscriptions/insight_snapshot.pysimilarity index 99%rename from posthog/temporal/subscriptions/insight_snapshot.pyrename to products/exports/backend/temporal/subscriptions/insight_snapshot.pyindex f7079a8d6ded..7d5c2d35f615 100644--- a/posthog/temporal/subscriptions/insight_snapshot.py+++ b/products/exports/backend/temporal/subscriptions/insight_snapshot.py@@ -24,10 +24,10 @@ from posthog.api.services.query import ExecutionModefrom posthog.caching.calculate_results import calculate_cache_key, calculate_for_query_based_insightfrom posthog.caching.fetch_from_cache import InsightResult, NothingInCacheResultfrom posthog.models import Team, User-from posthog.models.subscription import Subscriptionfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.exports.backend.models.subscription import Subscriptionfrom products.product_analytics.backend.models.insight import Insightlogger = structlog.get_logger(__name__)diff --git a/posthog/temporal/subscriptions/llm_change_summary.py b/products/exports/backend/temporal/subscriptions/llm_change_summary.pysimilarity index 99%rename from posthog/temporal/subscriptions/llm_change_summary.pyrename to products/exports/backend/temporal/subscriptions/llm_change_summary.pyindex e364f3a914b2..49ad467d2f7e 100644--- a/posthog/temporal/subscriptions/llm_change_summary.py+++ b/products/exports/backend/temporal/subscriptions/llm_change_summary.py@@ -18,15 +18,15 @@ if TYPE_CHECKING:from posthog.exceptions_capture import capture_exceptionfrom posthog.models.llm_prompt import normalize_prompt_to_string-from posthog.temporal.subscriptions.prompt_sanitization import (+from posthog.utils import get_instance_region++from products.exports.backend.temporal.subscriptions.prompt_sanitization import (INSIGHT_DESCRIPTION_MAX_LEN,INSIGHT_NAME_MAX_LEN,SUBSCRIPTION_TITLE_MAX_LEN,sanitize_core_memory_text,sanitize_user_text,)-from posthog.utils import get_instance_region-from products.product_analytics.backend.api.insight_suggestions import get_query_specific_instructionslogger = structlog.get_logger(__name__)diff --git a/posthog/temporal/subscriptions/prompt_sanitization.py b/products/exports/backend/temporal/subscriptions/prompt_sanitization.pysimilarity index 100%rename from posthog/temporal/subscriptions/prompt_sanitization.pyrename to products/exports/backend/temporal/subscriptions/prompt_sanitization.pydiff --git a/posthog/temporal/subscriptions/results_summarizer.py b/products/exports/backend/temporal/subscriptions/results_summarizer.pysimilarity index 99%rename from posthog/temporal/subscriptions/results_summarizer.pyrename to products/exports/backend/temporal/subscriptions/results_summarizer.pyindex 11d0dd7e5345..ec74ab2604ee 100644--- a/posthog/temporal/subscriptions/results_summarizer.py+++ b/products/exports/backend/temporal/subscriptions/results_summarizer.py@@ -3,7 +3,7 @@ from typing import Anyfrom structlog import get_logger-from posthog.temporal.subscriptions.prompt_sanitization import (+from products.exports.backend.temporal.subscriptions.prompt_sanitization import (GENERIC_VALUE_MAX_LEN,SERIES_LABEL_MAX_LEN,sanitize_user_text,diff --git a/posthog/temporal/subscriptions/snapshot_activities.py b/products/exports/backend/temporal/subscriptions/snapshot_activities.pysimilarity index 97%rename from posthog/temporal/subscriptions/snapshot_activities.pyrename to products/exports/backend/temporal/subscriptions/snapshot_activities.pyindex 4c0af596db4b..600a04e3dc77 100644--- a/posthog/temporal/subscriptions/snapshot_activities.py+++ b/products/exports/backend/temporal/subscriptions/snapshot_activities.py@@ -7,18 +7,18 @@ from asgiref.sync import sync_to_asyncfrom prometheus_client import Counterfrom structlog import get_logger-from posthog.api.annotation_context import build_annotations_block, resolve_snapshot_date_rangefrom posthog.constants import SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE_FEATURE_FLAG_KEY-from posthog.models.exported_asset import ExportedAsset-from posthog.models.subscription import Subscription, SubscriptionDeliveryfrom posthog.ph_client import ph_scoped_capturefrom posthog.storage import object_storagefrom posthog.sync import database_sync_to_async-from posthog.temporal.subscriptions.llm_change_summary import generate_change_summary-from posthog.temporal.subscriptions.prompt_sanitization import PROMPT_GUIDE_MAX_LEN, sanitize_user_text-from posthog.temporal.subscriptions.results_summarizer import build_results_summary-from posthog.temporal.subscriptions.types import SnapshotInsightsInputs, SnapshotInsightsResult+from products.annotations.backend.api.annotation_context import build_annotations_block, resolve_snapshot_date_range+from products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.models.subscription import Subscription, SubscriptionDelivery+from products.exports.backend.temporal.subscriptions.llm_change_summary import generate_change_summary+from products.exports.backend.temporal.subscriptions.prompt_sanitization import PROMPT_GUIDE_MAX_LEN, sanitize_user_text+from products.exports.backend.temporal.subscriptions.results_summarizer import build_results_summary+from products.exports.backend.temporal.subscriptions.types import SnapshotInsightsInputs, SnapshotInsightsResultfrom products.product_analytics.backend.models.insight import Insightfrom ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limiteddiff --git a/posthog/temporal/subscriptions/test_delivery_summary.py b/products/exports/backend/temporal/subscriptions/test_delivery_summary.pysimilarity index 100%rename from posthog/temporal/subscriptions/test_delivery_summary.pyrename to products/exports/backend/temporal/subscriptions/test_delivery_summary.pydiff --git a/posthog/temporal/subscriptions/test_insight_snapshot.py b/products/exports/backend/temporal/subscriptions/test_insight_snapshot.pysimilarity index 95%rename from posthog/temporal/subscriptions/test_insight_snapshot.pyrename to products/exports/backend/temporal/subscriptions/test_insight_snapshot.pyindex cf9b71909773..cdeb1e0a8de2 100644--- a/posthog/temporal/subscriptions/test_insight_snapshot.py+++ b/products/exports/backend/temporal/subscriptions/test_insight_snapshot.py@@ -5,7 +5,11 @@ from decimal import Decimalimport pytestfrom posthog.caching.fetch_from_cache import InsightResult-from posthog.temporal.subscriptions.insight_snapshot import _has_comparison_enabled, _serialize_insight_result++from products.exports.backend.temporal.subscriptions.insight_snapshot import (+ _has_comparison_enabled,+ _serialize_insight_result,+)def _build_insight_result(**overrides) -> InsightResult:diff --git a/posthog/temporal/subscriptions/test_llm_change_summary.py b/products/exports/backend/temporal/subscriptions/test_llm_change_summary.pysimilarity index 95%rename from posthog/temporal/subscriptions/test_llm_change_summary.pyrename to products/exports/backend/temporal/subscriptions/test_llm_change_summary.pyindex da203f6e0778..37421ab88c81 100644--- a/posthog/temporal/subscriptions/test_llm_change_summary.py+++ b/products/exports/backend/temporal/subscriptions/test_llm_change_summary.py@@ -3,7 +3,7 @@ from types import SimpleNamespaceimport pytestfrom unittest.mock import MagicMock, patch-from posthog.temporal.subscriptions.llm_change_summary import (+from products.exports.backend.temporal.subscriptions.llm_change_summary import (_attach_images_to_user_message,build_initial_prompt_messages,build_prompt_messages,@@ -456,7 +456,7 @@ def _mock_openai_response(content: str = "", prompt_tokens: int = 0, completion_class TestGenerateChangeSummary:- @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")+ @patch("products.exports.backend.temporal.subscriptions.llm_change_summary._get_openai_client")def test_returns_content_with_correct_params(self, mock_get_client):mock_client = mock_get_client.return_valuemock_client.chat.completions.create.return_value = _mock_openai_response(@@ -474,7 +474,7 @@ class TestGenerateChangeSummary:assert call_kwargs.kwargs["temperature"] == 0.3assert call_kwargs.kwargs["max_tokens"] == 500- @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")+ @patch("products.exports.backend.temporal.subscriptions.llm_change_summary._get_openai_client")def test_uses_initial_prompt_when_no_previous_states(self, mock_get_client):mock_client = mock_get_client.return_valuemock_client.chat.completions.create.return_value = _mock_openai_response(@@ -491,7 +491,7 @@ class TestGenerateChangeSummary:system_content = messages[0]["content"]assert "current state" in system_content- @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")+ @patch("products.exports.backend.temporal.subscriptions.llm_change_summary._get_openai_client")def test_handles_empty_content(self, mock_get_client):mock_client = mock_get_client.return_valuemock_client.chat.completions.create.return_value = _mock_openai_response("", 0, 0)@@ -503,7 +503,7 @@ class TestGenerateChangeSummary:assert result == ""- @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")+ @patch("products.exports.backend.temporal.subscriptions.llm_change_summary._get_openai_client")def test_attaches_insight_images_as_multimodal_parts(self, mock_get_client):mock_client = mock_get_client.return_valuemock_client.chat.completions.create.return_value = _mock_openai_response("- Data shown")@@ -525,7 +525,7 @@ class TestGenerateChangeSummary:assert image_parts[0]["image_url"]["url"].startswith("data:image/png;base64,")assert image_parts[0]["image_url"]["detail"] == "auto"- @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")+ @patch("products.exports.backend.temporal.subscriptions.llm_change_summary._get_openai_client")def test_prepends_label_text_part_before_each_image(self, mock_get_client):mock_client = mock_get_client.return_valuemock_client.chat.completions.create.return_value = _mock_openai_response("- ok")@@ -544,7 +544,7 @@ class TestGenerateChangeSummary:assert "Chart for: Pageviews" in label_textsassert "Chart for: Signups" in label_texts- @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")+ @patch("products.exports.backend.temporal.subscriptions.llm_change_summary._get_openai_client")def test_preserves_state_order_when_attaching_images(self, mock_get_client):import base64@@ -566,7 +566,7 @@ class TestGenerateChangeSummary:expected_first = f"data:image/png;base64,{base64.b64encode(b'su').decode()}"assert image_parts[0]["image_url"]["url"] == expected_first- @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")+ @patch("products.exports.backend.temporal.subscriptions.llm_change_summary._get_openai_client")def test_leaves_user_message_as_string_when_no_images(self, mock_get_client):mock_client = mock_get_client.return_valuemock_client.chat.completions.create.return_value = _mock_openai_response("- ok")@@ -578,7 +578,7 @@ class TestGenerateChangeSummary:messages = mock_client.chat.completions.create.call_args.kwargs["messages"]assert isinstance(messages[-1]["content"], str)- @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")+ @patch("products.exports.backend.temporal.subscriptions.llm_change_summary._get_openai_client")def test_skips_images_for_insights_not_in_current_states(self, mock_get_client):mock_client = mock_get_client.return_valuemock_client.chat.completions.create.return_value = _mock_openai_response("- ok")@@ -592,7 +592,7 @@ class TestGenerateChangeSummary:image_parts = [p for p in messages[-1]["content"] if p.get("type") == "image_url"]assert len(image_parts) == 1- @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")+ @patch("products.exports.backend.temporal.subscriptions.llm_change_summary._get_openai_client")def test_passes_core_memory_into_user_message(self, mock_get_client):mock_client = mock_get_client.return_valuemock_client.chat.completions.create.return_value = _mock_openai_response("- ok")@@ -611,7 +611,7 @@ class TestGenerateChangeSummary:assert "<core_memory>" in user_contentassert "Company is PostHog." in user_content- @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")+ @patch("products.exports.backend.temporal.subscriptions.llm_change_summary._get_openai_client")def test_user_tag_includes_delivery_id_when_provided(self, mock_get_client):mock_client = mock_get_client.return_valuemock_client.chat.completions.create.return_value = _mock_openai_response("- ok")@@ -623,7 +623,7 @@ class TestGenerateChangeSummary:user_tag = mock_client.chat.completions.create.call_args.kwargs["user"]assert user_tag.endswith("-delivery-abc-123")- @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")+ @patch("products.exports.backend.temporal.subscriptions.llm_change_summary._get_openai_client")def test_marks_generation_billable_to_team_when_team_provided(self, mock_get_client):mock_client = mock_get_client.return_valuemock_client.chat.completions.create.return_value = _mock_openai_response("- ok")@@ -641,7 +641,7 @@ class TestGenerateChangeSummary:assert call_kwargs["posthog_groups"] == {"project": "42"}assert call_kwargs["posthog_distinct_id"] == call_kwargs["user"]- @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")+ @patch("products.exports.backend.temporal.subscriptions.llm_change_summary._get_openai_client")def test_does_not_mark_billable_when_team_missing(self, mock_get_client):mock_client = mock_get_client.return_valuemock_client.chat.completions.create.return_value = _mock_openai_response("- ok")@@ -656,7 +656,7 @@ class TestGenerateChangeSummary:assert "posthog_groups" not in call_kwargsdef test_get_openai_client_raises_when_api_key_missing(self, monkeypatch):- from posthog.temporal.subscriptions.llm_change_summary import _get_openai_client+ from products.exports.backend.temporal.subscriptions.llm_change_summary import _get_openai_clientmonkeypatch.delenv("OPENAI_API_KEY", raising=False)with pytest.raises(ValueError, match="OPENAI_API_KEY"):diff --git a/posthog/temporal/subscriptions/test_prompt_sanitization.py b/products/exports/backend/temporal/subscriptions/test_prompt_sanitization.pysimilarity index 97%rename from posthog/temporal/subscriptions/test_prompt_sanitization.pyrename to products/exports/backend/temporal/subscriptions/test_prompt_sanitization.pyindex 16e9fd8e64ea..e8949b69db9c 100644--- a/posthog/temporal/subscriptions/test_prompt_sanitization.py+++ b/products/exports/backend/temporal/subscriptions/test_prompt_sanitization.py@@ -1,6 +1,9 @@import pytest-from posthog.temporal.subscriptions.prompt_sanitization import sanitize_core_memory_text, sanitize_user_text+from products.exports.backend.temporal.subscriptions.prompt_sanitization import (+ sanitize_core_memory_text,+ sanitize_user_text,+)class TestSanitizeUserText:diff --git a/posthog/temporal/subscriptions/test_results_summarizer.py b/products/exports/backend/temporal/subscriptions/test_results_summarizer.pysimilarity index 98%rename from posthog/temporal/subscriptions/test_results_summarizer.pyrename to products/exports/backend/temporal/subscriptions/test_results_summarizer.pyindex 0564ab2049f2..79e542e22152 100644--- a/posthog/temporal/subscriptions/test_results_summarizer.py+++ b/products/exports/backend/temporal/subscriptions/test_results_summarizer.py@@ -3,7 +3,7 @@ import pytestimport structlogfrom parameterized import parameterized_class-from posthog.temporal.subscriptions.results_summarizer import MAX_SUMMARY_LENGTH, build_results_summary+from products.exports.backend.temporal.subscriptions.results_summarizer import MAX_SUMMARY_LENGTH, build_results_summaryclass TestBuildResultsSummaryEmpty:diff --git a/posthog/temporal/subscriptions/test_snapshot_ai_consent.py b/products/exports/backend/temporal/subscriptions/test_snapshot_ai_consent.pysimilarity index 92%rename from posthog/temporal/subscriptions/test_snapshot_ai_consent.pyrename to products/exports/backend/temporal/subscriptions/test_snapshot_ai_consent.pyindex 5d8bd5b21a2f..deaab86eec38 100644--- a/posthog/temporal/subscriptions/test_snapshot_ai_consent.py+++ b/products/exports/backend/temporal/subscriptions/test_snapshot_ai_consent.py@@ -8,10 +8,9 @@ import structlogfrom asgiref.sync import sync_to_asyncfrom temporalio.testing import ActivityEnvironment-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.exports.backend.models.subscription import Subscription, SubscriptionDelivery+from products.exports.backend.temporal.subscriptions.snapshot_activities import snapshot_subscription_insights+from products.exports.backend.temporal.subscriptions.types import SnapshotInsightsInputsfrom products.product_analytics.backend.models.insight import Insightfrom ee.models import CoreMemory@@ -125,7 +124,7 @@ async def test_runs_summary_when_org_has_approved_ai(team, user, monkeypatch):return "- Pageviews is trending up"monkeypatch.setattr(- "posthog.temporal.subscriptions.snapshot_activities.generate_change_summary",+ "products.exports.backend.temporal.subscriptions.snapshot_activities.generate_change_summary",fake_generate,)@@ -184,11 +183,11 @@ async def test_summary_generation_respects_ai_credit_budget(return summary_textmonkeypatch.setattr(- "posthog.temporal.subscriptions.snapshot_activities.is_team_limited",+ "products.exports.backend.temporal.subscriptions.snapshot_activities.is_team_limited",is_team_limited_impl,)monkeypatch.setattr(- "posthog.temporal.subscriptions.snapshot_activities.generate_change_summary",+ "products.exports.backend.temporal.subscriptions.snapshot_activities.generate_change_summary",fake_generate,)@@ -255,11 +254,11 @@ async def test_stored_prompt_guide_is_ignored_when_prompt_guide_flag_is_off(teamreturn "- Pageviews is trending up"monkeypatch.setattr(- "posthog.temporal.subscriptions.snapshot_activities.generate_change_summary",+ "products.exports.backend.temporal.subscriptions.snapshot_activities.generate_change_summary",fake_generate,)monkeypatch.setattr(- "posthog.temporal.subscriptions.snapshot_activities.posthoganalytics.feature_enabled",+ "products.exports.backend.temporal.subscriptions.snapshot_activities.posthoganalytics.feature_enabled",lambda *a, **kw: False,)@@ -298,11 +297,11 @@ async def test_stored_prompt_guide_flows_when_prompt_guide_flag_is_on(team, userreturn "- Pageviews is trending up"monkeypatch.setattr(- "posthog.temporal.subscriptions.snapshot_activities.generate_change_summary",+ "products.exports.backend.temporal.subscriptions.snapshot_activities.generate_change_summary",fake_generate,)monkeypatch.setattr(- "posthog.temporal.subscriptions.snapshot_activities.posthoganalytics.feature_enabled",+ "products.exports.backend.temporal.subscriptions.snapshot_activities.posthoganalytics.feature_enabled",lambda *a, **kw: True,)@@ -334,7 +333,7 @@ async def test_captures_analytics_event_when_summary_is_generated(team, user, mo)monkeypatch.setattr(- "posthog.temporal.subscriptions.snapshot_activities.generate_change_summary",+ "products.exports.backend.temporal.subscriptions.snapshot_activities.generate_change_summary",lambda *a, **kw: "- Pageviews is trending up",)@@ -399,7 +398,7 @@ async def test_does_not_capture_analytics_event_for_empty_summary(team, user, mo)monkeypatch.setattr(- "posthog.temporal.subscriptions.snapshot_activities.generate_change_summary",+ "products.exports.backend.temporal.subscriptions.snapshot_activities.generate_change_summary",lambda *a, **kw: "",)@@ -439,7 +438,7 @@ async def test_captures_event_with_team_prefixed_distinct_id_when_no_creator(tea)monkeypatch.setattr(- "posthog.temporal.subscriptions.snapshot_activities.generate_change_summary",+ "products.exports.backend.temporal.subscriptions.snapshot_activities.generate_change_summary",lambda *a, **kw: "- Pageviews is trending up",)@@ -494,7 +493,7 @@ async def test_core_memory_flows_into_change_summary(team, user, monkeypatch, streturn "- Pageviews is trending up"monkeypatch.setattr(- "posthog.temporal.subscriptions.snapshot_activities.generate_change_summary",+ "products.exports.backend.temporal.subscriptions.snapshot_activities.generate_change_summary",fake_generate,)@@ -527,7 +526,7 @@ async def test_unhandled_exception_is_logged_and_reraised(team, user, monkeypatcraise RuntimeError("boom while building states")monkeypatch.setattr(- "posthog.temporal.subscriptions.snapshot_activities._build_states_from_content_snapshot",+ "products.exports.backend.temporal.subscriptions.snapshot_activities._build_states_from_content_snapshot",boom,)diff --git a/posthog/temporal/subscriptions/test_snapshot_annotations.py b/products/exports/backend/temporal/subscriptions/test_snapshot_annotations.pysimilarity index 93%rename from posthog/temporal/subscriptions/test_snapshot_annotations.pyrename to products/exports/backend/temporal/subscriptions/test_snapshot_annotations.pyindex d83bc4004a82..1e21d5b08998 100644--- a/posthog/temporal/subscriptions/test_snapshot_annotations.py+++ b/products/exports/backend/temporal/subscriptions/test_snapshot_annotations.py@@ -8,10 +8,9 @@ from posthog.test.base import APIBaseTestfrom parameterized import parameterized-from posthog.api.annotation_context import resolve_snapshot_date_range-from posthog.models import Annotation-from posthog.temporal.subscriptions.snapshot_activities import _load_annotations_section-+from products.annotations.backend.api.annotation_context import resolve_snapshot_date_range+from products.annotations.backend.models.annotation import Annotation+from products.exports.backend.temporal.subscriptions.snapshot_activities import _load_annotations_sectionfrom products.product_analytics.backend.models.insight import Insightdiff --git a/posthog/temporal/subscriptions/test_snapshot_image_loading.py b/products/exports/backend/temporal/subscriptions/test_snapshot_image_loading.pysimilarity index 92%rename from posthog/temporal/subscriptions/test_snapshot_image_loading.pyrename to products/exports/backend/temporal/subscriptions/test_snapshot_image_loading.pyindex 787db5a29ea6..9b7743b81753 100644--- a/posthog/temporal/subscriptions/test_snapshot_image_loading.py+++ b/products/exports/backend/temporal/subscriptions/test_snapshot_image_loading.py@@ -3,13 +3,12 @@ from contextlib import contextmanagerimport pytestfrom unittest.mock import patch-from posthog.models.exported_asset import ExportedAsset-from posthog.temporal.subscriptions.snapshot_activities import (+from products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.temporal.subscriptions.snapshot_activities import (MAX_SUMMARY_IMAGES,SUBSCRIPTION_SUMMARY_IMAGE_SKIPPED,_load_insight_images,)-from products.product_analytics.backend.models.insight import Insightpytestmark = pytest.mark.django_db@@ -50,7 +49,7 @@ def test_loads_bytes_from_object_storage_when_content_empty(team, user):asset = _create_png_asset(team, insight, content=None, content_location="s3://path/to/png")with patch(- "posthog.temporal.subscriptions.snapshot_activities.object_storage.read_bytes",+ "products.exports.backend.temporal.subscriptions.snapshot_activities.object_storage.read_bytes",return_value=b"from-s3",):result = _load_insight_images([asset.id], team.id)@@ -82,7 +81,7 @@ def _non_png_export_scenario(team, user):@contextmanagerdef _over_image_size_cap_scenario(team, user):- from posthog.temporal.subscriptions import snapshot_activities+ from products.exports.backend.temporal.subscriptions import snapshot_activitiesinsight = Insight.objects.create(team=team, name="pv", created_by=user)with patch.object(snapshot_activities, "MAX_IMAGE_BYTES", 4):@@ -95,7 +94,7 @@ def _storage_error_scenario(team, user):insight = Insight.objects.create(team=team, name="pv", created_by=user)asset = _create_png_asset(team, insight, content=None, content_location="s3://path")with patch(- "posthog.temporal.subscriptions.snapshot_activities.object_storage.read_bytes",+ "products.exports.backend.temporal.subscriptions.snapshot_activities.object_storage.read_bytes",side_effect=RuntimeError("boom"),):yield asset.id@@ -194,7 +193,7 @@ def test_scopes_to_team_and_drops_other_teams_assets(team, user):def test_skips_when_aggregate_bytes_exceeded(team, user):- from posthog.temporal.subscriptions import snapshot_activities+ from products.exports.backend.temporal.subscriptions import snapshot_activitiesinsights = [Insight.objects.create(team=team, name=f"pv-{i}", created_by=user) for i in range(3)]assets = [_create_png_asset(team, insight, content=b"XXXX") for insight in insights]diff --git a/posthog/temporal/subscriptions/types.py b/products/exports/backend/temporal/subscriptions/types.pysimilarity index 100%rename from posthog/temporal/subscriptions/types.pyrename to products/exports/backend/temporal/subscriptions/types.pydiff --git a/posthog/temporal/subscriptions/workflows.py b/products/exports/backend/temporal/subscriptions/workflows.pysimilarity index 98%rename from posthog/temporal/subscriptions/workflows.pyrename to products/exports/backend/temporal/subscriptions/workflows.pyindex 3a13e647a00d..a38e543336ca 100644--- a/posthog/temporal/subscriptions/workflows.py+++ b/products/exports/backend/temporal/subscriptions/workflows.py@@ -10,7 +10,6 @@ from temporalio.exceptions import ActivityError, ApplicationError, WorkflowAlreafrom posthog.event_usage import EventSourcefrom posthog.slo.types import SloArea, SloConfig, SloOperation, SloOutcome-from posthog.tasks.exports.failure_handler import is_user_query_error_typefrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.exports.activities import export_asset_activityfrom posthog.temporal.exports.retry_policy import EXPORT_RETRY_POLICY@@ -20,7 +19,9 @@ from posthog.temporal.exports.types import (ExportError,extract_error_details,)-from posthog.temporal.subscriptions.activities import (++from products.exports.backend.tasks.failure_handler import is_user_query_error_type+from products.exports.backend.temporal.subscriptions.activities import (advance_next_delivery_date,create_delivery_record,create_export_assets,@@ -29,8 +30,8 @@ from posthog.temporal.subscriptions.activities import (update_delivery_record,validate_subscription_for_delivery,)-from posthog.temporal.subscriptions.snapshot_activities import snapshot_subscription_insights-from posthog.temporal.subscriptions.types import (+from products.exports.backend.temporal.subscriptions.snapshot_activities import snapshot_subscription_insights+from products.exports.backend.temporal.subscriptions.types import (CreateDeliveryRecordInputs,CreateExportAssetsInputs,DeliverSubscriptionInputs,diff --git a/products/exports/backend/tests/__init__.py b/products/exports/backend/tests/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/models/test/test_exported_asset_model.py b/products/exports/backend/tests/test_exported_asset_model.pysimilarity index 98%rename from posthog/models/test/test_exported_asset_model.pyrename to products/exports/backend/tests/test_exported_asset_model.pyindex 3c87ca8c7ee5..4187336b1d8f 100644--- a/posthog/models/test/test_exported_asset_model.py+++ b/products/exports/backend/tests/test_exported_asset_model.py@@ -5,7 +5,7 @@ from posthog.test.base import APIBaseTestfrom parameterized import parameterized-from posthog.models.exported_asset import SEVEN_DAYS, SIX_MONTHS, TWELVE_MONTHS, ExportedAsset+from products.exports.backend.models.exported_asset import SEVEN_DAYS, SIX_MONTHS, TWELVE_MONTHS, ExportedAssetclass TestExportedAssetModel(APIBaseTest):diff --git a/products/exports/frontend/generated/api.schemas.ts b/products/exports/frontend/generated/api.schemas.tsnew file mode 100644index 000000000000..86d1a49764e0--- /dev/null+++ b/products/exports/frontend/generated/api.schemas.ts@@ -0,0 +1,72 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+/**+ * * `image/png` - image/png+ * `application/pdf` - application/pdf+ * `text/csv` - text/csv+ * `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet+ * `video/webm` - video/webm+ * `video/mp4` - video/mp4+ * `image/gif` - image/gif+ * `application/json` - application/json+ */+export type ExportFormatEnumApi = (typeof ExportFormatEnumApi)[keyof typeof ExportFormatEnumApi]++export const ExportFormatEnumApi = {+ ImagePng: 'image/png',+ ApplicationPdf: 'application/pdf',+ TextCsv: 'text/csv',+ ApplicationVndopenxmlformatsOfficedocumentspreadsheetmlsheet:+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+ VideoWebm: 'video/webm',+ VideoMp4: 'video/mp4',+ ImageGif: 'image/gif',+ ApplicationJson: 'application/json',+} as const++/**+ * Standard ExportedAsset serializer that doesn't return content.+ */+export interface ExportedAssetApi {+ readonly id: number+ /** @nullable */+ dashboard?: number | null+ /** @nullable */+ insight?: number | null+ export_format: ExportFormatEnumApi+ readonly created_at: string+ readonly has_content: boolean+ export_context?: unknown+ readonly filename: string+ /** @nullable */+ readonly expires_after: string | null+ /** @nullable */+ readonly exception: string | null+}++export interface PaginatedExportedAssetListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: ExportedAssetApi[]+}++export type ExportsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}diff --git a/products/exports/frontend/generated/api.ts b/products/exports/frontend/generated/api.tsnew file mode 100644index 000000000000..526f7d5f3b83--- /dev/null+++ b/products/exports/frontend/generated/api.ts@@ -0,0 +1,98 @@+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import type { ExportedAssetApi, ExportsListParams, PaginatedExportedAssetListApi } from './api.schemas'++// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497+type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B++type WritableKeys<T> = {+ [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>+}[keyof T]++type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never+type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never++type Writable<T> = Pick<T, WritableKeys<T>>+type NonReadonly<T> = [T] extends [UnionToIntersection<T>]+ ? {+ [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]+ }+ : DistributeReadOnlyOverUnions<T>++export const getExportsListUrl = (projectId: string, params?: ExportsListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/exports/?${stringifiedParams}`+ : `/api/projects/${projectId}/exports/`+}++export const exportsList = async (+ projectId: string,+ params?: ExportsListParams,+ options?: RequestInit+): Promise<PaginatedExportedAssetListApi> => {+ return apiMutator<PaginatedExportedAssetListApi>(getExportsListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getExportsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/exports/`+}++export const exportsCreate = async (+ projectId: string,+ exportedAssetApi: NonReadonly<ExportedAssetApi>,+ options?: RequestInit+): Promise<ExportedAssetApi> => {+ return apiMutator<ExportedAssetApi>(getExportsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(exportedAssetApi),+ })+}++export const getExportsRetrieveUrl = (projectId: string, id: number) => {+ return `/api/projects/${projectId}/exports/${id}/`+}++export const exportsRetrieve = async (+ projectId: string,+ id: number,+ options?: RequestInit+): Promise<ExportedAssetApi> => {+ return apiMutator<ExportedAssetApi>(getExportsRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getExportsContentRetrieveUrl = (projectId: string, id: number) => {+ return `/api/projects/${projectId}/exports/${id}/content/`+}++export const exportsContentRetrieve = async (projectId: string, id: number, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getExportsContentRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}diff --git a/products/exports/frontend/generated/api.zod.ts b/products/exports/frontend/generated/api.zod.tsnew file mode 100644index 000000000000..d82805c77427--- /dev/null+++ b/products/exports/frontend/generated/api.zod.ts@@ -0,0 +1,32 @@+/**+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.+ * To modify these schemas, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import * as zod from 'zod'++export const ExportsCreateBody = /* @__PURE__ */ zod+ .object({+ dashboard: zod.number().nullish(),+ insight: zod.number().nullish(),+ export_format: zod+ .enum([+ 'image/png',+ 'application/pdf',+ 'text/csv',+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+ 'video/webm',+ 'video/mp4',+ 'image/gif',+ 'application/json',+ ])+ .describe(+ '\* `image\/png` - image\/png\n\* `application\/pdf` - application\/pdf\n\* `text\/csv` - text\/csv\n\* `application\/vnd.openxmlformats-officedocument.spreadsheetml.sheet` - application\/vnd.openxmlformats-officedocument.spreadsheetml.sheet\n\* `video\/webm` - video\/webm\n\* `video\/mp4` - video\/mp4\n\* `image\/gif` - image\/gif\n\* `application\/json` - application\/json'+ ),+ export_context: zod.unknown().optional(),+ })+ .describe("Standard ExportedAsset serializer that doesn't return content.")diff --git a/products/exports/manifest.tsx b/products/exports/manifest.tsxnew file mode 100644index 000000000000..596b8850e633--- /dev/null+++ b/products/exports/manifest.tsx@@ -0,0 +1,23 @@+/**+ * Product manifest for exports.+ *+ * Defines scenes, routes, URLs, and navigation for this product.+ */+import { ProductManifest } from '../../frontend/src/types'++export const manifest: ProductManifest = {+ name: 'Exports',+ scenes: {+ // Define scenes here+ },+ routes: {+ // Define routes here+ },+ redirects: {},+ urls: {+ // Define URL helpers here+ },+ fileSystemTypes: {},+ treeItemsNew: [],+ treeItemsProducts: [],+}diff --git a/products/exports/package.json b/products/exports/package.jsonnew file mode 100644index 000000000000..68453926ec25--- /dev/null+++ b/products/exports/package.json@@ -0,0 +1,6 @@+{+ "name": "@posthog/products-exports",+ "scripts": {+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"+ }+}diff --git a/products/exports/product.yaml b/products/exports/product.yamlnew file mode 100644index 000000000000..54f5be7c60ce--- /dev/null+++ b/products/exports/product.yaml@@ -0,0 +1,3 @@+name: Exports+owners:+ - team-analytics-platformdiff --git a/products/exports/tsconfig.json b/products/exports/tsconfig.jsonnew file mode 100644index 000000000000..fe425d6fcba8--- /dev/null+++ b/products/exports/tsconfig.json@@ -0,0 +1,6 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "composite": true+ }+}diff --git a/products/logs/backend/api.py b/products/logs/backend/api.pyindex 7ce25aa35deb..1bec4491a0e6 100644--- a/products/logs/backend/api.py+++ b/products/logs/backend/api.py@@ -34,9 +34,9 @@ from posthog.event_usage import get_request_analytics_properties, report_user_acfrom posthog.hogql_queries.query_runner import ExecutionModefrom posthog.hogql_queries.utils.time_sliced_query import time_sliced_resultsfrom posthog.models import User-from posthog.models.exported_asset import ExportedAssetfrom posthog.tasks.exporter import export_asset+from products.exports.backend.models.exported_asset import ExportedAssetfrom products.logs.backend.alerts_api import LogsAlertViewSetfrom products.logs.backend.count_query_runner import CountQueryRunnerfrom products.logs.backend.count_ranges_query_runner import (diff --git a/products/logs/backend/test/test_logs_export.py b/products/logs/backend/test/test_logs_export.pyindex 34b84fb0bf00..c21ffad8ef0a 100644--- a/products/logs/backend/test/test_logs_export.py+++ b/products/logs/backend/test/test_logs_export.py@@ -29,7 +29,7 @@ class TestLogsExportEndpoint(APIBaseTest):assert response.status_code == status.HTTP_201_CREATEDassert response.json()["export_format"] == "text/csv"- from posthog.models.exported_asset import ExportedAsset+ from products.exports.backend.models.exported_asset import ExportedAssetasset = ExportedAsset.objects.get(id=response.json()["id"])assert asset.export_context is not None@@ -80,7 +80,7 @@ class TestLogsExportEndpoint(APIBaseTest):)assert response.status_code == status.HTTP_201_CREATED- from posthog.models.exported_asset import ExportedAsset+ from products.exports.backend.models.exported_asset import ExportedAssetasset = ExportedAsset.objects.get(id=response.json()["id"])assert asset.export_context is not Nonediff --git a/products/managed_migrations/frontend/generated/api.schemas.ts b/products/managed_migrations/frontend/generated/api.schemas.tsindex 50b1cb92ea3e..53112339e5be 100644--- a/products/managed_migrations/frontend/generated/api.schemas.ts+++ b/products/managed_migrations/frontend/generated/api.schemas.ts@@ -7,6 +7,11 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+/**+ * @nullable+ */+export type BatchImportApiCreatedBy = { [key: string]: unknown } | null+/*** * `completed` - Completed* `failed` - Failed@@ -22,11 +27,6 @@ export const BatchImportStatusEnumApi = {Running: 'running',} as const-/**- * @nullable- */-export type BatchImportApiCreatedBy = { [key: string]: unknown } | null-/*** Serializer for BatchImport model*/@@ -44,15 +44,6 @@ export interface BatchImportApi {readonly import_config: unknown}-export interface PaginatedBatchImportListApi {- count: number- /** @nullable */- next?: string | null- /** @nullable */- previous?: string | null- results: BatchImportApi[]-}-/*** @nullable*/@@ -74,38 +65,3 @@ export interface PatchedBatchImportApi {readonly display_status_message?: string | nullreadonly import_config?: unknown}--export type ManagedMigrationsListParams = {- /**- * Number of results to return per page.- */- limit?: number- /**- * The initial index from which to return the results.- */- offset?: number- /**- * Which field to use when ordering the results.- */- ordering?: string- /**- * A search term.- */- search?: string- /**- * * `completed` - Completed- * `failed` - Failed- * `paused` - Paused- * `running` - Running- */- status?: ManagedMigrationsListStatus-}--export type ManagedMigrationsListStatus = (typeof ManagedMigrationsListStatus)[keyof typeof ManagedMigrationsListStatus]--export const ManagedMigrationsListStatus = {- Completed: 'completed',- Failed: 'failed',- Paused: 'paused',- Running: 'running',-} as constdiff --git a/products/managed_migrations/frontend/generated/api.ts b/products/managed_migrations/frontend/generated/api.tsindex 4dbabe53b8a4..efacf3acfdbf 100644--- a/products/managed_migrations/frontend/generated/api.ts+++ b/products/managed_migrations/frontend/generated/api.ts@@ -8,12 +8,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* PostHog API - generated* OpenAPI spec version: 1.0.0*/-import type {- BatchImportApi,- ManagedMigrationsListParams,- PaginatedBatchImportListApi,- PatchedBatchImportApi,-} from './api.schemas'+import type { BatchImportApi, PatchedBatchImportApi } from './api.schemas'// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B@@ -32,56 +27,6 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]}: DistributeReadOnlyOverUnions<T>-export const getManagedMigrationsListUrl = (projectId: string, params?: ManagedMigrationsListParams) => {- const normalizedParams = new URLSearchParams()-- Object.entries(params || {}).forEach(([key, value]) => {- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : value.toString())- }- })-- const stringifiedParams = normalizedParams.toString()-- return stringifiedParams.length > 0- ? `/api/projects/${projectId}/managed_migrations/?${stringifiedParams}`- : `/api/projects/${projectId}/managed_migrations/`-}--/**- * List managed migrations using the response serializer- */-export const managedMigrationsList = async (- projectId: string,- params?: ManagedMigrationsListParams,- options?: RequestInit-): Promise<PaginatedBatchImportListApi> => {- return apiMutator<PaginatedBatchImportListApi>(getManagedMigrationsListUrl(projectId, params), {- ...options,- method: 'GET',- })-}--export const getManagedMigrationsCreateUrl = (projectId: string) => {- return `/api/projects/${projectId}/managed_migrations/`-}--/**- * Create a new managed migration/batch import.- */-export const managedMigrationsCreate = async (- projectId: string,- batchImportApi?: NonReadonly<BatchImportApi>,- options?: RequestInit-): Promise<BatchImportApi> => {- return apiMutator<BatchImportApi>(getManagedMigrationsCreateUrl(projectId), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(batchImportApi),- })-}-export const getManagedMigrationsRetrieveUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/managed_migrations/${id}/`}diff --git a/products/managed_migrations/frontend/generated/api.zod.ts b/products/managed_migrations/frontend/generated/api.zod.tsindex e2a13a1c186a..b9087d7d8154 100644--- a/products/managed_migrations/frontend/generated/api.zod.ts+++ b/products/managed_migrations/frontend/generated/api.zod.ts@@ -9,13 +9,6 @@*/import * as zod from 'zod'-/**- * Create a new managed migration/batch import.- */-export const ManagedMigrationsCreateBody = /* @__PURE__ */ zod- .looseObject({})- .describe('Serializer for BatchImport model')-/*** Viewset for BatchImport model*/diff --git a/products/product_analytics/backend/api/insight_suggestions.py b/products/product_analytics/backend/api/insight_suggestions.pyindex 3f2165c66410..5459695f1400 100644--- a/products/product_analytics/backend/api/insight_suggestions.py+++ b/products/product_analytics/backend/api/insight_suggestions.py@@ -18,9 +18,10 @@ from posthog.schema import (from posthog.hogql.ai import hit_openai-from posthog.api.annotation_context import build_annotations_block, resolve_query_date_rangefrom posthog.models import Team+from products.annotations.backend.api.annotation_context import build_annotations_block, resolve_query_date_range+logger = structlog.get_logger(__name__)diff --git a/products/replay_vision/backend/temporal/activities/ensure_session_asset.py b/products/replay_vision/backend/temporal/activities/ensure_session_asset.pyindex 5e97032cf4eb..0823520f48a7 100644--- a/products/replay_vision/backend/temporal/activities/ensure_session_asset.py+++ b/products/replay_vision/backend/temporal/activities/ensure_session_asset.py@@ -4,8 +4,7 @@ from django.utils.timezone import nowfrom temporalio import activity-from posthog.models.exported_asset import ExportedAsset-+from products.exports.backend.models.exported_asset import ExportedAssetfrom products.replay_vision.backend.temporal.decorators import track_activityfrom products.replay_vision.backend.temporal.types import EnsureSessionAssetInputs, EnsureSessionAssetOutputdiff --git a/products/replay_vision/backend/temporal/activities/upload_video_to_gemini.py b/products/replay_vision/backend/temporal/activities/upload_video_to_gemini.pyindex a7d085a28e1f..5fcee697cf2b 100644--- a/products/replay_vision/backend/temporal/activities/upload_video_to_gemini.py+++ b/products/replay_vision/backend/temporal/activities/upload_video_to_gemini.py@@ -15,10 +15,10 @@ from google.genai import ()from temporalio import activity-from posthog.models.exported_asset import ExportedAssetfrom posthog.storage import object_storagefrom posthog.temporal.session_replay.gemini_cleanup_sweep.tracking import track_uploaded_file+from products.exports.backend.models.exported_asset import ExportedAssetfrom products.replay_vision.backend.temporal.decorators import track_activityfrom products.replay_vision.backend.temporal.errors import FailureKind, ScannerFailureErrorfrom products.replay_vision.backend.temporal.types import UploadedVideo, UploadVideoToGeminiInputsdiff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.pyindex 3519a84c7418..dafce2383ff0 100644--- a/products/replay_vision/backend/tests/test_temporal.py+++ b/products/replay_vision/backend/tests/test_temporal.py@@ -16,11 +16,11 @@ from structlog.testing import capture_logsfrom temporalio.exceptions import ActivityError, ApplicationErrorfrom posthog.models import Organization, Team-from posthog.models.exported_asset import ExportedAssetfrom posthog.models.user import Userfrom posthog.redis import get_async_clientfrom posthog.session_recordings.queries.session_replay_events import SessionReplayEvents+from products.exports.backend.models.exported_asset import ExportedAssetfrom products.replay_vision.backend.models.replay_observation import (ObservationStatus,ObservationTrigger,diff --git a/products/ruff.toml b/products/ruff.tomlindex 839160d6466f..e605e568a453 100644--- a/products/ruff.toml+++ b/products/ruff.toml@@ -20,6 +20,7 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]# to check remaining count before removing the exemption."actions/backend/**" = ["ANN"]"alerts/backend/**" = ["ANN"]+"annotations/backend/**" = ["ANN"]"batch_exports/backend/**" = ["ANN"]"cdp/backend/**" = ["ANN"]"conversations/backend/**" = ["ANN"]@@ -32,6 +33,7 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]"endpoints/backend/**" = ["ANN"]"error_tracking/backend/**" = ["ANN"]"experiments/backend/**" = ["ANN"]+"exports/backend/**" = ["ANN"]"feature_flags/backend/**" = ["ANN"]"ai_observability/backend/**" = ["ANN"]"logs/backend/**" = ["ANN"]@@ -55,6 +57,7 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]"actions/**" = ["PLC0415"]"alerts/**" = ["PLC0415"]"analytics_platform/**" = ["PLC0415"]+"annotations/**" = ["PLC0415"]"batch_exports/**" = ["PLC0415"]"business_knowledge/**" = ["PLC0415"]"cdp/**" = ["PLC0415"]@@ -70,6 +73,7 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]"endpoints/**" = ["PLC0415"]"error_tracking/**" = ["PLC0415"]"experiments/**" = ["PLC0415"]+"exports/**" = ["PLC0415"]"feature_flags/**" = ["PLC0415"]"growth/**" = ["PLC0415"]"legal_documents/**" = ["PLC0415"]diff --git a/products/user_interviews/backend/presentation/views.py b/products/user_interviews/backend/presentation/views.pyindex a992b424c9b0..b227d238d82b 100644--- a/products/user_interviews/backend/presentation/views.py+++ b/products/user_interviews/backend/presentation/views.py@@ -41,7 +41,7 @@ from posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.permissions import PostHogFeatureFlagPermission-from posthog.tasks.exports.csv_exporter import _sanitize_formula_injection+from posthog.security.spreadsheet_safety import sanitize_formula_injectionfrom posthog.utils import absolute_urifrom ..facade.api import parse_interviewee_identifier@@ -909,10 +909,10 @@ class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):rows = [{- "interviewee_identifier": _sanitize_formula_injection(r["identifier"]),- "interviewee_email": _sanitize_formula_injection(r["email"] or ""),- "user_name": _sanitize_formula_injection(r["user_name"]),- "interview_url": _sanitize_formula_injection(r["interview_url"]),+ "interviewee_identifier": sanitize_formula_injection(r["identifier"]),+ "interviewee_email": sanitize_formula_injection(r["email"] or ""),+ "user_name": sanitize_formula_injection(r["user_name"]),+ "interview_url": sanitize_formula_injection(r["interview_url"]),}for r in results]diff --git a/tach.toml b/tach.tomlindex 7d94394ba6bc..f519f888021f 100644--- a/tach.toml+++ b/tach.toml@@ -56,6 +56,7 @@ depends_on = ["products.business_knowledge","products.user_interviews","products.warehouse_sources",+ "products.exports",]layer = "modules"@@ -110,7 +111,7 @@ depends_on = ["products.wizard","products.workflows","products.actions",- "products.alerts", "products.warehouse_sources", "products.data_tools",+ "products.alerts", "products.warehouse_sources", "products.data_tools", "products.exports", "products.annotations",]layer = "modules"@@ -157,6 +158,7 @@ depends_on = ["ee","posthog","products.actions",+ "products.batch_exports",]layer = "modules"@@ -178,6 +180,7 @@ depends_on = ["products.error_tracking","products.mcp_analytics","products.product_analytics",+ "products.annotations",]layer = "modules"@@ -215,7 +218,7 @@ depends_on = ["products.cdp","products.dashboards","products.data_modeling",- "products.revenue_analytics", "products.warehouse_sources", "products.data_tools",+ "products.revenue_analytics", "products.warehouse_sources", "products.data_tools", "products.batch_exports",]layer = "modules"@@ -336,6 +339,7 @@ path = "products.logs"depends_on = ["posthog","products.cdp",+ "products.exports","products.signals",]layer = "modules"@@ -437,6 +441,7 @@ depends_on = ["products.dashboards","products.data_warehouse","products.event_definitions",+ "products.annotations",]layer = "modules"@@ -462,6 +467,7 @@ path = "products.replay_vision"depends_on = ["ee","posthog",+ "products.exports",]layer = "modules"@@ -568,6 +574,7 @@ path = "products.user_interviews"depends_on = ["ee","posthog",+ "products.exports",]layer = "modules"@@ -770,3 +777,13 @@ expose = [from = ["products.engineering_analytics",]++[[modules]]+path = "products.exports"+depends_on = ["posthog", "products.actions", "products.dashboards", "ee", "products.annotations", "products.product_analytics"]+layer = "modules"++[[modules]]+path = "products.annotations"+depends_on = ["posthog", "products.product_analytics", "products.dashboards"]+layer = "modules"