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 alert and action models to product folders (#59224)

Julian Bez54d24c825c63
diff --git a/.semgrep/rules/idor-team-scoped-models.py b/.semgrep/rules/idor-team-scoped-models.py
index 3beb8c89f0a4..8594f7bc99b6 100644
--- a/.semgrep/rules/idor-team-scoped-models.py
+++ b/.semgrep/rules/idor-team-scoped-models.py
@@ -1,6 +1,6 @@
from django.shortcuts import get_object_or_404
-
-from posthog.models import Action, ChangeRequest, Cohort, Insight, Notebook
+from posthog.models import ChangeRequest, Cohort, Insight, Notebook
+from products.actions.backend.models.action import Action
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.project import Project
from posthog.models.user_scene_personalisation import UserScenePersonalisation
diff --git a/ee/api/rbac/test/test_access_control.py b/ee/api/rbac/test/test_access_control.py
index 04a8413fd2ba..9564c4bf67ed 100644
--- a/ee/api/rbac/test/test_access_control.py
+++ b/ee/api/rbac/test/test_access_control.py
@@ -150,8 +150,7 @@ class TestAccessControlMinimumLevelValidation(BaseAccessControlTest):
def test_action_access_level_cannot_be_below_viewer(self):
"""Test that action access level cannot be set below minimum 'viewer'"""
self._org_membership(OrganizationMembership.Level.ADMIN)
-
- from posthog.models.action import Action
+ from products.actions.backend.models.action import Action
action = Action.objects.create(team=self.team, name="test action")
@@ -165,8 +164,7 @@ class TestAccessControlMinimumLevelValidation(BaseAccessControlTest):
def test_action_access_level_accepts_viewer_and_above(self):
"""Test that action access level accepts viewer, editor, and manager"""
self._org_membership(OrganizationMembership.Level.ADMIN)
-
- from posthog.models.action import Action
+ from products.actions.backend.models.action import Action
action = Action.objects.create(team=self.team, name="test action")
diff --git a/ee/api/test/test_action.py b/ee/api/test/test_action.py
index ef0c59bd961d..93f3657a54dc 100644
--- a/ee/api/test/test_action.py
+++ b/ee/api/test/test_action.py
@@ -7,7 +7,9 @@ from posthog.test.base import APIBaseTest
from rest_framework import status
from posthog.cloud_utils import is_cloud
-from posthog.models import Action, Tag
+from posthog.models import Tag
+
+from products.actions.backend.models.action import Action
# Testing enterprise properties of actions here (i.e., tagging).
diff --git a/ee/api/test/test_hooks.py b/ee/api/test/test_hooks.py
index ca08505cc0d1..dc706f65ebc0 100644
--- a/ee/api/test/test_hooks.py
+++ b/ee/api/test/test_hooks.py
@@ -6,9 +6,10 @@ 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.action.action import Action
from posthog.models.hog_functions.hog_function import HogFunction
+from products.actions.backend.models.action import Action
+
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
diff --git a/ee/benchmarks/benchmarks.py b/ee/benchmarks/benchmarks.py
index 297d5b38c957..da72eb1b028e 100644
--- a/ee/benchmarks/benchmarks.py
+++ b/ee/benchmarks/benchmarks.py
@@ -18,7 +18,8 @@ from posthog.queries.session_recordings.session_recording_list import (
SessionRecordingList,
)
from posthog.queries.util import get_earliest_timestamp
-from posthog.models import Action, Cohort, Team, Organization
+from posthog.models import Cohort, Team, Organization
+from products.actions.backend.models.action import Action
from posthog.models.filters.session_recordings_filter import SessionRecordingsFilter
from posthog.models.filters.filter import Filter
from posthog.models.property import PropertyName, TableWithProperties
diff --git a/ee/clickhouse/models/test/test_action.py b/ee/clickhouse/models/test/test_action.py
index e997c4d46f6a..75f186e98a9b 100644
--- a/ee/clickhouse/models/test/test_action.py
+++ b/ee/clickhouse/models/test/test_action.py
@@ -7,10 +7,11 @@ from posthog.hogql.hogql import HogQLContext
from posthog.hogql.property import action_to_expr
from posthog.clickhouse.client import sync_execute
-from posthog.models.action import Action
-from posthog.models.action.util import filter_event, format_action_filter
from posthog.models.test.test_event_model import filter_by_actions_factory
+from products.actions.backend.models.action import Action
+from products.actions.backend.models.util import filter_event, format_action_filter
+
from common.hogvm.python.operation import (
HOGQL_BYTECODE_IDENTIFIER as _H,
HOGQL_BYTECODE_VERSION,
diff --git a/ee/clickhouse/models/test/test_cohort.py b/ee/clickhouse/models/test/test_cohort.py
index bce5faad1785..511b19c5b065 100644
--- a/ee/clickhouse/models/test/test_cohort.py
+++ b/ee/clickhouse/models/test/test_cohort.py
@@ -26,7 +26,6 @@ from posthog.hogql.constants import MAX_SELECT_COHORT_CALCULATION_LIMIT
from posthog.hogql.hogql import HogQLContext
from posthog.clickhouse.client import sync_execute
-from posthog.models.action import Action
from posthog.models.cohort import Cohort
from posthog.models.cohort.sql import GET_COHORTPEOPLE_BY_COHORT_ID
from posthog.models.cohort.util import format_filter_query
@@ -39,6 +38,8 @@ from posthog.models.team import Team
from posthog.queries.person_distinct_id_query import get_team_distinct_ids_query
from posthog.queries.util import PersonPropertiesMode
+from products.actions.backend.models.action import Action
+
def get_person_ids_by_cohort_id(
team_id: int,
diff --git a/ee/clickhouse/queries/column_optimizer.py b/ee/clickhouse/queries/column_optimizer.py
index 837c6393e885..6360c509c721 100644
--- a/ee/clickhouse/queries/column_optimizer.py
+++ b/ee/clickhouse/queries/column_optimizer.py
@@ -2,7 +2,6 @@ from collections import Counter as TCounter
from typing import cast
from posthog.constants import TREND_FILTER_TYPE_ACTIONS, FunnelCorrelationType
-from posthog.models.action.util import get_action_tables_and_properties
from posthog.models.filters.mixins.utils import cached_property
from posthog.models.filters.properties_timeline_filter import PropertiesTimelineFilter
from posthog.models.filters.stickiness_filter import StickinessFilter
@@ -12,6 +11,8 @@ from posthog.models.property.util import box_value, count_hogql_properties, extr
from posthog.queries.column_optimizer.foss_column_optimizer import FOSSColumnOptimizer
from posthog.queries.trends.util import is_series_group_based
+from products.actions.backend.models.util import get_action_tables_and_properties
+
class EnterpriseColumnOptimizer(FOSSColumnOptimizer):
@cached_property
diff --git a/ee/clickhouse/queries/experiments/test_utils.py b/ee/clickhouse/queries/experiments/test_utils.py
index 4a3f7c90fdb6..32681822adef 100644
--- a/ee/clickhouse/queries/experiments/test_utils.py
+++ b/ee/clickhouse/queries/experiments/test_utils.py
@@ -1,10 +1,11 @@
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from posthog.constants import INSIGHT_FUNNELS
-from posthog.models.action.action import Action
from posthog.models.filters.filter import Filter
from posthog.test.test_journeys import journeys_for
+from products.actions.backend.models.action import Action
+
from ee.clickhouse.queries.experiments.utils import requires_flag_warning
diff --git a/ee/clickhouse/queries/funnels/test/test_funnel.py b/ee/clickhouse/queries/funnels/test/test_funnel.py
index 97df3a1bfe9c..bd736fbc131b 100644
--- a/ee/clickhouse/queries/funnels/test/test_funnel.py
+++ b/ee/clickhouse/queries/funnels/test/test_funnel.py
@@ -3,7 +3,6 @@ from datetime import datetime
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
from posthog.constants import INSIGHT_FUNNELS
-from posthog.models.action import Action
from posthog.models.cohort import Cohort
from posthog.models.filters import Filter
from posthog.models.group.util import create_group
@@ -15,6 +14,8 @@ from posthog.queries.funnels.test.test_funnel import _create_action
from posthog.test.test_journeys import journeys_for
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.actions.backend.models.action import Action
+
from ee.clickhouse.queries.funnels.test.breakdown_cases import funnel_breakdown_group_test_factory
diff --git a/ee/clickhouse/queries/test/test_cohort_query.py b/ee/clickhouse/queries/test/test_cohort_query.py
index 4bbc03265096..0aa3bce05f1d 100644
--- a/ee/clickhouse/queries/test/test_cohort_query.py
+++ b/ee/clickhouse/queries/test/test_cohort_query.py
@@ -20,11 +20,11 @@ from posthog.clickhouse.client import sync_execute
from posthog.constants import PropertyOperatorType
from posthog.hogql_queries.hogql_cohort_query import TestWrapperCohortQuery as CohortQuery
from posthog.models import Team
-from posthog.models.action import Action
from posthog.models.cohort import Cohort
from posthog.models.filters.filter import Filter
from posthog.models.property import Property, PropertyGroup
+from products.actions.backend.models.action import Action
from products.event_definitions.backend.models.property_definition import PropertyDefinition
from ee.clickhouse.queries.enterprise_cohort_query import check_negation_clause
diff --git a/ee/clickhouse/queries/test/test_column_optimizer.py b/ee/clickhouse/queries/test/test_column_optimizer.py
index 03326d3eda7a..d6882ffaa549 100644
--- a/ee/clickhouse/queries/test/test_column_optimizer.py
+++ b/ee/clickhouse/queries/test/test_column_optimizer.py
@@ -1,8 +1,9 @@
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, cleanup_materialized_columns
-from posthog.models import Action
from posthog.models.filters import Filter, RetentionFilter
+from products.actions.backend.models.action import Action
+
from ee.clickhouse.materialized_columns.columns import materialize
from ee.clickhouse.queries.column_optimizer import EnterpriseColumnOptimizer
diff --git a/ee/clickhouse/queries/test/test_event_query.py b/ee/clickhouse/queries/test/test_event_query.py
index b51b5b3dee58..78e231e3c035 100644
--- a/ee/clickhouse/queries/test/test_event_query.py
+++ b/ee/clickhouse/queries/test/test_event_query.py
@@ -8,7 +8,6 @@ from posthog.test.base import (
)
from posthog.clickhouse.client import sync_execute
-from posthog.models import Action
from posthog.models.cohort import Cohort
from posthog.models.element import Element
from posthog.models.entity import Entity
@@ -18,6 +17,8 @@ from posthog.models.person import Person
from posthog.queries.trends.trends_event_query import TrendsEventQuery
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.actions.backend.models.action import Action
+
from ee.clickhouse.materialized_columns.columns import materialize
diff --git a/ee/clickhouse/queries/test/test_util.py b/ee/clickhouse/queries/test/test_util.py
index bd9990d8bf02..68554010a1a4 100644
--- a/ee/clickhouse/queries/test/test_util.py
+++ b/ee/clickhouse/queries/test/test_util.py
@@ -7,11 +7,12 @@ from posthog.test.base import _create_event
from posthog.hogql.hogql import HogQLContext
from posthog.clickhouse.client import sync_execute
-from posthog.models.action import Action
from posthog.models.cohort import Cohort
from posthog.queries.breakdown_props import _parse_breakdown_cohorts
from posthog.queries.util import get_earliest_timestamp
+from products.actions.backend.models.action import Action
+
def test_get_earliest_timestamp(db, team):
with freeze_time("2021-01-21") as frozen_time:
diff --git a/ee/clickhouse/views/test/test_experiment_saved_metrics.py b/ee/clickhouse/views/test/test_experiment_saved_metrics.py
index 460d44b1cda4..35c574f7808c 100644
--- a/ee/clickhouse/views/test/test_experiment_saved_metrics.py
+++ b/ee/clickhouse/views/test/test_experiment_saved_metrics.py
@@ -846,7 +846,7 @@ class TestExperimentSavedMetricsCRUD(APILicensedTest):
def test_saved_metric_refreshes_action_names(self):
"""Test that saved metrics show current action names when actions are renamed."""
- from posthog.models.action.action import Action
+ from products.actions.backend.models.action import Action
# Create an action
action = Action.objects.create(team=self.team, name="Original Action Name")
@@ -885,7 +885,7 @@ class TestExperimentSavedMetricsCRUD(APILicensedTest):
def test_saved_metric_preserves_name_for_deleted_action(self):
"""Test that saved metrics preserve old names when actions are deleted."""
- from posthog.models.action.action import Action
+ from products.actions.backend.models.action import Action
# Create an action
action = Action.objects.create(team=self.team, name="Action to Delete")
diff --git a/ee/clickhouse/views/test/test_experiments_action_names.py b/ee/clickhouse/views/test/test_experiments_action_names.py
index a325e288ec0c..1409a97b4c71 100644
--- a/ee/clickhouse/views/test/test_experiments_action_names.py
+++ b/ee/clickhouse/views/test/test_experiments_action_names.py
@@ -1,7 +1,7 @@
from parameterized import parameterized
from rest_framework import status
-from posthog.models.action.action import Action
+from products.actions.backend.models.action import Action
from ee.api.test.base import APILicensedTest
diff --git a/ee/hogai/chat_agent/query_planner/test/test_toolkit.py b/ee/hogai/chat_agent/query_planner/test/test_toolkit.py
index 4e967377c23f..7852ea5b288c 100644
--- a/ee/hogai/chat_agent/query_planner/test/test_toolkit.py
+++ b/ee/hogai/chat_agent/query_planner/test/test_toolkit.py
@@ -4,11 +4,11 @@ from textwrap import dedent
from freezegun import freeze_time
from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, _create_person
-from posthog.models import Action
from posthog.models.group.util import create_group
from posthog.models.group_type_mapping import invalidate_group_types_cache
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.actions.backend.models.action import Action
from products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType
from ee.hogai.chat_agent.query_planner.toolkit import TaxonomyAgentToolkit, final_answer
diff --git a/ee/hogai/chat_agent/query_planner/toolkit.py b/ee/hogai/chat_agent/query_planner/toolkit.py
index 776679e756fe..63834d0fe463 100644
--- a/ee/hogai/chat_agent/query_planner/toolkit.py
+++ b/ee/hogai/chat_agent/query_planner/toolkit.py
@@ -19,9 +19,10 @@ from posthog.event_usage import EventSource
from posthog.hogql_queries.ai.actors_property_taxonomy_query_runner import ActorsPropertyTaxonomyQueryRunner
from posthog.hogql_queries.ai.event_taxonomy_query_runner import EventTaxonomyQueryRunner
from posthog.hogql_queries.query_runner import ExecutionMode
-from posthog.models import Action, Team
+from posthog.models import Team
from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP
+from products.actions.backend.models.action import Action
from products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType
from ee.hogai.chat_agent.taxonomy.tools import (
diff --git a/ee/hogai/chat_agent/rag/nodes.py b/ee/hogai/chat_agent/rag/nodes.py
index fce9dc6fc15f..66f69c9e3d4d 100644
--- a/ee/hogai/chat_agent/rag/nodes.py
+++ b/ee/hogai/chat_agent/rag/nodes.py
@@ -20,7 +20,8 @@ from posthog.hogql_queries.ai.vector_search_query_runner import (
VectorSearchQueryRunner,
)
from posthog.hogql_queries.query_runner import ExecutionMode
-from posthog.models import Action
+
+from products.actions.backend.models.action import Action
from ee.hogai.core.node import AssistantNode
from ee.hogai.utils.embeddings import embed_search_query, get_azure_embeddings_client
diff --git a/ee/hogai/chat_agent/rag/test/test_nodes.py b/ee/hogai/chat_agent/rag/test/test_nodes.py
index 720bd2a792a8..a3c7875bd615 100644
--- a/ee/hogai/chat_agent/rag/test/test_nodes.py
+++ b/ee/hogai/chat_agent/rag/test/test_nodes.py
@@ -10,9 +10,10 @@ from azure.core.credentials import AzureKeyCredential
from posthog.schema import MaxActionContext, MaxUIContext, TeamTaxonomyQuery
from posthog.hogql_queries.query_runner import ExecutionMode
-from posthog.models import Action
from posthog.models.ai.utils import PgEmbeddingRow, bulk_create_pg_embeddings
+from products.actions.backend.models.action import Action
+
from ee.hogai.chat_agent.rag.nodes import InsightRagContextNode
from ee.hogai.utils.types import AssistantState
diff --git a/ee/hogai/chat_agent/retention/test/test_nodes.py b/ee/hogai/chat_agent/retention/test/test_nodes.py
index 0b7efb1dcb4d..147d5eb2dc45 100644
--- a/ee/hogai/chat_agent/retention/test/test_nodes.py
+++ b/ee/hogai/chat_agent/retention/test/test_nodes.py
@@ -13,7 +13,7 @@ from posthog.schema import (
HumanMessage,
)
-from posthog.models import Action
+from products.actions.backend.models.action import Action
from ee.hogai.chat_agent.retention.nodes import RetentionGeneratorNode, RetentionSchemaGeneratorOutput
from ee.hogai.utils.types import AssistantState
diff --git a/ee/hogai/chat_agent/taxonomy/test/test_events.py b/ee/hogai/chat_agent/taxonomy/test/test_events.py
index 0bbfdf7c45dc..b1251b3c5746 100644
--- a/ee/hogai/chat_agent/taxonomy/test/test_events.py
+++ b/ee/hogai/chat_agent/taxonomy/test/test_events.py
@@ -1,9 +1,9 @@
from posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTest, _create_event, flush_persons_and_events
-from posthog.models import Action
from posthog.models.group_type_mapping import invalidate_group_types_cache
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.actions.backend.models.action import Action
from products.event_definitions.backend.models.property_definition import PropertyDefinition
from ee.hogai.chat_agent.taxonomy.toolkit import TaxonomyAgentToolkit
diff --git a/ee/hogai/chat_agent/taxonomy/toolkit.py b/ee/hogai/chat_agent/taxonomy/toolkit.py
index 2f87f729abdf..55a05ee1fe21 100644
--- a/ee/hogai/chat_agent/taxonomy/toolkit.py
+++ b/ee/hogai/chat_agent/taxonomy/toolkit.py
@@ -28,10 +28,11 @@ from posthog.event_usage import EventSource
from posthog.hogql_queries.ai.actors_property_taxonomy_query_runner import ActorsPropertyTaxonomyQueryRunner
from posthog.hogql_queries.ai.event_taxonomy_query_runner import EventTaxonomyQueryRunner
from posthog.hogql_queries.query_runner import ExecutionMode
-from posthog.models import Action, Team, User
+from posthog.models import Team, User
from posthog.sync import database_sync_to_async
from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP
+from products.actions.backend.models.action import Action
from products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType
from ee.hogai.chat_agent.taxonomy.format import (
diff --git a/ee/hogai/chat_agent/test/test_chat_agent.py b/ee/hogai/chat_agent/test/test_chat_agent.py
index b9a9b6502907..108879144bdc 100644
--- a/ee/hogai/chat_agent/test/test_chat_agent.py
+++ b/ee/hogai/chat_agent/test/test_chat_agent.py
@@ -50,7 +50,7 @@ from posthog.schema import (
VisualizationArtifactContent,
)
-from posthog.models import Action
+from products.actions.backend.models.action import Action
from ee.hogai.chat_agent.funnels.nodes import FunnelsSchemaGeneratorOutput
from ee.hogai.chat_agent.graph import AssistantGraph
diff --git a/ee/hogai/context/entity_search/context.py b/ee/hogai/context/entity_search/context.py
index 6c0349101598..699adac0d4be 100644
--- a/ee/hogai/context/entity_search/context.py
+++ b/ee/hogai/context/entity_search/context.py
@@ -14,11 +14,12 @@ from posthog.api.search import (
EntityConfig,
search_entities as search_entities_fts,
)
-from posthog.models import Action, Cohort, FeatureFlag, Insight, Team, User
-from posthog.models.alert import AlertConfiguration
+from posthog.models import Cohort, FeatureFlag, Insight, Team, User
from posthog.rbac.user_access_control import UserAccessControl
from posthog.sync import database_sync_to_async
+from products.actions.backend.models.action import Action
+from products.alerts.backend.models.alert import AlertConfiguration
from products.dashboards.backend.models.dashboard import Dashboard
from products.experiments.backend.models.experiment import Experiment
from products.notebooks.backend.models import Notebook
diff --git a/ee/hogai/context/entity_search/test/test_context.py b/ee/hogai/context/entity_search/test/test_context.py
index 468bb34bdada..bb6b590696dd 100644
--- a/ee/hogai/context/entity_search/test/test_context.py
+++ b/ee/hogai/context/entity_search/test/test_context.py
@@ -7,9 +7,10 @@ from django.utils import timezone
from parameterized import parameterized
-from posthog.models import Action, Cohort, FeatureFlag, Insight
+from posthog.models import Cohort, FeatureFlag, Insight
from posthog.models.insight import InsightViewed
+from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.experiments.backend.models.experiment import Experiment
from products.surveys.backend.models import Survey
diff --git a/ee/hogai/core/mixins.py b/ee/hogai/core/mixins.py
index 0e16fa2c4061..96276bdb67cd 100644
--- a/ee/hogai/core/mixins.py
+++ b/ee/hogai/core/mixins.py
@@ -11,9 +11,10 @@ from posthog.schema import CurrencyCode, HumanMessage
from posthog.event_usage import groups
from posthog.models import Team
-from posthog.models.action.action import Action
from posthog.models.user import User
+from products.actions.backend.models.action import Action
+
from ee.hogai.utils.dispatcher import AssistantDispatcher, create_dispatcher_from_config
from ee.hogai.utils.feature_flags import is_core_memory_disabled
from ee.hogai.utils.helpers import find_start_message
diff --git a/ee/hogai/eval/ci/eval_ui_context.py b/ee/hogai/eval/ci/eval_ui_context.py
index c3c5eadeed6f..06a584977ce7 100644
--- a/ee/hogai/eval/ci/eval_ui_context.py
+++ b/ee/hogai/eval/ci/eval_ui_context.py
@@ -11,9 +11,10 @@ from posthog.schema import (
MaxUIContext,
)
-from posthog.models.action.action import Action
from posthog.models.team.team import Team
+from products.actions.backend.models.action import Action
+
from ee.hogai.chat_agent import AssistantGraph
from ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointer
from ee.hogai.utils.types import AssistantNodeName, AssistantState
diff --git a/ee/hogai/summarizers/actions.py b/ee/hogai/summarizers/actions.py
index 01700756286f..f862fc2b6553 100644
--- a/ee/hogai/summarizers/actions.py
+++ b/ee/hogai/summarizers/actions.py
@@ -1,6 +1,6 @@
from collections import defaultdict
-from posthog.models.action.action import Action, ActionStepJSON, ActionStepMatching
+from products.actions.backend.models.action import Action, ActionStepJSON, ActionStepMatching
from .property_filters import (
PropertyFilterCollectionDescriber,
diff --git a/ee/hogai/summarizers/chains.py b/ee/hogai/summarizers/chains.py
index dbc47378baf7..8e5a047634d6 100644
--- a/ee/hogai/summarizers/chains.py
+++ b/ee/hogai/summarizers/chains.py
@@ -10,7 +10,7 @@ from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from posthoganalytics.ai.langchain import CallbackHandler
-from posthog.models import Action
+from products.actions.backend.models.action import Action
from .actions import ActionSummarizer
from .prompts import ACTIONS_SUMMARIZER_SYSTEM_PROMPT
diff --git a/ee/hogai/summarizers/test/test_actions.py b/ee/hogai/summarizers/test/test_actions.py
index 679a1ec60c40..09769479804d 100644
--- a/ee/hogai/summarizers/test/test_actions.py
+++ b/ee/hogai/summarizers/test/test_actions.py
@@ -3,7 +3,7 @@ from textwrap import dedent
from posthog.test.base import BaseTest
-from posthog.models import Action
+from products.actions.backend.models.action import Action
from ee.hogai.summarizers.actions import ActionSummarizer
diff --git a/ee/hogai/test/test_insights_assistant.py b/ee/hogai/test/test_insights_assistant.py
index a3bbfe5b3f5d..d526aa91f363 100644
--- a/ee/hogai/test/test_insights_assistant.py
+++ b/ee/hogai/test/test_insights_assistant.py
@@ -24,7 +24,7 @@ from posthog.schema import (
VisualizationMessage,
)
-from posthog.models import Action
+from products.actions.backend.models.action import Action
from ee.hogai.chat_agent.funnels.nodes import FunnelsSchemaGeneratorOutput
from ee.hogai.chat_agent.retention.nodes import RetentionSchemaGeneratorOutput
diff --git a/posthog/admin/admins/alert_admin.py b/posthog/admin/admins/alert_admin.py
index ef0052a6d819..d940f7c5a437 100644
--- a/posthog/admin/admins/alert_admin.py
+++ b/posthog/admin/admins/alert_admin.py
@@ -3,7 +3,8 @@ from django.urls import reverse
from django.utils.html import format_html
from posthog.admin.paginators.no_count_paginator import NoCountPaginator
-from posthog.models import AlertConfiguration
+
+from products.alerts.backend.models.alert import AlertConfiguration
@admin.register(AlertConfiguration)
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.py
index 0aa39c5a8730..8386702af0ef 100644
--- a/posthog/api/__init__.py
+++ b/posthog/api/__init__.py
@@ -31,6 +31,7 @@ import products.endpoints.backend.api as endpoints
import products.signals.backend.views as signals
import products.tasks.backend.seat_api as seats
import products.deployments.backend.api as deployments
+import products.alerts.backend.api.alert as alert
import products.conversations.backend.api as conversations
import products.live_debugger.backend.api as live_debugger
import products.web_analytics.backend.api as web_analytics_api
@@ -137,7 +138,6 @@ from ..session_recordings.session_recording_playlist_api import SessionRecording
from ..taxonomy import property_definition_api
from . import (
advanced_activity_logs,
- alert,
annotation,
async_migration,
authentication,
@@ -804,7 +804,6 @@ router.register(r"instance_settings", instance_settings.InstanceSettingsViewset,
router.register(r"debug_ch_queries", debug_ch_queries.DebugCHQueries, "debug_ch_queries")
router.register(r"query_performance_proxy", QueryPerformanceProxyViewSet, "query_performance_proxy")
-from posthog.api.action import ActionViewSet # noqa: E402
from posthog.api.cohort import CohortViewSet, LegacyCohortViewSet # noqa: E402
from posthog.api.element import ElementViewSet, LegacyElementViewSet # noqa: E402
from posthog.api.event import EventViewSet, LegacyEventViewSet # noqa: E402
@@ -812,6 +811,8 @@ from posthog.api.insight import InsightViewSet # noqa: E402
from posthog.api.person import LegacyPersonViewSet, PersonViewSet # noqa: E402
from posthog.api.web_experiment import WebExperimentViewSet # noqa: E402
+from products.actions.backend.api.action import ActionViewSet # noqa: E402
+
# Legacy endpoints CH (to be removed eventually)
router.register(r"cohort", LegacyCohortViewSet, basename="cohort")
router.register(r"element", LegacyElementViewSet, basename="element")
diff --git a/posthog/api/file_system/registrations.py b/posthog/api/file_system/registrations.py
index f7f8a458bbac..6af21b50634c 100644
--- a/posthog/api/file_system/registrations.py
+++ b/posthog/api/file_system/registrations.py
@@ -339,7 +339,7 @@ def _feature_flag_pre_restore(context: RestoreContext, feature_flag: Any) -> Non
def register_core_file_system_types() -> None:
register_file_system_type(
"action",
- "posthog",
+ "actions",
"Action",
undo_message="Send PATCH /api/projects/@current/actions/{id} with deleted=false.",
)
diff --git a/posthog/api/insight.py b/posthog/api/insight.py
index 612cda35c8da..0a1f2d7df4aa 100644
--- a/posthog/api/insight.py
+++ b/posthog/api/insight.py
@@ -100,7 +100,6 @@ from posthog.models.activity_logging.activity_log import (
log_activity,
)
from posthog.models.activity_logging.activity_page import ActivityLogPaginatedResponseSerializer, activity_page_response
-from posthog.models.alert import AlertConfiguration
from posthog.models.filters.utils import get_filter
from posthog.models.insight import InsightViewed
from posthog.models.insight_caching_state import InsightCachingState
@@ -131,6 +130,7 @@ from posthog.utils import (
variables_override_requested_by_client,
)
+from products.alerts.backend.models.alert import AlertConfiguration
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
@@ -905,7 +905,7 @@ class InsightSerializer(InsightBasicSerializer):
# Use prefetched alerts data
alerts = getattr(insight, "_prefetched_alerts", [])
- from posthog.api.alert import AlertSerializer
+ from products.alerts.backend.api.alert import AlertSerializer
return AlertSerializer(alerts, many=True, context=self.context).data
diff --git a/posthog/api/search.py b/posthog/api/search.py
index e68dadb64ee2..222266422741 100644
--- a/posthog/api/search.py
+++ b/posthog/api/search.py
@@ -12,9 +12,10 @@ from rest_framework.response import Response
from posthog.api.documentation import _FallbackSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.helpers.full_text_search import build_rank, process_query
-from posthog.models import Action, Cohort, EventDefinition, FeatureFlag, Insight, PropertyDefinition
+from posthog.models import Cohort, EventDefinition, FeatureFlag, Insight, 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
from products.early_access_features.backend.models import EarlyAccessFeature
from products.experiments.backend.models.experiment import Experiment
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index 29b2812677f5..4de4eba8980e 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -24,7 +24,7 @@ from posthog.schema import PersonsOnEventsMode, PropertyOperator
from posthog.api.test.test_exports import TestExportMixin
from posthog.clickhouse.client.execute import sync_execute
-from posthog.models import Action, FeatureFlag, Person, User
+from posthog.models import FeatureFlag, Person, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.async_deletion.async_deletion import AsyncDeletion
from posthog.models.cohort import Cohort
@@ -40,6 +40,8 @@ from posthog.tasks.calculate_cohort import (
insert_cohort_from_filters,
)
+from products.actions.backend.models.action import Action
+
from ee.clickhouse.materialized_columns.analyze import materialize
diff --git a/posthog/api/test/test_event.py b/posthog/api/test/test_event.py
index 668b4dc17a2a..0603173cf0bb 100644
--- a/posthog/api/test/test_event.py
+++ b/posthog/api/test/test_event.py
@@ -23,11 +23,13 @@ from dateutil.relativedelta import relativedelta
from parameterized import parameterized
from rest_framework import status
-from posthog.models import Action, Element, Organization, Person, PropertyDefinition, User
+from posthog.models import Element, Organization, Person, PropertyDefinition, User
from posthog.models.cohort import Cohort
from posthog.models.event.query_event_list import insight_query_with_columns
from posthog.test.test_journeys import journeys_for
+from products.actions.backend.models.action import Action
+
class TestEvents(ClickhouseTestMixin, APIBaseTest):
ENDPOINT = "event"
diff --git a/posthog/api/test/test_event_definition.py b/posthog/api/test/test_event_definition.py
index 91537eb1dc9c..bb02cbcabbaa 100644
--- a/posthog/api/test/test_event_definition.py
+++ b/posthog/api/test/test_event_definition.py
@@ -16,7 +16,9 @@ from rest_framework import status
from posthog.api.test.test_organization import create_organization
from posthog.api.test.test_team import create_team
from posthog.api.test.test_user import create_user
-from posthog.models import Action, ActivityLog, EventDefinition, Organization, Team
+from posthog.models import ActivityLog, EventDefinition, Organization, Team
+
+from products.actions.backend.models.action import Action
@freeze_time("2020-01-02")
diff --git a/posthog/api/test/test_file_system.py b/posthog/api/test/test_file_system.py
index 10bdaa3da044..cb19eba670db 100644
--- a/posthog/api/test/test_file_system.py
+++ b/posthog/api/test/test_file_system.py
@@ -18,7 +18,6 @@ from rest_framework import status
from rest_framework.test import APIRequestFactory
from posthog.api.file_system.file_system_logging import log_api_file_system_view
-from posthog.models import Action
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.cohort.cohort import Cohort
from posthog.models.feature_flag.feature_flag import FeatureFlag
@@ -28,6 +27,7 @@ from posthog.models.hog_functions.hog_function import HogFunction, HogFunctionTy
from posthog.models.insight import Insight
from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
+from products.actions.backend.models.action import Action
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_hog_function.py b/posthog/api/test/test_hog_function.py
index dc278217d31f..4a96e103a823 100644
--- a/posthog/api/test/test_hog_function.py
+++ b/posthog/api/test/test_hog_function.py
@@ -15,10 +15,11 @@ 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.action.action import Action
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 common.hogvm.python.operation import HOGQL_BYTECODE_VERSION, Operation
webhook_template = MOCK_NODE_TEMPLATES[0]
diff --git a/posthog/api/test/test_resource_transfer.py b/posthog/api/test/test_resource_transfer.py
index 1f0003250021..b96286a67294 100644
--- a/posthog/api/test/test_resource_transfer.py
+++ b/posthog/api/test/test_resource_transfer.py
@@ -6,12 +6,13 @@ from unittest.mock import patch
from parameterized import parameterized
from rest_framework import status
-from posthog.models import Action, Insight, Project, Team
+from posthog.models import Insight, Project, Team
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.cohort import Cohort
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.resource_transfer.resource_transfer import ResourceTransfer
+from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.surveys.backend.models import Survey
diff --git a/posthog/cdp/filters.py b/posthog/cdp/filters.py
index b5a4d185db22..c10a8942dd4f 100644
--- a/posthog/cdp/filters.py
+++ b/posthog/cdp/filters.py
@@ -8,10 +8,11 @@ from posthog.hogql.parser import parse_expr
from posthog.hogql.property import action_to_expr, ast, property_to_expr
from posthog.hogql.visitor import TraversingVisitor
-from posthog.models.action.action import Action
from posthog.models.cohort.cohort import Cohort
from posthog.models.team.team import Team
+from products.actions.backend.models.action import Action
+
COHORT_FILTER_TYPES = frozenset({"cohort", "static-cohort", "precalculated-cohort", "dynamic-cohort"})
diff --git a/posthog/cdp/test/test_filters.py b/posthog/cdp/test/test_filters.py
index 2b6a2d5c4007..cbef110963e1 100644
--- a/posthog/cdp/test/test_filters.py
+++ b/posthog/cdp/test/test_filters.py
@@ -11,9 +11,10 @@ from posthog.cdp.filters import (
compile_filters_bytecode,
hog_function_filters_to_expr,
)
-from posthog.models.action.action import Action
from posthog.models.cohort.cohort import Cohort
+from products.actions.backend.models.action import Action
+
from common.hogvm.python.execute import execute_bytecode
from common.hogvm.python.operation import HOGQL_BYTECODE_VERSION
diff --git a/posthog/cdp/test/test_site_functions.py b/posthog/cdp/test/test_site_functions.py
index 1d29384f5dc9..a75f88a5ac46 100644
--- a/posthog/cdp/test/test_site_functions.py
+++ b/posthog/cdp/test/test_site_functions.py
@@ -12,7 +12,6 @@ from parameterized import parameterized
from posthog.cdp.site_functions import get_transpiled_function
from posthog.cdp.templates.helpers import mock_transpile
-from posthog.models.action.action import Action
from posthog.models.cohort import Cohort
from posthog.models.hog_functions.hog_function import HogFunction
from posthog.models.organization import Organization
@@ -21,6 +20,8 @@ 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
+
@pytest.mark.usefixtures("unittest_snapshot")
class TestSiteFunctions(TestCase):
diff --git a/posthog/demo/legacy/app_data_generator.py b/posthog/demo/legacy/app_data_generator.py
index ed41612b14b8..1b72784f4984 100644
--- a/posthog/demo/legacy/app_data_generator.py
+++ b/posthog/demo/legacy/app_data_generator.py
@@ -5,8 +5,9 @@ from django.utils.timezone import now
from dateutil.relativedelta import relativedelta
from posthog.constants import TREND_FILTER_TYPE_ACTIONS
-from posthog.models import Action, EventDefinition, Insight, Person, PropertyDefinition
+from posthog.models import EventDefinition, Insight, Person, PropertyDefinition
+from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
diff --git a/posthog/demo/legacy/revenue_data_generator.py b/posthog/demo/legacy/revenue_data_generator.py
index b91526fba337..d1f7bcb0353a 100644
--- a/posthog/demo/legacy/revenue_data_generator.py
+++ b/posthog/demo/legacy/revenue_data_generator.py
@@ -5,8 +5,9 @@ from django.utils.timezone import now
from dateutil.relativedelta import relativedelta
from posthog.constants import TREND_FILTER_TYPE_ACTIONS
-from posthog.models import Action, EventDefinition, Insight, Person, PropertyDefinition
+from posthog.models import EventDefinition, Insight, Person, PropertyDefinition
+from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
diff --git a/posthog/demo/legacy/web_data_generator.py b/posthog/demo/legacy/web_data_generator.py
index f8d741054179..2b390067c958 100644
--- a/posthog/demo/legacy/web_data_generator.py
+++ b/posthog/demo/legacy/web_data_generator.py
@@ -8,11 +8,12 @@ from django.utils.timezone import now
from dateutil.relativedelta import relativedelta
from posthog.constants import TREND_FILTER_TYPE_ACTIONS
-from posthog.models import Action, Insight, Person, PropertyDefinition
+from posthog.models import Insight, Person, PropertyDefinition
from posthog.models.filters.mixins.utils import cached_property
from posthog.models.utils import UUIDT
from posthog.utils import get_absolute_path
+from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
diff --git a/posthog/demo/products/hedgebox/matrix.py b/posthog/demo/products/hedgebox/matrix.py
index a86d8dfbdb50..6169e716f23c 100644
--- a/posthog/demo/products/hedgebox/matrix.py
+++ b/posthog/demo/products/hedgebox/matrix.py
@@ -50,11 +50,12 @@ from posthog.demo.matrix.matrix import Cluster, Matrix
from posthog.demo.matrix.models import SimEvent
from posthog.demo.matrix.randomization import Industry
from posthog.exceptions_capture import capture_exception
-from posthog.models import Action, Cohort, FeatureFlag, Insight, InsightViewed
+from posthog.models import Cohort, FeatureFlag, Insight, InsightViewed
from posthog.models.event.util import create_event
from posthog.models.oauth import OAuthApplication
from posthog.storage import object_storage
+from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.data_warehouse.backend.models.credential import get_or_create_datawarehouse_credential
diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.py
index 6bd77abf5b93..2b4d7a7144d2 100644
--- a/posthog/hogql/database/schema/test/test_system_tables.py
+++ b/posthog/hogql/database/schema/test/test_system_tables.py
@@ -11,7 +11,6 @@ from posthog.hogql.printer import prepare_and_print_ast
from posthog.hogql.query import execute_hogql_query
from posthog.models import (
- Action,
Annotation,
Cohort,
ExportedAsset,
@@ -25,12 +24,13 @@ from posthog.models import (
Team,
)
from posthog.models.activity_logging.activity_log import ActivityLog
-from posthog.models.alert import AlertConfiguration
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
+from products.alerts.backend.models.alert import AlertConfiguration
from products.conversations.backend.models import Ticket
from products.dashboards.backend.models.dashboard import Dashboard
from products.data_warehouse.backend.models.data_modeling_job import DataModelingJob
diff --git a/posthog/hogql/functions/action.py b/posthog/hogql/functions/action.py
index ca961e0f84e1..23a6109e366f 100644
--- a/posthog/hogql/functions/action.py
+++ b/posthog/hogql/functions/action.py
@@ -13,7 +13,7 @@ def matches_action(node: ast.Expr, args: list[ast.Expr], context: HogQLContext,
from posthog.hogql.property import action_to_expr
- from posthog.models import Action
+ from products.actions.backend.models.action import Action
if (isinstance(arg.value, int) or isinstance(arg.value, float)) and not isinstance(arg.value, bool):
actions = Action.objects.filter(id=int(arg.value), team__project_id=context.project_id).all()
diff --git a/posthog/hogql/functions/test/test_action.py b/posthog/hogql/functions/test/test_action.py
index e1c493b34d8c..007c12d7ce9a 100644
--- a/posthog/hogql/functions/test/test_action.py
+++ b/posthog/hogql/functions/test/test_action.py
@@ -4,9 +4,10 @@ from posthog.test.base import BaseTest, _create_action, _create_event, _create_p
from posthog.hogql.query import execute_hogql_query
from posthog.hogql.test.utils import pretty_print_response_in_tests
-from posthog.models import Action
from posthog.models.utils import UUIDT
+from products.actions.backend.models.action import Action
+
def _create_action_with_property(**kwargs):
team = kwargs.pop("team")
diff --git a/posthog/hogql/property.py b/posthog/hogql/property.py
index 23f0a5460e19..9ab746eb541d 100644
--- a/posthog/hogql/property.py
+++ b/posthog/hogql/property.py
@@ -48,14 +48,14 @@ from posthog.hogql.utils import map_virtual_properties
from posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_expr
from posthog.constants import AUTOCAPTURE_EVENT, TREND_FILTER_TYPE_ACTIONS, PropertyOperatorType
-from posthog.models import Action, Cohort, Property, PropertyDefinition, Team
-from posthog.models.action.action import ActionStepJSON
+from posthog.models import Cohort, Property, PropertyDefinition, Team
from posthog.models.element import Element
from posthog.models.event import Selector
from posthog.models.property import PropertyGroup, ValueT
from posthog.models.property.util import build_selector_regex
from posthog.utils import get_from_dict_or_attr
+from products.actions.backend.models.action import Action, ActionStepJSON
from products.data_warehouse.backend.models import DataWarehouseJoin
from products.data_warehouse.backend.models.util import get_view_or_table_by_name
from products.event_definitions.backend.models.property_definition import PropertyType
diff --git a/posthog/hogql/test/test_action_to_expr.py b/posthog/hogql/test/test_action_to_expr.py
index 832c87069567..001a385adc55 100644
--- a/posthog/hogql/test/test_action_to_expr.py
+++ b/posthog/hogql/test/test_action_to_expr.py
@@ -8,8 +8,7 @@ from posthog.hogql.property import action_to_expr, steps_to_expr
from posthog.hogql.query import execute_hogql_query
from posthog.hogql.visitor import clear_locations
-from posthog.models import Action
-from posthog.models.action.action import ActionStepJSON
+from products.actions.backend.models.action import Action, ActionStepJSON
class TestActionToExpr(BaseTest):
diff --git a/posthog/hogql/test/test_property.py b/posthog/hogql/test/test_property.py
index 95cf90db0ade..2d360d4d7803 100644
--- a/posthog/hogql/test/test_property.py
+++ b/posthog/hogql/test/test_property.py
@@ -994,7 +994,7 @@ class TestProperty(BaseTest):
def test_entity_to_expr_actions_type_with_id(self):
action_mock = MagicMock()
- with patch("posthog.models.Action.objects.get", return_value=action_mock):
+ with patch("products.actions.backend.models.action.Action.objects.get", return_value=action_mock):
entity = RetentionEntity(**{"type": TREND_FILTER_TYPE_ACTIONS, "id": 123})
result = entity_to_expr(entity, self.team)
self.assertIsInstance(result, ast.Expr)
diff --git a/posthog/hogql_queries/ai/event_taxonomy_query_runner.py b/posthog/hogql_queries/ai/event_taxonomy_query_runner.py
index cbaec98edc00..0adf300e2685 100644
--- a/posthog/hogql_queries/ai/event_taxonomy_query_runner.py
+++ b/posthog/hogql_queries/ai/event_taxonomy_query_runner.py
@@ -17,7 +17,8 @@ from posthog.clickhouse.query_tagging import Product, tags_context
from posthog.hogql_queries.ai.utils import TaxonomyCacheMixin
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
-from posthog.models import Action
+
+from products.actions.backend.models.action import Action
DEFAULT_LIMIT = 500
diff --git a/posthog/hogql_queries/ai/test/test_event_taxonomy_query_runner.py b/posthog/hogql_queries/ai/test/test_event_taxonomy_query_runner.py
index 5e4a700281a5..e85cf36b61c0 100644
--- a/posthog/hogql_queries/ai/test/test_event_taxonomy_query_runner.py
+++ b/posthog/hogql_queries/ai/test/test_event_taxonomy_query_runner.py
@@ -16,8 +16,9 @@ from django.utils import timezone
from posthog.schema import CachedEventTaxonomyQueryResponse, EventTaxonomyQuery
from posthog.hogql_queries.ai.event_taxonomy_query_runner import EventTaxonomyQueryRunner
-from posthog.models import Action, PropertyDefinition
+from posthog.models import PropertyDefinition
+from products.actions.backend.models.action import Action
from products.event_definitions.backend.models.property_definition import PropertyType
diff --git a/posthog/hogql_queries/events_query_runner.py b/posthog/hogql_queries/events_query_runner.py
index f6adb4609314..df522a13f5f5 100644
--- a/posthog/hogql_queries/events_query_runner.py
+++ b/posthog/hogql_queries/events_query_runner.py
@@ -27,13 +27,14 @@ from posthog.api.person import PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES
from posthog.hogql_queries.insights.insight_actors_query_runner import InsightActorsQueryRunner
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, get_query_runner
-from posthog.models import Action, Person, PropertyDefinition
-from posthog.models.action.action import ActionStepJSON
+from posthog.models import Person, PropertyDefinition
from posthog.models.element import chain_to_elements
from posthog.models.person.person import get_distinct_ids_for_subquery
from posthog.models.person.util import get_person_by_pk_or_uuid, get_persons_by_distinct_ids
from posthog.utils import relative_date_parse
+from products.actions.backend.models.action import Action, ActionStepJSON
+
logger = structlog.get_logger(__name__)
# Allow-listed fields returned when you select "*" from events. Person and group fields will be nested later.
diff --git a/posthog/hogql_queries/experiments/base_query_utils.py b/posthog/hogql_queries/experiments/base_query_utils.py
index 6452d31b5bf0..1902a3209068 100644
--- a/posthog/hogql_queries/experiments/base_query_utils.py
+++ b/posthog/hogql_queries/experiments/base_query_utils.py
@@ -31,9 +31,9 @@ from posthog.hogql_queries.experiments.hogql_aggregation_utils import (
)
from posthog.hogql_queries.insights.trends.aggregation_operations import ALLOWED_SESSION_MATH_PROPERTIES
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
-from posthog.models.action.action import Action
from posthog.models.team.team import Team
+from products.actions.backend.models.action import Action
from products.experiments.backend.models.experiment import Experiment
diff --git a/posthog/hogql_queries/experiments/exposure_query_logic.py b/posthog/hogql_queries/experiments/exposure_query_logic.py
index d04ec4790889..4c4ec4ee9df2 100644
--- a/posthog/hogql_queries/experiments/exposure_query_logic.py
+++ b/posthog/hogql_queries/experiments/exposure_query_logic.py
@@ -21,9 +21,10 @@ from posthog.hogql.property import action_to_expr, property_to_expr
from posthog.hogql_queries.experiments import MULTIPLE_VARIANT_KEY
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
-from posthog.models.action.action import Action
from posthog.models.team.team import Team
+from products.actions.backend.models.action import Action
+
logger = logging.getLogger(__name__)
diff --git a/posthog/hogql_queries/experiments/test/experiment_query_runner/test_base.py b/posthog/hogql_queries/experiments/test/experiment_query_runner/test_base.py
index 24d112ac3053..065d762045ee 100644
--- a/posthog/hogql_queries/experiments/test/experiment_query_runner/test_base.py
+++ b/posthog/hogql_queries/experiments/test/experiment_query_runner/test_base.py
@@ -23,12 +23,13 @@ from posthog.schema import (
from posthog.hogql_queries.experiments.experiment_query_runner import ExperimentQueryRunner
from posthog.hogql_queries.experiments.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest
from posthog.hogql_queries.experiments.test.experiment_query_runner.utils import create_standard_group_test_events
-from posthog.models.action.action import Action
from posthog.models.cohort.cohort import Cohort
from posthog.models.group.util import create_group
from posthog.test.test_journeys import journeys_for
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.actions.backend.models.action import Action
+
@override_settings(IN_UNIT_TESTING=True)
class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
diff --git a/posthog/hogql_queries/experiments/test/experiment_query_runner/test_experiment_exposures_query_runner.py b/posthog/hogql_queries/experiments/test/experiment_query_runner/test_experiment_exposures_query_runner.py
index 9beff8e7d769..5a4ac312d96e 100644
--- a/posthog/hogql_queries/experiments/test/experiment_query_runner/test_experiment_exposures_query_runner.py
+++ b/posthog/hogql_queries/experiments/test/experiment_query_runner/test_experiment_exposures_query_runner.py
@@ -15,10 +15,11 @@ from posthog.hogql_queries.experiments import MULTIPLE_VARIANT_KEY
from posthog.hogql_queries.experiments.experiment_exposures_query_runner import ExperimentExposuresQueryRunner
from posthog.hogql_queries.experiments.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest
from posthog.hogql_queries.experiments.test.experiment_query_runner.utils import create_standard_group_test_events
-from posthog.models.action.action import Action
from posthog.models.feature_flag import FeatureFlag
from posthog.test.test_journeys import journeys_for
+from products.actions.backend.models.action import Action
+
@override_settings(IN_UNIT_TESTING=True)
class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
diff --git a/posthog/hogql_queries/experiments/test/experiment_query_runner/test_funnel_metric.py b/posthog/hogql_queries/experiments/test/experiment_query_runner/test_funnel_metric.py
index c421627829c1..4fb2be03712a 100644
--- a/posthog/hogql_queries/experiments/test/experiment_query_runner/test_funnel_metric.py
+++ b/posthog/hogql_queries/experiments/test/experiment_query_runner/test_funnel_metric.py
@@ -34,11 +34,11 @@ from posthog.schema import (
from posthog.constants import ExperimentNoResultsErrorKeys
from posthog.hogql_queries.experiments.experiment_query_runner import ExperimentQueryRunner
from posthog.hogql_queries.experiments.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest
-from posthog.models.action.action import Action
from posthog.models.filters.utils import GroupTypeIndex
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.actions.backend.models.action import Action
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
diff --git a/posthog/hogql_queries/experiments/test/experiment_query_runner/test_ratio_metric.py b/posthog/hogql_queries/experiments/test/experiment_query_runner/test_ratio_metric.py
index e8aa20e9cbb4..8e877bb0a44e 100644
--- a/posthog/hogql_queries/experiments/test/experiment_query_runner/test_ratio_metric.py
+++ b/posthog/hogql_queries/experiments/test/experiment_query_runner/test_ratio_metric.py
@@ -21,9 +21,10 @@ from posthog.schema import (
from posthog.hogql_queries.experiments.experiment_query_runner import ExperimentQueryRunner
from posthog.hogql_queries.experiments.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest
-from posthog.models.action.action import Action
from posthog.test.test_journeys import journeys_for
+from products.actions.backend.models.action import Action
+
@override_settings(IN_UNIT_TESTING=True)
class TestExperimentRatioMetric(ExperimentQueryRunnerBaseTest):
diff --git a/posthog/hogql_queries/experiments/test/test_experiment_trends_query_runner.py b/posthog/hogql_queries/experiments/test/test_experiment_trends_query_runner.py
index 93c9d01463cf..32c3f33f72d5 100644
--- a/posthog/hogql_queries/experiments/test/test_experiment_trends_query_runner.py
+++ b/posthog/hogql_queries/experiments/test/test_experiment_trends_query_runner.py
@@ -33,13 +33,13 @@ from posthog.schema import (
from posthog.constants import ExperimentNoResultsErrorKeys
from posthog.hogql_queries.experiments.experiment_trends_query_runner import ExperimentTrendsQueryRunner
from posthog.hogql_queries.experiments.types import ExperimentMetricType
-from posthog.models.action.action import Action
from posthog.models.cohort.cohort import Cohort
from posthog.models.feature_flag.feature_flag import FeatureFlag
from posthog.models.group.util import create_group
from posthog.test.test_journeys import journeys_for
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.actions.backend.models.action import Action
from products.experiments.backend.models.experiment import Experiment, ExperimentHoldout
diff --git a/posthog/hogql_queries/insights/funnels/base.py b/posthog/hogql_queries/insights/funnels/base.py
index a372b375ebb8..9f3f5229722a 100644
--- a/posthog/hogql_queries/insights/funnels/base.py
+++ b/posthog/hogql_queries/insights/funnels/base.py
@@ -25,13 +25,14 @@ from posthog.hogql_queries.insights.funnels.funnel_query_context import FunnelQu
from posthog.hogql_queries.insights.funnels.utils import funnel_window_interval_unit_to_sql
from posthog.hogql_queries.insights.utils.breakdowns import ALL_USERS_COHORT_ID
from posthog.hogql_queries.insights.utils.entities import is_equal, is_superset
-from posthog.models.action.action import Action
from posthog.models.cohort.cohort import Cohort
from posthog.models.property.property import PropertyName
from posthog.queries.breakdown_props import get_breakdown_cohort_name
from posthog.queries.util import correct_result_for_sampling
from posthog.types import FunnelEntityNode
+from products.actions.backend.models.action import Action
+
JOIN_ALGOS = "auto"
diff --git a/posthog/hogql_queries/insights/funnels/funnel_correlation_query_runner.py b/posthog/hogql_queries/insights/funnels/funnel_correlation_query_runner.py
index ce85bddf343a..fd58319a1718 100644
--- a/posthog/hogql_queries/insights/funnels/funnel_correlation_query_runner.py
+++ b/posthog/hogql_queries/insights/funnels/funnel_correlation_query_runner.py
@@ -36,12 +36,13 @@ from posthog.hogql_queries.insights.funnels.utils import funnel_window_interval_
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models import Team
-from posthog.models.action.action import Action
from posthog.models.element.element import chain_to_elements
from posthog.models.event.util import ElementSerializer
from posthog.models.property.util import get_property_string_expr
from posthog.queries.util import correct_result_for_sampling
+from products.actions.backend.models.action import Action
+
class EventOddsRatio(TypedDict):
event: str
diff --git a/posthog/hogql_queries/insights/funnels/funnel_event_query.py b/posthog/hogql_queries/insights/funnels/funnel_event_query.py
index ae7687c968f9..fa69e8eccea4 100644
--- a/posthog/hogql_queries/insights/funnels/funnel_event_query.py
+++ b/posthog/hogql_queries/insights/funnels/funnel_event_query.py
@@ -40,10 +40,11 @@ from posthog.hogql_queries.insights.utils.breakdowns import NOT_IN_COHORT_ID, st
from posthog.hogql_queries.insights.utils.data_warehouse_schema_mixin import DataWarehouseSchemaMixin
from posthog.hogql_queries.insights.utils.properties import Properties
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
-from posthog.models.action.action import Action
from posthog.models.property.property import PropertyName
from posthog.types import FunnelEntityNode, FunnelExclusionEntityNode
+from products.actions.backend.models.action import Action
+
@dataclass
class TableConfigWithSteps:
diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel.py b/posthog/hogql_queries/insights/funnels/test/test_funnel.py
index c67103e7fb34..e73bc03928ab 100644
--- a/posthog/hogql_queries/insights/funnels/test/test_funnel.py
+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel.py
@@ -57,12 +57,13 @@ from posthog.hogql_queries.insights.funnels.test.breakdown_cases import (
funnel_breakdown_test_factory,
)
from posthog.hogql_queries.insights.funnels.test.conversion_time_cases import funnel_conversion_time_test_factory
-from posthog.models import Action, Element
+from posthog.models import Element
from posthog.models.cohort.cohort import Cohort
from posthog.models.group.util import create_group
from posthog.test.test_journeys import journeys_for
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.actions.backend.models.action import Action
from products.event_definitions.backend.models.property_definition import PropertyDefinition
diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel_event_query.py b/posthog/hogql_queries/insights/funnels/test/test_funnel_event_query.py
index 338c18d28020..58796e198538 100644
--- a/posthog/hogql_queries/insights/funnels/test/test_funnel_event_query.py
+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel_event_query.py
@@ -21,8 +21,8 @@ from posthog.hogql import ast
from posthog.hogql_queries.insights.funnels.funnel_event_query import FunnelEventQuery
from posthog.hogql_queries.insights.funnels.funnel_query_context import FunnelQueryContext
-from posthog.models.action.action import Action
+from products.actions.backend.models.action import Action
from products.data_warehouse.backend.models import DataWarehouseCredential, DataWarehouseTable
diff --git a/posthog/hogql_queries/insights/lifecycle/lifecycle_query_runner.py b/posthog/hogql_queries/insights/lifecycle/lifecycle_query_runner.py
index 21ffc1d27b37..e783e89765fe 100644
--- a/posthog/hogql_queries/insights/lifecycle/lifecycle_query_runner.py
+++ b/posthog/hogql_queries/insights/lifecycle/lifecycle_query_runner.py
@@ -35,9 +35,10 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRange, compare
from posthog.hogql_queries.utils.timestamp_utils import format_label_date, get_earliest_timestamp_from_series
from posthog.hogql_queries.validation.rules import DisallowUnsupportedDataWarehouseSettings, RequireAtLeastOneSeries
from posthog.hogql_queries.validation.validation import QueryValidationRule
-from posthog.models import Action
from posthog.models.filters.mixins.utils import cached_property
+from products.actions.backend.models.action import Action
+
class LifecycleQueryRunner(AnalyticsQueryRunner[LifecycleQueryResponse]):
query: LifecycleQuery
diff --git a/posthog/hogql_queries/insights/lifecycle/test/test_lifecycle_query_runner.py b/posthog/hogql_queries/insights/lifecycle/test/test_lifecycle_query_runner.py
index ddc3124c2e1e..4ceacb8172f4 100644
--- a/posthog/hogql_queries/insights/lifecycle/test/test_lifecycle_query_runner.py
+++ b/posthog/hogql_queries/insights/lifecycle/test/test_lifecycle_query_runner.py
@@ -32,13 +32,15 @@ from posthog.schema import (
from posthog.hogql.query import execute_hogql_query
from posthog.hogql_queries.insights.lifecycle.lifecycle_query_runner import LifecycleQueryRunner
-from posthog.models import Action, Cohort
+from posthog.models import Cohort
from posthog.models.group.util import create_group
from posthog.models.instance_setting import get_instance_setting
from posthog.models.team import WeekStartDay
from posthog.models.utils import UUIDT
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.actions.backend.models.action import Action
+
def create_action(**kwargs):
team = kwargs.pop("team")
diff --git a/posthog/hogql_queries/insights/retention/retention_query_runner.py b/posthog/hogql_queries/insights/retention/retention_query_runner.py
index 2dbb9c4ae21b..fc42e5e3f938 100644
--- a/posthog/hogql_queries/insights/retention/retention_query_runner.py
+++ b/posthog/hogql_queries/insights/retention/retention_query_runner.py
@@ -50,10 +50,11 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRangeWithInter
from posthog.hogql_queries.validation.rules import DisallowUnsupportedDataWarehouseSettings
from posthog.hogql_queries.validation.validation import QueryValidationRule
from posthog.models import Team
-from posthog.models.action.action import Action
from posthog.models.filters.mixins.utils import cached_property
from posthog.queries.util import correct_result_for_sampling
+from products.actions.backend.models.action import Action
+
DEFAULT_INTERVAL = IntervalType("day")
DEFAULT_TOTAL_INTERVALS = 7
diff --git a/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py b/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py
index 8494e514abd2..d53fd14c8720 100644
--- a/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py
+++ b/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py
@@ -37,12 +37,13 @@ from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner
from posthog.hogql_queries.insights.retention.retention_query_runner import RetentionQueryRunner
from posthog.hogql_queries.insights.retention.test.utils import pad, pluck
from posthog.hogql_queries.insights.utils.breakdowns import ALL_USERS_COHORT_ID, BREAKDOWN_OTHER_STRING_LABEL
-from posthog.models import Action, Cohort
+from posthog.models import Cohort
from posthog.models.group.util import create_group
from posthog.models.person import Person
from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.actions.backend.models.action import Action
from products.data_warehouse.backend.models import DataWarehouseJoin
from products.data_warehouse.backend.test.utils import create_data_warehouse_table_from_csv
diff --git a/posthog/hogql_queries/insights/trends/calendar_heatmap_query_runner.py b/posthog/hogql_queries/insights/trends/calendar_heatmap_query_runner.py
index 5ef18f172233..4ada96932cd1 100644
--- a/posthog/hogql_queries/insights/trends/calendar_heatmap_query_runner.py
+++ b/posthog/hogql_queries/insights/trends/calendar_heatmap_query_runner.py
@@ -39,9 +39,9 @@ from posthog.hogql_queries.insights.trends.series_with_extras import SeriesWithE
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models import Team
-from posthog.models.action.action import Action
from posthog.models.filters.mixins.utils import cached_property
+from products.actions.backend.models.action import Action
from products.event_definitions.backend.models.property_definition import PropertyDefinition
SEPARATOR = "','"
diff --git a/posthog/hogql_queries/insights/trends/test/test_calendar_heatmap_query_runner.py b/posthog/hogql_queries/insights/trends/test/test_calendar_heatmap_query_runner.py
index 7a27ab16ebfb..acbdbacb2e8c 100644
--- a/posthog/hogql_queries/insights/trends/test/test_calendar_heatmap_query_runner.py
+++ b/posthog/hogql_queries/insights/trends/test/test_calendar_heatmap_query_runner.py
@@ -6,9 +6,10 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _
from posthog.schema import ActionConversionGoal, CalendarHeatmapQuery, CustomEventConversionGoal, DateRange, EventsNode
from posthog.hogql_queries.insights.trends.calendar_heatmap_query_runner import CalendarHeatmapQueryRunner
-from posthog.models import Action
from posthog.models.utils import uuid7
+from products.actions.backend.models.action import Action
+
class TestCalendarHeatmapQueryRunner(ClickhouseTestMixin, APIBaseTest):
def _create_events(self, data, event="$pageview"):
diff --git a/posthog/hogql_queries/insights/trends/test/test_trends.py b/posthog/hogql_queries/insights/trends/test/test_trends.py
index 2737e107b75f..4fc5efb57dc3 100644
--- a/posthog/hogql_queries/insights/trends/test/test_trends.py
+++ b/posthog/hogql_queries/insights/trends/test/test_trends.py
@@ -33,7 +33,7 @@ from posthog.constants import TREND_FILTER_TYPE_EVENTS, TRENDS_BAR_VALUE, TRENDS
from posthog.hogql_queries.insights.trends.test.test_trends_persons import get_actors
from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner
from posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query
-from posthog.models import Action, Cohort, Entity, Filter, Organization, Person
+from posthog.models import Cohort, Entity, Filter, Organization, Person
from posthog.models.group.util import create_group
from posthog.models.instance_setting import get_instance_setting, override_instance_config
from posthog.models.person.util import create_person_distinct_id
@@ -42,6 +42,7 @@ from posthog.models.utils import uuid7
from posthog.test.test_journeys import journeys_for
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.actions.backend.models.action import Action
from products.event_definitions.backend.models.property_definition import PropertyDefinition
diff --git a/posthog/hogql_queries/insights/trends/test/test_trends_persons.py b/posthog/hogql_queries/insights/trends/test/test_trends_persons.py
index b7fb6a2b8ec2..d19c33bb6e54 100644
--- a/posthog/hogql_queries/insights/trends/test/test_trends_persons.py
+++ b/posthog/hogql_queries/insights/trends/test/test_trends_persons.py
@@ -38,10 +38,10 @@ from posthog.api.test.test_team import create_team
from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner
from posthog.hogql_queries.insights.utils.breakdowns import BREAKDOWN_NULL_STRING_LABEL, BREAKDOWN_OTHER_STRING_LABEL
from posthog.models import Cohort, Team
-from posthog.models.action.action import Action
from posthog.models.group.util import create_group
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.actions.backend.models.action import Action
from products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType
diff --git a/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py b/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py
index ef264de68a1b..4a9f8b039b65 100644
--- a/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py
+++ b/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py
@@ -69,13 +69,13 @@ from posthog.hogql_queries.insights.utils.breakdowns import (
BREAKDOWN_OTHER_DISPLAY,
BREAKDOWN_OTHER_STRING_LABEL,
)
-from posthog.models.action.action import Action
from posthog.models.cohort.cohort import Cohort
from posthog.models.group.util import create_group
from posthog.models.team.team import Team, WeekStartDay
from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.actions.backend.models.action import Action
from products.event_definitions.backend.models.property_definition import PropertyDefinition
diff --git a/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py b/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py
index 5cfee65c9d7a..b18c95248316 100644
--- a/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py
+++ b/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py
@@ -35,7 +35,9 @@ from posthog.hogql_queries.insights.trends.utils import group_node_to_expr, is_g
from posthog.hogql_queries.utils.query_compare_to_date_range import QueryCompareToDateRange
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPreviousPeriodDateRange
-from posthog.models import Action, Team
+from posthog.models import Team
+
+from products.actions.backend.models.action import Action
class TrendsActorsQueryBuilder:
diff --git a/posthog/hogql_queries/insights/trends/trends_query_builder.py b/posthog/hogql_queries/insights/trends/trends_query_builder.py
index 0dc0a2637916..68aceea00282 100644
--- a/posthog/hogql_queries/insights/trends/trends_query_builder.py
+++ b/posthog/hogql_queries/insights/trends/trends_query_builder.py
@@ -26,10 +26,11 @@ from posthog.hogql_queries.insights.trends.display import TrendsDisplay
from posthog.hogql_queries.insights.trends.utils import group_node_to_expr, is_groups_math
from posthog.hogql_queries.insights.utils.breakdowns import BREAKDOWN_NULL_STRING_LABEL, BREAKDOWN_OTHER_STRING_LABEL
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
-from posthog.models.action.action import Action
from posthog.models.filters.mixins.utils import cached_property
from posthog.models.team.team import Team
+from products.actions.backend.models.action import Action
+
class TrendsQueryBuilder(DataWarehouseInsightQueryMixin):
query: TrendsQuery
diff --git a/posthog/hogql_queries/insights/trends/trends_query_runner.py b/posthog/hogql_queries/insights/trends/trends_query_runner.py
index 9290bdd75d25..cc7ea0e8dd37 100644
--- a/posthog/hogql_queries/insights/trends/trends_query_runner.py
+++ b/posthog/hogql_queries/insights/trends/trends_query_runner.py
@@ -77,12 +77,12 @@ from posthog.hogql_queries.utils.timestamp_utils import format_label_date, get_e
from posthog.hogql_queries.validation.rules import DisallowUnsupportedDataWarehouseSettings, RequireAtLeastOneSeries
from posthog.hogql_queries.validation.validation import QueryValidationRule
from posthog.models import Team
-from posthog.models.action.action import Action
from posthog.models.cohort.cohort import Cohort
from posthog.models.filters.mixins.utils import cached_property
from posthog.queries.util import correct_result_for_sampling
from posthog.utils import multisort
+from products.actions.backend.models.action import Action
from products.data_warehouse.backend.models.util import get_view_or_table_by_name
from products.event_definitions.backend.models.property_definition import PropertyDefinition
diff --git a/posthog/hogql_queries/insights/trends/utils.py b/posthog/hogql_queries/insights/trends/utils.py
index 09b428f81f19..8601655b45ad 100644
--- a/posthog/hogql_queries/insights/trends/utils.py
+++ b/posthog/hogql_queries/insights/trends/utils.py
@@ -63,7 +63,7 @@ def is_groups_math(series: Union[EventsNode, ActionsNode, DataWarehouseNode | Gr
def group_node_to_expr(group: GroupNode, team: Team) -> ast.Expr | None:
- from posthog.models import Action
+ from products.actions.backend.models.action import Action
group_filters: list[ast.Expr] = []
for node in group.nodes:
diff --git a/posthog/hogql_queries/query_metadata.py b/posthog/hogql_queries/query_metadata.py
index 8dcaae008cdb..d33b0e86a3d5 100644
--- a/posthog/hogql_queries/query_metadata.py
+++ b/posthog/hogql_queries/query_metadata.py
@@ -37,9 +37,11 @@ from posthog.schema import (
)
from posthog.cache_utils import cache_for
-from posthog.models import Action, Team
+from posthog.models import Team
from posthog.utils import get_from_dict_or_attr
+from products.actions.backend.models.action import Action
+
T = TypeVar("T", bound=BaseModel)
diff --git a/posthog/hogql_queries/sessions_query_runner.py b/posthog/hogql_queries/sessions_query_runner.py
index 99c06579a1e5..5cb534f68122 100644
--- a/posthog/hogql_queries/sessions_query_runner.py
+++ b/posthog/hogql_queries/sessions_query_runner.py
@@ -20,12 +20,14 @@ from posthog.hogql.property import action_to_expr, has_aggregation, map_virtual_
from posthog.api.person import PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
-from posthog.models import Action, Person
+from posthog.models import Person
from posthog.models.person.person import get_distinct_ids_for_subquery
from posthog.models.person.util import get_person_by_pk_or_uuid
from posthog.models.property import Property
from posthog.utils import relative_date_parse
+from products.actions.backend.models.action import Action
+
COLUMN_COMMENT_SEPARATOR = " -- "
VALID_IDENTIFIER_PATTERN = re.compile(r"^[A-Za-z_$][A-Za-z0-9_$]*$")
SUPPORTED_PERSON_PROPERTY_OPERATORS = frozenset(
diff --git a/posthog/hogql_queries/test/test_query_metadata.py b/posthog/hogql_queries/test/test_query_metadata.py
index 16e89be8e83b..78b3a913c3c8 100644
--- a/posthog/hogql_queries/test/test_query_metadata.py
+++ b/posthog/hogql_queries/test/test_query_metadata.py
@@ -33,7 +33,8 @@ from posthog.schema import (
)
from posthog.hogql_queries.query_metadata import QueryEventsExtractor
-from posthog.models import Action
+
+from products.actions.backend.models.action import Action
class TestQueryEventsExtractor(TestCase):
@@ -60,7 +61,7 @@ class TestQueryEventsExtractor(TestCase):
result = self.extractor.extract_events(query)
self.assertCountEqual(result, ["pageview", "click"])
- @patch("posthog.models.action.Action.objects.get")
+ @patch("products.actions.backend.models.action.Action.objects.get")
def test_extract_events_with_actions_node(self, mock_action_get):
"""Test extracting events from query with ActionsNode"""
mock_action = Mock()
@@ -76,7 +77,7 @@ class TestQueryEventsExtractor(TestCase):
result = self.extractor.extract_events(query)
self.assertCountEqual(result, ["pageview", "signup", "purchase"])
- @patch("posthog.models.action.Action.objects.get")
+ @patch("products.actions.backend.models.action.Action.objects.get")
def test_extract_events_with_actions_node_with_none_steps(self, mock_action_get):
"""Test extracting events from query with ActionsNode"""
mock_action = Mock()
@@ -92,7 +93,7 @@ class TestQueryEventsExtractor(TestCase):
result = self.extractor.extract_events(query)
self.assertCountEqual(result, ["pageview", "signup"])
- @patch("posthog.models.action.Action.objects.get")
+ @patch("products.actions.backend.models.action.Action.objects.get")
def test_extract_events_with_non_existent_action(self, mock_action_get):
"""Test extracting events from query with non-existent ActionsNode"""
mock_action_get.side_effect = Action.DoesNotExist
@@ -181,7 +182,7 @@ class TestQueryEventsExtractor(TestCase):
result = self.extractor.extract_events(query)
self.assertCountEqual(result, ["signup", "purchase", "abandon_cart", "logout"])
- @patch("posthog.models.action.Action.objects.get")
+ @patch("products.actions.backend.models.action.Action.objects.get")
def test_extract_events_funnels_query_exclusions_actions(self, mock_action_get):
"""Test extracting events from FunnelsQuery with exclusions that include actions"""
mock_action = Mock()
@@ -224,7 +225,7 @@ class TestQueryEventsExtractor(TestCase):
result = self.extractor.extract_events(query)
self.assertCountEqual(result, ["signup", "purchase"])
- @patch("posthog.models.action.Action.objects.get")
+ @patch("products.actions.backend.models.action.Action.objects.get")
def test_extract_events_retention_query(self, mock_action_get):
"""Test extracting events from RetentionQuery"""
mock_action = Mock()
diff --git a/posthog/hogql_queries/utils/test/test_timestamp_utils.py b/posthog/hogql_queries/utils/test/test_timestamp_utils.py
index beb917eadeb5..4f660cfcd821 100644
--- a/posthog/hogql_queries/utils/test/test_timestamp_utils.py
+++ b/posthog/hogql_queries/utils/test/test_timestamp_utils.py
@@ -11,9 +11,10 @@ from posthog.schema import ActionsNode, DateRange, EventsNode, IntervalType
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.hogql_queries.utils.timestamp_utils import format_label_date, get_earliest_timestamp_from_series
-from posthog.models.action.action import Action
from posthog.models.team import WeekStartDay
+from products.actions.backend.models.action import Action
+
@override_settings(IN_UNIT_TESTING=True)
class TestTimestampUtils(APIBaseTest, ClickhouseDestroyTablesMixin):
diff --git a/posthog/hogql_queries/utils/timestamp_utils.py b/posthog/hogql_queries/utils/timestamp_utils.py
index f72e24b68203..ea4ed4d5ce29 100644
--- a/posthog/hogql_queries/utils/timestamp_utils.py
+++ b/posthog/hogql_queries/utils/timestamp_utils.py
@@ -23,10 +23,11 @@ from posthog.hogql.query import execute_hogql_query
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models import Team
-from posthog.models.action.action import Action
from posthog.models.team import WeekStartDay
from posthog.utils import get_safe_cache
+from products.actions.backend.models.action import Action
+
EARLIEST_TIMESTAMP_CACHE_TTL = 24 * 60 * 60
EARLIEST_EVENT_TIMESTAMP = datetime.fromisoformat("1980-01-01T00:00:00Z")
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_analytics_cohort_filter.py b/posthog/hogql_queries/web_analytics/test/test_web_analytics_cohort_filter.py
index ec72a76e1247..15074c4f47e3 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_analytics_cohort_filter.py
+++ b/posthog/hogql_queries/web_analytics/test/test_web_analytics_cohort_filter.py
@@ -16,9 +16,11 @@ from posthog.schema import (
from posthog.hogql_queries.web_analytics.stats_table import WebStatsTableQueryRunner
from posthog.hogql_queries.web_analytics.web_goals import WebGoalsQueryRunner
from posthog.hogql_queries.web_analytics.web_overview import WebOverviewQueryRunner
-from posthog.models import Action, Cohort
+from posthog.models import Cohort
from posthog.models.utils import uuid7
+from products.actions.backend.models.action import Action
+
class TestWebAnalyticsCohortFilter(ClickhouseTestMixin, APIBaseTest):
QUERY_TIMESTAMP = "2026-01-29"
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_goals.py b/posthog/hogql_queries/web_analytics/test/test_web_goals.py
index 0bd7c3f52a08..9bbf661d93b8 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_goals.py
+++ b/posthog/hogql_queries/web_analytics/test/test_web_goals.py
@@ -23,10 +23,12 @@ from posthog.hogql.test.utils import pretty_print_in_tests
from posthog.clickhouse.client import sync_execute
from posthog.hogql_queries.web_analytics.web_goals import WebGoalsQueryRunner
-from posthog.models import Action, Cohort, Element, Person
+from posthog.models import Cohort, Element, Person
from posthog.models.person.sql import PERSON_DISTINCT_ID_OVERRIDES_TABLE
from posthog.models.utils import uuid7
+from products.actions.backend.models.action import Action
+
@snapshot_clickhouse_queries
class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_overview.py b/posthog/hogql_queries/web_analytics/test/test_web_overview.py
index 00459fa0f636..77bdf2b72a7b 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_overview.py
+++ b/posthog/hogql_queries/web_analytics/test/test_web_overview.py
@@ -35,10 +35,12 @@ from posthog.hogql.printer import prepare_and_print_ast
from posthog.clickhouse.client.execute import sync_execute
from posthog.hogql_queries.web_analytics.web_overview import WebOverviewQueryRunner
from posthog.hogql_queries.web_analytics.web_overview_pre_aggregated import WebOverviewPreAggregatedQueryBuilder
-from posthog.models import Action, Cohort, Element
+from posthog.models import Cohort, Element
from posthog.models.utils import uuid7
from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
+from products.actions.backend.models.action import Action
+
@snapshot_clickhouse_queries
class TestWebOverviewQueryRunner(ClickhouseTestMixin, APIBaseTest):
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_stats_table.py b/posthog/hogql_queries/web_analytics/test/test_web_stats_table.py
index eabd3e8dab74..e8fa13b5bb88 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_stats_table.py
+++ b/posthog/hogql_queries/web_analytics/test/test_web_stats_table.py
@@ -36,9 +36,11 @@ from posthog.schema import (
)
from posthog.hogql_queries.web_analytics.stats_table import WebStatsTableQueryRunner
-from posthog.models import Action, Cohort, Element
+from posthog.models import Cohort, Element
from posthog.models.utils import uuid7
+from products.actions.backend.models.action import Action
+
nan_value = float("nan")
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_stats_table_pre_aggregated_conversions.py b/posthog/hogql_queries/web_analytics/test/test_web_stats_table_pre_aggregated_conversions.py
index 980ccac81b3d..8548ba7fd68c 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_stats_table_pre_aggregated_conversions.py
+++ b/posthog/hogql_queries/web_analytics/test/test_web_stats_table_pre_aggregated_conversions.py
@@ -13,10 +13,11 @@ from posthog.schema import (
from posthog.clickhouse.client.execute import sync_execute
from posthog.hogql_queries.web_analytics.stats_table import WebStatsTableQueryRunner
from posthog.hogql_queries.web_analytics.test.web_preaggregated_test_base import WebAnalyticsPreAggregatedTestBase
-from posthog.models import Action
from posthog.models.utils import uuid7
from posthog.models.web_preaggregated.sql import WEB_STATS_INSERT_SQL
+from products.actions.backend.models.action import Action
+
class TestWebStatsTablePreAggregatedConversions(WebAnalyticsPreAggregatedTestBase):
def _setup_test_data(self, user_prefix="user"):
diff --git a/posthog/hogql_queries/web_analytics/web_analytics_query_runner.py b/posthog/hogql_queries/web_analytics/web_analytics_query_runner.py
index 09c796d1d200..3049e6471cb1 100644
--- a/posthog/hogql_queries/web_analytics/web_analytics_query_runner.py
+++ b/posthog/hogql_queries/web_analytics/web_analytics_query_runner.py
@@ -46,11 +46,13 @@ from posthog.hogql_queries.web_analytics.metrics import (
WEB_ANALYTICS_QUERY_ERRORS,
)
from posthog.hogql_queries.web_analytics.traffic_type import get_traffic_category_expr, get_traffic_type_expr
-from posthog.models import Action, User
+from posthog.models import User
from posthog.models.filters.mixins.utils import cached_property
from posthog.rbac.user_access_control import UserAccessControl
from posthog.utils import generate_cache_key, get_safe_cache
+from products.actions.backend.models.action import Action
+
logger = structlog.get_logger(__name__)
WebQueryNode = Union[
diff --git a/posthog/hogql_queries/web_analytics/web_goals.py b/posthog/hogql_queries/web_analytics/web_goals.py
index 051d0b6f4bfd..0e989f98549d 100644
--- a/posthog/hogql_queries/web_analytics/web_goals.py
+++ b/posthog/hogql_queries/web_analytics/web_goals.py
@@ -9,7 +9,8 @@ from posthog.hogql.property import action_to_expr, get_property_type, property_t
from posthog.hogql.query import execute_hogql_query
from posthog.hogql_queries.web_analytics.web_analytics_query_runner import WebAnalyticsQueryRunner
-from posthog.models import Action
+
+from products.actions.backend.models.action import Action
# Returns an array `seq` split into chunks of size `size`
# Example:
diff --git a/posthog/management/commands/test/test_migrate_hooks.py b/posthog/management/commands/test/test_migrate_hooks.py
index 725ed010c271..890dbbac74ec 100644
--- a/posthog/management/commands/test/test_migrate_hooks.py
+++ b/posthog/management/commands/test/test_migrate_hooks.py
@@ -3,9 +3,10 @@ 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.action.action import Action
from posthog.models.hog_functions.hog_function import HogFunction
+from products.actions.backend.models.action import Action
+
from common.hogvm.python.operation import HOGQL_BYTECODE_VERSION
from ee.models.hook import Hook
diff --git a/posthog/middleware.py b/posthog/middleware.py
index 67029275116b..50ba35c259d8 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -40,7 +40,7 @@ from posthog.event_usage import get_event_source, get_mcp_properties, sanitize_h
from posthog.geoip import get_geoip_properties
from posthog.helpers.impersonation import get_original_user_from_session
from posthog.helpers.user_devices import set_known_device_cookie
-from posthog.models import Action, Cohort, FeatureFlag, Insight, Team, User
+from posthog.models import Cohort, FeatureFlag, Insight, Team, User
from posthog.models.activity_logging.utils import (
ACTIVITY_LOG_CLIENT_HEADER,
ACTIVITY_LOG_CLIENT_MAX_LENGTH,
@@ -52,6 +52,7 @@ from posthog.settings import PROJECT_SWITCHING_TOKEN_ALLOWLIST, SITE_URL
from posthog.user_permissions import UserPermissions
from posthog.utils import _is_valid_ip_address
+from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.notebooks.backend.models import Notebook
diff --git a/posthog/migrations/0410_action_steps_population.py b/posthog/migrations/0410_action_steps_population.py
index 74770af4d889..1d6f8b7ee02c 100644
--- a/posthog/migrations/0410_action_steps_population.py
+++ b/posthog/migrations/0410_action_steps_population.py
@@ -5,7 +5,7 @@ from django.db import migrations
def copy_action_steps_to_json(apps, schema_editor):
- from posthog.models import Action
+ from products.actions.backend.models.action import Action
all_actions_with_steps = Action.objects.prefetch_related("action_steps").order_by("pk").all()
diff --git a/posthog/migrations/1168_migrate_alerts_actions_models.py b/posthog/migrations/1168_migrate_alerts_actions_models.py
new file mode 100644
index 000000000000..16ed3553e052
--- /dev/null
+++ b/posthog/migrations/1168_migrate_alerts_actions_models.py
@@ -0,0 +1,163 @@
+# Generated by Django 5.2.14 on 2026-05-20 15:18
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+ALERTS_MODELS = ("alert", "alertcheck", "alertconfiguration", "alertsubscription", "threshold")
+ACTIONS_MODELS = ("action", "actionstep")
+
+
+def _move_content_types(apps, schema_editor, from_label, to_label, model_names):
+ db_alias = schema_editor.connection.alias
+ ContentType = apps.get_model("contenttypes", "ContentType")
+ Permission = apps.get_model("auth", "Permission")
+
+ for model_name in model_names:
+ 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", "alerts", ALERTS_MODELS)
+ _move_content_types(apps, schema_editor, "posthog", "actions", ACTIONS_MODELS)
+
+
+def reverse_content_types(apps, schema_editor):
+ _move_content_types(apps, schema_editor, "alerts", "posthog", ALERTS_MODELS)
+ _move_content_types(apps, schema_editor, "actions", "posthog", ACTIONS_MODELS)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("alerts", "0001_migrate_models"),
+ ("actions", "0001_migrate_actions_models"),
+ ("posthog", "1167_remove_alertconfiguration_is_calculating"),
+ ("surveys", "0002_action_fk_repoint"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AlterField(
+ model_name="pluginconfig",
+ name="match_action",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="plugin_configs",
+ to="actions.action",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="taggeditem",
+ name="action",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="tagged_items",
+ to="actions.action",
+ ),
+ ),
+ migrations.RemoveField(
+ model_name="actionstep",
+ name="action",
+ ),
+ migrations.RemoveField(
+ model_name="alert",
+ name="insight",
+ ),
+ migrations.RemoveField(
+ model_name="alert",
+ name="team",
+ ),
+ migrations.RemoveField(
+ model_name="alertcheck",
+ name="alert_configuration",
+ ),
+ migrations.RemoveField(
+ model_name="alertcheck",
+ name="investigation_notebook",
+ ),
+ migrations.RemoveField(
+ model_name="alertconfiguration",
+ name="created_by",
+ ),
+ migrations.RemoveField(
+ model_name="alertconfiguration",
+ name="insight",
+ ),
+ migrations.RemoveField(
+ model_name="alertconfiguration",
+ name="subscribed_users",
+ ),
+ migrations.RemoveField(
+ model_name="alertconfiguration",
+ name="team",
+ ),
+ migrations.RemoveField(
+ model_name="alertconfiguration",
+ name="threshold",
+ ),
+ migrations.RemoveField(
+ model_name="alertsubscription",
+ name="alert_configuration",
+ ),
+ migrations.AlterUniqueTogether(
+ name="alertsubscription",
+ unique_together=None,
+ ),
+ migrations.RemoveField(
+ model_name="alertsubscription",
+ name="created_by",
+ ),
+ migrations.RemoveField(
+ model_name="alertsubscription",
+ name="user",
+ ),
+ migrations.RemoveField(
+ model_name="threshold",
+ name="created_by",
+ ),
+ migrations.RemoveField(
+ model_name="threshold",
+ name="insight",
+ ),
+ migrations.RemoveField(
+ model_name="threshold",
+ name="team",
+ ),
+ migrations.DeleteModel(
+ name="Action",
+ ),
+ migrations.DeleteModel(
+ name="ActionStep",
+ ),
+ migrations.DeleteModel(
+ name="Alert",
+ ),
+ migrations.DeleteModel(
+ name="AlertCheck",
+ ),
+ migrations.DeleteModel(
+ name="AlertConfiguration",
+ ),
+ migrations.DeleteModel(
+ name="AlertSubscription",
+ ),
+ migrations.DeleteModel(
+ name="Threshold",
+ ),
+ ],
+ 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 f7de5fe37ae8..510001f5397d 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1167_remove_alertconfiguration_is_calculating
+1168_migrate_alerts_actions_models
diff --git a/posthog/models/__init__.py b/posthog/models/__init__.py
index 5ddfec733dde..3f50280b4c11 100644
--- a/posthog/models/__init__.py
+++ b/posthog/models/__init__.py
@@ -14,11 +14,8 @@ from ..session_recordings.models.session_recording_playlist import SessionRecord
from ..session_recordings.models.session_recording_playlist_item import SessionRecordingPlaylistItem
from products.data_warehouse.backend.models import DataWarehouseTable
from ._deprecated_prompts import Prompt, PromptSequence, UserPromptState
-from .action import Action
-from .action.action_step import ActionStep
from .activity_logging.activity_log import ActivityLog
from .activity_logging.notification_viewed import NotificationViewed
-from .alert import AlertConfiguration
from .annotation import Annotation
from .async_deletion import AsyncDeletion, DeletionType
from .async_migration import AsyncMigration, AsyncMigrationError, MigrationStatus
@@ -117,9 +114,6 @@ __all__ = [
"Approval",
"ApprovalPolicy",
"ChangeRequest",
- "AlertConfiguration",
- "Action",
- "ActionStep",
"ActivityLog",
"Annotation",
"AsyncDeletion",
diff --git a/posthog/models/action/__init__.py b/posthog/models/action/__init__.py
index af8c02420553..e69de29bb2d1 100644
--- a/posthog/models/action/__init__.py
+++ b/posthog/models/action/__init__.py
@@ -1,3 +0,0 @@
-from .action import Action
-
-__all__ = ["Action"]
diff --git a/posthog/models/cohort/util.py b/posthog/models/cohort/util.py
index 33450ccda55b..350d0b0d3289 100644
--- a/posthog/models/cohort/util.py
+++ b/posthog/models/cohort/util.py
@@ -35,8 +35,7 @@ from posthog.exceptions import (
ClickHouseQuerySizeExceeded,
ClickHouseQueryTimeOut,
)
-from posthog.models import Action, Filter, Team
-from posthog.models.action.util import format_action_filter
+from posthog.models import Filter, Team
from posthog.models.cohort.calculation_history import CohortCalculationHistory
from posthog.models.cohort.cohort import Cohort, CohortOrEmpty
from posthog.models.cohort.dependencies import get_cohort_dependents
@@ -57,6 +56,9 @@ from posthog.models.person.sql import (
from posthog.models.property import Property, PropertyGroup
from posthog.queries.person_distinct_id_query import get_team_distinct_ids_query
+from products.actions.backend.models.action import Action
+from products.actions.backend.models.util import format_action_filter
+
if TYPE_CHECKING:
from posthog.personhog_client import ReadConsistency
from posthog.queries.util import PersonPropertiesMode
diff --git a/posthog/models/entity/entity.py b/posthog/models/entity/entity.py
index 3b92a669c12a..6ee1e8915597 100644
--- a/posthog/models/entity/entity.py
+++ b/posthog/models/entity/entity.py
@@ -9,13 +9,14 @@ from rest_framework.exceptions import ValidationError
from posthog.schema import RevenueCurrencyPropertyConfig
from posthog.constants import TREND_FILTER_TYPE_ACTIONS, TREND_FILTER_TYPE_DATA_WAREHOUSE, TREND_FILTER_TYPE_EVENTS
-from posthog.models.action import Action
from posthog.models.filters.mixins.funnel import FunnelFromToStepsMixin
from posthog.models.filters.mixins.property import PropertyMixin
from posthog.models.filters.utils import validate_group_type_index
from posthog.models.property import GroupTypeIndex
from posthog.models.utils import sane_repr
+from products.actions.backend.models.action import Action
+
MathType = Literal[
"total",
"dau",
diff --git a/posthog/models/entity/util.py b/posthog/models/entity/util.py
index 6de800f6165f..e765d8173a3b 100644
--- a/posthog/models/entity/util.py
+++ b/posthog/models/entity/util.py
@@ -4,10 +4,11 @@ from typing import Any
from posthog.hogql.hogql import HogQLContext
from posthog.constants import TREND_FILTER_TYPE_ACTIONS
-from posthog.models.action.util import format_action_filter, format_action_filter_event_only
from posthog.models.entity import Entity
from posthog.queries.util import PersonPropertiesMode
+from products.actions.backend.models.util import format_action_filter, format_action_filter_event_only
+
def get_entity_filtering_params(
allowed_entities: Sequence[Entity],
diff --git a/posthog/models/event/query_event_list.py b/posthog/models/event/query_event_list.py
index e1a9475fc169..a81e0d9e2367 100644
--- a/posthog/models/event/query_event_list.py
+++ b/posthog/models/event/query_event_list.py
@@ -11,8 +11,7 @@ from posthog.hogql.constants import DEFAULT_RETURNED_ROWS
from posthog.hogql.context import HogQLContext
from posthog.clickhouse.client.connection import Workload
-from posthog.models import Action, Filter, Team
-from posthog.models.action.util import format_action_filter
+from posthog.models import Filter, Team
from posthog.models.event.sql import (
SELECT_EVENT_BY_TEAM_AND_CONDITIONS_FILTERS_SQL,
SELECT_EVENT_BY_TEAM_AND_CONDITIONS_SQL,
@@ -23,6 +22,9 @@ from posthog.models.property.util import parse_prop_grouped_clauses
from posthog.queries.insight import insight_query_with_columns
from posthog.utils import relative_date_parse
+from products.actions.backend.models.action import Action
+from products.actions.backend.models.util import format_action_filter
+
def parse_timestamp(timestamp: str, tzinfo: ZoneInfo) -> datetime:
try:
diff --git a/posthog/models/file_system/unfiled_file_saver.py b/posthog/models/file_system/unfiled_file_saver.py
index 436a3a2d2912..ed09692bef11 100644
--- a/posthog/models/file_system/unfiled_file_saver.py
+++ b/posthog/models/file_system/unfiled_file_saver.py
@@ -4,7 +4,6 @@ from typing import Optional
from django.utils import timezone
-from posthog.models.action.action import Action
from posthog.models.cohort import Cohort
from posthog.models.feature_flag import FeatureFlag
from posthog.models.file_system.file_system import FileSystem, escape_path, split_path
@@ -15,6 +14,7 @@ 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.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_flow/hog_flow.py b/posthog/models/hog_flow/hog_flow.py
index ac167f06b836..985b5d77990f 100644
--- a/posthog/models/hog_flow/hog_flow.py
+++ b/posthog/models/hog_flow/hog_flow.py
@@ -6,11 +6,12 @@ from django.dispatch.dispatcher import receiver
import structlog
-from posthog.models.action.action import Action
from posthog.models.team.team import Team
from posthog.models.utils import UUIDTModel
from posthog.plugins.plugin_server_api import reload_hog_flows_on_workers
+from products.actions.backend.models.action import Action
+
if TYPE_CHECKING:
pass
diff --git a/posthog/models/hog_functions/hog_function.py b/posthog/models/hog_functions/hog_function.py
index c6f0acc2ae40..902d932537dd 100644
--- a/posthog/models/hog_functions/hog_function.py
+++ b/posthog/models/hog_functions/hog_function.py
@@ -12,7 +12,6 @@ import structlog
from prometheus_client import Counter
from posthog.helpers.encrypted_fields import EncryptedJSONStringField
-from posthog.models.action.action import Action
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
@@ -28,6 +27,8 @@ from posthog.plugins.plugin_server_api import (
)
from posthog.utils import absolute_uri
+from products.actions.backend.models.action import Action
+
if TYPE_CHECKING:
from posthog.models.team import Team
diff --git a/posthog/models/organization.py b/posthog/models/organization.py
index 7062b064622f..d260a6cb8865 100644
--- a/posthog/models/organization.py
+++ b/posthog/models/organization.py
@@ -682,7 +682,7 @@ def ensure_organization_membership_consistency(sender, instance: OrganizationMem
@receiver(models.signals.post_delete, sender=OrganizationMembership)
def clean_up_alert_subscriptions_on_membership_removal(sender, instance: OrganizationMembership, **kwargs):
- from posthog.models.alert import AlertSubscription
+ from products.alerts.backend.models.alert import AlertSubscription
deleted_count, _ = AlertSubscription.objects.filter(
user=instance.user,
diff --git a/posthog/models/plugin.py b/posthog/models/plugin.py
index bf66a22cae79..ffcb85b9ed2c 100644
--- a/posthog/models/plugin.py
+++ b/posthog/models/plugin.py
@@ -251,7 +251,7 @@ class PluginConfig(models.Model):
# DEPRECATED - this never actually got used - filters is the way to go
match_action = models.ForeignKey(
- "posthog.Action",
+ "actions.Action",
on_delete=models.SET_NULL,
related_name="plugin_configs",
blank=True,
diff --git a/posthog/models/property/util.py b/posthog/models/property/util.py
index 4276381c7e39..9cd14bf77984 100644
--- a/posthog/models/property/util.py
+++ b/posthog/models/property/util.py
@@ -21,8 +21,6 @@ from posthog.hogql.visitor import TraversingVisitor
from posthog.clickhouse.kafka_engine import trim_quotes_expr
from posthog.clickhouse.materialized_columns import TableWithProperties, get_materialized_column_for_property
from posthog.constants import PropertyOperatorType
-from posthog.models.action.action import Action
-from posthog.models.action.util import get_action_tables_and_properties
from posthog.models.cohort import Cohort
from posthog.models.cohort.util import (
format_cohort_subquery,
@@ -50,6 +48,9 @@ from posthog.session_recordings.queries.session_query import SessionQuery
from posthog.types import ErrorTrackingIssueFilter
from posthog.utils import is_json, is_valid_regex
+from products.actions.backend.models.action import Action
+from products.actions.backend.models.util import get_action_tables_and_properties
+
StringMatching = Literal["selector", "tag_name", "href", "text"]
# Property Groups Example:
diff --git a/posthog/models/resource_transfer/test/test_inter_project_transferer.py b/posthog/models/resource_transfer/test/test_inter_project_transferer.py
index acbbe2272a63..d2d2a0e193a8 100644
--- a/posthog/models/resource_transfer/test/test_inter_project_transferer.py
+++ b/posthog/models/resource_transfer/test/test_inter_project_transferer.py
@@ -4,7 +4,7 @@ from posthog.test.base import BaseTest
from parameterized import parameterized
-from posthog.models import Action, Insight, Project, Team
+from posthog.models import Insight, Project, Team
from posthog.models.resource_transfer.inter_project_transferer import (
_get_mapped_substitutions,
build_resource_duplication_graph,
@@ -15,6 +15,7 @@ from posthog.models.resource_transfer.inter_project_transferer import (
from posthog.models.resource_transfer.resource_transfer import ResourceTransfer
from posthog.models.resource_transfer.types import ResourceKind, ResourceTransferVertex
+from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile, Text
from products.surveys.backend.models import Survey
diff --git a/posthog/models/resource_transfer/test/test_visitors.py b/posthog/models/resource_transfer/test/test_visitors.py
index 6f4146348680..7ddcebbe933f 100644
--- a/posthog/models/resource_transfer/test/test_visitors.py
+++ b/posthog/models/resource_transfer/test/test_visitors.py
@@ -7,7 +7,7 @@ from django.test import SimpleTestCase
from parameterized import parameterized
-from posthog.models import Action, Cohort
+from posthog.models import Cohort
from posthog.models.resource_transfer.visitors import CohortVisitor, InsightVisitor
from posthog.models.resource_transfer.visitors.experiment import ExperimentVisitor
from posthog.models.resource_transfer.visitors.experiment_holdout import ExperimentHoldoutVisitor
@@ -23,6 +23,7 @@ from posthog.models.resource_transfer.visitors.feature_flag_filters import (
)
from posthog.models.resource_transfer.visitors.survey import SurveyVisitor
+from products.actions.backend.models.action import Action
from products.experiments.backend.models.experiment import ExperimentHoldout
diff --git a/posthog/models/resource_transfer/visitors/action.py b/posthog/models/resource_transfer/visitors/action.py
index d0ba4bf8f7bc..6fd6d0c6f814 100644
--- a/posthog/models/resource_transfer/visitors/action.py
+++ b/posthog/models/resource_transfer/visitors/action.py
@@ -22,6 +22,6 @@ class ActionVisitor(
):
@classmethod
def get_model(cls) -> type[models.Model]:
- from posthog.models import Action
+ from products.actions.backend.models.action import Action
return Action
diff --git a/posthog/models/resource_transfer/visitors/cohort.py b/posthog/models/resource_transfer/visitors/cohort.py
index 71576a5c9008..7263a061fb00 100644
--- a/posthog/models/resource_transfer/visitors/cohort.py
+++ b/posthog/models/resource_transfer/visitors/cohort.py
@@ -36,7 +36,9 @@ class CohortVisitor(
@classmethod
def get_dynamic_edges(cls, resource: Any) -> list[ResourceTransferEdge]:
- from posthog.models import Action, Cohort
+ from posthog.models import Cohort
+
+ from products.actions.backend.models.action import Action
cohort_ids = cls._extract_cohort_ids(resource.filters)
action_ids = cls._extract_action_ids(resource.filters)
diff --git a/posthog/models/resource_transfer/visitors/experiment.py b/posthog/models/resource_transfer/visitors/experiment.py
index 0605804c2306..d48ca2453a8a 100644
--- a/posthog/models/resource_transfer/visitors/experiment.py
+++ b/posthog/models/resource_transfer/visitors/experiment.py
@@ -4,7 +4,7 @@ from typing import Any
from django.db import models
-from posthog.models import Action, Cohort
+from posthog.models import Cohort
from posthog.models.resource_transfer.types import ResourceTransferEdge
from posthog.models.resource_transfer.visitors.base import ResourceTransferVisitor
from posthog.models.resource_transfer.visitors.common import build_edges_for_ids
@@ -14,6 +14,8 @@ from posthog.models.resource_transfer.visitors.experiment_payload import (
rewrite_cohort_in_experiment_payload,
)
+from products.actions.backend.models.action import Action
+
class ExperimentVisitor(
ResourceTransferVisitor,
diff --git a/posthog/models/resource_transfer/visitors/experiment_saved_metric.py b/posthog/models/resource_transfer/visitors/experiment_saved_metric.py
index 564323a7d314..78b52cc41fe1 100644
--- a/posthog/models/resource_transfer/visitors/experiment_saved_metric.py
+++ b/posthog/models/resource_transfer/visitors/experiment_saved_metric.py
@@ -4,12 +4,14 @@ from typing import Any
from django.db import models
-from posthog.models import Action, Cohort
+from posthog.models import Cohort
from posthog.models.resource_transfer.types import ResourcePayload, ResourceTransferEdge
from posthog.models.resource_transfer.visitors.base import ResourceTransferVisitor
from posthog.models.resource_transfer.visitors.common import build_edges_for_ids
from posthog.models.resource_transfer.visitors.insight import InsightVisitor
+from products.actions.backend.models.action import Action
+
class ExperimentSavedMetricVisitor(
ResourceTransferVisitor,
diff --git a/posthog/models/resource_transfer/visitors/feature_flag.py b/posthog/models/resource_transfer/visitors/feature_flag.py
index 3d8aa37520ce..90d124b17756 100644
--- a/posthog/models/resource_transfer/visitors/feature_flag.py
+++ b/posthog/models/resource_transfer/visitors/feature_flag.py
@@ -4,7 +4,7 @@ from typing import Any
from django.db import models
-from posthog.models import Action, Cohort
+from posthog.models import Cohort
from posthog.models.resource_transfer.types import ResourceTransferEdge
from posthog.models.resource_transfer.visitors.base import ResourceTransferVisitor
from posthog.models.resource_transfer.visitors.common import build_edges_for_ids, make_json_id_rewriter
@@ -17,6 +17,7 @@ from posthog.models.resource_transfer.visitors.feature_flag_filters import (
rewrite_holdout_in_flag_payload,
)
+from products.actions.backend.models.action import Action
from products.experiments.backend.models.experiment import ExperimentHoldout
diff --git a/posthog/models/resource_transfer/visitors/insight.py b/posthog/models/resource_transfer/visitors/insight.py
index e13192dca093..350c6e1509bf 100644
--- a/posthog/models/resource_transfer/visitors/insight.py
+++ b/posthog/models/resource_transfer/visitors/insight.py
@@ -37,7 +37,9 @@ class InsightVisitor(
@classmethod
def get_dynamic_edges(cls, resource: Any) -> list[ResourceTransferEdge]:
- from posthog.models import Action, Cohort
+ from posthog.models import Cohort
+
+ from products.actions.backend.models.action import Action
action_ids = cls._extract_action_ids(resource.filters, resource.query)
cohort_ids = cls._extract_cohort_ids(resource.filters, resource.query)
diff --git a/posthog/models/tagged_item.py b/posthog/models/tagged_item.py
index 8a70c07961d9..ab069c76a687 100644
--- a/posthog/models/tagged_item.py
+++ b/posthog/models/tagged_item.py
@@ -64,7 +64,7 @@ class TaggedItem(ModelActivityMixin, UUIDTModel):
related_name="tagged_items",
)
action = models.ForeignKey(
- "Action",
+ "actions.Action",
on_delete=models.CASCADE,
null=True,
blank=True,
diff --git a/posthog/models/test/test_event_model.py b/posthog/models/test/test_event_model.py
index 946ae8d00921..d8d67297fd1b 100644
--- a/posthog/models/test/test_event_model.py
+++ b/posthog/models/test/test_event_model.py
@@ -1,8 +1,10 @@
from posthog.test.base import BaseTest
-from posthog.models import Action, Element, Organization
+from posthog.models import Element, Organization
from posthog.models.event import Selector
+from products.actions.backend.models.action import Action
+
def _create_action(team, steps):
return Action.objects.create(team=team, steps_json=steps)
diff --git a/posthog/models/test/test_hog_flow.py b/posthog/models/test/test_hog_flow.py
index 331ce30fb497..d6cf1f101201 100644
--- a/posthog/models/test/test_hog_flow.py
+++ b/posthog/models/test/test_hog_flow.py
@@ -2,10 +2,11 @@ from unittest.mock import patch
from django.test import TestCase
-from posthog.models.action.action import Action
from posthog.models.hog_flow.hog_flow import HogFlow
from posthog.models.user import User
+from products.actions.backend.models.action import Action
+
class TestHogFlow(TestCase):
def setUp(self):
diff --git a/posthog/models/test/test_hog_function.py b/posthog/models/test/test_hog_function.py
index 7c18461252b2..92c04063d4c6 100644
--- a/posthog/models/test/test_hog_function.py
+++ b/posthog/models/test/test_hog_function.py
@@ -6,7 +6,6 @@ from unittest.mock import Mock, patch
from django.test import TestCase
-from posthog.models.action.action import Action
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
@@ -14,6 +13,8 @@ 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 common.hogvm.python.operation import HOGQL_BYTECODE_VERSION
to_dict = lambda x: json.loads(json.dumps(x))
diff --git a/posthog/models/test/test_remote_config.py b/posthog/models/test/test_remote_config.py
index 3f05af65cc9d..6f5cf01b9209 100644
--- a/posthog/models/test/test_remote_config.py
+++ b/posthog/models/test/test_remote_config.py
@@ -10,11 +10,11 @@ from django.utils import timezone
from parameterized import parameterized
-from posthog.models.action.action import Action
from posthog.models.feature_flag.feature_flag import FeatureFlag
from posthog.models.project import Project
from posthog.models.remote_config import RemoteConfig
+from products.actions.backend.models.action import Action
from products.surveys.backend.models import Survey
CONFIG_REFRESH_QUERY_COUNT = 6
diff --git a/posthog/models/test/test_tagged_item_model.py b/posthog/models/test/test_tagged_item_model.py
index c15fc0a3d0d4..92eaaf36d44e 100644
--- a/posthog/models/test/test_tagged_item_model.py
+++ b/posthog/models/test/test_tagged_item_model.py
@@ -2,8 +2,9 @@ from posthog.test.base import BaseTest
from django.core.exceptions import ValidationError
-from posthog.models import Action, Insight, Tag, TaggedItem
+from posthog.models import Insight, Tag, TaggedItem
+from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
diff --git a/posthog/queries/column_optimizer/foss_column_optimizer.py b/posthog/queries/column_optimizer/foss_column_optimizer.py
index 6a59cde8108c..70d06ea5c2c8 100644
--- a/posthog/queries/column_optimizer/foss_column_optimizer.py
+++ b/posthog/queries/column_optimizer/foss_column_optimizer.py
@@ -7,7 +7,6 @@ from typing import Union, cast
from posthog.clickhouse.materialized_columns import ColumnName, get_materialized_column_for_property
from posthog.constants import TREND_FILTER_TYPE_ACTIONS, FunnelCorrelationType
-from posthog.models.action.util import get_action_tables_and_properties
from posthog.models.entity import Entity
from posthog.models.filters import Filter
from posthog.models.filters.mixins.utils import cached_property
@@ -20,6 +19,8 @@ from posthog.models.property import PropertyIdentifier, PropertyType, TableColum
from posthog.models.property.util import box_value, extract_tables_and_properties
from posthog.queries.property_optimizer import PropertyOptimizer
+from products.actions.backend.models.util import get_action_tables_and_properties
+
class FOSSColumnOptimizer:
"""
diff --git a/posthog/queries/foss_cohort_query.py b/posthog/queries/foss_cohort_query.py
index 556a822bc4a2..c6c812b6035e 100644
--- a/posthog/queries/foss_cohort_query.py
+++ b/posthog/queries/foss_cohort_query.py
@@ -7,7 +7,6 @@ from posthog.schema import PersonsOnEventsMode
from posthog.clickhouse.materialized_columns import ColumnName
from posthog.constants import PropertyOperatorType
from posthog.models import Filter, Team
-from posthog.models.action import Action
from posthog.models.cohort import Cohort
from posthog.models.cohort.util import format_static_cohort_query, get_count_operator, get_entity_query
from posthog.models.filters.mixins.utils import cached_property
@@ -17,6 +16,8 @@ from posthog.queries.event_query import EventQuery
from posthog.queries.util import PersonPropertiesMode
from posthog.utils import relative_date_parse
+from products.actions.backend.models.action import Action
+
Relative_Date = tuple[int, OperatorInterval]
Event = tuple[str, Union[str, int]]
diff --git a/posthog/queries/funnels/base.py b/posthog/queries/funnels/base.py
index 8b2ee1bf6303..c8eecf6ac7d7 100644
--- a/posthog/queries/funnels/base.py
+++ b/posthog/queries/funnels/base.py
@@ -20,7 +20,6 @@ from posthog.constants import (
FunnelOrderType,
)
from posthog.models import Entity, Filter, Team
-from posthog.models.action.util import format_action_filter
from posthog.models.property import PropertyName
from posthog.models.property.util import (
box_value,
@@ -38,6 +37,8 @@ from posthog.queries.insight import insight_sync_execute
from posthog.queries.util import alias_poe_mode_for_legacy, correct_result_for_sampling, get_person_properties_mode
from posthog.utils import generate_short_id, relative_date_parse
+from products.actions.backend.models.util import format_action_filter
+
class ClickhouseFunnelBase(ABC):
QUERY_TYPE = "funnel_base" # should be overridden in subclasses
diff --git a/posthog/queries/funnels/test/test_funnel.py b/posthog/queries/funnels/test/test_funnel.py
index 87e2b4b1595b..1ea9acb57dfc 100644
--- a/posthog/queries/funnels/test/test_funnel.py
+++ b/posthog/queries/funnels/test/test_funnel.py
@@ -20,7 +20,7 @@ from rest_framework.exceptions import ValidationError
from posthog.clickhouse.client import sync_execute
from posthog.constants import FILTER_TEST_ACCOUNTS, INSIGHT_FUNNELS
-from posthog.models import Action, Element
+from posthog.models import Element
from posthog.models.cohort import Cohort
from posthog.models.filters import Filter
from posthog.models.instance_setting import get_instance_setting
@@ -29,6 +29,8 @@ from posthog.queries.funnels.test.breakdown_cases import assert_funnel_results_e
from posthog.queries.funnels.test.conversion_time_cases import funnel_conversion_time_test_factory
from posthog.test.test_journeys import journeys_for
+from products.actions.backend.models.action import Action
+
class TestFunnelBreakdown(
ClickhouseTestMixin,
diff --git a/posthog/queries/test/test_lifecycle.py b/posthog/queries/test/test_lifecycle.py
index d11343796728..2882741e1a5a 100644
--- a/posthog/queries/test/test_lifecycle.py
+++ b/posthog/queries/test/test_lifecycle.py
@@ -10,11 +10,13 @@ from posthog.test.base import (
)
from posthog.constants import FILTER_TEST_ACCOUNTS, TRENDS_LIFECYCLE
-from posthog.models import Action, Filter
+from posthog.models import Filter
from posthog.models.filters.lifecycle_filter import LifecycleFilter
from posthog.models.instance_setting import get_instance_setting
from posthog.queries.trends.trends import Trends
+from products.actions.backend.models.action import Action
+
def create_action(**kwargs):
team = kwargs.pop("team")
diff --git a/posthog/queries/test/test_trends.py b/posthog/queries/test/test_trends.py
index 47c0cb50ce4c..fc943f8f874f 100644
--- a/posthog/queries/test/test_trends.py
+++ b/posthog/queries/test/test_trends.py
@@ -37,7 +37,7 @@ from posthog.constants import (
TRENDS_LINEAR,
TRENDS_TABLE,
)
-from posthog.models import Action, Cohort, Entity, Filter, Organization, Person
+from posthog.models import Cohort, Entity, Filter, Organization, Person
from posthog.models.group.util import create_group
from posthog.models.instance_setting import get_instance_setting, override_instance_config, set_instance_setting
from posthog.models.person.util import create_person_distinct_id
@@ -48,6 +48,8 @@ from posthog.test.test_journeys import journeys_for
from posthog.test.test_utils import create_group_type_mapping_without_created_at
from posthog.utils import generate_cache_key
+from products.actions.backend.models.action import Action
+
def breakdown_label(entity: Entity, value: Union[str, int]) -> dict[str, Optional[Union[str, int]]]:
ret_dict: dict[str, Optional[Union[str, int]]] = {}
diff --git a/posthog/queries/trends/breakdown.py b/posthog/queries/trends/breakdown.py
index e54b3b6653d7..4da9ad44ce15 100644
--- a/posthog/queries/trends/breakdown.py
+++ b/posthog/queries/trends/breakdown.py
@@ -20,7 +20,6 @@ from posthog.constants import (
WEEKLY_ACTIVE,
PropertyOperatorType,
)
-from posthog.models.action.util import format_action_filter
from posthog.models.entity import Entity
from posthog.models.event.sql import EVENT_JOIN_PERSON_SQL
from posthog.models.filters import Filter
@@ -77,6 +76,8 @@ from posthog.queries.util import (
from posthog.session_recordings.queries.session_query import SessionQuery
from posthog.utils import encode_get_request_params, generate_short_id
+from products.actions.backend.models.util import format_action_filter
+
BREAKDOWN_OTHER_DISPLAY = "Other (i.e. all remaining values)"
BREAKDOWN_NULL_DISPLAY = "None (i.e. no value)"
diff --git a/posthog/queries/trends/trends.py b/posthog/queries/trends/trends.py
index 3f1d72c8b8ee..2be8ffff58a5 100644
--- a/posthog/queries/trends/trends.py
+++ b/posthog/queries/trends/trends.py
@@ -18,7 +18,6 @@ from posthog.constants import (
TRENDS_LIFECYCLE,
TRENDS_LINEAR,
)
-from posthog.models.action import Action
from posthog.models.entity import Entity
from posthog.models.filters import Filter
from posthog.models.team import Team
@@ -29,6 +28,8 @@ from posthog.queries.trends.lifecycle import Lifecycle
from posthog.queries.trends.total_volume import TrendsTotalVolume
from posthog.utils import generate_cache_key, get_safe_cache
+from products.actions.backend.models.action import Action
+
class Trends(TrendsTotalVolume, Lifecycle):
def _get_sql_for_entity(self, filter: Filter, team: Team, entity: Entity) -> tuple[str, str, dict, Callable]:
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_by_top_level_event_property.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_by_top_level_event_property.py
index 64faeb74c818..97c8df1e09bc 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_by_top_level_event_property.py
+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_by_top_level_event_property.py
@@ -11,7 +11,6 @@ from parameterized import parameterized, parameterized_class
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.log_entries import TRUNCATE_LOG_ENTRIES_TABLE_SQL
from posthog.models import EventProperty, Person
-from posthog.models.action import Action
from posthog.models.team import Team
from posthog.models.utils import uuid7
from posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingQueryResult
@@ -23,6 +22,8 @@ from posthog.session_recordings.queries.test.listing_recordings.test_utils impor
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
from posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL
+from products.actions.backend.models.action import Action
+
@parameterized_class([{"allow_event_property_expansion": True}, {"allow_event_property_expansion": False}])
@freeze_time("2021-01-01T13:46:23")
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
index d9ebc2d9f3f8..85ab85eef665 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
@@ -32,7 +32,6 @@ from posthog.hogql.printer import prepare_and_print_ast
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.log_entries import TRUNCATE_LOG_ENTRIES_TABLE_SQL
from posthog.models import Person
-from posthog.models.action import Action
from posthog.models.cohort import Cohort
from posthog.models.group.util import create_group
from posthog.models.team import Team
@@ -49,6 +48,8 @@ from posthog.session_recordings.queries.test.session_replay_sql import produce_r
from posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.actions.backend.models.action import Action
+
from ee.clickhouse.materialized_columns.columns import get_materialized_columns, materialize
from ee.clickhouse.models.test.test_cohort import get_person_ids_by_cohort_id
diff --git a/posthog/session_recordings/queries/utils.py b/posthog/session_recordings/queries/utils.py
index 4042f524ffaa..42230e243ff3 100644
--- a/posthog/session_recordings/queries/utils.py
+++ b/posthog/session_recordings/queries/utils.py
@@ -20,9 +20,11 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.property import action_to_expr
-from posthog.models import Action, Team
+from posthog.models import Team
from posthog.types import AnyPropertyFilter
+from products.actions.backend.models.action import Action
+
logger = structlog.get_logger(__name__)
ANONYMOUS_USER_COHORT_FIX_FLAG = "anonymous-user-session-replay-filtering-fix"
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index fe64d2553a0a..26c80aa4894a 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -75,6 +75,8 @@ PRODUCTS_APPS = [
"products.warehouse_sources_queue.backend.apps.WarehouseSourcesQueueConfig",
"products.business_knowledge.backend.apps.BusinessKnowledgeConfig",
"products.deployments.backend.apps.DeploymentsConfig",
+ "products.alerts.backend.apps.AlertsConfig",
+ "products.actions.backend.apps.ActionsConfig",
]
INSTALLED_APPS = [
diff --git a/posthog/tasks/alerts/detector.py b/posthog/tasks/alerts/detector.py
index 5c166f31d1dc..84097212b901 100644
--- a/posthog/tasks/alerts/detector.py
+++ b/posthog/tasks/alerts/detector.py
@@ -7,7 +7,7 @@ from posthog.schema import DetectorType, IntervalType, TrendsAlertConfig, Trends
from posthog.api.services.query import ExecutionMode
from posthog.caching.calculate_results import calculate_for_query_based_insight
-from posthog.models import AlertConfiguration, Insight
+from posthog.models import Insight
from posthog.schema_migrations.upgrade_manager import upgrade_query
from posthog.tasks.alerts.detectors import get_detector
from posthog.tasks.alerts.detectors.base import DetectionResult
@@ -21,6 +21,8 @@ from posthog.tasks.alerts.trends import (
from posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, AlertEvaluationResult
from posthog.utils import get_from_dict_or_attr
+from products.alerts.backend.models.alert import AlertConfiguration
+
# Minimum samples required for each detector type
DETECTOR_MIN_SAMPLES: dict[DetectorType, int] = {
DetectorType.ZSCORE: 31, # window + 1
diff --git a/posthog/tasks/alerts/investigation_notifications.py b/posthog/tasks/alerts/investigation_notifications.py
index f902f78fe455..731789919c55 100644
--- a/posthog/tasks/alerts/investigation_notifications.py
+++ b/posthog/tasks/alerts/investigation_notifications.py
@@ -27,9 +27,10 @@ import structlog
from posthog.schema import AlertState
-from posthog.models.alert import AlertCheck, InvestigationStatus
from posthog.tasks.alerts.utils import dispatch_alert_notification, record_alert_delivery
+from products.alerts.backend.models.alert import AlertCheck, InvestigationStatus
+
logger = structlog.get_logger(__name__)
diff --git a/posthog/tasks/alerts/schedule_restriction.py b/posthog/tasks/alerts/schedule_restriction.py
index 015adb19ee12..5029362c7b26 100644
--- a/posthog/tasks/alerts/schedule_restriction.py
+++ b/posthog/tasks/alerts/schedule_restriction.py
@@ -8,7 +8,7 @@ from typing import Any
import pytz
import structlog
-from posthog.models import AlertConfiguration
+from products.alerts.backend.models.alert import AlertConfiguration
logger = structlog.get_logger(__name__)
diff --git a/posthog/tasks/alerts/test/alert_check_helpers.py b/posthog/tasks/alerts/test/alert_check_helpers.py
index 7172f2cb5677..7e3c89cd90fc 100644
--- a/posthog/tasks/alerts/test/alert_check_helpers.py
+++ b/posthog/tasks/alerts/test/alert_check_helpers.py
@@ -2,9 +2,10 @@ import traceback
from django.db import transaction
-from posthog.models import AlertConfiguration
from posthog.tasks.alerts import utils as alert_utils
+from products.alerts.backend.models import AlertConfiguration
+
def run_alert_check(alert_id: str) -> None:
"""Evaluate an alert, persist the AlertCheck, dispatch notifications."""
diff --git a/posthog/tasks/alerts/test/test_alert_check_helpers.py b/posthog/tasks/alerts/test/test_alert_check_helpers.py
index 6b9680660b6d..a4e785c112bb 100644
--- a/posthog/tasks/alerts/test/test_alert_check_helpers.py
+++ b/posthog/tasks/alerts/test/test_alert_check_helpers.py
@@ -4,10 +4,11 @@ from unittest.mock import MagicMock, patch
from posthog.schema import AlertConditionType, AlertState, InsightThresholdType
from posthog.api.test.dashboards import DashboardAPI
-from posthog.models.alert import AlertCheck
from posthog.tasks.alerts.test.alert_check_helpers import run_alert_check
from posthog.tasks.alerts.utils import AlertEvaluationResult
+from products.alerts.backend.models import AlertCheck
+
class TestRunAlertCheck(APIBaseTest):
def setUp(self) -> None:
diff --git a/posthog/tasks/alerts/test/test_alert_evaluation.py b/posthog/tasks/alerts/test/test_alert_evaluation.py
index 85a50f1a8a24..f4d1d9a833cc 100644
--- a/posthog/tasks/alerts/test/test_alert_evaluation.py
+++ b/posthog/tasks/alerts/test/test_alert_evaluation.py
@@ -7,11 +7,11 @@ from unittest.mock import MagicMock, patch
from posthog.schema import AlertState, ChartDisplayType, EventsNode, TrendsFilter, TrendsFormulaNode, TrendsQuery
from posthog.api.test.dashboards import DashboardAPI
-from posthog.models import AlertConfiguration
-from posthog.models.alert import AlertCheck
from posthog.models.instance_setting import set_instance_setting
from posthog.tasks.alerts.test.alert_check_helpers import run_alert_check
+from products.alerts.backend.models import AlertCheck, AlertConfiguration
+
@freeze_time("2024-06-02T08:55:00.000Z")
@patch("posthog.tasks.alerts.utils.send_notifications_for_errors", return_value=[])
diff --git a/posthog/tasks/alerts/test/test_alert_subscriptions.py b/posthog/tasks/alerts/test/test_alert_subscriptions.py
index bc67ec0b6673..6b7cabc76349 100644
--- a/posthog/tasks/alerts/test/test_alert_subscriptions.py
+++ b/posthog/tasks/alerts/test/test_alert_subscriptions.py
@@ -5,13 +5,14 @@ from unittest.mock import MagicMock, patch
from posthog.schema import ChartDisplayType, EventsNode, TrendsFilter, TrendsQuery
from posthog.api.test.dashboards import DashboardAPI
-from posthog.models import AlertConfiguration, User
-from posthog.models.alert import AlertSubscription
+from posthog.models import User
from posthog.models.instance_setting import set_instance_setting
from posthog.models.organization import Organization, OrganizationMembership
from posthog.tasks.alerts.utils import send_notifications_for_breaches
from posthog.tasks.test.utils_email_tests import mock_email_messages
+from products.alerts.backend.models import AlertConfiguration, AlertSubscription
+
@freeze_time("2024-06-02T08:55:00.000Z")
class TestAlertSubscriptionOrgMembership(APIBaseTest):
diff --git a/posthog/tasks/alerts/test/test_detector_breakdowns.py b/posthog/tasks/alerts/test/test_detector_breakdowns.py
index 832ea30d3919..16053b28a617 100644
--- a/posthog/tasks/alerts/test/test_detector_breakdowns.py
+++ b/posthog/tasks/alerts/test/test_detector_breakdowns.py
@@ -15,13 +15,15 @@ from posthog.schema import (
)
from posthog.caching.fetch_from_cache import InsightResult
-from posthog.models import AlertConfiguration, Insight
+from posthog.models import Insight
from posthog.tasks.alerts.detector import (
MAX_DETECTOR_BREAKDOWN_VALUES,
check_trends_alert_with_detector,
simulate_detector_on_insight,
)
+from products.alerts.backend.models.alert import AlertConfiguration
+
def _make_trend_result(label: str, data: list[float], breakdown_value: str = "") -> dict[str, Any]:
days = [f"2024-06-{i + 1:02d}" for i in range(len(data))]
diff --git a/posthog/tasks/alerts/test/test_investigation_notifications.py b/posthog/tasks/alerts/test/test_investigation_notifications.py
index 25255c575998..e340b21e7287 100644
--- a/posthog/tasks/alerts/test/test_investigation_notifications.py
+++ b/posthog/tasks/alerts/test/test_investigation_notifications.py
@@ -8,14 +8,15 @@ from parameterized import parameterized
from posthog.schema import AlertState
-from posthog.models import AlertConfiguration, Insight
-from posthog.models.alert import AlertCheck, InvestigationStatus
+from posthog.models import Insight
from posthog.tasks.alerts.investigation_notifications import (
INVESTIGATION_NOTIFY_GRACE_MINUTES,
INVESTIGATION_RUNNING_GRACE_MINUTES,
run_investigation_notification_safety_net,
)
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus
+
NOW = datetime(2026, 5, 4, 12, 0, 0, tzinfo=UTC)
diff --git a/posthog/tasks/alerts/test/test_schedule_restriction.py b/posthog/tasks/alerts/test/test_schedule_restriction.py
index 13add588f534..9a1dba413c44 100644
--- a/posthog/tasks/alerts/test/test_schedule_restriction.py
+++ b/posthog/tasks/alerts/test/test_schedule_restriction.py
@@ -7,7 +7,6 @@ from unittest.mock import MagicMock
from parameterized import parameterized
-from posthog.models import AlertConfiguration
from posthog.tasks.alerts import schedule_restriction as schedule_restriction_module
from posthog.tasks.alerts.schedule_restriction import (
is_utc_datetime_blocked,
@@ -16,6 +15,8 @@ from posthog.tasks.alerts.schedule_restriction import (
)
from posthog.tasks.alerts.utils import next_check_at_after_schedule_restriction_change
+from products.alerts.backend.models.alert import AlertConfiguration
+
class TestValidateAndNormalizeScheduleRestriction:
@parameterized.expand(
diff --git a/posthog/tasks/alerts/test/test_trends_absolute_alerts.py b/posthog/tasks/alerts/test/test_trends_absolute_alerts.py
index 38491a5473a2..aac2ebcb2231 100644
--- a/posthog/tasks/alerts/test/test_trends_absolute_alerts.py
+++ b/posthog/tasks/alerts/test/test_trends_absolute_alerts.py
@@ -24,11 +24,11 @@ from posthog.schema import (
from posthog.api.test.dashboards import DashboardAPI
from posthog.caching.calculate_results import calculate_for_query_based_insight
-from posthog.models import AlertConfiguration
-from posthog.models.alert import AlertCheck
from posthog.models.instance_setting import set_instance_setting
from posthog.tasks.alerts.test.alert_check_helpers import run_alert_check
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
+
# 8:55 AM
FROZEN_TIME = dateutil.parser.parse("2024-06-02T08:55:00.000Z")
diff --git a/posthog/tasks/alerts/test/test_trends_relative_alerts.py b/posthog/tasks/alerts/test/test_trends_relative_alerts.py
index a7882632992c..f1dad911f10c 100644
--- a/posthog/tasks/alerts/test/test_trends_relative_alerts.py
+++ b/posthog/tasks/alerts/test/test_trends_relative_alerts.py
@@ -26,11 +26,11 @@ from posthog.schema import (
from posthog.api.test.dashboards import DashboardAPI
from posthog.caching.calculate_results import calculate_for_query_based_insight
-from posthog.models import AlertConfiguration
-from posthog.models.alert import AlertCheck
from posthog.models.instance_setting import set_instance_setting
from posthog.tasks.alerts.test.alert_check_helpers import run_alert_check
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
+
# Tuesday
FROZEN_TIME = dateutil.parser.parse("2024-06-04T08:55:00.000Z")
diff --git a/posthog/tasks/alerts/trends.py b/posthog/tasks/alerts/trends.py
index 011cd17fea6a..9f2ab65eab38 100644
--- a/posthog/tasks/alerts/trends.py
+++ b/posthog/tasks/alerts/trends.py
@@ -18,9 +18,11 @@ from posthog.caching.calculate_results import calculate_for_query_based_insight
from posthog.caching.fetch_from_cache import InsightResult
from posthog.event_usage import EventSource
from posthog.hogql_queries.insights.utils.breakdowns import has_breakdown_filter
-from posthog.models import AlertConfiguration, Insight
+from posthog.models import Insight
from posthog.tasks.alerts.utils import NON_TIME_SERIES_DISPLAY_TYPES, AlertEvaluationResult
+from products.alerts.backend.models.alert import AlertConfiguration
+
# TODO: move the TrendResult UI type to schema.ts and use that instead
class TrendResult(TypedDict):
diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.py
index 4c0427a7d2e8..44d9aa8dee38 100644
--- a/posthog/tasks/alerts/utils.py
+++ b/posthog/tasks/alerts/utils.py
@@ -23,12 +23,12 @@ from posthog.schema import (
from posthog.cdp.internal_events import InternalEventEvent, produce_internal_event
from posthog.email import EmailMessage
from posthog.exceptions_capture import capture_exception
-from posthog.models import AlertConfiguration
-from posthog.models.alert import AlertCheck, derive_detector_event_fields
from posthog.schema_migrations.upgrade_manager import upgrade_query
from posthog.tasks.alerts.schedule_restriction import snap_candidate_utc_to_schedule_restriction
from posthog.utils import get_from_dict_or_attr
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, derive_detector_event_fields
+
logger = structlog.get_logger(__name__)
diff --git a/posthog/tasks/exports/test/test_csv_exporter.py b/posthog/tasks/exports/test/test_csv_exporter.py
index b3840121152b..04ff913b6568 100644
--- a/posthog/tasks/exports/test/test_csv_exporter.py
+++ b/posthog/tasks/exports/test/test_csv_exporter.py
@@ -21,7 +21,7 @@ from requests.exceptions import HTTPError
from posthog.hogql.constants import CSV_EXPORT_BREAKDOWN_LIMIT_INITIAL
-from posthog.models import Action, ExportedAsset
+from posthog.models import ExportedAsset
from posthog.models.utils import UUIDT
from posthog.settings import (
OBJECT_STORAGE_ACCESS_KEY_ID,
@@ -46,6 +46,8 @@ from posthog.tasks.exports.failure_handler import ExcelColumnLimitExceeded
from posthog.test.test_journeys import journeys_for
from posthog.utils import absolute_uri
+from products.actions.backend.models.action import Action
+
TEST_PREFIX = "Test-Exports"
# see GitHub issue #11204
diff --git a/posthog/tasks/hog_flows.py b/posthog/tasks/hog_flows.py
index 23414efeeccf..74f045a8cee2 100644
--- a/posthog/tasks/hog_flows.py
+++ b/posthog/tasks/hog_flows.py
@@ -5,11 +5,12 @@ from django.utils import timezone
from celery import shared_task
from structlog import get_logger
-from posthog.models.action.action import Action
from posthog.plugins.plugin_server_api import reload_hog_flows_on_workers
from posthog.scoping_audit import skip_team_scope_audit
from posthog.tasks.utils import CeleryQueue
+from products.actions.backend.models.action import Action
+
logger = get_logger(__name__)
diff --git a/posthog/tasks/hog_functions.py b/posthog/tasks/hog_functions.py
index b784ce44b7c4..c2e959507592 100644
--- a/posthog/tasks/hog_functions.py
+++ b/posthog/tasks/hog_functions.py
@@ -7,12 +7,13 @@ from celery import shared_task
from structlog import get_logger
from posthog.cdp.filters import compile_filters_bytecode
-from posthog.models.action.action import Action
from posthog.plugins.plugin_server_api import reload_hog_functions_on_workers
from posthog.redis import get_client
from posthog.scoping_audit import skip_team_scope_audit
from posthog.tasks.utils import CeleryQueue
+from products.actions.backend.models.action import Action
+
logger = get_logger(__name__)
diff --git a/posthog/temporal/ai/anomaly_investigation/notebook.py b/posthog/temporal/ai/anomaly_investigation/notebook.py
index d7d1a0edbb69..282d3e4dea22 100644
--- a/posthog/temporal/ai/anomaly_investigation/notebook.py
+++ b/posthog/temporal/ai/anomaly_investigation/notebook.py
@@ -4,9 +4,9 @@ from dataclasses import dataclass
from typing import Any
from posthog.models import Insight
-from posthog.models.alert import AlertCheck, AlertConfiguration
from posthog.temporal.ai.anomaly_investigation.report import InvestigationReport
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
from products.notebooks.backend.util import (
TipTapContent,
TipTapNode,
diff --git a/posthog/temporal/ai/anomaly_investigation/runner.py b/posthog/temporal/ai/anomaly_investigation/runner.py
index 24b1ae7e9d78..fcd83f94ec8f 100644
--- a/posthog/temporal/ai/anomaly_investigation/runner.py
+++ b/posthog/temporal/ai/anomaly_investigation/runner.py
@@ -26,7 +26,6 @@ from posthoganalytics.ai.langchain.callbacks import CallbackHandler
from pydantic import BaseModel, ValidationError
from posthog.models import Team, User
-from posthog.models.alert import AlertConfiguration
from posthog.temporal.ai.anomaly_investigation.prompts import SYSTEM_PROMPT
from posthog.temporal.ai.anomaly_investigation.report import InvestigationReport
from posthog.temporal.ai.anomaly_investigation.tools import (
@@ -38,6 +37,8 @@ from posthog.temporal.ai.anomaly_investigation.tools import (
TopBreakdownArgs,
)
+from products.alerts.backend.models.alert import AlertConfiguration
+
logger = logging.getLogger(__name__)
MAX_TOOL_CALLS = 10
diff --git a/posthog/temporal/ai/anomaly_investigation/tools.py b/posthog/temporal/ai/anomaly_investigation/tools.py
index 61e316193d52..8359d1c8f97e 100644
--- a/posthog/temporal/ai/anomaly_investigation/tools.py
+++ b/posthog/temporal/ai/anomaly_investigation/tools.py
@@ -22,7 +22,8 @@ from pydantic import BaseModel, Field
from posthog.hogql.query import execute_hogql_query
from posthog.models import Team
-from posthog.models.alert import AlertConfiguration
+
+from products.alerts.backend.models.alert import AlertConfiguration
MAX_HOGQL_ROWS = 50
MAX_SERIES_POINTS = 120
diff --git a/posthog/temporal/ai/anomaly_investigation/workflow.py b/posthog/temporal/ai/anomaly_investigation/workflow.py
index 0b4703755def..77331555ad23 100644
--- a/posthog/temporal/ai/anomaly_investigation/workflow.py
+++ b/posthog/temporal/ai/anomaly_investigation/workflow.py
@@ -22,7 +22,6 @@ from temporalio import activity, workflow
from temporalio.common import RetryPolicy
from posthog.models import Team, User
-from posthog.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus
from posthog.tasks.alerts.utils import dispatch_alert_notification, record_alert_delivery
from posthog.temporal.ai.anomaly_investigation.charts import png_to_b64, render_series_chart
from posthog.temporal.ai.anomaly_investigation.notebook import NotebookRenderContext, build_investigation_notebook
@@ -33,6 +32,7 @@ from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.utils import absolute_uri
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus
from products.notebooks.backend.models import Notebook
logger = structlog.get_logger(__name__)
diff --git a/posthog/temporal/ai/sync_vectors.py b/posthog/temporal/ai/sync_vectors.py
index 452bc1d0b1e8..33946ad3addc 100644
--- a/posthog/temporal/ai/sync_vectors.py
+++ b/posthog/temporal/ai/sync_vectors.py
@@ -18,12 +18,13 @@ from openai import APIError as OpenAIAPIError
from posthog.clickhouse.query_tagging import Product, tag_queries
from posthog.exceptions_capture import capture_exception
-from posthog.models import Action
from posthog.models.ai.pg_embeddings import INSERT_BULK_PG_EMBEDDINGS_SQL
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.clickhouse import ClickHouseClient, get_client
from posthog.temporal.common.utils import get_scheduled_start_time
+from products.actions.backend.models.action import Action
+
from ee.hogai.summarizers.chains import abatch_summarize_actions
from ee.hogai.utils.embeddings import aembed_documents, get_async_azure_embeddings_client
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index 0bc39f8a0787..f5326fde250a 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -13,8 +13,6 @@ from posthog.schema import AlertCalculationInterval, AlertState
from posthog.clickhouse.query_tagging import tag_queries
from posthog.errors import CH_TRANSIENT_ERRORS
from posthog.exceptions_capture import capture_exception
-from posthog.models import AlertConfiguration
-from posthog.models.alert import AlertCheck
from posthog.schema_migrations.upgrade_manager import upgrade_query
from posthog.sync import database_sync_to_async
from posthog.tasks.alerts.investigation_notifications import run_investigation_notification_safety_net
@@ -42,6 +40,7 @@ from posthog.temporal.alerts.types import (
)
from posthog.temporal.common.heartbeat import Heartbeater
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
from products.notifications.backend.facade.api import (
NotificationData,
NotificationType,
diff --git a/posthog/temporal/alerts/investigation.py b/posthog/temporal/alerts/investigation.py
index 1217e6ddb743..55daa2a2e606 100644
--- a/posthog/temporal/alerts/investigation.py
+++ b/posthog/temporal/alerts/investigation.py
@@ -12,8 +12,7 @@ from datetime import UTC, datetime, timedelta
from posthog.schema import AlertState
-from posthog.models import AlertConfiguration
-from posthog.models.alert import AlertCheck, InvestigationStatus
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus
INVESTIGATION_COOLDOWN = timedelta(hours=1)
diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_notebook.py b/posthog/temporal/tests/ai/test_anomaly_investigation_notebook.py
index 9eb8bb6008c2..2949c3fca511 100644
--- a/posthog/temporal/tests/ai/test_anomaly_investigation_notebook.py
+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_notebook.py
@@ -1,10 +1,11 @@
from posthog.test.base import BaseTest
from posthog.models import Insight
-from posthog.models.alert import AlertCheck, AlertConfiguration
from posthog.temporal.ai.anomaly_investigation.notebook import NotebookRenderContext, build_investigation_notebook
from posthog.temporal.ai.anomaly_investigation.report import InvestigationHypothesis, InvestigationReport
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
+
class TestAnomalyInvestigationNotebook(BaseTest):
def _make_context(self, report: InvestigationReport) -> NotebookRenderContext:
diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
index 7257f33bf11a..1793a316d782 100644
--- a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
@@ -9,7 +9,6 @@ from asgiref.sync import sync_to_async
from posthog.schema import AlertState
from posthog.models import Insight
-from posthog.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus, InvestigationVerdict
from posthog.temporal.ai.anomaly_investigation.report import InvestigationReport
from posthog.temporal.ai.anomaly_investigation.runner import InvestigationRunResult
from posthog.temporal.ai.anomaly_investigation.workflow import (
@@ -17,6 +16,13 @@ from posthog.temporal.ai.anomaly_investigation.workflow import (
investigate_anomaly_activity,
)
+from products.alerts.backend.models.alert import (
+ AlertCheck,
+ AlertConfiguration,
+ InvestigationStatus,
+ InvestigationVerdict,
+)
+
class TestInvestigationVerdictPersistence(NonAtomicBaseTest):
# NonAtomicBaseTest TRUNCATEs after each test so class-level fixtures stale out;
diff --git a/posthog/temporal/tests/ai/test_sync_vectors.py b/posthog/temporal/tests/ai/test_sync_vectors.py
index 21f906464f35..dad9a0ed3f73 100644
--- a/posthog/temporal/tests/ai/test_sync_vectors.py
+++ b/posthog/temporal/tests/ai/test_sync_vectors.py
@@ -22,7 +22,6 @@ from temporalio.testing import WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
from posthog.clickhouse.client import sync_execute
-from posthog.models import Action
from posthog.models.ai.pg_embeddings import TRUNCATE_PG_EMBEDDINGS_TABLE_SQL
from posthog.temporal.ai.sync_vectors import (
BatchEmbedAndSyncActionsInputs,
@@ -41,6 +40,8 @@ from posthog.temporal.ai.sync_vectors import (
)
from posthog.temporal.common.clickhouse import get_client
+from products.actions.backend.models.action import Action
+
@pytest.fixture(autouse=True)
def cleanup():
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index 7f0ce1f4c56c..dd57c0a1733a 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -22,8 +22,7 @@ from posthog.schema import (
)
from posthog.errors import CHQueryErrorTooManySimultaneousQueries
-from posthog.models import AlertConfiguration, Insight, User
-from posthog.models.alert import AlertCheck
+from posthog.models import Insight, User
from posthog.tasks.alerts.utils import AlertEvaluationResult
from posthog.temporal.alerts.activities import cleanup_alert_checks, evaluate_alert, notify_alert, prepare_alert
from posthog.temporal.alerts.types import (
@@ -34,6 +33,8 @@ from posthog.temporal.alerts.types import (
SkipReason,
)
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
+
def _valid_trends_query() -> dict:
return TrendsQuery(
diff --git a/posthog/temporal/tests/test_alerts_investigation.py b/posthog/temporal/tests/test_alerts_investigation.py
index 9896c62863f8..b37b734e998f 100644
--- a/posthog/temporal/tests/test_alerts_investigation.py
+++ b/posthog/temporal/tests/test_alerts_investigation.py
@@ -15,9 +15,10 @@ from parameterized import parameterized
from posthog.schema import AlertState
from posthog.models import Insight
-from posthog.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus
from posthog.temporal.alerts.investigation import claim_investigation_slot, should_trigger_investigation
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus
+
class TestShouldTriggerInvestigation(BaseTest):
def setUp(self) -> None:
diff --git a/posthog/temporal/tests/test_alerts_workflows.py b/posthog/temporal/tests/test_alerts_workflows.py
index 8cafeccf8f6d..ce089a00b736 100644
--- a/posthog/temporal/tests/test_alerts_workflows.py
+++ b/posthog/temporal/tests/test_alerts_workflows.py
@@ -22,8 +22,7 @@ from posthog.schema import (
TrendsQuery,
)
-from posthog.models import AlertConfiguration, Insight, User
-from posthog.models.alert import AlertCheck
+from posthog.models import Insight, User
from posthog.slo.types import SloArea, SloConfig, SloOperation, SloOutcome
from posthog.tasks.alerts.utils import AlertEvaluationResult
from posthog.temporal.alerts.activities import evaluate_alert, notify_alert, prepare_alert
@@ -32,6 +31,8 @@ from posthog.temporal.alerts.types import CheckAlertWorkflowInputs, SkipReason
from posthog.temporal.alerts.workflows import CheckAlertWorkflow
from posthog.temporal.common.slo_interceptor import SloInterceptor
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
+
CHECK_ALERT_ACTIVITIES: list[Callable[..., Any]] = [prepare_alert, evaluate_alert, notify_alert]
diff --git a/posthog/test/activity_logging/test_alert_activity_logging.py b/posthog/test/activity_logging/test_alert_activity_logging.py
index 5f4724505573..b6fbe8c9103f 100644
--- a/posthog/test/activity_logging/test_alert_activity_logging.py
+++ b/posthog/test/activity_logging/test_alert_activity_logging.py
@@ -223,7 +223,8 @@ class TestAlertActivityLogging(ActivityLogTestHelper):
def test_alert_subscription_activity_logging(self):
from posthog.models import User
- from posthog.models.alert import AlertSubscription
+
+ from products.alerts.backend.models.alert import AlertSubscription
alert = self.create_alert_configuration("Alert for subscription")
other_user = User.objects.create_and_join(
@@ -248,7 +249,8 @@ class TestAlertActivityLogging(ActivityLogTestHelper):
def test_alert_subscription_deletion_logging(self):
from posthog.models import User
- from posthog.models.alert import AlertSubscription
+
+ from products.alerts.backend.models.alert import AlertSubscription
alert = self.create_alert_configuration("Alert for deletion")
other_user = User.objects.create_and_join(
diff --git a/posthog/test/base.py b/posthog/test/base.py
index 375c9c4dba63..3eecdf862d76 100644
--- a/posthog/test/base.py
+++ b/posthog/test/base.py
@@ -77,7 +77,7 @@ from posthog.cloud_utils import TEST_clear_instance_license_cache
from posthog.helpers.two_factor_session import email_mfa_token_generator
from posthog.hogql_queries.ai.ai_table_resolver import AI_EVENT_NAMES as _AI_EVENT_TYPES
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
-from posthog.models import Action, Insight, Organization, Team, User
+from posthog.models import Insight, Organization, Team, User
from posthog.models.ai_events.sql import TRUNCATE_AI_EVENTS_TABLE_SQL
from posthog.models.channel_type.sql import (
CHANNEL_DEFINITION_DATA_SQL,
@@ -197,6 +197,7 @@ from posthog.session_recordings.sql.session_replay_event_sql import (
)
from posthog.test.assert_faster_than import assert_faster_than
+from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.event_definitions.backend.models.property_definition import (
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index 734b2baab639..9bb96b2721b7 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -26,12 +26,13 @@ from social_core.exceptions import AuthCanceled, AuthFailed, AuthMissingParamete
from posthog.api.test.test_organization import create_organization
from posthog.api.test.test_team import create_team
from posthog.middleware import per_request_logging_context_middleware
-from posthog.models import Action, Cohort, FeatureFlag, Insight
+from posthog.models import Cohort, FeatureFlag, Insight
from posthog.models.organization import Organization
from posthog.models.team import Team
from posthog.models.user import User
from posthog.settings import SITE_URL
+from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
diff --git a/products/actions/backend/__init__.py b/products/actions/backend/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/actions/backend/api/__init__.py b/products/actions/backend/api/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/api/action.py b/products/actions/backend/api/action.py
similarity index 97%
rename from posthog/api/action.py
rename to products/actions/backend/api/action.py
index 6a4a66bc0422..6964a23ddeca 100644
--- a/posthog/api/action.py
+++ b/products/actions/backend/api/action.py
@@ -16,12 +16,20 @@ from rest_framework_csv import renderers as csvrenderers
from posthog.schema import ProductKey
+from posthog.api.documentation import (
+ ArrayPropertyFilterSerializer,
+ DatePropertyFilterSerializer,
+ ExistencePropertyFilterSerializer,
+ NumericPropertyFilterSerializer,
+ StringPropertyFilterSerializer,
+)
+from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
+from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin
from posthog.constants import TREND_FILTER_TYPE_EVENTS
from posthog.event_usage import report_user_action
-from posthog.models import Action, Cohort, Insight, Team
-from posthog.models.action.action import ACTION_STEP_MATCHING_OPTIONS
+from posthog.models import Cohort, Insight, 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
@@ -31,18 +39,9 @@ from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
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.experiments.backend.models.experiment import Experiment
-from .documentation import (
- ArrayPropertyFilterSerializer,
- DatePropertyFilterSerializer,
- ExistencePropertyFilterSerializer,
- NumericPropertyFilterSerializer,
- StringPropertyFilterSerializer,
-)
-from .forbid_destroy_model import ForbidDestroyModel
-from .tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin
-
_PropertyFilterUnion = PolymorphicProxySerializer(
component_name="ActionStepPropertyFilter",
serializers=[
@@ -198,7 +197,7 @@ class ActionSerializer(
return False
@extend_schema_field(serializers.CharField(allow_null=True))
- def get_creation_context(self, obj):
+ def get_creation_context(self, obj) -> None:
return None
def validate(self, attrs):
@@ -580,7 +579,9 @@ class ActionViewSet(
@mutable_receiver(model_activity_signal, sender=Action)
-def handle_action_change(sender, scope, before_update, after_update, activity, was_impersonated=False, **kwargs):
+def handle_action_change(
+ sender, scope, before_update, after_update, activity, was_impersonated=False, **kwargs
+) -> None:
# Detect soft delete/restore by checking the deleted field
if before_update and after_update:
if not before_update.deleted and after_update.deleted:
diff --git a/products/actions/backend/api/test/__init__.py b/products/actions/backend/api/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/api/test/test_action.py b/products/actions/backend/api/test/test_action.py
similarity index 99%
rename from posthog/api/test/test_action.py
rename to products/actions/backend/api/test/test_action.py
index 944a56c1310e..4760f1edd386 100644
--- a/posthog/api/test/test_action.py
+++ b/products/actions/backend/api/test/test_action.py
@@ -10,9 +10,11 @@ from unittest.mock import ANY, patch
from rest_framework import status
-from posthog.models import Action, Cohort, Insight, Tag, User
+from posthog.models import Cohort, Insight, Tag, User
from posthog.models.hog_functions.hog_function import HogFunction
+from products.actions.backend.models.action import Action
+
class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
@patch("posthog.api.action.report_user_action")
diff --git a/products/actions/backend/apps.py b/products/actions/backend/apps.py
new file mode 100644
index 000000000000..c3ff9bb5d6f0
--- /dev/null
+++ b/products/actions/backend/apps.py
@@ -0,0 +1,7 @@
+from django.apps import AppConfig
+
+
+class ActionsConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "products.actions.backend"
+ label = "actions"
diff --git a/products/actions/backend/migrations/0001_migrate_actions_models.py b/products/actions/backend/migrations/0001_migrate_actions_models.py
new file mode 100644
index 000000000000..0c6052902ad1
--- /dev/null
+++ b/products/actions/backend/migrations/0001_migrate_actions_models.py
@@ -0,0 +1,194 @@
+# Generated by Django 5.2.14 on 2026-05-20 15:16
+
+import django.utils.timezone
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ initial = True
+
+ dependencies = [
+ ("posthog", "1163_alter_batchexportrun_batch_export_and_more"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.CreateModel(
+ name="Action",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("name", models.CharField(blank=True, max_length=400, null=True)),
+ ("description", models.TextField(blank=True, default="")),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("deleted", models.BooleanField(default=False)),
+ ("post_to_slack", models.BooleanField(default=False)),
+ (
+ "slack_message_format",
+ models.CharField(blank=True, default="", max_length=1200),
+ ),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ("bytecode", models.JSONField(blank=True, null=True)),
+ ("bytecode_error", models.TextField(blank=True, null=True)),
+ ("steps_json", models.JSONField(blank=True, null=True)),
+ (
+ "pinned_at",
+ models.DateTimeField(blank=True, default=None, null=True),
+ ),
+ (
+ "summary",
+ models.TextField(
+ blank=True,
+ help_text="A summary of the action, generated by AI",
+ null=True,
+ ),
+ ),
+ (
+ "last_summarized_at",
+ models.DateTimeField(
+ blank=True,
+ help_text="The last time the action was summarized by AI",
+ null=True,
+ ),
+ ),
+ (
+ "embedding_last_synced_at",
+ models.DateTimeField(
+ blank=True,
+ help_text="The last time the action was synced to the vector database",
+ null=True,
+ ),
+ ),
+ (
+ "embedding_version",
+ models.PositiveSmallIntegerField(
+ blank=True,
+ help_text="The version of the embedding model used to embed the action",
+ null=True,
+ ),
+ ),
+ ("is_calculating", models.BooleanField(default=False)),
+ (
+ "last_calculated_at",
+ models.DateTimeField(blank=True, default=django.utils.timezone.now),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ("events", models.ManyToManyField(blank=True, to="posthog.event")),
+ (
+ "project",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.project",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),
+ ),
+ ],
+ options={
+ "db_table": "posthog_action",
+ },
+ ),
+ migrations.CreateModel(
+ name="ActionStep",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("text", models.CharField(blank=True, max_length=400, null=True)),
+ (
+ "text_matching",
+ models.CharField(
+ blank=True,
+ choices=[
+ ("contains", "contains"),
+ ("regex", "regex"),
+ ("exact", "exact"),
+ ],
+ max_length=400,
+ null=True,
+ ),
+ ),
+ ("href", models.CharField(blank=True, max_length=65535, null=True)),
+ (
+ "href_matching",
+ models.CharField(
+ blank=True,
+ choices=[
+ ("contains", "contains"),
+ ("regex", "regex"),
+ ("exact", "exact"),
+ ],
+ max_length=400,
+ null=True,
+ ),
+ ),
+ ("selector", models.CharField(blank=True, max_length=65535, null=True)),
+ ("url", models.CharField(blank=True, max_length=65535, null=True)),
+ (
+ "url_matching",
+ models.CharField(
+ blank=True,
+ choices=[
+ ("contains", "contains"),
+ ("regex", "regex"),
+ ("exact", "exact"),
+ ],
+ default="contains",
+ max_length=400,
+ null=True,
+ ),
+ ),
+ ("event", models.CharField(blank=True, max_length=400, null=True)),
+ ("properties", models.JSONField(blank=True, default=list, null=True)),
+ ("name", models.CharField(blank=True, max_length=400, null=True)),
+ ("tag_name", models.CharField(blank=True, max_length=400, null=True)),
+ (
+ "action",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="action_steps",
+ to="actions.action",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_actionstep",
+ },
+ ),
+ migrations.AddIndex(
+ model_name="action",
+ index=models.Index(fields=["team_id", "-updated_at"], name="posthog_act_team_id_8c04de_idx"),
+ ),
+ ],
+ database_operations=[],
+ ),
+ ]
diff --git a/products/actions/backend/migrations/__init__.py b/products/actions/backend/migrations/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/actions/backend/migrations/max_migration.txt b/products/actions/backend/migrations/max_migration.txt
new file mode 100644
index 000000000000..05ca0bd663e6
--- /dev/null
+++ b/products/actions/backend/migrations/max_migration.txt
@@ -0,0 +1 @@
+0001_migrate_actions_models
diff --git a/products/actions/backend/models/__init__.py b/products/actions/backend/models/__init__.py
new file mode 100644
index 000000000000..a182089a39ec
--- /dev/null
+++ b/products/actions/backend/models/__init__.py
@@ -0,0 +1,8 @@
+from .action import Action, ActionStepJSON
+from .action_step import ActionStep
+
+__all__ = [
+ "Action",
+ "ActionStep",
+ "ActionStepJSON",
+]
diff --git a/posthog/models/action/action.py b/products/actions/backend/models/action.py
similarity index 88%
rename from posthog/models/action/action.py
rename to products/actions/backend/models/action.py
index 413b073da4ea..6a505d60158b 100644
--- a/posthog/models/action/action.py
+++ b/products/actions/backend/models/action.py
@@ -41,12 +41,12 @@ class ActionStepJSON:
class Action(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.Model):
name = models.CharField(max_length=400, null=True, blank=True)
description = models.TextField(blank=True, default="")
- team = models.ForeignKey("Team", on_delete=models.CASCADE)
- project = models.ForeignKey("Project", on_delete=models.CASCADE, null=True, blank=True)
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
+ project = models.ForeignKey("posthog.Project", on_delete=models.CASCADE, null=True, blank=True)
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)
- events = models.ManyToManyField("Event", blank=True) # type: models.ManyToManyField
+ events = models.ManyToManyField("posthog.Event", blank=True) # type: models.ManyToManyField
post_to_slack = models.BooleanField(default=False)
slack_message_format = models.CharField(default="", max_length=1200, blank=True)
updated_at = models.DateTimeField(auto_now=True)
@@ -71,11 +71,12 @@ class Action(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.Mode
class Meta:
indexes = [models.Index(fields=["team_id", "-updated_at"])]
+ db_table = "posthog_action"
- def __str__(self):
- return self.name
+ def __str__(self) -> str:
+ return self.name or ""
- def save(self, *args, **kwargs):
+ def save(self, *args, **kwargs) -> None:
self.refresh_bytecode()
super().save(*args, **kwargs)
@@ -98,7 +99,7 @@ class Action(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.Mode
should_delete=self.deleted,
)
- def get_analytics_metadata(self):
+ def get_analytics_metadata(self) -> dict:
return {
"post_to_slack": self.post_to_slack,
"name_length": len(self.name or ""),
@@ -120,14 +121,14 @@ class Action(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.Mode
return [ActionStepJSON(**step) for step in self.steps_json or []]
@steps.setter
- def steps(self, value: list[dict]):
+ def steps(self, value: list[dict]) -> None:
# TRICKY: This is a little tricky as DRF will deserialize this here as a dict but typing wise we would expect an ActionStepJSON
self.steps_json = [asdict(ActionStepJSON(**step)) for step in value]
def get_step_events(self) -> list[Union[str, None]]:
return [action_step.event for action_step in self.steps]
- def refresh_bytecode(self):
+ def refresh_bytecode(self) -> None:
from posthog.hogql.compiler.bytecode import create_bytecode
from posthog.hogql.property import action_to_expr
@@ -145,10 +146,10 @@ class Action(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.Mode
@receiver(post_save, sender=Action)
-def action_saved(sender, instance: Action, created, **kwargs):
+def action_saved(sender: type, instance: Action, created: bool, **kwargs: object) -> None:
reload_action_on_workers(team_id=instance.team_id, action_id=instance.id)
@mutable_receiver(post_delete, sender=Action)
-def action_deleted(sender, instance: Action, **kwargs):
+def action_deleted(sender: type, instance: Action, **kwargs: object) -> None:
drop_action_on_workers(team_id=instance.team_id, action_id=instance.id)
diff --git a/posthog/models/action/action_step.py b/products/actions/backend/models/action_step.py
similarity index 96%
rename from posthog/models/action/action_step.py
rename to products/actions/backend/models/action_step.py
index 975137ba39d1..dbe7716028fe 100644
--- a/posthog/models/action/action_step.py
+++ b/products/actions/backend/models/action_step.py
@@ -41,3 +41,6 @@ class ActionStep(models.Model):
name = models.CharField(max_length=400, null=True, blank=True)
# DEPRECATED, don't store new data here
tag_name = models.CharField(max_length=400, null=True, blank=True)
+
+ class Meta:
+ db_table = "posthog_actionstep"
diff --git a/posthog/models/action/util.py b/products/actions/backend/models/util.py
similarity index 98%
rename from posthog/models/action/util.py
rename to products/actions/backend/models/util.py
index 84b32cfb5134..b0b736da3a20 100644
--- a/posthog/models/action/util.py
+++ b/products/actions/backend/models/util.py
@@ -8,12 +8,12 @@ from posthog.hogql.hogql import HogQLContext
from posthog.constants import AUTOCAPTURE_EVENT
from posthog.models import Filter
-from posthog.models.action import Action
-from posthog.models.action.action import ActionStepJSON
from posthog.models.property import Property, PropertyIdentifier
from posthog.models.property.property import OperatorType
from posthog.queries.util import PersonPropertiesMode
+from products.actions.backend.models.action import Action, ActionStepJSON
+
def format_action_filter_event_only(
action: Action,
@@ -36,7 +36,7 @@ def format_action_filter(
action: Action,
hogql_context: HogQLContext,
prepend: str = "action",
- filter_by_team=True,
+ filter_by_team: bool = True,
table_name: str = "",
person_properties_mode: PersonPropertiesMode = PersonPropertiesMode.USING_SUBQUERY,
person_id_joined_alias: str = "person_id",
diff --git a/products/alerts/backend/api/__init__.py b/products/alerts/backend/api/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/api/alert.py b/products/alerts/backend/api/alert.py
similarity index 99%
rename from posthog/api/alert.py
rename to products/alerts/backend/api/alert.py
index d5a7fe247554..fbba6020fc11 100644
--- a/posthog/api/alert.py
+++ b/products/alerts/backend/api/alert.py
@@ -21,7 +21,6 @@ from posthog.schema import (
TrendsAlertConfig,
)
-from posthog.api.alert_schedule_restriction import AlertScheduleRestriction
from posthog.api.documentation import extend_schema_field
from posthog.api.insight import InsightBasicSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin
@@ -30,7 +29,6 @@ from posthog.api.shared import UserBasicSerializer
from posthog.event_usage import get_request_analytics_properties
from posthog.models import Insight, User
from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activity
-from posthog.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold
from posthog.models.signals import model_activity_signal, mutable_receiver
from posthog.resource_limits import LimitKey, check_count_limit
from posthog.schema_migrations.upgrade_manager import upgrade_query
@@ -39,6 +37,9 @@ from posthog.tasks.alerts.schedule_restriction import validate_and_normalize_sch
from posthog.tasks.alerts.utils import next_check_at_after_schedule_restriction_change, validate_alert_config
from posthog.utils import relative_date_parse
+from products.alerts.backend.api.alert_schedule_restriction import AlertScheduleRestriction
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold
+
@extend_schema_field(InsightThreshold) # type: ignore[arg-type]
class ThresholdConfigurationField(serializers.JSONField):
@@ -855,7 +856,7 @@ class AlertSubscriptionContext(AlertConfigurationContext):
@mutable_receiver(model_activity_signal, sender=AlertConfiguration)
def handle_alert_configuration_change(
sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs
-):
+) -> None:
log_activity(
organization_id=after_update.team.organization_id,
team_id=after_update.team_id,
@@ -879,7 +880,7 @@ def handle_alert_configuration_change(
@mutable_receiver(model_activity_signal, sender=Threshold)
def handle_threshold_change(
sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs
-):
+) -> None:
alert_config = None
if hasattr(after_update, "alertconfiguration_set"):
alert_config = after_update.alertconfiguration_set.first()
@@ -907,7 +908,9 @@ def handle_threshold_change(
@mutable_receiver(model_activity_signal, sender=AlertSubscription)
-def handle_alert_subscription_change(before_update, after_update, activity, user, was_impersonated=False, **kwargs):
+def handle_alert_subscription_change(
+ before_update, after_update, activity, user, was_impersonated=False, **kwargs
+) -> None:
alert_config = after_update.alert_configuration
if alert_config:
@@ -935,7 +938,7 @@ def handle_alert_subscription_change(before_update, after_update, activity, user
@receiver(pre_delete, sender=AlertConfiguration)
-def cleanup_alert_hog_functions(sender, instance: AlertConfiguration, **kwargs):
+def cleanup_alert_hog_functions(sender, instance: AlertConfiguration, **kwargs) -> None:
from posthog.models.hog_functions.hog_function import HogFunction, HogFunctionType
for hog_function in HogFunction.objects.filter(
@@ -950,7 +953,7 @@ def cleanup_alert_hog_functions(sender, instance: AlertConfiguration, **kwargs):
@receiver(pre_delete, sender=AlertSubscription)
-def handle_alert_subscription_delete(sender, instance, **kwargs):
+def handle_alert_subscription_delete(sender, instance, **kwargs) -> None:
from posthog.models.activity_logging.model_activity import get_current_user, get_was_impersonated
alert_config = instance.alert_configuration
diff --git a/posthog/api/alert_schedule_restriction.py b/products/alerts/backend/api/alert_schedule_restriction.py
similarity index 100%
rename from posthog/api/alert_schedule_restriction.py
rename to products/alerts/backend/api/alert_schedule_restriction.py
diff --git a/products/alerts/backend/api/test/__init__.py b/products/alerts/backend/api/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/api/test/test_alert.py b/products/alerts/backend/api/test/test_alert.py
similarity index 99%
rename from posthog/api/test/test_alert.py
rename to products/alerts/backend/api/test/test_alert.py
index 6a5d32f147b1..d68572660d9b 100644
--- a/posthog/api/test/test_alert.py
+++ b/products/alerts/backend/api/test/test_alert.py
@@ -11,13 +11,13 @@ from rest_framework import status
from posthog.schema import AlertConditionType, AlertState, InsightThresholdType
-from posthog.models import AlertConfiguration
-from posthog.models.alert import AlertCheck
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
+
class TestAlert(APIBaseTest, QueryMatchingTest):
def setUp(self):
@@ -305,7 +305,9 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
assert 4.0 not in values
def test_alert_limit(self) -> None:
- with mock.patch("posthog.api.alert.AlertConfiguration.ALERTS_ALLOWED_ON_FREE_TIER") as alert_limit:
+ with mock.patch(
+ "products.alerts.backend.api.alert.AlertConfiguration.ALERTS_ALLOWED_ON_FREE_TIER"
+ ) as alert_limit:
alert_limit.__get__ = mock.Mock(return_value=1)
creation_request = {
diff --git a/products/alerts/backend/apps.py b/products/alerts/backend/apps.py
new file mode 100644
index 000000000000..8b3464b3b11d
--- /dev/null
+++ b/products/alerts/backend/apps.py
@@ -0,0 +1,7 @@
+from django.apps import AppConfig
+
+
+class AlertsConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "products.alerts.backend"
+ label = "alerts"
diff --git a/products/alerts/backend/max_tools.py b/products/alerts/backend/max_tools.py
index 21277d5b239f..8db46cf9846d 100644
--- a/products/alerts/backend/max_tools.py
+++ b/products/alerts/backend/max_tools.py
@@ -17,13 +17,14 @@ from posthog.schema import (
from posthog.event_usage import EventSource
from posthog.exceptions_capture import capture_exception
-from posthog.models.alert import AlertConfiguration, AlertSubscription, Threshold
from posthog.models.insight import Insight
from posthog.models.team import Team
from posthog.models.user import User
from posthog.rbac.user_access_control import AccessControlLevel
from posthog.scopes import APIScopeObject
+from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Threshold
+
from ee.hogai.artifacts.types import ModelArtifactResult
from ee.hogai.tool import MaxTool
diff --git a/products/alerts/backend/migrations/0001_migrate_models.py b/products/alerts/backend/migrations/0001_migrate_models.py
new file mode 100644
index 000000000000..69e7d3370dbb
--- /dev/null
+++ b/products/alerts/backend/migrations/0001_migrate_models.py
@@ -0,0 +1,394 @@
+# Generated by Django 5.2.14 on 2026-05-20 15:18
+
+import django.db.models.deletion
+import django.db.models.expressions
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.schema
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ initial = True
+
+ dependencies = [
+ ("notebooks", "0003_add_kernel_timeouts"),
+ ("posthog", "1163_alter_batchexportrun_batch_export_and_more"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.CreateModel(
+ name="Alert",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("name", models.CharField(max_length=100)),
+ ("target_value", models.TextField()),
+ ("anomaly_condition", models.JSONField(default=dict)),
+ (
+ "insight",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.insight",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),
+ ),
+ ],
+ options={
+ "db_table": "posthog_alert",
+ },
+ ),
+ migrations.CreateModel(
+ name="AlertConfiguration",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.UUIDT,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("name", models.CharField(blank=True, max_length=255)),
+ ("config", models.JSONField(blank=True, default=dict, null=True)),
+ (
+ "calculation_interval",
+ models.CharField(
+ blank=True,
+ choices=[
+ (
+ posthog.schema.AlertCalculationInterval["EVERY_15_MINUTES"],
+ "every_15_minutes",
+ ),
+ (
+ posthog.schema.AlertCalculationInterval["HOURLY"],
+ "hourly",
+ ),
+ (posthog.schema.AlertCalculationInterval["DAILY"], "daily"),
+ (
+ posthog.schema.AlertCalculationInterval["WEEKLY"],
+ "weekly",
+ ),
+ (
+ posthog.schema.AlertCalculationInterval["MONTHLY"],
+ "monthly",
+ ),
+ ],
+ default=posthog.schema.AlertCalculationInterval["DAILY"],
+ max_length=20,
+ null=True,
+ ),
+ ),
+ ("condition", models.JSONField(default=dict)),
+ ("detector_config", models.JSONField(blank=True, null=True)),
+ (
+ "state",
+ models.CharField(
+ choices=[
+ (
+ posthog.schema.AlertState["FIRING"],
+ posthog.schema.AlertState["FIRING"],
+ ),
+ (
+ posthog.schema.AlertState["NOT_FIRING"],
+ posthog.schema.AlertState["NOT_FIRING"],
+ ),
+ (
+ posthog.schema.AlertState["ERRORED"],
+ posthog.schema.AlertState["ERRORED"],
+ ),
+ (
+ posthog.schema.AlertState["SNOOZED"],
+ posthog.schema.AlertState["SNOOZED"],
+ ),
+ ],
+ default=posthog.schema.AlertState["NOT_FIRING"],
+ max_length=10,
+ ),
+ ),
+ ("enabled", models.BooleanField(default=True)),
+ ("last_notified_at", models.DateTimeField(blank=True, null=True)),
+ ("last_checked_at", models.DateTimeField(blank=True, null=True)),
+ ("next_check_at", models.DateTimeField(blank=True, null=True)),
+ ("snoozed_until", models.DateTimeField(blank=True, null=True)),
+ (
+ "skip_weekend",
+ models.BooleanField(blank=True, default=False, null=True),
+ ),
+ (
+ "schedule_restriction",
+ models.JSONField(blank=True, default=None, null=True),
+ ),
+ ("investigation_agent_enabled", models.BooleanField(default=False)),
+ (
+ "investigation_gates_notifications",
+ models.BooleanField(default=False),
+ ),
+ (
+ "investigation_inconclusive_action",
+ models.CharField(
+ choices=[("notify", "Notify"), ("suppress", "Suppress")],
+ default="notify",
+ max_length=10,
+ ),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "insight",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.insight",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),
+ ),
+ ],
+ options={
+ "db_table": "posthog_alertconfiguration",
+ },
+ ),
+ migrations.CreateModel(
+ name="AlertCheck",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.UUIDT,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("calculated_value", models.FloatField(blank=True, null=True)),
+ ("condition", models.JSONField(default=dict)),
+ ("targets_notified", models.JSONField(default=dict)),
+ ("error", models.JSONField(blank=True, null=True)),
+ (
+ "state",
+ models.CharField(
+ choices=[
+ (
+ posthog.schema.AlertState["FIRING"],
+ posthog.schema.AlertState["FIRING"],
+ ),
+ (
+ posthog.schema.AlertState["NOT_FIRING"],
+ posthog.schema.AlertState["NOT_FIRING"],
+ ),
+ (
+ posthog.schema.AlertState["ERRORED"],
+ posthog.schema.AlertState["ERRORED"],
+ ),
+ (
+ posthog.schema.AlertState["SNOOZED"],
+ posthog.schema.AlertState["SNOOZED"],
+ ),
+ ],
+ default=posthog.schema.AlertState["NOT_FIRING"],
+ max_length=10,
+ ),
+ ),
+ ("anomaly_scores", models.JSONField(blank=True, null=True)),
+ ("triggered_points", models.JSONField(blank=True, null=True)),
+ ("triggered_dates", models.JSONField(blank=True, null=True)),
+ ("interval", models.CharField(blank=True, max_length=10, null=True)),
+ ("triggered_metadata", models.JSONField(blank=True, null=True)),
+ (
+ "investigation_status",
+ models.CharField(
+ blank=True,
+ choices=[
+ ("pending", "pending"),
+ ("running", "running"),
+ ("done", "done"),
+ ("failed", "failed"),
+ ("skipped", "skipped"),
+ ],
+ max_length=10,
+ null=True,
+ ),
+ ),
+ (
+ "investigation_verdict",
+ models.CharField(
+ blank=True,
+ choices=[
+ ("true_positive", "true_positive"),
+ ("false_positive", "false_positive"),
+ ("inconclusive", "inconclusive"),
+ ],
+ max_length=20,
+ null=True,
+ ),
+ ),
+ ("investigation_summary", models.TextField(blank=True, null=True)),
+ ("investigation_error", models.JSONField(blank=True, null=True)),
+ ("notification_sent_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "notification_suppressed_by_agent",
+ models.BooleanField(default=False),
+ ),
+ (
+ "investigation_notebook",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="notebooks.notebook",
+ ),
+ ),
+ (
+ "alert_configuration",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ to="alerts.alertconfiguration",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_alertcheck",
+ },
+ ),
+ migrations.CreateModel(
+ name="AlertSubscription",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.UUIDT,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("subscribed", models.BooleanField(default=True)),
+ (
+ "alert_configuration",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ to="alerts.alertconfiguration",
+ ),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "user",
+ models.ForeignKey(
+ limit_choices_to={
+ "is_active": True,
+ "organization_id": django.db.models.expressions.OuterRef(
+ "alert_configuration__team__organization_id"
+ ),
+ },
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="alert_subscriptions",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_alertsubscription",
+ "unique_together": {("user", "alert_configuration")},
+ },
+ ),
+ migrations.AddField(
+ model_name="alertconfiguration",
+ name="subscribed_users",
+ field=models.ManyToManyField(
+ related_name="alert_configurations",
+ through="alerts.AlertSubscription",
+ through_fields=("alert_configuration", "user"),
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ migrations.CreateModel(
+ name="Threshold",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.UUIDT,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("name", models.CharField(blank=True, max_length=255)),
+ ("configuration", models.JSONField(default=dict)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "insight",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.insight",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),
+ ),
+ ],
+ options={
+ "db_table": "posthog_threshold",
+ },
+ ),
+ migrations.AddField(
+ model_name="alertconfiguration",
+ name="threshold",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="alerts.threshold",
+ ),
+ ),
+ ],
+ database_operations=[],
+ ),
+ ]
diff --git a/products/alerts/backend/migrations/__init__.py b/products/alerts/backend/migrations/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/alerts/backend/migrations/max_migration.txt b/products/alerts/backend/migrations/max_migration.txt
new file mode 100644
index 000000000000..09da3a27f2cf
--- /dev/null
+++ b/products/alerts/backend/migrations/max_migration.txt
@@ -0,0 +1 @@
+0001_migrate_models
diff --git a/products/alerts/backend/models/__init__.py b/products/alerts/backend/models/__init__.py
new file mode 100644
index 000000000000..883ad1df8074
--- /dev/null
+++ b/products/alerts/backend/models/__init__.py
@@ -0,0 +1,9 @@
+from .alert import Alert, AlertCheck, AlertConfiguration, AlertSubscription, Threshold
+
+__all__ = [
+ "Alert",
+ "AlertCheck",
+ "AlertConfiguration",
+ "AlertSubscription",
+ "Threshold",
+]
diff --git a/posthog/models/alert.py b/products/alerts/backend/models/alert.py
similarity index 95%
rename from posthog/models/alert.py
rename to products/alerts/backend/models/alert.py
index e1038b93041e..aeda3d4c1328 100644
--- a/posthog/models/alert.py
+++ b/products/alerts/backend/models/alert.py
@@ -66,13 +66,16 @@ def derive_detector_event_fields(detector_config: dict | None) -> dict:
# TODO: Enable `@deprecated` once we move to Python 3.13
# @deprecated("AlertConfiguration should be used instead.")
class Alert(models.Model):
- team = models.ForeignKey("Team", on_delete=models.CASCADE)
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
insight = models.ForeignKey("posthog.Insight", on_delete=models.CASCADE)
name = models.CharField(max_length=100)
target_value = models.TextField()
anomaly_condition = models.JSONField(default=dict)
+ class Meta:
+ db_table = "posthog_alert"
+
class Threshold(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
"""
@@ -80,13 +83,16 @@ class Threshold(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
object for other purposes.
"""
- team = models.ForeignKey("Team", on_delete=models.CASCADE)
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
insight = models.ForeignKey("posthog.Insight", on_delete=models.CASCADE)
name = models.CharField(max_length=255, blank=True)
configuration = models.JSONField(default=dict)
- def clean(self):
+ class Meta:
+ db_table = "posthog_threshold"
+
+ def clean(self) -> None:
try:
config = InsightThreshold.model_validate(self.configuration)
except pydantic.ValidationError as e:
@@ -102,13 +108,13 @@ class Threshold(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
ALERTS_ALLOWED_ON_FREE_TIER = 5
- team = models.ForeignKey("Team", on_delete=models.CASCADE)
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
insight = models.ForeignKey("posthog.Insight", on_delete=models.CASCADE)
name = models.CharField(max_length=255, blank=True)
subscribed_users = models.ManyToManyField(
"posthog.User",
- through="posthog.AlertSubscription",
+ through="alerts.AlertSubscription",
through_fields=("alert_configuration", "user"),
related_name="alert_configurations",
)
@@ -178,7 +184,10 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
default="notify",
)
- def __str__(self):
+ class Meta:
+ db_table = "posthog_alertconfiguration"
+
+ def __str__(self) -> str:
return f"{self.name} (Team: {self.team})"
def get_subscribed_users_emails(self) -> list[str]:
@@ -198,7 +207,7 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
updated.append("next_check_at")
return updated
- def save(self, *args, **kwargs):
+ def save(self, *args, **kwargs) -> None:
if not self.enabled:
# When disabling an alert, set the state to not firing
self.state = AlertState.NOT_FIRING
@@ -302,7 +311,7 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
class AlertSubscription(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
user = models.ForeignKey(
- "User",
+ "posthog.User",
on_delete=models.CASCADE,
limit_choices_to={
"is_active": True,
@@ -313,11 +322,12 @@ class AlertSubscription(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
alert_configuration = models.ForeignKey(AlertConfiguration, on_delete=models.CASCADE)
subscribed = models.BooleanField(default=True)
- def __str__(self):
+ def __str__(self) -> str:
return f"AlertSubscription for {self.alert_configuration.name} by {self.user.email}"
class Meta:
unique_together = ["user", "alert_configuration"]
+ db_table = "posthog_alertsubscription"
class AlertCheck(UUIDTModel):
@@ -365,7 +375,10 @@ class AlertCheck(UUIDTModel):
# in the UI so users can audit which fires the agent swallowed.
notification_suppressed_by_agent = models.BooleanField(default=False)
- def __str__(self):
+ class Meta:
+ db_table = "posthog_alertcheck"
+
+ def __str__(self) -> str:
return f"AlertCheck for {self.alert_configuration.name} at {self.created_at}"
@classmethod
diff --git a/products/alerts/backend/test_max_tools.py b/products/alerts/backend/test_max_tools.py
index 9f6144588056..f8a74bfd3e88 100644
--- a/products/alerts/backend/test_max_tools.py
+++ b/products/alerts/backend/test_max_tools.py
@@ -10,9 +10,10 @@ from parameterized import parameterized
from posthog.schema import AlertCalculationInterval, AlertConditionType, AlertState, InsightThresholdType
from posthog.models import Organization, Team
-from posthog.models.alert import AlertConfiguration, AlertSubscription, Threshold
from posthog.models.insight import Insight
+from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Threshold
+
from .max_tools import CreateAlertAction, UpdateAlertAction, UpsertAlertTool
diff --git a/products/alerts/frontend/generated/api.schemas.ts b/products/alerts/frontend/generated/api.schemas.ts
index 7a10e33c9e3a..84d9c19bd0bf 100644
--- a/products/alerts/frontend/generated/api.schemas.ts
+++ b/products/alerts/frontend/generated/api.schemas.ts
@@ -635,6 +635,25 @@ export interface AlertSimulateResponseApi {
breakdown_results?: BreakdownSimulationResultApi[]
}
+export interface ThresholdWithAlertApi {
+ readonly id: string
+ readonly created_at: string
+ /** Optional name for the threshold. */
+ name?: string
+ /** Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage). */
+ configuration: InsightThresholdApi
+ readonly alerts: readonly AlertApi[]
+}
+
+export interface PaginatedThresholdWithAlertListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: ThresholdWithAlertApi[]
+}
+
export type AlertsListParams = {
/**
* Number of results to return per page.
@@ -664,3 +683,14 @@ export type AlertsRetrieveParams = {
*/
checks_offset?: number
}
+
+export type InsightsThresholdsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
diff --git a/products/alerts/frontend/generated/api.ts b/products/alerts/frontend/generated/api.ts
index 3c0b8816300e..afa6d57d0295 100644
--- a/products/alerts/frontend/generated/api.ts
+++ b/products/alerts/frontend/generated/api.ts
@@ -14,7 +14,9 @@ import type {
AlertSimulateResponseApi,
AlertsListParams,
AlertsRetrieveParams,
+ InsightsThresholdsListParams,
PaginatedAlertListApi,
+ PaginatedThresholdWithAlertListApi,
PatchedAlertApi,
} from './api.schemas'
@@ -173,3 +175,35 @@ export const alertsSimulateCreate = async (
body: JSON.stringify(alertSimulateApi),
})
}
+
+export const getInsightsThresholdsListUrl = (
+ projectId: string,
+ insightId: number,
+ params?: InsightsThresholdsListParams
+) => {
+ 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}/insights/${insightId}/thresholds/?${stringifiedParams}`
+ : `/api/projects/${projectId}/insights/${insightId}/thresholds/`
+}
+
+export const insightsThresholdsList = async (
+ projectId: string,
+ insightId: number,
+ params?: InsightsThresholdsListParams,
+ options?: RequestInit
+): Promise<PaginatedThresholdWithAlertListApi> => {
+ return apiMutator<PaginatedThresholdWithAlertListApi>(getInsightsThresholdsListUrl(projectId, insightId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
diff --git a/products/alerts/mcp/tools.yaml b/products/alerts/mcp/tools.yaml
index b3fb3cae93d0..ba255be00e0e 100644
--- a/products/alerts/mcp/tools.yaml
+++ b/products/alerts/mcp/tools.yaml
@@ -131,6 +131,9 @@ tools:
alerts-update:
operation: alerts_update
enabled: false
+ insights-thresholds-list:
+ operation: insights_thresholds_list
+ enabled: false
logs-alerts-create:
operation: logs_alerts_create
enabled: false
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index e4cb31b10200..45e7389eefc6 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -59,7 +59,6 @@ from posthog.helpers.trigram_search import (
from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.models import Insight
from posthog.models.activity_logging.activity_log import Detail, changes_between, log_activity
-from posthog.models.alert import AlertConfiguration
from posthog.models.insight_variable import InsightVariable
from posthog.models.quick_filter import QuickFilter
from posthog.models.signals import model_activity_signal, mutable_receiver
@@ -72,6 +71,7 @@ from posthog.resource_limits import LimitKey, check_count_limit
from posthog.user_permissions import UserPermissionsSerializerMixin
from posthog.utils import filters_override_requested_by_client, str_to_bool, variables_override_requested_by_client
+from products.alerts.backend.models.alert import AlertConfiguration
from products.dashboards.backend.api.dashboard_ai import generate_refresh_analysis
from products.dashboards.backend.api.dashboard_template_json_schema_parser import (
DashboardTemplateCreationJSONSchemaParser,
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 1ca9daec52c3..210d4e795da7 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -24,7 +24,6 @@ from posthog.api.feature_flag import FeatureFlagSerializer
from posthog.event_usage import EventSource, report_user_action
from posthog.hogql_queries.experiments.experiment_metric_fingerprint import compute_metric_fingerprint
from posthog.hogql_queries.experiments.funnel_validation import FunnelDWValidator
-from posthog.models.action.action import Action
from posthog.models.cohort import Cohort
from posthog.models.evaluation_context import FeatureFlagEvaluationContext
from posthog.models.feature_flag.feature_flag import FeatureFlag
@@ -33,6 +32,7 @@ from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.team.team import Team
from posthog.utils import str_to_bool
+from products.actions.backend.models.action import Action
from products.experiments.backend.models.experiment import (
LEGACY_METRIC_KINDS,
Experiment,
diff --git a/products/experiments/backend/metric_utils.py b/products/experiments/backend/metric_utils.py
index cd34d0d6d9d0..a77ca13b393f 100644
--- a/products/experiments/backend/metric_utils.py
+++ b/products/experiments/backend/metric_utils.py
@@ -4,9 +4,10 @@ import copy
import logging
from typing import Any
-from posthog.models.action.action import Action
from posthog.models.team.team import Team
+from products.actions.backend.models.action import Action
+
def _get_source_name(source: dict) -> str:
"""Extract a display name from an event/action/data warehouse source dict."""
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index 919e22a350ad..d2110a3439aa 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -18,11 +18,11 @@ from posthog.schema import EventsNode, ExperimentMetric
from posthog.api.feature_flag import FeatureFlagSerializer
from posthog.models import FeatureFlag, Team
-from posthog.models.action.action import Action
from posthog.models.cohort import Cohort
from posthog.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext
from posthog.models.team.extensions import get_or_create_team_extension
+from products.actions.backend.models.action import Action
from products.event_definitions.backend.models.event_definition import EventDefinition
from products.experiments.backend.experiment_service import ExperimentService
from products.experiments.backend.models.experiment import (
diff --git a/products/experiments/backend/test/test_metric_utils.py b/products/experiments/backend/test/test_metric_utils.py
index 10a90ae585d4..f51a5ed78ae9 100644
--- a/products/experiments/backend/test/test_metric_utils.py
+++ b/products/experiments/backend/test/test_metric_utils.py
@@ -4,8 +4,7 @@ from posthog.test.base import BaseTest
from parameterized import parameterized
-from posthog.models.action.action import Action
-
+from products.actions.backend.models.action import Action
from products.experiments.backend.metric_utils import refresh_action_names_in_metric
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index ca74db4de32b..79ef23204b53 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -12,7 +12,6 @@ from parameterized import parameterized
from rest_framework import status
from posthog.models import Organization, Team
-from posthog.models.action.action import Action
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.cohort.cohort import Cohort
from posthog.models.feature_flag import FeatureFlag, get_feature_flags_for_team_in_cache
@@ -20,6 +19,7 @@ from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.user import User
from posthog.test.test_journeys import journeys_for
+from products.actions.backend.models.action import Action
from products.event_definitions.backend.models.event_definition import EventDefinition
from products.experiments.backend.models.experiment import Experiment, ExperimentHoldout, ExperimentSavedMetric
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
diff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
index 9a8007b5be73..50b2ed26e050 100644
--- a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
@@ -18,7 +18,9 @@ from posthog.hogql.database.schema.channel_type import ChannelTypeExprs, create_
from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.property import action_to_expr, property_to_expr
-from posthog.models import Action, Team
+from posthog.models import Team
+
+from products.actions.backend.models.action import Action
from .adapters.factory import MarketingSourceFactory
from .marketing_analytics_config import MarketingAnalyticsConfig
diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.py
index 2344b502f7ab..9842af306f09 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.py
@@ -28,10 +28,10 @@ from posthog.hogql import ast
from posthog.hogql.query import execute_hogql_query
from posthog.hogql.test.utils import pretty_print_in_tests
-from posthog.models import Action
from posthog.models.event.util import bulk_create_events
from posthog.models.person.util import bulk_create_persons
+from products.actions.backend.models.action import Action
from products.marketing_analytics.backend.hogql_queries.conversion_goal_processor import (
ConversionGoalProcessor,
add_conversion_goal_property_filters,
diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py
index 3b56cc3e2f16..4e87486a4e24 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py
@@ -17,7 +17,8 @@ from posthog.hogql.query import execute_hogql_query
from posthog.hogql.test.utils import pretty_print_in_tests
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
-from posthog.models import Action
+
+from products.actions.backend.models.action import Action
from .conversion_goal_processor import ConversionGoalProcessor
from .conversion_goals_aggregator import ConversionGoalsAggregator
diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner_business.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner_business.py
index 56bee74be8f4..972496d4b2a5 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner_business.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner_business.py
@@ -20,9 +20,9 @@ from posthog.schema import (
from posthog.hogql.errors import QueryError
from posthog.hogql.test.utils import pretty_print_in_tests
-from posthog.models import Action
from posthog.models.team.team import Team
+from products.actions.backend.models.action import Action
from products.data_warehouse.backend.models import DataWarehouseTable, ExternalDataSource
from products.data_warehouse.backend.models.credential import DataWarehouseCredential
from products.data_warehouse.backend.test.utils import create_data_warehouse_table_from_csv
diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner_compare.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner_compare.py
index 781f81123bff..7a372361df88 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner_compare.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner_compare.py
@@ -20,9 +20,9 @@ from posthog.schema import (
from posthog.hogql.errors import QueryError
from posthog.hogql.test.utils import pretty_print_in_tests
-from posthog.models import Action
from posthog.models.team.team import Team
+from products.actions.backend.models.action import Action
from products.data_warehouse.backend.models import DataWarehouseTable, ExternalDataSource
from products.data_warehouse.backend.models.credential import DataWarehouseCredential
from products.data_warehouse.backend.test.utils import create_data_warehouse_table_from_csv
diff --git a/products/product_analytics/backend/hogql_queries/stickiness/stickiness_query_runner.py b/products/product_analytics/backend/hogql_queries/stickiness/stickiness_query_runner.py
index b3afbcede551..3b9867058ff4 100644
--- a/products/product_analytics/backend/hogql_queries/stickiness/stickiness_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/stickiness/stickiness_query_runner.py
@@ -33,10 +33,11 @@ from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPr
from posthog.hogql_queries.validation.rules import DisallowUnsupportedDataWarehouseSettings, RequireAtLeastOneSeries
from posthog.hogql_queries.validation.validation import QueryValidationRule
from posthog.models import Team
-from posthog.models.action.action import Action
from posthog.models.cohort.util import get_count_operator, get_count_operator_ast
from posthog.models.filters.mixins.utils import cached_property
+from products.actions.backend.models.action import Action
+
class SeriesWithExtras:
series: EventsNode | ActionsNode | DataWarehouseNode
diff --git a/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_query_runner.py b/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_query_runner.py
index ca4ec2584757..3ae5059c31b3 100644
--- a/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_query_runner.py
@@ -49,11 +49,11 @@ from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client.execute import sync_execute
from posthog.hogql_queries.query_runner import get_query_runner
-from posthog.models.action.action import Action
from posthog.models.group.util import create_group
from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.actions.backend.models.action import Action
from products.data_warehouse.backend.test.utils import create_data_warehouse_table_from_csv
from products.event_definitions.backend.models.property_definition import PropertyDefinition
from products.product_analytics.backend.hogql_queries.stickiness.stickiness_query_runner import StickinessQueryRunner
diff --git a/products/ruff.toml b/products/ruff.toml
index 161504ad46b1..9ba3119e88a3 100644
--- a/products/ruff.toml
+++ b/products/ruff.toml
@@ -18,6 +18,8 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]
# Temporarily exempted — too many violations to fix in one pass.
# Run: ruff check products/<name>/backend --select ANN --statistics
# to check remaining count before removing the exemption.
+"actions/backend/**" = ["ANN"]
+"alerts/backend/**" = ["ANN"]
"batch_exports/backend/**" = ["ANN"]
"conversations/backend/**" = ["ANN"]
"customer_analytics/backend/**" = ["ANN"]
diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.py
index 5ec70ead4300..3d2afe9b70d2 100644
--- a/products/surveys/backend/api/survey.py
+++ b/products/surveys/backend/api/survey.py
@@ -41,7 +41,6 @@ from rest_framework.response import Response
from posthog.schema import ProductKey
-from posthog.api.action import ActionSerializer, ActionStepJSONSerializer
from posthog.api.documentation import FeatureFlagFiltersSchemaSerializer
from posthog.api.feature_flag import (
BEHAVIOURAL_COHORT_FOUND_ERROR_CODE,
@@ -64,7 +63,7 @@ from posthog.helpers.trigram_search import (
MIN_NAME_TRIGRAM_SIMILARITY,
normalize_search_term,
)
-from posthog.models import Action, Insight
+from posthog.models import Insight
from posthog.models.activity_logging.activity_log import Change, Detail, changes_between, load_activity, log_activity
from posthog.models.activity_logging.activity_page import activity_page_response
from posthog.models.feature_flag import FeatureFlag
@@ -75,6 +74,8 @@ from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from posthog.rbac.user_access_control import UserAccessControlSerializerMixin
from posthog.utils_cors import cors_response
+from products.actions.backend.api.action import ActionSerializer, ActionStepJSONSerializer
+from products.actions.backend.models.action import Action
from products.surveys.backend.models import MAX_ITERATION_COUNT, Survey, SurveyResponseArchive, ensure_question_ids
from products.surveys.backend.summarization import fetch_responses, format_as_markdown, summarize_responses
from products.surveys.backend.translation import generate_survey_translation
diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.py
index 8e883d212c33..913601909944 100644
--- a/products/surveys/backend/api/test/test_survey.py
+++ b/products/surveys/backend/api/test/test_survey.py
@@ -24,10 +24,11 @@ from rest_framework import status
from posthog.api.test.test_personal_api_keys import PersonalAPIKeysBaseTest
from posthog.constants import AvailableFeature
-from posthog.models import Action, FeatureFlag, Insight, Person, Team
+from posthog.models import FeatureFlag, Insight, Person, Team
from posthog.models.cohort.cohort import Cohort
from posthog.models.organization import Organization, OrganizationMembership
+from products.actions.backend.models.action import Action
from products.product_tours.backend.models import ProductTour
from products.surveys.backend.api.survey import nh3_clean_with_allow_list
from products.surveys.backend.models import MAX_ITERATION_COUNT, Survey, SurveyResponseArchive
diff --git a/products/surveys/backend/migrations/0002_action_fk_repoint.py b/products/surveys/backend/migrations/0002_action_fk_repoint.py
new file mode 100644
index 000000000000..b3c3b89026bb
--- /dev/null
+++ b/products/surveys/backend/migrations/0002_action_fk_repoint.py
@@ -0,0 +1,23 @@
+# Generated by Django 5.2.14 on 2026-05-20 15:16
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("actions", "0001_migrate_actions_models"),
+ ("surveys", "0001_initial"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AlterField(
+ model_name="survey",
+ name="actions",
+ field=models.ManyToManyField(to="actions.action"),
+ ),
+ ],
+ database_operations=[],
+ ),
+ ]
diff --git a/products/surveys/backend/migrations/max_migration.txt b/products/surveys/backend/migrations/max_migration.txt
index cbab66dde92a..962cbf017dba 100644
--- a/products/surveys/backend/migrations/max_migration.txt
+++ b/products/surveys/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0001_initial
+0002_action_fk_repoint
diff --git a/products/surveys/backend/models.py b/products/surveys/backend/models.py
index dc3e65a807ad..e7a81d69c635 100644
--- a/products/surveys/backend/models.py
+++ b/products/surveys/backend/models.py
@@ -12,12 +12,13 @@ from django.dispatch import receiver
from dateutil.rrule import DAILY, rrule
from django_deprecate_fields import deprecate_field
-from posthog.models import Action
from posthog.models.file_system.file_system_mixin import FileSystemSyncMixin
from posthog.models.file_system.file_system_representation import FileSystemRepresentation
from posthog.models.utils import RootTeamMixin, UUIDModel, UUIDTModel
from posthog.storage.hypercache import HyperCache
+from products.actions.backend.models.action import Action
+
# we have seen users accidentally set a huge value for iteration count
# and cause performance issues, so we are extra careful with this value
# NB this is enforced in the UI too
diff --git a/products/web_analytics/backend/test/test_weekly_digest.py b/products/web_analytics/backend/test/test_weekly_digest.py
index b4fa808ce1bb..5e001a87a3a8 100644
--- a/products/web_analytics/backend/test/test_weekly_digest.py
+++ b/products/web_analytics/backend/test/test_weekly_digest.py
@@ -7,9 +7,10 @@ from django.utils import timezone
from parameterized import parameterized
-from posthog.models import Action, Team
+from posthog.models import Team
from posthog.models.utils import uuid7
+from products.actions.backend.models.action import Action
from products.web_analytics.backend.weekly_digest import (
_format_duration,
auto_select_project_for_user,
diff --git a/tach.toml b/tach.toml
index 33a3aa50a1bc..0ac1b8911bdf 100644
--- a/tach.toml
+++ b/tach.toml
@@ -35,6 +35,7 @@ utility = true
path = "ee"
depends_on = [
"posthog",
+ "products.actions",
"products.alerts",
"products.dashboards",
"products.data_warehouse",
@@ -102,6 +103,17 @@ depends_on = [
"products.warehouse_sources_queue",
"products.web_analytics",
"products.workflows",
+ "products.actions",
+ "products.alerts",
+]
+layer = "modules"
+
+[[modules]]
+path = "products.actions"
+depends_on = [
+ "ee",
+ "posthog",
+ "products.experiments",
]
layer = "modules"
@@ -159,6 +171,7 @@ path = "products.dashboards"
depends_on = [
"ee",
"posthog",
+ "products.alerts",
"products.llm_analytics",
"products.mcp_analytics",
]
@@ -241,6 +254,7 @@ path = "products.experiments"
depends_on = [
"ee",
"posthog",
+ "products.actions",
"products.event_definitions",
"products.notifications",
"products.product_tours",
@@ -304,6 +318,7 @@ layer = "modules"
path = "products.marketing_analytics"
depends_on = [
"posthog",
+ "products.actions",
"products.data_warehouse",
]
layer = "modules"
@@ -385,6 +400,7 @@ layer = "modules"
path = "products.product_analytics"
depends_on = [
"posthog",
+ "products.actions",
"products.data_warehouse",
"products.event_definitions",
]
@@ -451,6 +467,7 @@ path = "products.surveys"
depends_on = [
"ee",
"posthog",
+ "products.actions",
"products.product_tours",
]
layer = "modules"
@@ -504,6 +521,7 @@ path = "products.web_analytics"
depends_on = [
"ee",
"posthog",
+ "products.actions",
]
layer = "modules"