Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(devex): move workflows + cdp models to products apps (#60248)

Julian Bezfefcae2b83f3
diff --git a/ee/migrations/0046_migrate_cdp_models.py b/ee/migrations/0046_migrate_cdp_models.py
new file mode 100644
index 000000000000..ddfc30d9aaf5
--- /dev/null
+++ b/ee/migrations/0046_migrate_cdp_models.py
@@ -0,0 +1,48 @@
+from django.db import migrations
+
+MODELS_TO_MOVE = ("hook",)
+
+
+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, "ee", "cdp")
+
+
+def reverse_content_types(apps, schema_editor):
+ _move_content_types(apps, schema_editor, "cdp", "ee")
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("ee", "0045_migrate_feature_flags_models"),
+ ("cdp", "0001_migrate_cdp_models"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.DeleteModel(
+ name="Hook",
+ ),
+ ],
+ database_operations=[],
+ ),
+ migrations.RunPython(update_content_types, reverse_content_types),
+ ]
diff --git a/ee/migrations/max_migration.txt b/ee/migrations/max_migration.txt
index bfc21c1368e0..a3ba18c59c19 100644
--- a/ee/migrations/max_migration.txt
+++ b/ee/migrations/max_migration.txt
@@ -1 +1 @@
-0045_migrate_feature_flags_models
+0046_migrate_cdp_models
diff --git a/ee/models/__init__.py b/ee/models/__init__.py
index ee58862a3884..d517fdea8f8d 100644
--- a/ee/models/__init__.py
+++ b/ee/models/__init__.py
@@ -8,7 +8,6 @@ from .assistant import (
)
from .dashboard_privilege import DashboardPrivilege
from .event_definition import EnterpriseEventDefinition
-from .hook import Hook
from .license import License
from .property_definition import EnterprisePropertyDefinition
from .rbac.access_control import AccessControl
@@ -29,7 +28,6 @@ __all__ = [
"Conversation",
"EnterpriseEventDefinition",
"EnterprisePropertyDefinition",
- "Hook",
"License",
"Role",
"RoleMembership",
diff --git a/ee/urls.py b/ee/urls.py
index 72469d161bd8..b4a8516d3c0b 100644
--- a/ee/urls.py
+++ b/ee/urls.py
@@ -13,6 +13,8 @@ from django_otp.plugins.otp_totp.models import TOTPDevice
from posthog.middleware import impersonated_session_logout
from posthog.views import api_key_search_view, redis_edit_ttl_view, redis_values_view
+from products.cdp.backend.api import hooks
+
from ee.admin.loginas_views import loginas_user, upgrade_impersonation
from ee.admin.oauth_views import admin_auth_check, admin_oauth_success
from ee.api import integration
@@ -27,7 +29,6 @@ from .api import (
conversation,
core_memory,
dashboard_collaborator,
- hooks,
license,
sentry_stats,
subscription,
diff --git a/posthog/admin/test_admin.py b/posthog/admin/test_admin.py
index b061abbe563a..7e9103ef1a21 100644
--- a/posthog/admin/test_admin.py
+++ b/posthog/admin/test_admin.py
@@ -9,10 +9,11 @@ from posthog.admin import _OAUTH_ADMIN_MODEL_NAMES, install_admin_app_list_overr
from posthog.admin.admins.event_ingestion_restriction_config import EventIngestionRestrictionConfigAdmin
from posthog.admin.admins.user_admin import UserAdmin
from posthog.admin.inlines.organization_member_inline import OrganizationMemberForUserInline, OrganizationMemberInline
-from posthog.admin.inlines.plugin_attachment_inline import PluginAttachmentInline
from posthog.models import User
from posthog.models.event_ingestion_restriction_config import EventIngestionRestrictionConfig
+from products.cdp.backend.admin.plugin_attachment_inline import PluginAttachmentInline
+
class TestOAuthSidebarRegrouping(BaseTest):
def _patched_get_app_list(self):
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.py
index b69971dc1e98..a29791e353d0 100644
--- a/posthog/api/__init__.py
+++ b/posthog/api/__init__.py
@@ -3,16 +3,7 @@ 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: F401
-from posthog.api import (
- data_color_theme,
- hog_flow,
- hog_flow_template,
- metalytics,
- my_notifications,
- project,
- user_integration,
- user_push_token,
-)
+from posthog.api import data_color_theme, metalytics, my_notifications, project, user_integration, user_push_token
from posthog.api.batch_imports import BatchImportViewSet
from posthog.api.csp_reporting import CSPReportingViewSet
from posthog.api.js_snippet import JsSnippetViewSet
@@ -75,6 +66,7 @@ from products.ai_observability.backend.api import (
TraceReviewViewSet,
)
from products.ai_observability.backend.api.skills import LLMSkillViewSet
+from products.cdp.backend.api import hog_function, hog_function_template, plugin, plugin_log_entry
from products.dashboards.backend.api import dashboard, dashboard_templates
from products.data_modeling.backend.api import DAGViewSet, EdgeViewSet, NodeViewSet
from products.data_warehouse.backend.api import (
@@ -143,6 +135,7 @@ from products.web_analytics.backend.api.heatmaps_api import (
SavedHeatmapViewSet,
)
from products.web_analytics.backend.api.web_analytics_filter_preset import WebAnalyticsFilterPresetViewSet
+from products.workflows.backend.api import hog_flow, hog_flow_template
from ee.api.quota_limits import QuotaLimitsViewSet
from ee.api.session_summaries import SessionGroupSummaryViewSet
@@ -167,8 +160,6 @@ from . import (
exports,
health_issue,
hog,
- hog_function,
- hog_function_template,
ingestion_warnings,
instance_settings,
instance_status,
@@ -181,8 +172,6 @@ from . import (
organization_invite,
organization_member,
personal_api_key,
- plugin,
- plugin_log_entry,
project_secret_api_key,
proxy_record,
query,
diff --git a/posthog/api/file_system/deletion.py b/posthog/api/file_system/deletion.py
index f0187d63eb3f..74c87a30ad65 100644
--- a/posthog/api/file_system/deletion.py
+++ b/posthog/api/file_system/deletion.py
@@ -9,9 +9,10 @@ from django.apps import apps
from django.core.exceptions import ObjectDoesNotExist
from posthog.models.file_system.file_system import FileSystem, join_path, split_path
-from posthog.models.hog_functions.hog_function import HogFunctionType
from posthog.models.signals import mute_selected_signals
+from products.cdp.backend.models.hog_functions.hog_function import HogFunctionType
+
logger = logging.getLogger(__name__)
LEGACY_HOG_FUNCTION_TYPES = [
diff --git a/posthog/api/file_system/registrations.py b/posthog/api/file_system/registrations.py
index afdf7a7aa954..c98577cf275e 100644
--- a/posthog/api/file_system/registrations.py
+++ b/posthog/api/file_system/registrations.py
@@ -14,10 +14,11 @@ from posthog.api.file_system.deletion import (
)
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from posthog.models.activity_logging.model_activity import is_impersonated_session
-from posthog.models.hog_functions.utils import humanize_hog_function_type
from posthog.models.user import User
from posthog.session_recordings.session_recording_playlist_api import log_playlist_activity
+from products.cdp.backend.models.hog_functions.utils import humanize_hog_function_type
+
def _first_non_blank(*values: str | None) -> str | None:
for value in values:
@@ -417,7 +418,7 @@ def register_core_file_system_types() -> None:
type_string = f"hog_function/{hog_type}"
register_file_system_type(
type_string,
- "posthog",
+ "cdp",
"HogFunction",
undo_message="Send PATCH /api/projects/@current/hog_functions/{id} with deleted=false.",
)
diff --git a/posthog/api/file_system/test/test_file_system.py b/posthog/api/file_system/test/test_file_system.py
index 698c93fe3449..8c11774fe0da 100644
--- a/posthog/api/file_system/test/test_file_system.py
+++ b/posthog/api/file_system/test/test_file_system.py
@@ -15,9 +15,9 @@ from posthog.models import Project, Team, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.cohort import Cohort
from posthog.models.file_system.file_system import FileSystem
-from posthog.models.hog_functions.hog_function import HogFunction, HogFunctionType
from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType
from products.dashboards.backend.models.dashboard import Dashboard
from products.early_access_features.backend.models import EarlyAccessFeature
from products.experiments.backend.models.experiment import Experiment
diff --git a/posthog/api/metalytics.py b/posthog/api/metalytics.py
index 4193c25ccda6..321180bb904e 100644
--- a/posthog/api/metalytics.py
+++ b/posthog/api/metalytics.py
@@ -7,9 +7,10 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.kafka_client.routing import get_producer
from posthog.kafka_client.topics import KAFKA_APP_METRICS2
from posthog.models.event.util import format_clickhouse_timestamp
-from posthog.models.plugin import PluginConfig
from posthog.utils import cast_timestamp_or_now
+from products.cdp.backend.models.plugin import PluginConfig
+
class MetalyticsCreateRequestSerializer(serializers.Serializer):
metric_name = serializers.ChoiceField(choices=["viewed"], required=True)
diff --git a/posthog/api/my_notifications.py b/posthog/api/my_notifications.py
index 9c6b4999af4c..03628f67b200 100644
--- a/posthog/api/my_notifications.py
+++ b/posthog/api/my_notifications.py
@@ -12,9 +12,10 @@ from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.utils import ServerTimingsGathered, action
-from posthog.models import ActivityLog, Cohort, HogFunction, NotificationViewed, User
+from posthog.models import ActivityLog, Cohort, NotificationViewed, User
from posthog.models.comment import Comment
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.notebooks.backend.models import Notebook
from products.product_analytics.backend.models.insight import Insight
diff --git a/posthog/api/search.py b/posthog/api/search.py
index a26654d97bd0..dfd82a907f63 100644
--- a/posthog/api/search.py
+++ b/posthog/api/search.py
@@ -13,7 +13,6 @@ from posthog.api.documentation import _FallbackSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.helpers.full_text_search import build_rank, process_query
from posthog.models import Cohort, EventDefinition, PropertyDefinition
-from posthog.models.hog_flow.hog_flow import HogFlow
from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
@@ -23,6 +22,7 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.notebooks.backend.models import Notebook
from products.product_analytics.backend.models.insight import Insight
from products.surveys.backend.models import Survey
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
LIMIT = 25
diff --git a/posthog/api/test/test_file_system.py b/posthog/api/test/test_file_system.py
index d40ef12fede3..b48941a20219 100644
--- a/posthog/api/test/test_file_system.py
+++ b/posthog/api/test/test_file_system.py
@@ -22,10 +22,10 @@ from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.cohort.cohort import Cohort
from posthog.models.file_system.file_system import FileSystem
from posthog.models.file_system.file_system_view_log import FileSystemViewLog
-from posthog.models.hog_functions.hog_function import HogFunction, HogFunctionType
from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
from products.actions.backend.models.action import Action
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType
from products.dashboards.backend.models.dashboard import Dashboard
from products.early_access_features.backend.models import EarlyAccessFeature
from products.experiments.backend.models.experiment import Experiment
diff --git a/posthog/api/test/test_log_entries.py b/posthog/api/test/test_log_entries.py
index d0ac6464efea..5dcb3789c68b 100644
--- a/posthog/api/test/test_log_entries.py
+++ b/posthog/api/test/test_log_entries.py
@@ -5,7 +5,8 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixin, QueryMatchingTes
from rest_framework import status
from posthog.clickhouse.client.execute import sync_execute
-from posthog.models.hog_functions.hog_function import HogFunction
+
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
def create_log_entry(
diff --git a/posthog/api/test/test_search.py b/posthog/api/test/test_search.py
index d9c81bdd7dd9..5a7645a90eac 100644
--- a/posthog/api/test/test_search.py
+++ b/posthog/api/test/test_search.py
@@ -8,7 +8,6 @@ from django.test.utils import CaptureQueriesContext
from posthog.api.search import ENTITY_MAP, class_queryset, search_entities
from posthog.helpers.full_text_search import build_search_vector, process_query
from posthog.models import Team
-from posthog.models.hog_flow.hog_flow import HogFlow
from products.dashboards.backend.models.dashboard import Dashboard
from products.early_access_features.backend.models import EarlyAccessFeature
@@ -16,6 +15,7 @@ from products.event_definitions.backend.models.event_definition import EventDefi
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.notebooks.backend.models import Notebook
from products.product_analytics.backend.models.insight import Insight
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
class TestSearch(APIBaseTest):
diff --git a/posthog/api/test/test_site_app.py b/posthog/api/test/test_site_app.py
index fa80c4777369..766c3a3ad3a4 100644
--- a/posthog/api/test/test_site_app.py
+++ b/posthog/api/test/test_site_app.py
@@ -5,7 +5,8 @@ from django.test.client import Client
from rest_framework import status
from posthog.api.site_app import get_site_config_from_schema
-from posthog.models import Plugin, PluginConfig, PluginSourceFile
+
+from products.cdp.backend.models.plugin import Plugin, PluginConfig, PluginSourceFile
class TestSiteApp(BaseTest):
diff --git a/posthog/apps.py b/posthog/apps.py
index 3148e8e8404e..62d2b10082cd 100644
--- a/posthog/apps.py
+++ b/posthog/apps.py
@@ -106,7 +106,8 @@ class PostHogConfig(AppConfig):
setup_async_migrations()
from posthog.api.file_system import registrations as file_system_registrations
- from posthog.tasks.hog_functions import queue_sync_hog_function_templates
+
+ from products.cdp.backend.tasks.hog_functions import queue_sync_hog_function_templates
# Skip during tests since we handle this in conftest.py
# Skip during collectstatic (STATIC_COLLECTION=1 in Dockerfile) — no Redis available at build time
diff --git a/posthog/cdp/legacy_plugins.py b/posthog/cdp/legacy_plugins.py
index ff62224d8bff..35128e01ac72 100644
--- a/posthog/cdp/legacy_plugins.py
+++ b/posthog/cdp/legacy_plugins.py
@@ -1,5 +1,5 @@
-from posthog.api.hog_function import HogFunctionSerializer
-from posthog.models.hog_function_template import HogFunctionTemplate
+from products.cdp.backend.api.hog_function import HogFunctionSerializer
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
def hog_function_from_plugin_config(plugin_config: dict, serializer_context: dict) -> HogFunctionSerializer:
diff --git a/posthog/cdp/migrations.py b/posthog/cdp/migrations.py
index 7fbeb5c077a6..8f330ad4fc87 100644
--- a/posthog/cdp/migrations.py
+++ b/posthog/cdp/migrations.py
@@ -4,12 +4,13 @@ from typing import Any
from django.db import transaction
from django.db.models import Q
-from posthog.api.hog_function import HogFunctionSerializer
-from posthog.models.hog_function_template import HogFunctionTemplate
-from posthog.models.hog_functions.hog_function import HogFunction
-from posthog.models.plugin import PluginAttachment, PluginConfig
from posthog.models.team.team import Team
+from products.cdp.backend.api.hog_function import HogFunctionSerializer
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.cdp.backend.models.plugin import PluginAttachment, PluginConfig
+
# python manage.py migrate_plugins_to_hog_functions --dry-run --test-mode --kind=transformation
diff --git a/posthog/cdp/site_functions.py b/posthog/cdp/site_functions.py
index 4c3c6e5b5304..c16d975b21e1 100644
--- a/posthog/cdp/site_functions.py
+++ b/posthog/cdp/site_functions.py
@@ -4,8 +4,9 @@ from posthog.hogql.compiler.javascript import JavaScriptCompiler
from posthog.cdp.filters import hog_function_filters_to_expr
from posthog.cdp.validation import transpile_template_code
-from posthog.models.hog_functions.hog_function import HogFunction
-from posthog.models.plugin import transpile
+
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.cdp.backend.models.plugin import transpile
def get_transpiled_function(hog_function: HogFunction) -> str:
diff --git a/posthog/cdp/templates/avo/test_template_avo.py b/posthog/cdp/templates/avo/test_template_avo.py
index ae9dc91f4d9f..d3214069a891 100644
--- a/posthog/cdp/templates/avo/test_template_avo.py
+++ b/posthog/cdp/templates/avo/test_template_avo.py
@@ -5,7 +5,8 @@ from posthog.cdp.templates.avo.template_avo import (
template as template_avo,
)
from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest
-from posthog.models import PluginConfig
+
+from products.cdp.backend.models.plugin import PluginConfig
class TestTemplateAvo(BaseHogFunctionTemplateTest):
diff --git a/posthog/cdp/templates/customerio/test_template_customerio.py b/posthog/cdp/templates/customerio/test_template_customerio.py
index 94cc0d27dc3c..20ac4524b06d 100644
--- a/posthog/cdp/templates/customerio/test_template_customerio.py
+++ b/posthog/cdp/templates/customerio/test_template_customerio.py
@@ -6,7 +6,8 @@ from posthog.cdp.templates.customerio.template_customerio import (
template as template_customerio,
)
from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest
-from posthog.models.plugin import PluginConfig
+
+from products.cdp.backend.models.plugin import PluginConfig
from common.hogvm.python.utils import UncaughtHogVMException
diff --git a/posthog/cdp/templates/google_cloud_storage/template_google_cloud_storage.py b/posthog/cdp/templates/google_cloud_storage/template_google_cloud_storage.py
index 9041eac094da..85223bfff6d8 100644
--- a/posthog/cdp/templates/google_cloud_storage/template_google_cloud_storage.py
+++ b/posthog/cdp/templates/google_cloud_storage/template_google_cloud_storage.py
@@ -81,7 +81,7 @@ class TemplateGoogleCloudStorageMigrator(HogFunctionTemplateMigrator):
exportEventsToIgnore = [x.strip() for x in obj.config.get("exportEventsToIgnore", "").split(",") if x]
bucketName = obj.config.get("bucketName", "")
- from posthog.models.plugin import PluginAttachment
+ from products.cdp.backend.models.plugin import PluginAttachment
attachment: PluginAttachment | None = PluginAttachment.objects.filter(
plugin_config=obj, key="googleCloudKeyJson"
diff --git a/posthog/cdp/templates/google_cloud_storage/test_template_google_cloud_storage.py b/posthog/cdp/templates/google_cloud_storage/test_template_google_cloud_storage.py
index 716ed330840e..e1157b2f1fdc 100644
--- a/posthog/cdp/templates/google_cloud_storage/test_template_google_cloud_storage.py
+++ b/posthog/cdp/templates/google_cloud_storage/test_template_google_cloud_storage.py
@@ -4,7 +4,9 @@ from posthog.test.base import BaseTest
from unittest.mock import patch
from posthog.cdp.templates.google_cloud_storage.template_google_cloud_storage import TemplateGoogleCloudStorageMigrator
-from posthog.models import Integration, Plugin, PluginAttachment, PluginConfig
+from posthog.models import Integration
+
+from products.cdp.backend.models.plugin import Plugin, PluginAttachment, PluginConfig
class TestTemplateMigration(BaseTest):
diff --git a/posthog/cdp/templates/google_pubsub/template_google_pubsub.py b/posthog/cdp/templates/google_pubsub/template_google_pubsub.py
index f72d9333f34d..8cfeeab75f93 100644
--- a/posthog/cdp/templates/google_pubsub/template_google_pubsub.py
+++ b/posthog/cdp/templates/google_pubsub/template_google_pubsub.py
@@ -87,7 +87,7 @@ class TemplateGooglePubSubMigrator(HogFunctionTemplateMigrator):
exportEventsToIgnore = [x.strip() for x in obj.config.get("exportEventsToIgnore", "").split(",") if x]
topicId = obj.config.get("topicId", "")
- from posthog.models.plugin import PluginAttachment
+ from products.cdp.backend.models.plugin import PluginAttachment
attachment: PluginAttachment | None = PluginAttachment.objects.filter(
plugin_config=obj, key="googleCloudKeyJson"
diff --git a/posthog/cdp/templates/google_pubsub/test_template_google_pubsub.py b/posthog/cdp/templates/google_pubsub/test_template_google_pubsub.py
index 0d347df074ba..dc79257df646 100644
--- a/posthog/cdp/templates/google_pubsub/test_template_google_pubsub.py
+++ b/posthog/cdp/templates/google_pubsub/test_template_google_pubsub.py
@@ -4,7 +4,9 @@ from posthog.test.base import BaseTest
from unittest.mock import patch
from posthog.cdp.templates.google_pubsub.template_google_pubsub import TemplateGooglePubSubMigrator
-from posthog.models import Integration, Plugin, PluginAttachment, PluginConfig
+from posthog.models import Integration
+
+from products.cdp.backend.models.plugin import Plugin, PluginAttachment, PluginConfig
class TestTemplateMigration(BaseTest):
diff --git a/posthog/cdp/templates/helpers.py b/posthog/cdp/templates/helpers.py
index f407d6035610..6a9315e2e56d 100644
--- a/posthog/cdp/templates/helpers.py
+++ b/posthog/cdp/templates/helpers.py
@@ -9,9 +9,10 @@ from unittest.mock import MagicMock, patch
from posthog.cdp.site_functions import get_transpiled_function
from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC, sync_template_to_db
from posthog.cdp.validation import compile_hog
-from posthog.models import HogFunction
from posthog.models.utils import uuid7
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+
from common.hogvm.python.execute import execute_bytecode
from common.hogvm.python.stl import now
@@ -158,7 +159,9 @@ class BaseSiteDestinationFunctionTest(APIBaseTest):
# Mock the plugin server status endpoint to avoid connection errors
# Patch where it's used (in hog_function.py) not where it's defined
- self.mock_get_status = patch("posthog.models.hog_functions.hog_function.get_hog_function_status").start()
+ self.mock_get_status = patch(
+ "products.cdp.backend.models.hog_functions.hog_function.get_hog_function_status"
+ ).start()
self.mock_get_status.return_value = MagicMock(status_code=200, json=lambda: {"state": "idle", "tokens": 0})
self.addCleanup(self.mock_get_status.stop)
diff --git a/posthog/cdp/templates/hog_function_template.py b/posthog/cdp/templates/hog_function_template.py
index fef62c82b56e..5c8cc3dc2dc8 100644
--- a/posthog/cdp/templates/hog_function_template.py
+++ b/posthog/cdp/templates/hog_function_template.py
@@ -1,11 +1,11 @@
import dataclasses
from typing import TYPE_CHECKING, Literal, Optional
-from posthog.api.hog_function_template import HogFunctionTemplateSerializer
-from posthog.models.hog_function_template import HogFunctionTemplate
+from products.cdp.backend.api.hog_function_template import HogFunctionTemplateSerializer
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
if TYPE_CHECKING:
- from posthog.models.plugin import PluginConfig
+ from products.cdp.backend.models.plugin import PluginConfig
else:
PluginConfig = None
diff --git a/posthog/cdp/templates/hubspot/test_template_hubspot.py b/posthog/cdp/templates/hubspot/test_template_hubspot.py
index 92b451b98a2b..d184c12b3018 100644
--- a/posthog/cdp/templates/hubspot/test_template_hubspot.py
+++ b/posthog/cdp/templates/hubspot/test_template_hubspot.py
@@ -7,7 +7,8 @@ from posthog.cdp.templates.hubspot.template_hubspot import (
template as template_hubspot,
template_event as template_hubspot_event,
)
-from posthog.models import PluginConfig
+
+from products.cdp.backend.models.plugin import PluginConfig
from common.hogvm.python.utils import UncaughtHogVMException
diff --git a/posthog/cdp/templates/posthog/test_template_posthog.py b/posthog/cdp/templates/posthog/test_template_posthog.py
index 9e8bdf096f5f..a41d0f50c22b 100644
--- a/posthog/cdp/templates/posthog/test_template_posthog.py
+++ b/posthog/cdp/templates/posthog/test_template_posthog.py
@@ -5,7 +5,8 @@ from posthog.cdp.templates.posthog.template_posthog import (
TemplatePostHogMigrator,
template as template_posthog,
)
-from posthog.models import PluginConfig
+
+from products.cdp.backend.models.plugin import PluginConfig
class TestTemplatePosthog(BaseHogFunctionTemplateTest):
diff --git a/posthog/cdp/templates/rudderstack/test_template_rudderstack.py b/posthog/cdp/templates/rudderstack/test_template_rudderstack.py
index 784b5148858c..1ea1a62d7381 100644
--- a/posthog/cdp/templates/rudderstack/test_template_rudderstack.py
+++ b/posthog/cdp/templates/rudderstack/test_template_rudderstack.py
@@ -5,7 +5,8 @@ from posthog.cdp.templates.rudderstack.template_rudderstack import (
TemplateRudderstackMigrator,
template as template_rudderstack,
)
-from posthog.models import PluginConfig
+
+from products.cdp.backend.models.plugin import PluginConfig
class TestTemplateRudderstack(BaseHogFunctionTemplateTest):
diff --git a/posthog/cdp/templates/salesforce/test_template_salesforce.py b/posthog/cdp/templates/salesforce/test_template_salesforce.py
index f52b52f3d7ea..2e98a9325a27 100644
--- a/posthog/cdp/templates/salesforce/test_template_salesforce.py
+++ b/posthog/cdp/templates/salesforce/test_template_salesforce.py
@@ -6,7 +6,8 @@ from posthog.cdp.templates.salesforce.template_salesforce import (
template_create as template_salesforce_create,
template_update as template_salesforce_update,
)
-from posthog.models import PluginConfig
+
+from products.cdp.backend.models.plugin import PluginConfig
class TestTemplateSalesforceCreate(BaseHogFunctionTemplateTest):
diff --git a/posthog/cdp/templates/sendgrid/test_template_sendgrid.py b/posthog/cdp/templates/sendgrid/test_template_sendgrid.py
index 2eec17cbb752..67d60bca55a4 100644
--- a/posthog/cdp/templates/sendgrid/test_template_sendgrid.py
+++ b/posthog/cdp/templates/sendgrid/test_template_sendgrid.py
@@ -5,7 +5,8 @@ from posthog.cdp.templates.sendgrid.template_sendgrid import (
TemplateSendGridMigrator,
template as template_sendgrid,
)
-from posthog.models import PluginConfig
+
+from products.cdp.backend.models.plugin import PluginConfig
class TestTemplateSendgrid(BaseHogFunctionTemplateTest):
diff --git a/posthog/cdp/templates/test_cdp_templates.py b/posthog/cdp/templates/test_cdp_templates.py
index 89fb1e76cb39..73f4588bc172 100644
--- a/posthog/cdp/templates/test_cdp_templates.py
+++ b/posthog/cdp/templates/test_cdp_templates.py
@@ -5,8 +5,9 @@ from posthog.test.base import BaseTest
from posthog.cdp.templates import HOG_FUNCTION_TEMPLATES
from posthog.cdp.templates.hog_function_template import sync_template_to_db
from posthog.cdp.validation import InputsSchemaItemSerializer, compile_hog
-from posthog.models.hog_function_template import HogFunctionTemplate
-from posthog.models.hog_functions.hog_function import TYPES_WITH_TRANSPILED_FILTERS
+
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
+from products.cdp.backend.models.hog_functions.hog_function import TYPES_WITH_TRANSPILED_FILTERS
class TestTemplatesGeneral(BaseTest):
diff --git a/posthog/cdp/test/test_site_functions.py b/posthog/cdp/test/test_site_functions.py
index a75f88a5ac46..5434c3ab0ce2 100644
--- a/posthog/cdp/test/test_site_functions.py
+++ b/posthog/cdp/test/test_site_functions.py
@@ -13,14 +13,14 @@ from parameterized import parameterized
from posthog.cdp.site_functions import get_transpiled_function
from posthog.cdp.templates.helpers import mock_transpile
from posthog.models.cohort import Cohort
-from posthog.models.hog_functions.hog_function import HogFunction
from posthog.models.organization import Organization
-from posthog.models.plugin import TranspilerError
from posthog.models.project import Project
from posthog.models.user import User
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from products.actions.backend.models.action import Action
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.cdp.backend.models.plugin import TranspilerError
@pytest.mark.usefixtures("unittest_snapshot")
diff --git a/posthog/cdp/validation.py b/posthog/cdp/validation.py
index 39e56750b6c8..cd93a80617e1 100644
--- a/posthog/cdp/validation.py
+++ b/posthog/cdp/validation.py
@@ -13,7 +13,11 @@ from posthog.hogql.parser import parse_program, parse_string_template
from posthog.hogql.visitor import TraversingVisitor
from posthog.cdp.filters import compile_filters_bytecode, compile_filters_expr
-from posthog.models.hog_functions.hog_function import TYPES_WITH_JAVASCRIPT_SOURCE, TYPES_WITH_TRANSPILED_FILTERS
+
+from products.cdp.backend.models.hog_functions.hog_function import (
+ TYPES_WITH_JAVASCRIPT_SOURCE,
+ TYPES_WITH_TRANSPILED_FILTERS,
+)
from common.hogvm.python.stl import STL
from common.hogvm.python.stl.bytecode import BYTECODE_STL
diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.py
index 230aa3e14e35..e0483f97baff 100644
--- a/posthog/hogql/database/schema/test/test_system_tables.py
+++ b/posthog/hogql/database/schema/test/test_system_tables.py
@@ -22,8 +22,6 @@ from posthog.models import (
)
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.cohort.calculation_history import CohortCalculationHistory
-from posthog.models.hog_flow.hog_flow import HogFlow
-from posthog.models.hog_functions.hog_function import HogFunction
from posthog.models.project import Project
from products.actions.backend.models.action import Action
@@ -31,6 +29,7 @@ from products.ai_observability.backend.models.review_queues import ReviewQueue,
from products.ai_observability.backend.models.score_definitions import ScoreDefinition
from products.ai_observability.backend.models.trace_reviews import TraceReview, TraceReviewScore
from products.alerts.backend.models.alert import AlertConfiguration
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.conversations.backend.models import Ticket
from products.customer_analytics.backend.models.account import Account
from products.dashboards.backend.models.dashboard import Dashboard
@@ -51,6 +50,7 @@ from products.warehouse_sources.backend.models.external_data_job import External
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import DataWarehouseTable as DataWarehouseTableModel
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
ALL_SYSTEM_TABLE_NAMES = sorted(SystemTables().children.keys())
diff --git a/posthog/management/commands/backfill_hogflow_billable_action_types.py b/posthog/management/commands/backfill_hogflow_billable_action_types.py
index e9e883b59932..74da461a9ce0 100644
--- a/posthog/management/commands/backfill_hogflow_billable_action_types.py
+++ b/posthog/management/commands/backfill_hogflow_billable_action_types.py
@@ -5,7 +5,7 @@ from django.core.management.base import BaseCommand
from django.core.paginator import Paginator
from django.db import transaction
-from posthog.models.hog_flow.hog_flow import BILLABLE_ACTION_TYPES, HogFlow
+from products.workflows.backend.models.hog_flow.hog_flow import BILLABLE_ACTION_TYPES, HogFlow
logger = logging.getLogger(__name__)
diff --git a/posthog/management/commands/backfill_workflows_slack_integration.py b/posthog/management/commands/backfill_workflows_slack_integration.py
index 4f8ccc2f49a0..186d18b40497 100644
--- a/posthog/management/commands/backfill_workflows_slack_integration.py
+++ b/posthog/management/commands/backfill_workflows_slack_integration.py
@@ -6,7 +6,7 @@ from typing import Any
from django.core.management.base import BaseCommand
from django.db import transaction
-from posthog.models.hog_flow.hog_flow import HogFlow
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
logger = logging.getLogger(__name__)
diff --git a/posthog/management/commands/change_plugin_config_referenced_plugin.py b/posthog/management/commands/change_plugin_config_referenced_plugin.py
index e0302521905d..d68f3514a366 100644
--- a/posthog/management/commands/change_plugin_config_referenced_plugin.py
+++ b/posthog/management/commands/change_plugin_config_referenced_plugin.py
@@ -2,7 +2,7 @@ import time
from django.core.management.base import BaseCommand
-from posthog.models import Plugin, PluginConfig
+from products.cdp.backend.models.plugin import Plugin, PluginConfig
class Command(BaseCommand):
diff --git a/posthog/management/commands/change_plugin_private_access.py b/posthog/management/commands/change_plugin_private_access.py
index b5e3b9e7fda1..1300dca1bcb8 100644
--- a/posthog/management/commands/change_plugin_private_access.py
+++ b/posthog/management/commands/change_plugin_private_access.py
@@ -7,7 +7,8 @@ from django.core.management.base import BaseCommand
import structlog
from posthog.models import Organization
-from posthog.models.plugin import Plugin
+
+from products.cdp.backend.models.plugin import Plugin
logger = structlog.get_logger(__name__)
logger.setLevel(logging.INFO)
diff --git a/posthog/management/commands/migrate_hooks.py b/posthog/management/commands/migrate_hooks.py
index c0b0616ff23a..7ec9f5dc5827 100644
--- a/posthog/management/commands/migrate_hooks.py
+++ b/posthog/management/commands/migrate_hooks.py
@@ -1,18 +1,19 @@
from django.core.management.base import BaseCommand
from django.core.paginator import Paginator
-from posthog.models.hog_functions.hog_function import HogFunction
from posthog.plugins.plugin_server_api import reload_all_hog_functions_on_workers
from posthog.settings.ee import EE_AVAILABLE
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+
def migrate_hooks(hook_ids: list[str], team_ids: list[int], dry_run: bool = False):
if not EE_AVAILABLE:
print("This command is only available in PostHog EE") # noqa: T201
return
- from ee.api.hooks import create_zapier_hog_function
- from ee.models.hook import Hook
+ from products.cdp.backend.api.hooks import create_zapier_hog_function
+ from products.cdp.backend.models.hook import Hook
if hook_ids and team_ids:
print("Please provide either hook_ids or team_ids, not both") # noqa: T201
diff --git a/posthog/management/commands/refresh_hog_flows.py b/posthog/management/commands/refresh_hog_flows.py
index baf9fa1fe40a..fe1482cb6e88 100644
--- a/posthog/management/commands/refresh_hog_flows.py
+++ b/posthog/management/commands/refresh_hog_flows.py
@@ -6,8 +6,8 @@ from django.test import RequestFactory
import structlog
-from posthog.api.hog_flow import HogFlowSerializer
-from posthog.models.hog_flow.hog_flow import HogFlow
+from products.workflows.backend.api.hog_flow import HogFlowSerializer
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
logger = structlog.get_logger(__name__)
diff --git a/posthog/management/commands/refresh_hog_functions.py b/posthog/management/commands/refresh_hog_functions.py
index 396dee7ce1e6..e48f5f783145 100644
--- a/posthog/management/commands/refresh_hog_functions.py
+++ b/posthog/management/commands/refresh_hog_functions.py
@@ -5,7 +5,7 @@ from django.core.paginator import Paginator
import structlog
-from posthog.models.hog_functions.hog_function import HogFunction
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
logger = structlog.get_logger(__name__)
diff --git a/posthog/management/commands/resave_hog_functions.py b/posthog/management/commands/resave_hog_functions.py
index 4f0c40b80035..aa4449ca192f 100644
--- a/posthog/management/commands/resave_hog_functions.py
+++ b/posthog/management/commands/resave_hog_functions.py
@@ -1,7 +1,7 @@
from django.core.management.base import BaseCommand
from django.db import connection
-from posthog.models import HogFunction
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
class Command(BaseCommand):
diff --git a/posthog/management/commands/setup_dev.py b/posthog/management/commands/setup_dev.py
index e61cbdf4cc6f..c4f2a19da7c5 100644
--- a/posthog/management/commands/setup_dev.py
+++ b/posthog/management/commands/setup_dev.py
@@ -3,9 +3,10 @@ from django.db import transaction
from django.utils import timezone
from posthog.demo.legacy import ORGANIZATION_NAME, TEAM_NAME, create_demo_data
-from posthog.models import EventProperty, PersonalAPIKey, Plugin, PluginConfig, PluginSourceFile, Team, User
+from posthog.models import EventProperty, PersonalAPIKey, Team, User
from posthog.models.utils import hash_key_value
+from products.cdp.backend.models.plugin import Plugin, PluginConfig, PluginSourceFile
from products.event_definitions.backend.models.event_definition import EventDefinition
from products.event_definitions.backend.models.property_definition import PropertyDefinition
diff --git a/posthog/management/commands/sync_hog_function_templates.py b/posthog/management/commands/sync_hog_function_templates.py
index 6d6aa94b9dce..28704b0955aa 100644
--- a/posthog/management/commands/sync_hog_function_templates.py
+++ b/posthog/management/commands/sync_hog_function_templates.py
@@ -8,13 +8,14 @@ import structlog
from posthog.cdp.templates import HOG_FUNCTION_TEMPLATES
from posthog.cdp.templates.hog_function_template import sync_template_to_db
-from posthog.models.hog_function_template import HogFunctionTemplate
-from posthog.models.hog_functions.hog_function import HogFunctionType
from posthog.plugins.plugin_server_api import get_hog_function_templates
from posthog.temporal.data_imports.sources import SourceRegistry
from posthog.temporal.data_imports.sources.common.base import WebhookSource
from posthog.temporal.data_imports.sources.common.default_webhook_template import template as default_webhook_template
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
+from products.cdp.backend.models.hog_functions.hog_function import HogFunctionType
+
logger = structlog.get_logger(__name__)
TYPES_WITH_JAVASCRIPT_SOURCE = (HogFunctionType.SITE_DESTINATION, HogFunctionType.SITE_APP)
diff --git a/posthog/management/commands/test/test_backfill_workflows_slack_integration.py b/posthog/management/commands/test/test_backfill_workflows_slack_integration.py
index 4e8125a71e4c..d72cd186ebdf 100644
--- a/posthog/management/commands/test/test_backfill_workflows_slack_integration.py
+++ b/posthog/management/commands/test/test_backfill_workflows_slack_integration.py
@@ -6,7 +6,8 @@ from django.core.management import call_command
from posthog.management.commands import backfill_workflows_slack_integration as backfill
from posthog.management.commands.backfill_workflows_slack_integration import _rewrite_slack_workspace_in_actions
from posthog.models import Team
-from posthog.models.hog_flow.hog_flow import HogFlow
+
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
def _slack_action(action_id: str, slack_workspace_value: int | None) -> dict:
@@ -81,7 +82,7 @@ class TestBackfillWorkflowsSlackIntegrationCommand(BaseTest):
super().setUp()
self.other_team = Team.objects.create(organization=self.organization, name="Other team")
- with patch("posthog.models.hog_flow.hog_flow.reload_hog_flows_on_workers"):
+ with patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers"):
self.target_flow = HogFlow.objects.create(
team=self.team,
name="Target flow",
@@ -129,7 +130,7 @@ class TestBackfillWorkflowsSlackIntegrationCommand(BaseTest):
def test_rewrites_only_target_team(self):
with (
patch.object(backfill, "TEAM_ID", self.team.id),
- patch("posthog.models.hog_flow.hog_flow.reload_hog_flows_on_workers"),
+ patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers"),
):
call_command("backfill_workflows_slack_integration")
diff --git a/posthog/management/commands/test/test_migrate_hooks.py b/posthog/management/commands/test/test_migrate_hooks.py
index 890dbbac74ec..ef44484820dc 100644
--- a/posthog/management/commands/test/test_migrate_hooks.py
+++ b/posthog/management/commands/test/test_migrate_hooks.py
@@ -3,12 +3,12 @@ from posthog.test.base import BaseTest
from posthog.cdp.templates.hog_function_template import sync_template_to_db
from posthog.cdp.templates.zapier.template_zapier import template as template_zapier
from posthog.management.commands.migrate_hooks import migrate_hooks
-from posthog.models.hog_functions.hog_function import HogFunction
from products.actions.backend.models.action import Action
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.cdp.backend.models.hook import Hook
from common.hogvm.python.operation import HOGQL_BYTECODE_VERSION
-from ee.models.hook import Hook
class TestMigrateHooks(BaseTest):
diff --git a/posthog/management/commands/test/test_refresh_hog_flows.py b/posthog/management/commands/test/test_refresh_hog_flows.py
index 959de8ae2301..e8a7f9d9faf3 100644
--- a/posthog/management/commands/test/test_refresh_hog_flows.py
+++ b/posthog/management/commands/test/test_refresh_hog_flows.py
@@ -7,7 +7,8 @@ from django.core.management import call_command
from posthog.management.commands.refresh_hog_flows import remove_event_filters_from_conditionals
from posthog.models import Team
-from posthog.models.hog_flow.hog_flow import HogFlow
+
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
class TestRefreshHogFlows(BaseTest):
@@ -18,7 +19,7 @@ class TestRefreshHogFlows(BaseTest):
self.team2 = Team.objects.create(organization=self.organization, name="Test Team 2")
# Create HogFlows for testing with proper trigger actions
- with patch("posthog.models.hog_flow.hog_flow.reload_hog_flows_on_workers"):
+ with patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers"):
trigger_config_1 = {
"type": "event",
"filters": {
@@ -94,7 +95,7 @@ class TestRefreshHogFlows(BaseTest):
version=1,
)
- @patch("posthog.models.hog_flow.hog_flow.reload_hog_flows_on_workers")
+ @patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers")
def test_refresh_all_hog_flows(self, mock_reload):
"""Test refreshing all HogFlows across all teams."""
@@ -110,7 +111,7 @@ class TestRefreshHogFlows(BaseTest):
self.assertIn("Updated: 4", output)
self.assertIn("Errors: 0", output)
- @patch("posthog.models.hog_flow.hog_flow.reload_hog_flows_on_workers")
+ @patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers")
def test_refresh_by_team_id(self, mock_reload):
"""Test refreshing HogFlows for a specific team."""
@@ -125,7 +126,7 @@ class TestRefreshHogFlows(BaseTest):
self.assertIn("Found 3 HogFlows to process", output)
self.assertIn("Updated: 3", output)
- @patch("posthog.models.hog_flow.hog_flow.reload_hog_flows_on_workers")
+ @patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers")
def test_refresh_by_hog_flow_id(self, mock_reload):
"""Test refreshing a specific HogFlow by ID."""
@@ -140,7 +141,7 @@ class TestRefreshHogFlows(BaseTest):
self.assertIn("Found 1 HogFlows to process", output)
self.assertIn("Updated: 1", output)
- @patch("posthog.models.hog_flow.hog_flow.reload_hog_flows_on_workers")
+ @patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers")
def test_nonexistent_team_id(self, mock_reload):
"""Test handling of nonexistent team ID."""
@@ -153,7 +154,7 @@ class TestRefreshHogFlows(BaseTest):
self.assertIn("Found 0 HogFlows to process", output)
self.assertIn("No HogFlows found matching criteria", output)
- @patch("posthog.models.hog_flow.hog_flow.reload_hog_flows_on_workers")
+ @patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers")
def test_nonexistent_hog_flow_id(self, mock_reload):
"""Test handling of nonexistent HogFlow ID."""
@@ -168,7 +169,7 @@ class TestRefreshHogFlows(BaseTest):
self.assertIn("Found 0 HogFlows to process", output)
self.assertIn("No HogFlows found matching criteria", output)
- @patch("posthog.models.hog_flow.hog_flow.reload_hog_flows_on_workers")
+ @patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers")
def test_page_size_option(self, mock_reload):
"""Test that the page_size option works correctly."""
@@ -186,7 +187,7 @@ class TestRefreshHogFlows(BaseTest):
self.assertIn("Processed: 4", output)
self.assertIn("Updated: 4", output)
- @patch("posthog.models.hog_flow.hog_flow.reload_hog_flows_on_workers")
+ @patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers")
def test_error_handling(self, mock_reload):
"""Test error handling when a flow fails to save."""
@@ -217,7 +218,7 @@ class TestRefreshHogFlows(BaseTest):
self.assertIn("Errors: 1", output) # 1 failure
self.assertIn("Check logs for details on 1 errors encountered", output)
- @patch("posthog.models.hog_flow.hog_flow.reload_hog_flows_on_workers")
+ @patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers")
def test_bytecode_regeneration_on_conditional_branch(self, mock_reload):
"""Test that bytecode is regenerated when a conditional branch action is missing bytecode."""
diff --git a/posthog/management/commands/test/test_refresh_hog_functions.py b/posthog/management/commands/test/test_refresh_hog_functions.py
index 4b4e057c1778..9d7f070c99a6 100644
--- a/posthog/management/commands/test/test_refresh_hog_functions.py
+++ b/posthog/management/commands/test/test_refresh_hog_functions.py
@@ -6,7 +6,8 @@ from unittest.mock import patch
from django.core.management import call_command
from posthog.models import Team
-from posthog.models.hog_functions.hog_function import HogFunction
+
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
class TestRefreshHogFunctions(BaseTest):
@@ -17,7 +18,7 @@ class TestRefreshHogFunctions(BaseTest):
self.team2 = Team.objects.create(organization=self.organization, name="Test Team 2")
# Create HogFunctions for testing
- with patch("posthog.models.hog_functions.hog_function.reload_hog_functions_on_workers"):
+ with patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers"):
self.hog_function1 = HogFunction.objects.create(
team=self.team,
name="Test Function 1",
@@ -62,7 +63,7 @@ class TestRefreshHogFunctions(BaseTest):
deleted=True,
)
- @patch("posthog.models.hog_functions.hog_function.reload_hog_functions_on_workers")
+ @patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers")
def test_refresh_all_hog_functions(self, mock_reload):
"""Test refreshing all non-deleted destination HogFunctions (both enabled and disabled) across all teams."""
@@ -80,7 +81,7 @@ class TestRefreshHogFunctions(BaseTest):
self.assertIn("Updated: 3", output)
self.assertIn("Errors: 0", output)
- @patch("posthog.models.hog_functions.hog_function.reload_hog_functions_on_workers")
+ @patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers")
def test_refresh_by_team_id(self, mock_reload):
"""Test refreshing destination HogFunctions for a specific team."""
@@ -96,7 +97,7 @@ class TestRefreshHogFunctions(BaseTest):
self.assertIn("Found 2 HogFunctions to process", output)
self.assertIn("Updated: 2", output)
- @patch("posthog.models.hog_functions.hog_function.reload_hog_functions_on_workers")
+ @patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers")
def test_refresh_by_hog_function_id(self, mock_reload):
"""Test refreshing a specific HogFunction by ID."""
@@ -111,7 +112,7 @@ class TestRefreshHogFunctions(BaseTest):
self.assertIn("Found 1 HogFunctions to process", output)
self.assertIn("Updated: 1", output)
- @patch("posthog.models.hog_functions.hog_function.reload_hog_functions_on_workers")
+ @patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers")
def test_nonexistent_team_id(self, mock_reload):
"""Test handling of nonexistent team ID."""
@@ -124,7 +125,7 @@ class TestRefreshHogFunctions(BaseTest):
self.assertIn("Found 0 HogFunctions to process", output)
self.assertIn("No HogFunctions found matching criteria", output)
- @patch("posthog.models.hog_functions.hog_function.reload_hog_functions_on_workers")
+ @patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers")
def test_nonexistent_hog_function_id(self, mock_reload):
"""Test handling of nonexistent HogFunction ID."""
diff --git a/posthog/management/commands/test/test_resave_hog_functions.py b/posthog/management/commands/test/test_resave_hog_functions.py
index c42e81cd2c89..d6146dbf6051 100644
--- a/posthog/management/commands/test/test_resave_hog_functions.py
+++ b/posthog/management/commands/test/test_resave_hog_functions.py
@@ -3,9 +3,10 @@ from unittest.mock import call, patch
from django.core.management import call_command
-from posthog.models.hog_functions.hog_function import HogFunction
from posthog.models.integration import Integration
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+
class TestResaveHogFunctions(BaseTest):
def setUp(self):
@@ -24,7 +25,7 @@ class TestResaveHogFunctions(BaseTest):
)
# Create two HogFunctions that use different integrations
- with patch("posthog.models.hog_functions.hog_function.reload_hog_functions_on_workers"):
+ with patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers"):
self.hog_function1 = HogFunction.objects.create(
team=self.team,
name="Test Function 1",
@@ -47,7 +48,7 @@ class TestResaveHogFunctions(BaseTest):
inputs={"integration": {"value": str(self.integration2.id)}},
)
- @patch("posthog.models.hog_functions.hog_function.reload_hog_functions_on_workers")
+ @patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers")
def test_resave_hog_functions(self, mock_reload):
"""Test that the command correctly identifies and resaves HogFunctions connected to integrations."""
@@ -62,12 +63,12 @@ class TestResaveHogFunctions(BaseTest):
)
assert mock_reload.call_count == 2
- @patch("posthog.models.hog_functions.hog_function.reload_hog_functions_on_workers")
+ @patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers")
def test_only_resaves_enabled_non_deleted_functions(self, mock_reload):
"""Test that the command only resaves enabled and non-deleted functions."""
# Create a disabled function
- with patch("posthog.models.hog_functions.hog_function.reload_hog_functions_on_workers"):
+ with patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers"):
HogFunction.objects.create(
team=self.team,
name="Disabled Function",
diff --git a/posthog/management/commands/test/test_sync_hog_function_templates.py b/posthog/management/commands/test/test_sync_hog_function_templates.py
index 1c52c84b5746..c8cbe8d787f4 100644
--- a/posthog/management/commands/test/test_sync_hog_function_templates.py
+++ b/posthog/management/commands/test/test_sync_hog_function_templates.py
@@ -9,7 +9,8 @@ from posthog.management.commands.sync_hog_function_templates import (
TEST_INCLUDE_PYTHON_TEMPLATE_IDS,
TYPES_WITH_JAVASCRIPT_SOURCE,
)
-from posthog.models.hog_function_template import HogFunctionTemplate
+
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
pytestmark = pytest.mark.django_db
diff --git a/posthog/management/commands/test/test_update_hog_function_code.py b/posthog/management/commands/test/test_update_hog_function_code.py
index 240f0bdd4b53..12aa9c3aa763 100644
--- a/posthog/management/commands/test/test_update_hog_function_code.py
+++ b/posthog/management/commands/test/test_update_hog_function_code.py
@@ -5,7 +5,7 @@ from unittest.mock import patch
from django.core.management import call_command
-from posthog.models.hog_functions.hog_function import HogFunction
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
class TestUpdateHogFunctionCode(BaseTest):
@@ -13,7 +13,7 @@ class TestUpdateHogFunctionCode(BaseTest):
super().setUp()
# Create HogFunctions for testing
- with patch("posthog.models.hog_functions.hog_function.reload_hog_functions_on_workers"):
+ with patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers"):
# LinkedIn destination with old API version
self.linkedin_function1 = HogFunction.objects.create(
team=self.team,
diff --git a/posthog/management/commands/update_hog_function_code.py b/posthog/management/commands/update_hog_function_code.py
index dd7e84196176..bafc77f0b06f 100644
--- a/posthog/management/commands/update_hog_function_code.py
+++ b/posthog/management/commands/update_hog_function_code.py
@@ -6,7 +6,8 @@ from django.core.paginator import Paginator
import structlog
from posthog.cdp.validation import compile_hog
-from posthog.models.hog_functions.hog_function import HogFunction
+
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
logger = structlog.get_logger(__name__)
diff --git a/posthog/migrations/1187_migrate_hog_flow_models.py b/posthog/migrations/1187_migrate_hog_flow_models.py
new file mode 100644
index 000000000000..d6e2c47bb99d
--- /dev/null
+++ b/posthog/migrations/1187_migrate_hog_flow_models.py
@@ -0,0 +1,67 @@
+from django.db import migrations
+
+MODELS_TO_MOVE = ("hogflow", "hogflowtemplate")
+
+
+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", "workflows")
+
+
+def reverse_content_types(apps, schema_editor):
+ _move_content_types(apps, schema_editor, "workflows", "posthog")
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1186_activitylog_ip_address"),
+ ("workflows", "0007_migrate_hog_flow_models"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.RemoveField(
+ model_name="hogflow",
+ name="created_by",
+ ),
+ migrations.RemoveField(
+ model_name="hogflow",
+ name="team",
+ ),
+ migrations.RemoveField(
+ model_name="hogflowtemplate",
+ name="created_by",
+ ),
+ migrations.RemoveField(
+ model_name="hogflowtemplate",
+ name="team",
+ ),
+ migrations.DeleteModel(
+ name="HogFlow",
+ ),
+ migrations.DeleteModel(
+ name="HogFlowTemplate",
+ ),
+ ],
+ database_operations=[],
+ ),
+ migrations.RunPython(update_content_types, reverse_content_types),
+ ]
diff --git a/posthog/migrations/1188_migrate_cdp_models.py b/posthog/migrations/1188_migrate_cdp_models.py
new file mode 100644
index 000000000000..cf6bba1b2a95
--- /dev/null
+++ b/posthog/migrations/1188_migrate_cdp_models.py
@@ -0,0 +1,126 @@
+from django.db import migrations
+
+MODELS_TO_MOVE = (
+ "hogfunction",
+ "hogfunctiontemplate",
+ "plugin",
+ "pluginattachment",
+ "pluginconfig",
+ "pluginsourcefile",
+ "pluginstorage",
+)
+
+
+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", "cdp")
+
+
+def reverse_content_types(apps, schema_editor):
+ _move_content_types(apps, schema_editor, "cdp", "posthog")
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1187_migrate_hog_flow_models"),
+ ("cdp", "0001_migrate_cdp_models"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.RemoveField(
+ model_name="hogfunction",
+ name="batch_export",
+ ),
+ migrations.RemoveField(
+ model_name="hogfunction",
+ name="created_by",
+ ),
+ migrations.RemoveField(
+ model_name="hogfunction",
+ name="hog_function_template",
+ ),
+ migrations.RemoveField(
+ model_name="hogfunction",
+ name="team",
+ ),
+ migrations.RemoveField(
+ model_name="plugin",
+ name="has_private_access",
+ ),
+ migrations.RemoveField(
+ model_name="plugin",
+ name="organization",
+ ),
+ migrations.RemoveField(
+ model_name="pluginsourcefile",
+ name="plugin",
+ ),
+ migrations.RemoveField(
+ model_name="pluginconfig",
+ name="plugin",
+ ),
+ migrations.RemoveField(
+ model_name="pluginattachment",
+ name="plugin_config",
+ ),
+ migrations.RemoveField(
+ model_name="pluginattachment",
+ name="team",
+ ),
+ migrations.RemoveField(
+ model_name="pluginconfig",
+ name="match_action",
+ ),
+ migrations.RemoveField(
+ model_name="pluginconfig",
+ name="team",
+ ),
+ migrations.RemoveField(
+ model_name="pluginstorage",
+ name="plugin_config",
+ ),
+ migrations.DeleteModel(
+ name="HogFunctionTemplate",
+ ),
+ migrations.DeleteModel(
+ name="HogFunction",
+ ),
+ migrations.DeleteModel(
+ name="PluginSourceFile",
+ ),
+ migrations.DeleteModel(
+ name="Plugin",
+ ),
+ migrations.DeleteModel(
+ name="PluginAttachment",
+ ),
+ migrations.DeleteModel(
+ name="PluginConfig",
+ ),
+ migrations.DeleteModel(
+ name="PluginStorage",
+ ),
+ ],
+ database_operations=[],
+ ),
+ migrations.RunPython(update_content_types, reverse_content_types),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 555d8b7f07cf..61a3593fc9a4 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1186_activitylog_ip_address
+1188_migrate_cdp_models
diff --git a/posthog/models/__init__.py b/posthog/models/__init__.py
index 01e9ed934e15..68e07e615b69 100644
--- a/posthog/models/__init__.py
+++ b/posthog/models/__init__.py
@@ -46,9 +46,6 @@ from .group import Group
from .group_usage_metric import GroupUsageMetric
from .group_type_mapping import GroupTypeMapping
from .host_definition import HostDefinition
-from .hog_flow import HogFlow
-from .hog_functions import HogFunction
-from .hog_function_template import HogFunctionTemplate
from .health_issue import HealthIssue
from .instance_setting import InstanceSetting
from .integration import Integration
@@ -64,7 +61,6 @@ from .organization_invite import OrganizationInvite, InviteExpiredException
from .person import Person, PersonDistinctId, PersonOverride, PersonOverrideMapping
from .personal_api_key import PersonalAPIKey
from .project_secret_api_key import ProjectSecretAPIKey
-from .plugin import Plugin, PluginAttachment, PluginConfig, PluginLogEntry, PluginSourceFile
from .product_intent import ProductIntent
from .project import Project
from .property import Property
@@ -149,9 +145,6 @@ __all__ = [
"GroupUsageMetric",
"GroupTypeMapping",
"HealthIssue",
- "HogFlow",
- "HogFunction",
- "HogFunctionTemplate",
"LLMPrompt",
"HostDefinition",
"InstanceSetting",
@@ -181,11 +174,6 @@ __all__ = [
"ProjectSecretAPIKey",
"PersonOverride",
"PersonOverrideMapping",
- "Plugin",
- "PluginAttachment",
- "PluginConfig",
- "PluginLogEntry",
- "PluginSourceFile",
"ProductIntent",
"Project",
"Property",
diff --git a/posthog/models/file_system/unfiled_file_saver.py b/posthog/models/file_system/unfiled_file_saver.py
index 845386d28ec8..e827b98ad0d3 100644
--- a/posthog/models/file_system/unfiled_file_saver.py
+++ b/posthog/models/file_system/unfiled_file_saver.py
@@ -7,12 +7,12 @@ from django.utils import timezone
from posthog.models.cohort import Cohort
from posthog.models.file_system.file_system import FileSystem, escape_path, split_path
from posthog.models.file_system.file_system_mixin import FileSystemSyncMixin
-from posthog.models.hog_functions.hog_function import HogFunction
from posthog.models.team import Team
from posthog.models.user import User
from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
from products.actions.backend.models.action import Action
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.dashboards.backend.models.dashboard import Dashboard
from products.early_access_features.backend.models import EarlyAccessFeature
from products.experiments.backend.models.experiment import Experiment
diff --git a/posthog/models/hog_functions/__init__.py b/posthog/models/hog_functions/__init__.py
deleted file mode 100644
index 26498ac92250..000000000000
--- a/posthog/models/hog_functions/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from .hog_function import HogFunction
-
-__all__ = ["HogFunction"]
diff --git a/posthog/models/product_intent/product_intent.py b/posthog/models/product_intent/product_intent.py
index acab275e93e8..5f9f6bca284b 100644
--- a/posthog/models/product_intent/product_intent.py
+++ b/posthog/models/product_intent/product_intent.py
@@ -13,7 +13,6 @@ from rest_framework import serializers
from posthog.schema import ProductIntentContext, ProductKey
from posthog.exceptions_capture import capture_exception
-from posthog.models.hog_flow.hog_flow import HogFlow
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.models.utils import RootTeamMixin, UUIDTModel
@@ -29,6 +28,7 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.product_analytics.backend.models.insight import Insight
from products.product_tours.backend.models import ProductTour
from products.surveys.backend.models import Survey
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
logger = structlog.get_logger(__name__)
diff --git a/posthog/models/remote_config.py b/posthog/models/remote_config.py
index ea6ed598652c..5645a89eaf46 100644
--- a/posthog/models/remote_config.py
+++ b/posthog/models/remote_config.py
@@ -15,15 +15,15 @@ from prometheus_client import Counter
from posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIAS
from posthog.database_healthcheck import DATABASE_FOR_FLAG_MATCHING
from posthog.exceptions_capture import capture_exception
-from posthog.models.hog_functions.hog_function import HogFunction
from posthog.models.js_snippet_versioning import DEFAULT_SNIPPET_VERSION
-from posthog.models.plugin import PluginConfig
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.team.js_snippet_config import TeamJsSnippetConfig
from posthog.models.team.team import Team
from posthog.models.utils import UUIDTModel, execute_with_timeout
from posthog.storage.hypercache import HyperCache, HyperCacheStoreMissing
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.cdp.backend.models.plugin import PluginConfig
from products.error_tracking.backend.models import ErrorTrackingSuppressionRule
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.product_tours.backend.models import ProductTour
@@ -342,9 +342,10 @@ class RemoteConfig(UUIDTModel):
# NOTE: This is the web focused config for the frontend that includes site apps
from posthog.cdp.site_functions import get_transpiled_function
- from posthog.models import HogFunction
from posthog.plugins.site import get_site_apps_for_team, get_site_config_from_schema
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+
# Add in the site apps as an array of objects
site_apps_js = []
for site_app in get_site_apps_for_team(self.team.id):
diff --git a/posthog/models/test/test_async_deletion_model.py b/posthog/models/test/test_async_deletion_model.py
index 4e62ff416c95..636a3eb49152 100644
--- a/posthog/models/test/test_async_deletion_model.py
+++ b/posthog/models/test/test_async_deletion_model.py
@@ -17,9 +17,10 @@ from posthog.models.async_deletion.delete_events import AsyncEventDeletion
from posthog.models.cohort.util import insert_static_cohort
from posthog.models.group.util import create_group
from posthog.models.person.util import create_person, create_person_distinct_id
-from posthog.models.plugin import PluginLogEntrySource, PluginLogEntryType
from posthog.test.test_plugin_log_entry import create_plugin_log_entry
+from products.cdp.backend.models.plugin import PluginLogEntrySource, PluginLogEntryType
+
uuid = str(UUID("6ba7b810-9dad-11d1-80b4-00c04fd430c8"))
uuid2 = str(UUID("7ba7b810-9dad-11d1-80b4-00c04fd430c8"))
diff --git a/posthog/models/test/test_hog_flow_batch_job.py b/posthog/models/test/test_hog_flow_batch_job.py
index cb3b5cdff1e4..259c00c83424 100644
--- a/posthog/models/test/test_hog_flow_batch_job.py
+++ b/posthog/models/test/test_hog_flow_batch_job.py
@@ -2,9 +2,9 @@ from unittest.mock import patch
from django.test import TestCase
-from posthog.models.hog_flow.hog_flow import HogFlow
from posthog.models.user import User
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJob
diff --git a/posthog/models/test/test_hog_function.py b/posthog/models/test/test_hog_function.py
index 92c04063d4c6..0dfaf7775810 100644
--- a/posthog/models/test/test_hog_function.py
+++ b/posthog/models/test/test_hog_function.py
@@ -8,12 +8,12 @@ from django.test import TestCase
from posthog.models.cohort import Cohort
from posthog.models.file_system.file_system import FileSystem
-from posthog.models.hog_functions.hog_function import HogFunction, HogFunctionType
from posthog.models.team.team import Team
from posthog.models.user import User
-from posthog.tasks.hog_functions import refresh_affected_hog_functions
from products.actions.backend.models.action import Action
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType
+from products.cdp.backend.tasks.hog_functions import refresh_affected_hog_functions
from common.hogvm.python.operation import HOGQL_BYTECODE_VERSION
@@ -317,7 +317,7 @@ class TestHogFunctionsBackgroundReloading(TestCase, QueryMatchingTest):
self.team.test_account_filters = [{"type": "cohort", "key": "id", "value": cohort.id}]
self.team.save()
- with patch("posthog.tasks.hog_functions.refresh_affected_hog_functions.delay") as mock_delay:
+ with patch("products.cdp.backend.tasks.hog_functions.refresh_affected_hog_functions.delay") as mock_delay:
cohort.name = "Updated name"
cohort.save()
mock_delay.assert_any_call(cohort_id=cohort.id)
@@ -339,7 +339,7 @@ class TestHogFunctionsBackgroundReloading(TestCase, QueryMatchingTest):
]
self.team.save()
- with patch("posthog.tasks.hog_functions.refresh_affected_hog_functions.delay") as mock_delay:
+ with patch("products.cdp.backend.tasks.hog_functions.refresh_affected_hog_functions.delay") as mock_delay:
cohort.name = "Updated name"
cohort.save()
mock_delay.assert_not_called()
@@ -359,7 +359,7 @@ class TestHogFunctionsBackgroundReloading(TestCase, QueryMatchingTest):
self.team.test_account_filters = [{"type": "cohort", "key": "id", "value": cohort.id + 9999}]
self.team.save()
- with patch("posthog.tasks.hog_functions.refresh_affected_hog_functions.delay") as mock_delay:
+ with patch("products.cdp.backend.tasks.hog_functions.refresh_affected_hog_functions.delay") as mock_delay:
cohort.name = "Updated name"
cohort.save()
mock_delay.assert_not_called()
diff --git a/posthog/models/test/test_hog_function_template.py b/posthog/models/test/test_hog_function_template.py
index 0968f402a053..e92a60b1f724 100644
--- a/posthog/models/test/test_hog_function_template.py
+++ b/posthog/models/test/test_hog_function_template.py
@@ -2,7 +2,8 @@ from django.test import TestCase
from posthog.cdp.templates.hog_function_template import sync_template_to_db
from posthog.cdp.templates.slack.template_slack import template as slack_template
-from posthog.models.hog_function_template import HogFunctionTemplate
+
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
class TestHogFunctionTemplate(TestCase):
diff --git a/posthog/models/test/test_organization_model.py b/posthog/models/test/test_organization_model.py
index f1b89ecf9ecd..e84d00d61e9c 100644
--- a/posthog/models/test/test_organization_model.py
+++ b/posthog/models/test/test_organization_model.py
@@ -9,11 +9,13 @@ from django.utils import timezone
from parameterized import parameterized
-from posthog.models import Organization, OrganizationInvite, Plugin
+from posthog.models import Organization, OrganizationInvite
from posthog.models.organization import OrganizationMembership
from posthog.plugins.test.mock import mocked_plugin_requests_get
from posthog.plugins.test.plugin_archives import HELLO_WORLD_PLUGIN_GITHUB_ZIP
+from products.cdp.backend.models.plugin import Plugin
+
from ee.billing.quota_limiting import QuotaResource
diff --git a/posthog/models/test/test_product_intent.py b/posthog/models/test/test_product_intent.py
index 37046b59d022..5cc2438b900b 100644
--- a/posthog/models/test/test_product_intent.py
+++ b/posthog/models/test/test_product_intent.py
@@ -12,7 +12,6 @@ from parameterized import parameterized
from posthog.schema import ProductIntentContext, ProductKey
from posthog.models.file_system.user_product_list import UserProductList
-from posthog.models.hog_flow.hog_flow import HogFlow
from posthog.models.product_intent.product_intent import (
ProductIntent,
_fetch_product_intents,
@@ -31,6 +30,7 @@ from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.product_analytics.backend.models.insight import Insight
from products.surveys.backend.models import Survey
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
class TestProductIntent(BaseTest):
diff --git a/posthog/plugins/site.py b/posthog/plugins/site.py
index a2904b985667..889433a22076 100644
--- a/posthog/plugins/site.py
+++ b/posthog/plugins/site.py
@@ -33,7 +33,7 @@ def get_site_config_from_schema(config_schema: Optional[list[dict]], config: Opt
def get_transpiled_site_source(id: int, token: str) -> Optional[WebJsSource]:
- from posthog.models import PluginConfig, PluginSourceFile
+ from products.cdp.backend.models.plugin import PluginConfig, PluginSourceFile
response = (
# nosemgrep: idor-lookup-without-team (token-based auth; web_token acts as secret access key)
@@ -61,7 +61,7 @@ def get_transpiled_site_source(id: int, token: str) -> Optional[WebJsSource]:
def get_site_apps_for_team(team_id: int) -> list[WebJsSource]:
- from posthog.models import PluginConfig, PluginSourceFile
+ from products.cdp.backend.models.plugin import PluginConfig, PluginSourceFile
rows = (
PluginConfig.objects.filter(
@@ -89,7 +89,7 @@ def get_site_apps_for_team(team_id: int) -> list[WebJsSource]:
def get_decide_site_apps(team: "Team", using_database: str = "default") -> list[dict]:
- from posthog.models import PluginConfig, PluginSourceFile
+ from products.cdp.backend.models.plugin import PluginConfig, PluginSourceFile
sources = (
PluginConfig.objects.db_manager(using_database)
@@ -119,7 +119,7 @@ def get_decide_site_apps(team: "Team", using_database: str = "default") -> list[
def get_decide_site_functions(team: "Team", using_database: str = "default") -> list[dict]:
- from posthog.models import HogFunction
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
sources = (
HogFunction.objects.db_manager(using_database)
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index deac9d329e7f..d4f6602df4cc 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -55,6 +55,7 @@ PRODUCTS_APPS = [
"products.slack_app.backend.apps.SlackAppConfig",
"products.product_tours.backend.apps.ProductToursConfig",
"products.workflows.backend.apps.WorkflowsConfig",
+ "products.cdp.backend.apps.CdpConfig",
"products.posthog_ai.backend.apps.PosthogAiConfig",
"products.signals.backend.apps.SignalsConfig",
"products.visual_review.backend.apps.VisualReviewConfig",
@@ -460,7 +461,7 @@ SPECTACULAR_SETTINGS = {
"ExperimentMetricKindEnum": "products.ai_observability.backend.models.score_definitions.ScoreDefinition.Kind",
"IntegrationKindEnum": "posthog.models.integration.Integration.IntegrationKind",
"LLMProviderEnum": "products.ai_observability.backend.models.provider_keys.LLMProvider",
- "HogFlowStatusEnum": "posthog.models.hog_flow.hog_flow.HogFlow.State",
+ "HogFlowStatusEnum": "products.workflows.backend.models.hog_flow.hog_flow.HogFlow.State",
"MCPAuthTypeEnum": "products.mcp_store.backend.models.AUTH_TYPE_CHOICES",
"TaskRunStatusEnum": "products.tasks.backend.models.TaskRun.Status",
"TaskRunEnvironmentEnum": "products.tasks.backend.models.TaskRun.Environment",
diff --git a/posthog/tasks/__init__.py b/posthog/tasks/__init__.py
index 72028afcbecc..7969738898d8 100644
--- a/posthog/tasks/__init__.py
+++ b/posthog/tasks/__init__.py
@@ -10,8 +10,6 @@ from . import (
email,
exporter,
health_checks,
- hog_flows,
- hog_functions,
integrations,
llm_prompt_cache,
plugin_server,
@@ -39,8 +37,6 @@ __all__ = [
"email",
"exporter",
"health_checks",
- "hog_flows",
- "hog_functions",
"integrations",
"llm_prompt_cache",
"plugin_server",
diff --git a/posthog/tasks/email.py b/posthog/tasks/email.py
index 61254ebd4e74..8377ba1f47f4 100644
--- a/posthog/tasks/email.py
+++ b/posthog/tasks/email.py
@@ -22,26 +22,18 @@ from posthog.email import EMAIL_TASK_KWARGS, EmailMessage, is_email_available
from posthog.event_usage import groups
from posthog.geoip import get_geoip_properties
from posthog.helpers.email_utils import sanitize_display_name, sanitize_message_body
-from posthog.models import (
- Organization,
- OrganizationInvite,
- OrganizationMembership,
- PersonalAPIKey,
- Plugin,
- PluginConfig,
- Team,
- User,
-)
+from posthog.models import Organization, OrganizationInvite, OrganizationMembership, PersonalAPIKey, Team, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.comment import Comment
from posthog.models.comment.utils import build_comment_item_url
-from posthog.models.hog_functions.hog_function import HogFunction
from posthog.models.messaging import MessagingRecord, get_email_hash
from posthog.models.utils import UUIDT
from posthog.ph_client import get_client
from posthog.scoping_audit import skip_team_scope_audit
from posthog.user_permissions import UserPermissions
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.cdp.backend.models.plugin import Plugin, PluginConfig
from products.conversations.backend.models import Ticket
from products.error_tracking.backend.facade import api as error_tracking_api
@@ -1314,7 +1306,8 @@ def send_team_hog_functions_digest(team_id: int, hog_function_ids: list[str] | N
"""
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
- from posthog.models.hog_functions.hog_function import HogFunction
+
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
logger.info(f"Processing HogFunctions digest for team {team_id}")
diff --git a/posthog/tasks/plugin_server.py b/posthog/tasks/plugin_server.py
index 522b7bd89184..b7109c2d6340 100644
--- a/posthog/tasks/plugin_server.py
+++ b/posthog/tasks/plugin_server.py
@@ -3,10 +3,10 @@ from typing import Optional
from celery import shared_task
from structlog import get_logger
-from posthog.models import PluginConfig
from posthog.tasks.email import get_members_to_notify_for_pipeline_error, send_fatal_plugin_error
from posthog.tasks.utils import CeleryQueue
+from products.cdp.backend.models.plugin import PluginConfig
from products.notifications.backend.facade.api import (
NotificationData,
NotificationType,
@@ -104,7 +104,7 @@ def fatal_plugin_error(
def hog_function_state_transition(hog_function_id: str, state: int) -> None:
logger.info("hog_function_state_transition (disabled)", hog_function_id=hog_function_id, state=state)
return
- # from posthog.models.hog_functions.hog_function import HogFunction
+ # from products.cdp.backend.models.hog_functions.hog_function import HogFunction
# logger.info("hog_function_state_transition", hog_function_id=hog_function_id, state=state)
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index 7089c7a4d4ae..48287e9ac13b 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -59,9 +59,6 @@
'posthog.tasks.email.send_two_factor_reset_email',
'posthog.tasks.exporter.export_asset',
'posthog.tasks.health_checks.evaluate_health_check_for_team',
- 'posthog.tasks.hog_flows.refresh_affected_hog_flows',
- 'posthog.tasks.hog_functions.refresh_affected_hog_functions',
- 'posthog.tasks.hog_functions.sync_hog_function_templates_task',
'posthog.tasks.hypercache_verification.verify_and_fix_flag_definitions_cache_task',
'posthog.tasks.hypercache_verification.verify_and_fix_flag_definitions_without_cohorts_cache_task',
'posthog.tasks.hypercache_verification.verify_and_fix_flags_cache_task',
diff --git a/posthog/tasks/test/test_calculate_cohort.py b/posthog/tasks/test/test_calculate_cohort.py
index 5f5365f59cd8..c19a4ad90794 100644
--- a/posthog/tasks/test/test_calculate_cohort.py
+++ b/posthog/tasks/test/test_calculate_cohort.py
@@ -1107,7 +1107,7 @@ class TestCohortCalculationTasks(APIBaseTest):
with (
patch("posthog.models.cohort.dependencies._on_cohort_changed") as mock_dep_cache,
patch("products.feature_flags.backend.tasks.update_team_flags_cache") as mock_flags_cache,
- patch("posthog.tasks.hog_functions.refresh_affected_hog_functions") as mock_hog_refresh,
+ patch("products.cdp.backend.tasks.hog_functions.refresh_affected_hog_functions") as mock_hog_refresh,
):
cohort._safe_save_cohort_state(team_id=self.team.pk, processing_error=None)
diff --git a/posthog/tasks/test/test_email.py b/posthog/tasks/test/test_email.py
index cf03ee0c0664..dbdba80c10f1 100644
--- a/posthog/tasks/test/test_email.py
+++ b/posthog/tasks/test/test_email.py
@@ -15,11 +15,9 @@ from posthog.api.email_verification import email_verification_token_generator
from posthog.batch_exports.models import BatchExport, BatchExportDestination, BatchExportRun
from posthog.models import Organization, Team, User
from posthog.models.app_metrics2.sql import TRUNCATE_APP_METRICS2_TABLE_SQL
-from posthog.models.hog_functions.hog_function import HogFunction
from posthog.models.instance_setting import set_instance_setting
from posthog.models.organization import OrganizationMembership
from posthog.models.organization_invite import OrganizationInvite
-from posthog.models.plugin import Plugin, PluginConfig
from posthog.tasks.email import (
get_members_to_notify_for_pipeline_error,
login_from_new_device_notification,
@@ -44,6 +42,9 @@ from posthog.tasks.email import (
)
from posthog.tasks.test.utils_email_tests import mock_email_messages
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.cdp.backend.models.plugin import Plugin, PluginConfig
+
def create_org_team_and_user(creation_date: str, email: str, ingested_event: bool = False) -> tuple[Organization, User]:
with freeze_time(creation_date):
diff --git a/posthog/tasks/test/test_plugin_server.py b/posthog/tasks/test/test_plugin_server.py
index 0dcbc67bc206..84c4282c0cb8 100644
--- a/posthog/tasks/test/test_plugin_server.py
+++ b/posthog/tasks/test/test_plugin_server.py
@@ -2,9 +2,10 @@ from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from posthog.models import OrganizationMembership
-from posthog.models.plugin import Plugin, PluginConfig
from posthog.tasks.plugin_server import _dispatch_plugin_disabled_realtime
+from products.cdp.backend.models.plugin import Plugin, PluginConfig
+
class TestDispatchPluginDisabledRealtime(BaseTest):
@patch("posthog.tasks.plugin_server.create_notification")
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index 0b6c3f878ed0..1099f335c608 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -38,11 +38,10 @@ from posthog.clickhouse.client.connection import ClickHouseUser
from posthog.clickhouse.query_tagging import tag_queries
from posthog.cloud_utils import TEST_clear_instance_license_cache
from posthog.hogql_queries.events_query_runner import EventsQueryRunner
-from posthog.models import Organization, Plugin, Team
+from posthog.models import Organization, Team
from posthog.models.app_metrics2.sql import TRUNCATE_APP_METRICS2_TABLE_SQL
from posthog.models.event.util import create_event
from posthog.models.group.util import create_group
-from posthog.models.plugin import PluginConfig
from posthog.models.sharing_configuration import SharingConfiguration
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
from posthog.tasks.usage_report import (
@@ -62,6 +61,7 @@ from posthog.test.fixtures import create_app_metric2
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from posthog.utils import get_previous_day
+from products.cdp.backend.models.plugin import Plugin, PluginConfig
from products.dashboards.backend.models.dashboard import Dashboard
from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
from products.data_warehouse.backend.types import ExternalDataSourceType
@@ -1457,7 +1457,7 @@ class TestFeatureFlagsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickh
def test_active_hog_destinations_and_transformations_per_team(
self, billing_task_mock: MagicMock, posthog_capture_mock: MagicMock
) -> None:
- from posthog.models.hog_functions.hog_function import HogFunction, HogFunctionType
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType
self._setup_teams()
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index 294c935b1dc6..ff208c0eb34d 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -34,9 +34,7 @@ from posthog.constants import FlagRequestType
from posthog.exceptions_capture import capture_exception
from posthog.logging.timing import timed_log
from posthog.models import BatchExport, GroupTypeMapping, OrganizationMembership, User
-from posthog.models.hog_functions.hog_function import HogFunction, HogFunctionType
from posthog.models.organization import Organization
-from posthog.models.plugin import PluginConfig
from posthog.models.property.util import get_property_string_expr
from posthog.models.team.team import Team
from posthog.models.utils import namedtuplefetchall
@@ -46,6 +44,8 @@ from posthog.tasks.report_utils import capture_event
from posthog.tasks.utils import CeleryQueue
from posthog.utils import get_helm_info_env, get_instance_realm, get_instance_region, get_previous_day
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType
+from products.cdp.backend.models.plugin import PluginConfig
from products.dashboards.backend.models.dashboard import Dashboard
from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
from products.error_tracking.backend.facade import api as error_tracking_api
diff --git a/posthog/temporal/data_imports/pipelines/pipeline/cdp_producer.py b/posthog/temporal/data_imports/pipelines/pipeline/cdp_producer.py
index 27519d7e0c01..d8581013c157 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline/cdp_producer.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline/cdp_producer.py
@@ -15,10 +15,10 @@ from posthog.hogql.database.database import get_data_warehouse_table_name
from posthog.exceptions_capture import capture_exception
from posthog.kafka_client.routing import KafkaClusterProfile, async_producer_scope
from posthog.kafka_client.topics import KAFKA_DWH_CDP_RAW_TABLE
-from posthog.models.hog_functions import HogFunction
from posthog.sync import database_sync_to_async_pool
from posthog.temporal.data_imports.pipelines.helpers import build_table_name
+from products.cdp.backend.models.hog_functions import HogFunction
from products.data_warehouse.backend.s3 import aget_s3_client, ensure_bucket_exists
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
diff --git a/posthog/temporal/data_imports/pipelines/pipeline/test/test_cdp_producer.py b/posthog/temporal/data_imports/pipelines/pipeline/test/test_cdp_producer.py
index 6fecfe57b1f1..9b87cdb38250 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline/test/test_cdp_producer.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline/test/test_cdp_producer.py
@@ -10,9 +10,9 @@ import pyarrow as pa
import pyarrow.parquet as pq
from asgiref.sync import sync_to_async
-from posthog.models.hog_functions.hog_function import HogFunction
from posthog.temporal.data_imports.pipelines.pipeline.cdp_producer import CDPProducer
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.data_warehouse.backend.types import ExternalDataSourceType
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
diff --git a/posthog/temporal/data_imports/sources/common/webhook_s3.py b/posthog/temporal/data_imports/sources/common/webhook_s3.py
index 03068cc8fa60..757cb61c65e3 100644
--- a/posthog/temporal/data_imports/sources/common/webhook_s3.py
+++ b/posthog/temporal/data_imports/sources/common/webhook_s3.py
@@ -67,8 +67,7 @@ class WebhookSourceManager:
return s3_path.replace("s3://", "")
async def webhook_enabled(self, skip_initial_sync_complete_check: bool = False) -> bool:
- from posthog.models.hog_functions.hog_function import HogFunction
-
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
flag_enabled = await self._is_webhook_feature_flag_enabled()
diff --git a/posthog/temporal/tests/data_imports/test_end_to_end.py b/posthog/temporal/tests/data_imports/test_end_to_end.py
index 5020460378e0..35f7dbc30168 100644
--- a/posthog/temporal/tests/data_imports/test_end_to_end.py
+++ b/posthog/temporal/tests/data_imports/test_end_to_end.py
@@ -49,7 +49,6 @@ from posthog.hogql.query import execute_hogql_query
from posthog.hogql_queries.insights.funnels.funnel import FunnelUDF
from posthog.hogql_queries.insights.funnels.funnel_query_context import FunnelQueryContext
from posthog.models.event.util import format_clickhouse_timestamp
-from posthog.models.hog_functions.hog_function import HogFunction
from posthog.models.team.team import Team
from posthog.temporal.common.shutdown import ShutdownMonitor, WorkerShuttingDownError
from posthog.temporal.data_imports.cdp_producer_job import CDPProducerJobWorkflow
@@ -95,6 +94,7 @@ from posthog.temporal.ducklake import ACTIVITIES as DUCKLAKE_ACTIVITIES
from posthog.temporal.ducklake.ducklake_copy_data_imports_workflow import DuckLakeCopyDataImportsWorkflow
from posthog.temporal.utils import ExternalDataWorkflowInputs
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.data_tools.backend.models.join import DataWarehouseJoin
from products.data_warehouse.backend.webhook_consumer.config import WebhookConsumerConfig
from products.data_warehouse.backend.webhook_consumer.consumer import WebhookS3Sink
diff --git a/posthog/test/test_backfill_hogflow_billable_action_types.py b/posthog/test/test_backfill_hogflow_billable_action_types.py
index a095fa4c1c4b..95666a7e271e 100644
--- a/posthog/test/test_backfill_hogflow_billable_action_types.py
+++ b/posthog/test/test_backfill_hogflow_billable_action_types.py
@@ -4,7 +4,8 @@ from django.core.management import call_command
from django.test import TestCase
from posthog.models import User
-from posthog.models.hog_flow import HogFlow
+
+from products.workflows.backend.models.hog_flow import HogFlow
class BackfillHogFlowBillableActionTypesTest(TestCase):
diff --git a/posthog/test/test_migration_0273.py b/posthog/test/test_migration_0273.py
index 51da20888513..7c40904e3bd8 100644
--- a/posthog/test/test_migration_0273.py
+++ b/posthog/test/test_migration_0273.py
@@ -13,9 +13,10 @@ from django.utils import timezone
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.organization import Organization
-from posthog.models.plugin import Plugin, PluginConfig, PluginStorage
from posthog.models.team.team import Team
+from products.cdp.backend.models.plugin import Plugin, PluginConfig, PluginStorage
+
pytestmark = pytest.mark.skip("old migrations slow overall test run down")
diff --git a/posthog/test/test_plugin.py b/posthog/test/test_plugin.py
index 7497b8d80ce7..2b960d32161c 100644
--- a/posthog/test/test_plugin.py
+++ b/posthog/test/test_plugin.py
@@ -6,7 +6,6 @@ from unittest.mock import patch
from django.core import exceptions
from posthog.cdp.templates.helpers import mock_transpile
-from posthog.models import Plugin, PluginSourceFile
from posthog.plugins.test.plugin_archives import (
HELLO_WORLD_PLUGIN_FRONTEND_TSX,
HELLO_WORLD_PLUGIN_GITHUB_INDEX_JS,
@@ -24,6 +23,8 @@ from posthog.plugins.test.plugin_archives import (
HELLO_WORLD_PLUGIN_SITE_TS,
)
+from products.cdp.backend.models.plugin import Plugin, PluginSourceFile
+
class TestPlugin(BaseTest):
def test_default_config_list(self):
@@ -183,7 +184,7 @@ class TestPluginSourceFile(BaseTest, QueryMatchingTest):
self.assertEqual(frontend_tsx_file.source, HELLO_WORLD_PLUGIN_FRONTEND_TSX)
self.assertFalse(self.team.inject_web_apps)
- @patch("posthog.models.plugin.transpile", side_effect=mock_transpile)
+ @patch("products.cdp.backend.models.plugin.transpile", side_effect=mock_transpile)
@snapshot_postgres_queries
def test_sync_from_plugin_archive_from_zip_without_index_ts_but_site_ts_works(self, mock_transpile_fn):
self.assertFalse(self.team.inject_web_apps)
@@ -225,7 +226,7 @@ class TestPluginSourceFile(BaseTest, QueryMatchingTest):
f"Could not find main file index.js or index.ts in plugin Contoso",
)
- @patch("posthog.models.plugin.transpile", side_effect=mock_transpile)
+ @patch("products.cdp.backend.models.plugin.transpile", side_effect=mock_transpile)
@snapshot_postgres_queries
def test_sync_from_plugin_archive_twice_from_zip_with_index_ts_replaced_by_frontend_tsx_works(
self, mock_transpile_fn
diff --git a/posthog/test/test_plugin_log_entry.py b/posthog/test/test_plugin_log_entry.py
index 4869f590f1a4..b80b63218c92 100644
--- a/posthog/test/test_plugin_log_entry.py
+++ b/posthog/test/test_plugin_log_entry.py
@@ -5,10 +5,16 @@ from posthog.test.base import BaseTest
from django.utils import timezone
from posthog.clickhouse.client import sync_execute
-from posthog.models import Plugin, PluginConfig
-from posthog.models.plugin import PluginLogEntrySource, PluginLogEntryType, fetch_plugin_log_entries
from posthog.models.utils import UUIDT
+from products.cdp.backend.models.plugin import (
+ Plugin,
+ PluginConfig,
+ PluginLogEntrySource,
+ PluginLogEntryType,
+ fetch_plugin_log_entries,
+)
+
def create_plugin_log_entry(
*,
diff --git a/posthog/utils.py b/posthog/utils.py
index acfa1ea5b1ed..7702914d6a58 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -762,7 +762,7 @@ def get_default_event_name(team: "Team") -> str | None:
@tracer.start_as_current_span("template.frontend_apps")
def get_frontend_apps(team_id: int) -> dict[int, dict[str, Any]]:
- from posthog.models import Plugin, PluginSourceFile
+ from products.cdp.backend.models.plugin import Plugin, PluginSourceFile
plugin_configs = (
Plugin.objects.filter(pluginconfig__team_id=team_id, pluginconfig__enabled=True)
diff --git a/products/actions/backend/api/action.py b/products/actions/backend/api/action.py
index cb62efeeec2d..7884f1dec0ee 100644
--- a/products/actions/backend/api/action.py
+++ b/products/actions/backend/api/action.py
@@ -32,7 +32,6 @@ from posthog.event_usage import report_user_action
from posthog.models import Cohort, Team
from posthog.models.activity_logging.activity_log import Detail, changes_between, log_activity
from posthog.models.event.event import Selector
-from posthog.models.hog_functions.hog_function import HogFunction
from posthog.models.property.util import build_selector_regex
from posthog.models.signals import model_activity_signal, mutable_receiver
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
@@ -40,6 +39,7 @@ from posthog.rbac.user_access_control import UserAccessControlSerializerMixin
from posthog.resource_limits import LimitKey, check_count_limit
from products.actions.backend.models.action import ACTION_STEP_MATCHING_OPTIONS, Action
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.experiments.backend.models.experiment import Experiment
from products.product_analytics.backend.models.insight import Insight
diff --git a/products/actions/backend/api/test/test_action.py b/products/actions/backend/api/test/test_action.py
index 39ba23748ed4..7dadc0d599c7 100644
--- a/products/actions/backend/api/test/test_action.py
+++ b/products/actions/backend/api/test/test_action.py
@@ -11,9 +11,9 @@ from unittest.mock import ANY, patch
from rest_framework import status
from posthog.models import Cohort, Tag, User
-from posthog.models.hog_functions.hog_function import HogFunction
from products.actions.backend.models.action import Action
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.product_analytics.backend.models.insight import Insight
diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.py
index 0a4ae0aee86e..feb2f0c7fe19 100644
--- a/products/alerts/backend/api/alert.py
+++ b/products/alerts/backend/api/alert.py
@@ -961,7 +961,7 @@ def handle_alert_subscription_change(
@receiver(pre_delete, sender=AlertConfiguration)
def cleanup_alert_hog_functions(sender, instance: AlertConfiguration, **kwargs) -> None:
- from posthog.models.hog_functions.hog_function import HogFunction, HogFunctionType
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType
for hog_function in HogFunction.objects.filter(
team_id=instance.team_id,
diff --git a/products/alerts/backend/api/test/test_alert.py b/products/alerts/backend/api/test/test_alert.py
index 9c691b3d0a0c..22d7dae7a512 100644
--- a/products/alerts/backend/api/test/test_alert.py
+++ b/products/alerts/backend/api/test/test_alert.py
@@ -11,12 +11,12 @@ from rest_framework import status
from posthog.schema import AlertCalculationInterval, AlertConditionType, AlertState, InsightThresholdType
-from posthog.models.hog_functions.hog_function import HogFunction
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team import Team
from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
class TestAlert(APIBaseTest, QueryMatchingTest):
diff --git a/products/cdp/backend/admin/__init__.py b/products/cdp/backend/admin/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/admin/admins/hog_function_admin.py b/products/cdp/backend/admin/hog_function_admin.py
similarity index 95%
rename from posthog/admin/admins/hog_function_admin.py
rename to products/cdp/backend/admin/hog_function_admin.py
index a5ac3cf439e6..1c825b2e445e 100644
--- a/posthog/admin/admins/hog_function_admin.py
+++ b/products/cdp/backend/admin/hog_function_admin.py
@@ -3,7 +3,7 @@ from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html
-from posthog.models.hog_functions.hog_function import HogFunction, HogFunctionState
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionState
class HogFunctionAdminForm(forms.ModelForm):
diff --git a/posthog/admin/admins/plugin_admin.py b/products/cdp/backend/admin/plugin_admin.py
similarity index 97%
rename from posthog/admin/admins/plugin_admin.py
rename to products/cdp/backend/admin/plugin_admin.py
index 585399e7f7fd..eb1f7af5236a 100644
--- a/posthog/admin/admins/plugin_admin.py
+++ b/products/cdp/backend/admin/plugin_admin.py
@@ -1,7 +1,7 @@
from django.contrib import admin
from django.utils.html import format_html
-from posthog.models import Plugin
+from products.cdp.backend.models.plugin import Plugin
@admin.register(Plugin)
diff --git a/posthog/admin/inlines/plugin_attachment_inline.py b/products/cdp/backend/admin/plugin_attachment_inline.py
similarity index 96%
rename from posthog/admin/inlines/plugin_attachment_inline.py
rename to products/cdp/backend/admin/plugin_attachment_inline.py
index 2641506eb17f..b468cd3ebaea 100644
--- a/posthog/admin/inlines/plugin_attachment_inline.py
+++ b/products/cdp/backend/admin/plugin_attachment_inline.py
@@ -5,7 +5,7 @@ from django.db.models import Model
from django.http import HttpRequest
from django.utils.html import format_html
-from posthog.models import PluginAttachment
+from products.cdp.backend.models.plugin import PluginAttachment
ATTACHMENT_PREVIEW_SIZE_LIMIT_BYTES = 1024 * 1024
diff --git a/posthog/admin/admins/plugin_config_admin.py b/products/cdp/backend/admin/plugin_config_admin.py
similarity index 92%
rename from posthog/admin/admins/plugin_config_admin.py
rename to products/cdp/backend/admin/plugin_config_admin.py
index aacc6d7e07ec..442dba481fb3 100644
--- a/posthog/admin/admins/plugin_config_admin.py
+++ b/products/cdp/backend/admin/plugin_config_admin.py
@@ -1,8 +1,8 @@
from django.contrib import admin
from django.utils.html import format_html
-from posthog.admin.inlines.plugin_attachment_inline import PluginAttachmentInline
-from posthog.models import PluginConfig
+from products.cdp.backend.admin.plugin_attachment_inline import PluginAttachmentInline
+from products.cdp.backend.models.plugin import PluginConfig
@admin.register(PluginConfig)
diff --git a/products/cdp/backend/api/__init__.py b/products/cdp/backend/api/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/api/hog_function.py b/products/cdp/backend/api/hog_function.py
similarity index 98%
rename from posthog/api/hog_function.py
rename to products/cdp/backend/api/hog_function.py
index 207759b048be..fc7b3f2996a1 100644
--- a/posthog/api/hog_function.py
+++ b/products/cdp/backend/api/hog_function.py
@@ -21,7 +21,6 @@ from rest_framework.serializers import BaseSerializer
from posthog.api.app_metrics2 import AppMetricsMixin
from posthog.api.forbid_destroy_model import ForbidDestroyModel
-from posthog.api.hog_function_template import HogFunctionTemplateSerializer
from posthog.api.log_entries import LogEntryMixin
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
@@ -46,16 +45,18 @@ from posthog.helpers.trigram_search import (
)
from posthog.models import Team
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
-from posthog.models.hog_function_template import HogFunctionTemplate
-from posthog.models.hog_functions.hog_function import (
+from posthog.plugins.plugin_server_api import create_hog_invocation_test
+
+from products.cdp.backend.api.hog_function_template import HogFunctionTemplateSerializer
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
+from products.cdp.backend.models.hog_functions.hog_function import (
TYPES_WITH_JAVASCRIPT_SOURCE,
HogFunction,
HogFunctionState,
HogFunctionType,
)
-from posthog.models.hog_functions.utils import humanize_hog_function_type
-from posthog.models.plugin import TranspilerError
-from posthog.plugins.plugin_server_api import create_hog_invocation_test
+from products.cdp.backend.models.hog_functions.utils import humanize_hog_function_type
+from products.cdp.backend.models.plugin import TranspilerError
# Maximum size of HOG code as a string in bytes (100KB)
MAX_HOG_CODE_SIZE_BYTES = 100 * 1024
diff --git a/posthog/api/hog_function_template.py b/products/cdp/backend/api/hog_function_template.py
similarity index 97%
rename from posthog/api/hog_function_template.py
rename to products/cdp/backend/api/hog_function_template.py
index 6f332d7da391..7a5ec9063329 100644
--- a/posthog/api/hog_function_template.py
+++ b/products/cdp/backend/api/hog_function_template.py
@@ -6,8 +6,8 @@ from drf_spectacular.utils import OpenApiParameter, extend_schema
from rest_framework import mixins, permissions, serializers, viewsets
from rest_framework.request import Request
-from posthog.models.hog_function_template import HogFunctionTemplate
-from posthog.models.hog_functions import HogFunction
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
+from products.cdp.backend.models.hog_functions import HogFunction
logger = structlog.get_logger(__name__)
diff --git a/ee/api/hooks.py b/products/cdp/backend/api/hooks.py
similarity index 96%
rename from ee/api/hooks.py
rename to products/cdp/backend/api/hooks.py
index 4cd23b6d580e..2338661c821e 100644
--- a/ee/api/hooks.py
+++ b/products/cdp/backend/api/hooks.py
@@ -7,13 +7,13 @@ from django.http import Http404
from rest_framework import exceptions, mixins, serializers, status, viewsets
from rest_framework.response import Response
-from posthog.api.hog_function import HogFunctionSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.cdp.templates.zapier.template_zapier import template as template_zapier
-from posthog.models.hog_functions.hog_function import HogFunction
from posthog.models.user import User
-from ee.models.hook import HOOK_EVENTS, Hook
+from products.cdp.backend.api.hog_function import HogFunctionSerializer
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.cdp.backend.models.hook import HOOK_EVENTS, Hook
def create_zapier_hog_function(hook: Hook, serializer_context: dict, from_migration: bool = False) -> HogFunction:
diff --git a/posthog/api/plugin.py b/products/cdp/backend/api/plugin.py
similarity index 99%
rename from posthog/api/plugin.py
rename to products/cdp/backend/api/plugin.py
index 1779b9e9912c..82720a36ccc2 100644
--- a/posthog/api/plugin.py
+++ b/products/cdp/backend/api/plugin.py
@@ -21,12 +21,11 @@ from rest_framework.exceptions import NotFound, PermissionDenied, ValidationErro
from rest_framework.permissions import SAFE_METHODS, BasePermission, IsAuthenticated
from rest_framework.response import Response
-from posthog.api.hog_function import HogFunctionSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import ClassicBehaviorBooleanFieldSerializer, action
from posthog.cdp.templates import HOG_FUNCTION_MIGRATORS
from posthog.event_usage import report_user_action
-from posthog.models import Plugin, PluginAttachment, PluginConfig, User
+from posthog.models import User
from posthog.models.activity_logging.activity_log import (
ActivityPage,
Change,
@@ -39,7 +38,6 @@ from posthog.models.activity_logging.activity_log import (
from posthog.models.activity_logging.activity_page import activity_page_response
from posthog.models.activity_logging.serializers import ActivityLogSerializer
from posthog.models.organization import Organization
-from posthog.models.plugin import PluginSourceFile, transpile, update_validated_data_from_url
from posthog.models.utils import generate_random_token
from posthog.permissions import APIScopePermission
from posthog.plugins import can_configure_plugins, can_install_plugins, parse_url
@@ -47,6 +45,16 @@ from posthog.plugins.access import can_globally_manage_plugins, has_plugin_acces
from posthog.plugins.plugin_server_api import populate_plugin_capabilities_on_workers
from posthog.utils import format_query_params_absolute_url
+from products.cdp.backend.api.hog_function import HogFunctionSerializer
+from products.cdp.backend.models.plugin import (
+ Plugin,
+ PluginAttachment,
+ PluginConfig,
+ PluginSourceFile,
+ transpile,
+ update_validated_data_from_url,
+)
+
# Keep this in sync with: frontend/scenes/plugins/utils.ts
SECRET_FIELD_VALUE = "**************** POSTHOG SECRET FIELD ****************"
diff --git a/posthog/api/plugin_log_entry.py b/products/cdp/backend/api/plugin_log_entry.py
similarity index 92%
rename from posthog/api/plugin_log_entry.py
rename to products/cdp/backend/api/plugin_log_entry.py
index e412964454b9..eda859bc6e7c 100644
--- a/posthog/api/plugin_log_entry.py
+++ b/products/cdp/backend/api/plugin_log_entry.py
@@ -5,9 +5,10 @@ from rest_framework import exceptions, viewsets
from rest_framework.response import Response
from rest_framework_dataclasses.serializers import DataclassSerializer
-from posthog.api.plugin import PluginsAccessLevelPermission
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.models.plugin import PluginLogEntry, PluginLogEntryType, fetch_plugin_log_entries
+
+from products.cdp.backend.api.plugin import PluginsAccessLevelPermission
+from products.cdp.backend.models.plugin import PluginLogEntry, PluginLogEntryType, fetch_plugin_log_entries
class PluginLogEntrySerializer(DataclassSerializer):
diff --git a/posthog/api/test/__data__/hog_function_templates.json b/products/cdp/backend/api/test/__data__/hog_function_templates.json
similarity index 100%
rename from posthog/api/test/__data__/hog_function_templates.json
rename to products/cdp/backend/api/test/__data__/hog_function_templates.json
diff --git a/products/cdp/backend/api/test/__init__.py b/products/cdp/backend/api/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.py
similarity index 99%
rename from posthog/api/test/test_hog_function.py
rename to products/cdp/backend/api/test/test_hog_function.py
index 4a96e103a823..08f040d268b8 100644
--- a/posthog/api/test/test_hog_function.py
+++ b/products/cdp/backend/api/test/test_hog_function.py
@@ -10,15 +10,15 @@ from django.db import connection
from parameterized import parameterized
from rest_framework import status
-from posthog.api.hog_function import MAX_HOG_CODE_SIZE_BYTES, MAX_TRANSFORMATIONS_PER_TEAM
-from posthog.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES
from posthog.cdp.templates.helpers import mock_transpile
from posthog.cdp.templates.hog_function_template import sync_template_to_db
from posthog.cdp.templates.slack.template_slack import template as template_slack
-from posthog.models.hog_function_template import HogFunctionTemplate
-from posthog.models.hog_functions.hog_function import DEFAULT_STATE, HogFunction, HogFunctionState
from products.actions.backend.models.action import Action
+from products.cdp.backend.api.hog_function import MAX_HOG_CODE_SIZE_BYTES, MAX_TRANSFORMATIONS_PER_TEAM
+from products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
+from products.cdp.backend.models.hog_functions.hog_function import DEFAULT_STATE, HogFunction, HogFunctionState
from common.hogvm.python.operation import HOGQL_BYTECODE_VERSION, Operation
@@ -1659,7 +1659,9 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
]
def test_can_call_a_test_invocation(self):
- with patch("posthog.api.hog_function.create_hog_invocation_test") as mock_create_hog_invocation_test:
+ with patch(
+ "products.cdp.backend.api.hog_function.create_hog_invocation_test"
+ ) as mock_create_hog_invocation_test:
res = MagicMock(status_code=200, json=lambda: {"status": "success"})
mock_create_hog_invocation_test.return_value = res
@@ -2382,7 +2384,7 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
"""
Creating a HogFunction with a template_id that does not exist in the DB should raise a validation error and not create the object.
"""
- from posthog.models.hog_functions.hog_function import HogFunction
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
initial_count = HogFunction.objects.count()
response = self.client.post(
@@ -2442,7 +2444,7 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
assert len(response.json()["results"]) == 50, "With limit=50 and offset=100, should return last 50 items"
assert response.json()["count"] == 150, "Total count should still be 150"
- @patch("posthog.api.hog_function.posthoganalytics.feature_enabled", return_value=False)
+ @patch("products.cdp.backend.api.hog_function.posthoganalytics.feature_enabled", return_value=False)
def test_enable_backfills_blocked_without_feature_flag(self, mock_feature_enabled):
"""Test that enable_backfills is blocked when the feature flag is disabled."""
# Create a hog function
diff --git a/posthog/api/test/test_hog_function_templates.py b/products/cdp/backend/api/test/test_hog_function_templates.py
similarity index 98%
rename from posthog/api/test/test_hog_function_templates.py
rename to products/cdp/backend/api/test/test_hog_function_templates.py
index 695b2f17f971..b6b4afdecd5a 100644
--- a/posthog/api/test/test_hog_function_templates.py
+++ b/products/cdp/backend/api/test/test_hog_function_templates.py
@@ -8,8 +8,9 @@ from rest_framework import status
from posthog.cdp.templates.hog_function_template import sync_template_to_db
from posthog.cdp.templates.slack.template_slack import template as template_slack
-from posthog.models import HogFunction
-from posthog.models.hog_function_template import HogFunctionTemplate
+
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
MOCK_NODE_TEMPLATES = json.loads(
open(os.path.join(os.path.dirname(__file__), "__data__/hog_function_templates.json")).read()
diff --git a/ee/api/test/test_hooks.py b/products/cdp/backend/api/test/test_hooks.py
similarity index 96%
rename from ee/api/test/test_hooks.py
rename to products/cdp/backend/api/test/test_hooks.py
index dc706f65ebc0..1ee1210cc47a 100644
--- a/ee/api/test/test_hooks.py
+++ b/products/cdp/backend/api/test/test_hooks.py
@@ -6,14 +6,14 @@ from posthog.test.base import ClickhouseTestMixin
from posthog.cdp.templates.hog_function_template import sync_template_to_db
from posthog.cdp.templates.zapier.template_zapier import template as template_zapier
-from posthog.models.hog_functions.hog_function import HogFunction
from products.actions.backend.models.action import Action
+from products.cdp.backend.api.hooks import create_zapier_hog_function, valid_domain
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.cdp.backend.models.hook import Hook
from common.hogvm.python.operation import HOGQL_BYTECODE_VERSION
-from ee.api.hooks import create_zapier_hog_function, valid_domain
from ee.api.test.base import APILicensedTest
-from ee.models.hook import Hook
@pytest.mark.usefixtures("unittest_snapshot")
diff --git a/posthog/api/test/test_plugin.py b/products/cdp/backend/api/test/test_plugin.py
similarity index 98%
rename from posthog/api/test/test_plugin.py
rename to products/cdp/backend/api/test/test_plugin.py
index 8dcc0caf4d6a..29bd3d5ae16c 100644
--- a/posthog/api/test/test_plugin.py
+++ b/products/cdp/backend/api/test/test_plugin.py
@@ -11,12 +11,9 @@ from unittest.mock import patch
from rest_framework import status
-from posthog.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES
from posthog.cdp.templates.helpers import mock_transpile
from posthog.cdp.templates.hog_function_template import sync_template_to_db
from posthog.constants import FROZEN_POSTHOG_VERSION
-from posthog.models import Plugin, PluginConfig, PluginSourceFile
-from posthog.models.hog_functions.hog_function import HogFunction
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -24,13 +21,17 @@ from posthog.plugins.access import can_configure_plugins, can_globally_manage_pl
from posthog.plugins.test.mock import mocked_plugin_requests_get
from posthog.plugins.test.plugin_archives import HELLO_WORLD_PLUGIN_GITHUB_ATTACHMENT_ZIP, HELLO_WORLD_PLUGIN_GITHUB_ZIP
+from products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.cdp.backend.models.plugin import Plugin, PluginConfig, PluginSourceFile
+
def mocked_plugin_reload(*args, **kwargs):
pass
[email protected]("posthog.models.plugin.reload_plugins_on_workers", side_effect=mocked_plugin_reload)
[email protected]("posthog.api.plugin.requests.get", side_effect=mocked_plugin_requests_get)
[email protected]("products.cdp.backend.models.plugin.reload_plugins_on_workers", side_effect=mocked_plugin_reload)
[email protected]("products.cdp.backend.api.plugin.requests.get", side_effect=mocked_plugin_requests_get)
@pytest.mark.usefixtures("unittest_snapshot")
class TestPluginAPI(APIBaseTest, QueryMatchingTest):
maxDiff = None
@@ -347,7 +348,7 @@ class TestPluginAPI(APIBaseTest, QueryMatchingTest):
)
self.assertEqual(response.status_code, 400)
- @mock.patch("posthog.models.plugin.PluginSourceFile.objects.sync_from_plugin_archive")
+ @mock.patch("products.cdp.backend.models.plugin.PluginSourceFile.objects.sync_from_plugin_archive")
def test_update_plugin_auth(self, mock_sync_from_plugin_archive, mock_get, mock_reload):
self.assertEqual(mock_reload.call_count, 0)
self.assertEqual(mock_sync_from_plugin_archive.call_count, 0)
@@ -740,7 +741,7 @@ class TestPluginAPI(APIBaseTest, QueryMatchingTest):
self.assertEqual(response.json(), {"plugin.json": '{"name":"my plugin"}'})
self.assertEqual(mock_reload.call_count, 3)
- @patch("posthog.api.plugin.transpile", side_effect=mock_transpile)
+ @patch("products.cdp.backend.api.plugin.transpile", side_effect=mock_transpile)
def test_transpile_plugin_frontend_source(self, mock_transpile_fn, mock_get, mock_reload):
# Setup
assert mock_reload.call_count == 0
diff --git a/products/cdp/backend/apps.py b/products/cdp/backend/apps.py
index 8a598a10a6b6..091e5ddb5580 100644
--- a/products/cdp/backend/apps.py
+++ b/products/cdp/backend/apps.py
@@ -2,6 +2,10 @@ from django.apps import AppConfig
class CdpConfig(AppConfig):
- default_auto_field = "django.db.models.BigAutoField"
+ # Legacy Plugin/HogFunction/Hook tables used AutoField (INT4) before BigAutoField
+ # became Django's default. SeparateDatabaseAndState preserves the DB schema, so the
+ # app default must match — otherwise fresh test DBs would create INT8 columns and
+ # break clients that decode the id as i32 (notably the feature-flags Rust service).
+ default_auto_field = "django.db.models.AutoField"
name = "products.cdp.backend"
label = "cdp"
diff --git a/products/cdp/backend/migrations/0001_migrate_cdp_models.py b/products/cdp/backend/migrations/0001_migrate_cdp_models.py
new file mode 100644
index 000000000000..b0bf3e189b38
--- /dev/null
+++ b/products/cdp/backend/migrations/0001_migrate_cdp_models.py
@@ -0,0 +1,452 @@
+# Generated by Django 5.2.14 on 2026-05-27 13:30
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.models.utils
+import posthog.helpers.encrypted_fields
+
+
+class Migration(migrations.Migration):
+ initial = True
+
+ dependencies = [
+ ("actions", "0001_migrate_actions_models"),
+ ("posthog", "1187_migrate_hog_flow_models"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.CreateModel(
+ name="HogFunctionTemplate",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.UUIDT,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("template_id", models.CharField(db_index=True, max_length=255)),
+ ("sha", models.CharField(db_index=True, max_length=100)),
+ ("name", models.CharField(max_length=400)),
+ ("description", models.TextField(blank=True, null=True)),
+ ("code", models.TextField()),
+ ("code_language", models.CharField(default="hog", max_length=20)),
+ ("inputs_schema", models.JSONField()),
+ ("bytecode", models.JSONField(blank=True, null=True)),
+ ("type", models.CharField(max_length=50)),
+ ("status", models.CharField(default="alpha", max_length=20)),
+ ("category", models.JSONField(default=list)),
+ ("kind", models.CharField(blank=True, max_length=50, null=True)),
+ ("free", models.BooleanField(default=False)),
+ ("icon_url", models.CharField(blank=True, null=True)),
+ ("filters", models.JSONField(blank=True, null=True)),
+ ("masking", models.JSONField(blank=True, null=True)),
+ ("mapping_templates", models.JSONField(blank=True, null=True)),
+ ("mappings", models.JSONField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ],
+ options={
+ "db_table": "posthog_hogfunctiontemplate",
+ "indexes": [
+ models.Index(
+ fields=["template_id", "sha"],
+ name="posthog_hog_templat_55950b_idx",
+ ),
+ models.Index(fields=["type", "status"], name="posthog_hog_type_8cac9a_idx"),
+ models.Index(fields=["created_at"], name="posthog_hog_created_6a9df3_idx"),
+ models.Index(
+ fields=["template_id", "created_at"],
+ name="posthog_hog_templat_d1778e_idx",
+ ),
+ ],
+ "unique_together": {("template_id", "sha")},
+ },
+ ),
+ migrations.CreateModel(
+ name="Hook",
+ fields=[
+ (
+ "id",
+ models.CharField(
+ default=posthog.models.utils.generate_random_token,
+ max_length=50,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "event",
+ models.CharField(db_index=True, max_length=64, verbose_name="Event"),
+ ),
+ ("resource_id", models.IntegerField(blank=True, null=True)),
+ ("target", models.URLField(max_length=255, verbose_name="Target URL")),
+ ("created", models.DateTimeField(auto_now_add=True)),
+ ("updated", models.DateTimeField(auto_now=True)),
+ (
+ "team",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="rest_hooks",
+ to="posthog.team",
+ ),
+ ),
+ (
+ "user",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="rest_hooks",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ options={
+ "db_table": "ee_hook",
+ },
+ ),
+ migrations.CreateModel(
+ name="Plugin",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "plugin_type",
+ models.CharField(
+ blank=True,
+ choices=[
+ ("local", "local"),
+ ("custom", "custom"),
+ ("repository", "repository"),
+ ("source", "source"),
+ ("inline", "inline"),
+ ],
+ default=None,
+ max_length=200,
+ null=True,
+ ),
+ ),
+ ("is_global", models.BooleanField(default=False)),
+ ("is_preinstalled", models.BooleanField(default=False)),
+ (
+ "is_stateless",
+ models.BooleanField(blank=True, default=False, null=True),
+ ),
+ ("name", models.CharField(blank=True, max_length=200, null=True)),
+ ("description", models.TextField(blank=True, null=True)),
+ (
+ "url",
+ models.CharField(blank=True, max_length=800, null=True, unique=True),
+ ),
+ ("icon", models.CharField(blank=True, max_length=800, null=True)),
+ ("config_schema", models.JSONField(blank=True, default=dict)),
+ ("tag", models.CharField(blank=True, max_length=200, null=True)),
+ ("archive", models.BinaryField(blank=True, null=True)),
+ ("latest_tag", models.CharField(blank=True, max_length=800, null=True)),
+ ("latest_tag_checked_at", models.DateTimeField(blank=True, null=True)),
+ ("capabilities", models.JSONField(default=dict)),
+ ("metrics", models.JSONField(blank=True, default=dict, null=True)),
+ ("public_jobs", models.JSONField(blank=True, default=dict, null=True)),
+ ("error", models.JSONField(blank=True, default=None, null=True)),
+ ("from_json", models.BooleanField(default=False)),
+ ("from_web", models.BooleanField(default=False)),
+ ("source", models.TextField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(blank=True, null=True)),
+ ("log_level", models.IntegerField(blank=True, null=True)),
+ (
+ "has_private_access",
+ models.ManyToManyField(to="posthog.organization"),
+ ),
+ (
+ "organization",
+ models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="plugins",
+ related_query_name="plugin",
+ to="posthog.organization",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_plugin",
+ },
+ ),
+ migrations.CreateModel(
+ name="PluginConfig",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("enabled", models.BooleanField(default=False)),
+ ("order", models.IntegerField()),
+ ("config", models.JSONField(default=dict)),
+ ("error", models.JSONField(blank=True, default=None, null=True)),
+ ("web_token", models.CharField(default=None, max_length=64, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ("name", models.CharField(blank=True, max_length=400, null=True)),
+ (
+ "description",
+ models.CharField(blank=True, max_length=1000, null=True),
+ ),
+ ("deleted", models.BooleanField(default=False, null=True)),
+ ("filters", models.JSONField(blank=True, null=True)),
+ (
+ "match_action",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="plugin_configs",
+ to="actions.action",
+ ),
+ ),
+ (
+ "plugin",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="cdp.plugin"),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_pluginconfig",
+ },
+ ),
+ migrations.CreateModel(
+ name="PluginAttachment",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("key", models.CharField(max_length=200)),
+ ("content_type", models.CharField(max_length=200)),
+ ("file_name", models.CharField(max_length=200)),
+ ("file_size", models.IntegerField()),
+ ("contents", models.BinaryField()),
+ (
+ "team",
+ models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ (
+ "plugin_config",
+ models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="cdp.pluginconfig",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_pluginattachment",
+ },
+ ),
+ migrations.CreateModel(
+ name="PluginSourceFile",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.UUIDT,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("filename", models.CharField(max_length=200)),
+ ("source", models.TextField(blank=True, null=True)),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("LOCKED", "locked"),
+ ("TRANSPILED", "transpiled"),
+ ("ERROR", "error"),
+ ],
+ max_length=20,
+ null=True,
+ ),
+ ),
+ ("transpiled", models.TextField(blank=True, null=True)),
+ ("error", models.TextField(blank=True, null=True)),
+ ("updated_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "plugin",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="cdp.plugin"),
+ ),
+ ],
+ options={
+ "db_table": "posthog_pluginsourcefile",
+ },
+ ),
+ migrations.CreateModel(
+ name="PluginStorage",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("key", models.CharField(max_length=200)),
+ ("value", models.TextField(blank=True, null=True)),
+ (
+ "plugin_config",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ to="cdp.pluginconfig",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_pluginstorage",
+ },
+ ),
+ migrations.CreateModel(
+ name="HogFunction",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.UUIDT,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("name", models.CharField(blank=True, max_length=400, null=True)),
+ ("description", models.TextField(blank=True, default="")),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("deleted", models.BooleanField(default=False)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ("enabled", models.BooleanField(default=False)),
+ ("type", models.CharField(blank=True, max_length=24, null=True)),
+ ("kind", models.CharField(blank=True, max_length=24, null=True)),
+ ("icon_url", models.TextField(blank=True, null=True)),
+ ("hog", models.TextField()),
+ ("bytecode", models.JSONField(blank=True, null=True)),
+ ("transpiled", models.TextField(blank=True, null=True)),
+ ("inputs_schema", models.JSONField(null=True)),
+ ("inputs", models.JSONField(null=True)),
+ (
+ "encrypted_inputs",
+ posthog.helpers.encrypted_fields.EncryptedJSONStringField(blank=True, null=True),
+ ),
+ ("filters", models.JSONField(blank=True, null=True)),
+ ("mappings", models.JSONField(blank=True, null=True)),
+ ("masking", models.JSONField(blank=True, null=True)),
+ (
+ "template_id",
+ models.CharField(blank=True, max_length=400, null=True),
+ ),
+ (
+ "execution_order",
+ models.PositiveSmallIntegerField(blank=True, null=True),
+ ),
+ (
+ "batch_export",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to="posthog.batchexport",
+ ),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),
+ ),
+ (
+ "hog_function_template",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="hog_functions",
+ to="cdp.hogfunctiontemplate",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_hogfunction",
+ "indexes": [
+ models.Index(
+ fields=["type", "enabled", "team"],
+ name="posthog_hog_type_6f8967_idx",
+ )
+ ],
+ },
+ ),
+ migrations.AddIndex(
+ model_name="pluginconfig",
+ index=models.Index(fields=["web_token"], name="posthog_plu_web_tok_ac760a_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="pluginconfig",
+ index=models.Index(fields=["enabled"], name="posthog_plu_enabled_f5ed94_idx"),
+ ),
+ migrations.AddConstraint(
+ model_name="pluginsourcefile",
+ constraint=models.UniqueConstraint(
+ fields=("plugin_id", "filename"), name="unique_filename_for_plugin"
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="pluginstorage",
+ constraint=models.UniqueConstraint(
+ fields=("plugin_config_id", "key"),
+ name="posthog_unique_plugin_storage_key",
+ ),
+ ),
+ ],
+ database_operations=[],
+ ),
+ ]
diff --git a/products/cdp/backend/migrations/__init__.py b/products/cdp/backend/migrations/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/cdp/backend/migrations/max_migration.txt b/products/cdp/backend/migrations/max_migration.txt
new file mode 100644
index 000000000000..43312cdbb304
--- /dev/null
+++ b/products/cdp/backend/migrations/max_migration.txt
@@ -0,0 +1 @@
+0001_migrate_cdp_models
diff --git a/products/cdp/backend/models/__init__.py b/products/cdp/backend/models/__init__.py
new file mode 100644
index 000000000000..598267ac18fa
--- /dev/null
+++ b/products/cdp/backend/models/__init__.py
@@ -0,0 +1,29 @@
+from .hog_function_template import HogFunctionTemplate
+from .hog_functions import HogFunction
+from .hog_functions.hog_function import HogFunctionState
+from .hook import Hook
+from .plugin import (
+ Plugin,
+ PluginAttachment,
+ PluginConfig,
+ PluginLogEntry,
+ PluginLogEntrySource,
+ PluginLogEntryType,
+ PluginSourceFile,
+ PluginStorage,
+)
+
+__all__ = [
+ "HogFunction",
+ "HogFunctionState",
+ "HogFunctionTemplate",
+ "Hook",
+ "Plugin",
+ "PluginAttachment",
+ "PluginConfig",
+ "PluginLogEntry",
+ "PluginLogEntrySource",
+ "PluginLogEntryType",
+ "PluginSourceFile",
+ "PluginStorage",
+]
diff --git a/posthog/models/hog_function_template.py b/products/cdp/backend/models/hog_function_template.py
similarity index 99%
rename from posthog/models/hog_function_template.py
rename to products/cdp/backend/models/hog_function_template.py
index 44b8fd44076a..83e8a7aba0ac 100644
--- a/posthog/models/hog_function_template.py
+++ b/products/cdp/backend/models/hog_function_template.py
@@ -59,6 +59,7 @@ class HogFunctionTemplate(UUIDTModel):
updated_at = models.DateTimeField(auto_now=True)
class Meta:
+ db_table = "posthog_hogfunctiontemplate"
unique_together = ("template_id", "sha")
indexes = [
models.Index(fields=["template_id", "sha"]),
diff --git a/products/cdp/backend/models/hog_functions/__init__.py b/products/cdp/backend/models/hog_functions/__init__.py
new file mode 100644
index 000000000000..6363b39598ef
--- /dev/null
+++ b/products/cdp/backend/models/hog_functions/__init__.py
@@ -0,0 +1,3 @@
+from .hog_function import HogFunction, HogFunctionState
+
+__all__ = ["HogFunction", "HogFunctionState"]
diff --git a/posthog/models/hog_functions/hog_function.py b/products/cdp/backend/models/hog_functions/hog_function.py
similarity index 94%
rename from posthog/models/hog_functions/hog_function.py
rename to products/cdp/backend/models/hog_functions/hog_function.py
index 902d932537dd..c74d9eab4fa0 100644
--- a/posthog/models/hog_functions/hog_function.py
+++ b/products/cdp/backend/models/hog_functions/hog_function.py
@@ -15,8 +15,6 @@ from posthog.helpers.encrypted_fields import EncryptedJSONStringField
from posthog.models.cohort.cohort import is_cohort_recalculation_only_save
from posthog.models.file_system.file_system_mixin import FileSystemSyncMixin
from posthog.models.file_system.file_system_representation import FileSystemRepresentation
-from posthog.models.hog_function_template import HogFunctionTemplate
-from posthog.models.plugin import sync_team_inject_web_apps
from posthog.models.signals import mutable_receiver
from posthog.models.team.team import Team
from posthog.models.utils import UUIDTModel
@@ -28,6 +26,8 @@ from posthog.plugins.plugin_server_api import (
from posthog.utils import absolute_uri
from products.actions.backend.models.action import Action
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
+from products.cdp.backend.models.plugin import sync_team_inject_web_apps
if TYPE_CHECKING:
from posthog.models.team import Team
@@ -74,15 +74,16 @@ TYPES_WITH_JAVASCRIPT_SOURCE = (HogFunctionType.SITE_DESTINATION, HogFunctionTyp
class HogFunction(FileSystemSyncMixin, UUIDTModel):
class Meta:
+ db_table = "posthog_hogfunction"
indexes = [
models.Index(fields=["type", "enabled", "team"]),
]
- team = models.ForeignKey("Team", on_delete=models.CASCADE)
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
name = models.CharField(max_length=400, null=True, blank=True)
description = models.TextField(blank=True, default="")
created_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)
updated_at = models.DateTimeField(auto_now=True)
enabled = models.BooleanField(default=False)
@@ -109,7 +110,7 @@ class HogFunction(FileSystemSyncMixin, UUIDTModel):
masking = models.JSONField(null=True, blank=True)
template_id = models.CharField(max_length=400, null=True, blank=True)
hog_function_template = models.ForeignKey(
- "posthog.HogFunctionTemplate",
+ "cdp.HogFunctionTemplate",
on_delete=models.SET_NULL,
null=True,
blank=True,
@@ -259,14 +260,14 @@ def action_saved(sender, instance: Action, created, **kwargs):
# Whenever an action is saved we want to load all hog functions using it
# and trigger a refresh of the filters bytecode
- from posthog.tasks.hog_functions import refresh_affected_hog_functions
+ from products.cdp.backend.tasks.hog_functions import refresh_affected_hog_functions
refresh_affected_hog_functions.delay(action_id=instance.id)
@receiver(post_save, sender=Team)
def team_saved(sender, instance: Team, created, **kwargs):
- from posthog.tasks.hog_functions import refresh_affected_hog_functions
+ from products.cdp.backend.tasks.hog_functions import refresh_affected_hog_functions
refresh_affected_hog_functions.delay(team_id=instance.id)
@@ -286,7 +287,7 @@ def cohort_saved(sender, instance, **kwargs):
for f in team.test_account_filters
if isinstance(f, dict)
):
- from posthog.tasks.hog_functions import refresh_affected_hog_functions
+ from products.cdp.backend.tasks.hog_functions import refresh_affected_hog_functions
refresh_affected_hog_functions.delay(cohort_id=instance.id)
@@ -304,11 +305,12 @@ def team_inject_web_apps_changd(sender, instance, created=None, **kwargs):
@receiver(models.signals.post_save, sender=Team)
def enabled_default_hog_functions_for_new_team(sender, instance: Team, created: bool, **kwargs):
- from posthog.api.hog_function import HogFunctionSerializer
from posthog.cdp.templates.hog_function_template import sync_template_to_db
- from posthog.models.hog_function_template import HogFunctionTemplate
from posthog.plugins.plugin_server_api import get_hog_function_templates
+ from products.cdp.backend.api.hog_function import HogFunctionSerializer
+ from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
+
if settings.DISABLE_MMDB or not created:
return
diff --git a/posthog/models/hog_functions/utils.py b/products/cdp/backend/models/hog_functions/utils.py
similarity index 79%
rename from posthog/models/hog_functions/utils.py
rename to products/cdp/backend/models/hog_functions/utils.py
index 6755f497a6fc..6ca83b9f9df1 100644
--- a/posthog/models/hog_functions/utils.py
+++ b/products/cdp/backend/models/hog_functions/utils.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from posthog.models.hog_functions.hog_function import HogFunctionType
+from products.cdp.backend.models.hog_functions.hog_function import HogFunctionType
def humanize_hog_function_type(hog_type: str | None) -> str:
diff --git a/ee/models/hook.py b/products/cdp/backend/models/hook.py
similarity index 97%
rename from ee/models/hook.py
rename to products/cdp/backend/models/hook.py
index 35c49c8581e8..f4138f65900c 100644
--- a/ee/models/hook.py
+++ b/products/cdp/backend/models/hook.py
@@ -22,6 +22,9 @@ class Hook(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
+ class Meta:
+ db_table = "ee_hook"
+
def clean(self):
"""Validation for events."""
if self.event not in HOOK_EVENTS:
diff --git a/posthog/models/plugin.py b/products/cdp/backend/models/plugin.py
similarity index 96%
rename from posthog/models/plugin.py
rename to products/cdp/backend/models/plugin.py
index ffcb85b9ed2c..205028d7d859 100644
--- a/posthog/models/plugin.py
+++ b/products/cdp/backend/models/plugin.py
@@ -20,6 +20,7 @@ from posthog.constants import FROZEN_POSTHOG_VERSION
from posthog.models.organization import Organization
from posthog.models.signals import mutable_receiver
from posthog.models.team import Team
+from posthog.models.utils import UUIDTModel, sane_repr
from posthog.plugins.access import can_install_plugins
from posthog.plugins.plugin_server_api import populate_plugin_capabilities_on_workers, reload_plugins_on_workers
from posthog.plugins.site import get_decide_site_apps, get_decide_site_functions
@@ -31,8 +32,6 @@ from posthog.plugins.utils import (
parse_url,
)
-from .utils import UUIDTModel, sane_repr
-
try:
from posthog.clickhouse.client import sync_execute
except ImportError:
@@ -201,6 +200,9 @@ class Plugin(models.Model):
objects: PluginManager = PluginManager()
+ class Meta:
+ db_table = "posthog_plugin"
+
__repr__ = sane_repr("id", "name", "organization_id", "is_global")
def __str__(self) -> str:
@@ -225,8 +227,8 @@ class Plugin(models.Model):
class PluginConfig(models.Model):
- team = models.ForeignKey("Team", on_delete=models.CASCADE, null=True)
- plugin = models.ForeignKey("Plugin", on_delete=models.CASCADE)
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, null=True)
+ plugin = models.ForeignKey("cdp.Plugin", on_delete=models.CASCADE)
enabled = models.BooleanField(default=False)
order = models.IntegerField()
config = models.JSONField(default=dict)
@@ -259,6 +261,7 @@ class PluginConfig(models.Model):
)
class Meta:
+ db_table = "posthog_pluginconfig"
indexes = [
models.Index(fields=["web_token"]),
models.Index(fields=["enabled"]),
@@ -266,14 +269,17 @@ class PluginConfig(models.Model):
class PluginAttachment(models.Model):
- team = models.ForeignKey("Team", on_delete=models.CASCADE, null=True)
- plugin_config = models.ForeignKey("PluginConfig", on_delete=models.CASCADE, null=True)
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, null=True)
+ plugin_config = models.ForeignKey("cdp.PluginConfig", on_delete=models.CASCADE, null=True)
key = models.CharField(max_length=200)
content_type = models.CharField(max_length=200)
file_name = models.CharField(max_length=200)
file_size = models.IntegerField()
contents = models.BinaryField()
+ class Meta:
+ db_table = "posthog_pluginattachment"
+
def parse_contents(self) -> str | None:
contents: bytes | None = bytes(self.contents) if self.contents else None
if not contents:
@@ -288,11 +294,12 @@ class PluginAttachment(models.Model):
class PluginStorage(models.Model):
- plugin_config = models.ForeignKey("PluginConfig", on_delete=models.CASCADE)
+ plugin_config = models.ForeignKey("cdp.PluginConfig", on_delete=models.CASCADE)
key = models.CharField(max_length=200)
value = models.TextField(blank=True, null=True)
class Meta:
+ db_table = "posthog_pluginstorage"
constraints = [
models.UniqueConstraint(
fields=["plugin_config_id", "key"],
@@ -455,6 +462,7 @@ class PluginSourceFileManager(models.Manager):
class PluginSourceFile(UUIDTModel):
class Meta:
+ db_table = "posthog_pluginsourcefile"
constraints = [models.UniqueConstraint(name="unique_filename_for_plugin", fields=("plugin_id", "filename"))]
class Status(models.TextChoices):
@@ -462,7 +470,7 @@ class PluginSourceFile(UUIDTModel):
TRANSPILED = "TRANSPILED", "transpiled"
ERROR = "ERROR", "error"
- plugin = models.ForeignKey("Plugin", on_delete=models.CASCADE)
+ plugin = models.ForeignKey("cdp.Plugin", on_delete=models.CASCADE)
filename = models.CharField(max_length=200, blank=False)
# "source" can be null if we're only using this model to cache transpiled code from a ".zip"
source = models.TextField(blank=True, null=True)
diff --git a/products/cdp/backend/tasks/__init__.py b/products/cdp/backend/tasks/__init__.py
new file mode 100644
index 000000000000..85a1ebb14666
--- /dev/null
+++ b/products/cdp/backend/tasks/__init__.py
@@ -0,0 +1,3 @@
+from . import hog_functions
+
+__all__ = ["hog_functions"]
diff --git a/posthog/tasks/hog_functions.py b/products/cdp/backend/tasks/hog_functions.py
similarity index 98%
rename from posthog/tasks/hog_functions.py
rename to products/cdp/backend/tasks/hog_functions.py
index c2e959507592..41f38f201874 100644
--- a/posthog/tasks/hog_functions.py
+++ b/products/cdp/backend/tasks/hog_functions.py
@@ -22,7 +22,7 @@ logger = get_logger(__name__)
def refresh_affected_hog_functions(
team_id: Optional[int] = None, action_id: Optional[int] = None, cohort_id: Optional[int] = None
) -> int:
- from posthog.models.hog_functions.hog_function import HogFunction
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
affected_hog_functions: list[HogFunction] = []
diff --git a/products/cdp/backend/test/__init__.py b/products/cdp/backend/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/cdp/frontend/generated/api.schemas.ts b/products/cdp/frontend/generated/api.schemas.ts
index d6e1ab3ec641..72b6662f13ff 100644
--- a/products/cdp/frontend/generated/api.schemas.ts
+++ b/products/cdp/frontend/generated/api.schemas.ts
@@ -561,6 +561,57 @@ export interface PatchedHogFunctionRearrangeApi {
orders?: PatchedHogFunctionRearrangeApiOrders
}
+/**
+ * * `SYSTEM` - SYSTEM
+ * `PLUGIN` - PLUGIN
+ * `CONSOLE` - CONSOLE
+ */
+export type PluginLogEntrySourceEnumApi = (typeof PluginLogEntrySourceEnumApi)[keyof typeof PluginLogEntrySourceEnumApi]
+
+export const PluginLogEntrySourceEnumApi = {
+ System: 'SYSTEM',
+ Plugin: 'PLUGIN',
+ Console: 'CONSOLE',
+} as const
+
+/**
+ * * `DEBUG` - DEBUG
+ * `LOG` - LOG
+ * `INFO` - INFO
+ * `WARN` - WARN
+ * `ERROR` - ERROR
+ */
+export type PluginLogEntryTypeEnumApi = (typeof PluginLogEntryTypeEnumApi)[keyof typeof PluginLogEntryTypeEnumApi]
+
+export const PluginLogEntryTypeEnumApi = {
+ Debug: 'DEBUG',
+ Log: 'LOG',
+ Info: 'INFO',
+ Warn: 'WARN',
+ Error: 'ERROR',
+} as const
+
+export interface PluginLogEntryApi {
+ id: string
+ team_id: number
+ plugin_id: number
+ plugin_config_id: number
+ timestamp: string
+ source: PluginLogEntrySourceEnumApi
+ type: PluginLogEntryTypeEnumApi
+ message: string
+ instance_id: string
+}
+
+export interface PaginatedPluginLogEntryListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: PluginLogEntryApi[]
+}
+
export type HogFunctionTemplatesListParams = {
/**
* Number of results to return per page.
@@ -760,6 +811,17 @@ export const HogFunctionsMetricsTotalsRetrieveInterval = {
Week: 'week',
} as const
+export type PluginConfigsLogsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type PublicHogFunctionTemplatesListParams = {
/**
* Number of results to return per page.
diff --git a/products/cdp/frontend/generated/api.ts b/products/cdp/frontend/generated/api.ts
index e7703c1f0356..2980ba6f7c56 100644
--- a/products/cdp/frontend/generated/api.ts
+++ b/products/cdp/frontend/generated/api.ts
@@ -21,8 +21,10 @@ import type {
HogFunctionsMetricsTotalsRetrieveParams,
PaginatedHogFunctionMinimalListApi,
PaginatedHogFunctionTemplateListApi,
+ PaginatedPluginLogEntryListApi,
PatchedHogFunctionApi,
PatchedHogFunctionRearrangeApi,
+ PluginConfigsLogsListParams,
PublicHogFunctionTemplatesListParams,
} from './api.schemas'
@@ -368,6 +370,38 @@ export const hogFunctionsRearrangePartialUpdate = async (
})
}
+export const getPluginConfigsLogsListUrl = (
+ projectId: string,
+ pluginConfigId: number,
+ params?: PluginConfigsLogsListParams
+) => {
+ 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}/plugin_configs/${pluginConfigId}/logs/?${stringifiedParams}`
+ : `/api/projects/${projectId}/plugin_configs/${pluginConfigId}/logs/`
+}
+
+export const pluginConfigsLogsList = async (
+ projectId: string,
+ pluginConfigId: number,
+ params?: PluginConfigsLogsListParams,
+ options?: RequestInit
+): Promise<PaginatedPluginLogEntryListApi> => {
+ return apiMutator<PaginatedPluginLogEntryListApi>(getPluginConfigsLogsListUrl(projectId, pluginConfigId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getPublicHogFunctionTemplatesListUrl = (params?: PublicHogFunctionTemplatesListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/data_warehouse/backend/api/data_warehouse.py b/products/data_warehouse/backend/api/data_warehouse.py
index d77a5a11337c..0c577cad9037 100644
--- a/products/data_warehouse/backend/api/data_warehouse.py
+++ b/products/data_warehouse/backend/api/data_warehouse.py
@@ -28,11 +28,11 @@ from posthog.batch_exports.models import BatchExportRun
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.cloud_utils import get_cached_instance_license
from posthog.helpers.dashboard_templates import create_data_ops_dashboard
-from posthog.models.hog_functions.hog_function import HogFunction, HogFunctionState, HogFunctionType
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.security.outbound_proxy import internal_requests as _internal_requests
from posthog.utils import convert_property_value, flatten
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionState, HogFunctionType
from products.data_modeling.backend.models.data_modeling_job import DataModelingJob
from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
from products.data_warehouse.backend.models.team_data_warehouse_config import TeamDataWarehouseConfig
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.py
index f48af1819417..8a6520c16673 100644
--- a/products/data_warehouse/backend/api/external_data_source.py
+++ b/products/data_warehouse/backend/api/external_data_source.py
@@ -31,7 +31,6 @@ from posthog.schema import (
from posthog.hogql.database.database import Database
-from posthog.api.hog_function import HogFunctionSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
from posthog.exceptions_capture import capture_exception
@@ -40,7 +39,6 @@ from posthog.models.activity_logging.external_data_utils import (
get_external_data_source_created_by_info,
get_external_data_source_detail_name,
)
-from posthog.models.hog_functions.hog_function import HogFunction
from posthog.models.signals import model_activity_signal, mutable_receiver
from posthog.models.user import User
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
@@ -53,6 +51,8 @@ from posthog.temporal.data_imports.sources.common.sql import filter_dwh_columns_
from posthog.temporal.data_imports.sources.postgres.cdc.config import PostgresCDCConfig
from posthog.temporal.data_imports.sources.postgres.source import PostgresSource
+from products.cdp.backend.api.hog_function import HogFunctionSerializer
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.data_modeling.backend.models.datawarehouse_managed_viewset import DataWarehouseManagedViewSet
from products.data_warehouse.backend.api.external_data_schema import (
ExternalDataSchemaSerializer,
diff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.py
index 3a7da33ea90b..3ca6ecbd7d56 100644
--- a/products/data_warehouse/backend/api/test/test_external_data_source.py
+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py
@@ -5297,7 +5297,7 @@ class TestCreateWebhook(APIBaseTest):
)
def _create_hog_function_template(self):
- from posthog.models.hog_function_template import HogFunctionTemplate
+ from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
return HogFunctionTemplate.objects.create(
template_id="template-warehouse-source-stripe",
@@ -5347,9 +5347,10 @@ class TestCreateWebhook(APIBaseTest):
@patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.create_webhook")
def test_create_webhook_success(self, mock_create_webhook, _mock_flag):
mock_create_webhook.return_value = self._webhook_result()
- from posthog.models.hog_functions.hog_function import HogFunction
from posthog.temporal.data_imports.sources.stripe.constants import RESOURCE_TO_STRIPE_OBJECT_TYPE
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+
self._create_hog_function_template()
source = self._create_stripe_source()
schema = self._create_webhook_schema(source, STRIPE_CUSTOMER_RESOURCE_NAME)
@@ -5397,7 +5398,7 @@ class TestCreateWebhook(APIBaseTest):
@patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.create_webhook")
def test_create_webhook_external_creation_fails(self, mock_create_webhook, _mock_flag):
mock_create_webhook.return_value = self._webhook_result(success=False, error="Permission denied")
- from posthog.models.hog_functions.hog_function import HogFunction
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
self._create_hog_function_template()
source = self._create_stripe_source()
@@ -5451,9 +5452,10 @@ class TestCreateWebhook(APIBaseTest):
@patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.create_webhook")
def test_create_webhook_merges_schemas_on_update(self, mock_create_webhook, _mock_flag):
mock_create_webhook.return_value = self._webhook_result()
- from posthog.models.hog_functions.hog_function import HogFunction
from posthog.temporal.data_imports.sources.stripe.constants import RESOURCE_TO_STRIPE_OBJECT_TYPE
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+
self._create_hog_function_template()
source = self._create_stripe_source()
self._create_webhook_schema(source, STRIPE_CHARGE_RESOURCE_NAME)
@@ -5499,7 +5501,7 @@ class TestCreateWebhook(APIBaseTest):
@patch("posthog.temporal.data_imports.sources.stripe.source.is_webhook_feature_flag_enabled", return_value=True)
@patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.create_webhook")
def test_create_webhook_saves_extra_inputs(self, mock_create_webhook, _mock_flag):
- from posthog.models.hog_functions.hog_function import HogFunction
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
mock_create_webhook.return_value = self._webhook_result(extra_inputs={"signing_secret": "whsec_test123"})
@@ -5523,7 +5525,7 @@ class TestCreateWebhook(APIBaseTest):
@patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.webhook_inputs_updated")
@patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.create_webhook")
def test_update_webhook_inputs(self, mock_create_webhook, mock_inputs_updated, _mock_flag):
- from posthog.models.hog_functions.hog_function import HogFunction
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
mock_create_webhook.return_value = self._webhook_result()
mock_inputs_updated.return_value = (True, None)
@@ -5661,7 +5663,7 @@ class TestCreateWebhook(APIBaseTest):
):
from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType
- from posthog.models.hog_functions.hog_function import HogFunction
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
mock_create_webhook.return_value = self._webhook_result(extra_inputs={"signing_secret": "whsec_initial"})
self._create_hog_function_template()
@@ -5752,7 +5754,7 @@ class TestCreateWebhook(APIBaseTest):
# have zero schemas on webhook sync (e.g. Stripe with all schemas on incremental
# polling) and still need its signing secret rotated to keep the existing
# webhook hog function authenticating deliveries.
- from posthog.models.hog_functions.hog_function import HogFunction
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
mock_create_webhook.return_value = self._webhook_result()
mock_inputs_updated.return_value = (True, None)
@@ -5786,9 +5788,10 @@ class TestCreateWebhook(APIBaseTest):
create_webhook endpoint must populate schema_mapping for every webhook schema.
Webhook schemas have sync_type='webhook' (not 'incremental')."""
mock_create_webhook.return_value = self._webhook_result()
- from posthog.models.hog_functions.hog_function import HogFunction
from posthog.temporal.data_imports.sources.stripe.constants import RESOURCE_TO_STRIPE_OBJECT_TYPE
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+
self._create_hog_function_template()
source = self._create_stripe_source()
customer_schema = self._create_webhook_schema(source, STRIPE_CUSTOMER_RESOURCE_NAME)
@@ -6148,7 +6151,7 @@ class TestWebhookInfo(APIBaseTest):
)
def _create_hog_function(self, source: ExternalDataSource, enabled: bool = True):
- from posthog.models.hog_functions.hog_function import HogFunction
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
return HogFunction.objects.create(
team=self.team,
@@ -6278,7 +6281,7 @@ class TestWebhookInfo(APIBaseTest):
"posthog.temporal.data_imports.sources.stripe.source.StripeSource.get_external_webhook_info", return_value=None
)
def test_webhook_info_masks_set_secret_input(self, _mock_info, _mock_flag):
- from posthog.models.hog_functions.hog_function import HogFunction
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
source = self._create_stripe_source()
hog_function = self._create_hog_function(source)
@@ -6330,7 +6333,7 @@ class TestDeleteWebhook(APIBaseTest):
)
def _create_hog_function(self, source: ExternalDataSource, enabled: bool = True):
- from posthog.models.hog_functions.hog_function import HogFunction
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
return HogFunction.objects.create(
team=self.team,
@@ -6494,9 +6497,10 @@ class TestDestroySourceCleansUpWebhook(APIBaseTest):
@patch("posthog.temporal.data_imports.sources.stripe.source.is_webhook_feature_flag_enabled", return_value=True)
@patch("posthog.temporal.data_imports.sources.stripe.source.StripeSource.delete_webhook")
def test_destroy_source_deletes_webhook_and_hog_function(self, mock_delete_webhook, _mock_flag):
- from posthog.models.hog_functions.hog_function import HogFunction
from posthog.temporal.data_imports.sources.common.base import WebhookDeletionResult
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+
mock_delete_webhook.return_value = WebhookDeletionResult(success=True)
source = ExternalDataSource.objects.create(
@@ -6539,7 +6543,7 @@ class TestDestroySourceCleansUpWebhook(APIBaseTest):
def test_destroy_source_continues_if_webhook_cleanup_fails(
self, _mock_delete_webhook, mock_capture_exception, _mock_flag
):
- from posthog.models.hog_functions.hog_function import HogFunction
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
source = ExternalDataSource.objects.create(
team_id=self.team.pk,
diff --git a/products/data_warehouse/backend/external_data_source/test/test_webhooks.py b/products/data_warehouse/backend/external_data_source/test/test_webhooks.py
index 6ceb7c6e3bb9..abac89db1881 100644
--- a/products/data_warehouse/backend/external_data_source/test/test_webhooks.py
+++ b/products/data_warehouse/backend/external_data_source/test/test_webhooks.py
@@ -4,9 +4,9 @@ import pytest
from unittest.mock import MagicMock, patch
from posthog.models import Organization, Team
-from posthog.models.hog_function_template import HogFunctionTemplate
from posthog.temporal.data_imports.sources.common.base import WebhookCreationResult
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
from products.data_warehouse.backend.external_data_source.webhooks import (
create_and_register_webhook,
get_or_create_webhook_hog_function,
diff --git a/products/data_warehouse/backend/external_data_source/webhooks.py b/products/data_warehouse/backend/external_data_source/webhooks.py
index 5a07a85c8b0e..07919a72e52a 100644
--- a/products/data_warehouse/backend/external_data_source/webhooks.py
+++ b/products/data_warehouse/backend/external_data_source/webhooks.py
@@ -4,8 +4,6 @@ from typing import Any
from django.conf import settings
from posthog.models import Team
-from posthog.models.hog_function_template import HogFunctionTemplate
-from posthog.models.hog_functions.hog_function import HogFunction
from posthog.temporal.data_imports.sources.common.base import (
WebhookCreationResult,
WebhookDeletionResult,
@@ -13,6 +11,8 @@ from posthog.temporal.data_imports.sources.common.base import (
)
from posthog.temporal.data_imports.sources.common.config import Config
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
diff --git a/products/error_tracking/backend/api/test/test_recommendations.py b/products/error_tracking/backend/api/test/test_recommendations.py
index a9f422b91464..c93c4bd7ed17 100644
--- a/products/error_tracking/backend/api/test/test_recommendations.py
+++ b/products/error_tracking/backend/api/test/test_recommendations.py
@@ -9,9 +9,9 @@ from django.utils import timezone
from rest_framework import status
-from posthog.models.hog_functions.hog_function import HogFunction
from posthog.models.utils import uuid7
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.error_tracking.backend.models import (
ErrorTrackingIssue,
ErrorTrackingIssueFingerprintV2,
diff --git a/products/error_tracking/backend/recommendations/alerts.py b/products/error_tracking/backend/recommendations/alerts.py
index aedde2d60134..c5b8aa246a7e 100644
--- a/products/error_tracking/backend/recommendations/alerts.py
+++ b/products/error_tracking/backend/recommendations/alerts.py
@@ -4,9 +4,10 @@ from typing import Any
from django.db.models import Q
-from posthog.models.hog_functions.hog_function import HogFunction, HogFunctionType
from posthog.models.team.team import Team
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType
+
from .base import Recommendation
ALERT_TRIGGERS: list[dict[str, str]] = [
diff --git a/products/logs/backend/alerts_api.py b/products/logs/backend/alerts_api.py
index 718112b95a36..375507ed4a50 100644
--- a/products/logs/backend/alerts_api.py
+++ b/products/logs/backend/alerts_api.py
@@ -19,18 +19,18 @@ from rest_framework.response import Response
from posthog.schema import LogsAlertFilters
-from posthog.api.hog_function import HogFunctionSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.event_usage import report_user_action
from posthog.models.activity_logging.activity_log import Change, Detail, changes_between, log_activity
-from posthog.models.hog_functions.hog_function import HogFunction
from posthog.models.signals import model_activity_signal, mutable_receiver
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.permissions import PostHogFeatureFlagPermission
from posthog.utils import relative_date_parse
+from products.cdp.backend.api.hog_function import HogFunctionSerializer
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.logs.backend.alert_check_query import AlertCheckQuery, BucketedCount
from products.logs.backend.alert_destinations import EVENT_KINDS, EventKind, build_slack_config, build_webhook_config
from products.logs.backend.alert_state_machine import (
diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.py
index 408b74414c35..1629b9d3f037 100644
--- a/products/logs/backend/test/test_alerts_api.py
+++ b/products/logs/backend/test/test_alerts_api.py
@@ -725,7 +725,8 @@ class TestLogsAlertAPI(APIBaseTest):
# which looks up a HogFunctionTemplate by template_id. Seed Slack + webhook.
from posthog.cdp.templates.hog_function_template import sync_template_to_db
from posthog.cdp.templates.slack.template_slack import template as template_slack
- from posthog.models.hog_function_template import HogFunctionTemplate
+
+ from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
sync_template_to_db(template_slack)
HogFunctionTemplate.objects.get_or_create(
@@ -747,7 +748,7 @@ class TestLogsAlertAPI(APIBaseTest):
@patch("products.logs.backend.alerts_api.report_user_action")
def test_create_slack_destination_creates_one_hog_function_per_event_kind(self, mock_report):
self._sync_destination_templates()
- from posthog.models.hog_functions.hog_function import HogFunction
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
created = self._create_via_api()
response = self.client.post(
@@ -791,7 +792,7 @@ class TestLogsAlertAPI(APIBaseTest):
assert len(reset_calls) == 1
def test_create_webhook_destination_creates_one_hog_function_per_event_kind(self):
- from posthog.models.hog_functions.hog_function import HogFunction
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
self._sync_destination_templates()
created = self._create_via_api()
@@ -843,7 +844,7 @@ class TestLogsAlertAPI(APIBaseTest):
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_delete_destination_removes_hog_functions(self):
- from posthog.models.hog_functions.hog_function import HogFunction
+ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
self._sync_destination_templates()
created = self._create_via_api()
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index 57caf1f63b85..731e6acee54a 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -1395,57 +1395,6 @@ export interface _LogsValuesResponseApi {
refreshing: boolean
}
-/**
- * * `SYSTEM` - SYSTEM
- * `PLUGIN` - PLUGIN
- * `CONSOLE` - CONSOLE
- */
-export type PluginLogEntrySourceEnumApi = (typeof PluginLogEntrySourceEnumApi)[keyof typeof PluginLogEntrySourceEnumApi]
-
-export const PluginLogEntrySourceEnumApi = {
- System: 'SYSTEM',
- Plugin: 'PLUGIN',
- Console: 'CONSOLE',
-} as const
-
-/**
- * * `DEBUG` - DEBUG
- * `LOG` - LOG
- * `INFO` - INFO
- * `WARN` - WARN
- * `ERROR` - ERROR
- */
-export type PluginLogEntryTypeEnumApi = (typeof PluginLogEntryTypeEnumApi)[keyof typeof PluginLogEntryTypeEnumApi]
-
-export const PluginLogEntryTypeEnumApi = {
- Debug: 'DEBUG',
- Log: 'LOG',
- Info: 'INFO',
- Warn: 'WARN',
- Error: 'ERROR',
-} as const
-
-export interface PluginLogEntryApi {
- id: string
- team_id: number
- plugin_id: number
- plugin_config_id: number
- timestamp: string
- source: PluginLogEntrySourceEnumApi
- type: PluginLogEntryTypeEnumApi
- message: string
- instance_id: string
-}
-
-export interface PaginatedPluginLogEntryListApi {
- count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
- results: PluginLogEntryApi[]
-}
-
export type LogsViewsListParams = {
/**
* Number of results to return per page.
@@ -1596,14 +1545,3 @@ export const LogsValuesRetrieveAttributeType = {
Log: 'log',
Resource: 'resource',
} as const
-
-export type PluginConfigsLogsListParams = {
- /**
- * Number of results to return per page.
- */
- limit?: number
- /**
- * The initial index from which to return the results.
- */
- offset?: number
-}
diff --git a/products/logs/frontend/generated/api.ts b/products/logs/frontend/generated/api.ts
index 23a8e00d4ca6..ccd6a6b86337 100644
--- a/products/logs/frontend/generated/api.ts
+++ b/products/logs/frontend/generated/api.ts
@@ -33,11 +33,9 @@ import type {
PaginatedLogsAlertEventListApi,
PaginatedLogsSamplingRuleListApi,
PaginatedLogsViewListApi,
- PaginatedPluginLogEntryListApi,
PatchedLogsAlertConfigurationApi,
PatchedLogsSamplingRuleApi,
PatchedLogsViewApi,
- PluginConfigsLogsListParams,
_LogsAttributesResponseApi,
_LogsCountRangesRequestApi,
_LogsCountRangesResponseApi,
@@ -753,38 +751,6 @@ export const logsValuesRetrieve = async (
})
}
-export const getPluginConfigsLogsListUrl = (
- projectId: string,
- pluginConfigId: number,
- params?: PluginConfigsLogsListParams
-) => {
- 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}/plugin_configs/${pluginConfigId}/logs/?${stringifiedParams}`
- : `/api/projects/${projectId}/plugin_configs/${pluginConfigId}/logs/`
-}
-
-export const pluginConfigsLogsList = async (
- projectId: string,
- pluginConfigId: number,
- params?: PluginConfigsLogsListParams,
- options?: RequestInit
-): Promise<PaginatedPluginLogEntryListApi> => {
- return apiMutator<PaginatedPluginLogEntryListApi>(getPluginConfigsLogsListUrl(projectId, pluginConfigId, params), {
- ...options,
- method: 'GET',
- })
-}
-
export const getTasksRunsLogsRetrieveUrl = (projectId: string, taskId: string, id: string) => {
return `/api/projects/${projectId}/tasks/${taskId}/runs/${id}/logs/`
}
diff --git a/products/ruff.toml b/products/ruff.toml
index 1143fe22a10d..6f7d8c9806a9 100644
--- a/products/ruff.toml
+++ b/products/ruff.toml
@@ -21,6 +21,7 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]
"actions/backend/**" = ["ANN"]
"alerts/backend/**" = ["ANN"]
"batch_exports/backend/**" = ["ANN"]
+"cdp/backend/**" = ["ANN"]
"conversations/backend/**" = ["ANN"]
"customer_analytics/backend/**" = ["ANN"]
"dashboards/backend/**" = ["ANN"]
diff --git a/products/workflows/backend/admin/__init__.py b/products/workflows/backend/admin/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/admin/admins/hog_flow_admin.py b/products/workflows/backend/admin/hog_flow_admin.py
similarity index 96%
rename from posthog/admin/admins/hog_flow_admin.py
rename to products/workflows/backend/admin/hog_flow_admin.py
index 52ae0b3f2ede..d5c26caa36e1 100644
--- a/posthog/admin/admins/hog_flow_admin.py
+++ b/products/workflows/backend/admin/hog_flow_admin.py
@@ -2,8 +2,7 @@ from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html
-from posthog.models.hog_flow.hog_flow import HogFlow
-
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
from products.workflows.backend.models.hog_flow_schedule import HogFlowSchedule
diff --git a/posthog/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
similarity index 98%
rename from posthog/api/hog_flow.py
rename to products/workflows/backend/api/hog_flow.py
index 7542931bc2c9..fe45d8b52ce1 100644
--- a/posthog/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -20,7 +20,6 @@ from rest_framework.serializers import BaseSerializer
from posthog.api.app_metrics2 import AppMetricsMixin
from posthog.api.documentation import _FallbackSerializer
-from posthog.api.hog_flow_batch_job import HogFlowBatchJobSerializer
from posthog.api.log_entries import LogEntryMixin
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
@@ -33,15 +32,16 @@ from posthog.cdp.validation import (
generate_template_bytecode,
)
from posthog.models import Team
-from posthog.models.hog_flow.hog_flow import BILLABLE_ACTION_TYPES, HogFlow
-from posthog.models.hog_function_template import HogFunctionTemplate
from posthog.plugins.plugin_server_api import create_hog_flow_invocation_test, create_hog_flow_scheduled_invocation
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
from products.feature_flags.backend.user_blast_radius import (
PERSON_BATCH_SIZE,
get_user_blast_radius,
get_user_blast_radius_persons,
)
+from products.workflows.backend.api.hog_flow_batch_job import HogFlowBatchJobSerializer
+from products.workflows.backend.models.hog_flow.hog_flow import BILLABLE_ACTION_TYPES, HogFlow
from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJob
from products.workflows.backend.models.hog_flow_schedule import SCHEDULED_TRIGGER_TYPES, HogFlowSchedule
from products.workflows.backend.utils.rrule_utils import compute_next_occurrences, validate_rrule
@@ -716,11 +716,11 @@ class InternalHogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMi
Internal endpoint called by the scheduler service to process due schedules.
Handles both executing due schedules and initializing next_run_at for new ones.
"""
- from django.db import transaction
+ from django.db import transaction # noqa: PLC0415
- from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJob
- from products.workflows.backend.models.hog_flow_schedule import HogFlowSchedule
- from products.workflows.backend.utils.rrule_utils import compute_next_occurrences
+ from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJob # noqa: PLC0415
+ from products.workflows.backend.models.hog_flow_schedule import HogFlowSchedule # noqa: PLC0415
+ from products.workflows.backend.utils.rrule_utils import compute_next_occurrences # noqa: PLC0415
def advance_next_run(schedule, after=None):
"""Compute and set next_run_at, or mark completed if RRULE is exhausted."""
diff --git a/posthog/api/hog_flow_batch_job.py b/products/workflows/backend/api/hog_flow_batch_job.py
similarity index 100%
rename from posthog/api/hog_flow_batch_job.py
rename to products/workflows/backend/api/hog_flow_batch_job.py
diff --git a/posthog/api/hog_flow_template.py b/products/workflows/backend/api/hog_flow_template.py
similarity index 97%
rename from posthog/api/hog_flow_template.py
rename to products/workflows/backend/api/hog_flow_template.py
index 7b53a9fb3064..72fad1481793 100644
--- a/posthog/api/hog_flow_template.py
+++ b/products/workflows/backend/api/hog_flow_template.py
@@ -11,15 +11,15 @@ from rest_framework.permissions import SAFE_METHODS, BasePermission
from rest_framework.request import Request
from rest_framework.response import Response
-from posthog.api.hog_flow import HogFlowMaskingSerializer, HogFlowVariableSerializer
from posthog.api.log_entries import LogEntryMixin
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.cdp.validation import HogFunctionFiltersSerializer
from posthog.models import User
from posthog.models.activity_logging.activity_log import Detail, log_activity
-from posthog.models.hog_flow.hog_flow_template import HogFlowTemplate
-from posthog.models.hog_function_template import HogFunctionTemplate
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
+from products.workflows.backend.api.hog_flow import HogFlowMaskingSerializer, HogFlowVariableSerializer
+from products.workflows.backend.models.hog_flow.hog_flow_template import HogFlowTemplate
from products.workflows.backend.templates import get_global_template_by_id, load_global_templates
logger = structlog.get_logger(__name__)
@@ -157,7 +157,7 @@ class HogFlowTemplateSerializer(serializers.ModelSerializer):
@extend_schema_field({"type": "object", "nullable": True})
def get_created_by(self, obj):
if obj.created_by:
- from posthog.api.shared import UserBasicSerializer
+ from posthog.api.shared import UserBasicSerializer # noqa: PLC0415
return UserBasicSerializer(obj.created_by).data
return None
diff --git a/products/workflows/backend/api/test/__init__.py b/products/workflows/backend/api/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.py
similarity index 99%
rename from posthog/api/test/test_hog_flow.py
rename to products/workflows/backend/api/test/test_hog_flow.py
index ab558a9b0f50..d9d12a76baed 100644
--- a/posthog/api/test/test_hog_flow.py
+++ b/products/workflows/backend/api/test/test_hog_flow.py
@@ -6,11 +6,12 @@ from unittest.mock import patch
from parameterized import parameterized
from rest_framework import status
-from posthog.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES
from posthog.cdp.templates.hog_function_template import sync_template_to_db
from posthog.cdp.templates.slack.template_slack import template as template_slack
from posthog.models import Organization, Team, User
-from posthog.models.hog_flow.hog_flow import HogFlow
+
+from products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
webhook_template = MOCK_NODE_TEMPLATES[0]
@@ -693,7 +694,7 @@ class TestHogFlowAPI(APIBaseTest):
}
def test_hog_flow_user_blast_radius_requires_filters(self):
- with patch("posthog.api.hog_flow.get_user_blast_radius") as mock_get_user_blast_radius:
+ with patch("products.workflows.backend.api.hog_flow.get_user_blast_radius") as mock_get_user_blast_radius:
response = self.client.post(f"/api/projects/{self.team.id}/hog_flows/user_blast_radius", {})
assert response.status_code == 400, response.json()
@@ -701,8 +702,8 @@ class TestHogFlowAPI(APIBaseTest):
mock_get_user_blast_radius.assert_not_called()
def test_hog_flow_user_blast_radius_returns_counts(self):
- with patch("posthog.api.hog_flow.get_user_blast_radius") as mock_get_user_blast_radius:
- from products.feature_flags.backend.user_blast_radius import BlastRadiusResult
+ with patch("products.workflows.backend.api.hog_flow.get_user_blast_radius") as mock_get_user_blast_radius:
+ from products.feature_flags.backend.user_blast_radius import BlastRadiusResult # noqa: PLC0415
mock_get_user_blast_radius.return_value = BlastRadiusResult(affected=4, total=10)
diff --git a/posthog/api/test/test_hog_flow_template.py b/products/workflows/backend/api/test/test_hog_flow_template.py
similarity index 99%
rename from posthog/api/test/test_hog_flow_template.py
rename to products/workflows/backend/api/test/test_hog_flow_template.py
index 0d2c2bd32503..73c7f0b90fcb 100644
--- a/posthog/api/test/test_hog_flow_template.py
+++ b/products/workflows/backend/api/test/test_hog_flow_template.py
@@ -4,13 +4,13 @@ from posthog.test.base import APIBaseTest
from rest_framework import status
-from posthog.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES
from posthog.cdp.templates.hog_function_template import sync_template_to_db
from posthog.cdp.templates.slack.template_slack import template as template_slack
from posthog.models import Organization, Team, User
-from posthog.models.hog_flow.hog_flow_template import HogFlowTemplate
-from posthog.models.hog_function_template import HogFunctionTemplate
+from products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
+from products.workflows.backend.models.hog_flow.hog_flow_template import HogFlowTemplate
from products.workflows.backend.templates import clear_template_cache, load_global_templates
webhook_template = MOCK_NODE_TEMPLATES[0]
diff --git a/products/workflows/backend/migrations/0007_migrate_hog_flow_models.py b/products/workflows/backend/migrations/0007_migrate_hog_flow_models.py
new file mode 100644
index 000000000000..ff2425065bc7
--- /dev/null
+++ b/products/workflows/backend/migrations/0007_migrate_hog_flow_models.py
@@ -0,0 +1,216 @@
+# Generated by Django 5.2.14 on 2026-05-27 13:00
+
+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
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1185_fix_non_list_test_account_filters"),
+ ("workflows", "0006_drop_hogflowbatchjob_scheduled_at_column"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.CreateModel(
+ name="HogFlow",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.UUIDT,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("name", models.CharField(blank=True, max_length=400, null=True)),
+ ("description", models.TextField(blank=True, default="")),
+ ("version", models.IntegerField(default=1)),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("draft", "Draft"),
+ ("active", "Active"),
+ ("archived", "Archived"),
+ ],
+ default="draft",
+ max_length=20,
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ("trigger", models.JSONField(default=dict)),
+ ("trigger_masking", models.JSONField(blank=True, null=True)),
+ ("conversion", models.JSONField(blank=True, null=True)),
+ (
+ "exit_condition",
+ models.CharField(
+ choices=[
+ ("exit_on_conversion", "Conversion"),
+ ("exit_on_trigger_not_matched", "Trigger Not Matched"),
+ (
+ "exit_on_trigger_not_matched_or_conversion",
+ "Trigger Not Matched Or Conversion",
+ ),
+ ("exit_only_at_end", "Only At End"),
+ ],
+ default="exit_on_conversion",
+ max_length=100,
+ ),
+ ),
+ ("edges", models.JSONField(default=dict)),
+ ("actions", models.JSONField(default=dict)),
+ (
+ "abort_action",
+ models.CharField(blank=True, max_length=400, null=True),
+ ),
+ ("variables", models.JSONField(blank=True, default=list, null=True)),
+ (
+ "billable_action_types",
+ models.JSONField(blank=True, default=list, null=True),
+ ),
+ ("draft", models.JSONField(blank=True, null=True)),
+ ("draft_updated_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),
+ ),
+ ],
+ options={
+ "db_table": "posthog_hogflow",
+ },
+ ),
+ migrations.AlterField(
+ model_name="hogflowbatchjob",
+ name="hog_flow",
+ field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to="workflows.hogflow"),
+ ),
+ migrations.AlterField(
+ model_name="hogflowschedule",
+ name="hog_flow",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="schedules",
+ to="workflows.hogflow",
+ ),
+ ),
+ migrations.CreateModel(
+ name="HogFlowTemplate",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.UUIDT,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("name", models.CharField(max_length=400)),
+ ("description", models.TextField(blank=True, default="")),
+ ("image_url", models.CharField(blank=True, max_length=8201, null=True)),
+ (
+ "tags",
+ django.contrib.postgres.fields.ArrayField(
+ base_field=models.CharField(max_length=255),
+ blank=True,
+ default=list,
+ size=None,
+ ),
+ ),
+ (
+ "scope",
+ models.CharField(
+ choices=[
+ ("team", "Only team"),
+ ("organization", "Organization"),
+ ("global", "Global"),
+ ],
+ max_length=24,
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ("trigger", models.JSONField(default=dict)),
+ ("trigger_masking", models.JSONField(blank=True, null=True)),
+ ("conversion", models.JSONField(blank=True, null=True)),
+ (
+ "exit_condition",
+ models.CharField(
+ choices=[
+ ("exit_on_conversion", "Conversion"),
+ ("exit_on_trigger_not_matched", "Trigger Not Matched"),
+ (
+ "exit_on_trigger_not_matched_or_conversion",
+ "Trigger Not Matched Or Conversion",
+ ),
+ ("exit_only_at_end", "Only At End"),
+ ],
+ default="exit_on_conversion",
+ max_length=100,
+ ),
+ ),
+ ("edges", models.JSONField(default=dict)),
+ ("actions", models.JSONField(default=dict)),
+ (
+ "abort_action",
+ models.CharField(blank=True, max_length=400, null=True),
+ ),
+ ("variables", models.JSONField(blank=True, default=list, null=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),
+ ),
+ ],
+ options={
+ "db_table": "hogflow_templates",
+ },
+ ),
+ migrations.AddIndex(
+ model_name="hogflow",
+ index=models.Index(fields=["status", "team"], name="posthog_hog_status_53a054_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="hogflow",
+ index=models.Index(fields=["version", "team"], name="posthog_hog_version_c1677f_idx"),
+ ),
+ migrations.AddConstraint(
+ model_name="hogflow",
+ constraint=models.UniqueConstraint(
+ fields=("team", "version", "id"), name="unique_version_per_flow"
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="hogflowtemplate",
+ index=models.Index(fields=["team"], name="hogflow_tem_team_id_cb8b2b_idx"),
+ ),
+ ],
+ database_operations=[],
+ ),
+ ]
diff --git a/products/workflows/backend/migrations/max_migration.txt b/products/workflows/backend/migrations/max_migration.txt
index bf0033979825..94bb3e7dff70 100644
--- a/products/workflows/backend/migrations/max_migration.txt
+++ b/products/workflows/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0006_drop_hogflowbatchjob_scheduled_at_column
+0007_migrate_hog_flow_models
diff --git a/products/workflows/backend/models/__init__.py b/products/workflows/backend/models/__init__.py
index 3a98778f8a8b..f1fe3d358c67 100644
--- a/products/workflows/backend/models/__init__.py
+++ b/products/workflows/backend/models/__init__.py
@@ -1,3 +1,5 @@
+from .hog_flow.hog_flow import HogFlow
+from .hog_flow.hog_flow_template import HogFlowTemplate
from .hog_flow_batch_job import HogFlowBatchJob
-__all__ = ["HogFlowBatchJob"]
+__all__ = ["HogFlow", "HogFlowBatchJob", "HogFlowTemplate"]
diff --git a/posthog/models/hog_flow/__init__.py b/products/workflows/backend/models/hog_flow/__init__.py
similarity index 100%
rename from posthog/models/hog_flow/__init__.py
rename to products/workflows/backend/models/hog_flow/__init__.py
diff --git a/posthog/models/hog_flow/hog_flow.py b/products/workflows/backend/models/hog_flow/hog_flow.py
similarity index 89%
rename from posthog/models/hog_flow/hog_flow.py
rename to products/workflows/backend/models/hog_flow/hog_flow.py
index 985b5d77990f..3c691893c41c 100644
--- a/posthog/models/hog_flow/hog_flow.py
+++ b/products/workflows/backend/models/hog_flow/hog_flow.py
@@ -33,6 +33,7 @@ class HogFlow(UUIDTModel):
"""
class Meta:
+ db_table = "posthog_hogflow"
indexes = [
models.Index(fields=["status", "team"]),
models.Index(fields=["version", "team"]),
@@ -56,11 +57,11 @@ class HogFlow(UUIDTModel):
name = models.CharField(max_length=400, null=True, blank=True)
description = models.TextField(blank=True, default="")
version = models.IntegerField(default=1)
- team = models.ForeignKey("Team", on_delete=models.CASCADE)
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
status = models.CharField(max_length=20, choices=State, default=State.DRAFT)
created_at = models.DateTimeField(auto_now_add=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)
updated_at = models.DateTimeField(auto_now=True)
trigger = models.JSONField(default=dict)
@@ -92,15 +93,13 @@ def hog_flow_saved(sender, instance: HogFlow, created, **kwargs):
@receiver(post_save, sender=Action)
def action_saved_for_hog_flows(sender, instance: Action, created, **kwargs):
- # Whenever an action is saved we want to load all hog flows using it
- # and trigger a refresh
- from posthog.tasks.hog_flows import refresh_affected_hog_flows
+ from products.workflows.backend.tasks.hog_flows import refresh_affected_hog_flows # noqa: PLC0415
refresh_affected_hog_flows.delay(action_id=instance.id)
@receiver(post_save, sender=Team)
def team_saved_for_hog_flows(sender, instance: Team, created, **kwargs):
- from posthog.tasks.hog_flows import refresh_affected_hog_flows
+ from products.workflows.backend.tasks.hog_flows import refresh_affected_hog_flows # noqa: PLC0415
refresh_affected_hog_flows.delay(team_id=instance.id)
diff --git a/posthog/models/hog_flow/hog_flow_template.py b/products/workflows/backend/models/hog_flow/hog_flow_template.py
similarity index 92%
rename from posthog/models/hog_flow/hog_flow_template.py
rename to products/workflows/backend/models/hog_flow/hog_flow_template.py
index e2fd5d8d4e9b..e1ad0868cac3 100644
--- a/posthog/models/hog_flow/hog_flow_template.py
+++ b/products/workflows/backend/models/hog_flow/hog_flow_template.py
@@ -42,10 +42,10 @@ class HogFlowTemplate(UUIDTModel):
image_url = models.CharField(max_length=8201, null=True, blank=True)
tags = ArrayField(models.CharField(max_length=255), blank=True, default=list)
scope = models.CharField(max_length=24, choices=Scope)
- team = models.ForeignKey("Team", on_delete=models.CASCADE)
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=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)
updated_at = models.DateTimeField(auto_now=True)
trigger = models.JSONField(default=dict)
diff --git a/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.py b/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.py
index fa8bd76cd7b4..76623d93708e 100644
--- a/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.py
+++ b/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.py
@@ -29,7 +29,7 @@ class HogFlowBatchJob(RootTeamMixin, UUIDTModel):
FAILED = "failed"
team = models.ForeignKey("posthog.Team", on_delete=models.DO_NOTHING)
- hog_flow = models.ForeignKey("posthog.HogFlow", on_delete=models.DO_NOTHING)
+ hog_flow = models.ForeignKey("workflows.HogFlow", on_delete=models.DO_NOTHING)
variables = models.JSONField(default=dict)
filters = models.JSONField(default=dict)
status = models.CharField(max_length=20, choices=State, default=State.QUEUED)
diff --git a/products/workflows/backend/models/hog_flow_schedule/hog_flow_schedule.py b/products/workflows/backend/models/hog_flow_schedule/hog_flow_schedule.py
index 318ceb746386..a7d6dfc71fc8 100644
--- a/products/workflows/backend/models/hog_flow_schedule/hog_flow_schedule.py
+++ b/products/workflows/backend/models/hog_flow_schedule/hog_flow_schedule.py
@@ -19,7 +19,7 @@ class HogFlowSchedule(RootTeamMixin, UUIDTModel):
COMPLETED = "completed" # RRULE exhausted (COUNT/UNTIL reached)
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
- hog_flow = models.ForeignKey("posthog.HogFlow", on_delete=models.CASCADE, related_name="schedules")
+ hog_flow = models.ForeignKey("workflows.HogFlow", on_delete=models.CASCADE, related_name="schedules")
rrule = models.TextField()
starts_at = models.DateTimeField()
timezone = models.CharField(max_length=64, default="UTC")
diff --git a/products/workflows/backend/tasks/__init__.py b/products/workflows/backend/tasks/__init__.py
new file mode 100644
index 000000000000..50b82e95f50b
--- /dev/null
+++ b/products/workflows/backend/tasks/__init__.py
@@ -0,0 +1,3 @@
+from . import hog_flows
+
+__all__ = ["hog_flows"]
diff --git a/posthog/tasks/hog_flows.py b/products/workflows/backend/tasks/hog_flows.py
similarity index 96%
rename from posthog/tasks/hog_flows.py
rename to products/workflows/backend/tasks/hog_flows.py
index 74f045a8cee2..2cf105540e8d 100644
--- a/posthog/tasks/hog_flows.py
+++ b/products/workflows/backend/tasks/hog_flows.py
@@ -10,6 +10,7 @@ from posthog.scoping_audit import skip_team_scope_audit
from posthog.tasks.utils import CeleryQueue
from products.actions.backend.models.action import Action
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
logger = get_logger(__name__)
@@ -17,8 +18,6 @@ logger = get_logger(__name__)
@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)
@skip_team_scope_audit
def refresh_affected_hog_flows(team_id: Optional[int] = None, action_id: Optional[int] = None) -> int:
- from posthog.models.hog_flow.hog_flow import HogFlow
-
affected_hog_flows: list[HogFlow] = []
if action_id:
diff --git a/posthog/models/test/test_hog_flow.py b/products/workflows/backend/test/test_hog_flow.py
similarity index 73%
rename from posthog/models/test/test_hog_flow.py
rename to products/workflows/backend/test/test_hog_flow.py
index d6cf1f101201..cb6b1ddf0b5a 100644
--- a/posthog/models/test/test_hog_flow.py
+++ b/products/workflows/backend/test/test_hog_flow.py
@@ -2,10 +2,10 @@ from unittest.mock import patch
from django.test import TestCase
-from posthog.models.hog_flow.hog_flow import HogFlow
from posthog.models.user import User
from products.actions.backend.models.action import Action
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
class TestHogFlow(TestCase):
@@ -16,17 +16,17 @@ class TestHogFlow(TestCase):
self.user = user
self.org = org
- @patch("posthog.models.hog_flow.hog_flow.reload_hog_flows_on_workers")
+ @patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers")
def test_hog_flow_saved_receiver(self, mock_reload):
hog_flow = HogFlow.objects.create(name="Test Flow", team=self.team)
mock_reload.assert_called_once_with(team_id=self.team.id, hog_flow_ids=[str(hog_flow.id)])
- @patch("posthog.tasks.hog_flows.refresh_affected_hog_flows.delay")
+ @patch("products.workflows.backend.tasks.hog_flows.refresh_affected_hog_flows.delay")
def test_action_saved_receiver(self, mock_refresh):
action = Action.objects.create(team=self.team, name="Test Action")
mock_refresh.assert_called_once_with(action_id=action.id)
- @patch("posthog.tasks.hog_flows.refresh_affected_hog_flows.delay")
+ @patch("products.workflows.backend.tasks.hog_flows.refresh_affected_hog_flows.delay")
def test_team_saved_receiver(self, mock_refresh):
self.team.save()
mock_refresh.assert_called_once_with(team_id=self.team.id)
diff --git a/products/workflows/backend/test/test_hog_flow_schedule.py b/products/workflows/backend/test/test_hog_flow_schedule.py
index b4eb18430cbe..9eb6b0d137d6 100644
--- a/products/workflows/backend/test/test_hog_flow_schedule.py
+++ b/products/workflows/backend/test/test_hog_flow_schedule.py
@@ -9,8 +9,7 @@ from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
-from posthog.models.hog_flow.hog_flow import HogFlow
-
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJob
from products.workflows.backend.models.hog_flow_schedule import HogFlowSchedule
@@ -391,7 +390,7 @@ class TestProcessDueSchedules(APIBaseTest):
@override_settings(INTERNAL_API_SECRET="test-secret")
[email protected]("posthog.api.hog_flow.create_hog_flow_scheduled_invocation")
[email protected]("products.workflows.backend.api.hog_flow.create_hog_flow_scheduled_invocation")
class TestProcessDueScheduleTriggers(APIBaseTest):
INTERNAL_URL = "/api/internal/hog_flows/process_due_schedules"
diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.ts
index 64e44eda0bdc..41ea54ef83fc 100644
--- a/products/workflows/frontend/generated/api.ts
+++ b/products/workflows/frontend/generated/api.ts
@@ -47,6 +47,21 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
}
: DistributeReadOnlyOverUnions<T>
+export const getInternalHogFlowsProcessDueSchedulesCreateUrl = () => {
+ return `/api/internal/hog_flows/process_due_schedules`
+}
+
+/**
+ * Internal endpoint called by the scheduler service to process due schedules.
+Handles both executing due schedules and initializing next_run_at for new ones.
+ */
+export const internalHogFlowsProcessDueSchedulesCreate = async (options?: RequestInit): Promise<void> => {
+ return apiMutator<void>(getInternalHogFlowsProcessDueSchedulesCreateUrl(), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getHogFlowTemplatesListUrl = (projectId: string, params?: HogFlowTemplatesListParams) => {
const normalizedParams = new URLSearchParams()
@@ -568,3 +583,36 @@ export const hogFlowsUserBlastRadiusCreate = async (
body: JSON.stringify(blastRadiusRequestApi),
})
}
+
+export const getInternalHogFlowsUserBlastRadiusCreateUrl = (teamId: string) => {
+ return `/api/projects/${teamId}/internal/hog_flows/user_blast_radius`
+}
+
+/**
+ * Internal endpoint for Node.js services to query user blast radius.
+Requires Bearer token authentication via INTERNAL_API_SECRET.
+ */
+export const internalHogFlowsUserBlastRadiusCreate = async (teamId: string, options?: RequestInit): Promise<void> => {
+ return apiMutator<void>(getInternalHogFlowsUserBlastRadiusCreateUrl(teamId), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getInternalHogFlowsUserBlastRadiusPersonsCreateUrl = (teamId: string) => {
+ return `/api/projects/${teamId}/internal/hog_flows/user_blast_radius_persons`
+}
+
+/**
+ * Internal endpoint for Node.js services to query user blast radius persons with pagination.
+Requires Bearer token authentication via INTERNAL_API_SECRET.
+ */
+export const internalHogFlowsUserBlastRadiusPersonsCreate = async (
+ teamId: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getInternalHogFlowsUserBlastRadiusPersonsCreateUrl(teamId), {
+ ...options,
+ method: 'POST',
+ })
+}
diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yaml
index 83a16c71a9c3..02702bee6914 100644
--- a/products/workflows/mcp/tools.yaml
+++ b/products/workflows/mcp/tools.yaml
@@ -107,6 +107,15 @@ tools:
hog-flows-user-blast-radius-create:
operation: hog_flows_user_blast_radius_create
enabled: false
+ internal-hog-flows-process-due-schedules-create:
+ operation: internal_hog_flows_process_due_schedules_create
+ enabled: false
+ internal-hog-flows-user-blast-radius-create:
+ operation: internal_hog_flows_user_blast_radius_create
+ enabled: false
+ internal-hog-flows-user-blast-radius-persons-create:
+ operation: internal_hog_flows_user_blast_radius_persons_create
+ enabled: false
workflows-get:
operation: hog_flows_retrieve
enabled: true
diff --git a/tach.toml b/tach.toml
index 55b1ec9453c3..e4cd1edf7c51 100644
--- a/tach.toml
+++ b/tach.toml
@@ -37,6 +37,7 @@ depends_on = [
"posthog",
"products.actions",
"products.alerts",
+ "products.cdp",
"products.dashboards",
"products.data_modeling",
"products.error_tracking",
@@ -65,6 +66,7 @@ depends_on = [
"products.analytics_platform",
"products.batch_exports",
"products.business_knowledge",
+ "products.cdp",
"products.conversations",
"products.customer_analytics",
"products.dashboards",
@@ -116,6 +118,7 @@ layer = "modules"
path = "products.actions"
depends_on = [
"posthog",
+ "products.cdp",
"products.experiments",
"products.feature_flags",
"products.product_analytics",
@@ -127,6 +130,7 @@ path = "products.alerts"
depends_on = [
"ee",
"posthog",
+ "products.cdp",
"products.product_analytics",
]
layer = "modules"
@@ -152,6 +156,7 @@ path = "products.cdp"
depends_on = [
"ee",
"posthog",
+ "products.actions",
]
layer = "modules"
@@ -206,6 +211,7 @@ path = "products.data_warehouse"
depends_on = [
"ee",
"posthog",
+ "products.cdp",
"products.dashboards",
"products.data_modeling",
"products.revenue_analytics", "products.warehouse_sources", "products.data_tools",
@@ -256,6 +262,7 @@ path = "products.error_tracking"
depends_on = [
"ee",
"posthog",
+ "products.cdp",
"products.notifications",
]
layer = "modules"
@@ -340,6 +347,7 @@ layer = "modules"
path = "products.logs"
depends_on = [
"posthog",
+ "products.cdp",
]
layer = "modules"
@@ -596,6 +604,9 @@ path = "products.workflows"
depends_on = [
"ee",
"posthog",
+ "products.actions",
+ "products.cdp",
+ "products.feature_flags",
]
layer = "modules"